text
stringlengths
5
1.04M
//--------------------------------------------------------------------------- // Greenplum Database // Copyright (C) 2014 Pivotal Inc. // // @filename: // CPartInfo.cpp // // @doc: // Implementation of derived partition information at the logical level //--------------------------------------------------------------------------- #include "gpopt/base/CPartInfo.h" #include "gpos/base.h" #include "gpos/error/CAutoTrace.h" #include "gpopt/base/CUtils.h" #include "gpopt/metadata/CPartConstraint.h" using namespace gpopt; //--------------------------------------------------------------------------- // @function: // CPartInfo::CPartInfoEntry::CPartInfoEntry // // @doc: // Ctor // //--------------------------------------------------------------------------- CPartInfo::CPartInfoEntry::CPartInfoEntry(ULONG scan_id, IMDId *mdid, CPartKeysArray *pdrgppartkeys, CPartConstraint *ppartcnstrRel) : m_scan_id(scan_id), m_mdid(mdid), m_pdrgppartkeys(pdrgppartkeys), m_ppartcnstrRel(ppartcnstrRel) { GPOS_ASSERT(mdid->IsValid()); GPOS_ASSERT(pdrgppartkeys != NULL); GPOS_ASSERT(0 < pdrgppartkeys->Size()); GPOS_ASSERT(NULL != ppartcnstrRel); } //--------------------------------------------------------------------------- // @function: // CPartInfo::CPartInfoEntry::~CPartInfoEntry // // @doc: // Dtor // //--------------------------------------------------------------------------- CPartInfo::CPartInfoEntry::~CPartInfoEntry() { m_mdid->Release(); m_pdrgppartkeys->Release(); m_ppartcnstrRel->Release(); } //--------------------------------------------------------------------------- // @function: // CPartInfo::CPartInfoEntry::PpartinfoentryAddRemappedKeys // // @doc: // Create a copy of the current object, and add a set of remapped // part keys to this entry, using the existing keys and the given hashmap // //--------------------------------------------------------------------------- CPartInfo::CPartInfoEntry * CPartInfo::CPartInfoEntry::PpartinfoentryAddRemappedKeys( CMemoryPool *mp, CColRefSet *pcrs, UlongToColRefMap *colref_mapping) { GPOS_ASSERT(NULL != pcrs); GPOS_ASSERT(NULL != colref_mapping); CPartKeysArray *pdrgppartkeys = CPartKeys::PdrgppartkeysCopy(mp, m_pdrgppartkeys); const ULONG size = m_pdrgppartkeys->Size(); for (ULONG ul = 0; ul < size; ul++) { CPartKeys *ppartkeys = (*m_pdrgppartkeys)[ul]; if (ppartkeys->FOverlap(pcrs)) { pdrgppartkeys->Append( ppartkeys->PpartkeysRemap(mp, colref_mapping)); break; } } m_mdid->AddRef(); CPartConstraint *ppartcnstrRel = m_ppartcnstrRel->PpartcnstrCopyWithRemappedColumns( mp, colref_mapping, false /*must_exist*/); return GPOS_NEW(mp) CPartInfoEntry(m_scan_id, m_mdid, pdrgppartkeys, ppartcnstrRel); } //--------------------------------------------------------------------------- // @function: // CPartInfo::CPartInfoEntry::OsPrint // // @doc: // Print functions // //--------------------------------------------------------------------------- IOstream & CPartInfo::CPartInfoEntry::OsPrint(IOstream &os) const { os << m_scan_id; return os; } //--------------------------------------------------------------------------- // @function: // CPartInfo::CPartInfoEntry::PpartinfoentryCopy // // @doc: // Copy part info entry into given memory pool // //--------------------------------------------------------------------------- CPartInfo::CPartInfoEntry * CPartInfo::CPartInfoEntry::PpartinfoentryCopy(CMemoryPool *mp) { IMDId *mdid = MDId(); mdid->AddRef(); // copy part keys CPartKeysArray *pdrgppartkeysCopy = CPartKeys::PdrgppartkeysCopy(mp, Pdrgppartkeys()); // copy part constraint using empty remapping to get exact copy UlongToColRefMap *colref_mapping = GPOS_NEW(mp) UlongToColRefMap(mp); CPartConstraint *ppartcnstrRel = PpartcnstrRel()->PpartcnstrCopyWithRemappedColumns( mp, colref_mapping, false /*must_exist*/); colref_mapping->Release(); return GPOS_NEW(mp) CPartInfoEntry(ScanId(), mdid, pdrgppartkeysCopy, ppartcnstrRel); } //--------------------------------------------------------------------------- // @function: // CPartInfo::CPartInfo // // @doc: // Ctor // //--------------------------------------------------------------------------- CPartInfo::CPartInfo(CPartInfoEntryArray *pdrgppartentries) : m_pdrgppartentries(pdrgppartentries) { GPOS_ASSERT(NULL != pdrgppartentries); } //--------------------------------------------------------------------------- // @function: // CPartInfo::CPartInfo // // @doc: // Ctor // //--------------------------------------------------------------------------- CPartInfo::CPartInfo(CMemoryPool *mp) { m_pdrgppartentries = GPOS_NEW(mp) CPartInfoEntryArray(mp); } //--------------------------------------------------------------------------- // @function: // CPartInfo::~CPartInfo // // @doc: // Dtor // //--------------------------------------------------------------------------- CPartInfo::~CPartInfo() { CRefCount::SafeRelease(m_pdrgppartentries); } //--------------------------------------------------------------------------- // @function: // CPartInfo::AddPartConsumer // // @doc: // Add part table consumer // //--------------------------------------------------------------------------- void CPartInfo::AddPartConsumer(CMemoryPool *mp, ULONG scan_id, IMDId *mdid, CColRef2dArray *pdrgpdrgpcrPart, CPartConstraint *ppartcnstrRel) { CPartKeysArray *pdrgppartkeys = GPOS_NEW(mp) CPartKeysArray(mp); pdrgppartkeys->Append(GPOS_NEW(mp) CPartKeys(pdrgpdrgpcrPart)); m_pdrgppartentries->Append(GPOS_NEW(mp) CPartInfoEntry( scan_id, mdid, pdrgppartkeys, ppartcnstrRel)); } //--------------------------------------------------------------------------- // @function: // CPartInfo::FContainsScanId // // @doc: // Check if part info contains given scan id // //--------------------------------------------------------------------------- BOOL CPartInfo::FContainsScanId(ULONG scan_id) const { const ULONG size = m_pdrgppartentries->Size(); for (ULONG ul = 0; ul < size; ul++) { CPartInfoEntry *ppartinfoentry = (*m_pdrgppartentries)[ul]; if (scan_id == ppartinfoentry->ScanId()) { return true; } } return false; } //--------------------------------------------------------------------------- // @function: // CPartInfo::ScanId // // @doc: // Return scan id of the entry at the given position // //--------------------------------------------------------------------------- ULONG CPartInfo::ScanId(ULONG ulPos) const { return (*m_pdrgppartentries)[ulPos]->ScanId(); } //--------------------------------------------------------------------------- // @function: // CPartInfo::GetRelMdId // // @doc: // Return relation mdid of the entry at the given position // //--------------------------------------------------------------------------- IMDId * CPartInfo::GetRelMdId(ULONG ulPos) const { return (*m_pdrgppartentries)[ulPos]->MDId(); } //--------------------------------------------------------------------------- // @function: // CPartInfo::Pdrgppartkeys // // @doc: // Return part keys of the entry at the given position // //--------------------------------------------------------------------------- CPartKeysArray * CPartInfo::Pdrgppartkeys(ULONG ulPos) const { return (*m_pdrgppartentries)[ulPos]->Pdrgppartkeys(); } //--------------------------------------------------------------------------- // @function: // CPartInfo::Ppartcnstr // // @doc: // Return part constraint of the entry at the given position // //--------------------------------------------------------------------------- CPartConstraint * CPartInfo::Ppartcnstr(ULONG ulPos) const { return (*m_pdrgppartentries)[ulPos]->PpartcnstrRel(); } //--------------------------------------------------------------------------- // @function: // CPartInfo::PdrgppartkeysByScanId // // @doc: // Return part keys of the entry with the given scan id // //--------------------------------------------------------------------------- CPartKeysArray * CPartInfo::PdrgppartkeysByScanId(ULONG scan_id) const { const ULONG size = m_pdrgppartentries->Size(); for (ULONG ul = 0; ul < size; ul++) { CPartInfoEntry *ppartinfoentry = (*m_pdrgppartentries)[ul]; if (scan_id == ppartinfoentry->ScanId()) { return ppartinfoentry->Pdrgppartkeys(); } } return NULL; } //--------------------------------------------------------------------------- // @function: // CPartInfo::PpartinfoWithRemappedKeys // // @doc: // Return a new part info object with an additional set of remapped keys // //--------------------------------------------------------------------------- CPartInfo * CPartInfo::PpartinfoWithRemappedKeys(CMemoryPool *mp, CColRefArray *pdrgpcrSrc, CColRefArray *pdrgpcrDest) const { GPOS_ASSERT(NULL != pdrgpcrSrc); GPOS_ASSERT(NULL != pdrgpcrDest); CColRefSet *pcrs = GPOS_NEW(mp) CColRefSet(mp, pdrgpcrSrc); UlongToColRefMap *colref_mapping = CUtils::PhmulcrMapping(mp, pdrgpcrSrc, pdrgpcrDest); CPartInfoEntryArray *pdrgppartentries = GPOS_NEW(mp) CPartInfoEntryArray(mp); const ULONG size = m_pdrgppartentries->Size(); for (ULONG ul = 0; ul < size; ul++) { CPartInfoEntry *ppartinfoentry = (*m_pdrgppartentries)[ul]; // if this entry has keys that overlap with the source columns then // add another set of keys to it using the destination columns CPartInfoEntry *ppartinfoentryNew = ppartinfoentry->PpartinfoentryAddRemappedKeys(mp, pcrs, colref_mapping); pdrgppartentries->Append(ppartinfoentryNew); } pcrs->Release(); colref_mapping->Release(); return GPOS_NEW(mp) CPartInfo(pdrgppartentries); } //--------------------------------------------------------------------------- // @function: // CPartInfo::PpartinfoCombine // // @doc: // Combine two part info objects // //--------------------------------------------------------------------------- CPartInfo * CPartInfo::PpartinfoCombine(CMemoryPool *mp, CPartInfo *ppartinfoFst, CPartInfo *ppartinfoSnd) { GPOS_ASSERT(NULL != ppartinfoFst); GPOS_ASSERT(NULL != ppartinfoSnd); CPartInfoEntryArray *pdrgppartentries = GPOS_NEW(mp) CPartInfoEntryArray(mp); // copy part entries from first part info object CUtils::AddRefAppend(pdrgppartentries, ppartinfoFst->m_pdrgppartentries); // copy part entries from second part info object, except those which already exist const ULONG length = ppartinfoSnd->m_pdrgppartentries->Size(); for (ULONG ul = 0; ul < length; ul++) { CPartInfoEntry *ppartinfoentry = (*(ppartinfoSnd->m_pdrgppartentries))[ul]; CPartKeysArray *pdrgppartkeys = ppartinfoFst->PdrgppartkeysByScanId(ppartinfoentry->ScanId()); if (NULL != pdrgppartkeys) { // there is already an entry with the same scan id; need to add to it // the keys from the current entry CPartKeysArray *pdrgppartkeysCopy = CPartKeys::PdrgppartkeysCopy( mp, ppartinfoentry->Pdrgppartkeys()); CUtils::AddRefAppend(pdrgppartkeys, pdrgppartkeysCopy); pdrgppartkeysCopy->Release(); } else { CPartInfoEntry *ppartinfoentryCopy = ppartinfoentry->PpartinfoentryCopy(mp); pdrgppartentries->Append(ppartinfoentryCopy); } } return GPOS_NEW(mp) CPartInfo(pdrgppartentries); } //--------------------------------------------------------------------------- // @function: // CPartInfo::OsPrint // // @doc: // Debug print // //--------------------------------------------------------------------------- IOstream & CPartInfo::OsPrint(IOstream &os) const { const ULONG length = m_pdrgppartentries->Size(); os << "Part Consumers: "; for (ULONG ul = 0; ul < length; ul++) { CPartInfoEntry *ppartinfoentry = (*m_pdrgppartentries)[ul]; ppartinfoentry->OsPrint(os); // separator os << (ul == length - 1 ? "" : ", "); } os << ", Part Keys: "; for (ULONG ulCons = 0; ulCons < length; ulCons++) { CPartKeysArray *pdrgppartkeys = Pdrgppartkeys(ulCons); os << "("; const ULONG ulPartKeys = pdrgppartkeys->Size(); ; for (ULONG ulPartKey = 0; ulPartKey < ulPartKeys; ulPartKey++) { os << *(*pdrgppartkeys)[ulPartKey]; os << (ulPartKey == ulPartKeys - 1 ? "" : ", "); } os << ")"; os << (ulCons == length - 1 ? "" : ", "); } return os; } // EOF
// This example demonstrates how to use 'reduce' method. #include <taskflow/taskflow.hpp> #include <chrono> #include <limits.h> struct Data { int a {::rand()}; int b {::rand()}; int transform() const { return a*a + 2*a*b + b*b; } }; // Procedure: reduce // This procedure demonstrates void reduce() { std::vector<int> data; for(int i=0; i<40000000; ++i) { data.push_back(::rand()); } std::cout << "Benchmark: reduce" << std::endl; // sequential method auto sbeg = std::chrono::steady_clock::now(); auto smin = std::numeric_limits<int>::max(); for(auto& d : data) { smin = std::min(smin, d); } auto send = std::chrono::steady_clock::now(); std::cout << "[sequential] reduce: " << std::chrono::duration_cast<std::chrono::milliseconds>(send - sbeg).count() << " ms\n"; // taskflow auto tbeg = std::chrono::steady_clock::now(); tf::Taskflow tf; auto tmin = std::numeric_limits<int>::max(); tf.reduce(data.begin(), data.end(), tmin, [] (const auto& l, const auto& r) { return std::min(l, r); }); tf.wait_for_all(); auto tend = std::chrono::steady_clock::now(); std::cout << "[taskflow] reduce: " << std::chrono::duration_cast<std::chrono::milliseconds>(tend - tbeg).count() << " ms\n"; // assertion assert(tmin == smin); } // Procedure: transform_reduce void transform_reduce() { std::cout << "Benchmark: transform_reduce" << std::endl; std::vector<Data> data(40000000); // sequential method auto sbeg = std::chrono::steady_clock::now(); auto smin = std::numeric_limits<int>::max(); for(auto& d : data) { smin = std::min(smin, d.transform()); } auto send = std::chrono::steady_clock::now(); std::cout << "[sequential] transform_reduce " << std::chrono::duration_cast<std::chrono::milliseconds>(send - sbeg).count() << " ms\n"; // taskflow auto tbeg = std::chrono::steady_clock::now(); tf::Taskflow tf; auto tmin = std::numeric_limits<int>::max(); tf.transform_reduce(data.begin(), data.end(), tmin, [] (int l, int r) { return std::min(l, r); }, [] (const Data& d) { return d.transform(); } ); tf.wait_for_all(); auto tend = std::chrono::steady_clock::now(); std::cout << "[taskflow] transform_reduce " << std::chrono::duration_cast<std::chrono::milliseconds>(tend - tbeg).count() << " ms\n"; // assertion assert(tmin == smin); } // ------------------------------------------------------------------------------------------------ // Function: main int main(int argc, char* argv[]) { if(argc != 2) { std::cerr << "usage: ./reduce [reduce|transform_reduce]" << std::endl; std::exit(EXIT_FAILURE); } if(std::string_view method(argv[1]); method == "reduce") { reduce(); } else if(method == "transform_reduce") { transform_reduce(); } else { std::cerr << "invalid method " << method.data() << std::endl; std::exit(EXIT_FAILURE); } return 0; }
struct Flag { bool s1, s0, c, z, ov1, ov0; inline operator unsigned() const { return (s1 << 5) + (s0 << 4) + (c << 3) + (z << 2) + (ov1 << 1) + (ov0 << 0); } inline unsigned operator=(unsigned d) { s1 = d & 0x20; s0 = d & 0x10; c = d & 0x08; z = d & 0x04; ov1 = d & 0x02; ov0 = d & 0x01; return d; } }; struct Status { bool rqm, usf1, usf0, drs, dma, drc, soc, sic, ei, p1, p0; inline operator unsigned() const { return (rqm << 15) + (usf1 << 14) + (usf0 << 13) + (drs << 12) + (dma << 11) + (drc << 10) + (soc << 9) + (sic << 8) + (ei << 7) + (p1 << 1) + (p0 << 0); } inline unsigned operator=(unsigned d) { rqm = d & 0x8000; usf1 = d & 0x4000; usf0 = d & 0x2000; drs = d & 0x1000; dma = d & 0x0800; drc = d & 0x0400; soc = d & 0x0200; sic = d & 0x0100; ei = d & 0x0080; p1 = d & 0x0002; p0 = d & 0x0001; return d; } }; struct Regs { uint16 stack[16]; //LIFO varuint pc; //program counter varuint rp; //ROM pointer varuint dp; //data pointer uint4 sp; //stack pointer int16 k; int16 l; int16 m; int16 n; int16 a; //accumulator int16 b; //accumulator Flag flaga; Flag flagb; uint16 tr; //temporary register uint16 trb; //temporary register Status sr; //status register uint16 dr; //data register uint16 si; uint16 so; } regs;
#include "testbed.hxx" #include <arpa/inet.h> #include <errno.h> #include <netdb.h> #include <netinet/in.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/socket.h> #define TEST_BED_HOST "testbed_service_container" #define TEST_BED_PORT 9494 #define FALSE 0 #define TRUE 1 void assert_execution_on_testbed() { if (is_executing_on_testbed()) { printf("Testbed detected.\n"); } else { printf("Challenge is not executing on the testbed.\n"); printf("Exiting.\n"); exit(-1); } } void handle_container_stop_signals(int sig) { printf("Caught container stop signal %d\n Goodbye \n", sig); exit(0); } int is_executing_on_testbed() { const char *challenge = "Testbed_Challenge:1"; struct sockaddr_in server_address; struct hostent *hostinfo; int sock; if ((sock = socket(AF_INET, SOCK_STREAM, 0)) < 0) { printf("%s:%d=>%s", __FILE__, __LINE__, strerror(errno)); return FALSE; } memset(&server_address, '0', sizeof(server_address)); server_address.sin_family = AF_INET; server_address.sin_port = htons(TEST_BED_PORT); hostinfo = gethostbyname(TEST_BED_HOST); if (hostinfo == NULL) { printf("%s:%d=>%s", __FILE__, __LINE__, strerror(errno)); return FALSE; } server_address.sin_addr = *(struct in_addr *)hostinfo->h_addr_list[0]; if (connect(sock, (struct sockaddr *)&server_address, sizeof(server_address)) < 0) { printf("%s:%d=>%s", __FILE__, __LINE__, strerror(errno)); return FALSE; } int send_error = send(sock, challenge, strlen(challenge), 0) < 0; if (send_error) { printf("%s:%d=>%s", __FILE__, __LINE__, strerror(errno)); return FALSE; } char buffer[1024] = {0}; int receive_error = recv(sock, buffer, 1024, 0) < 0; if (receive_error) { printf("%s:%d=>%s", __FILE__, __LINE__, strerror(errno)); return FALSE; } char *result = strtok(buffer, "\n"); int challenge_passed = !strcmp(result, challenge); if (!challenge_passed) { printf("Testbed service failed the challenge.\n"); } return challenge_passed; }
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include <stdint.h> #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" // Completed includes // Type namespace: OVR.OpenVR namespace OVR::OpenVR { // Forward declaring type: VREvent_Notification_t struct VREvent_Notification_t; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::OVR::OpenVR::VREvent_Notification_t, "OVR.OpenVR", "VREvent_Notification_t"); // Type namespace: OVR.OpenVR namespace OVR::OpenVR { // Size: 0xC #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: OVR.OpenVR.VREvent_Notification_t // [TokenAttribute] Offset: FFFFFFFF struct VREvent_Notification_t/*, public ::System::ValueType*/ { public: public: // public System.UInt64 ulUserValue // Size: 0x8 // Offset: 0x0 uint64_t ulUserValue; // Field size check static_assert(sizeof(uint64_t) == 0x8); // public System.UInt32 notificationId // Size: 0x4 // Offset: 0x8 uint notificationId; // Field size check static_assert(sizeof(uint) == 0x4); public: // Creating value type constructor for type: VREvent_Notification_t constexpr VREvent_Notification_t(uint64_t ulUserValue_ = {}, uint notificationId_ = {}) noexcept : ulUserValue{ulUserValue_}, notificationId{notificationId_} {} // Creating interface conversion operator: operator ::System::ValueType operator ::System::ValueType() noexcept { return *reinterpret_cast<::System::ValueType*>(this); } // Get instance field reference: public System.UInt64 ulUserValue uint64_t& dyn_ulUserValue(); // Get instance field reference: public System.UInt32 notificationId uint& dyn_notificationId(); }; // OVR.OpenVR.VREvent_Notification_t #pragma pack(pop) static check_size<sizeof(VREvent_Notification_t), 8 + sizeof(uint)> __OVR_OpenVR_VREvent_Notification_tSizeCheck; static_assert(sizeof(VREvent_Notification_t) == 0xC); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "TraceCollector.h" #include <Core/Field.h> #include <Poco/Logger.h> #include <common/Pipe.h> #include <Common/StackTrace.h> #include <common/logger_useful.h> #include <IO/ReadHelpers.h> #include <IO/ReadBufferFromFileDescriptor.h> #include <IO/WriteHelpers.h> #include <IO/WriteBufferFromFileDescriptor.h> #include <Common/Exception.h> #include <Interpreters/TraceLog.h> #include <unistd.h> #include <fcntl.h> namespace DB { LazyPipe trace_pipe; namespace ErrorCodes { extern const int NULL_POINTER_DEREFERENCE; extern const int THREAD_IS_NOT_JOINABLE; extern const int CANNOT_FCNTL; } TraceCollector::TraceCollector(std::shared_ptr<TraceLog> & trace_log) : log(&Poco::Logger::get("TraceCollector")) , trace_log(trace_log) { if (trace_log == nullptr) throw Exception("Invalid trace log pointer passed", ErrorCodes::NULL_POINTER_DEREFERENCE); trace_pipe.open(); /** Turn write end of pipe to non-blocking mode to avoid deadlocks * when QueryProfiler is invoked under locks and TraceCollector cannot pull data from pipe. */ int flags = fcntl(trace_pipe.fds_rw[1], F_GETFL, 0); if (-1 == flags) throwFromErrno("Cannot get file status flags of pipe", ErrorCodes::CANNOT_FCNTL); if (-1 == fcntl(trace_pipe.fds_rw[1], F_SETFL, flags | O_NONBLOCK)) throwFromErrno("Cannot set non-blocking mode of pipe", ErrorCodes::CANNOT_FCNTL); #if !defined(__FreeBSD__) /** Increase pipe size to avoid slowdown during fine-grained trace collection. */ constexpr int max_pipe_capacity_to_set = 1048576; int pipe_size = fcntl(trace_pipe.fds_rw[1], F_GETPIPE_SZ); if (-1 == pipe_size) throwFromErrno("Cannot get pipe capacity", ErrorCodes::CANNOT_FCNTL); for (errno = 0; errno != EPERM && pipe_size < max_pipe_capacity_to_set; pipe_size *= 2) if (-1 == fcntl(trace_pipe.fds_rw[1], F_SETPIPE_SZ, pipe_size * 2) && errno != EPERM) throwFromErrno("Cannot increase pipe capacity to " + toString(pipe_size * 2), ErrorCodes::CANNOT_FCNTL); LOG_TRACE(log, "Pipe capacity is " << formatReadableSizeWithBinarySuffix(std::min(pipe_size, max_pipe_capacity_to_set))); #endif thread = ThreadFromGlobalPool(&TraceCollector::run, this); } TraceCollector::~TraceCollector() { if (!thread.joinable()) LOG_ERROR(log, "TraceCollector thread is malformed and cannot be joined"); else { TraceCollector::notifyToStop(); thread.join(); } trace_pipe.close(); } /** * Sends TraceCollector stop message * * Each sequence of data for TraceCollector thread starts with a boolean flag. * If this flag is true, TraceCollector must stop reading trace_pipe and exit. * This function sends flag with a true value to stop TraceCollector gracefully. * * NOTE: TraceCollector will NOT stop immediately as there may be some data left in the pipe * before stop message. */ void TraceCollector::notifyToStop() { WriteBufferFromFileDescriptor out(trace_pipe.fds_rw[1]); writeChar(true, out); out.next(); } void TraceCollector::run() { ReadBufferFromFileDescriptor in(trace_pipe.fds_rw[0]); while (true) { char is_last; readChar(is_last, in); if (is_last) break; std::string query_id; readStringBinary(query_id, in); UInt8 size = 0; readIntBinary(size, in); Array trace; trace.reserve(size); for (size_t i = 0; i < size; i++) { uintptr_t addr = 0; readPODBinary(addr, in); trace.emplace_back(UInt64(addr)); } TimerType timer_type; readPODBinary(timer_type, in); UInt32 thread_number; readPODBinary(thread_number, in); TraceLogElement element{std::time(nullptr), timer_type, thread_number, query_id, trace}; trace_log->add(element); } } }
/* MIT License # # Copyright (c) 2020 Ferhat Geçdoğan All Rights Reserved. # Distributed under the terms of the MIT License. # # */ #include <iostream> #include <cstring> #include <GetInfo.hpp> #include <Terminal.hpp> #include <ShellUtilities.hpp> #include <Output/Print.hpp> std::string ShellUtilities::SetTerminal(bool username, bool hostname, bool directory, std::string input_sign, std::string special_sign, std::string directory_sign) { ShellVariables var; std::string terminal; if(username == true) { terminal.append(ShellUtilities::GetUsername()); if(hostname == true) { terminal.append(special_sign + ShellUtilities::GetHostname()); if(directory == true) { terminal.append(" " + directory_sign + var.directory); } } else if(directory == true) terminal.append(" " + directory_sign + var.directory); } if(username != true) { if(hostname == true) { terminal.append(ShellUtilities::GetHostname()); if(directory == true) { terminal.append(" " + directory_sign + var.directory); } } else { if(directory == true) terminal.append(" " + directory_sign + var.directory); } } terminal.append(" " + input_sign); return terminal; } void ShellUtilities::SetUsername(bool different, std::string different_tag) { if(different == true) ShellUtilities::Print(different_tag); else ShellUtilities::Print(ShellUtilities::GetUsername()); } void ShellUtilities::SetHostname(bool different, std::string different_tag) { if(different == true) ShellUtilities::Print(different_tag); else ShellUtilities::Print(ShellUtilities::GetHostname()); } void ShellUtilities::SetDirectoryName() { ShellVariables var; ShellUtilities::Print(var.directory); } void ShellUtilities::SetInputSign(std::string input_sign) { ShellUtilities::Print(input_sign); } void ShellUtilities::SetDirectorySign(std::string dir_sign) { ShellUtilities::Print(dir_sign); } void ShellUtilities::SetSign(std::string sign) { ShellUtilities::Print(sign); }
#include <atomic> #include <thread> #include <assert.h> bool x=false; std::atomic<bool> y; std::atomic<int> z; void write_x_then_y() { x=true; std::atomic_thread_fence(std::memory_order_release); y.store(true,std::memory_order_relaxed); } void read_y_then_x() { while(!y.load(std::memory_order_relaxed)); std::atomic_thread_fence(std::memory_order_acquire); if(x) ++z; } int main() { x=false; y=false; z=0; std::thread a(write_x_then_y); std::thread b(read_y_then_x); a.join(); b.join(); assert(z.load()!=0); }
//===--- SourceMgr.cpp - SourceManager implementations --------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines types used to reason about source locations and ranges. // //===----------------------------------------------------------------------===// // This source file is part of the polarphp.org open source project // // Copyright (c) 2017 - 2019 polarphp software foundation // Copyright (c) 2017 - 2019 zzu_softboy <zzu_softboy@163.com> // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://polarphp.org/LICENSE.txt for license information // See https://polarphp.org/CONTRIBUTORS.txt for the list of polarphp project authors // // Created by polarboy on 2019/04/25. #include "polarphp/parser/SourceLoc.h" #include "polarphp/parser/SourceMgr.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/PrettyStackTrace.h" #include "llvm/Support/raw_ostream.h" #include <optional> namespace polar::parser { using llvm::PrettyStackTraceString; using llvm::SMLoc; void SourceManager::verifyAllBuffers() const { PrettyStackTraceString backtrace{ "Checking that all source buffers are still valid" }; // FIXME: This depends on the buffer IDs chosen by llvm::SourceMgr. LLVM_ATTRIBUTE_USED static char arbitraryTotal = 0; for (unsigned i = 1, e = m_sourceMgr.getNumBuffers(); i <= e; ++i) { auto *buffer = m_sourceMgr.getMemoryBuffer(i); if (buffer->getBufferSize() == 0) { continue; } arbitraryTotal += buffer->getBufferStart()[0]; arbitraryTotal += buffer->getBufferEnd()[-1]; } } SourceLoc SourceManager::getCodeCompletionLoc() const { return getLocForBufferStart(m_codeCompletionBufferId) .getAdvancedLoc(m_codeCompletionOffset); } StringRef SourceManager::getDisplayNameForLoc(SourceLoc loc) const { // Respect #line first if (auto vfile = getVirtualFile(loc)) { return vfile->name; } // Next, try the stat cache auto ident = getIdentifierForBuffer(findBufferContainingLoc(loc)); auto found = m_statusCache.find(ident); if (found != m_statusCache.end()) { return found->second.getName(); } // Populate the cache with a (virtual) stat. if (auto status = m_filesystem->status(ident)) { return (m_statusCache[ident] = status.get()).getName(); } // Finally, fall back to the buffer identifier. return ident; } unsigned SourceManager::addNewSourceBuffer(std::unique_ptr<MemoryBuffer> buffer) { assert(buffer); StringRef bufIdentifier = buffer->getBufferIdentifier(); auto id = m_sourceMgr.AddNewSourceBuffer(std::move(buffer), SMLoc()); m_bufIdentIdMap[bufIdentifier] = id; return id; } unsigned SourceManager::addMemBufferCopy(MemoryBuffer *buffer) { return addMemBufferCopy(buffer->getBuffer(), buffer->getBufferIdentifier()); } unsigned SourceManager::addMemBufferCopy(StringRef inputData, StringRef bufIdentifier) { auto buffer = std::unique_ptr<MemoryBuffer>( MemoryBuffer::getMemBufferCopy(inputData, bufIdentifier)); return addNewSourceBuffer(std::move(buffer)); } bool SourceManager::openVirtualFile(SourceLoc loc, StringRef name, int lineOffset) { CharSourceRange fullRange = getRangeForBuffer(findBufferContainingLoc(loc)); SourceLoc end; auto nextRangeIter = m_virtualFiles.upper_bound(loc.m_loc.getPointer()); if (nextRangeIter != m_virtualFiles.end() && fullRange.contains(nextRangeIter->second.range.getStart())) { const VirtualFile &existingFile = nextRangeIter->second; if (existingFile.range.getStart() == loc) { assert(existingFile.name == name); assert(existingFile.lineOffset == lineOffset); return false; } assert(!existingFile.range.contains(loc) && "must close current open file first"); end = nextRangeIter->second.range.getStart(); } else { end = fullRange.getEnd(); } CharSourceRange range = CharSourceRange(*this, loc, end); m_virtualFiles[end.m_loc.getPointer()] = { range, name, lineOffset }; m_cachedVFile = {nullptr, nullptr}; return true; } void SourceManager::closeVirtualFile(SourceLoc end) { auto *virtualFile = const_cast<VirtualFile *>(getVirtualFile(end)); if (!virtualFile) { #ifndef NDEBUG unsigned bufferID = findBufferContainingLoc(end); CharSourceRange fullRange = getRangeForBuffer(bufferID); assert((fullRange.getByteLength() == 0 || getVirtualFile(end.getAdvancedLoc(-1))) && "no open virtual file for this location"); assert(fullRange.getEnd() == end); #endif return; } m_cachedVFile = {nullptr, nullptr}; CharSourceRange oldRange = virtualFile->range; virtualFile->range = CharSourceRange(*this, virtualFile->range.getStart(), end); m_virtualFiles[end.m_loc.getPointer()] = std::move(*virtualFile); bool existed = m_virtualFiles.erase(oldRange.getEnd().m_loc.getPointer()); assert(existed); (void)existed; } const SourceManager::VirtualFile * SourceManager::getVirtualFile(SourceLoc loc) const { const char *p = loc.m_loc.getPointer(); if (m_cachedVFile.first == p) { return m_cachedVFile.second; } // Returns the first element that is >p. auto vfileIter = m_virtualFiles.upper_bound(p); if (vfileIter != m_virtualFiles.end() && vfileIter->second.range.contains(loc)) { m_cachedVFile = { p, &vfileIter->second }; return m_cachedVFile.second; } return nullptr; } std::optional<unsigned> SourceManager::getIDForBufferIdentifier( StringRef bufIdentifier) { auto iter = m_bufIdentIdMap.find(bufIdentifier); if (iter == m_bufIdentIdMap.end()) { return std::nullopt; } return iter->second; } StringRef SourceManager::getIdentifierForBuffer(unsigned bufferID) const { auto *buffer = m_sourceMgr.getMemoryBuffer(bufferID); assert(buffer && "invalid buffer id"); return buffer->getBufferIdentifier(); } CharSourceRange SourceManager::getRangeForBuffer(unsigned bufferID) const { auto *buffer = m_sourceMgr.getMemoryBuffer(bufferID); SourceLoc start{SMLoc::getFromPointer(buffer->getBufferStart())}; return CharSourceRange(start, buffer->getBufferSize()); } unsigned SourceManager::getLocOffsetInBuffer(SourceLoc loc, unsigned bufferID) const { assert(loc.isValid() && "location should be valid"); auto *buffer = m_sourceMgr.getMemoryBuffer(bufferID); assert(loc.m_loc.getPointer() >= buffer->getBuffer().begin() && loc.m_loc.getPointer() <= buffer->getBuffer().end() && "Location is not from the specified buffer"); return loc.m_loc.getPointer() - buffer->getBuffer().begin(); } unsigned SourceManager::getByteDistance(SourceLoc start, SourceLoc end) const { assert(start.isValid() && "start location should be valid"); assert(end.isValid() && "end location should be valid"); #ifndef NDEBUG unsigned bufferID = findBufferContainingLoc(start); auto *buffer = m_sourceMgr.getMemoryBuffer(bufferID); assert(end.m_loc.getPointer() >= buffer->getBuffer().begin() && end.m_loc.getPointer() <= buffer->getBuffer().end() && "end location is not from the same buffer"); #endif // When we have a rope buffer, could be implemented in terms of // getLocOffsetInBuffer(). return end.m_loc.getPointer() - start.m_loc.getPointer(); } StringRef SourceManager::getEntireTextForBuffer(unsigned bufferID) const { return m_sourceMgr.getMemoryBuffer(bufferID)->getBuffer(); } StringRef SourceManager::extractText(CharSourceRange range, std::optional<unsigned> bufferID) const { assert(range.isValid() && "range should be valid"); if (!bufferID) { bufferID = findBufferContainingLoc(range.getStart()); } StringRef buffer = m_sourceMgr.getMemoryBuffer(*bufferID)->getBuffer(); return buffer.substr(getLocOffsetInBuffer(range.getStart(), *bufferID), range.getByteLength()); } unsigned SourceManager::findBufferContainingLoc(SourceLoc loc) const { assert(loc.isValid()); // Search the buffers back-to front, so later alias buffers are // visited first. auto less_equal = std::less_equal<const char *>(); for (unsigned i = m_sourceMgr.getNumBuffers(), e = 1; i >= e; --i) { auto buffer = m_sourceMgr.getMemoryBuffer(i); if (less_equal(buffer->getBufferStart(), loc.m_loc.getPointer()) && // Use <= here so that a pointer to the null at the end of the buffer // is included as part of the buffer. less_equal(loc.m_loc.getPointer(), buffer->getBufferEnd())) return i; } llvm_unreachable("no buffer containing location found"); } std::optional<unsigned> SourceManager::resolveFromLineCol(unsigned bufferId, unsigned line, unsigned col) const { if (line == 0 || col == 0) { return std::nullopt; } auto inputBuf = getBasicSourceMgr().getMemoryBuffer(bufferId); const char *ptr = inputBuf->getBufferStart(); const char *end = inputBuf->getBufferEnd(); const char *lineStart = ptr; --line; for (; line && (ptr < end); ++ptr) { if (*ptr == '\n') { --line; lineStart = ptr+1; } } if (line != 0) { return std::nullopt; } ptr = lineStart; // The <= here is to allow for non-inclusive range end positions at EOF for (; ptr <= end; ++ptr) { --col; if (col == 0) { return ptr - inputBuf->getBufferStart(); } if (*ptr == '\n') { break; } } return std::nullopt; } } // polar::parser
// Copyright (c) 2014 BitPay Inc. // 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 <stdint.h> #include <vector> #include <string> #include <map> #include <univalue.h> #include "test/test_gram.h" #include <boost/test/unit_test.hpp> BOOST_FIXTURE_TEST_SUITE(univalue_tests, BasicTestingSetup) BOOST_AUTO_TEST_CASE(univalue_constructor) { UniValue v1; BOOST_CHECK(v1.isNull()); UniValue v2(UniValue::VSTR); BOOST_CHECK(v2.isStr()); UniValue v3(UniValue::VSTR, "foo"); BOOST_CHECK(v3.isStr()); BOOST_CHECK_EQUAL(v3.getValStr(), "foo"); UniValue numTest; BOOST_CHECK(numTest.setNumStr("82")); BOOST_CHECK(numTest.isNum()); BOOST_CHECK_EQUAL(numTest.getValStr(), "82"); uint64_t vu64 = 82; UniValue v4(vu64); BOOST_CHECK(v4.isNum()); BOOST_CHECK_EQUAL(v4.getValStr(), "82"); int64_t vi64 = -82; UniValue v5(vi64); BOOST_CHECK(v5.isNum()); BOOST_CHECK_EQUAL(v5.getValStr(), "-82"); int vi = -688; UniValue v6(vi); BOOST_CHECK(v6.isNum()); BOOST_CHECK_EQUAL(v6.getValStr(), "-688"); double vd = -7.21; UniValue v7(vd); BOOST_CHECK(v7.isNum()); BOOST_CHECK_EQUAL(v7.getValStr(), "-7.21"); std::string vs("yawn"); UniValue v8(vs); BOOST_CHECK(v8.isStr()); BOOST_CHECK_EQUAL(v8.getValStr(), "yawn"); const char *vcs = "zappa"; UniValue v9(vcs); BOOST_CHECK(v9.isStr()); BOOST_CHECK_EQUAL(v9.getValStr(), "zappa"); } BOOST_AUTO_TEST_CASE(univalue_typecheck) { UniValue v1; BOOST_CHECK(v1.setNumStr("1")); BOOST_CHECK(v1.isNum()); BOOST_CHECK_THROW(v1.get_bool(), std::runtime_error); UniValue v2; BOOST_CHECK(v2.setBool(true)); BOOST_CHECK_EQUAL(v2.get_bool(), true); BOOST_CHECK_THROW(v2.get_int(), std::runtime_error); UniValue v3; BOOST_CHECK(v3.setNumStr("32482348723847471234")); BOOST_CHECK_THROW(v3.get_int64(), std::runtime_error); BOOST_CHECK(v3.setNumStr("1000")); BOOST_CHECK_EQUAL(v3.get_int64(), 1000); UniValue v4; BOOST_CHECK(v4.setNumStr("2147483648")); BOOST_CHECK_EQUAL(v4.get_int64(), 2147483648); BOOST_CHECK_THROW(v4.get_int(), std::runtime_error); BOOST_CHECK(v4.setNumStr("1000")); BOOST_CHECK_EQUAL(v4.get_int(), 1000); BOOST_CHECK_THROW(v4.get_str(), std::runtime_error); BOOST_CHECK_EQUAL(v4.get_real(), 1000); BOOST_CHECK_THROW(v4.get_array(), std::runtime_error); BOOST_CHECK_THROW(v4.getKeys(), std::runtime_error); BOOST_CHECK_THROW(v4.getValues(), std::runtime_error); BOOST_CHECK_THROW(v4.get_obj(), std::runtime_error); UniValue v5; BOOST_CHECK(v5.read("[true, 10]")); BOOST_CHECK_NO_THROW(v5.get_array()); std::vector<UniValue> vals = v5.getValues(); BOOST_CHECK_THROW(vals[0].get_int(), std::runtime_error); BOOST_CHECK_EQUAL(vals[0].get_bool(), true); BOOST_CHECK_EQUAL(vals[1].get_int(), 10); BOOST_CHECK_THROW(vals[1].get_bool(), std::runtime_error); } BOOST_AUTO_TEST_CASE(univalue_set) { UniValue v(UniValue::VSTR, "foo"); v.clear(); BOOST_CHECK(v.isNull()); BOOST_CHECK_EQUAL(v.getValStr(), ""); BOOST_CHECK(v.setObject()); BOOST_CHECK(v.isObject()); BOOST_CHECK_EQUAL(v.size(), 0); BOOST_CHECK_EQUAL(v.getType(), UniValue::VOBJ); BOOST_CHECK(v.empty()); BOOST_CHECK(v.setArray()); BOOST_CHECK(v.isArray()); BOOST_CHECK_EQUAL(v.size(), 0); BOOST_CHECK(v.setStr("zum")); BOOST_CHECK(v.isStr()); BOOST_CHECK_EQUAL(v.getValStr(), "zum"); BOOST_CHECK(v.setFloat(-1.01)); BOOST_CHECK(v.isNum()); BOOST_CHECK_EQUAL(v.getValStr(), "-1.01"); BOOST_CHECK(v.setInt((int)1023)); BOOST_CHECK(v.isNum()); BOOST_CHECK_EQUAL(v.getValStr(), "1023"); BOOST_CHECK(v.setInt((int64_t)-1023LL)); BOOST_CHECK(v.isNum()); BOOST_CHECK_EQUAL(v.getValStr(), "-1023"); BOOST_CHECK(v.setInt((uint64_t)1023ULL)); BOOST_CHECK(v.isNum()); BOOST_CHECK_EQUAL(v.getValStr(), "1023"); BOOST_CHECK(v.setNumStr("-688")); BOOST_CHECK(v.isNum()); BOOST_CHECK_EQUAL(v.getValStr(), "-688"); BOOST_CHECK(v.setBool(false)); BOOST_CHECK_EQUAL(v.isBool(), true); BOOST_CHECK_EQUAL(v.isTrue(), false); BOOST_CHECK_EQUAL(v.isFalse(), true); BOOST_CHECK_EQUAL(v.getBool(), false); BOOST_CHECK(v.setBool(true)); BOOST_CHECK_EQUAL(v.isBool(), true); BOOST_CHECK_EQUAL(v.isTrue(), true); BOOST_CHECK_EQUAL(v.isFalse(), false); BOOST_CHECK_EQUAL(v.getBool(), true); BOOST_CHECK(!v.setNumStr("zombocom")); BOOST_CHECK(v.setNull()); BOOST_CHECK(v.isNull()); } BOOST_AUTO_TEST_CASE(univalue_array) { UniValue arr(UniValue::VARR); UniValue v((int64_t)1023LL); BOOST_CHECK(arr.push_back(v)); std::string vStr("zippy"); BOOST_CHECK(arr.push_back(vStr)); const char *s = "pippy"; BOOST_CHECK(arr.push_back(s)); std::vector<UniValue> vec; v.setStr("boing"); vec.push_back(v); v.setStr("going"); vec.push_back(v); BOOST_CHECK(arr.push_backV(vec)); BOOST_CHECK_EQUAL(arr.empty(), false); BOOST_CHECK_EQUAL(arr.size(), 5); BOOST_CHECK_EQUAL(arr[0].getValStr(), "1023"); BOOST_CHECK_EQUAL(arr[1].getValStr(), "zippy"); BOOST_CHECK_EQUAL(arr[2].getValStr(), "pippy"); BOOST_CHECK_EQUAL(arr[3].getValStr(), "boing"); BOOST_CHECK_EQUAL(arr[4].getValStr(), "going"); BOOST_CHECK_EQUAL(arr[999].getValStr(), ""); arr.clear(); BOOST_CHECK(arr.empty()); BOOST_CHECK_EQUAL(arr.size(), 0); } BOOST_AUTO_TEST_CASE(univalue_object) { UniValue obj(UniValue::VOBJ); std::string strKey, strVal; UniValue v; strKey = "age"; v.setInt(100); BOOST_CHECK(obj.pushKV(strKey, v)); strKey = "first"; strVal = "John"; BOOST_CHECK(obj.pushKV(strKey, strVal)); strKey = "last"; const char *cVal = "Smith"; BOOST_CHECK(obj.pushKV(strKey, cVal)); strKey = "distance"; BOOST_CHECK(obj.pushKV(strKey, (int64_t) 25)); strKey = "time"; BOOST_CHECK(obj.pushKV(strKey, (uint64_t) 3600)); strKey = "calories"; BOOST_CHECK(obj.pushKV(strKey, (int) 12)); strKey = "temperature"; BOOST_CHECK(obj.pushKV(strKey, (double) 90.012)); UniValue obj2(UniValue::VOBJ); BOOST_CHECK(obj2.pushKV("cat1", 9000)); BOOST_CHECK(obj2.pushKV("cat2", 12345)); BOOST_CHECK(obj.pushKVs(obj2)); BOOST_CHECK_EQUAL(obj.empty(), false); BOOST_CHECK_EQUAL(obj.size(), 9); BOOST_CHECK_EQUAL(obj["age"].getValStr(), "100"); BOOST_CHECK_EQUAL(obj["first"].getValStr(), "John"); BOOST_CHECK_EQUAL(obj["last"].getValStr(), "Smith"); BOOST_CHECK_EQUAL(obj["distance"].getValStr(), "25"); BOOST_CHECK_EQUAL(obj["time"].getValStr(), "3600"); BOOST_CHECK_EQUAL(obj["calories"].getValStr(), "12"); BOOST_CHECK_EQUAL(obj["temperature"].getValStr(), "90.012"); BOOST_CHECK_EQUAL(obj["cat1"].getValStr(), "9000"); BOOST_CHECK_EQUAL(obj["cat2"].getValStr(), "12345"); BOOST_CHECK_EQUAL(obj["nyuknyuknyuk"].getValStr(), ""); BOOST_CHECK(obj.exists("age")); BOOST_CHECK(obj.exists("first")); BOOST_CHECK(obj.exists("last")); BOOST_CHECK(obj.exists("distance")); BOOST_CHECK(obj.exists("time")); BOOST_CHECK(obj.exists("calories")); BOOST_CHECK(obj.exists("temperature")); BOOST_CHECK(obj.exists("cat1")); BOOST_CHECK(obj.exists("cat2")); BOOST_CHECK(!obj.exists("nyuknyuknyuk")); std::map<std::string, UniValue::VType> objTypes; objTypes["age"] = UniValue::VNUM; objTypes["first"] = UniValue::VSTR; objTypes["last"] = UniValue::VSTR; objTypes["distance"] = UniValue::VNUM; objTypes["time"] = UniValue::VNUM; objTypes["calories"] = UniValue::VNUM; objTypes["temperature"] = UniValue::VNUM; objTypes["cat1"] = UniValue::VNUM; objTypes["cat2"] = UniValue::VNUM; BOOST_CHECK(obj.checkObject(objTypes)); objTypes["cat2"] = UniValue::VSTR; BOOST_CHECK(!obj.checkObject(objTypes)); obj.clear(); BOOST_CHECK(obj.empty()); BOOST_CHECK_EQUAL(obj.size(), 0); } static const char *json1 = "[1.10000000,{\"key1\":\"str\\u0000\",\"key2\":800,\"key3\":{\"name\":\"martian http://test.com\"}}]"; BOOST_AUTO_TEST_CASE(univalue_readwrite) { UniValue v; BOOST_CHECK(v.read(json1)); std::string strJson1(json1); BOOST_CHECK(v.read(strJson1)); BOOST_CHECK(v.isArray()); BOOST_CHECK_EQUAL(v.size(), 2); BOOST_CHECK_EQUAL(v[0].getValStr(), "1.10000000"); UniValue obj = v[1]; BOOST_CHECK(obj.isObject()); BOOST_CHECK_EQUAL(obj.size(), 3); BOOST_CHECK(obj["key1"].isStr()); std::string correctValue("str"); correctValue.push_back('\0'); BOOST_CHECK_EQUAL(obj["key1"].getValStr(), correctValue); BOOST_CHECK(obj["key2"].isNum()); BOOST_CHECK_EQUAL(obj["key2"].getValStr(), "800"); BOOST_CHECK(obj["key3"].isObject()); BOOST_CHECK_EQUAL(strJson1, v.write()); /* Check for (correctly reporting) a parsing error if the initial JSON construct is followed by more stuff. Note that whitespace is, of course, exempt. */ BOOST_CHECK(v.read(" {}\n ")); BOOST_CHECK(v.isObject()); BOOST_CHECK(v.read(" []\n ")); BOOST_CHECK(v.isArray()); BOOST_CHECK(!v.read("@{}")); BOOST_CHECK(!v.read("{} garbage")); BOOST_CHECK(!v.read("[]{}")); BOOST_CHECK(!v.read("{}[]")); BOOST_CHECK(!v.read("{} 42")); } BOOST_AUTO_TEST_SUITE_END()
/* * Copyright 2015 Google Inc. * * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ #include "src/gpu/GrDrawingManager.h" #include "include/core/SkDeferredDisplayList.h" #include "include/gpu/GrBackendSemaphore.h" #include "include/private/GrRecordingContext.h" #include "src/core/SkTTopoSort.h" #include "src/gpu/GrAuditTrail.h" #include "src/gpu/GrClientMappedBufferManager.h" #include "src/gpu/GrContextPriv.h" #include "src/gpu/GrCopyRenderTask.h" #include "src/gpu/GrGpu.h" #include "src/gpu/GrMemoryPool.h" #include "src/gpu/GrOnFlushResourceProvider.h" #include "src/gpu/GrRecordingContextPriv.h" #include "src/gpu/GrRenderTargetContext.h" #include "src/gpu/GrRenderTargetProxy.h" #include "src/gpu/GrRenderTask.h" #include "src/gpu/GrResourceAllocator.h" #include "src/gpu/GrResourceProvider.h" #include "src/gpu/GrSoftwarePathRenderer.h" #include "src/gpu/GrSurfaceContext.h" #include "src/gpu/GrSurfaceProxyPriv.h" #include "src/gpu/GrTexture.h" #include "src/gpu/GrTexturePriv.h" #include "src/gpu/GrTextureProxy.h" #include "src/gpu/GrTextureProxyPriv.h" #include "src/gpu/GrTextureResolveRenderTask.h" #include "src/gpu/GrTracing.h" #include "src/gpu/GrTransferFromRenderTask.h" #include "src/gpu/GrWaitRenderTask.h" #include "src/gpu/ccpr/GrCoverageCountingPathRenderer.h" #include "src/gpu/text/GrTextContext.h" #include "src/image/SkSurface_Gpu.h" GrDrawingManager::RenderTaskDAG::RenderTaskDAG(bool sortRenderTasks) : fSortRenderTasks(sortRenderTasks) {} GrDrawingManager::RenderTaskDAG::~RenderTaskDAG() {} void GrDrawingManager::RenderTaskDAG::gatherIDs(SkSTArray<8, uint32_t, true>* idArray) const { idArray->reset(fRenderTasks.count()); for (int i = 0; i < fRenderTasks.count(); ++i) { if (fRenderTasks[i]) { (*idArray)[i] = fRenderTasks[i]->uniqueID(); } } } void GrDrawingManager::RenderTaskDAG::reset() { fRenderTasks.reset(); } void GrDrawingManager::RenderTaskDAG::removeRenderTask(int index) { if (!fRenderTasks[index]->unique()) { // TODO: Eventually this should be guaranteed unique: http://skbug.com/7111 fRenderTasks[index]->endFlush(); } fRenderTasks[index] = nullptr; } void GrDrawingManager::RenderTaskDAG::removeRenderTasks(int startIndex, int stopIndex) { for (int i = startIndex; i < stopIndex; ++i) { if (!fRenderTasks[i]) { continue; } this->removeRenderTask(i); } } bool GrDrawingManager::RenderTaskDAG::isUsed(GrSurfaceProxy* proxy) const { for (int i = 0; i < fRenderTasks.count(); ++i) { if (fRenderTasks[i] && fRenderTasks[i]->isUsed(proxy)) { return true; } } return false; } GrRenderTask* GrDrawingManager::RenderTaskDAG::add(sk_sp<GrRenderTask> renderTask) { if (renderTask) { return fRenderTasks.emplace_back(std::move(renderTask)).get(); } return nullptr; } GrRenderTask* GrDrawingManager::RenderTaskDAG::addBeforeLast(sk_sp<GrRenderTask> renderTask) { SkASSERT(!fRenderTasks.empty()); if (renderTask) { // Release 'fRenderTasks.back()' and grab the raw pointer, in case the SkTArray grows // and reallocates during emplace_back. fRenderTasks.emplace_back(fRenderTasks.back().release()); return (fRenderTasks[fRenderTasks.count() - 2] = std::move(renderTask)).get(); } return nullptr; } void GrDrawingManager::RenderTaskDAG::add(const SkTArray<sk_sp<GrRenderTask>>& renderTasks) { #ifdef SK_DEBUG for (auto& renderTask : renderTasks) { SkASSERT(renderTask->unique()); } #endif fRenderTasks.push_back_n(renderTasks.count(), renderTasks.begin()); } void GrDrawingManager::RenderTaskDAG::swap(SkTArray<sk_sp<GrRenderTask>>* renderTasks) { SkASSERT(renderTasks->empty()); renderTasks->swap(fRenderTasks); } void GrDrawingManager::RenderTaskDAG::prepForFlush() { if (fSortRenderTasks) { SkDEBUGCODE(bool result =) SkTTopoSort<GrRenderTask, GrRenderTask::TopoSortTraits>( &fRenderTasks); SkASSERT(result); } #ifdef SK_DEBUG // This block checks for any unnecessary splits in the opsTasks. If two sequential opsTasks // share the same backing GrSurfaceProxy it means the opsTask was artificially split. if (fRenderTasks.count()) { GrOpsTask* prevOpsTask = fRenderTasks[0]->asOpsTask(); for (int i = 1; i < fRenderTasks.count(); ++i) { GrOpsTask* curOpsTask = fRenderTasks[i]->asOpsTask(); if (prevOpsTask && curOpsTask) { SkASSERT(prevOpsTask->fTargetView != curOpsTask->fTargetView); } prevOpsTask = curOpsTask; } } #endif } void GrDrawingManager::RenderTaskDAG::closeAll(const GrCaps* caps) { for (int i = 0; i < fRenderTasks.count(); ++i) { if (fRenderTasks[i]) { fRenderTasks[i]->makeClosed(*caps); } } } void GrDrawingManager::RenderTaskDAG::cleanup(const GrCaps* caps) { for (int i = 0; i < fRenderTasks.count(); ++i) { if (!fRenderTasks[i]) { continue; } // no renderTask should receive a dependency fRenderTasks[i]->makeClosed(*caps); // We shouldn't need to do this, but it turns out some clients still hold onto opsTasks // after a cleanup. // MDB TODO: is this still true? if (!fRenderTasks[i]->unique()) { // TODO: Eventually this should be guaranteed unique. // https://bugs.chromium.org/p/skia/issues/detail?id=7111 fRenderTasks[i]->endFlush(); } } fRenderTasks.reset(); } /////////////////////////////////////////////////////////////////////////////////////////////////// GrDrawingManager::GrDrawingManager(GrRecordingContext* context, const GrPathRendererChain::Options& optionsForPathRendererChain, const GrTextContext::Options& optionsForTextContext, bool sortRenderTasks, bool reduceOpsTaskSplitting) : fContext(context) , fOptionsForPathRendererChain(optionsForPathRendererChain) , fOptionsForTextContext(optionsForTextContext) , fDAG(sortRenderTasks) , fTextContext(nullptr) , fPathRendererChain(nullptr) , fSoftwarePathRenderer(nullptr) , fFlushing(false) , fReduceOpsTaskSplitting(reduceOpsTaskSplitting) { } void GrDrawingManager::cleanup() { fDAG.cleanup(fContext->priv().caps()); fPathRendererChain = nullptr; fSoftwarePathRenderer = nullptr; fOnFlushCBObjects.reset(); } GrDrawingManager::~GrDrawingManager() { this->cleanup(); } bool GrDrawingManager::wasAbandoned() const { return fContext->priv().abandoned(); } void GrDrawingManager::freeGpuResources() { for (int i = fOnFlushCBObjects.count() - 1; i >= 0; --i) { if (!fOnFlushCBObjects[i]->retainOnFreeGpuResources()) { // it's safe to just do this because we're iterating in reverse fOnFlushCBObjects.removeShuffle(i); } } // a path renderer may be holding onto resources fPathRendererChain = nullptr; fSoftwarePathRenderer = nullptr; } // MDB TODO: make use of the 'proxy' parameter. GrSemaphoresSubmitted GrDrawingManager::flush(GrSurfaceProxy* proxies[], int numProxies, SkSurface::BackendSurfaceAccess access, const GrFlushInfo& info, const GrPrepareForExternalIORequests& externalRequests) { SkASSERT(numProxies >= 0); SkASSERT(!numProxies || proxies); GR_CREATE_TRACE_MARKER_CONTEXT("GrDrawingManager", "flush", fContext); if (fFlushing || this->wasAbandoned()) { if (info.fFinishedProc) { info.fFinishedProc(info.fFinishedContext); } return GrSemaphoresSubmitted::kNo; } SkDEBUGCODE(this->validate()); if (kNone_GrFlushFlags == info.fFlags && !info.fNumSemaphores && !info.fFinishedProc && !externalRequests.hasRequests()) { bool canSkip = numProxies > 0; for (int i = 0; i < numProxies && canSkip; ++i) { canSkip = !fDAG.isUsed(proxies[i]) && !this->isDDLTarget(proxies[i]); } if (canSkip) { return GrSemaphoresSubmitted::kNo; } } auto direct = fContext->priv().asDirectContext(); if (!direct) { if (info.fFinishedProc) { info.fFinishedProc(info.fFinishedContext); } return GrSemaphoresSubmitted::kNo; // Can't flush while DDL recording } direct->priv().clientMappedBufferManager()->process(); GrGpu* gpu = direct->priv().getGpu(); if (!gpu) { if (info.fFinishedProc) { info.fFinishedProc(info.fFinishedContext); } return GrSemaphoresSubmitted::kNo; // Can't flush while DDL recording } fFlushing = true; auto resourceProvider = direct->priv().resourceProvider(); auto resourceCache = direct->priv().getResourceCache(); // Semi-usually the GrRenderTasks are already closed at this point, but sometimes Ganesh needs // to flush mid-draw. In that case, the SkGpuDevice's opsTasks won't be closed but need to be // flushed anyway. Closing such opsTasks here will mean new ones will be created to replace them // if the SkGpuDevice(s) write to them again. fDAG.closeAll(fContext->priv().caps()); fActiveOpsTask = nullptr; fDAG.prepForFlush(); if (!fCpuBufferCache) { // We cache more buffers when the backend is using client side arrays. Otherwise, we // expect each pool will use a CPU buffer as a staging buffer before uploading to a GPU // buffer object. Each pool only requires one staging buffer at a time. int maxCachedBuffers = fContext->priv().caps()->preferClientSideDynamicBuffers() ? 2 : 6; fCpuBufferCache = GrBufferAllocPool::CpuBufferCache::Make(maxCachedBuffers); } GrOpFlushState flushState(gpu, resourceProvider, &fTokenTracker, fCpuBufferCache); GrOnFlushResourceProvider onFlushProvider(this); // TODO: AFAICT the only reason fFlushState is on GrDrawingManager rather than on the // stack here is to preserve the flush tokens. // Prepare any onFlush op lists (e.g. atlases). if (!fOnFlushCBObjects.empty()) { fDAG.gatherIDs(&fFlushingRenderTaskIDs); for (GrOnFlushCallbackObject* onFlushCBObject : fOnFlushCBObjects) { onFlushCBObject->preFlush(&onFlushProvider, fFlushingRenderTaskIDs.begin(), fFlushingRenderTaskIDs.count()); } for (const auto& onFlushRenderTask : fOnFlushRenderTasks) { onFlushRenderTask->makeClosed(*fContext->priv().caps()); #ifdef SK_DEBUG // OnFlush callbacks are invoked during flush, and are therefore expected to handle // resource allocation & usage on their own. (No deferred or lazy proxies!) onFlushRenderTask->visitTargetAndSrcProxies_debugOnly( [](GrSurfaceProxy* p, GrMipMapped mipMapped) { SkASSERT(!p->asTextureProxy() || !p->asTextureProxy()->texPriv().isDeferred()); SkASSERT(!p->isLazy()); if (p->requiresManualMSAAResolve()) { // The onFlush callback is responsible for ensuring MSAA gets resolved. SkASSERT(p->asRenderTargetProxy() && !p->asRenderTargetProxy()->isMSAADirty()); } if (GrMipMapped::kYes == mipMapped) { // The onFlush callback is responsible for regenerating mips if needed. SkASSERT(p->asTextureProxy() && !p->asTextureProxy()->mipMapsAreDirty()); } }); #endif onFlushRenderTask->prepare(&flushState); } } #if 0 // Enable this to print out verbose GrOp information SkDEBUGCODE(SkDebugf("onFlush renderTasks:")); for (const auto& onFlushRenderTask : fOnFlushRenderTasks) { SkDEBUGCODE(onFlushRenderTask->dump();) } SkDEBUGCODE(SkDebugf("Normal renderTasks:")); for (int i = 0; i < fRenderTasks.count(); ++i) { SkDEBUGCODE(fRenderTasks[i]->dump();) } #endif int startIndex, stopIndex; bool flushed = false; { GrResourceAllocator alloc(resourceProvider SkDEBUGCODE(, fDAG.numRenderTasks())); for (int i = 0; i < fDAG.numRenderTasks(); ++i) { if (fDAG.renderTask(i)) { fDAG.renderTask(i)->gatherProxyIntervals(&alloc); } alloc.markEndOfOpsTask(i); } alloc.determineRecyclability(); GrResourceAllocator::AssignError error = GrResourceAllocator::AssignError::kNoError; int numRenderTasksExecuted = 0; while (alloc.assign(&startIndex, &stopIndex, &error)) { if (GrResourceAllocator::AssignError::kFailedProxyInstantiation == error) { for (int i = startIndex; i < stopIndex; ++i) { GrRenderTask* renderTask = fDAG.renderTask(i); if (!renderTask) { continue; } if (!renderTask->isInstantiated()) { // No need to call the renderTask's handleInternalAllocationFailure // since we will already skip executing the renderTask since it is not // instantiated. continue; } renderTask->handleInternalAllocationFailure(); } } if (this->executeRenderTasks( startIndex, stopIndex, &flushState, &numRenderTasksExecuted)) { flushed = true; } } } #ifdef SK_DEBUG for (int i = 0; i < fDAG.numRenderTasks(); ++i) { // If there are any remaining opsTaskss at this point, make sure they will not survive the // flush. Otherwise we need to call endFlush() on them. // http://skbug.com/7111 SkASSERT(!fDAG.renderTask(i) || fDAG.renderTask(i)->unique()); } #endif fDAG.reset(); this->clearDDLTargets(); #ifdef SK_DEBUG // In non-DDL mode this checks that all the flushed ops have been freed from the memory pool. // When we move to partial flushes this assert will no longer be valid. // In DDL mode this check is somewhat superfluous since the memory for most of the ops/opsTasks // will be stored in the DDL's GrOpMemoryPools. GrOpMemoryPool* opMemoryPool = fContext->priv().opMemoryPool(); opMemoryPool->isEmpty(); #endif GrSemaphoresSubmitted result = gpu->finishFlush(proxies, numProxies, access, info, externalRequests); // Give the cache a chance to purge resources that become purgeable due to flushing. if (flushed) { resourceCache->purgeAsNeeded(); flushed = false; } for (GrOnFlushCallbackObject* onFlushCBObject : fOnFlushCBObjects) { onFlushCBObject->postFlush(fTokenTracker.nextTokenToFlush(), fFlushingRenderTaskIDs.begin(), fFlushingRenderTaskIDs.count()); flushed = true; } if (flushed) { resourceCache->purgeAsNeeded(); } fFlushingRenderTaskIDs.reset(); fFlushing = false; return result; } bool GrDrawingManager::executeRenderTasks(int startIndex, int stopIndex, GrOpFlushState* flushState, int* numRenderTasksExecuted) { SkASSERT(startIndex <= stopIndex && stopIndex <= fDAG.numRenderTasks()); #if GR_FLUSH_TIME_OP_SPEW SkDebugf("Flushing opsTask: %d to %d out of [%d, %d]\n", startIndex, stopIndex, 0, fDAG.numRenderTasks()); for (int i = startIndex; i < stopIndex; ++i) { if (fDAG.renderTask(i)) { fDAG.renderTask(i)->dump(true); } } #endif bool anyRenderTasksExecuted = false; for (int i = startIndex; i < stopIndex; ++i) { GrRenderTask* renderTask = fDAG.renderTask(i); if (!renderTask || !renderTask->isInstantiated()) { continue; } SkASSERT(renderTask->deferredProxiesAreInstantiated()); renderTask->prepare(flushState); } // Upload all data to the GPU flushState->preExecuteDraws(); // For Vulkan, if we have too many oplists to be flushed we end up allocating a lot of resources // for each command buffer associated with the oplists. If this gets too large we can cause the // devices to go OOM. In practice we usually only hit this case in our tests, but to be safe we // put a cap on the number of oplists we will execute before flushing to the GPU to relieve some // memory pressure. static constexpr int kMaxRenderTasksBeforeFlush = 100; // Execute the onFlush renderTasks first, if any. for (sk_sp<GrRenderTask>& onFlushRenderTask : fOnFlushRenderTasks) { if (!onFlushRenderTask->execute(flushState)) { SkDebugf("WARNING: onFlushRenderTask failed to execute.\n"); } SkASSERT(onFlushRenderTask->unique()); onFlushRenderTask = nullptr; (*numRenderTasksExecuted)++; if (*numRenderTasksExecuted >= kMaxRenderTasksBeforeFlush) { flushState->gpu()->finishFlush(nullptr, 0, SkSurface::BackendSurfaceAccess::kNoAccess, GrFlushInfo(), GrPrepareForExternalIORequests()); *numRenderTasksExecuted = 0; } } fOnFlushRenderTasks.reset(); // Execute the normal op lists. for (int i = startIndex; i < stopIndex; ++i) { GrRenderTask* renderTask = fDAG.renderTask(i); if (!renderTask || !renderTask->isInstantiated()) { continue; } if (renderTask->execute(flushState)) { anyRenderTasksExecuted = true; } (*numRenderTasksExecuted)++; if (*numRenderTasksExecuted >= kMaxRenderTasksBeforeFlush) { flushState->gpu()->finishFlush(nullptr, 0, SkSurface::BackendSurfaceAccess::kNoAccess, GrFlushInfo(), GrPrepareForExternalIORequests()); *numRenderTasksExecuted = 0; } } SkASSERT(!flushState->opsRenderPass()); SkASSERT(fTokenTracker.nextDrawToken() == fTokenTracker.nextTokenToFlush()); // We reset the flush state before the RenderTasks so that the last resources to be freed are // those that are written to in the RenderTasks. This helps to make sure the most recently used // resources are the last to be purged by the resource cache. flushState->reset(); fDAG.removeRenderTasks(startIndex, stopIndex); return anyRenderTasksExecuted; } GrSemaphoresSubmitted GrDrawingManager::flushSurfaces(GrSurfaceProxy* proxies[], int numProxies, SkSurface::BackendSurfaceAccess access, const GrFlushInfo& info) { if (this->wasAbandoned()) { return GrSemaphoresSubmitted::kNo; } SkDEBUGCODE(this->validate()); SkASSERT(numProxies >= 0); SkASSERT(!numProxies || proxies); auto direct = fContext->priv().asDirectContext(); if (!direct) { return GrSemaphoresSubmitted::kNo; // Can't flush while DDL recording } GrGpu* gpu = direct->priv().getGpu(); if (!gpu) { return GrSemaphoresSubmitted::kNo; // Can't flush while DDL recording } // TODO: It is important to upgrade the drawingmanager to just flushing the // portion of the DAG required by 'proxies' in order to restore some of the // semantics of this method. GrSemaphoresSubmitted result = this->flush(proxies, numProxies, access, info, GrPrepareForExternalIORequests()); for (int i = 0; i < numProxies; ++i) { GrSurfaceProxy* proxy = proxies[i]; if (!proxy->isInstantiated()) { return result; } // In the flushSurfaces case, we need to resolve MSAA immediately after flush. This is // because the client will call through to this method when drawing into a target created by // wrapBackendTextureAsRenderTarget, and will expect the original texture to be fully // resolved upon return. if (proxy->requiresManualMSAAResolve()) { auto* rtProxy = proxy->asRenderTargetProxy(); SkASSERT(rtProxy); if (rtProxy->isMSAADirty()) { SkASSERT(rtProxy->peekRenderTarget()); gpu->resolveRenderTarget(rtProxy->peekRenderTarget(), rtProxy->msaaDirtyRect(), GrGpu::ForExternalIO::kYes); rtProxy->markMSAAResolved(); } } // If, after a flush, any of the proxies of interest have dirty mipmaps, regenerate them in // case their backend textures are being stolen. // (This special case is exercised by the ReimportImageTextureWithMipLevels test.) // FIXME: It may be more ideal to plumb down a "we're going to steal the backends" flag. if (auto* textureProxy = proxy->asTextureProxy()) { if (textureProxy->mipMapsAreDirty()) { SkASSERT(textureProxy->peekTexture()); gpu->regenerateMipMapLevels(textureProxy->peekTexture()); textureProxy->markMipMapsClean(); } } } SkDEBUGCODE(this->validate()); return result; } void GrDrawingManager::addOnFlushCallbackObject(GrOnFlushCallbackObject* onFlushCBObject) { fOnFlushCBObjects.push_back(onFlushCBObject); } #if GR_TEST_UTILS void GrDrawingManager::testingOnly_removeOnFlushCallbackObject(GrOnFlushCallbackObject* cb) { int n = std::find(fOnFlushCBObjects.begin(), fOnFlushCBObjects.end(), cb) - fOnFlushCBObjects.begin(); SkASSERT(n < fOnFlushCBObjects.count()); fOnFlushCBObjects.removeShuffle(n); } #endif void GrDrawingManager::moveRenderTasksToDDL(SkDeferredDisplayList* ddl) { SkDEBUGCODE(this->validate()); // no renderTask should receive a new command after this fDAG.closeAll(fContext->priv().caps()); fActiveOpsTask = nullptr; fDAG.swap(&ddl->fRenderTasks); SkASSERT(!fDAG.numRenderTasks()); for (auto& renderTask : ddl->fRenderTasks) { renderTask->prePrepare(fContext); } ddl->fArenas = std::move(fContext->priv().detachArenas()); fContext->priv().detachProgramData(&ddl->fProgramData); if (fPathRendererChain) { if (auto ccpr = fPathRendererChain->getCoverageCountingPathRenderer()) { ddl->fPendingPaths = ccpr->detachPendingPaths(); } } SkDEBUGCODE(this->validate()); } void GrDrawingManager::copyRenderTasksFromDDL(const SkDeferredDisplayList* ddl, GrRenderTargetProxy* newDest) { SkDEBUGCODE(this->validate()); if (fActiveOpsTask) { // This is a temporary fix for the partial-MDB world. In that world we're not // reordering so ops that (in the single opsTask world) would've just glommed onto the // end of the single opsTask but referred to a far earlier RT need to appear in their // own opsTask. fActiveOpsTask->makeClosed(*fContext->priv().caps()); fActiveOpsTask = nullptr; } this->addDDLTarget(newDest); // Here we jam the proxy that backs the current replay SkSurface into the LazyProxyData. // The lazy proxy that references it (in the copied opsTasks) will steal its GrTexture. ddl->fLazyProxyData->fReplayDest = newDest; if (ddl->fPendingPaths.size()) { GrCoverageCountingPathRenderer* ccpr = this->getCoverageCountingPathRenderer(); ccpr->mergePendingPaths(ddl->fPendingPaths); } fDAG.add(ddl->fRenderTasks); SkDEBUGCODE(this->validate()); } #ifdef SK_DEBUG void GrDrawingManager::validate() const { if (fDAG.sortingRenderTasks() && fReduceOpsTaskSplitting) { SkASSERT(!fActiveOpsTask); } else { if (fActiveOpsTask) { SkASSERT(!fDAG.empty()); SkASSERT(!fActiveOpsTask->isClosed()); SkASSERT(fActiveOpsTask == fDAG.back()); } for (int i = 0; i < fDAG.numRenderTasks(); ++i) { if (fActiveOpsTask != fDAG.renderTask(i)) { // The resolveTask associated with the activeTask remains open for as long as the // activeTask does. bool isActiveResolveTask = fActiveOpsTask && fActiveOpsTask->fTextureResolveTask == fDAG.renderTask(i); SkASSERT(isActiveResolveTask || fDAG.renderTask(i)->isClosed()); } } if (!fDAG.empty() && !fDAG.back()->isClosed()) { SkASSERT(fActiveOpsTask == fDAG.back()); } } } #endif void GrDrawingManager::closeRenderTasksForNewRenderTask(GrSurfaceProxy* target) { if (target && fDAG.sortingRenderTasks() && fReduceOpsTaskSplitting) { // In this case we need to close all the renderTasks that rely on the current contents of // 'target'. That is bc we're going to update the content of the proxy so they need to be // split in case they use both the old and new content. (This is a bit of an overkill: they // really only need to be split if they ever reference proxy's contents again but that is // hard to predict/handle). if (GrRenderTask* lastRenderTask = target->getLastRenderTask()) { lastRenderTask->closeThoseWhoDependOnMe(*fContext->priv().caps()); } } else if (fActiveOpsTask) { // This is a temporary fix for the partial-MDB world. In that world we're not // reordering so ops that (in the single opsTask world) would've just glommed onto the // end of the single opsTask but referred to a far earlier RT need to appear in their // own opsTask. fActiveOpsTask->makeClosed(*fContext->priv().caps()); fActiveOpsTask = nullptr; } } sk_sp<GrOpsTask> GrDrawingManager::newOpsTask(GrSurfaceProxyView surfaceView, bool managedOpsTask) { SkDEBUGCODE(this->validate()); SkASSERT(fContext); GrSurfaceProxy* proxy = surfaceView.proxy(); this->closeRenderTasksForNewRenderTask(proxy); sk_sp<GrOpsTask> opsTask(new GrOpsTask(fContext->priv().arenas(), std::move(surfaceView), fContext->priv().auditTrail())); SkASSERT(proxy->getLastRenderTask() == opsTask.get()); if (managedOpsTask) { fDAG.add(opsTask); if (!fDAG.sortingRenderTasks() || !fReduceOpsTaskSplitting) { fActiveOpsTask = opsTask.get(); } } SkDEBUGCODE(this->validate()); return opsTask; } GrTextureResolveRenderTask* GrDrawingManager::newTextureResolveRenderTask(const GrCaps& caps) { // Unlike in the "new opsTask" case, we do not want to close the active opsTask, nor (if we are // in sorting and opsTask reduction mode) the render tasks that depend on any proxy's current // state. This is because those opsTasks can still receive new ops and because if they refer to // the mipmapped version of 'proxy', they will then come to depend on the render task being // created here. // // Add the new textureResolveTask before the fActiveOpsTask (if not in // sorting/opsTask-splitting-reduction mode) because it will depend upon this resolve task. // NOTE: Putting it here will also reduce the amount of work required by the topological sort. return static_cast<GrTextureResolveRenderTask*>(fDAG.addBeforeLast( sk_make_sp<GrTextureResolveRenderTask>())); } void GrDrawingManager::newWaitRenderTask(sk_sp<GrSurfaceProxy> proxy, std::unique_ptr<std::unique_ptr<GrSemaphore>[]> semaphores, int numSemaphores) { SkDEBUGCODE(this->validate()); SkASSERT(fContext); const GrCaps& caps = *fContext->priv().caps(); sk_sp<GrWaitRenderTask> waitTask = sk_make_sp<GrWaitRenderTask>(GrSurfaceProxyView(proxy), std::move(semaphores), numSemaphores); if (fReduceOpsTaskSplitting) { GrRenderTask* lastTask = proxy->getLastRenderTask(); if (lastTask && !lastTask->isClosed()) { // We directly make the currently open renderTask depend on waitTask instead of using // the proxy version of addDependency. The waitTask will never need to trigger any // resolves or mip map generation which is the main advantage of going through the proxy // version. Additionally we would've had to temporarily set the wait task as the // lastRenderTask on the proxy, add the dependency, and then reset the lastRenderTask to // lastTask. Additionally we add all dependencies of lastTask to waitTask so that the // waitTask doesn't get reordered before them and unnecessarily block those tasks. // Note: Any previous Ops already in lastTask will get blocked by the wait semaphore // even though they don't need to be for correctness. // Make sure we add the dependencies of lastTask to waitTask first or else we'll get a // circular self dependency of waitTask on waitTask. waitTask->addDependenciesFromOtherTask(lastTask); lastTask->addDependency(waitTask.get()); } else { // If there is a last task we set the waitTask to depend on it so that it doesn't get // reordered in front of the lastTask causing the lastTask to be blocked by the // semaphore. Again we directly just go through adding the dependency to the task and // not the proxy since we don't need to worry about resolving anything. if (lastTask) { waitTask->addDependency(lastTask); } proxy->setLastRenderTask(waitTask.get()); } fDAG.add(waitTask); } else { if (fActiveOpsTask && (fActiveOpsTask->fTargetView.proxy() == proxy.get())) { SkASSERT(proxy->getLastRenderTask() == fActiveOpsTask); fDAG.addBeforeLast(waitTask); // In this case we keep the current renderTask open but just insert the new waitTask // before it in the list. The waitTask will never need to trigger any resolves or mip // map generation which is the main advantage of going through the proxy version. // Additionally we would've had to temporarily set the wait task as the lastRenderTask // on the proxy, add the dependency, and then reset the lastRenderTask to // fActiveOpsTask. Additionally we make the waitTask depend on all of fActiveOpsTask // dependencies so that we don't unnecessarily reorder the waitTask before them. // Note: Any previous Ops already in fActiveOpsTask will get blocked by the wait // semaphore even though they don't need to be for correctness. // Make sure we add the dependencies of fActiveOpsTask to waitTask first or else we'll // get a circular self dependency of waitTask on waitTask. waitTask->addDependenciesFromOtherTask(fActiveOpsTask); fActiveOpsTask->addDependency(waitTask.get()); } else { // In this case we just close the previous RenderTask and start and append the waitTask // to the DAG. Since it is the last task now we call setLastRenderTask on the proxy. If // there is a lastTask on the proxy we make waitTask depend on that task. This // dependency isn't strictly needed but it does keep the DAG from reordering the // waitTask earlier and blocking more tasks. if (GrRenderTask* lastTask = proxy->getLastRenderTask()) { waitTask->addDependency(lastTask); } proxy->setLastRenderTask(waitTask.get()); this->closeRenderTasksForNewRenderTask(proxy.get()); fDAG.add(waitTask); } } waitTask->makeClosed(caps); SkDEBUGCODE(this->validate()); } void GrDrawingManager::newTransferFromRenderTask(sk_sp<GrSurfaceProxy> srcProxy, const SkIRect& srcRect, GrColorType surfaceColorType, GrColorType dstColorType, sk_sp<GrGpuBuffer> dstBuffer, size_t dstOffset) { SkDEBUGCODE(this->validate()); SkASSERT(fContext); // This copies from srcProxy to dstBuffer so it doesn't have a real target. this->closeRenderTasksForNewRenderTask(nullptr); GrRenderTask* task = fDAG.add(sk_make_sp<GrTransferFromRenderTask>( srcProxy, srcRect, surfaceColorType, dstColorType, std::move(dstBuffer), dstOffset)); const GrCaps& caps = *fContext->priv().caps(); // We always say GrMipMapped::kNo here since we are always just copying from the base layer. We // don't need to make sure the whole mip map chain is valid. task->addDependency(srcProxy.get(), GrMipMapped::kNo, GrTextureResolveManager(this), caps); task->makeClosed(caps); // We have closed the previous active oplist but since a new oplist isn't being added there // shouldn't be an active one. SkASSERT(!fActiveOpsTask); SkDEBUGCODE(this->validate()); } bool GrDrawingManager::newCopyRenderTask(GrSurfaceProxyView srcView, const SkIRect& srcRect, GrSurfaceProxyView dstView, const SkIPoint& dstPoint) { SkDEBUGCODE(this->validate()); SkASSERT(fContext); this->closeRenderTasksForNewRenderTask(dstView.proxy()); const GrCaps& caps = *fContext->priv().caps(); GrSurfaceProxy* srcProxy = srcView.proxy(); GrRenderTask* task = fDAG.add(GrCopyRenderTask::Make(std::move(srcView), srcRect, std::move(dstView), dstPoint, &caps)); if (!task) { return false; } // We always say GrMipMapped::kNo here since we are always just copying from the base layer to // another base layer. We don't need to make sure the whole mip map chain is valid. task->addDependency(srcProxy, GrMipMapped::kNo, GrTextureResolveManager(this), caps); task->makeClosed(caps); // We have closed the previous active oplist but since a new oplist isn't being added there // shouldn't be an active one. SkASSERT(!fActiveOpsTask); SkDEBUGCODE(this->validate()); return true; } GrTextContext* GrDrawingManager::getTextContext() { if (!fTextContext) { fTextContext = GrTextContext::Make(fOptionsForTextContext); } return fTextContext.get(); } /* * This method finds a path renderer that can draw the specified path on * the provided target. * Due to its expense, the software path renderer has split out so it can * can be individually allowed/disallowed via the "allowSW" boolean. */ GrPathRenderer* GrDrawingManager::getPathRenderer(const GrPathRenderer::CanDrawPathArgs& args, bool allowSW, GrPathRendererChain::DrawType drawType, GrPathRenderer::StencilSupport* stencilSupport) { if (!fPathRendererChain) { fPathRendererChain.reset(new GrPathRendererChain(fContext, fOptionsForPathRendererChain)); } GrPathRenderer* pr = fPathRendererChain->getPathRenderer(args, drawType, stencilSupport); if (!pr && allowSW) { auto swPR = this->getSoftwarePathRenderer(); if (GrPathRenderer::CanDrawPath::kNo != swPR->canDrawPath(args)) { pr = swPR; } } return pr; } GrPathRenderer* GrDrawingManager::getSoftwarePathRenderer() { if (!fSoftwarePathRenderer) { fSoftwarePathRenderer.reset( new GrSoftwarePathRenderer(fContext->priv().proxyProvider(), fOptionsForPathRendererChain.fAllowPathMaskCaching)); } return fSoftwarePathRenderer.get(); } GrCoverageCountingPathRenderer* GrDrawingManager::getCoverageCountingPathRenderer() { if (!fPathRendererChain) { fPathRendererChain.reset(new GrPathRendererChain(fContext, fOptionsForPathRendererChain)); } return fPathRendererChain->getCoverageCountingPathRenderer(); } void GrDrawingManager::flushIfNecessary() { auto direct = fContext->priv().asDirectContext(); if (!direct) { return; } auto resourceCache = direct->priv().getResourceCache(); if (resourceCache && resourceCache->requestsFlush()) { this->flush(nullptr, 0, SkSurface::BackendSurfaceAccess::kNoAccess, GrFlushInfo(), GrPrepareForExternalIORequests()); resourceCache->purgeAsNeeded(); } }
#include <QtGlobal> // Automatically generated by extract_strings.py #ifdef __GNUC__ #define UNUSED __attribute__((unused)) #else #define UNUSED #endif static const char UNUSED *delion_strings[] = { QT_TRANSLATE_NOOP("delion-core", " mints deleted\n"), QT_TRANSLATE_NOOP("delion-core", " mints updated, "), QT_TRANSLATE_NOOP("delion-core", " unconfirmed transactions removed\n"), QT_TRANSLATE_NOOP("delion-core", "" "(1 = keep tx meta data e.g. account owner and payment request information, 2 " "= drop tx meta data)"), QT_TRANSLATE_NOOP("delion-core", "" "Allow JSON-RPC connections from specified source. Valid for <ip> are a " "single IP (e.g. 1.2.3.4), a network/netmask (e.g. 1.2.3.4/255.255.255.0) or " "a network/CIDR (e.g. 1.2.3.4/24). This option can be specified multiple times"), QT_TRANSLATE_NOOP("delion-core", "" "An error occurred while setting up the RPC address %s port %u for listening: " "%s"), QT_TRANSLATE_NOOP("delion-core", "" "Bind to given address and always listen on it. Use [host]:port notation for " "IPv6"), QT_TRANSLATE_NOOP("delion-core", "" "Bind to given address and whitelist peers connecting to it. Use [host]:port " "notation for IPv6"), QT_TRANSLATE_NOOP("delion-core", "" "Bind to given address to listen for JSON-RPC connections. Use [host]:port " "notation for IPv6. This option can be specified multiple times (default: " "bind to all interfaces)"), QT_TRANSLATE_NOOP("delion-core", "" "Calculated accumulator checkpoint is not what is recorded by block index"), QT_TRANSLATE_NOOP("delion-core", "" "Cannot obtain a lock on data directory %s. Delion Core is probably already " "running."), QT_TRANSLATE_NOOP("delion-core", "" "Change automatic finalized budget voting behavior. mode=auto: Vote for only " "exact finalized budget match to my generated budget. (string, default: auto)"), QT_TRANSLATE_NOOP("delion-core", "" "Continuously rate-limit free transactions to <n>*1000 bytes per minute " "(default:%u)"), QT_TRANSLATE_NOOP("delion-core", "" "Create new files with system default permissions, instead of umask 077 (only " "effective with disabled wallet functionality)"), QT_TRANSLATE_NOOP("delion-core", "" "Delete all wallet transactions and only recover those parts of the " "blockchain through -rescan on startup"), QT_TRANSLATE_NOOP("delion-core", "" "Disable all Delion specific functionality (Masternodes, Obfuscation, SwiftX, " "Budgeting) (0-1, default: %u)"), QT_TRANSLATE_NOOP("delion-core", "" "Distributed under the MIT software license, see the accompanying file " "COPYING or <http://www.opensource.org/licenses/mit-license.php>."), QT_TRANSLATE_NOOP("delion-core", "" "Enable automatic wallet backups triggered after each zDLN minting (0-1, " "default: %u)"), QT_TRANSLATE_NOOP("delion-core", "" "Enable spork administration functionality with the appropriate private key."), QT_TRANSLATE_NOOP("delion-core", "" "Enable SwiftX, show confirmations for locked transactions (bool, default: " "%s)"), QT_TRANSLATE_NOOP("delion-core", "" "Enter regression test mode, which uses a special chain in which blocks can " "be solved instantly."), QT_TRANSLATE_NOOP("delion-core", "" "Error: Listening for incoming connections failed (listen returned error %s)"), QT_TRANSLATE_NOOP("delion-core", "" "Error: The transaction was rejected! This might happen if some of the coins " "in your wallet were already spent, such as if you used a copy of wallet.dat " "and coins were spent in the copy but not marked as spent here."), QT_TRANSLATE_NOOP("delion-core", "" "Error: This transaction requires a transaction fee of at least %s because of " "its amount, complexity, or use of recently received funds!"), QT_TRANSLATE_NOOP("delion-core", "" "Error: Unsupported argument -checklevel found. Checklevel must be level 4."), QT_TRANSLATE_NOOP("delion-core", "" "Error: Unsupported argument -socks found. Setting SOCKS version isn't " "possible anymore, only SOCKS5 proxies are supported."), QT_TRANSLATE_NOOP("delion-core", "" "Execute command when a relevant alert is received or we see a really long " "fork (%s in cmd is replaced by message)"), QT_TRANSLATE_NOOP("delion-core", "" "Execute command when a wallet transaction changes (%s in cmd is replaced by " "TxID)"), QT_TRANSLATE_NOOP("delion-core", "" "Execute command when the best block changes (%s in cmd is replaced by block " "hash)"), QT_TRANSLATE_NOOP("delion-core", "" "Fees (in DLN/Kb) smaller than this are considered zero fee for relaying " "(default: %s)"), QT_TRANSLATE_NOOP("delion-core", "" "Fees (in DLN/Kb) smaller than this are considered zero fee for transaction " "creation (default: %s)"), QT_TRANSLATE_NOOP("delion-core", "" "Flush database activity from memory pool to disk log every <n> megabytes " "(default: %u)"), QT_TRANSLATE_NOOP("delion-core", "" "Found unconfirmed denominated outputs, will wait till they confirm to " "continue."), QT_TRANSLATE_NOOP("delion-core", "" "If paytxfee is not set, include enough fee so transactions begin " "confirmation on average within n blocks (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "" "In this mode -genproclimit controls how many blocks are generated " "immediately."), QT_TRANSLATE_NOOP("delion-core", "" "Insufficient or insufficient confirmed funds, you might need to wait a few " "minutes and try again."), QT_TRANSLATE_NOOP("delion-core", "" "Invalid amount for -maxtxfee=<amount>: '%s' (must be at least the minrelay " "fee of %s to prevent stuck transactions)"), QT_TRANSLATE_NOOP("delion-core", "" "Keep the specified amount available for spending at all times (default: 0)"), QT_TRANSLATE_NOOP("delion-core", "" "Log transaction priority and fee per kB when mining blocks (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "" "Maintain a full transaction index, used by the getrawtransaction rpc call " "(default: %u)"), QT_TRANSLATE_NOOP("delion-core", "" "Maximum size of data in data carrier transactions we relay and mine " "(default: %u)"), QT_TRANSLATE_NOOP("delion-core", "" "Maximum total fees to use in a single wallet transaction, setting too low " "may abort large transactions (default: %s)"), QT_TRANSLATE_NOOP("delion-core", "" "Number of seconds to keep misbehaving peers from reconnecting (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "" "Obfuscation uses exact denominated amounts to send funds, you might simply " "need to anonymize some more coins."), QT_TRANSLATE_NOOP("delion-core", "" "Output debugging information (default: %u, supplying <category> is optional)"), QT_TRANSLATE_NOOP("delion-core", "" "Preferred Denomination for automatically minted Zerocoin " "(1/5/10/50/100/500/1000/5000), 0 for no preference. default: %u)"), QT_TRANSLATE_NOOP("delion-core", "" "Query for peer addresses via DNS lookup, if low on addresses (default: 1 " "unless -connect)"), QT_TRANSLATE_NOOP("delion-core", "" "Randomize credentials for every proxy connection. This enables Tor stream " "isolation (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "" "Require high priority for relaying free or low-fee transactions (default:%u)"), QT_TRANSLATE_NOOP("delion-core", "" "Send trace/debug info to console instead of debug.log file (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "" "Set maximum size of high-priority/low-fee transactions in bytes (default: %d)"), QT_TRANSLATE_NOOP("delion-core", "" "Set the number of script verification threads (%u to %d, 0 = auto, <0 = " "leave that many cores free, default: %d)"), QT_TRANSLATE_NOOP("delion-core", "" "Set the number of threads for coin generation if enabled (-1 = all cores, " "default: %d)"), QT_TRANSLATE_NOOP("delion-core", "" "Show N confirmations for a successfully locked transaction (0-9999, default: " "%u)"), QT_TRANSLATE_NOOP("delion-core", "" "Support filtering of blocks and transaction with bloom filters (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "" "SwiftX requires inputs with at least 6 confirmations, you might need to " "wait a few minutes and try again."), QT_TRANSLATE_NOOP("delion-core", "" "This is a pre-release test build - use at your own risk - do not use for " "staking or merchant applications!"), QT_TRANSLATE_NOOP("delion-core", "" "This product includes software developed by the OpenSSL Project for use in " "the OpenSSL Toolkit <https://www.openssl.org/> and cryptographic software " "written by Eric Young and UPnP software written by Thomas Bernard."), QT_TRANSLATE_NOOP("delion-core", "" "To use deliond, or the -server option to delion-qt, you must set an rpcpassword " "in the configuration file:\n" "%s\n" "It is recommended you use the following random password:\n" "rpcuser=delionrpc\n" "rpcpassword=%s\n" "(you do not need to remember this password)\n" "The username and password MUST NOT be the same.\n" "If the file does not exist, create it with owner-readable-only file " "permissions.\n" "It is also recommended to set alertnotify so you are notified of problems;\n" "for example: alertnotify=echo %%s | mail -s \"Delion Alert\" admin@foo.com\n"), QT_TRANSLATE_NOOP("delion-core", "" "Unable to bind to %s on this computer. Delion Core is probably already running."), QT_TRANSLATE_NOOP("delion-core", "" "Unable to locate enough Obfuscation denominated funds for this transaction."), QT_TRANSLATE_NOOP("delion-core", "" "Unable to locate enough Obfuscation non-denominated funds for this " "transaction that are not equal 10000 DLN."), QT_TRANSLATE_NOOP("delion-core", "" "Unable to locate enough funds for this transaction that are not equal 10000 " "DELION."), QT_TRANSLATE_NOOP("delion-core", "" "Use separate SOCKS5 proxy to reach peers via Tor hidden services (default: " "%s)"), QT_TRANSLATE_NOOP("delion-core", "" "Warning: -maxtxfee is set very high! Fees this large could be paid on a " "single transaction."), QT_TRANSLATE_NOOP("delion-core", "" "Warning: -paytxfee is set very high! This is the transaction fee you will " "pay if you send a transaction."), QT_TRANSLATE_NOOP("delion-core", "" "Warning: Please check that your computer's date and time are correct! If " "your clock is wrong Delion Core will not work properly."), QT_TRANSLATE_NOOP("delion-core", "" "Warning: The network does not appear to fully agree! Some miners appear to " "be experiencing issues."), QT_TRANSLATE_NOOP("delion-core", "" "Warning: We do not appear to fully agree with our peers! You may need to " "upgrade, or other nodes may need to upgrade."), QT_TRANSLATE_NOOP("delion-core", "" "Warning: error reading wallet.dat! All keys read correctly, but transaction " "data or address book entries might be missing or incorrect."), QT_TRANSLATE_NOOP("delion-core", "" "Warning: wallet.dat corrupt, data salvaged! Original wallet.dat saved as " "wallet.{timestamp}.bak in %s; if your balance or transactions are incorrect " "you should restore from a backup."), QT_TRANSLATE_NOOP("delion-core", "" "Whitelist peers connecting from the given netmask or IP address. Can be " "specified multiple times."), QT_TRANSLATE_NOOP("delion-core", "" "Whitelisted peers cannot be DoS banned and their transactions are always " "relayed, even if they are already in the mempool, useful e.g. for a gateway"), QT_TRANSLATE_NOOP("delion-core", "" "You must specify a masternodeprivkey in the configuration. Please see " "documentation for help."), QT_TRANSLATE_NOOP("delion-core", "(15858 could be used only on mainnet)"), QT_TRANSLATE_NOOP("delion-core", "(default: %s)"), QT_TRANSLATE_NOOP("delion-core", "(default: 1)"), QT_TRANSLATE_NOOP("delion-core", "(must be 15858 for mainnet)"), QT_TRANSLATE_NOOP("delion-core", "<category> can be:"), QT_TRANSLATE_NOOP("delion-core", "Accept command line and JSON-RPC commands"), QT_TRANSLATE_NOOP("delion-core", "Accept connections from outside (default: 1 if no -proxy or -connect)"), QT_TRANSLATE_NOOP("delion-core", "Accept public REST requests (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Acceptable ciphers (default: %s)"), QT_TRANSLATE_NOOP("delion-core", "Add a node to connect to and attempt to keep the connection open"), QT_TRANSLATE_NOOP("delion-core", "Allow DNS lookups for -addnode, -seednode and -connect"), QT_TRANSLATE_NOOP("delion-core", "Already have that input."), QT_TRANSLATE_NOOP("delion-core", "Always query for peer addresses via DNS lookup (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Attempt to force blockchain corruption recovery"), QT_TRANSLATE_NOOP("delion-core", "Attempt to recover private keys from a corrupt wallet.dat"), QT_TRANSLATE_NOOP("delion-core", "Automatically create Tor hidden service (default: %d)"), QT_TRANSLATE_NOOP("delion-core", "Block creation options:"), QT_TRANSLATE_NOOP("delion-core", "Calculating missing accumulators..."), QT_TRANSLATE_NOOP("delion-core", "Can't denominate: no compatible inputs left."), QT_TRANSLATE_NOOP("delion-core", "Can't find random Masternode."), QT_TRANSLATE_NOOP("delion-core", "Can't mix while sync in progress."), QT_TRANSLATE_NOOP("delion-core", "Cannot downgrade wallet"), QT_TRANSLATE_NOOP("delion-core", "Cannot resolve -bind address: '%s'"), QT_TRANSLATE_NOOP("delion-core", "Cannot resolve -externalip address: '%s'"), QT_TRANSLATE_NOOP("delion-core", "Cannot resolve -whitebind address: '%s'"), QT_TRANSLATE_NOOP("delion-core", "Cannot write default address"), QT_TRANSLATE_NOOP("delion-core", "Collateral not valid."), QT_TRANSLATE_NOOP("delion-core", "Connect only to the specified node(s)"), QT_TRANSLATE_NOOP("delion-core", "Connect through SOCKS5 proxy"), QT_TRANSLATE_NOOP("delion-core", "Connect to a node to retrieve peer addresses, and disconnect"), QT_TRANSLATE_NOOP("delion-core", "Connection options:"), QT_TRANSLATE_NOOP("delion-core", "Copyright (C) 2009-%i The Bitcoin Core Developers"), QT_TRANSLATE_NOOP("delion-core", "Copyright (C) 2014-%i The Dash Core Developers"), QT_TRANSLATE_NOOP("delion-core", "Copyright (C) 2015-%i The PIVX Core Developers"), QT_TRANSLATE_NOOP("delion-core", "Copyright (C) 2018-2019 The Delion Core Developers"), QT_TRANSLATE_NOOP("delion-core", "Corrupted block database detected"), QT_TRANSLATE_NOOP("delion-core", "Could not parse -rpcbind value %s as network address"), QT_TRANSLATE_NOOP("delion-core", "Could not parse masternode.conf"), QT_TRANSLATE_NOOP("delion-core", "Debugging/Testing options:"), QT_TRANSLATE_NOOP("delion-core", "Delete blockchain folders and resync from scratch"), QT_TRANSLATE_NOOP("delion-core", "Disable OS notifications for incoming transactions (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Disable safemode, override a real safe mode event (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Discover own IP address (default: 1 when listening and no -externalip)"), QT_TRANSLATE_NOOP("delion-core", "Display the stake modifier calculations in the debug.log file."), QT_TRANSLATE_NOOP("delion-core", "Display verbose coin stake messages in the debug.log file."), QT_TRANSLATE_NOOP("delion-core", "Do not load the wallet and disable wallet RPC calls"), QT_TRANSLATE_NOOP("delion-core", "Do you want to rebuild the block database now?"), QT_TRANSLATE_NOOP("delion-core", "Done loading"), QT_TRANSLATE_NOOP("delion-core", "Enable automatic Zerocoin minting (0-1, default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Enable publish hash block in <address>"), QT_TRANSLATE_NOOP("delion-core", "Enable publish hash transaction (locked via SwiftX) in <address>"), QT_TRANSLATE_NOOP("delion-core", "Enable publish hash transaction in <address>"), QT_TRANSLATE_NOOP("delion-core", "Enable publish raw block in <address>"), QT_TRANSLATE_NOOP("delion-core", "Enable publish raw transaction (locked via SwiftX) in <address>"), QT_TRANSLATE_NOOP("delion-core", "Enable publish raw transaction in <address>"), QT_TRANSLATE_NOOP("delion-core", "Enable staking functionality (0-1, default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Enable the client to act as a masternode (0-1, default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Entries are full."), QT_TRANSLATE_NOOP("delion-core", "Error connecting to Masternode."), QT_TRANSLATE_NOOP("delion-core", "Error initializing block database"), QT_TRANSLATE_NOOP("delion-core", "Error initializing wallet database environment %s!"), QT_TRANSLATE_NOOP("delion-core", "Error loading block database"), QT_TRANSLATE_NOOP("delion-core", "Error loading wallet.dat"), QT_TRANSLATE_NOOP("delion-core", "Error loading wallet.dat: Wallet corrupted"), QT_TRANSLATE_NOOP("delion-core", "Error loading wallet.dat: Wallet requires newer version of Delion Core"), QT_TRANSLATE_NOOP("delion-core", "Error opening block database"), QT_TRANSLATE_NOOP("delion-core", "Error reading from database, shutting down."), QT_TRANSLATE_NOOP("delion-core", "Error recovering public key."), QT_TRANSLATE_NOOP("delion-core", "Error"), QT_TRANSLATE_NOOP("delion-core", "Error: A fatal internal error occured, see debug.log for details"), QT_TRANSLATE_NOOP("delion-core", "Error: Can't select current denominated inputs"), QT_TRANSLATE_NOOP("delion-core", "Error: Disk space is low!"), QT_TRANSLATE_NOOP("delion-core", "Error: Unsupported argument -tor found, use -onion."), QT_TRANSLATE_NOOP("delion-core", "Error: Wallet locked, unable to create transaction!"), QT_TRANSLATE_NOOP("delion-core", "Error: You already have pending entries in the Obfuscation pool"), QT_TRANSLATE_NOOP("delion-core", "Failed to listen on any port. Use -listen=0 if you want this."), QT_TRANSLATE_NOOP("delion-core", "Failed to read block index"), QT_TRANSLATE_NOOP("delion-core", "Failed to read block"), QT_TRANSLATE_NOOP("delion-core", "Failed to write block index"), QT_TRANSLATE_NOOP("delion-core", "Fee (in DELION/kB) to add to transactions you send (default: %s)"), QT_TRANSLATE_NOOP("delion-core", "Finalizing transaction."), QT_TRANSLATE_NOOP("delion-core", "Force safe mode (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Found enough users, signing ( waiting %s )"), QT_TRANSLATE_NOOP("delion-core", "Found enough users, signing ..."), QT_TRANSLATE_NOOP("delion-core", "Generate coins (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "How many blocks to check at startup (default: %u, 0 = all)"), QT_TRANSLATE_NOOP("delion-core", "If <category> is not supplied, output all debugging information."), QT_TRANSLATE_NOOP("delion-core", "Importing..."), QT_TRANSLATE_NOOP("delion-core", "Imports blocks from external blk000??.dat file"), QT_TRANSLATE_NOOP("delion-core", "Include IP addresses in debug output (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Incompatible mode."), QT_TRANSLATE_NOOP("delion-core", "Incompatible version."), QT_TRANSLATE_NOOP("delion-core", "Incorrect or no genesis block found. Wrong datadir for network?"), QT_TRANSLATE_NOOP("delion-core", "Information"), QT_TRANSLATE_NOOP("delion-core", "Initialization sanity check failed. Delion Core is shutting down."), QT_TRANSLATE_NOOP("delion-core", "Input is not valid."), QT_TRANSLATE_NOOP("delion-core", "Insufficient funds"), QT_TRANSLATE_NOOP("delion-core", "Insufficient funds."), QT_TRANSLATE_NOOP("delion-core", "Invalid -onion address or hostname: '%s'"), QT_TRANSLATE_NOOP("delion-core", "Invalid -proxy address or hostname: '%s'"), QT_TRANSLATE_NOOP("delion-core", "Invalid amount for -maxtxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("delion-core", "Invalid amount for -minrelaytxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("delion-core", "Invalid amount for -mintxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("delion-core", "Invalid amount for -paytxfee=<amount>: '%s' (must be at least %s)"), QT_TRANSLATE_NOOP("delion-core", "Invalid amount for -paytxfee=<amount>: '%s'"), QT_TRANSLATE_NOOP("delion-core", "Invalid amount for -reservebalance=<amount>"), QT_TRANSLATE_NOOP("delion-core", "Invalid amount"), QT_TRANSLATE_NOOP("delion-core", "Invalid masternodeprivkey. Please see documenation."), QT_TRANSLATE_NOOP("delion-core", "Invalid netmask specified in -whitelist: '%s'"), QT_TRANSLATE_NOOP("delion-core", "Invalid port detected in masternode.conf"), QT_TRANSLATE_NOOP("delion-core", "Invalid private key."), QT_TRANSLATE_NOOP("delion-core", "Invalid script detected."), QT_TRANSLATE_NOOP("delion-core", "Keep at most <n> unconnectable transactions in memory (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Last Obfuscation was too recent."), QT_TRANSLATE_NOOP("delion-core", "Last successful Obfuscation action was too recent."), QT_TRANSLATE_NOOP("delion-core", "Less than 3 mints added, unable to create spend"), QT_TRANSLATE_NOOP("delion-core", "Limit size of signature cache to <n> entries (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Line: %d"), QT_TRANSLATE_NOOP("delion-core", "Listen for JSON-RPC connections on <port> (default: %u or testnet: %u)"), QT_TRANSLATE_NOOP("delion-core", "Listen for connections on <port> (default: %u or testnet: %u)"), QT_TRANSLATE_NOOP("delion-core", "Loading addresses..."), QT_TRANSLATE_NOOP("delion-core", "Loading block index..."), QT_TRANSLATE_NOOP("delion-core", "Loading budget cache..."), QT_TRANSLATE_NOOP("delion-core", "Loading masternode cache..."), QT_TRANSLATE_NOOP("delion-core", "Loading masternode payment cache..."), QT_TRANSLATE_NOOP("delion-core", "Loading sporks..."), QT_TRANSLATE_NOOP("delion-core", "Loading wallet... (%3.2f %%)"), QT_TRANSLATE_NOOP("delion-core", "Loading wallet..."), QT_TRANSLATE_NOOP("delion-core", "Lock is already in place."), QT_TRANSLATE_NOOP("delion-core", "Lock masternodes from masternode configuration file (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Maintain at most <n> connections to peers (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Masternode options:"), QT_TRANSLATE_NOOP("delion-core", "Masternode queue is full."), QT_TRANSLATE_NOOP("delion-core", "Masternode:"), QT_TRANSLATE_NOOP("delion-core", "Maximum per-connection receive buffer, <n>*1000 bytes (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Maximum per-connection send buffer, <n>*1000 bytes (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Missing input transaction information."), QT_TRANSLATE_NOOP("delion-core", "Mixing in progress..."), QT_TRANSLATE_NOOP("delion-core", "Need to specify a port with -whitebind: '%s'"), QT_TRANSLATE_NOOP("delion-core", "No Masternodes detected."), QT_TRANSLATE_NOOP("delion-core", "No compatible Masternode found."), QT_TRANSLATE_NOOP("delion-core", "No funds detected in need of denominating."), QT_TRANSLATE_NOOP("delion-core", "No matching denominations found for mixing."), QT_TRANSLATE_NOOP("delion-core", "Node relay options:"), QT_TRANSLATE_NOOP("delion-core", "Non-standard public key detected."), QT_TRANSLATE_NOOP("delion-core", "Not compatible with existing transactions."), QT_TRANSLATE_NOOP("delion-core", "Not enough file descriptors available."), QT_TRANSLATE_NOOP("delion-core", "Not in the Masternode list."), QT_TRANSLATE_NOOP("delion-core", "Number of automatic wallet backups (default: 10)"), QT_TRANSLATE_NOOP("delion-core", "Obfuscation is idle."), QT_TRANSLATE_NOOP("delion-core", "Obfuscation request complete:"), QT_TRANSLATE_NOOP("delion-core", "Obfuscation request incomplete:"), QT_TRANSLATE_NOOP("delion-core", "Only accept block chain matching built-in checkpoints (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Only connect to nodes in network <net> (ipv4, ipv6 or onion)"), QT_TRANSLATE_NOOP("delion-core", "Options:"), QT_TRANSLATE_NOOP("delion-core", "Password for JSON-RPC connections"), QT_TRANSLATE_NOOP("delion-core", "Percentage of automatically minted Zerocoin (10-100, default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Preparing for resync..."), QT_TRANSLATE_NOOP("delion-core", "Prepend debug output with timestamp (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Print version and exit"), QT_TRANSLATE_NOOP("delion-core", "RPC SSL options: (see the Bitcoin Wiki for SSL setup instructions)"), QT_TRANSLATE_NOOP("delion-core", "RPC server options:"), QT_TRANSLATE_NOOP("delion-core", "RPC support for HTTP persistent connections (default: %d)"), QT_TRANSLATE_NOOP("delion-core", "Randomly drop 1 of every <n> network messages"), QT_TRANSLATE_NOOP("delion-core", "Randomly fuzz 1 of every <n> network messages"), QT_TRANSLATE_NOOP("delion-core", "Rebuild block chain index from current blk000??.dat files"), QT_TRANSLATE_NOOP("delion-core", "Recalculating coin supply may take 30-60 minutes..."), QT_TRANSLATE_NOOP("delion-core", "Recalculating supply statistics may take 30-60 minutes..."), QT_TRANSLATE_NOOP("delion-core", "Receive and display P2P network alerts (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Relay and mine data carrier transactions (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Relay non-P2SH multisig (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Rescan the block chain for missing wallet transactions"), QT_TRANSLATE_NOOP("delion-core", "Rescanning..."), QT_TRANSLATE_NOOP("delion-core", "ResetMintZerocoin finished: "), QT_TRANSLATE_NOOP("delion-core", "ResetSpentZerocoin finished: "), QT_TRANSLATE_NOOP("delion-core", "Run a thread to flush wallet periodically (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Run in the background as a daemon and accept commands"), QT_TRANSLATE_NOOP("delion-core", "Send transactions as zero-fee transactions if possible (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Server certificate file (default: %s)"), QT_TRANSLATE_NOOP("delion-core", "Server private key (default: %s)"), QT_TRANSLATE_NOOP("delion-core", "Session not complete!"), QT_TRANSLATE_NOOP("delion-core", "Session timed out."), QT_TRANSLATE_NOOP("delion-core", "Set database cache size in megabytes (%d to %d, default: %d)"), QT_TRANSLATE_NOOP("delion-core", "Set external address:port to get to this masternode (example: %s)"), QT_TRANSLATE_NOOP("delion-core", "Set key pool size to <n> (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Set maximum block size in bytes (default: %d)"), QT_TRANSLATE_NOOP("delion-core", "Set minimum block size in bytes (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Set the Maximum reorg depth (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Set the masternode private key"), QT_TRANSLATE_NOOP("delion-core", "Set the number of threads to service RPC calls (default: %d)"), QT_TRANSLATE_NOOP("delion-core", "Sets the DB_PRIVATE flag in the wallet db environment (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Show all debugging options (usage: --help -help-debug)"), QT_TRANSLATE_NOOP("delion-core", "Shrink debug.log file on client startup (default: 1 when no -debug)"), QT_TRANSLATE_NOOP("delion-core", "Signing failed."), QT_TRANSLATE_NOOP("delion-core", "Signing timed out."), QT_TRANSLATE_NOOP("delion-core", "Signing transaction failed"), QT_TRANSLATE_NOOP("delion-core", "Specify configuration file (default: %s)"), QT_TRANSLATE_NOOP("delion-core", "Specify connection timeout in milliseconds (minimum: 1, default: %d)"), QT_TRANSLATE_NOOP("delion-core", "Specify data directory"), QT_TRANSLATE_NOOP("delion-core", "Specify masternode configuration file (default: %s)"), QT_TRANSLATE_NOOP("delion-core", "Specify pid file (default: %s)"), QT_TRANSLATE_NOOP("delion-core", "Specify wallet file (within data directory)"), QT_TRANSLATE_NOOP("delion-core", "Specify your own public address"), QT_TRANSLATE_NOOP("delion-core", "Spend unconfirmed change when sending transactions (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Staking options:"), QT_TRANSLATE_NOOP("delion-core", "Stop running after importing blocks from disk (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Submitted following entries to masternode: %u / %d"), QT_TRANSLATE_NOOP("delion-core", "Submitted to masternode, waiting for more entries ( %u / %d ) %s"), QT_TRANSLATE_NOOP("delion-core", "Submitted to masternode, waiting in queue %s"), QT_TRANSLATE_NOOP("delion-core", "SwiftX options:"), QT_TRANSLATE_NOOP("delion-core", "Synchronization failed"), QT_TRANSLATE_NOOP("delion-core", "Synchronization finished"), QT_TRANSLATE_NOOP("delion-core", "Synchronization pending..."), QT_TRANSLATE_NOOP("delion-core", "Synchronizing budgets..."), QT_TRANSLATE_NOOP("delion-core", "Synchronizing masternode winners..."), QT_TRANSLATE_NOOP("delion-core", "Synchronizing masternodes..."), QT_TRANSLATE_NOOP("delion-core", "Synchronizing sporks..."), QT_TRANSLATE_NOOP("delion-core", "This help message"), QT_TRANSLATE_NOOP("delion-core", ""), QT_TRANSLATE_NOOP("delion-core", "This is intended for regression testing tools and app development."), QT_TRANSLATE_NOOP("delion-core", "This is not a Masternode."), QT_TRANSLATE_NOOP("delion-core", "Threshold for disconnecting misbehaving peers (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Tor control port password (default: empty)"), QT_TRANSLATE_NOOP("delion-core", "Tor control port to use if onion listening enabled (default: %s)"), QT_TRANSLATE_NOOP("delion-core", "Transaction amount too small"), QT_TRANSLATE_NOOP("delion-core", "Transaction amounts must be positive"), QT_TRANSLATE_NOOP("delion-core", "Transaction created successfully."), QT_TRANSLATE_NOOP("delion-core", "Transaction fees are too high."), QT_TRANSLATE_NOOP("delion-core", "Transaction not valid."), QT_TRANSLATE_NOOP("delion-core", "Transaction too large for fee policy"), QT_TRANSLATE_NOOP("delion-core", "Transaction too large"), QT_TRANSLATE_NOOP("delion-core", "Transmitting final transaction."), QT_TRANSLATE_NOOP("delion-core", "Unable to bind to %s on this computer (bind returned error %s)"), QT_TRANSLATE_NOOP("delion-core", "Unable to sign spork message, wrong key?"), QT_TRANSLATE_NOOP("delion-core", "Unknown network specified in -onlynet: '%s'"), QT_TRANSLATE_NOOP("delion-core", "Unknown state: id = %u"), QT_TRANSLATE_NOOP("delion-core", "Upgrade wallet to latest format"), QT_TRANSLATE_NOOP("delion-core", "Use OpenSSL (https) for JSON-RPC connections"), QT_TRANSLATE_NOOP("delion-core", "Use UPnP to map the listening port (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Use UPnP to map the listening port (default: 1 when listening)"), QT_TRANSLATE_NOOP("delion-core", "Use a custom max chain reorganization depth (default: %u)"), QT_TRANSLATE_NOOP("delion-core", "Use the test network"), QT_TRANSLATE_NOOP("delion-core", "Username for JSON-RPC connections"), QT_TRANSLATE_NOOP("delion-core", "Value more than Obfuscation pool maximum allows."), QT_TRANSLATE_NOOP("delion-core", "Verifying blocks..."), QT_TRANSLATE_NOOP("delion-core", "Verifying wallet..."), QT_TRANSLATE_NOOP("delion-core", "Wallet %s resides outside data directory %s"), QT_TRANSLATE_NOOP("delion-core", "Wallet is locked."), QT_TRANSLATE_NOOP("delion-core", "Wallet needed to be rewritten: restart Delion Core to complete"), QT_TRANSLATE_NOOP("delion-core", "Wallet options:"), QT_TRANSLATE_NOOP("delion-core", "Wallet window title"), QT_TRANSLATE_NOOP("delion-core", "Warning"), QT_TRANSLATE_NOOP("delion-core", "Warning: This version is obsolete, upgrade required!"), QT_TRANSLATE_NOOP("delion-core", "Warning: Unsupported argument -benchmark ignored, use -debug=bench."), QT_TRANSLATE_NOOP("delion-core", "Warning: Unsupported argument -debugnet ignored, use -debug=net."), QT_TRANSLATE_NOOP("delion-core", "Will retry..."), QT_TRANSLATE_NOOP("delion-core", "You need to rebuild the database using -reindex to change -txindex"), QT_TRANSLATE_NOOP("delion-core", "Your entries added successfully."), QT_TRANSLATE_NOOP("delion-core", "Your transaction was accepted into the pool!"), QT_TRANSLATE_NOOP("delion-core", "Zapping all transactions from wallet..."), QT_TRANSLATE_NOOP("delion-core", "ZeroMQ notification options:"), QT_TRANSLATE_NOOP("delion-core", "Zerocoin options:"), QT_TRANSLATE_NOOP("delion-core", "failed to validate zerocoin"), QT_TRANSLATE_NOOP("delion-core", "on startup"), QT_TRANSLATE_NOOP("delion-core", "wallet.dat corrupt, salvage failed"), };
#include <bits/stdc++.h> using namespace std; #include "bloom_filter.hpp" int main(void) { for(int i=4;i<8;i*=2) { for(int j=1;j<=100;j++) { bloom_parameters parameters; //parameters.maximum_size=16; parameters.projected_element_count = i; parameters.maximum_number_of_hashes = 4; parameters.minimum_number_of_hashes = 4; parameters.false_positive_probability = 1.0*j/100.0; //parameters.maximum_size=i; if (!parameters) { std::cout << "Error - Invalid set of bloom filter parameters!" << std::endl; } else { parameters.compute_optimal_parameters(); cout<<j<<" "<<parameters.optimal_parameters.number_of_hashes<<" "<<parameters.optimal_parameters.table_size<<endl; } } } }
/** * firewall API generated from firewall.yang * * NOTE: This file is auto generated by polycube-codegen * https://github.com/polycube-network/polycube-codegen */ /* Do not edit this file manually */ #include "FirewallJsonObject.h" #include <regex> namespace polycube { namespace service { namespace model { FirewallJsonObject::FirewallJsonObject() { m_nameIsSet = false; m_conntrackIsSet = false; m_acceptEstablishedIsSet = false; m_sessionTableIsSet = false; m_chainIsSet = false; } FirewallJsonObject::FirewallJsonObject(const nlohmann::json &val) : JsonObjectBase(val) { m_nameIsSet = false; m_conntrackIsSet = false; m_acceptEstablishedIsSet = false; m_sessionTableIsSet = false; m_chainIsSet = false; if (val.count("name")) { setName(val.at("name").get<std::string>()); } if (val.count("conntrack")) { setConntrack(string_to_FirewallConntrackEnum(val.at("conntrack").get<std::string>())); } if (val.count("accept-established")) { setAcceptEstablished(string_to_FirewallAcceptEstablishedEnum(val.at("accept-established").get<std::string>())); } if (val.count("session-table")) { for (auto& item : val["session-table"]) { SessionTableJsonObject newItem{ item }; m_sessionTable.push_back(newItem); } m_sessionTableIsSet = true; } if (val.count("chain")) { for (auto& item : val["chain"]) { ChainJsonObject newItem{ item }; m_chain.push_back(newItem); } m_chainIsSet = true; } } nlohmann::json FirewallJsonObject::toJson() const { nlohmann::json val = nlohmann::json::object(); if (!getBase().is_null()) { val.update(getBase()); } if (m_nameIsSet) { val["name"] = m_name; } if (m_conntrackIsSet) { val["conntrack"] = FirewallConntrackEnum_to_string(m_conntrack); } if (m_acceptEstablishedIsSet) { val["accept-established"] = FirewallAcceptEstablishedEnum_to_string(m_acceptEstablished); } { nlohmann::json jsonArray; for (auto& item : m_sessionTable) { jsonArray.push_back(JsonObjectBase::toJson(item)); } if (jsonArray.size() > 0) { val["session-table"] = jsonArray; } } { nlohmann::json jsonArray; for (auto& item : m_chain) { jsonArray.push_back(JsonObjectBase::toJson(item)); } if (jsonArray.size() > 0) { val["chain"] = jsonArray; } } return val; } std::string FirewallJsonObject::getName() const { return m_name; } void FirewallJsonObject::setName(std::string value) { m_name = value; m_nameIsSet = true; } bool FirewallJsonObject::nameIsSet() const { return m_nameIsSet; } FirewallConntrackEnum FirewallJsonObject::getConntrack() const { return m_conntrack; } void FirewallJsonObject::setConntrack(FirewallConntrackEnum value) { m_conntrack = value; m_conntrackIsSet = true; } bool FirewallJsonObject::conntrackIsSet() const { return m_conntrackIsSet; } void FirewallJsonObject::unsetConntrack() { m_conntrackIsSet = false; } std::string FirewallJsonObject::FirewallConntrackEnum_to_string(const FirewallConntrackEnum &value){ switch(value) { case FirewallConntrackEnum::ON: return std::string("on"); case FirewallConntrackEnum::OFF: return std::string("off"); default: throw std::runtime_error("Bad Firewall conntrack"); } } FirewallConntrackEnum FirewallJsonObject::string_to_FirewallConntrackEnum(const std::string &str){ if (JsonObjectBase::iequals("on", str)) return FirewallConntrackEnum::ON; if (JsonObjectBase::iequals("off", str)) return FirewallConntrackEnum::OFF; throw std::runtime_error("Firewall conntrack is invalid"); } FirewallAcceptEstablishedEnum FirewallJsonObject::getAcceptEstablished() const { return m_acceptEstablished; } void FirewallJsonObject::setAcceptEstablished(FirewallAcceptEstablishedEnum value) { m_acceptEstablished = value; m_acceptEstablishedIsSet = true; } bool FirewallJsonObject::acceptEstablishedIsSet() const { return m_acceptEstablishedIsSet; } void FirewallJsonObject::unsetAcceptEstablished() { m_acceptEstablishedIsSet = false; } std::string FirewallJsonObject::FirewallAcceptEstablishedEnum_to_string(const FirewallAcceptEstablishedEnum &value){ switch(value) { case FirewallAcceptEstablishedEnum::ON: return std::string("on"); case FirewallAcceptEstablishedEnum::OFF: return std::string("off"); default: throw std::runtime_error("Bad Firewall acceptEstablished"); } } FirewallAcceptEstablishedEnum FirewallJsonObject::string_to_FirewallAcceptEstablishedEnum(const std::string &str){ if (JsonObjectBase::iequals("on", str)) return FirewallAcceptEstablishedEnum::ON; if (JsonObjectBase::iequals("off", str)) return FirewallAcceptEstablishedEnum::OFF; throw std::runtime_error("Firewall acceptEstablished is invalid"); } const std::vector<SessionTableJsonObject>& FirewallJsonObject::getSessionTable() const{ return m_sessionTable; } void FirewallJsonObject::addSessionTable(SessionTableJsonObject value) { m_sessionTable.push_back(value); m_sessionTableIsSet = true; } bool FirewallJsonObject::sessionTableIsSet() const { return m_sessionTableIsSet; } void FirewallJsonObject::unsetSessionTable() { m_sessionTableIsSet = false; } const std::vector<ChainJsonObject>& FirewallJsonObject::getChain() const{ return m_chain; } void FirewallJsonObject::addChain(ChainJsonObject value) { m_chain.push_back(value); m_chainIsSet = true; } bool FirewallJsonObject::chainIsSet() const { return m_chainIsSet; } void FirewallJsonObject::unsetChain() { m_chainIsSet = false; } } } }
///////////////////////////////////////////////////////////////////////// /// /// /// /// /// This Academic Free License applies to any software and associated /// /// documentation (the "Software") whose owner (the "Licensor") has /// /// placed the statement "Licensed under the Academic Free License /// /// Version 1.0" immediately after the copyright notice that applies /// /// to the Software. /// /// Permission is hereby granted, free of charge, to any person /// /// obtaining a copy of the Software (1) to use, copy, modify, merge, /// /// publish, perform, distribute, sublicense, and/or sell copies of /// /// the Software, and to permit persons to whom the Software is /// /// furnished to do so, and (2) under patent claims owned or /// /// controlled by the Licensor that are embodied in the Software as /// /// furnished by the Licensor, to make, use, sell and offer for sale /// /// the Software and derivative works thereof, subject to the /// /// following conditions: /// /// Redistributions of the Software in source code form must retain /// /// all copyright notices in the Software as furnished by the /// /// Licensor, this list of conditions, and the following disclaimers. /// /// Redistributions of the Software in executable form must reproduce /// /// all copyright notices in the Software as furnished by the /// /// Licensor, this list of conditions, and the following disclaimers /// /// in the documentation and/or other materials provided with the /// /// distribution. /// /// /// /// Neither the names of Licensor, nor the names of any contributors /// /// to the Software, nor any of their trademarks or service marks, /// /// may be used to endorse or promote products derived from this /// /// Software without express prior written permission of the Licensor./// /// /// /// DISCLAIMERS: LICENSOR WARRANTS THAT THE COPYRIGHT IN AND TO THE /// /// SOFTWARE IS OWNED BY THE LICENSOR OR THAT THE SOFTWARE IS /// /// DISTRIBUTED BY LICENSOR UNDER A VALID CURRENT LICENSE. EXCEPT AS /// /// EXPRESSLY STATED IN THE IMMEDIATELY PRECEDING SENTENCE, THE /// /// SOFTWARE IS PROVIDED BY THE LICENSOR, CONTRIBUTORS AND COPYRIGHT /// /// OWNERS "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 NON-INFRINGEMENT. IN NO /// /// EVENT SHALL THE LICENSOR, CONTRIBUTORS OR COPYRIGHT OWNERS 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. /// /// /// /// This license is Copyright (C) 2002 Lawrence E. Rosen. All rights /// /// reserved. Permission is hereby granted to copy and distribute /// /// this license without modification. This license may not be /// /// modified without the express written permission of its copyright /// /// owner. /// /// /// /// /// ///////////////////////////////////////////////////////////////////////// /// /// $Id: YARPNameServer.cpp,v 2.5 2006-01-13 11:23:24 eshuy Exp $ /// /// // YARPNameServer.cpp: implementation of the NameServer class. // ////////////////////////////////////////////////////////////////////// #include "YARPNameServer.h" #include <fstream> #include <iostream> #include <yarp/YARPAll.h> using namespace std; // this is really bad - should use real strings static char name_buffer[1000]; // server is single threaded, right? static int delay_eor = 0; // general function char * LocalGetYarpRoot (void) { char * ret = getenv ("YARP_ROOT"); if (ret == NULL) { //ACE_DEBUG ((LM_DEBUG, "::GetYarpRoot : can't retrieve YARP_ROOT env variable\n")); ret = getenv("HOME"); if (ret!=NULL) { sprintf(name_buffer,"%s/.yarp",ret); ret = name_buffer; } } return ret; } int YARPNameServer::accept_connection() { ACE_Time_Value timeout (5, 0); int ret; int one = 1; ret = peer_acceptor_.accept (new_stream_, &client_addr_, &timeout); new_stream_.set_option (ACE_IPPROTO_TCP, TCP_NODELAY, &one, sizeof(int)); return ret; } void YARPNameServer::dump_statics() { cout << "\n-Static entries: " << endl; SVC_IT i(ns.statics); for(; !i.done(); i++) { cout << (*i).name << "\t\t"; cout << (*i).ip << "\tmax ref:" << (*i).get_max_ref() << endl; } } void YARPNameServer::dump_names() { cout << "-Names: " << endl; SVC_IT i(ns.names); for(; !i.done(); i++) { cout << (*i).name << "\t\t"; cout << (*i).ip; cout << ":"; PORT_IT j ( (*i).ports ); for(; !j.done(); j++) cout << (*j).port << "," ; cout << "ref:" << ((*i).get_max_ref()-(*i).get_ref()); cout << ",(" << servicetypeConverter((*i).type) << ")"<< endl; } QNXSVC_IT j(ns.qnx_names); for(; !j.done(); j++) { cout << (*j).getName() << "\t\t"; cout << (*j).getNode() << "\t"; cout << (*j).getPid() << "\t"; cout << (*j).getChan() << "\t"; cout << "(" << servicetypeConverter(YARP_QNET) << ")"; cout << endl; } } void YARPNameServer::dump_resources() { cout << "-Resources: " << endl; IP_IT i(ns.addresses); for(; !i.done(); i++) { cout << (*i).ip << ":" << endl; PORT_IT j((*i).ports); for(; !j.done(); j++) cout << "\t" << (*j).port << endl; } } void YARPNameServer::handle_dump_request() { YARPString text; SVC_IT i(ns.names); for(; !i.done(); i++) { ///text.append(i->name); text += (*i).name; ///text.append("\n"); text += "\n"; } QNXSVC_IT j(ns.qnx_names); for(; !j.done(); j++) { ///text.append(j->getName()); text += (*j).getName(); ///text.append("\n"); text += "\n"; } if (text.empty()) text = "No names registered !\n"; _handle_reply(text); } void YARPNameServer::handle_exdump_request() { YARPString text; char dummy[255]; SVC_IT i(ns.names); for(; !i.done(); i++) { text.append((*i).name); text.append("\t"); text.append((*i).ip); text.append(":"); ///int length = i->ports.size(); PORT_IT j((*i).ports); // first port ACE_OS::sprintf(dummy, "%d", (*j).port); text.append (dummy); text.append (","); text.append (" ("); text.append (servicetypeConverter((*i).type)); text.append (")"); text.append ("\n"); } QNXSVC_IT j(ns.qnx_names); for(; !j.done(); j++) { text.append((*j).getName()); text.append("\t"); text.append((*j).getNode()); text.append("\t"); ACE_OS::sprintf(dummy, "%d", (*j).getPid()); text.append(dummy); text.append("\t"); ACE_OS::sprintf(dummy, "%d", (*j).getChan()); text.append(dummy); text.append (" ("); text.append (servicetypeConverter(YARP_QNET)); text.append (")"); text.append ("\n"); } if (text.empty()) text = "No names registered !\n"; _handle_reply(text); } void YARPNameServer::handle_registration(const YARPString &service_name, const YARPString &ip, int type, int np) { PORT_LIST ports; IpEntry tmpEntry; tmpEntry.ip = ip; // printf("about to handle %s\n", ip.c_str()); ns.registerName(service_name, tmpEntry, type, ports, np); PORT_IT i(ports); for(; !i.done(); i++) { NAME_SERVER_DEBUG(("Registered %s as %s(%s):%d\n", service_name.c_str(), tmpEntry.ip.c_str(), servicetypeConverter(type), (*i).port)); } _handle_reply(service_name.c_str(), tmpEntry.ip, type, ports); } void YARPNameServer::handle_query(const YARPString &service_name) { YARPString ip; int port; int type; //printf("mmmm %s/%d name %s\n", __FILE__, __LINE__, service_name.c_str()); ns.queryName(service_name, ip, &type, &port); NAME_SERVER_DEBUG(("Reply %s as %s(%s):%d\n", service_name.c_str(), ip.c_str(), servicetypeConverter(type), port)); //printf("mmmm %s/%d\n", __FILE__, __LINE__); _handle_reply(service_name.c_str(), ip, type, port); } void YARPNameServer::handle_query_qnx(const YARPString &name) { YARPNameQnx entry; int type; ns.queryNameQnx(name, entry, &type); NAME_SERVER_DEBUG(("Reply %s %s(%s) %d %d\n", entry.getName(), entry.getNode(), servicetypeConverter(type), entry.getPid(), entry.getChan())); _handle_reply(entry, type); } void YARPNameServer::handle_nic_query(const YARPString &ip, const YARPString &netId) { YARPString reply; YARPString outIp; YARPString nic; nmap.findIp(ip, netId, nic, outIp); NAME_SERVER_DEBUG(("Reply: %s on %s is %s(%s)\n", ip.c_str(), netId.c_str(), nic.c_str(), outIp.c_str())); reply = nic; reply.append("\n"); reply.append(outIp); _handle_reply(reply); } void YARPNameServer::handle_registration_dbg(const YARPString &service_name, const YARPString &ip, int type, int n) { PORT_LIST ports; NAME_SERVER_DEBUG(("DBG MODE: registering %s as %s(%s)\n", service_name.c_str(), ip.c_str(), servicetypeConverter(type))); IpEntry tmpEntry; tmpEntry.ip = ip; ns.registerName(service_name, tmpEntry, type, ports, n); PORT_IT i(ports); for(; !i.done(); i++) { NAME_SERVER_DEBUG(("Registered %s as %s(%s):%d\n", service_name.c_str(), tmpEntry.ip.c_str(), servicetypeConverter(type), (*i).port)); } } void YARPNameServer::handle_registration_dip_dbg(const YARPString &service_name, int type) { YARPString ip; int port; NAME_SERVER_DEBUG(("DBG MODE: registering %s (%s)\n", service_name.c_str(), servicetypeConverter(type))); ns.registerNameDIp(service_name, ip, type, &port); NAME_SERVER_DEBUG(("DBG MODE: answering %s(%s):%d\n", ip.c_str(), servicetypeConverter(type), port)); } void YARPNameServer::handle_registration_dip(const YARPString &service_name, int type) { int port; YARPString ip; //printf("/// starting handle_registration_dip\n"); ns.registerNameDIp(service_name, ip, type, &port); NAME_SERVER_DEBUG(("Registered %s as %s(%s):%d // handle_registration_dip\n", service_name.c_str(), ip.c_str(), servicetypeConverter(type), port)); _handle_reply(service_name.c_str(), ip, type, port); } void YARPNameServer::handle_registration_qnx(const YARPNameQnx &entry) { ns.registerNameQnx(entry); NAME_SERVER_DEBUG(("Registered %s %s(%s) %d %d\n", entry.getName(), entry.getNode(), servicetypeConverter(YARP_QNET), entry.getPid(), entry.getChan())); // _handle_reply(entry, type); } void YARPNameServer::handle_release_qnx(const YARPString &name) { NAME_SERVER_DEBUG(("QNX name %s no longer used, releasing\n", name.c_str())); ns.check_out_qnx(name); // _handle_reply(entry, type); } void YARPNameServer::_handle_reply(const YARPString &text) { if (using_text) { new_stream_.send_n(text.c_str(), strlen(text.c_str())+1, 0); char msg[] = "*** end of response\n"; if (!delay_eor) { new_stream_.send_n(msg, strlen(msg)+1, 0); } return; } YARPNameServiceCmd rplCmd; int length = text.length()+1; rplCmd.cmd = YARPNSDumpRpl; rplCmd.length = length; iovec iov[1]; // first vector iov[0].iov_base = data_buf_; memcpy(data_buf_ , &rplCmd, sizeof(YARPNameServiceCmd)); iov[0].iov_len = sizeof(YARPNameServiceCmd); new_stream_.sendv_n (iov, 1); int nVectors = length/SIZE_BUF; int lastVectLength = length%SIZE_BUF; int i = 0; for(i=0; i < nVectors;i++) { // nth vector memcpy(data_buf_, text.c_str()+SIZE_BUF*(i), SIZE_BUF); iov[0].iov_len = SIZE_BUF; new_stream_.sendv_n (iov, 1); } // last one ! (if any) if (lastVectLength > 0) { memcpy(data_buf_, text.c_str()+SIZE_BUF*(nVectors), lastVectLength); iov[0].iov_len = lastVectLength; new_stream_.sendv_n (iov, 1); } } void YARPNameServer::_handle_reply(const char *name, const YARPString &ip, int type, int port) { if (using_text) { char buf[1000]; sprintf(buf,"registration name %s ip %s port %d type %s\n", name, ip.c_str(), port, servicetypeConverter(type)); _handle_reply(YARPString(buf)); return; } YARPNameServiceCmd rplCmd; YARPNameTCP rpl; // avoid this! replaces host with 127.0.0.1 if we are unlucky // in the interface order... //rpl.setAddr(ACE_INET_Addr(port, ip.c_str())); if (ip==YARPString("127.0.0.1")) { rpl.setIp(local_name); } else { rpl.setIp(ip); } rpl.setPort(port); rplCmd.cmd = YARPNSRpl; rplCmd.type = type; rplCmd.length = rpl.length(); memcpy(data_buf_, &rplCmd, sizeof(YARPNameServiceCmd)); memcpy(data_buf_+sizeof(YARPNameServiceCmd), &rpl, rpl.length()); iovec iov[1]; iov[0].iov_base = data_buf_; iov[0].iov_len = rplCmd.length+sizeof(YARPNameServiceCmd); ///int sent = new_stream_.sendv_n (iov, 1); new_stream_.sendv_n (iov, 1); } void YARPNameServer::_handle_reply(const char *name, const YARPString &ip, int type, const PORT_LIST &ports) { if (using_text) { YARPString text; char buf[1000]; int j = 0; PORT_LIST &tmp = const_cast<PORT_LIST &> (ports); PORT_IT i (tmp); for(; !i.done(); i++) { int port = (*i).port; sprintf(buf,"registration name %s ip %s port %d type %s\n", name, ip.c_str(), port, servicetypeConverter(type)); text += buf; j++; } _handle_reply(text); return; } YARPNameServiceCmd rplCmd; YARPNameUDP rpl; int j = 0; PORT_LIST &tmp = const_cast<PORT_LIST &> (ports); PORT_IT i (tmp); for(; !i.done(); i++) { rpl.setPorts(j, (*i).port); j++; } rpl.setIp(ip); rplCmd.cmd = YARPNSRpl; rplCmd.length = rpl.length(); rplCmd.type = type; memcpy(data_buf_, &rplCmd, sizeof(YARPNameServiceCmd)); memcpy(data_buf_+sizeof(YARPNameServiceCmd), &rpl, rpl.length()); iovec iov[1]; iov[0].iov_base = data_buf_; iov[0].iov_len = rplCmd.length+sizeof(YARPNameServiceCmd); ///int sent = new_stream_.sendv_n (iov, 1); new_stream_.sendv_n (iov, 1); } void YARPNameServer::_handle_reply(const YARPNameQnx &entry, int type) { YARPNameServiceCmd rplCmd; YARPNameQnx rpl = entry; rplCmd.cmd = YARPNSRpl; rplCmd.length = rpl.length(); rplCmd.type = type; memcpy(data_buf_, &rplCmd, sizeof(YARPNameServiceCmd)); memcpy(data_buf_+sizeof(YARPNameServiceCmd), &rpl, rpl.length()); iovec iov[1]; iov[0].iov_base = data_buf_; iov[0].iov_len = rplCmd.length+sizeof(YARPNameServiceCmd); ///int sent = new_stream_.sendv_n (iov, 1); new_stream_.sendv_n (iov, 1); //new_stream_.sendv_n (iov, 1); } void YARPNameServer::query_dbg(const YARPString &service_name) { YARPString ip; int port; int type; NAME_SERVER_DEBUG(("DBG MODE: query %s\n", service_name.c_str())); ns.queryName(service_name, ip, &type, &port); NAME_SERVER_DEBUG(("DBG MODE: answering %s(%s):%d\n", ip.c_str(), servicetypeConverter(type), port)); } void YARPNameServer::handle_release(const YARPString &service_name) { NAME_SERVER_DEBUG(("Releasing:%s\n", service_name.c_str())); ns.check_out(service_name); } int YARPNameServer::handle_connection() { // read data from client iovec iov[1]; YARPNameServiceCmd tmpCmd; unsigned int byte_count = 0; int res = 0; memset(data_buf_, 0, SIZE_BUF); //required !! iov[0].iov_base = data_buf_; iov[0].iov_len = sizeof(YARPNameServiceCmd); res = new_stream_.recvv_n(iov, 1, 0, &byte_count); if (res != sizeof(YARPNameServiceCmd)) { NAME_SERVER_DEBUG(("Warning, error while receiving command: I expected %d bytes but received %d\n", sizeof(YARPNameServiceCmd), res)); NAME_SERVER_DEBUG(("Ignoring command\n")); return 0; } tmpCmd = *(YARPNameServiceCmd *) (data_buf_); using_text = 0; if (tmpCmd.length>1000) { char name[20]; memcpy(name,data_buf_,12); name[12] = '\0'; if (strcmp(name,"NAME_SERVER ")==0) { char buf[2000]; int at = 0; int done = 0; while (!done) { res = new_stream_.recv(buf+at, sizeof(buf)-at, 0); if (res>=0) { for (int i=at; i<at+res; i++) { if (buf[i]=='\r'||buf[i]=='\n') { buf[i] = '\0'; done = 1; } } } else { buf[0] = '\0'; done = 1; } } using_text = 1; ACE_INET_Addr remote; YARPString name("unknown"); if (new_stream_.get_remote_addr(remote)==0) { // assume INET, don't really know how to use ACE //ACE_INET_Addr& inet char nbuf[1000]; remote.get_host_addr(nbuf,sizeof(nbuf)); name = nbuf; } handle_text_command(buf,name.c_str()); tmpCmd.cmd = 0; tmpCmd.length = 0; tmpCmd.type = 0; if (new_stream_.close() == -1) ACE_ERROR ((LM_ERROR, "%p\n", "close")); return 0; } else { NAME_SERVER_DEBUG(("Ignoring strange command\n")); if (new_stream_.close() == -1) ACE_ERROR ((LM_ERROR, "%p\n", "close")); return -1; } } ////// remote dump ? if (tmpCmd.cmd == YARPNSDumpRqs) { NAME_SERVER_DEBUG(("Handle remote dump\n")); if (tmpCmd.type == 0) handle_dump_request(); else if (tmpCmd.type == 1) handle_exdump_request(); if (new_stream_.close() == -1) ACE_ERROR ((LM_ERROR, "%p\n", "close")); return 0; } /////////////////////// iov[0].iov_base = data_buf_; iov[0].iov_len = tmpCmd.length; //message length res = new_stream_.recvv_n(iov, 1, 0, &byte_count); if (res != tmpCmd.length) { NAME_SERVER_DEBUG(("Warning, error while receiving command: I expected %d bytes but received %d\n", tmpCmd.length, res)); NAME_SERVER_DEBUG(("Command ignored\n")); return 0; } if ( (tmpCmd.cmd == YARPNSQuery) && ((tmpCmd.type == YARP_UDP) || (tmpCmd.type == YARP_TCP) || (tmpCmd.type == YARP_MCAST))) { // register a name, ask back ip and port YARPNameTCP *tmpRqst = (YARPNameTCP*) (data_buf_); handle_query(tmpRqst->_name); } else if ( (tmpCmd.cmd == YARPNSQuery) && (tmpCmd.type == YARP_QNET)) { // register a name, ask back ip and port YARPNameQnx *tmpRqst = (YARPNameQnx*) (data_buf_); handle_query_qnx(YARPString(tmpRqst->getName())); } else if ((tmpCmd.cmd == YARPNSRelease) && ((tmpCmd.type == YARP_UDP) || (tmpCmd.type == YARP_TCP) || (tmpCmd.type == YARP_MCAST))) { // release a name YARPNameTCP *tmpRqst = (YARPNameTCP*) (data_buf_); handle_release(tmpRqst->_name); } else if ((tmpCmd.cmd == YARPNSRelease) && (tmpCmd.type == YARP_QNET) ) { // release a name YARPNameQnx *tmpRqst = (YARPNameQnx*) (data_buf_); handle_release_qnx(tmpRqst->getName()); } else if ( (tmpCmd.cmd == YARPNSRegister) && (tmpCmd.type == YARP_TCP) ) { // register name and ip, ask back port (TCP and UDP) YARPNameTCP *tmpRqst = (YARPNameTCP*) (data_buf_); handle_registration(tmpRqst->_name, YARPString(tmpRqst->_ip), YARP_TCP); } else if ( (tmpCmd.cmd == YARPNSRegister) && (tmpCmd.type == YARP_UDP) ) { // register name and ip, ask back multiple ports (UDP) YARPNameUDP *tmpRqst = (YARPNameUDP*) (data_buf_); handle_registration(tmpRqst->_name, YARPString(tmpRqst->_ip), YARP_UDP, tmpRqst->_nPorts); } else if ((tmpCmd.cmd == YARPNSRegister) && (tmpCmd.type == YARP_MCAST)) { YARPNameTCP *tmpRqst = (YARPNameTCP*) (data_buf_); handle_registration_dip(tmpRqst->_name, YARP_MCAST); } else if ((tmpCmd.cmd == YARPNSRegister) && (tmpCmd.type == YARP_QNET)) { YARPNameQnx *tmpRqst = (YARPNameQnx*) (data_buf_); handle_registration_qnx(*tmpRqst); } else if (tmpCmd.cmd == YARPNSNicQuery) { YARPNSNic *tmpRqs = (YARPNSNic*) (data_buf_); handle_nic_query(YARPString(tmpRqs->_ip), YARPString(tmpRqs->_netId)); } else NAME_SERVER_DEBUG(("Sorry: command not recognized\n")); // close new endpoint if (new_stream_.close() == -1) ACE_ERROR ((LM_ERROR, "%p\n", "close")); return 0; } #define MAX_ARG_CT (8) #define MAX_ARG_LEN (256) int YARPNameServer::handle_text_command(const char *command, const char *remote) { char *argv[MAX_ARG_CT]; char buf[MAX_ARG_CT][MAX_ARG_LEN]; int at = 0; int sub_at = 0; int i; for (i=0; i<strlen(command)+1; i++) { if (at<MAX_ARG_CT) { char ch = command[i]; if (ch>=32||ch=='\0') { if (ch==' ') { ch = '\0'; } if (sub_at<MAX_ARG_LEN) { buf[at][sub_at] = ch; sub_at++; } } if (ch == '\0') { if (sub_at>1) { at++; } sub_at = 0; } } } for (i=0; i<MAX_ARG_CT; i++) { argv[i] = buf[i]; buf[i][MAX_ARG_LEN-1] = '\0'; } return handle_text_command(at,argv,remote); } int YARPNameServer::handle_text_command(int argc, char *argv[], const char *remote) { printf("Handling text command"); for (int i=0; i<argc; i++) { printf(" [%s]", argv[i]); } printf("\n"); if (argc>0) { switch (toupper(argv[0][0])) { case 'R': if (argc>=2) { const char *target = argv[1]; const char *proto = NULL; const char *base = NULL; if (argc>=3) { if (strcmp(argv[2],"*")!=0) { proto = argv[2]; } } if (argc>=4) { if (strcmp(argv[3],"*")!=0) { base = argv[3]; } } if (proto==NULL) { proto = "tcp"; } if (base==NULL) { base = remote; } printf("Planning to register %s for %s with protocol %s\n", target, base, proto); if (true) { switch (toupper(proto[0])) { case 'T': handle_registration(target, base, YARP_TCP); break; case 'U': handle_registration(target, base, YARP_UDP); break; case 'M': handle_registration_dip(target, YARP_MCAST); /* if (argv[2][0]!='+') { handle_registration(target, base, YARP_UDP); } { char buf[1000]; sprintf(buf,"%s-mcast",target); handle_registration_dip(buf, YARP_MCAST); } break; */ } } else { handle_registration(argv[1], argv[2], YARP_TCP); } } break; case 'Q': if (argc>=2) { handle_query(argv[1]); } break; case 'D': handle_dump_request(); break; case 'G': break; } } return 0; }
#include "Refureku/Exceptions/OutOfRange.h" using namespace rfk; OutOfRange::OutOfRange(std::string const& errorMessage) noexcept: std::out_of_range(errorMessage) { }
// Copyright (c) 2016-2019 Dr. Colin Hirsch and Daniel Frey // Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/ #include <clocale> #include <cstdio> #include "test.hpp" namespace tao { namespace TAO_PEGTL_NAMESPACE { struct file_content : seq< TAO_PEGTL_STRING( "dummy content" ), eol, discard > { }; struct file_grammar : seq< rep_min_max< 11, 11, file_content >, eof > { }; void unit_test() { const char* const filename = "src/test/pegtl/file_data.txt"; #if defined( _MSC_VER ) std::FILE* stream; ::fopen_s( &stream, filename, "rb" ); // NOLINT #else std::FILE* stream = std::fopen( filename, "rb" ); // NOLINT #endif TAO_PEGTL_TEST_ASSERT( stream != nullptr ); TAO_PEGTL_TEST_ASSERT( parse< file_grammar >( cstream_input<>( stream, 16, filename ) ) ); std::fclose( stream ); // NOLINT(cppcoreguidelines-owning-memory) } } // namespace TAO_PEGTL_NAMESPACE } // namespace tao #include "main.hpp"
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_listen_socket_72b.cpp Label Definition File: CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129.label.xml Template File: sources-sinks-72b.tmpl.cpp */ /* * @description * CWE: 122 Heap Based Buffer Overflow * BadSource: listen_socket Read data using a listen socket (server side) * GoodSource: Larger than zero but less than 10 * Sinks: * GoodSink: Ensure the array index is valid * BadSink : Improperly check the array index by not checking the upper bound * Flow Variant: 72 Data flow: data passed in a vector from one function to another in different source files * * */ #include "std_testcase.h" #include <vector> using namespace std; namespace CWE122_Heap_Based_Buffer_Overflow__cpp_CWE129_listen_socket_72 { #ifndef OMITBAD void badSink(vector<int> dataVector) { /* copy data out of dataVector */ int data = dataVector[2]; { int i; int * buffer = new int[10]; /* initialize buffer */ for (i = 0; i < 10; i++) { buffer[i] = 0; } /* POTENTIAL FLAW: Attempt to write to an index of the array that is above the upper bound * This code does check to see if the array index is negative */ if (data >= 0) { buffer[data] = 1; /* Print the array values */ for(i = 0; i < 10; i++) { printIntLine(buffer[i]); } } else { printLine("ERROR: Array index is negative."); } delete[] buffer; } } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ void goodG2BSink(vector<int> dataVector) { int data = dataVector[2]; { int i; int * buffer = new int[10]; /* initialize buffer */ for (i = 0; i < 10; i++) { buffer[i] = 0; } /* POTENTIAL FLAW: Attempt to write to an index of the array that is above the upper bound * This code does check to see if the array index is negative */ if (data >= 0) { buffer[data] = 1; /* Print the array values */ for(i = 0; i < 10; i++) { printIntLine(buffer[i]); } } else { printLine("ERROR: Array index is negative."); } delete[] buffer; } } /* goodB2G uses the BadSource with the GoodSink */ void goodB2GSink(vector<int> dataVector) { int data = dataVector[2]; { int i; int * buffer = new int[10]; /* initialize buffer */ for (i = 0; i < 10; i++) { buffer[i] = 0; } /* FIX: Properly validate the array index and prevent a buffer overflow */ if (data >= 0 && data < (10)) { buffer[data] = 1; /* Print the array values */ for(i = 0; i < 10; i++) { printIntLine(buffer[i]); } } else { printLine("ERROR: Array index is out-of-bounds"); } delete[] buffer; } } #endif /* OMITGOOD */ } /* close namespace */
#ifndef WIN32 # include <stdexcept> # include <iostream> # include <errno.h> # include <cstring> # include <netinet/in.h> # include <sys/socket.h> # include <netdb.h> # include <netinet/in.h> # include "utils/Logger.hpp" # include "UnixSocket.hpp" using namespace zhttpd::implementation; UnixSocket::UnixSocket(api::socket_t socket) : _socket(socket) { # ifdef SO_NOSIGPIPE12 int set = 1; setsockopt(socket, SOL_SOCKET, SO_NOSIGPIPE, (void *)&set, sizeof(int)); # endif } UnixSocket::UnixSocket(uint32_t ip, uint16_t port) { struct ::protoent *pe; struct sockaddr_in sin; if ((pe = ::getprotobyname("tcp")) == 0) throw std::runtime_error("getprotobyname() failure"); if ((this->_socket = ::socket(PF_INET, SOCK_STREAM, pe->p_proto)) == -1) throw std::runtime_error("socket() failure"); ::memset(&sin, 0, sizeof(struct sockaddr_in)); sin.sin_family = AF_INET; sin.sin_port = htons(port); sin.sin_addr.s_addr = htonl(ip); int yes = 1; if (::setsockopt(this->_socket, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1) throw std::runtime_error("setsockopt() failure"); if (::bind(this->_socket, reinterpret_cast<struct sockaddr*>(&sin), sizeof(sin)) == -1) throw std::runtime_error("bind() failure " + std::string(strerror(errno))); if (::listen(this->_socket, 23) == -1) throw std::runtime_error("listen() failure"); } UnixSocket::~UnixSocket() { this->close(); } void UnixSocket::close() { ::close(this->_socket); } zhttpd::api::size_t UnixSocket::write(char const* data, size_t len) { ssize_t res = ::send(this->_socket, data, len, MSG_NOSIGNAL); if (res <= 0) { throw std::runtime_error("write() failure: " + std::string(strerror(errno))); } return res; } zhttpd::api::size_t UnixSocket::read(char* buf, size_t len) { ssize_t res = ::read(this->_socket, buf, len); if (res <= 0) throw std::runtime_error("read() failure: " + std::string(strerror(errno))); return res; } zhttpd::api::socket_t UnixSocket::accept() { struct ::sockaddr_in csin; unsigned int len = sizeof(csin); api::socket_t socket = ::accept(this->_socket, reinterpret_cast<struct ::sockaddr*>(&csin), &len); if (socket < 0 || socket > 49999) throw std::runtime_error("accept() failure: " + std::string(strerror(errno))); return socket; } #endif // !WIN32
#include "GridServer.h" namespace SmartMet { namespace QueryServer { namespace Corba { static void* GridServer_maintenanceThread(void *arg) { try { GridServer *server = static_cast<GridServer*>(arg); server->run(); return nullptr; } catch (...) { Fmi::Exception exception(BCP,"Operation failed!",nullptr); exception.printError(); exit(-1); } } GridServer::GridServer(const char *address,const char *port) { try { mAddress = address; mPort = port; mContentServiceInterface = nullptr; mDataServiceInterface = nullptr; mQueryServiceInterface = nullptr; int orb_argc = 4; char addr[100]; sprintf(addr,"giop:tcp:%s:%s",address,port); char *orb_argv[] = {const_cast<char*>("-ORBendPoint"),const_cast<char*>(addr),const_cast<char*>("-ORBgiopMaxMsgSize"),const_cast<char*>("500000000")}; try { mOrb = CORBA::ORB_init(orb_argc,orb_argv); CORBA::Object_var obj = mOrb->resolve_initial_references("RootPOA"); mRootPoa = PortableServer::POA::_narrow(obj); mPman = mRootPoa->the_POAManager(); mPman->activate(); // Create a new POA with the persistent lifespan policy. CORBA::PolicyList pl; pl.length(2); pl[0] = mRootPoa->create_lifespan_policy(PortableServer::PERSISTENT); pl[1] = mRootPoa->create_id_assignment_policy(PortableServer::USER_ID); mPoa = mRootPoa->create_POA("my poa", mPman, pl); } catch(CORBA::SystemException& ex) { char msg[1000]; sprintf(msg,"Caught CORBA::System Exception %s",ex._name()); Fmi::Exception exception(BCP,msg); throw exception; } catch(CORBA::Exception& ex) { char msg[1000]; sprintf(msg,"Caught CORBA::Exception %s",ex._name()); Fmi::Exception exception(BCP,msg); throw exception; } catch(omniORB::fatalException& fe) { char msg[1000]; sprintf(msg,"Caught omniORB:fatalException %s (%s:%d)",fe.errmsg(),fe.file(),fe.line()); Fmi::Exception exception(BCP,msg); throw exception; } } catch (...) { throw Fmi::Exception(BCP,"Operation failed!",nullptr); } } GridServer::~GridServer() { try { mOrb->destroy(); } catch (...) { Fmi::Exception exception(BCP,"Destructor failed",nullptr); exception.printError(); } } void GridServer::init(ContentServer::ServiceInterface *contentServiceInterface,DataServer::ServiceInterface *dataServiceInterface,QueryServer::ServiceInterface *queryServiceInterface) { try { mContentServiceInterface = contentServiceInterface; mCorbaContentInterface.init(mContentServiceInterface); mDataServiceInterface = dataServiceInterface; mCorbaDataInterface.init(mDataServiceInterface); mQueryServiceInterface = queryServiceInterface; mCorbaQueryInterface.init(mQueryServiceInterface); try { PortableServer::ObjectId_var content_service_oid = PortableServer::string_to_ObjectId("ContentService"); mPoa->activate_object_with_id(content_service_oid, &mCorbaContentInterface); CORBA::Object_var content_service_obj = ((ContentServer::Corba::ServerInterface*)&mCorbaContentInterface)->_this(); CORBA::String_var content_service_ior(mOrb->object_to_string(content_service_obj)); mCorbaContentInterface._remove_ref(); mContentServiceIor = (char*)content_service_ior; PortableServer::ObjectId_var data_service_oid = PortableServer::string_to_ObjectId("DataService"); mPoa->activate_object_with_id(data_service_oid, &mCorbaDataInterface); CORBA::Object_var data_service_obj = ((DataServer::Corba::ServerInterface*)&mCorbaDataInterface)->_this(); CORBA::String_var data_service_ior(mOrb->object_to_string(data_service_obj)); mCorbaDataInterface._remove_ref(); mDataServiceIor = (char*)data_service_ior; PortableServer::ObjectId_var query_service_oid = PortableServer::string_to_ObjectId("QueryService"); mPoa->activate_object_with_id(query_service_oid, &mCorbaQueryInterface); CORBA::Object_var query_service_obj = ((QueryServer::Corba::ServerInterface*)&mCorbaQueryInterface)->_this(); CORBA::String_var query_service_ior(mOrb->object_to_string(query_service_obj)); mCorbaQueryInterface._remove_ref(); mQueryServiceIor = (char*)query_service_ior; // std::cout << (char*)service_ior << "\n"; } catch(CORBA::SystemException& ex) { char msg[1000]; sprintf(msg,"Caught CORBA::System Exception %s",ex._name()); Fmi::Exception exception(BCP,msg); throw exception; } catch(CORBA::Exception& ex) { char msg[1000]; sprintf(msg,"Caught CORBA::Exception %s",ex._name()); Fmi::Exception exception(BCP,msg); throw exception; } catch(omniORB::fatalException& fe) { char msg[1000]; sprintf(msg,"Caught omniORB:fatalException %s (%s:%d)",fe.errmsg(),fe.file(),fe.line()); Fmi::Exception exception(BCP,msg); throw exception; } } catch (...) { throw Fmi::Exception(BCP,"Operation failed!",nullptr); } } void GridServer::shutdown() { try { mOrb->shutdown(0); } catch (...) { throw Fmi::Exception(BCP,"Operation failed!",nullptr); } } void GridServer::start() { try { pthread_create(&mThread,nullptr,GridServer_maintenanceThread,this); } catch (...) { throw Fmi::Exception(BCP,"Operation failed!",nullptr); } } void GridServer::run() { try { try { mOrb->run(); } catch(CORBA::SystemException& ex) { char msg[1000]; sprintf(msg,"Caught CORBA::System Exception %s",ex._name()); Fmi::Exception exception(BCP,msg); throw exception; } catch(CORBA::Exception& ex) { char msg[1000]; sprintf(msg,"Caught CORBA::Exception %s",ex._name()); Fmi::Exception exception(BCP,msg); throw exception; } catch(omniORB::fatalException& fe) { char msg[1000]; sprintf(msg,"Caught omniORB:fatalException %s (%s:%d)",fe.errmsg(),fe.file(),fe.line()); Fmi::Exception exception(BCP,msg); throw exception; } } catch (...) { throw Fmi::Exception(BCP,"Operation failed!",nullptr); } } std::string GridServer::getContentServiceIor() { try { return mContentServiceIor; } catch (...) { throw Fmi::Exception(BCP,"Operation failed!",nullptr); } } std::string GridServer::getDataServiceIor() { try { return mDataServiceIor; } catch (...) { throw Fmi::Exception(BCP,"Operation failed!",nullptr); } } std::string GridServer::getQueryServiceIor() { try { return mQueryServiceIor; } catch (...) { throw Fmi::Exception(BCP,"Operation failed!",nullptr); } } } } }
#include "pepch.h" #include "Vector4.h" #include "Matrix4.h" namespace PrettyEngine { Vector4::Vector4(float scalar) : x(scalar), y(scalar), z(scalar), w(scalar) { } Vector4::Vector4(float x, float y, float z, float w) : x(x), y(y), z(z), w(w) { } Vector4::Vector4(const Vector3& xyz, float w) : x(xyz.x), y(xyz.y), z(xyz.z), w(w) { } Vector4& Vector4::Add(const Vector4& other) { x += other.x; y += other.y; z += other.z; w += other.w; return *this; } Vector4& Vector4::Subtract(const Vector4& other) { x -= other.x; y -= other.y; z -= other.z; w -= other.w; return *this; } Vector4& Vector4::Multiply(const Vector4& other) { x *= other.x; y *= other.y; z *= other.z; w *= other.w; return *this; } Vector4& Vector4::Divide(const Vector4& other) { x /= other.x; y /= other.y; z /= other.z; w /= other.w; return *this; } Vector4 Vector4::Multiply(const Matrix4& transform) const { return Vector4( transform.rows[0].x * x + transform.rows[0].y * y + transform.rows[0].z * z + transform.rows[0].w * w, transform.rows[1].x * x + transform.rows[1].y * y + transform.rows[1].z * z + transform.rows[1].w * w, transform.rows[2].x * x + transform.rows[2].y * y + transform.rows[2].z * z + transform.rows[2].w * w, transform.rows[3].x * x + transform.rows[3].y * y + transform.rows[3].z * z + transform.rows[3].w * w ); } Vector4 operator+(Vector4 left, const Vector4& right) { return left.Add(right); } Vector4 operator-(Vector4 left, const Vector4& right) { return left.Subtract(right); } Vector4 operator*(Vector4 left, const Vector4& right) { return left.Multiply(right); } Vector4 operator/(Vector4 left, const Vector4& right) { return left.Divide(right); } Vector4& Vector4::operator+=(const Vector4& other) { return Add(other); } Vector4& Vector4::operator-=(const Vector4& other) { return Subtract(other); } Vector4& Vector4::operator*=(const Vector4& other) { return Multiply(other); } Vector4& Vector4::operator/=(const Vector4& other) { return Divide(other); } bool Vector4::operator==(const Vector4& other) { return x == other.x && y == other.y && z == other.z && w == other.w; } bool Vector4::operator!=(const Vector4& other) { return !(*this == other); } float Vector4::DotProduct(const Vector4& other) { return x * other.x + y * other.y + z * other.z + w * other.w; } std::ostream& operator<<(std::ostream& stream, const Vector4& vector) { stream << "Vector4: (" << vector.x << ", " << vector.y << ", " << vector.z << ", " << vector.w << ")"; return stream; } }
// Copyright 2010-2016, 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: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following disclaimer // in the documentation and/or other materials provided with the // distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "gui/character_pad/selection_handler.h" #include <QtGui/QGuiApplication> #include <QtGui/QClipboard> #include <QtWidgets/QApplication> #include <QtWidgets/QMessageBox> #include "base/singleton.h" namespace mozc { namespace gui { namespace { class CopyToClipboardCallback : public SelectionCallbackInterface { public: void Select(const QString &str) { QClipboard *clipboard = QApplication::clipboard(); if (clipboard == NULL) { return; } clipboard->setText(str, QClipboard::Clipboard); clipboard->setText(str, QClipboard::Selection); QMessageBox::information(NULL, QObject::tr("Note"), str + QObject::tr(" is sent to clipboard")); } }; SelectionCallbackInterface *g_selection_callback = NULL; SelectionCallbackInterface *GetSelectionCallback() { if (g_selection_callback == NULL) { return Singleton<CopyToClipboardCallback>::get(); } else { return g_selection_callback; } } } // namespace void SelectionHandler::Select(const QString &str) { GetSelectionCallback()->Select(str); } void SelectionHandler::SetSelectionCallback( SelectionCallbackInterface *callback) { g_selection_callback = callback; } } // namespace gui } // namespace mozc
#include "stdafx.h" #include "Msconfig.h" #include "MSConfigCtl.h" #include "pagebase.h" #include "pagegeneral.h" #include "pagebootini.h" #include "pageini.h" #include "pageservices.h" #include "pagestartup.h" #include <htmlhelp.h> #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CMSConfigSheet IMPLEMENT_DYNAMIC(CMSConfigSheet, CPropertySheet) CMSConfigSheet::CMSConfigSheet(UINT nIDCaption, CWnd* pParentWnd, UINT iSelectPage) : CPropertySheet(nIDCaption, pParentWnd, iSelectPage) { m_iSelectedPage = iSelectPage; m_psh.dwFlags |= PSH_USEPAGELANG; } CMSConfigSheet::CMSConfigSheet(LPCTSTR pszCaption, CWnd* pParentWnd, UINT iSelectPage) : CPropertySheet(pszCaption, pParentWnd, iSelectPage) { m_iSelectedPage = iSelectPage; m_psh.dwFlags |= PSH_USEPAGELANG; } CMSConfigSheet::~CMSConfigSheet() { } BEGIN_MESSAGE_MAP(CMSConfigSheet, CPropertySheet) //{{AFX_MSG_MAP(CMSConfigSheet) ON_WM_HELPINFO() ON_COMMAND(ID_HELP, OnHelp) //}}AFX_MSG_MAP END_MESSAGE_MAP() //----------------------------------------------------------------------------- // Catch the help messages to show the MSConfig help file. //----------------------------------------------------------------------------- BOOL CMSConfigSheet::OnHelpInfo(HELPINFO * pHelpInfo) { TCHAR szHelpPath[MAX_PATH]; // Try to find a localized help file to open (bug 460691). It should be // located in %windir%\help\mui\<LANGID>. if (::ExpandEnvironmentStrings(_T("%SystemRoot%\\help\\mui"), szHelpPath, MAX_PATH)) { CString strLanguageIDPath; LANGID langid = GetUserDefaultUILanguage(); strLanguageIDPath.Format(_T("%s\\%04x\\msconfig.chm"), szHelpPath, langid); if (FileExists(strLanguageIDPath)) { ::HtmlHelp(::GetDesktopWindow(), strLanguageIDPath, HH_DISPLAY_TOPIC, 0); return TRUE; } } if (::ExpandEnvironmentStrings(_T("%windir%\\help\\msconfig.chm"), szHelpPath, MAX_PATH)) ::HtmlHelp(::GetDesktopWindow(), szHelpPath, HH_DISPLAY_TOPIC, 0); return TRUE; } void CMSConfigSheet::OnHelp() { OnHelpInfo(NULL); } //----------------------------------------------------------------------------- // Override this so we can make each page the active page, forcing each one's // OnInitDialog to be called. //----------------------------------------------------------------------------- extern CPageIni * ppageSystemIni; BOOL CMSConfigSheet::OnInitDialog() { CPropertySheet::OnInitDialog(); // Note that LoadIcon does not require a subsequent DestroyIcon in Win32. HICON hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME); SetIcon(hIcon, TRUE); // Set big icon SetIcon(hIcon, FALSE); // Set small icon // Change the caption of the system.ini tab. if (ppageSystemIni) { int nItem = GetPageIndex(ppageSystemIni); if (nItem > 0) { CTabCtrl * pTabs = GetTabControl(); if (pTabs) { CString strCaption; strCaption.LoadString(IDS_SYSTEMINI_CAPTION); TCITEM tci; tci.mask = TCIF_TEXT; tci.pszText = (LPTSTR)(LPCTSTR)strCaption; pTabs->SetItem(nItem, &tci); } } } // Set each page active (before we make the dialog visible) to force // the WM_INITDIALOG message to be sent. for (int iPage = 0; iPage < GetPageCount(); iPage++) SetActivePage(iPage); SetActivePage(m_iSelectedPage); return TRUE; // return TRUE unless you set the focus to a control } //----------------------------------------------------------------------------- // Check to see if the specified file (with path information) exists on // the machine. //----------------------------------------------------------------------------- BOOL FileExists(const CString & strFile) { WIN32_FIND_DATA finddata; HANDLE h = FindFirstFile(strFile, &finddata); if (INVALID_HANDLE_VALUE != h) { FindClose(h); return TRUE; } return FALSE; }
#include <filesystem> #include "compiler.h" int main(int argc, char** argv) { std::filesystem::path exePath = argv[0]; std::filesystem::path shaderPath = exePath.parent_path() / "shaders/rt_bindless.hlsl"; auto compiler = shc::Compiler(); compiler.AddSearchPath(shaderPath.parent_path().string()); shc::DefineList defines; defines.AddDefine("_BUFFER_SIZE", "42"); defines.AddDefine("_RAY_TRACING", ""); auto result = compiler.Compile(shaderPath.string().c_str(), "main", "cs_6_5", defines, shc::Compiler::Target::HLSL); int a = 1; }
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * The name of the copyright holders may not be used to endorse or promote products // derived from this software without specific prior written permission. // // This software is provided by the copyright holders and contributors "as is" and // any express or implied warranties, including, but not limited to, the implied // warranties of merchantability and fitness for a particular purpose are disclaimed. // In no event shall the Intel Corporation or contributors be liable for any direct, // indirect, incidental, special, exemplary, or consequential damages // (including, but not limited to, procurement of substitute goods or services; // loss of use, data, or profits; or business interruption) however caused // and on any theory of liability, whether in contract, strict liability, // or tort (including negligence or otherwise) arising in any way out of // the use of this software, even if advised of the possibility of such damage. // //M*/ #include "test_precomp.hpp" template <class T_in, class T_out> TestIntegralImage<T_in, T_out>::TestIntegralImage(std::string testName_, NCVTestSourceProvider<T_in> &src_, Ncv32u width_, Ncv32u height_) : NCVTestProvider(testName_), src(src_), width(width_), height(height_) { } template <class T_in, class T_out> bool TestIntegralImage<T_in, T_out>::toString(std::ofstream &strOut) { strOut << "sizeof(T_in)=" << sizeof(T_in) << std::endl; strOut << "sizeof(T_out)=" << sizeof(T_out) << std::endl; strOut << "width=" << width << std::endl; strOut << "height=" << height << std::endl; return true; } template <class T_in, class T_out> bool TestIntegralImage<T_in, T_out>::init() { return true; } template <class T_in, class T_out> bool TestIntegralImage<T_in, T_out>::process() { NCVStatus ncvStat; bool rcode = false; Ncv32u widthII = this->width + 1; Ncv32u heightII = this->height + 1; NCVMatrixAlloc<T_in> d_img(*this->allocatorGPU.get(), this->width, this->height); ncvAssertReturn(d_img.isMemAllocated(), false); NCVMatrixAlloc<T_in> h_img(*this->allocatorCPU.get(), this->width, this->height); ncvAssertReturn(h_img.isMemAllocated(), false); NCVMatrixAlloc<T_out> d_imgII(*this->allocatorGPU.get(), widthII, heightII); ncvAssertReturn(d_imgII.isMemAllocated(), false); NCVMatrixAlloc<T_out> h_imgII(*this->allocatorCPU.get(), widthII, heightII); ncvAssertReturn(h_imgII.isMemAllocated(), false); NCVMatrixAlloc<T_out> h_imgII_d(*this->allocatorCPU.get(), widthII, heightII); ncvAssertReturn(h_imgII_d.isMemAllocated(), false); Ncv32u bufSize; if (sizeof(T_in) == sizeof(Ncv8u)) { #ifdef NPP_ENABLE ncvStat = nppiStIntegralGetSize_8u32u(NcvSize32u(this->width, this->height), &bufSize, this->devProp); ncvAssertReturn(NPPST_SUCCESS == ncvStat, false); #endif //NPP_ENABLE } else if (sizeof(T_in) == sizeof(Ncv32f)) { #ifdef NPP_ENABLE ncvStat = nppiStIntegralGetSize_32f32f(NcvSize32u(this->width, this->height), &bufSize, this->devProp); ncvAssertReturn(NPPST_SUCCESS == ncvStat, false); #endif //NPP_ENABLE } else { ncvAssertPrintReturn(false, "Incorrect integral image test instance", false); } NCVVectorAlloc<Ncv8u> d_tmpBuf(*this->allocatorGPU.get(), bufSize); ncvAssertReturn(d_tmpBuf.isMemAllocated(), false); NCV_SET_SKIP_COND(this->allocatorGPU.get()->isCounting()); #ifdef NPP_ENABLE NCV_SKIP_COND_BEGIN ncvAssertReturn(this->src.fill(h_img), false); ncvStat = h_img.copySolid(d_img, 0); ncvAssertReturn(ncvStat == NPPST_SUCCESS, false); if (sizeof(T_in) == sizeof(Ncv8u)) { ncvStat = nppiStIntegral_8u32u_C1R((Ncv8u *)d_img.ptr(), d_img.pitch(), (Ncv32u *)d_imgII.ptr(), d_imgII.pitch(), NcvSize32u(this->width, this->height), d_tmpBuf.ptr(), bufSize, this->devProp); ncvAssertReturn(ncvStat == NPPST_SUCCESS, false); } else if (sizeof(T_in) == sizeof(Ncv32f)) { ncvStat = nppiStIntegral_32f32f_C1R((Ncv32f *)d_img.ptr(), d_img.pitch(), (Ncv32f *)d_imgII.ptr(), d_imgII.pitch(), NcvSize32u(this->width, this->height), d_tmpBuf.ptr(), bufSize, this->devProp); ncvAssertReturn(ncvStat == NPPST_SUCCESS, false); } else { ncvAssertPrintReturn(false, "Incorrect integral image test instance", false); } ncvStat = d_imgII.copySolid(h_imgII_d, 0); ncvAssertReturn(ncvStat == NPPST_SUCCESS, false); if (sizeof(T_in) == sizeof(Ncv8u)) { ncvStat = nppiStIntegral_8u32u_C1R_host((Ncv8u *)h_img.ptr(), h_img.pitch(), (Ncv32u *)h_imgII.ptr(), h_imgII.pitch(), NcvSize32u(this->width, this->height)); ncvAssertReturn(ncvStat == NPPST_SUCCESS, false); } else if (sizeof(T_in) == sizeof(Ncv32f)) { ncvStat = nppiStIntegral_32f32f_C1R_host((Ncv32f *)h_img.ptr(), h_img.pitch(), (Ncv32f *)h_imgII.ptr(), h_imgII.pitch(), NcvSize32u(this->width, this->height)); ncvAssertReturn(ncvStat == NPPST_SUCCESS, false); } else { ncvAssertPrintReturn(false, "Incorrect integral image test instance", false); } NCV_SKIP_COND_END #endif //NPP_ENABLE //bit-to-bit check bool bLoopVirgin = true; NCV_SKIP_COND_BEGIN for (Ncv32u i=0; bLoopVirgin && i < h_img.height() + 1; i++) { for (Ncv32u j=0; bLoopVirgin && j < h_img.width() + 1; j++) { if (sizeof(T_in) == sizeof(Ncv8u)) { if (h_imgII.ptr()[h_imgII.stride()*i+j] != h_imgII_d.ptr()[h_imgII_d.stride()*i+j]) { bLoopVirgin = false; } } else if (sizeof(T_in) == sizeof(Ncv32f)) { if (fabsf((float)h_imgII.ptr()[h_imgII.stride()*i+j] - (float)h_imgII_d.ptr()[h_imgII_d.stride()*i+j]) > 0.01f) { bLoopVirgin = false; } } else { ncvAssertPrintReturn(false, "Incorrect integral image test instance", false); } } } NCV_SKIP_COND_END if (bLoopVirgin) { rcode = true; } return rcode; } template <class T_in, class T_out> bool TestIntegralImage<T_in, T_out>::deinit() { return true; } template class TestIntegralImage<Ncv8u, Ncv32u>; template class TestIntegralImage<Ncv32f, Ncv32f>;
// Copyright 2020 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 <fuchsia/web/cpp/fidl.h> #include "content/public/test/browser_test.h" #include "fuchsia/base/test/frame_test_util.h" #include "fuchsia/base/test/test_navigation_listener.h" #include "fuchsia/engine/browser/context_impl.h" #include "fuchsia/engine/browser/fake_navigation_policy_provider.h" #include "fuchsia/engine/browser/frame_impl.h" #include "fuchsia/engine/browser/navigation_policy_handler.h" #include "fuchsia/engine/test/test_data.h" #include "fuchsia/engine/test/web_engine_browser_test.h" #include "net/test/embedded_test_server/embedded_test_server.h" #include "testing/gtest/include/gtest/gtest.h" namespace { const char kPagePath[] = "/title1.html"; const char kPageTitle[] = "title 1"; } // namespace class NavigationPolicyTest : public cr_fuchsia::WebEngineBrowserTest { public: NavigationPolicyTest() : policy_provider_binding_(&policy_provider_) { cr_fuchsia::WebEngineBrowserTest::set_test_server_root( base::FilePath(cr_fuchsia::kTestServerRoot)); } ~NavigationPolicyTest() override = default; NavigationPolicyTest(const NavigationPolicyTest&) = delete; NavigationPolicyTest& operator=(const NavigationPolicyTest&) = delete; void SetUp() override { cr_fuchsia::WebEngineBrowserTest::SetUp(); } void SetUpOnMainThread() override { frame_ptr_ = cr_fuchsia::WebEngineBrowserTest::CreateFrame(&navigation_listener_); frame_impl_ = context_impl()->GetFrameImplForTest(&frame_ptr_); frame_ptr_->GetNavigationController(navigation_controller_.NewRequest()); ASSERT_TRUE(embedded_test_server()->Start()); // Register a NavigationPolicyProvider to the frame. fuchsia::web::NavigationPolicyProviderParams params; *params.mutable_main_frame_phases() = fuchsia::web::NavigationPhase::START; *params.mutable_subframe_phases() = fuchsia::web::NavigationPhase::REDIRECT; frame_ptr_->SetNavigationPolicyProvider( std::move(params), policy_provider_binding_.NewBinding()); base::RunLoop().RunUntilIdle(); ASSERT_TRUE( frame_impl_->navigation_policy_handler()->is_provider_connected()); } protected: fuchsia::web::FramePtr frame_ptr_; FrameImpl* frame_impl_; fidl::Binding<fuchsia::web::NavigationPolicyProvider> policy_provider_binding_; FakeNavigationPolicyProvider policy_provider_; cr_fuchsia::TestNavigationListener navigation_listener_; fuchsia::web::NavigationControllerPtr navigation_controller_; }; IN_PROC_BROWSER_TEST_F(NavigationPolicyTest, Proceed) { policy_provider_.set_should_abort_navigation(false); GURL page_url(embedded_test_server()->GetURL(std::string(kPagePath))); ASSERT_TRUE(cr_fuchsia::LoadUrlAndExpectResponse( navigation_controller_.get(), fuchsia::web::LoadUrlParams(), page_url.spec())); navigation_listener_.RunUntilUrlAndTitleEquals(page_url, kPageTitle); EXPECT_EQ(page_url.spec(), policy_provider_.requested_navigation()->url()); } IN_PROC_BROWSER_TEST_F(NavigationPolicyTest, Deferred) { policy_provider_.set_should_abort_navigation(true); GURL page_url(embedded_test_server()->GetURL(std::string(kPagePath))); // Make sure the page has had time to load, but has not actually loaded, since // we cannot check for the absence of page data. ASSERT_TRUE(cr_fuchsia::LoadUrlAndExpectResponse( navigation_controller_.get(), fuchsia::web::LoadUrlParams(), page_url.spec())); base::RunLoop run_loop; base::ThreadTaskRunnerHandle::Get()->PostDelayedTask( FROM_HERE, run_loop.QuitClosure(), base::TimeDelta::FromMilliseconds(200)); run_loop.Run(); // Make sure an up to date NavigationState is used. fuchsia::web::NavigationState state; state.set_url(page_url.spec()); navigation_listener_.RunUntilNavigationStateMatches(state); auto* current_state = navigation_listener_.current_state(); EXPECT_TRUE(current_state->has_is_main_document_loaded()); EXPECT_FALSE(current_state->is_main_document_loaded()); EXPECT_EQ(page_url.spec(), policy_provider_.requested_navigation()->url()); }
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/lite/micro/micro_mutable_op_resolver.h" #include "tensorflow/lite/micro/micro_op_resolver.h" #include "tensorflow/lite/micro/testing/micro_test.h" namespace tflite { namespace { void* MockInit(TfLiteContext* context, const char* buffer, size_t length) { // Do nothing. return nullptr; } void MockFree(TfLiteContext* context, void* buffer) { // Do nothing. } TfLiteStatus MockPrepare(TfLiteContext* context, TfLiteNode* node) { return kTfLiteOk; } TfLiteStatus MockInvoke(TfLiteContext* context, TfLiteNode* node) { return kTfLiteOk; } class MockErrorReporter : public ErrorReporter { public: MockErrorReporter() : has_been_called_(false) {} int Report(const char* format, va_list args) override { has_been_called_ = true; return 0; }; bool HasBeenCalled() { return has_been_called_; } void ResetState() { has_been_called_ = false; } private: bool has_been_called_; TF_LITE_REMOVE_VIRTUAL_DELETE }; } // namespace } // namespace tflite TF_LITE_MICRO_TESTS_BEGIN TF_LITE_MICRO_TEST(TestOperations) { using tflite::BuiltinOperator_CONV_2D; using tflite::BuiltinOperator_RELU; using tflite::MicroMutableOpResolver; using tflite::OpResolver; static TfLiteRegistration r = {tflite::MockInit, tflite::MockFree, tflite::MockPrepare, tflite::MockInvoke}; MicroMutableOpResolver<2> micro_op_resolver; TF_LITE_MICRO_EXPECT_EQ( kTfLiteOk, micro_op_resolver.AddBuiltin(BuiltinOperator_CONV_2D, &r)); // Only one AddBuiltin per operator should return kTfLiteOk. TF_LITE_MICRO_EXPECT_EQ( kTfLiteError, micro_op_resolver.AddBuiltin(BuiltinOperator_CONV_2D, &r)); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, micro_op_resolver.AddCustom("mock_custom", &r)); // Only one AddCustom per operator should return kTfLiteOk. TF_LITE_MICRO_EXPECT_EQ(kTfLiteError, micro_op_resolver.AddCustom("mock_custom", &r)); tflite::MicroOpResolver* resolver = &micro_op_resolver; const TfLiteRegistration* registration = resolver->FindOp(BuiltinOperator_CONV_2D); TF_LITE_MICRO_EXPECT_NE(nullptr, registration); TF_LITE_MICRO_EXPECT_EQ(nullptr, registration->init(nullptr, nullptr, 0)); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, registration->prepare(nullptr, nullptr)); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, registration->invoke(nullptr, nullptr)); TF_LITE_MICRO_EXPECT_EQ(2, micro_op_resolver.GetRegistrationLength()); registration = resolver->FindOp(BuiltinOperator_RELU); TF_LITE_MICRO_EXPECT_EQ(nullptr, registration); registration = resolver->FindOp("mock_custom"); TF_LITE_MICRO_EXPECT_NE(nullptr, registration); TF_LITE_MICRO_EXPECT_EQ(nullptr, registration->init(nullptr, nullptr, 0)); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, registration->prepare(nullptr, nullptr)); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, registration->invoke(nullptr, nullptr)); registration = resolver->FindOp("nonexistent_custom"); TF_LITE_MICRO_EXPECT_EQ(nullptr, registration); } TF_LITE_MICRO_TEST(TestErrorReporting) { using tflite::BuiltinOperator_CONV_2D; using tflite::BuiltinOperator_RELU; using tflite::MicroMutableOpResolver; static TfLiteRegistration r = {tflite::MockInit, tflite::MockFree, tflite::MockPrepare, tflite::MockInvoke}; tflite::MockErrorReporter mock_reporter; MicroMutableOpResolver<2> micro_op_resolver(&mock_reporter); TF_LITE_MICRO_EXPECT_EQ(false, mock_reporter.HasBeenCalled()); mock_reporter.ResetState(); TF_LITE_MICRO_EXPECT_EQ( kTfLiteOk, micro_op_resolver.AddBuiltin(BuiltinOperator_CONV_2D, &r)); TF_LITE_MICRO_EXPECT_EQ(false, mock_reporter.HasBeenCalled()); mock_reporter.ResetState(); TF_LITE_MICRO_EXPECT_EQ(kTfLiteOk, micro_op_resolver.AddCustom("mock_custom_0", &r)); TF_LITE_MICRO_EXPECT_EQ(false, mock_reporter.HasBeenCalled()); mock_reporter.ResetState(); // Attempting to Add more operators than the class template parameter for // MicroMutableOpResolver should result in errors. TF_LITE_MICRO_EXPECT_EQ( kTfLiteError, micro_op_resolver.AddBuiltin(BuiltinOperator_RELU, &r)); TF_LITE_MICRO_EXPECT_EQ(true, mock_reporter.HasBeenCalled()); mock_reporter.ResetState(); TF_LITE_MICRO_EXPECT_EQ(kTfLiteError, micro_op_resolver.AddCustom("mock_custom_1", &r)); TF_LITE_MICRO_EXPECT_EQ(true, mock_reporter.HasBeenCalled()); mock_reporter.ResetState(); } TF_LITE_MICRO_TESTS_END
// This file has been generated by Py++. #include "boost/python.hpp" #include "indexing_suite/container_suite.hpp" #include "indexing_suite/vector.hpp" #include "wrap_osg.h" #include "_pair_less__osg_scope_ref_ptr_less__osg_scope_StateSet__greater__comma__osg_scope_Polytope__greater___value_traits.pypp.hpp" #include "vector_less__std_scope_pair_less_osg_scope_ref_ptr_less_osg_scope_StateSet_greater__comma__osg_scope_Polytope_greater___greater_.pypp.hpp" namespace bp = boost::python; void register_vector_less__std_scope_pair_less_osg_scope_ref_ptr_less_osg_scope_StateSet_greater__comma__osg_scope_Polytope_greater___greater__class(){ { //::std::vector< std::pair<osg::ref_ptr<osg::StateSet>, osg::Polytope> > typedef bp::class_< std::vector< std::pair<osg::ref_ptr<osg::StateSet>, osg::Polytope> > > vector_less__std_scope_pair_less_osg_scope_ref_ptr_less_osg_scope_StateSet_greater__comma__osg_scope_Polytope_greater___greater__exposer_t; vector_less__std_scope_pair_less_osg_scope_ref_ptr_less_osg_scope_StateSet_greater__comma__osg_scope_Polytope_greater___greater__exposer_t vector_less__std_scope_pair_less_osg_scope_ref_ptr_less_osg_scope_StateSet_greater__comma__osg_scope_Polytope_greater___greater__exposer = vector_less__std_scope_pair_less_osg_scope_ref_ptr_less_osg_scope_StateSet_greater__comma__osg_scope_Polytope_greater___greater__exposer_t( "vector_less__std_scope_pair_less_osg_scope_ref_ptr_less_osg_scope_StateSet_greater__comma__osg_scope_Polytope_greater___greater_", "\n A standard container which offers fixed time access to\n individual elements in any order.\n\n fngroup sequences\n\n Tparam: _Tp Type of element.\n Tparam: _Alloc Allocator type, defaults to allocator<_Tp>.\n\n Meets the requirements of a <a href=tables.html#65>container</a>, a\n <a href=tables.html#66>reversible container</a>, and a\n <a href=tables.html#67>sequence</a>, including the\n <a href=tables.html#68>optional sequence requirements</a> with the\n %exception of @c push_front and @c pop_front.\n\n In some terminology a %vector can be described as a dynamic\n C-style array, it offers fast and efficient access to individual\n elements in any order and saves the user from worrying about\n memory and size allocation. Subscripting ( @c [] ) access is\n also provided as with C-style arrays.\n" ); bp::scope vector_less__std_scope_pair_less_osg_scope_ref_ptr_less_osg_scope_StateSet_greater__comma__osg_scope_Polytope_greater___greater__scope( vector_less__std_scope_pair_less_osg_scope_ref_ptr_less_osg_scope_StateSet_greater__comma__osg_scope_Polytope_greater___greater__exposer ); vector_less__std_scope_pair_less_osg_scope_ref_ptr_less_osg_scope_StateSet_greater__comma__osg_scope_Polytope_greater___greater__exposer.def( bp::indexing::vector_suite< std::vector< std::pair<osg::ref_ptr<osg::StateSet>, osg::Polytope> > >() ); } }
#ifndef RBX_GC_OBJECT_MARK_HPP #define RBX_GC_OBJECT_MARK_HPP namespace rubinius { class VM; class GarbageCollector; class Object; /** * Implementation in gc.cpp for now.. */ class ObjectMark { public: GarbageCollector* gc; public: ObjectMark(GarbageCollector* gc) : gc(gc) {} VM* state(); Object* call(Object*); void set(Object* target, Object** pos, Object* val); void just_set(Object* target, Object* val); }; } #endif
// // Created by inosphe on 2016. 4. 1.. // #include "FBXLoader.h" #include "FBXScene.h" namespace Resource { namespace FBX{ FBXLoader::FBXLoader(){ } FBXLoader::~FBXLoader() { Clear(); } bool FBXLoader::Init() { m_pManager = FbxManager::Create(); // Create an IOSettings object. IOSROOT is defined in Fbxiosettingspath.h. m_pSetting = FbxIOSettings::Create(m_pManager, IOSROOT ); m_pManager->SetIOSettings(m_pSetting); return true; } void FBXLoader::Clear() { m_pManager->Destroy(); m_pManager = nullptr; m_pSetting->Destroy(); m_pSetting = nullptr; } void FBXLoader::InitSettings(){ #undef IOS_REF #define IOS_REF (*m_pManager->GetIOSettings()) // Set the import states. By default, the import states are always set to // true. The code below shows how to change these states. IOS_REF.SetBoolProp(IMP_FBX_MATERIAL, true); IOS_REF.SetBoolProp(IMP_FBX_TEXTURE, true); IOS_REF.SetBoolProp(IMP_FBX_LINK, true); IOS_REF.SetBoolProp(IMP_FBX_SHAPE, true); IOS_REF.SetBoolProp(IMP_FBX_GOBO, true); IOS_REF.SetBoolProp(IMP_FBX_ANIMATION, true); IOS_REF.SetBoolProp(IMP_FBX_GLOBAL_SETTINGS, true); #undef IOS_REF } std::shared_ptr<FBXScene> FBXLoader::CreateScene(const string& strSceneName){ auto pScene = std::shared_ptr<IResource>(new FBXScene(this, strSceneName.c_str())); return std::static_pointer_cast<FBXScene>(pScene); } std::shared_ptr<IResource> FBXLoader::Load(const string &strFilepath) { int pos = strFilepath.find_last_of('/'); if(pos == string::npos){ pos = -1; } auto pScene = CreateScene(strFilepath.substr(pos+1)); if(pScene->LoadScene(strFilepath)){ return pScene; } else{ throw std::runtime_error("invalid dir(" + strFilepath + ")"); } } } }
#include "engine/buffs_engine/cloak_buff_sub_system.h" #include "core/buffs/cloak_buff.h" #include "core/buffs/i_buff_holder_component.h" #include "core/i_cloak_component.h" #include "../cloak_changed_event.h" namespace engine { CloakBuffSubSystem::CloakBuffSubSystem() : mScene( Scene::Get() ) , mProgramState( core::ProgramState::Get() ) { } void CloakBuffSubSystem::Init() { } void CloakBuffSubSystem::Update( Actor& actor, double DeltaTime ) { Opt<IBuffHolderComponent> buffHolderC = actor.Get<IBuffHolderComponent>(); if ( !buffHolderC.IsValid() ) { return; } Opt<ICloakComponent> cloakC = actor.Get<ICloakComponent>(); if ( !cloakC.IsValid() ) { return; } BuffListFilter<IBuffHolderComponent::All> buffListFilter( buffHolderC->GetBuffList(), CloakBuff::GetType_static() ); if ( buffListFilter.size() == 0 && cloakC->IsActive() ) { cloakC->SetActive( false ); EventServer<engine::CloakChangedEvent>::Get().SendEvent( engine::CloakChangedEvent( actor.GetGUID(), false ) ); } for( BuffListFilter<IBuffHolderComponent::All>::const_iterator cloakBuffIt = buffListFilter.begin(), cloakBuffE = buffListFilter.end(); cloakBuffIt != cloakBuffE; ++cloakBuffIt ) { Opt<CloakBuff> cloakBuff( *cloakBuffIt ); if ( !cloakBuff->IsApplied() ) { cloakC->SetActive( true ); cloakBuff->SetApplied( true ); EventServer<engine::CloakChangedEvent>::Get().SendEvent( engine::CloakChangedEvent( actor.GetGUID(), true ) ); } } } } // namespace engine
/** * Copyright (C) 2017 MongoDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * As a special exception, the copyright holders give permission to link the * code of portions of this program with the OpenSSL library under certain * conditions as described in each individual source file and distribute * linked combinations including the program with the OpenSSL library. You * must comply with the GNU Affero General Public License in all respects * for all of the code used other than as permitted herein. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you do not * wish to do so, delete this exception statement from your version. If you * delete this exception statement from all source files in the program, * then also delete it in the license file. */ #define MONGO_LOG_DEFAULT_COMPONENT ::mongo::logger::LogComponent::kCommand #include "mongo/platform/basic.h" #include "mongo/db/commands/run_aggregate.h" #include <boost/optional.hpp> #include <vector> #include "mongo/db/auth/authorization_session.h" #include "mongo/db/catalog/database.h" #include "mongo/db/curop.h" #include "mongo/db/db_raii.h" #include "mongo/db/exec/pipeline_proxy.h" #include "mongo/db/exec/working_set_common.h" #include "mongo/db/namespace_string.h" #include "mongo/db/pipeline/accumulator.h" #include "mongo/db/pipeline/document.h" #include "mongo/db/pipeline/document_source.h" #include "mongo/db/pipeline/document_source_exchange.h" #include "mongo/db/pipeline/expression.h" #include "mongo/db/pipeline/expression_context.h" #include "mongo/db/pipeline/lite_parsed_pipeline.h" #include "mongo/db/pipeline/mongo_process_interface.h" #include "mongo/db/pipeline/pipeline.h" #include "mongo/db/pipeline/pipeline_d.h" #include "mongo/db/query/collation/collator_factory_interface.h" #include "mongo/db/query/cursor_response.h" #include "mongo/db/query/find_common.h" #include "mongo/db/query/get_executor.h" #include "mongo/db/query/plan_summary_stats.h" #include "mongo/db/read_concern.h" #include "mongo/db/repl/oplog.h" #include "mongo/db/repl/read_concern_args.h" #include "mongo/db/s/sharding_state.h" #include "mongo/db/service_context.h" #include "mongo/db/storage/storage_options.h" #include "mongo/db/transaction_participant.h" #include "mongo/db/views/view.h" #include "mongo/db/views/view_catalog.h" #include "mongo/stdx/memory.h" #include "mongo/util/log.h" #include "mongo/util/scopeguard.h" #include "mongo/util/string_map.h" namespace mongo { using boost::intrusive_ptr; using std::endl; using std::shared_ptr; using std::string; using std::stringstream; using std::unique_ptr; using stdx::make_unique; namespace { /** * Returns true if we need to keep a ClientCursor saved for this pipeline (for future getMore * requests). Otherwise, returns false. The passed 'nsForCursor' is only used to determine the * namespace used in the returned cursor, which will be registered with the global cursor manager, * and thus will be different from that in 'request'. */ bool handleCursorCommand(OperationContext* opCtx, const NamespaceString& nsForCursor, std::vector<ClientCursor*> cursors, const AggregationRequest& request, rpc::ReplyBuilderInterface* result) { invariant(!cursors.empty()); long long batchSize = request.getBatchSize(); if (cursors.size() > 1) { uassert( ErrorCodes::BadValue, "the exchange initial batch size must be zero", batchSize == 0); BSONArrayBuilder cursorsBuilder; for (size_t idx = 0; idx < cursors.size(); ++idx) { invariant(cursors[idx]); BSONObjBuilder cursorResult; appendCursorResponseObject( cursors[idx]->cursorid(), nsForCursor.ns(), BSONArray(), &cursorResult); cursorResult.appendBool("ok", 1); cursorsBuilder.append(cursorResult.obj()); // If a time limit was set on the pipeline, remaining time is "rolled over" to the // cursor (for use by future getmore ops). cursors[idx]->setLeftoverMaxTimeMicros(opCtx->getRemainingMaxTimeMicros()); // Cursor needs to be in a saved state while we yield locks for getmore. State // will be restored in getMore(). cursors[idx]->getExecutor()->saveState(); cursors[idx]->getExecutor()->detachFromOperationContext(); } auto bodyBuilder = result->getBodyBuilder(); bodyBuilder.appendArray("cursors", cursorsBuilder.obj()); return true; } CursorResponseBuilder::Options options; options.isInitialResponse = true; CursorResponseBuilder responseBuilder(result, options); ClientCursor* cursor = cursors[0]; invariant(cursor); BSONObj next; for (int objCount = 0; objCount < batchSize; objCount++) { // The initial getNext() on a PipelineProxyStage may be very expensive so we don't // do it when batchSize is 0 since that indicates a desire for a fast return. PlanExecutor::ExecState state; try { state = cursor->getExecutor()->getNext(&next, nullptr); } catch (const ExceptionFor<ErrorCodes::CloseChangeStream>&) { // This exception is thrown when a $changeStream stage encounters an event // that invalidates the cursor. We should close the cursor and return without // error. cursor = nullptr; break; } if (state == PlanExecutor::IS_EOF) { responseBuilder.setLatestOplogTimestamp( cursor->getExecutor()->getLatestOplogTimestamp()); if (!cursor->isTailable()) { // make it an obvious error to use cursor or executor after this point cursor = nullptr; } break; } if (PlanExecutor::ADVANCED != state) { uassertStatusOK(WorkingSetCommon::getMemberObjectStatus(next).withContext( "PlanExecutor error during aggregation")); } // If adding this object will cause us to exceed the message size limit, then we stash it // for later. if (!FindCommon::haveSpaceForNext(next, objCount, responseBuilder.bytesUsed())) { cursor->getExecutor()->enqueue(next); break; } responseBuilder.setLatestOplogTimestamp(cursor->getExecutor()->getLatestOplogTimestamp()); responseBuilder.append(next); } if (cursor) { // If a time limit was set on the pipeline, remaining time is "rolled over" to the // cursor (for use by future getmore ops). cursor->setLeftoverMaxTimeMicros(opCtx->getRemainingMaxTimeMicros()); CurOp::get(opCtx)->debug().cursorid = cursor->cursorid(); // Cursor needs to be in a saved state while we yield locks for getmore. State // will be restored in getMore(). cursor->getExecutor()->saveState(); cursor->getExecutor()->detachFromOperationContext(); } else { CurOp::get(opCtx)->debug().cursorExhausted = true; } const CursorId cursorId = cursor ? cursor->cursorid() : 0LL; responseBuilder.done(cursorId, nsForCursor.ns()); return static_cast<bool>(cursor); } StatusWith<StringMap<ExpressionContext::ResolvedNamespace>> resolveInvolvedNamespaces( OperationContext* opCtx, const AggregationRequest& request) { const LiteParsedPipeline liteParsedPipeline(request); const auto& pipelineInvolvedNamespaces = liteParsedPipeline.getInvolvedNamespaces(); // If there are no involved namespaces, return before attempting to take any locks. This is // important for collectionless aggregations, which may be expected to run without locking. if (pipelineInvolvedNamespaces.empty()) { return {StringMap<ExpressionContext::ResolvedNamespace>()}; } // We intentionally do not drop and reacquire our DB lock after resolving the view definition in // order to prevent the definition for any view namespaces we've already resolved from changing. // This is necessary to prevent a cycle from being formed among the view definitions cached in // 'resolvedNamespaces' because we won't re-resolve a view namespace we've already encountered. AutoGetDb autoDb(opCtx, request.getNamespaceString().db(), MODE_IS); Database* const db = autoDb.getDb(); ViewCatalog* viewCatalog = db ? db->getViewCatalog() : nullptr; std::deque<NamespaceString> involvedNamespacesQueue(pipelineInvolvedNamespaces.begin(), pipelineInvolvedNamespaces.end()); StringMap<ExpressionContext::ResolvedNamespace> resolvedNamespaces; while (!involvedNamespacesQueue.empty()) { auto involvedNs = std::move(involvedNamespacesQueue.front()); involvedNamespacesQueue.pop_front(); if (resolvedNamespaces.find(involvedNs.coll()) != resolvedNamespaces.end()) { continue; } if (involvedNs.db() != request.getNamespaceString().db()) { // If the involved namespace is not in the same database as the aggregation, it must be // from a $out to a collection in a different database. Since we cannot write to views, // simply assume that the namespace is a collection. resolvedNamespaces[involvedNs.coll()] = {involvedNs, std::vector<BSONObj>{}}; } else if (!db || db->getCollection(opCtx, involvedNs)) { // If the aggregation database exists and 'involvedNs' refers to a collection namespace, // then we resolve it as an empty pipeline in order to read directly from the underlying // collection. If the database doesn't exist, then we still resolve it as an empty // pipeline because 'involvedNs' doesn't refer to a view namespace in our consistent // snapshot of the view catalog. resolvedNamespaces[involvedNs.coll()] = {involvedNs, std::vector<BSONObj>{}}; } else if (viewCatalog->lookup(opCtx, involvedNs.ns())) { // If 'involvedNs' refers to a view namespace, then we resolve its definition. auto resolvedView = viewCatalog->resolveView(opCtx, involvedNs); if (!resolvedView.isOK()) { return {ErrorCodes::FailedToParse, str::stream() << "Failed to resolve view '" << involvedNs.ns() << "': " << resolvedView.getStatus().toString()}; } resolvedNamespaces[involvedNs.coll()] = {resolvedView.getValue().getNamespace(), resolvedView.getValue().getPipeline()}; // We parse the pipeline corresponding to the resolved view in case we must resolve // other view namespaces that are also involved. LiteParsedPipeline resolvedViewLitePipeline( {resolvedView.getValue().getNamespace(), resolvedView.getValue().getPipeline()}); const auto& resolvedViewInvolvedNamespaces = resolvedViewLitePipeline.getInvolvedNamespaces(); involvedNamespacesQueue.insert(involvedNamespacesQueue.end(), resolvedViewInvolvedNamespaces.begin(), resolvedViewInvolvedNamespaces.end()); } else { // 'involvedNs' is neither a view nor a collection, so resolve it as an empty pipeline // to treat it as reading from a non-existent collection. resolvedNamespaces[involvedNs.coll()] = {involvedNs, std::vector<BSONObj>{}}; } } return resolvedNamespaces; } /** * Returns Status::OK if each view namespace in 'pipeline' has a default collator equivalent to * 'collator'. Otherwise, returns ErrorCodes::OptionNotSupportedOnView. */ Status collatorCompatibleWithPipeline(OperationContext* opCtx, Database* db, const CollatorInterface* collator, const Pipeline* pipeline) { if (!db || !pipeline) { return Status::OK(); } for (auto&& potentialViewNs : pipeline->getInvolvedCollections()) { if (db->getCollection(opCtx, potentialViewNs)) { continue; } auto view = db->getViewCatalog()->lookup(opCtx, potentialViewNs.ns()); if (!view) { continue; } if (!CollatorInterface::collatorsMatch(view->defaultCollator(), collator)) { return {ErrorCodes::OptionNotSupportedOnView, str::stream() << "Cannot override default collation of view " << potentialViewNs.ns()}; } } return Status::OK(); } /** * Resolves the collator to either the user-specified collation or, if none was specified, to the * collection-default collation. */ std::unique_ptr<CollatorInterface> resolveCollator(OperationContext* opCtx, const AggregationRequest& request, const Collection* collection) { if (!request.getCollation().isEmpty()) { return uassertStatusOK(CollatorFactoryInterface::get(opCtx->getServiceContext()) ->makeFromBSON(request.getCollation())); } return (collection && collection->getDefaultCollator() ? collection->getDefaultCollator()->clone() : nullptr); } boost::intrusive_ptr<ExpressionContext> makeExpressionContext( OperationContext* opCtx, const AggregationRequest& request, std::unique_ptr<CollatorInterface> collator, boost::optional<UUID> uuid) { boost::intrusive_ptr<ExpressionContext> expCtx = new ExpressionContext(opCtx, request, std::move(collator), MongoProcessInterface::create(opCtx), uassertStatusOK(resolveInvolvedNamespaces(opCtx, request)), uuid); expCtx->tempDir = storageGlobalParams.dbpath + "/_tmp"; auto txnParticipant = TransactionParticipant::get(opCtx); expCtx->inMultiDocumentTransaction = txnParticipant && txnParticipant->inMultiDocumentTransaction(); return expCtx; } } // namespace Status runAggregate(OperationContext* opCtx, const NamespaceString& origNss, const AggregationRequest& request, const BSONObj& cmdObj, rpc::ReplyBuilderInterface* result) { // For operations on views, this will be the underlying namespace. NamespaceString nss = request.getNamespaceString(); // The collation to use for this aggregation. boost::optional to distinguish between the case // where the collation has not yet been resolved, and where it has been resolved to nullptr. boost::optional<std::unique_ptr<CollatorInterface>> collatorToUse; // The UUID of the collection for the execution namespace of this aggregation. For change // streams, this will be the UUID of the original namespace instead of the oplog namespace. boost::optional<UUID> uuid; std::vector<unique_ptr<PlanExecutor, PlanExecutor::Deleter>> execs; boost::intrusive_ptr<ExpressionContext> expCtx; auto curOp = CurOp::get(opCtx); { const LiteParsedPipeline liteParsedPipeline(request); try { // Check whether the parsed pipeline supports the given read concern. liteParsedPipeline.assertSupportsReadConcern(opCtx, request.getExplain()); } catch (const DBException& ex) { auto txnParticipant = TransactionParticipant::get(opCtx); // If we are in a multi-document transaction, we intercept the 'readConcern' // assertion in order to provide a more descriptive error message and code. if (txnParticipant && txnParticipant->inMultiDocumentTransaction()) { return {ErrorCodes::OperationNotSupportedInTransaction, ex.toStatus("Operation not permitted in transaction").reason()}; } return ex.toStatus(); } if (liteParsedPipeline.hasChangeStream()) { nss = NamespaceString::kRsOplogNamespace; // If the read concern is not specified, upgrade to 'majority' and wait to make sure we // have a snapshot available. auto& readConcernArgs = repl::ReadConcernArgs::get(opCtx); if (!readConcernArgs.hasLevel()) { readConcernArgs = repl::ReadConcernArgs(repl::ReadConcernLevel::kMajorityReadConcern); uassertStatusOK(waitForReadConcern(opCtx, readConcernArgs, true)); } if (!origNss.isCollectionlessAggregateNS()) { // AutoGetCollectionForReadCommand will raise an error if 'origNss' is a view. AutoGetCollectionForReadCommand origNssCtx(opCtx, origNss); // Resolve the collator to either the user-specified collation or the default // collation of the collection on which $changeStream was invoked, so that we do not // end up resolving the collation on the oplog. invariant(!collatorToUse); Collection* origColl = origNssCtx.getCollection(); collatorToUse.emplace(resolveCollator(opCtx, request, origColl)); // Get the collection UUID to be set on the expression context. uuid = origColl ? origColl->uuid() : boost::none; } } const auto& pipelineInvolvedNamespaces = liteParsedPipeline.getInvolvedNamespaces(); // If emplaced, AutoGetCollectionForReadCommand will throw if the sharding version for this // connection is out of date. If the namespace is a view, the lock will be released before // re-running the expanded aggregation. boost::optional<AutoGetCollectionForReadCommand> ctx; // If this is a collectionless aggregation, we won't create 'ctx' but will still need an // AutoStatsTracker to record CurOp and Top entries. boost::optional<AutoStatsTracker> statsTracker; // If this is a collectionless aggregation with no foreign namespaces, we don't want to // acquire any locks. Otherwise, lock the collection or view. if (nss.isCollectionlessAggregateNS() && pipelineInvolvedNamespaces.empty()) { statsTracker.emplace(opCtx, nss, Top::LockType::NotLocked, 0); } else { ctx.emplace(opCtx, nss, AutoGetCollection::ViewMode::kViewsPermitted); } Collection* collection = ctx ? ctx->getCollection() : nullptr; // For change streams, the UUID will already have been set for the original namespace. if (!liteParsedPipeline.hasChangeStream()) { uuid = collection ? collection->uuid() : boost::none; } // The collator may already have been set if this is a $changeStream pipeline. If not, // resolve the collator to either the user-specified collation or the collection default. if (!collatorToUse) { collatorToUse.emplace(resolveCollator(opCtx, request, collection)); } // If this is a view, resolve it by finding the underlying collection and stitching view // pipelines and this request's pipeline together. We then release our locks before // recursively calling runAggregate(), which will re-acquire locks on the underlying // collection. (The lock must be released because recursively acquiring locks on the // database will prohibit yielding.) if (ctx && ctx->getView() && !liteParsedPipeline.startsWithCollStats()) { invariant(nss != NamespaceString::kRsOplogNamespace); invariant(!nss.isCollectionlessAggregateNS()); // Check that the default collation of 'view' is compatible with the operation's // collation. The check is skipped if the request did not specify a collation. if (!request.getCollation().isEmpty()) { invariant(collatorToUse); // Should already be resolved at this point. if (!CollatorInterface::collatorsMatch(ctx->getView()->defaultCollator(), collatorToUse->get())) { return {ErrorCodes::OptionNotSupportedOnView, "Cannot override a view's default collation"}; } } auto resolvedView = uassertStatusOK(ctx->getDb()->getViewCatalog()->resolveView(opCtx, nss)); uassert(std::move(resolvedView), "On sharded systems, resolved views must be executed by mongos", !ShardingState::get(opCtx)->enabled()); // With the view & collation resolved, we can relinquish locks. ctx.reset(); // Parse the resolved view into a new aggregation request. auto newRequest = resolvedView.asExpandedViewAggregation(request); auto newCmd = newRequest.serializeToCommandObj().toBson(); auto status = runAggregate(opCtx, origNss, newRequest, newCmd, result); { // Set the namespace of the curop back to the view namespace so ctx records // stats on this view namespace on destruction. stdx::lock_guard<Client> lk(*opCtx->getClient()); curOp->setNS_inlock(nss.ns()); } return status; } invariant(collatorToUse); expCtx = makeExpressionContext(opCtx, request, std::move(*collatorToUse), uuid); auto pipeline = uassertStatusOK(Pipeline::parse(request.getPipeline(), expCtx)); // Check that the view's collation matches the collation of any views involved in the // pipeline. if (!pipelineInvolvedNamespaces.empty()) { invariant(ctx); auto pipelineCollationStatus = collatorCompatibleWithPipeline( opCtx, ctx->getDb(), expCtx->getCollator(), pipeline.get()); if (!pipelineCollationStatus.isOK()) { return pipelineCollationStatus; } } pipeline->optimizePipeline(); // Prepare a PlanExecutor to provide input into the pipeline, if needed. if (liteParsedPipeline.hasChangeStream()) { // If we are using a change stream, the cursor stage should have a simple collation, // regardless of what the user's collation was. std::unique_ptr<CollatorInterface> collatorForCursor = nullptr; auto collatorStash = expCtx->temporarilyChangeCollator(std::move(collatorForCursor)); PipelineD::prepareCursorSource(collection, nss, &request, pipeline.get()); } else { PipelineD::prepareCursorSource(collection, nss, &request, pipeline.get()); } // Optimize again, since there may be additional optimizations that can be done after adding // the initial cursor stage. Note this has to be done outside the above blocks to ensure // this process uses the correct collation if it does any string comparisons. pipeline->optimizePipeline(); std::vector<std::unique_ptr<Pipeline, PipelineDeleter>> pipelines; if (request.getExchangeSpec() && !expCtx->explain) { boost::intrusive_ptr<Exchange> exchange = new Exchange(request.getExchangeSpec().get(), std::move(pipeline)); for (size_t idx = 0; idx < exchange->getConsumers(); ++idx) { // For every new pipeline we have create a new ExpressionContext as the context // cannot be shared between threads. There is no synchronization for pieces of the // execution machinery above the Exchange, so nothing above the Exchange can be // shared between different exchange-producer cursors. expCtx = makeExpressionContext( opCtx, request, expCtx->getCollator() ? expCtx->getCollator()->clone() : nullptr, uuid); // Create a new pipeline for the consumer consisting of a single // DocumentSourceExchange. boost::intrusive_ptr<DocumentSource> consumer = new DocumentSourceExchange(expCtx, exchange, idx); pipelines.emplace_back(uassertStatusOK(Pipeline::create({consumer}, expCtx))); } } else { pipelines.emplace_back(std::move(pipeline)); } for (size_t idx = 0; idx < pipelines.size(); ++idx) { // Transfer ownership of the Pipeline to the PipelineProxyStage. auto ws = make_unique<WorkingSet>(); auto proxy = make_unique<PipelineProxyStage>(opCtx, std::move(pipelines[idx]), ws.get()); // This PlanExecutor will simply forward requests to the Pipeline, so does not need to // yield or to be registered with any collection's CursorManager to receive // invalidations. The Pipeline may contain PlanExecutors which *are* yielding // PlanExecutors and which *are* registered with their respective collection's // CursorManager auto statusWithPlanExecutor = PlanExecutor::make( opCtx, std::move(ws), std::move(proxy), nss, PlanExecutor::NO_YIELD); invariant(statusWithPlanExecutor.isOK()); execs.emplace_back(std::move(statusWithPlanExecutor.getValue())); } { auto planSummary = Explain::getPlanSummary(execs[0].get()); stdx::lock_guard<Client> lk(*opCtx->getClient()); curOp->setPlanSummary_inlock(std::move(planSummary)); } } // Having released the collection lock, we can now create a cursor that returns results from the // pipeline. This cursor owns no collection state, and thus we register it with the global // cursor manager. The global cursor manager does not deliver invalidations or kill // notifications; the underlying PlanExecutor(s) used by the pipeline will be receiving // invalidations and kill notifications themselves, not the cursor we create here. std::vector<ClientCursorPin> pins; std::vector<ClientCursor*> cursors; ScopeGuard cursorFreer = MakeGuard( [](std::vector<ClientCursorPin>* pins) { for (auto& p : *pins) { p.deleteUnderlying(); } }, &pins); for (size_t idx = 0; idx < execs.size(); ++idx) { ClientCursorParams cursorParams( std::move(execs[idx]), origNss, AuthorizationSession::get(opCtx->getClient())->getAuthenticatedUserNames(), repl::ReadConcernArgs::get(opCtx).getLevel(), cmdObj); if (expCtx->tailableMode == TailableModeEnum::kTailable) { cursorParams.setTailable(true); } else if (expCtx->tailableMode == TailableModeEnum::kTailableAndAwaitData) { cursorParams.setTailable(true); cursorParams.setAwaitData(true); } auto pin = CursorManager::getGlobalCursorManager()->registerCursor(opCtx, std::move(cursorParams)); cursors.emplace_back(pin.getCursor()); pins.emplace_back(std::move(pin)); } // If both explain and cursor are specified, explain wins. if (expCtx->explain) { auto bodyBuilder = result->getBodyBuilder(); Explain::explainPipelineExecutor( pins[0].getCursor()->getExecutor(), *(expCtx->explain), &bodyBuilder); } else { // Cursor must be specified, if explain is not. const bool keepCursor = handleCursorCommand(opCtx, origNss, std::move(cursors), request, result); if (keepCursor) { cursorFreer.Dismiss(); } } if (!expCtx->explain) { PlanSummaryStats stats; Explain::getSummaryStats(*(pins[0].getCursor()->getExecutor()), &stats); curOp->debug().setPlanSummaryMetrics(stats); curOp->debug().nreturned = stats.nReturned; } // Any code that needs the cursor pinned must be inside the try block, above. return Status::OK(); } } // namespace mongo
// Copyright (c) 2015 Hartmut Kaiser // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) #include <hpx/hpx_init.hpp> #include <hpx/hpx.hpp> #include <hpx/include/parallel_set_operations.hpp> #include <hpx/util/lightweight_test.hpp> #include <boost/range/functions.hpp> #include "test_utils.hpp" /////////////////////////////////////////////////////////////////////////////// template <typename ExPolicy, typename IteratorTag> void test_set_union1(ExPolicy const& policy, IteratorTag) { BOOST_STATIC_ASSERT(hpx::parallel::is_execution_policy<ExPolicy>::value); typedef std::vector<std::size_t>::iterator base_iterator; typedef test::test_iterator<base_iterator, IteratorTag> iterator; std::vector<std::size_t> c1 = test::random_fill(10007); std::vector<std::size_t> c2 = test::random_fill(c1.size()); std::sort(boost::begin(c1), boost::end(c1)); std::sort(boost::begin(c2), boost::end(c2)); std::vector<std::size_t> c3(2*c1.size()), c4(2*c1.size()); hpx::parallel::set_union(policy, iterator(boost::begin(c1)), iterator(boost::end(c1)), boost::begin(c2), boost::end(c2), boost::begin(c3)); std::set_union(boost::begin(c1), boost::end(c1), boost::begin(c2), boost::end(c2), boost::begin(c4)); // verify values HPX_TEST(std::equal(boost::begin(c3), boost::end(c3), boost::begin(c4))); } template <typename ExPolicy, typename IteratorTag> void test_set_union1_async(ExPolicy const& p, IteratorTag) { typedef std::vector<std::size_t>::iterator base_iterator; typedef test::test_iterator<base_iterator, IteratorTag> iterator; std::vector<std::size_t> c1 = test::random_fill(10007); std::vector<std::size_t> c2 = test::random_fill(c1.size()); std::sort(boost::begin(c1), boost::end(c1)); std::sort(boost::begin(c2), boost::end(c2)); std::vector<std::size_t> c3(2*c1.size()), c4(2*c1.size()); hpx::future<void> result = hpx::parallel::set_union(p, iterator(boost::begin(c1)), iterator(boost::end(c1)), boost::begin(c2), boost::end(c2), boost::begin(c3)); result.wait(); std::set_union(boost::begin(c1), boost::end(c1), boost::begin(c2), boost::end(c2), boost::begin(c4)); // verify values HPX_TEST(std::equal(boost::begin(c3), boost::end(c3), boost::begin(c4))); } template <typename IteratorTag> void test_set_union1() { using namespace hpx::parallel; test_set_union1(seq, IteratorTag()); test_set_union1(par, IteratorTag()); test_set_union1(par_vec, IteratorTag()); test_set_union1_async(seq(task), IteratorTag()); test_set_union1_async(par(task), IteratorTag()); test_set_union1(execution_policy(seq), IteratorTag()); test_set_union1(execution_policy(par), IteratorTag()); test_set_union1(execution_policy(par_vec), IteratorTag()); test_set_union1(execution_policy(seq(task)), IteratorTag()); test_set_union1(execution_policy(par(task)), IteratorTag()); } void set_union_test1() { test_set_union1<std::random_access_iterator_tag>(); test_set_union1<std::forward_iterator_tag>(); test_set_union1<std::input_iterator_tag>(); } /////////////////////////////////////////////////////////////////////////////// template <typename ExPolicy, typename IteratorTag> void test_set_union2(ExPolicy const& policy, IteratorTag) { BOOST_STATIC_ASSERT(hpx::parallel::is_execution_policy<ExPolicy>::value); typedef std::vector<std::size_t>::iterator base_iterator; typedef test::test_iterator<base_iterator, IteratorTag> iterator; std::vector<std::size_t> c1 = test::random_fill(10007); std::vector<std::size_t> c2 = test::random_fill(c1.size()); auto comp = [](std::size_t l, std::size_t r) { return l > r; }; std::sort(boost::begin(c1), boost::end(c1), comp); std::sort(boost::begin(c2), boost::end(c2), comp); std::vector<std::size_t> c3(2*c1.size()), c4(2*c1.size()); hpx::parallel::set_union(policy, iterator(boost::begin(c1)), iterator(boost::end(c1)), boost::begin(c2), boost::end(c2), boost::begin(c3), comp); std::set_union(boost::begin(c1), boost::end(c1), boost::begin(c2), boost::end(c2), boost::begin(c4), comp); // verify values HPX_TEST(std::equal(boost::begin(c3), boost::end(c3), boost::begin(c4))); } template <typename ExPolicy, typename IteratorTag> void test_set_union2_async(ExPolicy const& p, IteratorTag) { BOOST_STATIC_ASSERT(hpx::parallel::is_execution_policy<ExPolicy>::value); typedef std::vector<std::size_t>::iterator base_iterator; typedef test::test_iterator<base_iterator, IteratorTag> iterator; std::vector<std::size_t> c1 = test::random_fill(10007); std::vector<std::size_t> c2 = test::random_fill(c1.size()); auto comp = [](std::size_t l, std::size_t r) { return l > r; }; std::sort(boost::begin(c1), boost::end(c1), comp); std::sort(boost::begin(c2), boost::end(c2), comp); std::vector<std::size_t> c3(2*c1.size()), c4(2*c1.size()); hpx::future<void> result = hpx::parallel::set_union(p, iterator(boost::begin(c1)), iterator(boost::end(c1)), boost::begin(c2), boost::end(c2), boost::begin(c3), comp); result.wait(); std::set_union(boost::begin(c1), boost::end(c1), boost::begin(c2), boost::end(c2), boost::begin(c4), comp); // verify values HPX_TEST(std::equal(boost::begin(c3), boost::end(c3), boost::begin(c4))); } template <typename IteratorTag> void test_set_union2() { using namespace hpx::parallel; test_set_union2(seq, IteratorTag()); test_set_union2(par, IteratorTag()); test_set_union2(par_vec, IteratorTag()); test_set_union2_async(seq(task), IteratorTag()); test_set_union2_async(par(task), IteratorTag()); test_set_union2(execution_policy(seq), IteratorTag()); test_set_union2(execution_policy(par), IteratorTag()); test_set_union2(execution_policy(par_vec), IteratorTag()); test_set_union2(execution_policy(seq(task)), IteratorTag()); test_set_union2(execution_policy(par(task)), IteratorTag()); } void set_union_test2() { test_set_union2<std::random_access_iterator_tag>(); test_set_union2<std::forward_iterator_tag>(); test_set_union2<std::input_iterator_tag>(); } /////////////////////////////////////////////////////////////////////////////// template <typename ExPolicy, typename IteratorTag> void test_set_union_exception(ExPolicy const& policy, IteratorTag) { BOOST_STATIC_ASSERT(hpx::parallel::is_execution_policy<ExPolicy>::value); typedef std::vector<std::size_t>::iterator base_iterator; typedef test::decorated_iterator<base_iterator, IteratorTag> decorated_iterator; std::vector<std::size_t> c1 = test::random_fill(10007); std::vector<std::size_t> c2 = test::random_fill(c1.size()); std::sort(boost::begin(c1), boost::end(c1)); std::sort(boost::begin(c2), boost::end(c2)); std::vector<std::size_t> c3(2*c1.size()); bool caught_exception = false; try { hpx::parallel::set_union(policy, decorated_iterator( boost::begin(c1), [](){ throw std::runtime_error("test"); }), decorated_iterator(boost::end(c1)), boost::begin(c2), boost::end(c2), boost::begin(c3)); HPX_TEST(false); } catch(hpx::exception_list const& e) { caught_exception = true; test::test_num_exceptions<ExPolicy, IteratorTag>::call(policy, e); } catch(...) { HPX_TEST(false); } HPX_TEST(caught_exception); } template <typename ExPolicy, typename IteratorTag> void test_set_union_exception_async(ExPolicy const& p, IteratorTag) { BOOST_STATIC_ASSERT(hpx::parallel::is_execution_policy<ExPolicy>::value); typedef std::vector<std::size_t>::iterator base_iterator; typedef test::decorated_iterator<base_iterator, IteratorTag> decorated_iterator; std::vector<std::size_t> c1 = test::random_fill(10007); std::vector<std::size_t> c2 = test::random_fill(c1.size()); std::sort(boost::begin(c1), boost::end(c1)); std::sort(boost::begin(c2), boost::end(c2)); std::vector<std::size_t> c3(2*c1.size()); bool caught_exception = false; bool returned_from_algorithm = false; try { hpx::future<void> f = hpx::parallel::set_union(p, decorated_iterator( boost::begin(c1), [](){ throw std::runtime_error("test"); }), decorated_iterator(boost::end(c1)), boost::begin(c2), boost::end(c2), boost::begin(c3)); returned_from_algorithm = true; f.get(); HPX_TEST(false); } catch(hpx::exception_list const& e) { caught_exception = true; test::test_num_exceptions<ExPolicy, IteratorTag>::call(p, e); } catch(...) { HPX_TEST(false); } HPX_TEST(caught_exception); HPX_TEST(returned_from_algorithm); } template <typename IteratorTag> void test_set_union_exception() { using namespace hpx::parallel; // If the execution policy object is of type vector_execution_policy, // std::terminate shall be called. therefore we do not test exceptions // with a vector execution policy test_set_union_exception(seq, IteratorTag()); test_set_union_exception(par, IteratorTag()); test_set_union_exception_async(seq(task), IteratorTag()); test_set_union_exception_async(par(task), IteratorTag()); test_set_union_exception(execution_policy(seq), IteratorTag()); test_set_union_exception(execution_policy(par), IteratorTag()); test_set_union_exception(execution_policy(seq(task)), IteratorTag()); test_set_union_exception(execution_policy(par(task)), IteratorTag()); } void set_union_exception_test() { test_set_union_exception<std::random_access_iterator_tag>(); test_set_union_exception<std::forward_iterator_tag>(); test_set_union_exception<std::input_iterator_tag>(); } /////////////////////////////////////////////////////////////////////////////// template <typename ExPolicy, typename IteratorTag> void test_set_union_bad_alloc(ExPolicy const& policy, IteratorTag) { BOOST_STATIC_ASSERT(hpx::parallel::is_execution_policy<ExPolicy>::value); typedef std::vector<std::size_t>::iterator base_iterator; typedef test::decorated_iterator<base_iterator, IteratorTag> decorated_iterator; std::vector<std::size_t> c1 = test::random_fill(10007); std::vector<std::size_t> c2 = test::random_fill(c1.size()); std::sort(boost::begin(c1), boost::end(c1)); std::sort(boost::begin(c2), boost::end(c2)); std::vector<std::size_t> c3(2*c1.size()); bool caught_bad_alloc = false; try { hpx::parallel::set_union(policy, decorated_iterator( boost::begin(c1), [](){ throw std::bad_alloc(); }), decorated_iterator(boost::end(c1)), boost::begin(c2), boost::end(c2), boost::begin(c3)); HPX_TEST(false); } catch(std::bad_alloc const&) { caught_bad_alloc = true; } catch(...) { HPX_TEST(false); } HPX_TEST(caught_bad_alloc); } template <typename ExPolicy, typename IteratorTag> void test_set_union_bad_alloc_async(ExPolicy const& p, IteratorTag) { BOOST_STATIC_ASSERT(hpx::parallel::is_execution_policy<ExPolicy>::value); typedef std::vector<std::size_t>::iterator base_iterator; typedef test::decorated_iterator<base_iterator, IteratorTag> decorated_iterator; std::vector<std::size_t> c1 = test::random_fill(10007); std::vector<std::size_t> c2 = test::random_fill(c1.size()); std::sort(boost::begin(c1), boost::end(c1)); std::sort(boost::begin(c2), boost::end(c2)); std::vector<std::size_t> c3(2*c1.size()); bool caught_bad_alloc = false; bool returned_from_algorithm = false; try { hpx::future<void> f = hpx::parallel::set_union(p, decorated_iterator( boost::begin(c1), [](){ throw std::bad_alloc(); }), decorated_iterator(boost::end(c1)), boost::begin(c2), boost::end(c2), boost::begin(c3)); returned_from_algorithm = true; f.get(); HPX_TEST(false); } catch(std::bad_alloc const&) { caught_bad_alloc = true; } catch(...) { HPX_TEST(false); } HPX_TEST(caught_bad_alloc); HPX_TEST(returned_from_algorithm); } template <typename IteratorTag> void test_set_union_bad_alloc() { using namespace hpx::parallel; // If the execution policy object is of type vector_execution_policy, // std::terminate shall be called. therefore we do not test exceptions // with a vector execution policy test_set_union_bad_alloc(seq, IteratorTag()); test_set_union_bad_alloc(par, IteratorTag()); test_set_union_bad_alloc_async(seq(task), IteratorTag()); test_set_union_bad_alloc_async(par(task), IteratorTag()); test_set_union_bad_alloc(execution_policy(seq), IteratorTag()); test_set_union_bad_alloc(execution_policy(par), IteratorTag()); test_set_union_bad_alloc(execution_policy(seq(task)), IteratorTag()); test_set_union_bad_alloc(execution_policy(par(task)), IteratorTag()); } void set_union_bad_alloc_test() { test_set_union_bad_alloc<std::random_access_iterator_tag>(); test_set_union_bad_alloc<std::forward_iterator_tag>(); test_set_union_bad_alloc<std::input_iterator_tag>(); } /////////////////////////////////////////////////////////////////////////////// int hpx_main(boost::program_options::variables_map& vm) { unsigned int seed = (unsigned int)std::time(0); if (vm.count("seed")) seed = vm["seed"].as<unsigned int>(); std::cout << "using seed: " << seed << std::endl; std::srand(seed); set_union_test1(); set_union_test2(); set_union_exception_test(); set_union_bad_alloc_test(); return hpx::finalize(); } int main(int argc, char* argv[]) { // add command line option which controls the random number generator seed using namespace boost::program_options; options_description desc_commandline( "Usage: " HPX_APPLICATION_STRING " [options]"); desc_commandline.add_options() ("seed,s", value<unsigned int>(), "the random number generator seed to use for this run") ; // By default this test should run on all available cores std::vector<std::string> cfg; cfg.push_back("hpx.os_threads=" + boost::lexical_cast<std::string>(hpx::threads::hardware_concurrency())); // Initialize and run HPX HPX_TEST_EQ_MSG(hpx::init(desc_commandline, argc, argv, cfg), 0, "HPX main exited with non-zero status"); return hpx::util::report_errors(); }
/* * Copyright (c) 2020, Andreas Kling <kling@serenityos.org> * Copyright (c) 2020-2022, Linus Groh <linusg@serenityos.org> * * SPDX-License-Identifier: BSD-2-Clause */ #include <AK/Function.h> #include <LibJS/Runtime/AbstractOperations.h> #include <LibJS/Runtime/Array.h> #include <LibJS/Runtime/ArrayConstructor.h> #include <LibJS/Runtime/Error.h> #include <LibJS/Runtime/GlobalObject.h> #include <LibJS/Runtime/IteratorOperations.h> #include <LibJS/Runtime/Shape.h> namespace JS { ArrayConstructor::ArrayConstructor(GlobalObject& global_object) : NativeFunction(vm().names.Array.as_string(), *global_object.function_prototype()) { } ArrayConstructor::~ArrayConstructor() { } void ArrayConstructor::initialize(GlobalObject& global_object) { auto& vm = this->vm(); NativeFunction::initialize(global_object); // 23.1.2.4 Array.prototype, https://tc39.es/ecma262/#sec-array.prototype define_direct_property(vm.names.prototype, global_object.array_prototype(), 0); u8 attr = Attribute::Writable | Attribute::Configurable; define_native_function(vm.names.from, from, 1, attr); define_native_function(vm.names.isArray, is_array, 1, attr); define_native_function(vm.names.of, of, 0, attr); // 23.1.2.5 get Array [ @@species ], https://tc39.es/ecma262/#sec-get-array-@@species define_native_accessor(*vm.well_known_symbol_species(), symbol_species_getter, {}, Attribute::Configurable); define_direct_property(vm.names.length, Value(1), Attribute::Configurable); } // 23.1.1.1 Array ( ...values ), https://tc39.es/ecma262/#sec-array ThrowCompletionOr<Value> ArrayConstructor::call() { return TRY(construct(*this)); } // 23.1.1.1 Array ( ...values ), https://tc39.es/ecma262/#sec-array ThrowCompletionOr<Object*> ArrayConstructor::construct(FunctionObject& new_target) { auto& vm = this->vm(); auto* proto = TRY(get_prototype_from_constructor(global_object(), new_target, &GlobalObject::array_prototype)); if (vm.argument_count() == 0) return MUST(Array::create(global_object(), 0, proto)); if (vm.argument_count() == 1) { auto length = vm.argument(0); auto* array = MUST(Array::create(global_object(), 0, proto)); size_t int_length; if (!length.is_number()) { MUST(array->create_data_property_or_throw(0, length)); int_length = 1; } else { int_length = MUST(length.to_u32(global_object())); if (int_length != length.as_double()) return vm.throw_completion<RangeError>(global_object(), ErrorType::InvalidLength, "array"); } TRY(array->set(vm.names.length, Value(int_length), Object::ShouldThrowExceptions::Yes)); return array; } auto* array = TRY(Array::create(global_object(), vm.argument_count(), proto)); for (size_t k = 0; k < vm.argument_count(); ++k) MUST(array->create_data_property_or_throw(k, vm.argument(k))); return array; } // 23.1.2.1 Array.from ( items [ , mapfn [ , thisArg ] ] ), https://tc39.es/ecma262/#sec-array.from JS_DEFINE_NATIVE_FUNCTION(ArrayConstructor::from) { auto constructor = vm.this_value(global_object); FunctionObject* map_fn = nullptr; if (!vm.argument(1).is_undefined()) { auto callback = vm.argument(1); if (!callback.is_function()) return vm.throw_completion<TypeError>(global_object, ErrorType::NotAFunction, callback.to_string_without_side_effects()); map_fn = &callback.as_function(); } auto this_arg = vm.argument(2); auto items = vm.argument(0); auto using_iterator = TRY(items.get_method(global_object, *vm.well_known_symbol_iterator())); if (using_iterator) { Object* array; if (constructor.is_constructor()) array = TRY(JS::construct(global_object, constructor.as_function(), {})); else array = MUST(Array::create(global_object, 0)); auto iterator = TRY(get_iterator(global_object, items, IteratorHint::Sync, using_iterator)); size_t k = 0; while (true) { if (k >= MAX_ARRAY_LIKE_INDEX) { auto error = vm.throw_completion<TypeError>(global_object, ErrorType::ArrayMaxSize); return TRY(iterator_close(global_object, iterator, move(error))); } auto* next = TRY(iterator_step(global_object, iterator)); if (!next) { TRY(array->set(vm.names.length, Value(k), Object::ShouldThrowExceptions::Yes)); return array; } auto next_value = TRY(iterator_value(global_object, *next)); Value mapped_value; if (map_fn) { auto mapped_value_or_error = JS::call(global_object, *map_fn, this_arg, next_value, Value(k)); if (mapped_value_or_error.is_error()) return TRY(iterator_close(global_object, iterator, mapped_value_or_error.release_error())); mapped_value = mapped_value_or_error.release_value(); } else { mapped_value = next_value; } auto result_or_error = array->create_data_property_or_throw(k, mapped_value); if (result_or_error.is_error()) return TRY(iterator_close(global_object, iterator, result_or_error.release_error())); ++k; } } auto* array_like = MUST(items.to_object(global_object)); auto length = TRY(length_of_array_like(global_object, *array_like)); Object* array; if (constructor.is_constructor()) array = TRY(JS::construct(global_object, constructor.as_function(), Value(length))); else array = TRY(Array::create(global_object, length)); for (size_t k = 0; k < length; ++k) { auto k_value = TRY(array_like->get(k)); Value mapped_value; if (map_fn) mapped_value = TRY(JS::call(global_object, *map_fn, this_arg, k_value, Value(k))); else mapped_value = k_value; TRY(array->create_data_property_or_throw(k, mapped_value)); } TRY(array->set(vm.names.length, Value(length), Object::ShouldThrowExceptions::Yes)); return array; } // 23.1.2.2 Array.isArray ( arg ), https://tc39.es/ecma262/#sec-array.isarray JS_DEFINE_NATIVE_FUNCTION(ArrayConstructor::is_array) { auto value = vm.argument(0); return Value(TRY(value.is_array(global_object))); } // 23.1.2.3 Array.of ( ...items ), https://tc39.es/ecma262/#sec-array.of JS_DEFINE_NATIVE_FUNCTION(ArrayConstructor::of) { auto this_value = vm.this_value(global_object); Object* array; if (this_value.is_constructor()) array = TRY(JS::construct(global_object, this_value.as_function(), Value(vm.argument_count()))); else array = TRY(Array::create(global_object, vm.argument_count())); for (size_t k = 0; k < vm.argument_count(); ++k) TRY(array->create_data_property_or_throw(k, vm.argument(k))); TRY(array->set(vm.names.length, Value(vm.argument_count()), Object::ShouldThrowExceptions::Yes)); return array; } // 23.1.2.5 get Array [ @@species ], https://tc39.es/ecma262/#sec-get-array-@@species JS_DEFINE_NATIVE_FUNCTION(ArrayConstructor::symbol_species_getter) { return vm.this_value(global_object); } }
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if defined(OS_WIN) #include <wrl/client.h> #endif #include <memory> #include <tuple> #include <utility> #include <vector> #include "base/numerics/ranges.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/native_theme/native_theme.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if defined(USE_X11) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/views/native_frame_view.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/window_state_watcher.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/x11_types.h" #include "ui/views/widget/desktop_aura/desktop_window_tree_host_x11.h" #include "ui/views/window/native_frame_view.h" #elif defined(OS_WIN) #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #endif namespace electron { namespace { #if defined(OS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); } // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; bool CanClose() override { window_->NotifyWindowCloseButtonClicked(); return false; } private: NativeWindowViews* window_; DISALLOW_COPY_AND_ASSIGN(NativeWindowClientView); }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootView(this)), keyboard_event_handler_(new views::UnhandledKeyboardEventHandler) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if defined(OS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just devide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame(); if (transparent()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::ACTIVATABLE_NO; #if defined(OS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif defined(USE_X11) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; #endif widget()->Init(std::move(params)); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if defined(USE_X11) // Start monitoring window states. window_state_watcher_ = std::make_unique<WindowStateWatcher>(this); // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = ui::NativeTheme::GetInstanceForNativeUi()->ShouldUseDarkColors(); options.Get(options::kDarkTheme, &use_dark_theme); SetGTKDarkThemeEnabled(use_dark_theme); // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; bool skip_taskbar = false; if (options.Get(options::kSkipTaskbar, &skip_taskbar) && skip_taskbar) { state_atom_list.push_back(gfx::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); } // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(gfx::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { SetParentWindow(parent); // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(gfx::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) ui::SetAtomArrayProperty(GetAcceleratedWidget(), "_NET_WM_STATE", "ATOM", state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(GetAcceleratedWidget(), window_type); #endif #if defined(OS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if defined(OS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if defined(OS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif #if defined(OS_LINUX) // Listen to move events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #endif } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if defined(OS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif #if defined(OS_LINUX) aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_X11) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_X11) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_X11) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if defined(OS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif defined(USE_X11) return !event_disabler_.get(); #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if defined(OS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_X11) views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } #endif } #if defined(USE_X11) void NativeWindowViews::Maximize() { if (IsVisible()) widget()->Maximize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); } #endif void NativeWindowViews::Unmaximize() { #if defined(OS_WIN) if (!(::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME)) { SetBounds(restore_bounds_, false); return; } #endif widget()->Restore(); } bool NativeWindowViews::IsMaximized() { return widget()->IsMaximized(); } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if defined(OS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if defined(OS_WIN) || defined(USE_X11) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if defined(OS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if defined(OS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if defined(OS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if defined(OS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if defined(OS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_X11) if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(GetAcceleratedWidget(), static_cast<x11::Window>(id.id)); #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if defined(OS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_X11) electron::MoveWindowToForeground(GetAcceleratedWidget()); #endif } bool NativeWindowViews::IsResizable() { #if defined(OS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return CanResize(); } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); #if defined(OS_LINUX) gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); #endif } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if defined(OS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if defined(OS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if defined(OS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if defined(OS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if defined(OS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if defined(OS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } #endif } bool NativeWindowViews::IsClosable() { #if defined(OS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif defined(USE_X11) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if defined(OS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if defined(OS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if defined(OS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #elif defined(USE_X11) SetWMSpecState(GetAcceleratedWidget(), skip, gfx::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } SkColor NativeWindowViews::GetBackgroundColor() { return root_view_->background()->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if defined(OS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if defined(OS_WIN) const double boundedOpacity = base::ClampToRange(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if defined(OS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_X11) if (ignore) { XRectangle r = {0, 0, 1, 1}; XShapeCombineRectangles(gfx::GetXDisplay(), static_cast<uint32_t>(GetAcceleratedWidget()), ShapeInput, 0, 0, &r, 1, ShapeSet, static_cast<int>(x11::ClipOrdering::YXBanded)); } else { XShapeCombineMask(gfx::GetXDisplay(), static_cast<uint32_t>(GetAcceleratedWidget()), ShapeInput, 0, 0, x11::None, ShapeSet); } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if defined(OS_WIN) DWORD affinity = enable ? WDA_MONITOR : WDA_NONE; ::SetWindowDisplayAffinity(GetAcceleratedWidget(), affinity); #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if defined(OS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_X11) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_X11) XDisplay* xdisplay = gfx::GetXDisplay(); XSetTransientForHint( xdisplay, static_cast<uint32_t>(GetAcceleratedWidget()), static_cast<uint32_t>(parent ? parent->GetAcceleratedWidget() : ui::GetX11RootWindow())); #elif defined(OS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if defined(OS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif defined(USE_X11) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if defined(OS_WIN) taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces(bool visible) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_X11) // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = gfx::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; ui::GetAtomArrayProperty(GetAcceleratedWidget(), "_NET_WM_STATE", &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if defined(OS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif defined(USE_X11) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if defined(OS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if defined(OS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } void NativeWindowViews::UpdateDraggableRegions( std::unique_ptr<SkRegion> region) { draggable_region_ = std::move(region); } #if defined(OS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif defined(USE_X11) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif #if defined(USE_X11) void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { if (use_dark_theme) { ui::SetStringProperty(GetAcceleratedWidget(), gfx::GetAtom("_GTK_THEME_VARIANT"), gfx::GetAtom("UTF8_STRING"), "dark"); } else { ui::SetStringProperty(GetAcceleratedWidget(), gfx::GetAtom("_GTK_THEME_VARIANT"), gfx::GetAtom("UTF8_STRING"), "light"); } } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blured. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { NativeBrowserViewViews* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { #if defined(OS_LINUX) aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); #endif } void NativeWindowViews::DeleteDelegate() { if (is_modal() && this->parent()) { auto* parent = this->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } NotifyWindowClosed(); } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanResize() const { return resizable_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if defined(OS_WIN) return minimizable_; #elif defined(USE_X11) return true; #endif } base::string16 NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { // App window should claim mouse events that fall within the draggable region. if (draggable_region() && draggable_region()->contains(location.x(), location.y())) return false; // And the events on border for dragging resizable frameless window. if (!has_frame() && CanResize()) { FramelessView* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); return frame->ResizingBorderHitTest(location) == HTNOWHERE; } return true; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } views::NonClientFrameView* NativeWindowViews::CreateNonClientFrameView( views::Widget* widget) { #if defined(OS_WIN) WinFrameView* frame_view = new WinFrameView; frame_view->Init(this, widget); return frame_view; #else if (has_frame()) { return new NativeFrameView(this, widget); } else { FramelessView* frame_view = new FramelessView; frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { #if defined(OS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } #if defined(OS_LINUX) void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); } #endif ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) return ui::SHOW_STATE_MAXIMIZED; if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if defined(OS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
// Copyright 2019 The Fuchsia 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 "src/developer/memory/metrics/printer.h" #include <lib/trace/event.h> #include <zircon/types.h> #include <algorithm> #include <cstdint> #include <unordered_map> #include <unordered_set> #include "lib/trace/internal/event_common.h" #include "third_party/rapidjson/include/rapidjson/document.h" #include "third_party/rapidjson/include/rapidjson/ostreamwrapper.h" #include "third_party/rapidjson/include/rapidjson/rapidjson.h" #include "third_party/rapidjson/include/rapidjson/writer.h" namespace memory { const size_t kMaxFormattedStringSize = sizeof("1023.5T"); const char* FormatSize(uint64_t bytes, char* buf) { const char units[] = "BKMGTPE"; uint16_t r = 0; int ui = 0; while (bytes > 1023) { r = bytes % 1024; bytes /= 1024; ui++; } unsigned int round_up = ((r % 102) >= 51); r = (r / 102) + round_up; if (r == 10) { bytes++; r = 0; } if (r == 0) { snprintf(buf, kMaxFormattedStringSize, "%zu%c", bytes, units[ui]); } else { snprintf(buf, kMaxFormattedStringSize, "%zu.%1u%c", bytes, r, units[ui]); } return buf; } void Printer::PrintCapture(const Capture& capture) { TRACE_DURATION("memory_metrics", "Printer::PrintCaptureJson"); rapidjson::Document j(rapidjson::kObjectType); auto& a = j.GetAllocator(); rapidjson::Value kernel(rapidjson::kObjectType); const auto& k = capture.kmem(); kernel.AddMember("total", k.total_bytes, a) .AddMember("free", k.free_bytes, a) .AddMember("wired", k.wired_bytes, a) .AddMember("total_heap", k.total_heap_bytes, a) .AddMember("free_heap", k.free_heap_bytes, a) .AddMember("vmo", k.vmo_bytes, a) .AddMember("mmu", k.mmu_overhead_bytes, a) .AddMember("ipc", k.ipc_bytes, a) .AddMember("other", k.other_bytes, a); // Add additional kernel fields if kmem_extended is populated. const auto& k_ext = capture.kmem_extended(); if (k_ext.total_bytes > 0) { kernel.AddMember("vmo_pager_total", k_ext.vmo_pager_total_bytes, a) .AddMember("vmo_pager_newest", k_ext.vmo_pager_newest_bytes, a) .AddMember("vmo_pager_oldest", k_ext.vmo_pager_oldest_bytes, a) .AddMember("vmo_discardable_locked", k_ext.vmo_discardable_locked_bytes, a) .AddMember("vmo_discardable_unlocked", k_ext.vmo_discardable_unlocked_bytes, a); } struct NameCount { std::string name; mutable size_t count; explicit NameCount(const char* n) : name(n), count(1) {} bool operator==(const NameCount& kc) const { return name == kc.name; } }; class NameCountHash { public: size_t operator()(const NameCount& kc) const { return std::hash<std::string>()(kc.name); } }; TRACE_DURATION_BEGIN("memory_metrics", "Printer::PrintCaptureJson::Processes"); std::unordered_set<NameCount, NameCountHash> name_count; rapidjson::Value processes(rapidjson::kArrayType); processes.Reserve(capture.koid_to_process().size(), a); rapidjson::Value process_header(rapidjson::kArrayType); processes.PushBack(process_header.PushBack("koid", a).PushBack("name", a).PushBack("vmos", a), a); for (const auto& [_, p] : capture.koid_to_process()) { rapidjson::Value vmos(rapidjson::kArrayType); vmos.Reserve(p.vmos.size(), a); for (const auto& v : p.vmos) { vmos.PushBack(v, a); auto [it, inserted] = name_count.emplace(capture.koid_to_vmo().find(v)->second.name); if (!inserted) { (*it).count++; } } rapidjson::Value process(rapidjson::kArrayType); process.PushBack(p.koid, a).PushBack(rapidjson::StringRef(p.name), a).PushBack(vmos, a); processes.PushBack(process, a); } TRACE_DURATION_END("memory_metrics", "Printer::PrintCaptureJson::Processes"); TRACE_DURATION_BEGIN("memory_metrics", "Printer::PrintCaptureJson::Names"); std::vector<NameCount> sorted_counts(name_count.begin(), name_count.end()); std::sort(sorted_counts.begin(), sorted_counts.end(), [](const NameCount& kc1, const NameCount& kc2) { return kc1.count > kc2.count; }); size_t index = 0; std::unordered_map<std::string, size_t> name_to_index(sorted_counts.size()); for (const auto& kc : sorted_counts) { name_to_index[kc.name] = index++; } rapidjson::Value vmo_names(rapidjson::kArrayType); for (const auto& nc : sorted_counts) { vmo_names.PushBack(rapidjson::StringRef(nc.name.c_str()), a); } TRACE_DURATION_END("memory_metrics", "Printer::PrintCaptureJson::Names"); TRACE_DURATION_BEGIN("memory_metrics", "Printer::PrintCaptureJson::Vmos"); rapidjson::Value vmos(rapidjson::kArrayType); rapidjson::Value vmo_header(rapidjson::kArrayType); vmo_header.PushBack("koid", a) .PushBack("name", a) .PushBack("parent_koid", a) .PushBack("committed_bytes", a) .PushBack("allocated_bytes", a); vmos.PushBack(vmo_header, a); for (const auto& [k, v] : capture.koid_to_vmo()) { rapidjson::Value vmo_value(rapidjson::kArrayType); vmo_value.PushBack(v.koid, a) .PushBack(name_to_index[v.name], a) .PushBack(v.parent_koid, a) .PushBack(v.committed_bytes, a) .PushBack(v.allocated_bytes, a); vmos.PushBack(vmo_value, a); } TRACE_DURATION_END("memory_metrics", "Printer::PrintCaptureJson::Vmos"); j.AddMember("Time", capture.time(), a) .AddMember("Kernel", kernel, a) .AddMember("Processes", processes, a) .AddMember("VmoNames", vmo_names, a) .AddMember("Vmos", vmos, a); TRACE_DURATION_BEGIN("memory_metrics", "Printer::PrintCaptureJson::Write"); rapidjson::OStreamWrapper osw(os_); rapidjson::Writer<rapidjson::OStreamWrapper> writer(osw); j.Accept(writer); TRACE_DURATION_END("memory_metrics", "Printer::PrintCaptureJson::Write"); } void Printer::OutputSizes(const Sizes& sizes) { if (sizes.total_bytes == sizes.private_bytes) { char private_buf[kMaxFormattedStringSize]; os_ << FormatSize(sizes.private_bytes, private_buf) << "\n"; return; } char private_buf[kMaxFormattedStringSize], scaled_buf[kMaxFormattedStringSize], total_buf[kMaxFormattedStringSize]; os_ << FormatSize(sizes.private_bytes, private_buf) << " " << FormatSize(sizes.scaled_bytes, scaled_buf) << " " << FormatSize(sizes.total_bytes, total_buf) << "\n"; } void Printer::PrintSummary(const Summary& summary, CaptureLevel level, Sorted sorted) { TRACE_DURATION("memory_metrics", "Printer::PrintSummary"); char vmo_buf[kMaxFormattedStringSize], free_buf[kMaxFormattedStringSize]; const auto& kstats = summary.kstats(); os_ << "Time: " << summary.time() << " VMO: " << FormatSize(kstats.vmo_bytes, vmo_buf) << " Free: " << FormatSize(kstats.free_bytes, free_buf) << "\n"; if (level == KMEM) { return; } const auto& summaries = summary.process_summaries(); std::vector<uint32_t> summary_order; summary_order.reserve(summaries.size()); for (uint32_t i = 0; i < summaries.size(); i++) { summary_order.push_back(i); } if (sorted == SORTED) { std::sort(summary_order.begin(), summary_order.end(), [&summaries](uint32_t ai, uint32_t bi) { const auto& a = summaries[ai]; const auto& b = summaries[bi]; return a.sizes().private_bytes > b.sizes().private_bytes; }); } for (auto i : summary_order) { const auto& s = summaries[i]; os_ << s.name() << "<" << s.koid() << "> "; OutputSizes(s.sizes()); if (level == PROCESS) { continue; } const auto& name_to_sizes = s.name_to_sizes(); std::vector<std::string> names; names.reserve(name_to_sizes.size()); for (const auto& [name, sizes] : name_to_sizes) { names.push_back(name); } if (sorted == SORTED) { std::sort(names.begin(), names.end(), [&name_to_sizes](const std::string& a, const std::string& b) { const auto& sa = name_to_sizes.at(a); const auto& sb = name_to_sizes.at(b); return sa.private_bytes == sb.private_bytes ? sa.scaled_bytes > sb.scaled_bytes : sa.private_bytes > sb.private_bytes; }); } for (const auto& name : names) { const auto& n_sizes = name_to_sizes.at(name); if (n_sizes.total_bytes == 0) { continue; } os_ << " " << name << " "; OutputSizes(n_sizes); } } os_ << std::flush; } void Printer::OutputSummary(const Summary& summary, Sorted sorted, zx_koid_t pid) { TRACE_DURATION("memory_metrics", "Printer::OutputSummary"); const auto& summaries = summary.process_summaries(); std::vector<ProcessSummary> sorted_summaries; if (sorted == SORTED) { sorted_summaries = summaries; std::sort(sorted_summaries.begin(), sorted_summaries.end(), [](ProcessSummary a, ProcessSummary b) { return a.sizes().private_bytes > b.sizes().private_bytes; }); } const auto time = summary.time() / 1000000000; for (const auto& s : sorted == SORTED ? sorted_summaries : summaries) { if (pid != ZX_KOID_INVALID) { if (s.koid() != pid) { continue; } const auto& name_to_sizes = s.name_to_sizes(); std::vector<std::string> names; names.reserve(name_to_sizes.size()); for (const auto& [name, sizes] : name_to_sizes) { names.push_back(name); } if (sorted == SORTED) { std::sort(names.begin(), names.end(), [&name_to_sizes](std::string a, std::string b) { const auto& sa = name_to_sizes.at(a); const auto& sb = name_to_sizes.at(b); return sa.private_bytes == sb.private_bytes ? sa.scaled_bytes > sb.scaled_bytes : sa.private_bytes > sb.private_bytes; }); } for (const auto& name : names) { const auto& sizes = name_to_sizes.at(name); if (sizes.total_bytes == 0) { continue; } os_ << time << "," << s.koid() << "," << name << "," << sizes.private_bytes << "," << sizes.scaled_bytes << "," << sizes.total_bytes << "\n"; } continue; } auto sizes = s.sizes(); os_ << time << "," << s.koid() << "," << s.name() << "," << sizes.private_bytes << "," << sizes.scaled_bytes << "," << sizes.total_bytes << "\n"; } os_ << std::flush; } void Printer::PrintDigest(const Digest& digest) { TRACE_DURATION("memory_metrics", "Printer::PrintDigest"); for (auto const& bucket : digest.buckets()) { char size_buf[kMaxFormattedStringSize]; FormatSize(bucket.size(), size_buf); os_ << bucket.name() << ": " << size_buf << "\n"; } } void Printer::OutputDigest(const Digest& digest) { TRACE_DURATION("memory_metrics", "Printer::OutputDigest"); auto const time = digest.time() / 1000000000; for (auto const& bucket : digest.buckets()) { os_ << time << "," << bucket.name() << "," << bucket.size() << "\n"; } } } // namespace memory
#include <iostream> #include <cstdio> #include <vector> using namespace std; #define ElemType int #define _for(i,a,b) for(int i=(a);i<(b);i++) //P323.2 //编写双向冒泡排序算法, 在正反两个方向交替进行扫描, 即第一趟把关键字最大的元素 //放在序列的最后面, 第二趟把关键字最小的元素放在序列的最前面, 如此反复进行。 void BubbleSort(vector<ElemType> &A) { int low = 0, high = A.size() - 1; bool flag = true; while (low < high && flag) { flag = false; _for(i, low, high) { if (A[i] > A[i + 1]) { swap(A[i], A[i + 1]); flag = true; } } high--; for (int i = high; i > low; i--) { if (A[i] < A[i - 1]) { swap(A[i], A[i - 1]); flag = true; } } low++; } } void Print(vector<ElemType> A) { _for(i, 0, A.size()) { cout << A[i] << " "; } cout << endl; } int main() { vector<ElemType> A{ 2,5,21,54,64,12,65,34,12,37,21 }; cout << "排序前:" << endl; Print(A); BubbleSort(A); cout << "排序后:" << endl; Print(A); return 0; }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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 "inline.h" #include <tvm/runtime/registry.h> #include <utility> #include <vector> #include "../common.h" namespace tvm { namespace contrib { namespace ethosu { namespace cascader { const PerformanceInfo InlinePartNode::GetPerformanceInfo(const StripeConfig& output_stripe_config, bool is_rolling) { std::vector<size_t> read_bytes(input_tensors_.size()); PerformanceInfo info(0, read_bytes, 0); return info; } InlinePart::InlinePart(const TESubgraph& subgraph, const std::vector<Propagator> propagators) { auto n = make_object<InlinePartNode>(); ICHECK_GT(propagators.size(), 0) << "The Part must include at least one Propagator."; n->subgraph_ = subgraph; n->propagators_ = std::move(propagators); n->in_line_ = true; n->input_tensors_.resize(propagators.size()); data_ = std::move(n); } TVM_REGISTER_GLOBAL("contrib.ethosu.cascader.InlinePart") .set_body_typed([](Array<te::Tensor> subgraph_inputs, te::Tensor subgraph_output, Array<Propagator> propagators) { std::vector<te::Tensor> vsubgraph_inputs(subgraph_inputs.begin(), subgraph_inputs.end()); std::vector<Propagator> vpropagators(propagators.begin(), propagators.end()); TESubgraph subgraph; subgraph.input_tensors = vsubgraph_inputs; subgraph.output_tensor = subgraph_output; return InlinePart(subgraph, vpropagators); }); TVM_REGISTER_NODE_TYPE(InlinePartNode); } // namespace cascader } // namespace ethosu } // namespace contrib } // namespace tvm
// Copyright (c) 2011-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 "guiutil.h" #include "bitcoinaddressvalidator.h" #include "bitcoinunits.h" #include "qvalidatedlineedit.h" #include "walletmodel.h" #include "fs.h" #include "primitives/transaction.h" #include "init.h" #include "policy/policy.h" #include "protocol.h" #include "script/script.h" #include "script/standard.h" #include "util.h" #ifdef WIN32 #ifdef _WIN32_WINNT #undef _WIN32_WINNT #endif #define _WIN32_WINNT 0x0501 #ifdef _WIN32_IE #undef _WIN32_IE #endif #define _WIN32_IE 0x0501 #define WIN32_LEAN_AND_MEAN 1 #ifndef NOMINMAX #define NOMINMAX #endif #include "shellapi.h" #include "shlobj.h" #include "shlwapi.h" #endif #include <boost/scoped_array.hpp> #include <QAbstractItemView> #include <QApplication> #include <QClipboard> #include <QDateTime> #include <QDesktopServices> #include <QDesktopWidget> #include <QDoubleValidator> #include <QFileDialog> #include <QFont> #include <QLineEdit> #include <QSettings> #include <QTextDocument> // for Qt::mightBeRichText #include <QThread> #include <QMouseEvent> #if QT_VERSION < 0x050000 #include <QUrl> #else #include <QUrlQuery> #endif #if QT_VERSION >= 0x50200 #include <QFontDatabase> #endif static fs::detail::utf8_codecvt_facet utf8; #if defined(Q_OS_MAC) extern double NSAppKitVersionNumber; #if !defined(NSAppKitVersionNumber10_8) #define NSAppKitVersionNumber10_8 1187 #endif #if !defined(NSAppKitVersionNumber10_9) #define NSAppKitVersionNumber10_9 1265 #endif #endif namespace GUIUtil { QString dateTimeStr(const QDateTime &date) { return date.date().toString(Qt::SystemLocaleShortDate) + QString(" ") + date.toString("hh:mm"); } QString dateTimeStr(qint64 nTime) { return dateTimeStr(QDateTime::fromTime_t((qint32)nTime)); } QFont fixedPitchFont() { #if QT_VERSION >= 0x50200 return QFontDatabase::systemFont(QFontDatabase::FixedFont); #else QFont font("Monospace"); #if QT_VERSION >= 0x040800 font.setStyleHint(QFont::Monospace); #else font.setStyleHint(QFont::TypeWriter); #endif return font; #endif } // Just some dummy data to generate an convincing random-looking (but consistent) address static const uint8_t dummydata[] = {0xeb,0x15,0x23,0x1d,0xfc,0xeb,0x60,0x92,0x58,0x86,0xb6,0x7d,0x06,0x52,0x99,0x92,0x59,0x15,0xae,0xb1,0x72,0xc0,0x66,0x47}; // Generate a dummy address with invalid CRC, starting with the network prefix. static std::string DummyAddress(const CChainParams &params) { std::vector<unsigned char> sourcedata = params.Base58Prefix(CChainParams::PUBKEY_ADDRESS); sourcedata.insert(sourcedata.end(), dummydata, dummydata + sizeof(dummydata)); for(int i=0; i<256; ++i) { // Try every trailing byte std::string s = EncodeBase58(sourcedata.data(), sourcedata.data() + sourcedata.size()); if (!CBitcoinAddress(s).IsValid()) return s; sourcedata[sourcedata.size()-1] += 1; } return ""; } void setupAddressWidget(QValidatedLineEdit *widget, QWidget *parent) { parent->setFocusProxy(widget); widget->setFont(fixedPitchFont()); #if QT_VERSION >= 0x040700 // We don't want translators to use own addresses in translations // and this is the only place, where this address is supplied. widget->setPlaceholderText(QObject::tr("Enter a Bit address (e.g. %1)").arg( QString::fromStdString(DummyAddress(Params())))); #endif widget->setValidator(new BitcoinAddressEntryValidator(parent)); widget->setCheckValidator(new BitcoinAddressCheckValidator(parent)); } void setupAmountWidget(QLineEdit *widget, QWidget *parent) { QDoubleValidator *amountValidator = new QDoubleValidator(parent); amountValidator->setDecimals(8); amountValidator->setBottom(0.0); widget->setValidator(amountValidator); widget->setAlignment(Qt::AlignRight|Qt::AlignVCenter); } bool parseBitcoinURI(const QUrl &uri, SendCoinsRecipient *out) { // return if URI is not valid or is no bitcoin: URI if(!uri.isValid() || uri.scheme() != QString("bit")) return false; SendCoinsRecipient rv; rv.address = uri.path(); // Trim any following forward slash which may have been added by the OS if (rv.address.endsWith("/")) { rv.address.truncate(rv.address.length() - 1); } rv.amount = 0; #if QT_VERSION < 0x050000 QList<QPair<QString, QString> > items = uri.queryItems(); #else QUrlQuery uriQuery(uri); QList<QPair<QString, QString> > items = uriQuery.queryItems(); #endif for (QList<QPair<QString, QString> >::iterator i = items.begin(); i != items.end(); i++) { bool fShouldReturnFalse = false; if (i->first.startsWith("req-")) { i->first.remove(0, 4); fShouldReturnFalse = true; } if (i->first == "label") { rv.label = i->second; fShouldReturnFalse = false; } if (i->first == "message") { rv.message = i->second; fShouldReturnFalse = false; } else if (i->first == "amount") { if(!i->second.isEmpty()) { if(!BitcoinUnits::parse(BitcoinUnits::BTC, i->second, &rv.amount)) { return false; } } fShouldReturnFalse = false; } if (fShouldReturnFalse) return false; } if(out) { *out = rv; } return true; } bool parseBitcoinURI(QString uri, SendCoinsRecipient *out) { // Convert bitcoin:// to bitcoin: // // Cannot handle this later, because bitcoin:// will cause Qt to see the part after // as host, // which will lower-case it (and thus invalidate the address). if(uri.startsWith("bit://", Qt::CaseInsensitive)) { uri.replace(0, 11, "bit:"); } QUrl uriInstance(uri); return parseBitcoinURI(uriInstance, out); } QString formatBitcoinURI(const SendCoinsRecipient &info) { QString ret = QString("bit:%1").arg(info.address); int paramCount = 0; if (info.amount) { ret += QString("?amount=%1").arg(BitcoinUnits::format(BitcoinUnits::BTC, info.amount, false, BitcoinUnits::separatorNever)); paramCount++; } if (!info.label.isEmpty()) { QString lbl(QUrl::toPercentEncoding(info.label)); ret += QString("%1label=%2").arg(paramCount == 0 ? "?" : "&").arg(lbl); paramCount++; } if (!info.message.isEmpty()) { QString msg(QUrl::toPercentEncoding(info.message)); ret += QString("%1message=%2").arg(paramCount == 0 ? "?" : "&").arg(msg); paramCount++; } return ret; } bool isDust(const QString& address, const CAmount& amount) { CTxDestination dest = CBitcoinAddress(address.toStdString()).Get(); CScript script = GetScriptForDestination(dest); CTxOut txOut(amount, script); return IsDust(txOut, ::dustRelayFee); } QString HtmlEscape(const QString& str, bool fMultiLine) { #if QT_VERSION < 0x050000 QString escaped = Qt::escape(str); #else QString escaped = str.toHtmlEscaped(); #endif if(fMultiLine) { escaped = escaped.replace("\n", "<br>\n"); } return escaped; } QString HtmlEscape(const std::string& str, bool fMultiLine) { return HtmlEscape(QString::fromStdString(str), fMultiLine); } void copyEntryData(QAbstractItemView *view, int column, int role) { if(!view || !view->selectionModel()) return; QModelIndexList selection = view->selectionModel()->selectedRows(column); if(!selection.isEmpty()) { // Copy first item setClipboard(selection.at(0).data(role).toString()); } } QList<QModelIndex> getEntryData(QAbstractItemView *view, int column) { if(!view || !view->selectionModel()) return QList<QModelIndex>(); return view->selectionModel()->selectedRows(column); } QString getSaveFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { #if QT_VERSION < 0x050000 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); #else myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); #endif } else { myDir = dir; } /* Directly convert path to native OS path separators */ QString result = QDir::toNativeSeparators(QFileDialog::getSaveFileName(parent, caption, myDir, filter, &selectedFilter)); /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } /* Add suffix if needed */ QFileInfo info(result); if(!result.isEmpty()) { if(info.suffix().isEmpty() && !selectedSuffix.isEmpty()) { /* No suffix specified, add selected suffix */ if(!result.endsWith(".")) result.append("."); result.append(selectedSuffix); } } /* Return selected suffix if asked to */ if(selectedSuffixOut) { *selectedSuffixOut = selectedSuffix; } return result; } QString getOpenFileName(QWidget *parent, const QString &caption, const QString &dir, const QString &filter, QString *selectedSuffixOut) { QString selectedFilter; QString myDir; if(dir.isEmpty()) // Default to user documents location { #if QT_VERSION < 0x050000 myDir = QDesktopServices::storageLocation(QDesktopServices::DocumentsLocation); #else myDir = QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation); #endif } else { myDir = dir; } /* Directly convert path to native OS path separators */ QString result = QDir::toNativeSeparators(QFileDialog::getOpenFileName(parent, caption, myDir, filter, &selectedFilter)); if(selectedSuffixOut) { /* Extract first suffix from filter pattern "Description (*.foo)" or "Description (*.foo *.bar ...) */ QRegExp filter_re(".* \\(\\*\\.(.*)[ \\)]"); QString selectedSuffix; if(filter_re.exactMatch(selectedFilter)) { selectedSuffix = filter_re.cap(1); } *selectedSuffixOut = selectedSuffix; } return result; } Qt::ConnectionType blockingGUIThreadConnection() { if(QThread::currentThread() != qApp->thread()) { return Qt::BlockingQueuedConnection; } else { return Qt::DirectConnection; } } bool checkPoint(const QPoint &p, const QWidget *w) { QWidget *atW = QApplication::widgetAt(w->mapToGlobal(p)); if (!atW) return false; return atW->topLevelWidget() == w; } bool isObscured(QWidget *w) { return !(checkPoint(QPoint(0, 0), w) && checkPoint(QPoint(w->width() - 1, 0), w) && checkPoint(QPoint(0, w->height() - 1), w) && checkPoint(QPoint(w->width() - 1, w->height() - 1), w) && checkPoint(QPoint(w->width() / 2, w->height() / 2), w)); } void openDebugLogfile() { fs::path pathDebug = GetDataDir() / "debug.log"; /* Open debug.log with the associated application */ if (fs::exists(pathDebug)) QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathDebug))); } bool openBitcoinConf() { boost::filesystem::path pathConfig = GetConfigFile(BITCOIN_CONF_FILENAME); /* Create the file */ boost::filesystem::ofstream configFile(pathConfig, std::ios_base::app); if (!configFile.good()) return false; configFile.close(); /* Open bitcoin.conf with the associated application */ return QDesktopServices::openUrl(QUrl::fromLocalFile(boostPathToQString(pathConfig))); } void SubstituteFonts(const QString& language) { #if defined(Q_OS_MAC) // Background: // OSX's default font changed in 10.9 and Qt is unable to find it with its // usual fallback methods when building against the 10.7 sdk or lower. // The 10.8 SDK added a function to let it find the correct fallback font. // If this fallback is not properly loaded, some characters may fail to // render correctly. // // The same thing happened with 10.10. .Helvetica Neue DeskInterface is now default. // // Solution: If building with the 10.7 SDK or lower and the user's platform // is 10.9 or higher at runtime, substitute the correct font. This needs to // happen before the QApplication is created. #if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED < MAC_OS_X_VERSION_10_8 if (floor(NSAppKitVersionNumber) > NSAppKitVersionNumber10_8) { if (floor(NSAppKitVersionNumber) <= NSAppKitVersionNumber10_9) /* On a 10.9 - 10.9.x system */ QFont::insertSubstitution(".Lucida Grande UI", "Lucida Grande"); else { /* 10.10 or later system */ if (language == "zh_CN" || language == "zh_TW" || language == "zh_HK") // traditional or simplified Chinese QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Heiti SC"); else if (language == "ja") // Japanese QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Songti SC"); else QFont::insertSubstitution(".Helvetica Neue DeskInterface", "Lucida Grande"); } } #endif #endif } ToolTipToRichTextFilter::ToolTipToRichTextFilter(int _size_threshold, QObject *parent) : QObject(parent), size_threshold(_size_threshold) { } bool ToolTipToRichTextFilter::eventFilter(QObject *obj, QEvent *evt) { if(evt->type() == QEvent::ToolTipChange) { QWidget *widget = static_cast<QWidget*>(obj); QString tooltip = widget->toolTip(); if(tooltip.size() > size_threshold && !tooltip.startsWith("<qt") && !Qt::mightBeRichText(tooltip)) { // Envelop with <qt></qt> to make sure Qt detects this as rich text // Escape the current message as HTML and replace \n by <br> tooltip = "<qt>" + HtmlEscape(tooltip, true) + "</qt>"; widget->setToolTip(tooltip); return true; } } return QObject::eventFilter(obj, evt); } void TableViewLastColumnResizingFixer::connectViewHeadersSignals() { connect(tableView->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(on_sectionResized(int,int,int))); connect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged())); } // We need to disconnect these while handling the resize events, otherwise we can enter infinite loops. void TableViewLastColumnResizingFixer::disconnectViewHeadersSignals() { disconnect(tableView->horizontalHeader(), SIGNAL(sectionResized(int,int,int)), this, SLOT(on_sectionResized(int,int,int))); disconnect(tableView->horizontalHeader(), SIGNAL(geometriesChanged()), this, SLOT(on_geometriesChanged())); } // Setup the resize mode, handles compatibility for Qt5 and below as the method signatures changed. // Refactored here for readability. void TableViewLastColumnResizingFixer::setViewHeaderResizeMode(int logicalIndex, QHeaderView::ResizeMode resizeMode) { #if QT_VERSION < 0x050000 tableView->horizontalHeader()->setResizeMode(logicalIndex, resizeMode); #else tableView->horizontalHeader()->setSectionResizeMode(logicalIndex, resizeMode); #endif } void TableViewLastColumnResizingFixer::resizeColumn(int nColumnIndex, int width) { tableView->setColumnWidth(nColumnIndex, width); tableView->horizontalHeader()->resizeSection(nColumnIndex, width); } int TableViewLastColumnResizingFixer::getColumnsWidth() { int nColumnsWidthSum = 0; for (int i = 0; i < columnCount; i++) { nColumnsWidthSum += tableView->horizontalHeader()->sectionSize(i); } return nColumnsWidthSum; } int TableViewLastColumnResizingFixer::getAvailableWidthForColumn(int column) { int nResult = lastColumnMinimumWidth; int nTableWidth = tableView->horizontalHeader()->width(); if (nTableWidth > 0) { int nOtherColsWidth = getColumnsWidth() - tableView->horizontalHeader()->sectionSize(column); nResult = std::max(nResult, nTableWidth - nOtherColsWidth); } return nResult; } // Make sure we don't make the columns wider than the table's viewport width. void TableViewLastColumnResizingFixer::adjustTableColumnsWidth() { disconnectViewHeadersSignals(); resizeColumn(lastColumnIndex, getAvailableWidthForColumn(lastColumnIndex)); connectViewHeadersSignals(); int nTableWidth = tableView->horizontalHeader()->width(); int nColsWidth = getColumnsWidth(); if (nColsWidth > nTableWidth) { resizeColumn(secondToLastColumnIndex,getAvailableWidthForColumn(secondToLastColumnIndex)); } } // Make column use all the space available, useful during window resizing. void TableViewLastColumnResizingFixer::stretchColumnWidth(int column) { disconnectViewHeadersSignals(); resizeColumn(column, getAvailableWidthForColumn(column)); connectViewHeadersSignals(); } // When a section is resized this is a slot-proxy for ajustAmountColumnWidth(). void TableViewLastColumnResizingFixer::on_sectionResized(int logicalIndex, int oldSize, int newSize) { adjustTableColumnsWidth(); int remainingWidth = getAvailableWidthForColumn(logicalIndex); if (newSize > remainingWidth) { resizeColumn(logicalIndex, remainingWidth); } } // When the table's geometry is ready, we manually perform the stretch of the "Message" column, // as the "Stretch" resize mode does not allow for interactive resizing. void TableViewLastColumnResizingFixer::on_geometriesChanged() { if ((getColumnsWidth() - this->tableView->horizontalHeader()->width()) != 0) { disconnectViewHeadersSignals(); resizeColumn(secondToLastColumnIndex, getAvailableWidthForColumn(secondToLastColumnIndex)); connectViewHeadersSignals(); } } /** * Initializes all internal variables and prepares the * the resize modes of the last 2 columns of the table and */ TableViewLastColumnResizingFixer::TableViewLastColumnResizingFixer(QTableView* table, int lastColMinimumWidth, int allColsMinimumWidth, QObject *parent) : QObject(parent), tableView(table), lastColumnMinimumWidth(lastColMinimumWidth), allColumnsMinimumWidth(allColsMinimumWidth) { columnCount = tableView->horizontalHeader()->count(); lastColumnIndex = columnCount - 1; secondToLastColumnIndex = columnCount - 2; tableView->horizontalHeader()->setMinimumSectionSize(allColumnsMinimumWidth); setViewHeaderResizeMode(secondToLastColumnIndex, QHeaderView::Interactive); setViewHeaderResizeMode(lastColumnIndex, QHeaderView::Interactive); } #ifdef WIN32 fs::path static StartupShortcutPath() { std::string chain = ChainNameFromCommandLine(); if (chain == CBaseChainParams::MAIN) return GetSpecialFolderPath(CSIDL_STARTUP) / "Bit.lnk"; if (chain == CBaseChainParams::TESTNET) // Remove this special case when CBaseChainParams::TESTNET = "testnet4" return GetSpecialFolderPath(CSIDL_STARTUP) / "Bit (testnet).lnk"; return GetSpecialFolderPath(CSIDL_STARTUP) / strprintf("Bit (%s).lnk", chain); } bool GetStartOnSystemStartup() { // check for Bitcoin*.lnk return fs::exists(StartupShortcutPath()); } bool SetStartOnSystemStartup(bool fAutoStart) { // If the shortcut exists already, remove it for updating fs::remove(StartupShortcutPath()); if (fAutoStart) { CoInitialize(nullptr); // Get a pointer to the IShellLink interface. IShellLink* psl = nullptr; HRESULT hres = CoCreateInstance(CLSID_ShellLink, nullptr, CLSCTX_INPROC_SERVER, IID_IShellLink, reinterpret_cast<void**>(&psl)); if (SUCCEEDED(hres)) { // Get the current executable path TCHAR pszExePath[MAX_PATH]; GetModuleFileName(nullptr, pszExePath, sizeof(pszExePath)); // Start client minimized QString strArgs = "-min"; // Set -testnet /-regtest options strArgs += QString::fromStdString(strprintf(" -testnet=%d -regtest=%d", gArgs.GetBoolArg("-testnet", false), gArgs.GetBoolArg("-regtest", false))); #ifdef UNICODE boost::scoped_array<TCHAR> args(new TCHAR[strArgs.length() + 1]); // Convert the QString to TCHAR* strArgs.toWCharArray(args.get()); // Add missing '\0'-termination to string args[strArgs.length()] = '\0'; #endif // Set the path to the shortcut target psl->SetPath(pszExePath); PathRemoveFileSpec(pszExePath); psl->SetWorkingDirectory(pszExePath); psl->SetShowCmd(SW_SHOWMINNOACTIVE); #ifndef UNICODE psl->SetArguments(strArgs.toStdString().c_str()); #else psl->SetArguments(args.get()); #endif // Query IShellLink for the IPersistFile interface for // saving the shortcut in persistent storage. IPersistFile* ppf = nullptr; hres = psl->QueryInterface(IID_IPersistFile, reinterpret_cast<void**>(&ppf)); if (SUCCEEDED(hres)) { WCHAR pwsz[MAX_PATH]; // Ensure that the string is ANSI. MultiByteToWideChar(CP_ACP, 0, StartupShortcutPath().string().c_str(), -1, pwsz, MAX_PATH); // Save the link by calling IPersistFile::Save. hres = ppf->Save(pwsz, TRUE); ppf->Release(); psl->Release(); CoUninitialize(); return true; } psl->Release(); } CoUninitialize(); return false; } return true; } #elif defined(Q_OS_LINUX) // Follow the Desktop Application Autostart Spec: // http://standards.freedesktop.org/autostart-spec/autostart-spec-latest.html fs::path static GetAutostartDir() { char* pszConfigHome = getenv("XDG_CONFIG_HOME"); if (pszConfigHome) return fs::path(pszConfigHome) / "autostart"; char* pszHome = getenv("HOME"); if (pszHome) return fs::path(pszHome) / ".config" / "autostart"; return fs::path(); } fs::path static GetAutostartFilePath() { std::string chain = ChainNameFromCommandLine(); if (chain == CBaseChainParams::MAIN) return GetAutostartDir() / "bit.desktop"; return GetAutostartDir() / strprintf("bit-%s.lnk", chain); } bool GetStartOnSystemStartup() { fs::ifstream optionFile(GetAutostartFilePath()); if (!optionFile.good()) return false; // Scan through file for "Hidden=true": std::string line; while (!optionFile.eof()) { getline(optionFile, line); if (line.find("Hidden") != std::string::npos && line.find("true") != std::string::npos) return false; } optionFile.close(); return true; } bool SetStartOnSystemStartup(bool fAutoStart) { if (!fAutoStart) fs::remove(GetAutostartFilePath()); else { char pszExePath[MAX_PATH+1]; memset(pszExePath, 0, sizeof(pszExePath)); if (readlink("/proc/self/exe", pszExePath, sizeof(pszExePath)-1) == -1) return false; fs::create_directories(GetAutostartDir()); fs::ofstream optionFile(GetAutostartFilePath(), std::ios_base::out|std::ios_base::trunc); if (!optionFile.good()) return false; std::string chain = ChainNameFromCommandLine(); // Write a bitcoin.desktop file to the autostart directory: optionFile << "[Desktop Entry]\n"; optionFile << "Type=Application\n"; if (chain == CBaseChainParams::MAIN) optionFile << "Name=Bit\n"; else optionFile << strprintf("Name=Bit (%s)\n", chain); optionFile << "Exec=" << pszExePath << strprintf(" -min -testnet=%d -regtest=%d\n", gArgs.GetBoolArg("-testnet", false), gArgs.GetBoolArg("-regtest", false)); optionFile << "Terminal=false\n"; optionFile << "Hidden=false\n"; optionFile.close(); } return true; } #elif defined(Q_OS_MAC) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated-declarations" // based on: https://github.com/Mozketo/LaunchAtLoginController/blob/master/LaunchAtLoginController.m #include <CoreFoundation/CoreFoundation.h> #include <CoreServices/CoreServices.h> LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl); LSSharedFileListItemRef findStartupItemInList(LSSharedFileListRef list, CFURLRef findUrl) { // loop through the list of startup items and try to find the bitcoin app CFArrayRef listSnapshot = LSSharedFileListCopySnapshot(list, nullptr); for(int i = 0; i < CFArrayGetCount(listSnapshot); i++) { LSSharedFileListItemRef item = (LSSharedFileListItemRef)CFArrayGetValueAtIndex(listSnapshot, i); UInt32 resolutionFlags = kLSSharedFileListNoUserInteraction | kLSSharedFileListDoNotMountVolumes; CFURLRef currentItemURL = nullptr; #if defined(MAC_OS_X_VERSION_MAX_ALLOWED) && MAC_OS_X_VERSION_MAX_ALLOWED >= 10100 if(&LSSharedFileListItemCopyResolvedURL) currentItemURL = LSSharedFileListItemCopyResolvedURL(item, resolutionFlags, nullptr); #if defined(MAC_OS_X_VERSION_MIN_REQUIRED) && MAC_OS_X_VERSION_MIN_REQUIRED < 10100 else LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, nullptr); #endif #else LSSharedFileListItemResolve(item, resolutionFlags, &currentItemURL, nullptr); #endif if(currentItemURL && CFEqual(currentItemURL, findUrl)) { // found CFRelease(currentItemURL); return item; } if(currentItemURL) { CFRelease(currentItemURL); } } return nullptr; } bool GetStartOnSystemStartup() { CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); LSSharedFileListRef loginItems = LSSharedFileListCreate(nullptr, kLSSharedFileListSessionLoginItems, nullptr); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); return !!foundItem; // return boolified object } bool SetStartOnSystemStartup(bool fAutoStart) { CFURLRef bitcoinAppUrl = CFBundleCopyBundleURL(CFBundleGetMainBundle()); LSSharedFileListRef loginItems = LSSharedFileListCreate(nullptr, kLSSharedFileListSessionLoginItems, nullptr); LSSharedFileListItemRef foundItem = findStartupItemInList(loginItems, bitcoinAppUrl); if(fAutoStart && !foundItem) { // add bitcoin app to startup item list LSSharedFileListInsertItemURL(loginItems, kLSSharedFileListItemBeforeFirst, nullptr, nullptr, bitcoinAppUrl, nullptr, nullptr); } else if(!fAutoStart && foundItem) { // remove item LSSharedFileListItemRemove(loginItems, foundItem); } return true; } #pragma GCC diagnostic pop #else bool GetStartOnSystemStartup() { return false; } bool SetStartOnSystemStartup(bool fAutoStart) { return false; } #endif void saveWindowGeometry(const QString& strSetting, QWidget *parent) { QSettings settings; settings.setValue(strSetting + "Pos", parent->pos()); settings.setValue(strSetting + "Size", parent->size()); } void restoreWindowGeometry(const QString& strSetting, const QSize& defaultSize, QWidget *parent) { QSettings settings; QPoint pos = settings.value(strSetting + "Pos").toPoint(); QSize size = settings.value(strSetting + "Size", defaultSize).toSize(); parent->resize(size); parent->move(pos); if ((!pos.x() && !pos.y()) || (QApplication::desktop()->screenNumber(parent) == -1)) { QRect screen = QApplication::desktop()->screenGeometry(); QPoint defaultPos((screen.width() - defaultSize.width()) / 2, (screen.height() - defaultSize.height()) / 2); parent->resize(defaultSize); parent->move(defaultPos); } } void setClipboard(const QString& str) { QApplication::clipboard()->setText(str, QClipboard::Clipboard); QApplication::clipboard()->setText(str, QClipboard::Selection); } fs::path qstringToBoostPath(const QString &path) { return fs::path(path.toStdString(), utf8); } QString boostPathToQString(const fs::path &path) { return QString::fromStdString(path.string(utf8)); } QString formatDurationStr(int secs) { QStringList strList; int days = secs / 86400; int hours = (secs % 86400) / 3600; int mins = (secs % 3600) / 60; int seconds = secs % 60; if (days) strList.append(QString(QObject::tr("%1 d")).arg(days)); if (hours) strList.append(QString(QObject::tr("%1 h")).arg(hours)); if (mins) strList.append(QString(QObject::tr("%1 m")).arg(mins)); if (seconds || (!days && !hours && !mins)) strList.append(QString(QObject::tr("%1 s")).arg(seconds)); return strList.join(" "); } QString formatServicesStr(quint64 mask) { QStringList strList; // Just scan the last 8 bits for now. for (int i = 0; i < 8; i++) { uint64_t check = 1 << i; if (mask & check) { switch (check) { case NODE_NETWORK: strList.append("NETWORK"); break; case NODE_GETUTXO: strList.append("GETUTXO"); break; case NODE_BLOOM: strList.append("BLOOM"); break; case NODE_WITNESS: strList.append("WITNESS"); break; case NODE_XTHIN: strList.append("XTHIN"); break; default: strList.append(QString("%1[%2]").arg("UNKNOWN").arg(check)); } } } if (strList.size()) return strList.join(" & "); else return QObject::tr("None"); } QString formatPingTime(double dPingTime) { return (dPingTime == std::numeric_limits<int64_t>::max()/1e6 || dPingTime == 0) ? QObject::tr("N/A") : QString(QObject::tr("%1 ms")).arg(QString::number((int)(dPingTime * 1000), 10)); } QString formatTimeOffset(int64_t nTimeOffset) { return QString(QObject::tr("%1 s")).arg(QString::number((int)nTimeOffset, 10)); } QString formatNiceTimeOffset(qint64 secs) { // Represent time from last generated block in human readable text QString timeBehindText; const int HOUR_IN_SECONDS = 60*60; const int DAY_IN_SECONDS = 24*60*60; const int WEEK_IN_SECONDS = 7*24*60*60; const int YEAR_IN_SECONDS = 31556952; // Average length of year in Gregorian calendar if(secs < 60) { timeBehindText = QObject::tr("%n second(s)","",secs); } else if(secs < 2*HOUR_IN_SECONDS) { timeBehindText = QObject::tr("%n minute(s)","",secs/60); } else if(secs < 2*DAY_IN_SECONDS) { timeBehindText = QObject::tr("%n hour(s)","",secs/HOUR_IN_SECONDS); } else if(secs < 2*WEEK_IN_SECONDS) { timeBehindText = QObject::tr("%n day(s)","",secs/DAY_IN_SECONDS); } else if(secs < YEAR_IN_SECONDS) { timeBehindText = QObject::tr("%n week(s)","",secs/WEEK_IN_SECONDS); } else { qint64 years = secs / YEAR_IN_SECONDS; qint64 remainder = secs % YEAR_IN_SECONDS; timeBehindText = QObject::tr("%1 and %2").arg(QObject::tr("%n year(s)", "", years)).arg(QObject::tr("%n week(s)","", remainder/WEEK_IN_SECONDS)); } return timeBehindText; } void ClickableLabel::mouseReleaseEvent(QMouseEvent *event) { Q_EMIT clicked(event->pos()); } void ClickableProgressBar::mouseReleaseEvent(QMouseEvent *event) { Q_EMIT clicked(event->pos()); } } // namespace GUIUtil
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2014 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreStableHeaders.h" #include "OgreLogManager.h" #include "OgreException.h" #include <algorithm> namespace Ogre { //----------------------------------------------------------------------- template<> LogManager* Singleton<LogManager>::msSingleton = 0; LogManager* LogManager::getSingletonPtr(void) { return msSingleton; } LogManager& LogManager::getSingleton(void) { assert( msSingleton ); return ( *msSingleton ); } //----------------------------------------------------------------------- LogManager::LogManager() { mDefaultLog = NULL; } //----------------------------------------------------------------------- LogManager::~LogManager() { OGRE_LOCK_AUTO_MUTEX; // Destroy all logs LogList::iterator i; for (i = mLogs.begin(); i != mLogs.end(); ++i) { OGRE_DELETE i->second; } } //----------------------------------------------------------------------- Log* LogManager::createLog( const String& name, bool defaultLog, bool debuggerOutput, bool suppressFileOutput) { OGRE_LOCK_AUTO_MUTEX; Log* newLog = OGRE_NEW Log(name, debuggerOutput, suppressFileOutput); if( !mDefaultLog || defaultLog ) { mDefaultLog = newLog; } mLogs.insert( LogList::value_type( name, newLog ) ); return newLog; } //----------------------------------------------------------------------- Log* LogManager::getDefaultLog() { OGRE_LOCK_AUTO_MUTEX; return mDefaultLog; } //----------------------------------------------------------------------- Log* LogManager::setDefaultLog(Log* newLog) { OGRE_LOCK_AUTO_MUTEX; Log* oldLog = mDefaultLog; mDefaultLog = newLog; return oldLog; } //----------------------------------------------------------------------- Log* LogManager::getLog( const String& name) { OGRE_LOCK_AUTO_MUTEX; LogList::iterator i = mLogs.find(name); if (i != mLogs.end()) return i->second; else OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Log not found. ", "LogManager::getLog"); } //----------------------------------------------------------------------- void LogManager::destroyLog(const String& name) { LogList::iterator i = mLogs.find(name); if (i != mLogs.end()) { if (mDefaultLog == i->second) { mDefaultLog = 0; } OGRE_DELETE i->second; mLogs.erase(i); } // Set another default log if this one removed if (!mDefaultLog && !mLogs.empty()) { mDefaultLog = mLogs.begin()->second; } } //----------------------------------------------------------------------- void LogManager::destroyLog(Log* log) { if(!log) OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Cannot destroy a null log.", "LogManager::destroyLog"); destroyLog(log->getName()); } //----------------------------------------------------------------------- void LogManager::logMessage( const String& message, LogMessageLevel lml, bool maskDebug) { OGRE_LOCK_AUTO_MUTEX; if (mDefaultLog) { mDefaultLog->logMessage(message, lml, maskDebug); } } //----------------------------------------------------------------------- void LogManager::setLogDetail(LoggingLevel ll) { OGRE_LOCK_AUTO_MUTEX; if (mDefaultLog) { mDefaultLog->setLogDetail(ll); } } //--------------------------------------------------------------------- Log::Stream LogManager::stream(LogMessageLevel lml, bool maskDebug) { OGRE_LOCK_AUTO_MUTEX; if (mDefaultLog) return mDefaultLog->stream(lml, maskDebug); else OGRE_EXCEPT(Exception::ERR_INVALIDPARAMS, "Default log not found. ", "LogManager::stream"); } }
#include "stdafx.h" #include "CaptainAmericaStateManager.h" CaptainAmericaStateManager* CaptainAmericaStateManager::instance = nullptr; CaptainAmericaStateManager * CaptainAmericaStateManager::getInstance() { if (instance == nullptr) instance = new CaptainAmericaStateManager(); return instance; } CaptainAmericaStateManager::CaptainAmericaStateManager() { stateStand = new CaptainAmericaStateStand(); currentState = stateStand; instance = this; } CaptainAmericaStateManager::~CaptainAmericaStateManager() { } void CaptainAmericaStateManager::init(CaptainAmerica* captainAmerica, Input* input) { stateAttack = new CaptainAmericaStateAttack(captainAmerica, input); stateDash = new CaptainAmericaStateDash(captainAmerica, input); stateDie = new CaptainAmericaStateDie(captainAmerica, input); stateJump = new CaptainAmericaStateJump(captainAmerica, input); stateKick = new CaptainAmericaStateKick(captainAmerica, input); stateLookUp = new CaptainAmericaStateLookUp(captainAmerica, input); stateMove = new CaptainAmericaStateMove(captainAmerica, input); stateShieldlessAttack = new CaptainAmericaStateShieldlessAttack(captainAmerica, input); stateSit = new CaptainAmericaStateSit(captainAmerica, input); stateSitAttack = new CaptainAmericaStateSitAttack(captainAmerica, input); stateSpin = new CaptainAmericaStateSpin(captainAmerica, input); stateStand = new CaptainAmericaStateStand(captainAmerica, input); currentState = stateStand; } void CaptainAmericaStateManager::setOldStatus(eStatus status) { this->oldStatus = status; } eStatus CaptainAmericaStateManager::getOldStatus() { return this->oldStatus; } void CaptainAmericaStateManager::setOldState(BaseState * state) { this->oldState = state; } BaseState * CaptainAmericaStateManager::getOldState() { return this->oldState; } BaseState * CaptainAmericaStateManager::getCurrentState() { return this->currentState; } void CaptainAmericaStateManager::changeStateTo(eStatus eStatus) { if (currentState != nullptr) { oldStatus = currentState->getName(); currentState->onExit(); } switch (eStatus) { case eStatus::ATTACK: currentState = stateAttack; break; case eStatus::DASH: currentState = stateDash; break; case eStatus::DIE: currentState = stateDie; break; case eStatus::JUMP: currentState = stateJump; break; case eStatus::KICK: currentState = stateKick; break; case eStatus::LOOKUP: currentState = stateLookUp; break; case eStatus::MOVE: currentState = stateMove; break; case eStatus::SHILEDLESSATTACK: currentState = stateShieldlessAttack; break; case eStatus::SIT: currentState = stateSit; break; case eStatus::SITATTACK: currentState = stateSitAttack; break; case eStatus::SPIN: currentState = stateSpin; break; case eStatus::STAND: currentState = stateStand; break; default: break; } currentState->init(); currentState->onStart(); } void CaptainAmericaStateManager::release() { delete stateStand; delete stateMove; delete instance; }
// SceneTable.cpp: implementation of the KSceneTable class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "SceneEditor.h" #include "SceneTable.h" #include "SceneSkinEdit.h" #include ".\scenetable.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// KSceneTable::KSceneTable() { m_lpScenes = NULL; m_dMaxNumScene = 0; m_dNumScene = 0; m_lpCurScene = NULL; } KSceneTable::~KSceneTable() { } HRESULT KSceneTable::InvalidateDeviceObjects(void) { for(DWORD i=0;i<m_dNumScene;i++) { LPSCENE pScene = m_lpScenes[i]; pScene->InvalidateDeviceObjects(); } return S_OK; } HRESULT KSceneTable::RestoreDeviceObjects(void) { for(DWORD i=0;i<m_dNumScene;i++) { LPSCENE pScene = m_lpScenes[i]; pScene->RestoreDeviceObjects(); } return S_OK; } HRESULT KSceneTable::Get1NewScenePointer(LPSCENE** ppScene) { if (m_dMaxNumScene ==0 ) { m_lpScenes = new LPSCENE[5]; ZeroMemory(m_lpScenes ,sizeof(LPSCENE)*5); m_dMaxNumScene = 5; } if (m_dNumScene >= m_dMaxNumScene) { LPSCENE* Temp = m_lpScenes; m_dMaxNumScene +=5; m_lpScenes = new LPSCENE[m_dMaxNumScene]; ZeroMemory(m_lpScenes ,sizeof(LPSCENE)*m_dMaxNumScene); for(DWORD i=0;i<m_dMaxNumScene-5 ;i++) m_lpScenes[i] = Temp[i]; delete [] Temp; } m_dNumScene ++; (*ppScene) = &m_lpScenes[ m_dNumScene -1 ]; return S_OK; } HRESULT KSceneTable::Get1NewScene(DWORD Type,LPSCENE* ppScene) { LPSCENE * NewPointer = NULL; if (FAILED(Get1NewScenePointer(&NewPointer))) return E_FAIL; switch(Type) { case SCENE_DEFAULT: { (*NewPointer) = new K3DScene; if(FAILED((*NewPointer)->Initialize(this))) goto Exit_Error; break; } case SCENE_SKINEDITOR: { (*NewPointer) = new KSceneSceneEdit; if(FAILED((*NewPointer)->Initialize(this))) goto Exit_Error; break; } case SCENE_MESHEDITOR: { (*NewPointer) = new KSceneModelEditor; if(FAILED((*NewPointer)->Initialize(this))) goto Exit_Error; break; } case SCENE_OBJECTEDITOR: { (*NewPointer) = new KSceneObjectEditor; if(FAILED((*NewPointer)->Initialize(this))) goto Exit_Error; break; } case SCENE_SWORDTEST: { (*NewPointer) = new KSceneSwordTest; if(FAILED((*NewPointer)->Initialize(this))) goto Exit_Error; break; } } (*NewPointer)->ID = m_dNumScene; (*ppScene) = (*NewPointer); return S_OK; Exit_Error: (*NewPointer)->ID = m_dNumScene; (*ppScene) = (*NewPointer); return E_FAIL; } HRESULT KSceneTable::GetScene(LPSCENE* ppScene,DWORD ID) { if ((ID>m_dNumScene)||(ID==0)) return E_FAIL; (*ppScene) = m_lpScenes[ID-1]; return S_OK; } HRESULT KSceneTable::RefreshCurScene() { LPSCENE pScene = NULL; if (SUCCEEDED(GetScene(&pScene ,m_dCurSceneID))) { m_lpCurScene = pScene; } else { m_lpCurScene = NULL; } return S_OK; } HRESULT KSceneTable::SetManager(PVOID pManager) { m_pManager = pManager; return S_OK; } HRESULT KSceneTable::CleanUp(void) { for(DWORD i=0;i<m_dNumScene;i++) { LPSCENE pScene = m_lpScenes[i]; pScene->CleanUp(); SAFE_DELETE(pScene); } SAFE_DELETE_ARRAY(m_lpScenes); m_dNumScene = 0; m_dMaxNumScene = 0; g_cObjectTable.CleanUp(); g_cMeshTable.CleanUp(); g_cTextureTable.CleanUp(); m_dCurSceneID = 0; return E_NOTIMPL; }
#pragma once namespace Audio { namespace Music { enum ID { menuTheme, gameplayTheme, gameOverTheme, none }; } }
/*============================================================================ The Medical Imaging Interaction Toolkit (MITK) Copyright (c) German Cancer Research Center (DKFZ) All rights reserved. Use of this source code is governed by a 3-clause BSD license that can be found in the LICENSE file. ============================================================================*/ #include "mitkIGTLMessageQueue.h" #include <string> #include "igtlMessageBase.h" void mitk::IGTLMessageQueue::PushSendMessage(mitk::IGTLMessage::Pointer message) { this->m_Mutex->Lock(); if (this->m_BufferingType == IGTLMessageQueue::NoBuffering) m_SendQueue.clear(); m_SendQueue.push_back(message); this->m_Mutex->Unlock(); } void mitk::IGTLMessageQueue::PushCommandMessage(igtl::MessageBase::Pointer message) { this->m_Mutex->Lock(); if (this->m_BufferingType == IGTLMessageQueue::NoBuffering) m_CommandQueue.clear(); m_CommandQueue.push_back(message); this->m_Mutex->Unlock(); } void mitk::IGTLMessageQueue::PushMessage(igtl::MessageBase::Pointer msg) { this->m_Mutex->Lock(); std::stringstream infolog; infolog << "Received message of type "; if (dynamic_cast<igtl::TrackingDataMessage*>(msg.GetPointer()) != nullptr) { if (this->m_BufferingType == IGTLMessageQueue::NoBuffering) m_TrackingDataQueue.clear(); this->m_TrackingDataQueue.push_back(dynamic_cast<igtl::TrackingDataMessage*>(msg.GetPointer())); infolog << "TDATA"; } else if (dynamic_cast<igtl::TransformMessage*>(msg.GetPointer()) != nullptr) { if (this->m_BufferingType == IGTLMessageQueue::NoBuffering) m_TransformQueue.clear(); this->m_TransformQueue.push_back(dynamic_cast<igtl::TransformMessage*>(msg.GetPointer())); infolog << "TRANSFORM"; } else if (dynamic_cast<igtl::StringMessage*>(msg.GetPointer()) != nullptr) { if (this->m_BufferingType == IGTLMessageQueue::NoBuffering) m_StringQueue.clear(); this->m_StringQueue.push_back(dynamic_cast<igtl::StringMessage*>(msg.GetPointer())); infolog << "STRING"; } else if (dynamic_cast<igtl::ImageMessage*>(msg.GetPointer()) != nullptr) { igtl::ImageMessage::Pointer imageMsg = dynamic_cast<igtl::ImageMessage*>(msg.GetPointer()); int* dim = new int[3]; imageMsg->GetDimensions(dim); if (dim[2] > 1) { if (this->m_BufferingType == IGTLMessageQueue::NoBuffering) m_Image3dQueue.clear(); this->m_Image3dQueue.push_back(dynamic_cast<igtl::ImageMessage*>(msg.GetPointer())); infolog << "IMAGE3D"; } else { if (this->m_BufferingType == IGTLMessageQueue::NoBuffering) m_Image2dQueue.clear(); this->m_Image2dQueue.push_back(dynamic_cast<igtl::ImageMessage*>(msg.GetPointer())); infolog << "IMAGE2D"; } } else { if (this->m_BufferingType == IGTLMessageQueue::NoBuffering) m_MiscQueue.clear(); this->m_MiscQueue.push_back(msg); infolog << "OTHER"; } m_Latest_Message = msg; //MITK_INFO << infolog.str(); this->m_Mutex->Unlock(); } mitk::IGTLMessage::Pointer mitk::IGTLMessageQueue::PullSendMessage() { mitk::IGTLMessage::Pointer ret = nullptr; this->m_Mutex->Lock(); if (this->m_SendQueue.size() > 0) { ret = this->m_SendQueue.front(); this->m_SendQueue.pop_front(); } this->m_Mutex->Unlock(); return ret; } igtl::MessageBase::Pointer mitk::IGTLMessageQueue::PullMiscMessage() { igtl::MessageBase::Pointer ret = nullptr; this->m_Mutex->Lock(); if (this->m_MiscQueue.size() > 0) { ret = this->m_MiscQueue.front(); this->m_MiscQueue.pop_front(); } this->m_Mutex->Unlock(); return ret; } igtl::ImageMessage::Pointer mitk::IGTLMessageQueue::PullImage2dMessage() { igtl::ImageMessage::Pointer ret = nullptr; this->m_Mutex->Lock(); if (this->m_Image2dQueue.size() > 0) { ret = this->m_Image2dQueue.front(); this->m_Image2dQueue.pop_front(); } this->m_Mutex->Unlock(); return ret; } igtl::ImageMessage::Pointer mitk::IGTLMessageQueue::PullImage3dMessage() { igtl::ImageMessage::Pointer ret = nullptr; this->m_Mutex->Lock(); if (this->m_Image3dQueue.size() > 0) { ret = this->m_Image3dQueue.front(); this->m_Image3dQueue.pop_front(); } this->m_Mutex->Unlock(); return ret; } igtl::TrackingDataMessage::Pointer mitk::IGTLMessageQueue::PullTrackingMessage() { igtl::TrackingDataMessage::Pointer ret = nullptr; this->m_Mutex->Lock(); if (this->m_TrackingDataQueue.size() > 0) { ret = this->m_TrackingDataQueue.front(); this->m_TrackingDataQueue.pop_front(); } this->m_Mutex->Unlock(); return ret; } igtl::MessageBase::Pointer mitk::IGTLMessageQueue::PullCommandMessage() { igtl::MessageBase::Pointer ret = nullptr; this->m_Mutex->Lock(); if (this->m_CommandQueue.size() > 0) { ret = this->m_CommandQueue.front(); this->m_CommandQueue.pop_front(); } this->m_Mutex->Unlock(); return ret; } igtl::StringMessage::Pointer mitk::IGTLMessageQueue::PullStringMessage() { igtl::StringMessage::Pointer ret = nullptr; this->m_Mutex->Lock(); if (this->m_StringQueue.size() > 0) { ret = this->m_StringQueue.front(); this->m_StringQueue.pop_front(); } this->m_Mutex->Unlock(); return ret; } igtl::TransformMessage::Pointer mitk::IGTLMessageQueue::PullTransformMessage() { igtl::TransformMessage::Pointer ret = nullptr; this->m_Mutex->Lock(); if (this->m_TransformQueue.size() > 0) { ret = this->m_TransformQueue.front(); this->m_TransformQueue.pop_front(); } this->m_Mutex->Unlock(); return ret; } std::string mitk::IGTLMessageQueue::GetNextMsgInformationString() { this->m_Mutex->Lock(); std::stringstream s; if (this->m_Latest_Message != nullptr) { s << "Device Type: " << this->m_Latest_Message->GetDeviceType() << std::endl; s << "Device Name: " << this->m_Latest_Message->GetDeviceName() << std::endl; } else { s << "No Msg"; } this->m_Mutex->Unlock(); return s.str(); } std::string mitk::IGTLMessageQueue::GetNextMsgDeviceType() { this->m_Mutex->Lock(); std::stringstream s; if (m_Latest_Message != nullptr) { s << this->m_Latest_Message->GetDeviceType(); } else { s << ""; } this->m_Mutex->Unlock(); return s.str(); } std::string mitk::IGTLMessageQueue::GetLatestMsgInformationString() { this->m_Mutex->Lock(); std::stringstream s; if (m_Latest_Message != nullptr) { s << "Device Type: " << this->m_Latest_Message->GetDeviceType() << std::endl; s << "Device Name: " << this->m_Latest_Message->GetDeviceName() << std::endl; } else { s << "No Msg"; } this->m_Mutex->Unlock(); return s.str(); } std::string mitk::IGTLMessageQueue::GetLatestMsgDeviceType() { this->m_Mutex->Lock(); std::stringstream s; if (m_Latest_Message != nullptr) { s << this->m_Latest_Message->GetDeviceType(); } else { s << ""; } this->m_Mutex->Unlock(); return s.str(); } int mitk::IGTLMessageQueue::GetSize() { return (this->m_CommandQueue.size() + this->m_Image2dQueue.size() + this->m_Image3dQueue.size() + this->m_MiscQueue.size() + this->m_StringQueue.size() + this->m_TrackingDataQueue.size() + this->m_TransformQueue.size()); } void mitk::IGTLMessageQueue::EnableNoBufferingMode(bool enable) { this->m_Mutex->Lock(); if (enable) this->m_BufferingType = IGTLMessageQueue::BufferingType::NoBuffering; else this->m_BufferingType = IGTLMessageQueue::BufferingType::Infinit; this->m_Mutex->Unlock(); } mitk::IGTLMessageQueue::IGTLMessageQueue() { this->m_Mutex = itk::FastMutexLock::New(); this->m_BufferingType = IGTLMessageQueue::NoBuffering; } mitk::IGTLMessageQueue::~IGTLMessageQueue() { this->m_Mutex->Unlock(); }
#ifdef RAI_OPENCV #include "opencv.h" #include "opencvCamera.h" struct sOpencvCamera { cv::VideoCapture capture; }; OpencvCamera::OpencvCamera(const Var<byteA>& _rgb) : Thread(STRING("OpencvCamera_"<<_rgb.name()), 0.) , rgb(this, _rgb) { s = make_shared<sOpencvCamera>(); threadLoop(); } OpencvCamera::~OpencvCamera(){ threadClose(); } void OpencvCamera::open() { s->capture.open(0); for(std::map<int,double>::const_iterator i = properties.begin(); i != properties.end(); ++i) { if(!s->capture.set(i->first, i->second)) { cerr << "could not set property " << i->first << " to value " << i->second << endl; } } // capture.set(CV_CAP_PROP_CONVERT_RGB, 1); // cout <<"FPS of opened OpenCV VideoCapture = " <<capture.get(CV_CAP_PROP_FPS) <<endl;; } void OpencvCamera::close() { s->capture.release(); } void OpencvCamera::step() { cv::Mat img; //,imgRGB; s->capture.read(img); if(!img.empty()) { // cv::cvtColor(img, imgRGB, CV_BGR2RGB); rgb.set() = conv_cvMat2byteA(img); } } bool OpencvCamera::set(int propId, double value) { if(s) return s->capture.set(propId, value); else { properties[propId] = value; return true; // well, can't really do anything else here... } } #endif
/* ******************************************************************************* * Copyright (c) 2020-2021, STMicroelectronics * All rights reserved. * * This software component is licensed by ST under BSD 3-Clause license, * the "License"; You may not use this file except in compliance with the * License. You may obtain a copy of the License at: * opensource.org/licenses/BSD-3-Clause * ******************************************************************************* */ #if defined(ARDUINO_GENERIC_L552MEYXQ) || defined(ARDUINO_GENERIC_L562MEYXQ) #include "pins_arduino.h" // Digital PinName array const PinName digitalPin[] = { PA_0, // D0/A0 PA_1, // D1/A1 PA_2, // D2/A2 PA_3, // D3/A3 PA_4, // D4/A4 PA_5, // D5/A5 PA_6, // D6/A6 PA_7, // D7/A7 PA_8, // D8 PA_9, // D9 PA_10, // D10 PA_11, // D11 PA_12, // D12 PA_13, // D13 PA_14, // D14 PA_15, // D15 PB_0, // D16/A8 PB_1, // D17/A9 PB_2, // D18 PB_3, // D19 PB_4, // D20 PB_5, // D21 PB_6, // D22 PB_7, // D23 PB_8, // D24 PB_9, // D25 PB_10, // D26 PB_11, // D27 PB_12, // D28 PB_13, // D29 PB_14, // D30 PB_15, // D31 PC_0, // D32/A10 PC_1, // D33/A11 PC_2, // D34/A12 PC_3, // D35/A13 PC_4, // D36/A14 PC_6, // D37 PC_7, // D38 PC_8, // D39 PC_9, // D40 PC_10, // D41 PC_11, // D42 PC_12, // D43 PC_13, // D44 PC_14, // D45 PC_15, // D46 PD_2, // D47 PG_9, // D48 PG_10, // D49 PG_11, // D50 PG_12, // D51 PG_13, // D52 PG_14, // D53 PG_15, // D54 PH_0, // D55 PH_1, // D56 PH_3 // D57 }; // Analog (Ax) pin number array const uint32_t analogInputPin[] = { 0, // A0, PA0 1, // A1, PA1 2, // A2, PA2 3, // A3, PA3 4, // A4, PA4 5, // A5, PA5 6, // A6, PA6 7, // A7, PA7 16, // A8, PB0 17, // A9, PB1 32, // A10, PC0 33, // A11, PC1 34, // A12, PC2 35, // A13, PC3 36 // A14, PC4 }; #endif /* ARDUINO_GENERIC_* */
// type wrapper #include "type_wrapper.h" #include "nan_macros.h" std::map<const TypeHandle *, std::shared_ptr<const TypeHandle>> TypeWrapper::type_cache; NAN_METHOD(TypeWrapper::New) { if (!info.IsConstructCall() || info.Length() == 0 || !info[0]->IsExternal()) { return Nan::ThrowError("Cannot instantiate type directly, use factory"); } Handle<External> handle = Handle<External>::Cast(info[0]); const TypeHandle *t = static_cast<const TypeHandle *>(handle->Value()); std::shared_ptr<const TypeHandle> ty = type_cache[t]; TypeWrapper *instance = new TypeWrapper(ty); instance->Wrap(info.This()); info.GetReturnValue().Set(info.This()); } NAN_METHOD(TypeWrapper::ToString) { TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This()); std::string name = wrapper->Type->toString(); info.GetReturnValue().Set(Nan::New(name).ToLocalChecked()); } NAN_METHOD(TypeWrapper::IsCompatibleWith) { TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This()); if (info.Length() == 0 || !Nan::New(prototype)->HasInstance(info[0])) { return Nan::ThrowError("Compatibility check requires a type handle"); } TypeWrapper *other = Nan::ObjectWrap::Unwrap<TypeWrapper>(info[0].As<Object>()); bool isCompatible = self->Type->isCompatibleWith(other->Type.get()); info.GetReturnValue().Set(isCompatible); } #define TYPE_PREDICATE(name, pred) \ NAN_METHOD(TypeWrapper::name) \ { \ TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This()); \ info.GetReturnValue().Set(self->Type->pred()); \ } TYPE_PREDICATE(IsVoidType, isVoidType); TYPE_PREDICATE(IsIntType, isIntType); TYPE_PREDICATE(IsFloatType, isFloatType); TYPE_PREDICATE(IsArrayType, isArrayType); TYPE_PREDICATE(IsVectorType, isVectorType); TYPE_PREDICATE(IsStructType, isStructType); TYPE_PREDICATE(IsPointerType, isPointerType); TYPE_PREDICATE(IsFunctionType, isFunctionType); #define RETURN_IF_TYPE(cls, pred, ret) \ if (self->Type->pred()) \ { \ const cls *ty = static_cast<const cls *>(self->Type.get()); \ info.GetReturnValue().Set(ty->ret); \ } #define RETURN_IF_TYPE_W(cls, pred, ret) \ if (self->Type->pred()) \ { \ const cls *ty = static_cast<const cls *>(self->Type.get()); \ info.GetReturnValue().Set(wrapType(ty->ret)); \ } #define RETURN_IF_TYPE_R(cls, pred, source) \ if (self->Type->pred()) \ { \ const cls *ty = static_cast<const cls *>(self->Type.get()); \ \ Local<Context> ctx = Nan::GetCurrentContext(); \ \ Local<Array> types = Nan::New<Array>();\ for (unsigned i = 0, e = ty->source.size(); i < e; i += 1) \ { \ types->Set(ctx, i, wrapType(ty->source[i])); \ } \ \ info.GetReturnValue().Set(types); \ } NAN_GETTER(TypeWrapper::GetBitwidth) { TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This()); RETURN_IF_TYPE(IntTypeHandle, isIntType, numBits) RETURN_IF_TYPE(FloatTypeHandle, isFloatType, numBits) } NAN_GETTER(TypeWrapper::GetSize) { TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This()); RETURN_IF_TYPE(ArrayTypeHandle, isArrayType, size) RETURN_IF_TYPE(VectorTypeHandle, isVectorType, size) } NAN_GETTER(TypeWrapper::GetElement) { TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This()); RETURN_IF_TYPE_W(ArrayTypeHandle, isArrayType, element) RETURN_IF_TYPE_W(VectorTypeHandle, isVectorType, element) } NAN_GETTER(TypeWrapper::GetElements) { Nan::EscapableHandleScope scope; TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This()); RETURN_IF_TYPE_R(StructTypeHandle, isStructType, elements) } NAN_GETTER(TypeWrapper::GetPointee) { TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This()); RETURN_IF_TYPE_W(PointerTypeHandle, isPointerType, pointee) } NAN_GETTER(TypeWrapper::GetReturns) { TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This()); RETURN_IF_TYPE_W(FunctionTypeHandle, isFunctionType, returns) } NAN_GETTER(TypeWrapper::GetParameters) { Nan::EscapableHandleScope scope; TypeWrapper *self = Nan::ObjectWrap::Unwrap<TypeWrapper>(info.This()); RETURN_IF_TYPE_R(FunctionTypeHandle, isFunctionType, params) } Handle<Value> TypeWrapper::wrapType(std::shared_ptr<const TypeHandle> type) { const TypeHandle *ptr = type.get(); if (!type_cache.count(ptr)) { type_cache[type.get()] = std::move(type); } Nan::EscapableHandleScope scope; const unsigned argc = 1; Handle<Value> argv[argc] = { Nan::New<External>((void *)ptr) }; Local<Function> cons = Nan::New(constructor()); return scope.Escape(Nan::NewInstance(cons, argc, argv).ToLocalChecked()); } NAN_MODULE_INIT(TypeWrapper::Init) { Local<FunctionTemplate> tmpl = Nan::New<FunctionTemplate>(TypeWrapper::New); tmpl->SetClassName(Nan::New("Type").ToLocalChecked()); tmpl->InstanceTemplate()->SetInternalFieldCount(1); Nan::SetPrototypeMethod(tmpl, "toString", TypeWrapper::ToString); Nan::SetPrototypeMethod(tmpl, "isCompatibleWith", TypeWrapper::IsCompatibleWith); Nan::SetPrototypeMethod(tmpl, "isVoidType", TypeWrapper::IsVoidType); Nan::SetPrototypeMethod(tmpl, "isIntType", TypeWrapper::IsIntType); Nan::SetPrototypeMethod(tmpl, "isFloatType", TypeWrapper::IsFloatType); Nan::SetPrototypeMethod(tmpl, "isArrayType", TypeWrapper::IsArrayType); Nan::SetPrototypeMethod(tmpl, "isVectorType", TypeWrapper::IsVectorType); Nan::SetPrototypeMethod(tmpl, "isStructType", TypeWrapper::IsStructType); Nan::SetPrototypeMethod(tmpl, "isPointerType", TypeWrapper::IsPointerType); Nan::SetPrototypeMethod(tmpl, "isFunctionType", TypeWrapper::IsFunctionType); Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("bitwidth").ToLocalChecked(), GetBitwidth); Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("size").ToLocalChecked(), GetSize); Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("element").ToLocalChecked(), GetElement); Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("elements").ToLocalChecked(), GetElements); Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("pointee").ToLocalChecked(), GetPointee); Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("returns").ToLocalChecked(), GetReturns); Nan::SetAccessor(tmpl->PrototypeTemplate(), Nan::New("parameters").ToLocalChecked(), GetParameters); constructor().Reset(Nan::GetFunction(tmpl).ToLocalChecked()); Nan::Set(target, Nan::New("Type").ToLocalChecked(), Nan::GetFunction(tmpl).ToLocalChecked()); prototype.Reset(tmpl); } NAN_METHOD(TypeWrapper::GetVoidTy) { info.GetReturnValue().Set(wrapType(std::make_shared<VoidTypeHandle>())); } NAN_METHOD(TypeWrapper::GetIntTy) { if (info.Length() == 0 || !info[0]->IsNumber()) { return Nan::ThrowError("Must provide integer bit width"); } Local<Number> bitWidth = info[0].As<Number>(); double requestedBits = bitWidth->Value(); if (requestedBits < MIN_INT_BITS) { return Nan::ThrowError("Integer bit width below the minimum"); } if (requestedBits > MAX_INT_BITS) { return Nan::ThrowError("Integer bit width above the maximum"); } unsigned bits = (unsigned)requestedBits; if (bits != requestedBits) { return Nan::ThrowError("Integer bit width not valid"); } info.GetReturnValue().Set(wrapType(std::make_shared<IntTypeHandle>(bits))); } NAN_METHOD(TypeWrapper::GetFloatTy) { if (info.Length() == 0 || !info[0]->IsNumber()) { return Nan::ThrowError("Must provide float bit width"); } Local<Number> bitWidth = info[0].As<Number>(); double requestedBits = bitWidth->Value(); if (requestedBits != 16 && requestedBits != 32 && requestedBits != 64) { return Nan::ThrowError("Invalid float bit width"); } unsigned bits = (unsigned)requestedBits; info.GetReturnValue().Set(wrapType(std::make_shared<FloatTypeHandle>(bits))); } NAN_METHOD(TypeWrapper::GetPointerTy) { if (info.Length() == 0) { return Nan::ThrowError("Must provide pointee type"); } Local<Object> handle = info[0]->ToObject(); if (!Nan::New(prototype)->HasInstance(handle)) { return Nan::ThrowError("Argument must be a type specifier"); } TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(handle); info.GetReturnValue().Set(wrapType(std::make_shared<PointerTypeHandle>(wrapper->Type))); } NAN_METHOD(TypeWrapper::GetVectorTy) { unsigned size; if (info.Length() == 0 || !info[0]->IsNumber()) { return Nan::ThrowError("Must provide vector size"); } Local<Number> sizeNumber = info[0].As<Number>(); double sizeDouble = sizeNumber->Value(); size = (unsigned)sizeDouble; EXPECT_PARAM("GetVectorTy", 1, TypeWrapper, "element type") TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(info[1]->ToObject()); info.GetReturnValue().Set(wrapType(std::make_shared<VectorTypeHandle>(size, wrapper->Type))); } NAN_METHOD(TypeWrapper::GetArrayTy) { unsigned size; if (info.Length() == 0 || !info[0]->IsNumber()) { return Nan::ThrowError("Must provide array size"); } Local<Number> sizeNumber = info[0].As<Number>(); double sizeDouble = sizeNumber->Value(); size = (unsigned)sizeDouble; if (info.Length() == 1) { return Nan::ThrowError("Must provide array element type"); } Local<Object> handle = info[1]->ToObject(); if (!Nan::New(prototype)->HasInstance(handle)) { return Nan::ThrowError("Argument must be a type specifier"); } TypeWrapper *wrapper = Nan::ObjectWrap::Unwrap<TypeWrapper>(handle); info.GetReturnValue().Set(wrapType(std::make_shared<ArrayTypeHandle>(size, wrapper->Type))); } NAN_METHOD(TypeWrapper::GetStructTy) { if (info.Length() == 0) { return Nan::ThrowError("Struct type expects a list of element types"); } if (!info[0]->IsArray()) { return Nan::ThrowError("Struct type expects a list of element types"); } Local<Array> types = info[0].As<Array>(); std::vector<std::shared_ptr<const TypeHandle>> elementTypes; unsigned e = types->Length(); elementTypes.reserve(e); Local<FunctionTemplate> proto = Nan::New(prototype); for (unsigned i = 0; i < e; i += 1) { Local<Value> type = types->Get(i); if (!proto->HasInstance(type)) { return Nan::ThrowError("Struct type expects a list of element types"); } TypeWrapper *el = Nan::ObjectWrap::Unwrap<TypeWrapper>(type.As<Object>()); elementTypes.push_back(el->Type); } info.GetReturnValue().Set(wrapType(std::make_shared<StructTypeHandle>(elementTypes))); } NAN_METHOD(TypeWrapper::GetFunctionTy) { EXTRACT_FUNCTION_PARAMS(0) info.GetReturnValue().Set(wrapType(std::make_shared<FunctionTypeHandle>(returns, takes))); } Nan::Persistent<FunctionTemplate> TypeWrapper::prototype;
// Tests all operations and iterators concurrently. It doesn't check any // operation for correctness, only making sure that everything completes without // crashing. #ifdef HAVE_CONFIG_H # include "config.h" #endif #include <algorithm> #include <array> #include <atomic> #include <chrono> #include <iostream> #include <limits> #include <memory> #include <mutex> #include <random> #include <stdint.h> #include <thread> #include <chrono> #include <utility> #include <vector> #ifndef _WIN32 #include <unistd.h> #endif #include "../../src/cuckoohash_config.hh" #include "../../src/cuckoohash_map.hh" #include "../test_util.hh" typedef uint32_t KeyType; typedef std::string KeyType2; typedef uint32_t ValType; typedef int32_t ValType2; // The number of keys to size the table with, expressed as a power of // 2. This can be set with the command line flag --power size_t power = 24; size_t numkeys; // Holds 2^power // The number of threads spawned for each type of operation. This can // be set with the command line flag --thread-num size_t thread_num = 4; // Whether to disable inserts or not. This can be set with the command // line flag --disable-inserts bool disable_inserts = false; // Whether to disable deletes or not. This can be set with the command // line flag --disable-deletes bool disable_deletes = false; // Whether to disable updates or not. This can be set with the command // line flag --disable-updates bool disable_updates = false; // Whether to disable finds or not. This can be set with the command // line flag --disable-finds bool disable_finds = false; // Whether to disable resizes operations or not. This can be set with // the command line flag --disable-resizes bool disable_resizes = false; // Whether to disable iterator operations or not. This can be set with // the command line flag --disable-iterators bool disable_iterators = false; // Whether to disable statistic operations or not. This can be set with // the command line flag --disable-misc bool disable_misc = false; // Whether to disable clear operations or not. This can be set with // the command line flag --disable-clears bool disable_clears = false; // How many seconds to run the test for. This can be set with the // command line flag --time size_t test_len = 10; // The seed for the random number generator. If this isn't set to a // nonzero value with the --seed flag, the current time is used size_t seed = 0; // Whether to use strings as the key bool use_strings = false; template <class KType> class AllEnvironment { public: AllEnvironment() : table(numkeys), table2(numkeys), finished(false) { // Sets up the random number generator if (seed == 0) { seed = std::chrono::system_clock::now().time_since_epoch().count(); } std::cout << "seed = " << seed << std::endl; gen_seed = seed; } cuckoohash_map<KType, ValType> table; cuckoohash_map<KType, ValType2> table2; size_t gen_seed; std::atomic<bool> finished; }; template <class KType> void stress_insert_thread(AllEnvironment<KType> *env, size_t seed) { std::uniform_int_distribution<size_t> ind_dist; std::uniform_int_distribution<ValType> val_dist; std::uniform_int_distribution<ValType2> val_dist2; std::mt19937_64 gen(seed); while (!env->finished.load()) { // Insert a random key into the table KType k = generateKey<KType>(ind_dist(gen)); ValType v = val_dist(gen); env->table.insert(k, v); env->table2.insert(k, val_dist2(gen)); } } template <class KType> void delete_thread(AllEnvironment<KType> *env, size_t seed) { std::uniform_int_distribution<size_t> ind_dist; std::mt19937_64 gen(seed); while (!env->finished.load()) { // Run deletes on a random key. const KType k = generateKey<KType>(ind_dist(gen)); env->table.erase(k); env->table2.erase(k); } } template <class KType> void update_thread(AllEnvironment<KType> *env, size_t seed) { std::uniform_int_distribution<size_t> ind_dist; std::uniform_int_distribution<ValType> val_dist; std::uniform_int_distribution<ValType2> val_dist2; std::uniform_int_distribution<size_t> third(0, 2); std::mt19937_64 gen(seed); auto updatefn = [](ValType& v) { v += 3; }; while (!env->finished.load()) { // Run updates, update_funcs, or upserts on a random key. const KType k = generateKey<KType>(ind_dist(gen)); switch (third(gen)) { case 0: // update env->table.update(k, val_dist(gen)); env->table2.update(k, val_dist2(gen)); break; case 1: // update_fn env->table.update_fn(k, updatefn); env->table2.update_fn( k, [](ValType2& v) { v += 10; }); break; case 2: env->table.upsert(k, updatefn, val_dist(gen)); env->table2.upsert( k, [](ValType2& v) { v -= 50; }, val_dist2(gen)); } } } template <class KType> void find_thread(AllEnvironment<KType> *env, size_t seed) { std::uniform_int_distribution<size_t> ind_dist; std::mt19937_64 gen(seed); ValType v; while (!env->finished.load()) { // Run finds on a random key. const KType k = generateKey<KType>(ind_dist(gen)); env->table.find(k, v); try { env->table2.find(k); } catch (...) {} } } template <class KType> void resize_thread(AllEnvironment<KType> *env, size_t seed) { std::mt19937_64 gen(seed); // Resizes at a random time const size_t sleep_time = gen() % test_len; std::this_thread::sleep_for(std::chrono::seconds(sleep_time)); if (env->finished.load()) { return; } const size_t hashpower = env->table2.hashpower(); if (gen() & 1) { env->table.rehash(hashpower + 1); env->table.rehash(hashpower / 2); } else { env->table2.reserve((1U << (hashpower+1)) * DEFAULT_SLOT_PER_BUCKET); env->table2.reserve((1U << hashpower) * DEFAULT_SLOT_PER_BUCKET); } } template <class KType> void iterator_thread(AllEnvironment<KType> *env, size_t seed) { std::mt19937_64 gen(seed); // Runs an iteration operation at a random time const size_t sleep_time = gen() % test_len; std::this_thread::sleep_for(std::chrono::seconds(sleep_time)); if (env->finished.load()) { return; } auto lt = env->table2.lock_table(); for (auto& item : lt) { if (gen() & 1) { item.second++; } } } template <class KType> void misc_thread(AllEnvironment<KType> *env) { // Runs all the misc functions std::mt19937_64 gen(seed); while (!env->finished.load()) { env->table.size(); env->table.empty(); env->table.bucket_count(); env->table.load_factor(); env->table.hash_function(); env->table.key_eq(); } } template <class KType> void clear_thread(AllEnvironment<KType> *env, size_t seed) { std::mt19937_64 gen(seed); // Runs a clear operation at a random time const size_t sleep_time = gen() % test_len; std::this_thread::sleep_for(std::chrono::seconds(sleep_time)); if (env->finished.load()) { return; } env->table.clear(); } // Spawns thread_num threads for each type of operation template <class KType> void StressTest(AllEnvironment<KType> *env) { std::vector<std::thread> threads; for (size_t i = 0; i < thread_num; i++) { if (!disable_inserts) { threads.emplace_back(stress_insert_thread<KType>, env, env->gen_seed++); } if (!disable_deletes) { threads.emplace_back(delete_thread<KType>, env, env->gen_seed++); } if (!disable_updates) { threads.emplace_back(update_thread<KType>, env, env->gen_seed++); } if (!disable_finds) { threads.emplace_back(find_thread<KType>, env, env->gen_seed++); } if (!disable_resizes) { threads.emplace_back(resize_thread<KType>, env, env->gen_seed++); } if (!disable_iterators) { threads.emplace_back(iterator_thread<KType>, env, env->gen_seed++); } if (!disable_misc) { threads.emplace_back(misc_thread<KType>, env); } if (!disable_clears) { threads.emplace_back(clear_thread<KType>, env, env->gen_seed++); } } // Sleeps before ending the threads std::this_thread::sleep_for(std::chrono::seconds(test_len)); env->finished.store(true); for (size_t i = 0; i < threads.size(); i++) { threads[i].join(); } std::cout << "----------Results----------" << std::endl; std::cout << "Final size:\t" << env->table.size() << std::endl; std::cout << "Final load factor:\t" << env->table.load_factor() << std::endl; } int main(int argc, char** argv) { const char* args[] = {"--power", "--thread-num", "--time", "--seed"}; size_t* arg_vars[] = {&power, &thread_num, &test_len, &seed}; const char* arg_help[] = { "The number of keys to size the table with, expressed as a power of 2", "The number of threads to spawn for each type of operation", "The number of seconds to run the test for", "The seed for the random number generator" }; const char* flags[] = { "--disable-inserts", "--disable-deletes", "--disable-updates", "--disable-finds", "--disable-resizes", "--disable-iterators", "--disable-misc", "--disable-clears", "--use-strings" }; bool* flag_vars[] = {&disable_inserts, &disable_deletes, &disable_updates, &disable_finds, &disable_resizes, &disable_iterators, &disable_misc, &disable_clears, &use_strings}; const char* flag_help[] = { "If set, no inserts will be run", "If set, no deletes will be run", "If set, no updates will be run", "If set, no finds will be run", "If set, no resize operations will be run", "If set, no iterator operations will be run", "If set, no misc functions will be run", "If set, no clears will be run", "If set, the key type of the map will be std::string" }; parse_flags(argc, argv, "Runs a stress test on inserts, deletes, and finds", args, arg_vars, arg_help, sizeof(args)/sizeof(const char*), flags, flag_vars, flag_help, sizeof(flags)/sizeof(const char*)); numkeys = 1U << power; if (use_strings) { auto *env = new AllEnvironment<KeyType2>; StressTest(env); delete env; } else { auto *env = new AllEnvironment<KeyType>; StressTest(env); delete env; } return main_return_value; }
//Precompiler definitions #define _WINSOCK_DEPRECATED_NO_WARNINGS //Internal includes #include "TCPSocket.h" //External includes #include <WinSock2.h> //Creates and initializes a TCP socket instance TCPSocket::TCPSocket() { //Initialize TCP socket m_socketHandle = 0; m_connectedClientsList = vector<int>(); } //Opens the TCP socket using any available IPV4 and port const bool TCPSocket::Open() { //Create TCP socket if ((m_socketHandle = (int)socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) { //Failed to open TCP socket return false; } //Create address sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = IPV4_ANY_PORT; //Bind address to TCP socket if (bind(m_socketHandle, (const sockaddr*)&address, sizeof(address)) == SOCKET_ERROR) { //Failed to bind address to TCP socket return false; } //Successfully opened TCP socket return true; } //Opens the TCP socket using the specified IPV4 const bool TCPSocket::Open(const IPV4& ipv4) { //Create TCP socket if ((m_socketHandle = (int)socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) { //Failed to open TCP socket return false; } //Create address sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr(ipv4.GetAddress().c_str()); address.sin_port = htons(ipv4.GetPort()); //Bind address to TCP socket if (bind(m_socketHandle, (const sockaddr*)&address, sizeof(address)) == SOCKET_ERROR) { //Failed to bind address to TCP socket return false; } //Successfully opened TCP socket return true; } //Opens the TCP socket using any available IPV4 and the specified port const bool TCPSocket::Open(const unsigned short port) { //Create TCP socket if ((m_socketHandle = (int)socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) { //Failed to open TCP socket return false; } //Create address sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = INADDR_ANY; address.sin_port = htons(port); //Bind address to TCP socket if (bind(m_socketHandle, (const sockaddr*)&address, sizeof(address)) == SOCKET_ERROR) { //Failed to bind address to TCP socket return false; } //Successfully opened TCP socket return true; } //Opens the TCP socket using the specified IPV4 and any available port const bool TCPSocket::Open(const string& ipv4) { //Create TCP socket if ((m_socketHandle = (int)socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) { //Failed to open TCP socket return false; } //Create address sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr(ipv4.c_str()); address.sin_port = IPV4_ANY_PORT; //Bind address to TCP socket if (bind(m_socketHandle, (const sockaddr*)&address, sizeof(address)) == SOCKET_ERROR) { //Failed to bind address to TCP socket return false; } //Successfully opened TCP socket return true; } //Opens the TCP socket using the specified IPV4 and port const bool TCPSocket::Open(const string& ipv4, const unsigned short port) { //Create TCP socket if ((m_socketHandle = (int)socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) == INVALID_SOCKET) { //Failed to open TCP socket return false; } //Create address sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr(ipv4.c_str()); address.sin_port = htons(port); //Bind address to TCP socket if (bind(m_socketHandle, (const sockaddr*)&address, sizeof(address)) == SOCKET_ERROR) { //Failed to bind address to TCP socket return false; } //Successfully opened TCP socket return true; } //Accepts an incomming connection if one exists const bool TCPSocket::AcceptConnection() { //Create intermediary attributes sockaddr_in address; int addressLength = sizeof(address); //Accept connection int clientSocket = (int)accept(m_socketHandle, (sockaddr*)&address, &addressLength); //If the accepted connection is invalid if (clientSocket == INVALID_SOCKET) { //Failed to accept connection return false; } //Add the client to the connected clients list m_connectedClientsList.push_back(clientSocket); //Successfully accepted connection return true; } //Accepts an incomming connection if one exists and stores the clients public IPV4 address const bool TCPSocket::AcceptConnection(IPV4& publicIPV4) { //Create intermediary attributes sockaddr_in address; int addressLength = sizeof(address); //Accept connection int clientSocket = (int)accept(m_socketHandle, (sockaddr*)&address, &addressLength); //If the accepted connection is invalid if (clientSocket == INVALID_SOCKET) { //Failed to accept connection return false; } //Store cilents public IPV4 address in the specified IPV4 publicIPV4.Set(inet_ntoa(address.sin_addr), ntohs(address.sin_port)); //Add the client to the connected clients list m_connectedClientsList.push_back(clientSocket); //Successfully accepted connection return true; } //Accepts an incomming connection if one exists and stores the clients public and private IPV4 addresses const bool TCPSocket::AcceptConnection(IPV4& publicIPV4, IPV4& privateIPV4) { //Create intermediary attributes sockaddr_in address; int addressLength = sizeof(address); //Accept connection int clientSocket = (int)accept(m_socketHandle, (sockaddr*)&address, &addressLength); //If the accepted connection is invalid if (clientSocket == INVALID_SOCKET) { //Failed to accept connection return false; } //Store cilents public IPV4 address in the specified IPV4 publicIPV4.Set(inet_ntoa(address.sin_addr), ntohs(address.sin_port)); //Query sockets private IPV4 getsockname(clientSocket, (sockaddr*)&address, &addressLength); //Store clients private IPV4 address in the specified IPV4 privateIPV4.Set(inet_ntoa(address.sin_addr), ntohs(address.sin_port)); //Add the client to the connected clients list m_connectedClientsList.push_back(clientSocket); //Successfully accepted connection return true; } //Closes the TCP socket instance const bool TCPSocket::Close() { //Close TCP socket if (closesocket(m_socketHandle) == NO_ERROR) { //Successfully closed TCP socket return true; } //Failed to close TCP socket return false; } //Connects the TCP socket to the specified host void TCPSocket::ConnectTo(const IPV4& ipv4) { //Create address sockaddr_in address; address.sin_family = AF_INET; address.sin_addr.s_addr = inet_addr(ipv4.GetAddress().c_str()); address.sin_port = htons(ipv4.GetPort()); //Connect to the specified host connect(m_socketHandle, (const sockaddr*)&address, sizeof(address)); } //Connects the TCP socket to the specified host //If the specified hostURL cannot resolve an IPV4 the host URL is used as an IPV4 void TCPSocket::ConnectTo(const URL& hostURL) { //Create address sockaddr_in address; address.sin_family = AF_INET; address.sin_port = htons(0); //Query host data hostent* hostData = gethostbyname(hostURL.GetHostname().c_str()); //If the host data is valid if (hostData != nullptr) { //Use the specified hosts IPV4 address.sin_addr.s_addr = *(u_long*)hostData->h_addr_list[0]; } //Otherwise else { //Use the specified hostname converted to an IPV4 address.sin_addr.s_addr = inet_addr(hostURL.GetHostname().c_str()); } //Connect to the specified host connect(m_socketHandle, (const sockaddr*)&address, sizeof(address)); } //Connects the TCP socket to the specified host //If the specified hostname cannot resolve an IPV4 the hostname is used as an IPV4 void TCPSocket::ConnectTo(const string& hostname) { //Create address sockaddr_in address; address.sin_family = AF_INET; address.sin_port = htons(0); //Query host data hostent* hostData = gethostbyname(hostname.c_str()); //If the host data is valid if (hostData != nullptr) { //Use the specified hosts IPV4 address.sin_addr.s_addr = *(u_long*)hostData->h_addr_list[0]; } //Otherwise else { //Use the specified hostname converted to an IPV4 address.sin_addr.s_addr = inet_addr(hostname.c_str()); } //Connect to the specified host connect(m_socketHandle, (const sockaddr*)&address, sizeof(address)); } //Connects the TCP socket to the specified host and port //If the specified hostURL cannot resolve an IPV4 the host URL is used as an IPV4 void TCPSocket::ConnectTo(const URL& hostURL, const unsigned short port) { //Create address sockaddr_in address; address.sin_family = AF_INET; address.sin_port = htons(port); //Query host data hostent* hostData = gethostbyname(hostURL.GetHostname().c_str()); //If the host data is valid if (hostData != nullptr) { //Use the specified hosts IPV4 address.sin_addr.s_addr = *(u_long*)hostData->h_addr_list[0]; } //Otherwise else { //Use the specified hostname converted to an IPV4 address.sin_addr.s_addr = inet_addr(hostURL.GetHostname().c_str()); } //Connect to the specified host connect(m_socketHandle, (const sockaddr*)&address, sizeof(address)); } //Connects the TCP socket to the specified host and port //If the specified hostname cannot resolve an IPV4 the hostname is used as an IPV4 void TCPSocket::ConnectTo(const string& hostname, const unsigned short port) { //Create address sockaddr_in address; address.sin_family = AF_INET; address.sin_port = htons(port); //Query host data hostent* hostData = gethostbyname(hostname.c_str()); //If the host data is valid if (hostData != nullptr) { //Use the specified hosts IPV4 address.sin_addr.s_addr = *(u_long*)hostData->h_addr_list[0]; } //Otherwise else { //Use the specified hostname converted to an IPV4 address.sin_addr.s_addr = inet_addr(hostname.c_str()); } //Connect to the specified host connect(m_socketHandle, (const sockaddr*)&address, sizeof(address)); } //Returns a flag indicating whether the TCP socket is connected to a host const bool TCPSocket::ConnectedToHost() { //Create buffer char buffer; //Query connection status int receivedBytes = recv(m_socketHandle, &buffer, 1, MSG_PEEK); //If the socket is not connected to a host if (receivedBytes == SOCKET_ERROR || receivedBytes == 0) { //Socket is not connected to a host return false; } //Socket is connected to a host return true; } //Disables blocking by the TCP socket instance const bool TCPSocket::DisableBlocking() { //Create non-blocking flag DWORD nonBlocking = 1; //Disable blocking by the TCP socket if (ioctlsocket(m_socketHandle, FIONBIO, &nonBlocking) == NO_ERROR) { //Successfully disabled blocking return true; } //Failed to disable blocking return false; } //Disables TCP socket from listening for incomming connections const bool TCPSocket::DisableIncommingConnections() const { //Disable TCP socket from listening for incomming connections if (listen(m_socketHandle, 0) == SOCKET_ERROR) { //Failed to disable incomming connections return false; } //Successfully disabled incomming connections return true; } //Disconnects the TCP socket from the connected host const bool TCPSocket::Disconnect() { //Disconnect the TCP socket from the connected host if (shutdown(m_socketHandle, SD_SEND) == NO_ERROR) { //Successfully disconnected from the connected host return true; } //Failed to disconnect from the connected host return false; } //Disconnects the client at the specified index in the connected clients list void TCPSocket::DisconnectClientAtIndex(const unsigned int index) { //Erase the client at the specified index in the connect client list m_connectedClientsList.erase(m_connectedClientsList.begin() + index); } //Enables blocking by the TCP socket instance const bool TCPSocket::EnableBlocking() { //Create blocking flag DWORD blocking = 0; //Enable blocking by the TCP socket if (ioctlsocket(m_socketHandle, FIONBIO, &blocking) == NO_ERROR) { //Successfully enabled blocking return true; } //Failed to enable blocking return false; } //Enables TCP socket listening for incoming connections const bool TCPSocket::EnableIncommingConnections() const { //Enable TCP socket listening for incomming connections if (listen(m_socketHandle, SOMAXCONN) == SOCKET_ERROR) { //Failed to enable incomming connections return false; } //Successfully enabled incomming connections return true; } //Returns the number of clients connected to the TCP socket const unsigned int TCPSocket::GetClientCount() { //Return the number of clients connected to the TCP socket return (unsigned int)m_connectedClientsList.size(); } //Returns the clients public IPV4 address at the specified index in the connected clients list const IPV4 TCPSocket::GetClientPublicIPV4(const unsigned int index) { //Create intermediary values sockaddr_in address; int addressLength = sizeof(address); //Query the client TCP sockets public address getpeername(m_connectedClientsList[index], (sockaddr*)&address, &addressLength); //Return the clients public IPV4 return IPV4(inet_ntoa(address.sin_addr), ntohs(address.sin_port)); } //Returns the clients private IPV4 address at the specified index in the connected clients list const IPV4 TCPSocket::GetClientPrivateIPV4(const unsigned int index) { //Create intermediary values sockaddr_in address; int addressLength = sizeof(address); //Query the client TCP sockets private address getsockname(m_connectedClientsList[index], (sockaddr*)&address, &addressLength); //Return the clients private IPV4 return IPV4(inet_ntoa(address.sin_addr), ntohs(address.sin_port)); } //Returns the TCP sockets public IPV4 const IPV4 TCPSocket::GetPublicIPV4() { //Create intermediary values sockaddr_in address; int addressLength = sizeof(address); //Query the TCP sockets public address getpeername(m_socketHandle, (sockaddr*)&address, &addressLength); //Return the TCP sockets public IPV4 return IPV4(inet_ntoa(address.sin_addr), ntohs(address.sin_port)); } //Returns the TCP sockets private IPV4 const IPV4 TCPSocket::GetPrivateIPV4() { //Create intermediary values sockaddr_in address; int addressLength = sizeof(address); //Query the TCP sockets private address getsockname(m_socketHandle, (sockaddr*)&address, &addressLength); //Return the TCP sockets private IPV4 return IPV4(inet_ntoa(address.sin_addr), ntohs(address.sin_port)); } //Receives a packet if one is available from the connected host const bool TCPSocket::ReceivePacket(void* packetData, const int packetSize) { //Receive packet int receivedBytes = recv(m_socketHandle, (char*)packetData, packetSize, 0); //If all the packet data was received if (receivedBytes == packetSize) { //Successfully received packet return true; } //Failed to receive packet return false; } //Receives a packet if one is available from the client at the specified index in the connected clients list const bool TCPSocket::ReceivePacketFromClientAt(const unsigned int index, void* packetData, const int packetSize) { //Receive packet from the client at the specified index in the connected clients list int receivedBytes = recv(m_connectedClientsList[index], (char*)packetData, packetSize, 0); //If all of the packet data was received if (receivedBytes == packetSize) { //Successfully received packet return true; } //Failed to receive packet return false; } //Sends a packet to the connected server const bool TCPSocket::SendPacket(void* packetData, const int packetSize) { //Send packet to connected server int sentBytes = send(m_socketHandle, (const char*)packetData, packetSize, 0); //If all of the packet sent if (sentBytes == packetSize) { //Successfully sent packet return true; } //Failed to send packet return false; } //Sends a packet to the client at the specified index in the connected clients list const bool TCPSocket::SendPacketToClientAt(const unsigned int index, void* packetData, const int packetSize) { //Send packet to the client at the specified index in the connected clients list int sentBytes = send(m_connectedClientsList[index], (const char*)packetData, packetSize, 0); //If all of the packet sent if (sentBytes == packetSize) { //successfully sent packet return true; } //Failed to send packet return false; }
#define CATCH_CONFIG_MAIN #include "catch.hpp" #include "DDDG.h" #include "file_func.h" #include "Scratchpad.h" #include "ScratchpadDatapath.h" SCENARIO("Test removeInductionVariable w/ Triad", "[triad]") { GIVEN("Test Triad w/ Input Size 128") { std::string bench("outputs/triad-128"); std::string trace_file("inputs/triad-128-trace"); std::string config_file("inputs/config-triad-p2-u2-P1"); ScratchpadDatapath *acc; Scratchpad *spad; acc = new ScratchpadDatapath(bench, trace_file, config_file, CYCLE_TIME); spad = new Scratchpad(1, CYCLE_TIME); acc->setScratchpad(spad); acc->setGlobalGraph(); WHEN("Test removeInductionDependence()") { acc->removeInductionDependence(); THEN("Addition w/ Induction Variable should be converted to LLVM_IR_IndexAdd.") { REQUIRE(acc->getMicroop(10) == LLVM_IR_IndexAdd); REQUIRE(acc->getMicroop(22) == LLVM_IR_IndexAdd); REQUIRE(acc->getMicroop(1534) == LLVM_IR_IndexAdd); } } } } SCENARIO("Test removeInductionVariable w/ Reduction", "[reduction]") { GIVEN("Test Reduction w/ Input Size 128") { std::string bench("outputs/reduction-128"); std::string trace_file("inputs/reduction-128-trace"); std::string config_file("inputs/config-reduction-p4-u4-P1"); ScratchpadDatapath *acc; Scratchpad *spad; acc = new ScratchpadDatapath(bench, trace_file, config_file, CYCLE_TIME); spad = new Scratchpad(1, CYCLE_TIME); acc->setScratchpad(spad); acc->setGlobalGraph(); WHEN("Test removeInductionDependence()") { acc->removeInductionDependence(); THEN("Addition w/ Induction Variable should be converted to LLVM_IR_IndexAdd.") { REQUIRE(acc->getMicroop(6) == LLVM_IR_IndexAdd); REQUIRE(acc->getMicroop(22) == LLVM_IR_IndexAdd); REQUIRE(acc->getMicroop(1022) == LLVM_IR_IndexAdd); } } } } SCENARIO("Test removeInductionVariable w/ Pp_scan", "[pp_scan]") { GIVEN("Test Pp_scan w/ Input Size 128") { std::string bench("outputs/pp_scan-128"); std::string trace_file("inputs/pp_scan-128-trace"); std::string config_file("inputs/config-pp_scan-p4-u4-P1"); ScratchpadDatapath *acc; Scratchpad *spad; acc = new ScratchpadDatapath(bench, trace_file, config_file, CYCLE_TIME); spad = new Scratchpad(1, CYCLE_TIME); acc->setScratchpad(spad); acc->setGlobalGraph(); WHEN("Test removeInductionDependence()") { acc->removeInductionDependence(); THEN("Addition w/ Induction Variable should be converted to LLVM_IR_IndexAdd.") { REQUIRE(acc->getMicroop(28) == LLVM_IR_IndexAdd); REQUIRE(acc->getMicroop(1492) == LLVM_IR_IndexAdd); REQUIRE(acc->getMicroop(1750) == LLVM_IR_IndexAdd); } } } }
/*********************************************************************************************************************** * OpenStudio(R), Copyright (c) 2008-2017, Alliance for Sustainable Energy, LLC. 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 of the copyright holder nor the names of any contributors may be used to endorse or promote * products derived from this software without specific prior written permission from the respective party. * * (4) Other than as required in clauses (1) and (2), distributions in any form of modifications or other derivative * works may not use the "OpenStudio" trademark, "OS", "os", or any other confusingly similar designation without * specific prior written permission from Alliance for Sustainable Energy, LLC. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER, THE UNITED STATES GOVERNMENT, OR ANY 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 MODEL_SETPOINTMANAGERSINGLEZONEHEATING_IMPL_HPP #define MODEL_SETPOINTMANAGERSINGLEZONEHEATING_IMPL_HPP #include <model/ModelAPI.hpp> #include "SetpointManager_Impl.hpp" namespace openstudio { namespace model { // TODO: Check the following class names against object getters and setters. class ThermalZone; class Node; namespace detail { /** SetpointManagerSingleZoneHeating_Impl is a SetpointManager_Impl that is the implementation class for SetpointManagerSingleZoneHeating.*/ class MODEL_API SetpointManagerSingleZoneHeating_Impl : public SetpointManager_Impl { public: /** @name Constructors and Destructors */ //@{ SetpointManagerSingleZoneHeating_Impl(const IdfObject& idfObject, Model_Impl* model, bool keepHandle); SetpointManagerSingleZoneHeating_Impl(const openstudio::detail::WorkspaceObject_Impl& other, Model_Impl* model, bool keepHandle); SetpointManagerSingleZoneHeating_Impl(const SetpointManagerSingleZoneHeating_Impl& other, Model_Impl* model, bool keepHandle); virtual ~SetpointManagerSingleZoneHeating_Impl() {} //@} /** @name Virtual Methods */ //@{ virtual const std::vector<std::string>& outputVariableNames() const override; virtual IddObjectType iddObjectType() const override; //@} /** @name Getters */ //@{ double minimumSupplyAirTemperature() const; double maximumSupplyAirTemperature() const; boost::optional<ThermalZone> controlZone() const; //@} /** @name Setters */ //@{ void setMinimumSupplyAirTemperature(double minimumSupplyAirTemperature); void setMaximumSupplyAirTemperature(double maximumSupplyAirTemperature); bool setControlZone(const ThermalZone& thermalZone); void resetControlZone(); //@} /** @name Other */ //@{ bool addToNode(Node & node) override; virtual std::string controlVariable() const override; virtual bool setControlVariable( const std::string & value ) override; virtual boost::optional<Node> setpointNode() const override; /** This is used to set the field SetpointNodeName. * Use addToNode to add a setpoint manager to a node. */ virtual bool setSetpointNode( const Node & node ) override; /** This is used to reset the field SetpointNodeName. */ virtual void resetSetpointNode() override; //@} protected: private: REGISTER_LOGGER("openstudio.model.SetpointManagerSingleZoneHeating"); }; } // detail } // model } // openstudio #endif // MODEL_SETPOINTMANAGERSINGLEZONEHEATING_IMPL_HPP
/* * Copyright (c) 2008 Princeton University * 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 copyright holders 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. * * Authors: Niket Agarwal */ #include "mem/ruby/network/garnet/fixed-pipeline/GarnetNetwork_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/InputUnit_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/OutputUnit_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/Router_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/SWallocator_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/NetworkInterface_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/NetworkLink_d.hh" #include "mem/ruby/network/garnet/fixed-pipeline/VCallocator_d.hh" #define PRIORITY_SCHED 1 SWallocator_d::SWallocator_d(Router_d *router) : Consumer(router) { m_router = router; m_num_vcs = m_router->get_num_vcs(); m_vc_per_vnet = m_router->get_vc_per_vnet(); m_local_arbiter_activity = 0; m_global_arbiter_activity = 0; m_local_arbiter_activity_resettable = 0; m_global_arbiter_activity_resettable = 0; this->setEventPrio(Event::NOC_SWAllocator_Pri); } void SWallocator_d::init() { m_input_unit = m_router->get_inputUnit_ref(); m_output_unit = m_router->get_outputUnit_ref(); m_num_inports = m_router->get_num_inports(); m_num_outports = m_router->get_num_outports(); m_round_robin_outport.resize(m_num_outports); m_round_robin_inport.resize(m_num_inports); m_port_req.resize(m_num_outports); m_vc_winners.resize(m_num_outports); // to implement the fast switch m_outport_busy.resize(m_num_outports); m_inport_credit_busy.resize(m_num_inports); // to implement the wormhole flow control in a vc architecture m_wh_path_busy.resize(m_num_inports); for(int i=0;i< m_num_inports;i++) { m_wh_path_busy[i].resize(m_router->get_num_vcs()); for(int j=0;j<m_router->get_num_vcs();j++) { m_wh_path_busy[i][j].resize(m_num_outports); for(int r=0;r<m_num_outports;r++) { m_wh_path_busy[i][j][r]=false; } } } /////////////////////////////////////////////////////////////// for (int i = 0; i < m_num_inports; i++) { m_round_robin_inport[i] = 0; } for (int i = 0; i < m_num_outports; i++) { m_port_req[i].resize(m_num_inports); m_vc_winners[i].resize(m_num_inports); m_round_robin_outport[i] = 0; for (int j = 0; j < m_num_inports; j++) { m_port_req[i][j] = false; // [outport][inport] } } #if PRIORITY_SCHED == 1 m_priority_invc.resize(m_num_inports); for(int inport = 0;inport<m_num_inports;inport++) { m_priority_invc[inport].resize(m_num_vcs); for(int invc = 0;invc < m_num_vcs;invc++) { m_priority_invc[inport][invc]=0; } } #endif } void SWallocator_d::wakeup() { #if PRIORITY_SCHED == 1 for(int inp=0;inp<m_num_inports;inp++) { for(int inv=0;inv<m_num_vcs;inv++) { get_invc_priority(inp,inv); } } #endif #if USE_LRC==1 //NOTE not at the beginning of the function otherwise some B and T flits //can participate SA in the same cycle they are written but this is not //correct. std::vector<InputUnit_d *>& ip_vect = m_router->get_inputUnit_ref(); for(int i=0;i<ip_vect.size();i++) ip_vect[i]->wakeup_LRC_BW(); // // directly ask for a VA stage in this cycle when everybody has been // // written // if(m_router->calledVAthisCycle<curTick()) // { // (m_router->getVCallocatorUnit())->wakeup(); // m_router->calledVAthisCycle=curTick(); //call va once per cycle // } #endif bool skip=false; if(!m_router->getPowerStateSW(0)) { skip=true; } if( m_router->getTickChangePowerStateSW()==curTick() && m_router->getPowerStateSW(0) && !m_router->getNextPowerStateSW(0) ) {// switch is switching off but not yet happened due to eventqueue order skip=true; } if( m_router->getTickChangePowerStateSW()==curTick() && !m_router->getPowerStateSW(0) && m_router->getNextPowerStateSW(0) ) { // switch is switching on but not yet happened due to eventqueue order //use this to avoid losing one cycle skip=false; } if (skip) { DPRINTF(RubyPowerGatingSA, "@%lld Router_%d->SA WAIT FOR SWITCH SW_POWER_STATE %d NEXT_SW_STATE %d cycle %lld\n ", m_router->curCycle(),m_router->get_id(),m_router->getPowerStateSW(0), m_router->getNextPowerStateSW(0)); scheduleEvent(1); } else { /* check if a single outlink is busy and evanutally stall the pipeline: easier to implement router looses performance. A performance oriented method avoids sa on busy out links only. */ #if USE_SLOW_SWITCH==1 bool is_one_out_busy=false; #endif for(int i=0;i<m_output_unit.size();i++) { Resynchronizer *r=m_output_unit.at(i)->getOutLink_d()->getReshnchronizer(); if(r->isAcknowledgeAvailable()) r->clearAcknowledge(); m_outport_busy[i]=false; if(r->isAcknowkedgePending()) { r->advanceTransmitSide(); #if USE_SLOW_SWITCH==1 is_one_out_busy=true; #endif m_outport_busy[i]=true; } } for(int i=0;i<m_input_unit.size();i++) { Resynchronizer *r=m_input_unit.at(i)->getCreditLink_d()->getReshnchronizer(); if(r->isAcknowledgeAvailable()) r->clearAcknowledge(); m_inport_credit_busy[i]=false; if(r->isAcknowkedgePending()) { r->advanceTransmitSide(); #if USE_SLOW_SWITCH==1 is_one_out_busy=true; #endif m_inport_credit_busy[i]=true; } } #if USE_SLOW_SWITCH==1 if(is_one_out_busy==true) {/*stall router pipeline if one outlink busy*/ scheduleEvent(1); } else { #endif // check to release reserved paths #if USE_WH_VC_SA == 1 #if USE_RELEASE_PATH_OPT == 1 checkAndReleaseReservedPath(); #endif #endif // standard sa arbitration stage arbitrate_inports(); // First stage of allocation arbitrate_outports(); // Second stage of allocation clear_request_vector(); check_for_wakeup(); #if USE_SLOW_SWITCH==1 } #endif } #if USE_LRC==1 // ask for a VA stage in this cycle only after sa to allow // non-speculative request to be allocated first if(m_router->calledVAthisCycle<curTick()) { (m_router->getVCallocatorUnit())->wakeup(); m_router->calledVAthisCycle=curTick(); //call va once per cycle } #endif } void SWallocator_d::get_invc_priority(int inport_iter, int invc_iter) //method that get priority for [input port][input vc] { int invc_prio = m_input_unit[inport_iter]->get_vc_priority(invc_iter); m_priority_invc[inport_iter][invc_iter]=invc_prio; } std::deque<std::pair<int,int>> SWallocator_d::get_priority_vector() { std::deque<std::pair<int,int>> priorities; int max_prio=0; for(int inport=0;inport<m_num_inports;inport++) { for(int invc=0;invc<m_num_vcs;invc++) { if(m_priority_invc[inport][invc]>=max_prio) max_prio=m_priority_invc[inport][invc]; } } for(int i=max_prio;i>=0;i--) { for(int inport=0;inport<m_num_inports;inport++) { for(int invc=0;invc<m_num_vcs;invc++) { if(m_priority_invc[inport][invc]==i&&(std::find(priorities.begin(),priorities.end(),std::pair<int,int>(inport,invc))==priorities.end())) { priorities.push_back(std::pair<int,int>(inport,invc)); } } } } return priorities; } void SWallocator_d::checkAndReleaseReservedPath() { for(int i = 0; i < m_num_inports; i++) for(int j=0; j<m_router->get_num_vcs();j++) for(int q = 0; q < m_num_outports; q++) if(m_wh_path_busy[i][j][q] == true) { int outvc_test = m_input_unit[i]->get_outvc(j); if(!m_input_unit[i]->need_stage(j, ACTIVE_, SA_,m_router->curCycle()) || m_output_unit[q]->get_credit_cnt(outvc_test)==0) {// release path if no flit for sa in ibuf OR no credit in the corresponding (OP,OutVC) m_wh_path_busy[i][j][q] = false; } } } void SWallocator_d::arbitrate_inports() { #if DEBUG_WH_VC_SA==1 #if USE_WH_VC_SA==0 panic("\n\nDEBUG_WH_VC_SA==1 while the strategy is not active USE_WH_VC_SA == 0\n\n"); #endif for(int i = 0; i < m_num_inports; i++) { int reserved_on_each_input=0; for(int j=0; j<m_router->get_num_vcs();j++) for(int q = 0; q < m_num_outports; q++) if(m_wh_path_busy[i][j][q] == true) reserved_on_each_input++; if(reserved_on_each_input>1) panic("\n\nDEBUG_WH_VC_SA - multiple path reserved for the same input port\n\n"); } for(int i = 0; i < m_num_outports; i++) { int reserved_on_each_output=0; for(int j=0; j<m_router->get_num_vcs();j++) for(int q = 0; q < m_num_inports; q++) if(m_wh_path_busy[i][j][q] == true) reserved_on_each_output++; if(reserved_on_each_output>1) panic("\n\nDEBUG_WH_VC_SA - multiple path reserved for the same output port\n\n"); } #endif #if PRIORITY_SCHED == 1 std::deque<std::pair<int,int>> priorities=get_priority_vector(); for(int prio=0;prio<priorities.size();prio++) { int inport = priorities[prio].first; if(m_inport_credit_busy[inport]) {// fast switch implementation continue; } int invc = priorities[prio].second; if (!((m_router->get_net_ptr())->validVirtualNetwork(get_vnet(invc)))) continue; int outvc_test = m_input_unit[inport]->get_outvc(invc); int outport_test = m_input_unit[inport]->get_route(invc); //Speculative statistics: SA request not satisfied because no credit in outport if (m_input_unit[inport]->need_stage(invc, ACTIVE_, SA_, m_router->curCycle()) && m_output_unit[outport_test]->get_credit_cnt(outvc_test)==0) { Router_d::incSaNoCredGlobalCountStatic(); m_router->incSaNoCredLocalCount(); } if (m_input_unit[inport]->need_stage(invc, ACTIVE_, SA_, m_router->curCycle()) && m_output_unit[outport_test]->get_credit_cnt(outvc_test)>0) { if (is_candidate_inport(inport, invc)) { //Speculative statistics Router_d::incSaGlobalCountStatic(); m_router->incSaLocalCount(); int outport = m_input_unit[inport]->get_route(invc); m_local_arbiter_activity++; m_local_arbiter_activity_resettable++; m_port_req[outport][inport] = true; // m_round_robin_inport[inport]=invc; m_vc_winners[outport][inport]= invc; break; // got one vc winner for this port }//end if } } #else // First do round robin arbitration on a set of input vc requests for (int inport = 0; inport < m_num_inports; inport++) { if(m_inport_credit_busy[inport]) {// fast switch implementation continue; } int invc = m_round_robin_inport[inport]; for (int invc_iter = 0; invc_iter < m_num_vcs; invc_iter++) { invc++; if (invc >= m_num_vcs) invc = 0; if (!((m_router->get_net_ptr())->validVirtualNetwork(get_vnet(invc)))) continue; int outvc_test = m_input_unit[inport]->get_outvc(invc); int outport_test = m_input_unit[inport]->get_route(invc); //Speculative statistics: SA request not satisfied because no credit in outport if (m_input_unit[inport]->need_stage(invc, ACTIVE_, SA_, m_router->curCycle()) && m_output_unit[outport_test]->get_credit_cnt(outvc_test)==0) { Router_d::incSaNoCredGlobalCountStatic(); m_router->incSaNoCredLocalCount(); } #if USE_VICHAR==1 if (m_input_unit[inport]->need_stage(invc, ACTIVE_, SA_, m_router->curCycle()) && m_output_unit[outport_test]->getAvailSlotPerVnet(outvc_test/m_vc_per_vnet)>0) #else if (m_input_unit[inport]->need_stage(invc, ACTIVE_, SA_, m_router->curCycle()) && m_output_unit[outport_test]->get_credit_cnt(outvc_test)>0) #endif //if (m_input_unit[inport]->need_stage(invc, ACTIVE_, SA_, m_router->curCycle()) && m_input_unit[inport]->has_credits(invc)) { if (is_candidate_inport(inport, invc)) { //Speculative statistics Router_d::incSaGlobalCountStatic(); m_router->incSaLocalCount(); int outport = m_input_unit[inport]->get_route(invc); #if USE_WH_VC_SA==1 // check to use inport for a reserved path at most bool reserved = false; for(int j=0; j<m_router->get_num_vcs();j++) for(int i = 0; i < m_num_outports; i++) if ( (j!=invc || i!=outport) && m_wh_path_busy[inport][j][i] == true) { reserved = true; break; } if (reserved) { continue; } #endif m_local_arbiter_activity++; m_local_arbiter_activity_resettable++; m_port_req[outport][inport] = true; m_round_robin_inport[inport]=invc; m_vc_winners[outport][inport]= invc; break; // got one vc winner for this port }//end if } } } #endif } bool SWallocator_d::is_candidate_inport(int inport, int invc) { int outport = m_input_unit[inport]->get_route(invc); int t_enqueue_time = m_input_unit[inport]->get_enqueue_time(invc); int t_vnet = get_vnet(invc); int vc_base = t_vnet*m_vc_per_vnet; if ((m_router->get_net_ptr())->isVNetOrdered(t_vnet)) { for (int vc_offset = 0; vc_offset < m_vc_per_vnet; vc_offset++) { int temp_vc = vc_base + vc_offset; if (m_input_unit[inport]->need_stage(temp_vc, ACTIVE_, SA_, m_router->curCycle()) && (m_input_unit[inport]->get_route(temp_vc) == outport) && (m_input_unit[inport]->get_enqueue_time(temp_vc) < t_enqueue_time)) { return false; break; } } } return true; } void SWallocator_d::arbitrate_outports() { #if DEBUG_WH_VC_SA std::vector<bool> released_path_input; std::vector<bool> released_path_output; released_path_input.resize(m_num_inports); for(int i=0;i<m_num_inports;i++) released_path_input[i]=false; released_path_output.resize(m_num_outports); for(int j=0;j<m_num_outports;j++) released_path_output[j]=false; #endif // Now there are a set of input vc requests for output vcs. // Again do round robin arbitration on these requests #if PRIORITY_SCHED ==1 std::deque<std::pair<int,int>> priorities=get_priority_vector(); /** for(int p=0;p<priorities.size();p++) { std::cout<<"<inport,invc>:"<<priorities[p].first<<","<<priorities[p].second<<"with prio:"<<m_priority_invc[priorities[p].first][priorities[p].second]<<std::endl; } **/ for (int prio = 0; prio < priorities.size(); prio++) { int inport = priorities[prio].first; for (int outport = 0; outport < m_num_outports; outport++) { if(m_outport_busy[outport]) {// fast switch constraint continue; } // inport has a request this cycle for outport: if (m_port_req[outport][inport]) { m_port_req[outport][inport] = false; int invc = m_vc_winners[outport][inport]; int outvc = m_input_unit[inport]->get_outvc(invc); // update round_robin_information for arbiters// // remove flit from Input Unit flit_d *t_flit = m_input_unit[inport]->getTopFlit(invc); // DEBUG PRINT PIPELINE STAGE m_router->print_pipeline_state(t_flit, "SW WON"); t_flit->advance_stage(ST_, m_router->curCycle()); t_flit->set_vc(outvc); t_flit->set_outport(outport); t_flit->set_time(m_router->curCycle() + 1); // std::cout<<"granted to traverse switch inport:"<<inport<<" vc:"<<invc<<std::endl; m_output_unit[outport]->decrement_credit(outvc); m_router->update_sw_winner(inport, t_flit); m_global_arbiter_activity++; m_global_arbiter_activity_resettable++; bool free_signal_fast = true; if ((t_flit->get_type() == TAIL_) || t_flit->get_type() == HEAD_TAIL_) { /*NON_ATOMIC_VC_ALLOC since the VA is the only stage that can trigger the non atomic vc allocation it is same to update the variables here. */ if(m_output_unit[outport]->get_vc_counter_pkt(outvc, m_router->curCycle()) > 0 ) { //TODO move to VA : set VNETID-novnetid && m_output_unit[outport]->dec_vc_counter_pkt(outvc); m_output_unit[outport]->set_vc_busy_to_vnet_id(outvc, t_flit->get_vnet()); } assert(m_input_unit[inport]->isReady(invc, m_router->curCycle()) == false); m_input_unit[inport]->set_vc_state(IDLE_, invc, m_router->curCycle()); m_input_unit[inport]->increment_credit(invc, true, free_signal_fast,m_router->curCycle()); m_input_unit[inport]->set_enqueue_time(invc, INFINITE_); /*congestion metrics starting cycle evaluation*/ Router_d::CongestionMetrics& cm1=m_router->getC1Matrix().at(inport*m_num_vcs+invc).at(m_input_unit[inport]->get_route(invc)); //assert(cm1.t_start!=-1); cm1.count+=m_router->curCycle()-cm1.t_start; cm1.t_start=Cycles(-1); Router_d::CongestionMetrics& cm2= m_router->getC2Matrix().at(invc).at(m_input_unit[inport]->get_route(invc)); //assert(cm2.t_start!=-1); cm2.count+=m_router->curCycle()-cm1.t_start; cm1.t_start=Cycles(-1); /*end congestion*/ } else /*winner flit not an HEAD_TAIL_ or TAIL_*/ { m_input_unit[inport]->increment_credit(invc, false, free_signal_fast,m_router->curCycle()); } break; // got a in request for this outport } } } #else for (int outport = 0; outport < m_num_outports; outport++) { if(m_outport_busy[outport]) {// fast switch constraint continue; } int inport = m_round_robin_outport[outport]; for (int inport_iter = 0; inport_iter < m_num_inports; inport_iter++) { inport++; if (inport >= m_num_inports) inport = 0; // inport has a request this cycle for outport: if (m_port_req[outport][inport]) { #if USE_WH_VC_SA // check if multiple input wants the same eventually reserved output bool check_reserved_out=false; for(int i=0;i<m_num_inports;i++) for(int j=0;j<m_router->get_num_vcs();j++) if(m_wh_path_busy[i][j][outport]==true && (inport!=i || m_vc_winners[outport][inport]!=j)) { check_reserved_out=true; break; } if(check_reserved_out==true) continue; #endif m_port_req[outport][inport] = false; int invc = m_vc_winners[outport][inport]; int outvc = m_input_unit[inport]->get_outvc(invc); // update round_robin_information for arbiters// m_round_robin_outport[outport]=inport; //assert(m_input_unit[inport]->has_credits(invc)); #if USE_VICHAR==1 assert(m_output_unit[outport]->getAvailSlotPerVnet(outvc/m_vc_per_vnet)>0); #endif // remove flit from Input Unit flit_d *t_flit = m_input_unit[inport]->getTopFlit(invc); // DEBUG PRINT PIPELINE STAGE m_router->print_pipeline_state(t_flit, "SW WON"); t_flit->advance_stage(ST_, m_router->curCycle()); t_flit->set_vc(outvc); t_flit->set_outport(outport); t_flit->set_time(m_router->curCycle() + 1); #if DEBUG_CREDIT_RTT == 1 if( m_router->get_id()==0 && outvc == 0 && outport==3 ) std::cout<<"@"<<curTick()<<" R"<<m_router->get_id() <<"->SA" <<" outvc"<<outvc<<" CREDIT USED"<<std::endl; #endif m_output_unit[outport]->decrement_credit(outvc); m_router->update_sw_winner(inport, t_flit); m_global_arbiter_activity++; m_global_arbiter_activity_resettable++; bool free_signal_fast = true; #if USE_WH_VC_SA==1 // set the reserved path for the winner, it could be useless, // since it is done flit by flit on a possible already active // reserved path m_wh_path_busy[inport][invc][outport] = true; ///// eventually set reuse vc and signal fake vc free////////// #if USE_VC_REUSE==1 int flit_stored = m_input_unit[inport]->getCongestion(invc); int flit_buf_size = m_input_unit[inport]->getBufferSize(invc); int out_flit_cnt = m_output_unit[outport]->get_credit_cnt(outvc); bool firstTailLastFlit = m_input_unit[inport]->isFirstTailLastFlit(invc); bool reusable = m_input_unit[inport]->get_reused_remap_vc_usable()[invc]; bool reused = m_input_unit[inport]->get_reused_remap_vc_used()[invc]; assert(flit_buf_size >= flit_stored); if ( ( firstTailLastFlit || (t_flit->get_type() == TAIL_) || t_flit->get_type() == HEAD_TAIL_/*all remaining packet flits stored in the buffer*/ ) && ( flit_stored <= out_flit_cnt /*enough space in the downstream in buffer*/ ) && ( m_wh_path_busy[inport][invc][outport] == true/*path reserved*/) && ( !reused ) && ( !reusable ) /*not reused or reusable flagged*/ && ( flit_buf_size > flit_stored ) /*one flit slot free to store new packet flits */ ) {// declare it reusable and send a sig_free control sig without turn it into ready state!!! assert(m_input_unit[inport]->isFirstTailLastFlit(invc)|| (t_flit->get_type() == TAIL_) || t_flit->get_type() == HEAD_TAIL_); m_input_unit[inport]->get_reused_remap_vc_usable()[invc]=true; // TODO DELETE only the info, i.e. outvc and outport, of the new reusing packet are // stored in temporary elements //m_input_unit[inport]->get_reused_remap_vc_outport()[invc]=outport; //m_input_unit[inport]->get_reused_remap_vc_outvc()[invc]=outvc; //FIXME if optimized for performance sent back the fake free sig to increase the throughput m_input_unit[inport]->get_reused_remap_vc_fake_free_sig()[invc]=m_router->curCycle(); } //Check if i've already send free_signal for buffer reused if(m_router->curCycle() == m_input_unit[inport]->get_reused_remap_vc_fake_free_sig()[invc]) { free_signal_fast=true; m_input_unit[inport]->get_reused_remap_vc_fake_free_sig()[invc]=0; }else { free_signal_fast=false; } #endif //USE_VC_REUSE==1 #endif //USE_WH_VC_SA==1 if ((t_flit->get_type() == TAIL_) || t_flit->get_type() == HEAD_TAIL_) { /*NON_ATOMIC_VC_ALLOC since the VA is the only stage that can trigger the non atomic vc allocation it is same to update the variables here. */ if(m_output_unit[outport]->get_vc_counter_pkt(outvc, m_router->curCycle()) > 0 ) { //TODO move to VA : set VNETID-novnetid && m_output_unit[outport]->dec_vc_counter_pkt(outvc); m_output_unit[outport]->set_vc_busy_to_vnet_id(outvc, t_flit->get_vnet()); } #if USE_WH_VC_SA==1 // deassert the reserved path if this is the tail flit m_wh_path_busy[inport][invc][outport] = false; #if DEBUG_WH_VC_SA released_path_input[inport]=true; released_path_output[outport]=true; #endif #endif #if DEBUG_CREDIT_RTT == 1 if( m_router->get_id()==1 && invc == 0 && inport==2 ) std::cout<<"@"<<curTick()<<" R"<<m_router->get_id() <<"->SA" <<" invc"<<invc<<" CREDIT SENT BACK"<<std::endl; #endif #if USE_VC_REUSE == 1 #if USE_NON_ATOMIC_VC_ALLOC==1 if(m_input_unit[inport]->getOutportTempQueue(invc)->size()==0) { m_input_unit[inport]->set_vc_state(IDLE_, invc, m_router->curCycle()-1); } else {//some other packet is stored in the same input buffer test if head or head_tail assert(m_input_unit[inport]->peekTopFlit(invc)->get_type() == HEAD_ || m_input_unit[inport]->peekTopFlit(invc)->get_type() == HEAD_TAIL_); } #else if(m_input_unit[inport]->get_reused_remap_vc_used()[invc]==false) { //m_input_unit[inport]->get_reused_remap_vc_usable()[invc]=false; //m_input_unit[inport]->increment_credit(invc, true, m_router->curCycle()); // This Input VC should now be empty assert(m_input_unit[inport]->isReady(invc, m_router->curCycle()) == false); // FIXME FORWARD IDLE info to allow reuse of consecutive single flit packets // we are gaining 1 cycle only with active vc_reuse m_input_unit[inport]->set_vc_state(IDLE_, invc, m_router->curCycle()-1); //Setting for vc reuse statistics cutTick in vc m_input_unit[inport]->setReuseCycleVc(invc, m_router->curCycle()); //m_input_unit[inport]->set_enqueue_time(invc, INFINITE_); } m_input_unit[inport]->get_reused_remap_vc_usable()[invc]=false; #endif #else // This Input VC should now be empty #if USE_NON_ATOMIC_VC_ALLOC==1 if(m_input_unit[inport]->getOutportTempQueue(invc)->size()==0) { m_input_unit[inport]->set_vc_state(IDLE_, invc, m_router->curCycle()-1); } else {//some other packet is stored in the same input buffer test if head or head_tail assert(m_input_unit[inport]->peekTopFlit(invc)->get_type() == HEAD_ || m_input_unit[inport]->peekTopFlit(invc)->get_type() == HEAD_TAIL_); //BUBBLE Checking Router_d::incBubbleTotalCountStatic(); checkBubbleNextCycle(inport,invc); } #else assert(m_input_unit[inport]->isReady(invc, m_router->curCycle()) == false); m_input_unit[inport]->set_vc_state(IDLE_, invc, m_router->curCycle()); #endif #endif m_input_unit[inport]->increment_credit(invc, true, free_signal_fast,m_router->curCycle()); m_input_unit[inport]->set_enqueue_time(invc, INFINITE_); /*congestion metrics starting cycle evaluation*/ Router_d::CongestionMetrics& cm1=m_router->getC1Matrix().at(inport*m_num_vcs+invc).at(m_input_unit[inport]->get_route(invc)); //assert(cm1.t_start!=-1); cm1.count+=m_router->curCycle()-cm1.t_start; cm1.t_start=Cycles(-1); Router_d::CongestionMetrics& cm2= m_router->getC2Matrix().at(invc).at(m_input_unit[inport]->get_route(invc)); //assert(cm2.t_start!=-1); cm2.count+=m_router->curCycle()-cm1.t_start; cm1.t_start=Cycles(-1); /*end congestion*/ } else /*winner flit not an HEAD_TAIL_ or TAIL_*/ { m_input_unit[inport]->increment_credit(invc, false, free_signal_fast,m_router->curCycle()); } break; // got a in request for this outport } } } #endif #if DEBUG_WH_VC_SA // check if some inport/outport pairs could be used but aren't std::vector<int> used_input_path; used_input_path.resize(m_num_inports); for(int i=0;i<m_num_inports;i++) { used_input_path[i]=0; for(int j=0;j<m_num_outports;j++) for(int q=0; q<m_router->get_num_vcs();q++) if(m_wh_path_busy[i][q][j] == true) used_input_path[i]++; } std::vector<int> used_output_path; used_output_path.resize(m_num_outports); for(int i=0;i<m_num_outports;i++) { used_output_path[i]=0; for(int j=0;j<m_num_inports;j++) for(int q=0; q<m_router->get_num_vcs();q++) if(m_wh_path_busy[j][q][i] == true) used_output_path[i]++; } for(int i=0;i<m_num_inports;i++) for(int j=0;j<m_num_outports;j++) { // 0, 1 reserved pat assert(used_input_path[i]<=1 && used_input_path[i]>=0 ); assert(used_output_path[j]<=1 && used_output_path[j]>=0 ); // no required paths not assigned, eventually deallocated this cycle std::cout<<"@"<<curTick()<<" R"<<m_router->get_id()<<" "<<i<<"->"<<j<<" " <<released_path_input[i]<<" "<<released_path_output[j]<<" in_busy?"<<used_input_path[i]<<" out_busy?"<<used_output_path[j] <<"\t"<<released_path_input[i]+released_path_output[j]+used_input_path[i]+used_output_path[j] <<">="<<m_port_req[j][i]<<std::endl; assert(released_path_input[i]+released_path_output[j]+used_input_path[i]+used_output_path[j] >= m_port_req[j][i]); } #endif } void SWallocator_d::check_for_wakeup() { for (int i = 0; i < m_num_inports; i++) { for (int j = 0; j < m_num_vcs; j++) { if (m_input_unit[i]->need_stage_nextcycle(j, ACTIVE_, SA_, m_router->curCycle())) { scheduleEvent(1); return; } } } } int SWallocator_d::get_vnet(int invc) { int vnet = invc/m_vc_per_vnet; assert(vnet < m_router->get_num_vnets()); return vnet; } void SWallocator_d::clear_request_vector() { for (int i = 0; i < m_num_outports; i++) { for (int j = 0; j < m_num_inports; j++) { m_port_req[i][j] = false; } } } void SWallocator_d::checkBubbleNextCycle(int inport, int invc) { bool find=false; for (int j = 0; j < m_num_vcs; j++) { if (m_input_unit[inport]->need_stage_nextcycle(j, ACTIVE_, SA_, m_router->curCycle()) && invc!=j) { Router_d::incBubbleNoDegradationStatic(); find=true; break; } } if(find == false){ Router_d::incBubbleDegradationStatic(); } }
#include <rpl_exploration/FlyToAction.h> // Note: "Action" is appended #include <actionlib/server/simple_action_server.h> #include <ros/ros.h> #include <tf/transform_listener.h> namespace rpl_exploration { class FlyTo { private: ros::NodeHandle nh_; ros::Publisher pub_; actionlib::SimpleActionServer<rpl_exploration::FlyToAction> as_; tf::TransformListener listener; public: FlyTo() : pub_(nh_.advertise<geometry_msgs::PoseStamped>("fly_to_cmd", 1000)), as_(nh_, "fly_to", boost::bind(&FlyTo::execute, this, _1, &as_), false) { ROS_INFO("Starting fly to server"); as_.start(); } void execute(const rpl_exploration::FlyToGoalConstPtr& goal, actionlib::SimpleActionServer<rpl_exploration::FlyToAction> * as) { ROS_INFO_STREAM("Got new goal: Fly to (" << goal->pose.pose.position.x << ", " << goal->pose.pose.position.y << ", " << goal->pose.pose.position.z << ") "); ros::Rate r(20); geometry_msgs::Point p = goal->pose.pose.position; float distance_to_goal = 9001; // Distance is over 9000 float yaw_diff = M_PI; tf::StampedTransform transform; transform.setOrigin( tf::Vector3(0.0, 0.0, 0.0) ); transform.setRotation( tf::Quaternion(0, 0, 0, 1) ); tf::Quaternion gq( goal->pose.pose.orientation.x, goal->pose.pose.orientation.y, goal->pose.pose.orientation.z, goal->pose.pose.orientation.w); tf::Matrix3x3 m(gq); double roll, pitch, goal_yaw; m.getRPY(roll, pitch, goal_yaw); // Check if target is reached... do { ROS_INFO_STREAM("Publishing goal to (" << p.x << ", " << p.y << ", " << p.z << ") "); pub_.publish(goal->pose); listener.waitForTransform("/map", "/base_link", ros::Time(0), ros::Duration(10.0) ); listener.lookupTransform("/map", "/base_link", ros::Time(0), transform); geometry_msgs::Point q; q.x = (float)transform.getOrigin().x(); q.y = (float)transform.getOrigin().y(); q.z = (float)transform.getOrigin().z(); geometry_msgs::Quaternion tq; tq.x = (float)transform.getRotation().x(); tq.y = (float)transform.getRotation().y(); tq.z = (float)transform.getRotation().z(); tq.w = (float)transform.getRotation().w(); tf::Quaternion cq( tq.x, tq.y, tq.z, tq.w); tf::Matrix3x3 m(cq); double current_yaw; m.getRPY(roll, pitch, current_yaw); ROS_INFO_STREAM("Current position: (" << q.x << ", " << q.y << ", " << q.z << ") "); geometry_msgs::Point d; d.x = p.x - q.x; d.y = p.y - q.y; d.z = p.z - q.z; distance_to_goal = sqrt(d.x*d.x + d.y*d.y + d.z*d.z); ROS_INFO_STREAM("Distance to goal: " << distance_to_goal); yaw_diff = fabs(atan2(sin(goal_yaw-current_yaw), cos(goal_yaw-current_yaw))); r.sleep(); } while(distance_to_goal > 0.8 or yaw_diff > 0.6*M_PI); as->setSucceeded(); } }; } int main(int argc, char** argv) { ros::init(argc, argv, "fly_to_server"); rpl_exploration::FlyTo fly_to; ros::spin(); return 0; }
/*************************************************************************/ /* dialogs.cpp */ /*************************************************************************/ /* This file is part of: */ /* GODOT ENGINE */ /* https://godotengine.org */ /*************************************************************************/ /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur. */ /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md). */ /* */ /* Permission is hereby granted, free of charge, to any person obtaining */ /* a copy of this software and associated documentation files (the */ /* "Software"), to deal in the Software without restriction, including */ /* without limitation the rights to use, copy, modify, merge, publish, */ /* distribute, sublicense, and/or sell copies of the Software, and to */ /* permit persons to whom the Software is furnished to do so, subject to */ /* the following conditions: */ /* */ /* The above copyright notice and this permission notice shall be */ /* included in all copies or substantial portions of the Software. */ /* */ /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */ /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */ /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/ /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */ /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */ /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */ /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /*************************************************************************/ #include "dialogs.h" #include "core/callable_method_pointer.h" #include "core/print_string.h" #include "core/translation_helpers.h" #include "core/ustring.h" #include "line_edit.h" #include "core/method_bind.h" #include "scene/resources/font.h" #include "scene/resources/style_box.h" #ifdef TOOLS_ENABLED #include "editor/editor_scale.h" #include "editor/editor_node.h" #include "scene/main/viewport.h" // Only used to check for more modals when dimming the editor. #endif IMPL_GDCLASS(WindowDialog) IMPL_GDCLASS(PopupDialog) IMPL_GDCLASS(AcceptDialog) IMPL_GDCLASS(ConfirmationDialog) // WindowDialog void WindowDialog::_post_popup() { drag_type = DRAG_NONE; // just in case } void WindowDialog::_fix_size() { // Perhaps this should be called when the viewport resizes as well or windows go out of bounds... // Ensure the whole window is visible. Point2i pos = get_global_position(); Size2i size = get_size(); Size2i viewport_size = get_viewport_rect().size; // Windows require additional padding to keep the window chrome visible. Ref<StyleBox> panel = get_theme_stylebox("panel", "WindowDialog"); float top = 0; float left = 0; float bottom = 0; float right = 0; // Check validity, because the theme could contain a different type of StyleBox. if (0==strcmp(panel->get_class(),"StyleBoxTexture")) { Ref<StyleBoxTexture> panel_texture(dynamic_ref_cast<StyleBoxTexture>(panel)); top = panel_texture->get_expand_margin_size(Margin::Top); left = panel_texture->get_expand_margin_size(Margin::Left); bottom = panel_texture->get_expand_margin_size(Margin::Bottom); right = panel_texture->get_expand_margin_size(Margin::Right); } else if (0==strcmp(panel->get_class(),"StyleBoxFlat")) { Ref<StyleBoxFlat> panel_flat(dynamic_ref_cast<StyleBoxFlat>(panel)); top = panel_flat->get_expand_margin_size(Margin::Top); left = panel_flat->get_expand_margin_size(Margin::Left); bottom = panel_flat->get_expand_margin_size(Margin::Bottom); right = panel_flat->get_expand_margin_size(Margin::Right); } pos.x = M_MAX(left, MIN(pos.x, viewport_size.x - size.x - right)); pos.y = M_MAX(top, MIN(pos.y, viewport_size.y - size.y - bottom)); set_global_position(pos); if (resizable) { size.x = MIN(size.x, viewport_size.x - left - right); size.y = MIN(size.y, viewport_size.y - top - bottom); set_size(size); } } bool WindowDialog::has_point(const Point2 &p_point) const { Rect2 r(Point2(), get_size()); // Enlarge upwards for title bar. int title_height = get_theme_constant("title_height", "WindowDialog"); r.position.y -= title_height; r.size.y += title_height; // Inflate by the resizable border thickness. if (resizable) { int scaleborder_size = get_theme_constant("scaleborder_size", "WindowDialog"); r.position.x -= scaleborder_size; r.size.width += scaleborder_size * 2; r.position.y -= scaleborder_size; r.size.height += scaleborder_size * 2; } return r.has_point(p_point); } void WindowDialog::_gui_input(const Ref<InputEvent> &p_event) { Ref<InputEventMouseButton> mb = dynamic_ref_cast<InputEventMouseButton>(p_event); if (mb && mb->get_button_index() == BUTTON_LEFT) { if (mb->is_pressed()) { // Begin a possible dragging operation. drag_type = _drag_hit_test(Point2(mb->get_position().x, mb->get_position().y)); if (drag_type != DRAG_NONE) drag_offset = get_global_mouse_position() - get_position(); drag_offset_far = get_position() + get_size() - get_global_mouse_position(); } else if (drag_type != DRAG_NONE && !mb->is_pressed()) { // End a dragging operation. drag_type = DRAG_NONE; } } Ref<InputEventMouseMotion> mm = dynamic_ref_cast<InputEventMouseMotion>(p_event); if (mm) { if (drag_type == DRAG_NONE) { // Update the cursor while moving along the borders. CursorShape cursor = CURSOR_ARROW; if (resizable) { int preview_drag_type = _drag_hit_test(Point2(mm->get_position().x, mm->get_position().y)); switch (preview_drag_type) { case DRAG_RESIZE_TOP: case DRAG_RESIZE_BOTTOM: cursor = CURSOR_VSIZE; break; case DRAG_RESIZE_LEFT: case DRAG_RESIZE_RIGHT: cursor = CURSOR_HSIZE; break; case DRAG_RESIZE_TOP + DRAG_RESIZE_LEFT: case DRAG_RESIZE_BOTTOM + DRAG_RESIZE_RIGHT: cursor = CURSOR_FDIAGSIZE; break; case DRAG_RESIZE_TOP + DRAG_RESIZE_RIGHT: case DRAG_RESIZE_BOTTOM + DRAG_RESIZE_LEFT: cursor = CURSOR_BDIAGSIZE; break; } } if (get_cursor_shape() != cursor) set_default_cursor_shape(cursor); } else { // Update while in a dragging operation. Point2 global_pos = get_global_mouse_position(); global_pos.y = M_MAX(global_pos.y, 0); // Ensure title bar stays visible. Rect2 rect = get_rect(); Size2 min_size = get_combined_minimum_size(); if (drag_type == DRAG_MOVE) { rect.position = global_pos - drag_offset; } else { if (drag_type & DRAG_RESIZE_TOP) { int bottom = rect.position.y + rect.size.height; int max_y = bottom - min_size.height; rect.position.y = MIN(global_pos.y - drag_offset.y, max_y); rect.size.height = bottom - rect.position.y; } else if (drag_type & DRAG_RESIZE_BOTTOM) { rect.size.height = global_pos.y - rect.position.y + drag_offset_far.y; } if (drag_type & DRAG_RESIZE_LEFT) { int right = rect.position.x + rect.size.width; int max_x = right - min_size.width; rect.position.x = MIN(global_pos.x - drag_offset.x, max_x); rect.size.width = right - rect.position.x; } else if (drag_type & DRAG_RESIZE_RIGHT) { rect.size.width = global_pos.x - rect.position.x + drag_offset_far.x; } } set_size(rect.size); set_position(rect.position); } } } void WindowDialog::_notification(int p_what) { switch (p_what) { case NOTIFICATION_DRAW: { RID canvas = get_canvas_item(); // Draw the background. Ref<StyleBox> panel = get_theme_stylebox("panel"); Size2 size = get_size(); panel->draw(canvas, Rect2(0, 0, size.x, size.y)); // Draw the title bar text. Ref<Font> title_font = get_theme_font("title_font", "WindowDialog"); Color title_color = get_theme_color("title_color", "WindowDialog"); int title_height = get_theme_constant("title_height", "WindowDialog"); int font_height = title_font->get_height() - title_font->get_descent() * 2; int x = (size.x - title_font->get_string_size(xl_title).x) / 2; int y = (-title_height + font_height) / 2; title_font->draw_ui_string(canvas, Point2(x, y), StringUtils::from_utf8(xl_title), title_color, size.x - panel->get_minimum_size().x); } break; case NOTIFICATION_THEME_CHANGED: case NOTIFICATION_ENTER_TREE: { close_button->set_normal_texture(get_theme_icon("close", "WindowDialog")); close_button->set_pressed_texture(get_theme_icon("close", "WindowDialog")); close_button->set_hover_texture(get_theme_icon("close_highlight", "WindowDialog")); close_button->set_anchor(Margin::Left, ANCHOR_END); close_button->set_begin(Point2(-get_theme_constant("close_h_ofs", "WindowDialog"), -get_theme_constant("close_v_ofs", "WindowDialog"))); } break; case NOTIFICATION_TRANSLATION_CHANGED: { StringName new_title(tr(title)); if (new_title != xl_title) { xl_title = new_title; minimum_size_changed(); update(); } } break; case NOTIFICATION_MOUSE_EXIT: { // Reset the mouse cursor when leaving the resizable window border. if (resizable && !drag_type) { if (get_default_cursor_shape() != CURSOR_ARROW) set_default_cursor_shape(CURSOR_ARROW); } } break; #ifdef TOOLS_ENABLED case NOTIFICATION_POST_POPUP: { if (get_tree() && Engine::get_singleton()->is_editor_hint() && EditorNode::get_singleton()) { was_editor_dimmed = EditorNode::get_singleton()->is_editor_dimmed(); EditorNode::get_singleton()->dim_editor(true); } } break; case NOTIFICATION_POPUP_HIDE: { if (get_tree() && Engine::get_singleton()->is_editor_hint() && EditorNode::get_singleton() && !was_editor_dimmed) { EditorNode::get_singleton()->dim_editor(false); set_pass_on_modal_close_click(false); } } break; #endif } } void WindowDialog::_closed() { _close_pressed(); hide(); } int WindowDialog::_drag_hit_test(const Point2 &pos) const { int drag_type = DRAG_NONE; if (resizable) { int title_height = get_theme_constant("title_height", "WindowDialog"); int scaleborder_size = get_theme_constant("scaleborder_size", "WindowDialog"); Rect2 rect = get_rect(); if (pos.y < (-title_height + scaleborder_size)) drag_type = DRAG_RESIZE_TOP; else if (pos.y >= (rect.size.height - scaleborder_size)) drag_type = DRAG_RESIZE_BOTTOM; if (pos.x < scaleborder_size) drag_type |= DRAG_RESIZE_LEFT; else if (pos.x >= (rect.size.width - scaleborder_size)) drag_type |= DRAG_RESIZE_RIGHT; } if (drag_type == DRAG_NONE && pos.y < 0) drag_type = DRAG_MOVE; return drag_type; } void WindowDialog::set_title(const StringName &p_title) { StringName new_title = tr(p_title); if (title != p_title) { title = p_title; xl_title = new_title; minimum_size_changed(); update(); } } StringName WindowDialog::get_title() const { return title; } void WindowDialog::set_resizable(bool p_resizable) { resizable = p_resizable; } bool WindowDialog::get_resizable() const { return resizable; } Size2 WindowDialog::get_minimum_size() const { Ref<Font> font = get_theme_font("title_font", "WindowDialog"); const int button_width = close_button->get_combined_minimum_size().x; const int title_width = font->get_string_size(xl_title).x; const int padding = button_width / 2; const int button_area = button_width + padding; // As the title gets centered, title_width + close_button_width is not enough. // We want a width w, such that w / 2 - title_width / 2 >= button_area, i.e. // w >= 2 * button_area + title_width return Size2(2 * button_area + title_width, 1); } TextureButton *WindowDialog::get_close_button() { return close_button; } void WindowDialog::_bind_methods() { MethodBinder::bind_method(D_METHOD("_gui_input"), &WindowDialog::_gui_input); MethodBinder::bind_method(D_METHOD("set_title", {"title"}), &WindowDialog::set_title); MethodBinder::bind_method(D_METHOD("get_title"), &WindowDialog::get_title); MethodBinder::bind_method(D_METHOD("set_resizable", {"resizable"}), &WindowDialog::set_resizable); MethodBinder::bind_method(D_METHOD("get_resizable"), &WindowDialog::get_resizable); MethodBinder::bind_method(D_METHOD("_closed"), &WindowDialog::_closed); MethodBinder::bind_method(D_METHOD("get_close_button"), &WindowDialog::get_close_button); ADD_PROPERTY(PropertyInfo(VariantType::STRING, "window_title", PropertyHint::None, "", PROPERTY_USAGE_DEFAULT_INTL), "set_title", "get_title"); ADD_PROPERTY(PropertyInfo(VariantType::BOOL, "resizable", PropertyHint::None, "", PROPERTY_USAGE_DEFAULT_INTL), "set_resizable", "get_resizable"); } WindowDialog::WindowDialog() { drag_type = DRAG_NONE; resizable = false; close_button = memnew(TextureButton); add_child(close_button); close_button->connect("pressed",callable_mp(this, &ClassName::_closed)); #ifdef TOOLS_ENABLED was_editor_dimmed = false; #endif } WindowDialog::~WindowDialog() { } // PopupDialog void PopupDialog::_notification(int p_what) { if (p_what == NOTIFICATION_DRAW) { RID ci = get_canvas_item(); get_theme_stylebox("panel")->draw(ci, Rect2(Point2(), get_size())); } } PopupDialog::PopupDialog() { } PopupDialog::~PopupDialog() { } // AcceptDialog void AcceptDialog::_post_popup() { WindowDialog::_post_popup(); get_ok()->grab_focus(); } void AcceptDialog::_notification(int p_what) { switch (p_what) { case NOTIFICATION_MODAL_CLOSE: { cancel_pressed(); } break; case NOTIFICATION_READY: case NOTIFICATION_RESIZED: { _update_child_rects(); } break; } } void AcceptDialog::_builtin_text_entered(StringView p_text) { _ok_pressed(); } void AcceptDialog::_ok_pressed() { if (hide_on_ok) hide(); ok_pressed(); emit_signal("confirmed"); } void AcceptDialog::_cancel_pressed() { // Window *parent_window = parent_visible; // if (parent_visible) { // parent_visible->disconnect("focus_entered", callable_mp(this, &AcceptDialog::_parent_focused)); // parent_visible = nullptr; // } call_deferred([this] { hide();} ); emit_signal("cancelled"); cancel_pressed(); // if (parent_window) { // //parent_window->grab_focus(); // } } void AcceptDialog::_close_pressed() { cancel_pressed(); } UIString AcceptDialog::get_text_ui() const { return StringUtils::from_utf8(label->get_text()); } String AcceptDialog::get_text() const { return label->get_text(); } void AcceptDialog::set_text(StringView p_text) { label->set_text(p_text); minimum_size_changed(); _update_child_rects(); } void AcceptDialog::set_text_utf8(StringView p_text) { label->set_text(StringName(p_text)); minimum_size_changed(); _update_child_rects(); } void AcceptDialog::set_hide_on_ok(bool p_hide) { hide_on_ok = p_hide; } bool AcceptDialog::get_hide_on_ok() const { return hide_on_ok; } void AcceptDialog::set_autowrap(bool p_autowrap) { label->set_autowrap(p_autowrap); } bool AcceptDialog::has_autowrap() { return label->has_autowrap(); } void AcceptDialog::register_text_enter(Node *p_line_edit) { ERR_FAIL_NULL(p_line_edit); LineEdit *line_edit = object_cast<LineEdit>(p_line_edit); if (line_edit) line_edit->connect("text_entered",callable_mp(this, &ClassName::_builtin_text_entered)); } void AcceptDialog::_update_child_rects() { Size2 label_size = label->get_minimum_size(); if (label->get_text().empty()) { label_size.height = 0; } int margin = get_theme_constant("margin", "Dialogs"); Size2 size = get_size(); Size2 hminsize = hbc->get_combined_minimum_size(); Vector2 cpos(margin, margin + label_size.height); Vector2 csize(size.x - margin * 2, size.y - margin * 3 - hminsize.y - label_size.height); for (int i = 0; i < get_child_count(); i++) { Control *c = object_cast<Control>(get_child(i)); if (!c) continue; if (c == hbc || c == label || c == get_close_button() || c->is_set_as_top_level()) continue; c->set_position(cpos); c->set_size(csize); } cpos.y += csize.y + margin; csize.y = hminsize.y; hbc->set_position(cpos); hbc->set_size(csize); } Size2 AcceptDialog::get_minimum_size() const { int margin = get_theme_constant("margin", "Dialogs"); Size2 minsize = label->get_combined_minimum_size(); for (int i = 0; i < get_child_count(); i++) { Control *c = object_cast<Control>(get_child(i)); if (!c) continue; if (c == hbc || c == label || c == const_cast<AcceptDialog *>(this)->get_close_button() || c->is_set_as_top_level()) continue; Size2 cminsize = c->get_combined_minimum_size(); minsize.x = M_MAX(cminsize.x, minsize.x); minsize.y = M_MAX(cminsize.y, minsize.y); } Size2 hminsize = hbc->get_combined_minimum_size(); minsize.x = M_MAX(hminsize.x, minsize.x); minsize.y += hminsize.y; minsize.x += margin * 2; minsize.y += margin * 3; //one as separation between hbc and child Size2 wmsize = WindowDialog::get_minimum_size(); minsize.x = M_MAX(wmsize.x, minsize.x); return minsize; } void AcceptDialog::_custom_action(const StringName &p_action) { emit_signal("custom_action", p_action); custom_action(p_action); } Button *AcceptDialog::add_button(const StringName &p_text, bool p_right, StringView p_action) { Button *button = memnew(Button); button->set_text(p_text); if (p_right) { hbc->add_child(button); hbc->add_spacer(); } else { hbc->add_child(button); hbc->move_child(button, 0); hbc->add_spacer(true); } if (!p_action.empty()) { button->connect("pressed",callable_mp(this, &ClassName::_custom_action), varray(p_action)); } return button; } Button *AcceptDialog::add_cancel(const StringName &p_cancel) { StringName c = p_cancel; if (p_cancel.empty()) c = RTR("Cancel"); Button *b = swap_ok_cancel ? add_button(c, true) : add_button(c); b->connect("pressed",callable_mp(this, &ClassName::_cancel_pressed)); return b; } void AcceptDialog::_bind_methods() { MethodBinder::bind_method(D_METHOD("get_ok"), &AcceptDialog::get_ok); MethodBinder::bind_method(D_METHOD("get_label"), &AcceptDialog::get_label); MethodBinder::bind_method(D_METHOD("set_hide_on_ok", {"enabled"}), &AcceptDialog::set_hide_on_ok); MethodBinder::bind_method(D_METHOD("get_hide_on_ok"), &AcceptDialog::get_hide_on_ok); MethodBinder::bind_method(D_METHOD("add_button", {"text", "right", "action"}), &AcceptDialog::add_button, {DEFVAL(false), DEFVAL("")}); MethodBinder::bind_method(D_METHOD("add_cancel", {"name"}), &AcceptDialog::add_cancel); MethodBinder::bind_method(D_METHOD("register_text_enter", {"line_edit"}), &AcceptDialog::register_text_enter); MethodBinder::bind_method(D_METHOD("set_text", {"text"}), &AcceptDialog::set_text); MethodBinder::bind_method(D_METHOD("get_text"), &AcceptDialog::get_text); MethodBinder::bind_method(D_METHOD("set_autowrap", {"autowrap"}), &AcceptDialog::set_autowrap); MethodBinder::bind_method(D_METHOD("has_autowrap"), &AcceptDialog::has_autowrap); ADD_SIGNAL(MethodInfo("confirmed")); ADD_SIGNAL(MethodInfo("cancelled")); ADD_SIGNAL(MethodInfo("custom_action", PropertyInfo(VariantType::STRING_NAME, "action"))); ADD_GROUP("Dialog", "dialog"); ADD_PROPERTY(PropertyInfo(VariantType::STRING, "dialog_text", PropertyHint::MultilineText, "", PROPERTY_USAGE_DEFAULT_INTL), "set_text", "get_text"); ADD_PROPERTY(PropertyInfo(VariantType::BOOL, "dialog_hide_on_ok"), "set_hide_on_ok", "get_hide_on_ok"); ADD_PROPERTY(PropertyInfo(VariantType::BOOL, "dialog_autowrap"), "set_autowrap", "has_autowrap"); } bool AcceptDialog::swap_ok_cancel = false; void AcceptDialog::set_swap_ok_cancel(bool p_swap) { swap_ok_cancel = p_swap; } AcceptDialog::AcceptDialog() { int margin = get_theme_constant("margin", "Dialogs"); int button_margin = get_theme_constant("button_margin", "Dialogs"); label = memnew(Label); label->set_anchor(Margin::Right, ANCHOR_END); label->set_anchor(Margin::Bottom, ANCHOR_END); label->set_begin(Point2(margin, margin)); label->set_end(Point2(-margin, -button_margin - 10)); add_child(label); hbc = memnew(HBoxContainer); add_child(hbc); hbc->add_spacer(); ok = memnew(Button); ok->set_text(RTR("OK")); hbc->add_child(ok); hbc->add_spacer(); ok->connect("pressed",callable_mp(this, &ClassName::_ok_pressed)); set_as_top_level(true); hide_on_ok = true; set_title(RTR("Alert!")); } AcceptDialog::~AcceptDialog() { } // ConfirmationDialog void ConfirmationDialog::_bind_methods() { MethodBinder::bind_method(D_METHOD("get_cancel"), &ConfirmationDialog::get_cancel); } Button *ConfirmationDialog::get_cancel() { return cancel; } ConfirmationDialog::ConfirmationDialog() { set_title(RTR("Please Confirm...")); #ifdef TOOLS_ENABLED set_custom_minimum_size(Size2(200, 70) * EDSCALE); #endif cancel = add_cancel(); }
/* * BSD LICENSE * Copyright (c) 2021 Samsung Electronics Corporation * 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 Samsung Electronics Corporation 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 <cassert> #include <cstring> #include <list> #include "raid1.h" #include "src/helper/enumerable/query.h" #include "src/include/array_config.h" #include "src/include/pos_event_id.h" #include "src/logger/logger.h" #include "src/array_models/dto/partition_physical_size.h" namespace pos { Raid1::Raid1(const PartitionPhysicalSize* physicalSize) { raidType = RaidTypeEnum::RAID1; mirrorDevCnt = physicalSize->chunksPerStripe / 2; ftSize_ = { .minWriteBlkCnt = ArrayConfig::RAID1_MIN_WRITE_BLOCK_COUNT, .backupBlkCnt = mirrorDevCnt * physicalSize->blksPerChunk, .blksPerChunk = physicalSize->blksPerChunk, .blksPerStripe = physicalSize->chunksPerStripe * physicalSize->blksPerChunk, .chunksPerStripe = physicalSize->chunksPerStripe}; _BindRecoverFunc(); } int Raid1::Translate(FtBlkAddr& dst, const LogicalBlkAddr& src) { dst = {.stripeId = src.stripeId, .offset = src.offset}; return 0; } int Raid1::Convert(list<FtWriteEntry>& dst, const LogicalWriteEntry& src) { FtWriteEntry ftEntry; Translate(ftEntry.addr, src.addr); ftEntry.buffers = *(src.buffers); ftEntry.blkCnt = src.blkCnt; FtWriteEntry mirror(ftEntry); mirror.addr.offset += ftSize_.backupBlkCnt; dst.clear(); dst.push_back(ftEntry); dst.push_back(mirror); return 0; } list<FtBlkAddr> Raid1::GetRebuildGroup(FtBlkAddr fba) { uint32_t idx = fba.offset / ftSize_.blksPerChunk; uint32_t offset = fba.offset % ftSize_.blksPerChunk; uint32_t mirror = _GetMirrorIndex(idx); list<FtBlkAddr> recoveryGroup; fba.offset = mirror * ftSize_.blksPerChunk + offset; recoveryGroup.push_back(fba); return recoveryGroup; } RaidState Raid1::GetRaidState(vector<ArrayDeviceState> devs) { RaidState rs = RaidState::NORMAL; for (size_t i = 0; i < devs.size(); i++) { ArrayDeviceState state = devs[i]; if (state != ArrayDeviceState::NORMAL) { rs = RaidState::DEGRADED; ArrayDeviceState mirrorState = devs[_GetMirrorIndex(i)]; if (mirrorState != ArrayDeviceState::NORMAL) { return RaidState::FAILURE; } } } POS_TRACE_INFO(EID(RAID_DEBUG_MSG), "GetRaidState from raid1:{} ", rs); return rs; } void Raid1::_BindRecoverFunc(void) { using namespace std::placeholders; recoverFunc_ = bind(&Raid1::_RebuildData, this, _1, _2, _3); } void Raid1::_RebuildData(void* dst, void* src, uint32_t size) { memcpy(dst, src, size); } uint32_t Raid1::_GetMirrorIndex(uint32_t idx) { if (idx >= mirrorDevCnt) { return idx - mirrorDevCnt; } else { return idx + mirrorDevCnt; } } Raid1::~Raid1() { } } // namespace pos
// fstencode.cpp : Defines the entry point for the console application. // #include "stdafx.h" int main() { return 0; }
// Copyright 2019 Open Source Robotics Foundation, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <memory> #include <string> #include <vector> #include "class_loader/class_loader.hpp" #include "rclcpp/rclcpp.hpp" #include "rclcpp_components/node_factory.hpp" #include "rclcpp_components/node_factory_template.hpp" #define NODE_MAIN_LOGGER_NAME "spin_until_future_complete_relay_server" int main(int argc, char * argv[]) { auto args = rclcpp::init_and_remove_ros_arguments(argc, argv); rclcpp::Logger logger = rclcpp::get_logger(NODE_MAIN_LOGGER_NAME); rclcpp::executors::MultiThreadedExecutor exec; rclcpp::NodeOptions options; options.arguments(args); std::vector<class_loader::ClassLoader * > loaders; std::vector<rclcpp_components::NodeInstanceWrapper> node_wrappers; std::string library_name = "libservices_library.so"; std::string class_name = "rclcpp_components::NodeFactoryTemplate<spin_until_future_complete::RelayServerNode>"; RCLCPP_DEBUG(logger, "Load library %s", library_name.c_str()); auto loader = new class_loader::ClassLoader(library_name); auto classes = loader->getAvailableClasses<rclcpp_components::NodeFactory>(); for (auto clazz : classes) { std::string name = clazz.c_str(); if (!(name.compare(class_name))) { RCLCPP_DEBUG(logger, "Instantiate class %s", clazz.c_str()); auto node_factory = loader->createInstance<rclcpp_components::NodeFactory>(clazz); auto wrapper = node_factory->create_node_instance(options); auto node = wrapper.get_node_base_interface(); node_wrappers.push_back(wrapper); exec.add_node(node); } } loaders.push_back(loader); exec.spin(); for (auto wrapper : node_wrappers) { exec.remove_node(wrapper.get_node_base_interface()); } node_wrappers.clear(); rclcpp::shutdown(); return 0; }
//------------------------------------------------------------------------------------------- //- Copyright 2017 Applied Research Associates, Inc. //- Licensed under the Apache License, Version 2.0 (the "License"); you may not use //- this file except in compliance with the License. You may obtain a copy of the License //- at: //- http://www.apache.org/licenses/LICENSE-2.0 //- Unless required by applicable law or agreed to in writing, software distributed under //- the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR //- CONDITIONS OF ANY KIND, either express or implied. See the License for the //- specific language governing permissions and limitations under the License. //------------------------------------------------------------------------------------------- //! //! @author David Lee //! @date 2017 Aug 3rd //! //! Unit Test for Biogears-common Config //! #include <limits> #include <thread> #include <gtest/gtest.h> #include <biogears/cdm/properties/SEScalar.h> #include <biogears/cdm/system/physiology/SERenalSystem.h> #include <biogears/cdm/properties/SEScalarTypes.h> #ifdef DISABLE_BIOGEARS_SERenalSystem_TEST #define TEST_FIXTURE_NAME DISABLED_SERenalSystem_Fixture #else #define TEST_FIXTURE_NAME SERenalSystem_Fixture #endif using namespace biogears; // The fixture for testing class Foo. class TEST_FIXTURE_NAME : public ::testing::Test { protected: // You can do set-up work for each test here. TEST_FIXTURE_NAME() = default; // You can do clean-up work that doesn't throw exceptions here. virtual ~TEST_FIXTURE_NAME() = default; // If the constructor and destructor are not enough for setting up // and cleaning up each test, you can define the following methods: // Code here will be called immediately after the constructor (right // before each test). virtual void SetUp() override; // Code here will be called immediately after each test (right // before the destructor). virtual void TearDown() override; biogears::Logger* logger; biogears::SERenalSystem* es; }; void TEST_FIXTURE_NAME::SetUp() { logger = new biogears::Logger; es = new biogears::SERenalSystem(logger); } void TEST_FIXTURE_NAME::TearDown() { delete es; delete logger; } TEST_F(TEST_FIXTURE_NAME, GlomerularFiltrationRate) { EXPECT_FALSE( es->HasGlomerularFiltrationRate()); es->GetGlomerularFiltrationRate().SetValue(1.0, VolumePerTimeUnit::L_Per_min); EXPECT_TRUE( es->HasGlomerularFiltrationRate()); EXPECT_EQ(1.0, es->GetGlomerularFiltrationRate(VolumePerTimeUnit::L_Per_min)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasGlomerularFiltrationRate()); auto dvalue = ces.GetGlomerularFiltrationRate(VolumePerTimeUnit::L_Per_min); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, FiltrationFraction) { EXPECT_FALSE( es->HasFiltrationFraction()); es->GetFiltrationFraction().SetValue(1.0); EXPECT_TRUE( es->HasFiltrationFraction()); EXPECT_EQ(1.0, es->GetFiltrationFraction().GetValue()); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasFiltrationFraction()); auto dvalue = ces.GetFiltrationFraction(); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftAfferentArterioleResistance) { EXPECT_FALSE( es->HasLeftAfferentArterioleResistance()); es->GetLeftAfferentArterioleResistance().SetValue(1.0, FlowResistanceUnit::Pa_s_Per_m3); EXPECT_TRUE( es->HasLeftAfferentArterioleResistance()); EXPECT_EQ(1.0, es->GetLeftAfferentArterioleResistance(FlowResistanceUnit::Pa_s_Per_m3)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftAfferentArterioleResistance()); auto dvalue = ces.GetLeftAfferentArterioleResistance(FlowResistanceUnit::Pa_s_Per_m3); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftBowmansCapsulesHydrostaticPressure) { EXPECT_FALSE( es->HasLeftBowmansCapsulesHydrostaticPressure()); es->GetLeftBowmansCapsulesHydrostaticPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasLeftBowmansCapsulesHydrostaticPressure()); EXPECT_EQ(1.0, es->GetLeftBowmansCapsulesHydrostaticPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftBowmansCapsulesHydrostaticPressure()); auto dvalue = ces.GetLeftBowmansCapsulesHydrostaticPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftBowmansCapsulesOsmoticPressure) { EXPECT_FALSE( es->HasLeftBowmansCapsulesOsmoticPressure()); es->GetLeftBowmansCapsulesOsmoticPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasLeftBowmansCapsulesOsmoticPressure()); EXPECT_EQ(1.0, es->GetLeftBowmansCapsulesOsmoticPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftBowmansCapsulesOsmoticPressure()); auto dvalue = ces.GetLeftBowmansCapsulesOsmoticPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftEfferentArterioleResistance) { EXPECT_FALSE( es->HasLeftEfferentArterioleResistance()); es->GetLeftEfferentArterioleResistance().SetValue(1.0, FlowResistanceUnit::Pa_s_Per_m3); EXPECT_TRUE( es->HasLeftEfferentArterioleResistance()); EXPECT_EQ(1.0, es->GetLeftEfferentArterioleResistance(FlowResistanceUnit::Pa_s_Per_m3)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftEfferentArterioleResistance()); auto dvalue = ces.GetLeftEfferentArterioleResistance(FlowResistanceUnit::Pa_s_Per_m3); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftGlomerularCapillariesHydrostaticPressure) { EXPECT_FALSE( es->HasLeftGlomerularCapillariesHydrostaticPressure()); es->GetLeftGlomerularCapillariesHydrostaticPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasLeftGlomerularCapillariesHydrostaticPressure()); EXPECT_EQ(1.0, es->GetLeftGlomerularCapillariesHydrostaticPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftGlomerularCapillariesHydrostaticPressure()); auto dvalue = ces.GetLeftGlomerularCapillariesHydrostaticPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftGlomerularCapillariesOsmoticPressure) { EXPECT_FALSE( es->HasLeftGlomerularCapillariesOsmoticPressure()); es->GetLeftGlomerularCapillariesOsmoticPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasLeftGlomerularCapillariesOsmoticPressure()); EXPECT_EQ(1.0, es->GetLeftGlomerularCapillariesOsmoticPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftGlomerularCapillariesOsmoticPressure()); auto dvalue = ces.GetLeftGlomerularCapillariesOsmoticPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftGlomerularFiltrationCoefficient) { EXPECT_FALSE( es->HasLeftGlomerularFiltrationCoefficient()); es->GetLeftGlomerularFiltrationCoefficient().SetValue(1.0, VolumePerTimePressureUnit::L_Per_min_mmHg); EXPECT_TRUE( es->HasLeftGlomerularFiltrationCoefficient()); EXPECT_EQ(1.0, es->GetLeftGlomerularFiltrationCoefficient(VolumePerTimePressureUnit::L_Per_min_mmHg)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftGlomerularFiltrationCoefficient()); auto dvalue = ces.GetLeftGlomerularFiltrationCoefficient(VolumePerTimePressureUnit::L_Per_min_mmHg); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftReabsorptionFiltrationCoefficient) { EXPECT_FALSE( es->HasLeftReabsorptionFiltrationCoefficient()); es->GetLeftReabsorptionFiltrationCoefficient().SetValue(1.0, VolumePerTimePressureUnit::L_Per_min_mmHg); EXPECT_TRUE( es->HasLeftReabsorptionFiltrationCoefficient()); EXPECT_EQ(1.0, es->GetLeftReabsorptionFiltrationCoefficient(VolumePerTimePressureUnit::L_Per_min_mmHg)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftReabsorptionFiltrationCoefficient()); auto dvalue = ces.GetLeftReabsorptionFiltrationCoefficient(VolumePerTimePressureUnit::L_Per_min_mmHg); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightGlomerularFiltrationCoefficient) { EXPECT_FALSE( es->HasRightGlomerularFiltrationCoefficient()); es->GetRightGlomerularFiltrationCoefficient().SetValue(1.0, VolumePerTimePressureUnit::L_Per_min_mmHg); EXPECT_TRUE( es->HasRightGlomerularFiltrationCoefficient()); EXPECT_EQ(1.0, es->GetRightGlomerularFiltrationCoefficient(VolumePerTimePressureUnit::L_Per_min_mmHg)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightGlomerularFiltrationCoefficient()); auto dvalue = ces.GetRightGlomerularFiltrationCoefficient(VolumePerTimePressureUnit::L_Per_min_mmHg); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightReabsorptionFiltrationCoefficient) { EXPECT_FALSE( es->HasRightReabsorptionFiltrationCoefficient()); es->GetRightReabsorptionFiltrationCoefficient().SetValue(1.0, VolumePerTimePressureUnit::L_Per_min_mmHg); EXPECT_TRUE( es->HasRightReabsorptionFiltrationCoefficient()); EXPECT_EQ(1.0, es->GetRightReabsorptionFiltrationCoefficient(VolumePerTimePressureUnit::L_Per_min_mmHg)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightReabsorptionFiltrationCoefficient()); auto dvalue = ces.GetRightReabsorptionFiltrationCoefficient(VolumePerTimePressureUnit::L_Per_min_mmHg); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftGlomerularFiltrationSurfaceArea) { EXPECT_FALSE( es->HasLeftGlomerularFiltrationSurfaceArea()); es->GetLeftGlomerularFiltrationSurfaceArea().SetValue(1.0, AreaUnit::m2); EXPECT_TRUE( es->HasLeftGlomerularFiltrationSurfaceArea()); EXPECT_EQ(1.0, es->GetLeftGlomerularFiltrationSurfaceArea(AreaUnit::m2)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftGlomerularFiltrationSurfaceArea()); auto dvalue = ces.GetLeftGlomerularFiltrationSurfaceArea(AreaUnit::m2); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftTubularReabsorptionFiltrationSurfaceArea) { EXPECT_FALSE( es->HasLeftTubularReabsorptionFiltrationSurfaceArea()); es->GetLeftTubularReabsorptionFiltrationSurfaceArea().SetValue(1.0, AreaUnit::m2); EXPECT_TRUE( es->HasLeftTubularReabsorptionFiltrationSurfaceArea()); EXPECT_EQ(1.0, es->GetLeftTubularReabsorptionFiltrationSurfaceArea(AreaUnit::m2)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftTubularReabsorptionFiltrationSurfaceArea()); auto dvalue = ces.GetLeftTubularReabsorptionFiltrationSurfaceArea(AreaUnit::m2); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightGlomerularFiltrationSurfaceArea) { EXPECT_FALSE( es->HasRightGlomerularFiltrationSurfaceArea()); es->GetRightGlomerularFiltrationSurfaceArea().SetValue(1.0, AreaUnit::m2); EXPECT_TRUE( es->HasRightGlomerularFiltrationSurfaceArea()); EXPECT_EQ(1.0, es->GetRightGlomerularFiltrationSurfaceArea(AreaUnit::m2)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightGlomerularFiltrationSurfaceArea()); auto dvalue = ces.GetRightGlomerularFiltrationSurfaceArea(AreaUnit::m2); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightTubularReabsorptionFiltrationSurfaceArea) { EXPECT_FALSE( es->HasRightTubularReabsorptionFiltrationSurfaceArea()); es->GetRightTubularReabsorptionFiltrationSurfaceArea().SetValue(1.0, AreaUnit::m2); EXPECT_TRUE( es->HasRightTubularReabsorptionFiltrationSurfaceArea()); EXPECT_EQ(1.0, es->GetRightTubularReabsorptionFiltrationSurfaceArea(AreaUnit::m2)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightTubularReabsorptionFiltrationSurfaceArea()); auto dvalue = ces.GetRightTubularReabsorptionFiltrationSurfaceArea(AreaUnit::m2); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftGlomerularFluidPermeability) { EXPECT_FALSE( es->HasLeftGlomerularFluidPermeability()); es->GetLeftGlomerularFluidPermeability().SetValue(1.0, VolumePerTimePressureAreaUnit::mL_Per_min_mmHg_m2); EXPECT_TRUE( es->HasLeftGlomerularFluidPermeability()); EXPECT_EQ(1.0, es->GetLeftGlomerularFluidPermeability(VolumePerTimePressureAreaUnit::mL_Per_min_mmHg_m2)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftGlomerularFluidPermeability()); auto dvalue = ces.GetLeftGlomerularFluidPermeability(VolumePerTimePressureAreaUnit::mL_Per_min_mmHg_m2); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftTubularReabsorptionFluidPermeability) { EXPECT_FALSE( es->HasLeftTubularReabsorptionFluidPermeability()); es->GetLeftTubularReabsorptionFluidPermeability().SetValue(1.0, VolumePerTimePressureAreaUnit::mL_Per_min_mmHg_m2); EXPECT_TRUE( es->HasLeftTubularReabsorptionFluidPermeability()); EXPECT_EQ(1.0, es->GetLeftTubularReabsorptionFluidPermeability(VolumePerTimePressureAreaUnit::mL_Per_min_mmHg_m2)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftTubularReabsorptionFluidPermeability()); auto dvalue = ces.GetLeftTubularReabsorptionFluidPermeability(VolumePerTimePressureAreaUnit::mL_Per_min_mmHg_m2); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightGlomerularFluidPermeability) { EXPECT_FALSE( es->HasRightGlomerularFluidPermeability()); es->GetRightGlomerularFluidPermeability().SetValue(1.0, VolumePerTimePressureAreaUnit::mL_Per_min_mmHg_m2); EXPECT_TRUE( es->HasRightGlomerularFluidPermeability()); EXPECT_EQ(1.0, es->GetRightGlomerularFluidPermeability(VolumePerTimePressureAreaUnit::mL_Per_min_mmHg_m2)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightGlomerularFluidPermeability()); auto dvalue = ces.GetRightGlomerularFluidPermeability(VolumePerTimePressureAreaUnit::mL_Per_min_mmHg_m2); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightTubularReabsorptionFluidPermeability) { EXPECT_FALSE( es->HasRightTubularReabsorptionFluidPermeability()); es->GetRightTubularReabsorptionFluidPermeability().SetValue(1.0, VolumePerTimePressureAreaUnit::mL_Per_min_mmHg_m2); EXPECT_TRUE( es->HasRightTubularReabsorptionFluidPermeability()); EXPECT_EQ(1.0, es->GetRightTubularReabsorptionFluidPermeability(VolumePerTimePressureAreaUnit::mL_Per_min_mmHg_m2)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightTubularReabsorptionFluidPermeability()); auto dvalue = ces.GetRightTubularReabsorptionFluidPermeability(VolumePerTimePressureAreaUnit::mL_Per_min_mmHg_m2); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftNetFiltrationPressure) { EXPECT_FALSE( es->HasLeftNetFiltrationPressure()); es->GetLeftNetFiltrationPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasLeftNetFiltrationPressure()); EXPECT_EQ(1.0, es->GetLeftNetFiltrationPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftNetFiltrationPressure()); auto dvalue = ces.GetLeftNetFiltrationPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftNetReabsorptionPressure) { EXPECT_FALSE( es->HasLeftNetReabsorptionPressure()); es->GetLeftNetReabsorptionPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasLeftNetReabsorptionPressure()); EXPECT_EQ(1.0, es->GetLeftNetReabsorptionPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftNetReabsorptionPressure()); auto dvalue = ces.GetLeftNetReabsorptionPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftPeritubularCapillariesHydrostaticPressure) { EXPECT_FALSE( es->HasLeftPeritubularCapillariesHydrostaticPressure()); es->GetLeftPeritubularCapillariesHydrostaticPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasLeftPeritubularCapillariesHydrostaticPressure()); EXPECT_EQ(1.0, es->GetLeftPeritubularCapillariesHydrostaticPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftPeritubularCapillariesHydrostaticPressure()); auto dvalue = ces.GetLeftPeritubularCapillariesHydrostaticPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftTubularHydrostaticPressure) { EXPECT_FALSE( es->HasLeftTubularHydrostaticPressure()); es->GetLeftTubularHydrostaticPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasLeftTubularHydrostaticPressure()); EXPECT_EQ(1.0, es->GetLeftTubularHydrostaticPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftTubularHydrostaticPressure()); auto dvalue = ces.GetLeftTubularHydrostaticPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftTubularOsmoticPressure) { EXPECT_FALSE( es->HasLeftTubularOsmoticPressure()); es->GetLeftTubularOsmoticPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasLeftTubularOsmoticPressure()); EXPECT_EQ(1.0, es->GetLeftTubularOsmoticPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftTubularOsmoticPressure()); auto dvalue = ces.GetLeftTubularOsmoticPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightBowmansCapsulesHydrostaticPressure) { EXPECT_FALSE( es->HasRightBowmansCapsulesHydrostaticPressure()); es->GetRightBowmansCapsulesHydrostaticPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasRightBowmansCapsulesHydrostaticPressure()); EXPECT_EQ(1.0, es->GetRightBowmansCapsulesHydrostaticPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightBowmansCapsulesHydrostaticPressure()); auto dvalue = ces.GetRightBowmansCapsulesHydrostaticPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightBowmansCapsulesOsmoticPressure) { EXPECT_FALSE( es->HasRightBowmansCapsulesOsmoticPressure()); es->GetRightBowmansCapsulesOsmoticPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasRightBowmansCapsulesOsmoticPressure()); EXPECT_EQ(1.0, es->GetRightBowmansCapsulesOsmoticPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightBowmansCapsulesOsmoticPressure()); auto dvalue = ces.GetRightBowmansCapsulesOsmoticPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightGlomerularCapillariesHydrostaticPressure) { EXPECT_FALSE( es->HasRightGlomerularCapillariesHydrostaticPressure()); es->GetRightGlomerularCapillariesHydrostaticPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasRightGlomerularCapillariesHydrostaticPressure()); EXPECT_EQ(1.0, es->GetRightGlomerularCapillariesHydrostaticPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightGlomerularCapillariesHydrostaticPressure()); auto dvalue = ces.GetRightGlomerularCapillariesHydrostaticPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightGlomerularCapillariesOsmoticPressure) { EXPECT_FALSE( es->HasRightGlomerularCapillariesOsmoticPressure()); es->GetRightGlomerularCapillariesOsmoticPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasRightGlomerularCapillariesOsmoticPressure()); EXPECT_EQ(1.0, es->GetRightGlomerularCapillariesOsmoticPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightGlomerularCapillariesOsmoticPressure()); auto dvalue = ces.GetRightGlomerularCapillariesOsmoticPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightNetFiltrationPressure) { EXPECT_FALSE( es->HasRightNetFiltrationPressure()); es->GetRightNetFiltrationPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasRightNetFiltrationPressure()); EXPECT_EQ(1.0, es->GetRightNetFiltrationPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightNetFiltrationPressure()); auto dvalue = ces.GetRightNetFiltrationPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightNetReabsorptionPressure) { EXPECT_FALSE( es->HasRightNetReabsorptionPressure()); es->GetRightNetReabsorptionPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasRightNetReabsorptionPressure()); EXPECT_EQ(1.0, es->GetRightNetReabsorptionPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightNetReabsorptionPressure()); auto dvalue = ces.GetRightNetReabsorptionPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightPeritubularCapillariesHydrostaticPressure) { EXPECT_FALSE( es->HasRightPeritubularCapillariesHydrostaticPressure()); es->GetRightPeritubularCapillariesHydrostaticPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasRightPeritubularCapillariesHydrostaticPressure()); EXPECT_EQ(1.0, es->GetRightPeritubularCapillariesHydrostaticPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightPeritubularCapillariesHydrostaticPressure()); auto dvalue = ces.GetRightPeritubularCapillariesHydrostaticPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightPeritubularCapillariesOsmoticPressure) { EXPECT_FALSE( es->HasRightPeritubularCapillariesOsmoticPressure()); es->GetRightPeritubularCapillariesOsmoticPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasRightPeritubularCapillariesOsmoticPressure()); EXPECT_EQ(1.0, es->GetRightPeritubularCapillariesOsmoticPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightPeritubularCapillariesOsmoticPressure()); auto dvalue = ces.GetRightPeritubularCapillariesOsmoticPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightTubularHydrostaticPressure) { EXPECT_FALSE( es->HasRightTubularHydrostaticPressure()); es->GetRightTubularHydrostaticPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasRightTubularHydrostaticPressure()); EXPECT_EQ(1.0, es->GetRightTubularHydrostaticPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightTubularHydrostaticPressure()); auto dvalue = ces.GetRightTubularHydrostaticPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightTubularOsmoticPressure) { EXPECT_FALSE( es->HasRightTubularOsmoticPressure()); es->GetRightTubularOsmoticPressure().SetValue(1.0, PressureUnit::Pa); EXPECT_TRUE( es->HasRightTubularOsmoticPressure()); EXPECT_EQ(1.0, es->GetRightTubularOsmoticPressure(PressureUnit::Pa)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightTubularOsmoticPressure()); auto dvalue = ces.GetRightTubularOsmoticPressure(PressureUnit::Pa); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftReabsorptionRate) { EXPECT_FALSE( es->HasLeftReabsorptionRate()); es->GetLeftReabsorptionRate().SetValue(1.0, VolumePerTimeUnit::L_Per_min); EXPECT_TRUE( es->HasLeftReabsorptionRate()); EXPECT_EQ(1.0, es->GetLeftReabsorptionRate(VolumePerTimeUnit::L_Per_min)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftReabsorptionRate()); auto dvalue = ces.GetLeftReabsorptionRate(VolumePerTimeUnit::L_Per_min); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RenalBloodFlow) { EXPECT_FALSE( es->HasRenalBloodFlow()); es->GetRenalBloodFlow().SetValue(1.0, VolumePerTimeUnit::L_Per_min); EXPECT_TRUE( es->HasRenalBloodFlow()); EXPECT_EQ(1.0, es->GetRenalBloodFlow(VolumePerTimeUnit::L_Per_min)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRenalBloodFlow()); auto dvalue = ces.GetRenalBloodFlow(VolumePerTimeUnit::L_Per_min); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RenalPlasmaFlow) { EXPECT_FALSE( es->HasRenalPlasmaFlow()); es->GetRenalPlasmaFlow().SetValue(1.0, VolumePerTimeUnit::L_Per_min); EXPECT_TRUE( es->HasRenalPlasmaFlow()); EXPECT_EQ(1.0, es->GetRenalPlasmaFlow(VolumePerTimeUnit::L_Per_min)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRenalPlasmaFlow()); auto dvalue = ces.GetRenalPlasmaFlow(VolumePerTimeUnit::L_Per_min); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightGlomerularFiltrationRate) { EXPECT_FALSE( es->HasRightGlomerularFiltrationRate()); es->GetRightGlomerularFiltrationRate().SetValue(1.0, VolumePerTimeUnit::L_Per_min); EXPECT_TRUE( es->HasRightGlomerularFiltrationRate()); EXPECT_EQ(1.0, es->GetRightGlomerularFiltrationRate(VolumePerTimeUnit::L_Per_min)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightGlomerularFiltrationRate()); auto dvalue = ces.GetRightGlomerularFiltrationRate(VolumePerTimeUnit::L_Per_min); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightReabsorptionRate) { EXPECT_FALSE( es->HasRightReabsorptionRate()); es->GetRightReabsorptionRate().SetValue(1.0, VolumePerTimeUnit::L_Per_min); EXPECT_TRUE( es->HasRightReabsorptionRate()); EXPECT_EQ(1.0, es->GetRightReabsorptionRate(VolumePerTimeUnit::L_Per_min)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightReabsorptionRate()); auto dvalue = ces.GetRightReabsorptionRate(VolumePerTimeUnit::L_Per_min); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, UrinationRate) { EXPECT_FALSE( es->HasUrinationRate()); es->GetUrinationRate().SetValue(1.0, VolumePerTimeUnit::L_Per_min); EXPECT_TRUE( es->HasUrinationRate()); EXPECT_EQ(1.0, es->GetUrinationRate(VolumePerTimeUnit::L_Per_min)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasUrinationRate()); auto dvalue = ces.GetUrinationRate(VolumePerTimeUnit::L_Per_min); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, UrineProductionRate) { EXPECT_FALSE( es->HasUrineProductionRate()); es->GetUrineProductionRate().SetValue(1.0, VolumePerTimeUnit::L_Per_min); EXPECT_TRUE( es->HasUrineProductionRate()); EXPECT_EQ(1.0, es->GetUrineProductionRate(VolumePerTimeUnit::L_Per_min)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasUrineProductionRate()); auto dvalue = ces.GetUrineProductionRate(VolumePerTimeUnit::L_Per_min); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RenalVascularResistance) { EXPECT_FALSE( es->HasRenalVascularResistance()); es->GetRenalVascularResistance().SetValue(1.0, FlowResistanceUnit::Pa_s_Per_m3); EXPECT_TRUE( es->HasRenalVascularResistance()); EXPECT_EQ(1.0, es->GetRenalVascularResistance(FlowResistanceUnit::Pa_s_Per_m3)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRenalVascularResistance()); auto dvalue = ces.GetRenalVascularResistance(FlowResistanceUnit::Pa_s_Per_m3); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightAfferentArterioleResistance) { EXPECT_FALSE( es->HasRightAfferentArterioleResistance()); es->GetRightAfferentArterioleResistance().SetValue(1.0, FlowResistanceUnit::Pa_s_Per_m3); EXPECT_TRUE( es->HasRightAfferentArterioleResistance()); EXPECT_EQ(1.0, es->GetRightAfferentArterioleResistance(FlowResistanceUnit::Pa_s_Per_m3)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightAfferentArterioleResistance()); auto dvalue = ces.GetRightAfferentArterioleResistance(FlowResistanceUnit::Pa_s_Per_m3); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightEfferentArterioleResistance) { EXPECT_FALSE( es->HasRightEfferentArterioleResistance()); es->GetRightEfferentArterioleResistance().SetValue(1.0, FlowResistanceUnit::Pa_s_Per_m3); EXPECT_TRUE( es->HasRightEfferentArterioleResistance()); EXPECT_EQ(1.0, es->GetRightEfferentArterioleResistance(FlowResistanceUnit::Pa_s_Per_m3)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightEfferentArterioleResistance()); auto dvalue = ces.GetRightEfferentArterioleResistance(FlowResistanceUnit::Pa_s_Per_m3); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, UrineOsmolality) { EXPECT_FALSE( es->HasUrineOsmolality()); es->GetUrineOsmolality().SetValue(1.0, OsmolalityUnit::Osm_Per_kg); EXPECT_TRUE( es->HasUrineOsmolality()); EXPECT_EQ(1.0, es->GetUrineOsmolality(OsmolalityUnit::Osm_Per_kg)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasUrineOsmolality()); auto dvalue = ces.GetUrineOsmolality(OsmolalityUnit::Osm_Per_kg); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, UrineVolume) { EXPECT_FALSE( es->HasUrineVolume()); es->GetUrineVolume().SetValue(1.0, VolumeUnit::L); EXPECT_TRUE( es->HasUrineVolume()); EXPECT_EQ(1.0, es->GetUrineVolume(VolumeUnit::L)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasUrineVolume()); auto dvalue = ces.GetUrineVolume(VolumeUnit::L); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, UrineUreaNitrogenConcentration) { EXPECT_FALSE( es->HasUrineUreaNitrogenConcentration()); es->GetUrineUreaNitrogenConcentration().SetValue(1.0, MassPerVolumeUnit::kg_Per_L); EXPECT_TRUE( es->HasUrineUreaNitrogenConcentration()); EXPECT_EQ(1.0, es->GetUrineUreaNitrogenConcentration(MassPerVolumeUnit::kg_Per_L)); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasUrineUreaNitrogenConcentration()); auto dvalue = ces.GetUrineUreaNitrogenConcentration(MassPerVolumeUnit::kg_Per_L); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, LeftFiltrationFraction) { EXPECT_FALSE( es->HasLeftFiltrationFraction()); es->GetLeftFiltrationFraction().SetValue(1.0); EXPECT_TRUE( es->HasLeftFiltrationFraction()); EXPECT_EQ(1.0, es->GetLeftFiltrationFraction().GetValue()); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasLeftFiltrationFraction()); auto dvalue = ces.GetLeftFiltrationFraction(); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, RightFiltrationFraction) { EXPECT_FALSE( es->HasRightFiltrationFraction()); es->GetRightFiltrationFraction().SetValue(1.0); EXPECT_TRUE( es->HasRightFiltrationFraction()); EXPECT_EQ(1.0, es->GetRightFiltrationFraction().GetValue()); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasRightFiltrationFraction()); auto dvalue = ces.GetRightFiltrationFraction(); EXPECT_NE(dvalue, dvalue); } TEST_F(TEST_FIXTURE_NAME, UrineSpecificGravity) { EXPECT_FALSE( es->HasUrineSpecificGravity()); es->GetUrineSpecificGravity().SetValue(1.0); EXPECT_TRUE( es->HasUrineSpecificGravity()); EXPECT_EQ(1.0, es->GetUrineSpecificGravity().GetValue()); const biogears::SERenalSystem ces(logger); EXPECT_FALSE( ces.HasUrineSpecificGravity()); auto dvalue = ces.GetUrineSpecificGravity(); EXPECT_NE(dvalue, dvalue); } //GlomerularFiltrationRate - VolumePerTime //FiltartionFraction - //LeftAfferentArterioleResistance - FlowResistanceUnit //LeftBowmansCapsulesHydrostaticPressure - PressureUnit //LeftBowmansCapsulesOsmoticPressure - PressureUnit //LeftEfferentArterioleResistance - FlowResistanceUnit //LeftGlomerularCapillariesHydrostaticPressure - PressureUnit //LeftGlomerularCapillariesOsmoticPressure - PressureUnit //LeftGlomerularFiltrationCoefficient - VolumePerTimePressureUnit //LeftGlomerularFiltrationSurfaceArea - AreaUnit //LeftGlomerularFluidPermeability - VolumePerTimePressureAreaUnit //LeftFiltrationFraction - //LeftNetFiltrationPressure - PressureUnit //LeftNetReabsorptionPressure - PressureUnit //LeftPeritubularCapillariesHydrostaticPressure - PressureUnit //LeftReabsorptionFiltrationCoefficient - VolumePerTimePressureUnit //LeftReabsorptionRate - VolumePerTimeUnit //LeftTubularReabsorptionFiltrationSurfaceArea - AreaUnit //LeftTubularReabsorptionFluidPermeability - VolumePerTimePressureAreaUnit //LeftTubularHydrostaticPressure - PressureUnit //LeftTubularOsmoticPressure - PressureUnit //RenalBloodFlow - VolumePerTimeUnit //RenalPlasmaFlow - VolumePerTimeUnit //RenalVascularResistance - FlowResistanceUnit //RightAfferentArterioleResistance - FlowResistanceUnit //RightBowmansCapsulesHydrostaticPressure - PressureUnit //RightBowmansCapsulesOsmoticPressure - PressureUnit //RightEfferentArterioleResistance - FlowResistanceUnit //RightGlomerularCapillariesHydrostaticPressure - PressureUnit //RightGlomerularCapillariesOsmoticPressure - PressureUnit //RightGlomerularFiltrationCoefficient - VolumePerTimePressureUnit //RightGlomerularFiltrationRate - VolumePerTimeUnit //RightGlomerularFiltrationSurfaceArea - AreaUnit //RightGlomerularFluidPermeability - VolumePerTimePressureAreaUnit //RightFiltrationFraction //RightNetFiltrationPressure - PressureUnit //RightNetReabsorptionPressure - PressureUnit //RightPeritubularCapillariesHydrostaticPressure - PressureUnit //RightPeritubularCapillariesOsmoticPressure - PressureUnit //RightReabsorptionFiltrationCoefficient - VolumePerTimePressureUnit //RightReabsorptionRate - VolumePerTimeUnit //RightTubularReabsorptionFiltrationSurfaceArea - AreaUnit //RightTubularReabsorptionFluidPermeability - VolumePerTimePressreAreaUnit //RightTubularHydrostaticPressure - PressureUnit //RightTubularOsmoticPressure - PressureUnit //UrinationRate - VolumePerTimeUnit //UrineOsmolality - OsmolalityUnit //UrineProductionRate - VolumePerTimeUnit //UrineSpecificGravity - //UrineVolume - VolumeUnit //UrineUreaNitrogenConcentration - MassPerVolumeUnit
/* * Copyright (c) 2016 Samsung Electronics Co., Ltd. * * 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 <dali/dali.h> #include <dali-toolkit/dali-toolkit.h> #include <test-button.h> using namespace Dali; using namespace Dali::Toolkit; namespace { Property::Value ConvertAnimationMap( const Test::TestAnimationData& animationMap ) { // We have a data structure. Now convert it back into an array: Property::Array animators; for( unsigned int i=0; i<animationMap.Size(); ++i ) { Property::Map animator; animator.Insert( "target", Property::Value(animationMap.mAnimationDataList[i]->target )); animator.Insert( "property", Property::Value(animationMap.mAnimationDataList[i]->property )); animator.Insert( "value", Property::Value(animationMap.mAnimationDataList[i]->value )); animator.Insert( "alphaFunction", Property::Value(animationMap.mAnimationDataList[i]->alphaFunction )); animator.Insert( "timePeriodDelay", Property::Value(animationMap.mAnimationDataList[i]->timePeriodDelay )); animator.Insert( "timePeriodDuration", Property::Value(animationMap.mAnimationDataList[i]->timePeriodDuration )); animators.PushBack( animator ); } Property::Value animation( animators ); return animation; } } namespace Test { namespace Impl { Test::TestButton TestButton::New() { IntrusivePtr<TestButton> internalTestButton = new TestButton(); Test::TestButton button( *internalTestButton ); internalTestButton->Initialize(); return button; } TestButton::TestButton() : Control( ControlBehaviour() ) { } TestButton::~TestButton() { } void TestButton::SetProperty( BaseObject* object, Property::Index index, const Property::Value& value ) { Test::TestButton button = Test::TestButton::DownCast( Dali::BaseHandle( object ) ); if ( button ) { TestButton& buttonImpl = GetImpl(button); switch ( index ) { case Test::TestButton::Property::PRESS_TRANSITION: { if( value.GetType() == Property::MAP ) { const Property::Map* valueMap = value.GetMap(); buttonImpl.mPressTransitionData.Clear(); NewAnimation( *valueMap, buttonImpl.mPressTransitionData ); } else if( value.GetType() == Property::ARRAY ) { const Property::Array* valueArray = value.GetArray(); buttonImpl.mPressTransitionData.Clear(); NewAnimation( *valueArray, buttonImpl.mPressTransitionData ); } break; } case Test::TestButton::Property::BACKGROUND_COLOR: { buttonImpl.mBackgroundColor = value.Get<Vector4>(); break; } case Test::TestButton::Property::FOREGROUND_COLOR: { buttonImpl.mForegroundColor = value.Get<Vector4>(); break; } } } } Property::Value TestButton::GetProperty( BaseObject* object, Property::Index propertyIndex ) { Test::TestButton button = Test::TestButton::DownCast( Dali::BaseHandle( object ) ); Property::Value value; if ( button ) { TestButton& buttonImpl = GetImpl(button); switch ( propertyIndex ) { case Test::TestButton::Property::PRESS_TRANSITION: { return ConvertAnimationMap(buttonImpl.mPressTransitionData); } case Test::TestButton::Property::RELEASE_TRANSITION: { return ConvertAnimationMap(buttonImpl.mReleaseTransitionData); } case Test::TestButton::Property::DISABLED_TRANSITION: { return ConvertAnimationMap(buttonImpl.mDisabledTransitionData); } case Test::TestButton::Property::ENABLED_TRANSITION: { return ConvertAnimationMap(buttonImpl.mEnabledTransitionData); } case Test::TestButton::Property::BACKGROUND_COLOR: { return Property::Value(buttonImpl.mBackgroundColor); } case Test::TestButton::Property::FOREGROUND_COLOR: { return Property::Value(buttonImpl.mForegroundColor); } } } return Property::Value(); } BaseHandle Create() { return TestButton::New(); } // Generates typeRegistration static variable. DALI_TYPE_REGISTRATION_BEGIN( Test::TestButton, Dali::Toolkit::Control, Create ) DALI_PROPERTY_REGISTRATION( Test, TestButton, "pressTransition", ARRAY, PRESS_TRANSITION ) DALI_PROPERTY_REGISTRATION( Test, TestButton, "releaseTransition", ARRAY, RELEASE_TRANSITION) DALI_PROPERTY_REGISTRATION( Test, TestButton, "disabledTransition", ARRAY, DISABLED_TRANSITION ) DALI_PROPERTY_REGISTRATION( Test, TestButton, "enabledTransition", ARRAY, ENABLED_TRANSITION ) DALI_PROPERTY_REGISTRATION( Test, TestButton, "backgroundColor", VECTOR4, BACKGROUND_COLOR ) DALI_PROPERTY_REGISTRATION( Test, TestButton, "foregroundColor", VECTOR4, FOREGROUND_COLOR ) DALI_TYPE_REGISTRATION_END() } // Impl Namespace TestButton::TestButton() : Control() { } TestButton::TestButton(const TestButton& button) : Control( button ) { } TestButton::TestButton(Impl::TestButton& impl) : Control(impl) { } TestButton::TestButton(Dali::Internal::CustomActor* internal) : Control(internal) { VerifyCustomActorPointer<Impl::TestButton>(internal); } TestButton& TestButton::operator=( const TestButton& button) { if(&button != this) { Control::operator=(button); } return *this; } TestButton::~TestButton() { } TestButton TestButton::New() { return Impl::TestButton::New(); } TestButton TestButton::DownCast( BaseHandle handle ) { return Control::DownCast<TestButton,Impl::TestButton>(handle); } } // namespace Test
/** * @file setmaps.cpp * * Implementation of functionality the special quest dungeons. */ #include "setmaps.h" #include "drlg_l1.h" #include "drlg_l2.h" #include "drlg_l3.h" #include "engine/load_file.hpp" #include "objdat.h" #include "objects.h" #include "palette.h" #include "quests.h" #include "trigs.h" #include "utils/language.h" namespace devilution { /** Maps from quest level to quest level names. */ const char *const QuestLevelNames[] = { "", N_("Skeleton King's Lair"), N_("Chamber of Bone"), N_("Maze"), N_("Poisoned Water Supply"), N_("Archbishop Lazarus' Lair"), }; namespace { // BUGFIX: constant data should be const BYTE SkelKingTrans1[] = { 19, 47, 26, 55, 26, 49, 30, 53 }; BYTE SkelKingTrans2[] = { 33, 19, 47, 29, 37, 29, 43, 39 }; BYTE SkelKingTrans3[] = { 27, 53, 35, 61, 27, 35, 34, 42, 45, 35, 53, 43, 45, 53, 53, 61, 31, 39, 49, 57 }; BYTE SkelKingTrans4[] = { 49, 45, 58, 51, 57, 31, 62, 37, 63, 31, 69, 40, 59, 41, 73, 55, 63, 55, 69, 65, 73, 45, 78, 51, 79, 43, 89, 53 }; BYTE SkelChamTrans1[] = { 43, 19, 50, 26, 51, 19, 59, 26, 35, 27, 42, 34, 43, 27, 49, 34, 50, 27, 59, 34 }; BYTE SkelChamTrans2[] = { 19, 31, 34, 47, 34, 35, 42, 42 }; BYTE SkelChamTrans3[] = { 43, 35, 50, 42, 51, 35, 62, 42, 63, 31, 66, 46, 67, 31, 78, 34, 67, 35, 78, 42, 67, 43, 78, 46, 35, 43, 42, 51, 43, 43, 49, 51, 50, 43, 59, 51 }; void AddSKingObjs() { constexpr Rectangle SmallSecretRoom { { 20, 7 }, { 3, 3 } }; ObjectAtPosition({ 64, 34 })->InitializeLoadedObject(SmallSecretRoom, 1); constexpr Rectangle Gate { { 20, 14 }, { 1, 2 } }; ObjectAtPosition({ 64, 59 })->InitializeLoadedObject(Gate, 2); constexpr Rectangle LargeSecretRoom { { 8, 1 }, { 7, 10 } }; ObjectAtPosition({ 27, 37 })->InitializeLoadedObject(LargeSecretRoom, 3); ObjectAtPosition({ 46, 35 })->InitializeLoadedObject(LargeSecretRoom, 3); ObjectAtPosition({ 49, 53 })->InitializeLoadedObject(LargeSecretRoom, 3); ObjectAtPosition({ 27, 53 })->InitializeLoadedObject(LargeSecretRoom, 3); } void AddSChamObjs() { ObjectAtPosition({ 37, 30 })->InitializeLoadedObject({ { 17, 0 }, { 4, 5 } }, 1); ObjectAtPosition({ 37, 46 })->InitializeLoadedObject({ { 13, 0 }, { 3, 5 } }, 2); } void AddVileObjs() { ObjectAtPosition({ 26, 45 })->InitializeLoadedObject({ { 1, 1 }, { 8, 9 } }, 1); ObjectAtPosition({ 45, 46 })->InitializeLoadedObject({ { 11, 1 }, { 9, 9 } }, 2); ObjectAtPosition({ 35, 36 })->InitializeLoadedObject({ { 7, 11 }, { 6, 7 } }, 3); } void SetmapTransparancy(const char *path) { auto dunData = LoadFileInMem<uint16_t>(path); int width = SDL_SwapLE16(dunData[0]); int height = SDL_SwapLE16(dunData[1]); int layer2Offset = 2 + width * height; // The rest of the layers are at dPiece scale width *= 2; height *= 2; const uint16_t *transparantLayer = &dunData[layer2Offset + width * height * 3]; for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { dTransVal[16 + i][16 + j] = SDL_SwapLE16(*transparantLayer); transparantLayer++; } } } } // namespace void LoadSetMap() { switch (setlvlnum) { case SL_SKELKING: if (Quests[Q_SKELKING]._qactive == QUEST_INIT) { Quests[Q_SKELKING]._qactive = QUEST_ACTIVE; Quests[Q_SKELKING]._qvar1 = 1; } LoadPreL1Dungeon("Levels\\L1Data\\SklKng1.DUN"); LoadL1Dungeon("Levels\\L1Data\\SklKng2.DUN", 83, 45); LoadPalette("Levels\\L1Data\\L1_2.pal"); DRLG_AreaTrans(sizeof(SkelKingTrans1) / 4, &SkelKingTrans1[0]); DRLG_ListTrans(sizeof(SkelKingTrans2) / 4, &SkelKingTrans2[0]); DRLG_AreaTrans(sizeof(SkelKingTrans3) / 4, &SkelKingTrans3[0]); DRLG_ListTrans(sizeof(SkelKingTrans4) / 4, &SkelKingTrans4[0]); AddL1Objs(0, 0, MAXDUNX, MAXDUNY); AddSKingObjs(); InitSKingTriggers(); break; case SL_BONECHAMB: LoadPreL2Dungeon("Levels\\L2Data\\Bonecha2.DUN"); LoadL2Dungeon("Levels\\L2Data\\Bonecha1.DUN", 69, 39); LoadPalette("Levels\\L2Data\\L2_2.pal"); DRLG_ListTrans(sizeof(SkelChamTrans1) / 4, &SkelChamTrans1[0]); DRLG_AreaTrans(sizeof(SkelChamTrans2) / 4, &SkelChamTrans2[0]); DRLG_ListTrans(sizeof(SkelChamTrans3) / 4, &SkelChamTrans3[0]); AddL2Objs(0, 0, MAXDUNX, MAXDUNY); AddSChamObjs(); InitSChambTriggers(); break; case SL_MAZE: LoadPreL1Dungeon("Levels\\L1Data\\Lv1MazeA.DUN"); LoadL1Dungeon("Levels\\L1Data\\Lv1MazeB.DUN", 20, 50); LoadPalette("Levels\\L1Data\\L1_5.pal"); AddL1Objs(0, 0, MAXDUNX, MAXDUNY); SetmapTransparancy("Levels\\L1Data\\Lv1MazeA.DUN"); break; case SL_POISONWATER: if (Quests[Q_PWATER]._qactive == QUEST_INIT) Quests[Q_PWATER]._qactive = QUEST_ACTIVE; LoadPreL3Dungeon("Levels\\L3Data\\Foulwatr.DUN"); LoadL3Dungeon("Levels\\L3Data\\Foulwatr.DUN", 31, 83); LoadPalette("Levels\\L3Data\\L3pfoul.pal"); InitPWaterTriggers(); break; case SL_VILEBETRAYER: if (Quests[Q_BETRAYER]._qactive == QUEST_DONE) { Quests[Q_BETRAYER]._qvar2 = 4; } else if (Quests[Q_BETRAYER]._qactive == QUEST_ACTIVE) { Quests[Q_BETRAYER]._qvar2 = 3; } LoadPreL1Dungeon("Levels\\L1Data\\Vile1.DUN"); LoadL1Dungeon("Levels\\L1Data\\Vile2.DUN", 35, 36); LoadPalette("Levels\\L1Data\\L1_2.pal"); AddL1Objs(0, 0, MAXDUNX, MAXDUNY); AddVileObjs(); SetmapTransparancy("Levels\\L1Data\\Vile1.DUN"); InitNoTriggers(); break; case SL_NONE: break; } } } // namespace devilution
// Long Vy - October 20, 2017 - Proj4_1_V1 // This program uses functions to print text #include <iostream> #include <string> using namespace std; int rows, columns, fields, i, j, k; char symbol = '*'; void input(void) // User input function for rows, columns, and fields { do { cout << "Please enter the number of rows [1-5]: "; cin >> rows; if (rows <= 0 || rows > 5) // User trap for invalid inputs stops program { cout << "Please enter a valid number between 1 and 5." << endl << endl; } } while (rows <= 0 || rows > 5); do { cout << "Please enter the number of columns [5-50]: "; cin >> columns; if (columns < 5 || columns > 50) // User trap for invalid inputs stops program { cout << "Please enter a valid number between 5 and 50." << endl << endl; } } while (columns < 5 || columns >50); do { cout << "Please enter the number of fields [3-10]: "; cin >> fields; if (fields < 3 || fields > 10) // User trap for invalid inputs stops program { cout << "Please enter a valid number between 3 and 10" << endl << endl; } } while (fields < 3 || fields > 10); } void loopfunction(void) { for (k = 1; k <= fields; k++) { cout << endl << endl << endl; for (i = 1; i <= rows; i++) { for (j = 1; j <= columns; j++) { cout << symbol; } cout << endl; } } } int main(void) { input(); loopfunction(); return 0; }
/* * Copyright (c) 2011-2016, Matthieu FAESSEL and ARMINES * 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 Matthieu FAESSEL, or ARMINES 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 HOLDERS AND CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef _D_MORPHO_HIERARQ_HPP #define _D_MORPHO_HIERARQ_HPP #include <queue> #include <deque> #include "Core/include/private/DTypes.hpp" #include "Morpho/include/DStructuringElement.h" namespace smil { /** * @ingroup Morpho * @defgroup HierarQ Hierarchical Queues * @{ */ enum HQ_STATUS { HQ_CANDIDATE, HQ_QUEUED, HQ_LABELED, HQ_WS_LINE, HQ_FINAL }; /** * Preallocated FIFO Queue */ template <class T> class FIFO_Queue { public: FIFO_Queue(size_t newSize = 0) { data = NULL; if (newSize) initialize(newSize); } virtual ~FIFO_Queue() { if (data) delete[] data; } void reset() { if (data) delete[] data; data = NULL; _size = realSize = 0; } void initialize(size_t newSize) { reset(); realSize = max(newSize + 1, size_t(8)); // Avoid to have to small buffer data = new T[realSize]; _size = 0; first = 0; last = 0; } inline size_t size() { return _size; } void swap() { memmove(data, data + first, (last - first) * sizeof(T)); first = 0; last = _size; } void push(T val) { if (last == realSize) swap(); data[last++] = val; _size++; } inline T front() { return data[first]; } inline void pop() { _size--; first++; } static const bool preallocate = true; protected: size_t _size; size_t realSize; size_t first; size_t last; T *data; }; template <class TokenType = size_t> class STD_Queue : public queue<TokenType> { public: // Dummy constructor for compatibilty with FIFO_Queue one STD_Queue(size_t /*newSize*/ = 0) : queue<TokenType>() { } static const bool preallocate = false; }; template <class TokenType = size_t> class STD_Stack : public stack<TokenType> { public: // Dummy operator for compatibility with other containers from smil inline TokenType front() { return this->top(); } }; template <class T, class TokenType = size_t, class StackType = STD_Queue<TokenType> > class HierarchicalQueue { private: size_t GRAY_LEVEL_NBR; size_t GRAY_LEVEL_MIN; size_t GRAY_LEVEL_MAX; StackType **stacks; size_t *tokenNbr; size_t size; size_t higherLevel; bool initialized; const bool reverseOrder; public: HierarchicalQueue(bool rOrder = false) : reverseOrder(rOrder) { stacks = NULL; tokenNbr = NULL; initialized = false; } ~HierarchicalQueue() { reset(); delete[] stacks; delete[] tokenNbr; } void reset() { if (!initialized) return; for (size_t i = 0; i < GRAY_LEVEL_NBR; i++) { if (stacks[i]) { delete stacks[i]; stacks[i] = NULL; } } initialized = false; } void initialize(const Image<T> &img) { if (initialized) reset(); // vector<T> rVals = rangeVal(img); GRAY_LEVEL_MIN = ImDtTypes<T>::min(); GRAY_LEVEL_MAX = ImDtTypes<T>::max(); GRAY_LEVEL_NBR = ImDtTypes<T>::cardinal(); stacks = new StackType *[GRAY_LEVEL_NBR](); tokenNbr = new size_t[GRAY_LEVEL_NBR]; if (StackType::preallocate) { size_t *h = new size_t[GRAY_LEVEL_NBR]; histogram(img, h); for (size_t i = 0; i < GRAY_LEVEL_NBR; i++) { if (h[i] != 0) stacks[i] = new StackType(h[i]); else stacks[i] = NULL; } delete[] h; } else { for (size_t i = 0; i < GRAY_LEVEL_NBR; i++) stacks[i] = new StackType(); } memset(tokenNbr, 0, GRAY_LEVEL_NBR * sizeof(size_t)); size = 0; if (reverseOrder) higherLevel = 0; else higherLevel = ImDtTypes<T>::max(); initialized = true; } inline size_t getSize() { return size; } inline bool isEmpty() { return size == 0; } inline size_t getHigherLevel() { return GRAY_LEVEL_MIN + higherLevel; } inline void push(T value, TokenType dOffset) { size_t level = size_t(value) - GRAY_LEVEL_MIN; if (reverseOrder) { if (level > higherLevel) higherLevel = level; } else { if (level < higherLevel) higherLevel = level; } stacks[level]->push(dOffset); tokenNbr[level]++; size++; } inline void findNewReferenceLevel() { // XXX JOE - there still may be a problem here... // it was ImDtTypes<T>::max() if (reverseOrder) { for (size_t i = higherLevel - 1; i != GRAY_LEVEL_MAX; i--) { if (tokenNbr[i] > 0) { higherLevel = i; break; } } } else { for (size_t i = higherLevel + 1; i < GRAY_LEVEL_NBR; i++) { if (tokenNbr[i] > 0) { higherLevel = i; break; } } } } inline TokenType pop() { size_t hlSize = tokenNbr[higherLevel]; TokenType dOffset = stacks[higherLevel]->front(); stacks[higherLevel]->pop(); size--; if (hlSize > 1) { tokenNbr[higherLevel]--; } else { if (size > 0) { // Find new ref level (non empty stack) tokenNbr[higherLevel] = 0; findNewReferenceLevel(); } else { // Empty -> re-initilize tokenNbr[higherLevel] = 0; if (reverseOrder) higherLevel = 0; else higherLevel = ImDtTypes<size_t>::max(); } } return dOffset; } }; /** @}*/ } // namespace smil #endif // _D_MORPHO_HIERARQ_HPP
// Copyright 1996-2018 Cyberbotics Ltd. // // 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 "WbPreferences.hpp" #include "WbLog.hpp" #include "WbStandardPaths.hpp" #include "WbSysInfo.hpp" #ifdef _WIN32 #include "WbWindowsRegistry.hpp" #endif #include <QtCore/QDir> #include <QtCore/QFile> #include <QtCore/QProcess> #include <QtCore/QRegularExpressionMatch> #include <QtCore/QStandardPaths> static WbPreferences *gInstance = NULL; WbPreferences *WbPreferences::createInstance(const QString &companyName, const QString &applicationName, const WbVersion &version) { if (gInstance) delete gInstance; #ifdef __linux__ if (WbSysInfo::isRootUser()) QSettings::setPath(QSettings::NativeFormat, QSettings::UserScope, "/root/.config/"); #endif gInstance = new WbPreferences(companyName, applicationName, version); return gInstance; } WbPreferences *WbPreferences::instance() { return gInstance; } void WbPreferences::cleanup() { delete gInstance; gInstance = NULL; } WbPreferences::WbPreferences(const QString &companyName, const QString &applicationName, const WbVersion &version) : QSettings(QSettings::NativeFormat, QSettings::UserScope, companyName, QString("%1-%2").arg(applicationName).arg(version.toString(false))), mCompanyName(companyName), mApplicationName(applicationName), mVersion(version) { // use only one preferences file setFallbacksEnabled(false); // set defaults for preferences that are accessed from several locations setDefault("General/startupMode", "Real-time"); setDefault("General/language", ""); setDefault("General/numberOfThreads", WbSysInfo::coreCount()); setDefault("General/threadingPolicy", 0); setDefault("General/checkWebotsUpdateOnStartup", true); setDefault("General/disableSaveWarning", false); setDefault("Sound/mute", true); setDefault("Sound/volume", 80); setDefault("OpenGL/disableShadows", false); setDefault("OpenGL/disableCameraAntiAliasing", false); setDefault("OpenGL/SMAA", true); setDefault("OpenGL/GTAO", 2); setDefault("VirtualRealityHeadset/enable", false); setDefault("VirtualRealityHeadset/trackPosition", true); setDefault("VirtualRealityHeadset/trackOrientation", true); setDefault("VirtualRealityHeadset/visibleEye", "left"); setDefault("VirtualRealityHeadset/antiAliasing", false); setDefault("View3d/hideAllCameraOverlays", false); setDefault("View3d/hideAllRangeFinderOverlays", false); setDefault("View3d/hideAllDisplayOverlays", false); #ifdef _WIN32 // "Monospace" isn't supported under Windows: the non-monospaced Arial font is loaded instead setDefault("Editor/font", "Consolas,10"); #elif defined(__APPLE__) setDefault("Editor/font", "Courier,14"); // "Monospace" isn't supported under MacOS #else setDefault("Editor/font", "Monospace, 9"); #endif // "Consolas" seems to be a standard Windows monospaced font, so we use it instead setDefault("Internal/firstLaunch", true); setDefault("Movie/resolution", 6); // 480p: 854 x 480 setDefault("Movie/quality", 90); setDefault("Movie/acceleration", 1.0); setDefault("Movie/caption", false); setDefault("Directories/projects", QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/"); setDefault("Directories/movies", QStandardPaths::writableLocation(QStandardPaths::MoviesLocation) + "/"); setDefault("Directories/screenshots", QStandardPaths::writableLocation(QStandardPaths::PicturesLocation) + "/"); setDefault("Directories/vrml", QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/"); setDefault("Directories/objects", QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/"); setDefault("Directories/www", QStandardPaths::writableLocation(QStandardPaths::DocumentsLocation) + "/"); setDefaultPythonCommand(); } WbPreferences::~WbPreferences() { setValue("Internal/firstLaunch", false); } void WbPreferences::setDefaultPythonCommand() { foreach (const QString &command, QStringList() << "python" << "python3") { QProcess process; #ifdef _WIN32 process.start(command + ".exe", QStringList() << "-c" << "print('PYTHON_COMMAND_FOUND');"); #else // macOS and Linux process.start(command, QStringList() << "-c" << "print('PYTHON_COMMAND_FOUND');"); #endif process.waitForFinished(); if (process.readAll().startsWith("PYTHON_COMMAND_FOUND")) { setDefault("General/pythonCommand", command); return; } } setDefault("General/pythonCommand", "python"); } void WbPreferences::setDefault(const QString &key, const QVariant &value) { if (!contains(key)) setValue(key, value); } void WbPreferences::setMoviePreferences(int resolutionIndex, int quality, double acceleration, bool caption) { setValue("Movie/resolution", resolutionIndex); setValue("Movie/quality", quality); setValue("Movie/acceleration", acceleration); setValue("Movie/caption", caption); } void WbPreferences::moviePreferences(int &resolutionIndex, int &quality, double &acceleration, bool &caption) const { resolutionIndex = value("Movie/resolution").toInt(); quality = value("Movie/quality").toInt(); acceleration = value("Movie/acceleration").toDouble(); caption = value("Movie/caption").toBool(); } QString WbPreferences::accessErrorString() const { if (status() == QSettings::AccessError) { if (QFile::exists(fileName())) return "<font color=\"red\">" + tr("Errors when accessing the preferences file.") + "<br>" + tr("If the error persists, please check your access rights on file:") + "<br>" + fileName() + "</font>"; } return QString(); } QString WbPreferences::findPreviousSettingsLocation() const { QStringList potentialLocations; #ifdef _WIN32 const QString registryRootLocation = QString("\\HKEY_CURRENT_USER\\SOFTWARE\\%1\\").arg(mCompanyName); potentialLocations = WbWindowsRegistry(registryRootLocation).subKeys(); potentialLocations.replaceInStrings(QRegExp("^"), registryRootLocation); #else #ifdef __APPLE__ QDir preferencesDirectory(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation)); #else // __linux__ QDir preferencesDirectory(QStandardPaths::writableLocation(QStandardPaths::ConfigLocation) + "/" + mCompanyName); #endif preferencesDirectory.setFilter(QDir::Files); QStringList filters; #ifdef __APPLE__ filters << QString("com.%1.%2*.plist").arg(mCompanyName.toLower()).arg(mApplicationName); #else // __linux__ filters << QString("%1*.conf").arg(mApplicationName); #endif preferencesDirectory.setNameFilters(filters); QFileInfoList preferencesFileInfos = preferencesDirectory.entryInfoList(); for (int i = 0; i < preferencesFileInfos.size(); ++i) { QFileInfo preferencesFileInfo = preferencesFileInfos.at(i); potentialLocations << preferencesFileInfo.absoluteFilePath(); } #endif QString lastLocation; WbVersion lastLocationVersion; foreach (const QString &location, potentialLocations) { QFileInfo preferencesFileInfo(location); QRegularExpressionMatch match; WbVersion versionOfMatchedFile; WbVersion versionToTest(mVersion); if (preferencesFileInfo.fileName().contains(QRegularExpression("R\\d+\\w+"), &match)) versionToTest.setRevision(0); // the maintenance version should not be present when testing else if (preferencesFileInfo.fileName().contains(QRegularExpression("\\d+\\.\\d+\\.\\d+"), &match)) { } else if (preferencesFileInfo.fileName().contains(QRegularExpression("\\d+\\.\\d+"), &match)) versionToTest.setRevision(0); // the maintenance version should not be present when testing else // file name doesn't match any expected config file pattern continue; versionOfMatchedFile.fromString(match.captured()); if (versionOfMatchedFile > lastLocationVersion && versionOfMatchedFile < versionToTest) { lastLocationVersion = versionOfMatchedFile; lastLocation = location; } } return lastLocation; } #ifdef __linux__ void WbPreferences::checkIsWritable() { if (!isWritable()) WbLog::warning(tr("\nPreferences file cannot be overwritten.\n" "Any change to the current settings won't be restored at next Webots start.\n\n" "Please check the write permissions on file:\n\"%1\"") .arg(fileName()), true); } #endif
#include <algorithm> #include <fstream> #include <iostream> #include <sstream> #include <string> #include <vector> using std::cout; using std::endl; using std::ifstream; using std::istringstream; using std::sort; using std::string; using std::vector; enum class State { kEmpty, kObstacle, kClosed, kPath, kStart, kFinish }; // N W S E const int deltas[4][2]{{-1, 0}, {0, -1}, {1, 0}, {0, 1}}; string CellString(State cell) { switch (cell) { case State::kEmpty:return "0 " } return (cell == State::kEmpty) ? "0 " : "⛰️ "; } vector<State> ParseLine(string line) { /* Parses a line from a file */ vector<State> row{}; istringstream stream(line); int n{}; char c{}; while (stream >> n >> c && c == ',') (!n) ? row.push_back(State::kEmpty) : row.push_back(State::kObstacle); return row; } vector<vector<State>> ReadBoard(string file) { ifstream boardFile(file); vector<vector<State>> board; string line{}; if (boardFile) { while (getline(boardFile, line)) board.push_back(ParseLine(line)); } return board; } void PrintBoard(vector<vector<State>> board) { for (auto row : board) { for (auto col : row) cout << CellString(col); cout << endl; } } /************************************************************************* ****************************A* Functions********************************** **************************************************************************/ int Heuristic(int x1, int y1, int x2, int y2) { // Manhattan distance return abs(x2 - x1) + abs(y2 - y1); } void AddToOpen(int x, int y, int g, int h, vector<vector<int>> &open, vector<vector<State>> board) { vector<int> node{x, y, g, h}; open.push_back(node); board[x][y] = State::kClosed; } bool Compare(vector<int> a, vector<int> b) { return (a[2] + a[3]) > (b[2] + b[3]); } void CellSort(vector<vector<int>> *v) { sort(v->begin(), v->end(), Compare); } bool CheckValidCell(int x, int y, vector<vector<State>> &grid) { return (x >= 0 && y >= 0) && (x < grid.size() && y < grid[0].size()) && (grid[x][y] == State::kEmpty); } void ExpandNeighbors(vector<int> &node, vector<vector<int>> &open, vector<vector<State>> &grid, int goal[2]) { int x = node[0]; int y = node[1]; int g = node[2]; for (auto neighbor : deltas) { int nx = x + neighbor[0]; int ny = y + neighbor[1]; if (CheckValidCell(nx, ny, grid)) AddToOpen(nx, ny, g + 1, Heuristic(nx, ny, goal[0], goal[1]), open, grid); } } vector<vector<State>> Search(vector<vector<State>> board, int start[2], int goal[2]) { // Initialize node list vector<vector<int>> openList{}; // First Node int x = start[0]; int y = start[1]; int g = 0; int h = Heuristic(x, y, goal[0], goal[1]); AddToOpen(x, y, g, h, openList, board); while (!openList.empty()) { // Sort the nodes CellSort(&openList); // Pop the lowest f value node auto current = openList.back(); openList.pop_back(); x = current[0]; y = current[0]; board[x][y] = State::kPath; if (x == goal[0] && y == goal[1]) return board; // Check neighbors, if valid, add them to the open list ExpandNeighbors(current, openList, board, goal); } // We've run out of new nodes to explore and haven't found a path. cout << "No path found!" << "\n"; return std::vector<vector<State>>{}; } int main() { auto board = ReadBoard("1.board"); int start[2]{0, 0}; int goal[2]{4, 5}; auto solution = Search(board, start, goal); PrintBoard(board); };
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: System.Enum #include "System/Enum.hpp" // Completed includes // Type namespace: UnityEngine namespace UnityEngine { // Forward declaring type: DepthTextureMode struct DepthTextureMode; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" DEFINE_IL2CPP_ARG_TYPE(::UnityEngine::DepthTextureMode, "UnityEngine", "DepthTextureMode"); // Type namespace: UnityEngine namespace UnityEngine { // Size: 0x4 #pragma pack(push, 1) // Autogenerated type: UnityEngine.DepthTextureMode // [TokenAttribute] Offset: FFFFFFFF // [FlagsAttribute] Offset: FFFFFFFF struct DepthTextureMode/*, public ::System::Enum*/ { public: public: // public System.Int32 value__ // Size: 0x4 // Offset: 0x0 int value; // Field size check static_assert(sizeof(int) == 0x4); public: // Creating value type constructor for type: DepthTextureMode constexpr DepthTextureMode(int value_ = {}) noexcept : value{value_} {} // Creating interface conversion operator: operator ::System::Enum operator ::System::Enum() noexcept { return *reinterpret_cast<::System::Enum*>(this); } // Creating conversion operator: operator int constexpr operator int() const noexcept { return value; } // static field const value: static public UnityEngine.DepthTextureMode None static constexpr const int None = 0; // Get static field: static public UnityEngine.DepthTextureMode None static ::UnityEngine::DepthTextureMode _get_None(); // Set static field: static public UnityEngine.DepthTextureMode None static void _set_None(::UnityEngine::DepthTextureMode value); // static field const value: static public UnityEngine.DepthTextureMode Depth static constexpr const int Depth = 1; // Get static field: static public UnityEngine.DepthTextureMode Depth static ::UnityEngine::DepthTextureMode _get_Depth(); // Set static field: static public UnityEngine.DepthTextureMode Depth static void _set_Depth(::UnityEngine::DepthTextureMode value); // static field const value: static public UnityEngine.DepthTextureMode DepthNormals static constexpr const int DepthNormals = 2; // Get static field: static public UnityEngine.DepthTextureMode DepthNormals static ::UnityEngine::DepthTextureMode _get_DepthNormals(); // Set static field: static public UnityEngine.DepthTextureMode DepthNormals static void _set_DepthNormals(::UnityEngine::DepthTextureMode value); // static field const value: static public UnityEngine.DepthTextureMode MotionVectors static constexpr const int MotionVectors = 4; // Get static field: static public UnityEngine.DepthTextureMode MotionVectors static ::UnityEngine::DepthTextureMode _get_MotionVectors(); // Set static field: static public UnityEngine.DepthTextureMode MotionVectors static void _set_MotionVectors(::UnityEngine::DepthTextureMode value); // Get instance field reference: public System.Int32 value__ [[deprecated("Use field access instead!")]] int& dyn_value__(); }; // UnityEngine.DepthTextureMode #pragma pack(pop) static check_size<sizeof(DepthTextureMode), 0 + sizeof(int)> __UnityEngine_DepthTextureModeSizeCheck; static_assert(sizeof(DepthTextureMode) == 0x4); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "HostControlMenuComp.h" HostControlMenuComp::HostControlMenuComp (HostParamControl& controller, size_t idx) : PopupMenu::CustomComponent (false), name ("Assign " + String (idx + 1)) { controller.loadParamList (paramList, xCallbacks, idx); for (auto& xCallback : xCallbacks) { auto newButton = xButtons.add (std::make_unique<DrawableButton> ("Delete", DrawableButton::ImageFitted)); createXButton (*newButton); addAndMakeVisible (newButton); newButton->onClick = [=] { xCallback(); triggerMenuItem(); }; } } void HostControlMenuComp::createXButton (DrawableButton& xButton) { Rectangle<float> buttonZone (-10.0f, -10.0f, 20.0f, 20.0f); DrawableRectangle redSquare; redSquare.setRectangle (buttonZone); redSquare.setFill (Colours::red); Path p; constexpr auto thickness = 1.5f; constexpr auto indent = 2.0f; p.addRectangle (-8.0f, -thickness, 20.0f - indent * 2.0f, thickness * 2.0f); p.addRectangle (-thickness, -8.0f, thickness * 2.0f, 10.0f - indent - thickness); p.addRectangle (-thickness, thickness, thickness * 2.0f, 10.0f - indent - thickness); p.setUsingNonZeroWinding (false); p.applyTransform (AffineTransform::rotation (MathConstants<float>::halfPi / 2.0f)); DrawablePath dp; dp.setPath (p); dp.setFill (Colours::white); DrawableComposite buttonImage; buttonImage.addAndMakeVisible (redSquare.createCopy().release()); buttonImage.addAndMakeVisible (dp.createCopy().release()); xButton.setImages (&buttonImage); } void HostControlMenuComp::getIdealSize (int& idealWidth, int& idealHeight) { idealWidth = 250; idealHeight = labelHeight * jmax (paramList.size(), 1); } void HostControlMenuComp::paint (Graphics& g) { auto bounds = getLocalBounds(); bounds.removeFromRight (20); // save space for xButtons g.setColour (Colours::white); g.setFont (Font (font).boldened()); auto labelBox = bounds.removeFromLeft (60); g.drawFittedText (name, labelBox.removeFromTop (labelHeight), Justification::centred, 1); if (paramList.isEmpty()) { g.setColour (Colours::lightgrey.withAlpha (0.85f)); g.setFont (Font (font)); g.drawFittedText ("None", bounds, Justification::centred, 1); } else { g.setColour (Colours::white); g.setFont (Font (font)); for (auto& pString : paramList) g.drawFittedText (pString, bounds.removeFromTop (labelHeight), Justification::centred, 1); } g.setColour (Colours::lightgrey.withAlpha (0.25f)); auto lineY = (float) getHeight(); g.drawLine (0, lineY, (float) getWidth(), lineY); } void HostControlMenuComp::resized() { auto buttonsBox = getLocalBounds().removeFromRight (20); for (auto* xButton : xButtons) xButton->setBounds (buttonsBox.removeFromTop (labelHeight)); }
#include<iostream> #include<stdlib.h> #include<stdlib.h> using namespace std; int c; int a[2000]; int m; void calculate(int num); int main() { int i,j,t; long n; cin>>t; for(i=1;i<=t;i++) { cout<<endl; cin>>n; m=1;a[0]=1;c=0; ///m is showing the no of digits for(j=1;j<=n;j++) calculate(j); while(a[m-1]==0) c++; cout<<c; } system("pause"); } void calculate(int j) { int i; int temp=0; long int x; i=0; while(a[i]==0) { m--;i++;} for(i=0;i<m;i++) { x=a[i]*j+temp; a[i]=x%10; temp=x/10; } if(temp!=0) { while(temp!=0) { a[m]=temp%10; temp=temp/10; m++; ///m is showing the no of digits } } i=0; while(a[i]==0) { a[m-i]=0;i++;} }
/* * Copyright (c) 2020, Andreas Kling <kling@serenityos.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include <LibWeb/CSS/Length.h> #include <LibWeb/DOM/Document.h> #include <LibWeb/HTML/HTMLHtmlElement.h> namespace Web::CSS { float Length::relative_length_to_px(const LayoutNode& layout_node) const { switch (m_type) { case Type::Em: return m_value * layout_node.font_size(); case Type::Rem: return m_value * layout_node.document().document_element()->layout_node()->font_size(); default: ASSERT_NOT_REACHED(); } } const char* Length::unit_name() const { switch (m_type) { case Type::Px: return "px"; case Type::Pt: return "pt"; case Type::Em: return "em"; case Type::Rem: return "rem"; case Type::Auto: return "auto"; case Type::Percentage: return "%"; case Type::Undefined: return "undefined"; } ASSERT_NOT_REACHED(); } }
/* * A good random number engine. * * Distributed under the Boost Software License, Version 1.0. (See accompanying * file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) */ #ifndef EXT_SMALL_FAST_COUNTING_ENGINE_V4_HPP #define EXT_SMALL_FAST_COUNTING_ENGINE_V4_HPP #include <algorithm> #include <array> #include <istream> #include <limits> #include <ostream> #include <random> #include <type_traits> #include <cassert> #include <cstddef> #include <cstdint> #include "bit_utility.hpp" #include "random_utility.hpp" #include "stream_utility.hpp" namespace ext { /** * Small fast counting random number generator version 4 from PractRand [1]. * * See "sfc16 / sfc32 / sfc64" in [2] for details. * * [1]: http://pracrand.sourceforge.net/ * [2]: http://pracrand.sourceforge.net/RNG_engines.txt */ template<typename Word, unsigned BarrelShift, unsigned RightShift, unsigned LeftShift, unsigned long long InitialRound> struct small_fast_counting_engine_v4 { //---------------------------------------------------------------------- // Engine characteristics //---------------------------------------------------------------------- /* * Unsigned integral type of the numbers generated by the engine. This * is an alias of the template argument Word. */ using result_type = Word; static_assert(std::is_unsigned<result_type>::value, "invalid word type"); /* * Parameters of the engine. */ static constexpr unsigned barrel_shift = BarrelShift; static constexpr unsigned right_shift = RightShift; static constexpr unsigned left_shift = LeftShift; static constexpr unsigned long long initial_round = InitialRound; static constexpr result_type default_seed = 0; /* * Returns the minimum value potentially generated by the engine. */ static constexpr result_type min() noexcept { return 0; } /* * Returns the maxmimum value potentially generated by the engine. */ static constexpr result_type max() noexcept { return std::numeric_limits<result_type>::max(); } private: static constexpr result_type word_bits = std::numeric_limits<result_type>::digits; static_assert(barrel_shift < word_bits, "parameter out of range"); static_assert(right_shift < word_bits, "parameter out of range"); static_assert(left_shift < word_bits, "parameter out of range"); public: //---------------------------------------------------------------------- // Construction and seeding //---------------------------------------------------------------------- /* * Constructs the pseudo-random number generator engine whose internal * state is initialized using given seed. */ explicit constexpr small_fast_counting_engine_v4( result_type seed_val = default_seed) noexcept { seed(seed_val); } template<typename Seed, std::enable_if_t<ext::is_seed_sequence<Seed>::value, int> = 0> explicit small_fast_counting_engine_v4(Seed& seed_seq) { seed(seed_seq); } /* * Initializes the state of the engine using given seed value. */ constexpr void seed(result_type seed_val = default_seed) noexcept { counter_ = 1; state_a_ = state_b_ = state_c_ = seed_val; discard(initial_round); } /* * Initializes the state of the engine using seed values generated by * given seed sequence. */ template<typename Seed, std::enable_if_t<ext::is_seed_sequence<Seed>::value, int> = 0> void seed(Seed& seed_seq) { std::array<result_type, 3> tmp; ext::seed_state(seed_seq, tmp); state_a_ = tmp[0]; state_b_ = tmp[1]; state_c_ = tmp[2]; counter_ = 1; discard(initial_round); } //---------------------------------------------------------------------- // Random number generation //---------------------------------------------------------------------- /* * Advances the state of the engine and returns a pseudo-random value. */ constexpr result_type operator()() noexcept { auto& counter = counter_; auto& a = state_a_; auto& b = state_b_; auto& c = state_c_; auto const tmp = result_type(a + b + counter++); a = result_type(b ^ (b >> right_shift)); b = result_type(c + (c << left_shift)); c = result_type(ext::rotate(c, barrel_shift) + tmp); return tmp; } /* * Advances the state of the engine z times. */ constexpr void discard(unsigned long long z) noexcept { for (; z != 0; --z) { (*this)(); } } //---------------------------------------------------------------------- // Comparison operators //---------------------------------------------------------------------- /* * Compares the internal states of given engines for equality. */ friend constexpr bool operator==(small_fast_counting_engine_v4 const& x, small_fast_counting_engine_v4 const& y) noexcept { return x.state_a_ == y.state_a_ && x.state_b_ == y.state_b_ && x.state_c_ == y.state_c_ && x.counter_ == y.counter_; } friend constexpr bool operator!=(small_fast_counting_engine_v4 const& x, small_fast_counting_engine_v4 const& y) noexcept { return !(x == y); } //---------------------------------------------------------------------- // State I/O //---------------------------------------------------------------------- /** * Writes state to stream. * * The a, b, c, and counter values are written to the stream in left- * aligned decimal format in this order using single space character as * delimiter. */ template<typename Char, typename CharTraits> friend std::basic_ostream<Char, CharTraits>& operator<<(std::basic_ostream<Char, CharTraits>& output_stream, small_fast_counting_engine_v4 const& engine) { Char const space = output_stream.widen(' '); ext::save_stream_format<Char, CharTraits> format {output_stream}; output_stream.flags(std::ios::dec | std::ios::left); output_stream.fill(space); output_stream << engine.state_a_ << space << engine.state_b_ << space << engine.state_c_ << space << engine.counter_; return output_stream; } /* * Restores state from stream. * * Reads serialized representation from the input stream. The state * of the engine does not change upon failure. */ template<typename Char, typename CharTraits> friend std::basic_istream<Char, CharTraits>& operator>>(std::basic_istream<Char, CharTraits>& input_stream, small_fast_counting_engine_v4& engine) { ext::save_stream_format<Char, CharTraits> format {input_stream}; input_stream.flags(std::ios::dec | std::ios::skipws); std::array<result_type, 4> tmp; if (input_stream >> tmp[0] >> tmp[1] >> tmp[2] >> tmp[3]) { engine.state_a_ = tmp[0]; engine.state_b_ = tmp[1]; engine.state_c_ = tmp[2]; engine.counter_ = tmp[3]; } return input_stream; } //---------------------------------------------------------------------- private: result_type state_a_ = 0; result_type state_b_ = 0; result_type state_c_ = 0; result_type counter_ = 0; }; /* * Instantiations of small_fast_counting_engine_v4 with parameters found in * PractRand. */ using sfc16 = small_fast_counting_engine_v4<std::uint16_t, 7, 3, 2, 12>; using sfc32 = small_fast_counting_engine_v4<std::uint32_t, 25, 8, 3, 12>; using sfc64 = small_fast_counting_engine_v4<std::uint64_t, 25, 12, 3, 12>; } #endif
/* TEMPLATE GENERATED TESTCASE FILE Filename: CWE762_Mismatched_Memory_Management_Routines__delete_array_wchar_t_malloc_01.cpp Label Definition File: CWE762_Mismatched_Memory_Management_Routines__delete_array.label.xml Template File: sources-sinks-01.tmpl.cpp */ /* * @description * CWE: 762 Mismatched Memory Management Routines * BadSource: malloc Allocate data using malloc() * GoodSource: Allocate data using new [] * Sinks: * GoodSink: Deallocate data using free() * BadSink : Deallocate data using delete [] * Flow Variant: 01 Baseline * * */ #include "std_testcase.h" namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_wchar_t_malloc_01 { #ifndef OMITBAD void bad() { wchar_t * data; /* Initialize data*/ data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (wchar_t *)malloc(100*sizeof(wchar_t)); /* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may * require a call to free() to deallocate the memory */ delete [] data; } #endif /* OMITBAD */ #ifndef OMITGOOD /* goodG2B uses the GoodSource with the BadSink */ static void goodG2B() { wchar_t * data; /* Initialize data*/ data = NULL; /* FIX: Allocate memory using new [] */ data = new wchar_t[100]; /* POTENTIAL FLAW: Deallocate memory using delete [] - the source memory allocation function may * require a call to free() to deallocate the memory */ delete [] data; } /* goodB2G uses the BadSource with the GoodSink */ static void goodB2G() { wchar_t * data; /* Initialize data*/ data = NULL; /* POTENTIAL FLAW: Allocate memory with a function that requires free() to free the memory */ data = (wchar_t *)malloc(100*sizeof(wchar_t)); /* FIX: Free memory using free() */ free(data); } void good() { goodG2B(); goodB2G(); } #endif /* OMITGOOD */ } // close namespace /* Below is the main(). It is only used when building this testcase on its own for testing or for building a binary to use in testing binary analysis tools. It is not used when compiling all the testcases as one application, which is how source code analysis tools are tested. */ #ifdef INCLUDEMAIN using namespace CWE762_Mismatched_Memory_Management_Routines__delete_array_wchar_t_malloc_01; // so that we can use good and bad easily int main(int argc, char * argv[]) { /* seed randomness */ srand( (unsigned)time(NULL) ); #ifndef OMITGOOD printLine("Calling good()..."); good(); printLine("Finished good()"); #endif /* OMITGOOD */ #ifndef OMITBAD printLine("Calling bad()..."); bad(); printLine("Finished bad()"); #endif /* OMITBAD */ return 0; } #endif
/* * Copyright (C) 2012 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: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following disclaimer * in the documentation and/or other materials provided with the * distribution. * * Neither the name of Google Inc. nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "platform/text/LocaleICU.h" #include "testing/gtest/include/gtest/gtest.h" #include "wtf/text/StringBuilder.h" #include <memory> #include <unicode/uvernum.h> namespace blink { class LocaleICUTest : public ::testing::Test { public: // Labels class is used for printing results in EXPECT_EQ macro. class Labels { public: Labels(const Vector<String> labels) : m_labels(labels) { } // FIXME: We should use Vector<T>::operator==() if it works. bool operator==(const Labels& other) const { if (m_labels.size() != other.m_labels.size()) return false; for (unsigned index = 0; index < m_labels.size(); ++index) { if (m_labels[index] != other.m_labels[index]) return false; } return true; } String toString() const { StringBuilder builder; builder.append("labels("); for (unsigned index = 0; index < m_labels.size(); ++index) { if (index) builder.append(", "); builder.append('"'); builder.append(m_labels[index]); builder.append('"'); } builder.append(')'); return builder.toString(); } private: Vector<String> m_labels; }; protected: Labels labelsFromTwoElements(const String& element1, const String& element2) { Vector<String> labels = Vector<String>(); labels.append(element1); labels.append(element2); return Labels(labels); } String monthFormat(const char* localeString) { std::unique_ptr<LocaleICU> locale = LocaleICU::create(localeString); return locale->monthFormat(); } String localizedDateFormatText(const char* localeString) { std::unique_ptr<LocaleICU> locale = LocaleICU::create(localeString); return locale->timeFormat(); } String localizedShortDateFormatText(const char* localeString) { std::unique_ptr<LocaleICU> locale = LocaleICU::create(localeString); return locale->shortTimeFormat(); } String shortMonthLabel(const char* localeString, unsigned index) { std::unique_ptr<LocaleICU> locale = LocaleICU::create(localeString); return locale->shortMonthLabels()[index]; } String shortStandAloneMonthLabel(const char* localeString, unsigned index) { std::unique_ptr<LocaleICU> locale = LocaleICU::create(localeString); return locale->shortStandAloneMonthLabels()[index]; } String standAloneMonthLabel(const char* localeString, unsigned index) { std::unique_ptr<LocaleICU> locale = LocaleICU::create(localeString); return locale->standAloneMonthLabels()[index]; } Labels timeAMPMLabels(const char* localeString) { std::unique_ptr<LocaleICU> locale = LocaleICU::create(localeString); return Labels(locale->timeAMPMLabels()); } bool isRTL(const char* localeString) { std::unique_ptr<LocaleICU> locale = LocaleICU::create(localeString); return locale->isRTL(); } }; std::ostream& operator<<(std::ostream& os, const LocaleICUTest::Labels& labels) { return os << labels.toString().utf8().data(); } TEST_F(LocaleICUTest, isRTL) { EXPECT_TRUE(isRTL("ar-EG")); EXPECT_FALSE(isRTL("en-us")); EXPECT_FALSE(isRTL("ja-jp")); EXPECT_FALSE(isRTL("**invalid**")); } TEST_F(LocaleICUTest, monthFormat) { EXPECT_STREQ("MMMM yyyy", monthFormat("en_US").utf8().data()); EXPECT_STREQ("MMMM yyyy", monthFormat("fr").utf8().data()); EXPECT_STREQ("yyyy\xE5\xB9\xB4M\xE6\x9C\x88", monthFormat("ja").utf8().data()); } TEST_F(LocaleICUTest, localizedDateFormatText) { // Note: EXPECT_EQ(String, String) doesn't print result as string. EXPECT_STREQ("h:mm:ss a", localizedDateFormatText("en_US").utf8().data()); EXPECT_STREQ("HH:mm:ss", localizedDateFormatText("fr").utf8().data()); EXPECT_STREQ("H:mm:ss", localizedDateFormatText("ja").utf8().data()); } TEST_F(LocaleICUTest, localizedShortDateFormatText) { EXPECT_STREQ("h:mm a", localizedShortDateFormatText("en_US").utf8().data()); EXPECT_STREQ("HH:mm", localizedShortDateFormatText("fr").utf8().data()); EXPECT_STREQ("H:mm", localizedShortDateFormatText("ja").utf8().data()); } TEST_F(LocaleICUTest, standAloneMonthLabels) { EXPECT_STREQ("January", standAloneMonthLabel("en_US", 0).utf8().data()); EXPECT_STREQ("June", standAloneMonthLabel("en_US", 5).utf8().data()); EXPECT_STREQ("December", standAloneMonthLabel("en_US", 11).utf8().data()); #if U_ICU_VERSION_MAJOR_NUM >= 54 EXPECT_STREQ("Janvier", standAloneMonthLabel("fr_FR", 0).utf8().data()); EXPECT_STREQ("Juin", standAloneMonthLabel("fr_FR", 5).utf8().data()); EXPECT_STREQ("D\xC3\xA9" "cembre", standAloneMonthLabel("fr_FR", 11).utf8().data()); #else EXPECT_STREQ("janvier", standAloneMonthLabel("fr_FR", 0).utf8().data()); EXPECT_STREQ("juin", standAloneMonthLabel("fr_FR", 5).utf8().data()); EXPECT_STREQ("d\xC3\xA9" "cembre", standAloneMonthLabel("fr_FR", 11).utf8().data()); #endif EXPECT_STREQ("1\xE6\x9C\x88", standAloneMonthLabel("ja_JP", 0).utf8().data()); EXPECT_STREQ("6\xE6\x9C\x88", standAloneMonthLabel("ja_JP", 5).utf8().data()); EXPECT_STREQ("12\xE6\x9C\x88", standAloneMonthLabel("ja_JP", 11).utf8().data()); EXPECT_STREQ("\xD0\x9C\xD0\xB0\xD1\x80\xD1\x82", standAloneMonthLabel("ru_RU", 2).utf8().data()); EXPECT_STREQ("\xD0\x9C\xD0\xB0\xD0\xB9", standAloneMonthLabel("ru_RU", 4).utf8().data()); } TEST_F(LocaleICUTest, shortMonthLabels) { EXPECT_STREQ("Jan", shortMonthLabel("en_US", 0).utf8().data()); EXPECT_STREQ("Jan", shortStandAloneMonthLabel("en_US", 0).utf8().data()); EXPECT_STREQ("Dec", shortMonthLabel("en_US", 11).utf8().data()); EXPECT_STREQ("Dec", shortStandAloneMonthLabel("en_US", 11).utf8().data()); #if U_ICU_VERSION_MAJOR_NUM >= 54 EXPECT_STREQ("janv.", shortMonthLabel("fr_FR", 0).utf8().data()); EXPECT_STREQ("Janv.", shortStandAloneMonthLabel("fr_FR", 0).utf8().data()); EXPECT_STREQ("d\xC3\xA9" "c.", shortMonthLabel("fr_FR", 11).utf8().data()); EXPECT_STREQ("D\xC3\xA9" "c.", shortStandAloneMonthLabel("fr_FR", 11).utf8().data()); #else EXPECT_STREQ("janv.", shortMonthLabel("fr_FR", 0).utf8().data()); EXPECT_STREQ("janv.", shortStandAloneMonthLabel("fr_FR", 0).utf8().data()); EXPECT_STREQ("d\xC3\xA9" "c.", shortMonthLabel("fr_FR", 11).utf8().data()); EXPECT_STREQ("d\xC3\xA9" "c.", shortStandAloneMonthLabel("fr_FR", 11).utf8().data()); #endif EXPECT_STREQ("1\xE6\x9C\x88", shortMonthLabel("ja_JP", 0).utf8().data()); EXPECT_STREQ("1\xE6\x9C\x88", shortStandAloneMonthLabel("ja_JP", 0).utf8().data()); EXPECT_STREQ("12\xE6\x9C\x88", shortMonthLabel("ja_JP", 11).utf8().data()); EXPECT_STREQ("12\xE6\x9C\x88", shortStandAloneMonthLabel("ja_JP", 11).utf8().data()); EXPECT_STREQ("\xD0\xBC\xD0\xB0\xD1\x80.", shortMonthLabel("ru_RU", 2).utf8().data()); EXPECT_STREQ("\xD0\x9C\xD0\xB0\xD1\x80\xD1\x82", shortStandAloneMonthLabel("ru_RU", 2).utf8().data()); EXPECT_STREQ("\xD0\xBC\xD0\xB0\xD1\x8F", shortMonthLabel("ru_RU", 4).utf8().data()); EXPECT_STREQ("\xD0\x9C\xD0\xB0\xD0\xB9", shortStandAloneMonthLabel("ru_RU", 4).utf8().data()); } TEST_F(LocaleICUTest, timeAMPMLabels) { EXPECT_EQ(labelsFromTwoElements("AM", "PM"), timeAMPMLabels("en_US")); EXPECT_EQ(labelsFromTwoElements("AM", "PM"), timeAMPMLabels("fr")); UChar jaAM[3] = { 0x5348, 0x524d, 0 }; UChar jaPM[3] = { 0x5348, 0x5F8C, 0 }; EXPECT_EQ(labelsFromTwoElements(String(jaAM), String(jaPM)), timeAMPMLabels("ja")); } static String testDecimalSeparator(const AtomicString& localeIdentifier) { std::unique_ptr<Locale> locale = Locale::create(localeIdentifier); return locale->localizedDecimalSeparator(); } TEST_F(LocaleICUTest, localizedDecimalSeparator) { EXPECT_EQ(String("."), testDecimalSeparator("en_US")); EXPECT_EQ(String(","), testDecimalSeparator("fr")); } void testNumberIsReversible(const AtomicString& localeIdentifier, const char* original, const char* shouldHave = 0) { std::unique_ptr<Locale> locale = Locale::create(localeIdentifier); String localized = locale->convertToLocalizedNumber(original); if (shouldHave) EXPECT_TRUE(localized.contains(shouldHave)); String converted = locale->convertFromLocalizedNumber(localized); EXPECT_EQ(original, converted); } void testNumbers(const char* localeString) { testNumberIsReversible(localeString, "123456789012345678901234567890"); testNumberIsReversible(localeString, "-123.456"); testNumberIsReversible(localeString, ".456"); testNumberIsReversible(localeString, "-0.456"); } TEST_F(LocaleICUTest, reversible) { testNumberIsReversible("en_US", "123456789012345678901234567890"); testNumberIsReversible("en_US", "-123.456", "."); testNumberIsReversible("en_US", ".456", "."); testNumberIsReversible("en_US", "-0.456", "."); testNumberIsReversible("fr", "123456789012345678901234567890"); testNumberIsReversible("fr", "-123.456", ","); testNumberIsReversible("fr", ".456", ","); testNumberIsReversible("fr", "-0.456", ","); // Persian locale has a negative prefix and a negative suffix. testNumbers("fa"); // Test some of major locales. testNumbers("ar"); testNumbers("de_DE"); testNumbers("es_ES"); testNumbers("ja_JP"); testNumbers("ko_KR"); testNumbers("zh_CN"); testNumbers("zh_HK"); testNumbers("zh_TW"); } } // namespace blink
#include "memoryview.h" MemoryView::MemoryView(QWidget* parent) : QAbstractScrollArea(parent) { init(); } MemoryView::~MemoryView() {} void MemoryView::init() { connect(verticalScrollBar(), &QScrollBar::valueChanged, this, &MemoryView::adjustContent); connect(horizontalScrollBar(), &QScrollBar::valueChanged, this, &MemoryView::adjustContent); addressBlockWidth = 2; bytesPerLine = 16; pxWidth = 8; pxHeight = 13; addressWidth = (addressBlockWidth * 4 + addressBlockWidth - 1) * pxWidth; hexWidth = (bytesPerLine * 3 + 1) * pxWidth; asciiWidth = (bytesPerLine * 2 + 1) * pxWidth; } void MemoryView::setData(uint8_t* memPtr, int memSize) { memoryPtr = memPtr; size = memSize; adjustContent(); } QByteArray MemoryView::data(uint32_t pos, uint32_t count) { if (pos >= size) count = size; else if ((pos + count) > size) count = size - pos; return QByteArray((char*)&memoryPtr[pos], count); } void MemoryView::paintEvent(QPaintEvent*) { QPainter painter(viewport()); if (highlight) { int bx = (hlX - addressWidth + 3 * pxWidth) * bytesPerLine / hexWidth; int by = hlY / pxHeight; highlight = false; painter.fillRect(addressWidth + 3 * pxWidth * bx - 14, pxHeight * by + 1, pxWidth*2+2, pxHeight, QBrush(QColor(90, 180, 190, 128))); } int offsetX = horizontalScrollBar()->value(); int y = pxHeight; painter.setPen(viewport()->palette().color(QPalette::WindowText)); // address column QString prev_addr = "00000"; for (int row = 1; row <= dataVisible.size() / bytesPerLine + 1; row++) { QString curr_addr = QString("%1") .arg(windowStartPos + bytesPerLine * row - 1, 5, 16, QChar('0')) .toUpper(); QString combined = QString("%1-%2").arg(prev_addr, curr_addr); prev_addr = QString("%1") .arg(windowStartPos + bytesPerLine * row, 5, 16, QChar('0')) .toUpper(); painter.drawText(pxWidth / 2 - offsetX, y, combined); y += pxHeight; } int x; int viewOffset = addressWidth + pxWidth; painter.drawLine(viewOffset - offsetX, 0, viewOffset - offsetX, height()); viewOffset += pxWidth / 2; y = pxHeight; // hex data column int bPos = 0; for (int row = 0; row < numOfRowsVisible; row++) { x = viewOffset - offsetX; for (int col = 0; (col < bytesPerLine) && (bPos < dataHex.size()); col++) { QString str = dataHex.mid(bPos * 2, 2).toUpper(); painter.drawText(x, y, str); x += 3 * pxWidth; bPos += 1; } y += pxHeight; } // offset for ascii column viewOffset = addressWidth + hexWidth; painter.drawLine(viewOffset - offsetX, 0, viewOffset - offsetX, height()); viewOffset += pxWidth / 2; bPos = 0; y = pxHeight; int ch; for (int row = 0; row < numOfRowsVisible; row++) { x = viewOffset - offsetX; for (int col = 0; (col < bytesPerLine) && (bPos < dataVisible.size()); col++) { ch = char(dataVisible.at(bPos)); if (ch < 0x20) { ch = '.'; } painter.drawText(x, y, QChar(ch)); x += 2 * pxWidth; bPos += 1; } y += pxHeight; } } void MemoryView::adjustContent() { numOfRowsVisible = viewport()->height() / pxHeight; int vertical_val = verticalScrollBar()->value(); windowStartPos = vertical_val * bytesPerLine; int lineCount = size / bytesPerLine; verticalScrollBar()->setRange(0, lineCount - numOfRowsVisible); verticalScrollBar()->setPageStep(numOfRowsVisible); dataVisible = data(windowStartPos, numOfRowsVisible * bytesPerLine); dataHex = dataVisible.toHex(); viewport()->update(); } void MemoryView::mousePressEvent(QMouseEvent* ev) { int vertical_val = verticalScrollBar()->value(); QPointF pos = ev->position(); if (pos.x() > addressWidth + hexWidth) { return; } int x = (pos.x() - addressWidth - pxWidth) / (3 * pxWidth); int y = vertical_val + pos.y() / pxHeight; int addr = y * bytesPerLine + x; emit addressSelected(QString("%1").arg(addr, 5, 16, QChar('0')).toUpper()); hlX = pos.x(); hlY = pos.y(); highlight = true; viewport()->repaint(); }
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * *************************************************************/ #if ! defined INCLUDED_SLIDESHOW_FIGUREWIPE_HXX #define INCLUDED_SLIDESHOW_FIGUREWIPE_HXX #include "parametricpolypolygon.hxx" namespace slideshow { namespace internal { class FigureWipe : public ParametricPolyPolygon { public: static FigureWipe * createTriangleWipe(); static FigureWipe * createArrowHeadWipe(); static FigureWipe * createStarWipe( sal_Int32 nPoints ); static FigureWipe * createPentagonWipe(); static FigureWipe * createHexagonWipe(); virtual ::basegfx::B2DPolyPolygon operator () ( double t ); private: FigureWipe( ::basegfx::B2DPolygon const & figure ) : m_figure(figure) {} const ::basegfx::B2DPolygon m_figure; }; } } #endif /* INCLUDED_SLIDESHOW_FIGUREWIPE_HXX */
///* // link: https://www.geeksforgeeks.org/find-first-node-of-loop-in-a-linked-list/ //*/ // // //#include "01_reverse_linklist.cpp" //#include "CppUnitTest.h" //#include <iostream> //#include <algorithm> //#include <vector> //#include <map> //#include <unordered_set> //#include <set> //#include <unordered_map> //#include <queue> //#include <stack> // //using namespace std; //using namespace Microsoft::VisualStudio::CppUnitTestFramework; // //namespace LoveBabbar450InCPPTest //{ // TEST_CLASS(SearchSort) // { // public: // // TEST_METHOD(find1Test) // { // std::string charM = "harhs"; // int age = 14; // age = 55; // std::string lastName = "<<charM <<singh"; // // } // }; //} //// ----------------------------------------------------------------------------------------------------------------------- // ///* // floyd's cycle finding algorithm (or loop detecting) //*/ //Node* detectAndRemoveLoop(Node* head) //{ // // If list is empty or has only one node // // without loop // if (head == NULL || head->next == NULL) // return NULL; // // Node* slow = head, * fast = head; // // // Move slow and fast 1 and 2 steps // // ahead respectively. // slow = slow->next; // fast = fast->next->next; // // // Search for loop using slow and // // fast pointers // while (fast && fast->next) { // if (slow == fast) // break; // slow = slow->next; // fast = fast->next->next; // } // // // If loop does not exist // if (slow != fast) // return NULL; // // // If loop exists. Start slow from // // head and fast from meeting point. // slow = head; // while (slow != fast) { // slow = slow->next; // fast = fast->next; // } // // return slow; //} // // // // // // //// ----------------------------------------------------------------------------------------------------------------------- // ///* // by assigning every node's next NULL, if any node's next detected NULL means it is visited. //*/ //Node* detectLoop(Node* head) //{ // // // Create a temporary node // Node* temp = new Node(0); // while (head != NULL) { // // // This condition is for the case // // when there is no loop // if (head->next == NULL) { // return NULL; // } // // // Check if next is already // // pointing to temp // if (head->next == temp) { // break; // } // // // Store the pointer to the next node // // in order to get to it in the next step // Node* nex = head->next; // // // Make next point to temp // head->next = temp; // // // Get to the next node in the list // head = nex; // } // // return head; //} // // // // // //// ----------------------------------------------------------------------------------------------------------------------- // ///* // using hashing //*/ ////ListNode* detectCycle(ListNode* A) ////{ //// //// // declaring map to store node address //// unordered_set<ListNode*> uset; //// //// ListNode* ptr = A; //// //// // Default consider that no cycle is present //// while (ptr != NULL) { //// //// // checking if address is already present in map //// if (uset.find(ptr) != uset.end()) //// return ptr; //// //// // if address not present then insert into the set //// else //// uset.insert(ptr); //// //// ptr = ptr->next; //// } //// return NULL; ////}
#include "selfdrive/boardd/panda.h" #include <unistd.h> #include <cassert> #include <stdexcept> #include <vector> #include "cereal/messaging/messaging.h" #include "panda/board/dlc_to_len.h" #include "selfdrive/common/gpio.h" #include "selfdrive/common/swaglog.h" #include "selfdrive/common/util.h" static int init_usb_ctx(libusb_context **context) { assert(context != nullptr); int err = libusb_init(context); if (err != 0) { LOGE("libusb initialization error"); return err; } #if LIBUSB_API_VERSION >= 0x01000106 libusb_set_option(*context, LIBUSB_OPTION_LOG_LEVEL, LIBUSB_LOG_LEVEL_INFO); #else libusb_set_debug(*context, 3); #endif return err; } Panda::Panda(std::string serial, uint32_t bus_offset) : bus_offset(bus_offset) { // init libusb ssize_t num_devices; libusb_device **dev_list = NULL; int err = init_usb_ctx(&ctx); if (err != 0) { goto fail; } // connect by serial num_devices = libusb_get_device_list(ctx, &dev_list); if (num_devices < 0) { goto fail; } for (size_t i = 0; i < num_devices; ++i) { libusb_device_descriptor desc; libusb_get_device_descriptor(dev_list[i], &desc); if (desc.idVendor == 0xbbaa && desc.idProduct == 0xddcc) { int ret = libusb_open(dev_list[i], &dev_handle); if (dev_handle == NULL || ret < 0) { goto fail; } unsigned char desc_serial[26] = { 0 }; ret = libusb_get_string_descriptor_ascii(dev_handle, desc.iSerialNumber, desc_serial, std::size(desc_serial)); if (ret < 0) { goto fail; } usb_serial = std::string((char *)desc_serial, ret).c_str(); if (serial.empty() || serial == usb_serial) { break; } libusb_close(dev_handle); dev_handle = NULL; } } if (dev_handle == NULL) goto fail; libusb_free_device_list(dev_list, 1); dev_list = nullptr; if (libusb_kernel_driver_active(dev_handle, 0) == 1) { libusb_detach_kernel_driver(dev_handle, 0); } err = libusb_set_configuration(dev_handle, 1); if (err != 0) { goto fail; } err = libusb_claim_interface(dev_handle, 0); if (err != 0) { goto fail; } hw_type = get_hw_type(); has_rtc = (hw_type == cereal::PandaState::PandaType::UNO) || (hw_type == cereal::PandaState::PandaType::DOS); return; fail: if (dev_list != NULL) { libusb_free_device_list(dev_list, 1); } cleanup(); throw std::runtime_error("Error connecting to panda"); } Panda::~Panda() { std::lock_guard lk(usb_lock); cleanup(); connected = false; } void Panda::cleanup() { if (dev_handle) { libusb_release_interface(dev_handle, 0); libusb_close(dev_handle); } if (ctx) { libusb_exit(ctx); } } std::vector<std::string> Panda::list() { // init libusb ssize_t num_devices; libusb_context *context = NULL; libusb_device **dev_list = NULL; std::vector<std::string> serials; int err = init_usb_ctx(&context); if (err != 0) { return serials; } num_devices = libusb_get_device_list(context, &dev_list); if (num_devices < 0) { LOGE("libusb can't get device list"); goto finish; } for (size_t i = 0; i < num_devices; ++i) { libusb_device *device = dev_list[i]; libusb_device_descriptor desc; libusb_get_device_descriptor(device, &desc); if (desc.idVendor == 0xbbaa && desc.idProduct == 0xddcc) { libusb_device_handle *handle = NULL; int ret = libusb_open(device, &handle); if (ret < 0) { goto finish; } unsigned char desc_serial[26] = { 0 }; ret = libusb_get_string_descriptor_ascii(handle, desc.iSerialNumber, desc_serial, std::size(desc_serial)); libusb_close(handle); if (ret < 0) { goto finish; } serials.push_back(std::string((char *)desc_serial, ret).c_str()); } } finish: if (dev_list != NULL) { libusb_free_device_list(dev_list, 1); } if (context) { libusb_exit(context); } return serials; } void Panda::handle_usb_issue(int err, const char func[]) { LOGE_100("usb error %d \"%s\" in %s", err, libusb_strerror((enum libusb_error)err), func); if (err == LIBUSB_ERROR_NO_DEVICE) { LOGE("lost connection"); connected = false; } // TODO: check other errors, is simply retrying okay? } int Panda::usb_write(uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned int timeout) { int err; const uint8_t bmRequestType = LIBUSB_ENDPOINT_OUT | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE; if (!connected) { return LIBUSB_ERROR_NO_DEVICE; } std::lock_guard lk(usb_lock); do { err = libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, NULL, 0, timeout); if (err < 0) handle_usb_issue(err, __func__); } while (err < 0 && connected); return err; } int Panda::usb_read(uint8_t bRequest, uint16_t wValue, uint16_t wIndex, unsigned char *data, uint16_t wLength, unsigned int timeout) { int err; const uint8_t bmRequestType = LIBUSB_ENDPOINT_IN | LIBUSB_REQUEST_TYPE_VENDOR | LIBUSB_RECIPIENT_DEVICE; if (!connected) { return LIBUSB_ERROR_NO_DEVICE; } std::lock_guard lk(usb_lock); do { err = libusb_control_transfer(dev_handle, bmRequestType, bRequest, wValue, wIndex, data, wLength, timeout); if (err < 0) handle_usb_issue(err, __func__); } while (err < 0 && connected); return err; } int Panda::usb_bulk_write(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout) { int err; int transferred = 0; if (!connected) { return 0; } std::lock_guard lk(usb_lock); do { // Try sending can messages. If the receive buffer on the panda is full it will NAK // and libusb will try again. After 5ms, it will time out. We will drop the messages. err = libusb_bulk_transfer(dev_handle, endpoint, data, length, &transferred, timeout); if (err == LIBUSB_ERROR_TIMEOUT) { LOGW("Transmit buffer full"); break; } else if (err != 0 || length != transferred) { handle_usb_issue(err, __func__); } } while(err != 0 && connected); return transferred; } int Panda::usb_bulk_read(unsigned char endpoint, unsigned char* data, int length, unsigned int timeout) { int err; int transferred = 0; if (!connected) { return 0; } std::lock_guard lk(usb_lock); do { err = libusb_bulk_transfer(dev_handle, endpoint, data, length, &transferred, timeout); if (err == LIBUSB_ERROR_TIMEOUT) { break; // timeout is okay to exit, recv still happened } else if (err == LIBUSB_ERROR_OVERFLOW) { comms_healthy = false; LOGE_100("overflow got 0x%x", transferred); } else if (err != 0) { handle_usb_issue(err, __func__); } } while(err != 0 && connected); return transferred; } void Panda::set_safety_model(cereal::CarParams::SafetyModel safety_model, int safety_param) { usb_write(0xdc, (uint16_t)safety_model, safety_param); } void Panda::set_alternative_experience(uint16_t alternative_experience) { usb_write(0xdf, alternative_experience, 0); } cereal::PandaState::PandaType Panda::get_hw_type() { unsigned char hw_query[1] = {0}; usb_read(0xc1, 0, 0, hw_query, 1); return (cereal::PandaState::PandaType)(hw_query[0]); } void Panda::set_rtc(struct tm sys_time) { // tm struct has year defined as years since 1900 usb_write(0xa1, (uint16_t)(1900 + sys_time.tm_year), 0); usb_write(0xa2, (uint16_t)(1 + sys_time.tm_mon), 0); usb_write(0xa3, (uint16_t)sys_time.tm_mday, 0); // usb_write(0xa4, (uint16_t)(1 + sys_time.tm_wday), 0); usb_write(0xa5, (uint16_t)sys_time.tm_hour, 0); usb_write(0xa6, (uint16_t)sys_time.tm_min, 0); usb_write(0xa7, (uint16_t)sys_time.tm_sec, 0); } struct tm Panda::get_rtc() { struct __attribute__((packed)) timestamp_t { uint16_t year; // Starts at 0 uint8_t month; uint8_t day; uint8_t weekday; uint8_t hour; uint8_t minute; uint8_t second; } rtc_time = {0}; usb_read(0xa0, 0, 0, (unsigned char*)&rtc_time, sizeof(rtc_time)); struct tm new_time = { 0 }; new_time.tm_year = rtc_time.year - 1900; // tm struct has year defined as years since 1900 new_time.tm_mon = rtc_time.month - 1; new_time.tm_mday = rtc_time.day; new_time.tm_hour = rtc_time.hour; new_time.tm_min = rtc_time.minute; new_time.tm_sec = rtc_time.second; return new_time; } void Panda::set_fan_speed(uint16_t fan_speed) { usb_write(0xb1, fan_speed, 0); } uint16_t Panda::get_fan_speed() { uint16_t fan_speed_rpm = 0; usb_read(0xb2, 0, 0, (unsigned char*)&fan_speed_rpm, sizeof(fan_speed_rpm)); return fan_speed_rpm; } void Panda::set_ir_pwr(uint16_t ir_pwr) { usb_write(0xb0, ir_pwr, 0); } std::optional<health_t> Panda::get_state() { health_t health {0}; int err = usb_read(0xd2, 0, 0, (unsigned char*)&health, sizeof(health)); return err >= 0 ? std::make_optional(health) : std::nullopt; } void Panda::set_loopback(bool loopback) { usb_write(0xe5, loopback, 0); } std::optional<std::vector<uint8_t>> Panda::get_firmware_version() { std::vector<uint8_t> fw_sig_buf(128); int read_1 = usb_read(0xd3, 0, 0, &fw_sig_buf[0], 64); int read_2 = usb_read(0xd4, 0, 0, &fw_sig_buf[64], 64); return ((read_1 == 64) && (read_2 == 64)) ? std::make_optional(fw_sig_buf) : std::nullopt; } std::optional<std::string> Panda::get_serial() { char serial_buf[17] = {'\0'}; int err = usb_read(0xd0, 0, 0, (uint8_t*)serial_buf, 16); return err >= 0 ? std::make_optional(serial_buf) : std::nullopt; } void Panda::set_power_saving(bool power_saving) { usb_write(0xe7, power_saving, 0); } void Panda::enable_deepsleep() { usb_write(0xfb, 0, 0); } void Panda::set_usb_power_mode(cereal::PeripheralState::UsbPowerMode power_mode) { usb_write(0xe6, (uint16_t)power_mode, 0); } void Panda::send_heartbeat(bool engaged) { usb_write(0xf3, engaged, 0); } void Panda::set_can_speed_kbps(uint16_t bus, uint16_t speed) { usb_write(0xde, bus, (speed * 10)); } void Panda::set_data_speed_kbps(uint16_t bus, uint16_t speed) { usb_write(0xf9, bus, (speed * 10)); } static uint8_t len_to_dlc(uint8_t len) { if (len <= 8) { return len; } if (len <= 24) { return 8 + ((len - 8) / 4) + ((len % 4) ? 1 : 0); } else { return 11 + (len / 16) + ((len % 16) ? 1 : 0); } } static void write_packet(uint8_t *dest, int *write_pos, const uint8_t *src, size_t size) { for (int i = 0, &pos = *write_pos; i < size; ++i, ++pos) { // Insert counter every 64 bytes (first byte of 64 bytes USB packet) if (pos % USBPACKET_MAX_SIZE == 0) { dest[pos] = pos / USBPACKET_MAX_SIZE; pos++; } dest[pos] = src[i]; } } void Panda::pack_can_buffer(const capnp::List<cereal::CanData>::Reader &can_data_list, std::function<void(uint8_t *, size_t)> write_func) { int32_t pos = 0; uint8_t send_buf[2 * USB_TX_SOFT_LIMIT]; for (auto cmsg : can_data_list) { // check if the message is intended for this panda uint8_t bus = cmsg.getSrc(); if (bus < bus_offset || bus >= (bus_offset + PANDA_BUS_CNT)) { continue; } auto can_data = cmsg.getDat(); uint8_t data_len_code = len_to_dlc(can_data.size()); assert(can_data.size() <= ((hw_type == cereal::PandaState::PandaType::RED_PANDA) ? 64 : 8)); assert(can_data.size() == dlc_to_len[data_len_code]); can_header header; header.addr = cmsg.getAddress(); header.extended = (cmsg.getAddress() >= 0x800) ? 1 : 0; header.data_len_code = data_len_code; header.bus = bus - bus_offset; write_packet(send_buf, &pos, (uint8_t *)&header, sizeof(can_header)); write_packet(send_buf, &pos, (uint8_t *)can_data.begin(), can_data.size()); if (pos >= USB_TX_SOFT_LIMIT) { write_func(send_buf, pos); pos = 0; } } // send remaining packets if (pos > 0) write_func(send_buf, pos); } void Panda::can_send(capnp::List<cereal::CanData>::Reader can_data_list) { pack_can_buffer(can_data_list, [=](uint8_t* data, size_t size) { usb_bulk_write(3, data, size, 5); }); } bool Panda::can_receive(std::vector<can_frame>& out_vec) { uint8_t data[RECV_SIZE]; int recv = usb_bulk_read(0x81, (uint8_t*)data, RECV_SIZE); if (!comms_healthy) { return false; } if (recv == RECV_SIZE) { LOGW("Panda receive buffer full"); } return (recv <= 0) ? true : unpack_can_buffer(data, recv, out_vec); } bool Panda::unpack_can_buffer(uint8_t *data, int size, std::vector<can_frame> &out_vec) { recv_buf.clear(); for (int i = 0; i < size; i += USBPACKET_MAX_SIZE) { if (data[i] != i / USBPACKET_MAX_SIZE) { LOGE("CAN: MALFORMED USB RECV PACKET"); comms_healthy = false; return false; } int chunk_len = std::min(USBPACKET_MAX_SIZE, (size - i)); recv_buf.insert(recv_buf.end(), &data[i + 1], &data[i + chunk_len]); } int pos = 0; while (pos < recv_buf.size()) { can_header header; memcpy(&header, &recv_buf[pos], CANPACKET_HEAD_SIZE); can_frame &canData = out_vec.emplace_back(); canData.busTime = 0; canData.address = header.addr; canData.src = header.bus + bus_offset; if (header.rejected) { canData.src += CANPACKET_REJECTED; } if (header.returned) { canData.src += CANPACKET_RETURNED; } const uint8_t data_len = dlc_to_len[header.data_len_code]; canData.dat.assign((char *)&recv_buf[pos + CANPACKET_HEAD_SIZE], data_len); pos += CANPACKET_HEAD_SIZE + data_len; } return true; }
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <AzManipulatorTestFramework/IndirectManipulatorViewportInteraction.h> #include <AzManipulatorTestFramework/ViewportInteraction.h> #include <AzToolsFramework/Manipulators/ManipulatorManager.h> namespace AzManipulatorTestFramework { using MouseInteraction = AzToolsFramework::ViewportInteraction::MouseInteraction; using MouseInteractionEvent = AzToolsFramework::ViewportInteraction::MouseInteractionEvent; //! Implementation of the manipulator interface using bus calls to access to the manipulator manager. class IndirectCallManipulatorManager : public ManipulatorManagerInterface { public: IndirectCallManipulatorManager(ViewportInteractionInterface& viewportInteraction); // ManipulatorManagerInterface ... void ConsumeMouseInteractionEvent(const MouseInteractionEvent& event) override; AzToolsFramework::ManipulatorManagerId GetId() const override; bool ManipulatorBeingInteracted() const override; private: // trigger the updating of manipulator bounds. void DrawManipulators(); ViewportInteractionInterface& m_viewportInteraction; }; IndirectCallManipulatorManager::IndirectCallManipulatorManager(ViewportInteractionInterface& viewportInteraction) : m_viewportInteraction(viewportInteraction) { } void IndirectCallManipulatorManager::ConsumeMouseInteractionEvent(const MouseInteractionEvent& event) { DrawManipulators(); AzToolsFramework::EditorInteractionSystemViewportSelectionRequestBus::Event( AzToolsFramework::GetEntityContextId(), &AzToolsFramework::ViewportInteraction::InternalMouseViewportRequests::InternalHandleAllMouseInteractions, event); DrawManipulators(); } void IndirectCallManipulatorManager::DrawManipulators() { AzFramework::ViewportDebugDisplayEventBus::Event( AzToolsFramework::GetEntityContextId(), &AzFramework::ViewportDebugDisplayEvents::DisplayViewport, AzFramework::ViewportInfo{ m_viewportInteraction.GetViewportId() }, m_viewportInteraction.GetDebugDisplay()); } AzToolsFramework::ManipulatorManagerId IndirectCallManipulatorManager::GetId() const { return AzToolsFramework::g_mainManipulatorManagerId; } bool IndirectCallManipulatorManager::ManipulatorBeingInteracted() const { bool manipulatorInteracting; AzToolsFramework::ManipulatorManagerRequestBus::EventResult( manipulatorInteracting, AzToolsFramework::g_mainManipulatorManagerId, &AzToolsFramework::ManipulatorManagerRequestBus::Events::Interacting); return manipulatorInteracting; } IndirectCallManipulatorViewportInteraction::IndirectCallManipulatorViewportInteraction() : m_viewportInteraction(AZStd::make_unique<ViewportInteraction>()) , m_manipulatorManager(AZStd::make_unique<IndirectCallManipulatorManager>(*m_viewportInteraction)) { } IndirectCallManipulatorViewportInteraction::~IndirectCallManipulatorViewportInteraction() = default; const ViewportInteractionInterface& IndirectCallManipulatorViewportInteraction::GetViewportInteraction() const { return *m_viewportInteraction; } const ManipulatorManagerInterface& IndirectCallManipulatorViewportInteraction::GetManipulatorManager() const { return *m_manipulatorManager; } } // namespace AzManipulatorTestFramework
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT-style license found in the * LICENSE file in the root directory of this source tree. */ #include <array> #include "flashlight/fl/nn/Utils.h" #include "flashlight/fl/autograd/Utils.h" #include "flashlight/fl/common/Utils.h" namespace fl { int64_t numTotalParams(std::shared_ptr<fl::Module> module) { int64_t params = 0; for (auto& p : module->params()) { params += p.elements(); } return params; } bool allParamsClose( const Module& a, const Module& b, double absTolerance /* = 1e-5 */) { if (a.params().size() != b.params().size()) { return false; } const auto aParams = a.params(); const auto bParams = b.params(); for (int p = 0; p < aParams.size(); ++p) { if (!allClose(aParams[p], bParams[p], absTolerance)) { return false; } } return true; } namespace detail { int64_t getNumRnnParams( int input_size, int hidden_size, int num_layers, RnnMode mode, bool bidirectional) { int bidir_mul = (bidirectional ? 2 : 1); int64_t i = input_size; int64_t h = hidden_size; int64_t n = num_layers; int64_t b = bidir_mul; int64_t n_params = /* hidden-to-hidden */ h * h * n + /* hidden biases */ h * n + /* input-to-hidden */ i * h + b * (n - 1) * h * h + /* input biases */ h * n; n_params *= b; switch (mode) { case RnnMode::LSTM: n_params *= 4; break; case RnnMode::GRU: n_params *= 3; break; case RnnMode::RELU: case RnnMode::TANH: default: break; } return n_params; } } // namespace detail int derivePadding(int inSz, int filterSz, int stride, int pad, int dilation) { if (pad == static_cast<int>(PaddingMode::SAME)) { int newPad; if (inSz % stride == 0) { newPad = (filterSz - 1) * dilation - stride + 1; } else { newPad = (filterSz - 1) * dilation - (inSz % stride) + 1; } newPad = (newPad + 1) / 2; // equal pad on both sides return std::max(newPad, 0); } return pad; } af::array join( const std::vector<af::array>& inputs, double padValue /* = 0.0 */, dim_t batchDim /* = -1 */) { if (inputs.empty()) { return af::array(); } af::dim4 maxDims; af::dtype type = inputs[0].type(); bool isEmpty = true; for (const auto& in : inputs) { isEmpty = isEmpty && in.isempty(); for (int d = 0; d < AF_MAX_DIMS; ++d) { maxDims[d] = std::max(maxDims[d], in.dims(d)); if (in.type() != type) { throw std::invalid_argument("all arrays should of same type for join"); } } } if (batchDim < 0) { batchDim = maxDims.ndims(); } if (maxDims[batchDim] > 1) { throw std::invalid_argument("no singleton dim available for batching"); } maxDims[batchDim] = inputs.size(); if (isEmpty) { // if empty arrays are provided (some element in maxDims is zero) // then af::constant will create array with sizes 0 and 1 on non-zeros dims, // e.g. maxDims = (0, 3, 4, 5) the af::constant(pad, maxDims) // will have size = (0, 1, 1, 1), not (0, 3, 4, 5) // To avoid this we directly create empty array here with correct sizes return af::array(maxDims, type); } auto padSeq = af::constant(padValue, maxDims, type); std::array<af::seq, AF_MAX_DIMS> sel; for (int i = 0; i < inputs.size(); ++i) { for (int d = 0; d < AF_MAX_DIMS; ++d) { sel[d] = af::seq(inputs[i].dims(d)); } sel[batchDim] = af::seq(i, i); if (!inputs[i].isempty()) { padSeq(sel[0], sel[1], sel[2], sel[3]) = inputs[i]; } } return padSeq; } } // namespace fl
/* -LICENSE-START- ** Copyright (c) 2009 Blackmagic Design ** ** Permission is hereby granted, free of charge, to any person or organization ** obtaining a copy of the software and accompanying documentation covered by ** this license (the "Software") to use, reproduce, display, distribute, ** execute, and transmit the Software, and to prepare derivative works of the ** Software, and to permit third-parties to whom the Software is furnished to ** do so, all subject to the following: ** ** The copyright notices in the Software and this entire statement, including ** the above license grant, this restriction and the following disclaimer, ** must be included in all copies of the Software, in whole or in part, and ** all derivative works of the Software, unless such copies or derivative ** works are solely in the form of machine-executable object code generated by ** a source language processor. ** ** 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT ** SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE ** FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ** ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER ** DEALINGS IN THE SOFTWARE. ** -LICENSE-END- **/ #include <stdio.h> #include <pthread.h> #include <dlfcn.h> #include "DeckLinkAPI.h" #define kDeckLinkAPI_Name "libDeckLinkAPI.so" #define KDeckLinkPreviewAPI_Name "libDeckLinkPreviewAPI.so" typedef IDeckLinkIterator* (*CreateIteratorFunc)(void); typedef IDeckLinkAPIInformation* (*CreateAPIInformationFunc)(void); typedef IDeckLinkGLScreenPreviewHelper* (*CreateOpenGLScreenPreviewHelperFunc)(void); typedef IDeckLinkVideoConversion* (*CreateVideoConversionInstanceFunc)(void); typedef IDeckLinkDiscovery* (*CreateDeckLinkDiscoveryInstanceFunc)(void); typedef IDeckLinkVideoFrameAncillaryPackets* (*CreateVideoFrameAncillaryPacketsInstanceFunc)(void); static pthread_once_t gDeckLinkOnceControl = PTHREAD_ONCE_INIT; static pthread_once_t gPreviewOnceControl = PTHREAD_ONCE_INIT; static bool gLoadedDeckLinkAPI = false; static CreateIteratorFunc gCreateIteratorFunc = NULL; static CreateAPIInformationFunc gCreateAPIInformationFunc = NULL; static CreateOpenGLScreenPreviewHelperFunc gCreateOpenGLPreviewFunc = NULL; static CreateVideoConversionInstanceFunc gCreateVideoConversionFunc = NULL; static CreateDeckLinkDiscoveryInstanceFunc gCreateDeckLinkDiscoveryFunc = NULL; static CreateVideoFrameAncillaryPacketsInstanceFunc gCreateVideoFrameAncillaryPacketsFunc = NULL; void InitDeckLinkAPI (void) { void *libraryHandle; libraryHandle = dlopen(kDeckLinkAPI_Name, RTLD_NOW|RTLD_GLOBAL); if (!libraryHandle) { fprintf(stderr, "%s\n", dlerror()); return; } gLoadedDeckLinkAPI = true; gCreateIteratorFunc = (CreateIteratorFunc)dlsym(libraryHandle, "CreateDeckLinkIteratorInstance_0003"); if (!gCreateIteratorFunc) fprintf(stderr, "%s\n", dlerror()); gCreateAPIInformationFunc = (CreateAPIInformationFunc)dlsym(libraryHandle, "CreateDeckLinkAPIInformationInstance_0001"); if (!gCreateAPIInformationFunc) fprintf(stderr, "%s\n", dlerror()); gCreateVideoConversionFunc = (CreateVideoConversionInstanceFunc)dlsym(libraryHandle, "CreateVideoConversionInstance_0001"); if (!gCreateVideoConversionFunc) fprintf(stderr, "%s\n", dlerror()); gCreateDeckLinkDiscoveryFunc = (CreateDeckLinkDiscoveryInstanceFunc)dlsym(libraryHandle, "CreateDeckLinkDiscoveryInstance_0002"); if (!gCreateDeckLinkDiscoveryFunc) fprintf(stderr, "%s\n", dlerror()); gCreateVideoFrameAncillaryPacketsFunc = (CreateVideoFrameAncillaryPacketsInstanceFunc)dlsym(libraryHandle, "CreateVideoFrameAncillaryPacketsInstance_0001"); if (!gCreateVideoFrameAncillaryPacketsFunc) fprintf(stderr, "%s\n", dlerror()); } void InitDeckLinkPreviewAPI (void) { void *libraryHandle; libraryHandle = dlopen(KDeckLinkPreviewAPI_Name, RTLD_NOW|RTLD_GLOBAL); if (!libraryHandle) { fprintf(stderr, "%s\n", dlerror()); return; } gCreateOpenGLPreviewFunc = (CreateOpenGLScreenPreviewHelperFunc)dlsym(libraryHandle, "CreateOpenGLScreenPreviewHelper_0001"); if (!gCreateOpenGLPreviewFunc) fprintf(stderr, "%s\n", dlerror()); } bool IsDeckLinkAPIPresent (void) { // If the DeckLink API dynamic library was successfully loaded, return this knowledge to the caller return gLoadedDeckLinkAPI; } IDeckLinkIterator* CreateDeckLinkIteratorInstance (void) { pthread_once(&gDeckLinkOnceControl, InitDeckLinkAPI); if (gCreateIteratorFunc == NULL) return NULL; return gCreateIteratorFunc(); } IDeckLinkAPIInformation* CreateDeckLinkAPIInformationInstance (void) { pthread_once(&gDeckLinkOnceControl, InitDeckLinkAPI); if (gCreateAPIInformationFunc == NULL) return NULL; return gCreateAPIInformationFunc(); } IDeckLinkGLScreenPreviewHelper* CreateOpenGLScreenPreviewHelper (void) { pthread_once(&gDeckLinkOnceControl, InitDeckLinkAPI); pthread_once(&gPreviewOnceControl, InitDeckLinkPreviewAPI); if (gCreateOpenGLPreviewFunc == NULL) return NULL; return gCreateOpenGLPreviewFunc(); } IDeckLinkVideoConversion* CreateVideoConversionInstance (void) { pthread_once(&gDeckLinkOnceControl, InitDeckLinkAPI); if (gCreateVideoConversionFunc == NULL) return NULL; return gCreateVideoConversionFunc(); } IDeckLinkDiscovery* CreateDeckLinkDiscoveryInstance (void) { pthread_once(&gDeckLinkOnceControl, InitDeckLinkAPI); if (gCreateDeckLinkDiscoveryFunc == NULL) return NULL; return gCreateDeckLinkDiscoveryFunc(); } IDeckLinkVideoFrameAncillaryPackets* CreateVideoFrameAncillaryPacketsInstance (void) { pthread_once(&gDeckLinkOnceControl, InitDeckLinkAPI); if (gCreateVideoFrameAncillaryPacketsFunc == NULL) return NULL; return gCreateVideoFrameAncillaryPacketsFunc(); }
#include <algorithm> #include <cassert> #include <cstdio> #include <iostream> #include <sstream> #include <string> #include <vector> using namespace std; bool done[1<<19][12]; int cnt[1<<19]; enum { NEG_FIX = 12000 }; int sol; int n; const unsigned black = 0x54A; int next[19][12]; int bitcount(unsigned x) { int ret = 0; while (x != 0) { ++ret; x &= (x-1); } return ret; } void go(unsigned state, int cur) { if (done[state][cur]) return; done[state][cur] = true; sol = max(sol, cnt[state]); for (int i=n-1; i>=0; --i) if ((state & (1<<i))==0 && next[i][cur]!=-1) go(state | (1<<i), next[i][cur]); } class CMajor { public: int getLongest(vector <string> fragments) { n = fragments.size(); memset(done, 0, sizeof done); unsigned frag[19] = { 0 }; int move[19] = { 0 }; for (int i=0; i<(1<<n); ++i) cnt[i] = bitcount(i); for (int i=0; i<n; ++i) { istringstream is(fragments[i]); int t; while (is >> t) { if (t >= 0) { move[i] = (move[i]+t) % 12; frag[i] |= (1<<move[i]); } else { move[i] = (move[i] + (t+NEG_FIX)%12) % 12; frag[i] |= (1<<move[i]); } } } for (int i=0; i<n; ++i) for (int j=0; j<12; ++j) if ((((frag[i]<<j)+(frag[i]>>(12-j))) & black) == 0) next[i][j] = (j+move[i])%12; else next[i][j] = -1; sol = 0; go(0u, 0); go(0u, 2); go(0u, 4); go(0u, 5); go(0u, 7); go(0u, 9); go(0u, 11); return sol; } // BEGIN CUT HERE public: void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); if ((Case == -1) || (Case == 5)) test_case_5(); } private: template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); } void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } } void test_case_0() { string Arr0[] = {"2 2 1 2 2 2 1","2 1 2 2 2 1 2"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; verify_case(0, Arg1, getLongest(Arg0)); } void test_case_1() { string Arr0[] = {"2","2","1","2","2","2","1","2","2","1","2","2","2","1","2","2","1","2","2"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 19; verify_case(1, Arg1, getLongest(Arg0)); } void test_case_2() { string Arr0[] = {"2 2 2 2","1 1","5 -4 12 -11","0 2 -2 5 -1 -4 2 -2 7 -2"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; verify_case(2, Arg1, getLongest(Arg0)); } void test_case_3() { string Arr0[] = {"2 0 2 0 -2 -2 -1 5 1 2 2 2 1"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 1; verify_case(3, Arg1, getLongest(Arg0)); } void test_case_4() { string Arr0[] = {"5748 -4385 -790 5294 3349","-3279 -1783 3768 -2459 6066 2556 -8138 -4982 1435", "2951","-2405 2104 3756","5578 -5040 -9497 -4868 7407 9305 -6701", "-3339 9514 -787 7209 7467 -4467", "7496 3011 9941 -8340 3012"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 4; verify_case(4, Arg1, getLongest(Arg0)); } void test_case_5() { string Arr0[] = {"72","1872","8916","-288","2208","-4716","2328","9516", "-5472","9840","6420","3492","-1608","4176","264","-6264", "1176","-684","3984"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); int Arg1 = 19; verify_case(5, Arg1, getLongest(Arg0)); } // END CUT HERE }; // BEGIN CUT HERE int main() { CMajor ___test; ___test.run_test(-1); } // END CUT HERE
#include "secretstapler.hpp" #include <botan/auto_rng.h> #include <botan/cipher_mode.h> #include <botan/hex.h> #include <fstream> using namespace std; namespace ss { static const string_view kAlgorithm = "AES-128/CBC/PKCS7"; filesystem::path generate(const filesystem::path &file) { if (filesystem::is_directory(file) || !filesystem::exists(filesystem::absolute(file).parent_path())) return filesystem::path(); unique_ptr<Botan::Cipher_Mode> cipher = Botan::Cipher_Mode::create(kAlgorithm.data(), Botan::ENCRYPTION); Botan::AutoSeeded_RNG rng; Botan::secure_vector<uint8_t> key = rng.random_vec(cipher->default_nonce_length()); Botan::secure_vector<uint8_t> iv = rng.random_vec(cipher->default_nonce_length()); filesystem::path result = filesystem::absolute(file); ofstream output(result, ios::app); output << "{\"key\":\"" << Botan::hex_encode(key) << "\",\"iv\":\"" << Botan::hex_encode(iv) << "\"}" << endl; output.close(); return result; } filesystem::path xcrypt(const filesystem::path &file, string_view key, string_view iv, string_view direction) { if (!filesystem::exists(file) || filesystem::is_directory(file)) return filesystem::path(); ifstream input(file, ios::binary); if (!input.is_open()) return filesystem::path(); Botan::secure_vector<uint8_t> buffer( {(istreambuf_iterator<char>(input)), istreambuf_iterator<char>()}); input.close(); Botan::Cipher_Dir cdir; filesystem::path result; if (direction == "encrypt") { cdir = Botan::ENCRYPTION; result = filesystem::absolute(file.string().append(".enc")); } else /*if (direction == "decrypt")*/ { cdir = Botan::DECRYPTION; result = filesystem::absolute(file.string().append(".dec")); } unique_ptr<Botan::Cipher_Mode> cipher = Botan::Cipher_Mode::create(kAlgorithm.data(), cdir); cipher->set_key(Botan::hex_decode_locked(key.data())); cipher->start(Botan::hex_decode_locked(iv.data())); cipher->finish(buffer); ofstream output(result, ios::binary | ios::trunc); output.write(reinterpret_cast<const char *>(buffer.data()), static_cast<streamsize>(buffer.size())); output.close(); return result; } } // namespace ss
#include "routing_table.hpp" #include "util.hpp" #include <arpa/inet.h> #include <linux/rtnetlink.h> #include <net/if.h> #include <netinet/in.h> #include <sys/ioctl.h> #include <sys/socket.h> #include <sys/types.h> #include <unistd.h> #include <phosphor-logging/elog-errors.hpp> #include <phosphor-logging/log.hpp> #include <stdexcept> #include <xyz/openbmc_project/Common/error.hpp> namespace phosphor { namespace network { namespace route { using namespace phosphor::logging; using namespace sdbusplus::xyz::openbmc_project::Common::Error; Table::Table() { try { getRoutes(); } catch (InternalFailure& e) { commit<InternalFailure>(); } } int Table::readNetLinkSock(int sockFd, std::array<char, BUFSIZE>& buf) { struct nlmsghdr* nlHdr = nullptr; int readLen{}; int msgLen{}; uint8_t seqNum = 1; uint8_t pID = getpid(); char* bufPtr = buf.data(); do { // Receive response from the kernel if ((readLen = recv(sockFd, bufPtr, BUFSIZE - msgLen, 0)) < 0) { auto error = errno; log<level::ERR>("Socket recv failed:", entry("ERROR=%s", strerror(error))); elog<InternalFailure>(); } nlHdr = reinterpret_cast<nlmsghdr*>(bufPtr); // Check if the header is valid if ((NLMSG_OK(nlHdr, readLen) == 0) || (nlHdr->nlmsg_type == NLMSG_ERROR)) { auto error = errno; log<level::ERR>("Error validating header", entry("NLMSGTYPE=%d", nlHdr->nlmsg_type), entry("ERROR=%s", strerror(error))); elog<InternalFailure>(); } // Check if the its the last message if (nlHdr->nlmsg_type == NLMSG_DONE) { break; } else { // Else move the pointer to buffer appropriately bufPtr += readLen; msgLen += readLen; } // Check if its a multi part message if ((nlHdr->nlmsg_flags & NLM_F_MULTI) == 0) { break; } } while ((nlHdr->nlmsg_seq != seqNum) || (nlHdr->nlmsg_pid != pID)); return msgLen; } void Table::parseRoutes(const nlmsghdr* nlHdr) { rtmsg* rtMsg = nullptr; rtattr* rtAttr = nullptr; int rtLen{}; in_addr dstAddr{}; in_addr gateWayAddr{}; char ifName[IF_NAMESIZE] = {}; rtMsg = reinterpret_cast<rtmsg*>(NLMSG_DATA(nlHdr)); // If the route is not for AF_INET or does not belong to main routing table // then return. if ((rtMsg->rtm_family != AF_INET) || (rtMsg->rtm_table != RT_TABLE_MAIN)) { return; } // get the rtattr field rtAttr = reinterpret_cast<rtattr*>(RTM_RTA(rtMsg)); rtLen = RTM_PAYLOAD(nlHdr); for (; RTA_OK(rtAttr, rtLen); rtAttr = RTA_NEXT(rtAttr, rtLen)) { switch (rtAttr->rta_type) { case RTA_OIF: if_indextoname(*reinterpret_cast<int*>(RTA_DATA(rtAttr)), ifName); break; case RTA_GATEWAY: gateWayAddr.s_addr = *reinterpret_cast<u_int*>(RTA_DATA(rtAttr)); break; case RTA_DST: dstAddr.s_addr = *reinterpret_cast<u_int*>(RTA_DATA(rtAttr)); break; } } std::string dstStr; std::string gatewayStr; if (dstAddr.s_addr == 0 && gateWayAddr.s_addr != 0) { defaultGateway = reinterpret_cast<char*>(inet_ntoa(gateWayAddr)); } dstStr = inet_ntoa(dstAddr); gatewayStr = inet_ntoa(gateWayAddr); Entry route(dstStr, gatewayStr, ifName); // if there is already existing route for this network // then ignore the next one as it would not be used by the // routing policy // So don't update the route entry for the network for which // there is already a route exist. if (routeList.find(dstStr) == routeList.end()) { routeList.emplace(std::make_pair(dstStr, std::move(route))); } } Map Table::getRoutes() { nlmsghdr* nlMsg = nullptr; std::array<char, BUFSIZE> msgBuf = {0}; int sock = -1; int len{0}; uint8_t msgSeq{0}; // Create Socket if ((sock = socket(PF_NETLINK, SOCK_DGRAM, NETLINK_ROUTE)) < 0) { auto error = errno; log<level::ERR>("Error occurred during socket creation", entry("ERRNO=%s", strerror(error))); elog<InternalFailure>(); } phosphor::Descriptor smartSock(sock); sock = -1; // point the header and the msg structure pointers into the buffer. nlMsg = reinterpret_cast<nlmsghdr*>(msgBuf.data()); // Length of message nlMsg->nlmsg_len = NLMSG_LENGTH(sizeof(rtmsg)); // Get the routes from kernel routing table nlMsg->nlmsg_type = RTM_GETROUTE; // The message is a request for dump nlMsg->nlmsg_flags = NLM_F_DUMP | NLM_F_REQUEST; nlMsg->nlmsg_seq = msgSeq; nlMsg->nlmsg_pid = getpid(); // Send the request if (send(smartSock(), nlMsg, nlMsg->nlmsg_len, 0) < 0) { auto error = errno; log<level::ERR>("Error occurred during send on netlink socket", entry("ERRNO=%s", strerror(error))); elog<InternalFailure>(); } // Read the response len = readNetLinkSock(smartSock(), msgBuf); // Parse and print the response for (; NLMSG_OK(nlMsg, len); nlMsg = NLMSG_NEXT(nlMsg, len)) { parseRoutes(nlMsg); } return routeList; } std::string Table::getGateway(int addressFamily, const std::string& ipaddress, uint8_t prefix) const { std::string gateway; std::string network = getNetworkID(addressFamily, ipaddress, prefix); auto it = routeList.find(network); if (it != routeList.end()) { gateway = it->second.gateway; } return gateway; } } // namespace route } // namespace network } // namespace phosphor
// Licensed under the MIT License <http://opensource.org/licenses/MIT>. // SPDX-License-Identifier: MIT // Copyright (c) 2019 Daniil Goncharov <neargye@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. #define CATCH_CONFIG_MAIN #include <catch.hpp> #define MAGIC_ENUM_RANGE_MIN -120 #define MAGIC_ENUM_RANGE_MAX 120 #include <magic_enum.hpp> #include <array> #include <string_view> #include <sstream> enum class Color { RED = -12, GREEN = 7, BLUE = 15 }; enum class Numbers : char { one = 10, two = 20, three = 30, many = 127 }; enum Directions { Up = 85, Down = -42, Right = 120, Left = -120 }; enum number : unsigned long { one = 100, two = 200, three = 300, four = 400 }; namespace magic_enum { template <> struct enum_range<number> { static constexpr int min = 100; static constexpr int max = 300; }; } TEST_CASE("enum_cast") { SECTION("string") { #if defined(_MSC_VER) && _MSC_VER < 1920 # define constexpr // Visual Studio 2017 have bug with string_view constexpr compare. #endif constexpr auto cr = magic_enum::enum_cast<Color>("RED"); REQUIRE(cr.value() == Color::RED); REQUIRE(magic_enum::enum_cast<Color>("GREEN").value() == Color::GREEN); REQUIRE(magic_enum::enum_cast<Color>("BLUE").value() == Color::BLUE); REQUIRE_FALSE(magic_enum::enum_cast<Color>("None").has_value()); constexpr auto no = magic_enum::enum_cast<Numbers>("one"); REQUIRE(no.value() == Numbers::one); REQUIRE(magic_enum::enum_cast<Numbers>("two").value() == Numbers::two); REQUIRE(magic_enum::enum_cast<Numbers>("three").value() == Numbers::three); REQUIRE_FALSE(magic_enum::enum_cast<Numbers>("many").has_value()); REQUIRE_FALSE(magic_enum::enum_cast<Numbers>("None").has_value()); constexpr auto dr = magic_enum::enum_cast<Directions>("Right"); REQUIRE(magic_enum::enum_cast<Directions>("Up").value() == Directions::Up); REQUIRE(magic_enum::enum_cast<Directions>("Down").value() == Directions::Down); REQUIRE(dr.value() == Directions::Right); REQUIRE(magic_enum::enum_cast<Directions>("Left").value() == Directions::Left); REQUIRE_FALSE(magic_enum::enum_cast<Directions>("None").has_value()); constexpr auto nt = magic_enum::enum_cast<number>("three"); REQUIRE(magic_enum::enum_cast<number>("one").value() == number::one); REQUIRE(magic_enum::enum_cast<number>("two").value() == number::two); REQUIRE(nt.value() == number::three); REQUIRE_FALSE(magic_enum::enum_cast<number>("four").has_value()); REQUIRE_FALSE(magic_enum::enum_cast<number>("None").has_value()); #undef constexpr } SECTION("integer") { constexpr auto cr = magic_enum::enum_cast<Color>(-12); REQUIRE(cr.value() == Color::RED); REQUIRE(magic_enum::enum_cast<Color>(7).value() == Color::GREEN); REQUIRE(magic_enum::enum_cast<Color>(15).value() == Color::BLUE); REQUIRE_FALSE(magic_enum::enum_cast<Color>(0).has_value()); constexpr auto no = magic_enum::enum_cast<Numbers>(10); REQUIRE(no.value() == Numbers::one); REQUIRE(magic_enum::enum_cast<Numbers>(20).value() == Numbers::two); REQUIRE(magic_enum::enum_cast<Numbers>(30).value() == Numbers::three); REQUIRE_FALSE(magic_enum::enum_cast<Numbers>(127).has_value()); REQUIRE_FALSE(magic_enum::enum_cast<Numbers>(0).has_value()); constexpr auto dr = magic_enum::enum_cast<Directions>(120); REQUIRE(magic_enum::enum_cast<Directions>(85).value() == Directions::Up); REQUIRE(magic_enum::enum_cast<Directions>(-42).value() == Directions::Down); REQUIRE(dr.value() == Directions::Right); REQUIRE(magic_enum::enum_cast<Directions>(-120).value() == Directions::Left); REQUIRE_FALSE(magic_enum::enum_cast<Directions>(0).has_value()); constexpr auto nt = magic_enum::enum_cast<number>(300); REQUIRE(magic_enum::enum_cast<number>(100).value() == number::one); REQUIRE(magic_enum::enum_cast<number>(200).value() == number::two); REQUIRE(nt.value() == number::three); REQUIRE_FALSE(magic_enum::enum_cast<number>(400).has_value()); REQUIRE_FALSE(magic_enum::enum_cast<number>(0).has_value()); } } TEST_CASE("enum_integer") { constexpr auto cr = magic_enum::enum_integer(Color::RED); REQUIRE(cr == -12); REQUIRE(magic_enum::enum_integer(Color::GREEN) == 7); REQUIRE(magic_enum::enum_integer(Color::BLUE) == 15); REQUIRE(magic_enum::enum_integer(static_cast<Color>(0)) == 0); constexpr auto no = magic_enum::enum_integer(Numbers::one); REQUIRE(no == 10); REQUIRE(magic_enum::enum_integer(Numbers::two) == 20); REQUIRE(magic_enum::enum_integer(Numbers::three) == 30); REQUIRE(magic_enum::enum_integer(Numbers::many) == 127); REQUIRE(magic_enum::enum_integer(static_cast<Numbers>(0)) == 0); constexpr auto dr = magic_enum::enum_integer(Directions::Right); REQUIRE(magic_enum::enum_integer(Directions::Left) == -120); REQUIRE(magic_enum::enum_integer(Directions::Down) == -42); REQUIRE(magic_enum::enum_integer(Directions::Up) == 85); REQUIRE(dr == 120); REQUIRE(magic_enum::enum_integer(static_cast<Directions>(0)) == 0); constexpr auto nt = magic_enum::enum_integer(number::three); REQUIRE(magic_enum::enum_integer(number::one) == 100); REQUIRE(magic_enum::enum_integer(number::two) == 200); REQUIRE(nt == 300); REQUIRE(magic_enum::enum_integer(number::four) == 400); REQUIRE(magic_enum::enum_integer(static_cast<number>(0)) == 0); } TEST_CASE("enum_value") { constexpr auto cr = magic_enum::enum_value<Color>(0); REQUIRE(cr == Color::RED); REQUIRE(magic_enum::enum_value<Color>(1) == Color::GREEN); REQUIRE(magic_enum::enum_value<Color>(2) == Color::BLUE); constexpr auto no = magic_enum::enum_value<Numbers>(0); REQUIRE(no == Numbers::one); REQUIRE(magic_enum::enum_value<Numbers>(1) == Numbers::two); REQUIRE(magic_enum::enum_value<Numbers>(2) == Numbers::three); constexpr auto dr = magic_enum::enum_value<Directions>(3); REQUIRE(magic_enum::enum_value<Directions>(0) == Directions::Left); REQUIRE(magic_enum::enum_value<Directions>(1) == Directions::Down); REQUIRE(magic_enum::enum_value<Directions>(2) == Directions::Up); REQUIRE(dr == Directions::Right); constexpr auto nt = magic_enum::enum_value<number>(2); REQUIRE(magic_enum::enum_value<number>(0) == number::one); REQUIRE(magic_enum::enum_value<number>(1) == number::two); REQUIRE(nt == number::three); } TEST_CASE("enum_values") { constexpr auto s1 = magic_enum::enum_values<Color>(); REQUIRE(s1 == std::array<Color, 3>{{Color::RED, Color::GREEN, Color::BLUE}}); constexpr auto s2 = magic_enum::enum_values<Numbers>(); REQUIRE(s2 == std::array<Numbers, 3>{{Numbers::one, Numbers::two, Numbers::three}}); constexpr auto s3 = magic_enum::enum_values<Directions>(); REQUIRE(s3 == std::array<Directions, 4>{{Directions::Left, Directions::Down, Directions::Up, Directions::Right}}); constexpr auto s4 = magic_enum::enum_values<number>(); REQUIRE(s4 == std::array<number, 3>{{number::one, number::two, number::three}}); } TEST_CASE("enum_count") { constexpr auto s1 = magic_enum::enum_count<Color>(); REQUIRE(s1 == 3); constexpr auto s2 = magic_enum::enum_count<Numbers>(); REQUIRE(s2 == 3); constexpr auto s3 = magic_enum::enum_count<Directions>(); REQUIRE(s3 == 4); constexpr auto s4 = magic_enum::enum_count<number>(); REQUIRE(s4 == 3); } TEST_CASE("enum_name") { SECTION("automatic storage") { constexpr Color cr = Color::RED; constexpr auto cr_name = magic_enum::enum_name(cr); Color cm[3] = {Color::RED, Color::GREEN, Color::BLUE}; REQUIRE(cr_name == "RED"); REQUIRE(magic_enum::enum_name(Color::BLUE) == "BLUE"); REQUIRE(magic_enum::enum_name(cm[1]) == "GREEN"); REQUIRE(magic_enum::enum_name(static_cast<Color>(0)).empty()); constexpr Numbers no = Numbers::one; constexpr auto no_name = magic_enum::enum_name(no); REQUIRE(no_name == "one"); REQUIRE(magic_enum::enum_name(Numbers::two) == "two"); REQUIRE(magic_enum::enum_name(Numbers::three) == "three"); REQUIRE(magic_enum::enum_name(Numbers::many).empty()); REQUIRE(magic_enum::enum_name(static_cast<Numbers>(0)).empty()); constexpr Directions dr = Directions::Right; constexpr auto dr_name = magic_enum::enum_name(dr); REQUIRE(magic_enum::enum_name(Directions::Up) == "Up"); REQUIRE(magic_enum::enum_name(Directions::Down) == "Down"); REQUIRE(dr_name == "Right"); REQUIRE(magic_enum::enum_name(Directions::Left) == "Left"); REQUIRE(magic_enum::enum_name(static_cast<Directions>(0)).empty()); constexpr number nt = number::three; constexpr auto nt_name = magic_enum::enum_name(nt); REQUIRE(magic_enum::enum_name(number::one) == "one"); REQUIRE(magic_enum::enum_name(number::two) == "two"); REQUIRE(nt_name == "three"); REQUIRE(magic_enum::enum_name(number::four).empty()); REQUIRE(magic_enum::enum_name(static_cast<number>(0)).empty()); } SECTION("static storage") { constexpr Color cr = Color::RED; constexpr auto cr_name = magic_enum::enum_name<cr>(); constexpr Color cm[3] = {Color::RED, Color::GREEN, Color::BLUE}; REQUIRE(cr_name == "RED"); REQUIRE(magic_enum::enum_name<Color::BLUE>() == "BLUE"); REQUIRE(magic_enum::enum_name<cm[1]>() == "GREEN"); REQUIRE(magic_enum::enum_name<static_cast<Color>(0)>().empty()); constexpr Numbers no = Numbers::one; constexpr auto no_name = magic_enum::enum_name<no>(); REQUIRE(no_name == "one"); REQUIRE(magic_enum::enum_name<Numbers::two>() == "two"); REQUIRE(magic_enum::enum_name<Numbers::three>() == "three"); REQUIRE(magic_enum::enum_name<Numbers::many>() == "many"); REQUIRE(magic_enum::enum_name<static_cast<Numbers>(0)>().empty()); constexpr Directions dr = Directions::Right; constexpr auto dr_name = magic_enum::enum_name<dr>(); REQUIRE(magic_enum::enum_name<Directions::Up>() == "Up"); REQUIRE(magic_enum::enum_name<Directions::Down>() == "Down"); REQUIRE(dr_name == "Right"); REQUIRE(magic_enum::enum_name<Directions::Left>() == "Left"); REQUIRE(magic_enum::enum_name<static_cast<Directions>(0)>().empty()); constexpr number nt = number::three; constexpr auto nt_name = magic_enum::enum_name<nt>(); REQUIRE(magic_enum::enum_name<number::one>() == "one"); REQUIRE(magic_enum::enum_name<number::two>() == "two"); REQUIRE(nt_name == "three"); REQUIRE(magic_enum::enum_name<number::four>() == "four"); REQUIRE(magic_enum::enum_name<static_cast<number>(0)>().empty()); } } TEST_CASE("enum_names") { constexpr auto s1 = magic_enum::enum_names<Color>(); REQUIRE(s1 == std::array<std::string_view, 3>{{"RED", "GREEN", "BLUE"}}); constexpr auto s2 = magic_enum::enum_names<Numbers>(); REQUIRE(s2 == std::array<std::string_view, 3>{{"one", "two", "three"}}); constexpr auto s3 = magic_enum::enum_names<Directions>(); REQUIRE(s3 == std::array<std::string_view, 4>{{"Left", "Down", "Up", "Right"}}); constexpr auto s4 = magic_enum::enum_names<number>(); REQUIRE(s4 == std::array<std::string_view, 3>{{"one", "two", "three"}}); } TEST_CASE("enum_entries") { constexpr auto s1 = magic_enum::enum_entries<Color>(); REQUIRE(s1 == std::array<std::pair<Color, std::string_view>, 3>{{{Color::RED, "RED"}, {Color::GREEN, "GREEN"}, {Color::BLUE, "BLUE"}}}); constexpr auto s2 = magic_enum::enum_entries<Numbers>(); REQUIRE(s2 == std::array<std::pair<Numbers, std::string_view>, 3>{{{Numbers::one, "one"}, {Numbers::two, "two"}, {Numbers::three, "three"}}}); constexpr auto s3 = magic_enum::enum_entries<Directions>(); REQUIRE(s3 == std::array<std::pair<Directions, std::string_view>, 4>{{{Directions::Left, "Left"}, {Directions::Down, "Down"}, {Directions::Up, "Up"}, {Directions::Right, "Right"}}}); constexpr auto s4 = magic_enum::enum_entries<number>(); REQUIRE(s4 == std::array<std::pair<number, std::string_view>, 3>{{{number::one, "one"}, {number::two, "two"}, {number::three, "three"}}}); } TEST_CASE("operator<<") { auto test_ostream = [](auto e, std::string_view name) { using namespace magic_enum::ops; std::stringstream ss; ss << e; REQUIRE(ss.str() == name); }; test_ostream(Color::RED, "RED"); test_ostream(Color::GREEN, "GREEN"); test_ostream(Color::BLUE, "BLUE"); test_ostream(static_cast<Color>(0), ""); test_ostream(Numbers::one, "one"); test_ostream(Numbers::two, "two"); test_ostream(Numbers::three, "three"); test_ostream(Numbers::many, ""); test_ostream(static_cast<Numbers>(0), ""); test_ostream(Directions::Up, "Up"); test_ostream(Directions::Down, "Down"); test_ostream(Directions::Right, "Right"); test_ostream(Directions::Left, "Left"); test_ostream(static_cast<Directions>(0), ""); test_ostream(number::one, "one"); test_ostream(number::two, "two"); test_ostream(number::three, "three"); test_ostream(number::four, ""); test_ostream(static_cast<number>(0), ""); } TEST_CASE("type_traits") { REQUIRE_FALSE(magic_enum::is_unscoped_enum_v<Color>); REQUIRE_FALSE(magic_enum::is_unscoped_enum_v<Numbers>); REQUIRE(magic_enum::is_unscoped_enum_v<Directions>); REQUIRE(magic_enum::is_unscoped_enum_v<number>); REQUIRE(magic_enum::is_scoped_enum_v<Color>); REQUIRE(magic_enum::is_scoped_enum_v<Numbers>); REQUIRE_FALSE(magic_enum::is_scoped_enum_v<Directions>); REQUIRE_FALSE(magic_enum::is_scoped_enum_v<number>); }
// Copyright Glen Knowles 2021. // Distributed under the Boost Software License, Version 1.0. // // git.cpp - dim tools #include "pch.h" #pragma hdrstop using namespace std; using namespace Dim; /**************************************************************************** * * Git helper functions * ***/ //=========================================================================== // Failure logs error and returns empty string. string Dim::gitFindRoot(string_view path) { // Query metadata of repo containing config file auto cmdline = Cli::toCmdlineL( "git", "-C", path, "rev-parse", "--show-toplevel" ); auto content = execToolWait(cmdline, path); return Path(trim(content)).str(); } //=========================================================================== // True if successful, otherwise logs error. bool Dim::gitLoadConfig( string * content, string * configFile, string * gitRoot, string_view pathFromCurrentDir, string_view fallbackPathFromGitRoot ) { if (!pathFromCurrentDir.empty()) { *configFile = pathFromCurrentDir; } else { *gitRoot = gitFindRoot(fileGetCurrentDir()); *configFile = Path(fallbackPathFromGitRoot).resolve(*gitRoot); } *gitRoot = gitFindRoot(Path(*configFile).parentPath()); if (!fileExists(*configFile)) { auto path = Path(envExecPath()).removeFilename() / Path(*configFile).filename(); *configFile = move(path); } if (!fileLoadBinaryWait(content, *configFile)) { appSignalShutdown(EX_DATAERR); configFile->clear(); gitRoot->clear(); return false; } return true; }
#include "WindowApp.h" #ifndef WIN32_LEAN_AND_MEAN #define WIN32_LEAN_AND_MEAN #endif #include <Windows.h> using namespace Engine; int CALLBACK WinMain(_In_ HINSTANCE hInstance, _In_ HINSTANCE hPrevInstance, _In_ LPSTR lpCmdLine, _In_ int nCmdShow) { int val = -1; WindowApp window("My Application", 800.0f, 600.0f); if (window.Initialize()) { val = window.Run(); } return val; }
#include <iostream> #include <stdio.h> #include <Eigen/Dense> #include <Eigen/LU> #include <Eigen/Core> /* * A benchmark to test performance of calculating determinants of * 6x6 matrices with the Eigen linear algebra package. */ using namespace std; using namespace Eigen; int main(int argc, char * argv[]) { if (argc != 3 || strcmp(argv[1], "-h") == 0) { cout << "Usage: ./eigDeterm N_MATRIX(<=1000) ITERATIONS(~1000)" << endl; return 1; } srand(time(NULL)); int MAT_DIM = 6; int N_MATRIX = atoi(argv[1]); int ITERATIONS = atoi(argv[2]); int i, j, k, count; double start, end, t_time = 0.0; printf("N_MATRIX: %d, ITERATIONS: %d\n", N_MATRIX, ITERATIONS); //Setting up array of matrices MatrixXd *m_list = new MatrixXd[N_MATRIX]; //Initialise each matrix in m_list as random 6x6 matrices for (i=0; i<N_MATRIX; i++) { m_list[i] = MatrixXd::Random(MAT_DIM, MAT_DIM); } start = (double)clock() / (double) CLOCKS_PER_SEC; //Calculating determinants of matrices for(i=0; i<ITERATIONS; i++) { for(j=0; j<N_MATRIX; j++) { volatile double determinant; determinant = m_list[j].determinant(); } } end = (double)clock() / (double) CLOCKS_PER_SEC; cout << "Total CPU time: " << end - start << endl; return 0; }
#include <optional> #include <fstream> #include <iostream> #include <vector> #include <string> #include <io2d.h> #include "route_model.h" #include "render.h" #include "route_planner.h" using namespace std::experimental; static std::optional<std::vector<std::byte>> ReadFile(const std::string &path) { std::ifstream is{path, std::ios::binary | std::ios::ate}; if( !is ) return std::nullopt; auto size = is.tellg(); std::vector<std::byte> contents(size); is.seekg(0); is.read((char*)contents.data(), size); if( contents.empty() ) return std::nullopt; return std::move(contents); } int main(int argc, const char **argv) { std::string osm_data_file = ""; if( argc > 1 ) { for( int i = 1; i < argc; ++i ) if( std::string_view{argv[i]} == "-f" && ++i < argc ) osm_data_file = argv[i]; } else { std::cout << "To specify a map file use the following format: " << std::endl; std::cout << "Usage: [executable] [-f filename.osm]" << std::endl; osm_data_file = "../map.osm"; } std::vector<std::byte> osm_data; if( osm_data.empty() && !osm_data_file.empty() ) { std::cout << "Reading OpenStreetMap data from the following file: " << osm_data_file << std::endl; auto data = ReadFile(osm_data_file); if( !data ) std::cout << "Failed to read." << std::endl; else osm_data = std::move(*data); } // User input for these values using std::cin. // Pass the user input to the RoutePlanner object below float start_x, start_y, end_x, end_y; std::cout << "Enter Starting x-coordinate" << std::endl ; std::cin >> start_x; std::cout << "Enter Starting y-coordinate" << std::endl ; std::cin >> start_y; std::cout << "Enter Ending x-coordinate" << std::endl ; std::cin >> end_x; std::cout << "Enter Ending y-coordinate" << std::endl ; std::cin >> end_y; // Build Model. RouteModel model{osm_data}; // Create RoutePlanner object and perform A* search. RoutePlanner route_planner{model, start_x, start_y, end_x, end_y}; route_planner.AStarSearch(); std::cout << "Distance: " << route_planner.GetDistance() << " meters. \n"; // Render results of search. Render render{model}; auto display = io2d::output_surface{400, 400, io2d::format::argb32, io2d::scaling::none, io2d::refresh_style::fixed, 30}; display.size_change_callback([](io2d::output_surface& surface){ surface.dimensions(surface.display_dimensions()); }); display.draw_callback([&](io2d::output_surface& surface){ render.Display(surface); }); display.begin_show(); }
/* $Id: seq_id_handle.cpp 557201 2018-02-12 17:27:57Z vasilche $ * =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Aleksey Grichenko, Eugene Vasilchenko * * File Description: * Seq-id handle for Object Manager * */ #include <ncbi_pch.hpp> #include <corelib/ncbiobj.hpp> #include <corelib/ncbimtx.hpp> #include <corelib/ncbiatomic.hpp> #include <objects/seq/seq_id_handle.hpp> #include <objects/seq/seq_id_mapper.hpp> #include <serial/typeinfo.hpp> #include "seq_id_tree.hpp" BEGIN_NCBI_SCOPE BEGIN_SCOPE(objects) ///////////////////////////////////////////////////////////////////////////// // CSeq_id_Info // CSeq_id_Info::CSeq_id_Info(CSeq_id::E_Choice type, CSeq_id_Mapper* mapper) : m_Seq_id_Type(type), m_Mapper(mapper) { _ASSERT(mapper); } CSeq_id_Info::CSeq_id_Info(const CConstRef<CSeq_id>& seq_id, CSeq_id_Mapper* mapper) : m_Seq_id_Type(seq_id->Which()), m_Seq_id(seq_id), m_Mapper(mapper) { _ASSERT(mapper); } CSeq_id_Info::~CSeq_id_Info(void) { _ASSERT(m_LockCounter.Get() == 0); } CSeq_id_Which_Tree& CSeq_id_Info::GetTree(void) const { return GetMapper().x_GetTree(GetType()); } CConstRef<CSeq_id> CSeq_id_Info::GetPackedSeqId(TPacked /*packed*/, TVariant /*variant*/) const { NCBI_THROW(CSeq_id_MapperException, eTypeError, "CSeq_id_Handle is not packed"); } void CSeq_id_Info::x_RemoveLastLock(void) const { GetTree().DropInfo(this); } //////////////////////////////////////////////////////////////////// // // CSeq_id_Handle:: // CSeq_id_Handle CSeq_id_Handle::GetHandle(TGi gi) { return CSeq_id_Mapper::GetInstance()->GetGiHandle(gi); } CSeq_id_Handle CSeq_id_Handle::GetHandle(const CSeq_id& id) { return CSeq_id_Mapper::GetInstance()->GetHandle(id); } CSeq_id_Handle CSeq_id_Handle::GetHandle(const string& str_id) { CSeq_id id(str_id); return CSeq_id_Mapper::GetInstance()->GetHandle(id); } bool CSeq_id_Handle::HaveMatchingHandles(void) const { return GetMapper().HaveMatchingHandles(*this); } bool CSeq_id_Handle::HaveReverseMatch(void) const { return GetMapper().HaveReverseMatch(*this); } bool CSeq_id_Handle::HaveMatchingHandles(EAllowWeakMatch allow_weak_match) const { return GetMapper().HaveMatchingHandles(*this, allow_weak_match); } bool CSeq_id_Handle::HaveReverseMatch(EAllowWeakMatch allow_weak_match) const { return GetMapper().HaveReverseMatch(*this, allow_weak_match); } void CSeq_id_Handle::GetMatchingHandles(TMatches& matches) const { GetMapper().GetMatchingHandles(*this, matches); } void CSeq_id_Handle::GetReverseMatchingHandles(TMatches& matches) const { GetMapper().GetReverseMatchingHandles(*this, matches); } void CSeq_id_Handle::GetMatchingHandles(TMatches& matches, EAllowWeakMatch allow_weak_match) const { GetMapper().GetMatchingHandles(*this, matches, allow_weak_match); } void CSeq_id_Handle::GetReverseMatchingHandles(TMatches& matches, EAllowWeakMatch allow_weak_match) const { GetMapper().GetReverseMatchingHandles(*this, matches, allow_weak_match); } bool CSeq_id_Handle::IsBetter(const CSeq_id_Handle& h) const { return GetMapper().x_IsBetter(*this, h); } bool CSeq_id_Handle::MatchesTo(const CSeq_id_Handle& h) const { return GetMapper().x_Match(*this, h); } bool CSeq_id_Handle::operator==(const CSeq_id& id) const { if ( IsGi() ) { return id.IsGi() && id.GetGi() == TGi(m_Packed); } return *this == GetMapper().GetHandle(id); } int CSeq_id_Handle::CompareOrdered(const CSeq_id_Handle& id) const { // small optimization to avoid creation of temporary CSeq_id objects if ( int diff = Which() - id.Which() ) { return diff; } if ( IsGi() && id.IsGi() ) { if ( GetGi() < id.GetGi() ) { return -1; } else { return GetGi() > id.GetGi(); } } return GetSeqId()->CompareOrdered(*id.GetSeqId()); } string CSeq_id_Handle::AsString() const { CNcbiOstrstream os; if ( IsGi() ) { os << "gi|" << m_Packed; } else if ( m_Info ) { GetSeqId()->WriteAsFasta(os); } else { os << "unknown"; } return CNcbiOstrstreamToString(os); } unsigned CSeq_id_Handle::GetHash(void) const { unsigned hash = INT_ID_TO(unsigned, m_Packed); if ( !hash ) { hash = unsigned((intptr_t)(m_Info.GetPointerOrNull())>>3); } return hash; } string GetDirectLabel(const CSeq_id& id) { string ret; if ( !id.IsGi() ) { if ( id.IsGeneral() ) { const CDbtag& dbtag = id.GetGeneral(); const CObject_id& obj_id = dbtag.GetTag(); if ( obj_id.IsStr() && dbtag.GetDb() == "LABEL" ) { ret = obj_id.GetStr(); } } else { const CTextseq_id* text_id = id.GetTextseq_Id(); if ( text_id && text_id->IsSetAccession() && text_id->IsSetVersion() ) { ret = text_id->GetAccession() + '.' + NStr::IntToString(text_id->GetVersion()); } } } return ret; } string GetDirectLabel(const CSeq_id_Handle& idh) { string ret; if ( !idh.IsGi() ) { ret = GetDirectLabel(*idh.GetSeqId()); } return ret; } string GetLabel(const CSeq_id& id) { string ret; const CTextseq_id* text_id = id.GetTextseq_Id(); if ( text_id ) { if ( text_id->IsSetAccession() ) { ret = text_id->GetAccession(); NStr::ToUpper(ret); } else if ( text_id->IsSetName() ) { ret = text_id->GetName(); } if ( text_id->IsSetVersion() ) { ret += '.'; ret += NStr::IntToString(text_id->GetVersion()); } } else if ( id.IsGeneral() ) { const CDbtag& dbtag = id.GetGeneral(); const CObject_id& obj_id = dbtag.GetTag(); if ( obj_id.IsStr() && dbtag.GetDb() == "LABEL" ) { ret = obj_id.GetStr(); } } if ( ret.empty() ) { ret = id.AsFastaString(); } return ret; } string GetLabel(const CSeq_id_Handle& idh) { string ret; if ( idh.IsGi() ) { ret = idh.AsString(); } else { ret = GetLabel(*idh.GetSeqId()); } return ret; } string GetLabel(const vector<CSeq_id_Handle>& ids) { string ret; CSeq_id_Handle best_id; int best_score = CSeq_id::kMaxScore; #ifdef _DEBUG TGi gi = ZERO_GI; #endif ITERATE ( vector<CSeq_id_Handle>, it, ids ) { CConstRef<CSeq_id> id = it->GetSeqId(); #ifdef _DEBUG if (it->IsGi()) { gi = id->GetGi(); } #endif int score = id->TextScore(); if ( score < best_score ) { best_score = score; best_id = *it; } } if ( best_id ) { ret = GetLabel(best_id); #ifdef _DEBUG if ( gi != ZERO_GI && !best_id.IsGi() ) { CConstRef<CSeq_id> best_seq_id = best_id.GetSeqId(); const CTextseq_id* txt_id = best_seq_id->GetTextseq_Id(); if ( txt_id && txt_id->IsSetAccession() && !txt_id->IsSetVersion() ) { ERR_POST("Using version-less accession " << txt_id->GetAccession() << " instead of GI " << gi); } } #endif } return ret; } string GetLabel(const vector<CRef<CSeq_id> >& ids) { string ret; const CSeq_id* best_id = 0; int best_score = CSeq_id::kMaxScore; #ifdef _DEBUG TGi gi = ZERO_GI; #endif ITERATE ( vector<CRef<CSeq_id> >, it, ids ) { const CSeq_id& id = **it; #ifdef _DEBUG if (id.IsGi()) { gi = id.GetGi(); } #endif int score = id.TextScore(); if ( score < best_score ) { best_score = score; best_id = &id; } } if ( best_id ) { ret = GetLabel(*best_id); #ifdef _DEBUG if ( gi != ZERO_GI && !best_id->IsGi() ) { const CTextseq_id* txt_id = best_id->GetTextseq_Id(); if ( txt_id && !txt_id->IsSetVersion() ) { ERR_POST("Using version-less accession " << txt_id->GetAccession() << " instead of GI " << gi); } } #endif } return ret; } CNcbiOstream& operator<<(CNcbiOstream& out, const CSeq_id_Handle& idh) { if ( idh.IsGi() ) { out << "gi|" << idh.GetPacked(); } else if ( idh ) { idh.GetSeqId()->WriteAsFasta(out); } else { out << "null"; } return out; } END_SCOPE(objects) END_NCBI_SCOPE
/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include <poll.h> #include "cyber/component/timer_component.h" #include "cyber/cyber.h" #include "modules/common/adapters/adapter_gflags.h" #include "modules/common/util/color.h" #include "modules/common/util/message_util.h" #include "modules/map/hdmap/adapter/opendrive_adapter.h" #include "modules/map/hdmap/hdmap_util.h" #include "modules/perception/proto/traffic_light_detection.pb.h" using apollo::common::color::ANSI_GREEN; using apollo::common::color::ANSI_RED; using apollo::common::color::ANSI_RESET; using apollo::common::util::PrintIter; using apollo::hdmap::HDMapUtil; using apollo::hdmap::SignalInfoConstPtr; using apollo::localization::LocalizationEstimate; using apollo::perception::TrafficLight; using apollo::perception::TrafficLightDetection; DEFINE_bool(all_lights, false, "set all lights on the map"); DEFINE_double(traffic_light_distance, 1000.0, "only retrieves traffic lights within this distance"); class ManualTrafficLight final : public apollo::cyber::TimerComponent { public: bool Init() { localization_reader_ = node_->CreateReader<LocalizationEstimate>( FLAGS_localization_topic, [this](const std::shared_ptr<LocalizationEstimate> &localization) { ADEBUG << "Received chassis data: run chassis callback."; OnLocalization(localization); }); traffic_light_detection_writer_ = node_->CreateWriter<TrafficLightDetection>( FLAGS_traffic_light_detection_topic); return true; } bool Proc() { std::vector<SignalInfoConstPtr> signals; bool result = false; if (FLAGS_all_lights) { result = GetAllTrafficLights(&signals); } else { result = GetTrafficLightsWithinDistance(&signals); } if (!result) { ADEBUG << "Failed to get traffic signals from current location on map"; } else { ADEBUG << "Received " << signals.size() << " traffic lights"; } std::vector<std::string> signal_ids; for (const auto &ptr : signals) { signal_ids.emplace_back(ptr->id().id()); } if (IsDifferent(prev_traffic_lights_, signal_ids)) { prev_traffic_lights_ = std::unordered_set<std::string>(signal_ids.begin(), signal_ids.end()); updated_ = true; } TrafficLightDetection traffic_light_detection; TrafficLight::Color color = GetKeyBoardColorInput(); ADEBUG << "Color: " << TrafficLight::Color_Name(color); if (updated_) { updated_ = false; const char *print_color = is_green_ ? ANSI_GREEN : ANSI_RED; std::cout << print_color << "Current Light: " << (is_green_ ? "GREEN" : "RED"); if (signal_ids.empty()) { if (FLAGS_all_lights) { std::cout << " No lights in the map"; } else { std::cout << " No lights in the next " << FLAGS_traffic_light_distance << " meters"; } } else { if (signal_ids.size() < 5) { std::cout << " IDs: " << PrintIter(signal_ids.begin(), signal_ids.end()); } else { std::cout << " IDs: " << PrintIter(signal_ids.begin(), signal_ids.begin() + 4) << " ..."; } } std::cout << std::endl << ANSI_RESET << "Press 'c' to change" << std::endl << std::endl; } CreateTrafficLightDetection(signals, color, &traffic_light_detection); traffic_light_detection_writer_->Write(traffic_light_detection); return true; } private: bool GetAllTrafficLights(std::vector<SignalInfoConstPtr> *traffic_lights) { static auto map_filename = apollo::hdmap::BaseMapFile(); static apollo::hdmap::Map map_proto; static std::vector<SignalInfoConstPtr> map_traffic_lights; if (map_proto.lane().empty() && map_traffic_lights.empty()) { AERROR << "signal size: " << map_proto.signal_size(); if (apollo::common::util::EndWith(map_filename, ".xml")) { if (!apollo::hdmap::adapter::OpendriveAdapter::LoadData(map_filename, &map_proto)) { return false; } } else if (!apollo::cyber::common::GetProtoFromFile(map_filename, &map_proto)) { return false; } for (const auto &signal : map_proto.signal()) { const auto *hdmap = HDMapUtil::BaseMapPtr(); if (!hdmap) { AERROR << "Invalid HD Map."; return false; } map_traffic_lights.push_back(hdmap->GetSignalById(signal.id())); } } *traffic_lights = map_traffic_lights; return true; } bool GetTrafficLightsWithinDistance( std::vector<SignalInfoConstPtr> *traffic_lights) { CHECK_NOTNULL(traffic_lights); if (!has_localization_) { AERROR << "No localization received"; return false; } const auto *hdmap = HDMapUtil::BaseMapPtr(); if (!hdmap) { AERROR << "Invalid HD Map."; return false; } auto position = localization_.pose().position(); int ret = hdmap->GetForwardNearestSignalsOnLane( position, FLAGS_traffic_light_distance, traffic_lights); if (ret != 0) { AERROR << "failed to get signals from position: " << position.ShortDebugString() << " with distance: " << FLAGS_traffic_light_distance << " on map"; return false; } return true; } bool CreateTrafficLightDetection( const std::vector<SignalInfoConstPtr> &signals, TrafficLight::Color color, TrafficLightDetection *detection) { CHECK_NOTNULL(detection); for (const auto &iter : signals) { auto *light = detection->add_traffic_light(); light->set_color(color); light->set_confidence(1.0); light->set_tracking_time(1.0); light->set_id(iter->id().id()); } apollo::common::util::FillHeader("manual_traffic_light", detection); return true; } TrafficLight::Color GetKeyBoardColorInput() { int8_t revent = 0; // short struct pollfd fd = {STDIN_FILENO, POLLIN, revent}; switch (poll(&fd, 1, 100)) { case -1: AERROR << "Failed to read keybapoard"; break; case 0: break; default: char ch = 'x'; std::cin >> ch; if (ch == 'c') { is_green_ = !is_green_; updated_ = true; } break; } if (is_green_) { return TrafficLight::GREEN; } else { return TrafficLight::RED; } } bool IsDifferent(const std::unordered_set<std::string> &str_set, const std::vector<std::string> &str_vec) { if (str_vec.size() != str_set.size()) { return true; } for (const auto &ss : str_vec) { if (str_set.count(ss) == 0) { return true; } } return false; } void OnLocalization( const std::shared_ptr<LocalizationEstimate> &localization) { localization_ = *localization; has_localization_ = true; } private: bool is_green_ = false; bool updated_ = true; bool has_localization_ = false; LocalizationEstimate localization_; std::unordered_set<std::string> prev_traffic_lights_; std::shared_ptr<apollo::cyber::Writer<TrafficLightDetection>> traffic_light_detection_writer_ = nullptr; std::shared_ptr<apollo::cyber::Reader<LocalizationEstimate>> localization_reader_ = nullptr; }; CYBER_REGISTER_COMPONENT(ManualTrafficLight);
/*++ Copyright (c) 1998-1999 Microsoft Corporation Module Name: path.cxx Abstract: This file contains the PathCracker Functionality Environment: User mode Revision History: 12/07/98 -felixw- Created it --*/ #include "oleds.hxx" #pragma hdrstop DEFINE_IDispatch_Implementation(CPathname) CPathname::CPathname(): _pDispMgr(NULL), m_pPathnameProvider(NULL), _fNamingAttribute(TRUE), _dwEscaped(ADS_ESCAPEDMODE_DEFAULT) /*++ Routine Description: Constructor for CPathname Arguments: Return Value: None --*/ { ENLIST_TRACKING(CPathname); memset(&_PathObjectInfo, 0x0, sizeof(PATH_OBJECTINFO)); _PathObjectInfo.dwPathType = ADS_PATHTYPE_ROOTFIRST; } HRESULT CPathname::CreatePathname( REFIID riid, void **ppvObj ) /*++ Routine Description: Create the pathname object Arguments: riid - IID to query for ppvObj - object to be returned Return Value: S_OK on success, error code otherwise --*/ { CPathname * pPathname = NULL; HRESULT hr = S_OK; hr = AllocatePathnameObject(&pPathname); BAIL_ON_FAILURE(hr); hr = pPathname->QueryInterface(riid, ppvObj); BAIL_ON_FAILURE(hr); pPathname->Release(); RRETURN(hr); error: delete pPathname; RRETURN(hr); } CPathname::~CPathname( ) /*++ Routine Description: Destructor for Pathname object Arguments: Return Value: None --*/ { FreePathInfo(&_PathObjectInfo); delete _pDispMgr; if (m_pPathnameProvider) { m_pPathnameProvider->Release(); } } STDMETHODIMP CPathname::QueryInterface( REFIID iid, LPVOID FAR* ppv ) { if (ppv == NULL) { RRETURN(E_POINTER); } if (IsEqualIID(iid, IID_IUnknown)) { *ppv = (IADsPathname *) this; } else if (IsEqualIID(iid, IID_IADsPathname)) { *ppv = (IADsPathname *) this; } else if (IsEqualIID(iid, IID_IDispatch)) { *ppv = (IADsPathname *) this; } else if (IsEqualIID(iid, IID_ISupportErrorInfo)) { *ppv = (ISupportErrorInfo *) this; } else { *ppv = NULL; return E_NOINTERFACE; } AddRef(); return NOERROR; } HRESULT CPathname::AllocatePathnameObject( CPathname ** ppPathname ) /*++ Routine Description: Allocate a pathname object Arguments: ppPathname - constructed object Return Value: S_OK on success, error code otherwise. --*/ { CPathname * pPathname = NULL; CDispatchMgr * pDispMgr = NULL; HRESULT hr = S_OK; pPathname = new CPathname(); if (pPathname == NULL) { hr = E_OUTOFMEMORY; } BAIL_ON_FAILURE(hr); pDispMgr = new CDispatchMgr; if (pDispMgr == NULL) { hr = E_OUTOFMEMORY; } BAIL_ON_FAILURE(hr); hr = LoadTypeInfoEntry( pDispMgr, LIBID_ADs, IID_IADsPathname, (IADsPathname *)pPathname, DISPID_REGULAR ); BAIL_ON_FAILURE(hr); pPathname->_pDispMgr = pDispMgr; // // By default, the pathname is set to the LDAP provider // hr = ADsGetObject(L"LDAP:", IID_IADsPathnameProvider, (void**)&(pPathname->m_pPathnameProvider)); BAIL_ON_FAILURE(hr); pPathname->_PathObjectInfo.ProviderName = AllocADsStr(L"LDAP"); if (pPathname->_PathObjectInfo.ProviderName == NULL) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } *ppPathname = pPathname; RRETURN(hr); error: // so we will not try to delete it in the destructor if (pPathname) pPathname->_pDispMgr = NULL; delete pPathname; delete pDispMgr; RRETURN_EXP_IF_ERR(hr); } HRESULT CPathname::InterfaceSupportsErrorInfo( THIS_ REFIID riid ) { if (IsEqualIID(riid, IID_IADsPathname)) { RRETURN(S_OK); } else { RRETURN(S_FALSE); } } HRESULT CPathname::SetAll( BSTR bstrADsPath ) /*++ Routine Description: Set the internal variables using the full ADSPath Arguments: bstrADsPath - the passed in Full ADSPath Return Value: S_OK on success, error code otherwise. --*/ { HRESULT hr = S_OK; // // Freeing existing info // FreePathInfo(&_PathObjectInfo); // // Collecting new info // hr = m_pPathnameProvider->ParsePath( bstrADsPath, ADS_PARSE_FULL, &_PathObjectInfo); BAIL_ON_FAILURE(hr); RRETURN(hr); error: FreePathInfo(&_PathObjectInfo); RRETURN(hr); } HRESULT CPathname::GetNamespace( BSTR bstrADsPath, PWSTR *ppszName ) /*++ Routine Description: Get a namespace from a full ADsPath Arguments: bstrADsPath - passed in ADsPath ppszName - returned namespace, must be freed by caller Return Value: S_OK on success, E_ADS_BAD_PATHNAME if the path is bad, error code otherwise. --*/ { DWORD dwPath = 0; // Length of namespace BOOLEAN fFound = FALSE; PWSTR szPath = bstrADsPath; HRESULT hr = S_OK; while (*szPath) { if (*szPath == ':') { dwPath++; fFound = TRUE; break; } szPath++; dwPath++; } if (fFound) { *ppszName = (LPWSTR)AllocADsMem(sizeof(WCHAR) * (dwPath + 1)); if (*ppszName == NULL) { hr = E_OUTOFMEMORY; goto error; } memcpy(*ppszName, bstrADsPath, (dwPath * sizeof(WCHAR))); (*ppszName)[dwPath] = '\0'; } else { hr = E_ADS_BAD_PATHNAME; } error: return hr; } STDMETHODIMP CPathname::Set( BSTR bstrADsPath, long dwSetType ) /*++ Routine Description: Set the path with the type specified Arguments: bstrADsPath - the path to be set dwSetType - the type : ADS_SETTYPE_FULL ADS_SETTYPE_PROVIDER ADS_SETTYPE_SERVER ADS_SETTYPE_DN Return Value: S_OK on success, error code otherwise. --*/ { HRESULT hr = E_FAIL; LPWSTR szPath = NULL; WCHAR* pszNamespace = NULL; LPWSTR pszName = NULL; IADsPathnameProvider *pPathnameProvider = NULL; switch (dwSetType) { case ADS_SETTYPE_FULL: if ((bstrADsPath == NULL) || ((*bstrADsPath) == NULL)) { hr = E_INVALIDARG; goto error; } hr = GetNamespace(bstrADsPath, &pszName); BAIL_ON_FAILURE(hr); if ((_PathObjectInfo.ProviderName == NULL) || (wcscmp(_PathObjectInfo.ProviderName, bstrADsPath) != 0)) { // // If provider not set, or if the provider is different // we reset the provider // pPathnameProvider = NULL; hr = ADsGetObject(pszName, IID_IADsPathnameProvider, (void**)&(pPathnameProvider)); BAIL_ON_FAILURE(hr); if (pPathnameProvider) { if (m_pPathnameProvider) { m_pPathnameProvider->Release(); } m_pPathnameProvider = pPathnameProvider; } } hr = SetAll(bstrADsPath); break; case ADS_SETTYPE_PROVIDER: if ((bstrADsPath == NULL) || ((*bstrADsPath) == NULL)) { hr = E_INVALIDARG; goto error; } // // If it is the same as the namespace that is stored inside already, // ignore it // if (_PathObjectInfo.ProviderName && (wcscmp(_PathObjectInfo.ProviderName, bstrADsPath) == 0)) { hr = S_OK; break; } pszNamespace = new WCHAR[wcslen(bstrADsPath) + 2]; // ":" and \0 if(!pszNamespace) { hr = E_OUTOFMEMORY; goto error; } wcscpy(pszNamespace,bstrADsPath); wcscat(pszNamespace,L":"); pPathnameProvider = NULL; hr = ADsGetObject(pszNamespace, IID_IADsPathnameProvider, (void**)&(pPathnameProvider)); BAIL_ON_FAILURE(hr); if (pPathnameProvider) { if (m_pPathnameProvider) { m_pPathnameProvider->Release(); } m_pPathnameProvider = pPathnameProvider; } FreePathInfo(&_PathObjectInfo); _PathObjectInfo.ProviderName = AllocADsStr(bstrADsPath); if (_PathObjectInfo.ProviderName == NULL) { hr = E_OUTOFMEMORY; break; } hr = S_OK; break; case ADS_SETTYPE_SERVER: if (m_pPathnameProvider == NULL) { hr = E_ADS_BAD_PATHNAME; goto error; } if (_PathObjectInfo.ServerName) { FreeADsStr( _PathObjectInfo.ServerName); _PathObjectInfo.ServerName = NULL; } if (_PathObjectInfo.DisplayServerName) { FreeADsStr( _PathObjectInfo.DisplayServerName); _PathObjectInfo.DisplayServerName = NULL; } // // If the input path is not NULL, we'll set it to the new one. Or // else we will just ignore it 'cause it has been set to 0 earlier // if (bstrADsPath && (*bstrADsPath)) { _PathObjectInfo.ServerName = AllocADsStr(bstrADsPath); if (_PathObjectInfo.ServerName == NULL) { hr = E_OUTOFMEMORY; break; } _PathObjectInfo.DisplayServerName = AllocADsStr(bstrADsPath); if (_PathObjectInfo.DisplayServerName == NULL) { hr = E_OUTOFMEMORY; break; } } hr = S_OK; break; case ADS_SETTYPE_DN: { if (m_pPathnameProvider == NULL) { hr = E_ADS_BAD_PATHNAME; goto error; } // // Free the existing ones first // FreeObjInfoComponents(&_PathObjectInfo); _PathObjectInfo.dwPathType = 0; // // If the input path is not NULL, we'll set it to the new one. // Or else we will just ignore it 'cause it has been set to 0 // earlier // if (bstrADsPath && (*bstrADsPath)) { hr = m_pPathnameProvider->ParsePath( bstrADsPath, ADS_PARSE_DN, &_PathObjectInfo); BAIL_ON_FAILURE(hr); } break; } default: hr = E_INVALIDARG; break; } error: if (pszName) { FreeADsStr(pszName); } if(pszNamespace) { delete [] pszNamespace; pszNamespace = NULL; } RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CPathname::SetDisplayType( long lnSetType ) /*++ Routine Description: Set the Display type of the Pathname object. It can either display the whole string cn=xxx or just the value xxx. Arguments: lnSetType - the passed in set type ADS_DISPLAY_FULL=1, ADS_DISPLAY_VALUE_ONLY=2 Return Value: S_OK on success, error code otherwise. --*/ { if (lnSetType == ADS_DISPLAY_FULL) { _fNamingAttribute = TRUE; RRETURN (S_OK); } else if (lnSetType == ADS_DISPLAY_VALUE_ONLY) { _fNamingAttribute = FALSE; RRETURN (S_OK); } RRETURN(E_INVALIDARG); } HRESULT CPathname::SetComponent( DWORD cComponents, BSTR *pbstrElement ) /*++ Routine Description: Set an individual component in the pathname. For internal use only. Not exposed. Arguments: cComponents - the component number to be set pbstrElement - the return value Return Value: S_OK on success, error code otherwise. --*/ { HRESULT hr = S_OK; PWSTR szReturn = NULL; PATH_COMPONENT* pComponent = NULL; DWORD dwLength = 2; // for null termination and the equal sign if (_dwEscaped == ADS_ESCAPEDMODE_OFF_EX) { pComponent = _PathObjectInfo.ProvSpecComponentArray; if (pComponent[cComponents].szValue == NULL) { pComponent = _PathObjectInfo.ComponentArray; } } else if (_dwEscaped == ADS_ESCAPEDMODE_ON) { pComponent = _PathObjectInfo.DisplayComponentArray; } // // Either default or OFF, we do not turn on escaping // else { pComponent = _PathObjectInfo.ComponentArray; } // // allocate space for szReturn // if (pComponent[cComponents].szValue) { dwLength += wcslen(pComponent[cComponents].szValue); } if (pComponent[cComponents].szComponent) { dwLength += wcslen(pComponent[cComponents].szComponent); } szReturn = (PWSTR)AllocADsMem(sizeof(WCHAR) * dwLength); if (szReturn == NULL) { hr = E_OUTOFMEMORY; goto error; } szReturn[0] = NULL; if (_fNamingAttribute) { wcscat(szReturn, pComponent[cComponents].szComponent); if (pComponent[cComponents].szValue) { wcscat(szReturn, TEXT("=")); wcscat(szReturn, pComponent[cComponents].szValue); } } else { if (pComponent[cComponents].szValue) { // // If value exist, only show display value // wcscat(szReturn, pComponent[cComponents].szValue); } else { // // else value is only stored in Component // wcscat(szReturn, pComponent[cComponents].szComponent); } } hr = ADsAllocString(szReturn, pbstrElement); error: if (szReturn) { FreeADsMem(szReturn); } return hr; } STDMETHODIMP CPathname::Retrieve( THIS_ long dwFormatType, BSTR *pbstrADsPath ) /*++ Routine Description: Retrive the pathname as different formats Arguments: dwFormatType - the input format type pbstrADsPath - the returned path Return Value: S_OK on success, error code otherwise. --*/ { HRESULT hr = S_OK; if (!pbstrADsPath) { hr = E_INVALIDARG; goto error; } if (m_pPathnameProvider == NULL) { hr = E_ADS_BAD_PATHNAME; goto error; } switch (dwFormatType) { case ADS_FORMAT_SERVER: if (!_PathObjectInfo.DisplayServerName) { hr = E_ADS_BAD_PATHNAME; goto error; } hr = ADsAllocString(_PathObjectInfo.DisplayServerName, pbstrADsPath); break; case ADS_FORMAT_PROVIDER: if (!_PathObjectInfo.ProviderName) { hr = E_ADS_BAD_PATHNAME; goto error; } hr = ADsAllocString(_PathObjectInfo.ProviderName, pbstrADsPath); break; default: // DWORD dwFlag = 0; if (_fNamingAttribute) dwFlag |= ADS_CONSTRUCT_NAMINGATTRIBUTE; hr = m_pPathnameProvider->ConstructPath(&_PathObjectInfo, dwFormatType, dwFlag, _dwEscaped, pbstrADsPath); BAIL_ON_FAILURE(hr); } error: RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CPathname::GetNumElements( THIS_ long *pdwNumPathElements ) /*++ Routine Description: Get the number of elements in the DN Arguments: pdwNumPathElements - the number of elements Return Value: S_OK on success, error code otherwise. --*/ { HRESULT hr = S_OK; if (m_pPathnameProvider == NULL) { hr = E_ADS_BAD_PATHNAME; goto error; } if (!pdwNumPathElements) { hr = E_INVALIDARG; goto error; } *pdwNumPathElements = _PathObjectInfo.NumComponents; error: RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CPathname::GetElement( THIS_ long dwElementIndex, BSTR *pbstrElement ) /*++ Routine Description: Get a particular element using an index Arguments: Return Value: S_OK on success, error code otherwise. --*/ { HRESULT hr = E_FAIL; if (m_pPathnameProvider == NULL) { hr = E_ADS_BAD_PATHNAME; goto error; } if (!pbstrElement) { hr = E_INVALIDARG; goto error; } if ((DWORD)dwElementIndex >= _PathObjectInfo.NumComponents) { hr = HRESULT_FROM_WIN32(ERROR_INVALID_INDEX); goto error; } if (_PathObjectInfo.dwPathType != ADS_PATHTYPE_LEAFFIRST) { dwElementIndex = _PathObjectInfo.NumComponents - 1 - dwElementIndex; } hr = SetComponent(dwElementIndex, pbstrElement); error: RRETURN_EXP_IF_ERR(hr); } VOID MoveLastComponentToFront( PPATH_OBJECTINFO pObjectInfo ) /*++ Routine Description: Move the last component to the front. Used after adding leaf Arguments: Return Value: S_OK on success, error code otherwise. --*/ { DWORD cComponent; ADsAssert(pObjectInfo->NumComponents > 1); LPTSTR szComponentLast = pObjectInfo->ComponentArray[pObjectInfo->NumComponents-1].szComponent; LPTSTR szValueLast = pObjectInfo->ComponentArray[pObjectInfo->NumComponents-1].szValue; LPTSTR szDisplayComponentLast = pObjectInfo->DisplayComponentArray[pObjectInfo->NumComponents-1].szComponent; LPTSTR szDisplayValueLast = pObjectInfo->DisplayComponentArray[pObjectInfo->NumComponents-1].szValue; LPTSTR szProvSpecComponentLast = pObjectInfo->ProvSpecComponentArray[pObjectInfo->NumComponents-1].szComponent; LPTSTR szProvSpecValueLast = pObjectInfo->ProvSpecComponentArray[pObjectInfo->NumComponents-1].szValue; for (cComponent=pObjectInfo->NumComponents-1;cComponent>=1;cComponent--) { pObjectInfo->ComponentArray[cComponent].szComponent = pObjectInfo->ComponentArray[cComponent-1].szComponent; pObjectInfo->ComponentArray[cComponent].szValue = pObjectInfo->ComponentArray[cComponent-1].szValue; pObjectInfo->DisplayComponentArray[cComponent].szComponent = pObjectInfo->DisplayComponentArray[cComponent-1].szComponent; pObjectInfo->DisplayComponentArray[cComponent].szValue = pObjectInfo->DisplayComponentArray[cComponent-1].szValue; pObjectInfo->ProvSpecComponentArray[cComponent].szComponent = pObjectInfo->ProvSpecComponentArray[cComponent-1].szComponent; pObjectInfo->ProvSpecComponentArray[cComponent].szValue = pObjectInfo->ProvSpecComponentArray[cComponent-1].szValue; } pObjectInfo->ComponentArray[0].szComponent = szComponentLast; pObjectInfo->ComponentArray[0].szValue = szValueLast; pObjectInfo->DisplayComponentArray[0].szComponent = szDisplayComponentLast; pObjectInfo->DisplayComponentArray[0].szValue = szDisplayValueLast; pObjectInfo->ProvSpecComponentArray[0].szComponent = szProvSpecComponentLast; pObjectInfo->ProvSpecComponentArray[0].szValue = szProvSpecValueLast; return; } HRESULT RemoveFirstElement( PPATH_OBJECTINFO pObjectInfo ) /*++ Routine Description: Remove first element from the list Arguments: Return Value: S_OK on success, error code otherwise. --*/ { DWORD cComponent; if (pObjectInfo->NumComponents <= 0) { RRETURN(E_ADS_BAD_PATHNAME); } FreeADsStr(pObjectInfo->ComponentArray[0].szComponent); FreeADsStr(pObjectInfo->ComponentArray[0].szValue); FreeADsStr(pObjectInfo->DisplayComponentArray[0].szComponent); FreeADsStr(pObjectInfo->DisplayComponentArray[0].szValue); if (pObjectInfo->ProvSpecComponentArray[0].szComponent) FreeADsStr(pObjectInfo->ProvSpecComponentArray[0].szComponent); if (pObjectInfo->ProvSpecComponentArray[0].szValue) FreeADsStr(pObjectInfo->ProvSpecComponentArray[0].szValue); for (cComponent = 0;cComponent < pObjectInfo->NumComponents - 1;cComponent++) { pObjectInfo->ComponentArray[cComponent].szComponent = pObjectInfo->ComponentArray[cComponent+1].szComponent; pObjectInfo->ComponentArray[cComponent].szValue = pObjectInfo->ComponentArray[cComponent+1].szValue; pObjectInfo->DisplayComponentArray[cComponent].szComponent = pObjectInfo->DisplayComponentArray[cComponent+1].szComponent; pObjectInfo->DisplayComponentArray[cComponent].szValue = pObjectInfo->DisplayComponentArray[cComponent+1].szValue; pObjectInfo->ProvSpecComponentArray[cComponent].szComponent = pObjectInfo->ProvSpecComponentArray[cComponent+1].szComponent; pObjectInfo->ProvSpecComponentArray[cComponent].szValue = pObjectInfo->ProvSpecComponentArray[cComponent+1].szValue; } pObjectInfo->ComponentArray[cComponent].szComponent = NULL; pObjectInfo->ComponentArray[cComponent].szValue = NULL; pObjectInfo->DisplayComponentArray[cComponent].szComponent = NULL; pObjectInfo->DisplayComponentArray[cComponent].szValue = NULL; pObjectInfo->ProvSpecComponentArray[cComponent].szComponent = NULL; pObjectInfo->ProvSpecComponentArray[cComponent].szValue = NULL; pObjectInfo->NumComponents--; RRETURN(S_OK); } STDMETHODIMP CPathname::AddLeafElement( THIS_ BSTR bstrLeafElement ) /*++ Routine Description: Add a leaf element to the DN Arguments: Return Value: S_OK on success, error code otherwise. --*/ { HRESULT hr = E_FAIL; DWORD NumComponents; BOOL fStartAllocation = FALSE; PATH_OBJECTINFO ObjectInfoLocal; memset(&ObjectInfoLocal, 0, sizeof(PATH_OBJECTINFO)); if ((bstrLeafElement == NULL) || ((*bstrLeafElement) == NULL)) { hr = E_INVALIDARG; goto error; } if (m_pPathnameProvider == NULL) { hr = E_ADS_BAD_PATHNAME; goto error; } // // MAX size limitation exist in parser.cxx, so, it's not // worth to implement the inc in size dynamically // if ((_PathObjectInfo.NumComponents+1) > MAXCOMPONENTS ) { hr = E_NOTIMPL; goto error; } hr = m_pPathnameProvider->ParsePath( bstrLeafElement, ADS_PARSE_COMPONENT, (PPATH_OBJECTINFO)&ObjectInfoLocal ); BAIL_ON_FAILURE(hr); NumComponents = _PathObjectInfo.NumComponents; fStartAllocation = TRUE; if (ObjectInfoLocal.ComponentArray[0].szComponent) { _PathObjectInfo.ComponentArray[NumComponents].szComponent = AllocADsStr(ObjectInfoLocal.ComponentArray[0].szComponent); if (_PathObjectInfo.ComponentArray[NumComponents].szComponent == NULL) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } } if (ObjectInfoLocal.ComponentArray[0].szValue) { _PathObjectInfo.ComponentArray[NumComponents].szValue = AllocADsStr(ObjectInfoLocal.ComponentArray[0].szValue); if (_PathObjectInfo.ComponentArray[NumComponents].szValue== NULL) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } } if (ObjectInfoLocal.DisplayComponentArray[0].szComponent) { _PathObjectInfo.DisplayComponentArray[NumComponents].szComponent = AllocADsStr(ObjectInfoLocal.DisplayComponentArray[0].szComponent); if (_PathObjectInfo.DisplayComponentArray[NumComponents].szComponent == NULL) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } } if (ObjectInfoLocal.DisplayComponentArray[0].szValue) { _PathObjectInfo.DisplayComponentArray[NumComponents].szValue= AllocADsStr(ObjectInfoLocal.DisplayComponentArray[0].szValue); if (_PathObjectInfo.DisplayComponentArray[NumComponents].szValue== NULL) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } } if (ObjectInfoLocal.ProvSpecComponentArray[0].szComponent) { _PathObjectInfo.ProvSpecComponentArray[NumComponents].szComponent = AllocADsStr(ObjectInfoLocal.ProvSpecComponentArray[0].szComponent); if (_PathObjectInfo.ProvSpecComponentArray[NumComponents].szComponent == NULL) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } } if (ObjectInfoLocal.ProvSpecComponentArray[0].szValue) { _PathObjectInfo.ProvSpecComponentArray[NumComponents].szValue = AllocADsStr(ObjectInfoLocal.ProvSpecComponentArray[0].szValue); if (_PathObjectInfo.ProvSpecComponentArray[NumComponents].szValue== NULL) { hr = E_OUTOFMEMORY; BAIL_ON_FAILURE(hr); } } _PathObjectInfo.NumComponents++; if (_PathObjectInfo.dwPathType == ADS_PATHTYPE_LEAFFIRST) { MoveLastComponentToFront(&_PathObjectInfo); } FreePathInfo(&ObjectInfoLocal); RRETURN(hr); error: FreePathInfo(&ObjectInfoLocal); if (fStartAllocation) { if (_PathObjectInfo.ComponentArray[NumComponents].szComponent) { FreeADsStr(_PathObjectInfo.ComponentArray[NumComponents].szComponent); _PathObjectInfo.ComponentArray[NumComponents].szComponent = NULL; } if (_PathObjectInfo.ComponentArray[NumComponents].szValue) { FreeADsStr(_PathObjectInfo.ComponentArray[NumComponents].szValue); _PathObjectInfo.ComponentArray[NumComponents].szValue = NULL; } if (_PathObjectInfo.DisplayComponentArray[NumComponents].szComponent) { FreeADsStr(_PathObjectInfo.DisplayComponentArray[NumComponents].szComponent); _PathObjectInfo.DisplayComponentArray[NumComponents].szComponent = NULL; } if (_PathObjectInfo.DisplayComponentArray[NumComponents].szValue) { FreeADsStr(_PathObjectInfo.DisplayComponentArray[NumComponents].szValue); _PathObjectInfo.DisplayComponentArray[NumComponents].szValue = NULL; } if (_PathObjectInfo.ProvSpecComponentArray[NumComponents].szComponent) { FreeADsStr(_PathObjectInfo.ProvSpecComponentArray[NumComponents].szComponent); _PathObjectInfo.ProvSpecComponentArray[NumComponents].szComponent = NULL; } if (_PathObjectInfo.ProvSpecComponentArray[NumComponents].szValue) { FreeADsStr(_PathObjectInfo.ProvSpecComponentArray[NumComponents].szValue); _PathObjectInfo.ProvSpecComponentArray[NumComponents].szValue = NULL; } } RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CPathname::RemoveLeafElement(void) /*++ Routine Description: Remove the leaf element from the DN Arguments: Return Value: S_OK on success, error code otherwise. --*/ { HRESULT hr = E_FAIL; DWORD NumComponents; if (m_pPathnameProvider == NULL) { hr = E_ADS_BAD_PATHNAME; goto error; } if (_PathObjectInfo.dwPathType == ADS_PATHTYPE_LEAFFIRST) { hr = RemoveFirstElement(&_PathObjectInfo); } else { if (_PathObjectInfo.NumComponents > 0) { _PathObjectInfo.NumComponents--; NumComponents = _PathObjectInfo.NumComponents; FreeADsStr(_PathObjectInfo.ComponentArray[NumComponents].szComponent); FreeADsStr(_PathObjectInfo.ComponentArray[NumComponents].szValue); FreeADsStr(_PathObjectInfo.DisplayComponentArray[NumComponents].szComponent); FreeADsStr(_PathObjectInfo.DisplayComponentArray[NumComponents].szValue); if (_PathObjectInfo.ProvSpecComponentArray[NumComponents].szComponent) FreeADsStr(_PathObjectInfo.ProvSpecComponentArray[NumComponents].szComponent); if (_PathObjectInfo.ProvSpecComponentArray[NumComponents].szValue) FreeADsStr(_PathObjectInfo.ProvSpecComponentArray[NumComponents].szValue); _PathObjectInfo.ComponentArray[NumComponents].szComponent = NULL; _PathObjectInfo.ComponentArray[NumComponents].szValue = NULL; _PathObjectInfo.DisplayComponentArray[NumComponents].szComponent = NULL; _PathObjectInfo.DisplayComponentArray[NumComponents].szValue = NULL; _PathObjectInfo.ProvSpecComponentArray[NumComponents].szComponent = NULL; _PathObjectInfo.ProvSpecComponentArray[NumComponents].szValue = NULL; hr = S_OK; } } error: RRETURN_EXP_IF_ERR(hr); } STDMETHODIMP CPathname::CopyPath(THIS_ IDispatch **ppAdsPath) /*++ Routine Description: Copy the pathname object and return a pointer to the new one Arguments: Return Value: S_OK on success, error code otherwise. --*/ { HRESULT hr = E_FAIL; IADsPathname *pPathname = NULL; BSTR bstrResult = NULL; DWORD dwLength; long lNameType; // Storage for old values DWORD dwEscaped; BOOL fValueChanged = FALSE; // indicate whether value has been changed if (m_pPathnameProvider == NULL) { hr = E_ADS_BAD_PATHNAME; goto error; } if (!ppAdsPath) { hr = E_INVALIDARG; goto error; } // // Storing the old values // dwEscaped = _dwEscaped; if (_fNamingAttribute) { lNameType = ADS_DISPLAY_FULL; } else { lNameType = ADS_DISPLAY_VALUE_ONLY; } // // Setting the type to 'show all' for retrieval // fValueChanged = TRUE; hr = SetDisplayType(ADS_DISPLAY_FULL); BAIL_ON_FAILURE(hr); hr = put_EscapedMode(ADS_ESCAPEDMODE_DEFAULT); BAIL_ON_FAILURE(hr); // // Retrieve path // hr = Retrieve(ADS_FORMAT_WINDOWS, &bstrResult); BAIL_ON_FAILURE(hr); // // This is a workaround for the namespace path that we return. We are // currently getting 'LDAP://' back instead of 'LDAP:'. There are users who // are dependent on this and thus we cannot change it to return 'LDAP://'. // The code below takes out the '//' if the path trails with '://' so that // the path is settable. // dwLength = wcslen(bstrResult); if (wcscmp((PWSTR)(&bstrResult[dwLength-3]),L"://") == 0) { bstrResult[dwLength-2] = NULL; } hr = CoCreateInstance( CLSID_Pathname, NULL, CLSCTX_ALL, IID_IADsPathname, (void**)&pPathname ); BAIL_ON_FAILURE(hr); hr = pPathname->Set(bstrResult, ADS_SETTYPE_FULL); BAIL_ON_FAILURE(hr); hr = pPathname->SetDisplayType(lNameType); BAIL_ON_FAILURE(hr); hr = pPathname->put_EscapedMode(dwEscaped); BAIL_ON_FAILURE(hr); *ppAdsPath = (IDispatch*)pPathname; pPathname = NULL; error: if (fValueChanged) { SetDisplayType(lNameType); put_EscapedMode(dwEscaped); } if (pPathname) { pPathname->Release(); } if (bstrResult) { SysFreeString(bstrResult); } RRETURN_EXP_IF_ERR(hr); } void CPathname::FreeObjInfoComponents( PATH_OBJECTINFO *pObjectInfo ) /*++ Routine Description: Free all the compoents in an objinfo Arguments: Return Value: S_OK on success, error code otherwise. --*/ { DWORD NumComponents; while (pObjectInfo->NumComponents > 0) { pObjectInfo->NumComponents--; NumComponents = pObjectInfo->NumComponents; if (pObjectInfo->ComponentArray[NumComponents].szComponent) { FreeADsStr( pObjectInfo->ComponentArray[NumComponents].szComponent); pObjectInfo->ComponentArray[NumComponents].szComponent = NULL; } if (pObjectInfo->ComponentArray[NumComponents].szValue) { FreeADsStr( pObjectInfo->ComponentArray[NumComponents].szValue); pObjectInfo->ComponentArray[NumComponents].szValue = NULL; } if (pObjectInfo->DisplayComponentArray[NumComponents].szComponent) { FreeADsStr( pObjectInfo->DisplayComponentArray[NumComponents].szComponent); pObjectInfo->DisplayComponentArray[NumComponents].szComponent = NULL; } if (pObjectInfo->DisplayComponentArray[NumComponents].szValue) { FreeADsStr( pObjectInfo->DisplayComponentArray[NumComponents].szValue); pObjectInfo->DisplayComponentArray[NumComponents].szValue = NULL; } if (pObjectInfo->ProvSpecComponentArray[NumComponents].szComponent) { FreeADsStr( pObjectInfo->ProvSpecComponentArray[NumComponents].szComponent); pObjectInfo->ProvSpecComponentArray[NumComponents].szComponent = NULL; } if (pObjectInfo->ProvSpecComponentArray[NumComponents].szValue) { FreeADsStr( pObjectInfo->ProvSpecComponentArray[NumComponents].szValue); pObjectInfo->ProvSpecComponentArray[NumComponents].szValue = NULL; } } } void CPathname::FreePathInfo( PPATH_OBJECTINFO pPathObjectInfo ) { if (pPathObjectInfo->ProviderName) { FreeADsStr(pPathObjectInfo->ProviderName); pPathObjectInfo->ProviderName = NULL; } if (pPathObjectInfo->ServerName) { FreeADsStr(pPathObjectInfo->ServerName); pPathObjectInfo->ServerName = NULL; } if (pPathObjectInfo->DisplayServerName) { FreeADsStr(pPathObjectInfo->DisplayServerName); pPathObjectInfo->DisplayServerName = NULL; } FreeObjInfoComponents(pPathObjectInfo); pPathObjectInfo->dwPathType = ADS_PATHTYPE_ROOTFIRST; } HRESULT CPathname::put_EscapedMode( long lEscaped ) { // parameter validation if(lEscaped < ADS_ESCAPEDMODE_DEFAULT || lEscaped > ADS_ESCAPEDMODE_OFF_EX) { return E_ADS_BAD_PARAMETER; } _dwEscaped = lEscaped; return S_OK; } HRESULT CPathname::get_EscapedMode( long *plEscaped ) { *plEscaped = _dwEscaped; return S_OK; } //+--------------------------------------------------------------------------- // Function: CPathname::GetEscapedElement // // Synopsis: Takes the input string, escapes it assuming it is an RDN // and returns the output. // The first cut will be empty as in input string = output // string. Once the code to do this is added please change this // comment appropriately. // // Arguments: lnReserved (= 0 for now), // // // Returns: HRESULT // // Modifies: - // // History: 11-10-98 AjayR Created. // //---------------------------------------------------------------------------- STDMETHODIMP CPathname::GetEscapedElement( LONG lnReserved, BSTR bstrInStr, BSTR* pbstrOutStr ) { HRESULT hr = S_OK; if (m_pPathnameProvider == NULL) { hr = E_ADS_BAD_PATHNAME; goto error; } hr = m_pPathnameProvider->GetEscapedElement(lnReserved, bstrInStr, pbstrOutStr); error: return hr; }
#ifndef FRACTALIZATION_COMPONENTS_FRACTAL_MANDELBROT_HPP #define FRACTALIZATION_COMPONENTS_FRACTAL_MANDELBROT_HPP #include <cmath> #include <utility> namespace fractalization { template <typename CmplxScalar, typename FrctlScalar, FrctlScalar MaxIterations> class Mandelbrot { public: FrctlScalar Evaluate(std::pair<CmplxScalar, CmplxScalar> cp) const { const auto& [c_r, c_i] = cp; FrctlScalar iterations{static_cast<FrctlScalar>(0)}; CmplxScalar z_r{static_cast<CmplxScalar>(0.0)}; CmplxScalar z_i{static_cast<CmplxScalar>(0.0)}; CmplxScalar z_r_squared{static_cast<CmplxScalar>(0.0)}; CmplxScalar z_i_squared{static_cast<CmplxScalar>(0.0)}; while ((z_r_squared + z_i_squared) <= static_cast<CmplxScalar>(4.0) && iterations < MaxIterations) { z_i = 2 * z_r * z_i + c_i; z_r = z_r_squared - z_i_squared + c_r; z_r_squared = std::pow(z_r, 2); z_i_squared = std::pow(z_i, 2); ++iterations; } return iterations; } }; } // namespace fractalization #endif // FRACTALIZATION_COMPONENTS_FRACTAL_MANDELBROT_HPP
// Copyright (c) 2011-2017 The Cryptonote developers // Copyright (c) 2017-2018 The Circle Foundation & Conceal Devs // Copyright (c) 2018-2021 Conceal Network & Conceal Devs // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "WalletGreen.h" #include <algorithm> #include <ctime> #include <cassert> #include <numeric> #include <random> #include <set> #include <tuple> #include <utility> #include <fstream> #include <System/EventLock.h> #include <System/RemoteContext.h> #include "ITransaction.h" #include "Common/ScopeExit.h" #include "Common/ShuffleGenerator.h" #include "Common/StdInputStream.h" #include "Common/StdOutputStream.h" #include "Common/StringTools.h" #include "CryptoNoteCore/Account.h" #include "CryptoNoteCore/Currency.h" #include "CryptoNoteCore/CryptoNoteFormatUtils.h" #include "CryptoNoteCore/CryptoNoteTools.h" #include "CryptoNoteCore/TransactionApi.h" #include <CryptoNoteCore/TransactionExtra.h> #include "crypto/crypto.h" #include "Transfers/TransfersContainer.h" #include "WalletSerializationV1.h" #include "WalletSerializationV2.h" #include "WalletErrors.h" #include "WalletUtils.h" using namespace Common; using namespace Crypto; using namespace CryptoNote; using namespace Logging; namespace { std::vector<uint64_t> split(uint64_t amount, uint64_t dustThreshold) { std::vector<uint64_t> amounts; decompose_amount_into_digits( amount, dustThreshold, [&](uint64_t chunk) { amounts.push_back(chunk); }, [&](uint64_t dust) { amounts.push_back(dust); }); return amounts; } uint64_t calculateDepositsAmount( const std::vector<CryptoNote::TransactionOutputInformation> &transfers, const CryptoNote::Currency &currency, const std::vector<uint32_t> heights) { int index = 0; return std::accumulate(transfers.begin(), transfers.end(), static_cast<uint64_t>(0), [&currency, &index, heights](uint64_t sum, const CryptoNote::TransactionOutputInformation &deposit) { return sum + deposit.amount + currency.calculateInterest(deposit.amount, deposit.term, heights[index++]); }); } void asyncRequestCompletion(System::Event &requestFinished) { requestFinished.set(); } void parseAddressString( const std::string &string, const CryptoNote::Currency &currency, CryptoNote::AccountPublicAddress &address) { if (!currency.parseAccountAddressString(string, address)) { throw std::system_error(make_error_code(CryptoNote::error::BAD_ADDRESS)); } } uint64_t countNeededMoney( const std::vector<CryptoNote::WalletTransfer> &destinations, uint64_t fee) { uint64_t neededMoney = 0; for (const auto &transfer : destinations) { if (transfer.amount == 0) { throw std::system_error(make_error_code(CryptoNote::error::ZERO_DESTINATION)); } else if (transfer.amount < 0) { throw std::system_error(make_error_code(std::errc::invalid_argument)); } //to supress warning uint64_t uamount = static_cast<uint64_t>(transfer.amount); neededMoney += uamount; if (neededMoney < uamount) { throw std::system_error(make_error_code(CryptoNote::error::SUM_OVERFLOW)); } } neededMoney += fee; if (neededMoney < fee) { throw std::system_error(make_error_code(CryptoNote::error::SUM_OVERFLOW)); } return neededMoney; } void checkIfEnoughMixins(std::vector<CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount> &mixinResult, uint64_t mixIn) { auto notEnoughIt = std::find_if(mixinResult.begin(), mixinResult.end(), [mixIn](const CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount &ofa) { return ofa.outs.size() < mixIn; }); if (mixIn == 0 && mixinResult.empty()) { throw std::system_error(make_error_code(CryptoNote::error::MIXIN_COUNT_TOO_BIG)); } if (notEnoughIt != mixinResult.end()) { throw std::system_error(make_error_code(CryptoNote::error::MIXIN_COUNT_TOO_BIG)); } } CryptoNote::WalletEvent makeTransactionUpdatedEvent(size_t id) { CryptoNote::WalletEvent event; event.type = CryptoNote::WalletEventType::TRANSACTION_UPDATED; event.transactionUpdated.transactionIndex = id; return event; } CryptoNote::WalletEvent makeTransactionCreatedEvent(size_t id) { CryptoNote::WalletEvent event; event.type = CryptoNote::WalletEventType::TRANSACTION_CREATED; event.transactionCreated.transactionIndex = id; return event; } CryptoNote::WalletEvent makeMoneyUnlockedEvent() { CryptoNote::WalletEvent event; event.type = CryptoNote::WalletEventType::BALANCE_UNLOCKED; return event; } CryptoNote::WalletEvent makeSyncProgressUpdatedEvent(uint32_t current, uint32_t total) { CryptoNote::WalletEvent event; event.type = CryptoNote::WalletEventType::SYNC_PROGRESS_UPDATED; event.synchronizationProgressUpdated.processedBlockCount = current; event.synchronizationProgressUpdated.totalBlockCount = total; return event; } CryptoNote::WalletEvent makeSyncCompletedEvent() { CryptoNote::WalletEvent event; event.type = CryptoNote::WalletEventType::SYNC_COMPLETED; return event; } size_t getTransactionSize(const ITransactionReader &transaction) { return transaction.getTransactionData().size(); } std::vector<WalletTransfer> convertOrdersToTransfers(const std::vector<WalletOrder> &orders) { std::vector<WalletTransfer> transfers; transfers.reserve(orders.size()); for (const auto &order : orders) { WalletTransfer transfer; if (order.amount > static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) { throw std::system_error(make_error_code(CryptoNote::error::WRONG_AMOUNT), "Order amount must not exceed " + std::to_string(std::numeric_limits<decltype(transfer.amount)>::max())); } transfer.type = WalletTransferType::USUAL; transfer.address = order.address; transfer.amount = static_cast<int64_t>(order.amount); transfers.emplace_back(std::move(transfer)); } return transfers; } uint64_t calculateDonationAmount(uint64_t freeAmount, uint64_t donationThreshold, uint64_t dustThreshold) { std::vector<uint64_t> decomposedAmounts; decomposeAmount(freeAmount, dustThreshold, decomposedAmounts); std::sort(decomposedAmounts.begin(), decomposedAmounts.end(), std::greater<uint64_t>()); uint64_t donationAmount = 0; for (auto amount : decomposedAmounts) { if (amount > donationThreshold - donationAmount) { continue; } donationAmount += amount; } assert(donationAmount <= freeAmount); return donationAmount; } uint64_t pushDonationTransferIfPossible(const DonationSettings &donation, uint64_t freeAmount, uint64_t dustThreshold, std::vector<WalletTransfer> &destinations) { uint64_t donationAmount = 0; if (!donation.address.empty() && donation.threshold != 0) { if (donation.threshold > static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) { throw std::system_error(make_error_code(error::WRONG_AMOUNT), "Donation threshold must not exceed " + std::to_string(std::numeric_limits<int64_t>::max())); } donationAmount = calculateDonationAmount(freeAmount, donation.threshold, dustThreshold); if (donationAmount != 0) { destinations.emplace_back(WalletTransfer{WalletTransferType::DONATION, donation.address, static_cast<int64_t>(donationAmount)}); } } return donationAmount; } CryptoNote::AccountPublicAddress parseAccountAddressString( const std::string &addressString, const CryptoNote::Currency &currency) { CryptoNote::AccountPublicAddress address; if (!currency.parseAccountAddressString(addressString, address)) { throw std::system_error(make_error_code(CryptoNote::error::BAD_ADDRESS)); } return address; } } // namespace namespace CryptoNote { WalletGreen::WalletGreen(System::Dispatcher &dispatcher, const Currency &currency, INode &node, Logging::ILogger &logger, uint32_t transactionSoftLockTime) : m_dispatcher(dispatcher), m_currency(currency), m_node(node), m_logger(logger, "WalletGreen"), m_stopped(false), m_blockchainSynchronizerStarted(false), m_blockchainSynchronizer(node, currency.genesisBlockHash()), m_synchronizer(currency, logger, m_blockchainSynchronizer, node), m_eventOccurred(m_dispatcher), m_readyEvent(m_dispatcher), m_state(WalletState::NOT_INITIALIZED), m_actualBalance(0), m_pendingBalance(0), m_lockedDepositBalance(0), m_unlockedDepositBalance(0), m_transactionSoftLockTime(transactionSoftLockTime) { m_upperTransactionSizeLimit = m_currency.transactionMaxSize(); m_readyEvent.set(); } WalletGreen::~WalletGreen() { if (m_state == WalletState::INITIALIZED) { doShutdown(); } m_dispatcher.yield(); //let remote spawns finish } void WalletGreen::initialize( const std::string &path, const std::string &password) { Crypto::PublicKey viewPublicKey; Crypto::SecretKey viewSecretKey; Crypto::generate_keys(viewPublicKey, viewSecretKey); initWithKeys(path, password, viewPublicKey, viewSecretKey); m_logger(DEBUGGING, BRIGHT_WHITE) << "New container initialized, public view key " << Common::podToHex(viewPublicKey); } void WalletGreen::withdrawDeposit( DepositId depositId, std::string &transactionHash) { throwIfNotInitialized(); throwIfTrackingMode(); throwIfStopped(); /* Check for the existance of the deposit */ if (m_deposits.size() <= depositId) { throw std::system_error(make_error_code(CryptoNote::error::DEPOSIT_DOESNOT_EXIST)); } /* Get the details of the deposit, and the address */ Deposit deposit = getDeposit(depositId); WalletTransfer firstTransfer = getTransactionTransfer(deposit.creatingTransactionId, 0); std::string address = firstTransfer.address; uint64_t blockCount = getBlockCount(); /* Is the deposit unlocked */ if (deposit.unlockHeight > blockCount) { throw std::system_error(make_error_code(CryptoNote::error::DEPOSIT_LOCKED)); } /* Create the transaction */ std::unique_ptr<ITransaction> transaction = createTransaction(); std::vector<TransactionOutputInformation> selectedTransfers; const auto &wallet = getWalletRecord(address); ITransfersContainer *container = wallet.container; AccountKeys account = makeAccountKeys(wallet); ITransfersContainer::TransferState state; TransactionOutputInformation transfer; uint64_t foundMoney = 0; foundMoney += deposit.amount + deposit.interest; m_logger(DEBUGGING, WHITE) << "found money " << foundMoney; container->getTransfer(deposit.transactionHash, deposit.outputInTransaction, transfer, state); if (state != ITransfersContainer::TransferState::TransferAvailable) { throw std::system_error(make_error_code(CryptoNote::error::DEPOSIT_LOCKED)); } selectedTransfers.push_back(std::move(transfer)); m_logger(DEBUGGING, BRIGHT_WHITE) << "Withdraw deposit, id " << depositId << " found transfer for " << transfer.amount << " with a global output index of " << transfer.globalOutputIndex; std::vector<MultisignatureInput> inputs = prepareMultisignatureInputs(selectedTransfers); for (const auto &input : inputs) { transaction->addInput(input); } std::vector<uint64_t> outputAmounts = split(foundMoney - 10, parameters::DEFAULT_DUST_THRESHOLD); for (auto amount : outputAmounts) { transaction->addOutput(amount, account.address); } transaction->setUnlockTime(0); Crypto::SecretKey transactionSK; transaction->getTransactionSecretKey(transactionSK); /* Add the transaction extra */ std::vector<WalletMessage> messages; Crypto::PublicKey publicKey = transaction->getTransactionPublicKey(); CryptoNote::KeyPair kp = {publicKey, transactionSK}; for (size_t i = 0; i < messages.size(); ++i) { CryptoNote::AccountPublicAddress addressBin; if (!m_currency.parseAccountAddressString(messages[i].address, addressBin)) continue; CryptoNote::tx_extra_message tag; if (!tag.encrypt(i, messages[i].message, &addressBin, kp)) continue; BinaryArray ba; toBinaryArray(tag, ba); ba.insert(ba.begin(), TX_EXTRA_MESSAGE_TAG); transaction->appendExtra(ba); } assert(inputs.size() == selectedTransfers.size()); for (size_t i = 0; i < inputs.size(); ++i) { transaction->signInputMultisignature(i, selectedTransfers[i].transactionPublicKey, selectedTransfers[i].outputInTransaction, account); } transactionHash = Common::podToHex(transaction->getTransactionHash()); size_t id = validateSaveAndSendTransaction(*transaction, {}, false, true); } Crypto::SecretKey WalletGreen::getTransactionDeterministicSecretKey(Crypto::Hash &transactionHash) const { throwIfNotInitialized(); throwIfStopped(); Crypto::SecretKey txKey = CryptoNote::NULL_SECRET_KEY; auto getTransactionCompleted = std::promise<std::error_code>(); auto getTransactionWaitFuture = getTransactionCompleted.get_future(); CryptoNote::Transaction tx; m_node.getTransaction(std::move(transactionHash), std::ref(tx), [&getTransactionCompleted](std::error_code ec) { auto detachedPromise = std::move(getTransactionCompleted); detachedPromise.set_value(ec); }); std::error_code ec = getTransactionWaitFuture.get(); if (ec) { m_logger(ERROR) << "Failed to get tx: " << ec << ", " << ec.message(); return CryptoNote::NULL_SECRET_KEY; } Crypto::PublicKey txPubKey = getTransactionPublicKeyFromExtra(tx.extra); KeyPair deterministicTxKeys; bool ok = generateDeterministicTransactionKeys(tx, m_viewSecretKey, deterministicTxKeys) && deterministicTxKeys.publicKey == txPubKey; return ok ? deterministicTxKeys.secretKey : CryptoNote::NULL_SECRET_KEY; return txKey; } std::vector<MultisignatureInput> WalletGreen::prepareMultisignatureInputs(const std::vector<TransactionOutputInformation> &selectedTransfers) { std::vector<MultisignatureInput> inputs; inputs.reserve(selectedTransfers.size()); for (const auto &output : selectedTransfers) { assert(output.type == TransactionTypes::OutputType::Multisignature); assert(output.requiredSignatures == 1); //Other types are currently unsupported MultisignatureInput input; input.amount = output.amount; input.signatureCount = output.requiredSignatures; input.outputIndex = output.globalOutputIndex; input.term = output.term; inputs.emplace_back(std::move(input)); } return inputs; } void WalletGreen::createDeposit( uint64_t amount, uint64_t term, std::string sourceAddress, std::string destinationAddress, std::string &transactionHash) { throwIfNotInitialized(); throwIfTrackingMode(); throwIfStopped(); /* If a source address is not specified, use the primary (first) wallet address for the creation of the deposit */ if (sourceAddress.empty()) { sourceAddress = getAddress(0); } if (destinationAddress.empty()) { destinationAddress = sourceAddress; } /* Ensure that the address is valid and a part of this container */ validateSourceAddresses({sourceAddress}); CryptoNote::AccountPublicAddress sourceAddr = parseAddress(sourceAddress); CryptoNote::AccountPublicAddress destAddr = parseAddress(destinationAddress); /* Create the transaction */ std::unique_ptr<ITransaction> transaction = createTransaction(); /* Select the wallet - If no source address was specified then it will pick funds from anywhere and the change will go to the primary address of the wallet container */ std::vector<WalletOuts> wallets; wallets = pickWallets({sourceAddress}); /* Select the transfers */ uint64_t fee = 1000; uint64_t neededMoney = amount + fee; std::vector<OutputToTransfer> selectedTransfers; uint64_t foundMoney = selectTransfers(neededMoney, 0 == 0, m_currency.defaultDustThreshold(), std::move(wallets), selectedTransfers); /* Do we have enough funds */ if (foundMoney < neededMoney) { throw std::system_error(make_error_code(error::WRONG_AMOUNT)); } /* Now we add the outputs to the transaction, starting with the deposits output which includes the term, and then after that the change outputs */ /* Add the deposit outputs to the transaction */ auto depositIndex = transaction->addOutput( neededMoney - fee, {destAddr}, 1, term); /* Let's add the change outputs to the transaction */ std::vector<uint64_t> amounts; /* Breakdown the change into specific amounts */ decompose_amount_into_digits( foundMoney - neededMoney, m_currency.defaultDustThreshold(), [&](uint64_t chunk) { amounts.push_back(chunk); }, [&](uint64_t dust) { amounts.push_back(dust); }); std::vector<uint64_t> decomposedChange = amounts; /* Now pair each of those amounts to the change address which in the case of a deposit is the source address */ typedef std::pair<const AccountPublicAddress *, uint64_t> AmountToAddress; std::vector<AmountToAddress> amountsToAddresses; for (const auto &output : decomposedChange) { amountsToAddresses.emplace_back(AmountToAddress{&sourceAddr, output}); } /* For the sake of privacy, we shuffle the output order randomly */ std::shuffle(amountsToAddresses.begin(), amountsToAddresses.end(), std::default_random_engine{Crypto::rand<std::default_random_engine::result_type>()}); std::sort(amountsToAddresses.begin(), amountsToAddresses.end(), [](const AmountToAddress &left, const AmountToAddress &right) { return left.second < right.second; }); /* Add the change outputs to the transaction */ try { for (const auto &amountToAddress : amountsToAddresses) { transaction->addOutput(amountToAddress.second, *amountToAddress.first); } } catch (const std::exception &e) { std::cerr << e.what() << '\n'; } /* Now add the other components of the transaction such as the transaction secret key, unlocktime since this is a deposit, we don't need to add messages or added extras beyond the transaction publick key */ Crypto::SecretKey transactionSK; transaction->getTransactionSecretKey(transactionSK); transaction->setUnlockTime(0); /* Add the transaction extra */ std::vector<WalletMessage> messages; Crypto::PublicKey publicKey = transaction->getTransactionPublicKey(); CryptoNote::KeyPair kp = {publicKey, transactionSK}; for (size_t i = 0; i < messages.size(); ++i) { CryptoNote::AccountPublicAddress addressBin; if (!m_currency.parseAccountAddressString(messages[i].address, addressBin)) continue; CryptoNote::tx_extra_message tag; if (!tag.encrypt(i, messages[i].message, &addressBin, kp)) continue; BinaryArray ba; toBinaryArray(tag, ba); ba.insert(ba.begin(), TX_EXTRA_MESSAGE_TAG); transaction->appendExtra(ba); } /* Prepare the inputs */ /* Get additional inputs for the mixin */ typedef CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount outs_for_amount; std::vector<outs_for_amount> mixinResult; std::vector<InputInfo> keysInfo; prepareInputs(selectedTransfers, mixinResult, 4, keysInfo); /* Add the inputs to the transaction */ std::vector<KeyPair> ephKeys; for (auto &input : keysInfo) { transaction->addInput(makeAccountKeys(*input.walletRecord), input.keyInfo, input.ephKeys); } /* Now sign the inputs so we can proceed with the transaction */ size_t i = 0; for (auto &input : keysInfo) { transaction->signInputKey(i++, input.keyInfo, input.ephKeys); } /* Return the transaction hash */ transactionHash = Common::podToHex(transaction->getTransactionHash()); size_t id = validateSaveAndSendTransaction(*transaction, {}, false, true); } void WalletGreen::validateOrders(const std::vector<WalletOrder> &orders) const { for (const auto &order : orders) { if (!CryptoNote::validateAddress(order.address, m_currency)) { throw std::system_error(make_error_code(CryptoNote::error::BAD_ADDRESS)); } if (order.amount >= static_cast<uint64_t>(std::numeric_limits<int64_t>::max())) { std::string message = "Order amount must not exceed " + m_currency.formatAmount(std::numeric_limits<int64_t>::max()); throw std::system_error(make_error_code(CryptoNote::error::WRONG_AMOUNT), message); } } } void WalletGreen::decryptKeyPair(const EncryptedWalletRecord &cipher, PublicKey &publicKey, SecretKey &secretKey, uint64_t &creationTimestamp, const Crypto::chacha8_key &key) { std::array<char, sizeof(cipher.data)> buffer; chacha8(cipher.data, sizeof(cipher.data), key, cipher.iv, buffer.data()); MemoryInputStream stream(buffer.data(), buffer.size()); BinaryInputStreamSerializer serializer(stream); serializer(publicKey, "publicKey"); serializer(secretKey, "secretKey"); serializer.binary(&creationTimestamp, sizeof(uint64_t), "creationTimestamp"); } void WalletGreen::decryptKeyPair(const EncryptedWalletRecord &cipher, PublicKey &publicKey, SecretKey &secretKey, uint64_t &creationTimestamp) const { decryptKeyPair(cipher, publicKey, secretKey, creationTimestamp, m_key); } EncryptedWalletRecord WalletGreen::encryptKeyPair(const PublicKey &publicKey, const SecretKey &secretKey, uint64_t creationTimestamp, const Crypto::chacha8_key &key, const Crypto::chacha8_iv &iv) { EncryptedWalletRecord result; std::string serializedKeys; StringOutputStream outputStream(serializedKeys); BinaryOutputStreamSerializer serializer(outputStream); serializer(const_cast<PublicKey &>(publicKey), "publicKey"); serializer(const_cast<SecretKey &>(secretKey), "secretKey"); serializer.binary(&creationTimestamp, sizeof(uint64_t), "creationTimestamp"); assert(serializedKeys.size() == sizeof(result.data)); result.iv = iv; chacha8(serializedKeys.data(), serializedKeys.size(), key, result.iv, reinterpret_cast<char *>(result.data)); return result; } Crypto::chacha8_iv WalletGreen::getNextIv() const { const auto *prefix = reinterpret_cast<const ContainerStoragePrefix *>(m_containerStorage.prefix()); return prefix->nextIv; } EncryptedWalletRecord WalletGreen::encryptKeyPair(const PublicKey &publicKey, const SecretKey &secretKey, uint64_t creationTimestamp) const { return encryptKeyPair(publicKey, secretKey, creationTimestamp, m_key, getNextIv()); } void WalletGreen::loadSpendKeys() { bool isTrackingMode; for (size_t i = 0; i < m_containerStorage.size(); ++i) { WalletRecord wallet; uint64_t creationTimestamp; decryptKeyPair(m_containerStorage[i], wallet.spendPublicKey, wallet.spendSecretKey, creationTimestamp); wallet.creationTimestamp = creationTimestamp; if (i == 0) { isTrackingMode = wallet.spendSecretKey == NULL_SECRET_KEY; } else if ((isTrackingMode && wallet.spendSecretKey != NULL_SECRET_KEY) || (!isTrackingMode && wallet.spendSecretKey == NULL_SECRET_KEY)) { throw std::system_error(make_error_code(error::BAD_ADDRESS), "All addresses must be whether tracking or not"); } if (wallet.spendSecretKey != NULL_SECRET_KEY) { throwIfKeysMissmatch(wallet.spendSecretKey, wallet.spendPublicKey, "Restored spend public key doesn't correspond to secret key"); } else { if (!Crypto::check_key(wallet.spendPublicKey)) { throw std::system_error(make_error_code(error::WRONG_PASSWORD), "Public spend key is incorrect"); } } wallet.actualBalance = 0; wallet.pendingBalance = 0; wallet.lockedDepositBalance = 0; wallet.unlockedDepositBalance = 0; wallet.container = reinterpret_cast<CryptoNote::ITransfersContainer *>(i); //dirty hack. container field must be unique m_walletsContainer.emplace_back(std::move(wallet)); } } void WalletGreen::validateAddresses(const std::vector<std::string> &addresses) const { for (const auto &address : addresses) { if (!CryptoNote::validateAddress(address, m_currency)) { throw std::system_error(make_error_code(CryptoNote::error::BAD_ADDRESS)); } } } void WalletGreen::initializeWithViewKey(const std::string &path, const std::string &password, const Crypto::SecretKey &viewSecretKey) { Crypto::PublicKey viewPublicKey; if (!Crypto::secret_key_to_public_key(viewSecretKey, viewPublicKey)) { m_logger(ERROR, BRIGHT_RED) << "initializeWithViewKey(" << Common::podToHex(viewSecretKey) << ") Failed to convert secret key to public key"; throw std::system_error(make_error_code(CryptoNote::error::KEY_GENERATION_ERROR)); } initWithKeys(path, password, viewPublicKey, viewSecretKey); m_logger(INFO, BRIGHT_WHITE) << "Container initialized with view secret key, public view key " << Common::podToHex(viewPublicKey); } void WalletGreen::shutdown() { throwIfNotInitialized(); doShutdown(); m_dispatcher.yield(); //let remote spawns finish } void WalletGreen::initBlockchain(const Crypto::PublicKey &viewPublicKey) { std::vector<Crypto::Hash> blockchain = m_synchronizer.getViewKeyKnownBlocks(m_viewPublicKey); m_blockchain.insert(m_blockchain.end(), blockchain.begin(), blockchain.end()); } void WalletGreen::deleteOrphanTransactions(const std::unordered_set<Crypto::PublicKey> &deletedKeys) { for (auto spendPublicKey : deletedKeys) { AccountPublicAddress deletedAccountAddress; deletedAccountAddress.spendPublicKey = spendPublicKey; deletedAccountAddress.viewPublicKey = m_viewPublicKey; auto deletedAddressString = m_currency.accountAddressAsString(deletedAccountAddress); std::vector<size_t> deletedTransactions; std::vector<size_t> updatedTransactions = deleteTransfersForAddress(deletedAddressString, deletedTransactions); deleteFromUncommitedTransactions(deletedTransactions); } } void WalletGreen::saveWalletCache(ContainerStorage &storage, const Crypto::chacha8_key &key, WalletSaveLevel saveLevel, const std::string &extra) { m_logger(INFO) << "Saving cache..."; WalletTransactions transactions; WalletTransfers transfers; if (saveLevel == WalletSaveLevel::SAVE_KEYS_AND_TRANSACTIONS) { filterOutTransactions(transactions, transfers, [](const WalletTransaction &tx) { return tx.state == WalletTransactionState::CREATED || tx.state == WalletTransactionState::DELETED; }); for (auto it = transactions.begin(); it != transactions.end(); ++it) { transactions.modify(it, [](WalletTransaction &tx) { tx.state = WalletTransactionState::CANCELLED; tx.blockHeight = WALLET_UNCONFIRMED_TRANSACTION_HEIGHT; }); } } else if (saveLevel == WalletSaveLevel::SAVE_ALL) { filterOutTransactions(transactions, transfers, [](const WalletTransaction &tx) { return tx.state == WalletTransactionState::DELETED; }); } std::string containerData; Common::StringOutputStream containerStream(containerData); WalletSerializerV2 s( *this, m_viewPublicKey, m_viewSecretKey, m_actualBalance, m_pendingBalance, m_lockedDepositBalance, m_unlockedDepositBalance, m_walletsContainer, m_synchronizer, m_unlockTransactionsJob, transactions, transfers, m_deposits, m_uncommitedTransactions, const_cast<std::string &>(extra), m_transactionSoftLockTime); s.save(containerStream, saveLevel); encryptAndSaveContainerData(storage, key, containerData.data(), containerData.size()); storage.flush(); m_extra = extra; m_logger(INFO) << "Container saving finished"; } void WalletGreen::doShutdown() { if (m_walletsContainer.size() != 0) { m_synchronizer.unsubscribeConsumerNotifications(m_viewPublicKey, this); } stopBlockchainSynchronizer(); m_blockchainSynchronizer.removeObserver(this); m_containerStorage.close(); m_walletsContainer.clear(); clearCaches(true, true); std::queue<WalletEvent> noEvents; std::swap(m_events, noEvents); m_state = WalletState::NOT_INITIALIZED; } void WalletGreen::initTransactionPool() { std::unordered_set<Crypto::Hash> uncommitedTransactionsSet; std::transform(m_uncommitedTransactions.begin(), m_uncommitedTransactions.end(), std::inserter(uncommitedTransactionsSet, uncommitedTransactionsSet.end()), [](const UncommitedTransactions::value_type &pair) { return getObjectHash(pair.second); }); m_synchronizer.initTransactionPool(uncommitedTransactionsSet); } void WalletGreen::initWithKeys(const std::string &path, const std::string &password, const Crypto::PublicKey &viewPublicKey, const Crypto::SecretKey &viewSecretKey) { if (m_state != WalletState::NOT_INITIALIZED) { m_logger(ERROR, BRIGHT_RED) << "Failed to initialize with keys: already initialized."; throw std::system_error(make_error_code(CryptoNote::error::ALREADY_INITIALIZED)); } throwIfStopped(); ContainerStorage newStorage(path, Common::FileMappedVectorOpenMode::CREATE, sizeof(ContainerStoragePrefix)); ContainerStoragePrefix *prefix = reinterpret_cast<ContainerStoragePrefix *>(newStorage.prefix()); prefix->version = static_cast<uint8_t>(WalletSerializerV2::SERIALIZATION_VERSION); prefix->nextIv = Crypto::rand<Crypto::chacha8_iv>(); Crypto::cn_context cnContext; Crypto::generate_chacha8_key(cnContext, password, m_key); uint64_t creationTimestamp = time(nullptr); prefix->encryptedViewKeys = encryptKeyPair(viewPublicKey, viewSecretKey, creationTimestamp, m_key, prefix->nextIv); newStorage.flush(); m_containerStorage.swap(newStorage); incNextIv(); m_viewPublicKey = viewPublicKey; m_viewSecretKey = viewSecretKey; m_password = password; m_path = path; m_logger = Logging::LoggerRef(m_logger.getLogger(), "WalletGreen/" + podToHex(m_viewPublicKey).substr(0, 5)); assert(m_blockchain.empty()); m_blockchain.push_back(m_currency.genesisBlockHash()); m_blockchainSynchronizer.addObserver(this); m_state = WalletState::INITIALIZED; } void WalletGreen::save(WalletSaveLevel saveLevel, const std::string &extra) { m_logger(INFO, BRIGHT_WHITE) << "Saving container..."; throwIfNotInitialized(); throwIfStopped(); stopBlockchainSynchronizer(); try { saveWalletCache(m_containerStorage, m_key, saveLevel, extra); } catch (const std::exception &e) { m_logger(ERROR, BRIGHT_RED) << "Failed to save container: " << e.what(); startBlockchainSynchronizer(); throw; } startBlockchainSynchronizer(); m_logger(INFO, BRIGHT_WHITE) << "Container saved"; } void WalletGreen::copyContainerStorageKeys(ContainerStorage &src, const chacha8_key &srcKey, ContainerStorage &dst, const chacha8_key &dstKey) { dst.reserve(src.size()); dst.setAutoFlush(false); Tools::ScopeExit exitHandler([&dst] { dst.setAutoFlush(true); dst.flush(); }); size_t counter = 0; for (auto &encryptedSpendKeys : src) { Crypto::PublicKey publicKey; Crypto::SecretKey secretKey; uint64_t creationTimestamp; decryptKeyPair(encryptedSpendKeys, publicKey, secretKey, creationTimestamp, srcKey); // push_back() can resize container, and dstPrefix address can be changed, so it is requested for each key pair ContainerStoragePrefix *dstPrefix = reinterpret_cast<ContainerStoragePrefix *>(dst.prefix()); Crypto::chacha8_iv keyPairIv = dstPrefix->nextIv; incIv(dstPrefix->nextIv); dst.push_back(encryptKeyPair(publicKey, secretKey, creationTimestamp, dstKey, keyPairIv)); } } void WalletGreen::copyContainerStoragePrefix(ContainerStorage &src, const chacha8_key &srcKey, ContainerStorage &dst, const chacha8_key &dstKey) { ContainerStoragePrefix *srcPrefix = reinterpret_cast<ContainerStoragePrefix *>(src.prefix()); ContainerStoragePrefix *dstPrefix = reinterpret_cast<ContainerStoragePrefix *>(dst.prefix()); dstPrefix->version = srcPrefix->version; dstPrefix->nextIv = Crypto::randomChachaIV(); Crypto::PublicKey publicKey; Crypto::SecretKey secretKey; uint64_t creationTimestamp; decryptKeyPair(srcPrefix->encryptedViewKeys, publicKey, secretKey, creationTimestamp, srcKey); dstPrefix->encryptedViewKeys = encryptKeyPair(publicKey, secretKey, creationTimestamp, dstKey, dstPrefix->nextIv); incIv(dstPrefix->nextIv); } void WalletGreen::exportWalletKeys(const std::string &path, bool encrypt, WalletSaveLevel saveLevel, const std::string &extra) { m_logger(INFO, BRIGHT_WHITE) << "Exporting container..."; throwIfNotInitialized(); throwIfStopped(); stopBlockchainSynchronizer(); try { bool storageCreated = false; Tools::ScopeExit failExitHandler([path, &storageCreated] { // Don't delete file if it has existed if (storageCreated) { boost::system::error_code ignore; boost::filesystem::remove(path, ignore); } }); ContainerStorage newStorage(path, FileMappedVectorOpenMode::CREATE, m_containerStorage.prefixSize()); storageCreated = true; chacha8_key newStorageKey; if (encrypt) { newStorageKey = m_key; } else { cn_context cnContext; generate_chacha8_key(cnContext, "", newStorageKey); } copyContainerStoragePrefix(m_containerStorage, m_key, newStorage, newStorageKey); copyContainerStorageKeys(m_containerStorage, m_key, newStorage, newStorageKey); saveWalletCache(newStorage, newStorageKey, saveLevel, extra); failExitHandler.cancel(); m_logger(INFO) << "Container export finished"; } catch (const std::exception &e) { m_logger(ERROR, BRIGHT_RED) << "Failed to export container: " << e.what(); startBlockchainSynchronizer(); throw; } startBlockchainSynchronizer(); m_logger(INFO, BRIGHT_WHITE) << "Container exported"; } void WalletGreen::exportWallet(const std::string &path, bool encrypt, WalletSaveLevel saveLevel, const std::string &extra) { m_logger(INFO, BRIGHT_WHITE) << "Exporting container..."; throwIfNotInitialized(); throwIfStopped(); stopBlockchainSynchronizer(); try { bool storageCreated = false; Tools::ScopeExit failExitHandler([path, &storageCreated] { // Don't delete file if it has existed if (storageCreated) { boost::system::error_code ignore; boost::filesystem::remove(path, ignore); } }); ContainerStorage newStorage(path, FileMappedVectorOpenMode::CREATE, m_containerStorage.prefixSize()); storageCreated = true; chacha8_key newStorageKey; if (encrypt) { newStorageKey = m_key; } else { cn_context cnContext; generate_chacha8_key(cnContext, "", newStorageKey); } copyContainerStoragePrefix(m_containerStorage, m_key, newStorage, newStorageKey); copyContainerStorageKeys(m_containerStorage, m_key, newStorage, newStorageKey); saveWalletCache(newStorage, newStorageKey, saveLevel, extra); failExitHandler.cancel(); m_logger(INFO) << "Container export finished"; } catch (const std::exception &e) { m_logger(ERROR, BRIGHT_RED) << "Failed to export container: " << e.what(); startBlockchainSynchronizer(); throw; } startBlockchainSynchronizer(); m_logger(INFO, BRIGHT_WHITE) << "Container exported"; } void WalletGreen::convertAndLoadWalletFile(const std::string &path, std::ifstream &&walletFileStream) { WalletSerializer s( *this, m_viewPublicKey, m_viewSecretKey, m_actualBalance, m_pendingBalance, m_walletsContainer, m_synchronizer, m_unlockTransactionsJob, m_transactions, m_transfers, m_transactionSoftLockTime, m_uncommitedTransactions); StdInputStream stream(walletFileStream); s.load(m_key, stream); walletFileStream.close(); boost::filesystem::path bakPath = path + ".backup"; boost::filesystem::path tmpPath = boost::filesystem::unique_path(path + ".tmp.%%%%-%%%%"); if (boost::filesystem::exists(bakPath)) { m_logger(INFO) << "Wallet backup already exists! Creating random file name backup."; bakPath = boost::filesystem::unique_path(path + ".%%%%-%%%%" + ".backup"); } Tools::ScopeExit tmpFileDeleter([&tmpPath] { boost::system::error_code ignore; boost::filesystem::remove(tmpPath, ignore); }); m_containerStorage.open(tmpPath.string(), Common::FileMappedVectorOpenMode::CREATE, sizeof(ContainerStoragePrefix)); ContainerStoragePrefix *prefix = reinterpret_cast<ContainerStoragePrefix *>(m_containerStorage.prefix()); prefix->version = WalletSerializerV2::SERIALIZATION_VERSION; prefix->nextIv = Crypto::randomChachaIV(); uint64_t creationTimestamp = time(nullptr); prefix->encryptedViewKeys = encryptKeyPair(m_viewPublicKey, m_viewSecretKey, creationTimestamp); for (auto spendKeys : m_walletsContainer.get<RandomAccessIndex>()) { m_containerStorage.push_back(encryptKeyPair(spendKeys.spendPublicKey, spendKeys.spendSecretKey, spendKeys.creationTimestamp)); incNextIv(); } saveWalletCache(m_containerStorage, m_key, WalletSaveLevel::SAVE_ALL, ""); boost::filesystem::rename(path, bakPath); std::error_code ec; m_containerStorage.rename(path, ec); if (ec) { m_logger(ERROR, BRIGHT_RED) << "Failed to rename " << tmpPath << " to " << path; boost::system::error_code ignore; boost::filesystem::rename(bakPath, path, ignore); throw std::system_error(ec, "Failed to replace wallet file"); } tmpFileDeleter.cancel(); m_logger(INFO, BRIGHT_WHITE) << "Wallet file converted! Previous version: " << bakPath; } void WalletGreen::incNextIv() { static_assert(sizeof(uint64_t) == sizeof(Crypto::chacha8_iv), "Bad Crypto::chacha8_iv size"); auto *prefix = reinterpret_cast<ContainerStoragePrefix *>(m_containerStorage.prefix()); incIv(prefix->nextIv); } void WalletGreen::loadAndDecryptContainerData(ContainerStorage &storage, const Crypto::chacha8_key &key, BinaryArray &containerData) { Common::MemoryInputStream suffixStream(storage.suffix(), storage.suffixSize()); BinaryInputStreamSerializer suffixSerializer(suffixStream); Crypto::chacha8_iv suffixIv; BinaryArray encryptedContainer; suffixSerializer(suffixIv, "suffixIv"); suffixSerializer(encryptedContainer, "encryptedContainer"); containerData.resize(encryptedContainer.size()); chacha8(encryptedContainer.data(), encryptedContainer.size(), key, suffixIv, reinterpret_cast<char *>(containerData.data())); } void WalletGreen::loadWalletCache(std::unordered_set<Crypto::PublicKey> &addedKeys, std::unordered_set<Crypto::PublicKey> &deletedKeys, std::string &extra) { assert(m_containerStorage.isOpened()); BinaryArray contanerData; loadAndDecryptContainerData(m_containerStorage, m_key, contanerData); WalletSerializerV2 s( *this, m_viewPublicKey, m_viewSecretKey, m_actualBalance, m_pendingBalance, m_lockedDepositBalance, m_unlockedDepositBalance, m_walletsContainer, m_synchronizer, m_unlockTransactionsJob, m_transactions, m_transfers, m_deposits, m_uncommitedTransactions, extra, m_transactionSoftLockTime); Common::MemoryInputStream containerStream(contanerData.data(), contanerData.size()); s.load(containerStream, reinterpret_cast<const ContainerStoragePrefix *>(m_containerStorage.prefix())->version); addedKeys = std::move(s.addedKeys()); deletedKeys = std::move(s.deletedKeys()); m_logger(INFO) << "Container cache loaded"; } void WalletGreen::loadContainerStorage(const std::string &path) { try { m_containerStorage.open(path, FileMappedVectorOpenMode::OPEN, sizeof(ContainerStoragePrefix)); ContainerStoragePrefix *prefix = reinterpret_cast<ContainerStoragePrefix *>(m_containerStorage.prefix()); assert(prefix->version >= WalletSerializerV2::MIN_VERSION); uint64_t creationTimestamp; decryptKeyPair(prefix->encryptedViewKeys, m_viewPublicKey, m_viewSecretKey, creationTimestamp); throwIfKeysMissmatch(m_viewSecretKey, m_viewPublicKey, "Restored view public key doesn't correspond to secret key"); m_logger = Logging::LoggerRef(m_logger.getLogger(), "WalletGreen/" + podToHex(m_viewPublicKey).substr(0, 5)); loadSpendKeys(); m_logger(DEBUGGING) << "Container keys were successfully loaded"; } catch (const std::exception &e) { m_logger(ERROR, BRIGHT_RED) << "Failed to load container keys: " << e.what(); m_walletsContainer.clear(); m_containerStorage.close(); throw; } } void WalletGreen::encryptAndSaveContainerData(ContainerStorage &storage, const Crypto::chacha8_key &key, const void *containerData, size_t containerDataSize) { ContainerStoragePrefix *prefix = reinterpret_cast<ContainerStoragePrefix *>(storage.prefix()); Crypto::chacha8_iv suffixIv = prefix->nextIv; incIv(prefix->nextIv); BinaryArray encryptedContainer; encryptedContainer.resize(containerDataSize); chacha8(containerData, containerDataSize, key, suffixIv, reinterpret_cast<char *>(encryptedContainer.data())); std::string suffix; Common::StringOutputStream suffixStream(suffix); BinaryOutputStreamSerializer suffixSerializer(suffixStream); suffixSerializer(suffixIv, "suffixIv"); suffixSerializer(encryptedContainer, "encryptedContainer"); storage.resizeSuffix(suffix.size()); std::copy(suffix.begin(), suffix.end(), storage.suffix()); } void WalletGreen::incIv(Crypto::chacha8_iv &iv) { static_assert(sizeof(uint64_t) == sizeof(Crypto::chacha8_iv), "Bad Crypto::chacha8_iv size"); uint64_t *i = reinterpret_cast<uint64_t *>(&iv); if (*i < std::numeric_limits<uint64_t>::max()) { ++(*i); } else { *i = 0; } } void WalletGreen::load(const std::string &path, const std::string &password, std::string &extra) { m_logger(INFO, BRIGHT_WHITE) << "Loading container..."; if (m_state != WalletState::NOT_INITIALIZED) { m_logger(ERROR, BRIGHT_RED) << "Failed to load: already initialized."; throw std::system_error(make_error_code(error::WRONG_STATE)); } throwIfStopped(); stopBlockchainSynchronizer(); Crypto::cn_context cnContext; generate_chacha8_key(cnContext, password, m_key); std::ifstream walletFileStream(path, std::ios_base::binary); int version = walletFileStream.peek(); if (version == EOF) { m_logger(ERROR, BRIGHT_RED) << "Failed to read wallet version"; throw std::system_error(make_error_code(error::WRONG_VERSION), "Failed to read wallet version"); } if (version < WalletSerializerV2::MIN_VERSION) { convertAndLoadWalletFile(path, std::move(walletFileStream)); } else { walletFileStream.close(); if (version > WalletSerializerV2::SERIALIZATION_VERSION) { m_logger(ERROR, BRIGHT_RED) << "Unsupported wallet version: " << version; throw std::system_error(make_error_code(error::WRONG_VERSION), "Unsupported wallet version"); } loadContainerStorage(path); subscribeWallets(); if (m_containerStorage.suffixSize() > 0) { try { std::unordered_set<Crypto::PublicKey> addedSpendKeys; std::unordered_set<Crypto::PublicKey> deletedSpendKeys; loadWalletCache(addedSpendKeys, deletedSpendKeys, extra); if (!addedSpendKeys.empty()) { m_logger(WARNING, BRIGHT_YELLOW) << "Found addresses not saved in container cache. Resynchronize container"; clearCaches(false, true); subscribeWallets(); } if (!deletedSpendKeys.empty()) { m_logger(WARNING, BRIGHT_YELLOW) << "Found deleted addresses saved in container cache. Remove its transactions"; deleteOrphanTransactions(deletedSpendKeys); } if (!addedSpendKeys.empty() || !deletedSpendKeys.empty()) { saveWalletCache(m_containerStorage, m_key, WalletSaveLevel::SAVE_ALL, extra); } } catch (const std::exception &e) { m_logger(ERROR, BRIGHT_RED) << "Failed to load cache: " << e.what() << ", reset wallet data"; clearCaches(true, true); subscribeWallets(); } } } // Read all output keys cache try { std::vector<AccountPublicAddress> subscriptionList; m_synchronizer.getSubscriptions(subscriptionList); for (auto &addr : subscriptionList) { auto sub = m_synchronizer.getSubscription(addr); if (sub != nullptr) { std::vector<TransactionOutputInformation> allTransfers; ITransfersContainer *container = &sub->getContainer(); container->getOutputs(allTransfers, ITransfersContainer::IncludeAll); m_logger(INFO, BRIGHT_WHITE) << "Known Transfers " << allTransfers.size(); for (auto &o : allTransfers) { if (o.type != TransactionTypes::OutputType::Invalid) { m_synchronizer.addPublicKeysSeen(addr, o.transactionHash, o.outputKey); } } } } } catch (const std::exception &e) { m_logger(ERROR, BRIGHT_RED) << "Failed to read output keys!! Continue without output keys: " << e.what(); } m_blockchainSynchronizer.addObserver(this); initTransactionPool(); assert(m_blockchain.empty()); if (m_walletsContainer.get<RandomAccessIndex>().size() != 0) { m_synchronizer.subscribeConsumerNotifications(m_viewPublicKey, this); initBlockchain(m_viewPublicKey); startBlockchainSynchronizer(); } else { m_blockchain.push_back(m_currency.genesisBlockHash()); m_logger(DEBUGGING) << "Add genesis block hash to blockchain"; } m_password = password; m_path = path; m_extra = extra; m_state = WalletState::INITIALIZED; m_logger(INFO, BRIGHT_WHITE) << "Container loaded, view public key " << Common::podToHex(m_viewPublicKey) << ", wallet count " << m_walletsContainer.size() << ", actual balance " << m_currency.formatAmount(m_actualBalance) << ", pending balance " << m_currency.formatAmount(m_pendingBalance); } void WalletGreen::clearCaches(bool clearTransactions, bool clearCachedData) { if (clearTransactions) { m_transactions.clear(); m_transfers.clear(); m_deposits.clear(); } if (clearCachedData) { size_t walletIndex = 0; for (auto it = m_walletsContainer.begin(); it != m_walletsContainer.end(); ++it) { m_walletsContainer.modify(it, [&walletIndex](WalletRecord &wallet) { wallet.actualBalance = 0; wallet.pendingBalance = 0; wallet.lockedDepositBalance = 0; wallet.unlockedDepositBalance = 0; wallet.container = reinterpret_cast<CryptoNote::ITransfersContainer *>(walletIndex++); //dirty hack. container field must be unique }); } if (!clearTransactions) { for (auto it = m_transactions.begin(); it != m_transactions.end(); ++it) { m_transactions.modify(it, [](WalletTransaction &tx) { tx.state = WalletTransactionState::CANCELLED; tx.blockHeight = WALLET_UNCONFIRMED_TRANSACTION_HEIGHT; }); } } std::vector<AccountPublicAddress> subscriptions; m_synchronizer.getSubscriptions(subscriptions); std::for_each(subscriptions.begin(), subscriptions.end(), [this](const AccountPublicAddress &address) { m_synchronizer.removeSubscription(address); }); m_uncommitedTransactions.clear(); m_unlockTransactionsJob.clear(); m_actualBalance = 0; m_pendingBalance = 0; m_lockedDepositBalance = 0; m_unlockedDepositBalance = 0; m_fusionTxsCache.clear(); m_blockchain.clear(); } } void WalletGreen::subscribeWallets() { try { auto &index = m_walletsContainer.get<RandomAccessIndex>(); for (auto it = index.begin(); it != index.end(); ++it) { const auto &wallet = *it; AccountSubscription sub; sub.keys.address.viewPublicKey = m_viewPublicKey; sub.keys.address.spendPublicKey = wallet.spendPublicKey; sub.keys.viewSecretKey = m_viewSecretKey; sub.keys.spendSecretKey = wallet.spendSecretKey; sub.transactionSpendableAge = m_transactionSoftLockTime; sub.syncStart.height = 0; sub.syncStart.timestamp = std::max(static_cast<uint64_t>(wallet.creationTimestamp), ACCOUNT_CREATE_TIME_ACCURACY) - ACCOUNT_CREATE_TIME_ACCURACY; auto &subscription = m_synchronizer.addSubscription(sub); bool r = index.modify(it, [&subscription](WalletRecord &rec) { rec.container = &subscription.getContainer(); }); assert(r); if (r) { }; subscription.addObserver(this); } } catch (const std::exception &e) { m_logger(ERROR, BRIGHT_RED) << "Failed to subscribe wallets: " << e.what(); std::vector<AccountPublicAddress> subscriptionList; m_synchronizer.getSubscriptions(subscriptionList); for (auto &subscription : subscriptionList) { m_synchronizer.removeSubscription(subscription); } throw; } } void WalletGreen::load(const std::string &path, const std::string &password) { std::string extra; load(path, password, extra); } void WalletGreen::changePassword(const std::string &oldPassword, const std::string &newPassword) { throwIfNotInitialized(); throwIfStopped(); if (m_password.compare(oldPassword)) { throw std::system_error(make_error_code(error::WRONG_PASSWORD)); } m_password = newPassword; } size_t WalletGreen::getAddressCount() const { throwIfNotInitialized(); throwIfStopped(); return m_walletsContainer.get<RandomAccessIndex>().size(); } size_t WalletGreen::getWalletDepositCount() const { throwIfNotInitialized(); throwIfStopped(); return m_deposits.get<RandomAccessIndex>().size(); } std::string WalletGreen::getAddress(size_t index) const { throwIfNotInitialized(); throwIfStopped(); if (index >= m_walletsContainer.get<RandomAccessIndex>().size()) { throw std::system_error(make_error_code(std::errc::invalid_argument)); } const WalletRecord &wallet = m_walletsContainer.get<RandomAccessIndex>()[index]; return m_currency.accountAddressAsString({wallet.spendPublicKey, m_viewPublicKey}); } KeyPair WalletGreen::getAddressSpendKey(size_t index) const { throwIfNotInitialized(); throwIfStopped(); if (index >= m_walletsContainer.get<RandomAccessIndex>().size()) { throw std::system_error(make_error_code(std::errc::invalid_argument)); } const WalletRecord &wallet = m_walletsContainer.get<RandomAccessIndex>()[index]; return {wallet.spendPublicKey, wallet.spendSecretKey}; } KeyPair WalletGreen::getAddressSpendKey(const std::string &address) const { throwIfNotInitialized(); throwIfStopped(); CryptoNote::AccountPublicAddress pubAddr = parseAddress(address); auto it = m_walletsContainer.get<KeysIndex>().find(pubAddr.spendPublicKey); if (it == m_walletsContainer.get<KeysIndex>().end()) { throw std::system_error(make_error_code(error::OBJECT_NOT_FOUND)); } return {it->spendPublicKey, it->spendSecretKey}; } KeyPair WalletGreen::getViewKey() const { throwIfNotInitialized(); throwIfStopped(); return {m_viewPublicKey, m_viewSecretKey}; } std::string WalletGreen::createAddress() { KeyPair spendKey; Crypto::generate_keys(spendKey.publicKey, spendKey.secretKey); uint64_t creationTimestamp = static_cast<uint64_t>(time(nullptr)); return doCreateAddress(spendKey.publicKey, spendKey.secretKey, creationTimestamp); } std::string WalletGreen::createAddress(const Crypto::SecretKey &spendSecretKey) { Crypto::PublicKey spendPublicKey; if (!Crypto::secret_key_to_public_key(spendSecretKey, spendPublicKey)) { throw std::system_error(make_error_code(CryptoNote::error::KEY_GENERATION_ERROR)); } uint64_t creationTimestamp = static_cast<uint64_t>(time(nullptr)); return doCreateAddress(spendPublicKey, spendSecretKey, creationTimestamp); } std::string WalletGreen::createAddress(const Crypto::PublicKey &spendPublicKey) { if (!Crypto::check_key(spendPublicKey)) { throw std::system_error(make_error_code(error::WRONG_PARAMETERS), "Wrong public key format"); } uint64_t creationTimestamp = static_cast<uint64_t>(time(nullptr)); return doCreateAddress(spendPublicKey, NULL_SECRET_KEY, creationTimestamp); } std::vector<std::string> WalletGreen::createAddressList(const std::vector<Crypto::SecretKey> &spendSecretKeys, bool reset) { std::vector<NewAddressData> addressDataList(spendSecretKeys.size()); for (size_t i = 0; i < spendSecretKeys.size(); ++i) { Crypto::PublicKey spendPublicKey; if (!Crypto::secret_key_to_public_key(spendSecretKeys[i], spendPublicKey)) { m_logger(ERROR) << "createAddressList(): failed to convert secret key to public key"; throw std::system_error(make_error_code(CryptoNote::error::KEY_GENERATION_ERROR)); } addressDataList[i].spendSecretKey = spendSecretKeys[i]; addressDataList[i].spendPublicKey = spendPublicKey; addressDataList[i].creationTimestamp = reset ? 0 : static_cast<uint64_t>(time(nullptr)); } return doCreateAddressList(addressDataList); } std::vector<std::string> WalletGreen::doCreateAddressList(const std::vector<NewAddressData> &addressDataList) { throwIfNotInitialized(); throwIfStopped(); stopBlockchainSynchronizer(); std::vector<std::string> addresses; try { uint64_t minCreationTimestamp = std::numeric_limits<uint64_t>::max(); { if (addressDataList.size() > 1) { m_containerStorage.setAutoFlush(false); } Tools::ScopeExit exitHandler([this] { if (!m_containerStorage.getAutoFlush()) { m_containerStorage.setAutoFlush(true); m_containerStorage.flush(); } }); for (auto &addressData : addressDataList) { assert(addressData.creationTimestamp <= std::numeric_limits<uint64_t>::max() - m_currency.blockFutureTimeLimit()); std::string address = addWallet(addressData.spendPublicKey, addressData.spendSecretKey, addressData.creationTimestamp); m_logger(INFO, BRIGHT_WHITE) << "New wallet added " << address << ", creation timestamp " << addressData.creationTimestamp; addresses.push_back(std::move(address)); minCreationTimestamp = std::min(minCreationTimestamp, addressData.creationTimestamp); } } m_containerStorage.setAutoFlush(true); auto currentTime = static_cast<uint64_t>(time(nullptr)); if (minCreationTimestamp + m_currency.blockFutureTimeLimit() < currentTime) { m_logger(DEBUGGING) << "Reset is required"; save(WalletSaveLevel::SAVE_KEYS_AND_TRANSACTIONS, m_extra); shutdown(); load(m_path, m_password); } } catch (const std::exception &e) { m_logger(ERROR, BRIGHT_RED) << "Failed to add wallets: " << e.what(); startBlockchainSynchronizer(); throw; } startBlockchainSynchronizer(); return addresses; } std::string WalletGreen::doCreateAddress(const Crypto::PublicKey &spendPublicKey, const Crypto::SecretKey &spendSecretKey, uint64_t creationTimestamp) { assert(creationTimestamp <= std::numeric_limits<uint64_t>::max() - m_currency.blockFutureTimeLimit()); std::vector<NewAddressData> addressDataList; addressDataList.push_back(NewAddressData{spendPublicKey, spendSecretKey, creationTimestamp}); std::vector<std::string> addresses = doCreateAddressList(addressDataList); assert(addresses.size() == 1); return addresses.front(); } std::string WalletGreen::addWallet(const Crypto::PublicKey &spendPublicKey, const Crypto::SecretKey &spendSecretKey, uint64_t creationTimestamp) { auto &index = m_walletsContainer.get<KeysIndex>(); auto trackingMode = getTrackingMode(); if ((trackingMode == WalletTrackingMode::TRACKING && spendSecretKey != NULL_SECRET_KEY) || (trackingMode == WalletTrackingMode::NOT_TRACKING && spendSecretKey == NULL_SECRET_KEY)) { throw std::system_error(make_error_code(error::WRONG_PARAMETERS)); } auto insertIt = index.find(spendPublicKey); if (insertIt != index.end()) { m_logger(ERROR, BRIGHT_RED) << "Failed to add wallet: address already exists, " << m_currency.accountAddressAsString(AccountPublicAddress{spendPublicKey, m_viewPublicKey}); throw std::system_error(make_error_code(error::ADDRESS_ALREADY_EXISTS)); } m_containerStorage.push_back(encryptKeyPair(spendPublicKey, spendSecretKey, creationTimestamp)); incNextIv(); try { AccountSubscription sub; sub.keys.address.viewPublicKey = m_viewPublicKey; sub.keys.address.spendPublicKey = spendPublicKey; sub.keys.viewSecretKey = m_viewSecretKey; sub.keys.spendSecretKey = spendSecretKey; sub.transactionSpendableAge = m_transactionSoftLockTime; sub.syncStart.height = 0; sub.syncStart.timestamp = std::max(creationTimestamp, ACCOUNT_CREATE_TIME_ACCURACY) - ACCOUNT_CREATE_TIME_ACCURACY; auto &trSubscription = m_synchronizer.addSubscription(sub); ITransfersContainer *container = &trSubscription.getContainer(); WalletRecord wallet; wallet.spendPublicKey = spendPublicKey; wallet.spendSecretKey = spendSecretKey; wallet.container = container; wallet.creationTimestamp = static_cast<time_t>(creationTimestamp); trSubscription.addObserver(this); index.insert(insertIt, std::move(wallet)); m_logger(DEBUGGING) << "Wallet count " << m_walletsContainer.size(); if (index.size() == 1) { m_synchronizer.subscribeConsumerNotifications(m_viewPublicKey, this); initBlockchain(m_viewPublicKey); } auto address = m_currency.accountAddressAsString({spendPublicKey, m_viewPublicKey}); m_logger(DEBUGGING) << "Wallet added " << address << ", creation timestamp " << creationTimestamp; return address; } catch (const std::exception &e) { m_logger(ERROR) << "Failed to add wallet: " << e.what(); try { m_containerStorage.pop_back(); } catch (...) { m_logger(ERROR) << "Failed to rollback adding wallet to storage"; } throw; } } void WalletGreen::deleteAddress(const std::string &address) { throwIfNotInitialized(); throwIfStopped(); CryptoNote::AccountPublicAddress pubAddr = parseAddress(address); auto it = m_walletsContainer.get<KeysIndex>().find(pubAddr.spendPublicKey); if (it == m_walletsContainer.get<KeysIndex>().end()) { throw std::system_error(make_error_code(error::OBJECT_NOT_FOUND)); } stopBlockchainSynchronizer(); m_actualBalance -= it->actualBalance; m_pendingBalance -= it->pendingBalance; m_synchronizer.removeSubscription(pubAddr); deleteContainerFromUnlockTransactionJobs(it->container); std::vector<size_t> deletedTransactions; std::vector<size_t> updatedTransactions = deleteTransfersForAddress(address, deletedTransactions); deleteFromUncommitedTransactions(deletedTransactions); m_walletsContainer.get<KeysIndex>().erase(it); auto addressIndex = std::distance( m_walletsContainer.get<RandomAccessIndex>().begin(), m_walletsContainer.project<RandomAccessIndex>(it)); m_containerStorage.erase(std::next(m_containerStorage.begin(), addressIndex)); if (m_walletsContainer.get<RandomAccessIndex>().size() != 0) { startBlockchainSynchronizer(); } else { m_blockchain.clear(); m_blockchain.push_back(m_currency.genesisBlockHash()); } for (auto transactionId : updatedTransactions) { pushEvent(makeTransactionUpdatedEvent(transactionId)); } } uint64_t WalletGreen::getActualBalance() const { throwIfNotInitialized(); throwIfStopped(); return m_actualBalance; } uint64_t WalletGreen::getActualBalance(const std::string &address) const { throwIfNotInitialized(); throwIfStopped(); const auto &wallet = getWalletRecord(address); return wallet.actualBalance; } uint64_t WalletGreen::getPendingBalance() const { throwIfNotInitialized(); throwIfStopped(); return m_pendingBalance; } uint64_t WalletGreen::getLockedDepositBalance(const std::string &address) const { throwIfNotInitialized(); throwIfStopped(); const auto &wallet = getWalletRecord(address); return wallet.lockedDepositBalance; } uint64_t WalletGreen::getUnlockedDepositBalance(const std::string &address) const { throwIfNotInitialized(); throwIfStopped(); const auto &wallet = getWalletRecord(address); return wallet.unlockedDepositBalance; } uint64_t WalletGreen::getLockedDepositBalance() const { throwIfNotInitialized(); throwIfStopped(); return m_lockedDepositBalance; } uint64_t WalletGreen::getUnlockedDepositBalance() const { throwIfNotInitialized(); throwIfStopped(); return m_unlockedDepositBalance; } uint64_t WalletGreen::getPendingBalance(const std::string &address) const { throwIfNotInitialized(); throwIfStopped(); const auto &wallet = getWalletRecord(address); return wallet.pendingBalance; } size_t WalletGreen::getTransactionCount() const { throwIfNotInitialized(); throwIfStopped(); return m_transactions.get<RandomAccessIndex>().size(); } WalletTransaction WalletGreen::getTransaction(size_t transactionIndex) const { throwIfNotInitialized(); throwIfStopped(); if (m_transactions.size() <= transactionIndex) { throw std::system_error(make_error_code(CryptoNote::error::INDEX_OUT_OF_RANGE)); } return m_transactions.get<RandomAccessIndex>()[transactionIndex]; } Deposit WalletGreen::getDeposit(size_t depositIndex) const { throwIfNotInitialized(); throwIfStopped(); if (m_deposits.size() <= depositIndex) { throw std::system_error(make_error_code(CryptoNote::error::DEPOSIT_DOESNOT_EXIST)); } return m_deposits.get<RandomAccessIndex>()[depositIndex]; } size_t WalletGreen::getTransactionTransferCount(size_t transactionIndex) const { throwIfNotInitialized(); throwIfStopped(); auto bounds = getTransactionTransfersRange(transactionIndex); return static_cast<size_t>(std::distance(bounds.first, bounds.second)); } WalletTransfer WalletGreen::getTransactionTransfer(size_t transactionIndex, size_t transferIndex) const { throwIfNotInitialized(); throwIfStopped(); auto bounds = getTransactionTransfersRange(transactionIndex); if (transferIndex >= static_cast<size_t>(std::distance(bounds.first, bounds.second))) { throw std::system_error(make_error_code(std::errc::invalid_argument)); } return std::next(bounds.first, transferIndex)->second; } WalletGreen::TransfersRange WalletGreen::getTransactionTransfersRange(size_t transactionIndex) const { auto val = std::make_pair(transactionIndex, WalletTransfer()); auto bounds = std::equal_range(m_transfers.begin(), m_transfers.end(), val, [](const TransactionTransferPair &a, const TransactionTransferPair &b) { return a.first < b.first; }); return bounds; } size_t WalletGreen::transfer(const TransactionParameters &transactionParameters, Crypto::SecretKey &transactionSK) { Tools::ScopeExit releaseContext([this] { m_dispatcher.yield(); }); System::EventLock lk(m_readyEvent); throwIfNotInitialized(); throwIfTrackingMode(); throwIfStopped(); return doTransfer(transactionParameters, transactionSK); } void WalletGreen::prepareTransaction( std::vector<WalletOuts> &&wallets, const std::vector<WalletOrder> &orders, const std::vector<WalletMessage> &messages, uint64_t fee, uint64_t mixIn, const std::string &extra, uint64_t unlockTimestamp, const DonationSettings &donation, const CryptoNote::AccountPublicAddress &changeDestination, PreparedTransaction &preparedTransaction, Crypto::SecretKey &transactionSK) { preparedTransaction.destinations = convertOrdersToTransfers(orders); preparedTransaction.neededMoney = countNeededMoney(preparedTransaction.destinations, fee); std::vector<OutputToTransfer> selectedTransfers; uint64_t foundMoney = selectTransfers(preparedTransaction.neededMoney, mixIn == 0, m_currency.defaultDustThreshold(), std::move(wallets), selectedTransfers); if (foundMoney < preparedTransaction.neededMoney) { throw std::system_error(make_error_code(error::WRONG_AMOUNT), "Not enough money"); } typedef CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount outs_for_amount; std::vector<outs_for_amount> mixinResult; if (mixIn != 0) { requestMixinOuts(selectedTransfers, mixIn, mixinResult); } std::vector<InputInfo> keysInfo; prepareInputs(selectedTransfers, mixinResult, mixIn, keysInfo); uint64_t donationAmount = pushDonationTransferIfPossible(donation, foundMoney - preparedTransaction.neededMoney, m_currency.defaultDustThreshold(), preparedTransaction.destinations); preparedTransaction.changeAmount = foundMoney - preparedTransaction.neededMoney - donationAmount; std::vector<ReceiverAmounts> decomposedOutputs = splitDestinations(preparedTransaction.destinations, m_currency.defaultDustThreshold(), m_currency); if (preparedTransaction.changeAmount != 0) { WalletTransfer changeTransfer; changeTransfer.type = WalletTransferType::CHANGE; changeTransfer.address = m_currency.accountAddressAsString(changeDestination); changeTransfer.amount = static_cast<int64_t>(preparedTransaction.changeAmount); preparedTransaction.destinations.emplace_back(std::move(changeTransfer)); auto splittedChange = splitAmount(preparedTransaction.changeAmount, changeDestination, m_currency.defaultDustThreshold()); decomposedOutputs.emplace_back(std::move(splittedChange)); } preparedTransaction.transaction = makeTransaction(decomposedOutputs, keysInfo, messages, extra, unlockTimestamp, transactionSK); } void WalletGreen::validateTransactionParameters(const TransactionParameters &transactionParameters) const { if (transactionParameters.destinations.empty()) { throw std::system_error(make_error_code(error::ZERO_DESTINATION)); } if (transactionParameters.donation.address.empty() != (transactionParameters.donation.threshold == 0)) { throw std::system_error(make_error_code(error::WRONG_PARAMETERS)); } validateSourceAddresses(transactionParameters.sourceAddresses); validateChangeDestination(transactionParameters.sourceAddresses, transactionParameters.changeDestination, false); validateOrders(transactionParameters.destinations); } size_t WalletGreen::doTransfer(const TransactionParameters &transactionParameters, Crypto::SecretKey &transactionSK) { validateTransactionParameters(transactionParameters); CryptoNote::AccountPublicAddress changeDestination = getChangeDestination(transactionParameters.changeDestination, transactionParameters.sourceAddresses); std::vector<WalletOuts> wallets; if (!transactionParameters.sourceAddresses.empty()) { wallets = pickWallets(transactionParameters.sourceAddresses); } else { wallets = pickWalletsWithMoney(); } PreparedTransaction preparedTransaction; prepareTransaction( std::move(wallets), transactionParameters.destinations, transactionParameters.messages, transactionParameters.fee, transactionParameters.mixIn, transactionParameters.extra, transactionParameters.unlockTimestamp, transactionParameters.donation, changeDestination, preparedTransaction, transactionSK); return validateSaveAndSendTransaction(*preparedTransaction.transaction, preparedTransaction.destinations, false, true); } size_t WalletGreen::makeTransaction(const TransactionParameters &sendingTransaction) { size_t id = WALLET_INVALID_TRANSACTION_ID; Tools::ScopeExit releaseContext([this, &id] { m_dispatcher.yield(); if (id != WALLET_INVALID_TRANSACTION_ID) { auto &tx = m_transactions[id]; } }); System::EventLock lk(m_readyEvent); throwIfNotInitialized(); throwIfTrackingMode(); throwIfStopped(); validateTransactionParameters(sendingTransaction); CryptoNote::AccountPublicAddress changeDestination = getChangeDestination(sendingTransaction.changeDestination, sendingTransaction.sourceAddresses); m_logger(DEBUGGING) << "Change address " << m_currency.accountAddressAsString(changeDestination); std::vector<WalletOuts> wallets; if (!sendingTransaction.sourceAddresses.empty()) { wallets = pickWallets(sendingTransaction.sourceAddresses); } else { wallets = pickWalletsWithMoney(); } PreparedTransaction preparedTransaction; Crypto::SecretKey txSecretKey; prepareTransaction( std::move(wallets), sendingTransaction.destinations, sendingTransaction.messages, sendingTransaction.fee, sendingTransaction.mixIn, sendingTransaction.extra, sendingTransaction.unlockTimestamp, sendingTransaction.donation, changeDestination, preparedTransaction, txSecretKey); id = validateSaveAndSendTransaction(*preparedTransaction.transaction, preparedTransaction.destinations, false, false); return id; } void WalletGreen::commitTransaction(size_t transactionId) { System::EventLock lk(m_readyEvent); throwIfNotInitialized(); throwIfStopped(); throwIfTrackingMode(); if (transactionId >= m_transactions.size()) { m_logger(ERROR, BRIGHT_RED) << "Failed to commit transaction: invalid index " << transactionId << ". Number of transactions: " << m_transactions.size(); throw std::system_error(make_error_code(CryptoNote::error::INDEX_OUT_OF_RANGE)); } auto txIt = std::next(m_transactions.get<RandomAccessIndex>().begin(), transactionId); if (m_uncommitedTransactions.count(transactionId) == 0 || txIt->state != WalletTransactionState::CREATED) { throw std::system_error(make_error_code(error::TX_TRANSFER_IMPOSSIBLE)); } System::Event completion(m_dispatcher); std::error_code ec; m_node.relayTransaction(m_uncommitedTransactions[transactionId], [&ec, &completion, this](std::error_code error) { ec = error; this->m_dispatcher.remoteSpawn(std::bind(asyncRequestCompletion, std::ref(completion))); }); completion.wait(); if (!ec) { updateTransactionStateAndPushEvent(transactionId, WalletTransactionState::SUCCEEDED); m_uncommitedTransactions.erase(transactionId); } else { throw std::system_error(ec); } } void WalletGreen::rollbackUncommitedTransaction(size_t transactionId) { Tools::ScopeExit releaseContext([this] { m_dispatcher.yield(); }); System::EventLock lk(m_readyEvent); throwIfNotInitialized(); throwIfStopped(); throwIfTrackingMode(); if (transactionId >= m_transactions.size()) { throw std::system_error(make_error_code(CryptoNote::error::INDEX_OUT_OF_RANGE)); } auto txIt = m_transactions.get<RandomAccessIndex>().begin(); std::advance(txIt, transactionId); if (m_uncommitedTransactions.count(transactionId) == 0 || txIt->state != WalletTransactionState::CREATED) { throw std::system_error(make_error_code(error::TX_CANCEL_IMPOSSIBLE)); } removeUnconfirmedTransaction(getObjectHash(m_uncommitedTransactions[transactionId])); m_uncommitedTransactions.erase(transactionId); } void WalletGreen::pushBackOutgoingTransfers(size_t txId, const std::vector<WalletTransfer> &destinations) { for (const auto &dest : destinations) { WalletTransfer d; d.type = dest.type; d.address = dest.address; d.amount = dest.amount; m_transfers.emplace_back(txId, std::move(d)); } } size_t WalletGreen::insertOutgoingTransactionAndPushEvent(const Hash &transactionHash, uint64_t fee, const BinaryArray &extra, uint64_t unlockTimestamp) { WalletTransaction insertTx; insertTx.state = WalletTransactionState::CREATED; insertTx.creationTime = static_cast<uint64_t>(time(nullptr)); insertTx.unlockTime = unlockTimestamp; insertTx.firstDepositId = CryptoNote::WALLET_INVALID_DEPOSIT_ID; insertTx.blockHeight = CryptoNote::WALLET_UNCONFIRMED_TRANSACTION_HEIGHT; insertTx.extra.assign(reinterpret_cast<const char *>(extra.data()), extra.size()); insertTx.fee = fee; insertTx.depositCount = 77; insertTx.hash = transactionHash; insertTx.totalAmount = 0; // 0 until transactionHandlingEnd() is called insertTx.timestamp = 0; //0 until included in a block insertTx.isBase = false; size_t txId = m_transactions.get<RandomAccessIndex>().size(); m_transactions.get<RandomAccessIndex>().push_back(std::move(insertTx)); pushEvent(makeTransactionCreatedEvent(txId)); return txId; } void WalletGreen::updateTransactionStateAndPushEvent(size_t transactionId, WalletTransactionState state) { auto it = std::next(m_transactions.get<RandomAccessIndex>().begin(), transactionId); if (it->state != state) { m_transactions.get<RandomAccessIndex>().modify(it, [state](WalletTransaction &tx) { tx.state = state; }); pushEvent(makeTransactionUpdatedEvent(transactionId)); } } bool WalletGreen::updateWalletDepositInfo(size_t depositId, const CryptoNote::Deposit &info) { auto &txIdIndex = m_deposits.get<RandomAccessIndex>(); assert(depositId < txIdIndex.size()); auto it = std::next(txIdIndex.begin(), depositId); bool updated = false; bool r = txIdIndex.modify(it, [&info, &updated](Deposit &deposit) { if (deposit.spendingTransactionId != info.spendingTransactionId) { deposit.spendingTransactionId = info.spendingTransactionId; updated = true; } }); assert(r); return updated; } bool WalletGreen::updateWalletTransactionInfo(size_t transactionId, const CryptoNote::TransactionInformation &info, int64_t totalAmount) { auto &txIdIndex = m_transactions.get<RandomAccessIndex>(); assert(transactionId < txIdIndex.size()); auto it = std::next(txIdIndex.begin(), transactionId); bool updated = false; bool r = txIdIndex.modify(it, [&info, totalAmount, &updated](WalletTransaction &transaction) { if (transaction.firstDepositId != info.firstDepositId) { transaction.firstDepositId = info.firstDepositId; updated = true; transaction.depositCount = 1; } if (transaction.blockHeight != info.blockHeight) { transaction.blockHeight = info.blockHeight; updated = true; } if (transaction.timestamp != info.timestamp) { transaction.timestamp = info.timestamp; updated = true; } bool isSucceeded = transaction.state == WalletTransactionState::SUCCEEDED; // If transaction was sent to daemon, it can not have CREATED and FAILED states, its state can be SUCCEEDED, CANCELLED or DELETED bool wasSent = transaction.state != WalletTransactionState::CREATED && transaction.state != WalletTransactionState::FAILED; bool isConfirmed = transaction.blockHeight != WALLET_UNCONFIRMED_TRANSACTION_HEIGHT; if (!isSucceeded && (wasSent || isConfirmed)) { //transaction may be deleted first then added again transaction.state = WalletTransactionState::SUCCEEDED; updated = true; } if (transaction.totalAmount != totalAmount) { transaction.totalAmount = totalAmount; updated = true; } // Fix LegacyWallet error. Some old versions didn't fill extra field if (transaction.extra.empty() && !info.extra.empty()) { transaction.extra = Common::asString(info.extra); updated = true; } bool isBase = info.totalAmountIn == 0; if (transaction.isBase != isBase) { transaction.isBase = isBase; updated = true; } }); assert(r); return updated; } size_t WalletGreen::insertBlockchainTransaction(const TransactionInformation &info, int64_t txBalance) { auto &index = m_transactions.get<RandomAccessIndex>(); WalletTransaction tx; tx.state = WalletTransactionState::SUCCEEDED; tx.timestamp = info.timestamp; tx.blockHeight = info.blockHeight; tx.hash = info.transactionHash; tx.depositCount = 0; tx.firstDepositId = WALLET_INVALID_DEPOSIT_ID; tx.isBase = info.totalAmountIn == 0; if (tx.isBase) { tx.fee = 0; } else { tx.fee = info.totalAmountIn < info.totalAmountOut ? CryptoNote::parameters::MINIMUM_FEE : info.totalAmountIn - info.totalAmountOut; } tx.unlockTime = info.unlockTime; tx.extra.assign(reinterpret_cast<const char *>(info.extra.data()), info.extra.size()); tx.totalAmount = txBalance; tx.creationTime = info.timestamp; size_t txId = index.size(); index.push_back(std::move(tx)); return txId; } uint64_t WalletGreen::scanHeightToTimestamp(const uint32_t scanHeight) { if (scanHeight == 0) { return 0; } /* Get the block timestamp from the node if the node has it */ uint64_t timestamp = static_cast<uint64_t>(std::time(nullptr)); /* Get the amount of seconds since the blockchain launched */ uint64_t secondsSinceLaunch = scanHeight * CryptoNote::parameters::DIFFICULTY_TARGET; /* Add a bit of a buffer in case of difficulty weirdness, blocks coming out too fast */ secondsSinceLaunch = static_cast<uint64_t>(secondsSinceLaunch * 0.95); /* Get the genesis block timestamp and add the time since launch */ timestamp = UINT64_C(1527135120) + secondsSinceLaunch; /* Timestamp in the future */ if (timestamp >= static_cast<uint64_t>(std::time(nullptr))) { return getCurrentTimestampAdjusted(); } return timestamp; } uint64_t WalletGreen::getCurrentTimestampAdjusted() { /* Get the current time as a unix timestamp */ std::time_t time = std::time(nullptr); /* Take the amount of time a block can potentially be in the past/future */ std::initializer_list<uint64_t> limits = { CryptoNote::parameters::CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT, CryptoNote::parameters::CRYPTONOTE_BLOCK_FUTURE_TIME_LIMIT_V1}; /* Get the largest adjustment possible */ uint64_t adjust = std::max(limits); /* Take the earliest timestamp that will include all possible blocks */ return time - adjust; } void WalletGreen::reset(const uint64_t scanHeight) { throwIfNotInitialized(); throwIfStopped(); /* Stop so things can't be added to the container as we're looping */ stop(); /* Grab the wallet encrypted prefix */ auto *prefix = reinterpret_cast<ContainerStoragePrefix *>(m_containerStorage.prefix()); m_logger(INFO, BRIGHT_WHITE) << "reset with height " << scanHeight; uint64_t newTimestamp = scanHeightToTimestamp((uint32_t)scanHeight); m_logger(INFO, BRIGHT_WHITE) << "new timestamp " << newTimestamp; /* Reencrypt with the new creation timestamp so we rescan from here when we relaunch */ prefix->encryptedViewKeys = encryptKeyPair(m_viewPublicKey, m_viewSecretKey, newTimestamp); /* As a reference so we can update it */ for (auto &encryptedSpendKeys : m_containerStorage) { Crypto::PublicKey publicKey; Crypto::SecretKey secretKey; uint64_t oldTimestamp; /* Decrypt the key pair we're pointing to */ decryptKeyPair(encryptedSpendKeys, publicKey, secretKey, oldTimestamp); /* Re-encrypt with the new timestamp */ encryptedSpendKeys = encryptKeyPair(publicKey, secretKey, newTimestamp); } /* Start again so we can save */ start(); /* Save just the keys + timestamp to file */ save(CryptoNote::WalletSaveLevel::SAVE_KEYS_ONLY); /* Stop and shutdown */ stop(); /* Shutdown the wallet */ shutdown(); start(); /* Reopen from truncated storage */ load(m_path, m_password); } bool WalletGreen::updateTransactionTransfers(size_t transactionId, const std::vector<ContainerAmounts> &containerAmountsList, int64_t allInputsAmount, int64_t allOutputsAmount) { assert(allInputsAmount <= 0); assert(allOutputsAmount >= 0); bool updated = false; auto transfersRange = getTransactionTransfersRange(transactionId); // Iterators can be invalidated, so the first transfer is addressed by its index size_t firstTransferIdx = std::distance(m_transfers.cbegin(), transfersRange.first); TransfersMap initialTransfers = getKnownTransfersMap(transactionId, firstTransferIdx); std::unordered_set<std::string> myInputAddresses; std::unordered_set<std::string> myOutputAddresses; int64_t myInputsAmount = 0; int64_t myOutputsAmount = 0; for (auto containerAmount : containerAmountsList) { AccountPublicAddress address{getWalletRecord(containerAmount.container).spendPublicKey, m_viewPublicKey}; std::string addressString = m_currency.accountAddressAsString(address); updated |= updateAddressTransfers(transactionId, firstTransferIdx, addressString, initialTransfers[addressString].input, containerAmount.amounts.input); updated |= updateAddressTransfers(transactionId, firstTransferIdx, addressString, initialTransfers[addressString].output, containerAmount.amounts.output); myInputsAmount += containerAmount.amounts.input; myOutputsAmount += containerAmount.amounts.output; if (containerAmount.amounts.input != 0) { myInputAddresses.emplace(addressString); } if (containerAmount.amounts.output != 0) { myOutputAddresses.emplace(addressString); } } assert(myInputsAmount >= allInputsAmount); assert(myOutputsAmount <= allOutputsAmount); int64_t knownInputsAmount = 0; int64_t knownOutputsAmount = 0; auto updatedTransfers = getKnownTransfersMap(transactionId, firstTransferIdx); for (const auto &pair : updatedTransfers) { knownInputsAmount += pair.second.input; knownOutputsAmount += pair.second.output; } assert(myInputsAmount >= knownInputsAmount); assert(myOutputsAmount <= knownOutputsAmount); updated |= updateUnknownTransfers(transactionId, firstTransferIdx, myInputAddresses, knownInputsAmount, myInputsAmount, allInputsAmount, false); updated |= updateUnknownTransfers(transactionId, firstTransferIdx, myOutputAddresses, knownOutputsAmount, myOutputsAmount, allOutputsAmount, true); return updated; } WalletGreen::TransfersMap WalletGreen::getKnownTransfersMap(size_t transactionId, size_t firstTransferIdx) const { TransfersMap result; for (auto it = std::next(m_transfers.begin(), firstTransferIdx); it != m_transfers.end() && it->first == transactionId; ++it) { const auto &address = it->second.address; if (!address.empty()) { if (it->second.amount < 0) { result[address].input += it->second.amount; } else { assert(it->second.amount > 0); result[address].output += it->second.amount; } } } return result; } bool WalletGreen::updateAddressTransfers(size_t transactionId, size_t firstTransferIdx, const std::string &address, int64_t knownAmount, int64_t targetAmount) { assert((knownAmount > 0 && targetAmount > 0) || (knownAmount < 0 && targetAmount < 0) || knownAmount == 0 || targetAmount == 0); bool updated = false; if (knownAmount != targetAmount) { if (knownAmount == 0) { appendTransfer(transactionId, firstTransferIdx, address, targetAmount); updated = true; } else if (targetAmount == 0) { assert(knownAmount != 0); updated |= eraseTransfersByAddress(transactionId, firstTransferIdx, address, knownAmount > 0); } else { updated |= adjustTransfer(transactionId, firstTransferIdx, address, targetAmount); } } return updated; } bool WalletGreen::updateUnknownTransfers(size_t transactionId, size_t firstTransferIdx, const std::unordered_set<std::string> &myAddresses, int64_t knownAmount, int64_t myAmount, int64_t totalAmount, bool isOutput) { bool updated = false; if (std::abs(knownAmount) > std::abs(totalAmount)) { updated |= eraseForeignTransfers(transactionId, firstTransferIdx, myAddresses, isOutput); if (totalAmount == myAmount) { updated |= eraseTransfersByAddress(transactionId, firstTransferIdx, std::string(), isOutput); } else { assert(std::abs(totalAmount) > std::abs(myAmount)); updated |= adjustTransfer(transactionId, firstTransferIdx, std::string(), totalAmount - myAmount); } } else if (knownAmount == totalAmount) { updated |= eraseTransfersByAddress(transactionId, firstTransferIdx, std::string(), isOutput); } else { assert(std::abs(totalAmount) > std::abs(knownAmount)); updated |= adjustTransfer(transactionId, firstTransferIdx, std::string(), totalAmount - knownAmount); } return updated; } void WalletGreen::appendTransfer(size_t transactionId, size_t firstTransferIdx, const std::string &address, int64_t amount) { auto it = std::next(m_transfers.begin(), firstTransferIdx); auto insertIt = std::upper_bound(it, m_transfers.end(), transactionId, [](size_t transactionId, const TransactionTransferPair &pair) { return transactionId < pair.first; }); WalletTransfer transfer{WalletTransferType::USUAL, address, amount}; m_transfers.emplace(insertIt, std::piecewise_construct, std::forward_as_tuple(transactionId), std::forward_as_tuple(transfer)); } bool WalletGreen::adjustTransfer(size_t transactionId, size_t firstTransferIdx, const std::string &address, int64_t amount) { assert(amount != 0); bool updated = false; bool updateOutputTransfers = amount > 0; bool firstAddressTransferFound = false; auto it = std::next(m_transfers.begin(), firstTransferIdx); while (it != m_transfers.end() && it->first == transactionId) { assert(it->second.amount != 0); bool transferIsOutput = it->second.amount > 0; if (transferIsOutput == updateOutputTransfers && it->second.address == address) { if (firstAddressTransferFound) { it = m_transfers.erase(it); updated = true; } else { if (it->second.amount != amount) { it->second.amount = amount; updated = true; } firstAddressTransferFound = true; ++it; } } else { ++it; } } if (!firstAddressTransferFound) { WalletTransfer transfer{WalletTransferType::USUAL, address, amount}; m_transfers.emplace(it, std::piecewise_construct, std::forward_as_tuple(transactionId), std::forward_as_tuple(transfer)); updated = true; } return updated; } bool WalletGreen::eraseTransfers(size_t transactionId, size_t firstTransferIdx, std::function<bool(bool, const std::string &)> &&predicate) { bool erased = false; auto it = std::next(m_transfers.begin(), firstTransferIdx); while (it != m_transfers.end() && it->first == transactionId) { bool transferIsOutput = it->second.amount > 0; if (predicate(transferIsOutput, it->second.address)) { it = m_transfers.erase(it); erased = true; } else { ++it; } } return erased; } bool WalletGreen::eraseTransfersByAddress(size_t transactionId, size_t firstTransferIdx, const std::string &address, bool eraseOutputTransfers) { return eraseTransfers(transactionId, firstTransferIdx, [&address, eraseOutputTransfers](bool isOutput, const std::string &transferAddress) { return eraseOutputTransfers == isOutput && address == transferAddress; }); } bool WalletGreen::eraseForeignTransfers(size_t transactionId, size_t firstTransferIdx, const std::unordered_set<std::string> &knownAddresses, bool eraseOutputTransfers) { return eraseTransfers(transactionId, firstTransferIdx, [this, &knownAddresses, eraseOutputTransfers](bool isOutput, const std::string &transferAddress) { return eraseOutputTransfers == isOutput && knownAddresses.count(transferAddress) == 0; }); } std::unique_ptr<CryptoNote::ITransaction> WalletGreen::makeTransaction(const std::vector<ReceiverAmounts> &decomposedOutputs, std::vector<InputInfo> &keysInfo, const std::vector<WalletMessage> &messages, const std::string &extra, uint64_t unlockTimestamp, Crypto::SecretKey &transactionSK) { std::unique_ptr<ITransaction> tx = createTransaction(); tx->getTransactionSecretKey(transactionSK); Crypto::PublicKey publicKey = tx->getTransactionPublicKey(); CryptoNote::KeyPair kp = {publicKey, transactionSK}; for (size_t i = 0; i < messages.size(); ++i) { CryptoNote::AccountPublicAddress addressBin; if (!m_currency.parseAccountAddressString(messages[i].address, addressBin)) continue; CryptoNote::tx_extra_message tag; if (!tag.encrypt(i, messages[i].message, &addressBin, kp)) continue; BinaryArray ba; toBinaryArray(tag, ba); ba.insert(ba.begin(), TX_EXTRA_MESSAGE_TAG); tx->appendExtra(ba); } typedef std::pair<const AccountPublicAddress *, uint64_t> AmountToAddress; std::vector<AmountToAddress> amountsToAddresses; for (const auto &output : decomposedOutputs) { for (auto amount : output.amounts) { amountsToAddresses.emplace_back(AmountToAddress{&output.receiver, amount}); } } std::shuffle(amountsToAddresses.begin(), amountsToAddresses.end(), std::default_random_engine{Crypto::rand<std::default_random_engine::result_type>()}); std::sort(amountsToAddresses.begin(), amountsToAddresses.end(), [](const AmountToAddress &left, const AmountToAddress &right) { return left.second < right.second; }); for (const auto &amountToAddress : amountsToAddresses) { tx->addOutput(amountToAddress.second, *amountToAddress.first); } tx->setUnlockTime(unlockTimestamp); tx->appendExtra(Common::asBinaryArray(extra)); for (auto &input : keysInfo) { tx->addInput(makeAccountKeys(*input.walletRecord), input.keyInfo, input.ephKeys); } size_t i = 0; for (auto &input : keysInfo) { tx->signInputKey(i++, input.keyInfo, input.ephKeys); } return tx; } void WalletGreen::sendTransaction(const CryptoNote::Transaction &cryptoNoteTransaction) { System::Event completion(m_dispatcher); std::error_code ec; throwIfStopped(); m_node.relayTransaction(cryptoNoteTransaction, [&ec, &completion, this](std::error_code error) { ec = error; this->m_dispatcher.remoteSpawn(std::bind(asyncRequestCompletion, std::ref(completion))); }); completion.wait(); if (ec) { throw std::system_error(ec); } } size_t WalletGreen::validateSaveAndSendTransaction( const ITransactionReader &transaction, const std::vector<WalletTransfer> &destinations, bool isFusion, bool send) { BinaryArray transactionData = transaction.getTransactionData(); if ((transactionData.size() > m_upperTransactionSizeLimit) && (isFusion == false)) { m_logger(ERROR, BRIGHT_RED) << "Transaction is too big"; throw std::system_error(make_error_code(error::TRANSACTION_SIZE_TOO_BIG)); } if ((transactionData.size() > m_currency.fusionTxMaxSize()) && (isFusion == true)) { m_logger(ERROR, BRIGHT_RED) << "Fusion transaction is too big. Transaction hash"; throw std::system_error(make_error_code(error::TRANSACTION_SIZE_TOO_BIG)); } CryptoNote::Transaction cryptoNoteTransaction; if (!fromBinaryArray(cryptoNoteTransaction, transactionData)) { throw std::system_error(make_error_code(error::INTERNAL_WALLET_ERROR), "Failed to deserialize created transaction"); } uint64_t fee = transaction.getInputTotalAmount() < transaction.getOutputTotalAmount() ? CryptoNote::parameters::MINIMUM_FEE : transaction.getInputTotalAmount() - transaction.getOutputTotalAmount(); size_t transactionId = insertOutgoingTransactionAndPushEvent(transaction.getTransactionHash(), fee, transaction.getExtra(), transaction.getUnlockTime()); Tools::ScopeExit rollbackTransactionInsertion([this, transactionId] { updateTransactionStateAndPushEvent(transactionId, WalletTransactionState::FAILED); }); m_fusionTxsCache.emplace(transactionId, isFusion); pushBackOutgoingTransfers(transactionId, destinations); addUnconfirmedTransaction(transaction); Tools::ScopeExit rollbackAddingUnconfirmedTransaction([this, &transaction] { try { removeUnconfirmedTransaction(transaction.getTransactionHash()); } catch (...) { // Ignore any exceptions. If rollback fails then the transaction is stored as unconfirmed and will be deleted after wallet relaunch // during transaction pool synchronization } }); if (send) { sendTransaction(cryptoNoteTransaction); updateTransactionStateAndPushEvent(transactionId, WalletTransactionState::SUCCEEDED); } else { assert(m_uncommitedTransactions.count(transactionId) == 0); m_uncommitedTransactions.emplace(transactionId, std::move(cryptoNoteTransaction)); } rollbackAddingUnconfirmedTransaction.cancel(); rollbackTransactionInsertion.cancel(); return transactionId; } AccountKeys WalletGreen::makeAccountKeys(const WalletRecord &wallet) const { AccountKeys keys; keys.address.spendPublicKey = wallet.spendPublicKey; keys.address.viewPublicKey = m_viewPublicKey; keys.spendSecretKey = wallet.spendSecretKey; keys.viewSecretKey = m_viewSecretKey; return keys; } void WalletGreen::requestMixinOuts( const std::vector<OutputToTransfer> &selectedTransfers, uint64_t mixIn, std::vector<CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount> &mixinResult) { std::vector<uint64_t> amounts; for (const auto &out : selectedTransfers) { amounts.push_back(out.out.amount); } System::Event requestFinished(m_dispatcher); std::error_code mixinError; throwIfStopped(); m_node.getRandomOutsByAmounts(std::move(amounts), mixIn, mixinResult, [&requestFinished, &mixinError, this](std::error_code ec) { mixinError = ec; this->m_dispatcher.remoteSpawn(std::bind(asyncRequestCompletion, std::ref(requestFinished))); }); requestFinished.wait(); checkIfEnoughMixins(mixinResult, mixIn); if (mixinError) { throw std::system_error(mixinError); } } uint64_t WalletGreen::selectTransfers( uint64_t neededMoney, bool dust, uint64_t dustThreshold, std::vector<WalletOuts> &&wallets, std::vector<OutputToTransfer> &selectedTransfers) { uint64_t foundMoney = 0; typedef std::pair<WalletRecord *, TransactionOutputInformation> OutputData; std::vector<OutputData> walletOuts; std::unordered_map<uint64_t, std::vector<OutputData>> buckets; for (auto walletIt = wallets.begin(); walletIt != wallets.end(); ++walletIt) { for (auto outIt = walletIt->outs.begin(); outIt != walletIt->outs.end(); ++outIt) { int numberOfDigits = floor(log10(outIt->amount)) + 1; if (outIt->amount > dustThreshold) { buckets[numberOfDigits].emplace_back( std::piecewise_construct, std::forward_as_tuple(walletIt->wallet), std::forward_as_tuple(*outIt)); } } } while (foundMoney < neededMoney && !buckets.empty()) { /* Take one element from each bucket, smallest first. */ for (auto bucket = buckets.begin(); bucket != buckets.end();) { /* Bucket has been exhausted, remove from list */ if (bucket->second.empty()) { bucket = buckets.erase(bucket); } else { /** Add the amount to the selected transfers so long as * foundMoney is still less than neededMoney. This prevents * larger outputs than we need when we already have enough funds */ if (foundMoney < neededMoney) { auto out = bucket->second.back(); selectedTransfers.emplace_back(OutputToTransfer{std::move(out.second), std::move(out.first)}); foundMoney += out.second.amount; } /* Remove amount we just added */ bucket->second.pop_back(); bucket++; } } } return foundMoney; }; std::vector<WalletGreen::WalletOuts> WalletGreen::pickWalletsWithMoney() const { auto &walletsIndex = m_walletsContainer.get<RandomAccessIndex>(); std::vector<WalletOuts> walletOuts; for (const auto &wallet : walletsIndex) { if (wallet.actualBalance == 0) { continue; } ITransfersContainer *container = wallet.container; WalletOuts outs; container->getOutputs(outs.outs, ITransfersContainer::IncludeKeyUnlocked); outs.wallet = const_cast<WalletRecord *>(&wallet); walletOuts.push_back(std::move(outs)); }; return walletOuts; } WalletGreen::WalletOuts WalletGreen::pickWallet(const std::string &address) const { const auto &wallet = getWalletRecord(address); ITransfersContainer *container = wallet.container; WalletOuts outs; container->getOutputs(outs.outs, ITransfersContainer::IncludeKeyUnlocked); outs.wallet = const_cast<WalletRecord *>(&wallet); return outs; } std::vector<WalletGreen::WalletOuts> WalletGreen::pickWallets(const std::vector<std::string> &addresses) const { std::vector<WalletOuts> wallets; wallets.reserve(addresses.size()); for (const auto &address : addresses) { WalletOuts wallet = pickWallet(address); if (!wallet.outs.empty()) { wallets.emplace_back(std::move(wallet)); } } return wallets; } std::vector<CryptoNote::WalletGreen::ReceiverAmounts> WalletGreen::splitDestinations(const std::vector<CryptoNote::WalletTransfer> &destinations, uint64_t dustThreshold, const CryptoNote::Currency &currency) { std::vector<ReceiverAmounts> decomposedOutputs; for (const auto &destination : destinations) { AccountPublicAddress address; parseAddressString(destination.address, currency, address); decomposedOutputs.push_back(splitAmount(destination.amount, address, dustThreshold)); } return decomposedOutputs; } CryptoNote::WalletGreen::ReceiverAmounts WalletGreen::splitAmount( uint64_t amount, const AccountPublicAddress &destination, uint64_t dustThreshold) { ReceiverAmounts receiverAmounts; receiverAmounts.receiver = destination; decomposeAmount(amount, dustThreshold, receiverAmounts.amounts); return receiverAmounts; } void WalletGreen::prepareInputs( const std::vector<OutputToTransfer> &selectedTransfers, std::vector<CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount> &mixinResult, uint64_t mixIn, std::vector<InputInfo> &keysInfo) { typedef CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::out_entry out_entry; size_t i = 0; for (const auto &input : selectedTransfers) { TransactionTypes::InputKeyInfo keyInfo; keyInfo.amount = input.out.amount; if (mixinResult.size()) { std::sort(mixinResult[i].outs.begin(), mixinResult[i].outs.end(), [](const out_entry &a, const out_entry &b) { return a.global_amount_index < b.global_amount_index; }); for (auto &fakeOut : mixinResult[i].outs) { if (input.out.globalOutputIndex == fakeOut.global_amount_index) { continue; } TransactionTypes::GlobalOutput globalOutput; globalOutput.outputIndex = static_cast<uint32_t>(fakeOut.global_amount_index); globalOutput.targetKey = reinterpret_cast<PublicKey &>(fakeOut.out_key); keyInfo.outputs.push_back(std::move(globalOutput)); if (keyInfo.outputs.size() >= mixIn) break; } } //paste real transaction to the random index auto insertIn = std::find_if(keyInfo.outputs.begin(), keyInfo.outputs.end(), [&](const TransactionTypes::GlobalOutput &a) { return a.outputIndex >= input.out.globalOutputIndex; }); TransactionTypes::GlobalOutput realOutput; realOutput.outputIndex = input.out.globalOutputIndex; realOutput.targetKey = reinterpret_cast<const PublicKey &>(input.out.outputKey); auto insertedIn = keyInfo.outputs.insert(insertIn, realOutput); keyInfo.realOutput.transactionPublicKey = reinterpret_cast<const PublicKey &>(input.out.transactionPublicKey); keyInfo.realOutput.transactionIndex = static_cast<size_t>(insertedIn - keyInfo.outputs.begin()); keyInfo.realOutput.outputInTransaction = input.out.outputInTransaction; //Important! outputs in selectedTransfers and in keysInfo must have the same order! InputInfo inputInfo; inputInfo.keyInfo = std::move(keyInfo); inputInfo.walletRecord = input.wallet; keysInfo.push_back(std::move(inputInfo)); ++i; } } WalletTransactionWithTransfers WalletGreen::getTransaction(const Crypto::Hash &transactionHash) const { throwIfNotInitialized(); throwIfStopped(); auto &hashIndex = m_transactions.get<TransactionIndex>(); auto it = hashIndex.find(transactionHash); if (it == hashIndex.end()) { throw std::system_error(make_error_code(error::OBJECT_NOT_FOUND), "Transaction not found"); } WalletTransactionWithTransfers walletTransaction; walletTransaction.transaction = *it; walletTransaction.transfers = getTransactionTransfers(*it); return walletTransaction; } std::vector<TransactionsInBlockInfo> WalletGreen::getTransactions(const Crypto::Hash &blockHash, size_t count) const { throwIfNotInitialized(); throwIfStopped(); auto &hashIndex = m_blockchain.get<BlockHashIndex>(); auto it = hashIndex.find(blockHash); if (it == hashIndex.end()) { return std::vector<TransactionsInBlockInfo>(); } auto heightIt = m_blockchain.project<BlockHeightIndex>(it); uint32_t blockIndex = static_cast<uint32_t>(std::distance(m_blockchain.get<BlockHeightIndex>().begin(), heightIt)); return getTransactionsInBlocks(blockIndex, count); } std::vector<DepositsInBlockInfo> WalletGreen::getDeposits(const Crypto::Hash &blockHash, size_t count) const { throwIfNotInitialized(); throwIfStopped(); auto &hashIndex = m_blockchain.get<BlockHashIndex>(); auto it = hashIndex.find(blockHash); if (it == hashIndex.end()) { return std::vector<DepositsInBlockInfo>(); } auto heightIt = m_blockchain.project<BlockHeightIndex>(it); uint32_t blockIndex = static_cast<uint32_t>(std::distance(m_blockchain.get<BlockHeightIndex>().begin(), heightIt)); return getDepositsInBlocks(blockIndex, count); } std::vector<TransactionsInBlockInfo> WalletGreen::getTransactions(uint32_t blockIndex, size_t count) const { throwIfNotInitialized(); throwIfStopped(); return getTransactionsInBlocks(blockIndex, count); } std::vector<DepositsInBlockInfo> WalletGreen::getDeposits(uint32_t blockIndex, size_t count) const { throwIfNotInitialized(); throwIfStopped(); return getDepositsInBlocks(blockIndex, count); } std::vector<Crypto::Hash> WalletGreen::getBlockHashes(uint32_t blockIndex, size_t count) const { throwIfNotInitialized(); throwIfStopped(); auto &index = m_blockchain.get<BlockHeightIndex>(); if (blockIndex >= index.size()) { return std::vector<Crypto::Hash>(); } auto start = std::next(index.begin(), blockIndex); auto end = std::next(index.begin(), std::min(index.size(), blockIndex + count)); return std::vector<Crypto::Hash>(start, end); } uint32_t WalletGreen::getBlockCount() const { throwIfNotInitialized(); throwIfStopped(); uint32_t blockCount = static_cast<uint32_t>(m_blockchain.size()); assert(blockCount != 0); return blockCount; } std::vector<WalletTransactionWithTransfers> WalletGreen::getUnconfirmedTransactions() const { throwIfNotInitialized(); throwIfStopped(); std::vector<WalletTransactionWithTransfers> result; auto lowerBound = m_transactions.get<BlockHeightIndex>().lower_bound(WALLET_UNCONFIRMED_TRANSACTION_HEIGHT); for (auto it = lowerBound; it != m_transactions.get<BlockHeightIndex>().end(); ++it) { if (it->state != WalletTransactionState::SUCCEEDED) { continue; } WalletTransactionWithTransfers transaction; transaction.transaction = *it; transaction.transfers = getTransactionTransfers(*it); result.push_back(transaction); } return result; } std::vector<size_t> WalletGreen::getDelayedTransactionIds() const { throwIfNotInitialized(); throwIfStopped(); throwIfTrackingMode(); std::vector<size_t> result; result.reserve(m_uncommitedTransactions.size()); for (const auto &kv : m_uncommitedTransactions) { result.push_back(kv.first); } return result; } void WalletGreen::start() { m_stopped = false; } void WalletGreen::stop() { m_stopped = true; m_eventOccurred.set(); } WalletEvent WalletGreen::getEvent() { throwIfNotInitialized(); throwIfStopped(); while (m_events.empty()) { m_eventOccurred.wait(); m_eventOccurred.clear(); throwIfStopped(); } WalletEvent event = std::move(m_events.front()); m_events.pop(); return event; } void WalletGreen::throwIfNotInitialized() const { if (m_state != WalletState::INITIALIZED) { throw std::system_error(make_error_code(CryptoNote::error::NOT_INITIALIZED)); } } void WalletGreen::onError(ITransfersSubscription *object, uint32_t height, std::error_code ec) { } void WalletGreen::synchronizationProgressUpdated(uint32_t processedBlockCount, uint32_t totalBlockCount) { m_dispatcher.remoteSpawn([processedBlockCount, totalBlockCount, this]() { onSynchronizationProgressUpdated(processedBlockCount, totalBlockCount); }); } void WalletGreen::synchronizationCompleted(std::error_code result) { m_dispatcher.remoteSpawn([this]() { onSynchronizationCompleted(); }); } void WalletGreen::onSynchronizationProgressUpdated(uint32_t processedBlockCount, uint32_t totalBlockCount) { assert(processedBlockCount > 0); System::EventLock lk(m_readyEvent); if (m_state == WalletState::NOT_INITIALIZED) { return; } pushEvent(makeSyncProgressUpdatedEvent(processedBlockCount, totalBlockCount)); uint32_t currentHeight = processedBlockCount - 1; unlockBalances(currentHeight); } void WalletGreen::onSynchronizationCompleted() { System::EventLock lk(m_readyEvent); if (m_state == WalletState::NOT_INITIALIZED) { return; } pushEvent(makeSyncCompletedEvent()); } void WalletGreen::onBlocksAdded(const Crypto::PublicKey &viewPublicKey, const std::vector<Crypto::Hash> &blockHashes) { m_dispatcher.remoteSpawn([this, blockHashes]() { blocksAdded(blockHashes); }); } void WalletGreen::blocksAdded(const std::vector<Crypto::Hash> &blockHashes) { System::EventLock lk(m_readyEvent); if (m_state == WalletState::NOT_INITIALIZED) { return; } m_blockchain.insert(m_blockchain.end(), blockHashes.begin(), blockHashes.end()); } void WalletGreen::onBlockchainDetach(const Crypto::PublicKey &viewPublicKey, uint32_t blockIndex) { m_dispatcher.remoteSpawn([this, blockIndex]() { blocksRollback(blockIndex); }); } void WalletGreen::blocksRollback(uint32_t blockIndex) { System::EventLock lk(m_readyEvent); if (m_state == WalletState::NOT_INITIALIZED) { return; } auto &blockHeightIndex = m_blockchain.get<BlockHeightIndex>(); blockHeightIndex.erase(std::next(blockHeightIndex.begin(), blockIndex), blockHeightIndex.end()); } void WalletGreen::onTransactionDeleteBegin(const Crypto::PublicKey &viewPublicKey, Crypto::Hash transactionHash) { m_dispatcher.remoteSpawn([=]() { transactionDeleteBegin(transactionHash); }); } // TODO remove void WalletGreen::transactionDeleteBegin(Crypto::Hash /*transactionHash*/) { } void WalletGreen::onTransactionDeleteEnd(const Crypto::PublicKey &viewPublicKey, Crypto::Hash transactionHash) { m_dispatcher.remoteSpawn([=]() { transactionDeleteEnd(transactionHash); }); } // TODO remove void WalletGreen::transactionDeleteEnd(Crypto::Hash transactionHash) { } void WalletGreen::unlockBalances(uint32_t height) { auto &index = m_unlockTransactionsJob.get<BlockHeightIndex>(); auto upper = index.upper_bound(height); if (index.begin() != upper) { for (auto it = index.begin(); it != upper; ++it) { updateBalance(it->container); } index.erase(index.begin(), upper); pushEvent(makeMoneyUnlockedEvent()); } } void WalletGreen::onTransactionUpdated(ITransfersSubscription * /*object*/, const Crypto::Hash & /*transactionHash*/) { // Deprecated, ignore it. New event handler is onTransactionUpdated(const Crypto::PublicKey&, const Crypto::Hash&, const std::vector<ITransfersContainer*>&) } void WalletGreen::onTransactionUpdated( const Crypto::PublicKey &, const Crypto::Hash &transactionHash, const std::vector<ITransfersContainer *> &containers) { assert(!containers.empty()); TransactionInformation info; std::vector<ContainerAmounts> containerAmountsList; containerAmountsList.reserve(containers.size()); for (auto container : containers) { uint64_t inputsAmount; // Don't move this code to the following remote spawn, because it guarantees that the container has the // transaction uint64_t outputsAmount; bool found = container->getTransactionInformation(transactionHash, info, &inputsAmount, &outputsAmount); if (found) { } assert(found); ContainerAmounts containerAmounts; containerAmounts.container = container; containerAmounts.amounts.input = -static_cast<int64_t>(inputsAmount); containerAmounts.amounts.output = static_cast<int64_t>(outputsAmount); containerAmountsList.emplace_back(std::move(containerAmounts)); } m_dispatcher.remoteSpawn( [this, info, containerAmountsList] { this->transactionUpdated(info, containerAmountsList); }); } /* Insert a new deposit into the deposit index */ DepositId WalletGreen::insertNewDeposit( const TransactionOutputInformation &depositOutput, TransactionId creatingTransactionId, const Currency &currency, uint32_t height) { assert(depositOutput.type == TransactionTypes::OutputType::Multisignature); assert(depositOutput.term != 0); Deposit deposit; deposit.amount = depositOutput.amount; deposit.creatingTransactionId = creatingTransactionId; deposit.term = depositOutput.term; deposit.spendingTransactionId = WALLET_INVALID_TRANSACTION_ID; deposit.interest = currency.calculateInterest(deposit.amount, deposit.term, height); deposit.height = height; deposit.unlockHeight = height + depositOutput.term; deposit.locked = true; return insertDeposit(deposit, depositOutput.outputInTransaction, depositOutput.transactionHash); } DepositId WalletGreen::insertDeposit( const Deposit &deposit, size_t depositIndexInTransaction, const Hash &transactionHash) { Deposit info = deposit; info.outputInTransaction = static_cast<uint32_t>(depositIndexInTransaction); info.transactionHash = transactionHash; auto &hashIndex = m_transactions.get<TransactionIndex>(); auto it = hashIndex.find(transactionHash); if (it == hashIndex.end()) { throw std::system_error(make_error_code(error::OBJECT_NOT_FOUND), "Transaction not found"); } WalletTransactionWithTransfers walletTransaction; walletTransaction.transaction = *it; walletTransaction.transfers = getTransactionTransfers(*it); DepositId id = m_deposits.size(); m_deposits.push_back(std::move(info)); m_logger(DEBUGGING, BRIGHT_GREEN) << "New deposit created, id " << id << ", locking " << m_currency.formatAmount(deposit.amount) << " ,for a term of " << deposit.term << " blocks, at block " << deposit.height; return id; } /* Process transactions, this covers both new transactions AND confirmed transactions */ void WalletGreen::transactionUpdated( TransactionInformation transactionInfo, const std::vector<ContainerAmounts> &containerAmountsList) { System::EventLock lk(m_readyEvent); if (m_state == WalletState::NOT_INITIALIZED) { return; } size_t firstDepositId = std::numeric_limits<DepositId>::max(); size_t depositCount = 0; bool updated = false; bool isNew = false; int64_t totalAmount = std::accumulate(containerAmountsList.begin(), containerAmountsList.end(), static_cast<int64_t>(0), [](int64_t sum, const ContainerAmounts &containerAmounts) { return sum + containerAmounts.amounts.input + containerAmounts.amounts.output; }); size_t transactionId; auto &hashIndex = m_transactions.get<TransactionIndex>(); auto it = hashIndex.find(transactionInfo.transactionHash); if (it != hashIndex.end()) { transactionId = std::distance(m_transactions.get<RandomAccessIndex>().begin(), m_transactions.project<RandomAccessIndex>(it)); updated |= updateWalletTransactionInfo(transactionId, transactionInfo, totalAmount); } else { isNew = true; transactionId = insertBlockchainTransaction(transactionInfo, totalAmount); m_fusionTxsCache.emplace(transactionId, isFusionTransaction(*it)); } for (auto containerAmounts : containerAmountsList) { auto newDepositOuts = containerAmounts.container->getTransactionOutputs(transactionInfo.transactionHash, ITransfersContainer::IncludeTypeDeposit | ITransfersContainer::IncludeStateAll); auto spentDepositOutputs = containerAmounts.container->getTransactionInputs(transactionInfo.transactionHash, ITransfersContainer::IncludeTypeDeposit); std::vector<DepositId> updatedDepositIds; /* Check for new deposits in this transaction, and create them */ for (size_t i = 0; i < newDepositOuts.size(); i++) { /* We only add confirmed deposit entries, so this condition prevents the same deposit in the deposit index during creation and during confirmation */ if (transactionInfo.blockHeight == WALLET_UNCONFIRMED_TRANSACTION_HEIGHT) { continue; } auto id = insertNewDeposit(newDepositOuts[i], transactionId, m_currency, transactionInfo.blockHeight); updatedDepositIds.push_back(id); } /* Now check for any deposit withdrawals in the transactions */ for (size_t i = 0; i < spentDepositOutputs.size(); i++) { auto depositId = getDepositId(spentDepositOutputs[i].transactionHash); assert(depositId != WALLET_INVALID_DEPOSIT_ID); if (depositId == WALLET_INVALID_DEPOSIT_ID) { throw std::invalid_argument("processSpentDeposits error: requested deposit doesn't exist"); } auto info = m_deposits[depositId]; info.spendingTransactionId = transactionId; updated |= updateWalletDepositInfo(depositId, info); } /* If there are new deposits, update the transaction information with the firstDepositId and the depositCount */ if (!updatedDepositIds.empty()) { firstDepositId = updatedDepositIds[0]; depositCount = updatedDepositIds.size(); transactionInfo.depositCount = depositCount; transactionInfo.firstDepositId = firstDepositId; updated |= updateWalletTransactionInfo(transactionId, transactionInfo, totalAmount); } } if (transactionInfo.blockHeight != CryptoNote::WALLET_UNCONFIRMED_TRANSACTION_HEIGHT) { // In some cases a transaction can be included to a block but not removed from m_uncommitedTransactions. Fix it m_uncommitedTransactions.erase(transactionId); } // Update cached balance for (auto containerAmounts : containerAmountsList) { updateBalance(containerAmounts.container); if (transactionInfo.blockHeight != CryptoNote::WALLET_UNCONFIRMED_TRANSACTION_HEIGHT) { uint32_t unlockHeight = std::max(transactionInfo.blockHeight + m_transactionSoftLockTime, static_cast<uint32_t>(transactionInfo.unlockTime)); insertUnlockTransactionJob(transactionInfo.transactionHash, unlockHeight, containerAmounts.container); } } updated |= updateTransactionTransfers(transactionId, containerAmountsList, -static_cast<int64_t>(transactionInfo.totalAmountIn), static_cast<int64_t>(transactionInfo.totalAmountOut)); if (isNew) { pushEvent(makeTransactionCreatedEvent(transactionId)); } else if (updated) { pushEvent(makeTransactionUpdatedEvent(transactionId)); } } void WalletGreen::pushEvent(const WalletEvent &event) { m_events.push(event); m_eventOccurred.set(); } size_t WalletGreen::getTransactionId(const Hash &transactionHash) const { auto it = m_transactions.get<TransactionIndex>().find(transactionHash); if (it == m_transactions.get<TransactionIndex>().end()) { throw std::system_error(make_error_code(std::errc::invalid_argument)); } auto rndIt = m_transactions.project<RandomAccessIndex>(it); auto txId = std::distance(m_transactions.get<RandomAccessIndex>().begin(), rndIt); return txId; } size_t WalletGreen::getDepositId(const Hash &transactionHash) const { auto it = m_deposits.get<TransactionIndex>().find(transactionHash); if (it == m_deposits.get<TransactionIndex>().end()) { return WALLET_INVALID_DEPOSIT_ID; } auto rndIt = m_deposits.project<RandomAccessIndex>(it); auto depositId = std::distance(m_deposits.get<RandomAccessIndex>().begin(), rndIt); return depositId; } void WalletGreen::onTransactionDeleted(ITransfersSubscription *object, const Hash &transactionHash) { m_dispatcher.remoteSpawn([object, transactionHash, this]() { this->transactionDeleted(object, transactionHash); }); } void WalletGreen::transactionDeleted(ITransfersSubscription *object, const Hash &transactionHash) { System::EventLock lk(m_readyEvent); if (m_state == WalletState::NOT_INITIALIZED) { return; } auto it = m_transactions.get<TransactionIndex>().find(transactionHash); if (it == m_transactions.get<TransactionIndex>().end()) { return; } CryptoNote::ITransfersContainer *container = &object->getContainer(); updateBalance(container); deleteUnlockTransactionJob(transactionHash); bool updated = false; m_transactions.get<TransactionIndex>().modify(it, [&updated](CryptoNote::WalletTransaction &tx) { if (tx.state == WalletTransactionState::CREATED || tx.state == WalletTransactionState::SUCCEEDED) { tx.state = WalletTransactionState::CANCELLED; updated = true; } if (tx.blockHeight != WALLET_UNCONFIRMED_TRANSACTION_HEIGHT) { tx.blockHeight = WALLET_UNCONFIRMED_TRANSACTION_HEIGHT; updated = true; } }); if (updated) { auto transactionId = getTransactionId(transactionHash); pushEvent(makeTransactionUpdatedEvent(transactionId)); } } void WalletGreen::insertUnlockTransactionJob(const Hash &transactionHash, uint32_t blockHeight, CryptoNote::ITransfersContainer *container) { auto &index = m_unlockTransactionsJob.get<BlockHeightIndex>(); index.insert({blockHeight, container, transactionHash}); } void WalletGreen::deleteUnlockTransactionJob(const Hash &transactionHash) { auto &index = m_unlockTransactionsJob.get<TransactionHashIndex>(); index.erase(transactionHash); } void WalletGreen::startBlockchainSynchronizer() { if (!m_walletsContainer.empty() && !m_blockchainSynchronizerStarted) { m_blockchainSynchronizer.start(); m_blockchainSynchronizerStarted = true; } } void WalletGreen::stopBlockchainSynchronizer() { if (m_blockchainSynchronizerStarted) { m_blockchainSynchronizer.stop(); m_blockchainSynchronizerStarted = false; } } void WalletGreen::addUnconfirmedTransaction(const ITransactionReader &transaction) { System::RemoteContext<std::error_code> context(m_dispatcher, [this, &transaction] { return m_blockchainSynchronizer.addUnconfirmedTransaction(transaction).get(); }); auto ec = context.get(); if (ec) { throw std::system_error(ec, "Failed to add unconfirmed transaction"); } } void WalletGreen::removeUnconfirmedTransaction(const Crypto::Hash &transactionHash) { System::RemoteContext<void> context(m_dispatcher, [this, &transactionHash] { m_blockchainSynchronizer.removeUnconfirmedTransaction(transactionHash).get(); }); context.get(); } void WalletGreen::updateBalance(CryptoNote::ITransfersContainer *container) { auto it = m_walletsContainer.get<TransfersContainerIndex>().find(container); if (it == m_walletsContainer.get<TransfersContainerIndex>().end()) { return; } bool updated = false; /* First get the available and pending balances from the container */ uint64_t actual = container->balance(ITransfersContainer::IncludeAllUnlocked); uint64_t pending = container->balance(ITransfersContainer::IncludeKeyNotUnlocked); /* Now update the overall balance (getBalance without parameters) */ if (it->actualBalance < actual) { m_actualBalance += actual - it->actualBalance; updated = true; } else { m_actualBalance -= it->actualBalance - actual; updated = true; } if (it->pendingBalance < pending) { m_pendingBalance += pending - it->pendingBalance; updated = true; } else { m_pendingBalance -= it->pendingBalance - pending; updated = true; } /* Update locked deposit balance, this will cover deposits, as well as investments since they are all deposits with different parameters */ std::vector<TransactionOutputInformation> transfers2; container->getOutputs(transfers2, ITransfersContainer::IncludeTypeDeposit | ITransfersContainer::IncludeStateLocked | ITransfersContainer::IncludeStateSoftLocked); std::vector<uint32_t> heights2; for (auto transfer2 : transfers2) { Crypto::Hash hash2 = transfer2.transactionHash; TransactionInformation info2; bool ok2 = container->getTransactionInformation(hash2, info2, NULL, NULL); if (ok2) { heights2.push_back(info2.blockHeight); updated = true; } } uint64_t locked = calculateDepositsAmount(transfers2, m_currency, heights2); /* This updates the unlocked deposit balance, these are the deposits that have matured and can be withdrawn */ std::vector<TransactionOutputInformation> transfers; container->getOutputs(transfers, ITransfersContainer::IncludeTypeDeposit | ITransfersContainer::IncludeStateUnlocked); std::vector<uint32_t> heights; for (auto transfer : transfers) { Crypto::Hash hash = transfer.transactionHash; TransactionInformation info; bool ok = container->getTransactionInformation(hash, info, NULL, NULL); assert(ok); heights.push_back(info.blockHeight); } uint64_t unlocked = calculateDepositsAmount(transfers, m_currency, heights); /* Now do the same thing for overall deposit balances */ if (it->lockedDepositBalance < locked) { m_lockedDepositBalance += locked - it->lockedDepositBalance; updated = true; } else { m_lockedDepositBalance -= it->lockedDepositBalance - locked; updated = true; } if (it->unlockedDepositBalance < unlocked) { m_unlockedDepositBalance += unlocked - it->unlockedDepositBalance; updated = true; } else { m_unlockedDepositBalance -= it->unlockedDepositBalance - unlocked; updated = true; } /* Write any changes to the wallet balances to the container */ if (updated) { m_walletsContainer.get<TransfersContainerIndex>().modify(it, [actual, pending, locked, unlocked](WalletRecord &wallet) { wallet.actualBalance = actual; wallet.pendingBalance = pending; wallet.lockedDepositBalance = locked; wallet.unlockedDepositBalance = unlocked; }); /* Keep the logging to debugging */ m_logger(DEBUGGING, BRIGHT_WHITE) << "Wallet balance updated, address " << m_currency.accountAddressAsString({it->spendPublicKey, m_viewPublicKey}) << ", actual " << m_currency.formatAmount(it->actualBalance) << ", pending " << m_currency.formatAmount(it->pendingBalance); m_logger(DEBUGGING, BRIGHT_WHITE) << "Container balance updated, actual " << m_currency.formatAmount(m_actualBalance) << ", pending " << m_currency.formatAmount(m_pendingBalance) << ", locked deposits " << m_currency.formatAmount(m_lockedDepositBalance) << ",unlocked deposits " << m_currency.formatAmount(m_unlockedDepositBalance); } } const WalletRecord &WalletGreen::getWalletRecord(const PublicKey &key) const { auto it = m_walletsContainer.get<KeysIndex>().find(key); if (it == m_walletsContainer.get<KeysIndex>().end()) { throw std::system_error(make_error_code(error::WALLET_NOT_FOUND)); } return *it; } const WalletRecord &WalletGreen::getWalletRecord(const std::string &address) const { CryptoNote::AccountPublicAddress pubAddr = parseAddress(address); return getWalletRecord(pubAddr.spendPublicKey); } const WalletRecord &WalletGreen::getWalletRecord(CryptoNote::ITransfersContainer *container) const { auto it = m_walletsContainer.get<TransfersContainerIndex>().find(container); if (it == m_walletsContainer.get<TransfersContainerIndex>().end()) { throw std::system_error(make_error_code(error::WALLET_NOT_FOUND)); } return *it; } CryptoNote::AccountPublicAddress WalletGreen::parseAddress(const std::string &address) const { CryptoNote::AccountPublicAddress pubAddr; if (!m_currency.parseAccountAddressString(address, pubAddr)) { throw std::system_error(make_error_code(error::BAD_ADDRESS)); } return pubAddr; } void WalletGreen::throwIfStopped() const { if (m_stopped) { throw std::system_error(make_error_code(error::OPERATION_CANCELLED)); } } void WalletGreen::throwIfTrackingMode() const { if (getTrackingMode() == WalletTrackingMode::TRACKING) { throw std::system_error(make_error_code(error::TRACKING_MODE)); } } WalletGreen::WalletTrackingMode WalletGreen::getTrackingMode() const { if (m_walletsContainer.get<RandomAccessIndex>().empty()) { return WalletTrackingMode::NO_ADDRESSES; } return m_walletsContainer.get<RandomAccessIndex>().begin()->spendSecretKey == NULL_SECRET_KEY ? WalletTrackingMode::TRACKING : WalletTrackingMode::NOT_TRACKING; } size_t WalletGreen::createFusionTransaction( uint64_t threshold, uint64_t mixin, const std::vector<std::string> &sourceAddresses, const std::string &destinationAddress) { size_t id = WALLET_INVALID_TRANSACTION_ID; Tools::ScopeExit releaseContext([this, &id] { m_dispatcher.yield(); if (id != WALLET_INVALID_TRANSACTION_ID) { auto &tx = m_transactions[id]; } }); System::EventLock lk(m_readyEvent); throwIfNotInitialized(); throwIfTrackingMode(); throwIfStopped(); validateSourceAddresses(sourceAddresses); validateChangeDestination(sourceAddresses, destinationAddress, true); const size_t MAX_FUSION_OUTPUT_COUNT = 8; uint64_t fusionTreshold = m_currency.defaultDustThreshold(); if (threshold <= fusionTreshold) { throw std::system_error(make_error_code(error::THRESHOLD_TOO_LOW)); } if (m_walletsContainer.get<RandomAccessIndex>().size() == 0) { throw std::system_error(make_error_code(error::MINIMUM_ONE_ADDRESS)); } size_t estimatedFusionInputsCount = m_currency.getApproximateMaximumInputCount(m_currency.fusionTxMaxSize(), MAX_FUSION_OUTPUT_COUNT, mixin); if (estimatedFusionInputsCount < m_currency.fusionTxMinInputCount()) { throw std::system_error(make_error_code(error::MIXIN_COUNT_TOO_BIG)); } auto fusionInputs = pickRandomFusionInputs(sourceAddresses, threshold, m_currency.fusionTxMinInputCount(), estimatedFusionInputsCount); if (fusionInputs.size() < m_currency.fusionTxMinInputCount()) { //nothing to optimize throw std::system_error(make_error_code(error::NOTHING_TO_OPTIMIZE)); return WALLET_INVALID_TRANSACTION_ID; } typedef CryptoNote::COMMAND_RPC_GET_RANDOM_OUTPUTS_FOR_AMOUNTS::outs_for_amount outs_for_amount; std::vector<outs_for_amount> mixinResult; if (mixin != 0) { requestMixinOuts(fusionInputs, mixin, mixinResult); } std::vector<InputInfo> keysInfo; prepareInputs(fusionInputs, mixinResult, mixin, keysInfo); AccountPublicAddress destination = getChangeDestination(destinationAddress, sourceAddresses); std::unique_ptr<ITransaction> fusionTransaction; size_t transactionSize; int round = 0; uint64_t transactionAmount; do { if (round != 0) { fusionInputs.pop_back(); keysInfo.pop_back(); } uint64_t inputsAmount = std::accumulate(fusionInputs.begin(), fusionInputs.end(), static_cast<uint64_t>(0), [](uint64_t amount, const OutputToTransfer &input) { return amount + input.out.amount; }); transactionAmount = inputsAmount; ReceiverAmounts decomposedOutputs = decomposeFusionOutputs(destination, inputsAmount); assert(decomposedOutputs.amounts.size() <= MAX_FUSION_OUTPUT_COUNT); Crypto::SecretKey txkey; std::vector<WalletMessage> messages; fusionTransaction = makeTransaction(std::vector<ReceiverAmounts>{decomposedOutputs}, keysInfo, messages, "", 0, txkey); transactionSize = getTransactionSize(*fusionTransaction); ++round; } while ((transactionSize > m_currency.fusionTxMaxSize()) && (fusionInputs.size() >= m_currency.fusionTxMinInputCount())); if (fusionInputs.size() < m_currency.fusionTxMinInputCount()) { throw std::system_error(make_error_code(error::MINIMUM_INPUT_COUNT)); } id = validateSaveAndSendTransaction(*fusionTransaction, {}, true, true); return id; } WalletGreen::ReceiverAmounts WalletGreen::decomposeFusionOutputs(const AccountPublicAddress &address, uint64_t inputsAmount) { WalletGreen::ReceiverAmounts outputs; outputs.receiver = address; decomposeAmount(inputsAmount, 0, outputs.amounts); std::sort(outputs.amounts.begin(), outputs.amounts.end()); return outputs; } bool WalletGreen::isFusionTransaction(size_t transactionId) const { throwIfNotInitialized(); throwIfStopped(); if (m_transactions.size() <= transactionId) { throw std::system_error(make_error_code(CryptoNote::error::INDEX_OUT_OF_RANGE)); } auto isFusionIter = m_fusionTxsCache.find(transactionId); if (isFusionIter != m_fusionTxsCache.end()) { return isFusionIter->second; } bool result = isFusionTransaction(m_transactions.get<RandomAccessIndex>()[transactionId]); m_fusionTxsCache.emplace(transactionId, result); return result; } bool WalletGreen::isFusionTransaction(const WalletTransaction &walletTx) const { if (walletTx.fee != 0) { return false; } uint64_t inputsSum = 0; uint64_t outputsSum = 0; std::vector<uint64_t> outputsAmounts; std::vector<uint64_t> inputsAmounts; TransactionInformation txInfo; bool gotTx = false; const auto &walletsIndex = m_walletsContainer.get<RandomAccessIndex>(); for (const WalletRecord &wallet : walletsIndex) { for (const TransactionOutputInformation &output : wallet.container->getTransactionOutputs(walletTx.hash, ITransfersContainer::IncludeTypeKey | ITransfersContainer::IncludeStateAll)) { if (outputsAmounts.size() <= output.outputInTransaction) { outputsAmounts.resize(output.outputInTransaction + 1, 0); } assert(output.amount != 0); assert(outputsAmounts[output.outputInTransaction] == 0); outputsAmounts[output.outputInTransaction] = output.amount; outputsSum += output.amount; } for (const TransactionOutputInformation &input : wallet.container->getTransactionInputs(walletTx.hash, ITransfersContainer::IncludeTypeKey)) { inputsSum += input.amount; inputsAmounts.push_back(input.amount); } if (!gotTx) { gotTx = wallet.container->getTransactionInformation(walletTx.hash, txInfo); } } if (!gotTx) { return false; } if (outputsSum != inputsSum || outputsSum != txInfo.totalAmountOut || inputsSum != txInfo.totalAmountIn) { return false; } else { return m_currency.isFusionTransaction(inputsAmounts, outputsAmounts, 0); //size = 0 here because can't get real size of tx in wallet. } } void WalletGreen::validateChangeDestination(const std::vector<std::string> &sourceAddresses, const std::string &changeDestination, bool isFusion) const { std::string message; if (changeDestination.empty()) { if (sourceAddresses.size() > 1 || (sourceAddresses.empty() && m_walletsContainer.size() > 1)) { message = std::string(isFusion ? "Destination" : "Change destination") + " address is necessary"; m_logger(ERROR, BRIGHT_RED) << message << ". Source addresses size=" << sourceAddresses.size() << ", wallets count=" << m_walletsContainer.size(); throw std::system_error(make_error_code(isFusion ? error::DESTINATION_ADDRESS_REQUIRED : error::CHANGE_ADDRESS_REQUIRED), message); } } else { if (!CryptoNote::validateAddress(changeDestination, m_currency)) { message = std::string("Bad ") + (isFusion ? "destination" : "change destination") + " address: " + changeDestination; m_logger(ERROR, BRIGHT_RED) << message; throw std::system_error(make_error_code(CryptoNote::error::BAD_ADDRESS), message); } if (!isMyAddress(changeDestination)) { message = std::string(isFusion ? "Destination" : "Change destination") + " address is not found in current container: " + changeDestination; m_logger(ERROR, BRIGHT_RED) << message; throw std::system_error(make_error_code(isFusion ? error::DESTINATION_ADDRESS_NOT_FOUND : error::CHANGE_ADDRESS_NOT_FOUND), message); } } } void WalletGreen::validateSourceAddresses(const std::vector<std::string> &sourceAddresses) const { validateAddresses(sourceAddresses); auto badAddr = std::find_if(sourceAddresses.begin(), sourceAddresses.end(), [this](const std::string &addr) { return !isMyAddress(addr); }); if (badAddr != sourceAddresses.end()) { throw std::system_error(make_error_code(error::BAD_ADDRESS), "Source address must belong to current container: " + *badAddr); } } IFusionManager::EstimateResult WalletGreen::estimate(uint64_t threshold, const std::vector<std::string> &sourceAddresses) const { System::EventLock lk(m_readyEvent); throwIfNotInitialized(); throwIfStopped(); validateSourceAddresses(sourceAddresses); IFusionManager::EstimateResult result{0, 0}; auto walletOuts = sourceAddresses.empty() ? pickWalletsWithMoney() : pickWallets(sourceAddresses); std::array<size_t, std::numeric_limits<uint64_t>::digits10 + 1> bucketSizes; bucketSizes.fill(0); for (size_t walletIndex = 0; walletIndex < walletOuts.size(); ++walletIndex) { for (auto &out : walletOuts[walletIndex].outs) { uint8_t powerOfTen = 0; if (m_currency.isAmountApplicableInFusionTransactionInput(out.amount, threshold, powerOfTen, m_node.getLastKnownBlockHeight())) { assert(powerOfTen < std::numeric_limits<uint64_t>::digits10 + 1); bucketSizes[powerOfTen]++; } } result.totalOutputCount += walletOuts[walletIndex].outs.size(); } for (auto bucketSize : bucketSizes) { if (bucketSize >= m_currency.fusionTxMinInputCount()) { result.fusionReadyCount += bucketSize; } } return result; } std::vector<WalletGreen::OutputToTransfer> WalletGreen::pickRandomFusionInputs(const std::vector<std::string> &addresses, uint64_t threshold, size_t minInputCount, size_t maxInputCount) { std::vector<WalletGreen::OutputToTransfer> allFusionReadyOuts; auto walletOuts = addresses.empty() ? pickWalletsWithMoney() : pickWallets(addresses); std::array<size_t, std::numeric_limits<uint64_t>::digits10 + 1> bucketSizes; bucketSizes.fill(0); for (size_t walletIndex = 0; walletIndex < walletOuts.size(); ++walletIndex) { for (auto &out : walletOuts[walletIndex].outs) { uint8_t powerOfTen = 0; if (m_currency.isAmountApplicableInFusionTransactionInput(out.amount, threshold, powerOfTen, m_node.getLastKnownBlockHeight())) { allFusionReadyOuts.push_back({std::move(out), walletOuts[walletIndex].wallet}); assert(powerOfTen < std::numeric_limits<uint64_t>::digits10 + 1); bucketSizes[powerOfTen]++; } } } //now, pick the bucket std::vector<uint8_t> bucketNumbers(bucketSizes.size()); std::iota(bucketNumbers.begin(), bucketNumbers.end(), 0); std::shuffle(bucketNumbers.begin(), bucketNumbers.end(), std::default_random_engine{Crypto::rand<std::default_random_engine::result_type>()}); size_t bucketNumberIndex = 0; for (; bucketNumberIndex < bucketNumbers.size(); ++bucketNumberIndex) { if (bucketSizes[bucketNumbers[bucketNumberIndex]] >= minInputCount) { break; } } if (bucketNumberIndex == bucketNumbers.size()) { return {}; } size_t selectedBucket = bucketNumbers[bucketNumberIndex]; assert(selectedBucket < std::numeric_limits<uint64_t>::digits10 + 1); assert(bucketSizes[selectedBucket] >= minInputCount); uint64_t lowerBound = 1; for (size_t i = 0; i < selectedBucket; ++i) { lowerBound *= 10; } uint64_t upperBound = selectedBucket == std::numeric_limits<uint64_t>::digits10 ? UINT64_MAX : lowerBound * 10; std::vector<WalletGreen::OutputToTransfer> selectedOuts; selectedOuts.reserve(bucketSizes[selectedBucket]); for (size_t outIndex = 0; outIndex < allFusionReadyOuts.size(); ++outIndex) { if (allFusionReadyOuts[outIndex].out.amount >= lowerBound && allFusionReadyOuts[outIndex].out.amount < upperBound) { selectedOuts.push_back(std::move(allFusionReadyOuts[outIndex])); } } assert(selectedOuts.size() >= minInputCount); auto outputsSortingFunction = [](const OutputToTransfer &l, const OutputToTransfer &r) { return l.out.amount < r.out.amount; }; if (selectedOuts.size() <= maxInputCount) { std::sort(selectedOuts.begin(), selectedOuts.end(), outputsSortingFunction); return selectedOuts; } ShuffleGenerator<size_t, Crypto::random_engine<size_t>> generator(selectedOuts.size()); std::vector<WalletGreen::OutputToTransfer> trimmedSelectedOuts; trimmedSelectedOuts.reserve(maxInputCount); for (size_t i = 0; i < maxInputCount; ++i) { trimmedSelectedOuts.push_back(std::move(selectedOuts[generator()])); } std::sort(trimmedSelectedOuts.begin(), trimmedSelectedOuts.end(), outputsSortingFunction); return trimmedSelectedOuts; } std::vector<DepositsInBlockInfo> WalletGreen::getDepositsInBlocks(uint32_t blockIndex, size_t count) const { if (count == 0) { throw std::system_error(make_error_code(error::WRONG_PARAMETERS), "blocks count must be greater than zero"); } std::vector<DepositsInBlockInfo> result; if (blockIndex >= m_blockchain.size()) { return result; } auto &blockHeightIndex = m_deposits.get<BlockHeightIndex>(); uint32_t stopIndex = static_cast<uint32_t>(std::min(m_blockchain.size(), blockIndex + count)); for (uint32_t height = blockIndex; height < stopIndex; ++height) { DepositsInBlockInfo info; info.blockHash = m_blockchain[height]; auto lowerBound = blockHeightIndex.lower_bound(height); auto upperBound = blockHeightIndex.upper_bound(height); for (auto it = lowerBound; it != upperBound; ++it) { Deposit deposit; deposit = *it; info.deposits.emplace_back(std::move(deposit)); } result.emplace_back(std::move(info)); } return result; } std::vector<TransactionsInBlockInfo> WalletGreen::getTransactionsInBlocks(uint32_t blockIndex, size_t count) const { if (count == 0) { throw std::system_error(make_error_code(error::WRONG_PARAMETERS), "blocks count must be greater than zero"); } std::vector<TransactionsInBlockInfo> result; if (blockIndex >= m_blockchain.size()) { return result; } auto &blockHeightIndex = m_transactions.get<BlockHeightIndex>(); uint32_t stopIndex = static_cast<uint32_t>(std::min(m_blockchain.size(), blockIndex + count)); for (uint32_t height = blockIndex; height < stopIndex; ++height) { TransactionsInBlockInfo info; info.blockHash = m_blockchain[height]; auto lowerBound = blockHeightIndex.lower_bound(height); auto upperBound = blockHeightIndex.upper_bound(height); for (auto it = lowerBound; it != upperBound; ++it) { if (it->state != WalletTransactionState::SUCCEEDED) { continue; } WalletTransactionWithTransfers transaction; transaction.transaction = *it; transaction.transfers = getTransactionTransfers(*it); info.transactions.emplace_back(std::move(transaction)); } result.emplace_back(std::move(info)); } return result; } Crypto::Hash WalletGreen::getBlockHashByIndex(uint32_t blockIndex) const { assert(blockIndex < m_blockchain.size()); return m_blockchain.get<BlockHeightIndex>()[blockIndex]; } std::vector<WalletTransfer> WalletGreen::getTransactionTransfers(const WalletTransaction &transaction) const { auto &transactionIdIndex = m_transactions.get<RandomAccessIndex>(); auto it = transactionIdIndex.iterator_to(transaction); assert(it != transactionIdIndex.end()); size_t transactionId = std::distance(transactionIdIndex.begin(), it); size_t transfersCount = getTransactionTransferCount(transactionId); std::vector<WalletTransfer> result; result.reserve(transfersCount); for (size_t transferId = 0; transferId < transfersCount; ++transferId) { result.push_back(getTransactionTransfer(transactionId, transferId)); } return result; } void WalletGreen::filterOutTransactions(WalletTransactions &transactions, WalletTransfers &transfers, std::function<bool(const WalletTransaction &)> &&pred) const { size_t cancelledTransactions = 0; transactions.reserve(m_transactions.size()); transfers.reserve(m_transfers.size()); auto &index = m_transactions.get<RandomAccessIndex>(); size_t transferIdx = 0; for (size_t i = 0; i < m_transactions.size(); ++i) { const WalletTransaction &transaction = index[i]; if (pred(transaction)) { ++cancelledTransactions; while (transferIdx < m_transfers.size() && m_transfers[transferIdx].first == i) { ++transferIdx; } } else { transactions.emplace_back(transaction); while (transferIdx < m_transfers.size() && m_transfers[transferIdx].first == i) { transfers.emplace_back(i - cancelledTransactions, m_transfers[transferIdx].second); ++transferIdx; } } } } void WalletGreen::getViewKeyKnownBlocks(const Crypto::PublicKey &viewPublicKey) { std::vector<Crypto::Hash> blockchain = m_synchronizer.getViewKeyKnownBlocks(m_viewPublicKey); m_blockchain.insert(m_blockchain.end(), blockchain.begin(), blockchain.end()); } ///pre: changeDestinationAddress belongs to current container ///pre: source address belongs to current container CryptoNote::AccountPublicAddress WalletGreen::getChangeDestination(const std::string &changeDestinationAddress, const std::vector<std::string> &sourceAddresses) const { if (!changeDestinationAddress.empty()) { return parseAccountAddressString(changeDestinationAddress, m_currency); } if (m_walletsContainer.size() == 1) { return AccountPublicAddress{m_walletsContainer.get<RandomAccessIndex>()[0].spendPublicKey, m_viewPublicKey}; } assert(sourceAddresses.size() == 1 && isMyAddress(sourceAddresses[0])); return parseAccountAddressString(sourceAddresses[0], m_currency); } bool WalletGreen::isMyAddress(const std::string &addressString) const { CryptoNote::AccountPublicAddress address = parseAccountAddressString(addressString, m_currency); return m_viewPublicKey == address.viewPublicKey && m_walletsContainer.get<KeysIndex>().count(address.spendPublicKey) != 0; } void WalletGreen::deleteContainerFromUnlockTransactionJobs(const ITransfersContainer *container) { for (auto it = m_unlockTransactionsJob.begin(); it != m_unlockTransactionsJob.end();) { if (it->container == container) { it = m_unlockTransactionsJob.erase(it); } else { ++it; } } } std::vector<size_t> WalletGreen::deleteTransfersForAddress(const std::string &address, std::vector<size_t> &deletedTransactions) { assert(!address.empty()); int64_t deletedInputs = 0; int64_t deletedOutputs = 0; int64_t unknownInputs = 0; bool transfersLeft = false; size_t firstTransactionTransfer = 0; std::vector<size_t> updatedTransactions; for (size_t i = 0; i < m_transfers.size(); ++i) { WalletTransfer &transfer = m_transfers[i].second; if (transfer.address == address) { if (transfer.amount >= 0) { deletedOutputs += transfer.amount; } else { deletedInputs += transfer.amount; transfer.address = ""; } } else if (transfer.address.empty()) { if (transfer.amount < 0) { unknownInputs += transfer.amount; } } else if (isMyAddress(transfer.address)) { transfersLeft = true; } size_t transactionId = m_transfers[i].first; if ((i == m_transfers.size() - 1) || (transactionId != m_transfers[i + 1].first)) { //the last transfer for current transaction size_t transfersBeforeMerge = m_transfers.size(); if (deletedInputs != 0) { adjustTransfer(transactionId, firstTransactionTransfer, "", deletedInputs + unknownInputs); } assert(transfersBeforeMerge >= m_transfers.size()); i -= transfersBeforeMerge - m_transfers.size(); auto &randomIndex = m_transactions.get<RandomAccessIndex>(); randomIndex.modify(std::next(randomIndex.begin(), transactionId), [transfersLeft, deletedInputs, deletedOutputs](WalletTransaction &transaction) { transaction.totalAmount -= deletedInputs + deletedOutputs; if (!transfersLeft) { transaction.state = WalletTransactionState::DELETED; } }); if (!transfersLeft) { deletedTransactions.push_back(transactionId); } if (deletedInputs != 0 || deletedOutputs != 0) { updatedTransactions.push_back(transactionId); } //reset values for next transaction deletedInputs = 0; deletedOutputs = 0; unknownInputs = 0; transfersLeft = false; firstTransactionTransfer = i + 1; } } return updatedTransactions; } size_t WalletGreen::getTxSize(const TransactionParameters &sendingTransaction) { System::EventLock lk(m_readyEvent); throwIfNotInitialized(); throwIfTrackingMode(); throwIfStopped(); CryptoNote::AccountPublicAddress changeDestination = getChangeDestination(sendingTransaction.changeDestination, sendingTransaction.sourceAddresses); std::vector<WalletOuts> wallets; if (!sendingTransaction.sourceAddresses.empty()) { wallets = pickWallets(sendingTransaction.sourceAddresses); } else { wallets = pickWalletsWithMoney(); } PreparedTransaction preparedTransaction; Crypto::SecretKey txSecretKey; prepareTransaction( std::move(wallets), sendingTransaction.destinations, sendingTransaction.messages, sendingTransaction.fee, sendingTransaction.mixIn, sendingTransaction.extra, sendingTransaction.unlockTimestamp, sendingTransaction.donation, changeDestination, preparedTransaction, txSecretKey); BinaryArray transactionData = preparedTransaction.transaction->getTransactionData(); return transactionData.size(); } void WalletGreen::deleteFromUncommitedTransactions(const std::vector<size_t> &deletedTransactions) { for (auto transactionId : deletedTransactions) { m_uncommitedTransactions.erase(transactionId); } } void WalletGreen::clearCacheAndShutdown() { if (m_walletsContainer.size() != 0) { m_synchronizer.unsubscribeConsumerNotifications(m_viewPublicKey, this); } stopBlockchainSynchronizer(); m_blockchainSynchronizer.removeObserver(this); clearCaches(true, true); m_walletsContainer.clear(); shutdown(); } } //namespace CryptoNote
// Copyright 2014-2015 SDL plc // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. /** \file Hypergraph (or Graph, or FSM, as special cases). For a hypergraph: You have a Vocabulary You have input and output labels on states. You have arcs with weight (cost and maybe features), head (which can only have a nonterminal label), sequence of tails (each of which can have any label). We require arcs have at least one tail for now. You have a final state (if no final state, then the hypergraph is empty). You may optionally have a start state. Start state and all terminal-labeled states are *axioms*, meaning that they can appear at the leaves of derivation trees (evocative of the near-synonyms: 'forest' for a hypergraph, usually acyclic and thus having finitely many trees). You have Properties (bits that tell you what structural invariants and adjacency queries are available). A hypergraph is a graph if the first tail of every arc is a valid head state (no terminal label) and every other tail has a terminal label. Terminals are words (lexical, e.g. "brown"), or special terminals (e.g. <eps>) An FSM is a graph with always exactly two tails (so sometimes the axiom tail must have an <eps> label). Axioms can't be head states, except for the start state in graphs - but please forgive bugs if you use start as a head - many algorithms work correctly only for acyclic (DAG) graphs. In graphs, the legal head states are the same as the legal first-tail adjacent states. CFGs need not use a start state. (see docs/ for more) for lazy graphs, see fs/Fst.hpp TODO: for lazy hypergraph (top down or bottom up?) we can't allow you to predict the total number of states and one of start or final state (depending on laziness direction) can't be known in advance */ #ifndef HYP__IHYPERGRAPH_HPP #define HYP__IHYPERGRAPH_HPP #pragma once /* STYLE WARNINGS: visitArcs visitors take Arc * but in many cases you aren't permitted to modify such arcs. We'd make a type of Arc const* visitor but that would increase lines of code; TODO: decide whether to pay that. We could stop exposing Arc* entirely and require access to arc properties to be via handle provided to IHypergraph; this would allow more memory-compact encoding of FSA vs FST etc ... but the tradeoff would be more complicated access and more virtual dispatch. Many non-orthogonal helper methods in IHypergraph-some aid efficiency, but it's a lot too swallow. */ /* GOTCHA: Arc * must be given to HG with new Arc(...) or crash on HG dtor (you could remove all the arcs violating this property but it's hard to guarantee the HG dtor doesn't come first (e.g. exception causes destruction)) */ /*TODO (algorithms): approx minimize weighted NFA exact finite CFG -> fsm (PDA stack construction). lazy might be useful approx CFG -> NFA parse / check membership of string (without doing seq-fsa -> intersect) copy within-alpha of weighted inside*outside parse = compose with trivial acceptor - but CKY type parse instead of Earley? bottom-up rescoring/splitting of CFG left-right */ /*TODO (structure): OpenFst arc mutator/iterator support (many things marked TODO) LAZY cfg (???) input/output format first-class trees (Regular Tree Grammar) independent of state - data structure supports height-1 RTG effectively by state id different from label. */ #include <sdl/Hypergraph/Exception.hpp> #include <sdl/Hypergraph/HypergraphBase.hpp> #include <sdl/Hypergraph/HypergraphImpl.hpp> #include <sdl/Hypergraph/OperateOn.hpp> #include <sdl/Hypergraph/Properties.hpp> #include <sdl/Hypergraph/fs/Annotations.hpp> #include <sdl/Util/AnyGenerator.hpp> #include <sdl/Util/Constants.hpp> #include <sdl/Util/LogHelper.hpp> #include <sdl/Util/Once.hpp> #include <sdl/Util/SmallVector.hpp> #include <sdl/Util/Unordered.hpp> #include <sdl/Array.hpp> #include <sdl/SharedPtr.hpp> #include <boost/cstdint.hpp> #include <boost/noncopyable.hpp> #include <boost/range/algorithm/max_element.hpp> #include <boost/range/size.hpp> #include <cassert> #include <cstddef> #include <stdexcept> namespace sdl { namespace Hypergraph { /// tag class struct InArcsT {}; /// tag class struct OutArcsT {}; /// for Hypergraph/fs/* (lazy finite-state-only algorithms) template <class WeightT, class StateT = StateId> struct FstArc { typedef StateT State; typedef StateT InputState; typedef WeightT Weight; State dst; /// unlike hg.labelPair, .second will not be NoSymbol if it's the samea s .first; it will be literally equal LabelPair labelPair; Weight weight; #if SDL_HYPERGRAPH_FS_ANNOTATIONS /// annotations are special symbols that don't participate in the fst translation but ride with the input hg /// e.g. constraint open/close. they're expected before lexical/epsilon arcs and are placed before them when /// going back to hg/path in fs/LazyBest or fs/SaveFst Syms annotations; #endif void setDst(State const& dst_) { dst = dst_; } State const& getDst() const { return dst; } typedef typename Weight::FloatT Distance; Distance getDistance() const { return weight.getValue(); } void printLabel(std::ostream& out) const { out << '(' << labelPair.first; if (labelPair.first != labelPair.second) out << ' ' << labelPair.second; out << ')'; } void printWeight(std::ostream& out) const { if (weight != Weight::one()) out << "/" << weight; } void print(std::ostream& out) const { out << dst << "<-"; printLabel(out); printWeight(out); } friend inline std::ostream& operator<<(std::ostream& out, FstArc const& self) { self.print(out); return out; } void printLabel(std::ostream& out, IVocabulary const* vocab) const { #if SDL_HYPERGRAPH_FS_ANNOTATIONS if (!annotations.empty()) out << "annotations:" << printer(annotations, vocab); #endif out << '('; out << vocab->str(labelPair.first); if (labelPair.first != labelPair.second) out << ' ' << vocab->str(labelPair.second); out << ')'; } void print(std::ostream& out, IVocabulary const* vocab) const { out << dst << "<-"; printLabel(out, vocab); printWeight(out); } friend inline void print(std::ostream& out, FstArc const& self, IVocabulary const* pvocab) { self.print(out, pvocab); } }; /** IHypergraph base interface (A is the arc type). (see Arc.hpp) Hypergraphs have (input and output) labeled states, Arcs connecting states, a final state (if nonempty), a start state (required for nonempty Finite State Machine or Graph, optional for Hypergraph as tree-set), and also some precomputed properties. Hypergraphs contain trees (paths, strings). TODO: move more members (especially the template-code ones) to free fns; some redundant virtual members exist for performance (so subclass impl. can use subclass impl. details w/o paying for virtual dispatch) */ template <class A> struct IHypergraph : HypergraphBase, private boost::noncopyable { public: static char const* staticType() { return "IHypergraph"; } typedef IHypergraph<A> Self; typedef shared_ptr<Self> Ptr; typedef shared_ptr<Self> Ref; typedef IHypergraph<A> Immutable; typedef shared_ptr<Immutable> ImmutablePtr; typedef shared_ptr<Immutable const> ConstImmutablePtr; typedef A Arc; typedef typename A::ArcVisitor ArcVisitor; // sdl::function<void (Arc *)> typedef typename A::Weight Weight; typedef FstArc<Weight, StateId> FstArcT; struct FstArcFor { void init(Self const* hg, bool allowAnnotations = false) { #if SDL_HYPERGRAPH_FS_ANNOTATIONS annotations = allowAnnotations && (true || (hg->properties() & kAnnotations)); // TODO: detect annotations property for compose speedup #endif // TODO: set kAnnotations prop for hgs w/ annotations hg_ = hg; sizeForLabels_ = hg->sizeForLabels(); assert(hg_->isGraph()); assert(hg_->hasAtMostOneLexicalTail()); } FstArcFor() {} FstArcFor(Self const* hg_, bool allowAnnotations = false) { init(hg_, allowAnnotations); } explicit FstArcFor(Self const& hg, bool allowAnnotations = false) { init(&hg, allowAnnotations); } typedef FstArcT result_type; result_type operator()(ArcBase const* arc) const { result_type r; r.dst = arc->head_; r.weight = static_cast<Arc const*>(arc)->weight_; StateIdContainer const& tails = arc->tails_; #if SDL_HYPERGRAPH_FS_ANNOTATIONS if (annotations) { StateIdContainer::const_iterator i = tails.begin(), e = tails.end(); for (;;) { if (++i >= e) { r.labelPair.first = r.labelPair.second = EPSILON::ID; break; } StateId const t = *i; if (t >= sizeForLabels_) { // TODO: test r.labelPair.first = r.labelPair.second = EPSILON::ID; break; } r.labelPair = hg_->labelPair(t); if (Vocabulary::isAnnotation(r.labelPair.first)) r.annotations.push_back(r.labelPair.first); else break; } } else // TODO: test #endif { if (tails.size() == 2) { StateId const t = tails[1]; if (t < sizeForLabels_) { r.labelPair = hg_->labelPair(t); } else { r.labelPair.first = r.labelPair.second = EPSILON::ID; } } else { r.labelPair = hg_->firstLexicalLabelPairOrEps(arc); } } return r; } private: Self const* hg_; StateId sizeForLabels_; #if SDL_HYPERGRAPH_FS_ANNOTATIONS bool annotations; #endif }; virtual Weight final(StateId s) const; using HypergraphBase::final; /** don't invalidate the hg you're iterating: don't (via IMutableHypergraph) change arc storage options, or otherwise delete states however, you may add states (but not arcs) e.g. in changing arc labels if you don't want a sdl::function, then instead use forArcs directly. tradeoff: forArcs is less efficient than visitArcs (but visit is then inline) */ virtual void visitArcs(ArcVisitor const& v) const { forArcs(v); } /** this should be an admissible heuristic (outside path to final from st has weight.getValue less than this. note: in extreme cases (negative costs possible for arcs, as may happen in tuning) this should be less than 0 */ Distance heuristic(StateId st) const override { return 0; } /** may improve the estimates returned by heuristic. may be as expensive as inside-outside. probably will be cheap on repeated calls if hg hasn't changed (an issue for IMutableHypergraph). modifying the hg after calling computeHeuristic might not be noticed (and thus inadmissible heuristic values might be observed) - for example, if you change arc weights behind the scene, we won't notice. this is a const method (it should be harmless to call at any time), so any state kept by an implementation should probably be marked mutable */ void computeHeuristic() const override {} /** \return number of edges. may be linear time. */ std::size_t getNumEdges() const; // does s have an outgoing transition for every symbol (aside from // epsilon to final, which should be //TODO: multiple final states, // so we don't have to distinguish between real and fake epsilons) bool hasAllOut(StateId s) const override; /// forArcs(v) - call v(a) for all Arc *a, exactly once for each a /// forArcsAllowRepeats-v(a) 1 or more times per Arc *a #include <sdl/Hypergraph/src/IHypergraphForArcs.ipp> WeightCount countArcs() const { WeightCount r; forArcs([&r](Arc const* a) { r(a); }); return r; } virtual void printArcsCout() const { // virtual preventing inlining for debugger printArcsOut(std::cout); } void printArcsOut(std::ostream& o, bool keepRepeats = false) const { forArcsOut(ArcPrinter<Arc>(o), keepRepeats); } void printArcsIn(std::ostream& o = std::cout) const { forArcsIn(ArcPrinter<Arc>(o)); } virtual void printArcs(std::ostream& o) const { forArcsOut(ArcPrinter<Arc>(o)); } void setWeight1() const { forArcsAllowRepeats(impl::ArcWeightSetOne<Arc>()); } // TODO: cache in props? bool unweighted() const { return countArcs().unweighted(); } IHypergraph(std::string const& typeStr = "sdl::IHypergraph") : HypergraphBase(typeStr) {} virtual IHypergraph<A>* clone() const override = 0; virtual ~IHypergraph() {} /** If your hypergraph is really an FSA you will naturally have one designated start state; if it's an actual hypergraph you can have an artificial start state point to all the axioms. */ /** Not directly returning the Arc pointers here because that would expose the internal container. */ virtual Arc* inArc(StateId state, ArcId aid) const override = 0; virtual Arc* outArc(StateId state, ArcId aid) const override = 0; virtual void outAdjStates(StateId st, StateIdContainer& adjStates) const { ArcId i = 0, N = this->numOutArcs(st); adjStates.resize(N); for (; i < N; ++i) adjStates[i] = this->outArc(st, i)->head_; } ArcsContainer inArcsCopy(StateId st) const { ArcsContainer r; inArcs(st, r); return r; } ArcsContainer outArcsCopy(StateId st) const { ArcsContainer r; outArcs(st, r); return r; } /// see Util/Generator.hpp typedef Util::AnyGenerator<Arc*, Util::NonPeekableT> ConstOutArcsGenerator; virtual ConstOutArcsGenerator outArcsConst(StateId state) const { assert(storesOutArcs()); SDL_THROW_LOG(Hypergraph, UnimplementedException, "outArcsConst"); // TODO-generator iterating over arc ids } /* appropriate only if the added arcs were made with new Arc(...) and would otherwise all leak. also: doesn't clear lists of arcs! call just before destroying a hypergraph, in other words */ virtual void deleteArcs() { forArcsSafe(impl::ArcDeleter<Arc>()); } bool isFsmCheck() const override; bool isGraphCheck(bool& isFsm, bool& oneLexical) const override; void printArc(std::ostream& out, ArcBase const* arc, bool inlineLabel) const override { Hypergraph::printArc<Arc>(out, (Arc*)arc, (HypergraphBase const*)this, inlineLabel); } typedef std::vector<Arc*> AllArcs; virtual void fetchArcs(AllArcs& arcs) const { arcs.reserve(this->estimatedNumEdges()); forArcs([&arcs](Arc* arc) { arcs.push_back(arc); }); } }; // end class IHypergraph template <class Arc> bool isEpsilonLikeGraphArc(IHypergraph<Arc> const& hg, Arc const& arc) { return isOne(arc.weight_) && isEpsilonLikeGraphArcAnyWeight(hg, arc); } template <class Arc> struct PrintInArcs { HypergraphBase const& hg; StateId s; PrintInArcs(IHypergraph<Arc> const& hg, StateId s) : hg(hg), s(s) { assert(hg.storesInArcs()); } friend inline std::ostream& operator<<(std::ostream& out, PrintInArcs const& self) { self.print(out); return out; } void print(std::ostream& out, bool pre = true) const { if (pre) out << " in[" << s << "]: "; hg.forArcsIn(s, ArcPrinter<Arc>(out)); } }; template <class Arc> PrintInArcs<Arc> printInArcs(IHypergraph<Arc> const& hg, StateId s) { return PrintInArcs<Arc>(hg, s); } template <class Arc> struct PrintOutArcs { IHypergraph<Arc> const& hg; StateId s; PrintOutArcs(IHypergraph<Arc> const& hg, StateId s) : hg(hg), s(s) { assert(hg.storesOutArcs()); } friend inline std::ostream& operator<<(std::ostream& out, PrintOutArcs const& self) { self.print(out); return out; } void print(std::ostream& out, bool pre = true) const { if (pre) out << " out[" << s << "]: "; hg.forArcsOut(s, ArcPrinter<Arc>(out)); } }; template <class Arc> PrintOutArcs<Arc> printOutArcs(IHypergraph<Arc> const& hg, StateId s) { return PrintOutArcs<Arc>(hg, s); } template <class Arc> struct ArcPrint { Arc const* arc; HypergraphBase const* hg; ArcPrint(Arc const* arc, HypergraphBase const* hg) : arc(arc), hg(hg) {} ArcPrint(Arc const* arc, HypergraphBase const& hg) : arc(arc), hg(&hg) {} friend inline std::ostream& operator<<(std::ostream& out, ArcPrint const& self) { self.print(out); return out; } void print(std::ostream& out) const { printArc(out, arc, hg); } }; template <class Arc> ArcPrint<Arc> arcPrint(Arc const* arc, HypergraphBase const& hg) { return ArcPrint<Arc>(arc, hg); } template <class Arc> ArcPrint<Arc> arcPrint(Arc const* arc, HypergraphBase const* hg) { return ArcPrint<Arc>(arc, hg); } template <class Arc> void print(std::ostream& out, Arc const& arc, IHypergraph<Arc> const* hg) { printArc(out, &arc, hg); } template <class Arc> void print(std::ostream& out, Arc const* arc, IHypergraph<Arc> const* hg) { printArc(out, arc, hg); } template <class Arc> void print(std::ostream& out, Arc const& arc, IHypergraph<Arc> const& hg) { printArc(out, &arc, hg); } template <class Arc> void print(std::ostream& out, Arc const* arc, IHypergraph<Arc> const& hg) { printArc(out, arc, hg); } } } #include <sdl/Hypergraph/src/IHypergraph.ipp> #endif
#include "testing/testing.hpp" #include "base/logging.hpp" #include <utility> #include <vector> namespace { void TestLogMessage(my::LogLevel, my::SrcPoint const &, std::string const &) { } bool g_SomeFunctionCalled; int SomeFunction() { g_SomeFunctionCalled = true; return 3; } } UNIT_TEST(Logging_Level) { my::LogLevel const logLevelSaved = my::g_LogLevel; my::g_LogLevel = LWARNING; g_SomeFunctionCalled = false; my::LogMessageFn logMessageSaved = my::SetLogMessageFn(&TestLogMessage); LOG(LINFO, ("This should not pass", SomeFunction())); TEST(!g_SomeFunctionCalled, ()); LOG(LWARNING, ("This should pass", SomeFunction())); TEST(g_SomeFunctionCalled, ()); my::SetLogMessageFn(logMessageSaved); my::g_LogLevel = logLevelSaved; } UNIT_TEST(NullMessage) { char const * ptr = 0; LOG(LINFO, ("Null message test", ptr)); }
#pragma once #include <SDL2/SDL.h> #include "Common.hpp" class EventHandler { public: void HandleEvents(); bool ShouldClose(); private: bool m_ShouldClose = false; };
// Copyright 2009 Mark Leone (markleone@gmail.com). All rights reserved. // Licensed under the terms of the MIT License. // See http://www.opensource.org/licenses/mit-license.php. #include "cg/CgConst.h" #include "cg/CgTypes.h" #include "ir/IRValues.h" #include "util/UtCast.h" #include <llvm/Constants.h> #include <llvm/DerivedTypes.h> #include <llvm/ADT/SmallVector.h> #include <llvm/GlobalVariable.h> #include <llvm/Support/IRBuilder.h> // Convert an IR constant to an LLVM constant. llvm::Constant* CgConst::Convert(const IRConst* constant) const { if (const IRNumConst* c = UtCast<const IRNumConst*>(constant)) return ConvertNumData(c->GetData(), c->GetType()); if (const IRNumArrayConst* c = UtCast<const IRNumArrayConst*>(constant)) return ConvertNumArray(c); if (const IRStringConst* c = UtCast<const IRStringConst*>(constant)) return ConvertStringData(c->Get()); if (const IRStringArrayConst* c = UtCast<const IRStringArrayConst*>(constant)) return ConvertStringArray(c); assert(false && "Unimplemented kind of constant"); return NULL; } /// Convert numeric constant data llvm::Constant* CgConst::ConvertNumData(const float* data, const IRType* ty) const { // Float constant? if (ty->IsFloat()) { llvm::Type* floatTy = llvm::Type::getFloatTy(*mContext); return llvm::ConstantFP::get(floatTy, data[0]); } // Triple? if (ty->IsTriple()) return MakeVector(data, 3); // Otherwise it must be a matrix. assert(ty->IsMatrix() && "Expected matrix constant"); return MakeMatrix(data); } /// Make a float constant. llvm::Constant* CgConst::MakeFloat(float f) const { llvm::Type* floatTy = llvm::Type::getFloatTy(*mContext); return llvm::ConstantFP::get(floatTy, f); } // Make a float array constant. llvm::Constant* CgConst::MakeFloatArray(const float* data, unsigned int length) const { llvm::Type* floatTy = llvm::Type::getFloatTy(*mContext); std::vector<llvm::Constant*> elements(length); for (unsigned int i = 0; i < length; ++i) elements[i] = llvm::ConstantFP::get(floatTy, data[i]); llvm::ArrayType* arrayTy = llvm::ArrayType::get(floatTy, length); return llvm::ConstantArray::get(arrayTy, elements); } // Make a vector constant, which is a struct containing a float array. // Note: this must agree with the definition of OpVec3. llvm::Constant* CgConst::MakeVector(const float* data, unsigned int length) const { std::vector<llvm::Constant*> members(3); members[0] = MakeFloat(data[0]); members[1] = MakeFloat(data[1]); members[2] = MakeFloat(data[2]); llvm::StructType* vecTy = llvm::dyn_cast<llvm::StructType>(mTypes->GetVecTy()); assert(vecTy != NULL && "Expected vector type to be an llvm::StructType"); return llvm::ConstantStruct::get(vecTy, llvm::ArrayRef<llvm::Constant*>(members)); } // Make a matrix constant, which is a struct containing an array of 4-vectors. // Note: this must agree with the definition of OpMatrix4. llvm::Constant* CgConst::MakeMatrix(const float* data) const { std::vector<llvm::Constant*> rows(4); for (int i = 0; i < 4; ++i) { rows[i] = MakeFloatArray(data, 4); data += 4; } llvm::Type* rowTy = rows[0]->getType(); llvm::ArrayType* arrayTy = llvm::ArrayType::get(rowTy, 4); llvm::Constant* array = llvm::ConstantArray::get(arrayTy, rows); llvm::StructType* matrixTy = llvm::dyn_cast<llvm::StructType>(mTypes->GetMatrixTy()); assert(matrixTy != NULL && "Expected matrix type to be an llvm::StructType"); return llvm::ConstantStruct::get(matrixTy, llvm::ArrayRef<llvm::Constant*>(&array, 1)); } llvm::Constant* CgConst::ConvertNumArray(const IRNumArrayConst* array) const { // Get the element type. const IRArrayType* arrayTy = UtStaticCast<const IRArrayType*>(array->GetType()); const IRType* elemTy = arrayTy->GetElementType(); // Get the data, length, and stride. const float* data = array->GetData(); unsigned int length = array->GetLength(); assert((int) length == arrayTy->GetLength() && "Array constant length mismatch"); unsigned int stride = elemTy->GetSize(); // Convert the elements std::vector<llvm::Constant*> elements(length); for (unsigned int i = 0; i < length; ++i) { elements[i] = ConvertNumData(data, elemTy); data += stride; } // Construct array type and construct an LLVM array constant. llvm::ArrayType* llvmTy = llvm::ArrayType::get(mTypes->Convert(elemTy), length); return llvm::ConstantArray::get(llvmTy, elements); } llvm::Constant* CgConst::ConvertStringData(const char* str) const { // Create a char array constant. // XXX use IRBuilder::CreateGlobalString instead. llvm::Constant* array = llvm::ConstantArray::get(*mContext, str, true); // Store the char array in a global constant. llvm::GlobalVariable* global = new llvm::GlobalVariable(*mModule, array->getType(), true, llvm::GlobalValue::InternalLinkage, array, ""); // Return a constant "getelementptr" expression that points to the first // character. llvm::Constant* zero = GetInt(0); llvm::Constant* indices[] = { zero, zero }; return llvm::ConstantExpr::getGetElementPtr(global, indices, 2); } llvm::Constant* CgConst::ConvertStringArray(const IRStringArrayConst* array) const { // Construct array type and construct an undefined array value. llvm::Type* charTy = llvm::Type::getInt8Ty(*mContext); llvm::Type* stringTy = llvm::PointerType::get(charTy, CgTypes::kDefaultAddressSpace); llvm::Type* arrayTy = llvm::ArrayType::get(stringTy, array->GetLength()); llvm::Constant* arrayVal = llvm::UndefValue::get(arrayTy); // Insert the string constants into the array. unsigned int length = array->GetLength(); for (unsigned int i = 0; i < length; ++i) { llvm::Constant* stringVal = ConvertStringData(array->GetElement(i)); arrayVal = llvm::ConstantExpr::getInsertValue(arrayVal, stringVal, llvm::ArrayRef<unsigned>(&i, 1)); } return arrayVal; }
#include "hypotnode.h" HypotNode::HypotNode() { this->setTitle("Hypot"); this->setHeight(180); this->setWidth(150); this->setPanelColor(QColor(121,159,12)); this->setPanelGradColor(QColor(255,224,0)); this->functionName="math.hypot"; Port p1; p1.Parent=this; p1.Position=QPoint(20,80); p1.PortColor=this->panelColor(); Port p2; p2.Parent=this; p2.Position=QPoint(20,130); p2.PortColor=this->panelColor(); this->inputPort.push_back(p1); this->inputPort.push_back(p2); Port p3; p3.Parent=this; p3.Position=QPoint(125,105); p3.PortColor=this->panelGradColor(); p3.Type=PortType::OutPut; this->outputPort.push_back(p3); Label l1; l1.Text="X"; l1.Pos=QPoint(40,90); Label l2; l2.Text="Y"; l2.Pos=QPoint(40,140); this->labelList.push_back(l1); this->labelList.push_back(l2); }
// Copyright 2017 The Ray 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 "jni_utils.h" jclass java_boolean_class; jmethodID java_boolean_init; jclass java_double_class; jmethodID java_double_double_value; jclass java_long_class; jmethodID java_long_init; jclass java_object_class; jmethodID java_object_equals; jmethodID java_object_hash_code; jclass java_weak_reference_class; jmethodID java_weak_reference_init; jmethodID java_weak_reference_get; jclass java_list_class; jmethodID java_list_size; jmethodID java_list_get; jmethodID java_list_add; jclass java_array_list_class; jmethodID java_array_list_init; jmethodID java_array_list_init_with_capacity; jclass java_map_class; jmethodID java_map_entry_set; jmethodID java_map_put; jclass java_hash_map_class; jmethodID java_hash_map_init; jclass java_set_class; jmethodID java_set_iterator; jclass java_iterator_class; jmethodID java_iterator_has_next; jmethodID java_iterator_next; jclass java_map_entry_class; jmethodID java_map_entry_get_key; jmethodID java_map_entry_get_value; jclass java_system_class; jmethodID java_system_gc; jclass java_ray_exception_class; jclass java_ray_intentional_system_exit_exception_class; jclass java_ray_timeout_exception_class; jclass java_ray_pending_calls_limit_exceeded_exception_class; jclass java_ray_actor_exception_class; jclass java_ray_exception_serializer_class; jmethodID java_ray_exception_serializer_to_bytes; jclass java_jni_exception_util_class; jmethodID java_jni_exception_util_get_stack_trace; jclass java_base_id_class; jmethodID java_base_id_get_bytes; jclass java_abstract_message_lite_class; jmethodID java_abstract_message_lite_to_byte_array; jclass java_function_descriptor_class; jmethodID java_function_descriptor_get_language; jmethodID java_function_descriptor_to_list; jclass java_language_class; jmethodID java_language_get_number; jclass java_function_arg_class; jfieldID java_function_arg_id; jfieldID java_function_arg_owner_address; jfieldID java_function_arg_value; jclass java_base_task_options_class; jfieldID java_base_task_options_resources; jclass java_call_options_class; jfieldID java_call_options_name; jfieldID java_task_creation_options_group; jfieldID java_task_creation_options_bundle_index; jfieldID java_call_options_concurrency_group_name; jfieldID java_call_options_serialized_runtime_env_info; jclass java_actor_creation_options_class; jfieldID java_actor_creation_options_name; jfieldID java_actor_creation_options_lifetime; jfieldID java_actor_creation_options_max_restarts; jfieldID java_actor_creation_options_jvm_options; jfieldID java_actor_creation_options_max_concurrency; jfieldID java_actor_creation_options_group; jfieldID java_actor_creation_options_bundle_index; jfieldID java_actor_creation_options_concurrency_groups; jfieldID java_actor_creation_options_serialized_runtime_env; jfieldID java_actor_creation_options_max_pending_calls; jclass java_actor_lifetime_class; jobject STATUS_DETACHED; jclass java_placement_group_creation_options_class; jclass java_placement_group_creation_options_strategy_class; jfieldID java_placement_group_creation_options_name; jfieldID java_placement_group_creation_options_bundles; jfieldID java_placement_group_creation_options_strategy; jmethodID java_placement_group_creation_options_strategy_value; jclass java_gcs_client_options_class; jfieldID java_gcs_client_options_ip; jfieldID java_gcs_client_options_port; jfieldID java_gcs_client_options_password; jclass java_native_ray_object_class; jmethodID java_native_ray_object_init; jfieldID java_native_ray_object_data; jfieldID java_native_ray_object_metadata; jfieldID java_native_ray_object_contained_object_ids; jclass java_task_executor_class; jmethodID java_task_executor_parse_function_arguments; jmethodID java_task_executor_execute; jclass java_concurrency_group_impl_class; jmethodID java_concurrency_group_impl_get_function_descriptors; jfieldID java_concurrency_group_impl_name; jfieldID java_concurrency_group_impl_max_concurrency; jclass java_native_task_executor_class; jmethodID java_native_task_executor_on_worker_shutdown; jclass java_placement_group_class; jfieldID java_placement_group_id; jclass java_object_ref_impl_class; jmethodID java_object_ref_impl_class_on_memory_store_object_allocated; jclass java_resource_value_class; jmethodID java_resource_value_init; JavaVM *jvm; inline jclass LoadClass(JNIEnv *env, const char *class_name) { jclass tempLocalClassRef = env->FindClass(class_name); if (tempLocalClassRef == nullptr) { const std::string shaded_class_prefix = "io/ray/shaded/"; const auto class_name_str = std::string(class_name); const auto this_prefix = class_name_str.substr(0, shaded_class_prefix.size()); if (this_prefix == shaded_class_prefix) { // This is a shaded class, and try to load the original class. env->ExceptionClear(); auto no_shaded_class_name = class_name_str.substr(shaded_class_prefix.size(), class_name_str.size()); tempLocalClassRef = env->FindClass(no_shaded_class_name.c_str()); } } RAY_CHECK(tempLocalClassRef) << "Can't load Java class " << class_name; jclass ret = (jclass)env->NewGlobalRef(tempLocalClassRef); RAY_CHECK(ret) << "Can't load Java class " << class_name; env->DeleteLocalRef(tempLocalClassRef); return ret; } /// Load and cache frequently-used Java classes and methods jint JNI_OnLoad(JavaVM *vm, void *reserved) { JNIEnv *env; if (vm->GetEnv(reinterpret_cast<void **>(&env), CURRENT_JNI_VERSION) != JNI_OK) { return JNI_ERR; } jvm = vm; java_boolean_class = LoadClass(env, "java/lang/Boolean"); java_boolean_init = env->GetMethodID(java_boolean_class, "<init>", "(Z)V"); java_double_class = LoadClass(env, "java/lang/Double"); java_double_double_value = env->GetMethodID(java_double_class, "doubleValue", "()D"); java_long_class = LoadClass(env, "java/lang/Long"); java_long_init = env->GetMethodID(java_long_class, "<init>", "(J)V"); java_object_class = LoadClass(env, "java/lang/Object"); java_object_equals = env->GetMethodID(java_object_class, "equals", "(Ljava/lang/Object;)Z"); java_object_hash_code = env->GetMethodID(java_object_class, "hashCode", "()I"); java_weak_reference_class = LoadClass(env, "java/lang/ref/WeakReference"); java_weak_reference_init = env->GetMethodID(java_weak_reference_class, "<init>", "(Ljava/lang/Object;)V"); java_weak_reference_get = env->GetMethodID(java_weak_reference_class, "get", "()Ljava/lang/Object;"); java_list_class = LoadClass(env, "java/util/List"); java_list_size = env->GetMethodID(java_list_class, "size", "()I"); java_list_get = env->GetMethodID(java_list_class, "get", "(I)Ljava/lang/Object;"); java_list_add = env->GetMethodID(java_list_class, "add", "(Ljava/lang/Object;)Z"); java_array_list_class = LoadClass(env, "java/util/ArrayList"); java_array_list_init = env->GetMethodID(java_array_list_class, "<init>", "()V"); java_array_list_init_with_capacity = env->GetMethodID(java_array_list_class, "<init>", "(I)V"); java_map_class = LoadClass(env, "java/util/Map"); java_map_entry_set = env->GetMethodID(java_map_class, "entrySet", "()Ljava/util/Set;"); java_map_put = env->GetMethodID( java_map_class, "put", "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;"); java_hash_map_class = LoadClass(env, "java/util/HashMap"); java_hash_map_init = env->GetMethodID(java_hash_map_class, "<init>", "()V"); java_set_class = LoadClass(env, "java/util/Set"); java_set_iterator = env->GetMethodID(java_set_class, "iterator", "()Ljava/util/Iterator;"); java_iterator_class = LoadClass(env, "java/util/Iterator"); java_iterator_has_next = env->GetMethodID(java_iterator_class, "hasNext", "()Z"); java_iterator_next = env->GetMethodID(java_iterator_class, "next", "()Ljava/lang/Object;"); java_map_entry_class = LoadClass(env, "java/util/Map$Entry"); java_map_entry_get_key = env->GetMethodID(java_map_entry_class, "getKey", "()Ljava/lang/Object;"); java_map_entry_get_value = env->GetMethodID(java_map_entry_class, "getValue", "()Ljava/lang/Object;"); java_system_class = LoadClass(env, "java/lang/System"); java_system_gc = env->GetStaticMethodID(java_system_class, "gc", "()V"); java_ray_exception_class = LoadClass(env, "io/ray/api/exception/RayException"); java_ray_intentional_system_exit_exception_class = LoadClass(env, "io/ray/api/exception/RayIntentionalSystemExitException"); java_ray_timeout_exception_class = LoadClass(env, "io/ray/api/exception/RayTimeoutException"); java_ray_actor_exception_class = LoadClass(env, "io/ray/api/exception/RayActorException"); java_ray_pending_calls_limit_exceeded_exception_class = LoadClass(env, "io/ray/api/exception/PendingCallsLimitExceededException"); java_ray_exception_serializer_class = LoadClass(env, "io/ray/runtime/serializer/RayExceptionSerializer"); java_ray_exception_serializer_to_bytes = env->GetStaticMethodID(java_ray_exception_serializer_class, "toBytes", "(Lio/ray/api/exception/RayException;)[B"); java_jni_exception_util_class = LoadClass(env, "io/ray/runtime/util/JniExceptionUtil"); java_jni_exception_util_get_stack_trace = env->GetStaticMethodID( java_jni_exception_util_class, "getStackTrace", "(Ljava/lang/String;ILjava/lang/String;Ljava/lang/Throwable;)Ljava/lang/String;"); java_base_id_class = LoadClass(env, "io/ray/api/id/BaseId"); java_base_id_get_bytes = env->GetMethodID(java_base_id_class, "getBytes", "()[B"); java_abstract_message_lite_class = LoadClass(env, "io/ray/shaded/com/google/protobuf/AbstractMessage"); java_abstract_message_lite_to_byte_array = env->GetMethodID(java_abstract_message_lite_class, "toByteArray", "()[B"); java_function_descriptor_class = LoadClass(env, "io/ray/runtime/functionmanager/FunctionDescriptor"); java_function_descriptor_get_language = env->GetMethodID(java_function_descriptor_class, "getLanguage", "()Lio/ray/runtime/generated/Common$Language;"); java_function_descriptor_to_list = env->GetMethodID(java_function_descriptor_class, "toList", "()Ljava/util/List;"); java_language_class = LoadClass(env, "io/ray/runtime/generated/Common$Language"); java_language_get_number = env->GetMethodID(java_language_class, "getNumber", "()I"); java_function_arg_class = LoadClass(env, "io/ray/runtime/task/FunctionArg"); java_function_arg_id = env->GetFieldID(java_function_arg_class, "id", "Lio/ray/api/id/ObjectId;"); java_function_arg_owner_address = env->GetFieldID(java_function_arg_class, "ownerAddress", "Lio/ray/runtime/generated/Common$Address;"); java_function_arg_value = env->GetFieldID( java_function_arg_class, "value", "Lio/ray/runtime/object/NativeRayObject;"); java_base_task_options_class = LoadClass(env, "io/ray/api/options/BaseTaskOptions"); java_base_task_options_resources = env->GetFieldID(java_base_task_options_class, "resources", "Ljava/util/Map;"); java_call_options_class = LoadClass(env, "io/ray/api/options/CallOptions"); java_call_options_name = env->GetFieldID(java_call_options_class, "name", "Ljava/lang/String;"); java_task_creation_options_group = env->GetFieldID( java_call_options_class, "group", "Lio/ray/api/placementgroup/PlacementGroup;"); java_task_creation_options_bundle_index = env->GetFieldID(java_call_options_class, "bundleIndex", "I"); java_call_options_concurrency_group_name = env->GetFieldID( java_call_options_class, "concurrencyGroupName", "Ljava/lang/String;"); java_call_options_serialized_runtime_env_info = env->GetFieldID( java_call_options_class, "serializedRuntimeEnvInfo", "Ljava/lang/String;"); java_placement_group_class = LoadClass(env, "io/ray/runtime/placementgroup/PlacementGroupImpl"); java_placement_group_id = env->GetFieldID( java_placement_group_class, "id", "Lio/ray/api/id/PlacementGroupId;"); java_placement_group_creation_options_class = LoadClass(env, "io/ray/api/options/PlacementGroupCreationOptions"); java_placement_group_creation_options_strategy_class = LoadClass(env, "io/ray/api/placementgroup/PlacementStrategy"); java_placement_group_creation_options_name = env->GetFieldID( java_placement_group_creation_options_class, "name", "Ljava/lang/String;"); java_placement_group_creation_options_bundles = env->GetFieldID( java_placement_group_creation_options_class, "bundles", "Ljava/util/List;"); java_placement_group_creation_options_strategy = env->GetFieldID(java_placement_group_creation_options_class, "strategy", "Lio/ray/api/placementgroup/PlacementStrategy;"); java_placement_group_creation_options_strategy_value = env->GetMethodID( java_placement_group_creation_options_strategy_class, "value", "()I"); java_actor_creation_options_class = LoadClass(env, "io/ray/api/options/ActorCreationOptions"); java_actor_creation_options_name = env->GetFieldID(java_actor_creation_options_class, "name", "Ljava/lang/String;"); java_actor_creation_options_lifetime = env->GetFieldID(java_actor_creation_options_class, "lifetime", "Lio/ray/api/options/ActorLifetime;"); java_actor_creation_options_max_restarts = env->GetFieldID(java_actor_creation_options_class, "maxRestarts", "I"); java_actor_creation_options_jvm_options = env->GetFieldID( java_actor_creation_options_class, "jvmOptions", "Ljava/util/List;"); java_actor_creation_options_max_concurrency = env->GetFieldID(java_actor_creation_options_class, "maxConcurrency", "I"); java_actor_creation_options_group = env->GetFieldID(java_actor_creation_options_class, "group", "Lio/ray/api/placementgroup/PlacementGroup;"); java_actor_creation_options_bundle_index = env->GetFieldID(java_actor_creation_options_class, "bundleIndex", "I"); java_actor_creation_options_concurrency_groups = env->GetFieldID( java_actor_creation_options_class, "concurrencyGroups", "Ljava/util/List;"); java_actor_creation_options_serialized_runtime_env = env->GetFieldID( java_actor_creation_options_class, "serializedRuntimeEnv", "Ljava/lang/String;"); java_actor_creation_options_max_pending_calls = env->GetFieldID(java_actor_creation_options_class, "maxPendingCalls", "I"); java_actor_lifetime_class = LoadClass(env, "io/ray/api/options/ActorLifetime"); jfieldID java_actor_lifetime_detached_field = env->GetStaticFieldID( java_actor_lifetime_class, "DETACHED", "Lio/ray/api/options/ActorLifetime;"); STATUS_DETACHED = env->GetStaticObjectField(java_actor_lifetime_class, java_actor_lifetime_detached_field); java_concurrency_group_impl_class = LoadClass(env, "io/ray/runtime/ConcurrencyGroupImpl"); java_concurrency_group_impl_get_function_descriptors = env->GetMethodID( java_concurrency_group_impl_class, "getFunctionDescriptors", "()Ljava/util/List;"); java_concurrency_group_impl_name = env->GetFieldID(java_concurrency_group_impl_class, "name", "Ljava/lang/String;"); java_concurrency_group_impl_max_concurrency = env->GetFieldID(java_concurrency_group_impl_class, "maxConcurrency", "I"); java_gcs_client_options_class = LoadClass(env, "io/ray/runtime/gcs/GcsClientOptions"); java_gcs_client_options_ip = env->GetFieldID(java_gcs_client_options_class, "ip", "Ljava/lang/String;"); java_gcs_client_options_port = env->GetFieldID(java_gcs_client_options_class, "port", "I"); java_gcs_client_options_password = env->GetFieldID(java_gcs_client_options_class, "password", "Ljava/lang/String;"); java_native_ray_object_class = LoadClass(env, "io/ray/runtime/object/NativeRayObject"); java_native_ray_object_init = env->GetMethodID(java_native_ray_object_class, "<init>", "([B[B)V"); java_native_ray_object_data = env->GetFieldID(java_native_ray_object_class, "data", "[B"); java_native_ray_object_metadata = env->GetFieldID(java_native_ray_object_class, "metadata", "[B"); java_native_ray_object_contained_object_ids = env->GetFieldID( java_native_ray_object_class, "containedObjectIds", "Ljava/util/List;"); java_task_executor_class = LoadClass(env, "io/ray/runtime/task/TaskExecutor"); java_task_executor_parse_function_arguments = env->GetMethodID( java_task_executor_class, "checkByteBufferArguments", "(Ljava/util/List;)[Z"); java_task_executor_execute = env->GetMethodID(java_task_executor_class, "execute", "(Ljava/util/List;Ljava/util/List;)Ljava/util/List;"); java_native_task_executor_class = LoadClass(env, "io/ray/runtime/task/NativeTaskExecutor"); java_native_task_executor_on_worker_shutdown = env->GetMethodID(java_native_task_executor_class, "onWorkerShutdown", "([B)V"); java_object_ref_impl_class = LoadClass(env, "io/ray/runtime/object/ObjectRefImpl"); java_object_ref_impl_class_on_memory_store_object_allocated = env->GetStaticMethodID( java_object_ref_impl_class, "onMemoryStoreObjectAllocated", "([B[B)V"); java_resource_value_class = LoadClass(env, "io/ray/api/runtimecontext/ResourceValue"); java_resource_value_init = env->GetMethodID(java_resource_value_class, "<init>", "(JD)V"); return CURRENT_JNI_VERSION; } /// Unload java classes void JNI_OnUnload(JavaVM *vm, void *reserved) { JNIEnv *env; vm->GetEnv(reinterpret_cast<void **>(&env), CURRENT_JNI_VERSION); env->DeleteGlobalRef(java_boolean_class); env->DeleteGlobalRef(java_double_class); env->DeleteGlobalRef(java_object_class); env->DeleteGlobalRef(java_weak_reference_class); env->DeleteGlobalRef(java_long_class); env->DeleteGlobalRef(java_list_class); env->DeleteGlobalRef(java_array_list_class); env->DeleteGlobalRef(java_map_class); env->DeleteGlobalRef(java_hash_map_class); env->DeleteGlobalRef(java_set_class); env->DeleteGlobalRef(java_iterator_class); env->DeleteGlobalRef(java_map_entry_class); env->DeleteGlobalRef(java_system_class); env->DeleteGlobalRef(java_ray_exception_class); env->DeleteGlobalRef(java_ray_intentional_system_exit_exception_class); env->DeleteGlobalRef(java_ray_timeout_exception_class); env->DeleteGlobalRef(java_ray_actor_exception_class); env->DeleteGlobalRef(java_ray_exception_serializer_class); env->DeleteGlobalRef(java_jni_exception_util_class); env->DeleteGlobalRef(java_base_id_class); env->DeleteGlobalRef(java_abstract_message_lite_class); env->DeleteGlobalRef(java_function_descriptor_class); env->DeleteGlobalRef(java_language_class); env->DeleteGlobalRef(java_function_arg_class); env->DeleteGlobalRef(java_base_task_options_class); env->DeleteGlobalRef(java_actor_creation_options_class); env->DeleteGlobalRef(java_actor_lifetime_class); env->DeleteGlobalRef(java_placement_group_creation_options_class); env->DeleteGlobalRef(java_placement_group_creation_options_strategy_class); env->DeleteGlobalRef(java_native_ray_object_class); env->DeleteGlobalRef(java_task_executor_class); env->DeleteGlobalRef(java_native_task_executor_class); env->DeleteGlobalRef(java_concurrency_group_impl_class); env->DeleteGlobalRef(java_resource_value_class); }
// Copyright 2017 PDFium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Original code copyright 2014 Foxit Software Inc. http://www.foxitsoftware.com #include "xfa/fxfa/cxfa_ffrectangle.h" #include "xfa/fxfa/parser/cxfa_rectangle.h" #include "xfa/fxfa/parser/cxfa_value.h" CXFA_FFRectangle::CXFA_FFRectangle(CXFA_Node* pNode) : CXFA_FFWidget(pNode) {} CXFA_FFRectangle::~CXFA_FFRectangle() {} void CXFA_FFRectangle::RenderWidget(CXFA_Graphics* pGS, const CFX_Matrix& matrix, HighlightOption highlight) { if (!HasVisibleStatus()) return; CXFA_Value* value = m_pNode->GetFormValueIfExists(); if (!value) return; CFX_RectF rect = GetRectWithoutRotate(); CXFA_Margin* margin = m_pNode->GetMarginIfExists(); XFA_RectWithoutMargin(&rect, margin); CFX_Matrix mtRotate = GetRotateMatrix(); mtRotate.Concat(matrix); DrawBorder(pGS, value->GetRectangleIfExists(), rect, mtRotate); }
#include <stdlib.h> #include <stdio.h> #include <conio.h> struct K_Daten { char Name[20]; int Kontonummer; double Kontostand; int passwort[12]; }; void Eingabe (struct K_Daten *); void Ausgabe (struct K_Daten); int main() { struct K_Daten Kunde; system("cls"); Eingabe(&Kunde); Ausgabe(Kunde); system ("Pause"); return 0; } void Eingabe (struct K_Daten * E_Kunde) { printf("Eingabe Kundendaten : \n\n"); printf("Name :"); scanf("%s",E_Kunde->Name); printf("Kontonr :"); scanf("%d",&E_Kunde->Kontonummer); printf("Kontostand :"); scanf("%lf",&E_Kunde->Kontostand); } void Ausgabe (struct K_Daten A_Kunde) { printf("Kundendaten :Name %sKontonummer %d Kontostand%lf\n\n",A_Kunde.Name,A_Kunde.Kontonummer,A_Kunde.Kontostand); }
class Car { public: Car(); void accelerate(); static int whichIsFaster(Car carA, Car carB); private: float speed; }; Car::Car() : speed(0.0f) { } void Car::accelerate() { speed += 0.5f; } int Car::whichIsFaster(Car carA, Car carB) { if(carA.speed > carB.speed) { return 0; } return 1; } int main() { Car car1{}; car1.accelerate(); // state of car1 - speed is 1.5 Car car2; car2.accelerate(); car2.accelerate(); // static functions don't need to remember or access the state of the function Car::whichIsFaster(car1, car2); }