diff --git a/CMakeLists.txt b/CMakeLists.txt index 5b91d84edf..7b14063f94 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -103,6 +103,11 @@ if(ENABLE_TSAN AND NOT WIN32 AND NOT APPLE AND CMAKE_SIZEOF_VOID_P MATCHES 8) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -fsanitize=thread") endif() +if(MSVC) + # undef min and max macro + target_compile_definitions(rfb PRIVATE NOMINMAX) +endif() + if(NOT DEFINED BUILD_WINVNC) set(BUILD_WINVNC 1) endif() diff --git a/common/CMakeLists.txt b/common/CMakeLists.txt index 6fd1e106c1..96b4e6b744 100644 --- a/common/CMakeLists.txt +++ b/common/CMakeLists.txt @@ -1,4 +1,4 @@ -add_subdirectory(os) +add_subdirectory(core) add_subdirectory(rdr) add_subdirectory(network) add_subdirectory(rfb) @@ -9,6 +9,6 @@ add_subdirectory(rfb) # is passed (additionally, libvnc is not used on Windows.) if(NOT WIN32) - set_target_properties(os rdr network rfb + set_target_properties(core rdr network rfb PROPERTIES COMPILE_FLAGS -fPIC) endif() diff --git a/common/core/CMakeLists.txt b/common/core/CMakeLists.txt new file mode 100644 index 0000000000..c0bd6944c6 --- /dev/null +++ b/common/core/CMakeLists.txt @@ -0,0 +1,36 @@ +add_library(core STATIC + Configuration.cxx + Exception.cxx + Logger.cxx + Logger_file.cxx + Logger_stdio.cxx + LogWriter.cxx + Mutex.cxx + Region.cxx + Timer.cxx + Thread.cxx + string.cxx + time.cxx + xdgdirs.cxx) + +target_include_directories(core PUBLIC ${CMAKE_SOURCE_DIR}/common) +target_include_directories(core SYSTEM PUBLIC ${PIXMAN_INCLUDE_DIRS}) +target_link_libraries(core ${PIXMAN_LIBRARIES}) +target_link_directories(core PUBLIC ${PIXMAN_LIBRARY_DIRS}) + +if(UNIX) + target_sources(core PRIVATE Logger_syslog.cxx) + target_link_libraries(core pthread) +endif() + +if(WIN32) + target_link_libraries(core ws2_32) +endif() + +if(UNIX) + target_sources(core PRIVATE Logger_syslog.cxx) +endif() + +if(UNIX) + libtool_create_control_file(core) +endif() diff --git a/common/rfb/Configuration.cxx b/common/core/Configuration.cxx similarity index 98% rename from common/rfb/Configuration.cxx rename to common/core/Configuration.cxx index 72947df12b..28b1465e16 100644 --- a/common/rfb/Configuration.cxx +++ b/common/core/Configuration.cxx @@ -32,21 +32,19 @@ #include -#include - -#include -#include -#include - -#define LOCK_CONFIG os::AutoMutex a(mutex) +#include +#include +#include +#include #include #include -using namespace rfb; +using namespace core; static LogWriter vlog("Config"); +#define LOCK_CONFIG AutoMutex a(mutex) // -=- The Global/server/viewer Configuration objects Configuration* Configuration::global_ = nullptr; @@ -210,7 +208,7 @@ VoidParameter::VoidParameter(const char* name_, const char* desc_, _next = conf->head; conf->head = this; - mutex = new os::Mutex(); + mutex = new Mutex(); } VoidParameter::~VoidParameter() { diff --git a/common/rfb/Configuration.h b/common/core/Configuration.h similarity index 98% rename from common/rfb/Configuration.h rename to common/core/Configuration.h index ec8d789aa2..837b4aeb8e 100644 --- a/common/rfb/Configuration.h +++ b/common/core/Configuration.h @@ -41,8 +41,8 @@ // NB: NO LOCKING is performed when linking Configurations to groups // or when adding Parameters to Configurations. -#ifndef __RFB_CONFIGURATION_H__ -#define __RFB_CONFIGURATION_H__ +#ifndef __CORE_CONFIGURATION_H__ +#define __CORE_CONFIGURATION_H__ #include #include @@ -50,9 +50,9 @@ #include #include -namespace os { class Mutex; } +namespace core { -namespace rfb { + class Mutex; class VoidParameter; struct ParameterIterator; @@ -189,7 +189,7 @@ namespace rfb { const char* name; const char* description; - os::Mutex* mutex; + Mutex* mutex; }; class AliasParameter : public VoidParameter { @@ -297,4 +297,4 @@ namespace rfb { }; -#endif // __RFB_CONFIGURATION_H__ +#endif // __CORE_CONFIGURATION_H__ diff --git a/common/rdr/Exception.cxx b/common/core/Exception.cxx similarity index 76% rename from common/rdr/Exception.cxx rename to common/core/Exception.cxx index f0c04a6a66..5b4f059978 100644 --- a/common/rdr/Exception.cxx +++ b/common/core/Exception.cxx @@ -26,9 +26,8 @@ #include #include -#include -#include -#include +#include +#include #ifdef _WIN32 #include @@ -40,20 +39,20 @@ #include -using namespace rdr; +using namespace core; getaddrinfo_error::getaddrinfo_error(const char* s, int err_) noexcept - : std::runtime_error(rfb::format("%s: %s (%d)", s, - strerror(err_).c_str(), err_)), + : std::runtime_error(core::format("%s: %s (%d)", s, + strerror(err_).c_str(), err_)), err(err_) { } getaddrinfo_error::getaddrinfo_error(const std::string& s, int err_) noexcept - : std::runtime_error(rfb::format("%s: %s (%d)", s.c_str(), - strerror(err_).c_str(), err_)), + : std::runtime_error(core::format("%s: %s (%d)", s.c_str(), + strerror(err_).c_str(), err_)), err(err_) { } @@ -73,15 +72,15 @@ std::string getaddrinfo_error::strerror(int err_) const noexcept } posix_error::posix_error(const char* what_arg, int err_) noexcept - : std::runtime_error(rfb::format("%s: %s (%d)", what_arg, - strerror(err_).c_str(), err_)), + : std::runtime_error(core::format("%s: %s (%d)", what_arg, + strerror(err_).c_str(), err_)), err(err_) { } posix_error::posix_error(const std::string& what_arg, int err_) noexcept - : std::runtime_error(rfb::format("%s: %s (%d)", what_arg.c_str(), - strerror(err_).c_str(), err_)), + : std::runtime_error(core::format("%s: %s (%d)", what_arg.c_str(), + strerror(err_).c_str(), err_)), err(err_) { } @@ -102,16 +101,16 @@ std::string posix_error::strerror(int err_) const noexcept #ifdef WIN32 win32_error::win32_error(const char* what_arg, unsigned err_) noexcept - : std::runtime_error(rfb::format("%s: %s (%d)", what_arg, - strerror(err_).c_str(), err_)), + : std::runtime_error(core::format("%s: %s (%d)", what_arg, + strerror(err_).c_str(), err_)), err(err_) { } win32_error::win32_error(const std::string& what_arg, unsigned err_) noexcept - : std::runtime_error(rfb::format("%s: %s (%d)", what_arg.c_str(), - strerror(err_).c_str(), err_)), + : std::runtime_error(core::format("%s: %s (%d)", what_arg.c_str(), + strerror(err_).c_str(), err_)), err(err_) { } diff --git a/common/rdr/Exception.h b/common/core/Exception.h similarity index 91% rename from common/rdr/Exception.h rename to common/core/Exception.h index d3cecc18a6..04463a1741 100644 --- a/common/rdr/Exception.h +++ b/common/core/Exception.h @@ -19,13 +19,13 @@ * USA. */ -#ifndef __RDR_EXCEPTION_H__ -#define __RDR_EXCEPTION_H__ +#ifndef __CORE_EXCEPTION_H__ +#define __CORE_EXCEPTION_H__ #include #include -namespace rdr { +namespace core { class posix_error : public std::runtime_error { public: @@ -70,11 +70,6 @@ namespace rdr { std::string strerror(int err_) const noexcept; }; - class end_of_stream : public std::runtime_error { - public: - end_of_stream() noexcept : std::runtime_error("End of stream") {} - }; - } #endif diff --git a/common/rfb/LogWriter.cxx b/common/core/LogWriter.cxx similarity index 96% rename from common/rfb/LogWriter.cxx rename to common/core/LogWriter.cxx index 8e39d5443b..c21a5d5bcd 100644 --- a/common/rfb/LogWriter.cxx +++ b/common/core/LogWriter.cxx @@ -22,17 +22,16 @@ #include #endif -#include - -#include -#include -#include #include +#include -rfb::LogParameter rfb::logParams; +#include +#include +#include -using namespace rfb; +using namespace core; +LogParameter core::logParams; LogWriter::LogWriter(const char* name) : m_name(name), m_level(0), m_log(nullptr), m_next(log_writers) { diff --git a/common/rfb/LogWriter.h b/common/core/LogWriter.h similarity index 94% rename from common/rfb/LogWriter.h rename to common/core/LogWriter.h index d1fd499049..6aa57c2cd9 100644 --- a/common/rfb/LogWriter.h +++ b/common/core/LogWriter.h @@ -18,12 +18,13 @@ // -=- LogWriter.h - The Log writer class. -#ifndef __RFB_LOG_WRITER_H__ -#define __RFB_LOG_WRITER_H__ +#ifndef __CORE_LOG_WRITER_H__ +#define __CORE_LOG_WRITER_H__ #include -#include -#include + +#include +#include // Each log writer instance has a unique textual name, // and is attached to a particular Log instance and @@ -46,9 +47,7 @@ } \ } -namespace rfb { - - class LogWriter; +namespace core { class LogWriter { public: @@ -110,4 +109,4 @@ namespace rfb { }; -#endif // __RFB_LOG_WRITER_H__ +#endif // __CORE_LOG_WRITER_H__ diff --git a/common/rfb/Logger.cxx b/common/core/Logger.cxx similarity index 96% rename from common/rfb/Logger.cxx rename to common/core/Logger.cxx index 25f7ccb7c7..ad9a3d6354 100644 --- a/common/rfb/Logger.cxx +++ b/common/core/Logger.cxx @@ -26,10 +26,10 @@ #include #include -#include -#include +#include +#include -using namespace rfb; +using namespace core; Logger* Logger::loggers = nullptr; diff --git a/common/rfb/Logger.h b/common/core/Logger.h similarity index 94% rename from common/rfb/Logger.h rename to common/core/Logger.h index 76f03535cd..5291915f80 100644 --- a/common/rfb/Logger.h +++ b/common/core/Logger.h @@ -18,8 +18,8 @@ // -=- Logger.h - The Logger class. -#ifndef __RFB_LOGGER_H__ -#define __RFB_LOGGER_H__ +#ifndef __CORE_LOGGER_H__ +#define __CORE_LOGGER_H__ #include #include @@ -28,7 +28,7 @@ // and is attached to a particular Logger instance and // is assigned a particular log level. -namespace rfb { +namespace core { class Logger { public: @@ -68,4 +68,4 @@ namespace rfb { }; -#endif // __RFB_LOGGER_H__ +#endif // __CORE_LOGGER_H__ diff --git a/common/rfb/Logger_file.cxx b/common/core/Logger_file.cxx similarity index 94% rename from common/rfb/Logger_file.cxx rename to common/core/Logger_file.cxx index eabe420a44..64014be9c8 100644 --- a/common/rfb/Logger_file.cxx +++ b/common/core/Logger_file.cxx @@ -26,18 +26,17 @@ #include #include -#include +#include +#include -#include - -using namespace rfb; +using namespace core; Logger_File::Logger_File(const char* loggerName) : Logger(loggerName), indent(13), width(79), m_file(nullptr), m_lastLogTime(0) { m_filename[0] = '\0'; - mutex = new os::Mutex(); + mutex = new Mutex(); } Logger_File::~Logger_File() @@ -48,7 +47,7 @@ Logger_File::~Logger_File() void Logger_File::write(int /*level*/, const char *logname, const char *message) { - os::AutoMutex a(mutex); + AutoMutex a(mutex); if (!m_file) { if (m_filename[0] == '\0') @@ -121,7 +120,8 @@ void Logger_File::closeFile() static Logger_File logger("file"); -bool rfb::initFileLogger(const char* filename) { +bool core::initFileLogger(const char* filename) +{ logger.setFilename(filename); logger.registerLogger(); return true; diff --git a/common/rfb/Logger_file.h b/common/core/Logger_file.h similarity index 89% rename from common/rfb/Logger_file.h rename to common/core/Logger_file.h index 6f2a4ef653..f7a5bf748e 100644 --- a/common/rfb/Logger_file.h +++ b/common/core/Logger_file.h @@ -18,17 +18,17 @@ // -=- Logger_file - log to a file -#ifndef __RFB_LOGGER_FILE_H__ -#define __RFB_LOGGER_FILE_H__ +#ifndef __CORE_LOGGER_FILE_H__ +#define __CORE_LOGGER_FILE_H__ #include #include -#include +#include -namespace os { class Mutex; } +namespace core { -namespace rfb { + class Mutex; class Logger_File : public Logger { public: @@ -47,10 +47,11 @@ namespace rfb { char m_filename[PATH_MAX]; FILE* m_file; time_t m_lastLogTime; - os::Mutex* mutex; + Mutex* mutex; }; bool initFileLogger(const char* filename); + }; #endif diff --git a/common/rfb/Logger_stdio.cxx b/common/core/Logger_stdio.cxx similarity index 92% rename from common/rfb/Logger_stdio.cxx rename to common/core/Logger_stdio.cxx index 5e5c6dea93..f27fc35d0e 100644 --- a/common/rfb/Logger_stdio.cxx +++ b/common/core/Logger_stdio.cxx @@ -22,14 +22,15 @@ #include #endif -#include +#include -using namespace rfb; +using namespace core; static Logger_StdIO logStdErr("stderr", stderr); static Logger_StdIO logStdOut("stdout", stdout); -bool rfb::initStdIOLoggers() { +bool core::initStdIOLoggers() +{ logStdErr.registerLogger(); logStdOut.registerLogger(); return true; diff --git a/common/rfb/Logger_stdio.h b/common/core/Logger_stdio.h similarity index 90% rename from common/rfb/Logger_stdio.h rename to common/core/Logger_stdio.h index a1d17a0fa7..7613a20b53 100644 --- a/common/rfb/Logger_stdio.h +++ b/common/core/Logger_stdio.h @@ -18,12 +18,12 @@ // -=- Logger_stdio - standard output logger instances -#ifndef __RFB_LOGGER_STDIO_H__ -#define __RFB_LOGGER_STDIO_H__ +#ifndef __CORE_LOGGER_STDIO_H__ +#define __CORE_LOGGER_STDIO_H__ -#include +#include -namespace rfb { +namespace core { class Logger_StdIO : public Logger_File { public: diff --git a/common/rfb/Logger_syslog.cxx b/common/core/Logger_syslog.cxx similarity index 93% rename from common/rfb/Logger_syslog.cxx rename to common/core/Logger_syslog.cxx index de9e425e2c..cf7d065db7 100644 --- a/common/rfb/Logger_syslog.cxx +++ b/common/core/Logger_syslog.cxx @@ -26,10 +26,10 @@ #include #include -#include -#include +#include +#include -using namespace rfb; +using namespace core; Logger_Syslog::Logger_Syslog(const char* loggerName) @@ -62,6 +62,7 @@ void Logger_Syslog::write(int level, const char *logname, const char *message) static Logger_Syslog logger("syslog"); -void rfb::initSyslogLogger() { +void core::initSyslogLogger() +{ logger.registerLogger(); } diff --git a/common/rfb/Logger_syslog.h b/common/core/Logger_syslog.h similarity index 90% rename from common/rfb/Logger_syslog.h rename to common/core/Logger_syslog.h index 20c46a5f66..46adf9328f 100644 --- a/common/rfb/Logger_syslog.h +++ b/common/core/Logger_syslog.h @@ -18,13 +18,14 @@ // -=- Logger_syslog - log to syslog -#ifndef __RFB_LOGGER_SYSLOG_H__ -#define __RFB_LOGGER_SYSLOG_H__ +#ifndef __CORE_LOGGER_SYSLOG_H__ +#define __CORE_LOGGER_SYSLOG_H__ #include -#include -namespace rfb { +#include + +namespace core { class Logger_Syslog : public Logger { public: diff --git a/common/os/Mutex.cxx b/common/core/Mutex.cxx similarity index 83% rename from common/os/Mutex.cxx rename to common/core/Mutex.cxx index 1889e66b43..6f72581e29 100644 --- a/common/os/Mutex.cxx +++ b/common/core/Mutex.cxx @@ -26,11 +26,10 @@ #include #endif -#include +#include +#include -#include - -using namespace os; +using namespace core; Mutex::Mutex() { @@ -43,7 +42,7 @@ Mutex::Mutex() systemMutex = new pthread_mutex_t; ret = pthread_mutex_init((pthread_mutex_t*)systemMutex, nullptr); if (ret != 0) - throw rdr::posix_error("Failed to create mutex", ret); + throw posix_error("Failed to create mutex", ret); #endif } @@ -67,7 +66,7 @@ void Mutex::lock() ret = pthread_mutex_lock((pthread_mutex_t*)systemMutex); if (ret != 0) - throw rdr::posix_error("Failed to lock mutex", ret); + throw posix_error("Failed to lock mutex", ret); #endif } @@ -80,7 +79,7 @@ void Mutex::unlock() ret = pthread_mutex_unlock((pthread_mutex_t*)systemMutex); if (ret != 0) - throw rdr::posix_error("Failed to unlock mutex", ret); + throw posix_error("Failed to unlock mutex", ret); #endif } @@ -97,7 +96,7 @@ Condition::Condition(Mutex* mutex_) systemCondition = new pthread_cond_t; ret = pthread_cond_init((pthread_cond_t*)systemCondition, nullptr); if (ret != 0) - throw rdr::posix_error("Failed to create condition variable", ret); + throw posix_error("Failed to create condition variable", ret); #endif } @@ -120,14 +119,14 @@ void Condition::wait() (CRITICAL_SECTION*)mutex->systemMutex, INFINITE); if (!ret) - throw rdr::win32_error("Failed to wait on condition variable", GetLastError()); + throw win32_error("Failed to wait on condition variable", GetLastError()); #else int ret; ret = pthread_cond_wait((pthread_cond_t*)systemCondition, (pthread_mutex_t*)mutex->systemMutex); if (ret != 0) - throw rdr::posix_error("Failed to wait on condition variable", ret); + throw posix_error("Failed to wait on condition variable", ret); #endif } @@ -140,7 +139,7 @@ void Condition::signal() ret = pthread_cond_signal((pthread_cond_t*)systemCondition); if (ret != 0) - throw rdr::posix_error("Failed to signal condition variable", ret); + throw posix_error("Failed to signal condition variable", ret); #endif } @@ -153,6 +152,6 @@ void Condition::broadcast() ret = pthread_cond_broadcast((pthread_cond_t*)systemCondition); if (ret != 0) - throw rdr::posix_error("Failed to broadcast condition variable", ret); + throw posix_error("Failed to broadcast condition variable", ret); #endif } diff --git a/common/os/Mutex.h b/common/core/Mutex.h similarity index 95% rename from common/os/Mutex.h rename to common/core/Mutex.h index 63c7e0cc02..17a97d1ba0 100644 --- a/common/os/Mutex.h +++ b/common/core/Mutex.h @@ -16,10 +16,10 @@ * USA. */ -#ifndef __OS_MUTEX_H__ -#define __OS_MUTEX_H__ +#ifndef __CORE_MUTEX_H__ +#define __CORE_MUTEX_H__ -namespace os { +namespace core { class Condition; class Mutex { diff --git a/common/rfb/Rect.h b/common/core/Rect.h similarity index 79% rename from common/rfb/Rect.h rename to common/core/Rect.h index b82ed2741f..e4cb1634b7 100644 --- a/common/rfb/Rect.h +++ b/common/core/Rect.h @@ -16,26 +16,16 @@ * USA. */ -// rfb::Rect and rfb::Point structures +// core::Rect and core::Point structures -#ifndef __RFB_RECT_INCLUDED__ -#define __RFB_RECT_INCLUDED__ +#ifndef __CORE_RECT_INCLUDED__ +#define __CORE_RECT_INCLUDED__ -// Some platforms (e.g. Windows) include max() and min() macros in their -// standard headers, but they are also standard C++ template functions, so some -// C++ headers will undefine them. So we steer clear of the names min and max -// and define __rfbmin and __rfbmax instead. +#include -#ifndef __rfbmax -#define __rfbmax(a,b) (((a) > (b)) ? (a) : (b)) -#endif -#ifndef __rfbmin -#define __rfbmin(a,b) (((a) < (b)) ? (a) : (b)) -#endif +namespace core { -namespace rfb { - - // rfb::Point + // core::Point // // Represents a point in 2D space, by X and Y coordinates. // Can also be used to represent a delta, or offset, between @@ -61,7 +51,7 @@ namespace rfb { int x, y; }; - // rfb::Rect + // core::Rect // // Represents a rectangular region defined by its top-left (tl) // and bottom-right (br) Points. @@ -83,10 +73,10 @@ namespace rfb { __attribute__ ((warn_unused_result)) { Rect result; - result.tl.x = __rfbmax(tl.x, r.tl.x); - result.tl.y = __rfbmax(tl.y, r.tl.y); - result.br.x = __rfbmax(__rfbmin(br.x, r.br.x), result.tl.x); - result.br.y = __rfbmax(__rfbmin(br.y, r.br.y), result.tl.y); + result.tl.x = std::max(tl.x, r.tl.x); + result.tl.y = std::max(tl.y, r.tl.y); + result.br.x = std::max(std::min(br.x, r.br.x), result.tl.x); + result.br.y = std::max(std::min(br.y, r.br.y), result.tl.y); return result; } inline Rect union_boundary(const Rect &r) const @@ -95,10 +85,10 @@ namespace rfb { if (r.is_empty()) return *this; if (is_empty()) return r; Rect result; - result.tl.x = __rfbmin(tl.x, r.tl.x); - result.tl.y = __rfbmin(tl.y, r.tl.y); - result.br.x = __rfbmax(br.x, r.br.x); - result.br.y = __rfbmax(br.y, r.br.y); + result.tl.x = std::min(tl.x, r.tl.x); + result.tl.y = std::min(tl.y, r.tl.y); + result.br.x = std::max(br.x, r.br.x); + result.br.y = std::max(br.y, r.br.y); return result; } inline Rect translate(const Point &p) const @@ -127,4 +117,4 @@ namespace rfb { Point br; }; } -#endif // __RFB_RECT_INCLUDED__ +#endif // __CORE_RECT_INCLUDED__ diff --git a/common/rfb/Region.cxx b/common/core/Region.cxx similarity index 74% rename from common/rfb/Region.cxx rename to common/core/Region.cxx index cfdf0ca2a1..03d788a9a8 100644 --- a/common/rfb/Region.cxx +++ b/common/core/Region.cxx @@ -21,100 +21,119 @@ #include #endif -#include -#include +#include +#include extern "C" { #include } -static rfb::LogWriter vlog("Region"); +using namespace core; -rfb::Region::Region() { +static LogWriter vlog("Region"); + +Region::Region() +{ rgn = new struct pixman_region16; pixman_region_init(rgn); } -rfb::Region::Region(const Rect& r) { +Region::Region(const Rect& r) +{ rgn = new struct pixman_region16; pixman_region_init_rect(rgn, r.tl.x, r.tl.y, r.width(), r.height()); } -rfb::Region::Region(const rfb::Region& r) { +Region::Region(const Region& r) +{ rgn = new struct pixman_region16; pixman_region_init(rgn); pixman_region_copy(rgn, r.rgn); } -rfb::Region::~Region() { +Region::~Region() +{ pixman_region_fini(rgn); delete rgn; } -rfb::Region& rfb::Region::operator=(const rfb::Region& r) { +Region& Region::operator=(const Region& r) +{ pixman_region_copy(rgn, r.rgn); return *this; } -void rfb::Region::clear() { +void Region::clear() +{ // pixman_region_clear() isn't available on some older systems pixman_region_fini(rgn); pixman_region_init(rgn); } -void rfb::Region::reset(const Rect& r) { +void Region::reset(const Rect& r) +{ pixman_region_fini(rgn); pixman_region_init_rect(rgn, r.tl.x, r.tl.y, r.width(), r.height()); } -void rfb::Region::translate(const Point& delta) { +void Region::translate(const Point& delta) +{ pixman_region_translate(rgn, delta.x, delta.y); } -void rfb::Region::assign_intersect(const rfb::Region& r) { +void Region::assign_intersect(const Region& r) +{ pixman_region_intersect(rgn, rgn, r.rgn); } -void rfb::Region::assign_union(const rfb::Region& r) { +void Region::assign_union(const Region& r) +{ pixman_region_union(rgn, rgn, r.rgn); } -void rfb::Region::assign_subtract(const rfb::Region& r) { +void Region::assign_subtract(const Region& r) +{ pixman_region_subtract(rgn, rgn, r.rgn); } -rfb::Region rfb::Region::intersect(const rfb::Region& r) const { - rfb::Region ret; +Region Region::intersect(const Region& r) const +{ + Region ret; pixman_region_intersect(ret.rgn, rgn, r.rgn); return ret; } -rfb::Region rfb::Region::union_(const rfb::Region& r) const { - rfb::Region ret; +Region Region::union_(const Region& r) const +{ + Region ret; pixman_region_union(ret.rgn, rgn, r.rgn); return ret; } -rfb::Region rfb::Region::subtract(const rfb::Region& r) const { - rfb::Region ret; +Region Region::subtract(const Region& r) const +{ + Region ret; pixman_region_subtract(ret.rgn, rgn, r.rgn); return ret; } -bool rfb::Region::operator==(const rfb::Region& r) const { +bool Region::operator==(const Region& r) const +{ return pixman_region_equal(rgn, r.rgn); } -bool rfb::Region::operator!=(const rfb::Region& r) const { +bool Region::operator!=(const Region& r) const +{ return !pixman_region_equal(rgn, r.rgn); } -int rfb::Region::numRects() const { +int Region::numRects() const +{ return pixman_region_n_rects(rgn); } -bool rfb::Region::get_rects(std::vector* rects, - bool left2right, bool topdown) const +bool Region::get_rects(std::vector* rects, + bool left2right, bool topdown) const { int nRects; const pixman_box16_t* boxes; @@ -156,14 +175,15 @@ bool rfb::Region::get_rects(std::vector* rects, return !rects->empty(); } -rfb::Rect rfb::Region::get_bounding_rect() const { +Rect Region::get_bounding_rect() const +{ const pixman_box16_t* extents; extents = pixman_region_extents(rgn); return Rect(extents->x1, extents->y1, extents->x2, extents->y2); } -void rfb::Region::debug_print(const char* prefix) const +void Region::debug_print(const char* prefix) const { Rect extents; std::vector rects; diff --git a/common/rfb/Region.h b/common/core/Region.h similarity index 90% rename from common/rfb/Region.h rename to common/core/Region.h index 38de67ce7f..729f14754a 100644 --- a/common/rfb/Region.h +++ b/common/core/Region.h @@ -19,15 +19,19 @@ // Region class wrapper around pixman's region operations -#ifndef __RFB_REGION_INCLUDED__ -#define __RFB_REGION_INCLUDED__ +#ifndef __CORE_REGION_INCLUDED__ +#define __CORE_REGION_INCLUDED__ -#include #include +#include + struct pixman_region16; -namespace rfb { +namespace core { + + struct Point; + struct Rect; class Region { public: @@ -45,7 +49,7 @@ namespace rfb { void clear(); void reset(const Rect& r); - void translate(const rfb::Point& delta); + void translate(const Point& delta); void assign_intersect(const Region& r); void assign_union(const Region& r); @@ -78,4 +82,4 @@ namespace rfb { }; -#endif // __RFB_REGION_INCLUDED__ +#endif // __CORE_REGION_INCLUDED__ diff --git a/common/os/Thread.cxx b/common/core/Thread.cxx similarity index 87% rename from common/os/Thread.cxx rename to common/core/Thread.cxx index 6dca75a1d1..be518cd4e8 100644 --- a/common/os/Thread.cxx +++ b/common/core/Thread.cxx @@ -28,12 +28,11 @@ #include #endif -#include +#include +#include +#include -#include -#include - -using namespace os; +using namespace core; Thread::Thread() : running(false), threadId(nullptr) { @@ -66,7 +65,7 @@ void Thread::start() #ifdef WIN32 *(HANDLE*)threadId = CreateThread(nullptr, 0, startRoutine, this, 0, nullptr); if (*(HANDLE*)threadId == nullptr) - throw rdr::win32_error("Failed to create thread", GetLastError()); + throw win32_error("Failed to create thread", GetLastError()); #else int ret; sigset_t all, old; @@ -76,14 +75,14 @@ void Thread::start() sigfillset(&all); ret = pthread_sigmask(SIG_SETMASK, &all, &old); if (ret != 0) - throw rdr::posix_error("Failed to mask signals", ret); + throw posix_error("Failed to mask signals", ret); ret = pthread_create((pthread_t*)threadId, nullptr, startRoutine, this); pthread_sigmask(SIG_SETMASK, &old, nullptr); if (ret != 0) - throw rdr::posix_error("Failed to create thread", ret); + throw posix_error("Failed to create thread", ret); #endif running = true; @@ -99,13 +98,13 @@ void Thread::wait() ret = WaitForSingleObject(*(HANDLE*)threadId, INFINITE); if (ret != WAIT_OBJECT_0) - throw rdr::win32_error("Failed to join thread", GetLastError()); + throw win32_error("Failed to join thread", GetLastError()); #else int ret; ret = pthread_join(*(pthread_t*)threadId, nullptr); if (ret != 0) - throw rdr::posix_error("Failed to join thread", ret); + throw posix_error("Failed to join thread", ret); #endif } diff --git a/common/os/Thread.h b/common/core/Thread.h similarity index 94% rename from common/os/Thread.h rename to common/core/Thread.h index 4c39884b4f..53c5ef180a 100644 --- a/common/os/Thread.h +++ b/common/core/Thread.h @@ -16,12 +16,12 @@ * USA. */ -#ifndef __OS_THREAD_H__ -#define __OS_THREAD_H__ +#ifndef __CORE_THREAD_H__ +#define __CORE_THREAD_H__ #include -namespace os { +namespace core { class Mutex; class Thread { diff --git a/common/rfb/Timer.cxx b/common/core/Timer.cxx similarity index 81% rename from common/rfb/Timer.cxx rename to common/core/Timer.cxx index 6f7ec7ba50..77e98daf17 100644 --- a/common/rfb/Timer.cxx +++ b/common/core/Timer.cxx @@ -28,38 +28,16 @@ #include -#include -#include -#include +#include +#include +#include -using namespace rfb; +using namespace core; #ifndef __NO_DEFINE_VLOG__ static LogWriter vlog("Timer"); #endif - -// Millisecond timeout processing helper functions - -inline static timeval addMillis(timeval inTime, int millis) { - int secs = millis / 1000; - millis = millis % 1000; - inTime.tv_sec += secs; - inTime.tv_usec += millis * 1000; - if (inTime.tv_usec >= 1000000) { - inTime.tv_sec++; - inTime.tv_usec -= 1000000; - } - return inTime; -} - -inline static int diffTimeMillis(timeval later, timeval earlier) { - long udiff; - udiff = ((later.tv_sec - earlier.tv_sec) * 1000000) + - (later.tv_usec - earlier.tv_usec); - return (udiff + 999) / 1000; -} - std::list Timer::pending; int Timer::checkTimeouts() { @@ -167,9 +145,7 @@ int Timer::getTimeoutMs() { } int Timer::getRemainingMs() { - timeval now; - gettimeofday(&now, nullptr); - return __rfbmax(0, diffTimeMillis(dueTime, now)); + return msUntil(&dueTime); } bool Timer::isBefore(timeval other) { diff --git a/common/rfb/Timer.h b/common/core/Timer.h similarity index 98% rename from common/rfb/Timer.h rename to common/core/Timer.h index 362cb84ee8..cde672b24c 100644 --- a/common/rfb/Timer.h +++ b/common/core/Timer.h @@ -17,13 +17,13 @@ * USA. */ -#ifndef __RFB_TIMER_H__ -#define __RFB_TIMER_H__ +#ifndef __CORE_TIMER_H__ +#define __CORE_TIMER_H__ #include #include -namespace rfb { +namespace core { /* Timer diff --git a/common/rfb/util.cxx b/common/core/string.cxx similarity index 94% rename from common/rfb/util.cxx rename to common/core/string.cxx index 3c62b1dfb9..49501a9fd7 100644 --- a/common/rfb/util.cxx +++ b/common/core/string.cxx @@ -26,11 +26,10 @@ #include #include #include -#include -#include +#include -namespace rfb { +namespace core { std::string format(const char *fmt, ...) { @@ -604,40 +603,6 @@ namespace rfb { return true; } - unsigned msBetween(const struct timeval *first, - const struct timeval *second) - { - unsigned diff; - - diff = (second->tv_sec - first->tv_sec) * 1000; - - diff += second->tv_usec / 1000; - diff -= first->tv_usec / 1000; - - return diff; - } - - unsigned msSince(const struct timeval *then) - { - struct timeval now; - - gettimeofday(&now, nullptr); - - return msBetween(then, &now); - } - - bool isBefore(const struct timeval *first, - const struct timeval *second) - { - if (first->tv_sec < second->tv_sec) - return true; - if (first->tv_sec > second->tv_sec) - return false; - if (first->tv_usec < second->tv_usec) - return true; - return false; - } - static std::string doPrefix(long long value, const char *unit, unsigned divisor, const char **prefixes, size_t prefixCount, int precision) { diff --git a/common/rfb/util.h b/common/core/string.h similarity index 67% rename from common/rfb/util.h rename to common/core/string.h index b47ac4c9de..1465484d37 100644 --- a/common/rfb/util.h +++ b/common/core/string.h @@ -18,21 +18,18 @@ */ // -// util.h - miscellaneous useful bits +// string.h - string utility functions // -#ifndef __RFB_UTIL_H__ -#define __RFB_UTIL_H__ +#ifndef __CORE_STRING_H__ +#define __CORE_STRING_H__ -#include #include #include #include -struct timeval; - -namespace rfb { +namespace core { // Formats according to printf(), with a dynamic allocation std::string format(const char *fmt, ...) @@ -71,24 +68,8 @@ namespace rfb { bool isValidUTF8(const char* str, size_t bytes = (size_t)-1); bool isValidUTF16(const wchar_t* wstr, size_t units = (size_t)-1); - // HELPER functions for timeout handling - - // secsToMillis() turns seconds into milliseconds, capping the value so it - // can't wrap round and become -ve - inline int secsToMillis(int secs) { - return (secs < 0 || secs > (INT_MAX/1000) ? INT_MAX : secs * 1000); - } - - // Returns time elapsed between two moments in milliseconds. - unsigned msBetween(const struct timeval *first, - const struct timeval *second); - - // Returns time elapsed since given moment in milliseconds. - unsigned msSince(const struct timeval *then); - - // Returns true if first happened before seconds - bool isBefore(const struct timeval *first, - const struct timeval *second); + // Convert a value to a string using the correct prefix to reduce + // the length of the string std::string siPrefix(long long value, const char *unit, int precision=6); @@ -96,16 +77,4 @@ namespace rfb { int precision=6); } -// Some platforms (e.g. Windows) include max() and min() macros in their -// standard headers, but they are also standard C++ template functions, so some -// C++ headers will undefine them. So we steer clear of the names min and max -// and define __rfbmin and __rfbmax instead. - -#ifndef __rfbmax -#define __rfbmax(a,b) (((a) > (b)) ? (a) : (b)) -#endif -#ifndef __rfbmin -#define __rfbmin(a,b) (((a) < (b)) ? (a) : (b)) -#endif - #endif diff --git a/common/core/time.cxx b/common/core/time.cxx new file mode 100644 index 0000000000..47a0ff8ad6 --- /dev/null +++ b/common/core/time.cxx @@ -0,0 +1,88 @@ +/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. + * Copyright 2011-2019 Pierre Ossman for Cendio AB + * + * This is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this software; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, + * USA. + */ + +#ifdef HAVE_CONFIG_H +#include +#endif + +#include +#include + +#include + +namespace core { + + unsigned msBetween(const struct timeval *first, + const struct timeval *second) + { + unsigned udiff; + + if (isBefore(second, first)) + return 0; + + udiff = (second->tv_sec - first->tv_sec) * 1000000 + + (second->tv_usec - first->tv_usec); + + return (udiff + 999) / 1000; + } + + unsigned msSince(const struct timeval *then) + { + struct timeval now; + + gettimeofday(&now, nullptr); + + return msBetween(then, &now); + } + + unsigned msUntil(const struct timeval *then) + { + struct timeval now; + + gettimeofday(&now, nullptr); + + return msBetween(&now, then); + } + + bool isBefore(const struct timeval *first, + const struct timeval *second) + { + if (first->tv_sec < second->tv_sec) + return true; + if (first->tv_sec > second->tv_sec) + return false; + if (first->tv_usec < second->tv_usec) + return true; + return false; + } + + struct timeval addMillis(struct timeval inTime, int millis) + { + int secs = millis / 1000; + millis = millis % 1000; + inTime.tv_sec += secs; + inTime.tv_usec += millis * 1000; + if (inTime.tv_usec >= 1000000) { + inTime.tv_sec++; + inTime.tv_usec -= 1000000; + } + return inTime; + } + +} diff --git a/common/core/time.h b/common/core/time.h new file mode 100644 index 0000000000..319f336f04 --- /dev/null +++ b/common/core/time.h @@ -0,0 +1,58 @@ +/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. + * Copyright 2011-2019 Pierre Ossman for Cendio AB + * + * This is free software; you can redistribute it and/or modify + * it under the terms of the GNU General Public License as published by + * the Free Software Foundation; either version 2 of the License, or + * (at your option) any later version. + * + * This software is distributed in the hope that it will be useful, + * but WITHOUT ANY WARRANTY; without even the implied warranty of + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + * GNU General Public License for more details. + * + * You should have received a copy of the GNU General Public License + * along with this software; if not, write to the Free Software + * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, + * USA. + */ + +// +// time.h - time helper functions +// + +#ifndef __CORE_TIME_H__ +#define __CORE_TIME_H__ + +#include + +struct timeval; + +namespace core { + + // secsToMillis() turns seconds into milliseconds, capping the value so it + // can't wrap round and become -ve + inline int secsToMillis(int secs) { + return (secs < 0 || secs > (INT_MAX/1000) ? INT_MAX : secs * 1000); + } + + // Returns time elapsed between two moments in milliseconds. + unsigned msBetween(const struct timeval *first, + const struct timeval *second); + + // Returns time elapsed since given moment in milliseconds. + unsigned msSince(const struct timeval *then); + + // Returns time until the given moment in milliseconds. + unsigned msUntil(const struct timeval *then); + + // Returns true if first happened before seconds + bool isBefore(const struct timeval *first, + const struct timeval *second); + + // Returns a new timeval a specified number of milliseconds later than + // the given timeval + struct timeval addMillis(struct timeval inTime, int millis); +} + +#endif diff --git a/common/os/winerrno.h b/common/core/winerrno.h similarity index 100% rename from common/os/winerrno.h rename to common/core/winerrno.h diff --git a/common/os/os.cxx b/common/core/xdgdirs.cxx similarity index 94% rename from common/os/os.cxx rename to common/core/xdgdirs.cxx index 2ac70550ee..2628f317b5 100644 --- a/common/os/os.cxx +++ b/common/core/xdgdirs.cxx @@ -21,8 +21,6 @@ #include #endif -#include - #include #include #include @@ -43,6 +41,8 @@ #define mkdir(path, mode) mkdir(path) #endif +#include + static const char* getvncdir(bool userDir, const char *xdg_env, const char *xdg_def) { static char dir[PATH_MAX], legacy[PATH_MAX]; @@ -109,27 +109,27 @@ static const char* getvncdir(bool userDir, const char *xdg_env, const char *xdg_ return (stat(dir, &st) != 0 && stat(legacy, &st) == 0) ? legacy : dir; } -const char* os::getuserhomedir() +const char* core::getuserhomedir() { return getvncdir(true, nullptr, nullptr); } -const char* os::getvncconfigdir() +const char* core::getvncconfigdir() { return getvncdir(false, "XDG_CONFIG_HOME", ".config"); } -const char* os::getvncdatadir() +const char* core::getvncdatadir() { return getvncdir(false, "XDG_DATA_HOME", ".local/share"); } -const char* os::getvncstatedir() +const char* core::getvncstatedir() { return getvncdir(false, "XDG_STATE_HOME", ".local/state"); } -int os::mkdir_p(const char *path_, mode_t mode) +int core::mkdir_p(const char *path_, mode_t mode) { char *path = strdup(path_); char *p; diff --git a/common/os/os.h b/common/core/xdgdirs.h similarity index 95% rename from common/os/os.h rename to common/core/xdgdirs.h index a3448070ed..0769ba8bae 100644 --- a/common/os/os.h +++ b/common/core/xdgdirs.h @@ -17,12 +17,12 @@ * USA. */ -#ifndef OS_OS_H -#define OS_OS_H +#ifndef CORE_XDGDIRS_H +#define CORE_XDGDIRS_H #include -namespace os { +namespace core { /* * Get user home directory. @@ -71,4 +71,4 @@ namespace os { int mkdir_p(const char *path, mode_t mode); } -#endif /* OS_OS_H */ +#endif /* CORE_XDGDIRS_H */ diff --git a/common/network/CMakeLists.txt b/common/network/CMakeLists.txt index f08eaa3149..42472b8dd6 100644 --- a/common/network/CMakeLists.txt +++ b/common/network/CMakeLists.txt @@ -7,7 +7,7 @@ if(NOT WIN32) endif() target_include_directories(network PUBLIC ${CMAKE_SOURCE_DIR}/common) -target_link_libraries(network os rdr rfb) +target_link_libraries(network core rdr) if(WIN32) target_link_libraries(network ws2_32) diff --git a/common/network/Socket.cxx b/common/network/Socket.cxx index 49abbc84d4..1a0ff4c357 100644 --- a/common/network/Socket.cxx +++ b/common/network/Socket.cxx @@ -39,15 +39,17 @@ #include #include -#include +#include +#include -#include +#include +#include -#include +#include using namespace network; -static rfb::LogWriter vlog("Socket"); +static core::LogWriter vlog("Socket"); // -=- Socket initialisation static bool socketsInitialised = false; @@ -59,7 +61,7 @@ void network::initSockets() { WSADATA initResult; if (WSAStartup(requiredVersion, &initResult) != 0) - throw rdr::socket_error("Unable to initialise Winsock2", errorNumber); + throw core::socket_error("Unable to initialise Winsock2", errorNumber); #else signal(SIGPIPE, SIG_IGN); #endif @@ -99,6 +101,11 @@ Socket::~Socket() delete outstream; } +int Socket::getFd() +{ + return outstream->getFd(); +} + // if shutdown() is overridden then the override MUST call on to here void Socket::shutdown() { @@ -122,6 +129,11 @@ bool Socket::isShutdown() const return isShutdown_; } +void Socket::cork(bool enable) +{ + outstream->cork(enable); +} + // Was there a "?" in the ConnectionFilter used to accept this Socket? void Socket::setRequiresQuery() { @@ -178,7 +190,7 @@ Socket* SocketListener::accept() { // Accept an incoming connection if ((new_sock = ::accept(fd, nullptr, nullptr)) < 0) - throw rdr::socket_error("Unable to accept new connection", errorNumber); + throw core::socket_error("Unable to accept new connection", errorNumber); // Create the socket object & check connection is allowed Socket* s = createSocket(new_sock); @@ -196,7 +208,7 @@ void SocketListener::listen(int sock) if (::listen(sock, 5) < 0) { int e = errorNumber; closesocket(sock); - throw rdr::socket_error("Unable to set socket to listening mode", e); + throw core::socket_error("Unable to set socket to listening mode", e); } fd = sock; diff --git a/common/network/Socket.h b/common/network/Socket.h index 34b8db8eb4..f1688c726f 100644 --- a/common/network/Socket.h +++ b/common/network/Socket.h @@ -24,8 +24,11 @@ #include #include -#include -#include + +namespace rdr { + class FdInStream; + class FdOutStream; +} namespace network { @@ -40,12 +43,12 @@ namespace network { rdr::FdInStream &inStream() {return *instream;} rdr::FdOutStream &outStream() {return *outstream;} - int getFd() {return outstream->getFd();} + int getFd(); void shutdown(); bool isShutdown() const; - void cork(bool enable) { outstream->cork(enable); } + void cork(bool enable); // information about the remote end of the socket virtual const char* getPeerAddress() = 0; // a string e.g. "192.168.0.1" diff --git a/common/network/TcpSocket.cxx b/common/network/TcpSocket.cxx index c5b86543f1..e941aa67cd 100644 --- a/common/network/TcpSocket.cxx +++ b/common/network/TcpSocket.cxx @@ -35,19 +35,21 @@ #include #endif +#include +#include #include +#include #include -#include +#include +#include +#include +#include #include -#include -#include -#include - #ifdef WIN32 -#include +#include #endif #ifndef INADDR_NONE @@ -68,12 +70,11 @@ #endif using namespace network; -using namespace rdr; -static rfb::LogWriter vlog("TcpSocket"); +static core::LogWriter vlog("TcpSocket"); -static rfb::BoolParameter UseIPv4("UseIPv4", "Use IPv4 for incoming and outgoing connections.", true); -static rfb::BoolParameter UseIPv6("UseIPv6", "Use IPv6 for incoming and outgoing connections.", true); +static core::BoolParameter UseIPv4("UseIPv4", "Use IPv4 for incoming and outgoing connections.", true); +static core::BoolParameter UseIPv6("UseIPv6", "Use IPv6 for incoming and outgoing connections.", true); /* Tunnelling support. */ int network::findFreeTcpPort (void) @@ -85,20 +86,105 @@ int network::findFreeTcpPort (void) addr.sin_addr.s_addr = INADDR_ANY; if ((sock = socket (AF_INET, SOCK_STREAM, 0)) < 0) - throw socket_error("Unable to create socket", errorNumber); + throw core::socket_error("Unable to create socket", errorNumber); addr.sin_port = 0; if (bind (sock, (struct sockaddr *)&addr, sizeof (addr)) < 0) - throw socket_error("Unable to find free port", errorNumber); + throw core::socket_error("Unable to find free port", errorNumber); socklen_t n = sizeof(addr); if (getsockname (sock, (struct sockaddr *)&addr, &n) < 0) - throw socket_error("Unable to get port number", errorNumber); + throw core::socket_error("Unable to get port number", errorNumber); closesocket (sock); return ntohs(addr.sin_port); } +static bool isAllSpace(const char *string) { + if (string == nullptr) + return false; + while(*string != '\0') { + if (! isspace(*string)) + return false; + string++; + } + return true; +} + +void network::getHostAndPort(const char* hi, std::string* host, + int* port, int basePort) +{ + const char* hostStart; + const char* hostEnd; + const char* portStart; + + if (hi == nullptr) + throw std::invalid_argument("NULL host specified"); + + // Trim leading whitespace + while(isspace(*hi)) + hi++; + + assert(host); + assert(port); + + if (hi[0] == '[') { + hostStart = &hi[1]; + hostEnd = strchr(hostStart, ']'); + if (hostEnd == nullptr) + throw std::invalid_argument("Unmatched [ in host"); + + portStart = hostEnd + 1; + if (isAllSpace(portStart)) + portStart = nullptr; + } else { + hostStart = &hi[0]; + hostEnd = strrchr(hostStart, ':'); + + if (hostEnd == nullptr) { + hostEnd = hostStart + strlen(hostStart); + portStart = nullptr; + } else { + if ((hostEnd > hostStart) && (hostEnd[-1] == ':')) + hostEnd--; + portStart = strchr(hostStart, ':'); + if (portStart != hostEnd) { + // We found more : in the host. This is probably an IPv6 address + hostEnd = hostStart + strlen(hostStart); + portStart = nullptr; + } + } + } + + // Back up past trailing space + while(isspace(*(hostEnd - 1)) && hostEnd > hostStart) + hostEnd--; + + if (hostStart == hostEnd) + *host = "localhost"; + else + *host = std::string(hostStart, hostEnd - hostStart); + + if (portStart == nullptr) + *port = basePort; + else { + char* end; + + if (portStart[0] != ':') + throw std::invalid_argument("Invalid port specified"); + + if (portStart[1] != ':') + *port = strtol(portStart + 1, &end, 10); + else + *port = strtol(portStart + 2, &end, 10); + if (*end != '\0' && ! isAllSpace(end)) + throw std::invalid_argument("Invalid port specified"); + + if ((portStart[1] != ':') && (*port < 100)) + *port += basePort; + } +} + int network::getSockPort(int sock) { vnc_sockaddr_t sa; @@ -137,7 +223,7 @@ TcpSocket::TcpSocket(const char *host, int port) hints.ai_next = nullptr; if ((result = getaddrinfo(host, nullptr, &hints, &ai)) != 0) { - throw getaddrinfo_error("Unable to resolve host by name", result); + throw core::getaddrinfo_error("Unable to resolve host by name", result); } sock = -1; @@ -178,7 +264,7 @@ TcpSocket::TcpSocket(const char *host, int port) if (sock == -1) { err = errorNumber; freeaddrinfo(ai); - throw socket_error("Unable to create socket", err); + throw core::socket_error("Unable to create socket", err); } /* Attempt to connect to the remote host */ @@ -205,7 +291,7 @@ TcpSocket::TcpSocket(const char *host, int port) if (err == 0) throw std::runtime_error("No useful address for host"); else - throw socket_error("Unable to connect to socket", err); + throw core::socket_error("Unable to connect to socket", err); } // Take proper ownership of the socket @@ -302,7 +388,7 @@ TcpListener::TcpListener(const struct sockaddr *listenaddr, int sock; if ((sock = socket (listenaddr->sa_family, SOCK_STREAM, 0)) < 0) - throw socket_error("Unable to create listening socket", errorNumber); + throw core::socket_error("Unable to create listening socket", errorNumber); memcpy (&sa, listenaddr, listenaddrlen); #ifdef IPV6_V6ONLY @@ -310,7 +396,7 @@ TcpListener::TcpListener(const struct sockaddr *listenaddr, if (setsockopt (sock, IPPROTO_IPV6, IPV6_V6ONLY, (char*)&one, sizeof(one))) { int e = errorNumber; closesocket(sock); - throw socket_error("Unable to set IPV6_V6ONLY", e); + throw core::socket_error("Unable to set IPV6_V6ONLY", e); } } #endif /* defined(IPV6_V6ONLY) */ @@ -328,14 +414,14 @@ TcpListener::TcpListener(const struct sockaddr *listenaddr, (char *)&one, sizeof(one)) < 0) { int e = errorNumber; closesocket(sock); - throw socket_error("Unable to create listening socket", e); + throw core::socket_error("Unable to create listening socket", e); } #endif if (bind(sock, &sa.u.sa, listenaddrlen) == -1) { int e = errorNumber; closesocket(sock); - throw socket_error("Failed to bind socket", e); + throw core::socket_error("Failed to bind socket", e); } listen(sock); @@ -446,7 +532,7 @@ void network::createTcpListeners(std::list *listeners, snprintf (service, sizeof (service) - 1, "%d", port); service[sizeof (service) - 1] = '\0'; if ((result = getaddrinfo(addr, service, &hints, &ai)) != 0) - throw getaddrinfo_error("Unable to resolve listening address", result); + throw core::getaddrinfo_error("Unable to resolve listening address", result); try { createTcpListeners(listeners, ai); @@ -485,7 +571,7 @@ void network::createTcpListeners(std::list *listeners, try { new_listeners.push_back(new TcpListener(current->ai_addr, current->ai_addrlen)); - } catch (socket_error& e) { + } catch (core::socket_error& e) { // Ignore this if it is due to lack of address family support on // the interface or on the system if (e.err != EADDRNOTAVAIL && e.err != EAFNOSUPPORT) { @@ -506,7 +592,7 @@ void network::createTcpListeners(std::list *listeners, TcpFilter::TcpFilter(const char* spec) { std::vector patterns; - patterns = rfb::split(spec, ','); + patterns = core::split(spec, ','); for (size_t i = 0; i < patterns.size(); i++) { if (!patterns[i].empty()) @@ -608,7 +694,7 @@ TcpFilter::Pattern TcpFilter::parsePattern(const char* p) { initSockets(); - parts = rfb::split(&p[1], '/'); + parts = core::split(&p[1], '/'); if (parts.size() > 2) throw std::invalid_argument("Invalid filter specified"); @@ -633,7 +719,7 @@ TcpFilter::Pattern TcpFilter::parsePattern(const char* p) { } if ((result = getaddrinfo (parts[0].c_str(), nullptr, &hints, &ai)) != 0) { - throw getaddrinfo_error("Unable to resolve host by name", result); + throw core::getaddrinfo_error("Unable to resolve host by name", result); } memcpy (&pattern.address.u.sa, ai->ai_addr, ai->ai_addrlen); @@ -666,9 +752,9 @@ TcpFilter::Pattern TcpFilter::parsePattern(const char* p) { family = pattern.address.u.sa.sa_family; if (pattern.prefixlen > (family == AF_INET ? 32: 128)) - throw std::invalid_argument(rfb::format("Invalid prefix length for " - "filter address: %u", - pattern.prefixlen)); + throw std::invalid_argument( + core::format("Invalid prefix length for filter address: %u", + pattern.prefixlen)); // Compute mask from address and prefix length memset (&pattern.mask, 0, sizeof (pattern.mask)); diff --git a/common/network/TcpSocket.h b/common/network/TcpSocket.h index b029bff262..17854e10d7 100644 --- a/common/network/TcpSocket.h +++ b/common/network/TcpSocket.h @@ -49,6 +49,9 @@ namespace network { /* Tunnelling support. */ int findFreeTcpPort (void); + void getHostAndPort(const char* hi, std::string* host, + int* port, int basePort=5900); + int getSockPort(int sock); class TcpSocket : public Socket { diff --git a/common/network/UnixSocket.cxx b/common/network/UnixSocket.cxx index 4856124573..9691cb23d6 100644 --- a/common/network/UnixSocket.cxx +++ b/common/network/UnixSocket.cxx @@ -28,17 +28,16 @@ #include #include #include +#include -#include +#include +#include #include -#include - using namespace network; -using namespace rdr; -static rfb::LogWriter vlog("UnixSocket"); +static core::LogWriter vlog("UnixSocket"); // -=- UnixSocket @@ -53,12 +52,12 @@ UnixSocket::UnixSocket(const char *path) socklen_t salen; if (strlen(path) >= sizeof(addr.sun_path)) - throw socket_error("Socket path is too long", ENAMETOOLONG); + throw core::socket_error("Socket path is too long", ENAMETOOLONG); // - Create a socket sock = socket(AF_UNIX, SOCK_STREAM, 0); if (sock == -1) - throw socket_error("Unable to create socket", errno); + throw core::socket_error("Unable to create socket", errno); // - Attempt to connect memset(&addr, 0, sizeof(addr)); @@ -72,7 +71,7 @@ UnixSocket::UnixSocket(const char *path) } if (result == -1) - throw socket_error("Unable to connect to socket", err); + throw core::socket_error("Unable to connect to socket", err); setFd(sock); } @@ -119,11 +118,11 @@ UnixListener::UnixListener(const char *path, int mode) int err, result; if (strlen(path) >= sizeof(addr.sun_path)) - throw socket_error("Socket path is too long", ENAMETOOLONG); + throw core::socket_error("Socket path is too long", ENAMETOOLONG); // - Create a socket if ((fd = socket(AF_UNIX, SOCK_STREAM, 0)) < 0) - throw socket_error("Unable to create listening socket", errno); + throw core::socket_error("Unable to create listening socket", errno); // - Delete existing socket (ignore result) unlink(path); @@ -138,14 +137,14 @@ UnixListener::UnixListener(const char *path, int mode) umask(saved_umask); if (result < 0) { close(fd); - throw socket_error("Unable to bind listening socket", err); + throw core::socket_error("Unable to bind listening socket", err); } // - Set socket mode if (chmod(path, mode) < 0) { err = errno; close(fd); - throw socket_error("Unable to set socket mode", err); + throw core::socket_error("Unable to set socket mode", err); } listen(fd); diff --git a/common/os/CMakeLists.txt b/common/os/CMakeLists.txt deleted file mode 100644 index 2573d08801..0000000000 --- a/common/os/CMakeLists.txt +++ /dev/null @@ -1,15 +0,0 @@ -add_library(os STATIC - Mutex.cxx - Thread.cxx - os.cxx) - -target_include_directories(os PUBLIC ${CMAKE_SOURCE_DIR}/common) -target_link_libraries(os rdr) - -if(UNIX) - target_link_libraries(os pthread) -endif() - -if(UNIX) - libtool_create_control_file(os) -endif() diff --git a/common/rdr/BufferedInStream.cxx b/common/rdr/BufferedInStream.cxx index bf94a9507a..bcdeef4adf 100644 --- a/common/rdr/BufferedInStream.cxx +++ b/common/rdr/BufferedInStream.cxx @@ -23,9 +23,9 @@ #include -#include +#include -#include +#include using namespace rdr; @@ -64,12 +64,10 @@ void BufferedInStream::ensureSpace(size_t needed) uint8_t* newBuffer; if (needed > MAX_BUF_SIZE) - throw std::out_of_range(rfb::format("BufferedInStream overrun: " - "requested size of %lu bytes " - "exceeds maximum of %lu " - "bytes", - (long unsigned)needed, - (long unsigned)MAX_BUF_SIZE)); + throw std::out_of_range(core::format( + "BufferedInStream overrun: requested size of %lu bytes exceeds " + "maximum of %lu bytes", + (long unsigned)needed, (long unsigned)MAX_BUF_SIZE)); newSize = DEFAULT_BUF_SIZE; while (newSize < needed) diff --git a/common/rdr/BufferedOutStream.cxx b/common/rdr/BufferedOutStream.cxx index efb71dd7d9..e2b756bb05 100644 --- a/common/rdr/BufferedOutStream.cxx +++ b/common/rdr/BufferedOutStream.cxx @@ -22,9 +22,9 @@ #include #endif -#include +#include -#include +#include using namespace rdr; @@ -138,11 +138,10 @@ void BufferedOutStream::overrun(size_t needed) // We'll need to allocate more buffer space... if (totalNeeded > MAX_BUF_SIZE) - throw std::out_of_range(rfb::format("BufferedOutStream overrun: " - "requested size of %lu bytes " - "exceeds maximum of %lu bytes", - (long unsigned)totalNeeded, - (long unsigned)MAX_BUF_SIZE)); + throw std::out_of_range(core::format( + "BufferedOutStream overrun: requested size of %lu bytes exceeds " + "maximum of %lu bytes", + (long unsigned)totalNeeded, (long unsigned)MAX_BUF_SIZE)); newSize = DEFAULT_BUF_SIZE; while (newSize < totalNeeded) diff --git a/common/rdr/CMakeLists.txt b/common/rdr/CMakeLists.txt index 2897119b25..55c691321a 100644 --- a/common/rdr/CMakeLists.txt +++ b/common/rdr/CMakeLists.txt @@ -3,7 +3,6 @@ add_library(rdr STATIC AESOutStream.cxx BufferedInStream.cxx BufferedOutStream.cxx - Exception.cxx FdInStream.cxx FdOutStream.cxx FileInStream.cxx @@ -18,12 +17,8 @@ add_library(rdr STATIC target_include_directories(rdr PUBLIC ${CMAKE_SOURCE_DIR}/common) target_include_directories(rdr SYSTEM PUBLIC ${ZLIB_INCLUDE_DIRS}) -target_link_libraries(rdr ${ZLIB_LIBRARIES} os rfb) - -if(MSVC) - # undef min and max macro - target_compile_definitions(rfb PRIVATE NOMINMAX) -endif() +target_link_libraries(rdr core) +target_link_libraries(rdr ${ZLIB_LIBRARIES}) if(GNUTLS_FOUND) target_include_directories(rdr SYSTEM PUBLIC ${GNUTLS_INCLUDE_DIR}) diff --git a/common/rdr/FdInStream.cxx b/common/rdr/FdInStream.cxx index 23ea2f8cc8..25542a0149 100644 --- a/common/rdr/FdInStream.cxx +++ b/common/rdr/FdInStream.cxx @@ -28,7 +28,7 @@ #include #define errorNumber WSAGetLastError() #define close closesocket -#include +#include #else #include #include @@ -41,8 +41,9 @@ #include #endif +#include + #include -#include using namespace rdr; @@ -92,7 +93,7 @@ size_t FdInStream::readFd(uint8_t* buf, size_t len) } while (n < 0 && errorNumber == EINTR); if (n < 0) - throw socket_error("select", errorNumber); + throw core::socket_error("select", errorNumber); if (n == 0) return 0; @@ -102,7 +103,7 @@ size_t FdInStream::readFd(uint8_t* buf, size_t len) } while (n < 0 && errorNumber == EINTR); if (n < 0) - throw socket_error("read", errorNumber); + throw core::socket_error("read", errorNumber); if (n == 0) throw end_of_stream(); diff --git a/common/rdr/FdOutStream.cxx b/common/rdr/FdOutStream.cxx index 6db8c0bb22..416926c1ec 100644 --- a/common/rdr/FdOutStream.cxx +++ b/common/rdr/FdOutStream.cxx @@ -28,7 +28,7 @@ #ifdef _WIN32 #include #define errorNumber WSAGetLastError() -#include +#include #else #include #include @@ -44,10 +44,10 @@ #include #endif -#include -#include -#include +#include +#include +#include using namespace rdr; @@ -68,7 +68,7 @@ FdOutStream::~FdOutStream() unsigned FdOutStream::getIdleTime() { - return rfb::msSince(&lastWrite); + return core::msSince(&lastWrite); } void FdOutStream::cork(bool enable) @@ -117,7 +117,7 @@ size_t FdOutStream::writeFd(const uint8_t* data, size_t length) } while (n < 0 && errorNumber == EINTR); if (n < 0) - throw socket_error("select", errorNumber); + throw core::socket_error("select", errorNumber); if (n == 0) return 0; @@ -134,7 +134,7 @@ size_t FdOutStream::writeFd(const uint8_t* data, size_t length) } while (n < 0 && (errorNumber == EINTR)); if (n < 0) - throw socket_error("write", errorNumber); + throw core::socket_error("write", errorNumber); gettimeofday(&lastWrite, nullptr); diff --git a/common/rdr/FileInStream.cxx b/common/rdr/FileInStream.cxx index df09ea768c..4dbe2d1f3c 100644 --- a/common/rdr/FileInStream.cxx +++ b/common/rdr/FileInStream.cxx @@ -24,7 +24,8 @@ #include -#include +#include + #include using namespace rdr; @@ -33,7 +34,7 @@ FileInStream::FileInStream(const char *fileName) { file = fopen(fileName, "rb"); if (!file) - throw posix_error("fopen", errno); + throw core::posix_error("fopen", errno); } FileInStream::~FileInStream(void) { @@ -48,7 +49,7 @@ bool FileInStream::fillBuffer() size_t n = fread((uint8_t*)end, 1, availSpace(), file); if (n == 0) { if (ferror(file)) - throw posix_error("fread", errno); + throw core::posix_error("fread", errno); if (feof(file)) throw end_of_stream(); return false; diff --git a/common/rdr/HexInStream.cxx b/common/rdr/HexInStream.cxx index 69c3e26084..b5a8826c92 100644 --- a/common/rdr/HexInStream.cxx +++ b/common/rdr/HexInStream.cxx @@ -22,8 +22,10 @@ #endif #include + +#include + #include -#include using namespace rdr; @@ -44,7 +46,7 @@ bool HexInStream::fillBuffer() { uint8_t* optr = (uint8_t*) end; for (size_t i=0; i #endif + #include + +#include + #include -#include using namespace rdr; @@ -42,7 +45,7 @@ bool HexOutStream::flushBuffer() size_t length = std::min((size_t)(ptr-sentUpTo), out_stream.avail()/2); for (size_t i=0; i -#include namespace rdr { diff --git a/common/rdr/RandomStream.cxx b/common/rdr/RandomStream.cxx index 3a524102a4..9784c2201c 100644 --- a/common/rdr/RandomStream.cxx +++ b/common/rdr/RandomStream.cxx @@ -20,9 +20,11 @@ #include #endif +#include +#include + #include -#include -#include + #include #include #ifndef WIN32 @@ -35,7 +37,7 @@ #endif #endif -static rfb::LogWriter vlog("RandomStream"); +static core::LogWriter vlog("RandomStream"); using namespace rdr; @@ -89,7 +91,7 @@ bool RandomStream::fillBuffer() { #ifdef RFB_HAVE_WINCRYPT if (provider) { if (!CryptGenRandom(provider, availSpace(), (uint8_t*)end)) - throw rdr::win32_error("Unable to CryptGenRandom", GetLastError()); + throw core::win32_error("Unable to CryptGenRandom", GetLastError()); end += availSpace(); } else { #else @@ -97,8 +99,8 @@ bool RandomStream::fillBuffer() { if (fp) { size_t n = fread((uint8_t*)end, 1, availSpace(), fp); if (n <= 0) - throw rdr::posix_error("Reading /dev/urandom or /dev/random " - "failed", errno); + throw core::posix_error( + "Reading /dev/urandom or /dev/random failed", errno); end += n; } else { #else diff --git a/common/rdr/TLSException.cxx b/common/rdr/TLSException.cxx index ee4f587b61..a1896af4c6 100644 --- a/common/rdr/TLSException.cxx +++ b/common/rdr/TLSException.cxx @@ -22,9 +22,9 @@ #include #endif -#include +#include -#include +#include #include #include @@ -36,8 +36,8 @@ using namespace rdr; #ifdef HAVE_GNUTLS tls_error::tls_error(const char* s, int err_) noexcept - : std::runtime_error(rfb::format("%s: %s (%d)", s, - gnutls_strerror(err_), err_)), + : std::runtime_error(core::format("%s: %s (%d)", s, + gnutls_strerror(err_), err_)), err(err_) { } diff --git a/common/rdr/TLSException.h b/common/rdr/TLSException.h index 62b090baf5..b35a675f26 100644 --- a/common/rdr/TLSException.h +++ b/common/rdr/TLSException.h @@ -21,7 +21,7 @@ #ifndef __RDR_TLSEXCEPTION_H__ #define __RDR_TLSEXCEPTION_H__ -#include +#include namespace rdr { diff --git a/common/rdr/TLSInStream.cxx b/common/rdr/TLSInStream.cxx index ee2739f4e6..9d9a33be12 100644 --- a/common/rdr/TLSInStream.cxx +++ b/common/rdr/TLSInStream.cxx @@ -23,16 +23,18 @@ #include #endif -#include +#include +#include + #include #include -#include + #include #ifdef HAVE_GNUTLS using namespace rdr; -static rfb::LogWriter vlog("TLSInStream"); +static core::LogWriter vlog("TLSInStream"); ssize_t TLSInStream::pull(gnutls_transport_ptr_t str, void* data, size_t size) { @@ -56,10 +58,10 @@ ssize_t TLSInStream::pull(gnutls_transport_ptr_t str, void* data, size_t size) in->readBytes((uint8_t*)data, size); } catch (end_of_stream&) { return 0; - } catch (socket_error& e) { + } catch (core::socket_error& e) { vlog.error("Failure reading TLS data: %s", e.what()); gnutls_transport_set_errno(self->session, e.err); - self->saved_exception = new socket_error(e); + self->saved_exception = new core::socket_error(e); return -1; } catch (std::exception& e) { vlog.error("Failure reading TLS data: %s", e.what()); @@ -118,8 +120,8 @@ size_t TLSInStream::readTLS(uint8_t* buf, size_t len) }; if (n == GNUTLS_E_PULL_ERROR) { - if (dynamic_cast(saved_exception)) - throw *dynamic_cast(saved_exception); + if (dynamic_cast(saved_exception)) + throw *dynamic_cast(saved_exception); else throw std::runtime_error(saved_exception->what()); } diff --git a/common/rdr/TLSOutStream.cxx b/common/rdr/TLSOutStream.cxx index 365ffd6004..5ea2b250f8 100644 --- a/common/rdr/TLSOutStream.cxx +++ b/common/rdr/TLSOutStream.cxx @@ -23,16 +23,18 @@ #include #endif -#include +#include +#include + #include #include -#include + #include #ifdef HAVE_GNUTLS using namespace rdr; -static rfb::LogWriter vlog("TLSOutStream"); +static core::LogWriter vlog("TLSOutStream"); ssize_t TLSOutStream::push(gnutls_transport_ptr_t str, const void* data, size_t size) @@ -46,10 +48,10 @@ ssize_t TLSOutStream::push(gnutls_transport_ptr_t str, const void* data, try { out->writeBytes((const uint8_t*)data, size); out->flush(); - } catch (socket_error& e) { + } catch (core::socket_error& e) { vlog.error("Failure sending TLS data: %s", e.what()); gnutls_transport_set_errno(self->session, e.err); - self->saved_exception = new socket_error(e); + self->saved_exception = new core::socket_error(e); return -1; } catch (std::exception& e) { vlog.error("Failure sending TLS data: %s", e.what()); @@ -115,8 +117,8 @@ size_t TLSOutStream::writeTLS(const uint8_t* data, size_t length) return 0; if (n == GNUTLS_E_PUSH_ERROR) { - if (dynamic_cast(saved_exception)) - throw *dynamic_cast(saved_exception); + if (dynamic_cast(saved_exception)) + throw *dynamic_cast(saved_exception); else throw std::runtime_error(saved_exception->what()); } diff --git a/common/rdr/ZlibOutStream.cxx b/common/rdr/ZlibOutStream.cxx index 73b5d459b2..1b8ac3077d 100644 --- a/common/rdr/ZlibOutStream.cxx +++ b/common/rdr/ZlibOutStream.cxx @@ -23,14 +23,15 @@ #include +#include + #include -#include #include #undef ZLIBOUT_DEBUG -static rfb::LogWriter vlog("ZlibOutStream"); +static core::LogWriter vlog("ZlibOutStream"); using namespace rdr; diff --git a/common/rfb/Blacklist.cxx b/common/rfb/Blacklist.cxx index 68420ae2f3..6de52a5868 100644 --- a/common/rfb/Blacklist.cxx +++ b/common/rfb/Blacklist.cxx @@ -21,24 +21,26 @@ #endif #include -#include +#include using namespace rfb; -BoolParameter enabled("UseBlacklist", - "Temporarily reject connections from a host if it " - "repeatedly fails to authenticate.", - true); -IntParameter threshold("BlacklistThreshold", - "The number of unauthenticated connection attempts " - "allowed from any individual host before that host " - "is black-listed", - 5); -IntParameter initialTimeout("BlacklistTimeout", - "The initial timeout applied when a host is " - "first black-listed. The host cannot re-attempt " - "a connection until the timeout expires.", - 10); +core::BoolParameter enabled("UseBlacklist", + "Temporarily reject connections from a " + "host if it repeatedly fails to " + "authenticate.", + true); +core::IntParameter threshold("BlacklistThreshold", + "The number of unauthenticated connection " + "attempts allowed from any individual " + "host before that host is black-listed", + 5); +core::IntParameter initialTimeout("BlacklistTimeout", + "The initial timeout applied when a " + "host is first black-listed. The " + "host cannot re-attempt a connection " + "until the timeout expires.", + 10); Blacklist::Blacklist() { diff --git a/common/rfb/Blacklist.h b/common/rfb/Blacklist.h index c1699f2924..3c9660cc62 100644 --- a/common/rfb/Blacklist.h +++ b/common/rfb/Blacklist.h @@ -27,13 +27,11 @@ #ifndef __RFB_BLACKLIST_H__ #define __RFB_BLACKLIST_H__ -#include #include + #include #include -#include - namespace rfb { // diff --git a/common/rfb/CConnection.cxx b/common/rfb/CConnection.cxx index 5e7530c80e..e8e54be426 100644 --- a/common/rfb/CConnection.cxx +++ b/common/rfb/CConnection.cxx @@ -27,6 +27,9 @@ #include +#include +#include + #include #include #include @@ -35,23 +38,21 @@ #include #include #include +#include #include #include #include -#include #define XK_MISCELLANY #define XK_XKB_KEYS #include -#include - #include #include using namespace rfb; -static LogWriter vlog("CConnection"); +static core::LogWriter vlog("CConnection"); CConnection::CConnection() : csecurity(nullptr), @@ -98,7 +99,7 @@ void CConnection::setFramebuffer(ModifiablePixelBuffer* fb) } if ((framebuffer != nullptr) && (fb != nullptr)) { - Rect rect; + core::Rect rect; const uint8_t* data; int stride; @@ -107,9 +108,8 @@ void CConnection::setFramebuffer(ModifiablePixelBuffer* fb) // Copy still valid area - rect.setXYWH(0, 0, - __rfbmin(fb->width(), framebuffer->width()), - __rfbmin(fb->height(), framebuffer->height())); + rect = fb->getRect(); + rect = rect.intersect(framebuffer->getRect()); data = framebuffer->getBuffer(framebuffer->getRect(), &stride); fb->imageRect(rect, data, stride); @@ -189,10 +189,9 @@ bool CConnection::processVersionMsg() vlog.error("Server gave unsupported RFB protocol version %d.%d", server.majorVersion, server.minorVersion); state_ = RFBSTATE_INVALID; - throw protocol_error(format("Server gave unsupported RFB protocol " - "version %d.%d", - server.majorVersion, - server.minorVersion)); + throw protocol_error( + core::format("Server gave unsupported RFB protocol version %d.%d", + server.majorVersion, server.minorVersion)); } else if (server.beforeVersion(3,7)) { server.setVersion(3,3); } else if (server.afterVersion(3,8)) { @@ -486,7 +485,7 @@ void CConnection::serverInit(int width, int height, } } -bool CConnection::readAndDecodeRect(const Rect& r, int encoding, +bool CConnection::readAndDecodeRect(const core::Rect& r, int encoding, ModifiablePixelBuffer* pb) { if (!decoder.decodeRect(r, encoding, pb)) @@ -533,7 +532,7 @@ void CConnection::framebufferUpdateEnd() } } -bool CConnection::dataRect(const Rect& r, int encoding) +bool CConnection::dataRect(const core::Rect& r, int encoding) { return decoder.decodeRect(r, encoding, framebuffer); } @@ -604,11 +603,11 @@ void CConnection::handleClipboardProvide(uint32_t flags, } // FIXME: This conversion magic should be in CMsgReader - if (!isValidUTF8((const char*)data[0], lengths[0])) { + if (!core::isValidUTF8((const char*)data[0], lengths[0])) { vlog.error("Invalid UTF-8 sequence in clipboard - ignoring"); return; } - serverClipboard = convertLF((const char*)data[0], lengths[0]); + serverClipboard = core::convertLF((const char*)data[0], lengths[0]); hasRemoteClipboard = true; // FIXME: Should probably verify that this data was actually requested @@ -679,7 +678,7 @@ void CConnection::sendClipboardData(const char* data) { if (server.clipboardFlags() & rfb::clipboardProvide) { // FIXME: This conversion magic should be in CMsgWriter - std::string filtered(convertCRLF(data)); + std::string filtered(core::convertCRLF(data)); size_t sizes[1] = { filtered.size() + 1 }; const uint8_t* datas[1] = { (const uint8_t*)filtered.c_str() }; @@ -833,6 +832,11 @@ void CConnection::setPF(const PixelFormat& pf) formatChange = true; } +bool CConnection::isSecure() const +{ + return csecurity ? csecurity->isSecure() : false; +} + void CConnection::fence(uint32_t flags, unsigned len, const uint8_t data[]) { CMsgHandler::fence(flags, len, data); @@ -884,9 +888,9 @@ void CConnection::requestNewUpdate() if (forceNonincremental || !continuousUpdates) { pendingUpdate = true; - writer()->writeFramebufferUpdateRequest(Rect(0, 0, - server.width(), - server.height()), + writer()->writeFramebufferUpdateRequest({0, 0, + server.width(), + server.height()}, !forceNonincremental); } diff --git a/common/rfb/CConnection.h b/common/rfb/CConnection.h index 07e47e3926..9ffbd2c573 100644 --- a/common/rfb/CConnection.h +++ b/common/rfb/CConnection.h @@ -29,8 +29,14 @@ #include #include +#include #include +namespace rdr { + class InStream; + class OutStream; +} + namespace rfb { class CMsgReader; @@ -114,12 +120,12 @@ namespace rfb { void serverInit(int width, int height, const PixelFormat& pf, const char* name) override; - bool readAndDecodeRect(const Rect& r, int encoding, + bool readAndDecodeRect(const core::Rect& r, int encoding, ModifiablePixelBuffer* pb) override; void framebufferUpdateStart() override; void framebufferUpdateEnd() override; - bool dataRect(const Rect& r, int encoding) override; + bool dataRect(const core::Rect& r, int encoding) override; void serverCutText(const char* str) override; @@ -237,7 +243,7 @@ namespace rfb { // Identities, to determine the unique(ish) name of the server. const char* getServerName() const { return serverName.c_str(); } - bool isSecure() const { return csecurity ? csecurity->isSecure() : false; } + bool isSecure() const; enum stateEnum { RFBSTATE_UNINITIALISED, diff --git a/common/rfb/CMakeLists.txt b/common/rfb/CMakeLists.txt index 365354484b..2b5eea68bd 100644 --- a/common/rfb/CMakeLists.txt +++ b/common/rfb/CMakeLists.txt @@ -12,7 +12,6 @@ add_library(rfb STATIC CSecurityVncAuth.cxx ClientParams.cxx ComparingUpdateTracker.cxx - Configuration.cxx CopyRectDecoder.cxx Cursor.cxx DecodeManager.cxx @@ -26,17 +25,12 @@ add_library(rfb STATIC JpegDecompressor.cxx KeyRemapper.cxx KeysymStr.c - LogWriter.cxx - Logger.cxx - Logger_file.cxx - Logger_stdio.cxx PixelBuffer.cxx PixelFormat.cxx RREEncoder.cxx RREDecoder.cxx RawDecoder.cxx RawEncoder.cxx - Region.cxx SConnection.cxx SMsgHandler.cxx SMsgReader.cxx @@ -50,7 +44,6 @@ add_library(rfb STATIC SSecurityStack.cxx SSecurityVncAuth.cxx SSecurityVeNCrypt.cxx - Timer.cxx TightDecoder.cxx TightEncoder.cxx TightJPEGEncoder.cxx @@ -60,15 +53,12 @@ add_library(rfb STATIC ZRLEEncoder.cxx ZRLEDecoder.cxx encodings.cxx - obfuscate.cxx - util.cxx) + obfuscate.cxx) target_include_directories(rfb PUBLIC ${CMAKE_SOURCE_DIR}/common) target_include_directories(rfb SYSTEM PUBLIC ${JPEG_INCLUDE_DIR}) -target_include_directories(rfb SYSTEM PUBLIC ${PIXMAN_INCLUDE_DIRS}) -target_link_libraries(rfb os rdr network) +target_link_libraries(rfb core rdr network) target_link_libraries(rfb ${JPEG_LIBRARIES} ${PIXMAN_LIBRARIES}) -target_link_directories(rfb PUBLIC ${PIXMAN_LIBRARY_DIRS}) if(ENABLE_H264 AND NOT H264_LIBS STREQUAL "NONE") target_sources(rfb PRIVATE H264Decoder.cxx H264DecoderContext.cxx) @@ -82,10 +72,6 @@ if(ENABLE_H264 AND NOT H264_LIBS STREQUAL "NONE") target_link_directories(rfb PUBLIC ${H264_LIBRARY_DIRS}) endif() -if(UNIX) - target_sources(rfb PRIVATE Logger_syslog.cxx) -endif() - if(WIN32) target_include_directories(rfb PUBLIC ${CMAKE_SOURCE_DIR}/win) target_sources(rfb PRIVATE WinPasswdValidator.cxx) diff --git a/common/rfb/CMsgHandler.cxx b/common/rfb/CMsgHandler.cxx index 0f3f6cd56b..2a88d86709 100644 --- a/common/rfb/CMsgHandler.cxx +++ b/common/rfb/CMsgHandler.cxx @@ -23,14 +23,14 @@ #include -#include -#include +#include +#include + #include #include #include -#include -static rfb::LogWriter vlog("CMsgHandler"); +static core::LogWriter vlog("CMsgHandler"); using namespace rfb; @@ -141,7 +141,7 @@ void CMsgHandler::handleClipboardCaps(uint32_t flags, const uint32_t* lengths) vlog.debug(" %s (only notify)", type); else { vlog.debug(" %s (automatically send up to %s)", - type, iecPrefix(lengths[i], "B").c_str()); + type, core::iecPrefix(lengths[i], "B").c_str()); } } } diff --git a/common/rfb/CMsgHandler.h b/common/rfb/CMsgHandler.h index b484b69526..e7ba2abcdf 100644 --- a/common/rfb/CMsgHandler.h +++ b/common/rfb/CMsgHandler.h @@ -27,13 +27,19 @@ #include #include -#include -#include + +namespace core { + struct Point; + struct Rect; +} namespace rdr { class InStream; } namespace rfb { + class ModifiablePixelBuffer; + struct ScreenSet; + class CMsgHandler { public: CMsgHandler(); @@ -50,9 +56,10 @@ namespace rfb { virtual void setExtendedDesktopSize(unsigned reason, unsigned result, int w, int h, const ScreenSet& layout); - virtual void setCursor(int width, int height, const Point& hotspot, + virtual void setCursor(int width, int height, const + core::Point& hotspot, const uint8_t* data) = 0; - virtual void setCursorPos(const Point& pos) = 0; + virtual void setCursorPos(const core::Point& pos) = 0; virtual void setName(const char* name); virtual void fence(uint32_t flags, unsigned len, const uint8_t data[]); virtual void endOfContinuousUpdates(); @@ -62,12 +69,12 @@ namespace rfb { const PixelFormat& pf, const char* name) = 0; - virtual bool readAndDecodeRect(const Rect& r, int encoding, + virtual bool readAndDecodeRect(const core::Rect& r, int encoding, ModifiablePixelBuffer* pb) = 0; virtual void framebufferUpdateStart(); virtual void framebufferUpdateEnd(); - virtual bool dataRect(const Rect& r, int encoding) = 0; + virtual bool dataRect(const core::Rect& r, int encoding) = 0; virtual void setColourMapEntries(int firstColour, int nColours, uint16_t* rgbs) = 0; diff --git a/common/rfb/CMsgReader.cxx b/common/rfb/CMsgReader.cxx index a10f7c47b1..9e48e8791e 100644 --- a/common/rfb/CMsgReader.cxx +++ b/common/rfb/CMsgReader.cxx @@ -26,20 +26,24 @@ #include +#include +#include + #include #include #include #include -#include #include -#include #include #include +#include +#include +#include -static rfb::LogWriter vlog("CMsgReader"); +static core::LogWriter vlog("CMsgReader"); -static rfb::IntParameter maxCutText("MaxCutText", "Maximum permitted length of an incoming clipboard update", 256*1024); +static core::IntParameter maxCutText("MaxCutText", "Maximum permitted length of an incoming clipboard update", 256*1024); using namespace rfb; @@ -77,11 +81,11 @@ bool CMsgReader::readServerInit() is->readBytes((uint8_t*)name.data(), len); name[len] = '\0'; - if (isValidUTF8(name.data())) + if (core::isValidUTF8(name.data())) handler->serverInit(width, height, pf, name.data()); else handler->serverInit(width, height, pf, - latin1ToUTF8(name.data()).c_str()); + core::latin1ToUTF8(name.data()).c_str()); return true; } @@ -119,7 +123,7 @@ bool CMsgReader::readMsg() ret = readEndOfContinuousUpdates(); break; default: - throw protocol_error(format("Unknown message type %d", currentMsgType)); + throw protocol_error(core::format("Unknown message type %d", currentMsgType)); } if (ret) @@ -288,8 +292,8 @@ bool CMsgReader::readServerCutText() std::vector ca(len); is->readBytes((uint8_t*)ca.data(), len); - std::string utf8(latin1ToUTF8(ca.data(), ca.size())); - std::string filtered(convertLF(utf8.data(), utf8.size())); + std::string utf8(core::latin1ToUTF8(ca.data(), ca.size())); + std::string filtered(core::convertLF(utf8.data(), utf8.size())); handler->serverCutText(filtered.c_str()); @@ -470,7 +474,7 @@ bool CMsgReader::readFramebufferUpdate() return true; } -bool CMsgReader::readRect(const Rect& r, int encoding) +bool CMsgReader::readRect(const core::Rect& r, int encoding) { if ((r.br.x > handler->server.width()) || (r.br.y > handler->server.height())) { @@ -486,7 +490,8 @@ bool CMsgReader::readRect(const Rect& r, int encoding) return handler->dataRect(r, encoding); } -bool CMsgReader::readSetXCursor(int width, int height, const Point& hotspot) +bool CMsgReader::readSetXCursor(int width, int height, + const core::Point& hotspot) { if (width > maxCursorSize || height > maxCursorSize) throw protocol_error("Too big cursor"); @@ -550,7 +555,8 @@ bool CMsgReader::readSetXCursor(int width, int height, const Point& hotspot) return true; } -bool CMsgReader::readSetCursor(int width, int height, const Point& hotspot) +bool CMsgReader::readSetCursor(int width, int height, + const core::Point& hotspot) { if (width > maxCursorSize || height > maxCursorSize) throw protocol_error("Too big cursor"); @@ -596,7 +602,8 @@ bool CMsgReader::readSetCursor(int width, int height, const Point& hotspot) return true; } -bool CMsgReader::readSetCursorWithAlpha(int width, int height, const Point& hotspot) +bool CMsgReader::readSetCursorWithAlpha(int width, int height, + const core::Point& hotspot) { if (width > maxCursorSize || height > maxCursorSize) throw protocol_error("Too big cursor"); @@ -657,7 +664,8 @@ bool CMsgReader::readSetCursorWithAlpha(int width, int height, const Point& hots return true; } -bool CMsgReader::readSetVMwareCursor(int width, int height, const Point& hotspot) +bool CMsgReader::readSetVMwareCursor(int width, int height, + const core::Point& hotspot) { if (width > maxCursorSize || height > maxCursorSize) throw protocol_error("Too big cursor"); @@ -784,7 +792,7 @@ bool CMsgReader::readSetDesktopName(int x, int y, int w, int h) return true; } - if (!isValidUTF8(name.data())) { + if (!core::isValidUTF8(name.data())) { vlog.error("Ignoring DesktopName rect with invalid UTF-8 sequence"); return true; } diff --git a/common/rfb/CMsgReader.h b/common/rfb/CMsgReader.h index 3b1c0ddbd6..e33f701d9d 100644 --- a/common/rfb/CMsgReader.h +++ b/common/rfb/CMsgReader.h @@ -26,14 +26,13 @@ #include -#include -#include +#include namespace rdr { class InStream; } namespace rfb { + class CMsgHandler; - struct Rect; class CMsgReader { public: @@ -59,12 +58,16 @@ namespace rfb { bool readFramebufferUpdate(); - bool readRect(const Rect& r, int encoding); + bool readRect(const core::Rect& r, int encoding); - bool readSetXCursor(int width, int height, const Point& hotspot); - bool readSetCursor(int width, int height, const Point& hotspot); - bool readSetCursorWithAlpha(int width, int height, const Point& hotspot); - bool readSetVMwareCursor(int width, int height, const Point& hotspot); + bool readSetXCursor(int width, int height, + const core::Point& hotspot); + bool readSetCursor(int width, int height, + const core::Point& hotspot); + bool readSetCursorWithAlpha(int width, int height, + const core::Point& hotspot); + bool readSetVMwareCursor(int width, int height, + const core::Point& hotspot); bool readSetDesktopName(int x, int y, int w, int h); bool readExtendedDesktopSize(int x, int y, int w, int h); bool readLEDState(); @@ -85,12 +88,14 @@ namespace rfb { uint8_t currentMsgType; int nUpdateRectsLeft; - Rect dataRect; + core::Rect dataRect; int rectEncoding; int cursorEncoding; static const int maxCursorSize = 256; }; + } + #endif diff --git a/common/rfb/CMsgWriter.cxx b/common/rfb/CMsgWriter.cxx index 0128c431d9..c592a25e66 100644 --- a/common/rfb/CMsgWriter.cxx +++ b/common/rfb/CMsgWriter.cxx @@ -24,6 +24,9 @@ #include #include +#include +#include + #include #include #include @@ -33,10 +36,9 @@ #include #include #include -#include +#include #include #include -#include using namespace rfb; @@ -101,7 +103,8 @@ void CMsgWriter::writeSetDesktopSize(int width, int height, endMsg(); } -void CMsgWriter::writeFramebufferUpdateRequest(const Rect& r, bool incremental) +void CMsgWriter::writeFramebufferUpdateRequest(const core::Rect& r, + bool incremental) { startMsg(msgTypeFramebufferUpdateRequest); os->writeU8(incremental); @@ -173,9 +176,10 @@ void CMsgWriter::writeKeyEvent(uint32_t keysym, uint32_t keycode, bool down) } -void CMsgWriter::writePointerEvent(const Point& pos, uint16_t buttonMask) +void CMsgWriter::writePointerEvent(const core::Point& pos, + uint16_t buttonMask) { - Point p(pos); + core::Point p(pos); bool extendedMouseButtons; if (p.x < 0) p.x = 0; @@ -223,7 +227,7 @@ void CMsgWriter::writeClientCutText(const char* str) if (strchr(str, '\r') != nullptr) throw std::invalid_argument("Invalid carriage return in clipboard data"); - std::string latin1(utf8ToLatin1(str)); + std::string latin1(core::utf8ToLatin1(str)); startMsg(msgTypeClientCutText); os->pad(3); diff --git a/common/rfb/CMsgWriter.h b/common/rfb/CMsgWriter.h index 9cb4adec62..d0378e62d7 100644 --- a/common/rfb/CMsgWriter.h +++ b/common/rfb/CMsgWriter.h @@ -27,6 +27,11 @@ #include +namespace core { + struct Point; + struct Rect; +} + namespace rdr { class OutStream; } namespace rfb { @@ -34,8 +39,6 @@ namespace rfb { class PixelFormat; class ServerParams; struct ScreenSet; - struct Point; - struct Rect; class CMsgWriter { public: @@ -48,13 +51,14 @@ namespace rfb { void writeSetEncodings(const std::list encodings); void writeSetDesktopSize(int width, int height, const ScreenSet& layout); - void writeFramebufferUpdateRequest(const Rect& r,bool incremental); + void writeFramebufferUpdateRequest(const core::Rect& r, + bool incremental); void writeEnableContinuousUpdates(bool enable, int x, int y, int w, int h); void writeFence(uint32_t flags, unsigned len, const uint8_t data[]); void writeKeyEvent(uint32_t keysym, uint32_t keycode, bool down); - void writePointerEvent(const Point& pos, uint16_t buttonMask); + void writePointerEvent(const core::Point& pos, uint16_t buttonMask); void writeClientCutText(const char* str); diff --git a/common/rfb/CSecurityDH.cxx b/common/rfb/CSecurityDH.cxx index 2f0365a681..93cf6b268c 100644 --- a/common/rfb/CSecurityDH.cxx +++ b/common/rfb/CSecurityDH.cxx @@ -40,7 +40,6 @@ #include #include #include -#include using namespace rfb; diff --git a/common/rfb/CSecurityMSLogonII.cxx b/common/rfb/CSecurityMSLogonII.cxx index a5a9928637..dfc0b65894 100644 --- a/common/rfb/CSecurityMSLogonII.cxx +++ b/common/rfb/CSecurityMSLogonII.cxx @@ -39,7 +39,6 @@ #include #include #include -#include using namespace rfb; diff --git a/common/rfb/CSecurityRSAAES.cxx b/common/rfb/CSecurityRSAAES.cxx index 0985d0f22c..513d560590 100644 --- a/common/rfb/CSecurityRSAAES.cxx +++ b/common/rfb/CSecurityRSAAES.cxx @@ -34,14 +34,17 @@ #include #include #include + +#include +#include + #include #include -#include #include -#include + #include #include -#include +#include enum { ReadPublicKey, @@ -55,7 +58,7 @@ const int MaxKeyLength = 8192; using namespace rfb; -static LogWriter vlog("CSecurityRSAAES"); +static core::LogWriter vlog("CSecurityRSAAES"); CSecurityRSAAES::CSecurityRSAAES(CConnection* cc_, uint32_t _secType, int _keySize, bool _isAllEncrypted) @@ -147,12 +150,12 @@ bool CSecurityRSAAES::processMsg() return false; } -static void random_func(void* ctx, size_t length, uint8_t* dst) +static void random_func(void*, size_t length, uint8_t* dst) { - rdr::RandomStream* rs = (rdr::RandomStream*)ctx; - if (!rs->hasData(length)) + rdr::RandomStream rs; + if (!rs.hasData(length)) throw std::runtime_error("Failed to generate random"); - rs->readBytes(dst, length); + rs.readBytes(dst, length); } void CSecurityRSAAES::writePublicKey() @@ -170,7 +173,7 @@ void CSecurityRSAAES::writePublicKey() // set e = 65537 mpz_set_ui(clientPublicKey.e, 65537); if (!rsa_generate_keypair(&clientPublicKey, &clientKey, - &rs, random_func, nullptr, nullptr, + nullptr, random_func, nullptr, nullptr, clientKeyLength, 0)) throw std::runtime_error("Failed to generate key"); clientKeyN = new uint8_t[rsaKeySize]; @@ -226,7 +229,7 @@ void CSecurityRSAAES::verifyServer() sha1_update(&ctx, serverKey.size, serverKeyE); sha1_digest(&ctx, sizeof(f), f); const char *title = "Server key fingerprint"; - std::string text = format( + std::string text = core::format( "The server has provided the following identifying information:\n" "Fingerprint: %02x-%02x-%02x-%02x-%02x-%02x-%02x-%02x\n" "Please verify that the information is correct and press \"Yes\". " @@ -237,6 +240,7 @@ void CSecurityRSAAES::verifyServer() void CSecurityRSAAES::writeRandom() { + rdr::RandomStream rs; rdr::OutStream* os = cc->getOutStream(); if (!rs.hasData(keySize / 8)) throw std::runtime_error("Failed to generate random"); diff --git a/common/rfb/CSecurityRSAAES.h b/common/rfb/CSecurityRSAAES.h index af380bd3ed..ecbfdc4fd9 100644 --- a/common/rfb/CSecurityRSAAES.h +++ b/common/rfb/CSecurityRSAAES.h @@ -29,7 +29,7 @@ #include #include -#include +namespace core { class IntParameter; } namespace rdr { class InStream; @@ -39,6 +39,7 @@ namespace rdr { } namespace rfb { + class CSecurityRSAAES : public CSecurity { public: CSecurityRSAAES(CConnection* cc, uint32_t secType, @@ -48,7 +49,7 @@ namespace rfb { int getType() const override { return secType; } bool isSecure() const override { return secType == secTypeRA256; } - static IntParameter RSAKeyLength; + static core::IntParameter RSAKeyLength; private: void cleanup(); @@ -86,9 +87,8 @@ namespace rfb { rdr::InStream* rawis; rdr::OutStream* rawos; - - rdr::RandomStream rs; }; + } #endif diff --git a/common/rfb/CSecurityStack.h b/common/rfb/CSecurityStack.h index 521597ec85..aec800f957 100644 --- a/common/rfb/CSecurityStack.h +++ b/common/rfb/CSecurityStack.h @@ -21,7 +21,6 @@ #define __RFB_CSECURITYSTACK_H__ #include -#include namespace rfb { diff --git a/common/rfb/CSecurityTLS.cxx b/common/rfb/CSecurityTLS.cxx index 0c10a85d61..8358daea50 100644 --- a/common/rfb/CSecurityTLS.cxx +++ b/common/rfb/CSecurityTLS.cxx @@ -34,15 +34,17 @@ #include #endif +#include +#include +#include + #include #include -#include #include -#include + #include #include #include -#include #include @@ -50,21 +52,21 @@ using namespace rfb; static const char* configdirfn(const char* fn); -StringParameter CSecurityTLS::X509CA("X509CA", "X509 CA certificate", - configdirfn("x509_ca.pem"), - ConfViewer); -StringParameter CSecurityTLS::X509CRL("X509CRL", "X509 CRL file", - configdirfn("x509_crl.pem"), - ConfViewer); +core::StringParameter CSecurityTLS::X509CA("X509CA", "X509 CA certificate", + configdirfn("x509_ca.pem"), + core::ConfViewer); +core::StringParameter CSecurityTLS::X509CRL("X509CRL", "X509 CRL file", + configdirfn("x509_crl.pem"), + core::ConfViewer); -static LogWriter vlog("TLS"); +static core::LogWriter vlog("TLS"); static const char* configdirfn(const char* fn) { static char full_path[PATH_MAX]; const char* configdir; - configdir = os::getvncconfigdir(); + configdir = core::getvncconfigdir(); if (configdir == nullptr) return ""; @@ -353,8 +355,8 @@ void CSecurityTLS::checkSession() gnutls_free(status_str.data); - throw protocol_error(format("Invalid server certificate: %s", - error.c_str())); + throw protocol_error( + core::format("Invalid server certificate: %s", error.c_str())); } err = gnutls_certificate_verification_status_print(status, @@ -398,7 +400,7 @@ void CSecurityTLS::checkSession() /* Certificate has some user overridable problems, so TOFU time */ - hostsDir = os::getvncstatedir(); + hostsDir = core::getvncstatedir(); if (hostsDir == nullptr) { throw std::runtime_error("Could not obtain VNC state directory " "path for known hosts storage"); @@ -443,16 +445,16 @@ void CSecurityTLS::checkSession() if (status & (GNUTLS_CERT_INVALID | GNUTLS_CERT_SIGNER_NOT_FOUND | GNUTLS_CERT_SIGNER_NOT_CA)) { - text = format("This certificate has been signed by an unknown " - "authority:\n" - "\n" - "%s\n" - "\n" - "Someone could be trying to impersonate the site " - "and you should not continue.\n" - "\n" - "Do you want to make an exception for this " - "server?", info.data); + text = core::format( + "This certificate has been signed by an unknown authority:\n" + "\n" + "%s\n" + "\n" + "Someone could be trying to impersonate the site and you " + "should not continue.\n" + "\n" + "Do you want to make an exception for this server?", + info.data); if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Unknown certificate issuer", @@ -465,15 +467,17 @@ void CSecurityTLS::checkSession() } if (status & GNUTLS_CERT_NOT_ACTIVATED) { - text = format("This certificate is not yet valid:\n" - "\n" - "%s\n" - "\n" - "Someone could be trying to impersonate the site " - "and you should not continue.\n" - "\n" - "Do you want to make an exception for this " - "server?", info.data); + text = core::format( + "This certificate is not yet valid:\n" + "\n" + "%s\n" + "\n" + "Someone could be trying to impersonate the site and you " + "should not continue.\n" + "\n" + "Do you want to make an exception for this server?", + info.data); + if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Certificate is not yet valid", text.c_str())) @@ -483,15 +487,16 @@ void CSecurityTLS::checkSession() } if (status & GNUTLS_CERT_EXPIRED) { - text = format("This certificate has expired:\n" - "\n" - "%s\n" - "\n" - "Someone could be trying to impersonate the site " - "and you should not continue.\n" - "\n" - "Do you want to make an exception for this " - "server?", info.data); + text = core::format( + "This certificate has expired:\n" + "\n" + "%s\n" + "\n" + "Someone could be trying to impersonate the site and you " + "should not continue.\n" + "\n" + "Do you want to make an exception for this server?", + info.data); if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Expired certificate", @@ -502,15 +507,16 @@ void CSecurityTLS::checkSession() } if (status & GNUTLS_CERT_INSECURE_ALGORITHM) { - text = format("This certificate uses an insecure algorithm:\n" - "\n" - "%s\n" - "\n" - "Someone could be trying to impersonate the site " - "and you should not continue.\n" - "\n" - "Do you want to make an exception for this " - "server?", info.data); + text = core::format( + "This certificate uses an insecure algorithm:\n" + "\n" + "%s\n" + "\n" + "Someone could be trying to impersonate the site and you " + "should not continue.\n" + "\n" + "Do you want to make an exception for this server?", + info.data); if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Insecure certificate algorithm", @@ -526,16 +532,17 @@ void CSecurityTLS::checkSession() } if (!hostname_match) { - text = format("The specified hostname \"%s\" does not match the " - "certificate provided by the server:\n" - "\n" - "%s\n" - "\n" - "Someone could be trying to impersonate the site " - "and you should not continue.\n" - "\n" - "Do you want to make an exception for this " - "server?", client->getServerName(), info.data); + text = core::format( + "The specified hostname \"%s\" does not match the certificate " + "provided by the server:\n" + "\n" + "%s\n" + "\n" + "Someone could be trying to impersonate the site and you " + "should not continue.\n" + "\n" + "Do you want to make an exception for this server?", + client->getServerName(), info.data); if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Certificate hostname mismatch", @@ -551,17 +558,18 @@ void CSecurityTLS::checkSession() if (status & (GNUTLS_CERT_INVALID | GNUTLS_CERT_SIGNER_NOT_FOUND | GNUTLS_CERT_SIGNER_NOT_CA)) { - text = format("This host is previously known with a different " - "certificate, and the new certificate has been " - "signed by an unknown authority:\n" - "\n" - "%s\n" - "\n" - "Someone could be trying to impersonate the site " - "and you should not continue.\n" - "\n" - "Do you want to make an exception for this " - "server?", info.data); + text = core::format( + "This host is previously known with a different certificate, " + "and the new certificate has been signed by an unknown " + "authority:\n" + "\n" + "%s\n" + "\n" + "Someone could be trying to impersonate the site and you " + "should not continue.\n" + "\n" + "Do you want to make an exception for this server?", + info.data); if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Unexpected server certificate", @@ -574,17 +582,17 @@ void CSecurityTLS::checkSession() } if (status & GNUTLS_CERT_NOT_ACTIVATED) { - text = format("This host is previously known with a different " - "certificate, and the new certificate is not yet " - "valid:\n" - "\n" - "%s\n" - "\n" - "Someone could be trying to impersonate the site " - "and you should not continue.\n" - "\n" - "Do you want to make an exception for this " - "server?", info.data); + text = core::format( + "This host is previously known with a different certificate, " + "and the new certificate is not yet valid:\n" + "\n" + "%s\n" + "\n" + "Someone could be trying to impersonate the site and you " + "should not continue.\n" + "\n" + "Do you want to make an exception for this server?", + info.data); if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Unexpected server certificate", @@ -595,17 +603,17 @@ void CSecurityTLS::checkSession() } if (status & GNUTLS_CERT_EXPIRED) { - text = format("This host is previously known with a different " - "certificate, and the new certificate has " - "expired:\n" - "\n" - "%s\n" - "\n" - "Someone could be trying to impersonate the site " - "and you should not continue.\n" - "\n" - "Do you want to make an exception for this " - "server?", info.data); + text = core::format( + "This host is previously known with a different certificate, " + "and the new certificate has expired:\n" + "\n" + "%s\n" + "\n" + "Someone could be trying to impersonate the site and you " + "should not continue.\n" + "\n" + "Do you want to make an exception for this server?", + info.data); if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Unexpected server certificate", @@ -616,17 +624,17 @@ void CSecurityTLS::checkSession() } if (status & GNUTLS_CERT_INSECURE_ALGORITHM) { - text = format("This host is previously known with a different " - "certificate, and the new certificate uses an " - "insecure algorithm:\n" - "\n" - "%s\n" - "\n" - "Someone could be trying to impersonate the site " - "and you should not continue.\n" - "\n" - "Do you want to make an exception for this " - "server?", info.data); + text = core::format( + "This host is previously known with a different certificate, " + "and the new certificate uses an insecure algorithm:\n" + "\n" + "%s\n" + "\n" + "Someone could be trying to impersonate the site and you " + "should not continue.\n" + "\n" + "Do you want to make an exception for this server?", + info.data); if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Unexpected server certificate", @@ -642,18 +650,18 @@ void CSecurityTLS::checkSession() } if (!hostname_match) { - text = format("This host is previously known with a different " - "certificate, and the specified hostname \"%s\" " - "does not match the new certificate provided by " - "the server:\n" - "\n" - "%s\n" - "\n" - "Someone could be trying to impersonate the site " - "and you should not continue.\n" - "\n" - "Do you want to make an exception for this " - "server?", client->getServerName(), info.data); + text = core::format( + "This host is previously known with a different certificate, " + "and the specified hostname \"%s\" does not match the new " + "certificate provided by the server:\n" + "\n" + "%s\n" + "\n" + "Someone could be trying to impersonate the site and you " + "should not continue.\n" + "\n" + "Do you want to make an exception for this server?", + client->getServerName(), info.data); if (!cc->showMsgBox(MsgBoxFlags::M_YESNO, "Unexpected server certificate", diff --git a/common/rfb/CSecurityTLS.h b/common/rfb/CSecurityTLS.h index 2464cb6c5d..9b70366de7 100644 --- a/common/rfb/CSecurityTLS.h +++ b/common/rfb/CSecurityTLS.h @@ -47,8 +47,8 @@ namespace rfb { int getType() const override { return anon ? secTypeTLSNone : secTypeX509None; } bool isSecure() const override { return !anon; } - static StringParameter X509CA; - static StringParameter X509CRL; + static core::StringParameter X509CA; + static core::StringParameter X509CRL; protected: void shutdown(); diff --git a/common/rfb/CSecurityVeNCrypt.cxx b/common/rfb/CSecurityVeNCrypt.cxx index 1b6ecf2205..a6e309479d 100644 --- a/common/rfb/CSecurityVeNCrypt.cxx +++ b/common/rfb/CSecurityVeNCrypt.cxx @@ -29,16 +29,17 @@ #include #include +#include + #include #include #include #include #include -#include using namespace rfb; -static LogWriter vlog("CVeNCrypt"); +static core::LogWriter vlog("CVeNCrypt"); CSecurityVeNCrypt::CSecurityVeNCrypt(CConnection* cc_, SecurityClient* sec) diff --git a/common/rfb/CSecurityVeNCrypt.h b/common/rfb/CSecurityVeNCrypt.h index f73e7927c2..8e2c6d5e31 100644 --- a/common/rfb/CSecurityVeNCrypt.h +++ b/common/rfb/CSecurityVeNCrypt.h @@ -28,10 +28,11 @@ #include #include -#include namespace rfb { + class SecurityClient; + class CSecurityVeNCrypt : public CSecurity { public: diff --git a/common/rfb/ClientParams.cxx b/common/rfb/ClientParams.cxx index e5fd105e38..972b89e8f7 100644 --- a/common/rfb/ClientParams.cxx +++ b/common/rfb/ClientParams.cxx @@ -24,11 +24,14 @@ #include +#include + #include #include #include #include -#include +#include +#include using namespace rfb; @@ -41,7 +44,11 @@ ClientParams::ClientParams() { setName(""); - cursor_ = new Cursor(0, 0, Point(), nullptr); + screenLayout_ = new ScreenSet(); + + pf_ = new PixelFormat(); + + cursor_ = new Cursor(0, 0, {}, nullptr); clipFlags = clipboardUTF8 | clipboardRTF | clipboardHTML | clipboardRequest | clipboardNotify | clipboardProvide; @@ -51,7 +58,9 @@ ClientParams::ClientParams() ClientParams::~ClientParams() { + delete screenLayout_; delete cursor_; + delete pf_; } void ClientParams::setDimensions(int width, int height) @@ -68,12 +77,14 @@ void ClientParams::setDimensions(int width, int height, const ScreenSet& layout) width_ = width; height_ = height; - screenLayout_ = layout; + delete screenLayout_; + screenLayout_ = new ScreenSet(layout); } void ClientParams::setPF(const PixelFormat& pf) { - pf_ = pf; + delete pf_; + pf_ = new PixelFormat(pf); if (pf.bpp != 8 && pf.bpp != 16 && pf.bpp != 32) throw std::invalid_argument("setPF: Not 8, 16 or 32 bpp?"); @@ -90,7 +101,7 @@ void ClientParams::setCursor(const Cursor& other) cursor_ = new Cursor(other); } -void ClientParams::setCursorPos(const Point& pos) +void ClientParams::setCursorPos(const core::Point& pos) { cursorPos_ = pos; } @@ -162,7 +173,7 @@ uint32_t ClientParams::clipboardSize(unsigned int format) const return clipSizes[i]; } - throw std::invalid_argument(rfb::format("Invalid clipboard format 0x%x", format)); + throw std::invalid_argument(core::format("Invalid clipboard format 0x%x", format)); } void ClientParams::setClipboardCaps(uint32_t flags, const uint32_t* lengths) diff --git a/common/rfb/ClientParams.h b/common/rfb/ClientParams.h index f715c47f16..0910181bc7 100644 --- a/common/rfb/ClientParams.h +++ b/common/rfb/ClientParams.h @@ -28,12 +28,14 @@ #include -#include -#include -#include +#include namespace rfb { + class Cursor; + class PixelFormat; + struct ScreenSet; + const int subsampleUndefined = -1; const int subsampleNone = 0; const int subsampleGray = 1; @@ -66,11 +68,11 @@ namespace rfb { int width() const { return width_; } int height() const { return height_; } - const ScreenSet& screenLayout() const { return screenLayout_; } + const ScreenSet& screenLayout() const { return *screenLayout_; } void setDimensions(int width, int height); void setDimensions(int width, int height, const ScreenSet& layout); - const PixelFormat& pf() const { return pf_; } + const PixelFormat& pf() const { return *pf_; } void setPF(const PixelFormat& pf); const char* name() const { return name_.c_str(); } @@ -79,8 +81,8 @@ namespace rfb { const Cursor& cursor() const { return *cursor_; } void setCursor(const Cursor& cursor); - const Point& cursorPos() const { return cursorPos_; } - void setCursorPos(const Point& pos); + const core::Point& cursorPos() const { return cursorPos_; } + void setCursorPos(const core::Point& pos); bool supportsEncoding(int32_t encoding) const; @@ -112,12 +114,12 @@ namespace rfb { int width_; int height_; - ScreenSet screenLayout_; + ScreenSet* screenLayout_; - PixelFormat pf_; + PixelFormat* pf_; std::string name_; Cursor* cursor_; - Point cursorPos_; + core::Point cursorPos_; std::set encodings_; unsigned int ledState_; uint32_t clipFlags; diff --git a/common/rfb/ComparingUpdateTracker.cxx b/common/rfb/ComparingUpdateTracker.cxx index dab5e6aa26..54839958d2 100644 --- a/common/rfb/ComparingUpdateTracker.cxx +++ b/common/rfb/ComparingUpdateTracker.cxx @@ -22,17 +22,18 @@ #include #include + +#include #include -#include -#include -#include +#include +#include #include using namespace rfb; -static LogWriter vlog("ComparingUpdateTracker"); +static core::LogWriter vlog("ComparingUpdateTracker"); ComparingUpdateTracker::ComparingUpdateTracker(PixelBuffer* buffer) : fb(buffer), oldFb(fb->getPF(), 0, 0), firstCompare(true), @@ -50,8 +51,8 @@ ComparingUpdateTracker::~ComparingUpdateTracker() bool ComparingUpdateTracker::compare() { - std::vector rects; - std::vector::iterator i; + std::vector rects; + std::vector::iterator i; if (!enabled) return false; @@ -62,7 +63,7 @@ bool ComparingUpdateTracker::compare() oldFb.setSize(fb->width(), fb->height()); for (int y=0; yheight(); y+=BLOCK_SIZE) { - Rect pos(0, y, fb->width(), __rfbmin(fb->height(), y+BLOCK_SIZE)); + core::Rect pos(0, y, fb->width(), std::min(fb->height(), y+BLOCK_SIZE)); int srcStride; const uint8_t* srcData = fb->getBuffer(pos, &srcStride); oldFb.imageRect(pos, srcData, srcStride); @@ -79,7 +80,7 @@ bool ComparingUpdateTracker::compare() changed.get_rects(&rects); - Region newChanged; + core::Region newChanged; for (i = rects.begin(); i != rects.end(); i++) compareRect(*i, &newChanged); @@ -111,10 +112,11 @@ void ComparingUpdateTracker::disable() firstCompare = true; } -void ComparingUpdateTracker::compareRect(const Rect& r, Region* newChanged) +void ComparingUpdateTracker::compareRect(const core::Rect& r, + core::Region* newChanged) { if (!r.enclosed_by(fb->getRect())) { - Rect safe; + core::Rect safe; // Crop the rect and try again safe = r.intersect(fb->getRect()); if (!safe.is_empty()) @@ -134,20 +136,20 @@ void ComparingUpdateTracker::compareRect(const Rect& r, Region* newChanged) for (int blockTop = r.tl.y; blockTop < r.br.y; blockTop += BLOCK_SIZE) { // Get a strip of the source buffer - Rect pos(r.tl.x, blockTop, r.br.x, __rfbmin(r.br.y, blockTop+BLOCK_SIZE)); + core::Rect pos(r.tl.x, blockTop, r.br.x, std::min(r.br.y, blockTop+BLOCK_SIZE)); int fbStride; const uint8_t* newBlockPtr = fb->getBuffer(pos, &fbStride); int newStrideBytes = fbStride * bytesPerPixel; uint8_t* oldBlockPtr = oldData; - int blockBottom = __rfbmin(blockTop+BLOCK_SIZE, r.br.y); + int blockBottom = std::min(blockTop+BLOCK_SIZE, r.br.y); for (int blockLeft = r.tl.x; blockLeft < r.br.x; blockLeft += BLOCK_SIZE) { const uint8_t* newPtr = newBlockPtr; uint8_t* oldPtr = oldBlockPtr; - int blockRight = __rfbmin(blockLeft+BLOCK_SIZE, r.br.x); + int blockRight = std::min(blockLeft+BLOCK_SIZE, r.br.x); int blockWidthInBytes = (blockRight-blockLeft) * bytesPerPixel; // Scan the block top to bottom, to identify the first row of change @@ -223,8 +225,10 @@ void ComparingUpdateTracker::compareRect(const Rect& r, Region* newChanged) } endOfChangeRight: - // Block change extends from (changeLeft, y) to (changeRight, y + changeHeight) - newChanged->assign_union(Region(Rect(changeLeft, y, changeRight, y + changeHeight))); + // Block change extends from (changeLeft, y) to (changeRight, + // y + changeHeight) + newChanged->assign_union({{changeLeft, y, + changeRight, y + changeHeight}}); // Copy the change from fb to oldFb to allow future changes to be identified for (int row = 0; row < changeHeight; row++) @@ -259,8 +263,8 @@ void ComparingUpdateTracker::logStats() ratio = (double)totalPixels / missedPixels; vlog.info("%s in / %s out", - siPrefix(totalPixels, "pixels").c_str(), - siPrefix(missedPixels, "pixels").c_str()); + core::siPrefix(totalPixels, "pixels").c_str(), + core::siPrefix(missedPixels, "pixels").c_str()); vlog.info("(1:%g ratio)", ratio); totalPixels = missedPixels = 0; diff --git a/common/rfb/ComparingUpdateTracker.h b/common/rfb/ComparingUpdateTracker.h index ca1dcc303f..dbe7a4ef93 100644 --- a/common/rfb/ComparingUpdateTracker.h +++ b/common/rfb/ComparingUpdateTracker.h @@ -19,6 +19,7 @@ #ifndef __RFB_COMPARINGUPDATETRACKER_H__ #define __RFB_COMPARINGUPDATETRACKER_H__ +#include #include namespace rfb { @@ -44,7 +45,7 @@ namespace rfb { void logStats(); private: - void compareRect(const Rect& r, Region* newchanged); + void compareRect(const core::Rect& r, core::Region* newchanged); PixelBuffer* fb; ManagedPixelBuffer oldFb; bool firstCompare; diff --git a/common/rfb/Congestion.cxx b/common/rfb/Congestion.cxx index 94f07055de..46bae00da4 100644 --- a/common/rfb/Congestion.cxx +++ b/common/rfb/Congestion.cxx @@ -49,9 +49,10 @@ #include #endif +#include +#include + #include -#include -#include // Debug output on what the congestion control is up to #undef CONGESTION_DEBUG @@ -78,7 +79,7 @@ static inline bool isAfter(unsigned a, unsigned b) { return a != b && a - b <= UINT_MAX / 2; } -static LogWriter vlog("Congestion"); +static core::LogWriter vlog("Congestion"); Congestion::Congestion() : lastPosition(0), extraBuffer(0), @@ -99,7 +100,7 @@ Congestion::~Congestion() void Congestion::updatePosition(unsigned pos) { struct timeval now; - unsigned delta, consumed; + unsigned idle, delta, consumed; gettimeofday(&now, nullptr); @@ -110,15 +111,17 @@ void Congestion::updatePosition(unsigned pos) // Idle for too long? // We use a very crude RTO calculation in order to keep things simple // FIXME: should implement RFC 2861 - if (msBetween(&lastSent, &now) > __rfbmax(baseRTT*2, 100)) { + idle = core::msBetween(&lastSent, &now); + if (idle > 100 && idle > baseRTT*2) { #ifdef CONGESTION_DEBUG vlog.debug("Connection idle for %d ms, resetting congestion control", - msBetween(&lastSent, &now)); + idle); #endif // Close congestion window and redo wire latency measurement - congWindow = __rfbmin(INITIAL_WINDOW, congWindow); + if (congWindow > INITIAL_WINDOW) + congWindow = INITIAL_WINDOW; baseRTT = -1; measurements = 0; gettimeofday(&lastAdjustment, nullptr); @@ -132,7 +135,7 @@ void Congestion::updatePosition(unsigned pos) // (we cannot do this until we have a RTT measurement though) if (baseRTT != (unsigned)-1) { extraBuffer += delta; - consumed = msBetween(&lastUpdate, &now) * congWindow / baseRTT; + consumed = core::msBetween(&lastUpdate, &now) * congWindow / baseRTT; if (extraBuffer < consumed) extraBuffer = 0; else @@ -174,7 +177,7 @@ void Congestion::gotPong() lastPong = rttInfo; lastPongArrival = now; - rtt = msBetween(&rttInfo.tv, &now); + rtt = core::msBetween(&rttInfo.tv, &now); if (rtt < 1) rtt = 1; @@ -184,7 +187,7 @@ void Congestion::gotPong() // Pings sent before the last adjustment aren't interesting as they // aren't a measurement of the current congestion window - if (isBefore(&rttInfo.tv, &lastAdjustment)) + if (core::isBefore(&rttInfo.tv, &lastAdjustment)) return; // Estimate added delay because of overtaxed buffers (see above) @@ -249,7 +252,7 @@ int Congestion::getUncongestedETA() prevPing = &lastPong; eta = 0; - elapsed = msSince(&lastPongArrival); + elapsed = core::msSince(&lastPongArrival); // Walk the ping queue and figure out which one we are waiting for to // get to an uncongested state @@ -268,7 +271,7 @@ int Congestion::getUncongestedETA() curPing = *iter; } - etaNext = msBetween(&prevPing->tv, &curPing.tv); + etaNext = core::msBetween(&prevPing->tv, &curPing.tv); // Compensate for buffering delays delay = curPing.extra * baseRTT / congWindow; etaNext += delay; @@ -349,7 +352,7 @@ unsigned Congestion::getExtraBuffer() if (baseRTT == (unsigned)-1) return 0; - elapsed = msSince(&lastUpdate); + elapsed = core::msSince(&lastUpdate); consumed = elapsed * congWindow / baseRTT; if (consumed >= extraBuffer) @@ -389,7 +392,7 @@ unsigned Congestion::getInFlight() // completely. Look at the next ping that should arrive and figure // out how far behind it should be and interpolate the positions. - etaNext = msBetween(&lastPong.tv, &nextPong.tv); + etaNext = core::msBetween(&lastPong.tv, &nextPong.tv); // Compensate for buffering delays delay = nextPong.extra * baseRTT / congWindow; etaNext += delay; @@ -399,7 +402,7 @@ unsigned Congestion::getInFlight() else etaNext -= delay; - elapsed = msSince(&lastPongArrival); + elapsed = core::msSince(&lastPongArrival); // The pong should be here any second. Be optimistic and assume // we can already use its value. @@ -430,7 +433,7 @@ void Congestion::updateCongestion() diff = minRTT - baseRTT; - if (diff > __rfbmax(100, baseRTT/2)) { + if (diff > 100 && diff > baseRTT/2) { // We have no way of detecting loss, so assume massive latency // spike means packet loss. Adjust the window and go directly // to congestion avoidance. diff --git a/common/rfb/CopyRectDecoder.cxx b/common/rfb/CopyRectDecoder.cxx index a73838811f..efc77c99e9 100644 --- a/common/rfb/CopyRectDecoder.cxx +++ b/common/rfb/CopyRectDecoder.cxx @@ -20,10 +20,12 @@ #include #endif +#include + #include #include + #include -#include #include using namespace rfb; @@ -36,7 +38,7 @@ CopyRectDecoder::~CopyRectDecoder() { } -bool CopyRectDecoder::readRect(const Rect& /*r*/, +bool CopyRectDecoder::readRect(const core::Rect& /*r*/, rdr::InStream* is, const ServerParams& /*server*/, rdr::OutStream* os) @@ -48,11 +50,11 @@ bool CopyRectDecoder::readRect(const Rect& /*r*/, } -void CopyRectDecoder::getAffectedRegion(const Rect& rect, +void CopyRectDecoder::getAffectedRegion(const core::Rect& rect, const uint8_t* buffer, size_t buflen, const ServerParams& server, - Region* region) + core::Region* region) { rdr::MemInStream is(buffer, buflen); int srcX = is.readU16(); @@ -60,11 +62,12 @@ void CopyRectDecoder::getAffectedRegion(const Rect& rect, Decoder::getAffectedRegion(rect, buffer, buflen, server, region); - region->assign_union(Region(rect.translate(Point(srcX-rect.tl.x, - srcY-rect.tl.y)))); + region->assign_union(rect.translate({srcX-rect.tl.x, + srcY-rect.tl.y})); } -void CopyRectDecoder::decodeRect(const Rect& r, const uint8_t* buffer, +void CopyRectDecoder::decodeRect(const core::Rect& r, + const uint8_t* buffer, size_t buflen, const ServerParams& /*server*/, ModifiablePixelBuffer* pb) @@ -72,5 +75,5 @@ void CopyRectDecoder::decodeRect(const Rect& r, const uint8_t* buffer, rdr::MemInStream is(buffer, buflen); int srcX = is.readU16(); int srcY = is.readU16(); - pb->copyRect(r, Point(r.tl.x-srcX, r.tl.y-srcY)); + pb->copyRect(r, {r.tl.x-srcX, r.tl.y-srcY}); } diff --git a/common/rfb/CopyRectDecoder.h b/common/rfb/CopyRectDecoder.h index 5165119624..b1d0d38dbe 100644 --- a/common/rfb/CopyRectDecoder.h +++ b/common/rfb/CopyRectDecoder.h @@ -26,13 +26,13 @@ namespace rfb { public: CopyRectDecoder(); virtual ~CopyRectDecoder(); - bool readRect(const Rect& r, rdr::InStream* is, + bool readRect(const core::Rect& r, rdr::InStream* is, const ServerParams& server, rdr::OutStream* os) override; - void getAffectedRegion(const Rect& rect, const uint8_t* buffer, + void getAffectedRegion(const core::Rect& rect, const uint8_t* buffer, size_t buflen, const ServerParams& server, - Region* region) override; - void decodeRect(const Rect& r, const uint8_t* buffer, + core::Region* region) override; + void decodeRect(const core::Rect& r, const uint8_t* buffer, size_t buflen, const ServerParams& server, ModifiablePixelBuffer* pb) override; }; diff --git a/common/rfb/Cursor.cxx b/common/rfb/Cursor.cxx index 9484414415..e094e4ed7c 100644 --- a/common/rfb/Cursor.cxx +++ b/common/rfb/Cursor.cxx @@ -26,14 +26,15 @@ #include +#include + #include -#include using namespace rfb; -static LogWriter vlog("Cursor"); +static core::LogWriter vlog("Cursor"); -Cursor::Cursor(int width, int height, const Point& hotspot, +Cursor::Cursor(int width, int height, const core::Point& hotspot, const uint8_t* data_) : width_(width), height_(height), hotspot_(hotspot) { @@ -215,9 +216,9 @@ std::vector Cursor::getMask() const void Cursor::crop() { - Rect busy = Rect(0, 0, width_, height_); - busy = busy.intersect(Rect(hotspot_.x, hotspot_.y, - hotspot_.x+1, hotspot_.y+1)); + core::Rect busy(0, 0, width_, height_); + busy = busy.intersect({hotspot_.x, hotspot_.y, + hotspot_.x+1, hotspot_.y+1}); int x, y; uint8_t *data_ptr = data; for (y = 0; y < height(); y++) { @@ -255,9 +256,10 @@ RenderedCursor::RenderedCursor() { } -const uint8_t* RenderedCursor::getBuffer(const Rect& _r, int* stride) const +const uint8_t* RenderedCursor::getBuffer(const core::Rect& _r, + int* stride) const { - Rect r; + core::Rect r; r = _r.translate(offset.negate()); if (!r.enclosed_by(buffer.getRect())) @@ -267,10 +269,10 @@ const uint8_t* RenderedCursor::getBuffer(const Rect& _r, int* stride) const } void RenderedCursor::update(PixelBuffer* framebuffer, - Cursor* cursor, const Point& pos) + Cursor* cursor, const core::Point& pos) { - Point rawOffset, diff; - Rect clippedRect; + core::Point rawOffset, diff; + core::Rect clippedRect; const uint8_t* data; int stride; @@ -282,7 +284,7 @@ void RenderedCursor::update(PixelBuffer* framebuffer, setSize(framebuffer->width(), framebuffer->height()); rawOffset = pos.subtract(cursor->hotspot()); - clippedRect = Rect(0, 0, cursor->width(), cursor->height()) + clippedRect = core::Rect(0, 0, cursor->width(), cursor->height()) .translate(rawOffset) .intersect(framebuffer->getRect()); offset = clippedRect.tl; @@ -313,7 +315,7 @@ void RenderedCursor::update(PixelBuffer* framebuffer, else if (fg[3] == 0xff) { memcpy(rgb, fg, 3); } else { - buffer.getImage(bg, Rect(x, y, x+1, y+1)); + buffer.getImage(bg, {x, y, x+1, y+1}); format.rgbFromBuffer(rgb, bg, 1); // FIXME: Gamma aware blending for (int i = 0;i < 3;i++) { @@ -323,7 +325,7 @@ void RenderedCursor::update(PixelBuffer* framebuffer, } format.bufferFromRGB(bg, rgb, 1); - buffer.imageRect(Rect(x, y, x+1, y+1), bg); + buffer.imageRect({x, y, x+1, y+1}, bg); } } } diff --git a/common/rfb/Cursor.h b/common/rfb/Cursor.h index c71f5a77a5..ef3c1b8090 100644 --- a/common/rfb/Cursor.h +++ b/common/rfb/Cursor.h @@ -26,19 +26,22 @@ #include +#include + #include namespace rfb { class Cursor { public: - Cursor(int width, int height, const Point& hotspot, const uint8_t* data); + Cursor(int width, int height, const core::Point& hotspot, + const uint8_t* data); Cursor(const Cursor& other); ~Cursor(); int width() const { return width_; }; int height() const { return height_; }; - const Point& hotspot() const { return hotspot_; }; + const core::Point& hotspot() const { return hotspot_; }; const uint8_t* getBuffer() const { return data; }; // getBitmap() returns a monochrome version of the cursor @@ -52,7 +55,7 @@ namespace rfb { protected: int width_, height_; - Point hotspot_; + core::Point hotspot_; uint8_t* data; }; @@ -60,15 +63,16 @@ namespace rfb { public: RenderedCursor(); - Rect getEffectiveRect() const { return buffer.getRect(offset); } + core::Rect getEffectiveRect() const { return buffer.getRect(offset); } - const uint8_t* getBuffer(const Rect& r, int* stride) const override; + const uint8_t* getBuffer(const core::Rect& r, int* stride) const override; - void update(PixelBuffer* framebuffer, Cursor* cursor, const Point& pos); + void update(PixelBuffer* framebuffer, Cursor* cursor, + const core::Point& pos); protected: ManagedPixelBuffer buffer; - Point offset; + core::Point offset; }; } diff --git a/common/rfb/DecodeManager.cxx b/common/rfb/DecodeManager.cxx index 4effe985ed..97a905490d 100644 --- a/common/rfb/DecodeManager.cxx +++ b/common/rfb/DecodeManager.cxx @@ -23,22 +23,21 @@ #include #include +#include +#include +#include +#include + #include #include #include #include -#include -#include -#include -#include #include -#include - using namespace rfb; -static LogWriter vlog("DecodeManager"); +static core::LogWriter vlog("DecodeManager"); DecodeManager::DecodeManager(CConnection *conn_) : conn(conn_), threadException(nullptr) @@ -49,11 +48,11 @@ DecodeManager::DecodeManager(CConnection *conn_) : memset(stats, 0, sizeof(stats)); - queueMutex = new os::Mutex(); - producerCond = new os::Condition(queueMutex); - consumerCond = new os::Condition(queueMutex); + queueMutex = new core::Mutex(); + producerCond = new core::Condition(queueMutex); + consumerCond = new core::Condition(queueMutex); - cpuCount = os::Thread::getSystemCPUCount(); + cpuCount = core::Thread::getSystemCPUCount(); if (cpuCount == 0) { vlog.error("Unable to determine the number of CPU cores on this system"); cpuCount = 1; @@ -101,7 +100,7 @@ DecodeManager::~DecodeManager() delete decoder; } -bool DecodeManager::decodeRect(const Rect& r, int encoding, +bool DecodeManager::decodeRect(const core::Rect& r, int encoding, ModifiablePixelBuffer* pb) { Decoder *decoder; @@ -149,7 +148,7 @@ bool DecodeManager::decodeRect(const Rect& r, int encoding, if (!decoder->readRect(r, conn->getInStream(), conn->server, bufferStream)) return false; } catch (std::exception& e) { - throw std::runtime_error(format("Error reading rect: %s", e.what())); + throw std::runtime_error(core::format("Error reading rect: %s", e.what())); } stats[encoding].rects++; @@ -227,35 +226,36 @@ void DecodeManager::logStats() ratio = (double)stats[i].equivalent / stats[i].bytes; vlog.info(" %s: %s, %s", encodingName(i), - siPrefix(stats[i].rects, "rects").c_str(), - siPrefix(stats[i].pixels, "pixels").c_str()); + core::siPrefix(stats[i].rects, "rects").c_str(), + core::siPrefix(stats[i].pixels, "pixels").c_str()); vlog.info(" %*s %s (1:%g ratio)", (int)strlen(encodingName(i)), "", - iecPrefix(stats[i].bytes, "B").c_str(), ratio); + core::iecPrefix(stats[i].bytes, "B").c_str(), ratio); } ratio = (double)equivalent / bytes; vlog.info(" Total: %s, %s", - siPrefix(rects, "rects").c_str(), - siPrefix(pixels, "pixels").c_str()); + core::siPrefix(rects, "rects").c_str(), + core::siPrefix(pixels, "pixels").c_str()); vlog.info(" %s (1:%g ratio)", - iecPrefix(bytes, "B").c_str(), ratio); + core::iecPrefix(bytes, "B").c_str(), ratio); } void DecodeManager::setThreadException(const std::exception& e) { - os::AutoMutex a(queueMutex); + core::AutoMutex a(queueMutex); if (threadException != nullptr) return; - threadException = new std::runtime_error(format("Exception on worker thread: %s", e.what())); + threadException = new std::runtime_error( + core::format("Exception on worker thread: %s", e.what())); } void DecodeManager::throwThreadException() { - os::AutoMutex a(queueMutex); + core::AutoMutex a(queueMutex); if (threadException == nullptr) return; @@ -282,7 +282,7 @@ DecodeManager::DecodeThread::~DecodeThread() void DecodeManager::DecodeThread::stop() { - os::AutoMutex a(manager->queueMutex); + core::AutoMutex a(manager->queueMutex); if (!isRunning()) return; @@ -344,7 +344,7 @@ void DecodeManager::DecodeThread::worker() DecodeManager::QueueEntry* DecodeManager::DecodeThread::findEntry() { - Region lockedRegion; + core::Region lockedRegion; if (manager->workQueue.empty()) return nullptr; diff --git a/common/rfb/DecodeManager.h b/common/rfb/DecodeManager.h index b11b704492..a26f5fd6de 100644 --- a/common/rfb/DecodeManager.h +++ b/common/rfb/DecodeManager.h @@ -21,14 +21,15 @@ #include -#include +#include +#include -#include #include -namespace os { +namespace core { class Condition; class Mutex; + struct Rect; } namespace rdr { @@ -36,17 +37,17 @@ namespace rdr { } namespace rfb { + class CConnection; class Decoder; class ModifiablePixelBuffer; - struct Rect; class DecodeManager { public: DecodeManager(CConnection *conn); ~DecodeManager(); - bool decodeRect(const Rect& r, int encoding, + bool decodeRect(const core::Rect& r, int encoding, ModifiablePixelBuffer* pb); void flush(); @@ -72,24 +73,24 @@ namespace rfb { struct QueueEntry { bool active; - Rect rect; + core::Rect rect; int encoding; Decoder* decoder; const ServerParams* server; ModifiablePixelBuffer* pb; rdr::MemOutStream* bufferStream; - Region affectedRegion; + core::Region affectedRegion; }; std::list freeBuffers; std::list workQueue; - os::Mutex* queueMutex; - os::Condition* producerCond; - os::Condition* consumerCond; + core::Mutex* queueMutex; + core::Condition* producerCond; + core::Condition* consumerCond; private: - class DecodeThread : public os::Thread { + class DecodeThread : public core::Thread { public: DecodeThread(DecodeManager* manager); ~DecodeThread(); @@ -109,6 +110,7 @@ namespace rfb { std::list threads; std::exception *threadException; }; + } #endif diff --git a/common/rfb/Decoder.cxx b/common/rfb/Decoder.cxx index e9bc9a4ff5..0f1cde8901 100644 --- a/common/rfb/Decoder.cxx +++ b/common/rfb/Decoder.cxx @@ -22,8 +22,10 @@ #endif #include + +#include + #include -#include #include #include #include @@ -45,19 +47,19 @@ Decoder::~Decoder() { } -void Decoder::getAffectedRegion(const Rect& rect, +void Decoder::getAffectedRegion(const core::Rect& rect, const uint8_t* /*buffer*/, size_t /*buflen*/, const ServerParams& /*server*/, - Region* region) + core::Region* region) { region->reset(rect); } -bool Decoder::doRectsConflict(const Rect& /*rectA*/, +bool Decoder::doRectsConflict(const core::Rect& /*rectA*/, const uint8_t* /*bufferA*/, size_t /*buflenA*/, - const Rect& /*rectB*/, + const core::Rect& /*rectB*/, const uint8_t* /*bufferB*/, size_t /*buflenB*/, const ServerParams& /*server*/) diff --git a/common/rfb/Decoder.h b/common/rfb/Decoder.h index 7798773737..c30b4e63f3 100644 --- a/common/rfb/Decoder.h +++ b/common/rfb/Decoder.h @@ -21,17 +21,20 @@ #include +namespace core { + class Region; + struct Rect; +} + namespace rdr { class InStream; class OutStream; } namespace rfb { + class ServerParams; class ModifiablePixelBuffer; - class Region; - - struct Rect; enum DecoderFlags { // A constant for decoders that don't need anything special @@ -54,7 +57,7 @@ namespace rfb { // InStream to the OutStream, possibly changing it along the way to // make it easier to decode. This function will always be called in // a serial manner on the main thread. - virtual bool readRect(const Rect& r, rdr::InStream* is, + virtual bool readRect(const core::Rect& r, rdr::InStream* is, const ServerParams& server, rdr::OutStream* os)=0; // These functions will be called from any of the worker threads. @@ -64,17 +67,17 @@ namespace rfb { // getAffectedRegion() returns the parts of the frame buffer will // be either read from or written do when decoding this rect. The // default implementation simply returns the given rectangle. - virtual void getAffectedRegion(const Rect& rect, const uint8_t* buffer, + virtual void getAffectedRegion(const core::Rect& rect, const uint8_t* buffer, size_t buflen, const ServerParams& server, - Region* region); + core::Region* region); // doesRectsConflict() determines if two rectangles must be decoded // in the order they were received. This will only be called if the // DecoderPartiallyOrdered flag has been set. - virtual bool doRectsConflict(const Rect& rectA, + virtual bool doRectsConflict(const core::Rect& rectA, const uint8_t* bufferA, size_t buflenA, - const Rect& rectB, + const core::Rect& rectB, const uint8_t* bufferB, size_t buflenB, const ServerParams& server); @@ -83,7 +86,7 @@ namespace rfb { // given buffer, onto the ModifiablePixelBuffer. The PixelFormat of // the PixelBuffer might not match the ConnParams and it is up to // the decoder to do any necessary conversion. - virtual void decodeRect(const Rect& r, const uint8_t* buffer, + virtual void decodeRect(const core::Rect& r, const uint8_t* buffer, size_t buflen, const ServerParams& server, ModifiablePixelBuffer* pb)=0; @@ -94,6 +97,7 @@ namespace rfb { public: const enum DecoderFlags flags; }; + } #endif diff --git a/common/rfb/EncodeManager.cxx b/common/rfb/EncodeManager.cxx index 67a32f5b45..7ec70e69c5 100644 --- a/common/rfb/EncodeManager.cxx +++ b/common/rfb/EncodeManager.cxx @@ -25,14 +25,17 @@ #include +#include +#include + +#include #include #include #include #include #include #include -#include -#include +#include #include #include @@ -43,7 +46,7 @@ using namespace rfb; -static LogWriter vlog("EncodeManager"); +static core::LogWriter vlog("EncodeManager"); // Split each rectangle into smaller ones no larger than this area, // and no wider than this width. @@ -191,11 +194,11 @@ void EncodeManager::logStats() ratio = (double)copyStats.equivalent / copyStats.bytes; vlog.info(" %s: %s, %s", "Copies", - siPrefix(copyStats.rects, "rects").c_str(), - siPrefix(copyStats.pixels, "pixels").c_str()); + core::siPrefix(copyStats.rects, "rects").c_str(), + core::siPrefix(copyStats.pixels, "pixels").c_str()); vlog.info(" %*s %s (1:%g ratio)", (int)strlen("Copies"), "", - iecPrefix(copyStats.bytes, "B").c_str(), ratio); + core::iecPrefix(copyStats.bytes, "B").c_str(), ratio); } for (i = 0;i < stats.size();i++) { @@ -221,21 +224,21 @@ void EncodeManager::logStats() ratio = (double)stats[i][j].equivalent / stats[i][j].bytes; vlog.info(" %s: %s, %s", encoderTypeName((EncoderType)j), - siPrefix(stats[i][j].rects, "rects").c_str(), - siPrefix(stats[i][j].pixels, "pixels").c_str()); + core::siPrefix(stats[i][j].rects, "rects").c_str(), + core::siPrefix(stats[i][j].pixels, "pixels").c_str()); vlog.info(" %*s %s (1:%g ratio)", (int)strlen(encoderTypeName((EncoderType)j)), "", - iecPrefix(stats[i][j].bytes, "B").c_str(), ratio); + core::iecPrefix(stats[i][j].bytes, "B").c_str(), ratio); } } ratio = (double)equivalent / bytes; vlog.info(" Total: %s, %s", - siPrefix(rects, "rects").c_str(), - siPrefix(pixels, "pixels").c_str()); + core::siPrefix(rects, "rects").c_str(), + core::siPrefix(pixels, "pixels").c_str()); vlog.info(" %s (1:%g ratio)", - iecPrefix(bytes, "B").c_str(), ratio); + core::iecPrefix(bytes, "B").c_str(), ratio); } bool EncodeManager::supported(int encoding) @@ -252,12 +255,12 @@ bool EncodeManager::supported(int encoding) } } -bool EncodeManager::needsLosslessRefresh(const Region& req) +bool EncodeManager::needsLosslessRefresh(const core::Region& req) { return !lossyRegion.intersect(req).is_empty(); } -int EncodeManager::getNextLosslessRefresh(const Region& req) +int EncodeManager::getNextLosslessRefresh(const core::Region& req) { // Do we have something we can send right away? if (!pendingRefreshRegion.intersect(req).is_empty()) @@ -269,7 +272,7 @@ int EncodeManager::getNextLosslessRefresh(const Region& req) return recentChangeTimer.getNextTimeout(); } -void EncodeManager::pruneLosslessRefresh(const Region& limits) +void EncodeManager::pruneLosslessRefresh(const core::Region& limits) { lossyRegion.assign_intersect(limits); pendingRefreshRegion.assign_intersect(limits); @@ -286,15 +289,16 @@ void EncodeManager::writeUpdate(const UpdateInfo& ui, const PixelBuffer* pb, recentChangeTimer.start(RecentChangeTimeout); } -void EncodeManager::writeLosslessRefresh(const Region& req, const PixelBuffer* pb, +void EncodeManager::writeLosslessRefresh(const core::Region& req, + const PixelBuffer* pb, const RenderedCursor* renderedCursor, size_t maxUpdateSize) { doUpdate(false, getLosslessRefresh(req, maxUpdateSize), - Region(), Point(), pb, renderedCursor); + {}, {}, pb, renderedCursor); } -void EncodeManager::handleTimeout(Timer* t) +void EncodeManager::handleTimeout(core::Timer* t) { if (t == &recentChangeTimer) { // Any lossy region that wasn't recently updated can @@ -308,13 +312,15 @@ void EncodeManager::handleTimeout(Timer* t) } } -void EncodeManager::doUpdate(bool allowLossy, const Region& changed_, - const Region& copied, const Point& copyDelta, +void EncodeManager::doUpdate(bool allowLossy, const + core::Region& changed_, + const core::Region& copied, + const core::Point& copyDelta, const PixelBuffer* pb, const RenderedCursor* renderedCursor) { int nRects; - Region changed, cursorRegion; + core::Region changed, cursorRegion; updates++; @@ -475,19 +481,20 @@ void EncodeManager::prepareEncoders(bool allowLossy) encoder->setFineQualityLevel(conn->client.fineQualityLevel, conn->client.subsampling); } else { - int level = __rfbmax(conn->client.qualityLevel, - encoder->losslessQuality); - encoder->setQualityLevel(level); + if (conn->client.qualityLevel < encoder->losslessQuality) + encoder->setQualityLevel(encoder->losslessQuality); + else + encoder->setQualityLevel(conn->client.qualityLevel); encoder->setFineQualityLevel(-1, subsampleUndefined); } } } -Region EncodeManager::getLosslessRefresh(const Region& req, - size_t maxUpdateSize) +core::Region EncodeManager::getLosslessRefresh(const core::Region& req, + size_t maxUpdateSize) { - std::vector rects; - Region refresh; + std::vector rects; + core::Region refresh; size_t area; // We make a conservative guess at the compression ratio at 2:1 @@ -500,7 +507,7 @@ Region EncodeManager::getLosslessRefresh(const Region& req, pendingRefreshRegion.intersect(req).get_rects(&rects); while (!rects.empty()) { size_t idx; - Rect rect; + core::Rect rect; // Grab a random rect so we don't keep damaging and restoring the // same rect over and over @@ -514,17 +521,21 @@ Region EncodeManager::getLosslessRefresh(const Region& req, // Use the narrowest axis to avoid getting to thin rects if (rect.width() > rect.height()) { int width = (maxUpdateSize - area) / rect.height(); - rect.br.x = rect.tl.x + __rfbmax(1, width); + if (width < 1) + width = 1; + rect.br.x = rect.tl.x + width; } else { int height = (maxUpdateSize - area) / rect.width(); - rect.br.y = rect.tl.y + __rfbmax(1, height); + if (height < 1) + height = 1; + rect.br.y = rect.tl.y + height; } - refresh.assign_union(Region(rect)); + refresh.assign_union(rect); break; } area += rect.area(); - refresh.assign_union(Region(rect)); + refresh.assign_union(rect); rects.erase(rects.begin() + idx); } @@ -532,11 +543,11 @@ Region EncodeManager::getLosslessRefresh(const Region& req, return refresh; } -int EncodeManager::computeNumRects(const Region& changed) +int EncodeManager::computeNumRects(const core::Region& changed) { int numRects; - std::vector rects; - std::vector::const_iterator rect; + std::vector rects; + std::vector::const_iterator rect; numRects = 0; changed.get_rects(&rects); @@ -566,7 +577,7 @@ int EncodeManager::computeNumRects(const Region& changed) return numRects; } -Encoder *EncodeManager::startRect(const Rect& rect, int type) +Encoder* EncodeManager::startRect(const core::Rect& rect, int type) { Encoder *encoder; int klass, equiv; @@ -587,13 +598,13 @@ Encoder *EncodeManager::startRect(const Rect& rect, int type) if ((encoder->flags & EncoderLossy) && ((encoder->losslessQuality == -1) || (encoder->getQualityLevel() < encoder->losslessQuality))) - lossyRegion.assign_union(Region(rect)); + lossyRegion.assign_union(rect); else - lossyRegion.assign_subtract(Region(rect)); + lossyRegion.assign_subtract(rect); // This was either a rect getting refreshed, or a rect that just got // new content. Either way we should not try to refresh it anymore. - pendingRefreshRegion.assign_subtract(Region(rect)); + pendingRefreshRegion.assign_subtract(rect); return encoder; } @@ -611,12 +622,13 @@ void EncodeManager::endRect() stats[klass][activeType].bytes += length; } -void EncodeManager::writeCopyRects(const Region& copied, const Point& delta) +void EncodeManager::writeCopyRects(const core::Region& copied, + const core::Point& delta) { - std::vector rects; - std::vector::const_iterator rect; + std::vector rects; + std::vector::const_iterator rect; - Region lossyCopy; + core::Region lossyCopy; beforeLength = conn->getOutStream()->length(); @@ -645,20 +657,22 @@ void EncodeManager::writeCopyRects(const Region& copied, const Point& delta) pendingRefreshRegion.assign_subtract(copied); } -void EncodeManager::writeSolidRects(Region *changed, const PixelBuffer* pb) +void EncodeManager::writeSolidRects(core::Region* changed, + const PixelBuffer* pb) { - std::vector rects; - std::vector::const_iterator rect; + std::vector rects; + std::vector::const_iterator rect; changed->get_rects(&rects); for (rect = rects.begin(); rect != rects.end(); ++rect) findSolidRect(*rect, changed, pb); } -void EncodeManager::findSolidRect(const Rect& rect, Region *changed, +void EncodeManager::findSolidRect(const core::Rect& rect, + core::Region* changed, const PixelBuffer* pb) { - Rect sr; + core::Rect sr; int dx, dy, dw, dh; // We start by finding a solid 16x16 block @@ -677,11 +691,11 @@ void EncodeManager::findSolidRect(const Rect& rect, Region *changed, if (dx + dw > rect.br.x) dw = rect.br.x - dx; - pb->getImage(colourValue, Rect(dx, dy, dx+1, dy+1)); + pb->getImage(colourValue, {dx, dy, dx+1, dy+1}); sr.setXYWH(dx, dy, dw, dh); if (checkSolidTile(sr, colourValue, pb)) { - Rect erb, erp; + core::Rect erb, erp; Encoder *encoder; @@ -721,7 +735,7 @@ void EncodeManager::findSolidRect(const Rect& rect, Region *changed, } endRect(); - changed->assign_subtract(Region(erp)); + changed->assign_subtract(erp); // Search remaining areas by recursion // FIXME: Is this the best way to divide things up? @@ -752,15 +766,16 @@ void EncodeManager::findSolidRect(const Rect& rect, Region *changed, } } -void EncodeManager::writeRects(const Region& changed, const PixelBuffer* pb) +void EncodeManager::writeRects(const core::Region& changed, + const PixelBuffer* pb) { - std::vector rects; - std::vector::const_iterator rect; + std::vector rects; + std::vector::const_iterator rect; changed.get_rects(&rects); for (rect = rects.begin(); rect != rects.end(); ++rect) { int w, h, sw, sh; - Rect sr; + core::Rect sr; w = rect->width(); h = rect->height(); @@ -794,7 +809,8 @@ void EncodeManager::writeRects(const Region& changed, const PixelBuffer* pb) } } -void EncodeManager::writeSubRect(const Rect& rect, const PixelBuffer *pb) +void EncodeManager::writeSubRect(const core::Rect& rect, + const PixelBuffer* pb) { PixelBuffer *ppb; @@ -878,7 +894,8 @@ void EncodeManager::writeSubRect(const Rect& rect, const PixelBuffer *pb) endRect(); } -bool EncodeManager::checkSolidTile(const Rect& r, const uint8_t* colourValue, +bool EncodeManager::checkSolidTile(const core::Rect& r, + const uint8_t* colourValue, const PixelBuffer *pb) { const uint8_t* buffer; @@ -902,13 +919,14 @@ bool EncodeManager::checkSolidTile(const Rect& r, const uint8_t* colourValue, } } -void EncodeManager::extendSolidAreaByBlock(const Rect& r, +void EncodeManager::extendSolidAreaByBlock(const core::Rect& r, const uint8_t* colourValue, - const PixelBuffer *pb, Rect* er) + const PixelBuffer* pb, + core::Rect* er) { int dx, dy, dw, dh; int w_prev; - Rect sr; + core::Rect sr; int w_best = 0, h_best = 0; w_prev = r.width(); @@ -958,12 +976,14 @@ void EncodeManager::extendSolidAreaByBlock(const Rect& r, er->br.y = er->tl.y + h_best; } -void EncodeManager::extendSolidAreaByPixel(const Rect& r, const Rect& sr, +void EncodeManager::extendSolidAreaByPixel(const core::Rect& r, + const core::Rect& sr, const uint8_t* colourValue, - const PixelBuffer *pb, Rect* er) + const PixelBuffer* pb, + core::Rect* er) { int cx, cy; - Rect tr; + core::Rect tr; // Try to extend the area upwards. for (cy = sr.tl.y - 1; cy >= r.tl.y; cy--) { @@ -998,7 +1018,7 @@ void EncodeManager::extendSolidAreaByPixel(const Rect& r, const Rect& sr, er->br.x = cx; } -PixelBuffer* EncodeManager::preparePixelBuffer(const Rect& rect, +PixelBuffer* EncodeManager::preparePixelBuffer(const core::Rect& rect, const PixelBuffer *pb, bool convert) { @@ -1063,7 +1083,7 @@ void EncodeManager::OffsetPixelBuffer::update(const PixelFormat& pf, setBuffer(width, height, (uint8_t*)data_, stride_); } -uint8_t* EncodeManager::OffsetPixelBuffer::getBufferRW(const Rect& /*r*/, int* /*stride*/) +uint8_t* EncodeManager::OffsetPixelBuffer::getBufferRW(const core::Rect& /*r*/, int* /*stride*/) { throw std::logic_error("Invalid write attempt to OffsetPixelBuffer"); } diff --git a/common/rfb/EncodeManager.h b/common/rfb/EncodeManager.h index 7ae9b5b8d0..959c13d639 100644 --- a/common/rfb/EncodeManager.h +++ b/common/rfb/EncodeManager.h @@ -24,21 +24,22 @@ #include +#include +#include + #include -#include -#include namespace rfb { + class SConnection; class Encoder; class UpdateInfo; class PixelBuffer; class RenderedCursor; - struct Rect; struct RectInfo; - class EncodeManager : public Timer::Callback { + class EncodeManager : public core::Timer::Callback { public: EncodeManager(SConnection* conn); ~EncodeManager(); @@ -48,51 +49,58 @@ namespace rfb { // Hack to let ConnParams calculate the client's preferred encoding static bool supported(int encoding); - bool needsLosslessRefresh(const Region& req); - int getNextLosslessRefresh(const Region& req); + bool needsLosslessRefresh(const core::Region& req); + int getNextLosslessRefresh(const core::Region& req); - void pruneLosslessRefresh(const Region& limits); + void pruneLosslessRefresh(const core::Region& limits); void writeUpdate(const UpdateInfo& ui, const PixelBuffer* pb, const RenderedCursor* renderedCursor); - void writeLosslessRefresh(const Region& req, const PixelBuffer* pb, + void writeLosslessRefresh(const core::Region& req, + const PixelBuffer* pb, const RenderedCursor* renderedCursor, size_t maxUpdateSize); protected: - void handleTimeout(Timer* t) override; + void handleTimeout(core::Timer* t) override; - void doUpdate(bool allowLossy, const Region& changed, - const Region& copied, const Point& copy_delta, + void doUpdate(bool allowLossy, const core::Region& changed, + const core::Region& copied, + const core::Point& copy_delta, const PixelBuffer* pb, const RenderedCursor* renderedCursor); void prepareEncoders(bool allowLossy); - Region getLosslessRefresh(const Region& req, size_t maxUpdateSize); + core::Region getLosslessRefresh(const core::Region& req, + size_t maxUpdateSize); - int computeNumRects(const Region& changed); + int computeNumRects(const core::Region& changed); - Encoder *startRect(const Rect& rect, int type); + Encoder* startRect(const core::Rect& rect, int type); void endRect(); - void writeCopyRects(const Region& copied, const Point& delta); - void writeSolidRects(Region *changed, const PixelBuffer* pb); - void findSolidRect(const Rect& rect, Region *changed, const PixelBuffer* pb); - void writeRects(const Region& changed, const PixelBuffer* pb); + void writeCopyRects(const core::Region& copied, + const core::Point& delta); + void writeSolidRects(core::Region* changed, const PixelBuffer* pb); + void findSolidRect(const core::Rect& rect, core::Region* changed, + const PixelBuffer* pb); + void writeRects(const core::Region& changed, const PixelBuffer* pb); - void writeSubRect(const Rect& rect, const PixelBuffer *pb); + void writeSubRect(const core::Rect& rect, const PixelBuffer* pb); - bool checkSolidTile(const Rect& r, const uint8_t* colourValue, + bool checkSolidTile(const core::Rect& r, const uint8_t* colourValue, const PixelBuffer *pb); - void extendSolidAreaByBlock(const Rect& r, const uint8_t* colourValue, - const PixelBuffer *pb, Rect* er); - void extendSolidAreaByPixel(const Rect& r, const Rect& sr, + void extendSolidAreaByBlock(const core::Rect& r, const uint8_t* colourValue, - const PixelBuffer *pb, Rect* er); + const PixelBuffer* pb, core::Rect* er); + void extendSolidAreaByPixel(const core::Rect& r, + const core::Rect& sr, + const uint8_t* colourValue, + const PixelBuffer* pb, core::Rect* er); - PixelBuffer* preparePixelBuffer(const Rect& rect, - const PixelBuffer *pb, bool convert); + PixelBuffer* preparePixelBuffer(const core::Rect& rect, + const PixelBuffer* pb, bool convert); bool analyseRect(const PixelBuffer *pb, struct RectInfo *info, int maxColours); @@ -114,11 +122,11 @@ namespace rfb { std::vector encoders; std::vector activeEncoders; - Region lossyRegion; - Region recentlyChangedRegion; - Region pendingRefreshRegion; + core::Region lossyRegion; + core::Region recentlyChangedRegion; + core::Region pendingRefreshRegion; - Timer recentChangeTimer; + core::Timer recentChangeTimer; struct EncoderStats { unsigned rects; @@ -143,12 +151,13 @@ namespace rfb { const uint8_t* data_, int stride); private: - uint8_t* getBufferRW(const Rect& r, int* stride) override; + uint8_t* getBufferRW(const core::Rect& r, int* stride) override; }; OffsetPixelBuffer offsetPixelBuffer; ManagedPixelBuffer convertedPixelBuffer; }; + } #endif diff --git a/common/rfb/Encoder.h b/common/rfb/Encoder.h index 5e066323f7..7fa2cc7545 100644 --- a/common/rfb/Encoder.h +++ b/common/rfb/Encoder.h @@ -22,8 +22,6 @@ #include -#include - namespace rfb { class SConnection; class PixelBuffer; diff --git a/common/rfb/H264Decoder.cxx b/common/rfb/H264Decoder.cxx index 89850ba470..c97eeea814 100644 --- a/common/rfb/H264Decoder.cxx +++ b/common/rfb/H264Decoder.cxx @@ -26,16 +26,18 @@ #include +#include + #include #include #include -#include + #include #include using namespace rfb; -static LogWriter vlog("H264Decoder"); +static core::LogWriter vlog("H264Decoder"); enum rectFlags { resetContext = 0x1, @@ -53,22 +55,22 @@ H264Decoder::~H264Decoder() void H264Decoder::resetContexts() { - os::AutoMutex lock(&mutex); + core::AutoMutex lock(&mutex); for (H264DecoderContext* context : contexts) delete context; contexts.clear(); } -H264DecoderContext* H264Decoder::findContext(const Rect& r) +H264DecoderContext* H264Decoder::findContext(const core::Rect& r) { - os::AutoMutex m(&mutex); + core::AutoMutex m(&mutex); for (H264DecoderContext* context : contexts) if (context->isEqualRect(r)) return context; return nullptr; } -bool H264Decoder::readRect(const Rect& /*r*/, +bool H264Decoder::readRect(const core::Rect& /*r*/, rdr::InStream* is, const ServerParams& /*server*/, rdr::OutStream* os) @@ -96,7 +98,7 @@ bool H264Decoder::readRect(const Rect& /*r*/, return true; } -void H264Decoder::decodeRect(const Rect& r, const uint8_t* buffer, +void H264Decoder::decodeRect(const core::Rect& r, const uint8_t* buffer, size_t buflen, const ServerParams& /*server*/, ModifiablePixelBuffer* pb) @@ -118,7 +120,7 @@ void H264Decoder::decodeRect(const Rect& r, const uint8_t* buffer, if (!ctx) { - os::AutoMutex lock(&mutex); + core::AutoMutex lock(&mutex); if (contexts.size() >= MAX_H264_INSTANCES) { H264DecoderContext* excess_ctx = contexts.front(); diff --git a/common/rfb/H264Decoder.h b/common/rfb/H264Decoder.h index 8ba4779951..969ab5c345 100644 --- a/common/rfb/H264Decoder.h +++ b/common/rfb/H264Decoder.h @@ -23,7 +23,8 @@ #include -#include +#include + #include namespace rfb { @@ -33,18 +34,18 @@ namespace rfb { public: H264Decoder(); virtual ~H264Decoder(); - bool readRect(const Rect& r, rdr::InStream* is, + bool readRect(const core::Rect& r, rdr::InStream* is, const ServerParams& server, rdr::OutStream* os) override; - void decodeRect(const Rect& r, const uint8_t* buffer, + void decodeRect(const core::Rect& r, const uint8_t* buffer, size_t buflen, const ServerParams& server, ModifiablePixelBuffer* pb) override; private: void resetContexts(); - H264DecoderContext* findContext(const Rect& r); + H264DecoderContext* findContext(const core::Rect& r); - os::Mutex mutex; + core::Mutex mutex; std::deque contexts; }; } diff --git a/common/rfb/H264DecoderContext.cxx b/common/rfb/H264DecoderContext.cxx index b2054554e7..a0bfd459f5 100644 --- a/common/rfb/H264DecoderContext.cxx +++ b/common/rfb/H264DecoderContext.cxx @@ -24,8 +24,8 @@ #include -#include -#include +#include +#include #include @@ -39,9 +39,9 @@ using namespace rfb; -static LogWriter vlog("H264DecoderContext"); +static core::LogWriter vlog("H264DecoderContext"); -H264DecoderContext *H264DecoderContext::createContext(const Rect &r) +H264DecoderContext* H264DecoderContext::createContext(const core::Rect& r) { H264DecoderContext *ret = new H264DecoderContextType(r); if (!ret->initCodec()) @@ -58,7 +58,7 @@ H264DecoderContext::~H264DecoderContext() bool H264DecoderContext::isReady() { - os::AutoMutex lock(&mutex); + core::AutoMutex lock(&mutex); return initialized; } diff --git a/common/rfb/H264DecoderContext.h b/common/rfb/H264DecoderContext.h index 88c2396c0d..b50db888e9 100644 --- a/common/rfb/H264DecoderContext.h +++ b/common/rfb/H264DecoderContext.h @@ -23,14 +23,16 @@ #include -#include -#include -#include +#include +#include namespace rfb { + + class ModifiablePixelBuffer; + class H264DecoderContext { public: - static H264DecoderContext *createContext(const Rect &r); + static H264DecoderContext* createContext(const core::Rect& r); virtual ~H264DecoderContext() = 0; @@ -39,19 +41,20 @@ namespace rfb { ModifiablePixelBuffer* /*pb*/) {} void reset(); - inline bool isEqualRect(const Rect &r) const { return r == rect; } + inline bool isEqualRect(const core::Rect& r) const { return r == rect; } bool isReady(); protected: - os::Mutex mutex; - rfb::Rect rect; + core::Mutex mutex; + core::Rect rect; bool initialized; - H264DecoderContext(const Rect &r) : rect(r) { initialized = false; } + H264DecoderContext(const core::Rect& r) : rect(r) { initialized = false; } virtual bool initCodec() { return false; } virtual void freeCodec() {} }; + } #endif diff --git a/common/rfb/H264LibavDecoderContext.cxx b/common/rfb/H264LibavDecoderContext.cxx index 2d8d03e7d6..d3bb3dd45d 100644 --- a/common/rfb/H264LibavDecoderContext.cxx +++ b/common/rfb/H264LibavDecoderContext.cxx @@ -33,16 +33,17 @@ extern "C" { #define FFMPEG_INIT_PACKET_DEPRECATED #endif -#include +#include + #include #include using namespace rfb; -static LogWriter vlog("H264LibavDecoderContext"); +static core::LogWriter vlog("H264LibavDecoderContext"); bool H264LibavDecoderContext::initCodec() { - os::AutoMutex lock(&mutex); + core::AutoMutex lock(&mutex); sws = nullptr; h264WorkBuffer = nullptr; @@ -93,7 +94,7 @@ bool H264LibavDecoderContext::initCodec() { } void H264LibavDecoderContext::freeCodec() { - os::AutoMutex lock(&mutex); + core::AutoMutex lock(&mutex); if (!initialized) return; @@ -130,7 +131,7 @@ uint8_t* H264LibavDecoderContext::makeH264WorkBuffer(const uint8_t* buffer, uint void H264LibavDecoderContext::decode(const uint8_t* h264_in_buffer, uint32_t len, ModifiablePixelBuffer* pb) { - os::AutoMutex lock(&mutex); + core::AutoMutex lock(&mutex); if (!initialized) return; uint8_t* h264_work_buffer = makeH264WorkBuffer(h264_in_buffer, len); diff --git a/common/rfb/H264LibavDecoderContext.h b/common/rfb/H264LibavDecoderContext.h index 96558bee90..a854bc2fe5 100644 --- a/common/rfb/H264LibavDecoderContext.h +++ b/common/rfb/H264LibavDecoderContext.h @@ -31,7 +31,7 @@ extern "C" { namespace rfb { class H264LibavDecoderContext : public H264DecoderContext { public: - H264LibavDecoderContext(const Rect &r) : H264DecoderContext(r) {} + H264LibavDecoderContext(const core::Rect& r) : H264DecoderContext(r) {} ~H264LibavDecoderContext() { freeCodec(); } void decode(const uint8_t* h264_buffer, uint32_t len, diff --git a/common/rfb/H264WinDecoderContext.cxx b/common/rfb/H264WinDecoderContext.cxx index a9b139428d..5b08a381dd 100644 --- a/common/rfb/H264WinDecoderContext.cxx +++ b/common/rfb/H264WinDecoderContext.cxx @@ -27,14 +27,15 @@ #include #define SAFE_RELEASE(obj) if (obj) { obj->Release(); obj = nullptr; } -#include -#include +#include +#include + #include #include using namespace rfb; -static LogWriter vlog("H264WinDecoderContext"); +static core::LogWriter vlog("H264WinDecoderContext"); // Older MinGW lacks this definition #ifndef HAVE_VIDEO_PROCESSOR_MFT @@ -42,7 +43,7 @@ static GUID CLSID_VideoProcessorMFT = { 0x88753b26, 0x5b24, 0x49bd, { 0xb2, 0xe7 #endif bool H264WinDecoderContext::initCodec() { - os::AutoMutex lock(&mutex); + core::AutoMutex lock(&mutex); if (FAILED(MFStartup(MF_VERSION, MFSTARTUP_LITE))) { @@ -146,7 +147,7 @@ bool H264WinDecoderContext::initCodec() { } void H264WinDecoderContext::freeCodec() { - os::AutoMutex lock(&mutex); + core::AutoMutex lock(&mutex); if (!initialized) return; @@ -165,7 +166,7 @@ void H264WinDecoderContext::freeCodec() { void H264WinDecoderContext::decode(const uint8_t* h264_buffer, uint32_t len, ModifiablePixelBuffer* pb) { - os::AutoMutex lock(&mutex); + core::AutoMutex lock(&mutex); if (!initialized) return; diff --git a/common/rfb/H264WinDecoderContext.h b/common/rfb/H264WinDecoderContext.h index 92041781be..b934b76e9a 100644 --- a/common/rfb/H264WinDecoderContext.h +++ b/common/rfb/H264WinDecoderContext.h @@ -30,7 +30,7 @@ namespace rfb { class H264WinDecoderContext : public H264DecoderContext { public: - H264WinDecoderContext(const Rect &r) : H264DecoderContext(r) {}; + H264WinDecoderContext(const core::Rect& r) : H264DecoderContext(r) {}; ~H264WinDecoderContext() { freeCodec(); } void decode(const uint8_t* h264_buffer, uint32_t len, diff --git a/common/rfb/HextileDecoder.cxx b/common/rfb/HextileDecoder.cxx index 35ec79285f..c6eb428b9e 100644 --- a/common/rfb/HextileDecoder.cxx +++ b/common/rfb/HextileDecoder.cxx @@ -21,6 +21,8 @@ #include #endif +#include + #include #include #include @@ -41,10 +43,10 @@ HextileDecoder::~HextileDecoder() { } -bool HextileDecoder::readRect(const Rect& r, rdr::InStream* is, +bool HextileDecoder::readRect(const core::Rect& r, rdr::InStream* is, const ServerParams& server, rdr::OutStream* os) { - Rect t; + core::Rect t; size_t bytesPerPixel; is->setRestorePoint(); @@ -53,12 +55,12 @@ bool HextileDecoder::readRect(const Rect& r, rdr::InStream* is, for (t.tl.y = r.tl.y; t.tl.y < r.br.y; t.tl.y += 16) { - t.br.y = __rfbmin(r.br.y, t.tl.y + 16); + t.br.y = std::min(r.br.y, t.tl.y + 16); for (t.tl.x = r.tl.x; t.tl.x < r.br.x; t.tl.x += 16) { uint8_t tileType; - t.br.x = __rfbmin(r.br.x, t.tl.x + 16); + t.br.x = std::min(r.br.x, t.tl.x + 16); if (!is->hasDataOrRestore(1)) return false; @@ -113,7 +115,7 @@ bool HextileDecoder::readRect(const Rect& r, rdr::InStream* is, return true; } -void HextileDecoder::decodeRect(const Rect& r, const uint8_t* buffer, +void HextileDecoder::decodeRect(const core::Rect& r, const uint8_t* buffer, size_t buflen, const ServerParams& server, ModifiablePixelBuffer* pb) { @@ -138,22 +140,22 @@ inline T HextileDecoder::readPixel(rdr::InStream* is) } template -void HextileDecoder::hextileDecode(const Rect& r, rdr::InStream* is, +void HextileDecoder::hextileDecode(const core::Rect& r, rdr::InStream* is, const PixelFormat& pf, ModifiablePixelBuffer* pb) { - Rect t; + core::Rect t; T bg = 0; T fg = 0; T buf[16 * 16]; for (t.tl.y = r.tl.y; t.tl.y < r.br.y; t.tl.y += 16) { - t.br.y = __rfbmin(r.br.y, t.tl.y + 16); + t.br.y = std::min(r.br.y, t.tl.y + 16); for (t.tl.x = r.tl.x; t.tl.x < r.br.x; t.tl.x += 16) { - t.br.x = __rfbmin(r.br.x, t.tl.x + 16); + t.br.x = std::min(r.br.x, t.tl.x + 16); int tileType = is->readU8(); diff --git a/common/rfb/HextileDecoder.h b/common/rfb/HextileDecoder.h index 38e8b776e5..6ff94a1ff8 100644 --- a/common/rfb/HextileDecoder.h +++ b/common/rfb/HextileDecoder.h @@ -29,17 +29,17 @@ namespace rfb { public: HextileDecoder(); virtual ~HextileDecoder(); - bool readRect(const Rect& r, rdr::InStream* is, + bool readRect(const core::Rect& r, rdr::InStream* is, const ServerParams& server, rdr::OutStream* os) override; - void decodeRect(const Rect& r, const uint8_t* buffer, + void decodeRect(const core::Rect& r, const uint8_t* buffer, size_t buflen, const ServerParams& server, ModifiablePixelBuffer* pb) override; private: template inline T readPixel(rdr::InStream* is); template - void hextileDecode(const Rect& r, rdr::InStream* is, + void hextileDecode(const core::Rect& r, rdr::InStream* is, const PixelFormat& pf, ModifiablePixelBuffer* pb); }; diff --git a/common/rfb/HextileEncoder.cxx b/common/rfb/HextileEncoder.cxx index 0666d02d9d..5ee07a2d9e 100644 --- a/common/rfb/HextileEncoder.cxx +++ b/common/rfb/HextileEncoder.cxx @@ -22,21 +22,28 @@ #include #endif +#include + +#include + +#include + #include #include #include #include #include -#include #include using namespace rfb; -BoolParameter improvedHextile("ImprovedHextile", - "Use improved compression algorithm for Hextile " - "encoding which achieves better compression " - "ratios by the cost of using more CPU time", - true); +core::BoolParameter improvedHextile("ImprovedHextile", + "Use improved compression " + "algorithm for Hextile encoding " + "which achieves better compression " + "ratios by the cost of using more " + "CPU time", + true); HextileEncoder::HextileEncoder(SConnection* conn_) : Encoder(conn_, encodingHextile, EncoderPlain) @@ -115,7 +122,7 @@ template void HextileEncoder::hextileEncode(rdr::OutStream* os, const PixelBuffer* pb) { - Rect t; + core::Rect t; T buf[256]; T oldBg = 0, oldFg = 0; bool oldBgValid = false; @@ -124,11 +131,11 @@ void HextileEncoder::hextileEncode(rdr::OutStream* os, for (t.tl.y = 0; t.tl.y < pb->height(); t.tl.y += 16) { - t.br.y = __rfbmin(pb->height(), t.tl.y + 16); + t.br.y = std::min(pb->height(), t.tl.y + 16); for (t.tl.x = 0; t.tl.x < pb->width(); t.tl.x += 16) { - t.br.x = __rfbmin(pb->width(), t.tl.x + 16); + t.br.x = std::min(pb->width(), t.tl.x + 16); pb->getImage(buf, t); @@ -532,7 +539,7 @@ template void HextileEncoder::hextileEncodeBetter(rdr::OutStream* os, const PixelBuffer* pb) { - Rect t; + core::Rect t; T buf[256]; T oldBg = 0, oldFg = 0; bool oldBgValid = false; @@ -543,11 +550,11 @@ void HextileEncoder::hextileEncodeBetter(rdr::OutStream* os, for (t.tl.y = 0; t.tl.y < pb->height(); t.tl.y += 16) { - t.br.y = __rfbmin(pb->height(), t.tl.y + 16); + t.br.y = std::min(pb->height(), t.tl.y + 16); for (t.tl.x = 0; t.tl.x < pb->width(); t.tl.x += 16) { - t.br.x = __rfbmin(pb->width(), t.tl.x + 16); + t.br.x = std::min(pb->width(), t.tl.x + 16); pb->getImage(buf, t); diff --git a/common/rfb/Hostname.h b/common/rfb/Hostname.h deleted file mode 100644 index f43e5067ab..0000000000 --- a/common/rfb/Hostname.h +++ /dev/null @@ -1,120 +0,0 @@ -/* Copyright (C) 2002-2005 RealVNC Ltd. All Rights Reserved. - * - * This is free software; you can redistribute it and/or modify - * it under the terms of the GNU General Public License as published by - * the Free Software Foundation; either version 2 of the License, or - * (at your option) any later version. - * - * This software is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this software; if not, write to the Free Software - * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, - * USA. - */ - -#ifndef __RFB_HOSTNAME_H__ -#define __RFB_HOSTNAME_H__ - -#include -#include -#include -#include - -#include - -#include - -namespace rfb { - - static bool isAllSpace(const char *string) { - if (string == nullptr) - return false; - while(*string != '\0') { - if (! isspace(*string)) - return false; - string++; - } - return true; - } - - static inline void getHostAndPort(const char* hi, std::string* host, - int* port, int basePort=5900) - { - const char* hostStart; - const char* hostEnd; - const char* portStart; - - if (hi == nullptr) - throw std::invalid_argument("NULL host specified"); - - // Trim leading whitespace - while(isspace(*hi)) - hi++; - - assert(host); - assert(port); - - if (hi[0] == '[') { - hostStart = &hi[1]; - hostEnd = strchr(hostStart, ']'); - if (hostEnd == nullptr) - throw std::invalid_argument("Unmatched [ in host"); - - portStart = hostEnd + 1; - if (isAllSpace(portStart)) - portStart = nullptr; - } else { - hostStart = &hi[0]; - hostEnd = strrchr(hostStart, ':'); - - if (hostEnd == nullptr) { - hostEnd = hostStart + strlen(hostStart); - portStart = nullptr; - } else { - if ((hostEnd > hostStart) && (hostEnd[-1] == ':')) - hostEnd--; - portStart = strchr(hostStart, ':'); - if (portStart != hostEnd) { - // We found more : in the host. This is probably an IPv6 address - hostEnd = hostStart + strlen(hostStart); - portStart = nullptr; - } - } - } - - // Back up past trailing space - while(isspace(*(hostEnd - 1)) && hostEnd > hostStart) - hostEnd--; - - if (hostStart == hostEnd) - *host = "localhost"; - else - *host = std::string(hostStart, hostEnd - hostStart); - - if (portStart == nullptr) - *port = basePort; - else { - char* end; - - if (portStart[0] != ':') - throw std::invalid_argument("Invalid port specified"); - - if (portStart[1] != ':') - *port = strtol(portStart + 1, &end, 10); - else - *port = strtol(portStart + 2, &end, 10); - if (*end != '\0' && ! isAllSpace(end)) - throw std::invalid_argument("Invalid port specified"); - - if ((portStart[1] != ':') && (*port < 100)) - *port += basePort; - } - } - -}; - -#endif // __RFB_HOSTNAME_H__ diff --git a/common/rfb/JpegCompressor.cxx b/common/rfb/JpegCompressor.cxx index 67a86cd932..d8216c99aa 100644 --- a/common/rfb/JpegCompressor.cxx +++ b/common/rfb/JpegCompressor.cxx @@ -24,8 +24,9 @@ #include +#include + #include -#include #include #include @@ -157,7 +158,8 @@ JpegCompressor::~JpegCompressor(void) } void JpegCompressor::compress(const uint8_t *buf, volatile int stride, - const Rect& r, const PixelFormat& pf, + const core::Rect& r, + const PixelFormat& pf, int quality, int subsamp) { int w = r.width(); diff --git a/common/rfb/JpegCompressor.h b/common/rfb/JpegCompressor.h index 26194204f6..2460f62b43 100644 --- a/common/rfb/JpegCompressor.h +++ b/common/rfb/JpegCompressor.h @@ -25,9 +25,9 @@ #ifndef __RFB_JPEGCOMPRESSOR_H__ #define __RFB_JPEGCOMPRESSOR_H__ +#include + #include -#include -#include struct jpeg_compress_struct; @@ -36,6 +36,9 @@ struct JPEG_DEST_MGR; namespace rfb { + class PixelFormat; + struct Rect; + class JpegCompressor : public rdr::MemOutStream { public: @@ -43,7 +46,8 @@ namespace rfb { JpegCompressor(int bufferLen = 128*1024); virtual ~JpegCompressor(); - void compress(const uint8_t *, int, const Rect&, const PixelFormat&, int, int); + void compress(const uint8_t*, int, const core::Rect&, + const PixelFormat&, int, int); void writeBytes(const uint8_t*, int); diff --git a/common/rfb/JpegDecompressor.cxx b/common/rfb/JpegDecompressor.cxx index 10c9e49cd6..ef548be08d 100644 --- a/common/rfb/JpegDecompressor.cxx +++ b/common/rfb/JpegDecompressor.cxx @@ -23,9 +23,10 @@ #include #endif +#include + #include #include -#include #include #include @@ -153,7 +154,8 @@ JpegDecompressor::~JpegDecompressor(void) void JpegDecompressor::decompress(const uint8_t *jpegBuf, int jpegBufLen, uint8_t *buf, volatile int stride, - const Rect& r, const PixelFormat& pf) + const core::Rect& r, + const PixelFormat& pf) { int w = r.width(); int h = r.height(); diff --git a/common/rfb/JpegDecompressor.h b/common/rfb/JpegDecompressor.h index 5d4f0c217e..8e651b1c95 100644 --- a/common/rfb/JpegDecompressor.h +++ b/common/rfb/JpegDecompressor.h @@ -26,16 +26,19 @@ #ifndef __RFB_JPEGDECOMPRESSOR_H__ #define __RFB_JPEGDECOMPRESSOR_H__ -#include -#include +#include struct jpeg_decompress_struct; struct JPEG_ERROR_MGR; struct JPEG_SRC_MGR; +namespace core { struct Rect; } + namespace rfb { + class PixelFormat; + class JpegDecompressor { public: @@ -43,8 +46,8 @@ namespace rfb { JpegDecompressor(void); virtual ~JpegDecompressor(); - void decompress(const uint8_t *, int, uint8_t *, int, const Rect&, - const PixelFormat&); + void decompress(const uint8_t*, int, uint8_t*, int, + const core::Rect&, const PixelFormat&); private: diff --git a/common/rfb/KeyRemapper.cxx b/common/rfb/KeyRemapper.cxx index 1c478178bc..2bf7db55cc 100644 --- a/common/rfb/KeyRemapper.cxx +++ b/common/rfb/KeyRemapper.cxx @@ -23,21 +23,21 @@ #include #include -#include +#include +#include +#include #include -#include -#include using namespace rfb; -static LogWriter vlog("KeyRemapper"); +static core::LogWriter vlog("KeyRemapper"); KeyRemapper KeyRemapper::defInstance; KeyRemapper::KeyRemapper(const char* m) { - mutex = new os::Mutex; + mutex = new core::Mutex; setMapping(m); } @@ -48,7 +48,7 @@ KeyRemapper::~KeyRemapper() } void KeyRemapper::setMapping(const char* m) { - os::AutoMutex a(mutex); + core::AutoMutex a(mutex); mapping.clear(); while (m[0]) { @@ -74,7 +74,7 @@ void KeyRemapper::setMapping(const char* m) { } uint32_t KeyRemapper::remapKey(uint32_t key) const { - os::AutoMutex a(mutex); + core::AutoMutex a(mutex); std::map::const_iterator i = mapping.find(key); if (i != mapping.end()) @@ -83,15 +83,15 @@ uint32_t KeyRemapper::remapKey(uint32_t key) const { } -class KeyMapParameter : public StringParameter { +class KeyMapParameter : public core::StringParameter { public: KeyMapParameter() - : StringParameter("RemapKeys", "Comma-separated list of incoming keysyms to remap. Mappings are expressed as two hex values, prefixed by 0x, and separated by ->", "") { + : core::StringParameter("RemapKeys", "Comma-separated list of incoming keysyms to remap. Mappings are expressed as two hex values, prefixed by 0x, and separated by ->", "") { KeyRemapper::defInstance.setMapping(""); } bool setParam(const char* v) override { KeyRemapper::defInstance.setMapping(v); - return StringParameter::setParam(v); + return core::StringParameter::setParam(v); } } defaultParam; diff --git a/common/rfb/KeyRemapper.h b/common/rfb/KeyRemapper.h index 89853721c3..43afd21b6b 100644 --- a/common/rfb/KeyRemapper.h +++ b/common/rfb/KeyRemapper.h @@ -23,7 +23,7 @@ #include -namespace os { class Mutex; } +namespace core { class Mutex; } namespace rfb { @@ -36,7 +36,7 @@ namespace rfb { static KeyRemapper defInstance; private: std::map mapping; - os::Mutex* mutex; + core::Mutex* mutex; }; }; diff --git a/common/rfb/PixelBuffer.cxx b/common/rfb/PixelBuffer.cxx index 5590c21407..32b0ce2f99 100644 --- a/common/rfb/PixelBuffer.cxx +++ b/common/rfb/PixelBuffer.cxx @@ -30,13 +30,14 @@ #include -#include +#include +#include + #include -#include using namespace rfb; -static LogWriter vlog("PixelBuffer"); +static core::LogWriter vlog("PixelBuffer"); // We do a lot of byte offset calculations that assume the result fits // inside a signed 32 bit integer. Limit the maximum size of pixel @@ -63,7 +64,8 @@ PixelBuffer::~PixelBuffer() {} void -PixelBuffer::getImage(void* imageBuf, const Rect& r, int outStride) const +PixelBuffer::getImage(void* imageBuf, const core::Rect& r, + int outStride) const { int inStride; const uint8_t* data; @@ -72,10 +74,9 @@ PixelBuffer::getImage(void* imageBuf, const Rect& r, int outStride) const const uint8_t* end; if (!r.enclosed_by(getRect())) - throw std::out_of_range(rfb::format("Source rect %dx%d at %d,%d exceeds framebuffer %dx%d", - r.width(), r.height(), - r.tl.x, r.tl.y, - width(), height())); + throw std::out_of_range(core::format( + "Source rect %dx%d at %d,%d exceeds framebuffer %dx%d", + r.width(), r.height(), r.tl.x, r.tl.y, width(), height())); data = getBuffer(r, &inStride); @@ -98,7 +99,7 @@ PixelBuffer::getImage(void* imageBuf, const Rect& r, int outStride) const } void PixelBuffer::getImage(const PixelFormat& pf, void* imageBuf, - const Rect& r, int stride) const + const core::Rect& r, int stride) const { const uint8_t* srcBuffer; int srcStride; @@ -109,10 +110,9 @@ void PixelBuffer::getImage(const PixelFormat& pf, void* imageBuf, } if (!r.enclosed_by(getRect())) - throw std::out_of_range(rfb::format("Source rect %dx%d at %d,%d exceeds framebuffer %dx%d", - r.width(), r.height(), - r.tl.x, r.tl.y, - width(), height())); + throw std::out_of_range(core::format( + "Source rect %dx%d at %d,%d exceeds framebuffer %dx%d", + r.width(), r.height(), r.tl.x, r.tl.y, width(), height())); if (stride == 0) stride = r.width(); @@ -126,9 +126,11 @@ void PixelBuffer::getImage(const PixelFormat& pf, void* imageBuf, void PixelBuffer::setSize(int width, int height) { if ((width < 0) || (width > maxPixelBufferWidth)) - throw std::out_of_range(rfb::format("Invalid PixelBuffer width of %d pixels requested", width)); + throw std::out_of_range(core::format( + "Invalid PixelBuffer width of %d pixels requested", width)); if ((height < 0) || (height > maxPixelBufferHeight)) - throw std::out_of_range(rfb::format("Invalid PixelBuffer height of %d pixels requested", height)); + throw std::out_of_range(core::format( + "Invalid PixelBuffer height of %d pixels requested", height)); width_ = width; height_ = height; @@ -150,17 +152,17 @@ ModifiablePixelBuffer::~ModifiablePixelBuffer() { } -void ModifiablePixelBuffer::fillRect(const Rect& r, const void* pix) +void ModifiablePixelBuffer::fillRect(const core::Rect& r, + const void* pix) { int stride; uint8_t *buf; int w, h, b; if (!r.enclosed_by(getRect())) - throw std::out_of_range(rfb::format("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", - r.width(), r.height(), - r.tl.x, r.tl.y, - width(), height())); + throw std::out_of_range(core::format( + "Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", + r.width(), r.height(), r.tl.x, r.tl.y, width(), height())); w = r.width(); h = r.height(); @@ -199,7 +201,7 @@ void ModifiablePixelBuffer::fillRect(const Rect& r, const void* pix) commitBufferRW(r); } -void ModifiablePixelBuffer::imageRect(const Rect& r, +void ModifiablePixelBuffer::imageRect(const core::Rect& r, const void* pixels, int srcStride) { uint8_t* dest; @@ -209,10 +211,9 @@ void ModifiablePixelBuffer::imageRect(const Rect& r, uint8_t* end; if (!r.enclosed_by(getRect())) - throw std::out_of_range(rfb::format("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", - r.width(), r.height(), - r.tl.x, r.tl.y, - width(), height())); + throw std::out_of_range(core::format( + "Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", + r.width(), r.height(), r.tl.x, r.tl.y, width(), height())); bytesPerPixel = getPF().bpp/8; @@ -237,29 +238,29 @@ void ModifiablePixelBuffer::imageRect(const Rect& r, commitBufferRW(r); } -void ModifiablePixelBuffer::copyRect(const Rect &rect, - const Point &move_by_delta) +void ModifiablePixelBuffer::copyRect(const core::Rect& rect, + const core::Point& move_by_delta) { int srcStride, dstStride; int bytesPerPixel; const uint8_t* srcData; uint8_t* dstData; - Rect drect, srect; + core::Rect drect, srect; drect = rect; if (!drect.enclosed_by(getRect())) - throw std::out_of_range(rfb::format("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", - drect.width(), drect.height(), - drect.tl.x, drect.tl.y, - width(), height())); + throw std::out_of_range(core::format( + "Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", + drect.width(), drect.height(), drect.tl.x, drect.tl.y, + width(), height())); srect = drect.translate(move_by_delta.negate()); if (!srect.enclosed_by(getRect())) - throw std::out_of_range(rfb::format("Source rect %dx%d at %d,%d exceeds framebuffer %dx%d", - srect.width(), srect.height(), - srect.tl.x, srect.tl.y, - width(), height())); + throw std::out_of_range(core::format( + "Source rect %dx%d at %d,%d exceeds framebuffer %dx%d", + srect.width(), srect.height(), srect.tl.x, srect.tl.y, + width(), height())); bytesPerPixel = format.bpp/8; @@ -297,7 +298,8 @@ void ModifiablePixelBuffer::copyRect(const Rect &rect, commitBufferRW(drect); } -void ModifiablePixelBuffer::fillRect(const PixelFormat& pf, const Rect &dest, +void ModifiablePixelBuffer::fillRect(const PixelFormat& pf, + const core::Rect& dest, const void* pix) { uint8_t buf[4]; @@ -305,17 +307,18 @@ void ModifiablePixelBuffer::fillRect(const PixelFormat& pf, const Rect &dest, fillRect(dest, buf); } -void ModifiablePixelBuffer::imageRect(const PixelFormat& pf, const Rect &dest, +void ModifiablePixelBuffer::imageRect(const PixelFormat& pf, + const core::Rect& dest, const void* pixels, int stride) { uint8_t* dstBuffer; int dstStride; if (!dest.enclosed_by(getRect())) - throw std::out_of_range(rfb::format("Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", - dest.width(), dest.height(), - dest.tl.x, dest.tl.y, - width(), height())); + throw std::out_of_range(core::format( + "Destination rect %dx%d at %d,%d exceeds framebuffer %dx%d", + dest.width(), dest.height(), dest.tl.x, dest.tl.y, + width(), height())); if (stride == 0) stride = dest.width(); @@ -339,29 +342,29 @@ FullFramePixelBuffer::FullFramePixelBuffer() : data(nullptr) {} FullFramePixelBuffer::~FullFramePixelBuffer() {} -uint8_t* FullFramePixelBuffer::getBufferRW(const Rect& r, int* stride_) +uint8_t* FullFramePixelBuffer::getBufferRW(const core::Rect& r, + int* stride_) { if (!r.enclosed_by(getRect())) - throw std::out_of_range(rfb::format("Pixel buffer request %dx%d at %d,%d exceeds framebuffer %dx%d", - r.width(), r.height(), - r.tl.x, r.tl.y, - width(), height())); + throw std::out_of_range(core::format( + "Pixel buffer request %dx%d at %d,%d exceeds framebuffer %dx%d", + r.width(), r.height(), r.tl.x, r.tl.y, width(), height())); *stride_ = stride; return &data[(r.tl.x + (r.tl.y * stride)) * (format.bpp/8)]; } -void FullFramePixelBuffer::commitBufferRW(const Rect& /*r*/) +void FullFramePixelBuffer::commitBufferRW(const core::Rect& /*r*/) { } -const uint8_t* FullFramePixelBuffer::getBuffer(const Rect& r, int* stride_) const +const uint8_t* FullFramePixelBuffer::getBuffer(const core::Rect& r, + int* stride_) const { if (!r.enclosed_by(getRect())) - throw std::out_of_range(rfb::format("Pixel buffer request %dx%d at %d,%d exceeds framebuffer %dx%d", - r.width(), r.height(), - r.tl.x, r.tl.y, - width(), height())); + throw std::out_of_range(core::format( + "Pixel buffer request %dx%d at %d,%d exceeds framebuffer %dx%d", + r.width(), r.height(), r.tl.x, r.tl.y, width(), height())); *stride_ = stride; return &data[(r.tl.x + (r.tl.y * stride)) * (format.bpp/8)]; @@ -371,13 +374,17 @@ void FullFramePixelBuffer::setBuffer(int width, int height, uint8_t* data_, int stride_) { if ((width < 0) || (width > maxPixelBufferWidth)) - throw std::out_of_range(rfb::format("Invalid PixelBuffer width of %d pixels requested", width)); + throw std::out_of_range(core::format( + "Invalid PixelBuffer width of %d pixels requested", width)); if ((height < 0) || (height > maxPixelBufferHeight)) - throw std::out_of_range(rfb::format("Invalid PixelBuffer height of %d pixels requested", height)); + throw std::out_of_range(core::format( + "Invalid PixelBuffer height of %d pixels requested", height)); if ((stride_ < 0) || (stride_ > maxPixelBufferStride) || (stride_ < width)) - throw std::invalid_argument(rfb::format("Invalid PixelBuffer stride of %d pixels requested", stride_)); + throw std::invalid_argument(core::format( + "Invalid PixelBuffer stride of %d pixels requested", stride_)); if ((width != 0) && (height != 0) && (data_ == nullptr)) - throw std::logic_error(rfb::format("PixelBuffer requested without a valid memory area")); + throw std::logic_error(core::format( + "PixelBuffer requested without a valid memory area")); ModifiablePixelBuffer::setSize(width, height); stride = stride_; diff --git a/common/rfb/PixelBuffer.h b/common/rfb/PixelBuffer.h index 963fbbf6ad..9fbea6112d 100644 --- a/common/rfb/PixelBuffer.h +++ b/common/rfb/PixelBuffer.h @@ -25,12 +25,13 @@ #ifndef __RFB_PIXEL_BUFFER_H__ #define __RFB_PIXEL_BUFFER_H__ +#include + #include -#include -namespace rfb { +namespace core { class Region; } - class Region; +namespace rfb { class PixelBuffer { public: @@ -52,9 +53,9 @@ namespace rfb { // Get rectangle encompassing this buffer // Top-left of rectangle is either at (0,0), or the specified point. - Rect getRect() const { return Rect(0, 0, width_, height_); } - Rect getRect(const Point& pos) const { - return Rect(pos, pos.translate(Point(width_, height_))); + core::Rect getRect() const { return {0, 0, width_, height_}; } + core::Rect getRect(const core::Point& pos) const { + return {pos, pos.translate({width_, height_})}; } /////////////////////////////////////////////// @@ -64,18 +65,20 @@ namespace rfb { // Get a pointer into the buffer // The pointer is to the top-left pixel of the specified Rect. // The buffer stride (in pixels) is returned. - virtual const uint8_t* getBuffer(const Rect& r, int* stride) const = 0; + virtual const uint8_t* getBuffer(const core::Rect& r, + int* stride) const = 0; // Get pixel data for a given part of the buffer // Data is copied into the supplied buffer, with the specified // stride. Try to avoid using this though as getBuffer() will in // most cases avoid the extra memory copy. - void getImage(void* imageBuf, const Rect& r, int stride=0) const; + void getImage(void* imageBuf, const core::Rect& r, + int stride=0) const; // Get pixel data in a given format // Works just the same as getImage(), but guaranteed to be in a // specific format. void getImage(const PixelFormat& pf, void* imageBuf, - const Rect& r, int stride=0) const; + const core::Rect& r, int stride=0) const; /////////////////////////////////////////////// // Framebuffer update methods @@ -84,7 +87,7 @@ namespace rfb { // Ensure that the specified rectangle of buffer is up to date. // Overridden by derived classes implementing framebuffer access // to copy the required display data into place. - virtual void grabRegion(const Region& /*region*/) {} + virtual void grabRegion(const core::Region& /*region*/) {} protected: PixelBuffer(); @@ -110,32 +113,35 @@ namespace rfb { // Get a writeable pointer into the buffer // Like getBuffer(), the pointer is to the top-left pixel of the // specified Rect and the stride in pixels is returned. - virtual uint8_t* getBufferRW(const Rect& r, int* stride) = 0; + virtual uint8_t* getBufferRW(const core::Rect& r, int* stride) = 0; // Commit the modified contents // Ensures that the changes to the specified Rect is properly // stored away and any temporary buffers are freed. The Rect given // here needs to match the Rect given to the earlier call to // getBufferRW(). - virtual void commitBufferRW(const Rect& r) = 0; + virtual void commitBufferRW(const core::Rect& r) = 0; /////////////////////////////////////////////// // Basic rendering operations // These operations DO NOT clip to the pixelbuffer area, or trap overruns. // Fill a rectangle - void fillRect(const Rect &dest, const void* pix); + void fillRect(const core::Rect& dest, const void* pix); // Copy pixel data to the buffer - void imageRect(const Rect &dest, const void* pixels, int stride=0); + void imageRect(const core::Rect& dest, const void* pixels, + int stride=0); // Copy pixel data from one PixelBuffer location to another - void copyRect(const Rect &dest, const Point& move_by_delta); + void copyRect(const core::Rect& dest, + const core::Point& move_by_delta); // Render in a specific format // Does the exact same thing as the above methods, but the given // pixel values are defined by the given PixelFormat. - void fillRect(const PixelFormat& pf, const Rect &dest, const void* pix); - void imageRect(const PixelFormat& pf, const Rect &dest, + void fillRect(const PixelFormat& pf, const core::Rect& dest, + const void* pix); + void imageRect(const PixelFormat& pf, const core::Rect& dest, const void* pixels, int stride=0); protected: @@ -151,9 +157,10 @@ namespace rfb { virtual ~FullFramePixelBuffer(); public: - const uint8_t* getBuffer(const Rect& r, int* stride) const override; - uint8_t* getBufferRW(const Rect& r, int* stride) override; - void commitBufferRW(const Rect& r) override; + const uint8_t* getBuffer(const core::Rect& r, + int* stride) const override; + uint8_t* getBufferRW(const core::Rect& r, int* stride) override; + void commitBufferRW(const core::Rect& r) override; protected: FullFramePixelBuffer(); diff --git a/common/rfb/RREDecoder.cxx b/common/rfb/RREDecoder.cxx index 53ddc2da49..d2c3d3e6c7 100644 --- a/common/rfb/RREDecoder.cxx +++ b/common/rfb/RREDecoder.cxx @@ -40,7 +40,7 @@ RREDecoder::~RREDecoder() { } -bool RREDecoder::readRect(const Rect& /*r*/, rdr::InStream* is, +bool RREDecoder::readRect(const core::Rect& /*r*/, rdr::InStream* is, const ServerParams& server, rdr::OutStream* os) { uint32_t numRects; @@ -66,7 +66,7 @@ bool RREDecoder::readRect(const Rect& /*r*/, rdr::InStream* is, return true; } -void RREDecoder::decodeRect(const Rect& r, const uint8_t* buffer, +void RREDecoder::decodeRect(const core::Rect& r, const uint8_t* buffer, size_t buflen, const ServerParams& server, ModifiablePixelBuffer* pb) { @@ -91,7 +91,7 @@ inline T RREDecoder::readPixel(rdr::InStream* is) } template -void RREDecoder::rreDecode(const Rect& r, rdr::InStream* is, +void RREDecoder::rreDecode(const core::Rect& r, rdr::InStream* is, const PixelFormat& pf, ModifiablePixelBuffer* pb) { @@ -109,6 +109,6 @@ void RREDecoder::rreDecode(const Rect& r, rdr::InStream* is, if (((x+w) > r.width()) || ((y+h) > r.height())) throw protocol_error("RRE decode error"); - pb->fillRect(pf, Rect(r.tl.x+x, r.tl.y+y, r.tl.x+x+w, r.tl.y+y+h), &pix); + pb->fillRect(pf, {r.tl.x+x, r.tl.y+y, r.tl.x+x+w, r.tl.y+y+h}, &pix); } } diff --git a/common/rfb/RREDecoder.h b/common/rfb/RREDecoder.h index 8490146c70..3fdcdd8551 100644 --- a/common/rfb/RREDecoder.h +++ b/common/rfb/RREDecoder.h @@ -29,17 +29,17 @@ namespace rfb { public: RREDecoder(); virtual ~RREDecoder(); - bool readRect(const Rect& r, rdr::InStream* is, + bool readRect(const core::Rect& r, rdr::InStream* is, const ServerParams& server, rdr::OutStream* os) override; - void decodeRect(const Rect& r, const uint8_t* buffer, + void decodeRect(const core::Rect& r, const uint8_t* buffer, size_t buflen, const ServerParams& server, ModifiablePixelBuffer* pb) override; private: template inline T readPixel(rdr::InStream* is); template - void rreDecode(const Rect& r, rdr::InStream* is, + void rreDecode(const core::Rect& r, rdr::InStream* is, const PixelFormat& pf, ModifiablePixelBuffer* pb); }; } diff --git a/common/rfb/RawDecoder.cxx b/common/rfb/RawDecoder.cxx index f2ea586b4b..43ce15a451 100644 --- a/common/rfb/RawDecoder.cxx +++ b/common/rfb/RawDecoder.cxx @@ -37,7 +37,7 @@ RawDecoder::~RawDecoder() { } -bool RawDecoder::readRect(const Rect& r, rdr::InStream* is, +bool RawDecoder::readRect(const core::Rect& r, rdr::InStream* is, const ServerParams& server, rdr::OutStream* os) { if (!is->hasData(r.area() * (server.pf().bpp/8))) @@ -46,7 +46,7 @@ bool RawDecoder::readRect(const Rect& r, rdr::InStream* is, return true; } -void RawDecoder::decodeRect(const Rect& r, const uint8_t* buffer, +void RawDecoder::decodeRect(const core::Rect& r, const uint8_t* buffer, size_t buflen, const ServerParams& server, ModifiablePixelBuffer* pb) { diff --git a/common/rfb/RawDecoder.h b/common/rfb/RawDecoder.h index 2ac8b0bd4d..6c3a635700 100644 --- a/common/rfb/RawDecoder.h +++ b/common/rfb/RawDecoder.h @@ -25,10 +25,10 @@ namespace rfb { public: RawDecoder(); virtual ~RawDecoder(); - bool readRect(const Rect& r, rdr::InStream* is, + bool readRect(const core::Rect& r, rdr::InStream* is, const ServerParams& server, rdr::OutStream* os) override; - void decodeRect(const Rect& r, const uint8_t* buffer, + void decodeRect(const core::Rect& r, const uint8_t* buffer, size_t buflen, const ServerParams& server, ModifiablePixelBuffer* pb) override; }; diff --git a/common/rfb/SConnection.cxx b/common/rfb/SConnection.cxx index a0a1c37311..c269fac023 100644 --- a/common/rfb/SConnection.cxx +++ b/common/rfb/SConnection.cxx @@ -26,6 +26,11 @@ #include +#include +#include + +#include + #include #include #include @@ -38,13 +43,10 @@ #include #include #include -#include - -#include using namespace rfb; -static LogWriter vlog("SConnection"); +static core::LogWriter vlog("SConnection"); SConnection::SConnection(AccessRights accessRights_) : readyForSetColourMapEntries(false), is(nullptr), os(nullptr), @@ -133,10 +135,10 @@ bool SConnection::processVersionMsg() if (client.majorVersion != 3) { // unknown protocol version - failConnection(format("Client needs protocol version %d.%d, " - "server has %d.%d", - client.majorVersion, client.minorVersion, - defaultMajorVersion, defaultMinorVersion)); + failConnection(core::format( + "Client needs protocol version %d.%d, server has %d.%d", + client.majorVersion, client.minorVersion, + defaultMajorVersion, defaultMinorVersion)); } if (client.minorVersion != 3 && client.minorVersion != 7 && client.minorVersion != 8) { @@ -166,9 +168,9 @@ bool SConnection::processVersionMsg() if (*i == secTypeNone || *i == secTypeVncAuth) break; } if (i == secTypes.end()) { - failConnection(format("No supported security type for " - "%d.%d client", - client.majorVersion, client.minorVersion)); + failConnection( + core::format("No supported security type for %d.%d client", + client.majorVersion, client.minorVersion)); } os->writeU32(*i); @@ -278,7 +280,7 @@ bool SConnection::processInitMsg() return reader_->readClientInit(); } -void SConnection::handleAuthFailureTimeout(Timer* /*t*/) +void SConnection::handleAuthFailureTimeout(core::Timer* /*t*/) { if (state_ != RFBSTATE_SECURITY_FAILURE) { close("SConnection::handleAuthFailureTimeout: Invalid state"); @@ -417,11 +419,11 @@ void SConnection::handleClipboardProvide(uint32_t flags, } // FIXME: This conversion magic should be in SMsgReader - if (!isValidUTF8((const char*)data[0], lengths[0])) { + if (!core::isValidUTF8((const char*)data[0], lengths[0])) { vlog.error("Invalid UTF-8 sequence in clipboard - ignoring"); return; } - clientClipboard = convertLF((const char*)data[0], lengths[0]); + clientClipboard = core::convertLF((const char*)data[0], lengths[0]); hasRemoteClipboard = true; // FIXME: Should probably verify that this data was actually requested @@ -506,7 +508,7 @@ void SConnection::setPixelFormat(const PixelFormat& pf) writeFakeColourMap(); } -void SConnection::framebufferUpdateRequest(const Rect& /*r*/, +void SConnection::framebufferUpdateRequest(const core::Rect& /*r*/, bool /*incremental*/) { if (!readyForSetColourMapEntries) { @@ -590,7 +592,7 @@ void SConnection::sendClipboardData(const char* data) if (client.supportsEncoding(pseudoEncodingExtendedClipboard) && (client.clipboardFlags() & rfb::clipboardProvide)) { // FIXME: This conversion magic should be in SMsgWriter - std::string filtered(convertCRLF(data)); + std::string filtered(core::convertCRLF(data)); size_t sizes[1] = { filtered.size() + 1 }; const uint8_t* datas[1] = { (const uint8_t*)filtered.c_str() }; diff --git a/common/rfb/SConnection.h b/common/rfb/SConnection.h index f030ae0538..0f4de5a52a 100644 --- a/common/rfb/SConnection.h +++ b/common/rfb/SConnection.h @@ -26,13 +26,16 @@ #include -#include -#include +#include #include #include #include -#include + +namespace rdr { + class InStream; + class OutStream; +} namespace rfb { @@ -132,7 +135,7 @@ namespace rfb { // framebufferUpdateRequest() is called when a FramebufferUpdateRequest // message is received. The derived class must call on to // SConnection::framebufferUpdateRequest(). - void framebufferUpdateRequest(const Rect& r, bool incremental) override; + void framebufferUpdateRequest(const core::Rect& r, bool incremental) override; // fence() is called when we get a fence request or response. By default // it responds directly to requests (stating it doesn't support any @@ -243,7 +246,7 @@ namespace rfb { bool processSecurityFailure(); bool processInitMsg(); - void handleAuthFailureTimeout(Timer* t); + void handleAuthFailureTimeout(core::Timer* t); int defaultMajorVersion, defaultMinorVersion; @@ -256,7 +259,7 @@ namespace rfb { SecurityServer security; SSecurity* ssecurity; - MethodTimer authFailureTimer; + core::MethodTimer authFailureTimer; std::string authFailureMsg; stateEnum state_; diff --git a/common/rfb/SDesktop.h b/common/rfb/SDesktop.h index c97e788a3b..402a13af38 100644 --- a/common/rfb/SDesktop.h +++ b/common/rfb/SDesktop.h @@ -38,14 +38,19 @@ #ifndef __RFB_SDESKTOP_H__ #define __RFB_SDESKTOP_H__ -#include -#include +#include + #include +namespace core { struct Point; } + namespace network { class Socket; } namespace rfb { + struct ScreenSet; + class VNCServer; + class SDesktop { public: // init() is called immediately when the VNCServer gets a reference @@ -97,7 +102,7 @@ namespace rfb { // pointerEvent() is called whenever a client sends an event that // the pointer moved, or a button was pressed or released. - virtual void pointerEvent(const Point& /*pos*/, + virtual void pointerEvent(const core::Point& /*pos*/, uint16_t /*buttonMask*/) {}; // handleClipboardRequest() is called whenever a client requests @@ -122,47 +127,6 @@ namespace rfb { virtual ~SDesktop() {} }; - // -=- SStaticDesktop - // Trivial implementation of the SDesktop interface, which provides - // dummy input handlers and event processing routine, and exports - // a plain black desktop of the specified format. - class SStaticDesktop : public SDesktop { - public: - SStaticDesktop(const Point& size) - : server(nullptr), buffer(nullptr) - { - PixelFormat pf; - const uint8_t black[4] = { 0, 0, 0, 0 }; - buffer = new ManagedPixelBuffer(pf, size.x, size.y); - if (buffer) - buffer->fillRect(buffer->getRect(), black); - } - SStaticDesktop(const Point& size, const PixelFormat& pf) - : buffer(nullptr) - { - const uint8_t black[4] = { 0, 0, 0, 0 }; - buffer = new ManagedPixelBuffer(pf, size.x, size.y); - if (buffer) - buffer->fillRect(buffer->getRect(), black); - } - virtual ~SStaticDesktop() { - if (buffer) delete buffer; - } - - void init(VNCServer* vs) override { - server = vs; - server->setPixelBuffer(buffer); - } - void queryConnection(network::Socket* sock, - const char* /*userName*/) override { - server->approveConnection(sock, true, nullptr); - } - - protected: - VNCServer* server; - ManagedPixelBuffer* buffer; - }; - }; #endif // __RFB_SDESKTOP_H__ diff --git a/common/rfb/SMsgHandler.cxx b/common/rfb/SMsgHandler.cxx index 1dce634dd5..9eb5ae08b8 100644 --- a/common/rfb/SMsgHandler.cxx +++ b/common/rfb/SMsgHandler.cxx @@ -21,17 +21,17 @@ #include #endif -#include -#include +#include +#include + #include #include #include #include -#include using namespace rfb; -static LogWriter vlog("SMsgHandler"); +static core::LogWriter vlog("SMsgHandler"); SMsgHandler::SMsgHandler() { @@ -82,7 +82,7 @@ void SMsgHandler::keyEvent(uint32_t /*keysym*/, uint32_t /*keycode*/, { } -void SMsgHandler::pointerEvent(const Point& /*pos*/, +void SMsgHandler::pointerEvent(const core::Point& /*pos*/, uint16_t /*buttonMask*/) { } @@ -125,7 +125,7 @@ void SMsgHandler::handleClipboardCaps(uint32_t flags, const uint32_t* lengths) vlog.debug(" %s (only notify)", type); else { vlog.debug(" %s (automatically send up to %s)", - type, iecPrefix(lengths[i], "B").c_str()); + type, core::iecPrefix(lengths[i], "B").c_str()); } } } diff --git a/common/rfb/SMsgHandler.h b/common/rfb/SMsgHandler.h index c5d13d7827..f5f5b769f2 100644 --- a/common/rfb/SMsgHandler.h +++ b/common/rfb/SMsgHandler.h @@ -25,9 +25,7 @@ #include -#include #include -#include namespace rdr { class InStream; } @@ -47,7 +45,8 @@ namespace rfb { virtual void setPixelFormat(const PixelFormat& pf); virtual void setEncodings(int nEncodings, const int32_t* encodings); - virtual void framebufferUpdateRequest(const Rect& r, bool incremental) = 0; + virtual void framebufferUpdateRequest(const core::Rect& r, + bool incremental) = 0; virtual void setDesktopSize(int fb_width, int fb_height, const ScreenSet& layout) = 0; virtual void fence(uint32_t flags, unsigned len, const uint8_t data[]) = 0; @@ -56,7 +55,7 @@ namespace rfb { virtual void keyEvent(uint32_t keysym, uint32_t keycode, bool down); - virtual void pointerEvent(const Point& pos, + virtual void pointerEvent(const core::Point& pos, uint16_t buttonMask); virtual void clientCutText(const char* str); diff --git a/common/rfb/SMsgReader.cxx b/common/rfb/SMsgReader.cxx index 5df1115310..a8e475dbd2 100644 --- a/common/rfb/SMsgReader.cxx +++ b/common/rfb/SMsgReader.cxx @@ -25,6 +25,10 @@ #include +#include +#include +#include + #include #include @@ -32,17 +36,16 @@ #include #include #include +#include +#include #include #include -#include -#include -#include using namespace rfb; -static LogWriter vlog("SMsgReader"); +static core::LogWriter vlog("SMsgReader"); -static IntParameter maxCutText("MaxCutText", "Maximum permitted length of an incoming clipboard update", 256*1024); +static core::IntParameter maxCutText("MaxCutText", "Maximum permitted length of an incoming clipboard update", 256*1024); SMsgReader::SMsgReader(SMsgHandler* handler_, rdr::InStream* is_) : handler(handler_), is(is_), state(MSGSTATE_IDLE) @@ -201,7 +204,7 @@ bool SMsgReader::readFramebufferUpdateRequest() int y = is->readU16(); int w = is->readU16(); int h = is->readU16(); - handler->framebufferUpdateRequest(Rect(x, y, x+w, y+h), inc); + handler->framebufferUpdateRequest({x, y, x+w, y+h}, inc); return true; } @@ -298,7 +301,7 @@ bool SMsgReader::readPointerEvent() } is->clearRestorePoint(); - handler->pointerEvent(Point(x, y), mask); + handler->pointerEvent({x, y}, mask); return true; } @@ -338,8 +341,8 @@ bool SMsgReader::readClientCutText() std::vector ca(len); is->readBytes((uint8_t*)ca.data(), len); - std::string utf8(latin1ToUTF8(ca.data(), ca.size())); - std::string filtered(convertLF(utf8.data(), utf8.size())); + std::string utf8(core::latin1ToUTF8(ca.data(), ca.size())); + std::string filtered(core::convertLF(utf8.data(), utf8.size())); handler->clientCutText(filtered.c_str()); @@ -485,7 +488,7 @@ bool SMsgReader::readQEMUMessage() ret = readQEMUKeyEvent(); break; default: - throw protocol_error(format("Unknown QEMU submessage type %d", subType)); + throw protocol_error(core::format("Unknown QEMU submessage type %d", subType)); } if (!ret) { diff --git a/common/rfb/SMsgWriter.cxx b/common/rfb/SMsgWriter.cxx index 5ee0905b3d..d52df511c8 100644 --- a/common/rfb/SMsgWriter.cxx +++ b/common/rfb/SMsgWriter.cxx @@ -24,6 +24,9 @@ #include +#include +#include + #include #include #include @@ -32,16 +35,17 @@ #include #include #include +#include #include #include +#include #include -#include +#include #include -#include using namespace rfb; -static LogWriter vlog("SMsgWriter"); +static core::LogWriter vlog("SMsgWriter"); SMsgWriter::SMsgWriter(ClientParams* client_, rdr::OutStream* os_) : client(client_), os(os_), @@ -95,7 +99,7 @@ void SMsgWriter::writeServerCutText(const char* str) if (strchr(str, '\r') != nullptr) throw std::invalid_argument("Invalid carriage return in clipboard data"); - std::string latin1(utf8ToLatin1(str)); + std::string latin1(core::utf8ToLatin1(str)); startMsg(msgTypeServerCutText); os->pad(3); @@ -405,7 +409,7 @@ void SMsgWriter::writeFramebufferUpdateEnd() endMsg(); } -void SMsgWriter::writeCopyRect(const Rect& r, int srcX, int srcY) +void SMsgWriter::writeCopyRect(const core::Rect& r, int srcX, int srcY) { startRect(r,encodingCopyRect); os->writeU16(srcX); @@ -413,7 +417,7 @@ void SMsgWriter::writeCopyRect(const Rect& r, int srcX, int srcY) endRect(); } -void SMsgWriter::startRect(const Rect& r, int encoding) +void SMsgWriter::startRect(const core::Rect& r, int encoding) { if (++nRectsInUpdate > nRectsInHeader && nRectsInHeader) throw std::logic_error("SMsgWriter::startRect: nRects out of sync"); @@ -488,7 +492,7 @@ void SMsgWriter::writePseudoRects() } if (needCursorPos) { - const Point& cursorPos = client->cursorPos(); + const core::Point& cursorPos = client->cursorPos(); if (client->supportsEncoding(pseudoEncodingVMwareCursorPosition)) { writeSetVMwareCursorPositionRect(cursorPos.x, cursorPos.y); diff --git a/common/rfb/SMsgWriter.h b/common/rfb/SMsgWriter.h index 7bc0ed6a50..113a93709d 100644 --- a/common/rfb/SMsgWriter.h +++ b/common/rfb/SMsgWriter.h @@ -25,8 +25,7 @@ #include -#include -#include +namespace core { struct Rect; } namespace rdr { class OutStream; } @@ -117,11 +116,11 @@ namespace rfb { void writeFramebufferUpdateEnd(); // There is no explicit encoder for CopyRect rects. - void writeCopyRect(const Rect& r, int srcX, int srcY); + void writeCopyRect(const core::Rect& r, int srcX, int srcY); // Encoders should call these to mark the start and stop of individual // rects. - void startRect(const Rect& r, int enc); + void startRect(const core::Rect& r, int enc); void endRect(); protected: diff --git a/common/rfb/SSecurity.h b/common/rfb/SSecurity.h index 0911ecd83b..edbe818594 100644 --- a/common/rfb/SSecurity.h +++ b/common/rfb/SSecurity.h @@ -44,12 +44,12 @@ #ifndef __RFB_SSECURITY_H__ #define __RFB_SSECURITY_H__ -#include - -#include +#include namespace rfb { + class SConnection; + class SSecurity { public: SSecurity(SConnection* sc_) : sc(sc_) {} diff --git a/common/rfb/SSecurityPlain.cxx b/common/rfb/SSecurityPlain.cxx index e62e6d6086..b604a44754 100644 --- a/common/rfb/SSecurityPlain.cxx +++ b/common/rfb/SSecurityPlain.cxx @@ -21,10 +21,12 @@ #include #endif +#include +#include + #include #include #include -#include #include #if !defined(WIN32) && !defined(__APPLE__) #include @@ -37,7 +39,7 @@ using namespace rfb; -StringParameter PasswordValidator::plainUsers +core::StringParameter PasswordValidator::plainUsers ("PlainUsers", "Users permitted to access via Plain security type (including TLSPlain, X509Plain etc.)" #ifdef HAVE_NETTLE @@ -50,7 +52,7 @@ bool PasswordValidator::validUser(const char* username) { std::vector users; - users = split(plainUsers, ','); + users = core::split(plainUsers, ','); for (size_t i = 0; i < users.size(); i++) { if (users[i] == "*") diff --git a/common/rfb/SSecurityPlain.h b/common/rfb/SSecurityPlain.h index c0ac049b02..b735e30254 100644 --- a/common/rfb/SSecurityPlain.h +++ b/common/rfb/SSecurityPlain.h @@ -20,18 +20,18 @@ #ifndef __RFB_SSECURITYPLAIN_H__ #define __RFB_SSECURITYPLAIN_H__ -#include +#include #include -#include -#include namespace rfb { + class StringParameter; + class PasswordValidator { public: bool validate(SConnection* sc, const char *username, const char *password) { return validUser(username) ? validateInternal(sc, username, password) : false; } - static StringParameter plainUsers; + static core::StringParameter plainUsers; virtual ~PasswordValidator() { } diff --git a/common/rfb/SSecurityRSAAES.cxx b/common/rfb/SSecurityRSAAES.cxx index d7e7cc4c31..1e552c0c2f 100644 --- a/common/rfb/SSecurityRSAAES.cxx +++ b/common/rfb/SSecurityRSAAES.cxx @@ -37,13 +37,15 @@ #include #include +#include +#include + #include #include -#include +#include #include #include -#include #include #if !defined(WIN32) && !defined(__APPLE__) #include @@ -67,14 +69,14 @@ const size_t MaxKeyFileSize = 32 * 1024; using namespace rfb; -StringParameter SSecurityRSAAES::keyFile +core::StringParameter SSecurityRSAAES::keyFile ("RSAKey", "Path to the RSA key for the RSA-AES security types in " - "PEM format", "", ConfServer); -BoolParameter SSecurityRSAAES::requireUsername + "PEM format", "", core::ConfServer); +core::BoolParameter SSecurityRSAAES::requireUsername ("RequireUsername", "Require username for the RSA-AES security types", - false, ConfServer); + false, core::ConfServer); -static LogWriter vlog("SSecurityRSAAES"); +static core::LogWriter vlog("SSecurityRSAAES"); SSecurityRSAAES::SSecurityRSAAES(SConnection* sc_, uint32_t _secType, int _keySize, bool _isAllEncrypted) @@ -174,7 +176,7 @@ void SSecurityRSAAES::loadPrivateKey() { FILE* file = fopen(keyFile, "rb"); if (!file) - throw rdr::posix_error("Failed to open key file", errno); + throw core::posix_error("Failed to open key file", errno); fseek(file, 0, SEEK_END); size_t size = ftell(file); if (size == 0 || size > MaxKeyFileSize) { @@ -185,7 +187,7 @@ void SSecurityRSAAES::loadPrivateKey() std::vector data(size); if (fread(data.data(), 1, data.size(), file) != size) { fclose(file); - throw rdr::posix_error("Failed to read key", errno); + throw core::posix_error("Failed to read key", errno); } fclose(file); @@ -345,6 +347,7 @@ static void random_func(void* ctx, size_t length, uint8_t* dst) void SSecurityRSAAES::writeRandom() { + rdr::RandomStream rs; rdr::OutStream* os = sc->getOutStream(); if (!rs.hasData(keySize / 8)) throw std::runtime_error("Failed to generate random"); diff --git a/common/rfb/SSecurityRSAAES.h b/common/rfb/SSecurityRSAAES.h index e3300cb7ea..283134db7c 100644 --- a/common/rfb/SSecurityRSAAES.h +++ b/common/rfb/SSecurityRSAAES.h @@ -27,7 +27,10 @@ #include -#include +namespace core { + class BoolParameter; + class StringParameter; +} namespace rdr { class InStream; @@ -51,8 +54,8 @@ namespace rfb { return accessRights; } - static StringParameter keyFile; - static BoolParameter requireUsername; + static core::StringParameter keyFile; + static core::BoolParameter requireUsername; private: void cleanup(); @@ -96,8 +99,6 @@ namespace rfb { rdr::InStream* rawis; rdr::OutStream* rawos; - - rdr::RandomStream rs; }; } diff --git a/common/rfb/SSecurityTLS.cxx b/common/rfb/SSecurityTLS.cxx index b297242b4f..ea0ad6ebbb 100644 --- a/common/rfb/SSecurityTLS.cxx +++ b/common/rfb/SSecurityTLS.cxx @@ -30,13 +30,16 @@ #include +#include + #include #include -#include #include + #include #include #include + #include #if defined (SSECURITYTLS__USE_DEPRECATED_DH) @@ -59,13 +62,15 @@ static const gnutls_datum_t ffdhe_pkcs3_param = { using namespace rfb; -StringParameter SSecurityTLS::X509_CertFile -("X509Cert", "Path to the X509 certificate in PEM format", "", ConfServer); +core::StringParameter SSecurityTLS::X509_CertFile( + "X509Cert", "Path to the X509 certificate in PEM format", + "", core::ConfServer); -StringParameter SSecurityTLS::X509_KeyFile -("X509Key", "Path to the key of the X509 certificate in PEM format", "", ConfServer); +core::StringParameter SSecurityTLS::X509_KeyFile( + "X509Key", "Path to the key of the X509 certificate in PEM format", + "", core::ConfServer); -static LogWriter vlog("TLS"); +static core::LogWriter vlog("TLS"); SSecurityTLS::SSecurityTLS(SConnection* sc_, bool _anon) : SSecurity(sc_), session(nullptr), anon_cred(nullptr), diff --git a/common/rfb/SSecurityTLS.h b/common/rfb/SSecurityTLS.h index 1dc33cfd88..e899cff2dd 100644 --- a/common/rfb/SSecurityTLS.h +++ b/common/rfb/SSecurityTLS.h @@ -26,6 +26,7 @@ #error "This header should not be included without HAVE_GNUTLS defined" #endif +#include #include #include @@ -46,6 +47,8 @@ namespace rdr { namespace rfb { + class StringParameter; + class SSecurityTLS : public SSecurity { public: SSecurityTLS(SConnection* sc, bool _anon); @@ -54,8 +57,8 @@ namespace rfb { const char* getUserName() const override {return nullptr;} int getType() const override { return anon ? secTypeTLSNone : secTypeX509None;} - static StringParameter X509_CertFile; - static StringParameter X509_KeyFile; + static core::StringParameter X509_CertFile; + static core::StringParameter X509_KeyFile; protected: void shutdown(); diff --git a/common/rfb/SSecurityVeNCrypt.cxx b/common/rfb/SSecurityVeNCrypt.cxx index 4617fddba9..757acc0643 100644 --- a/common/rfb/SSecurityVeNCrypt.cxx +++ b/common/rfb/SSecurityVeNCrypt.cxx @@ -26,15 +26,20 @@ #include #endif +#include + +#include +#include #include #include -#include +#include + #include #include using namespace rfb; -static LogWriter vlog("SVeNCrypt"); +static core::LogWriter vlog("SVeNCrypt"); SSecurityVeNCrypt::SSecurityVeNCrypt(SConnection* sc_, SecurityServer *sec) diff --git a/common/rfb/SSecurityVeNCrypt.h b/common/rfb/SSecurityVeNCrypt.h index ea2bb6fb12..534f94a67a 100644 --- a/common/rfb/SSecurityVeNCrypt.h +++ b/common/rfb/SSecurityVeNCrypt.h @@ -25,11 +25,13 @@ #ifndef __SSECURITYVENCRYPT_H__ #define __SSECURITYVENCRYPT_H__ -#include -#include +#include namespace rfb { + class SConnection; + class SecurityServer; + class SSecurityVeNCrypt : public SSecurity { public: SSecurityVeNCrypt(SConnection* sc, SecurityServer *sec); diff --git a/common/rfb/SSecurityVncAuth.cxx b/common/rfb/SSecurityVncAuth.cxx index 22d8807905..3ab02a1e9e 100644 --- a/common/rfb/SSecurityVncAuth.cxx +++ b/common/rfb/SSecurityVncAuth.cxx @@ -25,13 +25,17 @@ #include #endif +#include +#include + +#include + #include #include #include -#include -#include #include #include + #include #include #include @@ -42,12 +46,12 @@ extern "C" { using namespace rfb; -static LogWriter vlog("SVncAuth"); +static core::LogWriter vlog("SVncAuth"); -StringParameter SSecurityVncAuth::vncAuthPasswdFile -("PasswordFile", "Password file for VNC authentication", "", ConfServer); -AliasParameter rfbauth("rfbauth", "Alias for PasswordFile", - &SSecurityVncAuth::vncAuthPasswdFile, ConfServer); +core::StringParameter SSecurityVncAuth::vncAuthPasswdFile +("PasswordFile", "Password file for VNC authentication", "", core::ConfServer); +core::AliasParameter rfbauth("rfbauth", "Alias for PasswordFile", + &SSecurityVncAuth::vncAuthPasswdFile, core::ConfServer); VncAuthPasswdParameter SSecurityVncAuth::vncAuthPasswd ("Password", "Obfuscated binary encoding of the password which clients must supply to " "access the server", &SSecurityVncAuth::vncAuthPasswdFile); @@ -118,8 +122,8 @@ bool SSecurityVncAuth::processMsg() VncAuthPasswdParameter::VncAuthPasswdParameter(const char* name_, const char* desc, - StringParameter* passwdFile_) -: BinaryParameter(name_, desc, nullptr, 0, ConfServer), + core::StringParameter* passwdFile_) +: core::BinaryParameter(name_, desc, nullptr, 0, core::ConfServer), passwdFile(passwdFile_) { } diff --git a/common/rfb/SSecurityVncAuth.h b/common/rfb/SSecurityVncAuth.h index 532abe0ab5..e284533720 100644 --- a/common/rfb/SSecurityVncAuth.h +++ b/common/rfb/SSecurityVncAuth.h @@ -26,7 +26,8 @@ #include -#include +#include + #include #include @@ -41,12 +42,12 @@ namespace rfb { virtual ~VncAuthPasswdGetter() { } }; - class VncAuthPasswdParameter : public VncAuthPasswdGetter, BinaryParameter { + class VncAuthPasswdParameter : public VncAuthPasswdGetter, core::BinaryParameter { public: - VncAuthPasswdParameter(const char* name, const char* desc, StringParameter* passwdFile_); + VncAuthPasswdParameter(const char* name, const char* desc, core::StringParameter* passwdFile_); void getVncAuthPasswd(std::string *password, std::string *readOnlyPassword) override; protected: - StringParameter* passwdFile; + core::StringParameter* passwdFile; }; class SSecurityVncAuth : public SSecurity { @@ -56,7 +57,7 @@ namespace rfb { int getType() const override {return secTypeVncAuth;} const char* getUserName() const override {return nullptr;} AccessRights getAccessRights() const override { return accessRights; } - static StringParameter vncAuthPasswdFile; + static core::StringParameter vncAuthPasswdFile; static VncAuthPasswdParameter vncAuthPasswd; private: bool verifyResponse(const char* password); diff --git a/common/rfb/ScreenSet.h b/common/rfb/ScreenSet.h index fb93e5c298..10753b1781 100644 --- a/common/rfb/ScreenSet.h +++ b/common/rfb/ScreenSet.h @@ -25,10 +25,11 @@ #include #include -#include #include #include +#include + namespace rfb { // rfb::Screen @@ -52,7 +53,7 @@ namespace rfb { } uint32_t id; - Rect dimensions; + core::Rect dimensions; uint32_t flags; }; @@ -87,7 +88,7 @@ namespace rfb { inline bool validate(int fb_width, int fb_height) const { std::list::const_iterator iter; std::set seen_ids; - Rect fb_rect; + core::Rect fb_rect; if (screens.empty()) return false; diff --git a/common/rfb/Security.cxx b/common/rfb/Security.cxx index 3b0d95bf0f..32806e0c8d 100644 --- a/common/rfb/Security.cxx +++ b/common/rfb/Security.cxx @@ -25,16 +25,17 @@ #include -#include +#include +#include + #include -#include using namespace rfb; -static LogWriter vlog("Security"); +static core::LogWriter vlog("Security"); #ifdef HAVE_GNUTLS -StringParameter Security::GnuTLSPriority("GnuTLSPriority", +core::StringParameter Security::GnuTLSPriority("GnuTLSPriority", "GnuTLS priority string that controls the TLS session’s handshake algorithms", ""); #endif @@ -43,7 +44,7 @@ Security::Security() { } -Security::Security(StringParameter &secTypes) +Security::Security(core::StringParameter& secTypes) { enabledSecTypes = parseSecTypes(secTypes); } @@ -184,7 +185,7 @@ std::list rfb::parseSecTypes(const char* types_) { std::list result; std::vector types; - types = split(types_, ','); + types = core::split(types_, ','); for (size_t i = 0; i < types.size(); i++) { uint32_t typeNum = secTypeNum(types[i].c_str()); if (typeNum != secTypeInvalid) diff --git a/common/rfb/Security.h b/common/rfb/Security.h index 430a1d89d0..d704daa774 100644 --- a/common/rfb/Security.h +++ b/common/rfb/Security.h @@ -24,11 +24,12 @@ #include -#include - #include +namespace core { class StringParameter; } + namespace rfb { + const uint8_t secTypeInvalid = 0; const uint8_t secTypeNone = 1; const uint8_t secTypeVncAuth = 2; @@ -76,7 +77,7 @@ namespace rfb { * Create Security instance. */ Security(); - Security(StringParameter &secTypes); + Security(core::StringParameter& secTypes); /* * Note about security types. @@ -105,7 +106,7 @@ namespace rfb { char *ToString(void); #ifdef HAVE_GNUTLS - static StringParameter GnuTLSPriority; + static core::StringParameter GnuTLSPriority; #endif private: @@ -115,6 +116,7 @@ namespace rfb { const char* secTypeName(uint32_t num); uint32_t secTypeNum(const char* name); std::list parseSecTypes(const char* types); + } #endif diff --git a/common/rfb/SecurityClient.cxx b/common/rfb/SecurityClient.cxx index 027d47df2d..7350dad4c5 100644 --- a/common/rfb/SecurityClient.cxx +++ b/common/rfb/SecurityClient.cxx @@ -25,12 +25,15 @@ #include +#include + #include #include #include #include #include #include +#include #ifdef HAVE_GNUTLS #include #endif @@ -42,7 +45,7 @@ using namespace rfb; -StringParameter SecurityClient::secTypes +core::StringParameter SecurityClient::secTypes ("SecurityTypes", "Specify which security scheme to use (None, VncAuth, Plain" #ifdef HAVE_GNUTLS @@ -59,7 +62,7 @@ StringParameter SecurityClient::secTypes "RA2,RA2_256,RA2ne,RA2ne_256,DH,MSLogonII," #endif "VncAuth,None", -ConfViewer); +core::ConfViewer); CSecurity* SecurityClient::GetCSecurity(CConnection* cc, uint32_t secType) { diff --git a/common/rfb/SecurityClient.h b/common/rfb/SecurityClient.h index b86fcb35c1..c55cace671 100644 --- a/common/rfb/SecurityClient.h +++ b/common/rfb/SecurityClient.h @@ -22,12 +22,15 @@ #ifndef __RFB_SECURITYCLIENT_H__ #define __RFB_SECURITYCLIENT_H__ -#include #include -#include + +namespace core { class StringParameter; } namespace rfb { + class CConnection; + class CSecurity; + class SecurityClient : public Security { public: SecurityClient(void) : Security(secTypes) {} @@ -35,7 +38,7 @@ namespace rfb { /* Create client side CSecurity class instance */ CSecurity* GetCSecurity(CConnection* cc, uint32_t secType); - static StringParameter secTypes; + static core::StringParameter secTypes; }; } diff --git a/common/rfb/SecurityServer.cxx b/common/rfb/SecurityServer.cxx index d692f4fc93..65571753c2 100644 --- a/common/rfb/SecurityServer.cxx +++ b/common/rfb/SecurityServer.cxx @@ -21,7 +21,11 @@ #include #endif +#include + #include +#include + #include #include #include @@ -36,7 +40,7 @@ using namespace rfb; -StringParameter SecurityServer::secTypes +core::StringParameter SecurityServer::secTypes ("SecurityTypes", "Specify which security scheme to use (None, VncAuth, Plain" #ifdef HAVE_GNUTLS @@ -50,7 +54,7 @@ StringParameter SecurityServer::secTypes "TLSVnc," #endif "VncAuth", -ConfServer); +core::ConfServer); SSecurity* SecurityServer::GetSSecurity(SConnection* sc, uint32_t secType) { diff --git a/common/rfb/SecurityServer.h b/common/rfb/SecurityServer.h index a51ee23cf1..338dd1ddb9 100644 --- a/common/rfb/SecurityServer.h +++ b/common/rfb/SecurityServer.h @@ -20,7 +20,6 @@ #ifndef __RFB_SECURITYSERVER_H__ #define __RFB_SECURITYSERVER_H__ -#include #include namespace rfb { @@ -35,7 +34,7 @@ namespace rfb { /* Create server side SSecurity class instance */ SSecurity* GetSSecurity(SConnection* sc, uint32_t secType); - static StringParameter secTypes; + static core::StringParameter secTypes; }; } diff --git a/common/rfb/ServerCore.cxx b/common/rfb/ServerCore.cxx index 1a80dc0c05..866672f90b 100644 --- a/common/rfb/ServerCore.cxx +++ b/common/rfb/ServerCore.cxx @@ -28,74 +28,74 @@ #include #include -rfb::IntParameter rfb::Server::idleTimeout +core::IntParameter rfb::Server::idleTimeout ("IdleTimeout", "The number of seconds after which an idle VNC connection will be dropped " "(zero means no timeout)", 0, 0); -rfb::IntParameter rfb::Server::maxDisconnectionTime +core::IntParameter rfb::Server::maxDisconnectionTime ("MaxDisconnectionTime", "Terminate when no client has been connected for s seconds", 0, 0); -rfb::IntParameter rfb::Server::maxConnectionTime +core::IntParameter rfb::Server::maxConnectionTime ("MaxConnectionTime", "Terminate when a client has been connected for s seconds", 0, 0); -rfb::IntParameter rfb::Server::maxIdleTime +core::IntParameter rfb::Server::maxIdleTime ("MaxIdleTime", "Terminate after s seconds of user inactivity", 0, 0); -rfb::IntParameter rfb::Server::compareFB +core::IntParameter rfb::Server::compareFB ("CompareFB", "Perform pixel comparison on framebuffer to reduce unnecessary updates " "(0: never, 1: always, 2: auto)", 2); -rfb::IntParameter rfb::Server::frameRate +core::IntParameter rfb::Server::frameRate ("FrameRate", "The maximum number of updates per second sent to each client", 60); -rfb::BoolParameter rfb::Server::protocol3_3 +core::BoolParameter rfb::Server::protocol3_3 ("Protocol3.3", "Always use protocol version 3.3 for backwards compatibility with " "badly-behaved clients", false); -rfb::BoolParameter rfb::Server::alwaysShared +core::BoolParameter rfb::Server::alwaysShared ("AlwaysShared", "Always treat incoming connections as shared, regardless of the client-" "specified setting", false); -rfb::BoolParameter rfb::Server::neverShared +core::BoolParameter rfb::Server::neverShared ("NeverShared", "Never treat incoming connections as shared, regardless of the client-" "specified setting", false); -rfb::BoolParameter rfb::Server::disconnectClients +core::BoolParameter rfb::Server::disconnectClients ("DisconnectClients", "Disconnect existing clients if an incoming connection is non-shared. " "If combined with NeverShared then new connections will be refused " "while there is a client active", true); -rfb::BoolParameter rfb::Server::acceptKeyEvents +core::BoolParameter rfb::Server::acceptKeyEvents ("AcceptKeyEvents", "Accept key press and release events from clients.", true); -rfb::BoolParameter rfb::Server::acceptPointerEvents +core::BoolParameter rfb::Server::acceptPointerEvents ("AcceptPointerEvents", "Accept pointer movement and button events from clients.", true); -rfb::BoolParameter rfb::Server::acceptCutText +core::BoolParameter rfb::Server::acceptCutText ("AcceptCutText", "Accept clipboard updates from clients.", true); -rfb::BoolParameter rfb::Server::sendCutText +core::BoolParameter rfb::Server::sendCutText ("SendCutText", "Send clipboard changes to clients.", true); -rfb::BoolParameter rfb::Server::acceptSetDesktopSize +core::BoolParameter rfb::Server::acceptSetDesktopSize ("AcceptSetDesktopSize", "Accept set desktop size events from clients.", true); -rfb::BoolParameter rfb::Server::queryConnect +core::BoolParameter rfb::Server::queryConnect ("QueryConnect", "Prompt the local user to accept or reject incoming connections.", false); diff --git a/common/rfb/ServerCore.h b/common/rfb/ServerCore.h index 69cad39fda..a7c7f309ce 100644 --- a/common/rfb/ServerCore.h +++ b/common/rfb/ServerCore.h @@ -24,29 +24,29 @@ #ifndef __RFB_SERVER_CORE_H__ #define __RFB_SERVER_CORE_H__ -#include +#include namespace rfb { class Server { public: - static IntParameter idleTimeout; - static IntParameter maxDisconnectionTime; - static IntParameter maxConnectionTime; - static IntParameter maxIdleTime; - static IntParameter compareFB; - static IntParameter frameRate; - static BoolParameter protocol3_3; - static BoolParameter alwaysShared; - static BoolParameter neverShared; - static BoolParameter disconnectClients; - static BoolParameter acceptKeyEvents; - static BoolParameter acceptPointerEvents; - static BoolParameter acceptCutText; - static BoolParameter sendCutText; - static BoolParameter acceptSetDesktopSize; - static BoolParameter queryConnect; + static core::IntParameter idleTimeout; + static core::IntParameter maxDisconnectionTime; + static core::IntParameter maxConnectionTime; + static core::IntParameter maxIdleTime; + static core::IntParameter compareFB; + static core::IntParameter frameRate; + static core::BoolParameter protocol3_3; + static core::BoolParameter alwaysShared; + static core::BoolParameter neverShared; + static core::BoolParameter disconnectClients; + static core::BoolParameter acceptKeyEvents; + static core::BoolParameter acceptPointerEvents; + static core::BoolParameter acceptCutText; + static core::BoolParameter sendCutText; + static core::BoolParameter acceptSetDesktopSize; + static core::BoolParameter queryConnect; }; diff --git a/common/rfb/ServerParams.cxx b/common/rfb/ServerParams.cxx index b7432b8f2a..e4691e19e7 100644 --- a/common/rfb/ServerParams.cxx +++ b/common/rfb/ServerParams.cxx @@ -24,9 +24,12 @@ #include +#include + #include +#include +#include #include -#include using namespace rfb; @@ -40,7 +43,11 @@ ServerParams::ServerParams() { setName(""); - cursor_ = new Cursor(0, 0, Point(), nullptr); + screenLayout_ = new ScreenSet(); + + pf_ = new PixelFormat(); + + cursor_ = new Cursor(0, 0, {}, nullptr); clipFlags = 0; memset(clipSizes, 0, sizeof(clipSizes)); @@ -65,12 +72,14 @@ void ServerParams::setDimensions(int width, int height, const ScreenSet& layout) width_ = width; height_ = height; - screenLayout_ = layout; + delete screenLayout_; + screenLayout_ = new ScreenSet(layout); } void ServerParams::setPF(const PixelFormat& pf) { - pf_ = pf; + delete pf_; + pf_ = new PixelFormat(pf); if (pf.bpp != 8 && pf.bpp != 16 && pf.bpp != 32) throw std::invalid_argument("setPF: Not 8, 16 or 32 bpp?"); @@ -101,7 +110,8 @@ uint32_t ServerParams::clipboardSize(unsigned int format) const return clipSizes[i]; } - throw std::invalid_argument(rfb::format("Invalid clipboard format 0x%x", format)); + throw std::invalid_argument( + core::format("Invalid clipboard format 0x%x", format)); } void ServerParams::setClipboardCaps(uint32_t flags, const uint32_t* lengths) diff --git a/common/rfb/ServerParams.h b/common/rfb/ServerParams.h index d730b89139..6be9acd61c 100644 --- a/common/rfb/ServerParams.h +++ b/common/rfb/ServerParams.h @@ -25,12 +25,12 @@ #include -#include -#include -#include - namespace rfb { + class Cursor; + class PixelFormat; + struct ScreenSet; + class ServerParams { public: ServerParams(); @@ -55,11 +55,11 @@ namespace rfb { int width() const { return width_; } int height() const { return height_; } - const ScreenSet& screenLayout() const { return screenLayout_; } + const ScreenSet& screenLayout() const { return *screenLayout_; } void setDimensions(int width, int height); void setDimensions(int width, int height, const ScreenSet& layout); - const PixelFormat& pf() const { return pf_; } + const PixelFormat& pf() const { return *pf_; } void setPF(const PixelFormat& pf); const char* name() const { return name_.c_str(); } @@ -85,9 +85,9 @@ namespace rfb { int width_; int height_; - ScreenSet screenLayout_; + ScreenSet* screenLayout_; - PixelFormat pf_; + PixelFormat* pf_; std::string name_; Cursor* cursor_; unsigned int ledState_; diff --git a/common/rfb/TightDecoder.cxx b/common/rfb/TightDecoder.cxx index a26c0bfe02..da0d586591 100644 --- a/common/rfb/TightDecoder.cxx +++ b/common/rfb/TightDecoder.cxx @@ -27,16 +27,18 @@ #include +#include + #include #include #include #include #include +#include #include #include #include -#include using namespace rfb; @@ -51,7 +53,7 @@ TightDecoder::~TightDecoder() { } -bool TightDecoder::readRect(const Rect& r, rdr::InStream* is, +bool TightDecoder::readRect(const core::Rect& r, rdr::InStream* is, const ServerParams& server, rdr::OutStream* os) { uint8_t comp_ctl; @@ -111,7 +113,8 @@ bool TightDecoder::readRect(const Rect& r, rdr::InStream* is, int palSize = 0; if (r.width() > TIGHT_MAX_WIDTH) - throw protocol_error(format("TightDecoder: Too large rectangle (%d pixels)", r.width())); + throw protocol_error(core::format( + "TightDecoder: Too large rectangle (%d pixels)", r.width())); // Possible palette if ((comp_ctl & tightExplicitFilter) != 0) { @@ -192,10 +195,10 @@ bool TightDecoder::readRect(const Rect& r, rdr::InStream* is, return true; } -bool TightDecoder::doRectsConflict(const Rect& /*rectA*/, +bool TightDecoder::doRectsConflict(const core::Rect& /*rectA*/, const uint8_t* bufferA, size_t buflenA, - const Rect& /*rectB*/, + const core::Rect& /*rectB*/, const uint8_t* bufferB, size_t buflenB, const ServerParams& /*server*/) @@ -220,7 +223,7 @@ bool TightDecoder::doRectsConflict(const Rect& /*rectA*/, return false; } -void TightDecoder::decodeRect(const Rect& r, const uint8_t* buffer, +void TightDecoder::decodeRect(const core::Rect& r, const uint8_t* buffer, size_t buflen, const ServerParams& server, ModifiablePixelBuffer* pb) { @@ -506,7 +509,7 @@ uint32_t TightDecoder::readCompact(rdr::InStream* is) void TightDecoder::FilterGradient24(const uint8_t *inbuf, const PixelFormat& pf, uint32_t* outbuf, - int stride, const Rect& r) + int stride, const core::Rect& r) { int x, y, c; uint8_t prevRow[TIGHT_MAX_WIDTH*3]; @@ -552,7 +555,7 @@ TightDecoder::FilterGradient24(const uint8_t *inbuf, template void TightDecoder::FilterGradient(const uint8_t* inbuf, const PixelFormat& pf, T* outbuf, - int stride, const Rect& r) + int stride, const core::Rect& r) { int x, y, c; static uint8_t prevRow[TIGHT_MAX_WIDTH*3]; @@ -606,7 +609,7 @@ void TightDecoder::FilterGradient(const uint8_t* inbuf, template void TightDecoder::FilterPalette(const T* palette, int palSize, const uint8_t* inbuf, T* outbuf, - int stride, const Rect& r) + int stride, const core::Rect& r) { // Indexed color int x, h = r.height(), w = r.width(), b, pad = stride - w; diff --git a/common/rfb/TightDecoder.h b/common/rfb/TightDecoder.h index d569a7fd63..a75fc7daf4 100644 --- a/common/rfb/TightDecoder.h +++ b/common/rfb/TightDecoder.h @@ -22,7 +22,6 @@ #include #include -#include namespace rfb { @@ -31,15 +30,15 @@ namespace rfb { public: TightDecoder(); virtual ~TightDecoder(); - bool readRect(const Rect& r, rdr::InStream* is, + bool readRect(const core::Rect& r, rdr::InStream* is, const ServerParams& server, rdr::OutStream* os) override; - bool doRectsConflict(const Rect& rectA, + bool doRectsConflict(const core::Rect& rectA, const uint8_t* bufferA, size_t buflenA, - const Rect& rectB, + const core::Rect& rectB, const uint8_t* bufferB, size_t buflenB, const ServerParams& server) override; - void decodeRect(const Rect& r, const uint8_t* buffer, + void decodeRect(const core::Rect& r, const uint8_t* buffer, size_t buflen, const ServerParams& server, ModifiablePixelBuffer* pb) override; @@ -47,16 +46,16 @@ namespace rfb { uint32_t readCompact(rdr::InStream* is); void FilterGradient24(const uint8_t* inbuf, const PixelFormat& pf, - uint32_t* outbuf, int stride, const Rect& r); + uint32_t* outbuf, int stride, const core::Rect& r); template void FilterGradient(const uint8_t* inbuf, const PixelFormat& pf, - T* outbuf, int stride, const Rect& r); + T* outbuf, int stride, const core::Rect& r); template void FilterPalette(const T* palette, int palSize, const uint8_t* inbuf, T* outbuf, - int stride, const Rect& r); + int stride, const core::Rect& r); private: rdr::ZlibInStream zis[4]; diff --git a/common/rfb/UnixPasswordValidator.cxx b/common/rfb/UnixPasswordValidator.cxx index 57fa9b3965..36b8dd7af3 100644 --- a/common/rfb/UnixPasswordValidator.cxx +++ b/common/rfb/UnixPasswordValidator.cxx @@ -22,17 +22,17 @@ #include #endif -#include -#include +#include + #include #include using namespace rfb; -static StringParameter pamService +static core::StringParameter pamService ("PAMService", "Service name for PAM password validation", "vnc"); -AliasParameter pam_service("pam_service", "Alias for PAMService", - &pamService); +core::AliasParameter pam_service("pam_service", "Alias for PAMService", + &pamService); int do_pam_auth(const char *service, const char *username, const char *password); diff --git a/common/rfb/UpdateTracker.cxx b/common/rfb/UpdateTracker.cxx index 7c97a6b84d..1aedf4917a 100644 --- a/common/rfb/UpdateTracker.cxx +++ b/common/rfb/UpdateTracker.cxx @@ -25,27 +25,31 @@ #include #endif +#include + #include -#include using namespace rfb; -static LogWriter vlog("UpdateTracker"); +static core::LogWriter vlog("UpdateTracker"); // -=- ClippingUpdateTracker -void ClippingUpdateTracker::add_changed(const Region ®ion) { +void ClippingUpdateTracker::add_changed(const core::Region& region) +{ ut->add_changed(region.intersect(clipRect)); } -void ClippingUpdateTracker::add_copied(const Region &dest, const Point &delta) { +void ClippingUpdateTracker::add_copied(const core::Region& dest, + const core::Point& delta) +{ // Clip the destination to the display area - Region clipdest = dest.intersect(clipRect); + core::Region clipdest = dest.intersect(clipRect); if (clipdest.is_empty()) return; // Clip the source to the screen - Region tmp = clipdest; + core::Region tmp = clipdest; tmp.translate(delta.negate()); tmp.assign_intersect(clipRect); if (!tmp.is_empty()) { @@ -70,25 +74,28 @@ SimpleUpdateTracker::SimpleUpdateTracker() { SimpleUpdateTracker::~SimpleUpdateTracker() { } -void SimpleUpdateTracker::add_changed(const Region ®ion) { +void SimpleUpdateTracker::add_changed(const core::Region& region) +{ changed.assign_union(region); } -void SimpleUpdateTracker::add_copied(const Region &dest, const Point &delta) { +void SimpleUpdateTracker::add_copied(const core::Region& dest, + const core::Point& delta) +{ // Is there anything to do? if (dest.is_empty()) return; // Calculate whether any of this copy can be treated as a continuation // of an earlier one - Region src = dest; + core::Region src = dest; src.translate(delta.negate()); - Region overlap = src.intersect(copied); + core::Region overlap = src.intersect(copied); if (overlap.is_empty()) { // There is no overlap - Rect newbr = dest.get_bounding_rect(); - Rect oldbr = copied.get_bounding_rect(); + core::Rect newbr = dest.get_bounding_rect(); + core::Rect oldbr = copied.get_bounding_rect(); if (oldbr.area() > newbr.area()) { // Old copyrect is (probably) bigger - use it changed.assign_union(dest); @@ -97,7 +104,7 @@ void SimpleUpdateTracker::add_copied(const Region &dest, const Point &delta) { // Use the new one // But be careful not to copy stuff that still needs // to be updated. - Region invalid_src = src.intersect(changed); + core::Region invalid_src = src.intersect(changed); invalid_src.translate(delta); changed.assign_union(invalid_src); changed.assign_union(copied); @@ -107,13 +114,13 @@ void SimpleUpdateTracker::add_copied(const Region &dest, const Point &delta) { return; } - Region invalid_src = overlap.intersect(changed); + core::Region invalid_src = overlap.intersect(changed); invalid_src.translate(delta); changed.assign_union(invalid_src); overlap.translate(delta); - Region nonoverlapped_copied = dest.union_(copied).subtract(overlap); + core::Region nonoverlapped_copied = dest.union_(copied).subtract(overlap); changed.assign_union(nonoverlapped_copied); copied = overlap; @@ -122,12 +129,14 @@ void SimpleUpdateTracker::add_copied(const Region &dest, const Point &delta) { return; } -void SimpleUpdateTracker::subtract(const Region& region) { +void SimpleUpdateTracker::subtract(const core::Region& region) +{ copied.assign_subtract(region); changed.assign_subtract(region); } -void SimpleUpdateTracker::getUpdateInfo(UpdateInfo* info, const Region& clip) +void SimpleUpdateTracker::getUpdateInfo(UpdateInfo* info, + const core::Region& clip) { copied.assign_subtract(changed); info->changed = changed.intersect(clip); diff --git a/common/rfb/UpdateTracker.h b/common/rfb/UpdateTracker.h index e91b962147..3d7a2fcdd2 100644 --- a/common/rfb/UpdateTracker.h +++ b/common/rfb/UpdateTracker.h @@ -19,17 +19,16 @@ #ifndef __RFB_UPDATETRACKER_INCLUDED__ #define __RFB_UPDATETRACKER_INCLUDED__ -#include -#include -#include +#include +#include namespace rfb { class UpdateInfo { public: - Region changed; - Region copied; - Point copy_delta; + core::Region changed; + core::Region copied; + core::Point copy_delta; bool is_empty() const { return copied.is_empty() && changed.is_empty(); } @@ -47,23 +46,25 @@ namespace rfb { UpdateTracker() {}; virtual ~UpdateTracker() {}; - virtual void add_changed(const Region ®ion) = 0; - virtual void add_copied(const Region &dest, const Point &delta) = 0; + virtual void add_changed(const core::Region& region) = 0; + virtual void add_copied(const core::Region& dest, + const core::Point& delta) = 0; }; class ClippingUpdateTracker : public UpdateTracker { public: ClippingUpdateTracker() : ut(nullptr) {} - ClippingUpdateTracker(UpdateTracker* ut_, const Rect& r=Rect()) : ut(ut_), clipRect(r) {} + ClippingUpdateTracker(UpdateTracker* ut_, const core::Rect& r={}) : ut(ut_), clipRect(r) {} void setUpdateTracker(UpdateTracker* ut_) {ut = ut_;} - void setClipRect(const Rect& cr) {clipRect = cr;} + void setClipRect(const core::Rect& cr) {clipRect = cr;} - void add_changed(const Region ®ion) override; - void add_copied(const Region &dest, const Point &delta) override; + void add_changed(const core::Region& region) override; + void add_copied(const core::Region& dest, + const core::Point& delta) override; protected: UpdateTracker* ut; - Rect clipRect; + core::Rect clipRect; }; class SimpleUpdateTracker : public UpdateTracker { @@ -71,27 +72,29 @@ namespace rfb { SimpleUpdateTracker(); virtual ~SimpleUpdateTracker(); - void add_changed(const Region ®ion) override; - void add_copied(const Region &dest, const Point &delta) override; - virtual void subtract(const Region& region); + void add_changed(const core::Region& region) override; + void add_copied(const core::Region& dest, + const core::Point& delta) override; + virtual void subtract(const core::Region& region); // Fill the supplied UpdateInfo structure with update information // FIXME: Provide getUpdateInfo() with no clipping, for better efficiency. - virtual void getUpdateInfo(UpdateInfo* info, const Region& cliprgn); + virtual void getUpdateInfo(UpdateInfo* info, + const core::Region& cliprgn); // Copy the contained updates to another tracker virtual void copyTo(UpdateTracker* to) const; // Move the entire update region by an offset - void translate(const Point& p) {changed.translate(p); copied.translate(p);} + void translate(const core::Point& p) {changed.translate(p); copied.translate(p);} virtual bool is_empty() const {return changed.is_empty() && copied.is_empty();} virtual void clear() {changed.clear(); copied.clear();}; protected: - Region changed; - Region copied; - Point copy_delta; + core::Region changed; + core::Region copied; + core::Point copy_delta; }; } diff --git a/common/rfb/VNCSConnectionST.cxx b/common/rfb/VNCSConnectionST.cxx index a354f636cf..ca2ff31b20 100644 --- a/common/rfb/VNCSConnectionST.cxx +++ b/common/rfb/VNCSConnectionST.cxx @@ -22,7 +22,12 @@ #include #endif -#include +#include +#include +#include + +#include +#include #include @@ -31,12 +36,12 @@ #include #include #include -#include #include #include #include #include #include +#include #include #include #include @@ -44,13 +49,12 @@ #define XK_MISCELLANY #define XK_XKB_KEYS #include -#include using namespace rfb; -static LogWriter vlog("VNCSConnST"); +static core::LogWriter vlog("VNCSConnST"); -static Cursor emptyCursor(0, 0, Point(0, 0), nullptr); +static Cursor emptyCursor(0, 0, {0, 0}, nullptr); VNCSConnectionST::VNCSConnectionST(VNCServerST* server_, network::Socket *s, bool reverse, AccessRights ar) @@ -71,9 +75,9 @@ VNCSConnectionST::VNCSConnectionST(VNCServerST* server_, network::Socket *s, if (rfb::Server::idleTimeout) { // minimum of 15 seconds while authenticating if (rfb::Server::idleTimeout < 15) - idleTimer.start(secsToMillis(15)); + idleTimer.start(core::secsToMillis(15)); else - idleTimer.start(secsToMillis(rfb::Server::idleTimeout)); + idleTimer.start(core::secsToMillis(rfb::Server::idleTimeout)); } } @@ -216,11 +220,11 @@ void VNCSConnectionST::pixelBufferChange() //updates.intersect(server->pb->getRect()); // //if (server->pb->width() > client.width()) - // updates.add_changed(Rect(client.width(), 0, server->pb->width(), - // server->pb->height())); + // updates.add_changed({client.width(), 0, server->pb->width(), + // server->pb->height()}); //if (server->pb->height() > client.height()) - // updates.add_changed(Rect(0, client.height(), client.width(), - // server->pb->height())); + // updates.add_changed({0, client.height(), client.width(), + // server->pb->height()}); damagedCursorRegion.assign_intersect(server->getPixelBuffer()->getRect()); @@ -236,7 +240,7 @@ void VNCSConnectionST::pixelBufferChange() } // Drop any lossy tracking that is now outside the framebuffer - encodeManager.pruneLosslessRefresh(Region(server->getPixelBuffer()->getRect())); + encodeManager.pruneLosslessRefresh(server->getPixelBuffer()->getRect()); } // Just update the whole screen at the moment because we're too lazy to // work out what's actually changed. @@ -421,7 +425,7 @@ void VNCSConnectionST::approveConnectionOrClose(bool accept, void VNCSConnectionST::authSuccess() { if (rfb::Server::idleTimeout) - idleTimer.start(secsToMillis(rfb::Server::idleTimeout)); + idleTimer.start(core::secsToMillis(rfb::Server::idleTimeout)); // - Set the connection parameters appropriately client.setDimensions(server->getPixelBuffer()->width(), @@ -448,7 +452,7 @@ void VNCSConnectionST::queryConnection(const char* userName) void VNCSConnectionST::clientInit(bool shared) { if (rfb::Server::idleTimeout) - idleTimer.start(secsToMillis(rfb::Server::idleTimeout)); + idleTimer.start(core::secsToMillis(rfb::Server::idleTimeout)); if (rfb::Server::alwaysShared || reverseConnection) shared = true; if (!accessCheck(AccessNonShared)) shared = true; if (rfb::Server::neverShared) shared = false; @@ -465,10 +469,11 @@ void VNCSConnectionST::setPixelFormat(const PixelFormat& pf) setCursor(); } -void VNCSConnectionST::pointerEvent(const Point& pos, uint16_t buttonMask) +void VNCSConnectionST::pointerEvent(const core::Point& pos, + uint16_t buttonMask) { if (rfb::Server::idleTimeout) - idleTimer.start(secsToMillis(rfb::Server::idleTimeout)); + idleTimer.start(core::secsToMillis(rfb::Server::idleTimeout)); pointerEventTime = time(nullptr); if (!accessCheck(AccessPtrEvents)) return; if (!rfb::Server::acceptPointerEvents) return; @@ -502,7 +507,7 @@ void VNCSConnectionST::keyEvent(uint32_t keysym, uint32_t keycode, bool down) { uint32_t lookup; if (rfb::Server::idleTimeout) - idleTimer.start(secsToMillis(rfb::Server::idleTimeout)); + idleTimer.start(core::secsToMillis(rfb::Server::idleTimeout)); if (!accessCheck(AccessKeyEvents)) return; if (!rfb::Server::acceptKeyEvents) return; @@ -605,27 +610,28 @@ void VNCSConnectionST::keyEvent(uint32_t keysym, uint32_t keycode, bool down) { server->keyEvent(keysym, keycode, down); } -void VNCSConnectionST::framebufferUpdateRequest(const Rect& r,bool incremental) +void VNCSConnectionST::framebufferUpdateRequest(const core::Rect& r, + bool incremental) { - Rect safeRect; + core::Rect safeRect; if (!accessCheck(AccessView)) return; SConnection::framebufferUpdateRequest(r, incremental); // Check that the client isn't sending crappy requests - if (!r.enclosed_by(Rect(0, 0, client.width(), client.height()))) { + if (!r.enclosed_by({0, 0, client.width(), client.height()})) { vlog.error("FramebufferUpdateRequest %dx%d at %d,%d exceeds framebuffer %dx%d", r.width(), r.height(), r.tl.x, r.tl.y, client.width(), client.height()); - safeRect = r.intersect(Rect(0, 0, client.width(), client.height())); + safeRect = r.intersect({0, 0, client.width(), client.height()}); } else { safeRect = r; } // Just update the requested region. // Framebuffer update will be sent a bit later, see processMessages(). - Region reqRgn(safeRect); + core::Region reqRgn(safeRect); if (!incremental || !continuousUpdates) requested.assign_union(reqRgn); @@ -716,7 +722,7 @@ void VNCSConnectionST::fence(uint32_t flags, unsigned len, const uint8_t data[]) void VNCSConnectionST::enableContinuousUpdates(bool enable, int x, int y, int w, int h) { - Rect rect; + core::Rect rect; if (!client.supportsFence() || !client.supportsContinuousUpdates()) throw protocol_error("Client tried to enable continuous updates when not allowed"); @@ -790,7 +796,7 @@ void VNCSConnectionST::supportsLEDState() writer()->writeLEDState(); } -void VNCSConnectionST::handleTimeout(Timer* t) +void VNCSConnectionST::handleTimeout(core::Timer* t) { try { if ((t == &congestionTimer) || @@ -921,7 +927,7 @@ void VNCSConnectionST::writeNoDataUpdate() void VNCSConnectionST::writeDataUpdate() { - Region req; + core::Region req; UpdateInfo ui; bool needNewUpdateInfo; const RenderedCursor *cursor; @@ -946,7 +952,7 @@ void VNCSConnectionST::writeDataUpdate() // destination will be wrong, so add it to the changed region. if (!ui.copied.is_empty() && !damagedCursorRegion.is_empty()) { - Region bogusCopiedCursor; + core::Region bogusCopiedCursor; bogusCopiedCursor = damagedCursorRegion; bogusCopiedCursor.translate(ui.copy_delta); @@ -993,7 +999,7 @@ void VNCSConnectionST::writeDataUpdate() cursor = nullptr; if (needRenderedCursor()) { - Rect renderedCursorRect; + core::Rect renderedCursorRect; cursor = server->getRenderedCursor(); renderedCursorRect = cursor->getEffectiveRect(); @@ -1033,7 +1039,7 @@ void VNCSConnectionST::writeDataUpdate() void VNCSConnectionST::writeLosslessRefresh() { - Region req, pending; + core::Region req, pending; const RenderedCursor *cursor; int nextRefresh, nextUpdate; diff --git a/common/rfb/VNCSConnectionST.h b/common/rfb/VNCSConnectionST.h index 17de9d01e8..b618923fed 100644 --- a/common/rfb/VNCSConnectionST.h +++ b/common/rfb/VNCSConnectionST.h @@ -29,16 +29,17 @@ #include +#include + #include #include #include -#include namespace rfb { class VNCServerST; class VNCSConnectionST : private SConnection, - public Timer::Callback { + public core::Timer::Callback { public: VNCSConnectionST(VNCServerST* server_, network::Socket* s, bool reverse, AccessRights ar); @@ -108,8 +109,8 @@ namespace rfb { // Change tracking - void add_changed(const Region& region) { updates.add_changed(region); } - void add_copied(const Region& dest, const Point& delta) { + void add_changed(const core::Region& region) { updates.add_changed(region); } + void add_copied(const core::Region& dest, const core::Point& delta) { updates.add_copied(dest, delta); } @@ -123,10 +124,11 @@ namespace rfb { void queryConnection(const char* userName) override; void clientInit(bool shared) override; void setPixelFormat(const PixelFormat& pf) override; - void pointerEvent(const Point& pos, uint16_t buttonMask) override; + void pointerEvent(const core::Point& pos, + uint16_t buttonMask) override; void keyEvent(uint32_t keysym, uint32_t keycode, bool down) override; - void framebufferUpdateRequest(const Rect& r, + void framebufferUpdateRequest(const core::Rect& r, bool incremental) override; void setDesktopSize(int fb_width, int fb_height, const ScreenSet& layout) override; @@ -143,7 +145,7 @@ namespace rfb { void supportsLEDState() override; // Timer callbacks - void handleTimeout(Timer* t) override; + void handleTimeout(core::Timer* t) override; // Internal methods @@ -180,24 +182,24 @@ namespace rfb { uint8_t *fenceData; Congestion congestion; - Timer congestionTimer; - Timer losslessTimer; + core::Timer congestionTimer; + core::Timer losslessTimer; VNCServerST* server; SimpleUpdateTracker updates; - Region requested; + core::Region requested; bool updateRenderedCursor, removeRenderedCursor; - Region damagedCursorRegion; + core::Region damagedCursorRegion; bool continuousUpdates; - Region cuRegion; + core::Region cuRegion; EncodeManager encodeManager; std::map pressedKeys; - Timer idleTimer; + core::Timer idleTimer; time_t pointerEventTime; - Point pointerEventPos; + core::Point pointerEventPos; bool clientHasCursor; std::string closeReason; diff --git a/common/rfb/VNCServer.h b/common/rfb/VNCServer.h index 4e3a5b23d1..4d9b31ed75 100644 --- a/common/rfb/VNCServer.h +++ b/common/rfb/VNCServer.h @@ -23,14 +23,19 @@ #ifndef __RFB_VNCSERVER_H__ #define __RFB_VNCSERVER_H__ +#include + +#include #include -#include -#include namespace network { class Socket; } namespace rfb { + class PixelBuffer; + class SConnection; + struct ScreenSet; + class VNCServer : public UpdateTracker { public: // addSocket() tells the server to serve the Socket. The caller @@ -128,13 +133,14 @@ namespace rfb { // setCursor() tells the server that the cursor has changed. The // cursorData argument contains width*height rgba quadruplets with // non-premultiplied alpha. - virtual void setCursor(int width, int height, const Point& hotspot, + virtual void setCursor(int width, int height, + const core::Point& hotspot, const uint8_t* cursorData) = 0; // setCursorPos() tells the server the current position of the cursor, and // whether the server initiated that change (e.g. through another X11 // client calling XWarpPointer()). - virtual void setCursorPos(const Point& p, bool warped) = 0; + virtual void setCursorPos(const core::Point& p, bool warped) = 0; // setName() tells the server what desktop title to supply to clients virtual void setName(const char* name) = 0; diff --git a/common/rfb/VNCServerST.cxx b/common/rfb/VNCServerST.cxx index b99d33b0a2..51bc5103da 100644 --- a/common/rfb/VNCServerST.cxx +++ b/common/rfb/VNCServerST.cxx @@ -55,24 +55,28 @@ #include #include +#include +#include + +#include + #include #include #include #include -#include +#include #include #include #include #include -#include #include using namespace rfb; -static LogWriter slog("VNCServerST"); -static LogWriter connectionsLog("Connections"); +static core::LogWriter slog("VNCServerST"); +static core::LogWriter connectionsLog("Connections"); // // -=- VNCServerST Implementation @@ -85,7 +89,7 @@ VNCServerST::VNCServerST(const char* name_, SDesktop* desktop_) blockCounter(0), pb(nullptr), ledState(ledUnknown), name(name_), pointerClient(nullptr), clipboardClient(nullptr), pointerClientTime(0), - comparer(nullptr), cursor(new Cursor(0, 0, Point(), nullptr)), + comparer(nullptr), cursor(new Cursor(0, 0, {}, nullptr)), renderedCursorInvalid(false), keyRemapper(&KeyRemapper::defInstance), idleTimer(this), disconnectTimer(this), connectTimer(this), @@ -97,9 +101,9 @@ VNCServerST::VNCServerST(const char* name_, SDesktop* desktop_) // FIXME: Do we really want to kick off these right away? if (rfb::Server::maxIdleTime) - idleTimer.start(secsToMillis(rfb::Server::maxIdleTime)); + idleTimer.start(core::secsToMillis(rfb::Server::maxIdleTime)); if (rfb::Server::maxDisconnectionTime) - disconnectTimer.start(secsToMillis(rfb::Server::maxDisconnectionTime)); + disconnectTimer.start(core::secsToMillis(rfb::Server::maxDisconnectionTime)); } VNCServerST::~VNCServerST() @@ -161,7 +165,7 @@ void VNCServerST::addSocket(network::Socket* sock, bool outgoing, AccessRights a // Adjust the exit timers if (rfb::Server::maxConnectionTime && clients.empty()) - connectTimer.start(secsToMillis(rfb::Server::maxConnectionTime)); + connectTimer.start(core::secsToMillis(rfb::Server::maxConnectionTime)); disconnectTimer.stop(); VNCSConnectionST* client = new VNCSConnectionST(this, sock, outgoing, accessRights); @@ -203,7 +207,7 @@ void VNCServerST::removeSocket(network::Socket* sock) { // Adjust the exit timers connectTimer.stop(); if (rfb::Server::maxDisconnectionTime && clients.empty()) - disconnectTimer.start(secsToMillis(rfb::Server::maxDisconnectionTime)); + disconnectTimer.start(core::secsToMillis(rfb::Server::maxDisconnectionTime)); return; } @@ -313,7 +317,7 @@ void VNCServerST::setPixelBuffer(PixelBuffer* pb_) // Check that the screen layout is still valid if (pb_ && !layout.validate(pb_->width(), pb_->height())) { - Rect fbRect; + core::Rect fbRect; ScreenSet::iterator iter, iter_next; fbRect.setXYWH(0, 0, pb_->width(), pb_->height()); @@ -401,7 +405,7 @@ void VNCServerST::setName(const char* name_) (*ci)->setDesktopNameOrClose(name_); } -void VNCServerST::add_changed(const Region& region) +void VNCServerST::add_changed(const core::Region& region) { if (comparer == nullptr) return; @@ -410,7 +414,8 @@ void VNCServerST::add_changed(const Region& region) startFrameClock(); } -void VNCServerST::add_copied(const Region& dest, const Point& delta) +void VNCServerST::add_copied(const core::Region& dest, + const core::Point& delta) { if (comparer == nullptr) return; @@ -419,7 +424,8 @@ void VNCServerST::add_copied(const Region& dest, const Point& delta) startFrameClock(); } -void VNCServerST::setCursor(int width, int height, const Point& newHotspot, +void VNCServerST::setCursor(int width, int height, + const core::Point& newHotspot, const uint8_t* data) { delete cursor; @@ -435,7 +441,7 @@ void VNCServerST::setCursor(int width, int height, const Point& newHotspot, } } -void VNCServerST::setCursorPos(const Point& pos, bool warped) +void VNCServerST::setCursorPos(const core::Point& pos, bool warped) { if (cursorPos != pos) { cursorPos = pos; @@ -467,7 +473,7 @@ void VNCServerST::setLEDState(unsigned int state) void VNCServerST::keyEvent(uint32_t keysym, uint32_t keycode, bool down) { if (rfb::Server::maxIdleTime) - idleTimer.start(secsToMillis(rfb::Server::maxIdleTime)); + idleTimer.start(core::secsToMillis(rfb::Server::maxIdleTime)); // Remap the key if required if (keyRemapper) { @@ -484,11 +490,12 @@ void VNCServerST::keyEvent(uint32_t keysym, uint32_t keycode, bool down) } void VNCServerST::pointerEvent(VNCSConnectionST* client, - const Point& pos, uint16_t buttonMask) + const core::Point& pos, + uint16_t buttonMask) { time_t now = time(nullptr); if (rfb::Server::maxIdleTime) - idleTimer.start(secsToMillis(rfb::Server::maxIdleTime)); + idleTimer.start(core::secsToMillis(rfb::Server::maxIdleTime)); // Let one client own the cursor whilst buttons are pressed in order // to provide a bit more sane user experience. But limit the time to @@ -622,7 +629,7 @@ SConnection* VNCServerST::getConnection(network::Socket* sock) { return nullptr; } -void VNCServerST::handleTimeout(Timer* t) +void VNCServerST::handleTimeout(core::Timer* t) { if (t == &frameTimer) { int timeout; @@ -822,7 +829,7 @@ int VNCServerST::msToNextUpdate() void VNCServerST::writeUpdate() { UpdateInfo ui; - Region toCheck; + core::Region toCheck; std::list::iterator ci; @@ -834,9 +841,9 @@ void VNCServerST::writeUpdate() toCheck = ui.changed.union_(ui.copied); if (needRenderedCursor()) { - Rect clippedCursorRect = Rect(0, 0, cursor->width(), cursor->height()) - .translate(cursorPos.subtract(cursor->hotspot())) - .intersect(pb->getRect()); + core::Rect clippedCursorRect = core::Rect(0, 0, cursor->width(), cursor->height()) + .translate(cursorPos.subtract(cursor->hotspot())) + .intersect(pb->getRect()); if (!toCheck.intersect(clippedCursorRect).is_empty()) renderedCursorInvalid = true; @@ -864,7 +871,7 @@ void VNCServerST::writeUpdate() // checkUpdate() is called by clients to see if it is safe to read from // the framebuffer at this time. -Region VNCServerST::getPendingRegion() +core::Region VNCServerST::getPendingRegion() { UpdateInfo ui; @@ -876,7 +883,7 @@ Region VNCServerST::getPendingRegion() // Block client from updating if there are pending updates if (comparer->is_empty()) - return Region(); + return {}; comparer->getUpdateInfo(&ui, pb->getRect()); diff --git a/common/rfb/VNCServerST.h b/common/rfb/VNCServerST.h index dc4f9aad67..5db4513a5c 100644 --- a/common/rfb/VNCServerST.h +++ b/common/rfb/VNCServerST.h @@ -26,11 +26,11 @@ #include -#include +#include + #include #include #include -#include #include namespace rfb { @@ -40,9 +40,10 @@ namespace rfb { class ListConnInfo; class PixelBuffer; class KeyRemapper; + class SDesktop; class VNCServerST : public VNCServer, - public Timer::Callback { + public core::Timer::Callback { public: // -=- Constructors @@ -95,11 +96,12 @@ namespace rfb { void closeClients(const char* reason) override {closeClients(reason, nullptr);} SConnection* getConnection(network::Socket* sock) override; - void add_changed(const Region ®ion) override; - void add_copied(const Region &dest, const Point &delta) override; - void setCursor(int width, int height, const Point& hotspot, + void add_changed(const core::Region& region) override; + void add_copied(const core::Region& dest, + const core::Point& delta) override; + void setCursor(int width, int height, const core::Point& hotspot, const uint8_t* data) override; - void setCursorPos(const Point& p, bool warped) override; + void setCursorPos(const core::Point& p, bool warped) override; void setName(const char* name_) override; void setLEDState(unsigned state) override; @@ -111,13 +113,14 @@ namespace rfb { const ScreenSet& getScreenLayout() const { return screenLayout; } const Cursor* getCursor() const { return cursor; } - const Point& getCursorPos() const { return cursorPos; } + const core::Point& getCursorPos() const { return cursorPos; } const char* getName() const { return name.c_str(); } unsigned getLEDState() const { return ledState; } // Event handlers void keyEvent(uint32_t keysym, uint32_t keycode, bool down); - void pointerEvent(VNCSConnectionST* client, const Point& pos, uint16_t buttonMask); + void pointerEvent(VNCSConnectionST* client, + const core::Point& pos, uint16_t buttonMask); void handleClipboardRequest(VNCSConnectionST* client); void handleClipboardAnnounce(VNCSConnectionST* client, bool available); @@ -146,7 +149,7 @@ namespace rfb { // Part of the framebuffer that has been modified but is not yet // ready to be sent to clients - Region getPendingRegion(); + core::Region getPendingRegion(); // getRenderedCursor() returns an up to date version of the server // side rendered cursor buffer @@ -155,7 +158,7 @@ namespace rfb { protected: // Timer callbacks - void handleTimeout(Timer* t) override; + void handleTimeout(core::Timer* t) override; // - Internal methods @@ -195,19 +198,19 @@ namespace rfb { ComparingUpdateTracker* comparer; - Point cursorPos; + core::Point cursorPos; Cursor* cursor; RenderedCursor renderedCursor; bool renderedCursorInvalid; KeyRemapper* keyRemapper; - Timer idleTimer; - Timer disconnectTimer; - Timer connectTimer; + core::Timer idleTimer; + core::Timer disconnectTimer; + core::Timer connectTimer; uint64_t msc, queuedMsc; - Timer frameTimer; + core::Timer frameTimer; }; }; diff --git a/common/rfb/ZRLEDecoder.cxx b/common/rfb/ZRLEDecoder.cxx index 633d1c36eb..845bf4dcc1 100644 --- a/common/rfb/ZRLEDecoder.cxx +++ b/common/rfb/ZRLEDecoder.cxx @@ -21,6 +21,8 @@ #include #endif +#include + #include #include #include @@ -75,7 +77,7 @@ ZRLEDecoder::~ZRLEDecoder() { } -bool ZRLEDecoder::readRect(const Rect& /*r*/, rdr::InStream* is, +bool ZRLEDecoder::readRect(const core::Rect& /*r*/, rdr::InStream* is, const ServerParams& /*server*/, rdr::OutStream* os) { @@ -99,7 +101,7 @@ bool ZRLEDecoder::readRect(const Rect& /*r*/, rdr::InStream* is, return true; } -void ZRLEDecoder::decodeRect(const Rect& r, const uint8_t* buffer, +void ZRLEDecoder::decodeRect(const core::Rect& r, const uint8_t* buffer, size_t buflen, const ServerParams& server, ModifiablePixelBuffer* pb) { @@ -113,13 +115,13 @@ void ZRLEDecoder::decodeRect(const Rect& r, const uint8_t* buffer, } template -void ZRLEDecoder::zrleDecode(const Rect& r, rdr::InStream* is, +void ZRLEDecoder::zrleDecode(const core::Rect& r, rdr::InStream* is, const PixelFormat& pf, ModifiablePixelBuffer* pb) { int length = is->readU32(); zis.setUnderlying(is, length); - Rect t; + core::Rect t; T buf[64 * 64]; Pixel maxPixel = pf.pixelFromRGB((uint16_t)-1, (uint16_t)-1, (uint16_t)-1); @@ -134,11 +136,11 @@ void ZRLEDecoder::zrleDecode(const Rect& r, rdr::InStream* is, for (t.tl.y = r.tl.y; t.tl.y < r.br.y; t.tl.y += 64) { - t.br.y = __rfbmin(r.br.y, t.tl.y + 64); + t.br.y = std::min(r.br.y, t.tl.y + 64); for (t.tl.x = r.tl.x; t.tl.x < r.br.x; t.tl.x += 64) { - t.br.x = __rfbmin(r.br.x, t.tl.x + 64); + t.br.x = std::min(r.br.x, t.tl.x + 64); zlibHasData(&zis, 1); int mode = zis.readU8(); diff --git a/common/rfb/ZRLEDecoder.h b/common/rfb/ZRLEDecoder.h index facf0adca8..b9ebf77164 100644 --- a/common/rfb/ZRLEDecoder.h +++ b/common/rfb/ZRLEDecoder.h @@ -30,16 +30,16 @@ namespace rfb { public: ZRLEDecoder(); virtual ~ZRLEDecoder(); - bool readRect(const Rect& r, rdr::InStream* is, + bool readRect(const core::Rect& r, rdr::InStream* is, const ServerParams& server, rdr::OutStream* os) override; - void decodeRect(const Rect& r, const uint8_t* buffer, + void decodeRect(const core::Rect& r, const uint8_t* buffer, size_t buflen, const ServerParams& server, ModifiablePixelBuffer* pb) override; private: template - void zrleDecode(const Rect& r, rdr::InStream* is, + void zrleDecode(const core::Rect& r, rdr::InStream* is, const PixelFormat& pf, ModifiablePixelBuffer* pb); private: diff --git a/common/rfb/ZRLEEncoder.cxx b/common/rfb/ZRLEEncoder.cxx index 1e2c6ef47a..39450ff056 100644 --- a/common/rfb/ZRLEEncoder.cxx +++ b/common/rfb/ZRLEEncoder.cxx @@ -21,20 +21,21 @@ #include #endif +#include +#include + #include -#include #include #include +#include #include #include -#include -#include using namespace rfb; -static LogWriter vlog("ZRLEEncoder"); +static core::LogWriter vlog("ZRLEEncoder"); -IntParameter zlibLevel("ZlibLevel","[DEPRECATED] Zlib compression level",-1); +core::IntParameter zlibLevel("ZlibLevel","[DEPRECATED] Zlib compression level",-1); ZRLEEncoder::ZRLEEncoder(SConnection* conn_) : Encoder(conn_, encodingZRLE, EncoderPlain, 127), @@ -66,7 +67,7 @@ void ZRLEEncoder::setCompressLevel(int level) void ZRLEEncoder::writeRect(const PixelBuffer* pb, const Palette& palette) { int x, y; - Rect tile; + core::Rect tile; rdr::OutStream* os; @@ -132,7 +133,8 @@ void ZRLEEncoder::writeSolidRect(int width, int height, mos.clear(); } -void ZRLEEncoder::writePaletteTile(const Rect& tile, const PixelBuffer* pb, +void ZRLEEncoder::writePaletteTile(const core::Rect& tile, + const PixelBuffer* pb, const Palette& palette) { const uint8_t* buffer; @@ -158,7 +160,8 @@ void ZRLEEncoder::writePaletteTile(const Rect& tile, const PixelBuffer* pb, } } -void ZRLEEncoder::writePaletteRLETile(const Rect& tile, const PixelBuffer* pb, +void ZRLEEncoder::writePaletteRLETile(const core::Rect& tile, + const PixelBuffer* pb, const Palette& palette) { const uint8_t* buffer; @@ -184,7 +187,8 @@ void ZRLEEncoder::writePaletteRLETile(const Rect& tile, const PixelBuffer* pb, } } -void ZRLEEncoder::writeRawTile(const Rect& tile, const PixelBuffer* pb) +void ZRLEEncoder::writeRawTile(const core::Rect& tile, + const PixelBuffer* pb) { const uint8_t* buffer; int stride; diff --git a/common/rfb/ZRLEEncoder.h b/common/rfb/ZRLEEncoder.h index 87d87e94fc..3be81ba3de 100644 --- a/common/rfb/ZRLEEncoder.h +++ b/common/rfb/ZRLEEncoder.h @@ -40,11 +40,13 @@ namespace rfb { const uint8_t* colour) override; protected: - void writePaletteTile(const Rect& tile, const PixelBuffer* pb, + void writePaletteTile(const core::Rect& tile, + const PixelBuffer* pb, const Palette& palette); - void writePaletteRLETile(const Rect& tile, const PixelBuffer* pb, + void writePaletteRLETile(const core::Rect& tile, + const PixelBuffer* pb, const Palette& palette); - void writeRawTile(const Rect& tile, const PixelBuffer* pb); + void writeRawTile(const core::Rect& tile, const PixelBuffer* pb); void writePalette(const PixelFormat& pf, const Palette& palette); diff --git a/tests/perf/CMakeLists.txt b/tests/perf/CMakeLists.txt index 13061b9b7c..38f874d498 100644 --- a/tests/perf/CMakeLists.txt +++ b/tests/perf/CMakeLists.txt @@ -6,10 +6,10 @@ add_executable(convperf convperf.cxx) target_link_libraries(convperf test_util rfb) add_executable(decperf decperf.cxx) -target_link_libraries(decperf test_util rfb) +target_link_libraries(decperf test_util rdr rfb) add_executable(encperf encperf.cxx) -target_link_libraries(encperf test_util rfb) +target_link_libraries(encperf test_util core rdr rfb) if (BUILD_VIEWER) add_executable(fbperf @@ -28,7 +28,7 @@ if (BUILD_VIEWER) endif() target_include_directories(fbperf SYSTEM PUBLIC ${FLTK_INCLUDE_DIR}) target_include_directories(fbperf SYSTEM PUBLIC ${GETTEXT_INCLUDE_DIR}) - target_link_libraries(fbperf test_util rfb ${FLTK_LIBRARIES} ${GETTEXT_LIBRARIES}) + target_link_libraries(fbperf test_util core rfb ${FLTK_LIBRARIES} ${GETTEXT_LIBRARIES}) if(WIN32) target_link_libraries(fbperf msimg32) endif() diff --git a/tests/perf/decperf.cxx b/tests/perf/decperf.cxx index 46f42fa2ef..4d2f151ab4 100644 --- a/tests/perf/decperf.cxx +++ b/tests/perf/decperf.cxx @@ -33,7 +33,6 @@ #include #include -#include #include #include @@ -68,8 +67,8 @@ class CConn : public rfb::CConnection { ~CConn(); void initDone() override; - void setCursor(int, int, const rfb::Point&, const uint8_t*) override; - void setCursorPos(const rfb::Point&) override; + void setCursor(int, int, const core::Point&, const uint8_t*) override; + void setCursorPos(const core::Point&) override; void framebufferUpdateStart() override; void framebufferUpdateEnd() override; void setColourMapEntries(int, int, uint16_t*) override; @@ -141,11 +140,11 @@ void CConn::initDone() server.height())); } -void CConn::setCursor(int, int, const rfb::Point&, const uint8_t*) +void CConn::setCursor(int, int, const core::Point&, const uint8_t*) { } -void CConn::setCursorPos(const rfb::Point&) +void CConn::setCursorPos(const core::Point&) { } diff --git a/tests/perf/encperf.cxx b/tests/perf/encperf.cxx index d761bbed0c..1fc3c6d29a 100644 --- a/tests/perf/encperf.cxx +++ b/tests/perf/encperf.cxx @@ -37,34 +37,32 @@ #include #include -#include +#include + #include #include #include - #include - #include #include #include #include - #include #include #include #include "util.h" -static rfb::IntParameter width("width", "Frame buffer width", 0); -static rfb::IntParameter height("height", "Frame buffer height", 0); -static rfb::IntParameter count("count", "Number of benchmark iterations", 9); +static core::IntParameter width("width", "Frame buffer width", 0); +static core::IntParameter height("height", "Frame buffer height", 0); +static core::IntParameter count("count", "Number of benchmark iterations", 9); -static rfb::StringParameter format("format", "Pixel format (e.g. bgr888)", ""); +static core::StringParameter format("format", "Pixel format (e.g. bgr888)", ""); -static rfb::BoolParameter translate("translate", - "Translate 8-bit and 16-bit datasets into 24-bit", - true); +static core::BoolParameter translate("translate", + "Translate 8-bit and 16-bit datasets into 24-bit", + true); // The frame buffer (and output) is always this format static const rfb::PixelFormat fbPF(32, 24, false, true, 255, 255, 255, 0, 8, 16); @@ -100,11 +98,11 @@ class CConn : public rfb::CConnection { void initDone() override {}; void resizeFramebuffer() override; - void setCursor(int, int, const rfb::Point&, const uint8_t*) override; - void setCursorPos(const rfb::Point&) override; + void setCursor(int, int, const core::Point&, const uint8_t*) override; + void setCursorPos(const core::Point&) override; void framebufferUpdateStart() override; void framebufferUpdateEnd() override; - bool dataRect(const rfb::Rect&, int) override; + bool dataRect(const core::Rect&, int) override; void setColourMapEntries(int, int, uint16_t*) override; void bell() override; void serverCutText(const char*) override; @@ -221,11 +219,11 @@ void CConn::resizeFramebuffer() setFramebuffer(pb); } -void CConn::setCursor(int, int, const rfb::Point&, const uint8_t*) +void CConn::setCursor(int, int, const core::Point&, const uint8_t*) { } -void CConn::setCursorPos(const rfb::Point&) +void CConn::setCursorPos(const core::Point&) { } @@ -241,7 +239,7 @@ void CConn::framebufferUpdateEnd() { rfb::UpdateInfo ui; rfb::PixelBuffer* pb = getFramebuffer(); - rfb::Region clip(pb->getRect()); + core::Region clip(pb->getRect()); CConnection::framebufferUpdateEnd(); @@ -258,13 +256,13 @@ void CConn::framebufferUpdateEnd() encodeTime += getCpuCounter(); } -bool CConn::dataRect(const rfb::Rect &r, int encoding) +bool CConn::dataRect(const core::Rect& r, int encoding) { if (!CConnection::dataRect(r, encoding)) return false; if (encoding != rfb::encodingCopyRect) // FIXME - updates.add_changed(rfb::Region(r)); + updates.add_changed(r); return true; } @@ -421,7 +419,7 @@ static void usage(const char *argv0) { fprintf(stderr, "Syntax: %s [options] \n", argv0); fprintf(stderr, "Options:\n"); - rfb::Configuration::listParams(79, 14); + core::Configuration::listParams(79, 14); exit(1); } @@ -433,12 +431,12 @@ int main(int argc, char **argv) fn = nullptr; for (i = 1; i < argc; i++) { - if (rfb::Configuration::setParam(argv[i])) + if (core::Configuration::setParam(argv[i])) continue; if (argv[i][0] == '-') { if (i + 1 < argc) { - if (rfb::Configuration::setParam(&argv[i][1], argv[i + 1])) { + if (core::Configuration::setParam(&argv[i][1], argv[i + 1])) { i++; continue; } diff --git a/tests/perf/fbperf.cxx b/tests/perf/fbperf.cxx index e4d0febf96..1a5b5ba713 100644 --- a/tests/perf/fbperf.cxx +++ b/tests/perf/fbperf.cxx @@ -28,8 +28,8 @@ #include #include -#include -#include +#include +#include #include "../vncviewer/PlatformPixelBuffer.h" @@ -155,7 +155,7 @@ void TestWindow::flush() void TestWindow::update() { - rfb::Rect r; + core::Rect r; startTimeCounter(); @@ -194,7 +194,7 @@ void TestWindow::timer(void* data) void PartialTestWindow::changefb() { - rfb::Rect r; + core::Rect r; uint32_t pixel; r = fb->getRect(); @@ -300,7 +300,7 @@ static void dosubtest(TestWindow* win, int width, int height, win->start(width, height); gettimeofday(&start, nullptr); - while (rfb::msSince(&start) < 3000) + while (core::msSince(&start) < 3000) Fl::wait(); win->stop(); @@ -370,7 +370,7 @@ static void dotest(TestWindow* win) fprintf(stderr, "Rendering delay: %g ms/frame\n", delay * 1000.0); fprintf(stderr, "Rendering rate: %s\n", (rate == 0.0) ? "N/A pixels/s" : - rfb::siPrefix(1.0 / rate, "pixels/s").c_str()); + core::siPrefix(1.0 / rate, "pixels/s").c_str()); fprintf(stderr, "Maximum FPS: %g fps @ 1920x1080\n", 1.0 / (delay + rate * 1920 * 1080)); } diff --git a/tests/unit/CMakeLists.txt b/tests/unit/CMakeLists.txt index 8e22305285..3a267a10e3 100644 --- a/tests/unit/CMakeLists.txt +++ b/tests/unit/CMakeLists.txt @@ -5,20 +5,20 @@ add_executable(conv conv.cxx) target_link_libraries(conv rfb) add_executable(convertlf convertlf.cxx) -target_link_libraries(convertlf rfb) +target_link_libraries(convertlf core) add_executable(gesturehandler gesturehandler.cxx ../../vncviewer/GestureHandler.cxx) -target_link_libraries(gesturehandler rfb) +target_link_libraries(gesturehandler core) add_executable(hostport hostport.cxx) -target_link_libraries(hostport rfb) +target_link_libraries(hostport network) add_executable(pixelformat pixelformat.cxx) target_link_libraries(pixelformat rfb) add_executable(unicode unicode.cxx) -target_link_libraries(unicode rfb) +target_link_libraries(unicode core) add_executable(emulatemb emulatemb.cxx ../../vncviewer/EmulateMB.cxx) target_include_directories(emulatemb SYSTEM PUBLIC ${GETTEXT_INCLUDE_DIR}) -target_link_libraries(emulatemb rfb ${GETTEXT_LIBRARIES}) +target_link_libraries(emulatemb core ${GETTEXT_LIBRARIES}) diff --git a/tests/unit/convertlf.cxx b/tests/unit/convertlf.cxx index 1645532a15..75179f034a 100644 --- a/tests/unit/convertlf.cxx +++ b/tests/unit/convertlf.cxx @@ -22,7 +22,7 @@ #include -#include +#include static const char* escape(const char* input) { @@ -54,7 +54,7 @@ static void testLF(const char* input, const char* expected) printf("convertLF(\"%s\"): ", escape(input)); - output = rfb::convertLF(input); + output = core::convertLF(input); if (output != expected) printf("FAILED: got \"%s\"", escape(output.c_str())); @@ -70,7 +70,7 @@ static void testCRLF(const char* input, const char* expected) printf("convertCRLF(\"%s\"): ", escape(input)); - output = rfb::convertCRLF(input); + output = core::convertCRLF(input); if (output != expected) printf("FAILED: got \"%s\"", escape(output.c_str())); diff --git a/tests/unit/emulatemb.cxx b/tests/unit/emulatemb.cxx index 6db8ea380a..ac4c8a32e3 100644 --- a/tests/unit/emulatemb.cxx +++ b/tests/unit/emulatemb.cxx @@ -24,8 +24,9 @@ #include #include -#include -#include +#include +#include + #include "EmulateMB.h" // The button masks for the mouse buttons @@ -37,19 +38,19 @@ static const int right = 0x04; static const int both = 0x05; static const int middleAndRight = 0x06; -rfb::BoolParameter emulateMiddleButton("dummy_name", "dummy_desc", true); +core::BoolParameter emulateMiddleButton("dummy_name", "dummy_desc", true); class TestClass : public EmulateMB { public: - void sendPointerEvent(const rfb::Point& pos, uint16_t buttonMask) override; + void sendPointerEvent(const core::Point& pos, uint16_t buttonMask) override; - struct PointerEventParams {rfb::Point pos; uint16_t mask; }; + struct PointerEventParams {core::Point pos; uint16_t mask; }; std::vector results; }; -void TestClass::sendPointerEvent(const rfb::Point& pos, uint16_t buttonMask) +void TestClass::sendPointerEvent(const core::Point& pos, uint16_t buttonMask) { PointerEventParams params; params.pos = pos; @@ -69,7 +70,7 @@ void testDisabledOption() printf("%s: ", __func__); emulateMiddleButton.setParam(false); - test.filterPointerEvent(rfb::Point(0, 10), left); + test.filterPointerEvent({0, 10}, left); ASSERT_EQ(test.results.size(), 1); @@ -87,8 +88,8 @@ void testLeftClick() printf("%s: ", __func__); emulateMiddleButton.setParam(true); - test.filterPointerEvent(rfb::Point(0, 0), left); - test.filterPointerEvent(rfb::Point(0, 0), empty); + test.filterPointerEvent({0, 0}, left); + test.filterPointerEvent({0, 0}, empty); ASSERT_EQ(test.results.size(), 3); @@ -114,9 +115,9 @@ void testNormalLeftPress() printf("%s: ", __func__); emulateMiddleButton.setParam(true); - test.filterPointerEvent(rfb::Point(10, 20), left); + test.filterPointerEvent({10, 20}, left); usleep(100000); // 0.1s - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); ASSERT_EQ(test.results.size(), 2); @@ -138,7 +139,7 @@ void testNormalMiddlePress() printf("%s: ", __func__); emulateMiddleButton.setParam(true); - test.filterPointerEvent(rfb::Point(0, 0), middle); + test.filterPointerEvent({0, 0}, middle); ASSERT_EQ(test.results.size(), 1); @@ -156,9 +157,9 @@ void testNormalRightPress() printf("%s: ", __func__); emulateMiddleButton.setParam(true); - test.filterPointerEvent(rfb::Point(0, 0), right); + test.filterPointerEvent({0, 0}, right); usleep(100000); // 0.1s - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); ASSERT_EQ(test.results.size(), 2); @@ -180,8 +181,8 @@ void testEmulateMiddleMouseButton() printf("%s: ", __func__); emulateMiddleButton.setParam(true); - test.filterPointerEvent(rfb::Point(20, 30), right); - test.filterPointerEvent(rfb::Point(20, 30), both); + test.filterPointerEvent({20, 30}, right); + test.filterPointerEvent({20, 30}, both); ASSERT_EQ(test.results.size(), 2); @@ -203,9 +204,9 @@ void testLeftReleaseAfterEmulate() printf("%s: ", __func__); emulateMiddleButton.setParam(true); - test.filterPointerEvent(rfb::Point(20, 30), left); - test.filterPointerEvent(rfb::Point(20, 30), both); - test.filterPointerEvent(rfb::Point(20, 30), right); // left released + test.filterPointerEvent({20, 30}, left); + test.filterPointerEvent({20, 30}, both); + test.filterPointerEvent({20, 30}, right); // left released ASSERT_EQ(test.results.size(), 3); @@ -231,9 +232,9 @@ void testRightReleaseAfterEmulate() printf("%s: ", __func__); emulateMiddleButton.setParam(true); - test.filterPointerEvent(rfb::Point(20, 30), right); - test.filterPointerEvent(rfb::Point(20, 30), both); - test.filterPointerEvent(rfb::Point(20, 30), left); // right released + test.filterPointerEvent({20, 30}, right); + test.filterPointerEvent({20, 30}, both); + test.filterPointerEvent({20, 30}, left); // right released ASSERT_EQ(test.results.size(), 3); @@ -259,10 +260,10 @@ void testLeftRepressAfterEmulate() printf("%s: ", __func__); emulateMiddleButton.setParam(true); - test.filterPointerEvent(rfb::Point(20, 30), left); - test.filterPointerEvent(rfb::Point(20, 30), both); - test.filterPointerEvent(rfb::Point(20, 30), right); // left released - test.filterPointerEvent(rfb::Point(20, 30), both); + test.filterPointerEvent({20, 30}, left); + test.filterPointerEvent({20, 30}, both); + test.filterPointerEvent({20, 30}, right); // left released + test.filterPointerEvent({20, 30}, both); ASSERT_EQ(test.results.size(), 4); @@ -292,10 +293,10 @@ void testRightRepressAfterEmulate() printf("%s: ", __func__); emulateMiddleButton.setParam(true); - test.filterPointerEvent(rfb::Point(20, 30), right); - test.filterPointerEvent(rfb::Point(20, 30), both); - test.filterPointerEvent(rfb::Point(20, 30), left); // right released - test.filterPointerEvent(rfb::Point(20, 30), both); + test.filterPointerEvent({20, 30}, right); + test.filterPointerEvent({20, 30}, both); + test.filterPointerEvent({20, 30}, left); // right released + test.filterPointerEvent({20, 30}, both); ASSERT_EQ(test.results.size(), 4); @@ -325,10 +326,10 @@ void testBothPressAfterLeftTimeout() printf("%s: ", __func__); emulateMiddleButton.setParam(true); - test.filterPointerEvent(rfb::Point(10, 20), left); + test.filterPointerEvent({10, 20}, left); usleep(100000); // 0.1s - rfb::Timer::checkTimeouts(); - test.filterPointerEvent(rfb::Point(10, 20), both); + core::Timer::checkTimeouts(); + test.filterPointerEvent({10, 20}, both); ASSERT_EQ(test.results.size(), 3); @@ -354,10 +355,10 @@ void testBothPressAfterRightTimeout() printf("%s: ", __func__); emulateMiddleButton.setParam(true); - test.filterPointerEvent(rfb::Point(10, 20), right); + test.filterPointerEvent({10, 20}, right); usleep(100000); // 0.1s - rfb::Timer::checkTimeouts(); - test.filterPointerEvent(rfb::Point(10, 20), both); + core::Timer::checkTimeouts(); + test.filterPointerEvent({10, 20}, both); ASSERT_EQ(test.results.size(), 3); @@ -383,10 +384,10 @@ void testTimeoutAndDrag() printf("%s: ", __func__); emulateMiddleButton.setParam(true); - test.filterPointerEvent(rfb::Point(0, 0), left); + test.filterPointerEvent({0, 0}, left); usleep(100000); //0.1s - rfb::Timer::checkTimeouts(); - test.filterPointerEvent(rfb::Point(10, 10), left); + core::Timer::checkTimeouts(); + test.filterPointerEvent({10, 10}, left); ASSERT_EQ(test.results.size(), 3); @@ -412,10 +413,10 @@ void testDragAndTimeout() printf("%s: ", __func__); emulateMiddleButton.setParam(true); - test.filterPointerEvent(rfb::Point(10, 10), left); - test.filterPointerEvent(rfb::Point(30, 30), left); + test.filterPointerEvent({10, 10}, left); + test.filterPointerEvent({30, 30}, left); usleep(100000); //0.1s - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); ASSERT_EQ(test.results.size(), 3); @@ -441,8 +442,8 @@ void testDragAndRelease() printf("%s: ", __func__); emulateMiddleButton.setParam(true); - test.filterPointerEvent(rfb::Point(10, 10), left); - test.filterPointerEvent(rfb::Point(20, 20), empty); + test.filterPointerEvent({10, 10}, left); + test.filterPointerEvent({20, 20}, empty); ASSERT_EQ(test.results.size(), 3); diff --git a/tests/unit/gesturehandler.cxx b/tests/unit/gesturehandler.cxx index 73b8c62cf6..f4b5f92e20 100644 --- a/tests/unit/gesturehandler.cxx +++ b/tests/unit/gesturehandler.cxx @@ -115,7 +115,7 @@ void testTwoTapSlowBegin() test.handleTouchBegin(1, 20.0, 30.0); usleep(500000); - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); test.handleTouchBegin(2, 30.0, 50.0); test.handleTouchEnd(1); @@ -137,7 +137,7 @@ void testTwoTapSlowEnd() test.handleTouchEnd(1); usleep(500000); - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); test.handleTouchEnd(2); @@ -156,7 +156,7 @@ void testTwoTapTimeout() test.handleTouchBegin(2, 30.0, 50.0); usleep(1500000); - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); test.handleTouchEnd(1); test.handleTouchEnd(2); @@ -213,7 +213,7 @@ void testThreeTapSlowBegin() test.handleTouchBegin(2, 30.0, 50.0); usleep(500000); - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); test.handleTouchBegin(3, 40.0, 40.0); test.handleTouchEnd(1); @@ -238,7 +238,7 @@ void testThreeTapSlowEnd() test.handleTouchEnd(2); usleep(500000); - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); test.handleTouchEnd(3); @@ -281,7 +281,7 @@ void testThreeTapTimeout() test.handleTouchBegin(3, 40.0, 40.0); usleep(1500000); - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); test.handleTouchEnd(1); test.handleTouchEnd(2); @@ -429,7 +429,7 @@ void testLongPressNormal() ASSERT_EQ(test.events.size(), 0); usleep(1500000); - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); ASSERT_EQ(test.events.size(), 1); @@ -463,7 +463,7 @@ void testLongPressDrag() ASSERT_EQ(test.events.size(), 0); usleep(1500000); - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); ASSERT_EQ(test.events.size(), 1); @@ -673,7 +673,7 @@ void testTwoDragFastAlmost() ASSERT_EQ(test.events.size(), 0); usleep(500000); - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); ASSERT_EQ(test.events.size(), 0); @@ -694,7 +694,7 @@ void testTwoDragSlowHoriz() ASSERT_EQ(test.events.size(), 0); usleep(60000); // 60ms - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); ASSERT_EQ(test.events.size(), 2); ASSERT_EQ(test.events[0].type, GestureBegin); @@ -728,7 +728,7 @@ void testTwoDragSlowVert() ASSERT_EQ(test.events.size(), 0); usleep(60000); // 60ms - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); ASSERT_EQ(test.events.size(), 2); ASSERT_EQ(test.events[0].type, GestureBegin); @@ -762,7 +762,7 @@ void testTwoDragSlowDiag() ASSERT_EQ(test.events.size(), 0); usleep(60000); // 60ms - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); ASSERT_EQ(test.events.size(), 2); ASSERT_EQ(test.events[0].type, GestureBegin); @@ -791,7 +791,7 @@ void testTwoDragTooSlow() test.handleTouchBegin(1, 20.0, 30.0); usleep(500000); - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); test.handleTouchBegin(2, 30.0, 30.0); test.handleTouchUpdate(2, 50.0, 30.0); @@ -917,7 +917,7 @@ void testPinchFastAlmost() ASSERT_EQ(test.events.size(), 0); usleep(500000); - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); ASSERT_EQ(test.events.size(), 0); @@ -941,7 +941,7 @@ void testPinchSlowIn() ASSERT_EQ(test.events.size(), 0); usleep(60000); // 60ms - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); ASSERT_EQ(test.events.size(), 2); @@ -978,7 +978,7 @@ void testPinchSlowOut() ASSERT_EQ(test.events.size(), 0); usleep(60000); // 60ms - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); ASSERT_EQ(test.events.size(), 2); @@ -1008,7 +1008,7 @@ void testPinchTooSlow() test.handleTouchBegin(1, 0.0, 0.0); usleep(60000); // 60ms - rfb::Timer::checkTimeouts(); + core::Timer::checkTimeouts(); test.handleTouchBegin(2, 130.0, 130.0); test.handleTouchUpdate(2, 100.0, 130.0); diff --git a/tests/unit/hostport.cxx b/tests/unit/hostport.cxx index d82c3d5194..615fd2081b 100644 --- a/tests/unit/hostport.cxx +++ b/tests/unit/hostport.cxx @@ -22,7 +22,7 @@ #include -#include +#include static void doTest(const char* hostAndPort, const char* expectedHost, int expectedPort) @@ -32,7 +32,7 @@ static void doTest(const char* hostAndPort, printf("\"%s\": ", hostAndPort); - rfb::getHostAndPort(hostAndPort, &host, &port); + network::getHostAndPort(hostAndPort, &host, &port); if (host != expectedHost) printf("FAILED (\"%s\" != \"%s\")", host.c_str(), expectedHost); diff --git a/tests/unit/unicode.cxx b/tests/unit/unicode.cxx index 7181504214..40c38ead7e 100644 --- a/tests/unit/unicode.cxx +++ b/tests/unit/unicode.cxx @@ -24,7 +24,7 @@ #include #include -#include +#include struct _ucs4utf8 { unsigned ucs4; @@ -131,7 +131,7 @@ int main(int /*argc*/, char** /*argv*/) if (ucs4utf8[i].ucs4 == 0xfffd) continue; - len = rfb::ucs4ToUTF8(ucs4utf8[i].ucs4, utf8); + len = core::ucs4ToUTF8(ucs4utf8[i].ucs4, utf8); if ((len != strlen(utf8)) || (strcmp(utf8, ucs4utf8[i].utf8) != 0)) { printf("FAILED: ucs4ToUTF8() #%d\n", (int)i+1); @@ -144,7 +144,7 @@ int main(int /*argc*/, char** /*argv*/) if (strcmp(ucs4utf8[i].utf8, "\xef\xbf\xbd") == 0) continue; - len = rfb::utf8ToUCS4(ucs4utf8[i].utf8, strlen(ucs4utf8[i].utf8), &ucs4); + len = core::utf8ToUCS4(ucs4utf8[i].utf8, strlen(ucs4utf8[i].utf8), &ucs4); if ((len != strlen(ucs4utf8[i].utf8)) || (ucs4 != ucs4utf8[i].ucs4)) { printf("FAILED: utf8ToUCS4() #%d\n", (int)i+1); @@ -157,7 +157,7 @@ int main(int /*argc*/, char** /*argv*/) if (ucs4utf16[i].ucs4 == 0xfffd) continue; - len = rfb::ucs4ToUTF16(ucs4utf16[i].ucs4, utf16); + len = core::ucs4ToUTF16(ucs4utf16[i].ucs4, utf16); if ((len != wcslen(utf16)) || (wcscmp(utf16, ucs4utf16[i].utf16) != 0)) { printf("FAILED: ucs4ToUTF16() #%d\n", (int)i+1); @@ -170,7 +170,7 @@ int main(int /*argc*/, char** /*argv*/) if (wcscmp(ucs4utf16[i].utf16, L"\xfffd") == 0) continue; - len = rfb::utf16ToUCS4(ucs4utf16[i].utf16, wcslen(ucs4utf16[i].utf16), &ucs4); + len = core::utf16ToUCS4(ucs4utf16[i].utf16, wcslen(ucs4utf16[i].utf16), &ucs4); if ((len != wcslen(ucs4utf16[i].utf16)) || (ucs4 != ucs4utf16[i].ucs4)) { printf("FAILED: utf16ToUCS4() #%d\n", (int)i+1); @@ -183,7 +183,7 @@ int main(int /*argc*/, char** /*argv*/) if (strchr(latin1utf8[i].latin1, '?') != nullptr) continue; - out = rfb::latin1ToUTF8(latin1utf8[i].latin1); + out = core::latin1ToUTF8(latin1utf8[i].latin1); if (out != latin1utf8[i].utf8) { printf("FAILED: latin1ToUTF8() #%d\n", (int)i+1); failures++; @@ -191,7 +191,7 @@ int main(int /*argc*/, char** /*argv*/) } for (i = 0;i < ARRAY_SIZE(latin1utf8);i++) { - out = rfb::utf8ToLatin1(latin1utf8[i].utf8); + out = core::utf8ToLatin1(latin1utf8[i].utf8); if (out != latin1utf8[i].latin1) { printf("FAILED: utf8ToLatin1() #%d\n", (int)i+1); failures++; @@ -203,7 +203,7 @@ int main(int /*argc*/, char** /*argv*/) if (wcscmp(utf8utf16[i].utf16, L"\xfffd") == 0) continue; - out = rfb::utf16ToUTF8(utf8utf16[i].utf16); + out = core::utf16ToUTF8(utf8utf16[i].utf16); if (out != utf8utf16[i].utf8) { printf("FAILED: utf16ToUTF8() #%d\n", (int)i+1); failures++; @@ -215,7 +215,7 @@ int main(int /*argc*/, char** /*argv*/) if (strstr(utf8utf16[i].utf8, "\xef\xbf\xbd") != nullptr) continue; - wout = rfb::utf8ToUTF16(utf8utf16[i].utf8); + wout = core::utf8ToUTF16(utf8utf16[i].utf8); if (wout != utf8utf16[i].utf16) { printf("FAILED: utf8ToUTF16() #%d\n", (int)i+1); failures++; @@ -223,28 +223,28 @@ int main(int /*argc*/, char** /*argv*/) } for (i = 0;i < ARRAY_SIZE(validutf8);i++) { - if (!rfb::isValidUTF8(validutf8[i])) { + if (!core::isValidUTF8(validutf8[i])) { printf("FAILED: isValidUTF8() #%d\n", (int)i+1); failures++; } } for (i = 0;i < ARRAY_SIZE(invalidutf8);i++) { - if (rfb::isValidUTF8(invalidutf8[i])) { + if (core::isValidUTF8(invalidutf8[i])) { printf("FAILED: ! isValidUTF8() #%d\n", (int)i+1); failures++; } } for (i = 0;i < ARRAY_SIZE(validutf16);i++) { - if (!rfb::isValidUTF16(validutf16[i])) { + if (!core::isValidUTF16(validutf16[i])) { printf("FAILED: isValidUTF16() #%d\n", (int)i+1); failures++; } } for (i = 0;i < ARRAY_SIZE(invalidutf16);i++) { - if (rfb::isValidUTF16(invalidutf16[i])) { + if (core::isValidUTF16(invalidutf16[i])) { printf("FAILED: ! isValidUTF16() #%d\n", (int)i+1); failures++; } diff --git a/unix/common/CMakeLists.txt b/unix/common/CMakeLists.txt index 87e2ae7985..72662fdb77 100644 --- a/unix/common/CMakeLists.txt +++ b/unix/common/CMakeLists.txt @@ -3,6 +3,7 @@ add_library(unixcommon STATIC target_include_directories(unixcommon PUBLIC ${CMAKE_SOURCE_DIR}/common) target_include_directories(unixcommon PUBLIC ${CMAKE_SOURCE_DIR}/unix/common) +target_link_libraries(unixcommon core rfb) if(UNIX) libtool_create_control_file(unixcommon) diff --git a/unix/common/randr.cxx b/unix/common/randr.cxx index e4e2d7bed0..7f38f3c062 100644 --- a/unix/common/randr.cxx +++ b/unix/common/randr.cxx @@ -26,10 +26,15 @@ #include #include + +#include + #include -#include +#include + #include -static rfb::LogWriter vlog("RandR"); + +static core::LogWriter vlog("RandR"); static int ResizeScreen(bool dryrun, int fb_width, int fb_height, std::set* disabledOutputs) diff --git a/unix/common/unixcommon.h b/unix/common/unixcommon.h index d04c3ae98c..1f6cd8eb46 100644 --- a/unix/common/unixcommon.h +++ b/unix/common/unixcommon.h @@ -20,9 +20,12 @@ #ifndef UNIXCOMMON_H #define UNIXCOMMON_H +#include + #include +#include -#include +namespace rfb { struct ScreenSet; } typedef std::map OutputIdMap; diff --git a/unix/tx/CMakeLists.txt b/unix/tx/CMakeLists.txt index e28621a605..4967f1bcf2 100644 --- a/unix/tx/CMakeLists.txt +++ b/unix/tx/CMakeLists.txt @@ -6,4 +6,4 @@ target_include_directories(tx SYSTEM PUBLIC ${X11_INCLUDE_DIR}) target_include_directories(tx PUBLIC ${CMAKE_SOURCE_DIR}/common) target_include_directories(tx PUBLIC ${CMAKE_SOURCE_DIR}/common/rfb) -target_link_libraries(tx ${X11_LIBRARIES}) +target_link_libraries(tx core ${X11_LIBRARIES}) diff --git a/unix/tx/TXButton.h b/unix/tx/TXButton.h index 889648333d..f94561e309 100644 --- a/unix/tx/TXButton.h +++ b/unix/tx/TXButton.h @@ -26,8 +26,9 @@ #ifndef __TXBUTTON_H__ #define __TXBUTTON_H__ +#include + #include "TXWindow.h" -#include // TXButtonCallback's buttonActivate() method is called when a button is // activated. @@ -63,8 +64,8 @@ class TXButton : public TXWindow, public TXEventHandler { text = text_; int textWidth = XTextWidth(defaultFS, text.data(), text.size()); int textHeight = (defaultFS->ascent + defaultFS->descent); - int newWidth = __rfbmax(width(), textWidth + xPad*2 + bevel*2); - int newHeight = __rfbmax(height(), textHeight + yPad*2 + bevel*2); + int newWidth = std::max(width(), textWidth + xPad*2 + bevel*2); + int newHeight = std::max(height(), textHeight + yPad*2 + bevel*2); if (width() < newWidth || height() < newHeight) { resize(newWidth, newHeight); } diff --git a/unix/tx/TXCheckbox.h b/unix/tx/TXCheckbox.h index 179e3e848a..64d560747d 100644 --- a/unix/tx/TXCheckbox.h +++ b/unix/tx/TXCheckbox.h @@ -33,8 +33,9 @@ #ifndef __TXCHECKBOX_H__ #define __TXCHECKBOX_H__ +#include + #include "TXWindow.h" -#include // TXCheckboxCallback's checkboxSelect() method is called when the state of a // checkbox changes. @@ -72,8 +73,8 @@ class TXCheckbox : public TXWindow, public TXEventHandler { text = strdup((char*)text_); int textWidth = XTextWidth(defaultFS, text, strlen(text)); int textHeight = (defaultFS->ascent + defaultFS->descent); - int newWidth = __rfbmax(width(), textWidth + xPad*2 + boxPad*2 + boxSize); - int newHeight = __rfbmax(height(), textHeight + yPad*2); + int newWidth = std::max(width(), textWidth + xPad*2 + boxPad*2 + boxSize); + int newHeight = std::max(height(), textHeight + yPad*2); if (width() < newWidth || height() < newHeight) { resize(newWidth, newHeight); } diff --git a/unix/tx/TXDialog.h b/unix/tx/TXDialog.h index 6533377f6b..a04f07425f 100644 --- a/unix/tx/TXDialog.h +++ b/unix/tx/TXDialog.h @@ -28,7 +28,7 @@ #ifndef __TXDIALOG_H__ #define __TXDIALOG_H__ -#include +#include #include "TXWindow.h" #include @@ -65,7 +65,7 @@ class TXDialog : public TXWindow, public TXDeleteWindowCallback { FD_ZERO(&rfds); FD_SET(ConnectionNumber(dpy), &rfds); int n = select(FD_SETSIZE, &rfds, nullptr, nullptr, nullptr); - if (n < 0) throw rdr::socket_error("select", errno); + if (n < 0) throw core::socket_error("select", errno); } } return true; diff --git a/unix/tx/TXLabel.h b/unix/tx/TXLabel.h index 1e0cc0e51d..3d8245d24b 100644 --- a/unix/tx/TXLabel.h +++ b/unix/tx/TXLabel.h @@ -27,8 +27,11 @@ #define __TXLABEL_H__ #include + +#include + #include "TXWindow.h" -#include +#include class TXLabel : public TXWindow, public TXEventHandler { public: @@ -63,8 +66,8 @@ class TXLabel : public TXWindow, public TXEventHandler { } while (i < text.size()); int textHeight = ((defaultFS->ascent + defaultFS->descent + lineSpacing) * lines); - int newWidth = __rfbmax(width(), textWidth + xPad*2); - int newHeight = __rfbmax(height(), textHeight + yPad*2); + int newWidth = std::max(width(), textWidth + xPad*2); + int newHeight = std::max(height(), textHeight + yPad*2); if (width() < newWidth || height() < newHeight) { resize(newWidth, newHeight); } diff --git a/unix/vncconfig/CMakeLists.txt b/unix/vncconfig/CMakeLists.txt index 0589f161c3..4882dc7162 100644 --- a/unix/vncconfig/CMakeLists.txt +++ b/unix/vncconfig/CMakeLists.txt @@ -9,7 +9,7 @@ target_include_directories(vncconfig SYSTEM PUBLIC ${X11_INCLUDE_DIR}) target_include_directories(vncconfig PUBLIC ${CMAKE_SOURCE_DIR}/common) target_include_directories(vncconfig PUBLIC ${CMAKE_SOURCE_DIR}/unix/tx) -target_link_libraries(vncconfig tx rfb network rdr ${X11_LIBRARIES}) +target_link_libraries(vncconfig core tx rfb ${X11_LIBRARIES}) install(TARGETS vncconfig DESTINATION ${CMAKE_INSTALL_FULL_BINDIR}) install(FILES vncconfig.man DESTINATION ${CMAKE_INSTALL_FULL_MANDIR}/man1 RENAME vncconfig.1) diff --git a/unix/vncconfig/QueryConnectDialog.cxx b/unix/vncconfig/QueryConnectDialog.cxx index a265356f30..1d495ea5b5 100644 --- a/unix/vncconfig/QueryConnectDialog.cxx +++ b/unix/vncconfig/QueryConnectDialog.cxx @@ -21,7 +21,9 @@ #endif #include -#include + +#include + #include "QueryConnectDialog.h" #include "vncExt.h" @@ -43,7 +45,7 @@ QueryConnectDialog::QueryConnectDialog(Display* dpy_, { const int pad = 4; int y=pad; - int lblWidth = __rfbmax(addressLbl.width(), userLbl.width()); + int lblWidth = std::max(addressLbl.width(), userLbl.width()); userLbl.move(pad+lblWidth-userLbl.width(), y); user.move(pad+lblWidth, y); addressLbl.move(pad+lblWidth-addressLbl.width(), y+=userLbl.height()); @@ -51,9 +53,9 @@ QueryConnectDialog::QueryConnectDialog(Display* dpy_, timeoutLbl.move(pad, y+=addressLbl.height()); timeout.move(pad+timeoutLbl.width(), y); accept.move(pad, y+=addressLbl.height()); - int maxWidth = __rfbmax(user.width(), address.width()+pad+lblWidth); - maxWidth = __rfbmax(maxWidth, accept.width()*3); - maxWidth = __rfbmax(maxWidth, timeoutLbl.width()+timeout.width()+pad); + int maxWidth = std::max(user.width(), address.width()+pad+lblWidth); + maxWidth = std::max(maxWidth, accept.width()*3); + maxWidth = std::max(maxWidth, timeoutLbl.width()+timeout.width()+pad); reject.move(maxWidth-reject.width(), y); resize(maxWidth + pad, y+reject.height()+pad); setBorderWidth(1); @@ -74,7 +76,8 @@ void QueryConnectDialog::buttonActivate(TXButton* b) { callback->queryRejected(); } -void QueryConnectDialog::handleTimeout(rfb::Timer* t) { +void QueryConnectDialog::handleTimeout(core::Timer* t) +{ if (timeUntilReject-- == 0) { unmap(); callback->queryTimedOut(); diff --git a/unix/vncconfig/QueryConnectDialog.h b/unix/vncconfig/QueryConnectDialog.h index 5763e1cec6..7e9450b0b7 100644 --- a/unix/vncconfig/QueryConnectDialog.h +++ b/unix/vncconfig/QueryConnectDialog.h @@ -19,7 +19,8 @@ #ifndef __QUERYCONNECTDIALOG_H__ #define __QUERYCONNECTDIALOG_H__ -#include +#include + #include "TXLabel.h" #include "TXButton.h" #include "TXDialog.h" @@ -34,7 +35,7 @@ class QueryResultCallback { class QueryConnectDialog : public TXDialog, public TXEventHandler, public TXButtonCallback, - public rfb::Timer::Callback + public core::Timer::Callback { public: QueryConnectDialog(Display* dpy, const char* address_, @@ -43,14 +44,14 @@ class QueryConnectDialog : public TXDialog, public TXEventHandler, void handleEvent(TXWindow*, XEvent* ) override { } void deleteWindow(TXWindow*) override; void buttonActivate(TXButton* b) override; - void handleTimeout(rfb::Timer* t) override; + void handleTimeout(core::Timer* t) override; private: void refreshTimeout(); TXLabel addressLbl, address, userLbl, user, timeoutLbl, timeout; TXButton accept, reject; QueryResultCallback* callback; int timeUntilReject; - rfb::Timer timer; + core::Timer timer; }; #endif diff --git a/unix/vncconfig/vncconfig.cxx b/unix/vncconfig/vncconfig.cxx index bacbfb3f73..a51ad4e0a6 100644 --- a/unix/vncconfig/vncconfig.cxx +++ b/unix/vncconfig/vncconfig.cxx @@ -39,22 +39,22 @@ #include #include #include "vncExt.h" -#include -#include -#include -#include + +#include +#include +#include +#include + #include "TXWindow.h" #include "TXCheckbox.h" #include "TXLabel.h" #include "QueryConnectDialog.h" -using namespace rfb; - -static LogWriter vlog("vncconfig"); +static core::LogWriter vlog("vncconfig"); -StringParameter displayname("display", "The X display", ""); -BoolParameter noWindow("nowin", "Don't display a window", 0); -BoolParameter iconic("iconic", "Start with window iconified", 0); +core::StringParameter displayname("display", "The X display", ""); +core::BoolParameter noWindow("nowin", "Don't display a window", 0); +core::BoolParameter iconic("iconic", "Start with window iconified", 0); #define ACCEPT_CUT_TEXT "AcceptCutText" #define SEND_CUT_TEXT "SendCutText" @@ -192,7 +192,7 @@ static void usage() "Other valid forms are = -= " "--=\n" "Parameter names are case-insensitive. The parameters are:\n\n"); - Configuration::listParams(79, 14); + core::Configuration::listParams(79, 14); exit(1); } @@ -207,18 +207,18 @@ void removeArgs(int* argc, char** argv, int first, int n) int main(int argc, char** argv) { programName = argv[0]; - rfb::initStdIOLoggers(); - rfb::LogWriter::setLogParams("*:stderr:30"); + core::initStdIOLoggers(); + core::LogWriter::setLogParams("*:stderr:30"); // Process vncconfig's own parameters first, then we process the // other arguments when we have the X display. int i; for (i = 1; i < argc; i++) { - if (Configuration::setParam(argv[i])) + if (core::Configuration::setParam(argv[i])) continue; if (argv[i][0] == '-' && i+1 < argc && - Configuration::setParam(&argv[i][1], argv[i+1])) { + core::Configuration::setParam(&argv[i][1], argv[i+1])) { i++; continue; } @@ -312,7 +312,7 @@ int main(int argc, char** argv) TXWindow::handleXEvents(dpy); // Process expired timers and get the time until the next one - int timeoutMs = Timer::checkTimeouts(); + int timeoutMs = core::Timer::checkTimeouts(); if (timeoutMs >= 0) { tv.tv_sec = timeoutMs / 1000; tv.tv_usec = (timeoutMs % 1000) * 1000; @@ -330,7 +330,7 @@ int main(int argc, char** argv) FD_ZERO(&rfds); FD_SET(ConnectionNumber(dpy), &rfds); int n = select(FD_SETSIZE, &rfds, nullptr, nullptr, tvp); - if (n < 0) throw rdr::socket_error("select", errno); + if (n < 0) throw core::socket_error("select", errno); } XCloseDisplay(dpy); diff --git a/unix/vncpasswd/CMakeLists.txt b/unix/vncpasswd/CMakeLists.txt index f490a9338d..6ed4adaf05 100644 --- a/unix/vncpasswd/CMakeLists.txt +++ b/unix/vncpasswd/CMakeLists.txt @@ -2,7 +2,7 @@ add_executable(vncpasswd vncpasswd.cxx) target_include_directories(vncpasswd PUBLIC ${CMAKE_SOURCE_DIR}/common) -target_link_libraries(vncpasswd tx rfb os) +target_link_libraries(vncpasswd core tx rfb) if(PWQUALITY_FOUND) target_link_libraries(vncpasswd pwquality) diff --git a/unix/vncpasswd/vncpasswd.cxx b/unix/vncpasswd/vncpasswd.cxx index 368bd40ab9..bdded3df82 100644 --- a/unix/vncpasswd/vncpasswd.cxx +++ b/unix/vncpasswd/vncpasswd.cxx @@ -31,7 +31,8 @@ #include #include #include -#include + +#include #include @@ -41,8 +42,6 @@ #include #endif -using namespace rfb; - char* prog; static void usage() @@ -88,7 +87,7 @@ static int encrypt_pipe() { if (!result) break; - std::vector obfuscated = obfuscate(result); + std::vector obfuscated = rfb::obfuscate(result); if (fwrite(obfuscated.data(), obfuscated.size(), 1, stdout) != 1) { fprintf(stderr,"Writing to stdout failed\n"); return 1; @@ -177,7 +176,7 @@ static std::vector readpassword() { continue; } - return obfuscate(first.c_str()); + return rfb::obfuscate(first.c_str()); } } @@ -207,12 +206,12 @@ int main(int argc, char** argv) } if (fname[0] == '\0') { - const char *configDir = os::getvncconfigdir(); + const char* configDir = core::getvncconfigdir(); if (configDir == nullptr) { fprintf(stderr, "Could not determine VNC config directory path\n"); exit(1); } - if (os::mkdir_p(configDir, 0777) == -1) { + if (core::mkdir_p(configDir, 0777) == -1) { if (errno != EEXIST) { fprintf(stderr, "Could not create VNC config directory \"%s\": %s\n", configDir, strerror(errno)); diff --git a/unix/x0vncserver/CMakeLists.txt b/unix/x0vncserver/CMakeLists.txt index 9d6d213327..763f2de235 100644 --- a/unix/x0vncserver/CMakeLists.txt +++ b/unix/x0vncserver/CMakeLists.txt @@ -20,7 +20,7 @@ target_include_directories(x0vncserver PUBLIC ${CMAKE_SOURCE_DIR}/unix/common) target_include_directories(x0vncserver PUBLIC ${CMAKE_SOURCE_DIR}/unix/tx) target_include_directories(x0vncserver PUBLIC ${CMAKE_SOURCE_DIR}/unix) target_include_directories(x0vncserver PUBLIC ${CMAKE_SOURCE_DIR}/common) -target_link_libraries(x0vncserver tx rfb network rdr unixcommon) +target_link_libraries(x0vncserver core tx rfb network rdr unixcommon) # systemd support (socket activation) if (LIBSYSTEMD_FOUND) diff --git a/unix/x0vncserver/Geometry.cxx b/unix/x0vncserver/Geometry.cxx index 28e71be412..0a848cbbe9 100644 --- a/unix/x0vncserver/Geometry.cxx +++ b/unix/x0vncserver/Geometry.cxx @@ -26,14 +26,13 @@ #include -#include -#include +#include -using namespace rfb; +#include -static LogWriter vlog("Geometry"); +static core::LogWriter vlog("Geometry"); -StringParameter Geometry::m_geometryParam("Geometry", +core::StringParameter Geometry::m_geometryParam("Geometry", "Screen area shown to VNC clients. " "Format is x++, " "more information in man X, section GEOMETRY SPECIFICATIONS. " @@ -67,9 +66,9 @@ void Geometry::recalc(int fullWidth, int fullHeight) width(), height(), offsetLeft(), offsetTop()); } -Rect Geometry::parseString(const char *arg) const +core::Rect Geometry::parseString(const char* arg) const { - Rect result; // empty by default + core::Rect result; // empty by default if (arg != nullptr && strlen(arg) > 0) { int w, h; @@ -83,7 +82,7 @@ Rect Geometry::parseString(const char *arg) const x = m_fullWidth - w - x; if (sign_y[0] == '-') y = m_fullHeight - h - y; - Rect partRect(x, y, x + w, y + h); + core::Rect partRect(x, y, x + w, y + h); result = partRect.intersect(m_rect); if (result.area() <= 0) { vlog.error("Requested area is out of the desktop boundaries"); diff --git a/unix/x0vncserver/Geometry.h b/unix/x0vncserver/Geometry.h index d938d63fc9..284fbfbdcc 100644 --- a/unix/x0vncserver/Geometry.h +++ b/unix/x0vncserver/Geometry.h @@ -23,8 +23,9 @@ #ifndef __GEOMETRY_H__ #define __GEOMETRY_H__ -#include -#include +#include + +namespace rfb { class StringParameter; } class Geometry { @@ -42,18 +43,18 @@ class Geometry int offsetTop() const { return m_rect.tl.y; } // Return the same information as a Rect structure. - const rfb::Rect& getRect() const { return m_rect; } + const core::Rect& getRect() const { return m_rect; } protected: // Parse a string, extract size and coordinates, // and return that rectangle clipped to m_rect. - rfb::Rect parseString(const char *arg) const; + core::Rect parseString(const char* arg) const; - static rfb::StringParameter m_geometryParam; + static core::StringParameter m_geometryParam; int m_fullWidth; int m_fullHeight; - rfb::Rect m_rect; + core::Rect m_rect; }; #endif // __GEOMETRY_H__ diff --git a/unix/x0vncserver/Image.cxx b/unix/x0vncserver/Image.cxx index bd48c88d1d..88467c611d 100644 --- a/unix/x0vncserver/Image.cxx +++ b/unix/x0vncserver/Image.cxx @@ -32,7 +32,8 @@ #include #include -#include +#include + #include // @@ -60,7 +61,7 @@ ImageCleanup imageCleanup; // Image class implementation. // -static rfb::LogWriter vlog("Image"); +static core::LogWriter vlog("Image"); Image::Image(Display *d) : xim(nullptr), dpy(d) diff --git a/unix/x0vncserver/PollingManager.cxx b/unix/x0vncserver/PollingManager.cxx index 1761e358c7..04c3d065b2 100644 --- a/unix/x0vncserver/PollingManager.cxx +++ b/unix/x0vncserver/PollingManager.cxx @@ -27,17 +27,18 @@ #include #include #include + #include -#include + +#include +#include + #include -#include #include #include -using namespace rfb; - -static LogWriter vlog("PollingMgr"); +static core::LogWriter vlog("PollingMgr"); const int PollingManager::m_pollingOrder[32] = { 0, 16, 8, 24, 4, 20, 12, 28, @@ -123,7 +124,7 @@ void PollingManager::debugAfterPoll() // Search for changed rectangles on the screen. // -void PollingManager::poll(VNCServer *server) +void PollingManager::poll(rfb::VNCServer* server) { #ifdef DEBUG debugBeforePoll(); @@ -142,7 +143,7 @@ void PollingManager::poll(VNCServer *server) #define DBG_REPORT_CHANGES(title) #endif -bool PollingManager::pollScreen(VNCServer *server) +bool PollingManager::pollScreen(rfb::VNCServer* server) { if (!server) return false; @@ -259,12 +260,12 @@ int PollingManager::checkColumn(int x, int y, int h, bool *pChangeFlags) return nTilesChanged; } -int PollingManager::sendChanges(VNCServer *server) const +int PollingManager::sendChanges(rfb::VNCServer* server) const { const bool *pChangeFlags = m_changeFlags; int nTilesChanged = 0; - Rect rect; + core::Rect rect; for (int y = 0; y < m_heightTiles; y++) { for (int x = 0; x < m_widthTiles; x++) { if (*pChangeFlags++) { diff --git a/unix/x0vncserver/XDesktop.cxx b/unix/x0vncserver/XDesktop.cxx index b43e3f791f..fe20010258 100644 --- a/unix/x0vncserver/XDesktop.cxx +++ b/unix/x0vncserver/XDesktop.cxx @@ -28,9 +28,11 @@ #include +#include + #include -#include +#include #include @@ -56,25 +58,27 @@ void vncSetGlueContext(Display *dpy, void *res); #include #include -using namespace rfb; - extern const unsigned short code_map_qnum_to_xorgevdev[]; extern const unsigned int code_map_qnum_to_xorgevdev_len; extern const unsigned short code_map_qnum_to_xorgkbd[]; extern const unsigned int code_map_qnum_to_xorgkbd_len; -BoolParameter useShm("UseSHM", "Use MIT-SHM extension if available", true); -BoolParameter rawKeyboard("RawKeyboard", - "Send keyboard events straight through and " - "avoid mapping them to the current keyboard " - "layout", false); -IntParameter queryConnectTimeout("QueryConnectTimeout", - "Number of seconds to show the 'Accept connection' dialog before " - "rejecting the connection", - 10); - -static rfb::LogWriter vlog("XDesktop"); +core::BoolParameter + useShm("UseSHM", "Use MIT-SHM extension if available", true); +core::BoolParameter + rawKeyboard("RawKeyboard", + "Send keyboard events straight through and avoid " + "mapping them to the current keyboard layout", + false); +core::IntParameter + queryConnectTimeout("QueryConnectTimeout", + "Number of seconds to show the 'Accept " + "connection' dialog before rejecting the " + "connection", + 10); + +static core::LogWriter vlog("XDesktop"); // order is important as it must match RFB extension static const char * ledNames[XDESKTOP_N_LEDS] = { @@ -234,12 +238,12 @@ void XDesktop::poll() { &x, &y, &wx, &wy, &mask)) { x -= geometry->offsetLeft(); y -= geometry->offsetTop(); - server->setCursorPos(rfb::Point(x, y), false); + server->setCursorPos({x, y}, false); } } } -void XDesktop::init(VNCServer* vs) +void XDesktop::init(rfb::VNCServer* vs) { server = vs; } @@ -347,7 +351,9 @@ void XDesktop::queryConnection(network::Socket* sock, queryConnectDialog->map(); } -void XDesktop::pointerEvent(const Point& pos, uint16_t buttonMask) { +void XDesktop::pointerEvent(const core::Point& pos, + uint16_t buttonMask) +{ #ifdef HAVE_XTEST if (!haveXtest) return; XTestFakeMotionEvent(dpy, DefaultScreen(dpy), @@ -605,9 +611,9 @@ void XDesktop::keyEvent(uint32_t keysym, uint32_t xtcode, bool down) { #endif } -ScreenSet XDesktop::computeScreenLayout() +rfb::ScreenSet XDesktop::computeScreenLayout() { - ScreenSet layout; + rfb::ScreenSet layout; char buffer[2048]; #ifdef HAVE_XRANDR @@ -622,8 +628,8 @@ ScreenSet XDesktop::computeScreenLayout() XRRFreeScreenResources(res); // Adjust the layout relative to the geometry - ScreenSet::iterator iter, iter_next; - Point offset(-geometry->offsetLeft(), -geometry->offsetTop()); + rfb::ScreenSet::iterator iter, iter_next; + core::Point offset(-geometry->offsetLeft(), -geometry->offsetTop()); for (iter = layout.begin();iter != layout.end();iter = iter_next) { iter_next = iter; ++iter_next; iter->dimensions = iter->dimensions.intersect(geometry->getRect()); @@ -705,9 +711,9 @@ unsigned int XDesktop::setScreenLayout(int fb_width, int fb_height, } else { vlog.debug("Impossible layout - trying to adjust"); - ScreenSet::const_iterator firstscreen = layout.begin(); + rfb::ScreenSet::const_iterator firstscreen = layout.begin(); adjustedLayout.add_screen(*firstscreen); - ScreenSet::iterator iter = adjustedLayout.begin(); + rfb::ScreenSet::iterator iter = adjustedLayout.begin(); RROutput outputId = None; for (int i = 0;i < vncRandRGetOutputCount();i++) { @@ -861,15 +867,15 @@ bool XDesktop::handleGlobalEvent(XEvent* ev) { #ifdef HAVE_XDAMAGE } else if (ev->type == xdamageEventBase) { XDamageNotifyEvent* dev; - Rect rect; + core::Rect rect; if (!running) return true; dev = (XDamageNotifyEvent*)ev; rect.setXYWH(dev->area.x, dev->area.y, dev->area.width, dev->area.height); - rect = rect.translate(Point(-geometry->offsetLeft(), - -geometry->offsetTop())); + rect = rect.translate({-geometry->offsetLeft(), + -geometry->offsetTop()}); server->add_changed(rect); return true; @@ -940,7 +946,7 @@ bool XDesktop::handleGlobalEvent(XEvent* ev) { server->setPixelBuffer(pb, computeScreenLayout()); // Mark entire screen as changed - server->add_changed(rfb::Region(Rect(0, 0, cev->width, cev->height))); + server->add_changed({{0, 0, cev->width, cev->height}}); } return true; @@ -985,7 +991,7 @@ bool XDesktop::handleGlobalEvent(XEvent* ev) { if (cev->window == cev->root) return false; - server->setCursor(0, 0, Point(), nullptr); + server->setCursor(0, 0, {}, nullptr); return true; #endif } @@ -1046,7 +1052,7 @@ bool XDesktop::setCursor() } try { - server->setCursor(cim->width, cim->height, Point(cim->xhot, cim->yhot), + server->setCursor(cim->width, cim->height, {cim->xhot, cim->yhot}, cursorData); } catch (std::exception& e) { vlog.error("XserverDesktop::setCursor: %s",e.what()); diff --git a/unix/x0vncserver/XDesktop.h b/unix/x0vncserver/XDesktop.h index a27a1eae40..89e2531dbb 100644 --- a/unix/x0vncserver/XDesktop.h +++ b/unix/x0vncserver/XDesktop.h @@ -63,7 +63,8 @@ class XDesktop : public rfb::SDesktop, bool isRunning(); void queryConnection(network::Socket* sock, const char* userName) override; - void pointerEvent(const rfb::Point& pos, uint16_t buttonMask) override; + void pointerEvent(const core::Point& pos, + uint16_t buttonMask) override; void keyEvent(uint32_t keysym, uint32_t xtcode, bool down) override; unsigned int setScreenLayout(int fb_width, int fb_height, const rfb::ScreenSet& layout) override; diff --git a/unix/x0vncserver/XPixelBuffer.cxx b/unix/x0vncserver/XPixelBuffer.cxx index 0e24cc513f..5e89a342d9 100644 --- a/unix/x0vncserver/XPixelBuffer.cxx +++ b/unix/x0vncserver/XPixelBuffer.cxx @@ -25,15 +25,17 @@ #include #endif +#include #include -#include + #include -#include -using namespace rfb; +#include + +#include XPixelBuffer::XPixelBuffer(Display *dpy, ImageFactory &factory, - const Rect &rect) + const core::Rect& rect) : FullFramePixelBuffer(), m_poller(nullptr), m_dpy(dpy), @@ -42,16 +44,16 @@ XPixelBuffer::XPixelBuffer(Display *dpy, ImageFactory &factory, m_offsetTop(rect.tl.y) { // Fill in the PixelFormat structure of the parent class. - format = PixelFormat(m_image->xim->bits_per_pixel, - m_image->xim->depth, - (m_image->xim->byte_order == MSBFirst), - true, - m_image->xim->red_mask >> (ffs(m_image->xim->red_mask) - 1), - m_image->xim->green_mask >> (ffs(m_image->xim->green_mask) - 1), - m_image->xim->blue_mask >> (ffs(m_image->xim->blue_mask) - 1), - ffs(m_image->xim->red_mask) - 1, - ffs(m_image->xim->green_mask) - 1, - ffs(m_image->xim->blue_mask) - 1); + format = rfb::PixelFormat(m_image->xim->bits_per_pixel, + m_image->xim->depth, + (m_image->xim->byte_order == MSBFirst), + true, + m_image->xim->red_mask >> (ffs(m_image->xim->red_mask) - 1), + m_image->xim->green_mask >> (ffs(m_image->xim->green_mask) - 1), + m_image->xim->blue_mask >> (ffs(m_image->xim->blue_mask) - 1), + ffs(m_image->xim->red_mask) - 1, + ffs(m_image->xim->green_mask) - 1, + ffs(m_image->xim->blue_mask) - 1); // Set up the remaining data of the parent class. setBuffer(rect.width(), rect.height(), (uint8_t *)m_image->xim->data, @@ -72,10 +74,10 @@ XPixelBuffer::~XPixelBuffer() } void -XPixelBuffer::grabRegion(const rfb::Region& region) +XPixelBuffer::grabRegion(const core::Region& region) { - std::vector rects; - std::vector::const_iterator i; + std::vector rects; + std::vector::const_iterator i; region.get_rects(&rects); for (i = rects.begin(); i != rects.end(); i++) { grabRect(*i); diff --git a/unix/x0vncserver/XPixelBuffer.h b/unix/x0vncserver/XPixelBuffer.h index 7556e6ef6a..727d086770 100644 --- a/unix/x0vncserver/XPixelBuffer.h +++ b/unix/x0vncserver/XPixelBuffer.h @@ -24,10 +24,12 @@ #define __XPIXELBUFFER_H__ #include -#include + #include #include +namespace rfb { class VNCServer; } + // // XPixelBuffer is an Image-based implementation of FullFramePixelBuffer. // @@ -35,7 +37,7 @@ class XPixelBuffer : public rfb::FullFramePixelBuffer { public: - XPixelBuffer(Display *dpy, ImageFactory &factory, const rfb::Rect &rect); + XPixelBuffer(Display* dpy, ImageFactory& factory, const core::Rect& rect); virtual ~XPixelBuffer(); // Provide access to the underlying Image object. @@ -45,7 +47,7 @@ class XPixelBuffer : public rfb::FullFramePixelBuffer inline void poll(rfb::VNCServer *server) { m_poller->poll(server); } // Override PixelBuffer::grabRegion(). - void grabRegion(const rfb::Region& region) override; + void grabRegion(const core::Region& region) override; protected: PollingManager *m_poller; @@ -57,7 +59,7 @@ class XPixelBuffer : public rfb::FullFramePixelBuffer // Copy pixels from the screen to the pixel buffer, // for the specified rectangular area of the buffer. - inline void grabRect(const rfb::Rect &r) { + inline void grabRect(const core::Rect& r) { m_image->get(DefaultRootWindow(m_dpy), m_offsetLeft + r.tl.x, m_offsetTop + r.tl.y, r.width(), r.height(), r.tl.x, r.tl.y); diff --git a/unix/x0vncserver/XSelection.cxx b/unix/x0vncserver/XSelection.cxx index c724d2ac41..5de171d17a 100644 --- a/unix/x0vncserver/XSelection.cxx +++ b/unix/x0vncserver/XSelection.cxx @@ -17,19 +17,23 @@ */ #include -#include -#include -#include + +#include +#include +#include + #include -rfb::BoolParameter setPrimary("SetPrimary", - "Set the PRIMARY as well as the CLIPBOARD selection", - true); -rfb::BoolParameter sendPrimary("SendPrimary", - "Send the PRIMARY as well as the CLIPBOARD selection", - true); +core::BoolParameter + setPrimary("SetPrimary", + "Set the PRIMARY as well as the CLIPBOARD selection", + true); +core::BoolParameter + sendPrimary("SendPrimary", + "Send the PRIMARY as well as the CLIPBOARD selection", + true); -static rfb::LogWriter vlog("XSelection"); +static core::LogWriter vlog("XSelection"); XSelection::XSelection(Display* dpy_, XSelectionHandler* handler_) : TXWindow(dpy_, 1, 1, nullptr), handler(handler_), announcedSelection(None) @@ -89,7 +93,7 @@ bool XSelection::selectionRequest(Window requestor, Atom selection, Atom target, return false; if (target == XA_STRING) { - std::string latin1 = rfb::utf8ToLatin1(clientData.data(), clientData.length()); + std::string latin1 = core::utf8ToLatin1(clientData.data(), clientData.length()); XChangeProperty(dpy, requestor, property, XA_STRING, 8, PropModeReplace, (unsigned char*)latin1.data(), latin1.length()); return true; @@ -184,11 +188,11 @@ void XSelection::selectionNotify(XSelectionEvent* ev, Atom type, int format, return; if (type == xaUTF8_STRING) { - std::string result = rfb::convertLF((char*)data, nitems); + std::string result = core::convertLF((char*)data, nitems); handler->handleXSelectionData(result.c_str()); } else if (type == XA_STRING) { - std::string result = rfb::convertLF((char*)data, nitems); - result = rfb::latin1ToUTF8(result.data(), result.length()); + std::string result = core::convertLF((char*)data, nitems); + result = core::latin1ToUTF8(result.data(), result.length()); handler->handleXSelectionData(result.c_str()); } } diff --git a/unix/x0vncserver/x0vncserver.cxx b/unix/x0vncserver/x0vncserver.cxx index 7ea427ede3..1333b8766f 100644 --- a/unix/x0vncserver/x0vncserver.cxx +++ b/unix/x0vncserver/x0vncserver.cxx @@ -31,13 +31,19 @@ #include #include -#include -#include +#include +#include +#include +#include +#include + +#include + #include -#include -#include + #include #include + #ifdef HAVE_LIBSYSTEMD # include #endif @@ -54,30 +60,38 @@ extern char buildtime[]; -using namespace rfb; -using namespace network; - -static LogWriter vlog("Main"); +static core::LogWriter vlog("Main"); static const char* defaultDesktopName(); -IntParameter pollingCycle("PollingCycle", "Milliseconds per one polling " - "cycle; actual interval may be dynamically " - "adjusted to satisfy MaxProcessorUsage setting", 30); -IntParameter maxProcessorUsage("MaxProcessorUsage", "Maximum percentage of " - "CPU time to be consumed", 35); -StringParameter desktopName("desktop", "Name of VNC desktop", defaultDesktopName()); -StringParameter displayname("display", "The X display", ""); -IntParameter rfbport("rfbport", "TCP port to listen for RFB protocol",5900); -StringParameter rfbunixpath("rfbunixpath", "Unix socket to listen for RFB protocol", ""); -IntParameter rfbunixmode("rfbunixmode", "Unix socket access mode", 0600); -StringParameter hostsFile("HostsFile", "File with IP access control rules", ""); -BoolParameter localhostOnly("localhost", - "Only allow connections from localhost", - false); -StringParameter interface("interface", - "Listen on the specified network address", - "all"); +core::IntParameter + pollingCycle("PollingCycle", + "Milliseconds per one polling cycle; actual interval " + "may be dynamically adjusted to satisfy " + "MaxProcessorUsage setting", 30); +core::IntParameter + maxProcessorUsage("MaxProcessorUsage", + "Maximum percentage of CPU time to be consumed", + 35); +core::StringParameter + desktopName("desktop", "Name of VNC desktop", defaultDesktopName()); +core::StringParameter + displayname("display", "The X display", ""); +core::IntParameter + rfbport("rfbport", "TCP port to listen for RFB protocol", 5900); +core::StringParameter + rfbunixpath("rfbunixpath", + "Unix socket to listen for RFB protocol", ""); +core::IntParameter + rfbunixmode("rfbunixmode", "Unix socket access mode", 0600); +core::StringParameter + hostsFile("HostsFile", "File with IP access control rules", ""); +core::BoolParameter + localhostOnly("localhost", + "Only allow connections from localhost", false); +core::StringParameter + interface("interface", + "Listen on the specified network address", "all"); static const char* defaultDesktopName() { @@ -127,7 +141,7 @@ static bool hasSystemdListeners() #endif } -static int createSystemdListeners(std::list *listeners) +static int createSystemdListeners(std::list *listeners) { #ifdef HAVE_LIBSYSTEMD int count = sd_listen_fds(0); @@ -138,7 +152,7 @@ static int createSystemdListeners(std::list *listeners) } for (int i = 0; i < count; ++i) - listeners->push_back(new TcpListener(SD_LISTEN_FDS_START + i)); + listeners->push_back(new network::TcpListener(SD_LISTEN_FDS_START + i)); return count; #else @@ -148,7 +162,7 @@ static int createSystemdListeners(std::list *listeners) } -class FileTcpFilter : public TcpFilter +class FileTcpFilter : public network::TcpFilter { public: @@ -166,7 +180,7 @@ class FileTcpFilter : public TcpFilter free(fileName); } - bool verifyConnection(Socket* s) override + bool verifyConnection(network::Socket* s) override { if (!reloadRules()) { vlog.error("Could not read IP filtering rules, rejecting all clients"); @@ -267,31 +281,31 @@ static void usage() "Other valid forms are = -= " "--=\n" "Parameter names are case-insensitive. The parameters are:\n\n"); - Configuration::listParams(79, 14); + core::Configuration::listParams(79, 14); exit(1); } int main(int argc, char** argv) { - initStdIOLoggers(); - LogWriter::setLogParams("*:stderr:30"); + core::initStdIOLoggers(); + core::LogWriter::setLogParams("*:stderr:30"); programName = argv[0]; Display* dpy; - Configuration::enableServerParams(); + core::Configuration::enableServerParams(); // Assume different defaults when socket activated if (hasSystemdListeners()) rfbport.setParam(-1); for (int i = 1; i < argc; i++) { - if (Configuration::setParam(argv[i])) + if (core::Configuration::setParam(argv[i])) continue; if (argv[i][0] == '-') { if (i+1 < argc) { - if (Configuration::setParam(&argv[i][1], argv[i+1])) { + if (core::Configuration::setParam(&argv[i][1], argv[i+1])) { i++; continue; } @@ -319,7 +333,7 @@ int main(int argc, char** argv) signal(SIGINT, CleanupSignalHandler); signal(SIGTERM, CleanupSignalHandler); - std::list listeners; + std::list listeners; try { TXWindow::init(dpy,"x0vncserver"); @@ -331,7 +345,7 @@ int main(int argc, char** argv) } XDesktop desktop(dpy, &geo); - VNCServerST server(desktopName, &desktop); + rfb::VNCServerST server(desktopName, &desktop); if (createSystemdListeners(&listeners) > 0) { // When systemd is in charge of listeners, do not listen to anything else @@ -363,7 +377,7 @@ int main(int argc, char** argv) FileTcpFilter fileTcpFilter(hostsFile); if (strlen(hostsFile) != 0) - for (SocketListener* listener : listeners) + for (network::SocketListener* listener : listeners) listener->setFilter(&fileTcpFilter); } @@ -378,8 +392,8 @@ int main(int argc, char** argv) int wait_ms, nextTimeout; struct timeval tv; fd_set rfds, wfds; - std::list sockets; - std::list::iterator i; + std::list sockets; + std::list::iterator i; // Process any incoming X events TXWindow::handleXEvents(dpy); @@ -388,7 +402,7 @@ int main(int argc, char** argv) FD_ZERO(&wfds); FD_SET(ConnectionNumber(dpy), &rfds); - for (SocketListener* listener : listeners) + for (network::SocketListener* listener : listeners) FD_SET(listener->getFd(), &rfds); server.getSockets(&sockets); @@ -418,7 +432,7 @@ int main(int argc, char** argv) } // Trigger timers and check when the next will expire - nextTimeout = Timer::checkTimeouts(); + nextTimeout = core::Timer::checkTimeouts(); if (nextTimeout >= 0 && (wait_ms == -1 || nextTimeout < wait_ms)) wait_ms = nextTimeout; @@ -436,14 +450,14 @@ int main(int argc, char** argv) vlog.debug("Interrupted select() system call"); continue; } else { - throw rdr::socket_error("select", errno); + throw core::socket_error("select", errno); } } // Accept new VNC connections - for (SocketListener* listener : listeners) { + for (network::SocketListener* listener : listeners) { if (FD_ISSET(listener->getFd(), &rfds)) { - Socket* sock = listener->accept(); + network::Socket* sock = listener->accept(); if (sock) { server.addSocket(sock); } else { @@ -452,7 +466,7 @@ int main(int argc, char** argv) } } - Timer::checkTimeouts(); + core::Timer::checkTimeouts(); // Client list could have been changed. server.getSockets(&sockets); @@ -483,7 +497,7 @@ int main(int argc, char** argv) TXWindow::handleXEvents(dpy); // Run listener destructors; remove UNIX sockets etc - for (SocketListener* listener : listeners) + for (network::SocketListener* listener : listeners) delete listener; vlog.info("Terminated"); diff --git a/unix/xserver/hw/vnc/Makefile.am b/unix/xserver/hw/vnc/Makefile.am index 4049bafa8e..d1e25ec46a 100644 --- a/unix/xserver/hw/vnc/Makefile.am +++ b/unix/xserver/hw/vnc/Makefile.am @@ -1,15 +1,12 @@ -TIGERVNC_SRCDIR=${top_srcdir}/../.. -TIGERVNC_BUILDDIR=${TIGERVNC_SRCDIR} - -# FIXME: We add an extra / to the paths to trick libtool in to adding -# the libraries twice, to work around the dependency cycles we -# have -RFB_LIB=$(TIGERVNC_BUILDDIR)//common/rfb/librfb.la -RDR_LIB=$(TIGERVNC_BUILDDIR)//common/rdr/librdr.la -OS_LIB=$(TIGERVNC_BUILDDIR)//common/os/libos.la -NETWORK_LIB=$(TIGERVNC_BUILDDIR)//common/network/libnetwork.la -UNIXCOMMON_LIB=$(TIGERVNC_BUILDDIR)//unix/common/libunixcommon.la -COMMON_LIBS=$(NETWORK_LIB) $(RFB_LIB) $(RDR_LIB) $(OS_LIB) $(UNIXCOMMON_LIB) +TIGERVNC_SRCDIR=$(abspath ${top_srcdir}/../..) +TIGERVNC_BUILDDIR=$(abspath ${TIGERVNC_SRCDIR}) + +RFB_LIB=$(TIGERVNC_BUILDDIR)/common/rfb/librfb.la +RDR_LIB=$(TIGERVNC_BUILDDIR)/common/rdr/librdr.la +OS_LIB=$(TIGERVNC_BUILDDIR)/common/os/libos.la +NETWORK_LIB=$(TIGERVNC_BUILDDIR)/common/network/libnetwork.la +UNIXCOMMON_LIB=$(TIGERVNC_BUILDDIR)/unix/common/libunixcommon.la +COMMON_LIBS=$(UNIXCOMMON_LIB) $(RFB_LIB) $(NETWORK_LIB) $(RDR_LIB) $(CORE_LIB) AM_CPPFLAGS = \ -I$(TIGERVNC_BUILDDIR) \ diff --git a/unix/xserver/hw/vnc/RFBGlue.cc b/unix/xserver/hw/vnc/RFBGlue.cc index 2295bee85d..eb4927f717 100644 --- a/unix/xserver/hw/vnc/RFBGlue.cc +++ b/unix/xserver/hw/vnc/RFBGlue.cc @@ -22,35 +22,35 @@ #endif #include +#include + +#include +#include +#include +#include +#include #include -#include -#include -#include -#include -#include #include "RFBGlue.h" -using namespace rfb; - // Loggers used by C code must be created here -static LogWriter inputLog("Input"); -static LogWriter selectionLog("Selection"); +static core::LogWriter inputLog("Input"); +static core::LogWriter selectionLog("Selection"); void vncInitRFB(void) { - rfb::initStdIOLoggers(); - rfb::initSyslogLogger(); - rfb::LogWriter::setLogParams("*:stderr:30"); - rfb::Configuration::enableServerParams(); + core::initStdIOLoggers(); + core::initSyslogLogger(); + core::LogWriter::setLogParams("*:stderr:30"); + core::Configuration::enableServerParams(); } void vncLogError(const char *name, const char *format, ...) { - LogWriter *vlog; + core::LogWriter* vlog; va_list ap; - vlog = LogWriter::getLogWriter(name); + vlog = core::LogWriter::getLogWriter(name); if (vlog == nullptr) return; va_start(ap, format); @@ -60,9 +60,9 @@ void vncLogError(const char *name, const char *format, ...) void vncLogStatus(const char *name, const char *format, ...) { - LogWriter *vlog; + core::LogWriter* vlog; va_list ap; - vlog = LogWriter::getLogWriter(name); + vlog = core::LogWriter::getLogWriter(name); if (vlog == nullptr) return; va_start(ap, format); @@ -72,9 +72,9 @@ void vncLogStatus(const char *name, const char *format, ...) void vncLogInfo(const char *name, const char *format, ...) { - LogWriter *vlog; + core::LogWriter* vlog; va_list ap; - vlog = LogWriter::getLogWriter(name); + vlog = core::LogWriter::getLogWriter(name); if (vlog == nullptr) return; va_start(ap, format); @@ -84,9 +84,9 @@ void vncLogInfo(const char *name, const char *format, ...) void vncLogDebug(const char *name, const char *format, ...) { - LogWriter *vlog; + core::LogWriter* vlog; va_list ap; - vlog = LogWriter::getLogWriter(name); + vlog = core::LogWriter::getLogWriter(name); if (vlog == nullptr) return; va_start(ap, format); @@ -97,10 +97,10 @@ void vncLogDebug(const char *name, const char *format, ...) int vncSetParam(const char *name, const char *value) { if (value != nullptr) - return rfb::Configuration::setParam(name, value); + return core::Configuration::setParam(name, value); else { - VoidParameter *param; - param = rfb::Configuration::getParam(name); + core::VoidParameter* param; + param = core::Configuration::getParam(name); if (param == nullptr) return false; return param->setParam(); @@ -109,18 +109,18 @@ int vncSetParam(const char *name, const char *value) int vncSetParamSimple(const char *nameAndValue) { - return rfb::Configuration::setParam(nameAndValue); + return core::Configuration::setParam(nameAndValue); } char* vncGetParam(const char *name) { - VoidParameter *param; + core::VoidParameter* param; // Hack to avoid exposing password! if (strcasecmp(name, "Password") == 0) return nullptr; - param = rfb::Configuration::getParam(name); + param = core::Configuration::getParam(name); if (param == nullptr) return nullptr; @@ -129,9 +129,9 @@ char* vncGetParam(const char *name) const char* vncGetParamDesc(const char *name) { - rfb::VoidParameter *param; + core::VoidParameter* param; - param = rfb::Configuration::getParam(name); + param = core::Configuration::getParam(name); if (param == nullptr) return nullptr; @@ -140,14 +140,14 @@ const char* vncGetParamDesc(const char *name) int vncIsParamBool(const char *name) { - VoidParameter *param; - BoolParameter *bparam; + core::VoidParameter* param; + core::BoolParameter* bparam; - param = rfb::Configuration::getParam(name); + param = core::Configuration::getParam(name); if (param == nullptr) return false; - bparam = dynamic_cast(param); + bparam = dynamic_cast(param); if (bparam == nullptr) return false; @@ -159,7 +159,7 @@ int vncGetParamCount(void) int count; count = 0; - for (ParameterIterator i; i.param; i.next()) + for (core::ParameterIterator i; i.param; i.next()) count++; return count; @@ -172,7 +172,7 @@ char *vncGetParamList(void) len = 0; - for (ParameterIterator i; i.param; i.next()) { + for (core::ParameterIterator i; i.param; i.next()) { int l = strlen(i.param->getName()); if (l <= 255) len += l + 1; @@ -183,7 +183,7 @@ char *vncGetParamList(void) return nullptr; ptr = data; - for (ParameterIterator i; i.param; i.next()) { + for (core::ParameterIterator i; i.param; i.next()) { int l = strlen(i.param->getName()); if (l <= 255) { *ptr++ = l; @@ -198,7 +198,7 @@ char *vncGetParamList(void) void vncListParams(int width, int nameWidth) { - rfb::Configuration::listParams(width, nameWidth); + core::Configuration::listParams(width, nameWidth); } int vncGetSocketPort(int fd) @@ -225,7 +225,7 @@ int vncIsTCPPortUsed(int port) char* vncConvertLF(const char* src, size_t bytes) { try { - return strdup(convertLF(src, bytes).c_str()); + return strdup(core::convertLF(src, bytes).c_str()); } catch (...) { return nullptr; } @@ -234,7 +234,7 @@ char* vncConvertLF(const char* src, size_t bytes) char* vncLatin1ToUTF8(const char* src, size_t bytes) { try { - return strdup(latin1ToUTF8(src, bytes).c_str()); + return strdup(core::latin1ToUTF8(src, bytes).c_str()); } catch (...) { return nullptr; } @@ -243,7 +243,7 @@ char* vncLatin1ToUTF8(const char* src, size_t bytes) char* vncUTF8ToLatin1(const char* src, size_t bytes) { try { - return strdup(utf8ToLatin1(src, bytes).c_str()); + return strdup(core::utf8ToLatin1(src, bytes).c_str()); } catch (...) { return nullptr; } @@ -252,7 +252,7 @@ char* vncUTF8ToLatin1(const char* src, size_t bytes) int vncIsValidUTF8(const char* str, size_t bytes) { try { - return isValidUTF8(str, bytes); + return core::isValidUTF8(str, bytes); } catch (...) { return 0; } diff --git a/unix/xserver/hw/vnc/XserverDesktop.cc b/unix/xserver/hw/vnc/XserverDesktop.cc index 260ed3a629..d79c29b600 100644 --- a/unix/xserver/hw/vnc/XserverDesktop.cc +++ b/unix/xserver/hw/vnc/XserverDesktop.cc @@ -37,10 +37,14 @@ #include #include +#include +#include + +#include + #include + #include -#include -#include #include #include "XserverDesktop.h" @@ -56,20 +60,17 @@ void vncSetGlueContext(int screenIndex); void vncPresentMscEvent(uint64_t id, uint64_t msc); } -using namespace rfb; -using namespace network; - -static LogWriter vlog("XserverDesktop"); +static core::LogWriter vlog("XserverDesktop"); -BoolParameter rawKeyboard("RawKeyboard", - "Send keyboard events straight through and " - "avoid mapping them to the current keyboard " - "layout", false); -IntParameter queryConnectTimeout("QueryConnectTimeout", - "Number of seconds to show the " - "Accept connection dialog before " - "rejecting the connection", - 10); +core::BoolParameter + rawKeyboard("RawKeyboard", + "Send keyboard events straight through and avoid mapping " + "them to the current keyboard layout", false); +core::IntParameter + queryConnectTimeout("QueryConnectTimeout", + "Number of seconds to show the 'Accept " + "connection' dialog before rejecting the " + "connection", 10); XserverDesktop::XserverDesktop(int screenIndex_, @@ -84,10 +85,10 @@ XserverDesktop::XserverDesktop(int screenIndex_, { format = pf; - server = new VNCServerST(name, this); + server = new rfb::VNCServerST(name, this); setFramebuffer(width, height, fbptr, stride_); - for (SocketListener* listener : listeners) + for (network::SocketListener* listener : listeners) vncSetNotifyFd(listener->getFd(), screenIndex, true, false); } @@ -115,7 +116,7 @@ void XserverDesktop::unblockUpdates() void XserverDesktop::setFramebuffer(int w, int h, void* fbptr, int stride_) { - ScreenSet layout; + rfb::ScreenSet layout; if (shadowFramebuffer) { delete [] shadowFramebuffer; @@ -265,7 +266,7 @@ void XserverDesktop::setCursor(int width, int height, int hotX, int hotY, } try { - server->setCursor(width, height, Point(hotX, hotY), cursorData); + server->setCursor(width, height, {hotX, hotY}, cursorData); } catch (std::exception& e) { vlog.error("XserverDesktop::setCursor: %s",e.what()); } @@ -276,13 +277,13 @@ void XserverDesktop::setCursor(int width, int height, int hotX, int hotY, void XserverDesktop::setCursorPos(int x, int y, bool warped) { try { - server->setCursorPos(Point(x, y), warped); + server->setCursorPos({x, y}, warped); } catch (std::exception& e) { vlog.error("XserverDesktop::setCursorPos: %s",e.what()); } } -void XserverDesktop::add_changed(const rfb::Region ®ion) +void XserverDesktop::add_changed(const core::Region& region) { try { server->add_changed(region); @@ -291,7 +292,8 @@ void XserverDesktop::add_changed(const rfb::Region ®ion) } } -void XserverDesktop::add_copied(const rfb::Region &dest, const rfb::Point &delta) +void XserverDesktop::add_copied(const core::Region& dest, + const core::Point& delta) { try { server->add_copied(dest, delta); @@ -318,10 +320,10 @@ void XserverDesktop::handleSocketEvent(int fd, bool read, bool write) } bool XserverDesktop::handleListenerEvent(int fd, - std::list* sockets, - VNCServer* sockserv) + std::list* sockets, + rfb::VNCServer* sockserv) { - std::list::iterator i; + std::list::iterator i; for (i = sockets->begin(); i != sockets->end(); i++) { if ((*i)->getFd() == fd) @@ -331,7 +333,7 @@ bool XserverDesktop::handleListenerEvent(int fd, if (i == sockets->end()) return false; - Socket* sock = (*i)->accept(); + network::Socket* sock = (*i)->accept(); vlog.debug("New client, sock %d", sock->getFd()); sockserv->addSocket(sock); vncSetNotifyFd(sock->getFd(), screenIndex, true, false); @@ -340,11 +342,11 @@ bool XserverDesktop::handleListenerEvent(int fd, } bool XserverDesktop::handleSocketEvent(int fd, - VNCServer* sockserv, + rfb::VNCServer* sockserv, bool read, bool write) { - std::list sockets; - std::list::iterator i; + std::list sockets; + std::list::iterator i; sockserv->getSockets(&sockets); for (i = sockets.begin(); i != sockets.end(); i++) { @@ -373,8 +375,8 @@ void XserverDesktop::blockHandler(int* timeout) vncInitInputDevice(); try { - std::list sockets; - std::list::iterator i; + std::list sockets; + std::list::iterator i; server->getSockets(&sockets); for (i = sockets.begin(); i != sockets.end(); i++) { int fd = (*i)->getFd(); @@ -402,7 +404,7 @@ void XserverDesktop::blockHandler(int* timeout) } // Trigger timers and check when the next will expire - int nextTimeout = Timer::checkTimeouts(); + int nextTimeout = core::Timer::checkTimeouts(); if (nextTimeout >= 0 && (*timeout == -1 || nextTimeout < *timeout)) *timeout = nextTimeout; } catch (std::exception& e) { @@ -410,10 +412,12 @@ void XserverDesktop::blockHandler(int* timeout) } } -void XserverDesktop::addClient(Socket* sock, bool reverse, bool viewOnly) +void XserverDesktop::addClient(network::Socket* sock, + bool reverse, bool viewOnly) { vlog.debug("New client, sock %d reverse %d",sock->getFd(),reverse); - server->addSocket(sock, reverse, viewOnly ? AccessView : AccessDefault); + server->addSocket(sock, reverse, + viewOnly ? rfb::AccessView : rfb::AccessDefault); vncSetNotifyFd(sock->getFd(), screenIndex, true, false); } @@ -462,7 +466,8 @@ void XserverDesktop::terminate() kill(getpid(), SIGTERM); } -void XserverDesktop::pointerEvent(const Point& pos, uint16_t buttonMask) +void XserverDesktop::pointerEvent(const core::Point& pos, + uint16_t buttonMask) { vncPointerMove(pos.x + vncGetScreenX(screenIndex), pos.y + vncGetScreenY(screenIndex)); @@ -515,13 +520,13 @@ void XserverDesktop::handleClipboardData(const char* data_) vncHandleClipboardData(data_); } -void XserverDesktop::grabRegion(const rfb::Region& region) +void XserverDesktop::grabRegion(const core::Region& region) { if (shadowFramebuffer == nullptr) return; - std::vector rects; - std::vector::iterator i; + std::vector rects; + std::vector::iterator i; region.get_rects(&rects); for (i = rects.begin(); i != rects.end(); i++) { uint8_t *buffer; @@ -542,7 +547,7 @@ void XserverDesktop::keyEvent(uint32_t keysym, uint32_t keycode, bool down) vncKeyboardEvent(keysym, keycode, down); } -void XserverDesktop::handleTimeout(Timer* t) +void XserverDesktop::handleTimeout(core::Timer* t) { if (t == &queryConnectTimer) { server->approveConnection(queryConnectSocket, false, diff --git a/unix/xserver/hw/vnc/XserverDesktop.h b/unix/xserver/hw/vnc/XserverDesktop.h index 8c543db75e..37f5b1b5d1 100644 --- a/unix/xserver/hw/vnc/XserverDesktop.h +++ b/unix/xserver/hw/vnc/XserverDesktop.h @@ -31,11 +31,13 @@ #include +#include + #include #include -#include -#include + #include + #include "vncInput.h" namespace rfb { @@ -45,7 +47,7 @@ namespace rfb { namespace network { class SocketListener; class Socket; } class XserverDesktop : public rfb::SDesktop, public rfb::FullFramePixelBuffer, - public rfb::Timer::Callback { + public core::Timer::Callback { public: XserverDesktop(int screenIndex, @@ -71,8 +73,8 @@ class XserverDesktop : public rfb::SDesktop, public rfb::FullFramePixelBuffer, void setCursor(int width, int height, int hotX, int hotY, const unsigned char *rgbaData); void setCursorPos(int x, int y, bool warped); - void add_changed(const rfb::Region ®ion); - void add_copied(const rfb::Region &dest, const rfb::Point &delta); + void add_changed(const core::Region& region); + void add_copied(const core::Region& dest, const core::Point& delta); void handleSocketEvent(int fd, bool read, bool write); void blockHandler(int* timeout); void addClient(network::Socket* sock, bool reverse, bool viewOnly); @@ -95,7 +97,8 @@ class XserverDesktop : public rfb::SDesktop, public rfb::FullFramePixelBuffer, void terminate() override; void queryConnection(network::Socket* sock, const char* userName) override; - void pointerEvent(const rfb::Point& pos, uint16_t buttonMask) override; + void pointerEvent(const core::Point& pos, + uint16_t buttonMask) override; void keyEvent(uint32_t keysym, uint32_t keycode, bool down) override; unsigned int setScreenLayout(int fb_width, int fb_height, const rfb::ScreenSet& layout) override; @@ -105,7 +108,7 @@ class XserverDesktop : public rfb::SDesktop, public rfb::FullFramePixelBuffer, void handleClipboardData(const char* data) override; // rfb::PixelBuffer callbacks - void grabRegion(const rfb::Region& r) override; + void grabRegion(const core::Region& r) override; protected: bool handleListenerEvent(int fd, @@ -115,7 +118,7 @@ class XserverDesktop : public rfb::SDesktop, public rfb::FullFramePixelBuffer, rfb::VNCServer* sockserv, bool read, bool write); - void handleTimeout(rfb::Timer* t) override; + void handleTimeout(core::Timer* t) override; private: @@ -128,12 +131,12 @@ class XserverDesktop : public rfb::SDesktop, public rfb::FullFramePixelBuffer, network::Socket* queryConnectSocket; std::string queryConnectAddress; std::string queryConnectUsername; - rfb::Timer queryConnectTimer; + core::Timer queryConnectTimer; OutputIdMap outputIdMap; std::map pendingMsc; - rfb::Point oldCursorPos; + core::Point oldCursorPos; }; #endif diff --git a/unix/xserver/hw/vnc/vncExtInit.cc b/unix/xserver/hw/vnc/vncExtInit.cc index 367481ac29..b37de1bb22 100644 --- a/unix/xserver/hw/vnc/vncExtInit.cc +++ b/unix/xserver/hw/vnc/vncExtInit.cc @@ -30,15 +30,15 @@ #include #include -#include -#include -#include +#include +#include +#include +#include + #include #include -#include -#include -#include #include + #include #include @@ -55,9 +55,7 @@ extern "C" { void vncSetGlueContext(int screenIndex); } -using namespace rfb; - -static rfb::LogWriter vlog("vncext"); +static core::LogWriter vlog("vncext"); // We can't safely get this from Xorg #define MAXSCREENS 16 @@ -81,27 +79,39 @@ static ParamSet allowOverrideSet; static const char* defaultDesktopName(); -rfb::IntParameter rfbport("rfbport", "TCP port to listen for RFB protocol",0); -rfb::StringParameter rfbunixpath("rfbunixpath", "Unix socket to listen for RFB protocol", ""); -rfb::IntParameter rfbunixmode("rfbunixmode", "Unix socket access mode", 0600); -rfb::StringParameter desktopName("desktop", "Name of VNC desktop", defaultDesktopName()); -rfb::BoolParameter localhostOnly("localhost", - "Only allow connections from localhost", - false); -rfb::StringParameter interface("interface", - "Listen on the specified network address", - "all"); -rfb::BoolParameter avoidShiftNumLock("AvoidShiftNumLock", - "Avoid fake Shift presses for keys affected by NumLock.", - true); -rfb::StringParameter allowOverride("AllowOverride", - "Comma separated list of parameters that can be modified using VNC extension.", - "desktop,AcceptPointerEvents,SendCutText,AcceptCutText,SendPrimary,SetPrimary"); -rfb::BoolParameter setPrimary("SetPrimary", "Set the PRIMARY as well " - "as the CLIPBOARD selection", true); -rfb::BoolParameter sendPrimary("SendPrimary", - "Send the PRIMARY as well as the CLIPBOARD selection", - true); +core::IntParameter + rfbport("rfbport", "TCP port to listen for RFB protocol", 0); +core::StringParameter + rfbunixpath("rfbunixpath", + "Unix socket to listen for RFB protocol", ""); +core::IntParameter + rfbunixmode("rfbunixmode", "Unix socket access mode", 0600); +core::StringParameter + desktopName("desktop", "Name of VNC desktop", defaultDesktopName()); +core::BoolParameter + localhostOnly("localhost", + "Only allow connections from localhost", false); +core::StringParameter + interface("interface", + "Listen on the specified network address", "all"); +core::BoolParameter + avoidShiftNumLock("AvoidShiftNumLock", + "Avoid fake Shift presses for keys affected by " + "NumLock.", true); +core::StringParameter + allowOverride("AllowOverride", + "Comma separated list of parameters that can be " + "modified using VNC extension.", + "desktop,AcceptPointerEvents,SendCutText,AcceptCutText," + "SendPrimary,SetPrimary"); +core::BoolParameter + setPrimary("SetPrimary", + "Set the PRIMARY as well as the CLIPBOARD selection", + true); +core::BoolParameter + sendPrimary("SendPrimary", + "Send the PRIMARY as well as the CLIPBOARD selection", + true); static const char* defaultDesktopName() { @@ -128,7 +138,7 @@ static const char* defaultDesktopName() return name; } -static PixelFormat vncGetPixelFormat(int scrIdx) +static rfb::PixelFormat vncGetPixelFormat(int scrIdx) { int depth, bpp; int trueColour, bigEndian; @@ -152,9 +162,9 @@ static PixelFormat vncGetPixelFormat(int scrIdx) greenMax = greenMask >> greenShift; blueMax = blueMask >> blueShift; - return PixelFormat(bpp, depth, bigEndian, trueColour, - redMax, greenMax, blueMax, - redShift, greenShift, blueShift); + return rfb::PixelFormat(bpp, depth, bigEndian, trueColour, + redMax, greenMax, blueMax, + redShift, greenShift, blueShift); } static void parseOverrideList(const char *text, ParamSet &out) @@ -189,7 +199,7 @@ void vncExtensionInit(void) try { if (!initialised) { - rfb::initStdIOLoggers(); + core::initStdIOLoggers(); parseOverrideList(allowOverride, allowOverrideSet); allowOverride.setImmutable(); @@ -252,7 +262,7 @@ void vncExtensionInit(void) if (!inetd && listeners.empty()) throw std::runtime_error("No path or port configured for incoming connections"); - PixelFormat pf = vncGetPixelFormat(scr); + rfb::PixelFormat pf = vncGetPixelFormat(scr); vncSetGlueContext(scr); desktop[scr] = new XserverDesktop(scr, @@ -358,7 +368,7 @@ int vncConnectClient(const char *addr, int viewOnly) std::string host; int port; - getHostAndPort(addr, &host, &port, 5500); + network::getHostAndPort(addr, &host, &port, 5500); try { network::Socket* sock = new network::TcpSocket(host.c_str(), port); @@ -403,11 +413,11 @@ void vncSetLEDState(unsigned long leds) state = 0; if (leds & (1 << 0)) - state |= ledCapsLock; + state |= rfb::ledCapsLock; if (leds & (1 << 1)) - state |= ledNumLock; + state |= rfb::ledNumLock; if (leds & (1 << 2)) - state |= ledScrollLock; + state |= rfb::ledScrollLock; for (int scr = 0; scr < vncGetScreenCount(); scr++) desktop[scr]->setLEDState(state); @@ -417,8 +427,8 @@ void vncAddChanged(int scrIdx, int nRects, const struct UpdateRect *rects) { for (int i = 0;i < nRects;i++) { - desktop[scrIdx]->add_changed(Region(Rect(rects[i].x1, rects[i].y1, - rects[i].x2, rects[i].y2))); + desktop[scrIdx]->add_changed({{rects[i].x1, rects[i].y1, + rects[i].x2, rects[i].y2}}); } } @@ -427,9 +437,9 @@ void vncAddCopied(int scrIdx, int nRects, int dx, int dy) { for (int i = 0;i < nRects;i++) { - desktop[scrIdx]->add_copied(Region(Rect(rects[i].x1, rects[i].y1, - rects[i].x2, rects[i].y2)), - Point(dx, dy)); + desktop[scrIdx]->add_copied({{rects[i].x1, rects[i].y1, + rects[i].x2, rects[i].y2}}, + {dx, dy}); } } @@ -471,7 +481,7 @@ void vncPostScreenResize(int scrIdx, int success, int width, int height) if (success) { // Mark entire screen as changed - desktop[scrIdx]->add_changed(Region(Rect(0, 0, width, height))); + desktop[scrIdx]->add_changed({{0, 0, width, height}}); } } @@ -521,5 +531,5 @@ int vncOverrideParam(const char *nameAndValue) if (allowOverrideSet.find(key) == allowOverrideSet.end()) return 0; - return rfb::Configuration::setParam(nameAndValue); + return core::Configuration::setParam(nameAndValue); } diff --git a/vncviewer/BaseTouchHandler.cxx b/vncviewer/BaseTouchHandler.cxx index 6552634b4f..3100f86b98 100644 --- a/vncviewer/BaseTouchHandler.cxx +++ b/vncviewer/BaseTouchHandler.cxx @@ -24,9 +24,10 @@ #include #include +#include + #define XK_MISCELLANY #include -#include #include "GestureHandler.h" #include "BaseTouchHandler.h" @@ -172,7 +173,7 @@ void BaseTouchHandler::handleTapEvent(const GestureEvent& ev, // If the user quickly taps multiple times we assume they meant to // hit the same spot, so slightly adjust coordinates - if ((rfb::msSince(&lastTapTime) < DOUBLE_TAP_TIMEOUT) && + if ((core::msSince(&lastTapTime) < DOUBLE_TAP_TIMEOUT) && (firstDoubleTapEvent.type == ev.type)) { double dx = firstDoubleTapEvent.eventX - ev.eventX; diff --git a/vncviewer/CConn.cxx b/vncviewer/CConn.cxx index f8e8042974..23755b69d3 100644 --- a/vncviewer/CConn.cxx +++ b/vncviewer/CConn.cxx @@ -27,17 +27,20 @@ #include #endif -#include +#include +#include +#include + +#include +#include #include #include #include -#include -#include #include #include #include -#include + #include #ifndef WIN32 #include @@ -58,19 +61,17 @@ #include "win32.h" #endif -using namespace rfb; - -static rfb::LogWriter vlog("CConn"); +static core::LogWriter vlog("CConn"); // 8 colours (1 bit per component) -static const PixelFormat verylowColourPF(8, 3,false, true, - 1, 1, 1, 2, 1, 0); +static const rfb::PixelFormat verylowColourPF(8, 3,false, true, + 1, 1, 1, 2, 1, 0); // 64 colours (2 bits per component) -static const PixelFormat lowColourPF(8, 6, false, true, - 3, 3, 3, 4, 2, 0); +static const rfb::PixelFormat lowColourPF(8, 6, false, true, + 3, 3, 3, 4, 2, 0); // 256 colours (2-3 bits per component) -static const PixelFormat mediumColourPF(8, 8, false, true, - 7, 7, 3, 5, 2, 0); +static const rfb::PixelFormat mediumColourPF(8, 8, false, true, + 7, 7, 3, 5, 2, 0); // Time new bandwidth estimates are weighted against (in ms) static const unsigned bpsEstimateWindow = 1000; @@ -103,7 +104,7 @@ CConn::CConn(const char* vncServerName, network::Socket* socket=nullptr) } else #endif { - getHostAndPort(vncServerName, &serverHost, &serverPort); + network::getHostAndPort(vncServerName, &serverHost, &serverPort); sock = new network::TcpSocket(serverHost.c_str(), serverPort); vlog.info(_("Connected to host %s port %d"), @@ -148,46 +149,46 @@ std::string CConn::connectionInfo() char pfStr[100]; - infoText += format(_("Desktop name: %.80s"), server.name()); + infoText += core::format(_("Desktop name: %.80s"), server.name()); infoText += "\n"; - infoText += format(_("Host: %.80s port: %d"), - serverHost.c_str(), serverPort); + infoText += core::format(_("Host: %.80s port: %d"), + serverHost.c_str(), serverPort); infoText += "\n"; - infoText += format(_("Size: %d x %d"), - server.width(), server.height()); + infoText += core::format(_("Size: %d x %d"), + server.width(), server.height()); infoText += "\n"; // TRANSLATORS: Will be filled in with a string describing the // protocol pixel format in a fairly language neutral way server.pf().print(pfStr, 100); - infoText += format(_("Pixel format: %s"), pfStr); + infoText += core::format(_("Pixel format: %s"), pfStr); infoText += "\n"; // TRANSLATORS: Similar to the earlier "Pixel format" string serverPF.print(pfStr, 100); - infoText += format(_("(server default %s)"), pfStr); + infoText += core::format(_("(server default %s)"), pfStr); infoText += "\n"; - infoText += format(_("Requested encoding: %s"), - encodingName(getPreferredEncoding())); + infoText += core::format(_("Requested encoding: %s"), + rfb::encodingName(getPreferredEncoding())); infoText += "\n"; - infoText += format(_("Last used encoding: %s"), - encodingName(lastServerEncoding)); + infoText += core::format(_("Last used encoding: %s"), + rfb::encodingName(lastServerEncoding)); infoText += "\n"; - infoText += format(_("Line speed estimate: %d kbit/s"), - (int)(bpsEstimate / 1000)); + infoText += core::format(_("Line speed estimate: %d kbit/s"), + (int)(bpsEstimate / 1000)); infoText += "\n"; - infoText += format(_("Protocol version: %d.%d"), - server.majorVersion, server.minorVersion); + infoText += core::format(_("Protocol version: %d.%d"), + server.majorVersion, server.minorVersion); infoText += "\n"; - infoText += format(_("Security method: %s"), - secTypeName(csecurity->getType())); + infoText += core::format(_("Security method: %s"), + rfb::secTypeName(csecurity->getType())); infoText += "\n"; return infoText; @@ -236,7 +237,7 @@ void CConn::socketEvent(FL_SOCKET fd, void *data) // Make sure that the FLTK handling and the timers gets some CPU // time in case of back to back messages Fl::check(); - Timer::checkTimeouts(); + core::Timer::checkTimeouts(); // Also check if we need to stop reading and terminate if (should_disconnect()) @@ -282,7 +283,7 @@ void CConn::resetPassword() ////////////////////// CConnection callback methods ////////////////////// -bool CConn::showMsgBox(MsgBoxFlags flags, const char *title, +bool CConn::showMsgBox(rfb::MsgBoxFlags flags, const char *title, const char *text) { return dlg.showMsgBox(flags, title, text); @@ -312,7 +313,7 @@ void CConn::initDone() // Force a switch to the format and encoding we'd like updatePixelFormat(); - int encNum = encodingNum(::preferredEncoding); + int encNum = rfb::encodingNum(::preferredEncoding); if (encNum != -1) setPreferredEncoding(encNum); } @@ -331,7 +332,7 @@ void CConn::setExtendedDesktopSize(unsigned reason, unsigned result, { CConnection::setExtendedDesktopSize(reason, result, w, h, layout); - if ((reason == reasonClient) && (result != resultSuccess)) { + if ((reason == rfb::reasonClient) && (result != rfb::resultSuccess)) { vlog.error(_("SetDesktopSize failed: %d"), result); return; } @@ -413,11 +414,11 @@ void CConn::bell() fl_beep(); } -bool CConn::dataRect(const Rect& r, int encoding) +bool CConn::dataRect(const core::Rect& r, int encoding) { bool ret; - if (encoding != encodingCopyRect) + if (encoding != rfb::encodingCopyRect) lastServerEncoding = encoding; ret = CConnection::dataRect(r, encoding); @@ -428,13 +429,13 @@ bool CConn::dataRect(const Rect& r, int encoding) return ret; } -void CConn::setCursor(int width, int height, const Point& hotspot, +void CConn::setCursor(int width, int height, const core::Point& hotspot, const uint8_t* data) { desktop->setCursor(width, height, hotspot, data); } -void CConn::setCursorPos(const Point& pos) +void CConn::setCursorPos(const core::Point& pos) { desktop->setCursorPos(pos); } @@ -443,9 +444,10 @@ void CConn::fence(uint32_t flags, unsigned len, const uint8_t data[]) { CMsgHandler::fence(flags, len, data); - if (flags & fenceFlagRequest) { + if (flags & rfb::fenceFlagRequest) { // We handle everything synchronously so we trivially honor these modes - flags = flags & (fenceFlagBlockBefore | fenceFlagBlockAfter); + flags = flags & (rfb::fenceFlagBlockBefore | + rfb::fenceFlagBlockAfter); writer()->writeFence(flags, len, data); return; @@ -503,7 +505,7 @@ void CConn::autoSelectFormatAndEncoding() int newQualityLevel = ::qualityLevel; // Always use Tight - setPreferredEncoding(encodingTight); + setPreferredEncoding(rfb::encodingTight); // Select appropriate quality level if (!noJpeg) { @@ -549,7 +551,7 @@ void CConn::autoSelectFormatAndEncoding() // format and encoding appropriately. void CConn::updatePixelFormat() { - PixelFormat pf; + rfb::PixelFormat pf; if (fullColour) { pf = fullColourPF; @@ -577,7 +579,7 @@ void CConn::handleOptions(void *data) // list is cheap. Avoid overriding what the auto logic has selected // though. if (!autoSelect) { - int encNum = encodingNum(::preferredEncoding); + int encNum = rfb::encodingNum(::preferredEncoding); if (encNum != -1) self->setPreferredEncoding(encNum); diff --git a/vncviewer/CConn.h b/vncviewer/CConn.h index a7b9afdaf7..6eaad4ce5c 100644 --- a/vncviewer/CConn.h +++ b/vncviewer/CConn.h @@ -23,7 +23,7 @@ #include #include -#include + #include "UserDialog.h" namespace network { class Socket; } @@ -71,11 +71,11 @@ class CConn : public rfb::CConnection void framebufferUpdateStart() override; void framebufferUpdateEnd() override; - bool dataRect(const rfb::Rect& r, int encoding) override; + bool dataRect(const core::Rect& r, int encoding) override; - void setCursor(int width, int height, const rfb::Point& hotspot, + void setCursor(int width, int height, const core::Point& hotspot, const uint8_t* data) override; - void setCursorPos(const rfb::Point& pos) override; + void setCursorPos(const core::Point& pos) override; void fence(uint32_t flags, unsigned len, const uint8_t data[]) override; diff --git a/vncviewer/CMakeLists.txt b/vncviewer/CMakeLists.txt index 72904b25f3..d32ad2ea57 100644 --- a/vncviewer/CMakeLists.txt +++ b/vncviewer/CMakeLists.txt @@ -51,7 +51,8 @@ endif() target_include_directories(vncviewer SYSTEM PUBLIC ${FLTK_INCLUDE_DIR}) target_include_directories(vncviewer SYSTEM PUBLIC ${GETTEXT_INCLUDE_DIR}) target_include_directories(vncviewer PUBLIC ${CMAKE_SOURCE_DIR}/common) -target_link_libraries(vncviewer rfb network rdr os ${FLTK_LIBRARIES} ${GETTEXT_LIBRARIES}) +target_link_libraries(vncviewer core rfb network rdr) +target_link_libraries(vncviewer ${FLTK_LIBRARIES} ${GETTEXT_LIBRARIES}) if(WIN32) target_link_libraries(vncviewer msimg32) diff --git a/vncviewer/DesktopWindow.cxx b/vncviewer/DesktopWindow.cxx index 6dbd7d5f74..62b73769a8 100644 --- a/vncviewer/DesktopWindow.cxx +++ b/vncviewer/DesktopWindow.cxx @@ -28,9 +28,12 @@ #include #include -#include +#include +#include +#include + #include -#include +#include #include "DesktopWindow.h" #include "OptionsDialog.h" @@ -70,9 +73,7 @@ static int edge_scroll_size_y = 96; // default: roughly 60 fps for smooth motion #define EDGE_SCROLL_SECONDS_PER_FRAME 0.016666 -using namespace rfb; - -static rfb::LogWriter vlog("DesktopWindow"); +static core::LogWriter vlog("DesktopWindow"); // Global due to http://www.fltk.org/str.php?L2177 and the similar // issue for Fl::event_dispatch. @@ -225,7 +226,7 @@ DesktopWindow::DesktopWindow(int w, int h, const char *name, } // Throughput graph for debugging - if (vlog.getLevel() >= LogWriter::LEVEL_DEBUG) { + if (vlog.getLevel() >= core::LogWriter::LEVEL_DEBUG) { memset(&stats, 0, sizeof(stats)); Fl::add_timeout(0, handleStatsTimeout, this); } @@ -373,14 +374,14 @@ void DesktopWindow::resizeFramebuffer(int new_w, int new_h) void DesktopWindow::setCursor(int width, int height, - const rfb::Point& hotspot, + const core::Point& hotspot, const uint8_t* data) { viewport->setCursor(width, height, hotspot, data); } -void DesktopWindow::setCursorPos(const rfb::Point& pos) +void DesktopWindow::setCursorPos(const core::Point& pos) { if (!mouseGrabbed) { // Do nothing if we do not have the mouse captured. @@ -507,7 +508,7 @@ void DesktopWindow::draw() if (fullscreen_active()) { assert(Fl::screen_count() >= 1); - rfb::Rect windowRect, screenRect; + core::Rect windowRect, screenRect; windowRect.setXYWH(x(), y(), w(), h()); bool foundEnclosedScreen = false; @@ -799,7 +800,7 @@ void DesktopWindow::updateOverlay(void *data) self = (DesktopWindow*)data; - elapsed = msSince(&self->overlayStart); + elapsed = core::msSince(&self->overlayStart); if (elapsed < 500) { self->overlayAlpha = (unsigned)255 * elapsed / 500; @@ -1294,8 +1295,8 @@ void DesktopWindow::reconfigureFullscreen(void* /*data*/) void DesktopWindow::remoteResize(int width, int height) { - ScreenSet layout; - ScreenSet::const_iterator iter; + rfb::ScreenSet layout; + rfb::ScreenSet::const_iterator iter; if (!fullscreen_active() || (width > w()) || (height > h())) { // In windowed mode (or the framebuffer is so large that we need @@ -1331,7 +1332,7 @@ void DesktopWindow::remoteResize(int width, int height) } else { uint32_t id; int sx, sy, sw, sh; - rfb::Rect viewport_rect, screen_rect; + core::Rect viewport_rect, screen_rect; // In full screen we report all screens that are fully covered. @@ -1644,7 +1645,7 @@ void DesktopWindow::handleStatsTimeout(void *data) updates = self->cc->getUpdateCount(); pixels = self->cc->getPixelCount(); pos = self->cc->getPosition(); - elapsed = msSince(&self->statsLastTime); + elapsed = core::msSince(&self->statsLastTime); if (elapsed < 1) elapsed = 1; @@ -1719,11 +1720,11 @@ void DesktopWindow::handleStatsTimeout(void *data) fl_draw(buffer, 5, statsHeight - 5); fl_color(FL_YELLOW); - fl_draw(siPrefix(self->stats[statsCount-1].pps, "pix/s").c_str(), + fl_draw(core::siPrefix(self->stats[statsCount-1].pps, "pix/s").c_str(), 5 + (statsWidth-10)/3, statsHeight - 5); fl_color(FL_RED); - fl_draw(siPrefix(self->stats[statsCount-1].bps * 8, "bps").c_str(), + fl_draw(core::siPrefix(self->stats[statsCount-1].bps * 8, "bps").c_str(), 5 + (statsWidth-10)*2/3, statsHeight - 5); image = surface->image(); diff --git a/vncviewer/DesktopWindow.h b/vncviewer/DesktopWindow.h index ce7960ce6e..3b1e6f00d6 100644 --- a/vncviewer/DesktopWindow.h +++ b/vncviewer/DesktopWindow.h @@ -24,8 +24,6 @@ #include -#include - #include namespace rfb { class ModifiablePixelBuffer; } @@ -56,11 +54,11 @@ class DesktopWindow : public Fl_Window { void resizeFramebuffer(int new_w, int new_h); // New image for the locally rendered cursor - void setCursor(int width, int height, const rfb::Point& hotspot, + void setCursor(int width, int height, const core::Point& hotspot, const uint8_t* data); // Server-provided cursor position - void setCursorPos(const rfb::Point& pos); + void setCursorPos(const core::Point& pos); // Change client LED state void setLEDState(unsigned int state); diff --git a/vncviewer/EmulateMB.cxx b/vncviewer/EmulateMB.cxx index 44d927526b..8947027479 100644 --- a/vncviewer/EmulateMB.cxx +++ b/vncviewer/EmulateMB.cxx @@ -199,7 +199,8 @@ EmulateMB::EmulateMB() { } -void EmulateMB::filterPointerEvent(const rfb::Point& pos, uint16_t buttonMask) +void EmulateMB::filterPointerEvent(const core::Point& pos, + uint16_t buttonMask) { int btstate; int action1, action2; @@ -277,7 +278,7 @@ void EmulateMB::filterPointerEvent(const rfb::Point& pos, uint16_t buttonMask) } } -void EmulateMB::handleTimeout(rfb::Timer *t) +void EmulateMB::handleTimeout(core::Timer* t) { int action1, action2; uint16_t buttonMask; @@ -312,7 +313,8 @@ void EmulateMB::handleTimeout(rfb::Timer *t) state = stateTab[state][4][2]; } -void EmulateMB::sendAction(const rfb::Point& pos, uint16_t buttonMask, int action) +void EmulateMB::sendAction(const core::Point& pos, + uint16_t buttonMask, int action) { assert(action != 0); @@ -332,4 +334,4 @@ int EmulateMB::createButtonMask(uint16_t buttonMask) // Set the left and right buttons according to the action return buttonMask |= emulatedButtonMask; -} \ No newline at end of file +} diff --git a/vncviewer/EmulateMB.h b/vncviewer/EmulateMB.h index 127c34a404..393655e433 100644 --- a/vncviewer/EmulateMB.h +++ b/vncviewer/EmulateMB.h @@ -19,22 +19,24 @@ #ifndef __EMULATEMB__ #define __EMULATEMB__ -#include -#include +#include +#include -class EmulateMB : public rfb::Timer::Callback { +class EmulateMB : public core::Timer::Callback { public: EmulateMB(); - void filterPointerEvent(const rfb::Point& pos, uint16_t buttonMask); + void filterPointerEvent(const core::Point& pos, uint16_t buttonMask); protected: - virtual void sendPointerEvent(const rfb::Point& pos, uint16_t buttonMask)=0; + virtual void sendPointerEvent(const core::Point& pos, + uint16_t buttonMask)=0; - void handleTimeout(rfb::Timer *t) override; + void handleTimeout(core::Timer* t) override; private: - void sendAction(const rfb::Point& pos, uint16_t buttonMask, int action); + void sendAction(const core::Point& pos, uint16_t buttonMask, + int action); int createButtonMask(uint16_t buttonMask); @@ -42,8 +44,8 @@ class EmulateMB : public rfb::Timer::Callback { int state; uint16_t emulatedButtonMask; uint16_t lastButtonMask; - rfb::Point lastPos, origPos; - rfb::Timer timer; + core::Point lastPos, origPos; + core::Timer timer; }; #endif diff --git a/vncviewer/GestureHandler.cxx b/vncviewer/GestureHandler.cxx index 121ceecf22..2ede991b22 100644 --- a/vncviewer/GestureHandler.cxx +++ b/vncviewer/GestureHandler.cxx @@ -24,12 +24,12 @@ #include #include -#include -#include +#include +#include #include "GestureHandler.h" -static rfb::LogWriter vlog("GestureHandler"); +static core::LogWriter vlog("GestureHandler"); static const unsigned char GH_NOGESTURE = 0; static const unsigned char GH_ONETAP = 1; @@ -81,7 +81,7 @@ void GestureHandler::handleTouchBegin(int id, double x, double y) // Did it take too long between touches that we should no longer // consider this a single gesture? if ((tracked.size() > 0) && - (rfb::msSince(&tracked.begin()->second.started) > GH_MULTITOUCH_TIMEOUT)) { + (core::msSince(&tracked.begin()->second.started) > GH_MULTITOUCH_TIMEOUT)) { state = GH_NOGESTURE; ignored.insert(id); return; @@ -257,12 +257,12 @@ void GestureHandler::handleTouchEnd(int id) // Waiting for all touches to release? (i.e. some tap) if (waitingRelease) { // Were all touches released at roughly the same time? - if (rfb::msSince(&releaseStart) > GH_MULTITOUCH_TIMEOUT) + if (core::msSince(&releaseStart) > GH_MULTITOUCH_TIMEOUT) state = GH_NOGESTURE; // Did too long time pass between press and release? for (iter = tracked.begin(); iter != tracked.end(); ++iter) { - if (rfb::msSince(&iter->second.started) > GH_TAP_TIMEOUT) { + if (core::msSince(&iter->second.started) > GH_TAP_TIMEOUT) { state = GH_NOGESTURE; break; } @@ -323,7 +323,7 @@ bool GestureHandler::hasDetectedGesture() return true; } -void GestureHandler::handleTimeout(rfb::Timer* t) +void GestureHandler::handleTimeout(core::Timer* t) { if (t == &longpressTimer) longpressTimeout(); diff --git a/vncviewer/GestureHandler.h b/vncviewer/GestureHandler.h index 2b31703a9e..1c2134c04a 100644 --- a/vncviewer/GestureHandler.h +++ b/vncviewer/GestureHandler.h @@ -23,11 +23,11 @@ #include #include -#include +#include #include "GestureEvent.h" -class GestureHandler : public rfb::Timer::Callback { +class GestureHandler : public core::Timer::Callback { public: GestureHandler(); virtual ~GestureHandler(); @@ -42,7 +42,7 @@ class GestureHandler : public rfb::Timer::Callback { private: bool hasDetectedGesture(); - void handleTimeout(rfb::Timer* t) override; + void handleTimeout(core::Timer* t) override; void longpressTimeout(); void twoTouchTimeout(); @@ -74,8 +74,8 @@ class GestureHandler : public rfb::Timer::Callback { bool waitingRelease; struct timeval releaseStart; - rfb::Timer longpressTimer; - rfb::Timer twoTouchTimer; + core::Timer longpressTimer; + core::Timer twoTouchTimer; }; #endif // __GESTUREHANDLER_H__ diff --git a/vncviewer/KeyboardMacOS.mm b/vncviewer/KeyboardMacOS.mm index e0a10dc8d2..9ef2fc93ad 100644 --- a/vncviewer/KeyboardMacOS.mm +++ b/vncviewer/KeyboardMacOS.mm @@ -35,11 +35,12 @@ // And this is still missing const int kVK_Menu = 0x6E; +#include + #define XK_LATIN1 #define XK_MISCELLANY #include #include -#include #include #define NoSymbol 0 @@ -51,7 +52,7 @@ extern const unsigned short code_map_osx_to_qnum[]; extern const unsigned int code_map_osx_to_qnum_len; -static rfb::LogWriter vlog("KeyboardMacOS"); +static core::LogWriter vlog("KeyboardMacOS"); static const int kvk_map[][2] = { { kVK_Return, XK_Return }, diff --git a/vncviewer/KeyboardWin32.cxx b/vncviewer/KeyboardWin32.cxx index 1caf48637c..7628621763 100644 --- a/vncviewer/KeyboardWin32.cxx +++ b/vncviewer/KeyboardWin32.cxx @@ -31,12 +31,13 @@ #include +#include + #define XK_MISCELLANY #define XK_XKB_KEYS #define XK_KOREAN #include #include -#include #include #define NoSymbol 0 @@ -50,7 +51,7 @@ // Used to detect fake input (0xaa is not a real key) static const WORD SCAN_FAKE = 0xaa; -static rfb::LogWriter vlog("KeyboardWin32"); +static core::LogWriter vlog("KeyboardWin32"); // Layout independent keys static const UINT vkey_map[][3] = { diff --git a/vncviewer/KeyboardX11.cxx b/vncviewer/KeyboardX11.cxx index 0ee1d4f65b..973278fc07 100644 --- a/vncviewer/KeyboardX11.cxx +++ b/vncviewer/KeyboardX11.cxx @@ -27,7 +27,8 @@ #include #include -#include +#include + #include #include "i18n.h" @@ -39,7 +40,7 @@ extern const struct _code_map_xkb_to_qnum { } code_map_xkb_to_qnum[]; extern const unsigned int code_map_xkb_to_qnum_len; -static rfb::LogWriter vlog("KeyboardX11"); +static core::LogWriter vlog("KeyboardX11"); KeyboardX11::KeyboardX11(KeyboardHandler* handler_) : Keyboard(handler_) diff --git a/vncviewer/MonitorIndicesParameter.cxx b/vncviewer/MonitorIndicesParameter.cxx index 957ade06c5..1e2efdbcd3 100644 --- a/vncviewer/MonitorIndicesParameter.cxx +++ b/vncviewer/MonitorIndicesParameter.cxx @@ -30,13 +30,14 @@ #include #include "i18n.h" + #include -#include + +#include #include "MonitorIndicesParameter.h" -using namespace rfb; -static LogWriter vlog("MonitorIndicesParameter"); +static core::LogWriter vlog("MonitorIndicesParameter"); MonitorIndicesParameter::MonitorIndicesParameter(const char* name_, const char* desc_, const char* v) : StringParameter(name_, desc_, v) {} diff --git a/vncviewer/MonitorIndicesParameter.h b/vncviewer/MonitorIndicesParameter.h index d91c84fe5d..fa6a204553 100644 --- a/vncviewer/MonitorIndicesParameter.h +++ b/vncviewer/MonitorIndicesParameter.h @@ -22,9 +22,9 @@ #include #include -#include +#include -class MonitorIndicesParameter: public rfb::StringParameter { +class MonitorIndicesParameter: public core::StringParameter { public: MonitorIndicesParameter(const char* name_, const char* desc_, const char* v); std::set getParam(); diff --git a/vncviewer/OptionsDialog.cxx b/vncviewer/OptionsDialog.cxx index c5f21b2484..5a3d136132 100644 --- a/vncviewer/OptionsDialog.cxx +++ b/vncviewer/OptionsDialog.cxx @@ -53,9 +53,6 @@ #include #include -using namespace std; -using namespace rfb; - std::map OptionsDialog::callbacks; static std::set instances; @@ -162,24 +159,24 @@ void OptionsDialog::loadOptions(void) /* Compression */ autoselectCheckbox->value(autoSelect); - int encNum = encodingNum(preferredEncoding); + int encNum = rfb::encodingNum(preferredEncoding); switch (encNum) { - case encodingTight: + case rfb::encodingTight: tightButton->setonly(); break; - case encodingZRLE: + case rfb::encodingZRLE: zrleButton->setonly(); break; - case encodingHextile: + case rfb::encodingHextile: hextileButton->setonly(); break; #ifdef HAVE_H264 - case encodingH264: + case rfb::encodingH264: h264Button->setonly(); break; #endif - case encodingRaw: + case rfb::encodingRaw: rawButton->setonly(); break; } @@ -215,11 +212,11 @@ void OptionsDialog::loadOptions(void) #if defined(HAVE_GNUTLS) || defined(HAVE_NETTLE) /* Security */ - Security security(SecurityClient::secTypes); + rfb::Security security(rfb::SecurityClient::secTypes); - list secTypes; + std::list secTypes; - list secTypesExt; + std::list secTypesExt; encNoneCheckbox->value(false); #ifdef HAVE_GNUTLS @@ -237,11 +234,11 @@ void OptionsDialog::loadOptions(void) secTypes = security.GetEnabledSecTypes(); for (uint8_t type : secTypes) { switch (type) { - case secTypeNone: + case rfb::secTypeNone: encNoneCheckbox->value(true); authNoneCheckbox->value(true); break; - case secTypeVncAuth: + case rfb::secTypeVncAuth: encNoneCheckbox->value(true); authVncCheckbox->value(true); break; @@ -251,49 +248,49 @@ void OptionsDialog::loadOptions(void) secTypesExt = security.GetEnabledExtSecTypes(); for (uint32_t type : secTypesExt) { switch (type) { - case secTypePlain: + case rfb::secTypePlain: encNoneCheckbox->value(true); authPlainCheckbox->value(true); break; #ifdef HAVE_GNUTLS - case secTypeTLSNone: + case rfb::secTypeTLSNone: encTLSCheckbox->value(true); authNoneCheckbox->value(true); break; - case secTypeTLSVnc: + case rfb::secTypeTLSVnc: encTLSCheckbox->value(true); authVncCheckbox->value(true); break; - case secTypeTLSPlain: + case rfb::secTypeTLSPlain: encTLSCheckbox->value(true); authPlainCheckbox->value(true); break; - case secTypeX509None: + case rfb::secTypeX509None: encX509Checkbox->value(true); authNoneCheckbox->value(true); break; - case secTypeX509Vnc: + case rfb::secTypeX509Vnc: encX509Checkbox->value(true); authVncCheckbox->value(true); break; - case secTypeX509Plain: + case rfb::secTypeX509Plain: encX509Checkbox->value(true); authPlainCheckbox->value(true); break; #endif #ifdef HAVE_NETTLE - case secTypeRA2: - case secTypeRA256: + case rfb::secTypeRA2: + case rfb::secTypeRA256: encRSAAESCheckbox->value(true); authVncCheckbox->value(true); authPlainCheckbox->value(true); break; - case secTypeRA2ne: - case secTypeRAne256: + case rfb::secTypeRA2ne: + case rfb::secTypeRAne256: authVncCheckbox->value(true); /* fall through */ - case secTypeDH: - case secTypeMSLogonII: + case rfb::secTypeDH: + case rfb::secTypeMSLogonII: encNoneCheckbox->value(true); authPlainCheckbox->value(true); break; @@ -303,8 +300,8 @@ void OptionsDialog::loadOptions(void) } #ifdef HAVE_GNUTLS - caInput->value(CSecurityTLS::X509CA); - crlInput->value(CSecurityTLS::X509CRL); + caInput->value(rfb::CSecurityTLS::X509CA); + crlInput->value(rfb::CSecurityTLS::X509CRL); handleX509(encX509Checkbox, this); #endif @@ -362,17 +359,17 @@ void OptionsDialog::storeOptions(void) autoSelect.setParam(autoselectCheckbox->value()); if (tightButton->value()) - preferredEncoding.setParam(encodingName(encodingTight)); + preferredEncoding.setParam(rfb::encodingName(rfb::encodingTight)); else if (zrleButton->value()) - preferredEncoding.setParam(encodingName(encodingZRLE)); + preferredEncoding.setParam(rfb::encodingName(rfb::encodingZRLE)); else if (hextileButton->value()) - preferredEncoding.setParam(encodingName(encodingHextile)); + preferredEncoding.setParam(rfb::encodingName(rfb::encodingHextile)); #ifdef HAVE_H264 else if (h264Button->value()) - preferredEncoding.setParam(encodingName(encodingH264)); + preferredEncoding.setParam(rfb::encodingName(rfb::encodingH264)); #endif else if (rawButton->value()) - preferredEncoding.setParam(encodingName(encodingRaw)); + preferredEncoding.setParam(rfb::encodingName(rfb::encodingRaw)); fullColour.setParam(fullcolorCheckbox->value()); if (verylowcolorCheckbox->value()) @@ -389,26 +386,26 @@ void OptionsDialog::storeOptions(void) #if defined(HAVE_GNUTLS) || defined(HAVE_NETTLE) /* Security */ - Security security; + rfb::Security security; /* Process security types which don't use encryption */ if (encNoneCheckbox->value()) { if (authNoneCheckbox->value()) - security.EnableSecType(secTypeNone); + security.EnableSecType(rfb::secTypeNone); if (authVncCheckbox->value()) { - security.EnableSecType(secTypeVncAuth); + security.EnableSecType(rfb::secTypeVncAuth); #ifdef HAVE_NETTLE - security.EnableSecType(secTypeRA2ne); - security.EnableSecType(secTypeRAne256); + security.EnableSecType(rfb::secTypeRA2ne); + security.EnableSecType(rfb::secTypeRAne256); #endif } if (authPlainCheckbox->value()) { - security.EnableSecType(secTypePlain); + security.EnableSecType(rfb::secTypePlain); #ifdef HAVE_NETTLE - security.EnableSecType(secTypeRA2ne); - security.EnableSecType(secTypeRAne256); - security.EnableSecType(secTypeDH); - security.EnableSecType(secTypeMSLogonII); + security.EnableSecType(rfb::secTypeRA2ne); + security.EnableSecType(rfb::secTypeRAne256); + security.EnableSecType(rfb::secTypeDH); + security.EnableSecType(rfb::secTypeMSLogonII); #endif } } @@ -417,34 +414,34 @@ void OptionsDialog::storeOptions(void) /* Process security types which use TLS encryption */ if (encTLSCheckbox->value()) { if (authNoneCheckbox->value()) - security.EnableSecType(secTypeTLSNone); + security.EnableSecType(rfb::secTypeTLSNone); if (authVncCheckbox->value()) - security.EnableSecType(secTypeTLSVnc); + security.EnableSecType(rfb::secTypeTLSVnc); if (authPlainCheckbox->value()) - security.EnableSecType(secTypeTLSPlain); + security.EnableSecType(rfb::secTypeTLSPlain); } /* Process security types which use X509 encryption */ if (encX509Checkbox->value()) { if (authNoneCheckbox->value()) - security.EnableSecType(secTypeX509None); + security.EnableSecType(rfb::secTypeX509None); if (authVncCheckbox->value()) - security.EnableSecType(secTypeX509Vnc); + security.EnableSecType(rfb::secTypeX509Vnc); if (authPlainCheckbox->value()) - security.EnableSecType(secTypeX509Plain); + security.EnableSecType(rfb::secTypeX509Plain); } - CSecurityTLS::X509CA.setParam(caInput->value()); - CSecurityTLS::X509CRL.setParam(crlInput->value()); + rfb::CSecurityTLS::X509CA.setParam(caInput->value()); + rfb::CSecurityTLS::X509CRL.setParam(crlInput->value()); #endif #ifdef HAVE_NETTLE if (encRSAAESCheckbox->value()) { - security.EnableSecType(secTypeRA2); - security.EnableSecType(secTypeRA256); + security.EnableSecType(rfb::secTypeRA2); + security.EnableSecType(rfb::secTypeRA256); } #endif - SecurityClient::secTypes.setParam(security.ToString()); + rfb::SecurityClient::secTypes.setParam(security.ToString()); #endif /* Input */ diff --git a/vncviewer/PlatformPixelBuffer.cxx b/vncviewer/PlatformPixelBuffer.cxx index 0f152e114c..9916f1e4ec 100644 --- a/vncviewer/PlatformPixelBuffer.cxx +++ b/vncviewer/PlatformPixelBuffer.cxx @@ -33,11 +33,12 @@ #include #include -#include +#include +#include #include "PlatformPixelBuffer.h" -static rfb::LogWriter vlog("PlatformPixelBuffer"); +static core::LogWriter vlog("PlatformPixelBuffer"); PlatformPixelBuffer::PlatformPixelBuffer(int width, int height) : FullFramePixelBuffer(rfb::PixelFormat(32, 24, false, true, @@ -91,17 +92,17 @@ PlatformPixelBuffer::~PlatformPixelBuffer() #endif } -void PlatformPixelBuffer::commitBufferRW(const rfb::Rect& r) +void PlatformPixelBuffer::commitBufferRW(const core::Rect& r) { FullFramePixelBuffer::commitBufferRW(r); mutex.lock(); - damage.assign_union(rfb::Region(r)); + damage.assign_union(r); mutex.unlock(); } -rfb::Rect PlatformPixelBuffer::getDamage(void) +core::Rect PlatformPixelBuffer::getDamage(void) { - rfb::Rect r; + core::Rect r; mutex.lock(); r = damage.get_bounding_rect(); diff --git a/vncviewer/PlatformPixelBuffer.h b/vncviewer/PlatformPixelBuffer.h index 24763d4666..498b337f64 100644 --- a/vncviewer/PlatformPixelBuffer.h +++ b/vncviewer/PlatformPixelBuffer.h @@ -28,10 +28,10 @@ #include -#include +#include +#include #include -#include #include "Surface.h" @@ -40,16 +40,16 @@ class PlatformPixelBuffer: public rfb::FullFramePixelBuffer, public Surface { PlatformPixelBuffer(int width, int height); ~PlatformPixelBuffer(); - void commitBufferRW(const rfb::Rect& r) override; + void commitBufferRW(const core::Rect& r) override; - rfb::Rect getDamage(void); + core::Rect getDamage(void); using rfb::FullFramePixelBuffer::width; using rfb::FullFramePixelBuffer::height; protected: - os::Mutex mutex; - rfb::Region damage; + core::Mutex mutex; + core::Region damage; #if !defined(WIN32) && !defined(__APPLE__) protected: diff --git a/vncviewer/ServerDialog.cxx b/vncviewer/ServerDialog.cxx index e9d4e75bb6..26f9fc49d5 100644 --- a/vncviewer/ServerDialog.cxx +++ b/vncviewer/ServerDialog.cxx @@ -25,6 +25,11 @@ #include #include +// FIXME: Workaround for FLTK including windows.h +#ifdef WIN32 +#include +#endif + #include #include #include @@ -35,13 +40,14 @@ #include #include -#include +#include +#include +#include +#include -#include +#include -#include -#include -#include +#include #include "fltk/layout.h" #include "fltk/util.h" @@ -51,11 +57,7 @@ #include "vncviewer.h" #include "parameters.h" - -using namespace std; -using namespace rfb; - -static LogWriter vlog("ServerDialog"); +static core::LogWriter vlog("ServerDialog"); const char* SERVER_HISTORY="tigervnc.history"; @@ -139,7 +141,7 @@ void ServerDialog::run(const char* servername, char *newservername) dialog.loadServerHistory(); dialog.serverName->clear(); - for (const string& entry : dialog.serverHistory) + for (const std::string& entry : dialog.serverHistory) fltk_menu_add(dialog.serverName->menubutton(), entry.c_str(), 0, nullptr); } catch (std::exception& e) { @@ -170,7 +172,7 @@ void ServerDialog::handleLoad(Fl_Widget* /*widget*/, void* data) ServerDialog *dialog = (ServerDialog*)data; if (dialog->usedDir.empty()) - dialog->usedDir = os::getuserhomedir(); + dialog->usedDir = core::getuserhomedir(); Fl_File_Chooser* file_chooser = new Fl_File_Chooser(dialog->usedDir.c_str(), _("TigerVNC configuration (*.tigervnc)"), @@ -210,7 +212,7 @@ void ServerDialog::handleSaveAs(Fl_Widget* /*widget*/, void* data) const char* servername = dialog->serverName->value(); const char* filename; if (dialog->usedDir.empty()) - dialog->usedDir = os::getuserhomedir(); + dialog->usedDir = core::getuserhomedir(); Fl_File_Chooser* file_chooser = new Fl_File_Chooser(dialog->usedDir.c_str(), _("TigerVNC configuration (*.tigervnc)"), @@ -309,19 +311,20 @@ void ServerDialog::handleConnect(Fl_Widget* /*widget*/, void *data) } -static bool same_server(const string& a, const string& b) +static bool same_server(const std::string& a, const std::string& b) { - string hostA, hostB; + std::string hostA, hostB; int portA, portB; #ifndef WIN32 - if ((a.find("/") != string::npos) || (b.find("/") != string::npos)) + if ((a.find("/") != std::string::npos) || + (b.find("/") != std::string::npos)) return a == b; #endif try { - getHostAndPort(a.c_str(), &hostA, &portA); - getHostAndPort(b.c_str(), &hostB, &portB); + network::getHostAndPort(a.c_str(), &hostA, &portA); + network::getHostAndPort(b.c_str(), &hostB, &portB); } catch (std::exception& e) { return false; } @@ -338,7 +341,7 @@ static bool same_server(const string& a, const string& b) void ServerDialog::loadServerHistory() { - list rawHistory; + std::list rawHistory; serverHistory.clear(); @@ -346,7 +349,7 @@ void ServerDialog::loadServerHistory() rawHistory = loadHistoryFromRegKey(); #else - const char* stateDir = os::getvncstatedir(); + const char* stateDir = core::getvncstatedir(); if (stateDir == nullptr) throw std::runtime_error(_("Could not determine VNC state directory path")); @@ -360,8 +363,8 @@ void ServerDialog::loadServerHistory() // no history file return; } - std::string msg = format(_("Could not open \"%s\""), filepath); - throw rdr::posix_error(msg.c_str(), errno); + throw core::posix_error( + core::format(_("Could not open \"%s\""), filepath), errno); } int lineNr = 0; @@ -375,20 +378,21 @@ void ServerDialog::loadServerHistory() break; fclose(f); - std::string msg = format(_("Failed to read line %d in " - "file \"%s\""), lineNr, filepath); - throw rdr::posix_error(msg.c_str(), errno); + throw core::posix_error( + core::format(_("Failed to read line %d in file \"%s\""), + lineNr, filepath), + errno); } int len = strlen(line); if (len == (sizeof(line) - 1)) { fclose(f); - throw std::runtime_error(format("%s: %s", - format(_("Failed to read line %d " - "in file %s"), - lineNr, filepath).c_str(), - _("Line too long"))); + throw std::runtime_error(core::format( + "%s: %s", + core::format(_("Failed to read line %d in file \"%s\""), + lineNr, filepath).c_str(), + _("Line too long"))); } if ((len > 0) && (line[len-1] == '\n')) { @@ -410,9 +414,11 @@ void ServerDialog::loadServerHistory() #endif // Filter out duplicates, even if they have different formats - for (const string& entry : rawHistory) { + for (const std::string& entry : rawHistory) { if (std::find_if(serverHistory.begin(), serverHistory.end(), - [&entry](const string& s) { return same_server(s, entry); }) != serverHistory.end()) + [&entry](const std::string& s) { + return same_server(s, entry); + }) != serverHistory.end()) continue; serverHistory.push_back(entry); } @@ -425,7 +431,7 @@ void ServerDialog::saveServerHistory() return; #endif - const char* stateDir = os::getvncstatedir(); + const char* stateDir = core::getvncstatedir(); if (stateDir == nullptr) throw std::runtime_error(_("Could not determine VNC state directory path")); @@ -435,13 +441,13 @@ void ServerDialog::saveServerHistory() /* Write server history to file */ FILE* f = fopen(filepath, "w+"); if (!f) { - std::string msg = format(_("Could not open \"%s\""), filepath); - throw rdr::posix_error(msg.c_str(), errno); + std::string msg = core::format(_("Could not open \"%s\""), filepath); + throw core::posix_error(msg.c_str(), errno); } // Save the last X elements to the config file. size_t count = 0; - for (const string& entry : serverHistory) { + for (const std::string& entry : serverHistory) { if (++count > SERVER_HISTORY_SIZE) break; fprintf(f, "%s\n", entry.c_str()); diff --git a/vncviewer/Surface_Win32.cxx b/vncviewer/Surface_Win32.cxx index c992dbea40..c00cbc065f 100644 --- a/vncviewer/Surface_Win32.cxx +++ b/vncviewer/Surface_Win32.cxx @@ -25,7 +25,7 @@ #include #include -#include +#include #include "Surface.h" @@ -57,10 +57,10 @@ void Surface::draw(int src_x, int src_y, int dst_x, int dst_y, dc = CreateCompatibleDC(fl_gc); if (!dc) - throw rdr::win32_error("CreateCompatibleDC", GetLastError()); + throw core::win32_error("CreateCompatibleDC", GetLastError()); if (!SelectObject(dc, bitmap)) - throw rdr::win32_error("SelectObject", GetLastError()); + throw core::win32_error("SelectObject", GetLastError()); if (!BitBlt(fl_gc, dst_x, dst_y, dst_w, dst_h, dc, src_x, src_y, SRCCOPY)) { @@ -70,7 +70,7 @@ void Surface::draw(int src_x, int src_y, int dst_x, int dst_y, // with it. For now, we've only seen this error and for this function // so only ignore this combination. if (GetLastError() != ERROR_INVALID_HANDLE) - throw rdr::win32_error("BitBlt", GetLastError()); + throw core::win32_error("BitBlt", GetLastError()); } DeleteDC(dc); @@ -83,10 +83,10 @@ void Surface::draw(Surface* dst, int src_x, int src_y, dstdc = CreateCompatibleDC(nullptr); if (!dstdc) - throw rdr::win32_error("CreateCompatibleDC", GetLastError()); + throw core::win32_error("CreateCompatibleDC", GetLastError()); if (!SelectObject(dstdc, dst->bitmap)) - throw rdr::win32_error("SelectObject", GetLastError()); + throw core::win32_error("SelectObject", GetLastError()); origdc = fl_gc; fl_gc = dstdc; @@ -113,15 +113,15 @@ void Surface::blend(Surface* dst, int src_x, int src_y, dstdc = CreateCompatibleDC(nullptr); if (!dstdc) - throw rdr::win32_error("CreateCompatibleDC", GetLastError()); + throw core::win32_error("CreateCompatibleDC", GetLastError()); srcdc = CreateCompatibleDC(nullptr); if (!srcdc) - throw rdr::win32_error("CreateCompatibleDC", GetLastError()); + throw core::win32_error("CreateCompatibleDC", GetLastError()); if (!SelectObject(dstdc, dst->bitmap)) - throw rdr::win32_error("SelectObject", GetLastError()); + throw core::win32_error("SelectObject", GetLastError()); if (!SelectObject(srcdc, bitmap)) - throw rdr::win32_error("SelectObject", GetLastError()); + throw core::win32_error("SelectObject", GetLastError()); blend.BlendOp = AC_SRC_OVER; blend.BlendFlags = 0; @@ -136,7 +136,7 @@ void Surface::blend(Surface* dst, int src_x, int src_y, // with it. For now, we've only seen this error and for this function // so only ignore this combination. if (GetLastError() != ERROR_INVALID_HANDLE) - throw rdr::win32_error("BitBlt", GetLastError()); + throw core::win32_error("BitBlt", GetLastError()); } DeleteDC(srcdc); @@ -161,7 +161,7 @@ void Surface::alloc() bitmap = CreateDIBSection(nullptr, (BITMAPINFO*)&bih, DIB_RGB_COLORS, (void**)&data, nullptr, 0); if (!bitmap) - throw rdr::win32_error("CreateDIBSection", GetLastError()); + throw core::win32_error("CreateDIBSection", GetLastError()); } void Surface::dealloc() diff --git a/vncviewer/UserDialog.cxx b/vncviewer/UserDialog.cxx index c6cc02f78d..b20a5d612b 100644 --- a/vncviewer/UserDialog.cxx +++ b/vncviewer/UserDialog.cxx @@ -36,8 +36,9 @@ #include #include -#include +#include +#include #include #include @@ -54,8 +55,6 @@ #include "../media/insecure.xpm" #pragma GCC diagnostic pop -using namespace rfb; - static Fl_Pixmap secure_icon(secure); static Fl_Pixmap insecure_icon(insecure); @@ -120,12 +119,12 @@ void UserDialog::getUserPasswd(bool secure_, std::string* user, fp = fopen(passwordFileName, "rb"); if (!fp) - throw rdr::posix_error(_("Opening password file failed"), errno); + throw core::posix_error(_("Opening password file failed"), errno); obfPwd.resize(fread(obfPwd.data(), 1, obfPwd.size(), fp)); fclose(fp); - *password = deobfuscate(obfPwd.data(), obfPwd.size()); + *password = rfb::deobfuscate(obfPwd.data(), obfPwd.size()); return; } @@ -254,7 +253,8 @@ void UserDialog::getUserPasswd(bool secure_, std::string* user, throw rfb::auth_cancelled(); } -bool UserDialog::showMsgBox(MsgBoxFlags flags, const char* title, const char* text) +bool UserDialog::showMsgBox(rfb::MsgBoxFlags flags, + const char* title, const char* text) { char buffer[1024]; @@ -267,14 +267,14 @@ bool UserDialog::showMsgBox(MsgBoxFlags flags, const char* title, const char* te fl_message_title(title); switch (flags & 0xf) { - case M_OKCANCEL: + case rfb::M_OKCANCEL: return fl_choice("%s", nullptr, fl_ok, fl_cancel, buffer) == 1; - case M_YESNO: + case rfb::M_YESNO: return fl_choice("%s", nullptr, fl_yes, fl_no, buffer) == 1; - case M_OK: + case rfb::M_OK: default: - if (((flags & 0xf0) == M_ICONERROR) || - ((flags & 0xf0) == M_ICONWARNING)) + if (((flags & 0xf0) == rfb::M_ICONERROR) || + ((flags & 0xf0) == rfb::M_ICONWARNING)) fl_alert("%s", buffer); else fl_message("%s", buffer); diff --git a/vncviewer/UserDialog.h b/vncviewer/UserDialog.h index ddafbc3c25..22799fb956 100644 --- a/vncviewer/UserDialog.h +++ b/vncviewer/UserDialog.h @@ -19,8 +19,6 @@ #ifndef __USERDIALOG_H__ #define __USERDIALOG_H__ -#include - class UserDialog { public: diff --git a/vncviewer/Viewport.cxx b/vncviewer/Viewport.cxx index 8c3b5dc549..77872f0202 100644 --- a/vncviewer/Viewport.cxx +++ b/vncviewer/Viewport.cxx @@ -25,10 +25,13 @@ #include #include +#include + +#include +#include + #include -#include #include -#include // FLTK can pull in the X11 headers on some systems #ifndef XK_VoidSymbol @@ -68,9 +71,7 @@ #include "cocoa.h" #endif -using namespace rfb; - -static rfb::LogWriter vlog("Viewport"); +static core::LogWriter vlog("Viewport"); // Menu constants @@ -126,7 +127,7 @@ Viewport::Viewport(int w, int h, const rfb::PixelFormat& /*serverPF*/, CConn* cc OptionsDialog::addCallback(handleOptions, this); // Make sure we have an initial blank cursor set - setCursor(0, 0, rfb::Point(0, 0), nullptr); + setCursor(0, 0, {0, 0}, nullptr); } @@ -166,7 +167,7 @@ const rfb::PixelFormat &Viewport::getPreferredPF() void Viewport::updateWindow() { - Rect r; + core::Rect r; r = frameBuffer->getDamage(); damage(FL_DAMAGE_USER1, r.tl.x + x(), r.tl.y + y(), r.width(), r.height()); @@ -182,7 +183,8 @@ static const char * dotcursor_xpm[] = { " ... ", " "}; -void Viewport::setCursor(int width, int height, const Point& hotspot, +void Viewport::setCursor(int width, int height, + const core::Point& hotspot, const uint8_t* data) { int i; @@ -292,29 +294,32 @@ void Viewport::pushLEDState() unsigned int ledState; // Server support? - if (cc->server.ledState() == ledUnknown) + if (cc->server.ledState() == rfb::ledUnknown) return; ledState = keyboard->getLEDState(); - if (ledState == ledUnknown) + if (ledState == rfb::ledUnknown) return; #if defined(__APPLE__) // No support for Scroll Lock // - ledState |= (cc->server.ledState() & ledScrollLock); + ledState |= (cc->server.ledState() & rfb::ledScrollLock); #endif - if ((ledState & ledCapsLock) != (cc->server.ledState() & ledCapsLock)) { + if ((ledState & rfb::ledCapsLock) != + (cc->server.ledState() & rfb::ledCapsLock)) { vlog.debug("Inserting fake CapsLock to get in sync with server"); handleKeyPress(FAKE_KEY_CODE, 0x3a, XK_Caps_Lock); handleKeyRelease(FAKE_KEY_CODE); } - if ((ledState & ledNumLock) != (cc->server.ledState() & ledNumLock)) { + if ((ledState & rfb::ledNumLock) != + (cc->server.ledState() & rfb::ledNumLock)) { vlog.debug("Inserting fake NumLock to get in sync with server"); handleKeyPress(FAKE_KEY_CODE, 0x45, XK_Num_Lock); handleKeyRelease(FAKE_KEY_CODE); } - if ((ledState & ledScrollLock) != (cc->server.ledState() & ledScrollLock)) { + if ((ledState & rfb::ledScrollLock) != + (cc->server.ledState() & rfb::ledScrollLock)) { vlog.debug("Inserting fake ScrollLock to get in sync with server"); handleKeyPress(FAKE_KEY_CODE, 0x46, XK_Scroll_Lock); handleKeyRelease(FAKE_KEY_CODE); @@ -370,12 +375,12 @@ int Viewport::handle(int event) switch (event) { case FL_PASTE: - if (!isValidUTF8(Fl::event_text(), Fl::event_length())) { + if (!core::isValidUTF8(Fl::event_text(), Fl::event_length())) { vlog.error("Invalid UTF-8 sequence in system clipboard"); return 1; } - filtered = convertLF(Fl::event_text(), Fl::event_length()); + filtered = core::convertLF(Fl::event_text(), Fl::event_length()); vlog.debug("Sending clipboard data (%d bytes)", (int)filtered.size()); @@ -396,7 +401,7 @@ int Viewport::handle(int event) case FL_LEAVE: window()->cursor(FL_CURSOR_DEFAULT); // We want a last move event to help trigger edge stuff - handlePointerEvent(Point(Fl::event_x() - x(), Fl::event_y() - y()), 0); + handlePointerEvent({Fl::event_x() - x(), Fl::event_y() - y()}, 0); return 1; case FL_PUSH: @@ -439,11 +444,11 @@ int Viewport::handle(int event) // A quick press of the wheel "button", followed by a immediate // release below - handlePointerEvent(Point(Fl::event_x() - x(), Fl::event_y() - y()), + handlePointerEvent({Fl::event_x() - x(), Fl::event_y() - y()}, buttonMask | wheelMask); } - handlePointerEvent(Point(Fl::event_x() - x(), Fl::event_y() - y()), buttonMask); + handlePointerEvent({Fl::event_x() - x(), Fl::event_y() - y()}, buttonMask); return 1; case FL_FOCUS: @@ -480,7 +485,8 @@ int Viewport::handle(int event) return Fl_Widget::handle(event); } -void Viewport::sendPointerEvent(const rfb::Point& pos, uint16_t buttonMask) +void Viewport::sendPointerEvent(const core::Point& pos, + uint16_t buttonMask) { if (viewOnly) return; @@ -570,7 +576,8 @@ void Viewport::flushPendingClipboard() } -void Viewport::handlePointerEvent(const rfb::Point& pos, uint16_t buttonMask) +void Viewport::handlePointerEvent(const core::Point& pos, + uint16_t buttonMask) { filterPointerEvent(pos, buttonMask); } diff --git a/vncviewer/Viewport.h b/vncviewer/Viewport.h index 41696d9d74..8980f673d2 100644 --- a/vncviewer/Viewport.h +++ b/vncviewer/Viewport.h @@ -20,7 +20,7 @@ #ifndef __VIEWPORT_H__ #define __VIEWPORT_H__ -#include +#include #include @@ -49,7 +49,7 @@ class Viewport : public Fl_Widget, protected EmulateMB, void updateWindow(); // New image for the locally rendered cursor - void setCursor(int width, int height, const rfb::Point& hotspot, + void setCursor(int width, int height, const core::Point& hotspot, const uint8_t* data); // Change client LED state @@ -71,7 +71,8 @@ class Viewport : public Fl_Widget, protected EmulateMB, int handle(int event) override; protected: - void sendPointerEvent(const rfb::Point& pos, uint16_t buttonMask) override; + void sendPointerEvent(const core::Point& pos, + uint16_t buttonMask) override; private: bool hasFocus(); @@ -80,7 +81,7 @@ class Viewport : public Fl_Widget, protected EmulateMB, void flushPendingClipboard(); - void handlePointerEvent(const rfb::Point& pos, uint16_t buttonMask); + void handlePointerEvent(const core::Point& pos, uint16_t buttonMask); static void handlePointerTimeout(void *data); void resetKeyboard(); @@ -105,7 +106,7 @@ class Viewport : public Fl_Widget, protected EmulateMB, PlatformPixelBuffer* frameBuffer; - rfb::Point lastPointerPos; + core::Point lastPointerPos; uint16_t lastButtonMask; Keyboard* keyboard; @@ -124,7 +125,7 @@ class Viewport : public Fl_Widget, protected EmulateMB, bool menuAltKey; Fl_RGB_Image *cursor; - rfb::Point cursorHotspot; + core::Point cursorHotspot; }; #endif diff --git a/vncviewer/Win32TouchHandler.cxx b/vncviewer/Win32TouchHandler.cxx index 2be27ede9a..d1d81ae139 100644 --- a/vncviewer/Win32TouchHandler.cxx +++ b/vncviewer/Win32TouchHandler.cxx @@ -24,14 +24,15 @@ #include +#include + #define XK_MISCELLANY #include -#include #include "i18n.h" #include "Win32TouchHandler.h" -static rfb::LogWriter vlog("Win32TouchHandler"); +static core::LogWriter vlog("Win32TouchHandler"); static const DWORD MOUSEMOVE_FLAGS = MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE | MOUSEEVENTF_VIRTUALDESK; diff --git a/vncviewer/XInputTouchHandler.cxx b/vncviewer/XInputTouchHandler.cxx index 2b2e02c6a3..545a097eb6 100644 --- a/vncviewer/XInputTouchHandler.cxx +++ b/vncviewer/XInputTouchHandler.cxx @@ -30,16 +30,17 @@ #include +#include + #ifndef XK_MISCELLANY #define XK_MISCELLANY #include #endif -#include #include "i18n.h" #include "XInputTouchHandler.h" -static rfb::LogWriter vlog("XInputTouchHandler"); +static core::LogWriter vlog("XInputTouchHandler"); static bool grabbed = false; diff --git a/vncviewer/cocoa.mm b/vncviewer/cocoa.mm index 1d63b75024..19db342cba 100644 --- a/vncviewer/cocoa.mm +++ b/vncviewer/cocoa.mm @@ -26,7 +26,7 @@ #import -#include +#include static bool captured = false; @@ -54,7 +54,7 @@ int cocoa_capture_displays(Fl_Window *win) CGDirectDisplayID displays[16]; int sx, sy, sw, sh; - rfb::Rect windows_rect, screen_rect; + core::Rect windows_rect, screen_rect; windows_rect.setXYWH(win->x(), win->y(), win->w(), win->h()); diff --git a/vncviewer/parameters.cxx b/vncviewer/parameters.cxx index a6229a349c..ff6595372c 100644 --- a/vncviewer/parameters.cxx +++ b/vncviewer/parameters.cxx @@ -32,13 +32,12 @@ #include "parameters.h" -#include +#include +#include +#include +#include -#include - -#include #include -#include #include @@ -50,123 +49,172 @@ #include "i18n.h" -using namespace rfb; -using namespace std; - -static LogWriter vlog("Parameters"); - - -IntParameter pointerEventInterval("PointerEventInterval", - "Time in milliseconds to rate-limit" - " successive pointer events", 17); -BoolParameter emulateMiddleButton("EmulateMiddleButton", - "Emulate middle mouse button by pressing " - "left and right mouse buttons simultaneously", - false); -BoolParameter dotWhenNoCursor("DotWhenNoCursor", - "Show the dot cursor when the server sends an " - "invisible cursor", false); - -BoolParameter alertOnFatalError("AlertOnFatalError", - "Give a dialog on connection problems rather " - "than exiting immediately", true); - -BoolParameter reconnectOnError("ReconnectOnError", - "Give a dialog on connection problems rather " - "than exiting immediately and ask for a reconnect.", true); - -StringParameter passwordFile("PasswordFile", - "Password file for VNC authentication", ""); -AliasParameter passwd("passwd", "Alias for PasswordFile", &passwordFile); - -BoolParameter autoSelect("AutoSelect", - "Auto select pixel format and encoding. " - "Default if PreferredEncoding and FullColor are not specified.", - true); -BoolParameter fullColour("FullColor", - "Use full color", true); -AliasParameter fullColourAlias("FullColour", "Alias for FullColor", &fullColour); -IntParameter lowColourLevel("LowColorLevel", - "Color level to use on slow connections. " - "0 = Very Low, 1 = Low, 2 = Medium", 2); -AliasParameter lowColourLevelAlias("LowColourLevel", "Alias for LowColorLevel", &lowColourLevel); -StringParameter preferredEncoding("PreferredEncoding", - "Preferred encoding to use (Tight, ZRLE, Hextile or" - " Raw)", "Tight"); -BoolParameter customCompressLevel("CustomCompressLevel", - "Use custom compression level. " - "Default if CompressLevel is specified.", false); -IntParameter compressLevel("CompressLevel", - "Use specified compression level 0 = Low, 9 = High", - 2); -BoolParameter noJpeg("NoJPEG", - "Disable lossy JPEG compression in Tight encoding.", - false); -IntParameter qualityLevel("QualityLevel", - "JPEG quality level. 0 = Low, 9 = High", - 8); - -BoolParameter maximize("Maximize", "Maximize viewer window", false); -BoolParameter fullScreen("FullScreen", "Enable full screen", false); -StringParameter fullScreenMode("FullScreenMode", "Specify which monitors to use when in full screen. " - "Should be either Current, Selected or All", - "Current"); -BoolParameter fullScreenAllMonitors("FullScreenAllMonitors", - "[DEPRECATED] Enable full screen over all monitors", - false); -MonitorIndicesParameter fullScreenSelectedMonitors("FullScreenSelectedMonitors", - "Use the given list of monitors in full screen" - " when -FullScreenMode=Selected.", - "1"); -StringParameter desktopSize("DesktopSize", - "Reconfigure desktop size on the server on " - "connect (if possible)", ""); -StringParameter geometry("geometry", - "Specify size and position of viewer window", ""); - -BoolParameter listenMode("listen", "Listen for connections from VNC servers", false); - -BoolParameter remoteResize("RemoteResize", - "Dynamically resize the remote desktop size as " - "the size of the local client window changes. " - "(Does not work with all servers)", true); - -BoolParameter viewOnly("ViewOnly", - "Don't send any mouse or keyboard events to the server", - false); -BoolParameter shared("Shared", - "Don't disconnect other viewers upon connection - " - "share the desktop instead", - false); - -BoolParameter acceptClipboard("AcceptClipboard", - "Accept clipboard changes from the server", - true); -BoolParameter sendClipboard("SendClipboard", - "Send clipboard changes to the server", true); +static core::LogWriter vlog("Parameters"); + +core::IntParameter + pointerEventInterval("PointerEventInterval", + "Time in milliseconds to rate-limit successive " + "pointer events", + 17); +core::BoolParameter + emulateMiddleButton("EmulateMiddleButton", + "Emulate middle mouse button by pressing left " + "and right mouse buttons simultaneously", + false); +core::BoolParameter + dotWhenNoCursor("DotWhenNoCursor", + "Show the dot cursor when the server sends an " + "invisible cursor", + false); + +core::BoolParameter + alertOnFatalError("AlertOnFatalError", + "Give a dialog on connection problems rather than " + "exiting immediately", + true); + +core::BoolParameter + reconnectOnError("ReconnectOnError", + "Give a dialog on connection problems rather than " + "exiting immediately and ask for a reconnect.", + true); + +core::StringParameter + passwordFile("PasswordFile", + "Password file for VNC authentication", + ""); +core::AliasParameter + passwd("passwd", "Alias for PasswordFile", &passwordFile); + +core::BoolParameter + autoSelect("AutoSelect", + "Auto select pixel format and encoding. Default if " + "PreferredEncoding and FullColor are not specified.", + true); +core::BoolParameter + fullColour("FullColor", "Use full color", true); +core::AliasParameter + fullColourAlias("FullColour", "Alias for FullColor", &fullColour); +core::IntParameter + lowColourLevel("LowColorLevel", + "Color level to use on slow connections. " + "0 = Very Low, 1 = Low, 2 = Medium", + 2); +core::AliasParameter + lowColourLevelAlias("LowColourLevel", + "Alias for LowColorLevel", &lowColourLevel); +core::StringParameter + preferredEncoding("PreferredEncoding", + "Preferred encoding to use (Tight, ZRLE, Hextile " + "or Raw)", + "Tight"); +core::BoolParameter + customCompressLevel("CustomCompressLevel", + "Use custom compression level. Default if " + "CompressLevel is specified.", + false); +core::IntParameter + compressLevel("CompressLevel", + "Use specified compression level 0 = Low, 9 = High", + 2); +core::BoolParameter + noJpeg("NoJPEG", + "Disable lossy JPEG compression in Tight encoding.", + false); +core::IntParameter + qualityLevel("QualityLevel", + "JPEG quality level. 0 = Low, 9 = High", + 8); + +core::BoolParameter + maximize("Maximize", "Maximize viewer window", false); +core::BoolParameter + fullScreen("FullScreen", "Enable full screen", false); +core::StringParameter + fullScreenMode("FullScreenMode", + "Specify which monitors to use when in full screen. " + "Should be either Current, Selected or All", + "Current"); +core::BoolParameter + fullScreenAllMonitors("FullScreenAllMonitors", + "[DEPRECATED] Enable full screen over all " + "monitors", + false); +MonitorIndicesParameter + fullScreenSelectedMonitors("FullScreenSelectedMonitors", + "Use the given list of monitors in full " + "screen when -FullScreenMode=Selected.", + "1"); +core::StringParameter + desktopSize("DesktopSize", + "Reconfigure desktop size on the server on connect (if " + "possible)", + ""); +core::StringParameter + geometry("geometry", + "Specify size and position of viewer window", + ""); + +core::BoolParameter + listenMode("listen", + "Listen for connections from VNC servers", + false); + +core::BoolParameter + remoteResize("RemoteResize", + "Dynamically resize the remote desktop size as the size " + "of the local client window changes. (Does not work " + "with all servers)", + true); + +core::BoolParameter + viewOnly("ViewOnly", + "Don't send any mouse or keyboard events to the server", + false); +core::BoolParameter + shared("Shared", + "Don't disconnect other viewers upon connection - " + "share the desktop instead", + false); + +core::BoolParameter + acceptClipboard("AcceptClipboard", + "Accept clipboard changes from the server", + true); +core::BoolParameter + sendClipboard("SendClipboard", + "Send clipboard changes to the server", + true); #if !defined(WIN32) && !defined(__APPLE__) -BoolParameter setPrimary("SetPrimary", - "Set the primary selection as well as the " - "clipboard selection", true); -BoolParameter sendPrimary("SendPrimary", - "Send the primary selection to the " - "server as well as the clipboard selection", - true); -StringParameter display("display", - "Specifies the X display on which the VNC viewer window should appear.", - ""); +core::BoolParameter + setPrimary("SetPrimary", + "Set the primary selection as well as the clipboard " + "selection", + true); +core::BoolParameter + sendPrimary("SendPrimary", + "Send the primary selection to the server as well as the " + "clipboard selection", + true); +core::StringParameter + display("display", + "Specifies the X display on which the VNC viewer window " + "should appear.", + ""); #endif -StringParameter menuKey("MenuKey", "The key which brings up the popup menu", - "F8"); +core::StringParameter + menuKey("MenuKey", "The key which brings up the popup menu", "F8"); -BoolParameter fullscreenSystemKeys("FullscreenSystemKeys", - "Pass special keys (like Alt+Tab) directly " - "to the server when in full-screen mode.", - true); +core::BoolParameter + fullscreenSystemKeys("FullscreenSystemKeys", + "Pass special keys (like Alt+Tab) directly to " + "the server when in full-screen mode.", + true); #ifndef WIN32 -StringParameter via("via", "Gateway to tunnel via", ""); +core::StringParameter + via("via", "Gateway to tunnel via", ""); #endif static const char* IDENTIFIER_STRING = "TigerVNC Configuration file Version 1.0"; @@ -175,13 +223,13 @@ static const char* IDENTIFIER_STRING = "TigerVNC Configuration file Version 1.0" * We only save the sub set of parameters that can be modified from * the graphical user interface */ -static VoidParameter* parameterArray[] = { +static core::VoidParameter* parameterArray[] = { /* Security */ #ifdef HAVE_GNUTLS - &CSecurityTLS::X509CA, - &CSecurityTLS::X509CRL, + &rfb::CSecurityTLS::X509CA, + &rfb::CSecurityTLS::X509CRL, #endif // HAVE_GNUTLS - &SecurityClient::secTypes, + &rfb::SecurityClient::secTypes, /* Misc. */ &reconnectOnError, &shared, @@ -212,7 +260,7 @@ static VoidParameter* parameterArray[] = { &fullscreenSystemKeys }; -static VoidParameter* readOnlyParameterArray[] = { +static core::VoidParameter* readOnlyParameterArray[] = { &fullScreenAllMonitors }; @@ -320,7 +368,7 @@ static void setKeyString(const char *_name, const char *_value, HKEY* hKey) { LONG res = RegSetValueExW(*hKey, name, 0, REG_SZ, (BYTE*)&value, (wcslen(value)+1)*2); if (res != ERROR_SUCCESS) - throw rdr::win32_error("RegSetValueExW", res); + throw core::win32_error("RegSetValueExW", res); } @@ -336,7 +384,7 @@ static void setKeyInt(const char *_name, const int _value, HKEY* hKey) { LONG res = RegSetValueExW(*hKey, name, 0, REG_DWORD, (BYTE*)&value, sizeof(DWORD)); if (res != ERROR_SUCCESS) - throw rdr::win32_error("RegSetValueExW", res); + throw core::win32_error("RegSetValueExW", res); } @@ -357,7 +405,7 @@ static bool getKeyString(const char* _name, char* dest, size_t destSize, HKEY* h if (res != ERROR_SUCCESS){ delete [] value; if (res != ERROR_FILE_NOT_FOUND) - throw rdr::win32_error("RegQueryValueExW", res); + throw core::win32_error("RegQueryValueExW", res); // The value does not exist, defaults will be used. return false; } @@ -394,7 +442,7 @@ static bool getKeyInt(const char* _name, int* dest, HKEY* hKey) { LONG res = RegQueryValueExW(*hKey, name, nullptr, nullptr, (LPBYTE)&value, &dwordsize); if (res != ERROR_SUCCESS){ if (res != ERROR_FILE_NOT_FOUND) - throw rdr::win32_error("RegQueryValueExW", res); + throw core::win32_error("RegQueryValueExW", res); // The value does not exist, defaults will be used. return false; } @@ -414,13 +462,14 @@ static void removeValue(const char* _name, HKEY* hKey) { LONG res = RegDeleteValueW(*hKey, name); if (res != ERROR_SUCCESS) { if (res != ERROR_FILE_NOT_FOUND) - throw rdr::win32_error("RegDeleteValueW", res); + throw core::win32_error("RegDeleteValueW", res); // The value does not exist, no need to remove it. return; } } -void saveHistoryToRegKey(const list& serverHistory) { +void saveHistoryToRegKey(const std::list& serverHistory) +{ HKEY hKey; LONG res = RegCreateKeyExW(HKEY_CURRENT_USER, L"Software\\TigerVNC\\vncviewer\\history", 0, nullptr, @@ -428,14 +477,14 @@ void saveHistoryToRegKey(const list& serverHistory) { &hKey, nullptr); if (res != ERROR_SUCCESS) - throw rdr::win32_error(_("Failed to create registry key"), res); + throw core::win32_error(_("Failed to create registry key"), res); unsigned index = 0; assert(SERVER_HISTORY_SIZE < 100); char indexString[3]; try { - for (const string& entry : serverHistory) { + for (const std::string& entry : serverHistory) { if (index > SERVER_HISTORY_SIZE) break; snprintf(indexString, 3, "%d", index); @@ -449,7 +498,7 @@ void saveHistoryToRegKey(const list& serverHistory) { res = RegCloseKey(hKey); if (res != ERROR_SUCCESS) - throw rdr::win32_error(_("Failed to close registry key"), res); + throw core::win32_error(_("Failed to close registry key"), res); } static void saveToReg(const char* servername) { @@ -461,57 +510,66 @@ static void saveToReg(const char* servername) { REG_OPTION_NON_VOLATILE, KEY_ALL_ACCESS, nullptr, &hKey, nullptr); if (res != ERROR_SUCCESS) - throw rdr::win32_error(_("Failed to create registry key"), res); + throw core::win32_error(_("Failed to create registry key"), res); try { setKeyString("ServerName", servername, &hKey); } catch (std::exception& e) { RegCloseKey(hKey); - throw std::runtime_error(format(_("Failed to save \"%s\": %s"), - "ServerName", e.what())); + throw std::runtime_error(core::format( + _("Failed to save \"%s\": %s"), "ServerName", e.what())); } - for (size_t i = 0; i < sizeof(parameterArray)/sizeof(VoidParameter*); i++) { + for (core::VoidParameter* param : parameterArray) { + core::StringParameter* sparam; + core::IntParameter* iparam; + core::BoolParameter* bparam; + + sparam = dynamic_cast(param); + iparam = dynamic_cast(param); + bparam = dynamic_cast(param); + try { - if (dynamic_cast(parameterArray[i]) != nullptr) { - setKeyString(parameterArray[i]->getName(), *(StringParameter*)parameterArray[i], &hKey); - } else if (dynamic_cast(parameterArray[i]) != nullptr) { - setKeyInt(parameterArray[i]->getName(), (int)*(IntParameter*)parameterArray[i], &hKey); - } else if (dynamic_cast(parameterArray[i]) != nullptr) { - setKeyInt(parameterArray[i]->getName(), (int)*(BoolParameter*)parameterArray[i], &hKey); + if (sparam != nullptr) { + setKeyString(sparam->getName(), *(sparam), &hKey); + } else if (iparam != nullptr) { + setKeyInt(iparam->getName(), (int)*(iparam), &hKey); + } else if (bparam != nullptr) { + setKeyInt(bparam->getName(), (int)*(bparam), &hKey); } else { throw std::logic_error(_("Unknown parameter type")); } } catch (std::exception& e) { RegCloseKey(hKey); - throw std::runtime_error(format(_("Failed to save \"%s\": %s"), - parameterArray[i]->getName(), - e.what())); + throw std::runtime_error( + core::format(_("Failed to save \"%s\": %s"), + param->getName(), e.what())); } } // Remove read-only parameters to replicate the behaviour of Linux/macOS when they // store a config to disk. If the parameter hasn't been migrated at this point it // will be lost. - for (size_t i = 0; i < sizeof(readOnlyParameterArray)/sizeof(VoidParameter*); i++) { + for (core::VoidParameter* param : readOnlyParameterArray) { try { - removeValue(readOnlyParameterArray[i]->getName(), &hKey); + removeValue(param->getName(), &hKey); } catch (std::exception& e) { RegCloseKey(hKey); - throw std::runtime_error(format(_("Failed to remove \"%s\": %s"), - readOnlyParameterArray[i]->getName(), - e.what())); + throw std::runtime_error( + core::format(_("Failed to remove \"%s\": %s"), + param->getName(), e.what())); } } res = RegCloseKey(hKey); if (res != ERROR_SUCCESS) - throw rdr::win32_error(_("Failed to close registry key"), res); + throw core::win32_error(_("Failed to close registry key"), res); } -list loadHistoryFromRegKey() { +std::list loadHistoryFromRegKey() +{ HKEY hKey; - list serverHistory; + std::list serverHistory; LONG res = RegOpenKeyExW(HKEY_CURRENT_USER, L"Software\\TigerVNC\\vncviewer\\history", 0, @@ -522,7 +580,7 @@ list loadHistoryFromRegKey() { return serverHistory; } - throw rdr::win32_error(_("Failed to open registry key"), res); + throw core::win32_error(_("Failed to open registry key"), res); } unsigned index; @@ -549,29 +607,37 @@ list loadHistoryFromRegKey() { res = RegCloseKey(hKey); if (res != ERROR_SUCCESS) - throw rdr::win32_error(_("Failed to close registry key"), res); + throw core::win32_error(_("Failed to close registry key"), res); return serverHistory; } -static void getParametersFromReg(VoidParameter* parameters[], +static void getParametersFromReg(core::VoidParameter* parameters[], size_t parameters_len, HKEY* hKey) { const size_t buffersize = 256; int intValue = 0; char stringValue[buffersize]; - for (size_t i = 0; i < parameters_len/sizeof(VoidParameter*); i++) { + for (size_t i = 0; i < parameters_len; i++) { + core::StringParameter* sparam; + core::IntParameter* iparam; + core::BoolParameter* bparam; + + sparam = dynamic_cast(parameters[i]); + iparam = dynamic_cast(parameters[i]); + bparam = dynamic_cast(parameters[i]); + try { - if (dynamic_cast(parameters[i]) != nullptr) { - if (getKeyString(parameters[i]->getName(), stringValue, buffersize, hKey)) - parameters[i]->setParam(stringValue); - } else if (dynamic_cast(parameters[i]) != nullptr) { - if (getKeyInt(parameters[i]->getName(), &intValue, hKey)) - ((IntParameter*)parameters[i])->setParam(intValue); - } else if (dynamic_cast(parameters[i]) != nullptr) { - if (getKeyInt(parameters[i]->getName(), &intValue, hKey)) - ((BoolParameter*)parameters[i])->setParam(intValue); + if (sparam != nullptr) { + if (getKeyString(sparam->getName(), stringValue, buffersize, hKey)) + sparam->setParam(stringValue); + } else if (iparam != nullptr) { + if (getKeyInt(iparam->getName(), &intValue, hKey)) + iparam->setParam(intValue); + } else if (bparam != nullptr) { + if (getKeyInt(bparam->getName(), &intValue, hKey)) + bparam->setParam(intValue); } else { throw std::logic_error(_("Unknown parameter type")); } @@ -596,7 +662,7 @@ static char* loadFromReg() { return nullptr; } - throw rdr::win32_error(_("Failed to open registry key"), res); + throw core::win32_error(_("Failed to open registry key"), res); } const size_t buffersize = 256; @@ -612,13 +678,18 @@ static char* loadFromReg() { strcpy(servername, ""); } - getParametersFromReg(parameterArray, sizeof(parameterArray), &hKey); + getParametersFromReg(parameterArray, + sizeof(parameterArray) / + sizeof(core::VoidParameter*), + &hKey); getParametersFromReg(readOnlyParameterArray, - sizeof(readOnlyParameterArray), &hKey); + sizeof(readOnlyParameterArray) / + sizeof(core::VoidParameter*), + &hKey); res = RegCloseKey(hKey); if (res != ERROR_SUCCESS) - throw rdr::win32_error(_("Failed to close registry key"), res); + throw core::win32_error(_("Failed to close registry key"), res); return servername; } @@ -639,7 +710,7 @@ void saveViewerParameters(const char *filename, const char *servername) { return; #endif - const char* configDir = os::getvncconfigdir(); + const char* configDir = core::getvncconfigdir(); if (configDir == nullptr) throw std::runtime_error(_("Could not determine VNC config directory path")); @@ -650,73 +721,86 @@ void saveViewerParameters(const char *filename, const char *servername) { /* Write parameters to file */ FILE* f = fopen(filepath, "w+"); - if (!f) { - std::string msg = format(_("Could not open \"%s\""), filepath); - throw rdr::posix_error(msg.c_str(), errno); - } + if (!f) + throw core::posix_error( + core::format(_("Could not open \"%s\""), filepath), errno); fprintf(f, "%s\n", IDENTIFIER_STRING); fprintf(f, "\n"); if (!encodeValue(servername, encodingBuffer, buffersize)) { fclose(f); - throw std::runtime_error(format(_("Failed to save \"%s\": %s"), - "ServerName", - _("Could not encode parameter"))); + throw std::runtime_error( + core::format(_("Failed to save \"%s\": %s"), "ServerName", + _("Could not encode parameter"))); } fprintf(f, "ServerName=%s\n", encodingBuffer); - for (VoidParameter* param : parameterArray) { - if (dynamic_cast(param) != nullptr) { - if (!encodeValue(*(StringParameter*)param, - encodingBuffer, buffersize)) { + for (core::VoidParameter* param : parameterArray) { + core::StringParameter* sparam; + core::IntParameter* iparam; + core::BoolParameter* bparam; + + sparam = dynamic_cast(param); + iparam = dynamic_cast(param); + bparam = dynamic_cast(param); + + if (sparam != nullptr) { + if (!encodeValue(*sparam, encodingBuffer, buffersize)) { fclose(f); - throw std::runtime_error(format(_("Failed to save \"%s\": %s"), - param->getName(), - _("Could not encode parameter"))); + throw std::runtime_error( + core::format(_("Failed to save \"%s\": %s"), param->getName(), + _("Could not encode parameter"))); } - fprintf(f, "%s=%s\n", ((StringParameter*)param)->getName(), encodingBuffer); - } else if (dynamic_cast(param) != nullptr) { - fprintf(f, "%s=%d\n", ((IntParameter*)param)->getName(), (int)*(IntParameter*)param); - } else if (dynamic_cast(param) != nullptr) { - fprintf(f, "%s=%d\n", ((BoolParameter*)param)->getName(), (int)*(BoolParameter*)param); + fprintf(f, "%s=%s\n", sparam->getName(), encodingBuffer); + } else if (iparam != nullptr) { + fprintf(f, "%s=%d\n", iparam->getName(), (int)*iparam); + } else if (bparam != nullptr) { + fprintf(f, "%s=%d\n", bparam->getName(), (int)*bparam); } else { fclose(f); - throw std::logic_error(format(_("Failed to save \"%s\": %s"), - param->getName(), - _("Unknown parameter type"))); + throw std::logic_error( + core::format(_("Failed to save \"%s\": %s"), param->getName(), + _("Unknown parameter type"))); } } fclose(f); } static bool findAndSetViewerParameterFromValue( - VoidParameter* parameters[], size_t parameters_len, + core::VoidParameter* parameters[], size_t parameters_len, char* value, char* line) { const size_t buffersize = 256; char decodingBuffer[buffersize]; // Find and set the correct parameter - for (size_t i = 0; i < parameters_len/sizeof(VoidParameter*); i++) { + for (size_t i = 0; i < parameters_len; i++) { + core::StringParameter* sparam; + core::IntParameter* iparam; + core::BoolParameter* bparam; + + sparam = dynamic_cast(parameters[i]); + iparam = dynamic_cast(parameters[i]); + bparam = dynamic_cast(parameters[i]); - if (dynamic_cast(parameters[i]) != nullptr) { - if (strcasecmp(line, ((StringParameter*)parameters[i])->getName()) == 0) { + if (sparam != nullptr) { + if (strcasecmp(line, sparam->getName()) == 0) { if(!decodeValue(value, decodingBuffer, sizeof(decodingBuffer))) throw std::runtime_error(_("Invalid format or too large value")); - ((StringParameter*)parameters[i])->setParam(decodingBuffer); + sparam->setParam(decodingBuffer); return false; } - } else if (dynamic_cast(parameters[i]) != nullptr) { - if (strcasecmp(line, ((IntParameter*)parameters[i])->getName()) == 0) { - ((IntParameter*)parameters[i])->setParam(atoi(value)); + } else if (iparam != nullptr) { + if (strcasecmp(line, iparam->getName()) == 0) { + iparam->setParam(atoi(value)); return false; } - } else if (dynamic_cast(parameters[i]) != nullptr) { - if (strcasecmp(line, ((BoolParameter*)parameters[i])->getName()) == 0) { - ((BoolParameter*)parameters[i])->setParam(atoi(value)); + } else if (bparam != nullptr) { + if (strcasecmp(line, bparam->getName()) == 0) { + bparam->setParam(atoi(value)); return false; } @@ -745,7 +829,7 @@ char* loadViewerParameters(const char *filename) { return loadFromReg(); #endif - const char* configDir = os::getvncconfigdir(); + const char* configDir = core::getvncconfigdir(); if (configDir == nullptr) throw std::runtime_error(_("Could not determine VNC config directory path")); @@ -759,10 +843,10 @@ char* loadViewerParameters(const char *filename) { if (!f) { if (!filename) return nullptr; // Use defaults. - std::string msg = format(_("Could not open \"%s\""), filepath); - throw rdr::posix_error(msg.c_str(), errno); + throw core::posix_error( + core::format(_("Could not open \"%s\""), filepath), errno); } - + int lineNr = 0; while (!feof(f)) { @@ -773,18 +857,19 @@ char* loadViewerParameters(const char *filename) { break; fclose(f); - std::string msg = format(_("Failed to read line %d in " - "file \"%s\""), lineNr, filepath); - throw rdr::posix_error(msg.c_str(), errno); + throw core::posix_error( + core::format(_("Failed to read line %d in file \"%s\""), + lineNr, filepath), + errno); } if (strlen(line) == (sizeof(line) - 1)) { fclose(f); - throw std::runtime_error(format("%s: %s", - format(_("Failed to read line %d " - "in file \"%s\""), - lineNr, filepath).c_str(), - _("Line too long"))); + throw std::runtime_error(core::format( + "%s: %s", + core::format(_("Failed to read line %d in file \"%s\""), + lineNr, filepath).c_str(), + _("Line too long"))); } // Make sure that the first line of the file has the file identifier string @@ -793,11 +878,10 @@ char* loadViewerParameters(const char *filename) { continue; fclose(f); - throw std::runtime_error(format(_("Configuration file %s is in " - "an invalid format"), - filepath)); + throw std::runtime_error(core::format( + _("Configuration file %s is in an invalid format"), filepath)); } - + // Skip empty lines and comments if ((line[0] == '\n') || (line[0] == '#') || (line[0] == '\r')) continue; @@ -834,12 +918,17 @@ char* loadViewerParameters(const char *filename) { invalidParameterName = false; } else { - invalidParameterName = findAndSetViewerParameterFromValue(parameterArray, sizeof(parameterArray), - value, line); + invalidParameterName = findAndSetViewerParameterFromValue( + parameterArray, + sizeof(parameterArray) / sizeof(core::VoidParameter *), + value, line); if (invalidParameterName) { - invalidParameterName = findAndSetViewerParameterFromValue(readOnlyParameterArray, sizeof(readOnlyParameterArray), - value, line); + invalidParameterName = findAndSetViewerParameterFromValue( + readOnlyParameterArray, + sizeof(readOnlyParameterArray) / + sizeof(core::VoidParameter *), + value, line); } } } catch(std::exception& e) { diff --git a/vncviewer/parameters.h b/vncviewer/parameters.h index a25c932d95..a178fec477 100644 --- a/vncviewer/parameters.h +++ b/vncviewer/parameters.h @@ -20,7 +20,8 @@ #ifndef __PARAMETERS_H__ #define __PARAMETERS_H__ -#include +#include + #include "MonitorIndicesParameter.h" #ifdef _WIN32 @@ -31,53 +32,53 @@ #define SERVER_HISTORY_SIZE 20 -extern rfb::IntParameter pointerEventInterval; -extern rfb::BoolParameter emulateMiddleButton; -extern rfb::BoolParameter dotWhenNoCursor; +extern core::IntParameter pointerEventInterval; +extern core::BoolParameter emulateMiddleButton; +extern core::BoolParameter dotWhenNoCursor; -extern rfb::StringParameter passwordFile; +extern core::StringParameter passwordFile; -extern rfb::BoolParameter autoSelect; -extern rfb::BoolParameter fullColour; -extern rfb::AliasParameter fullColourAlias; -extern rfb::IntParameter lowColourLevel; -extern rfb::AliasParameter lowColourLevelAlias; -extern rfb::StringParameter preferredEncoding; -extern rfb::BoolParameter customCompressLevel; -extern rfb::IntParameter compressLevel; -extern rfb::BoolParameter noJpeg; -extern rfb::IntParameter qualityLevel; +extern core::BoolParameter autoSelect; +extern core::BoolParameter fullColour; +extern core::AliasParameter fullColourAlias; +extern core::IntParameter lowColourLevel; +extern core::AliasParameter lowColourLevelAlias; +extern core::StringParameter preferredEncoding; +extern core::BoolParameter customCompressLevel; +extern core::IntParameter compressLevel; +extern core::BoolParameter noJpeg; +extern core::IntParameter qualityLevel; -extern rfb::BoolParameter maximize; -extern rfb::BoolParameter fullScreen; -extern rfb::StringParameter fullScreenMode; -extern rfb::BoolParameter fullScreenAllMonitors; // deprecated +extern core::BoolParameter maximize; +extern core::BoolParameter fullScreen; +extern core::StringParameter fullScreenMode; +extern core::BoolParameter fullScreenAllMonitors; // deprecated extern MonitorIndicesParameter fullScreenSelectedMonitors; -extern rfb::StringParameter desktopSize; -extern rfb::StringParameter geometry; -extern rfb::BoolParameter remoteResize; +extern core::StringParameter desktopSize; +extern core::StringParameter geometry; +extern core::BoolParameter remoteResize; -extern rfb::BoolParameter listenMode; +extern core::BoolParameter listenMode; -extern rfb::BoolParameter viewOnly; -extern rfb::BoolParameter shared; +extern core::BoolParameter viewOnly; +extern core::BoolParameter shared; -extern rfb::BoolParameter acceptClipboard; -extern rfb::BoolParameter setPrimary; -extern rfb::BoolParameter sendClipboard; +extern core::BoolParameter acceptClipboard; +extern core::BoolParameter setPrimary; +extern core::BoolParameter sendClipboard; #if !defined(WIN32) && !defined(__APPLE__) -extern rfb::BoolParameter sendPrimary; -extern rfb::StringParameter display; +extern core::BoolParameter sendPrimary; +extern core::StringParameter display; #endif -extern rfb::StringParameter menuKey; +extern core::StringParameter menuKey; -extern rfb::BoolParameter fullscreenSystemKeys; -extern rfb::BoolParameter alertOnFatalError; -extern rfb::BoolParameter reconnectOnError; +extern core::BoolParameter fullscreenSystemKeys; +extern core::BoolParameter alertOnFatalError; +extern core::BoolParameter reconnectOnError; #ifndef WIN32 -extern rfb::StringParameter via; +extern core::StringParameter via; #endif void saveViewerParameters(const char *filename, const char *servername=nullptr); diff --git a/vncviewer/touch.cxx b/vncviewer/touch.cxx index 572e726ef5..8b9984253e 100644 --- a/vncviewer/touch.cxx +++ b/vncviewer/touch.cxx @@ -36,7 +36,7 @@ #include #include -#include +#include #include "i18n.h" #include "vncviewer.h" @@ -49,7 +49,7 @@ #include "touch.h" -static rfb::LogWriter vlog("Touch"); +static core::LogWriter vlog("Touch"); #if !defined(WIN32) && !defined(__APPLE__) static int xi_major; diff --git a/vncviewer/vncviewer.cxx b/vncviewer/vncviewer.cxx index 4efe6e931d..5263b59b4a 100644 --- a/vncviewer/vncviewer.cxx +++ b/vncviewer/vncviewer.cxx @@ -35,7 +35,7 @@ #include #ifdef WIN32 -#include +#include #include #endif @@ -48,16 +48,18 @@ #include #endif -#include +#include +#include +#include +#include + #ifdef HAVE_GNUTLS #include #endif -#include -#include -#include -#include + +#include + #include -#include #include #include @@ -79,10 +81,7 @@ #include "win32.h" #endif -static rfb::LogWriter vlog("main"); - -using namespace network; -using namespace rfb; +static core::LogWriter vlog("main"); char vncServerName[VNCSERVERNAMELEN] = { '\0' }; @@ -187,7 +186,7 @@ static void mainloop(const char* vncserver, network::Socket* sock) while (!exitMainloop) { int next_timer; - next_timer = Timer::checkTimeouts(); + next_timer = core::Timer::checkTimeouts(); if (next_timer < 0) next_timer = INT_MAX; @@ -476,7 +475,7 @@ static void usage(const char *programName) "Other valid forms are = -= " "--=\n" "Parameter names are case-insensitive. The parameters are:\n\n"); - Configuration::listParams(79, 14); + core::Configuration::listParams(79, 14); #ifdef WIN32 // Just wait for the user to kill the console window @@ -535,7 +534,7 @@ create_base_dirs() { const char *dir; - dir = os::getvncconfigdir(); + dir = core::getvncconfigdir(); if (dir == nullptr) { vlog.error(_("Could not determine VNC config directory path")); return; @@ -551,31 +550,31 @@ create_base_dirs() vlog.info(_("%%APPDATA%%\\vnc is deprecated, please switch to the %%APPDATA%%\\TigerVNC location.")); #endif - if (os::mkdir_p(dir, 0755) == -1) { + if (core::mkdir_p(dir, 0755) == -1) { if (errno != EEXIST) vlog.error(_("Could not create VNC config directory \"%s\": %s"), dir, strerror(errno)); } - dir = os::getvncdatadir(); + dir = core::getvncdatadir(); if (dir == nullptr) { vlog.error(_("Could not determine VNC data directory path")); return; } - if (os::mkdir_p(dir, 0755) == -1) { + if (core::mkdir_p(dir, 0755) == -1) { if (errno != EEXIST) vlog.error(_("Could not create VNC data directory \"%s\": %s"), dir, strerror(errno)); } - dir = os::getvncstatedir(); + dir = core::getvncstatedir(); if (dir == nullptr) { vlog.error(_("Could not determine VNC state directory path")); return; } - if (os::mkdir_p(dir, 0755) == -1) { + if (core::mkdir_p(dir, 0755) == -1) { if (errno != EEXIST) vlog.error(_("Could not create VNC state directory \"%s\": %s"), dir, strerror(errno)); @@ -610,10 +609,10 @@ static void mktunnel() { const char *gatewayHost; std::string remoteHost; - int localPort = findFreeTcpPort(); + int localPort = network::findFreeTcpPort(); int remotePort; - getHostAndPort(vncServerName, &remoteHost, &remotePort); + network::getHostAndPort(vncServerName, &remoteHost, &remotePort); snprintf(vncServerName, VNCSERVERNAMELEN, "localhost::%d", localPort); vncServerName[VNCSERVERNAMELEN - 1] = '\0'; gatewayHost = (const char*)via; @@ -645,13 +644,13 @@ int main(int argc, char** argv) bind_textdomain_codeset(PACKAGE_NAME, "UTF-8"); bind_textdomain_codeset("libc", "UTF-8"); - rfb::initStdIOLoggers(); + core::initStdIOLoggers(); #ifdef WIN32 - rfb::initFileLogger("C:\\temp\\vncviewer.log"); + core::initFileLogger("C:\\temp\\vncviewer.log"); #else - rfb::initFileLogger("/tmp/vncviewer.log"); + core::initFileLogger("/tmp/vncviewer.log"); #endif - rfb::LogWriter::setLogParams("*:stderr:30"); + core::LogWriter::setLogParams("*:stderr:30"); #ifdef SIGHUP signal(SIGHUP, CleanupSignalHandler); @@ -659,7 +658,7 @@ int main(int argc, char** argv) signal(SIGINT, CleanupSignalHandler); signal(SIGTERM, CleanupSignalHandler); - Configuration::enableViewerParams(); + core::Configuration::enableViewerParams(); /* Load the default parameter settings */ char defaultServerName[VNCSERVERNAMELEN] = ""; @@ -677,11 +676,11 @@ int main(int argc, char** argv) for (int i = 1; i < argc;) { /* We need to resolve an ambiguity for booleans */ if (argv[i][0] == '-' && i+1 < argc) { - VoidParameter *param; + core::VoidParameter* param; - param = Configuration::getParam(&argv[i][1]); + param = core::Configuration::getParam(&argv[i][1]); if ((param != nullptr) && - (dynamic_cast(param) != nullptr)) { + (dynamic_cast(param) != nullptr)) { if ((strcasecmp(argv[i+1], "0") == 0) || (strcasecmp(argv[i+1], "1") == 0) || (strcasecmp(argv[i+1], "true") == 0) || @@ -695,14 +694,14 @@ int main(int argc, char** argv) } } - if (Configuration::setParam(argv[i])) { + if (core::Configuration::setParam(argv[i])) { i++; continue; } if (argv[i][0] == '-') { if (i+1 < argc) { - if (Configuration::setParam(&argv[i][1], argv[i+1])) { + if (core::Configuration::setParam(&argv[i][1], argv[i+1])) { i += 2; continue; } @@ -734,7 +733,7 @@ int main(int argc, char** argv) create_base_dirs(); - Socket *sock = nullptr; + network::Socket* sock = nullptr; #ifndef WIN32 /* Specifying -via and -listen together is nonsense */ @@ -748,7 +747,7 @@ int main(int argc, char** argv) #endif if (listenMode) { - std::list listeners; + std::list listeners; try { int port = 5500; if (isdigit(vncServerName[0])) @@ -764,7 +763,7 @@ int main(int argc, char** argv) while (sock == nullptr) { fd_set rfds; FD_ZERO(&rfds); - for (SocketListener* listener : listeners) + for (network::SocketListener* listener : listeners) FD_SET(listener->getFd(), &rfds); int n = select(FD_SETSIZE, &rfds, nullptr, nullptr, nullptr); @@ -773,11 +772,11 @@ int main(int argc, char** argv) vlog.debug("Interrupted select() system call"); continue; } else { - throw rdr::socket_error("select", errno); + throw core::socket_error("select", errno); } } - for (SocketListener* listener : listeners) + for (network::SocketListener* listener : listeners) if (FD_ISSET(listener->getFd(), &rfds)) { sock = listener->accept(); if (sock) diff --git a/win/rfb_win32/AboutDialog.cxx b/win/rfb_win32/AboutDialog.cxx index a41ceefd75..ce876fe587 100644 --- a/win/rfb_win32/AboutDialog.cxx +++ b/win/rfb_win32/AboutDialog.cxx @@ -20,14 +20,15 @@ #include #endif +#include + #include #include -#include using namespace rfb; using namespace rfb::win32; -static LogWriter vlog("AboutDialog"); +static core::LogWriter vlog("AboutDialog"); AboutDialog AboutDialog::instance; diff --git a/win/rfb_win32/CleanDesktop.cxx b/win/rfb_win32/CleanDesktop.cxx index 9713b2cd5e..5205ed2e86 100644 --- a/win/rfb_win32/CleanDesktop.cxx +++ b/win/rfb_win32/CleanDesktop.cxx @@ -25,18 +25,20 @@ #include #include #include + +#include +#include + #include #include #include -#include -#include -#include + #include using namespace rfb; using namespace rfb::win32; -static LogWriter vlog("CleanDesktop"); +static core::LogWriter vlog("CleanDesktop"); struct ActiveDesktop { @@ -45,7 +47,7 @@ struct ActiveDesktop { HRESULT result = CoCreateInstance(CLSID_ActiveDesktop, nullptr, CLSCTX_INPROC_SERVER, IID_IActiveDesktop, (PVOID*)&handle); if (result != S_OK) - throw rdr::win32_error("Failed to contact Active Desktop", HRESULT_CODE(result)); + throw core::win32_error("Failed to contact Active Desktop", HRESULT_CODE(result)); } ~ActiveDesktop() { if (handle) diff --git a/win/rfb_win32/Clipboard.cxx b/win/rfb_win32/Clipboard.cxx index 8fdc79c85d..faff6e3dcd 100644 --- a/win/rfb_win32/Clipboard.cxx +++ b/win/rfb_win32/Clipboard.cxx @@ -23,14 +23,15 @@ #include #endif -#include +#include +#include + +#include #include #include -#include - -#include +using namespace core; using namespace rfb; using namespace rfb::win32; @@ -129,7 +130,7 @@ Clipboard::setClipText(const char* text) { // - Firstly, we must open the clipboard if (!OpenClipboard(getHandle())) - throw rdr::win32_error("Unable to open Win32 clipboard", GetLastError()); + throw core::win32_error("Unable to open Win32 clipboard", GetLastError()); // - Convert the supplied clipboard text into UTF-16 format with CRLF std::string filtered(convertCRLF(text)); @@ -144,11 +145,11 @@ Clipboard::setClipText(const char* text) { // - Next, we must clear out any existing data if (!EmptyClipboard()) - throw rdr::win32_error("Unable to empty Win32 clipboard", GetLastError()); + throw core::win32_error("Unable to empty Win32 clipboard", GetLastError()); // - Set the new clipboard data if (!SetClipboardData(CF_UNICODETEXT, clip_handle)) - throw rdr::win32_error("Unable to set Win32 clipboard", GetLastError()); + throw core::win32_error("Unable to set Win32 clipboard", GetLastError()); clip_handle = nullptr; vlog.debug("Set clipboard"); diff --git a/win/rfb_win32/CompatibleBitmap.h b/win/rfb_win32/CompatibleBitmap.h index c8fdf82913..4e00a35ff8 100644 --- a/win/rfb_win32/CompatibleBitmap.h +++ b/win/rfb_win32/CompatibleBitmap.h @@ -20,7 +20,7 @@ #define __RFB_WIN32_COMPAT_BITMAP_H__ #include -#include +#include namespace rfb { namespace win32 { @@ -30,7 +30,7 @@ namespace rfb { CompatibleBitmap(HDC hdc, int width, int height) { hbmp = CreateCompatibleBitmap(hdc, width, height); if (!hbmp) - throw rdr::win32_error("CreateCompatibleBitmap() failed", GetLastError()); + throw core::win32_error("CreateCompatibleBitmap() failed", GetLastError()); } virtual ~CompatibleBitmap() { if (hbmp) DeleteObject(hbmp); diff --git a/win/rfb_win32/CurrentUser.cxx b/win/rfb_win32/CurrentUser.cxx index a9404c9453..753967cb8f 100644 --- a/win/rfb_win32/CurrentUser.cxx +++ b/win/rfb_win32/CurrentUser.cxx @@ -23,16 +23,19 @@ #endif #include -#include + +#include + #include #include + #include #include using namespace rfb; using namespace win32; -static LogWriter vlog("CurrentUser"); +static core::LogWriter vlog("CurrentUser"); const char* shellIconClass = "Shell_TrayWnd"; @@ -80,7 +83,7 @@ CurrentUserToken::CurrentUserToken() { if (!OpenProcessToken(GetCurrentProcess(), GENERIC_ALL, &h)) { DWORD err = GetLastError(); if (err != ERROR_CALL_NOT_IMPLEMENTED) - throw rdr::win32_error("OpenProcessToken failed", err); + throw core::win32_error("OpenProcessToken failed", err); h = INVALID_HANDLE_VALUE; } } @@ -96,7 +99,7 @@ ImpersonateCurrentUser::ImpersonateCurrentUser() { if (!ImpersonateLoggedOnUser(token)) { DWORD err = GetLastError(); if (err != ERROR_CALL_NOT_IMPLEMENTED) - throw rdr::win32_error("Failed to impersonate user", GetLastError()); + throw core::win32_error("Failed to impersonate user", GetLastError()); } } @@ -114,7 +117,7 @@ UserName::UserName() { char buf[UNLEN+1]; DWORD len = UNLEN+1; if (!GetUserName(buf, &len)) - throw rdr::win32_error("GetUserName failed", GetLastError()); + throw core::win32_error("GetUserName failed", GetLastError()); assign(buf); } diff --git a/win/rfb_win32/DIBSectionBuffer.cxx b/win/rfb_win32/DIBSectionBuffer.cxx index 3ce9980980..e706dd00e7 100644 --- a/win/rfb_win32/DIBSectionBuffer.cxx +++ b/win/rfb_win32/DIBSectionBuffer.cxx @@ -21,17 +21,17 @@ #include #endif -#include +#include +#include #include #include #include -#include using namespace rfb; using namespace win32; -static LogWriter vlog("DIBSectionBuffer"); +static core::LogWriter vlog("DIBSectionBuffer"); DIBSectionBuffer::DIBSectionBuffer(HWND window_) @@ -87,7 +87,7 @@ void DIBSectionBuffer::initBuffer(const PixelFormat& pf, int w, int h) { if (!new_bitmap) { int err = GetLastError(); - throw rdr::win32_error("Unable to create DIB section", err); + throw core::win32_error("Unable to create DIB section", err); } vlog.debug("recreateBuffer()"); @@ -130,7 +130,7 @@ void DIBSectionBuffer::initBuffer(const PixelFormat& pf, int w, int h) { // Determine the *actual* DIBSection format DIBSECTION ds; if (!GetObject(bitmap, sizeof(ds), &ds)) - throw rdr::win32_error("GetObject", GetLastError()); + throw core::win32_error("GetObject", GetLastError()); // Correct the "stride" of the DIB // *** This code DWORD aligns each row - is that right??? diff --git a/win/rfb_win32/DIBSectionBuffer.h b/win/rfb_win32/DIBSectionBuffer.h index 2f099f39bd..fa40c02f90 100644 --- a/win/rfb_win32/DIBSectionBuffer.h +++ b/win/rfb_win32/DIBSectionBuffer.h @@ -26,8 +26,10 @@ #define __RFB_WIN32_DIB_SECTION_BUFFER_H__ #include + +#include + #include -#include #include namespace rfb { diff --git a/win/rfb_win32/DeviceContext.cxx b/win/rfb_win32/DeviceContext.cxx index 092279fb7b..212e3bf1bf 100644 --- a/win/rfb_win32/DeviceContext.cxx +++ b/win/rfb_win32/DeviceContext.cxx @@ -21,12 +21,14 @@ #include #endif +#include +#include + #include #include #include -#include -#include +using namespace core; using namespace rfb; using namespace win32; @@ -51,10 +53,10 @@ PixelFormat DeviceContext::getPF(HDC dc) { bi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER); bi.bmiHeader.biBitCount = 0; if (!::GetDIBits(dc, bitmap, 0, 1, nullptr, (BITMAPINFO*)&bi, DIB_RGB_COLORS)) { - throw rdr::win32_error("Unable to determine device pixel format", GetLastError()); + throw core::win32_error("Unable to determine device pixel format", GetLastError()); } if (!::GetDIBits(dc, bitmap, 0, 1, nullptr, (BITMAPINFO*)&bi, DIB_RGB_COLORS)) { - throw rdr::win32_error("Unable to determine pixel shifts/palette", GetLastError()); + throw core::win32_error("Unable to determine pixel shifts/palette", GetLastError()); } // Set the initial format information @@ -151,15 +153,15 @@ Rect DeviceContext::getClipBox(HDC dc) { // Get the display dimensions RECT cr; if (!GetClipBox(dc, &cr)) - throw rdr::win32_error("GetClipBox", GetLastError()); - return Rect(cr.left, cr.top, cr.right, cr.bottom); + throw core::win32_error("GetClipBox", GetLastError()); + return {cr.left, cr.top, cr.right, cr.bottom}; } DeviceDC::DeviceDC(const char* deviceName) { dc = ::CreateDC("DISPLAY", deviceName, nullptr, nullptr); if (!dc) - throw rdr::win32_error("Failed to create DeviceDC", GetLastError()); + throw core::win32_error("Failed to create DeviceDC", GetLastError()); } DeviceDC::~DeviceDC() { @@ -171,7 +173,7 @@ DeviceDC::~DeviceDC() { WindowDC::WindowDC(HWND wnd) : hwnd(wnd) { dc = GetDC(wnd); if (!dc) - throw rdr::win32_error("GetDC failed", GetLastError()); + throw core::win32_error("GetDC failed", GetLastError()); } WindowDC::~WindowDC() { @@ -183,7 +185,7 @@ WindowDC::~WindowDC() { CompatibleDC::CompatibleDC(HDC existing) { dc = CreateCompatibleDC(existing); if (!dc) - throw rdr::win32_error("CreateCompatibleDC failed", GetLastError()); + throw core::win32_error("CreateCompatibleDC failed", GetLastError()); } CompatibleDC::~CompatibleDC() { @@ -195,7 +197,7 @@ CompatibleDC::~CompatibleDC() { BitmapDC::BitmapDC(HDC hdc, HBITMAP hbitmap) : CompatibleDC(hdc){ oldBitmap = (HBITMAP)SelectObject(dc, hbitmap); if (!oldBitmap) - throw rdr::win32_error("SelectObject to CompatibleDC failed", + throw core::win32_error("SelectObject to CompatibleDC failed", GetLastError()); } diff --git a/win/rfb_win32/DeviceContext.h b/win/rfb_win32/DeviceContext.h index 7e89723c7e..a04c80a0ae 100644 --- a/win/rfb_win32/DeviceContext.h +++ b/win/rfb_win32/DeviceContext.h @@ -24,8 +24,10 @@ #define __RFB_WIN32_DEVICECONTEXT_H__ #include + +#include + #include -#include namespace rfb { @@ -40,8 +42,8 @@ namespace rfb { operator HDC() const {return dc;} PixelFormat getPF() const; static PixelFormat getPF(HDC dc); - Rect getClipBox() const; - static Rect getClipBox(HDC dc); + core::Rect getClipBox() const; + static core::Rect getClipBox(HDC dc); protected: HDC dc; }; diff --git a/win/rfb_win32/DeviceFrameBuffer.cxx b/win/rfb_win32/DeviceFrameBuffer.cxx index 9d215041b7..8a7d50f9f2 100644 --- a/win/rfb_win32/DeviceFrameBuffer.cxx +++ b/win/rfb_win32/DeviceFrameBuffer.cxx @@ -27,12 +27,16 @@ #endif #include + +#include + #include #include #include + #include -#include +using namespace core; using namespace rfb; using namespace win32; @@ -102,7 +106,7 @@ DeviceFrameBuffer::grabRect(const Rect &rect) { if (ignoreGrabErrors) vlog.error("BitBlt failed:%ld", GetLastError()); else - throw rdr::win32_error("BitBlt failed", GetLastError()); + throw core::win32_error("BitBlt failed", GetLastError()); } } @@ -123,7 +127,7 @@ void DeviceFrameBuffer::setCursor(HCURSOR hCursor, VNCServer* server) // - If hCursor is null then there is no cursor - clear the old one if (hCursor == nullptr) { - server->setCursor(0, 0, Point(), nullptr); + server->setCursor(0, 0, {}, nullptr); return; } @@ -138,7 +142,7 @@ void DeviceFrameBuffer::setCursor(HCURSOR hCursor, VNCServer* server) BITMAP maskInfo; if (!GetObject(iconInfo.hbmMask, sizeof(BITMAP), &maskInfo)) - throw rdr::win32_error("GetObject() failed", GetLastError()); + throw core::win32_error("GetObject() failed", GetLastError()); if (maskInfo.bmPlanes != 1) throw std::invalid_argument("Unsupported multi-plane cursor"); if (maskInfo.bmBitsPixel != 1) @@ -151,7 +155,7 @@ void DeviceFrameBuffer::setCursor(HCURSOR hCursor, VNCServer* server) buffer.resize(width * height * 4); - Point hotspot = Point(iconInfo.xHotspot, iconInfo.yHotspot); + Point hotspot(iconInfo.xHotspot, iconInfo.yHotspot); if (iconInfo.hbmColor) { // Colour cursor @@ -174,7 +178,7 @@ void DeviceFrameBuffer::setCursor(HCURSOR hCursor, VNCServer* server) if (!GetDIBits(dc, iconInfo.hbmColor, 0, height, buffer.data(), (LPBITMAPINFO)&bi, DIB_RGB_COLORS)) - throw rdr::win32_error("GetDIBits", GetLastError()); + throw core::win32_error("GetDIBits", GetLastError()); // We may not get the RGBA order we want, so shuffle things around int ridx, gidx, bidx, aidx; @@ -217,7 +221,7 @@ void DeviceFrameBuffer::setCursor(HCURSOR hCursor, VNCServer* server) if (!GetBitmapBits(iconInfo.hbmMask, maskInfo.bmWidthBytes * maskInfo.bmHeight, mask.data())) - throw rdr::win32_error("GetBitmapBits", GetLastError()); + throw core::win32_error("GetBitmapBits", GetLastError()); bool doOutline = false; uint8_t* rwbuffer = buffer.data(); diff --git a/win/rfb_win32/DeviceFrameBuffer.h b/win/rfb_win32/DeviceFrameBuffer.h index e9f06cb02b..67b1cd8751 100644 --- a/win/rfb_win32/DeviceFrameBuffer.h +++ b/win/rfb_win32/DeviceFrameBuffer.h @@ -27,11 +27,14 @@ #define __RFB_WIN32_DEVICE_FRAME_BUFFER_H__ #include + +#include +#include + #include + #include -#include #include -#include namespace rfb { @@ -63,13 +66,13 @@ namespace rfb { class DeviceFrameBuffer : public DIBSectionBuffer { public: - DeviceFrameBuffer(HDC deviceContext, const Rect& area_=Rect()); + DeviceFrameBuffer(HDC deviceContext, const core::Rect& area_={}); virtual ~DeviceFrameBuffer(); // - FrameBuffer overrides - virtual void grabRect(const Rect &rect); - void grabRegion(const Region ®ion) override; + virtual void grabRect(const core::Rect& rect); + void grabRegion(const core::Region& region) override; // - DeviceFrameBuffer specific methods @@ -79,15 +82,15 @@ namespace rfb { // Only set this if you are sure you'll capture the errors some other way! void setIgnoreGrabErrors(bool ie) {ignoreGrabErrors=ie;} - static BoolParameter useCaptureBlt; + static core::BoolParameter useCaptureBlt; protected: // Translate supplied Desktop coordinates into Device-relative coordinates // This translation may have been affected at start-time by the supplied sub-rect. - Point desktopToDevice(const Point p) const {return p.translate(deviceCoords.tl);} + core::Point desktopToDevice(const core::Point p) const {return p.translate(deviceCoords.tl);} HDC device; - Rect deviceCoords; + core::Rect deviceCoords; bool ignoreGrabErrors; }; diff --git a/win/rfb_win32/Dialog.cxx b/win/rfb_win32/Dialog.cxx index cf8b2475da..264db3f83b 100644 --- a/win/rfb_win32/Dialog.cxx +++ b/win/rfb_win32/Dialog.cxx @@ -25,9 +25,10 @@ #include #endif +#include +#include + #include -#include -#include #include #ifdef _DIALOG_CAPTURE @@ -43,8 +44,8 @@ using namespace rfb; using namespace rfb::win32; -static LogWriter dlog("Dialog"); -static LogWriter plog("PropSheet"); +static core::LogWriter dlog("Dialog"); +static core::LogWriter plog("PropSheet"); Dialog::Dialog(HINSTANCE inst_) @@ -65,7 +66,7 @@ bool Dialog::showDialog(const char* resource, HWND owner) INT_PTR result = DialogBoxParam(inst, resource, owner, staticDialogProc, (LPARAM)this); if (result<0) - throw rdr::win32_error("DialogBoxParam failed", GetLastError()); + throw core::win32_error("DialogBoxParam failed", GetLastError()); alreadyShowing = false; return (result == 1); } @@ -275,7 +276,7 @@ bool PropSheet::showPropSheet(HWND owner_, bool showApply, bool showCtxtHelp, bo handle = (HWND)PropertySheet(&header); if ((handle == nullptr) || (handle == (HWND)-1)) - throw rdr::win32_error("PropertySheet failed", GetLastError()); + throw core::win32_error("PropertySheet failed", GetLastError()); centerWindow(handle, owner_); plog.info("Created %p", handle); diff --git a/win/rfb_win32/EventManager.cxx b/win/rfb_win32/EventManager.cxx index 995c4fe209..6f45a35c18 100644 --- a/win/rfb_win32/EventManager.cxx +++ b/win/rfb_win32/EventManager.cxx @@ -25,8 +25,11 @@ #include #include -#include +#include +#include + +using namespace core; using namespace rfb; using namespace rfb::win32; diff --git a/win/rfb_win32/IconInfo.h b/win/rfb_win32/IconInfo.h index 991a5a13ae..6348e7b27c 100644 --- a/win/rfb_win32/IconInfo.h +++ b/win/rfb_win32/IconInfo.h @@ -20,7 +20,7 @@ #define __RFB_WIN32_ICONINFO_H__ #include -#include +#include namespace rfb { namespace win32 { @@ -28,7 +28,7 @@ namespace rfb { struct IconInfo : public ICONINFO { IconInfo(HICON icon) { if (!GetIconInfo(icon, this)) - throw rdr::win32_error("GetIconInfo() failed", GetLastError()); + throw core::win32_error("GetIconInfo() failed", GetLastError()); } ~IconInfo() { if (hbmColor) diff --git a/win/rfb_win32/IntervalTimer.h b/win/rfb_win32/IntervalTimer.h index b62040b35e..2e15821c72 100644 --- a/win/rfb_win32/IntervalTimer.h +++ b/win/rfb_win32/IntervalTimer.h @@ -23,6 +23,8 @@ #ifndef __RFB_WIN32_INTERVAL_TIMER_H__ #define __RFB_WIN32_INTERVAL_TIMER_H__ +#include + namespace rfb { namespace win32 { @@ -41,7 +43,7 @@ namespace rfb { if (!active || interval_ != interval) { interval = interval_; if (!SetTimer(hwnd, id, interval, nullptr)) - throw rdr::win32_error("SetTimer", GetLastError()); + throw core::win32_error("SetTimer", GetLastError()); active = true; } } diff --git a/win/rfb_win32/LaunchProcess.cxx b/win/rfb_win32/LaunchProcess.cxx index 93bd21fe36..a9e43fa6fc 100644 --- a/win/rfb_win32/LaunchProcess.cxx +++ b/win/rfb_win32/LaunchProcess.cxx @@ -22,10 +22,12 @@ #include #endif +#include + #include #include #include -#include + #include using namespace rfb; @@ -53,7 +55,7 @@ void LaunchProcess::start(HANDLE userToken, bool createConsole) { char buf[256]; HDESK desktop = GetThreadDesktop(GetCurrentThreadId()); if (!GetUserObjectInformation(desktop, UOI_NAME, buf, 256, &size)) - throw rdr::win32_error("Unable to launch process", GetLastError()); + throw core::win32_error("Unable to launch process", GetLastError()); snprintf(desktopName, 256, "WinSta0\\%s", buf); @@ -95,7 +97,7 @@ void LaunchProcess::start(HANDLE userToken, bool createConsole) { flags, nullptr, nullptr, &sinfo, &procInfo); if (!success) - throw rdr::win32_error("Unable to launch process", GetLastError()); + throw core::win32_error("Unable to launch process", GetLastError()); // Wait for it to finish initialising WaitForInputIdle(procInfo.hProcess, 15000); @@ -119,7 +121,7 @@ bool LaunchProcess::await(DWORD timeoutMs) { detach(); return true; } else if (result == WAIT_FAILED) { - throw rdr::win32_error("await() failed", GetLastError()); + throw core::win32_error("await() failed", GetLastError()); } return false; } diff --git a/win/rfb_win32/LocalMem.h b/win/rfb_win32/LocalMem.h index 5280dea3ce..54ac896bee 100644 --- a/win/rfb_win32/LocalMem.h +++ b/win/rfb_win32/LocalMem.h @@ -20,7 +20,7 @@ #define __RFB_WIN32_LOCALMEM_H__ #include -#include +#include namespace rfb { namespace win32 { @@ -28,7 +28,7 @@ namespace rfb { // Allocate and/or manage LocalAlloc memory. struct LocalMem { LocalMem(int size) : ptr(LocalAlloc(LMEM_FIXED, size)) { - if (!ptr) throw rdr::win32_error("LocalAlloc", GetLastError()); + if (!ptr) throw core::win32_error("LocalAlloc", GetLastError()); } LocalMem(void* p) : ptr(p) {} ~LocalMem() {LocalFree(ptr);} diff --git a/win/rfb_win32/MonitorInfo.cxx b/win/rfb_win32/MonitorInfo.cxx index 5d715ef61f..5b1f55332f 100644 --- a/win/rfb_win32/MonitorInfo.cxx +++ b/win/rfb_win32/MonitorInfo.cxx @@ -20,10 +20,11 @@ #include #endif +#include +#include + #include #include -#include -#include #ifndef min #define min(a,b) ((a)<(b)?(a):(b)) @@ -33,6 +34,7 @@ #define max(a,b) ((a)>(b)?(a):(b)) #endif +using namespace core; using namespace rfb; using namespace win32; @@ -44,7 +46,7 @@ static void fillMonitorInfo(HMONITOR monitor, MONITORINFOEXA* mi) { memset(mi, 0, sizeof(MONITORINFOEXA)); mi->cbSize = sizeof(MONITORINFOEXA); if (!GetMonitorInfo(monitor, mi)) - throw rdr::win32_error("Failed to GetMonitorInfo", GetLastError()); + throw core::win32_error("Failed to GetMonitorInfo", GetLastError()); vlog.debug("Monitor is %ld,%ld-%ld,%ld", mi->rcMonitor.left, mi->rcMonitor.top, mi->rcMonitor.right, mi->rcMonitor.bottom); vlog.debug("Work area is %ld,%ld-%ld,%ld", mi->rcWork.left, mi->rcWork.top, mi->rcWork.right, mi->rcWork.bottom); vlog.debug("Device is \"%s\"", mi->szDevice); @@ -57,7 +59,7 @@ MonitorInfo::MonitorInfo(HWND window) { HMONITOR monitor = MonitorFromWindow(window, MONITOR_DEFAULTTONEAREST); if (!monitor) - throw rdr::win32_error("Failed to get monitor", GetLastError()); + throw core::win32_error("Failed to get monitor", GetLastError()); fillMonitorInfo(monitor, this); } @@ -67,7 +69,7 @@ MonitorInfo::MonitorInfo(const RECT& r) { HMONITOR monitor = MonitorFromRect(&r, MONITOR_DEFAULTTONEAREST); if (!monitor) - throw rdr::win32_error("Failed to get monitor", GetLastError()); + throw core::win32_error("Failed to get monitor", GetLastError()); fillMonitorInfo(monitor, this); } diff --git a/win/rfb_win32/MsgWindow.cxx b/win/rfb_win32/MsgWindow.cxx index c89db851da..4b20dc88c3 100644 --- a/win/rfb_win32/MsgWindow.cxx +++ b/win/rfb_win32/MsgWindow.cxx @@ -23,16 +23,18 @@ #include #endif +#include +#include + #include #include -#include -#include + #include using namespace rfb; using namespace rfb::win32; -static LogWriter vlog("MsgWindow"); +static core::LogWriter vlog("MsgWindow"); // // -=- MsgWindowClass @@ -82,7 +84,7 @@ MsgWindowClass::MsgWindowClass() : classAtom(0) { wndClass.lpszClassName = "rfb::win32::MsgWindowClass"; classAtom = RegisterClass(&wndClass); if (!classAtom) { - throw rdr::win32_error("Unable to register MsgWindow window class", GetLastError()); + throw core::win32_error("Unable to register MsgWindow window class", GetLastError()); } } @@ -104,7 +106,7 @@ MsgWindow::MsgWindow(const char* name_) : name(name_), handle(nullptr) { name.c_str(), WS_OVERLAPPED, 0, 0, 10, 10, nullptr, nullptr, baseClass.instance, this); if (!handle) { - throw rdr::win32_error("Unable to create WMNotifier window instance", GetLastError()); + throw core::win32_error("Unable to create WMNotifier window instance", GetLastError()); } vlog.debug("Created window \"%s\" (%p)", name.c_str(), handle); } diff --git a/win/rfb_win32/RegConfig.cxx b/win/rfb_win32/RegConfig.cxx index d983520174..7d80871f79 100644 --- a/win/rfb_win32/RegConfig.cxx +++ b/win/rfb_win32/RegConfig.cxx @@ -24,15 +24,17 @@ #include +#include + #include -#include + //#include using namespace rfb; using namespace rfb::win32; -static LogWriter vlog("RegConfig"); +static core::LogWriter vlog("RegConfig"); RegConfig::RegConfig(EventManager* em) @@ -66,10 +68,10 @@ void RegConfig::loadRegistryConfig(RegKey& key) { const char *name = key.getValueName(i++); if (!name) break; std::string value = key.getRepresentation(name); - if (!Configuration::setParam(name, value.c_str())) + if (!core::Configuration::setParam(name, value.c_str())) vlog.info("Unable to process %s", name); } - } catch (rdr::win32_error& e) { + } catch (core::win32_error& e) { if (e.err != ERROR_INVALID_HANDLE) vlog.error("%s", e.what()); } @@ -115,5 +117,5 @@ void RegConfigThread::worker() { thread_id = GetCurrentThreadId(); while ((result = eventMgr.getMessage(&msg, nullptr, 0, 0)) > 0) {} if (result < 0) - throw rdr::win32_error("RegConfigThread failed", GetLastError()); + throw core::win32_error("RegConfigThread failed", GetLastError()); } diff --git a/win/rfb_win32/RegConfig.h b/win/rfb_win32/RegConfig.h index 401cb14826..00b305cf32 100644 --- a/win/rfb_win32/RegConfig.h +++ b/win/rfb_win32/RegConfig.h @@ -24,9 +24,9 @@ #ifndef __RFB_WIN32_REG_CONFIG_H__ #define __RFB_WIN32_REG_CONFIG_H__ -#include +#include +#include -#include #include #include #include @@ -64,7 +64,7 @@ namespace rfb { RegKey key; }; - class RegConfigThread : os::Thread { + class RegConfigThread : core::Thread { public: RegConfigThread(); ~RegConfigThread(); diff --git a/win/rfb_win32/Registry.cxx b/win/rfb_win32/Registry.cxx index d40c901645..aef15a1ba7 100644 --- a/win/rfb_win32/Registry.cxx +++ b/win/rfb_win32/Registry.cxx @@ -22,14 +22,17 @@ #include #endif +#include +#include + #include #include + #include #include #include + #include -#include -#include // These flags are required to control access control inheritance, // but are not defined by VC6's headers. These definitions comes @@ -42,6 +45,7 @@ #endif +using namespace core; using namespace rfb; using namespace rfb::win32; @@ -54,7 +58,7 @@ RegKey::RegKey() : key(nullptr), freeKey(false), valueName(nullptr), valueNameBu RegKey::RegKey(const HKEY k) : key(nullptr), freeKey(false), valueName(nullptr), valueNameBufLen(0) { LONG result = RegOpenKeyEx(k, nullptr, 0, KEY_ALL_ACCESS, &key); if (result != ERROR_SUCCESS) - throw rdr::win32_error("RegOpenKeyEx(HKEY)", result); + throw core::win32_error("RegOpenKeyEx(HKEY)", result); vlog.debug("Duplicated %p to %p", k, key); freeKey = true; } @@ -62,7 +66,7 @@ RegKey::RegKey(const HKEY k) : key(nullptr), freeKey(false), valueName(nullptr), RegKey::RegKey(const RegKey& k) : key(nullptr), freeKey(false), valueName(nullptr), valueNameBufLen(0) { LONG result = RegOpenKeyEx(k.key, nullptr, 0, KEY_ALL_ACCESS, &key); if (result != ERROR_SUCCESS) - throw rdr::win32_error("RegOpenKeyEx(RegKey&)", result); + throw core::win32_error("RegOpenKeyEx(RegKey&)", result); vlog.debug("Duplicated %p to %p", k.key, key); freeKey = true; } @@ -86,7 +90,7 @@ bool RegKey::createKey(const RegKey& root, const char* name) { LONG result = RegCreateKey(root.key, name, &key); if (result != ERROR_SUCCESS) { vlog.error("RegCreateKey(%p, %s): %lx", root.key, name, result); - throw rdr::win32_error("RegCreateKeyEx", result); + throw core::win32_error("RegCreateKeyEx", result); } vlog.debug("createKey(%p,%s) = %p", root.key, name, key); freeKey = true; @@ -97,7 +101,7 @@ void RegKey::openKey(const RegKey& root, const char* name, bool readOnly) { close(); LONG result = RegOpenKeyEx(root.key, name, 0, readOnly ? KEY_READ : KEY_ALL_ACCESS, &key); if (result != ERROR_SUCCESS) - throw rdr::win32_error("RegOpenKeyEx (open)", result); + throw core::win32_error("RegOpenKeyEx (open)", result); vlog.debug("openKey(%p,%s,%s) = %p", root.key, name, readOnly ? "ro" : "rw", key); freeKey = true; @@ -109,7 +113,7 @@ void RegKey::setDACL(const PACL acl, bool inherit) { DACL_SECURITY_INFORMATION | (inherit ? UNPROTECTED_DACL_SECURITY_INFORMATION : PROTECTED_DACL_SECURITY_INFORMATION), nullptr, nullptr, acl, nullptr)) != ERROR_SUCCESS) - throw rdr::win32_error("RegKey::setDACL failed", result); + throw core::win32_error("RegKey::setDACL failed", result); } void RegKey::close() { @@ -123,19 +127,19 @@ void RegKey::close() { void RegKey::deleteKey(const char* name) const { LONG result = RegDeleteKey(key, name); if (result != ERROR_SUCCESS) - throw rdr::win32_error("RegDeleteKey", result); + throw core::win32_error("RegDeleteKey", result); } void RegKey::deleteValue(const char* name) const { LONG result = RegDeleteValue(key, name); if (result != ERROR_SUCCESS) - throw rdr::win32_error("RegDeleteValue", result); + throw core::win32_error("RegDeleteValue", result); } void RegKey::awaitChange(bool watchSubTree, DWORD filter, HANDLE event) const { LONG result = RegNotifyChangeKeyValue(key, watchSubTree, filter, event, event != nullptr); if (result != ERROR_SUCCESS) - throw rdr::win32_error("RegNotifyChangeKeyValue", result); + throw core::win32_error("RegNotifyChangeKeyValue", result); } @@ -144,22 +148,22 @@ RegKey::operator HKEY() const {return key;} void RegKey::setExpandString(const char* valname, const char* value) const { LONG result = RegSetValueEx(key, valname, 0, REG_EXPAND_SZ, (const BYTE*)value, (strlen(value)+1)*sizeof(char)); - if (result != ERROR_SUCCESS) throw rdr::win32_error("setExpandString", result); + if (result != ERROR_SUCCESS) throw core::win32_error("setExpandString", result); } void RegKey::setString(const char* valname, const char* value) const { LONG result = RegSetValueEx(key, valname, 0, REG_SZ, (const BYTE*)value, (strlen(value)+1)*sizeof(char)); - if (result != ERROR_SUCCESS) throw rdr::win32_error("setString", result); + if (result != ERROR_SUCCESS) throw core::win32_error("setString", result); } void RegKey::setBinary(const char* valname, const void* value, size_t length) const { LONG result = RegSetValueEx(key, valname, 0, REG_BINARY, (const BYTE*)value, length); - if (result != ERROR_SUCCESS) throw rdr::win32_error("setBinary", result); + if (result != ERROR_SUCCESS) throw core::win32_error("setBinary", result); } void RegKey::setInt(const char* valname, int value) const { LONG result = RegSetValueEx(key, valname, 0, REG_DWORD, (const BYTE*)&value, sizeof(value)); - if (result != ERROR_SUCCESS) throw rdr::win32_error("setInt", result); + if (result != ERROR_SUCCESS) throw core::win32_error("setInt", result); } void RegKey::setBool(const char* valname, bool value) const { @@ -214,11 +218,11 @@ std::string RegKey::getRepresentation(const char* valname) const { DWORD type, length; LONG result = RegQueryValueEx(key, valname, nullptr, &type, nullptr, &length); if (result != ERROR_SUCCESS) - throw rdr::win32_error("Get registry value length", result); + throw core::win32_error("Get registry value length", result); std::vector data(length); result = RegQueryValueEx(key, valname, nullptr, &type, (BYTE*)data.data(), &length); if (result != ERROR_SUCCESS) - throw rdr::win32_error("Get registry value", result); + throw core::win32_error("Get registry value", result); switch (type) { case REG_BINARY: @@ -243,7 +247,7 @@ std::string RegKey::getRepresentation(const char* valname) const { std::string str((char*)data.data(), length); DWORD required = ExpandEnvironmentStrings(str.c_str(), nullptr, 0); if (required==0) - throw rdr::win32_error("ExpandEnvironmentStrings", GetLastError()); + throw core::win32_error("ExpandEnvironmentStrings", GetLastError()); std::vector expanded(required); length = ExpandEnvironmentStrings(str.c_str(), expanded.data(), required); if (required +#include + #include #include #include @@ -35,10 +37,11 @@ #include #include #include -#include +#include #include +using namespace core; using namespace rdr; using namespace rfb; using namespace rfb::win32; @@ -460,8 +463,8 @@ SDisplay::recreatePixelBuffer(bool force) { Rect newScreenRect; if (strlen(displayDevice) > 0) { MonitorInfo info(displayDevice); - newScreenRect = Rect(info.rcMonitor.left, info.rcMonitor.top, - info.rcMonitor.right, info.rcMonitor.bottom); + newScreenRect = {info.rcMonitor.left, info.rcMonitor.top, + info.rcMonitor.right, info.rcMonitor.bottom}; } else { newScreenRect = new_device->getClipBox(); } diff --git a/win/rfb_win32/SDisplay.h b/win/rfb_win32/SDisplay.h index aa1a69e553..e2bba019eb 100644 --- a/win/rfb_win32/SDisplay.h +++ b/win/rfb_win32/SDisplay.h @@ -24,9 +24,11 @@ #ifndef __RFB_SDISPLAY_H__ #define __RFB_SDISPLAY_H__ +#include + #include #include -#include + #include #include #include @@ -48,7 +50,7 @@ namespace rfb { class SDisplayCore { public: virtual ~SDisplayCore() {}; - virtual void setScreenRect(const Rect& screenRect_) = 0; + virtual void setScreenRect(const core::Rect& screenRect_) = 0; virtual void flushUpdates() = 0; virtual const char* methodName() const = 0; }; @@ -80,7 +82,8 @@ namespace rfb { void handleClipboardRequest() override; void handleClipboardAnnounce(bool available) override; void handleClipboardData(const char* data) override; - void pointerEvent(const Point& pos, uint16_t buttonmask) override; + void pointerEvent(const core::Point& pos, + uint16_t buttonmask) override; void keyEvent(uint32_t keysym, uint32_t keycode, bool down) override; // -=- Clipboard events @@ -107,11 +110,11 @@ namespace rfb { queryConnectionHandler = qch; } - static IntParameter updateMethod; - static BoolParameter disableLocalInputs; - static StringParameter disconnectAction; - static BoolParameter removeWallpaper; - static BoolParameter disableEffects; + static core::IntParameter updateMethod; + static core::BoolParameter disableLocalInputs; + static core::StringParameter disconnectAction; + static core::BoolParameter removeWallpaper; + static core::BoolParameter disableEffects; // -=- Use by VNC Config to determine whether hooks are available static bool areHooksAvailable(); @@ -133,7 +136,7 @@ namespace rfb { DeviceContext* device; // -=- The coordinates of Window's entire virtual Screen - Rect screenRect; + core::Rect screenRect; // -=- All changes are collected in UN-CLIPPED Display coords and merged // When they are to be flushed to the VNCServer, they are changed @@ -162,8 +165,8 @@ namespace rfb { // Cursor WMCursor* cursor; WMCursor::Info old_cursor; - Region old_cursor_region; - Point cursor_renderpos; + core::Region old_cursor_region; + core::Point cursor_renderpos; // -=- Event signalled to trigger an update to be flushed Handle updateEvent; diff --git a/win/rfb_win32/SDisplayCorePolling.cxx b/win/rfb_win32/SDisplayCorePolling.cxx index bd8883e664..0a600c9743 100644 --- a/win/rfb_win32/SDisplayCorePolling.cxx +++ b/win/rfb_win32/SDisplayCorePolling.cxx @@ -22,9 +22,11 @@ #include #endif +#include + #include -#include +using namespace core; using namespace rfb; using namespace rfb::win32; @@ -37,7 +39,9 @@ const unsigned int SDisplayCorePolling::pollTimerId = 1; SDisplayCorePolling::SDisplayCorePolling(SDisplay* d, UpdateTracker* ut, int pollInterval_) : MsgWindow("rfb::win32::SDisplayCorePolling"), pollTimer(getHandle(), pollTimerId), pollNextStrip(false), display(d), updateTracker(ut) { - pollInterval = __rfbmax(10, (pollInterval_ / POLLING_SEGMENTS)); + pollInterval = pollInterval_ / POLLING_SEGMENTS; + if (pollInterval < 10) + pollInterval = 10; copyrect.setUpdateTracker(ut); } @@ -78,7 +82,8 @@ void SDisplayCorePolling::flushUpdates() { // No. Poll the next section pollrect.tl.y = pollNextY; pollNextY += pollIncrementY; - pollrect.br.y = __rfbmin(pollNextY, pollrect.br.y); + if (pollrect.br.y > pollNextY) + pollrect.br.y = pollNextY; updateTracker->add_changed(pollrect); } } diff --git a/win/rfb_win32/SDisplayCorePolling.h b/win/rfb_win32/SDisplayCorePolling.h index 00de2d40f0..bfd72d746a 100644 --- a/win/rfb_win32/SDisplayCorePolling.h +++ b/win/rfb_win32/SDisplayCorePolling.h @@ -40,7 +40,7 @@ namespace rfb { ~SDisplayCorePolling(); // - Called by SDisplay to inform Core of the screen size - void setScreenRect(const Rect& screenRect_) override; + void setScreenRect(const core::Rect& screenRect_) override; // - Called by SDisplay to flush updates to the specified tracker void flushUpdates() override; @@ -58,7 +58,7 @@ namespace rfb { // - Background full screen polling fields IntervalTimer pollTimer; static const unsigned int pollTimerId; - Rect screenRect; + core::Rect screenRect; int pollInterval; int pollNextY; int pollIncrementY; diff --git a/win/rfb_win32/SDisplayCoreWMHooks.cxx b/win/rfb_win32/SDisplayCoreWMHooks.cxx index 056ff4cb09..62ab8f75e1 100644 --- a/win/rfb_win32/SDisplayCoreWMHooks.cxx +++ b/win/rfb_win32/SDisplayCoreWMHooks.cxx @@ -22,9 +22,11 @@ #include #endif +#include + #include -#include +using namespace core; using namespace rfb; using namespace rfb::win32; diff --git a/win/rfb_win32/SInput.cxx b/win/rfb_win32/SInput.cxx index 13ac9f269e..2a772fe84c 100644 --- a/win/rfb_win32/SInput.cxx +++ b/win/rfb_win32/SInput.cxx @@ -30,13 +30,15 @@ #define XK_CURRENCY #include +#include +#include + #include #include #include #include -#include -#include +using namespace core; using namespace rfb; static LogWriter vlog("SInput"); @@ -126,7 +128,7 @@ win32::SPointer::pointerEvent(const Point& pos, uint16_t buttonmask) evt.mi.mouseData = data; evt.mi.time = 0; if (SendInput(1, &evt, sizeof(evt)) != 1) - throw rdr::win32_error("SendInput", GetLastError()); + throw core::win32_error("SendInput", GetLastError()); } } diff --git a/win/rfb_win32/SInput.h b/win/rfb_win32/SInput.h index 018bec55c4..6f1341ee01 100644 --- a/win/rfb_win32/SInput.h +++ b/win/rfb_win32/SInput.h @@ -24,8 +24,8 @@ #ifndef __RFB_WIN32_INPUT_H__ #define __RFB_WIN32_INPUT_H__ -#include -#include +#include +#include #include #include @@ -44,9 +44,9 @@ namespace rfb { // - Create a pointer event at a the given coordinates, with the // specified button state. The event must be specified using // Screen coordinates. - void pointerEvent(const Point& pos, uint16_t buttonmask); + void pointerEvent(const core::Point& pos, uint16_t buttonmask); protected: - Point last_position; + core::Point last_position; uint16_t last_buttonmask; }; @@ -56,8 +56,8 @@ namespace rfb { public: SKeyboard(); void keyEvent(uint32_t keysym, uint32_t keycode, bool down); - static BoolParameter deadKeyAware; - static BoolParameter rawKeyboard; + static core::BoolParameter deadKeyAware; + static core::BoolParameter rawKeyboard; private: std::map vkMap; std::map extendedMap; diff --git a/win/rfb_win32/Security.cxx b/win/rfb_win32/Security.cxx index 8f000e1bbc..eededb6ada 100644 --- a/win/rfb_win32/Security.cxx +++ b/win/rfb_win32/Security.cxx @@ -22,13 +22,15 @@ #include #endif +#include + #include -#include #include #include #include +using namespace core; using namespace rfb; using namespace rfb::win32; @@ -99,7 +101,7 @@ PSID Sid::copySID(const PSID sid) { throw std::invalid_argument("Invalid SID in copyPSID"); PSID buf = (PSID)new uint8_t[GetLengthSid(sid)]; if (!CopySid(GetLengthSid(sid), buf, sid)) - throw rdr::win32_error("CopySid failed", GetLastError()); + throw core::win32_error("CopySid failed", GetLastError()); return buf; } @@ -108,7 +110,7 @@ void Sid::setSID(const PSID sid) { throw std::invalid_argument("Invalid SID in copyPSID"); resize(GetLengthSid(sid)); if (!CopySid(GetLengthSid(sid), data(), sid)) - throw rdr::win32_error("CopySid failed", GetLastError()); + throw core::win32_error("CopySid failed", GetLastError()); } void Sid::getUserNameAndDomain(char** name, char** domain) { @@ -117,12 +119,12 @@ void Sid::getUserNameAndDomain(char** name, char** domain) { SID_NAME_USE use; LookupAccountSid(nullptr, (PSID)*this, nullptr, &nameLen, nullptr, &domainLen, &use); if (GetLastError() != ERROR_INSUFFICIENT_BUFFER) - throw rdr::win32_error("Unable to determine SID name lengths", GetLastError()); + throw core::win32_error("Unable to determine SID name lengths", GetLastError()); vlog.info("nameLen=%lu, domainLen=%lu, use=%d", nameLen, domainLen, use); *name = new char[nameLen]; *domain = new char[domainLen]; if (!LookupAccountSid(nullptr, (PSID)*this, *name, &nameLen, *domain, &domainLen, &use)) - throw rdr::win32_error("Unable to lookup account SID", GetLastError()); + throw core::win32_error("Unable to lookup account SID", GetLastError()); } @@ -133,7 +135,7 @@ Sid::Administrators::Administrators() { SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &sid)) - throw rdr::win32_error("Sid::Administrators", GetLastError()); + throw core::win32_error("Sid::Administrators", GetLastError()); setSID(sid); FreeSid(sid); } @@ -144,7 +146,7 @@ Sid::SYSTEM::SYSTEM() { if (!AllocateAndInitializeSid(&ntAuth, 1, SECURITY_LOCAL_SYSTEM_RID, 0, 0, 0, 0, 0, 0, 0, &sid)) - throw rdr::win32_error("Sid::SYSTEM", GetLastError()); + throw core::win32_error("Sid::SYSTEM", GetLastError()); setSID(sid); FreeSid(sid); } @@ -154,7 +156,7 @@ Sid::FromToken::FromToken(HANDLE h) { GetTokenInformation(h, TokenUser, nullptr, 0, &required); std::vector tmp(required); if (!GetTokenInformation(h, TokenUser, tmp.data(), tmp.size(), &required)) - throw rdr::win32_error("GetTokenInformation", GetLastError()); + throw core::win32_error("GetTokenInformation", GetLastError()); TOKEN_USER* tokenUser = (TOKEN_USER*)tmp.data(); setSID(tokenUser->User.Sid); } @@ -164,7 +166,7 @@ PACL rfb::win32::CreateACL(const AccessEntries& ae, PACL existing_acl) { PACL new_dacl; DWORD result; if ((result = SetEntriesInAcl(ae.entry_count, ae.entries, existing_acl, &new_dacl)) != ERROR_SUCCESS) - throw rdr::win32_error("SetEntriesInAcl", result); + throw core::win32_error("SetEntriesInAcl", result); return new_dacl; } @@ -172,18 +174,18 @@ PACL rfb::win32::CreateACL(const AccessEntries& ae, PACL existing_acl) { PSECURITY_DESCRIPTOR rfb::win32::CreateSdWithDacl(const PACL dacl) { SECURITY_DESCRIPTOR absSD; if (!InitializeSecurityDescriptor(&absSD, SECURITY_DESCRIPTOR_REVISION)) - throw rdr::win32_error("InitializeSecurityDescriptor", GetLastError()); + throw core::win32_error("InitializeSecurityDescriptor", GetLastError()); Sid::SYSTEM owner; if (!SetSecurityDescriptorOwner(&absSD, owner, FALSE)) - throw rdr::win32_error("SetSecurityDescriptorOwner", GetLastError()); + throw core::win32_error("SetSecurityDescriptorOwner", GetLastError()); Sid::Administrators group; if (!SetSecurityDescriptorGroup(&absSD, group, FALSE)) - throw rdr::win32_error("SetSecurityDescriptorGroupp", GetLastError()); + throw core::win32_error("SetSecurityDescriptorGroupp", GetLastError()); if (!SetSecurityDescriptorDacl(&absSD, TRUE, dacl, FALSE)) - throw rdr::win32_error("SetSecurityDescriptorDacl", GetLastError()); + throw core::win32_error("SetSecurityDescriptorDacl", GetLastError()); DWORD sdSize = GetSecurityDescriptorLength(&absSD); SecurityDescriptorPtr sd(sdSize); if (!MakeSelfRelativeSD(&absSD, (PSECURITY_DESCRIPTOR)sd.ptr, &sdSize)) - throw rdr::win32_error("MakeSelfRelativeSD", GetLastError()); + throw core::win32_error("MakeSelfRelativeSD", GetLastError()); return sd.takeSD(); } diff --git a/win/rfb_win32/SecurityPage.cxx b/win/rfb_win32/SecurityPage.cxx index a6f026cf2c..f8523bc44c 100644 --- a/win/rfb_win32/SecurityPage.cxx +++ b/win/rfb_win32/SecurityPage.cxx @@ -21,9 +21,9 @@ #include #endif -#include +#include +#include -#include #include #include @@ -31,7 +31,7 @@ #include -using namespace rdr; +using namespace core; using namespace rfb; using namespace rfb::win32; using namespace std; diff --git a/win/rfb_win32/Service.cxx b/win/rfb_win32/Service.cxx index bc9875e593..d28fdb7538 100644 --- a/win/rfb_win32/Service.cxx +++ b/win/rfb_win32/Service.cxx @@ -22,18 +22,19 @@ #include #endif +#include +#include +#include + #include #include #include #include #include -#include -#include -#include -#include +#include -using namespace rdr; +using namespace core; using namespace rfb; using namespace win32; @@ -335,7 +336,7 @@ bool rfb::win32::registerService(const char* name, // - Open the SCM ServiceHandle scm = OpenSCManager(nullptr, nullptr, SC_MANAGER_CREATE_SERVICE); if (!scm) - throw rdr::win32_error("Unable to open Service Control Manager", GetLastError()); + throw core::win32_error("Unable to open Service Control Manager", GetLastError()); // - Add the service ServiceHandle handle = CreateService(scm, @@ -344,7 +345,7 @@ bool rfb::win32::registerService(const char* name, SERVICE_AUTO_START, SERVICE_ERROR_IGNORE, cmdline.c_str(), nullptr, nullptr, nullptr, nullptr, nullptr); if (!handle) - throw rdr::win32_error("Unable to create service", GetLastError()); + throw core::win32_error("Unable to create service", GetLastError()); // - Set a description SERVICE_DESCRIPTION sdesc = {(LPTSTR)desc}; @@ -380,14 +381,14 @@ bool rfb::win32::unregisterService(const char* name) { // - Open the SCM ServiceHandle scm = OpenSCManager(nullptr, nullptr, SC_MANAGER_CREATE_SERVICE); if (!scm) - throw rdr::win32_error("Unable to open Service Control Manager", GetLastError()); + throw core::win32_error("Unable to open Service Control Manager", GetLastError()); // - Create the service ServiceHandle handle = OpenService(scm, name, SC_MANAGER_ALL_ACCESS); if (!handle) - throw rdr::win32_error("Unable to locate the service", GetLastError()); + throw core::win32_error("Unable to locate the service", GetLastError()); if (!DeleteService(handle)) - throw rdr::win32_error("Unable to remove the service", GetLastError()); + throw core::win32_error("Unable to remove the service", GetLastError()); // - Register the event log source RegKey hk; @@ -407,16 +408,16 @@ bool rfb::win32::startService(const char* name) { // - Open the SCM ServiceHandle scm = OpenSCManager(nullptr, nullptr, SC_MANAGER_CONNECT); if (!scm) - throw rdr::win32_error("Unable to open Service Control Manager", GetLastError()); + throw core::win32_error("Unable to open Service Control Manager", GetLastError()); // - Locate the service ServiceHandle handle = OpenService(scm, name, SERVICE_START); if (!handle) - throw rdr::win32_error("Unable to open the service", GetLastError()); + throw core::win32_error("Unable to open the service", GetLastError()); // - Start the service if (!StartService(handle, 0, nullptr)) - throw rdr::win32_error("Unable to start the service", GetLastError()); + throw core::win32_error("Unable to start the service", GetLastError()); Sleep(500); @@ -427,17 +428,17 @@ bool rfb::win32::stopService(const char* name) { // - Open the SCM ServiceHandle scm = OpenSCManager(nullptr, nullptr, SC_MANAGER_CONNECT); if (!scm) - throw rdr::win32_error("Unable to open Service Control Manager", GetLastError()); + throw core::win32_error("Unable to open Service Control Manager", GetLastError()); // - Locate the service ServiceHandle handle = OpenService(scm, name, SERVICE_STOP); if (!handle) - throw rdr::win32_error("Unable to open the service", GetLastError()); + throw core::win32_error("Unable to open the service", GetLastError()); // - Start the service SERVICE_STATUS status; if (!ControlService(handle, SERVICE_CONTROL_STOP, &status)) - throw rdr::win32_error("Unable to stop the service", GetLastError()); + throw core::win32_error("Unable to stop the service", GetLastError()); Sleep(500); @@ -448,17 +449,17 @@ DWORD rfb::win32::getServiceState(const char* name) { // - Open the SCM ServiceHandle scm = OpenSCManager(nullptr, nullptr, SC_MANAGER_CONNECT); if (!scm) - throw rdr::win32_error("Unable to open Service Control Manager", GetLastError()); + throw core::win32_error("Unable to open Service Control Manager", GetLastError()); // - Locate the service ServiceHandle handle = OpenService(scm, name, SERVICE_INTERROGATE); if (!handle) - throw rdr::win32_error("Unable to open the service", GetLastError()); + throw core::win32_error("Unable to open the service", GetLastError()); // - Get the service status SERVICE_STATUS status; if (!ControlService(handle, SERVICE_CONTROL_INTERROGATE, (SERVICE_STATUS*)&status)) - throw rdr::win32_error("Unable to query the service", GetLastError()); + throw core::win32_error("Unable to query the service", GetLastError()); return status.dwCurrentState; } diff --git a/win/rfb_win32/SocketManager.cxx b/win/rfb_win32/SocketManager.cxx index 7f6d1773b3..9a22ee14f9 100644 --- a/win/rfb_win32/SocketManager.cxx +++ b/win/rfb_win32/SocketManager.cxx @@ -25,16 +25,19 @@ #include #include -#include +#include +#include +#include +#include + +#include #include -#include -#include #include -#include #include +using namespace core; using namespace rfb; using namespace rfb::win32; @@ -69,7 +72,7 @@ void SocketManager::addListener(network::SocketListener* sock_, flags |= FD_ADDRESS_LIST_CHANGE; try { if (event && (WSAEventSelect(sock_->getFd(), event, flags) == SOCKET_ERROR)) - throw rdr::socket_error("Unable to select on listener", WSAGetLastError()); + throw core::socket_error("Unable to select on listener", WSAGetLastError()); // requestAddressChangeEvents MUST happen after WSAEventSelect, so that the socket is non-blocking if (acn) @@ -186,7 +189,7 @@ int SocketManager::checkTimeouts() { if (j->second.sock->outStream().hasBufferedData()) eventMask |= FD_WRITE; if (WSAEventSelect(j->second.sock->getFd(), j->first, eventMask) == SOCKET_ERROR) - throw rdr::socket_error("unable to adjust WSAEventSelect:%u", WSAGetLastError()); + throw core::socket_error("unable to adjust WSAEventSelect:%u", WSAGetLastError()); } } @@ -236,11 +239,11 @@ void SocketManager::processEvent(HANDLE event) { // Fetch why this event notification triggered if (WSAEnumNetworkEvents(ci.sock->getFd(), event, &network_events) == SOCKET_ERROR) - throw rdr::socket_error("Unable to get WSAEnumNetworkEvents:%u", WSAGetLastError()); + throw core::socket_error("Unable to get WSAEnumNetworkEvents:%u", WSAGetLastError()); // Cancel event notification for this socket if (WSAEventSelect(ci.sock->getFd(), event, 0) == SOCKET_ERROR) - throw rdr::socket_error("unable to disable WSAEventSelect:%u", WSAGetLastError()); + throw core::socket_error("unable to disable WSAEventSelect:%u", WSAGetLastError()); // Reset the event object WSAResetEvent(event); @@ -268,7 +271,7 @@ void SocketManager::processEvent(HANDLE event) { if (ci.sock->outStream().hasBufferedData()) eventMask |= FD_WRITE; if (WSAEventSelect(ci.sock->getFd(), event, eventMask) == SOCKET_ERROR) - throw rdr::socket_error("unable to re-enable WSAEventSelect:%u", WSAGetLastError()); + throw core::socket_error("unable to re-enable WSAEventSelect:%u", WSAGetLastError()); } catch (std::exception& e) { vlog.error("%s", e.what()); remSocket(ci.sock); diff --git a/win/rfb_win32/TrayIcon.h b/win/rfb_win32/TrayIcon.h index b4e75ea586..9eccc937dc 100644 --- a/win/rfb_win32/TrayIcon.h +++ b/win/rfb_win32/TrayIcon.h @@ -25,8 +25,8 @@ #include #include + #include -#include namespace rfb { diff --git a/win/rfb_win32/TsSessions.cxx b/win/rfb_win32/TsSessions.cxx index faf83e894c..77d6cc528f 100644 --- a/win/rfb_win32/TsSessions.cxx +++ b/win/rfb_win32/TsSessions.cxx @@ -20,12 +20,14 @@ #include #endif +#include +#include + #include -#include -#include + #include -static rfb::LogWriter vlog("TsSessions"); +static core::LogWriter vlog("TsSessions"); namespace rfb { namespace win32 { @@ -35,7 +37,7 @@ namespace win32 { if (processId == (DWORD)-1) processId = GetCurrentProcessId(); if (!ProcessIdToSessionId(GetCurrentProcessId(), &id)) - throw rdr::win32_error("ProcessIdToSessionId", GetLastError()); + throw core::win32_error("ProcessIdToSessionId", GetLastError()); } ProcessSessionId mySessionId; @@ -57,7 +59,7 @@ namespace win32 { ConsoleSessionId console; vlog.info("Console session is %lu", console.id); if (!WTSConnectSession(sessionId, console.id, (PTSTR)"", 0)) - throw rdr::win32_error("Unable to connect session to Console", GetLastError()); + throw core::win32_error("Unable to connect session to Console", GetLastError()); // Lock the newly connected session, for security LockWorkStation(); diff --git a/win/rfb_win32/WMCursor.cxx b/win/rfb_win32/WMCursor.cxx index 65d7a9d7bf..4481f3f724 100644 --- a/win/rfb_win32/WMCursor.cxx +++ b/win/rfb_win32/WMCursor.cxx @@ -22,11 +22,14 @@ #include #endif +#include +#include + #include + #include -#include -using namespace rdr; +using namespace core; using namespace rfb; using namespace rfb::win32; @@ -45,9 +48,9 @@ WMCursor::getCursorInfo() { CURSORINFO info; info.cbSize = sizeof(CURSORINFO); if (!GetCursorInfo(&info)) - throw rdr::win32_error("GetCursorInfo failed", GetLastError()); + throw core::win32_error("GetCursorInfo failed", GetLastError()); result.cursor = info.hCursor; - result.position = Point(info.ptScreenPos.x, info.ptScreenPos.y); + result.position = {info.ptScreenPos.x, info.ptScreenPos.y}; result.visible = info.flags & CURSOR_SHOWING; return result; } diff --git a/win/rfb_win32/WMCursor.h b/win/rfb_win32/WMCursor.h index 465331dec3..1df5074154 100644 --- a/win/rfb_win32/WMCursor.h +++ b/win/rfb_win32/WMCursor.h @@ -38,7 +38,7 @@ namespace rfb { struct Info { HCURSOR cursor; - Point position; + core::Point position; bool visible; Info() : cursor(nullptr), visible(false) {} bool operator!=(const Info& info) { diff --git a/win/rfb_win32/WMHooks.cxx b/win/rfb_win32/WMHooks.cxx index e1840eef69..6b44416693 100644 --- a/win/rfb_win32/WMHooks.cxx +++ b/win/rfb_win32/WMHooks.cxx @@ -22,17 +22,18 @@ #include #endif -#include -#include +#include +#include +#include #include #include #include #include -#include #include +using namespace core; using namespace rfb; using namespace rfb::win32; @@ -114,7 +115,7 @@ static void LoadHooks() } -class WMHooksThread : public os::Thread { +class WMHooksThread : public Thread { public: WMHooksThread() : active(true), thread_id(-1) { } void stop(); @@ -128,7 +129,7 @@ class WMHooksThread : public os::Thread { static WMHooksThread* hook_mgr = nullptr; static std::list hooks; -static os::Mutex hook_mgr_lock; +static Mutex hook_mgr_lock; static bool StartHookThread() { @@ -166,7 +167,7 @@ static void StopHookThread() { static bool AddHook(WMHooks* hook) { vlog.debug("Adding hook"); - os::AutoMutex a(&hook_mgr_lock); + AutoMutex a(&hook_mgr_lock); if (!StartHookThread()) return false; hooks.push_back(hook); @@ -176,7 +177,7 @@ static bool AddHook(WMHooks* hook) { static bool RemHook(WMHooks* hook) { { vlog.debug("Removing hook"); - os::AutoMutex a(&hook_mgr_lock); + AutoMutex a(&hook_mgr_lock); hooks.remove(hook); } StopHookThread(); @@ -184,7 +185,7 @@ static bool RemHook(WMHooks* hook) { } static void NotifyHooksRegion(const Region& r) { - os::AutoMutex a(&hook_mgr_lock); + AutoMutex a(&hook_mgr_lock); std::list::iterator i; for (i=hooks.begin(); i!=hooks.end(); i++) (*i)->NotifyHooksRegion(r); @@ -236,8 +237,8 @@ WMHooksThread::worker() { hwnd = (HWND) msg.lParam; if (IsWindow(hwnd) && IsWindowVisible(hwnd) && !IsIconic(hwnd) && GetWindowRect(hwnd, &wrect) && !IsRectEmpty(&wrect)) { - updates[activeRgn].assign_union(Rect(wrect.left, wrect.top, - wrect.right, wrect.bottom)); + updates[activeRgn].assign_union({{wrect.left, wrect.top, + wrect.right, wrect.bottom}}); updateDelayTimer.start(updateDelayMs); } @@ -249,8 +250,8 @@ WMHooksThread::worker() { { POINT pt = {0,0}; if (ClientToScreen(hwnd, &pt)) { - updates[activeRgn].assign_union(Rect(wrect.left+pt.x, wrect.top+pt.y, - wrect.right+pt.x, wrect.bottom+pt.y)); + updates[activeRgn].assign_union({{wrect.left+pt.x, wrect.top+pt.y, + wrect.right+pt.x, wrect.bottom+pt.y}}); updateDelayTimer.start(updateDelayMs); } } @@ -260,14 +261,14 @@ WMHooksThread::worker() { if (IsWindow(hwnd) && IsWindowVisible(hwnd) && !IsIconic(hwnd) && GetWindowRect(hwnd, &wrect) && !IsRectEmpty(&wrect)) { - Region changed(Rect(wrect.left, wrect.top, wrect.right, wrect.bottom)); + Region changed({wrect.left, wrect.top, wrect.right, wrect.bottom}); RECT crect; POINT pt = {0,0}; if (GetClientRect(hwnd, &crect) && ClientToScreen(hwnd, &pt) && !IsRectEmpty(&crect)) { - changed.assign_subtract(Rect(crect.left+pt.x, crect.top+pt.y, - crect.right+pt.x, crect.bottom+pt.y)); + changed.assign_subtract({{crect.left+pt.x, crect.top+pt.y, + crect.right+pt.x, crect.bottom+pt.y}}); } if (!changed.is_empty()) { updates[activeRgn].assign_union(changed); @@ -275,8 +276,8 @@ WMHooksThread::worker() { } } } else if (msg.message == rectangleMsg) { - Rect r = Rect(LOWORD(msg.wParam), HIWORD(msg.wParam), - LOWORD(msg.lParam), HIWORD(msg.lParam)); + Rect r(LOWORD(msg.wParam), HIWORD(msg.wParam), + LOWORD(msg.lParam), HIWORD(msg.lParam)); if (!r.is_empty()) { updates[activeRgn].assign_union(r); updateDelayTimer.start(updateDelayMs); @@ -323,7 +324,7 @@ bool rfb::win32::WMHooks::setEvent(HANDLE ue) { bool rfb::win32::WMHooks::getUpdates(UpdateTracker* ut) { if (!updatesReady) return false; - os::AutoMutex a(&hook_mgr_lock); + AutoMutex a(&hook_mgr_lock); updates.copyTo(ut); updates.clear(); updatesReady = false; @@ -375,12 +376,12 @@ static bool blockRealInputs(bool block_) { return block_ == blocking; } -static os::Mutex blockMutex; +static Mutex blockMutex; static int blockCount = 0; bool rfb::win32::WMBlockInput::blockInputs(bool on) { if (active == on) return true; - os::AutoMutex a(&blockMutex); + AutoMutex a(&blockMutex); int newCount = on ? blockCount+1 : blockCount-1; if (!blockRealInputs(newCount > 0)) return false; diff --git a/win/rfb_win32/WMHooks.h b/win/rfb_win32/WMHooks.h index c1dbd5f37a..0a7292391e 100644 --- a/win/rfb_win32/WMHooks.h +++ b/win/rfb_win32/WMHooks.h @@ -22,8 +22,9 @@ #define __RFB_WIN32_WM_HOOKS_H__ #include + #include -#include + #include namespace rfb { @@ -53,7 +54,7 @@ namespace rfb { #endif // * INTERNAL NOTIFICATION FUNCTION * - void NotifyHooksRegion(const Region& r); + void NotifyHooksRegion(const core::Region& r); protected: HANDLE updateEvent; bool updatesReady; diff --git a/win/rfb_win32/WMNotifier.cxx b/win/rfb_win32/WMNotifier.cxx index 894add1c6b..3fda81e714 100644 --- a/win/rfb_win32/WMNotifier.cxx +++ b/win/rfb_win32/WMNotifier.cxx @@ -22,12 +22,13 @@ #include #endif +#include + #include #include #include -#include - +using namespace core; using namespace rfb; using namespace rfb::win32; diff --git a/win/rfb_win32/WMPoller.cxx b/win/rfb_win32/WMPoller.cxx index e2ff0ac645..e1efc4470e 100644 --- a/win/rfb_win32/WMPoller.cxx +++ b/win/rfb_win32/WMPoller.cxx @@ -22,12 +22,13 @@ #include #endif -#include +#include +#include +#include #include -#include -#include +using namespace core; using namespace rfb; using namespace rfb::win32; @@ -58,7 +59,7 @@ bool rfb::win32::WMPoller::checkPollWindow(HWND w) { char buffer[128]; if (!GetClassName(w, buffer, 128)) - throw rdr::win32_error("Unable to get window class:%u", GetLastError()); + throw core::win32_error("Unable to get window class:%u", GetLastError()); if ((strcmp(buffer, "tty") != 0) && (strcmp(buffer, "ConsoleWindowClass") != 0)) { return false; @@ -71,7 +72,7 @@ rfb::win32::WMPoller::pollWindow(HWND w, PollInfo* i) { RECT r; if (IsWindowVisible(w) && GetWindowRect(w, &r)) { if (IsRectEmpty(&r)) return; - Region wrgn(Rect(r.left, r.top, r.right, r.bottom)); + Region wrgn({r.left, r.top, r.right, r.bottom}); if (checkPollWindow(w)) { wrgn.assign_subtract(i->poll_exclude); i->poll_include.assign_union(wrgn); diff --git a/win/rfb_win32/WMPoller.h b/win/rfb_win32/WMPoller.h index 0783e4ff50..7fa896f08f 100644 --- a/win/rfb_win32/WMPoller.h +++ b/win/rfb_win32/WMPoller.h @@ -29,8 +29,10 @@ #define __RFB_WIN32_WM_POLLER_H__ #include + +#include + #include -#include namespace rfb { @@ -43,11 +45,11 @@ namespace rfb { bool processEvent(); bool setUpdateTracker(UpdateTracker* ut); - static BoolParameter poll_console_windows; + static core::BoolParameter poll_console_windows; protected: struct PollInfo { - Region poll_include; - Region poll_exclude; + core::Region poll_include; + core::Region poll_exclude; }; static bool checkPollWindow(HWND w); static void pollWindow(HWND w, PollInfo* info); diff --git a/win/rfb_win32/WMShatter.cxx b/win/rfb_win32/WMShatter.cxx index ede80e9121..0965da8604 100644 --- a/win/rfb_win32/WMShatter.cxx +++ b/win/rfb_win32/WMShatter.cxx @@ -22,10 +22,11 @@ #include #endif -#include +#include -#include +#include +using namespace core; using namespace rfb; using namespace rfb::win32; diff --git a/win/rfb_win32/WMWindowCopyRect.cxx b/win/rfb_win32/WMWindowCopyRect.cxx index ec6e1fdcb5..d64c0e31ed 100644 --- a/win/rfb_win32/WMWindowCopyRect.cxx +++ b/win/rfb_win32/WMWindowCopyRect.cxx @@ -22,10 +22,13 @@ #include #endif +#include + #include -#include + #include +using namespace core; using namespace rfb; using namespace rfb::win32; @@ -49,8 +52,8 @@ rfb::win32::WMCopyRect::processEvent() { // Window has moved - mark both the previous and new position as changed // (we can't use add_copied() here because we aren't that properly synced // with the actual state of the framebuffer) - ut->add_changed(Region(winrect)); - ut->add_changed(Region(fg_window_rect)); + ut->add_changed(winrect); + ut->add_changed(fg_window_rect); } } fg_window = window; diff --git a/win/rfb_win32/WMWindowCopyRect.h b/win/rfb_win32/WMWindowCopyRect.h index 5a0e876d15..d3ed788120 100644 --- a/win/rfb_win32/WMWindowCopyRect.h +++ b/win/rfb_win32/WMWindowCopyRect.h @@ -43,7 +43,7 @@ namespace rfb { protected: UpdateTracker* ut; void* fg_window; - Rect fg_window_rect; + core::Rect fg_window_rect; }; }; diff --git a/win/rfb_win32/Win32Util.cxx b/win/rfb_win32/Win32Util.cxx index b35bf6291f..f4220e32e7 100644 --- a/win/rfb_win32/Win32Util.cxx +++ b/win/rfb_win32/Win32Util.cxx @@ -22,15 +22,20 @@ #include #endif +#include +#include + #include #include #include #include + #include -#include -#include + #include +using namespace core; + namespace rfb { namespace win32 { @@ -46,19 +51,19 @@ FileVersionInfo::FileVersionInfo(const char* filename) { { Handle file(CreateFile(filename, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr)); if (file.h == INVALID_HANDLE_VALUE) - throw rdr::win32_error("Failed to open file", GetLastError()); + throw core::win32_error("Failed to open file", GetLastError()); } // Get version info size DWORD handle; int size = GetFileVersionInfoSize((char*)filename, &handle); if (!size) - throw rdr::win32_error("GetVersionInfoSize failed", GetLastError()); + throw core::win32_error("GetVersionInfoSize failed", GetLastError()); // Get version info buf = new char[size]; if (!GetFileVersionInfo((char*)filename, handle, size, buf)) - throw rdr::win32_error("GetVersionInfo failed", GetLastError()); + throw core::win32_error("GetVersionInfo failed", GetLastError()); } FileVersionInfo::~FileVersionInfo() { diff --git a/win/vncconfig/Authentication.h b/win/vncconfig/Authentication.h index 1123678fb2..2bf44deeff 100644 --- a/win/vncconfig/Authentication.h +++ b/win/vncconfig/Authentication.h @@ -33,7 +33,7 @@ #include #endif -static rfb::BoolParameter queryOnlyIfLoggedOn("QueryOnlyIfLoggedOn", +static core::BoolParameter queryOnlyIfLoggedOn("QueryOnlyIfLoggedOn", "Only prompt for a local user to accept incoming connections if there is a user logged on", false); namespace rfb { diff --git a/win/vncconfig/Connections.h b/win/vncconfig/Connections.h index 9ec78c072c..f7ecba3186 100644 --- a/win/vncconfig/Connections.h +++ b/win/vncconfig/Connections.h @@ -20,19 +20,22 @@ #include +#include +#include + #include #include #include -#include + #include -#include + #include -static rfb::IntParameter port_number("PortNumber", +static core::IntParameter port_number("PortNumber", "TCP/IP port on which the server will accept connections", 5900); -static rfb::StringParameter hosts("Hosts", +static core::StringParameter hosts("Hosts", "Filter describing which hosts are allowed access to this server", "+"); -static rfb::BoolParameter localHost("LocalHost", +static core::BoolParameter localHost("LocalHost", "Only accept connections from via the local loop-back network interface", false); namespace rfb { @@ -100,7 +103,7 @@ namespace rfb { SendMessage(listBox, LB_DELETESTRING, 0, 0); std::vector hostv; - hostv = split(hosts, ','); + hostv = core::split(hosts, ','); for (size_t i = 0; i < hostv.size(); i++) { if (!hostv[i].empty()) SendMessage(listBox, LB_ADDSTRING, 0, (LPARAM)hostv[i].c_str()); diff --git a/win/vncconfig/Legacy.cxx b/win/vncconfig/Legacy.cxx index 3280eaefef..bf073fd784 100644 --- a/win/vncconfig/Legacy.cxx +++ b/win/vncconfig/Legacy.cxx @@ -18,10 +18,12 @@ #include -#include -#include +#include +#include + #include +using namespace core; using namespace rfb; using namespace win32; @@ -42,7 +44,7 @@ void LegacyPage::LoadPrefs() std::string username; try { username = UserName(); - } catch (rdr::win32_error& e) { + } catch (core::win32_error& e) { if (e.err != ERROR_NOT_LOGGED_ON) throw; } @@ -70,7 +72,7 @@ void LegacyPage::LoadPrefs() try { // Split the AuthHosts string into patterns to match std::vector patterns; - patterns = rfb::split(authHosts.c_str(), ':'); + patterns = split(authHosts.c_str(), ':'); for (size_t i = 0; i < patterns.size(); i++) { if (!patterns[i].empty()) { int bits = 0; @@ -80,7 +82,7 @@ void LegacyPage::LoadPrefs() // Split the pattern into IP address parts and process std::vector parts; - parts = rfb::split(&patterns[i][1], '.'); + parts = split(&patterns[i][1], '.'); for (size_t j = 0; j < parts.size(); j++) { if (bits) strcat(pattern, "."); diff --git a/win/vncconfig/vncconfig.cxx b/win/vncconfig/vncconfig.cxx index fffdea186b..35eee38a73 100644 --- a/win/vncconfig/vncconfig.cxx +++ b/win/vncconfig/vncconfig.cxx @@ -22,12 +22,15 @@ #include #include "resource.h" -#include -#include + +#include +#include + #include #include #include +using namespace core; using namespace rfb; using namespace rfb::win32; @@ -125,7 +128,7 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE /*prev*/, char* /*cmdLine*/, int /* // Set the DACL, and don't allow the key to inherit its parent's DACL rootKey.setDACL(acl, false); - } catch (rdr::win32_error& e) { + } catch (core::win32_error& e) { // Something weird happens on NT 4.0 SP5 but I can't reproduce it on other // NT 4.0 service pack revisions. if (e.err == ERROR_INVALID_PARAMETER) { @@ -169,7 +172,7 @@ int WINAPI WinMain(HINSTANCE inst, HINSTANCE /*prev*/, char* /*cmdLine*/, int /* #else sheet.showPropSheet(nullptr, true, false); #endif - } catch (rdr::win32_error& e) { + } catch (core::win32_error& e) { switch (e.err) { case ERROR_ACCESS_DENIED: MsgBox(nullptr, "You do not have sufficient access rights to run the VNC Configuration applet", diff --git a/win/winvnc/ManagedListener.cxx b/win/winvnc/ManagedListener.cxx index 6690f3648e..7362b57cf1 100644 --- a/win/winvnc/ManagedListener.cxx +++ b/win/winvnc/ManagedListener.cxx @@ -20,10 +20,12 @@ #include #endif +#include + #include -#include using namespace winvnc; +using namespace core; using namespace rfb; using namespace win32; diff --git a/win/winvnc/QueryConnectDialog.cxx b/win/winvnc/QueryConnectDialog.cxx index e1df584dc4..fa1a9c6ee0 100644 --- a/win/winvnc/QueryConnectDialog.cxx +++ b/win/winvnc/QueryConnectDialog.cxx @@ -23,10 +23,13 @@ #include #include #include + +#include + #include #include -#include +using namespace core; using namespace rfb; using namespace win32; using namespace winvnc; @@ -74,7 +77,7 @@ void QueryConnectDialog::worker() { void QueryConnectDialog::initDialog() { if (!SetTimer(handle, 1, 1000, nullptr)) - throw rdr::win32_error("SetTimer", GetLastError()); + throw core::win32_error("SetTimer", GetLastError()); setItemString(IDC_QUERY_HOST, peerIp.c_str()); if (userName.empty()) userName = "(anonymous)"; diff --git a/win/winvnc/QueryConnectDialog.h b/win/winvnc/QueryConnectDialog.h index 332e7439a7..52a71ce23c 100644 --- a/win/winvnc/QueryConnectDialog.h +++ b/win/winvnc/QueryConnectDialog.h @@ -21,9 +21,9 @@ #ifndef __WINVNC_QUERY_CONNECT_DIALOG_H__ #define __WINVNC_QUERY_CONNECT_DIALOG_H__ -#include +#include -namespace os { class Thread; } +#include namespace network { class Socket; } @@ -31,7 +31,7 @@ namespace winvnc { class VNCServerWin32; - class QueryConnectDialog : public os::Thread, rfb::win32::Dialog { + class QueryConnectDialog : public core::Thread, rfb::win32::Dialog { public: QueryConnectDialog(network::Socket* sock, const char* userName, VNCServerWin32* s); virtual void startDialog(); diff --git a/win/winvnc/STrayIcon.cxx b/win/winvnc/STrayIcon.cxx index b64634b315..b8a5733091 100644 --- a/win/winvnc/STrayIcon.cxx +++ b/win/winvnc/STrayIcon.cxx @@ -26,11 +26,10 @@ #include #include -#include -#include - -#include -#include +#include +#include +#include +#include #include #include @@ -41,6 +40,7 @@ #include +using namespace core; using namespace rfb; using namespace win32; using namespace winvnc; @@ -217,7 +217,7 @@ class STrayIcon : public TrayIcon { case WM_SET_TOOLTIP: { - os::AutoMutex a(thread.lock); + AutoMutex a(thread.lock); if (!thread.toolTip.empty()) setToolTip(thread.toolTip.c_str()); } @@ -243,7 +243,7 @@ STrayIconThread::STrayIconThread(VNCServerWin32& sm, UINT inactiveIcon_, UINT ac inactiveIcon(inactiveIcon_), activeIcon(activeIcon_), dis_inactiveIcon(dis_inactiveIcon_), dis_activeIcon(dis_activeIcon_), menu(menu_), runTrayIcon(true) { - lock = new os::Mutex; + lock = new Mutex; start(); while (thread_id == (DWORD)-1) Sleep(0); @@ -277,7 +277,7 @@ void STrayIconThread::worker() { void STrayIconThread::setToolTip(const char* text) { if (!windowHandle) return; - os::AutoMutex a(lock); + AutoMutex a(lock); toolTip = text; PostMessage(windowHandle, WM_SET_TOOLTIP, 0, 0); } diff --git a/win/winvnc/STrayIcon.h b/win/winvnc/STrayIcon.h index 1aa7bfbc94..0df8ecabf2 100644 --- a/win/winvnc/STrayIcon.h +++ b/win/winvnc/STrayIcon.h @@ -20,16 +20,13 @@ #define WINVNC_TRAYICON_H #include -#include -namespace os { - class Mutex; - class Thread; -} +#include +#include namespace winvnc { - class STrayIconThread : os::Thread { + class STrayIconThread : core::Thread { public: STrayIconThread(VNCServerWin32& sm, UINT inactiveIcon, UINT activeIcon, UINT dis_inactiveIcon, UINT dis_activeIcon, UINT menu); @@ -37,14 +34,14 @@ namespace winvnc { void setToolTip(const char* text); - static rfb::BoolParameter disableOptions; - static rfb::BoolParameter disableClose; + static core::BoolParameter disableOptions; + static core::BoolParameter disableClose; friend class STrayIcon; protected: void worker() override; - os::Mutex* lock; + core::Mutex* lock; DWORD thread_id; HWND windowHandle; std::string toolTip; diff --git a/win/winvnc/VNCServerService.cxx b/win/winvnc/VNCServerService.cxx index 8ae4b747af..4da0a5dc08 100644 --- a/win/winvnc/VNCServerService.cxx +++ b/win/winvnc/VNCServerService.cxx @@ -23,15 +23,19 @@ #endif #include -#include -#include + +#include +#include + #include #include + #include #include #include using namespace winvnc; +using namespace core; using namespace rfb; using namespace win32; diff --git a/win/winvnc/VNCServerWin32.cxx b/win/winvnc/VNCServerWin32.cxx index ee6c60a701..6e80796b7d 100644 --- a/win/winvnc/VNCServerWin32.cxx +++ b/win/winvnc/VNCServerWin32.cxx @@ -27,15 +27,18 @@ #include #include -#include +#include +#include + +#include #include #include #include -#include -#include +#include +using namespace core; using namespace rfb; using namespace win32; using namespace winvnc; @@ -69,10 +72,10 @@ VNCServerWin32::VNCServerWin32() config(&sockMgr), rfbSock(&sockMgr), trayIcon(nullptr), queryConnectDialog(nullptr) { - commandLock = new os::Mutex; - commandSig = new os::Condition(commandLock); + commandLock = new Mutex; + commandSig = new Condition(commandLock); - runLock = new os::Mutex; + runLock = new Mutex; // Initialise the desktop desktop.setStatusLocation(&isDesktopStarted); @@ -158,7 +161,7 @@ void VNCServerWin32::regConfigChanged() { int VNCServerWin32::run() { { - os::AutoMutex a(runLock); + AutoMutex a(runLock); thread_id = GetCurrentThreadId(); runServer = true; } @@ -188,7 +191,7 @@ int VNCServerWin32::run() { while (runServer) { result = sockMgr.getMessage(&msg, nullptr, 0, 0); if (result < 0) - throw rdr::win32_error("getMessage", GetLastError()); + throw core::win32_error("getMessage", GetLastError()); if (!isServiceProcess() && (result == 0)) break; TranslateMessage(&msg); @@ -196,7 +199,7 @@ int VNCServerWin32::run() { } vlog.debug("Server exited cleanly"); - } catch (rdr::win32_error &s) { + } catch (core::win32_error &s) { vlog.error("%s", s.what()); result = s.err; } catch (std::exception &e) { @@ -204,7 +207,7 @@ int VNCServerWin32::run() { } { - os::AutoMutex a(runLock); + AutoMutex a(runLock); runServer = false; thread_id = (DWORD)-1; } @@ -213,7 +216,7 @@ int VNCServerWin32::run() { } void VNCServerWin32::stop() { - os::AutoMutex a(runLock); + AutoMutex a(runLock); runServer = false; if (thread_id != (DWORD)-1) PostThreadMessage(thread_id, WM_QUIT, 0, 0); @@ -270,7 +273,7 @@ void VNCServerWin32::queryConnectionComplete() { bool VNCServerWin32::queueCommand(Command cmd, const void* data, int len, bool wait) { - os::AutoMutex a(commandLock); + AutoMutex a(commandLock); while (command != NoCommand) commandSig->wait(); command = cmd; @@ -291,7 +294,7 @@ void VNCServerWin32::processEvent(HANDLE event_) { if (event_ == commandEvent.h) { // If there is no command queued then return immediately { - os::AutoMutex a(commandLock); + AutoMutex a(commandLock); if (command == NoCommand) return; } @@ -332,7 +335,7 @@ void VNCServerWin32::processEvent(HANDLE event_) { // Clear the command and signal completion { - os::AutoMutex a(commandLock); + AutoMutex a(commandLock); command = NoCommand; commandSig->signal(); } diff --git a/win/winvnc/VNCServerWin32.h b/win/winvnc/VNCServerWin32.h index 4fcc66d511..820ac9054a 100644 --- a/win/winvnc/VNCServerWin32.h +++ b/win/winvnc/VNCServerWin32.h @@ -28,7 +28,7 @@ #include #include -namespace os { +namespace core { class Mutex; class Condition; class Thread; @@ -106,15 +106,15 @@ namespace winvnc { Command command; const void* commandData; int commandDataLen; - os::Mutex* commandLock; - os::Condition* commandSig; + core::Mutex* commandLock; + core::Condition* commandSig; rfb::win32::Handle commandEvent; rfb::win32::Handle sessionEvent; // VNCServerWin32 Server-internal state rfb::win32::SDisplay desktop; rfb::VNCServerST vncServer; - os::Mutex* runLock; + core::Mutex* runLock; DWORD thread_id; bool runServer; bool isDesktopStarted; diff --git a/win/winvnc/winvnc.cxx b/win/winvnc/winvnc.cxx index 299e1fa1cb..89a9504827 100644 --- a/win/winvnc/winvnc.cxx +++ b/win/winvnc/winvnc.cxx @@ -28,15 +28,18 @@ #include #include -#include -#include -#include -#include +#include +#include +#include +#include + #include #include + #include using namespace winvnc; +using namespace core; using namespace rfb; using namespace win32; @@ -177,13 +180,13 @@ static void processParams(int argc, char** argv) { // Try to clean up earlier services we've had try { rfb::win32::unregisterService("WinVNC4"); - } catch (rdr::win32_error&) { + } catch (core::win32_error&) { // Do nothing as we might fail simply because there was no // service to remove } try { rfb::win32::unregisterService("TigerVNC Server"); - } catch (rdr::win32_error&) { + } catch (core::win32_error&) { } if (rfb::win32::registerService(VNCServerService::Name, diff --git a/win/wm_hooks/wm_hooks.cxx b/win/wm_hooks/wm_hooks.cxx index a48a173845..2f04b85173 100644 --- a/win/wm_hooks/wm_hooks.cxx +++ b/win/wm_hooks/wm_hooks.cxx @@ -25,7 +25,6 @@ #endif #include -#include #define SHARED __attribute__((section ("shared"), shared))