blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
sequencelengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
905 values
visit_date
timestamp[us]date
2015-08-09 11:21:18
2023-09-06 10:45:07
revision_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-17 19:19:19
committer_date
timestamp[us]date
1997-09-14 05:04:47
2023-09-06 06:22:19
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
22 values
gha_event_created_at
timestamp[us]date
2012-06-07 00:51:45
2023-09-14 21:58:39
gha_created_at
timestamp[us]date
2008-03-27 23:40:48
2023-08-21 23:17:38
gha_language
stringclasses
141 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
115 values
content
stringlengths
3
10.4M
authors
sequencelengths
1
1
author_id
stringlengths
0
158
fda12e39ca8f790c9ed0cca337daa03175a02ceb
b1f475245f859009aa36b7a173350c392bf8a62a
/hw7/hw7_q1/hw7_q1.cpp
0af9ecde8050b629e80fd66db5ec5324a22a0879
[]
no_license
NaveganteX/NYU-Bridge
98e55bd4520aab4e8c1d3e51a3392e03bb101dde
869e1be7ca30113d1522b90597967ae3bed083af
refs/heads/master
2022-07-08T06:24:42.543523
2020-05-17T16:24:57
2020-05-17T16:24:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,832
cpp
#include <iostream> #include <string> using namespace std; int printMonthCalendar(int numOfDays, int startingDay); bool isLeapYear(int year); int printYearCalendar(int year, int startingDay); int main() { int year = 0, firstDay = 0; cout << "Please enter a year: "; cin >> year; cout << "Enter the first day of the month (1-Mon, 2-Tues): "; cin >> firstDay; cout << endl; printYearCalendar(year, firstDay); return 0; } int printMonthCalendar(int numOfDays, int startingDay) { cout << "Mon\tTue\tWed\tThr\tFri\tSat\tSun" << endl; for (int i = 1; i < startingDay; i++) { cout << "\t"; } int dayCount = startingDay; for (int i = 1; i <= numOfDays; i++) { cout << i << "\t"; if ((i + startingDay - 1) % 7 == 0) { if (i != numOfDays) { cout << endl; } } dayCount++; if (dayCount == 8) { dayCount = 1; } } return dayCount; } int printYearCalendar(int year, int startingDay) { int daysInMonth = 0, offSet = 0; string month; for (int i = 1; i <= 12; i++) { if (i == 1) { month = "January"; daysInMonth = 31; } else if (i == 2) { month = "February"; if (isLeapYear(year)) { daysInMonth = 29; } else { daysInMonth = 28; } } else if (i == 3) { month = "March"; daysInMonth = 31; } else if (i == 4) { month = "April"; daysInMonth = 30; } else if (i == 5) { month = "May"; daysInMonth = 31; } else if (i == 6) { month = "June"; daysInMonth = 30; } else if (i == 7) { month = "July"; daysInMonth = 31; } else if (i == 8) { month = "August"; daysInMonth = 31; } else if (i == 9) { month = "September"; daysInMonth = 30; } else if (i == 10) { month = "October"; daysInMonth = 31; } else if (i == 11) { month = "November"; daysInMonth = 30; } else if (i == 12) { month = "December"; daysInMonth = 31; } cout << month << " " << year << endl; if (i == 1) { offSet = printMonthCalendar(daysInMonth, startingDay); } else { offSet = printMonthCalendar(daysInMonth, offSet); } cout << endl; cout << endl; } return 0; } bool isLeapYear(int year) { if ((year % 4) != 0) { return false; } else if ((year % 100) != 0) { return true; } else if ((year % 400) != 0) { return false; } return true; }
15455f5cd23a5b75111a09139aac1b21fa416cb8
054fbc9ca03e4ef0c06b448ac2215a4a5ee308c1
/Chiller Code/Chiller.cpp
d4136324112b4b084d808ceb73337f7515030476
[]
no_license
mlab-upenn/chiller_model
5c3f1cb9b1a0a59d52f3a269ad4aeb0559d714e6
adb3ea845eaa49892a394632010553ab0734dd61
refs/heads/master
2020-12-28T20:55:21.355955
2014-01-27T22:12:28
2014-01-27T22:12:28
16,287,888
1
0
null
null
null
null
UTF-8
C++
false
false
4,057
cpp
// Chiller.cpp : Defines the entry point for the console application. // #include <math.h> #include <mex.h> #include "Headers\Protos.h" #include "Headers\Properties.h" #include "Headers\Components.h" #include "Headers\NumRecipes.h" #include "Headers\ErrorLog.h" ErrorLog errorlog; #define N_NODES_C 15 #define N_NODES_E 15 // Input arguments #define T_IN prhs[0] #define U_IN prhs[1] // Output arguments #define Y_OUT plhs[0] #define X_OUT plhs[1] //Global System instance VapCompCentLiqChiller* chiller = NULL; //USAGE: y = Chiller(t,u) // // y = outputs // t = time // u = inputs // // Each call to Chiller runs the simulation for t secs, using inputs u, held constant over this time. // The outputs of the system are passed out at the end of that time. void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { double *t, *u, *y; unsigned int m,n; int i; if((nrhs!=1&&nrhs!=2)||(nrhs==1&&nlhs!=0)||(nrhs==2&&nlhs!=1)) { mexErrMsgTxt("Invalid call to chiller routine."); return; } //Instantiate a chiller if none exists, clear existing errorlog if(chiller==NULL) { chiller = new VapCompCentLiqChiller(); if(chiller==NULL) { mexErrMsgTxt("Cannot create engine."); return; } if(!chiller->fnDefineGeometry()) { errorlog.Add("System construction failed."); return; } if(errorlog.IsError()) errorlog.ClearError(); } if(nrhs==1) //Initialization/save/restore mode { m = mxGetM(T_IN); n = mxGetN(T_IN); if(!mxIsNumeric(T_IN)||mxIsComplex(T_IN)||mxIsSparse(T_IN)||!mxIsDouble(T_IN)||m!=1||n!=1) mexErrMsgTxt("Initialization code needs to be an integer."); t = mxGetPr(T_IN); if((int)t[0]!=0&&(int)t[0]!=1&&(int)t[0]!=2&&(int)t[0]!=3) mexErrMsgTxt("Invalid argument value."); if((int)t[0]==2) //Save current state { if(!chiller->fnSaveState("IOFiles\\SavedState.txt")) { errorlog.Add("System state could not be saved."); mexErrMsgTxt("System state could not be saved."); return; } } else if((int)t[0]==3) //Restore saved state { if(!chiller->fnLoadState("IOFiles\\SavedState.txt")) { errorlog.Add("System state could not be loaded."); mexErrMsgTxt("System state could not be loaded."); return; } } else //Initialize { if(chiller->fnInitialized()) mexWarnMsgTxt("Existing initialization is now overwritten."); if(!chiller->fnLoadState((int)t[0])) { errorlog.Add("System initialization failed."); mexErrMsgTxt("System initialization failed."); return; } } } else //Execution mode { //Check if system has been initalized if(!chiller->fnInitialized()) mexErrMsgTxt("Chiller not initialized."); //Check the first argument and make sure it is the correct format for time. m = mxGetM(T_IN); n = mxGetN(T_IN); if(!mxIsNumeric(T_IN)||mxIsComplex(T_IN)||mxIsSparse(T_IN)||!mxIsDouble(T_IN)||m!=1||n!=1) mexErrMsgTxt("t(time) is required to be a 1x1 vector."); //Assign the pointer to t(time); t = mxGetPr(T_IN); //Check the second argument and make sure it is the correct format for inputs m = mxGetM(U_IN); n = mxGetN(U_IN); if(!mxIsNumeric(U_IN)||mxIsComplex(U_IN)||mxIsSparse(U_IN)||!mxIsDouble(U_IN)||m!=(unsigned int)chiller->iN_INPUTS||n!=1) { char msg[128]; sprintf(msg,"u(inputs) is required to be a %d x 1 vector.",chiller->iN_INPUTS); mexErrMsgTxt(msg); } //Assign the pointer to u(inputs) u = mxGetPr(U_IN); if(t[0]<=0) mexErrMsgTxt("t(time) cannot be negative."); else { double tt=1; for(int i=0;i<chiller->iN_INPUTS;i++) chiller->VINPUTS(i+1,u[i]); while(tt++ <= t[0]) if(!chiller->fnAdvance1sec(EXPEPC)) { mexErrMsgTxt("ChillerSim Error. Consult error log file for details."); } } Y_OUT = mxCreateDoubleMatrix(chiller->iN_OUTPUTS+1,1,mxREAL); y = mxGetPr(Y_OUT); y[0] = chiller->dTIME; for(i=1;i<=chiller->iN_OUTPUTS;i++) y[i] = chiller->VOUTPUTS(i); // SAVE STATE COMMENTED // if(!chiller->fnSaveState()) // errorlog.Add("Could not save Chiller state."); } }
e011a76e9c3d506527aecb3198e018630b61f6ca
eb0c8b001de4e935cf3597d416e48cf1d9df6e9b
/include/universal/integer/integer_exceptions.hpp
fd90553213c303bd275fbc69dece4aeff6a29c7f
[ "MIT", "LGPL-3.0-only", "LicenseRef-scancode-public-domain" ]
permissive
gussmith23/universal
073547eb4801b96bf16ee01d333c2be453aa5cc6
b26fae9983105c876385d6cb0cc53ccb946ddd10
refs/heads/master
2020-12-27T21:45:30.620646
2020-02-02T00:50:12
2020-02-02T00:50:12
238,068,916
0
0
MIT
2020-02-03T21:48:41
2020-02-03T21:48:40
null
UTF-8
C++
false
false
1,641
hpp
#pragma once // integer_exceptions.hpp: definition of integer exceptions // // Copyright (C) 2017-2020 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <exception> #if defined(__clang__) /* Clang/LLVM. ---------------------------------------------- */ #elif defined(__ICC) || defined(__INTEL_COMPILER) /* Intel ICC/ICPC. ------------------------------------------ */ #elif defined(__GNUC__) || defined(__GNUG__) /* GNU GCC/G++. --------------------------------------------- */ #elif defined(__HP_cc) || defined(__HP_aCC) /* Hewlett-Packard C/aC++. ---------------------------------- */ #elif defined(__IBMC__) || defined(__IBMCPP__) /* IBM XL C/C++. -------------------------------------------- */ #elif defined(_MSC_VER) /* Microsoft Visual Studio. --------------------------------- */ #elif defined(__PGI) /* Portland Group PGCC/PGCPP. ------------------------------- */ #elif defined(__SUNPRO_C) || defined(__SUNPRO_CC) /* Oracle Solaris Studio. ----------------------------------- */ #endif namespace sw { namespace unum { // divide by zero arithmetic exception for integers struct integer_divide_by_zero : public std::runtime_error { integer_divide_by_zero() : std::runtime_error("integer division by zero") {} }; /////////////////////////////////////////////////////////////// // internal implementation exceptions struct integer_byte_index_out_of_bounds : public std::runtime_error { integer_byte_index_out_of_bounds() : std::runtime_error("byte index out of bounds") {} }; } // namespace unum } // namespace sw
26db506f8de7d47b4b92f4433d34c167fd43f0d4
215c9bd0c27e6a43c46d72072d14eeb2622d6fa5
/code/easylogging++.cc
a87f0b8970bb00bb6228f0753959759251ec2a95
[ "MIT" ]
permissive
oargudo/mountains
2d4b695db0741ceaf224f6df41c3b0a564065e59
b295281f81ed93163b71f5caf7465b0a91df8bb2
refs/heads/master
2021-05-23T09:43:01.344765
2020-09-15T17:58:18
2020-09-15T17:58:18
253,226,688
4
0
MIT
2020-09-15T17:58:20
2020-04-05T12:13:11
C++
UTF-8
C++
false
false
121,481
cc
// // Bismillah ar-Rahmaan ar-Raheem // // Easylogging++ v9.96.4 // Cross-platform logging library for C++ applications // // Copyright (c) 2012-2018 Muflihun Labs // Copyright (c) 2012-2018 @abumusamq // // This library is released under the MIT Licence. // https://github.com/muflihun/easyloggingpp/blob/master/LICENSE // // https://github.com/muflihun/easyloggingpp // https://muflihun.github.io/easyloggingpp // http://muflihun.com // #include "easylogging++.h" #if defined(AUTO_INITIALIZE_EASYLOGGINGPP) INITIALIZE_EASYLOGGINGPP #endif namespace el { // el::base namespace base { // el::base::consts namespace consts { // Level log values - These are values that are replaced in place of %level format specifier // Extra spaces after format specifiers are only for readability purposes in log files static const base::type::char_t* kInfoLevelLogValue = ELPP_LITERAL("INFO"); static const base::type::char_t* kDebugLevelLogValue = ELPP_LITERAL("DEBUG"); static const base::type::char_t* kWarningLevelLogValue = ELPP_LITERAL("WARNING"); static const base::type::char_t* kErrorLevelLogValue = ELPP_LITERAL("ERROR"); static const base::type::char_t* kFatalLevelLogValue = ELPP_LITERAL("FATAL"); static const base::type::char_t* kVerboseLevelLogValue = ELPP_LITERAL("VERBOSE"); // will become VERBOSE-x where x = verbose level static const base::type::char_t* kTraceLevelLogValue = ELPP_LITERAL("TRACE"); static const base::type::char_t* kInfoLevelShortLogValue = ELPP_LITERAL("I"); static const base::type::char_t* kDebugLevelShortLogValue = ELPP_LITERAL("D"); static const base::type::char_t* kWarningLevelShortLogValue = ELPP_LITERAL("W"); static const base::type::char_t* kErrorLevelShortLogValue = ELPP_LITERAL("E"); static const base::type::char_t* kFatalLevelShortLogValue = ELPP_LITERAL("F"); static const base::type::char_t* kVerboseLevelShortLogValue = ELPP_LITERAL("V"); static const base::type::char_t* kTraceLevelShortLogValue = ELPP_LITERAL("T"); // Format specifiers - These are used to define log format static const base::type::char_t* kAppNameFormatSpecifier = ELPP_LITERAL("%app"); static const base::type::char_t* kLoggerIdFormatSpecifier = ELPP_LITERAL("%logger"); static const base::type::char_t* kThreadIdFormatSpecifier = ELPP_LITERAL("%thread"); static const base::type::char_t* kSeverityLevelFormatSpecifier = ELPP_LITERAL("%level"); static const base::type::char_t* kSeverityLevelShortFormatSpecifier = ELPP_LITERAL("%levshort"); static const base::type::char_t* kDateTimeFormatSpecifier = ELPP_LITERAL("%datetime"); static const base::type::char_t* kLogFileFormatSpecifier = ELPP_LITERAL("%file"); static const base::type::char_t* kLogFileBaseFormatSpecifier = ELPP_LITERAL("%fbase"); static const base::type::char_t* kLogLineFormatSpecifier = ELPP_LITERAL("%line"); static const base::type::char_t* kLogLocationFormatSpecifier = ELPP_LITERAL("%loc"); static const base::type::char_t* kLogFunctionFormatSpecifier = ELPP_LITERAL("%func"); static const base::type::char_t* kCurrentUserFormatSpecifier = ELPP_LITERAL("%user"); static const base::type::char_t* kCurrentHostFormatSpecifier = ELPP_LITERAL("%host"); static const base::type::char_t* kMessageFormatSpecifier = ELPP_LITERAL("%msg"); static const base::type::char_t* kVerboseLevelFormatSpecifier = ELPP_LITERAL("%vlevel"); static const char* kDateTimeFormatSpecifierForFilename = "%datetime"; // Date/time static const char* kDays[7] = { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" }; static const char* kDaysAbbrev[7] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; static const char* kMonths[12] = { "January", "February", "March", "Apri", "May", "June", "July", "August", "September", "October", "November", "December" }; static const char* kMonthsAbbrev[12] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; static const char* kDefaultDateTimeFormat = "%Y-%M-%d %H:%m:%s,%g"; static const char* kDefaultDateTimeFormatInFilename = "%Y-%M-%d_%H-%m"; static const int kYearBase = 1900; static const char* kAm = "AM"; static const char* kPm = "PM"; // Miscellaneous constants static const char* kNullPointer = "nullptr"; #if ELPP_VARIADIC_TEMPLATES_SUPPORTED #endif // ELPP_VARIADIC_TEMPLATES_SUPPORTED static const base::type::VerboseLevel kMaxVerboseLevel = 9; static const char* kUnknownUser = "user"; static const char* kUnknownHost = "unknown-host"; //---------------- DEFAULT LOG FILE ----------------------- #if defined(ELPP_NO_DEFAULT_LOG_FILE) # if ELPP_OS_UNIX static const char* kDefaultLogFile = "/dev/null"; # elif ELPP_OS_WINDOWS static const char* kDefaultLogFile = "nul"; # endif // ELPP_OS_UNIX #elif defined(ELPP_DEFAULT_LOG_FILE) static const char* kDefaultLogFile = ELPP_DEFAULT_LOG_FILE; #else static const char* kDefaultLogFile = "myeasylog.log"; #endif // defined(ELPP_NO_DEFAULT_LOG_FILE) #if !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG) static const char* kDefaultLogFileParam = "--default-log-file"; #endif // !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG) #if defined(ELPP_LOGGING_FLAGS_FROM_ARG) static const char* kLoggingFlagsParam = "--logging-flags"; #endif // defined(ELPP_LOGGING_FLAGS_FROM_ARG) static const char* kValidLoggerIdSymbols = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._"; static const char* kConfigurationComment = "##"; static const char* kConfigurationLevel = "*"; static const char* kConfigurationLoggerId = "--"; } // el::base::utils namespace utils { /// @brief Aborts application due with user-defined status static void abort(int status, const std::string& reason) { // Both status and reason params are there for debugging with tools like gdb etc ELPP_UNUSED(status); ELPP_UNUSED(reason); #if defined(ELPP_COMPILER_MSVC) && defined(_M_IX86) && defined(_DEBUG) // Ignore msvc critical error dialog - break instead (on debug mode) _asm int 3 #else ::abort(); #endif // defined(ELPP_COMPILER_MSVC) && defined(_M_IX86) && defined(_DEBUG) } } // namespace utils } // namespace base // el // LevelHelper const char* LevelHelper::convertToString(Level level) { // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet. if (level == Level::Global) return "GLOBAL"; if (level == Level::Debug) return "DEBUG"; if (level == Level::Info) return "INFO"; if (level == Level::Warning) return "WARNING"; if (level == Level::Error) return "ERROR"; if (level == Level::Fatal) return "FATAL"; if (level == Level::Verbose) return "VERBOSE"; if (level == Level::Trace) return "TRACE"; return "UNKNOWN"; } struct StringToLevelItem { const char* levelString; Level level; }; static struct StringToLevelItem stringToLevelMap[] = { { "global", Level::Global }, { "debug", Level::Debug }, { "info", Level::Info }, { "warning", Level::Warning }, { "error", Level::Error }, { "fatal", Level::Fatal }, { "verbose", Level::Verbose }, { "trace", Level::Trace } }; Level LevelHelper::convertFromString(const char* levelStr) { for (auto& item : stringToLevelMap) { if (base::utils::Str::cStringCaseEq(levelStr, item.levelString)) { return item.level; } } return Level::Unknown; } void LevelHelper::forEachLevel(base::type::EnumType* startIndex, const std::function<bool(void)>& fn) { base::type::EnumType lIndexMax = LevelHelper::kMaxValid; do { if (fn()) { break; } *startIndex = static_cast<base::type::EnumType>(*startIndex << 1); } while (*startIndex <= lIndexMax); } // ConfigurationTypeHelper const char* ConfigurationTypeHelper::convertToString(ConfigurationType configurationType) { // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet. if (configurationType == ConfigurationType::Enabled) return "ENABLED"; if (configurationType == ConfigurationType::Filename) return "FILENAME"; if (configurationType == ConfigurationType::Format) return "FORMAT"; if (configurationType == ConfigurationType::ToFile) return "TO_FILE"; if (configurationType == ConfigurationType::ToStandardOutput) return "TO_STANDARD_OUTPUT"; if (configurationType == ConfigurationType::SubsecondPrecision) return "SUBSECOND_PRECISION"; if (configurationType == ConfigurationType::PerformanceTracking) return "PERFORMANCE_TRACKING"; if (configurationType == ConfigurationType::MaxLogFileSize) return "MAX_LOG_FILE_SIZE"; if (configurationType == ConfigurationType::LogFlushThreshold) return "LOG_FLUSH_THRESHOLD"; return "UNKNOWN"; } struct ConfigurationStringToTypeItem { const char* configString; ConfigurationType configType; }; static struct ConfigurationStringToTypeItem configStringToTypeMap[] = { { "enabled", ConfigurationType::Enabled }, { "to_file", ConfigurationType::ToFile }, { "to_standard_output", ConfigurationType::ToStandardOutput }, { "format", ConfigurationType::Format }, { "filename", ConfigurationType::Filename }, { "subsecond_precision", ConfigurationType::SubsecondPrecision }, { "milliseconds_width", ConfigurationType::MillisecondsWidth }, { "performance_tracking", ConfigurationType::PerformanceTracking }, { "max_log_file_size", ConfigurationType::MaxLogFileSize }, { "log_flush_threshold", ConfigurationType::LogFlushThreshold }, }; ConfigurationType ConfigurationTypeHelper::convertFromString(const char* configStr) { for (auto& item : configStringToTypeMap) { if (base::utils::Str::cStringCaseEq(configStr, item.configString)) { return item.configType; } } return ConfigurationType::Unknown; } void ConfigurationTypeHelper::forEachConfigType(base::type::EnumType* startIndex, const std::function<bool(void)>& fn) { base::type::EnumType cIndexMax = ConfigurationTypeHelper::kMaxValid; do { if (fn()) { break; } *startIndex = static_cast<base::type::EnumType>(*startIndex << 1); } while (*startIndex <= cIndexMax); } // Configuration Configuration::Configuration(const Configuration& c) : m_level(c.m_level), m_configurationType(c.m_configurationType), m_value(c.m_value) { } Configuration& Configuration::operator=(const Configuration& c) { if (&c != this) { m_level = c.m_level; m_configurationType = c.m_configurationType; m_value = c.m_value; } return *this; } /// @brief Full constructor used to sets value of configuration Configuration::Configuration(Level level, ConfigurationType configurationType, const std::string& value) : m_level(level), m_configurationType(configurationType), m_value(value) { } void Configuration::log(el::base::type::ostream_t& os) const { os << LevelHelper::convertToString(m_level) << ELPP_LITERAL(" ") << ConfigurationTypeHelper::convertToString(m_configurationType) << ELPP_LITERAL(" = ") << m_value.c_str(); } /// @brief Used to find configuration from configuration (pointers) repository. Avoid using it. Configuration::Predicate::Predicate(Level level, ConfigurationType configurationType) : m_level(level), m_configurationType(configurationType) { } bool Configuration::Predicate::operator()(const Configuration* conf) const { return ((conf != nullptr) && (conf->level() == m_level) && (conf->configurationType() == m_configurationType)); } // Configurations Configurations::Configurations(void) : m_configurationFile(std::string()), m_isFromFile(false) { } Configurations::Configurations(const std::string& configurationFile, bool useDefaultsForRemaining, Configurations* base) : m_configurationFile(configurationFile), m_isFromFile(false) { parseFromFile(configurationFile, base); if (useDefaultsForRemaining) { setRemainingToDefault(); } } bool Configurations::parseFromFile(const std::string& configurationFile, Configurations* base) { // We initial assertion with true because if we have assertion diabled, we want to pass this // check and if assertion is enabled we will have values re-assigned any way. bool assertionPassed = true; ELPP_ASSERT((assertionPassed = base::utils::File::pathExists(configurationFile.c_str(), true)) == true, "Configuration file [" << configurationFile << "] does not exist!"); if (!assertionPassed) { return false; } bool success = Parser::parseFromFile(configurationFile, this, base); m_isFromFile = success; return success; } bool Configurations::parseFromText(const std::string& configurationsString, Configurations* base) { bool success = Parser::parseFromText(configurationsString, this, base); if (success) { m_isFromFile = false; } return success; } void Configurations::setFromBase(Configurations* base) { if (base == nullptr || base == this) { return; } base::threading::ScopedLock scopedLock(base->lock()); for (Configuration*& conf : base->list()) { set(conf); } } bool Configurations::hasConfiguration(ConfigurationType configurationType) { base::type::EnumType lIndex = LevelHelper::kMinValid; bool result = false; LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { if (hasConfiguration(LevelHelper::castFromInt(lIndex), configurationType)) { result = true; } return result; }); return result; } bool Configurations::hasConfiguration(Level level, ConfigurationType configurationType) { base::threading::ScopedLock scopedLock(lock()); #if ELPP_COMPILER_INTEL // We cant specify template types here, Intel C++ throws compilation error // "error: type name is not allowed" return RegistryWithPred::get(level, configurationType) != nullptr; #else return RegistryWithPred<Configuration, Configuration::Predicate>::get(level, configurationType) != nullptr; #endif // ELPP_COMPILER_INTEL } void Configurations::set(Level level, ConfigurationType configurationType, const std::string& value) { base::threading::ScopedLock scopedLock(lock()); unsafeSet(level, configurationType, value); // This is not unsafe anymore as we have locked mutex if (level == Level::Global) { unsafeSetGlobally(configurationType, value, false); // Again this is not unsafe either } } void Configurations::set(Configuration* conf) { if (conf == nullptr) { return; } set(conf->level(), conf->configurationType(), conf->value()); } void Configurations::setToDefault(void) { setGlobally(ConfigurationType::Enabled, std::string("true"), true); setGlobally(ConfigurationType::Filename, std::string(base::consts::kDefaultLogFile), true); #if defined(ELPP_NO_LOG_TO_FILE) setGlobally(ConfigurationType::ToFile, std::string("false"), true); #else setGlobally(ConfigurationType::ToFile, std::string("true"), true); #endif // defined(ELPP_NO_LOG_TO_FILE) setGlobally(ConfigurationType::ToStandardOutput, std::string("true"), true); setGlobally(ConfigurationType::SubsecondPrecision, std::string("3"), true); setGlobally(ConfigurationType::PerformanceTracking, std::string("true"), true); setGlobally(ConfigurationType::MaxLogFileSize, std::string("0"), true); setGlobally(ConfigurationType::LogFlushThreshold, std::string("0"), true); setGlobally(ConfigurationType::Format, std::string("%datetime %level [%logger] %msg"), true); set(Level::Debug, ConfigurationType::Format, std::string("%datetime %level [%logger] [%user@%host] [%func] [%loc] %msg")); // INFO and WARNING are set to default by Level::Global set(Level::Error, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); set(Level::Fatal, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); set(Level::Verbose, ConfigurationType::Format, std::string("%datetime %level-%vlevel [%logger] %msg")); set(Level::Trace, ConfigurationType::Format, std::string("%datetime %level [%logger] [%func] [%loc] %msg")); } void Configurations::setRemainingToDefault(void) { base::threading::ScopedLock scopedLock(lock()); #if defined(ELPP_NO_LOG_TO_FILE) unsafeSetIfNotExist(Level::Global, ConfigurationType::Enabled, std::string("false")); #else unsafeSetIfNotExist(Level::Global, ConfigurationType::Enabled, std::string("true")); #endif // defined(ELPP_NO_LOG_TO_FILE) unsafeSetIfNotExist(Level::Global, ConfigurationType::Filename, std::string(base::consts::kDefaultLogFile)); unsafeSetIfNotExist(Level::Global, ConfigurationType::ToStandardOutput, std::string("true")); unsafeSetIfNotExist(Level::Global, ConfigurationType::SubsecondPrecision, std::string("3")); unsafeSetIfNotExist(Level::Global, ConfigurationType::PerformanceTracking, std::string("true")); unsafeSetIfNotExist(Level::Global, ConfigurationType::MaxLogFileSize, std::string("0")); unsafeSetIfNotExist(Level::Global, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); unsafeSetIfNotExist(Level::Debug, ConfigurationType::Format, std::string("%datetime %level [%logger] [%user@%host] [%func] [%loc] %msg")); // INFO and WARNING are set to default by Level::Global unsafeSetIfNotExist(Level::Error, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); unsafeSetIfNotExist(Level::Fatal, ConfigurationType::Format, std::string("%datetime %level [%logger] %msg")); unsafeSetIfNotExist(Level::Verbose, ConfigurationType::Format, std::string("%datetime %level-%vlevel [%logger] %msg")); unsafeSetIfNotExist(Level::Trace, ConfigurationType::Format, std::string("%datetime %level [%logger] [%func] [%loc] %msg")); } bool Configurations::Parser::parseFromFile(const std::string& configurationFile, Configurations* sender, Configurations* base) { sender->setFromBase(base); std::ifstream fileStream_(configurationFile.c_str(), std::ifstream::in); ELPP_ASSERT(fileStream_.is_open(), "Unable to open configuration file [" << configurationFile << "] for parsing."); bool parsedSuccessfully = false; std::string line = std::string(); Level currLevel = Level::Unknown; std::string currConfigStr = std::string(); std::string currLevelStr = std::string(); while (fileStream_.good()) { std::getline(fileStream_, line); parsedSuccessfully = parseLine(&line, &currConfigStr, &currLevelStr, &currLevel, sender); ELPP_ASSERT(parsedSuccessfully, "Unable to parse configuration line: " << line); } return parsedSuccessfully; } bool Configurations::Parser::parseFromText(const std::string& configurationsString, Configurations* sender, Configurations* base) { sender->setFromBase(base); bool parsedSuccessfully = false; std::stringstream ss(configurationsString); std::string line = std::string(); Level currLevel = Level::Unknown; std::string currConfigStr = std::string(); std::string currLevelStr = std::string(); while (std::getline(ss, line)) { parsedSuccessfully = parseLine(&line, &currConfigStr, &currLevelStr, &currLevel, sender); ELPP_ASSERT(parsedSuccessfully, "Unable to parse configuration line: " << line); } return parsedSuccessfully; } void Configurations::Parser::ignoreComments(std::string* line) { std::size_t foundAt = 0; std::size_t quotesStart = line->find("\""); std::size_t quotesEnd = std::string::npos; if (quotesStart != std::string::npos) { quotesEnd = line->find("\"", quotesStart + 1); while (quotesEnd != std::string::npos && line->at(quotesEnd - 1) == '\\') { // Do not erase slash yet - we will erase it in parseLine(..) while loop quotesEnd = line->find("\"", quotesEnd + 2); } } if ((foundAt = line->find(base::consts::kConfigurationComment)) != std::string::npos) { if (foundAt < quotesEnd) { foundAt = line->find(base::consts::kConfigurationComment, quotesEnd + 1); } *line = line->substr(0, foundAt); } } bool Configurations::Parser::isLevel(const std::string& line) { return base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationLevel)); } bool Configurations::Parser::isComment(const std::string& line) { return base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationComment)); } bool Configurations::Parser::isConfig(const std::string& line) { std::size_t assignment = line.find('='); return line != "" && ((line[0] >= 'A' && line[0] <= 'Z') || (line[0] >= 'a' && line[0] <= 'z')) && (assignment != std::string::npos) && (line.size() > assignment); } bool Configurations::Parser::parseLine(std::string* line, std::string* currConfigStr, std::string* currLevelStr, Level* currLevel, Configurations* conf) { ConfigurationType currConfig = ConfigurationType::Unknown; std::string currValue = std::string(); *line = base::utils::Str::trim(*line); if (isComment(*line)) return true; ignoreComments(line); *line = base::utils::Str::trim(*line); if (line->empty()) { // Comment ignored return true; } if (isLevel(*line)) { if (line->size() <= 2) { return true; } *currLevelStr = line->substr(1, line->size() - 2); *currLevelStr = base::utils::Str::toUpper(*currLevelStr); *currLevelStr = base::utils::Str::trim(*currLevelStr); *currLevel = LevelHelper::convertFromString(currLevelStr->c_str()); return true; } if (isConfig(*line)) { std::size_t assignment = line->find('='); *currConfigStr = line->substr(0, assignment); *currConfigStr = base::utils::Str::toUpper(*currConfigStr); *currConfigStr = base::utils::Str::trim(*currConfigStr); currConfig = ConfigurationTypeHelper::convertFromString(currConfigStr->c_str()); currValue = line->substr(assignment + 1); currValue = base::utils::Str::trim(currValue); std::size_t quotesStart = currValue.find("\"", 0); std::size_t quotesEnd = std::string::npos; if (quotesStart != std::string::npos) { quotesEnd = currValue.find("\"", quotesStart + 1); while (quotesEnd != std::string::npos && currValue.at(quotesEnd - 1) == '\\') { currValue = currValue.erase(quotesEnd - 1, 1); quotesEnd = currValue.find("\"", quotesEnd + 2); } } if (quotesStart != std::string::npos && quotesEnd != std::string::npos) { // Quote provided - check and strip if valid ELPP_ASSERT((quotesStart < quotesEnd), "Configuration error - No ending quote found in [" << currConfigStr << "]"); ELPP_ASSERT((quotesStart + 1 != quotesEnd), "Empty configuration value for [" << currConfigStr << "]"); if ((quotesStart != quotesEnd) && (quotesStart + 1 != quotesEnd)) { // Explicit check in case if assertion is disabled currValue = currValue.substr(quotesStart + 1, quotesEnd - 1); } } } ELPP_ASSERT(*currLevel != Level::Unknown, "Unrecognized severity level [" << *currLevelStr << "]"); ELPP_ASSERT(currConfig != ConfigurationType::Unknown, "Unrecognized configuration [" << *currConfigStr << "]"); if (*currLevel == Level::Unknown || currConfig == ConfigurationType::Unknown) { return false; // unrecognizable level or config } conf->set(*currLevel, currConfig, currValue); return true; } void Configurations::unsafeSetIfNotExist(Level level, ConfigurationType configurationType, const std::string& value) { Configuration* conf = RegistryWithPred<Configuration, Configuration::Predicate>::get(level, configurationType); if (conf == nullptr) { unsafeSet(level, configurationType, value); } } void Configurations::unsafeSet(Level level, ConfigurationType configurationType, const std::string& value) { Configuration* conf = RegistryWithPred<Configuration, Configuration::Predicate>::get(level, configurationType); if (conf == nullptr) { registerNew(new Configuration(level, configurationType, value)); } else { conf->setValue(value); } if (level == Level::Global) { unsafeSetGlobally(configurationType, value, false); } } void Configurations::setGlobally(ConfigurationType configurationType, const std::string& value, bool includeGlobalLevel) { if (includeGlobalLevel) { set(Level::Global, configurationType, value); } base::type::EnumType lIndex = LevelHelper::kMinValid; LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { set(LevelHelper::castFromInt(lIndex), configurationType, value); return false; // Do not break lambda function yet as we need to set all levels regardless }); } void Configurations::unsafeSetGlobally(ConfigurationType configurationType, const std::string& value, bool includeGlobalLevel) { if (includeGlobalLevel) { unsafeSet(Level::Global, configurationType, value); } base::type::EnumType lIndex = LevelHelper::kMinValid; LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { unsafeSet(LevelHelper::castFromInt(lIndex), configurationType, value); return false; // Do not break lambda function yet as we need to set all levels regardless }); } // LogBuilder void LogBuilder::convertToColoredOutput(base::type::string_t* logLine, Level level) { if (!m_termSupportsColor) return; const base::type::char_t* resetColor = ELPP_LITERAL("\x1b[0m"); if (level == Level::Error || level == Level::Fatal) *logLine = ELPP_LITERAL("\x1b[31m") + *logLine + resetColor; else if (level == Level::Warning) *logLine = ELPP_LITERAL("\x1b[33m") + *logLine + resetColor; else if (level == Level::Debug) *logLine = ELPP_LITERAL("\x1b[32m") + *logLine + resetColor; else if (level == Level::Info) *logLine = ELPP_LITERAL("\x1b[36m") + *logLine + resetColor; else if (level == Level::Trace) *logLine = ELPP_LITERAL("\x1b[35m") + *logLine + resetColor; } // Logger Logger::Logger(const std::string& id, base::LogStreamsReferenceMap* logStreamsReference) : m_id(id), m_typedConfigurations(nullptr), m_parentApplicationName(std::string()), m_isConfigured(false), m_logStreamsReference(logStreamsReference) { initUnflushedCount(); } Logger::Logger(const std::string& id, const Configurations& configurations, base::LogStreamsReferenceMap* logStreamsReference) : m_id(id), m_typedConfigurations(nullptr), m_parentApplicationName(std::string()), m_isConfigured(false), m_logStreamsReference(logStreamsReference) { initUnflushedCount(); configure(configurations); } Logger::Logger(const Logger& logger) { base::utils::safeDelete(m_typedConfigurations); m_id = logger.m_id; m_typedConfigurations = logger.m_typedConfigurations; m_parentApplicationName = logger.m_parentApplicationName; m_isConfigured = logger.m_isConfigured; m_configurations = logger.m_configurations; m_unflushedCount = logger.m_unflushedCount; m_logStreamsReference = logger.m_logStreamsReference; } Logger& Logger::operator=(const Logger& logger) { if (&logger != this) { base::utils::safeDelete(m_typedConfigurations); m_id = logger.m_id; m_typedConfigurations = logger.m_typedConfigurations; m_parentApplicationName = logger.m_parentApplicationName; m_isConfigured = logger.m_isConfigured; m_configurations = logger.m_configurations; m_unflushedCount = logger.m_unflushedCount; m_logStreamsReference = logger.m_logStreamsReference; } return *this; } void Logger::configure(const Configurations& configurations) { m_isConfigured = false; // we set it to false in case if we fail initUnflushedCount(); if (m_typedConfigurations != nullptr) { Configurations* c = const_cast<Configurations*>(m_typedConfigurations->configurations()); if (c->hasConfiguration(Level::Global, ConfigurationType::Filename)) { flush(); } } base::threading::ScopedLock scopedLock(lock()); if (m_configurations != configurations) { m_configurations.setFromBase(const_cast<Configurations*>(&configurations)); } base::utils::safeDelete(m_typedConfigurations); m_typedConfigurations = new base::TypedConfigurations(&m_configurations, m_logStreamsReference); resolveLoggerFormatSpec(); m_isConfigured = true; } void Logger::reconfigure(void) { ELPP_INTERNAL_INFO(1, "Reconfiguring logger [" << m_id << "]"); configure(m_configurations); } bool Logger::isValidId(const std::string& id) { for (std::string::const_iterator it = id.begin(); it != id.end(); ++it) { if (!base::utils::Str::contains(base::consts::kValidLoggerIdSymbols, *it)) { return false; } } return true; } void Logger::flush(void) { ELPP_INTERNAL_INFO(3, "Flushing logger [" << m_id << "] all levels"); base::threading::ScopedLock scopedLock(lock()); base::type::EnumType lIndex = LevelHelper::kMinValid; LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { flush(LevelHelper::castFromInt(lIndex), nullptr); return false; }); } void Logger::flush(Level level, base::type::fstream_t* fs) { if (fs == nullptr && m_typedConfigurations->toFile(level)) { fs = m_typedConfigurations->fileStream(level); } if (fs != nullptr) { fs->flush(); std::unordered_map<Level, unsigned int>::iterator iter = m_unflushedCount.find(level); if (iter != m_unflushedCount.end()) { iter->second = 0; } Helpers::validateFileRolling(this, level); } } void Logger::initUnflushedCount(void) { m_unflushedCount.clear(); base::type::EnumType lIndex = LevelHelper::kMinValid; LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { m_unflushedCount.insert(std::make_pair(LevelHelper::castFromInt(lIndex), 0)); return false; }); } void Logger::resolveLoggerFormatSpec(void) const { base::type::EnumType lIndex = LevelHelper::kMinValid; LevelHelper::forEachLevel(&lIndex, [&](void) -> bool { base::LogFormat* logFormat = const_cast<base::LogFormat*>(&m_typedConfigurations->logFormat(LevelHelper::castFromInt(lIndex))); base::utils::Str::replaceFirstWithEscape(logFormat->m_format, base::consts::kLoggerIdFormatSpecifier, m_id); return false; }); } // el::base namespace base { // el::base::utils namespace utils { // File base::type::fstream_t* File::newFileStream(const std::string& filename) { base::type::fstream_t *fs = new base::type::fstream_t(filename.c_str(), base::type::fstream_t::out #if !defined(ELPP_FRESH_LOG_FILE) | base::type::fstream_t::app #endif ); #if defined(ELPP_UNICODE) std::locale elppUnicodeLocale(""); # if ELPP_OS_WINDOWS std::locale elppUnicodeLocaleWindows(elppUnicodeLocale, new std::codecvt_utf8_utf16<wchar_t>); elppUnicodeLocale = elppUnicodeLocaleWindows; # endif // ELPP_OS_WINDOWS fs->imbue(elppUnicodeLocale); #endif // defined(ELPP_UNICODE) if (fs->is_open()) { fs->flush(); } else { base::utils::safeDelete(fs); ELPP_INTERNAL_ERROR("Bad file [" << filename << "]", true); } return fs; } std::size_t File::getSizeOfFile(base::type::fstream_t* fs) { if (fs == nullptr) { return 0; } // Since the file stream is appended to or truncated, the current // offset is the file size. std::size_t size = static_cast<std::size_t>(fs->tellg()); return size; } bool File::pathExists(const char* path, bool considerFile) { if (path == nullptr) { return false; } #if ELPP_OS_UNIX ELPP_UNUSED(considerFile); struct stat st; return (stat(path, &st) == 0); #elif ELPP_OS_WINDOWS DWORD fileType = GetFileAttributesA(path); if (fileType == INVALID_FILE_ATTRIBUTES) { return false; } return considerFile ? true : ((fileType & FILE_ATTRIBUTE_DIRECTORY) == 0 ? false : true); #endif // ELPP_OS_UNIX } bool File::createPath(const std::string& path) { if (path.empty()) { return false; } if (base::utils::File::pathExists(path.c_str())) { return true; } int status = -1; char* currPath = const_cast<char*>(path.c_str()); std::string builtPath = std::string(); #if ELPP_OS_UNIX if (path[0] == '/') { builtPath = "/"; } currPath = STRTOK(currPath, base::consts::kFilePathSeperator, 0); #elif ELPP_OS_WINDOWS // Use secure functions API char* nextTok_ = nullptr; currPath = STRTOK(currPath, base::consts::kFilePathSeperator, &nextTok_); ELPP_UNUSED(nextTok_); #endif // ELPP_OS_UNIX while (currPath != nullptr) { builtPath.append(currPath); builtPath.append(base::consts::kFilePathSeperator); #if ELPP_OS_UNIX status = mkdir(builtPath.c_str(), ELPP_LOG_PERMS); currPath = STRTOK(nullptr, base::consts::kFilePathSeperator, 0); #elif ELPP_OS_WINDOWS status = _mkdir(builtPath.c_str()); currPath = STRTOK(nullptr, base::consts::kFilePathSeperator, &nextTok_); #endif // ELPP_OS_UNIX } if (status == -1) { ELPP_INTERNAL_ERROR("Error while creating path [" << path << "]", true); return false; } return true; } std::string File::extractPathFromFilename(const std::string& fullPath, const char* separator) { if ((fullPath == "") || (fullPath.find(separator) == std::string::npos)) { return fullPath; } std::size_t lastSlashAt = fullPath.find_last_of(separator); if (lastSlashAt == 0) { return std::string(separator); } return fullPath.substr(0, lastSlashAt + 1); } void File::buildStrippedFilename(const char* filename, char buff[], std::size_t limit) { std::size_t sizeOfFilename = strlen(filename); if (sizeOfFilename >= limit) { filename += (sizeOfFilename - limit); if (filename[0] != '.' && filename[1] != '.') { // prepend if not already filename += 3; // 3 = '..' STRCAT(buff, "..", limit); } } STRCAT(buff, filename, limit); } void File::buildBaseFilename(const std::string& fullPath, char buff[], std::size_t limit, const char* separator) { const char *filename = fullPath.c_str(); std::size_t lastSlashAt = fullPath.find_last_of(separator); filename += lastSlashAt ? lastSlashAt+1 : 0; std::size_t sizeOfFilename = strlen(filename); if (sizeOfFilename >= limit) { filename += (sizeOfFilename - limit); if (filename[0] != '.' && filename[1] != '.') { // prepend if not already filename += 3; // 3 = '..' STRCAT(buff, "..", limit); } } STRCAT(buff, filename, limit); } // Str bool Str::wildCardMatch(const char* str, const char* pattern) { while (*pattern) { switch (*pattern) { case '?': if (!*str) return false; ++str; ++pattern; break; case '*': if (wildCardMatch(str, pattern + 1)) return true; if (*str && wildCardMatch(str + 1, pattern)) return true; return false; default: if (*str++ != *pattern++) return false; break; } } return !*str && !*pattern; } std::string& Str::ltrim(std::string& str) { str.erase(str.begin(), std::find_if(str.begin(), str.end(), [](char c) { return !std::isspace(c); } )); return str; } std::string& Str::rtrim(std::string& str) { str.erase(std::find_if(str.rbegin(), str.rend(), [](char c) { return !std::isspace(c); }).base(), str.end()); return str; } std::string& Str::trim(std::string& str) { return ltrim(rtrim(str)); } bool Str::startsWith(const std::string& str, const std::string& start) { return (str.length() >= start.length()) && (str.compare(0, start.length(), start) == 0); } bool Str::endsWith(const std::string& str, const std::string& end) { return (str.length() >= end.length()) && (str.compare(str.length() - end.length(), end.length(), end) == 0); } std::string& Str::replaceAll(std::string& str, char replaceWhat, char replaceWith) { std::replace(str.begin(), str.end(), replaceWhat, replaceWith); return str; } std::string& Str::replaceAll(std::string& str, const std::string& replaceWhat, const std::string& replaceWith) { if (replaceWhat == replaceWith) return str; std::size_t foundAt = std::string::npos; while ((foundAt = str.find(replaceWhat, foundAt + 1)) != std::string::npos) { str.replace(foundAt, replaceWhat.length(), replaceWith); } return str; } void Str::replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat, const base::type::string_t& replaceWith) { std::size_t foundAt = base::type::string_t::npos; while ((foundAt = str.find(replaceWhat, foundAt + 1)) != base::type::string_t::npos) { if (foundAt > 0 && str[foundAt - 1] == base::consts::kFormatSpecifierChar) { str.erase(foundAt > 0 ? foundAt - 1 : 0, 1); ++foundAt; } else { str.replace(foundAt, replaceWhat.length(), replaceWith); return; } } } #if defined(ELPP_UNICODE) void Str::replaceFirstWithEscape(base::type::string_t& str, const base::type::string_t& replaceWhat, const std::string& replaceWith) { replaceFirstWithEscape(str, replaceWhat, base::type::string_t(replaceWith.begin(), replaceWith.end())); } #endif // defined(ELPP_UNICODE) std::string& Str::toUpper(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), [](char c) { return static_cast<char>(::toupper(c)); }); return str; } bool Str::cStringEq(const char* s1, const char* s2) { if (s1 == nullptr && s2 == nullptr) return true; if (s1 == nullptr || s2 == nullptr) return false; return strcmp(s1, s2) == 0; } bool Str::cStringCaseEq(const char* s1, const char* s2) { if (s1 == nullptr && s2 == nullptr) return true; if (s1 == nullptr || s2 == nullptr) return false; // With thanks to cygwin for this code int d = 0; while (true) { const int c1 = toupper(*s1++); const int c2 = toupper(*s2++); if (((d = c1 - c2) != 0) || (c2 == '\0')) { break; } } return d == 0; } bool Str::contains(const char* str, char c) { for (; *str; ++str) { if (*str == c) return true; } return false; } char* Str::convertAndAddToBuff(std::size_t n, int len, char* buf, const char* bufLim, bool zeroPadded) { char localBuff[10] = ""; char* p = localBuff + sizeof(localBuff) - 2; if (n > 0) { for (; n > 0 && p > localBuff && len > 0; n /= 10, --len) *--p = static_cast<char>(n % 10 + '0'); } else { *--p = '0'; --len; } if (zeroPadded) while (p > localBuff && len-- > 0) *--p = static_cast<char>('0'); return addToBuff(p, buf, bufLim); } char* Str::addToBuff(const char* str, char* buf, const char* bufLim) { while ((buf < bufLim) && ((*buf = *str++) != '\0')) ++buf; return buf; } char* Str::clearBuff(char buff[], std::size_t lim) { STRCPY(buff, "", lim); ELPP_UNUSED(lim); // For *nix we dont have anything using lim in above STRCPY macro return buff; } /// @brief Converst wchar* to char* /// NOTE: Need to free return value after use! char* Str::wcharPtrToCharPtr(const wchar_t* line) { std::size_t len_ = wcslen(line) + 1; char* buff_ = static_cast<char*>(malloc(len_ + 1)); # if ELPP_OS_UNIX || (ELPP_OS_WINDOWS && !ELPP_CRT_DBG_WARNINGS) std::wcstombs(buff_, line, len_); # elif ELPP_OS_WINDOWS std::size_t convCount_ = 0; mbstate_t mbState_; ::memset(static_cast<void*>(&mbState_), 0, sizeof(mbState_)); wcsrtombs_s(&convCount_, buff_, len_, &line, len_, &mbState_); # endif // ELPP_OS_UNIX || (ELPP_OS_WINDOWS && !ELPP_CRT_DBG_WARNINGS) return buff_; } // OS #if ELPP_OS_WINDOWS /// @brief Gets environment variables for Windows based OS. /// We are not using <code>getenv(const char*)</code> because of CRT deprecation /// @param varname Variable name to get environment variable value for /// @return If variable exist the value of it otherwise nullptr const char* OS::getWindowsEnvironmentVariable(const char* varname) { const DWORD bufferLen = 50; static char buffer[bufferLen]; if (GetEnvironmentVariableA(varname, buffer, bufferLen)) { return buffer; } return nullptr; } #endif // ELPP_OS_WINDOWS #if ELPP_OS_ANDROID std::string OS::getProperty(const char* prop) { char propVal[PROP_VALUE_MAX + 1]; int ret = __system_property_get(prop, propVal); return ret == 0 ? std::string() : std::string(propVal); } std::string OS::getDeviceName(void) { std::stringstream ss; std::string manufacturer = getProperty("ro.product.manufacturer"); std::string model = getProperty("ro.product.model"); if (manufacturer.empty() || model.empty()) { return std::string(); } ss << manufacturer << "-" << model; return ss.str(); } #endif // ELPP_OS_ANDROID const std::string OS::getBashOutput(const char* command) { #if (ELPP_OS_UNIX && !ELPP_OS_ANDROID && !ELPP_CYGWIN) if (command == nullptr) { return std::string(); } FILE* proc = nullptr; if ((proc = popen(command, "r")) == nullptr) { ELPP_INTERNAL_ERROR("\nUnable to run command [" << command << "]", true); return std::string(); } char hBuff[4096]; if (fgets(hBuff, sizeof(hBuff), proc) != nullptr) { pclose(proc); const std::size_t buffLen = strlen(hBuff); if (buffLen > 0 && hBuff[buffLen - 1] == '\n') { hBuff[buffLen - 1] = '\0'; } return std::string(hBuff); } else { pclose(proc); } return std::string(); #else ELPP_UNUSED(command); return std::string(); #endif // (ELPP_OS_UNIX && !ELPP_OS_ANDROID && !ELPP_CYGWIN) } std::string OS::getEnvironmentVariable(const char* variableName, const char* defaultVal, const char* alternativeBashCommand) { #if ELPP_OS_UNIX const char* val = getenv(variableName); #elif ELPP_OS_WINDOWS const char* val = getWindowsEnvironmentVariable(variableName); #endif // ELPP_OS_UNIX if ((val == nullptr) || ((strcmp(val, "") == 0))) { #if ELPP_OS_UNIX && defined(ELPP_FORCE_ENV_VAR_FROM_BASH) // Try harder on unix-based systems std::string valBash = base::utils::OS::getBashOutput(alternativeBashCommand); if (valBash.empty()) { return std::string(defaultVal); } else { return valBash; } #elif ELPP_OS_WINDOWS || ELPP_OS_UNIX ELPP_UNUSED(alternativeBashCommand); return std::string(defaultVal); #endif // ELPP_OS_UNIX && defined(ELPP_FORCE_ENV_VAR_FROM_BASH) } return std::string(val); } std::string OS::currentUser(void) { #if ELPP_OS_UNIX && !ELPP_OS_ANDROID return getEnvironmentVariable("USER", base::consts::kUnknownUser, "whoami"); #elif ELPP_OS_WINDOWS return getEnvironmentVariable("USERNAME", base::consts::kUnknownUser); #elif ELPP_OS_ANDROID ELPP_UNUSED(base::consts::kUnknownUser); return std::string("android"); #else return std::string(); #endif // ELPP_OS_UNIX && !ELPP_OS_ANDROID } std::string OS::currentHost(void) { #if ELPP_OS_UNIX && !ELPP_OS_ANDROID return getEnvironmentVariable("HOSTNAME", base::consts::kUnknownHost, "hostname"); #elif ELPP_OS_WINDOWS return getEnvironmentVariable("COMPUTERNAME", base::consts::kUnknownHost); #elif ELPP_OS_ANDROID ELPP_UNUSED(base::consts::kUnknownHost); return getDeviceName(); #else return std::string(); #endif // ELPP_OS_UNIX && !ELPP_OS_ANDROID } bool OS::termSupportsColor(void) { std::string term = getEnvironmentVariable("TERM", ""); return term == "xterm" || term == "xterm-color" || term == "xterm-256color" || term == "screen" || term == "linux" || term == "cygwin" || term == "screen-256color"; } // DateTime void DateTime::gettimeofday(struct timeval* tv) { #if ELPP_OS_WINDOWS if (tv != nullptr) { # if ELPP_COMPILER_MSVC || defined(_MSC_EXTENSIONS) const unsigned __int64 delta_ = 11644473600000000Ui64; # else const unsigned __int64 delta_ = 11644473600000000ULL; # endif // ELPP_COMPILER_MSVC || defined(_MSC_EXTENSIONS) const double secOffSet = 0.000001; const unsigned long usecOffSet = 1000000; FILETIME fileTime; GetSystemTimeAsFileTime(&fileTime); unsigned __int64 present = 0; present |= fileTime.dwHighDateTime; present = present << 32; present |= fileTime.dwLowDateTime; present /= 10; // mic-sec // Subtract the difference present -= delta_; tv->tv_sec = static_cast<long>(present * secOffSet); tv->tv_usec = static_cast<long>(present % usecOffSet); } #else ::gettimeofday(tv, nullptr); #endif // ELPP_OS_WINDOWS } std::string DateTime::getDateTime(const char* format, const base::SubsecondPrecision* ssPrec) { struct timeval currTime; gettimeofday(&currTime); return timevalToString(currTime, format, ssPrec); } std::string DateTime::timevalToString(struct timeval tval, const char* format, const el::base::SubsecondPrecision* ssPrec) { struct ::tm timeInfo; buildTimeInfo(&tval, &timeInfo); const int kBuffSize = 30; char buff_[kBuffSize] = ""; parseFormat(buff_, kBuffSize, format, &timeInfo, static_cast<std::size_t>(tval.tv_usec / ssPrec->m_offset), ssPrec); return std::string(buff_); } base::type::string_t DateTime::formatTime(unsigned long long time, base::TimestampUnit timestampUnit) { base::type::EnumType start = static_cast<base::type::EnumType>(timestampUnit); const base::type::char_t* unit = base::consts::kTimeFormats[start].unit; for (base::type::EnumType i = start; i < base::consts::kTimeFormatsCount - 1; ++i) { if (time <= base::consts::kTimeFormats[i].value) { break; } if (base::consts::kTimeFormats[i].value == 1000.0f && time / 1000.0f < 1.9f) { break; } time /= static_cast<decltype(time)>(base::consts::kTimeFormats[i].value); unit = base::consts::kTimeFormats[i + 1].unit; } base::type::stringstream_t ss; ss << time << " " << unit; return ss.str(); } unsigned long long DateTime::getTimeDifference(const struct timeval& endTime, const struct timeval& startTime, base::TimestampUnit timestampUnit) { if (timestampUnit == base::TimestampUnit::Microsecond) { return static_cast<unsigned long long>(static_cast<unsigned long long>(1000000 * endTime.tv_sec + endTime.tv_usec) - static_cast<unsigned long long>(1000000 * startTime.tv_sec + startTime.tv_usec)); } // milliseconds auto conv = [](const struct timeval& tim) { return static_cast<unsigned long long>((tim.tv_sec * 1000) + (tim.tv_usec / 1000)); }; return static_cast<unsigned long long>(conv(endTime) - conv(startTime)); } struct ::tm* DateTime::buildTimeInfo(struct timeval* currTime, struct ::tm* timeInfo) { #if ELPP_OS_UNIX time_t rawTime = currTime->tv_sec; ::elpptime_r(&rawTime, timeInfo); return timeInfo; #else # if ELPP_COMPILER_MSVC ELPP_UNUSED(currTime); time_t t; # if defined(_USE_32BIT_TIME_T) _time32(&t); # else _time64(&t); # endif elpptime_s(timeInfo, &t); return timeInfo; # else // For any other compilers that don't have CRT warnings issue e.g, MinGW or TDM GCC- we use different method time_t rawTime = currTime->tv_sec; struct tm* tmInf = elpptime(&rawTime); *timeInfo = *tmInf; return timeInfo; # endif // ELPP_COMPILER_MSVC #endif // ELPP_OS_UNIX } char* DateTime::parseFormat(char* buf, std::size_t bufSz, const char* format, const struct tm* tInfo, std::size_t msec, const base::SubsecondPrecision* ssPrec) { const char* bufLim = buf + bufSz; for (; *format; ++format) { if (*format == base::consts::kFormatSpecifierChar) { switch (*++format) { case base::consts::kFormatSpecifierChar: // Escape break; case '\0': // End --format; break; case 'd': // Day buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_mday, 2, buf, bufLim); continue; case 'a': // Day of week (short) buf = base::utils::Str::addToBuff(base::consts::kDaysAbbrev[tInfo->tm_wday], buf, bufLim); continue; case 'A': // Day of week (long) buf = base::utils::Str::addToBuff(base::consts::kDays[tInfo->tm_wday], buf, bufLim); continue; case 'M': // month buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_mon + 1, 2, buf, bufLim); continue; case 'b': // month (short) buf = base::utils::Str::addToBuff(base::consts::kMonthsAbbrev[tInfo->tm_mon], buf, bufLim); continue; case 'B': // month (long) buf = base::utils::Str::addToBuff(base::consts::kMonths[tInfo->tm_mon], buf, bufLim); continue; case 'y': // year (two digits) buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_year + base::consts::kYearBase, 2, buf, bufLim); continue; case 'Y': // year (four digits) buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_year + base::consts::kYearBase, 4, buf, bufLim); continue; case 'h': // hour (12-hour) buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_hour % 12, 2, buf, bufLim); continue; case 'H': // hour (24-hour) buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_hour, 2, buf, bufLim); continue; case 'm': // minute buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_min, 2, buf, bufLim); continue; case 's': // second buf = base::utils::Str::convertAndAddToBuff(tInfo->tm_sec, 2, buf, bufLim); continue; case 'z': // subsecond part case 'g': buf = base::utils::Str::convertAndAddToBuff(msec, ssPrec->m_width, buf, bufLim); continue; case 'F': // AM/PM buf = base::utils::Str::addToBuff((tInfo->tm_hour >= 12) ? base::consts::kPm : base::consts::kAm, buf, bufLim); continue; default: continue; } } if (buf == bufLim) break; *buf++ = *format; } return buf; } // CommandLineArgs void CommandLineArgs::setArgs(int argc, char** argv) { m_params.clear(); m_paramsWithValue.clear(); if (argc == 0 || argv == nullptr) { return; } m_argc = argc; m_argv = argv; for (int i = 1; i < m_argc; ++i) { const char* v = (strstr(m_argv[i], "=")); if (v != nullptr && strlen(v) > 0) { std::string key = std::string(m_argv[i]); key = key.substr(0, key.find_first_of('=')); if (hasParamWithValue(key.c_str())) { ELPP_INTERNAL_INFO(1, "Skipping [" << key << "] arg since it already has value [" << getParamValue(key.c_str()) << "]"); } else { m_paramsWithValue.insert(std::make_pair(key, std::string(v + 1))); } } if (v == nullptr) { if (hasParam(m_argv[i])) { ELPP_INTERNAL_INFO(1, "Skipping [" << m_argv[i] << "] arg since it already exists"); } else { m_params.push_back(std::string(m_argv[i])); } } } } bool CommandLineArgs::hasParamWithValue(const char* paramKey) const { return m_paramsWithValue.find(std::string(paramKey)) != m_paramsWithValue.end(); } const char* CommandLineArgs::getParamValue(const char* paramKey) const { std::unordered_map<std::string, std::string>::const_iterator iter = m_paramsWithValue.find(std::string(paramKey)); return iter != m_paramsWithValue.end() ? iter->second.c_str() : ""; } bool CommandLineArgs::hasParam(const char* paramKey) const { return std::find(m_params.begin(), m_params.end(), std::string(paramKey)) != m_params.end(); } bool CommandLineArgs::empty(void) const { return m_params.empty() && m_paramsWithValue.empty(); } std::size_t CommandLineArgs::size(void) const { return m_params.size() + m_paramsWithValue.size(); } base::type::ostream_t& operator<<(base::type::ostream_t& os, const CommandLineArgs& c) { for (int i = 1; i < c.m_argc; ++i) { os << ELPP_LITERAL("[") << c.m_argv[i] << ELPP_LITERAL("]"); if (i < c.m_argc - 1) { os << ELPP_LITERAL(" "); } } return os; } } // namespace utils // el::base::threading namespace threading { #if ELPP_THREADING_ENABLED # if ELPP_USE_STD_THREADING # if ELPP_ASYNC_LOGGING static void msleep(int ms) { // Only when async logging enabled - this is because async is strict on compiler # if defined(ELPP_NO_SLEEP_FOR) usleep(ms * 1000); # else std::this_thread::sleep_for(std::chrono::milliseconds(ms)); # endif // defined(ELPP_NO_SLEEP_FOR) } # endif // ELPP_ASYNC_LOGGING # endif // !ELPP_USE_STD_THREADING #endif // ELPP_THREADING_ENABLED } // namespace threading // el::base // SubsecondPrecision void SubsecondPrecision::init(int width) { if (width < 1 || width > 6) { width = base::consts::kDefaultSubsecondPrecision; } m_width = width; switch (m_width) { case 3: m_offset = 1000; break; case 4: m_offset = 100; break; case 5: m_offset = 10; break; case 6: m_offset = 1; break; default: m_offset = 1000; break; } } // LogFormat LogFormat::LogFormat(void) : m_level(Level::Unknown), m_userFormat(base::type::string_t()), m_format(base::type::string_t()), m_dateTimeFormat(std::string()), m_flags(0x0), m_currentUser(base::utils::OS::currentUser()), m_currentHost(base::utils::OS::currentHost()) { } LogFormat::LogFormat(Level level, const base::type::string_t& format) : m_level(level), m_userFormat(format), m_currentUser(base::utils::OS::currentUser()), m_currentHost(base::utils::OS::currentHost()) { parseFromFormat(m_userFormat); } LogFormat::LogFormat(const LogFormat& logFormat): m_level(logFormat.m_level), m_userFormat(logFormat.m_userFormat), m_format(logFormat.m_format), m_dateTimeFormat(logFormat.m_dateTimeFormat), m_flags(logFormat.m_flags), m_currentUser(logFormat.m_currentUser), m_currentHost(logFormat.m_currentHost) { } LogFormat::LogFormat(LogFormat&& logFormat) { m_level = std::move(logFormat.m_level); m_userFormat = std::move(logFormat.m_userFormat); m_format = std::move(logFormat.m_format); m_dateTimeFormat = std::move(logFormat.m_dateTimeFormat); m_flags = std::move(logFormat.m_flags); m_currentUser = std::move(logFormat.m_currentUser); m_currentHost = std::move(logFormat.m_currentHost); } LogFormat& LogFormat::operator=(const LogFormat& logFormat) { if (&logFormat != this) { m_level = logFormat.m_level; m_userFormat = logFormat.m_userFormat; m_dateTimeFormat = logFormat.m_dateTimeFormat; m_flags = logFormat.m_flags; m_currentUser = logFormat.m_currentUser; m_currentHost = logFormat.m_currentHost; } return *this; } bool LogFormat::operator==(const LogFormat& other) { return m_level == other.m_level && m_userFormat == other.m_userFormat && m_format == other.m_format && m_dateTimeFormat == other.m_dateTimeFormat && m_flags == other.m_flags; } /// @brief Updates format to be used while logging. /// @param userFormat User provided format void LogFormat::parseFromFormat(const base::type::string_t& userFormat) { // We make copy because we will be changing the format // i.e, removing user provided date format from original format // and then storing it. base::type::string_t formatCopy = userFormat; m_flags = 0x0; auto conditionalAddFlag = [&](const base::type::char_t* specifier, base::FormatFlags flag) { std::size_t foundAt = base::type::string_t::npos; while ((foundAt = formatCopy.find(specifier, foundAt + 1)) != base::type::string_t::npos) { if (foundAt > 0 && formatCopy[foundAt - 1] == base::consts::kFormatSpecifierChar) { if (hasFlag(flag)) { // If we already have flag we remove the escape chars so that '%%' is turned to '%' // even after specifier resolution - this is because we only replaceFirst specifier formatCopy.erase(foundAt > 0 ? foundAt - 1 : 0, 1); ++foundAt; } } else { if (!hasFlag(flag)) addFlag(flag); } } }; conditionalAddFlag(base::consts::kAppNameFormatSpecifier, base::FormatFlags::AppName); conditionalAddFlag(base::consts::kSeverityLevelFormatSpecifier, base::FormatFlags::Level); conditionalAddFlag(base::consts::kSeverityLevelShortFormatSpecifier, base::FormatFlags::LevelShort); conditionalAddFlag(base::consts::kLoggerIdFormatSpecifier, base::FormatFlags::LoggerId); conditionalAddFlag(base::consts::kThreadIdFormatSpecifier, base::FormatFlags::ThreadId); conditionalAddFlag(base::consts::kLogFileFormatSpecifier, base::FormatFlags::File); conditionalAddFlag(base::consts::kLogFileBaseFormatSpecifier, base::FormatFlags::FileBase); conditionalAddFlag(base::consts::kLogLineFormatSpecifier, base::FormatFlags::Line); conditionalAddFlag(base::consts::kLogLocationFormatSpecifier, base::FormatFlags::Location); conditionalAddFlag(base::consts::kLogFunctionFormatSpecifier, base::FormatFlags::Function); conditionalAddFlag(base::consts::kCurrentUserFormatSpecifier, base::FormatFlags::User); conditionalAddFlag(base::consts::kCurrentHostFormatSpecifier, base::FormatFlags::Host); conditionalAddFlag(base::consts::kMessageFormatSpecifier, base::FormatFlags::LogMessage); conditionalAddFlag(base::consts::kVerboseLevelFormatSpecifier, base::FormatFlags::VerboseLevel); // For date/time we need to extract user's date format first std::size_t dateIndex = std::string::npos; if ((dateIndex = formatCopy.find(base::consts::kDateTimeFormatSpecifier)) != std::string::npos) { while (dateIndex > 0 && formatCopy[dateIndex - 1] == base::consts::kFormatSpecifierChar) { dateIndex = formatCopy.find(base::consts::kDateTimeFormatSpecifier, dateIndex + 1); } if (dateIndex != std::string::npos) { addFlag(base::FormatFlags::DateTime); updateDateFormat(dateIndex, formatCopy); } } m_format = formatCopy; updateFormatSpec(); } void LogFormat::updateDateFormat(std::size_t index, base::type::string_t& currFormat) { if (hasFlag(base::FormatFlags::DateTime)) { index += ELPP_STRLEN(base::consts::kDateTimeFormatSpecifier); } const base::type::char_t* ptr = currFormat.c_str() + index; if ((currFormat.size() > index) && (ptr[0] == '{')) { // User has provided format for date/time ++ptr; int count = 1; // Start by 1 in order to remove starting brace std::stringstream ss; for (; *ptr; ++ptr, ++count) { if (*ptr == '}') { ++count; // In order to remove ending brace break; } ss << static_cast<char>(*ptr); } currFormat.erase(index, count); m_dateTimeFormat = ss.str(); } else { // No format provided, use default if (hasFlag(base::FormatFlags::DateTime)) { m_dateTimeFormat = std::string(base::consts::kDefaultDateTimeFormat); } } } void LogFormat::updateFormatSpec(void) { // Do not use switch over strongly typed enums because Intel C++ compilers dont support them yet. if (m_level == Level::Debug) { base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, base::consts::kDebugLevelLogValue); base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, base::consts::kDebugLevelShortLogValue); } else if (m_level == Level::Info) { base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, base::consts::kInfoLevelLogValue); base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, base::consts::kInfoLevelShortLogValue); } else if (m_level == Level::Warning) { base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, base::consts::kWarningLevelLogValue); base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, base::consts::kWarningLevelShortLogValue); } else if (m_level == Level::Error) { base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, base::consts::kErrorLevelLogValue); base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, base::consts::kErrorLevelShortLogValue); } else if (m_level == Level::Fatal) { base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, base::consts::kFatalLevelLogValue); base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, base::consts::kFatalLevelShortLogValue); } else if (m_level == Level::Verbose) { base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, base::consts::kVerboseLevelLogValue); base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, base::consts::kVerboseLevelShortLogValue); } else if (m_level == Level::Trace) { base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelFormatSpecifier, base::consts::kTraceLevelLogValue); base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kSeverityLevelShortFormatSpecifier, base::consts::kTraceLevelShortLogValue); } if (hasFlag(base::FormatFlags::User)) { base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kCurrentUserFormatSpecifier, m_currentUser); } if (hasFlag(base::FormatFlags::Host)) { base::utils::Str::replaceFirstWithEscape(m_format, base::consts::kCurrentHostFormatSpecifier, m_currentHost); } // Ignore Level::Global and Level::Unknown } // TypedConfigurations TypedConfigurations::TypedConfigurations(Configurations* configurations, base::LogStreamsReferenceMap* logStreamsReference) { m_configurations = configurations; m_logStreamsReference = logStreamsReference; build(m_configurations); } TypedConfigurations::TypedConfigurations(const TypedConfigurations& other) { this->m_configurations = other.m_configurations; this->m_logStreamsReference = other.m_logStreamsReference; build(m_configurations); } bool TypedConfigurations::enabled(Level level) { return getConfigByVal<bool>(level, &m_enabledMap, "enabled"); } bool TypedConfigurations::toFile(Level level) { return getConfigByVal<bool>(level, &m_toFileMap, "toFile"); } const std::string& TypedConfigurations::filename(Level level) { return getConfigByRef<std::string>(level, &m_filenameMap, "filename"); } bool TypedConfigurations::toStandardOutput(Level level) { return getConfigByVal<bool>(level, &m_toStandardOutputMap, "toStandardOutput"); } const base::LogFormat& TypedConfigurations::logFormat(Level level) { return getConfigByRef<base::LogFormat>(level, &m_logFormatMap, "logFormat"); } const base::SubsecondPrecision& TypedConfigurations::subsecondPrecision(Level level) { return getConfigByRef<base::SubsecondPrecision>(level, &m_subsecondPrecisionMap, "subsecondPrecision"); } const base::MillisecondsWidth& TypedConfigurations::millisecondsWidth(Level level) { return getConfigByRef<base::MillisecondsWidth>(level, &m_subsecondPrecisionMap, "millisecondsWidth"); } bool TypedConfigurations::performanceTracking(Level level) { return getConfigByVal<bool>(level, &m_performanceTrackingMap, "performanceTracking"); } base::type::fstream_t* TypedConfigurations::fileStream(Level level) { return getConfigByRef<base::FileStreamPtr>(level, &m_fileStreamMap, "fileStream").get(); } std::size_t TypedConfigurations::maxLogFileSize(Level level) { return getConfigByVal<std::size_t>(level, &m_maxLogFileSizeMap, "maxLogFileSize"); } std::size_t TypedConfigurations::logFlushThreshold(Level level) { return getConfigByVal<std::size_t>(level, &m_logFlushThresholdMap, "logFlushThreshold"); } void TypedConfigurations::build(Configurations* configurations) { base::threading::ScopedLock scopedLock(lock()); auto getBool = [] (std::string boolStr) -> bool { // Pass by value for trimming base::utils::Str::trim(boolStr); return (boolStr == "TRUE" || boolStr == "true" || boolStr == "1"); }; std::vector<Configuration*> withFileSizeLimit; for (Configurations::const_iterator it = configurations->begin(); it != configurations->end(); ++it) { Configuration* conf = *it; // We cannot use switch on strong enums because Intel C++ dont support them yet if (conf->configurationType() == ConfigurationType::Enabled) { setValue(conf->level(), getBool(conf->value()), &m_enabledMap); } else if (conf->configurationType() == ConfigurationType::ToFile) { setValue(conf->level(), getBool(conf->value()), &m_toFileMap); } else if (conf->configurationType() == ConfigurationType::ToStandardOutput) { setValue(conf->level(), getBool(conf->value()), &m_toStandardOutputMap); } else if (conf->configurationType() == ConfigurationType::Filename) { // We do not yet configure filename but we will configure in another // loop. This is because if file cannot be created, we will force ToFile // to be false. Because configuring logger is not necessarily performance // sensative operation, we can live with another loop; (by the way this loop // is not very heavy either) } else if (conf->configurationType() == ConfigurationType::Format) { setValue(conf->level(), base::LogFormat(conf->level(), base::type::string_t(conf->value().begin(), conf->value().end())), &m_logFormatMap); } else if (conf->configurationType() == ConfigurationType::SubsecondPrecision) { setValue(Level::Global, base::SubsecondPrecision(static_cast<int>(getULong(conf->value()))), &m_subsecondPrecisionMap); } else if (conf->configurationType() == ConfigurationType::PerformanceTracking) { setValue(Level::Global, getBool(conf->value()), &m_performanceTrackingMap); } else if (conf->configurationType() == ConfigurationType::MaxLogFileSize) { auto v = getULong(conf->value()); setValue(conf->level(), static_cast<std::size_t>(v), &m_maxLogFileSizeMap); if (v != 0) { withFileSizeLimit.push_back(conf); } } else if (conf->configurationType() == ConfigurationType::LogFlushThreshold) { setValue(conf->level(), static_cast<std::size_t>(getULong(conf->value())), &m_logFlushThresholdMap); } } // As mentioned earlier, we will now set filename configuration in separate loop to deal with non-existent files for (Configurations::const_iterator it = configurations->begin(); it != configurations->end(); ++it) { Configuration* conf = *it; if (conf->configurationType() == ConfigurationType::Filename) { insertFile(conf->level(), conf->value()); } } for (std::vector<Configuration*>::iterator conf = withFileSizeLimit.begin(); conf != withFileSizeLimit.end(); ++conf) { // This is not unsafe as mutex is locked in currect scope unsafeValidateFileRolling((*conf)->level(), base::defaultPreRollOutCallback); } } unsigned long TypedConfigurations::getULong(std::string confVal) { bool valid = true; base::utils::Str::trim(confVal); valid = !confVal.empty() && std::find_if(confVal.begin(), confVal.end(), [](char c) { return !base::utils::Str::isDigit(c); }) == confVal.end(); if (!valid) { valid = false; ELPP_ASSERT(valid, "Configuration value not a valid integer [" << confVal << "]"); return 0; } return atol(confVal.c_str()); } std::string TypedConfigurations::resolveFilename(const std::string& filename) { std::string resultingFilename = filename; std::size_t dateIndex = std::string::npos; std::string dateTimeFormatSpecifierStr = std::string(base::consts::kDateTimeFormatSpecifierForFilename); if ((dateIndex = resultingFilename.find(dateTimeFormatSpecifierStr.c_str())) != std::string::npos) { while (dateIndex > 0 && resultingFilename[dateIndex - 1] == base::consts::kFormatSpecifierChar) { dateIndex = resultingFilename.find(dateTimeFormatSpecifierStr.c_str(), dateIndex + 1); } if (dateIndex != std::string::npos) { const char* ptr = resultingFilename.c_str() + dateIndex; // Goto end of specifier ptr += dateTimeFormatSpecifierStr.size(); std::string fmt; if ((resultingFilename.size() > dateIndex) && (ptr[0] == '{')) { // User has provided format for date/time ++ptr; int count = 1; // Start by 1 in order to remove starting brace std::stringstream ss; for (; *ptr; ++ptr, ++count) { if (*ptr == '}') { ++count; // In order to remove ending brace break; } ss << *ptr; } resultingFilename.erase(dateIndex + dateTimeFormatSpecifierStr.size(), count); fmt = ss.str(); } else { fmt = std::string(base::consts::kDefaultDateTimeFormatInFilename); } base::SubsecondPrecision ssPrec(3); std::string now = base::utils::DateTime::getDateTime(fmt.c_str(), &ssPrec); base::utils::Str::replaceAll(now, '/', '-'); // Replace path element since we are dealing with filename base::utils::Str::replaceAll(resultingFilename, dateTimeFormatSpecifierStr, now); } } return resultingFilename; } void TypedConfigurations::insertFile(Level level, const std::string& fullFilename) { std::string resolvedFilename = resolveFilename(fullFilename); if (resolvedFilename.empty()) { std::cerr << "Could not load empty file for logging, please re-check your configurations for level [" << LevelHelper::convertToString(level) << "]"; } std::string filePath = base::utils::File::extractPathFromFilename(resolvedFilename, base::consts::kFilePathSeperator); if (filePath.size() < resolvedFilename.size()) { base::utils::File::createPath(filePath); } auto create = [&](Level level) { base::LogStreamsReferenceMap::iterator filestreamIter = m_logStreamsReference->find(resolvedFilename); base::type::fstream_t* fs = nullptr; if (filestreamIter == m_logStreamsReference->end()) { // We need a completely new stream, nothing to share with fs = base::utils::File::newFileStream(resolvedFilename); m_filenameMap.insert(std::make_pair(level, resolvedFilename)); m_fileStreamMap.insert(std::make_pair(level, base::FileStreamPtr(fs))); m_logStreamsReference->insert(std::make_pair(resolvedFilename, base::FileStreamPtr(m_fileStreamMap.at(level)))); } else { // Woops! we have an existing one, share it! m_filenameMap.insert(std::make_pair(level, filestreamIter->first)); m_fileStreamMap.insert(std::make_pair(level, base::FileStreamPtr(filestreamIter->second))); fs = filestreamIter->second.get(); } if (fs == nullptr) { // We display bad file error from newFileStream() ELPP_INTERNAL_ERROR("Setting [TO_FILE] of [" << LevelHelper::convertToString(level) << "] to FALSE", false); setValue(level, false, &m_toFileMap); } }; // If we dont have file conf for any level, create it for Level::Global first // otherwise create for specified level create(m_filenameMap.empty() && m_fileStreamMap.empty() ? Level::Global : level); } bool TypedConfigurations::unsafeValidateFileRolling(Level level, const PreRollOutCallback& preRollOutCallback) { base::type::fstream_t* fs = unsafeGetConfigByRef(level, &m_fileStreamMap, "fileStream").get(); if (fs == nullptr) { return true; } std::size_t maxLogFileSize = unsafeGetConfigByVal(level, &m_maxLogFileSizeMap, "maxLogFileSize"); std::size_t currFileSize = base::utils::File::getSizeOfFile(fs); if (maxLogFileSize != 0 && currFileSize >= maxLogFileSize) { std::string fname = unsafeGetConfigByRef(level, &m_filenameMap, "filename"); ELPP_INTERNAL_INFO(1, "Truncating log file [" << fname << "] as a result of configurations for level [" << LevelHelper::convertToString(level) << "]"); fs->close(); preRollOutCallback(fname.c_str(), currFileSize); fs->open(fname, std::fstream::out | std::fstream::trunc); return true; } return false; } // RegisteredHitCounters bool RegisteredHitCounters::validateEveryN(const char* filename, base::type::LineNumber lineNumber, std::size_t n) { base::threading::ScopedLock scopedLock(lock()); base::HitCounter* counter = get(filename, lineNumber); if (counter == nullptr) { registerNew(counter = new base::HitCounter(filename, lineNumber)); } counter->validateHitCounts(n); bool result = (n >= 1 && counter->hitCounts() != 0 && counter->hitCounts() % n == 0); return result; } /// @brief Validates counter for hits >= N, i.e, registers new if does not exist otherwise updates original one /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned bool RegisteredHitCounters::validateAfterN(const char* filename, base::type::LineNumber lineNumber, std::size_t n) { base::threading::ScopedLock scopedLock(lock()); base::HitCounter* counter = get(filename, lineNumber); if (counter == nullptr) { registerNew(counter = new base::HitCounter(filename, lineNumber)); } // Do not use validateHitCounts here since we do not want to reset counter here // Note the >= instead of > because we are incrementing // after this check if (counter->hitCounts() >= n) return true; counter->increment(); return false; } /// @brief Validates counter for hits are <= n, i.e, registers new if does not exist otherwise updates original one /// @return True if validation resulted in triggering hit. Meaning logs should be written everytime true is returned bool RegisteredHitCounters::validateNTimes(const char* filename, base::type::LineNumber lineNumber, std::size_t n) { base::threading::ScopedLock scopedLock(lock()); base::HitCounter* counter = get(filename, lineNumber); if (counter == nullptr) { registerNew(counter = new base::HitCounter(filename, lineNumber)); } counter->increment(); // Do not use validateHitCounts here since we do not want to reset counter here if (counter->hitCounts() <= n) return true; return false; } // RegisteredLoggers RegisteredLoggers::RegisteredLoggers(const LogBuilderPtr& defaultLogBuilder) : m_defaultLogBuilder(defaultLogBuilder) { m_defaultConfigurations.setToDefault(); } Logger* RegisteredLoggers::get(const std::string& id, bool forceCreation) { base::threading::ScopedLock scopedLock(lock()); Logger* logger_ = base::utils::Registry<Logger, std::string>::get(id); if (logger_ == nullptr && forceCreation) { bool validId = Logger::isValidId(id); if (!validId) { ELPP_ASSERT(validId, "Invalid logger ID [" << id << "]. Not registering this logger."); return nullptr; } logger_ = new Logger(id, m_defaultConfigurations, &m_logStreamsReference); logger_->m_logBuilder = m_defaultLogBuilder; registerNew(id, logger_); LoggerRegistrationCallback* callback = nullptr; for (const std::pair<std::string, base::type::LoggerRegistrationCallbackPtr>& h : m_loggerRegistrationCallbacks) { callback = h.second.get(); if (callback != nullptr && callback->enabled()) { callback->handle(logger_); } } } return logger_; } bool RegisteredLoggers::remove(const std::string& id) { if (id == base::consts::kDefaultLoggerId) { return false; } // get has internal lock Logger* logger = base::utils::Registry<Logger, std::string>::get(id); if (logger != nullptr) { // unregister has internal lock unregister(logger); } return true; } void RegisteredLoggers::unsafeFlushAll(void) { ELPP_INTERNAL_INFO(1, "Flushing all log files"); for (base::LogStreamsReferenceMap::iterator it = m_logStreamsReference.begin(); it != m_logStreamsReference.end(); ++it) { if (it->second.get() == nullptr) continue; it->second->flush(); } } // VRegistry VRegistry::VRegistry(base::type::VerboseLevel level, base::type::EnumType* pFlags) : m_level(level), m_pFlags(pFlags) { } /// @brief Sets verbose level. Accepted range is 0-9 void VRegistry::setLevel(base::type::VerboseLevel level) { base::threading::ScopedLock scopedLock(lock()); if (level > 9) m_level = base::consts::kMaxVerboseLevel; else m_level = level; } void VRegistry::setModules(const char* modules) { base::threading::ScopedLock scopedLock(lock()); auto addSuffix = [](std::stringstream& ss, const char* sfx, const char* prev) { if (prev != nullptr && base::utils::Str::endsWith(ss.str(), std::string(prev))) { std::string chr(ss.str().substr(0, ss.str().size() - strlen(prev))); ss.str(std::string("")); ss << chr; } if (base::utils::Str::endsWith(ss.str(), std::string(sfx))) { std::string chr(ss.str().substr(0, ss.str().size() - strlen(sfx))); ss.str(std::string("")); ss << chr; } ss << sfx; }; auto insert = [&](std::stringstream& ss, base::type::VerboseLevel level) { if (!base::utils::hasFlag(LoggingFlag::DisableVModulesExtensions, *m_pFlags)) { addSuffix(ss, ".h", nullptr); m_modules.insert(std::make_pair(ss.str(), level)); addSuffix(ss, ".c", ".h"); m_modules.insert(std::make_pair(ss.str(), level)); addSuffix(ss, ".cpp", ".c"); m_modules.insert(std::make_pair(ss.str(), level)); addSuffix(ss, ".cc", ".cpp"); m_modules.insert(std::make_pair(ss.str(), level)); addSuffix(ss, ".cxx", ".cc"); m_modules.insert(std::make_pair(ss.str(), level)); addSuffix(ss, ".-inl.h", ".cxx"); m_modules.insert(std::make_pair(ss.str(), level)); addSuffix(ss, ".hxx", ".-inl.h"); m_modules.insert(std::make_pair(ss.str(), level)); addSuffix(ss, ".hpp", ".hxx"); m_modules.insert(std::make_pair(ss.str(), level)); addSuffix(ss, ".hh", ".hpp"); } m_modules.insert(std::make_pair(ss.str(), level)); }; bool isMod = true; bool isLevel = false; std::stringstream ss; int level = -1; for (; *modules; ++modules) { switch (*modules) { case '=': isLevel = true; isMod = false; break; case ',': isLevel = false; isMod = true; if (!ss.str().empty() && level != -1) { insert(ss, static_cast<base::type::VerboseLevel>(level)); ss.str(std::string("")); level = -1; } break; default: if (isMod) { ss << *modules; } else if (isLevel) { if (isdigit(*modules)) { level = static_cast<base::type::VerboseLevel>(*modules) - 48; } } break; } } if (!ss.str().empty() && level != -1) { insert(ss, static_cast<base::type::VerboseLevel>(level)); } } bool VRegistry::allowed(base::type::VerboseLevel vlevel, const char* file) { base::threading::ScopedLock scopedLock(lock()); if (m_modules.empty() || file == nullptr) { return vlevel <= m_level; } else { char baseFilename[base::consts::kSourceFilenameMaxLength] = ""; base::utils::File::buildBaseFilename(file, baseFilename); std::unordered_map<std::string, base::type::VerboseLevel>::iterator it = m_modules.begin(); for (; it != m_modules.end(); ++it) { if (base::utils::Str::wildCardMatch(baseFilename, it->first.c_str())) { return vlevel <= it->second; } } if (base::utils::hasFlag(LoggingFlag::AllowVerboseIfModuleNotSpecified, *m_pFlags)) { return true; } return false; } } void VRegistry::setFromArgs(const base::utils::CommandLineArgs* commandLineArgs) { if (commandLineArgs->hasParam("-v") || commandLineArgs->hasParam("--verbose") || commandLineArgs->hasParam("-V") || commandLineArgs->hasParam("--VERBOSE")) { setLevel(base::consts::kMaxVerboseLevel); } else if (commandLineArgs->hasParamWithValue("--v")) { setLevel(static_cast<base::type::VerboseLevel>(atoi(commandLineArgs->getParamValue("--v")))); } else if (commandLineArgs->hasParamWithValue("--V")) { setLevel(static_cast<base::type::VerboseLevel>(atoi(commandLineArgs->getParamValue("--V")))); } else if ((commandLineArgs->hasParamWithValue("-vmodule")) && vModulesEnabled()) { setModules(commandLineArgs->getParamValue("-vmodule")); } else if (commandLineArgs->hasParamWithValue("-VMODULE") && vModulesEnabled()) { setModules(commandLineArgs->getParamValue("-VMODULE")); } } #if !defined(ELPP_DEFAULT_LOGGING_FLAGS) # define ELPP_DEFAULT_LOGGING_FLAGS 0x0 #endif // !defined(ELPP_DEFAULT_LOGGING_FLAGS) // Storage #if ELPP_ASYNC_LOGGING Storage::Storage(const LogBuilderPtr& defaultLogBuilder, base::IWorker* asyncDispatchWorker) : #else Storage::Storage(const LogBuilderPtr& defaultLogBuilder) : #endif // ELPP_ASYNC_LOGGING m_registeredHitCounters(new base::RegisteredHitCounters()), m_registeredLoggers(new base::RegisteredLoggers(defaultLogBuilder)), m_flags(ELPP_DEFAULT_LOGGING_FLAGS), m_vRegistry(new base::VRegistry(0, &m_flags)), #if ELPP_ASYNC_LOGGING m_asyncLogQueue(new base::AsyncLogQueue()), m_asyncDispatchWorker(asyncDispatchWorker), #endif // ELPP_ASYNC_LOGGING m_preRollOutCallback(base::defaultPreRollOutCallback) { // Register default logger m_registeredLoggers->get(std::string(base::consts::kDefaultLoggerId)); // We register default logger anyway (worse case it's not going to register) just in case m_registeredLoggers->get("default"); // Register performance logger and reconfigure format Logger* performanceLogger = m_registeredLoggers->get(std::string(base::consts::kPerformanceLoggerId)); m_registeredLoggers->get("performance"); performanceLogger->configurations()->setGlobally(ConfigurationType::Format, std::string("%datetime %level %msg")); performanceLogger->reconfigure(); #if defined(ELPP_SYSLOG) // Register syslog logger and reconfigure format Logger* sysLogLogger = m_registeredLoggers->get(std::string(base::consts::kSysLogLoggerId)); sysLogLogger->configurations()->setGlobally(ConfigurationType::Format, std::string("%level: %msg")); sysLogLogger->reconfigure(); #endif // defined(ELPP_SYSLOG) addFlag(LoggingFlag::AllowVerboseIfModuleNotSpecified); #if ELPP_ASYNC_LOGGING installLogDispatchCallback<base::AsyncLogDispatchCallback>(std::string("AsyncLogDispatchCallback")); #else installLogDispatchCallback<base::DefaultLogDispatchCallback>(std::string("DefaultLogDispatchCallback")); #endif // ELPP_ASYNC_LOGGING #if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) installPerformanceTrackingCallback<base::DefaultPerformanceTrackingCallback> (std::string("DefaultPerformanceTrackingCallback")); #endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) ELPP_INTERNAL_INFO(1, "Easylogging++ has been initialized"); #if ELPP_ASYNC_LOGGING m_asyncDispatchWorker->start(); #endif // ELPP_ASYNC_LOGGING } Storage::~Storage(void) { ELPP_INTERNAL_INFO(4, "Destroying storage"); #if ELPP_ASYNC_LOGGING ELPP_INTERNAL_INFO(5, "Replacing log dispatch callback to synchronous"); uninstallLogDispatchCallback<base::AsyncLogDispatchCallback>(std::string("AsyncLogDispatchCallback")); installLogDispatchCallback<base::DefaultLogDispatchCallback>(std::string("DefaultLogDispatchCallback")); ELPP_INTERNAL_INFO(5, "Destroying asyncDispatchWorker"); base::utils::safeDelete(m_asyncDispatchWorker); ELPP_INTERNAL_INFO(5, "Destroying asyncLogQueue"); base::utils::safeDelete(m_asyncLogQueue); #endif // ELPP_ASYNC_LOGGING ELPP_INTERNAL_INFO(5, "Destroying registeredHitCounters"); base::utils::safeDelete(m_registeredHitCounters); ELPP_INTERNAL_INFO(5, "Destroying registeredLoggers"); base::utils::safeDelete(m_registeredLoggers); ELPP_INTERNAL_INFO(5, "Destroying vRegistry"); base::utils::safeDelete(m_vRegistry); } bool Storage::hasCustomFormatSpecifier(const char* formatSpecifier) { base::threading::ScopedLock scopedLock(customFormatSpecifiersLock()); return std::find(m_customFormatSpecifiers.begin(), m_customFormatSpecifiers.end(), formatSpecifier) != m_customFormatSpecifiers.end(); } void Storage::installCustomFormatSpecifier(const CustomFormatSpecifier& customFormatSpecifier) { if (hasCustomFormatSpecifier(customFormatSpecifier.formatSpecifier())) { return; } base::threading::ScopedLock scopedLock(customFormatSpecifiersLock()); m_customFormatSpecifiers.push_back(customFormatSpecifier); } bool Storage::uninstallCustomFormatSpecifier(const char* formatSpecifier) { base::threading::ScopedLock scopedLock(customFormatSpecifiersLock()); std::vector<CustomFormatSpecifier>::iterator it = std::find(m_customFormatSpecifiers.begin(), m_customFormatSpecifiers.end(), formatSpecifier); if (it != m_customFormatSpecifiers.end() && strcmp(formatSpecifier, it->formatSpecifier()) == 0) { m_customFormatSpecifiers.erase(it); return true; } return false; } void Storage::setApplicationArguments(int argc, char** argv) { m_commandLineArgs.setArgs(argc, argv); m_vRegistry->setFromArgs(commandLineArgs()); // default log file #if !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG) if (m_commandLineArgs.hasParamWithValue(base::consts::kDefaultLogFileParam)) { Configurations c; c.setGlobally(ConfigurationType::Filename, std::string(m_commandLineArgs.getParamValue(base::consts::kDefaultLogFileParam))); registeredLoggers()->setDefaultConfigurations(c); for (base::RegisteredLoggers::iterator it = registeredLoggers()->begin(); it != registeredLoggers()->end(); ++it) { it->second->configure(c); } } #endif // !defined(ELPP_DISABLE_LOG_FILE_FROM_ARG) #if defined(ELPP_LOGGING_FLAGS_FROM_ARG) if (m_commandLineArgs.hasParamWithValue(base::consts::kLoggingFlagsParam)) { int userInput = atoi(m_commandLineArgs.getParamValue(base::consts::kLoggingFlagsParam)); if (ELPP_DEFAULT_LOGGING_FLAGS == 0x0) { m_flags = userInput; } else { base::utils::addFlag<base::type::EnumType>(userInput, &m_flags); } } #endif // defined(ELPP_LOGGING_FLAGS_FROM_ARG) } } // namespace base // LogDispatchCallback void LogDispatchCallback::handle(const LogDispatchData* data) { #if defined(ELPP_THREAD_SAFE) base::threading::ScopedLock scopedLock(m_fileLocksMapLock); std::string filename = data->logMessage()->logger()->typedConfigurations()->filename(data->logMessage()->level()); auto lock = m_fileLocks.find(filename); if (lock == m_fileLocks.end()) { m_fileLocks.emplace(std::make_pair(filename, std::unique_ptr<base::threading::Mutex>(new base::threading::Mutex))); } #endif } base::threading::Mutex& LogDispatchCallback::fileHandle(const LogDispatchData* data) { auto it = m_fileLocks.find(data->logMessage()->logger()->typedConfigurations()->filename(data->logMessage()->level())); return *(it->second.get()); } namespace base { // DefaultLogDispatchCallback void DefaultLogDispatchCallback::handle(const LogDispatchData* data) { #if defined(ELPP_THREAD_SAFE) LogDispatchCallback::handle(data); base::threading::ScopedLock scopedLock(fileHandle(data)); #endif m_data = data; dispatch(m_data->logMessage()->logger()->logBuilder()->build(m_data->logMessage(), m_data->dispatchAction() == base::DispatchAction::NormalLog)); } void DefaultLogDispatchCallback::dispatch(base::type::string_t&& logLine) { if (m_data->dispatchAction() == base::DispatchAction::NormalLog) { if (m_data->logMessage()->logger()->m_typedConfigurations->toFile(m_data->logMessage()->level())) { base::type::fstream_t* fs = m_data->logMessage()->logger()->m_typedConfigurations->fileStream( m_data->logMessage()->level()); if (fs != nullptr) { fs->write(logLine.c_str(), logLine.size()); if (fs->fail()) { ELPP_INTERNAL_ERROR("Unable to write log to file [" << m_data->logMessage()->logger()->m_typedConfigurations->filename(m_data->logMessage()->level()) << "].\n" << "Few possible reasons (could be something else):\n" << " * Permission denied\n" << " * Disk full\n" << " * Disk is not writable", true); } else { if (ELPP->hasFlag(LoggingFlag::ImmediateFlush) || (m_data->logMessage()->logger()->isFlushNeeded(m_data->logMessage()->level()))) { m_data->logMessage()->logger()->flush(m_data->logMessage()->level(), fs); } } } else { ELPP_INTERNAL_ERROR("Log file for [" << LevelHelper::convertToString(m_data->logMessage()->level()) << "] " << "has not been configured but [TO_FILE] is configured to TRUE. [Logger ID: " << m_data->logMessage()->logger()->id() << "]", false); } } if (m_data->logMessage()->logger()->m_typedConfigurations->toStandardOutput(m_data->logMessage()->level())) { if (ELPP->hasFlag(LoggingFlag::ColoredTerminalOutput)) m_data->logMessage()->logger()->logBuilder()->convertToColoredOutput(&logLine, m_data->logMessage()->level()); ELPP_COUT << ELPP_COUT_LINE(logLine); } } #if defined(ELPP_SYSLOG) else if (m_data->dispatchAction() == base::DispatchAction::SysLog) { // Determine syslog priority int sysLogPriority = 0; if (m_data->logMessage()->level() == Level::Fatal) sysLogPriority = LOG_EMERG; else if (m_data->logMessage()->level() == Level::Error) sysLogPriority = LOG_ERR; else if (m_data->logMessage()->level() == Level::Warning) sysLogPriority = LOG_WARNING; else if (m_data->logMessage()->level() == Level::Info) sysLogPriority = LOG_INFO; else if (m_data->logMessage()->level() == Level::Debug) sysLogPriority = LOG_DEBUG; else sysLogPriority = LOG_NOTICE; # if defined(ELPP_UNICODE) char* line = base::utils::Str::wcharPtrToCharPtr(logLine.c_str()); syslog(sysLogPriority, "%s", line); free(line); # else syslog(sysLogPriority, "%s", logLine.c_str()); # endif } #endif // defined(ELPP_SYSLOG) } #if ELPP_ASYNC_LOGGING // AsyncLogDispatchCallback void AsyncLogDispatchCallback::handle(const LogDispatchData* data) { base::type::string_t logLine = data->logMessage()->logger()->logBuilder()->build(data->logMessage(), data->dispatchAction() == base::DispatchAction::NormalLog); if (data->dispatchAction() == base::DispatchAction::NormalLog && data->logMessage()->logger()->typedConfigurations()->toStandardOutput(data->logMessage()->level())) { if (ELPP->hasFlag(LoggingFlag::ColoredTerminalOutput)) data->logMessage()->logger()->logBuilder()->convertToColoredOutput(&logLine, data->logMessage()->level()); ELPP_COUT << ELPP_COUT_LINE(logLine); } // Save resources and only queue if we want to write to file otherwise just ignore handler if (data->logMessage()->logger()->typedConfigurations()->toFile(data->logMessage()->level())) { ELPP->asyncLogQueue()->push(AsyncLogItem(*(data->logMessage()), *data, logLine)); } } // AsyncDispatchWorker AsyncDispatchWorker::AsyncDispatchWorker() { setContinueRunning(false); } AsyncDispatchWorker::~AsyncDispatchWorker() { setContinueRunning(false); ELPP_INTERNAL_INFO(6, "Stopping dispatch worker - Cleaning log queue"); clean(); ELPP_INTERNAL_INFO(6, "Log queue cleaned"); } bool AsyncDispatchWorker::clean(void) { std::mutex m; std::unique_lock<std::mutex> lk(m); cv.wait(lk, [] { return !ELPP->asyncLogQueue()->empty(); }); emptyQueue(); lk.unlock(); cv.notify_one(); return ELPP->asyncLogQueue()->empty(); } void AsyncDispatchWorker::emptyQueue(void) { while (!ELPP->asyncLogQueue()->empty()) { AsyncLogItem data = ELPP->asyncLogQueue()->next(); handle(&data); base::threading::msleep(100); } } void AsyncDispatchWorker::start(void) { base::threading::msleep(5000); // 5s (why?) setContinueRunning(true); std::thread t1(&AsyncDispatchWorker::run, this); t1.join(); } void AsyncDispatchWorker::handle(AsyncLogItem* logItem) { LogDispatchData* data = logItem->data(); LogMessage* logMessage = logItem->logMessage(); Logger* logger = logMessage->logger(); base::TypedConfigurations* conf = logger->typedConfigurations(); base::type::string_t logLine = logItem->logLine(); if (data->dispatchAction() == base::DispatchAction::NormalLog) { if (conf->toFile(logMessage->level())) { base::type::fstream_t* fs = conf->fileStream(logMessage->level()); if (fs != nullptr) { fs->write(logLine.c_str(), logLine.size()); if (fs->fail()) { ELPP_INTERNAL_ERROR("Unable to write log to file [" << conf->filename(logMessage->level()) << "].\n" << "Few possible reasons (could be something else):\n" << " * Permission denied\n" << " * Disk full\n" << " * Disk is not writable", true); } else { if (ELPP->hasFlag(LoggingFlag::ImmediateFlush) || (logger->isFlushNeeded(logMessage->level()))) { logger->flush(logMessage->level(), fs); } } } else { ELPP_INTERNAL_ERROR("Log file for [" << LevelHelper::convertToString(logMessage->level()) << "] " << "has not been configured but [TO_FILE] is configured to TRUE. [Logger ID: " << logger->id() << "]", false); } } } # if defined(ELPP_SYSLOG) else if (data->dispatchAction() == base::DispatchAction::SysLog) { // Determine syslog priority int sysLogPriority = 0; if (logMessage->level() == Level::Fatal) sysLogPriority = LOG_EMERG; else if (logMessage->level() == Level::Error) sysLogPriority = LOG_ERR; else if (logMessage->level() == Level::Warning) sysLogPriority = LOG_WARNING; else if (logMessage->level() == Level::Info) sysLogPriority = LOG_INFO; else if (logMessage->level() == Level::Debug) sysLogPriority = LOG_DEBUG; else sysLogPriority = LOG_NOTICE; # if defined(ELPP_UNICODE) char* line = base::utils::Str::wcharPtrToCharPtr(logLine.c_str()); syslog(sysLogPriority, "%s", line); free(line); # else syslog(sysLogPriority, "%s", logLine.c_str()); # endif } # endif // defined(ELPP_SYSLOG) } void AsyncDispatchWorker::run(void) { while (continueRunning()) { emptyQueue(); base::threading::msleep(10); // 10ms } } #endif // ELPP_ASYNC_LOGGING // DefaultLogBuilder base::type::string_t DefaultLogBuilder::build(const LogMessage* logMessage, bool appendNewLine) const { base::TypedConfigurations* tc = logMessage->logger()->typedConfigurations(); const base::LogFormat* logFormat = &tc->logFormat(logMessage->level()); base::type::string_t logLine = logFormat->format(); char buff[base::consts::kSourceFilenameMaxLength + base::consts::kSourceLineMaxLength] = ""; const char* bufLim = buff + sizeof(buff); if (logFormat->hasFlag(base::FormatFlags::AppName)) { // App name base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kAppNameFormatSpecifier, logMessage->logger()->parentApplicationName()); } if (logFormat->hasFlag(base::FormatFlags::ThreadId)) { // Thread ID base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kThreadIdFormatSpecifier, ELPP->getThreadName(base::threading::getCurrentThreadId())); } if (logFormat->hasFlag(base::FormatFlags::DateTime)) { // DateTime base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kDateTimeFormatSpecifier, base::utils::DateTime::getDateTime(logFormat->dateTimeFormat().c_str(), &tc->subsecondPrecision(logMessage->level()))); } if (logFormat->hasFlag(base::FormatFlags::Function)) { // Function base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFunctionFormatSpecifier, logMessage->func()); } if (logFormat->hasFlag(base::FormatFlags::File)) { // File base::utils::Str::clearBuff(buff, base::consts::kSourceFilenameMaxLength); base::utils::File::buildStrippedFilename(logMessage->file().c_str(), buff); base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFileFormatSpecifier, std::string(buff)); } if (logFormat->hasFlag(base::FormatFlags::FileBase)) { // FileBase base::utils::Str::clearBuff(buff, base::consts::kSourceFilenameMaxLength); base::utils::File::buildBaseFilename(logMessage->file(), buff); base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogFileBaseFormatSpecifier, std::string(buff)); } if (logFormat->hasFlag(base::FormatFlags::Line)) { // Line char* buf = base::utils::Str::clearBuff(buff, base::consts::kSourceLineMaxLength); buf = base::utils::Str::convertAndAddToBuff(logMessage->line(), base::consts::kSourceLineMaxLength, buf, bufLim, false); base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogLineFormatSpecifier, std::string(buff)); } if (logFormat->hasFlag(base::FormatFlags::Location)) { // Location char* buf = base::utils::Str::clearBuff(buff, base::consts::kSourceFilenameMaxLength + base::consts::kSourceLineMaxLength); base::utils::File::buildStrippedFilename(logMessage->file().c_str(), buff); buf = base::utils::Str::addToBuff(buff, buf, bufLim); buf = base::utils::Str::addToBuff(":", buf, bufLim); buf = base::utils::Str::convertAndAddToBuff(logMessage->line(), base::consts::kSourceLineMaxLength, buf, bufLim, false); base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kLogLocationFormatSpecifier, std::string(buff)); } if (logMessage->level() == Level::Verbose && logFormat->hasFlag(base::FormatFlags::VerboseLevel)) { // Verbose level char* buf = base::utils::Str::clearBuff(buff, 1); buf = base::utils::Str::convertAndAddToBuff(logMessage->verboseLevel(), 1, buf, bufLim, false); base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kVerboseLevelFormatSpecifier, std::string(buff)); } if (logFormat->hasFlag(base::FormatFlags::LogMessage)) { // Log message base::utils::Str::replaceFirstWithEscape(logLine, base::consts::kMessageFormatSpecifier, logMessage->message()); } #if !defined(ELPP_DISABLE_CUSTOM_FORMAT_SPECIFIERS) el::base::threading::ScopedLock lock_(ELPP->customFormatSpecifiersLock()); ELPP_UNUSED(lock_); for (std::vector<CustomFormatSpecifier>::const_iterator it = ELPP->customFormatSpecifiers()->begin(); it != ELPP->customFormatSpecifiers()->end(); ++it) { std::string fs(it->formatSpecifier()); base::type::string_t wcsFormatSpecifier(fs.begin(), fs.end()); base::utils::Str::replaceFirstWithEscape(logLine, wcsFormatSpecifier, it->resolver()(logMessage)); } #endif // !defined(ELPP_DISABLE_CUSTOM_FORMAT_SPECIFIERS) if (appendNewLine) logLine += ELPP_LITERAL("\n"); return logLine; } // LogDispatcher void LogDispatcher::dispatch(void) { if (m_proceed && m_dispatchAction == base::DispatchAction::None) { m_proceed = false; } if (!m_proceed) { return; } #ifndef ELPP_NO_GLOBAL_LOCK // see https://github.com/muflihun/easyloggingpp/issues/580 // global lock is turned off by default unless // ELPP_NO_GLOBAL_LOCK is defined base::threading::ScopedLock scopedLock(ELPP->lock()); #endif base::TypedConfigurations* tc = m_logMessage->logger()->m_typedConfigurations; if (ELPP->hasFlag(LoggingFlag::StrictLogFileSizeCheck)) { tc->validateFileRolling(m_logMessage->level(), ELPP->preRollOutCallback()); } LogDispatchCallback* callback = nullptr; LogDispatchData data; for (const std::pair<std::string, base::type::LogDispatchCallbackPtr>& h : ELPP->m_logDispatchCallbacks) { callback = h.second.get(); if (callback != nullptr && callback->enabled()) { data.setLogMessage(m_logMessage); data.setDispatchAction(m_dispatchAction); callback->handle(&data); } } } // MessageBuilder void MessageBuilder::initialize(Logger* logger) { m_logger = logger; m_containerLogSeperator = ELPP->hasFlag(LoggingFlag::NewLineForContainer) ? ELPP_LITERAL("\n ") : ELPP_LITERAL(", "); } MessageBuilder& MessageBuilder::operator<<(const wchar_t* msg) { if (msg == nullptr) { m_logger->stream() << base::consts::kNullPointer; return *this; } # if defined(ELPP_UNICODE) m_logger->stream() << msg; # else char* buff_ = base::utils::Str::wcharPtrToCharPtr(msg); m_logger->stream() << buff_; free(buff_); # endif if (ELPP->hasFlag(LoggingFlag::AutoSpacing)) { m_logger->stream() << " "; } return *this; } // Writer Writer& Writer::construct(Logger* logger, bool needLock) { m_logger = logger; initializeLogger(logger->id(), false, needLock); m_messageBuilder.initialize(m_logger); return *this; } Writer& Writer::construct(int count, const char* loggerIds, ...) { if (ELPP->hasFlag(LoggingFlag::MultiLoggerSupport)) { va_list loggersList; va_start(loggersList, loggerIds); const char* id = loggerIds; m_loggerIds.reserve(count); for (int i = 0; i < count; ++i) { m_loggerIds.push_back(std::string(id)); id = va_arg(loggersList, const char*); } va_end(loggersList); initializeLogger(m_loggerIds.at(0)); } else { initializeLogger(std::string(loggerIds)); } m_messageBuilder.initialize(m_logger); return *this; } void Writer::initializeLogger(const std::string& loggerId, bool lookup, bool needLock) { if (lookup) { m_logger = ELPP->registeredLoggers()->get(loggerId, ELPP->hasFlag(LoggingFlag::CreateLoggerAutomatically)); } if (m_logger == nullptr) { { if (!ELPP->registeredLoggers()->has(std::string(base::consts::kDefaultLoggerId))) { // Somehow default logger has been unregistered. Not good! Register again ELPP->registeredLoggers()->get(std::string(base::consts::kDefaultLoggerId)); } } Writer(Level::Debug, m_file, m_line, m_func).construct(1, base::consts::kDefaultLoggerId) << "Logger [" << loggerId << "] is not registered yet!"; m_proceed = false; } else { if (needLock) { m_logger->acquireLock(); // This should not be unlocked by checking m_proceed because // m_proceed can be changed by lines below } if (ELPP->hasFlag(LoggingFlag::HierarchicalLogging)) { m_proceed = m_level == Level::Verbose ? m_logger->enabled(m_level) : LevelHelper::castToInt(m_level) >= LevelHelper::castToInt(ELPP->m_loggingLevel); } else { m_proceed = m_logger->enabled(m_level); } } } void Writer::processDispatch() { #if ELPP_LOGGING_ENABLED if (ELPP->hasFlag(LoggingFlag::MultiLoggerSupport)) { bool firstDispatched = false; base::type::string_t logMessage; std::size_t i = 0; do { if (m_proceed) { if (firstDispatched) { m_logger->stream() << logMessage; } else { firstDispatched = true; if (m_loggerIds.size() > 1) { logMessage = m_logger->stream().str(); } } triggerDispatch(); } else if (m_logger != nullptr) { m_logger->stream().str(ELPP_LITERAL("")); m_logger->releaseLock(); } if (i + 1 < m_loggerIds.size()) { initializeLogger(m_loggerIds.at(i + 1)); } } while (++i < m_loggerIds.size()); } else { if (m_proceed) { triggerDispatch(); } else if (m_logger != nullptr) { m_logger->stream().str(ELPP_LITERAL("")); m_logger->releaseLock(); } } #else if (m_logger != nullptr) { m_logger->stream().str(ELPP_LITERAL("")); m_logger->releaseLock(); } #endif // ELPP_LOGGING_ENABLED } void Writer::triggerDispatch(void) { if (m_proceed) { if (m_msg == nullptr) { LogMessage msg(m_level, m_file, m_line, m_func, m_verboseLevel, m_logger); base::LogDispatcher(m_proceed, &msg, m_dispatchAction).dispatch(); } else { base::LogDispatcher(m_proceed, m_msg, m_dispatchAction).dispatch(); } } if (m_logger != nullptr) { m_logger->stream().str(ELPP_LITERAL("")); m_logger->releaseLock(); } if (m_proceed && m_level == Level::Fatal && !ELPP->hasFlag(LoggingFlag::DisableApplicationAbortOnFatalLog)) { base::Writer(Level::Warning, m_file, m_line, m_func).construct(1, base::consts::kDefaultLoggerId) << "Aborting application. Reason: Fatal log at [" << m_file << ":" << m_line << "]"; std::stringstream reasonStream; reasonStream << "Fatal log at [" << m_file << ":" << m_line << "]" << " If you wish to disable 'abort on fatal log' please use " << "el::Loggers::addFlag(el::LoggingFlag::DisableApplicationAbortOnFatalLog)"; base::utils::abort(1, reasonStream.str()); } m_proceed = false; } // PErrorWriter PErrorWriter::~PErrorWriter(void) { if (m_proceed) { #if ELPP_COMPILER_MSVC char buff[256]; strerror_s(buff, 256, errno); m_logger->stream() << ": " << buff << " [" << errno << "]"; #else m_logger->stream() << ": " << strerror(errno) << " [" << errno << "]"; #endif } } // PerformanceTracker #if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) PerformanceTracker::PerformanceTracker(const std::string& blockName, base::TimestampUnit timestampUnit, const std::string& loggerId, bool scopedLog, Level level) : m_blockName(blockName), m_timestampUnit(timestampUnit), m_loggerId(loggerId), m_scopedLog(scopedLog), m_level(level), m_hasChecked(false), m_lastCheckpointId(std::string()), m_enabled(false) { #if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED // We store it locally so that if user happen to change configuration by the end of scope // or before calling checkpoint, we still depend on state of configuraton at time of construction el::Logger* loggerPtr = ELPP->registeredLoggers()->get(loggerId, false); m_enabled = loggerPtr != nullptr && loggerPtr->m_typedConfigurations->performanceTracking(m_level); if (m_enabled) { base::utils::DateTime::gettimeofday(&m_startTime); } #endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED } PerformanceTracker::~PerformanceTracker(void) { #if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED if (m_enabled) { base::threading::ScopedLock scopedLock(lock()); if (m_scopedLog) { base::utils::DateTime::gettimeofday(&m_endTime); base::type::string_t formattedTime = getFormattedTimeTaken(); PerformanceTrackingData data(PerformanceTrackingData::DataType::Complete); data.init(this); data.m_formattedTimeTaken = formattedTime; PerformanceTrackingCallback* callback = nullptr; for (const std::pair<std::string, base::type::PerformanceTrackingCallbackPtr>& h : ELPP->m_performanceTrackingCallbacks) { callback = h.second.get(); if (callback != nullptr && callback->enabled()) { callback->handle(&data); } } } } #endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) } void PerformanceTracker::checkpoint(const std::string& id, const char* file, base::type::LineNumber line, const char* func) { #if !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED if (m_enabled) { base::threading::ScopedLock scopedLock(lock()); base::utils::DateTime::gettimeofday(&m_endTime); base::type::string_t formattedTime = m_hasChecked ? getFormattedTimeTaken(m_lastCheckpointTime) : ELPP_LITERAL(""); PerformanceTrackingData data(PerformanceTrackingData::DataType::Checkpoint); data.init(this); data.m_checkpointId = id; data.m_file = file; data.m_line = line; data.m_func = func; data.m_formattedTimeTaken = formattedTime; PerformanceTrackingCallback* callback = nullptr; for (const std::pair<std::string, base::type::PerformanceTrackingCallbackPtr>& h : ELPP->m_performanceTrackingCallbacks) { callback = h.second.get(); if (callback != nullptr && callback->enabled()) { callback->handle(&data); } } base::utils::DateTime::gettimeofday(&m_lastCheckpointTime); m_hasChecked = true; m_lastCheckpointId = id; } #endif // !defined(ELPP_DISABLE_PERFORMANCE_TRACKING) && ELPP_LOGGING_ENABLED ELPP_UNUSED(id); ELPP_UNUSED(file); ELPP_UNUSED(line); ELPP_UNUSED(func); } const base::type::string_t PerformanceTracker::getFormattedTimeTaken(struct timeval startTime) const { if (ELPP->hasFlag(LoggingFlag::FixedTimeFormat)) { base::type::stringstream_t ss; ss << base::utils::DateTime::getTimeDifference(m_endTime, startTime, m_timestampUnit) << " " << base::consts::kTimeFormats[static_cast<base::type::EnumType> (m_timestampUnit)].unit; return ss.str(); } return base::utils::DateTime::formatTime(base::utils::DateTime::getTimeDifference(m_endTime, startTime, m_timestampUnit), m_timestampUnit); } #endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_PERFORMANCE_TRACKING) namespace debug { #if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) // StackTrace StackTrace::StackTraceEntry::StackTraceEntry(std::size_t index, const std::string& loc, const std::string& demang, const std::string& hex, const std::string& addr) : m_index(index), m_location(loc), m_demangled(demang), m_hex(hex), m_addr(addr) { } std::ostream& operator<<(std::ostream& ss, const StackTrace::StackTraceEntry& si) { ss << "[" << si.m_index << "] " << si.m_location << (si.m_hex.empty() ? "" : "+") << si.m_hex << " " << si.m_addr << (si.m_demangled.empty() ? "" : ":") << si.m_demangled; return ss; } std::ostream& operator<<(std::ostream& os, const StackTrace& st) { std::vector<StackTrace::StackTraceEntry>::const_iterator it = st.m_stack.begin(); while (it != st.m_stack.end()) { os << " " << *it++ << "\n"; } return os; } void StackTrace::generateNew(void) { #if ELPP_STACKTRACE m_stack.clear(); void* stack[kMaxStack]; unsigned int size = backtrace(stack, kMaxStack); char** strings = backtrace_symbols(stack, size); if (size > kStackStart) { // Skip StackTrace c'tor and generateNew for (std::size_t i = kStackStart; i < size; ++i) { std::string mangName; std::string location; std::string hex; std::string addr; // entry: 2 crash.cpp.bin 0x0000000101552be5 _ZN2el4base5debug10StackTraceC1Ev + 21 const std::string line(strings[i]); auto p = line.find("_"); if (p != std::string::npos) { mangName = line.substr(p); mangName = mangName.substr(0, mangName.find(" +")); } p = line.find("0x"); if (p != std::string::npos) { addr = line.substr(p); addr = addr.substr(0, addr.find("_")); } // Perform demangling if parsed properly if (!mangName.empty()) { int status = 0; char* demangName = abi::__cxa_demangle(mangName.data(), 0, 0, &status); // if demangling is successful, output the demangled function name if (status == 0) { // Success (see http://gcc.gnu.org/onlinedocs/libstdc++/libstdc++-html-USERS-4.3/a01696.html) StackTraceEntry entry(i - 1, location, demangName, hex, addr); m_stack.push_back(entry); } else { // Not successful - we will use mangled name StackTraceEntry entry(i - 1, location, mangName, hex, addr); m_stack.push_back(entry); } free(demangName); } else { StackTraceEntry entry(i - 1, line); m_stack.push_back(entry); } } } free(strings); #else ELPP_INTERNAL_INFO(1, "Stacktrace generation not supported for selected compiler"); #endif // ELPP_STACKTRACE } // Static helper functions static std::string crashReason(int sig) { std::stringstream ss; bool foundReason = false; for (int i = 0; i < base::consts::kCrashSignalsCount; ++i) { if (base::consts::kCrashSignals[i].numb == sig) { ss << "Application has crashed due to [" << base::consts::kCrashSignals[i].name << "] signal"; if (ELPP->hasFlag(el::LoggingFlag::LogDetailedCrashReason)) { ss << std::endl << " " << base::consts::kCrashSignals[i].brief << std::endl << " " << base::consts::kCrashSignals[i].detail; } foundReason = true; } } if (!foundReason) { ss << "Application has crashed due to unknown signal [" << sig << "]"; } return ss.str(); } /// @brief Logs reason of crash from sig static void logCrashReason(int sig, bool stackTraceIfAvailable, Level level, const char* logger) { std::stringstream ss; ss << "CRASH HANDLED; "; ss << crashReason(sig); #if ELPP_STACKTRACE if (stackTraceIfAvailable) { ss << std::endl << " ======= Backtrace: =========" << std::endl << base::debug::StackTrace(); } #else ELPP_UNUSED(stackTraceIfAvailable); #endif // ELPP_STACKTRACE ELPP_WRITE_LOG(el::base::Writer, level, base::DispatchAction::NormalLog, logger) << ss.str(); } static inline void crashAbort(int sig) { base::utils::abort(sig, std::string()); } /// @brief Default application crash handler /// /// @detail This function writes log using 'default' logger, prints stack trace for GCC based compilers and aborts program. static inline void defaultCrashHandler(int sig) { base::debug::logCrashReason(sig, true, Level::Fatal, base::consts::kDefaultLoggerId); base::debug::crashAbort(sig); } // CrashHandler CrashHandler::CrashHandler(bool useDefault) { if (useDefault) { setHandler(defaultCrashHandler); } } void CrashHandler::setHandler(const Handler& cHandler) { m_handler = cHandler; #if defined(ELPP_HANDLE_SIGABRT) int i = 0; // SIGABRT is at base::consts::kCrashSignals[0] #else int i = 1; #endif // defined(ELPP_HANDLE_SIGABRT) for (; i < base::consts::kCrashSignalsCount; ++i) { m_handler = signal(base::consts::kCrashSignals[i].numb, cHandler); } } #endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) } // namespace debug } // namespace base // el // Helpers #if defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) void Helpers::crashAbort(int sig, const char* sourceFile, unsigned int long line) { std::stringstream ss; ss << base::debug::crashReason(sig).c_str(); ss << " - [Called el::Helpers::crashAbort(" << sig << ")]"; if (sourceFile != nullptr && strlen(sourceFile) > 0) { ss << " - Source: " << sourceFile; if (line > 0) ss << ":" << line; else ss << " (line number not specified)"; } base::utils::abort(sig, ss.str()); } void Helpers::logCrashReason(int sig, bool stackTraceIfAvailable, Level level, const char* logger) { el::base::debug::logCrashReason(sig, stackTraceIfAvailable, level, logger); } #endif // defined(ELPP_FEATURE_ALL) || defined(ELPP_FEATURE_CRASH_LOG) // Loggers Logger* Loggers::getLogger(const std::string& identity, bool registerIfNotAvailable) { return ELPP->registeredLoggers()->get(identity, registerIfNotAvailable); } void Loggers::setDefaultLogBuilder(el::LogBuilderPtr& logBuilderPtr) { ELPP->registeredLoggers()->setDefaultLogBuilder(logBuilderPtr); } bool Loggers::unregisterLogger(const std::string& identity) { return ELPP->registeredLoggers()->remove(identity); } bool Loggers::hasLogger(const std::string& identity) { return ELPP->registeredLoggers()->has(identity); } Logger* Loggers::reconfigureLogger(Logger* logger, const Configurations& configurations) { if (!logger) return nullptr; logger->configure(configurations); return logger; } Logger* Loggers::reconfigureLogger(const std::string& identity, const Configurations& configurations) { return Loggers::reconfigureLogger(Loggers::getLogger(identity), configurations); } Logger* Loggers::reconfigureLogger(const std::string& identity, ConfigurationType configurationType, const std::string& value) { Logger* logger = Loggers::getLogger(identity); if (logger == nullptr) { return nullptr; } logger->configurations()->set(Level::Global, configurationType, value); logger->reconfigure(); return logger; } void Loggers::reconfigureAllLoggers(const Configurations& configurations) { for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->begin(); it != ELPP->registeredLoggers()->end(); ++it) { Loggers::reconfigureLogger(it->second, configurations); } } void Loggers::reconfigureAllLoggers(Level level, ConfigurationType configurationType, const std::string& value) { for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->begin(); it != ELPP->registeredLoggers()->end(); ++it) { Logger* logger = it->second; logger->configurations()->set(level, configurationType, value); logger->reconfigure(); } } void Loggers::setDefaultConfigurations(const Configurations& configurations, bool reconfigureExistingLoggers) { ELPP->registeredLoggers()->setDefaultConfigurations(configurations); if (reconfigureExistingLoggers) { Loggers::reconfigureAllLoggers(configurations); } } const Configurations* Loggers::defaultConfigurations(void) { return ELPP->registeredLoggers()->defaultConfigurations(); } const base::LogStreamsReferenceMap* Loggers::logStreamsReference(void) { return ELPP->registeredLoggers()->logStreamsReference(); } base::TypedConfigurations Loggers::defaultTypedConfigurations(void) { return base::TypedConfigurations( ELPP->registeredLoggers()->defaultConfigurations(), ELPP->registeredLoggers()->logStreamsReference()); } std::vector<std::string>* Loggers::populateAllLoggerIds(std::vector<std::string>* targetList) { targetList->clear(); for (base::RegisteredLoggers::iterator it = ELPP->registeredLoggers()->list().begin(); it != ELPP->registeredLoggers()->list().end(); ++it) { targetList->push_back(it->first); } return targetList; } void Loggers::configureFromGlobal(const char* globalConfigurationFilePath) { std::ifstream gcfStream(globalConfigurationFilePath, std::ifstream::in); ELPP_ASSERT(gcfStream.is_open(), "Unable to open global configuration file [" << globalConfigurationFilePath << "] for parsing."); std::string line = std::string(); std::stringstream ss; Logger* logger = nullptr; auto configure = [&](void) { ELPP_INTERNAL_INFO(8, "Configuring logger: '" << logger->id() << "' with configurations \n" << ss.str() << "\n--------------"); Configurations c; c.parseFromText(ss.str()); logger->configure(c); }; while (gcfStream.good()) { std::getline(gcfStream, line); ELPP_INTERNAL_INFO(1, "Parsing line: " << line); base::utils::Str::trim(line); if (Configurations::Parser::isComment(line)) continue; Configurations::Parser::ignoreComments(&line); base::utils::Str::trim(line); if (line.size() > 2 && base::utils::Str::startsWith(line, std::string(base::consts::kConfigurationLoggerId))) { if (!ss.str().empty() && logger != nullptr) { configure(); } ss.str(std::string("")); line = line.substr(2); base::utils::Str::trim(line); if (line.size() > 1) { ELPP_INTERNAL_INFO(1, "Getting logger: '" << line << "'"); logger = getLogger(line); } } else { ss << line << "\n"; } } if (!ss.str().empty() && logger != nullptr) { configure(); } } bool Loggers::configureFromArg(const char* argKey) { #if defined(ELPP_DISABLE_CONFIGURATION_FROM_PROGRAM_ARGS) ELPP_UNUSED(argKey); #else if (!Helpers::commandLineArgs()->hasParamWithValue(argKey)) { return false; } configureFromGlobal(Helpers::commandLineArgs()->getParamValue(argKey)); #endif // defined(ELPP_DISABLE_CONFIGURATION_FROM_PROGRAM_ARGS) return true; } void Loggers::flushAll(void) { ELPP->registeredLoggers()->flushAll(); } void Loggers::setVerboseLevel(base::type::VerboseLevel level) { ELPP->vRegistry()->setLevel(level); } base::type::VerboseLevel Loggers::verboseLevel(void) { return ELPP->vRegistry()->level(); } void Loggers::setVModules(const char* modules) { if (ELPP->vRegistry()->vModulesEnabled()) { ELPP->vRegistry()->setModules(modules); } } void Loggers::clearVModules(void) { ELPP->vRegistry()->clearModules(); } // VersionInfo const std::string VersionInfo::version(void) { return std::string("9.96.4"); } /// @brief Release date of current version const std::string VersionInfo::releaseDate(void) { return std::string("03-04-2018 1019hrs"); } } // namespace el
c5e3abc5c7cc479ae272f3513690c8544b68928b
707b9564d3d7d9c55a748974e273f1a8a5816eb5
/paths_in_graphs2/shortest_paths.cpp
b683e16ffeef6d6a232b6fd6c060bd3b6c710f37
[]
no_license
Aditya88Gupta/Graphs
d2186581194342d5515570772059da3ccf379e41
83a2d32c5962bbbbe90504bc469229b2c558e974
refs/heads/main
2023-06-02T08:38:57.071525
2021-06-22T06:32:26
2021-06-22T06:32:26
338,612,970
0
0
null
null
null
null
UTF-8
C++
false
false
2,505
cpp
#include <iostream> #include <limits> #include <vector> #include <queue> using std::vector; using std::queue; void BFS(vector<vector<int> > &adj, vector<bool> Visited, vector<bool> &shortest){ queue<int> Q; for(size_t i=0;i<adj.size();i++){ if(Visited[i]==true) Q.push(i); } while(!Q.empty()){ int vertex= Q.front(); Q.pop(); shortest[vertex]=false; vector<int> neighbours= adj[vertex]; for(int i=0;i<neighbours.size();i++){ if(Visited[neighbours[i]]==false){ Q.push(neighbours[i]); Visited[neighbours[i]]=true; } } } } void EdgeRelax(vector<long long> &Dist, int v, int u, long cost, bool &Relaxed){ if (Dist[u]<std::numeric_limits<long long>::max() && Dist[v]>Dist[u]+cost){ Dist[v] = Dist[u]+cost; Relaxed=true; } } vector<bool> BellmanFord(int vertex, vector<vector<int> > &adj, vector<vector<int> > cost, vector<long long> &Dist){ Dist[vertex] = 0; int count = 0; vector<bool> Visited(adj.size(),false); while(count<adj.size()){ for(size_t k=0;k<adj.size();k++){ vector<int> neighbours = adj[k]; for(size_t i=0;i<neighbours.size();i++){ bool Relaxed = false; EdgeRelax(Dist,neighbours[i],k,cost[k][i],Relaxed); if(count==adj.size()-1) Visited[neighbours[i]]=Relaxed; } } count++; } return Visited; } void shortest_paths(vector<vector<int> > &adj, vector<vector<int> > &cost, int s, vector<long long> &distance, vector<bool> &reachable, vector<bool> &shortest) { vector<bool> Visited = BellmanFord(s,adj,cost,distance); reachable[s]=true; for(size_t i=0;i<distance.size();i++){ if(distance[i]<std::numeric_limits<long long>::max()) reachable[i]=true; } BFS(adj,Visited,shortest); } int main() { int n, m, s; std::cin >> n >> m; vector<vector<int> > adj(n, vector<int>()); vector<vector<int> > cost(n, vector<int>()); for (int i = 0; i < m; i++) { int x, y, w; std::cin >> x >> y >> w; adj[x - 1].push_back(y - 1); cost[x - 1].push_back(w); } std::cin >> s; s--; vector<long long> distance(n, std::numeric_limits<long long>::max()); vector<bool> reachable(n, false); vector<bool> shortest(n, true); shortest_paths(adj, cost, s, distance, reachable, shortest); for (int i = 0; i < n; i++) { if (!reachable[i]) { std::cout << "*\n"; } else if (!shortest[i]) { std::cout << "-\n"; } else { std::cout << distance[i] << "\n"; } } }
ca97173781cf2e744b41fbb79f8376a6bfbdf163
a6b698105aec67701cdd509cb9a48528786049d2
/RegainEarthCheat/SDK/W_Setting_SoundFrame_classes.h
94683dc60c913616492b0e56846c0348ab7ed3b6
[]
no_license
ejiaogl/RegainEarth-Cheat
859d44d8400a3694b4e946061b20d30561c6304f
4136c2c11e78e9dbb305e55556928dfba7f4f620
refs/heads/master
2023-08-29T09:39:45.222291
2021-10-19T19:56:05
2021-10-19T19:56:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
8,116
h
#pragma once // Name: RegainEart-FirtstStrike, Version: Version-1 /*!!DEFINE!!*/ /*!!HELPER_DEF!!*/ /*!!HELPER_INC!!*/ #ifdef _MSC_VER #pragma pack(push, 0x01) #endif namespace CG { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // WidgetBlueprintGeneratedClass W_Setting_SoundFrame.W_Setting_SoundFrame_C // 0x00B1 (FullSize[0x0341] - InheritedSize[0x0290]) class UW_Setting_SoundFrame_C : public UW_ParentWidget_C { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x0290(0x0008) (ZeroConstructor, Transient, DuplicateTransient, UObjectWrapper) class UOverlay* Overlay_2; // 0x0298(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UTextBlock* TextBlock_2; // 0x02A0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UVerticalBox* VerticalBox_1; // 0x02A8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UW_SliderButton_C* W_Amb; // 0x02B0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UW_MainFrameButton_C* W_Back; // 0x02B8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UW_SliderButton_C* W_Dial; // 0x02C0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UW_SliderButton_C* W_Effects; // 0x02C8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UW_SliderButton_C* W_Ex1; // 0x02D0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UW_SliderButton_C* W_Ex2; // 0x02D8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UW_SliderButton_C* W_Master; // 0x02E0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UW_SliderButton_C* W_Music; // 0x02E8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UW_MainFrameButton_C* W_ResChang; // 0x02F0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UW_MainFrameButton_C* W_ResDef; // 0x02F8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UW_TimerWarningFrame_C* W_WarningFrame; // 0x0300(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UWidgetSwitcher* WidgetSwitcher_1; // 0x0308(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, NoDestructor, PersistentInstance, HasGetValueTypeHash) class UBP_Save_Sound_Settings_C* SaveSettings; // 0x0310(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash) struct FSSettings_Sounds SettingsBufer; // 0x0318(0x001C) (Edit, BlueprintVisible, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash) unsigned char UnknownData_TSD1[0x4]; // 0x0334(0x0004) MISSED OFFSET (FIX SPACE BETWEEN PREVIOUS PROPERTY) class UBP_GameInstance_RE_C* GameInstance; // 0x0338(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor, HasGetValueTypeHash) bool ConstructorRunAlready; // 0x0340(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData, NoDestructor) static UClass* StaticClass() { static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass W_Setting_SoundFrame.W_Setting_SoundFrame_C"); return ptr; } float CalcAndClampSound(int inInt); void RestoreButtonsVisibility(); bool IsSettingsEqual(const struct FSSettings_Sounds& A, const struct FSSettings_Sounds& B); void Save_SaveSettings(); void ApplySettings(const struct FSSettings_Sounds& SSettings_Sounds, float Fade); void RestoreValues(const struct FSSettings_Sounds& SSettings_Sounds); void Construct(); void BndEvt__W_MainFrameButton_0_K2Node_ComponentBoundEvent_177_OnPressed__DelegateSignature(const struct FName& ID, class UW_ParentButtons_C* ParentButton); void BndEvt__W_MainFrameButton_1_K2Node_ComponentBoundEvent_190_OnPressed__DelegateSignature(const struct FName& ID, class UW_ParentButtons_C* ParentButton); void BndEvt__W_Master_K2Node_ComponentBoundEvent_22_OnChangeValue__DelegateSignature(int NewValue); void BndEvt__W_Music_K2Node_ComponentBoundEvent_23_OnChangeValue__DelegateSignature(int NewValue); void BndEvt__W_Effects_K2Node_ComponentBoundEvent_24_OnChangeValue__DelegateSignature(int NewValue); void BndEvt__W_Dial_K2Node_ComponentBoundEvent_25_OnChangeValue__DelegateSignature(int NewValue); void BndEvt__W_Amb_K2Node_ComponentBoundEvent_26_OnChangeValue__DelegateSignature(int NewValue); void BndEvt__W_Ex1_K2Node_ComponentBoundEvent_27_OnChangeValue__DelegateSignature(int NewValue); void BndEvt__W_Ex2_K2Node_ComponentBoundEvent_28_OnChangeValue__DelegateSignature(int NewValue); void ActiveWidget(bool IsActive); void OnHovered(const struct FText& Description, class UW_ParentButtons_C* ParentButton); void BndEvt__W_WarningFrame_K2Node_ComponentBoundEvent_0_OnSave__DelegateSignature(); void BndEvt__W_WarningFrame_K2Node_ComponentBoundEvent_1_OnCancel__DelegateSignature(); void AllButtonsPressedEvents(const struct FName& ID, class UW_ParentButtons_C* ParentButton); void ExecuteUbergraph_W_Setting_SoundFrame(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
161e054f468322015256a4ed5c336c6a52d717c5
39eca8f785bb50992d5d1ce97e1b05cb8445954a
/USACO/2016OpenGold/SplittingTheField.cpp
26d4290220da75218939ddcdf20d54e400addce2
[]
no_license
diegoteran/Contest-Archive
eea5c14f17812216d48e89ec121a326328d8b6a5
0992a5914ec0b9140a33c2219b3cf740b2dc0658
refs/heads/master
2021-05-16T02:45:57.126921
2017-09-28T02:37:50
2017-09-28T02:37:50
42,429,676
0
0
null
null
null
null
UTF-8
C++
false
false
1,626
cpp
#include <iostream> #include <fstream> #include <algorithm> #define fst first #define snd second #define MAXN 50010 #define mp make_pair using namespace std; typedef pair<long long, long long> pii; long long N, x, y, xMax[MAXN], xMin[MAXN], yMax[MAXN], yMin[MAXN], A, B, a, b; pii xf[MAXN]; int main(){ ifstream in ("split.in"); ofstream out ("split.out"); in >> N; a = b = 1000000009; A = B = 0; for (int i = 0; i < N; i++){ in >> x >> y; xf[i] = mp(x, y); a = min(a, x); b = min(b, y); A = max(A, x); B = max(B, y); } sort(xf, xf+N); yMax[0] = yMin[0] = xf[0].snd; xMax[N-1] = xMin[N-1] = xf[N-1].snd; for(int i = 1; i < N; i++){ yMax[i] = max(yMax[i-1], xf[i].snd); yMin[i] = min(yMin[i-1], xf[i].snd); xMax[N-1-i] = max(xMax[N-i], xf[N-1-i].snd); xMin[N-1-i] = min(xMin[N-i], xf[N-1-i].snd); } long long ans = (xf[N-1].fst - xf[0].fst) * (yMax[N-1] - yMin[N-1]); for(int i = 1; i < N; i++) ans = min(ans, (xf[i-1].fst - xf[0].fst)*(yMax[i-1] - yMin[i-1]) + (xf[N-1].fst - xf[i].fst)*(xMax[i] - xMin[i])); for(int i = 0; i < N; i++) xf[i] = mp(xf[i].snd, xf[i].fst); sort(xf, xf+N); yMax[0] = yMin[0] = xf[0].snd; xMax[N-1] = xMin[N-1] = xf[N-1].snd; for(int i = 1; i < N; i++){ yMax[i] = max(yMax[i-1], xf[i].snd); yMin[i] = min(yMin[i-1], xf[i].snd); xMax[N-1-i] = max(xMax[N-i], xf[N-1-i].snd); xMin[N-1-i] = min(xMin[N-i], xf[N-1-i].snd); } for(int i = 1; i < N; i++) ans = min(ans, (xf[i-1].fst - xf[0].fst)*(yMax[i-1] - yMin[i-1]) + (xf[N-1].fst - xf[i].fst)*(xMax[i] - xMin[i])); ans = (A-a)*(B-b) - ans; out << ans << endl; }
019ffd74308eb759a81486888ccd2f49d5934fa4
ee5880c557312a993caf74ad1bda6e4b810fdd6f
/CArmWorkStation/FunctionalWidget/Config/QConfigPageAbstract.h
34ba0903551d9d7233eeeaf60ca82ccc8f4babb8
[]
no_license
isliulin/MobileCArm
f6d8fa49d57f2d4558783337daa36a5c83df85c4
344776d2f960855cc5c13e303aa1e6a801dcc224
refs/heads/master
2023-03-18T22:08:34.517191
2020-09-10T02:32:28
2020-09-10T02:32:28
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,168
h
#ifndef QCONFIGPAGEABSTRACT_H #define QCONFIGPAGEABSTRACT_H #include <QWidget> #include "Config.h" #define ToQSTR(v) (QString::fromStdString(v)) #define QStr2Std(v) (v.QString::toStdString()) #define UNOVERWRITEVIRTUAL() virtual void updatePage(){}; \ virtual void savePage(){}; \ virtual void enteryPage(){}; \ virtual void exitPage(){}; namespace Ui { class SystemConfigWidget; } // namespace Ui class QConfigPageAbstract : public QWidget { Q_OBJECT public: explicit QConfigPageAbstract(QWidget *parent = 0); virtual ~QConfigPageAbstract(); virtual void updatePage() = 0; virtual void savePage() = 0; virtual void enteryPage() = 0; virtual void exitPage() = 0; virtual void init(); static void setUiPtr(Ui::SystemConfigWidget *); static void saveSystemCfg(); static void updateSysCfg(); signals: void entery(QConfigPageAbstract *); void exit(QConfigPageAbstract *); public slots: public: static CArmConfig cfg; static Ui::SystemConfigWidget *ui; }; #endif // QCONFIGPAGEABSTRACT_H
62496f4c415b0e82cbd1fb496077d28bb61f2fee
67bf93cfae8f8153e65601fd3bc5442349ee665c
/Chapter14/winec2.cpp
ed2fc2f0baf3cb7038f27e340195b9913018988b
[]
no_license
Ali-Fawzi-Lateef/C-PrimerPlus
ce86c880dc3a2b6b4eda6a277463563136c1cc00
f53bca85c36dffb768aa18a15d0446dd766fe309
refs/heads/master
2023-08-02T02:38:05.418154
2021-09-23T18:06:47
2021-09-23T18:06:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,399
cpp
// winec2.cpp -- implementation of the wine class // This is exercise 1 of chapter 14 in C++ Primer Plus 5e by Stephen Prata #include"winec2.h" #include<iostream> using std::string; Wine::Wine(const char * l, int y, const int yr[], const int bot[]) : PairArray(ArrayInt(y), ArrayInt(y)), string(l) { years = y; for (int i = 0; i < years; i++) { PairArray::first()[i] = yr[i]; PairArray::second()[i] = bot[i]; } } Wine::Wine(const char * l, int y) : PairArray(ArrayInt(y), ArrayInt(y)), string(l) { years = y; } Wine::~Wine() { } void Wine::Show() const { using std::cout; using std::endl; cout << "Wine: " << Label() << endl; cout << "\tYear\tBottles" << endl; for (int i = 0; i < years; i++) { cout << "\t" << PairArray::first()[i] << "\t"; cout << PairArray::second()[i] << endl; } } void Wine::GetBottles() { using std::cout; using std::endl; using std::cin; cout << "Enter " << Label() << " data for " << years << " year(s):\n"; int input; for (int i = 0; i < years; i++) { cout << "Enter year: "; cin >> input; PairArray::first()[i] = input; cout << "Enter bottles for that year: "; cin >> input; PairArray::second()[i] = input; } } const string & Wine::Label() const { return (const string &) (*this); } int Wine::sum() const { int sum = 0; for (int i = 0; i < years; i++) sum += PairArray::second()[i]; return sum; }
00442e223c2624c08077f1514b72fc273509cf45
571c183a1177d22a1e49b1b5d12136dbbda1f3a2
/boost/di/concepts/creatable.hpp
ef565eab9c60b52ca536c0fdd5c5f40008b53747
[]
no_license
wher021/DependencyInjection
bb7d0470307cbc4649c211c85e9f988b2b85ea53
ba263f090e7ed4c0d7f81d95641fe7c971a533c0
refs/heads/master
2021-04-09T16:10:25.645729
2018-03-18T11:11:18
2018-03-18T11:11:18
125,716,455
0
0
null
null
null
null
UTF-8
C++
false
false
5,720
hpp
// // Copyright (c) 2012-2018 Kris Jusiak (kris at jusiak dot net) // // 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 BOOST_DI_CONCEPTS_CREATABLE_HPP #define BOOST_DI_CONCEPTS_CREATABLE_HPP #include "boost/di/aux_/compiler.hpp" #include "boost/di/aux_/type_traits.hpp" #include "boost/di/aux_/utility.hpp" #include "boost/di/type_traits/ctor_traits.hpp" #define __BOOST_DI_CONCEPTS_CREATABLE_ERROR_MSG __BOOST_DI_DEPRECATED("creatable constraint not satisfied") namespace concepts { template <class T> struct abstract_type { struct is_not_bound { operator T*() const { using constraint_not_satisfied = is_not_bound; return constraint_not_satisfied{}.error(); } // clang-format off static inline T* error(_ = "type is not bound, did you forget to add: 'di::bind<interface>.to<implementation>()'?"); // clang-format on }; template <class TName> struct named { struct is_not_bound { operator T*() const { using constraint_not_satisfied = is_not_bound; return constraint_not_satisfied{}.error(); } // clang-format off static inline T* error(_ = "type is not bound, did you forget to add: 'di::bind<interface>.named(name).to<implementation>()'?"); // clang-format on }; }; }; template <class TScope, class T> struct scoped { template <class To> struct is_not_convertible_to { operator To() const { using constraint_not_satisfied = is_not_convertible_to; return constraint_not_satisfied{}.error(); } // clang-format off static inline To error(_ = "scoped object is not convertible to the requested type, did you mistake the scope: 'di::bind<T>.in(scope)'?"); // clang-format on }; }; template <class T> struct scoped<scopes::instance, T> { template <class To> struct is_not_convertible_to { operator To() const { using constraint_not_satisfied = is_not_convertible_to; return constraint_not_satisfied{}.error(); } // clang-format off static inline To error(_ = "instance is not convertible to the requested type, verify binding: 'di::bind<T>.to(value)'?"); // clang-format on }; }; template <class T> struct type { struct has_ambiguous_number_of_constructor_parameters { template <int Given> struct given { template <int Expected> struct expected { operator T*() const { using constraint_not_satisfied = expected; return constraint_not_satisfied{}.error(); } // clang-format off static inline T* error(_ = "verify BOOST_DI_INJECT_TRAITS or di::ctor_traits"); // clang-format on }; }; }; struct has_to_many_constructor_parameters { template <int TMax> struct max { operator T*() const { using constraint_not_satisfied = max; return constraint_not_satisfied{}.error(); } // clang-format off static inline T* error(_ = "increase BOOST_DI_CFG_CTOR_LIMIT_SIZE value or reduce number of constructor parameters"); // clang-format on }; }; struct is_not_exposed { operator T() const { using constraint_not_satisfied = is_not_exposed; return constraint_not_satisfied{}.error(); } // clang-format off static inline T error(_ = "type is not exposed, did you forget to add: 'di::injector<T>'?"); // clang-format on }; template <class TName> struct named { struct is_not_exposed { operator T() const { using constraint_not_satisfied = is_not_exposed; return constraint_not_satisfied{}.error(); } // clang-format off static inline T error(_ = "type is not exposed, did you forget to add: 'di::injector<BOOST_DI_EXPOSE((named = name)T)>'?"); // clang-format on }; }; }; template <class> struct ctor_size; template <class TInit, class... TCtor> struct ctor_size<aux::pair<TInit, aux::type_list<TCtor...>>> : aux::integral_constant<int, sizeof...(TCtor)> {}; template <class... TCtor> struct ctor_size<aux::type_list<TCtor...>> : aux::integral_constant<int, sizeof...(TCtor)> {}; template <class T> using ctor_size_t = ctor_size<typename type_traits::ctor<T, type_traits::ctor_impl_t<aux::is_constructible, T>>::type>; template <class TInitialization, class TName, class _, class TCtor, class T = aux::decay_t<_>> struct creatable_error_impl : aux::conditional_t< aux::is_polymorphic<T>::value, aux::conditional_t<aux::is_same<TName, no_name>::value, typename abstract_type<T>::is_not_bound, typename abstract_type<T>::template named<TName>::is_not_bound>, aux::conditional_t<ctor_size_t<T>::value == ctor_size<TCtor>::value, typename type<T>::has_to_many_constructor_parameters::template max<BOOST_DI_CFG_CTOR_LIMIT_SIZE>, typename type<T>::has_ambiguous_number_of_constructor_parameters::template given< ctor_size<TCtor>::value>::template expected<ctor_size_t<T>::value>>> {}; template <class TInit, class T, class... TArgs> struct creatable { static constexpr auto value = aux::is_constructible<T, TArgs...>::value; }; template <class T, class... TArgs> struct creatable<type_traits::uniform, T, TArgs...> { static constexpr auto value = aux::is_braces_constructible<T, TArgs...>::value; }; template <class TInitialization, class TName, class T, class... TArgs> T creatable_error() { return creatable_error_impl<TInitialization, TName, T, aux::type_list<TArgs...>>{}; } } // concepts #endif
0e543e818a13a91e6a620a5fa16eae00ac70d9a4
a7b5d8c15ed289e75c026709923a032ba5eacb6b
/ercf/code/ERCF.cpp
212afd5e501a3457a41715678fa3551fa1631a26
[]
no_license
ojaisnielsen/mva-2011-computer-vision
5ee3ba68d980237640c1287b32d26a5552f77d4e
845ee994e3bee5dc9999da5aa218a927d394e6ef
refs/heads/master
2020-05-17T15:29:27.964649
2019-04-27T15:45:41
2019-04-27T15:45:41
183,791,786
0
0
null
null
null
null
UTF-8
C++
false
false
7,579
cpp
/*! \file */ #include "stdafx.h" #include "ErcForest.h" #include "tools.h" #include "FeatureExtractor.h" #include "Classifier.h" using namespace ercf; void train(vector<string> imageSearchPaths, vector<string> maskSearchPaths, unsigned int featureType, unsigned int maxNPictures) { unsigned int nClasses = imageSearchPaths.size(); unsigned int maxNDescriptorsPerImage = 67; unsigned int patchSize = 16; unsigned int imageBucketSize = 20; CImgList<double> featureList(maxNDescriptorsPerImage * maxNPictures * nClasses); vector<unsigned int> labels(featureList.size(), 0); CImg<double> positions(featureList.size(), 2); unsigned int nDescriptors = 0; Timer totalTimer; vector<unsigned int> nDescriptorsPerImage(maxNPictures * nClasses); unsigned int nImages = 0; totalTimer.begin(); for (int c = 0; c < nClasses; ++c) { bool useMasks = (maskSearchPaths[c].size() != 0); vector<string> imagePaths = getFileNames(imageSearchPaths[c]); unsigned int nPictures = min(imagePaths.size(), maxNPictures); vector<string> maskPaths; if (useMasks) { maskPaths = getFileNames(maskSearchPaths[c]); nPictures = min(nPictures, maskPaths.size()); } cout << "Found " << nPictures << "/" << maxNPictures << " pictures "; if (useMasks) cout << "and masks "; cout << "of class " << c << "/" << nClasses << "." << endl; for (int i = 0; i < nPictures; i += imageBucketSize) { CImgList<double> imList; CImgList<bool> maskList; CImgList<bool> *maskListPtr; Timer timer; maskListPtr = useMasks ? &maskList : NULL; unsigned int i0 = i; unsigned int i1 = min(nPictures, i0 + imageBucketSize); timer.begin(); loadImages<double>(imList, vector<string>(imagePaths.begin() + i0, imagePaths.begin() + i1)); cout << "Pictures " << i0 << "->" << i1 << "/" << nPictures << " of class " << c << "/" << nClasses << " loaded in " << timer.end() << "s." << endl; if (useMasks) { timer.begin(); loadImages<bool>(maskList, vector<string>(maskPaths.begin() + i0, maskPaths.begin() + i1)); cout << "Masks " << i0 << "->" << i1 << "/" << nPictures << " of class " << c << "/" << nClasses << " loaded in " << timer.end() << "s." << endl; } timer.begin(); FeatureExtractor featureExtractor(&featureList, nDescriptorsPerImage.data() + nImages, &labels, maxNDescriptorsPerImage, &imList, maskListPtr); cout << "Feature extractor created in " << timer.end() << "s" << endl; //featureExtractor.setDisplay(true); timer.begin(); unsigned int nNewDecriptors; if (featureType == 0) nNewDecriptors = featureExtractor.getMultipleHsl(nDescriptors, 0, imList.size(), patchSize, c); else if (featureType == 1) nNewDecriptors = featureExtractor.getMultipleHslHaar(nDescriptors, 0, imList.size(), patchSize, c); else nNewDecriptors = featureExtractor.getMultipleSift(nDescriptors, 0, imList.size(), c); cout << "Descriptors " << nDescriptors << "->" << nDescriptors + nNewDecriptors << "/" << featureList.size() << " descriptors extracted in " << timer.end() << "s" << endl; nDescriptors += nNewDecriptors; nImages += i1 - i0; } } cout << "Spent " << totalTimer.end() << "s loading data and extracting " << nDescriptors << "/" << featureList.size() << "features." << endl; while (featureList.size() > nDescriptors) featureList.pop_back(); CImg<double> features = featureList.get_append('x'); totalTimer.begin(); TrainingSet set(&features, &labels, nClasses); cout << "Training set created in " << totalTimer.end() << "s." << endl; totalTimer.begin(); ErcForest forest(5); forest.train(set, 0.5, set.getFeatureDim()); forest.prune(1000); forest.save("forest.xml"); cout << "Spent " << totalTimer.end() << "s training the forest and saving it to \"forest.xml\"." << endl; totalTimer.begin(); Classifier classifier(&forest); classifier.train(set, nDescriptorsPerImage); classifier.save("classifier.bin"); cout << "Spent " << totalTimer.end() << "s training the SVM classifier and saving it to \"classifier.bin\"." << endl; } void test(string forestPath, string classifierPath, string testImagePath, unsigned int featureType) { ErcForest forest(forestPath); Classifier classifier(&forest); classifier.load(classifierPath); unsigned int maxNDescriptors = 8000; unsigned int nDescriptorsPerImage; CImgList<double> imList; CImgList<double> featureList(maxNDescriptors); CImg<double> positions(featureList.size(), 2); vector<string> imagePaths; imagePaths.push_back(testImagePath); loadImages<double>(imList, imagePaths); FeatureExtractor featureExtractor(&featureList, &nDescriptorsPerImage, &positions, maxNDescriptors, &imList); unsigned int nDescriptors; if (featureType == 0) nDescriptors = featureExtractor.getHsl(0, 0, 16); else if (featureType == 1) nDescriptors = featureExtractor.getHslHaar(0, 0, 16); else nDescriptors = featureExtractor.getSift(0, 0); while (featureList.size() > nDescriptors) featureList.pop_back(); CImg<double> features = featureList.get_append('x'); for (unsigned int c = 0; c < classifier.getNModels(); ++c) { cout << classifier.unmixedPoints(imList.at(0), features, positions, c) << " unmixed points for label " << c << endl; cout << "Decision function for label " << c << ": " << classifier.classify(features, c) << endl; } } int main(unsigned int argc, char* argv[]) { if (argc == 2) { vector<string> imageSearchPaths; vector<string> maskSearchPaths; cout << "Training model from paths in \"" << argv[1] << "\"" << endl; FILE *pathFile = fopen(argv[1], "r"); char line[MAX_PATH]; while (fgets(line, MAX_PATH, pathFile)) { if (line[strlen(line) - 1] == '\n') line[strlen(line) - 1] = '\0'; imageSearchPaths.push_back(string(line)); if (!fgets(line, MAX_PATH, pathFile)) { maskSearchPaths.push_back(""); break; } if (line[strlen(line) - 1] == '\n') line[strlen(line) - 1] = '\0'; maskSearchPaths.push_back(string(line)); } fclose(pathFile); unsigned int maxNPictures; cout << "Number of images to use: "; cin >> maxNPictures; unsigned int featureType; cout << "Type of features (0: HSL, 1: Haar transform of HSL, 2: SIFT): "; cin >> featureType; if (featureType == 0) cout << "Using HSL." << endl; else if (featureType == 1) cout << "Using Haar transform of HSL." << endl; else cout << "Using SIFT." << endl; train(imageSearchPaths, maskSearchPaths, featureType, maxNPictures); } else if (argc == 4) { string forestPath = argv[1]; string classifierPath = argv[2]; string testImagePath = argv[3]; cout << "Testing image \"" << testImagePath << "\" with forest \"" << forestPath << "\" and classifier \"" << classifierPath << "\"." << endl; unsigned int featureType; cout << "Type of features (0: HSL, 1: Haar transform of HSL, 2: SIFT): "; cin >> featureType; test(forestPath, classifierPath, testImagePath, featureType); } else { cout << "Usage" << endl << endl; cout << "For training models to \"forest.xml\" and \"classifier.bin\" with image search paths indicated in \"paths.txt\" :" << endl; cout << "ERCF.exe \"paths.txt\"" << endl << endl; cout << "For testing image \"image.jpg\" with models \"forest.xml\" and \"classifier.bin\" :" << endl; cout << "ERCF.exe \"forest.xml\" \"clasifier.bin\" \"image.jpg\"" << endl << endl; } return 0; }
a5eed3db93f89ed14433462772013eb94ffa2ea7
0f867ab0c8930e88e267dd637d48fdc6c422bed7
/Mercury2/src/Orthographic.cpp
04ea9a4b8f5a975964a443381ab3f9ffd238a159
[]
no_license
axlecrusher/hgengine
e15f29f955352da55776de45a21d60845491b91e
7e7e75c41a86d83acdcaab2b346a6b8c2f87da54
refs/heads/master
2021-01-20T05:43:26.316683
2013-01-31T05:42:34
2013-01-31T05:42:34
89,799,775
1
0
null
null
null
null
UTF-8
C++
false
false
3,530
cpp
#include <Orthographic.h> #include <GLHeaders.h> #include <MercuryWindow.h> REGISTER_NODE_TYPE(Orthographic); Orthographic::Orthographic() { } void Orthographic::PreRender(const MercuryMatrix& matrix) { FRUSTUM = &m_frustum; //Load the frustum into the projection GLCALL( glMatrixMode(GL_PROJECTION) ); GLCALL( glLoadMatrix( m_frustum.GetMatrix() ) ); GLCALL( glMatrixMode(GL_MODELVIEW) ); VIEWMATRIX = matrix; MercuryNode::PreRender(matrix); } void Orthographic::Render(const MercuryMatrix& matrix) { FRUSTUM = &m_frustum; //Load the frustum into the projection GLCALL( glMatrixMode(GL_PROJECTION) ); GLCALL( glLoadMatrix( m_frustum.GetMatrix() ) ); GLCALL( glMatrixMode(GL_MODELVIEW) ); VIEWMATRIX = matrix; MercuryNode::Render(matrix); } void Orthographic::LoadFromXML(const XMLNode& node) { m_frustum.Ortho( StrToFloat(node.Attribute("left")), StrToFloat(node.Attribute("right")), StrToFloat(node.Attribute("bottom")), StrToFloat(node.Attribute("top")), StrToFloat(node.Attribute("near")), StrToFloat(node.Attribute("far")) ); MercuryNode::LoadFromXML(node); } /**************************************************************************** * Copyright (C) 2009 by Joshua Allen * * * * * * 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 Mercury Engine 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. * ***************************************************************************/
[ "axlecrusher@141cdb93-e927-4a07-a99f-75eb1556cfc9" ]
axlecrusher@141cdb93-e927-4a07-a99f-75eb1556cfc9
b4127cdaaba39c6a4e63c3df164f2ae433ae9bbd
b259158ad684b189d0473eeba41b30a2d6d52157
/mainwindow.cpp
073eaa7f7a47d311a1c6724b0b4f7ed701b5efc4
[]
no_license
htphilipp/CoinExample
ccd79a2431d5082300b8e111d66fff7227eec80d
567598504a83ee6983d694ec52625a2cdcdcd794
refs/heads/master
2021-04-15T17:14:13.016248
2018-03-24T19:15:24
2018-03-24T19:15:24
126,628,951
0
0
null
null
null
null
UTF-8
C++
false
false
7,682
cpp
#include "mainwindow.h" #include "ui_mainwindow.h" //added to github testing QT integration MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->graphOne->addGraph(); // ui->graphOne->graph(0)->setScatterStyle(QCPScatterStyle(QCPScatterStyle::ssCircle, QPen(Qt::black, 1.5), QBrush(Qt::white), 9)); ui->graphOne->graph(0)->setBrush(QBrush(QColor(0, 0, 255, 20))); int pN = 1001; // number of probability partitions // LogProb prior; // LogProb prob; // QVector< double> probToPlot; // QVector< double> probHeads; // std::vector < std::vector < double> > hist; for(auto i = 0; i<pN; i++) { prior.prb.push_back( log(1.0/double(pN))); // assuming head probability is maximum of 1 (of course) prob.prb.push_back(1); } prior.normfull(); prob.normfull(); connect(ui->graphOne,SIGNAL(mousePress(QMouseEvent*)),this,SLOT(crement(QMouseEvent*))); connect(ui->graphOne,SIGNAL(mouseWheel(QWheelEvent*)),this,SLOT(crement(QWheelEvent*))); auto p =[](int h, double ho) { if(h==1) { if(ho<=0) { return -99999.0; } else { return log(ho); } } else { if((1-ho)<=0) { return -999999.0; } else { return log(1.0-ho); } } }; hist.push_back(prob.prb); int data[]={1,1,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0, 1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0, 1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0, 1,1,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0, 1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0, 1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0, 1,1,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0, 1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0, 1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0, 1,1,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0, 1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0, 1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,1,1,1,1,1,1,1,0,1,0,0,0,0,1,0,1,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; countmax = sizeof(data)/sizeof(data[0]); for(auto j: data) { for(auto k=0; k<prior.prb.size();k++) { prob.prb[k]=p(j,(1.0/(double(prior.prb.size())-1.0))*double(k)); //ui->textBrowser->append(QString::number(p(j,(1.0/(double(prior.prb.size())-1.0))*double(k)))); } prob.normfull(); for(auto k=0; k<prior.prb.size();k++) { prob.prb[k]+=prior.prb[k]; //ui->textBrowser->append(QString::number(prob.prb[k])); } prob.normfull(); hist.push_back(prob.prb); for(auto k=0; k<prior.prb.size();k++) { prior.prb[k] = prob.prb[k]; } } count=countmax-1; //double temp; for(auto k=0; k<prior.prb.size();k++) { probHeads.push_back(double(k*1.0/pN)); probToPlot.push_back(exp(hist[count][k])); //probToPlot.push_back(exp(prior.prb[k])); } ui->graphOne->graph(0)->setData(probHeads,probToPlot); ui->graphOne->yAxis->grid()->setSubGridVisible(true); ui->graphOne->xAxis->grid()->setSubGridVisible(true); //ui->graphOne->yAxis->setScaleType(QCPAxis::stLogarithmic); ui->label->setText(QString::number(count)); ui->graphOne->graph(0)->rescaleAxes(); ui->graphOne->graph(0)->visible(); ui->graphOne->replot(); //connect(ui->graphOne,SIGNAL(mousePress(QMouseEvent*)),this,SLOT(crement(QMouseEvent*))); } void MainWindow::crement(QMouseEvent *event) { //double sum=0; if((event->button()==Qt::RightButton)) { if(count<(countmax-2)) { count++; } else { count = 0; } } if(event->button()==Qt::LeftButton) { if(count>0) { count--; } else { count=countmax-1; } } probToPlot.clear(); for(auto k=0; k<prior.prb.size();k++) { probToPlot.push_back(exp(hist[count][k])); } // for(auto j:probToPlot) // { // sum += j; // } ui->label->setText(QString("# of coins: ")+QString::number(count));//+QString(" int_norm")+QString::number(sum)); ui->graphOne->graph(0)->setData(probHeads,probToPlot); ui->graphOne->yAxis->grid()->setSubGridVisible(true); ui->graphOne->xAxis->grid()->setSubGridVisible(true); ui->graphOne->graph(0)->rescaleAxes(); ui->graphOne->graph(0)->visible(); ui->graphOne->replot(); } void MainWindow::crement(QWheelEvent *event) { //double sum=0; if(event->delta()>0) { if(count<(countmax-2)) { count++; } else { count = 0; } } if(event->delta()<0) { if(count>0) { count--; } else { count=countmax-1; } } probToPlot.clear(); for(auto k=0; k<prior.prb.size();k++) { probToPlot.push_back(exp(hist[count][k])); } // for(auto j:probToPlot) // { // sum += j; // } ui->label->setText(QString("# of coins: ")+QString::number(count)); //+QString(" int_norm")+QString::number(sum)); ui->graphOne->graph(0)->setData(probHeads,probToPlot); ui->graphOne->yAxis->grid()->setSubGridVisible(true); ui->graphOne->xAxis->grid()->setSubGridVisible(true); ui->graphOne->graph(0)->rescaleAxes(); ui->graphOne->graph(0)->visible(); ui->graphOne->replot(); } // Destructor MainWindow::~MainWindow() { delete ui; }
[ "hugh'[at]'his.com" ]
hugh'[at]'his.com
faf76375955822862f846115f4d2b855943e1af8
099c2076771c1fd5bba80e5f1465410dfa70375a
/PE018_Maximum_path_sum_I/pe018.cpp
889510be00ba2cb104a68c0b060a503494dabecc
[]
no_license
Jul-Le/project-euler
73595411effa3c150c9bae04ae8f155b4c69aae6
17fc9e0ad252931ba0dbaeb033a139727eb99e45
refs/heads/master
2021-10-07T23:45:29.106429
2018-12-05T18:24:00
2018-12-05T18:24:00
159,533,336
0
0
null
null
null
null
UTF-8
C++
false
false
4,682
cpp
#include <iostream> #include <string> #define SIZE 15 struct cell { int up_left; int up_right; }; cell triangle[SIZE][SIZE]{ 0 }; const int originalTriangle[SIZE][SIZE] { 75,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 95,64,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 17,47,82,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 18,35,87,10,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 20,4,82,47,65,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, 19,1,23,75,3,34,-1,-1,-1,-1,-1,-1,-1,-1,-1, 88,2,77,73,7,63,67,-1,-1,-1,-1,-1,-1,-1,-1, 99,65,4,28,6,16,70,92,-1,-1,-1,-1,-1,-1,-1, 41,41,26,56,83,40,80,70,33,-1,-1,-1,-1,-1,-1, 41,48,72,33,47,32,37,16,94,29,-1,-1,-1,-1,-1, 53,71,44,65,25,43,91,52,97,51,14,-1,-1,-1,-1, 70,11,33,28,77,73,17,78,39,68,17,57,-1,-1,-1, 91,71,52,38,17,14,91,43,58,50,27,29,48,-1,-1, 63,66,4,68,89,53,67,30,73,16,69,87,40,31,-1, 4,62,98,27,23,9,70,98,73,93,38,53,60,4,23 }; int invertedTriangle[SIZE][SIZE]{ 0 }; cell path[SIZE][SIZE]{ 0 }; int x = 0; int y = 0; char pathDrawingThingy[SIZE][SIZE]{ ' ' }; bool pathNotFound() { // ---- If bottom row not reached ---- // for (int i = 0; i < SIZE; i++) { if (!(triangle[i][SIZE - 1].up_left && triangle[i][SIZE - 1].up_right)) { return false; } } return true; } void findPath() { x = 0; y = 0; // ---- Clear first cell ---- // triangle[x][y].up_left = 0; triangle[x][y].up_right = 0; while (pathNotFound()) { for (x = 0; x < SIZE; x++) { for (y = 0; y < SIZE; y++) { // ---- If cell has been reached ---- // if (!triangle[x][y].up_left || !triangle[x][y].up_right) { // ---- If lower left cell has not been reached ---- // if (triangle[x][y + 1].up_left && triangle[x][y + 1].up_right) { // ---- Decrement it, if it reaches ---- // // ------- zero, mark it as path ------- // if (!(--triangle[x][y + 1].up_right)) { path[x][y + 1].up_right = 1; //std::cout << "(" << x << ", " << y + 1 << ")" << std::endl; } } // ---- If lower right cell has not been reached ---- // if (triangle[x + 1][y + 1].up_left && triangle[x + 1][y + 1].up_right) { // ---- Decrement it, if it reaches ---- // // ------- zero, mark it as path ------- // if (!(--triangle[x + 1][y + 1].up_left)) { path[x + 1][y + 1].up_left = 1; //std::cout << "(" << x + 1 << ", " << y + 1 << ")" << std::endl; } } } // endif reached } // end for y } // end for x } // end while } void printPathTotal() { // ---- Reverse direction ---- // for (int i = 0; i < SIZE; i++) { if (path[i][SIZE - 1].up_left || path[i][SIZE - 1].up_right) { x = i; break; } } y = SIZE - 1; int total = originalTriangle[y][x]; pathDrawingThingy[x][y] = '*'; while (y) { if (path[x][y].up_left) { x--; y--; } else if (path[x][y].up_right) y--; total += originalTriangle[y][x]; pathDrawingThingy[x][y] = '*'; } std::cout << "Total sum: " << total << std::endl; } void printPath() { for (y = 0; y < SIZE; y++) { for (x = 0; x < SIZE; x++) { std::cout << pathDrawingThingy[x][y] << " "; } std::cout << std::endl; } } void init() { for (x = 0; x < SIZE; x++) { for (y = 0; y < SIZE; y++) { if (originalTriangle[y][x] != -1) { invertedTriangle[x][y] = (originalTriangle[y][x] - 100) * (-1); } else { invertedTriangle[x][y] = -1; } triangle[x][y].up_left = invertedTriangle[x][y]; triangle[x][y].up_right = invertedTriangle[x][y]; } } } int main() { // ------- Parse --------- // init(); // ---- Do some magic ---- // findPath(); // --- Calculate total --- // printPathTotal(); // --- Draw fancy path --- // printPath(); return 0; }
58df7b3a286eaecd79c64d5ff97e97182836a835
8c37b5363ff77a10e9c54204bc88b1c9861cdee6
/torch/csrc/api/src/nn/options/instancenorm.cpp
930fc276db9dc23ca3f3a4b68ee5dd7023fc9d57
[ "BSD-2-Clause", "BSD-3-Clause", "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
gchanan/pytorch
50bf0843388c5ce3a818cf79688cf319b2262b15
0d03e73ae73aa6964ef72f848a77d27afeacf329
refs/heads/master
2021-07-02T16:20:50.304428
2019-12-26T20:52:21
2019-12-26T20:52:21
88,906,627
9
1
NOASSERTION
2019-12-26T20:52:23
2017-04-20T20:14:16
Python
UTF-8
C++
false
false
214
cpp
#include <torch/nn/options/instancenorm.h> namespace torch { namespace nn { InstanceNormOptions::InstanceNormOptions(int64_t num_features) : num_features_(num_features) {} } // namespace nn } // namespace torch
05e7a609f5b502230abcbce3eea8c2b19b59ef40
cdbfd8891cde8e11bd15b9d00e677e20e75f93aa
/python/riegeli/bytes/python_writer.cc
dd65bc50974ab8e63770314be1d2d431b6f5f079
[ "Apache-2.0" ]
permissive
micahcc/riegeli
dbe317a8f8183f9a8a8c63b21702e0406e6452dd
d8cc64857253037d4f022e860b7b86cbe7d4b8d8
refs/heads/master
2023-06-24T21:36:14.894457
2021-07-20T16:07:49
2021-07-21T08:18:02
265,888,704
0
0
Apache-2.0
2020-05-21T15:47:47
2020-05-21T15:47:46
null
UTF-8
C++
false
false
13,194
cc
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // 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. // From https://docs.python.org/3/c-api/intro.html: // Since Python may define some pre-processor definitions which affect the // standard headers on some systems, you must include Python.h before any // standard headers are included. #define PY_SSIZE_T_CLEAN #include <Python.h> // clang-format: do not reorder the above include. #include "python/riegeli/bytes/python_writer.h" // clang-format: do not reorder the above include. #include <stddef.h> #include <limits> #include <memory> #include <string> #include "absl/base/attributes.h" #include "absl/base/optimization.h" #include "absl/status/status.h" #include "absl/strings/str_cat.h" #include "absl/strings/string_view.h" #include "absl/types/optional.h" #include "python/riegeli/base/utils.h" #include "riegeli/base/base.h" #include "riegeli/bytes/buffered_writer.h" namespace riegeli { namespace python { PythonWriter::PythonWriter(PyObject* dest, Options options) : BufferedWriter(options.buffer_size()), owns_dest_(options.owns_dest()) { PythonLock::AssertHeld(); Py_INCREF(dest); dest_.reset(dest); if (options.assumed_pos() != absl::nullopt) { set_start_pos(*options.assumed_pos()); } else { static constexpr Identifier id_seekable("seekable"); const PythonPtr seekable_result( PyObject_CallMethodObjArgs(dest_.get(), id_seekable.get(), nullptr)); if (ABSL_PREDICT_FALSE(seekable_result == nullptr)) { FailOperation("seekable()"); return; } const int seekable_is_true = PyObject_IsTrue(seekable_result.get()); if (ABSL_PREDICT_FALSE(seekable_is_true < 0)) return; if (seekable_is_true == 0) { // Random access is not supported. Assume 0 as the initial position. return; } static constexpr Identifier id_tell("tell"); const PythonPtr tell_result( PyObject_CallMethodObjArgs(dest_.get(), id_tell.get(), nullptr)); if (ABSL_PREDICT_FALSE(tell_result == nullptr)) { FailOperation("tell()"); return; } const absl::optional<Position> file_pos = PositionFromPython(tell_result.get()); if (ABSL_PREDICT_FALSE(file_pos == absl::nullopt)) { FailOperation("PositionFromPython() after tell()"); return; } set_start_pos(*file_pos); supports_random_access_ = true; } } void PythonWriter::Done() { BufferedWriter::Done(); if (owns_dest_ && dest_ != nullptr) { PythonLock lock; static constexpr Identifier id_close("close"); const PythonPtr close_result( PyObject_CallMethodObjArgs(dest_.get(), id_close.get(), nullptr)); if (ABSL_PREDICT_FALSE(close_result == nullptr)) FailOperation("close()"); } } bool PythonWriter::FailOperation(absl::string_view operation) { RIEGELI_ASSERT(is_open()) << "Failed precondition of PythonWriter::FailOperation(): " "Object closed"; PythonLock::AssertHeld(); if (ABSL_PREDICT_FALSE(!healthy())) { // Ignore this error because `PythonWriter` already failed. PyErr_Clear(); return false; } exception_ = Exception::Fetch(); return Fail(absl::UnknownError( absl::StrCat(operation, " failed: ", exception_.message()))); } bool PythonWriter::WriteInternal(absl::string_view src) { RIEGELI_ASSERT(!src.empty()) << "Failed precondition of BufferedWriter::WriteInternal(): " "nothing to write"; RIEGELI_ASSERT(healthy()) << "Failed precondition of BufferedWriter::WriteInternal(): " << status(); if (ABSL_PREDICT_FALSE(src.size() > std::numeric_limits<Position>::max() - start_pos())) { return FailOverflow(); } PythonLock lock; if (ABSL_PREDICT_FALSE(write_function_ == nullptr)) { static constexpr Identifier id_write("write"); write_function_.reset(PyObject_GetAttr(dest_.get(), id_write.get())); if (ABSL_PREDICT_FALSE(write_function_ == nullptr)) { return FailOperation("write()"); } } do { size_t length_written; { const size_t length_to_write = UnsignedMin( src.size(), size_t{std::numeric_limits<Py_ssize_t>::max()}); PythonPtr write_result; if (!use_bytes_) { // Prefer passing a `memoryview` to avoid copying memory. MemoryView memory_view; PyObject* const memory_view_object = memory_view.ToPython( absl::string_view(src.data(), length_to_write)); if (ABSL_PREDICT_FALSE(memory_view_object == nullptr)) { return FailOperation("MemoryView::ToPython()"); } write_result.reset(PyObject_CallFunctionObjArgs( write_function_.get(), memory_view_object, nullptr)); if (ABSL_PREDICT_FALSE(write_result == nullptr)) { if (!PyErr_ExceptionMatches(PyExc_TypeError)) { return FailOperation("write()"); } PyErr_Clear(); use_bytes_ = true; } if (ABSL_PREDICT_FALSE(!memory_view.Release())) { return FailOperation("MemoryView::Release()"); } } if (use_bytes_) { // `write()` does not support `memoryview`. Use `bytes`. const PythonPtr bytes = BytesToPython(src.substr(0, length_to_write)); if (ABSL_PREDICT_FALSE(bytes == nullptr)) { return FailOperation("BytesToPython()"); } write_result.reset(PyObject_CallFunctionObjArgs(write_function_.get(), bytes.get(), nullptr)); if (ABSL_PREDICT_FALSE(write_result == nullptr)) { return FailOperation("write()"); } } if (write_result.get() == Py_None) { // Python2 `file.write()` returns `None`, and would raise an exception // if less than the full length had been written. Python2 is dead, but // some classes still behave like that. length_written = length_to_write; } else { // `io.IOBase.write()` returns the length written. const absl::optional<size_t> length_written_opt = SizeFromPython(write_result.get()); if (ABSL_PREDICT_FALSE(length_written_opt == absl::nullopt)) { return FailOperation("SizeFromPython() after write()"); } length_written = *length_written_opt; } } if (ABSL_PREDICT_FALSE(length_written > src.size())) { return Fail(absl::InternalError("write() wrote more than requested")); } move_start_pos(length_written); src.remove_prefix(length_written); } while (!src.empty()); return true; } bool PythonWriter::FlushImpl(FlushType flush_type) { if (ABSL_PREDICT_FALSE(!BufferedWriter::FlushImpl(flush_type))) return false; switch (flush_type) { case FlushType::kFromObject: if (!owns_dest_) return true; ABSL_FALLTHROUGH_INTENDED; case FlushType::kFromProcess: case FlushType::kFromMachine: PythonLock lock; static constexpr Identifier id_flush("flush"); const PythonPtr flush_result( PyObject_CallMethodObjArgs(dest_.get(), id_flush.get(), nullptr)); if (ABSL_PREDICT_FALSE(flush_result == nullptr)) { return FailOperation("flush()"); } return true; } RIEGELI_ASSERT_UNREACHABLE() << "Unknown flush type: " << static_cast<int>(flush_type); } bool PythonWriter::SeekBehindBuffer(Position new_pos) { RIEGELI_ASSERT_EQ(buffer_size(), 0u) << "Failed precondition of BufferedWriter::SeekBehindBuffer(): " "buffer not empty"; if (ABSL_PREDICT_FALSE(!supports_random_access_)) { return Fail(absl::UnimplementedError("PythonWriter::Seek() not supported")); } PythonLock lock; if (new_pos >= start_pos()) { // Seeking forwards. const absl::optional<Position> size = SizeInternal(); if (ABSL_PREDICT_FALSE(size == absl::nullopt)) return false; if (ABSL_PREDICT_FALSE(new_pos > *size)) { // File ends. set_start_pos(*size); return false; } } set_start_pos(new_pos); const PythonPtr file_pos = PositionToPython(start_pos()); if (ABSL_PREDICT_FALSE(file_pos == nullptr)) { return FailOperation("PositionToPython()"); } static constexpr Identifier id_seek("seek"); const PythonPtr seek_result(PyObject_CallMethodObjArgs( dest_.get(), id_seek.get(), file_pos.get(), nullptr)); if (ABSL_PREDICT_FALSE(seek_result == nullptr)) { return FailOperation("seek()"); } return true; } inline absl::optional<Position> PythonWriter::SizeInternal() { RIEGELI_ASSERT(healthy()) << "Failed precondition of PythonWriter::SizeInternal(): " << status(); RIEGELI_ASSERT(supports_random_access_) << "Failed precondition of PythonWriter::SizeInternal(): " "random access not supported"; RIEGELI_ASSERT_EQ(buffer_size(), 0u) << "Failed precondition of PythonWriter::SizeInternal(): " "buffer not empty"; PythonLock::AssertHeld(); absl::string_view operation; const PythonPtr file_pos = PositionToPython(0); if (ABSL_PREDICT_FALSE(file_pos == nullptr)) { FailOperation("PositionToPython()"); return absl::nullopt; } const PythonPtr whence = IntToPython(2); // `io.SEEK_END` if (ABSL_PREDICT_FALSE(whence == nullptr)) { FailOperation("IntToPython()"); return absl::nullopt; } static constexpr Identifier id_seek("seek"); PythonPtr result(PyObject_CallMethodObjArgs( dest_.get(), id_seek.get(), file_pos.get(), whence.get(), nullptr)); if (result.get() == Py_None) { // Python2 `file.seek()` returns `None`. Python2 is dead, but some classes // still behave like that. static constexpr Identifier id_tell("tell"); result.reset( PyObject_CallMethodObjArgs(dest_.get(), id_tell.get(), nullptr)); operation = "tell()"; } else { // `io.IOBase.seek()` returns the new position. operation = "seek()"; } if (ABSL_PREDICT_FALSE(result == nullptr)) { FailOperation(operation); return absl::nullopt; } const absl::optional<Position> size = PositionFromPython(result.get()); if (ABSL_PREDICT_FALSE(size == absl::nullopt)) { FailOperation(absl::StrCat("PositionFromPython() after ", operation)); return absl::nullopt; } return *size; } absl::optional<Position> PythonWriter::SizeBehindBuffer() { RIEGELI_ASSERT_EQ(buffer_size(), 0u) << "Failed precondition of BufferedWriter::SizeBehindBuffer(): " "buffer not empty"; if (ABSL_PREDICT_FALSE(!healthy())) return absl::nullopt; if (ABSL_PREDICT_FALSE(!supports_random_access_)) { Fail(absl::UnimplementedError("PythonWriter::Size() not supported")); return absl::nullopt; } PythonLock lock; const absl::optional<Position> size = SizeInternal(); if (ABSL_PREDICT_FALSE(size == absl::nullopt)) return absl::nullopt; const PythonPtr file_pos = PositionToPython(start_pos()); if (ABSL_PREDICT_FALSE(file_pos == nullptr)) { FailOperation("PositionToPython()"); return absl::nullopt; } static constexpr Identifier id_seek("seek"); const PythonPtr seek_result(PyObject_CallMethodObjArgs( dest_.get(), id_seek.get(), file_pos.get(), nullptr)); if (ABSL_PREDICT_FALSE(seek_result == nullptr)) { FailOperation("seek()"); return absl::nullopt; } return *size; } bool PythonWriter::TruncateBehindBuffer(Position new_size) { RIEGELI_ASSERT_EQ(buffer_size(), 0u) << "Failed precondition of BufferedWriter::TruncateBehindBuffer(): " "buffer not empty"; if (ABSL_PREDICT_FALSE(!healthy())) return false; if (ABSL_PREDICT_FALSE(!supports_random_access_)) { return Fail( absl::UnimplementedError("PythonWriter::Truncate() not supported")); } PythonLock lock; const absl::optional<Position> size = SizeInternal(); if (ABSL_PREDICT_FALSE(size == absl::nullopt)) return false; if (ABSL_PREDICT_FALSE(new_size > *size)) { // File ends. set_start_pos(*size); return false; } { const PythonPtr file_pos = PositionToPython(new_size); if (ABSL_PREDICT_FALSE(file_pos == nullptr)) { return FailOperation("PositionToPython()"); } static constexpr Identifier id_seek("seek"); const PythonPtr seek_result(PyObject_CallMethodObjArgs( dest_.get(), id_seek.get(), file_pos.get(), nullptr)); if (ABSL_PREDICT_FALSE(seek_result == nullptr)) { return FailOperation("seek()"); } } set_start_pos(new_size); static constexpr Identifier id_truncate("truncate"); const PythonPtr truncate_result( PyObject_CallMethodObjArgs(dest_.get(), id_truncate.get(), nullptr)); if (ABSL_PREDICT_FALSE(truncate_result == nullptr)) { return FailOperation("truncate()"); } return true; } } // namespace python } // namespace riegeli
7a1dabde683031ff382f17dafe2fb7d7fbc06237
8b127cab5c35c1b5a754fc152118baec7df74003
/Accelerated-Cpp/ch_6/ex_6-3.cpp
ef1fccbff41d3b456a6650bca093db6133f14f9a
[]
no_license
arshjot/Cpp-Practice
76cb07c30b02a110fbe1fba9b65045402f3818df
0463d6f1c5fcb60967e7e3be88717e566dbcf984
refs/heads/master
2020-12-19T20:04:43.343339
2020-03-06T15:10:58
2020-03-06T15:10:58
235,838,197
0
0
null
null
null
null
UTF-8
C++
false
false
666
cpp
// The below program gives a "Segmentation fault" error // because v is an empty vector so cannot accomodate // elements of u #include <iostream> #include <string> #include <vector> #include <algorithm> using std::vector; using std::cin; using std::cout; using std::endl; int main() { vector<int> u(10, 100); vector<int> v; copy(u.begin(), u.end(), v.begin()); for (vector<int>::const_iterator iter = u.begin(); iter != u.end(); ++iter) { cout << (*iter) << endl; } for (vector<int>::const_iterator iter = v.begin(); iter != v.end(); ++iter) { cout << (*iter) << endl; } return 0; }
d9559cc6ff1a45e19b9402e3b99b3b1213ec1200
6f833cbd5b035870bafc112676e4a96d79abb108
/Config.h
dc4f85e20af8fe937213108ce21dda1460ae7c48
[]
no_license
cc222ip/Video_Game
6d0e115597ecf02e25a986f6ef46a9096c69f3c4
6e1d29ae2be0dab26fe51b5777ae5b6fb7c2db7e
refs/heads/master
2020-03-11T08:57:08.676571
2018-04-17T11:56:21
2018-04-17T11:56:21
129,897,139
0
0
null
null
null
null
UTF-8
C++
false
false
762
h
#ifndef CONFIG_H #define CONFIG_H #include "Character.h" class Config { public: int nbr_monster; //Nombre de Monstres sur la Carte int nbr_obstacle; //Nombre d'obstacle sur la Carte int dim_map; //Dimension d'un cote de la carte int nbr_pot_map; //Nombre de potion de vie sur la carte int nbr_pot_perso; //Nombre de potion de vie dans l'inventaire du personnage int nbr_mana_map; //Nombre de potion de mana sur la carte int nbr_mana_perso; //Nombre de potion de mana dans l'inventaire du personnage int pot_mana; //Points de mana d'une potion de vie int pot_life; //Points de vie d'une potion de vie Character **heros; //Tableau des Heros Character **monsters; //Tableau des Monstres Config(); void editConfig(); }; #endif
8998dc2b4c452e1bf97462ab210a983f3fbf4ca3
776c5767effd31fd917df2a2a060af107c9b62eb
/mdvw/mdvw.cpp
c91d893c9af35dbedd4f730fb1a90b68cc4f1785
[]
no_license
hchen90/mdvw-win32
6fd9b7812aff50dd4773a45da331f4c3d62f8ce2
a63db554f23259fc456539ed8e0c181460407531
refs/heads/master
2021-03-22T04:39:28.515932
2018-03-11T09:18:16
2018-03-11T09:18:16
110,072,436
0
0
null
null
null
null
UTF-8
C++
false
false
6,533
cpp
// This MFC Samples source code demonstrates using MFC Microsoft Office Fluent User Interface // (the "Fluent UI") and is provided only as referential material to supplement the // Microsoft Foundation Classes Reference and related electronic documentation // included with the MFC C++ library software. // License terms to copy, use or distribute the Fluent UI are available separately. // To learn more about our Fluent UI licensing program, please visit // http://go.microsoft.com/fwlink/?LinkId=238214. // // Copyright (C) Microsoft Corporation // All rights reserved. // mdvw.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "afxwinappex.h" #include "afxdialogex.h" #include "mdvw.h" #include "MainFrm.h" #include "mdvwDoc.h" #include "mdvwView.h" #include "trans.h" #ifdef _DEBUG #define new DEBUG_NEW #endif // CmdvwApp BEGIN_MESSAGE_MAP(CmdvwApp, CWinAppEx) ON_COMMAND(ID_APP_ABOUT, &CmdvwApp::OnAppAbout) // Standard file based document commands //ON_COMMAND(ID_FILE_NEW, &CWinAppEx::OnFileNew) //ON_COMMAND(ID_FILE_OPEN, &CmdvwApp::OnFileOpen) // Standard print setup command //ON_COMMAND(ID_FILE_PRINT_SETUP, &CWinAppEx::OnFilePrintSetup) END_MESSAGE_MAP() // CmdvwApp construction CmdvwApp::CmdvwApp() : _newnm(0) { m_bHiColorIcons = TRUE; // support Restart Manager m_dwRestartManagerSupportFlags = AFX_RESTART_MANAGER_SUPPORT_ALL_ASPECTS; #ifdef _MANAGED // If the application is built using Common Language Runtime support (/clr): // 1) This additional setting is needed for Restart Manager support to work properly. // 2) In your project, you must add a reference to System.Windows.Forms in order to build. System::Windows::Forms::Application::SetUnhandledExceptionMode(System::Windows::Forms::UnhandledExceptionMode::ThrowException); #endif // TODO: replace application ID string below with unique ID string; recommended // format for string is CompanyName.ProductName.SubProduct.VersionInformation SetAppID(_T("mdvw.AppID.NoVersion")); // TODO: add construction code here, // Place all significant initialization in InitInstance _newnm = new TCHAR[MAX_PATH]; } CmdvwApp::~CmdvwApp() { if (_newnm) delete[] _newnm; } // The one and only CmdvwApp object CmdvwApp theApp; // CmdvwApp initialization BOOL CmdvwApp::InitInstance() { // InitCommonControlsEx() is required on Windows XP if an application // manifest specifies use of ComCtl32.dll version 6 or later to enable // visual styles. Otherwise, any window creation will fail. INITCOMMONCONTROLSEX InitCtrls; InitCtrls.dwSize = sizeof(InitCtrls); // Set this to include all the common control classes you want to use // in your application. InitCtrls.dwICC = ICC_WIN95_CLASSES; InitCommonControlsEx(&InitCtrls); CWinAppEx::InitInstance(); // Initialize OLE libraries if (!AfxOleInit()) { AfxMessageBox(IDP_OLE_INIT_FAILED); return FALSE; } AfxEnableControlContainer(); EnableTaskbarInteraction(FALSE); // AfxInitRichEdit2() is required to use RichEdit control // AfxInitRichEdit2(); // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need // Change the registry key under which our settings are stored // TODO: You should modify this string to be something appropriate // such as the name of your company or organization SetRegistryKey(_T("chenxiang")); LoadStdProfileSettings(10); // Load standard INI file options (including MRU) InitContextMenuManager(); InitKeyboardManager(); InitTooltipManager(); CMFCToolTipInfo ttParams; ttParams.m_bVislManagerTheme = TRUE; theApp.GetTooltipManager()->SetTooltipParams(AFX_TOOLTIP_TYPE_ALL, RUNTIME_CLASS(CMFCToolTipCtrl), &ttParams); // Register the application's document templates. Document templates // serve as the connection between documents, frame windows and views CSingleDocTemplate* pDocTemplate; pDocTemplate = new CSingleDocTemplate( IDR_MAINFRAME, RUNTIME_CLASS(CmdvwDoc), RUNTIME_CLASS(CMainFrame), // main SDI frame window RUNTIME_CLASS(CmdvwView)); if (!pDocTemplate) return FALSE; AddDocTemplate(pDocTemplate); // Parse command line for standard shell commands, DDE, file open CCommandLineInfo cmdInfo; ParseCommandLine(cmdInfo); cmdInfo.m_nShellCommand = CCommandLineInfo::FileNew; if (cmdInfo.m_strFileName.GetLength() > 0) { if (trans::isMD(cmdInfo.m_strFileName) && _newnm) { if (trans::tempfile(_newnm, trans::pathtitle(cmdInfo.m_strFileName))) { trans::trans_start(cmdInfo.m_strFileName, _newnm); cmdInfo.m_nShellCommand = CCommandLineInfo::FileOpen; cmdInfo.m_strFileName = _newnm; } } else { cmdInfo.m_nShellCommand = CCommandLineInfo::FileOpen; } } else { cmdInfo.m_nShellCommand = CCommandLineInfo::FileOpen; cmdInfo.m_strFileName = _T("mdvw.html"); } // Enable DDE Execute open EnableShellOpen(); RegisterShellFileTypes(TRUE); // Dispatch commands specified on the command line. Will return FALSE if // app was launched with /RegServer, /Register, /Unregserver or /Unregister. if (!ProcessShellCommand(cmdInfo)) return FALSE; // The one and only window has been initialized, so show and update it m_pMainWnd->ShowWindow(SW_SHOW); m_pMainWnd->UpdateWindow(); // call DragAcceptFiles only if there's a suffix // In an SDI app, this should occur after ProcessShellCommand // Enable drag/drop open m_pMainWnd->DragAcceptFiles(); return TRUE; } int CmdvwApp::ExitInstance() { //TODO: handle additional resources you may have added AfxOleTerm(FALSE); return CWinAppEx::ExitInstance(); } // CmdvwApp message handlers // App command to run the dialog void CmdvwApp::OnAppAbout() { ShellAbout(m_pMainWnd->m_hWnd, _T("About..#MarkDown Viewer"), _T("Copyright(C)2017 Hsiang Chen"), LoadIcon(IDR_MAINFRAME)); } // CmdvwApp customization load/save methods void CmdvwApp::PreLoadState() { } void CmdvwApp::LoadCustomState() { } void CmdvwApp::SaveCustomState() { } // CmdvwApp message handlers // // //CDocument* CmdvwApp::OpenDocumentFile(LPCTSTR lpFileName, BOOL bAddMRU) //{ // AfxMessageBox(lpFileName); // // return CWinAppEx::OpenDocumentFile(lpFileName, bAddMRU); //}
0062cdbe03bbbb0757396c678736104229473bc1
0514949c259aea5dbef62ddb26826a1bc28185a8
/code/SDK/include/Maya_17/maya/MFnNIdData.h
e023fb77ab2a44331e2e07170c22b39152dda95c
[ "Apache-2.0", "LicenseRef-scancode-warranty-disclaimer", "BSD-2-Clause" ]
permissive
ArtemGen/xray-oxygen
f759a1c72803b9aabc1fdb2d5c62f8c0b14b7858
f62d3e1f4e211986c057fd37e97fd03c98b5e275
refs/heads/master
2020-12-18T15:41:40.774697
2020-01-22T02:36:23
2020-01-22T02:36:23
235,440,782
1
0
NOASSERTION
2020-01-22T02:36:24
2020-01-21T21:01:45
C++
UTF-8
C++
false
false
2,024
h
#ifndef _MFnNIdData #define _MFnNIdData // //- // =========================================================================== // Copyright 2018 Autodesk, Inc. All rights reserved. // // Use of this software is subject to the terms of the Autodesk license // agreement provided at the time of installation or download, or which // otherwise accompanies this software in either electronic or hard copy form. // =========================================================================== //+ // // CLASS: MFnNIdData // // ***************************************************************************** // // CLASS DESCRIPTION (MFnNIdData) // // This class is the function set for nucleus geometry data. // // ***************************************************************************** #if defined __cplusplus // ***************************************************************************** // INCLUDED HEADER FILES #include <maya/MFnData.h> OPENMAYA_MAJOR_NAMESPACE_OPEN // ***************************************************************************** // CLASS DECLARATION (MFnNIdData) //! \ingroup OpenMayaFX MFn //! \brief function set for nId object data /*! Class for transferring N id data between connections */ #ifdef _WIN32 #pragma warning(disable: 4522) #endif // _WIN32 class OPENMAYAFX_EXPORT MFnNIdData : public MFnData { declareMFn( MFnNIdData, MFnData ); public: MObject create() const ; BEGIN_NO_SCRIPT_SUPPORT: //! NO SCRIPT SUPPORT MStatus getObjectPtr( MnObject *& ptr ) const; END_NO_SCRIPT_SUPPORT: MnObject * getObjectPtr( MStatus *status=NULL ) const; BEGIN_NO_SCRIPT_SUPPORT: declareMFnConstConstructor( MFnNIdData, MFnData ); END_NO_SCRIPT_SUPPORT: protected: // No protected members private: // No Private members }; #ifdef _WIN32 #pragma warning(default: 4522) #endif // _WIN32 // ***************************************************************************** OPENMAYA_NAMESPACE_CLOSE #endif /* __cplusplus */ #endif /* _MFnNIdData */
6cda8eb08368913f9bf2f089dd91758882f83674
aa1a579dccc2e87bedc458fa987ee233f7ab37e6
/src/actions/advanced.cpp
237b0bc3c5a74c9c15f072bc7841b9cd4f31585c
[]
no_license
STEVEMARS/midRecovery
b6baea52f322b97ee43f4a857a8ceb5316f073aa
4f456fe7621375e7daa145cc78bd5e6e0ad4ac86
refs/heads/master
2021-01-15T18:51:44.245661
2012-08-25T08:52:16
2012-08-25T08:52:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,231
cpp
/* * backups.cpp: * - Actions for "Advanced" menu. */ // Shows a window asking for size for the named partition. // Returns one of the selected values. int GetPartitionSize(const char *name, vector<int> sizes) { for (;;) { // Build title. string title = "Select size of '"; title += name; title += "' partition in MB"; // Build options. vector<WindowOption> opts; for (int i = 0; i < sizes.size(); i++) opts.push_back(WindowOption(NumberToString(sizes[i]), NULL)); // Show window. Window win; win.SetTitle(title.c_str()); win.SetOptions(opts); int ret = win.Show(); if (ret < 0 || ret >= sizes.size()) continue; return sizes[ret]; } } // Partitions and formats the internal SD card according to the // given layout. bool PartitionAndFormatSDCard(int cache, int data, int system) { bool failed = false; char strCache[32], strData[32], strSystem[32]; gTerminal.clear(); sprintf(strCache, "%d", cache); sprintf(strData, "%d", data); sprintf(strSystem, "%d", system); cout << "Making partitions..." << endl; if (!ExecuteShellScript("/scripts/partition.sh", 4, DEV_INTSD, strCache, strData, strSystem)) return false; cout << "Formatting user area..." << endl; failed |= !FormatFat(DEV_INTSDP); cout << "Formatting 'cache' partition..." << endl; failed |= !Format(DEV_CACHE, FS_CACHE); cout << "Formatting 'data' partition..." << endl; failed |= !Format(DEV_DATA, FS_DATA); cout << "Formatting 'system' partition..." << endl; failed |= !Format(DEV_SYSTEM, FS_SYSTEM); return failed; } bool ShowLog() { Log::Flush(); FileView fv; fv.SetFile(Log::GetPath()); fv.Show(); return false; } bool WipeDalvikCache() { string dalvikPath = MOUNT_DATA_DALVIK; dalvikPath += "/*"; bool success; gTerminal.clear(); cout << "Press the HOME key to wipe Dalvik cache, or" << endl << "any other key to cancel." << endl; if (GetButtonPress() != KEY_HOME) return false; cout << "Mounting /data..." << endl; if (!Mount(DEV_DATA, MOUNT_DATA)) goto fail_mount; cout << "Cleaning..." << endl; success = Remove(dalvikPath.c_str(), true, true); cout << "Unmounting..." << endl; UnmountA(MOUNT_DATA); if (success) cout << "Success!" << endl; fail_mount: NotifyWaitForButton(); return false; } bool PartitionSDCard() { vector<int> sizes; int sizeCache, sizeData, sizeSystem, sizeDevice; gTerminal.clear(); if (Log::IsInternalSD()) { cout << "Because the recovery log is being stored in the internal" << endl << "SD card, it is not possible to re-partition the SD card." << endl << "Insert an external SD card, reboot, and try again." << endl; NotifyWaitForButton(); return false; } if ((sizeDevice = GetBlockDeviceSize(SYS_INTSD) / 2048) == 0) { cout << "Unable to determine size of internal SD card." << endl << "The partitioning utility cannot continue." << endl; NotifyWaitForButton(); return false; } cout << "Press the HOME key to repartition the internal SD card," << endl << "or any other key to cancel. If your firmware is installed on" << endl << "the 'system' partition (of the internal SD card) it *WILL* be" << endl << "erased, and you will have to flash again or restore a backup." << endl; if (GetButtonPress() != KEY_HOME) return false; for (;;) { for (int i = 64; i <= 256; i += 32) sizes.push_back(i); sizeCache = GetPartitionSize("cache", sizes); sizes.clear(); for (int i = 256; i <= 1024; i += 128) sizes.push_back(i); sizeData = GetPartitionSize("data", sizes); sizes.clear(); for (int i = 128; i <= 512; i += 64) sizes.push_back(i); sizeSystem = GetPartitionSize("system", sizes); sizes.clear(); int sizeIntSD = sizeDevice - (32 + sizeCache + sizeData + sizeSystem + 4); if (sizeIntSD <= 0) { cout << "There is no room left for user area on internal SD card." << endl << "Please enter the sizes for cache, data and system again" << endl << "(cache=" << sizeCache << ", data=" << sizeData << ", system=" << sizeSystem << " and detected card size = " << sizeDevice << ")" << endl; continue; } cout << "You selected cache = " << sizeCache << " MB, data = " << sizeData << " MB and system = " << sizeSystem << " MB." << endl << "This leaves " << sizeIntSD << " MB for the user area of internal SD." << endl << "Press HOME key to continue with this layout, or any other key" << endl << "to change the layout." << endl; if (GetButtonPress() == KEY_HOME) break; } if (PartitionAndFormatSDCard(sizeCache, sizeData, sizeSystem)) cout << "Success!" << endl; NotifyWaitForButton(); return false; } bool FixROMPermissions() { bool success; gTerminal.clear(); cout << "Press the HOME key to fix ROM permissions, or" << endl << "any other key to cancel." << endl; if (GetButtonPress() != KEY_HOME) return false; if (!MountRootfs()) goto fail; cout << "Fixing ROM permissions..." << endl; success = ExecuteShellScript("/scripts/fixperms.sh"); UnmountRootfs(); if (success) cout << "Success!" << endl; fail: NotifyWaitForButton(); return false; } bool ShowFileInspector() { FileWindow fw; fw.SetPath(GetDefaultPath()); fw.Show(); FileView fv; fv.SetFile(fw.GetSelectedPath()); fv.Show(); return false; } bool DumpKernelMessages() { gTerminal.clear(); cout << "Dumping kernel messages..." << endl; if (ExecuteAndNotifyIfFail("dmesg")) cout << "Success! Entire \"dmesg\" dumped to log!" << endl; NotifyWaitForButton(); return false; }
f06d2c0309f9bec75f2525925b28cff8c727c3dd
20ba322d959c1168eda6741bc4b2de2e3c63a1ef
/src/init.cpp
1765744257ca1704278ec5d46aebe4c0c8e53d62
[ "MIT" ]
permissive
seacoin-project/cc
fa4c0a150ed391ab0e17418612ed1e7056cbaaea
cc2046e7472cce76b1ae1483ff8c1ded4a92086f
refs/heads/master
2016-09-10T10:42:10.772284
2014-03-22T15:55:12
2014-03-22T15:55:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
42,954
cpp
// Copyright (c) 2009-2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "txdb.h" #include "walletdb.h" #include "bitcoinrpc.h" #include "net.h" #include "init.h" #include "util.h" #include "ui_interface.h" #include <boost/filesystem.hpp> #include <boost/filesystem/fstream.hpp> #include <boost/filesystem/convenience.hpp> #include <boost/interprocess/sync/file_lock.hpp> #include <boost/algorithm/string/predicate.hpp> #include <openssl/crypto.h> #ifndef WIN32 #include <signal.h> #endif using namespace std; using namespace boost; CWallet* pwalletMain; CClientUIInterface uiInterface; #ifdef WIN32 // Win32 LevelDB doesn't use filedescriptors, and the ones used for // accessing block files, don't count towards to fd_set size limit // anyway. #define MIN_CORE_FILEDESCRIPTORS 0 #else #define MIN_CORE_FILEDESCRIPTORS 150 #endif // Used to pass flags to the Bind() function enum BindFlags { BF_NONE = 0, BF_EXPLICIT = (1U << 0), BF_REPORT_ERROR = (1U << 1) }; ////////////////////////////////////////////////////////////////////////////// // // Shutdown // // // Thread management and startup/shutdown: // // The network-processing threads are all part of a thread group // created by AppInit() or the Qt main() function. // // A clean exit happens when StartShutdown() or the SIGTERM // signal handler sets fRequestShutdown, which triggers // the DetectShutdownThread(), which interrupts the main thread group. // DetectShutdownThread() then exits, which causes AppInit() to // continue (it .joins the shutdown thread). // Shutdown() is then // called to clean up database connections, and stop other // threads that should only be stopped after the main network-processing // threads have exited. // // Note that if running -daemon the parent process returns from AppInit2 // before adding any threads to the threadGroup, so .join_all() returns // immediately and the parent exits from main(). // // Shutdown for Qt is very similar, only it uses a QTimer to detect // fRequestShutdown getting set, and then does the normal Qt // shutdown thing. // volatile bool fRequestShutdown = false; void StartShutdown() { fRequestShutdown = true; } bool ShutdownRequested() { return fRequestShutdown; } static CCoinsViewDB *pcoinsdbview; void Shutdown() { printf("Shutdown : In progress...\n"); static CCriticalSection cs_Shutdown; TRY_LOCK(cs_Shutdown, lockShutdown); if (!lockShutdown) return; RenameThread("bitcoin-shutoff"); nTransactionsUpdated++; StopRPCThreads(); bitdb.Flush(false); StopNode(); { LOCK(cs_main); if (pwalletMain) pwalletMain->SetBestChain(CBlockLocator(pindexBest)); if (pblocktree) pblocktree->Flush(); if (pcoinsTip) pcoinsTip->Flush(); delete pcoinsTip; pcoinsTip = NULL; delete pcoinsdbview; pcoinsdbview = NULL; delete pblocktree; pblocktree = NULL; } bitdb.Flush(true); boost::filesystem::remove(GetPidFile()); UnregisterWallet(pwalletMain); delete pwalletMain; printf("Shutdown : done\n"); } // // Signal handlers are very limited in what they are allowed to do, so: // void DetectShutdownThread(boost::thread_group* threadGroup) { // Tell the main threads to shutdown. while (!fRequestShutdown) { MilliSleep(200); if (fRequestShutdown) threadGroup->interrupt_all(); } } void HandleSIGTERM(int) { fRequestShutdown = true; } void HandleSIGHUP(int) { fReopenDebugLog = true; } ////////////////////////////////////////////////////////////////////////////// // // Start // #if !defined(QT_GUI) bool AppInit(int argc, char* argv[]) { boost::thread_group threadGroup; boost::thread* detectShutdownThread = NULL; bool fRet = false; try { // // Parameters // // If Qt is used, parameters/crowncoin.conf are parsed in qt/crowncoin.cpp's main() ParseParameters(argc, argv); if (!boost::filesystem::is_directory(GetDataDir(false))) { fprintf(stderr, "Error: Specified directory does not exist\n"); Shutdown(); } ReadConfigFile(mapArgs, mapMultiArgs); if (mapArgs.count("-?") || mapArgs.count("--help")) { // First part of help message is specific to crowncoind / RPC client std::string strUsage = _("Crowncoin version") + " " + FormatFullVersion() + "\n\n" + _("Usage:") + "\n" + " crowncoind [options] " + "\n" + " crowncoind [options] <command> [params] " + _("Send command to -server or crowncoind") + "\n" + " crowncoind [options] help " + _("List commands") + "\n" + " crowncoind [options] help <command> " + _("Get help for a command") + "\n"; strUsage += "\n" + HelpMessage(); fprintf(stdout, "%s", strUsage.c_str()); return false; } // Command-line RPC for (int i = 1; i < argc; i++) if (!IsSwitchChar(argv[i][0]) && !boost::algorithm::istarts_with(argv[i], "crowncoin:")) fCommandLine = true; if (fCommandLine) { int ret = CommandLineRPC(argc, argv); exit(ret); } #if !defined(WIN32) fDaemon = GetBoolArg("-daemon"); if (fDaemon) { // Daemonize pid_t pid = fork(); if (pid < 0) { fprintf(stderr, "Error: fork() returned %d errno %d\n", pid, errno); return false; } if (pid > 0) // Parent process, pid is child process id { CreatePidFile(GetPidFile(), pid); return true; } // Child process falls through to rest of initialization pid_t sid = setsid(); if (sid < 0) fprintf(stderr, "Error: setsid() returned %d errno %d\n", sid, errno); } #endif detectShutdownThread = new boost::thread(boost::bind(&DetectShutdownThread, &threadGroup)); fRet = AppInit2(threadGroup); } catch (std::exception& e) { PrintExceptionContinue(&e, "AppInit()"); } catch (...) { PrintExceptionContinue(NULL, "AppInit()"); } if (!fRet) { if (detectShutdownThread) detectShutdownThread->interrupt(); threadGroup.interrupt_all(); } if (detectShutdownThread) { detectShutdownThread->join(); delete detectShutdownThread; detectShutdownThread = NULL; } Shutdown(); return fRet; } extern void noui_connect(); int main(int argc, char* argv[]) { bool fRet = false; // Connect crowncoind signal handlers noui_connect(); fRet = AppInit(argc, argv); if (fRet && fDaemon) return 0; return (fRet ? 0 : 1); } #endif bool static InitError(const std::string &str) { uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_ERROR); return false; } bool static InitWarning(const std::string &str) { uiInterface.ThreadSafeMessageBox(str, "", CClientUIInterface::MSG_WARNING); return true; } bool static Bind(const CService &addr, unsigned int flags) { if (!(flags & BF_EXPLICIT) && IsLimited(addr)) return false; std::string strError; if (!BindListenPort(addr, strError)) { if (flags & BF_REPORT_ERROR) return InitError(strError); return false; } return true; } // Core-specific options shared between UI and daemon std::string HelpMessage() { string strUsage = _("Options:") + "\n" + " -? " + _("This help message") + "\n" + " -conf=<file> " + _("Specify configuration file (default: crowncoin.conf)") + "\n" + " -pid=<file> " + _("Specify pid file (default: bitcoind.pid)") + "\n" + " -gen " + _("Generate coins (default: 0)") + "\n" + " -datadir=<dir> " + _("Specify data directory") + "\n" + " -dbcache=<n> " + _("Set database cache size in megabytes (default: 25)") + "\n" + " -timeout=<n> " + _("Specify connection timeout in milliseconds (default: 5000)") + "\n" + " -proxy=<ip:port> " + _("Connect through socks proxy") + "\n" + " -socks=<n> " + _("Select the version of socks proxy to use (4-5, default: 5)") + "\n" + " -tor=<ip:port> " + _("Use proxy to reach tor hidden services (default: same as -proxy)") + "\n" " -dns " + _("Allow DNS lookups for -addnode, -seednode and -connect") + "\n" + " -port=<port> " + _("Listen for connections on <port> (default: 9111 or testnet: 19111)") + "\n" + " -maxconnections=<n> " + _("Maintain at most <n> connections to peers (default: 125)") + "\n" + " -addnode=<ip> " + _("Add a node to connect to and attempt to keep the connection open") + "\n" + " -connect=<ip> " + _("Connect only to the specified node(s)") + "\n" + " -seednode=<ip> " + _("Connect to a node to retrieve peer addresses, and disconnect") + "\n" + " -externalip=<ip> " + _("Specify your own public address") + "\n" + " -onlynet=<net> " + _("Only connect to nodes in network <net> (IPv4, IPv6 or Tor)") + "\n" + " -discover " + _("Discover own IP address (default: 1 when listening and no -externalip)") + "\n" + " -checkpoints " + _("Only accept block chain matching built-in checkpoints (default: 1)") + "\n" + " -listen " + _("Accept connections from outside (default: 1 if no -proxy or -connect)") + "\n" + " -bind=<addr> " + _("Bind to given address and always listen on it. Use [host]:port notation for IPv6") + "\n" + " -dnsseed " + _("Find peers using DNS lookup (default: 1 unless -connect)") + "\n" + " -banscore=<n> " + _("Threshold for disconnecting misbehaving peers (default: 100)") + "\n" + " -bantime=<n> " + _("Number of seconds to keep misbehaving peers from reconnecting (default: 86400)") + "\n" + " -maxreceivebuffer=<n> " + _("Maximum per-connection receive buffer, <n>*1000 bytes (default: 5000)") + "\n" + " -maxsendbuffer=<n> " + _("Maximum per-connection send buffer, <n>*1000 bytes (default: 1000)") + "\n" + #ifdef USE_UPNP #if USE_UPNP " -upnp " + _("Use UPnP to map the listening port (default: 1 when listening)") + "\n" + #else " -upnp " + _("Use UPnP to map the listening port (default: 0)") + "\n" + #endif #endif " -paytxfee=<amt> " + _("Fee per KB to add to transactions you send") + "\n" + #ifdef QT_GUI " -server " + _("Accept command line and JSON-RPC commands") + "\n" + #endif #if !defined(WIN32) && !defined(QT_GUI) " -daemon " + _("Run in the background as a daemon and accept commands") + "\n" + #endif " -testnet " + _("Use the test network") + "\n" + " -debug " + _("Output extra debugging information. Implies all other -debug* options") + "\n" + " -debugnet " + _("Output extra network debugging information") + "\n" + " -logtimestamps " + _("Prepend debug output with timestamp (default: 1)") + "\n" + " -shrinkdebugfile " + _("Shrink debug.log file on client startup (default: 1 when no -debug)") + "\n" + " -printtoconsole " + _("Send trace/debug info to console instead of debug.log file") + "\n" + #ifdef WIN32 " -printtodebugger " + _("Send trace/debug info to debugger") + "\n" + #endif " -rpcuser=<user> " + _("Username for JSON-RPC connections") + "\n" + " -rpcpassword=<pw> " + _("Password for JSON-RPC connections") + "\n" + " -rpcport=<port> " + _("Listen for JSON-RPC connections on <port> (default: 9112 or testnet: 19112)") + "\n" + " -rpcallowip=<ip> " + _("Allow JSON-RPC connections from specified IP address") + "\n" + #ifndef QT_GUI " -rpcconnect=<ip> " + _("Send commands to node running on <ip> (default: 127.0.0.1)") + "\n" + #endif " -rpcthreads=<n> " + _("Set the number of threads to service RPC calls (default: 4)") + "\n" + " -blocknotify=<cmd> " + _("Execute command when the best block changes (%s in cmd is replaced by block hash)") + "\n" + " -walletnotify=<cmd> " + _("Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)") + "\n" + " -alertnotify=<cmd> " + _("Execute command when a relevant alert is received (%s in cmd is replaced by message)") + "\n" + " -upgradewallet " + _("Upgrade wallet to latest format") + "\n" + " -keypool=<n> " + _("Set key pool size to <n> (default: 100)") + "\n" + " -rescan " + _("Rescan the block chain for missing wallet transactions") + "\n" + " -salvagewallet " + _("Attempt to recover private keys from a corrupt wallet.dat") + "\n" + " -checkblocks=<n> " + _("How many blocks to check at startup (default: 288, 0 = all)") + "\n" + " -checklevel=<n> " + _("How thorough the block verification is (0-4, default: 3)") + "\n" + " -txindex " + _("Maintain a full transaction index (default: 0)") + "\n" + " -loadblock=<file> " + _("Imports blocks from external blk000??.dat file") + "\n" + " -reindex " + _("Rebuild block chain index from current blk000??.dat files") + "\n" + " -par=<n> " + _("Set the number of script verification threads (up to 16, 0 = auto, <0 = leave that many cores free, default: 0)") + "\n" + "\n" + _("Block creation options:") + "\n" + " -blockminsize=<n> " + _("Set minimum block size in bytes (default: 0)") + "\n" + " -blockmaxsize=<n> " + _("Set maximum block size in bytes (default: 250000)") + "\n" + " -blockprioritysize=<n> " + _("Set maximum size of high-priority/low-fee transactions in bytes (default: 27000)") + "\n" + "\n" + _("SSL options: (see the Bitcoin Wiki for SSL setup instructions)") + "\n" + " -rpcssl " + _("Use OpenSSL (https) for JSON-RPC connections") + "\n" + " -rpcsslcertificatechainfile=<file.cert> " + _("Server certificate file (default: server.cert)") + "\n" + " -rpcsslprivatekeyfile=<file.pem> " + _("Server private key (default: server.pem)") + "\n" + " -rpcsslciphers=<ciphers> " + _("Acceptable ciphers (default: TLSv1+HIGH:!SSLv2:!aNULL:!eNULL:!AH:!3DES:@STRENGTH)") + "\n"; return strUsage; } struct CImportingNow { CImportingNow() { assert(fImporting == false); fImporting = true; } ~CImportingNow() { assert(fImporting == true); fImporting = false; } }; void ThreadImport(std::vector<boost::filesystem::path> vImportFiles) { RenameThread("bitcoin-loadblk"); // -reindex if (fReindex) { CImportingNow imp; int nFile = 0; while (true) { CDiskBlockPos pos(nFile, 0); FILE *file = OpenBlockFile(pos, true); if (!file) break; printf("Reindexing block file blk%05u.dat...\n", (unsigned int)nFile); LoadExternalBlockFile(file, &pos); nFile++; } pblocktree->WriteReindexing(false); fReindex = false; printf("Reindexing finished\n"); // To avoid ending up in a situation without genesis block, re-try initializing (no-op if reindexing worked): InitBlockIndex(); } // hardcoded $DATADIR/bootstrap.dat filesystem::path pathBootstrap = GetDataDir() / "bootstrap.dat"; if (filesystem::exists(pathBootstrap)) { FILE *file = fopen(pathBootstrap.string().c_str(), "rb"); if (file) { CImportingNow imp; filesystem::path pathBootstrapOld = GetDataDir() / "bootstrap.dat.old"; printf("Importing bootstrap.dat...\n"); LoadExternalBlockFile(file); RenameOver(pathBootstrap, pathBootstrapOld); } } // -loadblock= BOOST_FOREACH(boost::filesystem::path &path, vImportFiles) { FILE *file = fopen(path.string().c_str(), "rb"); if (file) { CImportingNow imp; printf("Importing %s...\n", path.string().c_str()); LoadExternalBlockFile(file); } } } /** Initialize crowncoin. * @pre Parameters should be parsed and config file should be read. */ bool AppInit2(boost::thread_group& threadGroup) { // ********************************************************* Step 1: setup #ifdef _MSC_VER // Turn off Microsoft heap dump noise _CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE); _CrtSetReportFile(_CRT_WARN, CreateFileA("NUL", GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, 0)); #endif #if _MSC_VER >= 1400 // Disable confusing "helpful" text message on abort, Ctrl-C _set_abort_behavior(0, _WRITE_ABORT_MSG | _CALL_REPORTFAULT); #endif #ifdef WIN32 // Enable Data Execution Prevention (DEP) // Minimum supported OS versions: WinXP SP3, WinVista >= SP1, Win Server 2008 // A failure is non-critical and needs no further attention! #ifndef PROCESS_DEP_ENABLE // We define this here, because GCCs winbase.h limits this to _WIN32_WINNT >= 0x0601 (Windows 7), // which is not correct. Can be removed, when GCCs winbase.h is fixed! #define PROCESS_DEP_ENABLE 0x00000001 #endif typedef BOOL (WINAPI *PSETPROCDEPPOL)(DWORD); PSETPROCDEPPOL setProcDEPPol = (PSETPROCDEPPOL)GetProcAddress(GetModuleHandleA("Kernel32.dll"), "SetProcessDEPPolicy"); if (setProcDEPPol != NULL) setProcDEPPol(PROCESS_DEP_ENABLE); // Initialize Windows Sockets WSADATA wsadata; int ret = WSAStartup(MAKEWORD(2,2), &wsadata); if (ret != NO_ERROR || LOBYTE(wsadata.wVersion ) != 2 || HIBYTE(wsadata.wVersion) != 2) { return InitError(strprintf("Error: Winsock library failed to start (WSAStartup returned error %d)", ret)); } #endif #ifndef WIN32 umask(077); // Clean shutdown on SIGTERM struct sigaction sa; sa.sa_handler = HandleSIGTERM; sigemptyset(&sa.sa_mask); sa.sa_flags = 0; sigaction(SIGTERM, &sa, NULL); sigaction(SIGINT, &sa, NULL); // Reopen debug.log on SIGHUP struct sigaction sa_hup; sa_hup.sa_handler = HandleSIGHUP; sigemptyset(&sa_hup.sa_mask); sa_hup.sa_flags = 0; sigaction(SIGHUP, &sa_hup, NULL); #endif // ********************************************************* Step 2: parameter interactions fTestNet = GetBoolArg("-testnet"); if (mapArgs.count("-bind")) { // when specifying an explicit binding address, you want to listen on it // even when -connect or -proxy is specified SoftSetBoolArg("-listen", true); } if (mapArgs.count("-connect") && mapMultiArgs["-connect"].size() > 0) { // when only connecting to trusted nodes, do not seed via DNS, or listen by default SoftSetBoolArg("-dnsseed", false); SoftSetBoolArg("-listen", false); } if (mapArgs.count("-proxy")) { // to protect privacy, do not listen by default if a proxy server is specified SoftSetBoolArg("-listen", false); } if (!GetBoolArg("-listen", true)) { // do not map ports or try to retrieve public IP when not listening (pointless) SoftSetBoolArg("-upnp", false); SoftSetBoolArg("-discover", false); } if (mapArgs.count("-externalip")) { // if an explicit public IP is specified, do not try to find others SoftSetBoolArg("-discover", false); } if (GetBoolArg("-salvagewallet")) { // Rewrite just private keys: rescan to find transactions SoftSetBoolArg("-rescan", true); } // Make sure enough file descriptors are available int nBind = std::max((int)mapArgs.count("-bind"), 1); nMaxConnections = GetArg("-maxconnections", 125); nMaxConnections = std::max(std::min(nMaxConnections, (int)(FD_SETSIZE - nBind - MIN_CORE_FILEDESCRIPTORS)), 0); int nFD = RaiseFileDescriptorLimit(nMaxConnections + MIN_CORE_FILEDESCRIPTORS); if (nFD < MIN_CORE_FILEDESCRIPTORS) return InitError(_("Not enough file descriptors available.")); if (nFD - MIN_CORE_FILEDESCRIPTORS < nMaxConnections) nMaxConnections = nFD - MIN_CORE_FILEDESCRIPTORS; // ********************************************************* Step 3: parameter-to-internal-flags fDebug = GetBoolArg("-debug"); fBenchmark = GetBoolArg("-benchmark"); // -par=0 means autodetect, but nScriptCheckThreads==0 means no concurrency nScriptCheckThreads = GetArg("-par", 0); if (nScriptCheckThreads <= 0) nScriptCheckThreads += boost::thread::hardware_concurrency(); if (nScriptCheckThreads <= 1) nScriptCheckThreads = 0; else if (nScriptCheckThreads > MAX_SCRIPTCHECK_THREADS) nScriptCheckThreads = MAX_SCRIPTCHECK_THREADS; // -debug implies fDebug* if (fDebug) fDebugNet = true; else fDebugNet = GetBoolArg("-debugnet"); if (fDaemon) fServer = true; else fServer = GetBoolArg("-server"); /* force fServer when running without GUI */ #if !defined(QT_GUI) fServer = true; #endif fPrintToConsole = GetBoolArg("-printtoconsole"); fPrintToDebugger = GetBoolArg("-printtodebugger"); fLogTimestamps = GetBoolArg("-logtimestamps", true); if (mapArgs.count("-timeout")) { int nNewTimeout = GetArg("-timeout", 5000); if (nNewTimeout > 0 && nNewTimeout < 600000) nConnectTimeout = nNewTimeout; } // Continue to put "/P2SH/" in the coinbase to monitor // BIP16 support. // This can be removed eventually... const char* pszP2SH = "/P2SH/"; COINBASE_FLAGS << std::vector<unsigned char>(pszP2SH, pszP2SH+strlen(pszP2SH)); // Fee-per-kilobyte amount considered the same as "free" // If you are mining, be careful setting this: // if you set it to zero then // a transaction spammer can cheaply fill blocks using // 1-satoshi-fee transactions. It should be set above the real // cost to you of processing a transaction. if (mapArgs.count("-mintxfee")) { int64 n = 0; if (ParseMoney(mapArgs["-mintxfee"], n) && n > 0) CTransaction::nMinTxFee = n; else return InitError(strprintf(_("Invalid amount for -mintxfee=<amount>: '%s'"), mapArgs["-mintxfee"].c_str())); } if (mapArgs.count("-minrelaytxfee")) { int64 n = 0; if (ParseMoney(mapArgs["-minrelaytxfee"], n) && n > 0) CTransaction::nMinRelayTxFee = n; else return InitError(strprintf(_("Invalid amount for -minrelaytxfee=<amount>: '%s'"), mapArgs["-minrelaytxfee"].c_str())); } if (mapArgs.count("-paytxfee")) { if (!ParseMoney(mapArgs["-paytxfee"], nTransactionFee)) return InitError(strprintf(_("Invalid amount for -paytxfee=<amount>: '%s'"), mapArgs["-paytxfee"].c_str())); if (nTransactionFee > 0.25 * COIN) InitWarning(_("Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.")); } // ********************************************************* Step 4: application initialization: dir lock, daemonize, pidfile, debug log std::string strDataDir = GetDataDir().string(); // Make sure only a single Crowncoin process is using the data directory. boost::filesystem::path pathLockFile = GetDataDir() / ".lock"; FILE* file = fopen(pathLockFile.string().c_str(), "a"); // empty lock file; created if it doesn't exist. if (file) fclose(file); static boost::interprocess::file_lock lock(pathLockFile.string().c_str()); if (!lock.try_lock()) return InitError(strprintf(_("Cannot obtain a lock on data directory %s. Crowncoin is probably already running."), strDataDir.c_str())); if (GetBoolArg("-shrinkdebugfile", !fDebug)) ShrinkDebugFile(); printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"); printf("Crowncoin version %s (%s)\n", FormatFullVersion().c_str(), CLIENT_DATE.c_str()); printf("Using OpenSSL version %s\n", SSLeay_version(SSLEAY_VERSION)); if (!fLogTimestamps) printf("Startup time: %s\n", DateTimeStrFormat("%Y-%m-%d %H:%M:%S", GetTime()).c_str()); printf("Default data directory %s\n", GetDefaultDataDir().string().c_str()); printf("Using data directory %s\n", strDataDir.c_str()); printf("Using at most %i connections (%i file descriptors available)\n", nMaxConnections, nFD); std::ostringstream strErrors; if (fDaemon) fprintf(stdout, "Crowncoin server starting\n"); if (nScriptCheckThreads) { printf("Using %u threads for script verification\n", nScriptCheckThreads); for (int i=0; i<nScriptCheckThreads-1; i++) threadGroup.create_thread(&ThreadScriptCheck); } int64 nStart; // ********************************************************* Step 5: verify wallet database integrity uiInterface.InitMessage(_("Verifying wallet...")); if (!bitdb.Open(GetDataDir())) { // try moving the database env out of the way boost::filesystem::path pathDatabase = GetDataDir() / "database"; boost::filesystem::path pathDatabaseBak = GetDataDir() / strprintf("database.%"PRI64d".bak", GetTime()); try { boost::filesystem::rename(pathDatabase, pathDatabaseBak); printf("Moved old %s to %s. Retrying.\n", pathDatabase.string().c_str(), pathDatabaseBak.string().c_str()); } catch(boost::filesystem::filesystem_error &error) { // failure is ok (well, not really, but it's not worse than what we started with) } // try again if (!bitdb.Open(GetDataDir())) { // if it still fails, it probably means we can't even create the database env string msg = strprintf(_("Error initializing wallet database environment %s!"), strDataDir.c_str()); return InitError(msg); } } if (GetBoolArg("-salvagewallet")) { // Recover readable keypairs: if (!CWalletDB::Recover(bitdb, "wallet.dat", true)) return false; } if (filesystem::exists(GetDataDir() / "wallet.dat")) { CDBEnv::VerifyResult r = bitdb.Verify("wallet.dat", CWalletDB::Recover); if (r == CDBEnv::RECOVER_OK) { string msg = strprintf(_("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."), strDataDir.c_str()); InitWarning(msg); } if (r == CDBEnv::RECOVER_FAIL) return InitError(_("wallet.dat corrupt, salvage failed")); } // ********************************************************* Step 6: network initialization int nSocksVersion = GetArg("-socks", 5); if (nSocksVersion != 4 && nSocksVersion != 5) return InitError(strprintf(_("Unknown -socks proxy version requested: %i"), nSocksVersion)); if (mapArgs.count("-onlynet")) { std::set<enum Network> nets; BOOST_FOREACH(std::string snet, mapMultiArgs["-onlynet"]) { enum Network net = ParseNetwork(snet); if (net == NET_UNROUTABLE) return InitError(strprintf(_("Unknown network specified in -onlynet: '%s'"), snet.c_str())); nets.insert(net); } for (int n = 0; n < NET_MAX; n++) { enum Network net = (enum Network)n; if (!nets.count(net)) SetLimited(net); } } #if defined(USE_IPV6) #if ! USE_IPV6 else SetLimited(NET_IPV6); #endif #endif CService addrProxy; bool fProxy = false; if (mapArgs.count("-proxy")) { addrProxy = CService(mapArgs["-proxy"], 9042); if (!addrProxy.IsValid()) return InitError(strprintf(_("Invalid -proxy address: '%s'"), mapArgs["-proxy"].c_str())); if (!IsLimited(NET_IPV4)) SetProxy(NET_IPV4, addrProxy, nSocksVersion); if (nSocksVersion > 4) { #ifdef USE_IPV6 if (!IsLimited(NET_IPV6)) SetProxy(NET_IPV6, addrProxy, nSocksVersion); #endif SetNameProxy(addrProxy, nSocksVersion); } fProxy = true; } // -tor can override normal proxy, -notor disables tor entirely if (!(mapArgs.count("-tor") && mapArgs["-tor"] == "0") && (fProxy || mapArgs.count("-tor"))) { CService addrOnion; if (!mapArgs.count("-tor")) addrOnion = addrProxy; else addrOnion = CService(mapArgs["-tor"], 9042); if (!addrOnion.IsValid()) return InitError(strprintf(_("Invalid -tor address: '%s'"), mapArgs["-tor"].c_str())); SetProxy(NET_TOR, addrOnion, 5); SetReachable(NET_TOR); } // see Step 2: parameter interactions for more information about these fNoListen = !GetBoolArg("-listen", true); fDiscover = GetBoolArg("-discover", true); fNameLookup = GetBoolArg("-dns", true); bool fBound = false; if (!fNoListen) { if (mapArgs.count("-bind")) { BOOST_FOREACH(std::string strBind, mapMultiArgs["-bind"]) { CService addrBind; if (!Lookup(strBind.c_str(), addrBind, GetListenPort(), false)) return InitError(strprintf(_("Cannot resolve -bind address: '%s'"), strBind.c_str())); fBound |= Bind(addrBind, (BF_EXPLICIT | BF_REPORT_ERROR)); } } else { struct in_addr inaddr_any; inaddr_any.s_addr = INADDR_ANY; #ifdef USE_IPV6 fBound |= Bind(CService(in6addr_any, GetListenPort()), BF_NONE); #endif fBound |= Bind(CService(inaddr_any, GetListenPort()), !fBound ? BF_REPORT_ERROR : BF_NONE); } if (!fBound) return InitError(_("Failed to listen on any port. Use -listen=0 if you want this.")); } if (mapArgs.count("-externalip")) { BOOST_FOREACH(string strAddr, mapMultiArgs["-externalip"]) { CService addrLocal(strAddr, GetListenPort(), fNameLookup); if (!addrLocal.IsValid()) return InitError(strprintf(_("Cannot resolve -externalip address: '%s'"), strAddr.c_str())); AddLocal(CService(strAddr, GetListenPort(), fNameLookup), LOCAL_MANUAL); } } BOOST_FOREACH(string strDest, mapMultiArgs["-seednode"]) AddOneShot(strDest); // ********************************************************* Step 7: load block chain fReindex = GetBoolArg("-reindex"); // Upgrading to 0.8; hard-link the old blknnnn.dat files into /blocks/ filesystem::path blocksDir = GetDataDir() / "blocks"; if (!filesystem::exists(blocksDir)) { filesystem::create_directories(blocksDir); bool linked = false; for (unsigned int i = 1; i < 10000; i++) { filesystem::path source = GetDataDir() / strprintf("blk%04u.dat", i); if (!filesystem::exists(source)) break; filesystem::path dest = blocksDir / strprintf("blk%05u.dat", i-1); try { filesystem::create_hard_link(source, dest); printf("Hardlinked %s -> %s\n", source.string().c_str(), dest.string().c_str()); linked = true; } catch (filesystem::filesystem_error & e) { // Note: hardlink creation failing is not a disaster, it just means // blocks will get re-downloaded from peers. printf("Error hardlinking blk%04u.dat : %s\n", i, e.what()); break; } } if (linked) { fReindex = true; } } // cache size calculations size_t nTotalCache = GetArg("-dbcache", 25) << 20; if (nTotalCache < (1 << 22)) nTotalCache = (1 << 22); // total cache cannot be less than 4 MiB size_t nBlockTreeDBCache = nTotalCache / 8; if (nBlockTreeDBCache > (1 << 21) && !GetBoolArg("-txindex", false)) nBlockTreeDBCache = (1 << 21); // block tree db cache shouldn't be larger than 2 MiB nTotalCache -= nBlockTreeDBCache; size_t nCoinDBCache = nTotalCache / 2; // use half of the remaining cache for coindb cache nTotalCache -= nCoinDBCache; nCoinCacheSize = nTotalCache / 300; // coins in memory require around 300 bytes bool fLoaded = false; while (!fLoaded) { bool fReset = fReindex; std::string strLoadError; uiInterface.InitMessage(_("Loading block index...")); nStart = GetTimeMillis(); do { try { UnloadBlockIndex(); delete pcoinsTip; delete pcoinsdbview; delete pblocktree; pblocktree = new CBlockTreeDB(nBlockTreeDBCache, false, fReindex); pcoinsdbview = new CCoinsViewDB(nCoinDBCache, false, fReindex); pcoinsTip = new CCoinsViewCache(*pcoinsdbview); if (fReindex) pblocktree->WriteReindexing(true); if (!LoadBlockIndex()) { strLoadError = _("Error loading block database"); break; } // Initialize the block index (no-op if non-empty database was already loaded) if (!InitBlockIndex()) { strLoadError = _("Error initializing block database"); break; } uiInterface.InitMessage(_("Verifying blocks...")); if (!VerifyDB()) { strLoadError = _("Corrupted block database detected"); break; } } catch(std::exception &e) { strLoadError = _("Error opening block database"); break; } fLoaded = true; } while(false); if (!fLoaded) { // first suggest a reindex if (!fReset) { bool fRet = uiInterface.ThreadSafeMessageBox( strLoadError + ".\n" + _("Do you want to rebuild the block database now?"), "", CClientUIInterface::MSG_ERROR | CClientUIInterface::BTN_ABORT); if (fRet) { fReindex = true; fRequestShutdown = false; } else { return false; } } else { return InitError(strLoadError); } } } if (mapArgs.count("-txindex") && fTxIndex != GetBoolArg("-txindex", false)) return InitError(_("You need to rebuild the databases using -reindex to change -txindex")); // as LoadBlockIndex can take several minutes, it's possible the user // requested to kill crowncoin-qt during the last operation. If so, exit. // As the program has not fully started yet, Shutdown() is possibly overkill. if (fRequestShutdown) { printf("Shutdown requested. Exiting.\n"); return false; } printf(" block index %15"PRI64d"ms\n", GetTimeMillis() - nStart); if (GetBoolArg("-printblockindex") || GetBoolArg("-printblocktree")) { PrintBlockTree(); return false; } if (mapArgs.count("-printblock")) { string strMatch = mapArgs["-printblock"]; int nFound = 0; for (map<uint256, CBlockIndex*>::iterator mi = mapBlockIndex.begin(); mi != mapBlockIndex.end(); ++mi) { uint256 hash = (*mi).first; if (strncmp(hash.ToString().c_str(), strMatch.c_str(), strMatch.size()) == 0) { CBlockIndex* pindex = (*mi).second; CBlock block; block.ReadFromDisk(pindex); block.BuildMerkleTree(); block.print(); printf("\n"); nFound++; } } if (nFound == 0) printf("No blocks matching %s were found\n", strMatch.c_str()); return false; } // ********************************************************* Step 8: load wallet uiInterface.InitMessage(_("Loading wallet...")); nStart = GetTimeMillis(); bool fFirstRun = true; pwalletMain = new CWallet("wallet.dat"); DBErrors nLoadWalletRet = pwalletMain->LoadWallet(fFirstRun); if (nLoadWalletRet != DB_LOAD_OK) { if (nLoadWalletRet == DB_CORRUPT) strErrors << _("Error loading wallet.dat: Wallet corrupted") << "\n"; else if (nLoadWalletRet == DB_NONCRITICAL_ERROR) { string msg(_("Warning: error reading wallet.dat! All keys read correctly, but transaction data" " or address book entries might be missing or incorrect.")); InitWarning(msg); } else if (nLoadWalletRet == DB_TOO_NEW) strErrors << _("Error loading wallet.dat: Wallet requires newer version of Crowncoin") << "\n"; else if (nLoadWalletRet == DB_NEED_REWRITE) { strErrors << _("Wallet needed to be rewritten: restart Crowncoin to complete") << "\n"; printf("%s", strErrors.str().c_str()); return InitError(strErrors.str()); } else strErrors << _("Error loading wallet.dat") << "\n"; } if (GetBoolArg("-upgradewallet", fFirstRun)) { int nMaxVersion = GetArg("-upgradewallet", 0); if (nMaxVersion == 0) // the -upgradewallet without argument case { printf("Performing wallet upgrade to %i\n", FEATURE_LATEST); nMaxVersion = CLIENT_VERSION; pwalletMain->SetMinVersion(FEATURE_LATEST); // permanently upgrade the wallet immediately } else printf("Allowing wallet upgrade up to %i\n", nMaxVersion); if (nMaxVersion < pwalletMain->GetVersion()) strErrors << _("Cannot downgrade wallet") << "\n"; pwalletMain->SetMaxVersion(nMaxVersion); } if (fFirstRun) { // Create new keyUser and set as default key RandAddSeedPerfmon(); CPubKey newDefaultKey; if (pwalletMain->GetKeyFromPool(newDefaultKey, false)) { pwalletMain->SetDefaultKey(newDefaultKey); if (!pwalletMain->SetAddressBookName(pwalletMain->vchDefaultKey.GetID(), "")) strErrors << _("Cannot write default address") << "\n"; } pwalletMain->SetBestChain(CBlockLocator(pindexBest)); } printf("%s", strErrors.str().c_str()); printf(" wallet %15"PRI64d"ms\n", GetTimeMillis() - nStart); RegisterWallet(pwalletMain); CBlockIndex *pindexRescan = pindexBest; if (GetBoolArg("-rescan")) pindexRescan = pindexGenesisBlock; else { CWalletDB walletdb("wallet.dat"); CBlockLocator locator; if (walletdb.ReadBestBlock(locator)) pindexRescan = locator.GetBlockIndex(); else pindexRescan = pindexGenesisBlock; } if (pindexBest && pindexBest != pindexRescan) { uiInterface.InitMessage(_("Rescanning...")); printf("Rescanning last %i blocks (from block %i)...\n", pindexBest->nHeight - pindexRescan->nHeight, pindexRescan->nHeight); nStart = GetTimeMillis(); pwalletMain->ScanForWalletTransactions(pindexRescan, true); printf(" rescan %15"PRI64d"ms\n", GetTimeMillis() - nStart); pwalletMain->SetBestChain(CBlockLocator(pindexBest)); nWalletDBUpdated++; } // ********************************************************* Step 9: import blocks // scan for better chains in the block chain database, that are not yet connected in the active best chain CValidationState state; if (!ConnectBestBlock(state)) strErrors << "Failed to connect best block"; std::vector<boost::filesystem::path> vImportFiles; if (mapArgs.count("-loadblock")) { BOOST_FOREACH(string strFile, mapMultiArgs["-loadblock"]) vImportFiles.push_back(strFile); } threadGroup.create_thread(boost::bind(&ThreadImport, vImportFiles)); // ********************************************************* Step 10: load peers uiInterface.InitMessage(_("Loading addresses...")); nStart = GetTimeMillis(); { CAddrDB adb; if (!adb.Read(addrman)) printf("Invalid or missing peers.dat; recreating\n"); } printf("Loaded %i addresses from peers.dat %"PRI64d"ms\n", addrman.size(), GetTimeMillis() - nStart); // ********************************************************* Step 11: start node if (!CheckDiskSpace()) return false; if (!strErrors.str().empty()) return InitError(strErrors.str()); RandAddSeedPerfmon(); //// debug print printf("mapBlockIndex.size() = %"PRIszu"\n", mapBlockIndex.size()); printf("nBestHeight = %d\n", nBestHeight); printf("setKeyPool.size() = %"PRIszu"\n", pwalletMain->setKeyPool.size()); printf("mapWallet.size() = %"PRIszu"\n", pwalletMain->mapWallet.size()); printf("mapAddressBook.size() = %"PRIszu"\n", pwalletMain->mapAddressBook.size()); StartNode(threadGroup); if (fServer) StartRPCThreads(); // Generate coins in the background GenerateBitcoins(GetBoolArg("-gen", false), pwalletMain); // ********************************************************* Step 12: finished uiInterface.InitMessage(_("Done loading")); // Add wallet transactions that aren't already in a block to mapTransactions pwalletMain->ReacceptWalletTransactions(); // Run a thread to flush wallet periodically threadGroup.create_thread(boost::bind(&ThreadFlushWalletDB, boost::ref(pwalletMain->strWalletFile))); return !fRequestShutdown; }
0e5bf7b869a3039d63d293b7d79930af56ba8c46
aaf86162b5f90e5d3358d9629a84a5af8feaf14b
/codeVS/1430 素数判定/main.cpp
4e876e4141e094e97f408375acfc2942fb5d8408
[]
no_license
Linsenx/AcmCodes
ffbd5b5b634a693d9d5e8af680dfc8657085f2e1
08f6c708c9b47a3e8234dc2f9d2534344c0597c5
refs/heads/master
2021-09-14T11:57:43.707852
2018-05-13T06:04:00
2018-05-13T06:04:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
351
cpp
#include <bits/stdc++.h> using namespace std; int isPrime(int x) { int v = sqrt(x); for(int i = 2; i <= v; ++i) { if (x % i == 0) return 0; } return 1; } int main() { freopen("in.txt", "r", stdin); int a; cin >> a; if (isPrime(a) == 1) { cout << "\\t" << endl; } else{ cout << "\\n" << endl; } return 0; }
16cad8b479f480b29b00fd7f754d00770f689329
67d1eba373b9afe9cd1f6bc8a52fde774207e6c7
/UVA/186 - Trip Routing.cpp
3563c6e99d4b210112744037850aac658ed3a7b2
[]
no_license
evan-hossain/competitive-programming
879b8952df587baf906298a609b471971bdfd421
561ce1a6b4a4a6958260206a5d0252cc9ea80c75
refs/heads/master
2021-06-01T13:54:04.351848
2018-01-19T14:18:35
2018-01-19T14:18:35
93,148,046
2
3
null
2020-10-01T13:29:54
2017-06-02T09:04:50
C++
UTF-8
C++
false
false
3,772
cpp
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include <queue> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <cstring> #define out freopen("output.txt", "w", stdout); #define in freopen("input.txt", "r", stdin); #define pub push_back #define pob pop_back #define infinity 2147483647 >> 1 ///int col[8] = {0, 1, 1, 1, 0, -1, -1, -1}; ///int row[8] = {1, 1, 0, -1, -1, -1, 0, 1}; using namespace std; struct edge { string route; int dist; }; int nodes; edge grid[110][110]; int pred[110][110]; map <int, string> itos; void initialize(void); void floyed(int n); void path(int a, int b); int main() { char c; string a, b, r; int n; map <string, int> mp; initialize(); while(true) { if((c = getchar()) == '\n') break; a.clear(), b.clear(), r.clear(); a += c; while((c = getchar()) != ',') a += c; if(mp.find(a) == mp.end()) { mp[a] = nodes; itos[nodes] = a; nodes++; } while((c = getchar()) != ',') b += c; if(mp.find(b) == mp.end()) { mp[b] = nodes; itos[nodes] = b; nodes++; } while((c = getchar()) != ',') r += c; scanf("%d", &n); getchar(); if(a != b && grid[mp[a]][mp[b]].dist > n) { grid[mp[a]][mp[b]].dist = grid[mp[b]][mp[a]].dist = n; grid[mp[a]][mp[b]].route = grid[mp[b]][mp[a]].route = r; } } floyed(nodes); while(scanf("%c", &c) == 1) { printf("\n\nFrom To Route Miles\n"); printf("-------------------- -------------------- ---------- -----\n"); a.clear(), b.clear(); a += c; while((c = getchar()) != ',') a += c; while(scanf("%c", &c) == 1) { if(c == '\n') break; b += c; } path(mp[a], mp[b]); printf(" -----\n"); printf(" Total %5d\n", grid[mp[a]][mp[b]].dist); } return 0; } void initialize(void) { int i, j; for(i = 0; i < 105; i++) { for(j = 0; j < 105; j++) grid[i][j].dist = infinity; grid[i][i].dist = 0; } } void floyed(int n) { int i, j, k; for(k = 0; k < n; k++) for(i = 0; i < n; i++) for(j = 0; j < n; j++) { if(grid[i][j].dist > grid[i][k].dist + grid[k][j].dist) { grid[i][j].dist = grid[i][k].dist + grid[k][j].dist; pred[i][j] = k; } } return; } void path(int a, int b) { if(pred[a][b] == 0) { printf("%-20s %-20s %-10s %5d\n", itos[a].c_str(), itos[b].c_str(), grid[a][b].route.c_str(), grid[a][b].dist); return; } path(a, pred[a][b]); path(pred[a][b], b); }
cb7e003b7585dc8033e09da1097e3070fd6ccbab
88ae8695987ada722184307301e221e1ba3cc2fa
/components/history_clusters/core/file_clustering_backend_unittest.cc
a69bf78645242b0071ed88eff20e3e17d6132503
[ "BSD-3-Clause" ]
permissive
iridium-browser/iridium-browser
71d9c5ff76e014e6900b825f67389ab0ccd01329
5ee297f53dc7f8e70183031cff62f37b0f19d25f
refs/heads/master
2023-08-03T16:44:16.844552
2023-07-20T15:17:00
2023-07-23T16:09:30
220,016,632
341
40
BSD-3-Clause
2021-08-13T13:54:45
2019-11-06T14:32:31
null
UTF-8
C++
false
false
5,238
cc
// Copyright 2022 The Chromium Authors // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/history_clusters/core/file_clustering_backend.h" #include "base/command_line.h" #include "base/containers/flat_set.h" #include "base/files/file_util.h" #include "base/files/scoped_temp_dir.h" #include "base/run_loop.h" #include "base/test/task_environment.h" #include "components/history_clusters/core/clustering_test_utils.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace history_clusters { namespace { using ::testing::ElementsAre; class FileClusteringBackendTest : public ::testing::Test { public: FileClusteringBackendTest() = default; ~FileClusteringBackendTest() override = default; void SetUp() override { ::testing::Test::SetUp(); ASSERT_TRUE(temp_dir_.CreateUniqueTempDir()); } base::FilePath temp_dir() const { return temp_dir_.GetPath(); } private: base::test::TaskEnvironment task_environment_; base::ScopedTempDir temp_dir_; }; TEST_F(FileClusteringBackendTest, NoCommandLine) { std::unique_ptr<FileClusteringBackend> backend = FileClusteringBackend::CreateIfEnabled(); EXPECT_EQ(backend, nullptr); } TEST_F(FileClusteringBackendTest, EmptyCommandLine) { base::CommandLine::ForCurrentProcess()->AppendSwitch( switches::kClustersOverrideFile); std::unique_ptr<FileClusteringBackend> backend = FileClusteringBackend::CreateIfEnabled(); EXPECT_EQ(backend, nullptr); } TEST_F(FileClusteringBackendTest, Success) { std::string clusters_json_string = R"( { "clusters": [ { "visits": [ { "visitId": "1", "score": 0.5 }, { "visitId": "2", "score": 0.3 } ] }, { "visits": [ { "visitId": "3", "score": 0.5, "duplicateVisitIds": ["10", "11"], "imageUrl": "https://publicimage.com/image.jpg" }, { "score": 0.5 }, { "visitId": "10" }, { "visitId": "4", "score": 0.4 } ] }, { "visits": [ { "visitId": "35", "score": 0.5 }, { "visitId": "36", "score": 0.4 } ] } ] })"; base::FilePath file_path = temp_dir().Append(FILE_PATH_LITERAL("clusters.json")); ASSERT_TRUE(base::WriteFile(file_path, clusters_json_string)); base::CommandLine::ForCurrentProcess()->AppendSwitchPath( switches::kClustersOverrideFile, file_path); std::unique_ptr<FileClusteringBackend> backend = FileClusteringBackend::CreateIfEnabled(); ASSERT_NE(backend, nullptr); std::vector<history::AnnotatedVisit> annotated_visits; history::AnnotatedVisit visit = testing::CreateDefaultAnnotatedVisit(1, GURL("https://www.google.com/")); annotated_visits.push_back(visit); history::AnnotatedVisit visit2 = testing::CreateDefaultAnnotatedVisit(2, GURL("https://bar.com/")); annotated_visits.push_back(visit2); history::AnnotatedVisit visit3 = testing::CreateDefaultAnnotatedVisit(3, GURL("https://foo.com/")); annotated_visits.push_back(visit3); history::AnnotatedVisit visit10 = testing::CreateDefaultAnnotatedVisit(10, GURL("https://foo.com/")); annotated_visits.push_back(visit10); base::RunLoop run_loop; std::vector<history::Cluster> result_clusters; backend->GetClusters(ClusteringRequestSource::kJourneysPage, base::BindOnce( [](base::RunLoop* run_loop, std::vector<history::Cluster>* out_clusters, std::vector<history::Cluster> clusters) { *out_clusters = std::move(clusters); run_loop->Quit(); }, &run_loop, &result_clusters), annotated_visits, /*unused_requires_ui_and_triggerability=*/true); run_loop.Run(); EXPECT_THAT(testing::ToVisitResults(result_clusters), ElementsAre(ElementsAre(testing::VisitResult(1, 0.5), testing::VisitResult(2, 0.3)), ElementsAre(testing::VisitResult( 3, 0.5, {history::DuplicateClusterVisit{10}})))); // Make sure visit URLs have URLs for display. for (const auto& result_cluster : result_clusters) { for (const auto& result_visit : result_cluster.visits) { EXPECT_FALSE(result_visit.url_for_display.empty()); } } // Make sure image URL was parsed. EXPECT_EQ(result_clusters[1].visits[0].image_url.possibly_invalid_spec(), "https://publicimage.com/image.jpg"); } } // namespace } // namespace history_clusters
4962dc3d0c5901158c6191aba25f39459270d622
2f64ba43d5dc6142c02aadf4bc2a34f81e0e226c
/day2/b/gen.cpp
774541ac8c2a40d7bc8cb994336a46581cdbc537
[]
no_license
cppascalinux/guangzhoujixun
e4ae73f032548835e22a5a4ff344a43a1454968b
a06ed0a10db5cd1f7fd335ea8b23ba3c6e5c7cdd
refs/heads/master
2020-06-05T01:43:10.535027
2019-07-15T08:39:51
2019-07-15T08:39:51
192,269,274
0
0
null
null
null
null
UTF-8
C++
false
false
675
cpp
#include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #include<random> using namespace std; int s[10009]; random_device sd; mt19937 rnd(sd()); void build(int l,int r) { if(l==r) return; int p=l; printf("%d ",p); build(l,p); build(p+1,r); } int main() { freopen("b.in","w",stdout); int n=10000,m=100000; printf("%d %d\n",n,m); build(1,n); printf("\n"); for(int i=2;i<=2*n-1;i++) printf("%d %d\n",i,(int)(rnd()%(i-1)+1)); for(int i=1;i<=m;i++) { int a=rnd()%n+1,b=rnd()%n+1,c,d; if(rnd()&1) c=1,d=rnd()%n+1; else c=rnd()%n+1,d=n; if(a>b) swap(a,b); if(c>d) swap(c,d); printf("%d %d %d %d\n",a,b,c,d); } return 0; }
c897e4264b37ff28b03cdc58385c3aa31afb317f
20a09e80a6fabab0ba9c7a821b73b726bb79666a
/src/indexer/indexer.h
0451c672ec908f8d2f560b1662444039b6d62f80
[ "MIT" ]
permissive
j5land/cloriSearch
daaca077ce24351779f0fd82da58bcae48d54dd7
ba113ba193cd24f6fa1fbfa7b16a5f52a240e6cd
refs/heads/master
2020-12-19T13:39:41.148981
2018-12-29T15:40:59
2018-12-29T15:40:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
909
h
// // indexer main class definition // version: 1.0 // Copyright (C) 2018 James Wei ([email protected]). All rights reserved // #ifndef CLORIS_INDEXER_H_ #define CLORIS_INDEXER_H_ #include <list> #include "inverted_index.pb.h" #include "posting_list.h" #include "term.h" namespace cloris { class Indexer { public: Indexer(const std::string& name) : name_(name) {} virtual ~Indexer() { } virtual bool ParseTermsFromConjValue(std::vector<Term>& terms, const ConjValue& value) = 0; virtual bool Add(const ConjValue& value, bool is_belong_to, int docid, bool is_incremental) = 0; virtual std::list<DocidNode>* GetPostingLists(const Term& term) = 0; const ReclaimHandler& reclaim_handler() const { return reclaim_handler_; } protected: std::string name_; ValueType type_; ReclaimHandler reclaim_handler_; private: }; } // namespace cloris #endif // CLORIS_INDEXER_H_
7fcedf5112914d3d02c185e226433f78134406c8
04251e142abab46720229970dab4f7060456d361
/lib/rosetta/source/src/core/select/residue_selector/ResidueNameSelector.hh
c19eebeb73fe9350d0a8582c7e85a4a4862c5c4f
[]
no_license
sailfish009/binding_affinity_calculator
216257449a627d196709f9743ca58d8764043f12
7af9ce221519e373aa823dadc2005de7a377670d
refs/heads/master
2022-12-29T11:15:45.164881
2020-10-22T09:35:32
2020-10-22T09:35:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,430
hh
// -*- mode:c++;tab-width:2;indent-tabs-mode:t;show-trailing-whitespace:t;rm-trailing-spaces:t -*- // vi: set ts=2 noet: // // (c) Copyright Rosetta Commons Member Institutions. // (c) This file is part of the Rosetta software suite and is made available under license. // (c) The Rosetta software is developed by the contributing members of the Rosetta Commons. // (c) For more information, see http://www.rosettacommons.org. Questions about this can be // (c) addressed to University of Washington CoMotion, email: [email protected]. /// @file core/select/residue_selector/ResidueNameSelector.hh /// @brief The ResidueNameSelector selects residues using a string containing residue names /// @author Tom Linsky ([email protected])) #ifndef INCLUDED_core_select_residue_selector_ResidueNameSelector_HH #define INCLUDED_core_select_residue_selector_ResidueNameSelector_HH // Unit headers #include <core/select/residue_selector/ResidueNameSelector.fwd.hh> // Package headers #include <core/types.hh> #include <core/select/residue_selector/ResidueSelector.hh> #include <core/pose/Pose.fwd.hh> // Utility Headers #include <utility/tag/Tag.fwd.hh> #include <utility/tag/XMLSchemaGeneration.fwd.hh> #include <utility/vector1.hh> // C++ headers #include <set> #ifdef SERIALIZATION // Cereal headers #include <cereal/types/polymorphic.fwd.hpp> #endif // SERIALIZATION namespace core { namespace select { namespace residue_selector { /// @brief The ResidueNameSelector returns a ResidueSubset, i.e. a utility::vector1< bool > containing /// 'true' for residue positions which match the given residue index. The index is read as comma-separated /// list of either Rosetta indices (e.g. 10) or PDB numbers (e.g. 10A, residue 10 of chain A). Detection /// and mapping from PDB to Rosetta residue numbers is done internally. class ResidueNameSelector : public ResidueSelector { public: // derived from base class ResidueNameSelector(); /// @brief Copy constructor ResidueNameSelector( ResidueNameSelector const &src); ResidueNameSelector( std::string const & res_name_str ); ResidueNameSelector( std::string const & res_name3_str, bool dummy ); ~ResidueNameSelector() override; /// @brief Clone operator. /// @details Copy this object and return an owning pointer to the new object. ResidueSelectorOP clone() const override; ResidueSubset apply( core::pose::Pose const & pose ) const override; void parse_my_tag( utility::tag::TagCOP tag, basic::datacache::DataMap & ) override; std::string get_name() const override; static std::string class_name(); //unit-specific /// @brief sets the comma-separated string of residue names to be selected void set_residue_names( std::string const & res_name_str ); /// @brief sets the comma-separated string of 3-character residue names to be selected void set_residue_name3( std::string const & res_name3_str ); static void provide_xml_schema( utility::tag::XMLSchemaDefinition & xsd ); private: // data members std::string res_name_str_; std::string res_name3_str_; #ifdef SERIALIZATION public: template< class Archive > void save( Archive & arc ) const; template< class Archive > void load( Archive & arc ); #endif // SERIALIZATION }; } //namespace residue_selector } //namespace select } //namespace core #ifdef SERIALIZATION CEREAL_FORCE_DYNAMIC_INIT( core_pack_task_residue_selector_ResidueNameSelector ) #endif // SERIALIZATION #endif
517524a7310ee127d8daf75524fe7b8879e80435
3c6faf45fa2a2c1daa7b3a56c507bcc0273b3463
/Source/BattleOfShips/BattleOfShipsGameModeBase.h
1ed06dccc1d8a5c16d991e63d2ec5c351c4080db
[]
no_license
wangyars/BattleOfShips
fd396d10b19b2afce4f65a6b9943cc659f0f8749
278e0e4c72a4cb27da07803f0ab4a80ab55d4e09
refs/heads/master
2020-06-14T19:32:04.270182
2016-12-02T02:41:36
2016-12-02T02:41:36
75,353,698
1
0
null
null
null
null
UTF-8
C++
false
false
310
h
// Fill out your copyright notice in the Description page of Project Settings. #pragma once #include "GameFramework/GameModeBase.h" #include "BattleOfShipsGameModeBase.generated.h" /** * */ UCLASS() class BATTLEOFSHIPS_API ABattleOfShipsGameModeBase : public AGameModeBase { GENERATED_BODY() };
5f56f57452dfaf4c5434e438646721344fc3ad09
8687a237b885bb7a116410491e48c35d444745b5
/c++/primer_plus_s_pratt/ch_9/pr_ex4/app.cpp
295340827cd5ad0cec0f951ce55518633ed3e15b
[ "MIT" ]
permissive
dinimar/Projects
150b3d95247c738ca9a5ce6b2ec1ed9cee30b415
7606c23c4e55d6f0c03692b4a1d2bb5b42f10992
refs/heads/master
2021-06-11T20:34:29.081266
2021-05-15T19:22:36
2021-05-15T19:22:36
183,491,754
0
0
MIT
2019-04-25T18:47:39
2019-04-25T18:47:39
null
UTF-8
C++
false
false
263
cpp
#ifndef SALES_H #define SALES_H #include "sales.h" #endif using namespace SALES; int main(int argc, char const *argv[]) { double ar[4] = {0, 1, 2, 3}; Sales s1; Sales s2; setSales(s1, ar, 3); showSales(s1); setSales(s2); showSales(s2); return 0; }
b63940f55c078538e05e57fc8a4adb3df90aeb25
44ab57520bb1a9b48045cb1ee9baee8816b44a5b
/EngineTesting/Code/Mathematics/MathematicsTesting/MeshesSuite/TriangleKeyTesting.cpp
7c80863e75fbd56ad2b70228b1c0ae2746265156
[ "BSD-3-Clause" ]
permissive
WuyangPeng/Engine
d5d81fd4ec18795679ce99552ab9809f3b205409
738fde5660449e87ccd4f4878f7bf2a443ae9f1f
refs/heads/master
2023-08-17T17:01:41.765963
2023-08-16T07:27:05
2023-08-16T07:27:05
246,266,843
10
0
null
null
null
null
GB18030
C++
false
false
2,179
cpp
/// Copyright (c) 2010-2023 /// Threading Core Render Engine /// /// 作者:彭武阳,彭晔恩,彭晔泽 /// 联系作者:[email protected] /// /// 标准:std:c++20 /// 引擎测试版本:0.9.0.12 (2023/06/09 15:55) #include "TriangleKeyTesting.h" #include "CoreTools/Helper/AssertMacro.h" #include "CoreTools/Helper/ClassInvariant/MathematicsClassInvariantMacro.h" #include "CoreTools/UnitTestSuite/UnitTestDetail.h" #include "Mathematics/Meshes/TriangleKey.h" Mathematics::TriangleKeyTesting::TriangleKeyTesting(const OStreamShared& streamShared) : ParentType{ streamShared } { MATHEMATICS_SELF_CLASS_IS_VALID_1; } CLASS_INVARIANT_PARENT_IS_VALID_DEFINE(Mathematics, TriangleKeyTesting) void Mathematics::TriangleKeyTesting::DoRunUnitTest() { ASSERT_NOT_THROW_EXCEPTION_0(MainTest); } void Mathematics::TriangleKeyTesting::MainTest() { ASSERT_NOT_THROW_EXCEPTION_0(KeyTest); } void Mathematics::TriangleKeyTesting::KeyTest() { const TriangleKey firstTriangleKey(5, 4, 6); ASSERT_EQUAL(firstTriangleKey.GetKey(0), 4); ASSERT_EQUAL(firstTriangleKey.GetKey(1), 6); ASSERT_EQUAL(firstTriangleKey.GetKey(2), 5); const TriangleKey secondTriangleKey(5, 14, 18); ASSERT_EQUAL(secondTriangleKey.GetKey(0), 5); ASSERT_EQUAL(secondTriangleKey.GetKey(1), 14); ASSERT_EQUAL(secondTriangleKey.GetKey(2), 18); const TriangleKey thirdTriangleKey(5, 14, 1); ASSERT_EQUAL(thirdTriangleKey.GetKey(0), 1); ASSERT_EQUAL(thirdTriangleKey.GetKey(1), 5); ASSERT_EQUAL(thirdTriangleKey.GetKey(2), 14); const TriangleKey fourthTriangleKey(15, 14, 1); ASSERT_EQUAL(fourthTriangleKey.GetKey(0), 1); ASSERT_EQUAL(fourthTriangleKey.GetKey(1), 15); ASSERT_EQUAL(fourthTriangleKey.GetKey(2), 14); const TriangleKey fifthTriangleKey(15, 2, 13); ASSERT_EQUAL(fifthTriangleKey.GetKey(0), 2); ASSERT_EQUAL(fifthTriangleKey.GetKey(1), 13); ASSERT_EQUAL(fifthTriangleKey.GetKey(2), 15); const TriangleKey sixthTriangleKey(1, 112, 13); ASSERT_EQUAL(sixthTriangleKey.GetKey(0), 1); ASSERT_EQUAL(sixthTriangleKey.GetKey(1), 112); ASSERT_EQUAL(sixthTriangleKey.GetKey(2), 13); }
55deac4ee8b47ad5a286e5a0dbe76622c36fb944
947cb6c70634ae9004eddbd4687b69288e663321
/projCompiladores/projCompiladores/SyntacticAnalyzer.cpp
3fb14e2519c8303a5ae30adc1f3bc93ae132b397
[]
no_license
jdmaia/projCompiladoresMaisNovo
08d0260fca165122dbb7219541462a0388bb9a8c
4e2b367853bd94b08d72a9e2d2fbc89afb563ee0
refs/heads/master
2021-05-28T16:28:49.213346
2014-06-29T20:08:20
2014-06-29T20:08:20
null
0
0
null
null
null
null
ISO-8859-1
C++
false
false
20,050
cpp
#include <cstring> #include <fstream> #include <string> #include "SyntacticAnalyzer.h" #include <iostream> using namespace std; /* Funcoes de Classe */ SyntacticAnalyzer::SyntacticAnalyzer(string filename){ ifstream *file = new ifstream(filename.c_str()); string leitura; tokens = new vector<string>(); classes = new vector<string>(); linhas = new vector<string>(); /* Leitura de Cabeçalho */ getline(*file, leitura); getline(*file, leitura); //getline(*file, leitura); /* Leitura de Arquivo */ getline(*file, leitura); while (!file->eof()){ char *token; char *str = new char[leitura.length()]; strcpy(str,leitura.c_str()); token = strtok(str, " "); string tok(token); tokens->push_back(tok); token = strtok(NULL, " "); string cla(token); classes->push_back(cla); tok = strtok(NULL, " "); string lin(tok); linhas->push_back(lin); getline(*file, leitura); } /* Adição de um elemento final ao array para caso de segurança (não é bom correr o risco de chegar no fim do array e tomar uma falha de segmentação */ tokens->push_back("1"); classes->push_back("Neutro"); linhas->push_back("0"); file->close(); } SyntacticAnalyzer::~SyntacticAnalyzer(){ delete tokens; delete classes; delete linhas; } /* Funcoes de Leitura */ string SyntacticAnalyzer::getToken(int index){ return tokens->at(index); } string SyntacticAnalyzer::getClass(int index){ return classes->at(index); } string SyntacticAnalyzer::getLinha(int index){ return linhas->at(index); } /* Funcoes de Sintaxe */ void SyntacticAnalyzer::analyze(){ int index = 0; index = programa(index); string classeLida, linhaLida; classeLida = getClass(index); linhaLida = getLinha(index); if (classeLida.compare("Neutro")){ /* Significa que tem código após o ponto "." */ cout << "ERRO: " << linhaLida << " Não deve haver código após o delimitador ponto '.' para final de programa. Pode apenas haver comentários" << endl; exit(1); } } int SyntacticAnalyzer::programa(int index){ string tokenLido, classeLida, linhaLida, linhaBuffer; tokenLido = getToken(index); linhaLida = getLinha(index); index++; if(tokenLido.compare("program")){ cout << "ERRO: " << linhaLida << " O programa precisa iniciar com a palavra-chave program " << endl; exit(1); } tokenLido = getToken(index); classeLida = getClass(index); index++; if(classeLida.compare("Identificador")){ cout << "ERRO: "<< linhaLida << " Depois da palavra-chave program, deve haver um identificador" << endl; exit(1); } tokenLido = getToken(index); index++; if(tokenLido.compare(";")){ cout << "ERRO: " << linhaLida << " Faltando o ;" << endl; exit(1); } index = declaracoes_variaveis(index); index = declaracoes_de_subprogramas(index); index = comando_composto(index); tokenLido = getToken(index); index++; if (tokenLido.compare(".")){ cout << "ERRO: " << linhaLida << " Faltando o ." << endl; exit(1); } return index; } int SyntacticAnalyzer::declaracoes_variaveis(int index){ string tokenLido, classeLida, linhaLida, linhaBuffer; tokenLido = getToken(index); if(!tokenLido.compare("var")){ index++; index = lista_declaracoes_variaveis(index); return index; } return index; } int SyntacticAnalyzer::lista_declaracoes_variaveis(int index){ string tokenLido, classeLida, linhaLida; index = lista_de_identificadores(index); linhaLida = getLinha(index); tokenLido = getToken(index); index++; if(tokenLido.compare(":")){ cout <<"ERRO: " << linhaLida << " Necessario ':' após lista de declaracoes de variaveis" << endl; exit(1); } /*linhaLida = getLinha(index); tokenLido = getToken(index); classeLida = getClass(index); index++; if(classeLida.compare("Inteiro") && classeLida.compare("Real") && classeLida.compare("Booleano")){ cout <<"ERRO: " << linhaLida << " Necessario tipo após lista de variaveis" << endl; exit(1); }*/ index = tipo(index); linhaLida = getLinha(index); tokenLido = getToken(index); classeLida = getClass(index); index++; if(tokenLido.compare(";")){ cout <<"ERRO: " << linhaLida << " Esperado ';' " << endl; exit(1); } index = lista_declaracoes_variaveis_auxiliar(index); return index; } int SyntacticAnalyzer::lista_declaracoes_variaveis_auxiliar(int index){ string tokenLido, classeLida, linhaLida; linhaLida = getLinha(index); tokenLido = getToken(index); classeLida = getClass(index); //index++; if(!classeLida.compare("Identificador")){ index = lista_de_identificadores(index); tokenLido = getToken(index); index++; if(!tokenLido.compare(":")){ index = tipo(index); tokenLido = getToken(index); index++; if(!tokenLido.compare(";")){ index = lista_declaracoes_variaveis_auxiliar(index); return index; }else { cout <<"ERRO: " << linhaLida << " Esperado ';' " << endl; exit(1); } }else{ cout <<"ERRO: " << linhaLida << " Esperado ':' " << endl; exit(1); } } return index; } int SyntacticAnalyzer::lista_de_identificadores(int index){ string tokenLido, classeLida, linhaLida; linhaLida = getLinha(index); tokenLido = getToken(index); classeLida = getClass(index); index++; if(classeLida.compare("Identificador")){ cout << "ERRO: "<< linhaLida << " Esperado um identificador" << endl; exit(1); } index = lista_de_identificadores_auxiliar(index); return index; } int SyntacticAnalyzer::lista_de_identificadores_auxiliar(int index){ string tokenLido, classeLida, linhaLida; linhaLida = getLinha(index); tokenLido = getToken(index); classeLida = getClass(index); if(!tokenLido.compare(",")){ index++; linhaLida = getLinha(index); tokenLido = getToken(index); classeLida = getClass(index); index++; if(!classeLida.compare("Identificador")){ index = lista_de_identificadores_auxiliar(index); return index; }else{ cout << "ERRO: "<< linhaLida << " Esperado um identificador" << endl; exit(1); } } return index; } int SyntacticAnalyzer::tipo(int index){ string tokenLido, classeLida, linhaLida; linhaLida = getLinha(index); tokenLido = getToken(index); classeLida = getClass(index); index++; if(tokenLido.compare("integer") && tokenLido.compare("real") && tokenLido.compare("boolean")){ cout <<"ERRO: " << linhaLida << " Type expected" << endl; exit(1); } return index; } int SyntacticAnalyzer::declaracoes_de_subprogramas(int index){ string tokenLido, classeLida, linhaLida; index = declaracoes_de_subprogramas_auxiliar(index); return index; } int SyntacticAnalyzer::declaracoes_de_subprogramas_auxiliar(int index){ string tokenLido, classeLida, linhaLida; //Tenho que verificar se comeca com procedure tokenLido = getToken(index); if(!tokenLido.compare("procedure")){ index = declaracao_de_subprograma(index); tokenLido = getToken(index); classeLida = getClass(index); index++; if(tokenLido.compare(";")){ cout <<"ERRO: " << linhaLida << " Esperado ';' " << endl; exit(1); } index = declaracoes_de_subprogramas_auxiliar(index); } return index; } int SyntacticAnalyzer::declaracao_de_subprograma(int index){ string tokenLido, classeLida, linhaLida; linhaLida = getLinha(index); tokenLido = getToken(index); classeLida = getClass(index); index++; if(tokenLido.compare("procedure")){ cout <<"ERRO: " << linhaLida << " Esperado 'procedure' " << endl; exit(1); } linhaLida = getLinha(index); tokenLido = getToken(index); classeLida = getClass(index); index++; if(classeLida.compare("Identificador")){ cout <<"ERRO: " << linhaLida << " Esperado identificador " << endl; exit(1); } index = argumentos(index); tokenLido = getToken(index); index++; if(tokenLido.compare(";")){ cout <<"ERRO: " << linhaLida << " Esperado ';' " << endl; exit(1); } index = declaracoes_variaveis(index); index = declaracoes_de_subprogramas(index); index = comando_composto(index); return index; } int SyntacticAnalyzer::argumentos(int index){ string tokenLido, classeLida, linhaLida; linhaLida = getLinha(index); tokenLido = getToken(index); classeLida = getClass(index); index++; if(!tokenLido.compare("(")){ index = lista_de_parametros(index); linhaLida = getLinha(index); tokenLido = getToken(index); classeLida = getClass(index); index++; if(tokenLido.compare(")")){ cout <<"ERRO: " << linhaLida << " Esperado ')' " << endl; exit(1); } return index; }else return index; } int SyntacticAnalyzer::lista_de_parametros(int index){ string tokenLido, classeLida, linhaLida; index = lista_de_identificadores(index); tokenLido = getToken(index); index++; if(tokenLido.compare(":")){ cout <<"ERRO: " << linhaLida << " Esperado ':' " << endl; exit(1); } index = tipo(index); index = lista_de_parametros_auxiliar(index); return index; } int SyntacticAnalyzer::lista_de_parametros_auxiliar(int index){ string tokenLido, classeLida, linhaLida; linhaLida = getLinha(index); tokenLido = getToken(index); classeLida = getClass(index); if(!tokenLido.compare(";")){ index++; index = lista_de_identificadores(index); tokenLido = getToken(index); index++; if(tokenLido.compare(":")){ cout <<"ERRO: " << linhaLida << " Esperado ':' " << endl; exit(1); } index = tipo(index); index = lista_de_parametros_auxiliar(index); return index; }else{ return index; } } int SyntacticAnalyzer::comando_composto(int index){ string tokenLido, classeLida, linhaLida; linhaLida = getLinha(index); tokenLido = getToken(index); classeLida = getClass(index); index++; if(tokenLido.compare("begin")){ cout <<"ERRO: " << linhaLida << " Esperado 'begin' " << endl; exit(1); } index = comandos_opcionais(index); tokenLido = getToken(index); index++; if(tokenLido.compare("end")){ cout <<"ERRO: " << linhaLida << " Esperado 'end' " << endl; exit(1); } return index; } int SyntacticAnalyzer::comandos_opcionais(int index){ string tokenLido, classeLida, linhaLida; tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); if (classeLida.compare("Identificador") && tokenLido.compare("begin") && tokenLido.compare("if") && tokenLido.compare("while")){ /* Significa que é vazio */ return index; } index = lista_de_comandos(index); return index; } int SyntacticAnalyzer::lista_de_comandos(int index){ index = comando(index); index = lista_de_comandos_auxiliar(index); return index; } int SyntacticAnalyzer::lista_de_comandos_auxiliar(int index){ string tokenLido, classeLida, linhaLida; tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); if (tokenLido.compare(";")){ /* Significa que é vazio */ return index; } index++; index = comando(index); index = lista_de_comandos_auxiliar(index); return index; } int SyntacticAnalyzer::comando(int index){ string tokenLido, classeLida, linhaLida; tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); if (!classeLida.compare("Identificador")){ /* Significa que é um identificador */ index++; tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); if (tokenLido.compare(":=")){ /* Significa que é ativação de procedimento */ index = ativacao_de_procedimentos(index); return index; } index++; index = expressao(index); return index; } if (!tokenLido.compare("begin")){ /* Significa que é comando composto */ index = comando_composto(index); return index; } if (!tokenLido.compare("if")){ index++; index = expressao(index); tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); if (tokenLido.compare("then")){ /* Significa que está faltando then */ cout << "ERRO: " << linhaLida << " Comando if exige then após expressão" << endl; exit(1); } index++; index = comando(index); index = parte_else(index); return index; } if (!tokenLido.compare("while")){ index++; index = expressao(index); tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); if (tokenLido.compare("do")){ /* Significa que está faltando do */ cout << "ERRO: " << linhaLida << " Comando while exige do após expressão" << endl; exit(1); } index++; index = comando(index); return index; } /* Significa que não é um comando */ cout << "ERRO: " << linhaLida << " Esperado um comando" << endl; exit(1); } int SyntacticAnalyzer::parte_else(int index){ string tokenLido, classeLida, linhaLida; tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); if (tokenLido.compare("else")){ /* Significa que é vazio */ return index; } index++; index = comando(index); return index; } int SyntacticAnalyzer::variavel(int index){ string tokenLido, classeLida, linhaLida; tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); index++; if (classeLida.compare("Identificador")){ /* Significa que NÃO é um identificador */ cout << "ERRO: " << linhaLida << " Esperado um identificador" << endl; exit(1); } return index; } int SyntacticAnalyzer::ativacao_de_procedimentos(int index){ string tokenLido, classeLida, linhaLida; tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); index++; if (classeLida.compare("Identificador")){ /* Significa que NÃO começou com identificador */ cout << "ERRO: " << linhaLida << " Esperado um identificador" << endl; exit(1); } tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); if (tokenLido.compare("(")){ /* Significa que é um identificador isolado */; return index; } index++; index = lista_de_expressoes(index); tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); index++; if (tokenLido.compare(")")){ /* Significa que NÃO foi fechado */ cout << "ERRO: " << linhaLida << " Parêntese aberto e não fechado" << endl; exit(1); } return index; } int SyntacticAnalyzer::lista_de_expressoes(int index){ index = expressao(index); index = lista_declaracoes_variaveis_auxiliar(index); return index; } int SyntacticAnalyzer::lista_de_expressoes_auxiliar(int index){ string tokenLido, classeLida, linhaLida; tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); if (tokenLido.compare(",")){ /* Significa que é vazio */ return index; } index++; index = expressao(index); index = lista_de_expressoes_auxiliar(index); return index; } int SyntacticAnalyzer::expressao(int index){ string tokenLido, classeLida, linhaLida; index = expressao_simples(index); tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); if (classeLida.compare("Operador_Relacional")) { /* Significa que é uma expressão simples isolada */ return index; } index = op_relacional(index); index = expressao_simples(index); return index; } int SyntacticAnalyzer::expressao_simples(int index){ string tokenLido, classeLida, linhaLida; tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); if (!tokenLido.compare("+") && !tokenLido.compare("-")){ /* Significa que começa com sinal */ index = sinal(index); } index = termo(index); index = expressao_simples_auxiliar(index); return index; } int SyntacticAnalyzer::expressao_simples_auxiliar(int index){ string tokenLido, classeLida, linhaLida; tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); if (tokenLido.compare("+") && tokenLido.compare("-") && tokenLido.compare("or")) { /* Significa que é vazio */ return index; } index = op_aditivo(index); index = termo(index); index = expressao_simples_auxiliar(index); return index; } int SyntacticAnalyzer::termo(int index){ index = fator(index); index = termo_auxiliar(index); return index; } int SyntacticAnalyzer::termo_auxiliar(int index){ string tokenLido, classeLida, linhaLida; tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); if (tokenLido.compare("*") && tokenLido.compare("/") && tokenLido.compare("and")) { /* Significa que é vazio */ return index; } /* Significa que não é vazio. Não precisa incrementar já que op_multiplicativo lerá essa mesma linha */ index = op_multiplicativo(index); index = fator(index); index = termo_auxiliar(index); return index; } int SyntacticAnalyzer::fator(int index){ string tokenLido, classeLida, linhaLida; tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); index++; if (!classeLida.compare("Identificador")){ /* Significa que inicia com Identificador */ tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); if (!tokenLido.compare("(")){ /* Significa que o parêntese foi aberto */ index++; index = lista_de_expressoes(index); tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); index++; if (tokenLido.compare(")")){ /* Significa que NÃO fechou corretamente */ cout << "ERRO: " << linhaLida << " Parêntese aberto e não fechado" << endl; exit(1); } return index; } else { /* Significa que é um identificador isolado */ return index; } } if (!classeLida.compare("Inteiro")){ return index; } if (!classeLida.compare("Real")){ return index; } if (!tokenLido.compare("true")){ return index; } if (!tokenLido.compare("false")){ return index; } if (!tokenLido.compare("(")){ index = expressao(index); tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); index++; if (tokenLido.compare(")")){ /* Significa que NÃO fechou corretamente */ cout << "ERRO: " << linhaLida << " Parêntese aberto e não fechado" << endl; exit(1); } return index; } cout << "ERRO: " << linhaLida << " Esperado um fator" << endl; exit(1); } int SyntacticAnalyzer::sinal(int index){ string tokenLido, classeLida, linhaLida; tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); index++; if (tokenLido.compare("+") && tokenLido.compare("-")) { /* Significa que não é sinal */ cout << "ERRO: " << linhaLida << " Esperado um sinal + -" << endl; exit(1); } return index; } int SyntacticAnalyzer::op_relacional(int index){ string tokenLido, classeLida, linhaLida; tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); index++; if (tokenLido.compare("=") && tokenLido.compare("<") && tokenLido.compare(">") && tokenLido.compare("<=") && tokenLido.compare(">=") && tokenLido.compare("<>")) { /* Significa que não é relacional */ cout << "ERRO: " << linhaLida << " Esperado um operador relacional = < > <= >= <>" << endl; exit(1); } return index; } int SyntacticAnalyzer::op_aditivo(int index){ string tokenLido, classeLida, linhaLida; tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); index++; if (tokenLido.compare("+") && tokenLido.compare("-") && tokenLido.compare("or")) { /* Significa que não é aditivo */ cout << "ERRO: " << linhaLida << " Esperado um operador aditivo + - or" << endl; exit(1); } return index; } int SyntacticAnalyzer::op_multiplicativo(int index){ string tokenLido, classeLida, linhaLida; tokenLido = getToken(index); classeLida = getClass(index); linhaLida = getLinha(index); index++; if (tokenLido.compare("*") && tokenLido.compare("/") && tokenLido.compare("and")) { /* Significa que não é multiplicativo */ cout << "ERRO: " << linhaLida << " Esperado um operador multiplicativo + - and" << endl; exit(1); } return index; }
cf82bb1e13c1d3855cb9d7b6d527436092b392f9
dfd47d4de1169f0a390e94a53711345918a2d8d6
/Hamza_ait_Messaoud/Map/map.cpp
9eb493541998640bf0ce3d9a9fa3ed07e2df436f
[]
no_license
CasperTI/THO78-Roborescue
b801e83ec96d1c658296a6cee7019f67aad4ac60
54e3e3711560afbeb7d6637f4e3024e9e4addd4f
refs/heads/master
2021-01-16T18:44:06.105845
2015-03-13T11:14:06
2015-03-13T11:14:06
32,157,567
0
0
null
2015-03-13T13:33:21
2015-03-13T13:33:21
null
UTF-8
C++
false
false
3,279
cpp
#include "map.h" enum ColorCode{ Nothing = 0, Wall = 1, Robot = 2, Rosbee = 3 }; struct boxColors{ QColor wall = Qt::black; QColor Nothing = Qt::white; QColor Rosbee = Qt::blue; QColor Robot = Qt::red; } boxcolors; struct toolTips{ QString Wall = "Wall"; QString Nothing = "Nothing"; QString Rosbee = "Rosbee"; QString Robot = "Robot"; } tooltips; Map::Map() { } Map::~Map() { } void Map::load(QTableWidget * table){ QString fileName = QFileDialog::getOpenFileName(); if (fileName.isEmpty()){ return; std::cout << "Fout" << std::endl; } QFile file(fileName); if (!file.open(QFile::ReadOnly | QFile::Text)) { return; std::cout << "Fout" << std::endl; } std::vector<QStringList> mm; QTextStream in(&file); while (!in.atEnd()) { mm.push_back(in.readLine().split(",")); } for(int y = 0; y < 20; y++){ for(int x = 0; x < 20; x++ ){ QTableWidgetItem *item = table->item(y, x); item->setBackgroundColor(Qt::white); int i = mm.at(y).at(x).toInt(); if(i == 0){ i = 3; }else{ i--; } item->setData(Qt::UserRole, QVariant(i)); changeColor(item); } } } void Map::save(QTableWidget * table){ QString output; for(int y = 0; y < 20; y++){ for(int x = 0; x < 20; x++ ){ QTableWidgetItem *item = table->item(y, x); output.push_back(item->data(Qt::UserRole).toString()); output.push_back(","); } output.remove(output.length()-1,1); output.append("\n"); } QString fileName = "map.txt"; QFile file(fileName); if (!file.open(QFile::WriteOnly | QFile::Text)) { return; } QTextStream out(&file); out << output; } void Map::newMap(QTableWidget * table){ for(int y = 0; y < 20; y++){ for(int x = 0; x < 20; x++ ){ if(table->item(y,x) != nullptr) table->removeCellWidget(y, x); QTableWidgetItem * item = new QTableWidgetItem; item->setToolTip("Nothing"); item->setBackgroundColor(Qt::white); item->setData(Qt::UserRole, QVariant(0)); table->setItem(y, x, item); } } } void Map::changeColor(QTableWidgetItem *item){ int c = item->data(Qt::UserRole).toInt(); QColor nextColor; QString tp; switch(c){ case ColorCode::Rosbee: nextColor = boxcolors.Nothing; c = ColorCode::Nothing; tp = tooltips.Nothing; break; case ColorCode::Nothing: nextColor = boxcolors.wall; c = ColorCode::Wall; tp = tooltips.Wall; break; case ColorCode::Wall: nextColor = boxcolors.Robot; c = ColorCode::Robot; tp = tooltips.Robot; break; case ColorCode::Robot: nextColor = boxcolors.Rosbee; c = ColorCode::Rosbee; tp = tooltips.Rosbee; break; } item->setBackgroundColor(nextColor); item->setToolTip(tp); item->setData(Qt::UserRole, QVariant(c)); }
4e053c279d86f0bb61a56ee60b4b975d111ce789
842a1c51b7342b39001cea38c4c46f1d4f6ad232
/src/Components/ProjectileEmitterComponent.h
e889f9394cf1b2a94ef122b9c12c399198a356fb
[]
no_license
D1amond/2dgameengine
2d7ece0f005dd4c1dd8c0be087878ba4296ea598
0228e115abc4764fb96529dd9eb616c7b41efd78
refs/heads/master
2020-12-28T14:19:39.296916
2020-02-13T01:46:07
2020-02-13T01:46:07
238,366,787
1
0
null
null
null
null
UTF-8
C++
false
false
577
h
#ifndef PROJECTILEEMITTERCOMPONENT_H #define PROJECTILEEMITTERCOMPONENT_H #include "../../lib/glm/glm.hpp" #include "../EntityManager.h" #include "./TransformComponent.h" class ProjectileEmitterComponent: public Component { private: TransformComponent* transform; glm::vec2 origin; int speed; int range; float angle; //radian bool loop; public: ProjectileEmitterComponent(Entity* owner, int speed, int angle, int range, bool loop); void Initialize() override; void Update(float deltaTime) override; void Render() override; }; #endif
bd9b3319d8d0f538048bd9e02f11e3fb5792fb63
ae7ec837eb954d7be7878f367aa7afb70d1a3897
/libs/lwwx/basic_list_mediator.cpp
fe653d3b0a2662391c3695caeddb31dc7be9195b
[ "MIT", "BSD-3-Clause" ]
permissive
hajokirchhoff/litwindow
0387bd1e59200eddb77784c665ba921089589026
7f574d4e80ee8339ac11c35f075857c20391c223
refs/heads/master
2022-06-18T20:15:21.475921
2016-12-28T18:16:58
2016-12-28T18:16:58
77,551,164
0
0
null
null
null
null
UTF-8
C++
false
false
1,053
cpp
#include "stdwx.h" #include "litwindow/wx/basic_list_mediator.hpp" namespace litwindow { namespace wx { wxString VirtualListCtrl::OnGetItemText( long item, long column ) const { return on_get_item_text ? on_get_item_text(item, column) : wxString(); } int VirtualListCtrl::OnGetItemColumnImage(long item, long column) const { return on_get_item_image ? on_get_item_image(item, column) : -1; } } } IMPLEMENT_DYNAMIC_CLASS(litwindow::wx::VirtualListCtrl, wxListCtrl); void litwindow::wx::VirtualListCtrl::Create( wxWindow *parent, wxWindowID id, const wxPoint &pos/*=wxDefaultPosition*/, const wxSize &size/*=wxDefaultSize*/, long style/*=wxLC_ICON*/, const wxValidator &validator/*=wxDefaultValidator*/, const wxString &name/*=wxListCtrlNameStr*/ ) { wxListCtrl::Create(parent, id, pos, size, (style& ~ (wxLC_ICON|wxLC_LIST))|wxLC_VIRTUAL|wxLC_REPORT, validator, name); } wxDEFINE_EVENT(lwEVT_GET_LAYOUT_PERSPECTIVE, wxCommandEvent); wxDEFINE_EVENT(lwEVT_SET_LAYOUT_PERSPECTIVE, wxCommandEvent);
d55746cf72859a4a1f00832bbaba08f03934fb36
358668370a91ea6dbefc52fac818677af78f7669
/homework/Week04_fireworks/src/testApp.h
179e4fea1ea0418508527566ee80b6cf7de52280
[]
no_license
jmatthewgriffis/griffis_algo2013
73efb45b53f5a76e617d1e46257acebcec07bcbb
4cd17cff9481a6c845683a0da6b531ebb6b0d049
refs/heads/master
2016-09-07T23:56:35.770684
2015-01-05T21:32:51
2015-01-05T21:32:51
12,420,109
0
0
null
null
null
null
UTF-8
C++
false
false
881
h
#pragma once #include "ofMain.h" #include "Particle.h" class testApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed(int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void windowResized(int w, int h); void dragEvent(ofDragInfo dragInfo); void gotMessage(ofMessage msg); // CHALLENGE: create a looping fireworks animation (non interactive). You will need to reset or restart particles every so often. Take a look at the last code example from class today (NoiceParticles) to see how to delete from a vector safely! // NOTE: starting from Charlie's noiseParticles example. void addParticle(ofPoint pos); vector<Particle> pList; };
db9fe9d00881628818761575be47ca0cab8cb3c8
9870e11c26c15aec3cc13bc910e711367749a7ff
/SPOJ/sp_3580.cpp
71ef8174d52a7e711ada5f90948177bad09a5090
[]
no_license
liuq901/code
56eddb81972d00f2b733121505555b7c7cbc2544
fcbfba70338d3d10bad2a4c08f59d501761c205a
refs/heads/master
2021-01-15T23:50:10.570996
2016-01-16T16:14:18
2016-01-16T16:14:18
12,918,517
1
1
null
null
null
null
UTF-8
C++
false
false
1,563
cpp
#include <cstdio> #include <cstdlib> #include <cstring> #include <cmath> #include <cctype> #include <ctime> #include <cstdarg> #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <vector> #include <list> #include <deque> #include <stack> #include <queue> #include <set> #include <map> #include <utility> #include <algorithm> #include <numeric> #include <functional> #include <bitset> #include <complex> #include <iterator> #include <memory> #define SQR(x) ((x)*(x)) using namespace std; typedef long long ll; typedef long double ld; const int inf=1061109567; const int mod=1000000007; const double eps=1e-7; const double pi=acos(-1.0); int tot,d[1010],b[1010],a[10010][2],ans[10010][2]; int main() { void bfs(int),print(int); int n,m; scanf("%d%d",&n,&m); for (int i=1;i<=m;i++) { int x,y; scanf("%d%d",&x,&y); a[i][0]=y,a[i][1]=b[x],b[x]=i; } tot=0; for (int i=1;i<=n;i++) { memset(d,0,sizeof(d)); bfs(i); print(i); } printf("%d\n",tot); for (int i=1;i<=tot;i++) printf("%d %d\n",ans[i][0],ans[i][1]); system("pause"); return(0); } int q[1010]; void bfs(int x) { int l,r; l=r=1,q[1]=x,d[1]=1; while (l<=r) { int x=q[l]; for (int i=b[x];i;i=a[i][1]) { int y=a[i][0]; if (!d[y]) q[++r]=y; d[y]=d[x]+1; } l++; } } void print(int x) { for (int i=b[x];i;i=a[i][1]) { int y=a[i][0]; if (d[y]==d[x]+1) ans[++tot][0]=x,ans[tot][1]=y; } }
765e11d62203237ee4f73ae66776bc47c16291b5
579a5aad9aabc60f4f2d245dbf1c74b704fc9a96
/src/main.cpp
f024c50eb23a7cef5594335cd13d70457fb99cfa
[]
no_license
dead-tech/A-Star-Pathfinding
c1b8d1e7521ead831d0ff0ea1e262503e890383f
2c5c5cceef1b4b2b1b2b32e9c288a95447609005
refs/heads/master
2022-11-24T14:00:27.338033
2020-07-30T16:53:55
2020-07-30T17:05:20
280,620,341
0
0
null
null
null
null
UTF-8
C++
false
false
607
cpp
#define FMT_HEADER_ONLY #include <fmt/format.h> #include "GraphGen.hpp" #include "GraphRenderer.hpp" int main() { const std::size_t graphDim = 10; Graph graph { graphDim }; GraphRenderer renderer { std::make_unique<Graph>(graph) }; while (!glfwWindowShouldClose(renderer.m_window)) { renderer.handleInput(); glClearColor(0.0f, 0.0f, 0.0f, 1.0f); glClear(GL_COLOR_BUFFER_BIT); renderer.draw(); glfwSwapBuffers(renderer.m_window); glfwPollEvents(); } renderer.cleanup(); return 0; }
8e42eadc105b613eb0da103460ccb54a352101ea
25dcf2bda9558e9621502d2575420cccf1b71b72
/clahevid.cpp
c2be7f742349f2dd01bd71aceb9af66d7f29c5e3
[]
no_license
singhsterabhi/globous
b07c6533b37caf171b11b2700a8830da34150042
c1f3341151125cb4c1ff68ea5a5b16702a4fab74
refs/heads/master
2021-03-24T13:46:03.390193
2017-07-29T11:52:10
2017-07-29T11:52:10
95,944,731
2
1
null
null
null
null
UTF-8
C++
false
false
3,703
cpp
#include "opencv2/opencv.hpp" #include "iostream" #include<string> #include <opencv2/core/core.hpp> // Basic OpenCV structures (cv::Mat) #include <opencv2/highgui/highgui.hpp> // Video write using namespace cv; using namespace std; // void GammaCorrection(Mat& src, Mat& dst, float fGamma); int main(int, char**) { cout << "abc\n"; VideoCapture cap ( "vid.MP4" ); // open the default camera cout << cap.isOpened(); // print 1 if ok if( ! cap.isOpened() ) // check if we succeeded { cout<<"-1\n"; return -1; } cout<<"\nt\n"; /* Mat edges; */ // namedWindow ( "tree" , 1 ); double frnb ( cap.get ( CV_CAP_PROP_FRAME_COUNT ) ); double fps (cap.get(CV_CAP_PROP_FPS)); std::cout << "frame count = " << frnb << endl; int i; int codec = CV_FOURCC('H', '2', '6', '4'); Mat src; cap>>src; if (src.empty()) { cerr << "ERROR! blank frame grabbed\n"; return -1; } bool isColor = (src.type() == CV_8UC3); //--- INITIALIZE VIDEOWRITER VideoWriter writer; string filename = "live_clahe.avi"; // name of the output video file cout << filename ; cout << "\n"; writer.open(filename, codec, fps, src.size(), isColor); // check if we succeeded if (!writer.isOpened()) { cerr << "Could not open the output video file for write\n"; return -1; } for(i=1;i<=frnb;i++) { Mat frame; cout << cap.read(src); cout << "\nhi\n"; if (!cap.read(src)) { cerr << "ERROR! blank frame grabbed\n"; continue; } // Mat dst(src.rows, src.cols, src.type()); //GammaCorrection(src, dst,2); cv::Mat lab_image; cv::cvtColor(src, lab_image, CV_BGR2Lab); // Extract the L channel std::vector<cv::Mat> lab_planes(3); cv::split(lab_image, lab_planes); // now we have the L image in lab_planes[0] // apply the CLAHE algorithm to the L channel cv::Ptr<cv::CLAHE> clahe = cv::createCLAHE(); clahe->setClipLimit(4); cv::Mat dst; clahe->apply(lab_planes[0], dst); // Merge the the color planes back into an Lab image dst.copyTo(lab_planes[0]); cv::merge(lab_planes, lab_image); // convert back to RGB cv::Mat image_clahe; cv::cvtColor(lab_image, image_clahe, CV_Lab2BGR); // display the results (you might also want to see lab_planes[0] before and after) writer.write(image_clahe); cout << i <<endl; if (waitKey(5) == 0) cout << "\n breaking \n"; //break; } return 0; } // void GammaCorrection(Mat& src, Mat& dst, float fGamma) // { // CV_Assert(src.data); // // accept only char type matrices // CV_Assert(src.depth() != sizeof(uchar)); // // build look up table // unsigned char lut[256]; // for (int i = 0; i < 256; i++) // { // lut[i] = saturate_cast<uchar>(pow((float)(i / 255.0), fGamma) * 255.0f); // } // dst = src.clone(); // const int channels = dst.channels(); // switch (channels) // { // case 1: // { // MatIterator_<uchar> it, end; // for (it = dst.begin<uchar>(), end = dst.end<uchar>(); it != end; it++) // //*it = pow((float)(((*it))/255.0), fGamma) * 255.0; // *it = lut[(*it)]; // break; // } // case 3: // { // MatIterator_<Vec3b> it, end; // for (it = dst.begin<Vec3b>(), end = dst.end<Vec3b>(); it != end; it++) // { // (*it)[0] = lut[((*it)[0])]; // (*it)[1] = lut[((*it)[1])]; // (*it)[2] = lut[((*it)[2])]; // } // break; // } // } // }
366b3015462c3ca9924857aff0db479859b21faf
d902ec7f2fe6a8d1ad8cc231bd4c237175879902
/api.hpp
640fbbaf9ea2db7a8f47cdb195af71946f77e87d
[]
no_license
moosingin3space/optical-iq-raspi
79252fd0055a7a711693f2ce5d5734290cabfb9d
e0b1fa188e9c2d18936ca85fe73bb0c8571fcec3
refs/heads/master
2016-09-10T00:12:12.548557
2014-09-07T04:12:09
2014-09-07T04:12:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
395
hpp
#ifndef __API_HPP #define __API_HPP #include <iostream> #include <string> #include <cmath> #include <restclient-cpp/restclient.h> #include <picojson.h> using namespace std; namespace mhacks { const string API_ROOT = "http://wirelessturnstile.mybluemix.net"; RestClient::response send_delta(int delta, string roomId); RestClient::response register_room(string roomName); } #endif
dbe7ce495a709ba2d3be385d1986a1b1df4e1c52
fef58dcd0c1434724a0a0a82e4c84ae906200289
/usages/0x52923C4710DD9907.cpp
f6766195a5bdfd2a979935ede3529b1a0fd3a3ff
[]
no_license
DottieDot/gta5-additional-nativedb-data
a8945d29a60c04dc202f180e947cbdb3e0842ace
aea92b8b66833f063f391cb86cbcf4d58e1d7da3
refs/heads/main
2023-06-14T08:09:24.230253
2021-07-11T20:43:48
2021-07-11T20:43:48
380,364,689
1
0
null
null
null
null
UTF-8
C++
false
false
458
cpp
// am_casino_peds.ysc @ L66736 void func_520(int iParam0, int iParam1, var uParam2) { int iVar0; if (INTERIOR::IS_VALID_INTERIOR(iParam1->f_9093) && INTERIOR::IS_INTERIOR_READY(iParam1->f_9093)) { if (func_15(iParam1->f_217[iParam0 /*71*/])) { iVar0 = func_521(iParam1, uParam2, iParam0); if (iVar0 != 0) { INTERIOR::FORCE_ROOM_FOR_ENTITY(iParam1->f_217[iParam0 /*71*/], iParam1->f_9093, iVar0); } } } }
8298927c4448b6fc47539213b4a3da8b1578857a
238e46a903cf7fac4f83fa8681094bf3c417d22d
/VTK/vtk_7.1.1_x64_Debug/include/vtk-7.1/vtkPerlinNoise.h
b2b85c5d404a3395e5bcd94da603705a19598196
[ "BSD-3-Clause" ]
permissive
baojunli/FastCAE
da1277f90e584084d461590a3699b941d8c4030b
a3f99f6402da564df87fcef30674ce5f44379962
refs/heads/master
2023-02-25T20:25:31.815729
2021-02-01T03:17:33
2021-02-01T03:17:33
268,390,180
1
0
BSD-3-Clause
2020-06-01T00:39:31
2020-06-01T00:39:31
null
UTF-8
C++
false
false
3,386
h
/*========================================================================= Program: Visualization Toolkit Module: vtkPerlinNoise.h Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ /** * @class vtkPerlinNoise * @brief an implicit function that implements Perlin noise * * vtkPerlinNoise computes a Perlin noise field as an implicit function. * vtkPerlinNoise is a concrete implementation of vtkImplicitFunction. * Perlin noise, originally described by Ken Perlin, is a non-periodic and * continuous noise function useful for modeling real-world objects. * * The amplitude and frequency of the noise pattern are adjustable. This * implementation of Perlin noise is derived closely from Greg Ward's version * in Graphics Gems II. * * @sa * vtkImplicitFunction */ #ifndef vtkPerlinNoise_h #define vtkPerlinNoise_h #include "vtkCommonDataModelModule.h" // For export macro #include "vtkImplicitFunction.h" class VTKCOMMONDATAMODEL_EXPORT vtkPerlinNoise : public vtkImplicitFunction { public: vtkTypeMacro(vtkPerlinNoise,vtkImplicitFunction); void PrintSelf(ostream& os, vtkIndent indent) VTK_OVERRIDE; /** * Instantiate the class. */ static vtkPerlinNoise *New(); //@{ /** * Evaluate PerlinNoise function. */ double EvaluateFunction(double x[3]) VTK_OVERRIDE; double EvaluateFunction(double x, double y, double z) {return this->vtkImplicitFunction::EvaluateFunction(x, y, z); } ; //@} /** * Evaluate PerlinNoise gradient. Currently, the method returns a 0 * gradient. */ void EvaluateGradient(double x[3], double n[3]) VTK_OVERRIDE; //@{ /** * Set/get the frequency, or physical scale, of the noise function * (higher is finer scale). The frequency can be adjusted per axis, or * the same for all axes. */ vtkSetVector3Macro(Frequency,double); vtkGetVectorMacro(Frequency,double,3); //@} //@{ /** * Set/get the phase of the noise function. This parameter can be used to * shift the noise function within space (perhaps to avoid a beat with a * noise pattern at another scale). Phase tends to repeat about every * unit, so a phase of 0.5 is a half-cycle shift. */ vtkSetVector3Macro(Phase,double); vtkGetVectorMacro(Phase,double,3); //@} //@{ /** * Set/get the amplitude of the noise function. Amplitude can be negative. * The noise function varies randomly between -|Amplitude| and |Amplitude|. * Therefore the range of values is 2*|Amplitude| large. * The initial amplitude is 1. */ vtkSetMacro(Amplitude,double); vtkGetMacro(Amplitude,double); //@} protected: vtkPerlinNoise(); ~vtkPerlinNoise() VTK_OVERRIDE {} double Frequency[3]; double Phase[3]; double Amplitude; private: vtkPerlinNoise(const vtkPerlinNoise&) VTK_DELETE_FUNCTION; void operator=(const vtkPerlinNoise&) VTK_DELETE_FUNCTION; }; #endif
[ "l”[email protected]“" ]
5465cb014bd39fc13cdb0b679499bf7d9a967cb0
6d7301f57f4ddcb0cd502843be97adf355be2843
/src/Platforms/OpenGL/PostProccessing/bloomOpenGL.h
8508c610aa7c8c0e6527919f3c72f6a26f7559bb
[ "MIT" ]
permissive
merpheus-dev/LavaEngine
1b413a32600d3eb9f8881fe7c1c21417cb0d7ebb
33fc8cab9b31a93426f5ad430ca355dd4456197a
refs/heads/master
2023-02-17T12:34:49.781884
2020-08-16T22:19:26
2020-08-16T22:19:26
231,239,338
1
1
null
null
null
null
UTF-8
C++
false
false
282
h
#pragma once #include "GLBloomPostProcess.h" namespace Lava { namespace OpenGL { class BloomFX : public GLBloomPostProcess { public: BloomFX() : GLBloomPostProcess( "Shaders/bloom.fp" ) { //m_bank->GetShader( 1 )->SetBool( "horizontal" , horizontal ); }; }; } }
ca4f4aa24ff66b6f56203f56f6e338baf9cca250
429bc8f2431bcf734225317754827c2288881c7b
/pick_objects/src/pick_objects.cpp
e12d2287679eb5b112ce35b9c37438718691fc08
[ "MIT" ]
permissive
acampos074/HomeServiceRobot
3c022e2a12d14dd0882b331e0797921cebfebe7d
a5803cbb131092a50caae4c42f69b5b780d74501
refs/heads/master
2023-02-23T04:56:00.865822
2021-01-25T06:10:11
2021-01-25T06:10:11
332,589,424
0
0
null
null
null
null
UTF-8
C++
false
false
3,061
cpp
#include <ros/ros.h> #include <move_base_msgs/MoveBaseAction.h> #include <actionlib/client/simple_action_client.h> #include "std_msgs/Bool.h" // Define a client for to send goal requests to the move_base server through a SimpleActionClient typedef actionlib::SimpleActionClient<move_base_msgs::MoveBaseAction> MoveBaseClient; // Global boolean marker state variable ros::Publisher marker_state_pub; int main(int argc, char** argv){ // Initialize the simple_navigation_goals node // TODO: edit the node name to pick_objects ros::init(argc, argv, "pick_objects"); // Create a handle for this node ros::NodeHandle n; // Define a publisher to publish std_msgs::Bool messages on the state of the marker marker_state_pub = n.advertise<std_msgs::Bool>("/pick_objects/marker_state",10); // Create boolean variable state of the marker (pickup_zone = true: the package is currently in the pick up zone) std_msgs::Bool pickup_zone; //tell the action client that we want to spin a thread by default MoveBaseClient ac("move_base", true); // Wait 5 sec for move_base action server to come up while(!ac.waitForServer(ros::Duration(5.0))){ ROS_INFO("Waiting for the move_base action server to come up"); } move_base_msgs::MoveBaseGoal goal; // set up the frame parameters // TODO: edit the frame_id to map goal.target_pose.header.frame_id = "map"; goal.target_pose.header.stamp = ros::Time::now(); // Define a position and orientation for the robot to reach // TODO: define desired pickup goal goal.target_pose.pose.position.x = 6.11; goal.target_pose.pose.position.y = -3.81; goal.target_pose.pose.orientation.w = 1.0; // Send the goal position and orientation for the robot to reach ROS_INFO("Sending goal"); ac.sendGoal(goal); // Wait an infinite time for the results ac.waitForResult(); // Check if the robot reached its goal if(ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) { ROS_INFO("The robot has reached its destination!"); ros::Duration(5.0).sleep(); // sleep for five seconds // Update the pickup_zone topic to false, so that the robot can move to the drop off zone pickup_zone.data = false; marker_state_pub.publish(pickup_zone); } else ROS_INFO("The robot failed to move for some reason"); // TODO: include an extra goal position and orientation for the robot to reached // This is the desired drop off goal goal.target_pose.pose.position.x = -5.85; goal.target_pose.pose.position.y = -5.55; goal.target_pose.pose.orientation.w = 1.0; // Send the goal position and orientation for the robot to reach ROS_INFO("Sending goal"); ac.sendGoal(goal); // Wait an infinite time for the results ac.waitForResult(); // Check if the robot reached its goal if(ac.getState() == actionlib::SimpleClientGoalState::SUCCEEDED) ROS_INFO("The robot has reached the desired drop off zone!"); else ROS_INFO("The robot failed to move for some reason"); // Handle ROS communication events ros::spin(); return 0; }
51fee9b99090154d44ba943184f012b415ca157e
634120df190b6262fccf699ac02538360fd9012d
/Develop/Game/XMyCharacterAlphaMgr.cpp
9bf0080b23757036f3e6773bf038c803166c4b84
[]
no_license
ktj007/Raiderz_Public
c906830cca5c644be384e68da205ee8abeb31369
a71421614ef5711740d154c961cbb3ba2a03f266
refs/heads/master
2021-06-08T03:37:10.065320
2016-11-28T07:50:57
2016-11-28T07:50:57
74,959,309
6
4
null
2016-11-28T09:53:49
2016-11-28T09:53:49
null
UTF-8
C++
false
false
506
cpp
#include "stdafx.h" #include "XMyCharacterAlphaMgr.h" #include "XCameraManager.h" #include "XModuleEntity.h" void XMyCharacterAlphaMgr::Check( float fCameraDist, XModuleEntity* pModuleEntity ) { if (m_bAlphaState) { if (fCameraDist >= CONST_ALPHA_DIST()) { pModuleEntity->StartFade(1.0f, CONST_FADE_TIME()); m_bAlphaState = false; } } else { if (fCameraDist < CONST_ALPHA_DIST()) { pModuleEntity->StartFade(CONST_ALPHA_VALUE(), CONST_FADE_TIME()); m_bAlphaState = true; } } }
cf840f085ad72638988322c88bcb0b7d614c8e12
19f9de1ca8b169fe3009aae26637e2cdcf810213
/HopsanCore/src/ComponentUtilities/HopsanPowerUser.cpp
10c123266f1a8429b27b3acfb77149788facc119
[ "Apache-2.0", "LicenseRef-scancode-free-unknown", "GPL-3.0-only" ]
permissive
Hopsan/hopsan
b9f5eca1da31b69ea07682bbf302dbc5fa0466ad
e93e2dc107d86efdbfef1da757880f62204b05c5
refs/heads/master
2023-06-24T01:49:34.199161
2023-06-22T18:33:10
2023-06-22T18:33:58
91,779,008
125
41
Apache-2.0
2023-06-22T18:46:25
2017-05-19T07:35:11
Mathematica
UTF-8
C++
false
false
3,438
cpp
/*----------------------------------------------------------------------------- Copyright 2017 Hopsan Group 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. The full license is available in the file LICENSE. For details about the 'Hopsan Group' or information about Authors and Contributors see the HOPSANGROUP and AUTHORS files that are located in the Hopsan source code root directory. -----------------------------------------------------------------------------*/ //$Id$ #include "ComponentUtilities/HopsanPowerUser.h" using namespace hopsan; //! @brief Help function to create components and abort safely if that fails //! @param [in] pSystem A pointer to the system in which to create the component //! @param [in] rType A string with the unique type name of the component to create //! @ingroup ComponentPowerAuthorFunctions //! @returns Pointer to created component or dummy Component* hopsan::createSafeComponent(ComponentSystem *pSystem, const HString &rType) { Component* pComp = pSystem->getHopsanEssentials()->createComponent(rType); if (pComp == 0) { pSystem->addErrorMessage("Could not create subcomponent: " + rType + " returning DummyComponent"); pComp = pSystem->getHopsanEssentials()->createComponent("DummyComponent"); pSystem->stopSimulation(); } return pComp; } //! @brief Help function that only call connect if the ports are not already connected to each other //! @param [in] pSystem The system to handle the connection //! @param [in] pPort1 The first port to connect //! @param [in] pPort2 The other port to connect //! @ingroup ComponentPowerAuthorFunctions //! @returns true if connection was OK, else false bool hopsan::smartConnect(ComponentSystem *pSystem, Port *pPort1, Port *pPort2) { // Fail if any pointer is nullptr if (!pSystem) { return false; } if (!(pPort1 && pPort2)) { pSystem->addErrorMessage("In smartConnect(): pPort1 or pPort2 is 0"); return false; } if (!pPort1->isConnectedTo(pPort2)) { return pSystem->connect(pPort1, pPort2); } return true; } //! @brief Help function that only call disconnect if the ports are connected to each other //! @param [in] pSystem The system to handle the disconnection //! @param [in] pPort1 The first port to disconnect //! @param [in] pPort2 The other port to disconnect //! @ingroup ComponentPowerAuthorFunctions //! @returns true if disconnection was OK, else false bool hopsan::smartDisconnect(ComponentSystem *pSystem, Port *pPort1, Port *pPort2) { // Fail if any pointer is nullptr if (!pSystem) { return false; } if (!(pPort1 && pPort2)) { pSystem->addErrorMessage("In smartConnect(): pPort1 or pPort2 is 0"); return false; } if (pPort1->isConnectedTo(pPort2)) { return pSystem->disconnect(pPort1, pPort2); } return true; }
2368fed0169565dbbf863f7a4ff2c9d0eba07474
88ab55311591ad5f2d9a9bc97eb839d66dccb875
/surface_mesh/data_structure/IO.h
f26ce0b0c949c95051ac6a10c8dce617925ece4b
[]
no_license
hometao/graphene
e9581ba02483ff65d3c4ef43a6721d80316e95a4
f2bc352566dde832cd49ba0e013426a63e17a90d
refs/heads/master
2020-03-12T13:00:27.755089
2018-04-23T03:10:03
2018-04-23T03:10:03
130,631,955
0
0
null
null
null
null
UTF-8
C++
false
false
2,583
h
//============================================================================= // Copyright (C) 2001-2005 by Computer Graphics Group, RWTH Aachen // Copyright (C) 2011 by Graphics & Geometry Group, Bielefeld University // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public License // as published by the Free Software Foundation, version 2. // // This library is distributed in the hope that it will be useful, but // WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. //============================================================================= #ifndef GRAPHENE_SURFACE_MESH_IO_H #define GRAPHENE_SURFACE_MESH_IO_H //== INCLUDES ================================================================= #include <string> #include "Surface_mesh.h" //== NAMESPACE ================================================================ namespace graphene { namespace surface_mesh { //============================================================================= bool read_mesh(Surface_mesh& mesh, const std::string& filename,const std::string& ext); bool read_feature(Surface_mesh& mesh, const std::string& filename); bool read_segmentation(Surface_mesh& mesh, const std::string& filename); bool read_off(Surface_mesh& mesh, const std::string& filename); bool read_obj(Surface_mesh& mesh, const std::string& filename); bool read_stl(Surface_mesh& mesh, const std::string& filename); bool read_fld(Surface_mesh& mesh, const std::string& filename); bool read_clr(Surface_mesh& mesh, const std::string& filename); bool write_mesh(const Surface_mesh& mesh, const std::string& filename); bool write_off(const Surface_mesh& mesh, const std::string& filename, const bool write_normals = false, const bool write_texcoords = false); bool write_obj(const Surface_mesh& mesh, const std::string& filename); //============================================================================= } // namespace surface_mesh } // namespace graphene //============================================================================= #endif // GRAPHENE_SURFACE_MESH_IO_H //=============================================================================
79a97abdd1874b35a84698be88ce4e98140748c2
4196f6223e897f1438ff5b03a24c0fd758cac784
/src/support/operations/mkdir.h
332729fcaa450f9a5ff4bb898542fe7ad3d48d2a
[ "MIT" ]
permissive
ivan-f-n/DHTFS
b8514f884a519c3a02177ee0c4d2876830097714
eca33ef4651a6f10188b0e888c8bae5add732cb8
refs/heads/master
2023-05-30T19:03:52.631758
2021-06-16T12:37:26
2021-06-16T12:37:26
363,394,528
5
0
null
null
null
null
UTF-8
C++
false
false
1,428
h
#ifndef __MKDIR_H_ #define __MKDIR_H_ #include "../../FSpart.h" #include "../global.h" #include "../logger.h" #include "../globalFunctions.h" using namespace std; int FSpart::mkdir(const char *path, mode_t mode) { Logger("Making directory " + string(path)); std::mutex mtx; std::unique_lock<std::mutex> lk(mtx); std::condition_variable cv; if (!inst) { inodeMap = Fuse::this_()->fi; valuePtr = Fuse::this_()->fiv; fileStr = "fileStr"; runner = Fuse::this_()->n; inst = 1; } inodeFile *i = getInodeStruct(path, runner); if (i != NULL) { return -ENOENT; } else { inodeFile *i = new inodeFile(); i->st.st_mode = S_IFDIR | 0755; i->st.st_uid = getuid(); i->st.st_gid = getgid(); i->st.st_nlink = 2; i->files.emplace_back(string(".")); i->files.emplace_back(string("..")); int inode = genInode(); changeEntry(path, inode, runner); bool s = false; runner->put( dht::InfoHash::get(to_string(inode)), *i, [&](bool success) { std::lock_guard<std::mutex> l(mtx); s = true; cv.notify_all(); }, dht::time_point::max(), true); cv.wait(lk, [&] { return s; }); if (!s) return -1; } return 0; } #endif
b1aa945633fec3727056e319042e14bf1a346fdf
32f8a5ad85b87cbf7bd031a09164a50725f49847
/Source/LuminoEngine/Source/Audio/DirectMusic/DirectMusicAudioDevice.h
4151ee10ca8cbe62d11f105ba34f3c7e23430000
[ "MIT" ]
permissive
mediabuff/Lumino
9787c588bac3a983c79199cbc168a919bb17a0f6
684be8f25631a104f5236e6131c0fcb84df8bb57
refs/heads/master
2021-05-14T17:04:46.553426
2017-12-28T14:33:47
2017-12-28T14:33:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
823
h
 #pragma once #include "../AudioDevice.h" LN_NAMESPACE_BEGIN LN_NAMESPACE_AUDIO_BEGIN namespace detail { // DirectMusic 用の AudioDevice の実装 class DirectMusicAudioDevice : public AudioDevice { public: struct ConfigData { DirectMusicMode DMInitMode; ///< DirectMusic を初期化する時の方法 HWND hWnd; ///< DirectMusic の初期化に使うウィンドウハンドル float ReverbLevel; }; public: DirectMusicAudioDevice(); virtual ~DirectMusicAudioDevice(); public: void initialize( const ConfigData& configData ); virtual AudioPlayer* createAudioPlayer(AudioStream* source, bool enable3d, SoundPlayingMode mode); virtual void update(); virtual void setMetreUnitDistance(float d); }; } // namespace detail LN_NAMESPACE_AUDIO_END LN_NAMESPACE_END
3cbd19240a22e6f82456375d985ecaddabca2d6b
c5308806060f6cf9fddf68617136134c9a043ebe
/Programme/build-Dodge_Cruasder-Desktop_Qt_5_12_6_MinGW_32_bit-Debug/ui_game.h
7dc360c4486efed8f7a4837008e5ab205e5fb4cc
[]
no_license
tikotti/PPO_G6_DODGE_CRUSADERS
15422f38b08326e41a3b0fa2d67270b25275b1b2
d4483093ee3f4fe2ee4ba34d5868547fd03e3964
refs/heads/master
2020-08-20T13:45:15.625492
2019-12-13T11:09:54
2019-12-13T11:09:54
216,029,666
0
0
null
null
null
null
UTF-8
C++
false
false
3,421
h
/******************************************************************************** ** Form generated from reading UI file 'game.ui' ** ** Created by: Qt User Interface Compiler version 5.12.6 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_GAME_H #define UI_GAME_H #include <QtCore/QVariant> #include <QtWidgets/QApplication> #include <QtWidgets/QDialog> #include <QtWidgets/QLabel> #include <QtWidgets/QPushButton> QT_BEGIN_NAMESPACE class Ui_game { public: QLabel *Hero; QPushButton *pushButton_3; QPushButton *pushButton_4; QLabel *Asteroide; QLabel *Asteroide1; QLabel *Asteroide2; QLabel *BackGroundGame; void setupUi(QDialog *game) { if (game->objectName().isEmpty()) game->setObjectName(QString::fromUtf8("game")); game->resize(720, 720); Hero = new QLabel(game); Hero->setObjectName(QString::fromUtf8("Hero")); Hero->setGeometry(QRect(0, 0, 61, 61)); Hero->setScaledContents(true); pushButton_3 = new QPushButton(game); pushButton_3->setObjectName(QString::fromUtf8("pushButton_3")); pushButton_3->setEnabled(true); pushButton_3->setGeometry(QRect(660, 680, 51, 31)); pushButton_4 = new QPushButton(game); pushButton_4->setObjectName(QString::fromUtf8("pushButton_4")); pushButton_4->setEnabled(true); pushButton_4->setGeometry(QRect(10, 680, 61, 31)); Asteroide = new QLabel(game); Asteroide->setObjectName(QString::fromUtf8("Asteroide")); Asteroide->setGeometry(QRect(30, 30, 81, 81)); Asteroide->setScaledContents(true); Asteroide1 = new QLabel(game); Asteroide1->setObjectName(QString::fromUtf8("Asteroide1")); Asteroide1->setGeometry(QRect(280, 30, 81, 81)); Asteroide1->setScaledContents(true); Asteroide2 = new QLabel(game); Asteroide2->setObjectName(QString::fromUtf8("Asteroide2")); Asteroide2->setGeometry(QRect(520, 20, 81, 81)); Asteroide2->setScaledContents(true); BackGroundGame = new QLabel(game); BackGroundGame->setObjectName(QString::fromUtf8("BackGroundGame")); BackGroundGame->setGeometry(QRect(0, 0, 721, 721)); BackGroundGame->setScaledContents(true); BackGroundGame->raise(); Asteroide2->raise(); Asteroide1->raise(); Asteroide->raise(); pushButton_3->raise(); pushButton_4->raise(); Hero->raise(); retranslateUi(game); QMetaObject::connectSlotsByName(game); } // setupUi void retranslateUi(QDialog *game) { game->setWindowTitle(QApplication::translate("game", "Dialog", nullptr)); Hero->setText(QString()); pushButton_3->setText(QApplication::translate("game", "Right", nullptr)); pushButton_4->setText(QApplication::translate("game", "Left", nullptr)); Asteroide->setText(QString()); Asteroide1->setText(QString()); Asteroide2->setText(QString()); BackGroundGame->setText(QString()); } // retranslateUi }; namespace Ui { class game: public Ui_game {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_GAME_H
3497d35fa75ab2734086edda655b13c2b883eaa0
7bfdaa5be493d8e98ff6f97be9a297e8ee98285b
/01-C++ Programing/47.cpp
f67c0ff1dbabff6812182b927d7adfadea03ecea
[]
no_license
GhulamMustafaGM/C-Programming
a21795ff9183462d41bb6916966342c4059cd2e2
4db74317e85ea883dbef173f02d937765ee2a6f5
refs/heads/master
2023-03-16T23:31:45.024962
2021-02-18T22:25:25
2021-02-18T22:25:25
194,243,282
0
0
null
null
null
null
UTF-8
C++
false
false
503
cpp
/* C++ Program - Octal to decimal conversion */ #include <iostream> #include <cmath> using namespace std; int main() { long int octnum, decnum = 0; int i = 0; cout << "\nEnter any octal number :"; cin >> octnum; while (octnum != 0) { decnum = decnum + (octnum % 10) * pow(8, i); i++; octnum = octnum / 10; } cout << "Equivalent decimal value = " << decnum; return 0; } /*output Enter any octal number :346 Equivalent decimal value = 230 */
5228cdd56f07d3b90ac2dae8d20e6ffc964cb8d4
d95f8ed0f35834814eb82f9da599c3fb4d99d165
/PortScan/PortScan.h
52175eb5b635b95be948034114e16b89f27062c4
[]
no_license
hackpascal/PortScan
a7fb3f00488e471f1a9143439e56a51189b5411f
a901d72bcee5f958ddd11e62db9399363c4f5baf
refs/heads/master
2021-01-19T17:37:52.418466
2017-04-15T09:18:56
2017-04-15T09:18:56
88,336,802
8
6
null
null
null
null
GB18030
C++
false
false
517
h
// PortScan.h : PROJECT_NAME 应用程序的主头文件 // #pragma once #ifndef __AFXWIN_H__ #error "在包含此文件之前包含“stdafx.h”以生成 PCH 文件" #endif #include "resource.h" // 主符号 // CPortScanApp: // 有关此类的实现,请参阅 PortScan.cpp // class CPortScanApp : public CWinApp { public: CPortScanApp(); ~CPortScanApp(); // 重写 public: virtual BOOL InitInstance(); // 实现 DECLARE_MESSAGE_MAP() }; extern CPortScanApp theApp;
3023b94b3ba7206a939f68b999a794ab4b763ba8
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/ProcessStatisticalInformation/UNIX_ProcessStatisticalInformation_SOLARIS.hxx
bf0af4dbee2f44df4bb7a8d455b5046985c61110
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
156
hxx
#ifdef PEGASUS_OS_SOLARIS #ifndef __UNIX_PROCESSSTATISTICALINFORMATION_PRIVATE_H #define __UNIX_PROCESSSTATISTICALINFORMATION_PRIVATE_H #endif #endif
939f692d670d2a1a0f09d84ab070402a3b851252
3fff1471c7b80ab8c56cab666e3c412c22eeac5b
/main.cpp
b70f682eb22499c3d101423c81a2d08fe78805e1
[]
no_license
SigmaDeltaTechnologiesInc/SDT-example-ble-uart-echo
23ca4b801bb2cc5f3e18f227537ca41cfa8a1480
4460835710c0e0e308225441263912fc3a5e3f4f
refs/heads/master
2020-03-28T06:02:44.374381
2018-12-11T16:10:33
2018-12-11T16:10:33
147,810,715
1
0
null
null
null
null
UTF-8
C++
false
false
5,073
cpp
/* SDT-example-ble-uart-echo * * Copyright (c) 2018 Sigma Delta Technologies Inc. * * MIT License * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, * copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following * conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ #include "mbed.h" #include "ble/BLE.h" #include "ble/services/UARTService.h" /* Serial */ #define BAUDRATE 9600 Serial serial_pc(USBTX, USBRX, BAUDRATE); /* DigitalOut */ #define LED_ON 0 #define LED_OFF 1 DigitalOut do_ledRed(LED_RED, LED_OFF); // For SDT52832B, the GPIO0 operates as an NFC function and cannot serve as LED0 DigitalOut do_ledGreen(LED_GREEN, LED_OFF); // For SDT52832B, the GPIO1 operates as an NFC function and cannot serve as LED1 DigitalOut do_ledBlue(LED_BLUE, LED_OFF); DigitalOut* pDO_led = &do_ledBlue; /* Ticker */ Ticker ticker; /* BLE */ #define BLE_DEVICE_NAME "SDT Device" BLE& ble_SDTDevice = BLE::Instance(); // you can't use this name, 'ble', because this name is already declared in UARTService.h /* UART service */ UARTService* pUartService; /* Variable */ bool b_bleConnect = false; void callbackTicker(void) { *pDO_led = !(*pDO_led); } void callbackBleDataWritten(const GattWriteCallbackParams* params) { if ((pUartService != NULL) && (params->handle == pUartService->getTXCharacteristicHandle())) { uint16_t bytesRead = params->len; const uint8_t* pBleRxBuf = params->data; ble_SDTDevice.gattServer().write(pUartService->getRXCharacteristicHandle(), pBleRxBuf, bytesRead); } } void callbackBleConnection(const Gap::ConnectionCallbackParams_t* params) { serial_pc.printf("Connected!\n"); b_bleConnect = true; ticker.attach(callbackTicker, 1); } void callbackBleDisconnection(const Gap::DisconnectionCallbackParams_t* params) { serial_pc.printf("Disconnected!\n"); serial_pc.printf("Restarting the advertising process\n\r"); b_bleConnect = false; ticker.detach(); *pDO_led = LED_ON; ble_SDTDevice.gap().startAdvertising(); } void callbackBleInitComplete(BLE::InitializationCompleteCallbackContext* params) { BLE& ble = params->ble; // 'ble' equals ble_SDTDevice declared in global ble_error_t error = params->error; // 'error' has BLE_ERROR_NONE if the initialization procedure started successfully. if (error == BLE_ERROR_NONE) { serial_pc.printf("Initialization completed successfully\n"); } else { /* In case of error, forward the error handling to onBleInitError */ serial_pc.printf("Initialization failled\n"); return; } /* Ensure that it is the default instance of BLE */ if(ble.getInstanceID() != BLE::DEFAULT_INSTANCE) { serial_pc.printf("ID of BLE instance is not DEFAULT_INSTANCE\n"); return; } /* Setup UARTService */ pUartService = new UARTService(ble); /* Setup and start advertising */ ble.gattServer().onDataWritten(callbackBleDataWritten); ble.gap().onConnection(callbackBleConnection); ble.gap().onDisconnection(callbackBleDisconnection); ble.gap().setAdvertisingType(GapAdvertisingParams::ADV_CONNECTABLE_UNDIRECTED); ble.gap().setAdvertisingInterval(1000); // Advertising interval in units of milliseconds ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::BREDR_NOT_SUPPORTED); ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::SHORTENED_LOCAL_NAME, (const uint8_t *)BLE_DEVICE_NAME, sizeof(BLE_DEVICE_NAME) - 1); ble.gap().accumulateAdvertisingPayload(GapAdvertisingData::COMPLETE_LIST_128BIT_SERVICE_IDS, (const uint8_t *)UARTServiceUUID_reversed, sizeof(UARTServiceUUID_reversed)); ble.gap().startAdvertising(); serial_pc.printf("Start advertising\n"); } int main(void) { serial_pc.printf("< Sigma Delta Technologies Inc. >\n\r"); /* Init BLE */ // ble_SDTDevice.onEventsToProcess(callbackEventsToProcess); ble_SDTDevice.init(callbackBleInitComplete); /* Check whether IC is running or not */ *pDO_led = LED_ON; while (true) { ble_SDTDevice.waitForEvent(); } return 0; }
6662a6ed42e902accc1aa1eef68b765e114dc2b0
0cc5ccce3488d47cb664635d868e73db146b4fb5
/index_tests/multi_file/static.cc
c0a7267a242af03146bb4ad2845b6faa4eae3c3d
[]
no_license
y2kbcm1/ccls
d5f2196dc91a0070e0b09ed965df930c7b281948
7923ce5ee9c7f0e65045d11cf5fa18cdda4ee3db
refs/heads/master
2020-03-23T07:06:08.233883
2018-07-17T07:52:52
2018-07-17T07:52:52
141,248,548
0
0
null
null
null
null
UTF-8
C++
false
false
1,963
cc
#include "static.h" void Buffer::CreateSharedBuffer() {} /* OUTPUT: static.h { "includes": [], "skipped_ranges": [], "usr2func": [{ "usr": 14576076421851654759, "detailed_name": "static void Buffer::CreateSharedBuffer()", "qual_name_offset": 12, "short_name": "CreateSharedBuffer", "kind": 6, "storage": 0, "declarations": ["4:15-4:33|9411323049603567600|2|1025"], "bases": [], "derived": [], "vars": [], "uses": [], "callees": [] }], "usr2type": [{ "usr": 9411323049603567600, "detailed_name": "struct Buffer {}", "qual_name_offset": 7, "short_name": "Buffer", "kind": 23, "declarations": [], "spell": "3:8-3:14|0|1|2", "extent": "3:1-5:2|0|1|0", "alias_of": 0, "bases": [], "derived": [], "types": [], "funcs": [14576076421851654759], "vars": [], "instances": [], "uses": [] }], "usr2var": [] } OUTPUT: static.cc { "includes": [{ "line": 0, "resolved_path": "&static.h" }], "skipped_ranges": [], "usr2func": [{ "usr": 14576076421851654759, "detailed_name": "void Buffer::CreateSharedBuffer()", "qual_name_offset": 5, "short_name": "CreateSharedBuffer", "kind": 6, "storage": 0, "declarations": [], "spell": "3:14-3:32|9411323049603567600|2|1026", "extent": "3:1-3:37|0|1|0", "bases": [], "derived": [], "vars": [], "uses": [], "callees": [] }], "usr2type": [{ "usr": 9411323049603567600, "detailed_name": "struct Buffer {}", "qual_name_offset": 7, "short_name": "Buffer", "kind": 23, "declarations": [], "alias_of": 0, "bases": [], "derived": [], "types": [], "funcs": [14576076421851654759], "vars": [], "instances": [], "uses": ["3:6-3:12|0|1|4"] }], "usr2var": [] } */
9de5e5e8045d40f8613e69c036369dc98f0a01bf
e4ecca96e8011e578d019e49feb5a8b17a264166
/AlgoFramework/commonUsage/algorithm.cpp
514005ed3645295e5e29b0746bf4726b0f130aa4
[]
no_license
wondron/selfSoftWare
eda189a36a82d590702601da303e68bc40f96808
e735eabe38213d6ebddd134dd22a819dbf7a7683
refs/heads/master
2023-06-27T01:05:29.568524
2021-08-05T15:00:45
2021-08-05T15:00:45
393,076,901
0
0
null
null
null
null
UTF-8
C++
false
false
20,849
cpp
#include "algorithm.h" #include "QList" #include "qline.h" #include "qdebug.h" #include "commonDef.h" #include "QFileInfo" #include "QTime" using namespace Detect; using namespace HalconCpp; Algorithm::Algorithm() { } CError Algorithm::objIsEmpty(CONSTIMG obj) { try { bool ini = obj.IsInitialized(); if (!ini) { return 1; } HObject null; HTuple number; GenEmptyObj(&null); TestEqualObj(obj, null, &number); //判定是否和空对象相等。 ini = number == 1 ? 1 : 0; return ini; } catch (...) { return CError(2, "Algorithm unexpected happened!"); } } CError Algorithm::tupleisEmpty(const HTuple& tuple) { try { HTuple Length; TupleLength(tuple, &Length); bool ini = (Length.I() == 0); return ini; } catch (...) { return CError(2, "Algorithm unexpected happened!"); } } CCircleInfo Algorithm::getAverCircle(QList<CCircleInfo> info) { CCircleInfo res; int num = 0; double totalX = 0; double totalY = 0; double totalR = 0; for (auto i : info) { totalX += i.X; totalY += i.Y; totalR += i.Radius; num ++; } res.X = totalX / num; res.Y = totalY / num; res.Radius = totalR / num; return res; } CError Algorithm::isFileExist(const QString filename) { try { QFileInfo fileCheck; fileCheck.setFile(filename); if (fileCheck.exists()) { return 0; } else { return CError(NG, QString("* %1 * is not exist").arg(filename)); } } catch (...) { return CError(UNEXCEPTION, "Algorithm::isfileExist is crashed"); } } QPointF Algorithm::getCrossPoint(qreal pX, qreal pY, qreal lX1, qreal lY1, qreal lX2, qreal lY2) { qreal lK = (lY2 - lY1) / (lX2 - lX1); qreal pK = -1 / (lK); qreal lB = lY1 - lK * lX1; qreal pB = pY - pK * pX; qreal X = (pB - lB) / (lK - pK); qreal Y = lK * X + lB; return QPointF(X, Y); } LineInfo Algorithm::getCrossInfo(qreal pX, qreal pY, const LineInfo& info) { LineInfo data = info; qreal lX1 = info.startCol; qreal lY1 = info.startRow; qreal lX2 = info.endCol; qreal lY2 = info.endRow; qreal lK = (lY2 - lY1) / (lX2 - lX1); qreal pK = -1 / (lK); qreal lB = lY1 - lK * lX1; qreal pB = pY - pK * pX; qreal X = (pB - lB) / (lK - pK); qreal Y = lK * X + lB; data.pX = pX; data.pY = pY; data.crossX = X; data.crossY = Y; data.distance = QLineF(pX, pY, X, Y).length(); return data; } const QString Algorithm::getErrDescri(cint errIndex) { QString info; switch (errIndex) { case LACKAREA: info = "lackarea"; break; case CUPOS: info = "cupos"; break; case REGIONNUM: info = "regionnum"; break; case HANSIZE: info = "hanSize"; break; case EMPTYOBJ: info = "emptyRegion"; break; default: info = "Other"; } return info; } const QString Algorithm::getErrDescri(cint errIndex, cint Pos) { QString info = QObject::tr(" "); QString pos = QObject::tr(" "); switch (Pos) { case CUTOP: pos = QObject::tr("CUTOP"); break; case CUBTM: pos = QObject::tr("CUBTM"); break; case ALTOP: pos = QObject::tr("ALTOP"); break; case ALBTM: pos = QObject::tr("ALBTM"); break; default: break; } switch (errIndex) { case LACKAREA: info = QObject::tr("lackarea"); break; case CUPOS: info = QObject::tr("cupos"); break; case REGIONNUM: info = QObject::tr("regionnum"); break; case HANSIZE: info = QObject::tr("hanSize"); break; case EMPTYOBJ: info = QObject::tr("emptyRegion"); break; case HanRegHig: info = QObject::tr("height"); break; case HanRegWidth: info = QObject::tr("width"); break; case HanRegNum: info = QObject::tr("num"); break; default: info = QObject::tr("Other"); } QString item = pos + info; return item; } void Algorithm::saveHImage(CONSTIMG region, CONSTIMG dst, const char* filepath) { try { bool empty = objIsEmpty(region); if (empty) { qDebug() << "Algorithm::saveHImage region is empty"; return ; } empty = objIsEmpty(dst); if (empty) { qDebug() << "Algorithm::saveHImage dst is empty"; return ; } HObject saveImg; HTuple Width, Height; GetImageSize(dst, &Width, &Height); RegionToBin(region, &saveImg, 255, 0, Width, Height); WriteImage(saveImg, "bmp", 0, filepath); } catch (...) { qDebug() << "Algorithm::saveHImage crashed"; } } CError Algorithm::dynThre(CONSTIMG dst, RHOBJ res, cint threVal, cint meanSize) { try { CHECKEMPIMG(dst, "Algorithm::dynThre is empty"); HObject ImageMean; MeanImage(dst, &ImageMean, meanSize, meanSize); DynThreshold(dst, ImageMean, &res, threVal, "light"); ClearObj(ImageMean); return 0; } catch (...) { return CError(UNEXCEPTION, "Algorithm::dynThre crashed!"); } } CError Algorithm::dynThre(const HObject& dst, HObject& res, cint threVal, cint meanSize, cint ligORDark) { try { CHECKEMPIMG(dst, "Algorithm::dynThre is empty"); HObject ImageMean; MeanImage(dst, &ImageMean, meanSize, meanSize); QString ligOrDk = ligORDark == 0 ? "light" : "dark"; DynThreshold(dst, ImageMean, &res, threVal, ligOrDk.toStdString().c_str()); ClearObj(ImageMean); return 0; } catch (...) { return CError(UNEXCEPTION, "Algorithm::dynThre crashed!"); } } CError Algorithm::edgeLineDtct(CONSTIMG dst, RHOBJ showLine, RHOBJ showPoints, LineInfo& resLine, cint direct, cint dtctTime, const LineInfo dtctRegion, const MeasureposPam measurePam) { try { CHECKEMPIMG(dst, "Algorithm::edgeLineDtct input image is empty!"); HObject Contour; int interval; HTuple phi, colRatio, rowRatio; HTuple Width, Height, edgeCol, edgeRow, indx; HTuple row, col, MeasureHandle, RowEdge, ColumnEdge; HTuple Amplitude, Distance, Nr, Nc, Dist; HTuple RowBegin, ColBegin, RowEnd, ColEnd; HTuple transition, pntSlct; int endCol = dtctRegion.endCol.D(); int endRow = dtctRegion.endRow.D(); int startCol = dtctRegion.startCol.D(); int startRow = dtctRegion.startRow.D(); if (direct == 1) { phi = 3.1415926 / 2; interval = (endCol - startCol) / (dtctTime - 1); colRatio = 1; rowRatio = 0; } else { phi = 0; interval = (endRow - startRow) / (dtctTime - 1); colRatio = 0; rowRatio = 1; } GetImageSize(dst, &Width, &Height); switch (measurePam.transition) { case ALLTRANS: transition = "all"; break; case POSITIVE: transition = "positive"; break; case NAGETIVE: transition = "negative"; break; default: transition = "all"; } switch (measurePam.pntSelect) { case ALL: pntSlct = "all"; break; case FIRSTPNT: pntSlct = "first"; break; case LASTPNT: pntSlct = "last"; break; default: pntSlct = "first"; break; } edgeCol = HTuple(); edgeRow = HTuple(); { HTuple end_val16 = dtctTime - 1; HTuple step_val16 = 1; for (indx = 0; indx.Continue(end_val16, step_val16); indx += step_val16) { row = startRow + ((interval * rowRatio) * indx); col = startCol + ((interval * colRatio) * indx); GenMeasureRectangle2(row, col, phi, measurePam.recLen1, measurePam.recLen2, Width, Height, "nearest_neighbor", &MeasureHandle); MeasurePos(dst, MeasureHandle, measurePam.sigma, measurePam.threshold, transition, pntSlct, &RowEdge, &ColumnEdge, &Amplitude, &Distance); edgeRow = edgeRow.TupleConcat(RowEdge); edgeCol = edgeCol.TupleConcat(ColumnEdge); } } GenContourPolygonXld(&Contour, edgeRow, edgeCol); GenCrossContourXld(&showPoints, edgeRow, edgeCol, 10, 1); FitLineContourXld(Contour, "tukey", -1, 0, 5, 2, &RowBegin, &ColBegin, &RowEnd, &ColEnd, &Nr, &Nc, &Dist); CHECKEMPTUPLE(RowBegin, "Algorithm::edgeLineDtct not get the line"); showLine = Contour; resLine.startRow = RowBegin[0]; resLine.startCol = ColBegin[0]; resLine.endRow = RowEnd[0]; resLine.endCol = ColEnd[0]; resLine.angle = (resLine.endRow.D() - resLine.startRow.D()) / (resLine.endCol.D() - resLine.startCol.D()) * 180.0 / 3.1415926; CloseMeasure(MeasureHandle); return 0; } catch (...) { return CError(UNEXCEPTION, "edgeLineDtct algorithm crashed!"); } } CError Algorithm::useGridGetRegion(CONSTIMG dst, RHOBJ resRegion, cint gridWid, cint gridHigt, cint minThre, cint eroValue, cint slctNum) { try { if (slctNum <= 0) return CError(PAMVALUE, "Algorithm useGridGetRegion:: select num shold large than 0"); CHECKEMPIMG(dst, "Algorithm::edgeLineDtct input image is empty!"); HObject RegionGrid, ImageReduced, Region; HObject RegionFillUp, RegionErosion, ConnectedRegions1; HObject ConnectedRegions, SelectedRegions; HTuple Width, Height, Area, Row; HTuple Column, Sorted; CHECKEMPIMG(dst, "Algorithm::useGridGetRegion input image is empty"); GetImageSize(dst, &Width, &Height); GenGridRegion(&RegionGrid, gridWid, gridHigt, "lines", Width, Height); ReduceDomain(dst, RegionGrid, &ImageReduced); Threshold(ImageReduced, &Region, minThre, 255); FillUp(Region, &RegionFillUp); if (eroValue > 0) ErosionCircle(RegionFillUp, &RegionFillUp, eroValue); ErosionCircle(RegionFillUp, &RegionErosion, 1); Connection(RegionErosion, &ConnectedRegions); AreaCenter(ConnectedRegions, &Area, &Row, &Column); CHECKEMPTUPLE(Column, "Algorithm::useGridGetRegion dnot get the region after threshold"); TupleSort(Area, &Sorted); SelectShape(ConnectedRegions, &SelectedRegions, "area", "and", HTuple(Sorted[(Area.TupleLength()) - slctNum]), HTuple(Sorted[(Area.TupleLength()) - 1]) + 10); Union1(SelectedRegions, &resRegion); return 0; } catch (...) { return CError(UNEXCEPTION, "Algorithm::useGridGetRegion crashed!"); } } CError Algorithm::getRegionByQuadrant(const RHOBJ dstObj, RHOBJ region, cint quadrant) { try { CHECKEMPIMG(dstObj, "Algorithm::getRegionByQuadrant dstObj is empty"); HObject detect, finalRegion; Connection(dstObj, &detect); HTuple area, row, col, rowMean, colMean; AreaCenter(detect, &area, &row, &col); TupleMean(col, &colMean); TupleMean(row, &rowMean); int row1 = 0; int row2 = 99999; int col1 = 0; int col2 = 99999; int midRow = rowMean.D(); int midCol = colMean.D(); switch (quadrant) { case 0: row2 = midRow; col1 = midCol; break; case 1: row2 = midRow; col2 = midCol; break; case 2: row1 = midRow; col2 = midCol; break; case 3: row1 = midRow; col1 = midCol; break; default: break; } GenEmptyRegion(&finalRegion); SelectShape(detect, &finalRegion, (HTuple("row").Append("column")), "and", (HTuple(row1).Append(col1)), (HTuple(row2).Append(col2))); CHECKEMPIMG(finalRegion, "Algorithm::getRegionByQuadrant slected region is empty"); AreaCenter(finalRegion, &area, &row, &col); if (area.Length() != 1) return CError(REGIONNUM, QString("Algorithm::getRegionByQuadrant slected is not 1: %1").arg(area.Length())); region = finalRegion; return 0; } catch (...) { return CError(UNEXCEPTION, "Algorithm::getRegionByQuadrant crashed!"); } } CError Algorithm::getRectByQuadrant(const QList<QRect> rects, QRect& rectInfo, cint quadrant) { if (rects.size() != 4) return CError(PAMVALUE, "Algorithm::getRectByQuadrant rects size is not 4"); float totalX = 0, totalY = 0; float meanX, meanY; for (auto rect : rects) { totalX += rect.x(); totalY += rect.y(); } meanX = totalX / 4.0; meanY = totalY / 4.0; int row1 = 0; int row2 = 99999; int col1 = 0; int col2 = 99999; int midRow = meanY; int midCol = meanX; switch (quadrant) { case 0: row2 = midRow; col1 = midCol; break; case 1: row2 = midRow; col2 = midCol; break; case 2: row1 = midRow; col2 = midCol; break; case 3: row1 = midRow; col1 = midCol; break; default: break; } for (auto rect : rects) { if (rect.y() < row2 && rect.y() > row1 && rect.x() < col2 && rect.x() > col1) rectInfo = rect; } return 0; } CError Algorithm::detectRegionExit(CONSTIMG dstObj, RHOBJ showObj, const QList<RectInfo>& inRect, QList<RectInfo>& gdRect, QList<RectInfo>& ngRect, const QPoint basePt, cint minThre, cint maxThre, const qreal percent, const QSize minSize) { try { CHECKEMPIMG(dstObj, "Algorithm::detectRegionExit dstObj empty"); int rectSize = inRect.size(); if (rectSize == 0) return CError(PAMVALUE, "Algorithm::detectRegionExit inRect is empty"); gdRect.clear(); ngRect.clear(); HTuple row, col, phi, len1, len2; HTuple row1, row2, col1, col2; HTuple area, cols, rows; HObject hRect, hReduceImg, hThreRg; GenEmptyObj(&showObj); double resRatio = 0; RectInfo info; for (auto i : inRect) { row = basePt.y() + i.YBia; col = basePt.x() + i.XBia; phi = i.phi; len1 = i.len1; len2 = i.len2; info = i; info.row = row.D(); info.col = col.D(); GenRectangle2(&hRect, row, col, phi, len1, len2); ReduceDomain(dstObj, hRect, &hReduceImg); Threshold(hReduceImg, &hThreRg, minThre, maxThre); Union2(showObj, hThreRg, &showObj); AreaCenter(hThreRg, &area, &rows, &cols); SmallestRectangle1(hThreRg, &row1, &col1, &row2, &col2); bool isOK = (minSize.width() < (col2.D() - col1.D())) && (minSize.height() < (row2.D() - row1.D())); if (objIsEmpty(hThreRg)) resRatio = 0; else resRatio = area.D() / (len1.D() * len2.D() * 4); if ((resRatio >= percent) && isOK) { gdRect.push_back(info); } else { ngRect.push_back(info); } } return 0; } catch (...) { qDebug() << "Algorithm::detectRegionExit crashed"; return CError(UNEXCEPTION, "Algorithm::detectRegionExit crashed"); } } CError Algorithm::getEdgePoint(CONSTIMG dst, RectInfo rectInfo, QList<QPointF>& pts, qreal& maxVa, const qreal sigma, const qreal maxThre) { try { CHECKEMPIMG(dst, "Algorithm::detectRegionExit dstObj empty"); HTuple hGrayList, hminY, hMaxY, hWidth, hHeight; HTuple hMeasureHandle, hFunction, hSmooth, hFirst, hAbsFirst, hSecond, hZeroCross, hYValue; HObject hRect; pts.clear(); GetImageSize(dst, &hWidth, &hHeight); hGrayList = HTuple(); GenMeasureRectangle2(rectInfo.row, rectInfo.col, rectInfo.phi, rectInfo.len1, rectInfo.len2, hWidth, hHeight, "nearest_neighbor", &hMeasureHandle); MeasureProjection(dst, hMeasureHandle, &hGrayList); //获取函数 CreateFunct1dArray(hGrayList, &hFunction); SmoothFunct1dGauss(hFunction, sigma, &hSmooth); DerivateFunct1d(hSmooth, "first", &hFirst); DerivateFunct1d(hSmooth, "second", &hSecond); //获取函数的最大值 AbsFunct1d(hFirst, &hAbsFirst); YRangeFunct1d(hAbsFirst, &hminY, &hMaxY); maxVa = hMaxY.D(); //获取二阶函数的0交点 ZeroCrossingsFunct1d(hSecond, &hZeroCross); CHECKEMPTUPLE(hZeroCross, "Algorithm::getEdgePoint hZeroCross is empty"); for (int i = 0; i < hZeroCross.Length(); i++) { GetYValueFunct1d(hFirst, HTuple(hZeroCross[i]), "constant", &hYValue); hYValue = hYValue.TupleAbs(); if (hYValue >= maxThre) pts.push_back(QPointF(hZeroCross[i].D(), hYValue.D())); } return 0; } catch (...) { qDebug() << "Algorithm::getEdgePoint crashed"; return CError(UNEXCEPTION, "Algorithm::getEdgePoint crashed"); } } CError Algorithm::genSpotArrayRegion(SDotArray& array) { try { HObject circles; HObject singCircle; int startRowNum = array.startRowIndex; int rowNum = array.rowNum; int startColNum = array.startColIndex; int colNum = array.colNum; int baseRow = array.baseRow; int rowInter = array.rowInter; int baseCol = array.baseCol; int colInter = array.colInter; int radius = array.radius; QTime times; GenEmptyObj(&circles); for ( int i = startRowNum; i < rowNum + startRowNum; i++) { for (int j = startColNum; j < colNum + startColNum; j++) { qDebug() << "row col:" << baseRow + i* rowInter << baseCol + j* colInter; GenCircle(&singCircle, baseRow + i * rowInter, baseCol + j * colInter, radius); Union2(circles, singCircle, &circles); } } array.arrayObj = circles; return 0; } catch (...) { qDebug() << "algorithm:: gencircleregion crashed"; return CError(UNEXCEPTION, "algorithm::gencircleregion crashed!"); } } CError Algorithm::metrologyLineMeasure(const HObject& dst, const MetrologyPam dtctPam, LineInfo& line, HObject& hShow, HTuple rows, HTuple cols) { try { CHECKEMPIMG(dst, "algorithm::metrologyLineMeasure dst is empty"); HTuple tMetrologyHandle, tMetroLine, tWid, tHig; GetImageSize(dst, &tWid, &tHig); CreateMetrologyModel(&tMetrologyHandle); SetMetrologyModelImageSize(tMetrologyHandle, tWid, tHig); AddMetrologyObjectLineMeasure(tMetrologyHandle, line.startRow, line.startCol, line.endRow, line.endCol, dtctPam.measureLen1, dtctPam.measureLen2, dtctPam.sigma, dtctPam.thre, HTuple(), HTuple(), &tMetroLine); QString transition, ptSlct; switch (dtctPam.transition) { case 0: transition = "all"; break; case 1: transition = "positive"; break; case 2: transition = "negative"; break; default: transition = "all"; break; } switch (dtctPam.ptSlect) { case 0: ptSlct = "all"; break; case 1: ptSlct = "first"; break; case 2: ptSlct = "last"; break; default: ptSlct = "all"; break; } SetMetrologyObjectParam(tMetrologyHandle, tMetroLine, "num_instances", dtctPam.numInstance); SetMetrologyObjectParam(tMetrologyHandle, tMetroLine, "measure_transition", "positive"); SetMetrologyObjectParam(tMetrologyHandle, tMetroLine, "min_score", dtctPam.sigma); SetMetrologyObjectParam(tMetrologyHandle, tMetroLine, "measure_select", "last"); return 0; } catch (...) { qDebug() << "Algorithm::metrologyLineMeasure crashed"; return CError(UNEXCEPTION, "Algorithm::metrologyLineMeasure crashed"); } }
0d01fc3855d28708c6e28b99f9ca1b291352e077
03e1d3d39f2f21646b0f97815f821ecd8707df88
/src/PythonPlugin/PythonExecutor.cpp
202941437ffdd1e3e39789c98bbe454dd9b5b7ce
[]
no_license
s-nakaoka/cnoid-boost-python
23d1278b6b2d28b19b8149ea0238c96547d35a23
a8e71fffbd7852f59b1bc1e7dee425aa45f7079f
refs/heads/master
2021-06-30T16:14:53.969455
2020-01-16T01:37:44
2020-01-16T01:37:44
186,990,211
0
2
null
2020-11-30T10:33:54
2019-05-16T08:54:53
C++
UTF-8
C++
false
false
15,424
cpp
/** @author Shin'ichiro Nakaoka */ #include "PythonExecutor.h" #include <cnoid/PyUtil> #include <cnoid/FileUtil> #include <cnoid/LazyCaller> #include <QThread> #include <QMutex> #include <QWaitCondition> #include <map> #include <boost/version.hpp> // Boost 1.58 #if BOOST_VERSION / 100 % 1000 == 58 #include <fstream> #endif using namespace std; using namespace cnoid; namespace filesystem = boost::filesystem; namespace { bool isDefaultModuleRefreshEnabled = false; typedef map<string, int> PathRefMap; PathRefMap additionalPythonPathRefMap; } namespace cnoid { // defined in PythonPlugin.cpp python::object getGlobalNamespace(); python::module getSysModule(); python::object getExitException(); python::module getRollbackImporterModule(); python::object getStringOutBufClass(); class PythonExecutorImpl : public QThread { public: bool isBackgroundMode; bool isRunningForeground; bool isModuleRefreshEnabled; std::function<python::object()> functionToExecScript; Qt::HANDLE threadId; mutable QMutex stateMutex; QWaitCondition stateCondition; python::object resultObject; string resultString; Signal<void()> sigFinished; string scriptDirectory; PathRefMap::iterator pathRefIter; bool hasException; string exceptionTypeName; string exceptionText; python::object exceptionType; python::object exceptionValue; python::object lastResultObject; string lastResultString; python::object lastExceptionType; python::object lastExceptionValue; string lastExceptionTypeName; string lastExceptionText; bool isTerminated; PythonExecutorImpl(); PythonExecutorImpl(const PythonExecutorImpl& org); void resetLastResultObjects(); ~PythonExecutorImpl(); PythonExecutor::State state() const; bool exec(std::function<python::object()> execScript, const string& filename); bool execMain(std::function<python::object()> execScript); virtual void run(); bool waitToFinish(double timeout); void onBackgroundExecutionFinished(); void releasePythonPathRef(); bool terminateScript(); }; } void PythonExecutor::setModuleRefreshEnabled(bool on) { isDefaultModuleRefreshEnabled = on; } PythonExecutor::PythonExecutor() { impl = new PythonExecutorImpl(); } PythonExecutorImpl::PythonExecutorImpl() { isBackgroundMode = false; isRunningForeground = false; isModuleRefreshEnabled = isDefaultModuleRefreshEnabled; hasException = false; isTerminated = false; resetLastResultObjects(); } PythonExecutor::PythonExecutor(const PythonExecutor& org) { impl = new PythonExecutorImpl(*org.impl); } PythonExecutorImpl::PythonExecutorImpl(const PythonExecutorImpl& org) { isBackgroundMode = org.isBackgroundMode; isRunningForeground = false; isModuleRefreshEnabled = isDefaultModuleRefreshEnabled; hasException = false; isTerminated = false; resetLastResultObjects(); } void PythonExecutorImpl::resetLastResultObjects() { lastResultObject = python::object(); // null lastExceptionType = python::object(); // null lastExceptionValue = python::object(); // null } PythonExecutor::~PythonExecutor() { delete impl; } PythonExecutorImpl::~PythonExecutorImpl() { if(state() == PythonExecutor::RUNNING_BACKGROUND){ if(!terminateScript()){ QThread::terminate(); wait(); } } } void PythonExecutor::setBackgroundMode(bool on) { impl->isBackgroundMode = on; } bool PythonExecutor::isBackgroundMode() const { return impl->isBackgroundMode; } PythonExecutor::State PythonExecutorImpl::state() const { PythonExecutor::State state; if(QThread::isRunning()){ state = PythonExecutor::RUNNING_BACKGROUND; } else { stateMutex.lock(); if(isRunningForeground){ state = PythonExecutor::RUNNING_FOREGROUND; } else { state = PythonExecutor::NOT_RUNNING; } stateMutex.unlock(); } return state; } PythonExecutor::State PythonExecutor::state() const { return impl->state(); } static python::object execPythonFileSub(const std::string& filename) { // Boost 1.58 #if BOOST_VERSION / 100 % 1000 == 58 // Avoid a segv with exec_file // See: https://github.com/boostorg/python/pull/15 std::ifstream t(filename.c_str()); std::stringstream buffer; buffer << t.rdbuf(); return python::exec(buffer.str().c_str(), getGlobalNamespace()); #else // default implementation return boost::python::exec_file(filename.c_str(), getGlobalNamespace()); #endif } bool PythonExecutor::execCode(const std::string& code) { return impl->exec( [=](){ return python::exec(code.c_str(), getGlobalNamespace()); }, ""); } bool PythonExecutor::execFile(const std::string& filename) { return impl->exec([=](){ return execPythonFileSub(filename); }, filename); } bool PythonExecutorImpl::exec(std::function<python::object()> execScript, const string& filename) { if(state() != PythonExecutor::NOT_RUNNING){ return false; } bool doAddPythonPath = false; pathRefIter = additionalPythonPathRefMap.end(); filesystem::path filepath; if(filename.empty()){ scriptDirectory.clear(); } else { filepath = getAbsolutePath(filesystem::path(filename)); scriptDirectory = getPathString(filepath.parent_path()); if(!scriptDirectory.empty()){ pathRefIter = additionalPythonPathRefMap.find(scriptDirectory); if(pathRefIter == additionalPythonPathRefMap.end()){ pathRefIter = additionalPythonPathRefMap.insert(PathRefMap::value_type(scriptDirectory, 1)).first; doAddPythonPath = true; } else { pathRefIter->second += 1; } } } bool result = true; { python::gil_scoped_acquire lock; // clear exception variables hasException = false; exceptionTypeName.clear(); exceptionText.clear(); exceptionType = python::object(); exceptionValue = python::object(); isTerminated = false; functionToExecScript = execScript; if(doAddPythonPath){ boost::python::list syspath = boost::python::extract<python::list>(getSysModule().attr("path")); syspath.insert(0, scriptDirectory); } if(isModuleRefreshEnabled){ getRollbackImporterModule().attr("refresh")(scriptDirectory); } if(!filename.empty()){ filesystem::path relative; if(findRelativePath(filesystem::current_path(), filepath, relative)){ getGlobalNamespace()["__file__"] = getPathString(relative); } } if(!isBackgroundMode){ stateMutex.lock(); threadId = currentThreadId(); isRunningForeground = true; stateMutex.unlock(); result = execMain(execScript); } } if(isBackgroundMode){ stateMutex.lock(); isRunningForeground = false; start(); // wait for the threadId variable to be set in the run() function. stateCondition.wait(&stateMutex); stateMutex.unlock(); } return result; } bool PythonExecutorImpl::execMain(std::function<python::object()> execScript) { bool completed = false; resultObject = python::object(); resultString.clear(); try { resultObject = execScript(); resultString = boost::python::extract<string>(boost::python::str(resultObject)); completed = true; } catch(const python::error_already_set& ex) { if(PyErr_Occurred()){ if(PyErr_ExceptionMatches(getExitException().ptr())){ PyErr_Clear(); isTerminated = true; } else { PyObject* ptype; PyObject* pvalue; PyObject* ptraceback; PyErr_Fetch(&ptype, &pvalue, &ptraceback); if(ptype){ exceptionType = boost::python::object(boost::python::handle<>(boost::python::borrowed(ptype))); exceptionTypeName = boost::python::extract<string>(boost::python::str(exceptionType)); } if(pvalue){ exceptionValue = boost::python::object(boost::python::handle<>(boost::python::borrowed(pvalue))); } // get an error message by redirecting the output of PyErr_Print() python::module sys = getSysModule(); boost::python::object stderr_ = sys.attr("stderr"); boost::python::object strout = getStringOutBufClass()(); sys.attr("stderr") = strout; PyErr_Restore(ptype, pvalue, ptraceback); PyErr_Print(); sys.attr("stderr") = stderr_; exceptionText = boost::python::extract<string>(strout.attr("text")()); resultObject = exceptionValue; resultString = exceptionText; hasException = true; } } } releasePythonPathRef(); stateMutex.lock(); isRunningForeground = false; lastResultObject = resultObject; lastResultString = resultString; lastExceptionType = exceptionType; lastExceptionValue = exceptionValue; lastExceptionTypeName = exceptionTypeName; lastExceptionText = exceptionText; stateCondition.wakeAll(); stateMutex.unlock(); if(QThread::isRunning()){ callLater([&](){ onBackgroundExecutionFinished(); }); } else { sigFinished(); } return completed; } void PythonExecutorImpl::run() { stateMutex.lock(); threadId = currentThreadId(); stateCondition.wakeAll(); stateMutex.unlock(); python::gil_scoped_acquire lock; execMain(functionToExecScript); } bool PythonExecutor::waitToFinish(double timeout) { return impl->waitToFinish(timeout); } bool PythonExecutorImpl::waitToFinish(double timeout) { unsigned long time = (timeout == 0.0) ? ULONG_MAX : timeout * 1000.0; if(QThread::isRunning()){ return wait(time); } else if(isRunningForeground){ stateMutex.lock(); const bool isDifferentThread = (threadId != QThread::currentThreadId()); stateMutex.unlock(); if(!isDifferentThread){ return false; } else { bool isTimeout = false; while(true){ bool finished = false; stateMutex.lock(); if(!isRunningForeground){ finished = true; } else { isTimeout = !stateCondition.wait(&stateMutex, time); finished = !isRunningForeground; } stateMutex.unlock(); if(finished || isTimeout){ break; } } return !isTimeout; } } return true; } /** \note GIL must be obtained when accessing this object. */ python::object PythonExecutor::resultObject() { impl->stateMutex.lock(); python::object object = impl->lastResultObject; impl->stateMutex.unlock(); return object; } const std::string PythonExecutor::resultString() const { impl->stateMutex.lock(); string result = impl->lastResultString; impl->stateMutex.unlock(); return result; } void PythonExecutorImpl::onBackgroundExecutionFinished() { sigFinished(); } void PythonExecutorImpl::releasePythonPathRef() { /** When a number of Python scripts is proccessed, releasing the path corresponding to a certain script may affect other scripts. To prevent it, set true to the following constant value. */ static const bool DISABLE_RELEASE = true; if(DISABLE_RELEASE){ return; } if(pathRefIter != additionalPythonPathRefMap.end()){ if(--pathRefIter->second == 0){ python::gil_scoped_acquire lock; boost::python::list syspath = boost::python::extract<boost::python::list>(getSysModule().attr("path")); int n = boost::python::len(syspath); for(int i=0; i < n; ++i){ string path = boost::python::extract<string>(syspath[i]); if(path == scriptDirectory){ syspath.pop(i); break; } } additionalPythonPathRefMap.erase(pathRefIter); } pathRefIter = additionalPythonPathRefMap.end(); } } SignalProxy<void()> PythonExecutor::sigFinished() { return impl->sigFinished; } bool PythonExecutor::terminate() { return impl->terminateScript(); } bool PythonExecutorImpl::terminateScript() { bool terminated = true; if(QThread::isRunning()){ terminated = false; for(int i=0; i < 400; ++i){ { python::gil_scoped_acquire lock; /** Set the exception class itself instead of an instance of the exception class because the following function only accepts a single parameter with regard to the exception object in constrast to PyErr_SetObject that takes both the type and value of the exeption, and if the instance is given to the following function, the exception type will be unknown in the exception handler, which makes it impossible for the handler to check if the termination is requested. By giving the class object, the handler can detect the exception type even in this case. */ PyThreadState_SetAsyncExc((long)threadId, getExitException().ptr()); } if(wait(20)){ terminated = true; break; } } releasePythonPathRef(); } else if(isRunningForeground){ python::gil_scoped_acquire lock; PyErr_SetObject(getExitException().ptr(), 0); releasePythonPathRef(); boost::python::throw_error_already_set(); } return terminated; } bool PythonExecutor::hasException() const { return impl->hasException; } /** \note The name includes module components. */ const std::string PythonExecutor::exceptionTypeName() const { impl->stateMutex.lock(); string name = impl->lastExceptionTypeName; impl->stateMutex.unlock(); return name; } const std::string PythonExecutor::exceptionText() const { impl->stateMutex.lock(); string text = impl->lastExceptionText; impl->stateMutex.unlock(); return text; } /** \note GIL must be obtained when accessing this object. */ python::object PythonExecutor::exceptionType() const { impl->stateMutex.lock(); python::object exceptionType = impl->lastExceptionType; impl->stateMutex.unlock(); return exceptionType; } /** \note GIL must be obtained when accessing this object. */ python::object PythonExecutor::exceptionValue() const { impl->stateMutex.lock(); python::object value = impl->lastExceptionValue; impl->stateMutex.unlock(); return value; } bool PythonExecutor::isTerminated() const { return impl->isTerminated; }
965e334ba0eb699824fa8e95092f674c4d8a8d96
2e55fbf3303ad89bbee963170f708acf38a103f3
/December Lunchtime 2020 Division 2/temp.cpp
13ee1773a7073fe4f849c0648fd8ef53885a02c9
[]
no_license
abaran803/myContests
ff083a342841af453fb5b92ea58bd67bae0feaf7
5b93cfe403721ee2ed45dc1d7d2454edf6e9c3c7
refs/heads/main
2023-02-15T09:16:50.228926
2021-01-13T13:11:06
2021-01-13T13:11:06
329,311,128
0
0
null
null
null
null
UTF-8
C++
false
false
3,410
cpp
// #include<bits/stdc++.h> // #define int long long // using namespace std; // void solve(); // int32_t main() // { // ios_base::sync_with_stdio(false);cin.tie(NULL); // #ifndef ONLINE_JUDGE // freopen("inp.txt", "r", stdin); // freopen("err.txt", "w", stderr); // freopen("out.txt", "w", stdout); // #endif // int t=1; // //cin>>t; // while(t--) // { // solve(); // cout<<endl; // } // cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" secs"<<endl; // return 0; // } // map<int,int> color; // bool NonColouredNode(int **arr,int &val,int n) { // for(int i=0;i<n;i++) { // if(!color[i]) { // val = i; // return true; // } // } // return false; // } // bool isValid(int **arr,int val,int num,int n) { // for(int i=0;i<n;i++) { // if(arr[val][i] && color[i] == num) { // return false; // } // } // return true; // } // bool algo(int **arr,int n,int m) { // int val; // if(!NonColouredNode(arr,val,n)) // return true; // for(int i=1;i<=m;i++) { // if(isValid(arr,val,i,n)) { // color[val] = i; // if(algo(arr,n,m)) { // return true; // } // color[val] = 0; // } // } // return false; // } // void solve() // { // int n,m,e; // cin >> n >> m >> e; // int **arr = new int*[n]; // for(int i=0;i<n;i++) // arr[i] = new int[n]; // for(int i=0;i<n;i++) // for(int j=0;j<n;j++) // arr[i][j] = 0; // for(int i=0;i<e;i++) { // int a,b; // cin >> a >> b; // arr[a-1][b-1] = 1; // arr[b-1][a-1] = 1; // } // cout << algo(arr,n,m); // } #include<bits/stdc++.h> #define int long long using namespace std; void solve(); int32_t main() { ios_base::sync_with_stdio(false);cin.tie(NULL); #ifndef ONLINE_JUDGE freopen("inp.txt", "r", stdin); freopen("err.txt", "w", stderr); freopen("out.txt", "w", stdout); #endif int t=1; cin>>t; while(t--) { solve(); cout<<endl; } cerr<<"time taken : "<<(float)clock()/CLOCKS_PER_SEC<<" secs"<<endl; return 0; } map<int,int> color; bool NonColouredNode(bool arr[101][101],int &val,int n) { for(int i=0;i<n;i++) { if(!color[i]) { val = i; return true; } } return false; } bool isValid(bool arr[101][101],int val,int num,int n) { for(int i=0;i<n;i++) { if(arr[val][i] && color[i] == num) { return false; } } return true; } bool graphColoring(bool arr[101][101],int m,int n) { int val; if(!NonColouredNode(arr,val,n)) return true; for(int i=1;i<=m;i++) { if(isValid(arr,val,i,n)) { color[val] = i; if(graphColoring(arr,m,n)) { return true; } color[val] = 0; } } return false; } void solve() { int n,m,e; cin >> n >> m >> e; bool arr[101][101]; for(int i=0;i<n;i++) memset(arr[i],0,sizeof(arr[i])); for(int i=0;i<e;i++) { int a,b; cin >> a >> b; arr[a-1][b-1] = 1; arr[b-1][a-1] = 1; } cout << graphColoring(arr,m,n); }
519b4069d7cf122c51a8e3c69b11874931737a37
770b7ad3c4e294e9c60d7c0e4f5d90f62daf3de0
/ComponentSeq2SeqCom/smartsoft/src/CommandHandler.cc
942117dd67e9947f693cdb865f9b10c25f61cb16
[]
no_license
Servicerobotics-Ulm/ComponentRepository
b1b73ea8871366f05846aedc4ca4df4024b8fe39
0c958e9dd9263b525b404bb9581f33c15cfbb3d8
refs/heads/master
2022-12-15T07:54:19.437434
2022-12-06T14:30:05
2022-12-06T14:30:05
122,948,164
2
11
null
2021-02-10T12:03:13
2018-02-26T09:46:20
C++
UTF-8
C++
false
false
2,582
cc
//-------------------------------------------------------------------------- // Code generated by the SmartSoft MDSD Toolchain // The SmartSoft Toolchain has been developed by: // // Service Robotics Research Center // University of Applied Sciences Ulm // Prittwitzstr. 10 // 89075 Ulm (Germany) // // Information about the SmartSoft MDSD Toolchain is available at: // www.servicerobotik-ulm.de // // This file is generated once. Modify this file to your needs. // If you want the toolchain to re-generate this file, please // delete it before running the code generator. //-------------------------------------------------------------------------- //-------------------------------------------------------------------------- // // Copyright (C) 2018 Matthias Lutz // // [email protected] // [email protected] // // ZAFH Servicerobotic Ulm // Christian Schlegel // University of Applied Sciences // Prittwitzstr. 10 // 89075 Ulm // Germany // // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA // //------------------------------------------------------------------------- #include "CommandHandler.hh" #include "ComponentSeq2SeqCom.hh" #include <iostream> CommandHandler::CommandHandler(Smart::InputSubject<CommBasicObjects::CommTaskMessage> *subject, const int &prescaleFactor) : CommandHandlerCore(subject, prescaleFactor) { std::cout << "constructor CommandHandler\n"; } CommandHandler::~CommandHandler() { std::cout << "destructor CommandHandler\n"; } void CommandHandler::on_TaskSendIn(const CommBasicObjects::CommTaskMessage &input) { // implement business logic here // (do not use blocking calls here, otherwise this might block the InputPort TaskSendIn) CommBasicObjects::CommTaskEventState state; state.setJob(input); COMP->taskEventOut->put(state); std::cout<<"Put Event "<<input<<std::endl; }
b3dfeb8d06b445600f4acf31f7ae07b01701281a
5712a01bc06416cf32fb637e10b21b34b938961c
/Zerojudge/d563 等值首尾和.cpp
17842247fec242c9a3b6ad13da70840d1511a25f
[]
no_license
WenShihKen/uva
654a9f5f3e56935625e061795f152609899b79e5
03a3d603941dd9b9ec13e76fb99d24da6749a81b
refs/heads/master
2021-01-10T14:34:29.580527
2020-06-25T15:34:23
2020-06-25T15:34:23
48,536,090
1
0
null
null
null
null
UTF-8
C++
false
false
619
cpp
#include<iostream> #include<stdio.h> #include<algorithm> #include<map> #include<string> using namespace std; int all[100005] = {}, in1; int count() { int start = 0, end = in1 - 1, c = 0; int sum1 = 0, sum2 = 0; while (start <= in1 - 1 || end >= 0) { if (sum1 > sum2) { sum2 += all[end--]; } else if (sum1 < sum2) { sum1 += all[start++]; } else { c++; sum1 += all[start++]; sum2 += all[end--]; } } return c; } int main() { while (cin >> in1) { int ans = 0; fill(all, all + 100003, 0); for (int i = 0; i < in1; i++) cin >> all[i]; ans = count(); cout << ans << endl; } }
9310800444741178d2ece0fedb5233ef89155177
9b1a0e9ac2c5ffc35f368ca5108cd8953eb2716d
/3/06 Audio/07 Luchs/src/lib/atomgaud/GAMath.cpp
7a567a81b81a5c8672932c8d6884c3718ba2be0a
[]
no_license
TomasRejhons/gpg-source-backup
c6993579e96bf5a6d8cba85212f94ec20134df11
bbc8266c6cd7df8a7e2f5ad638cdcd7f6298052e
refs/heads/main
2023-06-05T05:14:00.374344
2021-06-16T15:08:41
2021-06-16T15:08:41
377,536,509
2
2
null
null
null
null
WINDOWS-1252
C++
false
false
8,137
cpp
// GAMath Implementation // -------------------------------------------------------------------------------------------------------- // System: ATOMGAUD // Description: Simple math for FLOAT32 scalar and vector // ... // ... // Location: http://www.visiomedia.com/rooms/labor/src/sphinxmmos/index.htm // Version: 0401 // Author: Frank Luchs // History: // 1996-05-07 first draft // -------------------------------------------------------------------------------------------------------- // This is part of Sphinx MMOS, the open source version of Sphinx Modular Media. // Copyright © 1985-2001 Visiomedia Software Corporation, All Rights Reserved. // -------------------------------------------------------------------------------------------------------- #include "stdafx.h" #include "GAMath.h" #ifdef ATOMOS namespace atomos { #endif // ATOMOS // metaclass implementation void* __stdcall CreateCGAMath() { return( new CGAMath); } const CClass CGAMath::classCGAMath(CID_GAMath, CID_GAObject, "CGAMath", CreateCGAMath); const IClass* CGAMath::GetClass() { return((const IClass*)&classCGAMath); } // CTOR CGAMath::CGAMath() { } // DTOR CGAMath::~CGAMath() { } // explicit terminate baseclass void CGAMath::Terminate() { CGAObject::Terminate(); } // round INT32 CGAMath::Round (FLOAT32 fValue) { INT32 nRounded=0; nRounded = (fValue >= 0.0f) ? ((INT32) (fValue + 0.5f)) : ((INT32) (fValue - 0.5f)); return nRounded; } // zero //--------------------------------------------------------------------------------------- void CGAMath::Zero (FLOAT32* pfDest, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { pfDest[i] = 0.0f; } } // set //--------------------------------------------------------------------------------------- void CGAMath::Set (FLOAT32* pfDest, FLOAT32 fSource, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { pfDest[i] = fSource; } } // add //--------------------------------------------------------------------------------------- void CGAMath::Add (FLOAT32* pfDest, FLOAT32 fSource, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { pfDest[i] += fSource; } } void CGAMath::Add (FLOAT32* pfDest, const FLOAT32* pfSource, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { pfDest[i] += pfSource[i]; } } void CGAMath::Add (FLOAT32* pfDest, const FLOAT32* pfSource1, const FLOAT32* pfSource2, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { pfDest[i] = pfSource1[i] + pfSource2[i]; } } // sub //--------------------------------------------------------------------------------------- void CGAMath::Sub (FLOAT32* pfDest, FLOAT32 fSource, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { pfDest[i] += fSource; } } void CGAMath::Sub (FLOAT32* pfDest, const FLOAT32* pfSource, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { pfDest[i] -= pfSource[i]; } } void CGAMath::Sub (FLOAT32* pfDest, const FLOAT32* pfSource1, const FLOAT32* pfSource2, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { pfDest[i] = pfSource1[i] - pfSource2[i]; } } // mul //--------------------------------------------------------------------------------------- void CGAMath::Mul (FLOAT32* pfDest, FLOAT32 fSource, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { pfDest[i] *= fSource; } } void CGAMath::Mul (FLOAT32* pfDest, const FLOAT32* pfSource, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { pfDest[i] *= pfSource[i]; } } void CGAMath::Mul (FLOAT32* pfDest, const FLOAT32* pfSource1, const FLOAT32* pfSource2, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { pfDest[i] = pfSource1[i] * pfSource2[i]; } } // div //--------------------------------------------------------------------------------------- void CGAMath::Div (FLOAT32* pfDest, FLOAT32 fSource, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { pfDest[i] /= fSource; } } void CGAMath::Div (FLOAT32* pfDest, const FLOAT32* pfSource, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { pfDest[i] /= pfSource[i]; } } void CGAMath::Div (FLOAT32* pfDest, const FLOAT32* pfSource1, const FLOAT32* pfSource2, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { pfDest[i] = pfSource1[i] / pfSource2[i]; } } // abs //--------------------------------------------------------------------------------------- void CGAMath::Abs (FLOAT32* pfDest, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { pfDest[i] = fabsf(pfDest[i]); } } void CGAMath::Abs (FLOAT32* pfDest, const FLOAT32* pfSource, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { pfDest[i] = fabsf(pfSource[i]); } } // sqrt //--------------------------------------------------------------------------------------- void CGAMath::Sqrt (FLOAT32* pfDest, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { pfDest[i] = sqrtf(pfDest[i]); } } void CGAMath::Sqrt (FLOAT32* pfDest, const FLOAT32* pfSource, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { pfDest[i] = sqrtf(pfSource[i]); } } // max //--------------------------------------------------------------------------------------- void CGAMath::Max (FLOAT32* pfDest, FLOAT32 fMax, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { if(pfDest[i] > fMax) pfDest[i] = fMax; } } void CGAMath::Max (FLOAT32* pfDest, const FLOAT32* pfSource, FLOAT32 fMax, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { if(pfSource[i] > fMax) pfDest[i] = fMax; else pfDest[i] = pfSource[i]; } } // min //--------------------------------------------------------------------------------------- void CGAMath::Min (FLOAT32* pfDest, FLOAT32 fMin, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { if(pfDest[i] < fMin) pfDest[i] = fMin; } } void CGAMath::Min (FLOAT32* pfDest, const FLOAT32* pfSource, FLOAT32 fMin, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { if(pfSource[i] < fMin) pfDest[i] = fMin; else pfDest[i] = pfSource[i]; } } // clip //--------------------------------------------------------------------------------------- void CGAMath::Clip (FLOAT32* pfDest, FLOAT32 fMin, FLOAT32 fMax, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { if(pfDest[i] < fMin) pfDest[i] = fMin; else if(pfDest[i] > fMax) pfDest[i] = fMax; } } void CGAMath::Clip (FLOAT32* pfDest, const FLOAT32* pfSource, FLOAT32 fMin, FLOAT32 fMax, UINT32 nCount) { for (UINT32 i = 0; i < nCount; i++) { if(pfSource[i] < fMin) pfDest[i] = fMin; else if(pfSource[i] > fMax) pfDest[i] = fMax; else pfDest[i] = pfSource[i]; } } // convolve //--------------------------------------------------------------------------------------- FLOAT32 CGAMath::Convolve (const FLOAT32* pfx, const FLOAT32* pfy,UINT32 nCount) { FLOAT32 fConv = 0.0f; UINT32 nEnd = nCount - 1; for (UINT32 i = 0; i < nCount; i++) { fConv = fConv +(pfx[i] * pfy[nEnd-i]); } return(fConv); } void CGAMath::Convolve (FLOAT32* pfDest, const FLOAT32* pfx, const FLOAT32* pfy,UINT32 nCount) { FLOAT32 fConv = 0.0f; UINT32 nEnd = nCount - 1; UINT32 ndx =0; for (UINT32 di = 0; di < nCount; di++) { for (UINT32 i = 0; i < nCount; i++) { ndx = i - di; if(ndx < 0) ndx += nEnd; fConv = fConv +(pfx[nEnd- i] * pfy[ndx]); } pfDest[di] = fConv; fConv = 0.0f; } } FLOAT32 CGAMath::Freq2Pitch(FLOAT32 fFreq) { FLOAT32 f = 69.0f + 12.0f * (log(fFreq/440.0f)/log(2.0f)); return (f); } #ifdef ATOMOS } // namespace atomos #endif // ATOMOS // --------------------------------------------------------------------------------------------------------
c65d320c59262da3af91ab710390a14fd63f5df5
dfe3e8569e2785e062345f9854f02afeac67b8a0
/Source/Utility/StringTools.h
02d49809f4c1097379cfbc3b9d2b4c3af94cca4e
[]
no_license
mangeg/MG3
e16f73b26b59a5729ac59b97efe8c38844adaa6d
6915ea72650ed0bca0ecfe5ae3d4a20c8ac5a0f1
refs/heads/master
2016-08-05T08:48:25.031859
2011-07-18T23:24:30
2011-07-18T23:24:30
1,919,166
0
0
null
null
null
null
UTF-8
C++
false
false
345
h
//------------------------------------------------------------------------| #pragma once //------------------------------------------------------------------------| namespace MG3 { class StringTools { public: static std::string ToAscii(std::wstring& txt); static std::wstring ToUnicode(std::string& txt); private: StringTools(); }; }
[ "" ]
8a147c0d38d875a0017e0e8e9c8d2a3e6742f31e
f834dc3940a70c26757cd47db50800e774586eb5
/mainwindow.h
2591c6e307a8c70b0ce065432aa96469146d556d
[]
no_license
yitiaoyu1996/Qt-gradecalculator
f6c951cbd76dfd140fd417ff622e9d079c768e20
d37f685e721ab23cf4dffb74950b13b7355adcf4
refs/heads/master
2021-08-30T08:39:18.131326
2017-12-17T01:52:05
2017-12-17T01:52:05
112,532,266
0
0
null
null
null
null
UTF-8
C++
false
false
406
h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = 0); ~MainWindow(); signals: void compute_overall(); public slots: void update_overall(int); void compute_sum() const ; private: Ui::MainWindow *ui; }; #endif // MAINWINDOW_H
dd9e57662a7ac4196205ab803703f49c1ab1a049
b7f3edb5b7c62174bed808079c3b21fb9ea51d52
/content/common/in_process_child_thread_params.cc
520122de5f3630cec0bc799e75716bfd4c43b70e
[ "BSD-3-Clause" ]
permissive
otcshare/chromium-src
26a7372773b53b236784c51677c566dc0ad839e4
64bee65c921db7e78e25d08f1e98da2668b57be5
refs/heads/webml
2023-03-21T03:20:15.377034
2020-11-16T01:40:14
2020-11-16T01:40:14
209,262,645
18
21
BSD-3-Clause
2023-03-23T06:20:07
2019-09-18T08:52:07
null
UTF-8
C++
false
false
687
cc
// Copyright 2015 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/common/in_process_child_thread_params.h" namespace content { InProcessChildThreadParams::InProcessChildThreadParams( scoped_refptr<base::SingleThreadTaskRunner> io_runner, mojo::OutgoingInvitation* mojo_invitation) : io_runner_(std::move(io_runner)), mojo_invitation_(mojo_invitation) {} InProcessChildThreadParams::InProcessChildThreadParams( const InProcessChildThreadParams& other) = default; InProcessChildThreadParams::~InProcessChildThreadParams() { } } // namespace content
100663059d275523396f2dc86c197136aa13ac30
35fdbeb171f989627b57044c14e7ac90b36a8985
/components/main_class.h
af624d22493a94370e34d15c9065745615fedb84
[]
no_license
Alexponomarev7/mini_java_compiler
354d32befdafbb9ccfa4354a07d78da50ae32f09
f59c4d62d5305046bcdb613bfc63aed808c47743
refs/heads/master
2021-05-25T21:20:06.938888
2020-05-24T02:01:53
2020-05-24T02:01:53
253,923,553
0
0
null
null
null
null
UTF-8
C++
false
false
846
h
#ifndef COMPILER_MAIN_CLASS_H #define COMPILER_MAIN_CLASS_H #include "base.h" class MainClass : public BaseElement { public: MainClass(Identifier id, std::vector<Statement*> statements) : id_(std::move(id)) , statements_(std::move(statements)) {} void Accept(Visitor* visitor) override { auto current_location = Location::GetInstance()->GetLocation(); Location::GetInstance()->SetLocation(this->GetLocation()); visitor->Visit(this); Location::GetInstance()->SetLocation(current_location); } private: Identifier id_; std::vector<Statement*> statements_; friend class PrintVisitor; friend class InterpreterVisitor; friend class SymbolTreeVisitor; friend class FunctionCallVisitor; friend class IrtreeBuildVisitor; }; #endif //COMPILER_MAIN_CLASS_H
1c41ca4835e3d3ca5d1248b4c1c68dd5f0834d24
752630bd87a55f4db56217e6a3f4b8bc7cc1c6bf
/cpp-htp/standard/ch05solutions/Ex05_08/ex05_08.cpp
f3a2fb80dbd46ae88e64783a910379323c4e5335
[ "Apache-2.0" ]
permissive
wgfi110/cpp-playground
e4cfc8440a338d3fbb865b720f38cadd843759b6
6767a0ac50de8b532255511cd450dc84c66d1517
refs/heads/master
2021-09-27T22:25:32.963986
2018-11-12T09:13:56
2018-11-12T09:13:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,856
cpp
// Exercise 5.8 Solution: ex05_08.cpp // Find the smallest of several integers. #include <iostream> using namespace std; int main() { int number; // number of values int value; // current value int smallest; // smallest value so far cout << "Enter the number of integers to be processed "; cout << "followed by the integers: " << endl; cin >> number >> smallest; // loop (number -1) times for ( int i = 2; i <= number; i++ ) { cin >> value; // read in next value // if current value less than smallest, update smallest if ( value < smallest ) smallest = value; } // end for // display smallest integer cout << "\nThe smallest integer is: " << smallest << endl; } // end main /************************************************************************** * (C) Copyright 1992-2010 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
f5db283e63233ef45aa96c882b5cc78a72d2f825
08b92f8a2a6c4de809f6da036502d19422f3afc1
/code/Xadrez_Version_01/quadrado.cpp
63196860c6e7b0951f2a6b13313c0c345f04688f
[ "MIT" ]
permissive
matheusfbonfim/SimulateChessDesktopApp
92eca7397760540d5c1ed99f3824c57b2ff95cdb
09aaf703416644aaecbef0f6bad9548aad31f490
refs/heads/master
2023-04-27T08:04:42.467722
2020-08-01T15:25:01
2020-08-01T15:25:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,371
cpp
#include "quadrado.h" Quadrado::Quadrado(double x_,double y_) { x = x_; y = y_; caneta = new QPen(Qt::black); // Cria a caneta com contorno preto peca = NULL; } //Retorna a coordenada X do quadrado double Quadrado::getX() { return x; } //Retorna a coordenada Y do quadrado double Quadrado::getY() { return y; } // Retorna a caneta QPen Quadrado::getCaneta() { return *caneta; } // Retorna o balde de tinta QBrush Quadrado::getBalde() { return *balde; } // Setar o balde conforme a tinta void Quadrado::setBalde(int cor) { if(cor==1) { balde = new QBrush(Qt::white); } else if(cor == 0) { balde = new QBrush(Qt::lightGray); } else { delete balde; balde = new QBrush(Qt::green); } } //Setar o indice da Coluna void Quadrado::setColuna(int c) { indice_coluna = c; } //Setar o indice da Linha void Quadrado::setLinha(int l) { indice_linha = l; } // Retornar o indice da linha int Quadrado::getLinha() { return indice_linha; } //Retornar o indice da coluna int Quadrado::getColuna() { return indice_coluna; } //Retorna a peça inserida no quadrado Peca* Quadrado::getPeca() { return peca; } //Seta a peca do quadrado void Quadrado::setPeca(Peca* p) { peca = p; } //Desconstrutor Quadrado::~Quadrado() { free(caneta); free(balde); }
64d882ee7a8f192bec86a4ec3845a1e840725a24
c728ad7e699fe39716c3e7bf79c00659a4f0fa77
/src/ytyaru/Framework/SingleWindow/Window.cpp
db3a4b8cb9ad789f5c05ebe6a2e41889dfb01fe0
[ "CC0-1.0" ]
permissive
ytyaru/ProjectSplit201607300826
6a6c1a56afcf88f67a9c3b59997f90faf4352188
25a2c5ebbb2dad6221f84f2e5404e8e0e9f48de5
refs/heads/master
2021-01-19T01:38:09.044552
2016-07-30T07:02:58
2016-07-30T07:02:58
64,531,167
0
0
null
null
null
null
SHIFT_JIS
C++
false
false
2,022
cpp
#include "Window.h" #include "Uuid.h" namespace ytyaru { namespace Framework { namespace SingleWindow { using ytyaru::Framework::SingleWindow::IPartWndProc; vector<IPartWndProc*> Window::partWndProcs; Window::Window(void) {} Window::~Window(void) {} void Window::Create(HINSTANCE hInstance) { basic_string<TCHAR> className = ytyaru::Library::Uuid::Get(); WNDCLASSEX wc; wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = Window::WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = NULL; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); wc.lpszMenuName = NULL; wc.lpszClassName = className.c_str(); wc.hIconSm = LoadIcon(NULL, IDI_APPLICATION); if (!RegisterClassEx(&wc)) { throw "RegisterClassEx関数が失敗した。"; } HWND hWnd = CreateWindowEx( 0, // 拡張ウィンドウスタイル className.c_str(), // class名 _T("Window::Createで生成したWindowです。"), // タイトル WS_OVERLAPPEDWINDOW, // Style CW_USEDEFAULT, // X CW_USEDEFAULT, // Y CW_USEDEFAULT, // Width CW_USEDEFAULT, // Height NULL, // 親ウィンドウまたはオーナーウィンドウのハンドル NULL, // メニューハンドルまたは子ウィンドウ ID hInstance, // アプリケーションインスタンスのハンドル NULL // ウィンドウ作成データ ); if (NULL == hWnd) { throw "CreateWindow関数が失敗した。"; } ShowWindow(hWnd, SW_SHOWNORMAL); UpdateWindow(hWnd); } LRESULT CALLBACK Window::WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { BOOL isReturn = false; for (unsigned int i = 0; i < Window::partWndProcs.size(); i++) { LRESULT res = Window::partWndProcs[i]->PartWndProc(hWnd, uMsg, wParam, lParam, &isReturn); if (isReturn) { return res; } } if (uMsg == WM_NCDESTROY) { PostQuitMessage(0); } return (DefWindowProc(hWnd, uMsg, wParam, lParam)); } } } }
0ff7a4a1038cc2ccef66db9e926491e7afbd8327
4396e4a00332aabcd943aee98cf29f5faec60764
/talk/src/endpoint2/StreamHandler.h
7125bb8e788ac7b837fdedb827e85851701b1279
[]
no_license
xiaoyu0/Talk-RenRen
431fbebb13920c6eeb2651932f131460c487b5e7
c7409b745e0056dec7e22a7c1995be122af27d3d
refs/heads/master
2021-10-09T04:22:09.195537
2018-12-21T03:52:33
2018-12-21T03:52:33
6,398,175
0
0
null
null
null
null
UTF-8
C++
false
false
857
h
#ifndef TALK_HTTP_SERVER_HTTP_STREAM_HANDLER_H_ #define TALK_HTTP_SERVER_HTTP_STREAM_HANDLER_H_ #include <boost/shared_ptr.hpp> #include <string> #include "proxy/SocketServiceProxy.h" #include "net/Connection.h" namespace mtalk{ namespace endpoint2{ // typedef boost::shared_ptr<net::Connection> ConnectionPtr; class StreamHandler { public : StreamHandler(); virtual ~StreamHandler(); /** * @brief 对接受的请求做基础的处理 * * @param request * @param response */ void handler(const std::string& request, net::ConnectionPtr& connectionPtr); private : std::string generateErr(const std::string& errMsg); boost::shared_ptr<proxy::SocketServiceProxy> socketServiceProxyPtr_; }; }; }; #endif //TALK_HTTP_SERVER_SERVER_REQUEST_HANDLER_H_
9eb50c28c43c3d2b37e3bfec573ecc2a52d9f05f
c4338ebd1bd0358d9abc1f1f7350e37ab0314c2f
/Atcoder/M-Solutions2020D.cpp
7d77f097759c27e250b97d6bd857a46b3df7cbe5
[]
no_license
mt-revolution/Competition
4b93a43230aff1f11e6614fcb45bb999ecdd633b
6da911b1674d8d6ec2c27f073f35a935972547e3
refs/heads/master
2023-02-26T08:16:40.597143
2021-01-30T14:17:05
2021-01-30T14:17:05
300,127,965
0
0
null
null
null
null
UTF-8
C++
false
false
788
cpp
#include<bits/stdc++.h> using namespace std; int main() { int N; cin >> N; long long money = 1000; long long stock = 0; vector<int> A(N); for(int i = 0; i < N; i++) { cin >> A[i]; } for(int i = 0; i < N-1; i++) { // 株価が上がるときは金をつぎ込んで変えるだけ買う if(A[i] < A[i+1]) { stock += money / A[i]; money -= (money / A[i]) * A[i]; // 株価が下がるときは持ってる分を全て売る } else if(A[i] > A[i+1]) { money += stock * A[i]; stock = 0; } } // 最後に残ってる株を全て売る money += stock * A[N-1]; stock = 0; cout << money << endl; return 0; }
b2ea373880391f23b70469b8b83530367e2cdbc3
3812d4c6a283305100d8d4ff597d31178c2f2468
/FlowMapStudy/Code/Mesh/Mesh.h
0eb2cf92e77c42f520b5c06dcc1c75e9bc471747
[]
no_license
rbleile/ParticleAdvection
d1029d8608ba770c046c81352f77d0ac191848fd
70026c845fa20776a87c92a1750ce28cf49028a5
refs/heads/master
2020-12-24T13:35:48.712480
2015-06-23T02:21:46
2015-06-23T02:21:46
34,482,101
0
0
null
null
null
null
UTF-8
C++
false
false
4,585
h
#include <Particle.h> #include <Flow.h> #ifndef MESH_H #define MESH_H //************************************************************************************************* // Mesh Class for Rectilinear or Regular Meshes // Utilizes the Flow Map Classes //************************************************************************************************* class Mesh { public: // Number of Points in Each Dimension long int nx; long int ny; long int nz; // Step Size in Each Dimension double dx; double dy; double dz; // Origin Point of Mesh double x0; double y0; double z0; // Mesh Vector Field double* V; //Mesh Empty Mesh Constructor Mesh() : V(NULL), nx(0), ny(0), nz(0), dx(-1), dy(-1), dz(-1), x0(0), y0(0), z0(0){}; //Mesh Regular Mesh Constructor Mesh( long int num_x, long int num_y, long int num_z, double del_x, double del_y, double del_z, double x_p, double y_p, double z_p, double *v_field ) : nx(num_x), ny(num_y), nz(num_z), dx(del_x), dy(del_y), dz(del_z), x0(x_p), y0(y_p), z0(z_p), V(v_field) {}; // Get the Cell ID for a given Point in a given coordinate long int getRegularCellID_X( double xp ){ return (int)((xp-x0)/dx); } long int getRegularCellID_Y( double yp ){ return (int)((yp-y0)/dy); } long int getRegularCellID_Z( double zp ){ return (int)((zp-z0)/dz); } void getRegularLogicalCellID( double xp, double yp, double zp, long int *cellID ) { cellID[0] = getRegularCellID_X( xp ); cellID[1] = getRegularCellID_Y( yp ); cellID[2] = getRegularCellID_Z( zp ); } void getLogicalCellID( double xp, double yp, double zp, long int *cellID ) { getRegularLogicalCellID( xp, yp, zp, cellID ); } // Simple Regular Cell ID Calculation long int getRegularCellID( double xp, double yp, double zp ) { long int cellID[3]; getRegularLogicalCellID( xp, yp, zp, cellID ); return cellID[2]*(nx-1)*(ny-1)+cellID[1]*(nx-1)+cellID[0]; } //Generic Function to compute the cell id of a point on this mesh long int getCellID( double xp, double yp, double zp ) { return getRegularCellID( xp, yp, zp ); } void getCellXRangeRegular( long int xid, double &xmin, double &xmax ) { xmin = x0 + dx*xid; xmax = x0 + dx*(xid+1); } void getCellYRangeRegular( long int yid, double &ymin, double &ymax ) { ymin = y0 + dy*yid; ymax = y0 + dy*(yid+1); } void getCellZRangeRegular( long int zid, double &zmin, double &zmax ) { zmin = z0 + dz*zid; zmax = z0 + dz*(zid+1); } //Get the Min and Max of a cell given a logical id void getCellXRange( long int xid, double &xmin, double &xmax ) { getCellXRangeRegular( xid, xmin, xmax ); } void getCellYRange( long int yid, double &ymin, double &ymax ) { getCellYRangeRegular( yid, ymin, ymax ); } void getCellZRange( long int zid, double &zmin, double &zmax ) { getCellZRangeRegular( zid, zmin, zmax ); } //Get the boundingBox for a cell given global id void getCellBounds( long int cid, double* bb ) { long int ids[3]; D1to3C( cid, ids ); getCellXRange( ids[0], bb[0], bb[1] ); getCellYRange( ids[1], bb[2], bb[3] ); getCellZRange( ids[2], bb[4], bb[5] ); } //Convert an index from a one dimensional representaiton to a three dimensional representation void D1to3C( long int id, long int *ids ) { ids[0] = id % (nx-1); ids[1] = (id/(nx-1)) % (ny-1); ids[2] = id / ((nx-1) * (ny-1)); } //Convert an index from a three dimensional representaiton to a one dimensional representation long int D3to1C( long int x, long int y, long int z ) { return x + (nx-1)*(y + (ny-1)*z); } //Convert an index from a one dimensional representaiton to a three dimensional representation void D1to3P( long int id, long int *ids ) { ids[0] = id % nx; ids[1] = (id/nx) % ny; ids[2] = id / (nx * ny); } //Convert an index from a three dimensional representaiton to a one dimensional representation long int D3to1P( long int x, long int y, long int z ) { return x + nx*(y + ny*z); } //Advection Functions void getVelocity( Point point, double *outVelocity ); void getVelocity( Particle point, double *outVelocity ); int Euler( double* bbox, double* mbb, double endTime, Particle &particle); int RK4( double* bbox, double* mbb, double endTime, Particle &particle); int REV_Euler( double* bbox, double* mbb, double endTime, Particle &particle); int REV_RK4( double* bbox, double* mbb, double endTime, Particle &particle); int onBoundary( Particle particle, double* bbox ); }; #endif
03336aeb53a17cd78ab856631b738d09b3c99a56
167c1259f696bd8570eb83279fbaafc8cb877099
/MicroProjet/Entity.cpp
9655b65467ef42e090bd457b2ed05d02142b5c82
[]
no_license
hantisse/MicroProjet
a6aff0d7f37acf7a9ef281961691f4084e30d27e
0d8f05ff4ad94be819f26a987c5c6954f21f0386
refs/heads/master
2020-05-31T04:34:49.321047
2019-07-06T00:00:06
2019-07-06T00:00:06
190,100,841
0
0
null
null
null
null
UTF-8
C++
false
false
1,695
cpp
#include "pch.h" #include <iostream> #include "Entity.h" extern std::vector<EntityModelPtr>* GameEntityModels; Entity::Entity(EntityID id) : m_model((*GameEntityModels)[id]) { m_sprite = sf::Sprite(m_model->sourceTexture, m_model->spriteRect); } Entity::Entity(EntityID id, b2Vec2 position) : m_model((*GameEntityModels)[id]) { m_sprite = sf::Sprite(m_model->sourceTexture, m_model->spriteRect); m_bodyDef.position.Set(position.x, position.y); } void Entity::update(sf::Time dt) { //this->m_sfShape.setPosition(sf::Vector2f(m_body->GetPosition().x, m_body->GetPosition().y)); m_sprite.setPosition(sf::Vector2f(m_body->GetPosition().x, m_body->GetPosition().y)); m_animator.update(dt); m_animator.animate(m_sprite); } void Entity::draw(sf::RenderTarget& target, sf::RenderStates states) const { target.draw(m_sprite); } void Entity::playAnimation(std::string animation) { m_animator.playAnimation(animation); } void Entity::stopAnimation() { m_animator.stopAnimation(); } bool Entity::isAnimationPlaying() { return m_animator.isPlayingAnimation(); } void Entity::createBody(b2World& world) { m_body = world.CreateBody(&m_bodyDef); b2Fixture* fixture = m_body->CreateFixture(&m_model->bodyFixDef); fixture->SetUserData(&m_bodyData); } void Entity::applyLinearImpulseToCenter(b2Vec2 const& impulse, bool wake) { m_body->ApplyLinearImpulseToCenter(impulse, wake); } void Entity::setLinearVelocity(b2Vec2 const& impulse) { m_body->SetLinearVelocity(impulse); } b2Vec2 Entity::getLinearVelocity() const { return m_body->GetLinearVelocity(); } float32 Entity::getMass() const { return m_body->GetMass(); } void Entity::invalidate() { m_body = nullptr; }
e18bef428bb5c687d3152515d3c82fa9dc662973
62651a10428b77e6eb0f7c8717344daea6ce4f95
/src/spider.cpp
d11b59e8fab84fae5067dee0b5d0bd32e22c0eb6
[ "MIT" ]
permissive
Thiago-AS/http-inspector
2f058241d2180da81909c571d896dc6954b8705a
43f6743a0096051fc5f1b22543fcc57ac3e62b0d
refs/heads/master
2020-09-11T21:06:56.093077
2019-12-05T10:04:40
2019-12-05T10:04:40
222,190,781
0
0
null
null
null
null
UTF-8
C++
false
false
2,777
cpp
#include "../include/spider.hpp" #include "../include/proxy.hpp" #include <sys/stat.h> #include <sstream> #include <fstream> #define PROXY_PORT 8228 using namespace std; void Spider::run(string file_name, string addr, int tree_h, int act_h) { string path = file_name; replace( path.begin(), path.end(), '_', '/'); this->references.push_back(path); if (act_h < tree_h){ fstream file; string f_name = "http://"+addr+path; replace( f_name.begin(), f_name.end(), '/', '_'); file.open("../cache/response_" + f_name); if(file.is_open()) { get_page_references(addr, act_h, tree_h, file); } else { proxy->send_http_request("GET " + path + " HTTP/1.1\r\nHost: " + addr + "\r\n\r\n\r\n", f_name); } file.close(); if (act_h != 0) { // string cmd = "rm ../cache/response_" + f_name; // system(cmd.c_str()); } } } void Spider::get_page_references(string addr, int act_h, int tree_h, fstream& req_file) { unsigned int position = 0; string line; while(getline(req_file, line)) { while (line.find("href=", position) != string::npos) { position = get_line_reference("href=", 6, line, position, addr, act_h, tree_h); } position = 0; while (line.find("src=\"", position) != string::npos) { position = get_line_reference("src=\"", 5 ,line, position, addr, act_h, tree_h); } } } int Spider::get_line_reference(string search_token, int offset, string line, int position, string addr, int act_h, int tree_h) { string value; int pos = line.find(search_token, position), i = 0; if (line[pos+offset] != '#') { for(i = pos + offset; ; i++) { if(i >= pos && line[i] != '"') value = value + line[i]; else if ( i >= pos && line[i] == '"') { break; } } if (value.find("http://" + addr) != string::npos || value.find("http") == string::npos) { if(value.find("http://" + addr) != string::npos){ value = value.substr(7, value.size()); value = value.substr(value.find('/'), value.size()); }else{ value.insert(0, 1, '/'); } int flag = 0; for(unsigned int i = 0; i < this->references.size() ; i++) { if (this->references[i] == value) { flag = 1; break; } } if (!flag) { for(int i = 0; i < act_h + 1; i++) { this->file << "\t"; } this->file << value << endl; this->references.push_back(value); if (value.find(".jpg") == string::npos && value.find(".png") == string::npos && value.find(".ico") == string::npos && value.find(".gif") == string::npos && value.find(".js") == string::npos && value.find(".css") == string::npos) { replace( value.begin(), value.end(), '/', '_'); this->run(value, addr, tree_h, act_h+1); } } return i + 1; } else { return pos + offset; } } else { return pos + offset; } }
ce676e1efe3eeeb47a0624c26f1a126bbc61bd55
08b8cf38e1936e8cec27f84af0d3727321cec9c4
/data/crawl/squid/hunk_4906.cpp
eb285009d7b7d5c8939e0ceabd7cf355ba22a436
[]
no_license
ccdxc/logSurvey
eaf28e9c2d6307140b17986d5c05106d1fd8e943
6b80226e1667c1e0760ab39160893ee19b0e9fb1
refs/heads/master
2022-01-07T21:31:55.446839
2018-04-21T14:12:43
2018-04-21T14:12:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
743
cpp
virginSendClaim.protectAll(); } + const HttpRequest *request = virgin->data->cause ? + virgin->data->cause : + dynamic_cast<const HttpRequest*>(virgin->data->header); + + if (request->client_addr.s_addr != any_addr.s_addr) + buf.Printf("X-Client-IP: %s\r\n", inet_ntoa(request->client_addr)); + + if (request->auth_user_request) + if (request->auth_user_request->username()) + buf.Printf("X-Client-Username: %s\r\n", request->auth_user_request->username()); + + fprintf(stderr, "%s\n", buf.content()); + buf.append(ICAP::crlf, 2); // terminate ICAP header // start ICAP request body with encapsulated HTTP headers
d784614938a9f5542c6886f20bdf37bcfae0f934
99ed5156c9b83d22dcd7c8a29937825694f4f36d
/dll/ALL/Demo示例/1-MFC综合示例(人脸库、人脸底图)/Config/ItsPictureCommon2.h
8d6e4c5b434ee0e2faf0a2bfa6c1ab612064a7a5
[ "MIT" ]
permissive
zyx030613/algorithm_its
73e862988f375a73e517db4f39b8f9005a819609
eae3628a498d2bd9d61487b53b9cdde23b99e314
refs/heads/master
2020-04-25T07:53:45.586587
2019-12-03T06:37:26
2019-12-03T06:37:26
172,627,700
0
1
null
null
null
null
GB18030
C++
false
false
2,902
h
#pragma once #include "../BasePage.h" #include "afxwin.h" #include "afxcmn.h" #define MANUL 0 #define AUTO_SIMPLE 1 #define AUTO_DIFFCULT 2 #define ITS_TYPE_NUM 14 #define ITS_JPEG_MIN_VALUE 0 #define ITS_JPEG_MAX_VALUE 100 #define ITS_LIMIT_MIN 64 #define ITS_LIMIT_MAX 8192 #define ITS_MAX_HOUR 24 #define ITS_MAX_MINUTE 59 // Cls_ItsPictureCommon2 对话框 class Cls_ItsPictureCommon2 : public CLS_BasePage { DECLARE_DYNAMIC(Cls_ItsPictureCommon2) public: Cls_ItsPictureCommon2(CWnd* pParent = NULL); // 标准构造函数 virtual ~Cls_ItsPictureCommon2(); // 对话框数据 enum { IDD = IDD_DLG_ITS_PICTURE_COMMON2 }; protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV 支持 virtual BOOL OnInitDialog(); DECLARE_MESSAGE_MAP() public: int m_iLogonID; int m_iChannelNo; virtual void OnChannelChanged(int _iLogonID,int _iChannelNo,int _iStreamNo); virtual void OnLanguageChanged(int _iLanguage); virtual void OnParamChangeNotify(int _iLogonID, int _iChannelNo, int _iParaType,void* _pPara,int _iUserData); private: void UI_UpdateDialog(); void UI_UpdateTimeAgcFlash(); void UI_UpdateBacklightSet(); void UI_UpdateCap(); void UI_UpdatePic(); void CheckEnable(); void UI_UpdatePageEnable(); void UI_UpdateDenoise(); public: CButton m_chkFlashLamp; afx_msg void OnBnClickedBtnBacklightSet(); CButton m_chkFlashLampAuto; CButton m_chkStrobe; CButton m_chkStrobeAuto; afx_msg void OnBnClickedButtonTimerange2(); CComboBox m_cboTimeRangeIndex2; CButton m_chkTimeRangeIndex2; CEdit m_edtTimeRange2; CButton m_btnTimeRange2; afx_msg void OnBnClickedChkCapEnable(); afx_msg void OnNMCustomdrawSldLightExpect(NMHDR *pNMHDR, LRESULT *pResult); CButton m_chkCapEnable; afx_msg void OnNMCustomdrawSldExpoUpperLimit(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnNMCustomdrawSldGainUpperLimit(NMHDR *pNMHDR, LRESULT *pResult); afx_msg void OnBnClickedBtnPicSizeLimitSet(); afx_msg void OnStnClickedStaPicSizeLimit2(); afx_msg void OnBnClickedRadio2(); afx_msg void OnBnClickedRdoAuto(); afx_msg void OnBnClickedRdoManul(); CComboBox m_cboDenoise3D; CEdit m_edtDenoise2D; int m_rdoHand; int m_rdoEasy; int m_rdoDiffcult; afx_msg void OnBnClickedRadio1(); CComboBox m_cboSelectForm; afx_msg void OnBnClickedStaticCapture(); afx_msg void OnBnClickedButton1(); CButton m_btnSetDenoise; afx_msg void OnBnClickedBtnSetDenoise(); //afx_msg void OnCbnSelchangeCboLevel(); afx_msg void OnBnClickedBtnSet(); CButton m_btnSet; afx_msg void OnCbnSelchangeComboTimerangeindex2(); CSliderCtrl m_sldLightExpect; CSliderCtrl m_sldExpoUpperLimit; CSliderCtrl m_sldGainUpperLimit; afx_msg void OnBnClickedCheckTimerangeindex2(); CButton m_btnSetLight; afx_msg void OnCbnSelchangeCombo1(); CEdit m_edtDenoise3D; CEdit m_edtDenoiseValue; afx_msg void OnStnClickedStc3dLevel(); afx_msg void OnCbnSelchangeCboLevel(); };
f55999994fff470510f9871979100bb32ae74514
52093e30d5ff4da56aa617df0b59c22909154f9a
/f2gameServer/Block.h
066df708d4401a5e2a5aec74df536f40fe8f9970
[]
no_license
LQ1234/f2gameServer
1d06b07a7665b8d027e48634d9183f1c49f07fab
7793314efa39902ae85348d6ef7138d71e46a5b6
refs/heads/master
2020-07-13T05:27:12.862814
2020-05-24T23:41:49
2020-05-24T23:41:49
205,003,384
0
0
null
null
null
null
UTF-8
C++
false
false
770
h
#pragma once #include <vector> #include "ListSerializer.h" #include <Box2D/Box2D.h> #include "gameObjectData.h" #include <set> #define BLOCK_TYPES_PP NULLBLOCK, STONEBLOCK, PLANKBLOCK, STONEBRICKBLOCK, LOGVBLOCK, LOGHBLOCK, GLASSBLOCK, TORCHBLOCK, LEAFBLOCK #define BLOCK_HITABLE_PP STONEBLOCK, PLANKBLOCK, STONEBRICKBLOCK, LOGVBLOCK, LOGHBLOCK, GLASSBLOCK class Block :Serializable { public: b2Body* physBody; b2World* wrd; enum BlockType { BLOCK_TYPES_PP }; static const std::vector<BlockType> blockTypes; static const std::set<BlockType> hitableBlockTypes; Block(BlockType bt,int x,int y, b2World& world); ~Block(); BlockType thisBlockType; int x, y; void** getAttributes(); static std::vector < ListSerializer::dataType > getAttributeTypes(); };
[ "Larry Qiu@DESKTOP-LG0O7G3" ]
Larry Qiu@DESKTOP-LG0O7G3
44ad6753b4ec9ca303c6847a062905469a2a3ae0
31d3018a2c9a7856fd4f614977ec6cb565dd2732
/lib/Sema/SemaExprObjC.cpp
0d41d2ef81d7c9fc0b2564539348435e4ada8c9c
[ "NCSA" ]
permissive
iewrer/Clang
1e80b97d0cb8b51850519b23fdf77e8c5aaa3257
d629b6fd7e1d1f5f54894e473909a84bfd8504c6
refs/heads/master
2020-06-04T21:34:09.859848
2014-03-20T07:46:22
2014-03-20T07:46:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
154,975
cpp
//===--- SemaExprObjC.cpp - Semantic Analysis for ObjC Expressions --------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file implements semantic analysis for Objective-C expressions. // //===----------------------------------------------------------------------===// #include "clang/Sema/SemaInternal.h" #include "clang/AST/ASTContext.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/ExprObjC.h" #include "clang/AST/StmtVisitor.h" #include "clang/AST/TypeLoc.h" #include "clang/Analysis/DomainSpecific/CocoaConventions.h" #include "clang/Edit/Commit.h" #include "clang/Edit/Rewriters.h" #include "clang/Lex/Preprocessor.h" #include "clang/Sema/Initialization.h" #include "clang/Sema/Lookup.h" #include "clang/Sema/Scope.h" #include "clang/Sema/ScopeInfo.h" #include "llvm/ADT/SmallString.h" using namespace clang; using namespace sema; using llvm::makeArrayRef; ExprResult Sema::ParseObjCStringLiteral(SourceLocation *AtLocs, Expr **strings, unsigned NumStrings) { StringLiteral **Strings = reinterpret_cast<StringLiteral**>(strings); // Most ObjC strings are formed out of a single piece. However, we *can* // have strings formed out of multiple @ strings with multiple pptokens in // each one, e.g. @"foo" "bar" @"baz" "qux" which need to be turned into one // StringLiteral for ObjCStringLiteral to hold onto. StringLiteral *S = Strings[0]; // If we have a multi-part string, merge it all together. if (NumStrings != 1) { // Concatenate objc strings. SmallString<128> StrBuf; SmallVector<SourceLocation, 8> StrLocs; for (unsigned i = 0; i != NumStrings; ++i) { S = Strings[i]; // ObjC strings can't be wide or UTF. if (!S->isAscii()) { Diag(S->getLocStart(), diag::err_cfstring_literal_not_string_constant) << S->getSourceRange(); return true; } // Append the string. StrBuf += S->getString(); // Get the locations of the string tokens. StrLocs.append(S->tokloc_begin(), S->tokloc_end()); } // Create the aggregate string with the appropriate content and location // information. const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType()); assert(CAT && "String literal not of constant array type!"); QualType StrTy = Context.getConstantArrayType( CAT->getElementType(), llvm::APInt(32, StrBuf.size() + 1), CAT->getSizeModifier(), CAT->getIndexTypeCVRQualifiers()); S = StringLiteral::Create(Context, StrBuf, StringLiteral::Ascii, /*Pascal=*/false, StrTy, &StrLocs[0], StrLocs.size()); } return BuildObjCStringLiteral(AtLocs[0], S); } ExprResult Sema::BuildObjCStringLiteral(SourceLocation AtLoc, StringLiteral *S){ // Verify that this composite string is acceptable for ObjC strings. if (CheckObjCString(S)) return true; // Initialize the constant string interface lazily. This assumes // the NSString interface is seen in this translation unit. Note: We // don't use NSConstantString, since the runtime team considers this // interface private (even though it appears in the header files). QualType Ty = Context.getObjCConstantStringInterface(); if (!Ty.isNull()) { Ty = Context.getObjCObjectPointerType(Ty); } else if (getLangOpts().NoConstantCFStrings) { IdentifierInfo *NSIdent=0; std::string StringClass(getLangOpts().ObjCConstantStringClass); if (StringClass.empty()) NSIdent = &Context.Idents.get("NSConstantString"); else NSIdent = &Context.Idents.get(StringClass); NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc, LookupOrdinaryName); if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) { Context.setObjCConstantStringInterface(StrIF); Ty = Context.getObjCConstantStringInterface(); Ty = Context.getObjCObjectPointerType(Ty); } else { // If there is no NSConstantString interface defined then treat this // as error and recover from it. Diag(S->getLocStart(), diag::err_no_nsconstant_string_class) << NSIdent << S->getSourceRange(); Ty = Context.getObjCIdType(); } } else { IdentifierInfo *NSIdent = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString); NamedDecl *IF = LookupSingleName(TUScope, NSIdent, AtLoc, LookupOrdinaryName); if (ObjCInterfaceDecl *StrIF = dyn_cast_or_null<ObjCInterfaceDecl>(IF)) { Context.setObjCConstantStringInterface(StrIF); Ty = Context.getObjCConstantStringInterface(); Ty = Context.getObjCObjectPointerType(Ty); } else { // If there is no NSString interface defined, implicitly declare // a @class NSString; and use that instead. This is to make sure // type of an NSString literal is represented correctly, instead of // being an 'id' type. Ty = Context.getObjCNSStringType(); if (Ty.isNull()) { ObjCInterfaceDecl *NSStringIDecl = ObjCInterfaceDecl::Create (Context, Context.getTranslationUnitDecl(), SourceLocation(), NSIdent, 0, SourceLocation()); Ty = Context.getObjCInterfaceType(NSStringIDecl); Context.setObjCNSStringType(Ty); } Ty = Context.getObjCObjectPointerType(Ty); } } return new (Context) ObjCStringLiteral(S, Ty, AtLoc); } /// \brief Emits an error if the given method does not exist, or if the return /// type is not an Objective-C object. static bool validateBoxingMethod(Sema &S, SourceLocation Loc, const ObjCInterfaceDecl *Class, Selector Sel, const ObjCMethodDecl *Method) { if (!Method) { // FIXME: Is there a better way to avoid quotes than using getName()? S.Diag(Loc, diag::err_undeclared_boxing_method) << Sel << Class->getName(); return false; } // Make sure the return type is reasonable. QualType ReturnType = Method->getReturnType(); if (!ReturnType->isObjCObjectPointerType()) { S.Diag(Loc, diag::err_objc_literal_method_sig) << Sel; S.Diag(Method->getLocation(), diag::note_objc_literal_method_return) << ReturnType; return false; } return true; } /// \brief Retrieve the NSNumber factory method that should be used to create /// an Objective-C literal for the given type. static ObjCMethodDecl *getNSNumberFactoryMethod(Sema &S, SourceLocation Loc, QualType NumberType, bool isLiteral = false, SourceRange R = SourceRange()) { Optional<NSAPI::NSNumberLiteralMethodKind> Kind = S.NSAPIObj->getNSNumberFactoryMethodKind(NumberType); if (!Kind) { if (isLiteral) { S.Diag(Loc, diag::err_invalid_nsnumber_type) << NumberType << R; } return 0; } // If we already looked up this method, we're done. if (S.NSNumberLiteralMethods[*Kind]) return S.NSNumberLiteralMethods[*Kind]; Selector Sel = S.NSAPIObj->getNSNumberLiteralSelector(*Kind, /*Instance=*/false); ASTContext &CX = S.Context; // Look up the NSNumber class, if we haven't done so already. It's cached // in the Sema instance. if (!S.NSNumberDecl) { IdentifierInfo *NSNumberId = S.NSAPIObj->getNSClassId(NSAPI::ClassId_NSNumber); NamedDecl *IF = S.LookupSingleName(S.TUScope, NSNumberId, Loc, Sema::LookupOrdinaryName); S.NSNumberDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); if (!S.NSNumberDecl) { if (S.getLangOpts().DebuggerObjCLiteral) { // Create a stub definition of NSNumber. S.NSNumberDecl = ObjCInterfaceDecl::Create(CX, CX.getTranslationUnitDecl(), SourceLocation(), NSNumberId, 0, SourceLocation()); } else { // Otherwise, require a declaration of NSNumber. S.Diag(Loc, diag::err_undeclared_nsnumber); return 0; } } else if (!S.NSNumberDecl->hasDefinition()) { S.Diag(Loc, diag::err_undeclared_nsnumber); return 0; } // generate the pointer to NSNumber type. QualType NSNumberObject = CX.getObjCInterfaceType(S.NSNumberDecl); S.NSNumberPointer = CX.getObjCObjectPointerType(NSNumberObject); } // Look for the appropriate method within NSNumber. ObjCMethodDecl *Method = S.NSNumberDecl->lookupClassMethod(Sel); if (!Method && S.getLangOpts().DebuggerObjCLiteral) { // create a stub definition this NSNumber factory method. TypeSourceInfo *ReturnTInfo = 0; Method = ObjCMethodDecl::Create(CX, SourceLocation(), SourceLocation(), Sel, S.NSNumberPointer, ReturnTInfo, S.NSNumberDecl, /*isInstance=*/false, /*isVariadic=*/false, /*isPropertyAccessor=*/false, /*isImplicitlyDeclared=*/true, /*isDefined=*/false, ObjCMethodDecl::Required, /*HasRelatedResultType=*/false); ParmVarDecl *value = ParmVarDecl::Create(S.Context, Method, SourceLocation(), SourceLocation(), &CX.Idents.get("value"), NumberType, /*TInfo=*/0, SC_None, 0); Method->setMethodParams(S.Context, value, None); } if (!validateBoxingMethod(S, Loc, S.NSNumberDecl, Sel, Method)) return 0; // Note: if the parameter type is out-of-line, we'll catch it later in the // implicit conversion. S.NSNumberLiteralMethods[*Kind] = Method; return Method; } /// BuildObjCNumericLiteral - builds an ObjCBoxedExpr AST node for the /// numeric literal expression. Type of the expression will be "NSNumber *". ExprResult Sema::BuildObjCNumericLiteral(SourceLocation AtLoc, Expr *Number) { // Determine the type of the literal. QualType NumberType = Number->getType(); if (CharacterLiteral *Char = dyn_cast<CharacterLiteral>(Number)) { // In C, character literals have type 'int'. That's not the type we want // to use to determine the Objective-c literal kind. switch (Char->getKind()) { case CharacterLiteral::Ascii: NumberType = Context.CharTy; break; case CharacterLiteral::Wide: NumberType = Context.getWideCharType(); break; case CharacterLiteral::UTF16: NumberType = Context.Char16Ty; break; case CharacterLiteral::UTF32: NumberType = Context.Char32Ty; break; } } // Look for the appropriate method within NSNumber. // Construct the literal. SourceRange NR(Number->getSourceRange()); ObjCMethodDecl *Method = getNSNumberFactoryMethod(*this, AtLoc, NumberType, true, NR); if (!Method) return ExprError(); // Convert the number to the type that the parameter expects. ParmVarDecl *ParamDecl = Method->param_begin()[0]; InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, ParamDecl); ExprResult ConvertedNumber = PerformCopyInitialization(Entity, SourceLocation(), Owned(Number)); if (ConvertedNumber.isInvalid()) return ExprError(); Number = ConvertedNumber.get(); // Use the effective source range of the literal, including the leading '@'. return MaybeBindToTemporary( new (Context) ObjCBoxedExpr(Number, NSNumberPointer, Method, SourceRange(AtLoc, NR.getEnd()))); } ExprResult Sema::ActOnObjCBoolLiteral(SourceLocation AtLoc, SourceLocation ValueLoc, bool Value) { ExprResult Inner; if (getLangOpts().CPlusPlus) { Inner = ActOnCXXBoolLiteral(ValueLoc, Value? tok::kw_true : tok::kw_false); } else { // C doesn't actually have a way to represent literal values of type // _Bool. So, we'll use 0/1 and implicit cast to _Bool. Inner = ActOnIntegerConstant(ValueLoc, Value? 1 : 0); Inner = ImpCastExprToType(Inner.get(), Context.BoolTy, CK_IntegralToBoolean); } return BuildObjCNumericLiteral(AtLoc, Inner.get()); } /// \brief Check that the given expression is a valid element of an Objective-C /// collection literal. static ExprResult CheckObjCCollectionLiteralElement(Sema &S, Expr *Element, QualType T, bool ArrayLiteral = false) { // If the expression is type-dependent, there's nothing for us to do. if (Element->isTypeDependent()) return Element; ExprResult Result = S.CheckPlaceholderExpr(Element); if (Result.isInvalid()) return ExprError(); Element = Result.get(); // In C++, check for an implicit conversion to an Objective-C object pointer // type. if (S.getLangOpts().CPlusPlus && Element->getType()->isRecordType()) { InitializedEntity Entity = InitializedEntity::InitializeParameter(S.Context, T, /*Consumed=*/false); InitializationKind Kind = InitializationKind::CreateCopy(Element->getLocStart(), SourceLocation()); InitializationSequence Seq(S, Entity, Kind, Element); if (!Seq.Failed()) return Seq.Perform(S, Entity, Kind, Element); } Expr *OrigElement = Element; // Perform lvalue-to-rvalue conversion. Result = S.DefaultLvalueConversion(Element); if (Result.isInvalid()) return ExprError(); Element = Result.get(); // Make sure that we have an Objective-C pointer type or block. if (!Element->getType()->isObjCObjectPointerType() && !Element->getType()->isBlockPointerType()) { bool Recovered = false; // If this is potentially an Objective-C numeric literal, add the '@'. if (isa<IntegerLiteral>(OrigElement) || isa<CharacterLiteral>(OrigElement) || isa<FloatingLiteral>(OrigElement) || isa<ObjCBoolLiteralExpr>(OrigElement) || isa<CXXBoolLiteralExpr>(OrigElement)) { if (S.NSAPIObj->getNSNumberFactoryMethodKind(OrigElement->getType())) { int Which = isa<CharacterLiteral>(OrigElement) ? 1 : (isa<CXXBoolLiteralExpr>(OrigElement) || isa<ObjCBoolLiteralExpr>(OrigElement)) ? 2 : 3; S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection) << Which << OrigElement->getSourceRange() << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@"); Result = S.BuildObjCNumericLiteral(OrigElement->getLocStart(), OrigElement); if (Result.isInvalid()) return ExprError(); Element = Result.get(); Recovered = true; } } // If this is potentially an Objective-C string literal, add the '@'. else if (StringLiteral *String = dyn_cast<StringLiteral>(OrigElement)) { if (String->isAscii()) { S.Diag(OrigElement->getLocStart(), diag::err_box_literal_collection) << 0 << OrigElement->getSourceRange() << FixItHint::CreateInsertion(OrigElement->getLocStart(), "@"); Result = S.BuildObjCStringLiteral(OrigElement->getLocStart(), String); if (Result.isInvalid()) return ExprError(); Element = Result.get(); Recovered = true; } } if (!Recovered) { S.Diag(Element->getLocStart(), diag::err_invalid_collection_element) << Element->getType(); return ExprError(); } } if (ArrayLiteral) if (ObjCStringLiteral *getString = dyn_cast<ObjCStringLiteral>(OrigElement)) { if (StringLiteral *SL = getString->getString()) { unsigned numConcat = SL->getNumConcatenated(); if (numConcat > 1) { // Only warn if the concatenated string doesn't come from a macro. bool hasMacro = false; for (unsigned i = 0; i < numConcat ; ++i) if (SL->getStrTokenLoc(i).isMacroID()) { hasMacro = true; break; } if (!hasMacro) S.Diag(Element->getLocStart(), diag::warn_concatenated_nsarray_literal) << Element->getType(); } } } // Make sure that the element has the type that the container factory // function expects. return S.PerformCopyInitialization( InitializedEntity::InitializeParameter(S.Context, T, /*Consumed=*/false), Element->getLocStart(), Element); } ExprResult Sema::BuildObjCBoxedExpr(SourceRange SR, Expr *ValueExpr) { if (ValueExpr->isTypeDependent()) { ObjCBoxedExpr *BoxedExpr = new (Context) ObjCBoxedExpr(ValueExpr, Context.DependentTy, NULL, SR); return Owned(BoxedExpr); } ObjCMethodDecl *BoxingMethod = NULL; QualType BoxedType; // Convert the expression to an RValue, so we can check for pointer types... ExprResult RValue = DefaultFunctionArrayLvalueConversion(ValueExpr); if (RValue.isInvalid()) { return ExprError(); } ValueExpr = RValue.get(); QualType ValueType(ValueExpr->getType()); if (const PointerType *PT = ValueType->getAs<PointerType>()) { QualType PointeeType = PT->getPointeeType(); if (Context.hasSameUnqualifiedType(PointeeType, Context.CharTy)) { if (!NSStringDecl) { IdentifierInfo *NSStringId = NSAPIObj->getNSClassId(NSAPI::ClassId_NSString); NamedDecl *Decl = LookupSingleName(TUScope, NSStringId, SR.getBegin(), LookupOrdinaryName); NSStringDecl = dyn_cast_or_null<ObjCInterfaceDecl>(Decl); if (!NSStringDecl) { if (getLangOpts().DebuggerObjCLiteral) { // Support boxed expressions in the debugger w/o NSString declaration. DeclContext *TU = Context.getTranslationUnitDecl(); NSStringDecl = ObjCInterfaceDecl::Create(Context, TU, SourceLocation(), NSStringId, 0, SourceLocation()); } else { Diag(SR.getBegin(), diag::err_undeclared_nsstring); return ExprError(); } } else if (!NSStringDecl->hasDefinition()) { Diag(SR.getBegin(), diag::err_undeclared_nsstring); return ExprError(); } assert(NSStringDecl && "NSStringDecl should not be NULL"); QualType NSStringObject = Context.getObjCInterfaceType(NSStringDecl); NSStringPointer = Context.getObjCObjectPointerType(NSStringObject); } if (!StringWithUTF8StringMethod) { IdentifierInfo *II = &Context.Idents.get("stringWithUTF8String"); Selector stringWithUTF8String = Context.Selectors.getUnarySelector(II); // Look for the appropriate method within NSString. BoxingMethod = NSStringDecl->lookupClassMethod(stringWithUTF8String); if (!BoxingMethod && getLangOpts().DebuggerObjCLiteral) { // Debugger needs to work even if NSString hasn't been defined. TypeSourceInfo *ReturnTInfo = 0; ObjCMethodDecl *M = ObjCMethodDecl::Create( Context, SourceLocation(), SourceLocation(), stringWithUTF8String, NSStringPointer, ReturnTInfo, NSStringDecl, /*isInstance=*/false, /*isVariadic=*/false, /*isPropertyAccessor=*/false, /*isImplicitlyDeclared=*/true, /*isDefined=*/false, ObjCMethodDecl::Required, /*HasRelatedResultType=*/false); QualType ConstCharType = Context.CharTy.withConst(); ParmVarDecl *value = ParmVarDecl::Create(Context, M, SourceLocation(), SourceLocation(), &Context.Idents.get("value"), Context.getPointerType(ConstCharType), /*TInfo=*/0, SC_None, 0); M->setMethodParams(Context, value, None); BoxingMethod = M; } if (!validateBoxingMethod(*this, SR.getBegin(), NSStringDecl, stringWithUTF8String, BoxingMethod)) return ExprError(); StringWithUTF8StringMethod = BoxingMethod; } BoxingMethod = StringWithUTF8StringMethod; BoxedType = NSStringPointer; } } else if (ValueType->isBuiltinType()) { // The other types we support are numeric, char and BOOL/bool. We could also // provide limited support for structure types, such as NSRange, NSRect, and // NSSize. See NSValue (NSValueGeometryExtensions) in <Foundation/NSGeometry.h> // for more details. // Check for a top-level character literal. if (const CharacterLiteral *Char = dyn_cast<CharacterLiteral>(ValueExpr->IgnoreParens())) { // In C, character literals have type 'int'. That's not the type we want // to use to determine the Objective-c literal kind. switch (Char->getKind()) { case CharacterLiteral::Ascii: ValueType = Context.CharTy; break; case CharacterLiteral::Wide: ValueType = Context.getWideCharType(); break; case CharacterLiteral::UTF16: ValueType = Context.Char16Ty; break; case CharacterLiteral::UTF32: ValueType = Context.Char32Ty; break; } } // FIXME: Do I need to do anything special with BoolTy expressions? // Look for the appropriate method within NSNumber. BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ValueType); BoxedType = NSNumberPointer; } else if (const EnumType *ET = ValueType->getAs<EnumType>()) { if (!ET->getDecl()->isComplete()) { Diag(SR.getBegin(), diag::err_objc_incomplete_boxed_expression_type) << ValueType << ValueExpr->getSourceRange(); return ExprError(); } BoxingMethod = getNSNumberFactoryMethod(*this, SR.getBegin(), ET->getDecl()->getIntegerType()); BoxedType = NSNumberPointer; } if (!BoxingMethod) { Diag(SR.getBegin(), diag::err_objc_illegal_boxed_expression_type) << ValueType << ValueExpr->getSourceRange(); return ExprError(); } // Convert the expression to the type that the parameter requires. ParmVarDecl *ParamDecl = BoxingMethod->param_begin()[0]; InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, ParamDecl); ExprResult ConvertedValueExpr = PerformCopyInitialization(Entity, SourceLocation(), Owned(ValueExpr)); if (ConvertedValueExpr.isInvalid()) return ExprError(); ValueExpr = ConvertedValueExpr.get(); ObjCBoxedExpr *BoxedExpr = new (Context) ObjCBoxedExpr(ValueExpr, BoxedType, BoxingMethod, SR); return MaybeBindToTemporary(BoxedExpr); } /// Build an ObjC subscript pseudo-object expression, given that /// that's supported by the runtime. ExprResult Sema::BuildObjCSubscriptExpression(SourceLocation RB, Expr *BaseExpr, Expr *IndexExpr, ObjCMethodDecl *getterMethod, ObjCMethodDecl *setterMethod) { assert(!LangOpts.isSubscriptPointerArithmetic()); // We can't get dependent types here; our callers should have // filtered them out. assert((!BaseExpr->isTypeDependent() && !IndexExpr->isTypeDependent()) && "base or index cannot have dependent type here"); // Filter out placeholders in the index. In theory, overloads could // be preserved here, although that might not actually work correctly. ExprResult Result = CheckPlaceholderExpr(IndexExpr); if (Result.isInvalid()) return ExprError(); IndexExpr = Result.get(); // Perform lvalue-to-rvalue conversion on the base. Result = DefaultLvalueConversion(BaseExpr); if (Result.isInvalid()) return ExprError(); BaseExpr = Result.get(); // Build the pseudo-object expression. return Owned(ObjCSubscriptRefExpr::Create(Context, BaseExpr, IndexExpr, Context.PseudoObjectTy, getterMethod, setterMethod, RB)); } ExprResult Sema::BuildObjCArrayLiteral(SourceRange SR, MultiExprArg Elements) { // Look up the NSArray class, if we haven't done so already. if (!NSArrayDecl) { NamedDecl *IF = LookupSingleName(TUScope, NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray), SR.getBegin(), LookupOrdinaryName); NSArrayDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); if (!NSArrayDecl && getLangOpts().DebuggerObjCLiteral) NSArrayDecl = ObjCInterfaceDecl::Create (Context, Context.getTranslationUnitDecl(), SourceLocation(), NSAPIObj->getNSClassId(NSAPI::ClassId_NSArray), 0, SourceLocation()); if (!NSArrayDecl) { Diag(SR.getBegin(), diag::err_undeclared_nsarray); return ExprError(); } } // Find the arrayWithObjects:count: method, if we haven't done so already. QualType IdT = Context.getObjCIdType(); if (!ArrayWithObjectsMethod) { Selector Sel = NSAPIObj->getNSArraySelector(NSAPI::NSArr_arrayWithObjectsCount); ObjCMethodDecl *Method = NSArrayDecl->lookupClassMethod(Sel); if (!Method && getLangOpts().DebuggerObjCLiteral) { TypeSourceInfo *ReturnTInfo = 0; Method = ObjCMethodDecl::Create( Context, SourceLocation(), SourceLocation(), Sel, IdT, ReturnTInfo, Context.getTranslationUnitDecl(), false /*Instance*/, false /*isVariadic*/, /*isPropertyAccessor=*/false, /*isImplicitlyDeclared=*/true, /*isDefined=*/false, ObjCMethodDecl::Required, false); SmallVector<ParmVarDecl *, 2> Params; ParmVarDecl *objects = ParmVarDecl::Create(Context, Method, SourceLocation(), SourceLocation(), &Context.Idents.get("objects"), Context.getPointerType(IdT), /*TInfo=*/0, SC_None, 0); Params.push_back(objects); ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method, SourceLocation(), SourceLocation(), &Context.Idents.get("cnt"), Context.UnsignedLongTy, /*TInfo=*/0, SC_None, 0); Params.push_back(cnt); Method->setMethodParams(Context, Params, None); } if (!validateBoxingMethod(*this, SR.getBegin(), NSArrayDecl, Sel, Method)) return ExprError(); // Dig out the type that all elements should be converted to. QualType T = Method->param_begin()[0]->getType(); const PointerType *PtrT = T->getAs<PointerType>(); if (!PtrT || !Context.hasSameUnqualifiedType(PtrT->getPointeeType(), IdT)) { Diag(SR.getBegin(), diag::err_objc_literal_method_sig) << Sel; Diag(Method->param_begin()[0]->getLocation(), diag::note_objc_literal_method_param) << 0 << T << Context.getPointerType(IdT.withConst()); return ExprError(); } // Check that the 'count' parameter is integral. if (!Method->param_begin()[1]->getType()->isIntegerType()) { Diag(SR.getBegin(), diag::err_objc_literal_method_sig) << Sel; Diag(Method->param_begin()[1]->getLocation(), diag::note_objc_literal_method_param) << 1 << Method->param_begin()[1]->getType() << "integral"; return ExprError(); } // We've found a good +arrayWithObjects:count: method. Save it! ArrayWithObjectsMethod = Method; } QualType ObjectsType = ArrayWithObjectsMethod->param_begin()[0]->getType(); QualType RequiredType = ObjectsType->castAs<PointerType>()->getPointeeType(); // Check that each of the elements provided is valid in a collection literal, // performing conversions as necessary. Expr **ElementsBuffer = Elements.data(); for (unsigned I = 0, N = Elements.size(); I != N; ++I) { ExprResult Converted = CheckObjCCollectionLiteralElement(*this, ElementsBuffer[I], RequiredType, true); if (Converted.isInvalid()) return ExprError(); ElementsBuffer[I] = Converted.get(); } QualType Ty = Context.getObjCObjectPointerType( Context.getObjCInterfaceType(NSArrayDecl)); return MaybeBindToTemporary( ObjCArrayLiteral::Create(Context, Elements, Ty, ArrayWithObjectsMethod, SR)); } ExprResult Sema::BuildObjCDictionaryLiteral(SourceRange SR, ObjCDictionaryElement *Elements, unsigned NumElements) { // Look up the NSDictionary class, if we haven't done so already. if (!NSDictionaryDecl) { NamedDecl *IF = LookupSingleName(TUScope, NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary), SR.getBegin(), LookupOrdinaryName); NSDictionaryDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF); if (!NSDictionaryDecl && getLangOpts().DebuggerObjCLiteral) NSDictionaryDecl = ObjCInterfaceDecl::Create (Context, Context.getTranslationUnitDecl(), SourceLocation(), NSAPIObj->getNSClassId(NSAPI::ClassId_NSDictionary), 0, SourceLocation()); if (!NSDictionaryDecl) { Diag(SR.getBegin(), diag::err_undeclared_nsdictionary); return ExprError(); } } // Find the dictionaryWithObjects:forKeys:count: method, if we haven't done // so already. QualType IdT = Context.getObjCIdType(); if (!DictionaryWithObjectsMethod) { Selector Sel = NSAPIObj->getNSDictionarySelector( NSAPI::NSDict_dictionaryWithObjectsForKeysCount); ObjCMethodDecl *Method = NSDictionaryDecl->lookupClassMethod(Sel); if (!Method && getLangOpts().DebuggerObjCLiteral) { Method = ObjCMethodDecl::Create(Context, SourceLocation(), SourceLocation(), Sel, IdT, 0 /*TypeSourceInfo */, Context.getTranslationUnitDecl(), false /*Instance*/, false/*isVariadic*/, /*isPropertyAccessor=*/false, /*isImplicitlyDeclared=*/true, /*isDefined=*/false, ObjCMethodDecl::Required, false); SmallVector<ParmVarDecl *, 3> Params; ParmVarDecl *objects = ParmVarDecl::Create(Context, Method, SourceLocation(), SourceLocation(), &Context.Idents.get("objects"), Context.getPointerType(IdT), /*TInfo=*/0, SC_None, 0); Params.push_back(objects); ParmVarDecl *keys = ParmVarDecl::Create(Context, Method, SourceLocation(), SourceLocation(), &Context.Idents.get("keys"), Context.getPointerType(IdT), /*TInfo=*/0, SC_None, 0); Params.push_back(keys); ParmVarDecl *cnt = ParmVarDecl::Create(Context, Method, SourceLocation(), SourceLocation(), &Context.Idents.get("cnt"), Context.UnsignedLongTy, /*TInfo=*/0, SC_None, 0); Params.push_back(cnt); Method->setMethodParams(Context, Params, None); } if (!validateBoxingMethod(*this, SR.getBegin(), NSDictionaryDecl, Sel, Method)) return ExprError(); // Dig out the type that all values should be converted to. QualType ValueT = Method->param_begin()[0]->getType(); const PointerType *PtrValue = ValueT->getAs<PointerType>(); if (!PtrValue || !Context.hasSameUnqualifiedType(PtrValue->getPointeeType(), IdT)) { Diag(SR.getBegin(), diag::err_objc_literal_method_sig) << Sel; Diag(Method->param_begin()[0]->getLocation(), diag::note_objc_literal_method_param) << 0 << ValueT << Context.getPointerType(IdT.withConst()); return ExprError(); } // Dig out the type that all keys should be converted to. QualType KeyT = Method->param_begin()[1]->getType(); const PointerType *PtrKey = KeyT->getAs<PointerType>(); if (!PtrKey || !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(), IdT)) { bool err = true; if (PtrKey) { if (QIDNSCopying.isNull()) { // key argument of selector is id<NSCopying>? if (ObjCProtocolDecl *NSCopyingPDecl = LookupProtocol(&Context.Idents.get("NSCopying"), SR.getBegin())) { ObjCProtocolDecl *PQ[] = {NSCopyingPDecl}; QIDNSCopying = Context.getObjCObjectType(Context.ObjCBuiltinIdTy, (ObjCProtocolDecl**) PQ,1); QIDNSCopying = Context.getObjCObjectPointerType(QIDNSCopying); } } if (!QIDNSCopying.isNull()) err = !Context.hasSameUnqualifiedType(PtrKey->getPointeeType(), QIDNSCopying); } if (err) { Diag(SR.getBegin(), diag::err_objc_literal_method_sig) << Sel; Diag(Method->param_begin()[1]->getLocation(), diag::note_objc_literal_method_param) << 1 << KeyT << Context.getPointerType(IdT.withConst()); return ExprError(); } } // Check that the 'count' parameter is integral. QualType CountType = Method->param_begin()[2]->getType(); if (!CountType->isIntegerType()) { Diag(SR.getBegin(), diag::err_objc_literal_method_sig) << Sel; Diag(Method->param_begin()[2]->getLocation(), diag::note_objc_literal_method_param) << 2 << CountType << "integral"; return ExprError(); } // We've found a good +dictionaryWithObjects:keys:count: method; save it! DictionaryWithObjectsMethod = Method; } QualType ValuesT = DictionaryWithObjectsMethod->param_begin()[0]->getType(); QualType ValueT = ValuesT->castAs<PointerType>()->getPointeeType(); QualType KeysT = DictionaryWithObjectsMethod->param_begin()[1]->getType(); QualType KeyT = KeysT->castAs<PointerType>()->getPointeeType(); // Check that each of the keys and values provided is valid in a collection // literal, performing conversions as necessary. bool HasPackExpansions = false; for (unsigned I = 0, N = NumElements; I != N; ++I) { // Check the key. ExprResult Key = CheckObjCCollectionLiteralElement(*this, Elements[I].Key, KeyT); if (Key.isInvalid()) return ExprError(); // Check the value. ExprResult Value = CheckObjCCollectionLiteralElement(*this, Elements[I].Value, ValueT); if (Value.isInvalid()) return ExprError(); Elements[I].Key = Key.get(); Elements[I].Value = Value.get(); if (Elements[I].EllipsisLoc.isInvalid()) continue; if (!Elements[I].Key->containsUnexpandedParameterPack() && !Elements[I].Value->containsUnexpandedParameterPack()) { Diag(Elements[I].EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) << SourceRange(Elements[I].Key->getLocStart(), Elements[I].Value->getLocEnd()); return ExprError(); } HasPackExpansions = true; } QualType Ty = Context.getObjCObjectPointerType( Context.getObjCInterfaceType(NSDictionaryDecl)); return MaybeBindToTemporary(ObjCDictionaryLiteral::Create( Context, makeArrayRef(Elements, NumElements), HasPackExpansions, Ty, DictionaryWithObjectsMethod, SR)); } ExprResult Sema::BuildObjCEncodeExpression(SourceLocation AtLoc, TypeSourceInfo *EncodedTypeInfo, SourceLocation RParenLoc) { QualType EncodedType = EncodedTypeInfo->getType(); QualType StrTy; if (EncodedType->isDependentType()) StrTy = Context.DependentTy; else { if (!EncodedType->getAsArrayTypeUnsafe() && //// Incomplete array is handled. !EncodedType->isVoidType()) // void is handled too. if (RequireCompleteType(AtLoc, EncodedType, diag::err_incomplete_type_objc_at_encode, EncodedTypeInfo->getTypeLoc())) return ExprError(); std::string Str; Context.getObjCEncodingForType(EncodedType, Str); // The type of @encode is the same as the type of the corresponding string, // which is an array type. StrTy = Context.CharTy; // A C++ string literal has a const-qualified element type (C++ 2.13.4p1). if (getLangOpts().CPlusPlus || getLangOpts().ConstStrings) StrTy.addConst(); StrTy = Context.getConstantArrayType(StrTy, llvm::APInt(32, Str.size()+1), ArrayType::Normal, 0); } return new (Context) ObjCEncodeExpr(StrTy, EncodedTypeInfo, AtLoc, RParenLoc); } ExprResult Sema::ParseObjCEncodeExpression(SourceLocation AtLoc, SourceLocation EncodeLoc, SourceLocation LParenLoc, ParsedType ty, SourceLocation RParenLoc) { // FIXME: Preserve type source info ? TypeSourceInfo *TInfo; QualType EncodedType = GetTypeFromParser(ty, &TInfo); if (!TInfo) TInfo = Context.getTrivialTypeSourceInfo(EncodedType, PP.getLocForEndOfToken(LParenLoc)); return BuildObjCEncodeExpression(AtLoc, TInfo, RParenLoc); } ExprResult Sema::ParseObjCSelectorExpression(Selector Sel, SourceLocation AtLoc, SourceLocation SelLoc, SourceLocation LParenLoc, SourceLocation RParenLoc) { ObjCMethodDecl *Method = LookupInstanceMethodInGlobalPool(Sel, SourceRange(LParenLoc, RParenLoc), false, false); if (!Method) Method = LookupFactoryMethodInGlobalPool(Sel, SourceRange(LParenLoc, RParenLoc)); if (!Method) { if (const ObjCMethodDecl *OM = SelectorsForTypoCorrection(Sel)) { Selector MatchedSel = OM->getSelector(); SourceRange SelectorRange(LParenLoc.getLocWithOffset(1), RParenLoc.getLocWithOffset(-1)); Diag(SelLoc, diag::warn_undeclared_selector_with_typo) << Sel << MatchedSel << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString()); } else Diag(SelLoc, diag::warn_undeclared_selector) << Sel; } if (!Method || Method->getImplementationControl() != ObjCMethodDecl::Optional) { llvm::DenseMap<Selector, SourceLocation>::iterator Pos = ReferencedSelectors.find(Sel); if (Pos == ReferencedSelectors.end()) ReferencedSelectors.insert(std::make_pair(Sel, AtLoc)); } // In ARC, forbid the user from using @selector for // retain/release/autorelease/dealloc/retainCount. if (getLangOpts().ObjCAutoRefCount) { switch (Sel.getMethodFamily()) { case OMF_retain: case OMF_release: case OMF_autorelease: case OMF_retainCount: case OMF_dealloc: Diag(AtLoc, diag::err_arc_illegal_selector) << Sel << SourceRange(LParenLoc, RParenLoc); break; case OMF_None: case OMF_alloc: case OMF_copy: case OMF_finalize: case OMF_init: case OMF_mutableCopy: case OMF_new: case OMF_self: case OMF_performSelector: break; } } QualType Ty = Context.getObjCSelType(); return new (Context) ObjCSelectorExpr(Ty, Sel, AtLoc, RParenLoc); } ExprResult Sema::ParseObjCProtocolExpression(IdentifierInfo *ProtocolId, SourceLocation AtLoc, SourceLocation ProtoLoc, SourceLocation LParenLoc, SourceLocation ProtoIdLoc, SourceLocation RParenLoc) { ObjCProtocolDecl* PDecl = LookupProtocol(ProtocolId, ProtoIdLoc); if (!PDecl) { Diag(ProtoLoc, diag::err_undeclared_protocol) << ProtocolId; return true; } QualType Ty = Context.getObjCProtoType(); if (Ty.isNull()) return true; Ty = Context.getObjCObjectPointerType(Ty); return new (Context) ObjCProtocolExpr(Ty, PDecl, AtLoc, ProtoIdLoc, RParenLoc); } /// Try to capture an implicit reference to 'self'. ObjCMethodDecl *Sema::tryCaptureObjCSelf(SourceLocation Loc) { DeclContext *DC = getFunctionLevelDeclContext(); // If we're not in an ObjC method, error out. Note that, unlike the // C++ case, we don't require an instance method --- class methods // still have a 'self', and we really do still need to capture it! ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(DC); if (!method) return 0; tryCaptureVariable(method->getSelfDecl(), Loc); return method; } static QualType stripObjCInstanceType(ASTContext &Context, QualType T) { if (T == Context.getObjCInstanceType()) return Context.getObjCIdType(); return T; } QualType Sema::getMessageSendResultType(QualType ReceiverType, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage) { assert(Method && "Must have a method"); if (!Method->hasRelatedResultType()) return Method->getSendResultType(); // If a method has a related return type: // - if the method found is an instance method, but the message send // was a class message send, T is the declared return type of the method // found if (Method->isInstanceMethod() && isClassMessage) return stripObjCInstanceType(Context, Method->getSendResultType()); // - if the receiver is super, T is a pointer to the class of the // enclosing method definition if (isSuperMessage) { if (ObjCMethodDecl *CurMethod = getCurMethodDecl()) if (ObjCInterfaceDecl *Class = CurMethod->getClassInterface()) return Context.getObjCObjectPointerType( Context.getObjCInterfaceType(Class)); } // - if the receiver is the name of a class U, T is a pointer to U if (ReceiverType->getAs<ObjCInterfaceType>() || ReceiverType->isObjCQualifiedInterfaceType()) return Context.getObjCObjectPointerType(ReceiverType); // - if the receiver is of type Class or qualified Class type, // T is the declared return type of the method. if (ReceiverType->isObjCClassType() || ReceiverType->isObjCQualifiedClassType()) return stripObjCInstanceType(Context, Method->getSendResultType()); // - if the receiver is id, qualified id, Class, or qualified Class, T // is the receiver type, otherwise // - T is the type of the receiver expression. return ReceiverType; } /// Look for an ObjC method whose result type exactly matches the given type. static const ObjCMethodDecl * findExplicitInstancetypeDeclarer(const ObjCMethodDecl *MD, QualType instancetype) { if (MD->getReturnType() == instancetype) return MD; // For these purposes, a method in an @implementation overrides a // declaration in the @interface. if (const ObjCImplDecl *impl = dyn_cast<ObjCImplDecl>(MD->getDeclContext())) { const ObjCContainerDecl *iface; if (const ObjCCategoryImplDecl *catImpl = dyn_cast<ObjCCategoryImplDecl>(impl)) { iface = catImpl->getCategoryDecl(); } else { iface = impl->getClassInterface(); } const ObjCMethodDecl *ifaceMD = iface->getMethod(MD->getSelector(), MD->isInstanceMethod()); if (ifaceMD) return findExplicitInstancetypeDeclarer(ifaceMD, instancetype); } SmallVector<const ObjCMethodDecl *, 4> overrides; MD->getOverriddenMethods(overrides); for (unsigned i = 0, e = overrides.size(); i != e; ++i) { if (const ObjCMethodDecl *result = findExplicitInstancetypeDeclarer(overrides[i], instancetype)) return result; } return 0; } void Sema::EmitRelatedResultTypeNoteForReturn(QualType destType) { // Only complain if we're in an ObjC method and the required return // type doesn't match the method's declared return type. ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(CurContext); if (!MD || !MD->hasRelatedResultType() || Context.hasSameUnqualifiedType(destType, MD->getReturnType())) return; // Look for a method overridden by this method which explicitly uses // 'instancetype'. if (const ObjCMethodDecl *overridden = findExplicitInstancetypeDeclarer(MD, Context.getObjCInstanceType())) { SourceLocation loc; SourceRange range; if (TypeSourceInfo *TSI = overridden->getReturnTypeSourceInfo()) { range = TSI->getTypeLoc().getSourceRange(); loc = range.getBegin(); } if (loc.isInvalid()) loc = overridden->getLocation(); Diag(loc, diag::note_related_result_type_explicit) << /*current method*/ 1 << range; return; } // Otherwise, if we have an interesting method family, note that. // This should always trigger if the above didn't. if (ObjCMethodFamily family = MD->getMethodFamily()) Diag(MD->getLocation(), diag::note_related_result_type_family) << /*current method*/ 1 << family; } void Sema::EmitRelatedResultTypeNote(const Expr *E) { E = E->IgnoreParenImpCasts(); const ObjCMessageExpr *MsgSend = dyn_cast<ObjCMessageExpr>(E); if (!MsgSend) return; const ObjCMethodDecl *Method = MsgSend->getMethodDecl(); if (!Method) return; if (!Method->hasRelatedResultType()) return; if (Context.hasSameUnqualifiedType( Method->getReturnType().getNonReferenceType(), MsgSend->getType())) return; if (!Context.hasSameUnqualifiedType(Method->getReturnType(), Context.getObjCInstanceType())) return; Diag(Method->getLocation(), diag::note_related_result_type_inferred) << Method->isInstanceMethod() << Method->getSelector() << MsgSend->getType(); } bool Sema::CheckMessageArgumentTypes(QualType ReceiverType, MultiExprArg Args, Selector Sel, ArrayRef<SourceLocation> SelectorLocs, ObjCMethodDecl *Method, bool isClassMessage, bool isSuperMessage, SourceLocation lbrac, SourceLocation rbrac, QualType &ReturnType, ExprValueKind &VK) { SourceLocation SelLoc; if (!SelectorLocs.empty() && SelectorLocs.front().isValid()) SelLoc = SelectorLocs.front(); else SelLoc = lbrac; if (!Method) { // Apply default argument promotion as for (C99 6.5.2.2p6). for (unsigned i = 0, e = Args.size(); i != e; i++) { if (Args[i]->isTypeDependent()) continue; ExprResult result; if (getLangOpts().DebuggerSupport) { QualType paramTy; // ignored result = checkUnknownAnyArg(SelLoc, Args[i], paramTy); } else { result = DefaultArgumentPromotion(Args[i]); } if (result.isInvalid()) return true; Args[i] = result.take(); } unsigned DiagID; if (getLangOpts().ObjCAutoRefCount) DiagID = diag::err_arc_method_not_found; else DiagID = isClassMessage ? diag::warn_class_method_not_found : diag::warn_inst_method_not_found; if (!getLangOpts().DebuggerSupport) { const ObjCMethodDecl *OMD = SelectorsForTypoCorrection(Sel, ReceiverType); if (OMD && !OMD->isInvalidDecl()) { if (getLangOpts().ObjCAutoRefCount) DiagID = diag::error_method_not_found_with_typo; else DiagID = isClassMessage ? diag::warn_class_method_not_found_with_typo : diag::warn_instance_method_not_found_with_typo; Selector MatchedSel = OMD->getSelector(); SourceRange SelectorRange(SelectorLocs.front(), SelectorLocs.back()); Diag(SelLoc, DiagID) << Sel<< isClassMessage << MatchedSel << FixItHint::CreateReplacement(SelectorRange, MatchedSel.getAsString()); } else Diag(SelLoc, DiagID) << Sel << isClassMessage << SourceRange(SelectorLocs.front(), SelectorLocs.back()); // Find the class to which we are sending this message. if (ReceiverType->isObjCObjectPointerType()) { if (ObjCInterfaceDecl *Class = ReceiverType->getAs<ObjCObjectPointerType>()->getInterfaceDecl()) Diag(Class->getLocation(), diag::note_receiver_class_declared); } } // In debuggers, we want to use __unknown_anytype for these // results so that clients can cast them. if (getLangOpts().DebuggerSupport) { ReturnType = Context.UnknownAnyTy; } else { ReturnType = Context.getObjCIdType(); } VK = VK_RValue; return false; } ReturnType = getMessageSendResultType(ReceiverType, Method, isClassMessage, isSuperMessage); VK = Expr::getValueKindForType(Method->getReturnType()); unsigned NumNamedArgs = Sel.getNumArgs(); // Method might have more arguments than selector indicates. This is due // to addition of c-style arguments in method. if (Method->param_size() > Sel.getNumArgs()) NumNamedArgs = Method->param_size(); // FIXME. This need be cleaned up. if (Args.size() < NumNamedArgs) { Diag(SelLoc, diag::err_typecheck_call_too_few_args) << 2 << NumNamedArgs << static_cast<unsigned>(Args.size()); return false; } bool IsError = false; for (unsigned i = 0; i < NumNamedArgs; i++) { // We can't do any type-checking on a type-dependent argument. if (Args[i]->isTypeDependent()) continue; Expr *argExpr = Args[i]; ParmVarDecl *param = Method->param_begin()[i]; assert(argExpr && "CheckMessageArgumentTypes(): missing expression"); // Strip the unbridged-cast placeholder expression off unless it's // a consumed argument. if (argExpr->hasPlaceholderType(BuiltinType::ARCUnbridgedCast) && !param->hasAttr<CFConsumedAttr>()) argExpr = stripARCUnbridgedCast(argExpr); // If the parameter is __unknown_anytype, infer its type // from the argument. if (param->getType() == Context.UnknownAnyTy) { QualType paramType; ExprResult argE = checkUnknownAnyArg(SelLoc, argExpr, paramType); if (argE.isInvalid()) { IsError = true; } else { Args[i] = argE.take(); // Update the parameter type in-place. param->setType(paramType); } continue; } if (RequireCompleteType(argExpr->getSourceRange().getBegin(), param->getType(), diag::err_call_incomplete_argument, argExpr)) return true; InitializedEntity Entity = InitializedEntity::InitializeParameter(Context, param); ExprResult ArgE = PerformCopyInitialization(Entity, SelLoc, Owned(argExpr)); if (ArgE.isInvalid()) IsError = true; else Args[i] = ArgE.takeAs<Expr>(); } // Promote additional arguments to variadic methods. if (Method->isVariadic()) { for (unsigned i = NumNamedArgs, e = Args.size(); i < e; ++i) { if (Args[i]->isTypeDependent()) continue; ExprResult Arg = DefaultVariadicArgumentPromotion(Args[i], VariadicMethod, 0); IsError |= Arg.isInvalid(); Args[i] = Arg.take(); } } else { // Check for extra arguments to non-variadic methods. if (Args.size() != NumNamedArgs) { Diag(Args[NumNamedArgs]->getLocStart(), diag::err_typecheck_call_too_many_args) << 2 /*method*/ << NumNamedArgs << static_cast<unsigned>(Args.size()) << Method->getSourceRange() << SourceRange(Args[NumNamedArgs]->getLocStart(), Args.back()->getLocEnd()); } } DiagnoseSentinelCalls(Method, SelLoc, Args); // Do additional checkings on method. IsError |= CheckObjCMethodCall( Method, SelLoc, makeArrayRef<const Expr *>(Args.data(), Args.size())); return IsError; } bool Sema::isSelfExpr(Expr *RExpr) { // 'self' is objc 'self' in an objc method only. ObjCMethodDecl *Method = dyn_cast_or_null<ObjCMethodDecl>(CurContext->getNonClosureAncestor()); return isSelfExpr(RExpr, Method); } bool Sema::isSelfExpr(Expr *receiver, const ObjCMethodDecl *method) { if (!method) return false; receiver = receiver->IgnoreParenLValueCasts(); if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(receiver)) if (DRE->getDecl() == method->getSelfDecl()) return true; return false; } /// LookupMethodInType - Look up a method in an ObjCObjectType. ObjCMethodDecl *Sema::LookupMethodInObjectType(Selector sel, QualType type, bool isInstance) { const ObjCObjectType *objType = type->castAs<ObjCObjectType>(); if (ObjCInterfaceDecl *iface = objType->getInterface()) { // Look it up in the main interface (and categories, etc.) if (ObjCMethodDecl *method = iface->lookupMethod(sel, isInstance)) return method; // Okay, look for "private" methods declared in any // @implementations we've seen. if (ObjCMethodDecl *method = iface->lookupPrivateMethod(sel, isInstance)) return method; } // Check qualifiers. for (ObjCObjectType::qual_iterator i = objType->qual_begin(), e = objType->qual_end(); i != e; ++i) if (ObjCMethodDecl *method = (*i)->lookupMethod(sel, isInstance)) return method; return 0; } /// LookupMethodInQualifiedType - Lookups up a method in protocol qualifier /// list of a qualified objective pointer type. ObjCMethodDecl *Sema::LookupMethodInQualifiedType(Selector Sel, const ObjCObjectPointerType *OPT, bool Instance) { ObjCMethodDecl *MD = 0; for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), E = OPT->qual_end(); I != E; ++I) { ObjCProtocolDecl *PROTO = (*I); if ((MD = PROTO->lookupMethod(Sel, Instance))) { return MD; } } return 0; } static void DiagnoseARCUseOfWeakReceiver(Sema &S, Expr *Receiver) { if (!Receiver) return; if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Receiver)) Receiver = OVE->getSourceExpr(); Expr *RExpr = Receiver->IgnoreParenImpCasts(); SourceLocation Loc = RExpr->getLocStart(); QualType T = RExpr->getType(); const ObjCPropertyDecl *PDecl = 0; const ObjCMethodDecl *GDecl = 0; if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(RExpr)) { RExpr = POE->getSyntacticForm(); if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(RExpr)) { if (PRE->isImplicitProperty()) { GDecl = PRE->getImplicitPropertyGetter(); if (GDecl) { T = GDecl->getReturnType(); } } else { PDecl = PRE->getExplicitProperty(); if (PDecl) { T = PDecl->getType(); } } } } else if (ObjCMessageExpr *ME = dyn_cast<ObjCMessageExpr>(RExpr)) { // See if receiver is a method which envokes a synthesized getter // backing a 'weak' property. ObjCMethodDecl *Method = ME->getMethodDecl(); if (Method && Method->getSelector().getNumArgs() == 0) { PDecl = Method->findPropertyDecl(); if (PDecl) T = PDecl->getType(); } } if (T.getObjCLifetime() != Qualifiers::OCL_Weak) { if (!PDecl) return; if (!(PDecl->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak)) return; } S.Diag(Loc, diag::warn_receiver_is_weak) << ((!PDecl && !GDecl) ? 0 : (PDecl ? 1 : 2)); if (PDecl) S.Diag(PDecl->getLocation(), diag::note_property_declare); else if (GDecl) S.Diag(GDecl->getLocation(), diag::note_method_declared_at) << GDecl; S.Diag(Loc, diag::note_arc_assign_to_strong); } /// HandleExprPropertyRefExpr - Handle foo.bar where foo is a pointer to an /// objective C interface. This is a property reference expression. ExprResult Sema:: HandleExprPropertyRefExpr(const ObjCObjectPointerType *OPT, Expr *BaseExpr, SourceLocation OpLoc, DeclarationName MemberName, SourceLocation MemberLoc, SourceLocation SuperLoc, QualType SuperType, bool Super) { const ObjCInterfaceType *IFaceT = OPT->getInterfaceType(); ObjCInterfaceDecl *IFace = IFaceT->getDecl(); if (!MemberName.isIdentifier()) { Diag(MemberLoc, diag::err_invalid_property_name) << MemberName << QualType(OPT, 0); return ExprError(); } IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); SourceRange BaseRange = Super? SourceRange(SuperLoc) : BaseExpr->getSourceRange(); if (RequireCompleteType(MemberLoc, OPT->getPointeeType(), diag::err_property_not_found_forward_class, MemberName, BaseRange)) return ExprError(); // Search for a declared property first. if (ObjCPropertyDecl *PD = IFace->FindPropertyDeclaration(Member)) { // Check whether we can reference this property. if (DiagnoseUseOfDecl(PD, MemberLoc)) return ExprError(); if (Super) return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc, SuperLoc, SuperType)); else return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc, BaseExpr)); } // Check protocols on qualified interfaces. for (ObjCObjectPointerType::qual_iterator I = OPT->qual_begin(), E = OPT->qual_end(); I != E; ++I) if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) { // Check whether we can reference this property. if (DiagnoseUseOfDecl(PD, MemberLoc)) return ExprError(); if (Super) return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc, SuperLoc, SuperType)); else return Owned(new (Context) ObjCPropertyRefExpr(PD, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc, BaseExpr)); } // If that failed, look for an "implicit" property by seeing if the nullary // selector is implemented. // FIXME: The logic for looking up nullary and unary selectors should be // shared with the code in ActOnInstanceMessage. Selector Sel = PP.getSelectorTable().getNullarySelector(Member); ObjCMethodDecl *Getter = IFace->lookupInstanceMethod(Sel); // May be founf in property's qualified list. if (!Getter) Getter = LookupMethodInQualifiedType(Sel, OPT, true); // If this reference is in an @implementation, check for 'private' methods. if (!Getter) Getter = IFace->lookupPrivateMethod(Sel); if (Getter) { // Check if we can reference this property. if (DiagnoseUseOfDecl(Getter, MemberLoc)) return ExprError(); } // If we found a getter then this may be a valid dot-reference, we // will look for the matching setter, in case it is needed. Selector SetterSel = SelectorTable::constructSetterSelector(PP.getIdentifierTable(), PP.getSelectorTable(), Member); ObjCMethodDecl *Setter = IFace->lookupInstanceMethod(SetterSel); // May be founf in property's qualified list. if (!Setter) Setter = LookupMethodInQualifiedType(SetterSel, OPT, true); if (!Setter) { // If this reference is in an @implementation, also check for 'private' // methods. Setter = IFace->lookupPrivateMethod(SetterSel); } if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) return ExprError(); if (Getter || Setter) { if (Super) return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc, SuperLoc, SuperType)); else return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, MemberLoc, BaseExpr)); } // Attempt to correct for typos in property names. DeclFilterCCC<ObjCPropertyDecl> Validator; if (TypoCorrection Corrected = CorrectTypo( DeclarationNameInfo(MemberName, MemberLoc), LookupOrdinaryName, NULL, NULL, Validator, IFace, false, OPT)) { diagnoseTypo(Corrected, PDiag(diag::err_property_not_found_suggest) << MemberName << QualType(OPT, 0)); DeclarationName TypoResult = Corrected.getCorrection(); return HandleExprPropertyRefExpr(OPT, BaseExpr, OpLoc, TypoResult, MemberLoc, SuperLoc, SuperType, Super); } ObjCInterfaceDecl *ClassDeclared; if (ObjCIvarDecl *Ivar = IFace->lookupInstanceVariable(Member, ClassDeclared)) { QualType T = Ivar->getType(); if (const ObjCObjectPointerType * OBJPT = T->getAsObjCInterfacePointerType()) { if (RequireCompleteType(MemberLoc, OBJPT->getPointeeType(), diag::err_property_not_as_forward_class, MemberName, BaseExpr)) return ExprError(); } Diag(MemberLoc, diag::err_ivar_access_using_property_syntax_suggest) << MemberName << QualType(OPT, 0) << Ivar->getDeclName() << FixItHint::CreateReplacement(OpLoc, "->"); return ExprError(); } Diag(MemberLoc, diag::err_property_not_found) << MemberName << QualType(OPT, 0); if (Setter) Diag(Setter->getLocation(), diag::note_getter_unavailable) << MemberName << BaseExpr->getSourceRange(); return ExprError(); } ExprResult Sema:: ActOnClassPropertyRefExpr(IdentifierInfo &receiverName, IdentifierInfo &propertyName, SourceLocation receiverNameLoc, SourceLocation propertyNameLoc) { IdentifierInfo *receiverNamePtr = &receiverName; ObjCInterfaceDecl *IFace = getObjCInterfaceDecl(receiverNamePtr, receiverNameLoc); bool IsSuper = false; if (IFace == 0) { // If the "receiver" is 'super' in a method, handle it as an expression-like // property reference. if (receiverNamePtr->isStr("super")) { IsSuper = true; if (ObjCMethodDecl *CurMethod = tryCaptureObjCSelf(receiverNameLoc)) { if (CurMethod->isInstanceMethod()) { ObjCInterfaceDecl *Super = CurMethod->getClassInterface()->getSuperClass(); if (!Super) { // The current class does not have a superclass. Diag(receiverNameLoc, diag::error_root_class_cannot_use_super) << CurMethod->getClassInterface()->getIdentifier(); return ExprError(); } QualType T = Context.getObjCInterfaceType(Super); T = Context.getObjCObjectPointerType(T); return HandleExprPropertyRefExpr(T->getAsObjCInterfacePointerType(), /*BaseExpr*/0, SourceLocation()/*OpLoc*/, &propertyName, propertyNameLoc, receiverNameLoc, T, true); } // Otherwise, if this is a class method, try dispatching to our // superclass. IFace = CurMethod->getClassInterface()->getSuperClass(); } } if (IFace == 0) { Diag(receiverNameLoc, diag::err_expected_either) << tok::identifier << tok::l_paren; return ExprError(); } } // Search for a declared property first. Selector Sel = PP.getSelectorTable().getNullarySelector(&propertyName); ObjCMethodDecl *Getter = IFace->lookupClassMethod(Sel); // If this reference is in an @implementation, check for 'private' methods. if (!Getter) if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation()) Getter = ImpDecl->getClassMethod(Sel); if (Getter) { // FIXME: refactor/share with ActOnMemberReference(). // Check if we can reference this property. if (DiagnoseUseOfDecl(Getter, propertyNameLoc)) return ExprError(); } // Look for the matching setter, in case it is needed. Selector SetterSel = SelectorTable::constructSetterSelector(PP.getIdentifierTable(), PP.getSelectorTable(), &propertyName); ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); if (!Setter) { // If this reference is in an @implementation, also check for 'private' // methods. if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) if (ObjCImplementationDecl *ImpDecl = ClassDecl->getImplementation()) Setter = ImpDecl->getClassMethod(SetterSel); } // Look through local category implementations associated with the class. if (!Setter) Setter = IFace->getCategoryClassMethod(SetterSel); if (Setter && DiagnoseUseOfDecl(Setter, propertyNameLoc)) return ExprError(); if (Getter || Setter) { if (IsSuper) return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, propertyNameLoc, receiverNameLoc, Context.getObjCInterfaceType(IFace))); return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter, Context.PseudoObjectTy, VK_LValue, OK_ObjCProperty, propertyNameLoc, receiverNameLoc, IFace)); } return ExprError(Diag(propertyNameLoc, diag::err_property_not_found) << &propertyName << Context.getObjCInterfaceType(IFace)); } namespace { class ObjCInterfaceOrSuperCCC : public CorrectionCandidateCallback { public: ObjCInterfaceOrSuperCCC(ObjCMethodDecl *Method) { // Determine whether "super" is acceptable in the current context. if (Method && Method->getClassInterface()) WantObjCSuper = Method->getClassInterface()->getSuperClass(); } bool ValidateCandidate(const TypoCorrection &candidate) override { return candidate.getCorrectionDeclAs<ObjCInterfaceDecl>() || candidate.isKeyword("super"); } }; } Sema::ObjCMessageKind Sema::getObjCMessageKind(Scope *S, IdentifierInfo *Name, SourceLocation NameLoc, bool IsSuper, bool HasTrailingDot, ParsedType &ReceiverType) { ReceiverType = ParsedType(); // If the identifier is "super" and there is no trailing dot, we're // messaging super. If the identifier is "super" and there is a // trailing dot, it's an instance message. if (IsSuper && S->isInObjcMethodScope()) return HasTrailingDot? ObjCInstanceMessage : ObjCSuperMessage; LookupResult Result(*this, Name, NameLoc, LookupOrdinaryName); LookupName(Result, S); switch (Result.getResultKind()) { case LookupResult::NotFound: // Normal name lookup didn't find anything. If we're in an // Objective-C method, look for ivars. If we find one, we're done! // FIXME: This is a hack. Ivar lookup should be part of normal // lookup. if (ObjCMethodDecl *Method = getCurMethodDecl()) { if (!Method->getClassInterface()) { // Fall back: let the parser try to parse it as an instance message. return ObjCInstanceMessage; } ObjCInterfaceDecl *ClassDeclared; if (Method->getClassInterface()->lookupInstanceVariable(Name, ClassDeclared)) return ObjCInstanceMessage; } // Break out; we'll perform typo correction below. break; case LookupResult::NotFoundInCurrentInstantiation: case LookupResult::FoundOverloaded: case LookupResult::FoundUnresolvedValue: case LookupResult::Ambiguous: Result.suppressDiagnostics(); return ObjCInstanceMessage; case LookupResult::Found: { // If the identifier is a class or not, and there is a trailing dot, // it's an instance message. if (HasTrailingDot) return ObjCInstanceMessage; // We found something. If it's a type, then we have a class // message. Otherwise, it's an instance message. NamedDecl *ND = Result.getFoundDecl(); QualType T; if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(ND)) T = Context.getObjCInterfaceType(Class); else if (TypeDecl *Type = dyn_cast<TypeDecl>(ND)) { T = Context.getTypeDeclType(Type); DiagnoseUseOfDecl(Type, NameLoc); } else return ObjCInstanceMessage; // We have a class message, and T is the type we're // messaging. Build source-location information for it. TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc); ReceiverType = CreateParsedType(T, TSInfo); return ObjCClassMessage; } } ObjCInterfaceOrSuperCCC Validator(getCurMethodDecl()); if (TypoCorrection Corrected = CorrectTypo(Result.getLookupNameInfo(), Result.getLookupKind(), S, NULL, Validator, NULL, false, NULL, false)) { if (Corrected.isKeyword()) { // If we've found the keyword "super" (the only keyword that would be // returned by CorrectTypo), this is a send to super. diagnoseTypo(Corrected, PDiag(diag::err_unknown_receiver_suggest) << Name); return ObjCSuperMessage; } else if (ObjCInterfaceDecl *Class = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) { // If we found a declaration, correct when it refers to an Objective-C // class. diagnoseTypo(Corrected, PDiag(diag::err_unknown_receiver_suggest) << Name); QualType T = Context.getObjCInterfaceType(Class); TypeSourceInfo *TSInfo = Context.getTrivialTypeSourceInfo(T, NameLoc); ReceiverType = CreateParsedType(T, TSInfo); return ObjCClassMessage; } } // Fall back: let the parser try to parse it as an instance message. return ObjCInstanceMessage; } ExprResult Sema::ActOnSuperMessage(Scope *S, SourceLocation SuperLoc, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args) { // Determine whether we are inside a method or not. ObjCMethodDecl *Method = tryCaptureObjCSelf(SuperLoc); if (!Method) { Diag(SuperLoc, diag::err_invalid_receiver_to_message_super); return ExprError(); } ObjCInterfaceDecl *Class = Method->getClassInterface(); if (!Class) { Diag(SuperLoc, diag::error_no_super_class_message) << Method->getDeclName(); return ExprError(); } ObjCInterfaceDecl *Super = Class->getSuperClass(); if (!Super) { // The current class does not have a superclass. Diag(SuperLoc, diag::error_root_class_cannot_use_super) << Class->getIdentifier(); return ExprError(); } // We are in a method whose class has a superclass, so 'super' // is acting as a keyword. if (Method->getSelector() == Sel) getCurFunction()->ObjCShouldCallSuper = false; if (Method->isInstanceMethod()) { // Since we are in an instance method, this is an instance // message to the superclass instance. QualType SuperTy = Context.getObjCInterfaceType(Super); SuperTy = Context.getObjCObjectPointerType(SuperTy); return BuildInstanceMessage(0, SuperTy, SuperLoc, Sel, /*Method=*/0, LBracLoc, SelectorLocs, RBracLoc, Args); } // Since we are in a class method, this is a class message to // the superclass. return BuildClassMessage(/*ReceiverTypeInfo=*/0, Context.getObjCInterfaceType(Super), SuperLoc, Sel, /*Method=*/0, LBracLoc, SelectorLocs, RBracLoc, Args); } ExprResult Sema::BuildClassMessageImplicit(QualType ReceiverType, bool isSuperReceiver, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args) { TypeSourceInfo *receiverTypeInfo = 0; if (!ReceiverType.isNull()) receiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType); return BuildClassMessage(receiverTypeInfo, ReceiverType, /*SuperLoc=*/isSuperReceiver ? Loc : SourceLocation(), Sel, Method, Loc, Loc, Loc, Args, /*isImplicit=*/true); } static void applyCocoaAPICheck(Sema &S, const ObjCMessageExpr *Msg, unsigned DiagID, bool (*refactor)(const ObjCMessageExpr *, const NSAPI &, edit::Commit &)) { SourceLocation MsgLoc = Msg->getExprLoc(); if (S.Diags.getDiagnosticLevel(DiagID, MsgLoc) == DiagnosticsEngine::Ignored) return; SourceManager &SM = S.SourceMgr; edit::Commit ECommit(SM, S.LangOpts); if (refactor(Msg,*S.NSAPIObj, ECommit)) { DiagnosticBuilder Builder = S.Diag(MsgLoc, DiagID) << Msg->getSelector() << Msg->getSourceRange(); // FIXME: Don't emit diagnostic at all if fixits are non-commitable. if (!ECommit.isCommitable()) return; for (edit::Commit::edit_iterator I = ECommit.edit_begin(), E = ECommit.edit_end(); I != E; ++I) { const edit::Commit::Edit &Edit = *I; switch (Edit.Kind) { case edit::Commit::Act_Insert: Builder.AddFixItHint(FixItHint::CreateInsertion(Edit.OrigLoc, Edit.Text, Edit.BeforePrev)); break; case edit::Commit::Act_InsertFromRange: Builder.AddFixItHint( FixItHint::CreateInsertionFromRange(Edit.OrigLoc, Edit.getInsertFromRange(SM), Edit.BeforePrev)); break; case edit::Commit::Act_Remove: Builder.AddFixItHint(FixItHint::CreateRemoval(Edit.getFileRange(SM))); break; } } } } static void checkCocoaAPI(Sema &S, const ObjCMessageExpr *Msg) { applyCocoaAPICheck(S, Msg, diag::warn_objc_redundant_literal_use, edit::rewriteObjCRedundantCallWithLiteral); } /// \brief Build an Objective-C class message expression. /// /// This routine takes care of both normal class messages and /// class messages to the superclass. /// /// \param ReceiverTypeInfo Type source information that describes the /// receiver of this message. This may be NULL, in which case we are /// sending to the superclass and \p SuperLoc must be a valid source /// location. /// \param ReceiverType The type of the object receiving the /// message. When \p ReceiverTypeInfo is non-NULL, this is the same /// type as that refers to. For a superclass send, this is the type of /// the superclass. /// /// \param SuperLoc The location of the "super" keyword in a /// superclass message. /// /// \param Sel The selector to which the message is being sent. /// /// \param Method The method that this class message is invoking, if /// already known. /// /// \param LBracLoc The location of the opening square bracket ']'. /// /// \param RBracLoc The location of the closing square bracket ']'. /// /// \param ArgsIn The message arguments. ExprResult Sema::BuildClassMessage(TypeSourceInfo *ReceiverTypeInfo, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg ArgsIn, bool isImplicit) { SourceLocation Loc = SuperLoc.isValid()? SuperLoc : ReceiverTypeInfo->getTypeLoc().getSourceRange().getBegin(); if (LBracLoc.isInvalid()) { Diag(Loc, diag::err_missing_open_square_message_send) << FixItHint::CreateInsertion(Loc, "["); LBracLoc = Loc; } SourceLocation SelLoc; if (!SelectorLocs.empty() && SelectorLocs.front().isValid()) SelLoc = SelectorLocs.front(); else SelLoc = Loc; if (ReceiverType->isDependentType()) { // If the receiver type is dependent, we can't type-check anything // at this point. Build a dependent expression. unsigned NumArgs = ArgsIn.size(); Expr **Args = ArgsIn.data(); assert(SuperLoc.isInvalid() && "Message to super with dependent type"); return Owned(ObjCMessageExpr::Create(Context, ReceiverType, VK_RValue, LBracLoc, ReceiverTypeInfo, Sel, SelectorLocs, /*Method=*/0, makeArrayRef(Args, NumArgs),RBracLoc, isImplicit)); } // Find the class to which we are sending this message. ObjCInterfaceDecl *Class = 0; const ObjCObjectType *ClassType = ReceiverType->getAs<ObjCObjectType>(); if (!ClassType || !(Class = ClassType->getInterface())) { Diag(Loc, diag::err_invalid_receiver_class_message) << ReceiverType; return ExprError(); } assert(Class && "We don't know which class we're messaging?"); // objc++ diagnoses during typename annotation. if (!getLangOpts().CPlusPlus) (void)DiagnoseUseOfDecl(Class, SelLoc); // Find the method we are messaging. if (!Method) { SourceRange TypeRange = SuperLoc.isValid()? SourceRange(SuperLoc) : ReceiverTypeInfo->getTypeLoc().getSourceRange(); if (RequireCompleteType(Loc, Context.getObjCInterfaceType(Class), (getLangOpts().ObjCAutoRefCount ? diag::err_arc_receiver_forward_class : diag::warn_receiver_forward_class), TypeRange)) { // A forward class used in messaging is treated as a 'Class' Method = LookupFactoryMethodInGlobalPool(Sel, SourceRange(LBracLoc, RBracLoc)); if (Method && !getLangOpts().ObjCAutoRefCount) Diag(Method->getLocation(), diag::note_method_sent_forward_class) << Method->getDeclName(); } if (!Method) Method = Class->lookupClassMethod(Sel); // If we have an implementation in scope, check "private" methods. if (!Method) Method = Class->lookupPrivateClassMethod(Sel); if (Method && DiagnoseUseOfDecl(Method, SelLoc)) return ExprError(); } // Check the argument types and determine the result type. QualType ReturnType; ExprValueKind VK = VK_RValue; unsigned NumArgs = ArgsIn.size(); Expr **Args = ArgsIn.data(); if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs), Sel, SelectorLocs, Method, true, SuperLoc.isValid(), LBracLoc, RBracLoc, ReturnType, VK)) return ExprError(); if (Method && !Method->getReturnType()->isVoidType() && RequireCompleteType(LBracLoc, Method->getReturnType(), diag::err_illegal_message_expr_incomplete_type)) return ExprError(); // Construct the appropriate ObjCMessageExpr. ObjCMessageExpr *Result; if (SuperLoc.isValid()) Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, SuperLoc, /*IsInstanceSuper=*/false, ReceiverType, Sel, SelectorLocs, Method, makeArrayRef(Args, NumArgs), RBracLoc, isImplicit); else { Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, ReceiverTypeInfo, Sel, SelectorLocs, Method, makeArrayRef(Args, NumArgs), RBracLoc, isImplicit); if (!isImplicit) checkCocoaAPI(*this, Result); } return MaybeBindToTemporary(Result); } // ActOnClassMessage - used for both unary and keyword messages. // ArgExprs is optional - if it is present, the number of expressions // is obtained from Sel.getNumArgs(). ExprResult Sema::ActOnClassMessage(Scope *S, ParsedType Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args) { TypeSourceInfo *ReceiverTypeInfo; QualType ReceiverType = GetTypeFromParser(Receiver, &ReceiverTypeInfo); if (ReceiverType.isNull()) return ExprError(); if (!ReceiverTypeInfo) ReceiverTypeInfo = Context.getTrivialTypeSourceInfo(ReceiverType, LBracLoc); return BuildClassMessage(ReceiverTypeInfo, ReceiverType, /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0, LBracLoc, SelectorLocs, RBracLoc, Args); } ExprResult Sema::BuildInstanceMessageImplicit(Expr *Receiver, QualType ReceiverType, SourceLocation Loc, Selector Sel, ObjCMethodDecl *Method, MultiExprArg Args) { return BuildInstanceMessage(Receiver, ReceiverType, /*SuperLoc=*/!Receiver ? Loc : SourceLocation(), Sel, Method, Loc, Loc, Loc, Args, /*isImplicit=*/true); } /// \brief Build an Objective-C instance message expression. /// /// This routine takes care of both normal instance messages and /// instance messages to the superclass instance. /// /// \param Receiver The expression that computes the object that will /// receive this message. This may be empty, in which case we are /// sending to the superclass instance and \p SuperLoc must be a valid /// source location. /// /// \param ReceiverType The (static) type of the object receiving the /// message. When a \p Receiver expression is provided, this is the /// same type as that expression. For a superclass instance send, this /// is a pointer to the type of the superclass. /// /// \param SuperLoc The location of the "super" keyword in a /// superclass instance message. /// /// \param Sel The selector to which the message is being sent. /// /// \param Method The method that this instance message is invoking, if /// already known. /// /// \param LBracLoc The location of the opening square bracket ']'. /// /// \param RBracLoc The location of the closing square bracket ']'. /// /// \param ArgsIn The message arguments. ExprResult Sema::BuildInstanceMessage(Expr *Receiver, QualType ReceiverType, SourceLocation SuperLoc, Selector Sel, ObjCMethodDecl *Method, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg ArgsIn, bool isImplicit) { // The location of the receiver. SourceLocation Loc = SuperLoc.isValid()? SuperLoc : Receiver->getLocStart(); SourceRange RecRange = SuperLoc.isValid()? SuperLoc : Receiver->getSourceRange(); SourceLocation SelLoc; if (!SelectorLocs.empty() && SelectorLocs.front().isValid()) SelLoc = SelectorLocs.front(); else SelLoc = Loc; if (LBracLoc.isInvalid()) { Diag(Loc, diag::err_missing_open_square_message_send) << FixItHint::CreateInsertion(Loc, "["); LBracLoc = Loc; } // If we have a receiver expression, perform appropriate promotions // and determine receiver type. if (Receiver) { if (Receiver->hasPlaceholderType()) { ExprResult Result; if (Receiver->getType() == Context.UnknownAnyTy) Result = forceUnknownAnyToType(Receiver, Context.getObjCIdType()); else Result = CheckPlaceholderExpr(Receiver); if (Result.isInvalid()) return ExprError(); Receiver = Result.take(); } if (Receiver->isTypeDependent()) { // If the receiver is type-dependent, we can't type-check anything // at this point. Build a dependent expression. unsigned NumArgs = ArgsIn.size(); Expr **Args = ArgsIn.data(); assert(SuperLoc.isInvalid() && "Message to super with dependent type"); return Owned(ObjCMessageExpr::Create(Context, Context.DependentTy, VK_RValue, LBracLoc, Receiver, Sel, SelectorLocs, /*Method=*/0, makeArrayRef(Args, NumArgs), RBracLoc, isImplicit)); } // If necessary, apply function/array conversion to the receiver. // C99 6.7.5.3p[7,8]. ExprResult Result = DefaultFunctionArrayLvalueConversion(Receiver); if (Result.isInvalid()) return ExprError(); Receiver = Result.take(); ReceiverType = Receiver->getType(); // If the receiver is an ObjC pointer, a block pointer, or an // __attribute__((NSObject)) pointer, we don't need to do any // special conversion in order to look up a receiver. if (ReceiverType->isObjCRetainableType()) { // do nothing } else if (!getLangOpts().ObjCAutoRefCount && !Context.getObjCIdType().isNull() && (ReceiverType->isPointerType() || ReceiverType->isIntegerType())) { // Implicitly convert integers and pointers to 'id' but emit a warning. // But not in ARC. Diag(Loc, diag::warn_bad_receiver_type) << ReceiverType << Receiver->getSourceRange(); if (ReceiverType->isPointerType()) { Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), CK_CPointerToObjCPointerCast).take(); } else { // TODO: specialized warning on null receivers? bool IsNull = Receiver->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull); CastKind Kind = IsNull ? CK_NullToPointer : CK_IntegralToPointer; Receiver = ImpCastExprToType(Receiver, Context.getObjCIdType(), Kind).take(); } ReceiverType = Receiver->getType(); } else if (getLangOpts().CPlusPlus) { // The receiver must be a complete type. if (RequireCompleteType(Loc, Receiver->getType(), diag::err_incomplete_receiver_type)) return ExprError(); ExprResult result = PerformContextuallyConvertToObjCPointer(Receiver); if (result.isUsable()) { Receiver = result.take(); ReceiverType = Receiver->getType(); } } } // There's a somewhat weird interaction here where we assume that we // won't actually have a method unless we also don't need to do some // of the more detailed type-checking on the receiver. if (!Method) { // Handle messages to id. bool receiverIsId = ReceiverType->isObjCIdType(); if (receiverIsId || ReceiverType->isBlockPointerType() || (Receiver && Context.isObjCNSObjectType(Receiver->getType()))) { Method = LookupInstanceMethodInGlobalPool(Sel, SourceRange(LBracLoc, RBracLoc), receiverIsId); if (!Method) Method = LookupFactoryMethodInGlobalPool(Sel, SourceRange(LBracLoc,RBracLoc), receiverIsId); } else if (ReceiverType->isObjCClassType() || ReceiverType->isObjCQualifiedClassType()) { // Handle messages to Class. // We allow sending a message to a qualified Class ("Class<foo>"), which // is ok as long as one of the protocols implements the selector (if not, warn). if (const ObjCObjectPointerType *QClassTy = ReceiverType->getAsObjCQualifiedClassType()) { // Search protocols for class methods. Method = LookupMethodInQualifiedType(Sel, QClassTy, false); if (!Method) { Method = LookupMethodInQualifiedType(Sel, QClassTy, true); // warn if instance method found for a Class message. if (Method) { Diag(SelLoc, diag::warn_instance_method_on_class_found) << Method->getSelector() << Sel; Diag(Method->getLocation(), diag::note_method_declared_at) << Method->getDeclName(); } } } else { if (ObjCMethodDecl *CurMeth = getCurMethodDecl()) { if (ObjCInterfaceDecl *ClassDecl = CurMeth->getClassInterface()) { // First check the public methods in the class interface. Method = ClassDecl->lookupClassMethod(Sel); if (!Method) Method = ClassDecl->lookupPrivateClassMethod(Sel); } if (Method && DiagnoseUseOfDecl(Method, SelLoc)) return ExprError(); } if (!Method) { // If not messaging 'self', look for any factory method named 'Sel'. if (!Receiver || !isSelfExpr(Receiver)) { Method = LookupFactoryMethodInGlobalPool(Sel, SourceRange(LBracLoc, RBracLoc), true); if (!Method) { // If no class (factory) method was found, check if an _instance_ // method of the same name exists in the root class only. Method = LookupInstanceMethodInGlobalPool(Sel, SourceRange(LBracLoc, RBracLoc), true); if (Method) if (const ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(Method->getDeclContext())) { if (ID->getSuperClass()) Diag(SelLoc, diag::warn_root_inst_method_not_found) << Sel << SourceRange(LBracLoc, RBracLoc); } } } } } } else { ObjCInterfaceDecl* ClassDecl = 0; // We allow sending a message to a qualified ID ("id<foo>"), which is ok as // long as one of the protocols implements the selector (if not, warn). // And as long as message is not deprecated/unavailable (warn if it is). if (const ObjCObjectPointerType *QIdTy = ReceiverType->getAsObjCQualifiedIdType()) { // Search protocols for instance methods. Method = LookupMethodInQualifiedType(Sel, QIdTy, true); if (!Method) Method = LookupMethodInQualifiedType(Sel, QIdTy, false); if (Method && DiagnoseUseOfDecl(Method, SelLoc)) return ExprError(); } else if (const ObjCObjectPointerType *OCIType = ReceiverType->getAsObjCInterfacePointerType()) { // We allow sending a message to a pointer to an interface (an object). ClassDecl = OCIType->getInterfaceDecl(); // Try to complete the type. Under ARC, this is a hard error from which // we don't try to recover. const ObjCInterfaceDecl *forwardClass = 0; if (RequireCompleteType(Loc, OCIType->getPointeeType(), getLangOpts().ObjCAutoRefCount ? diag::err_arc_receiver_forward_instance : diag::warn_receiver_forward_instance, Receiver? Receiver->getSourceRange() : SourceRange(SuperLoc))) { if (getLangOpts().ObjCAutoRefCount) return ExprError(); forwardClass = OCIType->getInterfaceDecl(); Diag(Receiver ? Receiver->getLocStart() : SuperLoc, diag::note_receiver_is_id); Method = 0; } else { Method = ClassDecl->lookupInstanceMethod(Sel); } if (!Method) // Search protocol qualifiers. Method = LookupMethodInQualifiedType(Sel, OCIType, true); if (!Method) { // If we have implementations in scope, check "private" methods. Method = ClassDecl->lookupPrivateMethod(Sel); if (!Method && getLangOpts().ObjCAutoRefCount) { Diag(SelLoc, diag::err_arc_may_not_respond) << OCIType->getPointeeType() << Sel << RecRange << SourceRange(SelectorLocs.front(), SelectorLocs.back()); return ExprError(); } if (!Method && (!Receiver || !isSelfExpr(Receiver))) { // If we still haven't found a method, look in the global pool. This // behavior isn't very desirable, however we need it for GCC // compatibility. FIXME: should we deviate?? if (OCIType->qual_empty()) { Method = LookupInstanceMethodInGlobalPool(Sel, SourceRange(LBracLoc, RBracLoc)); if (Method && !forwardClass) Diag(SelLoc, diag::warn_maynot_respond) << OCIType->getInterfaceDecl()->getIdentifier() << Sel << RecRange; } } } if (Method && DiagnoseUseOfDecl(Method, SelLoc, forwardClass)) return ExprError(); } else { // Reject other random receiver types (e.g. structs). Diag(Loc, diag::err_bad_receiver_type) << ReceiverType << Receiver->getSourceRange(); return ExprError(); } } } if (Method && Method->getMethodFamily() == OMF_init && getCurFunction()->ObjCIsDesignatedInit && (SuperLoc.isValid() || isSelfExpr(Receiver))) { bool isDesignatedInitChain = false; if (SuperLoc.isValid()) { if (const ObjCObjectPointerType * OCIType = ReceiverType->getAsObjCInterfacePointerType()) { if (const ObjCInterfaceDecl *ID = OCIType->getInterfaceDecl()) { // Either we know this is a designated initializer or we // conservatively assume it because we don't know for sure. if (!ID->declaresOrInheritsDesignatedInitializers() || ID->isDesignatedInitializer(Sel)) { isDesignatedInitChain = true; getCurFunction()->ObjCWarnForNoDesignatedInitChain = false; } } } } if (!isDesignatedInitChain) { const ObjCMethodDecl *InitMethod = 0; bool isDesignated = getCurMethodDecl()->isDesignatedInitializerForTheInterface(&InitMethod); assert(isDesignated && InitMethod); (void)isDesignated; Diag(SelLoc, SuperLoc.isValid() ? diag::warn_objc_designated_init_non_designated_init_call : diag::warn_objc_designated_init_non_super_designated_init_call); Diag(InitMethod->getLocation(), diag::note_objc_designated_init_marked_here); } } if (Method && Method->getMethodFamily() == OMF_init && getCurFunction()->ObjCIsSecondaryInit && (SuperLoc.isValid() || isSelfExpr(Receiver))) { if (SuperLoc.isValid()) { Diag(SelLoc, diag::warn_objc_secondary_init_super_init_call); } else { getCurFunction()->ObjCWarnForNoInitDelegation = false; } } // Check the message arguments. unsigned NumArgs = ArgsIn.size(); Expr **Args = ArgsIn.data(); QualType ReturnType; ExprValueKind VK = VK_RValue; bool ClassMessage = (ReceiverType->isObjCClassType() || ReceiverType->isObjCQualifiedClassType()); if (CheckMessageArgumentTypes(ReceiverType, MultiExprArg(Args, NumArgs), Sel, SelectorLocs, Method, ClassMessage, SuperLoc.isValid(), LBracLoc, RBracLoc, ReturnType, VK)) return ExprError(); if (Method && !Method->getReturnType()->isVoidType() && RequireCompleteType(LBracLoc, Method->getReturnType(), diag::err_illegal_message_expr_incomplete_type)) return ExprError(); // In ARC, forbid the user from sending messages to // retain/release/autorelease/dealloc/retainCount explicitly. if (getLangOpts().ObjCAutoRefCount) { ObjCMethodFamily family = (Method ? Method->getMethodFamily() : Sel.getMethodFamily()); switch (family) { case OMF_init: if (Method) checkInitMethod(Method, ReceiverType); case OMF_None: case OMF_alloc: case OMF_copy: case OMF_finalize: case OMF_mutableCopy: case OMF_new: case OMF_self: break; case OMF_dealloc: case OMF_retain: case OMF_release: case OMF_autorelease: case OMF_retainCount: Diag(SelLoc, diag::err_arc_illegal_explicit_message) << Sel << RecRange; break; case OMF_performSelector: if (Method && NumArgs >= 1) { if (ObjCSelectorExpr *SelExp = dyn_cast<ObjCSelectorExpr>(Args[0])) { Selector ArgSel = SelExp->getSelector(); ObjCMethodDecl *SelMethod = LookupInstanceMethodInGlobalPool(ArgSel, SelExp->getSourceRange()); if (!SelMethod) SelMethod = LookupFactoryMethodInGlobalPool(ArgSel, SelExp->getSourceRange()); if (SelMethod) { ObjCMethodFamily SelFamily = SelMethod->getMethodFamily(); switch (SelFamily) { case OMF_alloc: case OMF_copy: case OMF_mutableCopy: case OMF_new: case OMF_self: case OMF_init: // Issue error, unless ns_returns_not_retained. if (!SelMethod->hasAttr<NSReturnsNotRetainedAttr>()) { // selector names a +1 method Diag(SelLoc, diag::err_arc_perform_selector_retains); Diag(SelMethod->getLocation(), diag::note_method_declared_at) << SelMethod->getDeclName(); } break; default: // +0 call. OK. unless ns_returns_retained. if (SelMethod->hasAttr<NSReturnsRetainedAttr>()) { // selector names a +1 method Diag(SelLoc, diag::err_arc_perform_selector_retains); Diag(SelMethod->getLocation(), diag::note_method_declared_at) << SelMethod->getDeclName(); } break; } } } else { // error (may leak). Diag(SelLoc, diag::warn_arc_perform_selector_leaks); Diag(Args[0]->getExprLoc(), diag::note_used_here); } } break; } } // Construct the appropriate ObjCMessageExpr instance. ObjCMessageExpr *Result; if (SuperLoc.isValid()) Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, SuperLoc, /*IsInstanceSuper=*/true, ReceiverType, Sel, SelectorLocs, Method, makeArrayRef(Args, NumArgs), RBracLoc, isImplicit); else { Result = ObjCMessageExpr::Create(Context, ReturnType, VK, LBracLoc, Receiver, Sel, SelectorLocs, Method, makeArrayRef(Args, NumArgs), RBracLoc, isImplicit); if (!isImplicit) checkCocoaAPI(*this, Result); } if (getLangOpts().ObjCAutoRefCount) { DiagnoseARCUseOfWeakReceiver(*this, Receiver); // In ARC, annotate delegate init calls. if (Result->getMethodFamily() == OMF_init && (SuperLoc.isValid() || isSelfExpr(Receiver))) { // Only consider init calls *directly* in init implementations, // not within blocks. ObjCMethodDecl *method = dyn_cast<ObjCMethodDecl>(CurContext); if (method && method->getMethodFamily() == OMF_init) { // The implicit assignment to self means we also don't want to // consume the result. Result->setDelegateInitCall(true); return Owned(Result); } } // In ARC, check for message sends which are likely to introduce // retain cycles. checkRetainCycles(Result); if (!isImplicit && Method) { if (const ObjCPropertyDecl *Prop = Method->findPropertyDecl()) { bool IsWeak = Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_weak; if (!IsWeak && Sel.isUnarySelector()) IsWeak = ReturnType.getObjCLifetime() & Qualifiers::OCL_Weak; if (IsWeak) { DiagnosticsEngine::Level Level = Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, LBracLoc); if (Level != DiagnosticsEngine::Ignored) getCurFunction()->recordUseOfWeak(Result, Prop); } } } } return MaybeBindToTemporary(Result); } static void RemoveSelectorFromWarningCache(Sema &S, Expr* Arg) { if (ObjCSelectorExpr *OSE = dyn_cast<ObjCSelectorExpr>(Arg->IgnoreParenCasts())) { Selector Sel = OSE->getSelector(); SourceLocation Loc = OSE->getAtLoc(); llvm::DenseMap<Selector, SourceLocation>::iterator Pos = S.ReferencedSelectors.find(Sel); if (Pos != S.ReferencedSelectors.end() && Pos->second == Loc) S.ReferencedSelectors.erase(Pos); } } // ActOnInstanceMessage - used for both unary and keyword messages. // ArgExprs is optional - if it is present, the number of expressions // is obtained from Sel.getNumArgs(). ExprResult Sema::ActOnInstanceMessage(Scope *S, Expr *Receiver, Selector Sel, SourceLocation LBracLoc, ArrayRef<SourceLocation> SelectorLocs, SourceLocation RBracLoc, MultiExprArg Args) { if (!Receiver) return ExprError(); // A ParenListExpr can show up while doing error recovery with invalid code. if (isa<ParenListExpr>(Receiver)) { ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Receiver); if (Result.isInvalid()) return ExprError(); Receiver = Result.take(); } if (RespondsToSelectorSel.isNull()) { IdentifierInfo *SelectorId = &Context.Idents.get("respondsToSelector"); RespondsToSelectorSel = Context.Selectors.getUnarySelector(SelectorId); } if (Sel == RespondsToSelectorSel) RemoveSelectorFromWarningCache(*this, Args[0]); return BuildInstanceMessage(Receiver, Receiver->getType(), /*SuperLoc=*/SourceLocation(), Sel, /*Method=*/0, LBracLoc, SelectorLocs, RBracLoc, Args); } enum ARCConversionTypeClass { /// int, void, struct A ACTC_none, /// id, void (^)() ACTC_retainable, /// id*, id***, void (^*)(), ACTC_indirectRetainable, /// void* might be a normal C type, or it might a CF type. ACTC_voidPtr, /// struct A* ACTC_coreFoundation }; static bool isAnyRetainable(ARCConversionTypeClass ACTC) { return (ACTC == ACTC_retainable || ACTC == ACTC_coreFoundation || ACTC == ACTC_voidPtr); } static bool isAnyCLike(ARCConversionTypeClass ACTC) { return ACTC == ACTC_none || ACTC == ACTC_voidPtr || ACTC == ACTC_coreFoundation; } static ARCConversionTypeClass classifyTypeForARCConversion(QualType type) { bool isIndirect = false; // Ignore an outermost reference type. if (const ReferenceType *ref = type->getAs<ReferenceType>()) { type = ref->getPointeeType(); isIndirect = true; } // Drill through pointers and arrays recursively. while (true) { if (const PointerType *ptr = type->getAs<PointerType>()) { type = ptr->getPointeeType(); // The first level of pointer may be the innermost pointer on a CF type. if (!isIndirect) { if (type->isVoidType()) return ACTC_voidPtr; if (type->isRecordType()) return ACTC_coreFoundation; } } else if (const ArrayType *array = type->getAsArrayTypeUnsafe()) { type = QualType(array->getElementType()->getBaseElementTypeUnsafe(), 0); } else { break; } isIndirect = true; } if (isIndirect) { if (type->isObjCARCBridgableType()) return ACTC_indirectRetainable; return ACTC_none; } if (type->isObjCARCBridgableType()) return ACTC_retainable; return ACTC_none; } namespace { /// A result from the cast checker. enum ACCResult { /// Cannot be casted. ACC_invalid, /// Can be safely retained or not retained. ACC_bottom, /// Can be casted at +0. ACC_plusZero, /// Can be casted at +1. ACC_plusOne }; ACCResult merge(ACCResult left, ACCResult right) { if (left == right) return left; if (left == ACC_bottom) return right; if (right == ACC_bottom) return left; return ACC_invalid; } /// A checker which white-lists certain expressions whose conversion /// to or from retainable type would otherwise be forbidden in ARC. class ARCCastChecker : public StmtVisitor<ARCCastChecker, ACCResult> { typedef StmtVisitor<ARCCastChecker, ACCResult> super; ASTContext &Context; ARCConversionTypeClass SourceClass; ARCConversionTypeClass TargetClass; bool Diagnose; static bool isCFType(QualType type) { // Someday this can use ns_bridged. For now, it has to do this. return type->isCARCBridgableType(); } public: ARCCastChecker(ASTContext &Context, ARCConversionTypeClass source, ARCConversionTypeClass target, bool diagnose) : Context(Context), SourceClass(source), TargetClass(target), Diagnose(diagnose) {} using super::Visit; ACCResult Visit(Expr *e) { return super::Visit(e->IgnoreParens()); } ACCResult VisitStmt(Stmt *s) { return ACC_invalid; } /// Null pointer constants can be casted however you please. ACCResult VisitExpr(Expr *e) { if (e->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNotNull)) return ACC_bottom; return ACC_invalid; } /// Objective-C string literals can be safely casted. ACCResult VisitObjCStringLiteral(ObjCStringLiteral *e) { // If we're casting to any retainable type, go ahead. Global // strings are immune to retains, so this is bottom. if (isAnyRetainable(TargetClass)) return ACC_bottom; return ACC_invalid; } /// Look through certain implicit and explicit casts. ACCResult VisitCastExpr(CastExpr *e) { switch (e->getCastKind()) { case CK_NullToPointer: return ACC_bottom; case CK_NoOp: case CK_LValueToRValue: case CK_BitCast: case CK_CPointerToObjCPointerCast: case CK_BlockPointerToObjCPointerCast: case CK_AnyPointerToBlockPointerCast: return Visit(e->getSubExpr()); default: return ACC_invalid; } } /// Look through unary extension. ACCResult VisitUnaryExtension(UnaryOperator *e) { return Visit(e->getSubExpr()); } /// Ignore the LHS of a comma operator. ACCResult VisitBinComma(BinaryOperator *e) { return Visit(e->getRHS()); } /// Conditional operators are okay if both sides are okay. ACCResult VisitConditionalOperator(ConditionalOperator *e) { ACCResult left = Visit(e->getTrueExpr()); if (left == ACC_invalid) return ACC_invalid; return merge(left, Visit(e->getFalseExpr())); } /// Look through pseudo-objects. ACCResult VisitPseudoObjectExpr(PseudoObjectExpr *e) { // If we're getting here, we should always have a result. return Visit(e->getResultExpr()); } /// Statement expressions are okay if their result expression is okay. ACCResult VisitStmtExpr(StmtExpr *e) { return Visit(e->getSubStmt()->body_back()); } /// Some declaration references are okay. ACCResult VisitDeclRefExpr(DeclRefExpr *e) { // References to global constants from system headers are okay. // These are things like 'kCFStringTransformToLatin'. They are // can also be assumed to be immune to retains. VarDecl *var = dyn_cast<VarDecl>(e->getDecl()); if (isAnyRetainable(TargetClass) && isAnyRetainable(SourceClass) && var && var->getStorageClass() == SC_Extern && var->getType().isConstQualified() && Context.getSourceManager().isInSystemHeader(var->getLocation())) { return ACC_bottom; } // Nothing else. return ACC_invalid; } /// Some calls are okay. ACCResult VisitCallExpr(CallExpr *e) { if (FunctionDecl *fn = e->getDirectCallee()) if (ACCResult result = checkCallToFunction(fn)) return result; return super::VisitCallExpr(e); } ACCResult checkCallToFunction(FunctionDecl *fn) { // Require a CF*Ref return type. if (!isCFType(fn->getReturnType())) return ACC_invalid; if (!isAnyRetainable(TargetClass)) return ACC_invalid; // Honor an explicit 'not retained' attribute. if (fn->hasAttr<CFReturnsNotRetainedAttr>()) return ACC_plusZero; // Honor an explicit 'retained' attribute, except that for // now we're not going to permit implicit handling of +1 results, // because it's a bit frightening. if (fn->hasAttr<CFReturnsRetainedAttr>()) return Diagnose ? ACC_plusOne : ACC_invalid; // ACC_plusOne if we start accepting this // Recognize this specific builtin function, which is used by CFSTR. unsigned builtinID = fn->getBuiltinID(); if (builtinID == Builtin::BI__builtin___CFStringMakeConstantString) return ACC_bottom; // Otherwise, don't do anything implicit with an unaudited function. if (!fn->hasAttr<CFAuditedTransferAttr>()) return ACC_invalid; // Otherwise, it's +0 unless it follows the create convention. if (ento::coreFoundation::followsCreateRule(fn)) return Diagnose ? ACC_plusOne : ACC_invalid; // ACC_plusOne if we start accepting this return ACC_plusZero; } ACCResult VisitObjCMessageExpr(ObjCMessageExpr *e) { return checkCallToMethod(e->getMethodDecl()); } ACCResult VisitObjCPropertyRefExpr(ObjCPropertyRefExpr *e) { ObjCMethodDecl *method; if (e->isExplicitProperty()) method = e->getExplicitProperty()->getGetterMethodDecl(); else method = e->getImplicitPropertyGetter(); return checkCallToMethod(method); } ACCResult checkCallToMethod(ObjCMethodDecl *method) { if (!method) return ACC_invalid; // Check for message sends to functions returning CF types. We // just obey the Cocoa conventions with these, even though the // return type is CF. if (!isAnyRetainable(TargetClass) || !isCFType(method->getReturnType())) return ACC_invalid; // If the method is explicitly marked not-retained, it's +0. if (method->hasAttr<CFReturnsNotRetainedAttr>()) return ACC_plusZero; // If the method is explicitly marked as returning retained, or its // selector follows a +1 Cocoa convention, treat it as +1. if (method->hasAttr<CFReturnsRetainedAttr>()) return ACC_plusOne; switch (method->getSelector().getMethodFamily()) { case OMF_alloc: case OMF_copy: case OMF_mutableCopy: case OMF_new: return ACC_plusOne; default: // Otherwise, treat it as +0. return ACC_plusZero; } } }; } bool Sema::isKnownName(StringRef name) { if (name.empty()) return false; LookupResult R(*this, &Context.Idents.get(name), SourceLocation(), Sema::LookupOrdinaryName); return LookupName(R, TUScope, false); } static void addFixitForObjCARCConversion(Sema &S, DiagnosticBuilder &DiagB, Sema::CheckedConversionKind CCK, SourceLocation afterLParen, QualType castType, Expr *castExpr, Expr *realCast, const char *bridgeKeyword, const char *CFBridgeName) { // We handle C-style and implicit casts here. switch (CCK) { case Sema::CCK_ImplicitConversion: case Sema::CCK_CStyleCast: case Sema::CCK_OtherCast: break; case Sema::CCK_FunctionalCast: return; } if (CFBridgeName) { if (CCK == Sema::CCK_OtherCast) { if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) { SourceRange range(NCE->getOperatorLoc(), NCE->getAngleBrackets().getEnd()); SmallString<32> BridgeCall; SourceManager &SM = S.getSourceManager(); char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1)); if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts())) BridgeCall += ' '; BridgeCall += CFBridgeName; DiagB.AddFixItHint(FixItHint::CreateReplacement(range, BridgeCall)); } return; } Expr *castedE = castExpr; if (CStyleCastExpr *CCE = dyn_cast<CStyleCastExpr>(castedE)) castedE = CCE->getSubExpr(); castedE = castedE->IgnoreImpCasts(); SourceRange range = castedE->getSourceRange(); SmallString<32> BridgeCall; SourceManager &SM = S.getSourceManager(); char PrevChar = *SM.getCharacterData(range.getBegin().getLocWithOffset(-1)); if (Lexer::isIdentifierBodyChar(PrevChar, S.getLangOpts())) BridgeCall += ' '; BridgeCall += CFBridgeName; if (isa<ParenExpr>(castedE)) { DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), BridgeCall)); } else { BridgeCall += '('; DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), BridgeCall)); DiagB.AddFixItHint(FixItHint::CreateInsertion( S.PP.getLocForEndOfToken(range.getEnd()), ")")); } return; } if (CCK == Sema::CCK_CStyleCast) { DiagB.AddFixItHint(FixItHint::CreateInsertion(afterLParen, bridgeKeyword)); } else if (CCK == Sema::CCK_OtherCast) { if (const CXXNamedCastExpr *NCE = dyn_cast<CXXNamedCastExpr>(realCast)) { std::string castCode = "("; castCode += bridgeKeyword; castCode += castType.getAsString(); castCode += ")"; SourceRange Range(NCE->getOperatorLoc(), NCE->getAngleBrackets().getEnd()); DiagB.AddFixItHint(FixItHint::CreateReplacement(Range, castCode)); } } else { std::string castCode = "("; castCode += bridgeKeyword; castCode += castType.getAsString(); castCode += ")"; Expr *castedE = castExpr->IgnoreImpCasts(); SourceRange range = castedE->getSourceRange(); if (isa<ParenExpr>(castedE)) { DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), castCode)); } else { castCode += "("; DiagB.AddFixItHint(FixItHint::CreateInsertion(range.getBegin(), castCode)); DiagB.AddFixItHint(FixItHint::CreateInsertion( S.PP.getLocForEndOfToken(range.getEnd()), ")")); } } } template <typename T> static inline T *getObjCBridgeAttr(const TypedefType *TD) { TypedefNameDecl *TDNDecl = TD->getDecl(); QualType QT = TDNDecl->getUnderlyingType(); if (QT->isPointerType()) { QT = QT->getPointeeType(); if (const RecordType *RT = QT->getAs<RecordType>()) if (RecordDecl *RD = RT->getDecl()) return RD->getAttr<T>(); } return 0; } static ObjCBridgeRelatedAttr *ObjCBridgeRelatedAttrFromType(QualType T, TypedefNameDecl *&TDNDecl) { while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) { TDNDecl = TD->getDecl(); if (ObjCBridgeRelatedAttr *ObjCBAttr = getObjCBridgeAttr<ObjCBridgeRelatedAttr>(TD)) return ObjCBAttr; T = TDNDecl->getUnderlyingType(); } return 0; } static void diagnoseObjCARCConversion(Sema &S, SourceRange castRange, QualType castType, ARCConversionTypeClass castACTC, Expr *castExpr, Expr *realCast, ARCConversionTypeClass exprACTC, Sema::CheckedConversionKind CCK) { SourceLocation loc = (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc()); if (S.makeUnavailableInSystemHeader(loc, "converts between Objective-C and C pointers in -fobjc-arc")) return; QualType castExprType = castExpr->getType(); TypedefNameDecl *TDNDecl = 0; if ((castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable && ObjCBridgeRelatedAttrFromType(castType, TDNDecl)) || (exprACTC == ACTC_coreFoundation && castACTC == ACTC_retainable && ObjCBridgeRelatedAttrFromType(castExprType, TDNDecl))) return; unsigned srcKind = 0; switch (exprACTC) { case ACTC_none: case ACTC_coreFoundation: case ACTC_voidPtr: srcKind = (castExprType->isPointerType() ? 1 : 0); break; case ACTC_retainable: srcKind = (castExprType->isBlockPointerType() ? 2 : 3); break; case ACTC_indirectRetainable: srcKind = 4; break; } // Check whether this could be fixed with a bridge cast. SourceLocation afterLParen = S.PP.getLocForEndOfToken(castRange.getBegin()); SourceLocation noteLoc = afterLParen.isValid() ? afterLParen : loc; // Bridge from an ARC type to a CF type. if (castACTC == ACTC_retainable && isAnyRetainable(exprACTC)) { S.Diag(loc, diag::err_arc_cast_requires_bridge) << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit << 2 // of C pointer type << castExprType << unsigned(castType->isBlockPointerType()) // to ObjC|block type << castType << castRange << castExpr->getSourceRange(); bool br = S.isKnownName("CFBridgingRelease"); ACCResult CreateRule = ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr); assert(CreateRule != ACC_bottom && "This cast should already be accepted."); if (CreateRule != ACC_plusOne) { DiagnosticBuilder DiagB = (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge) : S.Diag(noteLoc, diag::note_arc_cstyle_bridge); addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, castType, castExpr, realCast, "__bridge ", 0); } if (CreateRule != ACC_plusZero) { DiagnosticBuilder DiagB = (CCK == Sema::CCK_OtherCast && !br) ? S.Diag(noteLoc, diag::note_arc_cstyle_bridge_transfer) << castExprType : S.Diag(br ? castExpr->getExprLoc() : noteLoc, diag::note_arc_bridge_transfer) << castExprType << br; addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, castType, castExpr, realCast, "__bridge_transfer ", br ? "CFBridgingRelease" : 0); } return; } // Bridge from a CF type to an ARC type. if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC)) { bool br = S.isKnownName("CFBridgingRetain"); S.Diag(loc, diag::err_arc_cast_requires_bridge) << unsigned(CCK == Sema::CCK_ImplicitConversion) // cast|implicit << unsigned(castExprType->isBlockPointerType()) // of ObjC|block type << castExprType << 2 // to C pointer type << castType << castRange << castExpr->getSourceRange(); ACCResult CreateRule = ARCCastChecker(S.Context, exprACTC, castACTC, true).Visit(castExpr); assert(CreateRule != ACC_bottom && "This cast should already be accepted."); if (CreateRule != ACC_plusOne) { DiagnosticBuilder DiagB = (CCK != Sema::CCK_OtherCast) ? S.Diag(noteLoc, diag::note_arc_bridge) : S.Diag(noteLoc, diag::note_arc_cstyle_bridge); addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, castType, castExpr, realCast, "__bridge ", 0); } if (CreateRule != ACC_plusZero) { DiagnosticBuilder DiagB = (CCK == Sema::CCK_OtherCast && !br) ? S.Diag(noteLoc, diag::note_arc_cstyle_bridge_retained) << castType : S.Diag(br ? castExpr->getExprLoc() : noteLoc, diag::note_arc_bridge_retained) << castType << br; addFixitForObjCARCConversion(S, DiagB, CCK, afterLParen, castType, castExpr, realCast, "__bridge_retained ", br ? "CFBridgingRetain" : 0); } return; } S.Diag(loc, diag::err_arc_mismatched_cast) << (CCK != Sema::CCK_ImplicitConversion) << srcKind << castExprType << castType << castRange << castExpr->getSourceRange(); } template <typename TB> static bool CheckObjCBridgeNSCast(Sema &S, QualType castType, Expr *castExpr) { QualType T = castExpr->getType(); while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) { TypedefNameDecl *TDNDecl = TD->getDecl(); if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) { if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) { NamedDecl *Target = 0; // Check for an existing type with this name. LookupResult R(S, DeclarationName(Parm), SourceLocation(), Sema::LookupOrdinaryName); if (S.LookupName(R, S.TUScope)) { Target = R.getFoundDecl(); if (Target && isa<ObjCInterfaceDecl>(Target)) { ObjCInterfaceDecl *ExprClass = cast<ObjCInterfaceDecl>(Target); if (const ObjCObjectPointerType *InterfacePointerType = castType->getAsObjCInterfacePointerType()) { ObjCInterfaceDecl *CastClass = InterfacePointerType->getObjectType()->getInterface(); if ((CastClass == ExprClass) || (CastClass && ExprClass->isSuperClassOf(CastClass))) return true; S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge) << T << Target->getName() << castType->getPointeeType(); return true; } else if (castType->isObjCIdType() || (S.Context.ObjCObjectAdoptsQTypeProtocols( castType, ExprClass))) // ok to cast to 'id'. // casting to id<p-list> is ok if bridge type adopts all of // p-list protocols. return true; else { S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge) << T << Target->getName() << castType; S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); S.Diag(Target->getLocStart(), diag::note_declared_at); return true; } } } S.Diag(castExpr->getLocStart(), diag::err_objc_cf_bridged_not_interface) << castExpr->getType() << Parm; S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); if (Target) S.Diag(Target->getLocStart(), diag::note_declared_at); } return true; } T = TDNDecl->getUnderlyingType(); } return false; } template <typename TB> static bool CheckObjCBridgeCFCast(Sema &S, QualType castType, Expr *castExpr) { QualType T = castType; while (const TypedefType *TD = dyn_cast<TypedefType>(T.getTypePtr())) { TypedefNameDecl *TDNDecl = TD->getDecl(); if (TB *ObjCBAttr = getObjCBridgeAttr<TB>(TD)) { if (IdentifierInfo *Parm = ObjCBAttr->getBridgedType()) { NamedDecl *Target = 0; // Check for an existing type with this name. LookupResult R(S, DeclarationName(Parm), SourceLocation(), Sema::LookupOrdinaryName); if (S.LookupName(R, S.TUScope)) { Target = R.getFoundDecl(); if (Target && isa<ObjCInterfaceDecl>(Target)) { ObjCInterfaceDecl *CastClass = cast<ObjCInterfaceDecl>(Target); if (const ObjCObjectPointerType *InterfacePointerType = castExpr->getType()->getAsObjCInterfacePointerType()) { ObjCInterfaceDecl *ExprClass = InterfacePointerType->getObjectType()->getInterface(); if ((CastClass == ExprClass) || (ExprClass && CastClass->isSuperClassOf(ExprClass))) return true; S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf) << castExpr->getType()->getPointeeType() << T; S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); return true; } else if (castExpr->getType()->isObjCIdType() || (S.Context.QIdProtocolsAdoptObjCObjectProtocols( castExpr->getType(), CastClass))) // ok to cast an 'id' expression to a CFtype. // ok to cast an 'id<plist>' expression to CFtype provided plist // adopts all of CFtype's ObjetiveC's class plist. return true; else { S.Diag(castExpr->getLocStart(), diag::warn_objc_invalid_bridge_to_cf) << castExpr->getType() << castType; S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); S.Diag(Target->getLocStart(), diag::note_declared_at); return true; } } } S.Diag(castExpr->getLocStart(), diag::err_objc_ns_bridged_invalid_cfobject) << castExpr->getType() << castType; S.Diag(TDNDecl->getLocStart(), diag::note_declared_at); if (Target) S.Diag(Target->getLocStart(), diag::note_declared_at); } return true; } T = TDNDecl->getUnderlyingType(); } return false; } void Sema::CheckTollFreeBridgeCast(QualType castType, Expr *castExpr) { // warn in presence of __bridge casting to or from a toll free bridge cast. ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExpr->getType()); ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType); if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation) { (void)CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr); (void)CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr); } else if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable) { (void)CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr); (void)CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr); } } bool Sema::checkObjCBridgeRelatedComponents(SourceLocation Loc, QualType DestType, QualType SrcType, ObjCInterfaceDecl *&RelatedClass, ObjCMethodDecl *&ClassMethod, ObjCMethodDecl *&InstanceMethod, TypedefNameDecl *&TDNDecl, bool CfToNs) { QualType T = CfToNs ? SrcType : DestType; ObjCBridgeRelatedAttr *ObjCBAttr = ObjCBridgeRelatedAttrFromType(T, TDNDecl); if (!ObjCBAttr) return false; IdentifierInfo *RCId = ObjCBAttr->getRelatedClass(); IdentifierInfo *CMId = ObjCBAttr->getClassMethod(); IdentifierInfo *IMId = ObjCBAttr->getInstanceMethod(); if (!RCId) return false; NamedDecl *Target = 0; // Check for an existing type with this name. LookupResult R(*this, DeclarationName(RCId), SourceLocation(), Sema::LookupOrdinaryName); if (!LookupName(R, TUScope)) { Diag(Loc, diag::err_objc_bridged_related_invalid_class) << RCId << SrcType << DestType; Diag(TDNDecl->getLocStart(), diag::note_declared_at); return false; } Target = R.getFoundDecl(); if (Target && isa<ObjCInterfaceDecl>(Target)) RelatedClass = cast<ObjCInterfaceDecl>(Target); else { Diag(Loc, diag::err_objc_bridged_related_invalid_class_name) << RCId << SrcType << DestType; Diag(TDNDecl->getLocStart(), diag::note_declared_at); if (Target) Diag(Target->getLocStart(), diag::note_declared_at); return false; } // Check for an existing class method with the given selector name. if (CfToNs && CMId) { Selector Sel = Context.Selectors.getUnarySelector(CMId); ClassMethod = RelatedClass->lookupMethod(Sel, false); if (!ClassMethod) { Diag(Loc, diag::err_objc_bridged_related_known_method) << SrcType << DestType << Sel << false; Diag(TDNDecl->getLocStart(), diag::note_declared_at); return false; } } // Check for an existing instance method with the given selector name. if (!CfToNs && IMId) { Selector Sel = Context.Selectors.getNullarySelector(IMId); InstanceMethod = RelatedClass->lookupMethod(Sel, true); if (!InstanceMethod) { Diag(Loc, diag::err_objc_bridged_related_known_method) << SrcType << DestType << Sel << true; Diag(TDNDecl->getLocStart(), diag::note_declared_at); return false; } } return true; } bool Sema::CheckObjCBridgeRelatedConversions(SourceLocation Loc, QualType DestType, QualType SrcType, Expr *&SrcExpr) { ARCConversionTypeClass rhsExprACTC = classifyTypeForARCConversion(SrcType); ARCConversionTypeClass lhsExprACTC = classifyTypeForARCConversion(DestType); bool CfToNs = (rhsExprACTC == ACTC_coreFoundation && lhsExprACTC == ACTC_retainable); bool NsToCf = (rhsExprACTC == ACTC_retainable && lhsExprACTC == ACTC_coreFoundation); if (!CfToNs && !NsToCf) return false; ObjCInterfaceDecl *RelatedClass; ObjCMethodDecl *ClassMethod = 0; ObjCMethodDecl *InstanceMethod = 0; TypedefNameDecl *TDNDecl = 0; if (!checkObjCBridgeRelatedComponents(Loc, DestType, SrcType, RelatedClass, ClassMethod, InstanceMethod, TDNDecl, CfToNs)) return false; if (CfToNs) { // Implicit conversion from CF to ObjC object is needed. if (ClassMethod) { std::string ExpressionString = "["; ExpressionString += RelatedClass->getNameAsString(); ExpressionString += " "; ExpressionString += ClassMethod->getSelector().getAsString(); SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd()); // Provide a fixit: [RelatedClass ClassMethod SrcExpr] Diag(Loc, diag::err_objc_bridged_related_known_method) << SrcType << DestType << ClassMethod->getSelector() << false << FixItHint::CreateInsertion(SrcExpr->getLocStart(), ExpressionString) << FixItHint::CreateInsertion(SrcExprEndLoc, "]"); Diag(RelatedClass->getLocStart(), diag::note_declared_at); Diag(TDNDecl->getLocStart(), diag::note_declared_at); QualType receiverType = Context.getObjCInterfaceType(RelatedClass); // Argument. Expr *args[] = { SrcExpr }; ExprResult msg = BuildClassMessageImplicit(receiverType, false, ClassMethod->getLocation(), ClassMethod->getSelector(), ClassMethod, MultiExprArg(args, 1)); SrcExpr = msg.take(); return true; } } else { // Implicit conversion from ObjC type to CF object is needed. if (InstanceMethod) { std::string ExpressionString; SourceLocation SrcExprEndLoc = PP.getLocForEndOfToken(SrcExpr->getLocEnd()); if (InstanceMethod->isPropertyAccessor()) if (const ObjCPropertyDecl *PDecl = InstanceMethod->findPropertyDecl()) { // fixit: ObjectExpr.propertyname when it is aproperty accessor. ExpressionString = "."; ExpressionString += PDecl->getNameAsString(); Diag(Loc, diag::err_objc_bridged_related_known_method) << SrcType << DestType << InstanceMethod->getSelector() << true << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString); } if (ExpressionString.empty()) { // Provide a fixit: [ObjectExpr InstanceMethod] ExpressionString = " "; ExpressionString += InstanceMethod->getSelector().getAsString(); ExpressionString += "]"; Diag(Loc, diag::err_objc_bridged_related_known_method) << SrcType << DestType << InstanceMethod->getSelector() << true << FixItHint::CreateInsertion(SrcExpr->getLocStart(), "[") << FixItHint::CreateInsertion(SrcExprEndLoc, ExpressionString); } Diag(RelatedClass->getLocStart(), diag::note_declared_at); Diag(TDNDecl->getLocStart(), diag::note_declared_at); ExprResult msg = BuildInstanceMessageImplicit(SrcExpr, SrcType, InstanceMethod->getLocation(), InstanceMethod->getSelector(), InstanceMethod, None); SrcExpr = msg.take(); return true; } } return false; } Sema::ARCConversionResult Sema::CheckObjCARCConversion(SourceRange castRange, QualType castType, Expr *&castExpr, CheckedConversionKind CCK, bool DiagnoseCFAudited) { QualType castExprType = castExpr->getType(); // For the purposes of the classification, we assume reference types // will bind to temporaries. QualType effCastType = castType; if (const ReferenceType *ref = castType->getAs<ReferenceType>()) effCastType = ref->getPointeeType(); ARCConversionTypeClass exprACTC = classifyTypeForARCConversion(castExprType); ARCConversionTypeClass castACTC = classifyTypeForARCConversion(effCastType); if (exprACTC == castACTC) { // check for viablity and report error if casting an rvalue to a // life-time qualifier. if ((castACTC == ACTC_retainable) && (CCK == CCK_CStyleCast || CCK == CCK_OtherCast) && (castType != castExprType)) { const Type *DT = castType.getTypePtr(); QualType QDT = castType; // We desugar some types but not others. We ignore those // that cannot happen in a cast; i.e. auto, and those which // should not be de-sugared; i.e typedef. if (const ParenType *PT = dyn_cast<ParenType>(DT)) QDT = PT->desugar(); else if (const TypeOfType *TP = dyn_cast<TypeOfType>(DT)) QDT = TP->desugar(); else if (const AttributedType *AT = dyn_cast<AttributedType>(DT)) QDT = AT->desugar(); if (QDT != castType && QDT.getObjCLifetime() != Qualifiers::OCL_None) { SourceLocation loc = (castRange.isValid() ? castRange.getBegin() : castExpr->getExprLoc()); Diag(loc, diag::err_arc_nolifetime_behavior); } } return ACR_okay; } if (isAnyCLike(exprACTC) && isAnyCLike(castACTC)) return ACR_okay; // Allow all of these types to be cast to integer types (but not // vice-versa). if (castACTC == ACTC_none && castType->isIntegralType(Context)) return ACR_okay; // Allow casts between pointers to lifetime types (e.g., __strong id*) // and pointers to void (e.g., cv void *). Casting from void* to lifetime* // must be explicit. if (exprACTC == ACTC_indirectRetainable && castACTC == ACTC_voidPtr) return ACR_okay; if (castACTC == ACTC_indirectRetainable && exprACTC == ACTC_voidPtr && CCK != CCK_ImplicitConversion) return ACR_okay; if (castACTC == ACTC_retainable && exprACTC == ACTC_coreFoundation && (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast)) if (CheckObjCBridgeNSCast<ObjCBridgeAttr>(*this, castType, castExpr) || CheckObjCBridgeNSCast<ObjCBridgeMutableAttr>(*this, castType, castExpr)) return ACR_okay; if (castACTC == ACTC_coreFoundation && exprACTC == ACTC_retainable && (CCK == CCK_CStyleCast || CCK == CCK_FunctionalCast)) if (CheckObjCBridgeCFCast<ObjCBridgeAttr>(*this, castType, castExpr) || CheckObjCBridgeCFCast<ObjCBridgeMutableAttr>(*this, castType, castExpr)) return ACR_okay; switch (ARCCastChecker(Context, exprACTC, castACTC, false).Visit(castExpr)) { // For invalid casts, fall through. case ACC_invalid: break; // Do nothing for both bottom and +0. case ACC_bottom: case ACC_plusZero: return ACR_okay; // If the result is +1, consume it here. case ACC_plusOne: castExpr = ImplicitCastExpr::Create(Context, castExpr->getType(), CK_ARCConsumeObject, castExpr, 0, VK_RValue); ExprNeedsCleanups = true; return ACR_okay; } // If this is a non-implicit cast from id or block type to a // CoreFoundation type, delay complaining in case the cast is used // in an acceptable context. if (exprACTC == ACTC_retainable && isAnyRetainable(castACTC) && CCK != CCK_ImplicitConversion) return ACR_unbridged; // Do not issue bridge cast" diagnostic when implicit casting a cstring // to 'NSString *'. Let caller issue a normal mismatched diagnostic with // suitable fix-it. if (castACTC == ACTC_retainable && exprACTC == ACTC_none && ConversionToObjCStringLiteralCheck(castType, castExpr)) return ACR_okay; // Do not issue "bridge cast" diagnostic when implicit casting // a retainable object to a CF type parameter belonging to an audited // CF API function. Let caller issue a normal type mismatched diagnostic // instead. if (!DiagnoseCFAudited || exprACTC != ACTC_retainable || castACTC != ACTC_coreFoundation) diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr, castExpr, exprACTC, CCK); return ACR_okay; } /// Given that we saw an expression with the ARCUnbridgedCastTy /// placeholder type, complain bitterly. void Sema::diagnoseARCUnbridgedCast(Expr *e) { // We expect the spurious ImplicitCastExpr to already have been stripped. assert(!e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); CastExpr *realCast = cast<CastExpr>(e->IgnoreParens()); SourceRange castRange; QualType castType; CheckedConversionKind CCK; if (CStyleCastExpr *cast = dyn_cast<CStyleCastExpr>(realCast)) { castRange = SourceRange(cast->getLParenLoc(), cast->getRParenLoc()); castType = cast->getTypeAsWritten(); CCK = CCK_CStyleCast; } else if (ExplicitCastExpr *cast = dyn_cast<ExplicitCastExpr>(realCast)) { castRange = cast->getTypeInfoAsWritten()->getTypeLoc().getSourceRange(); castType = cast->getTypeAsWritten(); CCK = CCK_OtherCast; } else { castType = cast->getType(); CCK = CCK_ImplicitConversion; } ARCConversionTypeClass castACTC = classifyTypeForARCConversion(castType.getNonReferenceType()); Expr *castExpr = realCast->getSubExpr(); assert(classifyTypeForARCConversion(castExpr->getType()) == ACTC_retainable); diagnoseObjCARCConversion(*this, castRange, castType, castACTC, castExpr, realCast, ACTC_retainable, CCK); } /// stripARCUnbridgedCast - Given an expression of ARCUnbridgedCast /// type, remove the placeholder cast. Expr *Sema::stripARCUnbridgedCast(Expr *e) { assert(e->hasPlaceholderType(BuiltinType::ARCUnbridgedCast)); if (ParenExpr *pe = dyn_cast<ParenExpr>(e)) { Expr *sub = stripARCUnbridgedCast(pe->getSubExpr()); return new (Context) ParenExpr(pe->getLParen(), pe->getRParen(), sub); } else if (UnaryOperator *uo = dyn_cast<UnaryOperator>(e)) { assert(uo->getOpcode() == UO_Extension); Expr *sub = stripARCUnbridgedCast(uo->getSubExpr()); return new (Context) UnaryOperator(sub, UO_Extension, sub->getType(), sub->getValueKind(), sub->getObjectKind(), uo->getOperatorLoc()); } else if (GenericSelectionExpr *gse = dyn_cast<GenericSelectionExpr>(e)) { assert(!gse->isResultDependent()); unsigned n = gse->getNumAssocs(); SmallVector<Expr*, 4> subExprs(n); SmallVector<TypeSourceInfo*, 4> subTypes(n); for (unsigned i = 0; i != n; ++i) { subTypes[i] = gse->getAssocTypeSourceInfo(i); Expr *sub = gse->getAssocExpr(i); if (i == gse->getResultIndex()) sub = stripARCUnbridgedCast(sub); subExprs[i] = sub; } return new (Context) GenericSelectionExpr(Context, gse->getGenericLoc(), gse->getControllingExpr(), subTypes, subExprs, gse->getDefaultLoc(), gse->getRParenLoc(), gse->containsUnexpandedParameterPack(), gse->getResultIndex()); } else { assert(isa<ImplicitCastExpr>(e) && "bad form of unbridged cast!"); return cast<ImplicitCastExpr>(e)->getSubExpr(); } } bool Sema::CheckObjCARCUnavailableWeakConversion(QualType castType, QualType exprType) { QualType canCastType = Context.getCanonicalType(castType).getUnqualifiedType(); QualType canExprType = Context.getCanonicalType(exprType).getUnqualifiedType(); if (isa<ObjCObjectPointerType>(canCastType) && castType.getObjCLifetime() == Qualifiers::OCL_Weak && canExprType->isObjCObjectPointerType()) { if (const ObjCObjectPointerType *ObjT = canExprType->getAs<ObjCObjectPointerType>()) if (const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl()) return !ObjI->isArcWeakrefUnavailable(); } return true; } /// Look for an ObjCReclaimReturnedObject cast and destroy it. static Expr *maybeUndoReclaimObject(Expr *e) { // For now, we just undo operands that are *immediately* reclaim // expressions, which prevents the vast majority of potential // problems here. To catch them all, we'd need to rebuild arbitrary // value-propagating subexpressions --- we can't reliably rebuild // in-place because of expression sharing. if (ImplicitCastExpr *ice = dyn_cast<ImplicitCastExpr>(e)) if (ice->getCastKind() == CK_ARCReclaimReturnedObject) return ice->getSubExpr(); return e; } ExprResult Sema::BuildObjCBridgedCast(SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, TypeSourceInfo *TSInfo, Expr *SubExpr) { ExprResult SubResult = UsualUnaryConversions(SubExpr); if (SubResult.isInvalid()) return ExprError(); SubExpr = SubResult.take(); QualType T = TSInfo->getType(); QualType FromType = SubExpr->getType(); CastKind CK; bool MustConsume = false; if (T->isDependentType() || SubExpr->isTypeDependent()) { // Okay: we'll build a dependent expression type. CK = CK_Dependent; } else if (T->isObjCARCBridgableType() && FromType->isCARCBridgableType()) { // Casting CF -> id CK = (T->isBlockPointerType() ? CK_AnyPointerToBlockPointerCast : CK_CPointerToObjCPointerCast); switch (Kind) { case OBC_Bridge: break; case OBC_BridgeRetained: { bool br = isKnownName("CFBridgingRelease"); Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind) << 2 << FromType << (T->isBlockPointerType()? 1 : 0) << T << SubExpr->getSourceRange() << Kind; Diag(BridgeKeywordLoc, diag::note_arc_bridge) << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge"); Diag(BridgeKeywordLoc, diag::note_arc_bridge_transfer) << FromType << br << FixItHint::CreateReplacement(BridgeKeywordLoc, br ? "CFBridgingRelease " : "__bridge_transfer "); Kind = OBC_Bridge; break; } case OBC_BridgeTransfer: // We must consume the Objective-C object produced by the cast. MustConsume = true; break; } } else if (T->isCARCBridgableType() && FromType->isObjCARCBridgableType()) { // Okay: id -> CF CK = CK_BitCast; switch (Kind) { case OBC_Bridge: // Reclaiming a value that's going to be __bridge-casted to CF // is very dangerous, so we don't do it. SubExpr = maybeUndoReclaimObject(SubExpr); break; case OBC_BridgeRetained: // Produce the object before casting it. SubExpr = ImplicitCastExpr::Create(Context, FromType, CK_ARCProduceObject, SubExpr, 0, VK_RValue); break; case OBC_BridgeTransfer: { bool br = isKnownName("CFBridgingRetain"); Diag(BridgeKeywordLoc, diag::err_arc_bridge_cast_wrong_kind) << (FromType->isBlockPointerType()? 1 : 0) << FromType << 2 << T << SubExpr->getSourceRange() << Kind; Diag(BridgeKeywordLoc, diag::note_arc_bridge) << FixItHint::CreateReplacement(BridgeKeywordLoc, "__bridge "); Diag(BridgeKeywordLoc, diag::note_arc_bridge_retained) << T << br << FixItHint::CreateReplacement(BridgeKeywordLoc, br ? "CFBridgingRetain " : "__bridge_retained"); Kind = OBC_Bridge; break; } } } else { Diag(LParenLoc, diag::err_arc_bridge_cast_incompatible) << FromType << T << Kind << SubExpr->getSourceRange() << TSInfo->getTypeLoc().getSourceRange(); return ExprError(); } Expr *Result = new (Context) ObjCBridgedCastExpr(LParenLoc, Kind, CK, BridgeKeywordLoc, TSInfo, SubExpr); if (MustConsume) { ExprNeedsCleanups = true; Result = ImplicitCastExpr::Create(Context, T, CK_ARCConsumeObject, Result, 0, VK_RValue); } return Result; } ExprResult Sema::ActOnObjCBridgedCast(Scope *S, SourceLocation LParenLoc, ObjCBridgeCastKind Kind, SourceLocation BridgeKeywordLoc, ParsedType Type, SourceLocation RParenLoc, Expr *SubExpr) { TypeSourceInfo *TSInfo = 0; QualType T = GetTypeFromParser(Type, &TSInfo); if (Kind == OBC_Bridge) CheckTollFreeBridgeCast(T, SubExpr); if (!TSInfo) TSInfo = Context.getTrivialTypeSourceInfo(T, LParenLoc); return BuildObjCBridgedCast(LParenLoc, Kind, BridgeKeywordLoc, TSInfo, SubExpr); }
34f0813d68e0fb1b6cd090aa7cc3457cf72e1b90
e54b9ff5eaf41ab13d156430554077f133b1be06
/leetcode1710/leetcode1710_my_version.cpp
aef8b1b5631c237fe46db13aa87c956f22e45771
[]
no_license
allpasscool/leetcodes
bb0bd1391d5201baad214e5b4f8089dfe9c782b0
4fd81b4cf9382890cadc6bf8def721cc25eb9949
refs/heads/master
2022-05-21T11:34:06.958063
2022-03-24T08:57:41
2022-03-24T08:57:41
163,725,766
0
0
null
null
null
null
UTF-8
C++
false
false
939
cpp
class Solution { public: int maximumUnits(vector<vector<int>>& boxTypes, int truckSize) { sort(boxTypes.begin(), boxTypes.end(), [](const vector<int>& left, const vector<int>& right) { return left[1] > right[1]; }); int ans = 0; int count = 0; for (int i = 0; i < boxTypes.size(); ++i) { if (count + boxTypes[i][0] <= truckSize) { ans += boxTypes[i][0] * boxTypes[i][1]; count += boxTypes[i][0]; } else { ans += (truckSize - count) * boxTypes[i][1]; return ans; } } return ans; } }; // time complexity: O(n log n) // space complexity: O(1) // Runtime: 80 ms, faster than 85.99% of C++ online submissions for Maximum Units on a Truck. // Memory Usage: 16.5 MB, less than 66.27% of C++ online submissions for Maximum Units on a Truck.
2326788bd8c55329fcbc2648baaf8081901535e5
ad9ca29988acfd2cdddd573c068cfd61dfa942f0
/src/qt/splashscreen.h
f1a3fe71369313c6e7f4c98595a863b6acac2032
[ "MIT" ]
permissive
5GL/5GL
5d6ca603079e7abf673596f59c38eaa96392c42f
6a24c394206d53de3bccd4cb79a9dc22fa782ffa
refs/heads/master
2020-07-27T00:36:33.568205
2019-09-16T13:52:11
2019-09-16T13:52:11
208,810,885
1
0
null
null
null
null
UTF-8
C++
false
false
1,409
h
// Copyright (c) 2018-2019 The 5GL developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #ifndef 5GL_QT_SPLASHSCREEN_H #define 5GL_QT_SPLASHSCREEN_H #include <QSplashScreen> class NetworkStyle; /** Class for the splashscreen with information of the running client. * * @note this is intentionally not a QSplashScreen. 5GL Core initialization * can take a long time, and in that case a progress window that cannot be * moved around and minimized has turned out to be frustrating to the user. */ class SplashScreen : public QWidget { Q_OBJECT public: explicit SplashScreen(Qt::WindowFlags f, const NetworkStyle *networkStyle); ~SplashScreen(); protected: void paintEvent(QPaintEvent *event); void closeEvent(QCloseEvent *event); public slots: /** Slot to call finish() method as it's not defined as slot */ void slotFinish(QWidget *mainWin); /** Show message and progress */ void showMessage(const QString &message, int alignment, const QColor &color); private: /** Connect core signals to splash screen */ void subscribeToCoreSignals(); /** Disconnect core signals to splash screen */ void unsubscribeFromCoreSignals(); QPixmap pixmap; QString curMessage; QColor curColor; int curAlignment; }; #endif // 5GL_QT_SPLASHSCREEN_H
6970906a66a2dd5936a7a8022fe9d253ca4b6729
c804da20fc2305b36a81fb2d0b43f64e7dc89f79
/random.cpp
86618a020edd5f31a221b2d0e5b91d96e38fbdd0
[]
no_license
morisummer2/Random-question-program
39260f0f914726853791e1859f5e4eb62a8322e9
e59f7234458fa10ea32b719cae90b8e53a7249bb
refs/heads/main
2023-03-07T05:42:44.576581
2021-02-25T00:43:25
2021-02-25T00:43:25
341,868,023
0
0
null
null
null
null
UTF-8
C++
false
false
143
cpp
#include"NODE.h" #include"ITERATOR.h" #include"UI_MANAGER.h" int _tmain() { ITERATOR iterator; UI_MANAGER ui(iterator); ui.Start(); }
8b2b5dea0c153f36fef8b3b7e7bc925d67e76598
a6ceaaff1224a7db1162084f48a9ae9a4678401d
/CitrusEngine/CitrusEngine/Layer.h
ecc3e3845611d363dd33eb450cbfa89835ebfdf1
[]
no_license
Kysumi/CitrusEngine
dfba0b102f184dc63240c97630d3e0da9888c714
81b3c2d720418158b359a1ff066c52658c38d815
refs/heads/master
2018-12-26T05:49:19.271100
2018-10-20T06:27:57
2018-10-20T06:27:57
111,181,043
0
0
null
null
null
null
UTF-8
C++
false
false
426
h
#pragma once #ifndef LAYER_H #define LAYER_H #include "pugixml.hpp" #include <vector> #include <SFML\Graphics.hpp> #include "strippper.h" #include <iostream> #include "Tile.h" class Layer { public: Layer(pugi::xml_node lNode); std::string LayerId; private: bool _isVisible; std::string _description; sf::Vector2f _layerSize; sf::Vector2f _tileSize; std::vector<std::vector<Tile>> _tileMap; }; #endif // !LAYER_H
b4e77fd1dff4f3991006d7d802798a6e9061d774
c4cb9bb1ca9bd22c27def2a61380a4df3ecb0520
/native/services/inputflinger/InputReader.cpp
e5c24abfe3f6a6a8a50c07e1291237914f824838
[ "LicenseRef-scancode-unicode", "Apache-2.0" ]
permissive
SchedulerShu/android-framework
28b2da34ce883314bcc1ad808faa7b804711a9ef
44d10a60a799a1addcab49507793a94f9121be20
refs/heads/master
2021-08-22T04:52:20.070306
2017-11-29T09:57:02
2017-11-29T09:57:02
109,920,662
0
0
null
null
null
null
UTF-8
C++
false
false
295,461
cpp
/* * Copyright (C) 2014 MediaTek Inc. * Modification based on code covered by the mentioned copyright * and/or permission notice(s). */ /* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "InputReader" //#define LOG_NDEBUG 0 // Log debug messages for each raw event received from the EventHub. #define DEBUG_RAW_EVENTS 0 // Log debug messages about touch screen filtering hacks. #define DEBUG_HACKS 0 // Log debug messages about virtual key processing. #define DEBUG_VIRTUAL_KEYS 0 // Log debug messages about pointers. #define DEBUG_POINTERS 0 // Log debug messages about pointer assignment calculations. #define DEBUG_POINTER_ASSIGNMENT 0 // Log debug messages about gesture detection. #define DEBUG_GESTURES 0 // Log debug messages about the vibrator. #define DEBUG_VIBRATOR 0 // Log debug messages about fusing stylus data. #define DEBUG_STYLUS_FUSION 0 #include "InputReader.h" #include <cutils/log.h> #include <input/Keyboard.h> #include <input/VirtualKeyMap.h> #include <inttypes.h> #include <stddef.h> #include <stdlib.h> #include <unistd.h> #include <errno.h> #include <limits.h> #include <math.h> #include <utils/Trace.h> #include <cutils/properties.h> #define INDENT " " #define INDENT2 " " #define INDENT3 " " #define INDENT4 " " #define INDENT5 " " /// M: Switch log by command @{ #define ALOGD_READER(...) if (gInputLogReader) __android_log_print(ANDROID_LOG_DEBUG, LOG_TAG, __VA_ARGS__) /// @} namespace android { /// M: Switch log by command @{ static bool gInputLogReader = false;//false; /// @} // --- Constants --- // Maximum number of slots supported when using the slot-based Multitouch Protocol B. static const size_t MAX_SLOTS = 32; // Maximum amount of latency to add to touch events while waiting for data from an // external stylus. static const nsecs_t EXTERNAL_STYLUS_DATA_TIMEOUT = ms2ns(72); // Maximum amount of time to wait on touch data before pushing out new pressure data. static const nsecs_t TOUCH_DATA_TIMEOUT = ms2ns(20); // Artificial latency on synthetic events created from stylus data without corresponding touch // data. static const nsecs_t STYLUS_DATA_LATENCY = ms2ns(10); // --- Static Functions --- template<typename T> inline static T abs(const T& value) { return value < 0 ? - value : value; } template<typename T> inline static T min(const T& a, const T& b) { return a < b ? a : b; } template<typename T> inline static void swap(T& a, T& b) { T temp = a; a = b; b = temp; } inline static float avg(float x, float y) { return (x + y) / 2; } inline static float distance(float x1, float y1, float x2, float y2) { return hypotf(x1 - x2, y1 - y2); } inline static int32_t signExtendNybble(int32_t value) { return value >= 8 ? value - 16 : value; } static inline const char* toString(bool value) { return value ? "true" : "false"; } static int32_t rotateValueUsingRotationMap(int32_t value, int32_t orientation, const int32_t map[][4], size_t mapSize) { if (orientation != DISPLAY_ORIENTATION_0) { for (size_t i = 0; i < mapSize; i++) { if (value == map[i][0]) { return map[i][orientation]; } } } return value; } static const int32_t keyCodeRotationMap[][4] = { // key codes enumerated counter-clockwise with the original (unrotated) key first // no rotation, 90 degree rotation, 180 degree rotation, 270 degree rotation { AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT }, { AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN }, { AKEYCODE_DPAD_UP, AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT }, { AKEYCODE_DPAD_LEFT, AKEYCODE_DPAD_DOWN, AKEYCODE_DPAD_RIGHT, AKEYCODE_DPAD_UP }, }; static const size_t keyCodeRotationMapSize = sizeof(keyCodeRotationMap) / sizeof(keyCodeRotationMap[0]); static int32_t rotateKeyCode(int32_t keyCode, int32_t orientation) { return rotateValueUsingRotationMap(keyCode, orientation, keyCodeRotationMap, keyCodeRotationMapSize); } static void rotateDelta(int32_t orientation, float* deltaX, float* deltaY) { float temp; switch (orientation) { case DISPLAY_ORIENTATION_90: temp = *deltaX; *deltaX = *deltaY; *deltaY = -temp; break; case DISPLAY_ORIENTATION_180: *deltaX = -*deltaX; *deltaY = -*deltaY; break; case DISPLAY_ORIENTATION_270: temp = *deltaX; *deltaX = -*deltaY; *deltaY = temp; break; } } static inline bool sourcesMatchMask(uint32_t sources, uint32_t sourceMask) { return (sources & sourceMask & ~ AINPUT_SOURCE_CLASS_MASK) != 0; } // Returns true if the pointer should be reported as being down given the specified // button states. This determines whether the event is reported as a touch event. static bool isPointerDown(int32_t buttonState) { return buttonState & (AMOTION_EVENT_BUTTON_PRIMARY | AMOTION_EVENT_BUTTON_SECONDARY | AMOTION_EVENT_BUTTON_TERTIARY); } static float calculateCommonVector(float a, float b) { if (a > 0 && b > 0) { return a < b ? a : b; } else if (a < 0 && b < 0) { return a > b ? a : b; } else { return 0; } } static void synthesizeButtonKey(InputReaderContext* context, int32_t action, nsecs_t when, int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState, int32_t buttonState, int32_t keyCode) { if ( (action == AKEY_EVENT_ACTION_DOWN && !(lastButtonState & buttonState) && (currentButtonState & buttonState)) || (action == AKEY_EVENT_ACTION_UP && (lastButtonState & buttonState) && !(currentButtonState & buttonState))) { NotifyKeyArgs args(when, deviceId, source, policyFlags, action, 0, keyCode, 0, context->getGlobalMetaState(), when); context->getListener()->notifyKey(&args); } } static void synthesizeButtonKeys(InputReaderContext* context, int32_t action, nsecs_t when, int32_t deviceId, uint32_t source, uint32_t policyFlags, int32_t lastButtonState, int32_t currentButtonState) { synthesizeButtonKey(context, action, when, deviceId, source, policyFlags, lastButtonState, currentButtonState, AMOTION_EVENT_BUTTON_BACK, AKEYCODE_BACK); synthesizeButtonKey(context, action, when, deviceId, source, policyFlags, lastButtonState, currentButtonState, AMOTION_EVENT_BUTTON_FORWARD, AKEYCODE_FORWARD); } // --- InputReaderConfiguration --- bool InputReaderConfiguration::getDisplayInfo(bool external, DisplayViewport* outViewport) const { const DisplayViewport& viewport = external ? mExternalDisplay : mInternalDisplay; if (viewport.displayId >= 0) { *outViewport = viewport; return true; } return false; } void InputReaderConfiguration::setDisplayInfo(bool external, const DisplayViewport& viewport) { DisplayViewport& v = external ? mExternalDisplay : mInternalDisplay; v = viewport; } // -- TouchAffineTransformation -- void TouchAffineTransformation::applyTo(float& x, float& y) const { float newX, newY; newX = x * x_scale + y * x_ymix + x_offset; newY = x * y_xmix + y * y_scale + y_offset; x = newX; y = newY; } // --- InputReader --- InputReader::InputReader(const sp<EventHubInterface>& eventHub, const sp<InputReaderPolicyInterface>& policy, const sp<InputListenerInterface>& listener) : mContext(this), mEventHub(eventHub), mPolicy(policy), mGlobalMetaState(0), mGeneration(1), mDisableVirtualKeysTimeout(LLONG_MIN), mNextTimeout(LLONG_MAX), mConfigurationChangesToRefresh(0) { mQueuedListener = new QueuedInputListener(listener); { // acquire lock AutoMutex _l(mLock); ALOGD("InputReader:: InputReader lock " ); refreshConfigurationLocked(0); updateGlobalMetaStateLocked(); } // release lock ALOGD("InputReader:: InputReader unlock " ); } InputReader::~InputReader() { for (size_t i = 0; i < mDevices.size(); i++) { delete mDevices.valueAt(i); } } void InputReader::loopOnce() { int32_t oldGeneration; int32_t timeoutMillis; bool inputDevicesChanged = false; Vector<InputDeviceInfo> inputDevices; { // acquire lock AutoMutex _l(mLock); oldGeneration = mGeneration; timeoutMillis = -1; uint32_t changes = mConfigurationChangesToRefresh; if (changes) { mConfigurationChangesToRefresh = 0; timeoutMillis = 0; refreshConfigurationLocked(changes); } else if (mNextTimeout != LLONG_MAX) { nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); timeoutMillis = toMillisecondTimeoutDelay(now, mNextTimeout); } } // release lock size_t count = mEventHub->getEvents(timeoutMillis, mEventBuffer, EVENT_BUFFER_SIZE); { // acquire lock AutoMutex _l(mLock); mReaderIsAliveCondition.broadcast(); if (count) { processEventsLocked(mEventBuffer, count); } if (mNextTimeout != LLONG_MAX) { nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); if (now >= mNextTimeout) { #if DEBUG_RAW_EVENTS ALOGD("Timeout expired, latency=%0.3fms", (now - mNextTimeout) * 0.000001f); #endif mNextTimeout = LLONG_MAX; timeoutExpiredLocked(now); } } if (oldGeneration != mGeneration) { inputDevicesChanged = true; getInputDevicesLocked(inputDevices); } } // release lock // Send out a message that the describes the changed input devices. if (inputDevicesChanged) { mPolicy->notifyInputDevicesChanged(inputDevices); } // Flush queued events out to the listener. // This must happen outside of the lock because the listener could potentially call // back into the InputReader's methods, such as getScanCodeState, or become blocked // on another thread similarly waiting to acquire the InputReader lock thereby // resulting in a deadlock. This situation is actually quite plausible because the // listener is actually the input dispatcher, which calls into the window manager, // which occasionally calls into the input reader. mQueuedListener->flush(); } void InputReader::processEventsLocked(const RawEvent* rawEvents, size_t count) { for (const RawEvent* rawEvent = rawEvents; count;) { int32_t type = rawEvent->type; size_t batchSize = 1; if (type < EventHubInterface::FIRST_SYNTHETIC_EVENT) { int32_t deviceId = rawEvent->deviceId; while (batchSize < count) { if (rawEvent[batchSize].type >= EventHubInterface::FIRST_SYNTHETIC_EVENT || rawEvent[batchSize].deviceId != deviceId) { break; } batchSize += 1; } #if DEBUG_RAW_EVENTS ALOGD("BatchSize: %d Count: %d", batchSize, count); #endif processEventsForDeviceLocked(deviceId, rawEvent, batchSize); } else { switch (rawEvent->type) { case EventHubInterface::DEVICE_ADDED: addDeviceLocked(rawEvent->when, rawEvent->deviceId); break; case EventHubInterface::DEVICE_REMOVED: removeDeviceLocked(rawEvent->when, rawEvent->deviceId); break; case EventHubInterface::FINISHED_DEVICE_SCAN: handleConfigurationChangedLocked(rawEvent->when); break; default: ALOG_ASSERT(false); // can't happen break; } } count -= batchSize; rawEvent += batchSize; } } void InputReader::addDeviceLocked(nsecs_t when, int32_t deviceId) { ssize_t deviceIndex = mDevices.indexOfKey(deviceId); if (deviceIndex >= 0) { ALOGW("Ignoring spurious device added event for deviceId %d.", deviceId); return; } InputDeviceIdentifier identifier = mEventHub->getDeviceIdentifier(deviceId); uint32_t classes = mEventHub->getDeviceClasses(deviceId); int32_t controllerNumber = mEventHub->getDeviceControllerNumber(deviceId); InputDevice* device = createDeviceLocked(deviceId, controllerNumber, identifier, classes); device->configure(when, &mConfig, 0); device->reset(when); if (device->isIgnored()) { ALOGI("Device added: id=%d, name='%s' (ignored non-input device)", deviceId, identifier.name.string()); } else { ALOGI("Device added: id=%d, name='%s', sources=0x%08x", deviceId, identifier.name.string(), device->getSources()); } mDevices.add(deviceId, device); bumpGenerationLocked(); if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) { notifyExternalStylusPresenceChanged(); } } void InputReader::removeDeviceLocked(nsecs_t when, int32_t deviceId) { InputDevice* device = NULL; ssize_t deviceIndex = mDevices.indexOfKey(deviceId); if (deviceIndex < 0) { ALOGW("Ignoring spurious device removed event for deviceId %d.", deviceId); return; } device = mDevices.valueAt(deviceIndex); mDevices.removeItemsAt(deviceIndex, 1); bumpGenerationLocked(); if (device->isIgnored()) { ALOGI("Device removed: id=%d, name='%s' (ignored non-input device)", device->getId(), device->getName().string()); } else { ALOGI("Device removed: id=%d, name='%s', sources=0x%08x", device->getId(), device->getName().string(), device->getSources()); } if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) { notifyExternalStylusPresenceChanged(); } device->reset(when); delete device; } InputDevice* InputReader::createDeviceLocked(int32_t deviceId, int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) { InputDevice* device = new InputDevice(&mContext, deviceId, bumpGenerationLocked(), controllerNumber, identifier, classes); // External devices. if (classes & INPUT_DEVICE_CLASS_EXTERNAL) { device->setExternal(true); } // Devices with mics. if (classes & INPUT_DEVICE_CLASS_MIC) { device->setMic(true); } // Switch-like devices. if (classes & INPUT_DEVICE_CLASS_SWITCH) { device->addMapper(new SwitchInputMapper(device)); } // Scroll wheel-like devices. if (classes & INPUT_DEVICE_CLASS_ROTARY_ENCODER) { device->addMapper(new RotaryEncoderInputMapper(device)); } // Vibrator-like devices. if (classes & INPUT_DEVICE_CLASS_VIBRATOR) { device->addMapper(new VibratorInputMapper(device)); } // Keyboard-like devices. uint32_t keyboardSource = 0; int32_t keyboardType = AINPUT_KEYBOARD_TYPE_NON_ALPHABETIC; if (classes & INPUT_DEVICE_CLASS_KEYBOARD) { keyboardSource |= AINPUT_SOURCE_KEYBOARD; } if (classes & INPUT_DEVICE_CLASS_ALPHAKEY) { keyboardType = AINPUT_KEYBOARD_TYPE_ALPHABETIC; } if (classes & INPUT_DEVICE_CLASS_DPAD) { keyboardSource |= AINPUT_SOURCE_DPAD; } if (classes & INPUT_DEVICE_CLASS_GAMEPAD) { keyboardSource |= AINPUT_SOURCE_GAMEPAD; } if (keyboardSource != 0) { device->addMapper(new KeyboardInputMapper(device, keyboardSource, keyboardType)); } // Cursor-like devices. if (classes & INPUT_DEVICE_CLASS_CURSOR) { device->addMapper(new CursorInputMapper(device)); } // Touchscreens and touchpad devices. if (classes & INPUT_DEVICE_CLASS_TOUCH_MT) { device->addMapper(new MultiTouchInputMapper(device)); } else if (classes & INPUT_DEVICE_CLASS_TOUCH) { device->addMapper(new SingleTouchInputMapper(device)); } // Joystick-like devices. if (classes & INPUT_DEVICE_CLASS_JOYSTICK) { device->addMapper(new JoystickInputMapper(device)); } // External stylus-like devices. if (classes & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS) { device->addMapper(new ExternalStylusInputMapper(device)); } return device; } void InputReader::processEventsForDeviceLocked(int32_t deviceId, const RawEvent* rawEvents, size_t count) { ssize_t deviceIndex = mDevices.indexOfKey(deviceId); if (deviceIndex < 0) { ALOGW("Discarding event for unknown deviceId %d.", deviceId); return; } InputDevice* device = mDevices.valueAt(deviceIndex); if (device->isIgnored()) { //ALOGD("Discarding event for ignored deviceId %d.", deviceId); return; } device->process(rawEvents, count); } void InputReader::timeoutExpiredLocked(nsecs_t when) { for (size_t i = 0; i < mDevices.size(); i++) { InputDevice* device = mDevices.valueAt(i); if (!device->isIgnored()) { device->timeoutExpired(when); } } } void InputReader::handleConfigurationChangedLocked(nsecs_t when) { // Reset global meta state because it depends on the list of all configured devices. updateGlobalMetaStateLocked(); // Enqueue configuration changed. NotifyConfigurationChangedArgs args(when); mQueuedListener->notifyConfigurationChanged(&args); } void InputReader::refreshConfigurationLocked(uint32_t changes) { mPolicy->getReaderConfiguration(&mConfig); mEventHub->setExcludedDevices(mConfig.excludedDeviceNames); if (changes) { ALOGI("Reconfiguring input devices. changes=0x%08x", changes); nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); if (changes & InputReaderConfiguration::CHANGE_MUST_REOPEN) { mEventHub->requestReopenDevices(); } else { for (size_t i = 0; i < mDevices.size(); i++) { InputDevice* device = mDevices.valueAt(i); device->configure(now, &mConfig, changes); } } } } void InputReader::updateGlobalMetaStateLocked() { mGlobalMetaState = 0; for (size_t i = 0; i < mDevices.size(); i++) { InputDevice* device = mDevices.valueAt(i); mGlobalMetaState |= device->getMetaState(); } } int32_t InputReader::getGlobalMetaStateLocked() { return mGlobalMetaState; } void InputReader::notifyExternalStylusPresenceChanged() { refreshConfigurationLocked(InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE); } void InputReader::getExternalStylusDevicesLocked(Vector<InputDeviceInfo>& outDevices) { for (size_t i = 0; i < mDevices.size(); i++) { InputDevice* device = mDevices.valueAt(i); if (device->getClasses() & INPUT_DEVICE_CLASS_EXTERNAL_STYLUS && !device->isIgnored()) { outDevices.push(); device->getDeviceInfo(&outDevices.editTop()); } } } void InputReader::dispatchExternalStylusState(const StylusState& state) { for (size_t i = 0; i < mDevices.size(); i++) { InputDevice* device = mDevices.valueAt(i); device->updateExternalStylusState(state); } } void InputReader::disableVirtualKeysUntilLocked(nsecs_t time) { mDisableVirtualKeysTimeout = time; } bool InputReader::shouldDropVirtualKeyLocked(nsecs_t now, InputDevice* device, int32_t keyCode, int32_t scanCode) { if (now < mDisableVirtualKeysTimeout) { ALOGI("Dropping virtual key from device %s because virtual keys are " "temporarily disabled for the next %0.3fms. keyCode=%d, scanCode=%d", device->getName().string(), (mDisableVirtualKeysTimeout - now) * 0.000001, keyCode, scanCode); return true; } else { return false; } } void InputReader::fadePointerLocked() { for (size_t i = 0; i < mDevices.size(); i++) { InputDevice* device = mDevices.valueAt(i); device->fadePointer(); } } void InputReader::requestTimeoutAtTimeLocked(nsecs_t when) { if (when < mNextTimeout) { mNextTimeout = when; mEventHub->wake(); } } int32_t InputReader::bumpGenerationLocked() { return ++mGeneration; } void InputReader::getInputDevices(Vector<InputDeviceInfo>& outInputDevices) { AutoMutex _l(mLock); ALOGD("getInputDevices:: acquire lock " ); getInputDevicesLocked(outInputDevices); ALOGD("getInputDevices:: release lock " ); } void InputReader::getInputDevicesLocked(Vector<InputDeviceInfo>& outInputDevices) { outInputDevices.clear(); size_t numDevices = mDevices.size(); for (size_t i = 0; i < numDevices; i++) { InputDevice* device = mDevices.valueAt(i); if (!device->isIgnored()) { outInputDevices.push(); device->getDeviceInfo(&outInputDevices.editTop()); } } } int32_t InputReader::getKeyCodeState(int32_t deviceId, uint32_t sourceMask, int32_t keyCode) { AutoMutex _l(mLock); ALOGD("InputReader:: getKeyCodeState lock " ); return getStateLocked(deviceId, sourceMask, keyCode, &InputDevice::getKeyCodeState); } int32_t InputReader::getScanCodeState(int32_t deviceId, uint32_t sourceMask, int32_t scanCode) { AutoMutex _l(mLock); ALOGD("InputReader:: getScanCodeState lock " ); return getStateLocked(deviceId, sourceMask, scanCode, &InputDevice::getScanCodeState); } int32_t InputReader::getSwitchState(int32_t deviceId, uint32_t sourceMask, int32_t switchCode) { AutoMutex _l(mLock); ALOGD("InputReader:: getSwitchState lock " ); return getStateLocked(deviceId, sourceMask, switchCode, &InputDevice::getSwitchState); } int32_t InputReader::getStateLocked(int32_t deviceId, uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) { int32_t result = AKEY_STATE_UNKNOWN; if (deviceId >= 0) { ssize_t deviceIndex = mDevices.indexOfKey(deviceId); if (deviceIndex >= 0) { InputDevice* device = mDevices.valueAt(deviceIndex); if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { result = (device->*getStateFunc)(sourceMask, code); } } } else { size_t numDevices = mDevices.size(); for (size_t i = 0; i < numDevices; i++) { InputDevice* device = mDevices.valueAt(i); if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { // If any device reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that // value. Otherwise, return AKEY_STATE_UP as long as one device reports it. int32_t currentResult = (device->*getStateFunc)(sourceMask, code); if (currentResult >= AKEY_STATE_DOWN) { return currentResult; } else if (currentResult == AKEY_STATE_UP) { result = currentResult; } } } } ALOGD("InputReader::getStateLocked:: return " ); return result; } void InputReader::toggleCapsLockState(int32_t deviceId) { ssize_t deviceIndex = mDevices.indexOfKey(deviceId); if (deviceIndex < 0) { ALOGW("Ignoring toggleCapsLock for unknown deviceId %" PRId32 ".", deviceId); return; } InputDevice* device = mDevices.valueAt(deviceIndex); if (device->isIgnored()) { return; } device->updateMetaState(AKEYCODE_CAPS_LOCK); } bool InputReader::hasKeys(int32_t deviceId, uint32_t sourceMask, size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { AutoMutex _l(mLock); ALOGD("K_lock" ); memset(outFlags, 0, numCodes); return markSupportedKeyCodesLocked(deviceId, sourceMask, numCodes, keyCodes, outFlags); } bool InputReader::markSupportedKeyCodesLocked(int32_t deviceId, uint32_t sourceMask, size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { bool result = false; if (deviceId >= 0) { ssize_t deviceIndex = mDevices.indexOfKey(deviceId); if (deviceIndex >= 0) { InputDevice* device = mDevices.valueAt(deviceIndex); if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { result = device->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags); } } } else { size_t numDevices = mDevices.size(); for (size_t i = 0; i < numDevices; i++) { InputDevice* device = mDevices.valueAt(i); if (! device->isIgnored() && sourcesMatchMask(device->getSources(), sourceMask)) { result |= device->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags); } } } ALOGD("SK_Lock_r" ); return result; } void InputReader::requestRefreshConfiguration(uint32_t changes) { AutoMutex _l(mLock); ALOGD("InputReader:: requestRefreshConfiguration lock " ); if (changes) { bool needWake = !mConfigurationChangesToRefresh; mConfigurationChangesToRefresh |= changes; if (needWake) { mEventHub->wake(); } } ALOGD("InputReader:: requestRefreshConfiguration unlock " ); } void InputReader::vibrate(int32_t deviceId, const nsecs_t* pattern, size_t patternSize, ssize_t repeat, int32_t token) { AutoMutex _l(mLock); ALOGD("InputReader:: vibrate lock " ); ssize_t deviceIndex = mDevices.indexOfKey(deviceId); if (deviceIndex >= 0) { InputDevice* device = mDevices.valueAt(deviceIndex); device->vibrate(pattern, patternSize, repeat, token); } ALOGD("InputReader:: vibrate unlock " ); } void InputReader::cancelVibrate(int32_t deviceId, int32_t token) { AutoMutex _l(mLock); ALOGD("InputReader:: cancelVibrate lock " ); ssize_t deviceIndex = mDevices.indexOfKey(deviceId); if (deviceIndex >= 0) { InputDevice* device = mDevices.valueAt(deviceIndex); device->cancelVibrate(token); } ALOGD("InputReader:: cancelVibrate unlock " ); } void InputReader::dump(String8& dump) { AutoMutex _l(mLock); ALOGD("InputReader:: dump lock " ); /// M: Switch log by command @{ char buf[PROPERTY_VALUE_MAX]; property_get("sys.inputlog.latency", buf, "false"); if (!strcmp(buf, "true")) { gInputLogReader = true; ALOGD("Input reader log is enabled"); } else if (!strcmp(buf, "false")) { gInputLogReader = false; ALOGD("Input reader log is disabled"); } /// @} mEventHub->dump(dump); dump.append("\n"); dump.append("Input Reader State:\n"); for (size_t i = 0; i < mDevices.size(); i++) { mDevices.valueAt(i)->dump(dump); } dump.append(INDENT "Configuration:\n"); dump.append(INDENT2 "ExcludedDeviceNames: ["); for (size_t i = 0; i < mConfig.excludedDeviceNames.size(); i++) { if (i != 0) { dump.append(", "); } dump.append(mConfig.excludedDeviceNames.itemAt(i).string()); } dump.append("]\n"); dump.appendFormat(INDENT2 "VirtualKeyQuietTime: %0.1fms\n", mConfig.virtualKeyQuietTime * 0.000001f); dump.appendFormat(INDENT2 "PointerVelocityControlParameters: " "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n", mConfig.pointerVelocityControlParameters.scale, mConfig.pointerVelocityControlParameters.lowThreshold, mConfig.pointerVelocityControlParameters.highThreshold, mConfig.pointerVelocityControlParameters.acceleration); dump.appendFormat(INDENT2 "WheelVelocityControlParameters: " "scale=%0.3f, lowThreshold=%0.3f, highThreshold=%0.3f, acceleration=%0.3f\n", mConfig.wheelVelocityControlParameters.scale, mConfig.wheelVelocityControlParameters.lowThreshold, mConfig.wheelVelocityControlParameters.highThreshold, mConfig.wheelVelocityControlParameters.acceleration); dump.appendFormat(INDENT2 "PointerGesture:\n"); dump.appendFormat(INDENT3 "Enabled: %s\n", toString(mConfig.pointerGesturesEnabled)); dump.appendFormat(INDENT3 "QuietInterval: %0.1fms\n", mConfig.pointerGestureQuietInterval * 0.000001f); dump.appendFormat(INDENT3 "DragMinSwitchSpeed: %0.1fpx/s\n", mConfig.pointerGestureDragMinSwitchSpeed); dump.appendFormat(INDENT3 "TapInterval: %0.1fms\n", mConfig.pointerGestureTapInterval * 0.000001f); dump.appendFormat(INDENT3 "TapDragInterval: %0.1fms\n", mConfig.pointerGestureTapDragInterval * 0.000001f); dump.appendFormat(INDENT3 "TapSlop: %0.1fpx\n", mConfig.pointerGestureTapSlop); dump.appendFormat(INDENT3 "MultitouchSettleInterval: %0.1fms\n", mConfig.pointerGestureMultitouchSettleInterval * 0.000001f); dump.appendFormat(INDENT3 "MultitouchMinDistance: %0.1fpx\n", mConfig.pointerGestureMultitouchMinDistance); dump.appendFormat(INDENT3 "SwipeTransitionAngleCosine: %0.1f\n", mConfig.pointerGestureSwipeTransitionAngleCosine); dump.appendFormat(INDENT3 "SwipeMaxWidthRatio: %0.1f\n", mConfig.pointerGestureSwipeMaxWidthRatio); dump.appendFormat(INDENT3 "MovementSpeedRatio: %0.1f\n", mConfig.pointerGestureMovementSpeedRatio); dump.appendFormat(INDENT3 "ZoomSpeedRatio: %0.1f\n", mConfig.pointerGestureZoomSpeedRatio); ALOGD("InputReader:: dump unlock " ); } void InputReader::monitor() { // Acquire and release the lock to ensure that the reader has not deadlocked. mLock.lock(); ALOGD("InputReader::monitor: lock" ); mEventHub->wake(); ALOGD("InputReader::monitor: wait " ); mReaderIsAliveCondition.wait(mLock); mLock.unlock(); ALOGD("InputReader::monitor: unlock" ); // Check the EventHub mEventHub->monitor(); ALOGD("InputReader::monitor: done" ); } // --- InputReader::ContextImpl --- InputReader::ContextImpl::ContextImpl(InputReader* reader) : mReader(reader) { } void InputReader::ContextImpl::updateGlobalMetaState() { // lock is already held by the input loop mReader->updateGlobalMetaStateLocked(); } int32_t InputReader::ContextImpl::getGlobalMetaState() { // lock is already held by the input loop return mReader->getGlobalMetaStateLocked(); } void InputReader::ContextImpl::disableVirtualKeysUntil(nsecs_t time) { // lock is already held by the input loop mReader->disableVirtualKeysUntilLocked(time); } bool InputReader::ContextImpl::shouldDropVirtualKey(nsecs_t now, InputDevice* device, int32_t keyCode, int32_t scanCode) { // lock is already held by the input loop return mReader->shouldDropVirtualKeyLocked(now, device, keyCode, scanCode); } void InputReader::ContextImpl::fadePointer() { // lock is already held by the input loop mReader->fadePointerLocked(); } void InputReader::ContextImpl::requestTimeoutAtTime(nsecs_t when) { // lock is already held by the input loop mReader->requestTimeoutAtTimeLocked(when); } int32_t InputReader::ContextImpl::bumpGeneration() { // lock is already held by the input loop return mReader->bumpGenerationLocked(); } void InputReader::ContextImpl::getExternalStylusDevices(Vector<InputDeviceInfo>& outDevices) { // lock is already held by whatever called refreshConfigurationLocked mReader->getExternalStylusDevicesLocked(outDevices); } void InputReader::ContextImpl::dispatchExternalStylusState(const StylusState& state) { mReader->dispatchExternalStylusState(state); } InputReaderPolicyInterface* InputReader::ContextImpl::getPolicy() { return mReader->mPolicy.get(); } InputListenerInterface* InputReader::ContextImpl::getListener() { return mReader->mQueuedListener.get(); } EventHubInterface* InputReader::ContextImpl::getEventHub() { return mReader->mEventHub.get(); } // --- InputReaderThread --- InputReaderThread::InputReaderThread(const sp<InputReaderInterface>& reader) : Thread(/*canCallJava*/ true), mReader(reader) { } InputReaderThread::~InputReaderThread() { } bool InputReaderThread::threadLoop() { mReader->loopOnce(); return true; } // --- InputDevice --- InputDevice::InputDevice(InputReaderContext* context, int32_t id, int32_t generation, int32_t controllerNumber, const InputDeviceIdentifier& identifier, uint32_t classes) : mContext(context), mId(id), mGeneration(generation), mControllerNumber(controllerNumber), mIdentifier(identifier), mClasses(classes), mSources(0), mIsExternal(false), mHasMic(false), mDropUntilNextSync(false) { } InputDevice::~InputDevice() { size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { delete mMappers[i]; } mMappers.clear(); } void InputDevice::dump(String8& dump) { InputDeviceInfo deviceInfo; getDeviceInfo(& deviceInfo); dump.appendFormat(INDENT "Device %d: %s\n", deviceInfo.getId(), deviceInfo.getDisplayName().string()); dump.appendFormat(INDENT2 "Generation: %d\n", mGeneration); dump.appendFormat(INDENT2 "IsExternal: %s\n", toString(mIsExternal)); dump.appendFormat(INDENT2 "HasMic: %s\n", toString(mHasMic)); dump.appendFormat(INDENT2 "Sources: 0x%08x\n", deviceInfo.getSources()); dump.appendFormat(INDENT2 "KeyboardType: %d\n", deviceInfo.getKeyboardType()); const Vector<InputDeviceInfo::MotionRange>& ranges = deviceInfo.getMotionRanges(); if (!ranges.isEmpty()) { dump.append(INDENT2 "Motion Ranges:\n"); for (size_t i = 0; i < ranges.size(); i++) { const InputDeviceInfo::MotionRange& range = ranges.itemAt(i); const char* label = getAxisLabel(range.axis); char name[32]; if (label) { strncpy(name, label, sizeof(name)); name[sizeof(name) - 1] = '\0'; } else { snprintf(name, sizeof(name), "%d", range.axis); } dump.appendFormat(INDENT3 "%s: source=0x%08x, " "min=%0.3f, max=%0.3f, flat=%0.3f, fuzz=%0.3f, resolution=%0.3f\n", name, range.source, range.min, range.max, range.flat, range.fuzz, range.resolution); } } size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->dump(dump); } } void InputDevice::addMapper(InputMapper* mapper) { mMappers.add(mapper); } void InputDevice::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) { mSources = 0; if (!isIgnored()) { if (!changes) { // first time only mContext->getEventHub()->getConfiguration(mId, &mConfiguration); } if (!changes || (changes & InputReaderConfiguration::CHANGE_KEYBOARD_LAYOUTS)) { if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) { sp<KeyCharacterMap> keyboardLayout = mContext->getPolicy()->getKeyboardLayoutOverlay(mIdentifier); if (mContext->getEventHub()->setKeyboardLayoutOverlay(mId, keyboardLayout)) { bumpGeneration(); } } } if (!changes || (changes & InputReaderConfiguration::CHANGE_DEVICE_ALIAS)) { if (!(mClasses & INPUT_DEVICE_CLASS_VIRTUAL)) { String8 alias = mContext->getPolicy()->getDeviceAlias(mIdentifier); if (mAlias != alias) { mAlias = alias; bumpGeneration(); } } } size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->configure(when, config, changes); mSources |= mapper->getSources(); } } } void InputDevice::reset(nsecs_t when) { size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->reset(when); } mContext->updateGlobalMetaState(); notifyReset(when); } void InputDevice::process(const RawEvent* rawEvents, size_t count) { // Process all of the events in order for each mapper. // We cannot simply ask each mapper to process them in bulk because mappers may // have side-effects that must be interleaved. For example, joystick movement events and // gamepad button presses are handled by different mappers but they should be dispatched // in the order received. size_t numMappers = mMappers.size(); for (const RawEvent* rawEvent = rawEvents; count--; rawEvent++) { #if DEBUG_RAW_EVENTS ALOGD("Input event: device=%d type=0x%04x code=0x%04x value=0x%08x when=%lld", rawEvent->deviceId, rawEvent->type, rawEvent->code, rawEvent->value, rawEvent->when); #endif if (mDropUntilNextSync) { if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) { mDropUntilNextSync = false; #if DEBUG_RAW_EVENTS ALOGD("Recovered from input event buffer overrun."); #endif } else { #if DEBUG_RAW_EVENTS ALOGD("Dropped input event while waiting for next input sync."); #endif } } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_DROPPED) { ALOGI("Detected input event buffer overrun for device %s.", getName().string()); mDropUntilNextSync = true; reset(rawEvent->when); } else { for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->process(rawEvent); } } } } void InputDevice::timeoutExpired(nsecs_t when) { size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->timeoutExpired(when); } } void InputDevice::updateExternalStylusState(const StylusState& state) { size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->updateExternalStylusState(state); } } void InputDevice::getDeviceInfo(InputDeviceInfo* outDeviceInfo) { outDeviceInfo->initialize(mId, mGeneration, mControllerNumber, mIdentifier, mAlias, mIsExternal, mHasMic); size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->populateDeviceInfo(outDeviceInfo); } } int32_t InputDevice::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { return getState(sourceMask, keyCode, & InputMapper::getKeyCodeState); } int32_t InputDevice::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { return getState(sourceMask, scanCode, & InputMapper::getScanCodeState); } int32_t InputDevice::getSwitchState(uint32_t sourceMask, int32_t switchCode) { return getState(sourceMask, switchCode, & InputMapper::getSwitchState); } int32_t InputDevice::getState(uint32_t sourceMask, int32_t code, GetStateFunc getStateFunc) { int32_t result = AKEY_STATE_UNKNOWN; size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; if (sourcesMatchMask(mapper->getSources(), sourceMask)) { // If any mapper reports AKEY_STATE_DOWN or AKEY_STATE_VIRTUAL, return that // value. Otherwise, return AKEY_STATE_UP as long as one mapper reports it. int32_t currentResult = (mapper->*getStateFunc)(sourceMask, code); if (currentResult >= AKEY_STATE_DOWN) { return currentResult; } else if (currentResult == AKEY_STATE_UP) { result = currentResult; } } } return result; } bool InputDevice::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { bool result = false; size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; if (sourcesMatchMask(mapper->getSources(), sourceMask)) { result |= mapper->markSupportedKeyCodes(sourceMask, numCodes, keyCodes, outFlags); } } return result; } void InputDevice::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat, int32_t token) { size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->vibrate(pattern, patternSize, repeat, token); } } void InputDevice::cancelVibrate(int32_t token) { size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->cancelVibrate(token); } } void InputDevice::cancelTouch(nsecs_t when) { size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->cancelTouch(when); } } int32_t InputDevice::getMetaState() { int32_t result = 0; size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; result |= mapper->getMetaState(); } return result; } void InputDevice::updateMetaState(int32_t keyCode) { size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { mMappers[i]->updateMetaState(keyCode); } } void InputDevice::fadePointer() { size_t numMappers = mMappers.size(); for (size_t i = 0; i < numMappers; i++) { InputMapper* mapper = mMappers[i]; mapper->fadePointer(); } } void InputDevice::bumpGeneration() { mGeneration = mContext->bumpGeneration(); } void InputDevice::notifyReset(nsecs_t when) { NotifyDeviceResetArgs args(when, mId); mContext->getListener()->notifyDeviceReset(&args); } // --- CursorButtonAccumulator --- CursorButtonAccumulator::CursorButtonAccumulator() { clearButtons(); mChangePrimaryKey=false; } void CursorButtonAccumulator::configure(const InputReaderConfiguration * config) { if(config->changePrimaryKey) mChangePrimaryKey=true; else mChangePrimaryKey=false; } void CursorButtonAccumulator::reset(InputDevice* device) { if(!mChangePrimaryKey) { mBtnLeft = device->isKeyPressed(BTN_LEFT); mBtnRight = device->isKeyPressed(BTN_RIGHT); } else { mBtnRight = device->isKeyPressed(BTN_LEFT); mBtnLeft = device->isKeyPressed(BTN_RIGHT); } mBtnMiddle = device->isKeyPressed(BTN_MIDDLE); mBtnBack = device->isKeyPressed(BTN_BACK); mBtnSide = device->isKeyPressed(BTN_SIDE); mBtnForward = device->isKeyPressed(BTN_FORWARD); mBtnExtra = device->isKeyPressed(BTN_EXTRA); mBtnTask = device->isKeyPressed(BTN_TASK); } void CursorButtonAccumulator::clearButtons() { mBtnLeft = 0; mBtnRight = 0; mBtnMiddle = 0; mBtnBack = 0; mBtnSide = 0; mBtnForward = 0; mBtnExtra = 0; mBtnTask = 0; } void CursorButtonAccumulator::process(const RawEvent* rawEvent) { if (rawEvent->type == EV_KEY) { switch (rawEvent->code) { case BTN_LEFT: ALOGD_READER("Button Left!"); if(!mChangePrimaryKey) mBtnLeft = rawEvent->value; else mBtnRight = rawEvent->value; break; case BTN_RIGHT: ALOGD_READER("Button Right!"); if(!mChangePrimaryKey) mBtnRight = rawEvent->value; else mBtnLeft = rawEvent->value; break; case BTN_MIDDLE: mBtnMiddle = rawEvent->value; break; case BTN_BACK: mBtnBack = rawEvent->value; break; case BTN_SIDE: mBtnSide = rawEvent->value; break; case BTN_FORWARD: mBtnForward = rawEvent->value; break; case BTN_EXTRA: mBtnExtra = rawEvent->value; break; case BTN_TASK: mBtnTask = rawEvent->value; break; } } } uint32_t CursorButtonAccumulator::getButtonState() const { uint32_t result = 0; if (mBtnLeft) { result |= AMOTION_EVENT_BUTTON_PRIMARY; } if (mBtnRight) { result |= AMOTION_EVENT_BUTTON_SECONDARY; } if (mBtnMiddle) { result |= AMOTION_EVENT_BUTTON_TERTIARY; } if (mBtnBack || mBtnSide) { result |= AMOTION_EVENT_BUTTON_BACK; } if (mBtnForward || mBtnExtra) { result |= AMOTION_EVENT_BUTTON_FORWARD; } return result; } // --- CursorMotionAccumulator --- CursorMotionAccumulator::CursorMotionAccumulator() { clearRelativeAxes(); } void CursorMotionAccumulator::reset(InputDevice* device) { clearRelativeAxes(); } void CursorMotionAccumulator::clearRelativeAxes() { mRelX = 0; mRelY = 0; } void CursorMotionAccumulator::process(const RawEvent* rawEvent) { if (rawEvent->type == EV_REL) { switch (rawEvent->code) { case REL_X: mRelX = rawEvent->value; break; case REL_Y: mRelY = rawEvent->value; break; } } } void CursorMotionAccumulator::finishSync() { clearRelativeAxes(); } // --- CursorScrollAccumulator --- CursorScrollAccumulator::CursorScrollAccumulator() : mHaveRelWheel(false), mHaveRelHWheel(false) { clearRelativeAxes(); } void CursorScrollAccumulator::configure(InputDevice* device) { mHaveRelWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_WHEEL); mHaveRelHWheel = device->getEventHub()->hasRelativeAxis(device->getId(), REL_HWHEEL); } void CursorScrollAccumulator::reset(InputDevice* device) { clearRelativeAxes(); } void CursorScrollAccumulator::clearRelativeAxes() { mRelWheel = 0; mRelHWheel = 0; } void CursorScrollAccumulator::process(const RawEvent* rawEvent) { if (rawEvent->type == EV_REL) { switch (rawEvent->code) { case REL_WHEEL: mRelWheel = rawEvent->value; break; case REL_HWHEEL: mRelHWheel = rawEvent->value; break; } } } void CursorScrollAccumulator::finishSync() { clearRelativeAxes(); } // --- TouchButtonAccumulator --- TouchButtonAccumulator::TouchButtonAccumulator() : mHaveBtnTouch(false), mHaveStylus(false) { clearButtons(); } void TouchButtonAccumulator::configure(InputDevice* device) { mHaveBtnTouch = device->hasKey(BTN_TOUCH); mHaveStylus = device->hasKey(BTN_TOOL_PEN) || device->hasKey(BTN_TOOL_RUBBER) || device->hasKey(BTN_TOOL_BRUSH) || device->hasKey(BTN_TOOL_PENCIL) || device->hasKey(BTN_TOOL_AIRBRUSH); } void TouchButtonAccumulator::reset(InputDevice* device) { mBtnTouch = device->isKeyPressed(BTN_TOUCH); mBtnStylus = device->isKeyPressed(BTN_STYLUS); // BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch mBtnStylus2 = device->isKeyPressed(BTN_STYLUS2) || device->isKeyPressed(BTN_0); mBtnToolFinger = device->isKeyPressed(BTN_TOOL_FINGER); mBtnToolPen = device->isKeyPressed(BTN_TOOL_PEN); mBtnToolRubber = device->isKeyPressed(BTN_TOOL_RUBBER); mBtnToolBrush = device->isKeyPressed(BTN_TOOL_BRUSH); mBtnToolPencil = device->isKeyPressed(BTN_TOOL_PENCIL); mBtnToolAirbrush = device->isKeyPressed(BTN_TOOL_AIRBRUSH); mBtnToolMouse = device->isKeyPressed(BTN_TOOL_MOUSE); mBtnToolLens = device->isKeyPressed(BTN_TOOL_LENS); mBtnToolDoubleTap = device->isKeyPressed(BTN_TOOL_DOUBLETAP); mBtnToolTripleTap = device->isKeyPressed(BTN_TOOL_TRIPLETAP); mBtnToolQuadTap = device->isKeyPressed(BTN_TOOL_QUADTAP); } void TouchButtonAccumulator::clearButtons() { mBtnTouch = 0; mBtnStylus = 0; mBtnStylus2 = 0; mBtnToolFinger = 0; mBtnToolPen = 0; mBtnToolRubber = 0; mBtnToolBrush = 0; mBtnToolPencil = 0; mBtnToolAirbrush = 0; mBtnToolMouse = 0; mBtnToolLens = 0; mBtnToolDoubleTap = 0; mBtnToolTripleTap = 0; mBtnToolQuadTap = 0; } void TouchButtonAccumulator::process(const RawEvent* rawEvent) { if (rawEvent->type == EV_KEY) { switch (rawEvent->code) { case BTN_TOUCH: mBtnTouch = rawEvent->value; break; case BTN_STYLUS: mBtnStylus = rawEvent->value; break; case BTN_STYLUS2: case BTN_0:// BTN_0 is what gets mapped for the HID usage Digitizers.SecondaryBarrelSwitch mBtnStylus2 = rawEvent->value; break; case BTN_TOOL_FINGER: mBtnToolFinger = rawEvent->value; break; case BTN_TOOL_PEN: mBtnToolPen = rawEvent->value; break; case BTN_TOOL_RUBBER: mBtnToolRubber = rawEvent->value; break; case BTN_TOOL_BRUSH: mBtnToolBrush = rawEvent->value; break; case BTN_TOOL_PENCIL: mBtnToolPencil = rawEvent->value; break; case BTN_TOOL_AIRBRUSH: mBtnToolAirbrush = rawEvent->value; break; case BTN_TOOL_MOUSE: mBtnToolMouse = rawEvent->value; break; case BTN_TOOL_LENS: mBtnToolLens = rawEvent->value; break; case BTN_TOOL_DOUBLETAP: mBtnToolDoubleTap = rawEvent->value; break; case BTN_TOOL_TRIPLETAP: mBtnToolTripleTap = rawEvent->value; break; case BTN_TOOL_QUADTAP: mBtnToolQuadTap = rawEvent->value; break; } } } uint32_t TouchButtonAccumulator::getButtonState() const { uint32_t result = 0; if (mBtnStylus) { result |= AMOTION_EVENT_BUTTON_STYLUS_PRIMARY; } if (mBtnStylus2) { result |= AMOTION_EVENT_BUTTON_STYLUS_SECONDARY; } return result; } int32_t TouchButtonAccumulator::getToolType() const { if (mBtnToolMouse || mBtnToolLens) { return AMOTION_EVENT_TOOL_TYPE_MOUSE; } if (mBtnToolRubber) { return AMOTION_EVENT_TOOL_TYPE_ERASER; } if (mBtnToolPen || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush) { return AMOTION_EVENT_TOOL_TYPE_STYLUS; } if (mBtnToolFinger || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap) { return AMOTION_EVENT_TOOL_TYPE_FINGER; } return AMOTION_EVENT_TOOL_TYPE_UNKNOWN; } bool TouchButtonAccumulator::isToolActive() const { return mBtnTouch || mBtnToolFinger || mBtnToolPen || mBtnToolRubber || mBtnToolBrush || mBtnToolPencil || mBtnToolAirbrush || mBtnToolMouse || mBtnToolLens || mBtnToolDoubleTap || mBtnToolTripleTap || mBtnToolQuadTap; } bool TouchButtonAccumulator::isHovering() const { return mHaveBtnTouch && !mBtnTouch; } bool TouchButtonAccumulator::hasStylus() const { return mHaveStylus; } // --- RawPointerAxes --- RawPointerAxes::RawPointerAxes() { clear(); } void RawPointerAxes::clear() { x.clear(); y.clear(); pressure.clear(); touchMajor.clear(); touchMinor.clear(); toolMajor.clear(); toolMinor.clear(); orientation.clear(); distance.clear(); tiltX.clear(); tiltY.clear(); trackingId.clear(); slot.clear(); } // --- RawPointerData --- RawPointerData::RawPointerData() { clear(); } void RawPointerData::clear() { pointerCount = 0; clearIdBits(); } void RawPointerData::copyFrom(const RawPointerData& other) { pointerCount = other.pointerCount; hoveringIdBits = other.hoveringIdBits; touchingIdBits = other.touchingIdBits; for (uint32_t i = 0; i < pointerCount; i++) { pointers[i] = other.pointers[i]; int id = pointers[i].id; idToIndex[id] = other.idToIndex[id]; } } void RawPointerData::getCentroidOfTouchingPointers(float* outX, float* outY) const { float x = 0, y = 0; uint32_t count = touchingIdBits.count(); if (count) { for (BitSet32 idBits(touchingIdBits); !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); const Pointer& pointer = pointerForId(id); x += pointer.x; y += pointer.y; } x /= count; y /= count; } *outX = x; *outY = y; } // --- CookedPointerData --- CookedPointerData::CookedPointerData() { clear(); } void CookedPointerData::clear() { pointerCount = 0; hoveringIdBits.clear(); touchingIdBits.clear(); } void CookedPointerData::copyFrom(const CookedPointerData& other) { pointerCount = other.pointerCount; hoveringIdBits = other.hoveringIdBits; touchingIdBits = other.touchingIdBits; for (uint32_t i = 0; i < pointerCount; i++) { pointerProperties[i].copyFrom(other.pointerProperties[i]); pointerCoords[i].copyFrom(other.pointerCoords[i]); int id = pointerProperties[i].id; idToIndex[id] = other.idToIndex[id]; } } // --- SingleTouchMotionAccumulator --- SingleTouchMotionAccumulator::SingleTouchMotionAccumulator() { clearAbsoluteAxes(); } void SingleTouchMotionAccumulator::reset(InputDevice* device) { mAbsX = device->getAbsoluteAxisValue(ABS_X); mAbsY = device->getAbsoluteAxisValue(ABS_Y); mAbsPressure = device->getAbsoluteAxisValue(ABS_PRESSURE); mAbsToolWidth = device->getAbsoluteAxisValue(ABS_TOOL_WIDTH); mAbsDistance = device->getAbsoluteAxisValue(ABS_DISTANCE); mAbsTiltX = device->getAbsoluteAxisValue(ABS_TILT_X); mAbsTiltY = device->getAbsoluteAxisValue(ABS_TILT_Y); } void SingleTouchMotionAccumulator::clearAbsoluteAxes() { mAbsX = 0; mAbsY = 0; mAbsPressure = 0; mAbsToolWidth = 0; mAbsDistance = 0; mAbsTiltX = 0; mAbsTiltY = 0; } void SingleTouchMotionAccumulator::process(const RawEvent* rawEvent) { if (rawEvent->type == EV_ABS) { switch (rawEvent->code) { case ABS_X: mAbsX = rawEvent->value; break; case ABS_Y: mAbsY = rawEvent->value; break; case ABS_PRESSURE: mAbsPressure = rawEvent->value; break; case ABS_TOOL_WIDTH: mAbsToolWidth = rawEvent->value; break; case ABS_DISTANCE: mAbsDistance = rawEvent->value; break; case ABS_TILT_X: mAbsTiltX = rawEvent->value; break; case ABS_TILT_Y: mAbsTiltY = rawEvent->value; break; } } } // --- MultiTouchMotionAccumulator --- MultiTouchMotionAccumulator::MultiTouchMotionAccumulator() : mCurrentSlot(-1), mSlots(NULL), mSlotCount(0), mUsingSlotsProtocol(false), mHaveStylus(false) { } MultiTouchMotionAccumulator::~MultiTouchMotionAccumulator() { delete[] mSlots; } void MultiTouchMotionAccumulator::configure(InputDevice* device, size_t slotCount, bool usingSlotsProtocol) { mSlotCount = slotCount; mUsingSlotsProtocol = usingSlotsProtocol; mHaveStylus = device->hasAbsoluteAxis(ABS_MT_TOOL_TYPE); delete[] mSlots; mSlots = new Slot[slotCount]; } void MultiTouchMotionAccumulator::reset(InputDevice* device) { // Unfortunately there is no way to read the initial contents of the slots. // So when we reset the accumulator, we must assume they are all zeroes. if (mUsingSlotsProtocol) { // Query the driver for the current slot index and use it as the initial slot // before we start reading events from the device. It is possible that the // current slot index will not be the same as it was when the first event was // written into the evdev buffer, which means the input mapper could start // out of sync with the initial state of the events in the evdev buffer. // In the extremely unlikely case that this happens, the data from // two slots will be confused until the next ABS_MT_SLOT event is received. // This can cause the touch point to "jump", but at least there will be // no stuck touches. int32_t initialSlot; status_t status = device->getEventHub()->getAbsoluteAxisValue(device->getId(), ABS_MT_SLOT, &initialSlot); if (status) { ALOGD("Could not retrieve current multitouch slot index. status=%d", status); initialSlot = -1; } clearSlots(initialSlot); } else { clearSlots(-1); } } void MultiTouchMotionAccumulator::clearSlots(int32_t initialSlot) { if (mSlots) { for (size_t i = 0; i < mSlotCount; i++) { mSlots[i].clear(); } } mCurrentSlot = initialSlot; } void MultiTouchMotionAccumulator::process(const RawEvent* rawEvent) { if (rawEvent->type == EV_ABS) { bool newSlot = false; if (mUsingSlotsProtocol) { if (rawEvent->code == ABS_MT_SLOT) { mCurrentSlot = rawEvent->value; newSlot = true; } } else if (mCurrentSlot < 0) { mCurrentSlot = 0; } if (mCurrentSlot < 0 || size_t(mCurrentSlot) >= mSlotCount) { #if DEBUG_POINTERS if (newSlot) { ALOGW("MultiTouch device emitted invalid slot index %d but it " "should be between 0 and %d; ignoring this slot.", mCurrentSlot, mSlotCount - 1); } #endif } else { Slot* slot = &mSlots[mCurrentSlot]; switch (rawEvent->code) { case ABS_MT_POSITION_X: slot->mInUse = true; slot->mAbsMTPositionX = rawEvent->value; break; case ABS_MT_POSITION_Y: slot->mInUse = true; slot->mAbsMTPositionY = rawEvent->value; break; case ABS_MT_TOUCH_MAJOR: slot->mInUse = true; slot->mAbsMTTouchMajor = rawEvent->value; break; case ABS_MT_TOUCH_MINOR: slot->mInUse = true; slot->mAbsMTTouchMinor = rawEvent->value; slot->mHaveAbsMTTouchMinor = true; break; case ABS_MT_WIDTH_MAJOR: slot->mInUse = true; slot->mAbsMTWidthMajor = rawEvent->value; break; case ABS_MT_WIDTH_MINOR: slot->mInUse = true; slot->mAbsMTWidthMinor = rawEvent->value; slot->mHaveAbsMTWidthMinor = true; break; case ABS_MT_ORIENTATION: slot->mInUse = true; slot->mAbsMTOrientation = rawEvent->value; break; case ABS_MT_TRACKING_ID: if (mUsingSlotsProtocol && rawEvent->value < 0) { // The slot is no longer in use but it retains its previous contents, // which may be reused for subsequent touches. slot->mInUse = false; } else { slot->mInUse = true; slot->mAbsMTTrackingId = rawEvent->value; } break; case ABS_MT_PRESSURE: slot->mInUse = true; slot->mAbsMTPressure = rawEvent->value; break; case ABS_MT_DISTANCE: slot->mInUse = true; slot->mAbsMTDistance = rawEvent->value; break; case ABS_MT_TOOL_TYPE: slot->mInUse = true; slot->mAbsMTToolType = rawEvent->value; slot->mHaveAbsMTToolType = true; break; } } } else if (rawEvent->type == EV_SYN && rawEvent->code == SYN_MT_REPORT) { // MultiTouch Sync: The driver has returned all data for *one* of the pointers. mCurrentSlot += 1; } } void MultiTouchMotionAccumulator::finishSync() { if (!mUsingSlotsProtocol) { clearSlots(-1); } } bool MultiTouchMotionAccumulator::hasStylus() const { return mHaveStylus; } // --- MultiTouchMotionAccumulator::Slot --- MultiTouchMotionAccumulator::Slot::Slot() { clear(); } void MultiTouchMotionAccumulator::Slot::clear() { mInUse = false; mHaveAbsMTTouchMinor = false; mHaveAbsMTWidthMinor = false; mHaveAbsMTToolType = false; mAbsMTPositionX = 0; mAbsMTPositionY = 0; mAbsMTTouchMajor = 0; mAbsMTTouchMinor = 0; mAbsMTWidthMajor = 0; mAbsMTWidthMinor = 0; mAbsMTOrientation = 0; mAbsMTTrackingId = -1; mAbsMTPressure = 0; mAbsMTDistance = 0; mAbsMTToolType = 0; } int32_t MultiTouchMotionAccumulator::Slot::getToolType() const { if (mHaveAbsMTToolType) { switch (mAbsMTToolType) { case MT_TOOL_FINGER: return AMOTION_EVENT_TOOL_TYPE_FINGER; case MT_TOOL_PEN: return AMOTION_EVENT_TOOL_TYPE_STYLUS; } } return AMOTION_EVENT_TOOL_TYPE_UNKNOWN; } // --- InputMapper --- InputMapper::InputMapper(InputDevice* device) : mDevice(device), mContext(device->getContext()) { } InputMapper::~InputMapper() { } void InputMapper::populateDeviceInfo(InputDeviceInfo* info) { info->addSource(getSources()); } void InputMapper::dump(String8& dump) { } void InputMapper::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) { } void InputMapper::reset(nsecs_t when) { } void InputMapper::timeoutExpired(nsecs_t when) { } int32_t InputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { return AKEY_STATE_UNKNOWN; } int32_t InputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { return AKEY_STATE_UNKNOWN; } int32_t InputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) { return AKEY_STATE_UNKNOWN; } bool InputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { return false; } void InputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat, int32_t token) { } void InputMapper::cancelVibrate(int32_t token) { } void InputMapper::cancelTouch(nsecs_t when) { } int32_t InputMapper::getMetaState() { return 0; } void InputMapper::updateMetaState(int32_t keyCode) { } void InputMapper::updateExternalStylusState(const StylusState& state) { } void InputMapper::fadePointer() { } status_t InputMapper::getAbsoluteAxisInfo(int32_t axis, RawAbsoluteAxisInfo* axisInfo) { return getEventHub()->getAbsoluteAxisInfo(getDeviceId(), axis, axisInfo); } void InputMapper::bumpGeneration() { mDevice->bumpGeneration(); } void InputMapper::dumpRawAbsoluteAxisInfo(String8& dump, const RawAbsoluteAxisInfo& axis, const char* name) { if (axis.valid) { dump.appendFormat(INDENT4 "%s: min=%d, max=%d, flat=%d, fuzz=%d, resolution=%d\n", name, axis.minValue, axis.maxValue, axis.flat, axis.fuzz, axis.resolution); } else { dump.appendFormat(INDENT4 "%s: unknown range\n", name); } } void InputMapper::dumpStylusState(String8& dump, const StylusState& state) { dump.appendFormat(INDENT4 "When: %" PRId64 "\n", state.when); dump.appendFormat(INDENT4 "Pressure: %f\n", state.pressure); dump.appendFormat(INDENT4 "Button State: 0x%08x\n", state.buttons); dump.appendFormat(INDENT4 "Tool Type: %" PRId32 "\n", state.toolType); } // --- SwitchInputMapper --- SwitchInputMapper::SwitchInputMapper(InputDevice* device) : InputMapper(device), mSwitchValues(0), mUpdatedSwitchMask(0) { } SwitchInputMapper::~SwitchInputMapper() { } uint32_t SwitchInputMapper::getSources() { return AINPUT_SOURCE_SWITCH; } void SwitchInputMapper::process(const RawEvent* rawEvent) { switch (rawEvent->type) { case EV_SW: processSwitch(rawEvent->code, rawEvent->value); break; case EV_SYN: if (rawEvent->code == SYN_REPORT) { sync(rawEvent->when); } } } void SwitchInputMapper::processSwitch(int32_t switchCode, int32_t switchValue) { if (switchCode >= 0 && switchCode < 32) { if (switchValue) { mSwitchValues |= 1 << switchCode; } else { mSwitchValues &= ~(1 << switchCode); } mUpdatedSwitchMask |= 1 << switchCode; } } void SwitchInputMapper::sync(nsecs_t when) { if (mUpdatedSwitchMask) { uint32_t updatedSwitchValues = mSwitchValues & mUpdatedSwitchMask; NotifySwitchArgs args(when, 0, updatedSwitchValues, mUpdatedSwitchMask); getListener()->notifySwitch(&args); mUpdatedSwitchMask = 0; } } int32_t SwitchInputMapper::getSwitchState(uint32_t sourceMask, int32_t switchCode) { return getEventHub()->getSwitchState(getDeviceId(), switchCode); } void SwitchInputMapper::dump(String8& dump) { dump.append(INDENT2 "Switch Input Mapper:\n"); dump.appendFormat(INDENT3 "SwitchValues: %x\n", mSwitchValues); } // --- VibratorInputMapper --- VibratorInputMapper::VibratorInputMapper(InputDevice* device) : InputMapper(device), mVibrating(false) { } VibratorInputMapper::~VibratorInputMapper() { } uint32_t VibratorInputMapper::getSources() { return 0; } void VibratorInputMapper::populateDeviceInfo(InputDeviceInfo* info) { InputMapper::populateDeviceInfo(info); info->setVibrator(true); } void VibratorInputMapper::process(const RawEvent* rawEvent) { // TODO: Handle FF_STATUS, although it does not seem to be widely supported. } void VibratorInputMapper::vibrate(const nsecs_t* pattern, size_t patternSize, ssize_t repeat, int32_t token) { #if DEBUG_VIBRATOR String8 patternStr; for (size_t i = 0; i < patternSize; i++) { if (i != 0) { patternStr.append(", "); } patternStr.appendFormat("%lld", pattern[i]); } ALOGD("vibrate: deviceId=%d, pattern=[%s], repeat=%ld, token=%d", getDeviceId(), patternStr.string(), repeat, token); #endif mVibrating = true; memcpy(mPattern, pattern, patternSize * sizeof(nsecs_t)); mPatternSize = patternSize; mRepeat = repeat; mToken = token; mIndex = -1; nextStep(); } void VibratorInputMapper::cancelVibrate(int32_t token) { #if DEBUG_VIBRATOR ALOGD("cancelVibrate: deviceId=%d, token=%d", getDeviceId(), token); #endif if (mVibrating && mToken == token) { stopVibrating(); } } void VibratorInputMapper::timeoutExpired(nsecs_t when) { if (mVibrating) { if (when >= mNextStepTime) { nextStep(); } else { getContext()->requestTimeoutAtTime(mNextStepTime); } } } void VibratorInputMapper::nextStep() { mIndex += 1; if (size_t(mIndex) >= mPatternSize) { if (mRepeat < 0) { // We are done. stopVibrating(); return; } mIndex = mRepeat; } bool vibratorOn = mIndex & 1; nsecs_t duration = mPattern[mIndex]; if (vibratorOn) { #if DEBUG_VIBRATOR ALOGD("nextStep: sending vibrate deviceId=%d, duration=%lld", getDeviceId(), duration); #endif getEventHub()->vibrate(getDeviceId(), duration); } else { #if DEBUG_VIBRATOR ALOGD("nextStep: sending cancel vibrate deviceId=%d", getDeviceId()); #endif getEventHub()->cancelVibrate(getDeviceId()); } nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); mNextStepTime = now + duration; getContext()->requestTimeoutAtTime(mNextStepTime); #if DEBUG_VIBRATOR ALOGD("nextStep: scheduled timeout in %0.3fms", duration * 0.000001f); #endif } void VibratorInputMapper::stopVibrating() { mVibrating = false; #if DEBUG_VIBRATOR ALOGD("stopVibrating: sending cancel vibrate deviceId=%d", getDeviceId()); #endif getEventHub()->cancelVibrate(getDeviceId()); } void VibratorInputMapper::dump(String8& dump) { dump.append(INDENT2 "Vibrator Input Mapper:\n"); dump.appendFormat(INDENT3 "Vibrating: %s\n", toString(mVibrating)); } // --- KeyboardInputMapper --- KeyboardInputMapper::KeyboardInputMapper(InputDevice* device, uint32_t source, int32_t keyboardType) : InputMapper(device), mSource(source), mKeyboardType(keyboardType) { } KeyboardInputMapper::~KeyboardInputMapper() { } uint32_t KeyboardInputMapper::getSources() { return mSource; } void KeyboardInputMapper::populateDeviceInfo(InputDeviceInfo* info) { InputMapper::populateDeviceInfo(info); info->setKeyboardType(mKeyboardType); info->setKeyCharacterMap(getEventHub()->getKeyCharacterMap(getDeviceId())); } void KeyboardInputMapper::dump(String8& dump) { dump.append(INDENT2 "Keyboard Input Mapper:\n"); dumpParameters(dump); dump.appendFormat(INDENT3 "KeyboardType: %d\n", mKeyboardType); dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation); dump.appendFormat(INDENT3 "KeyDowns: %zu keys currently down\n", mKeyDowns.size()); dump.appendFormat(INDENT3 "MetaState: 0x%0x\n", mMetaState); dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime); } void KeyboardInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) { InputMapper::configure(when, config, changes); if (!changes) { // first time only // Configure basic parameters. configureParameters(); } if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) { DisplayViewport v; if (config->getDisplayInfo(false /*external*/, &v)) { mOrientation = v.orientation; } else { mOrientation = DISPLAY_ORIENTATION_0; } } else { mOrientation = DISPLAY_ORIENTATION_0; } } } void KeyboardInputMapper::configureParameters() { mParameters.orientationAware = false; getDevice()->getConfiguration().tryGetProperty(String8("keyboard.orientationAware"), mParameters.orientationAware); mParameters.hasAssociatedDisplay = false; if (mParameters.orientationAware) { mParameters.hasAssociatedDisplay = true; } mParameters.handlesKeyRepeat = false; getDevice()->getConfiguration().tryGetProperty(String8("keyboard.handlesKeyRepeat"), mParameters.handlesKeyRepeat); } void KeyboardInputMapper::dumpParameters(String8& dump) { dump.append(INDENT3 "Parameters:\n"); dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n", toString(mParameters.hasAssociatedDisplay)); dump.appendFormat(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware)); dump.appendFormat(INDENT4 "HandlesKeyRepeat: %s\n", toString(mParameters.handlesKeyRepeat)); } void KeyboardInputMapper::reset(nsecs_t when) { mMetaState = AMETA_NONE; mDownTime = 0; mKeyDowns.clear(); mCurrentHidUsage = 0; resetLedState(); InputMapper::reset(when); } void KeyboardInputMapper::process(const RawEvent* rawEvent) { switch (rawEvent->type) { case EV_KEY: { int32_t scanCode = rawEvent->code; int32_t usageCode = mCurrentHidUsage; mCurrentHidUsage = 0; if (isKeyboardOrGamepadKey(scanCode)) { processKey(rawEvent->when, rawEvent->value != 0, scanCode, usageCode); } break; } case EV_MSC: { if (rawEvent->code == MSC_SCAN) { mCurrentHidUsage = rawEvent->value; } break; } case EV_SYN: { if (rawEvent->code == SYN_REPORT) { mCurrentHidUsage = 0; } } } } bool KeyboardInputMapper::isKeyboardOrGamepadKey(int32_t scanCode) { return scanCode < BTN_MOUSE || scanCode >= KEY_OK || (scanCode >= BTN_MISC && scanCode < BTN_MOUSE) || (scanCode >= BTN_JOYSTICK && scanCode < BTN_DIGI); } void KeyboardInputMapper::processKey(nsecs_t when, bool down, int32_t scanCode, int32_t usageCode) { int32_t keyCode; int32_t keyMetaState; uint32_t policyFlags; if (getEventHub()->mapKey(getDeviceId(), scanCode, usageCode, mMetaState, &keyCode, &keyMetaState, &policyFlags)) { keyCode = AKEYCODE_UNKNOWN; keyMetaState = mMetaState; policyFlags = 0; } if (down) { // Rotate key codes according to orientation if needed. if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) { keyCode = rotateKeyCode(keyCode, mOrientation); } // Add key down. ssize_t keyDownIndex = findKeyDown(scanCode); if (keyDownIndex >= 0) { // key repeat, be sure to use same keycode as before in case of rotation keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode; } else { // key down if ((policyFlags & POLICY_FLAG_VIRTUAL) && mContext->shouldDropVirtualKey(when, getDevice(), keyCode, scanCode)) { return; } if (policyFlags & POLICY_FLAG_GESTURE) { mDevice->cancelTouch(when); } mKeyDowns.push(); KeyDown& keyDown = mKeyDowns.editTop(); keyDown.keyCode = keyCode; keyDown.scanCode = scanCode; } mDownTime = when; } else { // Remove key down. ssize_t keyDownIndex = findKeyDown(scanCode); if (keyDownIndex >= 0) { // key up, be sure to use same keycode as before in case of rotation keyCode = mKeyDowns.itemAt(keyDownIndex).keyCode; mKeyDowns.removeAt(size_t(keyDownIndex)); } else { // key was not actually down ALOGI("Dropping key up from device %s because the key was not down. " "keyCode=%d, scanCode=%d", getDeviceName().string(), keyCode, scanCode); return; } } if (updateMetaStateIfNeeded(keyCode, down)) { // If global meta state changed send it along with the key. // If it has not changed then we'll use what keymap gave us, // since key replacement logic might temporarily reset a few // meta bits for given key. keyMetaState = mMetaState; } nsecs_t downTime = mDownTime; // Key down on external an keyboard should wake the device. // We don't do this for internal keyboards to prevent them from waking up in your pocket. // For internal keyboards, the key layout file should specify the policy flags for // each wake key individually. // TODO: Use the input device configuration to control this behavior more finely. if (down && getDevice()->isExternal()) { policyFlags |= POLICY_FLAG_WAKE; } if (mParameters.handlesKeyRepeat) { policyFlags |= POLICY_FLAG_DISABLE_KEY_REPEAT; } if (down && !isMetaKey(keyCode)) { getContext()->fadePointer(); } NotifyKeyArgs args(when, getDeviceId(), mSource, policyFlags, down ? AKEY_EVENT_ACTION_DOWN : AKEY_EVENT_ACTION_UP, AKEY_EVENT_FLAG_FROM_SYSTEM, keyCode, scanCode, keyMetaState, downTime); getListener()->notifyKey(&args); ALOGD_READER("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, " "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld", args.eventTime, args.deviceId, args.source, args.policyFlags, args.action, args.flags, args.keyCode, args.scanCode, args.metaState, args.downTime); } ssize_t KeyboardInputMapper::findKeyDown(int32_t scanCode) { size_t n = mKeyDowns.size(); for (size_t i = 0; i < n; i++) { if (mKeyDowns[i].scanCode == scanCode) { return i; } } return -1; } int32_t KeyboardInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { return getEventHub()->getKeyCodeState(getDeviceId(), keyCode); } int32_t KeyboardInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { return getEventHub()->getScanCodeState(getDeviceId(), scanCode); } bool KeyboardInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { return getEventHub()->markSupportedKeyCodes(getDeviceId(), numCodes, keyCodes, outFlags); } int32_t KeyboardInputMapper::getMetaState() { return mMetaState; } void KeyboardInputMapper::updateMetaState(int32_t keyCode) { updateMetaStateIfNeeded(keyCode, false); } bool KeyboardInputMapper::updateMetaStateIfNeeded(int32_t keyCode, bool down) { int32_t oldMetaState = mMetaState; int32_t newMetaState = android::updateMetaState(keyCode, down, oldMetaState); bool metaStateChanged = oldMetaState != newMetaState; if (metaStateChanged) { mMetaState = newMetaState; updateLedState(false); getContext()->updateGlobalMetaState(); } return metaStateChanged; } void KeyboardInputMapper::resetLedState() { initializeLedState(mCapsLockLedState, ALED_CAPS_LOCK); initializeLedState(mNumLockLedState, ALED_NUM_LOCK); initializeLedState(mScrollLockLedState, ALED_SCROLL_LOCK); updateLedState(true); } void KeyboardInputMapper::initializeLedState(LedState& ledState, int32_t led) { ledState.avail = getEventHub()->hasLed(getDeviceId(), led); ledState.on = false; } void KeyboardInputMapper::updateLedState(bool reset) { updateLedStateForModifier(mCapsLockLedState, ALED_CAPS_LOCK, AMETA_CAPS_LOCK_ON, reset); updateLedStateForModifier(mNumLockLedState, ALED_NUM_LOCK, AMETA_NUM_LOCK_ON, reset); updateLedStateForModifier(mScrollLockLedState, ALED_SCROLL_LOCK, AMETA_SCROLL_LOCK_ON, reset); } void KeyboardInputMapper::updateLedStateForModifier(LedState& ledState, int32_t led, int32_t modifier, bool reset) { if (ledState.avail) { bool desiredState = (mMetaState & modifier) != 0; if (reset || ledState.on != desiredState) { getEventHub()->setLedState(getDeviceId(), led, desiredState); ledState.on = desiredState; } } } // --- CursorInputMapper --- CursorInputMapper::CursorInputMapper(InputDevice* device) : InputMapper(device) { } CursorInputMapper::~CursorInputMapper() { } uint32_t CursorInputMapper::getSources() { return mSource; } void CursorInputMapper::populateDeviceInfo(InputDeviceInfo* info) { InputMapper::populateDeviceInfo(info); if (mParameters.mode == Parameters::MODE_POINTER) { float minX, minY, maxX, maxY; if (mPointerController->getBounds(&minX, &minY, &maxX, &maxY)) { info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, minX, maxX, 0.0f, 0.0f, 0.0f); info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, minY, maxY, 0.0f, 0.0f, 0.0f); } } else { info->addMotionRange(AMOTION_EVENT_AXIS_X, mSource, -1.0f, 1.0f, 0.0f, mXScale, 0.0f); info->addMotionRange(AMOTION_EVENT_AXIS_Y, mSource, -1.0f, 1.0f, 0.0f, mYScale, 0.0f); } info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, mSource, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f); if (mCursorScrollAccumulator.haveRelativeVWheel()) { info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f); } if (mCursorScrollAccumulator.haveRelativeHWheel()) { info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f); } } void CursorInputMapper::dump(String8& dump) { dump.append(INDENT2 "Cursor Input Mapper:\n"); dumpParameters(dump); dump.appendFormat(INDENT3 "XScale: %0.3f\n", mXScale); dump.appendFormat(INDENT3 "YScale: %0.3f\n", mYScale); dump.appendFormat(INDENT3 "XPrecision: %0.3f\n", mXPrecision); dump.appendFormat(INDENT3 "YPrecision: %0.3f\n", mYPrecision); dump.appendFormat(INDENT3 "HaveVWheel: %s\n", toString(mCursorScrollAccumulator.haveRelativeVWheel())); dump.appendFormat(INDENT3 "HaveHWheel: %s\n", toString(mCursorScrollAccumulator.haveRelativeHWheel())); dump.appendFormat(INDENT3 "VWheelScale: %0.3f\n", mVWheelScale); dump.appendFormat(INDENT3 "HWheelScale: %0.3f\n", mHWheelScale); dump.appendFormat(INDENT3 "Orientation: %d\n", mOrientation); dump.appendFormat(INDENT3 "ButtonState: 0x%08x\n", mButtonState); dump.appendFormat(INDENT3 "Down: %s\n", toString(isPointerDown(mButtonState))); dump.appendFormat(INDENT3 "DownTime: %lld\n", (long long)mDownTime); } void CursorInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) { InputMapper::configure(when, config, changes); if (!changes) { // first time only mCursorScrollAccumulator.configure(getDevice()); // Configure basic parameters. configureParameters(); // Configure device mode. switch (mParameters.mode) { case Parameters::MODE_POINTER: mSource = AINPUT_SOURCE_MOUSE; mXPrecision = 1.0f; mYPrecision = 1.0f; mXScale = 1.0f; mYScale = 1.0f; mPointerController = getPolicy()->obtainPointerController(getDeviceId()); break; case Parameters::MODE_NAVIGATION: mSource = AINPUT_SOURCE_TRACKBALL; mXPrecision = TRACKBALL_MOVEMENT_THRESHOLD; mYPrecision = TRACKBALL_MOVEMENT_THRESHOLD; mXScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD; mYScale = 1.0f / TRACKBALL_MOVEMENT_THRESHOLD; break; } mVWheelScale = 1.0f; mHWheelScale = 1.0f; } if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) { mPointerVelocityControl.setParameters(config->pointerVelocityControlParameters); mWheelXVelocityControl.setParameters(config->wheelVelocityControlParameters); mWheelYVelocityControl.setParameters(config->wheelVelocityControlParameters); } if (!changes || (changes & InputReaderConfiguration::CHANGE_PRIMARY_KEY)) { mCursorButtonAccumulator.configure(config); } if (!changes || (changes & InputReaderConfiguration::CHANGE_DISPLAY_INFO)) { if (mParameters.orientationAware && mParameters.hasAssociatedDisplay) { DisplayViewport v; if (config->getDisplayInfo(false /*external*/, &v)) { mOrientation = v.orientation; } else { mOrientation = DISPLAY_ORIENTATION_0; } } else { mOrientation = DISPLAY_ORIENTATION_0; } bumpGeneration(); } } void CursorInputMapper::configureParameters() { mParameters.mode = Parameters::MODE_POINTER; String8 cursorModeString; if (getDevice()->getConfiguration().tryGetProperty(String8("cursor.mode"), cursorModeString)) { if (cursorModeString == "navigation") { mParameters.mode = Parameters::MODE_NAVIGATION; } else if (cursorModeString != "pointer" && cursorModeString != "default") { ALOGW("Invalid value for cursor.mode: '%s'", cursorModeString.string()); } } mParameters.orientationAware = false; getDevice()->getConfiguration().tryGetProperty(String8("cursor.orientationAware"), mParameters.orientationAware); mParameters.hasAssociatedDisplay = false; if (mParameters.mode == Parameters::MODE_POINTER || mParameters.orientationAware) { mParameters.hasAssociatedDisplay = true; } } void CursorInputMapper::dumpParameters(String8& dump) { dump.append(INDENT3 "Parameters:\n"); dump.appendFormat(INDENT4 "HasAssociatedDisplay: %s\n", toString(mParameters.hasAssociatedDisplay)); switch (mParameters.mode) { case Parameters::MODE_POINTER: dump.append(INDENT4 "Mode: pointer\n"); break; case Parameters::MODE_NAVIGATION: dump.append(INDENT4 "Mode: navigation\n"); break; default: ALOG_ASSERT(false); } dump.appendFormat(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware)); } void CursorInputMapper::reset(nsecs_t when) { mButtonState = 0; mDownTime = 0; mPointerVelocityControl.reset(); mWheelXVelocityControl.reset(); mWheelYVelocityControl.reset(); mCursorButtonAccumulator.reset(getDevice()); mCursorMotionAccumulator.reset(getDevice()); mCursorScrollAccumulator.reset(getDevice()); fadePointer(); InputMapper::reset(when); } void CursorInputMapper::process(const RawEvent* rawEvent) { mCursorButtonAccumulator.process(rawEvent); mCursorMotionAccumulator.process(rawEvent); mCursorScrollAccumulator.process(rawEvent); if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) { sync(rawEvent->when); } } void CursorInputMapper::sync(nsecs_t when) { int32_t lastButtonState = mButtonState; int32_t currentButtonState = mCursorButtonAccumulator.getButtonState(); mButtonState = currentButtonState; bool wasDown = isPointerDown(lastButtonState); bool down = isPointerDown(currentButtonState); bool downChanged; if (!wasDown && down) { mDownTime = when; downChanged = true; } else if (wasDown && !down) { downChanged = true; } else { downChanged = false; } nsecs_t downTime = mDownTime; bool buttonsChanged = currentButtonState != lastButtonState; int32_t buttonsPressed = currentButtonState & ~lastButtonState; int32_t buttonsReleased = lastButtonState & ~currentButtonState; float deltaX = mCursorMotionAccumulator.getRelativeX() * mXScale; float deltaY = mCursorMotionAccumulator.getRelativeY() * mYScale; bool moved = deltaX != 0 || deltaY != 0; // Rotate delta according to orientation if needed. if (mParameters.orientationAware && mParameters.hasAssociatedDisplay && (deltaX != 0.0f || deltaY != 0.0f)) { rotateDelta(mOrientation, &deltaX, &deltaY); } // Move the pointer. PointerProperties pointerProperties; pointerProperties.clear(); pointerProperties.id = 0; pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_MOUSE; PointerCoords pointerCoords; pointerCoords.clear(); float vscroll = mCursorScrollAccumulator.getRelativeVWheel(); float hscroll = mCursorScrollAccumulator.getRelativeHWheel(); bool scrolled = vscroll != 0 || hscroll != 0; mWheelYVelocityControl.move(when, NULL, &vscroll); mWheelXVelocityControl.move(when, &hscroll, NULL); mPointerVelocityControl.move(when, &deltaX, &deltaY); int32_t displayId; if (mPointerController != NULL) { if (moved || scrolled || buttonsChanged) { mPointerController->setPresentation( PointerControllerInterface::PRESENTATION_POINTER); if (moved) { mPointerController->move(deltaX, deltaY); } if (buttonsChanged) { mPointerController->setButtonState(currentButtonState); } mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE); } float x, y; mPointerController->getPosition(&x, &y); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY); displayId = ADISPLAY_ID_DEFAULT; } else { pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, deltaX); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, deltaY); displayId = ADISPLAY_ID_NONE; } pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f); // Moving an external trackball or mouse should wake the device. // We don't do this for internal cursor devices to prevent them from waking up // the device in your pocket. // TODO: Use the input device configuration to control this behavior more finely. uint32_t policyFlags = 0; if ((buttonsPressed || moved || scrolled) && getDevice()->isExternal()) { policyFlags |= POLICY_FLAG_WAKE; } // Synthesize key down from buttons if needed. synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource, policyFlags, lastButtonState, currentButtonState); // Send motion event. if (downChanged || moved || scrolled || buttonsChanged) { int32_t metaState = mContext->getGlobalMetaState(); int32_t buttonState = lastButtonState; int32_t motionEventAction; if (downChanged) { motionEventAction = down ? AMOTION_EVENT_ACTION_DOWN : AMOTION_EVENT_ACTION_UP; } else if (down || mPointerController == NULL) { motionEventAction = AMOTION_EVENT_ACTION_MOVE; } else { motionEventAction = AMOTION_EVENT_ACTION_HOVER_MOVE; } if (buttonsReleased) { BitSet32 released(buttonsReleased); while (!released.isEmpty()) { int32_t actionButton = BitSet32::valueForBit(released.clearFirstMarkedBit()); buttonState &= ~actionButton; NotifyMotionArgs releaseArgs(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, displayId, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); getListener()->notifyMotion(&releaseArgs); } } NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, motionEventAction, 0, 0, metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE, displayId, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); getListener()->notifyMotion(&args); if (buttonsPressed) { BitSet32 pressed(buttonsPressed); while (!pressed.isEmpty()) { int32_t actionButton = BitSet32::valueForBit(pressed.clearFirstMarkedBit()); buttonState |= actionButton; NotifyMotionArgs pressArgs(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, displayId, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); getListener()->notifyMotion(&pressArgs); } } ALOG_ASSERT(buttonState == currentButtonState); // Send hover move after UP to tell the application that the mouse is hovering now. if (motionEventAction == AMOTION_EVENT_ACTION_UP && mPointerController != NULL) { NotifyMotionArgs hoverArgs(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE, displayId, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); getListener()->notifyMotion(&hoverArgs); } // Send scroll events. if (scrolled) { pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll); NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, currentButtonState, AMOTION_EVENT_EDGE_FLAG_NONE, displayId, 1, &pointerProperties, &pointerCoords, mXPrecision, mYPrecision, downTime); getListener()->notifyMotion(&scrollArgs); } } // Synthesize key up from buttons if needed. synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource, policyFlags, lastButtonState, currentButtonState); mCursorMotionAccumulator.finishSync(); mCursorScrollAccumulator.finishSync(); } int32_t CursorInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { if (scanCode >= BTN_MOUSE && scanCode < BTN_JOYSTICK) { return getEventHub()->getScanCodeState(getDeviceId(), scanCode); } else { return AKEY_STATE_UNKNOWN; } } void CursorInputMapper::fadePointer() { if (mPointerController != NULL) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); } } // --- RotaryEncoderInputMapper --- RotaryEncoderInputMapper::RotaryEncoderInputMapper(InputDevice* device) : InputMapper(device) { mSource = AINPUT_SOURCE_ROTARY_ENCODER; } RotaryEncoderInputMapper::~RotaryEncoderInputMapper() { } uint32_t RotaryEncoderInputMapper::getSources() { return mSource; } void RotaryEncoderInputMapper::populateDeviceInfo(InputDeviceInfo* info) { InputMapper::populateDeviceInfo(info); if (mRotaryEncoderScrollAccumulator.haveRelativeVWheel()) { float res = 0.0f; if (!mDevice->getConfiguration().tryGetProperty(String8("device.res"), res)) { ALOGW("Rotary Encoder device configuration file didn't specify resolution!\n"); } if (!mDevice->getConfiguration().tryGetProperty(String8("device.scalingFactor"), mScalingFactor)) { ALOGW("Rotary Encoder device configuration file didn't specify scaling factor," "default to 1.0!\n"); mScalingFactor = 1.0f; } info->addMotionRange(AMOTION_EVENT_AXIS_SCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, res * mScalingFactor); } } void RotaryEncoderInputMapper::dump(String8& dump) { dump.append(INDENT2 "Rotary Encoder Input Mapper:\n"); dump.appendFormat(INDENT3 "HaveWheel: %s\n", toString(mRotaryEncoderScrollAccumulator.haveRelativeVWheel())); } void RotaryEncoderInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) { InputMapper::configure(when, config, changes); if (!changes) { mRotaryEncoderScrollAccumulator.configure(getDevice()); } } void RotaryEncoderInputMapper::reset(nsecs_t when) { mRotaryEncoderScrollAccumulator.reset(getDevice()); InputMapper::reset(when); } void RotaryEncoderInputMapper::process(const RawEvent* rawEvent) { mRotaryEncoderScrollAccumulator.process(rawEvent); if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) { sync(rawEvent->when); } } void RotaryEncoderInputMapper::sync(nsecs_t when) { PointerCoords pointerCoords; pointerCoords.clear(); PointerProperties pointerProperties; pointerProperties.clear(); pointerProperties.id = 0; pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN; float scroll = mRotaryEncoderScrollAccumulator.getRelativeVWheel(); bool scrolled = scroll != 0; // This is not a pointer, so it's not associated with a display. int32_t displayId = ADISPLAY_ID_NONE; // Moving the rotary encoder should wake the device (if specified). uint32_t policyFlags = 0; if (scrolled && getDevice()->isExternal()) { policyFlags |= POLICY_FLAG_WAKE; } // Send motion event. if (scrolled) { int32_t metaState = mContext->getGlobalMetaState(); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_SCROLL, scroll * mScalingFactor); NotifyMotionArgs scrollArgs(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, 0, AMOTION_EVENT_EDGE_FLAG_NONE, displayId, 1, &pointerProperties, &pointerCoords, 0, 0, 0); getListener()->notifyMotion(&scrollArgs); } mRotaryEncoderScrollAccumulator.finishSync(); } // --- TouchInputMapper --- TouchInputMapper::TouchInputMapper(InputDevice* device) : InputMapper(device), mSource(0), mDeviceMode(DEVICE_MODE_DISABLED), mSurfaceWidth(-1), mSurfaceHeight(-1), mSurfaceLeft(0), mSurfaceTop(0), mSurfaceOrientation(DISPLAY_ORIENTATION_0) { } TouchInputMapper::~TouchInputMapper() { } uint32_t TouchInputMapper::getSources() { return mSource; } void TouchInputMapper::populateDeviceInfo(InputDeviceInfo* info) { InputMapper::populateDeviceInfo(info); if (mDeviceMode != DEVICE_MODE_DISABLED) { info->addMotionRange(mOrientedRanges.x); info->addMotionRange(mOrientedRanges.y); info->addMotionRange(mOrientedRanges.pressure); if (mOrientedRanges.haveSize) { info->addMotionRange(mOrientedRanges.size); } if (mOrientedRanges.haveTouchSize) { info->addMotionRange(mOrientedRanges.touchMajor); info->addMotionRange(mOrientedRanges.touchMinor); } if (mOrientedRanges.haveToolSize) { info->addMotionRange(mOrientedRanges.toolMajor); info->addMotionRange(mOrientedRanges.toolMinor); } if (mOrientedRanges.haveOrientation) { info->addMotionRange(mOrientedRanges.orientation); } if (mOrientedRanges.haveDistance) { info->addMotionRange(mOrientedRanges.distance); } if (mOrientedRanges.haveTilt) { info->addMotionRange(mOrientedRanges.tilt); } if (mCursorScrollAccumulator.haveRelativeVWheel()) { info->addMotionRange(AMOTION_EVENT_AXIS_VSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f); } if (mCursorScrollAccumulator.haveRelativeHWheel()) { info->addMotionRange(AMOTION_EVENT_AXIS_HSCROLL, mSource, -1.0f, 1.0f, 0.0f, 0.0f, 0.0f); } if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) { const InputDeviceInfo::MotionRange& x = mOrientedRanges.x; const InputDeviceInfo::MotionRange& y = mOrientedRanges.y; info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_1, mSource, x.min, x.max, x.flat, x.fuzz, x.resolution); info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_2, mSource, y.min, y.max, y.flat, y.fuzz, y.resolution); info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_3, mSource, x.min, x.max, x.flat, x.fuzz, x.resolution); info->addMotionRange(AMOTION_EVENT_AXIS_GENERIC_4, mSource, y.min, y.max, y.flat, y.fuzz, y.resolution); } info->setButtonUnderPad(mParameters.hasButtonUnderPad); } } void TouchInputMapper::dump(String8& dump) { dump.append(INDENT2 "Touch Input Mapper:\n"); dumpParameters(dump); dumpVirtualKeys(dump); dumpRawPointerAxes(dump); dumpCalibration(dump); dumpAffineTransformation(dump); dumpSurface(dump); dump.appendFormat(INDENT3 "Translation and Scaling Factors:\n"); dump.appendFormat(INDENT4 "XTranslate: %0.3f\n", mXTranslate); dump.appendFormat(INDENT4 "YTranslate: %0.3f\n", mYTranslate); dump.appendFormat(INDENT4 "XScale: %0.3f\n", mXScale); dump.appendFormat(INDENT4 "YScale: %0.3f\n", mYScale); dump.appendFormat(INDENT4 "XPrecision: %0.3f\n", mXPrecision); dump.appendFormat(INDENT4 "YPrecision: %0.3f\n", mYPrecision); dump.appendFormat(INDENT4 "GeometricScale: %0.3f\n", mGeometricScale); dump.appendFormat(INDENT4 "PressureScale: %0.3f\n", mPressureScale); dump.appendFormat(INDENT4 "SizeScale: %0.3f\n", mSizeScale); dump.appendFormat(INDENT4 "OrientationScale: %0.3f\n", mOrientationScale); dump.appendFormat(INDENT4 "DistanceScale: %0.3f\n", mDistanceScale); dump.appendFormat(INDENT4 "HaveTilt: %s\n", toString(mHaveTilt)); dump.appendFormat(INDENT4 "TiltXCenter: %0.3f\n", mTiltXCenter); dump.appendFormat(INDENT4 "TiltXScale: %0.3f\n", mTiltXScale); dump.appendFormat(INDENT4 "TiltYCenter: %0.3f\n", mTiltYCenter); dump.appendFormat(INDENT4 "TiltYScale: %0.3f\n", mTiltYScale); dump.appendFormat(INDENT3 "Last Raw Button State: 0x%08x\n", mLastRawState.buttonState); dump.appendFormat(INDENT3 "Last Raw Touch: pointerCount=%d\n", mLastRawState.rawPointerData.pointerCount); for (uint32_t i = 0; i < mLastRawState.rawPointerData.pointerCount; i++) { const RawPointerData::Pointer& pointer = mLastRawState.rawPointerData.pointers[i]; dump.appendFormat(INDENT4 "[%d]: id=%d, x=%d, y=%d, pressure=%d, " "touchMajor=%d, touchMinor=%d, toolMajor=%d, toolMinor=%d, " "orientation=%d, tiltX=%d, tiltY=%d, distance=%d, " "toolType=%d, isHovering=%s\n", i, pointer.id, pointer.x, pointer.y, pointer.pressure, pointer.touchMajor, pointer.touchMinor, pointer.toolMajor, pointer.toolMinor, pointer.orientation, pointer.tiltX, pointer.tiltY, pointer.distance, pointer.toolType, toString(pointer.isHovering)); } dump.appendFormat(INDENT3 "Last Cooked Button State: 0x%08x\n", mLastCookedState.buttonState); dump.appendFormat(INDENT3 "Last Cooked Touch: pointerCount=%d\n", mLastCookedState.cookedPointerData.pointerCount); for (uint32_t i = 0; i < mLastCookedState.cookedPointerData.pointerCount; i++) { const PointerProperties& pointerProperties = mLastCookedState.cookedPointerData.pointerProperties[i]; const PointerCoords& pointerCoords = mLastCookedState.cookedPointerData.pointerCoords[i]; dump.appendFormat(INDENT4 "[%d]: id=%d, x=%0.3f, y=%0.3f, pressure=%0.3f, " "touchMajor=%0.3f, touchMinor=%0.3f, toolMajor=%0.3f, toolMinor=%0.3f, " "orientation=%0.3f, tilt=%0.3f, distance=%0.3f, " "toolType=%d, isHovering=%s\n", i, pointerProperties.id, pointerCoords.getX(), pointerCoords.getY(), pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE), pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR), pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR), pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR), pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR), pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION), pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_TILT), pointerCoords.getAxisValue(AMOTION_EVENT_AXIS_DISTANCE), pointerProperties.toolType, toString(mLastCookedState.cookedPointerData.isHovering(i))); } dump.append(INDENT3 "Stylus Fusion:\n"); dump.appendFormat(INDENT4 "ExternalStylusConnected: %s\n", toString(mExternalStylusConnected)); dump.appendFormat(INDENT4 "External Stylus ID: %" PRId64 "\n", mExternalStylusId); dump.appendFormat(INDENT4 "External Stylus Data Timeout: %" PRId64 "\n", mExternalStylusFusionTimeout); dump.append(INDENT3 "External Stylus State:\n"); dumpStylusState(dump, mExternalStylusState); if (mDeviceMode == DEVICE_MODE_POINTER) { dump.appendFormat(INDENT3 "Pointer Gesture Detector:\n"); dump.appendFormat(INDENT4 "XMovementScale: %0.3f\n", mPointerXMovementScale); dump.appendFormat(INDENT4 "YMovementScale: %0.3f\n", mPointerYMovementScale); dump.appendFormat(INDENT4 "XZoomScale: %0.3f\n", mPointerXZoomScale); dump.appendFormat(INDENT4 "YZoomScale: %0.3f\n", mPointerYZoomScale); dump.appendFormat(INDENT4 "MaxSwipeWidth: %f\n", mPointerGestureMaxSwipeWidth); } } void TouchInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) { InputMapper::configure(when, config, changes); mConfig = *config; if (!changes) { // first time only // Configure basic parameters. configureParameters(); // Configure common accumulators. mCursorScrollAccumulator.configure(getDevice()); mTouchButtonAccumulator.configure(getDevice()); // Configure absolute axis information. configureRawPointerAxes(); // Prepare input device calibration. parseCalibration(); resolveCalibration(); } if (!changes || (changes & InputReaderConfiguration::CHANGE_TOUCH_AFFINE_TRANSFORMATION)) { // Update location calibration to reflect current settings updateAffineTransformation(); } if (!changes || (changes & InputReaderConfiguration::CHANGE_POINTER_SPEED)) { // Update pointer speed. mPointerVelocityControl.setParameters(mConfig.pointerVelocityControlParameters); mWheelXVelocityControl.setParameters(mConfig.wheelVelocityControlParameters); mWheelYVelocityControl.setParameters(mConfig.wheelVelocityControlParameters); } if (!changes || (changes & InputReaderConfiguration::CHANGE_PRIMARY_KEY)) { mCursorButtonAccumulator.configure(config); } bool resetNeeded = false; if (!changes || (changes & (InputReaderConfiguration::CHANGE_DISPLAY_INFO | InputReaderConfiguration::CHANGE_POINTER_GESTURE_ENABLEMENT | InputReaderConfiguration::CHANGE_SHOW_TOUCHES | InputReaderConfiguration::CHANGE_EXTERNAL_STYLUS_PRESENCE))) { // Configure device sources, surface dimensions, orientation and // scaling factors. configureSurface(when, &resetNeeded); } if (changes && resetNeeded) { // Send reset, unless this is the first time the device has been configured, // in which case the reader will call reset itself after all mappers are ready. getDevice()->notifyReset(when); } } void TouchInputMapper::resolveExternalStylusPresence() { Vector<InputDeviceInfo> devices; mContext->getExternalStylusDevices(devices); mExternalStylusConnected = !devices.isEmpty(); if (!mExternalStylusConnected) { resetExternalStylus(); } } void TouchInputMapper::configureParameters() { // Use the pointer presentation mode for devices that do not support distinct // multitouch. The spot-based presentation relies on being able to accurately // locate two or more fingers on the touch pad. mParameters.gestureMode = getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_SEMI_MT) ? Parameters::GESTURE_MODE_SINGLE_TOUCH : Parameters::GESTURE_MODE_MULTI_TOUCH; String8 gestureModeString; if (getDevice()->getConfiguration().tryGetProperty(String8("touch.gestureMode"), gestureModeString)) { if (gestureModeString == "single-touch") { mParameters.gestureMode = Parameters::GESTURE_MODE_SINGLE_TOUCH; } else if (gestureModeString == "multi-touch") { mParameters.gestureMode = Parameters::GESTURE_MODE_MULTI_TOUCH; } else if (gestureModeString != "default") { ALOGW("Invalid value for touch.gestureMode: '%s'", gestureModeString.string()); } } if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_DIRECT)) { // The device is a touch screen. mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN; } else if (getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_POINTER)) { // The device is a pointing device like a track pad. mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER; } else if (getEventHub()->hasRelativeAxis(getDeviceId(), REL_X) || getEventHub()->hasRelativeAxis(getDeviceId(), REL_Y)) { // The device is a cursor device with a touch pad attached. // By default don't use the touch pad to move the pointer. mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD; } else { // The device is a touch pad of unknown purpose. mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER; } mParameters.hasButtonUnderPad= getEventHub()->hasInputProperty(getDeviceId(), INPUT_PROP_BUTTONPAD); String8 deviceTypeString; if (getDevice()->getConfiguration().tryGetProperty(String8("touch.deviceType"), deviceTypeString)) { if (deviceTypeString == "touchScreen") { mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_SCREEN; } else if (deviceTypeString == "touchPad") { mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_PAD; } else if (deviceTypeString == "touchNavigation") { mParameters.deviceType = Parameters::DEVICE_TYPE_TOUCH_NAVIGATION; } else if (deviceTypeString == "pointer") { mParameters.deviceType = Parameters::DEVICE_TYPE_POINTER; } else if (deviceTypeString != "default") { ALOGW("Invalid value for touch.deviceType: '%s'", deviceTypeString.string()); } } mParameters.orientationAware = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN; getDevice()->getConfiguration().tryGetProperty(String8("touch.orientationAware"), mParameters.orientationAware); mParameters.hasAssociatedDisplay = false; mParameters.associatedDisplayIsExternal = false; if (mParameters.orientationAware || mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN || mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER) { mParameters.hasAssociatedDisplay = true; mParameters.associatedDisplayIsExternal = mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN && getDevice()->isExternal(); } // Initial downs on external touch devices should wake the device. // Normally we don't do this for internal touch screens to prevent them from waking // up in your pocket but you can enable it using the input device configuration. mParameters.wake = getDevice()->isExternal(); getDevice()->getConfiguration().tryGetProperty(String8("touch.wake"), mParameters.wake); } void TouchInputMapper::dumpParameters(String8& dump) { dump.append(INDENT3 "Parameters:\n"); switch (mParameters.gestureMode) { case Parameters::GESTURE_MODE_SINGLE_TOUCH: dump.append(INDENT4 "GestureMode: single-touch\n"); break; case Parameters::GESTURE_MODE_MULTI_TOUCH: dump.append(INDENT4 "GestureMode: multi-touch\n"); break; default: assert(false); } switch (mParameters.deviceType) { case Parameters::DEVICE_TYPE_TOUCH_SCREEN: dump.append(INDENT4 "DeviceType: touchScreen\n"); break; case Parameters::DEVICE_TYPE_TOUCH_PAD: dump.append(INDENT4 "DeviceType: touchPad\n"); break; case Parameters::DEVICE_TYPE_TOUCH_NAVIGATION: dump.append(INDENT4 "DeviceType: touchNavigation\n"); break; case Parameters::DEVICE_TYPE_POINTER: dump.append(INDENT4 "DeviceType: pointer\n"); break; default: ALOG_ASSERT(false); } dump.appendFormat(INDENT4 "AssociatedDisplay: hasAssociatedDisplay=%s, isExternal=%s\n", toString(mParameters.hasAssociatedDisplay), toString(mParameters.associatedDisplayIsExternal)); dump.appendFormat(INDENT4 "OrientationAware: %s\n", toString(mParameters.orientationAware)); } void TouchInputMapper::configureRawPointerAxes() { mRawPointerAxes.clear(); } void TouchInputMapper::dumpRawPointerAxes(String8& dump) { dump.append(INDENT3 "Raw Touch Axes:\n"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.x, "X"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.y, "Y"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.pressure, "Pressure"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMajor, "TouchMajor"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.touchMinor, "TouchMinor"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMajor, "ToolMajor"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.toolMinor, "ToolMinor"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.orientation, "Orientation"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.distance, "Distance"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltX, "TiltX"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.tiltY, "TiltY"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.trackingId, "TrackingId"); dumpRawAbsoluteAxisInfo(dump, mRawPointerAxes.slot, "Slot"); } bool TouchInputMapper::hasExternalStylus() const { return mExternalStylusConnected; } void TouchInputMapper::configureSurface(nsecs_t when, bool* outResetNeeded) { int32_t oldDeviceMode = mDeviceMode; resolveExternalStylusPresence(); // Determine device mode. if (mParameters.deviceType == Parameters::DEVICE_TYPE_POINTER && mConfig.pointerGesturesEnabled) { mSource = AINPUT_SOURCE_MOUSE; mDeviceMode = DEVICE_MODE_POINTER; if (hasStylus()) { mSource |= AINPUT_SOURCE_STYLUS; } } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_SCREEN && mParameters.hasAssociatedDisplay) { mSource = AINPUT_SOURCE_TOUCHSCREEN; mDeviceMode = DEVICE_MODE_DIRECT; if (hasStylus()) { mSource |= AINPUT_SOURCE_STYLUS; } if (hasExternalStylus()) { mSource |= AINPUT_SOURCE_BLUETOOTH_STYLUS; } } else if (mParameters.deviceType == Parameters::DEVICE_TYPE_TOUCH_NAVIGATION) { mSource = AINPUT_SOURCE_TOUCH_NAVIGATION; mDeviceMode = DEVICE_MODE_NAVIGATION; } else { mSource = AINPUT_SOURCE_TOUCHPAD; mDeviceMode = DEVICE_MODE_UNSCALED; } // Ensure we have valid X and Y axes. if (!mRawPointerAxes.x.valid || !mRawPointerAxes.y.valid) { ALOGW(INDENT "Touch device '%s' did not report support for X or Y axis! " "The device will be inoperable.", getDeviceName().string()); mDeviceMode = DEVICE_MODE_DISABLED; return; } // Raw width and height in the natural orientation. int32_t rawWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1; int32_t rawHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1; // Get associated display dimensions. DisplayViewport newViewport; if (mParameters.hasAssociatedDisplay) { if (!mConfig.getDisplayInfo(mParameters.associatedDisplayIsExternal, &newViewport)) { ALOGI(INDENT "Touch device '%s' could not query the properties of its associated " "display. The device will be inoperable until the display size " "becomes available.", getDeviceName().string()); mDeviceMode = DEVICE_MODE_DISABLED; return; } } else { newViewport.setNonDisplayViewport(rawWidth, rawHeight); } bool viewportChanged = mViewport != newViewport; if (viewportChanged) { mViewport = newViewport; if (mDeviceMode == DEVICE_MODE_DIRECT || mDeviceMode == DEVICE_MODE_POINTER) { // Convert rotated viewport to natural surface coordinates. int32_t naturalLogicalWidth, naturalLogicalHeight; int32_t naturalPhysicalWidth, naturalPhysicalHeight; int32_t naturalPhysicalLeft, naturalPhysicalTop; int32_t naturalDeviceWidth, naturalDeviceHeight; switch (mViewport.orientation) { case DISPLAY_ORIENTATION_90: naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop; naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft; naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop; naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft; naturalPhysicalLeft = mViewport.deviceHeight - mViewport.physicalBottom; naturalPhysicalTop = mViewport.physicalLeft; naturalDeviceWidth = mViewport.deviceHeight; naturalDeviceHeight = mViewport.deviceWidth; break; case DISPLAY_ORIENTATION_180: naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft; naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop; naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft; naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop; naturalPhysicalLeft = mViewport.deviceWidth - mViewport.physicalRight; naturalPhysicalTop = mViewport.deviceHeight - mViewport.physicalBottom; naturalDeviceWidth = mViewport.deviceWidth; naturalDeviceHeight = mViewport.deviceHeight; break; case DISPLAY_ORIENTATION_270: naturalLogicalWidth = mViewport.logicalBottom - mViewport.logicalTop; naturalLogicalHeight = mViewport.logicalRight - mViewport.logicalLeft; naturalPhysicalWidth = mViewport.physicalBottom - mViewport.physicalTop; naturalPhysicalHeight = mViewport.physicalRight - mViewport.physicalLeft; naturalPhysicalLeft = mViewport.physicalTop; naturalPhysicalTop = mViewport.deviceWidth - mViewport.physicalRight; naturalDeviceWidth = mViewport.deviceHeight; naturalDeviceHeight = mViewport.deviceWidth; break; case DISPLAY_ORIENTATION_0: default: naturalLogicalWidth = mViewport.logicalRight - mViewport.logicalLeft; naturalLogicalHeight = mViewport.logicalBottom - mViewport.logicalTop; naturalPhysicalWidth = mViewport.physicalRight - mViewport.physicalLeft; naturalPhysicalHeight = mViewport.physicalBottom - mViewport.physicalTop; naturalPhysicalLeft = mViewport.physicalLeft; naturalPhysicalTop = mViewport.physicalTop; naturalDeviceWidth = mViewport.deviceWidth; naturalDeviceHeight = mViewport.deviceHeight; break; } mSurfaceWidth = naturalLogicalWidth * naturalDeviceWidth / naturalPhysicalWidth; mSurfaceHeight = naturalLogicalHeight * naturalDeviceHeight / naturalPhysicalHeight; mSurfaceLeft = naturalPhysicalLeft * naturalLogicalWidth / naturalPhysicalWidth; mSurfaceTop = naturalPhysicalTop * naturalLogicalHeight / naturalPhysicalHeight; mSurfaceOrientation = mParameters.orientationAware ? mViewport.orientation : DISPLAY_ORIENTATION_0; } else { mSurfaceWidth = rawWidth; mSurfaceHeight = rawHeight; mSurfaceLeft = 0; mSurfaceTop = 0; mSurfaceOrientation = DISPLAY_ORIENTATION_0; } } // If moving between pointer modes, need to reset some state. bool deviceModeChanged = mDeviceMode != oldDeviceMode; if (deviceModeChanged) { mOrientedRanges.clear(); } // Create pointer controller if needed. if (mDeviceMode == DEVICE_MODE_POINTER || (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches)) { if (mPointerController == NULL) { mPointerController = getPolicy()->obtainPointerController(getDeviceId()); } } else { mPointerController.clear(); } if (viewportChanged || deviceModeChanged) { ALOGI("Device reconfigured: id=%d, name='%s', size %dx%d, orientation %d, mode %d, " "display id %d", getDeviceId(), getDeviceName().string(), mSurfaceWidth, mSurfaceHeight, mSurfaceOrientation, mDeviceMode, mViewport.displayId); // Configure X and Y factors. mXScale = float(mSurfaceWidth) / rawWidth; mYScale = float(mSurfaceHeight) / rawHeight; mXTranslate = -mSurfaceLeft; mYTranslate = -mSurfaceTop; mXPrecision = 1.0f / mXScale; mYPrecision = 1.0f / mYScale; mOrientedRanges.x.axis = AMOTION_EVENT_AXIS_X; mOrientedRanges.x.source = mSource; mOrientedRanges.y.axis = AMOTION_EVENT_AXIS_Y; mOrientedRanges.y.source = mSource; configureVirtualKeys(); // Scale factor for terms that are not oriented in a particular axis. // If the pixels are square then xScale == yScale otherwise we fake it // by choosing an average. mGeometricScale = avg(mXScale, mYScale); // Size of diagonal axis. float diagonalSize = hypotf(mSurfaceWidth, mSurfaceHeight); // Size factors. if (mCalibration.sizeCalibration != Calibration::SIZE_CALIBRATION_NONE) { if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.touchMajor.maxValue != 0) { mSizeScale = 1.0f / mRawPointerAxes.touchMajor.maxValue; } else if (mRawPointerAxes.toolMajor.valid && mRawPointerAxes.toolMajor.maxValue != 0) { mSizeScale = 1.0f / mRawPointerAxes.toolMajor.maxValue; } else { mSizeScale = 0.0f; } mOrientedRanges.haveTouchSize = true; mOrientedRanges.haveToolSize = true; mOrientedRanges.haveSize = true; mOrientedRanges.touchMajor.axis = AMOTION_EVENT_AXIS_TOUCH_MAJOR; mOrientedRanges.touchMajor.source = mSource; mOrientedRanges.touchMajor.min = 0; mOrientedRanges.touchMajor.max = diagonalSize; mOrientedRanges.touchMajor.flat = 0; mOrientedRanges.touchMajor.fuzz = 0; mOrientedRanges.touchMajor.resolution = 0; mOrientedRanges.touchMinor = mOrientedRanges.touchMajor; mOrientedRanges.touchMinor.axis = AMOTION_EVENT_AXIS_TOUCH_MINOR; mOrientedRanges.toolMajor.axis = AMOTION_EVENT_AXIS_TOOL_MAJOR; mOrientedRanges.toolMajor.source = mSource; mOrientedRanges.toolMajor.min = 0; mOrientedRanges.toolMajor.max = diagonalSize; mOrientedRanges.toolMajor.flat = 0; mOrientedRanges.toolMajor.fuzz = 0; mOrientedRanges.toolMajor.resolution = 0; mOrientedRanges.toolMinor = mOrientedRanges.toolMajor; mOrientedRanges.toolMinor.axis = AMOTION_EVENT_AXIS_TOOL_MINOR; mOrientedRanges.size.axis = AMOTION_EVENT_AXIS_SIZE; mOrientedRanges.size.source = mSource; mOrientedRanges.size.min = 0; mOrientedRanges.size.max = 1.0; mOrientedRanges.size.flat = 0; mOrientedRanges.size.fuzz = 0; mOrientedRanges.size.resolution = 0; } else { mSizeScale = 0.0f; } // Pressure factors. mPressureScale = 0; if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_PHYSICAL || mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_AMPLITUDE) { if (mCalibration.havePressureScale) { mPressureScale = mCalibration.pressureScale; } else if (mRawPointerAxes.pressure.valid && mRawPointerAxes.pressure.maxValue != 0) { mPressureScale = 1.0f / mRawPointerAxes.pressure.maxValue; } } mOrientedRanges.pressure.axis = AMOTION_EVENT_AXIS_PRESSURE; mOrientedRanges.pressure.source = mSource; mOrientedRanges.pressure.min = 0; mOrientedRanges.pressure.max = 1.0; mOrientedRanges.pressure.flat = 0; mOrientedRanges.pressure.fuzz = 0; mOrientedRanges.pressure.resolution = 0; // Tilt mTiltXCenter = 0; mTiltXScale = 0; mTiltYCenter = 0; mTiltYScale = 0; mHaveTilt = mRawPointerAxes.tiltX.valid && mRawPointerAxes.tiltY.valid; if (mHaveTilt) { mTiltXCenter = avg(mRawPointerAxes.tiltX.minValue, mRawPointerAxes.tiltX.maxValue); mTiltYCenter = avg(mRawPointerAxes.tiltY.minValue, mRawPointerAxes.tiltY.maxValue); mTiltXScale = M_PI / 180; mTiltYScale = M_PI / 180; mOrientedRanges.haveTilt = true; mOrientedRanges.tilt.axis = AMOTION_EVENT_AXIS_TILT; mOrientedRanges.tilt.source = mSource; mOrientedRanges.tilt.min = 0; mOrientedRanges.tilt.max = M_PI_2; mOrientedRanges.tilt.flat = 0; mOrientedRanges.tilt.fuzz = 0; mOrientedRanges.tilt.resolution = 0; } // Orientation mOrientationScale = 0; if (mHaveTilt) { mOrientedRanges.haveOrientation = true; mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION; mOrientedRanges.orientation.source = mSource; mOrientedRanges.orientation.min = -M_PI; mOrientedRanges.orientation.max = M_PI; mOrientedRanges.orientation.flat = 0; mOrientedRanges.orientation.fuzz = 0; mOrientedRanges.orientation.resolution = 0; } else if (mCalibration.orientationCalibration != Calibration::ORIENTATION_CALIBRATION_NONE) { if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_INTERPOLATED) { if (mRawPointerAxes.orientation.valid) { if (mRawPointerAxes.orientation.maxValue > 0) { mOrientationScale = M_PI_2 / mRawPointerAxes.orientation.maxValue; } else if (mRawPointerAxes.orientation.minValue < 0) { mOrientationScale = -M_PI_2 / mRawPointerAxes.orientation.minValue; } else { mOrientationScale = 0; } } } mOrientedRanges.haveOrientation = true; mOrientedRanges.orientation.axis = AMOTION_EVENT_AXIS_ORIENTATION; mOrientedRanges.orientation.source = mSource; mOrientedRanges.orientation.min = -M_PI_2; mOrientedRanges.orientation.max = M_PI_2; mOrientedRanges.orientation.flat = 0; mOrientedRanges.orientation.fuzz = 0; mOrientedRanges.orientation.resolution = 0; } // Distance mDistanceScale = 0; if (mCalibration.distanceCalibration != Calibration::DISTANCE_CALIBRATION_NONE) { if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_SCALED) { if (mCalibration.haveDistanceScale) { mDistanceScale = mCalibration.distanceScale; } else { mDistanceScale = 1.0f; } } mOrientedRanges.haveDistance = true; mOrientedRanges.distance.axis = AMOTION_EVENT_AXIS_DISTANCE; mOrientedRanges.distance.source = mSource; mOrientedRanges.distance.min = mRawPointerAxes.distance.minValue * mDistanceScale; mOrientedRanges.distance.max = mRawPointerAxes.distance.maxValue * mDistanceScale; mOrientedRanges.distance.flat = 0; mOrientedRanges.distance.fuzz = mRawPointerAxes.distance.fuzz * mDistanceScale; mOrientedRanges.distance.resolution = 0; } // Compute oriented precision, scales and ranges. // Note that the maximum value reported is an inclusive maximum value so it is one // unit less than the total width or height of surface. switch (mSurfaceOrientation) { case DISPLAY_ORIENTATION_90: case DISPLAY_ORIENTATION_270: mOrientedXPrecision = mYPrecision; mOrientedYPrecision = mXPrecision; mOrientedRanges.x.min = mYTranslate; mOrientedRanges.x.max = mSurfaceHeight + mYTranslate - 1; mOrientedRanges.x.flat = 0; mOrientedRanges.x.fuzz = 0; mOrientedRanges.x.resolution = mRawPointerAxes.y.resolution * mYScale; mOrientedRanges.y.min = mXTranslate; mOrientedRanges.y.max = mSurfaceWidth + mXTranslate - 1; mOrientedRanges.y.flat = 0; mOrientedRanges.y.fuzz = 0; mOrientedRanges.y.resolution = mRawPointerAxes.x.resolution * mXScale; break; default: mOrientedXPrecision = mXPrecision; mOrientedYPrecision = mYPrecision; mOrientedRanges.x.min = mXTranslate; mOrientedRanges.x.max = mSurfaceWidth + mXTranslate - 1; mOrientedRanges.x.flat = 0; mOrientedRanges.x.fuzz = 0; mOrientedRanges.x.resolution = mRawPointerAxes.x.resolution * mXScale; mOrientedRanges.y.min = mYTranslate; mOrientedRanges.y.max = mSurfaceHeight + mYTranslate - 1; mOrientedRanges.y.flat = 0; mOrientedRanges.y.fuzz = 0; mOrientedRanges.y.resolution = mRawPointerAxes.y.resolution * mYScale; break; } // Location updateAffineTransformation(); if (mDeviceMode == DEVICE_MODE_POINTER) { // Compute pointer gesture detection parameters. float rawDiagonal = hypotf(rawWidth, rawHeight); float displayDiagonal = hypotf(mSurfaceWidth, mSurfaceHeight); // Scale movements such that one whole swipe of the touch pad covers a // given area relative to the diagonal size of the display when no acceleration // is applied. // Assume that the touch pad has a square aspect ratio such that movements in // X and Y of the same number of raw units cover the same physical distance. mPointerXMovementScale = mConfig.pointerGestureMovementSpeedRatio * displayDiagonal / rawDiagonal; mPointerYMovementScale = mPointerXMovementScale; // Scale zooms to cover a smaller range of the display than movements do. // This value determines the area around the pointer that is affected by freeform // pointer gestures. mPointerXZoomScale = mConfig.pointerGestureZoomSpeedRatio * displayDiagonal / rawDiagonal; mPointerYZoomScale = mPointerXZoomScale; // Max width between pointers to detect a swipe gesture is more than some fraction // of the diagonal axis of the touch pad. Touches that are wider than this are // translated into freeform gestures. mPointerGestureMaxSwipeWidth = mConfig.pointerGestureSwipeMaxWidthRatio * rawDiagonal; // Abort current pointer usages because the state has changed. abortPointerUsage(when, 0 /*policyFlags*/); } // Inform the dispatcher about the changes. *outResetNeeded = true; bumpGeneration(); } } void TouchInputMapper::dumpSurface(String8& dump) { dump.appendFormat(INDENT3 "Viewport: displayId=%d, orientation=%d, " "logicalFrame=[%d, %d, %d, %d], " "physicalFrame=[%d, %d, %d, %d], " "deviceSize=[%d, %d]\n", mViewport.displayId, mViewport.orientation, mViewport.logicalLeft, mViewport.logicalTop, mViewport.logicalRight, mViewport.logicalBottom, mViewport.physicalLeft, mViewport.physicalTop, mViewport.physicalRight, mViewport.physicalBottom, mViewport.deviceWidth, mViewport.deviceHeight); dump.appendFormat(INDENT3 "SurfaceWidth: %dpx\n", mSurfaceWidth); dump.appendFormat(INDENT3 "SurfaceHeight: %dpx\n", mSurfaceHeight); dump.appendFormat(INDENT3 "SurfaceLeft: %d\n", mSurfaceLeft); dump.appendFormat(INDENT3 "SurfaceTop: %d\n", mSurfaceTop); dump.appendFormat(INDENT3 "SurfaceOrientation: %d\n", mSurfaceOrientation); } void TouchInputMapper::configureVirtualKeys() { Vector<VirtualKeyDefinition> virtualKeyDefinitions; getEventHub()->getVirtualKeyDefinitions(getDeviceId(), virtualKeyDefinitions); mVirtualKeys.clear(); if (virtualKeyDefinitions.size() == 0) { return; } mVirtualKeys.setCapacity(virtualKeyDefinitions.size()); int32_t touchScreenLeft = mRawPointerAxes.x.minValue; int32_t touchScreenTop = mRawPointerAxes.y.minValue; int32_t touchScreenWidth = mRawPointerAxes.x.maxValue - mRawPointerAxes.x.minValue + 1; int32_t touchScreenHeight = mRawPointerAxes.y.maxValue - mRawPointerAxes.y.minValue + 1; for (size_t i = 0; i < virtualKeyDefinitions.size(); i++) { const VirtualKeyDefinition& virtualKeyDefinition = virtualKeyDefinitions[i]; mVirtualKeys.add(); VirtualKey& virtualKey = mVirtualKeys.editTop(); virtualKey.scanCode = virtualKeyDefinition.scanCode; int32_t keyCode; int32_t dummyKeyMetaState; uint32_t flags; if (getEventHub()->mapKey(getDeviceId(), virtualKey.scanCode, 0, 0, &keyCode, &dummyKeyMetaState, &flags)) { ALOGW(INDENT "VirtualKey %d: could not obtain key code, ignoring", virtualKey.scanCode); mVirtualKeys.pop(); // drop the key continue; } virtualKey.keyCode = keyCode; virtualKey.flags = flags; // convert the key definition's display coordinates into touch coordinates for a hit box int32_t halfWidth = virtualKeyDefinition.width / 2; int32_t halfHeight = virtualKeyDefinition.height / 2; virtualKey.hitLeft = (virtualKeyDefinition.centerX - halfWidth) * touchScreenWidth / mSurfaceWidth + touchScreenLeft; virtualKey.hitRight= (virtualKeyDefinition.centerX + halfWidth) * touchScreenWidth / mSurfaceWidth + touchScreenLeft; virtualKey.hitTop = (virtualKeyDefinition.centerY - halfHeight) * touchScreenHeight / mSurfaceHeight + touchScreenTop; virtualKey.hitBottom = (virtualKeyDefinition.centerY + halfHeight) * touchScreenHeight / mSurfaceHeight + touchScreenTop; } } void TouchInputMapper::dumpVirtualKeys(String8& dump) { if (!mVirtualKeys.isEmpty()) { dump.append(INDENT3 "Virtual Keys:\n"); for (size_t i = 0; i < mVirtualKeys.size(); i++) { const VirtualKey& virtualKey = mVirtualKeys.itemAt(i); dump.appendFormat(INDENT4 "%zu: scanCode=%d, keyCode=%d, " "hitLeft=%d, hitRight=%d, hitTop=%d, hitBottom=%d\n", i, virtualKey.scanCode, virtualKey.keyCode, virtualKey.hitLeft, virtualKey.hitRight, virtualKey.hitTop, virtualKey.hitBottom); } } } void TouchInputMapper::parseCalibration() { const PropertyMap& in = getDevice()->getConfiguration(); Calibration& out = mCalibration; // Size out.sizeCalibration = Calibration::SIZE_CALIBRATION_DEFAULT; String8 sizeCalibrationString; if (in.tryGetProperty(String8("touch.size.calibration"), sizeCalibrationString)) { if (sizeCalibrationString == "none") { out.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE; } else if (sizeCalibrationString == "geometric") { out.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC; } else if (sizeCalibrationString == "diameter") { out.sizeCalibration = Calibration::SIZE_CALIBRATION_DIAMETER; } else if (sizeCalibrationString == "box") { out.sizeCalibration = Calibration::SIZE_CALIBRATION_BOX; } else if (sizeCalibrationString == "area") { out.sizeCalibration = Calibration::SIZE_CALIBRATION_AREA; } else if (sizeCalibrationString != "default") { ALOGW("Invalid value for touch.size.calibration: '%s'", sizeCalibrationString.string()); } } out.haveSizeScale = in.tryGetProperty(String8("touch.size.scale"), out.sizeScale); out.haveSizeBias = in.tryGetProperty(String8("touch.size.bias"), out.sizeBias); out.haveSizeIsSummed = in.tryGetProperty(String8("touch.size.isSummed"), out.sizeIsSummed); // Pressure out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_DEFAULT; String8 pressureCalibrationString; if (in.tryGetProperty(String8("touch.pressure.calibration"), pressureCalibrationString)) { if (pressureCalibrationString == "none") { out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE; } else if (pressureCalibrationString == "physical") { out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL; } else if (pressureCalibrationString == "amplitude") { out.pressureCalibration = Calibration::PRESSURE_CALIBRATION_AMPLITUDE; } else if (pressureCalibrationString != "default") { ALOGW("Invalid value for touch.pressure.calibration: '%s'", pressureCalibrationString.string()); } } out.havePressureScale = in.tryGetProperty(String8("touch.pressure.scale"), out.pressureScale); // Orientation out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_DEFAULT; String8 orientationCalibrationString; if (in.tryGetProperty(String8("touch.orientation.calibration"), orientationCalibrationString)) { if (orientationCalibrationString == "none") { out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE; } else if (orientationCalibrationString == "interpolated") { out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED; } else if (orientationCalibrationString == "vector") { out.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_VECTOR; } else if (orientationCalibrationString != "default") { ALOGW("Invalid value for touch.orientation.calibration: '%s'", orientationCalibrationString.string()); } } // Distance out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_DEFAULT; String8 distanceCalibrationString; if (in.tryGetProperty(String8("touch.distance.calibration"), distanceCalibrationString)) { if (distanceCalibrationString == "none") { out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE; } else if (distanceCalibrationString == "scaled") { out.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED; } else if (distanceCalibrationString != "default") { ALOGW("Invalid value for touch.distance.calibration: '%s'", distanceCalibrationString.string()); } } out.haveDistanceScale = in.tryGetProperty(String8("touch.distance.scale"), out.distanceScale); out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_DEFAULT; String8 coverageCalibrationString; if (in.tryGetProperty(String8("touch.coverage.calibration"), coverageCalibrationString)) { if (coverageCalibrationString == "none") { out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE; } else if (coverageCalibrationString == "box") { out.coverageCalibration = Calibration::COVERAGE_CALIBRATION_BOX; } else if (coverageCalibrationString != "default") { ALOGW("Invalid value for touch.coverage.calibration: '%s'", coverageCalibrationString.string()); } } } void TouchInputMapper::resolveCalibration() { // Size if (mRawPointerAxes.touchMajor.valid || mRawPointerAxes.toolMajor.valid) { if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DEFAULT) { mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_GEOMETRIC; } } else { mCalibration.sizeCalibration = Calibration::SIZE_CALIBRATION_NONE; } // Pressure if (mRawPointerAxes.pressure.valid) { if (mCalibration.pressureCalibration == Calibration::PRESSURE_CALIBRATION_DEFAULT) { mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_PHYSICAL; } } else { mCalibration.pressureCalibration = Calibration::PRESSURE_CALIBRATION_NONE; } // Orientation if (mRawPointerAxes.orientation.valid) { if (mCalibration.orientationCalibration == Calibration::ORIENTATION_CALIBRATION_DEFAULT) { mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_INTERPOLATED; } } else { mCalibration.orientationCalibration = Calibration::ORIENTATION_CALIBRATION_NONE; } // Distance if (mRawPointerAxes.distance.valid) { if (mCalibration.distanceCalibration == Calibration::DISTANCE_CALIBRATION_DEFAULT) { mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_SCALED; } } else { mCalibration.distanceCalibration = Calibration::DISTANCE_CALIBRATION_NONE; } // Coverage if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_DEFAULT) { mCalibration.coverageCalibration = Calibration::COVERAGE_CALIBRATION_NONE; } } void TouchInputMapper::dumpCalibration(String8& dump) { dump.append(INDENT3 "Calibration:\n"); // Size switch (mCalibration.sizeCalibration) { case Calibration::SIZE_CALIBRATION_NONE: dump.append(INDENT4 "touch.size.calibration: none\n"); break; case Calibration::SIZE_CALIBRATION_GEOMETRIC: dump.append(INDENT4 "touch.size.calibration: geometric\n"); break; case Calibration::SIZE_CALIBRATION_DIAMETER: dump.append(INDENT4 "touch.size.calibration: diameter\n"); break; case Calibration::SIZE_CALIBRATION_BOX: dump.append(INDENT4 "touch.size.calibration: box\n"); break; case Calibration::SIZE_CALIBRATION_AREA: dump.append(INDENT4 "touch.size.calibration: area\n"); break; default: ALOG_ASSERT(false); } if (mCalibration.haveSizeScale) { dump.appendFormat(INDENT4 "touch.size.scale: %0.3f\n", mCalibration.sizeScale); } if (mCalibration.haveSizeBias) { dump.appendFormat(INDENT4 "touch.size.bias: %0.3f\n", mCalibration.sizeBias); } if (mCalibration.haveSizeIsSummed) { dump.appendFormat(INDENT4 "touch.size.isSummed: %s\n", toString(mCalibration.sizeIsSummed)); } // Pressure switch (mCalibration.pressureCalibration) { case Calibration::PRESSURE_CALIBRATION_NONE: dump.append(INDENT4 "touch.pressure.calibration: none\n"); break; case Calibration::PRESSURE_CALIBRATION_PHYSICAL: dump.append(INDENT4 "touch.pressure.calibration: physical\n"); break; case Calibration::PRESSURE_CALIBRATION_AMPLITUDE: dump.append(INDENT4 "touch.pressure.calibration: amplitude\n"); break; default: ALOG_ASSERT(false); } if (mCalibration.havePressureScale) { dump.appendFormat(INDENT4 "touch.pressure.scale: %0.3f\n", mCalibration.pressureScale); } // Orientation switch (mCalibration.orientationCalibration) { case Calibration::ORIENTATION_CALIBRATION_NONE: dump.append(INDENT4 "touch.orientation.calibration: none\n"); break; case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED: dump.append(INDENT4 "touch.orientation.calibration: interpolated\n"); break; case Calibration::ORIENTATION_CALIBRATION_VECTOR: dump.append(INDENT4 "touch.orientation.calibration: vector\n"); break; default: ALOG_ASSERT(false); } // Distance switch (mCalibration.distanceCalibration) { case Calibration::DISTANCE_CALIBRATION_NONE: dump.append(INDENT4 "touch.distance.calibration: none\n"); break; case Calibration::DISTANCE_CALIBRATION_SCALED: dump.append(INDENT4 "touch.distance.calibration: scaled\n"); break; default: ALOG_ASSERT(false); } if (mCalibration.haveDistanceScale) { dump.appendFormat(INDENT4 "touch.distance.scale: %0.3f\n", mCalibration.distanceScale); } switch (mCalibration.coverageCalibration) { case Calibration::COVERAGE_CALIBRATION_NONE: dump.append(INDENT4 "touch.coverage.calibration: none\n"); break; case Calibration::COVERAGE_CALIBRATION_BOX: dump.append(INDENT4 "touch.coverage.calibration: box\n"); break; default: ALOG_ASSERT(false); } } void TouchInputMapper::dumpAffineTransformation(String8& dump) { dump.append(INDENT3 "Affine Transformation:\n"); dump.appendFormat(INDENT4 "X scale: %0.3f\n", mAffineTransform.x_scale); dump.appendFormat(INDENT4 "X ymix: %0.3f\n", mAffineTransform.x_ymix); dump.appendFormat(INDENT4 "X offset: %0.3f\n", mAffineTransform.x_offset); dump.appendFormat(INDENT4 "Y xmix: %0.3f\n", mAffineTransform.y_xmix); dump.appendFormat(INDENT4 "Y scale: %0.3f\n", mAffineTransform.y_scale); dump.appendFormat(INDENT4 "Y offset: %0.3f\n", mAffineTransform.y_offset); } void TouchInputMapper::updateAffineTransformation() { mAffineTransform = getPolicy()->getTouchAffineTransformation(mDevice->getDescriptor(), mSurfaceOrientation); } void TouchInputMapper::reset(nsecs_t when) { mCursorButtonAccumulator.reset(getDevice()); mCursorScrollAccumulator.reset(getDevice()); mTouchButtonAccumulator.reset(getDevice()); mPointerVelocityControl.reset(); mWheelXVelocityControl.reset(); mWheelYVelocityControl.reset(); mRawStatesPending.clear(); mCurrentRawState.clear(); mCurrentCookedState.clear(); mLastRawState.clear(); mLastCookedState.clear(); mPointerUsage = POINTER_USAGE_NONE; mSentHoverEnter = false; mHavePointerIds = false; mCurrentMotionAborted = false; mDownTime = 0; mCurrentVirtualKey.down = false; mPointerGesture.reset(); mPointerSimple.reset(); resetExternalStylus(); if (mPointerController != NULL) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); mPointerController->clearSpots(); } InputMapper::reset(when); } void TouchInputMapper::resetExternalStylus() { mExternalStylusState.clear(); mExternalStylusId = -1; mExternalStylusFusionTimeout = LLONG_MAX; mExternalStylusDataPending = false; } void TouchInputMapper::clearStylusDataPendingFlags() { mExternalStylusDataPending = false; mExternalStylusFusionTimeout = LLONG_MAX; } void TouchInputMapper::process(const RawEvent* rawEvent) { mCursorButtonAccumulator.process(rawEvent); mCursorScrollAccumulator.process(rawEvent); mTouchButtonAccumulator.process(rawEvent); if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) { sync(rawEvent->when); } } void TouchInputMapper::sync(nsecs_t when) { const RawState* last = mRawStatesPending.isEmpty() ? &mCurrentRawState : &mRawStatesPending.top(); // Push a new state. mRawStatesPending.push(); RawState* next = &mRawStatesPending.editTop(); next->clear(); next->when = when; // Sync button state. next->buttonState = mTouchButtonAccumulator.getButtonState() | mCursorButtonAccumulator.getButtonState(); // Sync scroll next->rawVScroll = mCursorScrollAccumulator.getRelativeVWheel(); next->rawHScroll = mCursorScrollAccumulator.getRelativeHWheel(); mCursorScrollAccumulator.finishSync(); // Sync touch syncTouch(when, next); // Assign pointer ids. if (!mHavePointerIds) { assignPointerIds(last, next); } #if DEBUG_RAW_EVENTS ALOGD("syncTouch: pointerCount %d -> %d, touching ids 0x%08x -> 0x%08x, " "hovering ids 0x%08x -> 0x%08x", last->rawPointerData.pointerCount, next->rawPointerData.pointerCount, last->rawPointerData.touchingIdBits.value, next->rawPointerData.touchingIdBits.value, last->rawPointerData.hoveringIdBits.value, next->rawPointerData.hoveringIdBits.value); #endif processRawTouches(false /*timeout*/); } void TouchInputMapper::processRawTouches(bool timeout) { if (mDeviceMode == DEVICE_MODE_DISABLED) { // Drop all input if the device is disabled. mCurrentRawState.clear(); mRawStatesPending.clear(); return; } // Drain any pending touch states. The invariant here is that the mCurrentRawState is always // valid and must go through the full cook and dispatch cycle. This ensures that anything // touching the current state will only observe the events that have been dispatched to the // rest of the pipeline. const size_t N = mRawStatesPending.size(); size_t count; for(count = 0; count < N; count++) { const RawState& next = mRawStatesPending[count]; // A failure to assign the stylus id means that we're waiting on stylus data // and so should defer the rest of the pipeline. if (assignExternalStylusId(next, timeout)) { break; } // All ready to go. clearStylusDataPendingFlags(); mCurrentRawState.copyFrom(next); if (mCurrentRawState.when < mLastRawState.when) { mCurrentRawState.when = mLastRawState.when; } cookAndDispatch(mCurrentRawState.when); } if (count != 0) { mRawStatesPending.removeItemsAt(0, count); } if (mExternalStylusDataPending) { if (timeout) { nsecs_t when = mExternalStylusFusionTimeout - STYLUS_DATA_LATENCY; clearStylusDataPendingFlags(); mCurrentRawState.copyFrom(mLastRawState); #if DEBUG_STYLUS_FUSION ALOGD("Timeout expired, synthesizing event with new stylus data"); #endif cookAndDispatch(when); } else if (mExternalStylusFusionTimeout == LLONG_MAX) { mExternalStylusFusionTimeout = mExternalStylusState.when + TOUCH_DATA_TIMEOUT; getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout); } } } void TouchInputMapper::cookAndDispatch(nsecs_t when) { // Always start with a clean state. mCurrentCookedState.clear(); // Apply stylus buttons to current raw state. applyExternalStylusButtonState(when); // Handle policy on initial down or hover events. bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 && mCurrentRawState.rawPointerData.pointerCount != 0; uint32_t policyFlags = 0; bool buttonsPressed = mCurrentRawState.buttonState & ~mLastRawState.buttonState; if (initialDown || buttonsPressed) { // If this is a touch screen, hide the pointer on an initial down. if (mDeviceMode == DEVICE_MODE_DIRECT) { getContext()->fadePointer(); } if (mParameters.wake) { policyFlags |= POLICY_FLAG_WAKE; } } // Consume raw off-screen touches before cooking pointer data. // If touches are consumed, subsequent code will not receive any pointer data. if (consumeRawTouches(when, policyFlags)) { mCurrentRawState.rawPointerData.clear(); } // Cook pointer data. This call populates the mCurrentCookedState.cookedPointerData structure // with cooked pointer data that has the same ids and indices as the raw data. // The following code can use either the raw or cooked data, as needed. cookPointerData(); // Apply stylus pressure to current cooked state. applyExternalStylusTouchState(when); // Synthesize key down from raw buttons if needed. synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_DOWN, when, getDeviceId(), mSource, policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState); // Dispatch the touches either directly or by translation through a pointer on screen. if (mDeviceMode == DEVICE_MODE_POINTER) { for (BitSet32 idBits(mCurrentRawState.rawPointerData.touchingIdBits); !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id); if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) { mCurrentCookedState.stylusIdBits.markBit(id); } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_FINGER || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) { mCurrentCookedState.fingerIdBits.markBit(id); } else if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_MOUSE) { mCurrentCookedState.mouseIdBits.markBit(id); } } for (BitSet32 idBits(mCurrentRawState.rawPointerData.hoveringIdBits); !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id); if (pointer.toolType == AMOTION_EVENT_TOOL_TYPE_STYLUS || pointer.toolType == AMOTION_EVENT_TOOL_TYPE_ERASER) { mCurrentCookedState.stylusIdBits.markBit(id); } } // Stylus takes precedence over all tools, then mouse, then finger. PointerUsage pointerUsage = mPointerUsage; if (!mCurrentCookedState.stylusIdBits.isEmpty()) { mCurrentCookedState.mouseIdBits.clear(); mCurrentCookedState.fingerIdBits.clear(); pointerUsage = POINTER_USAGE_STYLUS; } else if (!mCurrentCookedState.mouseIdBits.isEmpty()) { mCurrentCookedState.fingerIdBits.clear(); pointerUsage = POINTER_USAGE_MOUSE; } else if (!mCurrentCookedState.fingerIdBits.isEmpty() || isPointerDown(mCurrentRawState.buttonState)) { pointerUsage = POINTER_USAGE_GESTURES; } dispatchPointerUsage(when, policyFlags, pointerUsage); } else { if (mDeviceMode == DEVICE_MODE_DIRECT && mConfig.showTouches && mPointerController != NULL) { mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_SPOT); mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); mPointerController->setButtonState(mCurrentRawState.buttonState); mPointerController->setSpots(mCurrentCookedState.cookedPointerData.pointerCoords, mCurrentCookedState.cookedPointerData.idToIndex, mCurrentCookedState.cookedPointerData.touchingIdBits); } if (!mCurrentMotionAborted) { dispatchButtonRelease(when, policyFlags); dispatchHoverExit(when, policyFlags); dispatchTouches(when, policyFlags); dispatchHoverEnterAndMove(when, policyFlags); dispatchButtonPress(when, policyFlags); } if (mCurrentCookedState.cookedPointerData.pointerCount == 0) { mCurrentMotionAborted = false; } } // Synthesize key up from raw buttons if needed. synthesizeButtonKeys(getContext(), AKEY_EVENT_ACTION_UP, when, getDeviceId(), mSource, policyFlags, mLastCookedState.buttonState, mCurrentCookedState.buttonState); // Clear some transient state. mCurrentRawState.rawVScroll = 0; mCurrentRawState.rawHScroll = 0; // Copy current touch to last touch in preparation for the next cycle. mLastRawState.copyFrom(mCurrentRawState); mLastCookedState.copyFrom(mCurrentCookedState); } void TouchInputMapper::applyExternalStylusButtonState(nsecs_t when) { if (mDeviceMode == DEVICE_MODE_DIRECT && hasExternalStylus() && mExternalStylusId != -1) { mCurrentRawState.buttonState |= mExternalStylusState.buttons; } } void TouchInputMapper::applyExternalStylusTouchState(nsecs_t when) { CookedPointerData& currentPointerData = mCurrentCookedState.cookedPointerData; const CookedPointerData& lastPointerData = mLastCookedState.cookedPointerData; if (mExternalStylusId != -1 && currentPointerData.isTouching(mExternalStylusId)) { float pressure = mExternalStylusState.pressure; if (pressure == 0.0f && lastPointerData.isTouching(mExternalStylusId)) { const PointerCoords& coords = lastPointerData.pointerCoordsForId(mExternalStylusId); pressure = coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE); } PointerCoords& coords = currentPointerData.editPointerCoordsWithId(mExternalStylusId); coords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure); PointerProperties& properties = currentPointerData.editPointerPropertiesWithId(mExternalStylusId); if (mExternalStylusState.toolType != AMOTION_EVENT_TOOL_TYPE_UNKNOWN) { properties.toolType = mExternalStylusState.toolType; } } } bool TouchInputMapper::assignExternalStylusId(const RawState& state, bool timeout) { if (mDeviceMode != DEVICE_MODE_DIRECT || !hasExternalStylus()) { return false; } const bool initialDown = mLastRawState.rawPointerData.pointerCount == 0 && state.rawPointerData.pointerCount != 0; if (initialDown) { if (mExternalStylusState.pressure != 0.0f) { #if DEBUG_STYLUS_FUSION ALOGD("Have both stylus and touch data, beginning fusion"); #endif mExternalStylusId = state.rawPointerData.touchingIdBits.firstMarkedBit(); } else if (timeout) { #if DEBUG_STYLUS_FUSION ALOGD("Timeout expired, assuming touch is not a stylus."); #endif resetExternalStylus(); } else { if (mExternalStylusFusionTimeout == LLONG_MAX) { mExternalStylusFusionTimeout = state.when + EXTERNAL_STYLUS_DATA_TIMEOUT; } #if DEBUG_STYLUS_FUSION ALOGD("No stylus data but stylus is connected, requesting timeout " "(%" PRId64 "ms)", mExternalStylusFusionTimeout); #endif getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout); return true; } } // Check if the stylus pointer has gone up. if (mExternalStylusId != -1 && !state.rawPointerData.touchingIdBits.hasBit(mExternalStylusId)) { #if DEBUG_STYLUS_FUSION ALOGD("Stylus pointer is going up"); #endif mExternalStylusId = -1; } return false; } void TouchInputMapper::timeoutExpired(nsecs_t when) { if (mDeviceMode == DEVICE_MODE_POINTER) { if (mPointerUsage == POINTER_USAGE_GESTURES) { dispatchPointerGestures(when, 0 /*policyFlags*/, true /*isTimeout*/); } } else if (mDeviceMode == DEVICE_MODE_DIRECT) { if (mExternalStylusFusionTimeout < when) { processRawTouches(true /*timeout*/); } else if (mExternalStylusFusionTimeout != LLONG_MAX) { getContext()->requestTimeoutAtTime(mExternalStylusFusionTimeout); } } } void TouchInputMapper::updateExternalStylusState(const StylusState& state) { mExternalStylusState.copyFrom(state); if (mExternalStylusId != -1 || mExternalStylusFusionTimeout != LLONG_MAX) { // We're either in the middle of a fused stream of data or we're waiting on data before // dispatching the initial down, so go ahead and dispatch now that we have fresh stylus // data. mExternalStylusDataPending = true; processRawTouches(false /*timeout*/); } } bool TouchInputMapper::consumeRawTouches(nsecs_t when, uint32_t policyFlags) { // Check for release of a virtual key. if (mCurrentVirtualKey.down) { if (mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) { // Pointer went up while virtual key was down. mCurrentVirtualKey.down = false; if (!mCurrentVirtualKey.ignored) { #if DEBUG_VIRTUAL_KEYS ALOGD("VirtualKeys: Generating key up: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode); #endif dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP, AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY); } return true; } if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) { uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit(); const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id); const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y); if (virtualKey && virtualKey->keyCode == mCurrentVirtualKey.keyCode) { // Pointer is still within the space of the virtual key. return true; } } // Pointer left virtual key area or another pointer also went down. // Send key cancellation but do not consume the touch yet. // This is useful when the user swipes through from the virtual key area // into the main display surface. mCurrentVirtualKey.down = false; if (!mCurrentVirtualKey.ignored) { #if DEBUG_VIRTUAL_KEYS ALOGD("VirtualKeys: Canceling key: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode); #endif dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_UP, AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY | AKEY_EVENT_FLAG_CANCELED); } } if (mLastRawState.rawPointerData.touchingIdBits.isEmpty() && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) { // Pointer just went down. Check for virtual key press or off-screen touches. uint32_t id = mCurrentRawState.rawPointerData.touchingIdBits.firstMarkedBit(); const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id); if (!isPointInsideSurface(pointer.x, pointer.y)) { // If exactly one pointer went down, check for virtual key hit. // Otherwise we will drop the entire stroke. if (mCurrentRawState.rawPointerData.touchingIdBits.count() == 1) { const VirtualKey* virtualKey = findVirtualKeyHit(pointer.x, pointer.y); if (virtualKey) { mCurrentVirtualKey.down = true; mCurrentVirtualKey.downTime = when; mCurrentVirtualKey.keyCode = virtualKey->keyCode; mCurrentVirtualKey.scanCode = virtualKey->scanCode; mCurrentVirtualKey.ignored = mContext->shouldDropVirtualKey( when, getDevice(), virtualKey->keyCode, virtualKey->scanCode); if (!mCurrentVirtualKey.ignored) { #if DEBUG_VIRTUAL_KEYS ALOGD("VirtualKeys: Generating key down: keyCode=%d, scanCode=%d", mCurrentVirtualKey.keyCode, mCurrentVirtualKey.scanCode); #endif dispatchVirtualKey(when, policyFlags, AKEY_EVENT_ACTION_DOWN, AKEY_EVENT_FLAG_FROM_SYSTEM | AKEY_EVENT_FLAG_VIRTUAL_HARD_KEY); } } } return true; } } // Disable all virtual key touches that happen within a short time interval of the // most recent touch within the screen area. The idea is to filter out stray // virtual key presses when interacting with the touch screen. // // Problems we're trying to solve: // // 1. While scrolling a list or dragging the window shade, the user swipes down into a // virtual key area that is implemented by a separate touch panel and accidentally // triggers a virtual key. // // 2. While typing in the on screen keyboard, the user taps slightly outside the screen // area and accidentally triggers a virtual key. This often happens when virtual keys // are layed out below the screen near to where the on screen keyboard's space bar // is displayed. if (mConfig.virtualKeyQuietTime > 0 && !mCurrentRawState.rawPointerData.touchingIdBits.isEmpty()) { mContext->disableVirtualKeysUntil(when + mConfig.virtualKeyQuietTime); } return false; } void TouchInputMapper::dispatchVirtualKey(nsecs_t when, uint32_t policyFlags, int32_t keyEventAction, int32_t keyEventFlags) { int32_t keyCode = mCurrentVirtualKey.keyCode; int32_t scanCode = mCurrentVirtualKey.scanCode; nsecs_t downTime = mCurrentVirtualKey.downTime; int32_t metaState = mContext->getGlobalMetaState(); nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); policyFlags |= POLICY_FLAG_VIRTUAL; ALOGD_READER("dispatchVirtualKey now(ns): %lld",now); NotifyKeyArgs args(when, getDeviceId(), AINPUT_SOURCE_KEYBOARD, policyFlags, keyEventAction, keyEventFlags, keyCode, scanCode, metaState, downTime); getListener()->notifyKey(&args); ALOGD_READER("notifyKey - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, action=0x%x, " "flags=0x%x, keyCode=0x%x, scanCode=0x%x, metaState=0x%x, downTime=%lld", args.eventTime, args.deviceId, args.source, args.policyFlags, args.action, args.flags, args.keyCode, args.scanCode, args.metaState, args.downTime); } void TouchInputMapper::abortTouches(nsecs_t when, uint32_t policyFlags) { BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits; if (!currentIdBits.isEmpty()) { int32_t metaState = getContext()->getGlobalMetaState(); int32_t buttonState = mCurrentCookedState.buttonState; dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, mCurrentCookedState.cookedPointerData.pointerProperties, mCurrentCookedState.cookedPointerData.pointerCoords, mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime); mCurrentMotionAborted = true; } } void TouchInputMapper::dispatchTouches(nsecs_t when, uint32_t policyFlags) { BitSet32 currentIdBits = mCurrentCookedState.cookedPointerData.touchingIdBits; BitSet32 lastIdBits = mLastCookedState.cookedPointerData.touchingIdBits; int32_t metaState = getContext()->getGlobalMetaState(); int32_t buttonState = mCurrentCookedState.buttonState; nsecs_t now = systemTime(SYSTEM_TIME_MONOTONIC); if (currentIdBits == lastIdBits) { if (!currentIdBits.isEmpty()) { // No pointer id changes so this is a move event. // The listener takes care of batching moves so we don't have to deal with that here. ALOGD_READER("dispatchTouches POINTER MOVE now(ns): %lld",now); dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, mCurrentCookedState.cookedPointerData.pointerProperties, mCurrentCookedState.cookedPointerData.pointerCoords, mCurrentCookedState.cookedPointerData.idToIndex, currentIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime); } } else { // There may be pointers going up and pointers going down and pointers moving // all at the same time. BitSet32 upIdBits(lastIdBits.value & ~currentIdBits.value); BitSet32 downIdBits(currentIdBits.value & ~lastIdBits.value); BitSet32 moveIdBits(lastIdBits.value & currentIdBits.value); BitSet32 dispatchedIdBits(lastIdBits.value); // Update last coordinates of pointers that have moved so that we observe the new // pointer positions at the same time as other pointers that have just gone up. bool moveNeeded = updateMovedPointers( mCurrentCookedState.cookedPointerData.pointerProperties, mCurrentCookedState.cookedPointerData.pointerCoords, mCurrentCookedState.cookedPointerData.idToIndex, mLastCookedState.cookedPointerData.pointerProperties, mLastCookedState.cookedPointerData.pointerCoords, mLastCookedState.cookedPointerData.idToIndex, moveIdBits); if (buttonState != mLastCookedState.buttonState) { moveNeeded = true; } // Dispatch pointer up events. while (!upIdBits.isEmpty()) { uint32_t upId = upIdBits.clearFirstMarkedBit(); { ScopedTrace _l(ATRACE_TAG_INPUT|ATRACE_TAG_PERF, "AppLaunch_dispatchPtr:Up"); ALOGD("AP_PROF:AppLaunch_dispatchPtr:Up:%lld, ID:%d, Index:%d", when/1000000, upId, mLastCookedState.cookedPointerData.idToIndex); ALOGD_READER("dispatchMotion POINTER UP now(ns): %lld",now); dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, 0, mLastCookedState.cookedPointerData.pointerProperties, mLastCookedState.cookedPointerData.pointerCoords, mLastCookedState.cookedPointerData.idToIndex, dispatchedIdBits, upId, mOrientedXPrecision, mOrientedYPrecision, mDownTime); dispatchedIdBits.clearBit(upId); } } // Dispatch move events if any of the remaining pointers moved from their old locations. // Although applications receive new locations as part of individual pointer up // events, they do not generally handle them except when presented in a move event. if (moveNeeded && !moveIdBits.isEmpty()) { ALOG_ASSERT(moveIdBits.value == dispatchedIdBits.value); ALOGD_READER("dispatchMotion POINTER MOVE, now(ns): %lld",now); dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties, mCurrentCookedState.cookedPointerData.pointerCoords, mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime); } // Dispatch pointer down events using the new pointer locations. while (!downIdBits.isEmpty()) { uint32_t downId = downIdBits.clearFirstMarkedBit(); dispatchedIdBits.markBit(downId); if (dispatchedIdBits.count() == 1) { // First pointer is going down. Set down time. mDownTime = when; { ScopedTrace _l(ATRACE_TAG_INPUT, "AppLaunch_dispatchPtr:Down"); ALOGD("AP_PROF:AppLaunch_dispatchPtr:Down:%lld, ID:%d, Index:%d", mDownTime/1000000, downId, mCurrentCookedState.cookedPointerData.idToIndex); } } ALOGD_READER("dispatchMotion POINTER DOWN now(ns): %lld",now); dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties, mCurrentCookedState.cookedPointerData.pointerCoords, mCurrentCookedState.cookedPointerData.idToIndex, dispatchedIdBits, downId, mOrientedXPrecision, mOrientedYPrecision, mDownTime); } } } void TouchInputMapper::dispatchHoverExit(nsecs_t when, uint32_t policyFlags) { if (mSentHoverEnter && (mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty() || !mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty())) { int32_t metaState = getContext()->getGlobalMetaState(); dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastCookedState.buttonState, 0, mLastCookedState.cookedPointerData.pointerProperties, mLastCookedState.cookedPointerData.pointerCoords, mLastCookedState.cookedPointerData.idToIndex, mLastCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime); mSentHoverEnter = false; } } void TouchInputMapper::dispatchHoverEnterAndMove(nsecs_t when, uint32_t policyFlags) { if (mCurrentCookedState.cookedPointerData.touchingIdBits.isEmpty() && !mCurrentCookedState.cookedPointerData.hoveringIdBits.isEmpty()) { int32_t metaState = getContext()->getGlobalMetaState(); if (!mSentHoverEnter) { dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState, mCurrentRawState.buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties, mCurrentCookedState.cookedPointerData.pointerCoords, mCurrentCookedState.cookedPointerData.idToIndex, mCurrentCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime); mSentHoverEnter = true; } dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties, mCurrentCookedState.cookedPointerData.pointerCoords, mCurrentCookedState.cookedPointerData.idToIndex, mCurrentCookedState.cookedPointerData.hoveringIdBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime); } } void TouchInputMapper::dispatchButtonRelease(nsecs_t when, uint32_t policyFlags) { BitSet32 releasedButtons(mLastCookedState.buttonState & ~mCurrentCookedState.buttonState); const BitSet32& idBits = findActiveIdBits(mLastCookedState.cookedPointerData); const int32_t metaState = getContext()->getGlobalMetaState(); int32_t buttonState = mLastCookedState.buttonState; while (!releasedButtons.isEmpty()) { int32_t actionButton = BitSet32::valueForBit(releasedButtons.clearFirstMarkedBit()); buttonState &= ~actionButton; dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_RELEASE, actionButton, 0, metaState, buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties, mCurrentCookedState.cookedPointerData.pointerCoords, mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime); } } void TouchInputMapper::dispatchButtonPress(nsecs_t when, uint32_t policyFlags) { BitSet32 pressedButtons(mCurrentCookedState.buttonState & ~mLastCookedState.buttonState); const BitSet32& idBits = findActiveIdBits(mCurrentCookedState.cookedPointerData); const int32_t metaState = getContext()->getGlobalMetaState(); int32_t buttonState = mLastCookedState.buttonState; while (!pressedButtons.isEmpty()) { int32_t actionButton = BitSet32::valueForBit(pressedButtons.clearFirstMarkedBit()); buttonState |= actionButton; dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_BUTTON_PRESS, actionButton, 0, metaState, buttonState, 0, mCurrentCookedState.cookedPointerData.pointerProperties, mCurrentCookedState.cookedPointerData.pointerCoords, mCurrentCookedState.cookedPointerData.idToIndex, idBits, -1, mOrientedXPrecision, mOrientedYPrecision, mDownTime); } } const BitSet32& TouchInputMapper::findActiveIdBits(const CookedPointerData& cookedPointerData) { if (!cookedPointerData.touchingIdBits.isEmpty()) { return cookedPointerData.touchingIdBits; } return cookedPointerData.hoveringIdBits; } void TouchInputMapper::cookPointerData() { uint32_t currentPointerCount = mCurrentRawState.rawPointerData.pointerCount; mCurrentCookedState.cookedPointerData.clear(); mCurrentCookedState.cookedPointerData.pointerCount = currentPointerCount; mCurrentCookedState.cookedPointerData.hoveringIdBits = mCurrentRawState.rawPointerData.hoveringIdBits; mCurrentCookedState.cookedPointerData.touchingIdBits = mCurrentRawState.rawPointerData.touchingIdBits; if (mCurrentCookedState.cookedPointerData.pointerCount == 0) { mCurrentCookedState.buttonState = 0; } else { mCurrentCookedState.buttonState = mCurrentRawState.buttonState; } // Walk through the the active pointers and map device coordinates onto // surface coordinates and adjust for display orientation. for (uint32_t i = 0; i < currentPointerCount; i++) { const RawPointerData::Pointer& in = mCurrentRawState.rawPointerData.pointers[i]; // Size float touchMajor, touchMinor, toolMajor, toolMinor, size; switch (mCalibration.sizeCalibration) { case Calibration::SIZE_CALIBRATION_GEOMETRIC: case Calibration::SIZE_CALIBRATION_DIAMETER: case Calibration::SIZE_CALIBRATION_BOX: case Calibration::SIZE_CALIBRATION_AREA: if (mRawPointerAxes.touchMajor.valid && mRawPointerAxes.toolMajor.valid) { touchMajor = in.touchMajor; touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor; toolMajor = in.toolMajor; toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor; size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor) : in.touchMajor; } else if (mRawPointerAxes.touchMajor.valid) { toolMajor = touchMajor = in.touchMajor; toolMinor = touchMinor = mRawPointerAxes.touchMinor.valid ? in.touchMinor : in.touchMajor; size = mRawPointerAxes.touchMinor.valid ? avg(in.touchMajor, in.touchMinor) : in.touchMajor; } else if (mRawPointerAxes.toolMajor.valid) { touchMajor = toolMajor = in.toolMajor; touchMinor = toolMinor = mRawPointerAxes.toolMinor.valid ? in.toolMinor : in.toolMajor; size = mRawPointerAxes.toolMinor.valid ? avg(in.toolMajor, in.toolMinor) : in.toolMajor; } else { ALOG_ASSERT(false, "No touch or tool axes. " "Size calibration should have been resolved to NONE."); touchMajor = 0; touchMinor = 0; toolMajor = 0; toolMinor = 0; size = 0; } if (mCalibration.haveSizeIsSummed && mCalibration.sizeIsSummed) { uint32_t touchingCount = mCurrentRawState.rawPointerData.touchingIdBits.count(); if (touchingCount > 1) { touchMajor /= touchingCount; touchMinor /= touchingCount; toolMajor /= touchingCount; toolMinor /= touchingCount; size /= touchingCount; } } if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_GEOMETRIC) { touchMajor *= mGeometricScale; touchMinor *= mGeometricScale; toolMajor *= mGeometricScale; toolMinor *= mGeometricScale; } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_AREA) { touchMajor = touchMajor > 0 ? sqrtf(touchMajor) : 0; touchMinor = touchMajor; toolMajor = toolMajor > 0 ? sqrtf(toolMajor) : 0; toolMinor = toolMajor; } else if (mCalibration.sizeCalibration == Calibration::SIZE_CALIBRATION_DIAMETER) { touchMinor = touchMajor; toolMinor = toolMajor; } mCalibration.applySizeScaleAndBias(&touchMajor); mCalibration.applySizeScaleAndBias(&touchMinor); mCalibration.applySizeScaleAndBias(&toolMajor); mCalibration.applySizeScaleAndBias(&toolMinor); size *= mSizeScale; break; default: touchMajor = 0; touchMinor = 0; toolMajor = 0; toolMinor = 0; size = 0; break; } // Pressure float pressure; switch (mCalibration.pressureCalibration) { case Calibration::PRESSURE_CALIBRATION_PHYSICAL: case Calibration::PRESSURE_CALIBRATION_AMPLITUDE: pressure = in.pressure * mPressureScale; break; default: pressure = in.isHovering ? 0 : 1; break; } // Tilt and Orientation float tilt; float orientation; if (mHaveTilt) { float tiltXAngle = (in.tiltX - mTiltXCenter) * mTiltXScale; float tiltYAngle = (in.tiltY - mTiltYCenter) * mTiltYScale; orientation = atan2f(-sinf(tiltXAngle), sinf(tiltYAngle)); tilt = acosf(cosf(tiltXAngle) * cosf(tiltYAngle)); } else { tilt = 0; switch (mCalibration.orientationCalibration) { case Calibration::ORIENTATION_CALIBRATION_INTERPOLATED: orientation = in.orientation * mOrientationScale; break; case Calibration::ORIENTATION_CALIBRATION_VECTOR: { int32_t c1 = signExtendNybble((in.orientation & 0xf0) >> 4); int32_t c2 = signExtendNybble(in.orientation & 0x0f); if (c1 != 0 || c2 != 0) { orientation = atan2f(c1, c2) * 0.5f; float confidence = hypotf(c1, c2); float scale = 1.0f + confidence / 16.0f; touchMajor *= scale; touchMinor /= scale; toolMajor *= scale; toolMinor /= scale; } else { orientation = 0; } break; } default: orientation = 0; } } // Distance float distance; switch (mCalibration.distanceCalibration) { case Calibration::DISTANCE_CALIBRATION_SCALED: distance = in.distance * mDistanceScale; break; default: distance = 0; } // Coverage int32_t rawLeft, rawTop, rawRight, rawBottom; switch (mCalibration.coverageCalibration) { case Calibration::COVERAGE_CALIBRATION_BOX: rawLeft = (in.toolMinor & 0xffff0000) >> 16; rawRight = in.toolMinor & 0x0000ffff; rawBottom = in.toolMajor & 0x0000ffff; rawTop = (in.toolMajor & 0xffff0000) >> 16; break; default: rawLeft = rawTop = rawRight = rawBottom = 0; break; } // Adjust X,Y coords for device calibration // TODO: Adjust coverage coords? float xTransformed = in.x, yTransformed = in.y; mAffineTransform.applyTo(xTransformed, yTransformed); // Adjust X, Y, and coverage coords for surface orientation. float x, y; float left, top, right, bottom; switch (mSurfaceOrientation) { case DISPLAY_ORIENTATION_90: x = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate; y = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate; left = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate; right = float(rawBottom- mRawPointerAxes.y.minValue) * mYScale + mYTranslate; bottom = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate; top = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate; orientation -= M_PI_2; if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) { orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min); } break; case DISPLAY_ORIENTATION_180: x = float(mRawPointerAxes.x.maxValue - xTransformed) * mXScale + mXTranslate; y = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate; left = float(mRawPointerAxes.x.maxValue - rawRight) * mXScale + mXTranslate; right = float(mRawPointerAxes.x.maxValue - rawLeft) * mXScale + mXTranslate; bottom = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate; top = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate; orientation -= M_PI; if (mOrientedRanges.haveOrientation && orientation < mOrientedRanges.orientation.min) { orientation += (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min); } break; case DISPLAY_ORIENTATION_270: x = float(mRawPointerAxes.y.maxValue - yTransformed) * mYScale + mYTranslate; y = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate; left = float(mRawPointerAxes.y.maxValue - rawBottom) * mYScale + mYTranslate; right = float(mRawPointerAxes.y.maxValue - rawTop) * mYScale + mYTranslate; bottom = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate; top = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate; orientation += M_PI_2; if (mOrientedRanges.haveOrientation && orientation > mOrientedRanges.orientation.max) { orientation -= (mOrientedRanges.orientation.max - mOrientedRanges.orientation.min); } break; default: x = float(xTransformed - mRawPointerAxes.x.minValue) * mXScale + mXTranslate; y = float(yTransformed - mRawPointerAxes.y.minValue) * mYScale + mYTranslate; left = float(rawLeft - mRawPointerAxes.x.minValue) * mXScale + mXTranslate; right = float(rawRight - mRawPointerAxes.x.minValue) * mXScale + mXTranslate; bottom = float(rawBottom - mRawPointerAxes.y.minValue) * mYScale + mYTranslate; top = float(rawTop - mRawPointerAxes.y.minValue) * mYScale + mYTranslate; break; } // Write output coords. PointerCoords& out = mCurrentCookedState.cookedPointerData.pointerCoords[i]; out.clear(); out.setAxisValue(AMOTION_EVENT_AXIS_X, x); out.setAxisValue(AMOTION_EVENT_AXIS_Y, y); out.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, pressure); out.setAxisValue(AMOTION_EVENT_AXIS_SIZE, size); out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR, touchMajor); out.setAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR, touchMinor); out.setAxisValue(AMOTION_EVENT_AXIS_ORIENTATION, orientation); out.setAxisValue(AMOTION_EVENT_AXIS_TILT, tilt); out.setAxisValue(AMOTION_EVENT_AXIS_DISTANCE, distance); if (mCalibration.coverageCalibration == Calibration::COVERAGE_CALIBRATION_BOX) { out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_1, left); out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_2, top); out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_3, right); out.setAxisValue(AMOTION_EVENT_AXIS_GENERIC_4, bottom); } else { out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR, toolMajor); out.setAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR, toolMinor); } // Write output properties. PointerProperties& properties = mCurrentCookedState.cookedPointerData.pointerProperties[i]; uint32_t id = in.id; properties.clear(); properties.id = id; properties.toolType = in.toolType; // Write id index. mCurrentCookedState.cookedPointerData.idToIndex[id] = i; } } void TouchInputMapper::dispatchPointerUsage(nsecs_t when, uint32_t policyFlags, PointerUsage pointerUsage) { if (pointerUsage != mPointerUsage) { abortPointerUsage(when, policyFlags); mPointerUsage = pointerUsage; } switch (mPointerUsage) { case POINTER_USAGE_GESTURES: dispatchPointerGestures(when, policyFlags, false /*isTimeout*/); break; case POINTER_USAGE_STYLUS: dispatchPointerStylus(when, policyFlags); break; case POINTER_USAGE_MOUSE: dispatchPointerMouse(when, policyFlags); break; default: break; } } void TouchInputMapper::abortPointerUsage(nsecs_t when, uint32_t policyFlags) { switch (mPointerUsage) { case POINTER_USAGE_GESTURES: abortPointerGestures(when, policyFlags); break; case POINTER_USAGE_STYLUS: abortPointerStylus(when, policyFlags); break; case POINTER_USAGE_MOUSE: abortPointerMouse(when, policyFlags); break; default: break; } mPointerUsage = POINTER_USAGE_NONE; } void TouchInputMapper::dispatchPointerGestures(nsecs_t when, uint32_t policyFlags, bool isTimeout) { // Update current gesture coordinates. bool cancelPreviousGesture, finishPreviousGesture; bool sendEvents = preparePointerGestures(when, &cancelPreviousGesture, &finishPreviousGesture, isTimeout); if (!sendEvents) { return; } if (finishPreviousGesture) { cancelPreviousGesture = false; } // Update the pointer presentation and spots. if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) { mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER); if (finishPreviousGesture || cancelPreviousGesture) { mPointerController->clearSpots(); } if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) { mPointerController->setSpots(mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, mPointerGesture.currentGestureIdBits); } } else { mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER); } // Show or hide the pointer if needed. switch (mPointerGesture.currentGestureMode) { case PointerGesture::NEUTRAL: case PointerGesture::QUIET: if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH && mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) { // Remind the user of where the pointer is after finishing a gesture with spots. mPointerController->unfade(PointerControllerInterface::TRANSITION_GRADUAL); } break; case PointerGesture::TAP: case PointerGesture::TAP_DRAG: case PointerGesture::BUTTON_CLICK_OR_DRAG: case PointerGesture::HOVER: case PointerGesture::PRESS: case PointerGesture::SWIPE: // Unfade the pointer when the current gesture manipulates the // area directly under the pointer. mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE); break; case PointerGesture::FREEFORM: // Fade the pointer when the current gesture manipulates a different // area and there are spots to guide the user experience. if (mParameters.gestureMode == Parameters::GESTURE_MODE_MULTI_TOUCH) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); } else { mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE); } break; } // Send events! int32_t metaState = getContext()->getGlobalMetaState(); int32_t buttonState = mCurrentCookedState.buttonState; // Update last coordinates of pointers that have moved so that we observe the new // pointer positions at the same time as other pointers that have just gone up. bool down = mPointerGesture.currentGestureMode == PointerGesture::TAP || mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG || mPointerGesture.currentGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG || mPointerGesture.currentGestureMode == PointerGesture::PRESS || mPointerGesture.currentGestureMode == PointerGesture::SWIPE || mPointerGesture.currentGestureMode == PointerGesture::FREEFORM; bool moveNeeded = false; if (down && !cancelPreviousGesture && !finishPreviousGesture && !mPointerGesture.lastGestureIdBits.isEmpty() && !mPointerGesture.currentGestureIdBits.isEmpty()) { BitSet32 movedGestureIdBits(mPointerGesture.currentGestureIdBits.value & mPointerGesture.lastGestureIdBits.value); moveNeeded = updateMovedPointers(mPointerGesture.currentGestureProperties, mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex, movedGestureIdBits); if (buttonState != mLastCookedState.buttonState) { moveNeeded = true; } } // Send motion events for all pointers that went up or were canceled. BitSet32 dispatchedGestureIdBits(mPointerGesture.lastGestureIdBits); if (!dispatchedGestureIdBits.isEmpty()) { if (cancelPreviousGesture) { dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0, mPointerGesture.downTime); dispatchedGestureIdBits.clear(); } else { BitSet32 upGestureIdBits; if (finishPreviousGesture) { upGestureIdBits = dispatchedGestureIdBits; } else { upGestureIdBits.value = dispatchedGestureIdBits.value & ~mPointerGesture.currentGestureIdBits.value; } while (!upGestureIdBits.isEmpty()) { uint32_t id = upGestureIdBits.clearFirstMarkedBit(); dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_UP, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex, dispatchedGestureIdBits, id, 0, 0, mPointerGesture.downTime); dispatchedGestureIdBits.clearBit(id); } } } // Send motion events for all pointers that moved. if (moveNeeded) { dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.currentGestureProperties, mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, -1, 0, 0, mPointerGesture.downTime); } // Send motion events for all pointers that went down. if (down) { BitSet32 downGestureIdBits(mPointerGesture.currentGestureIdBits.value & ~dispatchedGestureIdBits.value); while (!downGestureIdBits.isEmpty()) { uint32_t id = downGestureIdBits.clearFirstMarkedBit(); dispatchedGestureIdBits.markBit(id); if (dispatchedGestureIdBits.count() == 1) { mPointerGesture.downTime = when; } dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_POINTER_DOWN, 0, 0, metaState, buttonState, 0, mPointerGesture.currentGestureProperties, mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, dispatchedGestureIdBits, id, 0, 0, mPointerGesture.downTime); } } // Send motion events for hover. if (mPointerGesture.currentGestureMode == PointerGesture::HOVER) { dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.currentGestureProperties, mPointerGesture.currentGestureCoords, mPointerGesture.currentGestureIdToIndex, mPointerGesture.currentGestureIdBits, -1, 0, 0, mPointerGesture.downTime); } else if (dispatchedGestureIdBits.isEmpty() && !mPointerGesture.lastGestureIdBits.isEmpty()) { // Synthesize a hover move event after all pointers go up to indicate that // the pointer is hovering again even if the user is not currently touching // the touch pad. This ensures that a view will receive a fresh hover enter // event after a tap. float x, y; mPointerController->getPosition(&x, &y); PointerProperties pointerProperties; pointerProperties.clear(); pointerProperties.id = 0; pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; PointerCoords pointerCoords; pointerCoords.clear(); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, mViewport.displayId, 1, &pointerProperties, &pointerCoords, 0, 0, mPointerGesture.downTime); getListener()->notifyMotion(&args); } // Update state. mPointerGesture.lastGestureMode = mPointerGesture.currentGestureMode; if (!down) { mPointerGesture.lastGestureIdBits.clear(); } else { mPointerGesture.lastGestureIdBits = mPointerGesture.currentGestureIdBits; for (BitSet32 idBits(mPointerGesture.currentGestureIdBits); !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); uint32_t index = mPointerGesture.currentGestureIdToIndex[id]; mPointerGesture.lastGestureProperties[index].copyFrom( mPointerGesture.currentGestureProperties[index]); mPointerGesture.lastGestureCoords[index].copyFrom( mPointerGesture.currentGestureCoords[index]); mPointerGesture.lastGestureIdToIndex[id] = index; } } } void TouchInputMapper::abortPointerGestures(nsecs_t when, uint32_t policyFlags) { // Cancel previously dispatches pointers. if (!mPointerGesture.lastGestureIdBits.isEmpty()) { int32_t metaState = getContext()->getGlobalMetaState(); int32_t buttonState = mCurrentRawState.buttonState; dispatchMotion(when, policyFlags, mSource, AMOTION_EVENT_ACTION_CANCEL, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, mPointerGesture.lastGestureProperties, mPointerGesture.lastGestureCoords, mPointerGesture.lastGestureIdToIndex, mPointerGesture.lastGestureIdBits, -1, 0, 0, mPointerGesture.downTime); } // Reset the current pointer gesture. mPointerGesture.reset(); mPointerVelocityControl.reset(); // Remove any current spots. if (mPointerController != NULL) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); mPointerController->clearSpots(); } } bool TouchInputMapper::preparePointerGestures(nsecs_t when, bool* outCancelPreviousGesture, bool* outFinishPreviousGesture, bool isTimeout) { *outCancelPreviousGesture = false; *outFinishPreviousGesture = false; // Handle TAP timeout. if (isTimeout) { #if DEBUG_GESTURES ALOGD("Gestures: Processing timeout"); #endif if (mPointerGesture.lastGestureMode == PointerGesture::TAP) { if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) { // The tap/drag timeout has not yet expired. getContext()->requestTimeoutAtTime(mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval); } else { // The tap is finished. #if DEBUG_GESTURES ALOGD("Gestures: TAP finished"); #endif *outFinishPreviousGesture = true; mPointerGesture.activeGestureId = -1; mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL; mPointerGesture.currentGestureIdBits.clear(); mPointerVelocityControl.reset(); return true; } } // We did not handle this timeout. return false; } const uint32_t currentFingerCount = mCurrentCookedState.fingerIdBits.count(); const uint32_t lastFingerCount = mLastCookedState.fingerIdBits.count(); // Update the velocity tracker. { VelocityTracker::Position positions[MAX_POINTERS]; uint32_t count = 0; for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); count++) { uint32_t id = idBits.clearFirstMarkedBit(); const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(id); positions[count].x = pointer.x * mPointerXMovementScale; positions[count].y = pointer.y * mPointerYMovementScale; } mPointerGesture.velocityTracker.addMovement(when, mCurrentCookedState.fingerIdBits, positions); } // If the gesture ever enters a mode other than TAP, HOVER or TAP_DRAG, without first returning // to NEUTRAL, then we should not generate tap event. if (mPointerGesture.lastGestureMode != PointerGesture::HOVER && mPointerGesture.lastGestureMode != PointerGesture::TAP && mPointerGesture.lastGestureMode != PointerGesture::TAP_DRAG) { mPointerGesture.resetTap(); } // Pick a new active touch id if needed. // Choose an arbitrary pointer that just went down, if there is one. // Otherwise choose an arbitrary remaining pointer. // This guarantees we always have an active touch id when there is at least one pointer. // We keep the same active touch id for as long as possible. bool activeTouchChanged = false; int32_t lastActiveTouchId = mPointerGesture.activeTouchId; int32_t activeTouchId = lastActiveTouchId; if (activeTouchId < 0) { if (!mCurrentCookedState.fingerIdBits.isEmpty()) { activeTouchChanged = true; activeTouchId = mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit(); mPointerGesture.firstTouchTime = when; } } else if (!mCurrentCookedState.fingerIdBits.hasBit(activeTouchId)) { activeTouchChanged = true; if (!mCurrentCookedState.fingerIdBits.isEmpty()) { activeTouchId = mPointerGesture.activeTouchId = mCurrentCookedState.fingerIdBits.firstMarkedBit(); } else { activeTouchId = mPointerGesture.activeTouchId = -1; } } // Determine whether we are in quiet time. bool isQuietTime = false; if (activeTouchId < 0) { mPointerGesture.resetQuietTime(); } else { isQuietTime = when < mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval; if (!isQuietTime) { if ((mPointerGesture.lastGestureMode == PointerGesture::PRESS || mPointerGesture.lastGestureMode == PointerGesture::SWIPE || mPointerGesture.lastGestureMode == PointerGesture::FREEFORM) && currentFingerCount < 2) { // Enter quiet time when exiting swipe or freeform state. // This is to prevent accidentally entering the hover state and flinging the // pointer when finishing a swipe and there is still one pointer left onscreen. isQuietTime = true; } else if (mPointerGesture.lastGestureMode == PointerGesture::BUTTON_CLICK_OR_DRAG && currentFingerCount >= 2 && !isPointerDown(mCurrentRawState.buttonState)) { // Enter quiet time when releasing the button and there are still two or more // fingers down. This may indicate that one finger was used to press the button // but it has not gone up yet. isQuietTime = true; } if (isQuietTime) { mPointerGesture.quietTime = when; } } } // Switch states based on button and pointer state. if (isQuietTime) { // Case 1: Quiet time. (QUIET) #if DEBUG_GESTURES ALOGD("Gestures: QUIET for next %0.3fms", (mPointerGesture.quietTime + mConfig.pointerGestureQuietInterval - when) * 0.000001f); #endif if (mPointerGesture.lastGestureMode != PointerGesture::QUIET) { *outFinishPreviousGesture = true; } mPointerGesture.activeGestureId = -1; mPointerGesture.currentGestureMode = PointerGesture::QUIET; mPointerGesture.currentGestureIdBits.clear(); mPointerVelocityControl.reset(); } else if (isPointerDown(mCurrentRawState.buttonState)) { // Case 2: Button is pressed. (BUTTON_CLICK_OR_DRAG) // The pointer follows the active touch point. // Emit DOWN, MOVE, UP events at the pointer location. // // Only the active touch matters; other fingers are ignored. This policy helps // to handle the case where the user places a second finger on the touch pad // to apply the necessary force to depress an integrated button below the surface. // We don't want the second finger to be delivered to applications. // // For this to work well, we need to make sure to track the pointer that is really // active. If the user first puts one finger down to click then adds another // finger to drag then the active pointer should switch to the finger that is // being dragged. #if DEBUG_GESTURES ALOGD("Gestures: BUTTON_CLICK_OR_DRAG activeTouchId=%d, " "currentFingerCount=%d", activeTouchId, currentFingerCount); #endif // Reset state when just starting. if (mPointerGesture.lastGestureMode != PointerGesture::BUTTON_CLICK_OR_DRAG) { *outFinishPreviousGesture = true; mPointerGesture.activeGestureId = 0; } // Switch pointers if needed. // Find the fastest pointer and follow it. if (activeTouchId >= 0 && currentFingerCount > 1) { int32_t bestId = -1; float bestSpeed = mConfig.pointerGestureDragMinSwitchSpeed; for (BitSet32 idBits(mCurrentCookedState.fingerIdBits); !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); float vx, vy; if (mPointerGesture.velocityTracker.getVelocity(id, &vx, &vy)) { float speed = hypotf(vx, vy); if (speed > bestSpeed) { bestId = id; bestSpeed = speed; } } } if (bestId >= 0 && bestId != activeTouchId) { mPointerGesture.activeTouchId = activeTouchId = bestId; activeTouchChanged = true; #if DEBUG_GESTURES ALOGD("Gestures: BUTTON_CLICK_OR_DRAG switched pointers, " "bestId=%d, bestSpeed=%0.3f", bestId, bestSpeed); #endif } } float deltaX = 0, deltaY = 0; if (activeTouchId >= 0 && mLastCookedState.fingerIdBits.hasBit(activeTouchId)) { const RawPointerData::Pointer& currentPointer = mCurrentRawState.rawPointerData.pointerForId(activeTouchId); const RawPointerData::Pointer& lastPointer = mLastRawState.rawPointerData.pointerForId(activeTouchId); deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale; deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale; rotateDelta(mSurfaceOrientation, &deltaX, &deltaY); mPointerVelocityControl.move(when, &deltaX, &deltaY); // Move the pointer using a relative motion. // When using spots, the click will occur at the position of the anchor // spot and all other spots will move there. mPointerController->move(deltaX, deltaY); } else { mPointerVelocityControl.reset(); } float x, y; mPointerController->getPosition(&x, &y); mPointerGesture.currentGestureMode = PointerGesture::BUTTON_CLICK_OR_DRAG; mPointerGesture.currentGestureIdBits.clear(); mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId); mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0; mPointerGesture.currentGestureProperties[0].clear(); mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId; mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; mPointerGesture.currentGestureCoords[0].clear(); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, deltaX); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY); } else if (currentFingerCount == 0) { // Case 3. No fingers down and button is not pressed. (NEUTRAL) if (mPointerGesture.lastGestureMode != PointerGesture::NEUTRAL) { *outFinishPreviousGesture = true; } // Watch for taps coming out of HOVER or TAP_DRAG mode. // Checking for taps after TAP_DRAG allows us to detect double-taps. bool tapped = false; if ((mPointerGesture.lastGestureMode == PointerGesture::HOVER || mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) && lastFingerCount == 1) { if (when <= mPointerGesture.tapDownTime + mConfig.pointerGestureTapInterval) { float x, y; mPointerController->getPosition(&x, &y); if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) { #if DEBUG_GESTURES ALOGD("Gestures: TAP"); #endif mPointerGesture.tapUpTime = when; getContext()->requestTimeoutAtTime(when + mConfig.pointerGestureTapDragInterval); mPointerGesture.activeGestureId = 0; mPointerGesture.currentGestureMode = PointerGesture::TAP; mPointerGesture.currentGestureIdBits.clear(); mPointerGesture.currentGestureIdBits.markBit( mPointerGesture.activeGestureId); mPointerGesture.currentGestureIdToIndex[ mPointerGesture.activeGestureId] = 0; mPointerGesture.currentGestureProperties[0].clear(); mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId; mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; mPointerGesture.currentGestureCoords[0].clear(); mPointerGesture.currentGestureCoords[0].setAxisValue( AMOTION_EVENT_AXIS_X, mPointerGesture.tapX); mPointerGesture.currentGestureCoords[0].setAxisValue( AMOTION_EVENT_AXIS_Y, mPointerGesture.tapY); mPointerGesture.currentGestureCoords[0].setAxisValue( AMOTION_EVENT_AXIS_PRESSURE, 1.0f); tapped = true; } else { #if DEBUG_GESTURES ALOGD("Gestures: Not a TAP, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX, y - mPointerGesture.tapY); #endif } } else { #if DEBUG_GESTURES if (mPointerGesture.tapDownTime != LLONG_MIN) { ALOGD("Gestures: Not a TAP, %0.3fms since down", (when - mPointerGesture.tapDownTime) * 0.000001f); } else { ALOGD("Gestures: Not a TAP, incompatible mode transitions"); } #endif } } mPointerVelocityControl.reset(); if (!tapped) { #if DEBUG_GESTURES ALOGD("Gestures: NEUTRAL"); #endif mPointerGesture.activeGestureId = -1; mPointerGesture.currentGestureMode = PointerGesture::NEUTRAL; mPointerGesture.currentGestureIdBits.clear(); } } else if (currentFingerCount == 1) { // Case 4. Exactly one finger down, button is not pressed. (HOVER or TAP_DRAG) // The pointer follows the active touch point. // When in HOVER, emit HOVER_MOVE events at the pointer location. // When in TAP_DRAG, emit MOVE events at the pointer location. ALOG_ASSERT(activeTouchId >= 0); mPointerGesture.currentGestureMode = PointerGesture::HOVER; if (mPointerGesture.lastGestureMode == PointerGesture::TAP) { if (when <= mPointerGesture.tapUpTime + mConfig.pointerGestureTapDragInterval) { float x, y; mPointerController->getPosition(&x, &y); if (fabs(x - mPointerGesture.tapX) <= mConfig.pointerGestureTapSlop && fabs(y - mPointerGesture.tapY) <= mConfig.pointerGestureTapSlop) { mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG; } else { #if DEBUG_GESTURES ALOGD("Gestures: Not a TAP_DRAG, deltaX=%f, deltaY=%f", x - mPointerGesture.tapX, y - mPointerGesture.tapY); #endif } } else { #if DEBUG_GESTURES ALOGD("Gestures: Not a TAP_DRAG, %0.3fms time since up", (when - mPointerGesture.tapUpTime) * 0.000001f); #endif } } else if (mPointerGesture.lastGestureMode == PointerGesture::TAP_DRAG) { mPointerGesture.currentGestureMode = PointerGesture::TAP_DRAG; } float deltaX = 0, deltaY = 0; if (mLastCookedState.fingerIdBits.hasBit(activeTouchId)) { const RawPointerData::Pointer& currentPointer = mCurrentRawState.rawPointerData.pointerForId(activeTouchId); const RawPointerData::Pointer& lastPointer = mLastRawState.rawPointerData.pointerForId(activeTouchId); deltaX = (currentPointer.x - lastPointer.x) * mPointerXMovementScale; deltaY = (currentPointer.y - lastPointer.y) * mPointerYMovementScale; rotateDelta(mSurfaceOrientation, &deltaX, &deltaY); mPointerVelocityControl.move(when, &deltaX, &deltaY); // Move the pointer using a relative motion. // When using spots, the hover or drag will occur at the position of the anchor spot. mPointerController->move(deltaX, deltaY); } else { mPointerVelocityControl.reset(); } bool down; if (mPointerGesture.currentGestureMode == PointerGesture::TAP_DRAG) { #if DEBUG_GESTURES ALOGD("Gestures: TAP_DRAG"); #endif down = true; } else { #if DEBUG_GESTURES ALOGD("Gestures: HOVER"); #endif if (mPointerGesture.lastGestureMode != PointerGesture::HOVER) { *outFinishPreviousGesture = true; } mPointerGesture.activeGestureId = 0; down = false; } float x, y; mPointerController->getPosition(&x, &y); mPointerGesture.currentGestureIdBits.clear(); mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId); mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0; mPointerGesture.currentGestureProperties[0].clear(); mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId; mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; mPointerGesture.currentGestureCoords[0].clear(); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, x); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, y); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, down ? 1.0f : 0.0f); mPointerGesture.currentGestureCoords[0].setAxisValue( AMOTION_EVENT_AXIS_RELATIVE_X, deltaX); mPointerGesture.currentGestureCoords[0].setAxisValue( AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY); if (lastFingerCount == 0 && currentFingerCount != 0) { mPointerGesture.resetTap(); mPointerGesture.tapDownTime = when; mPointerGesture.tapX = x; mPointerGesture.tapY = y; } } else { // Case 5. At least two fingers down, button is not pressed. (PRESS, SWIPE or FREEFORM) // We need to provide feedback for each finger that goes down so we cannot wait // for the fingers to move before deciding what to do. // // The ambiguous case is deciding what to do when there are two fingers down but they // have not moved enough to determine whether they are part of a drag or part of a // freeform gesture, or just a press or long-press at the pointer location. // // When there are two fingers we start with the PRESS hypothesis and we generate a // down at the pointer location. // // When the two fingers move enough or when additional fingers are added, we make // a decision to transition into SWIPE or FREEFORM mode accordingly. ALOG_ASSERT(activeTouchId >= 0); bool settled = when >= mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval; if (mPointerGesture.lastGestureMode != PointerGesture::PRESS && mPointerGesture.lastGestureMode != PointerGesture::SWIPE && mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) { *outFinishPreviousGesture = true; } else if (!settled && currentFingerCount > lastFingerCount) { // Additional pointers have gone down but not yet settled. // Reset the gesture. #if DEBUG_GESTURES ALOGD("Gestures: Resetting gesture since additional pointers went down for MULTITOUCH, " "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval - when) * 0.000001f); #endif *outCancelPreviousGesture = true; } else { // Continue previous gesture. mPointerGesture.currentGestureMode = mPointerGesture.lastGestureMode; } if (*outFinishPreviousGesture || *outCancelPreviousGesture) { mPointerGesture.currentGestureMode = PointerGesture::PRESS; mPointerGesture.activeGestureId = 0; mPointerGesture.referenceIdBits.clear(); mPointerVelocityControl.reset(); // Use the centroid and pointer location as the reference points for the gesture. #if DEBUG_GESTURES ALOGD("Gestures: Using centroid as reference for MULTITOUCH, " "settle time remaining %0.3fms", (mPointerGesture.firstTouchTime + mConfig.pointerGestureMultitouchSettleInterval - when) * 0.000001f); #endif mCurrentRawState.rawPointerData.getCentroidOfTouchingPointers( &mPointerGesture.referenceTouchX, &mPointerGesture.referenceTouchY); mPointerController->getPosition(&mPointerGesture.referenceGestureX, &mPointerGesture.referenceGestureY); } // Clear the reference deltas for fingers not yet included in the reference calculation. for (BitSet32 idBits(mCurrentCookedState.fingerIdBits.value & ~mPointerGesture.referenceIdBits.value); !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); mPointerGesture.referenceDeltas[id].dx = 0; mPointerGesture.referenceDeltas[id].dy = 0; } mPointerGesture.referenceIdBits = mCurrentCookedState.fingerIdBits; // Add delta for all fingers and calculate a common movement delta. float commonDeltaX = 0, commonDeltaY = 0; BitSet32 commonIdBits(mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value); for (BitSet32 idBits(commonIdBits); !idBits.isEmpty(); ) { bool first = (idBits == commonIdBits); uint32_t id = idBits.clearFirstMarkedBit(); const RawPointerData::Pointer& cpd = mCurrentRawState.rawPointerData.pointerForId(id); const RawPointerData::Pointer& lpd = mLastRawState.rawPointerData.pointerForId(id); PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id]; delta.dx += cpd.x - lpd.x; delta.dy += cpd.y - lpd.y; if (first) { commonDeltaX = delta.dx; commonDeltaY = delta.dy; } else { commonDeltaX = calculateCommonVector(commonDeltaX, delta.dx); commonDeltaY = calculateCommonVector(commonDeltaY, delta.dy); } } // Consider transitions from PRESS to SWIPE or MULTITOUCH. if (mPointerGesture.currentGestureMode == PointerGesture::PRESS) { float dist[MAX_POINTER_ID + 1]; int32_t distOverThreshold = 0; for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id]; dist[id] = hypotf(delta.dx * mPointerXZoomScale, delta.dy * mPointerYZoomScale); if (dist[id] > mConfig.pointerGestureMultitouchMinDistance) { distOverThreshold += 1; } } // Only transition when at least two pointers have moved further than // the minimum distance threshold. if (distOverThreshold >= 2) { if (currentFingerCount > 2) { // There are more than two pointers, switch to FREEFORM. #if DEBUG_GESTURES ALOGD("Gestures: PRESS transitioned to FREEFORM, number of pointers %d > 2", currentFingerCount); #endif *outCancelPreviousGesture = true; mPointerGesture.currentGestureMode = PointerGesture::FREEFORM; } else { // There are exactly two pointers. BitSet32 idBits(mCurrentCookedState.fingerIdBits); uint32_t id1 = idBits.clearFirstMarkedBit(); uint32_t id2 = idBits.firstMarkedBit(); const RawPointerData::Pointer& p1 = mCurrentRawState.rawPointerData.pointerForId(id1); const RawPointerData::Pointer& p2 = mCurrentRawState.rawPointerData.pointerForId(id2); float mutualDistance = distance(p1.x, p1.y, p2.x, p2.y); if (mutualDistance > mPointerGestureMaxSwipeWidth) { // There are two pointers but they are too far apart for a SWIPE, // switch to FREEFORM. #if DEBUG_GESTURES ALOGD("Gestures: PRESS transitioned to FREEFORM, distance %0.3f > %0.3f", mutualDistance, mPointerGestureMaxSwipeWidth); #endif *outCancelPreviousGesture = true; mPointerGesture.currentGestureMode = PointerGesture::FREEFORM; } else { // There are two pointers. Wait for both pointers to start moving // before deciding whether this is a SWIPE or FREEFORM gesture. float dist1 = dist[id1]; float dist2 = dist[id2]; if (dist1 >= mConfig.pointerGestureMultitouchMinDistance && dist2 >= mConfig.pointerGestureMultitouchMinDistance) { // Calculate the dot product of the displacement vectors. // When the vectors are oriented in approximately the same direction, // the angle betweeen them is near zero and the cosine of the angle // approches 1.0. Recall that dot(v1, v2) = cos(angle) * mag(v1) * mag(v2). PointerGesture::Delta& delta1 = mPointerGesture.referenceDeltas[id1]; PointerGesture::Delta& delta2 = mPointerGesture.referenceDeltas[id2]; float dx1 = delta1.dx * mPointerXZoomScale; float dy1 = delta1.dy * mPointerYZoomScale; float dx2 = delta2.dx * mPointerXZoomScale; float dy2 = delta2.dy * mPointerYZoomScale; float dot = dx1 * dx2 + dy1 * dy2; float cosine = dot / (dist1 * dist2); // denominator always > 0 if (cosine >= mConfig.pointerGestureSwipeTransitionAngleCosine) { // Pointers are moving in the same direction. Switch to SWIPE. #if DEBUG_GESTURES ALOGD("Gestures: PRESS transitioned to SWIPE, " "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, " "cosine %0.3f >= %0.3f", dist1, mConfig.pointerGestureMultitouchMinDistance, dist2, mConfig.pointerGestureMultitouchMinDistance, cosine, mConfig.pointerGestureSwipeTransitionAngleCosine); #endif mPointerGesture.currentGestureMode = PointerGesture::SWIPE; } else { // Pointers are moving in different directions. Switch to FREEFORM. #if DEBUG_GESTURES ALOGD("Gestures: PRESS transitioned to FREEFORM, " "dist1 %0.3f >= %0.3f, dist2 %0.3f >= %0.3f, " "cosine %0.3f < %0.3f", dist1, mConfig.pointerGestureMultitouchMinDistance, dist2, mConfig.pointerGestureMultitouchMinDistance, cosine, mConfig.pointerGestureSwipeTransitionAngleCosine); #endif *outCancelPreviousGesture = true; mPointerGesture.currentGestureMode = PointerGesture::FREEFORM; } } } } } } else if (mPointerGesture.currentGestureMode == PointerGesture::SWIPE) { // Switch from SWIPE to FREEFORM if additional pointers go down. // Cancel previous gesture. if (currentFingerCount > 2) { #if DEBUG_GESTURES ALOGD("Gestures: SWIPE transitioned to FREEFORM, number of pointers %d > 2", currentFingerCount); #endif *outCancelPreviousGesture = true; mPointerGesture.currentGestureMode = PointerGesture::FREEFORM; } } // Move the reference points based on the overall group motion of the fingers // except in PRESS mode while waiting for a transition to occur. if (mPointerGesture.currentGestureMode != PointerGesture::PRESS && (commonDeltaX || commonDeltaY)) { for (BitSet32 idBits(mPointerGesture.referenceIdBits); !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); PointerGesture::Delta& delta = mPointerGesture.referenceDeltas[id]; delta.dx = 0; delta.dy = 0; } mPointerGesture.referenceTouchX += commonDeltaX; mPointerGesture.referenceTouchY += commonDeltaY; commonDeltaX *= mPointerXMovementScale; commonDeltaY *= mPointerYMovementScale; rotateDelta(mSurfaceOrientation, &commonDeltaX, &commonDeltaY); mPointerVelocityControl.move(when, &commonDeltaX, &commonDeltaY); mPointerGesture.referenceGestureX += commonDeltaX; mPointerGesture.referenceGestureY += commonDeltaY; } // Report gestures. if (mPointerGesture.currentGestureMode == PointerGesture::PRESS || mPointerGesture.currentGestureMode == PointerGesture::SWIPE) { // PRESS or SWIPE mode. #if DEBUG_GESTURES ALOGD("Gestures: PRESS or SWIPE activeTouchId=%d," "activeGestureId=%d, currentTouchPointerCount=%d", activeTouchId, mPointerGesture.activeGestureId, currentFingerCount); #endif ALOG_ASSERT(mPointerGesture.activeGestureId >= 0); mPointerGesture.currentGestureIdBits.clear(); mPointerGesture.currentGestureIdBits.markBit(mPointerGesture.activeGestureId); mPointerGesture.currentGestureIdToIndex[mPointerGesture.activeGestureId] = 0; mPointerGesture.currentGestureProperties[0].clear(); mPointerGesture.currentGestureProperties[0].id = mPointerGesture.activeGestureId; mPointerGesture.currentGestureProperties[0].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; mPointerGesture.currentGestureCoords[0].clear(); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, commonDeltaX); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, commonDeltaY); mPointerGesture.currentGestureCoords[0].setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, 1.0f); } else if (mPointerGesture.currentGestureMode == PointerGesture::FREEFORM) { // FREEFORM mode. #if DEBUG_GESTURES ALOGD("Gestures: FREEFORM activeTouchId=%d," "activeGestureId=%d, currentTouchPointerCount=%d", activeTouchId, mPointerGesture.activeGestureId, currentFingerCount); #endif ALOG_ASSERT(mPointerGesture.activeGestureId >= 0); mPointerGesture.currentGestureIdBits.clear(); BitSet32 mappedTouchIdBits; BitSet32 usedGestureIdBits; if (mPointerGesture.lastGestureMode != PointerGesture::FREEFORM) { // Initially, assign the active gesture id to the active touch point // if there is one. No other touch id bits are mapped yet. if (!*outCancelPreviousGesture) { mappedTouchIdBits.markBit(activeTouchId); usedGestureIdBits.markBit(mPointerGesture.activeGestureId); mPointerGesture.freeformTouchToGestureIdMap[activeTouchId] = mPointerGesture.activeGestureId; } else { mPointerGesture.activeGestureId = -1; } } else { // Otherwise, assume we mapped all touches from the previous frame. // Reuse all mappings that are still applicable. mappedTouchIdBits.value = mLastCookedState.fingerIdBits.value & mCurrentCookedState.fingerIdBits.value; usedGestureIdBits = mPointerGesture.lastGestureIdBits; // Check whether we need to choose a new active gesture id because the // current went went up. for (BitSet32 upTouchIdBits(mLastCookedState.fingerIdBits.value & ~mCurrentCookedState.fingerIdBits.value); !upTouchIdBits.isEmpty(); ) { uint32_t upTouchId = upTouchIdBits.clearFirstMarkedBit(); uint32_t upGestureId = mPointerGesture.freeformTouchToGestureIdMap[upTouchId]; if (upGestureId == uint32_t(mPointerGesture.activeGestureId)) { mPointerGesture.activeGestureId = -1; break; } } } #if DEBUG_GESTURES ALOGD("Gestures: FREEFORM follow up " "mappedTouchIdBits=0x%08x, usedGestureIdBits=0x%08x, " "activeGestureId=%d", mappedTouchIdBits.value, usedGestureIdBits.value, mPointerGesture.activeGestureId); #endif BitSet32 idBits(mCurrentCookedState.fingerIdBits); for (uint32_t i = 0; i < currentFingerCount; i++) { uint32_t touchId = idBits.clearFirstMarkedBit(); uint32_t gestureId; if (!mappedTouchIdBits.hasBit(touchId)) { gestureId = usedGestureIdBits.markFirstUnmarkedBit(); mPointerGesture.freeformTouchToGestureIdMap[touchId] = gestureId; #if DEBUG_GESTURES ALOGD("Gestures: FREEFORM " "new mapping for touch id %d -> gesture id %d", touchId, gestureId); #endif } else { gestureId = mPointerGesture.freeformTouchToGestureIdMap[touchId]; #if DEBUG_GESTURES ALOGD("Gestures: FREEFORM " "existing mapping for touch id %d -> gesture id %d", touchId, gestureId); #endif } mPointerGesture.currentGestureIdBits.markBit(gestureId); mPointerGesture.currentGestureIdToIndex[gestureId] = i; const RawPointerData::Pointer& pointer = mCurrentRawState.rawPointerData.pointerForId(touchId); float deltaX = (pointer.x - mPointerGesture.referenceTouchX) * mPointerXZoomScale; float deltaY = (pointer.y - mPointerGesture.referenceTouchY) * mPointerYZoomScale; rotateDelta(mSurfaceOrientation, &deltaX, &deltaY); mPointerGesture.currentGestureProperties[i].clear(); mPointerGesture.currentGestureProperties[i].id = gestureId; mPointerGesture.currentGestureProperties[i].toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; mPointerGesture.currentGestureCoords[i].clear(); mPointerGesture.currentGestureCoords[i].setAxisValue( AMOTION_EVENT_AXIS_X, mPointerGesture.referenceGestureX + deltaX); mPointerGesture.currentGestureCoords[i].setAxisValue( AMOTION_EVENT_AXIS_Y, mPointerGesture.referenceGestureY + deltaY); mPointerGesture.currentGestureCoords[i].setAxisValue( AMOTION_EVENT_AXIS_PRESSURE, 1.0f); mPointerGesture.currentGestureCoords[i].setAxisValue( AMOTION_EVENT_AXIS_RELATIVE_X, deltaX); mPointerGesture.currentGestureCoords[i].setAxisValue( AMOTION_EVENT_AXIS_RELATIVE_Y, deltaY); } if (mPointerGesture.activeGestureId < 0) { mPointerGesture.activeGestureId = mPointerGesture.currentGestureIdBits.firstMarkedBit(); #if DEBUG_GESTURES ALOGD("Gestures: FREEFORM new " "activeGestureId=%d", mPointerGesture.activeGestureId); #endif } } } mPointerController->setButtonState(mCurrentRawState.buttonState); #if DEBUG_GESTURES ALOGD("Gestures: finishPreviousGesture=%s, cancelPreviousGesture=%s, " "currentGestureMode=%d, currentGestureIdBits=0x%08x, " "lastGestureMode=%d, lastGestureIdBits=0x%08x", toString(*outFinishPreviousGesture), toString(*outCancelPreviousGesture), mPointerGesture.currentGestureMode, mPointerGesture.currentGestureIdBits.value, mPointerGesture.lastGestureMode, mPointerGesture.lastGestureIdBits.value); for (BitSet32 idBits = mPointerGesture.currentGestureIdBits; !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); uint32_t index = mPointerGesture.currentGestureIdToIndex[id]; const PointerProperties& properties = mPointerGesture.currentGestureProperties[index]; const PointerCoords& coords = mPointerGesture.currentGestureCoords[index]; ALOGD(" currentGesture[%d]: index=%d, toolType=%d, " "x=%0.3f, y=%0.3f, pressure=%0.3f", id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X), coords.getAxisValue(AMOTION_EVENT_AXIS_Y), coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)); } for (BitSet32 idBits = mPointerGesture.lastGestureIdBits; !idBits.isEmpty(); ) { uint32_t id = idBits.clearFirstMarkedBit(); uint32_t index = mPointerGesture.lastGestureIdToIndex[id]; const PointerProperties& properties = mPointerGesture.lastGestureProperties[index]; const PointerCoords& coords = mPointerGesture.lastGestureCoords[index]; ALOGD(" lastGesture[%d]: index=%d, toolType=%d, " "x=%0.3f, y=%0.3f, pressure=%0.3f", id, index, properties.toolType, coords.getAxisValue(AMOTION_EVENT_AXIS_X), coords.getAxisValue(AMOTION_EVENT_AXIS_Y), coords.getAxisValue(AMOTION_EVENT_AXIS_PRESSURE)); } #endif return true; } void TouchInputMapper::dispatchPointerStylus(nsecs_t when, uint32_t policyFlags) { mPointerSimple.currentCoords.clear(); mPointerSimple.currentProperties.clear(); bool down, hovering; if (!mCurrentCookedState.stylusIdBits.isEmpty()) { uint32_t id = mCurrentCookedState.stylusIdBits.firstMarkedBit(); uint32_t index = mCurrentCookedState.cookedPointerData.idToIndex[id]; float x = mCurrentCookedState.cookedPointerData.pointerCoords[index].getX(); float y = mCurrentCookedState.cookedPointerData.pointerCoords[index].getY(); mPointerController->setPosition(x, y); hovering = mCurrentCookedState.cookedPointerData.hoveringIdBits.hasBit(id); down = !hovering; mPointerController->getPosition(&x, &y); mPointerSimple.currentCoords.copyFrom( mCurrentCookedState.cookedPointerData.pointerCoords[index]); mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x); mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); mPointerSimple.currentProperties.id = 0; mPointerSimple.currentProperties.toolType = mCurrentCookedState.cookedPointerData.pointerProperties[index].toolType; } else { down = false; hovering = false; } dispatchPointerSimple(when, policyFlags, down, hovering); } void TouchInputMapper::abortPointerStylus(nsecs_t when, uint32_t policyFlags) { abortPointerSimple(when, policyFlags); } void TouchInputMapper::dispatchPointerMouse(nsecs_t when, uint32_t policyFlags) { mPointerSimple.currentCoords.clear(); mPointerSimple.currentProperties.clear(); bool down, hovering; if (!mCurrentCookedState.mouseIdBits.isEmpty()) { uint32_t id = mCurrentCookedState.mouseIdBits.firstMarkedBit(); uint32_t currentIndex = mCurrentRawState.rawPointerData.idToIndex[id]; float deltaX = 0, deltaY = 0; if (mLastCookedState.mouseIdBits.hasBit(id)) { uint32_t lastIndex = mCurrentRawState.rawPointerData.idToIndex[id]; deltaX = (mCurrentRawState.rawPointerData.pointers[currentIndex].x - mLastRawState.rawPointerData.pointers[lastIndex].x) * mPointerXMovementScale; deltaY = (mCurrentRawState.rawPointerData.pointers[currentIndex].y - mLastRawState.rawPointerData.pointers[lastIndex].y) * mPointerYMovementScale; rotateDelta(mSurfaceOrientation, &deltaX, &deltaY); mPointerVelocityControl.move(when, &deltaX, &deltaY); mPointerController->move(deltaX, deltaY); } else { mPointerVelocityControl.reset(); } down = isPointerDown(mCurrentRawState.buttonState); hovering = !down; float x, y; mPointerController->getPosition(&x, &y); mPointerSimple.currentCoords.copyFrom( mCurrentCookedState.cookedPointerData.pointerCoords[currentIndex]); mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_X, x); mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_Y, y); mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_PRESSURE, hovering ? 0.0f : 1.0f); mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_X, x); mPointerSimple.currentCoords.setAxisValue(AMOTION_EVENT_AXIS_RELATIVE_Y, y); mPointerSimple.currentProperties.id = 0; mPointerSimple.currentProperties.toolType = mCurrentCookedState.cookedPointerData.pointerProperties[currentIndex].toolType; } else { mPointerVelocityControl.reset(); down = false; hovering = false; } dispatchPointerSimple(when, policyFlags, down, hovering); } void TouchInputMapper::abortPointerMouse(nsecs_t when, uint32_t policyFlags) { abortPointerSimple(when, policyFlags); mPointerVelocityControl.reset(); } void TouchInputMapper::dispatchPointerSimple(nsecs_t when, uint32_t policyFlags, bool down, bool hovering) { int32_t metaState = getContext()->getGlobalMetaState(); if (mPointerController != NULL) { if (down || hovering) { mPointerController->setPresentation(PointerControllerInterface::PRESENTATION_POINTER); mPointerController->clearSpots(); mPointerController->setButtonState(mCurrentRawState.buttonState); mPointerController->unfade(PointerControllerInterface::TRANSITION_IMMEDIATE); } else if (!down && !hovering && (mPointerSimple.down || mPointerSimple.hovering)) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); } } if (mPointerSimple.down && !down) { mPointerSimple.down = false; // Send up. NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_UP, 0, 0, metaState, mLastRawState.buttonState, 0, mViewport.displayId, 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); getListener()->notifyMotion(&args); } if (mPointerSimple.hovering && !hovering) { mPointerSimple.hovering = false; // Send hover exit. NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_HOVER_EXIT, 0, 0, metaState, mLastRawState.buttonState, 0, mViewport.displayId, 1, &mPointerSimple.lastProperties, &mPointerSimple.lastCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); getListener()->notifyMotion(&args); } if (down) { if (!mPointerSimple.down) { mPointerSimple.down = true; mPointerSimple.downTime = when; // Send down. NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_DOWN, 0, 0, metaState, mCurrentRawState.buttonState, 0, mViewport.displayId, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); getListener()->notifyMotion(&args); } // Send move. NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0, mViewport.displayId, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); getListener()->notifyMotion(&args); } if (hovering) { if (!mPointerSimple.hovering) { mPointerSimple.hovering = true; // Send hover enter. NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_HOVER_ENTER, 0, 0, metaState, mCurrentRawState.buttonState, 0, mViewport.displayId, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); getListener()->notifyMotion(&args); } // Send hover move. NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_HOVER_MOVE, 0, 0, metaState, mCurrentRawState.buttonState, 0, mViewport.displayId, 1, &mPointerSimple.currentProperties, &mPointerSimple.currentCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); getListener()->notifyMotion(&args); } if (mCurrentRawState.rawVScroll || mCurrentRawState.rawHScroll) { float vscroll = mCurrentRawState.rawVScroll; float hscroll = mCurrentRawState.rawHScroll; mWheelYVelocityControl.move(when, NULL, &vscroll); mWheelXVelocityControl.move(when, &hscroll, NULL); // Send scroll. PointerCoords pointerCoords; pointerCoords.copyFrom(mPointerSimple.currentCoords); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_VSCROLL, vscroll); pointerCoords.setAxisValue(AMOTION_EVENT_AXIS_HSCROLL, hscroll); NotifyMotionArgs args(when, getDeviceId(), mSource, policyFlags, AMOTION_EVENT_ACTION_SCROLL, 0, 0, metaState, mCurrentRawState.buttonState, 0, mViewport.displayId, 1, &mPointerSimple.currentProperties, &pointerCoords, mOrientedXPrecision, mOrientedYPrecision, mPointerSimple.downTime); getListener()->notifyMotion(&args); } // Save state. if (down || hovering) { mPointerSimple.lastCoords.copyFrom(mPointerSimple.currentCoords); mPointerSimple.lastProperties.copyFrom(mPointerSimple.currentProperties); } else { mPointerSimple.reset(); } } void TouchInputMapper::abortPointerSimple(nsecs_t when, uint32_t policyFlags) { mPointerSimple.currentCoords.clear(); mPointerSimple.currentProperties.clear(); dispatchPointerSimple(when, policyFlags, false, false); } void TouchInputMapper::dispatchMotion(nsecs_t when, uint32_t policyFlags, uint32_t source, int32_t action, int32_t actionButton, int32_t flags, int32_t metaState, int32_t buttonState, int32_t edgeFlags, const PointerProperties* properties, const PointerCoords* coords, const uint32_t* idToIndex, BitSet32 idBits, int32_t changedId, float xPrecision, float yPrecision, nsecs_t downTime) { PointerCoords pointerCoords[MAX_POINTERS]; PointerProperties pointerProperties[MAX_POINTERS]; uint32_t pointerCount = 0; while (!idBits.isEmpty()) { uint32_t id = idBits.clearFirstMarkedBit(); uint32_t index = idToIndex[id]; pointerProperties[pointerCount].copyFrom(properties[index]); pointerCoords[pointerCount].copyFrom(coords[index]); if (changedId >= 0 && id == uint32_t(changedId)) { action |= pointerCount << AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT; } pointerCount += 1; } ALOG_ASSERT(pointerCount != 0); if (changedId >= 0 && pointerCount == 1) { // Replace initial down and final up action. // We can compare the action without masking off the changed pointer index // because we know the index is 0. if (action == AMOTION_EVENT_ACTION_POINTER_DOWN) { action = AMOTION_EVENT_ACTION_DOWN; } else if (action == AMOTION_EVENT_ACTION_POINTER_UP) { action = AMOTION_EVENT_ACTION_UP; } else { // Can't happen. ALOG_ASSERT(false); } } NotifyMotionArgs args(when, getDeviceId(), source, policyFlags, action, actionButton, flags, metaState, buttonState, edgeFlags, mViewport.displayId, pointerCount, pointerProperties, pointerCoords, xPrecision, yPrecision, downTime); ALOGD_READER("notifyMotion call dispatcher"); getListener()->notifyMotion(&args); /** M: MET inputreader milestone. @{ */ { char* buff = NULL; buff = (char*)malloc(4096); if (buff) { sprintf(buff, "MET_notifyMotion: %llx,%d,%x,%x", args.eventTime, args.action, (int)args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_X), (int)args.pointerCoords[0].getAxisValue(AMOTION_EVENT_AXIS_Y)); ScopedTrace _l(ATRACE_TAG_INPUT, buff); free(buff); } } /** @} */ /// M: input systrace @{ ALOGD_READER("notifyMotion - eventTime=%lld, deviceId=%d, source=0x%x, policyFlags=0x%x, " "action=0x%x, flags=0x%x, metaState=0x%x, buttonState=0x%x, edgeFlags=0x%x, " "xPrecision=%f, yPrecision=%f, downTime=%lld", args.eventTime, args.deviceId, args.source, args.policyFlags, args.action, args.flags, args.metaState, args.buttonState, args.edgeFlags, args.xPrecision, args.yPrecision, args.downTime); if(gInputLogReader){ for (uint32_t i = 0; i < args.pointerCount; i++) { ALOGD_READER("notifyMotion - Pointer %d: id=%d, toolType=%d, " "x=%f, y=%f, pressure=%f, size=%f, " "touchMajor=%f, touchMinor=%f, toolMajor=%f, toolMinor=%f, " "orientation=%f", i, args.pointerProperties[i].id, args.pointerProperties[i].toolType, args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_X), args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_Y), args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_PRESSURE), args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_SIZE), args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MAJOR), args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOUCH_MINOR), args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MAJOR), args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_TOOL_MINOR), args.pointerCoords[i].getAxisValue(AMOTION_EVENT_AXIS_ORIENTATION)); } } /// @} } bool TouchInputMapper::updateMovedPointers(const PointerProperties* inProperties, const PointerCoords* inCoords, const uint32_t* inIdToIndex, PointerProperties* outProperties, PointerCoords* outCoords, const uint32_t* outIdToIndex, BitSet32 idBits) const { bool changed = false; while (!idBits.isEmpty()) { uint32_t id = idBits.clearFirstMarkedBit(); uint32_t inIndex = inIdToIndex[id]; uint32_t outIndex = outIdToIndex[id]; const PointerProperties& curInProperties = inProperties[inIndex]; const PointerCoords& curInCoords = inCoords[inIndex]; PointerProperties& curOutProperties = outProperties[outIndex]; PointerCoords& curOutCoords = outCoords[outIndex]; if (curInProperties != curOutProperties) { curOutProperties.copyFrom(curInProperties); changed = true; } if (curInCoords != curOutCoords) { curOutCoords.copyFrom(curInCoords); changed = true; } } return changed; } void TouchInputMapper::fadePointer() { if (mPointerController != NULL) { mPointerController->fade(PointerControllerInterface::TRANSITION_GRADUAL); } } void TouchInputMapper::cancelTouch(nsecs_t when) { abortPointerUsage(when, 0 /*policyFlags*/); abortTouches(when, 0 /* policyFlags*/); } bool TouchInputMapper::isPointInsideSurface(int32_t x, int32_t y) { return x >= mRawPointerAxes.x.minValue && x <= mRawPointerAxes.x.maxValue && y >= mRawPointerAxes.y.minValue && y <= mRawPointerAxes.y.maxValue; } const TouchInputMapper::VirtualKey* TouchInputMapper::findVirtualKeyHit( int32_t x, int32_t y) { size_t numVirtualKeys = mVirtualKeys.size(); for (size_t i = 0; i < numVirtualKeys; i++) { const VirtualKey& virtualKey = mVirtualKeys[i]; #if DEBUG_VIRTUAL_KEYS ALOGD("VirtualKeys: Hit test (%d, %d): keyCode=%d, scanCode=%d, " "left=%d, top=%d, right=%d, bottom=%d", x, y, virtualKey.keyCode, virtualKey.scanCode, virtualKey.hitLeft, virtualKey.hitTop, virtualKey.hitRight, virtualKey.hitBottom); #endif if (virtualKey.isHit(x, y)) { return & virtualKey; } } return NULL; } void TouchInputMapper::assignPointerIds(const RawState* last, RawState* current) { uint32_t currentPointerCount = current->rawPointerData.pointerCount; uint32_t lastPointerCount = last->rawPointerData.pointerCount; current->rawPointerData.clearIdBits(); if (currentPointerCount == 0) { // No pointers to assign. return; } if (lastPointerCount == 0) { // All pointers are new. for (uint32_t i = 0; i < currentPointerCount; i++) { uint32_t id = i; current->rawPointerData.pointers[i].id = id; current->rawPointerData.idToIndex[id] = i; current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(i)); } return; } if (currentPointerCount == 1 && lastPointerCount == 1 && current->rawPointerData.pointers[0].toolType == last->rawPointerData.pointers[0].toolType) { // Only one pointer and no change in count so it must have the same id as before. uint32_t id = last->rawPointerData.pointers[0].id; current->rawPointerData.pointers[0].id = id; current->rawPointerData.idToIndex[id] = 0; current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(0)); return; } // General case. // We build a heap of squared euclidean distances between current and last pointers // associated with the current and last pointer indices. Then, we find the best // match (by distance) for each current pointer. // The pointers must have the same tool type but it is possible for them to // transition from hovering to touching or vice-versa while retaining the same id. PointerDistanceHeapElement heap[MAX_POINTERS * MAX_POINTERS]; uint32_t heapSize = 0; for (uint32_t currentPointerIndex = 0; currentPointerIndex < currentPointerCount; currentPointerIndex++) { for (uint32_t lastPointerIndex = 0; lastPointerIndex < lastPointerCount; lastPointerIndex++) { const RawPointerData::Pointer& currentPointer = current->rawPointerData.pointers[currentPointerIndex]; const RawPointerData::Pointer& lastPointer = last->rawPointerData.pointers[lastPointerIndex]; if (currentPointer.toolType == lastPointer.toolType) { int64_t deltaX = currentPointer.x - lastPointer.x; int64_t deltaY = currentPointer.y - lastPointer.y; uint64_t distance = uint64_t(deltaX * deltaX + deltaY * deltaY); // Insert new element into the heap (sift up). heap[heapSize].currentPointerIndex = currentPointerIndex; heap[heapSize].lastPointerIndex = lastPointerIndex; heap[heapSize].distance = distance; heapSize += 1; } } } // Heapify for (uint32_t startIndex = heapSize / 2; startIndex != 0; ) { startIndex -= 1; for (uint32_t parentIndex = startIndex; ;) { uint32_t childIndex = parentIndex * 2 + 1; if (childIndex >= heapSize) { break; } if (childIndex + 1 < heapSize && heap[childIndex + 1].distance < heap[childIndex].distance) { childIndex += 1; } if (heap[parentIndex].distance <= heap[childIndex].distance) { break; } swap(heap[parentIndex], heap[childIndex]); parentIndex = childIndex; } } #if DEBUG_POINTER_ASSIGNMENT ALOGD("assignPointerIds - initial distance min-heap: size=%d", heapSize); for (size_t i = 0; i < heapSize; i++) { ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld", i, heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance); } #endif // Pull matches out by increasing order of distance. // To avoid reassigning pointers that have already been matched, the loop keeps track // of which last and current pointers have been matched using the matchedXXXBits variables. // It also tracks the used pointer id bits. BitSet32 matchedLastBits(0); BitSet32 matchedCurrentBits(0); BitSet32 usedIdBits(0); bool first = true; for (uint32_t i = min(currentPointerCount, lastPointerCount); heapSize > 0 && i > 0; i--) { while (heapSize > 0) { if (first) { // The first time through the loop, we just consume the root element of // the heap (the one with smallest distance). first = false; } else { // Previous iterations consumed the root element of the heap. // Pop root element off of the heap (sift down). heap[0] = heap[heapSize]; for (uint32_t parentIndex = 0; ;) { uint32_t childIndex = parentIndex * 2 + 1; if (childIndex >= heapSize) { break; } if (childIndex + 1 < heapSize && heap[childIndex + 1].distance < heap[childIndex].distance) { childIndex += 1; } if (heap[parentIndex].distance <= heap[childIndex].distance) { break; } swap(heap[parentIndex], heap[childIndex]); parentIndex = childIndex; } #if DEBUG_POINTER_ASSIGNMENT ALOGD("assignPointerIds - reduced distance min-heap: size=%d", heapSize); for (size_t i = 0; i < heapSize; i++) { ALOGD(" heap[%d]: cur=%d, last=%d, distance=%lld", i, heap[i].currentPointerIndex, heap[i].lastPointerIndex, heap[i].distance); } #endif } heapSize -= 1; uint32_t currentPointerIndex = heap[0].currentPointerIndex; if (matchedCurrentBits.hasBit(currentPointerIndex)) continue; // already matched uint32_t lastPointerIndex = heap[0].lastPointerIndex; if (matchedLastBits.hasBit(lastPointerIndex)) continue; // already matched matchedCurrentBits.markBit(currentPointerIndex); matchedLastBits.markBit(lastPointerIndex); uint32_t id = last->rawPointerData.pointers[lastPointerIndex].id; current->rawPointerData.pointers[currentPointerIndex].id = id; current->rawPointerData.idToIndex[id] = currentPointerIndex; current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(currentPointerIndex)); usedIdBits.markBit(id); #if DEBUG_POINTER_ASSIGNMENT ALOGD("assignPointerIds - matched: cur=%d, last=%d, id=%d, distance=%lld", lastPointerIndex, currentPointerIndex, id, heap[0].distance); #endif break; } } // Assign fresh ids to pointers that were not matched in the process. for (uint32_t i = currentPointerCount - matchedCurrentBits.count(); i != 0; i--) { uint32_t currentPointerIndex = matchedCurrentBits.markFirstUnmarkedBit(); uint32_t id = usedIdBits.markFirstUnmarkedBit(); current->rawPointerData.pointers[currentPointerIndex].id = id; current->rawPointerData.idToIndex[id] = currentPointerIndex; current->rawPointerData.markIdBit(id, current->rawPointerData.isHovering(currentPointerIndex)); #if DEBUG_POINTER_ASSIGNMENT ALOGD("assignPointerIds - assigned: cur=%d, id=%d", currentPointerIndex, id); #endif } } int32_t TouchInputMapper::getKeyCodeState(uint32_t sourceMask, int32_t keyCode) { if (mCurrentVirtualKey.down && mCurrentVirtualKey.keyCode == keyCode) { return AKEY_STATE_VIRTUAL; } size_t numVirtualKeys = mVirtualKeys.size(); for (size_t i = 0; i < numVirtualKeys; i++) { const VirtualKey& virtualKey = mVirtualKeys[i]; if (virtualKey.keyCode == keyCode) { return AKEY_STATE_UP; } } return AKEY_STATE_UNKNOWN; } int32_t TouchInputMapper::getScanCodeState(uint32_t sourceMask, int32_t scanCode) { if (mCurrentVirtualKey.down && mCurrentVirtualKey.scanCode == scanCode) { return AKEY_STATE_VIRTUAL; } size_t numVirtualKeys = mVirtualKeys.size(); for (size_t i = 0; i < numVirtualKeys; i++) { const VirtualKey& virtualKey = mVirtualKeys[i]; if (virtualKey.scanCode == scanCode) { return AKEY_STATE_UP; } } return AKEY_STATE_UNKNOWN; } bool TouchInputMapper::markSupportedKeyCodes(uint32_t sourceMask, size_t numCodes, const int32_t* keyCodes, uint8_t* outFlags) { size_t numVirtualKeys = mVirtualKeys.size(); for (size_t i = 0; i < numVirtualKeys; i++) { const VirtualKey& virtualKey = mVirtualKeys[i]; for (size_t i = 0; i < numCodes; i++) { if (virtualKey.keyCode == keyCodes[i]) { outFlags[i] = 1; } } } return true; } // --- SingleTouchInputMapper --- SingleTouchInputMapper::SingleTouchInputMapper(InputDevice* device) : TouchInputMapper(device) { } SingleTouchInputMapper::~SingleTouchInputMapper() { } void SingleTouchInputMapper::reset(nsecs_t when) { mSingleTouchMotionAccumulator.reset(getDevice()); TouchInputMapper::reset(when); } void SingleTouchInputMapper::process(const RawEvent* rawEvent) { TouchInputMapper::process(rawEvent); mSingleTouchMotionAccumulator.process(rawEvent); } void SingleTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) { if (mTouchButtonAccumulator.isToolActive()) { outState->rawPointerData.pointerCount = 1; outState->rawPointerData.idToIndex[0] = 0; bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE && (mTouchButtonAccumulator.isHovering() || (mRawPointerAxes.pressure.valid && mSingleTouchMotionAccumulator.getAbsolutePressure() <= 0)); outState->rawPointerData.markIdBit(0, isHovering); RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[0]; outPointer.id = 0; outPointer.x = mSingleTouchMotionAccumulator.getAbsoluteX(); outPointer.y = mSingleTouchMotionAccumulator.getAbsoluteY(); outPointer.pressure = mSingleTouchMotionAccumulator.getAbsolutePressure(); outPointer.touchMajor = 0; outPointer.touchMinor = 0; outPointer.toolMajor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth(); outPointer.toolMinor = mSingleTouchMotionAccumulator.getAbsoluteToolWidth(); outPointer.orientation = 0; outPointer.distance = mSingleTouchMotionAccumulator.getAbsoluteDistance(); outPointer.tiltX = mSingleTouchMotionAccumulator.getAbsoluteTiltX(); outPointer.tiltY = mSingleTouchMotionAccumulator.getAbsoluteTiltY(); outPointer.toolType = mTouchButtonAccumulator.getToolType(); if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) { outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; } outPointer.isHovering = isHovering; } } void SingleTouchInputMapper::configureRawPointerAxes() { TouchInputMapper::configureRawPointerAxes(); getAbsoluteAxisInfo(ABS_X, &mRawPointerAxes.x); getAbsoluteAxisInfo(ABS_Y, &mRawPointerAxes.y); getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPointerAxes.pressure); getAbsoluteAxisInfo(ABS_TOOL_WIDTH, &mRawPointerAxes.toolMajor); getAbsoluteAxisInfo(ABS_DISTANCE, &mRawPointerAxes.distance); getAbsoluteAxisInfo(ABS_TILT_X, &mRawPointerAxes.tiltX); getAbsoluteAxisInfo(ABS_TILT_Y, &mRawPointerAxes.tiltY); } bool SingleTouchInputMapper::hasStylus() const { return mTouchButtonAccumulator.hasStylus(); } // --- MultiTouchInputMapper --- MultiTouchInputMapper::MultiTouchInputMapper(InputDevice* device) : TouchInputMapper(device) { } MultiTouchInputMapper::~MultiTouchInputMapper() { } void MultiTouchInputMapper::reset(nsecs_t when) { mMultiTouchMotionAccumulator.reset(getDevice()); mPointerIdBits.clear(); TouchInputMapper::reset(when); } void MultiTouchInputMapper::process(const RawEvent* rawEvent) { TouchInputMapper::process(rawEvent); mMultiTouchMotionAccumulator.process(rawEvent); } void MultiTouchInputMapper::syncTouch(nsecs_t when, RawState* outState) { size_t inCount = mMultiTouchMotionAccumulator.getSlotCount(); size_t outCount = 0; BitSet32 newPointerIdBits; for (size_t inIndex = 0; inIndex < inCount; inIndex++) { const MultiTouchMotionAccumulator::Slot* inSlot = mMultiTouchMotionAccumulator.getSlot(inIndex); if (!inSlot->isInUse()) { continue; } if (outCount >= MAX_POINTERS) { #if DEBUG_POINTERS ALOGD("MultiTouch device %s emitted more than maximum of %d pointers; " "ignoring the rest.", getDeviceName().string(), MAX_POINTERS); #endif break; // too many fingers! } RawPointerData::Pointer& outPointer = outState->rawPointerData.pointers[outCount]; outPointer.x = inSlot->getX(); outPointer.y = inSlot->getY(); outPointer.pressure = inSlot->getPressure(); outPointer.touchMajor = inSlot->getTouchMajor(); outPointer.touchMinor = inSlot->getTouchMinor(); outPointer.toolMajor = inSlot->getToolMajor(); outPointer.toolMinor = inSlot->getToolMinor(); outPointer.orientation = inSlot->getOrientation(); outPointer.distance = inSlot->getDistance(); outPointer.tiltX = 0; outPointer.tiltY = 0; outPointer.toolType = inSlot->getToolType(); if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) { outPointer.toolType = mTouchButtonAccumulator.getToolType(); if (outPointer.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) { outPointer.toolType = AMOTION_EVENT_TOOL_TYPE_FINGER; } } bool isHovering = mTouchButtonAccumulator.getToolType() != AMOTION_EVENT_TOOL_TYPE_MOUSE && (mTouchButtonAccumulator.isHovering() || (mRawPointerAxes.pressure.valid && inSlot->getPressure() <= 0)); outPointer.isHovering = isHovering; // Assign pointer id using tracking id if available. mHavePointerIds = true; int32_t trackingId = inSlot->getTrackingId(); int32_t id = -1; if (trackingId >= 0) { for (BitSet32 idBits(mPointerIdBits); !idBits.isEmpty(); ) { uint32_t n = idBits.clearFirstMarkedBit(); if (mPointerTrackingIdMap[n] == trackingId) { id = n; } } if (id < 0 && !mPointerIdBits.isFull()) { id = mPointerIdBits.markFirstUnmarkedBit(); mPointerTrackingIdMap[id] = trackingId; } } if (id < 0) { mHavePointerIds = false; outState->rawPointerData.clearIdBits(); newPointerIdBits.clear(); } else { outPointer.id = id; outState->rawPointerData.idToIndex[id] = outCount; outState->rawPointerData.markIdBit(id, isHovering); newPointerIdBits.markBit(id); } outCount += 1; } outState->rawPointerData.pointerCount = outCount; mPointerIdBits = newPointerIdBits; mMultiTouchMotionAccumulator.finishSync(); } void MultiTouchInputMapper::configureRawPointerAxes() { TouchInputMapper::configureRawPointerAxes(); getAbsoluteAxisInfo(ABS_MT_POSITION_X, &mRawPointerAxes.x); getAbsoluteAxisInfo(ABS_MT_POSITION_Y, &mRawPointerAxes.y); getAbsoluteAxisInfo(ABS_MT_TOUCH_MAJOR, &mRawPointerAxes.touchMajor); getAbsoluteAxisInfo(ABS_MT_TOUCH_MINOR, &mRawPointerAxes.touchMinor); getAbsoluteAxisInfo(ABS_MT_WIDTH_MAJOR, &mRawPointerAxes.toolMajor); getAbsoluteAxisInfo(ABS_MT_WIDTH_MINOR, &mRawPointerAxes.toolMinor); getAbsoluteAxisInfo(ABS_MT_ORIENTATION, &mRawPointerAxes.orientation); getAbsoluteAxisInfo(ABS_MT_PRESSURE, &mRawPointerAxes.pressure); getAbsoluteAxisInfo(ABS_MT_DISTANCE, &mRawPointerAxes.distance); getAbsoluteAxisInfo(ABS_MT_TRACKING_ID, &mRawPointerAxes.trackingId); getAbsoluteAxisInfo(ABS_MT_SLOT, &mRawPointerAxes.slot); if (mRawPointerAxes.trackingId.valid && mRawPointerAxes.slot.valid && mRawPointerAxes.slot.minValue == 0 && mRawPointerAxes.slot.maxValue > 0) { size_t slotCount = mRawPointerAxes.slot.maxValue + 1; if (slotCount > MAX_SLOTS) { ALOGW("MultiTouch Device %s reported %zu slots but the framework " "only supports a maximum of %zu slots at this time.", getDeviceName().string(), slotCount, MAX_SLOTS); slotCount = MAX_SLOTS; } mMultiTouchMotionAccumulator.configure(getDevice(), slotCount, true /*usingSlotsProtocol*/); } else { mMultiTouchMotionAccumulator.configure(getDevice(), MAX_POINTERS, false /*usingSlotsProtocol*/); } } bool MultiTouchInputMapper::hasStylus() const { return mMultiTouchMotionAccumulator.hasStylus() || mTouchButtonAccumulator.hasStylus(); } // --- ExternalStylusInputMapper ExternalStylusInputMapper::ExternalStylusInputMapper(InputDevice* device) : InputMapper(device) { } uint32_t ExternalStylusInputMapper::getSources() { return AINPUT_SOURCE_STYLUS; } void ExternalStylusInputMapper::populateDeviceInfo(InputDeviceInfo* info) { InputMapper::populateDeviceInfo(info); info->addMotionRange(AMOTION_EVENT_AXIS_PRESSURE, AINPUT_SOURCE_STYLUS, 0.0f, 1.0f, 0.0f, 0.0f, 0.0f); } void ExternalStylusInputMapper::dump(String8& dump) { dump.append(INDENT2 "External Stylus Input Mapper:\n"); dump.append(INDENT3 "Raw Stylus Axes:\n"); dumpRawAbsoluteAxisInfo(dump, mRawPressureAxis, "Pressure"); dump.append(INDENT3 "Stylus State:\n"); dumpStylusState(dump, mStylusState); } void ExternalStylusInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) { getAbsoluteAxisInfo(ABS_PRESSURE, &mRawPressureAxis); mTouchButtonAccumulator.configure(getDevice()); } void ExternalStylusInputMapper::reset(nsecs_t when) { InputDevice* device = getDevice(); mSingleTouchMotionAccumulator.reset(device); mTouchButtonAccumulator.reset(device); InputMapper::reset(when); } void ExternalStylusInputMapper::process(const RawEvent* rawEvent) { mSingleTouchMotionAccumulator.process(rawEvent); mTouchButtonAccumulator.process(rawEvent); if (rawEvent->type == EV_SYN && rawEvent->code == SYN_REPORT) { sync(rawEvent->when); } } void ExternalStylusInputMapper::sync(nsecs_t when) { mStylusState.clear(); mStylusState.when = when; mStylusState.toolType = mTouchButtonAccumulator.getToolType(); if (mStylusState.toolType == AMOTION_EVENT_TOOL_TYPE_UNKNOWN) { mStylusState.toolType = AMOTION_EVENT_TOOL_TYPE_STYLUS; } int32_t pressure = mSingleTouchMotionAccumulator.getAbsolutePressure(); if (mRawPressureAxis.valid) { mStylusState.pressure = float(pressure) / mRawPressureAxis.maxValue; } else if (mTouchButtonAccumulator.isToolActive()) { mStylusState.pressure = 1.0f; } else { mStylusState.pressure = 0.0f; } mStylusState.buttons = mTouchButtonAccumulator.getButtonState(); mContext->dispatchExternalStylusState(mStylusState); } // --- JoystickInputMapper --- JoystickInputMapper::JoystickInputMapper(InputDevice* device) : InputMapper(device) { } JoystickInputMapper::~JoystickInputMapper() { } uint32_t JoystickInputMapper::getSources() { return AINPUT_SOURCE_JOYSTICK; } void JoystickInputMapper::populateDeviceInfo(InputDeviceInfo* info) { InputMapper::populateDeviceInfo(info); for (size_t i = 0; i < mAxes.size(); i++) { const Axis& axis = mAxes.valueAt(i); addMotionRange(axis.axisInfo.axis, axis, info); if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { addMotionRange(axis.axisInfo.highAxis, axis, info); } } } void JoystickInputMapper::addMotionRange(int32_t axisId, const Axis& axis, InputDeviceInfo* info) { info->addMotionRange(axisId, AINPUT_SOURCE_JOYSTICK, axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution); /* In order to ease the transition for developers from using the old axes * to the newer, more semantically correct axes, we'll continue to register * the old axes as duplicates of their corresponding new ones. */ int32_t compatAxis = getCompatAxis(axisId); if (compatAxis >= 0) { info->addMotionRange(compatAxis, AINPUT_SOURCE_JOYSTICK, axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution); } } /* A mapping from axes the joystick actually has to the axes that should be * artificially created for compatibility purposes. * Returns -1 if no compatibility axis is needed. */ int32_t JoystickInputMapper::getCompatAxis(int32_t axis) { switch(axis) { case AMOTION_EVENT_AXIS_LTRIGGER: return AMOTION_EVENT_AXIS_BRAKE; case AMOTION_EVENT_AXIS_RTRIGGER: return AMOTION_EVENT_AXIS_GAS; } return -1; } void JoystickInputMapper::dump(String8& dump) { dump.append(INDENT2 "Joystick Input Mapper:\n"); dump.append(INDENT3 "Axes:\n"); size_t numAxes = mAxes.size(); for (size_t i = 0; i < numAxes; i++) { const Axis& axis = mAxes.valueAt(i); const char* label = getAxisLabel(axis.axisInfo.axis); if (label) { dump.appendFormat(INDENT4 "%s", label); } else { dump.appendFormat(INDENT4 "%d", axis.axisInfo.axis); } if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { label = getAxisLabel(axis.axisInfo.highAxis); if (label) { dump.appendFormat(" / %s (split at %d)", label, axis.axisInfo.splitValue); } else { dump.appendFormat(" / %d (split at %d)", axis.axisInfo.highAxis, axis.axisInfo.splitValue); } } else if (axis.axisInfo.mode == AxisInfo::MODE_INVERT) { dump.append(" (invert)"); } dump.appendFormat(": min=%0.5f, max=%0.5f, flat=%0.5f, fuzz=%0.5f, resolution=%0.5f\n", axis.min, axis.max, axis.flat, axis.fuzz, axis.resolution); dump.appendFormat(INDENT4 " scale=%0.5f, offset=%0.5f, " "highScale=%0.5f, highOffset=%0.5f\n", axis.scale, axis.offset, axis.highScale, axis.highOffset); dump.appendFormat(INDENT4 " rawAxis=%d, rawMin=%d, rawMax=%d, " "rawFlat=%d, rawFuzz=%d, rawResolution=%d\n", mAxes.keyAt(i), axis.rawAxisInfo.minValue, axis.rawAxisInfo.maxValue, axis.rawAxisInfo.flat, axis.rawAxisInfo.fuzz, axis.rawAxisInfo.resolution); } } void JoystickInputMapper::configure(nsecs_t when, const InputReaderConfiguration* config, uint32_t changes) { InputMapper::configure(when, config, changes); if (!changes) { // first time only // Collect all axes. for (int32_t abs = 0; abs <= ABS_MAX; abs++) { if (!(getAbsAxisUsage(abs, getDevice()->getClasses()) & INPUT_DEVICE_CLASS_JOYSTICK)) { continue; // axis must be claimed by a different device } RawAbsoluteAxisInfo rawAxisInfo; getAbsoluteAxisInfo(abs, &rawAxisInfo); if (rawAxisInfo.valid) { // Map axis. AxisInfo axisInfo; bool explicitlyMapped = !getEventHub()->mapAxis(getDeviceId(), abs, &axisInfo); if (!explicitlyMapped) { // Axis is not explicitly mapped, will choose a generic axis later. axisInfo.mode = AxisInfo::MODE_NORMAL; axisInfo.axis = -1; } // Apply flat override. int32_t rawFlat = axisInfo.flatOverride < 0 ? rawAxisInfo.flat : axisInfo.flatOverride; // Calculate scaling factors and limits. Axis axis; if (axisInfo.mode == AxisInfo::MODE_SPLIT) { float scale = 1.0f / (axisInfo.splitValue - rawAxisInfo.minValue); float highScale = 1.0f / (rawAxisInfo.maxValue - axisInfo.splitValue); axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, scale, 0.0f, highScale, 0.0f, 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale, rawAxisInfo.resolution * scale); } else if (isCenteredAxis(axisInfo.axis)) { float scale = 2.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue); float offset = avg(rawAxisInfo.minValue, rawAxisInfo.maxValue) * -scale; axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, scale, offset, scale, offset, -1.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale, rawAxisInfo.resolution * scale); } else { float scale = 1.0f / (rawAxisInfo.maxValue - rawAxisInfo.minValue); axis.initialize(rawAxisInfo, axisInfo, explicitlyMapped, scale, 0.0f, scale, 0.0f, 0.0f, 1.0f, rawFlat * scale, rawAxisInfo.fuzz * scale, rawAxisInfo.resolution * scale); } // To eliminate noise while the joystick is at rest, filter out small variations // in axis values up front. axis.filter = axis.fuzz ? axis.fuzz : axis.flat * 0.25f; mAxes.add(abs, axis); } } // If there are too many axes, start dropping them. // Prefer to keep explicitly mapped axes. if (mAxes.size() > PointerCoords::MAX_AXES) { ALOGI("Joystick '%s' has %zu axes but the framework only supports a maximum of %d.", getDeviceName().string(), mAxes.size(), PointerCoords::MAX_AXES); pruneAxes(true); pruneAxes(false); } // Assign generic axis ids to remaining axes. int32_t nextGenericAxisId = AMOTION_EVENT_AXIS_GENERIC_1; size_t numAxes = mAxes.size(); for (size_t i = 0; i < numAxes; i++) { Axis& axis = mAxes.editValueAt(i); if (axis.axisInfo.axis < 0) { while (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16 && haveAxis(nextGenericAxisId)) { nextGenericAxisId += 1; } if (nextGenericAxisId <= AMOTION_EVENT_AXIS_GENERIC_16) { axis.axisInfo.axis = nextGenericAxisId; nextGenericAxisId += 1; } else { ALOGI("Ignoring joystick '%s' axis %d because all of the generic axis ids " "have already been assigned to other axes.", getDeviceName().string(), mAxes.keyAt(i)); mAxes.removeItemsAt(i--); numAxes -= 1; } } } } } bool JoystickInputMapper::haveAxis(int32_t axisId) { size_t numAxes = mAxes.size(); for (size_t i = 0; i < numAxes; i++) { const Axis& axis = mAxes.valueAt(i); if (axis.axisInfo.axis == axisId || (axis.axisInfo.mode == AxisInfo::MODE_SPLIT && axis.axisInfo.highAxis == axisId)) { return true; } } return false; } void JoystickInputMapper::pruneAxes(bool ignoreExplicitlyMappedAxes) { size_t i = mAxes.size(); while (mAxes.size() > PointerCoords::MAX_AXES && i-- > 0) { if (ignoreExplicitlyMappedAxes && mAxes.valueAt(i).explicitlyMapped) { continue; } ALOGI("Discarding joystick '%s' axis %d because there are too many axes.", getDeviceName().string(), mAxes.keyAt(i)); mAxes.removeItemsAt(i); } } bool JoystickInputMapper::isCenteredAxis(int32_t axis) { switch (axis) { case AMOTION_EVENT_AXIS_X: case AMOTION_EVENT_AXIS_Y: case AMOTION_EVENT_AXIS_Z: case AMOTION_EVENT_AXIS_RX: case AMOTION_EVENT_AXIS_RY: case AMOTION_EVENT_AXIS_RZ: case AMOTION_EVENT_AXIS_HAT_X: case AMOTION_EVENT_AXIS_HAT_Y: case AMOTION_EVENT_AXIS_ORIENTATION: case AMOTION_EVENT_AXIS_RUDDER: case AMOTION_EVENT_AXIS_WHEEL: return true; default: return false; } } void JoystickInputMapper::reset(nsecs_t when) { // Recenter all axes. size_t numAxes = mAxes.size(); for (size_t i = 0; i < numAxes; i++) { Axis& axis = mAxes.editValueAt(i); axis.resetValue(); } InputMapper::reset(when); } void JoystickInputMapper::process(const RawEvent* rawEvent) { switch (rawEvent->type) { case EV_ABS: { ssize_t index = mAxes.indexOfKey(rawEvent->code); if (index >= 0) { Axis& axis = mAxes.editValueAt(index); float newValue, highNewValue; switch (axis.axisInfo.mode) { case AxisInfo::MODE_INVERT: newValue = (axis.rawAxisInfo.maxValue - rawEvent->value) * axis.scale + axis.offset; highNewValue = 0.0f; break; case AxisInfo::MODE_SPLIT: if (rawEvent->value < axis.axisInfo.splitValue) { newValue = (axis.axisInfo.splitValue - rawEvent->value) * axis.scale + axis.offset; highNewValue = 0.0f; } else if (rawEvent->value > axis.axisInfo.splitValue) { newValue = 0.0f; highNewValue = (rawEvent->value - axis.axisInfo.splitValue) * axis.highScale + axis.highOffset; } else { newValue = 0.0f; highNewValue = 0.0f; } break; default: newValue = rawEvent->value * axis.scale + axis.offset; highNewValue = 0.0f; break; } axis.newValue = newValue; axis.highNewValue = highNewValue; } break; } case EV_SYN: switch (rawEvent->code) { case SYN_REPORT: sync(rawEvent->when, false /*force*/); break; } break; } } void JoystickInputMapper::sync(nsecs_t when, bool force) { if (!filterAxes(force)) { return; } int32_t metaState = mContext->getGlobalMetaState(); int32_t buttonState = 0; PointerProperties pointerProperties; pointerProperties.clear(); pointerProperties.id = 0; pointerProperties.toolType = AMOTION_EVENT_TOOL_TYPE_UNKNOWN; PointerCoords pointerCoords; pointerCoords.clear(); size_t numAxes = mAxes.size(); for (size_t i = 0; i < numAxes; i++) { const Axis& axis = mAxes.valueAt(i); setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.axis, axis.currentValue); if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { setPointerCoordsAxisValue(&pointerCoords, axis.axisInfo.highAxis, axis.highCurrentValue); } } // Moving a joystick axis should not wake the device because joysticks can // be fairly noisy even when not in use. On the other hand, pushing a gamepad // button will likely wake the device. // TODO: Use the input device configuration to control this behavior more finely. uint32_t policyFlags = 0; NotifyMotionArgs args(when, getDeviceId(), AINPUT_SOURCE_JOYSTICK, policyFlags, AMOTION_EVENT_ACTION_MOVE, 0, 0, metaState, buttonState, AMOTION_EVENT_EDGE_FLAG_NONE, ADISPLAY_ID_NONE, 1, &pointerProperties, &pointerCoords, 0, 0, 0); getListener()->notifyMotion(&args); } void JoystickInputMapper::setPointerCoordsAxisValue(PointerCoords* pointerCoords, int32_t axis, float value) { pointerCoords->setAxisValue(axis, value); /* In order to ease the transition for developers from using the old axes * to the newer, more semantically correct axes, we'll continue to produce * values for the old axes as mirrors of the value of their corresponding * new axes. */ int32_t compatAxis = getCompatAxis(axis); if (compatAxis >= 0) { pointerCoords->setAxisValue(compatAxis, value); } } bool JoystickInputMapper::filterAxes(bool force) { bool atLeastOneSignificantChange = force; size_t numAxes = mAxes.size(); for (size_t i = 0; i < numAxes; i++) { Axis& axis = mAxes.editValueAt(i); if (force || hasValueChangedSignificantly(axis.filter, axis.newValue, axis.currentValue, axis.min, axis.max)) { axis.currentValue = axis.newValue; atLeastOneSignificantChange = true; } if (axis.axisInfo.mode == AxisInfo::MODE_SPLIT) { if (force || hasValueChangedSignificantly(axis.filter, axis.highNewValue, axis.highCurrentValue, axis.min, axis.max)) { axis.highCurrentValue = axis.highNewValue; atLeastOneSignificantChange = true; } } } return atLeastOneSignificantChange; } bool JoystickInputMapper::hasValueChangedSignificantly( float filter, float newValue, float currentValue, float min, float max) { if (newValue != currentValue) { // Filter out small changes in value unless the value is converging on the axis // bounds or center point. This is intended to reduce the amount of information // sent to applications by particularly noisy joysticks (such as PS3). if (fabs(newValue - currentValue) > filter || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, min) || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, max) || hasMovedNearerToValueWithinFilteredRange(filter, newValue, currentValue, 0)) { return true; } } return false; } bool JoystickInputMapper::hasMovedNearerToValueWithinFilteredRange( float filter, float newValue, float currentValue, float thresholdValue) { float newDistance = fabs(newValue - thresholdValue); if (newDistance < filter) { float oldDistance = fabs(currentValue - thresholdValue); if (newDistance < oldDistance) { return true; } } return false; } } // namespace android
b00100240223db480452a985efe5fd4a41027d03
7f74c236881176d673fd5b8bed6e18283232deca
/modules/predicates/unit/simd/is_nlez.cpp
68079a018292e3483f554c7d0788dad7a23b6219
[ "BSL-1.0" ]
permissive
pesterie/nt2
57a3cbe4e3631d5eacbd1703b79af769f40b13f1
94e4062794466136987bf0afd9a94d43275b13cf
refs/heads/master
2021-01-18T06:52:52.070291
2011-08-31T12:04:16
2011-08-31T12:04:16
1,566,046
0
0
null
null
null
null
UTF-8
C++
false
false
3,188
cpp
////////////////////////////////////////////////////////////////////////////// /// Copyright 2003 and onward LASMEA UMR 6602 CNRS/U.B.P Clermont-Ferrand /// Copyright 2009 and onward LRI UMR 8623 CNRS/Univ Paris Sud XI /// /// Distributed under the Boost Software License, Version 1.0 /// See accompanying file LICENSE.txt or copy at /// http://www.boost.org/LICENSE_1_0.txt ////////////////////////////////////////////////////////////////////////////// #define NT2_UNIT_MODULE "nt2 predicates toolbox - is_nlez/simd Mode" ////////////////////////////////////////////////////////////////////////////// // unit test behavior of predicates components in simd mode ////////////////////////////////////////////////////////////////////////////// /// created by jt the 21/02/2011 /// #include <nt2/toolbox/predicates/include/functions/is_nlez.hpp> #include <nt2/include/functions/ulpdist.hpp> #include <nt2/sdk/meta/logical.hpp> #include <boost/type_traits/is_same.hpp> #include <nt2/sdk/functor/meta/call.hpp> #include <nt2/sdk/meta/as_integer.hpp> #include <nt2/sdk/meta/as_real.hpp> #include <nt2/sdk/meta/as_signed.hpp> #include <nt2/sdk/meta/upgrade.hpp> #include <nt2/sdk/meta/downgrade.hpp> #include <nt2/sdk/meta/scalar_of.hpp> #include <nt2/sdk/meta/floating.hpp> #include <nt2/sdk/meta/arithmetic.hpp> #include <nt2/sdk/unit/tests.hpp> #include <nt2/sdk/unit/module.hpp> #include <nt2/sdk/memory/buffer.hpp> #include <nt2/toolbox/constant/constant.hpp> #include <nt2/sdk/meta/cardinal_of.hpp> #include <nt2/include/functions/splat.hpp> #include <nt2/sdk/memory/is_aligned.hpp> #include <nt2/sdk/memory/aligned_type.hpp> #include <nt2/include/functions/load.hpp> NT2_TEST_CASE_TPL ( is_nlez_real__1_0, NT2_SIMD_REAL_TYPES) { using nt2::is_nlez; using nt2::tag::is_nlez_; using nt2::load; using boost::simd::native; using nt2::meta::cardinal_of; typedef NT2_SIMD_DEFAULT_EXTENSION ext_t; typedef typename nt2::meta::upgrade<T>::type u_t; typedef native<T,ext_t> n_t; typedef n_t vT; typedef typename nt2::meta::as_integer<T>::type iT; typedef native<iT,ext_t> ivT; typedef typename nt2::meta::call<is_nlez_(vT)>::type r_t; typedef typename nt2::meta::call<is_nlez_(T)>::type sr_t; typedef typename nt2::meta::scalar_of<r_t>::type ssr_t; double ulpd; ulpd=0.0; // specific values tests NT2_TEST_EQUAL(is_nlez(-nt2::Zero<vT>())[0]!=0, nt2::False<sr_t>()); NT2_TEST_EQUAL(is_nlez(nt2::Half<vT>())[0]!=0, nt2::True<sr_t>()); NT2_TEST_EQUAL(is_nlez(nt2::Inf<vT>())[0]!=0, nt2::True<sr_t>()); NT2_TEST_EQUAL(is_nlez(nt2::Minf<vT>())[0]!=0, nt2::False<sr_t>()); NT2_TEST_EQUAL(is_nlez(nt2::Mone<vT>())[0]!=0, nt2::False<sr_t>()); NT2_TEST_EQUAL(is_nlez(nt2::Nan<vT>())[0]!=0, nt2::True<sr_t>()); NT2_TEST_EQUAL(is_nlez(nt2::One<vT>())[0]!=0, nt2::True<sr_t>()); NT2_TEST_EQUAL(is_nlez(nt2::Quarter<vT>())[0]!=0, nt2::True<sr_t>()); NT2_TEST_EQUAL(is_nlez(nt2::Two<vT>())[0]!=0, nt2::True<sr_t>()); NT2_TEST_EQUAL(is_nlez(nt2::Zero<vT>())[0]!=0, nt2::False<sr_t>()); } // end of test for real_
d21ac26b4e2a04f4fffd9086328cde47cc6fe22b
f7fa487f1872352781372611e3322d494de569da
/MemLeak/MemLeak.cpp
ad63ba70aca10d1f2c4edbe5f3a3686f5c2a8620
[]
no_license
rainhenry/CodeNote
151494aa5069d49ccf27112c8fc791a1c355bc5c
ba55ca15ee003aa2a02ffae7563629907a831333
refs/heads/master
2023-07-02T03:51:23.163637
2021-08-07T17:16:32
2021-08-07T17:16:32
393,670,260
1
0
null
null
null
null
UTF-8
C++
false
false
245
cpp
#include "stdafx.h" #include "MemLeak.h" CMemLeak mCMemLeak; bool CMemLeak::init_flag = false; CMemLeak::CMemLeak() { if (init_flag == false) { init_flag = true; CheckMemoryLeak; } } CMemLeak::~CMemLeak() { }
37e3022172c224a75908aeccb589c2f15eae28cb
3ea315a54e19789dc3fa1d4146931fcf4e0a3667
/fibonacci.cpp
1d5ee5dc9281c7d41f53e10103f67956a9e717c6
[]
no_license
Nikhil-Reddy1/my_cpp_codes
b3c6062bbb3abcf1508944ce458ee1a85027f949
a5f99410445aa72188af71ea3d953d58e1e4cc61
refs/heads/master
2020-12-21T05:20:11.958160
2020-01-26T13:45:47
2020-01-26T13:45:47
236,320,412
0
0
null
null
null
null
UTF-8
C++
false
false
254
cpp
#include<iostream> using namespace std; int main() { int a=0,n,b=1; std::cout<<"enter the limit of fibonacci no..\n"; std::cin>>n; std::cout<<a<<" "<<b<<" "; for(int i=2;i<n;i++) { int c = a + b; std::cout<<c<<" "; a=b; b=c; } return 0; }
665eec45d44a2b1ba94cac6f948d3cd599d45a9c
7ba882fdb150d9125852b5ac7a75510619f5c05d
/sumi/allreduce.h
4f19109149a0bf5704efc81d9a095217c72eb2db
[]
no_license
jjwilke/sumi
402c32dd8af0ecd73c47453197a38f7333f8a030
bd8971adf0765f93f64f1667dd7683de3028ded9
refs/heads/master
2021-01-10T09:10:46.039904
2016-03-22T01:31:52
2016-03-22T01:31:52
51,499,960
0
0
null
null
null
null
UTF-8
C++
false
false
1,304
h
#ifndef sstmac_sw_api_simpsg_ALLREDUCE_H #define sstmac_sw_api_simpsg_ALLREDUCE_H #include <sumi/collective.h> #include <sumi/collective_actor.h> #include <sumi/collective_message.h> #include <sumi/comm_functions.h> DeclareDebugSlot(sumi_allreduce) namespace sumi { class wilke_allreduce_actor : public dag_collective_actor { public: std::string to_string() const { return "virtual all reduce actor"; } void buffer_action(void *dst_buffer, void *msg_buffer, action* ac); wilke_allreduce_actor(reduce_fxn fxn); private: bool is_lower_partner(int virtual_me, int partner_gap); void finalize_buffers(); void init_buffers(void *dst, void *src); void init_dag(); private: reduce_fxn fxn_; int num_reducing_rounds_; int num_total_rounds_; }; class wilke_halving_allreduce : public dag_collective { public: std::string to_string() const { return "sumi allreduce"; } wilke_halving_allreduce(reduce_fxn fxn); wilke_halving_allreduce(){} virtual void init_reduce(reduce_fxn fxn){ fxn_ = fxn; } dag_collective_actor* new_actor() const { return new wilke_allreduce_actor(fxn_); } dag_collective* clone() const { return new wilke_halving_allreduce(fxn_); } private: reduce_fxn fxn_; }; } #endif // ALLREDUCE_H
1e4b3a19b009be64d0be444a2ef6c5fb54e64627
184180d341d2928ab7c5a626d94f2a9863726c65
/issuestests/fbroc/inst/testfiles/fpr_at_tpr_cached/libFuzzer_fpr_at_tpr_cached/fpr_at_tpr_cached_DeepState_TestHarness.cpp
63ea5f8069aa53fa04a235f39c01b6bd2083e81c
[]
no_license
akhikolla/RcppDeepStateTest
f102ddf03a22b0fc05e02239d53405c8977cbc2b
97e73fe4f8cb0f8e5415f52a2474c8bc322bbbe5
refs/heads/master
2023-03-03T12:19:31.725234
2021-02-12T21:50:12
2021-02-12T21:50:12
254,214,504
2
1
null
null
null
null
UTF-8
C++
false
false
1,907
cpp
#include <fstream> #include <RInside.h> #include <iostream> #include <RcppDeepState.h> #include <qs.h> #include <DeepState.hpp> NumericMatrix fpr_at_tpr_cached(NumericMatrix tpr, NumericMatrix fpr, int n_steps); TEST(fbroc_deepstate_test,fpr_at_tpr_cached_test){ static int rinside_flag = 0; if(rinside_flag == 0) { rinside_flag = 1; RInside R; } std::time_t current_timestamp = std::time(0); std::cout << "input starts" << std::endl; NumericMatrix tpr = RcppDeepState_NumericMatrix(); std::string tpr_t = "/home/akhila/R/x86_64-pc-linux-gnu-library/3.6/RcppDeepState/extdata/issuestests/fbroc/inst/testfiles/fpr_at_tpr_cached/libFuzzer_fpr_at_tpr_cached/libfuzzer_inputs/" + std::to_string(current_timestamp) + "_tpr.qs"; qs::c_qsave(tpr,tpr_t, "high", "zstd", 1, 15, true, 1); std::cout << "tpr values: "<< tpr << std::endl; NumericMatrix fpr = RcppDeepState_NumericMatrix(); std::string fpr_t = "/home/akhila/R/x86_64-pc-linux-gnu-library/3.6/RcppDeepState/extdata/issuestests/fbroc/inst/testfiles/fpr_at_tpr_cached/libFuzzer_fpr_at_tpr_cached/libfuzzer_inputs/" + std::to_string(current_timestamp) + "_fpr.qs"; qs::c_qsave(fpr,fpr_t, "high", "zstd", 1, 15, true, 1); std::cout << "fpr values: "<< fpr << std::endl; IntegerVector n_steps(1); n_steps[0] = RcppDeepState_int(); std::string n_steps_t = "/home/akhila/R/x86_64-pc-linux-gnu-library/3.6/RcppDeepState/extdata/issuestests/fbroc/inst/testfiles/fpr_at_tpr_cached/libFuzzer_fpr_at_tpr_cached/libfuzzer_inputs/" + std::to_string(current_timestamp) + "_n_steps.qs"; qs::c_qsave(n_steps,n_steps_t, "high", "zstd", 1, 15, true, 1); std::cout << "n_steps values: "<< n_steps << std::endl; std::cout << "input ends" << std::endl; try{ fpr_at_tpr_cached(tpr,fpr,n_steps[0]); } catch(Rcpp::exception& e){ std::cout<<"Exception Handled"<<std::endl; } }
8391dd95d7892d9907d55aa7e9afe97c52ed6be3
62cebce3183176b9d8e05f8437318072b8ef1ab3
/test/src/dataman.cpp
9aff3ce0a51709989a16077f36dbd5843b86c2f7
[]
no_license
dec1/user_io
f4422f04622b979b16a1e457b0f290e438d2c8f7
2b26a69cffe065a2b02441f80398e8661521851c
refs/heads/master
2020-06-23T06:26:12.543726
2017-09-07T10:01:31
2017-09-07T10:01:31
94,231,380
0
0
null
null
null
null
UTF-8
C++
false
false
911
cpp
#include "dataman.h" #include "dataelem.h" tDataMan::tDataMan(tMan * Man) : _Man(Man) { _Elems = new tDataElems(); } //--------------------------- tDataMan::~tDataMan() { freeElems(); delete _Elems; } //--------------------------- void tDataMan::addElem(tDataElem *Elem) { elems()->append(Elem); } //--------------------------- void tDataMan::freeElems() { foreach(tDataElem * Elem, *_Elems) delete Elem; elems()->clear(); } //--------------------------- tDataElems tDataMan::elemsSortedAscending() { // C++11 Lambda notation tSortFun sortAscending = [](const tDataElem * d1, const tDataElem * d2) { return d1->val() < d2->val(); }; return elemsSorted(*elems(), sortAscending); } //--------------------------- tDataElems tDataMan::elemsSorted(tDataElems Elems, tSortFun sortFun) { std::sort(Elems.begin(), Elems.end(),sortFun); return Elems; }
0ea2e6f773b20ae4436a3f273651a58d0e5fef73
4eaaeaaec02753509eb5118e1060e91377fa3290
/BT_lesson_5/BaiTap_1.cpp
7e2644eba4ec37715e30bc8c0f09843a24113486
[]
no_license
luongngoc2194/T2104E
0e5c8493aa7c7b5e34c3b5c89b41b5c9247b82d4
e2156c6935d912d31b772a2b44d4806a2affb77f
refs/heads/main
2023-07-15T00:30:58.884664
2021-08-26T13:30:54
2021-08-26T13:30:54
367,024,169
0
0
null
null
null
null
UTF-8
C++
false
false
180
cpp
//inso chan nho hon n #include<stdio.h> int main(){ int n; printf("Nhap so n :"); scanf("%d",&n); for(int i=1;i<n;i++){ if(i%2==0){ printf("%d\n",i); } } }
ae4d1354fb023e8a1213414b57ac791827a66260
59d8c7160e92c235bdc28385a741fd9e4745f4ab
/mine/Section13/DeclareClassAndObjects/main.cpp
979247c2c46035063023daab72012778caaaf27c
[]
no_license
mhirai-bit/BeginningCppProgrammingFromBeginnerToBeyond
1ba3b56cea711a12c78bedfa6fc1f8a7cf422abe
52ce8c4c3494b540bcba385b6a6826663387ebbe
refs/heads/master
2022-12-17T01:51:34.622302
2020-09-23T03:42:54
2020-09-23T03:42:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
698
cpp
// Sectioin 13 // Declare Classes and Objects #include <iostream> #include <string> #include <vector> using namespace std; class Player{ //attributes string name {"Player"}; int health {100}; int xp {3}; // methods void talk(string); bool is_dead(); }; class Account { //attributes string name {"Account"}; double balance {0.0}; // methods bool deposit(double); bool withdraw(double); }; int main(){ Account frank_account; Account jim_account; Player frank; Player hero; Player players[] {frank, hero}; vector<Player> player_vec {frank}; player_vec.push_back(hero); Player *enemy {nullptr}; enemy = new Player; delete enemy; return 0; }
0fcc4454bb6905d729740ea7ea5338d00d689a87
b0ab9fd432e4de81bfa1213efd664e44573fd763
/2008/main.cpp
93b633972280ca43dfc2080c59a9592928a49cc9
[]
no_license
Strazdonis/informatikos_egzai
293912655d362f42bb8eca56236d68b12645e7fb
686413aee87a3082ae9b279ef7d2d18b89e5afb2
refs/heads/master
2020-05-25T07:39:29.720259
2019-05-27T19:52:54
2019-05-27T19:52:54
187,690,336
0
0
null
null
null
null
UTF-8
C++
false
false
1,535
cpp
#include <iostream> #include <fstream> using namespace std; struct duomenys { string pavadinimas; int msk; int mnr[100]; }; duomenys duom[100]; int marsrutai[100] = {0}; int stoteles[100] = {0}; void nuskaitymas() { ifstream fin; fin.open("U2.txt"); int sk; fin >> sk; fin.get(); char raide[100]; for(int i = 0; i<sk; i++) { fin.get(raide, 20); duom[i].pavadinimas = raide; fin >> duom[i].msk; for(int j = 0; j < duom[i].msk; j++) { fin >> duom[i].mnr[j]; marsrutai[duom[i].mnr[j]] += duom[i].msk; stoteles[duom[i].mnr[j]]++; } fin.get(); } fin.close(); } int didziausias(int mars[100], int stot[100]) { int didz_mars = mars[0]; int didz_stot = stot[0]; int didzi; for(int i = 0; i<100; i++) { if(mars[i] >= didz_mars && stot[i] > didz_stot) { didz_mars = mars[i]; didz_stot = stot[i]; didzi = i; } } return didzi; } void stoteliuPav(int sk) { ofstream fout; fout.open("U2rez.txt"); fout << sk << endl; // sita reiktu spausdint main() turbut for(int i = 0; i < 100; i++) { for(int j = 0; j < duom[i].msk; j++) { if(sk == duom[i].mnr[j]) { fout << duom[i].pavadinimas << endl; } } } fout.close(); } int main() { nuskaitymas(); stoteliuPav(didziausias(marsrutai, stoteles)); //nezinau ar gerai taip turbut ne bet nesvarbu return 0; }
eb81209f78c20e20794110ee3393e637eae35d5d
9f6cd4fa5c014673f24aad768802c5c0e9c279f1
/lib/src/facts/posix/external_resolvers_factory.cc
5f65222a23a52732ae63c6fc3b07d8925a5b3da1
[ "Apache-2.0" ]
permissive
nwops/facter
9b0de994c47ba5c8cf0065b6afb9b1bdfcacce98
e36657bea27254f003c8fc71d8ef57454db643e2
refs/heads/master
2022-12-22T07:21:29.274914
2020-09-21T13:45:35
2020-09-21T13:45:35
298,468,479
0
0
MIT
2020-09-25T04:37:36
2020-09-25T04:37:35
null
UTF-8
C++
false
false
494
cc
#include <leatherman/locale/locale.hpp> #include <facter/facts/external_resolvers_factory.hpp> using namespace std; namespace facter { namespace facts { shared_ptr<external::resolver> external_resolvers_factory::get_resolver(const string& path) { auto resolver = get_common_resolver(path); if (resolver) return resolver; throw external::external_fact_no_resolver(leatherman::locale::_("No resolver for external facts file {1}", path)); } }} // facter::facts
0abd8e0c58ee141a14021aa9d54689c8a2a71f00
f770634e8d0926b0fe365e634682ca9ac5a426da
/Tencent_intership_2016/construct_huiwen.cpp
7609a47217131c0df7e06be9efd4e3090676982f
[]
no_license
hu18yuanwai/code_work
4ea838f884e619c815f97dcab6d67c153e4c256a
040bba008ee0f32ef96a3bfc7560134440d56006
refs/heads/master
2020-04-02T04:58:01.760054
2017-03-26T12:55:54
2017-03-26T12:55:54
62,209,794
0
0
null
null
null
null
UTF-8
C++
false
false
677
cpp
#include <iostream> #include <cstring> #include <string> using namespace std; #define INT_MAX 2147483647 bool is_P(string s){ if(s.size()<=1) return true; int i=0,j=s.size()-1; while(i<=j){ if(s[i]!=s[j]) return false; i++; j--; } return true; } void back(string s,int num,int &min){ if(num>=min) return; for(int i=0;i<s.size();i++){ string ss=s; ss=ss.erase(i,1); if(is_P(ss)){ min=num; return; } } for(int i=0;i<s.size();i++){ string ss=s; ss=ss.erase(i,1); back(ss,num+1,min); } } int main(){ string s; while(cin>>s){ int min=INT_MAX; if(is_P(s)) cout<<0<<endl; else{ back(s,1,min); cout<<min<<endl; } } return 0; }
380a5c79d767938539f43fb37d57ac673d89b5d1
32783ad2a0aecdbfae71be7a684e13887e038a28
/CodeChef/Easy/RESQ.cpp
c24c2c3378c3a4d041cad2ff9dc2b4e4f42c366c
[ "MIT" ]
permissive
malathidhandapani/Competitive-Coding
7c6fe2074bb8a171b54f633f84a69fceee6cd483
ffefe5f8b299c623af1ef01bf024af339401de0b
refs/heads/master
2020-04-02T02:50:01.341770
2017-12-19T09:07:53
2017-12-19T09:07:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
801
cpp
#include "bits/stdc++.h" using namespace std; # define s(n) scanf("%d",&n) # define sc(n) scanf("%c",&n) # define sl(n) scanf("%lld",&n) # define sf(n) scanf("%lf",&n) # define ss(n) scanf("%s",n) # define INF (int)1e9 # define EPS 1e-9 # define MOD 1000000007 typedef long long ll; int main() { int t; cin >> t; while(t--){ ll n; sl(n); ll min=MOD; ll square_root = (ll) sqrt(n) + 1; for (ll i = 1; i < square_root; i++) { if (n%i == 0 && i*i!=n) { if(labs(n/i - i)<min) min=labs(n/i-i); } if (n % i == 0 && i*i==n){ min=0; } } printf("%lld\n",min ); } return 0; }
03c1cca67b5d3c377aedcd30f89dfc6ce97c9d30
793c8848753f530aab28076a4077deac815af5ac
/src/dskphone/logic/lamp/ledlamp/src/eventslot.h
55bfcd908f7c1668d109e7a727b7ebc130e10d9c
[]
no_license
Parantido/sipphone
4c1b9b18a7a6e478514fe0aadb79335e734bc016
f402efb088bb42900867608cc9ccf15d9b946d7d
refs/heads/master
2021-09-10T20:12:36.553640
2018-03-30T12:44:13
2018-03-30T12:44:13
263,628,242
1
0
null
2020-05-13T12:49:19
2020-05-13T12:49:18
null
UTF-8
C++
false
false
720
h
#ifndef _EVENTSLOTH_ #define _EVENTSLOTH_ #ifdef _T42 #else // #include <list> // #include <vector> #endif #include <ETLLib.hpp> #include "ledlampstruct.h" class CLedLamp; class CEventSlot { public: CEventSlot(); ~CEventSlot(); bool PostEvent(LAMP_EVENTTYPE _eventType, const tEventUnit & eventUnit, bool bRegister, int iLampNum); //如果当前控制的灯是pLedLamp,且移除 void RemoveLedLamp(CLedLamp * pLedLamp); /* 内存释放 */ void ClearVLightInfo(); /* 取list中头元素, 进行灯的操作 */ bool DoneListHead(int nLightNum); private: static VECTORLIGHTINFO m_vLightInfo; /* 数组:存储所有灯信息(灯号 + 灯属性) */ }; #endif
344db27bf7c62d80483bee339beeeaf2bba159bc
508510d10ddcb009fc4fb53a26d897bc462039c0
/PUBG/SDK/PUBG_HudMain_parameters.hpp
62aba74126421ef6ebd6ca4c8560ed248b4d285d
[]
no_license
Avatarchik/PUBG-SDK
ed6e0aa27eac646e557272bbf1607b7351905c8c
07639ddf96bc0f57fb4b1be0a9b29d5446fcc5da
refs/heads/master
2021-06-21T07:51:37.309095
2017-08-10T08:15:56
2017-08-10T08:15:56
100,607,141
1
1
null
2017-08-17T13:36:40
2017-08-17T13:36:40
null
UTF-8
C++
false
false
13,017
hpp
#pragma once // PLAYERUNKNOWN BattleGrounds () SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "../SDK.hpp" namespace Classes { //--------------------------------------------------------------------------- //Parameters //--------------------------------------------------------------------------- // Function HudMain.HudMain_C.OnKey_ReplayMenuOrEscape struct UHudMain_C_OnKey_ReplayMenuOrEscape_Params { }; // Function HudMain.HudMain_C.InitForReplay struct UHudMain_C_InitForReplay_Params { }; // Function HudMain.HudMain_C.OnToggleOption struct UHudMain_C_OnToggleOption_Params { }; // Function HudMain.HudMain_C.On_Name_Prepass_1 struct UHudMain_C_On_Name_Prepass_1_Params { class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.ShowReplayTimeline struct UHudMain_C_ShowReplayTimeline_Params { }; // Function HudMain.HudMain_C.OnToggleBattleList struct UHudMain_C_OnToggleBattleList_Params { }; // Function HudMain.HudMain_C.OnMapHide struct UHudMain_C_OnMapHide_Params { }; // Function HudMain.HudMain_C.OnMapShow struct UHudMain_C_OnMapShow_Params { }; // Function HudMain.HudMain_C.OnKey_MapReleased struct UHudMain_C_OnKey_MapReleased_Params { }; // Function HudMain.HudMain_C.OnKey_MapPressed struct UHudMain_C_OnKey_MapPressed_Params { }; // Function HudMain.HudMain_C.OnShowCarePackageItemList struct UHudMain_C_OnShowCarePackageItemList_Params { }; // Function HudMain.HudMain_C.GetMiniMapType struct UHudMain_C_GetMiniMapType_Params { int Index; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) class UClass* MiniMapype; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.On_BlueZoneGpsWidget_RoundType_Prepass_1 struct UHudMain_C_On_BlueZoneGpsWidget_RoundType_Prepass_1_Params { class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.IsShowMapOrInventory struct UHudMain_C_IsShowMapOrInventory_Params { bool bIsShow; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.Get_Spectating_Text_1 struct UHudMain_C_Get_Spectating_Text_1_Params { struct FText ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ReturnParm) }; // Function HudMain.HudMain_C.OnPrepass_2 struct UHudMain_C_OnPrepass_2_Params { class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.On_CharacterCanvas_Prepass_1 struct UHudMain_C_On_CharacterCanvas_Prepass_1_Params { class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.OnTogglePlayerList struct UHudMain_C_OnTogglePlayerList_Params { }; // Function HudMain.HudMain_C.Get_KeyInfo_Text_1 struct UHudMain_C_Get_KeyInfo_Text_1_Params { struct FText ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ReturnParm) }; // Function HudMain.HudMain_C.On_SpectatingKeyInfo_Prepass_1 struct UHudMain_C_On_SpectatingKeyInfo_Prepass_1_Params { class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.IsCharacterAlive struct UHudMain_C_IsCharacterAlive_Params { bool IsAlive; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.OnToggleInventory struct UHudMain_C_OnToggleInventory_Params { bool Bold; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.On_InventoryShowHiddenCanvas_Prepass_1 struct UHudMain_C_On_InventoryShowHiddenCanvas_Prepass_1_Params { class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.Get_TextBlock_1_Text_1 struct UHudMain_C_Get_TextBlock_1_Text_1_Params { struct FText ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ReturnParm) }; // Function HudMain.HudMain_C.On_OnlySpectating_Prepass_1 struct UHudMain_C_On_OnlySpectating_Prepass_1_Params { class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.OnPrepass_1 struct UHudMain_C_OnPrepass_1_Params { class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.OnPrepass_VisibilityOnMatchState struct UHudMain_C_OnPrepass_VisibilityOnMatchState_Params { class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.On_BaseCanvas_Prepass_1 struct UHudMain_C_On_BaseCanvas_Prepass_1_Params { class UWidget* BoundWidget; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.GetBoostRatio struct UHudMain_C_GetBoostRatio_Params { float ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.OnNitifyHit struct UHudMain_C_OnNitifyHit_Params { float DamagePercent; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) TEnumAsByte<EDamageTypeCategory> DamageTypeCategory; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.Get_ParachuteText_Visibility_1 struct UHudMain_C_Get_ParachuteText_Visibility_1_Params { TEnumAsByte<ESlateVisibility> ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.Get_VisibilityOnMatchState struct UHudMain_C_Get_VisibilityOnMatchState_Params { TEnumAsByte<ESlateVisibility> ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.OnDisplaySystemMessage struct UHudMain_C_OnDisplaySystemMessage_Params { TEnumAsByte<ESystemMessageType> MessageType; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) struct FText Message; // (CPF_Parm) }; // Function HudMain.HudMain_C.OnDisplayKilledMessage struct UHudMain_C_OnDisplayKilledMessage_Params { struct FDeathMessage DeathMessage; // (CPF_Parm) }; // Function HudMain.HudMain_C.OnButtonClick struct UHudMain_C_OnButtonClick_Params { struct FString ButotnName; // (CPF_Parm, CPF_ZeroConstructor) }; // Function HudMain.HudMain_C.Get_HealthBar_FillColorAndOpacity_1 struct UHudMain_C_Get_HealthBar_FillColorAndOpacity_1_Params { struct FLinearColor ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.OnKey_SystemMenuOrEscape struct UHudMain_C_OnKey_SystemMenuOrEscape_Params { }; // Function HudMain.HudMain_C.Get_Vehicle_Health_Ratio struct UHudMain_C_Get_Vehicle_Health_Ratio_Params { float ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.GetFillColorAndOpacity_1 struct UHudMain_C_GetFillColorAndOpacity_1_Params { struct FLinearColor ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.Get_DebugInformation_Text_1 struct UHudMain_C_Get_DebugInformation_Text_1_Params { struct FText ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ReturnParm) }; // Function HudMain.HudMain_C.OnToggleMap struct UHudMain_C_OnToggleMap_Params { }; // Function HudMain.HudMain_C.OnKey_ToggleInventory struct UHudMain_C_OnKey_ToggleInventory_Params { }; // Function HudMain.HudMain_C.Get_PlayerCoordinate_Text_1 struct UHudMain_C_Get_PlayerCoordinate_Text_1_Params { struct FText ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ReturnParm) }; // Function HudMain.HudMain_C.Get_NumPlayersLeft_Text_1 struct UHudMain_C_Get_NumPlayersLeft_Text_1_Params { struct FText ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ReturnParm) }; // Function HudMain.HudMain_C.Get_Health_Text_1 struct UHudMain_C_Get_Health_Text_1_Params { struct FText ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ReturnParm) }; // Function HudMain.HudMain_C.Get_HealthMax_Text_1 struct UHudMain_C_Get_HealthMax_Text_1_Params { struct FText ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ReturnParm) }; // Function HudMain.HudMain_C.GetHpRatio struct UHudMain_C_GetHpRatio_Params { float ReturnValue; // (CPF_Parm, CPF_OutParm, CPF_ZeroConstructor, CPF_ReturnParm, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.OnPossessPawnChange struct UHudMain_C_OnPossessPawnChange_Params { }; // Function HudMain.HudMain_C.InitializeHUD struct UHudMain_C_InitializeHUD_Params { }; // Function HudMain.HudMain_C.Construct struct UHudMain_C_Construct_Params { }; // Function HudMain.HudMain_C.OnShowWidget struct UHudMain_C_OnShowWidget_Params { struct FString WidgetName; // (CPF_Parm, CPF_ZeroConstructor) bool bShow; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.HideMapForInitReplay struct UHudMain_C_HideMapForInitReplay_Params { }; // Function HudMain.HudMain_C.CheckReplayTimer struct UHudMain_C_CheckReplayTimer_Params { }; // Function HudMain.HudMain_C.CreateCheckReplayTimer struct UHudMain_C_CreateCheckReplayTimer_Params { }; // Function HudMain.HudMain_C.Tick struct UHudMain_C_Tick_Params { struct FGeometry* MyGeometry; // (CPF_Parm, CPF_IsPlainOldData) float* InDeltaTime; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.ExecuteUbergraph_HudMain struct UHudMain_C_ExecuteUbergraph_HudMain_Params { int EntryPoint; // (CPF_Parm, CPF_ZeroConstructor, CPF_IsPlainOldData) }; // Function HudMain.HudMain_C.ButtonClickedDispatcher__DelegateSignature struct UHudMain_C_ButtonClickedDispatcher__DelegateSignature_Params { }; } #ifdef _MSC_VER #pragma pack(pop) #endif
248a245ea5251927f865ecebd479e2b0ba4e9ad2
212f1210ab1da799fb26262614edee0cf2c14380
/src/libtcod/sdl2/sdl2_display.cpp
b9bdbfd616b4e7c99e87e9e29e20493cf5e5f823
[]
no_license
MSylvia/libtcod
43ae15408a35d9d583dfe13119e8b8767681914a
f1089129890bbf2d84abed08b73874c129d6ec6f
refs/heads/master
2020-04-04T09:07:29.655093
2018-10-24T23:04:45
2018-10-24T23:04:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,904
cpp
/* libtcod * Copyright © 2008-2018 Jice and the libtcod contributers. * All rights reserved. * * libtcod 'The Doryen library' is a cross-platform C/C++ library for roguelike * developers. * Its source code is available from: * https://github.com/libtcod/libtcod * * 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. * * The name of copyright holder nor the names of its contributors 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 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 "sdl2_display.h" #include <cstdint> #include <stdexcept> #include "../console.h" #include "../libtcod_int.h" #include <SDL.h> namespace tcod { namespace sdl2 { WindowedDisplay::WindowedDisplay(std::pair<int, int> window_size, int window_flags, const std::string& title) { int width = window_size.first; int height = window_size.second; if (width < 0 || height < 0) { throw std::invalid_argument("width and height must be non-negative."); } if (SDL_Init(SDL_INIT_VIDEO | SDL_INIT_EVENTS | SDL_INIT_TIMER)) { throw std::runtime_error(SDL_GetError()); } SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 2); SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 1); window_ = std::shared_ptr<SDL_Window>( SDL_CreateWindow( title.c_str(), SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED, width, height, window_flags), [](SDL_Window* window){ SDL_DestroyWindow(window); }); if (!window_) { throw std::runtime_error(SDL_GetError()); } } void WindowedDisplay::set_title(const std::string title) { if (!window_) { throw std::logic_error("Unresolved class invariant."); } SDL_SetWindowTitle(window_.get(), title.c_str()); } std::string WindowedDisplay::get_title() { if (!window_) { throw std::logic_error("Unresolved class invariant."); } return std::string(SDL_GetWindowTitle(window_.get())); } void WindowedDisplay::set_fullscreen(bool fullscreen) { if (fullscreen) { SDL_SetWindowFullscreen(window_.get(), SDL_WINDOW_FULLSCREEN_DESKTOP); } else { SDL_SetWindowFullscreen(window_.get(), 0); } } int WindowedDisplay::get_fullscreen() { return ((SDL_GetWindowFlags(window_.get()) & (SDL_WINDOW_FULLSCREEN | SDL_WINDOW_FULLSCREEN_DESKTOP)) != 0); } SDL2Display::SDL2Display(std::shared_ptr<Tileset> tileset, std::pair<int, int> window_size, int window_flags, const std::string& title) : WindowedDisplay(window_size, window_flags, title) { // Configure SDL2 renderer. renderer_ = std::shared_ptr<SDL_Renderer>( SDL_CreateRenderer(get_window(), -1, SDL_RENDERER_TARGETTEXTURE), [](SDL_Renderer* renderer){ SDL_DestroyRenderer(renderer); }); if (!renderer_) { throw std::runtime_error(SDL_GetError()); } // Configure libtcod renderer. set_tileset(tileset); } void SDL2Display::set_tileset(std::shared_ptr<Tileset> tileset) { if (!renderer_) { throw std::logic_error("Unresolved class invariant."); } if (!tileset) { throw std::invalid_argument("tileset must not be nullptr."); } tcod_renderer_ = SDL2Renderer(renderer_.get(), tileset); } void SDL2Display::present(const TCOD_Console* console) { if (!renderer_) { throw std::logic_error("Unresolved class invariant."); } SDL_Texture* backbuffer = tcod_renderer_.render(console); SDL_RenderClear(renderer_.get()); SDL_RenderCopy(renderer_.get(), backbuffer, nullptr, nullptr); SDL_RenderPresent(renderer_.get()); } } // namespace sdl2 } // namespace tcod
d7a457738012bac2c7091aeb8e4c0795ed17c6dc
0f46bca9176f453ea28be8a7c91adfdeee4af3e5
/include/dynamics/STVD.h
0b16adcca884298101996bc55ea488a0f65278f2
[]
no_license
PeterZs/RIM
3181baf1b668c719ae55dbc0448228d233083cd4
81639c2f06b969c668f6d187f6cccf5d97a71ba7
refs/heads/master
2022-12-01T04:35:23.344641
2020-08-06T07:29:16
2020-08-06T07:29:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,451
h
/* ******************************************************************************** MIT License Copyright(c) 2019 Christopher Brandt Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files(the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and / or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions : The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ******************************************************************************** */ #pragma once #include <Eigen\Dense> #include <Eigen\Sparse> #include "ProjDynTypeDef.h" #include <queue> #define STVD_MODE_GRAPH_DIJKSTRA 0 #define STVD_MODE_ST_DIJKSTRA 1 #define STVD_DEFAULT_K 10 using namespace PD; typedef std::pair<unsigned int, float> QueVert; class QueVertComp { public: bool operator() (QueVert v1, QueVert v2) { return v1.second > v2.second; } }; class STVD { public: STVD(); void init(PDPositions const& verts, PDTriangles const& tris = PDTriangles(0, 3), PDTets const& tets = PDTets(0, 4)); STVD(PDPositions const& verts, PDTriangles const& tris = PDTriangles(0, 3), PDTets const& tets = PDTets(0, 4)); /* Removes all source points from the mesh. */ void resetSources(); /* Marks a vertex as a source, such that computeDistances() will yield the minimal geodesic distances to this vertex and all other marked vertices. */ void addSource(unsigned int vertexInd); /* Fills the vector distances with per-vertex values that correspond to the geodesic distance to the nearest marked vertex. */ void computeDistances(bool update = false, unsigned int mode = STVD_MODE_GRAPH_DIJKSTRA, PDScalar maxDist = -1); /* Sets all distances to -1 (i.e. infinity), so even if computeDistances is run with update == true, the distances will be new. */ void resetDistances(); /* Returns the current distance of the vector with index vInd to the sources set via addSource. Requires updated distances via computeDistances()! */ double getDistance(unsigned int vInd); PDVector& getDistances(); /* Set the parameter k which defines the size of the short term memory. Only affects the process if the mode is set to STVD_MODE_ST_DIJKSTRA. */ void setK(unsigned int k); private: unsigned int m_numVerts; bool m_forTets; std::vector<unsigned int> m_sources; std::vector<std::vector<unsigned int>> m_neighbours; unsigned int m_k; unsigned int m_mode; bool m_isUpdated; PDVector m_distances; PDPositions m_positions; PDPositions m_outerVertNormals; double updateVertDist(unsigned int v1, unsigned int v2, std::vector<int>& predecessors); };
06ca0d9c5fbb35273341ebee8d7aca5a30185387
6f53e715ab0edeafc89cbf33941228314181c4cb
/Classes/Utility/Config.cpp
2b9c29488278c78c0edced42a89d21aa06319b44
[]
no_license
HuyenPhuong/mini
859a9b4450117ddc6ffea0b723a231d2787ea72e
e3a29eecebb5cdf2b2d5c34c801e17bdab8fdce2
refs/heads/master
2021-01-23T21:35:35.789464
2015-06-26T15:59:28
2015-06-26T15:59:28
38,119,254
0
0
null
null
null
null
UTF-8
C++
false
false
529
cpp
#include "Config.h" Config::Config(){} Config::~Config(){} Vec2 Config::centerPoint = Vec2(0,0); Size Config::screenSize = Size(0, 0); float Config::getScale(Node* p) { float xScale = screenSize.width / p->getContentSize().width; float yScale = screenSize.height / p->getContentSize().height; return max(xScale, yScale); } float Config::getScale(string backgroundFileName) { Sprite* background = Sprite::create(backgroundFileName); float theScale = getScale(background); //background->release(); return theScale; }
[ "huyensoc.mta" ]
huyensoc.mta
89af3058bb78c9bf3c57b0c6a3cf58031eae6a6b
35891e29e295589495a3d4196f59cbf8dddaf3cb
/main.cpp
79303b2d1316ec390fed822d073f8a92bac51645
[]
no_license
dmehrotra/smelly-wifi
de3aef0f56edeb92d449b4c94af755bdf173bbb8
1d17289e8d087ac15035e8613b0935d7632967a6
refs/heads/master
2021-01-13T00:16:53.210693
2016-03-24T23:59:01
2016-03-24T23:59:01
54,681,911
0
0
null
null
null
null
UTF-8
C++
false
false
1,287
cpp
#include <vector> #include <tins.h> //g++ main.cpp -o test -O3 -std=c++11 -lpthread -ltins using namespace Tins; using namespace std; string get_header_from_raw(string header, const RawPDU& rawpdu){ string payL = ""; string content = ""; const RawPDU::payload_type& payload = rawpdu.payload(); for (const auto& bit : payload) { payL += (char) bit; } int pos_header = (int) payL.find(header); if(pos_header != -1){ content = payL.substr(pos_header); int endHeader = (int) content.find("\n"); content = content.substr(0, endHeader - 1); } return content; } int main() { SnifferConfiguration config; config.set_rfmon(true); config.set_promisc_mode(true); Sniffer sniffer("en0", config); while (Packet packet = sniffer.next_packet()) { if (packet.pdu()->find_pdu<Dot11Data>()) { try{ const PDU& pdu = *packet.pdu(); const RawPDU &raw = pdu.rfind_pdu<RawPDU>(); string header = "GET"; cout << get_header_from_raw(header, raw) << endl; } catch(...){} } } }