diff --git a/src/cmd/core/main.cpp b/src/cmd/core/main.cpp index 88e0ec72..8f2a22e5 100644 --- a/src/cmd/core/main.cpp +++ b/src/cmd/core/main.cpp @@ -17,17 +17,17 @@ */ #include "core/ClientApp.h" -#include "core/ServerApp.h" #include "arch/Arch.h" -#include "base/Log.h" #include "base/EventQueue.h" +#include "base/Log.h" +#include "core/ServerApp.h" #include int main(int argc, char** argv) { - // TODO: use existing arg parse code + // TODO(andrew): use existing arg parse code bool server, client; if (argc > 1) { server = std::string(argv[1]) == "--server"; @@ -49,12 +49,12 @@ main(int argc, char** argv) ServerApp app(&events); return app.run(argc, argv); } - else if (client) { + if (client) { ClientApp app(&events); return app.run(argc, argv); } else { - // TODO: use common error code + // TODO(andrew): use common error code std::cerr << "error: use --client or --server args" << std::endl; return 1; } diff --git a/src/cmd/synergyc/synergyc.cpp b/src/cmd/synergyc/synergyc.cpp index dd1f8e0d..f8542dae 100644 --- a/src/cmd/synergyc/synergyc.cpp +++ b/src/cmd/synergyc/synergyc.cpp @@ -18,8 +18,8 @@ #include "core/ClientApp.h" #include "arch/Arch.h" -#include "base/Log.h" #include "base/EventQueue.h" +#include "base/Log.h" #include diff --git a/src/cmd/synergys/synergys.cpp b/src/cmd/synergys/synergys.cpp index 553cef45..46039d1f 100644 --- a/src/cmd/synergys/synergys.cpp +++ b/src/cmd/synergys/synergys.cpp @@ -18,8 +18,8 @@ #include "core/ServerApp.h" #include "arch/Arch.h" -#include "base/Log.h" #include "base/EventQueue.h" +#include "base/Log.h" #include diff --git a/src/lib/arch/Arch.cpp b/src/lib/arch/Arch.cpp index 5eb0025d..8978df55 100644 --- a/src/lib/arch/Arch.cpp +++ b/src/lib/arch/Arch.cpp @@ -22,7 +22,7 @@ // Arch // -Arch* Arch::s_instance = NULL; +Arch* Arch::s_instance = nullptr; Arch::Arch() { diff --git a/src/lib/arch/ArchConsoleStd.cpp b/src/lib/arch/ArchConsoleStd.cpp index 44814ba8..c8b60866 100644 --- a/src/lib/arch/ArchConsoleStd.cpp +++ b/src/lib/arch/ArchConsoleStd.cpp @@ -24,10 +24,11 @@ void ArchConsoleStd::writeConsole(ELevel level, const char* str) { - if ((level >= kFATAL) && (level <= kWARNING)) + if ((level >= kFATAL) && (level <= kWARNING)) { std::cerr << str << std::endl; - else + } else { std::cout << str << std::endl; +} std::cout.flush(); } \ No newline at end of file diff --git a/src/lib/arch/ArchDaemonNone.cpp b/src/lib/arch/ArchDaemonNone.cpp index 71210632..47577f1c 100644 --- a/src/lib/arch/ArchDaemonNone.cpp +++ b/src/lib/arch/ArchDaemonNone.cpp @@ -33,17 +33,17 @@ ArchDaemonNone::~ArchDaemonNone() } void -ArchDaemonNone::installDaemon(const char*, - const char*, - const char*, - const char*, - const char*) +ArchDaemonNone::installDaemon(const char* /*name*/, + const char* /*description*/, + const char* /*pathname*/, + const char* /*commandLine*/, + const char* /*dependencies*/) { // do nothing } void -ArchDaemonNone::uninstallDaemon(const char*) +ArchDaemonNone::uninstallDaemon(const char* /*name*/) { // do nothing } @@ -57,13 +57,13 @@ ArchDaemonNone::daemonize(const char* name, DaemonFunc func) } bool -ArchDaemonNone::canInstallDaemon(const char*) +ArchDaemonNone::canInstallDaemon(const char* /*name*/) { return false; } bool -ArchDaemonNone::isDaemonInstalled(const char*) +ArchDaemonNone::isDaemonInstalled(const char* /*name*/) { return false; } diff --git a/src/lib/arch/IArchString.cpp b/src/lib/arch/IArchString.cpp index 57365363..5336802a 100644 --- a/src/lib/arch/IArchString.cpp +++ b/src/lib/arch/IArchString.cpp @@ -21,10 +21,10 @@ #include "common/common.h" #include -#include #include +#include -static ArchMutex s_mutex = NULL; +static ArchMutex s_mutex = nullptr; // // use C library non-reentrant multibyte conversion with mutex @@ -32,9 +32,9 @@ static ArchMutex s_mutex = NULL; IArchString::~IArchString() { - if (s_mutex != NULL) { + if (s_mutex != nullptr) { ARCH->closeMutex(s_mutex); - s_mutex = NULL; + s_mutex = nullptr; } } @@ -45,17 +45,17 @@ IArchString::convStringWCToMB(char* dst, ptrdiff_t len = 0; bool dummyErrors; - if (errors == NULL) { + if (errors == nullptr) { errors = &dummyErrors; } - if (s_mutex == NULL) { + if (s_mutex == nullptr) { s_mutex = ARCH->newMutex(); } ARCH->lockMutex(s_mutex); - if (dst == NULL) { + if (dst == nullptr) { char dummy[MB_LEN_MAX]; for (const wchar_t* scan = src; n > 0; ++scan, --n) { ptrdiff_t mblen = wctomb(dummy, *scan); @@ -102,17 +102,17 @@ IArchString::convStringMBToWC(wchar_t* dst, wchar_t dummy; bool dummyErrors; - if (errors == NULL) { + if (errors == nullptr) { errors = &dummyErrors; } - if (s_mutex == NULL) { + if (s_mutex == nullptr) { s_mutex = ARCH->newMutex(); } ARCH->lockMutex(s_mutex); - if (dst == NULL) { + if (dst == nullptr) { for (const char* scan = src; n > 0; ) { ptrdiff_t mblen = mbtowc(&dummy, scan, n); switch (mblen) { @@ -155,7 +155,7 @@ IArchString::convStringMBToWC(wchar_t* dst, case -2: // incomplete character. convert to unknown character. *errors = true; - *dst = (wchar_t)0xfffd; + *dst = static_cast(0xfffd); n = 0; break; @@ -163,13 +163,13 @@ IArchString::convStringMBToWC(wchar_t* dst, // invalid character. count one unknown character and // start at the next byte. *errors = true; - *dst = (wchar_t)0xfffd; + *dst = static_cast(0xfffd); scan += 1; n -= 1; break; case 0: - *dst = (wchar_t)0x0000; + *dst = static_cast(0x0000); scan += 1; n -= 1; break; diff --git a/src/lib/arch/unix/ArchConsoleUnix.cpp b/src/lib/arch/unix/ArchConsoleUnix.cpp index b5e20223..085ac244 100644 --- a/src/lib/arch/unix/ArchConsoleUnix.cpp +++ b/src/lib/arch/unix/ArchConsoleUnix.cpp @@ -18,6 +18,6 @@ #include "arch/unix/ArchConsoleUnix.h" -ArchConsoleUnix::ArchConsoleUnix() { } +ArchConsoleUnix::ArchConsoleUnix() = default; -ArchConsoleUnix::~ArchConsoleUnix() { } +ArchConsoleUnix::~ArchConsoleUnix() = default; diff --git a/src/lib/arch/unix/ArchDaemonUnix.cpp b/src/lib/arch/unix/ArchDaemonUnix.cpp index 9041e1a0..e00fe349 100644 --- a/src/lib/arch/unix/ArchDaemonUnix.cpp +++ b/src/lib/arch/unix/ArchDaemonUnix.cpp @@ -21,12 +21,12 @@ #include "arch/unix/XArchUnix.h" #include "base/Log.h" -#include -#include -#include -#include -#include #include +#include +#include +#include +#include +#include // // ArchDaemonUnix @@ -96,11 +96,12 @@ ArchDaemonUnix::daemonize(const char* name, DaemonFunc func) #ifndef __APPLE__ // NB: don't run chdir on apple; causes strange behaviour. // chdir to root so we don't keep mounted filesystems points busy - // TODO: this is a bit of a hack - can we find a better solution? + // TODO(andrew): this is a bit of a hack - can we find a better solution? int chdirErr = chdir("/"); - if (chdirErr) + if (chdirErr != 0) { // NB: file logging actually isn't working at this point! LOG((CLOG_ERR "chdir error: %i", chdirErr)); +} #endif // mask off permissions for any but owner @@ -113,8 +114,8 @@ ArchDaemonUnix::daemonize(const char* name, DaemonFunc func) // attach file descriptors 0, 1, 2 to /dev/null so inadvertent use // of standard I/O safely goes in the bit bucket. - open("/dev/null", O_RDONLY); - open("/dev/null", O_RDWR); + open("/dev/null", O_RDONLY | O_CLOEXEC); + open("/dev/null", O_RDWR | O_CLOEXEC); int dupErr = dup(1); diff --git a/src/lib/arch/unix/ArchFileUnix.cpp b/src/lib/arch/unix/ArchFileUnix.cpp index 4558720c..6115809f 100644 --- a/src/lib/arch/unix/ArchFileUnix.cpp +++ b/src/lib/arch/unix/ArchFileUnix.cpp @@ -18,11 +18,11 @@ #include "arch/unix/ArchFileUnix.h" -#include -#include -#include -#include #include +#include +#include +#include +#include // // ArchFileUnix @@ -41,26 +41,26 @@ ArchFileUnix::~ArchFileUnix() const char* ArchFileUnix::getBasename(const char* pathname) { - if (pathname == NULL) { - return NULL; + if (pathname == nullptr) { + return nullptr; } const char* basename = strrchr(pathname, '/'); - if (basename != NULL) { + if (basename != nullptr) { return basename + 1; } - else { + return pathname; - } + } std::string ArchFileUnix::getUserDirectory() { - char* buffer = NULL; + char* buffer = nullptr; std::string dir; #if HAVE_GETPWUID_R - struct passwd pwent; + struct passwd pwent{}; struct passwd* pwentp; #if defined(_SC_GETPW_R_SIZE_MAX) long size = sysconf(_SC_GETPW_R_SIZE_MAX); @@ -75,7 +75,7 @@ ArchFileUnix::getUserDirectory() #else struct passwd* pwentp = getpwuid(getuid()); #endif - if (pwentp != NULL && pwentp->pw_dir != NULL) { + if (pwentp != nullptr && pwentp->pw_dir != nullptr) { dir = pwentp->pw_dir; } delete[] buffer; @@ -143,7 +143,7 @@ ArchFileUnix::concatPath(const std::string& prefix, std::string path; path.reserve(prefix.size() + 1 + suffix.size()); path += prefix; - if (path.size() == 0 || path[path.size() - 1] != '/') { + if (path.empty() || path[path.size() - 1] != '/') { path += '/'; } path += suffix; diff --git a/src/lib/arch/unix/ArchInternetUnix.cpp b/src/lib/arch/unix/ArchInternetUnix.cpp index 06326ed6..93a5beba 100644 --- a/src/lib/arch/unix/ArchInternetUnix.cpp +++ b/src/lib/arch/unix/ArchInternetUnix.cpp @@ -18,11 +18,11 @@ #include "arch/unix/ArchInternetUnix.h" #include "arch/XArch.h" -#include "common/Version.h" #include "base/Log.h" +#include "common/Version.h" -#include #include +#include class CurlFacade { public: @@ -60,12 +60,12 @@ ArchInternetUnix::urlEncode(const String& url) static size_t curlWriteCallback(void *contents, size_t size, size_t nmemb, void *userp) { - ((std::string*)userp)->append((char*)contents, size * nmemb); + (static_cast(userp))->append(static_cast(contents), size * nmemb); return size * nmemb; } CurlFacade::CurlFacade() : - m_curl(NULL) + m_curl(nullptr) { CURLcode init = curl_global_init(CURL_GLOBAL_ALL); if (init != CURLE_OK) { @@ -73,14 +73,14 @@ CurlFacade::CurlFacade() : } m_curl = curl_easy_init(); - if (m_curl == NULL) { + if (m_curl == nullptr) { throw XArch("CURL easy init failed."); } } CurlFacade::~CurlFacade() { - if (m_curl != NULL) { + if (m_curl != nullptr) { curl_easy_cleanup(m_curl); } @@ -115,7 +115,7 @@ CurlFacade::urlEncode(const String& url) { char* resultCStr = curl_easy_escape(m_curl, url.c_str(), 0); - if (resultCStr == NULL) { + if (resultCStr == nullptr) { throw XArch("CURL escape failed."); } diff --git a/src/lib/arch/unix/ArchLogUnix.cpp b/src/lib/arch/unix/ArchLogUnix.cpp index 070e0272..2d5cc135 100644 --- a/src/lib/arch/unix/ArchLogUnix.cpp +++ b/src/lib/arch/unix/ArchLogUnix.cpp @@ -47,7 +47,7 @@ ArchLogUnix::closeLog() } void -ArchLogUnix::showLog(bool) +ArchLogUnix::showLog(bool /*showIfEmpty*/) { // do nothing } diff --git a/src/lib/arch/unix/ArchMultithreadPosix.cpp b/src/lib/arch/unix/ArchMultithreadPosix.cpp index 23a348aa..2f47c400 100644 --- a/src/lib/arch/unix/ArchMultithreadPosix.cpp +++ b/src/lib/arch/unix/ArchMultithreadPosix.cpp @@ -21,10 +21,10 @@ #include "arch/Arch.h" #include "arch/XArch.h" -#include +#include #if TIME_WITH_SYS_TIME # include -# include +# include #else # if HAVE_SYS_TIME_H # include @@ -67,28 +67,23 @@ public: ArchThreadImpl(); public: - int m_refCount; - IArchMultithread::ThreadID m_id; - pthread_t m_thread; + int m_refCount{1}; + IArchMultithread::ThreadID m_id{0}; + pthread_t m_thread{}; IArchMultithread::ThreadFunc m_func; void* m_userData; - bool m_cancel; - bool m_cancelling; - bool m_exited; + bool m_cancel{false}; + bool m_cancelling{false}; + bool m_exited{false}; void* m_result; void* m_networkData; }; ArchThreadImpl::ArchThreadImpl() : - m_refCount(1), - m_id(0), - m_func(NULL), - m_userData(NULL), - m_cancel(false), - m_cancelling(false), - m_exited(false), - m_result(NULL), - m_networkData(NULL) + m_func(nullptr), + m_userData(nullptr), + m_result(nullptr), + m_networkData(nullptr) { // do nothing } @@ -98,7 +93,7 @@ ArchThreadImpl::ArchThreadImpl() : // ArchMultithreadPosix // -ArchMultithreadPosix* ArchMultithreadPosix::s_instance = NULL; +ArchMultithreadPosix* ArchMultithreadPosix::s_instance = nullptr; ArchMultithreadPosix::ArchMultithreadPosix() : m_newThreadCalled(false), @@ -110,8 +105,8 @@ ArchMultithreadPosix::ArchMultithreadPosix() : // no signal handlers for (size_t i = 0; i < kNUM_SIGNALS; ++i) { - m_signalFunc[i] = NULL; - m_signalUserData[i] = NULL; + m_signalFunc[i] = nullptr; + m_signalUserData[i] = nullptr; } // create mutex for thread list @@ -128,7 +123,7 @@ ArchMultithreadPosix::ArchMultithreadPosix() : // to wake up immediately if it's blocked in a system call. we // won't need this until another thread is created but it's fine // to install it now. - struct sigaction act; + struct sigaction act{}; sigemptyset(&act.sa_mask); # if defined(SA_INTERRUPT) act.sa_flags = SA_INTERRUPT; @@ -136,17 +131,17 @@ ArchMultithreadPosix::ArchMultithreadPosix() : act.sa_flags = 0; # endif act.sa_handler = &threadCancel; - sigaction(SIGWAKEUP, &act, NULL); + sigaction(SIGWAKEUP, &act, nullptr); // set desired signal dispositions. let SIGWAKEUP through but // ignore SIGPIPE (we'll handle EPIPE). - sigset_t sigset; + sigset_t sigset{}; sigemptyset(&sigset); sigaddset(&sigset, SIGWAKEUP); - pthread_sigmask(SIG_UNBLOCK, &sigset, NULL); + pthread_sigmask(SIG_UNBLOCK, &sigset, nullptr); sigemptyset(&sigset); sigaddset(&sigset, SIGPIPE); - pthread_sigmask(SIG_BLOCK, &sigset, NULL); + pthread_sigmask(SIG_BLOCK, &sigset, nullptr); } ArchMultithreadPosix::~ArchMultithreadPosix() @@ -154,7 +149,7 @@ ArchMultithreadPosix::~ArchMultithreadPosix() assert(s_instance != NULL); closeMutex(m_threadMutex); - s_instance = NULL; + s_instance = nullptr; } void @@ -184,8 +179,8 @@ ArchMultithreadPosix::getInstance() ArchCond ArchMultithreadPosix::newCondVar() { - ArchCondImpl* cond = new ArchCondImpl; - int status = pthread_cond_init(&cond->m_cond, NULL); + auto* cond = new ArchCondImpl; + int status = pthread_cond_init(&cond->m_cond, nullptr); (void)status; assert(status == 0); return cond; @@ -237,13 +232,13 @@ ArchMultithreadPosix::waitCondVar(ArchCond cond, testCancelThread(); // get final time - struct timeval now; - gettimeofday(&now, NULL); - struct timespec finalTime; + struct timeval now{}; + gettimeofday(&now, nullptr); + struct timespec finalTime{}; finalTime.tv_sec = now.tv_sec; finalTime.tv_nsec = now.tv_usec * 1000; - long timeout_sec = (long)timeout; - long timeout_nsec = (long)(1.0e+9 * (timeout - timeout_sec)); + auto timeout_sec = static_cast(timeout); + auto timeout_nsec = static_cast(1.0e+9 * (timeout - timeout_sec)); finalTime.tv_sec += timeout_sec; finalTime.tv_nsec += timeout_nsec; if (finalTime.tv_nsec >= 1000000000) { @@ -275,10 +270,10 @@ ArchMultithreadPosix::waitCondVar(ArchCond cond, ArchMutex ArchMultithreadPosix::newMutex() { - pthread_mutexattr_t attr; + pthread_mutexattr_t attr{}; int status = pthread_mutexattr_init(&attr); assert(status == 0); - ArchMutexImpl* mutex = new ArchMutexImpl; + auto* mutex = new ArchMutexImpl; status = pthread_mutex_init(&mutex->m_mutex, &attr); assert(status == 0); return mutex; @@ -359,13 +354,13 @@ ArchMultithreadPosix::newThread(ThreadFunc func, void* data) lockMutex(m_threadMutex); // create thread impl for new thread - ArchThreadImpl* thread = new ArchThreadImpl; + auto* thread = new ArchThreadImpl; thread->m_func = func; thread->m_userData = data; // create the thread. pthread_create() on RedHat 7.2 smp fails // if passed a NULL attr so use a default attr. - pthread_attr_t attr; + pthread_attr_t attr{}; int status = pthread_attr_init(&attr); if (status == 0) { status = pthread_create(&thread->m_thread, &attr, @@ -377,7 +372,7 @@ ArchMultithreadPosix::newThread(ThreadFunc func, void* data) if (status != 0) { // failed to start thread so clean up delete thread; - thread = NULL; + thread = nullptr; } else { // add thread to list @@ -411,7 +406,7 @@ ArchMultithreadPosix::closeThread(ArchThread thread) // decrement ref count and clean up thread if no more references if (--thread->m_refCount == 0) { // detach from thread (unless it's the main thread) - if (thread->m_func != NULL) { + if (thread->m_func != nullptr) { pthread_detach(thread->m_thread); } @@ -454,7 +449,7 @@ ArchMultithreadPosix::cancelThread(ArchThread thread) } void -ArchMultithreadPosix::setPriorityOfThread(ArchThread thread, int /*n*/) +ArchMultithreadPosix::setPriorityOfThread(ArchThread /*thread*/, int /*n*/) { assert(thread != NULL); @@ -573,7 +568,7 @@ void ArchMultithreadPosix::raiseSignal(ESignal signal) { lockMutex(m_threadMutex); - if (m_signalFunc[signal] != NULL) { + if (m_signalFunc[signal] != nullptr) { m_signalFunc[signal](signal, m_signalUserData[signal]); pthread_kill(m_mainThread->m_thread, SIGWAKEUP); } @@ -588,7 +583,7 @@ ArchMultithreadPosix::startSignalHandler() { // set signal mask. the main thread blocks these signals and // the signal handler thread will listen for them. - sigset_t sigset, oldsigset; + sigset_t sigset{}, oldsigset{}; setSignalSet(&sigset); pthread_sigmask(SIG_BLOCK, &sigset, &oldsigset); @@ -596,18 +591,18 @@ ArchMultithreadPosix::startSignalHandler() // instead arrange to catch and handle these signals but // we'd be unable to cancel the main thread since no pthread // calls are allowed in a signal handler. - pthread_attr_t attr; + pthread_attr_t attr{}; int status = pthread_attr_init(&attr); if (status == 0) { status = pthread_create(&m_signalThread, &attr, &ArchMultithreadPosix::threadSignalHandler, - NULL); + nullptr); pthread_attr_destroy(&attr); } if (status != 0) { // can't create thread to wait for signal so don't block // the signals. - pthread_sigmask(SIG_UNBLOCK, &oldsigset, NULL); + pthread_sigmask(SIG_UNBLOCK, &oldsigset, nullptr); } } @@ -615,7 +610,7 @@ ArchThreadImpl* ArchMultithreadPosix::find(pthread_t thread) { ArchThreadImpl* impl = findNoRef(thread); - if (impl != NULL) { + if (impl != nullptr) { refThread(impl); } return impl; @@ -631,7 +626,7 @@ ArchMultithreadPosix::findNoRef(pthread_t thread) return *index; } } - return NULL; + return nullptr; } void @@ -655,7 +650,7 @@ ArchMultithreadPosix::insert(ArchThreadImpl* thread) void ArchMultithreadPosix::erase(ArchThreadImpl* thread) { - for (ThreadList::iterator index = m_threadList.begin(); + for (auto index = m_threadList.begin(); index != m_threadList.end(); ++index) { if (*index == thread) { m_threadList.erase(index); @@ -697,17 +692,17 @@ void* ArchMultithreadPosix::threadFunc(void* vrep) { // get the thread - ArchThreadImpl* thread = static_cast(vrep); + auto* thread = static_cast(vrep); // setup pthreads - pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); - pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL); + pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, nullptr); + pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, nullptr); // run thread s_instance->doThreadFunc(thread); // terminate the thread - return NULL; + return nullptr; } void @@ -720,7 +715,7 @@ ArchMultithreadPosix::doThreadFunc(ArchThread thread) lockMutex(m_threadMutex); unlockMutex(m_threadMutex); - void* result = NULL; + void* result = nullptr; try { // go result = (*thread->m_func)(thread->m_userData); @@ -749,19 +744,19 @@ ArchMultithreadPosix::doThreadFunc(ArchThread thread) } void -ArchMultithreadPosix::threadCancel(int) +ArchMultithreadPosix::threadCancel(int /*unused*/) { // do nothing } void* -ArchMultithreadPosix::threadSignalHandler(void*) +ArchMultithreadPosix::threadSignalHandler(void* /*unused*/) { // detach pthread_detach(pthread_self()); // add signal to mask - sigset_t sigset; + sigset_t sigset{}; setSignalSet(&sigset); // also wait on SIGABRT. on linux (others?) this thread (process) @@ -808,5 +803,5 @@ ArchMultithreadPosix::threadSignalHandler(void*) } } - return NULL; + return nullptr; } diff --git a/src/lib/arch/unix/ArchMultithreadPosix.h b/src/lib/arch/unix/ArchMultithreadPosix.h index 983b7ff1..744c1f5c 100644 --- a/src/lib/arch/unix/ArchMultithreadPosix.h +++ b/src/lib/arch/unix/ArchMultithreadPosix.h @@ -89,8 +89,8 @@ private: void insert(ArchThreadImpl* thread); void erase(ArchThreadImpl* thread); - void refThread(ArchThreadImpl* rep); - void testCancelThreadImpl(ArchThreadImpl* rep); + void refThread(ArchThreadImpl* thread); + void testCancelThreadImpl(ArchThreadImpl* thread); void doThreadFunc(ArchThread thread); static void* threadFunc(void* vrep); @@ -109,7 +109,7 @@ private: ThreadList m_threadList; ThreadID m_nextID; - pthread_t m_signalThread; - SignalFunc m_signalFunc[kNUM_SIGNALS]; - void* m_signalUserData[kNUM_SIGNALS]; + pthread_t m_signalThread{}; + SignalFunc m_signalFunc[kNUM_SIGNALS]{}; + void* m_signalUserData[kNUM_SIGNALS]{}; }; diff --git a/src/lib/arch/unix/ArchNetworkBSD.cpp b/src/lib/arch/unix/ArchNetworkBSD.cpp index 5c80a7ad..a00df41f 100644 --- a/src/lib/arch/unix/ArchNetworkBSD.cpp +++ b/src/lib/arch/unix/ArchNetworkBSD.cpp @@ -18,22 +18,22 @@ #include "arch/unix/ArchNetworkBSD.h" +#include "arch/Arch.h" #include "arch/unix/ArchMultithreadPosix.h" #include "arch/unix/XArchUnix.h" -#include "arch/Arch.h" #if HAVE_UNISTD_H # include #endif -#include #include +#include #if !defined(TCP_NODELAY) # include #endif #include -#include #include -#include +#include +#include #if HAVE_POLL # include @@ -87,8 +87,7 @@ inet_aton(const char* cp, struct in_addr* inp) // ArchNetworkBSD::ArchNetworkBSD() -{ -} += default; ArchNetworkBSD::~ArchNetworkBSD() { @@ -119,7 +118,7 @@ ArchNetworkBSD::newSocket(EAddressFamily family, ESocketType type) } // allocate socket object - ArchSocketImpl* newSocket = new ArchSocketImpl; + auto* newSocket = new ArchSocketImpl; newSocket->m_fd = fd; newSocket->m_refCount = 1; return newSocket; @@ -214,25 +213,25 @@ ArchNetworkBSD::acceptSocket(ArchSocket s, ArchNetAddress* addr) // if user passed NULL in addr then use scratch space ArchNetAddress dummy; - if (addr == NULL) { + if (addr == nullptr) { addr = &dummy; } // create new socket and address - ArchSocketImpl* newSocket = new ArchSocketImpl; + auto* newSocket = new ArchSocketImpl; *addr = new ArchNetAddressImpl; // accept on socket - ACCEPT_TYPE_ARG3 len = (ACCEPT_TYPE_ARG3)((*addr)->m_len); + auto len = ((*addr)->m_len); int fd = accept(s->m_fd, &(*addr)->m_addr, &len); - (*addr)->m_len = (socklen_t)len; + (*addr)->m_len = len; if (fd == -1) { int err = errno; delete newSocket; delete *addr; - *addr = NULL; + *addr = nullptr; if (err == EAGAIN) { - return NULL; + return nullptr; } throwError(err); } @@ -244,7 +243,7 @@ ArchNetworkBSD::acceptSocket(ArchSocket s, ArchNetAddress* addr) close(fd); delete newSocket; delete *addr; - *addr = NULL; + *addr = nullptr; throw; } @@ -294,11 +293,11 @@ ArchNetworkBSD::pollSocket(PollEntry pe[], int num, double timeout) } // allocate space for translated query - struct pollfd* pfd = new struct pollfd[1 + num]; + auto* pfd = new struct pollfd[1 + num]; // translate query for (int i = 0; i < num; ++i) { - pfd[i].fd = (pe[i].m_socket == NULL) ? -1 : pe[i].m_socket->m_fd; + pfd[i].fd = (pe[i].m_socket == nullptr) ? -1 : pe[i].m_socket->m_fd; pfd[i].events = 0; if ((pe[i].m_events & kPOLLIN) != 0) { pfd[i].events |= POLLIN; @@ -311,7 +310,7 @@ ArchNetworkBSD::pollSocket(PollEntry pe[], int num, double timeout) // add the unblock pipe const int* unblockPipe = getUnblockPipe(); - if (unblockPipe != NULL) { + if (unblockPipe != nullptr) { pfd[n].fd = unblockPipe[0]; pfd[n].events = POLLIN; ++n; @@ -324,7 +323,7 @@ ArchNetworkBSD::pollSocket(PollEntry pe[], int num, double timeout) n = poll(pfd, n, t); // reset the unblock pipe - if (n > 0 && unblockPipe != NULL && (pfd[num].revents & POLLIN) != 0) { + if (n > 0 && unblockPipe != nullptr && (pfd[num].revents & POLLIN) != 0) { // the unblock event was signalled. flush the pipe. char dummy[100]; int ignore; @@ -500,7 +499,7 @@ void ArchNetworkBSD::unblockPollSocket(ArchThread thread) { const int* unblockPipe = getUnblockPipeForThread(thread); - if (unblockPipe != NULL) { + if (unblockPipe != nullptr) { char dummy = 0; int ignore; @@ -545,9 +544,9 @@ ArchNetworkBSD::throwErrorOnSocket(ArchSocket s) // get the error from the socket layer int err = 0; - socklen_t size = (socklen_t)sizeof(err); + auto size = static_cast(sizeof(err)); if (getsockopt(s->m_fd, SOL_SOCKET, SO_ERROR, - (optval_t*)&err, &size) == -1) { + reinterpret_cast(&err), &size) == -1) { err = errno; } @@ -584,16 +583,16 @@ ArchNetworkBSD::setNoDelayOnSocket(ArchSocket s, bool noDelay) // get old state int oflag; - socklen_t size = (socklen_t)sizeof(oflag); + auto size = static_cast(sizeof(oflag)); if (getsockopt(s->m_fd, IPPROTO_TCP, TCP_NODELAY, - (optval_t*)&oflag, &size) == -1) { + reinterpret_cast(&oflag), &size) == -1) { throwError(errno); } int flag = noDelay ? 1 : 0; - size = (socklen_t)sizeof(flag); + size = static_cast(sizeof(flag)); if (setsockopt(s->m_fd, IPPROTO_TCP, TCP_NODELAY, - (optval_t*)&flag, size) == -1) { + reinterpret_cast(&flag), size) == -1) { throwError(errno); } @@ -607,16 +606,16 @@ ArchNetworkBSD::setReuseAddrOnSocket(ArchSocket s, bool reuse) // get old state int oflag; - socklen_t size = (socklen_t)sizeof(oflag); + auto size = static_cast(sizeof(oflag)); if (getsockopt(s->m_fd, SOL_SOCKET, SO_REUSEADDR, - (optval_t*)&oflag, &size) == -1) { + reinterpret_cast(&oflag), &size) == -1) { throwError(errno); } int flag = reuse ? 1 : 0; - size = (socklen_t)sizeof(flag); + size = static_cast(sizeof(flag)); if (setsockopt(s->m_fd, SOL_SOCKET, SO_REUSEADDR, - (optval_t*)&flag, size) == -1) { + reinterpret_cast(&flag), size) == -1) { throwError(errno); } @@ -640,17 +639,17 @@ ArchNetAddress ArchNetworkBSD::newAnyAddr(EAddressFamily family) { // allocate address - ArchNetAddressImpl* addr = new ArchNetAddressImpl; + auto* addr = new ArchNetAddressImpl; // fill it in switch (family) { case kINET: { - struct sockaddr_in* ipAddr = + auto* ipAddr = reinterpret_cast(&addr->m_addr); ipAddr->sin_family = AF_INET; ipAddr->sin_port = 0; ipAddr->sin_addr.s_addr = INADDR_ANY; - addr->m_len = (socklen_t)sizeof(struct sockaddr_in); + addr->m_len = static_cast(sizeof(struct sockaddr_in)); break; } @@ -675,14 +674,14 @@ ArchNetAddress ArchNetworkBSD::nameToAddr(const std::string& name) { // allocate address - ArchNetAddressImpl* addr = new ArchNetAddressImpl; + auto* addr = new ArchNetAddressImpl; // try to convert assuming an IPv4 dot notation address - struct sockaddr_in inaddr; + struct sockaddr_in inaddr{}; memset(&inaddr, 0, sizeof(inaddr)); if (inet_aton(name.c_str(), &inaddr.sin_addr) != 0) { // it's a dot notation address - addr->m_len = (socklen_t)sizeof(struct sockaddr_in); + addr->m_len = static_cast(sizeof(struct sockaddr_in)); inaddr.sin_family = AF_INET; inaddr.sin_port = 0; memcpy(&addr->m_addr, &inaddr, addr->m_len); @@ -692,7 +691,7 @@ ArchNetworkBSD::nameToAddr(const std::string& name) // mutexed address lookup (ugh) ARCH->lockMutex(m_mutex); struct hostent* info = gethostbyname(name.c_str()); - if (info == NULL) { + if (info == nullptr) { ARCH->unlockMutex(m_mutex); delete addr; throwNameError(h_errno); @@ -700,7 +699,7 @@ ArchNetworkBSD::nameToAddr(const std::string& name) // copy over address (only IPv4 currently supported) if (info->h_addrtype == AF_INET) { - addr->m_len = (socklen_t)sizeof(struct sockaddr_in); + addr->m_len = static_cast(sizeof(struct sockaddr_in)); inaddr.sin_family = info->h_addrtype; inaddr.sin_port = 0; memcpy(&inaddr.sin_addr, info->h_addr_list[0], @@ -739,7 +738,7 @@ ArchNetworkBSD::addrToName(ArchNetAddress addr) ARCH->lockMutex(m_mutex); struct hostent* info = gethostbyaddr(&addr->m_addr, addr->m_len, addr->m_addr.sa_family); - if (info == NULL) { + if (info == nullptr) { ARCH->unlockMutex(m_mutex); throwNameError(h_errno); } @@ -760,7 +759,7 @@ ArchNetworkBSD::addrToString(ArchNetAddress addr) switch (getAddrFamily(addr)) { case kINET: { - struct sockaddr_in* ipAddr = + auto* ipAddr = reinterpret_cast(&addr->m_addr); ARCH->lockMutex(m_mutex); std::string s = inet_ntoa(ipAddr->sin_addr); @@ -795,7 +794,7 @@ ArchNetworkBSD::setAddrPort(ArchNetAddress addr, int port) switch (getAddrFamily(addr)) { case kINET: { - struct sockaddr_in* ipAddr = + auto* ipAddr = reinterpret_cast(&addr->m_addr); ipAddr->sin_port = htons(port); break; @@ -814,7 +813,7 @@ ArchNetworkBSD::getAddrPort(ArchNetAddress addr) switch (getAddrFamily(addr)) { case kINET: { - struct sockaddr_in* ipAddr = + auto* ipAddr = reinterpret_cast(&addr->m_addr); return ntohs(ipAddr->sin_port); } @@ -832,10 +831,10 @@ ArchNetworkBSD::isAnyAddr(ArchNetAddress addr) switch (getAddrFamily(addr)) { case kINET: { - struct sockaddr_in* ipAddr = + auto* ipAddr = reinterpret_cast(&addr->m_addr); return (ipAddr->sin_addr.s_addr == INADDR_ANY && - addr->m_len == (socklen_t)sizeof(struct sockaddr_in)); + addr->m_len == static_cast(sizeof(struct sockaddr_in))); } default: @@ -865,8 +864,8 @@ const int* ArchNetworkBSD::getUnblockPipeForThread(ArchThread thread) { ArchMultithreadPosix* mt = ArchMultithreadPosix::getInstance(); - int* unblockPipe = (int*)mt->getNetworkDataForThread(thread); - if (unblockPipe == NULL) { + auto* unblockPipe = static_cast(mt->getNetworkDataForThread(thread)); + if (unblockPipe == nullptr) { unblockPipe = new int[2]; if (pipe(unblockPipe) != -1) { try { @@ -875,12 +874,12 @@ ArchNetworkBSD::getUnblockPipeForThread(ArchThread thread) } catch (...) { delete[] unblockPipe; - unblockPipe = NULL; + unblockPipe = nullptr; } } else { delete[] unblockPipe; - unblockPipe = NULL; + unblockPipe = nullptr; } } return unblockPipe; diff --git a/src/lib/arch/unix/ArchNetworkBSD.h b/src/lib/arch/unix/ArchNetworkBSD.h index 32a22cfd..7426baf0 100644 --- a/src/lib/arch/unix/ArchNetworkBSD.h +++ b/src/lib/arch/unix/ArchNetworkBSD.h @@ -70,7 +70,7 @@ public: virtual void bindSocket(ArchSocket s, ArchNetAddress addr); virtual void listenOnSocket(ArchSocket s); virtual ArchSocket acceptSocket(ArchSocket s, ArchNetAddress* addr); - virtual bool connectSocket(ArchSocket s, ArchNetAddress name); + virtual bool connectSocket(ArchSocket s, ArchNetAddress addr); virtual int pollSocket(PollEntry[], int num, double timeout); virtual void unblockPollSocket(ArchThread thread); virtual size_t readSocket(ArchSocket s, void* buf, size_t len); @@ -100,5 +100,5 @@ private: void throwNameError(int); private: - ArchMutex m_mutex; + ArchMutex m_mutex{}; }; diff --git a/src/lib/arch/unix/ArchSleepUnix.cpp b/src/lib/arch/unix/ArchSleepUnix.cpp index ad093c30..27f24243 100644 --- a/src/lib/arch/unix/ArchSleepUnix.cpp +++ b/src/lib/arch/unix/ArchSleepUnix.cpp @@ -22,7 +22,7 @@ #if TIME_WITH_SYS_TIME # include -# include +# include #else # if HAVE_SYS_TIME_H # include @@ -66,13 +66,14 @@ ArchSleepUnix::sleep(double timeout) #if HAVE_NANOSLEEP // prep timeout - struct timespec t; - t.tv_sec = (long)timeout; - t.tv_nsec = (long)(1.0e+9 * (timeout - (double)t.tv_sec)); + struct timespec t{}; + t.tv_sec = static_cast(timeout); + t.tv_nsec = static_cast(1.0e+9 * (timeout - static_cast(t.tv_sec))); // wait - while (nanosleep(&t, &t) < 0) + while (nanosleep(&t, &t) < 0) { ARCH->testCancelThread(); +} #else /* emulate nanosleep() with select() */ double startTime = ARCH->time(); diff --git a/src/lib/arch/unix/ArchStringUnix.cpp b/src/lib/arch/unix/ArchStringUnix.cpp index fbb3e098..1a96f1b5 100644 --- a/src/lib/arch/unix/ArchStringUnix.cpp +++ b/src/lib/arch/unix/ArchStringUnix.cpp @@ -18,7 +18,7 @@ #include "arch/unix/ArchStringUnix.h" -#include +#include // // ArchStringUnix @@ -28,12 +28,10 @@ #include "arch/vsnprintf.h" ArchStringUnix::ArchStringUnix() -{ -} += default; ArchStringUnix::~ArchStringUnix() -{ -} += default; IArchString::EWideCharEncoding ArchStringUnix::getWideCharEncoding() diff --git a/src/lib/arch/unix/ArchSystemUnix.cpp b/src/lib/arch/unix/ArchSystemUnix.cpp index e877f23e..11a0ca47 100644 --- a/src/lib/arch/unix/ArchSystemUnix.cpp +++ b/src/lib/arch/unix/ArchSystemUnix.cpp @@ -38,7 +38,7 @@ std::string ArchSystemUnix::getOSName() const { #if defined(HAVE_SYS_UTSNAME_H) - struct utsname info; + struct utsname info{}; if (uname(&info) == 0) { std::string msg; msg += info.sysname; @@ -54,7 +54,7 @@ std::string ArchSystemUnix::getPlatformName() const { #if defined(HAVE_SYS_UTSNAME_H) - struct utsname info; + struct utsname info{}; if (uname(&info) == 0) { return std::string(info.machine); } @@ -63,18 +63,18 @@ ArchSystemUnix::getPlatformName() const } std::string -ArchSystemUnix::setting(const std::string&) const +ArchSystemUnix::setting(const std::string& /*valueName*/) const { return ""; } void -ArchSystemUnix::setting(const std::string&, const std::string&) const +ArchSystemUnix::setting(const std::string& /*valueName*/, const std::string& /*valueString*/) const { } std::string -ArchSystemUnix::getLibsUsed(void) const +ArchSystemUnix::getLibsUsed() const { return "not implemented.\nuse lsof on shell"; } diff --git a/src/lib/arch/unix/ArchTimeUnix.cpp b/src/lib/arch/unix/ArchTimeUnix.cpp index cc5d7a38..ce236f13 100644 --- a/src/lib/arch/unix/ArchTimeUnix.cpp +++ b/src/lib/arch/unix/ArchTimeUnix.cpp @@ -20,7 +20,7 @@ #if TIME_WITH_SYS_TIME # include -# include +# include #else # if HAVE_SYS_TIME_H # include @@ -46,7 +46,7 @@ ArchTimeUnix::~ArchTimeUnix() double ArchTimeUnix::time() { - struct timeval t; - gettimeofday(&t, NULL); - return (double)t.tv_sec + 1.0e-6 * (double)t.tv_usec; + struct timeval t{}; + gettimeofday(&t, nullptr); + return static_cast(t.tv_sec) + 1.0e-6 * static_cast(t.tv_usec); } diff --git a/src/lib/base/Event.cpp b/src/lib/base/Event.cpp index 9e12664c..e439b65a 100644 --- a/src/lib/base/Event.cpp +++ b/src/lib/base/Event.cpp @@ -25,8 +25,8 @@ Event::Event() : m_type(kUnknown), - m_target(NULL), - m_data(NULL), + m_target(nullptr), + m_data(nullptr), m_flags(0), m_dataObject(nullptr) { diff --git a/src/lib/base/EventQueue.cpp b/src/lib/base/EventQueue.cpp index dfdebe20..14443769 100644 --- a/src/lib/base/EventQueue.cpp +++ b/src/lib/base/EventQueue.cpp @@ -18,15 +18,15 @@ #include "base/EventQueue.h" -#include "mt/Mutex.h" -#include "mt/Lock.h" #include "arch/Arch.h" +#include "base/EventTypes.h" +#include "base/IEventJob.h" +#include "base/Log.h" #include "base/SimpleEventQueueBuffer.h" #include "base/Stopwatch.h" -#include "base/IEventJob.h" -#include "base/EventTypes.h" -#include "base/Log.h" #include "base/XBase.h" +#include "mt/Lock.h" +#include "mt/Mutex.h" EVENT_TYPE_ACCESSOR(Client) EVENT_TYPE_ACCESSOR(IStream) @@ -52,9 +52,9 @@ EVENT_TYPE_ACCESSOR(File) // interrupt handler. this just adds a quit event to the queue. static void -interrupt(Arch::ESignal, void* data) +interrupt(Arch::ESignal /*unused*/, void* data) { - EventQueue* events = static_cast(data); + auto* events = static_cast(data); events->addEvent(Event(Event::kQuit)); } @@ -66,26 +66,26 @@ interrupt(Arch::ESignal, void* data) EventQueue::EventQueue() : m_systemTarget(0), m_nextType(Event::kLast), - m_typesForClient(NULL), - m_typesForIStream(NULL), - m_typesForIpcClient(NULL), - m_typesForIpcClientProxy(NULL), - m_typesForIpcServer(NULL), - m_typesForIpcServerProxy(NULL), - m_typesForIDataSocket(NULL), - m_typesForIListenSocket(NULL), - m_typesForISocket(NULL), - m_typesForOSXScreen(NULL), - m_typesForClientListener(NULL), - m_typesForClientProxy(NULL), - m_typesForClientProxyUnknown(NULL), - m_typesForServer(NULL), - m_typesForServerApp(NULL), - m_typesForIKeyState(NULL), - m_typesForIPrimaryScreen(NULL), - m_typesForIScreen(NULL), - m_typesForClipboard(NULL), - m_typesForFile(NULL), + m_typesForClient(nullptr), + m_typesForIStream(nullptr), + m_typesForIpcClient(nullptr), + m_typesForIpcClientProxy(nullptr), + m_typesForIpcServer(nullptr), + m_typesForIpcServerProxy(nullptr), + m_typesForIDataSocket(nullptr), + m_typesForIListenSocket(nullptr), + m_typesForISocket(nullptr), + m_typesForOSXScreen(nullptr), + m_typesForClientListener(nullptr), + m_typesForClientProxy(nullptr), + m_typesForClientProxyUnknown(nullptr), + m_typesForServer(nullptr), + m_typesForServerApp(nullptr), + m_typesForIKeyState(nullptr), + m_typesForIPrimaryScreen(nullptr), + m_typesForIScreen(nullptr), + m_typesForClipboard(nullptr), + m_typesForFile(nullptr), m_readyMutex(new Mutex), m_readyCondVar(new CondVar(m_readyMutex, false)) { @@ -101,8 +101,8 @@ EventQueue::~EventQueue() delete m_readyCondVar; delete m_readyMutex; - ARCH->setSignalHandler(Arch::kINTERRUPT, NULL, NULL); - ARCH->setSignalHandler(Arch::kTERMINATE, NULL, NULL); + ARCH->setSignalHandler(Arch::kINTERRUPT, nullptr, nullptr); + ARCH->setSignalHandler(Arch::kTERMINATE, nullptr, nullptr); ARCH->closeMutex(m_mutex); } @@ -166,9 +166,9 @@ EventQueue::getTypeName(Event::Type type) if (i == m_typeMap.end()) { return ""; } - else { + return i->second; - } + } } @@ -179,7 +179,7 @@ EventQueue::adoptBuffer(IEventQueueBuffer* buffer) LOG((CLOG_DEBUG "adopting new buffer")); - if (m_events.size() != 0) { + if (!m_events.empty()) { // this can come as a nasty surprise to programmers expecting // their events to be raised, only to have them deleted. LOG((CLOG_DEBUG "discarding %d event(s)", m_events.size())); @@ -187,15 +187,15 @@ EventQueue::adoptBuffer(IEventQueueBuffer* buffer) // discard old buffer and old events delete m_buffer; - for (EventTable::iterator i = m_events.begin(); i != m_events.end(); ++i) { - Event::deleteData(i->second); + for (auto & m_event : m_events) { + Event::deleteData(m_event.second); } m_events.clear(); m_oldEventIDs.clear(); // use new buffer m_buffer = buffer; - if (m_buffer == NULL) { + if (m_buffer == nullptr) { m_buffer = new SimpleEventQueueBuffer; } } @@ -264,10 +264,10 @@ EventQueue::dispatchEvent(const Event& event) { void* target = event.getTarget(); IEventJob* job = getHandler(event.getType(), target); - if (job == NULL) { + if (job == nullptr) { job = getHandler(Event::kUnknown, target); } - if (job != NULL) { + if (job != nullptr) { job->run(event); return true; } @@ -322,7 +322,7 @@ EventQueue::newTimer(double duration, void* target) assert(duration > 0.0); EventQueueTimer* timer = m_buffer->newTimer(duration, false); - if (target == NULL) { + if (target == nullptr) { target = timer; } ArchMutexLock lock(m_mutex); @@ -341,7 +341,7 @@ EventQueue::newOneShotTimer(double duration, void* target) assert(duration > 0.0); EventQueueTimer* timer = m_buffer->newTimer(duration, true); - if (target == NULL) { + if (target == nullptr) { target = timer; } ArchMutexLock lock(m_mutex); @@ -358,14 +358,14 @@ void EventQueue::deleteTimer(EventQueueTimer* timer) { ArchMutexLock lock(m_mutex); - for (TimerQueue::iterator index = m_timerQueue.begin(); + for (auto index = m_timerQueue.begin(); index != m_timerQueue.end(); ++index) { if (index->getTimer() == timer) { m_timerQueue.erase(index); break; } } - Timers::iterator index = m_timers.find(timer); + auto index = m_timers.find(timer); if (index != m_timers.end()) { m_timers.erase(index); } @@ -384,13 +384,13 @@ EventQueue::adoptHandler(Event::Type type, void* target, IEventJob* handler) void EventQueue::removeHandler(Event::Type type, void* target) { - IEventJob* handler = NULL; + IEventJob* handler = nullptr; { ArchMutexLock lock(m_mutex); - HandlerTable::iterator index = m_handlers.find(target); + auto index = m_handlers.find(target); if (index != m_handlers.end()) { TypeHandlerTable& typeHandlers = index->second; - TypeHandlerTable::iterator index2 = typeHandlers.find(type); + auto index2 = typeHandlers.find(type); if (index2 != typeHandlers.end()) { handler = index2->second; typeHandlers.erase(index2); @@ -406,22 +406,20 @@ EventQueue::removeHandlers(void* target) std::vector handlers; { ArchMutexLock lock(m_mutex); - HandlerTable::iterator index = m_handlers.find(target); + auto index = m_handlers.find(target); if (index != m_handlers.end()) { // copy to handlers array and clear table for target TypeHandlerTable& typeHandlers = index->second; - for (TypeHandlerTable::iterator index2 = typeHandlers.begin(); - index2 != typeHandlers.end(); ++index2) { - handlers.push_back(index2->second); + for (auto & typeHandler : typeHandlers) { + handlers.push_back(typeHandler.second); } typeHandlers.clear(); } } // delete handlers - for (std::vector::iterator index = handlers.begin(); - index != handlers.end(); ++index) { - delete *index; + for (auto & handler : handlers) { + delete handler; } } @@ -435,15 +433,15 @@ IEventJob* EventQueue::getHandler(Event::Type type, void* target) const { ArchMutexLock lock(m_mutex); - HandlerTable::const_iterator index = m_handlers.find(target); + auto index = m_handlers.find(target); if (index != m_handlers.end()) { const TypeHandlerTable& typeHandlers = index->second; - TypeHandlerTable::const_iterator index2 = typeHandlers.find(type); + auto index2 = typeHandlers.find(type); if (index2 != typeHandlers.end()) { return index2->second; } } - return NULL; + return nullptr; } UInt32 @@ -470,9 +468,9 @@ Event EventQueue::removeEvent(UInt32 eventID) { // look up id - EventTable::iterator index = m_events.find(eventID); + auto index = m_events.find(eventID); if (index == m_events.end()) { - return Event(); + return {}; } // get data @@ -500,9 +498,8 @@ EventQueue::hasTimerExpired(Event& event) m_time.reset(); // countdown elapsed time - for (TimerQueue::iterator index = m_timerQueue.begin(); - index != m_timerQueue.end(); ++index) { - (*index) -= time; + for (auto & index : m_timerQueue) { + index -= time; } // done if no timers are expired @@ -545,9 +542,10 @@ EventQueue::getNextTimerTimeout() const Event::Type EventQueue::getRegisteredType(const String& name) const { - NameMap::const_iterator found = m_nameMap.find(name); - if (found != m_nameMap.end()) + auto found = m_nameMap.find(name); + if (found != m_nameMap.end()) { return found->second; +} return Event::kUnknown; } diff --git a/src/lib/base/EventQueue.h b/src/lib/base/EventQueue.h index 4a390b8d..8b85f46a 100644 --- a/src/lib/base/EventQueue.h +++ b/src/lib/base/EventQueue.h @@ -130,7 +130,7 @@ private: Stopwatch m_time; Timers m_timers; TimerQueue m_timerQueue; - TimerEvent m_timerEvent; + TimerEvent m_timerEvent{}; // event handlers HandlerTable m_handlers; diff --git a/src/lib/base/EventTypes.cpp b/src/lib/base/EventTypes.cpp index f9eff21b..38bfc5da 100644 --- a/src/lib/base/EventTypes.cpp +++ b/src/lib/base/EventTypes.cpp @@ -18,11 +18,11 @@ #include "base/EventTypes.h" #include "base/IEventQueue.h" -#include -#include +#include +#include EventTypes::EventTypes() : - m_events(NULL) + m_events(nullptr) { } diff --git a/src/lib/base/FunctionEventJob.cpp b/src/lib/base/FunctionEventJob.cpp index 88ea35c6..76a44afa 100644 --- a/src/lib/base/FunctionEventJob.cpp +++ b/src/lib/base/FunctionEventJob.cpp @@ -38,7 +38,7 @@ FunctionEventJob::~FunctionEventJob() void FunctionEventJob::run(const Event& event) { - if (m_func != NULL) { + if (m_func != nullptr) { m_func(event, m_arg); } } diff --git a/src/lib/base/FunctionJob.cpp b/src/lib/base/FunctionJob.cpp index 10b06c44..93df6192 100644 --- a/src/lib/base/FunctionJob.cpp +++ b/src/lib/base/FunctionJob.cpp @@ -37,7 +37,7 @@ FunctionJob::~FunctionJob() void FunctionJob::run() { - if (m_func != NULL) { + if (m_func != nullptr) { m_func(m_arg); } } diff --git a/src/lib/base/Log.cpp b/src/lib/base/Log.cpp index 3a8351b8..60393ec0 100644 --- a/src/lib/base/Log.cpp +++ b/src/lib/base/Log.cpp @@ -25,8 +25,8 @@ #include #include -#include #include +#include // names of priorities static const char* g_priority[] = { @@ -44,7 +44,7 @@ static const char* g_priority[] = { }; // number of priorities -static const int g_numPriority = (int)(sizeof(g_priority) / sizeof(g_priority[0])); +static const int g_numPriority = static_cast(sizeof(g_priority) / sizeof(g_priority[0])); // the default priority #ifndef NDEBUG @@ -57,7 +57,7 @@ static const int g_defaultMaxPriority = kINFO; // Log // -Log* Log::s_log = NULL; +Log* Log::s_log = nullptr; Log::Log() { @@ -82,13 +82,11 @@ Log::Log(Log* src) Log::~Log() { // clean up - for (OutputterList::iterator index = m_outputters.begin(); - index != m_outputters.end(); ++index) { - delete *index; + for (auto & m_outputter : m_outputters) { + delete m_outputter; } - for (OutputterList::iterator index = m_alwaysOutputters.begin(); - index != m_alwaysOutputters.end(); ++index) { - delete *index; + for (auto & m_alwaysOutputter : m_alwaysOutputters) { + delete m_alwaysOutputter; } ARCH->closeMutex(m_mutex); } @@ -116,7 +114,7 @@ Log::getFilterName(int level) const } void -Log::print(const char* file, int line, const char* fmt, ...) +Log::print(const char* /*file*/, int /*line*/, const char* fmt, ...) { // check if fmt begins with a priority argument ELevel priority = kINFO; @@ -125,7 +123,7 @@ Log::print(const char* file, int line, const char* fmt, ...) // 060 in octal is 0 (48 in decimal), so subtracting this converts ascii // number it a true number. we could use atoi instead, but this is how // it was done originally. - priority = (ELevel)(fmt[2] - '\060'); + priority = static_cast(fmt[2] - '\060'); // move the pointer on past the debug priority char fmt += 3; @@ -145,7 +143,7 @@ Log::print(const char* file, int line, const char* fmt, ...) // print to buffer, leaving space for a newline at the end and prefix // at the beginning. char* buffer = stack; - int len = (int)(sizeof(stack) / sizeof(stack[0])); + auto len = static_cast(sizeof(stack) / sizeof(stack[0])); while (true) { // try printing into the buffer va_list args; @@ -154,7 +152,7 @@ Log::print(const char* file, int line, const char* fmt, ...) va_end(args); // if the buffer wasn't big enough then make it bigger and try again - if (n < 0 || n > (int)len) { + if (n < 0 || n > len) { if (buffer != stack) { delete[] buffer; } @@ -189,7 +187,7 @@ Log::print(const char* file, int line, const char* fmt, ...) // assume there is no file contains over 100k lines of code size += 6; #endif - char* message = new char[size]; + auto* message = new char[size]; #ifndef NDEBUG sprintf(message, "[%s] %s: %s\n\t%s,%d", timestamp, g_priority[priority], buffer, file, line); @@ -256,7 +254,7 @@ Log::pop_front(bool alwaysAtHead) bool Log::setFilter(const char* maxPriority) { - if (maxPriority != NULL) { + if (maxPriority != nullptr) { for (int i = 0; i < g_numPriority; ++i) { if (strcmp(maxPriority, g_priority[i]) == 0) { setFilter(i); @@ -287,7 +285,8 @@ Log::output(ELevel priority, char* msg) { assert(priority >= -1 && priority < g_numPriority); assert(msg != NULL); - if (!msg) return; + if (msg == nullptr) { return; +} ArchMutexLock lock(m_mutex); diff --git a/src/lib/base/Log.h b/src/lib/base/Log.h index b54e82f5..b527af79 100644 --- a/src/lib/base/Log.h +++ b/src/lib/base/Log.h @@ -62,7 +62,7 @@ public: By default, the logger has one outputter installed which writes to the console. */ - void insert(ILogOutputter* adopted, + void insert(ILogOutputter* outputter, bool alwaysAtHead = false); //! Remove an outputter from the list @@ -71,7 +71,7 @@ public: outputter list. It does nothing if the outputter is not in the list. The outputter is not deleted. */ - void remove(ILogOutputter* orphaned); + void remove(ILogOutputter* outputter); //! Remove the outputter from the head of the list /*! @@ -89,7 +89,7 @@ public: true if the priority \c name was recognized; if \c name is NULL then it simply returns true. */ - bool setFilter(const char* name); + bool setFilter(const char* maxPriority); //! Set the minimum priority filter (by ordinal). void setFilter(int); @@ -105,7 +105,7 @@ public: neither the file nor the line are printed. */ void print(const char* file, int line, - const char* format, ...); + const char* fmt, ...); //! Get the minimum priority level. int getFilter() const; @@ -132,11 +132,11 @@ private: static Log* s_log; - ArchMutex m_mutex; + ArchMutex m_mutex{}; OutputterList m_outputters; OutputterList m_alwaysOutputters; - int m_maxNewlineLength; - int m_maxPriority; + int m_maxNewlineLength{}; + int m_maxPriority{}; }; /*! diff --git a/src/lib/base/SimpleEventQueueBuffer.cpp b/src/lib/base/SimpleEventQueueBuffer.cpp index b8603403..8b2db1b2 100644 --- a/src/lib/base/SimpleEventQueueBuffer.cpp +++ b/src/lib/base/SimpleEventQueueBuffer.cpp @@ -17,8 +17,8 @@ */ #include "base/SimpleEventQueueBuffer.h" -#include "base/Stopwatch.h" #include "arch/Arch.h" +#include "base/Stopwatch.h" class EventQueueTimer { }; @@ -57,7 +57,7 @@ SimpleEventQueueBuffer::waitForEvent(double timeout) } IEventQueueBuffer::Type -SimpleEventQueueBuffer::getEvent(Event&, UInt32& dataID) +SimpleEventQueueBuffer::getEvent(Event& /*event*/, UInt32& dataID) { ArchMutexLock lock(m_queueMutex); if (!m_queueReady) { @@ -89,7 +89,7 @@ SimpleEventQueueBuffer::isEmpty() const } EventQueueTimer* -SimpleEventQueueBuffer::newTimer(double, bool) const +SimpleEventQueueBuffer::newTimer(double /*duration*/, bool /*oneShot*/) const { return new EventQueueTimer; } diff --git a/src/lib/base/Stopwatch.cpp b/src/lib/base/Stopwatch.cpp index f5dee045..e20b35de 100644 --- a/src/lib/base/Stopwatch.cpp +++ b/src/lib/base/Stopwatch.cpp @@ -46,12 +46,12 @@ Stopwatch::reset() m_mark = 0.0; return dt; } - else { + const double t = ARCH->time(); const double dt = t - m_mark; m_mark = t; return dt; - } + } void @@ -94,7 +94,7 @@ Stopwatch::getTime() start(); return dt; } - else if (m_stopped) { + if (m_stopped) { return m_mark; } else { @@ -119,9 +119,9 @@ Stopwatch::getTime() const if (m_stopped) { return m_mark; } - else { + return ARCH->time() - m_mark; - } + } Stopwatch::operator double() const diff --git a/src/lib/base/String.cpp b/src/lib/base/String.cpp index 8349715b..861468d6 100644 --- a/src/lib/base/String.cpp +++ b/src/lib/base/String.cpp @@ -20,17 +20,17 @@ #include "common/common.h" #include "common/stdvector.h" +#include +#include #include +#include +#include #include #include #include -#include -#include -#include -#include #include -#include -#include +#include +#include namespace synergy { namespace string { @@ -59,7 +59,7 @@ vformat(const char* fmt, va_list args) if (*scan == '\0') { break; } - else if (*scan == '%') { + if (*scan == '%') { // literal index.push_back(0); pos.push_back(static_cast((scan - 1) - fmt)); @@ -104,7 +104,7 @@ vformat(const char* fmt, va_list args) // compute final length size_t resultLength = strlen(fmt); - const int n = static_cast(pos.size()); + const auto n = static_cast(pos.size()); for (int i = 0; i < n; ++i) { resultLength -= width[i]; resultLength += length[index[i]]; @@ -129,9 +129,9 @@ sprintf(const char* fmt, ...) { char tmp[1024]; char* buffer = tmp; - int len = (int)(sizeof(tmp) / sizeof(tmp[0])); + auto len = static_cast(sizeof(tmp) / sizeof(tmp[0])); String result; - while (buffer != NULL) { + while (buffer != nullptr) { // try printing into the buffer va_list args; va_start(args, fmt); @@ -153,7 +153,7 @@ sprintf(const char* fmt, ...) if (buffer != tmp) { delete[] buffer; } - buffer = NULL; + buffer = nullptr; } } @@ -190,8 +190,8 @@ toHex(String& subject, int width, const char fill) { std::stringstream ss; ss << std::hex; - for (unsigned int i = 0; i < subject.length(); i++) { - ss << std::setw(width) << std::setfill(fill) << (int)(unsigned char)subject[i]; + for (char i : subject) { + ss << std::setw(width) << std::setfill(fill) << static_cast(static_cast(i)); } subject = ss.str(); @@ -218,7 +218,7 @@ sizeTypeToString(size_t n) } size_t -stringToSizeType(String string) +stringToSizeType(const String& string) { std::istringstream iss(string); size_t value; @@ -227,7 +227,7 @@ stringToSizeType(String string) } std::vector -splitString(String string, const char c) +splitString(const String& string, const char c) { std::vector results; @@ -291,5 +291,5 @@ CaselessCmp::operator()(const String& a, const String& b) const return less(a, b); } -} -} +} // namespace string +} // namespace synergy diff --git a/src/lib/base/String.h b/src/lib/base/String.h index 92d70712..be4e8a15 100644 --- a/src/lib/base/String.h +++ b/src/lib/base/String.h @@ -99,13 +99,13 @@ String sizeTypeToString(size_t n); /*! Convert an a \c string to an size type */ -size_t stringToSizeType(String string); +size_t stringToSizeType(const String& string); //! Split a string into substrings /*! Split a \c string that separated by a \c c into substrings */ -std::vector splitString(String string, const char c); +std::vector splitString(const String& string, const char c); //! Case-insensitive comparisons /*! diff --git a/src/lib/base/Unicode.cpp b/src/lib/base/Unicode.cpp index ea814eae..0cbe58ad 100644 --- a/src/lib/base/Unicode.cpp +++ b/src/lib/base/Unicode.cpp @@ -33,7 +33,7 @@ decode16(const UInt8* n, bool byteSwapped) union x16 { UInt8 n8[2]; UInt16 n16; - } c; + } c{}; if (byteSwapped) { c.n8[0] = n[1]; c.n8[1] = n[0]; @@ -53,7 +53,7 @@ decode32(const UInt8* n, bool byteSwapped) union x32 { UInt8 n8[4]; UInt32 n32; - } c; + } c{}; if (byteSwapped) { c.n8[0] = n[3]; c.n8[1] = n[2]; @@ -74,7 +74,7 @@ static void resetError(bool* errors) { - if (errors != NULL) { + if (errors != nullptr) { *errors = false; } } @@ -84,7 +84,7 @@ static void setError(bool* errors) { - if (errors != NULL) { + if (errors != nullptr) { *errors = true; } } @@ -101,8 +101,8 @@ bool Unicode::isUTF8(const String& src) { // convert and test each character - const UInt8* data = reinterpret_cast(src.c_str()); - for (UInt32 n = (UInt32)src.size(); n > 0; ) { + const auto* data = reinterpret_cast(src.c_str()); + for (auto n = static_cast(src.size()); n > 0; ) { if (fromUTF8(data, n) == s_invalid) { return false; } @@ -117,12 +117,12 @@ Unicode::UTF8ToUCS2(const String& src, bool* errors) resetError(errors); // get size of input string and reserve some space in output - UInt32 n = (UInt32)src.size(); + auto n = static_cast(src.size()); String dst; dst.reserve(2 * n); // convert each character - const UInt8* data = reinterpret_cast(src.c_str()); + const auto* data = reinterpret_cast(src.c_str()); while (n > 0) { UInt32 c = fromUTF8(data, n); if (c == s_invalid) { @@ -132,7 +132,7 @@ Unicode::UTF8ToUCS2(const String& src, bool* errors) setError(errors); c = s_replacement; } - UInt16 ucs2 = static_cast(c); + auto ucs2 = static_cast(c); dst.append(reinterpret_cast(&ucs2), 2); } @@ -146,12 +146,12 @@ Unicode::UTF8ToUCS4(const String& src, bool* errors) resetError(errors); // get size of input string and reserve some space in output - UInt32 n = (UInt32)src.size(); + auto n = static_cast(src.size()); String dst; dst.reserve(4 * n); // convert each character - const UInt8* data = reinterpret_cast(src.c_str()); + const auto* data = reinterpret_cast(src.c_str()); while (n > 0) { UInt32 c = fromUTF8(data, n); if (c == s_invalid) { @@ -170,12 +170,12 @@ Unicode::UTF8ToUTF16(const String& src, bool* errors) resetError(errors); // get size of input string and reserve some space in output - UInt32 n = (UInt32)src.size(); + auto n = static_cast(src.size()); String dst; dst.reserve(2 * n); // convert each character - const UInt8* data = reinterpret_cast(src.c_str()); + const auto* data = reinterpret_cast(src.c_str()); while (n > 0) { UInt32 c = fromUTF8(data, n); if (c == s_invalid) { @@ -186,13 +186,13 @@ Unicode::UTF8ToUTF16(const String& src, bool* errors) c = s_replacement; } if (c < 0x00010000) { - UInt16 ucs2 = static_cast(c); + auto ucs2 = static_cast(c); dst.append(reinterpret_cast(&ucs2), 2); } else { c -= 0x00010000; - UInt16 utf16h = static_cast((c >> 10) + 0xd800); - UInt16 utf16l = static_cast((c & 0x03ff) + 0xdc00); + auto utf16h = static_cast((c >> 10) + 0xd800); + auto utf16l = static_cast((c & 0x03ff) + 0xdc00); dst.append(reinterpret_cast(&utf16h), 2); dst.append(reinterpret_cast(&utf16l), 2); } @@ -208,12 +208,12 @@ Unicode::UTF8ToUTF32(const String& src, bool* errors) resetError(errors); // get size of input string and reserve some space in output - UInt32 n = (UInt32)src.size(); + auto n = static_cast(src.size()); String dst; dst.reserve(4 * n); // convert each character - const UInt8* data = reinterpret_cast(src.c_str()); + const auto* data = reinterpret_cast(src.c_str()); while (n > 0) { UInt32 c = fromUTF8(data, n); if (c == s_invalid) { @@ -240,8 +240,8 @@ Unicode::UTF8ToText(const String& src, bool* errors) wchar_t* tmp = UTF8ToWideChar(src, size, errors); // convert string to multibyte - int len = ARCH->convStringWCToMB(NULL, tmp, size, errors); - char* mbs = new char[len + 1]; + int len = ARCH->convStringWCToMB(nullptr, tmp, size, errors); + auto* mbs = new char[len + 1]; ARCH->convStringWCToMB(mbs, tmp, size, errors); String text(mbs, len); @@ -259,7 +259,7 @@ Unicode::UCS2ToUTF8(const String& src, bool* errors) resetError(errors); // convert - UInt32 n = (UInt32)src.size() >> 1; + UInt32 n = static_cast(src.size()) >> 1; return doUCS2ToUTF8(reinterpret_cast(src.data()), n, errors); } @@ -270,7 +270,7 @@ Unicode::UCS4ToUTF8(const String& src, bool* errors) resetError(errors); // convert - UInt32 n = (UInt32)src.size() >> 2; + UInt32 n = static_cast(src.size()) >> 2; return doUCS4ToUTF8(reinterpret_cast(src.data()), n, errors); } @@ -281,7 +281,7 @@ Unicode::UTF16ToUTF8(const String& src, bool* errors) resetError(errors); // convert - UInt32 n = (UInt32)src.size() >> 1; + UInt32 n = static_cast(src.size()) >> 1; return doUTF16ToUTF8(reinterpret_cast(src.data()), n, errors); } @@ -292,7 +292,7 @@ Unicode::UTF32ToUTF8(const String& src, bool* errors) resetError(errors); // convert - UInt32 n = (UInt32)src.size() >> 2; + UInt32 n = static_cast(src.size()) >> 2; return doUTF32ToUTF8(reinterpret_cast(src.data()), n, errors); } @@ -303,9 +303,9 @@ Unicode::textToUTF8(const String& src, bool* errors) resetError(errors); // convert string to wide characters - UInt32 n = (UInt32)src.size(); - int len = ARCH->convStringMBToWC(NULL, src.c_str(), n, errors); - wchar_t* wcs = new wchar_t[len + 1]; + auto n = static_cast(src.size()); + int len = ARCH->convStringMBToWC(nullptr, src.c_str(), n, errors); + auto* wcs = new wchar_t[len + 1]; ARCH->convStringMBToWC(wcs, src.c_str(), n, errors); // convert to UTF8 @@ -325,22 +325,22 @@ Unicode::UTF8ToWideChar(const String& src, UInt32& size, bool* errors) switch (ARCH->getWideCharEncoding()) { case IArchString::kUCS2: tmp = UTF8ToUCS2(src, errors); - size = (UInt32)tmp.size() >> 1; + size = static_cast(tmp.size()) >> 1; break; case IArchString::kUCS4: tmp = UTF8ToUCS4(src, errors); - size = (UInt32)tmp.size() >> 2; + size = static_cast(tmp.size()) >> 2; break; case IArchString::kUTF16: tmp = UTF8ToUTF16(src, errors); - size = (UInt32)tmp.size() >> 1; + size = static_cast(tmp.size()) >> 1; break; case IArchString::kUTF32: tmp = UTF8ToUTF32(src, errors); - size = (UInt32)tmp.size() >> 2; + size = static_cast(tmp.size()) >> 2; break; default: @@ -348,7 +348,7 @@ Unicode::UTF8ToWideChar(const String& src, UInt32& size, bool* errors) } // copy to a wchar_t array - wchar_t* dst = new wchar_t[size]; + auto* dst = new wchar_t[size]; ::memcpy(dst, tmp.data(), sizeof(wchar_t) * size); return dst; } @@ -486,7 +486,7 @@ Unicode::doUTF16ToUTF8(const UInt8* data, UInt32 n, bool* errors) else if (n == 1) { // error -- missing second word setError(errors); - toUTF8(dst, s_replacement, NULL); + toUTF8(dst, s_replacement, nullptr); } else if (c >= 0x0000d800 && c <= 0x0000dbff) { UInt32 c2 = decode16(data, byteSwapped); @@ -495,7 +495,7 @@ Unicode::doUTF16ToUTF8(const UInt8* data, UInt32 n, bool* errors) if (c2 < 0x0000dc00 || c2 > 0x0000dfff) { // error -- [d800,dbff] not followed by [dc00,dfff] setError(errors); - toUTF8(dst, s_replacement, NULL); + toUTF8(dst, s_replacement, nullptr); } else { c = (((c - 0x0000d800) << 10) | (c2 - 0x0000dc00)) + 0x00010000; @@ -505,7 +505,7 @@ Unicode::doUTF16ToUTF8(const UInt8* data, UInt32 n, bool* errors) else { // error -- [dc00,dfff] without leading [d800,dbff] setError(errors); - toUTF8(dst, s_replacement, NULL); + toUTF8(dst, s_replacement, nullptr); } } diff --git a/src/lib/base/Unicode.h b/src/lib/base/Unicode.h index b92b665b..892f9915 100644 --- a/src/lib/base/Unicode.h +++ b/src/lib/base/Unicode.h @@ -129,13 +129,13 @@ private: UInt32 size, bool* errors); // internal conversion to UTF8 - static String doUCS2ToUTF8(const UInt8* src, UInt32 n, bool* errors); - static String doUCS4ToUTF8(const UInt8* src, UInt32 n, bool* errors); - static String doUTF16ToUTF8(const UInt8* src, UInt32 n, bool* errors); - static String doUTF32ToUTF8(const UInt8* src, UInt32 n, bool* errors); + static String doUCS2ToUTF8(const UInt8* data, UInt32 n, bool* errors); + static String doUCS4ToUTF8(const UInt8* data, UInt32 n, bool* errors); + static String doUTF16ToUTF8(const UInt8* data, UInt32 n, bool* errors); + static String doUTF32ToUTF8(const UInt8* data, UInt32 n, bool* errors); // convert characters to/from UTF8 - static UInt32 fromUTF8(const UInt8*& src, UInt32& size); + static UInt32 fromUTF8(const UInt8*& data, UInt32& n); static void toUTF8(String& dst, UInt32 c, bool* errors); private: diff --git a/src/lib/base/XBase.cpp b/src/lib/base/XBase.cpp index ee4b5665..958a4419 100644 --- a/src/lib/base/XBase.cpp +++ b/src/lib/base/XBase.cpp @@ -38,13 +38,13 @@ XBase::XBase(const String& msg) : // do nothing } -XBase::~XBase() _NOEXCEPT +XBase::~XBase() noexcept { // do nothing } const char* -XBase::what() const _NOEXCEPT +XBase::what() const noexcept { const char* what = std::runtime_error::what(); if (strlen(what) == 0) { @@ -55,7 +55,7 @@ XBase::what() const _NOEXCEPT } String -XBase::format(const char* /*id*/, const char* fmt, ...) const throw() +XBase::format(const char* /*id*/, const char* fmt, ...) const noexcept { // FIXME -- lookup message string using id as an index. set // fmt to that string if it exists. diff --git a/src/lib/base/XBase.h b/src/lib/base/XBase.h index 33da3bc4..f1de3f20 100644 --- a/src/lib/base/XBase.h +++ b/src/lib/base/XBase.h @@ -47,7 +47,7 @@ protected: the format string and returns the result. */ virtual String format(const char* id, - const char* defaultFormat, ...) const throw(); + const char* fmt, ...) const throw(); private: mutable String m_what; }; diff --git a/src/lib/base/log_outputters.cpp b/src/lib/base/log_outputters.cpp index 514e0fa3..668a59ee 100644 --- a/src/lib/base/log_outputters.cpp +++ b/src/lib/base/log_outputters.cpp @@ -17,8 +17,8 @@ */ #include "base/log_outputters.h" -#include "base/TMethodJob.h" #include "arch/Arch.h" +#include "base/TMethodJob.h" #include @@ -41,7 +41,7 @@ StopLogOutputter::~StopLogOutputter() } void -StopLogOutputter::open(const char*) +StopLogOutputter::open(const char* /*title*/) { // do nothing } @@ -53,13 +53,13 @@ StopLogOutputter::close() } void -StopLogOutputter::show(bool) +StopLogOutputter::show(bool /*showIfEmpty*/) { // do nothing } bool -StopLogOutputter::write(ELevel, const char*) +StopLogOutputter::write(ELevel /*level*/, const char* /*message*/) { return false; } @@ -70,12 +70,10 @@ StopLogOutputter::write(ELevel, const char*) // ConsoleLogOutputter::ConsoleLogOutputter() -{ -} += default; ConsoleLogOutputter::~ConsoleLogOutputter() -{ -} += default; void ConsoleLogOutputter::open(const char* title) @@ -153,7 +151,7 @@ SystemLogOutputter::write(ELevel level, const char* msg) // SystemLogger::SystemLogger(const char* title, bool blockConsole) : - m_stop(NULL) + m_stop(nullptr) { // redirect log messages if (blockConsole) { @@ -169,7 +167,7 @@ SystemLogger::~SystemLogger() { CLOG->remove(m_syslog); delete m_syslog; - if (m_stop != NULL) { + if (m_stop != nullptr) { CLOG->remove(m_stop); delete m_stop; } @@ -204,7 +202,7 @@ BufferedLogOutputter::end() const } void -BufferedLogOutputter::open(const char*) +BufferedLogOutputter::open(const char* /*title*/) { // do nothing } @@ -217,18 +215,18 @@ BufferedLogOutputter::close() } void -BufferedLogOutputter::show(bool) +BufferedLogOutputter::show(bool /*showIfEmpty*/) { // do nothing } bool -BufferedLogOutputter::write(ELevel, const char* message) +BufferedLogOutputter::write(ELevel /*level*/, const char* message) { while (m_buffer.size() >= m_maxBufferSize) { m_buffer.pop_front(); } - m_buffer.push_back(String(message)); + m_buffer.emplace_back(message); return true; } @@ -243,8 +241,7 @@ FileLogOutputter::FileLogOutputter(const char* logFile) } FileLogOutputter::~FileLogOutputter() -{ -} += default; void FileLogOutputter::setLogFilename(const char* logFile) @@ -254,13 +251,13 @@ FileLogOutputter::setLogFilename(const char* logFile) } bool -FileLogOutputter::write(ELevel level, const char *message) +FileLogOutputter::write(ELevel /*level*/, const char *message) { bool moveFile = false; std::ofstream m_handle; m_handle.open(m_fileName.c_str(), std::fstream::app); - if (m_handle.is_open() && m_handle.fail() != true) { + if (m_handle.is_open() && !m_handle.fail()) { m_handle << message << std::endl; // when file size exceeds limits, move to 'old log' filename. @@ -281,13 +278,13 @@ FileLogOutputter::write(ELevel level, const char *message) } void -FileLogOutputter::open(const char *title) {} +FileLogOutputter::open(const char * /*title*/) {} void FileLogOutputter::close() {} void -FileLogOutputter::show(bool showIfEmpty) {} +FileLogOutputter::show(bool /*showIfEmpty*/) {} // // MesssageBoxLogOutputter @@ -304,7 +301,7 @@ MesssageBoxLogOutputter::~MesssageBoxLogOutputter() } void -MesssageBoxLogOutputter::open(const char* title) +MesssageBoxLogOutputter::open(const char* /*title*/) { // do nothing } @@ -316,13 +313,13 @@ MesssageBoxLogOutputter::close() } void -MesssageBoxLogOutputter::show(bool showIfEmpty) +MesssageBoxLogOutputter::show(bool /*showIfEmpty*/) { // do nothing } bool -MesssageBoxLogOutputter::write(ELevel level, const char* msg) +MesssageBoxLogOutputter::write(ELevel level, const char* /*msg*/) { // don't spam user with messages. if (level > kERROR) { diff --git a/src/lib/base/log_outputters.h b/src/lib/base/log_outputters.h index fb94c02e..22de24b0 100644 --- a/src/lib/base/log_outputters.h +++ b/src/lib/base/log_outputters.h @@ -59,7 +59,7 @@ public: virtual void open(const char* title); virtual void close(); virtual void show(bool showIfEmpty); - virtual bool write(ELevel level, const char* message); + virtual bool write(ELevel level, const char* msg); virtual void flush(); }; @@ -80,7 +80,7 @@ public: virtual void show(bool showIfEmpty); virtual bool write(ELevel level, const char* message); - void setLogFilename(const char* title); + void setLogFilename(const char* logFile); private: std::string m_fileName; @@ -99,7 +99,7 @@ public: virtual void open(const char* title); virtual void close(); virtual void show(bool showIfEmpty); - virtual bool write(ELevel level, const char* message); + virtual bool write(ELevel level, const char* msg); }; //! Write log to system log only diff --git a/src/lib/client/Client.cpp b/src/lib/client/Client.cpp index 4321074e..a9276de1 100644 --- a/src/lib/client/Client.cpp +++ b/src/lib/client/Client.cpp @@ -18,31 +18,32 @@ #include "client/Client.h" -#include "client/ServerProxy.h" -#include "core/Screen.h" -#include "core/FileChunk.h" -#include "core/DropHelper.h" -#include "core/PacketStreamFilter.h" -#include "core/ProtocolUtil.h" -#include "core/protocol_types.h" -#include "core/XSynergy.h" -#include "core/StreamChunker.h" -#include "core/IPlatformScreen.h" -#include "mt/Thread.h" -#include "net/TCPSocket.h" -#include "net/IDataSocket.h" -#include "net/ISocketFactory.h" #include "arch/Arch.h" -#include "base/Log.h" #include "base/IEventQueue.h" +#include "base/Log.h" #include "base/TMethodEventJob.h" #include "base/TMethodJob.h" +#include "client/ServerProxy.h" #include "common/stdexcept.h" +#include "core/DropHelper.h" +#include "core/FileChunk.h" +#include "core/IPlatformScreen.h" +#include "core/PacketStreamFilter.h" +#include "core/ProtocolUtil.h" +#include "core/Screen.h" +#include "core/StreamChunker.h" +#include "core/XSynergy.h" +#include "core/protocol_types.h" +#include "mt/Thread.h" +#include "net/IDataSocket.h" +#include "net/ISocketFactory.h" +#include "net/TCPSocket.h" -#include #include -#include +#include #include +#include +#include // // Client @@ -50,27 +51,27 @@ Client::Client( IEventQueue* events, - const String& name, const NetworkAddress& address, + String name, const NetworkAddress& address, ISocketFactory* socketFactory, synergy::Screen* screen, - ClientArgs const& args) : + ClientArgs args) : m_mock(false), - m_name(name), + m_name(std::move(name)), m_serverAddress(address), m_socketFactory(socketFactory), m_screen(screen), - m_stream(NULL), - m_timer(NULL), - m_server(NULL), + m_stream(nullptr), + m_timer(nullptr), + m_server(nullptr), m_ready(false), m_active(false), m_suspended(false), m_connectOnResume(false), m_events(events), - m_sendFileThread(NULL), - m_writeToDropDirThread(NULL), - m_socket(NULL), - m_args(args), + m_sendFileThread(nullptr), + m_writeToDropDirThread(nullptr), + m_socket(nullptr), + m_args(std::move(args)), m_enableClipboard(true) { assert(m_socketFactory != NULL); @@ -119,7 +120,7 @@ Client::~Client() void Client::connect() { - if (m_stream != NULL) { + if (m_stream != nullptr) { return; } if (m_suspended) { @@ -136,7 +137,7 @@ Client::connect() m_serverAddress.resolve(); // m_serverAddress will be null if the hostname address is not reolved - if (m_serverAddress.getAddress() != NULL) { + if (m_serverAddress.getAddress() != nullptr) { // to help users troubleshoot, show server host name (issue: 60) LOG((CLOG_NOTE "connecting to '%s': %s:%i", m_serverAddress.getHostname().c_str(), @@ -176,11 +177,11 @@ Client::disconnect(const char* msg) cleanupScreen(); cleanupConnecting(); cleanupConnection(); - if (msg != NULL) { + if (msg != nullptr) { sendConnectionFailedEvent(msg); } else { - sendEvent(m_events->forClient().disconnected(), NULL); + sendEvent(m_events->forClient().disconnected(), nullptr); } } @@ -189,19 +190,19 @@ Client::handshakeComplete() { m_ready = true; m_screen->enable(); - sendEvent(m_events->forClient().connected(), NULL); + sendEvent(m_events->forClient().connected(), nullptr); } bool Client::isConnected() const { - return (m_server != NULL); + return (m_server != nullptr); } bool Client::isConnecting() const { - return (m_timer != NULL); + return (m_timer != nullptr); } NetworkAddress @@ -235,15 +236,15 @@ Client::getCursorPos(SInt32& x, SInt32& y) const } void -Client::enter(SInt32 xAbs, SInt32 yAbs, UInt32, KeyModifierMask mask, bool) +Client::enter(SInt32 xAbs, SInt32 yAbs, UInt32 /*seqNum*/, KeyModifierMask mask, bool /*forScreensaver*/) { m_active = true; m_screen->mouseMove(xAbs, yAbs); m_screen->enter(mask); - if (m_sendFileThread != NULL) { + if (m_sendFileThread != nullptr) { StreamChunker::interruptFile(); - m_sendFileThread = NULL; + m_sendFileThread = nullptr; } } @@ -283,7 +284,7 @@ Client::grabClipboard(ClipboardID id) } void -Client::setClipboardDirty(ClipboardID, bool) +Client::setClipboardDirty(ClipboardID /*unused*/, bool /*dirty*/) { assert(0 && "shouldn't be called"); } @@ -352,7 +353,7 @@ Client::resetOptions() void Client::setOptions(const OptionsList& options) { - for (OptionsList::const_iterator index = options.begin(); + for (auto index = options.begin(); index != options.end(); ++index) { const OptionID id = *index; if (id == kOptionClipboardSharing) { @@ -360,7 +361,7 @@ Client::setOptions(const OptionsList& options) if (*index == static_cast(false)) { LOG((CLOG_NOTE "clipboard sharing is disabled")); } - m_enableClipboard = *index; + m_enableClipboard = (*index != 0u); break; } @@ -419,7 +420,7 @@ Client::sendEvent(Event::Type type, void* data) void Client::sendConnectionFailedEvent(const char* msg) { - FailInfo* info = new FailInfo(msg); + auto* info = new FailInfo(msg); info->m_retry = true; Event event(m_events->forClient().connectionFailed(), getEventTarget(), info, Event::kDontFreeData); m_events->addEvent(event); @@ -428,7 +429,7 @@ Client::sendConnectionFailedEvent(const char* msg) void Client::sendFileChunk(const void* data) { - FileChunk* chunk = static_cast(const_cast(data)); + auto* chunk = static_cast(const_cast(data)); LOG((CLOG_DEBUG1 "send file chunk")); assert(m_server != NULL); @@ -505,7 +506,7 @@ Client::setupTimer() { assert(m_timer == NULL); - m_timer = m_events->newOneShotTimer(15.0, NULL); + m_timer = m_events->newOneShotTimer(15.0, nullptr); m_events->adoptHandler(Event::kTimer, m_timer, new TMethodEventJob(this, &Client::handleConnectTimeout)); @@ -514,7 +515,7 @@ Client::setupTimer() void Client::cleanupConnecting() { - if (m_stream != NULL) { + if (m_stream != nullptr) { m_events->removeHandler(m_events->forIDataSocket().connected(), m_stream->getEventTarget()); m_events->removeHandler(m_events->forIDataSocket().connectionFailed(), @@ -525,7 +526,7 @@ Client::cleanupConnecting() void Client::cleanupConnection() { - if (m_stream != NULL) { + if (m_stream != nullptr) { m_events->removeHandler(m_events->forIStream().inputReady(), m_stream->getEventTarget()); m_events->removeHandler(m_events->forIStream().outputError(), @@ -545,7 +546,7 @@ Client::cleanupConnection() void Client::cleanupScreen() { - if (m_server != NULL) { + if (m_server != nullptr) { if (m_ready) { m_screen->disable(); m_ready = false; @@ -555,17 +556,17 @@ Client::cleanupScreen() m_events->removeHandler(m_events->forClipboard().clipboardGrabbed(), getEventTarget()); delete m_server; - m_server = NULL; + m_server = nullptr; } } void Client::cleanupTimer() { - if (m_timer != NULL) { + if (m_timer != nullptr) { m_events->removeHandler(Event::kTimer, m_timer); m_events->deleteTimer(m_timer); - m_timer = NULL; + m_timer = nullptr; } } @@ -573,11 +574,11 @@ void Client::cleanupStream() { delete m_stream; - m_stream = NULL; + m_stream = nullptr; } void -Client::handleConnected(const Event&, void*) +Client::handleConnected(const Event& /*unused*/, void* /*unused*/) { LOG((CLOG_DEBUG1 "connected; wait for hello")); cleanupConnecting(); @@ -592,9 +593,9 @@ Client::handleConnected(const Event&, void*) } void -Client::handleConnectionFailed(const Event& event, void*) +Client::handleConnectionFailed(const Event& event, void* /*unused*/) { - IDataSocket::ConnectionFailedInfo* info = + auto* info = static_cast(event.getData()); cleanupTimer(); @@ -606,7 +607,7 @@ Client::handleConnectionFailed(const Event& event, void*) } void -Client::handleConnectTimeout(const Event&, void*) +Client::handleConnectTimeout(const Event& /*unused*/, void* /*unused*/) { cleanupTimer(); cleanupConnecting(); @@ -617,40 +618,40 @@ Client::handleConnectTimeout(const Event&, void*) } void -Client::handleOutputError(const Event&, void*) +Client::handleOutputError(const Event& /*unused*/, void* /*unused*/) { cleanupTimer(); cleanupScreen(); cleanupConnection(); LOG((CLOG_WARN "error sending to server")); - sendEvent(m_events->forClient().disconnected(), NULL); + sendEvent(m_events->forClient().disconnected(), nullptr); } void -Client::handleDisconnected(const Event&, void*) +Client::handleDisconnected(const Event& /*unused*/, void* /*unused*/) { cleanupTimer(); cleanupScreen(); cleanupConnection(); LOG((CLOG_DEBUG1 "disconnected")); - sendEvent(m_events->forClient().disconnected(), NULL); + sendEvent(m_events->forClient().disconnected(), nullptr); } void -Client::handleShapeChanged(const Event&, void*) +Client::handleShapeChanged(const Event& /*unused*/, void* /*unused*/) { LOG((CLOG_DEBUG "resolution changed")); m_server->onInfoChanged(); } void -Client::handleClipboardGrabbed(const Event& event, void*) +Client::handleClipboardGrabbed(const Event& event, void* /*unused*/) { if (!m_enableClipboard) { return; } - const IScreen::ClipboardInfo* info = + const auto* info = static_cast(event.getData()); // grab ownership @@ -669,7 +670,7 @@ Client::handleClipboardGrabbed(const Event& event, void*) } void -Client::handleHello(const Event&, void*) +Client::handleHello(const Event& /*unused*/, void* /*unused*/) { SInt16 major, minor; if (!ProtocolUtil::readf(m_stream, kMsgHello, &major, &minor)) { @@ -709,17 +710,17 @@ Client::handleHello(const Event&, void*) } void -Client::handleSuspend(const Event&, void*) +Client::handleSuspend(const Event& /*unused*/, void* /*unused*/) { LOG((CLOG_INFO "suspend")); m_suspended = true; bool wasConnected = isConnected(); - disconnect(NULL); + disconnect(nullptr); m_connectOnResume = wasConnected; } void -Client::handleResume(const Event&, void*) +Client::handleResume(const Event& /*unused*/, void* /*unused*/) { LOG((CLOG_INFO "resume")); m_suspended = false; @@ -730,13 +731,13 @@ Client::handleResume(const Event&, void*) } void -Client::handleFileChunkSending(const Event& event, void*) +Client::handleFileChunkSending(const Event& event, void* /*unused*/) { sendFileChunk(event.getData()); } void -Client::handleFileRecieveCompleted(const Event& event, void*) +Client::handleFileRecieveCompleted(const Event& /*event*/, void* /*unused*/) { onFileRecieveCompleted(); } @@ -752,13 +753,13 @@ Client::onFileRecieveCompleted() } void -Client::handleStopRetry(const Event&, void*) +Client::handleStopRetry(const Event& /*unused*/, void* /*unused*/) { m_args.m_restartable = false; } void -Client::writeToDropDirThread(void*) +Client::writeToDropDirThread(void* /*unused*/) { LOG((CLOG_DEBUG "starting write to drop dir thread")); @@ -773,13 +774,13 @@ Client::writeToDropDirThread(void*) void Client::dragInfoReceived(UInt32 fileNum, String data) { - // TODO: fix duplicate function from CServer + // TODO(andrew): fix duplicate function from CServer if (!m_args.m_enableDragDrop) { LOG((CLOG_DEBUG "drag drop not enabled, ignoring drag info.")); return; } - DragInformation::parseDragInfo(m_dragFileList, fileNum, data); + DragInformation::parseDragInfo(m_dragFileList, fileNum, std::move(data)); m_screen->startDraggingFiles(m_dragFileList); } @@ -793,7 +794,7 @@ Client::isReceivedFileSizeValid() void Client::sendFileToServer(const char* filename) { - if (m_sendFileThread != NULL) { + if (m_sendFileThread != nullptr) { StreamChunker::interruptFile(); } @@ -807,14 +808,14 @@ void Client::sendFileThread(void* filename) { try { - char* name = static_cast(filename); + auto* name = static_cast(filename); StreamChunker::sendFile(name, m_events, this); } catch (std::runtime_error& error) { LOG((CLOG_ERR "failed sending file chunks: %s", error.what())); } - m_sendFileThread = NULL; + m_sendFileThread = nullptr; } void diff --git a/src/lib/client/Client.h b/src/lib/client/Client.h index 9aae4f3c..cc5fccff 100644 --- a/src/lib/client/Client.h +++ b/src/lib/client/Client.h @@ -57,9 +57,9 @@ public: as its name and \p address as the server's address and \p factory to create the socket. \p screen is the local screen. */ - Client(IEventQueue* events, const String& name, + Client(IEventQueue* events, String name, const NetworkAddress& address, ISocketFactory* socketFactory, - synergy::Screen* screen, ClientArgs const& args); + synergy::Screen* screen, ClientArgs args); ~Client(); @@ -137,7 +137,7 @@ public: virtual void* getEventTarget() const; virtual bool getClipboard(ClipboardID id, IClipboard*) const; virtual void getShape(SInt32& x, SInt32& y, - SInt32& width, SInt32& height) const; + SInt32& w, SInt32& h) const; virtual void getCursorPos(SInt32& x, SInt32& y) const; // IClient overrides @@ -154,8 +154,8 @@ public: virtual void keyUp(KeyID, KeyModifierMask, KeyButton); virtual void mouseDown(ButtonID); virtual void mouseUp(ButtonID); - virtual void mouseMove(SInt32 xAbs, SInt32 yAbs); - virtual void mouseRelativeMove(SInt32 xRel, SInt32 yRel); + virtual void mouseMove(SInt32 x, SInt32 y); + virtual void mouseRelativeMove(SInt32 dx, SInt32 dy); virtual void mouseWheel(SInt32 xDelta, SInt32 yDelta); virtual void screensaver(bool activate); virtual void resetOptions(); @@ -209,12 +209,12 @@ private: bool m_active; bool m_suspended; bool m_connectOnResume; - bool m_ownClipboard[kClipboardEnd]; - bool m_sentClipboard[kClipboardEnd]; - IClipboard::Time m_timeClipboard[kClipboardEnd]; + bool m_ownClipboard[kClipboardEnd]{}; + bool m_sentClipboard[kClipboardEnd]{}; + IClipboard::Time m_timeClipboard[kClipboardEnd]{}; String m_dataClipboard[kClipboardEnd]; IEventQueue* m_events; - std::size_t m_expectedFileSize; + std::size_t m_expectedFileSize{}; String m_receivedFileData; DragFileList m_dragFileList; String m_dragFileExt; diff --git a/src/lib/client/ServerProxy.cpp b/src/lib/client/ServerProxy.cpp index f8b7c91b..77f607fe 100644 --- a/src/lib/client/ServerProxy.cpp +++ b/src/lib/client/ServerProxy.cpp @@ -18,19 +18,19 @@ #include "client/ServerProxy.h" +#include "base/IEventQueue.h" +#include "base/Log.h" +#include "base/TMethodEventJob.h" +#include "base/XBase.h" #include "client/Client.h" -#include "core/FileChunk.h" -#include "core/ClipboardChunk.h" -#include "core/StreamChunker.h" #include "core/Clipboard.h" +#include "core/ClipboardChunk.h" +#include "core/FileChunk.h" #include "core/ProtocolUtil.h" +#include "core/StreamChunker.h" #include "core/option_types.h" #include "core/protocol_types.h" #include "io/IStream.h" -#include "base/Log.h" -#include "base/IEventQueue.h" -#include "base/TMethodEventJob.h" -#include "base/XBase.h" #include @@ -50,7 +50,7 @@ ServerProxy::ServerProxy(Client* client, synergy::IStream* stream, IEventQueue* m_dyMouse(0), m_ignoreMouse(false), m_keepAliveAlarm(0.0), - m_keepAliveAlarmTimer(NULL), + m_keepAliveAlarmTimer(nullptr), m_parser(&ServerProxy::parseHandshakeMessage), m_events(events) { @@ -58,8 +58,9 @@ ServerProxy::ServerProxy(Client* client, synergy::IStream* stream, IEventQueue* assert(m_stream != NULL); // initialize modifier translation table - for (KeyModifierID id = 0; id < kKeyModifierIDLast; ++id) + for (KeyModifierID id = 0; id < kKeyModifierIDLast; ++id) { m_modifierTranslationTable[id] = id; +} // handle data on stream m_events->adoptHandler(m_events->forIStream().inputReady(), @@ -86,14 +87,14 @@ ServerProxy::~ServerProxy() void ServerProxy::resetKeepAliveAlarm() { - if (m_keepAliveAlarmTimer != NULL) { + if (m_keepAliveAlarmTimer != nullptr) { m_events->removeHandler(Event::kTimer, m_keepAliveAlarmTimer); m_events->deleteTimer(m_keepAliveAlarmTimer); - m_keepAliveAlarmTimer = NULL; + m_keepAliveAlarmTimer = nullptr; } if (m_keepAliveAlarm > 0.0) { m_keepAliveAlarmTimer = - m_events->newOneShotTimer(m_keepAliveAlarm, NULL); + m_events->newOneShotTimer(m_keepAliveAlarm, nullptr); m_events->adoptHandler(Event::kTimer, m_keepAliveAlarmTimer, new TMethodEventJob(this, &ServerProxy::handleKeepAliveAlarm)); @@ -108,7 +109,7 @@ ServerProxy::setKeepAliveRate(double rate) } void -ServerProxy::handleData(const Event&, void*) +ServerProxy::handleData(const Event& /*unused*/, void* /*unused*/) { // handle messages until there are no more. first read message code. UInt8 code[4]; @@ -179,7 +180,7 @@ ServerProxy::parseHandshakeMessage(const UInt8* code) else if (memcmp(code, kMsgCClose, 4) == 0) { // server wants us to hangup LOG((CLOG_DEBUG1 "recv close")); - m_client->disconnect(NULL); + m_client->disconnect(nullptr); return kDisconnect; } @@ -307,7 +308,7 @@ ServerProxy::parseMessage(const UInt8* code) else if (memcmp(code, kMsgCClose, 4) == 0) { // server wants us to hangup LOG((CLOG_DEBUG1 "recv close")); - m_client->disconnect(NULL); + m_client->disconnect(nullptr); return kDisconnect; } else if (memcmp(code, kMsgEBad, 4) == 0) { @@ -332,7 +333,7 @@ ServerProxy::parseMessage(const UInt8* code) } void -ServerProxy::handleKeepAliveAlarm(const Event&, void*) +ServerProxy::handleKeepAliveAlarm(const Event& /*unused*/, void* /*unused*/) { LOG((CLOG_NOTE "server is dead")); m_client->disconnect("server is not responding"); @@ -466,9 +467,9 @@ ServerProxy::translateKey(KeyID id) const if (id2 != kKeyModifierIDNull) { return s_translationTable[m_modifierTranslationTable[id2]][side]; } - else { + return id; - } + } KeyModifierMask @@ -605,8 +606,9 @@ ServerProxy::keyDown() KeyModifierMask mask2 = translateModifierMask( static_cast(mask)); if (id2 != static_cast(id) || - mask2 != static_cast(mask)) + mask2 != static_cast(mask)) { LOG((CLOG_DEBUG1 "key down translated to id=0x%08x, mask=0x%04x", id2, mask2)); +} // forward m_client->keyDown(id2, mask2, button); @@ -629,8 +631,9 @@ ServerProxy::keyRepeat() KeyModifierMask mask2 = translateModifierMask( static_cast(mask)); if (id2 != static_cast(id) || - mask2 != static_cast(mask)) + mask2 != static_cast(mask)) { LOG((CLOG_DEBUG1 "key repeat translated to id=0x%08x, mask=0x%04x", id2, mask2)); +} // forward m_client->keyRepeat(id2, mask2, count, button); @@ -652,8 +655,9 @@ ServerProxy::keyUp() KeyModifierMask mask2 = translateModifierMask( static_cast(mask)); if (id2 != static_cast(id) || - mask2 != static_cast(mask)) + mask2 != static_cast(mask)) { LOG((CLOG_DEBUG1 "key up translated to id=0x%08x, mask=0x%04x", id2, mask2)); +} // forward m_client->keyUp(id2, mask2, button); @@ -809,7 +813,7 @@ ServerProxy::setOptions() m_client->setOptions(options); // update modifier table - for (UInt32 i = 0, n = (UInt32)options.size(); i < n; i += 2) { + for (UInt32 i = 0, n = static_cast(options.size()); i < n; i += 2) { KeyModifierID id = kKeyModifierIDNull; if (options[i] == kOptionModifierMapForShift) { id = kKeyModifierIDShift; @@ -845,7 +849,7 @@ ServerProxy::setOptions() void ServerProxy::queryInfo() { - ClientInfo info; + ClientInfo info{}; m_client->getShape(info.m_x, info.m_y, info.m_w, info.m_h); m_client->getCursorPos(info.m_mx, info.m_my); sendInfo(info); @@ -870,7 +874,7 @@ ServerProxy::fileChunkReceived() m_events->addEvent(Event(m_events->forFile().fileRecieveCompleted(), m_client)); } else if (result == kStart) { - if (m_client->getDragFileList().size() > 0) { + if (!m_client->getDragFileList().empty()) { String filename = m_client->getDragFileList().at(0).getFilename(); LOG((CLOG_DEBUG "start receiving %s", filename.c_str())); } @@ -889,7 +893,7 @@ ServerProxy::dragInfoReceived() } void -ServerProxy::handleClipboardSendingEvent(const Event& event, void*) +ServerProxy::handleClipboardSendingEvent(const Event& event, void* /*unused*/) { ClipboardChunk::send(m_stream, event.getData()); } diff --git a/src/lib/client/ServerProxy.h b/src/lib/client/ServerProxy.h index 234894dd..50879dde 100644 --- a/src/lib/client/ServerProxy.h +++ b/src/lib/client/ServerProxy.h @@ -123,7 +123,7 @@ private: bool m_ignoreMouse; - KeyModifierID m_modifierTranslationTable[kKeyModifierIDLast]; + KeyModifierID m_modifierTranslationTable[kKeyModifierIDLast]{}; double m_keepAliveAlarm; EventQueueTimer* m_keepAliveAlarmTimer; diff --git a/src/lib/core/App.cpp b/src/lib/core/App.cpp index 06d0cd12..beeac81b 100644 --- a/src/lib/core/App.cpp +++ b/src/lib/core/App.cpp @@ -18,23 +18,23 @@ #include "core/App.h" -#include "base/Log.h" -#include "common/Version.h" -#include "core/protocol_types.h" #include "arch/Arch.h" -#include "base/XBase.h" #include "arch/XArch.h" -#include "base/log_outputters.h" -#include "core/XSynergy.h" -#include "core/ArgsBase.h" -#include "ipc/IpcServerProxy.h" -#include "base/TMethodEventJob.h" -#include "ipc/IpcMessage.h" -#include "ipc/Ipc.h" #include "base/EventQueue.h" +#include "base/Log.h" +#include "base/TMethodEventJob.h" +#include "base/XBase.h" +#include "base/log_outputters.h" +#include "common/Version.h" +#include "core/ArgsBase.h" +#include "core/XSynergy.h" +#include "core/protocol_types.h" +#include "ipc/Ipc.h" +#include "ipc/IpcMessage.h" +#include "ipc/IpcServerProxy.h" #include -#include +#include #if SYSAPI_WIN32 #include "arch/win32/ArchMiscWindows.h" @@ -137,7 +137,7 @@ App::run(int argc, char** argv) } int -App::daemonMainLoop(int, const char**) +App::daemonMainLoop(int /*unused*/, const char** /*unused*/) { #if SYSAPI_WIN32 SystemLogger sysLogger(daemonName(), false); @@ -150,7 +150,7 @@ App::daemonMainLoop(int, const char**) void App::setupFileLogging() { - if (argsBase().m_logFile != NULL) { + if (argsBase().m_logFile != nullptr) { m_fileLog = new FileLogOutputter(argsBase().m_logFile); CLOG->insert(m_fileLog); LOG((CLOG_DEBUG1 "logging to file (%s) enabled", argsBase().m_logFile)); @@ -161,7 +161,7 @@ void App::loggingFilterWarning() { if (CLOG->getFilter() > CLOG->getConsoleMaxLevel()) { - if (argsBase().m_logFile == NULL) { + if (argsBase().m_logFile == nullptr) { LOG((CLOG_WARN "log messages above %s are NOT sent to console (use file logging)", CLOG->getFilterName(CLOG->getConsoleMaxLevel()))); } @@ -179,7 +179,7 @@ App::initApp(int argc, const char** argv) // this is a simple way to allow the core process to talk to X. this avoids // the "WARNING: primary screen unavailable: unable to open screen" error. // a better way would be to use xauth cookie and dbus to get access to X. - if (!argsBase().m_runAsUid != -1) { + if (static_cast((!(argsBase().m_runAsUid) == 0 != -1))) { if (setuid(argsBase().m_runAsUid) == 0) { LOG((CLOG_DEBUG "process uid was set to: %d", argsBase().m_runAsUid)); } @@ -231,9 +231,9 @@ App::cleanupIpcClient() } void -App::handleIpcMessage(const Event& e, void*) +App::handleIpcMessage(const Event& e, void* /*unused*/) { - IpcMessage* m = static_cast(e.getDataObject()); + auto* m = dynamic_cast(e.getDataObject()); if (m->type() == kIpcShutdown) { LOG((CLOG_INFO "got ipc shutdown message")); m_events->addEvent(Event(Event::kQuit)); @@ -241,7 +241,7 @@ App::handleIpcMessage(const Event& e, void*) } void -App::runEventsLoop(void*) +App::runEventsLoop(void* /*unused*/) { m_events->loop(); @@ -257,24 +257,23 @@ App::runEventsLoop(void*) // MinimalApp::MinimalApp() : - App(NULL, new ArgsBase()) + App(nullptr, new ArgsBase()) { m_arch.init(); setEvents(m_events); } MinimalApp::~MinimalApp() -{ -} += default; int -MinimalApp::standardStartup(int argc, char** argv) +MinimalApp::standardStartup(int /*argc*/, char** /*argv*/) { return 0; } int -MinimalApp::runInner(int argc, char** argv, ILogOutputter* outputter, StartupFunc startup) +MinimalApp::runInner(int /*argc*/, char** /*argv*/, ILogOutputter* /*outputter*/, StartupFunc /*startup*/) { return 0; } @@ -291,7 +290,7 @@ MinimalApp::mainLoop() } int -MinimalApp::foregroundStartup(int argc, char** argv) +MinimalApp::foregroundStartup(int /*argc*/, char** /*argv*/) { return 0; } @@ -299,7 +298,7 @@ MinimalApp::foregroundStartup(int argc, char** argv) synergy::Screen* MinimalApp::createScreen() { - return NULL; + return nullptr; } void @@ -308,7 +307,7 @@ MinimalApp::loadConfig() } bool -MinimalApp::loadConfig(const String& pathname) +MinimalApp::loadConfig(const String& /*pathname*/) { return false; } @@ -326,6 +325,6 @@ MinimalApp::daemonName() const } void -MinimalApp::parseArgs(int argc, const char* const* argv) +MinimalApp::parseArgs(int /*argc*/, const char* const* /*argv*/) { } diff --git a/src/lib/core/AppUtil.cpp b/src/lib/core/AppUtil.cpp index 2b1ea47c..67bbe7ff 100644 --- a/src/lib/core/AppUtil.cpp +++ b/src/lib/core/AppUtil.cpp @@ -27,8 +27,7 @@ m_app(nullptr) } AppUtil::~AppUtil() -{ -} += default; void AppUtil::adoptApp(IApp* app) diff --git a/src/lib/core/ArgParser.cpp b/src/lib/core/ArgParser.cpp index a2e0475f..217474cd 100644 --- a/src/lib/core/ArgParser.cpp +++ b/src/lib/core/ArgParser.cpp @@ -17,20 +17,20 @@ #include "core/ArgParser.h" -#include "core/StreamChunker.h" -#include "core/App.h" -#include "core/ServerArgs.h" -#include "core/ClientArgs.h" -#include "core/ToolArgs.h" -#include "core/ArgsBase.h" #include "base/Log.h" #include "base/String.h" +#include "core/App.h" +#include "core/ArgsBase.h" +#include "core/ClientArgs.h" +#include "core/ServerArgs.h" +#include "core/StreamChunker.h" +#include "core/ToolArgs.h" #ifdef WINAPI_MSWINDOWS #include #endif -ArgsBase* ArgParser::m_argsBase = NULL; +ArgsBase* ArgParser::m_argsBase = nullptr; ArgParser::ArgParser(App* app) : m_app(app) @@ -47,7 +47,7 @@ ArgParser::parseServerArgs(ServerArgs& args, int argc, const char* const* argv) if (parsePlatformArg(args, argc, argv, i)) { continue; } - else if (parseGenericArgs(argc, argv, i)) { + if (parseGenericArgs(argc, argv, i)) { continue; } else if (parseDeprecatedArgs(argc, argv, i)) { @@ -70,11 +70,7 @@ ArgParser::parseServerArgs(ServerArgs& args, int argc, const char* const* argv) } } - if (checkUnexpectedArgs()) { - return false; - } - - return true; + return !checkUnexpectedArgs(); } bool @@ -88,19 +84,19 @@ ArgParser::parseClientArgs(ClientArgs& args, int argc, const char* const* argv) if (parsePlatformArg(args, argc, argv, i)) { continue; } - else if (parseGenericArgs(argc, argv, i)) { + if (parseGenericArgs(argc, argv, i)) { continue; } else if (parseDeprecatedArgs(argc, argv, i)) { continue; } - else if (isArg(i, argc, argv, NULL, "--camp")) { + else if (isArg(i, argc, argv, nullptr, "--camp")) { // ignore -- included for backwards compatibility } - else if (isArg(i, argc, argv, NULL, "--no-camp")) { + else if (isArg(i, argc, argv, nullptr, "--no-camp")) { // ignore -- included for backwards compatibility } - else if (isArg(i, argc, argv, NULL, "--yscroll", 1)) { + else if (isArg(i, argc, argv, nullptr, "--yscroll", 1)) { // define scroll args.m_yscroll = atoi(argv[++i]); } @@ -122,11 +118,7 @@ ArgParser::parseClientArgs(ClientArgs& args, int argc, const char* const* argv) return false; } - if (checkUnexpectedArgs()) { - return false; - } - - return true; + return !checkUnexpectedArgs(); } bool @@ -155,7 +147,7 @@ ArgParser::parsePlatformArg(ArgsBase& argsBase, const int& argc, const char* con argsBase.m_display = argv[++i]; } - else if (isArg(i, argc, argv, NULL, "--no-xinitthreads")) { + else if (isArg(i, argc, argv, nullptr, "--no-xinitthreads")) { argsBase.m_disableXInitThreads = true; } @@ -175,31 +167,31 @@ bool ArgParser::parseToolArgs(ToolArgs& args, int argc, const char* const* argv) { for (int i = 1; i < argc; ++i) { - if (isArg(i, argc, argv, NULL, "--get-active-desktop", 0)) { + if (isArg(i, argc, argv, nullptr, "--get-active-desktop", 0)) { args.m_printActiveDesktopName = true; return true; } - else if (isArg(i, argc, argv, NULL, "--login-auth", 0)) { + if (isArg(i, argc, argv, nullptr, "--login-auth", 0)) { args.m_loginAuthenticate = true; return true; } - else if (isArg(i, argc, argv, NULL, "--get-installed-dir", 0)) { + else if (isArg(i, argc, argv, nullptr, "--get-installed-dir", 0)) { args.m_getInstalledDir = true; return true; } - else if (isArg(i, argc, argv, NULL, "--get-profile-dir", 0)) { + else if (isArg(i, argc, argv, nullptr, "--get-profile-dir", 0)) { args.m_getProfileDir = true; return true; } - else if (isArg(i, argc, argv, NULL, "--get-arch", 0)) { + else if (isArg(i, argc, argv, nullptr, "--get-arch", 0)) { args.m_getArch = true; return true; } - else if (isArg(i, argc, argv, NULL, "--notify-activation", 0)) { + else if (isArg(i, argc, argv, nullptr, "--notify-activation", 0)) { args.m_notifyActivation = true; return true; } - else if (isArg(i, argc, argv, NULL, "--notify-update", 0)) { + else if (isArg(i, argc, argv, nullptr, "--notify-update", 0)) { args.m_notifyUpdate = true; return true; } @@ -225,7 +217,7 @@ ArgParser::parseGenericArgs(int argc, const char* const* argv, int& i) // not a daemon argsBase().m_daemon = false; } - else if (isArg(i, argc, argv, NULL, "--daemon")) { + else if (isArg(i, argc, argv, nullptr, "--daemon")) { // daemonize argsBase().m_daemon = true; } @@ -237,38 +229,38 @@ ArgParser::parseGenericArgs(int argc, const char* const* argv, int& i) // don't try to restart argsBase().m_restartable = false; } - else if (isArg(i, argc, argv, NULL, "--restart")) { + else if (isArg(i, argc, argv, nullptr, "--restart")) { // try to restart argsBase().m_restartable = true; } - else if (isArg(i, argc, argv, "-z", NULL)) { + else if (isArg(i, argc, argv, "-z", nullptr)) { argsBase().m_backend = true; } - else if (isArg(i, argc, argv, NULL, "--no-hooks")) { + else if (isArg(i, argc, argv, nullptr, "--no-hooks")) { argsBase().m_noHooks = true; } else if (isArg(i, argc, argv, "-h", "--help")) { - if (m_app) { + if (m_app != nullptr) { m_app->help(); } argsBase().m_shouldExit = true; } - else if (isArg(i, argc, argv, NULL, "--version")) { - if (m_app) { + else if (isArg(i, argc, argv, nullptr, "--version")) { + if (m_app != nullptr) { m_app->version(); } argsBase().m_shouldExit = true; } - else if (isArg(i, argc, argv, NULL, "--ipc")) { + else if (isArg(i, argc, argv, nullptr, "--ipc")) { argsBase().m_enableIpc = true; } - else if (isArg(i, argc, argv, NULL, "--server")) { + else if (isArg(i, argc, argv, nullptr, "--server")) { // supress error when --server is used } - else if (isArg(i, argc, argv, NULL, "--client")) { + else if (isArg(i, argc, argv, nullptr, "--client")) { // supress error when --client is used } - else if (isArg(i, argc, argv, NULL, "--enable-drag-drop")) { + else if (isArg(i, argc, argv, nullptr, "--enable-drag-drop")) { bool useDragDrop = true; #ifdef WINAPI_XWINDOWS @@ -290,18 +282,18 @@ ArgParser::parseGenericArgs(int argc, const char* const* argv, int& i) argsBase().m_enableDragDrop = true; } } - else if (isArg(i, argc, argv, NULL, "--enable-crypto")) { + else if (isArg(i, argc, argv, nullptr, "--enable-crypto")) { LOG((CLOG_INFO "--enable-crypto ignored, TLS is no longer supported in Synergy Core")); return false; } - else if (isArg(i, argc, argv, NULL, "--profile-dir", 1)) { + else if (isArg(i, argc, argv, nullptr, "--profile-dir", 1)) { argsBase().m_profileDirectory = argv[++i]; } - else if (isArg(i, argc, argv, NULL, "--plugin-dir", 1)) { + else if (isArg(i, argc, argv, nullptr, "--plugin-dir", 1)) { argsBase().m_pluginDirectory = argv[++i]; } #if WINAPI_XWINDOWS - else if (isArg(i, argc, argv, NULL, "--run-as-uid", 1)) { + else if (isArg(i, argc, argv, nullptr, "--run-as-uid", 1)) { argsBase().m_runAsUid = std::stoi(argv[++i]); } #endif @@ -316,27 +308,27 @@ ArgParser::parseGenericArgs(int argc, const char* const* argv, int& i) bool ArgParser::parseDeprecatedArgs(int argc, const char* const* argv, int& i) { - if (isArg(i, argc, argv, NULL, "--crypto-pass")) { + if (isArg(i, argc, argv, nullptr, "--crypto-pass")) { LOG((CLOG_NOTE "--crypto-pass is deprecated")); i++; return true; } - else if (isArg(i, argc, argv, NULL, "--res-w")) { + if (isArg(i, argc, argv, nullptr, "--res-w")) { LOG((CLOG_NOTE "--res-w is deprecated")); i++; return true; } - else if (isArg(i, argc, argv, NULL, "--res-h")) { + else if (isArg(i, argc, argv, nullptr, "--res-h")) { LOG((CLOG_NOTE "--res-h is deprecated")); i++; return true; } - else if (isArg(i, argc, argv, NULL, "--prm-wc")) { + else if (isArg(i, argc, argv, nullptr, "--prm-wc")) { LOG((CLOG_NOTE "--prm-wc is deprecated")); i++; return true; } - else if (isArg(i, argc, argv, NULL, "--prm-hc")) { + else if (isArg(i, argc, argv, nullptr, "--prm-hc")) { LOG((CLOG_NOTE "--prm-hc is deprecated")); i++; return true; @@ -351,8 +343,8 @@ ArgParser::isArg( const char* name1, const char* name2, int minRequiredParameters) { - if ((name1 != NULL && strcmp(argv[argi], name1) == 0) || - (name2 != NULL && strcmp(argv[argi], name2) == 0)) { + if ((name1 != nullptr && strcmp(argv[argi], name1) == 0) || + (name2 != nullptr && strcmp(argv[argi], name2) == 0)) { // match. check args left. if (argi + minRequiredParameters >= argc) { LOG((CLOG_PRINT "%s: missing arguments for `%s'" BYE, @@ -379,7 +371,7 @@ ArgParser::splitCommandString(String& command, std::vector& argv) searchDoubleQuotes(command, leftDoubleQuote, rightDoubleQuote); size_t startPos = 0; - size_t space = command.find(" ", startPos); + size_t space = command.find(' ', startPos); while (space != String::npos) { bool ignoreThisSpace = false; @@ -401,11 +393,11 @@ ArgParser::splitCommandString(String& command, std::vector& argv) // find next space if (ignoreThisSpace) { - space = command.find(" ", rightDoubleQuote + 1); + space = command.find(' ', rightDoubleQuote + 1); } else { startPos = space + 1; - space = command.find(" ", startPos); + space = command.find(' ', startPos); } } @@ -421,9 +413,9 @@ ArgParser::searchDoubleQuotes(String& command, size_t& left, size_t& right, size left = String::npos; right = String::npos; - left = command.find("\"", startPos); + left = command.find('\"', startPos); if (left != String::npos) { - right = command.find("\"", left + 1); + right = command.find('\"', left + 1); if (right != String::npos) { result = true; } @@ -456,7 +448,7 @@ ArgParser::getArgv(std::vector& argsArray) // we use the c string pointers from argsArray and assign // them to the inner array. So caller only need to use // delete[] to delete the outer array - const char** argv = new const char*[argc]; + const auto** argv = new const char*[argc]; for (size_t i = 0; i < argc; i++) { argv[i] = argsArray[i].c_str(); @@ -466,12 +458,12 @@ ArgParser::getArgv(std::vector& argsArray) } String -ArgParser::assembleCommand(std::vector& argsArray, String ignoreArg, int parametersRequired) +ArgParser::assembleCommand(std::vector& argsArray, const String& ignoreArg, int parametersRequired) { String result; - for (std::vector::iterator it = argsArray.begin(); it != argsArray.end(); ++it) { - if (it->compare(ignoreArg) == 0) { + for (auto it = argsArray.begin(); it != argsArray.end(); ++it) { + if (*it == ignoreArg) { it = it + parametersRequired; continue; } diff --git a/src/lib/core/ArgParser.h b/src/lib/core/ArgParser.h index 4fc8a263..e2846df4 100644 --- a/src/lib/core/ArgParser.h +++ b/src/lib/core/ArgParser.h @@ -48,7 +48,7 @@ public: static void removeDoubleQuotes(String& arg); static const char** getArgv(std::vector& argsArray); static String assembleCommand(std::vector& argsArray, - String ignoreArg = "", int parametersRequired = 0); + const String& ignoreArg = "", int parametersRequired = 0); private: void updateCommonArgs(const char* const* argv); diff --git a/src/lib/core/ArgsBase.cpp b/src/lib/core/ArgsBase.cpp index ee5bf35c..083c30af 100644 --- a/src/lib/core/ArgsBase.cpp +++ b/src/lib/core/ArgsBase.cpp @@ -34,19 +34,17 @@ m_runAsUid(-1), m_backend(false), m_restartable(true), m_noHooks(false), -m_pname(NULL), -m_logFilter(NULL), -m_logFile(NULL), -m_display(NULL), +m_pname(nullptr), +m_logFilter(nullptr), +m_logFile(nullptr), +m_display(nullptr), m_enableIpc(false), m_enableDragDrop(false), m_shouldExit(false), -m_synergyAddress(), m_profileDirectory(""), m_pluginDirectory("") { } ArgsBase::~ArgsBase() -{ -} += default; diff --git a/src/lib/core/ClientApp.cpp b/src/lib/core/ClientApp.cpp index 79bc74c8..d34cfea2 100644 --- a/src/lib/core/ClientApp.cpp +++ b/src/lib/core/ClientApp.cpp @@ -18,28 +18,28 @@ #include "core/ClientApp.h" +#include "arch/Arch.h" +#include "arch/IArchTaskBarReceiver.h" +#include "base/Event.h" +#include "base/EventQueue.h" +#include "base/IEventQueue.h" +#include "base/Log.h" +#include "base/String.h" +#include "base/TMethodEventJob.h" +#include "base/TMethodJob.h" +#include "base/log_outputters.h" #include "client/Client.h" +#include "common/Version.h" #include "core/ArgParser.h" -#include "core/protocol_types.h" +#include "core/ClientArgs.h" #include "core/Screen.h" #include "core/XScreen.h" -#include "core/ClientArgs.h" -#include "net/NetworkAddress.h" -#include "net/TCPSocketFactory.h" -#include "net/SocketMultiplexer.h" -#include "net/XSocket.h" +#include "core/protocol_types.h" #include "mt/Thread.h" -#include "arch/IArchTaskBarReceiver.h" -#include "arch/Arch.h" -#include "base/String.h" -#include "base/Event.h" -#include "base/IEventQueue.h" -#include "base/TMethodEventJob.h" -#include "base/log_outputters.h" -#include "base/EventQueue.h" -#include "base/TMethodJob.h" -#include "base/Log.h" -#include "common/Version.h" +#include "net/NetworkAddress.h" +#include "net/SocketMultiplexer.h" +#include "net/TCPSocketFactory.h" +#include "net/XSocket.h" #if SYSAPI_WIN32 #include "arch/win32/ArchMiscWindows.h" @@ -58,21 +58,20 @@ #endif #include -#include +#include #define RETRY_TIME 1.0 ClientApp::ClientApp(IEventQueue* events) : App(events, new ClientArgs()), - m_client(NULL), - m_clientScreen(NULL), - m_serverAddress(NULL) + m_client(nullptr), + m_clientScreen(nullptr), + m_serverAddress(nullptr) { } ClientApp::~ClientApp() -{ -} += default; void ClientApp::parseArgs(int argc, const char* const* argv) @@ -192,7 +191,7 @@ ClientApp::updateStatus() void -ClientApp::updateStatus(const String& msg) +ClientApp::updateStatus(const String& /*msg*/) { } @@ -229,7 +228,7 @@ ClientApp::nextRestartTimeout() void -ClientApp::handleScreenError(const Event&, void*) +ClientApp::handleScreenError(const Event& /*unused*/, void* /*unused*/) { LOG((CLOG_CRIT "error on screen")); m_events->addEvent(Event(Event::kQuit)); @@ -252,7 +251,7 @@ ClientApp::openClientScreen() void ClientApp::closeClientScreen(synergy::Screen* screen) { - if (screen != NULL) { + if (screen != nullptr) { m_events->removeHandler(m_events->forIScreen().error(), screen->getEventTarget()); delete screen; @@ -261,10 +260,10 @@ ClientApp::closeClientScreen(synergy::Screen* screen) void -ClientApp::handleClientRestart(const Event&, void* vtimer) +ClientApp::handleClientRestart(const Event& /*unused*/, void* vtimer) { // discard old timer - EventQueueTimer* timer = static_cast(vtimer); + auto* timer = static_cast(vtimer); m_events->deleteTimer(timer); m_events->removeHandler(Event::kTimer, timer); @@ -278,14 +277,14 @@ ClientApp::scheduleClientRestart(double retryTime) { // install a timer and handler to retry later LOG((CLOG_DEBUG "retry in %.0f seconds", retryTime)); - EventQueueTimer* timer = m_events->newOneShotTimer(retryTime, NULL); + EventQueueTimer* timer = m_events->newOneShotTimer(retryTime, nullptr); m_events->adoptHandler(Event::kTimer, timer, new TMethodEventJob(this, &ClientApp::handleClientRestart, timer)); } void -ClientApp::handleClientConnected(const Event&, void*) +ClientApp::handleClientConnected(const Event& /*unused*/, void* /*unused*/) { LOG((CLOG_NOTE "connected to server")); resetRestartTimeout(); @@ -294,9 +293,9 @@ ClientApp::handleClientConnected(const Event&, void*) void -ClientApp::handleClientFailed(const Event& e, void*) +ClientApp::handleClientFailed(const Event& e, void* /*unused*/) { - Client::FailInfo* info = + auto* info = static_cast(e.getData()); updateStatus(String("Failed to connect to server: ") + info->m_what); @@ -315,7 +314,7 @@ ClientApp::handleClientFailed(const Event& e, void*) void -ClientApp::handleClientDisconnected(const Event&, void*) +ClientApp::handleClientDisconnected(const Event& /*unused*/, void* /*unused*/) { LOG((CLOG_NOTE "disconnected from server")); if (!args().m_restartable) { @@ -331,7 +330,7 @@ Client* ClientApp::openClient(const String& name, const NetworkAddress& address, synergy::Screen* screen) { - Client* client = new Client( + auto* client = new Client( m_events, name, address, @@ -367,7 +366,7 @@ ClientApp::openClient(const String& name, const NetworkAddress& address, void ClientApp::closeClient(Client* client) { - if (client == NULL) { + if (client == nullptr) { return; } @@ -390,9 +389,9 @@ bool ClientApp::startClient() { double retryTime; - synergy::Screen* clientScreen = NULL; + synergy::Screen* clientScreen = nullptr; try { - if (m_clientScreen == NULL) { + if (m_clientScreen == nullptr) { clientScreen = openClientScreen(); m_client = openClient(args().m_name, *m_serverAddress, clientScreen); @@ -426,10 +425,10 @@ ClientApp::startClient() scheduleClientRestart(retryTime); return true; } - else { + // don't try again return false; - } + } @@ -438,8 +437,8 @@ ClientApp::stopClient() { closeClient(m_client); closeClientScreen(m_clientScreen); - m_client = NULL; - m_clientScreen = NULL; + m_client = nullptr; + m_clientScreen = nullptr; } @@ -513,9 +512,9 @@ ClientApp::standardStartup(int argc, char** argv) if (args().m_daemon) { return ARCH->daemonize(daemonName(), &daemonMainLoopStatic); } - else { + return mainLoop(); - } + } int @@ -526,7 +525,7 @@ ClientApp::runInner(int argc, char** argv, ILogOutputter* outputter, StartupFunc args().m_pname = ARCH->getBasename(argv[0]); // install caller's output filter - if (outputter != NULL) { + if (outputter != nullptr) { CLOG->insert(outputter); } diff --git a/src/lib/core/ClientTaskBarReceiver.cpp b/src/lib/core/ClientTaskBarReceiver.cpp index ae6368c4..1a41039c 100644 --- a/src/lib/core/ClientTaskBarReceiver.cpp +++ b/src/lib/core/ClientTaskBarReceiver.cpp @@ -17,12 +17,12 @@ */ #include "core/ClientTaskBarReceiver.h" -#include "client/Client.h" -#include "mt/Lock.h" -#include "base/String.h" -#include "base/IEventQueue.h" #include "arch/Arch.h" +#include "base/IEventQueue.h" +#include "base/String.h" +#include "client/Client.h" #include "common/Version.h" +#include "mt/Lock.h" // // ClientTaskBarReceiver @@ -46,7 +46,7 @@ ClientTaskBarReceiver::updateStatus(Client* client, const String& errorMsg) { // update our status m_errorMessage = errorMsg; - if (client == NULL) { + if (client == nullptr) { if (m_errorMessage.empty()) { m_state = kNotRunning; } @@ -95,7 +95,7 @@ ClientTaskBarReceiver::quit() } void -ClientTaskBarReceiver::onStatusChanged(Client*) +ClientTaskBarReceiver::onStatusChanged(Client* /*unused*/) { // do nothing } diff --git a/src/lib/core/Clipboard.h b/src/lib/core/Clipboard.h index 4aeeeb2e..3fee898a 100644 --- a/src/lib/core/Clipboard.h +++ b/src/lib/core/Clipboard.h @@ -63,9 +63,9 @@ public: private: mutable bool m_open; - mutable Time m_time; + mutable Time m_time{}; bool m_owner; - Time m_timeOwned; - bool m_added[kNumFormats]; + Time m_timeOwned{}; + bool m_added[kNumFormats]{}; String m_data[kNumFormats]; }; diff --git a/src/lib/core/ClipboardChunk.cpp b/src/lib/core/ClipboardChunk.cpp index 054e38f5..fedfbf37 100644 --- a/src/lib/core/ClipboardChunk.cpp +++ b/src/lib/core/ClipboardChunk.cpp @@ -17,10 +17,10 @@ #include "core/ClipboardChunk.h" +#include "base/Log.h" #include "core/ProtocolUtil.h" #include "core/protocol_types.h" #include "io/IStream.h" -#include "base/Log.h" #include size_t ClipboardChunk::s_expectedSize = 0; @@ -38,7 +38,7 @@ ClipboardChunk::start( const String& size) { size_t sizeLength = size.size(); - ClipboardChunk* start = new ClipboardChunk(sizeLength + CLIPBOARD_CHUNK_META_SIZE); + auto* start = new ClipboardChunk(sizeLength + CLIPBOARD_CHUNK_META_SIZE); char* chunk = start->m_chunk; chunk[0] = id; @@ -57,7 +57,7 @@ ClipboardChunk::data( const String& data) { size_t dataSize = data.size(); - ClipboardChunk* chunk = new ClipboardChunk(dataSize + CLIPBOARD_CHUNK_META_SIZE); + auto* chunk = new ClipboardChunk(dataSize + CLIPBOARD_CHUNK_META_SIZE); char* chunkData = chunk->m_chunk; chunkData[0] = id; @@ -72,7 +72,7 @@ ClipboardChunk::data( ClipboardChunk* ClipboardChunk::end(ClipboardID id, UInt32 sequence) { - ClipboardChunk* end = new ClipboardChunk(CLIPBOARD_CHUNK_META_SIZE); + auto* end = new ClipboardChunk(CLIPBOARD_CHUNK_META_SIZE); char* chunk = end->m_chunk; chunk[0] = id; @@ -102,7 +102,7 @@ ClipboardChunk::assemble(synergy::IStream* stream, dataCached.clear(); return kStart; } - else if (mark == kDataChunk) { + if (mark == kDataChunk) { dataCached.append(data); return kNotFinish; } @@ -111,7 +111,7 @@ ClipboardChunk::assemble(synergy::IStream* stream, if (id >= kClipboardEnd) { return kError; } - else if (s_expectedSize != dataCached.size()) { + if (s_expectedSize != dataCached.size()) { LOG((CLOG_ERR "corrupted clipboard data, expected size=%d actual size=%d", s_expectedSize, dataCached.size())); return kError; } @@ -125,7 +125,7 @@ ClipboardChunk::assemble(synergy::IStream* stream, void ClipboardChunk::send(synergy::IStream* stream, void* data) { - ClipboardChunk* clipboardData = static_cast(data); + auto* clipboardData = static_cast(data); LOG((CLOG_DEBUG1 "sending clipboard chunk")); diff --git a/src/lib/core/DaemonApp.cpp b/src/lib/core/DaemonApp.cpp index 6351fb32..701537d5 100644 --- a/src/lib/core/DaemonApp.cpp +++ b/src/lib/core/DaemonApp.cpp @@ -16,26 +16,26 @@ * along with this program. If not, see . */ -// TODO: split this class into windows and unix to get rid +// TODO(andrew): split this class into windows and unix to get rid // of all the #ifdefs! #include "core/DaemonApp.h" +#include "arch/XArch.h" +#include "base/EventQueue.h" +#include "base/Log.h" +#include "base/Log.h" +#include "base/TMethodEventJob.h" +#include "base/TMethodJob.h" +#include "base/log_outputters.h" #include "core/App.h" #include "core/ArgParser.h" -#include "core/ServerArgs.h" #include "core/ClientArgs.h" +#include "core/ServerArgs.h" #include "ipc/IpcClientProxy.h" -#include "ipc/IpcMessage.h" #include "ipc/IpcLogOutputter.h" +#include "ipc/IpcMessage.h" #include "net/SocketMultiplexer.h" -#include "arch/XArch.h" -#include "base/Log.h" -#include "base/TMethodJob.h" -#include "base/TMethodEventJob.h" -#include "base/EventQueue.h" -#include "base/log_outputters.h" -#include "base/Log.h" #if SYSAPI_WIN32 @@ -52,13 +52,13 @@ #endif -#include #include #include +#include using namespace std; -DaemonApp* DaemonApp::s_instance = NULL; +DaemonApp* DaemonApp::s_instance = nullptr; int mainLoopStatic() @@ -68,7 +68,7 @@ mainLoopStatic() } int -unixMainLoopStatic(int, const char**) +unixMainLoopStatic(int /*unused*/, const char** /*unused*/) { return mainLoopStatic(); } @@ -94,8 +94,7 @@ DaemonApp::DaemonApp() : } DaemonApp::~DaemonApp() -{ -} += default; int DaemonApp::run(int argc, char** argv) @@ -122,8 +121,9 @@ DaemonApp::run(int argc, char** argv) // default log level to system setting. string logLevel = arch.setting("LogLevel"); - if (logLevel != "") + if (!logLevel.empty()) { log.setFilter(logLevel.c_str()); +} bool foreground = false; @@ -170,7 +170,7 @@ DaemonApp::run(int argc, char** argv) catch (XArch& e) { String message = e.what(); if (uninstall && (message.find("The service has not been started") != String::npos)) { - // TODO: if we're keeping this use error code instead (what is it?!). + // TODO(andrew): if we're keeping this use error code instead (what is it?!). // HACK: this message happens intermittently, not sure where from but // it's quite misleading for the user. they thing something has gone // horribly wrong, but it's just the service manager reporting a false @@ -288,12 +288,12 @@ DaemonApp::logFilename() } void -DaemonApp::handleIpcMessage(const Event& e, void*) +DaemonApp::handleIpcMessage(const Event& e, void* /*unused*/) { - IpcMessage* m = static_cast(e.getDataObject()); + auto* m = dynamic_cast(e.getDataObject()); switch (m->type()) { case kIpcCommand: { - IpcCommandMessage* cm = static_cast(m); + auto* cm = dynamic_cast(m); String command = cm->command(); // if empty quotes, clear. @@ -306,13 +306,13 @@ DaemonApp::handleIpcMessage(const Event& e, void*) std::vector argsArray; ArgParser::splitCommandString(command, argsArray); - ArgParser argParser(NULL); + ArgParser argParser(nullptr); const char** argv = argParser.getArgv(argsArray); ServerArgs serverArgs; ClientArgs clientArgs; - int argc = static_cast(argsArray.size()); - bool server = argsArray[0].find("synergys") != String::npos ? true : false; - ArgsBase* argBase = NULL; + auto argc = static_cast(argsArray.size()); + bool server = argsArray[0].find("synergys") != String::npos; + ArgsBase* argBase = nullptr; if (server) { argParser.parseServerArgs(serverArgs, argc, argv); @@ -364,7 +364,7 @@ DaemonApp::handleIpcMessage(const Event& e, void*) // next starts. ARCH->setting("Command", command); - // TODO: it would be nice to store bools/ints... + // TODO(andrew): it would be nice to store bools/ints... ARCH->setting("Elevate", String(cm->elevate() ? "1" : "0")); } catch (XArch& e) { @@ -381,7 +381,7 @@ DaemonApp::handleIpcMessage(const Event& e, void*) } case kIpcHello: - IpcHelloMessage* hm = static_cast(m); + auto* hm = dynamic_cast(m); String type; switch (hm->clientType()) { case kIpcClientGui: type = "gui"; break; diff --git a/src/lib/core/DragInformation.cpp b/src/lib/core/DragInformation.cpp index 6af1719d..e6bc4c6a 100644 --- a/src/lib/core/DragInformation.cpp +++ b/src/lib/core/DragInformation.cpp @@ -25,20 +25,19 @@ using namespace std; DragInformation::DragInformation() : - m_filename(), m_filesize(0) { } void -DragInformation::parseDragInfo(DragFileList& dragFileList, UInt32 fileNum, String data) +DragInformation::parseDragInfo(DragFileList& dragFileList, UInt32 fileNum, const String& data) { size_t startPos = 0; size_t findResult1 = 0; size_t findResult2 = 0; dragFileList.clear(); String slash("\\"); - if (data.find("/", startPos) != string::npos) { + if (data.find('/', startPos) != string::npos) { slash = "/"; } @@ -48,7 +47,7 @@ DragInformation::parseDragInfo(DragFileList& dragFileList, UInt32 fileNum, Strin findResult2 = data.find_last_of(slash, findResult1); if (findResult1 == startPos) { - //TODO: file number does not match, something goes wrong + // TODO(andrew): file number does not match, something goes wrong break; } @@ -86,22 +85,22 @@ DragInformation::parseDragInfo(DragFileList& dragFileList, UInt32 fileNum, Strin } String -DragInformation::getDragFileExtension(String filename) +DragInformation::getDragFileExtension(const String& filename) { size_t findResult = string::npos; - findResult = filename.find_last_of(".", filename.size()); + findResult = filename.find_last_of('.', filename.size()); if (findResult != string::npos) { return filename.substr(findResult + 1, filename.size() - findResult - 1); } - else { + return ""; - } + } int DragInformation::setupDragInfo(DragFileList& fileList, String& output) { - int size = static_cast(fileList.size()); + auto size = static_cast(fileList.size()); for (int i = 0; i < size; ++i) { output.append(fileList.at(i).getFilename()); output.append(","); @@ -113,7 +112,7 @@ DragInformation::setupDragInfo(DragFileList& fileList, String& output) } bool -DragInformation::isFileValid(String filename) +DragInformation::isFileValid(const String& filename) { bool result = false; std::fstream file(filename.c_str(), ios::in|ios::binary); @@ -130,7 +129,7 @@ DragInformation::isFileValid(String filename) size_t DragInformation::stringToNum(String& str) { - istringstream iss(str.c_str()); + istringstream iss(str); size_t size; iss >> size; return size; @@ -147,7 +146,7 @@ DragInformation::getFileSize(String& filename) // check file size file.seekg (0, std::ios::end); - size_t size = (size_t)file.tellg(); + auto size = (size_t)file.tellg(); stringstream ss; ss << size; diff --git a/src/lib/core/DragInformation.h b/src/lib/core/DragInformation.h index 470146ce..7c69dfd7 100644 --- a/src/lib/core/DragInformation.h +++ b/src/lib/core/DragInformation.h @@ -34,14 +34,14 @@ public: size_t getFilesize() { return m_filesize; } void setFilesize(size_t size) { m_filesize = size; } - static void parseDragInfo(DragFileList& dragFileList, UInt32 fileNum, String data); - static String getDragFileExtension(String filename); + static void parseDragInfo(DragFileList& dragFileList, UInt32 fileNum, const String& data); + static String getDragFileExtension(const String& filename); // helper function to setup drag info // example: filename1,filesize1,filename2,filesize2, // return file count static int setupDragInfo(DragFileList& fileList, String& output); - static bool isFileValid(String filename); + static bool isFileValid(const String& filename); private: static size_t stringToNum(String& str); diff --git a/src/lib/core/DropHelper.cpp b/src/lib/core/DropHelper.cpp index 164ed8e0..271933d6 100644 --- a/src/lib/core/DropHelper.cpp +++ b/src/lib/core/DropHelper.cpp @@ -26,7 +26,7 @@ DropHelper::writeToDir(const String& destination, DragFileList& fileList, String { LOG((CLOG_DEBUG "dropping file, files=%i target=%s", fileList.size(), destination.c_str())); - if (!destination.empty() && fileList.size() > 0) { + if (!destination.empty() && !fileList.empty()) { std::fstream file; String dropTarget = destination; #ifdef SYSAPI_WIN32 diff --git a/src/lib/core/FileChunk.cpp b/src/lib/core/FileChunk.cpp index 0a86bd22..04f31501 100644 --- a/src/lib/core/FileChunk.cpp +++ b/src/lib/core/FileChunk.cpp @@ -17,11 +17,11 @@ #include "core/FileChunk.h" +#include "base/Log.h" +#include "base/Stopwatch.h" #include "core/ProtocolUtil.h" #include "core/protocol_types.h" #include "io/IStream.h" -#include "base/Stopwatch.h" -#include "base/Log.h" static const UInt16 kIntervalThreshold = 1; @@ -35,7 +35,7 @@ FileChunk* FileChunk::start(const String& size) { size_t sizeLength = size.size(); - FileChunk* start = new FileChunk(sizeLength + FILE_CHUNK_META_SIZE); + auto* start = new FileChunk(sizeLength + FILE_CHUNK_META_SIZE); char* chunk = start->m_chunk; chunk[0] = kDataStart; memcpy(&chunk[1], size.c_str(), sizeLength); @@ -47,7 +47,7 @@ FileChunk::start(const String& size) FileChunk* FileChunk::data(UInt8* data, size_t dataSize) { - FileChunk* chunk = new FileChunk(dataSize + FILE_CHUNK_META_SIZE); + auto* chunk = new FileChunk(dataSize + FILE_CHUNK_META_SIZE); char* chunkData = chunk->m_chunk; chunkData[0] = kDataChunk; memcpy(&chunkData[1], data, dataSize); @@ -59,7 +59,7 @@ FileChunk::data(UInt8* data, size_t dataSize) FileChunk* FileChunk::end() { - FileChunk* end = new FileChunk(FILE_CHUNK_META_SIZE); + auto* end = new FileChunk(FILE_CHUNK_META_SIZE); char* chunk = end->m_chunk; chunk[0] = kDataEnd; chunk[1] = '\0'; diff --git a/src/lib/core/FileChunk.h b/src/lib/core/FileChunk.h index 0637e2b7..d63d017c 100644 --- a/src/lib/core/FileChunk.h +++ b/src/lib/core/FileChunk.h @@ -36,7 +36,7 @@ public: static FileChunk* end(); static int assemble( synergy::IStream* stream, - String& dataCached, + String& dataReceived, size_t& expectedSize); static void send( synergy::IStream* stream, diff --git a/src/lib/core/IClipboard.cpp b/src/lib/core/IClipboard.cpp index 63439875..15d8ee1d 100644 --- a/src/lib/core/IClipboard.cpp +++ b/src/lib/core/IClipboard.cpp @@ -41,7 +41,7 @@ IClipboard::unmarshall(IClipboard* clipboard, const String& data, Time time) // read each format for (UInt32 i = 0; i < numFormats; ++i) { // get the format id - IClipboard::EFormat format = + auto format = static_cast(readUInt32(index)); index += 4; @@ -90,7 +90,7 @@ IClipboard::marshall(const IClipboard* clipboard) ++numFormats; formatData[format] = clipboard->get(static_cast(format)); - size += 4 + 4 + (UInt32)formatData[format].size(); + size += 4 + 4 + static_cast(formatData[format].size()); } } @@ -102,7 +102,7 @@ IClipboard::marshall(const IClipboard* clipboard) for (UInt32 format = 0; format != IClipboard::kNumFormats; ++format) { if (clipboard->has(static_cast(format))) { writeUInt32(&data, format); - writeUInt32(&data, (UInt32)formatData[format].size()); + writeUInt32(&data, static_cast(formatData[format].size())); data += formatData[format]; } } @@ -133,7 +133,7 @@ IClipboard::copy(IClipboard* dst, const IClipboard* src, Time time) if (dst->empty()) { for (SInt32 format = 0; format != IClipboard::kNumFormats; ++format) { - IClipboard::EFormat eFormat = (IClipboard::EFormat)format; + auto eFormat = static_cast(format); if (src->has(eFormat)) { dst->add(eFormat, src->get(eFormat)); } @@ -151,7 +151,7 @@ IClipboard::copy(IClipboard* dst, const IClipboard* src, Time time) UInt32 IClipboard::readUInt32(const char* buf) { - const unsigned char* ubuf = reinterpret_cast(buf); + const auto* ubuf = reinterpret_cast(buf); return (static_cast(ubuf[0]) << 24) | (static_cast(ubuf[1]) << 16) | (static_cast(ubuf[2]) << 8) | diff --git a/src/lib/core/IKeyState.cpp b/src/lib/core/IKeyState.cpp index cd0c0c39..52fbb13c 100644 --- a/src/lib/core/IKeyState.cpp +++ b/src/lib/core/IKeyState.cpp @@ -19,14 +19,14 @@ #include "core/IKeyState.h" #include "base/EventQueue.h" -#include #include +#include // // IKeyState // -IKeyState::IKeyState(IEventQueue* events) +IKeyState::IKeyState(IEventQueue* /*events*/) { } @@ -38,12 +38,12 @@ IKeyState::KeyInfo* IKeyState::KeyInfo::alloc(KeyID id, KeyModifierMask mask, KeyButton button, SInt32 count) { - KeyInfo* info = (KeyInfo*)malloc(sizeof(KeyInfo)); + auto* info = static_cast(malloc(sizeof(KeyInfo))); info->m_key = id; info->m_mask = mask; info->m_button = button; info->m_count = count; - info->m_screens = NULL; + info->m_screens = nullptr; info->m_screensBuffer[0] = '\0'; return info; } @@ -56,7 +56,7 @@ IKeyState::KeyInfo::alloc(KeyID id, String screens = join(destinations); // build structure - KeyInfo* info = (KeyInfo*)malloc(sizeof(KeyInfo) + screens.size()); + auto* info = static_cast(malloc(sizeof(KeyInfo) + screens.size())); info->m_key = id; info->m_mask = mask; info->m_button = button; @@ -69,13 +69,13 @@ IKeyState::KeyInfo::alloc(KeyID id, IKeyState::KeyInfo* IKeyState::KeyInfo::alloc(const KeyInfo& x) { - KeyInfo* info = (KeyInfo*)malloc(sizeof(KeyInfo) + - strlen(x.m_screensBuffer)); + auto* info = static_cast(malloc(sizeof(KeyInfo) + + strlen(x.m_screensBuffer))); info->m_key = x.m_key; info->m_mask = x.m_mask; info->m_button = x.m_button; info->m_count = x.m_count; - info->m_screens = x.m_screens ? info->m_screensBuffer : NULL; + info->m_screens = x.m_screens != nullptr ? info->m_screensBuffer : nullptr; strcpy(info->m_screensBuffer, x.m_screensBuffer); return info; } @@ -83,7 +83,7 @@ IKeyState::KeyInfo::alloc(const KeyInfo& x) bool IKeyState::KeyInfo::isDefault(const char* screens) { - return (screens == NULL || screens[0] == '\0'); + return (screens == nullptr || screens[0] == '\0'); } bool @@ -103,7 +103,7 @@ IKeyState::KeyInfo::contains(const char* screens, const String& name) match += ":"; match += name; match += ":"; - return (strstr(screens, match.c_str()) != NULL); + return (strstr(screens, match.c_str()) != nullptr); } bool @@ -123,19 +123,18 @@ IKeyState::KeyInfo::join(const std::set& destinations) // which makes searching easy. the string is empty if there are no // destinations and "*" means all destinations. String screens; - for (std::set::const_iterator i = destinations.begin(); - i != destinations.end(); ++i) { - if (*i == "*") { + for (const auto & destination : destinations) { + if (destination == "*") { screens = "*"; break; } - else { + if (screens.empty()) { screens = ":"; } - screens += *i; + screens += destination; screens += ":"; - } + } return screens; } diff --git a/src/lib/core/IPlatformScreen.cpp b/src/lib/core/IPlatformScreen.cpp index a794d86b..f5d1a607 100644 --- a/src/lib/core/IPlatformScreen.cpp +++ b/src/lib/core/IPlatformScreen.cpp @@ -18,7 +18,7 @@ #include "core/IPlatformScreen.h" bool -IPlatformScreen::fakeMediaKey(KeyID id) +IPlatformScreen::fakeMediaKey(KeyID /*id*/) { return false; } diff --git a/src/lib/core/IPrimaryScreen.cpp b/src/lib/core/IPrimaryScreen.cpp index a29e2638..317ea828 100644 --- a/src/lib/core/IPrimaryScreen.cpp +++ b/src/lib/core/IPrimaryScreen.cpp @@ -28,7 +28,7 @@ IPrimaryScreen::ButtonInfo* IPrimaryScreen::ButtonInfo::alloc(ButtonID id, KeyModifierMask mask) { - ButtonInfo* info = (ButtonInfo*)malloc(sizeof(ButtonInfo)); + auto* info = static_cast(malloc(sizeof(ButtonInfo))); info->m_button = id; info->m_mask = mask; return info; @@ -37,7 +37,7 @@ IPrimaryScreen::ButtonInfo::alloc(ButtonID id, KeyModifierMask mask) IPrimaryScreen::ButtonInfo* IPrimaryScreen::ButtonInfo::alloc(const ButtonInfo& x) { - ButtonInfo* info = (ButtonInfo*)malloc(sizeof(ButtonInfo)); + auto* info = static_cast(malloc(sizeof(ButtonInfo))); info->m_button = x.m_button; info->m_mask = x.m_mask; return info; @@ -57,7 +57,7 @@ IPrimaryScreen::ButtonInfo::equal(const ButtonInfo* a, const ButtonInfo* b) IPrimaryScreen::MotionInfo* IPrimaryScreen::MotionInfo::alloc(SInt32 x, SInt32 y) { - MotionInfo* info = (MotionInfo*)malloc(sizeof(MotionInfo)); + auto* info = static_cast(malloc(sizeof(MotionInfo))); info->m_x = x; info->m_y = y; return info; @@ -71,7 +71,7 @@ IPrimaryScreen::MotionInfo::alloc(SInt32 x, SInt32 y) IPrimaryScreen::WheelInfo* IPrimaryScreen::WheelInfo::alloc(SInt32 xDelta, SInt32 yDelta) { - WheelInfo* info = (WheelInfo*)malloc(sizeof(WheelInfo)); + auto* info = static_cast(malloc(sizeof(WheelInfo))); info->m_xDelta = xDelta; info->m_yDelta = yDelta; return info; @@ -85,7 +85,7 @@ IPrimaryScreen::WheelInfo::alloc(SInt32 xDelta, SInt32 yDelta) IPrimaryScreen::HotKeyInfo* IPrimaryScreen::HotKeyInfo::alloc(UInt32 id) { - HotKeyInfo* info = (HotKeyInfo*)malloc(sizeof(HotKeyInfo)); + auto* info = static_cast(malloc(sizeof(HotKeyInfo))); info->m_id = id; return info; } diff --git a/src/lib/core/KeyMap.cpp b/src/lib/core/KeyMap.cpp index e091eac0..43081745 100644 --- a/src/lib/core/KeyMap.cpp +++ b/src/lib/core/KeyMap.cpp @@ -17,19 +17,19 @@ */ #include "core/KeyMap.h" -#include "core/key_types.h" #include "base/Log.h" +#include "core/key_types.h" -#include +#include #include #include namespace synergy { -KeyMap::NameToKeyMap* KeyMap::s_nameToKeyMap = NULL; -KeyMap::NameToModifierMap* KeyMap::s_nameToModifierMap = NULL; -KeyMap::KeyToNameMap* KeyMap::s_keyToNameMap = NULL; -KeyMap::ModifierToNameMap* KeyMap::s_modifierToNameMap = NULL; +KeyMap::NameToKeyMap* KeyMap::s_nameToKeyMap = nullptr; +KeyMap::NameToModifierMap* KeyMap::s_nameToModifierMap = nullptr; +KeyMap::KeyToNameMap* KeyMap::s_keyToNameMap = nullptr; +KeyMap::ModifierToNameMap* KeyMap::s_modifierToNameMap = nullptr; KeyMap::KeyMap() : m_numGroups(0), @@ -97,8 +97,8 @@ KeyMap::addKeyEntry(const KeyItem& item) // see if we already have this item; just return if so KeyEntryList& entries = groupTable[item.m_group]; - for (size_t i = 0, n = entries.size(); i < n; ++i) { - if (entries[i].size() == 1 && newItem == entries[i][0]) { + for (auto & entrie : entries) { + if (entrie.size() == 1 && newItem == entrie[0]) { return; } } @@ -118,7 +118,7 @@ KeyMap::addKeyAliasEntry(KeyID targetID, SInt32 group, { // if we can already generate the target as desired then we're done. if (findCompatibleKey(targetID, group, targetRequired, - targetSensitive) != NULL) { + targetSensitive) != nullptr) { return; } @@ -128,7 +128,7 @@ KeyMap::addKeyAliasEntry(KeyID targetID, SInt32 group, const KeyItemList* sourceEntry = findCompatibleKey(sourceID, eg, sourceRequired, sourceSensitive); - if (sourceEntry != NULL && sourceEntry->size() == 1) { + if (sourceEntry != nullptr && sourceEntry->size() == 1) { KeyMap::KeyItem targetItem = sourceEntry->back(); targetItem.m_id = targetID; targetItem.m_group = eg; @@ -173,17 +173,17 @@ KeyMap::addKeyCombinationEntry(KeyID id, SInt32 group, // groups for keys, otherwise search just the given group. SInt32 n = 1; if (m_composeAcrossGroups) { - n = (SInt32)groupTable.size(); + n = static_cast(groupTable.size()); } bool found = false; for (SInt32 gd = 0; gd < n && !found; ++gd) { SInt32 eg = (group + gd) % getNumGroups(); const KeyEntryList& entries = groupTable[eg]; - for (size_t j = 0; j < entries.size(); ++j) { - if (entries[j].size() == 1) { + for (const auto & entrie : entries) { + if (entrie.size() == 1) { found = true; - items.push_back(entries[j][0]); + items.push_back(entrie[0]); break; } } @@ -229,9 +229,8 @@ KeyMap::finish() m_numGroups = findNumGroups(); // make sure every key has the same number of groups - for (KeyIDMap::iterator i = m_keyIDMap.begin(); - i != m_keyIDMap.end(); ++i) { - i->second.resize(m_numGroups); + for (auto & i : m_keyIDMap) { + i.second.resize(m_numGroups); } // compute keys that generate each modifier @@ -241,16 +240,14 @@ KeyMap::finish() void KeyMap::foreachKey(ForeachKeyCallback cb, void* userData) { - for (KeyIDMap::iterator i = m_keyIDMap.begin(); - i != m_keyIDMap.end(); ++i) { - KeyGroupTable& groupTable = i->second; + for (auto & i : m_keyIDMap) { + KeyGroupTable& groupTable = i.second; for (size_t group = 0; group < groupTable.size(); ++group) { KeyEntryList& entryList = groupTable[group]; - for (size_t j = 0; j < entryList.size(); ++j) { - KeyItemList& itemList = entryList[j]; - for (size_t k = 0; k < itemList.size(); ++k) { - (*cb)(i->first, static_cast(group), - itemList[k], userData); + for (auto & itemList : entryList) { + for (auto & k : itemList) { + (*cb)(i.first, static_cast(group), + k, userData); } } } @@ -268,12 +265,12 @@ KeyMap::mapKey(Keystrokes& keys, KeyID id, SInt32 group, // handle group change if (id == kKeyNextGroup) { - keys.push_back(Keystroke(1, false, false)); - return NULL; + keys.emplace_back(1, false, false); + return nullptr; } - else if (id == kKeyPrevGroup) { - keys.push_back(Keystroke(-1, false, false)); - return NULL; + if (id == kKeyPrevGroup) { + keys.emplace_back(-1, false, false); + return nullptr; } const KeyItem* item; @@ -300,7 +297,7 @@ KeyMap::mapKey(Keystrokes& keys, KeyID id, SInt32 group, if (!keysForModifierState(0, group, activeModifiers, currentState, desiredMask, desiredMask, 0, keys)) { LOG((CLOG_DEBUG1 "unable to set modifiers %04x", desiredMask)); - return NULL; + return nullptr; } return &m_modifierKeyItem; @@ -309,7 +306,7 @@ KeyMap::mapKey(Keystrokes& keys, KeyID id, SInt32 group, currentState & ~desiredMask, desiredMask, 0, keys)) { LOG((CLOG_DEBUG1 "unable to clear modifiers %04x", desiredMask)); - return NULL; + return nullptr; } return &m_modifierKeyItem; @@ -325,7 +322,7 @@ KeyMap::mapKey(Keystrokes& keys, KeyID id, SInt32 group, break; } - if (item != NULL) { + if (item != nullptr) { LOG((CLOG_DEBUG1 "mapped to %03x, new state %04x", item->m_button, currentState)); } return item; @@ -349,21 +346,21 @@ KeyMap::findCompatibleKey(KeyID id, SInt32 group, { assert(group >= 0 && group < getNumGroups()); - KeyIDMap::const_iterator i = m_keyIDMap.find(id); + auto i = m_keyIDMap.find(id); if (i == m_keyIDMap.end()) { - return NULL; + return nullptr; } const KeyEntryList& entries = i->second[group]; - for (size_t j = 0; j < entries.size(); ++j) { - if ((entries[j].back().m_sensitive & sensitive) == 0 || - (entries[j].back().m_required & sensitive) == + for (const auto & entrie : entries) { + if ((entrie.back().m_sensitive & sensitive) == 0 || + (entrie.back().m_required & sensitive) == (required & sensitive)) { - return &entries[j]; + return &entrie; } } - return NULL; + return nullptr; } bool @@ -395,9 +392,8 @@ void KeyMap::collectButtons(const ModifierToKeys& mods, ButtonToKeyMap& keys) { keys.clear(); - for (ModifierToKeys::const_iterator i = mods.begin(); - i != mods.end(); ++i) { - keys.insert(std::make_pair(i->second.m_button, &i->second)); + for (const auto & mod : mods) { + keys.insert(std::make_pair(mod.second.m_button, &mod.second)); } } @@ -461,10 +457,9 @@ SInt32 KeyMap::findNumGroups() const { size_t max = 0; - for (KeyIDMap::const_iterator i = m_keyIDMap.begin(); - i != m_keyIDMap.end(); ++i) { - if (i->second.size() > max) { - max = i->second.size(); + for (const auto & i : m_keyIDMap) { + if (i.second.size() > max) { + max = i.second.size(); } } return static_cast(max); @@ -480,14 +475,14 @@ KeyMap::setModifierKeys() const KeyGroupTable& groupTable = i->second; for (size_t g = 0; g < groupTable.size(); ++g) { const KeyEntryList& entries = groupTable[g]; - for (size_t j = 0; j < entries.size(); ++j) { + for (const auto & entrie : entries) { // skip multi-key sequences - if (entries[j].size() != 1) { + if (entrie.size() != 1) { continue; } // skip keys that don't generate a modifier - const KeyItem& item = entries[j].back(); + const KeyItem& item = entrie.back(); if (item.m_generates == 0) { continue; } @@ -496,7 +491,7 @@ KeyMap::setModifierKeys() for (SInt32 b = 0; b < kKeyModifierNumBits; ++b) { // skip if item doesn't generate bit b if (((1u << b) & item.m_generates) != 0) { - SInt32 mIndex = (SInt32)g * kKeyModifierNumBits + b; + SInt32 mIndex = static_cast(g) * kKeyModifierNumBits + b; m_modifierKeys[mIndex].push_back(&item); } } @@ -515,22 +510,22 @@ KeyMap::mapCommandKey(Keystrokes& keys, KeyID id, SInt32 group, static const KeyModifierMask s_overrideModifiers = 0xffffu; // find KeySym in table - KeyIDMap::const_iterator i = m_keyIDMap.find(id); + auto i = m_keyIDMap.find(id); if (i == m_keyIDMap.end()) { // unknown key LOG((CLOG_DEBUG1 "key %04x is not on keyboard", id)); - return NULL; + return nullptr; } const KeyGroupTable& keyGroupTable = i->second; // find the first key that generates this KeyID - const KeyItem* keyItem = NULL; + const KeyItem* keyItem = nullptr; SInt32 numGroups = getNumGroups(); for (SInt32 groupOffset = 0; groupOffset < numGroups; ++groupOffset) { SInt32 effectiveGroup = getEffectiveGroup(group, groupOffset); const KeyEntryList& entryList = keyGroupTable[effectiveGroup]; - for (size_t i = 0; i < entryList.size(); ++i) { - if (entryList[i].size() != 1) { + for (const auto & i : entryList) { + if (i.size() != 1) { // ignore multikey entries continue; } @@ -540,7 +535,7 @@ KeyMap::mapCommandKey(Keystrokes& keys, KeyID id, SInt32 group, // after the right button not the right character. // we'll use desiredMask as-is, overriding the key's required // modifiers, when synthesizing this button. - const KeyItem& item = entryList[i].back(); + const KeyItem& item = i.back(); KeyModifierMask desiredShiftMask = KeyModifierShift & desiredMask; KeyModifierMask requiredIgnoreShiftMask = item.m_required & ~KeyModifierShift; if ((item.m_required & desiredShiftMask) == (item.m_sensitive & desiredShiftMask) && @@ -550,14 +545,14 @@ KeyMap::mapCommandKey(Keystrokes& keys, KeyID id, SInt32 group, break; } } - if (keyItem != NULL) { + if (keyItem != nullptr) { break; } } - if (keyItem == NULL) { + if (keyItem == nullptr) { // no mapping for this keysym LOG((CLOG_DEBUG1 "no mapping for key %04x", id)); - return NULL; + return nullptr; } // make working copy of modifiers @@ -575,7 +570,7 @@ KeyMap::mapCommandKey(Keystrokes& keys, KeyID id, SInt32 group, s_overrideModifiers, isAutoRepeat, keys)) { LOG((CLOG_DEBUG1 "can't map key")); keys.clear(); - return NULL; + return nullptr; } // add keystrokes to restore modifier keys @@ -583,12 +578,12 @@ KeyMap::mapCommandKey(Keystrokes& keys, KeyID id, SInt32 group, activeModifiers, keys)) { LOG((CLOG_DEBUG1 "failed to restore modifiers")); keys.clear(); - return NULL; + return nullptr; } // add keystrokes to restore group if (newGroup != group) { - keys.push_back(Keystroke(group, true, true)); + keys.emplace_back(group, true, true); } // save new modifiers @@ -606,11 +601,11 @@ KeyMap::mapCharacterKey(Keystrokes& keys, KeyID id, SInt32 group, bool isAutoRepeat) const { // find KeySym in table - KeyIDMap::const_iterator i = m_keyIDMap.find(id); + auto i = m_keyIDMap.find(id); if (i == m_keyIDMap.end()) { // unknown key LOG((CLOG_DEBUG1 "key %04x is not on keyboard", id)); - return NULL; + return nullptr; } const KeyGroupTable& keyGroupTable = i->second; @@ -631,14 +626,14 @@ KeyMap::mapCharacterKey(Keystrokes& keys, KeyID id, SInt32 group, if (keyIndex == -1) { // no mapping for this keysym LOG((CLOG_DEBUG1 "no mapping for key %04x", id)); - return NULL; + return nullptr; } // get keys to press for key SInt32 effectiveGroup = getEffectiveGroup(group, groupOffset); const KeyItemList& itemList = keyGroupTable[effectiveGroup][keyIndex]; if (itemList.empty()) { - return NULL; + return nullptr; } const KeyItem& keyItem = itemList.back(); @@ -648,13 +643,13 @@ KeyMap::mapCharacterKey(Keystrokes& keys, KeyID id, SInt32 group, SInt32 newGroup = group; // add each key - for (size_t j = 0; j < itemList.size(); ++j) { - if (!keysForKeyItem(itemList[j], newGroup, newModifiers, + for (const auto & j : itemList) { + if (!keysForKeyItem(j, newGroup, newModifiers, newState, desiredMask, 0, isAutoRepeat, keys)) { LOG((CLOG_DEBUG1 "can't map key")); keys.clear(); - return NULL; + return nullptr; } } @@ -663,12 +658,12 @@ KeyMap::mapCharacterKey(Keystrokes& keys, KeyID id, SInt32 group, activeModifiers, keys)) { LOG((CLOG_DEBUG1 "failed to restore modifiers")); keys.clear(); - return NULL; + return nullptr; } // add keystrokes to restore group if (newGroup != group) { - keys.push_back(Keystroke(group, true, true)); + keys.emplace_back(group, true, true); } // save new modifiers @@ -695,7 +690,7 @@ KeyMap::findBestKey(const KeyEntryList& entryList, KeyModifierMask desiredState) const { // check for an item that can accommodate the desiredState exactly - for (SInt32 i = 0; i < (SInt32)entryList.size(); ++i) { + for (SInt32 i = 0; i < static_cast(entryList.size()); ++i) { const KeyItem& item = entryList[i].back(); if ((item.m_required & desiredState) == item.m_required && (item.m_required & desiredState) == (item.m_sensitive & desiredState)) { @@ -707,7 +702,7 @@ KeyMap::findBestKey(const KeyEntryList& entryList, // choose the item that requires the fewest modifier changes SInt32 bestCount = 32; SInt32 bestIndex = -1; - for (SInt32 i = 0; i < (SInt32)entryList.size(); ++i) { + for (SInt32 i = 0; i < static_cast(entryList.size()); ++i) { const KeyItem& item = entryList[i].back(); KeyModifierMask change = ((item.m_required ^ desiredState) & item.m_sensitive); @@ -740,13 +735,12 @@ KeyMap::keyForModifier(KeyButton button, SInt32 group, // must use the other shift button to do the shifting. const ModifierKeyItemList& items = m_modifierKeys[group * kKeyModifierNumBits + modifierBit]; - for (ModifierKeyItemList::const_iterator i = items.begin(); - i != items.end(); ++i) { - if ((*i)->m_button != button) { - return (*i); + for (auto item : items) { + if (item->m_button != button) { + return item; } } - return NULL; + return nullptr; } bool @@ -763,7 +757,7 @@ KeyMap::keysForKeyItem(const KeyItem& keyItem, SInt32& group, // add keystrokes to adjust the group if (group != keyItem.m_group) { group = keyItem.m_group; - keystrokes.push_back(Keystroke(group, true, false)); + keystrokes.emplace_back(group, true, false); } EKeystroke type; @@ -823,7 +817,7 @@ KeyMap::keysForKeyItem(const KeyItem& keyItem, SInt32& group, } bool -KeyMap::keysToRestoreModifiers(const KeyItem& keyItem, SInt32, +KeyMap::keysToRestoreModifiers(const KeyItem& keyItem, SInt32 /*unused*/, ModifierToKeys& activeModifiers, KeyModifierMask& currentState, const ModifierToKeys& desiredModifiers, @@ -853,15 +847,14 @@ KeyMap::keysToRestoreModifiers(const KeyItem& keyItem, SInt32, } // press wanted keys - for (ModifierToKeys::const_iterator i = desiredModifiers.begin(); - i != desiredModifiers.end(); ++i) { - KeyButton button = i->second.m_button; + for (const auto & desiredModifier : desiredModifiers) { + KeyButton button = desiredModifier.second.m_button; if (button != keyItem.m_button && oldKeys.count(button) == 0) { EKeystroke type = kKeystrokePress; - if (i->second.m_lock) { + if (desiredModifier.second.m_lock) { type = kKeystrokeModify; } - addKeystrokes(type, i->second, + addKeystrokes(type, desiredModifier.second, activeModifiers, currentState, keystrokes); } } @@ -908,14 +901,14 @@ KeyMap::keysForModifierState(KeyButton button, SInt32 group, // get the KeyItem for the modifier in the group const KeyItem* keyItem = keyForModifier(button, group, bit); - if (keyItem == NULL) { + if (keyItem == nullptr) { if ((mask & notRequiredMask) == 0) { LOG((CLOG_DEBUG1 "no key for modifier %04x", mask)); return false; } - else { + continue; - } + } // if this modifier is sensitive to modifiers then adjust those @@ -940,7 +933,7 @@ KeyMap::keysForModifierState(KeyButton button, SInt32 group, notRequiredMask, keystrokes)) { return false; } - else if (!active) { + if (!active) { // release the modifier // XXX -- this doesn't work! if Alt and Meta are mapped // to one key and we want to release Meta we can't do @@ -974,7 +967,7 @@ KeyMap::addKeystrokes(EKeystroke type, const KeyItem& keyItem, UInt32 data = keyItem.m_client; switch (type) { case kKeystrokePress: - keystrokes.push_back(Keystroke(button, true, false, data)); + keystrokes.emplace_back(button, true, false, data); if (keyItem.m_generates != 0) { if (!keyItem.m_lock || (currentState & keyItem.m_generates) == 0) { // add modifier key and activate modifier @@ -991,13 +984,13 @@ KeyMap::addKeystrokes(EKeystroke type, const KeyItem& keyItem, break; case kKeystrokeRelease: - keystrokes.push_back(Keystroke(button, false, false, data)); + keystrokes.emplace_back(button, false, false, data); if (keyItem.m_generates != 0 && !keyItem.m_lock) { // remove key from active modifiers std::pair range = activeModifiers.equal_range(keyItem.m_generates); - for (ModifierToKeys::iterator i = range.first; + for (auto i = range.first; i != range.second; ++i) { if (i->second.m_button == button) { activeModifiers.erase(i); @@ -1013,14 +1006,14 @@ KeyMap::addKeystrokes(EKeystroke type, const KeyItem& keyItem, break; case kKeystrokeRepeat: - keystrokes.push_back(Keystroke(button, false, true, data)); - keystrokes.push_back(Keystroke(button, true, true, data)); + keystrokes.emplace_back(button, false, true, data); + keystrokes.emplace_back(button, true, true, data); // no modifier changes on key repeat break; case kKeystrokeClick: - keystrokes.push_back(Keystroke(button, true, false, data)); - keystrokes.push_back(Keystroke(button, false, false, data)); + keystrokes.emplace_back(button, true, false, data); + keystrokes.emplace_back(button, false, false, data); // no modifier changes on key click break; @@ -1031,22 +1024,22 @@ KeyMap::addKeystrokes(EKeystroke type, const KeyItem& keyItem, if (m_halfDuplex.count(button) > 0) { if (type == kKeystrokeModify) { // turn half-duplex toggle on (press) - keystrokes.push_back(Keystroke(button, true, false, data)); + keystrokes.emplace_back(button, true, false, data); } else { // turn half-duplex toggle off (release) - keystrokes.push_back(Keystroke(button, false, false, data)); + keystrokes.emplace_back(button, false, false, data); } } else { // toggle (click) - keystrokes.push_back(Keystroke(button, true, false, data)); - keystrokes.push_back(Keystroke(button, false, false, data)); + keystrokes.emplace_back(button, true, false, data); + keystrokes.emplace_back(button, false, false, data); } } else if (type == kKeystrokeModify) { // press modifier - keystrokes.push_back(Keystroke(button, true, false, data)); + keystrokes.emplace_back(button, true, false, data); } else { // release all the keys that generate the modifier that are @@ -1054,10 +1047,10 @@ KeyMap::addKeystrokes(EKeystroke type, const KeyItem& keyItem, std::pair range = activeModifiers.equal_range(keyItem.m_generates); - for (ModifierToKeys::const_iterator i = range.first; + for (auto i = range.first; i != range.second; ++i) { - keystrokes.push_back(Keystroke(i->second.m_button, - false, false, i->second.m_client)); + keystrokes.emplace_back(i->second.m_button, + false, false, i->second.m_client); } } @@ -1170,7 +1163,7 @@ KeyMap::formatKey(KeyID key, KeyModifierMask mask) } // XXX -- we're assuming ASCII here else if (key >= 33 && key < 127) { - x += (char)key; + x += static_cast(key); } else { x += synergy::string::sprintf("\\u%04x", key); @@ -1196,16 +1189,16 @@ KeyMap::parseKey(const String& x, KeyID& key) } // XXX -- we're assuming ASCII encoding here else if (x.size() == 1) { - if (!isgraph(x[0])) { + if (isgraph(x[0]) == 0) { // unknown key return false; } - key = (KeyID)x[0]; + key = static_cast(x[0]); } else if (x.size() == 6 && x[0] == '\\' && x[1] == 'u') { // escaped unicode (\uXXXX where XXXX is a hex number) char* end; - key = (KeyID)strtol(x.c_str() + 2, &end, 16); + key = static_cast(strtol(x.c_str() + 2, &end, 16)); if (*end != '\0') { return false; } @@ -1280,19 +1273,19 @@ void KeyMap::initKeyNameMaps() { // initialize tables - if (s_nameToKeyMap == NULL) { + if (s_nameToKeyMap == nullptr) { s_nameToKeyMap = new NameToKeyMap; s_keyToNameMap = new KeyToNameMap; - for (const KeyNameMapEntry* i = kKeyNameMap; i->m_name != NULL; ++i) { + for (const KeyNameMapEntry* i = kKeyNameMap; i->m_name != nullptr; ++i) { (*s_nameToKeyMap)[i->m_name] = i->m_id; (*s_keyToNameMap)[i->m_id] = i->m_name; } } - if (s_nameToModifierMap == NULL) { + if (s_nameToModifierMap == nullptr) { s_nameToModifierMap = new NameToModifierMap; s_modifierToNameMap = new ModifierToNameMap; for (const KeyModifierNameMapEntry* i = kModifierNameMap; - i->m_name != NULL; ++i) { + i->m_name != nullptr; ++i) { (*s_nameToModifierMap)[i->m_name] = i->m_mask; (*s_modifierToNameMap)[i->m_mask] = i->m_name; } @@ -1341,4 +1334,4 @@ KeyMap::Keystroke::Keystroke(SInt32 group, bool absolute, bool restore) : m_data.m_group.m_restore = restore; } -} +} // namespace synergy diff --git a/src/lib/core/KeyMap.h b/src/lib/core/KeyMap.h index 574d48ce..7f63e82a 100644 --- a/src/lib/core/KeyMap.h +++ b/src/lib/core/KeyMap.h @@ -82,7 +82,7 @@ public: kGroup //!< Set new group }; - Keystroke(KeyButton, bool press, bool repeat, UInt32 clientData); + Keystroke(KeyButton, bool press, bool repeat, UInt32 data); Keystroke(SInt32 group, bool absolute, bool restore); public: @@ -106,7 +106,7 @@ public: }; EType m_type; - Data m_data; + Data m_data{}; }; //! A sequence of keystrokes @@ -278,7 +278,7 @@ public: /*! Put all the keys in \p modifiers into \p keys. */ - static void collectButtons(const ModifierToKeys& modifiers, + static void collectButtons(const ModifierToKeys& mods, ButtonToKeyMap& keys); //! Set modifier key state @@ -500,7 +500,7 @@ private: KeySet m_halfDuplexMods; // half-duplex set by user // dummy KeyItem for changing modifiers - KeyItem m_modifierKeyItem; + KeyItem m_modifierKeyItem{}; // parsing/formatting tables static NameToKeyMap* s_nameToKeyMap; diff --git a/src/lib/core/KeyState.cpp b/src/lib/core/KeyState.cpp index e72e7631..bcf9eff3 100644 --- a/src/lib/core/KeyState.cpp +++ b/src/lib/core/KeyState.cpp @@ -19,12 +19,12 @@ #include "core/KeyState.h" #include "base/Log.h" -#include #include +#include #include #include -static const KeyButton kButtonMask = (KeyButton)(IKeyState::kNumButtons - 1); +static const KeyButton kButtonMask = static_cast(IKeyState::kNumButtons - 1); static const KeyID s_decomposeTable[] = { // spacing version of dead keys @@ -395,7 +395,7 @@ KeyState::KeyState(IEventQueue* events) : KeyState::KeyState(IEventQueue* events, synergy::KeyMap& keyMap) : IKeyState(events), - m_keyMapPtr(0), + m_keyMapPtr(nullptr), m_keyMap(keyMap), m_mask(0), m_events(events) @@ -405,8 +405,7 @@ KeyState::KeyState(IEventQueue* events, synergy::KeyMap& keyMap) : KeyState::~KeyState() { - if (m_keyMapPtr) - delete m_keyMapPtr; + delete m_keyMapPtr; } void @@ -503,9 +502,8 @@ KeyState::updateKeyState() // get the current keyboard state KeyButtonSet keysDown; pollPressedKeys(keysDown); - for (KeyButtonSet::const_iterator i = keysDown.begin(); - i != keysDown.end(); ++i) { - m_keys[*i] = 1; + for (unsigned short i : keysDown) { + m_keys[i] = 1; } // get the current modifier state @@ -520,10 +518,10 @@ KeyState::updateKeyState() } void -KeyState::addActiveModifierCB(KeyID, SInt32 group, +KeyState::addActiveModifierCB(KeyID /*unused*/, SInt32 group, synergy::KeyMap::KeyItem& keyItem, void* vcontext) { - AddActiveModifierContext* context = + auto* context = static_cast(vcontext); if (group == context->m_activeGroup && (keyItem.m_generates & context->m_mask) != 0) { @@ -570,7 +568,7 @@ KeyState::fakeKeyDown(KeyID id, KeyModifierMask mask, KeyButton serverID) const synergy::KeyMap::KeyItem* keyItem = m_keyMap.mapKey(keys, id, pollActiveGroup(), m_activeModifiers, getActiveModifiersRValue(), mask, false); - if (keyItem == NULL) { + if (keyItem == nullptr) { // a media key won't be mapped on mac, so we need to fake it in a // special way if (id == kKeyAudioDown || id == kKeyAudioUp || @@ -585,7 +583,7 @@ KeyState::fakeKeyDown(KeyID id, KeyModifierMask mask, KeyButton serverID) return; } - KeyButton localID = (KeyButton)(keyItem->m_button & kButtonMask); + auto localID = static_cast(keyItem->m_button & kButtonMask); updateModifierKeyState(localID, oldActiveModifiers, m_activeModifiers); if (localID != 0) { // note keys down @@ -618,10 +616,10 @@ KeyState::fakeKeyRepeat( const synergy::KeyMap::KeyItem* keyItem = m_keyMap.mapKey(keys, id, pollActiveGroup(), m_activeModifiers, getActiveModifiersRValue(), mask, true); - if (keyItem == NULL) { + if (keyItem == nullptr) { return false; } - KeyButton localID = (KeyButton)(keyItem->m_button & kButtonMask); + auto localID = static_cast(keyItem->m_button & kButtonMask); if (localID == 0) { return false; } @@ -635,11 +633,10 @@ KeyState::fakeKeyRepeat( if (localID != oldLocalID) { // replace key up with previous KeyButton but leave key down // alone so it uses the new KeyButton. - for (Keystrokes::iterator index = keys.begin(); - index != keys.end(); ++index) { - if (index->m_type == Keystroke::kButton && - index->m_data.m_button.m_button == localID) { - index->m_data.m_button.m_button = oldLocalID; + for (auto & key : keys) { + if (key.m_type == Keystroke::kButton && + key.m_data.m_button.m_button == localID) { + key.m_data.m_button.m_button = oldLocalID; break; } } @@ -672,7 +669,7 @@ KeyState::fakeKeyUp(KeyButton serverID) // get the sequence of keys to simulate key release Keystrokes keys; - keys.push_back(Keystroke(localID, false, false, m_keyClientData[localID])); + keys.emplace_back(localID, false, false, m_keyClientData[localID]); // note keys down --m_keys[localID]; @@ -680,13 +677,13 @@ KeyState::fakeKeyUp(KeyButton serverID) m_serverKeys[serverID] = 0; // check if this is a modifier - ModifierToKeys::iterator i = m_activeModifiers.begin(); + auto i = m_activeModifiers.begin(); while (i != m_activeModifiers.end()) { if (i->second.m_button == localID && !i->second.m_lock) { // modifier is no longer down KeyModifierMask mask = i->first; - ModifierToKeys::iterator tmp = i; + auto tmp = i; ++i; m_activeModifiers.erase(tmp); @@ -712,7 +709,7 @@ KeyState::fakeAllKeysUp() Keystrokes keys; for (KeyButton i = 0; i < IKeyState::kNumButtons; ++i) { if (m_syntheticKeys[i] > 0) { - keys.push_back(Keystroke(i, false, false, m_keyClientData[i])); + keys.emplace_back(i, false, false, m_keyClientData[i]); m_keys[i] = 0; m_syntheticKeys[i] = 0; } @@ -724,7 +721,7 @@ KeyState::fakeAllKeysUp() } bool -KeyState::fakeMediaKey(KeyID id) +KeyState::fakeMediaKey(KeyID /*id*/) { return false; } @@ -754,7 +751,7 @@ KeyState::getEffectiveGroup(SInt32 group, SInt32 offset) const } bool -KeyState::isIgnoredKey(KeyID key, KeyModifierMask) const +KeyState::isIgnoredKey(KeyID key, KeyModifierMask /*unused*/) const { switch (key) { case kKeyCapsLock: @@ -772,12 +769,12 @@ KeyState::getButton(KeyID id, SInt32 group) const { const synergy::KeyMap::KeyItemList* items = m_keyMap.findCompatibleKey(id, group, 0, 0); - if (items == NULL) { + if (items == nullptr) { return 0; } - else { + return items->back().m_button; - } + } void @@ -849,11 +846,11 @@ KeyState::fakeKeys(const Keystrokes& keys, UInt32 count) // generate key events LOG((CLOG_DEBUG1 "keystrokes:")); - for (Keystrokes::const_iterator k = keys.begin(); k != keys.end(); ) { + for (auto k = keys.begin(); k != keys.end(); ) { if (k->m_type == Keystroke::kButton && k->m_data.m_button.m_repeat) { // repeat from here up to but not including the next key // with m_repeat == false count times. - Keystrokes::const_iterator start = k; + auto start = k; while (count-- > 0) { // send repeating events for (k = start; k != keys.end() && @@ -883,13 +880,11 @@ KeyState::updateModifierKeyState(KeyButton button, { // get the pressed modifier buttons before and after synergy::KeyMap::ButtonToKeyMap oldKeys, newKeys; - for (ModifierToKeys::const_iterator i = oldModifiers.begin(); - i != oldModifiers.end(); ++i) { - oldKeys.insert(std::make_pair(i->second.m_button, &i->second)); + for (const auto & oldModifier : oldModifiers) { + oldKeys.insert(std::make_pair(oldModifier.second.m_button, &oldModifier.second)); } - for (ModifierToKeys::const_iterator i = newModifiers.begin(); - i != newModifiers.end(); ++i) { - newKeys.insert(std::make_pair(i->second.m_button, &i->second)); + for (const auto & newModifier : newModifiers) { + newKeys.insert(std::make_pair(newModifier.second.m_button, &newModifier.second)); } // get the modifier buttons that were pressed or released diff --git a/src/lib/core/KeyState.h b/src/lib/core/KeyState.h index 9ae3da52..aa92bf60 100644 --- a/src/lib/core/KeyState.h +++ b/src/lib/core/KeyState.h @@ -67,10 +67,10 @@ public: virtual void updateKeyState(); virtual void setHalfDuplexMask(KeyModifierMask); virtual void fakeKeyDown(KeyID id, KeyModifierMask mask, - KeyButton button); + KeyButton serverID); virtual bool fakeKeyRepeat(KeyID id, KeyModifierMask mask, - SInt32 count, KeyButton button); - virtual bool fakeKeyUp(KeyButton button); + SInt32 count, KeyButton serverID); + virtual bool fakeKeyUp(KeyButton serverID); virtual void fakeAllKeysUp(); virtual bool fakeCtrlAltDel() = 0; virtual bool fakeMediaKey(KeyID id); @@ -213,20 +213,20 @@ private: // current keyboard state (> 0 if pressed, 0 otherwise). this is // initialized to the keyboard state according to the system then // it tracks synthesized events. - SInt32 m_keys[kNumButtons]; + SInt32 m_keys[kNumButtons]{}; // synthetic keyboard state (> 0 if pressed, 0 otherwise). this // tracks the synthesized keyboard state. if m_keys[n] > 0 but // m_syntheticKeys[n] == 0 then the key was pressed locally and // not synthesized yet. - SInt32 m_syntheticKeys[kNumButtons]; + SInt32 m_syntheticKeys[kNumButtons]{}; // client data for each pressed key - UInt32 m_keyClientData[kNumButtons]; + UInt32 m_keyClientData[kNumButtons]{}; // server keyboard state. an entry is 0 if not the key isn't pressed // otherwise it's the local KeyButton synthesized for the server key. - KeyButton m_serverKeys[kNumButtons]; + KeyButton m_serverKeys[kNumButtons]{}; IEventQueue* m_events; }; diff --git a/src/lib/core/PacketStreamFilter.cpp b/src/lib/core/PacketStreamFilter.cpp index 652b4152..85d20ae1 100644 --- a/src/lib/core/PacketStreamFilter.cpp +++ b/src/lib/core/PacketStreamFilter.cpp @@ -18,8 +18,8 @@ #include "core/PacketStreamFilter.h" #include "base/IEventQueue.h" -#include "mt/Lock.h" #include "base/TMethodEventJob.h" +#include "mt/Lock.h" #include #include @@ -71,7 +71,7 @@ PacketStreamFilter::read(void* buffer, UInt32 n) } // read it - if (buffer != NULL) { + if (buffer != nullptr) { memcpy(buffer, m_buffer.peek(n), n); } m_buffer.pop(n); @@ -83,7 +83,7 @@ PacketStreamFilter::read(void* buffer, UInt32 n) if (m_inputShutdown && m_size == 0) { m_events->addEvent(Event(m_events->forIStream().inputShutdown(), - getEventTarget(), NULL)); + getEventTarget(), nullptr)); } return n; @@ -94,10 +94,10 @@ PacketStreamFilter::write(const void* buffer, UInt32 count) { // write the length of the payload UInt8 length[4]; - length[0] = (UInt8)((count >> 24) & 0xff); - length[1] = (UInt8)((count >> 16) & 0xff); - length[2] = (UInt8)((count >> 8) & 0xff); - length[3] = (UInt8)( count & 0xff); + length[0] = static_cast((count >> 24) & 0xff); + length[1] = static_cast((count >> 16) & 0xff); + length[2] = static_cast((count >> 8) & 0xff); + length[3] = static_cast( count & 0xff); getStream()->write(length, sizeof(length)); // write the payload @@ -142,10 +142,10 @@ PacketStreamFilter::readPacketSize() UInt8 buffer[4]; memcpy(buffer, m_buffer.peek(sizeof(buffer)), sizeof(buffer)); m_buffer.pop(sizeof(buffer)); - m_size = ((UInt32)buffer[0] << 24) | - ((UInt32)buffer[1] << 16) | - ((UInt32)buffer[2] << 8) | - (UInt32)buffer[3]; + m_size = (static_cast(buffer[0]) << 24) | + (static_cast(buffer[1]) << 16) | + (static_cast(buffer[2]) << 8) | + static_cast(buffer[3]); } } diff --git a/src/lib/core/PacketStreamFilter.h b/src/lib/core/PacketStreamFilter.h index e196235f..c4412a22 100644 --- a/src/lib/core/PacketStreamFilter.h +++ b/src/lib/core/PacketStreamFilter.h @@ -36,7 +36,7 @@ public: // IStream overrides virtual void close(); virtual UInt32 read(void* buffer, UInt32 n); - virtual void write(const void* buffer, UInt32 n); + virtual void write(const void* buffer, UInt32 count); virtual void shutdownInput(); virtual bool isReady() const; virtual UInt32 getSize() const; diff --git a/src/lib/core/PortableTaskBarReceiver.cpp b/src/lib/core/PortableTaskBarReceiver.cpp index 8c584b99..7e4eee5b 100644 --- a/src/lib/core/PortableTaskBarReceiver.cpp +++ b/src/lib/core/PortableTaskBarReceiver.cpp @@ -17,11 +17,11 @@ */ #include "core/PortableTaskBarReceiver.h" -#include "mt/Lock.h" -#include "base/String.h" -#include "base/IEventQueue.h" #include "arch/Arch.h" +#include "base/IEventQueue.h" +#include "base/String.h" #include "common/Version.h" +#include "mt/Lock.h" // // PortableTaskBarReceiver @@ -45,7 +45,7 @@ PortableTaskBarReceiver::updateStatus(INode* node, const String& errorMsg) { // update our status m_errorMessage = errorMsg; - if (node == NULL) { + if (node == nullptr) { if (m_errorMessage.empty()) { m_state = kNotRunning; } @@ -84,7 +84,7 @@ PortableTaskBarReceiver::quit() } void -PortableTaskBarReceiver::onStatusChanged(INode*) +PortableTaskBarReceiver::onStatusChanged(INode* /*unused*/) { // do nothing } diff --git a/src/lib/core/ProtocolUtil.cpp b/src/lib/core/ProtocolUtil.cpp index 88ca6c05..9440a24c 100644 --- a/src/lib/core/ProtocolUtil.cpp +++ b/src/lib/core/ProtocolUtil.cpp @@ -17,9 +17,9 @@ */ #include "core/ProtocolUtil.h" -#include "io/IStream.h" #include "base/Log.h" #include "common/stdvector.h" +#include "io/IStream.h" #include #include @@ -78,7 +78,7 @@ ProtocolUtil::vwritef(synergy::IStream* stream, } // fill buffer - UInt8* buffer = new UInt8[size]; + auto* buffer = new UInt8[size]; writef(buffer, fmt, args); try { @@ -101,7 +101,7 @@ ProtocolUtil::vreadf(synergy::IStream* stream, const char* fmt, va_list args) assert(fmt != NULL); // begin scanning - while (*fmt) { + while (*fmt != 0) { if (*fmt == '%') { // format specifier. determine argument size. ++fmt; @@ -234,7 +234,7 @@ ProtocolUtil::vreadf(synergy::IStream* stream, const char* fmt, va_list args) // save the data String* dst = va_arg(args, String*); - dst->assign((const char*)sBuffer, len); + dst->assign(reinterpret_cast(sBuffer), len); // release the buffer if (!useFixed) { @@ -275,7 +275,7 @@ UInt32 ProtocolUtil::getLength(const char* fmt, va_list args) { UInt32 n = 0; - while (*fmt) { + while (*fmt != 0) { if (*fmt == '%') { // format specifier. determine argument size. ++fmt; @@ -290,22 +290,22 @@ ProtocolUtil::getLength(const char* fmt, va_list args) assert(len == 1 || len == 2 || len == 4); switch (len) { case 1: - len = (UInt32)(va_arg(args, std::vector*))->size() + 4; + len = static_cast((va_arg(args, std::vector*))->size()) + 4; break; case 2: - len = 2 * (UInt32)(va_arg(args, std::vector*))->size() + 4; + len = 2 * static_cast((va_arg(args, std::vector*))->size()) + 4; break; case 4: - len = 4 * (UInt32)(va_arg(args, std::vector*))->size() + 4; + len = 4 * static_cast((va_arg(args, std::vector*))->size()) + 4; break; } break; case 's': assert(len == 0); - len = (UInt32)(va_arg(args, String*))->size() + 4; + len = static_cast((va_arg(args, String*))->size()) + 4; (void)va_arg(args, UInt8*); break; @@ -340,9 +340,9 @@ ProtocolUtil::getLength(const char* fmt, va_list args) void ProtocolUtil::writef(void* buffer, const char* fmt, va_list args) { - UInt8* dst = static_cast(buffer); + auto* dst = static_cast(buffer); - while (*fmt) { + while (*fmt != 0) { if (*fmt == '%') { // format specifier. determine argument size. ++fmt; @@ -383,7 +383,7 @@ ProtocolUtil::writef(void* buffer, const char* fmt, va_list args) // 1 byte integers const std::vector* list = va_arg(args, const std::vector*); - const UInt32 n = (UInt32)list->size(); + const auto n = static_cast(list->size()); *dst++ = static_cast((n >> 24) & 0xff); *dst++ = static_cast((n >> 16) & 0xff); *dst++ = static_cast((n >> 8) & 0xff); @@ -398,7 +398,7 @@ ProtocolUtil::writef(void* buffer, const char* fmt, va_list args) // 2 byte integers const std::vector* list = va_arg(args, const std::vector*); - const UInt32 n = (UInt32)list->size(); + const auto n = static_cast(list->size()); *dst++ = static_cast((n >> 24) & 0xff); *dst++ = static_cast((n >> 16) & 0xff); *dst++ = static_cast((n >> 8) & 0xff); @@ -415,7 +415,7 @@ ProtocolUtil::writef(void* buffer, const char* fmt, va_list args) // 4 byte integers const std::vector* list = va_arg(args, const std::vector*); - const UInt32 n = (UInt32)list->size(); + const auto n = static_cast(list->size()); *dst++ = static_cast((n >> 24) & 0xff); *dst++ = static_cast((n >> 16) & 0xff); *dst++ = static_cast((n >> 8) & 0xff); @@ -440,7 +440,7 @@ ProtocolUtil::writef(void* buffer, const char* fmt, va_list args) case 's': { assert(len == 0); const String* src = va_arg(args, String*); - const UInt32 len = (src != NULL) ? (UInt32)src->size() : 0; + const UInt32 len = (src != nullptr) ? static_cast(src->size()) : 0; *dst++ = static_cast((len >> 24) & 0xff); *dst++ = static_cast((len >> 16) & 0xff); *dst++ = static_cast((len >> 8) & 0xff); @@ -515,7 +515,7 @@ ProtocolUtil::read(synergy::IStream* stream, void* vbuffer, UInt32 count) assert(stream != NULL); assert(vbuffer != NULL); - UInt8* buffer = static_cast(vbuffer); + auto* buffer = static_cast(vbuffer); while (count > 0) { // read more UInt32 n = stream->read(buffer, count); @@ -538,7 +538,7 @@ ProtocolUtil::read(synergy::IStream* stream, void* vbuffer, UInt32 count) // String -XIOReadMismatch::getWhat() const throw() +XIOReadMismatch::getWhat() const noexcept { return format("XIOReadMismatch", "ProtocolUtil::readf() mismatch"); } diff --git a/src/lib/core/ProtocolUtil.h b/src/lib/core/ProtocolUtil.h index b7e43836..eb861147 100644 --- a/src/lib/core/ProtocolUtil.h +++ b/src/lib/core/ProtocolUtil.h @@ -80,7 +80,7 @@ private: static UInt32 getLength(const char* fmt, va_list); static void writef(void*, const char* fmt, va_list); - static UInt32 eatLength(const char** fmt); + static UInt32 eatLength(const char** pfmt); static void read(synergy::IStream*, void*, UInt32); }; diff --git a/src/lib/core/Screen.cpp b/src/lib/core/Screen.cpp index 216fe11a..fdc37787 100644 --- a/src/lib/core/Screen.cpp +++ b/src/lib/core/Screen.cpp @@ -17,12 +17,12 @@ */ #include "core/Screen.h" +#include "base/IEventQueue.h" +#include "base/Log.h" +#include "base/TMethodEventJob.h" #include "core/IPlatformScreen.h" #include "core/protocol_types.h" -#include "base/Log.h" -#include "base/IEventQueue.h" #include "server/ClientProxy.h" -#include "base/TMethodEventJob.h" namespace synergy { @@ -172,7 +172,7 @@ Screen::setClipboard(ClipboardID id, const IClipboard* clipboard) void Screen::grabClipboard(ClipboardID id) { - m_screen->setClipboard(id, NULL); + m_screen->setClipboard(id, nullptr); } void @@ -210,7 +210,7 @@ Screen::keyRepeat(KeyID id, } void -Screen::keyUp(KeyID, KeyModifierMask, KeyButton button) +Screen::keyUp(KeyID /*unused*/, KeyModifierMask /*unused*/, KeyButton button) { m_screen->fakeKeyUp(button); } @@ -272,7 +272,7 @@ Screen::setOptions(const OptionsList& options) { // update options bool oldScreenSaverSync = m_screenSaverSync; - for (UInt32 i = 0, n = (UInt32)options.size(); i < n; i += 2) { + for (UInt32 i = 0, n = static_cast(options.size()); i < n; i += 2) { if (options[i] == kOptionScreenSaverSync) { m_screenSaverSync = (options[i + 1] != 0); LOG((CLOG_DEBUG1 "screen saver synchronization %s", m_screenSaverSync ? "on" : "off")); @@ -378,11 +378,11 @@ Screen::isLockedToScreen() const } if (m_enableDragDrop) { - return (buttonID == kButtonLeft) ? false : true; + return buttonID != kButtonLeft; } - else { + return true; - } + } // not locked @@ -395,9 +395,9 @@ Screen::getJumpZoneSize() const if (!m_isPrimary) { return 0; } - else { + return m_screen->getJumpZoneSize(); - } + } void @@ -535,7 +535,7 @@ Screen::enterPrimary() } void -Screen::enterSecondary(KeyModifierMask) +Screen::enterSecondary(KeyModifierMask /*unused*/) { // do nothing } @@ -556,4 +556,4 @@ Screen::leaveSecondary() m_screen->fakeAllKeysUp(); } -} +} // namespace synergy diff --git a/src/lib/core/Screen.h b/src/lib/core/Screen.h index 5bd6484d..4564f200 100644 --- a/src/lib/core/Screen.h +++ b/src/lib/core/Screen.h @@ -143,27 +143,27 @@ public: /*! Synthesize mouse events to generate a press of mouse button \c id. */ - void mouseDown(ButtonID id); + void mouseDown(ButtonID button); //! Notify of mouse release /*! Synthesize mouse events to generate a release of mouse button \c id. */ - void mouseUp(ButtonID id); + void mouseUp(ButtonID button); //! Notify of mouse motion /*! Synthesize mouse events to generate mouse motion to the absolute screen position \c xAbs,yAbs. */ - void mouseMove(SInt32 xAbs, SInt32 yAbs); + void mouseMove(SInt32 x, SInt32 y); //! Notify of mouse motion /*! Synthesize mouse events to generate mouse motion by the relative amount \c xRel,yRel. */ - void mouseRelativeMove(SInt32 xRel, SInt32 yRel); + void mouseRelativeMove(SInt32 dx, SInt32 dy); //! Notify of mouse wheel motion /*! @@ -297,7 +297,7 @@ public: virtual void* getEventTarget() const; virtual bool getClipboard(ClipboardID id, IClipboard*) const; virtual void getShape(SInt32& x, SInt32& y, - SInt32& width, SInt32& height) const; + SInt32& w, SInt32& h) const; virtual void getCursorPos(SInt32& x, SInt32& y) const; IPlatformScreen* getPlatformScreen() { return m_screen; } @@ -331,7 +331,7 @@ private: // note toggle keys that toggles on up/down (false) or on // transition (true) - KeyModifierMask m_halfDuplex; + KeyModifierMask m_halfDuplex{}; // true if we're faking input on a primary screen bool m_fakeInput; diff --git a/src/lib/core/ServerApp.cpp b/src/lib/core/ServerApp.cpp index d487ca3f..af09e950 100644 --- a/src/lib/core/ServerApp.cpp +++ b/src/lib/core/ServerApp.cpp @@ -18,27 +18,27 @@ #include "core/ServerApp.h" -#include "server/Server.h" -#include "server/ClientListener.h" -#include "server/ClientProxy.h" -#include "server/PrimaryClient.h" -#include "core/ArgParser.h" -#include "core/Screen.h" -#include "core/XScreen.h" -#include "core/ServerTaskBarReceiver.h" -#include "core/ServerArgs.h" -#include "net/SocketMultiplexer.h" -#include "net/TCPSocketFactory.h" -#include "net/XSocket.h" #include "arch/Arch.h" #include "base/EventQueue.h" -#include "base/log_outputters.h" #include "base/FunctionEventJob.h" -#include "base/TMethodJob.h" #include "base/IEventQueue.h" #include "base/Log.h" #include "base/TMethodEventJob.h" +#include "base/TMethodJob.h" +#include "base/log_outputters.h" #include "common/Version.h" +#include "core/ArgParser.h" +#include "core/Screen.h" +#include "core/ServerArgs.h" +#include "core/ServerTaskBarReceiver.h" +#include "core/XScreen.h" +#include "net/SocketMultiplexer.h" +#include "net/TCPSocketFactory.h" +#include "net/XSocket.h" +#include "server/ClientListener.h" +#include "server/ClientProxy.h" +#include "server/PrimaryClient.h" +#include "server/Server.h" #if SYSAPI_WIN32 #include "arch/win32/ArchMiscWindows.h" @@ -56,9 +56,9 @@ #include "platform/OSXDragSimulator.h" #endif +#include #include #include -#include // // ServerApp @@ -66,19 +66,18 @@ ServerApp::ServerApp(IEventQueue* events) : App(events, new ServerArgs()), - m_server(NULL), + m_server(nullptr), m_serverState(kUninitialized), - m_serverScreen(NULL), - m_primaryClient(NULL), - m_listener(NULL), - m_timer(NULL), - m_synergyAddress(NULL) + m_serverScreen(nullptr), + m_primaryClient(nullptr), + m_listener(nullptr), + m_timer(nullptr), + m_synergyAddress(nullptr) { } ServerApp::~ServerApp() -{ -} += default; void ServerApp::parseArgs(int argc, const char* const* argv) @@ -159,7 +158,7 @@ ServerApp::help() } void -ServerApp::reloadSignalHandler(Arch::ESignal, void*) +ServerApp::reloadSignalHandler(Arch::ESignal /*unused*/, void* /*unused*/) { IEventQueue* events = App::instance().getEvents(); events->addEvent(Event(events->forServerApp().reloadConfig(), @@ -167,11 +166,11 @@ ServerApp::reloadSignalHandler(Arch::ESignal, void*) } void -ServerApp::reloadConfig(const Event&, void*) +ServerApp::reloadConfig(const Event& /*unused*/, void* /*unused*/) { LOG((CLOG_DEBUG "reload configuration")); if (loadConfig(args().m_configFile)) { - if (m_server != NULL) { + if (m_server != nullptr) { m_server->setConfig(*args().m_config); } LOG((CLOG_NOTE "reloaded configuration")); @@ -249,26 +248,26 @@ ServerApp::loadConfig(const String& pathname) } void -ServerApp::forceReconnect(const Event&, void*) +ServerApp::forceReconnect(const Event& /*unused*/, void* /*unused*/) { - if (m_server != NULL) { + if (m_server != nullptr) { m_server->disconnect(); } } void -ServerApp::handleClientConnected(const Event&, void* vlistener) +ServerApp::handleClientConnected(const Event& /*unused*/, void* vlistener) { - ClientListener* listener = static_cast(vlistener); + auto* listener = static_cast(vlistener); ClientProxy* client = listener->getNextClient(); - if (client != NULL) { + if (client != nullptr) { m_server->adoptClient(client); updateStatus(); } } void -ServerApp::handleClientsDisconnected(const Event&, void*) +ServerApp::handleClientsDisconnected(const Event& /*unused*/, void* /*unused*/) { m_events->addEvent(Event(Event::kQuit)); } @@ -276,7 +275,7 @@ ServerApp::handleClientsDisconnected(const Event&, void*) void ServerApp::closeServer(Server* server) { - if (server == NULL) { + if (server == nullptr) { return; } @@ -285,7 +284,7 @@ ServerApp::closeServer(Server* server) // wait for clients to disconnect for up to timeout seconds double timeout = 3.0; - EventQueueTimer* timer = m_events->newOneShotTimer(timeout, NULL); + EventQueueTimer* timer = m_events->newOneShotTimer(timeout, nullptr); m_events->adoptHandler(Event::kTimer, timer, new TMethodEventJob(this, &ServerApp::handleClientsDisconnected)); m_events->adoptHandler(m_events->forServer().disconnected(), server, @@ -304,10 +303,10 @@ ServerApp::closeServer(Server* server) void ServerApp::stopRetryTimer() { - if (m_timer != NULL) { + if (m_timer != nullptr) { m_events->deleteTimer(m_timer); - m_events->removeHandler(Event::kTimer, NULL); - m_timer = NULL; + m_events->removeHandler(Event::kTimer, nullptr); + m_timer = nullptr; } } @@ -317,14 +316,14 @@ ServerApp::updateStatus() updateStatus(""); } -void ServerApp::updateStatus(const String& msg) +void ServerApp::updateStatus(const String& /*msg*/) { } void ServerApp::closeClientListener(ClientListener* listen) { - if (listen != NULL) { + if (listen != nullptr) { m_events->removeHandler(m_events->forClientListener().connected(), listen); delete listen; } @@ -336,8 +335,8 @@ ServerApp::stopServer() if (m_serverState == kStarted) { closeServer(m_server); closeClientListener(m_listener); - m_server = NULL; - m_listener = NULL; + m_server = nullptr; + m_listener = nullptr; m_serverState = kInitialized; } else if (m_serverState == kStarting) { @@ -357,7 +356,7 @@ ServerApp::closePrimaryClient(PrimaryClient* primaryClient) void ServerApp::closeServerScreen(synergy::Screen* screen) { - if (screen != NULL) { + if (screen != nullptr) { m_events->removeHandler(m_events->forIScreen().error(), screen->getEventTarget()); m_events->removeHandler(m_events->forIScreen().suspend(), @@ -374,8 +373,8 @@ void ServerApp::cleanupServer() if (m_serverState == kInitialized) { closePrimaryClient(m_primaryClient); closeServerScreen(m_serverScreen); - m_primaryClient = NULL; - m_serverScreen = NULL; + m_primaryClient = nullptr; + m_serverScreen = nullptr; m_serverState = kUninitialized; } else if (m_serverState == kInitializing || @@ -389,7 +388,7 @@ void ServerApp::cleanupServer() } void -ServerApp::retryHandler(const Event&, void*) +ServerApp::retryHandler(const Event& /*unused*/, void* /*unused*/) { // discard old timer assert(m_timer != NULL); @@ -443,8 +442,8 @@ bool ServerApp::initServer() } double retryTime; - synergy::Screen* serverScreen = NULL; - PrimaryClient* primaryClient = NULL; + synergy::Screen* serverScreen = nullptr; + PrimaryClient* primaryClient = nullptr; try { String name = args().m_config->getCanonicalName(args().m_name); serverScreen = openServerScreen(); @@ -479,16 +478,16 @@ bool ServerApp::initServer() // install a timer and handler to retry later assert(m_timer == NULL); LOG((CLOG_DEBUG "retry in %.0f seconds", retryTime)); - m_timer = m_events->newOneShotTimer(retryTime, NULL); + m_timer = m_events->newOneShotTimer(retryTime, nullptr); m_events->adoptHandler(Event::kTimer, m_timer, new TMethodEventJob(this, &ServerApp::retryHandler)); m_serverState = kInitializing; return true; } - else { + // don't try again return false; - } + } synergy::Screen* @@ -534,7 +533,7 @@ ServerApp::startServer() } double retryTime; - ClientListener* listener = NULL; + ClientListener* listener = nullptr; try { listener = openClientListener(args().m_config->getSynergyAddress()); m_server = openServer(*args().m_config, m_primaryClient); @@ -562,16 +561,16 @@ ServerApp::startServer() // install a timer and handler to retry later assert(m_timer == NULL); LOG((CLOG_DEBUG "retry in %.0f seconds", retryTime)); - m_timer = m_events->newOneShotTimer(retryTime, NULL); + m_timer = m_events->newOneShotTimer(retryTime, nullptr); m_events->adoptHandler(Event::kTimer, m_timer, new TMethodEventJob(this, &ServerApp::retryHandler)); m_serverState = kStarting; return true; } - else { + // don't try again return false; - } + } synergy::Screen* @@ -597,14 +596,14 @@ ServerApp::openPrimaryClient(const String& name, synergy::Screen* screen) } void -ServerApp::handleScreenError(const Event&, void*) +ServerApp::handleScreenError(const Event& /*unused*/, void* /*unused*/) { LOG((CLOG_CRIT "error on screen")); m_events->addEvent(Event(Event::kQuit)); } void -ServerApp::handleSuspend(const Event&, void*) +ServerApp::handleSuspend(const Event& /*unused*/, void* /*unused*/) { if (!m_suspended) { LOG((CLOG_INFO "suspend")); @@ -614,7 +613,7 @@ ServerApp::handleSuspend(const Event&, void*) } void -ServerApp::handleResume(const Event&, void*) +ServerApp::handleResume(const Event& /*unused*/, void* /*unused*/) { if (m_suspended) { LOG((CLOG_INFO "resume")); @@ -626,7 +625,7 @@ ServerApp::handleResume(const Event&, void*) ClientListener* ServerApp::openClientListener(const NetworkAddress& address) { - ClientListener* listen = new ClientListener( + auto* listen = new ClientListener( address, new TCPSocketFactory(m_events, getSocketMultiplexer()), m_events); @@ -642,7 +641,7 @@ ServerApp::openClientListener(const NetworkAddress& address) Server* ServerApp::openServer(Config& config, PrimaryClient* primaryClient) { - Server* server = new Server(config, primaryClient, m_serverScreen, m_events, args()); + auto* server = new Server(config, primaryClient, m_serverScreen, m_events, args()); try { m_events->adoptHandler( m_events->forServer().disconnected(), server, @@ -661,13 +660,13 @@ ServerApp::openServer(Config& config, PrimaryClient* primaryClient) } void -ServerApp::handleNoClients(const Event&, void*) +ServerApp::handleNoClients(const Event& /*unused*/, void* /*unused*/) { updateStatus(); } void -ServerApp::handleScreenSwitched(const Event& e, void*) +ServerApp::handleScreenSwitched(const Event& /*e*/, void* /*unused*/) { } @@ -712,7 +711,7 @@ ServerApp::mainLoop() } // handle hangup signal by reloading the server's configuration - ARCH->setSignalHandler(Arch::kHANGUP, &reloadSignalHandler, NULL); + ARCH->setSignalHandler(Arch::kHANGUP, &reloadSignalHandler, nullptr); m_events->adoptHandler(m_events->forServerApp().reloadConfig(), m_events->getSystemTarget(), new TMethodEventJob(this, &ServerApp::reloadConfig)); @@ -770,7 +769,7 @@ ServerApp::mainLoop() return kExitSuccess; } -void ServerApp::resetServer(const Event&, void*) +void ServerApp::resetServer(const Event& /*unused*/, void* /*unused*/) { LOG((CLOG_DEBUG1 "resetting server")); stopServer(); @@ -787,7 +786,7 @@ ServerApp::runInner(int argc, char** argv, ILogOutputter* outputter, StartupFunc args().m_pname = ARCH->getBasename(argv[0]); // install caller's output filter - if (outputter != NULL) { + if (outputter != nullptr) { CLOG->insert(outputter); } @@ -812,9 +811,9 @@ ServerApp::standardStartup(int argc, char** argv) if (args().m_daemon) { return ARCH->daemonize(daemonName(), daemonMainLoopStatic); } - else { + return mainLoop(); - } + } int diff --git a/src/lib/core/ServerArgs.cpp b/src/lib/core/ServerArgs.cpp index 6fc37b56..00769629 100644 --- a/src/lib/core/ServerArgs.cpp +++ b/src/lib/core/ServerArgs.cpp @@ -18,9 +18,7 @@ #include "core/ServerArgs.h" ServerArgs::ServerArgs() : - m_configFile(), - m_serial(), - m_config(NULL) + m_config(nullptr) { } diff --git a/src/lib/core/ServerTaskBarReceiver.cpp b/src/lib/core/ServerTaskBarReceiver.cpp index 87418678..9de70d34 100644 --- a/src/lib/core/ServerTaskBarReceiver.cpp +++ b/src/lib/core/ServerTaskBarReceiver.cpp @@ -17,12 +17,12 @@ */ #include "core/ServerTaskBarReceiver.h" -#include "server/Server.h" -#include "mt/Lock.h" -#include "base/String.h" -#include "base/IEventQueue.h" #include "arch/Arch.h" +#include "base/IEventQueue.h" +#include "base/String.h" #include "common/Version.h" +#include "mt/Lock.h" +#include "server/Server.h" // // ServerTaskBarReceiver @@ -46,7 +46,7 @@ ServerTaskBarReceiver::updateStatus(Server* server, const String& errorMsg) { // update our status m_errorMessage = errorMsg; - if (server == NULL) { + if (server == nullptr) { if (m_errorMessage.empty()) { m_state = kNotRunning; } @@ -98,7 +98,7 @@ ServerTaskBarReceiver::quit() } void -ServerTaskBarReceiver::onStatusChanged(Server*) +ServerTaskBarReceiver::onStatusChanged(Server* /*unused*/) { // do nothing } diff --git a/src/lib/core/StreamChunker.cpp b/src/lib/core/StreamChunker.cpp index bc03a771..9b8aa77e 100644 --- a/src/lib/core/StreamChunker.cpp +++ b/src/lib/core/StreamChunker.cpp @@ -17,19 +17,19 @@ #include "core/StreamChunker.h" -#include "mt/Lock.h" -#include "mt/Mutex.h" -#include "core/FileChunk.h" -#include "core/ClipboardChunk.h" -#include "core/protocol_types.h" -#include "base/EventTypes.h" #include "base/Event.h" -#include "base/IEventQueue.h" #include "base/EventTypes.h" +#include "base/EventTypes.h" +#include "base/IEventQueue.h" #include "base/Log.h" #include "base/Stopwatch.h" #include "base/String.h" #include "common/stdexcept.h" +#include "core/ClipboardChunk.h" +#include "core/FileChunk.h" +#include "core/protocol_types.h" +#include "mt/Lock.h" +#include "mt/Mutex.h" #include @@ -39,7 +39,7 @@ static const size_t g_chunkSize = 32 * 1024; //32kb bool StreamChunker::s_isChunkingFile = false; bool StreamChunker::s_interruptFile = false; -Mutex* StreamChunker::s_interruptMutex = NULL; +Mutex* StreamChunker::s_interruptMutex = nullptr; void StreamChunker::sendFile( @@ -57,7 +57,7 @@ StreamChunker::sendFile( // check file size file.seekg (0, std::ios::end); - size_t size = (size_t)file.tellg(); + auto size = (size_t)file.tellg(); // send first message (file size) String fileSize = synergy::string::sizeTypeToString(size); @@ -84,9 +84,9 @@ StreamChunker::sendFile( chunkSize = size - sentLength; } - char* chunkData = new char[chunkSize]; + auto* chunkData = new char[chunkSize]; file.read(chunkData, chunkSize); - UInt8* data = reinterpret_cast(chunkData); + auto* data = reinterpret_cast(chunkData); FileChunk* fileChunk = FileChunk::data(data, chunkSize); delete[] chunkData; diff --git a/src/lib/core/ToolApp.cpp b/src/lib/core/ToolApp.cpp index dff26f53..18acf68a 100644 --- a/src/lib/core/ToolApp.cpp +++ b/src/lib/core/ToolApp.cpp @@ -17,10 +17,10 @@ #include "core/ToolApp.h" -#include "core/ArgParser.h" #include "arch/Arch.h" #include "base/Log.h" #include "base/String.h" +#include "core/ArgParser.h" #include #include diff --git a/src/lib/core/XScreen.cpp b/src/lib/core/XScreen.cpp index 5a2883a5..3103d0a3 100644 --- a/src/lib/core/XScreen.cpp +++ b/src/lib/core/XScreen.cpp @@ -23,7 +23,7 @@ // String -XScreenOpenFailure::getWhat() const throw() +XScreenOpenFailure::getWhat() const noexcept { return format("XScreenOpenFailure", "unable to open screen"); } @@ -34,7 +34,7 @@ XScreenOpenFailure::getWhat() const throw() // String -XScreenXInputFailure::getWhat() const throw() +XScreenXInputFailure::getWhat() const noexcept { return ""; } @@ -50,7 +50,7 @@ XScreenUnavailable::XScreenUnavailable(double timeUntilRetry) : // do nothing } -XScreenUnavailable::~XScreenUnavailable() _NOEXCEPT +XScreenUnavailable::~XScreenUnavailable() noexcept { // do nothing } @@ -62,7 +62,7 @@ XScreenUnavailable::getRetryTime() const } String -XScreenUnavailable::getWhat() const throw() +XScreenUnavailable::getWhat() const noexcept { return format("XScreenUnavailable", "unable to open screen"); } diff --git a/src/lib/core/XSynergy.cpp b/src/lib/core/XSynergy.cpp index 215cead4..65ba9924 100644 --- a/src/lib/core/XSynergy.cpp +++ b/src/lib/core/XSynergy.cpp @@ -17,6 +17,8 @@ */ #include "core/XSynergy.h" + +#include #include "base/String.h" // @@ -24,7 +26,7 @@ // String -XBadClient::getWhat() const throw() +XBadClient::getWhat() const noexcept { return "XBadClient"; } @@ -42,19 +44,19 @@ XIncompatibleClient::XIncompatibleClient(int major, int minor) : } int -XIncompatibleClient::getMajor() const throw() +XIncompatibleClient::getMajor() const noexcept { return m_major; } int -XIncompatibleClient::getMinor() const throw() +XIncompatibleClient::getMinor() const noexcept { return m_minor; } String -XIncompatibleClient::getWhat() const throw() +XIncompatibleClient::getWhat() const noexcept { return format("XIncompatibleClient", "incompatible client %{1}.%{2}", synergy::string::sprintf("%d", m_major).c_str(), @@ -66,20 +68,20 @@ XIncompatibleClient::getWhat() const throw() // XDuplicateClient // -XDuplicateClient::XDuplicateClient(const String& name) : - m_name(name) +XDuplicateClient::XDuplicateClient(String name) : + m_name(std::move(name)) { // do nothing } const String& -XDuplicateClient::getName() const throw() +XDuplicateClient::getName() const noexcept { return m_name; } String -XDuplicateClient::getWhat() const throw() +XDuplicateClient::getWhat() const noexcept { return format("XDuplicateClient", "duplicate client %{1}", m_name.c_str()); } @@ -89,20 +91,20 @@ XDuplicateClient::getWhat() const throw() // XUnknownClient // -XUnknownClient::XUnknownClient(const String& name) : - m_name(name) +XUnknownClient::XUnknownClient(String name) : + m_name(std::move(name)) { // do nothing } const String& -XUnknownClient::getName() const throw() +XUnknownClient::getName() const noexcept { return m_name; } String -XUnknownClient::getWhat() const throw() +XUnknownClient::getWhat() const noexcept { return format("XUnknownClient", "unknown client %{1}", m_name.c_str()); } @@ -119,13 +121,13 @@ XExitApp::XExitApp(int code) : } int -XExitApp::getCode() const throw() +XExitApp::getCode() const noexcept { return m_code; } String -XExitApp::getWhat() const throw() +XExitApp::getWhat() const noexcept { return format( "XExitApp", "exiting with code %{1}", diff --git a/src/lib/core/XSynergy.h b/src/lib/core/XSynergy.h index 20a97424..e23d74b9 100644 --- a/src/lib/core/XSynergy.h +++ b/src/lib/core/XSynergy.h @@ -68,7 +68,7 @@ a client that is already connected. */ class XDuplicateClient : public XSynergy { public: - XDuplicateClient(const String& name); + XDuplicateClient(String name); virtual ~XDuplicateClient() _NOEXCEPT { } //! @name accessors @@ -94,7 +94,7 @@ unknown to the server. */ class XUnknownClient : public XSynergy { public: - XUnknownClient(const String& name); + XUnknownClient(String name); virtual ~XUnknownClient() _NOEXCEPT { } //! @name accessors diff --git a/src/lib/core/key_types.cpp b/src/lib/core/key_types.cpp index b52e5037..aadb26a2 100644 --- a/src/lib/core/key_types.cpp +++ b/src/lib/core/key_types.cpp @@ -191,7 +191,7 @@ const KeyNameMapEntry kKeyNameMap[] = { { "Bar", 0x007c }, { "BraceR", 0x007d }, { "Tilde", 0x007e }, - { NULL, 0 }, + { nullptr, 0 }, }; const KeyModifierNameMapEntry kModifierNameMap[] = { @@ -204,5 +204,5 @@ const KeyModifierNameMapEntry kModifierNameMap[] = { // { "ScrollLock", KeyModifierScrollLock }, { "Shift", KeyModifierShift }, { "Super", KeyModifierSuper }, - { NULL, 0 }, + { nullptr, 0 }, }; diff --git a/src/lib/core/unix/AppUtilUnix.cpp b/src/lib/core/unix/AppUtilUnix.cpp index 547497fe..d3fa68aa 100644 --- a/src/lib/core/unix/AppUtilUnix.cpp +++ b/src/lib/core/unix/AppUtilUnix.cpp @@ -19,13 +19,12 @@ #include "core/unix/AppUtilUnix.h" #include "core/ArgsBase.h" -AppUtilUnix::AppUtilUnix(IEventQueue* events) +AppUtilUnix::AppUtilUnix(IEventQueue* /*events*/) { } AppUtilUnix::~AppUtilUnix() -{ -} += default; int standardStartupStatic(int argc, char** argv) @@ -36,7 +35,7 @@ standardStartupStatic(int argc, char** argv) int AppUtilUnix::run(int argc, char** argv) { - return app().runInner(argc, argv, NULL, &standardStartupStatic); + return app().runInner(argc, argv, nullptr, &standardStartupStatic); } void diff --git a/src/lib/io/StreamBuffer.cpp b/src/lib/io/StreamBuffer.cpp index f8b3b010..fcbbe214 100644 --- a/src/lib/io/StreamBuffer.cpp +++ b/src/lib/io/StreamBuffer.cpp @@ -44,15 +44,15 @@ StreamBuffer::peek(UInt32 n) // if requesting no data then return NULL so we don't try to access // an empty list. if (n == 0) { - return NULL; + return nullptr; } // reserve space in first chunk - ChunkList::iterator head = m_chunks.begin(); + auto head = m_chunks.begin(); head->reserve(n + m_headUsed); // consolidate chunks into the first chunk until it has n bytes - ChunkList::iterator scan = head; + auto scan = head; ++scan; while (head->size() - m_headUsed < n && scan != m_chunks.end()) { head->insert(head->end(), scan->begin(), scan->end()); @@ -77,10 +77,10 @@ StreamBuffer::pop(UInt32 n) m_size -= n; // discard chunks until more than n bytes would've been discarded - ChunkList::iterator scan = m_chunks.begin(); + auto scan = m_chunks.begin(); assert(scan != m_chunks.end()); while (scan->size() - m_headUsed <= n) { - n -= (UInt32)scan->size() - m_headUsed; + n -= static_cast(scan->size()) - m_headUsed; m_headUsed = 0; scan = m_chunks.erase(scan); assert(scan != m_chunks.end()); @@ -104,10 +104,10 @@ StreamBuffer::write(const void* vdata, UInt32 n) m_size += n; // cast data to bytes - const UInt8* data = static_cast(vdata); + const auto* data = static_cast(vdata); // point to last chunk if it has space, otherwise append an empty chunk - ChunkList::iterator scan = m_chunks.end(); + auto scan = m_chunks.end(); if (scan != m_chunks.begin()) { --scan; if (scan->size() >= kChunkSize) { @@ -122,9 +122,10 @@ StreamBuffer::write(const void* vdata, UInt32 n) while (n > 0) { // choose number of bytes for next chunk assert(scan->size() <= kChunkSize); - UInt32 count = kChunkSize - (UInt32)scan->size(); - if (count > n) + UInt32 count = kChunkSize - static_cast(scan->size()); + if (count > n) { count = n; +} // transfer data scan->insert(scan->end(), data, data + count); diff --git a/src/lib/io/StreamBuffer.h b/src/lib/io/StreamBuffer.h index db218cc0..6ef68a97 100644 --- a/src/lib/io/StreamBuffer.h +++ b/src/lib/io/StreamBuffer.h @@ -53,7 +53,7 @@ public: /*! Appends \c n bytes from \c data to the buffer. */ - void write(const void* data, UInt32 n); + void write(const void* vdata, UInt32 n); //@} //! @name accessors diff --git a/src/lib/io/StreamFilter.cpp b/src/lib/io/StreamFilter.cpp index ceefb89e..1afa6f08 100644 --- a/src/lib/io/StreamFilter.cpp +++ b/src/lib/io/StreamFilter.cpp @@ -112,7 +112,7 @@ StreamFilter::filterEvent(const Event& event) } void -StreamFilter::handleUpstreamEvent(const Event& event, void*) +StreamFilter::handleUpstreamEvent(const Event& event, void* /*unused*/) { filterEvent(event); } diff --git a/src/lib/io/XIO.cpp b/src/lib/io/XIO.cpp index 5ff04fc4..78ef3aab 100644 --- a/src/lib/io/XIO.cpp +++ b/src/lib/io/XIO.cpp @@ -23,7 +23,7 @@ // String -XIOClosed::getWhat() const throw() +XIOClosed::getWhat() const noexcept { return format("XIOClosed", "already closed"); } @@ -34,7 +34,7 @@ XIOClosed::getWhat() const throw() // String -XIOEndOfStream::getWhat() const throw() +XIOEndOfStream::getWhat() const noexcept { return format("XIOEndOfStream", "reached end of stream"); } @@ -45,7 +45,7 @@ XIOEndOfStream::getWhat() const throw() // String -XIOWouldBlock::getWhat() const throw() +XIOWouldBlock::getWhat() const noexcept { return format("XIOWouldBlock", "stream operation would block"); } diff --git a/src/lib/ipc/IpcClient.cpp b/src/lib/ipc/IpcClient.cpp index 22726abc..ffe8358e 100644 --- a/src/lib/ipc/IpcClient.cpp +++ b/src/lib/ipc/IpcClient.cpp @@ -17,10 +17,10 @@ */ #include "ipc/IpcClient.h" -#include "ipc/Ipc.h" -#include "ipc/IpcServerProxy.h" -#include "ipc/IpcMessage.h" #include "base/TMethodEventJob.h" +#include "ipc/Ipc.h" +#include "ipc/IpcMessage.h" +#include "ipc/IpcServerProxy.h" // // IpcClient @@ -51,8 +51,7 @@ IpcClient::init() } IpcClient::~IpcClient() -{ -} += default; void IpcClient::connect() @@ -90,7 +89,7 @@ IpcClient::send(const IpcMessage& message) } void -IpcClient::handleConnected(const Event&, void*) +IpcClient::handleConnected(const Event& /*unused*/, void* /*unused*/) { m_events->addEvent(Event( m_events->forIpcClient().connected(), this, m_server, Event::kDontFreeData)); @@ -100,7 +99,7 @@ IpcClient::handleConnected(const Event&, void*) } void -IpcClient::handleMessageReceived(const Event& e, void*) +IpcClient::handleMessageReceived(const Event& e, void* /*unused*/) { Event event(m_events->forIpcClient().messageReceived(), this); event.setDataObject(e.getDataObject()); diff --git a/src/lib/ipc/IpcClientProxy.cpp b/src/lib/ipc/IpcClientProxy.cpp index 2a279f69..6e18209a 100644 --- a/src/lib/ipc/IpcClientProxy.cpp +++ b/src/lib/ipc/IpcClientProxy.cpp @@ -18,13 +18,13 @@ #include "ipc/IpcClientProxy.h" -#include "ipc/Ipc.h" -#include "ipc/IpcMessage.h" +#include "arch/Arch.h" +#include "base/Log.h" +#include "base/TMethodEventJob.h" #include "core/ProtocolUtil.h" #include "io/IStream.h" -#include "arch/Arch.h" -#include "base/TMethodEventJob.h" -#include "base/Log.h" +#include "ipc/Ipc.h" +#include "ipc/IpcMessage.h" // // IpcClientProxy @@ -82,21 +82,21 @@ IpcClientProxy::~IpcClientProxy() } void -IpcClientProxy::handleDisconnect(const Event&, void*) +IpcClientProxy::handleDisconnect(const Event& /*unused*/, void* /*unused*/) { disconnect(); LOG((CLOG_DEBUG "ipc client disconnected")); } void -IpcClientProxy::handleWriteError(const Event&, void*) +IpcClientProxy::handleWriteError(const Event& /*unused*/, void* /*unused*/) { disconnect(); LOG((CLOG_DEBUG "ipc client write error")); } void -IpcClientProxy::handleData(const Event&, void*) +IpcClientProxy::handleData(const Event& /*unused*/, void* /*unused*/) { // don't allow the dtor to destroy the stream while we're using it. ArchMutexLock lock(m_readMutex); @@ -123,7 +123,7 @@ IpcClientProxy::handleData(const Event&, void*) } // don't delete with this event; the data is passed to a new event. - Event e(m_events->forIpcClientProxy().messageReceived(), this, NULL, Event::kDontFreeData); + Event e(m_events->forIpcClientProxy().messageReceived(), this, nullptr, Event::kDontFreeData); e.setDataObject(m); m_events->addEvent(e); @@ -145,7 +145,7 @@ IpcClientProxy::send(const IpcMessage& message) switch (message.type()) { case kIpcLogLine: { - const IpcLogLineMessage& llm = static_cast(message); + const auto& llm = dynamic_cast(message); const String logLine = llm.logLine(); ProtocolUtil::writef(&m_stream, kIpcMsgLogLine, &logLine); break; diff --git a/src/lib/ipc/IpcLogOutputter.cpp b/src/lib/ipc/IpcLogOutputter.cpp index 120fd66f..cbf749d5 100644 --- a/src/lib/ipc/IpcLogOutputter.cpp +++ b/src/lib/ipc/IpcLogOutputter.cpp @@ -18,17 +18,17 @@ #include "ipc/IpcLogOutputter.h" -#include "ipc/IpcServer.h" -#include "ipc/IpcMessage.h" -#include "ipc/Ipc.h" -#include "ipc/IpcClientProxy.h" -#include "mt/Thread.h" #include "arch/Arch.h" #include "arch/XArch.h" #include "base/Event.h" #include "base/EventQueue.h" #include "base/TMethodEventJob.h" #include "base/TMethodJob.h" +#include "ipc/Ipc.h" +#include "ipc/IpcClientProxy.h" +#include "ipc/IpcMessage.h" +#include "ipc/IpcServer.h" +#include "mt/Thread.h" enum EIpcLogOutputter { kBufferMaxSize = 1000, @@ -78,7 +78,7 @@ IpcLogOutputter::~IpcLogOutputter() } void -IpcLogOutputter::open(const char* title) +IpcLogOutputter::open(const char* /*title*/) { } @@ -94,12 +94,12 @@ IpcLogOutputter::close() } void -IpcLogOutputter::show(bool showIfEmpty) +IpcLogOutputter::show(bool /*showIfEmpty*/) { } bool -IpcLogOutputter::write(ELevel, const char* text) +IpcLogOutputter::write(ELevel /*level*/, const char* text) { // ignore events from the buffer thread (would cause recursion). if (m_bufferThread != nullptr && @@ -148,7 +148,7 @@ IpcLogOutputter::isRunning() } void -IpcLogOutputter::bufferThread(void*) +IpcLogOutputter::bufferThread(void* /*unused*/) { m_bufferThreadId = m_bufferThread->getID(); m_running = true; diff --git a/src/lib/ipc/IpcLogOutputter.h b/src/lib/ipc/IpcLogOutputter.h index b6b285b8..dad845d1 100644 --- a/src/lib/ipc/IpcLogOutputter.h +++ b/src/lib/ipc/IpcLogOutputter.h @@ -47,7 +47,7 @@ public: virtual void open(const char* title); virtual void close(); virtual void show(bool showIfEmpty); - virtual bool write(ELevel level, const char* message); + virtual bool write(ELevel level, const char* text); //! @name manipulators //@{ diff --git a/src/lib/ipc/IpcMessage.cpp b/src/lib/ipc/IpcMessage.cpp index f8162ce1..4bc18824 100644 --- a/src/lib/ipc/IpcMessage.cpp +++ b/src/lib/ipc/IpcMessage.cpp @@ -17,6 +17,8 @@ */ #include "ipc/IpcMessage.h" + +#include #include "ipc/Ipc.h" IpcMessage::IpcMessage(UInt8 type) : @@ -25,8 +27,7 @@ IpcMessage::IpcMessage(UInt8 type) : } IpcMessage::~IpcMessage() -{ -} += default; IpcHelloMessage::IpcHelloMessage(EIpcClientType clientType) : IpcMessage(kIpcHello), @@ -35,8 +36,7 @@ IpcHelloMessage::IpcHelloMessage(EIpcClientType clientType) : } IpcHelloMessage::~IpcHelloMessage() -{ -} += default; IpcShutdownMessage::IpcShutdownMessage() : IpcMessage(kIpcShutdown) @@ -44,26 +44,23 @@ IpcMessage(kIpcShutdown) } IpcShutdownMessage::~IpcShutdownMessage() -{ -} += default; -IpcLogLineMessage::IpcLogLineMessage(const String& logLine) : +IpcLogLineMessage::IpcLogLineMessage(String logLine) : IpcMessage(kIpcLogLine), -m_logLine(logLine) +m_logLine(std::move(logLine)) { } IpcLogLineMessage::~IpcLogLineMessage() -{ -} += default; -IpcCommandMessage::IpcCommandMessage(const String& command, bool elevate) : +IpcCommandMessage::IpcCommandMessage(String command, bool elevate) : IpcMessage(kIpcCommand), -m_command(command), +m_command(std::move(command)), m_elevate(elevate) { } IpcCommandMessage::~IpcCommandMessage() -{ -} += default; diff --git a/src/lib/ipc/IpcMessage.h b/src/lib/ipc/IpcMessage.h index 5407c562..ec8e9a11 100644 --- a/src/lib/ipc/IpcMessage.h +++ b/src/lib/ipc/IpcMessage.h @@ -58,7 +58,7 @@ public: class IpcLogLineMessage : public IpcMessage { public: - IpcLogLineMessage(const String& logLine); + IpcLogLineMessage(String logLine); virtual ~IpcLogLineMessage(); //! Gets the log line. @@ -70,7 +70,7 @@ private: class IpcCommandMessage : public IpcMessage { public: - IpcCommandMessage(const String& command, bool elevate); + IpcCommandMessage(String command, bool elevate); virtual ~IpcCommandMessage(); //! Gets the command. diff --git a/src/lib/ipc/IpcServer.cpp b/src/lib/ipc/IpcServer.cpp index 791595f2..b92a0ef3 100644 --- a/src/lib/ipc/IpcServer.cpp +++ b/src/lib/ipc/IpcServer.cpp @@ -18,15 +18,15 @@ #include "ipc/IpcServer.h" +#include "base/Event.h" +#include "base/IEventQueue.h" +#include "base/Log.h" +#include "base/TMethodEventJob.h" +#include "io/IStream.h" #include "ipc/Ipc.h" #include "ipc/IpcClientProxy.h" #include "ipc/IpcMessage.h" #include "net/IDataSocket.h" -#include "io/IStream.h" -#include "base/IEventQueue.h" -#include "base/TMethodEventJob.h" -#include "base/Event.h" -#include "base/Log.h" // // IpcServer @@ -71,9 +71,9 @@ IpcServer::~IpcServer() return; } - if (m_socket != nullptr) { + delete m_socket; - } + ARCH->lockMutex(m_clientsMutex); ClientList::iterator it; @@ -94,17 +94,17 @@ IpcServer::listen() } void -IpcServer::handleClientConnecting(const Event&, void*) +IpcServer::handleClientConnecting(const Event& /*unused*/, void* /*unused*/) { synergy::IStream* stream = m_socket->accept(); - if (stream == NULL) { + if (stream == nullptr) { return; } LOG((CLOG_DEBUG "accepted ipc client connection")); ARCH->lockMutex(m_clientsMutex); - IpcClientProxy* proxy = new IpcClientProxy(*stream, m_events); + auto* proxy = new IpcClientProxy(*stream, m_events); m_clients.push_back(proxy); ARCH->unlockMutex(m_clientsMutex); @@ -123,9 +123,9 @@ IpcServer::handleClientConnecting(const Event&, void*) } void -IpcServer::handleClientDisconnected(const Event& e, void*) +IpcServer::handleClientDisconnected(const Event& e, void* /*unused*/) { - IpcClientProxy* proxy = static_cast(e.getTarget()); + auto* proxy = static_cast(e.getTarget()); ArchMutexLock lock(m_clientsMutex); m_clients.remove(proxy); @@ -135,7 +135,7 @@ IpcServer::handleClientDisconnected(const Event& e, void*) } void -IpcServer::handleMessageReceived(const Event& e, void*) +IpcServer::handleMessageReceived(const Event& e, void* /*unused*/) { Event event(m_events->forIpcServer().messageReceived(), this); event.setDataObject(e.getDataObject()); diff --git a/src/lib/ipc/IpcServer.h b/src/lib/ipc/IpcServer.h index b6477f8a..b1548776 100644 --- a/src/lib/ipc/IpcServer.h +++ b/src/lib/ipc/IpcServer.h @@ -76,10 +76,10 @@ private: bool m_mock; IEventQueue* m_events; SocketMultiplexer* m_socketMultiplexer; - TCPListenSocket* m_socket; + TCPListenSocket* m_socket{}; NetworkAddress m_address; ClientList m_clients; - ArchMutex m_clientsMutex; + ArchMutex m_clientsMutex{}; #ifdef TEST_ENV public: diff --git a/src/lib/ipc/IpcServerProxy.cpp b/src/lib/ipc/IpcServerProxy.cpp index 8b631412..4b64df55 100644 --- a/src/lib/ipc/IpcServerProxy.cpp +++ b/src/lib/ipc/IpcServerProxy.cpp @@ -18,12 +18,12 @@ #include "ipc/IpcServerProxy.h" -#include "ipc/IpcMessage.h" -#include "ipc/Ipc.h" +#include "base/Log.h" +#include "base/TMethodEventJob.h" #include "core/ProtocolUtil.h" #include "io/IStream.h" -#include "base/TMethodEventJob.h" -#include "base/Log.h" +#include "ipc/Ipc.h" +#include "ipc/IpcMessage.h" // // IpcServerProxy @@ -46,7 +46,7 @@ IpcServerProxy::~IpcServerProxy() } void -IpcServerProxy::handleData(const Event&, void*) +IpcServerProxy::handleData(const Event& /*unused*/, void* /*unused*/) { LOG((CLOG_DEBUG "start ipc handle data")); @@ -70,7 +70,7 @@ IpcServerProxy::handleData(const Event&, void*) } // don't delete with this event; the data is passed to a new event. - Event e(m_events->forIpcServerProxy().messageReceived(), this, NULL, Event::kDontFreeData); + Event e(m_events->forIpcServerProxy().messageReceived(), this, nullptr, Event::kDontFreeData); e.setDataObject(m); m_events->addEvent(e); @@ -87,13 +87,13 @@ IpcServerProxy::send(const IpcMessage& message) switch (message.type()) { case kIpcHello: { - const IpcHelloMessage& hm = static_cast(message); + const auto& hm = dynamic_cast(message); ProtocolUtil::writef(&m_stream, kIpcMsgHello, hm.clientType()); break; } case kIpcCommand: { - const IpcCommandMessage& cm = static_cast(message); + const auto& cm = dynamic_cast(message); const String command = cm.command(); ProtocolUtil::writef(&m_stream, kIpcMsgCommand, &command); break; diff --git a/src/lib/mt/CondVar.cpp b/src/lib/mt/CondVar.cpp index 99ebf267..423cc3a1 100644 --- a/src/lib/mt/CondVar.cpp +++ b/src/lib/mt/CondVar.cpp @@ -70,9 +70,11 @@ CondVarBase::wait(Stopwatch& timer, double timeout) const // Always call wait at least once, even if remain is 0, to give // other thread a chance to grab the mutex to avoid deadlocks on // busy waiting. - if (remain<0.0) remain=0.0; - if (wait(remain)) + if (remain<0.0) { remain=0.0; +} + if (wait(remain)) { return true; +} remain = timeout - timer.getTime(); } while (remain >= 0.0); return false; diff --git a/src/lib/mt/Mutex.cpp b/src/lib/mt/Mutex.cpp index beed6aa3..a9833790 100644 --- a/src/lib/mt/Mutex.cpp +++ b/src/lib/mt/Mutex.cpp @@ -29,7 +29,7 @@ Mutex::Mutex() m_mutex = ARCH->newMutex(); } -Mutex::Mutex(const Mutex&) +Mutex::Mutex(const Mutex& /*unused*/) { m_mutex = ARCH->newMutex(); } @@ -40,7 +40,7 @@ Mutex::~Mutex() } Mutex& -Mutex::operator=(const Mutex&) +Mutex::operator=(const Mutex& /*unused*/) { return *this; } diff --git a/src/lib/mt/Thread.cpp b/src/lib/mt/Thread.cpp index 9016906c..64fb6b7f 100644 --- a/src/lib/mt/Thread.cpp +++ b/src/lib/mt/Thread.cpp @@ -18,11 +18,11 @@ #include "mt/Thread.h" +#include "arch/Arch.h" +#include "base/IJob.h" +#include "base/Log.h" #include "mt/XMT.h" #include "mt/XThread.h" -#include "arch/Arch.h" -#include "base/Log.h" -#include "base/IJob.h" // // Thread @@ -31,7 +31,7 @@ Thread::Thread(IJob* job) { m_thread = ARCH->newThread(&Thread::threadFunc, job); - if (m_thread == NULL) { + if (m_thread == nullptr) { // couldn't create thread delete job; throw XMTThreadUnavailable(); @@ -111,10 +111,11 @@ Thread::wait(double timeout) const void* Thread::getResult() const { - if (wait()) + if (wait()) { return ARCH->getResultOfThread(m_thread); - else - return NULL; + } else { + return nullptr; + } } IArchMultithread::ThreadID @@ -147,10 +148,10 @@ Thread::threadFunc(void* vjob) } // get job - IJob* job = static_cast(vjob); + auto* job = static_cast(vjob); // run job - void* result = NULL; + void* result = nullptr; try { // go LOG((CLOG_DEBUG1 "thread 0x%08x entry", id)); diff --git a/src/lib/mt/Thread.h b/src/lib/mt/Thread.h index e3320230..3c9160dd 100644 --- a/src/lib/mt/Thread.h +++ b/src/lib/mt/Thread.h @@ -47,7 +47,7 @@ public: Create and start a new thread executing the \c adoptedJob. The new thread takes ownership of \c adoptedJob and will delete it. */ - Thread(IJob* adoptedJob); + Thread(IJob* job); //! Duplicate a thread handle /*! diff --git a/src/lib/mt/XMT.cpp b/src/lib/mt/XMT.cpp index ff7d8751..a16a25ba 100644 --- a/src/lib/mt/XMT.cpp +++ b/src/lib/mt/XMT.cpp @@ -23,7 +23,7 @@ // String -XMTThreadUnavailable::getWhat() const throw() +XMTThreadUnavailable::getWhat() const noexcept { return format("XMTThreadUnavailable", "cannot create thread"); } diff --git a/src/lib/net/IDataSocket.cpp b/src/lib/net/IDataSocket.cpp index 4d4d8944..d6bab1e6 100644 --- a/src/lib/net/IDataSocket.cpp +++ b/src/lib/net/IDataSocket.cpp @@ -35,5 +35,5 @@ IDataSocket::getEventTarget() const { // this is here to work around a VC++6 bug. see the header file. assert(0 && "bad call"); - return NULL; + return nullptr; } diff --git a/src/lib/net/NetworkAddress.cpp b/src/lib/net/NetworkAddress.cpp index c0df9805..2be4fdc1 100644 --- a/src/lib/net/NetworkAddress.cpp +++ b/src/lib/net/NetworkAddress.cpp @@ -18,11 +18,12 @@ #include "net/NetworkAddress.h" -#include "net/XSocket.h" #include "arch/Arch.h" #include "arch/XArch.h" +#include "net/XSocket.h" #include +#include // // NetworkAddress @@ -31,8 +32,7 @@ // name re-resolution adapted from a patch by Brent Priddy. NetworkAddress::NetworkAddress() : - m_address(NULL), - m_hostname(), + m_address(nullptr), m_port(0) { // note -- make no calls to Network socket interface here; @@ -40,8 +40,7 @@ NetworkAddress::NetworkAddress() : } NetworkAddress::NetworkAddress(int port) : - m_address(NULL), - m_hostname(), + m_address(nullptr), m_port(port) { checkPort(); @@ -50,16 +49,16 @@ NetworkAddress::NetworkAddress(int port) : } NetworkAddress::NetworkAddress(const NetworkAddress& addr) : - m_address(addr.m_address != NULL ? ARCH->copyAddr(addr.m_address) : NULL), + m_address(addr.m_address != nullptr ? ARCH->copyAddr(addr.m_address) : nullptr), m_hostname(addr.m_hostname), m_port(addr.m_port) { // do nothing } -NetworkAddress::NetworkAddress(const String& hostname, int port) : - m_address(NULL), - m_hostname(hostname), +NetworkAddress::NetworkAddress(String hostname, int port) : + m_address(nullptr), + m_hostname(std::move(hostname)), m_port(port) { // check for port suffix @@ -111,7 +110,7 @@ NetworkAddress::NetworkAddress(const String& hostname, int port) : NetworkAddress::~NetworkAddress() { - if (m_address != NULL) { + if (m_address != nullptr) { ARCH->closeAddr(m_address); } } @@ -119,11 +118,11 @@ NetworkAddress::~NetworkAddress() NetworkAddress& NetworkAddress::operator=(const NetworkAddress& addr) { - ArchNetAddress newAddr = NULL; - if (addr.m_address != NULL) { + ArchNetAddress newAddr = nullptr; + if (addr.m_address != nullptr) { newAddr = ARCH->copyAddr(addr.m_address); } - if (m_address != NULL) { + if (m_address != nullptr) { ARCH->closeAddr(m_address); } m_address = newAddr; @@ -136,9 +135,9 @@ void NetworkAddress::resolve() { // discard previous address - if (m_address != NULL) { + if (m_address != nullptr) { ARCH->closeAddr(m_address); - m_address = NULL; + m_address = nullptr; } try { @@ -183,7 +182,7 @@ NetworkAddress::operator!=(const NetworkAddress& addr) const bool NetworkAddress::isValid() const { - return (m_address != NULL); + return (m_address != nullptr); } const ArchNetAddress& diff --git a/src/lib/net/NetworkAddress.h b/src/lib/net/NetworkAddress.h index f4266854..beffaa11 100644 --- a/src/lib/net/NetworkAddress.h +++ b/src/lib/net/NetworkAddress.h @@ -49,7 +49,7 @@ public: is thrown with an error of \c XSocketAddress::kBadPort. The hostname is not resolved by the c'tor; use \c resolve to do that. */ - NetworkAddress(const String& hostname, int port); + NetworkAddress(String hostname, int port); NetworkAddress(const NetworkAddress&); @@ -77,13 +77,13 @@ public: /*! Returns true if this address is equal to \p address. */ - bool operator==(const NetworkAddress& address) const; + bool operator==(const NetworkAddress& addr) const; //! Check address inequality /*! Returns true if this address is not equal to \p address. */ - bool operator!=(const NetworkAddress& address) const; + bool operator!=(const NetworkAddress& addr) const; //! Check address validity /*! diff --git a/src/lib/net/SocketMultiplexer.cpp b/src/lib/net/SocketMultiplexer.cpp index 77b5f0dd..a88c079b 100644 --- a/src/lib/net/SocketMultiplexer.cpp +++ b/src/lib/net/SocketMultiplexer.cpp @@ -18,16 +18,16 @@ #include "net/SocketMultiplexer.h" -#include "net/ISocketMultiplexerJob.h" -#include "mt/CondVar.h" -#include "mt/Lock.h" -#include "mt/Mutex.h" -#include "mt/Thread.h" #include "arch/Arch.h" #include "arch/XArch.h" #include "base/Log.h" #include "base/TMethodJob.h" #include "common/stdvector.h" +#include "mt/CondVar.h" +#include "mt/Lock.h" +#include "mt/Mutex.h" +#include "mt/Thread.h" +#include "net/ISocketMultiplexerJob.h" // // SocketMultiplexer @@ -35,18 +35,18 @@ SocketMultiplexer::SocketMultiplexer() : m_mutex(new Mutex), - m_thread(NULL), + m_thread(nullptr), m_update(false), m_jobsReady(new CondVar(m_mutex, false)), m_jobListLock(new CondVar(m_mutex, false)), m_jobListLockLocked(new CondVar(m_mutex, false)), - m_jobListLocker(NULL), - m_jobListLockLocker(NULL) + m_jobListLocker(nullptr), + m_jobListLockLocker(nullptr) { // this pointer just has to be unique and not NULL. it will // never be dereferenced. it's used to identify cursor nodes // in the jobs list. - // TODO: Remove this evilness + // TODO(andrew): Remove this evilness m_cursorMark = reinterpret_cast(this); // start thread @@ -68,9 +68,8 @@ SocketMultiplexer::~SocketMultiplexer() delete m_mutex; // clean up jobs - for (SocketJobMap::iterator i = m_socketJobMap.begin(); - i != m_socketJobMap.end(); ++i) { - delete *(i->second); + for (auto & i : m_socketJobMap) { + delete *(i.second); } } @@ -90,17 +89,17 @@ SocketMultiplexer::addSocket(ISocket* socket, ISocketMultiplexerJob* job) lockJobList(); // insert/replace job - SocketJobMap::iterator i = m_socketJobMap.find(socket); + auto i = m_socketJobMap.find(socket); if (i == m_socketJobMap.end()) { // we *must* put the job at the end so the order of jobs in // the list continue to match the order of jobs in pfds in // serviceThread(). - JobCursor j = m_socketJobs.insert(m_socketJobs.end(), job); + auto j = m_socketJobs.insert(m_socketJobs.end(), job); m_update = true; m_socketJobMap.insert(std::make_pair(socket, j)); } else { - JobCursor j = i->second; + auto j = i->second; if (*j != job) { delete *j; *j = job; @@ -129,7 +128,7 @@ SocketMultiplexer::removeSocket(ISocket* socket) // remove job. rather than removing it from the map we put NULL // in the list instead so the order of jobs in the list continues // to match the order of jobs in pfds in serviceThread(). - SocketJobMap::iterator i = m_socketJobMap.find(socket); + auto i = m_socketJobMap.find(socket); if (i != m_socketJobMap.end()) { if (*(i->second) != NULL) { delete *(i->second); @@ -143,10 +142,10 @@ SocketMultiplexer::removeSocket(ISocket* socket) } void -SocketMultiplexer::serviceThread(void*) +SocketMultiplexer::serviceThread(void* /*unused*/) { std::vector pfds; - IArchNetwork::PollEntry pfd; + IArchNetwork::PollEntry pfd{}; // service the connections for (;;) { @@ -170,11 +169,11 @@ SocketMultiplexer::serviceThread(void*) pfds.clear(); pfds.reserve(m_socketJobMap.size()); - JobCursor cursor = newCursor(); - JobCursor jobCursor = nextCursor(cursor); + auto cursor = newCursor(); + auto jobCursor = nextCursor(cursor); while (jobCursor != m_socketJobs.end()) { ISocketMultiplexerJob* job = *jobCursor; - if (job != NULL) { + if (job != nullptr) { pfd.m_socket = job->getSocket(); pfd.m_events = 0; if (job->isReadable()) { @@ -194,7 +193,7 @@ SocketMultiplexer::serviceThread(void*) try { // check for status if (!pfds.empty()) { - status = ARCH->pollSocket(&pfds[0], (int)pfds.size(), -1); + status = ARCH->pollSocket(&pfds[0], static_cast(pfds.size()), -1); } else { status = 0; @@ -209,8 +208,8 @@ SocketMultiplexer::serviceThread(void*) // iterate over socket jobs, invoking each and saving the // new job. UInt32 i = 0; - JobCursor cursor = newCursor(); - JobCursor jobCursor = nextCursor(cursor); + auto cursor = newCursor(); + auto jobCursor = nextCursor(cursor); while (i < pfds.size() && jobCursor != m_socketJobs.end()) { if (*jobCursor != NULL) { // get poll state @@ -241,7 +240,7 @@ SocketMultiplexer::serviceThread(void*) } // delete any removed socket jobs - for (SocketJobMap::iterator i = m_socketJobMap.begin(); + for (auto i = m_socketJobMap.begin(); i != m_socketJobMap.end();) { if (*(i->second) == NULL) { m_socketJobs.erase(i->second); @@ -269,8 +268,8 @@ SocketMultiplexer::JobCursor SocketMultiplexer::nextCursor(JobCursor cursor) { Lock lock(m_mutex); - JobCursor j = m_socketJobs.end(); - JobCursor i = cursor; + auto j = m_socketJobs.end(); + auto i = cursor; while (++i != m_socketJobs.end()) { if (*i != m_cursorMark) { // found a real job (as opposed to a cursor) @@ -322,7 +321,7 @@ SocketMultiplexer::lockJobList() // take ownership of the lock *m_jobListLock = true; m_jobListLocker = m_jobListLockLocker; - m_jobListLockLocker = NULL; + m_jobListLockLocker = nullptr; // release the lock on the lock *m_jobListLockLocked = false; @@ -339,7 +338,7 @@ SocketMultiplexer::unlockJobList() // release the lock delete m_jobListLocker; - m_jobListLocker = NULL; + m_jobListLocker = nullptr; *m_jobListLock = false; m_jobListLock->signal(); diff --git a/src/lib/net/TCPListenSocket.cpp b/src/lib/net/TCPListenSocket.cpp index 23abed40..83bf7861 100644 --- a/src/lib/net/TCPListenSocket.cpp +++ b/src/lib/net/TCPListenSocket.cpp @@ -18,17 +18,17 @@ #include "net/TCPListenSocket.h" +#include "arch/Arch.h" +#include "arch/XArch.h" +#include "base/IEventQueue.h" +#include "io/XIO.h" +#include "mt/Lock.h" +#include "mt/Mutex.h" #include "net/NetworkAddress.h" #include "net/SocketMultiplexer.h" #include "net/TCPSocket.h" #include "net/TSocketMultiplexerMethodJob.h" #include "net/XSocket.h" -#include "io/XIO.h" -#include "mt/Lock.h" -#include "mt/Mutex.h" -#include "arch/Arch.h" -#include "arch/XArch.h" -#include "base/IEventQueue.h" // // TCPListenSocket @@ -50,7 +50,7 @@ TCPListenSocket::TCPListenSocket(IEventQueue* events, SocketMultiplexer* socketM TCPListenSocket::~TCPListenSocket() { try { - if (m_socket != NULL) { + if (m_socket != nullptr) { m_socketMultiplexer->removeSocket(this); ARCH->closeSocket(m_socket); } @@ -86,13 +86,13 @@ void TCPListenSocket::close() { Lock lock(m_mutex); - if (m_socket == NULL) { + if (m_socket == nullptr) { throw XIOClosed(); } try { m_socketMultiplexer->removeSocket(this); ARCH->closeSocket(m_socket); - m_socket = NULL; + m_socket = nullptr; } catch (XArchNetwork& e) { throw XSocketIOClose(e.what()); @@ -108,23 +108,23 @@ TCPListenSocket::getEventTarget() const IDataSocket* TCPListenSocket::accept() { - IDataSocket* socket = NULL; + IDataSocket* socket = nullptr; try { - socket = new TCPSocket(m_events, m_socketMultiplexer, ARCH->acceptSocket(m_socket, NULL)); - if (socket != NULL) { + socket = new TCPSocket(m_events, m_socketMultiplexer, ARCH->acceptSocket(m_socket, nullptr)); + if (socket != nullptr) { setListeningJob(); } return socket; } catch (XArchNetwork&) { - if (socket != NULL) { + if (socket != nullptr) { delete socket; setListeningJob(); } - return NULL; + return nullptr; } catch (std::exception &ex) { - if (socket != NULL) { + if (socket != nullptr) { delete socket; setListeningJob(); } @@ -143,16 +143,16 @@ TCPListenSocket::setListeningJob() ISocketMultiplexerJob* TCPListenSocket::serviceListening(ISocketMultiplexerJob* job, - bool read, bool, bool error) + bool read, bool /*unused*/, bool error) { if (error) { close(); - return NULL; + return nullptr; } if (read) { - m_events->addEvent(Event(m_events->forIListenSocket().connecting(), this, NULL)); + m_events->addEvent(Event(m_events->forIListenSocket().connecting(), this, nullptr)); // stop polling on this socket until the client accepts - return NULL; + return nullptr; } return job; } diff --git a/src/lib/net/TCPSocket.cpp b/src/lib/net/TCPSocket.cpp index aa18f49a..2d189fd7 100644 --- a/src/lib/net/TCPSocket.cpp +++ b/src/lib/net/TCPSocket.cpp @@ -18,19 +18,19 @@ #include "net/TCPSocket.h" +#include "arch/Arch.h" +#include "arch/XArch.h" +#include "base/IEventJob.h" +#include "base/IEventQueue.h" +#include "base/Log.h" +#include "mt/Lock.h" #include "net/NetworkAddress.h" #include "net/SocketMultiplexer.h" #include "net/TSocketMultiplexerMethodJob.h" #include "net/XSocket.h" -#include "mt/Lock.h" -#include "arch/Arch.h" -#include "arch/XArch.h" -#include "base/Log.h" -#include "base/IEventQueue.h" -#include "base/IEventJob.h" -#include #include +#include #include // @@ -40,7 +40,6 @@ TCPSocket::TCPSocket(IEventQueue* events, SocketMultiplexer* socketMultiplexer) : IDataSocket(events), m_events(events), - m_mutex(), m_flushed(&m_mutex, true), m_socketMultiplexer(socketMultiplexer) { @@ -57,7 +56,6 @@ TCPSocket::TCPSocket(IEventQueue* events, SocketMultiplexer* socketMultiplexer) TCPSocket::TCPSocket(IEventQueue* events, SocketMultiplexer* socketMultiplexer, ArchSocket socket) : IDataSocket(events), m_events(events), - m_mutex(), m_socket(socket), m_flushed(&m_mutex, true), m_socketMultiplexer(socketMultiplexer) @@ -98,7 +96,7 @@ void TCPSocket::close() { // remove ourself from the multiplexer - setJob(NULL); + setJob(nullptr); Lock lock(&m_mutex); @@ -109,9 +107,9 @@ TCPSocket::close() onDisconnected(); // close the socket - if (m_socket != NULL) { + if (m_socket != nullptr) { ArchSocket socket = m_socket; - m_socket = NULL; + m_socket = nullptr; try { ARCH->closeSocket(socket); } @@ -137,7 +135,7 @@ TCPSocket::read(void* buffer, UInt32 n) if (n > size) { n = size; } - if (buffer != NULL && n != 0) { + if (buffer != nullptr && n != 0) { memcpy(buffer, m_inputBuffer.peek(n), n); } m_inputBuffer.pop(n); @@ -187,7 +185,7 @@ void TCPSocket::flush() { Lock lock(&m_mutex); - while (m_flushed == false) { + while (!m_flushed) { m_flushed.wait(); } } @@ -273,7 +271,7 @@ TCPSocket::connect(const NetworkAddress& addr) Lock lock(&m_mutex); // fail on attempts to reconnect - if (m_socket == NULL || m_connected) { + if (m_socket == nullptr || m_connected) { sendConnectionFailedEvent("busy"); return; } @@ -312,7 +310,7 @@ TCPSocket::init() catch (XArchNetwork& e) { try { ARCH->closeSocket(m_socket); - m_socket = NULL; + m_socket = nullptr; } catch (XArchNetwork&) { // ignore @@ -370,7 +368,7 @@ TCPSocket::doWrite() bufferSize = m_outputBuffer.getSize(); const void* buffer = m_outputBuffer.peek(bufferSize); - bytesWrote = (UInt32)ARCH->writeSocket(m_socket, buffer, bufferSize); + bytesWrote = static_cast(ARCH->writeSocket(m_socket, buffer, bufferSize)); if (bytesWrote > 0) { discardWrittenData(bytesWrote); @@ -384,7 +382,7 @@ void TCPSocket::setJob(ISocketMultiplexerJob* job) { // multiplexer will delete the old job - if (job == NULL) { + if (job == nullptr) { m_socketMultiplexer->removeSocket(this); } else { @@ -397,13 +395,13 @@ TCPSocket::newJob() { // note -- must have m_mutex locked on entry - if (m_socket == NULL) { - return NULL; + if (m_socket == nullptr) { + return nullptr; } - else if (!m_connected) { + if (!m_connected) { assert(!m_readable); if (!(m_readable || m_writable)) { - return NULL; + return nullptr; } return new TSocketMultiplexerMethodJob( this, &TCPSocket::serviceConnecting, @@ -411,7 +409,7 @@ TCPSocket::newJob() } else { if (!(m_readable || (m_writable && (m_outputBuffer.getSize() > 0)))) { - return NULL; + return nullptr; } return new TSocketMultiplexerMethodJob( this, &TCPSocket::serviceConnected, @@ -423,7 +421,7 @@ TCPSocket::newJob() void TCPSocket::sendConnectionFailedEvent(const char* msg) { - ConnectionFailedInfo* info = new ConnectionFailedInfo(msg); + auto* info = new ConnectionFailedInfo(msg); m_events->addEvent(Event(m_events->forIDataSocket().connectionFailed(), getEventTarget(), info, Event::kDontFreeData)); } @@ -431,7 +429,7 @@ TCPSocket::sendConnectionFailedEvent(const char* msg) void TCPSocket::sendEvent(Event::Type type) { - m_events->addEvent(Event(type, getEventTarget(), NULL)); + m_events->addEvent(Event(type, getEventTarget(), nullptr)); } void @@ -482,7 +480,7 @@ TCPSocket::onDisconnected() ISocketMultiplexerJob* TCPSocket::serviceConnecting(ISocketMultiplexerJob* job, - bool, bool write, bool error) + bool /*unused*/, bool write, bool error) { Lock lock(&m_mutex); @@ -503,7 +501,7 @@ TCPSocket::serviceConnecting(ISocketMultiplexerJob* job, // connection refused. when that happens it at least doesn't // report the socket as being writable so synergy is able to time // out the attempt.) - if (error || true) { + if (true) { try { // connection may have failed or succeeded ARCH->throwErrorOnSocket(m_socket); @@ -584,5 +582,5 @@ TCPSocket::serviceConnected(ISocketMultiplexerJob* job, } } - return result == kBreak ? NULL : result == kNew ? newJob() : job; + return result == kBreak ? nullptr : result == kNew ? newJob() : job; } diff --git a/src/lib/net/TCPSocket.h b/src/lib/net/TCPSocket.h index b29aa927..42c717cc 100644 --- a/src/lib/net/TCPSocket.h +++ b/src/lib/net/TCPSocket.h @@ -101,9 +101,9 @@ private: bool, bool, bool); protected: - bool m_readable; - bool m_writable; - bool m_connected; + bool m_readable{}; + bool m_writable{}; + bool m_connected{}; IEventQueue* m_events; StreamBuffer m_inputBuffer; StreamBuffer m_outputBuffer; diff --git a/src/lib/net/TCPSocketFactory.cpp b/src/lib/net/TCPSocketFactory.cpp index b0d0717b..6795e73c 100644 --- a/src/lib/net/TCPSocketFactory.cpp +++ b/src/lib/net/TCPSocketFactory.cpp @@ -17,10 +17,10 @@ */ #include "net/TCPSocketFactory.h" -#include "net/TCPSocket.h" -#include "net/TCPListenSocket.h" #include "arch/Arch.h" #include "base/Log.h" +#include "net/TCPListenSocket.h" +#include "net/TCPSocket.h" // // TCPSocketFactory diff --git a/src/lib/net/XSocket.cpp b/src/lib/net/XSocket.cpp index 77c9ea16..d47533e9 100644 --- a/src/lib/net/XSocket.cpp +++ b/src/lib/net/XSocket.cpp @@ -17,6 +17,8 @@ */ #include "net/XSocket.h" + +#include #include "base/String.h" // @@ -24,34 +26,34 @@ // XSocketAddress::XSocketAddress(EError error, - const String& hostname, int port) _NOEXCEPT : + String hostname, int port) noexcept : m_error(error), - m_hostname(hostname), + m_hostname(std::move(hostname)), m_port(port) { // do nothing } XSocketAddress::EError -XSocketAddress::getError() const throw() +XSocketAddress::getError() const noexcept { return m_error; } String -XSocketAddress::getHostname() const throw() +XSocketAddress::getHostname() const noexcept { return m_hostname; } int -XSocketAddress::getPort() const throw() +XSocketAddress::getPort() const noexcept { return m_port; } String -XSocketAddress::getWhat() const throw() +XSocketAddress::getWhat() const noexcept { static const char* s_errorID[] = { "XSocketAddressUnknown", @@ -78,7 +80,7 @@ XSocketAddress::getWhat() const throw() // String -XSocketIOClose::getWhat() const throw() +XSocketIOClose::getWhat() const noexcept { return format("XSocketIOClose", "close: %{1}", what()); } @@ -89,7 +91,7 @@ XSocketIOClose::getWhat() const throw() // String -XSocketBind::getWhat() const throw() +XSocketBind::getWhat() const noexcept { return format("XSocketBind", "cannot bind address: %{1}", what()); } @@ -100,7 +102,7 @@ XSocketBind::getWhat() const throw() // String -XSocketConnect::getWhat() const throw() +XSocketConnect::getWhat() const noexcept { return format("XSocketConnect", "cannot connect socket: %{1}", what()); } @@ -111,7 +113,7 @@ XSocketConnect::getWhat() const throw() // String -XSocketCreate::getWhat() const throw() +XSocketCreate::getWhat() const noexcept { return format("XSocketCreate", "cannot create socket: %{1}", what()); } diff --git a/src/lib/net/XSocket.h b/src/lib/net/XSocket.h index f6e3ca9f..383ab066 100644 --- a/src/lib/net/XSocket.h +++ b/src/lib/net/XSocket.h @@ -41,7 +41,7 @@ public: kBadPort //!< The port is invalid }; - XSocketAddress(EError, const String& hostname, int port) _NOEXCEPT; + XSocketAddress(EError, String hostname, int port) _NOEXCEPT; virtual ~XSocketAddress() _NOEXCEPT { } //! @name accessors diff --git a/src/lib/platform/XWindowsClipboard.cpp b/src/lib/platform/XWindowsClipboard.cpp index 7e79f7e3..46d58093 100644 --- a/src/lib/platform/XWindowsClipboard.cpp +++ b/src/lib/platform/XWindowsClipboard.cpp @@ -18,21 +18,22 @@ #include "platform/XWindowsClipboard.h" -#include "platform/XWindowsClipboardTextConverter.h" -#include "platform/XWindowsClipboardUCS2Converter.h" -#include "platform/XWindowsClipboardUTF8Converter.h" -#include "platform/XWindowsClipboardHTMLConverter.h" -#include "platform/XWindowsClipboardBMPConverter.h" -#include "platform/XWindowsUtil.h" -#include "mt/Thread.h" #include "arch/Arch.h" #include "base/Log.h" #include "base/Stopwatch.h" #include "common/stdvector.h" +#include "mt/Thread.h" +#include "platform/XWindowsClipboardBMPConverter.h" +#include "platform/XWindowsClipboardHTMLConverter.h" +#include "platform/XWindowsClipboardTextConverter.h" +#include "platform/XWindowsClipboardUCS2Converter.h" +#include "platform/XWindowsClipboardUTF8Converter.h" +#include "platform/XWindowsUtil.h" -#include -#include #include +#include +#include +#include // // XWindowsClipboard @@ -176,7 +177,7 @@ XWindowsClipboard::addSimpleRequest(Window requestor, } else { IXWindowsClipboardConverter* converter = getConverter(target); - if (converter != NULL) { + if (converter != nullptr) { IClipboard::EFormat clipboardFormat = converter->getFormat(); if (m_added[clipboardFormat]) { try { @@ -198,19 +199,19 @@ XWindowsClipboard::addSimpleRequest(Window requestor, property, data, type, format)); return true; } - else { + // failure LOG((CLOG_DEBUG1 "failed")); insertReply(new Reply(requestor, target, time)); return false; - } + } bool XWindowsClipboard::processRequest(Window requestor, ::Time /*time*/, Atom property) { - ReplyMap::iterator index = m_replies.find(requestor); + auto index = m_replies.find(requestor); if (index == m_replies.end()) { // unknown requestor window return false; @@ -220,7 +221,7 @@ XWindowsClipboard::processRequest(Window requestor, // find the property in the known requests. it should be the // first property but we'll check 'em all if we have to. ReplyList& replies = index->second; - for (ReplyList::iterator index2 = replies.begin(); + for (auto index2 = replies.begin(); index2 != replies.end(); ++index2) { Reply* reply = *index2; if (reply->m_replied && reply->m_property == property) { @@ -237,7 +238,7 @@ XWindowsClipboard::processRequest(Window requestor, bool XWindowsClipboard::destroyRequest(Window requestor) { - ReplyMap::iterator index = m_replies.find(requestor); + auto index = m_replies.find(requestor); if (index == m_replies.end()) { // unknown requestor window return false; @@ -394,9 +395,8 @@ XWindowsClipboard::get(EFormat format) const void XWindowsClipboard::clearConverters() { - for (ConverterList::iterator index = m_converters.begin(); - index != m_converters.end(); ++index) { - delete *index; + for (auto & m_converter : m_converters) { + delete m_converter; } m_converters.clear(); } @@ -404,24 +404,23 @@ XWindowsClipboard::clearConverters() IXWindowsClipboardConverter* XWindowsClipboard::getConverter(Atom target, bool onlyIfNotAdded) const { - IXWindowsClipboardConverter* converter = NULL; - for (ConverterList::const_iterator index = m_converters.begin(); - index != m_converters.end(); ++index) { - converter = *index; + IXWindowsClipboardConverter* converter = nullptr; + for (auto m_converter : m_converters) { + converter = m_converter; if (converter->getAtom() == target) { break; } } - if (converter == NULL) { + if (converter == nullptr) { LOG((CLOG_DEBUG1 " no converter for target %s", XWindowsUtil::atomToString(m_display, target).c_str())); - return NULL; + return nullptr; } // optionally skip already handled targets if (onlyIfNotAdded) { if (m_added[converter->getFormat()]) { LOG((CLOG_DEBUG1 " skipping handled format %d", converter->getFormat())); - return NULL; + return nullptr; } } @@ -517,7 +516,7 @@ XWindowsClipboard::icccmFillCache() } XWindowsUtil::convertAtomProperty(data); - const Atom* targets = reinterpret_cast(data.data()); // TODO: Safe? + const auto* targets = reinterpret_cast(data.data()); // TODO(andrew): Safe? const UInt32 numTargets = data.size() / sizeof(Atom); LOG((CLOG_DEBUG " available targets: %s", XWindowsUtil::atomsToString(m_display, targets, numTargets).c_str())); @@ -581,7 +580,7 @@ XWindowsClipboard::icccmGetSelection(Atom target, LOGC(getter.m_error, (CLOG_WARN "ICCCM violation by clipboard owner")); return false; } - else if (*actualTarget == None) { + if (*actualTarget == None) { LOG((CLOG_DEBUG1 "selection conversion failed for target %s", XWindowsUtil::atomToString(m_display, target).c_str())); return false; } @@ -599,11 +598,11 @@ XWindowsClipboard::icccmGetTime() const LOG((CLOG_DEBUG1 "got ICCCM time %d", time)); return time; } - else { + // no timestamp LOG((CLOG_DEBUG1 "can't get ICCCM time")); return 0; - } + } bool @@ -673,7 +672,7 @@ XWindowsClipboard::motifOwnsClipboard() const // check the owner window against the current clipboard owner if (data.size() >= sizeof(MotifClipHeader)) { - MotifClipHeader header; + MotifClipHeader header{}; std::memcpy (&header, data.data(), sizeof(header)); if ((header.m_id == kMotifClipHeader) && (static_cast(header.m_selectionOwner) == owner)) { @@ -700,7 +699,7 @@ XWindowsClipboard::motifFillCache() return; } - MotifClipHeader header; + MotifClipHeader header{}; if (data.size() < sizeof(header)) { // check that the header is okay return; } @@ -720,7 +719,7 @@ XWindowsClipboard::motifFillCache() return; } - MotifClipItem item; + MotifClipItem item{}; if (data.size() < sizeof(item)) { // check that the item is okay return; } @@ -732,7 +731,7 @@ XWindowsClipboard::motifFillCache() // format list is after static item structure elements const SInt32 numFormats = item.m_numFormats - item.m_numDeletedFormats; - const SInt32* formats = reinterpret_cast(item.m_size + + const auto* formats = reinterpret_cast(item.m_size + static_cast(data.data())); // get the available formats @@ -750,7 +749,7 @@ XWindowsClipboard::motifFillCache() } // check that the format is okay - MotifClipFormat motifFormat; + MotifClipFormat motifFormat{}; if (data.size() < sizeof(motifFormat)) { continue; } @@ -786,7 +785,7 @@ XWindowsClipboard::motifFillCache() } // get format - MotifClipFormat motifFormat; + MotifClipFormat motifFormat{}; std::memcpy (&motifFormat, index2->second.data(), sizeof(motifFormat)); const Atom target = motifFormat.m_type; @@ -828,7 +827,7 @@ XWindowsClipboard::motifGetSelection(const MotifClipFormat* format, Window root = RootWindow(m_display, DefaultScreen(m_display)); return XWindowsUtil::getWindowProperty(m_display, root, target, data, - actualTarget, NULL, False); + actualTarget, nullptr, False); } IClipboard::Time @@ -858,7 +857,7 @@ XWindowsClipboard::insertMultipleReply(Window requestor, // data is a list of atom pairs: target, property XWindowsUtil::convertAtomProperty(data); - const Atom* targets = reinterpret_cast(data.data()); + const auto* targets = reinterpret_cast(data.data()); const UInt32 numTargets = data.size() / sizeof(Atom); // add replies for each target @@ -918,7 +917,7 @@ XWindowsClipboard::insertReply(Reply* reply) XWindowsUtil::ErrorLock lock(m_display, &error); // get and save the current event mask - XWindowAttributes attr; + XWindowAttributes attr{}; XGetWindowAttributes(m_display, reply->m_requestor, &attr); m_eventMasks[reply->m_requestor] = attr.your_event_mask; @@ -940,13 +939,14 @@ XWindowsClipboard::pushReplies() { // send the first reply for each window if that reply hasn't // been sent yet. - for (ReplyMap::iterator index = m_replies.begin(); + for (auto index = m_replies.begin(); index != m_replies.end(); ) { assert(!index->second.empty()); - ReplyList::iterator listit = index->second.begin(); + auto listit = index->second.begin(); while (listit != index->second.end()) { - if (!(*listit)->m_replied) + if (!(*listit)->m_replied) { break; +} ++listit; } if (listit != index->second.end() && !(*listit)->m_replied) { @@ -1023,8 +1023,9 @@ XWindowsClipboard::sendReply(Reply* reply) else { // how much more data should we send? UInt32 size = reply->m_data.size() - reply->m_ptr; - if (size > maxRequestSize) + if (size > maxRequestSize) { size = maxRequestSize; +} // send it if (!XWindowsUtil::setWindowProperty(m_display, @@ -1066,7 +1067,7 @@ XWindowsClipboard::sendReply(Reply* reply) // don't wait for any reply (because we're not expecting one) return true; } - else { + static const char dummy = 0; XWindowsUtil::setWindowProperty(m_display, reply->m_requestor, reply->m_property, @@ -1076,7 +1077,7 @@ XWindowsClipboard::sendReply(Reply* reply) // wait for delete notify return false; - } + } // send notification if we haven't yet @@ -1099,7 +1100,7 @@ XWindowsClipboard::sendReply(Reply* reply) char* name = XGetAtomName(m_display, props[i]); if (!XWindowsUtil::getWindowProperty(m_display, reply->m_requestor, - props[i], &data, &target, NULL, False)) { + props[i], &data, &target, nullptr, False)) { LOG((CLOG_DEBUG2 " %s: ", name)); } else { @@ -1111,7 +1112,7 @@ XWindowsClipboard::sendReply(Reply* reply) String tmp; tmp.reserve(data.size() * 3); for (j = 0; j < data.size(); ++j) { - unsigned char v = (unsigned char)data[j]; + auto v = static_cast(data[j]); tmp += hex[v >> 16]; tmp += hex[v & 15]; tmp += ' '; @@ -1122,15 +1123,15 @@ XWindowsClipboard::sendReply(Reply* reply) } char* type = XGetAtomName(m_display, target); LOG((CLOG_DEBUG2 " %s (%s): %s", name, type, data.c_str())); - if (type != NULL) { + if (type != nullptr) { XFree(type); } } - if (name != NULL) { + if (name != nullptr) { XFree(name); } } - if (props != NULL) { + if (props != nullptr) { XFree(props); } } @@ -1147,9 +1148,8 @@ XWindowsClipboard::sendReply(Reply* reply) void XWindowsClipboard::clearReplies() { - for (ReplyMap::iterator index = m_replies.begin(); - index != m_replies.end(); ++index) { - clearReplies(index->second); + for (auto & m_replie : m_replies) { + clearReplies(m_replie.second); } m_replies.clear(); m_eventMasks.clear(); @@ -1158,9 +1158,8 @@ XWindowsClipboard::clearReplies() void XWindowsClipboard::clearReplies(ReplyList& replies) { - for (ReplyList::iterator index = replies.begin(); - index != replies.end(); ++index) { - delete *index; + for (auto & replie : replies) { + delete replie; } replies.clear(); } @@ -1169,7 +1168,7 @@ void XWindowsClipboard::sendNotify(Window requestor, Atom selection, Atom target, Atom property, Time time) { - XEvent event; + XEvent event{}; event.xselection.type = SelectionNotify; event.xselection.display = m_display; event.xselection.requestor = requestor; @@ -1199,9 +1198,9 @@ XWindowsClipboard::wasOwnedAtTime(::Time time) const if (time == CurrentTime) { return true; } - else { + lost = XWindowsUtil::getCurrentTime(m_display, m_window); - } + } else { if (time == CurrentTime) { @@ -1226,10 +1225,7 @@ XWindowsClipboard::getTargetsData(String& data, int* format) const XWindowsUtil::appendAtomData(data, m_atomTimestamp); // add targets we can convert to - for (ConverterList::const_iterator index = m_converters.begin(); - index != m_converters.end(); ++index) { - IXWindowsClipboardConverter* converter = *index; - + for (auto converter : m_converters) { // skip formats we don't have if (m_added[converter->getFormat()]) { XWindowsUtil::appendAtomData(data, converter->getAtom()); @@ -1265,8 +1261,8 @@ XWindowsClipboard::CICCCMGetClipboard::CICCCMGetClipboard( m_failed(false), m_done(false), m_reading(false), - m_data(NULL), - m_actualTarget(NULL), + m_data(nullptr), + m_actualTarget(nullptr), m_error(false) { // do nothing @@ -1301,7 +1297,7 @@ XWindowsClipboard::CICCCMGetClipboard::readClipboard(Display* display, XDeleteProperty(display, m_requestor, m_property); // select window for property changes - XWindowAttributes attr; + XWindowAttributes attr{}; XGetWindowAttributes(display, m_requestor, &attr); XSelectInput(display, m_requestor, attr.your_event_mask | PropertyChangeMask); @@ -1318,7 +1314,7 @@ XWindowsClipboard::CICCCMGetClipboard::readClipboard(Display* display, // to do it.) we'll poll until we have what we're looking for or // a timeout expires. we use a timeout so we don't get locked up // by badly behaved selection owners. - XEvent xevent; + XEvent xevent{}; std::vector events; Stopwatch timeout(false); // timer not stopped, not triggered static const double s_timeout = 0.25; // FIXME -- is this too short? @@ -1393,7 +1389,7 @@ XWindowsClipboard::CICCCMGetClipboard::processEvent( } // proceed if conversion successful - else if (xevent->xselection.property == m_property) { + if (xevent->xselection.property == m_property) { m_reading = true; break; } @@ -1426,7 +1422,7 @@ XWindowsClipboard::CICCCMGetClipboard::processEvent( Atom target; const String::size_type oldSize = m_data->size(); if (!XWindowsUtil::getWindowProperty(display, m_requestor, - m_property, m_data, &target, NULL, True)) { + m_property, m_data, &target, nullptr, True)) { // unable to read property m_failed = true; return true; @@ -1500,7 +1496,6 @@ XWindowsClipboard::Reply::Reply(Window requestor, Atom target, ::Time time) : m_property(None), m_replied(false), m_done(false), - m_data(), m_type(None), m_format(32), m_ptr(0) @@ -1509,14 +1504,14 @@ XWindowsClipboard::Reply::Reply(Window requestor, Atom target, ::Time time) : } XWindowsClipboard::Reply::Reply(Window requestor, Atom target, ::Time time, - Atom property, const String& data, Atom type, int format) : + Atom property, String data, Atom type, int format) : m_requestor(requestor), m_target(target), m_time(time), m_property(property), m_replied(false), m_done(false), - m_data(data), + m_data(std::move(data)), m_type(type), m_format(format), m_ptr(0) diff --git a/src/lib/platform/XWindowsClipboard.h b/src/lib/platform/XWindowsClipboard.h index 7d65579b..9e4176c7 100644 --- a/src/lib/platform/XWindowsClipboard.h +++ b/src/lib/platform/XWindowsClipboard.h @@ -149,7 +149,7 @@ private: Atom* actualTarget, String* data); private: - bool processEvent(Display* display, XEvent* event); + bool processEvent(Display* display, XEvent* xevent); private: Window m_requestor; @@ -160,8 +160,8 @@ private: bool m_done; // atoms needed for the protocol - Atom m_atomNone; // NONE, not None - Atom m_atomIncr; + Atom m_atomNone{}; // NONE, not None + Atom m_atomIncr{}; // true iff we've received the selection notify bool m_reading; @@ -223,7 +223,7 @@ private: public: Reply(Window, Atom target, ::Time); Reply(Window, Atom target, ::Time, Atom property, - const String& data, Atom type, int format); + String data, Atom type, int format); public: // information about the request @@ -296,13 +296,13 @@ private: Time m_timeLost; // true iff open and clipboard owned by a motif app - mutable bool m_motif; + mutable bool m_motif{}; // the added/cached clipboard data - mutable bool m_checkCache; - bool m_cached; - Time m_cacheTime; - bool m_added[kNumFormats]; + mutable bool m_checkCache{}; + bool m_cached{}; + Time m_cacheTime{}; + bool m_added[kNumFormats]{}; String m_data[kNumFormats]; // conversion request replies diff --git a/src/lib/platform/XWindowsClipboardAnyBitmapConverter.cpp b/src/lib/platform/XWindowsClipboardAnyBitmapConverter.cpp index 4c18b537..964d2070 100644 --- a/src/lib/platform/XWindowsClipboardAnyBitmapConverter.cpp +++ b/src/lib/platform/XWindowsClipboardAnyBitmapConverter.cpp @@ -126,8 +126,8 @@ String XWindowsClipboardAnyBitmapConverter::fromIClipboard(const String& bmp) const { // fill BMP info header with native-endian data - CBMPInfoHeader infoHeader; - const UInt8* rawBMPInfoHeader = reinterpret_cast(bmp.data()); + CBMPInfoHeader infoHeader{}; + const auto* rawBMPInfoHeader = reinterpret_cast(bmp.data()); infoHeader.biSize = fromLEU32(rawBMPInfoHeader + 0); infoHeader.biWidth = fromLES32(rawBMPInfoHeader + 4); infoHeader.biHeight = fromLES32(rawBMPInfoHeader + 8); @@ -154,10 +154,10 @@ XWindowsClipboardAnyBitmapConverter::fromIClipboard(const String& bmp) const return doBGRFromIClipboard(rawBMPPixels, infoHeader.biWidth, infoHeader.biHeight); } - else { + return doBGRAFromIClipboard(rawBMPPixels, infoHeader.biWidth, infoHeader.biHeight); - } + } String diff --git a/src/lib/platform/XWindowsClipboardBMPConverter.cpp b/src/lib/platform/XWindowsClipboardBMPConverter.cpp index 22c6dcbe..86c02699 100644 --- a/src/lib/platform/XWindowsClipboardBMPConverter.cpp +++ b/src/lib/platform/XWindowsClipboardBMPConverter.cpp @@ -125,7 +125,7 @@ XWindowsClipboardBMPConverter::toIClipboard(const String& bmp) const } // check BMP file header - const UInt8* rawBMPHeader = reinterpret_cast(bmp.data()); + const auto* rawBMPHeader = reinterpret_cast(bmp.data()); if (rawBMPHeader[0] != 'B' || rawBMPHeader[1] != 'M') { return String(); } @@ -137,7 +137,7 @@ XWindowsClipboardBMPConverter::toIClipboard(const String& bmp) const if (offset == 14 + 40) { return bmp.substr(14); } - else { + return bmp.substr(14, 40) + bmp.substr(offset, bmp.size() - offset); - } + } diff --git a/src/lib/platform/XWindowsEventQueueBuffer.cpp b/src/lib/platform/XWindowsEventQueueBuffer.cpp index 71e2cfba..3bdaa557 100644 --- a/src/lib/platform/XWindowsEventQueueBuffer.cpp +++ b/src/lib/platform/XWindowsEventQueueBuffer.cpp @@ -18,10 +18,10 @@ #include "platform/XWindowsEventQueueBuffer.h" -#include "mt/Lock.h" -#include "mt/Thread.h" #include "base/Event.h" #include "base/IEventQueue.h" +#include "mt/Lock.h" +#include "mt/Thread.h" #include #if HAVE_UNISTD_H @@ -165,7 +165,7 @@ XWindowsEventQueueBuffer::waitForEvent(double dtimeout) while (((dtimeout < 0.0) || (remaining > 0)) && QLength(m_display)==0 && retval==0){ #if HAVE_POLL retval = poll(pfds, 2, TIMEOUT_DELAY); //16ms = 60hz, but we make it > to play nicely with the cpu - if (pfds[1].revents & POLLIN) { + if ((pfds[1].revents & POLLIN) != 0) { ssize_t read_response = read(m_pipefd[0], buf, 15); // with linux automake, warnings are treated as errors by default @@ -214,18 +214,18 @@ XWindowsEventQueueBuffer::getEvent(Event& event, UInt32& dataID) dataID = static_cast(m_event.xclient.data.l[0]); return kUser; } - else { + event = Event(Event::kSystem, m_events->getSystemTarget(), &m_event); return kSystem; - } + } bool XWindowsEventQueueBuffer::addEvent(UInt32 dataID) { // prepare a message - XEvent xevent; + XEvent xevent{}; xevent.xclient.type = ClientMessage; xevent.xclient.window = m_window; xevent.xclient.message_type = m_userEvent; @@ -266,7 +266,7 @@ XWindowsEventQueueBuffer::isEmpty() const } EventQueueTimer* -XWindowsEventQueueBuffer::newTimer(double, bool) const +XWindowsEventQueueBuffer::newTimer(double /*duration*/, bool /*oneShot*/) const { return new EventQueueTimer; } @@ -283,8 +283,8 @@ XWindowsEventQueueBuffer::flush() // note -- m_mutex must be locked on entry // flush the posted event list to the X server - for (size_t i = 0; i < m_postedEvents.size(); ++i) { - XSendEvent(m_display, m_window, False, 0, &m_postedEvents[i]); + for (auto & m_postedEvent : m_postedEvents) { + XSendEvent(m_display, m_window, False, 0, &m_postedEvent); } XFlush(m_display); m_postedEvents.clear(); diff --git a/src/lib/platform/XWindowsEventQueueBuffer.h b/src/lib/platform/XWindowsEventQueueBuffer.h index 7614deea..9907b84f 100644 --- a/src/lib/platform/XWindowsEventQueueBuffer.h +++ b/src/lib/platform/XWindowsEventQueueBuffer.h @@ -38,7 +38,7 @@ public: // IEventQueueBuffer overrides virtual void init() { } - virtual void waitForEvent(double timeout); + virtual void waitForEvent(double dtimeout); virtual Type getEvent(Event& event, UInt32& dataID); virtual bool addEvent(UInt32 dataID); virtual bool isEmpty() const; @@ -56,9 +56,9 @@ private: Display* m_display; Window m_window; Atom m_userEvent; - XEvent m_event; + XEvent m_event{}; EventList m_postedEvents; bool m_waiting; - int m_pipefd[2]; + int m_pipefd[2]{}; IEventQueue* m_events; }; diff --git a/src/lib/platform/XWindowsKeyState.cpp b/src/lib/platform/XWindowsKeyState.cpp index f9dc722d..2b093eb7 100644 --- a/src/lib/platform/XWindowsKeyState.cpp +++ b/src/lib/platform/XWindowsKeyState.cpp @@ -18,13 +18,13 @@ #include "platform/XWindowsKeyState.h" -#include "platform/XWindowsUtil.h" #include "base/Log.h" #include "base/String.h" #include "common/stdmap.h" +#include "platform/XWindowsUtil.h" -#include #include +#include #if X_DISPLAY_MISSING # error X11 is required to build synergy #else @@ -63,14 +63,14 @@ XWindowsKeyState::XWindowsKeyState( XWindowsKeyState::~XWindowsKeyState() { #if HAVE_XKB_EXTENSION - if (m_xkb != NULL) { + if (m_xkb != nullptr) { XkbFreeKeyboard(m_xkb, 0, True); } #endif } void -XWindowsKeyState::init(Display* display, bool useXKB) +XWindowsKeyState::init(Display* /*display*/, bool useXKB) { XGetKeyboardControl(m_display, &m_keyboardState); #if HAVE_XKB_EXTENSION @@ -79,7 +79,7 @@ XWindowsKeyState::init(Display* display, bool useXKB) XkbAllClientInfoMask, XkbUseCoreKbd); } else { - m_xkb = NULL; + m_xkb = nullptr; } #endif setActiveGroup(kGroupPollAndSet); @@ -138,13 +138,13 @@ XWindowsKeyState::mapModifiersToX(KeyModifierMask mask, for (SInt32 i = 0; i < kKeyModifierNumBits; ++i) { KeyModifierMask bit = (1u << i); if ((mask & bit) != 0) { - KeyModifierToXMask::const_iterator j = m_modifierToX.find(bit); + auto j = m_modifierToX.find(bit); if (j == m_modifierToX.end()) { return false; } - else { + modifiers |= j->second; - } + } } @@ -158,7 +158,7 @@ XWindowsKeyState::mapKeyToKeycodes(KeyID key, KeycodeList& keycodes) const std::pair range = m_keyCodeFromKey.equal_range(key); - for (KeyToKeyCodeMap::const_iterator i = range.first; + for (auto i = range.first; i != range.second; ++i) { keycodes.push_back(i->second); } @@ -193,8 +193,8 @@ XWindowsKeyState::pollActiveGroup() const } #if HAVE_XKB_EXTENSION - if (m_xkb != NULL) { - XkbStateRec state; + if (m_xkb != nullptr) { + XkbStateRec state{}; if (XkbGetState(m_display, XkbUseCoreKbd, &state) == Success) { return state.group; } @@ -227,7 +227,7 @@ XWindowsKeyState::getKeyMap(synergy::KeyMap& keyMap) m_keyboardState.global_auto_repeat = oldGlobalAutoRepeat; #if HAVE_XKB_EXTENSION - if (m_xkb != NULL) { + if (m_xkb != nullptr) { if (XkbGetUpdatedMap(m_display, XkbKeyActionsMask | XkbKeyBehaviorsMask | XkbAllClientInfoMask, m_xkb) == Success) { updateKeysymMapXKB(keyMap); @@ -263,7 +263,7 @@ XWindowsKeyState::fakeKey(const Keystroke& keystroke) if (keystroke.m_data.m_group.m_absolute) { LOG((CLOG_DEBUG1 " group %d", keystroke.m_data.m_group.m_group)); #if HAVE_XKB_EXTENSION - if (m_xkb != NULL) { + if (m_xkb != nullptr) { if (XkbLockGroup(m_display, XkbUseCoreKbd, keystroke.m_data.m_group.m_group) == False) { LOG((CLOG_DEBUG1 "XkbLockGroup request not sent")); @@ -278,7 +278,7 @@ XWindowsKeyState::fakeKey(const Keystroke& keystroke) else { LOG((CLOG_DEBUG1 " group %+d", keystroke.m_data.m_group.m_group)); #if HAVE_XKB_EXTENSION - if (m_xkb != NULL) { + if (m_xkb != nullptr) { if (XkbLockGroup(m_display, XkbUseCoreKbd, getEffectiveGroup(pollActiveGroup(), keystroke.m_data.m_group.m_group)) == False) { @@ -331,7 +331,7 @@ XWindowsKeyState::updateKeysymMap(synergy::KeyMap& keyMap) // it's more convenient to always have maxKeysyms KeySyms per key { - KeySym* tmpKeysyms = new KeySym[maxKeysyms * numKeycodes]; + auto* tmpKeysyms = new KeySym[maxKeysyms * numKeycodes]; for (int i = 0; i < numKeycodes; ++i) { for (int j = 0; j < maxKeysyms; ++j) { if (j < keysymsPerKeycode) { @@ -391,10 +391,10 @@ XWindowsKeyState::updateKeysymMap(synergy::KeyMap& keyMap) } // add entries for each keycode - synergy::KeyMap::KeyItem item; + synergy::KeyMap::KeyItem item{}; for (int i = 0; i < numKeycodes; ++i) { KeySym* keysyms = allKeysyms + maxKeysyms * i; - KeyCode keycode = static_cast(i + minKeycode); + auto keycode = static_cast(i + minKeycode); item.m_button = static_cast(keycode); item.m_client = 0; @@ -589,9 +589,9 @@ XWindowsKeyState::updateKeysymMapXKB(synergy::KeyMap& keyMap) // check every button. on this pass we save all modifiers as native // X modifier masks. - synergy::KeyMap::KeyItem item; + synergy::KeyMap::KeyItem item{}; for (int i = m_xkb->min_key_code; i <= m_xkb->max_key_code; ++i) { - KeyCode keycode = static_cast(i); + auto keycode = static_cast(i); item.m_button = static_cast(keycode); item.m_client = 0; @@ -621,7 +621,7 @@ XWindowsKeyState::updateKeysymMapXKB(synergy::KeyMap& keyMap) for (int j = -1; j < type->map_count; ++j) { const XkbKTMapEntryRec* mapEntry = ((j == -1) ? &defMapEntry : type->map + j); - if (!mapEntry->active) { + if (mapEntry->active == 0) { continue; } int level = mapEntry->level; @@ -629,7 +629,7 @@ XWindowsKeyState::updateKeysymMapXKB(synergy::KeyMap& keyMap) // set required modifiers for this item item.m_required = mapEntry->mods.mask; if ((item.m_required & LockMask) != 0 && - j != -1 && type->preserve != NULL && + j != -1 && type->preserve != nullptr && (type->preserve[j].mask & LockMask) != 0) { // sensitive caps lock and we preserve caps-lock. // preserving caps-lock means we Xlib functions would @@ -782,10 +782,10 @@ XWindowsKeyState::updateKeysymMapXKB(synergy::KeyMap& keyMap) #endif void -XWindowsKeyState::remapKeyModifiers(KeyID id, SInt32 group, +XWindowsKeyState::remapKeyModifiers(KeyID /*id*/, SInt32 group, synergy::KeyMap::KeyItem& item, void* vself) { - XWindowsKeyState* self = static_cast(vself); + auto* self = static_cast(vself); item.m_required = self->mapModifiersFromX(XkbBuildCoreState(item.m_required, group)); item.m_sensitive = @@ -798,7 +798,7 @@ XWindowsKeyState::hasModifiersXKB() const #if HAVE_XKB_EXTENSION // iterate over all keycodes for (int i = m_xkb->min_key_code; i <= m_xkb->max_key_code; ++i) { - KeyCode keycode = static_cast(i); + auto keycode = static_cast(i); if (XkbKeyHasActions(m_xkb, keycode) == True) { // iterate over all groups int numGroups = XkbKeyNumGroups(m_xkb, keycode); @@ -806,7 +806,7 @@ XWindowsKeyState::hasModifiersXKB() const // iterate over all shift levels for the button (including none) XkbKeyTypePtr type = XkbKeyKeyType(m_xkb, keycode, group); for (int j = -1; j < type->map_count; ++j) { - if (j != -1 && !type->map[j].active) { + if (j != -1 && (type->map[j].active == 0)) { continue; } int level = ((j == -1) ? 0 : type->map[j].level); @@ -859,7 +859,7 @@ UInt32 XWindowsKeyState::getGroupFromState(unsigned int state) const { #if HAVE_XKB_EXTENSION - if (m_xkb != NULL) { + if (m_xkb != nullptr) { return XkbGroupForCoreState(state); } #endif diff --git a/src/lib/platform/XWindowsKeyState.h b/src/lib/platform/XWindowsKeyState.h index a47c2c59..517700ff 100644 --- a/src/lib/platform/XWindowsKeyState.h +++ b/src/lib/platform/XWindowsKeyState.h @@ -147,9 +147,9 @@ private: Display* m_display; #if HAVE_XKB_EXTENSION - XkbDescPtr m_xkb; + XkbDescPtr m_xkb{}; #endif - SInt32 m_group; + SInt32 m_group{}; XKBModifierMap m_lastGoodXKBModifiers; NonXKBModifierMap m_lastGoodNonXKBModifiers; @@ -163,7 +163,7 @@ private: KeyToKeyCodeMap m_keyCodeFromKey; // autorepeat state - XKeyboardState m_keyboardState; + XKeyboardState m_keyboardState{}; #ifdef TEST_ENV public: diff --git a/src/lib/platform/XWindowsScreen.cpp b/src/lib/platform/XWindowsScreen.cpp index de8766aa..2516ba42 100644 --- a/src/lib/platform/XWindowsScreen.cpp +++ b/src/lib/platform/XWindowsScreen.cpp @@ -18,25 +18,25 @@ #include "platform/XWindowsScreen.h" +#include "arch/Arch.h" +#include "arch/XArch.h" +#include "base/IEventQueue.h" +#include "base/Log.h" +#include "base/Stopwatch.h" +#include "base/String.h" +#include "base/TMethodEventJob.h" +#include "core/Clipboard.h" +#include "core/KeyMap.h" +#include "core/XScreen.h" #include "platform/XWindowsClipboard.h" #include "platform/XWindowsEventQueueBuffer.h" #include "platform/XWindowsKeyState.h" #include "platform/XWindowsScreenSaver.h" #include "platform/XWindowsUtil.h" -#include "core/Clipboard.h" -#include "core/KeyMap.h" -#include "core/XScreen.h" -#include "arch/XArch.h" -#include "arch/Arch.h" -#include "base/Log.h" -#include "base/Stopwatch.h" -#include "base/String.h" -#include "base/IEventQueue.h" -#include "base/TMethodEventJob.h" -#include -#include #include +#include +#include #if X_DISPLAY_MISSING # error X11 is required to build synergy #else @@ -89,7 +89,7 @@ static int xi_opcode; // display and the X11 event queue buffer, ignore any calls that try // to use the display, and wait to be destroyed. -XWindowsScreen* XWindowsScreen::s_screen = NULL; +XWindowsScreen* XWindowsScreen::s_screen = nullptr; XWindowsScreen::XWindowsScreen( const char* displayName, @@ -99,7 +99,7 @@ XWindowsScreen::XWindowsScreen( IEventQueue* events) : m_isPrimary(isPrimary), m_mouseScrollDelta(mouseScrollDelta), - m_display(NULL), + m_display(nullptr), m_root(None), m_window(None), m_isOnScreen(true), @@ -107,14 +107,14 @@ XWindowsScreen::XWindowsScreen( m_w(0), m_h(0), m_xCenter(0), m_yCenter(0), m_xCursor(0), m_yCursor(0), - m_keyState(NULL), + m_keyState(nullptr), m_lastFocus(None), m_lastFocusRevert(RevertToNone), - m_im(NULL), - m_ic(NULL), + m_im(nullptr), + m_ic(nullptr), m_lastKeycode(0), m_sequenceNumber(0), - m_screensaver(NULL), + m_screensaver(nullptr), m_screensaverNotify(false), m_xtestIsXineramaUnaware(true), m_preserveFocus(false), @@ -126,13 +126,15 @@ XWindowsScreen::XWindowsScreen( { assert(s_screen == NULL); - if (mouseScrollDelta==0) m_mouseScrollDelta=120; + if (mouseScrollDelta==0) { m_mouseScrollDelta=120; +} s_screen = this; if (!disableXInitThreads) { // initializes Xlib support for concurrent threads. - if (XInitThreads() == 0) + if (XInitThreads() == 0) { throw XArch("XInitThreads() returned zero"); +} } else { LOG((CLOG_DEBUG "skipping XInitThreads()")); } @@ -152,7 +154,7 @@ XWindowsScreen::XWindowsScreen( LOG((CLOG_DEBUG "window is 0x%08x", m_window)); } catch (...) { - if (m_display != NULL) { + if (m_display != nullptr) { XCloseDisplay(m_display); } throw; @@ -197,28 +199,28 @@ XWindowsScreen::~XWindowsScreen() assert(s_screen != NULL); assert(m_display != NULL); - m_events->adoptBuffer(NULL); + m_events->adoptBuffer(nullptr); m_events->removeHandler(Event::kSystem, m_events->getSystemTarget()); - for (ClipboardID id = 0; id < kClipboardEnd; ++id) { - delete m_clipboard[id]; + for (auto & id : m_clipboard) { + delete id; } delete m_keyState; delete m_screensaver; - m_keyState = NULL; - m_screensaver = NULL; - if (m_display != NULL) { + m_keyState = nullptr; + m_screensaver = nullptr; + if (m_display != nullptr) { // FIXME -- is it safe to clean up the IC and IM without a display? - if (m_ic != NULL) { + if (m_ic != nullptr) { XDestroyIC(m_ic); } - if (m_im != NULL) { + if (m_im != nullptr) { XCloseIM(m_im); } XDestroyWindow(m_display, m_window); XCloseDisplay(m_display); } - XSetIOErrorHandler(NULL); + XSetIOErrorHandler(nullptr); - s_screen = NULL; + s_screen = nullptr; } void @@ -226,7 +228,7 @@ XWindowsScreen::enable() { if (!m_isPrimary) { // get the keyboard control state - XKeyboardState keyControl; + XKeyboardState keyControl{}; XGetKeyboardControl(m_display, &keyControl); m_autoRepeat = (keyControl.global_auto_repeat == AutoRepeatModeOn); m_keyState->setAutoRepeat(keyControl); @@ -247,7 +249,7 @@ void XWindowsScreen::disable() { // release input context focus - if (m_ic != NULL) { + if (m_ic != nullptr) { XUnsetICFocus(m_ic); } @@ -267,7 +269,7 @@ XWindowsScreen::enter() screensaver(false); // release input context focus - if (m_ic != NULL) { + if (m_ic != nullptr) { XUnsetICFocus(m_ic); } @@ -284,12 +286,13 @@ XWindowsScreen::enter() int dummy; CARD16 powerlevel; BOOL enabled; - if (DPMSQueryExtension(m_display, &dummy, &dummy) && - DPMSCapable(m_display) && - DPMSInfo(m_display, &powerlevel, &enabled)) + if ((DPMSQueryExtension(m_display, &dummy, &dummy) != 0) && + (DPMSCapable(m_display) != 0) && + (DPMSInfo(m_display, &powerlevel, &enabled) != 0)) { - if (enabled && powerlevel != DPMSModeOn) + if ((enabled != 0u) && powerlevel != DPMSModeOn) { DPMSForceLevel(m_display, DPMSModeOn); +} } #endif @@ -305,7 +308,7 @@ XWindowsScreen::enter() if (!m_isPrimary) { // get the keyboard control state - XKeyboardState keyControl; + XKeyboardState keyControl{}; XGetKeyboardControl(m_display, &keyControl); m_autoRepeat = (keyControl.global_auto_repeat == AutoRepeatModeOn); m_keyState->setAutoRepeat(keyControl); @@ -360,7 +363,7 @@ XWindowsScreen::leave() warpCursor(m_xCenter, m_yCenter); // set input context focus to our window - if (m_ic != NULL) { + if (m_ic != nullptr) { XmbResetIC(m_ic); XSetICFocus(m_ic); m_filtered.clear(); @@ -376,7 +379,7 @@ bool XWindowsScreen::setClipboard(ClipboardID id, const IClipboard* clipboard) { // fail if we don't have the requested clipboard - if (m_clipboard[id] == NULL) { + if (m_clipboard[id] == nullptr) { return false; } @@ -384,11 +387,11 @@ XWindowsScreen::setClipboard(ClipboardID id, const IClipboard* clipboard) Time timestamp = XWindowsUtil::getCurrentTime( m_display, m_clipboard[id]->getWindow()); - if (clipboard != NULL) { + if (clipboard != nullptr) { // save clipboard data return Clipboard::copy(m_clipboard[id], clipboard, timestamp); } - else { + // assert clipboard ownership if (!m_clipboard[id]->open(timestamp)) { return false; @@ -396,7 +399,7 @@ XWindowsScreen::setClipboard(ClipboardID id, const IClipboard* clipboard) m_clipboard[id]->empty(); m_clipboard[id]->close(); return true; - } + } void @@ -479,7 +482,7 @@ XWindowsScreen::getClipboard(ClipboardID id, IClipboard* clipboard) const assert(clipboard != NULL); // fail if we don't have the requested clipboard - if (m_clipboard[id] == NULL) { + if (m_clipboard[id] == nullptr) { return false; } @@ -507,7 +510,7 @@ XWindowsScreen::getCursorPos(SInt32& x, SInt32& y) const int mx, my, xWindow, yWindow; unsigned int mask; if (XQueryPointer(m_display, m_root, &root, &window, - &mx, &my, &xWindow, &yWindow, &mask)) { + &mx, &my, &xWindow, &yWindow, &mask) != 0) { x = mx; y = my; } @@ -518,7 +521,7 @@ XWindowsScreen::getCursorPos(SInt32& x, SInt32& y) const } void -XWindowsScreen::reconfigure(UInt32) +XWindowsScreen::reconfigure(UInt32 /*activeSides*/) { // do nothing } @@ -530,12 +533,12 @@ XWindowsScreen::warpCursor(SInt32 x, SInt32 y) warpCursorNoFlush(x, y); // remove all input events before and including warp - XEvent event; + XEvent event{}; while (XCheckMaskEvent(m_display, PointerMotionMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask | KeymapStateMask, - &event)) { + &event) != 0) { // do nothing } @@ -666,7 +669,7 @@ XWindowsScreen::registerHotKey(KeyID key, KeyModifierMask mask) XGrabKey(m_display, code, modifiers2, m_root, False, GrabModeAsync, GrabModeAsync); if (!err) { - hotKeys.push_back(std::make_pair(code, modifiers2)); + hotKeys.emplace_back(code, modifiers2); m_hotKeyToIDMap[HotKeyItem(code, modifiers2)] = id; } } @@ -694,7 +697,7 @@ XWindowsScreen::registerHotKey(KeyID key, KeyModifierMask mask) } - for (XWindowsKeyState::KeycodeList::iterator j = keycodes.begin(); + for (auto j = keycodes.begin(); j != keycodes.end() && !err; ++j) { for (size_t i = 0; i < (1u << numToggleModifiers); ++i) { // add toggle modifiers for index i @@ -713,7 +716,7 @@ XWindowsScreen::registerHotKey(KeyID key, KeyModifierMask mask) XGrabKey(m_display, *j, tmpModifiers, m_root, False, GrabModeAsync, GrabModeAsync); if (!err) { - hotKeys.push_back(std::make_pair(*j, tmpModifiers)); + hotKeys.emplace_back(*j, tmpModifiers); m_hotKeyToIDMap[HotKeyItem(*j, tmpModifiers)] = id; } } @@ -723,10 +726,9 @@ XWindowsScreen::registerHotKey(KeyID key, KeyModifierMask mask) if (err) { // if any failed then unregister any we did get - for (HotKeyList::iterator j = hotKeys.begin(); - j != hotKeys.end(); ++j) { - XUngrabKey(m_display, j->first, j->second, m_root); - m_hotKeyToIDMap.erase(HotKeyItem(j->first, j->second)); + for (auto & hotKey : hotKeys) { + XUngrabKey(m_display, hotKey.first, hotKey.second, m_root); + m_hotKeyToIDMap.erase(HotKeyItem(hotKey.first, hotKey.second)); } m_oldHotKeyIDs.push_back(id); @@ -743,7 +745,7 @@ void XWindowsScreen::unregisterHotKey(UInt32 id) { // look up hotkey - HotKeyMap::iterator i = m_hotKeys.find(id); + auto i = m_hotKeys.find(id); if (i == m_hotKeys.end()) { return; } @@ -753,10 +755,9 @@ XWindowsScreen::unregisterHotKey(UInt32 id) { XWindowsUtil::ErrorLock lock(m_display, &err); HotKeyList& hotKeys = i->second; - for (HotKeyList::iterator j = hotKeys.begin(); - j != hotKeys.end(); ++j) { - XUngrabKey(m_display, j->first, j->second, m_root); - m_hotKeyToIDMap.erase(HotKeyItem(j->first, j->second)); + for (auto & hotKey : hotKeys) { + XUngrabKey(m_display, hotKey.first, hotKey.second, m_root); + m_hotKeyToIDMap.erase(HotKeyItem(hotKey.first, hotKey.second)); } } if (err) { @@ -790,14 +791,14 @@ XWindowsScreen::getJumpZoneSize() const } bool -XWindowsScreen::isAnyMouseButtonDown(UInt32& buttonID) const +XWindowsScreen::isAnyMouseButtonDown(UInt32& /*buttonID*/) const { // query the pointer to get the button state Window root, window; int xRoot, yRoot, xWindow, yWindow; unsigned int state; if (XQueryPointer(m_display, m_root, &root, &window, - &xRoot, &yRoot, &xWindow, &yWindow, &state)) { + &xRoot, &yRoot, &xWindow, &yWindow, &state) != 0) { return ((state & (Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask)) != 0); } @@ -840,7 +841,7 @@ void XWindowsScreen::fakeMouseRelativeMove(SInt32 dx, SInt32 dy) const { // FIXME -- ignore xinerama for now - if (false && m_xinerama && m_xtestIsXineramaUnaware) { + if (false && m_xtestIsXineramaUnaware) { // XWarpPointer(m_display, None, m_root, 0, 0, 0, 0, x, y); } else { @@ -850,7 +851,7 @@ XWindowsScreen::fakeMouseRelativeMove(SInt32 dx, SInt32 dy) const } void -XWindowsScreen::fakeMouseWheel(SInt32, SInt32 yDelta) const +XWindowsScreen::fakeMouseWheel(SInt32 /*xDelta*/, SInt32 yDelta) const { // XXX -- support x-axis scrolling if (yDelta == 0) { @@ -899,9 +900,9 @@ Display* XWindowsScreen::openDisplay(const char* displayName) { // get the DISPLAY - if (displayName == NULL) { + if (displayName == nullptr) { displayName = getenv("DISPLAY"); - if (displayName == NULL) { + if (displayName == nullptr) { displayName = ":0.0"; } } @@ -909,15 +910,15 @@ XWindowsScreen::openDisplay(const char* displayName) // open the display LOG((CLOG_DEBUG "XOpenDisplay(\"%s\")", displayName)); Display* display = XOpenDisplay(displayName); - if (display == NULL) { + if (display == nullptr) { throw XScreenUnavailable(60.0); } // verify the availability of the XTest extension if (!m_isPrimary) { int majorOpcode, firstEvent, firstError; - if (!XQueryExtension(display, XTestExtensionName, - &majorOpcode, &firstEvent, &firstError)) { + if (XQueryExtension(display, XTestExtensionName, + &majorOpcode, &firstEvent, &firstError) == 0) { LOG((CLOG_ERR "XTEST extension not available")); XCloseDisplay(display); throw XScreenOpenFailure(); @@ -928,10 +929,10 @@ XWindowsScreen::openDisplay(const char* displayName) { m_xkb = false; int major = XkbMajorVersion, minor = XkbMinorVersion; - if (XkbLibraryVersion(&major, &minor)) { + if (XkbLibraryVersion(&major, &minor) != 0) { int opcode, firstError; if (XkbQueryExtension(display, &opcode, &m_xkbEventBase, - &firstError, &major, &minor)) { + &firstError, &major, &minor) != 0) { m_xkb = true; XkbSelectEvents(display, XkbUseCoreKbd, XkbMapNotifyMask, XkbMapNotifyMask); @@ -946,7 +947,7 @@ XWindowsScreen::openDisplay(const char* displayName) #if HAVE_X11_EXTENSIONS_XRANDR_H // query for XRandR extension int dummyError; - m_xrandr = XRRQueryExtension(display, &m_xrandrEventBase, &dummyError); + m_xrandr = (XRRQueryExtension(display, &m_xrandrEventBase, &dummyError) != 0); if (m_xrandr) { // enable XRRScreenChangeNotifyEvent XRRSelectInput(display, DefaultRootWindow(display), RRScreenChangeNotifyMask | RRCrtcChangeNotifyMask); @@ -986,12 +987,12 @@ XWindowsScreen::saveShape() m_xinerama = false; #if HAVE_X11_EXTENSIONS_XINERAMA_H int eventBase, errorBase; - if (XineramaQueryExtension(m_display, &eventBase, &errorBase) && - XineramaIsActive(m_display)) { + if ((XineramaQueryExtension(m_display, &eventBase, &errorBase) != 0) && + (XineramaIsActive(m_display) != 0)) { int numScreens; XineramaScreenInfo* screens; screens = XineramaQueryScreens(m_display, &numScreens); - if (screens != NULL) { + if (screens != nullptr) { if (numScreens > 1) { m_xinerama = true; m_xCenter = screens[0].x_org + (screens[0].width >> 1); @@ -1009,7 +1010,7 @@ XWindowsScreen::openWindow() const // default window attributes. we don't want the window manager // messing with our window and we don't want the cursor to be // visible inside the window. - XSetWindowAttributes attr; + XSetWindowAttributes attr{}; attr.do_not_propagate_mask = 0; attr.override_redirect = True; attr.cursor = createBlankCursor(); @@ -1062,8 +1063,8 @@ void XWindowsScreen::openIM() { // open the input methods - XIM im = XOpenIM(m_display, NULL, NULL, NULL); - if (im == NULL) { + XIM im = XOpenIM(m_display, nullptr, nullptr, nullptr); + if (im == nullptr) { LOG((CLOG_INFO "no support for IM")); return; } @@ -1071,8 +1072,8 @@ XWindowsScreen::openIM() // find the appropriate style. synergy supports XIMPreeditNothing // only at the moment. XIMStyles* styles; - if (XGetIMValues(im, XNQueryInputStyle, &styles, NULL) != NULL || - styles == NULL) { + if (XGetIMValues(im, XNQueryInputStyle, &styles, NULL) != nullptr || + styles == nullptr) { LOG((CLOG_WARN "cannot get IM styles")); XCloseIM(im); return; @@ -1095,7 +1096,7 @@ XWindowsScreen::openIM() // create an input context for the style and tell it about our window XIC ic = XCreateIC(im, XNInputStyle, style, XNClientWindow, m_window, NULL); - if (ic == NULL) { + if (ic == nullptr) { LOG((CLOG_WARN "cannot create IC")); XCloseIM(im); return; @@ -1103,7 +1104,7 @@ XWindowsScreen::openIM() // find out the events we must select for and do so unsigned long mask; - if (XGetICValues(ic, XNFilterEvents, &mask, NULL) != NULL) { + if (XGetICValues(ic, XNFilterEvents, &mask, NULL) != nullptr) { LOG((CLOG_WARN "cannot get IC filter events")); XDestroyIC(ic); XCloseIM(im); @@ -1116,7 +1117,7 @@ XWindowsScreen::openIM() m_lastKeycode = 0; // select events on our window that IM requires - XWindowAttributes attr; + XWindowAttributes attr{}; XGetWindowAttributes(m_display, m_window, &attr); XSelectInput(m_display, m_window, attr.your_event_mask | mask); } @@ -1130,7 +1131,7 @@ XWindowsScreen::sendEvent(Event::Type type, void* data) void XWindowsScreen::sendClipboardEvent(Event::Type type, ClipboardID id) { - ClipboardInfo* info = (ClipboardInfo*)malloc(sizeof(ClipboardInfo)); + auto* info = static_cast(malloc(sizeof(ClipboardInfo))); info->m_id = id; info->m_sequenceNumber = m_sequenceNumber; sendEvent(type, info); @@ -1143,9 +1144,9 @@ XWindowsScreen::getKeyState() const } Bool -XWindowsScreen::findKeyEvent(Display*, XEvent* xevent, XPointer arg) +XWindowsScreen::findKeyEvent(Display* /*unused*/, XEvent* xevent, XPointer arg) { - KeyEventFilter* filter = reinterpret_cast(arg); + auto* filter = reinterpret_cast(arg); return (xevent->type == filter->m_event && xevent->xkey.window == filter->m_window && xevent->xkey.time == filter->m_time && @@ -1153,9 +1154,9 @@ XWindowsScreen::findKeyEvent(Display*, XEvent* xevent, XPointer arg) } void -XWindowsScreen::handleSystemEvent(const Event& event, void*) +XWindowsScreen::handleSystemEvent(const Event& event, void* /*unused*/) { - XEvent* xevent = static_cast(event.getData()); + auto* xevent = static_cast(event.getData()); assert(xevent != NULL); // update key state @@ -1166,15 +1167,15 @@ XWindowsScreen::handleSystemEvent(const Event& event, void*) // KeyPress event that has the same key and time as // this release event, if any. first prepare the // filter info. - KeyEventFilter filter; + KeyEventFilter filter{}; filter.m_event = KeyPress; filter.m_window = xevent->xkey.window; filter.m_time = xevent->xkey.time; filter.m_keycode = xevent->xkey.keycode; - XEvent xevent2; + XEvent xevent2{}; isRepeat = (XCheckIfEvent(m_display, &xevent2, &XWindowsScreen::findKeyEvent, - (XPointer)&filter) == True); + reinterpret_cast(&filter)) == True); } if (xevent->type == KeyPress || xevent->type == KeyRelease) { @@ -1183,7 +1184,7 @@ XWindowsScreen::handleSystemEvent(const Event& event, void*) onHotKey(xevent->xkey, isRepeat); return; } - else if (!m_isOnScreen) { + if (!m_isOnScreen) { // this might be a hot key if (onHotKey(xevent->xkey, isRepeat)) { return; @@ -1198,7 +1199,7 @@ XWindowsScreen::handleSystemEvent(const Event& event, void*) } // let input methods try to handle event first - if (m_ic != NULL) { + if (m_ic != nullptr) { // XFilterEvent() may eat the event and generate a new KeyPress // event with a keycode of 0 because there isn't an actual key // associated with the keysym. but the KeyRelease may pass @@ -1217,19 +1218,19 @@ XWindowsScreen::handleSystemEvent(const Event& event, void*) } // now filter the event - if (XFilterEvent(xevent, DefaultRootWindow(m_display))) { + if (XFilterEvent(xevent, DefaultRootWindow(m_display)) != 0) { if (xevent->type == KeyPress) { // add filtered presses to the filtered list - m_filtered.insert(m_lastKeycode); + m_filtered.insert(m_lastKeycode != 0u); } return; } // discard matching key releases for key presses that were // filtered and remove them from our filtered list. - else if (xevent->type == KeyRelease && - m_filtered.count(xevent->xkey.keycode) > 0) { - m_filtered.erase(xevent->xkey.keycode); + if (xevent->type == KeyRelease && + m_filtered.count(xevent->xkey.keycode != 0u) > 0) { + m_filtered.erase(xevent->xkey.keycode != 0u); return; } } @@ -1243,15 +1244,15 @@ XWindowsScreen::handleSystemEvent(const Event& event, void*) #ifdef HAVE_XI2 if (m_xi2detected) { // Process RawMotion - XGenericEventCookie *cookie = (XGenericEventCookie*)&xevent->xcookie; - if (XGetEventData(m_display, cookie) && + auto *cookie = &xevent->xcookie; + if ((XGetEventData(m_display, cookie) != 0) && cookie->type == GenericEvent && cookie->extension == xi_opcode) { if (cookie->evtype == XI_RawMotion) { if (m_isPrimary) { // Get current pointer's position Window root, child; - XMotionEvent xmotion; + XMotionEvent xmotion{}; xmotion.type = MotionNotify; xmotion.send_event = False; // Raw motion xmotion.display = m_display; @@ -1398,7 +1399,7 @@ XWindowsScreen::handleSystemEvent(const Event& event, void*) default: #if HAVE_XKB_EXTENSION if (m_xkb && xevent->type == m_xkbEventBase) { - XkbEvent* xkbEvent = reinterpret_cast(xevent); + auto* xkbEvent = reinterpret_cast(xevent); switch (xkbEvent->any.xkb_type) { case XkbMapNotify: refreshKeyboard(xevent); @@ -1406,7 +1407,7 @@ XWindowsScreen::handleSystemEvent(const Event& event, void*) case XkbStateNotify: LOG((CLOG_INFO "group change: %d", xkbEvent->state.group)); - m_keyState->setActiveGroup((SInt32)xkbEvent->state.group); + m_keyState->setActiveGroup(static_cast(xkbEvent->state.group)); return; } } @@ -1461,7 +1462,7 @@ XWindowsScreen::onKeyPress(XKeyEvent& xkey) // get which button. see call to XFilterEvent() in onEvent() // for more info. bool isFake = false; - KeyButton keycode = static_cast(xkey.keycode); + auto keycode = static_cast(xkey.keycode); if (keycode == 0) { isFake = true; keycode = static_cast(m_lastKeycode); @@ -1503,7 +1504,7 @@ XWindowsScreen::onKeyRelease(XKeyEvent& xkey, bool isRepeat) isRepeat = false; } - KeyButton keycode = static_cast(xkey.keycode); + auto keycode = static_cast(xkey.keycode); if (!isRepeat) { // no press event follows so it's a plain release LOG((CLOG_DEBUG1 "event: KeyRelease code=%d, state=0x%04x", keycode, xkey.state)); @@ -1597,13 +1598,13 @@ XWindowsScreen::onMouseMove(const XMotionEvent& xmotion) m_xCursor = xmotion.x_root; m_yCursor = xmotion.y_root; - if (xmotion.send_event) { + if (xmotion.send_event != 0) { // we warped the mouse. discard events until we // find the matching sent event. see // warpCursorNoFlush() for where the events are // sent. we discard the matching sent event and // can be sure we've skipped the warp event. - XEvent xevent; + XEvent xevent{}; char cntr = 0; do { XMaskEvent(m_display, PointerMotionMask, &xevent); @@ -1611,7 +1612,7 @@ XWindowsScreen::onMouseMove(const XMotionEvent& xmotion) LOG((CLOG_WARN "too many discarded events! %d", cntr)); break; } - } while (!xevent.xany.send_event); + } while (xevent.xany.send_event == 0); cntr = 0; } else if (m_isOnScreen) { @@ -1667,14 +1668,14 @@ XWindowsScreen::createBlankCursor() const // is blank we can use the same bitmap for shape and mask: all // zeros. const int size = ((w + 7) >> 3) * h; - char* data = new char[size]; + auto* data = new char[size]; memset(data, 0, size); // make bitmap Pixmap bitmap = XCreateBitmapFromData(m_display, m_root, data, w, h); // need an arbitrary color for the cursor - XColor color; + XColor color{}; color.pixel = 0; color.red = color.green = color.blue = 0; color.flags = DoRed | DoGreen | DoBlue; @@ -1694,7 +1695,7 @@ ClipboardID XWindowsScreen::getClipboardID(Atom selection) const { for (ClipboardID id = 0; id < kClipboardEnd; ++id) { - if (m_clipboard[id] != NULL && + if (m_clipboard[id] != nullptr && m_clipboard[id]->getSelection() == selection) { return id; } @@ -1707,9 +1708,9 @@ XWindowsScreen::processClipboardRequest(Window requestor, Time time, Atom property) { // check every clipboard until one returns success - for (ClipboardID id = 0; id < kClipboardEnd; ++id) { - if (m_clipboard[id] != NULL && - m_clipboard[id]->processRequest(requestor, time, property)) { + for (auto & id : m_clipboard) { + if (id != nullptr && + id->processRequest(requestor, time, property)) { break; } } @@ -1719,9 +1720,9 @@ void XWindowsScreen::destroyClipboardRequest(Window requestor) { // check every clipboard until one returns success - for (ClipboardID id = 0; id < kClipboardEnd; ++id) { - if (m_clipboard[id] != NULL && - m_clipboard[id]->destroyRequest(requestor)) { + for (auto & id : m_clipboard) { + if (id != nullptr && + id->destroyRequest(requestor)) { break; } } @@ -1731,13 +1732,13 @@ void XWindowsScreen::onError() { // prevent further access to the X display - m_events->adoptBuffer(NULL); + m_events->adoptBuffer(nullptr); m_screensaver->destroy(); - m_screensaver = NULL; - m_display = NULL; + m_screensaver = nullptr; + m_display = nullptr; // notify of failure - sendEvent(m_events->forIScreen().error(), NULL); + sendEvent(m_events->forIScreen().error(), nullptr); // FIXME -- should ensure that we ignore operations that involve // m_display from now on. however, Xlib will simply exit the @@ -1750,7 +1751,7 @@ XWindowsScreen::onError() } int -XWindowsScreen::ioErrorHandler(Display*) +XWindowsScreen::ioErrorHandler(Display* /*unused*/) { // the display has disconnected, probably because X is shutting // down. X forces us to exit at this point which is annoying. @@ -1796,7 +1797,7 @@ XWindowsScreen::doSelectEvents(Window w) const // Avoid selecting PointerMotionMask unless some other client selected // it already. long mask = SubstructureNotifyMask; - XWindowAttributes attr; + XWindowAttributes attr{}; XGetWindowAttributes(m_display, w, &attr); if ((attr.all_event_masks & PointerMotionMask) == PointerMotionMask) { mask |= PointerMotionMask; @@ -1810,7 +1811,7 @@ XWindowsScreen::doSelectEvents(Window w) const // recurse on child windows Window rw, pw, *cw; unsigned int nc; - if (XQueryTree(m_display, w, &rw, &pw, &cw, &nc)) { + if (XQueryTree(m_display, w, &rw, &pw, &cw, &nc) != 0) { for (unsigned int i = 0; i < nc; ++i) { doSelectEvents(cw[i]); } @@ -1823,7 +1824,7 @@ XWindowsScreen::mapKeyFromX(XKeyEvent* event) const { // convert to a keysym KeySym keysym; - if (event->type == KeyPress && m_ic != NULL) { + if (event->type == KeyPress && m_ic != nullptr) { // do multibyte lookup. can only call XmbLookupString with a // key press event and a valid XIC so we checked those above. char scratch[32]; @@ -1855,7 +1856,7 @@ XWindowsScreen::mapKeyFromX(XKeyEvent* event) const else { // plain old lookup char dummy[1]; - XLookupString(event, dummy, 0, &keysym, NULL); + XLookupString(event, dummy, 0, &keysym, nullptr); } LOG((CLOG_DEBUG2 "mapped code=%d to keysym=0x%04x", event->keycode, keysym)); @@ -1878,7 +1879,7 @@ XWindowsScreen::mapButtonFromX(const XButtonEvent* event) const // buttons 4 and 5 are ignored here. they're used for the wheel. // buttons 6, 7, etc and up map to 4, 5, etc. - else if (button >= 6) { + if (button >= 6) { return static_cast(button - 2); } @@ -1923,7 +1924,7 @@ XWindowsScreen::warpCursorNoFlush(SInt32 x, SInt32 y) assert(m_window != None); // send an event that we can recognize before the mouse warp - XEvent eventBefore; + XEvent eventBefore{}; eventBefore.type = MotionNotify; eventBefore.xmotion.display = m_display; eventBefore.xmotion.window = m_window; @@ -1954,8 +1955,8 @@ void XWindowsScreen::updateButtons() { // query the button mapping - UInt32 numButtons = XGetPointerMapping(m_display, NULL, 0); - unsigned char* tmpButtons = new unsigned char[numButtons]; + UInt32 numButtons = XGetPointerMapping(m_display, nullptr, 0); + auto* tmpButtons = new unsigned char[numButtons]; XGetPointerMapping(m_display, tmpButtons, numButtons); // find the largest logical button id @@ -2035,7 +2036,7 @@ void XWindowsScreen::refreshKeyboard(XEvent* event) { if (XPending(m_display) > 0) { - XEvent tmpEvent; + XEvent tmpEvent{}; XPeekEvent(m_display, &tmpEvent); if (tmpEvent.type == MappingNotify) { // discard this event since another follows. @@ -2047,15 +2048,16 @@ XWindowsScreen::refreshKeyboard(XEvent* event) // keyboard mapping changed #if HAVE_XKB_EXTENSION if (m_xkb && event->type == m_xkbEventBase) { - XkbRefreshKeyboardMapping((XkbMapNotifyEvent*)event); + XkbRefreshKeyboardMapping(reinterpret_cast(event)); } - else + else { #else { XRefreshKeyboardMapping(&event->xmapping); } #endif m_keyState->updateKeyMap(); +} m_keyState->updateKeyState(); } @@ -2083,18 +2085,18 @@ XWindowsScreen::detectXI2() { int event, error; return XQueryExtension(m_display, - "XInputExtension", &xi_opcode, &event, &error); + "XInputExtension", &xi_opcode, &event, &error) != 0; } #ifdef HAVE_XI2 void XWindowsScreen::selectXIRawMotion() { - XIEventMask mask; + XIEventMask mask{}; mask.deviceid = XIAllDevices; mask.mask_len = XIMaskLen(XI_RawMotion); - mask.mask = (unsigned char*)calloc(mask.mask_len, sizeof(char)); + mask.mask = static_cast(calloc(mask.mask_len, sizeof(char))); mask.deviceid = XIAllMasterDevices; memset(mask.mask, 0, 2); XISetMask(mask.mask, XI_RawKeyRelease); diff --git a/src/lib/platform/XWindowsScreen.h b/src/lib/platform/XWindowsScreen.h index 40422da6..fbe6a0e8 100644 --- a/src/lib/platform/XWindowsScreen.h +++ b/src/lib/platform/XWindowsScreen.h @@ -50,7 +50,7 @@ public: virtual void* getEventTarget() const; virtual bool getClipboard(ClipboardID id, IClipboard*) const; virtual void getShape(SInt32& x, SInt32& y, - SInt32& width, SInt32& height) const; + SInt32& w, SInt32& h) const; virtual void getCursorPos(SInt32& x, SInt32& y) const; // IPrimaryScreen overrides @@ -65,7 +65,7 @@ public: virtual void getCursorCenter(SInt32& x, SInt32& y) const; // ISecondaryScreen overrides - virtual void fakeMouseButton(ButtonID id, bool press); + virtual void fakeMouseButton(ButtonID button, bool press); virtual void fakeMouseMove(SInt32 x, SInt32 y); virtual void fakeMouseRelativeMove(SInt32 dx, SInt32 dy) const; virtual void fakeMouseWheel(SInt32 xDelta, SInt32 yDelta) const; @@ -104,11 +104,11 @@ private: ClipboardID getClipboardID(Atom selection) const; // continue processing a selection request - void processClipboardRequest(Window window, + void processClipboardRequest(Window requestor, Time time, Atom property); // terminate a selection request - void destroyClipboardRequest(Window window); + void destroyClipboardRequest(Window requestor); // X I/O error handler void onError(); @@ -208,7 +208,7 @@ private: FilteredKeycodes m_filtered; // clipboards - XWindowsClipboard* m_clipboard[kClipboardEnd]; + XWindowsClipboard* m_clipboard[kClipboardEnd]{}; UInt32 m_sequenceNumber; // screen saver stuff @@ -220,14 +220,14 @@ private: std::vector m_buttons; // true if global auto-repeat was enabled before we turned it off - bool m_autoRepeat; + bool m_autoRepeat{}; // stuff to workaround xtest being xinerama unaware. attempting // to fake a mouse motion under xinerama may behave strangely, // especially if screen 0 is not at 0,0 or if faking a motion on // a screen other than screen 0. bool m_xtestIsXineramaUnaware; - bool m_xinerama; + bool m_xinerama{}; // stuff to work around lost focus issues on certain systems // (ie: a MythTV front-end). @@ -235,13 +235,13 @@ private: // XKB extension stuff bool m_xkb; - int m_xkbEventBase; + int m_xkbEventBase{}; bool m_xi2detected; // XRandR extension stuff bool m_xrandr; - int m_xrandrEventBase; + int m_xrandrEventBase{}; IEventQueue* m_events; synergy::KeyMap m_keyMap; diff --git a/src/lib/platform/XWindowsScreenSaver.cpp b/src/lib/platform/XWindowsScreenSaver.cpp index ab4069af..9111c2ab 100644 --- a/src/lib/platform/XWindowsScreenSaver.cpp +++ b/src/lib/platform/XWindowsScreenSaver.cpp @@ -18,12 +18,12 @@ #include "platform/XWindowsScreenSaver.h" -#include "platform/XWindowsUtil.h" -#include "core/IPlatformScreen.h" -#include "base/Log.h" #include "base/Event.h" #include "base/IEventQueue.h" +#include "base/Log.h" #include "base/TMethodEventJob.h" +#include "core/IPlatformScreen.h" +#include "platform/XWindowsUtil.h" #include #if HAVE_X11_EXTENSIONS_XTEST_H @@ -68,7 +68,7 @@ XWindowsScreenSaver::XWindowsScreenSaver( m_dpms(false), m_disabled(false), m_suppressDisable(false), - m_disableTimer(NULL), + m_disableTimer(nullptr), m_disablePos(0), m_events(events) { @@ -86,8 +86,8 @@ XWindowsScreenSaver::XWindowsScreenSaver( // that powers down the display. #if HAVE_X11_EXTENSIONS_DPMS_H int eventBase, errorBase; - if (DPMSQueryExtension(m_display, &eventBase, &errorBase)) { - if (DPMSCapable(m_display)) { + if (DPMSQueryExtension(m_display, &eventBase, &errorBase) != 0) { + if (DPMSCapable(m_display) != 0) { // we have DPMS m_dpms = true; } @@ -99,7 +99,7 @@ XWindowsScreenSaver::XWindowsScreenSaver( { XWindowsUtil::ErrorLock lock(m_display, &error); Window root = DefaultRootWindow(m_display); - XWindowAttributes attr; + XWindowAttributes attr{}; XGetWindowAttributes(m_display, root, &attr); m_rootEventMask = attr.your_event_mask; XSelectInput(m_display, root, m_rootEventMask | SubstructureNotifyMask); @@ -130,12 +130,12 @@ XWindowsScreenSaver::XWindowsScreenSaver( XWindowsScreenSaver::~XWindowsScreenSaver() { // done with disable job - if (m_disableTimer != NULL) { + if (m_disableTimer != nullptr) { m_events->deleteTimer(m_disableTimer); } m_events->removeHandler(Event::kTimer, this); - if (m_display != NULL) { + if (m_display != nullptr) { enableDPMS(m_dpmsEnabled); XSetScreenSaver(m_display, m_timeout, m_interval, m_preferBlanking, m_allowExposures); @@ -148,7 +148,7 @@ XWindowsScreenSaver::~XWindowsScreenSaver() void XWindowsScreenSaver::destroy() { - m_display = NULL; + m_display = nullptr; delete this; } @@ -326,7 +326,7 @@ XWindowsScreenSaver::findXScreenSaver() Window root = DefaultRootWindow(m_display); Window rw, pw, *cw; unsigned int nc; - if (XQueryTree(m_display, root, &rw, &pw, &cw, &nc)) { + if (XQueryTree(m_display, root, &rw, &pw, &cw, &nc) != 0) { for (unsigned int i = 0; i < nc; ++i) { if (isXScreenSaver(cw[i])) { setXScreenSaver(cw[i]); @@ -354,7 +354,7 @@ XWindowsScreenSaver::setXScreenSaver(Window window) // see if xscreensaver is active bool error = false; - XWindowAttributes attr; + XWindowAttributes attr{}; { XWindowsUtil::ErrorLock lock(m_display, &error); XGetWindowAttributes(m_display, m_xscreensaver, &attr); @@ -380,7 +380,7 @@ XWindowsScreenSaver::isXScreenSaver(Window w) const Atom type; return (XWindowsUtil::getWindowProperty(m_display, w, m_atomScreenSaverVersion, - NULL, &type, NULL, False) && + nullptr, &type, nullptr, False) && type == XA_STRING); } @@ -414,7 +414,7 @@ XWindowsScreenSaver::setXScreenSaverActive(bool activated) void XWindowsScreenSaver::sendXScreenSaverCommand(Atom cmd, long arg1, long arg2) { - XEvent event; + XEvent event{}; event.xclient.type = ClientMessage; event.xclient.display = m_display; event.xclient.window = m_xscreensaverSink; @@ -447,7 +447,7 @@ XWindowsScreenSaver::watchForXScreenSaver() Window root = DefaultRootWindow(m_display); Window rw, pw, *cw; unsigned int nc; - if (XQueryTree(m_display, root, &rw, &pw, &cw, &nc)) { + if (XQueryTree(m_display, root, &rw, &pw, &cw, &nc) != 0) { for (unsigned int i = 0; i < nc; ++i) { addWatchXScreenSaver(cw[i]); } @@ -467,9 +467,8 @@ XWindowsScreenSaver::clearWatchForXScreenSaver() { // stop watching all windows XWindowsUtil::ErrorLock lock(m_display); - for (WatchList::iterator index = m_watchWindows.begin(); - index != m_watchWindows.end(); ++index) { - XSelectInput(m_display, index->first, index->second); + for (auto & m_watchWindow : m_watchWindows) { + XSelectInput(m_display, m_watchWindow.first, m_watchWindow.second); } m_watchWindows.clear(); } @@ -479,7 +478,7 @@ XWindowsScreenSaver::addWatchXScreenSaver(Window window) { // get window attributes bool error = false; - XWindowAttributes attr; + XWindowAttributes attr{}; { XWindowsUtil::ErrorLock lock(m_display, &error); XGetWindowAttributes(m_display, window, &attr); @@ -504,22 +503,22 @@ XWindowsScreenSaver::addWatchXScreenSaver(Window window) void XWindowsScreenSaver::updateDisableTimer() { - if (m_disabled && !m_suppressDisable && m_disableTimer == NULL) { + if (m_disabled && !m_suppressDisable && m_disableTimer == nullptr) { // 5 seconds should be plenty often to suppress the screen saver m_disableTimer = m_events->newTimer(5.0, this); } - else if ((!m_disabled || m_suppressDisable) && m_disableTimer != NULL) { + else if ((!m_disabled || m_suppressDisable) && m_disableTimer != nullptr) { m_events->deleteTimer(m_disableTimer); - m_disableTimer = NULL; + m_disableTimer = nullptr; } } void -XWindowsScreenSaver::handleDisableTimer(const Event&, void*) +XWindowsScreenSaver::handleDisableTimer(const Event& /*unused*/, void* /*unused*/) { // send fake mouse motion directly to xscreensaver if (m_xscreensaver != None) { - XEvent event; + XEvent event{}; event.xmotion.type = MotionNotify; event.xmotion.display = m_display; event.xmotion.window = m_xscreensaver; @@ -578,9 +577,9 @@ XWindowsScreenSaver::isDPMSEnabled() const DPMSInfo(m_display, &level, &state); return (state != False); } - else { + return false; - } + #else return false; #endif @@ -596,9 +595,9 @@ XWindowsScreenSaver::isDPMSActivated() const DPMSInfo(m_display, &level, &state); return (level != DPMSModeOn); } - else { + return false; - } + #else return false; #endif diff --git a/src/lib/platform/XWindowsScreenSaver.h b/src/lib/platform/XWindowsScreenSaver.h index 452d9594..d08268c5 100644 --- a/src/lib/platform/XWindowsScreenSaver.h +++ b/src/lib/platform/XWindowsScreenSaver.h @@ -140,10 +140,10 @@ private: Atom m_atomScreenSaverDeactivate; // built-in screen saver settings - int m_timeout; - int m_interval; - int m_preferBlanking; - int m_allowExposures; + int m_timeout{}; + int m_interval{}; + int m_preferBlanking{}; + int m_allowExposures{}; // DPMS screen saver settings bool m_dpms; diff --git a/src/lib/platform/XWindowsUtil.cpp b/src/lib/platform/XWindowsUtil.cpp index c0625bc6..f9dd93f1 100644 --- a/src/lib/platform/XWindowsUtil.cpp +++ b/src/lib/platform/XWindowsUtil.cpp @@ -18,10 +18,10 @@ #include "platform/XWindowsUtil.h" -#include "core/key_types.h" -#include "mt/Thread.h" #include "base/Log.h" #include "base/String.h" +#include "core/key_types.h" +#include "mt/Thread.h" #include #define XK_APL @@ -1345,8 +1345,8 @@ XWindowsUtil::getWindowProperty(Display* display, Window window, } // append data - if (data != NULL) { - data->append((char*)rawData, numBytes); + if (data != nullptr) { + data->append(reinterpret_cast(rawData), numBytes); } else { // data is not required so don't try to get any more @@ -1363,21 +1363,21 @@ XWindowsUtil::getWindowProperty(Display* display, Window window, } // save property info - if (type != NULL) { + if (type != nullptr) { *type = actualType; } - if (format != NULL) { + if (format != nullptr) { *format = static_cast(actualDatumSize); } if (okay) { - LOG((CLOG_DEBUG2 "read property %d on window 0x%08x: bytes=%d", property, window, (data == NULL) ? 0 : data->size())); + LOG((CLOG_DEBUG2 "read property %d on window 0x%08x: bytes=%d", property, window, (data == nullptr) ? 0 : data->size())); return true; } - else { + LOG((CLOG_DEBUG2 "can't read property %d on window 0x%08x", property, window)); return false; - } + } bool @@ -1386,8 +1386,8 @@ XWindowsUtil::setWindowProperty(Display* display, Window window, Atom type, SInt32 format) { const UInt32 length = 4 * XMaxRequestSize(display); - const unsigned char* data = static_cast(vdata); - UInt32 datumSize = static_cast(format / 8); + const auto* data = static_cast(vdata); + auto datumSize = static_cast(format / 8); // format 32 on 64bit systems is 8 bytes not 4. if (format == 32) { datumSize = sizeof(Atom); @@ -1431,7 +1431,7 @@ XWindowsUtil::getCurrentTime(Display* display, Window window) { XLockDisplay(display); // select property events on window - XWindowAttributes attr; + XWindowAttributes attr{}; XGetWindowAttributes(display, window, &attr); XSelectInput(display, window, attr.your_event_mask | PropertyChangeMask); @@ -1446,14 +1446,14 @@ XWindowsUtil::getCurrentTime(Display* display, Window window) &dummy, 0); // look for property notify events with the following - PropertyNotifyPredicateInfo filter; + PropertyNotifyPredicateInfo filter{}; filter.m_window = window; filter.m_property = atom; // wait for reply - XEvent xevent; + XEvent xevent{}; XIfEvent(display, &xevent, &XWindowsUtil::propertyNotifyPredicate, - (XPointer)&filter); + reinterpret_cast(&filter)); assert(xevent.type == PropertyNotify); assert(xevent.xproperty.window == window); assert(xevent.xproperty.atom == atom); @@ -1619,31 +1619,31 @@ XWindowsUtil::atomToString(Display* display, Atom atom) XWindowsUtil::ErrorLock lock(display, &error); char* name = XGetAtomName(display, atom); if (error) { - return synergy::string::sprintf(" (%d)", (int)atom); + return synergy::string::sprintf(" (%d)", static_cast(atom)); } - else { - String msg = synergy::string::sprintf("%s (%d)", name, (int)atom); + + String msg = synergy::string::sprintf("%s (%d)", name, static_cast(atom)); XFree(name); return msg; - } + } String XWindowsUtil::atomsToString(Display* display, const Atom* atom, UInt32 num) { - char** names = new char*[num]; + auto** names = new char*[num]; bool error = false; XWindowsUtil::ErrorLock lock(display, &error); - XGetAtomNames(display, const_cast(atom), (int)num, names); + XGetAtomNames(display, const_cast(atom), static_cast(num), names); String msg; if (error) { for (UInt32 i = 0; i < num; ++i) { - msg += synergy::string::sprintf(" (%d), ", (int)atom[i]); + msg += synergy::string::sprintf(" (%d), ", static_cast(atom[i])); } } else { for (UInt32 i = 0; i < num; ++i) { - msg += synergy::string::sprintf("%s (%d), ", names[i], (int)atom[i]); + msg += synergy::string::sprintf("%s (%d), ", names[i], static_cast(atom[i])); XFree(names[i]); } } @@ -1690,9 +1690,9 @@ XWindowsUtil::appendTimeData(String& data, Time time) } Bool -XWindowsUtil::propertyNotifyPredicate(Display*, XEvent* xevent, XPointer arg) +XWindowsUtil::propertyNotifyPredicate(Display* /*unused*/, XEvent* xevent, XPointer arg) { - PropertyNotifyPredicateInfo* filter = + auto* filter = reinterpret_cast(arg); return (xevent->type == PropertyNotify && xevent->xproperty.window == filter->m_window && @@ -1704,8 +1704,8 @@ void XWindowsUtil::initKeyMaps() { if (s_keySymToUCS4.empty()) { - for (size_t i =0; i < sizeof(s_keymap) / sizeof(s_keymap[0]); ++i) { - s_keySymToUCS4[s_keymap[i].keysym] = s_keymap[i].ucs4; + for (auto & i : s_keymap) { + s_keySymToUCS4[i.keysym] = i.ucs4; } } } @@ -1715,12 +1715,12 @@ XWindowsUtil::initKeyMaps() // XWindowsUtil::ErrorLock // -XWindowsUtil::ErrorLock* XWindowsUtil::ErrorLock::s_top = NULL; +XWindowsUtil::ErrorLock* XWindowsUtil::ErrorLock::s_top = nullptr; XWindowsUtil::ErrorLock::ErrorLock(Display* display) : m_display(display) { - install(&XWindowsUtil::ErrorLock::ignoreHandler, NULL); + install(&XWindowsUtil::ErrorLock::ignoreHandler, nullptr); } XWindowsUtil::ErrorLock::ErrorLock(Display* display, bool* flag) : @@ -1739,7 +1739,7 @@ XWindowsUtil::ErrorLock::ErrorLock(Display* display, XWindowsUtil::ErrorLock::~ErrorLock() { // make sure everything finishes before uninstalling handler - if (m_display != NULL) { + if (m_display != nullptr) { XSync(m_display, False); } @@ -1752,7 +1752,7 @@ void XWindowsUtil::ErrorLock::install(ErrorHandler handler, void* data) { // make sure everything finishes before installing handler - if (m_display != NULL) { + if (m_display != nullptr) { XSync(m_display, False); } @@ -1768,20 +1768,20 @@ XWindowsUtil::ErrorLock::install(ErrorHandler handler, void* data) int XWindowsUtil::ErrorLock::internalHandler(Display* display, XErrorEvent* event) { - if (s_top != NULL && s_top->m_handler != NULL) { + if (s_top != nullptr && s_top->m_handler != nullptr) { s_top->m_handler(display, event, s_top->m_userData); } return 0; } void -XWindowsUtil::ErrorLock::ignoreHandler(Display*, XErrorEvent* e, void*) +XWindowsUtil::ErrorLock::ignoreHandler(Display* /*unused*/, XErrorEvent* e, void* /*unused*/) { LOG((CLOG_DEBUG1 "ignoring X error: %d", e->error_code)); } void -XWindowsUtil::ErrorLock::saveHandler(Display*, XErrorEvent* e, void* flag) +XWindowsUtil::ErrorLock::saveHandler(Display* /*unused*/, XErrorEvent* e, void* flag) { LOG((CLOG_DEBUG1 "flagging X error: %d", e->error_code)); *static_cast(flag) = true; diff --git a/src/lib/platform/XWindowsUtil.h b/src/lib/platform/XWindowsUtil.h index f953e32d..cb269037 100644 --- a/src/lib/platform/XWindowsUtil.h +++ b/src/lib/platform/XWindowsUtil.h @@ -54,7 +54,7 @@ public: */ static bool setWindowProperty(Display*, Window window, Atom property, - const void* data, UInt32 size, + const void* vdata, UInt32 size, Atom type, SInt32 format); //! Get X server time @@ -142,12 +142,12 @@ public: /*! Set \c *errorFlag if any error occurs. */ - ErrorLock(Display*, bool* errorFlag); + ErrorLock(Display*, bool* flag); /*! Call \c handler on each error. */ - ErrorLock(Display*, ErrorHandler handler, void* userData); + ErrorLock(Display*, ErrorHandler handler, void* data); ~ErrorLock(); @@ -161,10 +161,10 @@ public: typedef int (*XErrorHandler)(Display*, XErrorEvent*); Display* m_display; - ErrorHandler m_handler; - void* m_userData; - XErrorHandler m_oldXHandler; - ErrorLock* m_next; + ErrorHandler m_handler{}; + void* m_userData{}; + XErrorHandler m_oldXHandler{}; + ErrorLock* m_next{}; static ErrorLock* s_top; }; diff --git a/src/lib/server/BaseClientProxy.cpp b/src/lib/server/BaseClientProxy.cpp index 029f999f..c4c2c2f8 100644 --- a/src/lib/server/BaseClientProxy.cpp +++ b/src/lib/server/BaseClientProxy.cpp @@ -18,12 +18,14 @@ #include "server/BaseClientProxy.h" +#include + // // BaseClientProxy // -BaseClientProxy::BaseClientProxy(const String& name) : - m_name(name), +BaseClientProxy::BaseClientProxy(String name) : + m_name(std::move(name)), m_x(0), m_y(0) { diff --git a/src/lib/server/BaseClientProxy.h b/src/lib/server/BaseClientProxy.h index 90034952..3ea0f085 100644 --- a/src/lib/server/BaseClientProxy.h +++ b/src/lib/server/BaseClientProxy.h @@ -29,7 +29,7 @@ public: /*! \c name is the name of the client. */ - BaseClientProxy(const String& name); + BaseClientProxy(String name); ~BaseClientProxy(); //! @name manipulators diff --git a/src/lib/server/ClientListener.cpp b/src/lib/server/ClientListener.cpp index 705794bb..a7e835b7 100644 --- a/src/lib/server/ClientListener.cpp +++ b/src/lib/server/ClientListener.cpp @@ -18,16 +18,16 @@ #include "server/ClientListener.h" -#include "server/ClientProxy.h" -#include "server/ClientProxyUnknown.h" +#include "base/IEventQueue.h" +#include "base/Log.h" +#include "base/TMethodEventJob.h" #include "core/PacketStreamFilter.h" #include "net/IDataSocket.h" #include "net/IListenSocket.h" #include "net/ISocketFactory.h" #include "net/XSocket.h" -#include "base/Log.h" -#include "base/IEventQueue.h" -#include "base/TMethodEventJob.h" +#include "server/ClientProxy.h" +#include "server/ClientProxyUnknown.h" // // ClientListener @@ -37,7 +37,7 @@ ClientListener::ClientListener(const NetworkAddress& address, ISocketFactory* socketFactory, IEventQueue* events) : m_socketFactory(socketFactory), - m_server(NULL), + m_server(nullptr), m_events(events) { assert(m_socketFactory != NULL); @@ -73,9 +73,7 @@ ClientListener::~ClientListener() LOG((CLOG_DEBUG1 "stop listening for clients")); // discard already connected clients - for (NewClients::iterator index = m_newClients.begin(); - index != m_newClients.end(); ++index) { - ClientProxyUnknown* client = *index; + for (auto client : m_newClients) { m_events->removeHandler( m_events->forClientProxyUnknown().success(), client); m_events->removeHandler( @@ -87,7 +85,7 @@ ClientListener::~ClientListener() // discard waiting clients ClientProxy* client = getNextClient(); - while (client != NULL) { + while (client != nullptr) { delete client; client = getNextClient(); } @@ -107,7 +105,7 @@ ClientListener::setServer(Server* server) ClientProxy* ClientListener::getNextClient() { - ClientProxy* client = NULL; + ClientProxy* client = nullptr; if (!m_waitingClients.empty()) { client = m_waitingClients.front(); m_waitingClients.pop_front(); @@ -117,12 +115,12 @@ ClientListener::getNextClient() } void -ClientListener::handleClientConnecting(const Event&, void*) +ClientListener::handleClientConnecting(const Event& /*unused*/, void* /*unused*/) { // accept client connection IDataSocket* socket = m_listen->accept(); - if (socket == NULL) { + if (socket == nullptr) { return; } @@ -136,18 +134,18 @@ ClientListener::handleClientConnecting(const Event&, void*) } void -ClientListener::handleClientAccepted(const Event&, void* vsocket) +ClientListener::handleClientAccepted(const Event& /*unused*/, void* vsocket) { LOG((CLOG_NOTE "accepted client connection")); - IDataSocket* socket = static_cast(vsocket); + auto* socket = static_cast(vsocket); // filter socket messages, including a packetizing filter synergy::IStream* stream = new PacketStreamFilter(m_events, socket, true); assert(m_server != NULL); // create proxy for unknown client - ClientProxyUnknown* client = new ClientProxyUnknown(stream, 30.0, m_server, m_events); + auto* client = new ClientProxyUnknown(stream, 30.0, m_server, m_events); m_newClients.insert(client); @@ -163,9 +161,9 @@ ClientListener::handleClientAccepted(const Event&, void* vsocket) } void -ClientListener::handleUnknownClient(const Event&, void* vclient) +ClientListener::handleUnknownClient(const Event& /*unused*/, void* vclient) { - ClientProxyUnknown* unknownClient = + auto* unknownClient = static_cast(vclient); // we should have the client in our new client list @@ -174,7 +172,7 @@ ClientListener::handleUnknownClient(const Event&, void* vclient) // get the real client proxy and install it ClientProxy* client = unknownClient->orphanClientProxy(); bool handshakeOk = true; - if (client != NULL) { + if (client != nullptr) { // handshake was successful m_waitingClients.push_back(client); m_events->addEvent(Event(m_events->forClientListener().connected(), @@ -194,9 +192,9 @@ ClientListener::handleUnknownClient(const Event&, void* vclient) m_events->removeHandler(m_events->forClientProxyUnknown().success(), client); m_events->removeHandler(m_events->forClientProxyUnknown().failure(), client); m_newClients.erase(unknownClient); - PacketStreamFilter* streamFileter = dynamic_cast(unknownClient->getStream()); - IDataSocket* socket = NULL; - if (streamFileter != NULL) { + auto* streamFileter = dynamic_cast(unknownClient->getStream()); + IDataSocket* socket = nullptr; + if (streamFileter != nullptr) { socket = dynamic_cast(streamFileter->getStream()); } @@ -204,12 +202,12 @@ ClientListener::handleUnknownClient(const Event&, void* vclient) } void -ClientListener::handleClientDisconnected(const Event&, void* vclient) +ClientListener::handleClientDisconnected(const Event& /*unused*/, void* vclient) { - ClientProxy* client = static_cast(vclient); + auto* client = static_cast(vclient); // find client in waiting clients queue - for (WaitingClients::iterator i = m_waitingClients.begin(), + for (auto i = m_waitingClients.begin(), n = m_waitingClients.end(); i != n; ++i) { if (*i == client) { m_waitingClients.erase(i); diff --git a/src/lib/server/ClientProxy.cpp b/src/lib/server/ClientProxy.cpp index 248b2ba8..71a581e6 100644 --- a/src/lib/server/ClientProxy.cpp +++ b/src/lib/server/ClientProxy.cpp @@ -18,10 +18,10 @@ #include "server/ClientProxy.h" +#include "base/EventQueue.h" +#include "base/Log.h" #include "core/ProtocolUtil.h" #include "io/IStream.h" -#include "base/Log.h" -#include "base/EventQueue.h" // // ClientProxy diff --git a/src/lib/server/ClientProxy.h b/src/lib/server/ClientProxy.h index 3d05a072..1f561db5 100644 --- a/src/lib/server/ClientProxy.h +++ b/src/lib/server/ClientProxy.h @@ -31,7 +31,7 @@ public: /*! \c name is the name of the client. */ - ClientProxy(const String& name, synergy::IStream* adoptedStream); + ClientProxy(const String& name, synergy::IStream* stream); ~ClientProxy(); //! @name manipulators diff --git a/src/lib/server/ClientProxy1_0.cpp b/src/lib/server/ClientProxy1_0.cpp index 1fada449..9b4abce6 100644 --- a/src/lib/server/ClientProxy1_0.cpp +++ b/src/lib/server/ClientProxy1_0.cpp @@ -18,12 +18,12 @@ #include "server/ClientProxy1_0.h" +#include "base/IEventQueue.h" +#include "base/Log.h" +#include "base/TMethodEventJob.h" #include "core/ProtocolUtil.h" #include "core/XSynergy.h" #include "io/IStream.h" -#include "base/Log.h" -#include "base/IEventQueue.h" -#include "base/TMethodEventJob.h" #include @@ -33,7 +33,7 @@ ClientProxy1_0::ClientProxy1_0(const String& name, synergy::IStream* stream, IEventQueue* events) : ClientProxy(name, stream), - m_heartbeatTimer(NULL), + m_heartbeatTimer(nullptr), m_parser(&ClientProxy1_0::parseHandshakeMessage), m_events(events) { @@ -41,22 +41,22 @@ ClientProxy1_0::ClientProxy1_0(const String& name, synergy::IStream* stream, IEv m_events->adoptHandler(m_events->forIStream().inputReady(), stream->getEventTarget(), new TMethodEventJob(this, - &ClientProxy1_0::handleData, NULL)); + &ClientProxy1_0::handleData, nullptr)); m_events->adoptHandler(m_events->forIStream().outputError(), stream->getEventTarget(), new TMethodEventJob(this, - &ClientProxy1_0::handleWriteError, NULL)); + &ClientProxy1_0::handleWriteError, nullptr)); m_events->adoptHandler(m_events->forIStream().inputShutdown(), stream->getEventTarget(), new TMethodEventJob(this, - &ClientProxy1_0::handleDisconnect, NULL)); + &ClientProxy1_0::handleDisconnect, nullptr)); m_events->adoptHandler(m_events->forIStream().outputShutdown(), stream->getEventTarget(), new TMethodEventJob(this, - &ClientProxy1_0::handleWriteError, NULL)); + &ClientProxy1_0::handleWriteError, nullptr)); m_events->adoptHandler(Event::kTimer, this, new TMethodEventJob(this, - &ClientProxy1_0::handleFlatline, NULL)); + &ClientProxy1_0::handleFlatline, nullptr)); setHeartbeatRate(kHeartRate, kHeartRate * kHeartBeatsUntilDeath); @@ -106,9 +106,9 @@ ClientProxy1_0::addHeartbeatTimer() void ClientProxy1_0::removeHeartbeatTimer() { - if (m_heartbeatTimer != NULL) { + if (m_heartbeatTimer != nullptr) { m_events->deleteTimer(m_heartbeatTimer); - m_heartbeatTimer = NULL; + m_heartbeatTimer = nullptr; } } @@ -127,13 +127,13 @@ ClientProxy1_0::resetHeartbeatRate() } void -ClientProxy1_0::setHeartbeatRate(double, double alarm) +ClientProxy1_0::setHeartbeatRate(double /*unused*/, double alarm) { m_heartbeatAlarm = alarm; } void -ClientProxy1_0::handleData(const Event&, void*) +ClientProxy1_0::handleData(const Event& /*unused*/, void* /*unused*/) { // handle messages until there are no more. first read message code. UInt8 code[4]; @@ -170,7 +170,7 @@ ClientProxy1_0::parseHandshakeMessage(const UInt8* code) LOG((CLOG_DEBUG2 "no-op from", getName().c_str())); return true; } - else if (memcmp(code, kMsgDInfo, 4) == 0) { + if (memcmp(code, kMsgDInfo, 4) == 0) { // future messages get parsed by parseMessage m_parser = &ClientProxy1_0::parseMessage; if (recvInfo()) { @@ -193,7 +193,7 @@ ClientProxy1_0::parseMessage(const UInt8* code) } return false; } - else if (memcmp(code, kMsgCNoop, 4) == 0) { + if (memcmp(code, kMsgCNoop, 4) == 0) { // discard no-ops LOG((CLOG_DEBUG2 "no-op from", getName().c_str())); return true; @@ -208,21 +208,21 @@ ClientProxy1_0::parseMessage(const UInt8* code) } void -ClientProxy1_0::handleDisconnect(const Event&, void*) +ClientProxy1_0::handleDisconnect(const Event& /*unused*/, void* /*unused*/) { LOG((CLOG_NOTE "client \"%s\" has disconnected", getName().c_str())); disconnect(); } void -ClientProxy1_0::handleWriteError(const Event&, void*) +ClientProxy1_0::handleWriteError(const Event& /*unused*/, void* /*unused*/) { LOG((CLOG_WARN "error writing to client \"%s\"", getName().c_str())); disconnect(); } void -ClientProxy1_0::handleFlatline(const Event&, void*) +ClientProxy1_0::handleFlatline(const Event& /*unused*/, void* /*unused*/) { // didn't get a heartbeat fast enough. assume client is dead. LOG((CLOG_NOTE "client \"%s\" is dead", getName().c_str())); @@ -255,7 +255,7 @@ ClientProxy1_0::getCursorPos(SInt32& x, SInt32& y) const void ClientProxy1_0::enter(SInt32 xAbs, SInt32 yAbs, - UInt32 seqNum, KeyModifierMask mask, bool) + UInt32 seqNum, KeyModifierMask mask, bool /*forScreensaver*/) { LOG((CLOG_DEBUG1 "send enter to \"%s\", %d,%d %d %04x", getName().c_str(), xAbs, yAbs, seqNum, mask)); ProtocolUtil::writef(getStream(), kMsgCEnter, @@ -273,7 +273,7 @@ ClientProxy1_0::leave() } void -ClientProxy1_0::setClipboard(ClipboardID id, const IClipboard* clipboard) +ClientProxy1_0::setClipboard(ClipboardID /*id*/, const IClipboard* /*clipboard*/) { // ignore -- deprecated in protocol 1.0 } @@ -295,7 +295,7 @@ ClientProxy1_0::setClipboardDirty(ClipboardID id, bool dirty) } void -ClientProxy1_0::keyDown(KeyID key, KeyModifierMask mask, KeyButton) +ClientProxy1_0::keyDown(KeyID key, KeyModifierMask mask, KeyButton /*unused*/) { LOG((CLOG_DEBUG1 "send key down to \"%s\" id=%d, mask=0x%04x", getName().c_str(), key, mask)); ProtocolUtil::writef(getStream(), kMsgDKeyDown1_0, key, mask); @@ -303,14 +303,14 @@ ClientProxy1_0::keyDown(KeyID key, KeyModifierMask mask, KeyButton) void ClientProxy1_0::keyRepeat(KeyID key, KeyModifierMask mask, - SInt32 count, KeyButton) + SInt32 count, KeyButton /*unused*/) { LOG((CLOG_DEBUG1 "send key repeat to \"%s\" id=%d, mask=0x%04x, count=%d", getName().c_str(), key, mask, count)); ProtocolUtil::writef(getStream(), kMsgDKeyRepeat1_0, key, mask, count); } void -ClientProxy1_0::keyUp(KeyID key, KeyModifierMask mask, KeyButton) +ClientProxy1_0::keyUp(KeyID key, KeyModifierMask mask, KeyButton /*unused*/) { LOG((CLOG_DEBUG1 "send key up to \"%s\" id=%d, mask=0x%04x", getName().c_str(), key, mask)); ProtocolUtil::writef(getStream(), kMsgDKeyUp1_0, key, mask); @@ -338,13 +338,13 @@ ClientProxy1_0::mouseMove(SInt32 xAbs, SInt32 yAbs) } void -ClientProxy1_0::mouseRelativeMove(SInt32, SInt32) +ClientProxy1_0::mouseRelativeMove(SInt32 /*xRel*/, SInt32 /*yRel*/) { // ignore -- not supported in protocol 1.0 } void -ClientProxy1_0::mouseWheel(SInt32, SInt32 yDelta) +ClientProxy1_0::mouseWheel(SInt32 /*xDelta*/, SInt32 yDelta) { // clients prior to 1.3 only support the y axis LOG((CLOG_DEBUG2 "send mouse wheel to \"%s\" %+d", getName().c_str(), yDelta)); @@ -352,14 +352,14 @@ ClientProxy1_0::mouseWheel(SInt32, SInt32 yDelta) } void -ClientProxy1_0::sendDragInfo(UInt32 fileCount, const char* info, size_t size) +ClientProxy1_0::sendDragInfo(UInt32 /*fileCount*/, const char* /*info*/, size_t /*size*/) { // ignore -- not supported in protocol 1.0 LOG((CLOG_DEBUG "draggingInfoSending not supported")); } void -ClientProxy1_0::fileChunkSending(UInt8 mark, char* data, size_t dataSize) +ClientProxy1_0::fileChunkSending(UInt8 /*mark*/, char* /*data*/, size_t /*dataSize*/) { // ignore -- not supported in protocol 1.0 LOG((CLOG_DEBUG "fileChunkSending not supported")); @@ -391,7 +391,7 @@ ClientProxy1_0::setOptions(const OptionsList& options) ProtocolUtil::writef(getStream(), kMsgDSetOptions, &options); // check options - for (UInt32 i = 0, n = (UInt32)options.size(); i < n; i += 2) { + for (UInt32 i = 0, n = static_cast(options.size()); i < n; i += 2) { if (options[i] == kOptionHeartbeat) { double rate = 1.0e-3 * static_cast(options[i + 1]); if (rate <= 0.0) { @@ -462,7 +462,7 @@ ClientProxy1_0::recvGrabClipboard() } // notify - ClipboardInfo* info = new ClipboardInfo; + auto* info = new ClipboardInfo; info->m_id = id; info->m_sequenceNumber = seqNum; m_events->addEvent(Event(m_events->forClipboard().clipboardGrabbed(), @@ -476,7 +476,6 @@ ClientProxy1_0::recvGrabClipboard() // ClientProxy1_0::ClientClipboard::ClientClipboard() : - m_clipboard(), m_sequenceNumber(0), m_dirty(true) { diff --git a/src/lib/server/ClientProxy1_0.h b/src/lib/server/ClientProxy1_0.h index 96fc4c8c..f49e8116 100644 --- a/src/lib/server/ClientProxy1_0.h +++ b/src/lib/server/ClientProxy1_0.h @@ -29,13 +29,13 @@ class IEventQueue; //! Proxy for client implementing protocol version 1.0 class ClientProxy1_0 : public ClientProxy { public: - ClientProxy1_0(const String& name, synergy::IStream* adoptedStream, IEventQueue* events); + ClientProxy1_0(const String& name, synergy::IStream* stream, IEventQueue* events); ~ClientProxy1_0(); // IScreen virtual bool getClipboard(ClipboardID id, IClipboard*) const; virtual void getShape(SInt32& x, SInt32& y, - SInt32& width, SInt32& height) const; + SInt32& w, SInt32& h) const; virtual void getCursorPos(SInt32& x, SInt32& y) const; // IClient overrides @@ -55,7 +55,7 @@ public: virtual void mouseMove(SInt32 xAbs, SInt32 yAbs); virtual void mouseRelativeMove(SInt32 xRel, SInt32 yRel); virtual void mouseWheel(SInt32 xDelta, SInt32 yDelta); - virtual void screensaver(bool activate); + virtual void screensaver(bool on); virtual void resetOptions(); virtual void setOptions(const OptionsList& options); virtual void sendDragInfo(UInt32 fileCount, const char* info, size_t size); @@ -99,8 +99,8 @@ protected: private: typedef bool (ClientProxy1_0::*MessageParser)(const UInt8*); - ClientInfo m_info; - double m_heartbeatAlarm; + ClientInfo m_info{}; + double m_heartbeatAlarm{}; EventQueueTimer* m_heartbeatTimer; MessageParser m_parser; IEventQueue* m_events; diff --git a/src/lib/server/ClientProxy1_1.cpp b/src/lib/server/ClientProxy1_1.cpp index ce6b7443..ebf613de 100644 --- a/src/lib/server/ClientProxy1_1.cpp +++ b/src/lib/server/ClientProxy1_1.cpp @@ -18,8 +18,8 @@ #include "server/ClientProxy1_1.h" -#include "core/ProtocolUtil.h" #include "base/Log.h" +#include "core/ProtocolUtil.h" #include diff --git a/src/lib/server/ClientProxy1_1.h b/src/lib/server/ClientProxy1_1.h index 22cda44f..2e7a5b92 100644 --- a/src/lib/server/ClientProxy1_1.h +++ b/src/lib/server/ClientProxy1_1.h @@ -23,7 +23,7 @@ //! Proxy for client implementing protocol version 1.1 class ClientProxy1_1 : public ClientProxy1_0 { public: - ClientProxy1_1(const String& name, synergy::IStream* adoptedStream, IEventQueue* events); + ClientProxy1_1(const String& name, synergy::IStream* stream, IEventQueue* events); ~ClientProxy1_1(); // IClient overrides diff --git a/src/lib/server/ClientProxy1_2.cpp b/src/lib/server/ClientProxy1_2.cpp index 05f62f47..1e30d710 100644 --- a/src/lib/server/ClientProxy1_2.cpp +++ b/src/lib/server/ClientProxy1_2.cpp @@ -18,8 +18,8 @@ #include "server/ClientProxy1_2.h" -#include "core/ProtocolUtil.h" #include "base/Log.h" +#include "core/ProtocolUtil.h" // // ClientProxy1_1 diff --git a/src/lib/server/ClientProxy1_2.h b/src/lib/server/ClientProxy1_2.h index c54b90d2..0bd4c109 100644 --- a/src/lib/server/ClientProxy1_2.h +++ b/src/lib/server/ClientProxy1_2.h @@ -25,7 +25,7 @@ class IEventQueue; //! Proxy for client implementing protocol version 1.2 class ClientProxy1_2 : public ClientProxy1_1 { public: - ClientProxy1_2(const String& name, synergy::IStream* adoptedStream, IEventQueue* events); + ClientProxy1_2(const String& name, synergy::IStream* stream, IEventQueue* events); ~ClientProxy1_2(); // IClient overrides diff --git a/src/lib/server/ClientProxy1_3.cpp b/src/lib/server/ClientProxy1_3.cpp index 3de7a9ee..ac710845 100644 --- a/src/lib/server/ClientProxy1_3.cpp +++ b/src/lib/server/ClientProxy1_3.cpp @@ -18,10 +18,10 @@ #include "server/ClientProxy1_3.h" -#include "core/ProtocolUtil.h" -#include "base/Log.h" #include "base/IEventQueue.h" +#include "base/Log.h" #include "base/TMethodEventJob.h" +#include "core/ProtocolUtil.h" #include #include @@ -33,7 +33,7 @@ ClientProxy1_3::ClientProxy1_3(const String& name, synergy::IStream* stream, IEventQueue* events) : ClientProxy1_2(name, stream, events), m_keepAliveRate(kKeepAliveRate), - m_keepAliveTimer(NULL), + m_keepAliveTimer(nullptr), m_events(events) { setHeartbeatRate(kKeepAliveRate, kKeepAliveRate * kKeepAlivesUntilDeath); @@ -61,9 +61,9 @@ ClientProxy1_3::parseMessage(const UInt8* code) resetHeartbeatTimer(); return true; } - else { + return ClientProxy1_2::parseMessage(code); - } + } void @@ -73,7 +73,7 @@ ClientProxy1_3::resetHeartbeatRate() } void -ClientProxy1_3::setHeartbeatRate(double rate, double) +ClientProxy1_3::setHeartbeatRate(double rate, double /*alarm*/) { m_keepAliveRate = rate; ClientProxy1_2::setHeartbeatRate(rate, rate * kKeepAlivesUntilDeath); @@ -92,10 +92,10 @@ ClientProxy1_3::addHeartbeatTimer() { // create and install a timer to periodically send keep alives if (m_keepAliveRate > 0.0) { - m_keepAliveTimer = m_events->newTimer(m_keepAliveRate, NULL); + m_keepAliveTimer = m_events->newTimer(m_keepAliveRate, nullptr); m_events->adoptHandler(Event::kTimer, m_keepAliveTimer, new TMethodEventJob(this, - &ClientProxy1_3::handleKeepAlive, NULL)); + &ClientProxy1_3::handleKeepAlive, nullptr)); } // superclass does the alarm @@ -106,10 +106,10 @@ void ClientProxy1_3::removeHeartbeatTimer() { // remove the timer that sends keep alives periodically - if (m_keepAliveTimer != NULL) { + if (m_keepAliveTimer != nullptr) { m_events->removeHandler(Event::kTimer, m_keepAliveTimer); m_events->deleteTimer(m_keepAliveTimer); - m_keepAliveTimer = NULL; + m_keepAliveTimer = nullptr; } // superclass does the alarm @@ -117,7 +117,7 @@ ClientProxy1_3::removeHeartbeatTimer() } void -ClientProxy1_3::handleKeepAlive(const Event&, void*) +ClientProxy1_3::handleKeepAlive(const Event& /*unused*/, void* /*unused*/) { keepAlive(); } diff --git a/src/lib/server/ClientProxy1_3.h b/src/lib/server/ClientProxy1_3.h index 37299ca6..88305d04 100644 --- a/src/lib/server/ClientProxy1_3.h +++ b/src/lib/server/ClientProxy1_3.h @@ -23,7 +23,7 @@ //! Proxy for client implementing protocol version 1.3 class ClientProxy1_3 : public ClientProxy1_2 { public: - ClientProxy1_3(const String& name, synergy::IStream* adoptedStream, IEventQueue* events); + ClientProxy1_3(const String& name, synergy::IStream* stream, IEventQueue* events); ~ClientProxy1_3(); // IClient overrides diff --git a/src/lib/server/ClientProxy1_4.cpp b/src/lib/server/ClientProxy1_4.cpp index 49669f9f..f85fb8bd 100644 --- a/src/lib/server/ClientProxy1_4.cpp +++ b/src/lib/server/ClientProxy1_4.cpp @@ -18,11 +18,11 @@ #include "server/ClientProxy1_4.h" -#include "server/Server.h" -#include "core/ProtocolUtil.h" -#include "base/Log.h" #include "base/IEventQueue.h" +#include "base/Log.h" #include "base/TMethodEventJob.h" +#include "core/ProtocolUtil.h" +#include "server/Server.h" #include #include @@ -38,8 +38,7 @@ ClientProxy1_4::ClientProxy1_4(const String& name, synergy::IStream* stream, Ser } ClientProxy1_4::~ClientProxy1_4() -{ -} += default; void ClientProxy1_4::keyDown(KeyID key, KeyModifierMask mask, KeyButton button) diff --git a/src/lib/server/ClientProxy1_4.h b/src/lib/server/ClientProxy1_4.h index 8b08bc13..c63642c6 100644 --- a/src/lib/server/ClientProxy1_4.h +++ b/src/lib/server/ClientProxy1_4.h @@ -25,7 +25,7 @@ class Server; //! Proxy for client implementing protocol version 1.4 class ClientProxy1_4 : public ClientProxy1_3 { public: - ClientProxy1_4(const String& name, synergy::IStream* adoptedStream, Server* server, IEventQueue* events); + ClientProxy1_4(const String& name, synergy::IStream* stream, Server* server, IEventQueue* events); ~ClientProxy1_4(); //! @name accessors diff --git a/src/lib/server/ClientProxy1_5.cpp b/src/lib/server/ClientProxy1_5.cpp index 812fe545..51d8573c 100644 --- a/src/lib/server/ClientProxy1_5.cpp +++ b/src/lib/server/ClientProxy1_5.cpp @@ -17,13 +17,13 @@ #include "server/ClientProxy1_5.h" -#include "server/Server.h" -#include "core/FileChunk.h" -#include "core/StreamChunker.h" -#include "core/ProtocolUtil.h" -#include "io/IStream.h" -#include "base/TMethodEventJob.h" #include "base/Log.h" +#include "base/TMethodEventJob.h" +#include "core/FileChunk.h" +#include "core/ProtocolUtil.h" +#include "core/StreamChunker.h" +#include "io/IStream.h" +#include "server/Server.h" #include @@ -39,7 +39,7 @@ ClientProxy1_5::ClientProxy1_5(const String& name, synergy::IStream* stream, Ser m_events->adoptHandler(m_events->forFile().keepAlive(), this, new TMethodEventJob(this, - &ClientProxy1_3::handleKeepAlive, NULL)); + &ClientProxy1_3::handleKeepAlive, nullptr)); } ClientProxy1_5::~ClientProxy1_5() @@ -91,7 +91,7 @@ ClientProxy1_5::fileChunkReceived() m_events->addEvent(Event(m_events->forFile().fileRecieveCompleted(), server)); } else if (result == kStart) { - if (server->getFakeDragFileList().size() > 0) { + if (!server->getFakeDragFileList().empty()) { String filename = server->getFakeDragFileList().at(0).getFilename(); LOG((CLOG_DEBUG "start receiving %s", filename.c_str())); } diff --git a/src/lib/server/ClientProxy1_5.h b/src/lib/server/ClientProxy1_5.h index 1d541005..0d8ed0a4 100644 --- a/src/lib/server/ClientProxy1_5.h +++ b/src/lib/server/ClientProxy1_5.h @@ -27,7 +27,7 @@ class IEventQueue; //! Proxy for client implementing protocol version 1.5 class ClientProxy1_5 : public ClientProxy1_4 { public: - ClientProxy1_5(const String& name, synergy::IStream* adoptedStream, Server* server, IEventQueue* events); + ClientProxy1_5(const String& name, synergy::IStream* stream, Server* server, IEventQueue* events); ~ClientProxy1_5(); virtual void sendDragInfo(UInt32 fileCount, const char* info, size_t size); diff --git a/src/lib/server/ClientProxy1_6.cpp b/src/lib/server/ClientProxy1_6.cpp index f36a9f0c..fa4417ad 100644 --- a/src/lib/server/ClientProxy1_6.cpp +++ b/src/lib/server/ClientProxy1_6.cpp @@ -17,13 +17,13 @@ #include "server/ClientProxy1_6.h" -#include "server/Server.h" +#include "base/Log.h" +#include "base/TMethodEventJob.h" +#include "core/ClipboardChunk.h" #include "core/ProtocolUtil.h" #include "core/StreamChunker.h" -#include "core/ClipboardChunk.h" #include "io/IStream.h" -#include "base/TMethodEventJob.h" -#include "base/Log.h" +#include "server/Server.h" // // ClientProxy1_6 @@ -40,8 +40,7 @@ ClientProxy1_6::ClientProxy1_6(const String& name, synergy::IStream* stream, Ser } ClientProxy1_6::~ClientProxy1_6() -{ -} += default; void ClientProxy1_6::setClipboard(ClipboardID id, const IClipboard* clipboard) @@ -62,7 +61,7 @@ ClientProxy1_6::setClipboard(ClipboardID id, const IClipboard* clipboard) } void -ClientProxy1_6::handleClipboardSendingEvent(const Event& event, void*) +ClientProxy1_6::handleClipboardSendingEvent(const Event& event, void* /*unused*/) { ClipboardChunk::send(getStream(), event.getData()); } @@ -89,7 +88,7 @@ ClientProxy1_6::recvClipboard() m_clipboard[id].m_sequenceNumber = seq; // notify - ClipboardInfo* info = new ClipboardInfo; + auto* info = new ClipboardInfo; info->m_id = id; info->m_sequenceNumber = seq; m_events->addEvent(Event(m_events->forClipboard().clipboardChanged(), diff --git a/src/lib/server/ClientProxy1_6.h b/src/lib/server/ClientProxy1_6.h index 395365e6..6df34ccf 100644 --- a/src/lib/server/ClientProxy1_6.h +++ b/src/lib/server/ClientProxy1_6.h @@ -25,7 +25,7 @@ class IEventQueue; //! Proxy for client implementing protocol version 1.6 class ClientProxy1_6 : public ClientProxy1_5 { public: - ClientProxy1_6(const String& name, synergy::IStream* adoptedStream, Server* server, IEventQueue* events); + ClientProxy1_6(const String& name, synergy::IStream* stream, Server* server, IEventQueue* events); ~ClientProxy1_6(); virtual void setClipboard(ClipboardID id, const IClipboard* clipboard); diff --git a/src/lib/server/ClientProxyUnknown.cpp b/src/lib/server/ClientProxyUnknown.cpp index bc0fd4a6..b97d1971 100644 --- a/src/lib/server/ClientProxyUnknown.cpp +++ b/src/lib/server/ClientProxyUnknown.cpp @@ -18,7 +18,15 @@ #include "server/ClientProxyUnknown.h" -#include "server/Server.h" +#include "base/IEventQueue.h" +#include "base/Log.h" +#include "base/String.h" +#include "base/TMethodEventJob.h" +#include "core/ProtocolUtil.h" +#include "core/XSynergy.h" +#include "core/protocol_types.h" +#include "io/IStream.h" +#include "io/XIO.h" #include "server/ClientProxy1_0.h" #include "server/ClientProxy1_1.h" #include "server/ClientProxy1_2.h" @@ -26,15 +34,7 @@ #include "server/ClientProxy1_4.h" #include "server/ClientProxy1_5.h" #include "server/ClientProxy1_6.h" -#include "core/protocol_types.h" -#include "core/ProtocolUtil.h" -#include "core/XSynergy.h" -#include "io/IStream.h" -#include "io/XIO.h" -#include "base/Log.h" -#include "base/String.h" -#include "base/IEventQueue.h" -#include "base/TMethodEventJob.h" +#include "server/Server.h" // // ClientProxyUnknown @@ -42,7 +42,7 @@ ClientProxyUnknown::ClientProxyUnknown(synergy::IStream* stream, double timeout, Server* server, IEventQueue* events) : m_stream(stream), - m_proxy(NULL), + m_proxy(nullptr), m_ready(false), m_server(server), m_events(events) @@ -51,7 +51,7 @@ ClientProxyUnknown::ClientProxyUnknown(synergy::IStream* stream, double timeout, m_events->adoptHandler(Event::kTimer, this, new TMethodEventJob(this, - &ClientProxyUnknown::handleTimeout, NULL)); + &ClientProxyUnknown::handleTimeout, nullptr)); m_timer = m_events->newOneShotTimer(timeout, this); addStreamHandlers(); @@ -75,12 +75,12 @@ ClientProxyUnknown::orphanClientProxy() if (m_ready) { removeHandlers(); ClientProxy* proxy = m_proxy; - m_proxy = NULL; + m_proxy = nullptr; return proxy; } - else { - return NULL; - } + + return nullptr; + } void @@ -95,7 +95,7 @@ void ClientProxyUnknown::sendFailure() { delete m_proxy; - m_proxy = NULL; + m_proxy = nullptr; m_ready = false; removeHandlers(); removeTimer(); @@ -143,7 +143,7 @@ ClientProxyUnknown::addProxyHandlers() void ClientProxyUnknown::removeHandlers() { - if (m_stream != NULL) { + if (m_stream != nullptr) { m_events->removeHandler(m_events->forIStream().inputReady(), m_stream->getEventTarget()); m_events->removeHandler(m_events->forIStream().outputError(), @@ -153,7 +153,7 @@ ClientProxyUnknown::removeHandlers() m_events->removeHandler(m_events->forIStream().outputShutdown(), m_stream->getEventTarget()); } - if (m_proxy != NULL) { + if (m_proxy != nullptr) { m_events->removeHandler(m_events->forClientProxy().ready(), m_proxy); m_events->removeHandler(m_events->forClientProxy().disconnected(), @@ -164,15 +164,15 @@ ClientProxyUnknown::removeHandlers() void ClientProxyUnknown::removeTimer() { - if (m_timer != NULL) { + if (m_timer != nullptr) { m_events->deleteTimer(m_timer); m_events->removeHandler(Event::kTimer, this); - m_timer = NULL; + m_timer = nullptr; } } void -ClientProxyUnknown::handleData(const Event&, void*) +ClientProxyUnknown::handleData(const Event& /*unused*/, void* /*unused*/) { LOG((CLOG_DEBUG1 "parsing hello reply")); @@ -236,13 +236,13 @@ ClientProxyUnknown::handleData(const Event&, void*) } // hangup (with error) if version isn't supported - if (m_proxy == NULL) { + if (m_proxy == nullptr) { throw XIncompatibleClient(major, minor); } // the proxy is created and now proxy now owns the stream LOG((CLOG_DEBUG1 "created proxy for client \"%s\" version %d.%d", name.c_str(), major, minor)); - m_stream = NULL; + m_stream = nullptr; // wait until the proxy signals that it's ready or has disconnected addProxyHandlers(); @@ -268,28 +268,28 @@ ClientProxyUnknown::handleData(const Event&, void*) } void -ClientProxyUnknown::handleWriteError(const Event&, void*) +ClientProxyUnknown::handleWriteError(const Event& /*unused*/, void* /*unused*/) { LOG((CLOG_NOTE "error communicating with new client")); sendFailure(); } void -ClientProxyUnknown::handleTimeout(const Event&, void*) +ClientProxyUnknown::handleTimeout(const Event& /*unused*/, void* /*unused*/) { LOG((CLOG_NOTE "new client is unresponsive")); sendFailure(); } void -ClientProxyUnknown::handleDisconnect(const Event&, void*) +ClientProxyUnknown::handleDisconnect(const Event& /*unused*/, void* /*unused*/) { LOG((CLOG_NOTE "new client disconnected")); sendFailure(); } void -ClientProxyUnknown::handleReady(const Event&, void*) +ClientProxyUnknown::handleReady(const Event& /*unused*/, void* /*unused*/) { sendSuccess(); } diff --git a/src/lib/server/Config.cpp b/src/lib/server/Config.cpp index c5cf8573..f9284138 100644 --- a/src/lib/server/Config.cpp +++ b/src/lib/server/Config.cpp @@ -18,13 +18,13 @@ #include "server/Config.h" -#include "server/Server.h" -#include "core/KeyMap.h" -#include "core/key_types.h" -#include "net/XSocket.h" #include "base/IEventQueue.h" #include "common/stdistream.h" #include "common/stdostream.h" +#include "core/KeyMap.h" +#include "core/key_types.h" +#include "net/XSocket.h" +#include "server/Server.h" #include @@ -70,7 +70,7 @@ Config::renameScreen(const String& oldName, { // get canonical name and find cell String oldCanonical = getCanonicalName(oldName); - CellMap::iterator index = m_map.find(oldCanonical); + auto index = m_map.find(oldCanonical); if (index == m_map.end()) { return false; } @@ -99,11 +99,10 @@ Config::renameScreen(const String& oldName, // update alias targets if (CaselessCmp::equal(oldName, oldCanonical)) { - for (NameMap::iterator iter = m_nameToCanonicalName.begin(); - iter != m_nameToCanonicalName.end(); ++iter) { + for (auto & iter : m_nameToCanonicalName) { if (CaselessCmp::equal( - iter->second, oldCanonical)) { - iter->second = newName; + iter.second, oldCanonical)) { + iter.second = newName; } } } @@ -116,7 +115,7 @@ Config::removeScreen(const String& name) { // get canonical name and find cell String canonical = getCanonicalName(name); - CellMap::iterator index = m_map.find(canonical); + auto index = m_map.find(canonical); if (index == m_map.end()) { return; } @@ -131,7 +130,7 @@ Config::removeScreen(const String& name) } // remove aliases (and canonical name) - for (NameMap::iterator iter = m_nameToCanonicalName.begin(); + for (auto iter = m_nameToCanonicalName.begin(); iter != m_nameToCanonicalName.end(); ) { if (iter->second == canonical) { m_nameToCanonicalName.erase(iter++); @@ -177,7 +176,7 @@ Config::removeAlias(const String& alias) } // find alias - NameMap::iterator index = m_nameToCanonicalName.find(alias); + auto index = m_nameToCanonicalName.find(alias); if (index == m_nameToCanonicalName.end()) { return false; } @@ -197,7 +196,7 @@ Config::removeAliases(const String& canonical) } // find and removing matching aliases - for (NameMap::iterator index = m_nameToCanonicalName.begin(); + for (auto index = m_nameToCanonicalName.begin(); index != m_nameToCanonicalName.end(); ) { if (index->second == canonical && index->first != canonical) { m_nameToCanonicalName.erase(index++); @@ -217,10 +216,9 @@ Config::removeAllAliases() m_nameToCanonicalName.clear(); // put the canonical names back in - for (CellMap::iterator index = m_map.begin(); - index != m_map.end(); ++index) { + for (auto & index : m_map) { m_nameToCanonicalName.insert( - std::make_pair(index->first, index->first)); + std::make_pair(index.first, index.first)); } } @@ -234,7 +232,7 @@ Config::connect(const String& srcName, assert(srcSide >= kFirstDirection && srcSide <= kLastDirection); // find source cell - CellMap::iterator index = m_map.find(getCanonicalName(srcName)); + auto index = m_map.find(getCanonicalName(srcName)); if (index == m_map.end()) { return false; } @@ -251,7 +249,7 @@ Config::disconnect(const String& srcName, EDirection srcSide) assert(srcSide >= kFirstDirection && srcSide <= kLastDirection); // find source cell - CellMap::iterator index = m_map.find(srcName); + auto index = m_map.find(srcName); if (index == m_map.end()) { return false; } @@ -268,7 +266,7 @@ Config::disconnect(const String& srcName, EDirection srcSide, float position) assert(srcSide >= kFirstDirection && srcSide <= kLastDirection); // find source cell - CellMap::iterator index = m_map.find(srcName); + auto index = m_map.find(srcName); if (index == m_map.end()) { return false; } @@ -289,17 +287,17 @@ bool Config::addOption(const String& name, OptionID option, OptionValue value) { // find options - ScreenOptions* options = NULL; + ScreenOptions* options = nullptr; if (name.empty()) { options = &m_globalOptions; } else { - CellMap::iterator index = m_map.find(name); + auto index = m_map.find(name); if (index != m_map.end()) { options = &index->second.m_options; } } - if (options == NULL) { + if (options == nullptr) { return false; } @@ -312,17 +310,17 @@ bool Config::removeOption(const String& name, OptionID option) { // find options - ScreenOptions* options = NULL; + ScreenOptions* options = nullptr; if (name.empty()) { options = &m_globalOptions; } else { - CellMap::iterator index = m_map.find(name); + auto index = m_map.find(name); if (index != m_map.end()) { options = &index->second.m_options; } } - if (options == NULL) { + if (options == nullptr) { return false; } @@ -335,17 +333,17 @@ bool Config::removeOptions(const String& name) { // find options - ScreenOptions* options = NULL; + ScreenOptions* options = nullptr; if (name.empty()) { options = &m_globalOptions; } else { - CellMap::iterator index = m_map.find(name); + auto index = m_map.find(name); if (index != m_map.end()) { options = &index->second.m_options; } } - if (options == NULL) { + if (options == nullptr) { return false; } @@ -389,14 +387,14 @@ Config::isValidScreenName(const String& name) const } // check first and last characters - if (!(isalnum(name[b]) || name[b] == '_') || - !(isalnum(name[e - 1]) || name[e - 1] == '_')) { + if (!((isalnum(name[b]) != 0) || name[b] == '_') || + !((isalnum(name[e - 1]) != 0) || name[e - 1] == '_')) { return false; } // check interior characters for (String::size_type i = b; i < e; ++i) { - if (!isalnum(name[i]) && name[i] != '_' && name[i] != '-') { + if ((isalnum(name[i]) == 0) && name[i] != '_' && name[i] != '-') { return false; } } @@ -452,13 +450,13 @@ Config::isCanonicalName(const String& name) const String Config::getCanonicalName(const String& name) const { - NameMap::const_iterator index = m_nameToCanonicalName.find(name); + auto index = m_nameToCanonicalName.find(name); if (index == m_nameToCanonicalName.end()) { return String(); } - else { + return index->second; - } + } String @@ -468,7 +466,7 @@ Config::getNeighbor(const String& srcName, EDirection srcSide, assert(srcSide >= kFirstDirection && srcSide <= kLastDirection); // find source cell - CellMap::const_iterator index = m_map.find(getCanonicalName(srcName)); + auto index = m_map.find(getCanonicalName(srcName)); if (index == m_map.end()) { return String(); } @@ -479,16 +477,16 @@ Config::getNeighbor(const String& srcName, EDirection srcSide, // no neighbor return ""; } - else { + // compute position on neighbor - if (positionOut != NULL) { + if (positionOut != nullptr) { *positionOut = dstEdge->inverseTransform(srcEdge->transform(position)); } // return neighbor's name return getCanonicalName(dstEdge->getName()); - } + } bool @@ -504,7 +502,7 @@ Config::hasNeighbor(const String& srcName, EDirection srcSide, assert(srcSide >= kFirstDirection && srcSide <= kLastDirection); // find source cell - CellMap::const_iterator index = m_map.find(getCanonicalName(srcName)); + auto index = m_map.find(getCanonicalName(srcName)); if (index == m_map.end()) { return false; } @@ -515,7 +513,7 @@ Config::hasNeighbor(const String& srcName, EDirection srcSide, Config::link_const_iterator Config::beginNeighbor(const String& srcName) const { - CellMap::const_iterator index = m_map.find(getCanonicalName(srcName)); + auto index = m_map.find(getCanonicalName(srcName)); assert(index != m_map.end()); return index->second.begin(); } @@ -523,7 +521,7 @@ Config::beginNeighbor(const String& srcName) const Config::link_const_iterator Config::endNeighbor(const String& srcName) const { - CellMap::const_iterator index = m_map.find(getCanonicalName(srcName)); + auto index = m_map.find(getCanonicalName(srcName)); assert(index != m_map.end()); return index->second.end(); } @@ -538,12 +536,12 @@ const Config::ScreenOptions* Config::getOptions(const String& name) const { // find options - const ScreenOptions* options = NULL; + const ScreenOptions* options = nullptr; if (name.empty()) { options = &m_globalOptions; } else { - CellMap::const_iterator index = m_map.find(name); + auto index = m_map.find(name); if (index != m_map.end()) { options = &index->second.m_options; } @@ -577,7 +575,7 @@ Config::operator==(const Config& x) const return false; } - for (CellMap::const_iterator index1 = m_map.begin(), + for (auto index1 = m_map.begin(), index2 = x.m_map.begin(); index1 != m_map.end(); ++index1, ++index2) { // compare names @@ -591,7 +589,7 @@ Config::operator==(const Config& x) const } } - for (NameMap::const_iterator index1 = m_nameToCanonicalName.begin(), + for (auto index1 = m_nameToCanonicalName.begin(), index2 = x.m_nameToCanonicalName.begin(); index1 != m_nameToCanonicalName.end(); ++index1, ++index2) { @@ -602,11 +600,7 @@ Config::operator==(const Config& x) const } // compare input filters - if (m_inputFilter != x.m_inputFilter) { - return false; - } - - return true; + return m_inputFilter == x.m_inputFilter; } bool @@ -647,8 +641,8 @@ Config::formatInterval(const Interval& x) if (x.first == 0.0f && x.second == 1.0f) { return ""; } - return synergy::string::sprintf("(%d,%d)", (int)(x.first * 100.0f + 0.5f), - (int)(x.second * 100.0f + 0.5f)); + return synergy::string::sprintf("(%d,%d)", static_cast(x.first * 100.0f + 0.5f), + static_cast(x.second * 100.0f + 0.5f)); } void @@ -776,7 +770,7 @@ Config::readSectionOptions(ConfigReadContext& s) if (handled) { // make sure handled options aren't followed by more values if (i < line.size() && (line[i] == ',' || line[i] == ';')) { - throw XConfigRead(s, "to many arguments to %s", name.c_str()); + throw XConfigRead(s, "to many arguments to %s", name); } } else { @@ -1100,7 +1094,7 @@ Config::parseAction(ConfigReadContext& s, InputFilter::Action* action; if (name == "keystroke" || name == "keyDown" || name == "keyUp") { - if (args.size() < 1 || args.size() > 2) { + if (args.empty() || args.size() > 2) { throw XConfigRead(s, "syntax for action: keystroke(modifiers+key[,screens])"); } @@ -1243,7 +1237,7 @@ Config::parseAction(ConfigReadContext& s, InputFilter::KeyboardBroadcastAction::Mode mode = InputFilter::KeyboardBroadcastAction::kToggle; - if (args.size() >= 1) { + if (!args.empty()) { if (args[0] == "off") { mode = InputFilter::KeyboardBroadcastAction::kOff; } @@ -1383,7 +1377,7 @@ Config::getOptionName(OptionID id) if (id == kOptionClipboardSharing) { return "clipboardSharing"; } - return NULL; + return nullptr; } String @@ -1585,7 +1579,7 @@ Config::CellEdge::operator<(const CellEdge& o) const if (static_cast(m_side) < static_cast(o.m_side)) { return true; } - else if (static_cast(m_side) > static_cast(o.m_side)) { + if (static_cast(m_side) > static_cast(o.m_side)) { return false; } @@ -1626,7 +1620,7 @@ Config::Cell::add(const CellEdge& src, const CellEdge& dst) void Config::Cell::remove(EDirection side) { - for (EdgeLinks::iterator j = m_neighbors.begin(); + for (auto j = m_neighbors.begin(); j != m_neighbors.end(); ) { if (j->first.getSide() == side) { m_neighbors.erase(j++); @@ -1640,7 +1634,7 @@ Config::Cell::remove(EDirection side) void Config::Cell::remove(EDirection side, float position) { - for (EdgeLinks::iterator j = m_neighbors.begin(); + for (auto j = m_neighbors.begin(); j != m_neighbors.end(); ++j) { if (j->first.getSide() == side && j->first.isInside(position)) { m_neighbors.erase(j); @@ -1651,7 +1645,7 @@ Config::Cell::remove(EDirection side, float position) void Config::Cell::remove(const Name& name) { - for (EdgeLinks::iterator j = m_neighbors.begin(); + for (auto j = m_neighbors.begin(); j != m_neighbors.end(); ) { if (name == j->second.getName()) { m_neighbors.erase(j++); @@ -1665,10 +1659,9 @@ Config::Cell::remove(const Name& name) void Config::Cell::rename(const Name& oldName, const String& newName) { - for (EdgeLinks::iterator j = m_neighbors.begin(); - j != m_neighbors.end(); ++j) { - if (oldName == j->second.getName()) { - j->second.setName(newName); + for (auto & m_neighbor : m_neighbors) { + if (oldName == m_neighbor.second.getName()) { + m_neighbor.second.setName(newName); } } } @@ -1676,14 +1669,14 @@ Config::Cell::rename(const Name& oldName, const String& newName) bool Config::Cell::hasEdge(const CellEdge& edge) const { - EdgeLinks::const_iterator i = m_neighbors.find(edge); + auto i = m_neighbors.find(edge); return (i != m_neighbors.end() && i->first == edge); } bool Config::Cell::overlaps(const CellEdge& edge) const { - EdgeLinks::const_iterator i = m_neighbors.upper_bound(edge); + auto i = m_neighbors.upper_bound(edge); if (i != m_neighbors.end() && i->first.overlaps(edge)) { return true; } @@ -1698,7 +1691,7 @@ Config::Cell::getLink(EDirection side, float position, const CellEdge*& src, const CellEdge*& dst) const { CellEdge edge(side, position); - EdgeLinks::const_iterator i = m_neighbors.upper_bound(edge); + auto i = m_neighbors.upper_bound(edge); if (i == m_neighbors.begin()) { return false; } @@ -1723,7 +1716,7 @@ Config::Cell::operator==(const Cell& x) const if (m_neighbors.size() != x.m_neighbors.size()) { return false; } - for (EdgeLinks::const_iterator index1 = m_neighbors.begin(), + for (auto index1 = m_neighbors.begin(), index2 = x.m_neighbors.begin(); index1 != m_neighbors.end(); ++index1, ++index2) { @@ -1784,14 +1777,12 @@ operator<<(std::ostream& s, const Config& config) screen != config.end(); ++screen) { s << "\t" << screen->c_str() << ":" << std::endl; const Config::ScreenOptions* options = config.getOptions(*screen); - if (options != NULL && options->size() > 0) { - for (Config::ScreenOptions::const_iterator - option = options->begin(); - option != options->end(); ++option) { - const char* name = Config::getOptionName(option->first); - String value = Config::getOptionValue(option->first, - option->second); - if (name != NULL && !value.empty()) { + if (options != nullptr && !options->empty()) { + for (auto option : *options) { + const char* name = Config::getOptionName(option.first); + String value = Config::getOptionValue(option.first, + option.second); + if (name != nullptr && !value.empty()) { s << "\t\t" << name << " = " << value << std::endl; } } @@ -1806,7 +1797,7 @@ operator<<(std::ostream& s, const Config& config) screen != config.end(); ++screen) { s << "\t" << screen->c_str() << ":" << std::endl; - for (Config::link_const_iterator + for (auto link = config.beginNeighbor(*screen), nend = config.endNeighbor(*screen); link != nend; ++link) { s << "\t\t" << Config::dirName(link->first.getSide()) << @@ -1824,12 +1815,9 @@ operator<<(std::ostream& s, const Config& config) typedef std::multimap CMNameMap; CMNameMap aliases; - for (Config::NameMap::const_iterator - index = config.m_nameToCanonicalName.begin(); - index != config.m_nameToCanonicalName.end(); - ++index) { - if (index->first != index->second) { - aliases.insert(std::make_pair(index->second, index->first)); + for (const auto & index : config.m_nameToCanonicalName) { + if (index.first != index.second) { + aliases.insert(std::make_pair(index.second, index.first)); } } @@ -1850,14 +1838,12 @@ operator<<(std::ostream& s, const Config& config) // options section s << "section: options" << std::endl; const Config::ScreenOptions* options = config.getOptions(""); - if (options != NULL && options->size() > 0) { - for (Config::ScreenOptions::const_iterator - option = options->begin(); - option != options->end(); ++option) { - const char* name = Config::getOptionName(option->first); - String value = Config::getOptionValue(option->first, - option->second); - if (name != NULL && !value.empty()) { + if (options != nullptr && !options->empty()) { + for (auto option : *options) { + const char* name = Config::getOptionName(option.first); + String value = Config::getOptionValue(option.first, + option.second); + if (name != nullptr && !value.empty()) { s << "\t" << name << " = " << value << std::endl; } } @@ -1914,7 +1900,7 @@ ConfigReadContext::readLine(String& line) if (!line.empty()) { // make sure there are no invalid characters for (i = 0; i < line.length(); ++i) { - if (!isgraph(line[i]) && line[i] != ' ' && line[i] != '\t') { + if ((isgraph(line[i]) == 0) && line[i] != ' ' && line[i] != '\t') { throw XConfigRead(*this, "invalid character %{1}", synergy::string::sprintf("%#2x", line[i])); @@ -1964,7 +1950,7 @@ ConfigReadContext::parseInt(const String& arg) const // invalid characters throw XConfigRead(*this, "invalid integer argument \"%{1}\"", arg); } - OptionValue value = static_cast(tmp); + auto value = static_cast(tmp); if (value != tmp) { // out of range throw XConfigRead(*this, "integer argument \"%{1}\" out of range", arg); @@ -2005,7 +1991,7 @@ ConfigReadContext::parseCorner(const String& arg) const if (CaselessCmp::equal(arg, "left")) { return kTopLeftMask | kBottomLeftMask; } - else if (CaselessCmp::equal(arg, "right")) { + if (CaselessCmp::equal(arg, "right")) { return kTopRightMask | kBottomRightMask; } else if (CaselessCmp::equal(arg, "top")) { @@ -2088,7 +2074,7 @@ ConfigReadContext::parseCorners(const String& args) const Config::Interval ConfigReadContext::parseInterval(const ArgList& args) const { - if (args.size() == 0) { + if (args.empty()) { return Config::Interval(0.0f, 1.0f); } if (args.size() != 2 || args[0].empty() || args[1].empty()) { @@ -2217,7 +2203,6 @@ ConfigReadContext::parseNameWithArgs( } index = j; - return; } IPlatformScreen::KeyInfo* @@ -2260,7 +2245,7 @@ ConfigReadContext::parseMouse(const String& mouse) const } char* end; - ButtonID button = (ButtonID)strtol(s.c_str(), &end, 10); + auto button = static_cast(strtol(s.c_str(), &end, 10)); if (*end != '\0') { throw XConfigRead(*this, "unable to parse button"); } @@ -2323,13 +2308,13 @@ XConfigRead::XConfigRead(const ConfigReadContext& context, // do nothing } -XConfigRead::~XConfigRead() _NOEXCEPT +XConfigRead::~XConfigRead() noexcept { // do nothing } String -XConfigRead::getWhat() const throw() +XConfigRead::getWhat() const noexcept { return format("XConfigRead", "read error: %{1}", m_error.c_str()); } diff --git a/src/lib/server/Config.h b/src/lib/server/Config.h index 5b2ab865..29598f77 100644 --- a/src/lib/server/Config.h +++ b/src/lib/server/Config.h @@ -119,7 +119,7 @@ private: bool add(const CellEdge& src, const CellEdge& dst); void remove(EDirection side); void remove(EDirection side, float position); - void remove(const Name& destinationName); + void remove(const Name& name); void rename(const Name& oldName, const String& newName); bool hasEdge(const CellEdge&) const; @@ -459,10 +459,10 @@ private: InputFilter::Condition* parseCondition(ConfigReadContext&, - const String& condition, + const String& name, const std::vector& args); void parseAction(ConfigReadContext&, - const String& action, + const String& name, const std::vector& args, InputFilter::Rule&, bool activate); diff --git a/src/lib/server/InputFilter.cpp b/src/lib/server/InputFilter.cpp index d9c68255..6c7a4154 100644 --- a/src/lib/server/InputFilter.cpp +++ b/src/lib/server/InputFilter.cpp @@ -17,15 +17,16 @@ */ #include "server/InputFilter.h" -#include "server/Server.h" -#include "server/PrimaryClient.h" -#include "core/KeyMap.h" #include "base/EventQueue.h" #include "base/Log.h" #include "base/TMethodEventJob.h" +#include "core/KeyMap.h" +#include "server/PrimaryClient.h" +#include "server/Server.h" #include #include +#include // ----------------------------------------------------------------------------- // Input Filter Condition Classes @@ -41,13 +42,13 @@ InputFilter::Condition::~Condition() } void -InputFilter::Condition::enablePrimary(PrimaryClient*) +InputFilter::Condition::enablePrimary(PrimaryClient* /*unused*/) { // do nothing } void -InputFilter::Condition::disablePrimary(PrimaryClient*) +InputFilter::Condition::disablePrimary(PrimaryClient* /*unused*/) { // do nothing } @@ -120,7 +121,7 @@ InputFilter::KeystrokeCondition::match(const Event& event) } // check if it's our hotkey - IPrimaryScreen::HotKeyInfo* kinfo = + auto* kinfo = static_cast(event.getData()); if (kinfo->m_id != m_id) { return kNoMatch; @@ -216,7 +217,7 @@ InputFilter::MouseButtonCondition::match(const Event& event) // check if it's the right button and modifiers. ignore modifiers // that cannot be combined with a mouse button. - IPlatformScreen::ButtonInfo* minfo = + auto* minfo = static_cast(event.getData()); if (minfo->m_button != m_button || (minfo->m_mask & ~s_ignoreMask) != m_mask) { @@ -227,8 +228,8 @@ InputFilter::MouseButtonCondition::match(const Event& event) } InputFilter::ScreenConnectedCondition::ScreenConnectedCondition( - IEventQueue* events, const String& screen) : - m_screen(screen), + IEventQueue* events, String screen) : + m_screen(std::move(screen)), m_events(events) { // do nothing @@ -255,7 +256,7 @@ InputFilter::EFilterStatus InputFilter::ScreenConnectedCondition::match(const Event& event) { if (event.getType() == m_events->forServer().connected()) { - Server::ScreenConnectedInfo* info = + auto* info = static_cast(event.getData()); if (m_screen == info->m_screen || m_screen.empty()) { return kActivate; @@ -324,8 +325,8 @@ InputFilter::LockCursorToScreenAction::perform(const Event& event) } InputFilter::SwitchToScreenAction::SwitchToScreenAction( - IEventQueue* events, const String& screen) : - m_screen(screen), + IEventQueue* events, String screen) : + m_screen(std::move(screen)), m_events(events) { // do nothing @@ -356,7 +357,7 @@ InputFilter::SwitchToScreenAction::perform(const Event& event) // event if it has one. String screen = m_screen; if (screen.empty() && event.getType() == m_events->forServer().connected()) { - Server::ScreenConnectedInfo* info = + auto* info = static_cast(event.getData()); screen = info->m_screen; } @@ -461,11 +462,11 @@ InputFilter::KeyboardBroadcastAction::format() const if (m_screens.empty() || m_screens[0] == '*') { return synergy::string::sprintf("%s(%s)", s_name, s_mode[m_mode]); } - else { + return synergy::string::sprintf("%s(%s,%.*s)", s_name, s_mode[m_mode], m_screens.size() - 2, m_screens.c_str() + 1); - } + } void @@ -535,7 +536,7 @@ InputFilter::KeystrokeAction::format() const synergy::KeyMap::formatKey(m_keyInfo->m_key, m_keyInfo->m_mask).c_str()); } - else if (m_keyInfo->m_screens[0] == '*') { + if (m_keyInfo->m_screens[0] == '*') { return synergy::string::sprintf("%s(%s,*)", type, synergy::KeyMap::formatKey(m_keyInfo->m_key, m_keyInfo->m_mask).c_str()); @@ -557,13 +558,13 @@ InputFilter::KeystrokeAction::perform(const Event& event) m_events->forIKeyState().keyUp(); m_events->addEvent(Event(m_events->forIPrimaryScreen().fakeInputBegin(), - event.getTarget(), NULL, + event.getTarget(), nullptr, Event::kDeliverImmediately)); m_events->addEvent(Event(type, event.getTarget(), m_keyInfo, Event::kDeliverImmediately | Event::kDontFreeData)); m_events->addEvent(Event(m_events->forIPrimaryScreen().fakeInputEnd(), - event.getTarget(), NULL, + event.getTarget(), nullptr, Event::kDeliverImmediately)); } @@ -623,7 +624,7 @@ InputFilter::MouseButtonAction::perform(const Event& event) { // send modifiers - IPlatformScreen::KeyInfo* modifierInfo = NULL; + IPlatformScreen::KeyInfo* modifierInfo = nullptr; if (m_buttonInfo->m_mask != 0) { KeyID key = m_press ? kKeySetModifiers : kKeyClearModifiers; modifierInfo = @@ -652,7 +653,7 @@ InputFilter::MouseButtonAction::formatName() const // InputFilter::Rule::Rule() : - m_condition(NULL) + m_condition(nullptr) { // do nothing } @@ -664,7 +665,7 @@ InputFilter::Rule::Rule(Condition* adoptedCondition) : } InputFilter::Rule::Rule(const Rule& rule) : - m_condition(NULL) + m_condition(nullptr) { copy(rule); } @@ -687,16 +688,14 @@ void InputFilter::Rule::clear() { delete m_condition; - for (ActionList::iterator i = m_activateActions.begin(); - i != m_activateActions.end(); ++i) { - delete *i; + for (auto & m_activateAction : m_activateActions) { + delete m_activateAction; } - for (ActionList::iterator i = m_deactivateActions.begin(); - i != m_deactivateActions.end(); ++i) { - delete *i; + for (auto & m_deactivateAction : m_deactivateActions) { + delete m_deactivateAction; } - m_condition = NULL; + m_condition = nullptr; m_activateActions.clear(); m_deactivateActions.clear(); } @@ -705,16 +704,14 @@ void InputFilter::Rule::copy(const Rule& rule) { clear(); - if (rule.m_condition != NULL) { + if (rule.m_condition != nullptr) { m_condition = rule.m_condition->clone(); } - for (ActionList::const_iterator i = rule.m_activateActions.begin(); - i != rule.m_activateActions.end(); ++i) { - m_activateActions.push_back((*i)->clone()); + for (auto m_activateAction : rule.m_activateActions) { + m_activateActions.push_back(m_activateAction->clone()); } - for (ActionList::const_iterator i = rule.m_deactivateActions.begin(); - i != rule.m_deactivateActions.end(); ++i) { - m_deactivateActions.push_back((*i)->clone()); + for (auto m_deactivateAction : rule.m_deactivateActions) { + m_deactivateActions.push_back(m_deactivateAction->clone()); } } @@ -728,7 +725,7 @@ InputFilter::Rule::setCondition(Condition* adopted) void InputFilter::Rule::adoptAction(Action* action, bool onActivation) { - if (action != NULL) { + if (action != nullptr) { if (onActivation) { m_activateActions.push_back(action); } @@ -755,7 +752,7 @@ void InputFilter::Rule::replaceAction(Action* adopted, bool onActivation, UInt32 index) { - if (adopted == NULL) { + if (adopted == nullptr) { removeAction(onActivation, index); } else if (onActivation) { @@ -771,7 +768,7 @@ InputFilter::Rule::replaceAction(Action* adopted, void InputFilter::Rule::enable(PrimaryClient* primaryClient) { - if (m_condition != NULL) { + if (m_condition != nullptr) { m_condition->enablePrimary(primaryClient); } } @@ -779,7 +776,7 @@ InputFilter::Rule::enable(PrimaryClient* primaryClient) void InputFilter::Rule::disable(PrimaryClient* primaryClient) { - if (m_condition != NULL) { + if (m_condition != nullptr) { m_condition->disablePrimary(primaryClient); } } @@ -788,7 +785,7 @@ bool InputFilter::Rule::handleEvent(const Event& event) { // NULL condition never matches - if (m_condition == NULL) { + if (m_condition == nullptr) { return false; } @@ -811,10 +808,9 @@ InputFilter::Rule::handleEvent(const Event& event) } // perform actions - for (ActionList::const_iterator i = actions->begin(); - i != actions->end(); ++i) { - LOG((CLOG_DEBUG1 "hotkey: %s", (*i)->format().c_str())); - (*i)->perform(event); + for (auto action : *actions) { + LOG((CLOG_DEBUG1 "hotkey: %s", action->format().c_str())); + action->perform(event); } return true; @@ -824,13 +820,13 @@ String InputFilter::Rule::format() const { String s; - if (m_condition != NULL) { + if (m_condition != nullptr) { // condition s += m_condition->format(); s += " = "; // activate actions - ActionList::const_iterator i = m_activateActions.begin(); + auto i = m_activateActions.begin(); if (i != m_activateActions.end()) { s += (*i)->format(); while (++i != m_activateActions.end()) { @@ -867,9 +863,9 @@ InputFilter::Rule::getNumActions(bool onActivation) const if (onActivation) { return static_cast(m_activateActions.size()); } - else { + return static_cast(m_deactivateActions.size()); - } + } const InputFilter::Action& @@ -878,9 +874,9 @@ InputFilter::Rule::getAction(bool onActivation, UInt32 index) const if (onActivation) { return *m_activateActions[index]; } - else { + return *m_deactivateActions[index]; - } + } @@ -888,7 +884,7 @@ InputFilter::Rule::getAction(bool onActivation, UInt32 index) const // Input Filter Class // ----------------------------------------------------------------------------- InputFilter::InputFilter(IEventQueue* events) : - m_primaryClient(NULL), + m_primaryClient(nullptr), m_events(events) { // do nothing @@ -896,7 +892,7 @@ InputFilter::InputFilter(IEventQueue* events) : InputFilter::InputFilter(const InputFilter& x) : m_ruleList(x.m_ruleList), - m_primaryClient(NULL), + m_primaryClient(nullptr), m_events(x.m_events) { setPrimaryClient(x.m_primaryClient); @@ -904,7 +900,7 @@ InputFilter::InputFilter(const InputFilter& x) : InputFilter::~InputFilter() { - setPrimaryClient(NULL); + setPrimaryClient(nullptr); } InputFilter& @@ -912,7 +908,7 @@ InputFilter::operator=(const InputFilter& x) { if (&x != this) { PrimaryClient* oldClient = m_primaryClient; - setPrimaryClient(NULL); + setPrimaryClient(nullptr); m_ruleList = x.m_ruleList; @@ -925,7 +921,7 @@ void InputFilter::addFilterRule(const Rule& rule) { m_ruleList.push_back(rule); - if (m_primaryClient != NULL) { + if (m_primaryClient != nullptr) { m_ruleList.back().enable(m_primaryClient); } } @@ -933,7 +929,7 @@ InputFilter::addFilterRule(const Rule& rule) void InputFilter::removeFilterRule(UInt32 index) { - if (m_primaryClient != NULL) { + if (m_primaryClient != nullptr) { m_ruleList[index].disable(m_primaryClient); } m_ruleList.erase(m_ruleList.begin() + index); @@ -952,10 +948,9 @@ InputFilter::setPrimaryClient(PrimaryClient* client) return; } - if (m_primaryClient != NULL) { - for (RuleList::iterator rule = m_ruleList.begin(); - rule != m_ruleList.end(); ++rule) { - rule->disable(m_primaryClient); + if (m_primaryClient != nullptr) { + for (auto & rule : m_ruleList) { + rule.disable(m_primaryClient); } m_events->removeHandler(m_events->forIKeyState().keyDown(), @@ -978,7 +973,7 @@ InputFilter::setPrimaryClient(PrimaryClient* client) m_primaryClient = client; - if (m_primaryClient != NULL) { + if (m_primaryClient != nullptr) { m_events->adoptHandler(m_events->forIKeyState().keyDown(), m_primaryClient->getEventTarget(), new TMethodEventJob(this, @@ -1012,9 +1007,8 @@ InputFilter::setPrimaryClient(PrimaryClient* client) new TMethodEventJob(this, &InputFilter::handleEvent)); - for (RuleList::iterator rule = m_ruleList.begin(); - rule != m_ruleList.end(); ++rule) { - rule->enable(m_primaryClient); + for (auto & rule : m_ruleList) { + rule.enable(m_primaryClient); } } } @@ -1023,10 +1017,9 @@ String InputFilter::format(const String& linePrefix) const { String s; - for (RuleList::const_iterator i = m_ruleList.begin(); - i != m_ruleList.end(); ++i) { + for (const auto & i : m_ruleList) { s += linePrefix; - s += i->format(); + s += i.format(); s += "\n"; } return s; @@ -1049,13 +1042,11 @@ InputFilter::operator==(const InputFilter& x) const // compare rule lists. the easiest way to do that is to format each // rule into a string, sort the strings, then compare the results. std::vector aList, bList; - for (RuleList::const_iterator i = m_ruleList.begin(); - i != m_ruleList.end(); ++i) { - aList.push_back(i->format()); + for (const auto & i : m_ruleList) { + aList.push_back(i.format()); } - for (RuleList::const_iterator i = x.m_ruleList.begin(); - i != x.m_ruleList.end(); ++i) { - bList.push_back(i->format()); + for (const auto & i : x.m_ruleList) { + bList.push_back(i.format()); } std::partial_sort(aList.begin(), aList.end(), aList.end()); std::partial_sort(bList.begin(), bList.end(), bList.end()); @@ -1069,7 +1060,7 @@ InputFilter::operator!=(const InputFilter& x) const } void -InputFilter::handleEvent(const Event& event, void*) +InputFilter::handleEvent(const Event& event, void* /*unused*/) { // copy event and adjust target Event myEvent(event.getType(), this, event.getData(), @@ -1077,9 +1068,8 @@ InputFilter::handleEvent(const Event& event, void*) Event::kDeliverImmediately); // let each rule try to match the event until one does - for (RuleList::iterator rule = m_ruleList.begin(); - rule != m_ruleList.end(); ++rule) { - if (rule->handleEvent(myEvent)) { + for (auto & rule : m_ruleList) { + if (rule.handleEvent(myEvent)) { // handled return; } diff --git a/src/lib/server/InputFilter.h b/src/lib/server/InputFilter.h index 601ced42..a2d5a4de 100644 --- a/src/lib/server/InputFilter.h +++ b/src/lib/server/InputFilter.h @@ -103,7 +103,7 @@ public: // ScreenConnectedCondition class ScreenConnectedCondition : public Condition { public: - ScreenConnectedCondition(IEventQueue* events, const String& screen); + ScreenConnectedCondition(IEventQueue* events, String screen); virtual ~ScreenConnectedCondition(); // Condition overrides @@ -153,7 +153,7 @@ public: // SwitchToScreenAction class SwitchToScreenAction : public Action { public: - SwitchToScreenAction(IEventQueue* events, const String& screen); + SwitchToScreenAction(IEventQueue* events, String screen); String getScreen() const; @@ -209,7 +209,7 @@ public: // KeystrokeAction class KeystrokeAction : public Action { public: - KeystrokeAction(IEventQueue* events, IPlatformScreen::KeyInfo* adoptedInfo, bool press); + KeystrokeAction(IEventQueue* events, IPlatformScreen::KeyInfo* info, bool press); ~KeystrokeAction(); void adoptInfo(IPlatformScreen::KeyInfo*); @@ -235,7 +235,7 @@ public: class MouseButtonAction : public Action { public: MouseButtonAction(IEventQueue* events, - IPlatformScreen::ButtonInfo* adoptedInfo, + IPlatformScreen::ButtonInfo* info, bool press); ~MouseButtonAction(); @@ -260,7 +260,7 @@ public: class Rule { public: Rule(); - Rule(Condition* adopted); + Rule(Condition* adoptedCondition); Rule(const Rule&); ~Rule(); diff --git a/src/lib/server/PrimaryClient.cpp b/src/lib/server/PrimaryClient.cpp index 63122f54..806821a3 100644 --- a/src/lib/server/PrimaryClient.cpp +++ b/src/lib/server/PrimaryClient.cpp @@ -18,9 +18,9 @@ #include "server/PrimaryClient.h" -#include "core/Screen.h" -#include "core/Clipboard.h" #include "base/Log.h" +#include "core/Clipboard.h" +#include "core/Screen.h" // // PrimaryClient @@ -32,8 +32,8 @@ PrimaryClient::PrimaryClient(const String& name, synergy::Screen* screen) : m_fakeInputCount(0) { // all clipboards are clean - for (UInt32 i = 0; i < kClipboardEnd; ++i) { - m_clipboardDirty[i] = false; + for (bool & i : m_clipboardDirty) { + i = false; } } @@ -196,7 +196,7 @@ PrimaryClient::keyDown(KeyID key, KeyModifierMask mask, KeyButton button) } void -PrimaryClient::keyRepeat(KeyID, KeyModifierMask, SInt32, KeyButton) +PrimaryClient::keyRepeat(KeyID /*unused*/, KeyModifierMask /*unused*/, SInt32 /*count*/, KeyButton /*unused*/) { // ignore } @@ -214,13 +214,13 @@ PrimaryClient::keyUp(KeyID key, KeyModifierMask mask, KeyButton button) } void -PrimaryClient::mouseDown(ButtonID) +PrimaryClient::mouseDown(ButtonID /*unused*/) { // ignore } void -PrimaryClient::mouseUp(ButtonID) +PrimaryClient::mouseUp(ButtonID /*unused*/) { // ignore } @@ -232,31 +232,31 @@ PrimaryClient::mouseMove(SInt32 x, SInt32 y) } void -PrimaryClient::mouseRelativeMove(SInt32, SInt32) +PrimaryClient::mouseRelativeMove(SInt32 /*xRel*/, SInt32 /*yRel*/) { // ignore } void -PrimaryClient::mouseWheel(SInt32, SInt32) +PrimaryClient::mouseWheel(SInt32 /*xDelta*/, SInt32 /*yDelta*/) { // ignore } void -PrimaryClient::screensaver(bool) +PrimaryClient::screensaver(bool /*activate*/) { // ignore } void -PrimaryClient::sendDragInfo(UInt32 fileCount, const char* info, size_t size) +PrimaryClient::sendDragInfo(UInt32 /*fileCount*/, const char* /*info*/, size_t /*size*/) { // ignore } void -PrimaryClient::fileChunkSending(UInt8 mark, char* data, size_t dataSize) +PrimaryClient::fileChunkSending(UInt8 /*mark*/, char* /*data*/, size_t /*dataSize*/) { // ignore } diff --git a/src/lib/server/PrimaryClient.h b/src/lib/server/PrimaryClient.h index 112bc01b..7ddc60ce 100644 --- a/src/lib/server/PrimaryClient.h +++ b/src/lib/server/PrimaryClient.h @@ -126,7 +126,7 @@ public: // IClient overrides virtual void enter(SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, - bool forScreensaver); + bool screensaver); virtual bool leave(); virtual void setClipboard(ClipboardID, const IClipboard*); virtual void grabClipboard(ClipboardID); @@ -137,7 +137,7 @@ public: virtual void keyUp(KeyID, KeyModifierMask, KeyButton); virtual void mouseDown(ButtonID); virtual void mouseUp(ButtonID); - virtual void mouseMove(SInt32 xAbs, SInt32 yAbs); + virtual void mouseMove(SInt32 x, SInt32 y); virtual void mouseRelativeMove(SInt32 xRel, SInt32 yRel); virtual void mouseWheel(SInt32 xDelta, SInt32 yDelta); virtual void screensaver(bool activate); @@ -151,6 +151,6 @@ public: bool isPrimary() const { return true; } private: synergy::Screen* m_screen; - bool m_clipboardDirty[kClipboardEnd]; + bool m_clipboardDirty[kClipboardEnd]{}; SInt32 m_fakeInputCount; }; diff --git a/src/lib/server/Server.cpp b/src/lib/server/Server.cpp index 2d071755..b6a440ec 100644 --- a/src/lib/server/Server.cpp +++ b/src/lib/server/Server.cpp @@ -18,39 +18,40 @@ #include "server/Server.h" -#include "server/ClientProxy.h" -#include "server/ClientProxyUnknown.h" -#include "server/PrimaryClient.h" -#include "server/ClientListener.h" -#include "core/FileChunk.h" -#include "core/IPlatformScreen.h" -#include "core/DropHelper.h" -#include "core/option_types.h" -#include "core/protocol_types.h" -#include "core/XScreen.h" -#include "core/XSynergy.h" -#include "core/StreamChunker.h" -#include "core/KeyState.h" -#include "core/Screen.h" -#include "core/PacketStreamFilter.h" -#include "net/TCPSocket.h" -#include "net/IDataSocket.h" -#include "net/IListenSocket.h" -#include "net/XSocket.h" -#include "mt/Thread.h" #include "arch/Arch.h" -#include "base/TMethodJob.h" #include "base/IEventQueue.h" #include "base/Log.h" #include "base/TMethodEventJob.h" +#include "base/TMethodJob.h" #include "common/stdexcept.h" +#include "core/DropHelper.h" +#include "core/FileChunk.h" +#include "core/IPlatformScreen.h" +#include "core/KeyState.h" +#include "core/PacketStreamFilter.h" +#include "core/Screen.h" +#include "core/StreamChunker.h" +#include "core/XScreen.h" +#include "core/XSynergy.h" +#include "core/option_types.h" +#include "core/protocol_types.h" +#include "mt/Thread.h" +#include "net/IDataSocket.h" +#include "net/IListenSocket.h" +#include "net/TCPSocket.h" +#include "net/XSocket.h" +#include "server/ClientListener.h" +#include "server/ClientProxy.h" +#include "server/ClientProxyUnknown.h" +#include "server/PrimaryClient.h" #include "shared/SerialKey.h" -#include #include -#include -#include +#include #include +#include +#include +#include // // Server @@ -61,7 +62,7 @@ Server::Server( PrimaryClient* primaryClient, synergy::Screen* screen, IEventQueue* events, - ServerArgs const& args) : + ServerArgs args) : m_mock(false), m_primaryClient(primaryClient), m_active(primaryClient), @@ -72,11 +73,11 @@ Server::Server( m_yDelta2(0), m_config(&config), m_inputFilter(config.getInputFilter()), - m_activeSaver(NULL), + m_activeSaver(nullptr), m_switchDir(kNoDirection), - m_switchScreen(NULL), + m_switchScreen(nullptr), m_switchWaitDelay(0.0), - m_switchWaitTimer(NULL), + m_switchWaitTimer(nullptr), m_switchTwoTapDelay(0.0), m_switchTwoTapEngaged(false), m_switchTwoTapArmed(false), @@ -89,13 +90,13 @@ Server::Server( m_lockedToScreen(false), m_screen(screen), m_events(events), - m_sendFileThread(NULL), - m_writeToDropDirThread(NULL), + m_sendFileThread(nullptr), + m_writeToDropDirThread(nullptr), m_ignoreFileTransfer(false), m_enableClipboard(true), - m_sendDragInfoThread(NULL), + m_sendDragInfoThread(nullptr), m_waitDragInfoThread(true), - m_args(args) + m_args(std::move(args)) { // must have a primary client and it must have a canonical name assert(m_primaryClient != NULL); @@ -105,9 +106,8 @@ Server::Server( String primaryName = getName(primaryClient); // clear clipboards - for (ClipboardID id = 0; id < kClipboardEnd; ++id) { - ClipboardInfo& clipboard = m_clipboards[id]; - clipboard.m_clipboardOwner = primaryName; + for (auto & clipboard : m_clipboards) { + clipboard.m_clipboardOwner = primaryName; clipboard.m_clipboardSeqNum = m_seqNum; if (clipboard.m_clipboard.open(0)) { clipboard.m_clipboard.empty(); @@ -207,7 +207,7 @@ Server::Server( m_inputFilter->setPrimaryClient(m_primaryClient); // Determine if scroll lock is already set. If so, lock the cursor to the primary screen - if (m_primaryClient->getToggleMask() & KeyModifierScrollLock) { + if ((m_primaryClient->getToggleMask() & KeyModifierScrollLock) != 0u) { LOG((CLOG_NOTE "Scroll Lock is on, locking cursor to screen")); m_lockedToScreen = true; } @@ -250,17 +250,16 @@ Server::~Server() // force immediate disconnection of secondary clients disconnect(); - for (OldClients::iterator index = m_oldClients.begin(); - index != m_oldClients.end(); ++index) { - BaseClientProxy* client = index->first; - m_events->deleteTimer(index->second); + for (auto & m_oldClient : m_oldClients) { + BaseClientProxy* client = m_oldClient.first; + m_events->deleteTimer(m_oldClient.second); m_events->removeHandler(Event::kTimer, client); m_events->removeHandler(m_events->forClientProxy().disconnected(), client); delete client; } // remove input filter - m_inputFilter->setPrimaryClient(NULL); + m_inputFilter->setPrimaryClient(nullptr); // disable and disconnect primary client m_primaryClient->disable(); @@ -340,7 +339,7 @@ Server::adoptClient(BaseClientProxy* client) sendOptions(client); // activate screen saver on new client if active on the primary screen - if (m_activeSaver != NULL) { + if (m_activeSaver != nullptr) { client->screensaver(true); } @@ -367,16 +366,15 @@ Server::disconnect() UInt32 Server::getNumClients() const { - return (SInt32)m_clients.size(); + return static_cast(m_clients.size()); } void Server::getClients(std::vector& list) const { list.clear(); - for (ClientList::const_iterator index = m_clients.begin(); - index != m_clients.end(); ++index) { - list.push_back(index->first); + for (const auto & m_client : m_clients) { + list.push_back(m_client.first); } } @@ -442,9 +440,9 @@ Server::getJumpZoneSize(BaseClientProxy* client) const if (client == m_primaryClient) { return m_primaryClient->getJumpZoneSize(); } - else { + return 0; - } + } void @@ -454,7 +452,7 @@ Server::switchScreen(BaseClientProxy* dst, assert(dst != NULL); // if trial is expired, exit the process - if (m_args.m_serial.isExpired(std::time(0))) { + if (m_args.m_serial.isExpired(std::time(nullptr))) { LOG((CLOG_ERR "trial has expired, aborting server")); exit(kExitSuccess); } @@ -626,12 +624,12 @@ Server::getNeighbor(BaseClientProxy* src, // connected neighbor we return NULL. if (dstName.empty()) { LOG((CLOG_DEBUG2 "no neighbor on %s of \"%s\"", Config::dirName(dir), srcName.c_str())); - return NULL; + return nullptr; } // look up neighbor cell. if the screen is connected and // ready then we can stop. - ClientList::const_iterator index = m_clients.find(dstName); + auto index = m_clients.find(dstName); if (index != m_clients.end()) { LOG((CLOG_DEBUG2 "\"%s\" is on %s of \"%s\" at %f", dstName.c_str(), Config::dirName(dir), srcName.c_str(), t)); mapToPixel(index->second, dir, tTmp, x, y); @@ -657,8 +655,8 @@ Server::mapToNeighbor(BaseClientProxy* src, // get the first neighbor BaseClientProxy* dst = getNeighbor(src, srcSide, x, y); - if (dst == NULL) { - return NULL; + if (dst == nullptr) { + return nullptr; } // get the source screen's size @@ -674,7 +672,7 @@ Server::mapToNeighbor(BaseClientProxy* src, switch (srcSide) { case kLeft: x -= dx; - while (dst != NULL) { + while (dst != nullptr) { lastGoodScreen = dst; lastGoodScreen->getShape(dx, dy, dw, dh); x += dw; @@ -690,7 +688,7 @@ Server::mapToNeighbor(BaseClientProxy* src, case kRight: x -= dx; - while (dst != NULL) { + while (dst != nullptr) { x -= dw; lastGoodScreen = dst; lastGoodScreen->getShape(dx, dy, dw, dh); @@ -706,7 +704,7 @@ Server::mapToNeighbor(BaseClientProxy* src, case kTop: y -= dy; - while (dst != NULL) { + while (dst != nullptr) { lastGoodScreen = dst; lastGoodScreen->getShape(dx, dy, dw, dh); y += dh; @@ -722,7 +720,7 @@ Server::mapToNeighbor(BaseClientProxy* src, case kBottom: y -= dy; - while (dst != NULL) { + while (dst != nullptr) { y -= dh; lastGoodScreen = dst; lastGoodScreen->getShape(dx, dy, dw, dh); @@ -738,7 +736,7 @@ Server::mapToNeighbor(BaseClientProxy* src, case kNoDirection: assert(0 && "bad direction"); - return NULL; + return nullptr; } // save destination screen @@ -774,27 +772,31 @@ Server::avoidJumpZone(BaseClientProxy* dst, // don't need to move inwards because that side can't provoke a jump. switch (dir) { case kLeft: - if (!m_config->getNeighbor(dstName, kRight, t, NULL).empty() && - x > dx + dw - 1 - z) + if (!m_config->getNeighbor(dstName, kRight, t, nullptr).empty() && + x > dx + dw - 1 - z) { x = dx + dw - 1 - z; +} break; case kRight: - if (!m_config->getNeighbor(dstName, kLeft, t, NULL).empty() && - x < dx + z) + if (!m_config->getNeighbor(dstName, kLeft, t, nullptr).empty() && + x < dx + z) { x = dx + z; +} break; case kTop: - if (!m_config->getNeighbor(dstName, kBottom, t, NULL).empty() && - y > dy + dh - 1 - z) + if (!m_config->getNeighbor(dstName, kBottom, t, nullptr).empty() && + y > dy + dh - 1 - z) { y = dy + dh - 1 - z; +} break; case kBottom: - if (!m_config->getNeighbor(dstName, kTop, t, NULL).empty() && - y < dy + z) + if (!m_config->getNeighbor(dstName, kTop, t, nullptr).empty() && + y < dy + z) { y = dy + z; +} break; case kNoDirection: @@ -810,7 +812,7 @@ Server::isSwitchOkay(BaseClientProxy* newScreen, LOG((CLOG_DEBUG1 "try to leave \"%s\" on %s", getName(m_active).c_str(), Config::dirName(dir))); // is there a neighbor? - if (newScreen == NULL) { + if (newScreen == nullptr) { // there's no neighbor. we don't want to switch and we don't // want to try to switch later. LOG((CLOG_DEBUG1 "no neighbor %s", Config::dirName(dir))); @@ -825,7 +827,7 @@ Server::isSwitchOkay(BaseClientProxy* newScreen, // note if the switch direction has changed. save the new // direction and screen if so. bool isNewDirection = (dir != m_switchDir); - if (isNewDirection || m_switchScreen == NULL) { + if (isNewDirection || m_switchScreen == nullptr) { m_switchDir = dir; m_switchScreen = newScreen; } @@ -857,14 +859,14 @@ Server::isSwitchOkay(BaseClientProxy* newScreen, // and, if not, check the global options. const Config::ScreenOptions* options = m_config->getOptions(getName(m_active)); - if (options == NULL || options->count(kOptionScreenSwitchCorners) == 0) { + if (options == nullptr || options->count(kOptionScreenSwitchCorners) == 0) { options = m_config->getOptions(""); } - if (options != NULL && options->count(kOptionScreenSwitchCorners) > 0) { + if (options != nullptr && options->count(kOptionScreenSwitchCorners) > 0) { // get corner mask and size - Config::ScreenOptions::const_iterator i = + auto i = options->find(kOptionScreenSwitchCorners); - UInt32 corners = static_cast(i->second); + auto corners = static_cast(i->second); i = options->find(kOptionScreenSwitchCornerSize); SInt32 size = 0; if (i != options->end()) { @@ -913,8 +915,8 @@ Server::noSwitch(SInt32 x, SInt32 y) void Server::stopSwitch() { - if (m_switchScreen != NULL) { - m_switchScreen = NULL; + if (m_switchScreen != nullptr) { + m_switchScreen = nullptr; m_switchDir = kNoDirection; stopSwitchTwoTap(); stopSwitchWait(); @@ -1012,16 +1014,16 @@ Server::startSwitchWait(SInt32 x, SInt32 y) void Server::stopSwitchWait() { - if (m_switchWaitTimer != NULL) { + if (m_switchWaitTimer != nullptr) { m_events->deleteTimer(m_switchWaitTimer); - m_switchWaitTimer = NULL; + m_switchWaitTimer = nullptr; } } bool Server::isSwitchWaitStarted() const { - return (m_switchWaitTimer != NULL); + return (m_switchWaitTimer != nullptr); } UInt32 @@ -1063,7 +1065,7 @@ Server::getCorner(BaseClientProxy* client, if (y < ay + size) { return (xSide < 0) ? kTopLeftMask : kTopRightMask; } - else if (y >= ay + ah - size) { + if (y >= ay + ah - size) { return (xSide < 0) ? kBottomLeftMask : kBottomRightMask; } } @@ -1073,7 +1075,7 @@ Server::getCorner(BaseClientProxy* client, if (x < ax + size) { return (ySide < 0) ? kTopLeftMask : kBottomLeftMask; } - else if (x >= ax + aw - size) { + if (x >= ax + aw - size) { return (ySide < 0) ? kTopRightMask : kBottomRightMask; } } @@ -1107,25 +1109,23 @@ Server::sendOptions(BaseClientProxy* client) const // look up options for client const Config::ScreenOptions* options = m_config->getOptions(getName(client)); - if (options != NULL) { + if (options != nullptr) { // convert options to a more convenient form for sending optionsList.reserve(2 * options->size()); - for (Config::ScreenOptions::const_iterator index = options->begin(); - index != options->end(); ++index) { - optionsList.push_back(index->first); - optionsList.push_back(static_cast(index->second)); + for (auto option : *options) { + optionsList.push_back(option.first); + optionsList.push_back(static_cast(option.second)); } } // look up global options options = m_config->getOptions(""); - if (options != NULL) { + if (options != nullptr) { // convert options to a more convenient form for sending optionsList.reserve(optionsList.size() + 2 * options->size()); - for (Config::ScreenOptions::const_iterator index = options->begin(); - index != options->end(); ++index) { - optionsList.push_back(index->first); - optionsList.push_back(static_cast(index->second)); + for (auto option : *options) { + optionsList.push_back(option.first); + optionsList.push_back(static_cast(option.second)); } } @@ -1138,7 +1138,7 @@ void Server::processOptions() { const Config::ScreenOptions* options = m_config->getOptions(""); - if (options == NULL) { + if (options == nullptr) { return; } @@ -1147,10 +1147,9 @@ Server::processOptions() m_switchNeedsAlt = false; // doesnt' work correct. bool newRelativeMoves = m_relativeMoves; - for (Config::ScreenOptions::const_iterator index = options->begin(); - index != options->end(); ++index) { - const OptionID id = index->first; - const OptionValue value = index->second; + for (auto option : *options) { + const OptionID id = option.first; + const OptionValue value = option.second; if (id == kOptionScreenSwitchDelay) { m_switchWaitDelay = 1.0e-3 * static_cast(value); if (m_switchWaitDelay < 0.0) { @@ -1180,7 +1179,7 @@ Server::processOptions() else if (id == kOptionClipboardSharing) { m_enableClipboard = (value != 0); - if (m_enableClipboard == false) { + if (!m_enableClipboard) { LOG((CLOG_NOTE "clipboard sharing is disabled")); } } @@ -1192,10 +1191,10 @@ Server::processOptions() } void -Server::handleShapeChanged(const Event&, void* vclient) +Server::handleShapeChanged(const Event& /*unused*/, void* vclient) { // ignore events from unknown clients - BaseClientProxy* client = static_cast(vclient); + auto* client = static_cast(vclient); if (m_clientSet.count(client) == 0) { return; } @@ -1232,11 +1231,11 @@ Server::handleClipboardGrabbed(const Event& event, void* vclient) } // ignore events from unknown clients - BaseClientProxy* grabber = static_cast(vclient); + auto* grabber = static_cast(vclient); if (m_clientSet.count(grabber) == 0) { return; } - const IScreen::ClipboardInfo* info = + const auto* info = static_cast(event.getData()); // ignore grab if sequence number is old. always allow primary @@ -1262,9 +1261,8 @@ Server::handleClipboardGrabbed(const Event& event, void* vclient) // tell all other screens to take ownership of clipboard. tell the // grabber that it's clipboard isn't dirty. - for (ClientList::iterator index = m_clients.begin(); - index != m_clients.end(); ++index) { - BaseClientProxy* client = index->second; + for (auto & m_client : m_clients) { + BaseClientProxy* client = m_client.second; if (client == grabber) { client->setClipboardDirty(info->m_id, false); } @@ -1278,93 +1276,93 @@ void Server::handleClipboardChanged(const Event& event, void* vclient) { // ignore events from unknown clients - BaseClientProxy* sender = static_cast(vclient); + auto* sender = static_cast(vclient); if (m_clientSet.count(sender) == 0) { return; } - const IScreen::ClipboardInfo* info = + const auto* info = static_cast(event.getData()); onClipboardChanged(sender, info->m_id, info->m_sequenceNumber); } void -Server::handleKeyDownEvent(const Event& event, void*) +Server::handleKeyDownEvent(const Event& event, void* /*unused*/) { - IPlatformScreen::KeyInfo* info = + auto* info = static_cast(event.getData()); onKeyDown(info->m_key, info->m_mask, info->m_button, info->m_screens); } void -Server::handleKeyUpEvent(const Event& event, void*) +Server::handleKeyUpEvent(const Event& event, void* /*unused*/) { - IPlatformScreen::KeyInfo* info = + auto* info = static_cast(event.getData()); onKeyUp(info->m_key, info->m_mask, info->m_button, info->m_screens); } void -Server::handleKeyRepeatEvent(const Event& event, void*) +Server::handleKeyRepeatEvent(const Event& event, void* /*unused*/) { - IPlatformScreen::KeyInfo* info = + auto* info = static_cast(event.getData()); onKeyRepeat(info->m_key, info->m_mask, info->m_count, info->m_button); } void -Server::handleButtonDownEvent(const Event& event, void*) +Server::handleButtonDownEvent(const Event& event, void* /*unused*/) { - IPlatformScreen::ButtonInfo* info = + auto* info = static_cast(event.getData()); onMouseDown(info->m_button); } void -Server::handleButtonUpEvent(const Event& event, void*) +Server::handleButtonUpEvent(const Event& event, void* /*unused*/) { - IPlatformScreen::ButtonInfo* info = + auto* info = static_cast(event.getData()); onMouseUp(info->m_button); } void -Server::handleMotionPrimaryEvent(const Event& event, void*) +Server::handleMotionPrimaryEvent(const Event& event, void* /*unused*/) { - IPlatformScreen::MotionInfo* info = + auto* info = static_cast(event.getData()); onMouseMovePrimary(info->m_x, info->m_y); } void -Server::handleMotionSecondaryEvent(const Event& event, void*) +Server::handleMotionSecondaryEvent(const Event& event, void* /*unused*/) { - IPlatformScreen::MotionInfo* info = + auto* info = static_cast(event.getData()); onMouseMoveSecondary(info->m_x, info->m_y); } void -Server::handleWheelEvent(const Event& event, void*) +Server::handleWheelEvent(const Event& event, void* /*unused*/) { - IPlatformScreen::WheelInfo* info = + auto* info = static_cast(event.getData()); onMouseWheel(info->m_xDelta, info->m_yDelta); } void -Server::handleScreensaverActivatedEvent(const Event&, void*) +Server::handleScreensaverActivatedEvent(const Event& /*unused*/, void* /*unused*/) { onScreensaver(true); } void -Server::handleScreensaverDeactivatedEvent(const Event&, void*) +Server::handleScreensaverDeactivatedEvent(const Event& /*unused*/, void* /*unused*/) { onScreensaver(false); } void -Server::handleSwitchWaitTimeout(const Event&, void*) +Server::handleSwitchWaitTimeout(const Event& /*unused*/, void* /*unused*/) { // ignore if mouse is locked to screen if (isLockedToScreen()) { @@ -1378,11 +1376,11 @@ Server::handleSwitchWaitTimeout(const Event&, void*) } void -Server::handleClientDisconnected(const Event&, void* vclient) +Server::handleClientDisconnected(const Event& /*unused*/, void* vclient) { // client has disconnected. it might be an old client or an // active client. we don't care so just handle it both ways. - BaseClientProxy* client = static_cast(vclient); + auto* client = static_cast(vclient); removeActiveClient(client); removeOldClient(client); @@ -1390,10 +1388,10 @@ Server::handleClientDisconnected(const Event&, void* vclient) } void -Server::handleClientCloseTimeout(const Event&, void* vclient) +Server::handleClientCloseTimeout(const Event& /*unused*/, void* vclient) { // client took too long to disconnect. just dump it. - BaseClientProxy* client = static_cast(vclient); + auto* client = static_cast(vclient); LOG((CLOG_NOTE "forced disconnection of client \"%s\"", getName(client).c_str())); removeOldClient(client); @@ -1401,9 +1399,9 @@ Server::handleClientCloseTimeout(const Event&, void* vclient) } void -Server::handleSwitchToScreenEvent(const Event& event, void*) +Server::handleSwitchToScreenEvent(const Event& event, void* /*unused*/) { - SwitchToScreenInfo* info = + auto* info = static_cast(event.getData()); ClientList::const_iterator index = m_clients.find(info->m_screen); @@ -1416,16 +1414,16 @@ Server::handleSwitchToScreenEvent(const Event& event, void*) } void -Server::handleSwitchInDirectionEvent(const Event& event, void*) +Server::handleSwitchInDirectionEvent(const Event& event, void* /*unused*/) { - SwitchInDirectionInfo* info = + auto* info = static_cast(event.getData()); // jump to screen in chosen direction from center of this screen SInt32 x = m_x, y = m_y; BaseClientProxy* newScreen = getNeighbor(m_active, info->m_direction, x, y); - if (newScreen == NULL) { + if (newScreen == nullptr) { LOG((CLOG_DEBUG1 "no neighbor %s", Config::dirName(info->m_direction))); } else { @@ -1434,9 +1432,9 @@ Server::handleSwitchInDirectionEvent(const Event& event, void*) } void -Server::handleKeyboardBroadcastEvent(const Event& event, void*) +Server::handleKeyboardBroadcastEvent(const Event& event, void* /*unused*/) { - KeyboardBroadcastInfo* info = (KeyboardBroadcastInfo*)event.getData(); + auto* info = static_cast(event.getData()); // choose new state bool newState; @@ -1465,9 +1463,9 @@ Server::handleKeyboardBroadcastEvent(const Event& event, void*) } void -Server::handleLockCursorToScreenEvent(const Event& event, void*) +Server::handleLockCursorToScreenEvent(const Event& event, void* /*unused*/) { - LockCursorToScreenInfo* info = (LockCursorToScreenInfo*)event.getData(); + auto* info = static_cast(event.getData()); // choose new state bool newState; @@ -1499,25 +1497,25 @@ Server::handleLockCursorToScreenEvent(const Event& event, void*) } void -Server::handleFakeInputBeginEvent(const Event&, void*) +Server::handleFakeInputBeginEvent(const Event& /*unused*/, void* /*unused*/) { m_primaryClient->fakeInputBegin(); } void -Server::handleFakeInputEndEvent(const Event&, void*) +Server::handleFakeInputEndEvent(const Event& /*unused*/, void* /*unused*/) { m_primaryClient->fakeInputEnd(); } void -Server::handleFileChunkSendingEvent(const Event& event, void*) +Server::handleFileChunkSendingEvent(const Event& event, void* /*unused*/) { onFileChunkSending(event.getData()); } void -Server::handleFileRecieveCompletedEvent(const Event& event, void*) +Server::handleFileRecieveCompletedEvent(const Event& /*event*/, void* /*unused*/) { onFileRecieveCompleted(); } @@ -1582,7 +1580,7 @@ Server::onScreensaver(bool activated) // jump back to previous screen and position. we must check // that the position is still valid since the screen may have // changed resolutions while the screen saver was running. - if (m_activeSaver != NULL && m_activeSaver != m_primaryClient) { + if (m_activeSaver != nullptr && m_activeSaver != m_primaryClient) { // check position BaseClientProxy* screen = m_activeSaver; SInt32 x, y, w, h; @@ -1606,7 +1604,7 @@ Server::onScreensaver(bool activated) } // reset state - m_activeSaver = NULL; + m_activeSaver = nullptr; } // send message to all clients @@ -1629,7 +1627,7 @@ Server::onKeyDown(KeyID id, KeyModifierMask mask, KeyButton button, m_active->keyDown(id, mask, button); } else { - if (!screens && m_keyboardBroadcasting) { + if ((screens == nullptr) && m_keyboardBroadcasting) { screens = m_keyboardBroadcastingScreens.c_str(); if (IKeyState::KeyInfo::isDefault(screens)) { screens = "*"; @@ -1656,7 +1654,7 @@ Server::onKeyUp(KeyID id, KeyModifierMask mask, KeyButton button, m_active->keyUp(id, mask, button); } else { - if (!screens && m_keyboardBroadcasting) { + if ((screens == nullptr) && m_keyboardBroadcasting) { screens = m_keyboardBroadcastingScreens.c_str(); if (IKeyState::KeyInfo::isDefault(screens)) { screens = "*"; @@ -1811,7 +1809,7 @@ Server::onMouseMovePrimary(SInt32 x, SInt32 y) && m_screen->isDraggingStarted() && m_active != newScreen && m_waitDragInfoThread) { - if (m_sendDragInfoThread == NULL) { + if (m_sendDragInfoThread == nullptr) { m_sendDragInfoThread = new Thread( new TMethodJob( this, @@ -1834,7 +1832,7 @@ Server::onMouseMovePrimary(SInt32 x, SInt32 y) void Server::sendDragInfoThread(void* arg) { - BaseClientProxy* newScreen = static_cast(arg); + auto* newScreen = static_cast(arg); m_dragFileList.clear(); String& dragFileList = m_screen->getDraggingFilename(); @@ -1853,12 +1851,12 @@ Server::sendDragInfoThread(void* arg) #endif // send drag file info to client if there is any - if (m_dragFileList.size() > 0) { + if (!m_dragFileList.empty()) { sendDragInfo(newScreen); m_dragFileList.clear(); } m_waitDragInfoThread = false; - m_sendDragInfoThread = NULL; + m_sendDragInfoThread = nullptr; } void @@ -1868,7 +1866,7 @@ Server::sendDragInfo(BaseClientProxy* newScreen) UInt32 fileCount = DragInformation::setupDragInfo(m_dragFileList, infoString); if (fileCount > 0) { - char* info = NULL; + char* info = nullptr; size_t size = infoString.size(); info = new char[size]; memcpy(info, infoString.c_str(), size); @@ -1964,7 +1962,7 @@ Server::onMouseMoveSecondary(SInt32 dx, SInt32 dy) // if waiting and mouse is not on the border we're waiting // on then stop waiting. also if it's not on the border // then arm the double tap. - if (m_switchScreen != NULL) { + if (m_switchScreen != nullptr) { bool clearWait; SInt32 zoneSize = m_primaryClient->getJumpZoneSize(); switch (m_switchDir) { @@ -2009,9 +2007,9 @@ Server::onMouseMoveSecondary(SInt32 dx, SInt32 dy) } while (false); if (jump) { - if (m_sendFileThread != NULL) { + if (m_sendFileThread != nullptr) { StreamChunker::interruptFile(); - m_sendFileThread = NULL; + m_sendFileThread = nullptr; } SInt32 newX = m_x; @@ -2062,7 +2060,7 @@ Server::onMouseWheel(SInt32 xDelta, SInt32 yDelta) void Server::onFileChunkSending(const void* data) { - FileChunk* chunk = static_cast(const_cast(data)); + auto* chunk = static_cast(const_cast(data)); LOG((CLOG_DEBUG1 "sending file chunk")); assert(m_active != NULL); @@ -2082,7 +2080,7 @@ Server::onFileRecieveCompleted() } void -Server::writeToDropDirThread(void*) +Server::writeToDropDirThread(void* /*unused*/) { LOG((CLOG_DEBUG "starting write to drop dir thread")); @@ -2135,7 +2133,7 @@ bool Server::removeClient(BaseClientProxy* client) { // return false if not in list - ClientSet::iterator i = m_clientSet.find(client); + auto i = m_clientSet.find(client); if (i == m_clientSet.end()) { return false; } @@ -2173,11 +2171,11 @@ Server::closeClient(BaseClientProxy* client, const char* msg) // send message // FIXME -- avoid type cast (kinda hard, though) - ((ClientProxy*)client)->close(msg); + (dynamic_cast(client))->close(msg); // install timer. wait timeout seconds for client to close. double timeout = 5.0; - EventQueueTimer* timer = m_events->newOneShotTimer(timeout, NULL); + EventQueueTimer* timer = m_events->newOneShotTimer(timeout, nullptr); m_events->adoptHandler(Event::kTimer, timer, new TMethodEventJob(this, &Server::handleClientCloseTimeout, client)); @@ -2196,12 +2194,11 @@ Server::closeClients(const Config& config) { // collect the clients that are connected but are being dropped // from the configuration (or who's canonical name is changing). - typedef std::set RemovedClients; + using RemovedClients = std::set; RemovedClients removed; - for (ClientList::iterator index = m_clients.begin(); - index != m_clients.end(); ++index) { - if (!config.isCanonicalName(index->first)) { - removed.insert(index->second); + for (auto & m_client : m_clients) { + if (!config.isCanonicalName(m_client.first)) { + removed.insert(m_client.second); } } @@ -2210,9 +2207,8 @@ Server::closeClients(const Config& config) // now close them. we collect the list then close in two steps // because closeClient() modifies the collection we iterate over. - for (RemovedClients::iterator index = removed.begin(); - index != removed.end(); ++index) { - closeClient(*index, kMsgCClose); + for (auto index : removed) { + closeClient(index, kMsgCClose); } } @@ -2231,7 +2227,7 @@ Server::removeActiveClient(BaseClientProxy* client) void Server::removeOldClient(BaseClientProxy* client) { - OldClients::iterator i = m_oldClients.find(client); + auto i = m_oldClients.find(client); if (i != m_oldClients.end()) { m_events->removeHandler(m_events->forClientProxy().disconnected(), client); m_events->removeHandler(Event::kTimer, i->second); @@ -2247,7 +2243,7 @@ void Server::forceLeaveClient(BaseClientProxy* client) { BaseClientProxy* active = - (m_activeSaver != NULL) ? m_activeSaver : m_active; + (m_activeSaver != nullptr) ? m_activeSaver : m_active; if (active == client) { // record new position (center of primary screen) m_primaryClient->getCursorCenter(m_x, m_y); @@ -2266,7 +2262,7 @@ Server::forceLeaveClient(BaseClientProxy* client) // enter new screen (unless we already have because of the // screen saver) - if (m_activeSaver == NULL) { + if (m_activeSaver == nullptr) { m_primaryClient->enter(m_x, m_y, m_seqNum, m_primaryClient->getToggleMask(), false); } @@ -2276,7 +2272,7 @@ Server::forceLeaveClient(BaseClientProxy* client) // then we can't switch back to it when the screen saver // deactivates. if (m_activeSaver == client) { - m_activeSaver = NULL; + m_activeSaver = nullptr; } // tell primary client about the active sides @@ -2289,9 +2285,6 @@ Server::forceLeaveClient(BaseClientProxy* client) // Server::ClipboardInfo::ClipboardInfo() : - m_clipboard(), - m_clipboardData(), - m_clipboardOwner(), m_clipboardSeqNum(0) { // do nothing @@ -2305,8 +2298,8 @@ Server::ClipboardInfo::ClipboardInfo() : Server::LockCursorToScreenInfo* Server::LockCursorToScreenInfo::alloc(State state) { - LockCursorToScreenInfo* info = - (LockCursorToScreenInfo*)malloc(sizeof(LockCursorToScreenInfo)); + auto* info = + static_cast(malloc(sizeof(LockCursorToScreenInfo))); info->m_state = state; return info; } @@ -2319,9 +2312,9 @@ Server::LockCursorToScreenInfo::alloc(State state) Server::SwitchToScreenInfo* Server::SwitchToScreenInfo::alloc(const String& screen) { - SwitchToScreenInfo* info = - (SwitchToScreenInfo*)malloc(sizeof(SwitchToScreenInfo) + - screen.size()); + auto* info = + static_cast(malloc(sizeof(SwitchToScreenInfo) + + screen.size())); strcpy(info->m_screen, screen.c_str()); return info; } @@ -2334,8 +2327,8 @@ Server::SwitchToScreenInfo::alloc(const String& screen) Server::SwitchInDirectionInfo* Server::SwitchInDirectionInfo::alloc(EDirection direction) { - SwitchInDirectionInfo* info = - (SwitchInDirectionInfo*)malloc(sizeof(SwitchInDirectionInfo)); + auto* info = + static_cast(malloc(sizeof(SwitchInDirectionInfo))); info->m_direction = direction; return info; } @@ -2347,8 +2340,8 @@ Server::SwitchInDirectionInfo::alloc(EDirection direction) Server::KeyboardBroadcastInfo* Server::KeyboardBroadcastInfo::alloc(State state) { - KeyboardBroadcastInfo* info = - (KeyboardBroadcastInfo*)malloc(sizeof(KeyboardBroadcastInfo)); + auto* info = + static_cast(malloc(sizeof(KeyboardBroadcastInfo))); info->m_state = state; info->m_screens[0] = '\0'; return info; @@ -2357,9 +2350,9 @@ Server::KeyboardBroadcastInfo::alloc(State state) Server::KeyboardBroadcastInfo* Server::KeyboardBroadcastInfo::alloc(State state, const String& screens) { - KeyboardBroadcastInfo* info = - (KeyboardBroadcastInfo*)malloc(sizeof(KeyboardBroadcastInfo) + - screens.size()); + auto* info = + static_cast(malloc(sizeof(KeyboardBroadcastInfo) + + screens.size())); info->m_state = state; strcpy(info->m_screens, screens.c_str()); return info; @@ -2374,7 +2367,7 @@ Server::isReceivedFileSizeValid() void Server::sendFileToClient(const char* filename) { - if (m_sendFileThread != NULL) { + if (m_sendFileThread != nullptr) { StreamChunker::interruptFile(); } @@ -2388,7 +2381,7 @@ void Server::sendFileThread(void* data) { try { - char* filename = static_cast(data); + auto* filename = static_cast(data); LOG((CLOG_DEBUG "sending file to client, filename=%s", filename)); StreamChunker::sendFile(filename, m_events, this); } @@ -2396,7 +2389,7 @@ Server::sendFileThread(void* data) LOG((CLOG_ERR "failed sending file chunks, error: %s", error.what())); } - m_sendFileThread = NULL; + m_sendFileThread = nullptr; } void @@ -2407,7 +2400,7 @@ Server::dragInfoReceived(UInt32 fileNum, String content) return; } - DragInformation::parseDragInfo(m_fakeDragFileList, fileNum, content); + DragInformation::parseDragInfo(m_fakeDragFileList, fileNum, std::move(content)); m_screen->startDraggingFiles(m_fakeDragFileList); } diff --git a/src/lib/server/Server.h b/src/lib/server/Server.h index e7e86a31..99164fe1 100644 --- a/src/lib/server/Server.h +++ b/src/lib/server/Server.h @@ -107,7 +107,7 @@ public: ownership of \p primaryClient. */ Server(Config& config, PrimaryClient* primaryClient, - synergy::Screen* screen, IEventQueue* events, ServerArgs const& args); + synergy::Screen* screen, IEventQueue* events, ServerArgs args); ~Server(); #ifdef TEST_ENV @@ -202,7 +202,7 @@ private: // change the active screen void switchScreen(BaseClientProxy*, - SInt32 x, SInt32 y, bool forScreenSaver); + SInt32 x, SInt32 y, bool forScreensaver); // jump to screen void jumpToScreen(BaseClientProxy*); @@ -242,7 +242,7 @@ private: // test if a switch is permitted. this includes testing user // options like switch delay and tracking any state required to // implement them. returns true iff a switch is permitted. - bool isSwitchOkay(BaseClientProxy* dst, EDirection, + bool isSwitchOkay(BaseClientProxy* newScreen, EDirection, SInt32 x, SInt32 y, SInt32 xActive, SInt32 yActive); // update switch state due to a mouse move at \p x, \p y that @@ -404,7 +404,7 @@ private: // current mouse position (in absolute screen coordinates) on // whichever screen is active - SInt32 m_x, m_y; + SInt32 m_x{}, m_y{}; // last mouse deltas. this is needed to smooth out double tap // on win32 which reports bogus mouse motion at the edge of @@ -424,7 +424,7 @@ private: // state saved when screen saver activates BaseClientProxy* m_activeSaver; - SInt32 m_xSaver, m_ySaver; + SInt32 m_xSaver{}, m_ySaver{}; // common state for screen switch tests. all tests are always // trying to reach the same screen in the same direction. @@ -434,7 +434,7 @@ private: // state for delayed screen switching double m_switchWaitDelay; EventQueueTimer* m_switchWaitTimer; - SInt32 m_switchWaitX, m_switchWaitY; + SInt32 m_switchWaitX{}, m_switchWaitY{}; // state for double-tap screen switching double m_switchTwoTapDelay; @@ -465,7 +465,7 @@ private: IEventQueue* m_events; // file transfer - size_t m_expectedFileSize; + size_t m_expectedFileSize{}; String m_receivedFileData; DragFileList m_dragFileList; DragFileList m_fakeDragFileList; @@ -478,6 +478,6 @@ private: Thread* m_sendDragInfoThread; bool m_waitDragInfoThread; - ClientListener* m_clientListener; + ClientListener* m_clientListener{}; ServerArgs m_args; }; diff --git a/src/lib/shared/SerialKey.cpp b/src/lib/shared/SerialKey.cpp index 7a47adfb..9eed4922 100644 --- a/src/lib/shared/SerialKey.cpp +++ b/src/lib/shared/SerialKey.cpp @@ -17,14 +17,14 @@ #include "SerialKey.h" -#include -#include #include -#include #include -#include +#include #include +#include +#include #include +#include using namespace std; @@ -37,7 +37,7 @@ SerialKey::SerialKey(Edition edition): { } -SerialKey::SerialKey(std::string serial) : +SerialKey::SerialKey(const std::string& serial) : m_userLimit(1), m_warnTime(0), m_expireTime(0), @@ -113,8 +113,7 @@ SerialKey::editionString() const static std::string hexEncode (std::string const& str) { std::ostringstream oss; - for (size_t i = 0; i < str.size(); ++i) { - unsigned c = str[i]; + for (unsigned int c : str) { c %= 256; oss << std::setfill('0') << std::hex << std::setw(2) << std::uppercase; @@ -172,7 +171,7 @@ SerialKey::decode(const std::string& serial) static const char* const lut = "0123456789ABCDEF"; string output; size_t len = serial.length(); - if (len & 1) { + if ((len & 1) != 0u) { return output; } @@ -213,7 +212,7 @@ SerialKey::parse(std::string plainSerial) bool look = true; while (look) { std::string::size_type start = pos; - pos = plainSerial.find(";", pos); + pos = plainSerial.find(';', pos); if (pos == string::npos) { pos = plainSerial.length(); look = false; @@ -238,7 +237,7 @@ SerialKey::parse(std::string plainSerial) else if ((parts.size() == 9) && (parts.at(0).find("v2") != string::npos)) { // e.g.: {v2;trial;basic;Bob;1;email;company name;1398297600;1398384000} - m_trial = parts.at(1) == "trial" ? true : false; + m_trial = parts.at(1) == "trial"; m_edition = parseEdition(parts.at(2)); m_name = parts.at(3); sscanf(parts.at(4).c_str(), "%d", &m_userLimit); diff --git a/src/lib/shared/SerialKey.h b/src/lib/shared/SerialKey.h index a27382cc..41925ddc 100644 --- a/src/lib/shared/SerialKey.h +++ b/src/lib/shared/SerialKey.h @@ -29,7 +29,7 @@ class SerialKey { friend bool operator== (SerialKey const&, SerialKey const&); public: explicit SerialKey(Edition edition = kUnregistered); - explicit SerialKey(std::string serial); + explicit SerialKey(const std::string& serial); bool isExpiring(time_t currentTime) const; bool isExpired(time_t currentTime) const; diff --git a/src/test/global/TestEventQueue.cpp b/src/test/global/TestEventQueue.cpp index 470ab334..6dd91b60 100644 --- a/src/test/global/TestEventQueue.cpp +++ b/src/test/global/TestEventQueue.cpp @@ -18,8 +18,8 @@ #include "test/global/TestEventQueue.h" #include "base/Log.h" -#include "base/TMethodEventJob.h" #include "base/SimpleEventQueueBuffer.h" +#include "base/TMethodEventJob.h" #include "common/stdexcept.h" class EventQueueTimer { }; @@ -34,7 +34,7 @@ void TestEventQueue::initQuitTimeout(double timeout) { assert(m_quitTimeoutTimer == nullptr); - m_quitTimeoutTimer = newOneShotTimer(timeout, NULL); + m_quitTimeoutTimer = newOneShotTimer(timeout, nullptr); adoptHandler(Event::kTimer, m_quitTimeoutTimer, new TMethodEventJob( this, &TestEventQueue::handleQuitTimeout)); @@ -49,7 +49,7 @@ TestEventQueue::cleanupQuitTimeout() } void -TestEventQueue::handleQuitTimeout(const Event&, void* vclient) +TestEventQueue::handleQuitTimeout(const Event& /*unused*/, void* /*vclient*/) { throw std::runtime_error("test event queue timeout"); } diff --git a/src/test/integtests/Main.cpp b/src/test/integtests/Main.cpp index 15598db2..ee587f4d 100644 --- a/src/test/integtests/Main.cpp +++ b/src/test/integtests/Main.cpp @@ -24,15 +24,15 @@ #endif #include "test/global/gtest.h" -#include #include +#include #define LOCK_TIMEOUT 30 using namespace std; -void lock(string lockFile); -void unlock(string lockFile); +void lock(const string& lockFile); +void unlock(const string& lockFile); int main(int argc, char **argv) @@ -50,7 +50,7 @@ main(int argc, char **argv) string lockFile; for (int i = 0; i < argc; i++) { - if (string(argv[i]).compare("--lock-file") == 0) { + if (string(argv[i]) == "--lock-file") { lockFile = argv[i + 1]; } } @@ -77,7 +77,7 @@ main(int argc, char **argv) } void -lock(string lockFile) +lock(const string& lockFile) { double start = ARCH->time(); @@ -102,7 +102,7 @@ lock(string lockFile) } void -unlock(string lockFile) +unlock(const string& lockFile) { remove(lockFile.c_str()); } diff --git a/src/test/integtests/ipc/IpcTests.cpp b/src/test/integtests/ipc/IpcTests.cpp index fc9ed8da..127e481c 100644 --- a/src/test/integtests/ipc/IpcTests.cpp +++ b/src/test/integtests/ipc/IpcTests.cpp @@ -16,26 +16,26 @@ * along with this program. If not, see . */ -// TODO: fix, tests failing intermittently on mac. +// TODO(andrew): fix, tests failing intermittently on mac. #ifndef WINAPI_CARBON #define TEST_ENV #include "test/global/TestEventQueue.h" -#include "ipc/IpcServer.h" -#include "ipc/IpcClient.h" -#include "ipc/IpcServerProxy.h" -#include "ipc/IpcMessage.h" -#include "ipc/IpcClientProxy.h" -#include "ipc/Ipc.h" -#include "net/SocketMultiplexer.h" -#include "mt/Thread.h" #include "arch/Arch.h" -#include "base/TMethodJob.h" -#include "base/String.h" -#include "base/Log.h" #include "base/EventQueue.h" +#include "base/Log.h" +#include "base/String.h" #include "base/TMethodEventJob.h" +#include "base/TMethodJob.h" +#include "ipc/Ipc.h" +#include "ipc/IpcClient.h" +#include "ipc/IpcClientProxy.h" +#include "ipc/IpcMessage.h" +#include "ipc/IpcServer.h" +#include "ipc/IpcServerProxy.h" +#include "mt/Thread.h" +#include "net/SocketMultiplexer.h" #include "test/global/gtest.h" @@ -45,22 +45,22 @@ class IpcTests : public ::testing::Test { public: IpcTests(); - virtual ~IpcTests(); + ~IpcTests() override; - void connectToServer_handleMessageReceived(const Event&, void*); - void sendMessageToServer_serverHandleMessageReceived(const Event&, void*); - void sendMessageToClient_serverHandleClientConnected(const Event&, void*); - void sendMessageToClient_clientHandleMessageReceived(const Event&, void*); + void connectToServer_handleMessageReceived(const Event& /*e*/, void* /*unused*/); + void sendMessageToServer_serverHandleMessageReceived(const Event& /*e*/, void* /*unused*/); + void sendMessageToClient_serverHandleClientConnected(const Event& /*e*/, void* /*unused*/); + void sendMessageToClient_clientHandleMessageReceived(const Event& /*e*/, void* /*unused*/); public: SocketMultiplexer m_multiplexer; - bool m_connectToServer_helloMessageReceived; - bool m_connectToServer_hasClientNode; - IpcServer* m_connectToServer_server; + bool m_connectToServer_helloMessageReceived{false}; + bool m_connectToServer_hasClientNode{false}; + IpcServer* m_connectToServer_server{nullptr}; String m_sendMessageToServer_receivedString; String m_sendMessageToClient_receivedString; - IpcClient* m_sendMessageToServer_client; - IpcServer* m_sendMessageToClient_server; + IpcClient* m_sendMessageToServer_client{nullptr}; + IpcServer* m_sendMessageToClient_server{nullptr}; TestEventQueue m_events; }; @@ -143,23 +143,17 @@ TEST_F(IpcTests, sendMessageToClient) EXPECT_EQ("test", m_sendMessageToClient_receivedString); } -IpcTests::IpcTests() : -m_connectToServer_helloMessageReceived(false), -m_connectToServer_hasClientNode(false), -m_connectToServer_server(nullptr), -m_sendMessageToClient_server(nullptr), -m_sendMessageToServer_client(nullptr) +IpcTests::IpcTests() { } IpcTests::~IpcTests() -{ -} += default; void -IpcTests::connectToServer_handleMessageReceived(const Event& e, void*) +IpcTests::connectToServer_handleMessageReceived(const Event& e, void* /*unused*/) { - IpcMessage* m = static_cast(e.getDataObject()); + auto* m = dynamic_cast(e.getDataObject()); if (m->type() == kIpcHello) { m_connectToServer_hasClientNode = m_connectToServer_server->hasClients(kIpcClientNode); @@ -169,16 +163,16 @@ IpcTests::connectToServer_handleMessageReceived(const Event& e, void*) } void -IpcTests::sendMessageToServer_serverHandleMessageReceived(const Event& e, void*) +IpcTests::sendMessageToServer_serverHandleMessageReceived(const Event& e, void* /*unused*/) { - IpcMessage* m = static_cast(e.getDataObject()); + auto* m = dynamic_cast(e.getDataObject()); if (m->type() == kIpcHello) { LOG((CLOG_DEBUG "client said hello, sending test to server")); IpcCommandMessage m("test", true); m_sendMessageToServer_client->send(m); } else if (m->type() == kIpcCommand) { - IpcCommandMessage* cm = static_cast(m); + auto* cm = dynamic_cast(m); LOG((CLOG_DEBUG "got ipc command message, %d", cm->command().c_str())); m_sendMessageToServer_receivedString = cm->command(); m_events.raiseQuitEvent(); @@ -186,9 +180,9 @@ IpcTests::sendMessageToServer_serverHandleMessageReceived(const Event& e, void*) } void -IpcTests::sendMessageToClient_serverHandleClientConnected(const Event& e, void*) +IpcTests::sendMessageToClient_serverHandleClientConnected(const Event& e, void* /*unused*/) { - IpcMessage* m = static_cast(e.getDataObject()); + auto* m = dynamic_cast(e.getDataObject()); if (m->type() == kIpcHello) { LOG((CLOG_DEBUG "client said hello, sending test to client")); IpcLogLineMessage m("test"); @@ -197,11 +191,11 @@ IpcTests::sendMessageToClient_serverHandleClientConnected(const Event& e, void*) } void -IpcTests::sendMessageToClient_clientHandleMessageReceived(const Event& e, void*) +IpcTests::sendMessageToClient_clientHandleMessageReceived(const Event& e, void* /*unused*/) { - IpcMessage* m = static_cast(e.getDataObject()); + auto* m = dynamic_cast(e.getDataObject()); if (m->type() == kIpcLogLine) { - IpcLogLineMessage* llm = static_cast(m); + auto* llm = dynamic_cast(m); LOG((CLOG_DEBUG "got ipc log message, %d", llm->logLine().c_str())); m_sendMessageToClient_receivedString = llm->logLine(); m_events.raiseQuitEvent(); diff --git a/src/test/integtests/net/NetworkTests.cpp b/src/test/integtests/net/NetworkTests.cpp index 610f2776..fe7ca8d2 100644 --- a/src/test/integtests/net/NetworkTests.cpp +++ b/src/test/integtests/net/NetworkTests.cpp @@ -15,36 +15,36 @@ * along with this program. If not, see . */ -// TODO: fix, tests failing intermittently on mac. +// TODO(andrew): fix, tests failing intermittently on mac. #ifndef WINAPI_CARBON #define TEST_ENV #include "test/mock/server/MockConfig.h" -#include "test/mock/server/MockPrimaryClient.h" -#include "test/mock/synergy/MockScreen.h" -#include "test/mock/server/MockInputFilter.h" -#include "test/global/TestEventQueue.h" -#include "server/Server.h" -#include "server/ClientListener.h" -#include "server/ClientProxy.h" -#include "client/Client.h" -#include "core/FileChunk.h" -#include "core/StreamChunker.h" -#include "net/SocketMultiplexer.h" -#include "net/NetworkAddress.h" -#include "net/TCPSocketFactory.h" -#include "mt/Thread.h" +#include "base/Log.h" #include "base/TMethodEventJob.h" #include "base/TMethodJob.h" -#include "base/Log.h" +#include "client/Client.h" #include "common/stdexcept.h" +#include "core/FileChunk.h" +#include "core/StreamChunker.h" +#include "mt/Thread.h" +#include "net/NetworkAddress.h" +#include "net/SocketMultiplexer.h" +#include "net/TCPSocketFactory.h" +#include "server/ClientListener.h" +#include "server/ClientProxy.h" +#include "server/Server.h" +#include "test/global/TestEventQueue.h" +#include "test/mock/server/MockInputFilter.h" +#include "test/mock/server/MockPrimaryClient.h" +#include "test/mock/synergy/MockScreen.h" #include "test/global/gtest.h" -#include #include #include -#include +#include +#include using namespace std; using ::testing::_; @@ -69,15 +69,13 @@ class NetworkTests : public ::testing::Test { public: NetworkTests() : - m_mockData(NULL), - m_mockDataSize(0), - m_mockFileSize(0) + m_mockData(nullptr) { m_mockData = newMockData(kMockDataSize); createFile(m_mockFile, kMockFilename, kMockFileSize); } - ~NetworkTests() + ~NetworkTests() override { remove(kMockFilename); delete[] m_mockData; @@ -85,24 +83,24 @@ public: void sendMockData(void* eventTarget); - void sendToClient_mockData_handleClientConnected(const Event&, void* vlistener); - void sendToClient_mockData_fileRecieveCompleted(const Event&, void*); + void sendToClient_mockData_handleClientConnected(const Event& /*unused*/, void* vlistener); + void sendToClient_mockData_fileRecieveCompleted(const Event& /*event*/, void* /*unused*/); - void sendToClient_mockFile_handleClientConnected(const Event&, void* vlistener); - void sendToClient_mockFile_fileRecieveCompleted(const Event& event, void*); + void sendToClient_mockFile_handleClientConnected(const Event& /*unused*/, void* vlistener); + void sendToClient_mockFile_fileRecieveCompleted(const Event& event, void* /*unused*/); - void sendToServer_mockData_handleClientConnected(const Event&, void* vlistener); - void sendToServer_mockData_fileRecieveCompleted(const Event& event, void*); + void sendToServer_mockData_handleClientConnected(const Event& /*unused*/, void* vclient); + void sendToServer_mockData_fileRecieveCompleted(const Event& event, void* /*unused*/); - void sendToServer_mockFile_handleClientConnected(const Event&, void* vlistener); - void sendToServer_mockFile_fileRecieveCompleted(const Event& event, void*); + void sendToServer_mockFile_handleClientConnected(const Event& /*unused*/, void* vclient); + void sendToServer_mockFile_fileRecieveCompleted(const Event& event, void* /*unused*/); public: TestEventQueue m_events; UInt8* m_mockData; - size_t m_mockDataSize; + size_t m_mockDataSize{0}; fstream m_mockFile; - size_t m_mockFileSize; + size_t m_mockFileSize{0}; }; TEST_F(NetworkTests, sendToClient_mockData) @@ -114,7 +112,7 @@ TEST_F(NetworkTests, sendToClient_mockData) // server SocketMultiplexer serverSocketMultiplexer; - TCPSocketFactory* serverSocketFactory = new TCPSocketFactory(&m_events, &serverSocketMultiplexer); + auto* serverSocketFactory = new TCPSocketFactory(&m_events, &serverSocketMultiplexer); ClientListener listener(serverAddress, serverSocketFactory, &m_events); NiceMock serverScreen; NiceMock primaryClient; @@ -138,7 +136,7 @@ TEST_F(NetworkTests, sendToClient_mockData) // client NiceMock clientScreen; SocketMultiplexer clientSocketMultiplexer; - TCPSocketFactory* clientSocketFactory = new TCPSocketFactory(&m_events, &clientSocketMultiplexer); + auto* clientSocketFactory = new TCPSocketFactory(&m_events, &clientSocketMultiplexer); ON_CALL(clientScreen, getShape(_, _, _, _)).WillByDefault(Invoke(getScreenShape)); ON_CALL(clientScreen, getCursorPos(_, _)).WillByDefault(Invoke(getCursorPos)); @@ -171,7 +169,7 @@ TEST_F(NetworkTests, sendToClient_mockFile) // server SocketMultiplexer serverSocketMultiplexer; - TCPSocketFactory* serverSocketFactory = new TCPSocketFactory(&m_events, &serverSocketMultiplexer); + auto* serverSocketFactory = new TCPSocketFactory(&m_events, &serverSocketMultiplexer); ClientListener listener(serverAddress, serverSocketFactory, &m_events); NiceMock serverScreen; NiceMock primaryClient; @@ -195,7 +193,7 @@ TEST_F(NetworkTests, sendToClient_mockFile) // client NiceMock clientScreen; SocketMultiplexer clientSocketMultiplexer; - TCPSocketFactory* clientSocketFactory = new TCPSocketFactory(&m_events, &clientSocketMultiplexer); + auto* clientSocketFactory = new TCPSocketFactory(&m_events, &clientSocketMultiplexer); ON_CALL(clientScreen, getShape(_, _, _, _)).WillByDefault(Invoke(getScreenShape)); ON_CALL(clientScreen, getCursorPos(_, _)).WillByDefault(Invoke(getCursorPos)); @@ -227,7 +225,7 @@ TEST_F(NetworkTests, sendToServer_mockData) // server SocketMultiplexer serverSocketMultiplexer; - TCPSocketFactory* serverSocketFactory = new TCPSocketFactory(&m_events, &serverSocketMultiplexer); + auto* serverSocketFactory = new TCPSocketFactory(&m_events, &serverSocketMultiplexer); ClientListener listener(serverAddress, serverSocketFactory, &m_events); NiceMock serverScreen; NiceMock primaryClient; @@ -246,7 +244,7 @@ TEST_F(NetworkTests, sendToServer_mockData) // client NiceMock clientScreen; SocketMultiplexer clientSocketMultiplexer; - TCPSocketFactory* clientSocketFactory = new TCPSocketFactory(&m_events, &clientSocketMultiplexer); + auto* clientSocketFactory = new TCPSocketFactory(&m_events, &clientSocketMultiplexer); ON_CALL(clientScreen, getShape(_, _, _, _)).WillByDefault(Invoke(getScreenShape)); ON_CALL(clientScreen, getCursorPos(_, _)).WillByDefault(Invoke(getCursorPos)); @@ -283,7 +281,7 @@ TEST_F(NetworkTests, sendToServer_mockFile) // server SocketMultiplexer serverSocketMultiplexer; - TCPSocketFactory* serverSocketFactory = new TCPSocketFactory(&m_events, &serverSocketMultiplexer); + auto* serverSocketFactory = new TCPSocketFactory(&m_events, &serverSocketMultiplexer); ClientListener listener(serverAddress, serverSocketFactory, &m_events); NiceMock serverScreen; NiceMock primaryClient; @@ -302,7 +300,7 @@ TEST_F(NetworkTests, sendToServer_mockFile) // client NiceMock clientScreen; SocketMultiplexer clientSocketMultiplexer; - TCPSocketFactory* clientSocketFactory = new TCPSocketFactory(&m_events, &clientSocketMultiplexer); + auto* clientSocketFactory = new TCPSocketFactory(&m_events, &clientSocketMultiplexer); ON_CALL(clientScreen, getShape(_, _, _, _)).WillByDefault(Invoke(getScreenShape)); ON_CALL(clientScreen, getCursorPos(_, _)).WillByDefault(Invoke(getCursorPos)); @@ -331,13 +329,13 @@ TEST_F(NetworkTests, sendToServer_mockFile) } void -NetworkTests::sendToClient_mockData_handleClientConnected(const Event&, void* vlistener) +NetworkTests::sendToClient_mockData_handleClientConnected(const Event& /*unused*/, void* vlistener) { - ClientListener* listener = static_cast(vlistener); + auto* listener = static_cast(vlistener); Server* server = listener->getServer(); ClientProxy* client = listener->getNextClient(); - if (client == NULL) { + if (client == nullptr) { throw runtime_error("client is null"); } @@ -349,22 +347,22 @@ NetworkTests::sendToClient_mockData_handleClientConnected(const Event&, void* vl } void -NetworkTests::sendToClient_mockData_fileRecieveCompleted(const Event& event, void*) +NetworkTests::sendToClient_mockData_fileRecieveCompleted(const Event& event, void* /*unused*/) { - Client* client = static_cast(event.getTarget()); + auto* client = static_cast(event.getTarget()); EXPECT_TRUE(client->isReceivedFileSizeValid()); m_events.raiseQuitEvent(); } void -NetworkTests::sendToClient_mockFile_handleClientConnected(const Event&, void* vlistener) +NetworkTests::sendToClient_mockFile_handleClientConnected(const Event& /*unused*/, void* vlistener) { - ClientListener* listener = static_cast(vlistener); + auto* listener = static_cast(vlistener); Server* server = listener->getServer(); ClientProxy* client = listener->getNextClient(); - if (client == NULL) { + if (client == nullptr) { throw runtime_error("client is null"); } @@ -376,41 +374,41 @@ NetworkTests::sendToClient_mockFile_handleClientConnected(const Event&, void* vl } void -NetworkTests::sendToClient_mockFile_fileRecieveCompleted(const Event& event, void*) +NetworkTests::sendToClient_mockFile_fileRecieveCompleted(const Event& event, void* /*unused*/) { - Client* client = static_cast(event.getTarget()); + auto* client = static_cast(event.getTarget()); EXPECT_TRUE(client->isReceivedFileSizeValid()); m_events.raiseQuitEvent(); } void -NetworkTests::sendToServer_mockData_handleClientConnected(const Event&, void* vclient) +NetworkTests::sendToServer_mockData_handleClientConnected(const Event& /*unused*/, void* vclient) { - Client* client = static_cast(vclient); + auto* client = static_cast(vclient); sendMockData(client); } void -NetworkTests::sendToServer_mockData_fileRecieveCompleted(const Event& event, void*) +NetworkTests::sendToServer_mockData_fileRecieveCompleted(const Event& event, void* /*unused*/) { - Server* server = static_cast(event.getTarget()); + auto* server = static_cast(event.getTarget()); EXPECT_TRUE(server->isReceivedFileSizeValid()); m_events.raiseQuitEvent(); } void -NetworkTests::sendToServer_mockFile_handleClientConnected(const Event&, void* vclient) +NetworkTests::sendToServer_mockFile_handleClientConnected(const Event& /*unused*/, void* vclient) { - Client* client = static_cast(vclient); + auto* client = static_cast(vclient); client->sendFileToServer(kMockFilename); } void -NetworkTests::sendToServer_mockFile_fileRecieveCompleted(const Event& event, void*) +NetworkTests::sendToServer_mockFile_fileRecieveCompleted(const Event& event, void* /*unused*/) { - Server* server = static_cast(event.getTarget()); + auto* server = static_cast(event.getTarget()); EXPECT_TRUE(server->isReceivedFileSizeValid()); m_events.raiseQuitEvent(); @@ -457,7 +455,7 @@ NetworkTests::sendMockData(void* eventTarget) UInt8* newMockData(size_t size) { - UInt8* buffer = new UInt8[size]; + auto* buffer = new UInt8[size]; UInt8* data = buffer; const UInt8 head[] = "mock head... "; diff --git a/src/test/integtests/platform/XWindowsClipboardTests.cpp b/src/test/integtests/platform/XWindowsClipboardTests.cpp index 0cd0f710..97799bd2 100644 --- a/src/test/integtests/platform/XWindowsClipboardTests.cpp +++ b/src/test/integtests/platform/XWindowsClipboardTests.cpp @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -// TODO: fix tests - compile error on linux +// TODO(andrew): fix tests - compile error on linux #if 0 #include "platform/XWindowsClipboard.h" diff --git a/src/test/integtests/platform/XWindowsKeyStateTests.cpp b/src/test/integtests/platform/XWindowsKeyStateTests.cpp index 69fe64a9..a375790e 100644 --- a/src/test/integtests/platform/XWindowsKeyStateTests.cpp +++ b/src/test/integtests/platform/XWindowsKeyStateTests.cpp @@ -19,9 +19,9 @@ #define TEST_ENV #include "test/mock/synergy/MockKeyMap.h" -#include "test/mock/synergy/MockEventQueue.h" -#include "platform/XWindowsKeyState.h" #include "base/Log.h" +#include "platform/XWindowsKeyState.h" +#include "test/mock/synergy/MockEventQueue.h" #define XK_LATIN1 #define XK_MISCELLANY @@ -31,41 +31,41 @@ # include #endif -#include "test/global/gtest.h" #include "test/global/gmock.h" -#include +#include "test/global/gtest.h" +#include class XWindowsKeyStateTests : public ::testing::Test { protected: XWindowsKeyStateTests() : - m_display(NULL) + m_display(nullptr) { } - ~XWindowsKeyStateTests() + ~XWindowsKeyStateTests() override { - if (m_display != NULL) { + if (m_display != nullptr) { LOG((CLOG_DEBUG "closing display")); XCloseDisplay(m_display); } } - virtual void - SetUp() + void + SetUp() override { // open the display only once for the entire test suite - if (this->m_display == NULL) { + if (this->m_display == nullptr) { LOG((CLOG_DEBUG "opening display")); - this->m_display = XOpenDisplay(NULL); + this->m_display = XOpenDisplay(nullptr); - ASSERT_TRUE(this->m_display != NULL) + ASSERT_TRUE(this->m_display != nullptr) << "unable to open display: " << errno; } } - virtual void - TearDown() + void + TearDown() override { } @@ -157,7 +157,7 @@ TEST_F(XWindowsKeyStateTests, pollActiveModifiers_defaultState_returnsZero) ASSERT_EQ(0, actual); } -#if 0 // TODO: fix, causes sigsegv +#if 0 // TODO(andrew): fix, causes sigsegv TEST_F(XWindowsKeyStateTests, pollActiveModifiers_shiftKeyDownThenUp_masksAreCorrect) { MockKeyMap keyMap; @@ -228,7 +228,7 @@ TEST_F(XWindowsKeyStateTests, pollActiveGroup_xkb_areEqual) // reset the group keyState.group(-1); - XkbStateRec state; + XkbStateRec state{}; // compare pollActiveGroup() with XkbGetState() if (XkbGetState(m_display, XkbUseCoreKbd, &state) == Success) { diff --git a/src/test/integtests/platform/XWindowsScreenSaverTests.cpp b/src/test/integtests/platform/XWindowsScreenSaverTests.cpp index e9a5e937..e205d9e9 100644 --- a/src/test/integtests/platform/XWindowsScreenSaverTests.cpp +++ b/src/test/integtests/platform/XWindowsScreenSaverTests.cpp @@ -16,7 +16,7 @@ * along with this program. If not, see . */ -// TODO: fix tests +// TODO(andrew): fix tests #if 0 #include "test/mock/synergy/MockEventQueue.h" diff --git a/src/test/unittests/ipc/IpcLogOutputterTests.cpp b/src/test/unittests/ipc/IpcLogOutputterTests.cpp index 22adfdf1..142e54fc 100644 --- a/src/test/unittests/ipc/IpcLogOutputterTests.cpp +++ b/src/test/unittests/ipc/IpcLogOutputterTests.cpp @@ -19,10 +19,10 @@ #include "test/mock/ipc/MockIpcServer.h" -#include "mt/Thread.h" -#include "ipc/IpcLogOutputter.h" #include "base/String.h" #include "common/common.h" +#include "ipc/IpcLogOutputter.h" +#include "mt/Thread.h" #include "test/global/gmock.h" #include "test/global/gtest.h" diff --git a/src/test/unittests/synergy/ArgParserTests.cpp b/src/test/unittests/synergy/ArgParserTests.cpp index 31095d68..f9b1eb4d 100644 --- a/src/test/unittests/synergy/ArgParserTests.cpp +++ b/src/test/unittests/synergy/ArgParserTests.cpp @@ -25,7 +25,7 @@ TEST(ArgParserTests, isArg_abbreviationsArg_returnTrue) int i = 1; const int argc = 2; const char* argv[argc] = { "stub", "-t" }; - bool result = ArgParser::isArg(i, argc, argv, "-t", NULL); + bool result = ArgParser::isArg(i, argc, argv, "-t", nullptr); EXPECT_EQ(true, result); } @@ -35,7 +35,7 @@ TEST(ArgParserTests, isArg_fullArg_returnTrue) int i = 1; const int argc = 2; const char* argv[argc] = { "stub", "--test" }; - bool result = ArgParser::isArg(i, argc, argv, NULL, "--test"); + bool result = ArgParser::isArg(i, argc, argv, nullptr, "--test"); EXPECT_EQ(true, result); } @@ -45,11 +45,11 @@ TEST(ArgParserTests, isArg_missingArgs_returnFalse) int i = 1; const int argc = 2; const char* argv[argc] = { "stub", "-t" }; - ArgParser argParser(NULL); + ArgParser argParser(nullptr); ArgsBase argsBase; argParser.setArgsBase(argsBase); - bool result = ArgParser::isArg(i, argc, argv, "-t", NULL, 1); + bool result = ArgParser::isArg(i, argc, argv, "-t", nullptr, 1); EXPECT_FALSE(result); EXPECT_EQ(true, argsBase.m_shouldExit); @@ -119,7 +119,7 @@ TEST(ArgParserTests, splitCommandString_twoArgs_returnArgv) TEST(ArgParserTests, splitCommandString_doubleQuotedArgs_returnArgv) { - String command("\"stub1\" stub2 \"stub3\""); + String command(R"("stub1" stub2 "stub3")"); std::vector argv; ArgParser::splitCommandString(command, argv); @@ -132,7 +132,7 @@ TEST(ArgParserTests, splitCommandString_doubleQuotedArgs_returnArgv) TEST(ArgParserTests, splitCommandString_spaceDoubleQuotedArgs_returnArgv) { - String command("\"stub1\" stub2 \"stub3 space\""); + String command(R"("stub1" stub2 "stub3 space")"); std::vector argv; ArgParser::splitCommandString(command, argv); @@ -146,9 +146,9 @@ TEST(ArgParserTests, splitCommandString_spaceDoubleQuotedArgs_returnArgv) TEST(ArgParserTests, getArgv_stringArray_return2DArray) { std::vector argArray; - argArray.push_back("stub1"); - argArray.push_back("stub2"); - argArray.push_back("stub3 space"); + argArray.emplace_back("stub1"); + argArray.emplace_back("stub2"); + argArray.emplace_back("stub3 space"); const char** argv = ArgParser::getArgv(argArray); String row1(argv[0]); @@ -165,8 +165,8 @@ TEST(ArgParserTests, getArgv_stringArray_return2DArray) TEST(ArgParserTests, assembleCommand_stringArray_returnCommand) { std::vector argArray; - argArray.push_back("stub1"); - argArray.push_back("stub2"); + argArray.emplace_back("stub1"); + argArray.emplace_back("stub2"); String command = ArgParser::assembleCommand(argArray); EXPECT_EQ("stub1 stub2", command); @@ -175,8 +175,8 @@ TEST(ArgParserTests, assembleCommand_stringArray_returnCommand) TEST(ArgParserTests, assembleCommand_ignoreSecondArg_returnCommand) { std::vector argArray; - argArray.push_back("stub1"); - argArray.push_back("stub2"); + argArray.emplace_back("stub1"); + argArray.emplace_back("stub2"); String command = ArgParser::assembleCommand(argArray, "stub2"); EXPECT_EQ("stub1", command); @@ -185,10 +185,10 @@ TEST(ArgParserTests, assembleCommand_ignoreSecondArg_returnCommand) TEST(ArgParserTests, assembleCommand_ignoreSecondArgWithOneParameter_returnCommand) { std::vector argArray; - argArray.push_back("stub1"); - argArray.push_back("stub2"); - argArray.push_back("stub3"); - argArray.push_back("stub4"); + argArray.emplace_back("stub1"); + argArray.emplace_back("stub2"); + argArray.emplace_back("stub3"); + argArray.emplace_back("stub4"); String command = ArgParser::assembleCommand(argArray, "stub2", 1); EXPECT_EQ("stub1 stub4", command); @@ -197,9 +197,9 @@ TEST(ArgParserTests, assembleCommand_ignoreSecondArgWithOneParameter_returnComma TEST(ArgParserTests, assembleCommand_stringArrayWithSpace_returnCommand) { std::vector argArray; - argArray.push_back("stub1 space"); - argArray.push_back("stub2"); - argArray.push_back("stub3 space"); + argArray.emplace_back("stub1 space"); + argArray.emplace_back("stub2"); + argArray.emplace_back("stub3 space"); String command = ArgParser::assembleCommand(argArray); EXPECT_EQ("\"stub1 space\" stub2 \"stub3 space\"", command); diff --git a/src/test/unittests/synergy/ClientArgsParsingTests.cpp b/src/test/unittests/synergy/ClientArgsParsingTests.cpp index 7342b693..b453162f 100644 --- a/src/test/unittests/synergy/ClientArgsParsingTests.cpp +++ b/src/test/unittests/synergy/ClientArgsParsingTests.cpp @@ -26,7 +26,7 @@ using ::testing::Invoke; using ::testing::NiceMock; bool -client_stubParseGenericArgs(int, const char* const*, int&) +client_stubParseGenericArgs(int /*unused*/, const char* const* /*unused*/, int& /*unused*/) { return false; } diff --git a/src/test/unittests/synergy/ClipboardTests.cpp b/src/test/unittests/synergy/ClipboardTests.cpp index b6aec012..37aae395 100644 --- a/src/test/unittests/synergy/ClipboardTests.cpp +++ b/src/test/unittests/synergy/ClipboardTests.cpp @@ -192,7 +192,7 @@ TEST(ClipboardTests, marshall_withTextAdded_lastSizeCharIs14) EXPECT_EQ(14, (int)actual[11]); } -// TODO: there's some integer -> char encoding going on here. i find it +// TODO(andrew): there's some integer -> char encoding going on here. i find it // hard to believe that the clipboard is the only thing doing this. maybe // we should refactor this stuff out of the clipboard. TEST(ClipboardTests, marshall_withTextSize285_sizeCharsValid) @@ -274,10 +274,10 @@ TEST(ClipboardTests, unmarshall_emptyData_hasTextIsFalse) Clipboard clipboard; String data; - data += (char)0; - data += (char)0; - data += (char)0; - data += (char)0; // 0 formats added + data += static_cast(0); + data += static_cast(0); + data += static_cast(0); + data += static_cast(0); // 0 formats added clipboard.unmarshall(data, 0); @@ -299,18 +299,18 @@ TEST(ClipboardTests, unmarshall_withTextSize285_getTextIsValid) text.append("network. Synergy is supported on Windows, Mac OS X and Linux."); String data; - data += (char)0; - data += (char)0; - data += (char)0; - data += (char)1; // 1 format added - data += (char)0; - data += (char)0; - data += (char)0; - data += (char)IClipboard::kText; - data += (char)0; // 285 >> 24 = 285 / (256^3) = 0 - data += (char)0; // 285 >> 16 = 285 / (256^2) = 0 - data += (char)1; // 285 >> 8 = 285 / (256^1) = 1(.11328125) - data += (char)29; // 285 - 256 = 29 + data += static_cast(0); + data += static_cast(0); + data += static_cast(0); + data += static_cast(1); // 1 format added + data += static_cast(0); + data += static_cast(0); + data += static_cast(0); + data += static_cast(IClipboard::kText); + data += static_cast(0); // 285 >> 24 = 285 / (256^3) = 0 + data += static_cast(0); // 285 >> 16 = 285 / (256^2) = 0 + data += static_cast(1); // 285 >> 8 = 285 / (256^1) = 1(.11328125) + data += static_cast(29); // 285 - 256 = 29 data += text; clipboard.unmarshall(data, 0); @@ -324,27 +324,27 @@ TEST(ClipboardTests, unmarshall_withTextAndHtml_getTextIsValid) { Clipboard clipboard; String data; - data += (char)0; - data += (char)0; - data += (char)0; - data += (char)2; // 2 formats added - data += (char)0; - data += (char)0; - data += (char)0; - data += (char)IClipboard::kText; - data += (char)0; - data += (char)0; - data += (char)0; - data += (char)14; + data += static_cast(0); + data += static_cast(0); + data += static_cast(0); + data += static_cast(2); // 2 formats added + data += static_cast(0); + data += static_cast(0); + data += static_cast(0); + data += static_cast(IClipboard::kText); + data += static_cast(0); + data += static_cast(0); + data += static_cast(0); + data += static_cast(14); data += "synergy rocks!"; - data += (char)0; - data += (char)0; - data += (char)0; - data += (char)IClipboard::kHTML; - data += (char)0; - data += (char)0; - data += (char)0; - data += (char)10; + data += static_cast(0); + data += static_cast(0); + data += static_cast(0); + data += static_cast(IClipboard::kHTML); + data += static_cast(0); + data += static_cast(0); + data += static_cast(0); + data += static_cast(10); data += "html sucks"; clipboard.unmarshall(data, 0); @@ -358,27 +358,27 @@ TEST(ClipboardTests, unmarshall_withTextAndHtml_getHtmlIsValid) { Clipboard clipboard; String data; - data += (char)0; - data += (char)0; - data += (char)0; - data += (char)2; // 2 formats added - data += (char)0; - data += (char)0; - data += (char)0; - data += (char)IClipboard::kText; - data += (char)0; - data += (char)0; - data += (char)0; - data += (char)14; + data += static_cast(0); + data += static_cast(0); + data += static_cast(0); + data += static_cast(2); // 2 formats added + data += static_cast(0); + data += static_cast(0); + data += static_cast(0); + data += static_cast(IClipboard::kText); + data += static_cast(0); + data += static_cast(0); + data += static_cast(0); + data += static_cast(14); data += "synergy rocks!"; - data += (char)0; - data += (char)0; - data += (char)0; - data += (char)IClipboard::kHTML; - data += (char)0; - data += (char)0; - data += (char)0; - data += (char)10; + data += static_cast(0); + data += static_cast(0); + data += static_cast(0); + data += static_cast(IClipboard::kHTML); + data += static_cast(0); + data += static_cast(0); + data += static_cast(0); + data += static_cast(10); data += "html sucks"; clipboard.unmarshall(data, 0); diff --git a/src/test/unittests/synergy/DeprecatedArgsParsingTests.cpp b/src/test/unittests/synergy/DeprecatedArgsParsingTests.cpp index e7c549b7..63eea9b3 100644 --- a/src/test/unittests/synergy/DeprecatedArgsParsingTests.cpp +++ b/src/test/unittests/synergy/DeprecatedArgsParsingTests.cpp @@ -27,7 +27,7 @@ TEST(DeprecatedArgsParsingTests, parseDeprecatedArgs_cryptoPass_returnTrue) const int argc = 3; const char* kCryptoPassCmd[argc] = { "stub", "--crypto-pass", "mock_pass" }; - ArgParser argParser(NULL); + ArgParser argParser(nullptr); bool result = argParser.parseDeprecatedArgs(argc, kCryptoPassCmd, i); @@ -41,7 +41,7 @@ TEST(DeprecatedArgsParsingTests, parseDeprecatedArgs_cryptoPass_returnFalse) const int argc = 3; const char* kCryptoPassCmd[argc] = { "stub", "--mock-arg", "mock_value" }; - ArgParser argParser(NULL); + ArgParser argParser(nullptr); bool result = argParser.parseDeprecatedArgs(argc, kCryptoPassCmd, i); diff --git a/src/test/unittests/synergy/GenericArgsParsingTests.cpp b/src/test/unittests/synergy/GenericArgsParsingTests.cpp index f10dad52..066c3acb 100644 --- a/src/test/unittests/synergy/GenericArgsParsingTests.cpp +++ b/src/test/unittests/synergy/GenericArgsParsingTests.cpp @@ -22,7 +22,6 @@ #include "test/global/gtest.h" using namespace synergy; -using ::testing::_; using ::testing::Invoke; using ::testing::NiceMock; @@ -47,7 +46,7 @@ TEST(GenericArgsParsingTests, parseGenericArgs_logLevelCmd_setLogLevel) const int argc = 3; const char* kLogLevelCmd[argc] = { "stub", "--debug", "DEBUG" }; - ArgParser argParser(NULL); + ArgParser argParser(nullptr); ArgsBase argsBase; argParser.setArgsBase(argsBase); @@ -65,7 +64,7 @@ TEST(GenericArgsParsingTests, parseGenericArgs_logFileCmd_saveLogFilename) const int argc = 3; const char* kLogFileCmd[argc] = { "stub", "--log", "mock_filename" }; - ArgParser argParser(NULL); + ArgParser argParser(nullptr); ArgsBase argsBase; argParser.setArgsBase(argsBase); @@ -83,7 +82,7 @@ TEST(GenericArgsParsingTests, parseGenericArgs_logFileCmdWithSpace_saveLogFilena const int argc = 3; const char* kLogFileCmdWithSpace[argc] = { "stub", "--log", "mo ck_filename" }; - ArgParser argParser(NULL); + ArgParser argParser(nullptr); ArgsBase argsBase; argParser.setArgsBase(argsBase); @@ -101,7 +100,7 @@ TEST(GenericArgsParsingTests, parseGenericArgs_noDeamonCmd_daemonFalse) const int argc = 2; const char* kNoDeamonCmd[argc] = { "stub", "-f" }; - ArgParser argParser(NULL); + ArgParser argParser(nullptr); ArgsBase argsBase; argParser.setArgsBase(argsBase); @@ -117,7 +116,7 @@ TEST(GenericArgsParsingTests, parseGenericArgs_deamonCmd_daemonTrue) const int argc = 2; const char* kDeamonCmd[argc] = { "stub", "--daemon" }; - ArgParser argParser(NULL); + ArgParser argParser(nullptr); ArgsBase argsBase; argParser.setArgsBase(argsBase); @@ -133,7 +132,7 @@ TEST(GenericArgsParsingTests, parseGenericArgs_nameCmd_saveName) const int argc = 3; const char* kNameCmd[argc] = { "stub", "--name", "mock" }; - ArgParser argParser(NULL); + ArgParser argParser(nullptr); ArgsBase argsBase; argParser.setArgsBase(argsBase); @@ -149,7 +148,7 @@ TEST(GenericArgsParsingTests, parseGenericArgs_noRestartCmd_restartFalse) const int argc = 2; const char* kNoRestartCmd[argc] = { "stub", "--no-restart" }; - ArgParser argParser(NULL); + ArgParser argParser(nullptr); ArgsBase argsBase; argParser.setArgsBase(argsBase); @@ -165,7 +164,7 @@ TEST(GenericArgsParsingTests, parseGenericArgs_restartCmd_restartTrue) const int argc = 2; const char* kRestartCmd[argc] = { "stub", "--restart" }; - ArgParser argParser(NULL); + ArgParser argParser(nullptr); ArgsBase argsBase; argParser.setArgsBase(argsBase); @@ -181,7 +180,7 @@ TEST(GenericArgsParsingTests, parseGenericArgs_backendCmd_backendTrue) const int argc = 2; const char* kBackendCmd[argc] = { "stub", "-z" }; - ArgParser argParser(NULL); + ArgParser argParser(nullptr); ArgsBase argsBase; argParser.setArgsBase(argsBase); @@ -197,7 +196,7 @@ TEST(GenericArgsParsingTests, parseGenericArgs_noHookCmd_noHookTrue) const int argc = 2; const char* kNoHookCmd[argc] = { "stub", "--no-hooks" }; - ArgParser argParser(NULL); + ArgParser argParser(nullptr); ArgsBase argsBase; argParser.setArgsBase(argsBase); @@ -252,7 +251,7 @@ TEST(GenericArgsParsingTests, parseGenericArgs_noTrayCmd_disableTrayTrue) const int argc = 2; const char* kNoTrayCmd[argc] = { "stub", "--no-tray" }; - ArgParser argParser(NULL); + ArgParser argParser(nullptr); ArgsBase argsBase; argParser.setArgsBase(argsBase); @@ -267,7 +266,7 @@ TEST(GenericArgsParsingTests, parseGenericArgs_ipcCmd_enableIpcTrue) const int argc = 2; const char* kIpcCmd[argc] = { "stub", "--ipc" }; - ArgParser argParser(NULL); + ArgParser argParser(nullptr); ArgsBase argsBase; argParser.setArgsBase(argsBase); @@ -302,7 +301,7 @@ TEST(GenericArgsParsingTests, parseGenericArgs_dragDropCmdOnLinux_enableDragDrop const int argc = 2; const char* kDragDropCmd[argc] = { "stub", "--enable-drag-drop" }; - ArgParser argParser(NULL); + ArgParser argParser(nullptr); ArgsBase argsBase; argParser.setArgsBase(argsBase); diff --git a/src/test/unittests/synergy/KeyMapTests.cpp b/src/test/unittests/synergy/KeyMapTests.cpp index dca1fbd9..f08f6088 100644 --- a/src/test/unittests/synergy/KeyMapTests.cpp +++ b/src/test/unittests/synergy/KeyMapTests.cpp @@ -17,15 +17,9 @@ #include "core/KeyMap.h" -#include "test/global/gtest.h" #include "test/global/gmock.h" +#include "test/global/gtest.h" -using ::testing::_; -using ::testing::NiceMock; -using ::testing::Invoke; -using ::testing::Return; -using ::testing::ReturnRef; -using ::testing::SaveArg; namespace synergy { @@ -34,7 +28,7 @@ TEST(KeyMapTests, findBestKey_requiredDown_matchExactFirstItem) KeyMap keyMap; KeyMap::KeyEntryList entryList; KeyMap::KeyItemList itemList; - KeyMap::KeyItem item; + KeyMap::KeyItem item{}; item.m_required = KeyModifierShift; item.m_sensitive = KeyModifierShift; KeyModifierMask currentState = KeyModifierShift; @@ -50,7 +44,7 @@ TEST(KeyMapTests, findBestKey_requiredAndExtraSensitiveDown_matchExactFirstItem) KeyMap keyMap; KeyMap::KeyEntryList entryList; KeyMap::KeyItemList itemList; - KeyMap::KeyItem item; + KeyMap::KeyItem item{}; item.m_required = KeyModifierShift; item.m_sensitive = KeyModifierShift | KeyModifierAlt; KeyModifierMask currentState = KeyModifierShift; @@ -66,11 +60,11 @@ TEST(KeyMapTests, findBestKey_requiredAndExtraSensitiveDown_matchExactSecondItem KeyMap keyMap; KeyMap::KeyEntryList entryList; KeyMap::KeyItemList itemList1; - KeyMap::KeyItem item1; + KeyMap::KeyItem item1{}; item1.m_required = KeyModifierAlt; item1.m_sensitive = KeyModifierShift | KeyModifierAlt; KeyMap::KeyItemList itemList2; - KeyMap::KeyItem item2; + KeyMap::KeyItem item2{}; item2.m_required = KeyModifierShift; item2.m_sensitive = KeyModifierShift | KeyModifierAlt; KeyModifierMask currentState = KeyModifierShift; @@ -88,11 +82,11 @@ TEST(KeyMapTests, findBestKey_extraSensitiveDown_matchExactSecondItem) KeyMap keyMap; KeyMap::KeyEntryList entryList; KeyMap::KeyItemList itemList1; - KeyMap::KeyItem item1; + KeyMap::KeyItem item1{}; item1.m_required = 0; item1.m_sensitive = KeyModifierAlt; KeyMap::KeyItemList itemList2; - KeyMap::KeyItem item2; + KeyMap::KeyItem item2{}; item2.m_required = 0; item2.m_sensitive = KeyModifierShift; KeyModifierMask currentState = KeyModifierAlt; @@ -110,11 +104,11 @@ TEST(KeyMapTests, findBestKey_noRequiredDown_matchOneRequiredChangeItem) KeyMap keyMap; KeyMap::KeyEntryList entryList; KeyMap::KeyItemList itemList1; - KeyMap::KeyItem item1; + KeyMap::KeyItem item1{}; item1.m_required = KeyModifierShift | KeyModifierAlt; item1.m_sensitive = KeyModifierShift | KeyModifierAlt; KeyMap::KeyItemList itemList2; - KeyMap::KeyItem item2; + KeyMap::KeyItem item2{}; item2.m_required = KeyModifierShift; item2.m_sensitive = KeyModifierShift | KeyModifierAlt; KeyModifierMask currentState = 0; @@ -132,11 +126,11 @@ TEST(KeyMapTests, findBestKey_onlyOneRequiredDown_matchTwoRequiredChangesItem) KeyMap keyMap; KeyMap::KeyEntryList entryList; KeyMap::KeyItemList itemList1; - KeyMap::KeyItem item1; + KeyMap::KeyItem item1{}; item1.m_required = KeyModifierShift | KeyModifierAlt | KeyModifierControl; item1.m_sensitive = KeyModifierShift | KeyModifierAlt | KeyModifierControl; KeyMap::KeyItemList itemList2; - KeyMap::KeyItem item2; + KeyMap::KeyItem item2{}; item2.m_required = KeyModifierShift| KeyModifierAlt; item2.m_sensitive = KeyModifierShift | KeyModifierAlt | KeyModifierControl; KeyModifierMask currentState = 0; @@ -154,7 +148,7 @@ TEST(KeyMapTests, findBestKey_noRequiredDown_cannotMatch) KeyMap keyMap; KeyMap::KeyEntryList entryList; KeyMap::KeyItemList itemList; - KeyMap::KeyItem item; + KeyMap::KeyItem item{}; item.m_required = 0xffffffff; item.m_sensitive = 0xffffffff; KeyModifierMask currentState = 0; @@ -213,4 +207,4 @@ TEST(KeyMapTests, isCommand_superMask_returnTrue) EXPECT_EQ(true, keyMap.isCommand(mask)); } -} +} // namespace synergy diff --git a/src/test/unittests/synergy/KeyStateTests.cpp b/src/test/unittests/synergy/KeyStateTests.cpp index bbe3b79f..98fbdd33 100644 --- a/src/test/unittests/synergy/KeyStateTests.cpp +++ b/src/test/unittests/synergy/KeyStateTests.cpp @@ -20,15 +20,14 @@ #include "test/mock/synergy/MockEventQueue.h" #include "test/mock/synergy/MockKeyMap.h" -#include "test/global/gtest.h" #include "test/global/gmock.h" +#include "test/global/gtest.h" using ::testing::_; using ::testing::NiceMock; using ::testing::Invoke; using ::testing::Return; using ::testing::ReturnRef; -using ::testing::SaveArg; void stubPollPressedKeys(IKeyState::KeyButtonSet& pressedKeys); @@ -90,7 +89,7 @@ TEST(KeyStateTests, sendKeyEvent_halfDuplexAndRepeat_addEventNotCalled) EXPECT_CALL(eventQueue, addEvent(_)).Times(0); - keyState.sendKeyEvent(NULL, false, true, kKeyCapsLock, 0, 0, 0); + keyState.sendKeyEvent(nullptr, false, true, kKeyCapsLock, 0, 0, 0); } TEST(KeyStateTests, sendKeyEvent_halfDuplex_addEventCalledTwice) @@ -106,7 +105,7 @@ TEST(KeyStateTests, sendKeyEvent_halfDuplex_addEventCalledTwice) EXPECT_CALL(eventQueue, addEvent(_)).Times(2); - keyState.sendKeyEvent(NULL, false, false, kKeyCapsLock, 0, 0, 0); + keyState.sendKeyEvent(nullptr, false, false, kKeyCapsLock, 0, 0, 0); } TEST(KeyStateTests, sendKeyEvent_keyRepeat_addEventCalledOnce) @@ -121,7 +120,7 @@ TEST(KeyStateTests, sendKeyEvent_keyRepeat_addEventCalledOnce) EXPECT_CALL(eventQueue, addEvent(_)).Times(1); - keyState.sendKeyEvent(NULL, false, true, 1, 0, 0, 0); + keyState.sendKeyEvent(nullptr, false, true, 1, 0, 0, 0); } TEST(KeyStateTests, sendKeyEvent_keyDown_addEventCalledOnce) @@ -136,7 +135,7 @@ TEST(KeyStateTests, sendKeyEvent_keyDown_addEventCalledOnce) EXPECT_CALL(eventQueue, addEvent(_)).Times(1); - keyState.sendKeyEvent(NULL, true, false, 1, 0, 0, 0); + keyState.sendKeyEvent(nullptr, true, false, 1, 0, 0, 0); } TEST(KeyStateTests, sendKeyEvent_keyUp_addEventCalledOnce) @@ -151,7 +150,7 @@ TEST(KeyStateTests, sendKeyEvent_keyUp_addEventCalledOnce) EXPECT_CALL(eventQueue, addEvent(_)).Times(1); - keyState.sendKeyEvent(NULL, false, false, 1, 0, 0, 0); + keyState.sendKeyEvent(nullptr, false, false, 1, 0, 0, 0); } TEST(KeyStateTests, updateKeyMap_mockKeyMap_keyMapGotMock) @@ -324,14 +323,14 @@ TEST(KeyStateTests, fakeKeyRepeat_nullKey_returnsFalse) KeyStateImpl keyState(eventQueue, keyMap); // set the key to down (we need to make mapKey return a valid key to do this). - synergy::KeyMap::KeyItem keyItem; + synergy::KeyMap::KeyItem keyItem{}; keyItem.m_client = 0; keyItem.m_button = 1; ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _)).WillByDefault(Return(&keyItem)); keyState.fakeKeyDown(1, 0, 0); // change mapKey to return NULL so that fakeKeyRepeat exits early. - synergy::KeyMap::KeyItem* nullKeyItem = NULL; + synergy::KeyMap::KeyItem* nullKeyItem = nullptr; ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _)).WillByDefault(Return(nullKeyItem)); bool actual = keyState.fakeKeyRepeat(1, 0, 0, 0); @@ -346,7 +345,7 @@ TEST(KeyStateTests, fakeKeyRepeat_invalidButton_returnsFalse) KeyStateImpl keyState(eventQueue, keyMap); // set the key to down (we need to make mapKey return a valid key to do this). - synergy::KeyMap::KeyItem keyItem; + synergy::KeyMap::KeyItem keyItem{}; keyItem.m_client = 0; keyItem.m_button = 1; // set to 1 to make fakeKeyDown work. ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _)).WillByDefault(Return(&keyItem)); @@ -470,18 +469,18 @@ stubPollPressedKeys(IKeyState::KeyButtonSet& pressedKeys) } void -assertMaskIsOne(ForeachKeyCallback cb, void* userData) +assertMaskIsOne(ForeachKeyCallback /*cb*/, void* userData) { ASSERT_EQ(1, ((KeyState::AddActiveModifierContext*)userData)->m_mask); } const synergy::KeyMap::KeyItem* stubMapKey( - synergy::KeyMap::Keystrokes& keys, KeyID id, SInt32 group, - synergy::KeyMap::ModifierToKeys& activeModifiers, - KeyModifierMask& currentState, - KeyModifierMask desiredMask, - bool isAutoRepeat) + synergy::KeyMap::Keystrokes& keys, KeyID /*id*/, SInt32 /*group*/, + synergy::KeyMap::ModifierToKeys& /*activeModifiers*/, + KeyModifierMask& /*currentState*/, + KeyModifierMask /*desiredMask*/, + bool /*isAutoRepeat*/) { keys.push_back(s_stubKeystroke); return &s_stubKeyItem; diff --git a/src/test/unittests/synergy/ServerArgsParsingTests.cpp b/src/test/unittests/synergy/ServerArgsParsingTests.cpp index 77a6ca0c..144c9b66 100644 --- a/src/test/unittests/synergy/ServerArgsParsingTests.cpp +++ b/src/test/unittests/synergy/ServerArgsParsingTests.cpp @@ -26,7 +26,7 @@ using ::testing::Invoke; using ::testing::NiceMock; bool -server_stubParseGenericArgs(int, const char* const*, int&) +server_stubParseGenericArgs(int /*unused*/, const char* const* /*unused*/, int& /*unused*/) { return false; }