Apply clang-tidy fixes

This commit is contained in:
Andrew Nelless 2017-11-26 16:42:00 +00:00
parent 5fbada9424
commit 75b2cd0b41
170 changed files with 2312 additions and 2405 deletions

View File

@ -17,17 +17,17 @@
*/ */
#include "core/ClientApp.h" #include "core/ClientApp.h"
#include "core/ServerApp.h"
#include "arch/Arch.h" #include "arch/Arch.h"
#include "base/Log.h"
#include "base/EventQueue.h" #include "base/EventQueue.h"
#include "base/Log.h"
#include "core/ServerApp.h"
#include <iostream> #include <iostream>
int int
main(int argc, char** argv) main(int argc, char** argv)
{ {
// TODO: use existing arg parse code // TODO(andrew): use existing arg parse code
bool server, client; bool server, client;
if (argc > 1) { if (argc > 1) {
server = std::string(argv[1]) == "--server"; server = std::string(argv[1]) == "--server";
@ -49,12 +49,12 @@ main(int argc, char** argv)
ServerApp app(&events); ServerApp app(&events);
return app.run(argc, argv); return app.run(argc, argv);
} }
else if (client) { if (client) {
ClientApp app(&events); ClientApp app(&events);
return app.run(argc, argv); return app.run(argc, argv);
} }
else { else {
// TODO: use common error code // TODO(andrew): use common error code
std::cerr << "error: use --client or --server args" << std::endl; std::cerr << "error: use --client or --server args" << std::endl;
return 1; return 1;
} }

View File

@ -18,8 +18,8 @@
#include "core/ClientApp.h" #include "core/ClientApp.h"
#include "arch/Arch.h" #include "arch/Arch.h"
#include "base/Log.h"
#include "base/EventQueue.h" #include "base/EventQueue.h"
#include "base/Log.h"
#include <iostream> #include <iostream>

View File

@ -18,8 +18,8 @@
#include "core/ServerApp.h" #include "core/ServerApp.h"
#include "arch/Arch.h" #include "arch/Arch.h"
#include "base/Log.h"
#include "base/EventQueue.h" #include "base/EventQueue.h"
#include "base/Log.h"
#include <iostream> #include <iostream>

View File

@ -22,7 +22,7 @@
// Arch // Arch
// //
Arch* Arch::s_instance = NULL; Arch* Arch::s_instance = nullptr;
Arch::Arch() Arch::Arch()
{ {

View File

@ -24,10 +24,11 @@
void void
ArchConsoleStd::writeConsole(ELevel level, const char* str) ArchConsoleStd::writeConsole(ELevel level, const char* str)
{ {
if ((level >= kFATAL) && (level <= kWARNING)) if ((level >= kFATAL) && (level <= kWARNING)) {
std::cerr << str << std::endl; std::cerr << str << std::endl;
else } else {
std::cout << str << std::endl; std::cout << str << std::endl;
}
std::cout.flush(); std::cout.flush();
} }

View File

@ -33,17 +33,17 @@ ArchDaemonNone::~ArchDaemonNone()
} }
void void
ArchDaemonNone::installDaemon(const char*, ArchDaemonNone::installDaemon(const char* /*name*/,
const char*, const char* /*description*/,
const char*, const char* /*pathname*/,
const char*, const char* /*commandLine*/,
const char*) const char* /*dependencies*/)
{ {
// do nothing // do nothing
} }
void void
ArchDaemonNone::uninstallDaemon(const char*) ArchDaemonNone::uninstallDaemon(const char* /*name*/)
{ {
// do nothing // do nothing
} }
@ -57,13 +57,13 @@ ArchDaemonNone::daemonize(const char* name, DaemonFunc func)
} }
bool bool
ArchDaemonNone::canInstallDaemon(const char*) ArchDaemonNone::canInstallDaemon(const char* /*name*/)
{ {
return false; return false;
} }
bool bool
ArchDaemonNone::isDaemonInstalled(const char*) ArchDaemonNone::isDaemonInstalled(const char* /*name*/)
{ {
return false; return false;
} }

View File

@ -21,10 +21,10 @@
#include "common/common.h" #include "common/common.h"
#include <climits> #include <climits>
#include <cstring>
#include <cstdlib> #include <cstdlib>
#include <cstring>
static ArchMutex s_mutex = NULL; static ArchMutex s_mutex = nullptr;
// //
// use C library non-reentrant multibyte conversion with mutex // use C library non-reentrant multibyte conversion with mutex
@ -32,9 +32,9 @@ static ArchMutex s_mutex = NULL;
IArchString::~IArchString() IArchString::~IArchString()
{ {
if (s_mutex != NULL) { if (s_mutex != nullptr) {
ARCH->closeMutex(s_mutex); ARCH->closeMutex(s_mutex);
s_mutex = NULL; s_mutex = nullptr;
} }
} }
@ -45,17 +45,17 @@ IArchString::convStringWCToMB(char* dst,
ptrdiff_t len = 0; ptrdiff_t len = 0;
bool dummyErrors; bool dummyErrors;
if (errors == NULL) { if (errors == nullptr) {
errors = &dummyErrors; errors = &dummyErrors;
} }
if (s_mutex == NULL) { if (s_mutex == nullptr) {
s_mutex = ARCH->newMutex(); s_mutex = ARCH->newMutex();
} }
ARCH->lockMutex(s_mutex); ARCH->lockMutex(s_mutex);
if (dst == NULL) { if (dst == nullptr) {
char dummy[MB_LEN_MAX]; char dummy[MB_LEN_MAX];
for (const wchar_t* scan = src; n > 0; ++scan, --n) { for (const wchar_t* scan = src; n > 0; ++scan, --n) {
ptrdiff_t mblen = wctomb(dummy, *scan); ptrdiff_t mblen = wctomb(dummy, *scan);
@ -102,17 +102,17 @@ IArchString::convStringMBToWC(wchar_t* dst,
wchar_t dummy; wchar_t dummy;
bool dummyErrors; bool dummyErrors;
if (errors == NULL) { if (errors == nullptr) {
errors = &dummyErrors; errors = &dummyErrors;
} }
if (s_mutex == NULL) { if (s_mutex == nullptr) {
s_mutex = ARCH->newMutex(); s_mutex = ARCH->newMutex();
} }
ARCH->lockMutex(s_mutex); ARCH->lockMutex(s_mutex);
if (dst == NULL) { if (dst == nullptr) {
for (const char* scan = src; n > 0; ) { for (const char* scan = src; n > 0; ) {
ptrdiff_t mblen = mbtowc(&dummy, scan, n); ptrdiff_t mblen = mbtowc(&dummy, scan, n);
switch (mblen) { switch (mblen) {
@ -155,7 +155,7 @@ IArchString::convStringMBToWC(wchar_t* dst,
case -2: case -2:
// incomplete character. convert to unknown character. // incomplete character. convert to unknown character.
*errors = true; *errors = true;
*dst = (wchar_t)0xfffd; *dst = static_cast<wchar_t>(0xfffd);
n = 0; n = 0;
break; break;
@ -163,13 +163,13 @@ IArchString::convStringMBToWC(wchar_t* dst,
// invalid character. count one unknown character and // invalid character. count one unknown character and
// start at the next byte. // start at the next byte.
*errors = true; *errors = true;
*dst = (wchar_t)0xfffd; *dst = static_cast<wchar_t>(0xfffd);
scan += 1; scan += 1;
n -= 1; n -= 1;
break; break;
case 0: case 0:
*dst = (wchar_t)0x0000; *dst = static_cast<wchar_t>(0x0000);
scan += 1; scan += 1;
n -= 1; n -= 1;
break; break;

View File

@ -18,6 +18,6 @@
#include "arch/unix/ArchConsoleUnix.h" #include "arch/unix/ArchConsoleUnix.h"
ArchConsoleUnix::ArchConsoleUnix() { } ArchConsoleUnix::ArchConsoleUnix() = default;
ArchConsoleUnix::~ArchConsoleUnix() { } ArchConsoleUnix::~ArchConsoleUnix() = default;

View File

@ -21,12 +21,12 @@
#include "arch/unix/XArchUnix.h" #include "arch/unix/XArchUnix.h"
#include "base/Log.h" #include "base/Log.h"
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <cstdlib> #include <cstdlib>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
// //
// ArchDaemonUnix // ArchDaemonUnix
@ -96,11 +96,12 @@ ArchDaemonUnix::daemonize(const char* name, DaemonFunc func)
#ifndef __APPLE__ #ifndef __APPLE__
// NB: don't run chdir on apple; causes strange behaviour. // NB: don't run chdir on apple; causes strange behaviour.
// chdir to root so we don't keep mounted filesystems points busy // 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("/"); int chdirErr = chdir("/");
if (chdirErr) if (chdirErr != 0) {
// NB: file logging actually isn't working at this point! // NB: file logging actually isn't working at this point!
LOG((CLOG_ERR "chdir error: %i", chdirErr)); LOG((CLOG_ERR "chdir error: %i", chdirErr));
}
#endif #endif
// mask off permissions for any but owner // 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 // attach file descriptors 0, 1, 2 to /dev/null so inadvertent use
// of standard I/O safely goes in the bit bucket. // of standard I/O safely goes in the bit bucket.
open("/dev/null", O_RDONLY); open("/dev/null", O_RDONLY | O_CLOEXEC);
open("/dev/null", O_RDWR); open("/dev/null", O_RDWR | O_CLOEXEC);
int dupErr = dup(1); int dupErr = dup(1);

View File

@ -18,11 +18,11 @@
#include "arch/unix/ArchFileUnix.h" #include "arch/unix/ArchFileUnix.h"
#include <stdio.h>
#include <unistd.h>
#include <pwd.h>
#include <sys/types.h>
#include <cstring> #include <cstring>
#include <pwd.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
// //
// ArchFileUnix // ArchFileUnix
@ -41,26 +41,26 @@ ArchFileUnix::~ArchFileUnix()
const char* const char*
ArchFileUnix::getBasename(const char* pathname) ArchFileUnix::getBasename(const char* pathname)
{ {
if (pathname == NULL) { if (pathname == nullptr) {
return NULL; return nullptr;
} }
const char* basename = strrchr(pathname, '/'); const char* basename = strrchr(pathname, '/');
if (basename != NULL) { if (basename != nullptr) {
return basename + 1; return basename + 1;
} }
else {
return pathname; return pathname;
}
} }
std::string std::string
ArchFileUnix::getUserDirectory() ArchFileUnix::getUserDirectory()
{ {
char* buffer = NULL; char* buffer = nullptr;
std::string dir; std::string dir;
#if HAVE_GETPWUID_R #if HAVE_GETPWUID_R
struct passwd pwent; struct passwd pwent{};
struct passwd* pwentp; struct passwd* pwentp;
#if defined(_SC_GETPW_R_SIZE_MAX) #if defined(_SC_GETPW_R_SIZE_MAX)
long size = sysconf(_SC_GETPW_R_SIZE_MAX); long size = sysconf(_SC_GETPW_R_SIZE_MAX);
@ -75,7 +75,7 @@ ArchFileUnix::getUserDirectory()
#else #else
struct passwd* pwentp = getpwuid(getuid()); struct passwd* pwentp = getpwuid(getuid());
#endif #endif
if (pwentp != NULL && pwentp->pw_dir != NULL) { if (pwentp != nullptr && pwentp->pw_dir != nullptr) {
dir = pwentp->pw_dir; dir = pwentp->pw_dir;
} }
delete[] buffer; delete[] buffer;
@ -143,7 +143,7 @@ ArchFileUnix::concatPath(const std::string& prefix,
std::string path; std::string path;
path.reserve(prefix.size() + 1 + suffix.size()); path.reserve(prefix.size() + 1 + suffix.size());
path += prefix; path += prefix;
if (path.size() == 0 || path[path.size() - 1] != '/') { if (path.empty() || path[path.size() - 1] != '/') {
path += '/'; path += '/';
} }
path += suffix; path += suffix;

View File

@ -18,11 +18,11 @@
#include "arch/unix/ArchInternetUnix.h" #include "arch/unix/ArchInternetUnix.h"
#include "arch/XArch.h" #include "arch/XArch.h"
#include "common/Version.h"
#include "base/Log.h" #include "base/Log.h"
#include "common/Version.h"
#include <sstream>
#include <curl/curl.h> #include <curl/curl.h>
#include <sstream>
class CurlFacade { class CurlFacade {
public: public:
@ -60,12 +60,12 @@ ArchInternetUnix::urlEncode(const String& url)
static size_t static size_t
curlWriteCallback(void *contents, size_t size, size_t nmemb, void *userp) curlWriteCallback(void *contents, size_t size, size_t nmemb, void *userp)
{ {
((std::string*)userp)->append((char*)contents, size * nmemb); (static_cast<std::string*>(userp))->append(static_cast<char*>(contents), size * nmemb);
return size * nmemb; return size * nmemb;
} }
CurlFacade::CurlFacade() : CurlFacade::CurlFacade() :
m_curl(NULL) m_curl(nullptr)
{ {
CURLcode init = curl_global_init(CURL_GLOBAL_ALL); CURLcode init = curl_global_init(CURL_GLOBAL_ALL);
if (init != CURLE_OK) { if (init != CURLE_OK) {
@ -73,14 +73,14 @@ CurlFacade::CurlFacade() :
} }
m_curl = curl_easy_init(); m_curl = curl_easy_init();
if (m_curl == NULL) { if (m_curl == nullptr) {
throw XArch("CURL easy init failed."); throw XArch("CURL easy init failed.");
} }
} }
CurlFacade::~CurlFacade() CurlFacade::~CurlFacade()
{ {
if (m_curl != NULL) { if (m_curl != nullptr) {
curl_easy_cleanup(m_curl); 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); char* resultCStr = curl_easy_escape(m_curl, url.c_str(), 0);
if (resultCStr == NULL) { if (resultCStr == nullptr) {
throw XArch("CURL escape failed."); throw XArch("CURL escape failed.");
} }

View File

@ -47,7 +47,7 @@ ArchLogUnix::closeLog()
} }
void void
ArchLogUnix::showLog(bool) ArchLogUnix::showLog(bool /*showIfEmpty*/)
{ {
// do nothing // do nothing
} }

View File

@ -21,10 +21,10 @@
#include "arch/Arch.h" #include "arch/Arch.h"
#include "arch/XArch.h" #include "arch/XArch.h"
#include <signal.h> #include <csignal>
#if TIME_WITH_SYS_TIME #if TIME_WITH_SYS_TIME
# include <sys/time.h> # include <sys/time.h>
# include <time.h> # include <ctime>
#else #else
# if HAVE_SYS_TIME_H # if HAVE_SYS_TIME_H
# include <sys/time.h> # include <sys/time.h>
@ -67,28 +67,23 @@ public:
ArchThreadImpl(); ArchThreadImpl();
public: public:
int m_refCount; int m_refCount{1};
IArchMultithread::ThreadID m_id; IArchMultithread::ThreadID m_id{0};
pthread_t m_thread; pthread_t m_thread{};
IArchMultithread::ThreadFunc m_func; IArchMultithread::ThreadFunc m_func;
void* m_userData; void* m_userData;
bool m_cancel; bool m_cancel{false};
bool m_cancelling; bool m_cancelling{false};
bool m_exited; bool m_exited{false};
void* m_result; void* m_result;
void* m_networkData; void* m_networkData;
}; };
ArchThreadImpl::ArchThreadImpl() : ArchThreadImpl::ArchThreadImpl() :
m_refCount(1), m_func(nullptr),
m_id(0), m_userData(nullptr),
m_func(NULL), m_result(nullptr),
m_userData(NULL), m_networkData(nullptr)
m_cancel(false),
m_cancelling(false),
m_exited(false),
m_result(NULL),
m_networkData(NULL)
{ {
// do nothing // do nothing
} }
@ -98,7 +93,7 @@ ArchThreadImpl::ArchThreadImpl() :
// ArchMultithreadPosix // ArchMultithreadPosix
// //
ArchMultithreadPosix* ArchMultithreadPosix::s_instance = NULL; ArchMultithreadPosix* ArchMultithreadPosix::s_instance = nullptr;
ArchMultithreadPosix::ArchMultithreadPosix() : ArchMultithreadPosix::ArchMultithreadPosix() :
m_newThreadCalled(false), m_newThreadCalled(false),
@ -110,8 +105,8 @@ ArchMultithreadPosix::ArchMultithreadPosix() :
// no signal handlers // no signal handlers
for (size_t i = 0; i < kNUM_SIGNALS; ++i) { for (size_t i = 0; i < kNUM_SIGNALS; ++i) {
m_signalFunc[i] = NULL; m_signalFunc[i] = nullptr;
m_signalUserData[i] = NULL; m_signalUserData[i] = nullptr;
} }
// create mutex for thread list // create mutex for thread list
@ -128,7 +123,7 @@ ArchMultithreadPosix::ArchMultithreadPosix() :
// to wake up immediately if it's blocked in a system call. we // 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 // won't need this until another thread is created but it's fine
// to install it now. // to install it now.
struct sigaction act; struct sigaction act{};
sigemptyset(&act.sa_mask); sigemptyset(&act.sa_mask);
# if defined(SA_INTERRUPT) # if defined(SA_INTERRUPT)
act.sa_flags = SA_INTERRUPT; act.sa_flags = SA_INTERRUPT;
@ -136,17 +131,17 @@ ArchMultithreadPosix::ArchMultithreadPosix() :
act.sa_flags = 0; act.sa_flags = 0;
# endif # endif
act.sa_handler = &threadCancel; act.sa_handler = &threadCancel;
sigaction(SIGWAKEUP, &act, NULL); sigaction(SIGWAKEUP, &act, nullptr);
// set desired signal dispositions. let SIGWAKEUP through but // set desired signal dispositions. let SIGWAKEUP through but
// ignore SIGPIPE (we'll handle EPIPE). // ignore SIGPIPE (we'll handle EPIPE).
sigset_t sigset; sigset_t sigset{};
sigemptyset(&sigset); sigemptyset(&sigset);
sigaddset(&sigset, SIGWAKEUP); sigaddset(&sigset, SIGWAKEUP);
pthread_sigmask(SIG_UNBLOCK, &sigset, NULL); pthread_sigmask(SIG_UNBLOCK, &sigset, nullptr);
sigemptyset(&sigset); sigemptyset(&sigset);
sigaddset(&sigset, SIGPIPE); sigaddset(&sigset, SIGPIPE);
pthread_sigmask(SIG_BLOCK, &sigset, NULL); pthread_sigmask(SIG_BLOCK, &sigset, nullptr);
} }
ArchMultithreadPosix::~ArchMultithreadPosix() ArchMultithreadPosix::~ArchMultithreadPosix()
@ -154,7 +149,7 @@ ArchMultithreadPosix::~ArchMultithreadPosix()
assert(s_instance != NULL); assert(s_instance != NULL);
closeMutex(m_threadMutex); closeMutex(m_threadMutex);
s_instance = NULL; s_instance = nullptr;
} }
void void
@ -184,8 +179,8 @@ ArchMultithreadPosix::getInstance()
ArchCond ArchCond
ArchMultithreadPosix::newCondVar() ArchMultithreadPosix::newCondVar()
{ {
ArchCondImpl* cond = new ArchCondImpl; auto* cond = new ArchCondImpl;
int status = pthread_cond_init(&cond->m_cond, NULL); int status = pthread_cond_init(&cond->m_cond, nullptr);
(void)status; (void)status;
assert(status == 0); assert(status == 0);
return cond; return cond;
@ -237,13 +232,13 @@ ArchMultithreadPosix::waitCondVar(ArchCond cond,
testCancelThread(); testCancelThread();
// get final time // get final time
struct timeval now; struct timeval now{};
gettimeofday(&now, NULL); gettimeofday(&now, nullptr);
struct timespec finalTime; struct timespec finalTime{};
finalTime.tv_sec = now.tv_sec; finalTime.tv_sec = now.tv_sec;
finalTime.tv_nsec = now.tv_usec * 1000; finalTime.tv_nsec = now.tv_usec * 1000;
long timeout_sec = (long)timeout; auto timeout_sec = static_cast<long>(timeout);
long timeout_nsec = (long)(1.0e+9 * (timeout - timeout_sec)); auto timeout_nsec = static_cast<long>(1.0e+9 * (timeout - timeout_sec));
finalTime.tv_sec += timeout_sec; finalTime.tv_sec += timeout_sec;
finalTime.tv_nsec += timeout_nsec; finalTime.tv_nsec += timeout_nsec;
if (finalTime.tv_nsec >= 1000000000) { if (finalTime.tv_nsec >= 1000000000) {
@ -275,10 +270,10 @@ ArchMultithreadPosix::waitCondVar(ArchCond cond,
ArchMutex ArchMutex
ArchMultithreadPosix::newMutex() ArchMultithreadPosix::newMutex()
{ {
pthread_mutexattr_t attr; pthread_mutexattr_t attr{};
int status = pthread_mutexattr_init(&attr); int status = pthread_mutexattr_init(&attr);
assert(status == 0); assert(status == 0);
ArchMutexImpl* mutex = new ArchMutexImpl; auto* mutex = new ArchMutexImpl;
status = pthread_mutex_init(&mutex->m_mutex, &attr); status = pthread_mutex_init(&mutex->m_mutex, &attr);
assert(status == 0); assert(status == 0);
return mutex; return mutex;
@ -359,13 +354,13 @@ ArchMultithreadPosix::newThread(ThreadFunc func, void* data)
lockMutex(m_threadMutex); lockMutex(m_threadMutex);
// create thread impl for new thread // create thread impl for new thread
ArchThreadImpl* thread = new ArchThreadImpl; auto* thread = new ArchThreadImpl;
thread->m_func = func; thread->m_func = func;
thread->m_userData = data; thread->m_userData = data;
// create the thread. pthread_create() on RedHat 7.2 smp fails // create the thread. pthread_create() on RedHat 7.2 smp fails
// if passed a NULL attr so use a default attr. // if passed a NULL attr so use a default attr.
pthread_attr_t attr; pthread_attr_t attr{};
int status = pthread_attr_init(&attr); int status = pthread_attr_init(&attr);
if (status == 0) { if (status == 0) {
status = pthread_create(&thread->m_thread, &attr, status = pthread_create(&thread->m_thread, &attr,
@ -377,7 +372,7 @@ ArchMultithreadPosix::newThread(ThreadFunc func, void* data)
if (status != 0) { if (status != 0) {
// failed to start thread so clean up // failed to start thread so clean up
delete thread; delete thread;
thread = NULL; thread = nullptr;
} }
else { else {
// add thread to list // add thread to list
@ -411,7 +406,7 @@ ArchMultithreadPosix::closeThread(ArchThread thread)
// decrement ref count and clean up thread if no more references // decrement ref count and clean up thread if no more references
if (--thread->m_refCount == 0) { if (--thread->m_refCount == 0) {
// detach from thread (unless it's the main thread) // detach from thread (unless it's the main thread)
if (thread->m_func != NULL) { if (thread->m_func != nullptr) {
pthread_detach(thread->m_thread); pthread_detach(thread->m_thread);
} }
@ -454,7 +449,7 @@ ArchMultithreadPosix::cancelThread(ArchThread thread)
} }
void void
ArchMultithreadPosix::setPriorityOfThread(ArchThread thread, int /*n*/) ArchMultithreadPosix::setPriorityOfThread(ArchThread /*thread*/, int /*n*/)
{ {
assert(thread != NULL); assert(thread != NULL);
@ -573,7 +568,7 @@ void
ArchMultithreadPosix::raiseSignal(ESignal signal) ArchMultithreadPosix::raiseSignal(ESignal signal)
{ {
lockMutex(m_threadMutex); lockMutex(m_threadMutex);
if (m_signalFunc[signal] != NULL) { if (m_signalFunc[signal] != nullptr) {
m_signalFunc[signal](signal, m_signalUserData[signal]); m_signalFunc[signal](signal, m_signalUserData[signal]);
pthread_kill(m_mainThread->m_thread, SIGWAKEUP); pthread_kill(m_mainThread->m_thread, SIGWAKEUP);
} }
@ -588,7 +583,7 @@ ArchMultithreadPosix::startSignalHandler()
{ {
// set signal mask. the main thread blocks these signals and // set signal mask. the main thread blocks these signals and
// the signal handler thread will listen for them. // the signal handler thread will listen for them.
sigset_t sigset, oldsigset; sigset_t sigset{}, oldsigset{};
setSignalSet(&sigset); setSignalSet(&sigset);
pthread_sigmask(SIG_BLOCK, &sigset, &oldsigset); pthread_sigmask(SIG_BLOCK, &sigset, &oldsigset);
@ -596,18 +591,18 @@ ArchMultithreadPosix::startSignalHandler()
// instead arrange to catch and handle these signals but // instead arrange to catch and handle these signals but
// we'd be unable to cancel the main thread since no pthread // we'd be unable to cancel the main thread since no pthread
// calls are allowed in a signal handler. // calls are allowed in a signal handler.
pthread_attr_t attr; pthread_attr_t attr{};
int status = pthread_attr_init(&attr); int status = pthread_attr_init(&attr);
if (status == 0) { if (status == 0) {
status = pthread_create(&m_signalThread, &attr, status = pthread_create(&m_signalThread, &attr,
&ArchMultithreadPosix::threadSignalHandler, &ArchMultithreadPosix::threadSignalHandler,
NULL); nullptr);
pthread_attr_destroy(&attr); pthread_attr_destroy(&attr);
} }
if (status != 0) { if (status != 0) {
// can't create thread to wait for signal so don't block // can't create thread to wait for signal so don't block
// the signals. // the signals.
pthread_sigmask(SIG_UNBLOCK, &oldsigset, NULL); pthread_sigmask(SIG_UNBLOCK, &oldsigset, nullptr);
} }
} }
@ -615,7 +610,7 @@ ArchThreadImpl*
ArchMultithreadPosix::find(pthread_t thread) ArchMultithreadPosix::find(pthread_t thread)
{ {
ArchThreadImpl* impl = findNoRef(thread); ArchThreadImpl* impl = findNoRef(thread);
if (impl != NULL) { if (impl != nullptr) {
refThread(impl); refThread(impl);
} }
return impl; return impl;
@ -631,7 +626,7 @@ ArchMultithreadPosix::findNoRef(pthread_t thread)
return *index; return *index;
} }
} }
return NULL; return nullptr;
} }
void void
@ -655,7 +650,7 @@ ArchMultithreadPosix::insert(ArchThreadImpl* thread)
void void
ArchMultithreadPosix::erase(ArchThreadImpl* thread) ArchMultithreadPosix::erase(ArchThreadImpl* thread)
{ {
for (ThreadList::iterator index = m_threadList.begin(); for (auto index = m_threadList.begin();
index != m_threadList.end(); ++index) { index != m_threadList.end(); ++index) {
if (*index == thread) { if (*index == thread) {
m_threadList.erase(index); m_threadList.erase(index);
@ -697,17 +692,17 @@ void*
ArchMultithreadPosix::threadFunc(void* vrep) ArchMultithreadPosix::threadFunc(void* vrep)
{ {
// get the thread // get the thread
ArchThreadImpl* thread = static_cast<ArchThreadImpl*>(vrep); auto* thread = static_cast<ArchThreadImpl*>(vrep);
// setup pthreads // setup pthreads
pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, NULL); pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, nullptr);
pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL); pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, nullptr);
// run thread // run thread
s_instance->doThreadFunc(thread); s_instance->doThreadFunc(thread);
// terminate the thread // terminate the thread
return NULL; return nullptr;
} }
void void
@ -720,7 +715,7 @@ ArchMultithreadPosix::doThreadFunc(ArchThread thread)
lockMutex(m_threadMutex); lockMutex(m_threadMutex);
unlockMutex(m_threadMutex); unlockMutex(m_threadMutex);
void* result = NULL; void* result = nullptr;
try { try {
// go // go
result = (*thread->m_func)(thread->m_userData); result = (*thread->m_func)(thread->m_userData);
@ -749,19 +744,19 @@ ArchMultithreadPosix::doThreadFunc(ArchThread thread)
} }
void void
ArchMultithreadPosix::threadCancel(int) ArchMultithreadPosix::threadCancel(int /*unused*/)
{ {
// do nothing // do nothing
} }
void* void*
ArchMultithreadPosix::threadSignalHandler(void*) ArchMultithreadPosix::threadSignalHandler(void* /*unused*/)
{ {
// detach // detach
pthread_detach(pthread_self()); pthread_detach(pthread_self());
// add signal to mask // add signal to mask
sigset_t sigset; sigset_t sigset{};
setSignalSet(&sigset); setSignalSet(&sigset);
// also wait on SIGABRT. on linux (others?) this thread (process) // also wait on SIGABRT. on linux (others?) this thread (process)
@ -808,5 +803,5 @@ ArchMultithreadPosix::threadSignalHandler(void*)
} }
} }
return NULL; return nullptr;
} }

View File

@ -89,8 +89,8 @@ private:
void insert(ArchThreadImpl* thread); void insert(ArchThreadImpl* thread);
void erase(ArchThreadImpl* thread); void erase(ArchThreadImpl* thread);
void refThread(ArchThreadImpl* rep); void refThread(ArchThreadImpl* thread);
void testCancelThreadImpl(ArchThreadImpl* rep); void testCancelThreadImpl(ArchThreadImpl* thread);
void doThreadFunc(ArchThread thread); void doThreadFunc(ArchThread thread);
static void* threadFunc(void* vrep); static void* threadFunc(void* vrep);
@ -109,7 +109,7 @@ private:
ThreadList m_threadList; ThreadList m_threadList;
ThreadID m_nextID; ThreadID m_nextID;
pthread_t m_signalThread; pthread_t m_signalThread{};
SignalFunc m_signalFunc[kNUM_SIGNALS]; SignalFunc m_signalFunc[kNUM_SIGNALS]{};
void* m_signalUserData[kNUM_SIGNALS]; void* m_signalUserData[kNUM_SIGNALS]{};
}; };

View File

@ -18,22 +18,22 @@
#include "arch/unix/ArchNetworkBSD.h" #include "arch/unix/ArchNetworkBSD.h"
#include "arch/Arch.h"
#include "arch/unix/ArchMultithreadPosix.h" #include "arch/unix/ArchMultithreadPosix.h"
#include "arch/unix/XArchUnix.h" #include "arch/unix/XArchUnix.h"
#include "arch/Arch.h"
#if HAVE_UNISTD_H #if HAVE_UNISTD_H
# include <unistd.h> # include <unistd.h>
#endif #endif
#include <netinet/in.h>
#include <netdb.h> #include <netdb.h>
#include <netinet/in.h>
#if !defined(TCP_NODELAY) #if !defined(TCP_NODELAY)
# include <netinet/tcp.h> # include <netinet/tcp.h>
#endif #endif
#include <arpa/inet.h> #include <arpa/inet.h>
#include <fcntl.h>
#include <errno.h> #include <errno.h>
#include <string.h> #include <fcntl.h>
#include <cstring>
#if HAVE_POLL #if HAVE_POLL
# include <poll.h> # include <poll.h>
@ -87,8 +87,7 @@ inet_aton(const char* cp, struct in_addr* inp)
// //
ArchNetworkBSD::ArchNetworkBSD() ArchNetworkBSD::ArchNetworkBSD()
{ = default;
}
ArchNetworkBSD::~ArchNetworkBSD() ArchNetworkBSD::~ArchNetworkBSD()
{ {
@ -119,7 +118,7 @@ ArchNetworkBSD::newSocket(EAddressFamily family, ESocketType type)
} }
// allocate socket object // allocate socket object
ArchSocketImpl* newSocket = new ArchSocketImpl; auto* newSocket = new ArchSocketImpl;
newSocket->m_fd = fd; newSocket->m_fd = fd;
newSocket->m_refCount = 1; newSocket->m_refCount = 1;
return newSocket; return newSocket;
@ -214,25 +213,25 @@ ArchNetworkBSD::acceptSocket(ArchSocket s, ArchNetAddress* addr)
// if user passed NULL in addr then use scratch space // if user passed NULL in addr then use scratch space
ArchNetAddress dummy; ArchNetAddress dummy;
if (addr == NULL) { if (addr == nullptr) {
addr = &dummy; addr = &dummy;
} }
// create new socket and address // create new socket and address
ArchSocketImpl* newSocket = new ArchSocketImpl; auto* newSocket = new ArchSocketImpl;
*addr = new ArchNetAddressImpl; *addr = new ArchNetAddressImpl;
// accept on socket // 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); int fd = accept(s->m_fd, &(*addr)->m_addr, &len);
(*addr)->m_len = (socklen_t)len; (*addr)->m_len = len;
if (fd == -1) { if (fd == -1) {
int err = errno; int err = errno;
delete newSocket; delete newSocket;
delete *addr; delete *addr;
*addr = NULL; *addr = nullptr;
if (err == EAGAIN) { if (err == EAGAIN) {
return NULL; return nullptr;
} }
throwError(err); throwError(err);
} }
@ -244,7 +243,7 @@ ArchNetworkBSD::acceptSocket(ArchSocket s, ArchNetAddress* addr)
close(fd); close(fd);
delete newSocket; delete newSocket;
delete *addr; delete *addr;
*addr = NULL; *addr = nullptr;
throw; throw;
} }
@ -294,11 +293,11 @@ ArchNetworkBSD::pollSocket(PollEntry pe[], int num, double timeout)
} }
// allocate space for translated query // allocate space for translated query
struct pollfd* pfd = new struct pollfd[1 + num]; auto* pfd = new struct pollfd[1 + num];
// translate query // translate query
for (int i = 0; i < num; ++i) { 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; pfd[i].events = 0;
if ((pe[i].m_events & kPOLLIN) != 0) { if ((pe[i].m_events & kPOLLIN) != 0) {
pfd[i].events |= POLLIN; pfd[i].events |= POLLIN;
@ -311,7 +310,7 @@ ArchNetworkBSD::pollSocket(PollEntry pe[], int num, double timeout)
// add the unblock pipe // add the unblock pipe
const int* unblockPipe = getUnblockPipe(); const int* unblockPipe = getUnblockPipe();
if (unblockPipe != NULL) { if (unblockPipe != nullptr) {
pfd[n].fd = unblockPipe[0]; pfd[n].fd = unblockPipe[0];
pfd[n].events = POLLIN; pfd[n].events = POLLIN;
++n; ++n;
@ -324,7 +323,7 @@ ArchNetworkBSD::pollSocket(PollEntry pe[], int num, double timeout)
n = poll(pfd, n, t); n = poll(pfd, n, t);
// reset the unblock pipe // 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. // the unblock event was signalled. flush the pipe.
char dummy[100]; char dummy[100];
int ignore; int ignore;
@ -500,7 +499,7 @@ void
ArchNetworkBSD::unblockPollSocket(ArchThread thread) ArchNetworkBSD::unblockPollSocket(ArchThread thread)
{ {
const int* unblockPipe = getUnblockPipeForThread(thread); const int* unblockPipe = getUnblockPipeForThread(thread);
if (unblockPipe != NULL) { if (unblockPipe != nullptr) {
char dummy = 0; char dummy = 0;
int ignore; int ignore;
@ -545,9 +544,9 @@ ArchNetworkBSD::throwErrorOnSocket(ArchSocket s)
// get the error from the socket layer // get the error from the socket layer
int err = 0; int err = 0;
socklen_t size = (socklen_t)sizeof(err); auto size = static_cast<socklen_t>(sizeof(err));
if (getsockopt(s->m_fd, SOL_SOCKET, SO_ERROR, if (getsockopt(s->m_fd, SOL_SOCKET, SO_ERROR,
(optval_t*)&err, &size) == -1) { reinterpret_cast<optval_t*>(&err), &size) == -1) {
err = errno; err = errno;
} }
@ -584,16 +583,16 @@ ArchNetworkBSD::setNoDelayOnSocket(ArchSocket s, bool noDelay)
// get old state // get old state
int oflag; int oflag;
socklen_t size = (socklen_t)sizeof(oflag); auto size = static_cast<socklen_t>(sizeof(oflag));
if (getsockopt(s->m_fd, IPPROTO_TCP, TCP_NODELAY, if (getsockopt(s->m_fd, IPPROTO_TCP, TCP_NODELAY,
(optval_t*)&oflag, &size) == -1) { reinterpret_cast<optval_t*>(&oflag), &size) == -1) {
throwError(errno); throwError(errno);
} }
int flag = noDelay ? 1 : 0; int flag = noDelay ? 1 : 0;
size = (socklen_t)sizeof(flag); size = static_cast<socklen_t>(sizeof(flag));
if (setsockopt(s->m_fd, IPPROTO_TCP, TCP_NODELAY, if (setsockopt(s->m_fd, IPPROTO_TCP, TCP_NODELAY,
(optval_t*)&flag, size) == -1) { reinterpret_cast<optval_t*>(&flag), size) == -1) {
throwError(errno); throwError(errno);
} }
@ -607,16 +606,16 @@ ArchNetworkBSD::setReuseAddrOnSocket(ArchSocket s, bool reuse)
// get old state // get old state
int oflag; int oflag;
socklen_t size = (socklen_t)sizeof(oflag); auto size = static_cast<socklen_t>(sizeof(oflag));
if (getsockopt(s->m_fd, SOL_SOCKET, SO_REUSEADDR, if (getsockopt(s->m_fd, SOL_SOCKET, SO_REUSEADDR,
(optval_t*)&oflag, &size) == -1) { reinterpret_cast<optval_t*>(&oflag), &size) == -1) {
throwError(errno); throwError(errno);
} }
int flag = reuse ? 1 : 0; int flag = reuse ? 1 : 0;
size = (socklen_t)sizeof(flag); size = static_cast<socklen_t>(sizeof(flag));
if (setsockopt(s->m_fd, SOL_SOCKET, SO_REUSEADDR, if (setsockopt(s->m_fd, SOL_SOCKET, SO_REUSEADDR,
(optval_t*)&flag, size) == -1) { reinterpret_cast<optval_t*>(&flag), size) == -1) {
throwError(errno); throwError(errno);
} }
@ -640,17 +639,17 @@ ArchNetAddress
ArchNetworkBSD::newAnyAddr(EAddressFamily family) ArchNetworkBSD::newAnyAddr(EAddressFamily family)
{ {
// allocate address // allocate address
ArchNetAddressImpl* addr = new ArchNetAddressImpl; auto* addr = new ArchNetAddressImpl;
// fill it in // fill it in
switch (family) { switch (family) {
case kINET: { case kINET: {
struct sockaddr_in* ipAddr = auto* ipAddr =
reinterpret_cast<struct sockaddr_in*>(&addr->m_addr); reinterpret_cast<struct sockaddr_in*>(&addr->m_addr);
ipAddr->sin_family = AF_INET; ipAddr->sin_family = AF_INET;
ipAddr->sin_port = 0; ipAddr->sin_port = 0;
ipAddr->sin_addr.s_addr = INADDR_ANY; ipAddr->sin_addr.s_addr = INADDR_ANY;
addr->m_len = (socklen_t)sizeof(struct sockaddr_in); addr->m_len = static_cast<socklen_t>(sizeof(struct sockaddr_in));
break; break;
} }
@ -675,14 +674,14 @@ ArchNetAddress
ArchNetworkBSD::nameToAddr(const std::string& name) ArchNetworkBSD::nameToAddr(const std::string& name)
{ {
// allocate address // allocate address
ArchNetAddressImpl* addr = new ArchNetAddressImpl; auto* addr = new ArchNetAddressImpl;
// try to convert assuming an IPv4 dot notation address // try to convert assuming an IPv4 dot notation address
struct sockaddr_in inaddr; struct sockaddr_in inaddr{};
memset(&inaddr, 0, sizeof(inaddr)); memset(&inaddr, 0, sizeof(inaddr));
if (inet_aton(name.c_str(), &inaddr.sin_addr) != 0) { if (inet_aton(name.c_str(), &inaddr.sin_addr) != 0) {
// it's a dot notation address // it's a dot notation address
addr->m_len = (socklen_t)sizeof(struct sockaddr_in); addr->m_len = static_cast<socklen_t>(sizeof(struct sockaddr_in));
inaddr.sin_family = AF_INET; inaddr.sin_family = AF_INET;
inaddr.sin_port = 0; inaddr.sin_port = 0;
memcpy(&addr->m_addr, &inaddr, addr->m_len); memcpy(&addr->m_addr, &inaddr, addr->m_len);
@ -692,7 +691,7 @@ ArchNetworkBSD::nameToAddr(const std::string& name)
// mutexed address lookup (ugh) // mutexed address lookup (ugh)
ARCH->lockMutex(m_mutex); ARCH->lockMutex(m_mutex);
struct hostent* info = gethostbyname(name.c_str()); struct hostent* info = gethostbyname(name.c_str());
if (info == NULL) { if (info == nullptr) {
ARCH->unlockMutex(m_mutex); ARCH->unlockMutex(m_mutex);
delete addr; delete addr;
throwNameError(h_errno); throwNameError(h_errno);
@ -700,7 +699,7 @@ ArchNetworkBSD::nameToAddr(const std::string& name)
// copy over address (only IPv4 currently supported) // copy over address (only IPv4 currently supported)
if (info->h_addrtype == AF_INET) { if (info->h_addrtype == AF_INET) {
addr->m_len = (socklen_t)sizeof(struct sockaddr_in); addr->m_len = static_cast<socklen_t>(sizeof(struct sockaddr_in));
inaddr.sin_family = info->h_addrtype; inaddr.sin_family = info->h_addrtype;
inaddr.sin_port = 0; inaddr.sin_port = 0;
memcpy(&inaddr.sin_addr, info->h_addr_list[0], memcpy(&inaddr.sin_addr, info->h_addr_list[0],
@ -739,7 +738,7 @@ ArchNetworkBSD::addrToName(ArchNetAddress addr)
ARCH->lockMutex(m_mutex); ARCH->lockMutex(m_mutex);
struct hostent* info = gethostbyaddr(&addr->m_addr, struct hostent* info = gethostbyaddr(&addr->m_addr,
addr->m_len, addr->m_addr.sa_family); addr->m_len, addr->m_addr.sa_family);
if (info == NULL) { if (info == nullptr) {
ARCH->unlockMutex(m_mutex); ARCH->unlockMutex(m_mutex);
throwNameError(h_errno); throwNameError(h_errno);
} }
@ -760,7 +759,7 @@ ArchNetworkBSD::addrToString(ArchNetAddress addr)
switch (getAddrFamily(addr)) { switch (getAddrFamily(addr)) {
case kINET: { case kINET: {
struct sockaddr_in* ipAddr = auto* ipAddr =
reinterpret_cast<struct sockaddr_in*>(&addr->m_addr); reinterpret_cast<struct sockaddr_in*>(&addr->m_addr);
ARCH->lockMutex(m_mutex); ARCH->lockMutex(m_mutex);
std::string s = inet_ntoa(ipAddr->sin_addr); std::string s = inet_ntoa(ipAddr->sin_addr);
@ -795,7 +794,7 @@ ArchNetworkBSD::setAddrPort(ArchNetAddress addr, int port)
switch (getAddrFamily(addr)) { switch (getAddrFamily(addr)) {
case kINET: { case kINET: {
struct sockaddr_in* ipAddr = auto* ipAddr =
reinterpret_cast<struct sockaddr_in*>(&addr->m_addr); reinterpret_cast<struct sockaddr_in*>(&addr->m_addr);
ipAddr->sin_port = htons(port); ipAddr->sin_port = htons(port);
break; break;
@ -814,7 +813,7 @@ ArchNetworkBSD::getAddrPort(ArchNetAddress addr)
switch (getAddrFamily(addr)) { switch (getAddrFamily(addr)) {
case kINET: { case kINET: {
struct sockaddr_in* ipAddr = auto* ipAddr =
reinterpret_cast<struct sockaddr_in*>(&addr->m_addr); reinterpret_cast<struct sockaddr_in*>(&addr->m_addr);
return ntohs(ipAddr->sin_port); return ntohs(ipAddr->sin_port);
} }
@ -832,10 +831,10 @@ ArchNetworkBSD::isAnyAddr(ArchNetAddress addr)
switch (getAddrFamily(addr)) { switch (getAddrFamily(addr)) {
case kINET: { case kINET: {
struct sockaddr_in* ipAddr = auto* ipAddr =
reinterpret_cast<struct sockaddr_in*>(&addr->m_addr); reinterpret_cast<struct sockaddr_in*>(&addr->m_addr);
return (ipAddr->sin_addr.s_addr == INADDR_ANY && return (ipAddr->sin_addr.s_addr == INADDR_ANY &&
addr->m_len == (socklen_t)sizeof(struct sockaddr_in)); addr->m_len == static_cast<socklen_t>(sizeof(struct sockaddr_in)));
} }
default: default:
@ -865,8 +864,8 @@ const int*
ArchNetworkBSD::getUnblockPipeForThread(ArchThread thread) ArchNetworkBSD::getUnblockPipeForThread(ArchThread thread)
{ {
ArchMultithreadPosix* mt = ArchMultithreadPosix::getInstance(); ArchMultithreadPosix* mt = ArchMultithreadPosix::getInstance();
int* unblockPipe = (int*)mt->getNetworkDataForThread(thread); auto* unblockPipe = static_cast<int*>(mt->getNetworkDataForThread(thread));
if (unblockPipe == NULL) { if (unblockPipe == nullptr) {
unblockPipe = new int[2]; unblockPipe = new int[2];
if (pipe(unblockPipe) != -1) { if (pipe(unblockPipe) != -1) {
try { try {
@ -875,12 +874,12 @@ ArchNetworkBSD::getUnblockPipeForThread(ArchThread thread)
} }
catch (...) { catch (...) {
delete[] unblockPipe; delete[] unblockPipe;
unblockPipe = NULL; unblockPipe = nullptr;
} }
} }
else { else {
delete[] unblockPipe; delete[] unblockPipe;
unblockPipe = NULL; unblockPipe = nullptr;
} }
} }
return unblockPipe; return unblockPipe;

View File

@ -70,7 +70,7 @@ public:
virtual void bindSocket(ArchSocket s, ArchNetAddress addr); virtual void bindSocket(ArchSocket s, ArchNetAddress addr);
virtual void listenOnSocket(ArchSocket s); virtual void listenOnSocket(ArchSocket s);
virtual ArchSocket acceptSocket(ArchSocket s, ArchNetAddress* addr); 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 int pollSocket(PollEntry[], int num, double timeout);
virtual void unblockPollSocket(ArchThread thread); virtual void unblockPollSocket(ArchThread thread);
virtual size_t readSocket(ArchSocket s, void* buf, size_t len); virtual size_t readSocket(ArchSocket s, void* buf, size_t len);
@ -100,5 +100,5 @@ private:
void throwNameError(int); void throwNameError(int);
private: private:
ArchMutex m_mutex; ArchMutex m_mutex{};
}; };

View File

@ -22,7 +22,7 @@
#if TIME_WITH_SYS_TIME #if TIME_WITH_SYS_TIME
# include <sys/time.h> # include <sys/time.h>
# include <time.h> # include <ctime>
#else #else
# if HAVE_SYS_TIME_H # if HAVE_SYS_TIME_H
# include <sys/time.h> # include <sys/time.h>
@ -66,13 +66,14 @@ ArchSleepUnix::sleep(double timeout)
#if HAVE_NANOSLEEP #if HAVE_NANOSLEEP
// prep timeout // prep timeout
struct timespec t; struct timespec t{};
t.tv_sec = (long)timeout; t.tv_sec = static_cast<long>(timeout);
t.tv_nsec = (long)(1.0e+9 * (timeout - (double)t.tv_sec)); t.tv_nsec = static_cast<long>(1.0e+9 * (timeout - static_cast<double>(t.tv_sec)));
// wait // wait
while (nanosleep(&t, &t) < 0) while (nanosleep(&t, &t) < 0) {
ARCH->testCancelThread(); ARCH->testCancelThread();
}
#else #else
/* emulate nanosleep() with select() */ /* emulate nanosleep() with select() */
double startTime = ARCH->time(); double startTime = ARCH->time();

View File

@ -18,7 +18,7 @@
#include "arch/unix/ArchStringUnix.h" #include "arch/unix/ArchStringUnix.h"
#include <stdio.h> #include <cstdio>
// //
// ArchStringUnix // ArchStringUnix
@ -28,12 +28,10 @@
#include "arch/vsnprintf.h" #include "arch/vsnprintf.h"
ArchStringUnix::ArchStringUnix() ArchStringUnix::ArchStringUnix()
{ = default;
}
ArchStringUnix::~ArchStringUnix() ArchStringUnix::~ArchStringUnix()
{ = default;
}
IArchString::EWideCharEncoding IArchString::EWideCharEncoding
ArchStringUnix::getWideCharEncoding() ArchStringUnix::getWideCharEncoding()

View File

@ -38,7 +38,7 @@ std::string
ArchSystemUnix::getOSName() const ArchSystemUnix::getOSName() const
{ {
#if defined(HAVE_SYS_UTSNAME_H) #if defined(HAVE_SYS_UTSNAME_H)
struct utsname info; struct utsname info{};
if (uname(&info) == 0) { if (uname(&info) == 0) {
std::string msg; std::string msg;
msg += info.sysname; msg += info.sysname;
@ -54,7 +54,7 @@ std::string
ArchSystemUnix::getPlatformName() const ArchSystemUnix::getPlatformName() const
{ {
#if defined(HAVE_SYS_UTSNAME_H) #if defined(HAVE_SYS_UTSNAME_H)
struct utsname info; struct utsname info{};
if (uname(&info) == 0) { if (uname(&info) == 0) {
return std::string(info.machine); return std::string(info.machine);
} }
@ -63,18 +63,18 @@ ArchSystemUnix::getPlatformName() const
} }
std::string std::string
ArchSystemUnix::setting(const std::string&) const ArchSystemUnix::setting(const std::string& /*valueName*/) const
{ {
return ""; return "";
} }
void void
ArchSystemUnix::setting(const std::string&, const std::string&) const ArchSystemUnix::setting(const std::string& /*valueName*/, const std::string& /*valueString*/) const
{ {
} }
std::string std::string
ArchSystemUnix::getLibsUsed(void) const ArchSystemUnix::getLibsUsed() const
{ {
return "not implemented.\nuse lsof on shell"; return "not implemented.\nuse lsof on shell";
} }

View File

@ -20,7 +20,7 @@
#if TIME_WITH_SYS_TIME #if TIME_WITH_SYS_TIME
# include <sys/time.h> # include <sys/time.h>
# include <time.h> # include <ctime>
#else #else
# if HAVE_SYS_TIME_H # if HAVE_SYS_TIME_H
# include <sys/time.h> # include <sys/time.h>
@ -46,7 +46,7 @@ ArchTimeUnix::~ArchTimeUnix()
double double
ArchTimeUnix::time() ArchTimeUnix::time()
{ {
struct timeval t; struct timeval t{};
gettimeofday(&t, NULL); gettimeofday(&t, nullptr);
return (double)t.tv_sec + 1.0e-6 * (double)t.tv_usec; return static_cast<double>(t.tv_sec) + 1.0e-6 * static_cast<double>(t.tv_usec);
} }

View File

@ -25,8 +25,8 @@
Event::Event() : Event::Event() :
m_type(kUnknown), m_type(kUnknown),
m_target(NULL), m_target(nullptr),
m_data(NULL), m_data(nullptr),
m_flags(0), m_flags(0),
m_dataObject(nullptr) m_dataObject(nullptr)
{ {

View File

@ -18,15 +18,15 @@
#include "base/EventQueue.h" #include "base/EventQueue.h"
#include "mt/Mutex.h"
#include "mt/Lock.h"
#include "arch/Arch.h" #include "arch/Arch.h"
#include "base/EventTypes.h"
#include "base/IEventJob.h"
#include "base/Log.h"
#include "base/SimpleEventQueueBuffer.h" #include "base/SimpleEventQueueBuffer.h"
#include "base/Stopwatch.h" #include "base/Stopwatch.h"
#include "base/IEventJob.h"
#include "base/EventTypes.h"
#include "base/Log.h"
#include "base/XBase.h" #include "base/XBase.h"
#include "mt/Lock.h"
#include "mt/Mutex.h"
EVENT_TYPE_ACCESSOR(Client) EVENT_TYPE_ACCESSOR(Client)
EVENT_TYPE_ACCESSOR(IStream) EVENT_TYPE_ACCESSOR(IStream)
@ -52,9 +52,9 @@ EVENT_TYPE_ACCESSOR(File)
// interrupt handler. this just adds a quit event to the queue. // interrupt handler. this just adds a quit event to the queue.
static static
void void
interrupt(Arch::ESignal, void* data) interrupt(Arch::ESignal /*unused*/, void* data)
{ {
EventQueue* events = static_cast<EventQueue*>(data); auto* events = static_cast<EventQueue*>(data);
events->addEvent(Event(Event::kQuit)); events->addEvent(Event(Event::kQuit));
} }
@ -66,26 +66,26 @@ interrupt(Arch::ESignal, void* data)
EventQueue::EventQueue() : EventQueue::EventQueue() :
m_systemTarget(0), m_systemTarget(0),
m_nextType(Event::kLast), m_nextType(Event::kLast),
m_typesForClient(NULL), m_typesForClient(nullptr),
m_typesForIStream(NULL), m_typesForIStream(nullptr),
m_typesForIpcClient(NULL), m_typesForIpcClient(nullptr),
m_typesForIpcClientProxy(NULL), m_typesForIpcClientProxy(nullptr),
m_typesForIpcServer(NULL), m_typesForIpcServer(nullptr),
m_typesForIpcServerProxy(NULL), m_typesForIpcServerProxy(nullptr),
m_typesForIDataSocket(NULL), m_typesForIDataSocket(nullptr),
m_typesForIListenSocket(NULL), m_typesForIListenSocket(nullptr),
m_typesForISocket(NULL), m_typesForISocket(nullptr),
m_typesForOSXScreen(NULL), m_typesForOSXScreen(nullptr),
m_typesForClientListener(NULL), m_typesForClientListener(nullptr),
m_typesForClientProxy(NULL), m_typesForClientProxy(nullptr),
m_typesForClientProxyUnknown(NULL), m_typesForClientProxyUnknown(nullptr),
m_typesForServer(NULL), m_typesForServer(nullptr),
m_typesForServerApp(NULL), m_typesForServerApp(nullptr),
m_typesForIKeyState(NULL), m_typesForIKeyState(nullptr),
m_typesForIPrimaryScreen(NULL), m_typesForIPrimaryScreen(nullptr),
m_typesForIScreen(NULL), m_typesForIScreen(nullptr),
m_typesForClipboard(NULL), m_typesForClipboard(nullptr),
m_typesForFile(NULL), m_typesForFile(nullptr),
m_readyMutex(new Mutex), m_readyMutex(new Mutex),
m_readyCondVar(new CondVar<bool>(m_readyMutex, false)) m_readyCondVar(new CondVar<bool>(m_readyMutex, false))
{ {
@ -101,8 +101,8 @@ EventQueue::~EventQueue()
delete m_readyCondVar; delete m_readyCondVar;
delete m_readyMutex; delete m_readyMutex;
ARCH->setSignalHandler(Arch::kINTERRUPT, NULL, NULL); ARCH->setSignalHandler(Arch::kINTERRUPT, nullptr, nullptr);
ARCH->setSignalHandler(Arch::kTERMINATE, NULL, NULL); ARCH->setSignalHandler(Arch::kTERMINATE, nullptr, nullptr);
ARCH->closeMutex(m_mutex); ARCH->closeMutex(m_mutex);
} }
@ -166,9 +166,9 @@ EventQueue::getTypeName(Event::Type type)
if (i == m_typeMap.end()) { if (i == m_typeMap.end()) {
return "<unknown>"; return "<unknown>";
} }
else {
return i->second; return i->second;
}
} }
} }
@ -179,7 +179,7 @@ EventQueue::adoptBuffer(IEventQueueBuffer* buffer)
LOG((CLOG_DEBUG "adopting new 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 // this can come as a nasty surprise to programmers expecting
// their events to be raised, only to have them deleted. // their events to be raised, only to have them deleted.
LOG((CLOG_DEBUG "discarding %d event(s)", m_events.size())); LOG((CLOG_DEBUG "discarding %d event(s)", m_events.size()));
@ -187,15 +187,15 @@ EventQueue::adoptBuffer(IEventQueueBuffer* buffer)
// discard old buffer and old events // discard old buffer and old events
delete m_buffer; delete m_buffer;
for (EventTable::iterator i = m_events.begin(); i != m_events.end(); ++i) { for (auto & m_event : m_events) {
Event::deleteData(i->second); Event::deleteData(m_event.second);
} }
m_events.clear(); m_events.clear();
m_oldEventIDs.clear(); m_oldEventIDs.clear();
// use new buffer // use new buffer
m_buffer = buffer; m_buffer = buffer;
if (m_buffer == NULL) { if (m_buffer == nullptr) {
m_buffer = new SimpleEventQueueBuffer; m_buffer = new SimpleEventQueueBuffer;
} }
} }
@ -264,10 +264,10 @@ EventQueue::dispatchEvent(const Event& event)
{ {
void* target = event.getTarget(); void* target = event.getTarget();
IEventJob* job = getHandler(event.getType(), target); IEventJob* job = getHandler(event.getType(), target);
if (job == NULL) { if (job == nullptr) {
job = getHandler(Event::kUnknown, target); job = getHandler(Event::kUnknown, target);
} }
if (job != NULL) { if (job != nullptr) {
job->run(event); job->run(event);
return true; return true;
} }
@ -322,7 +322,7 @@ EventQueue::newTimer(double duration, void* target)
assert(duration > 0.0); assert(duration > 0.0);
EventQueueTimer* timer = m_buffer->newTimer(duration, false); EventQueueTimer* timer = m_buffer->newTimer(duration, false);
if (target == NULL) { if (target == nullptr) {
target = timer; target = timer;
} }
ArchMutexLock lock(m_mutex); ArchMutexLock lock(m_mutex);
@ -341,7 +341,7 @@ EventQueue::newOneShotTimer(double duration, void* target)
assert(duration > 0.0); assert(duration > 0.0);
EventQueueTimer* timer = m_buffer->newTimer(duration, true); EventQueueTimer* timer = m_buffer->newTimer(duration, true);
if (target == NULL) { if (target == nullptr) {
target = timer; target = timer;
} }
ArchMutexLock lock(m_mutex); ArchMutexLock lock(m_mutex);
@ -358,14 +358,14 @@ void
EventQueue::deleteTimer(EventQueueTimer* timer) EventQueue::deleteTimer(EventQueueTimer* timer)
{ {
ArchMutexLock lock(m_mutex); ArchMutexLock lock(m_mutex);
for (TimerQueue::iterator index = m_timerQueue.begin(); for (auto index = m_timerQueue.begin();
index != m_timerQueue.end(); ++index) { index != m_timerQueue.end(); ++index) {
if (index->getTimer() == timer) { if (index->getTimer() == timer) {
m_timerQueue.erase(index); m_timerQueue.erase(index);
break; break;
} }
} }
Timers::iterator index = m_timers.find(timer); auto index = m_timers.find(timer);
if (index != m_timers.end()) { if (index != m_timers.end()) {
m_timers.erase(index); m_timers.erase(index);
} }
@ -384,13 +384,13 @@ EventQueue::adoptHandler(Event::Type type, void* target, IEventJob* handler)
void void
EventQueue::removeHandler(Event::Type type, void* target) EventQueue::removeHandler(Event::Type type, void* target)
{ {
IEventJob* handler = NULL; IEventJob* handler = nullptr;
{ {
ArchMutexLock lock(m_mutex); ArchMutexLock lock(m_mutex);
HandlerTable::iterator index = m_handlers.find(target); auto index = m_handlers.find(target);
if (index != m_handlers.end()) { if (index != m_handlers.end()) {
TypeHandlerTable& typeHandlers = index->second; TypeHandlerTable& typeHandlers = index->second;
TypeHandlerTable::iterator index2 = typeHandlers.find(type); auto index2 = typeHandlers.find(type);
if (index2 != typeHandlers.end()) { if (index2 != typeHandlers.end()) {
handler = index2->second; handler = index2->second;
typeHandlers.erase(index2); typeHandlers.erase(index2);
@ -406,22 +406,20 @@ EventQueue::removeHandlers(void* target)
std::vector<IEventJob*> handlers; std::vector<IEventJob*> handlers;
{ {
ArchMutexLock lock(m_mutex); ArchMutexLock lock(m_mutex);
HandlerTable::iterator index = m_handlers.find(target); auto index = m_handlers.find(target);
if (index != m_handlers.end()) { if (index != m_handlers.end()) {
// copy to handlers array and clear table for target // copy to handlers array and clear table for target
TypeHandlerTable& typeHandlers = index->second; TypeHandlerTable& typeHandlers = index->second;
for (TypeHandlerTable::iterator index2 = typeHandlers.begin(); for (auto & typeHandler : typeHandlers) {
index2 != typeHandlers.end(); ++index2) { handlers.push_back(typeHandler.second);
handlers.push_back(index2->second);
} }
typeHandlers.clear(); typeHandlers.clear();
} }
} }
// delete handlers // delete handlers
for (std::vector<IEventJob*>::iterator index = handlers.begin(); for (auto & handler : handlers) {
index != handlers.end(); ++index) { delete handler;
delete *index;
} }
} }
@ -435,15 +433,15 @@ IEventJob*
EventQueue::getHandler(Event::Type type, void* target) const EventQueue::getHandler(Event::Type type, void* target) const
{ {
ArchMutexLock lock(m_mutex); ArchMutexLock lock(m_mutex);
HandlerTable::const_iterator index = m_handlers.find(target); auto index = m_handlers.find(target);
if (index != m_handlers.end()) { if (index != m_handlers.end()) {
const TypeHandlerTable& typeHandlers = index->second; const TypeHandlerTable& typeHandlers = index->second;
TypeHandlerTable::const_iterator index2 = typeHandlers.find(type); auto index2 = typeHandlers.find(type);
if (index2 != typeHandlers.end()) { if (index2 != typeHandlers.end()) {
return index2->second; return index2->second;
} }
} }
return NULL; return nullptr;
} }
UInt32 UInt32
@ -470,9 +468,9 @@ Event
EventQueue::removeEvent(UInt32 eventID) EventQueue::removeEvent(UInt32 eventID)
{ {
// look up id // look up id
EventTable::iterator index = m_events.find(eventID); auto index = m_events.find(eventID);
if (index == m_events.end()) { if (index == m_events.end()) {
return Event(); return {};
} }
// get data // get data
@ -500,9 +498,8 @@ EventQueue::hasTimerExpired(Event& event)
m_time.reset(); m_time.reset();
// countdown elapsed time // countdown elapsed time
for (TimerQueue::iterator index = m_timerQueue.begin(); for (auto & index : m_timerQueue) {
index != m_timerQueue.end(); ++index) { index -= time;
(*index) -= time;
} }
// done if no timers are expired // done if no timers are expired
@ -545,9 +542,10 @@ EventQueue::getNextTimerTimeout() const
Event::Type Event::Type
EventQueue::getRegisteredType(const String& name) const EventQueue::getRegisteredType(const String& name) const
{ {
NameMap::const_iterator found = m_nameMap.find(name); auto found = m_nameMap.find(name);
if (found != m_nameMap.end()) if (found != m_nameMap.end()) {
return found->second; return found->second;
}
return Event::kUnknown; return Event::kUnknown;
} }

View File

@ -130,7 +130,7 @@ private:
Stopwatch m_time; Stopwatch m_time;
Timers m_timers; Timers m_timers;
TimerQueue m_timerQueue; TimerQueue m_timerQueue;
TimerEvent m_timerEvent; TimerEvent m_timerEvent{};
// event handlers // event handlers
HandlerTable m_handlers; HandlerTable m_handlers;

View File

@ -18,11 +18,11 @@
#include "base/EventTypes.h" #include "base/EventTypes.h"
#include "base/IEventQueue.h" #include "base/IEventQueue.h"
#include <assert.h> #include <cassert>
#include <stddef.h> #include <cstddef>
EventTypes::EventTypes() : EventTypes::EventTypes() :
m_events(NULL) m_events(nullptr)
{ {
} }

View File

@ -38,7 +38,7 @@ FunctionEventJob::~FunctionEventJob()
void void
FunctionEventJob::run(const Event& event) FunctionEventJob::run(const Event& event)
{ {
if (m_func != NULL) { if (m_func != nullptr) {
m_func(event, m_arg); m_func(event, m_arg);
} }
} }

View File

@ -37,7 +37,7 @@ FunctionJob::~FunctionJob()
void void
FunctionJob::run() FunctionJob::run()
{ {
if (m_func != NULL) { if (m_func != nullptr) {
m_func(m_arg); m_func(m_arg);
} }
} }

View File

@ -25,8 +25,8 @@
#include <cstdio> #include <cstdio>
#include <cstring> #include <cstring>
#include <iostream>
#include <ctime> #include <ctime>
#include <iostream>
// names of priorities // names of priorities
static const char* g_priority[] = { static const char* g_priority[] = {
@ -44,7 +44,7 @@ static const char* g_priority[] = {
}; };
// number of priorities // number of priorities
static const int g_numPriority = (int)(sizeof(g_priority) / sizeof(g_priority[0])); static const int g_numPriority = static_cast<int>(sizeof(g_priority) / sizeof(g_priority[0]));
// the default priority // the default priority
#ifndef NDEBUG #ifndef NDEBUG
@ -57,7 +57,7 @@ static const int g_defaultMaxPriority = kINFO;
// Log // Log
// //
Log* Log::s_log = NULL; Log* Log::s_log = nullptr;
Log::Log() Log::Log()
{ {
@ -82,13 +82,11 @@ Log::Log(Log* src)
Log::~Log() Log::~Log()
{ {
// clean up // clean up
for (OutputterList::iterator index = m_outputters.begin(); for (auto & m_outputter : m_outputters) {
index != m_outputters.end(); ++index) { delete m_outputter;
delete *index;
} }
for (OutputterList::iterator index = m_alwaysOutputters.begin(); for (auto & m_alwaysOutputter : m_alwaysOutputters) {
index != m_alwaysOutputters.end(); ++index) { delete m_alwaysOutputter;
delete *index;
} }
ARCH->closeMutex(m_mutex); ARCH->closeMutex(m_mutex);
} }
@ -116,7 +114,7 @@ Log::getFilterName(int level) const
} }
void 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 // check if fmt begins with a priority argument
ELevel priority = kINFO; 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 // 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 // number it a true number. we could use atoi instead, but this is how
// it was done originally. // it was done originally.
priority = (ELevel)(fmt[2] - '\060'); priority = static_cast<ELevel>(fmt[2] - '\060');
// move the pointer on past the debug priority char // move the pointer on past the debug priority char
fmt += 3; 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 // print to buffer, leaving space for a newline at the end and prefix
// at the beginning. // at the beginning.
char* buffer = stack; char* buffer = stack;
int len = (int)(sizeof(stack) / sizeof(stack[0])); auto len = static_cast<int>(sizeof(stack) / sizeof(stack[0]));
while (true) { while (true) {
// try printing into the buffer // try printing into the buffer
va_list args; va_list args;
@ -154,7 +152,7 @@ Log::print(const char* file, int line, const char* fmt, ...)
va_end(args); va_end(args);
// if the buffer wasn't big enough then make it bigger and try again // 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) { if (buffer != stack) {
delete[] buffer; 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 // assume there is no file contains over 100k lines of code
size += 6; size += 6;
#endif #endif
char* message = new char[size]; auto* message = new char[size];
#ifndef NDEBUG #ifndef NDEBUG
sprintf(message, "[%s] %s: %s\n\t%s,%d", timestamp, g_priority[priority], buffer, file, line); 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 bool
Log::setFilter(const char* maxPriority) Log::setFilter(const char* maxPriority)
{ {
if (maxPriority != NULL) { if (maxPriority != nullptr) {
for (int i = 0; i < g_numPriority; ++i) { for (int i = 0; i < g_numPriority; ++i) {
if (strcmp(maxPriority, g_priority[i]) == 0) { if (strcmp(maxPriority, g_priority[i]) == 0) {
setFilter(i); setFilter(i);
@ -287,7 +285,8 @@ Log::output(ELevel priority, char* msg)
{ {
assert(priority >= -1 && priority < g_numPriority); assert(priority >= -1 && priority < g_numPriority);
assert(msg != NULL); assert(msg != NULL);
if (!msg) return; if (msg == nullptr) { return;
}
ArchMutexLock lock(m_mutex); ArchMutexLock lock(m_mutex);

View File

@ -62,7 +62,7 @@ public:
By default, the logger has one outputter installed which writes to By default, the logger has one outputter installed which writes to
the console. the console.
*/ */
void insert(ILogOutputter* adopted, void insert(ILogOutputter* outputter,
bool alwaysAtHead = false); bool alwaysAtHead = false);
//! Remove an outputter from the list //! Remove an outputter from the list
@ -71,7 +71,7 @@ public:
outputter list. It does nothing if the outputter is not in the outputter list. It does nothing if the outputter is not in the
list. The outputter is not deleted. list. The outputter is not deleted.
*/ */
void remove(ILogOutputter* orphaned); void remove(ILogOutputter* outputter);
//! Remove the outputter from the head of the list //! 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 true if the priority \c name was recognized; if \c name is NULL
then it simply returns true. then it simply returns true.
*/ */
bool setFilter(const char* name); bool setFilter(const char* maxPriority);
//! Set the minimum priority filter (by ordinal). //! Set the minimum priority filter (by ordinal).
void setFilter(int); void setFilter(int);
@ -105,7 +105,7 @@ public:
neither the file nor the line are printed. neither the file nor the line are printed.
*/ */
void print(const char* file, int line, void print(const char* file, int line,
const char* format, ...); const char* fmt, ...);
//! Get the minimum priority level. //! Get the minimum priority level.
int getFilter() const; int getFilter() const;
@ -132,11 +132,11 @@ private:
static Log* s_log; static Log* s_log;
ArchMutex m_mutex; ArchMutex m_mutex{};
OutputterList m_outputters; OutputterList m_outputters;
OutputterList m_alwaysOutputters; OutputterList m_alwaysOutputters;
int m_maxNewlineLength; int m_maxNewlineLength{};
int m_maxPriority; int m_maxPriority{};
}; };
/*! /*!

View File

@ -17,8 +17,8 @@
*/ */
#include "base/SimpleEventQueueBuffer.h" #include "base/SimpleEventQueueBuffer.h"
#include "base/Stopwatch.h"
#include "arch/Arch.h" #include "arch/Arch.h"
#include "base/Stopwatch.h"
class EventQueueTimer { }; class EventQueueTimer { };
@ -57,7 +57,7 @@ SimpleEventQueueBuffer::waitForEvent(double timeout)
} }
IEventQueueBuffer::Type IEventQueueBuffer::Type
SimpleEventQueueBuffer::getEvent(Event&, UInt32& dataID) SimpleEventQueueBuffer::getEvent(Event& /*event*/, UInt32& dataID)
{ {
ArchMutexLock lock(m_queueMutex); ArchMutexLock lock(m_queueMutex);
if (!m_queueReady) { if (!m_queueReady) {
@ -89,7 +89,7 @@ SimpleEventQueueBuffer::isEmpty() const
} }
EventQueueTimer* EventQueueTimer*
SimpleEventQueueBuffer::newTimer(double, bool) const SimpleEventQueueBuffer::newTimer(double /*duration*/, bool /*oneShot*/) const
{ {
return new EventQueueTimer; return new EventQueueTimer;
} }

View File

@ -46,12 +46,12 @@ Stopwatch::reset()
m_mark = 0.0; m_mark = 0.0;
return dt; return dt;
} }
else {
const double t = ARCH->time(); const double t = ARCH->time();
const double dt = t - m_mark; const double dt = t - m_mark;
m_mark = t; m_mark = t;
return dt; return dt;
}
} }
void void
@ -94,7 +94,7 @@ Stopwatch::getTime()
start(); start();
return dt; return dt;
} }
else if (m_stopped) { if (m_stopped) {
return m_mark; return m_mark;
} }
else { else {
@ -119,9 +119,9 @@ Stopwatch::getTime() const
if (m_stopped) { if (m_stopped) {
return m_mark; return m_mark;
} }
else {
return ARCH->time() - m_mark; return ARCH->time() - m_mark;
}
} }
Stopwatch::operator double() const Stopwatch::operator double() const

View File

@ -20,17 +20,17 @@
#include "common/common.h" #include "common/common.h"
#include "common/stdvector.h" #include "common/stdvector.h"
#include <algorithm>
#include <algorithm>
#include <cctype> #include <cctype>
#include <cerrno>
#include <cstdarg>
#include <cstdio> #include <cstdio>
#include <cstdlib> #include <cstdlib>
#include <cstring> #include <cstring>
#include <algorithm>
#include <stdio.h>
#include <cstdarg>
#include <sstream>
#include <iomanip> #include <iomanip>
#include <algorithm> #include <sstream>
#include <cerrno> #include <stdio.h>
namespace synergy { namespace synergy {
namespace string { namespace string {
@ -59,7 +59,7 @@ vformat(const char* fmt, va_list args)
if (*scan == '\0') { if (*scan == '\0') {
break; break;
} }
else if (*scan == '%') { if (*scan == '%') {
// literal // literal
index.push_back(0); index.push_back(0);
pos.push_back(static_cast<size_t>((scan - 1) - fmt)); pos.push_back(static_cast<size_t>((scan - 1) - fmt));
@ -104,7 +104,7 @@ vformat(const char* fmt, va_list args)
// compute final length // compute final length
size_t resultLength = strlen(fmt); size_t resultLength = strlen(fmt);
const int n = static_cast<int>(pos.size()); const auto n = static_cast<int>(pos.size());
for (int i = 0; i < n; ++i) { for (int i = 0; i < n; ++i) {
resultLength -= width[i]; resultLength -= width[i];
resultLength += length[index[i]]; resultLength += length[index[i]];
@ -129,9 +129,9 @@ sprintf(const char* fmt, ...)
{ {
char tmp[1024]; char tmp[1024];
char* buffer = tmp; char* buffer = tmp;
int len = (int)(sizeof(tmp) / sizeof(tmp[0])); auto len = static_cast<int>(sizeof(tmp) / sizeof(tmp[0]));
String result; String result;
while (buffer != NULL) { while (buffer != nullptr) {
// try printing into the buffer // try printing into the buffer
va_list args; va_list args;
va_start(args, fmt); va_start(args, fmt);
@ -153,7 +153,7 @@ sprintf(const char* fmt, ...)
if (buffer != tmp) { if (buffer != tmp) {
delete[] buffer; delete[] buffer;
} }
buffer = NULL; buffer = nullptr;
} }
} }
@ -190,8 +190,8 @@ toHex(String& subject, int width, const char fill)
{ {
std::stringstream ss; std::stringstream ss;
ss << std::hex; ss << std::hex;
for (unsigned int i = 0; i < subject.length(); i++) { for (char i : subject) {
ss << std::setw(width) << std::setfill(fill) << (int)(unsigned char)subject[i]; ss << std::setw(width) << std::setfill(fill) << static_cast<int>(static_cast<unsigned char>(i));
} }
subject = ss.str(); subject = ss.str();
@ -218,7 +218,7 @@ sizeTypeToString(size_t n)
} }
size_t size_t
stringToSizeType(String string) stringToSizeType(const String& string)
{ {
std::istringstream iss(string); std::istringstream iss(string);
size_t value; size_t value;
@ -227,7 +227,7 @@ stringToSizeType(String string)
} }
std::vector<String> std::vector<String>
splitString(String string, const char c) splitString(const String& string, const char c)
{ {
std::vector<String> results; std::vector<String> results;
@ -291,5 +291,5 @@ CaselessCmp::operator()(const String& a, const String& b) const
return less(a, b); return less(a, b);
} }
} } // namespace string
} } // namespace synergy

View File

@ -99,13 +99,13 @@ String sizeTypeToString(size_t n);
/*! /*!
Convert an a \c string to an size type 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 string into substrings
/*! /*!
Split a \c string that separated by a \c c into substrings Split a \c string that separated by a \c c into substrings
*/ */
std::vector<String> splitString(String string, const char c); std::vector<String> splitString(const String& string, const char c);
//! Case-insensitive comparisons //! Case-insensitive comparisons
/*! /*!

View File

@ -33,7 +33,7 @@ decode16(const UInt8* n, bool byteSwapped)
union x16 { union x16 {
UInt8 n8[2]; UInt8 n8[2];
UInt16 n16; UInt16 n16;
} c; } c{};
if (byteSwapped) { if (byteSwapped) {
c.n8[0] = n[1]; c.n8[0] = n[1];
c.n8[1] = n[0]; c.n8[1] = n[0];
@ -53,7 +53,7 @@ decode32(const UInt8* n, bool byteSwapped)
union x32 { union x32 {
UInt8 n8[4]; UInt8 n8[4];
UInt32 n32; UInt32 n32;
} c; } c{};
if (byteSwapped) { if (byteSwapped) {
c.n8[0] = n[3]; c.n8[0] = n[3];
c.n8[1] = n[2]; c.n8[1] = n[2];
@ -74,7 +74,7 @@ static
void void
resetError(bool* errors) resetError(bool* errors)
{ {
if (errors != NULL) { if (errors != nullptr) {
*errors = false; *errors = false;
} }
} }
@ -84,7 +84,7 @@ static
void void
setError(bool* errors) setError(bool* errors)
{ {
if (errors != NULL) { if (errors != nullptr) {
*errors = true; *errors = true;
} }
} }
@ -101,8 +101,8 @@ bool
Unicode::isUTF8(const String& src) Unicode::isUTF8(const String& src)
{ {
// convert and test each character // convert and test each character
const UInt8* data = reinterpret_cast<const UInt8*>(src.c_str()); const auto* data = reinterpret_cast<const UInt8*>(src.c_str());
for (UInt32 n = (UInt32)src.size(); n > 0; ) { for (auto n = static_cast<UInt32>(src.size()); n > 0; ) {
if (fromUTF8(data, n) == s_invalid) { if (fromUTF8(data, n) == s_invalid) {
return false; return false;
} }
@ -117,12 +117,12 @@ Unicode::UTF8ToUCS2(const String& src, bool* errors)
resetError(errors); resetError(errors);
// get size of input string and reserve some space in output // get size of input string and reserve some space in output
UInt32 n = (UInt32)src.size(); auto n = static_cast<UInt32>(src.size());
String dst; String dst;
dst.reserve(2 * n); dst.reserve(2 * n);
// convert each character // convert each character
const UInt8* data = reinterpret_cast<const UInt8*>(src.c_str()); const auto* data = reinterpret_cast<const UInt8*>(src.c_str());
while (n > 0) { while (n > 0) {
UInt32 c = fromUTF8(data, n); UInt32 c = fromUTF8(data, n);
if (c == s_invalid) { if (c == s_invalid) {
@ -132,7 +132,7 @@ Unicode::UTF8ToUCS2(const String& src, bool* errors)
setError(errors); setError(errors);
c = s_replacement; c = s_replacement;
} }
UInt16 ucs2 = static_cast<UInt16>(c); auto ucs2 = static_cast<UInt16>(c);
dst.append(reinterpret_cast<const char*>(&ucs2), 2); dst.append(reinterpret_cast<const char*>(&ucs2), 2);
} }
@ -146,12 +146,12 @@ Unicode::UTF8ToUCS4(const String& src, bool* errors)
resetError(errors); resetError(errors);
// get size of input string and reserve some space in output // get size of input string and reserve some space in output
UInt32 n = (UInt32)src.size(); auto n = static_cast<UInt32>(src.size());
String dst; String dst;
dst.reserve(4 * n); dst.reserve(4 * n);
// convert each character // convert each character
const UInt8* data = reinterpret_cast<const UInt8*>(src.c_str()); const auto* data = reinterpret_cast<const UInt8*>(src.c_str());
while (n > 0) { while (n > 0) {
UInt32 c = fromUTF8(data, n); UInt32 c = fromUTF8(data, n);
if (c == s_invalid) { if (c == s_invalid) {
@ -170,12 +170,12 @@ Unicode::UTF8ToUTF16(const String& src, bool* errors)
resetError(errors); resetError(errors);
// get size of input string and reserve some space in output // get size of input string and reserve some space in output
UInt32 n = (UInt32)src.size(); auto n = static_cast<UInt32>(src.size());
String dst; String dst;
dst.reserve(2 * n); dst.reserve(2 * n);
// convert each character // convert each character
const UInt8* data = reinterpret_cast<const UInt8*>(src.c_str()); const auto* data = reinterpret_cast<const UInt8*>(src.c_str());
while (n > 0) { while (n > 0) {
UInt32 c = fromUTF8(data, n); UInt32 c = fromUTF8(data, n);
if (c == s_invalid) { if (c == s_invalid) {
@ -186,13 +186,13 @@ Unicode::UTF8ToUTF16(const String& src, bool* errors)
c = s_replacement; c = s_replacement;
} }
if (c < 0x00010000) { if (c < 0x00010000) {
UInt16 ucs2 = static_cast<UInt16>(c); auto ucs2 = static_cast<UInt16>(c);
dst.append(reinterpret_cast<const char*>(&ucs2), 2); dst.append(reinterpret_cast<const char*>(&ucs2), 2);
} }
else { else {
c -= 0x00010000; c -= 0x00010000;
UInt16 utf16h = static_cast<UInt16>((c >> 10) + 0xd800); auto utf16h = static_cast<UInt16>((c >> 10) + 0xd800);
UInt16 utf16l = static_cast<UInt16>((c & 0x03ff) + 0xdc00); auto utf16l = static_cast<UInt16>((c & 0x03ff) + 0xdc00);
dst.append(reinterpret_cast<const char*>(&utf16h), 2); dst.append(reinterpret_cast<const char*>(&utf16h), 2);
dst.append(reinterpret_cast<const char*>(&utf16l), 2); dst.append(reinterpret_cast<const char*>(&utf16l), 2);
} }
@ -208,12 +208,12 @@ Unicode::UTF8ToUTF32(const String& src, bool* errors)
resetError(errors); resetError(errors);
// get size of input string and reserve some space in output // get size of input string and reserve some space in output
UInt32 n = (UInt32)src.size(); auto n = static_cast<UInt32>(src.size());
String dst; String dst;
dst.reserve(4 * n); dst.reserve(4 * n);
// convert each character // convert each character
const UInt8* data = reinterpret_cast<const UInt8*>(src.c_str()); const auto* data = reinterpret_cast<const UInt8*>(src.c_str());
while (n > 0) { while (n > 0) {
UInt32 c = fromUTF8(data, n); UInt32 c = fromUTF8(data, n);
if (c == s_invalid) { if (c == s_invalid) {
@ -240,8 +240,8 @@ Unicode::UTF8ToText(const String& src, bool* errors)
wchar_t* tmp = UTF8ToWideChar(src, size, errors); wchar_t* tmp = UTF8ToWideChar(src, size, errors);
// convert string to multibyte // convert string to multibyte
int len = ARCH->convStringWCToMB(NULL, tmp, size, errors); int len = ARCH->convStringWCToMB(nullptr, tmp, size, errors);
char* mbs = new char[len + 1]; auto* mbs = new char[len + 1];
ARCH->convStringWCToMB(mbs, tmp, size, errors); ARCH->convStringWCToMB(mbs, tmp, size, errors);
String text(mbs, len); String text(mbs, len);
@ -259,7 +259,7 @@ Unicode::UCS2ToUTF8(const String& src, bool* errors)
resetError(errors); resetError(errors);
// convert // convert
UInt32 n = (UInt32)src.size() >> 1; UInt32 n = static_cast<UInt32>(src.size()) >> 1;
return doUCS2ToUTF8(reinterpret_cast<const UInt8*>(src.data()), n, errors); return doUCS2ToUTF8(reinterpret_cast<const UInt8*>(src.data()), n, errors);
} }
@ -270,7 +270,7 @@ Unicode::UCS4ToUTF8(const String& src, bool* errors)
resetError(errors); resetError(errors);
// convert // convert
UInt32 n = (UInt32)src.size() >> 2; UInt32 n = static_cast<UInt32>(src.size()) >> 2;
return doUCS4ToUTF8(reinterpret_cast<const UInt8*>(src.data()), n, errors); return doUCS4ToUTF8(reinterpret_cast<const UInt8*>(src.data()), n, errors);
} }
@ -281,7 +281,7 @@ Unicode::UTF16ToUTF8(const String& src, bool* errors)
resetError(errors); resetError(errors);
// convert // convert
UInt32 n = (UInt32)src.size() >> 1; UInt32 n = static_cast<UInt32>(src.size()) >> 1;
return doUTF16ToUTF8(reinterpret_cast<const UInt8*>(src.data()), n, errors); return doUTF16ToUTF8(reinterpret_cast<const UInt8*>(src.data()), n, errors);
} }
@ -292,7 +292,7 @@ Unicode::UTF32ToUTF8(const String& src, bool* errors)
resetError(errors); resetError(errors);
// convert // convert
UInt32 n = (UInt32)src.size() >> 2; UInt32 n = static_cast<UInt32>(src.size()) >> 2;
return doUTF32ToUTF8(reinterpret_cast<const UInt8*>(src.data()), n, errors); return doUTF32ToUTF8(reinterpret_cast<const UInt8*>(src.data()), n, errors);
} }
@ -303,9 +303,9 @@ Unicode::textToUTF8(const String& src, bool* errors)
resetError(errors); resetError(errors);
// convert string to wide characters // convert string to wide characters
UInt32 n = (UInt32)src.size(); auto n = static_cast<UInt32>(src.size());
int len = ARCH->convStringMBToWC(NULL, src.c_str(), n, errors); int len = ARCH->convStringMBToWC(nullptr, src.c_str(), n, errors);
wchar_t* wcs = new wchar_t[len + 1]; auto* wcs = new wchar_t[len + 1];
ARCH->convStringMBToWC(wcs, src.c_str(), n, errors); ARCH->convStringMBToWC(wcs, src.c_str(), n, errors);
// convert to UTF8 // convert to UTF8
@ -325,22 +325,22 @@ Unicode::UTF8ToWideChar(const String& src, UInt32& size, bool* errors)
switch (ARCH->getWideCharEncoding()) { switch (ARCH->getWideCharEncoding()) {
case IArchString::kUCS2: case IArchString::kUCS2:
tmp = UTF8ToUCS2(src, errors); tmp = UTF8ToUCS2(src, errors);
size = (UInt32)tmp.size() >> 1; size = static_cast<UInt32>(tmp.size()) >> 1;
break; break;
case IArchString::kUCS4: case IArchString::kUCS4:
tmp = UTF8ToUCS4(src, errors); tmp = UTF8ToUCS4(src, errors);
size = (UInt32)tmp.size() >> 2; size = static_cast<UInt32>(tmp.size()) >> 2;
break; break;
case IArchString::kUTF16: case IArchString::kUTF16:
tmp = UTF8ToUTF16(src, errors); tmp = UTF8ToUTF16(src, errors);
size = (UInt32)tmp.size() >> 1; size = static_cast<UInt32>(tmp.size()) >> 1;
break; break;
case IArchString::kUTF32: case IArchString::kUTF32:
tmp = UTF8ToUTF32(src, errors); tmp = UTF8ToUTF32(src, errors);
size = (UInt32)tmp.size() >> 2; size = static_cast<UInt32>(tmp.size()) >> 2;
break; break;
default: default:
@ -348,7 +348,7 @@ Unicode::UTF8ToWideChar(const String& src, UInt32& size, bool* errors)
} }
// copy to a wchar_t array // 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); ::memcpy(dst, tmp.data(), sizeof(wchar_t) * size);
return dst; return dst;
} }
@ -486,7 +486,7 @@ Unicode::doUTF16ToUTF8(const UInt8* data, UInt32 n, bool* errors)
else if (n == 1) { else if (n == 1) {
// error -- missing second word // error -- missing second word
setError(errors); setError(errors);
toUTF8(dst, s_replacement, NULL); toUTF8(dst, s_replacement, nullptr);
} }
else if (c >= 0x0000d800 && c <= 0x0000dbff) { else if (c >= 0x0000d800 && c <= 0x0000dbff) {
UInt32 c2 = decode16(data, byteSwapped); UInt32 c2 = decode16(data, byteSwapped);
@ -495,7 +495,7 @@ Unicode::doUTF16ToUTF8(const UInt8* data, UInt32 n, bool* errors)
if (c2 < 0x0000dc00 || c2 > 0x0000dfff) { if (c2 < 0x0000dc00 || c2 > 0x0000dfff) {
// error -- [d800,dbff] not followed by [dc00,dfff] // error -- [d800,dbff] not followed by [dc00,dfff]
setError(errors); setError(errors);
toUTF8(dst, s_replacement, NULL); toUTF8(dst, s_replacement, nullptr);
} }
else { else {
c = (((c - 0x0000d800) << 10) | (c2 - 0x0000dc00)) + 0x00010000; c = (((c - 0x0000d800) << 10) | (c2 - 0x0000dc00)) + 0x00010000;
@ -505,7 +505,7 @@ Unicode::doUTF16ToUTF8(const UInt8* data, UInt32 n, bool* errors)
else { else {
// error -- [dc00,dfff] without leading [d800,dbff] // error -- [dc00,dfff] without leading [d800,dbff]
setError(errors); setError(errors);
toUTF8(dst, s_replacement, NULL); toUTF8(dst, s_replacement, nullptr);
} }
} }

View File

@ -129,13 +129,13 @@ private:
UInt32 size, bool* errors); UInt32 size, bool* errors);
// internal conversion to UTF8 // internal conversion to UTF8
static String doUCS2ToUTF8(const UInt8* src, UInt32 n, bool* errors); static String doUCS2ToUTF8(const UInt8* data, UInt32 n, bool* errors);
static String doUCS4ToUTF8(const UInt8* src, UInt32 n, bool* errors); static String doUCS4ToUTF8(const UInt8* data, UInt32 n, bool* errors);
static String doUTF16ToUTF8(const UInt8* src, UInt32 n, bool* errors); static String doUTF16ToUTF8(const UInt8* data, UInt32 n, bool* errors);
static String doUTF32ToUTF8(const UInt8* src, UInt32 n, bool* errors); static String doUTF32ToUTF8(const UInt8* data, UInt32 n, bool* errors);
// convert characters to/from UTF8 // 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); static void toUTF8(String& dst, UInt32 c, bool* errors);
private: private:

View File

@ -38,13 +38,13 @@ XBase::XBase(const String& msg) :
// do nothing // do nothing
} }
XBase::~XBase() _NOEXCEPT XBase::~XBase() noexcept
{ {
// do nothing // do nothing
} }
const char* const char*
XBase::what() const _NOEXCEPT XBase::what() const noexcept
{ {
const char* what = std::runtime_error::what(); const char* what = std::runtime_error::what();
if (strlen(what) == 0) { if (strlen(what) == 0) {
@ -55,7 +55,7 @@ XBase::what() const _NOEXCEPT
} }
String 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 // FIXME -- lookup message string using id as an index. set
// fmt to that string if it exists. // fmt to that string if it exists.

View File

@ -47,7 +47,7 @@ protected:
the format string and returns the result. the format string and returns the result.
*/ */
virtual String format(const char* id, virtual String format(const char* id,
const char* defaultFormat, ...) const throw(); const char* fmt, ...) const throw();
private: private:
mutable String m_what; mutable String m_what;
}; };

View File

@ -17,8 +17,8 @@
*/ */
#include "base/log_outputters.h" #include "base/log_outputters.h"
#include "base/TMethodJob.h"
#include "arch/Arch.h" #include "arch/Arch.h"
#include "base/TMethodJob.h"
#include <fstream> #include <fstream>
@ -41,7 +41,7 @@ StopLogOutputter::~StopLogOutputter()
} }
void void
StopLogOutputter::open(const char*) StopLogOutputter::open(const char* /*title*/)
{ {
// do nothing // do nothing
} }
@ -53,13 +53,13 @@ StopLogOutputter::close()
} }
void void
StopLogOutputter::show(bool) StopLogOutputter::show(bool /*showIfEmpty*/)
{ {
// do nothing // do nothing
} }
bool bool
StopLogOutputter::write(ELevel, const char*) StopLogOutputter::write(ELevel /*level*/, const char* /*message*/)
{ {
return false; return false;
} }
@ -70,12 +70,10 @@ StopLogOutputter::write(ELevel, const char*)
// //
ConsoleLogOutputter::ConsoleLogOutputter() ConsoleLogOutputter::ConsoleLogOutputter()
{ = default;
}
ConsoleLogOutputter::~ConsoleLogOutputter() ConsoleLogOutputter::~ConsoleLogOutputter()
{ = default;
}
void void
ConsoleLogOutputter::open(const char* title) ConsoleLogOutputter::open(const char* title)
@ -153,7 +151,7 @@ SystemLogOutputter::write(ELevel level, const char* msg)
// //
SystemLogger::SystemLogger(const char* title, bool blockConsole) : SystemLogger::SystemLogger(const char* title, bool blockConsole) :
m_stop(NULL) m_stop(nullptr)
{ {
// redirect log messages // redirect log messages
if (blockConsole) { if (blockConsole) {
@ -169,7 +167,7 @@ SystemLogger::~SystemLogger()
{ {
CLOG->remove(m_syslog); CLOG->remove(m_syslog);
delete m_syslog; delete m_syslog;
if (m_stop != NULL) { if (m_stop != nullptr) {
CLOG->remove(m_stop); CLOG->remove(m_stop);
delete m_stop; delete m_stop;
} }
@ -204,7 +202,7 @@ BufferedLogOutputter::end() const
} }
void void
BufferedLogOutputter::open(const char*) BufferedLogOutputter::open(const char* /*title*/)
{ {
// do nothing // do nothing
} }
@ -217,18 +215,18 @@ BufferedLogOutputter::close()
} }
void void
BufferedLogOutputter::show(bool) BufferedLogOutputter::show(bool /*showIfEmpty*/)
{ {
// do nothing // do nothing
} }
bool bool
BufferedLogOutputter::write(ELevel, const char* message) BufferedLogOutputter::write(ELevel /*level*/, const char* message)
{ {
while (m_buffer.size() >= m_maxBufferSize) { while (m_buffer.size() >= m_maxBufferSize) {
m_buffer.pop_front(); m_buffer.pop_front();
} }
m_buffer.push_back(String(message)); m_buffer.emplace_back(message);
return true; return true;
} }
@ -243,8 +241,7 @@ FileLogOutputter::FileLogOutputter(const char* logFile)
} }
FileLogOutputter::~FileLogOutputter() FileLogOutputter::~FileLogOutputter()
{ = default;
}
void void
FileLogOutputter::setLogFilename(const char* logFile) FileLogOutputter::setLogFilename(const char* logFile)
@ -254,13 +251,13 @@ FileLogOutputter::setLogFilename(const char* logFile)
} }
bool bool
FileLogOutputter::write(ELevel level, const char *message) FileLogOutputter::write(ELevel /*level*/, const char *message)
{ {
bool moveFile = false; bool moveFile = false;
std::ofstream m_handle; std::ofstream m_handle;
m_handle.open(m_fileName.c_str(), std::fstream::app); 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; m_handle << message << std::endl;
// when file size exceeds limits, move to 'old log' filename. // when file size exceeds limits, move to 'old log' filename.
@ -281,13 +278,13 @@ FileLogOutputter::write(ELevel level, const char *message)
} }
void void
FileLogOutputter::open(const char *title) {} FileLogOutputter::open(const char * /*title*/) {}
void void
FileLogOutputter::close() {} FileLogOutputter::close() {}
void void
FileLogOutputter::show(bool showIfEmpty) {} FileLogOutputter::show(bool /*showIfEmpty*/) {}
// //
// MesssageBoxLogOutputter // MesssageBoxLogOutputter
@ -304,7 +301,7 @@ MesssageBoxLogOutputter::~MesssageBoxLogOutputter()
} }
void void
MesssageBoxLogOutputter::open(const char* title) MesssageBoxLogOutputter::open(const char* /*title*/)
{ {
// do nothing // do nothing
} }
@ -316,13 +313,13 @@ MesssageBoxLogOutputter::close()
} }
void void
MesssageBoxLogOutputter::show(bool showIfEmpty) MesssageBoxLogOutputter::show(bool /*showIfEmpty*/)
{ {
// do nothing // do nothing
} }
bool bool
MesssageBoxLogOutputter::write(ELevel level, const char* msg) MesssageBoxLogOutputter::write(ELevel level, const char* /*msg*/)
{ {
// don't spam user with messages. // don't spam user with messages.
if (level > kERROR) { if (level > kERROR) {

View File

@ -59,7 +59,7 @@ public:
virtual void open(const char* title); virtual void open(const char* title);
virtual void close(); virtual void close();
virtual void show(bool showIfEmpty); virtual void show(bool showIfEmpty);
virtual bool write(ELevel level, const char* message); virtual bool write(ELevel level, const char* msg);
virtual void flush(); virtual void flush();
}; };
@ -80,7 +80,7 @@ public:
virtual void show(bool showIfEmpty); virtual void show(bool showIfEmpty);
virtual bool write(ELevel level, const char* message); virtual bool write(ELevel level, const char* message);
void setLogFilename(const char* title); void setLogFilename(const char* logFile);
private: private:
std::string m_fileName; std::string m_fileName;
@ -99,7 +99,7 @@ public:
virtual void open(const char* title); virtual void open(const char* title);
virtual void close(); virtual void close();
virtual void show(bool showIfEmpty); 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 //! Write log to system log only

View File

@ -18,31 +18,32 @@
#include "client/Client.h" #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 "arch/Arch.h"
#include "base/Log.h"
#include "base/IEventQueue.h" #include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h" #include "base/TMethodEventJob.h"
#include "base/TMethodJob.h" #include "base/TMethodJob.h"
#include "client/ServerProxy.h"
#include "common/stdexcept.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 <cstring>
#include <cstdlib> #include <cstdlib>
#include <sstream> #include <cstring>
#include <fstream> #include <fstream>
#include <sstream>
#include <utility>
// //
// Client // Client
@ -50,27 +51,27 @@
Client::Client( Client::Client(
IEventQueue* events, IEventQueue* events,
const String& name, const NetworkAddress& address, String name, const NetworkAddress& address,
ISocketFactory* socketFactory, ISocketFactory* socketFactory,
synergy::Screen* screen, synergy::Screen* screen,
ClientArgs const& args) : ClientArgs args) :
m_mock(false), m_mock(false),
m_name(name), m_name(std::move(name)),
m_serverAddress(address), m_serverAddress(address),
m_socketFactory(socketFactory), m_socketFactory(socketFactory),
m_screen(screen), m_screen(screen),
m_stream(NULL), m_stream(nullptr),
m_timer(NULL), m_timer(nullptr),
m_server(NULL), m_server(nullptr),
m_ready(false), m_ready(false),
m_active(false), m_active(false),
m_suspended(false), m_suspended(false),
m_connectOnResume(false), m_connectOnResume(false),
m_events(events), m_events(events),
m_sendFileThread(NULL), m_sendFileThread(nullptr),
m_writeToDropDirThread(NULL), m_writeToDropDirThread(nullptr),
m_socket(NULL), m_socket(nullptr),
m_args(args), m_args(std::move(args)),
m_enableClipboard(true) m_enableClipboard(true)
{ {
assert(m_socketFactory != NULL); assert(m_socketFactory != NULL);
@ -119,7 +120,7 @@ Client::~Client()
void void
Client::connect() Client::connect()
{ {
if (m_stream != NULL) { if (m_stream != nullptr) {
return; return;
} }
if (m_suspended) { if (m_suspended) {
@ -136,7 +137,7 @@ Client::connect()
m_serverAddress.resolve(); m_serverAddress.resolve();
// m_serverAddress will be null if the hostname address is not reolved // 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) // to help users troubleshoot, show server host name (issue: 60)
LOG((CLOG_NOTE "connecting to '%s': %s:%i", LOG((CLOG_NOTE "connecting to '%s': %s:%i",
m_serverAddress.getHostname().c_str(), m_serverAddress.getHostname().c_str(),
@ -176,11 +177,11 @@ Client::disconnect(const char* msg)
cleanupScreen(); cleanupScreen();
cleanupConnecting(); cleanupConnecting();
cleanupConnection(); cleanupConnection();
if (msg != NULL) { if (msg != nullptr) {
sendConnectionFailedEvent(msg); sendConnectionFailedEvent(msg);
} }
else { else {
sendEvent(m_events->forClient().disconnected(), NULL); sendEvent(m_events->forClient().disconnected(), nullptr);
} }
} }
@ -189,19 +190,19 @@ Client::handshakeComplete()
{ {
m_ready = true; m_ready = true;
m_screen->enable(); m_screen->enable();
sendEvent(m_events->forClient().connected(), NULL); sendEvent(m_events->forClient().connected(), nullptr);
} }
bool bool
Client::isConnected() const Client::isConnected() const
{ {
return (m_server != NULL); return (m_server != nullptr);
} }
bool bool
Client::isConnecting() const Client::isConnecting() const
{ {
return (m_timer != NULL); return (m_timer != nullptr);
} }
NetworkAddress NetworkAddress
@ -235,15 +236,15 @@ Client::getCursorPos(SInt32& x, SInt32& y) const
} }
void 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_active = true;
m_screen->mouseMove(xAbs, yAbs); m_screen->mouseMove(xAbs, yAbs);
m_screen->enter(mask); m_screen->enter(mask);
if (m_sendFileThread != NULL) { if (m_sendFileThread != nullptr) {
StreamChunker::interruptFile(); StreamChunker::interruptFile();
m_sendFileThread = NULL; m_sendFileThread = nullptr;
} }
} }
@ -283,7 +284,7 @@ Client::grabClipboard(ClipboardID id)
} }
void void
Client::setClipboardDirty(ClipboardID, bool) Client::setClipboardDirty(ClipboardID /*unused*/, bool /*dirty*/)
{ {
assert(0 && "shouldn't be called"); assert(0 && "shouldn't be called");
} }
@ -352,7 +353,7 @@ Client::resetOptions()
void void
Client::setOptions(const OptionsList& options) Client::setOptions(const OptionsList& options)
{ {
for (OptionsList::const_iterator index = options.begin(); for (auto index = options.begin();
index != options.end(); ++index) { index != options.end(); ++index) {
const OptionID id = *index; const OptionID id = *index;
if (id == kOptionClipboardSharing) { if (id == kOptionClipboardSharing) {
@ -360,7 +361,7 @@ Client::setOptions(const OptionsList& options)
if (*index == static_cast<OptionValue>(false)) { if (*index == static_cast<OptionValue>(false)) {
LOG((CLOG_NOTE "clipboard sharing is disabled")); LOG((CLOG_NOTE "clipboard sharing is disabled"));
} }
m_enableClipboard = *index; m_enableClipboard = (*index != 0u);
break; break;
} }
@ -419,7 +420,7 @@ Client::sendEvent(Event::Type type, void* data)
void void
Client::sendConnectionFailedEvent(const char* msg) Client::sendConnectionFailedEvent(const char* msg)
{ {
FailInfo* info = new FailInfo(msg); auto* info = new FailInfo(msg);
info->m_retry = true; info->m_retry = true;
Event event(m_events->forClient().connectionFailed(), getEventTarget(), info, Event::kDontFreeData); Event event(m_events->forClient().connectionFailed(), getEventTarget(), info, Event::kDontFreeData);
m_events->addEvent(event); m_events->addEvent(event);
@ -428,7 +429,7 @@ Client::sendConnectionFailedEvent(const char* msg)
void void
Client::sendFileChunk(const void* data) Client::sendFileChunk(const void* data)
{ {
FileChunk* chunk = static_cast<FileChunk*>(const_cast<void*>(data)); auto* chunk = static_cast<FileChunk*>(const_cast<void*>(data));
LOG((CLOG_DEBUG1 "send file chunk")); LOG((CLOG_DEBUG1 "send file chunk"));
assert(m_server != NULL); assert(m_server != NULL);
@ -505,7 +506,7 @@ Client::setupTimer()
{ {
assert(m_timer == NULL); 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, m_events->adoptHandler(Event::kTimer, m_timer,
new TMethodEventJob<Client>(this, new TMethodEventJob<Client>(this,
&Client::handleConnectTimeout)); &Client::handleConnectTimeout));
@ -514,7 +515,7 @@ Client::setupTimer()
void void
Client::cleanupConnecting() Client::cleanupConnecting()
{ {
if (m_stream != NULL) { if (m_stream != nullptr) {
m_events->removeHandler(m_events->forIDataSocket().connected(), m_events->removeHandler(m_events->forIDataSocket().connected(),
m_stream->getEventTarget()); m_stream->getEventTarget());
m_events->removeHandler(m_events->forIDataSocket().connectionFailed(), m_events->removeHandler(m_events->forIDataSocket().connectionFailed(),
@ -525,7 +526,7 @@ Client::cleanupConnecting()
void void
Client::cleanupConnection() Client::cleanupConnection()
{ {
if (m_stream != NULL) { if (m_stream != nullptr) {
m_events->removeHandler(m_events->forIStream().inputReady(), m_events->removeHandler(m_events->forIStream().inputReady(),
m_stream->getEventTarget()); m_stream->getEventTarget());
m_events->removeHandler(m_events->forIStream().outputError(), m_events->removeHandler(m_events->forIStream().outputError(),
@ -545,7 +546,7 @@ Client::cleanupConnection()
void void
Client::cleanupScreen() Client::cleanupScreen()
{ {
if (m_server != NULL) { if (m_server != nullptr) {
if (m_ready) { if (m_ready) {
m_screen->disable(); m_screen->disable();
m_ready = false; m_ready = false;
@ -555,17 +556,17 @@ Client::cleanupScreen()
m_events->removeHandler(m_events->forClipboard().clipboardGrabbed(), m_events->removeHandler(m_events->forClipboard().clipboardGrabbed(),
getEventTarget()); getEventTarget());
delete m_server; delete m_server;
m_server = NULL; m_server = nullptr;
} }
} }
void void
Client::cleanupTimer() Client::cleanupTimer()
{ {
if (m_timer != NULL) { if (m_timer != nullptr) {
m_events->removeHandler(Event::kTimer, m_timer); m_events->removeHandler(Event::kTimer, m_timer);
m_events->deleteTimer(m_timer); m_events->deleteTimer(m_timer);
m_timer = NULL; m_timer = nullptr;
} }
} }
@ -573,11 +574,11 @@ void
Client::cleanupStream() Client::cleanupStream()
{ {
delete m_stream; delete m_stream;
m_stream = NULL; m_stream = nullptr;
} }
void void
Client::handleConnected(const Event&, void*) Client::handleConnected(const Event& /*unused*/, void* /*unused*/)
{ {
LOG((CLOG_DEBUG1 "connected; wait for hello")); LOG((CLOG_DEBUG1 "connected; wait for hello"));
cleanupConnecting(); cleanupConnecting();
@ -592,9 +593,9 @@ Client::handleConnected(const Event&, void*)
} }
void void
Client::handleConnectionFailed(const Event& event, void*) Client::handleConnectionFailed(const Event& event, void* /*unused*/)
{ {
IDataSocket::ConnectionFailedInfo* info = auto* info =
static_cast<IDataSocket::ConnectionFailedInfo*>(event.getData()); static_cast<IDataSocket::ConnectionFailedInfo*>(event.getData());
cleanupTimer(); cleanupTimer();
@ -606,7 +607,7 @@ Client::handleConnectionFailed(const Event& event, void*)
} }
void void
Client::handleConnectTimeout(const Event&, void*) Client::handleConnectTimeout(const Event& /*unused*/, void* /*unused*/)
{ {
cleanupTimer(); cleanupTimer();
cleanupConnecting(); cleanupConnecting();
@ -617,40 +618,40 @@ Client::handleConnectTimeout(const Event&, void*)
} }
void void
Client::handleOutputError(const Event&, void*) Client::handleOutputError(const Event& /*unused*/, void* /*unused*/)
{ {
cleanupTimer(); cleanupTimer();
cleanupScreen(); cleanupScreen();
cleanupConnection(); cleanupConnection();
LOG((CLOG_WARN "error sending to server")); LOG((CLOG_WARN "error sending to server"));
sendEvent(m_events->forClient().disconnected(), NULL); sendEvent(m_events->forClient().disconnected(), nullptr);
} }
void void
Client::handleDisconnected(const Event&, void*) Client::handleDisconnected(const Event& /*unused*/, void* /*unused*/)
{ {
cleanupTimer(); cleanupTimer();
cleanupScreen(); cleanupScreen();
cleanupConnection(); cleanupConnection();
LOG((CLOG_DEBUG1 "disconnected")); LOG((CLOG_DEBUG1 "disconnected"));
sendEvent(m_events->forClient().disconnected(), NULL); sendEvent(m_events->forClient().disconnected(), nullptr);
} }
void void
Client::handleShapeChanged(const Event&, void*) Client::handleShapeChanged(const Event& /*unused*/, void* /*unused*/)
{ {
LOG((CLOG_DEBUG "resolution changed")); LOG((CLOG_DEBUG "resolution changed"));
m_server->onInfoChanged(); m_server->onInfoChanged();
} }
void void
Client::handleClipboardGrabbed(const Event& event, void*) Client::handleClipboardGrabbed(const Event& event, void* /*unused*/)
{ {
if (!m_enableClipboard) { if (!m_enableClipboard) {
return; return;
} }
const IScreen::ClipboardInfo* info = const auto* info =
static_cast<const IScreen::ClipboardInfo*>(event.getData()); static_cast<const IScreen::ClipboardInfo*>(event.getData());
// grab ownership // grab ownership
@ -669,7 +670,7 @@ Client::handleClipboardGrabbed(const Event& event, void*)
} }
void void
Client::handleHello(const Event&, void*) Client::handleHello(const Event& /*unused*/, void* /*unused*/)
{ {
SInt16 major, minor; SInt16 major, minor;
if (!ProtocolUtil::readf(m_stream, kMsgHello, &major, &minor)) { if (!ProtocolUtil::readf(m_stream, kMsgHello, &major, &minor)) {
@ -709,17 +710,17 @@ Client::handleHello(const Event&, void*)
} }
void void
Client::handleSuspend(const Event&, void*) Client::handleSuspend(const Event& /*unused*/, void* /*unused*/)
{ {
LOG((CLOG_INFO "suspend")); LOG((CLOG_INFO "suspend"));
m_suspended = true; m_suspended = true;
bool wasConnected = isConnected(); bool wasConnected = isConnected();
disconnect(NULL); disconnect(nullptr);
m_connectOnResume = wasConnected; m_connectOnResume = wasConnected;
} }
void void
Client::handleResume(const Event&, void*) Client::handleResume(const Event& /*unused*/, void* /*unused*/)
{ {
LOG((CLOG_INFO "resume")); LOG((CLOG_INFO "resume"));
m_suspended = false; m_suspended = false;
@ -730,13 +731,13 @@ Client::handleResume(const Event&, void*)
} }
void void
Client::handleFileChunkSending(const Event& event, void*) Client::handleFileChunkSending(const Event& event, void* /*unused*/)
{ {
sendFileChunk(event.getData()); sendFileChunk(event.getData());
} }
void void
Client::handleFileRecieveCompleted(const Event& event, void*) Client::handleFileRecieveCompleted(const Event& /*event*/, void* /*unused*/)
{ {
onFileRecieveCompleted(); onFileRecieveCompleted();
} }
@ -752,13 +753,13 @@ Client::onFileRecieveCompleted()
} }
void void
Client::handleStopRetry(const Event&, void*) Client::handleStopRetry(const Event& /*unused*/, void* /*unused*/)
{ {
m_args.m_restartable = false; m_args.m_restartable = false;
} }
void void
Client::writeToDropDirThread(void*) Client::writeToDropDirThread(void* /*unused*/)
{ {
LOG((CLOG_DEBUG "starting write to drop dir thread")); LOG((CLOG_DEBUG "starting write to drop dir thread"));
@ -773,13 +774,13 @@ Client::writeToDropDirThread(void*)
void void
Client::dragInfoReceived(UInt32 fileNum, String data) Client::dragInfoReceived(UInt32 fileNum, String data)
{ {
// TODO: fix duplicate function from CServer // TODO(andrew): fix duplicate function from CServer
if (!m_args.m_enableDragDrop) { if (!m_args.m_enableDragDrop) {
LOG((CLOG_DEBUG "drag drop not enabled, ignoring drag info.")); LOG((CLOG_DEBUG "drag drop not enabled, ignoring drag info."));
return; return;
} }
DragInformation::parseDragInfo(m_dragFileList, fileNum, data); DragInformation::parseDragInfo(m_dragFileList, fileNum, std::move(data));
m_screen->startDraggingFiles(m_dragFileList); m_screen->startDraggingFiles(m_dragFileList);
} }
@ -793,7 +794,7 @@ Client::isReceivedFileSizeValid()
void void
Client::sendFileToServer(const char* filename) Client::sendFileToServer(const char* filename)
{ {
if (m_sendFileThread != NULL) { if (m_sendFileThread != nullptr) {
StreamChunker::interruptFile(); StreamChunker::interruptFile();
} }
@ -807,14 +808,14 @@ void
Client::sendFileThread(void* filename) Client::sendFileThread(void* filename)
{ {
try { try {
char* name = static_cast<char*>(filename); auto* name = static_cast<char*>(filename);
StreamChunker::sendFile(name, m_events, this); StreamChunker::sendFile(name, m_events, this);
} }
catch (std::runtime_error& error) { catch (std::runtime_error& error) {
LOG((CLOG_ERR "failed sending file chunks: %s", error.what())); LOG((CLOG_ERR "failed sending file chunks: %s", error.what()));
} }
m_sendFileThread = NULL; m_sendFileThread = nullptr;
} }
void void

View File

@ -57,9 +57,9 @@ public:
as its name and \p address as the server's address and \p factory as its name and \p address as the server's address and \p factory
to create the socket. \p screen is the local screen. 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, const NetworkAddress& address, ISocketFactory* socketFactory,
synergy::Screen* screen, ClientArgs const& args); synergy::Screen* screen, ClientArgs args);
~Client(); ~Client();
@ -137,7 +137,7 @@ public:
virtual void* getEventTarget() const; virtual void* getEventTarget() const;
virtual bool getClipboard(ClipboardID id, IClipboard*) const; virtual bool getClipboard(ClipboardID id, IClipboard*) const;
virtual void getShape(SInt32& x, SInt32& y, 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; virtual void getCursorPos(SInt32& x, SInt32& y) const;
// IClient overrides // IClient overrides
@ -154,8 +154,8 @@ public:
virtual void keyUp(KeyID, KeyModifierMask, KeyButton); virtual void keyUp(KeyID, KeyModifierMask, KeyButton);
virtual void mouseDown(ButtonID); virtual void mouseDown(ButtonID);
virtual void mouseUp(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 mouseRelativeMove(SInt32 dx, SInt32 dy);
virtual void mouseWheel(SInt32 xDelta, SInt32 yDelta); virtual void mouseWheel(SInt32 xDelta, SInt32 yDelta);
virtual void screensaver(bool activate); virtual void screensaver(bool activate);
virtual void resetOptions(); virtual void resetOptions();
@ -209,12 +209,12 @@ private:
bool m_active; bool m_active;
bool m_suspended; bool m_suspended;
bool m_connectOnResume; bool m_connectOnResume;
bool m_ownClipboard[kClipboardEnd]; bool m_ownClipboard[kClipboardEnd]{};
bool m_sentClipboard[kClipboardEnd]; bool m_sentClipboard[kClipboardEnd]{};
IClipboard::Time m_timeClipboard[kClipboardEnd]; IClipboard::Time m_timeClipboard[kClipboardEnd]{};
String m_dataClipboard[kClipboardEnd]; String m_dataClipboard[kClipboardEnd];
IEventQueue* m_events; IEventQueue* m_events;
std::size_t m_expectedFileSize; std::size_t m_expectedFileSize{};
String m_receivedFileData; String m_receivedFileData;
DragFileList m_dragFileList; DragFileList m_dragFileList;
String m_dragFileExt; String m_dragFileExt;

View File

@ -18,19 +18,19 @@
#include "client/ServerProxy.h" #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 "client/Client.h"
#include "core/FileChunk.h"
#include "core/ClipboardChunk.h"
#include "core/StreamChunker.h"
#include "core/Clipboard.h" #include "core/Clipboard.h"
#include "core/ClipboardChunk.h"
#include "core/FileChunk.h"
#include "core/ProtocolUtil.h" #include "core/ProtocolUtil.h"
#include "core/StreamChunker.h"
#include "core/option_types.h" #include "core/option_types.h"
#include "core/protocol_types.h" #include "core/protocol_types.h"
#include "io/IStream.h" #include "io/IStream.h"
#include "base/Log.h"
#include "base/IEventQueue.h"
#include "base/TMethodEventJob.h"
#include "base/XBase.h"
#include <memory> #include <memory>
@ -50,7 +50,7 @@ ServerProxy::ServerProxy(Client* client, synergy::IStream* stream, IEventQueue*
m_dyMouse(0), m_dyMouse(0),
m_ignoreMouse(false), m_ignoreMouse(false),
m_keepAliveAlarm(0.0), m_keepAliveAlarm(0.0),
m_keepAliveAlarmTimer(NULL), m_keepAliveAlarmTimer(nullptr),
m_parser(&ServerProxy::parseHandshakeMessage), m_parser(&ServerProxy::parseHandshakeMessage),
m_events(events) m_events(events)
{ {
@ -58,8 +58,9 @@ ServerProxy::ServerProxy(Client* client, synergy::IStream* stream, IEventQueue*
assert(m_stream != NULL); assert(m_stream != NULL);
// initialize modifier translation table // initialize modifier translation table
for (KeyModifierID id = 0; id < kKeyModifierIDLast; ++id) for (KeyModifierID id = 0; id < kKeyModifierIDLast; ++id) {
m_modifierTranslationTable[id] = id; m_modifierTranslationTable[id] = id;
}
// handle data on stream // handle data on stream
m_events->adoptHandler(m_events->forIStream().inputReady(), m_events->adoptHandler(m_events->forIStream().inputReady(),
@ -86,14 +87,14 @@ ServerProxy::~ServerProxy()
void void
ServerProxy::resetKeepAliveAlarm() ServerProxy::resetKeepAliveAlarm()
{ {
if (m_keepAliveAlarmTimer != NULL) { if (m_keepAliveAlarmTimer != nullptr) {
m_events->removeHandler(Event::kTimer, m_keepAliveAlarmTimer); m_events->removeHandler(Event::kTimer, m_keepAliveAlarmTimer);
m_events->deleteTimer(m_keepAliveAlarmTimer); m_events->deleteTimer(m_keepAliveAlarmTimer);
m_keepAliveAlarmTimer = NULL; m_keepAliveAlarmTimer = nullptr;
} }
if (m_keepAliveAlarm > 0.0) { if (m_keepAliveAlarm > 0.0) {
m_keepAliveAlarmTimer = m_keepAliveAlarmTimer =
m_events->newOneShotTimer(m_keepAliveAlarm, NULL); m_events->newOneShotTimer(m_keepAliveAlarm, nullptr);
m_events->adoptHandler(Event::kTimer, m_keepAliveAlarmTimer, m_events->adoptHandler(Event::kTimer, m_keepAliveAlarmTimer,
new TMethodEventJob<ServerProxy>(this, new TMethodEventJob<ServerProxy>(this,
&ServerProxy::handleKeepAliveAlarm)); &ServerProxy::handleKeepAliveAlarm));
@ -108,7 +109,7 @@ ServerProxy::setKeepAliveRate(double rate)
} }
void void
ServerProxy::handleData(const Event&, void*) ServerProxy::handleData(const Event& /*unused*/, void* /*unused*/)
{ {
// handle messages until there are no more. first read message code. // handle messages until there are no more. first read message code.
UInt8 code[4]; UInt8 code[4];
@ -179,7 +180,7 @@ ServerProxy::parseHandshakeMessage(const UInt8* code)
else if (memcmp(code, kMsgCClose, 4) == 0) { else if (memcmp(code, kMsgCClose, 4) == 0) {
// server wants us to hangup // server wants us to hangup
LOG((CLOG_DEBUG1 "recv close")); LOG((CLOG_DEBUG1 "recv close"));
m_client->disconnect(NULL); m_client->disconnect(nullptr);
return kDisconnect; return kDisconnect;
} }
@ -307,7 +308,7 @@ ServerProxy::parseMessage(const UInt8* code)
else if (memcmp(code, kMsgCClose, 4) == 0) { else if (memcmp(code, kMsgCClose, 4) == 0) {
// server wants us to hangup // server wants us to hangup
LOG((CLOG_DEBUG1 "recv close")); LOG((CLOG_DEBUG1 "recv close"));
m_client->disconnect(NULL); m_client->disconnect(nullptr);
return kDisconnect; return kDisconnect;
} }
else if (memcmp(code, kMsgEBad, 4) == 0) { else if (memcmp(code, kMsgEBad, 4) == 0) {
@ -332,7 +333,7 @@ ServerProxy::parseMessage(const UInt8* code)
} }
void void
ServerProxy::handleKeepAliveAlarm(const Event&, void*) ServerProxy::handleKeepAliveAlarm(const Event& /*unused*/, void* /*unused*/)
{ {
LOG((CLOG_NOTE "server is dead")); LOG((CLOG_NOTE "server is dead"));
m_client->disconnect("server is not responding"); m_client->disconnect("server is not responding");
@ -466,9 +467,9 @@ ServerProxy::translateKey(KeyID id) const
if (id2 != kKeyModifierIDNull) { if (id2 != kKeyModifierIDNull) {
return s_translationTable[m_modifierTranslationTable[id2]][side]; return s_translationTable[m_modifierTranslationTable[id2]][side];
} }
else {
return id; return id;
}
} }
KeyModifierMask KeyModifierMask
@ -605,8 +606,9 @@ ServerProxy::keyDown()
KeyModifierMask mask2 = translateModifierMask( KeyModifierMask mask2 = translateModifierMask(
static_cast<KeyModifierMask>(mask)); static_cast<KeyModifierMask>(mask));
if (id2 != static_cast<KeyID>(id) || if (id2 != static_cast<KeyID>(id) ||
mask2 != static_cast<KeyModifierMask>(mask)) mask2 != static_cast<KeyModifierMask>(mask)) {
LOG((CLOG_DEBUG1 "key down translated to id=0x%08x, mask=0x%04x", id2, mask2)); LOG((CLOG_DEBUG1 "key down translated to id=0x%08x, mask=0x%04x", id2, mask2));
}
// forward // forward
m_client->keyDown(id2, mask2, button); m_client->keyDown(id2, mask2, button);
@ -629,8 +631,9 @@ ServerProxy::keyRepeat()
KeyModifierMask mask2 = translateModifierMask( KeyModifierMask mask2 = translateModifierMask(
static_cast<KeyModifierMask>(mask)); static_cast<KeyModifierMask>(mask));
if (id2 != static_cast<KeyID>(id) || if (id2 != static_cast<KeyID>(id) ||
mask2 != static_cast<KeyModifierMask>(mask)) mask2 != static_cast<KeyModifierMask>(mask)) {
LOG((CLOG_DEBUG1 "key repeat translated to id=0x%08x, mask=0x%04x", id2, mask2)); LOG((CLOG_DEBUG1 "key repeat translated to id=0x%08x, mask=0x%04x", id2, mask2));
}
// forward // forward
m_client->keyRepeat(id2, mask2, count, button); m_client->keyRepeat(id2, mask2, count, button);
@ -652,8 +655,9 @@ ServerProxy::keyUp()
KeyModifierMask mask2 = translateModifierMask( KeyModifierMask mask2 = translateModifierMask(
static_cast<KeyModifierMask>(mask)); static_cast<KeyModifierMask>(mask));
if (id2 != static_cast<KeyID>(id) || if (id2 != static_cast<KeyID>(id) ||
mask2 != static_cast<KeyModifierMask>(mask)) mask2 != static_cast<KeyModifierMask>(mask)) {
LOG((CLOG_DEBUG1 "key up translated to id=0x%08x, mask=0x%04x", id2, mask2)); LOG((CLOG_DEBUG1 "key up translated to id=0x%08x, mask=0x%04x", id2, mask2));
}
// forward // forward
m_client->keyUp(id2, mask2, button); m_client->keyUp(id2, mask2, button);
@ -809,7 +813,7 @@ ServerProxy::setOptions()
m_client->setOptions(options); m_client->setOptions(options);
// update modifier table // update modifier table
for (UInt32 i = 0, n = (UInt32)options.size(); i < n; i += 2) { for (UInt32 i = 0, n = static_cast<UInt32>(options.size()); i < n; i += 2) {
KeyModifierID id = kKeyModifierIDNull; KeyModifierID id = kKeyModifierIDNull;
if (options[i] == kOptionModifierMapForShift) { if (options[i] == kOptionModifierMapForShift) {
id = kKeyModifierIDShift; id = kKeyModifierIDShift;
@ -845,7 +849,7 @@ ServerProxy::setOptions()
void void
ServerProxy::queryInfo() ServerProxy::queryInfo()
{ {
ClientInfo info; ClientInfo info{};
m_client->getShape(info.m_x, info.m_y, info.m_w, info.m_h); m_client->getShape(info.m_x, info.m_y, info.m_w, info.m_h);
m_client->getCursorPos(info.m_mx, info.m_my); m_client->getCursorPos(info.m_mx, info.m_my);
sendInfo(info); sendInfo(info);
@ -870,7 +874,7 @@ ServerProxy::fileChunkReceived()
m_events->addEvent(Event(m_events->forFile().fileRecieveCompleted(), m_client)); m_events->addEvent(Event(m_events->forFile().fileRecieveCompleted(), m_client));
} }
else if (result == kStart) { else if (result == kStart) {
if (m_client->getDragFileList().size() > 0) { if (!m_client->getDragFileList().empty()) {
String filename = m_client->getDragFileList().at(0).getFilename(); String filename = m_client->getDragFileList().at(0).getFilename();
LOG((CLOG_DEBUG "start receiving %s", filename.c_str())); LOG((CLOG_DEBUG "start receiving %s", filename.c_str()));
} }
@ -889,7 +893,7 @@ ServerProxy::dragInfoReceived()
} }
void void
ServerProxy::handleClipboardSendingEvent(const Event& event, void*) ServerProxy::handleClipboardSendingEvent(const Event& event, void* /*unused*/)
{ {
ClipboardChunk::send(m_stream, event.getData()); ClipboardChunk::send(m_stream, event.getData());
} }

View File

@ -123,7 +123,7 @@ private:
bool m_ignoreMouse; bool m_ignoreMouse;
KeyModifierID m_modifierTranslationTable[kKeyModifierIDLast]; KeyModifierID m_modifierTranslationTable[kKeyModifierIDLast]{};
double m_keepAliveAlarm; double m_keepAliveAlarm;
EventQueueTimer* m_keepAliveAlarmTimer; EventQueueTimer* m_keepAliveAlarmTimer;

View File

@ -18,23 +18,23 @@
#include "core/App.h" #include "core/App.h"
#include "base/Log.h"
#include "common/Version.h"
#include "core/protocol_types.h"
#include "arch/Arch.h" #include "arch/Arch.h"
#include "base/XBase.h"
#include "arch/XArch.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/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 <iostream> #include <iostream>
#include <stdio.h> #include <cstdio>
#if SYSAPI_WIN32 #if SYSAPI_WIN32
#include "arch/win32/ArchMiscWindows.h" #include "arch/win32/ArchMiscWindows.h"
@ -137,7 +137,7 @@ App::run(int argc, char** argv)
} }
int int
App::daemonMainLoop(int, const char**) App::daemonMainLoop(int /*unused*/, const char** /*unused*/)
{ {
#if SYSAPI_WIN32 #if SYSAPI_WIN32
SystemLogger sysLogger(daemonName(), false); SystemLogger sysLogger(daemonName(), false);
@ -150,7 +150,7 @@ App::daemonMainLoop(int, const char**)
void void
App::setupFileLogging() App::setupFileLogging()
{ {
if (argsBase().m_logFile != NULL) { if (argsBase().m_logFile != nullptr) {
m_fileLog = new FileLogOutputter(argsBase().m_logFile); m_fileLog = new FileLogOutputter(argsBase().m_logFile);
CLOG->insert(m_fileLog); CLOG->insert(m_fileLog);
LOG((CLOG_DEBUG1 "logging to file (%s) enabled", argsBase().m_logFile)); LOG((CLOG_DEBUG1 "logging to file (%s) enabled", argsBase().m_logFile));
@ -161,7 +161,7 @@ void
App::loggingFilterWarning() App::loggingFilterWarning()
{ {
if (CLOG->getFilter() > CLOG->getConsoleMaxLevel()) { 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)", LOG((CLOG_WARN "log messages above %s are NOT sent to console (use file logging)",
CLOG->getFilterName(CLOG->getConsoleMaxLevel()))); 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 // 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. // 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. // a better way would be to use xauth cookie and dbus to get access to X.
if (!argsBase().m_runAsUid != -1) { if (static_cast<int>((!(argsBase().m_runAsUid) == 0 != -1))) {
if (setuid(argsBase().m_runAsUid) == 0) { if (setuid(argsBase().m_runAsUid) == 0) {
LOG((CLOG_DEBUG "process uid was set to: %d", argsBase().m_runAsUid)); LOG((CLOG_DEBUG "process uid was set to: %d", argsBase().m_runAsUid));
} }
@ -231,9 +231,9 @@ App::cleanupIpcClient()
} }
void void
App::handleIpcMessage(const Event& e, void*) App::handleIpcMessage(const Event& e, void* /*unused*/)
{ {
IpcMessage* m = static_cast<IpcMessage*>(e.getDataObject()); auto* m = dynamic_cast<IpcMessage*>(e.getDataObject());
if (m->type() == kIpcShutdown) { if (m->type() == kIpcShutdown) {
LOG((CLOG_INFO "got ipc shutdown message")); LOG((CLOG_INFO "got ipc shutdown message"));
m_events->addEvent(Event(Event::kQuit)); m_events->addEvent(Event(Event::kQuit));
@ -241,7 +241,7 @@ App::handleIpcMessage(const Event& e, void*)
} }
void void
App::runEventsLoop(void*) App::runEventsLoop(void* /*unused*/)
{ {
m_events->loop(); m_events->loop();
@ -257,24 +257,23 @@ App::runEventsLoop(void*)
// //
MinimalApp::MinimalApp() : MinimalApp::MinimalApp() :
App(NULL, new ArgsBase()) App(nullptr, new ArgsBase())
{ {
m_arch.init(); m_arch.init();
setEvents(m_events); setEvents(m_events);
} }
MinimalApp::~MinimalApp() MinimalApp::~MinimalApp()
{ = default;
}
int int
MinimalApp::standardStartup(int argc, char** argv) MinimalApp::standardStartup(int /*argc*/, char** /*argv*/)
{ {
return 0; return 0;
} }
int int
MinimalApp::runInner(int argc, char** argv, ILogOutputter* outputter, StartupFunc startup) MinimalApp::runInner(int /*argc*/, char** /*argv*/, ILogOutputter* /*outputter*/, StartupFunc /*startup*/)
{ {
return 0; return 0;
} }
@ -291,7 +290,7 @@ MinimalApp::mainLoop()
} }
int int
MinimalApp::foregroundStartup(int argc, char** argv) MinimalApp::foregroundStartup(int /*argc*/, char** /*argv*/)
{ {
return 0; return 0;
} }
@ -299,7 +298,7 @@ MinimalApp::foregroundStartup(int argc, char** argv)
synergy::Screen* synergy::Screen*
MinimalApp::createScreen() MinimalApp::createScreen()
{ {
return NULL; return nullptr;
} }
void void
@ -308,7 +307,7 @@ MinimalApp::loadConfig()
} }
bool bool
MinimalApp::loadConfig(const String& pathname) MinimalApp::loadConfig(const String& /*pathname*/)
{ {
return false; return false;
} }
@ -326,6 +325,6 @@ MinimalApp::daemonName() const
} }
void void
MinimalApp::parseArgs(int argc, const char* const* argv) MinimalApp::parseArgs(int /*argc*/, const char* const* /*argv*/)
{ {
} }

View File

@ -27,8 +27,7 @@ m_app(nullptr)
} }
AppUtil::~AppUtil() AppUtil::~AppUtil()
{ = default;
}
void void
AppUtil::adoptApp(IApp* app) AppUtil::adoptApp(IApp* app)

View File

@ -17,20 +17,20 @@
#include "core/ArgParser.h" #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/Log.h"
#include "base/String.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 #ifdef WINAPI_MSWINDOWS
#include <VersionHelpers.h> #include <VersionHelpers.h>
#endif #endif
ArgsBase* ArgParser::m_argsBase = NULL; ArgsBase* ArgParser::m_argsBase = nullptr;
ArgParser::ArgParser(App* app) : ArgParser::ArgParser(App* app) :
m_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)) { if (parsePlatformArg(args, argc, argv, i)) {
continue; continue;
} }
else if (parseGenericArgs(argc, argv, i)) { if (parseGenericArgs(argc, argv, i)) {
continue; continue;
} }
else if (parseDeprecatedArgs(argc, argv, i)) { else if (parseDeprecatedArgs(argc, argv, i)) {
@ -70,11 +70,7 @@ ArgParser::parseServerArgs(ServerArgs& args, int argc, const char* const* argv)
} }
} }
if (checkUnexpectedArgs()) { return !checkUnexpectedArgs();
return false;
}
return true;
} }
bool bool
@ -88,19 +84,19 @@ ArgParser::parseClientArgs(ClientArgs& args, int argc, const char* const* argv)
if (parsePlatformArg(args, argc, argv, i)) { if (parsePlatformArg(args, argc, argv, i)) {
continue; continue;
} }
else if (parseGenericArgs(argc, argv, i)) { if (parseGenericArgs(argc, argv, i)) {
continue; continue;
} }
else if (parseDeprecatedArgs(argc, argv, i)) { else if (parseDeprecatedArgs(argc, argv, i)) {
continue; continue;
} }
else if (isArg(i, argc, argv, NULL, "--camp")) { else if (isArg(i, argc, argv, nullptr, "--camp")) {
// ignore -- included for backwards compatibility // 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 // 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 // define scroll
args.m_yscroll = atoi(argv[++i]); args.m_yscroll = atoi(argv[++i]);
} }
@ -122,11 +118,7 @@ ArgParser::parseClientArgs(ClientArgs& args, int argc, const char* const* argv)
return false; return false;
} }
if (checkUnexpectedArgs()) { return !checkUnexpectedArgs();
return false;
}
return true;
} }
bool bool
@ -155,7 +147,7 @@ ArgParser::parsePlatformArg(ArgsBase& argsBase, const int& argc, const char* con
argsBase.m_display = argv[++i]; 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; argsBase.m_disableXInitThreads = true;
} }
@ -175,31 +167,31 @@ bool
ArgParser::parseToolArgs(ToolArgs& args, int argc, const char* const* argv) ArgParser::parseToolArgs(ToolArgs& args, int argc, const char* const* argv)
{ {
for (int i = 1; i < argc; ++i) { 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; args.m_printActiveDesktopName = true;
return 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; args.m_loginAuthenticate = true;
return 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; args.m_getInstalledDir = true;
return 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; args.m_getProfileDir = true;
return 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; args.m_getArch = true;
return 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; args.m_notifyActivation = true;
return 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; args.m_notifyUpdate = true;
return true; return true;
} }
@ -225,7 +217,7 @@ ArgParser::parseGenericArgs(int argc, const char* const* argv, int& i)
// not a daemon // not a daemon
argsBase().m_daemon = false; argsBase().m_daemon = false;
} }
else if (isArg(i, argc, argv, NULL, "--daemon")) { else if (isArg(i, argc, argv, nullptr, "--daemon")) {
// daemonize // daemonize
argsBase().m_daemon = true; argsBase().m_daemon = true;
} }
@ -237,38 +229,38 @@ ArgParser::parseGenericArgs(int argc, const char* const* argv, int& i)
// don't try to restart // don't try to restart
argsBase().m_restartable = false; argsBase().m_restartable = false;
} }
else if (isArg(i, argc, argv, NULL, "--restart")) { else if (isArg(i, argc, argv, nullptr, "--restart")) {
// try to restart // try to restart
argsBase().m_restartable = true; argsBase().m_restartable = true;
} }
else if (isArg(i, argc, argv, "-z", NULL)) { else if (isArg(i, argc, argv, "-z", nullptr)) {
argsBase().m_backend = true; 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; argsBase().m_noHooks = true;
} }
else if (isArg(i, argc, argv, "-h", "--help")) { else if (isArg(i, argc, argv, "-h", "--help")) {
if (m_app) { if (m_app != nullptr) {
m_app->help(); m_app->help();
} }
argsBase().m_shouldExit = true; argsBase().m_shouldExit = true;
} }
else if (isArg(i, argc, argv, NULL, "--version")) { else if (isArg(i, argc, argv, nullptr, "--version")) {
if (m_app) { if (m_app != nullptr) {
m_app->version(); m_app->version();
} }
argsBase().m_shouldExit = true; argsBase().m_shouldExit = true;
} }
else if (isArg(i, argc, argv, NULL, "--ipc")) { else if (isArg(i, argc, argv, nullptr, "--ipc")) {
argsBase().m_enableIpc = true; 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 // 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 // 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; bool useDragDrop = true;
#ifdef WINAPI_XWINDOWS #ifdef WINAPI_XWINDOWS
@ -290,18 +282,18 @@ ArgParser::parseGenericArgs(int argc, const char* const* argv, int& i)
argsBase().m_enableDragDrop = true; 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")); LOG((CLOG_INFO "--enable-crypto ignored, TLS is no longer supported in Synergy Core"));
return false; 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]; 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]; argsBase().m_pluginDirectory = argv[++i];
} }
#if WINAPI_XWINDOWS #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]); argsBase().m_runAsUid = std::stoi(argv[++i]);
} }
#endif #endif
@ -316,27 +308,27 @@ ArgParser::parseGenericArgs(int argc, const char* const* argv, int& i)
bool bool
ArgParser::parseDeprecatedArgs(int argc, const char* const* argv, int& i) 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")); LOG((CLOG_NOTE "--crypto-pass is deprecated"));
i++; i++;
return true; 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")); LOG((CLOG_NOTE "--res-w is deprecated"));
i++; i++;
return true; 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")); LOG((CLOG_NOTE "--res-h is deprecated"));
i++; i++;
return true; 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")); LOG((CLOG_NOTE "--prm-wc is deprecated"));
i++; i++;
return true; 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")); LOG((CLOG_NOTE "--prm-hc is deprecated"));
i++; i++;
return true; return true;
@ -351,8 +343,8 @@ ArgParser::isArg(
const char* name1, const char* name2, const char* name1, const char* name2,
int minRequiredParameters) int minRequiredParameters)
{ {
if ((name1 != NULL && strcmp(argv[argi], name1) == 0) || if ((name1 != nullptr && strcmp(argv[argi], name1) == 0) ||
(name2 != NULL && strcmp(argv[argi], name2) == 0)) { (name2 != nullptr && strcmp(argv[argi], name2) == 0)) {
// match. check args left. // match. check args left.
if (argi + minRequiredParameters >= argc) { if (argi + minRequiredParameters >= argc) {
LOG((CLOG_PRINT "%s: missing arguments for `%s'" BYE, LOG((CLOG_PRINT "%s: missing arguments for `%s'" BYE,
@ -379,7 +371,7 @@ ArgParser::splitCommandString(String& command, std::vector<String>& argv)
searchDoubleQuotes(command, leftDoubleQuote, rightDoubleQuote); searchDoubleQuotes(command, leftDoubleQuote, rightDoubleQuote);
size_t startPos = 0; size_t startPos = 0;
size_t space = command.find(" ", startPos); size_t space = command.find(' ', startPos);
while (space != String::npos) { while (space != String::npos) {
bool ignoreThisSpace = false; bool ignoreThisSpace = false;
@ -401,11 +393,11 @@ ArgParser::splitCommandString(String& command, std::vector<String>& argv)
// find next space // find next space
if (ignoreThisSpace) { if (ignoreThisSpace) {
space = command.find(" ", rightDoubleQuote + 1); space = command.find(' ', rightDoubleQuote + 1);
} }
else { else {
startPos = space + 1; 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; left = String::npos;
right = String::npos; right = String::npos;
left = command.find("\"", startPos); left = command.find('\"', startPos);
if (left != String::npos) { if (left != String::npos) {
right = command.find("\"", left + 1); right = command.find('\"', left + 1);
if (right != String::npos) { if (right != String::npos) {
result = true; result = true;
} }
@ -456,7 +448,7 @@ ArgParser::getArgv(std::vector<String>& argsArray)
// we use the c string pointers from argsArray and assign // we use the c string pointers from argsArray and assign
// them to the inner array. So caller only need to use // them to the inner array. So caller only need to use
// delete[] to delete the outer array // 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++) { for (size_t i = 0; i < argc; i++) {
argv[i] = argsArray[i].c_str(); argv[i] = argsArray[i].c_str();
@ -466,12 +458,12 @@ ArgParser::getArgv(std::vector<String>& argsArray)
} }
String String
ArgParser::assembleCommand(std::vector<String>& argsArray, String ignoreArg, int parametersRequired) ArgParser::assembleCommand(std::vector<String>& argsArray, const String& ignoreArg, int parametersRequired)
{ {
String result; String result;
for (std::vector<String>::iterator it = argsArray.begin(); it != argsArray.end(); ++it) { for (auto it = argsArray.begin(); it != argsArray.end(); ++it) {
if (it->compare(ignoreArg) == 0) { if (*it == ignoreArg) {
it = it + parametersRequired; it = it + parametersRequired;
continue; continue;
} }

View File

@ -48,7 +48,7 @@ public:
static void removeDoubleQuotes(String& arg); static void removeDoubleQuotes(String& arg);
static const char** getArgv(std::vector<String>& argsArray); static const char** getArgv(std::vector<String>& argsArray);
static String assembleCommand(std::vector<String>& argsArray, static String assembleCommand(std::vector<String>& argsArray,
String ignoreArg = "", int parametersRequired = 0); const String& ignoreArg = "", int parametersRequired = 0);
private: private:
void updateCommonArgs(const char* const* argv); void updateCommonArgs(const char* const* argv);

View File

@ -34,19 +34,17 @@ m_runAsUid(-1),
m_backend(false), m_backend(false),
m_restartable(true), m_restartable(true),
m_noHooks(false), m_noHooks(false),
m_pname(NULL), m_pname(nullptr),
m_logFilter(NULL), m_logFilter(nullptr),
m_logFile(NULL), m_logFile(nullptr),
m_display(NULL), m_display(nullptr),
m_enableIpc(false), m_enableIpc(false),
m_enableDragDrop(false), m_enableDragDrop(false),
m_shouldExit(false), m_shouldExit(false),
m_synergyAddress(),
m_profileDirectory(""), m_profileDirectory(""),
m_pluginDirectory("") m_pluginDirectory("")
{ {
} }
ArgsBase::~ArgsBase() ArgsBase::~ArgsBase()
{ = default;
}

View File

@ -18,28 +18,28 @@
#include "core/ClientApp.h" #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 "client/Client.h"
#include "common/Version.h"
#include "core/ArgParser.h" #include "core/ArgParser.h"
#include "core/protocol_types.h" #include "core/ClientArgs.h"
#include "core/Screen.h" #include "core/Screen.h"
#include "core/XScreen.h" #include "core/XScreen.h"
#include "core/ClientArgs.h" #include "core/protocol_types.h"
#include "net/NetworkAddress.h"
#include "net/TCPSocketFactory.h"
#include "net/SocketMultiplexer.h"
#include "net/XSocket.h"
#include "mt/Thread.h" #include "mt/Thread.h"
#include "arch/IArchTaskBarReceiver.h" #include "net/NetworkAddress.h"
#include "arch/Arch.h" #include "net/SocketMultiplexer.h"
#include "base/String.h" #include "net/TCPSocketFactory.h"
#include "base/Event.h" #include "net/XSocket.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"
#if SYSAPI_WIN32 #if SYSAPI_WIN32
#include "arch/win32/ArchMiscWindows.h" #include "arch/win32/ArchMiscWindows.h"
@ -58,21 +58,20 @@
#endif #endif
#include <iostream> #include <iostream>
#include <stdio.h> #include <cstdio>
#define RETRY_TIME 1.0 #define RETRY_TIME 1.0
ClientApp::ClientApp(IEventQueue* events) : ClientApp::ClientApp(IEventQueue* events) :
App(events, new ClientArgs()), App(events, new ClientArgs()),
m_client(NULL), m_client(nullptr),
m_clientScreen(NULL), m_clientScreen(nullptr),
m_serverAddress(NULL) m_serverAddress(nullptr)
{ {
} }
ClientApp::~ClientApp() ClientApp::~ClientApp()
{ = default;
}
void void
ClientApp::parseArgs(int argc, const char* const* argv) ClientApp::parseArgs(int argc, const char* const* argv)
@ -192,7 +191,7 @@ ClientApp::updateStatus()
void void
ClientApp::updateStatus(const String& msg) ClientApp::updateStatus(const String& /*msg*/)
{ {
} }
@ -229,7 +228,7 @@ ClientApp::nextRestartTimeout()
void void
ClientApp::handleScreenError(const Event&, void*) ClientApp::handleScreenError(const Event& /*unused*/, void* /*unused*/)
{ {
LOG((CLOG_CRIT "error on screen")); LOG((CLOG_CRIT "error on screen"));
m_events->addEvent(Event(Event::kQuit)); m_events->addEvent(Event(Event::kQuit));
@ -252,7 +251,7 @@ ClientApp::openClientScreen()
void void
ClientApp::closeClientScreen(synergy::Screen* screen) ClientApp::closeClientScreen(synergy::Screen* screen)
{ {
if (screen != NULL) { if (screen != nullptr) {
m_events->removeHandler(m_events->forIScreen().error(), m_events->removeHandler(m_events->forIScreen().error(),
screen->getEventTarget()); screen->getEventTarget());
delete screen; delete screen;
@ -261,10 +260,10 @@ ClientApp::closeClientScreen(synergy::Screen* screen)
void void
ClientApp::handleClientRestart(const Event&, void* vtimer) ClientApp::handleClientRestart(const Event& /*unused*/, void* vtimer)
{ {
// discard old timer // discard old timer
EventQueueTimer* timer = static_cast<EventQueueTimer*>(vtimer); auto* timer = static_cast<EventQueueTimer*>(vtimer);
m_events->deleteTimer(timer); m_events->deleteTimer(timer);
m_events->removeHandler(Event::kTimer, timer); m_events->removeHandler(Event::kTimer, timer);
@ -278,14 +277,14 @@ ClientApp::scheduleClientRestart(double retryTime)
{ {
// install a timer and handler to retry later // install a timer and handler to retry later
LOG((CLOG_DEBUG "retry in %.0f seconds", retryTime)); 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, m_events->adoptHandler(Event::kTimer, timer,
new TMethodEventJob<ClientApp>(this, &ClientApp::handleClientRestart, timer)); new TMethodEventJob<ClientApp>(this, &ClientApp::handleClientRestart, timer));
} }
void void
ClientApp::handleClientConnected(const Event&, void*) ClientApp::handleClientConnected(const Event& /*unused*/, void* /*unused*/)
{ {
LOG((CLOG_NOTE "connected to server")); LOG((CLOG_NOTE "connected to server"));
resetRestartTimeout(); resetRestartTimeout();
@ -294,9 +293,9 @@ ClientApp::handleClientConnected(const Event&, void*)
void void
ClientApp::handleClientFailed(const Event& e, void*) ClientApp::handleClientFailed(const Event& e, void* /*unused*/)
{ {
Client::FailInfo* info = auto* info =
static_cast<Client::FailInfo*>(e.getData()); static_cast<Client::FailInfo*>(e.getData());
updateStatus(String("Failed to connect to server: ") + info->m_what); updateStatus(String("Failed to connect to server: ") + info->m_what);
@ -315,7 +314,7 @@ ClientApp::handleClientFailed(const Event& e, void*)
void void
ClientApp::handleClientDisconnected(const Event&, void*) ClientApp::handleClientDisconnected(const Event& /*unused*/, void* /*unused*/)
{ {
LOG((CLOG_NOTE "disconnected from server")); LOG((CLOG_NOTE "disconnected from server"));
if (!args().m_restartable) { if (!args().m_restartable) {
@ -331,7 +330,7 @@ Client*
ClientApp::openClient(const String& name, const NetworkAddress& address, ClientApp::openClient(const String& name, const NetworkAddress& address,
synergy::Screen* screen) synergy::Screen* screen)
{ {
Client* client = new Client( auto* client = new Client(
m_events, m_events,
name, name,
address, address,
@ -367,7 +366,7 @@ ClientApp::openClient(const String& name, const NetworkAddress& address,
void void
ClientApp::closeClient(Client* client) ClientApp::closeClient(Client* client)
{ {
if (client == NULL) { if (client == nullptr) {
return; return;
} }
@ -390,9 +389,9 @@ bool
ClientApp::startClient() ClientApp::startClient()
{ {
double retryTime; double retryTime;
synergy::Screen* clientScreen = NULL; synergy::Screen* clientScreen = nullptr;
try { try {
if (m_clientScreen == NULL) { if (m_clientScreen == nullptr) {
clientScreen = openClientScreen(); clientScreen = openClientScreen();
m_client = openClient(args().m_name, m_client = openClient(args().m_name,
*m_serverAddress, clientScreen); *m_serverAddress, clientScreen);
@ -426,10 +425,10 @@ ClientApp::startClient()
scheduleClientRestart(retryTime); scheduleClientRestart(retryTime);
return true; return true;
} }
else {
// don't try again // don't try again
return false; return false;
}
} }
@ -438,8 +437,8 @@ ClientApp::stopClient()
{ {
closeClient(m_client); closeClient(m_client);
closeClientScreen(m_clientScreen); closeClientScreen(m_clientScreen);
m_client = NULL; m_client = nullptr;
m_clientScreen = NULL; m_clientScreen = nullptr;
} }
@ -513,9 +512,9 @@ ClientApp::standardStartup(int argc, char** argv)
if (args().m_daemon) { if (args().m_daemon) {
return ARCH->daemonize(daemonName(), &daemonMainLoopStatic); return ARCH->daemonize(daemonName(), &daemonMainLoopStatic);
} }
else {
return mainLoop(); return mainLoop();
}
} }
int int
@ -526,7 +525,7 @@ ClientApp::runInner(int argc, char** argv, ILogOutputter* outputter, StartupFunc
args().m_pname = ARCH->getBasename(argv[0]); args().m_pname = ARCH->getBasename(argv[0]);
// install caller's output filter // install caller's output filter
if (outputter != NULL) { if (outputter != nullptr) {
CLOG->insert(outputter); CLOG->insert(outputter);
} }

View File

@ -17,12 +17,12 @@
*/ */
#include "core/ClientTaskBarReceiver.h" #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 "arch/Arch.h"
#include "base/IEventQueue.h"
#include "base/String.h"
#include "client/Client.h"
#include "common/Version.h" #include "common/Version.h"
#include "mt/Lock.h"
// //
// ClientTaskBarReceiver // ClientTaskBarReceiver
@ -46,7 +46,7 @@ ClientTaskBarReceiver::updateStatus(Client* client, const String& errorMsg)
{ {
// update our status // update our status
m_errorMessage = errorMsg; m_errorMessage = errorMsg;
if (client == NULL) { if (client == nullptr) {
if (m_errorMessage.empty()) { if (m_errorMessage.empty()) {
m_state = kNotRunning; m_state = kNotRunning;
} }
@ -95,7 +95,7 @@ ClientTaskBarReceiver::quit()
} }
void void
ClientTaskBarReceiver::onStatusChanged(Client*) ClientTaskBarReceiver::onStatusChanged(Client* /*unused*/)
{ {
// do nothing // do nothing
} }

View File

@ -63,9 +63,9 @@ public:
private: private:
mutable bool m_open; mutable bool m_open;
mutable Time m_time; mutable Time m_time{};
bool m_owner; bool m_owner;
Time m_timeOwned; Time m_timeOwned{};
bool m_added[kNumFormats]; bool m_added[kNumFormats]{};
String m_data[kNumFormats]; String m_data[kNumFormats];
}; };

View File

@ -17,10 +17,10 @@
#include "core/ClipboardChunk.h" #include "core/ClipboardChunk.h"
#include "base/Log.h"
#include "core/ProtocolUtil.h" #include "core/ProtocolUtil.h"
#include "core/protocol_types.h" #include "core/protocol_types.h"
#include "io/IStream.h" #include "io/IStream.h"
#include "base/Log.h"
#include <cstring> #include <cstring>
size_t ClipboardChunk::s_expectedSize = 0; size_t ClipboardChunk::s_expectedSize = 0;
@ -38,7 +38,7 @@ ClipboardChunk::start(
const String& size) const String& size)
{ {
size_t sizeLength = size.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; char* chunk = start->m_chunk;
chunk[0] = id; chunk[0] = id;
@ -57,7 +57,7 @@ ClipboardChunk::data(
const String& data) const String& data)
{ {
size_t dataSize = data.size(); 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; char* chunkData = chunk->m_chunk;
chunkData[0] = id; chunkData[0] = id;
@ -72,7 +72,7 @@ ClipboardChunk::data(
ClipboardChunk* ClipboardChunk*
ClipboardChunk::end(ClipboardID id, UInt32 sequence) 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; char* chunk = end->m_chunk;
chunk[0] = id; chunk[0] = id;
@ -102,7 +102,7 @@ ClipboardChunk::assemble(synergy::IStream* stream,
dataCached.clear(); dataCached.clear();
return kStart; return kStart;
} }
else if (mark == kDataChunk) { if (mark == kDataChunk) {
dataCached.append(data); dataCached.append(data);
return kNotFinish; return kNotFinish;
} }
@ -111,7 +111,7 @@ ClipboardChunk::assemble(synergy::IStream* stream,
if (id >= kClipboardEnd) { if (id >= kClipboardEnd) {
return kError; 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())); LOG((CLOG_ERR "corrupted clipboard data, expected size=%d actual size=%d", s_expectedSize, dataCached.size()));
return kError; return kError;
} }
@ -125,7 +125,7 @@ ClipboardChunk::assemble(synergy::IStream* stream,
void void
ClipboardChunk::send(synergy::IStream* stream, void* data) ClipboardChunk::send(synergy::IStream* stream, void* data)
{ {
ClipboardChunk* clipboardData = static_cast<ClipboardChunk*>(data); auto* clipboardData = static_cast<ClipboardChunk*>(data);
LOG((CLOG_DEBUG1 "sending clipboard chunk")); LOG((CLOG_DEBUG1 "sending clipboard chunk"));

View File

@ -16,26 +16,26 @@
* along with this program. If not, see <http://www.gnu.org/licenses/>. * along with this program. If not, see <http://www.gnu.org/licenses/>.
*/ */
// 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! // of all the #ifdefs!
#include "core/DaemonApp.h" #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/App.h"
#include "core/ArgParser.h" #include "core/ArgParser.h"
#include "core/ServerArgs.h"
#include "core/ClientArgs.h" #include "core/ClientArgs.h"
#include "core/ServerArgs.h"
#include "ipc/IpcClientProxy.h" #include "ipc/IpcClientProxy.h"
#include "ipc/IpcMessage.h"
#include "ipc/IpcLogOutputter.h" #include "ipc/IpcLogOutputter.h"
#include "ipc/IpcMessage.h"
#include "net/SocketMultiplexer.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 #if SYSAPI_WIN32
@ -52,13 +52,13 @@
#endif #endif
#include <string>
#include <iostream> #include <iostream>
#include <sstream> #include <sstream>
#include <string>
using namespace std; using namespace std;
DaemonApp* DaemonApp::s_instance = NULL; DaemonApp* DaemonApp::s_instance = nullptr;
int int
mainLoopStatic() mainLoopStatic()
@ -68,7 +68,7 @@ mainLoopStatic()
} }
int int
unixMainLoopStatic(int, const char**) unixMainLoopStatic(int /*unused*/, const char** /*unused*/)
{ {
return mainLoopStatic(); return mainLoopStatic();
} }
@ -94,8 +94,7 @@ DaemonApp::DaemonApp() :
} }
DaemonApp::~DaemonApp() DaemonApp::~DaemonApp()
{ = default;
}
int int
DaemonApp::run(int argc, char** argv) DaemonApp::run(int argc, char** argv)
@ -122,8 +121,9 @@ DaemonApp::run(int argc, char** argv)
// default log level to system setting. // default log level to system setting.
string logLevel = arch.setting("LogLevel"); string logLevel = arch.setting("LogLevel");
if (logLevel != "") if (!logLevel.empty()) {
log.setFilter(logLevel.c_str()); log.setFilter(logLevel.c_str());
}
bool foreground = false; bool foreground = false;
@ -170,7 +170,7 @@ DaemonApp::run(int argc, char** argv)
catch (XArch& e) { catch (XArch& e) {
String message = e.what(); String message = e.what();
if (uninstall && (message.find("The service has not been started") != String::npos)) { 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 // HACK: this message happens intermittently, not sure where from but
// it's quite misleading for the user. they thing something has gone // it's quite misleading for the user. they thing something has gone
// horribly wrong, but it's just the service manager reporting a false // horribly wrong, but it's just the service manager reporting a false
@ -288,12 +288,12 @@ DaemonApp::logFilename()
} }
void void
DaemonApp::handleIpcMessage(const Event& e, void*) DaemonApp::handleIpcMessage(const Event& e, void* /*unused*/)
{ {
IpcMessage* m = static_cast<IpcMessage*>(e.getDataObject()); auto* m = dynamic_cast<IpcMessage*>(e.getDataObject());
switch (m->type()) { switch (m->type()) {
case kIpcCommand: { case kIpcCommand: {
IpcCommandMessage* cm = static_cast<IpcCommandMessage*>(m); auto* cm = dynamic_cast<IpcCommandMessage*>(m);
String command = cm->command(); String command = cm->command();
// if empty quotes, clear. // if empty quotes, clear.
@ -306,13 +306,13 @@ DaemonApp::handleIpcMessage(const Event& e, void*)
std::vector<String> argsArray; std::vector<String> argsArray;
ArgParser::splitCommandString(command, argsArray); ArgParser::splitCommandString(command, argsArray);
ArgParser argParser(NULL); ArgParser argParser(nullptr);
const char** argv = argParser.getArgv(argsArray); const char** argv = argParser.getArgv(argsArray);
ServerArgs serverArgs; ServerArgs serverArgs;
ClientArgs clientArgs; ClientArgs clientArgs;
int argc = static_cast<int>(argsArray.size()); auto argc = static_cast<int>(argsArray.size());
bool server = argsArray[0].find("synergys") != String::npos ? true : false; bool server = argsArray[0].find("synergys") != String::npos;
ArgsBase* argBase = NULL; ArgsBase* argBase = nullptr;
if (server) { if (server) {
argParser.parseServerArgs(serverArgs, argc, argv); argParser.parseServerArgs(serverArgs, argc, argv);
@ -364,7 +364,7 @@ DaemonApp::handleIpcMessage(const Event& e, void*)
// next starts. // next starts.
ARCH->setting("Command", command); 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")); ARCH->setting("Elevate", String(cm->elevate() ? "1" : "0"));
} }
catch (XArch& e) { catch (XArch& e) {
@ -381,7 +381,7 @@ DaemonApp::handleIpcMessage(const Event& e, void*)
} }
case kIpcHello: case kIpcHello:
IpcHelloMessage* hm = static_cast<IpcHelloMessage*>(m); auto* hm = dynamic_cast<IpcHelloMessage*>(m);
String type; String type;
switch (hm->clientType()) { switch (hm->clientType()) {
case kIpcClientGui: type = "gui"; break; case kIpcClientGui: type = "gui"; break;

View File

@ -25,20 +25,19 @@
using namespace std; using namespace std;
DragInformation::DragInformation() : DragInformation::DragInformation() :
m_filename(),
m_filesize(0) m_filesize(0)
{ {
} }
void void
DragInformation::parseDragInfo(DragFileList& dragFileList, UInt32 fileNum, String data) DragInformation::parseDragInfo(DragFileList& dragFileList, UInt32 fileNum, const String& data)
{ {
size_t startPos = 0; size_t startPos = 0;
size_t findResult1 = 0; size_t findResult1 = 0;
size_t findResult2 = 0; size_t findResult2 = 0;
dragFileList.clear(); dragFileList.clear();
String slash("\\"); String slash("\\");
if (data.find("/", startPos) != string::npos) { if (data.find('/', startPos) != string::npos) {
slash = "/"; slash = "/";
} }
@ -48,7 +47,7 @@ DragInformation::parseDragInfo(DragFileList& dragFileList, UInt32 fileNum, Strin
findResult2 = data.find_last_of(slash, findResult1); findResult2 = data.find_last_of(slash, findResult1);
if (findResult1 == startPos) { if (findResult1 == startPos) {
//TODO: file number does not match, something goes wrong // TODO(andrew): file number does not match, something goes wrong
break; break;
} }
@ -86,22 +85,22 @@ DragInformation::parseDragInfo(DragFileList& dragFileList, UInt32 fileNum, Strin
} }
String String
DragInformation::getDragFileExtension(String filename) DragInformation::getDragFileExtension(const String& filename)
{ {
size_t findResult = string::npos; size_t findResult = string::npos;
findResult = filename.find_last_of(".", filename.size()); findResult = filename.find_last_of('.', filename.size());
if (findResult != string::npos) { if (findResult != string::npos) {
return filename.substr(findResult + 1, filename.size() - findResult - 1); return filename.substr(findResult + 1, filename.size() - findResult - 1);
} }
else {
return ""; return "";
}
} }
int int
DragInformation::setupDragInfo(DragFileList& fileList, String& output) DragInformation::setupDragInfo(DragFileList& fileList, String& output)
{ {
int size = static_cast<int>(fileList.size()); auto size = static_cast<int>(fileList.size());
for (int i = 0; i < size; ++i) { for (int i = 0; i < size; ++i) {
output.append(fileList.at(i).getFilename()); output.append(fileList.at(i).getFilename());
output.append(","); output.append(",");
@ -113,7 +112,7 @@ DragInformation::setupDragInfo(DragFileList& fileList, String& output)
} }
bool bool
DragInformation::isFileValid(String filename) DragInformation::isFileValid(const String& filename)
{ {
bool result = false; bool result = false;
std::fstream file(filename.c_str(), ios::in|ios::binary); std::fstream file(filename.c_str(), ios::in|ios::binary);
@ -130,7 +129,7 @@ DragInformation::isFileValid(String filename)
size_t size_t
DragInformation::stringToNum(String& str) DragInformation::stringToNum(String& str)
{ {
istringstream iss(str.c_str()); istringstream iss(str);
size_t size; size_t size;
iss >> size; iss >> size;
return size; return size;
@ -147,7 +146,7 @@ DragInformation::getFileSize(String& filename)
// check file size // check file size
file.seekg (0, std::ios::end); file.seekg (0, std::ios::end);
size_t size = (size_t)file.tellg(); auto size = (size_t)file.tellg();
stringstream ss; stringstream ss;
ss << size; ss << size;

View File

@ -34,14 +34,14 @@ public:
size_t getFilesize() { return m_filesize; } size_t getFilesize() { return m_filesize; }
void setFilesize(size_t size) { m_filesize = size; } void setFilesize(size_t size) { m_filesize = size; }
static void parseDragInfo(DragFileList& dragFileList, UInt32 fileNum, String data); static void parseDragInfo(DragFileList& dragFileList, UInt32 fileNum, const String& data);
static String getDragFileExtension(String filename); static String getDragFileExtension(const String& filename);
// helper function to setup drag info // helper function to setup drag info
// example: filename1,filesize1,filename2,filesize2, // example: filename1,filesize1,filename2,filesize2,
// return file count // return file count
static int setupDragInfo(DragFileList& fileList, String& output); static int setupDragInfo(DragFileList& fileList, String& output);
static bool isFileValid(String filename); static bool isFileValid(const String& filename);
private: private:
static size_t stringToNum(String& str); static size_t stringToNum(String& str);

View File

@ -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())); 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; std::fstream file;
String dropTarget = destination; String dropTarget = destination;
#ifdef SYSAPI_WIN32 #ifdef SYSAPI_WIN32

View File

@ -17,11 +17,11 @@
#include "core/FileChunk.h" #include "core/FileChunk.h"
#include "base/Log.h"
#include "base/Stopwatch.h"
#include "core/ProtocolUtil.h" #include "core/ProtocolUtil.h"
#include "core/protocol_types.h" #include "core/protocol_types.h"
#include "io/IStream.h" #include "io/IStream.h"
#include "base/Stopwatch.h"
#include "base/Log.h"
static const UInt16 kIntervalThreshold = 1; static const UInt16 kIntervalThreshold = 1;
@ -35,7 +35,7 @@ FileChunk*
FileChunk::start(const String& size) FileChunk::start(const String& size)
{ {
size_t sizeLength = size.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; char* chunk = start->m_chunk;
chunk[0] = kDataStart; chunk[0] = kDataStart;
memcpy(&chunk[1], size.c_str(), sizeLength); memcpy(&chunk[1], size.c_str(), sizeLength);
@ -47,7 +47,7 @@ FileChunk::start(const String& size)
FileChunk* FileChunk*
FileChunk::data(UInt8* data, size_t dataSize) 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; char* chunkData = chunk->m_chunk;
chunkData[0] = kDataChunk; chunkData[0] = kDataChunk;
memcpy(&chunkData[1], data, dataSize); memcpy(&chunkData[1], data, dataSize);
@ -59,7 +59,7 @@ FileChunk::data(UInt8* data, size_t dataSize)
FileChunk* FileChunk*
FileChunk::end() FileChunk::end()
{ {
FileChunk* end = new FileChunk(FILE_CHUNK_META_SIZE); auto* end = new FileChunk(FILE_CHUNK_META_SIZE);
char* chunk = end->m_chunk; char* chunk = end->m_chunk;
chunk[0] = kDataEnd; chunk[0] = kDataEnd;
chunk[1] = '\0'; chunk[1] = '\0';

View File

@ -36,7 +36,7 @@ public:
static FileChunk* end(); static FileChunk* end();
static int assemble( static int assemble(
synergy::IStream* stream, synergy::IStream* stream,
String& dataCached, String& dataReceived,
size_t& expectedSize); size_t& expectedSize);
static void send( static void send(
synergy::IStream* stream, synergy::IStream* stream,

View File

@ -41,7 +41,7 @@ IClipboard::unmarshall(IClipboard* clipboard, const String& data, Time time)
// read each format // read each format
for (UInt32 i = 0; i < numFormats; ++i) { for (UInt32 i = 0; i < numFormats; ++i) {
// get the format id // get the format id
IClipboard::EFormat format = auto format =
static_cast<IClipboard::EFormat>(readUInt32(index)); static_cast<IClipboard::EFormat>(readUInt32(index));
index += 4; index += 4;
@ -90,7 +90,7 @@ IClipboard::marshall(const IClipboard* clipboard)
++numFormats; ++numFormats;
formatData[format] = formatData[format] =
clipboard->get(static_cast<IClipboard::EFormat>(format)); clipboard->get(static_cast<IClipboard::EFormat>(format));
size += 4 + 4 + (UInt32)formatData[format].size(); size += 4 + 4 + static_cast<UInt32>(formatData[format].size());
} }
} }
@ -102,7 +102,7 @@ IClipboard::marshall(const IClipboard* clipboard)
for (UInt32 format = 0; format != IClipboard::kNumFormats; ++format) { for (UInt32 format = 0; format != IClipboard::kNumFormats; ++format) {
if (clipboard->has(static_cast<IClipboard::EFormat>(format))) { if (clipboard->has(static_cast<IClipboard::EFormat>(format))) {
writeUInt32(&data, format); writeUInt32(&data, format);
writeUInt32(&data, (UInt32)formatData[format].size()); writeUInt32(&data, static_cast<UInt32>(formatData[format].size()));
data += formatData[format]; data += formatData[format];
} }
} }
@ -133,7 +133,7 @@ IClipboard::copy(IClipboard* dst, const IClipboard* src, Time time)
if (dst->empty()) { if (dst->empty()) {
for (SInt32 format = 0; for (SInt32 format = 0;
format != IClipboard::kNumFormats; ++format) { format != IClipboard::kNumFormats; ++format) {
IClipboard::EFormat eFormat = (IClipboard::EFormat)format; auto eFormat = static_cast<IClipboard::EFormat>(format);
if (src->has(eFormat)) { if (src->has(eFormat)) {
dst->add(eFormat, src->get(eFormat)); dst->add(eFormat, src->get(eFormat));
} }
@ -151,7 +151,7 @@ IClipboard::copy(IClipboard* dst, const IClipboard* src, Time time)
UInt32 UInt32
IClipboard::readUInt32(const char* buf) IClipboard::readUInt32(const char* buf)
{ {
const unsigned char* ubuf = reinterpret_cast<const unsigned char*>(buf); const auto* ubuf = reinterpret_cast<const unsigned char*>(buf);
return (static_cast<UInt32>(ubuf[0]) << 24) | return (static_cast<UInt32>(ubuf[0]) << 24) |
(static_cast<UInt32>(ubuf[1]) << 16) | (static_cast<UInt32>(ubuf[1]) << 16) |
(static_cast<UInt32>(ubuf[2]) << 8) | (static_cast<UInt32>(ubuf[2]) << 8) |

View File

@ -19,14 +19,14 @@
#include "core/IKeyState.h" #include "core/IKeyState.h"
#include "base/EventQueue.h" #include "base/EventQueue.h"
#include <cstring>
#include <cstdlib> #include <cstdlib>
#include <cstring>
// //
// IKeyState // IKeyState
// //
IKeyState::IKeyState(IEventQueue* events) IKeyState::IKeyState(IEventQueue* /*events*/)
{ {
} }
@ -38,12 +38,12 @@ IKeyState::KeyInfo*
IKeyState::KeyInfo::alloc(KeyID id, IKeyState::KeyInfo::alloc(KeyID id,
KeyModifierMask mask, KeyButton button, SInt32 count) KeyModifierMask mask, KeyButton button, SInt32 count)
{ {
KeyInfo* info = (KeyInfo*)malloc(sizeof(KeyInfo)); auto* info = static_cast<KeyInfo*>(malloc(sizeof(KeyInfo)));
info->m_key = id; info->m_key = id;
info->m_mask = mask; info->m_mask = mask;
info->m_button = button; info->m_button = button;
info->m_count = count; info->m_count = count;
info->m_screens = NULL; info->m_screens = nullptr;
info->m_screensBuffer[0] = '\0'; info->m_screensBuffer[0] = '\0';
return info; return info;
} }
@ -56,7 +56,7 @@ IKeyState::KeyInfo::alloc(KeyID id,
String screens = join(destinations); String screens = join(destinations);
// build structure // build structure
KeyInfo* info = (KeyInfo*)malloc(sizeof(KeyInfo) + screens.size()); auto* info = static_cast<KeyInfo*>(malloc(sizeof(KeyInfo) + screens.size()));
info->m_key = id; info->m_key = id;
info->m_mask = mask; info->m_mask = mask;
info->m_button = button; info->m_button = button;
@ -69,13 +69,13 @@ IKeyState::KeyInfo::alloc(KeyID id,
IKeyState::KeyInfo* IKeyState::KeyInfo*
IKeyState::KeyInfo::alloc(const KeyInfo& x) IKeyState::KeyInfo::alloc(const KeyInfo& x)
{ {
KeyInfo* info = (KeyInfo*)malloc(sizeof(KeyInfo) + auto* info = static_cast<KeyInfo*>(malloc(sizeof(KeyInfo) +
strlen(x.m_screensBuffer)); strlen(x.m_screensBuffer)));
info->m_key = x.m_key; info->m_key = x.m_key;
info->m_mask = x.m_mask; info->m_mask = x.m_mask;
info->m_button = x.m_button; info->m_button = x.m_button;
info->m_count = x.m_count; 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); strcpy(info->m_screensBuffer, x.m_screensBuffer);
return info; return info;
} }
@ -83,7 +83,7 @@ IKeyState::KeyInfo::alloc(const KeyInfo& x)
bool bool
IKeyState::KeyInfo::isDefault(const char* screens) IKeyState::KeyInfo::isDefault(const char* screens)
{ {
return (screens == NULL || screens[0] == '\0'); return (screens == nullptr || screens[0] == '\0');
} }
bool bool
@ -103,7 +103,7 @@ IKeyState::KeyInfo::contains(const char* screens, const String& name)
match += ":"; match += ":";
match += name; match += name;
match += ":"; match += ":";
return (strstr(screens, match.c_str()) != NULL); return (strstr(screens, match.c_str()) != nullptr);
} }
bool bool
@ -123,19 +123,18 @@ IKeyState::KeyInfo::join(const std::set<String>& destinations)
// which makes searching easy. the string is empty if there are no // which makes searching easy. the string is empty if there are no
// destinations and "*" means all destinations. // destinations and "*" means all destinations.
String screens; String screens;
for (std::set<String>::const_iterator i = destinations.begin(); for (const auto & destination : destinations) {
i != destinations.end(); ++i) { if (destination == "*") {
if (*i == "*") {
screens = "*"; screens = "*";
break; break;
} }
else {
if (screens.empty()) { if (screens.empty()) {
screens = ":"; screens = ":";
} }
screens += *i; screens += destination;
screens += ":"; screens += ":";
}
} }
return screens; return screens;
} }

View File

@ -18,7 +18,7 @@
#include "core/IPlatformScreen.h" #include "core/IPlatformScreen.h"
bool bool
IPlatformScreen::fakeMediaKey(KeyID id) IPlatformScreen::fakeMediaKey(KeyID /*id*/)
{ {
return false; return false;
} }

View File

@ -28,7 +28,7 @@
IPrimaryScreen::ButtonInfo* IPrimaryScreen::ButtonInfo*
IPrimaryScreen::ButtonInfo::alloc(ButtonID id, KeyModifierMask mask) IPrimaryScreen::ButtonInfo::alloc(ButtonID id, KeyModifierMask mask)
{ {
ButtonInfo* info = (ButtonInfo*)malloc(sizeof(ButtonInfo)); auto* info = static_cast<ButtonInfo*>(malloc(sizeof(ButtonInfo)));
info->m_button = id; info->m_button = id;
info->m_mask = mask; info->m_mask = mask;
return info; return info;
@ -37,7 +37,7 @@ IPrimaryScreen::ButtonInfo::alloc(ButtonID id, KeyModifierMask mask)
IPrimaryScreen::ButtonInfo* IPrimaryScreen::ButtonInfo*
IPrimaryScreen::ButtonInfo::alloc(const ButtonInfo& x) IPrimaryScreen::ButtonInfo::alloc(const ButtonInfo& x)
{ {
ButtonInfo* info = (ButtonInfo*)malloc(sizeof(ButtonInfo)); auto* info = static_cast<ButtonInfo*>(malloc(sizeof(ButtonInfo)));
info->m_button = x.m_button; info->m_button = x.m_button;
info->m_mask = x.m_mask; info->m_mask = x.m_mask;
return info; return info;
@ -57,7 +57,7 @@ IPrimaryScreen::ButtonInfo::equal(const ButtonInfo* a, const ButtonInfo* b)
IPrimaryScreen::MotionInfo* IPrimaryScreen::MotionInfo*
IPrimaryScreen::MotionInfo::alloc(SInt32 x, SInt32 y) IPrimaryScreen::MotionInfo::alloc(SInt32 x, SInt32 y)
{ {
MotionInfo* info = (MotionInfo*)malloc(sizeof(MotionInfo)); auto* info = static_cast<MotionInfo*>(malloc(sizeof(MotionInfo)));
info->m_x = x; info->m_x = x;
info->m_y = y; info->m_y = y;
return info; return info;
@ -71,7 +71,7 @@ IPrimaryScreen::MotionInfo::alloc(SInt32 x, SInt32 y)
IPrimaryScreen::WheelInfo* IPrimaryScreen::WheelInfo*
IPrimaryScreen::WheelInfo::alloc(SInt32 xDelta, SInt32 yDelta) IPrimaryScreen::WheelInfo::alloc(SInt32 xDelta, SInt32 yDelta)
{ {
WheelInfo* info = (WheelInfo*)malloc(sizeof(WheelInfo)); auto* info = static_cast<WheelInfo*>(malloc(sizeof(WheelInfo)));
info->m_xDelta = xDelta; info->m_xDelta = xDelta;
info->m_yDelta = yDelta; info->m_yDelta = yDelta;
return info; return info;
@ -85,7 +85,7 @@ IPrimaryScreen::WheelInfo::alloc(SInt32 xDelta, SInt32 yDelta)
IPrimaryScreen::HotKeyInfo* IPrimaryScreen::HotKeyInfo*
IPrimaryScreen::HotKeyInfo::alloc(UInt32 id) IPrimaryScreen::HotKeyInfo::alloc(UInt32 id)
{ {
HotKeyInfo* info = (HotKeyInfo*)malloc(sizeof(HotKeyInfo)); auto* info = static_cast<HotKeyInfo*>(malloc(sizeof(HotKeyInfo)));
info->m_id = id; info->m_id = id;
return info; return info;
} }

View File

@ -17,19 +17,19 @@
*/ */
#include "core/KeyMap.h" #include "core/KeyMap.h"
#include "core/key_types.h"
#include "base/Log.h" #include "base/Log.h"
#include "core/key_types.h"
#include <assert.h> #include <cassert>
#include <cctype> #include <cctype>
#include <cstdlib> #include <cstdlib>
namespace synergy { namespace synergy {
KeyMap::NameToKeyMap* KeyMap::s_nameToKeyMap = NULL; KeyMap::NameToKeyMap* KeyMap::s_nameToKeyMap = nullptr;
KeyMap::NameToModifierMap* KeyMap::s_nameToModifierMap = NULL; KeyMap::NameToModifierMap* KeyMap::s_nameToModifierMap = nullptr;
KeyMap::KeyToNameMap* KeyMap::s_keyToNameMap = NULL; KeyMap::KeyToNameMap* KeyMap::s_keyToNameMap = nullptr;
KeyMap::ModifierToNameMap* KeyMap::s_modifierToNameMap = NULL; KeyMap::ModifierToNameMap* KeyMap::s_modifierToNameMap = nullptr;
KeyMap::KeyMap() : KeyMap::KeyMap() :
m_numGroups(0), m_numGroups(0),
@ -97,8 +97,8 @@ KeyMap::addKeyEntry(const KeyItem& item)
// see if we already have this item; just return if so // see if we already have this item; just return if so
KeyEntryList& entries = groupTable[item.m_group]; KeyEntryList& entries = groupTable[item.m_group];
for (size_t i = 0, n = entries.size(); i < n; ++i) { for (auto & entrie : entries) {
if (entries[i].size() == 1 && newItem == entries[i][0]) { if (entrie.size() == 1 && newItem == entrie[0]) {
return; 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 we can already generate the target as desired then we're done.
if (findCompatibleKey(targetID, group, targetRequired, if (findCompatibleKey(targetID, group, targetRequired,
targetSensitive) != NULL) { targetSensitive) != nullptr) {
return; return;
} }
@ -128,7 +128,7 @@ KeyMap::addKeyAliasEntry(KeyID targetID, SInt32 group,
const KeyItemList* sourceEntry = const KeyItemList* sourceEntry =
findCompatibleKey(sourceID, eg, findCompatibleKey(sourceID, eg,
sourceRequired, sourceSensitive); sourceRequired, sourceSensitive);
if (sourceEntry != NULL && sourceEntry->size() == 1) { if (sourceEntry != nullptr && sourceEntry->size() == 1) {
KeyMap::KeyItem targetItem = sourceEntry->back(); KeyMap::KeyItem targetItem = sourceEntry->back();
targetItem.m_id = targetID; targetItem.m_id = targetID;
targetItem.m_group = eg; targetItem.m_group = eg;
@ -173,17 +173,17 @@ KeyMap::addKeyCombinationEntry(KeyID id, SInt32 group,
// groups for keys, otherwise search just the given group. // groups for keys, otherwise search just the given group.
SInt32 n = 1; SInt32 n = 1;
if (m_composeAcrossGroups) { if (m_composeAcrossGroups) {
n = (SInt32)groupTable.size(); n = static_cast<SInt32>(groupTable.size());
} }
bool found = false; bool found = false;
for (SInt32 gd = 0; gd < n && !found; ++gd) { for (SInt32 gd = 0; gd < n && !found; ++gd) {
SInt32 eg = (group + gd) % getNumGroups(); SInt32 eg = (group + gd) % getNumGroups();
const KeyEntryList& entries = groupTable[eg]; const KeyEntryList& entries = groupTable[eg];
for (size_t j = 0; j < entries.size(); ++j) { for (const auto & entrie : entries) {
if (entries[j].size() == 1) { if (entrie.size() == 1) {
found = true; found = true;
items.push_back(entries[j][0]); items.push_back(entrie[0]);
break; break;
} }
} }
@ -229,9 +229,8 @@ KeyMap::finish()
m_numGroups = findNumGroups(); m_numGroups = findNumGroups();
// make sure every key has the same number of groups // make sure every key has the same number of groups
for (KeyIDMap::iterator i = m_keyIDMap.begin(); for (auto & i : m_keyIDMap) {
i != m_keyIDMap.end(); ++i) { i.second.resize(m_numGroups);
i->second.resize(m_numGroups);
} }
// compute keys that generate each modifier // compute keys that generate each modifier
@ -241,16 +240,14 @@ KeyMap::finish()
void void
KeyMap::foreachKey(ForeachKeyCallback cb, void* userData) KeyMap::foreachKey(ForeachKeyCallback cb, void* userData)
{ {
for (KeyIDMap::iterator i = m_keyIDMap.begin(); for (auto & i : m_keyIDMap) {
i != m_keyIDMap.end(); ++i) { KeyGroupTable& groupTable = i.second;
KeyGroupTable& groupTable = i->second;
for (size_t group = 0; group < groupTable.size(); ++group) { for (size_t group = 0; group < groupTable.size(); ++group) {
KeyEntryList& entryList = groupTable[group]; KeyEntryList& entryList = groupTable[group];
for (size_t j = 0; j < entryList.size(); ++j) { for (auto & itemList : entryList) {
KeyItemList& itemList = entryList[j]; for (auto & k : itemList) {
for (size_t k = 0; k < itemList.size(); ++k) { (*cb)(i.first, static_cast<SInt32>(group),
(*cb)(i->first, static_cast<SInt32>(group), k, userData);
itemList[k], userData);
} }
} }
} }
@ -268,12 +265,12 @@ KeyMap::mapKey(Keystrokes& keys, KeyID id, SInt32 group,
// handle group change // handle group change
if (id == kKeyNextGroup) { if (id == kKeyNextGroup) {
keys.push_back(Keystroke(1, false, false)); keys.emplace_back(1, false, false);
return NULL; return nullptr;
} }
else if (id == kKeyPrevGroup) { if (id == kKeyPrevGroup) {
keys.push_back(Keystroke(-1, false, false)); keys.emplace_back(-1, false, false);
return NULL; return nullptr;
} }
const KeyItem* item; const KeyItem* item;
@ -300,7 +297,7 @@ KeyMap::mapKey(Keystrokes& keys, KeyID id, SInt32 group,
if (!keysForModifierState(0, group, activeModifiers, currentState, if (!keysForModifierState(0, group, activeModifiers, currentState,
desiredMask, desiredMask, 0, keys)) { desiredMask, desiredMask, 0, keys)) {
LOG((CLOG_DEBUG1 "unable to set modifiers %04x", desiredMask)); LOG((CLOG_DEBUG1 "unable to set modifiers %04x", desiredMask));
return NULL; return nullptr;
} }
return &m_modifierKeyItem; return &m_modifierKeyItem;
@ -309,7 +306,7 @@ KeyMap::mapKey(Keystrokes& keys, KeyID id, SInt32 group,
currentState & ~desiredMask, currentState & ~desiredMask,
desiredMask, 0, keys)) { desiredMask, 0, keys)) {
LOG((CLOG_DEBUG1 "unable to clear modifiers %04x", desiredMask)); LOG((CLOG_DEBUG1 "unable to clear modifiers %04x", desiredMask));
return NULL; return nullptr;
} }
return &m_modifierKeyItem; return &m_modifierKeyItem;
@ -325,7 +322,7 @@ KeyMap::mapKey(Keystrokes& keys, KeyID id, SInt32 group,
break; break;
} }
if (item != NULL) { if (item != nullptr) {
LOG((CLOG_DEBUG1 "mapped to %03x, new state %04x", item->m_button, currentState)); LOG((CLOG_DEBUG1 "mapped to %03x, new state %04x", item->m_button, currentState));
} }
return item; return item;
@ -349,21 +346,21 @@ KeyMap::findCompatibleKey(KeyID id, SInt32 group,
{ {
assert(group >= 0 && group < getNumGroups()); assert(group >= 0 && group < getNumGroups());
KeyIDMap::const_iterator i = m_keyIDMap.find(id); auto i = m_keyIDMap.find(id);
if (i == m_keyIDMap.end()) { if (i == m_keyIDMap.end()) {
return NULL; return nullptr;
} }
const KeyEntryList& entries = i->second[group]; const KeyEntryList& entries = i->second[group];
for (size_t j = 0; j < entries.size(); ++j) { for (const auto & entrie : entries) {
if ((entries[j].back().m_sensitive & sensitive) == 0 || if ((entrie.back().m_sensitive & sensitive) == 0 ||
(entries[j].back().m_required & sensitive) == (entrie.back().m_required & sensitive) ==
(required & sensitive)) { (required & sensitive)) {
return &entries[j]; return &entrie;
} }
} }
return NULL; return nullptr;
} }
bool bool
@ -395,9 +392,8 @@ void
KeyMap::collectButtons(const ModifierToKeys& mods, ButtonToKeyMap& keys) KeyMap::collectButtons(const ModifierToKeys& mods, ButtonToKeyMap& keys)
{ {
keys.clear(); keys.clear();
for (ModifierToKeys::const_iterator i = mods.begin(); for (const auto & mod : mods) {
i != mods.end(); ++i) { keys.insert(std::make_pair(mod.second.m_button, &mod.second));
keys.insert(std::make_pair(i->second.m_button, &i->second));
} }
} }
@ -461,10 +457,9 @@ SInt32
KeyMap::findNumGroups() const KeyMap::findNumGroups() const
{ {
size_t max = 0; size_t max = 0;
for (KeyIDMap::const_iterator i = m_keyIDMap.begin(); for (const auto & i : m_keyIDMap) {
i != m_keyIDMap.end(); ++i) { if (i.second.size() > max) {
if (i->second.size() > max) { max = i.second.size();
max = i->second.size();
} }
} }
return static_cast<SInt32>(max); return static_cast<SInt32>(max);
@ -480,14 +475,14 @@ KeyMap::setModifierKeys()
const KeyGroupTable& groupTable = i->second; const KeyGroupTable& groupTable = i->second;
for (size_t g = 0; g < groupTable.size(); ++g) { for (size_t g = 0; g < groupTable.size(); ++g) {
const KeyEntryList& entries = groupTable[g]; const KeyEntryList& entries = groupTable[g];
for (size_t j = 0; j < entries.size(); ++j) { for (const auto & entrie : entries) {
// skip multi-key sequences // skip multi-key sequences
if (entries[j].size() != 1) { if (entrie.size() != 1) {
continue; continue;
} }
// skip keys that don't generate a modifier // skip keys that don't generate a modifier
const KeyItem& item = entries[j].back(); const KeyItem& item = entrie.back();
if (item.m_generates == 0) { if (item.m_generates == 0) {
continue; continue;
} }
@ -496,7 +491,7 @@ KeyMap::setModifierKeys()
for (SInt32 b = 0; b < kKeyModifierNumBits; ++b) { for (SInt32 b = 0; b < kKeyModifierNumBits; ++b) {
// skip if item doesn't generate bit b // skip if item doesn't generate bit b
if (((1u << b) & item.m_generates) != 0) { if (((1u << b) & item.m_generates) != 0) {
SInt32 mIndex = (SInt32)g * kKeyModifierNumBits + b; SInt32 mIndex = static_cast<SInt32>(g) * kKeyModifierNumBits + b;
m_modifierKeys[mIndex].push_back(&item); m_modifierKeys[mIndex].push_back(&item);
} }
} }
@ -515,22 +510,22 @@ KeyMap::mapCommandKey(Keystrokes& keys, KeyID id, SInt32 group,
static const KeyModifierMask s_overrideModifiers = 0xffffu; static const KeyModifierMask s_overrideModifiers = 0xffffu;
// find KeySym in table // find KeySym in table
KeyIDMap::const_iterator i = m_keyIDMap.find(id); auto i = m_keyIDMap.find(id);
if (i == m_keyIDMap.end()) { if (i == m_keyIDMap.end()) {
// unknown key // unknown key
LOG((CLOG_DEBUG1 "key %04x is not on keyboard", id)); LOG((CLOG_DEBUG1 "key %04x is not on keyboard", id));
return NULL; return nullptr;
} }
const KeyGroupTable& keyGroupTable = i->second; const KeyGroupTable& keyGroupTable = i->second;
// find the first key that generates this KeyID // find the first key that generates this KeyID
const KeyItem* keyItem = NULL; const KeyItem* keyItem = nullptr;
SInt32 numGroups = getNumGroups(); SInt32 numGroups = getNumGroups();
for (SInt32 groupOffset = 0; groupOffset < numGroups; ++groupOffset) { for (SInt32 groupOffset = 0; groupOffset < numGroups; ++groupOffset) {
SInt32 effectiveGroup = getEffectiveGroup(group, groupOffset); SInt32 effectiveGroup = getEffectiveGroup(group, groupOffset);
const KeyEntryList& entryList = keyGroupTable[effectiveGroup]; const KeyEntryList& entryList = keyGroupTable[effectiveGroup];
for (size_t i = 0; i < entryList.size(); ++i) { for (const auto & i : entryList) {
if (entryList[i].size() != 1) { if (i.size() != 1) {
// ignore multikey entries // ignore multikey entries
continue; continue;
} }
@ -540,7 +535,7 @@ KeyMap::mapCommandKey(Keystrokes& keys, KeyID id, SInt32 group,
// after the right button not the right character. // after the right button not the right character.
// we'll use desiredMask as-is, overriding the key's required // we'll use desiredMask as-is, overriding the key's required
// modifiers, when synthesizing this button. // modifiers, when synthesizing this button.
const KeyItem& item = entryList[i].back(); const KeyItem& item = i.back();
KeyModifierMask desiredShiftMask = KeyModifierShift & desiredMask; KeyModifierMask desiredShiftMask = KeyModifierShift & desiredMask;
KeyModifierMask requiredIgnoreShiftMask = item.m_required & ~KeyModifierShift; KeyModifierMask requiredIgnoreShiftMask = item.m_required & ~KeyModifierShift;
if ((item.m_required & desiredShiftMask) == (item.m_sensitive & desiredShiftMask) && if ((item.m_required & desiredShiftMask) == (item.m_sensitive & desiredShiftMask) &&
@ -550,14 +545,14 @@ KeyMap::mapCommandKey(Keystrokes& keys, KeyID id, SInt32 group,
break; break;
} }
} }
if (keyItem != NULL) { if (keyItem != nullptr) {
break; break;
} }
} }
if (keyItem == NULL) { if (keyItem == nullptr) {
// no mapping for this keysym // no mapping for this keysym
LOG((CLOG_DEBUG1 "no mapping for key %04x", id)); LOG((CLOG_DEBUG1 "no mapping for key %04x", id));
return NULL; return nullptr;
} }
// make working copy of modifiers // make working copy of modifiers
@ -575,7 +570,7 @@ KeyMap::mapCommandKey(Keystrokes& keys, KeyID id, SInt32 group,
s_overrideModifiers, isAutoRepeat, keys)) { s_overrideModifiers, isAutoRepeat, keys)) {
LOG((CLOG_DEBUG1 "can't map key")); LOG((CLOG_DEBUG1 "can't map key"));
keys.clear(); keys.clear();
return NULL; return nullptr;
} }
// add keystrokes to restore modifier keys // add keystrokes to restore modifier keys
@ -583,12 +578,12 @@ KeyMap::mapCommandKey(Keystrokes& keys, KeyID id, SInt32 group,
activeModifiers, keys)) { activeModifiers, keys)) {
LOG((CLOG_DEBUG1 "failed to restore modifiers")); LOG((CLOG_DEBUG1 "failed to restore modifiers"));
keys.clear(); keys.clear();
return NULL; return nullptr;
} }
// add keystrokes to restore group // add keystrokes to restore group
if (newGroup != group) { if (newGroup != group) {
keys.push_back(Keystroke(group, true, true)); keys.emplace_back(group, true, true);
} }
// save new modifiers // save new modifiers
@ -606,11 +601,11 @@ KeyMap::mapCharacterKey(Keystrokes& keys, KeyID id, SInt32 group,
bool isAutoRepeat) const bool isAutoRepeat) const
{ {
// find KeySym in table // find KeySym in table
KeyIDMap::const_iterator i = m_keyIDMap.find(id); auto i = m_keyIDMap.find(id);
if (i == m_keyIDMap.end()) { if (i == m_keyIDMap.end()) {
// unknown key // unknown key
LOG((CLOG_DEBUG1 "key %04x is not on keyboard", id)); LOG((CLOG_DEBUG1 "key %04x is not on keyboard", id));
return NULL; return nullptr;
} }
const KeyGroupTable& keyGroupTable = i->second; const KeyGroupTable& keyGroupTable = i->second;
@ -631,14 +626,14 @@ KeyMap::mapCharacterKey(Keystrokes& keys, KeyID id, SInt32 group,
if (keyIndex == -1) { if (keyIndex == -1) {
// no mapping for this keysym // no mapping for this keysym
LOG((CLOG_DEBUG1 "no mapping for key %04x", id)); LOG((CLOG_DEBUG1 "no mapping for key %04x", id));
return NULL; return nullptr;
} }
// get keys to press for key // get keys to press for key
SInt32 effectiveGroup = getEffectiveGroup(group, groupOffset); SInt32 effectiveGroup = getEffectiveGroup(group, groupOffset);
const KeyItemList& itemList = keyGroupTable[effectiveGroup][keyIndex]; const KeyItemList& itemList = keyGroupTable[effectiveGroup][keyIndex];
if (itemList.empty()) { if (itemList.empty()) {
return NULL; return nullptr;
} }
const KeyItem& keyItem = itemList.back(); const KeyItem& keyItem = itemList.back();
@ -648,13 +643,13 @@ KeyMap::mapCharacterKey(Keystrokes& keys, KeyID id, SInt32 group,
SInt32 newGroup = group; SInt32 newGroup = group;
// add each key // add each key
for (size_t j = 0; j < itemList.size(); ++j) { for (const auto & j : itemList) {
if (!keysForKeyItem(itemList[j], newGroup, newModifiers, if (!keysForKeyItem(j, newGroup, newModifiers,
newState, desiredMask, newState, desiredMask,
0, isAutoRepeat, keys)) { 0, isAutoRepeat, keys)) {
LOG((CLOG_DEBUG1 "can't map key")); LOG((CLOG_DEBUG1 "can't map key"));
keys.clear(); keys.clear();
return NULL; return nullptr;
} }
} }
@ -663,12 +658,12 @@ KeyMap::mapCharacterKey(Keystrokes& keys, KeyID id, SInt32 group,
activeModifiers, keys)) { activeModifiers, keys)) {
LOG((CLOG_DEBUG1 "failed to restore modifiers")); LOG((CLOG_DEBUG1 "failed to restore modifiers"));
keys.clear(); keys.clear();
return NULL; return nullptr;
} }
// add keystrokes to restore group // add keystrokes to restore group
if (newGroup != group) { if (newGroup != group) {
keys.push_back(Keystroke(group, true, true)); keys.emplace_back(group, true, true);
} }
// save new modifiers // save new modifiers
@ -695,7 +690,7 @@ KeyMap::findBestKey(const KeyEntryList& entryList,
KeyModifierMask desiredState) const KeyModifierMask desiredState) const
{ {
// check for an item that can accommodate the desiredState exactly // 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<SInt32>(entryList.size()); ++i) {
const KeyItem& item = entryList[i].back(); const KeyItem& item = entryList[i].back();
if ((item.m_required & desiredState) == item.m_required && if ((item.m_required & desiredState) == item.m_required &&
(item.m_required & desiredState) == (item.m_sensitive & desiredState)) { (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 // choose the item that requires the fewest modifier changes
SInt32 bestCount = 32; SInt32 bestCount = 32;
SInt32 bestIndex = -1; SInt32 bestIndex = -1;
for (SInt32 i = 0; i < (SInt32)entryList.size(); ++i) { for (SInt32 i = 0; i < static_cast<SInt32>(entryList.size()); ++i) {
const KeyItem& item = entryList[i].back(); const KeyItem& item = entryList[i].back();
KeyModifierMask change = KeyModifierMask change =
((item.m_required ^ desiredState) & item.m_sensitive); ((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. // must use the other shift button to do the shifting.
const ModifierKeyItemList& items = const ModifierKeyItemList& items =
m_modifierKeys[group * kKeyModifierNumBits + modifierBit]; m_modifierKeys[group * kKeyModifierNumBits + modifierBit];
for (ModifierKeyItemList::const_iterator i = items.begin(); for (auto item : items) {
i != items.end(); ++i) { if (item->m_button != button) {
if ((*i)->m_button != button) { return item;
return (*i);
} }
} }
return NULL; return nullptr;
} }
bool bool
@ -763,7 +757,7 @@ KeyMap::keysForKeyItem(const KeyItem& keyItem, SInt32& group,
// add keystrokes to adjust the group // add keystrokes to adjust the group
if (group != keyItem.m_group) { if (group != keyItem.m_group) {
group = keyItem.m_group; group = keyItem.m_group;
keystrokes.push_back(Keystroke(group, true, false)); keystrokes.emplace_back(group, true, false);
} }
EKeystroke type; EKeystroke type;
@ -823,7 +817,7 @@ KeyMap::keysForKeyItem(const KeyItem& keyItem, SInt32& group,
} }
bool bool
KeyMap::keysToRestoreModifiers(const KeyItem& keyItem, SInt32, KeyMap::keysToRestoreModifiers(const KeyItem& keyItem, SInt32 /*unused*/,
ModifierToKeys& activeModifiers, ModifierToKeys& activeModifiers,
KeyModifierMask& currentState, KeyModifierMask& currentState,
const ModifierToKeys& desiredModifiers, const ModifierToKeys& desiredModifiers,
@ -853,15 +847,14 @@ KeyMap::keysToRestoreModifiers(const KeyItem& keyItem, SInt32,
} }
// press wanted keys // press wanted keys
for (ModifierToKeys::const_iterator i = desiredModifiers.begin(); for (const auto & desiredModifier : desiredModifiers) {
i != desiredModifiers.end(); ++i) { KeyButton button = desiredModifier.second.m_button;
KeyButton button = i->second.m_button;
if (button != keyItem.m_button && oldKeys.count(button) == 0) { if (button != keyItem.m_button && oldKeys.count(button) == 0) {
EKeystroke type = kKeystrokePress; EKeystroke type = kKeystrokePress;
if (i->second.m_lock) { if (desiredModifier.second.m_lock) {
type = kKeystrokeModify; type = kKeystrokeModify;
} }
addKeystrokes(type, i->second, addKeystrokes(type, desiredModifier.second,
activeModifiers, currentState, keystrokes); activeModifiers, currentState, keystrokes);
} }
} }
@ -908,14 +901,14 @@ KeyMap::keysForModifierState(KeyButton button, SInt32 group,
// get the KeyItem for the modifier in the group // get the KeyItem for the modifier in the group
const KeyItem* keyItem = keyForModifier(button, group, bit); const KeyItem* keyItem = keyForModifier(button, group, bit);
if (keyItem == NULL) { if (keyItem == nullptr) {
if ((mask & notRequiredMask) == 0) { if ((mask & notRequiredMask) == 0) {
LOG((CLOG_DEBUG1 "no key for modifier %04x", mask)); LOG((CLOG_DEBUG1 "no key for modifier %04x", mask));
return false; return false;
} }
else {
continue; continue;
}
} }
// if this modifier is sensitive to modifiers then adjust those // if this modifier is sensitive to modifiers then adjust those
@ -940,7 +933,7 @@ KeyMap::keysForModifierState(KeyButton button, SInt32 group,
notRequiredMask, keystrokes)) { notRequiredMask, keystrokes)) {
return false; return false;
} }
else if (!active) { if (!active) {
// release the modifier // release the modifier
// XXX -- this doesn't work! if Alt and Meta are mapped // XXX -- this doesn't work! if Alt and Meta are mapped
// to one key and we want to release Meta we can't do // 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; UInt32 data = keyItem.m_client;
switch (type) { switch (type) {
case kKeystrokePress: 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_generates != 0) {
if (!keyItem.m_lock || (currentState & keyItem.m_generates) == 0) { if (!keyItem.m_lock || (currentState & keyItem.m_generates) == 0) {
// add modifier key and activate modifier // add modifier key and activate modifier
@ -991,13 +984,13 @@ KeyMap::addKeystrokes(EKeystroke type, const KeyItem& keyItem,
break; break;
case kKeystrokeRelease: 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) { if (keyItem.m_generates != 0 && !keyItem.m_lock) {
// remove key from active modifiers // remove key from active modifiers
std::pair<ModifierToKeys::iterator, std::pair<ModifierToKeys::iterator,
ModifierToKeys::iterator> range = ModifierToKeys::iterator> range =
activeModifiers.equal_range(keyItem.m_generates); activeModifiers.equal_range(keyItem.m_generates);
for (ModifierToKeys::iterator i = range.first; for (auto i = range.first;
i != range.second; ++i) { i != range.second; ++i) {
if (i->second.m_button == button) { if (i->second.m_button == button) {
activeModifiers.erase(i); activeModifiers.erase(i);
@ -1013,14 +1006,14 @@ KeyMap::addKeystrokes(EKeystroke type, const KeyItem& keyItem,
break; break;
case kKeystrokeRepeat: case kKeystrokeRepeat:
keystrokes.push_back(Keystroke(button, false, true, data)); keystrokes.emplace_back(button, false, true, data);
keystrokes.push_back(Keystroke(button, true, true, data)); keystrokes.emplace_back(button, true, true, data);
// no modifier changes on key repeat // no modifier changes on key repeat
break; break;
case kKeystrokeClick: case kKeystrokeClick:
keystrokes.push_back(Keystroke(button, true, false, data)); keystrokes.emplace_back(button, true, false, data);
keystrokes.push_back(Keystroke(button, false, false, data)); keystrokes.emplace_back(button, false, false, data);
// no modifier changes on key click // no modifier changes on key click
break; break;
@ -1031,22 +1024,22 @@ KeyMap::addKeystrokes(EKeystroke type, const KeyItem& keyItem,
if (m_halfDuplex.count(button) > 0) { if (m_halfDuplex.count(button) > 0) {
if (type == kKeystrokeModify) { if (type == kKeystrokeModify) {
// turn half-duplex toggle on (press) // turn half-duplex toggle on (press)
keystrokes.push_back(Keystroke(button, true, false, data)); keystrokes.emplace_back(button, true, false, data);
} }
else { else {
// turn half-duplex toggle off (release) // turn half-duplex toggle off (release)
keystrokes.push_back(Keystroke(button, false, false, data)); keystrokes.emplace_back(button, false, false, data);
} }
} }
else { else {
// toggle (click) // toggle (click)
keystrokes.push_back(Keystroke(button, true, false, data)); keystrokes.emplace_back(button, true, false, data);
keystrokes.push_back(Keystroke(button, false, false, data)); keystrokes.emplace_back(button, false, false, data);
} }
} }
else if (type == kKeystrokeModify) { else if (type == kKeystrokeModify) {
// press modifier // press modifier
keystrokes.push_back(Keystroke(button, true, false, data)); keystrokes.emplace_back(button, true, false, data);
} }
else { else {
// release all the keys that generate the modifier that are // release all the keys that generate the modifier that are
@ -1054,10 +1047,10 @@ KeyMap::addKeystrokes(EKeystroke type, const KeyItem& keyItem,
std::pair<ModifierToKeys::const_iterator, std::pair<ModifierToKeys::const_iterator,
ModifierToKeys::const_iterator> range = ModifierToKeys::const_iterator> range =
activeModifiers.equal_range(keyItem.m_generates); activeModifiers.equal_range(keyItem.m_generates);
for (ModifierToKeys::const_iterator i = range.first; for (auto i = range.first;
i != range.second; ++i) { i != range.second; ++i) {
keystrokes.push_back(Keystroke(i->second.m_button, keystrokes.emplace_back(i->second.m_button,
false, false, i->second.m_client)); false, false, i->second.m_client);
} }
} }
@ -1170,7 +1163,7 @@ KeyMap::formatKey(KeyID key, KeyModifierMask mask)
} }
// XXX -- we're assuming ASCII here // XXX -- we're assuming ASCII here
else if (key >= 33 && key < 127) { else if (key >= 33 && key < 127) {
x += (char)key; x += static_cast<char>(key);
} }
else { else {
x += synergy::string::sprintf("\\u%04x", key); 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 // XXX -- we're assuming ASCII encoding here
else if (x.size() == 1) { else if (x.size() == 1) {
if (!isgraph(x[0])) { if (isgraph(x[0]) == 0) {
// unknown key // unknown key
return false; return false;
} }
key = (KeyID)x[0]; key = static_cast<KeyID>(x[0]);
} }
else if (x.size() == 6 && x[0] == '\\' && x[1] == 'u') { else if (x.size() == 6 && x[0] == '\\' && x[1] == 'u') {
// escaped unicode (\uXXXX where XXXX is a hex number) // escaped unicode (\uXXXX where XXXX is a hex number)
char* end; char* end;
key = (KeyID)strtol(x.c_str() + 2, &end, 16); key = static_cast<KeyID>(strtol(x.c_str() + 2, &end, 16));
if (*end != '\0') { if (*end != '\0') {
return false; return false;
} }
@ -1280,19 +1273,19 @@ void
KeyMap::initKeyNameMaps() KeyMap::initKeyNameMaps()
{ {
// initialize tables // initialize tables
if (s_nameToKeyMap == NULL) { if (s_nameToKeyMap == nullptr) {
s_nameToKeyMap = new NameToKeyMap; s_nameToKeyMap = new NameToKeyMap;
s_keyToNameMap = new KeyToNameMap; 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_nameToKeyMap)[i->m_name] = i->m_id;
(*s_keyToNameMap)[i->m_id] = i->m_name; (*s_keyToNameMap)[i->m_id] = i->m_name;
} }
} }
if (s_nameToModifierMap == NULL) { if (s_nameToModifierMap == nullptr) {
s_nameToModifierMap = new NameToModifierMap; s_nameToModifierMap = new NameToModifierMap;
s_modifierToNameMap = new ModifierToNameMap; s_modifierToNameMap = new ModifierToNameMap;
for (const KeyModifierNameMapEntry* i = kModifierNameMap; for (const KeyModifierNameMapEntry* i = kModifierNameMap;
i->m_name != NULL; ++i) { i->m_name != nullptr; ++i) {
(*s_nameToModifierMap)[i->m_name] = i->m_mask; (*s_nameToModifierMap)[i->m_name] = i->m_mask;
(*s_modifierToNameMap)[i->m_mask] = i->m_name; (*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; m_data.m_group.m_restore = restore;
} }
} } // namespace synergy

View File

@ -82,7 +82,7 @@ public:
kGroup //!< Set new group 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); Keystroke(SInt32 group, bool absolute, bool restore);
public: public:
@ -106,7 +106,7 @@ public:
}; };
EType m_type; EType m_type;
Data m_data; Data m_data{};
}; };
//! A sequence of keystrokes //! A sequence of keystrokes
@ -278,7 +278,7 @@ public:
/*! /*!
Put all the keys in \p modifiers into \p keys. Put all the keys in \p modifiers into \p keys.
*/ */
static void collectButtons(const ModifierToKeys& modifiers, static void collectButtons(const ModifierToKeys& mods,
ButtonToKeyMap& keys); ButtonToKeyMap& keys);
//! Set modifier key state //! Set modifier key state
@ -500,7 +500,7 @@ private:
KeySet m_halfDuplexMods; // half-duplex set by user KeySet m_halfDuplexMods; // half-duplex set by user
// dummy KeyItem for changing modifiers // dummy KeyItem for changing modifiers
KeyItem m_modifierKeyItem; KeyItem m_modifierKeyItem{};
// parsing/formatting tables // parsing/formatting tables
static NameToKeyMap* s_nameToKeyMap; static NameToKeyMap* s_nameToKeyMap;

View File

@ -19,12 +19,12 @@
#include "core/KeyState.h" #include "core/KeyState.h"
#include "base/Log.h" #include "base/Log.h"
#include <cstring>
#include <algorithm> #include <algorithm>
#include <cstring>
#include <iterator> #include <iterator>
#include <list> #include <list>
static const KeyButton kButtonMask = (KeyButton)(IKeyState::kNumButtons - 1); static const KeyButton kButtonMask = static_cast<KeyButton>(IKeyState::kNumButtons - 1);
static const KeyID s_decomposeTable[] = { static const KeyID s_decomposeTable[] = {
// spacing version of dead keys // spacing version of dead keys
@ -395,7 +395,7 @@ KeyState::KeyState(IEventQueue* events) :
KeyState::KeyState(IEventQueue* events, synergy::KeyMap& keyMap) : KeyState::KeyState(IEventQueue* events, synergy::KeyMap& keyMap) :
IKeyState(events), IKeyState(events),
m_keyMapPtr(0), m_keyMapPtr(nullptr),
m_keyMap(keyMap), m_keyMap(keyMap),
m_mask(0), m_mask(0),
m_events(events) m_events(events)
@ -405,8 +405,7 @@ KeyState::KeyState(IEventQueue* events, synergy::KeyMap& keyMap) :
KeyState::~KeyState() KeyState::~KeyState()
{ {
if (m_keyMapPtr) delete m_keyMapPtr;
delete m_keyMapPtr;
} }
void void
@ -503,9 +502,8 @@ KeyState::updateKeyState()
// get the current keyboard state // get the current keyboard state
KeyButtonSet keysDown; KeyButtonSet keysDown;
pollPressedKeys(keysDown); pollPressedKeys(keysDown);
for (KeyButtonSet::const_iterator i = keysDown.begin(); for (unsigned short i : keysDown) {
i != keysDown.end(); ++i) { m_keys[i] = 1;
m_keys[*i] = 1;
} }
// get the current modifier state // get the current modifier state
@ -520,10 +518,10 @@ KeyState::updateKeyState()
} }
void void
KeyState::addActiveModifierCB(KeyID, SInt32 group, KeyState::addActiveModifierCB(KeyID /*unused*/, SInt32 group,
synergy::KeyMap::KeyItem& keyItem, void* vcontext) synergy::KeyMap::KeyItem& keyItem, void* vcontext)
{ {
AddActiveModifierContext* context = auto* context =
static_cast<AddActiveModifierContext*>(vcontext); static_cast<AddActiveModifierContext*>(vcontext);
if (group == context->m_activeGroup && if (group == context->m_activeGroup &&
(keyItem.m_generates & context->m_mask) != 0) { (keyItem.m_generates & context->m_mask) != 0) {
@ -570,7 +568,7 @@ KeyState::fakeKeyDown(KeyID id, KeyModifierMask mask, KeyButton serverID)
const synergy::KeyMap::KeyItem* keyItem = const synergy::KeyMap::KeyItem* keyItem =
m_keyMap.mapKey(keys, id, pollActiveGroup(), m_activeModifiers, m_keyMap.mapKey(keys, id, pollActiveGroup(), m_activeModifiers,
getActiveModifiersRValue(), mask, false); 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 // a media key won't be mapped on mac, so we need to fake it in a
// special way // special way
if (id == kKeyAudioDown || id == kKeyAudioUp || if (id == kKeyAudioDown || id == kKeyAudioUp ||
@ -585,7 +583,7 @@ KeyState::fakeKeyDown(KeyID id, KeyModifierMask mask, KeyButton serverID)
return; return;
} }
KeyButton localID = (KeyButton)(keyItem->m_button & kButtonMask); auto localID = static_cast<KeyButton>(keyItem->m_button & kButtonMask);
updateModifierKeyState(localID, oldActiveModifiers, m_activeModifiers); updateModifierKeyState(localID, oldActiveModifiers, m_activeModifiers);
if (localID != 0) { if (localID != 0) {
// note keys down // note keys down
@ -618,10 +616,10 @@ KeyState::fakeKeyRepeat(
const synergy::KeyMap::KeyItem* keyItem = const synergy::KeyMap::KeyItem* keyItem =
m_keyMap.mapKey(keys, id, pollActiveGroup(), m_activeModifiers, m_keyMap.mapKey(keys, id, pollActiveGroup(), m_activeModifiers,
getActiveModifiersRValue(), mask, true); getActiveModifiersRValue(), mask, true);
if (keyItem == NULL) { if (keyItem == nullptr) {
return false; return false;
} }
KeyButton localID = (KeyButton)(keyItem->m_button & kButtonMask); auto localID = static_cast<KeyButton>(keyItem->m_button & kButtonMask);
if (localID == 0) { if (localID == 0) {
return false; return false;
} }
@ -635,11 +633,10 @@ KeyState::fakeKeyRepeat(
if (localID != oldLocalID) { if (localID != oldLocalID) {
// replace key up with previous KeyButton but leave key down // replace key up with previous KeyButton but leave key down
// alone so it uses the new KeyButton. // alone so it uses the new KeyButton.
for (Keystrokes::iterator index = keys.begin(); for (auto & key : keys) {
index != keys.end(); ++index) { if (key.m_type == Keystroke::kButton &&
if (index->m_type == Keystroke::kButton && key.m_data.m_button.m_button == localID) {
index->m_data.m_button.m_button == localID) { key.m_data.m_button.m_button = oldLocalID;
index->m_data.m_button.m_button = oldLocalID;
break; break;
} }
} }
@ -672,7 +669,7 @@ KeyState::fakeKeyUp(KeyButton serverID)
// get the sequence of keys to simulate key release // get the sequence of keys to simulate key release
Keystrokes keys; Keystrokes keys;
keys.push_back(Keystroke(localID, false, false, m_keyClientData[localID])); keys.emplace_back(localID, false, false, m_keyClientData[localID]);
// note keys down // note keys down
--m_keys[localID]; --m_keys[localID];
@ -680,13 +677,13 @@ KeyState::fakeKeyUp(KeyButton serverID)
m_serverKeys[serverID] = 0; m_serverKeys[serverID] = 0;
// check if this is a modifier // check if this is a modifier
ModifierToKeys::iterator i = m_activeModifiers.begin(); auto i = m_activeModifiers.begin();
while (i != m_activeModifiers.end()) { while (i != m_activeModifiers.end()) {
if (i->second.m_button == localID && !i->second.m_lock) { if (i->second.m_button == localID && !i->second.m_lock) {
// modifier is no longer down // modifier is no longer down
KeyModifierMask mask = i->first; KeyModifierMask mask = i->first;
ModifierToKeys::iterator tmp = i; auto tmp = i;
++i; ++i;
m_activeModifiers.erase(tmp); m_activeModifiers.erase(tmp);
@ -712,7 +709,7 @@ KeyState::fakeAllKeysUp()
Keystrokes keys; Keystrokes keys;
for (KeyButton i = 0; i < IKeyState::kNumButtons; ++i) { for (KeyButton i = 0; i < IKeyState::kNumButtons; ++i) {
if (m_syntheticKeys[i] > 0) { 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_keys[i] = 0;
m_syntheticKeys[i] = 0; m_syntheticKeys[i] = 0;
} }
@ -724,7 +721,7 @@ KeyState::fakeAllKeysUp()
} }
bool bool
KeyState::fakeMediaKey(KeyID id) KeyState::fakeMediaKey(KeyID /*id*/)
{ {
return false; return false;
} }
@ -754,7 +751,7 @@ KeyState::getEffectiveGroup(SInt32 group, SInt32 offset) const
} }
bool bool
KeyState::isIgnoredKey(KeyID key, KeyModifierMask) const KeyState::isIgnoredKey(KeyID key, KeyModifierMask /*unused*/) const
{ {
switch (key) { switch (key) {
case kKeyCapsLock: case kKeyCapsLock:
@ -772,12 +769,12 @@ KeyState::getButton(KeyID id, SInt32 group) const
{ {
const synergy::KeyMap::KeyItemList* items = const synergy::KeyMap::KeyItemList* items =
m_keyMap.findCompatibleKey(id, group, 0, 0); m_keyMap.findCompatibleKey(id, group, 0, 0);
if (items == NULL) { if (items == nullptr) {
return 0; return 0;
} }
else {
return items->back().m_button; return items->back().m_button;
}
} }
void void
@ -849,11 +846,11 @@ KeyState::fakeKeys(const Keystrokes& keys, UInt32 count)
// generate key events // generate key events
LOG((CLOG_DEBUG1 "keystrokes:")); 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) { if (k->m_type == Keystroke::kButton && k->m_data.m_button.m_repeat) {
// repeat from here up to but not including the next key // repeat from here up to but not including the next key
// with m_repeat == false count times. // with m_repeat == false count times.
Keystrokes::const_iterator start = k; auto start = k;
while (count-- > 0) { while (count-- > 0) {
// send repeating events // send repeating events
for (k = start; k != keys.end() && for (k = start; k != keys.end() &&
@ -883,13 +880,11 @@ KeyState::updateModifierKeyState(KeyButton button,
{ {
// get the pressed modifier buttons before and after // get the pressed modifier buttons before and after
synergy::KeyMap::ButtonToKeyMap oldKeys, newKeys; synergy::KeyMap::ButtonToKeyMap oldKeys, newKeys;
for (ModifierToKeys::const_iterator i = oldModifiers.begin(); for (const auto & oldModifier : oldModifiers) {
i != oldModifiers.end(); ++i) { oldKeys.insert(std::make_pair(oldModifier.second.m_button, &oldModifier.second));
oldKeys.insert(std::make_pair(i->second.m_button, &i->second));
} }
for (ModifierToKeys::const_iterator i = newModifiers.begin(); for (const auto & newModifier : newModifiers) {
i != newModifiers.end(); ++i) { newKeys.insert(std::make_pair(newModifier.second.m_button, &newModifier.second));
newKeys.insert(std::make_pair(i->second.m_button, &i->second));
} }
// get the modifier buttons that were pressed or released // get the modifier buttons that were pressed or released

View File

@ -67,10 +67,10 @@ public:
virtual void updateKeyState(); virtual void updateKeyState();
virtual void setHalfDuplexMask(KeyModifierMask); virtual void setHalfDuplexMask(KeyModifierMask);
virtual void fakeKeyDown(KeyID id, KeyModifierMask mask, virtual void fakeKeyDown(KeyID id, KeyModifierMask mask,
KeyButton button); KeyButton serverID);
virtual bool fakeKeyRepeat(KeyID id, KeyModifierMask mask, virtual bool fakeKeyRepeat(KeyID id, KeyModifierMask mask,
SInt32 count, KeyButton button); SInt32 count, KeyButton serverID);
virtual bool fakeKeyUp(KeyButton button); virtual bool fakeKeyUp(KeyButton serverID);
virtual void fakeAllKeysUp(); virtual void fakeAllKeysUp();
virtual bool fakeCtrlAltDel() = 0; virtual bool fakeCtrlAltDel() = 0;
virtual bool fakeMediaKey(KeyID id); virtual bool fakeMediaKey(KeyID id);
@ -213,20 +213,20 @@ private:
// current keyboard state (> 0 if pressed, 0 otherwise). this is // current keyboard state (> 0 if pressed, 0 otherwise). this is
// initialized to the keyboard state according to the system then // initialized to the keyboard state according to the system then
// it tracks synthesized events. // it tracks synthesized events.
SInt32 m_keys[kNumButtons]; SInt32 m_keys[kNumButtons]{};
// synthetic keyboard state (> 0 if pressed, 0 otherwise). this // synthetic keyboard state (> 0 if pressed, 0 otherwise). this
// tracks the synthesized keyboard state. if m_keys[n] > 0 but // tracks the synthesized keyboard state. if m_keys[n] > 0 but
// m_syntheticKeys[n] == 0 then the key was pressed locally and // m_syntheticKeys[n] == 0 then the key was pressed locally and
// not synthesized yet. // not synthesized yet.
SInt32 m_syntheticKeys[kNumButtons]; SInt32 m_syntheticKeys[kNumButtons]{};
// client data for each pressed key // 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 // 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. // otherwise it's the local KeyButton synthesized for the server key.
KeyButton m_serverKeys[kNumButtons]; KeyButton m_serverKeys[kNumButtons]{};
IEventQueue* m_events; IEventQueue* m_events;
}; };

View File

@ -18,8 +18,8 @@
#include "core/PacketStreamFilter.h" #include "core/PacketStreamFilter.h"
#include "base/IEventQueue.h" #include "base/IEventQueue.h"
#include "mt/Lock.h"
#include "base/TMethodEventJob.h" #include "base/TMethodEventJob.h"
#include "mt/Lock.h"
#include <cstring> #include <cstring>
#include <memory> #include <memory>
@ -71,7 +71,7 @@ PacketStreamFilter::read(void* buffer, UInt32 n)
} }
// read it // read it
if (buffer != NULL) { if (buffer != nullptr) {
memcpy(buffer, m_buffer.peek(n), n); memcpy(buffer, m_buffer.peek(n), n);
} }
m_buffer.pop(n); m_buffer.pop(n);
@ -83,7 +83,7 @@ PacketStreamFilter::read(void* buffer, UInt32 n)
if (m_inputShutdown && m_size == 0) { if (m_inputShutdown && m_size == 0) {
m_events->addEvent(Event(m_events->forIStream().inputShutdown(), m_events->addEvent(Event(m_events->forIStream().inputShutdown(),
getEventTarget(), NULL)); getEventTarget(), nullptr));
} }
return n; return n;
@ -94,10 +94,10 @@ PacketStreamFilter::write(const void* buffer, UInt32 count)
{ {
// write the length of the payload // write the length of the payload
UInt8 length[4]; UInt8 length[4];
length[0] = (UInt8)((count >> 24) & 0xff); length[0] = static_cast<UInt8>((count >> 24) & 0xff);
length[1] = (UInt8)((count >> 16) & 0xff); length[1] = static_cast<UInt8>((count >> 16) & 0xff);
length[2] = (UInt8)((count >> 8) & 0xff); length[2] = static_cast<UInt8>((count >> 8) & 0xff);
length[3] = (UInt8)( count & 0xff); length[3] = static_cast<UInt8>( count & 0xff);
getStream()->write(length, sizeof(length)); getStream()->write(length, sizeof(length));
// write the payload // write the payload
@ -142,10 +142,10 @@ PacketStreamFilter::readPacketSize()
UInt8 buffer[4]; UInt8 buffer[4];
memcpy(buffer, m_buffer.peek(sizeof(buffer)), sizeof(buffer)); memcpy(buffer, m_buffer.peek(sizeof(buffer)), sizeof(buffer));
m_buffer.pop(sizeof(buffer)); m_buffer.pop(sizeof(buffer));
m_size = ((UInt32)buffer[0] << 24) | m_size = (static_cast<UInt32>(buffer[0]) << 24) |
((UInt32)buffer[1] << 16) | (static_cast<UInt32>(buffer[1]) << 16) |
((UInt32)buffer[2] << 8) | (static_cast<UInt32>(buffer[2]) << 8) |
(UInt32)buffer[3]; static_cast<UInt32>(buffer[3]);
} }
} }

View File

@ -36,7 +36,7 @@ public:
// IStream overrides // IStream overrides
virtual void close(); virtual void close();
virtual UInt32 read(void* buffer, UInt32 n); 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 void shutdownInput();
virtual bool isReady() const; virtual bool isReady() const;
virtual UInt32 getSize() const; virtual UInt32 getSize() const;

View File

@ -17,11 +17,11 @@
*/ */
#include "core/PortableTaskBarReceiver.h" #include "core/PortableTaskBarReceiver.h"
#include "mt/Lock.h"
#include "base/String.h"
#include "base/IEventQueue.h"
#include "arch/Arch.h" #include "arch/Arch.h"
#include "base/IEventQueue.h"
#include "base/String.h"
#include "common/Version.h" #include "common/Version.h"
#include "mt/Lock.h"
// //
// PortableTaskBarReceiver // PortableTaskBarReceiver
@ -45,7 +45,7 @@ PortableTaskBarReceiver::updateStatus(INode* node, const String& errorMsg)
{ {
// update our status // update our status
m_errorMessage = errorMsg; m_errorMessage = errorMsg;
if (node == NULL) { if (node == nullptr) {
if (m_errorMessage.empty()) { if (m_errorMessage.empty()) {
m_state = kNotRunning; m_state = kNotRunning;
} }
@ -84,7 +84,7 @@ PortableTaskBarReceiver::quit()
} }
void void
PortableTaskBarReceiver::onStatusChanged(INode*) PortableTaskBarReceiver::onStatusChanged(INode* /*unused*/)
{ {
// do nothing // do nothing
} }

View File

@ -17,9 +17,9 @@
*/ */
#include "core/ProtocolUtil.h" #include "core/ProtocolUtil.h"
#include "io/IStream.h"
#include "base/Log.h" #include "base/Log.h"
#include "common/stdvector.h" #include "common/stdvector.h"
#include "io/IStream.h"
#include <cctype> #include <cctype>
#include <cstring> #include <cstring>
@ -78,7 +78,7 @@ ProtocolUtil::vwritef(synergy::IStream* stream,
} }
// fill buffer // fill buffer
UInt8* buffer = new UInt8[size]; auto* buffer = new UInt8[size];
writef(buffer, fmt, args); writef(buffer, fmt, args);
try { try {
@ -101,7 +101,7 @@ ProtocolUtil::vreadf(synergy::IStream* stream, const char* fmt, va_list args)
assert(fmt != NULL); assert(fmt != NULL);
// begin scanning // begin scanning
while (*fmt) { while (*fmt != 0) {
if (*fmt == '%') { if (*fmt == '%') {
// format specifier. determine argument size. // format specifier. determine argument size.
++fmt; ++fmt;
@ -234,7 +234,7 @@ ProtocolUtil::vreadf(synergy::IStream* stream, const char* fmt, va_list args)
// save the data // save the data
String* dst = va_arg(args, String*); String* dst = va_arg(args, String*);
dst->assign((const char*)sBuffer, len); dst->assign(reinterpret_cast<const char*>(sBuffer), len);
// release the buffer // release the buffer
if (!useFixed) { if (!useFixed) {
@ -275,7 +275,7 @@ UInt32
ProtocolUtil::getLength(const char* fmt, va_list args) ProtocolUtil::getLength(const char* fmt, va_list args)
{ {
UInt32 n = 0; UInt32 n = 0;
while (*fmt) { while (*fmt != 0) {
if (*fmt == '%') { if (*fmt == '%') {
// format specifier. determine argument size. // format specifier. determine argument size.
++fmt; ++fmt;
@ -290,22 +290,22 @@ ProtocolUtil::getLength(const char* fmt, va_list args)
assert(len == 1 || len == 2 || len == 4); assert(len == 1 || len == 2 || len == 4);
switch (len) { switch (len) {
case 1: case 1:
len = (UInt32)(va_arg(args, std::vector<UInt8>*))->size() + 4; len = static_cast<UInt32>((va_arg(args, std::vector<UInt8>*))->size()) + 4;
break; break;
case 2: case 2:
len = 2 * (UInt32)(va_arg(args, std::vector<UInt16>*))->size() + 4; len = 2 * static_cast<UInt32>((va_arg(args, std::vector<UInt16>*))->size()) + 4;
break; break;
case 4: case 4:
len = 4 * (UInt32)(va_arg(args, std::vector<UInt32>*))->size() + 4; len = 4 * static_cast<UInt32>((va_arg(args, std::vector<UInt32>*))->size()) + 4;
break; break;
} }
break; break;
case 's': case 's':
assert(len == 0); assert(len == 0);
len = (UInt32)(va_arg(args, String*))->size() + 4; len = static_cast<UInt32>((va_arg(args, String*))->size()) + 4;
(void)va_arg(args, UInt8*); (void)va_arg(args, UInt8*);
break; break;
@ -340,9 +340,9 @@ ProtocolUtil::getLength(const char* fmt, va_list args)
void void
ProtocolUtil::writef(void* buffer, const char* fmt, va_list args) ProtocolUtil::writef(void* buffer, const char* fmt, va_list args)
{ {
UInt8* dst = static_cast<UInt8*>(buffer); auto* dst = static_cast<UInt8*>(buffer);
while (*fmt) { while (*fmt != 0) {
if (*fmt == '%') { if (*fmt == '%') {
// format specifier. determine argument size. // format specifier. determine argument size.
++fmt; ++fmt;
@ -383,7 +383,7 @@ ProtocolUtil::writef(void* buffer, const char* fmt, va_list args)
// 1 byte integers // 1 byte integers
const std::vector<UInt8>* list = const std::vector<UInt8>* list =
va_arg(args, const std::vector<UInt8>*); va_arg(args, const std::vector<UInt8>*);
const UInt32 n = (UInt32)list->size(); const auto n = static_cast<UInt32>(list->size());
*dst++ = static_cast<UInt8>((n >> 24) & 0xff); *dst++ = static_cast<UInt8>((n >> 24) & 0xff);
*dst++ = static_cast<UInt8>((n >> 16) & 0xff); *dst++ = static_cast<UInt8>((n >> 16) & 0xff);
*dst++ = static_cast<UInt8>((n >> 8) & 0xff); *dst++ = static_cast<UInt8>((n >> 8) & 0xff);
@ -398,7 +398,7 @@ ProtocolUtil::writef(void* buffer, const char* fmt, va_list args)
// 2 byte integers // 2 byte integers
const std::vector<UInt16>* list = const std::vector<UInt16>* list =
va_arg(args, const std::vector<UInt16>*); va_arg(args, const std::vector<UInt16>*);
const UInt32 n = (UInt32)list->size(); const auto n = static_cast<UInt32>(list->size());
*dst++ = static_cast<UInt8>((n >> 24) & 0xff); *dst++ = static_cast<UInt8>((n >> 24) & 0xff);
*dst++ = static_cast<UInt8>((n >> 16) & 0xff); *dst++ = static_cast<UInt8>((n >> 16) & 0xff);
*dst++ = static_cast<UInt8>((n >> 8) & 0xff); *dst++ = static_cast<UInt8>((n >> 8) & 0xff);
@ -415,7 +415,7 @@ ProtocolUtil::writef(void* buffer, const char* fmt, va_list args)
// 4 byte integers // 4 byte integers
const std::vector<UInt32>* list = const std::vector<UInt32>* list =
va_arg(args, const std::vector<UInt32>*); va_arg(args, const std::vector<UInt32>*);
const UInt32 n = (UInt32)list->size(); const auto n = static_cast<UInt32>(list->size());
*dst++ = static_cast<UInt8>((n >> 24) & 0xff); *dst++ = static_cast<UInt8>((n >> 24) & 0xff);
*dst++ = static_cast<UInt8>((n >> 16) & 0xff); *dst++ = static_cast<UInt8>((n >> 16) & 0xff);
*dst++ = static_cast<UInt8>((n >> 8) & 0xff); *dst++ = static_cast<UInt8>((n >> 8) & 0xff);
@ -440,7 +440,7 @@ ProtocolUtil::writef(void* buffer, const char* fmt, va_list args)
case 's': { case 's': {
assert(len == 0); assert(len == 0);
const String* src = va_arg(args, String*); const String* src = va_arg(args, String*);
const UInt32 len = (src != NULL) ? (UInt32)src->size() : 0; const UInt32 len = (src != nullptr) ? static_cast<UInt32>(src->size()) : 0;
*dst++ = static_cast<UInt8>((len >> 24) & 0xff); *dst++ = static_cast<UInt8>((len >> 24) & 0xff);
*dst++ = static_cast<UInt8>((len >> 16) & 0xff); *dst++ = static_cast<UInt8>((len >> 16) & 0xff);
*dst++ = static_cast<UInt8>((len >> 8) & 0xff); *dst++ = static_cast<UInt8>((len >> 8) & 0xff);
@ -515,7 +515,7 @@ ProtocolUtil::read(synergy::IStream* stream, void* vbuffer, UInt32 count)
assert(stream != NULL); assert(stream != NULL);
assert(vbuffer != NULL); assert(vbuffer != NULL);
UInt8* buffer = static_cast<UInt8*>(vbuffer); auto* buffer = static_cast<UInt8*>(vbuffer);
while (count > 0) { while (count > 0) {
// read more // read more
UInt32 n = stream->read(buffer, count); UInt32 n = stream->read(buffer, count);
@ -538,7 +538,7 @@ ProtocolUtil::read(synergy::IStream* stream, void* vbuffer, UInt32 count)
// //
String String
XIOReadMismatch::getWhat() const throw() XIOReadMismatch::getWhat() const noexcept
{ {
return format("XIOReadMismatch", "ProtocolUtil::readf() mismatch"); return format("XIOReadMismatch", "ProtocolUtil::readf() mismatch");
} }

View File

@ -80,7 +80,7 @@ private:
static UInt32 getLength(const char* fmt, va_list); static UInt32 getLength(const char* fmt, va_list);
static void writef(void*, 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); static void read(synergy::IStream*, void*, UInt32);
}; };

View File

@ -17,12 +17,12 @@
*/ */
#include "core/Screen.h" #include "core/Screen.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "core/IPlatformScreen.h" #include "core/IPlatformScreen.h"
#include "core/protocol_types.h" #include "core/protocol_types.h"
#include "base/Log.h"
#include "base/IEventQueue.h"
#include "server/ClientProxy.h" #include "server/ClientProxy.h"
#include "base/TMethodEventJob.h"
namespace synergy { namespace synergy {
@ -172,7 +172,7 @@ Screen::setClipboard(ClipboardID id, const IClipboard* clipboard)
void void
Screen::grabClipboard(ClipboardID id) Screen::grabClipboard(ClipboardID id)
{ {
m_screen->setClipboard(id, NULL); m_screen->setClipboard(id, nullptr);
} }
void void
@ -210,7 +210,7 @@ Screen::keyRepeat(KeyID id,
} }
void void
Screen::keyUp(KeyID, KeyModifierMask, KeyButton button) Screen::keyUp(KeyID /*unused*/, KeyModifierMask /*unused*/, KeyButton button)
{ {
m_screen->fakeKeyUp(button); m_screen->fakeKeyUp(button);
} }
@ -272,7 +272,7 @@ Screen::setOptions(const OptionsList& options)
{ {
// update options // update options
bool oldScreenSaverSync = m_screenSaverSync; bool oldScreenSaverSync = m_screenSaverSync;
for (UInt32 i = 0, n = (UInt32)options.size(); i < n; i += 2) { for (UInt32 i = 0, n = static_cast<UInt32>(options.size()); i < n; i += 2) {
if (options[i] == kOptionScreenSaverSync) { if (options[i] == kOptionScreenSaverSync) {
m_screenSaverSync = (options[i + 1] != 0); m_screenSaverSync = (options[i + 1] != 0);
LOG((CLOG_DEBUG1 "screen saver synchronization %s", m_screenSaverSync ? "on" : "off")); LOG((CLOG_DEBUG1 "screen saver synchronization %s", m_screenSaverSync ? "on" : "off"));
@ -378,11 +378,11 @@ Screen::isLockedToScreen() const
} }
if (m_enableDragDrop) { if (m_enableDragDrop) {
return (buttonID == kButtonLeft) ? false : true; return buttonID != kButtonLeft;
} }
else {
return true; return true;
}
} }
// not locked // not locked
@ -395,9 +395,9 @@ Screen::getJumpZoneSize() const
if (!m_isPrimary) { if (!m_isPrimary) {
return 0; return 0;
} }
else {
return m_screen->getJumpZoneSize(); return m_screen->getJumpZoneSize();
}
} }
void void
@ -535,7 +535,7 @@ Screen::enterPrimary()
} }
void void
Screen::enterSecondary(KeyModifierMask) Screen::enterSecondary(KeyModifierMask /*unused*/)
{ {
// do nothing // do nothing
} }
@ -556,4 +556,4 @@ Screen::leaveSecondary()
m_screen->fakeAllKeysUp(); m_screen->fakeAllKeysUp();
} }
} } // namespace synergy

View File

@ -143,27 +143,27 @@ public:
/*! /*!
Synthesize mouse events to generate a press of mouse button \c id. Synthesize mouse events to generate a press of mouse button \c id.
*/ */
void mouseDown(ButtonID id); void mouseDown(ButtonID button);
//! Notify of mouse release //! Notify of mouse release
/*! /*!
Synthesize mouse events to generate a release of mouse button \c id. Synthesize mouse events to generate a release of mouse button \c id.
*/ */
void mouseUp(ButtonID id); void mouseUp(ButtonID button);
//! Notify of mouse motion //! Notify of mouse motion
/*! /*!
Synthesize mouse events to generate mouse motion to the absolute Synthesize mouse events to generate mouse motion to the absolute
screen position \c xAbs,yAbs. screen position \c xAbs,yAbs.
*/ */
void mouseMove(SInt32 xAbs, SInt32 yAbs); void mouseMove(SInt32 x, SInt32 y);
//! Notify of mouse motion //! Notify of mouse motion
/*! /*!
Synthesize mouse events to generate mouse motion by the relative Synthesize mouse events to generate mouse motion by the relative
amount \c xRel,yRel. amount \c xRel,yRel.
*/ */
void mouseRelativeMove(SInt32 xRel, SInt32 yRel); void mouseRelativeMove(SInt32 dx, SInt32 dy);
//! Notify of mouse wheel motion //! Notify of mouse wheel motion
/*! /*!
@ -297,7 +297,7 @@ public:
virtual void* getEventTarget() const; virtual void* getEventTarget() const;
virtual bool getClipboard(ClipboardID id, IClipboard*) const; virtual bool getClipboard(ClipboardID id, IClipboard*) const;
virtual void getShape(SInt32& x, SInt32& y, 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; virtual void getCursorPos(SInt32& x, SInt32& y) const;
IPlatformScreen* getPlatformScreen() { return m_screen; } IPlatformScreen* getPlatformScreen() { return m_screen; }
@ -331,7 +331,7 @@ private:
// note toggle keys that toggles on up/down (false) or on // note toggle keys that toggles on up/down (false) or on
// transition (true) // transition (true)
KeyModifierMask m_halfDuplex; KeyModifierMask m_halfDuplex{};
// true if we're faking input on a primary screen // true if we're faking input on a primary screen
bool m_fakeInput; bool m_fakeInput;

View File

@ -18,27 +18,27 @@
#include "core/ServerApp.h" #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 "arch/Arch.h"
#include "base/EventQueue.h" #include "base/EventQueue.h"
#include "base/log_outputters.h"
#include "base/FunctionEventJob.h" #include "base/FunctionEventJob.h"
#include "base/TMethodJob.h"
#include "base/IEventQueue.h" #include "base/IEventQueue.h"
#include "base/Log.h" #include "base/Log.h"
#include "base/TMethodEventJob.h" #include "base/TMethodEventJob.h"
#include "base/TMethodJob.h"
#include "base/log_outputters.h"
#include "common/Version.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 #if SYSAPI_WIN32
#include "arch/win32/ArchMiscWindows.h" #include "arch/win32/ArchMiscWindows.h"
@ -56,9 +56,9 @@
#include "platform/OSXDragSimulator.h" #include "platform/OSXDragSimulator.h"
#endif #endif
#include <fstream>
#include <iostream> #include <iostream>
#include <stdio.h> #include <stdio.h>
#include <fstream>
// //
// ServerApp // ServerApp
@ -66,19 +66,18 @@
ServerApp::ServerApp(IEventQueue* events) : ServerApp::ServerApp(IEventQueue* events) :
App(events, new ServerArgs()), App(events, new ServerArgs()),
m_server(NULL), m_server(nullptr),
m_serverState(kUninitialized), m_serverState(kUninitialized),
m_serverScreen(NULL), m_serverScreen(nullptr),
m_primaryClient(NULL), m_primaryClient(nullptr),
m_listener(NULL), m_listener(nullptr),
m_timer(NULL), m_timer(nullptr),
m_synergyAddress(NULL) m_synergyAddress(nullptr)
{ {
} }
ServerApp::~ServerApp() ServerApp::~ServerApp()
{ = default;
}
void void
ServerApp::parseArgs(int argc, const char* const* argv) ServerApp::parseArgs(int argc, const char* const* argv)
@ -159,7 +158,7 @@ ServerApp::help()
} }
void void
ServerApp::reloadSignalHandler(Arch::ESignal, void*) ServerApp::reloadSignalHandler(Arch::ESignal /*unused*/, void* /*unused*/)
{ {
IEventQueue* events = App::instance().getEvents(); IEventQueue* events = App::instance().getEvents();
events->addEvent(Event(events->forServerApp().reloadConfig(), events->addEvent(Event(events->forServerApp().reloadConfig(),
@ -167,11 +166,11 @@ ServerApp::reloadSignalHandler(Arch::ESignal, void*)
} }
void void
ServerApp::reloadConfig(const Event&, void*) ServerApp::reloadConfig(const Event& /*unused*/, void* /*unused*/)
{ {
LOG((CLOG_DEBUG "reload configuration")); LOG((CLOG_DEBUG "reload configuration"));
if (loadConfig(args().m_configFile)) { if (loadConfig(args().m_configFile)) {
if (m_server != NULL) { if (m_server != nullptr) {
m_server->setConfig(*args().m_config); m_server->setConfig(*args().m_config);
} }
LOG((CLOG_NOTE "reloaded configuration")); LOG((CLOG_NOTE "reloaded configuration"));
@ -249,26 +248,26 @@ ServerApp::loadConfig(const String& pathname)
} }
void void
ServerApp::forceReconnect(const Event&, void*) ServerApp::forceReconnect(const Event& /*unused*/, void* /*unused*/)
{ {
if (m_server != NULL) { if (m_server != nullptr) {
m_server->disconnect(); m_server->disconnect();
} }
} }
void void
ServerApp::handleClientConnected(const Event&, void* vlistener) ServerApp::handleClientConnected(const Event& /*unused*/, void* vlistener)
{ {
ClientListener* listener = static_cast<ClientListener*>(vlistener); auto* listener = static_cast<ClientListener*>(vlistener);
ClientProxy* client = listener->getNextClient(); ClientProxy* client = listener->getNextClient();
if (client != NULL) { if (client != nullptr) {
m_server->adoptClient(client); m_server->adoptClient(client);
updateStatus(); updateStatus();
} }
} }
void void
ServerApp::handleClientsDisconnected(const Event&, void*) ServerApp::handleClientsDisconnected(const Event& /*unused*/, void* /*unused*/)
{ {
m_events->addEvent(Event(Event::kQuit)); m_events->addEvent(Event(Event::kQuit));
} }
@ -276,7 +275,7 @@ ServerApp::handleClientsDisconnected(const Event&, void*)
void void
ServerApp::closeServer(Server* server) ServerApp::closeServer(Server* server)
{ {
if (server == NULL) { if (server == nullptr) {
return; return;
} }
@ -285,7 +284,7 @@ ServerApp::closeServer(Server* server)
// wait for clients to disconnect for up to timeout seconds // wait for clients to disconnect for up to timeout seconds
double timeout = 3.0; double timeout = 3.0;
EventQueueTimer* timer = m_events->newOneShotTimer(timeout, NULL); EventQueueTimer* timer = m_events->newOneShotTimer(timeout, nullptr);
m_events->adoptHandler(Event::kTimer, timer, m_events->adoptHandler(Event::kTimer, timer,
new TMethodEventJob<ServerApp>(this, &ServerApp::handleClientsDisconnected)); new TMethodEventJob<ServerApp>(this, &ServerApp::handleClientsDisconnected));
m_events->adoptHandler(m_events->forServer().disconnected(), server, m_events->adoptHandler(m_events->forServer().disconnected(), server,
@ -304,10 +303,10 @@ ServerApp::closeServer(Server* server)
void void
ServerApp::stopRetryTimer() ServerApp::stopRetryTimer()
{ {
if (m_timer != NULL) { if (m_timer != nullptr) {
m_events->deleteTimer(m_timer); m_events->deleteTimer(m_timer);
m_events->removeHandler(Event::kTimer, NULL); m_events->removeHandler(Event::kTimer, nullptr);
m_timer = NULL; m_timer = nullptr;
} }
} }
@ -317,14 +316,14 @@ ServerApp::updateStatus()
updateStatus(""); updateStatus("");
} }
void ServerApp::updateStatus(const String& msg) void ServerApp::updateStatus(const String& /*msg*/)
{ {
} }
void void
ServerApp::closeClientListener(ClientListener* listen) ServerApp::closeClientListener(ClientListener* listen)
{ {
if (listen != NULL) { if (listen != nullptr) {
m_events->removeHandler(m_events->forClientListener().connected(), listen); m_events->removeHandler(m_events->forClientListener().connected(), listen);
delete listen; delete listen;
} }
@ -336,8 +335,8 @@ ServerApp::stopServer()
if (m_serverState == kStarted) { if (m_serverState == kStarted) {
closeServer(m_server); closeServer(m_server);
closeClientListener(m_listener); closeClientListener(m_listener);
m_server = NULL; m_server = nullptr;
m_listener = NULL; m_listener = nullptr;
m_serverState = kInitialized; m_serverState = kInitialized;
} }
else if (m_serverState == kStarting) { else if (m_serverState == kStarting) {
@ -357,7 +356,7 @@ ServerApp::closePrimaryClient(PrimaryClient* primaryClient)
void void
ServerApp::closeServerScreen(synergy::Screen* screen) ServerApp::closeServerScreen(synergy::Screen* screen)
{ {
if (screen != NULL) { if (screen != nullptr) {
m_events->removeHandler(m_events->forIScreen().error(), m_events->removeHandler(m_events->forIScreen().error(),
screen->getEventTarget()); screen->getEventTarget());
m_events->removeHandler(m_events->forIScreen().suspend(), m_events->removeHandler(m_events->forIScreen().suspend(),
@ -374,8 +373,8 @@ void ServerApp::cleanupServer()
if (m_serverState == kInitialized) { if (m_serverState == kInitialized) {
closePrimaryClient(m_primaryClient); closePrimaryClient(m_primaryClient);
closeServerScreen(m_serverScreen); closeServerScreen(m_serverScreen);
m_primaryClient = NULL; m_primaryClient = nullptr;
m_serverScreen = NULL; m_serverScreen = nullptr;
m_serverState = kUninitialized; m_serverState = kUninitialized;
} }
else if (m_serverState == kInitializing || else if (m_serverState == kInitializing ||
@ -389,7 +388,7 @@ void ServerApp::cleanupServer()
} }
void void
ServerApp::retryHandler(const Event&, void*) ServerApp::retryHandler(const Event& /*unused*/, void* /*unused*/)
{ {
// discard old timer // discard old timer
assert(m_timer != NULL); assert(m_timer != NULL);
@ -443,8 +442,8 @@ bool ServerApp::initServer()
} }
double retryTime; double retryTime;
synergy::Screen* serverScreen = NULL; synergy::Screen* serverScreen = nullptr;
PrimaryClient* primaryClient = NULL; PrimaryClient* primaryClient = nullptr;
try { try {
String name = args().m_config->getCanonicalName(args().m_name); String name = args().m_config->getCanonicalName(args().m_name);
serverScreen = openServerScreen(); serverScreen = openServerScreen();
@ -479,16 +478,16 @@ bool ServerApp::initServer()
// install a timer and handler to retry later // install a timer and handler to retry later
assert(m_timer == NULL); assert(m_timer == NULL);
LOG((CLOG_DEBUG "retry in %.0f seconds", retryTime)); 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, m_events->adoptHandler(Event::kTimer, m_timer,
new TMethodEventJob<ServerApp>(this, &ServerApp::retryHandler)); new TMethodEventJob<ServerApp>(this, &ServerApp::retryHandler));
m_serverState = kInitializing; m_serverState = kInitializing;
return true; return true;
} }
else {
// don't try again // don't try again
return false; return false;
}
} }
synergy::Screen* synergy::Screen*
@ -534,7 +533,7 @@ ServerApp::startServer()
} }
double retryTime; double retryTime;
ClientListener* listener = NULL; ClientListener* listener = nullptr;
try { try {
listener = openClientListener(args().m_config->getSynergyAddress()); listener = openClientListener(args().m_config->getSynergyAddress());
m_server = openServer(*args().m_config, m_primaryClient); m_server = openServer(*args().m_config, m_primaryClient);
@ -562,16 +561,16 @@ ServerApp::startServer()
// install a timer and handler to retry later // install a timer and handler to retry later
assert(m_timer == NULL); assert(m_timer == NULL);
LOG((CLOG_DEBUG "retry in %.0f seconds", retryTime)); 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, m_events->adoptHandler(Event::kTimer, m_timer,
new TMethodEventJob<ServerApp>(this, &ServerApp::retryHandler)); new TMethodEventJob<ServerApp>(this, &ServerApp::retryHandler));
m_serverState = kStarting; m_serverState = kStarting;
return true; return true;
} }
else {
// don't try again // don't try again
return false; return false;
}
} }
synergy::Screen* synergy::Screen*
@ -597,14 +596,14 @@ ServerApp::openPrimaryClient(const String& name, synergy::Screen* screen)
} }
void void
ServerApp::handleScreenError(const Event&, void*) ServerApp::handleScreenError(const Event& /*unused*/, void* /*unused*/)
{ {
LOG((CLOG_CRIT "error on screen")); LOG((CLOG_CRIT "error on screen"));
m_events->addEvent(Event(Event::kQuit)); m_events->addEvent(Event(Event::kQuit));
} }
void void
ServerApp::handleSuspend(const Event&, void*) ServerApp::handleSuspend(const Event& /*unused*/, void* /*unused*/)
{ {
if (!m_suspended) { if (!m_suspended) {
LOG((CLOG_INFO "suspend")); LOG((CLOG_INFO "suspend"));
@ -614,7 +613,7 @@ ServerApp::handleSuspend(const Event&, void*)
} }
void void
ServerApp::handleResume(const Event&, void*) ServerApp::handleResume(const Event& /*unused*/, void* /*unused*/)
{ {
if (m_suspended) { if (m_suspended) {
LOG((CLOG_INFO "resume")); LOG((CLOG_INFO "resume"));
@ -626,7 +625,7 @@ ServerApp::handleResume(const Event&, void*)
ClientListener* ClientListener*
ServerApp::openClientListener(const NetworkAddress& address) ServerApp::openClientListener(const NetworkAddress& address)
{ {
ClientListener* listen = new ClientListener( auto* listen = new ClientListener(
address, address,
new TCPSocketFactory(m_events, getSocketMultiplexer()), new TCPSocketFactory(m_events, getSocketMultiplexer()),
m_events); m_events);
@ -642,7 +641,7 @@ ServerApp::openClientListener(const NetworkAddress& address)
Server* Server*
ServerApp::openServer(Config& config, PrimaryClient* primaryClient) 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 { try {
m_events->adoptHandler( m_events->adoptHandler(
m_events->forServer().disconnected(), server, m_events->forServer().disconnected(), server,
@ -661,13 +660,13 @@ ServerApp::openServer(Config& config, PrimaryClient* primaryClient)
} }
void void
ServerApp::handleNoClients(const Event&, void*) ServerApp::handleNoClients(const Event& /*unused*/, void* /*unused*/)
{ {
updateStatus(); updateStatus();
} }
void 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 // 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->adoptHandler(m_events->forServerApp().reloadConfig(),
m_events->getSystemTarget(), m_events->getSystemTarget(),
new TMethodEventJob<ServerApp>(this, &ServerApp::reloadConfig)); new TMethodEventJob<ServerApp>(this, &ServerApp::reloadConfig));
@ -770,7 +769,7 @@ ServerApp::mainLoop()
return kExitSuccess; return kExitSuccess;
} }
void ServerApp::resetServer(const Event&, void*) void ServerApp::resetServer(const Event& /*unused*/, void* /*unused*/)
{ {
LOG((CLOG_DEBUG1 "resetting server")); LOG((CLOG_DEBUG1 "resetting server"));
stopServer(); stopServer();
@ -787,7 +786,7 @@ ServerApp::runInner(int argc, char** argv, ILogOutputter* outputter, StartupFunc
args().m_pname = ARCH->getBasename(argv[0]); args().m_pname = ARCH->getBasename(argv[0]);
// install caller's output filter // install caller's output filter
if (outputter != NULL) { if (outputter != nullptr) {
CLOG->insert(outputter); CLOG->insert(outputter);
} }
@ -812,9 +811,9 @@ ServerApp::standardStartup(int argc, char** argv)
if (args().m_daemon) { if (args().m_daemon) {
return ARCH->daemonize(daemonName(), daemonMainLoopStatic); return ARCH->daemonize(daemonName(), daemonMainLoopStatic);
} }
else {
return mainLoop(); return mainLoop();
}
} }
int int

View File

@ -18,9 +18,7 @@
#include "core/ServerArgs.h" #include "core/ServerArgs.h"
ServerArgs::ServerArgs() : ServerArgs::ServerArgs() :
m_configFile(), m_config(nullptr)
m_serial(),
m_config(NULL)
{ {
} }

View File

@ -17,12 +17,12 @@
*/ */
#include "core/ServerTaskBarReceiver.h" #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 "arch/Arch.h"
#include "base/IEventQueue.h"
#include "base/String.h"
#include "common/Version.h" #include "common/Version.h"
#include "mt/Lock.h"
#include "server/Server.h"
// //
// ServerTaskBarReceiver // ServerTaskBarReceiver
@ -46,7 +46,7 @@ ServerTaskBarReceiver::updateStatus(Server* server, const String& errorMsg)
{ {
// update our status // update our status
m_errorMessage = errorMsg; m_errorMessage = errorMsg;
if (server == NULL) { if (server == nullptr) {
if (m_errorMessage.empty()) { if (m_errorMessage.empty()) {
m_state = kNotRunning; m_state = kNotRunning;
} }
@ -98,7 +98,7 @@ ServerTaskBarReceiver::quit()
} }
void void
ServerTaskBarReceiver::onStatusChanged(Server*) ServerTaskBarReceiver::onStatusChanged(Server* /*unused*/)
{ {
// do nothing // do nothing
} }

View File

@ -17,19 +17,19 @@
#include "core/StreamChunker.h" #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/Event.h"
#include "base/IEventQueue.h"
#include "base/EventTypes.h" #include "base/EventTypes.h"
#include "base/EventTypes.h"
#include "base/IEventQueue.h"
#include "base/Log.h" #include "base/Log.h"
#include "base/Stopwatch.h" #include "base/Stopwatch.h"
#include "base/String.h" #include "base/String.h"
#include "common/stdexcept.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 <fstream> #include <fstream>
@ -39,7 +39,7 @@ static const size_t g_chunkSize = 32 * 1024; //32kb
bool StreamChunker::s_isChunkingFile = false; bool StreamChunker::s_isChunkingFile = false;
bool StreamChunker::s_interruptFile = false; bool StreamChunker::s_interruptFile = false;
Mutex* StreamChunker::s_interruptMutex = NULL; Mutex* StreamChunker::s_interruptMutex = nullptr;
void void
StreamChunker::sendFile( StreamChunker::sendFile(
@ -57,7 +57,7 @@ StreamChunker::sendFile(
// check file size // check file size
file.seekg (0, std::ios::end); file.seekg (0, std::ios::end);
size_t size = (size_t)file.tellg(); auto size = (size_t)file.tellg();
// send first message (file size) // send first message (file size)
String fileSize = synergy::string::sizeTypeToString(size); String fileSize = synergy::string::sizeTypeToString(size);
@ -84,9 +84,9 @@ StreamChunker::sendFile(
chunkSize = size - sentLength; chunkSize = size - sentLength;
} }
char* chunkData = new char[chunkSize]; auto* chunkData = new char[chunkSize];
file.read(chunkData, chunkSize); file.read(chunkData, chunkSize);
UInt8* data = reinterpret_cast<UInt8*>(chunkData); auto* data = reinterpret_cast<UInt8*>(chunkData);
FileChunk* fileChunk = FileChunk::data(data, chunkSize); FileChunk* fileChunk = FileChunk::data(data, chunkSize);
delete[] chunkData; delete[] chunkData;

View File

@ -17,10 +17,10 @@
#include "core/ToolApp.h" #include "core/ToolApp.h"
#include "core/ArgParser.h"
#include "arch/Arch.h" #include "arch/Arch.h"
#include "base/Log.h" #include "base/Log.h"
#include "base/String.h" #include "base/String.h"
#include "core/ArgParser.h"
#include <iostream> #include <iostream>
#include <sstream> #include <sstream>

View File

@ -23,7 +23,7 @@
// //
String String
XScreenOpenFailure::getWhat() const throw() XScreenOpenFailure::getWhat() const noexcept
{ {
return format("XScreenOpenFailure", "unable to open screen"); return format("XScreenOpenFailure", "unable to open screen");
} }
@ -34,7 +34,7 @@ XScreenOpenFailure::getWhat() const throw()
// //
String String
XScreenXInputFailure::getWhat() const throw() XScreenXInputFailure::getWhat() const noexcept
{ {
return ""; return "";
} }
@ -50,7 +50,7 @@ XScreenUnavailable::XScreenUnavailable(double timeUntilRetry) :
// do nothing // do nothing
} }
XScreenUnavailable::~XScreenUnavailable() _NOEXCEPT XScreenUnavailable::~XScreenUnavailable() noexcept
{ {
// do nothing // do nothing
} }
@ -62,7 +62,7 @@ XScreenUnavailable::getRetryTime() const
} }
String String
XScreenUnavailable::getWhat() const throw() XScreenUnavailable::getWhat() const noexcept
{ {
return format("XScreenUnavailable", "unable to open screen"); return format("XScreenUnavailable", "unable to open screen");
} }

View File

@ -17,6 +17,8 @@
*/ */
#include "core/XSynergy.h" #include "core/XSynergy.h"
#include <utility>
#include "base/String.h" #include "base/String.h"
// //
@ -24,7 +26,7 @@
// //
String String
XBadClient::getWhat() const throw() XBadClient::getWhat() const noexcept
{ {
return "XBadClient"; return "XBadClient";
} }
@ -42,19 +44,19 @@ XIncompatibleClient::XIncompatibleClient(int major, int minor) :
} }
int int
XIncompatibleClient::getMajor() const throw() XIncompatibleClient::getMajor() const noexcept
{ {
return m_major; return m_major;
} }
int int
XIncompatibleClient::getMinor() const throw() XIncompatibleClient::getMinor() const noexcept
{ {
return m_minor; return m_minor;
} }
String String
XIncompatibleClient::getWhat() const throw() XIncompatibleClient::getWhat() const noexcept
{ {
return format("XIncompatibleClient", "incompatible client %{1}.%{2}", return format("XIncompatibleClient", "incompatible client %{1}.%{2}",
synergy::string::sprintf("%d", m_major).c_str(), synergy::string::sprintf("%d", m_major).c_str(),
@ -66,20 +68,20 @@ XIncompatibleClient::getWhat() const throw()
// XDuplicateClient // XDuplicateClient
// //
XDuplicateClient::XDuplicateClient(const String& name) : XDuplicateClient::XDuplicateClient(String name) :
m_name(name) m_name(std::move(name))
{ {
// do nothing // do nothing
} }
const String& const String&
XDuplicateClient::getName() const throw() XDuplicateClient::getName() const noexcept
{ {
return m_name; return m_name;
} }
String String
XDuplicateClient::getWhat() const throw() XDuplicateClient::getWhat() const noexcept
{ {
return format("XDuplicateClient", "duplicate client %{1}", m_name.c_str()); return format("XDuplicateClient", "duplicate client %{1}", m_name.c_str());
} }
@ -89,20 +91,20 @@ XDuplicateClient::getWhat() const throw()
// XUnknownClient // XUnknownClient
// //
XUnknownClient::XUnknownClient(const String& name) : XUnknownClient::XUnknownClient(String name) :
m_name(name) m_name(std::move(name))
{ {
// do nothing // do nothing
} }
const String& const String&
XUnknownClient::getName() const throw() XUnknownClient::getName() const noexcept
{ {
return m_name; return m_name;
} }
String String
XUnknownClient::getWhat() const throw() XUnknownClient::getWhat() const noexcept
{ {
return format("XUnknownClient", "unknown client %{1}", m_name.c_str()); return format("XUnknownClient", "unknown client %{1}", m_name.c_str());
} }
@ -119,13 +121,13 @@ XExitApp::XExitApp(int code) :
} }
int int
XExitApp::getCode() const throw() XExitApp::getCode() const noexcept
{ {
return m_code; return m_code;
} }
String String
XExitApp::getWhat() const throw() XExitApp::getWhat() const noexcept
{ {
return format( return format(
"XExitApp", "exiting with code %{1}", "XExitApp", "exiting with code %{1}",

View File

@ -68,7 +68,7 @@ a client that is already connected.
*/ */
class XDuplicateClient : public XSynergy { class XDuplicateClient : public XSynergy {
public: public:
XDuplicateClient(const String& name); XDuplicateClient(String name);
virtual ~XDuplicateClient() _NOEXCEPT { } virtual ~XDuplicateClient() _NOEXCEPT { }
//! @name accessors //! @name accessors
@ -94,7 +94,7 @@ unknown to the server.
*/ */
class XUnknownClient : public XSynergy { class XUnknownClient : public XSynergy {
public: public:
XUnknownClient(const String& name); XUnknownClient(String name);
virtual ~XUnknownClient() _NOEXCEPT { } virtual ~XUnknownClient() _NOEXCEPT { }
//! @name accessors //! @name accessors

View File

@ -191,7 +191,7 @@ const KeyNameMapEntry kKeyNameMap[] = {
{ "Bar", 0x007c }, { "Bar", 0x007c },
{ "BraceR", 0x007d }, { "BraceR", 0x007d },
{ "Tilde", 0x007e }, { "Tilde", 0x007e },
{ NULL, 0 }, { nullptr, 0 },
}; };
const KeyModifierNameMapEntry kModifierNameMap[] = { const KeyModifierNameMapEntry kModifierNameMap[] = {
@ -204,5 +204,5 @@ const KeyModifierNameMapEntry kModifierNameMap[] = {
// { "ScrollLock", KeyModifierScrollLock }, // { "ScrollLock", KeyModifierScrollLock },
{ "Shift", KeyModifierShift }, { "Shift", KeyModifierShift },
{ "Super", KeyModifierSuper }, { "Super", KeyModifierSuper },
{ NULL, 0 }, { nullptr, 0 },
}; };

View File

@ -19,13 +19,12 @@
#include "core/unix/AppUtilUnix.h" #include "core/unix/AppUtilUnix.h"
#include "core/ArgsBase.h" #include "core/ArgsBase.h"
AppUtilUnix::AppUtilUnix(IEventQueue* events) AppUtilUnix::AppUtilUnix(IEventQueue* /*events*/)
{ {
} }
AppUtilUnix::~AppUtilUnix() AppUtilUnix::~AppUtilUnix()
{ = default;
}
int int
standardStartupStatic(int argc, char** argv) standardStartupStatic(int argc, char** argv)
@ -36,7 +35,7 @@ standardStartupStatic(int argc, char** argv)
int int
AppUtilUnix::run(int argc, char** argv) AppUtilUnix::run(int argc, char** argv)
{ {
return app().runInner(argc, argv, NULL, &standardStartupStatic); return app().runInner(argc, argv, nullptr, &standardStartupStatic);
} }
void void

View File

@ -44,15 +44,15 @@ StreamBuffer::peek(UInt32 n)
// if requesting no data then return NULL so we don't try to access // if requesting no data then return NULL so we don't try to access
// an empty list. // an empty list.
if (n == 0) { if (n == 0) {
return NULL; return nullptr;
} }
// reserve space in first chunk // reserve space in first chunk
ChunkList::iterator head = m_chunks.begin(); auto head = m_chunks.begin();
head->reserve(n + m_headUsed); head->reserve(n + m_headUsed);
// consolidate chunks into the first chunk until it has n bytes // consolidate chunks into the first chunk until it has n bytes
ChunkList::iterator scan = head; auto scan = head;
++scan; ++scan;
while (head->size() - m_headUsed < n && scan != m_chunks.end()) { while (head->size() - m_headUsed < n && scan != m_chunks.end()) {
head->insert(head->end(), scan->begin(), scan->end()); head->insert(head->end(), scan->begin(), scan->end());
@ -77,10 +77,10 @@ StreamBuffer::pop(UInt32 n)
m_size -= n; m_size -= n;
// discard chunks until more than n bytes would've been discarded // 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()); assert(scan != m_chunks.end());
while (scan->size() - m_headUsed <= n) { while (scan->size() - m_headUsed <= n) {
n -= (UInt32)scan->size() - m_headUsed; n -= static_cast<UInt32>(scan->size()) - m_headUsed;
m_headUsed = 0; m_headUsed = 0;
scan = m_chunks.erase(scan); scan = m_chunks.erase(scan);
assert(scan != m_chunks.end()); assert(scan != m_chunks.end());
@ -104,10 +104,10 @@ StreamBuffer::write(const void* vdata, UInt32 n)
m_size += n; m_size += n;
// cast data to bytes // cast data to bytes
const UInt8* data = static_cast<const UInt8*>(vdata); const auto* data = static_cast<const UInt8*>(vdata);
// point to last chunk if it has space, otherwise append an empty chunk // 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()) { if (scan != m_chunks.begin()) {
--scan; --scan;
if (scan->size() >= kChunkSize) { if (scan->size() >= kChunkSize) {
@ -122,9 +122,10 @@ StreamBuffer::write(const void* vdata, UInt32 n)
while (n > 0) { while (n > 0) {
// choose number of bytes for next chunk // choose number of bytes for next chunk
assert(scan->size() <= kChunkSize); assert(scan->size() <= kChunkSize);
UInt32 count = kChunkSize - (UInt32)scan->size(); UInt32 count = kChunkSize - static_cast<UInt32>(scan->size());
if (count > n) if (count > n) {
count = n; count = n;
}
// transfer data // transfer data
scan->insert(scan->end(), data, data + count); scan->insert(scan->end(), data, data + count);

View File

@ -53,7 +53,7 @@ public:
/*! /*!
Appends \c n bytes from \c data to the buffer. 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 //! @name accessors

View File

@ -112,7 +112,7 @@ StreamFilter::filterEvent(const Event& event)
} }
void void
StreamFilter::handleUpstreamEvent(const Event& event, void*) StreamFilter::handleUpstreamEvent(const Event& event, void* /*unused*/)
{ {
filterEvent(event); filterEvent(event);
} }

View File

@ -23,7 +23,7 @@
// //
String String
XIOClosed::getWhat() const throw() XIOClosed::getWhat() const noexcept
{ {
return format("XIOClosed", "already closed"); return format("XIOClosed", "already closed");
} }
@ -34,7 +34,7 @@ XIOClosed::getWhat() const throw()
// //
String String
XIOEndOfStream::getWhat() const throw() XIOEndOfStream::getWhat() const noexcept
{ {
return format("XIOEndOfStream", "reached end of stream"); return format("XIOEndOfStream", "reached end of stream");
} }
@ -45,7 +45,7 @@ XIOEndOfStream::getWhat() const throw()
// //
String String
XIOWouldBlock::getWhat() const throw() XIOWouldBlock::getWhat() const noexcept
{ {
return format("XIOWouldBlock", "stream operation would block"); return format("XIOWouldBlock", "stream operation would block");
} }

View File

@ -17,10 +17,10 @@
*/ */
#include "ipc/IpcClient.h" #include "ipc/IpcClient.h"
#include "ipc/Ipc.h"
#include "ipc/IpcServerProxy.h"
#include "ipc/IpcMessage.h"
#include "base/TMethodEventJob.h" #include "base/TMethodEventJob.h"
#include "ipc/Ipc.h"
#include "ipc/IpcMessage.h"
#include "ipc/IpcServerProxy.h"
// //
// IpcClient // IpcClient
@ -51,8 +51,7 @@ IpcClient::init()
} }
IpcClient::~IpcClient() IpcClient::~IpcClient()
{ = default;
}
void void
IpcClient::connect() IpcClient::connect()
@ -90,7 +89,7 @@ IpcClient::send(const IpcMessage& message)
} }
void void
IpcClient::handleConnected(const Event&, void*) IpcClient::handleConnected(const Event& /*unused*/, void* /*unused*/)
{ {
m_events->addEvent(Event( m_events->addEvent(Event(
m_events->forIpcClient().connected(), this, m_server, Event::kDontFreeData)); m_events->forIpcClient().connected(), this, m_server, Event::kDontFreeData));
@ -100,7 +99,7 @@ IpcClient::handleConnected(const Event&, void*)
} }
void void
IpcClient::handleMessageReceived(const Event& e, void*) IpcClient::handleMessageReceived(const Event& e, void* /*unused*/)
{ {
Event event(m_events->forIpcClient().messageReceived(), this); Event event(m_events->forIpcClient().messageReceived(), this);
event.setDataObject(e.getDataObject()); event.setDataObject(e.getDataObject());

View File

@ -18,13 +18,13 @@
#include "ipc/IpcClientProxy.h" #include "ipc/IpcClientProxy.h"
#include "ipc/Ipc.h" #include "arch/Arch.h"
#include "ipc/IpcMessage.h" #include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "core/ProtocolUtil.h" #include "core/ProtocolUtil.h"
#include "io/IStream.h" #include "io/IStream.h"
#include "arch/Arch.h" #include "ipc/Ipc.h"
#include "base/TMethodEventJob.h" #include "ipc/IpcMessage.h"
#include "base/Log.h"
// //
// IpcClientProxy // IpcClientProxy
@ -82,21 +82,21 @@ IpcClientProxy::~IpcClientProxy()
} }
void void
IpcClientProxy::handleDisconnect(const Event&, void*) IpcClientProxy::handleDisconnect(const Event& /*unused*/, void* /*unused*/)
{ {
disconnect(); disconnect();
LOG((CLOG_DEBUG "ipc client disconnected")); LOG((CLOG_DEBUG "ipc client disconnected"));
} }
void void
IpcClientProxy::handleWriteError(const Event&, void*) IpcClientProxy::handleWriteError(const Event& /*unused*/, void* /*unused*/)
{ {
disconnect(); disconnect();
LOG((CLOG_DEBUG "ipc client write error")); LOG((CLOG_DEBUG "ipc client write error"));
} }
void 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. // don't allow the dtor to destroy the stream while we're using it.
ArchMutexLock lock(m_readMutex); 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. // 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); e.setDataObject(m);
m_events->addEvent(e); m_events->addEvent(e);
@ -145,7 +145,7 @@ IpcClientProxy::send(const IpcMessage& message)
switch (message.type()) { switch (message.type()) {
case kIpcLogLine: { case kIpcLogLine: {
const IpcLogLineMessage& llm = static_cast<const IpcLogLineMessage&>(message); const auto& llm = dynamic_cast<const IpcLogLineMessage&>(message);
const String logLine = llm.logLine(); const String logLine = llm.logLine();
ProtocolUtil::writef(&m_stream, kIpcMsgLogLine, &logLine); ProtocolUtil::writef(&m_stream, kIpcMsgLogLine, &logLine);
break; break;

View File

@ -18,17 +18,17 @@
#include "ipc/IpcLogOutputter.h" #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/Arch.h"
#include "arch/XArch.h" #include "arch/XArch.h"
#include "base/Event.h" #include "base/Event.h"
#include "base/EventQueue.h" #include "base/EventQueue.h"
#include "base/TMethodEventJob.h" #include "base/TMethodEventJob.h"
#include "base/TMethodJob.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 { enum EIpcLogOutputter {
kBufferMaxSize = 1000, kBufferMaxSize = 1000,
@ -78,7 +78,7 @@ IpcLogOutputter::~IpcLogOutputter()
} }
void void
IpcLogOutputter::open(const char* title) IpcLogOutputter::open(const char* /*title*/)
{ {
} }
@ -94,12 +94,12 @@ IpcLogOutputter::close()
} }
void void
IpcLogOutputter::show(bool showIfEmpty) IpcLogOutputter::show(bool /*showIfEmpty*/)
{ {
} }
bool bool
IpcLogOutputter::write(ELevel, const char* text) IpcLogOutputter::write(ELevel /*level*/, const char* text)
{ {
// ignore events from the buffer thread (would cause recursion). // ignore events from the buffer thread (would cause recursion).
if (m_bufferThread != nullptr && if (m_bufferThread != nullptr &&
@ -148,7 +148,7 @@ IpcLogOutputter::isRunning()
} }
void void
IpcLogOutputter::bufferThread(void*) IpcLogOutputter::bufferThread(void* /*unused*/)
{ {
m_bufferThreadId = m_bufferThread->getID(); m_bufferThreadId = m_bufferThread->getID();
m_running = true; m_running = true;

View File

@ -47,7 +47,7 @@ public:
virtual void open(const char* title); virtual void open(const char* title);
virtual void close(); virtual void close();
virtual void show(bool showIfEmpty); virtual void show(bool showIfEmpty);
virtual bool write(ELevel level, const char* message); virtual bool write(ELevel level, const char* text);
//! @name manipulators //! @name manipulators
//@{ //@{

View File

@ -17,6 +17,8 @@
*/ */
#include "ipc/IpcMessage.h" #include "ipc/IpcMessage.h"
#include <utility>
#include "ipc/Ipc.h" #include "ipc/Ipc.h"
IpcMessage::IpcMessage(UInt8 type) : IpcMessage::IpcMessage(UInt8 type) :
@ -25,8 +27,7 @@ IpcMessage::IpcMessage(UInt8 type) :
} }
IpcMessage::~IpcMessage() IpcMessage::~IpcMessage()
{ = default;
}
IpcHelloMessage::IpcHelloMessage(EIpcClientType clientType) : IpcHelloMessage::IpcHelloMessage(EIpcClientType clientType) :
IpcMessage(kIpcHello), IpcMessage(kIpcHello),
@ -35,8 +36,7 @@ IpcHelloMessage::IpcHelloMessage(EIpcClientType clientType) :
} }
IpcHelloMessage::~IpcHelloMessage() IpcHelloMessage::~IpcHelloMessage()
{ = default;
}
IpcShutdownMessage::IpcShutdownMessage() : IpcShutdownMessage::IpcShutdownMessage() :
IpcMessage(kIpcShutdown) IpcMessage(kIpcShutdown)
@ -44,26 +44,23 @@ IpcMessage(kIpcShutdown)
} }
IpcShutdownMessage::~IpcShutdownMessage() IpcShutdownMessage::~IpcShutdownMessage()
{ = default;
}
IpcLogLineMessage::IpcLogLineMessage(const String& logLine) : IpcLogLineMessage::IpcLogLineMessage(String logLine) :
IpcMessage(kIpcLogLine), IpcMessage(kIpcLogLine),
m_logLine(logLine) m_logLine(std::move(logLine))
{ {
} }
IpcLogLineMessage::~IpcLogLineMessage() IpcLogLineMessage::~IpcLogLineMessage()
{ = default;
}
IpcCommandMessage::IpcCommandMessage(const String& command, bool elevate) : IpcCommandMessage::IpcCommandMessage(String command, bool elevate) :
IpcMessage(kIpcCommand), IpcMessage(kIpcCommand),
m_command(command), m_command(std::move(command)),
m_elevate(elevate) m_elevate(elevate)
{ {
} }
IpcCommandMessage::~IpcCommandMessage() IpcCommandMessage::~IpcCommandMessage()
{ = default;
}

View File

@ -58,7 +58,7 @@ public:
class IpcLogLineMessage : public IpcMessage { class IpcLogLineMessage : public IpcMessage {
public: public:
IpcLogLineMessage(const String& logLine); IpcLogLineMessage(String logLine);
virtual ~IpcLogLineMessage(); virtual ~IpcLogLineMessage();
//! Gets the log line. //! Gets the log line.
@ -70,7 +70,7 @@ private:
class IpcCommandMessage : public IpcMessage { class IpcCommandMessage : public IpcMessage {
public: public:
IpcCommandMessage(const String& command, bool elevate); IpcCommandMessage(String command, bool elevate);
virtual ~IpcCommandMessage(); virtual ~IpcCommandMessage();
//! Gets the command. //! Gets the command.

View File

@ -18,15 +18,15 @@
#include "ipc/IpcServer.h" #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/Ipc.h"
#include "ipc/IpcClientProxy.h" #include "ipc/IpcClientProxy.h"
#include "ipc/IpcMessage.h" #include "ipc/IpcMessage.h"
#include "net/IDataSocket.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 // IpcServer
@ -71,9 +71,9 @@ IpcServer::~IpcServer()
return; return;
} }
if (m_socket != nullptr) {
delete m_socket; delete m_socket;
}
ARCH->lockMutex(m_clientsMutex); ARCH->lockMutex(m_clientsMutex);
ClientList::iterator it; ClientList::iterator it;
@ -94,17 +94,17 @@ IpcServer::listen()
} }
void void
IpcServer::handleClientConnecting(const Event&, void*) IpcServer::handleClientConnecting(const Event& /*unused*/, void* /*unused*/)
{ {
synergy::IStream* stream = m_socket->accept(); synergy::IStream* stream = m_socket->accept();
if (stream == NULL) { if (stream == nullptr) {
return; return;
} }
LOG((CLOG_DEBUG "accepted ipc client connection")); LOG((CLOG_DEBUG "accepted ipc client connection"));
ARCH->lockMutex(m_clientsMutex); ARCH->lockMutex(m_clientsMutex);
IpcClientProxy* proxy = new IpcClientProxy(*stream, m_events); auto* proxy = new IpcClientProxy(*stream, m_events);
m_clients.push_back(proxy); m_clients.push_back(proxy);
ARCH->unlockMutex(m_clientsMutex); ARCH->unlockMutex(m_clientsMutex);
@ -123,9 +123,9 @@ IpcServer::handleClientConnecting(const Event&, void*)
} }
void void
IpcServer::handleClientDisconnected(const Event& e, void*) IpcServer::handleClientDisconnected(const Event& e, void* /*unused*/)
{ {
IpcClientProxy* proxy = static_cast<IpcClientProxy*>(e.getTarget()); auto* proxy = static_cast<IpcClientProxy*>(e.getTarget());
ArchMutexLock lock(m_clientsMutex); ArchMutexLock lock(m_clientsMutex);
m_clients.remove(proxy); m_clients.remove(proxy);
@ -135,7 +135,7 @@ IpcServer::handleClientDisconnected(const Event& e, void*)
} }
void void
IpcServer::handleMessageReceived(const Event& e, void*) IpcServer::handleMessageReceived(const Event& e, void* /*unused*/)
{ {
Event event(m_events->forIpcServer().messageReceived(), this); Event event(m_events->forIpcServer().messageReceived(), this);
event.setDataObject(e.getDataObject()); event.setDataObject(e.getDataObject());

View File

@ -76,10 +76,10 @@ private:
bool m_mock; bool m_mock;
IEventQueue* m_events; IEventQueue* m_events;
SocketMultiplexer* m_socketMultiplexer; SocketMultiplexer* m_socketMultiplexer;
TCPListenSocket* m_socket; TCPListenSocket* m_socket{};
NetworkAddress m_address; NetworkAddress m_address;
ClientList m_clients; ClientList m_clients;
ArchMutex m_clientsMutex; ArchMutex m_clientsMutex{};
#ifdef TEST_ENV #ifdef TEST_ENV
public: public:

View File

@ -18,12 +18,12 @@
#include "ipc/IpcServerProxy.h" #include "ipc/IpcServerProxy.h"
#include "ipc/IpcMessage.h" #include "base/Log.h"
#include "ipc/Ipc.h" #include "base/TMethodEventJob.h"
#include "core/ProtocolUtil.h" #include "core/ProtocolUtil.h"
#include "io/IStream.h" #include "io/IStream.h"
#include "base/TMethodEventJob.h" #include "ipc/Ipc.h"
#include "base/Log.h" #include "ipc/IpcMessage.h"
// //
// IpcServerProxy // IpcServerProxy
@ -46,7 +46,7 @@ IpcServerProxy::~IpcServerProxy()
} }
void void
IpcServerProxy::handleData(const Event&, void*) IpcServerProxy::handleData(const Event& /*unused*/, void* /*unused*/)
{ {
LOG((CLOG_DEBUG "start ipc handle data")); 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. // 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); e.setDataObject(m);
m_events->addEvent(e); m_events->addEvent(e);
@ -87,13 +87,13 @@ IpcServerProxy::send(const IpcMessage& message)
switch (message.type()) { switch (message.type()) {
case kIpcHello: { case kIpcHello: {
const IpcHelloMessage& hm = static_cast<const IpcHelloMessage&>(message); const auto& hm = dynamic_cast<const IpcHelloMessage&>(message);
ProtocolUtil::writef(&m_stream, kIpcMsgHello, hm.clientType()); ProtocolUtil::writef(&m_stream, kIpcMsgHello, hm.clientType());
break; break;
} }
case kIpcCommand: { case kIpcCommand: {
const IpcCommandMessage& cm = static_cast<const IpcCommandMessage&>(message); const auto& cm = dynamic_cast<const IpcCommandMessage&>(message);
const String command = cm.command(); const String command = cm.command();
ProtocolUtil::writef(&m_stream, kIpcMsgCommand, &command); ProtocolUtil::writef(&m_stream, kIpcMsgCommand, &command);
break; break;

View File

@ -70,9 +70,11 @@ CondVarBase::wait(Stopwatch& timer, double timeout) const
// Always call wait at least once, even if remain is 0, to give // 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 // other thread a chance to grab the mutex to avoid deadlocks on
// busy waiting. // busy waiting.
if (remain<0.0) remain=0.0; if (remain<0.0) { remain=0.0;
if (wait(remain)) }
if (wait(remain)) {
return true; return true;
}
remain = timeout - timer.getTime(); remain = timeout - timer.getTime();
} while (remain >= 0.0); } while (remain >= 0.0);
return false; return false;

View File

@ -29,7 +29,7 @@ Mutex::Mutex()
m_mutex = ARCH->newMutex(); m_mutex = ARCH->newMutex();
} }
Mutex::Mutex(const Mutex&) Mutex::Mutex(const Mutex& /*unused*/)
{ {
m_mutex = ARCH->newMutex(); m_mutex = ARCH->newMutex();
} }
@ -40,7 +40,7 @@ Mutex::~Mutex()
} }
Mutex& Mutex&
Mutex::operator=(const Mutex&) Mutex::operator=(const Mutex& /*unused*/)
{ {
return *this; return *this;
} }

View File

@ -18,11 +18,11 @@
#include "mt/Thread.h" #include "mt/Thread.h"
#include "arch/Arch.h"
#include "base/IJob.h"
#include "base/Log.h"
#include "mt/XMT.h" #include "mt/XMT.h"
#include "mt/XThread.h" #include "mt/XThread.h"
#include "arch/Arch.h"
#include "base/Log.h"
#include "base/IJob.h"
// //
// Thread // Thread
@ -31,7 +31,7 @@
Thread::Thread(IJob* job) Thread::Thread(IJob* job)
{ {
m_thread = ARCH->newThread(&Thread::threadFunc, job); m_thread = ARCH->newThread(&Thread::threadFunc, job);
if (m_thread == NULL) { if (m_thread == nullptr) {
// couldn't create thread // couldn't create thread
delete job; delete job;
throw XMTThreadUnavailable(); throw XMTThreadUnavailable();
@ -111,10 +111,11 @@ Thread::wait(double timeout) const
void* void*
Thread::getResult() const Thread::getResult() const
{ {
if (wait()) if (wait()) {
return ARCH->getResultOfThread(m_thread); return ARCH->getResultOfThread(m_thread);
else } else {
return NULL; return nullptr;
}
} }
IArchMultithread::ThreadID IArchMultithread::ThreadID
@ -147,10 +148,10 @@ Thread::threadFunc(void* vjob)
} }
// get job // get job
IJob* job = static_cast<IJob*>(vjob); auto* job = static_cast<IJob*>(vjob);
// run job // run job
void* result = NULL; void* result = nullptr;
try { try {
// go // go
LOG((CLOG_DEBUG1 "thread 0x%08x entry", id)); LOG((CLOG_DEBUG1 "thread 0x%08x entry", id));

View File

@ -47,7 +47,7 @@ public:
Create and start a new thread executing the \c adoptedJob. The Create and start a new thread executing the \c adoptedJob. The
new thread takes ownership of \c adoptedJob and will delete it. new thread takes ownership of \c adoptedJob and will delete it.
*/ */
Thread(IJob* adoptedJob); Thread(IJob* job);
//! Duplicate a thread handle //! Duplicate a thread handle
/*! /*!

View File

@ -23,7 +23,7 @@
// //
String String
XMTThreadUnavailable::getWhat() const throw() XMTThreadUnavailable::getWhat() const noexcept
{ {
return format("XMTThreadUnavailable", "cannot create thread"); return format("XMTThreadUnavailable", "cannot create thread");
} }

Some files were not shown because too many files have changed in this diff Show More