diff --git a/.clang-format b/.clang-format index 6a994d72f..560b799c7 100644 --- a/.clang-format +++ b/.clang-format @@ -13,16 +13,40 @@ BasedOnStyle: LLVM # Turn off LLVM default alignment of params with the opening bracket, # which can be less readable in some cases in our code base. # -# Using `AlwaysBreak` will result in: +# Using `BlockIndent` will result in: # void fooBarBazQuxHelloWorld( # int a, -# int b); +# int b +# ); # # Instead of: # void fooBarBazQuxHelloWorld(int a, # int b); -AlignAfterOpenBracket: AlwaysBreak +AlignAfterOpenBracket: BlockIndent # Turn off LLVM default packing of ctor initializers. # This makes it easier to see which members were initialized and in what order. PackConstructorInitializers: CurrentLine + +# up our limit to 120 +ColumnLimit: 120 + +# Custom Breaking rules +BreakBeforeBraces: Custom +BraceWrapping: + AfterCaseLabel: false + AfterClass: true + AfterControlStatement: Never + AfterEnum: true + AfterFunction: true + AfterNamespace: false + AfterStruct: true + AfterUnion: true + AfterExternBlock: true + BeforeCatch: false + BeforeElse: false + BeforeLambdaBody: false + BeforeWhile: false + +# no single line functions +AllowShortFunctionsOnASingleLine: None diff --git a/src/cmd/deskflow-core/deskflow-core.cpp b/src/cmd/deskflow-core/deskflow-core.cpp index 828b77cb2..f104f9d18 100644 --- a/src/cmd/deskflow-core/deskflow-core.cpp +++ b/src/cmd/deskflow-core/deskflow-core.cpp @@ -26,27 +26,26 @@ #include "arch/win32/ArchMiscWindows.h" #endif -void showHelp() { - std::cout << "Usage: " CORE_BINARY_NAME " [...options]" - << std::endl; - std::cout << "server - start as a server (" << SERVER_BINARY_NAME << ")" - << std::endl; - std::cout << "client - start as a client (" << CLIENT_BINARY_NAME << ")" - << std::endl; - std::cout << "use " CORE_BINARY_NAME - " --help for more information." - << std::endl; +void showHelp() +{ + std::cout << "Usage: " CORE_BINARY_NAME " [...options]" << std::endl; + std::cout << "server - start as a server (" << SERVER_BINARY_NAME << ")" << std::endl; + std::cout << "client - start as a client (" << CLIENT_BINARY_NAME << ")" << std::endl; + std::cout << "use " CORE_BINARY_NAME " --help for more information." << std::endl; } -bool isServer(int argc, char **argv) { +bool isServer(int argc, char **argv) +{ return (argc > 1 && argv[1] == std::string("server")); } -bool isClient(int argc, char **argv) { +bool isClient(int argc, char **argv) +{ return (argc > 1 && argv[1] == std::string("client")); } -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ #if SYSAPI_WIN32 ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL)); #endif diff --git a/src/cmd/deskflow-legacy/deskflow-legacy.cpp b/src/cmd/deskflow-legacy/deskflow-legacy.cpp index 70e68a178..d187496de 100644 --- a/src/cmd/deskflow-legacy/deskflow-legacy.cpp +++ b/src/cmd/deskflow-legacy/deskflow-legacy.cpp @@ -22,7 +22,8 @@ #include "arch/win32/ArchMiscWindows.h" #endif -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ #if SYSAPI_WIN32 // record window instance for tray icon, etc ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL)); diff --git a/src/cmd/deskflowc/MSWindowsClientTaskBarReceiver.cpp b/src/cmd/deskflowc/MSWindowsClientTaskBarReceiver.cpp index 2f0a3b10b..015a1dd89 100644 --- a/src/cmd/deskflowc/MSWindowsClientTaskBarReceiver.cpp +++ b/src/cmd/deskflowc/MSWindowsClientTaskBarReceiver.cpp @@ -34,16 +34,18 @@ // const UINT MSWindowsClientTaskBarReceiver::s_stateToIconID[kMaxState] = { - IDI_TASKBAR_NOT_RUNNING, IDI_TASKBAR_NOT_WORKING, IDI_TASKBAR_NOT_CONNECTED, - IDI_TASKBAR_NOT_CONNECTED, IDI_TASKBAR_CONNECTED}; + IDI_TASKBAR_NOT_RUNNING, IDI_TASKBAR_NOT_WORKING, IDI_TASKBAR_NOT_CONNECTED, IDI_TASKBAR_NOT_CONNECTED, + IDI_TASKBAR_CONNECTED +}; MSWindowsClientTaskBarReceiver::MSWindowsClientTaskBarReceiver( - HINSTANCE appInstance, const BufferedLogOutputter *logBuffer, - IEventQueue *events) + HINSTANCE appInstance, const BufferedLogOutputter *logBuffer, IEventQueue *events +) : ClientTaskBarReceiver(events), m_appInstance(appInstance), m_window(NULL), - m_logBuffer(logBuffer) { + m_logBuffer(logBuffer) +{ for (UInt32 i = 0; i < kMaxState; ++i) { m_icon[i] = loadIcon(s_stateToIconID[i]); } @@ -58,9 +60,13 @@ MSWindowsClientTaskBarReceiver::MSWindowsClientTaskBarReceiver( ARCH->addReceiver(this); } -MSWindowsClientTaskBarReceiver::~MSWindowsClientTaskBarReceiver() { cleanup(); } +MSWindowsClientTaskBarReceiver::~MSWindowsClientTaskBarReceiver() +{ + cleanup(); +} -void MSWindowsClientTaskBarReceiver::cleanup() { +void MSWindowsClientTaskBarReceiver::cleanup() +{ ARCH->removeReceiver(this); for (UInt32 i = 0; i < kMaxState; ++i) { deleteIcon(m_icon[i]); @@ -69,7 +75,8 @@ void MSWindowsClientTaskBarReceiver::cleanup() { destroyWindow(); } -void MSWindowsClientTaskBarReceiver::showStatus() { +void MSWindowsClientTaskBarReceiver::showStatus() +{ // create the window createWindow(); @@ -126,7 +133,8 @@ void MSWindowsClientTaskBarReceiver::showStatus() { } } -void MSWindowsClientTaskBarReceiver::runMenu(int x, int y) { +void MSWindowsClientTaskBarReceiver::runMenu(int x, int y) +{ // do popup menu. we need a window to pass to TrackPopupMenu(). // the SetForegroundWindow() and SendMessage() calls around // TrackPopupMenu() are to get the menu to be dismissed when @@ -137,11 +145,9 @@ void MSWindowsClientTaskBarReceiver::runMenu(int x, int y) { HMENU menu = GetSubMenu(m_menu, 0); SetMenuDefaultItem(menu, IDC_TASKBAR_STATUS, FALSE); HMENU logLevelMenu = GetSubMenu(menu, 3); - CheckMenuRadioItem( - logLevelMenu, 0, 6, CLOG->getFilter() - kERROR, MF_BYPOSITION); - int n = TrackPopupMenu( - menu, TPM_NONOTIFY | TPM_RETURNCMD | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, x, - y, 0, m_window, NULL); + CheckMenuRadioItem(logLevelMenu, 0, 6, CLOG->getFilter() - kERROR, MF_BYPOSITION); + int n = + TrackPopupMenu(menu, TPM_NONOTIFY | TPM_RETURNCMD | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, x, y, 0, m_window, NULL); SendMessage(m_window, WM_NULL, 0, 0); // perform the requested operation @@ -192,19 +198,22 @@ void MSWindowsClientTaskBarReceiver::runMenu(int x, int y) { } } -void MSWindowsClientTaskBarReceiver::primaryAction() { showStatus(); } +void MSWindowsClientTaskBarReceiver::primaryAction() +{ + showStatus(); +} -const IArchTaskBarReceiver::Icon -MSWindowsClientTaskBarReceiver::getIcon() const { +const IArchTaskBarReceiver::Icon MSWindowsClientTaskBarReceiver::getIcon() const +{ return static_cast(m_icon[getStatus()]); } -void MSWindowsClientTaskBarReceiver::copyLog() const { +void MSWindowsClientTaskBarReceiver::copyLog() const +{ if (m_logBuffer != NULL) { // collect log buffer String data; - for (BufferedLogOutputter::const_iterator index = m_logBuffer->begin(); - index != m_logBuffer->end(); ++index) { + for (BufferedLogOutputter::const_iterator index = m_logBuffer->begin(); index != m_logBuffer->end(); ++index) { data += *index; data += "\n"; } @@ -220,26 +229,29 @@ void MSWindowsClientTaskBarReceiver::copyLog() const { } } -void MSWindowsClientTaskBarReceiver::onStatusChanged() { +void MSWindowsClientTaskBarReceiver::onStatusChanged() +{ if (IsWindowVisible(m_window)) { showStatus(); } } HICON -MSWindowsClientTaskBarReceiver::loadIcon(UINT id) { - HANDLE icon = LoadImage( - m_appInstance, MAKEINTRESOURCE(id), IMAGE_ICON, 0, 0, LR_DEFAULTCOLOR); +MSWindowsClientTaskBarReceiver::loadIcon(UINT id) +{ + HANDLE icon = LoadImage(m_appInstance, MAKEINTRESOURCE(id), IMAGE_ICON, 0, 0, LR_DEFAULTCOLOR); return static_cast(icon); } -void MSWindowsClientTaskBarReceiver::deleteIcon(HICON icon) { +void MSWindowsClientTaskBarReceiver::deleteIcon(HICON icon) +{ if (icon != NULL) { DestroyIcon(icon); } } -void MSWindowsClientTaskBarReceiver::createWindow() { +void MSWindowsClientTaskBarReceiver::createWindow() +{ // ignore if already created if (m_window != NULL) { return; @@ -247,9 +259,9 @@ void MSWindowsClientTaskBarReceiver::createWindow() { // get the status dialog m_window = CreateDialogParam( - m_appInstance, MAKEINTRESOURCE(IDD_TASKBAR_STATUS), NULL, - (DLGPROC)&MSWindowsClientTaskBarReceiver::staticDlgProc, - reinterpret_cast(static_cast(this))); + m_appInstance, MAKEINTRESOURCE(IDD_TASKBAR_STATUS), NULL, (DLGPROC)&MSWindowsClientTaskBarReceiver::staticDlgProc, + reinterpret_cast(static_cast(this)) + ); // window should appear on top of everything, including (especially) // the task bar. @@ -261,7 +273,8 @@ void MSWindowsClientTaskBarReceiver::createWindow() { ArchTaskBarWindows::addDialog(m_window); } -void MSWindowsClientTaskBarReceiver::destroyWindow() { +void MSWindowsClientTaskBarReceiver::destroyWindow() +{ if (m_window != NULL) { ArchTaskBarWindows::removeDialog(m_window); DestroyWindow(m_window); @@ -269,8 +282,8 @@ void MSWindowsClientTaskBarReceiver::destroyWindow() { } } -BOOL MSWindowsClientTaskBarReceiver::dlgProc( - HWND hwnd, UINT msg, WPARAM wParam, LPARAM) { +BOOL MSWindowsClientTaskBarReceiver::dlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM) +{ switch (msg) { case WM_INITDIALOG: // use default focus @@ -286,14 +299,13 @@ BOOL MSWindowsClientTaskBarReceiver::dlgProc( return FALSE; } -BOOL CALLBACK MSWindowsClientTaskBarReceiver::staticDlgProc( - HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { +BOOL CALLBACK MSWindowsClientTaskBarReceiver::staticDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ // if msg is WM_INITDIALOG, extract the MSWindowsClientTaskBarReceiver* // and put it in the extra window data then forward the call. MSWindowsClientTaskBarReceiver *self = NULL; if (msg == WM_INITDIALOG) { - self = static_cast( - reinterpret_cast(lParam)); + self = static_cast(reinterpret_cast(lParam)); SetWindowLongPtr(hwnd, GWLP_USERDATA, (LONG_PTR)lParam); } else { // get the extra window data and forward the call @@ -311,16 +323,12 @@ BOOL CALLBACK MSWindowsClientTaskBarReceiver::staticDlgProc( } } -IArchTaskBarReceiver *createTaskBarReceiver( - const BufferedLogOutputter *logBuffer, IEventQueue *events) { +IArchTaskBarReceiver *createTaskBarReceiver(const BufferedLogOutputter *logBuffer, IEventQueue *events) +{ ArchMiscWindows::setIcons( - (HICON)LoadImage( - ArchMiscWindows::instanceWin32(), MAKEINTRESOURCE(IDI_DESKFLOW), - IMAGE_ICON, 32, 32, LR_SHARED), - (HICON)LoadImage( - ArchMiscWindows::instanceWin32(), MAKEINTRESOURCE(IDI_DESKFLOW), - IMAGE_ICON, 16, 16, LR_SHARED)); + (HICON)LoadImage(ArchMiscWindows::instanceWin32(), MAKEINTRESOURCE(IDI_DESKFLOW), IMAGE_ICON, 32, 32, LR_SHARED), + (HICON)LoadImage(ArchMiscWindows::instanceWin32(), MAKEINTRESOURCE(IDI_DESKFLOW), IMAGE_ICON, 16, 16, LR_SHARED) + ); - return new MSWindowsClientTaskBarReceiver( - MSWindowsScreen::getWindowInstance(), logBuffer, events); + return new MSWindowsClientTaskBarReceiver(MSWindowsScreen::getWindowInstance(), logBuffer, events); } diff --git a/src/cmd/deskflowc/MSWindowsClientTaskBarReceiver.h b/src/cmd/deskflowc/MSWindowsClientTaskBarReceiver.h index 090a0cced..d6a00d63c 100644 --- a/src/cmd/deskflowc/MSWindowsClientTaskBarReceiver.h +++ b/src/cmd/deskflowc/MSWindowsClientTaskBarReceiver.h @@ -27,10 +27,10 @@ class BufferedLogOutputter; class IEventQueue; //! Implementation of ClientTaskBarReceiver for Microsoft Windows -class MSWindowsClientTaskBarReceiver : public ClientTaskBarReceiver { +class MSWindowsClientTaskBarReceiver : public ClientTaskBarReceiver +{ public: - MSWindowsClientTaskBarReceiver( - HINSTANCE, const BufferedLogOutputter *, IEventQueue *events); + MSWindowsClientTaskBarReceiver(HINSTANCE, const BufferedLogOutputter *, IEventQueue *events); virtual ~MSWindowsClientTaskBarReceiver(); // IArchTaskBarReceiver overrides @@ -53,8 +53,7 @@ private: void destroyWindow(); BOOL dlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); - static BOOL CALLBACK - staticDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); + static BOOL CALLBACK staticDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); private: HINSTANCE m_appInstance; diff --git a/src/cmd/deskflowc/OSXClientTaskBarReceiver.cpp b/src/cmd/deskflowc/OSXClientTaskBarReceiver.cpp index bbd8e12e5..baaae0445 100644 --- a/src/cmd/deskflowc/OSXClientTaskBarReceiver.cpp +++ b/src/cmd/deskflowc/OSXClientTaskBarReceiver.cpp @@ -23,34 +23,39 @@ // OSXClientTaskBarReceiver // -OSXClientTaskBarReceiver::OSXClientTaskBarReceiver( - const BufferedLogOutputter *, IEventQueue *events) - : ClientTaskBarReceiver(events) { +OSXClientTaskBarReceiver::OSXClientTaskBarReceiver(const BufferedLogOutputter *, IEventQueue *events) + : ClientTaskBarReceiver(events) +{ // add ourself to the task bar ARCH->addReceiver(this); } -OSXClientTaskBarReceiver::~OSXClientTaskBarReceiver() { +OSXClientTaskBarReceiver::~OSXClientTaskBarReceiver() +{ ARCH->removeReceiver(this); } -void OSXClientTaskBarReceiver::showStatus() { +void OSXClientTaskBarReceiver::showStatus() +{ // do nothing } -void OSXClientTaskBarReceiver::runMenu(int, int) { +void OSXClientTaskBarReceiver::runMenu(int, int) +{ // do nothing } -void OSXClientTaskBarReceiver::primaryAction() { +void OSXClientTaskBarReceiver::primaryAction() +{ // do nothing } -const IArchTaskBarReceiver::Icon OSXClientTaskBarReceiver::getIcon() const { +const IArchTaskBarReceiver::Icon OSXClientTaskBarReceiver::getIcon() const +{ return NULL; } -IArchTaskBarReceiver *createTaskBarReceiver( - const BufferedLogOutputter *logBuffer, IEventQueue *events) { +IArchTaskBarReceiver *createTaskBarReceiver(const BufferedLogOutputter *logBuffer, IEventQueue *events) +{ return new OSXClientTaskBarReceiver(logBuffer, events); } diff --git a/src/cmd/deskflowc/OSXClientTaskBarReceiver.h b/src/cmd/deskflowc/OSXClientTaskBarReceiver.h index 31e3d971f..0a2e9f292 100644 --- a/src/cmd/deskflowc/OSXClientTaskBarReceiver.h +++ b/src/cmd/deskflowc/OSXClientTaskBarReceiver.h @@ -24,7 +24,8 @@ class BufferedLogOutputter; class IEventQueue; //! Implementation of ClientTaskBarReceiver for OS X -class OSXClientTaskBarReceiver : public ClientTaskBarReceiver { +class OSXClientTaskBarReceiver : public ClientTaskBarReceiver +{ public: OSXClientTaskBarReceiver(const BufferedLogOutputter *, IEventQueue *events); virtual ~OSXClientTaskBarReceiver(); diff --git a/src/cmd/deskflowc/XWindowsClientTaskBarReceiver.cpp b/src/cmd/deskflowc/XWindowsClientTaskBarReceiver.cpp index 0f45b919d..84e3638c9 100644 --- a/src/cmd/deskflowc/XWindowsClientTaskBarReceiver.cpp +++ b/src/cmd/deskflowc/XWindowsClientTaskBarReceiver.cpp @@ -23,35 +23,39 @@ // CXWindowsClientTaskBarReceiver // -CXWindowsClientTaskBarReceiver::CXWindowsClientTaskBarReceiver( - const BufferedLogOutputter *, IEventQueue *events) - : ClientTaskBarReceiver(events) { +CXWindowsClientTaskBarReceiver::CXWindowsClientTaskBarReceiver(const BufferedLogOutputter *, IEventQueue *events) + : ClientTaskBarReceiver(events) +{ // add ourself to the task bar ARCH->addReceiver(this); } -CXWindowsClientTaskBarReceiver::~CXWindowsClientTaskBarReceiver() { +CXWindowsClientTaskBarReceiver::~CXWindowsClientTaskBarReceiver() +{ ARCH->removeReceiver(this); } -void CXWindowsClientTaskBarReceiver::showStatus() { +void CXWindowsClientTaskBarReceiver::showStatus() +{ // do nothing } -void CXWindowsClientTaskBarReceiver::runMenu(int, int) { +void CXWindowsClientTaskBarReceiver::runMenu(int, int) +{ // do nothing } -void CXWindowsClientTaskBarReceiver::primaryAction() { +void CXWindowsClientTaskBarReceiver::primaryAction() +{ // do nothing } -const IArchTaskBarReceiver::Icon -CXWindowsClientTaskBarReceiver::getIcon() const { +const IArchTaskBarReceiver::Icon CXWindowsClientTaskBarReceiver::getIcon() const +{ return NULL; } -IArchTaskBarReceiver *createTaskBarReceiver( - const BufferedLogOutputter *logBuffer, IEventQueue *events) { +IArchTaskBarReceiver *createTaskBarReceiver(const BufferedLogOutputter *logBuffer, IEventQueue *events) +{ return new CXWindowsClientTaskBarReceiver(logBuffer, events); } diff --git a/src/cmd/deskflowc/XWindowsClientTaskBarReceiver.h b/src/cmd/deskflowc/XWindowsClientTaskBarReceiver.h index 91fa3d189..afdd01372 100644 --- a/src/cmd/deskflowc/XWindowsClientTaskBarReceiver.h +++ b/src/cmd/deskflowc/XWindowsClientTaskBarReceiver.h @@ -24,19 +24,16 @@ class BufferedLogOutputter; class IEventQueue; //! Implementation of ClientTaskBarReceiver for X Windows -class CXWindowsClientTaskBarReceiver : public ClientTaskBarReceiver { +class CXWindowsClientTaskBarReceiver : public ClientTaskBarReceiver +{ public: - CXWindowsClientTaskBarReceiver( - const BufferedLogOutputter *, IEventQueue *events); - CXWindowsClientTaskBarReceiver(const CXWindowsClientTaskBarReceiver &) = - delete; + CXWindowsClientTaskBarReceiver(const BufferedLogOutputter *, IEventQueue *events); + CXWindowsClientTaskBarReceiver(const CXWindowsClientTaskBarReceiver &) = delete; CXWindowsClientTaskBarReceiver(CXWindowsClientTaskBarReceiver &&) = delete; virtual ~CXWindowsClientTaskBarReceiver(); - CXWindowsClientTaskBarReceiver & - operator=(const CXWindowsClientTaskBarReceiver &) = delete; - CXWindowsClientTaskBarReceiver & - operator=(CXWindowsClientTaskBarReceiver &&) = delete; + CXWindowsClientTaskBarReceiver &operator=(const CXWindowsClientTaskBarReceiver &) = delete; + CXWindowsClientTaskBarReceiver &operator=(CXWindowsClientTaskBarReceiver &&) = delete; // IArchTaskBarReceiver overrides virtual void showStatus(); diff --git a/src/cmd/deskflowc/deskflowc.cpp b/src/cmd/deskflowc/deskflowc.cpp index f0d162125..48181e145 100644 --- a/src/cmd/deskflowc/deskflowc.cpp +++ b/src/cmd/deskflowc/deskflowc.cpp @@ -35,7 +35,8 @@ #error Platform not supported. #endif -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ #if SYSAPI_WIN32 // record window instance for tray icon, etc ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL)); diff --git a/src/cmd/deskflowd/deskflowd.cpp b/src/cmd/deskflowd/deskflowd.cpp index 42b2b266f..498b24128 100644 --- a/src/cmd/deskflowd/deskflowd.cpp +++ b/src/cmd/deskflowd/deskflowd.cpp @@ -22,7 +22,8 @@ #ifdef SYSAPI_UNIX -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ DaemonApp app; return app.run(argc, argv); } @@ -32,7 +33,8 @@ int main(int argc, char **argv) { #define WIN32_LEAN_AND_MEAN #include -int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) { +int WINAPI WinMain(HINSTANCE, HINSTANCE, LPSTR, int) +{ DaemonApp app; return app.run(__argc, __argv); } diff --git a/src/cmd/deskflows/MSWindowsServerTaskBarReceiver.cpp b/src/cmd/deskflows/MSWindowsServerTaskBarReceiver.cpp index ec1d762f1..17ee86615 100644 --- a/src/cmd/deskflows/MSWindowsServerTaskBarReceiver.cpp +++ b/src/cmd/deskflows/MSWindowsServerTaskBarReceiver.cpp @@ -35,17 +35,18 @@ // const UINT MSWindowsServerTaskBarReceiver::s_stateToIconID[kMaxState] = { - IDI_TASKBAR_NOT_RUNNING, IDI_TASKBAR_NOT_WORKING, IDI_TASKBAR_NOT_CONNECTED, - IDI_TASKBAR_CONNECTED}; + IDI_TASKBAR_NOT_RUNNING, IDI_TASKBAR_NOT_WORKING, IDI_TASKBAR_NOT_CONNECTED, IDI_TASKBAR_CONNECTED +}; MSWindowsServerTaskBarReceiver::MSWindowsServerTaskBarReceiver( - HINSTANCE appInstance, const BufferedLogOutputter *logBuffer, - IEventQueue *events) + HINSTANCE appInstance, const BufferedLogOutputter *logBuffer, IEventQueue *events +) : ServerTaskBarReceiver(events), m_events(events), m_appInstance(appInstance), m_window(NULL), - m_logBuffer(logBuffer) { + m_logBuffer(logBuffer) +{ for (UInt32 i = 0; i < kMaxState; ++i) { m_icon[i] = loadIcon(s_stateToIconID[i]); } @@ -60,7 +61,8 @@ MSWindowsServerTaskBarReceiver::MSWindowsServerTaskBarReceiver( ARCH->addReceiver(this); } -void MSWindowsServerTaskBarReceiver::cleanup() { +void MSWindowsServerTaskBarReceiver::cleanup() +{ ARCH->removeReceiver(this); for (UInt32 i = 0; i < kMaxState; ++i) { deleteIcon(m_icon[i]); @@ -69,9 +71,13 @@ void MSWindowsServerTaskBarReceiver::cleanup() { destroyWindow(); } -MSWindowsServerTaskBarReceiver::~MSWindowsServerTaskBarReceiver() { cleanup(); } +MSWindowsServerTaskBarReceiver::~MSWindowsServerTaskBarReceiver() +{ + cleanup(); +} -void MSWindowsServerTaskBarReceiver::showStatus() { +void MSWindowsServerTaskBarReceiver::showStatus() +{ // create the window createWindow(); @@ -92,8 +98,7 @@ void MSWindowsServerTaskBarReceiver::showStatus() { SendMessage(child, WM_SETTEXT, 0, (LPARAM)status.c_str()); child = GetDlgItem(m_window, IDC_TASKBAR_STATUS_CLIENTS); SendMessage(child, LB_RESETCONTENT, 0, 0); - for (Clients::const_iterator index = clients.begin(); - index != clients.end();) { + for (Clients::const_iterator index = clients.begin(); index != clients.end();) { const char *client = index->c_str(); if (++index == clients.end()) { SendMessage(child, LB_ADDSTRING, 0, (LPARAM)client); @@ -142,7 +147,8 @@ void MSWindowsServerTaskBarReceiver::showStatus() { } } -void MSWindowsServerTaskBarReceiver::runMenu(int x, int y) { +void MSWindowsServerTaskBarReceiver::runMenu(int x, int y) +{ // do popup menu. we need a window to pass to TrackPopupMenu(). // the SetForegroundWindow() and SendMessage() calls around // TrackPopupMenu() are to get the menu to be dismissed when @@ -153,11 +159,9 @@ void MSWindowsServerTaskBarReceiver::runMenu(int x, int y) { HMENU menu = GetSubMenu(m_menu, 0); SetMenuDefaultItem(menu, IDC_TASKBAR_STATUS, FALSE); HMENU logLevelMenu = GetSubMenu(menu, 3); - CheckMenuRadioItem( - logLevelMenu, 0, 6, CLOG->getFilter() - kERROR, MF_BYPOSITION); - int n = TrackPopupMenu( - menu, TPM_NONOTIFY | TPM_RETURNCMD | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, x, - y, 0, m_window, NULL); + CheckMenuRadioItem(logLevelMenu, 0, 6, CLOG->getFilter() - kERROR, MF_BYPOSITION); + int n = + TrackPopupMenu(menu, TPM_NONOTIFY | TPM_RETURNCMD | TPM_LEFTBUTTON | TPM_RIGHTBUTTON, x, y, 0, m_window, NULL); SendMessage(m_window, WM_NULL, 0, 0); // perform the requested operation @@ -175,19 +179,15 @@ void MSWindowsServerTaskBarReceiver::runMenu(int x, int y) { break; case IDC_RELOAD_CONFIG: - m_events->addEvent(Event( - m_events->forServerApp().reloadConfig(), m_events->getSystemTarget())); + m_events->addEvent(Event(m_events->forServerApp().reloadConfig(), m_events->getSystemTarget())); break; case IDC_FORCE_RECONNECT: - m_events->addEvent(Event( - m_events->forServerApp().forceReconnect(), - m_events->getSystemTarget())); + m_events->addEvent(Event(m_events->forServerApp().forceReconnect(), m_events->getSystemTarget())); break; case ID_DESKFLOW_RESETSERVER: - m_events->addEvent(Event( - m_events->forServerApp().resetServer(), m_events->getSystemTarget())); + m_events->addEvent(Event(m_events->forServerApp().resetServer(), m_events->getSystemTarget())); break; case IDC_TASKBAR_LOG_LEVEL_ERROR: @@ -224,19 +224,22 @@ void MSWindowsServerTaskBarReceiver::runMenu(int x, int y) { } } -void MSWindowsServerTaskBarReceiver::primaryAction() { showStatus(); } +void MSWindowsServerTaskBarReceiver::primaryAction() +{ + showStatus(); +} -const IArchTaskBarReceiver::Icon -MSWindowsServerTaskBarReceiver::getIcon() const { +const IArchTaskBarReceiver::Icon MSWindowsServerTaskBarReceiver::getIcon() const +{ return static_cast(m_icon[getStatus()]); } -void MSWindowsServerTaskBarReceiver::copyLog() const { +void MSWindowsServerTaskBarReceiver::copyLog() const +{ if (m_logBuffer != NULL) { // collect log buffer String data; - for (BufferedLogOutputter::const_iterator index = m_logBuffer->begin(); - index != m_logBuffer->end(); ++index) { + for (BufferedLogOutputter::const_iterator index = m_logBuffer->begin(); index != m_logBuffer->end(); ++index) { data += *index; data += "\n"; } @@ -252,26 +255,29 @@ void MSWindowsServerTaskBarReceiver::copyLog() const { } } -void MSWindowsServerTaskBarReceiver::onStatusChanged() { +void MSWindowsServerTaskBarReceiver::onStatusChanged() +{ if (IsWindowVisible(m_window)) { showStatus(); } } HICON -MSWindowsServerTaskBarReceiver::loadIcon(UINT id) { - HANDLE icon = LoadImage( - m_appInstance, MAKEINTRESOURCE(id), IMAGE_ICON, 0, 0, LR_DEFAULTCOLOR); +MSWindowsServerTaskBarReceiver::loadIcon(UINT id) +{ + HANDLE icon = LoadImage(m_appInstance, MAKEINTRESOURCE(id), IMAGE_ICON, 0, 0, LR_DEFAULTCOLOR); return static_cast(icon); } -void MSWindowsServerTaskBarReceiver::deleteIcon(HICON icon) { +void MSWindowsServerTaskBarReceiver::deleteIcon(HICON icon) +{ if (icon != NULL) { DestroyIcon(icon); } } -void MSWindowsServerTaskBarReceiver::createWindow() { +void MSWindowsServerTaskBarReceiver::createWindow() +{ // ignore if already created if (m_window != NULL) { return; @@ -279,9 +285,9 @@ void MSWindowsServerTaskBarReceiver::createWindow() { // get the status dialog m_window = CreateDialogParam( - m_appInstance, MAKEINTRESOURCE(IDD_TASKBAR_STATUS), NULL, - (DLGPROC)&MSWindowsServerTaskBarReceiver::staticDlgProc, - reinterpret_cast(static_cast(this))); + m_appInstance, MAKEINTRESOURCE(IDD_TASKBAR_STATUS), NULL, (DLGPROC)&MSWindowsServerTaskBarReceiver::staticDlgProc, + reinterpret_cast(static_cast(this)) + ); // window should appear on top of everything, including (especially) // the task bar. @@ -293,7 +299,8 @@ void MSWindowsServerTaskBarReceiver::createWindow() { ArchTaskBarWindows::addDialog(m_window); } -void MSWindowsServerTaskBarReceiver::destroyWindow() { +void MSWindowsServerTaskBarReceiver::destroyWindow() +{ if (m_window != NULL) { ArchTaskBarWindows::removeDialog(m_window); DestroyWindow(m_window); @@ -301,8 +308,8 @@ void MSWindowsServerTaskBarReceiver::destroyWindow() { } } -BOOL MSWindowsServerTaskBarReceiver::dlgProc( - HWND hwnd, UINT msg, WPARAM wParam, LPARAM) { +BOOL MSWindowsServerTaskBarReceiver::dlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM) +{ switch (msg) { case WM_INITDIALOG: // use default focus @@ -318,21 +325,19 @@ BOOL MSWindowsServerTaskBarReceiver::dlgProc( return FALSE; } -BOOL CALLBACK MSWindowsServerTaskBarReceiver::staticDlgProc( - HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { +BOOL CALLBACK MSWindowsServerTaskBarReceiver::staticDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ // if msg is WM_INITDIALOG, extract the MSWindowsServerTaskBarReceiver* // and put it in the extra window data then forward the call. MSWindowsServerTaskBarReceiver *self = NULL; if (msg == WM_INITDIALOG) { - self = static_cast( - reinterpret_cast(lParam)); + self = static_cast(reinterpret_cast(lParam)); SetWindowLongPtr(hwnd, GWLP_USERDATA, lParam); } else { // get the extra window data and forward the call LONG_PTR data = GetWindowLongPtr(hwnd, GWLP_USERDATA); if (data != 0) { - self = static_cast( - reinterpret_cast(data)); + self = static_cast(reinterpret_cast(data)); } } @@ -344,16 +349,12 @@ BOOL CALLBACK MSWindowsServerTaskBarReceiver::staticDlgProc( } } -IArchTaskBarReceiver *createTaskBarReceiver( - const BufferedLogOutputter *logBuffer, IEventQueue *events) { +IArchTaskBarReceiver *createTaskBarReceiver(const BufferedLogOutputter *logBuffer, IEventQueue *events) +{ ArchMiscWindows::setIcons( - (HICON)LoadImage( - ArchMiscWindows::instanceWin32(), MAKEINTRESOURCE(IDI_DESKFLOW), - IMAGE_ICON, 32, 32, LR_SHARED), - (HICON)LoadImage( - ArchMiscWindows::instanceWin32(), MAKEINTRESOURCE(IDI_DESKFLOW), - IMAGE_ICON, 16, 16, LR_SHARED)); + (HICON)LoadImage(ArchMiscWindows::instanceWin32(), MAKEINTRESOURCE(IDI_DESKFLOW), IMAGE_ICON, 32, 32, LR_SHARED), + (HICON)LoadImage(ArchMiscWindows::instanceWin32(), MAKEINTRESOURCE(IDI_DESKFLOW), IMAGE_ICON, 16, 16, LR_SHARED) + ); - return new MSWindowsServerTaskBarReceiver( - MSWindowsScreen::getWindowInstance(), logBuffer, events); + return new MSWindowsServerTaskBarReceiver(MSWindowsScreen::getWindowInstance(), logBuffer, events); } diff --git a/src/cmd/deskflows/MSWindowsServerTaskBarReceiver.h b/src/cmd/deskflows/MSWindowsServerTaskBarReceiver.h index 4b0d1484d..0906b5e2b 100644 --- a/src/cmd/deskflows/MSWindowsServerTaskBarReceiver.h +++ b/src/cmd/deskflows/MSWindowsServerTaskBarReceiver.h @@ -27,10 +27,10 @@ class BufferedLogOutputter; class IEventQueue; //! Implementation of ServerTaskBarReceiver for Microsoft Windows -class MSWindowsServerTaskBarReceiver : public ServerTaskBarReceiver { +class MSWindowsServerTaskBarReceiver : public ServerTaskBarReceiver +{ public: - MSWindowsServerTaskBarReceiver( - HINSTANCE, const BufferedLogOutputter *, IEventQueue *events); + MSWindowsServerTaskBarReceiver(HINSTANCE, const BufferedLogOutputter *, IEventQueue *events); virtual ~MSWindowsServerTaskBarReceiver(); // IArchTaskBarReceiver overrides @@ -53,8 +53,7 @@ private: void destroyWindow(); BOOL dlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); - static BOOL CALLBACK - staticDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); + static BOOL CALLBACK staticDlgProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam); private: HINSTANCE m_appInstance; diff --git a/src/cmd/deskflows/OSXServerTaskBarReceiver.cpp b/src/cmd/deskflows/OSXServerTaskBarReceiver.cpp index 3dc8684b9..004fab1c3 100644 --- a/src/cmd/deskflows/OSXServerTaskBarReceiver.cpp +++ b/src/cmd/deskflows/OSXServerTaskBarReceiver.cpp @@ -23,34 +23,39 @@ // OSXServerTaskBarReceiver // -OSXServerTaskBarReceiver::OSXServerTaskBarReceiver( - const BufferedLogOutputter *, IEventQueue *events) - : ServerTaskBarReceiver(events) { +OSXServerTaskBarReceiver::OSXServerTaskBarReceiver(const BufferedLogOutputter *, IEventQueue *events) + : ServerTaskBarReceiver(events) +{ // add ourself to the task bar ARCH->addReceiver(this); } -OSXServerTaskBarReceiver::~OSXServerTaskBarReceiver() { +OSXServerTaskBarReceiver::~OSXServerTaskBarReceiver() +{ ARCH->removeReceiver(this); } -void OSXServerTaskBarReceiver::showStatus() { +void OSXServerTaskBarReceiver::showStatus() +{ // do nothing } -void OSXServerTaskBarReceiver::runMenu(int, int) { +void OSXServerTaskBarReceiver::runMenu(int, int) +{ // do nothing } -void OSXServerTaskBarReceiver::primaryAction() { +void OSXServerTaskBarReceiver::primaryAction() +{ // do nothing } -const IArchTaskBarReceiver::Icon OSXServerTaskBarReceiver::getIcon() const { +const IArchTaskBarReceiver::Icon OSXServerTaskBarReceiver::getIcon() const +{ return NULL; } -IArchTaskBarReceiver *createTaskBarReceiver( - const BufferedLogOutputter *logBuffer, IEventQueue *events) { +IArchTaskBarReceiver *createTaskBarReceiver(const BufferedLogOutputter *logBuffer, IEventQueue *events) +{ return new OSXServerTaskBarReceiver(logBuffer, events); } diff --git a/src/cmd/deskflows/OSXServerTaskBarReceiver.h b/src/cmd/deskflows/OSXServerTaskBarReceiver.h index c2c4a6402..69eeaf226 100644 --- a/src/cmd/deskflows/OSXServerTaskBarReceiver.h +++ b/src/cmd/deskflows/OSXServerTaskBarReceiver.h @@ -23,7 +23,8 @@ class BufferedLogOutputter; //! Implementation of ServerTaskBarReceiver for OS X -class OSXServerTaskBarReceiver : public ServerTaskBarReceiver { +class OSXServerTaskBarReceiver : public ServerTaskBarReceiver +{ public: OSXServerTaskBarReceiver(const BufferedLogOutputter *, IEventQueue *events); virtual ~OSXServerTaskBarReceiver(); diff --git a/src/cmd/deskflows/XWindowsServerTaskBarReceiver.cpp b/src/cmd/deskflows/XWindowsServerTaskBarReceiver.cpp index 64212cee9..4857df2da 100644 --- a/src/cmd/deskflows/XWindowsServerTaskBarReceiver.cpp +++ b/src/cmd/deskflows/XWindowsServerTaskBarReceiver.cpp @@ -23,35 +23,39 @@ // CXWindowsServerTaskBarReceiver // -CXWindowsServerTaskBarReceiver::CXWindowsServerTaskBarReceiver( - const BufferedLogOutputter *, IEventQueue *events) - : ServerTaskBarReceiver(events) { +CXWindowsServerTaskBarReceiver::CXWindowsServerTaskBarReceiver(const BufferedLogOutputter *, IEventQueue *events) + : ServerTaskBarReceiver(events) +{ // add ourself to the task bar ARCH->addReceiver(this); } -CXWindowsServerTaskBarReceiver::~CXWindowsServerTaskBarReceiver() { +CXWindowsServerTaskBarReceiver::~CXWindowsServerTaskBarReceiver() +{ ARCH->removeReceiver(this); } -void CXWindowsServerTaskBarReceiver::showStatus() { +void CXWindowsServerTaskBarReceiver::showStatus() +{ // do nothing } -void CXWindowsServerTaskBarReceiver::runMenu(int, int) { +void CXWindowsServerTaskBarReceiver::runMenu(int, int) +{ // do nothing } -void CXWindowsServerTaskBarReceiver::primaryAction() { +void CXWindowsServerTaskBarReceiver::primaryAction() +{ // do nothing } -const IArchTaskBarReceiver::Icon -CXWindowsServerTaskBarReceiver::getIcon() const { +const IArchTaskBarReceiver::Icon CXWindowsServerTaskBarReceiver::getIcon() const +{ return NULL; } -IArchTaskBarReceiver *createTaskBarReceiver( - const BufferedLogOutputter *logBuffer, IEventQueue *events) { +IArchTaskBarReceiver *createTaskBarReceiver(const BufferedLogOutputter *logBuffer, IEventQueue *events) +{ return new CXWindowsServerTaskBarReceiver(logBuffer, events); } diff --git a/src/cmd/deskflows/XWindowsServerTaskBarReceiver.h b/src/cmd/deskflows/XWindowsServerTaskBarReceiver.h index 54c5d7746..7cab6ea2f 100644 --- a/src/cmd/deskflows/XWindowsServerTaskBarReceiver.h +++ b/src/cmd/deskflows/XWindowsServerTaskBarReceiver.h @@ -24,19 +24,16 @@ class BufferedLogOutputter; class IEventQueue; //! Implementation of ServerTaskBarReceiver for X Windows -class CXWindowsServerTaskBarReceiver : public ServerTaskBarReceiver { +class CXWindowsServerTaskBarReceiver : public ServerTaskBarReceiver +{ public: - CXWindowsServerTaskBarReceiver( - const BufferedLogOutputter *, IEventQueue *events); - CXWindowsServerTaskBarReceiver(const CXWindowsServerTaskBarReceiver &) = - delete; + CXWindowsServerTaskBarReceiver(const BufferedLogOutputter *, IEventQueue *events); + CXWindowsServerTaskBarReceiver(const CXWindowsServerTaskBarReceiver &) = delete; CXWindowsServerTaskBarReceiver(CXWindowsServerTaskBarReceiver &&) = delete; virtual ~CXWindowsServerTaskBarReceiver(); - CXWindowsServerTaskBarReceiver & - operator=(const CXWindowsServerTaskBarReceiver &) = delete; - CXWindowsServerTaskBarReceiver & - operator=(const CXWindowsServerTaskBarReceiver &&) = delete; + CXWindowsServerTaskBarReceiver &operator=(const CXWindowsServerTaskBarReceiver &) = delete; + CXWindowsServerTaskBarReceiver &operator=(const CXWindowsServerTaskBarReceiver &&) = delete; // IArchTaskBarReceiver overrides virtual void showStatus(); diff --git a/src/cmd/deskflows/deskflows.cpp b/src/cmd/deskflows/deskflows.cpp index 931395066..85f6af248 100644 --- a/src/cmd/deskflows/deskflows.cpp +++ b/src/cmd/deskflows/deskflows.cpp @@ -35,7 +35,8 @@ #error Platform not supported. #endif -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ #if SYSAPI_WIN32 // record window instance for tray icon, etc ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL)); diff --git a/src/gui/src/Action.cpp b/src/gui/src/Action.cpp index 610ba359b..73647ace5 100644 --- a/src/gui/src/Action.cpp +++ b/src/gui/src/Action.cpp @@ -22,11 +22,9 @@ #include const char *Action::m_ActionTypeNames[] = { - "keyDown", "keyUp", - "keystroke", "switchToScreen", - "switchInDirection", "lockCursorToScreen", - "restartServer", "mouseDown", - "mouseUp", "mousebutton"}; + "keyDown", "keyUp", "keystroke", "switchToScreen", "switchInDirection", "lockCursorToScreen", + "restartServer", "mouseDown", "mouseUp", "mousebutton" +}; const char *Action::m_SwitchDirectionNames[] = {"left", "right", "up", "down"}; const char *Action::m_LockCursorModeNames[] = {"toggle", "on", "off"}; @@ -39,13 +37,13 @@ Action::Action() m_SwitchDirection(switchLeft), m_LockCursorMode(lockCursorToggle), m_ActiveOnRelease(false), - m_HasScreens(false) {} + m_HasScreens(false) +{ +} -QString Action::text() const { - QString text = - QString(m_ActionTypeNames - [keySequence().isMouseButton() ? type() + 6 : type()]) + - "("; +QString Action::text() const +{ + QString text = QString(m_ActionTypeNames[keySequence().isMouseButton() ? type() + 6 : type()]) + "("; switch (type()) { case keyDown: @@ -93,7 +91,8 @@ QString Action::text() const { return text; } -void Action::loadSettings(QSettings &settings) { +void Action::loadSettings(QSettings &settings) +{ keySequence().loadSettings(settings); setType(settings.value("type", keyDown).toInt()); @@ -107,14 +106,14 @@ void Action::loadSettings(QSettings &settings) { setSwitchScreenName(settings.value("switchScreenName").toString()); setSwitchDirection(settings.value("switchInDirection", switchLeft).toInt()); - setLockCursorMode( - settings.value("lockCursorToScreen", lockCursorToggle).toInt()); + setLockCursorMode(settings.value("lockCursorToScreen", lockCursorToggle).toInt()); setActiveOnRelease(settings.value("activeOnRelease", false).toBool()); setHaveScreens(settings.value("hasScreens", false).toBool()); setRestartServer(settings.value("restartServer", false).toBool()); } -void Action::saveSettings(QSettings &settings) const { +void Action::saveSettings(QSettings &settings) const +{ keySequence().saveSettings(settings); settings.setValue("type", type()); @@ -133,17 +132,16 @@ void Action::saveSettings(QSettings &settings) const { settings.setValue("restartServer", restartServer()); } -bool Action::operator==(const Action &a) const { - return m_KeySequence == a.m_KeySequence && m_Type == a.m_Type && - m_TypeScreenNames == a.m_TypeScreenNames && - m_SwitchScreenName == a.m_SwitchScreenName && - m_SwitchDirection == a.m_SwitchDirection && - m_LockCursorMode == a.m_LockCursorMode && - m_ActiveOnRelease == a.m_ActiveOnRelease && +bool Action::operator==(const Action &a) const +{ + return m_KeySequence == a.m_KeySequence && m_Type == a.m_Type && m_TypeScreenNames == a.m_TypeScreenNames && + m_SwitchScreenName == a.m_SwitchScreenName && m_SwitchDirection == a.m_SwitchDirection && + m_LockCursorMode == a.m_LockCursorMode && m_ActiveOnRelease == a.m_ActiveOnRelease && m_HasScreens == a.m_HasScreens && m_restartServer == a.m_restartServer; } -QTextStream &operator<<(QTextStream &outStream, const Action &action) { +QTextStream &operator<<(QTextStream &outStream, const Action &action) +{ if (action.activeOnRelease()) outStream << ";"; diff --git a/src/gui/src/Action.h b/src/gui/src/Action.h index 63c1ff1de..b2e9febf7 100644 --- a/src/gui/src/Action.h +++ b/src/gui/src/Action.h @@ -28,12 +28,14 @@ class ActionDialog; class QSettings; class QTextStream; -class Action { +class Action +{ friend class ActionDialog; friend QTextStream &operator<<(QTextStream &outStream, const Action &action); public: - enum ActionType { + enum ActionType + { keyDown, keyUp, keystroke, @@ -45,39 +47,107 @@ public: mouseUp, mousebutton, }; - enum SwitchDirection { switchLeft, switchRight, switchUp, switchDown }; - enum LockCursorMode { lockCursorToggle, lockCursonOn, lockCursorOff }; + enum SwitchDirection + { + switchLeft, + switchRight, + switchUp, + switchDown + }; + enum LockCursorMode + { + lockCursorToggle, + lockCursonOn, + lockCursorOff + }; public: Action(); public: QString text() const; - const KeySequence &keySequence() const { return m_KeySequence; } + const KeySequence &keySequence() const + { + return m_KeySequence; + } void loadSettings(QSettings &settings); void saveSettings(QSettings &settings) const; - int type() const { return m_Type; } - const QStringList &typeScreenNames() const { return m_TypeScreenNames; } - const QString &switchScreenName() const { return m_SwitchScreenName; } - int switchDirection() const { return m_SwitchDirection; } - int lockCursorMode() const { return m_LockCursorMode; } - bool activeOnRelease() const { return m_ActiveOnRelease; } - bool haveScreens() const { return m_HasScreens; } - bool restartServer() const { return m_restartServer; } + int type() const + { + return m_Type; + } + const QStringList &typeScreenNames() const + { + return m_TypeScreenNames; + } + const QString &switchScreenName() const + { + return m_SwitchScreenName; + } + int switchDirection() const + { + return m_SwitchDirection; + } + int lockCursorMode() const + { + return m_LockCursorMode; + } + bool activeOnRelease() const + { + return m_ActiveOnRelease; + } + bool haveScreens() const + { + return m_HasScreens; + } + bool restartServer() const + { + return m_restartServer; + } bool operator==(const Action &a) const; protected: - KeySequence &keySequence() { return m_KeySequence; } - void setKeySequence(const KeySequence &seq) { m_KeySequence = seq; } - void setType(int t) { m_Type = t; } - QStringList &typeScreenNames() { return m_TypeScreenNames; } - void setSwitchScreenName(const QString &n) { m_SwitchScreenName = n; } - void setSwitchDirection(int d) { m_SwitchDirection = d; } - void setLockCursorMode(int m) { m_LockCursorMode = m; } - void setActiveOnRelease(bool b) { m_ActiveOnRelease = b; } - void setHaveScreens(bool b) { m_HasScreens = b; } - void setRestartServer(bool b) { m_restartServer = b; } + KeySequence &keySequence() + { + return m_KeySequence; + } + void setKeySequence(const KeySequence &seq) + { + m_KeySequence = seq; + } + void setType(int t) + { + m_Type = t; + } + QStringList &typeScreenNames() + { + return m_TypeScreenNames; + } + void setSwitchScreenName(const QString &n) + { + m_SwitchScreenName = n; + } + void setSwitchDirection(int d) + { + m_SwitchDirection = d; + } + void setLockCursorMode(int m) + { + m_LockCursorMode = m; + } + void setActiveOnRelease(bool b) + { + m_ActiveOnRelease = b; + } + void setHaveScreens(bool b) + { + m_HasScreens = b; + } + void setRestartServer(bool b) + { + m_restartServer = b; + } private: KeySequence m_KeySequence; diff --git a/src/gui/src/ActionDialog.cpp b/src/gui/src/ActionDialog.cpp index a691e9574..cb0d70ab2 100644 --- a/src/gui/src/ActionDialog.cpp +++ b/src/gui/src/ActionDialog.cpp @@ -27,14 +27,14 @@ #include #include -ActionDialog::ActionDialog( - QWidget *parent, ServerConfig &config, Hotkey &hotkey, Action &action) +ActionDialog::ActionDialog(QWidget *parent, ServerConfig &config, Hotkey &hotkey, Action &action) : QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint), Ui::ActionDialogBase(), m_ServerConfig(config), m_Hotkey(hotkey), m_Action(action), - m_pButtonGroupType(new QButtonGroup(this)) { + m_pButtonGroupType(new QButtonGroup(this)) +{ setupUi(this); // work around Qt Designer's lack of a QButtonGroup; we need it to get @@ -46,10 +46,10 @@ ActionDialog::ActionDialog( m_pRadioSwitchToScreen, m_pRadioSwitchInDirection, m_pRadioLockCursorToScreen, - m_pRadioRestartAllConnections}; + m_pRadioRestartAllConnections + }; - for (unsigned int i = 0; i < sizeof(typeButtons) / sizeof(typeButtons[0]); - i++) + for (unsigned int i = 0; i < sizeof(typeButtons) / sizeof(typeButtons[0]); i++) m_pButtonGroupType->addButton(typeButtons[i], i); m_pKeySequenceWidgetHotkey->setText(m_Action.keySequence().toString()); @@ -81,9 +81,9 @@ ActionDialog::ActionDialog( } } -void ActionDialog::accept() { - if (!sequenceWidget()->valid() && m_pButtonGroupType->checkedId() >= 0 && - m_pButtonGroupType->checkedId() < 3) +void ActionDialog::accept() +{ + if (!sequenceWidget()->valid() && m_pButtonGroupType->checkedId() >= 0 && m_pButtonGroupType->checkedId() < 3) return; m_Action.setKeySequence(sequenceWidget()->keySequence()); @@ -103,7 +103,8 @@ void ActionDialog::accept() { QDialog::accept(); } -void ActionDialog::on_m_pKeySequenceWidgetHotkey_keySequenceChanged() { +void ActionDialog::on_m_pKeySequenceWidgetHotkey_keySequenceChanged() +{ if (sequenceWidget()->keySequence().isMouseButton()) { m_pGroupBoxScreens->setEnabled(false); m_pListScreens->setEnabled(false); diff --git a/src/gui/src/ActionDialog.h b/src/gui/src/ActionDialog.h index ce40bd69a..62fcda6f4 100644 --- a/src/gui/src/ActionDialog.h +++ b/src/gui/src/ActionDialog.h @@ -28,22 +28,26 @@ class QRadioButton; class QButtonGroup; class ServerConfig; -class ActionDialog : public QDialog, public Ui::ActionDialogBase { +class ActionDialog : public QDialog, public Ui::ActionDialogBase +{ Q_OBJECT public: - ActionDialog( - QWidget *parent, ServerConfig &config, Hotkey &hotkey, Action &action); + ActionDialog(QWidget *parent, ServerConfig &config, Hotkey &hotkey, Action &action); protected slots: void accept(); void on_m_pKeySequenceWidgetHotkey_keySequenceChanged(); protected: - const KeySequenceWidget *sequenceWidget() const { + const KeySequenceWidget *sequenceWidget() const + { return m_pKeySequenceWidgetHotkey; } - const ServerConfig &serverConfig() const { return m_ServerConfig; } + const ServerConfig &serverConfig() const + { + return m_ServerConfig; + } private: const ServerConfig &m_ServerConfig; diff --git a/src/gui/src/AddClientDialog.cpp b/src/gui/src/AddClientDialog.cpp index e902a7a88..38842d559 100644 --- a/src/gui/src/AddClientDialog.cpp +++ b/src/gui/src/AddClientDialog.cpp @@ -24,13 +24,15 @@ AddClientDialog::AddClientDialog(const QString &clientName, QWidget *parent) : QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint), Ui::AddClientDialog(), - m_AddResult(kAddClientIgnore) { + m_AddResult(kAddClientIgnore) +{ setupUi(this); m_pLabelHead->setText( "A client wants to connect. " "Please choose a location for " + - clientName + "."); + clientName + "." + ); QIcon icon(":res/icons/64x64/video-display.png"); QSize IconSize(32, 32); @@ -39,33 +41,25 @@ AddClientDialog::AddClientDialog(const QString &clientName, QWidget *parent) m_pButtonLeft->setIcon(icon); m_pButtonLeft->setIconSize(IconSize); gridLayout->addWidget(m_pButtonLeft, 2, 0, 1, 1, Qt::AlignCenter); - connect( - m_pButtonLeft, &QPushButton::clicked, this, - &AddClientDialog::handleButtonLeft); + connect(m_pButtonLeft, &QPushButton::clicked, this, &AddClientDialog::handleButtonLeft); m_pButtonUp = new QPushButton(this); m_pButtonUp->setIcon(icon); m_pButtonUp->setIconSize(IconSize); gridLayout->addWidget(m_pButtonUp, 1, 1, 1, 1, Qt::AlignCenter); - connect( - m_pButtonUp, &QPushButton::clicked, this, - &AddClientDialog::handleButtonUp); + connect(m_pButtonUp, &QPushButton::clicked, this, &AddClientDialog::handleButtonUp); m_pButtonRight = new QPushButton(this); m_pButtonRight->setIcon(icon); m_pButtonRight->setIconSize(IconSize); gridLayout->addWidget(m_pButtonRight, 2, 2, 1, 1, Qt::AlignCenter); - connect( - m_pButtonRight, &QPushButton::clicked, this, - &AddClientDialog::handleButtonRight); + connect(m_pButtonRight, &QPushButton::clicked, this, &AddClientDialog::handleButtonRight); m_pButtonDown = new QPushButton(this); m_pButtonDown->setIcon(icon); m_pButtonDown->setIconSize(IconSize); gridLayout->addWidget(m_pButtonDown, 3, 1, 1, 1, Qt::AlignCenter); - connect( - m_pButtonDown, &QPushButton::clicked, this, - &AddClientDialog::handleButtonDown); + connect(m_pButtonDown, &QPushButton::clicked, this, &AddClientDialog::handleButtonDown); m_pLabelCenter = new QLabel(this); m_pLabelCenter->setPixmap(QPixmap(":res/icons/64x64/video-display.png")); @@ -75,14 +69,12 @@ AddClientDialog::AddClientDialog(const QString &clientName, QWidget *parent) m_pDialogButtonBox->setLayoutDirection(Qt::RightToLeft); #endif - QPushButton *advanced = - m_pDialogButtonBox->addButton("Advanced", QDialogButtonBox::HelpRole); - connect( - advanced, &QPushButton::clicked, this, - &AddClientDialog::handleButtonAdvanced); + QPushButton *advanced = m_pDialogButtonBox->addButton("Advanced", QDialogButtonBox::HelpRole); + connect(advanced, &QPushButton::clicked, this, &AddClientDialog::handleButtonAdvanced); } -AddClientDialog::~AddClientDialog() { +AddClientDialog::~AddClientDialog() +{ delete m_pButtonUp; delete m_pButtonDown; delete m_pButtonLeft; @@ -90,27 +82,32 @@ AddClientDialog::~AddClientDialog() { delete m_pLabelCenter; } -void AddClientDialog::handleButtonLeft() { +void AddClientDialog::handleButtonLeft() +{ m_AddResult = kAddClientLeft; close(); } -void AddClientDialog::handleButtonUp() { +void AddClientDialog::handleButtonUp() +{ m_AddResult = kAddClientUp; close(); } -void AddClientDialog::handleButtonRight() { +void AddClientDialog::handleButtonRight() +{ m_AddResult = kAddClientRight; close(); } -void AddClientDialog::handleButtonDown() { +void AddClientDialog::handleButtonDown() +{ m_AddResult = kAddClientDown; close(); } -void AddClientDialog::handleButtonAdvanced() { +void AddClientDialog::handleButtonAdvanced() +{ m_AddResult = kAddClientOther; close(); } diff --git a/src/gui/src/AddClientDialog.h b/src/gui/src/AddClientDialog.h index b7f552b88..739245538 100644 --- a/src/gui/src/AddClientDialog.h +++ b/src/gui/src/AddClientDialog.h @@ -24,7 +24,8 @@ class QPushButton; class QLabel; -enum { +enum +{ kAddClientRight, kAddClientLeft, kAddClientUp, @@ -33,13 +34,17 @@ enum { kAddClientIgnore }; -class AddClientDialog : public QDialog, public Ui::AddClientDialog { +class AddClientDialog : public QDialog, public Ui::AddClientDialog +{ Q_OBJECT public: AddClientDialog(const QString &clientName, QWidget *parent = 0); ~AddClientDialog(); - int addResult() { return m_AddResult; } + int addResult() + { + return m_AddResult; + } private slots: void handleButtonLeft(); diff --git a/src/gui/src/AppDelegate.h b/src/gui/src/AppDelegate.h index 6d9f99a5c..6ac22739a 100644 --- a/src/gui/src/AppDelegate.h +++ b/src/gui/src/AppDelegate.h @@ -1,21 +1,19 @@ #pragma once #ifdef __cplusplus -extern "C" { +extern "C" +{ #endif #import #if OSX_DEPLOYMENT_TARGET >= 1014 #import -@interface AppDelegate - : NSObject < - NSApplicationDelegate, NSUserNotificationCenterDelegate, - UNUserNotificationCenterDelegate> + @interface AppDelegate + : NSObject #else -@interface AppDelegate - : NSObject +@interface AppDelegate : NSObject #endif -@end + @end #ifdef __cplusplus } diff --git a/src/gui/src/DataDownloader.cpp b/src/gui/src/DataDownloader.cpp index deb1f2ab8..36e59ec04 100644 --- a/src/gui/src/DataDownloader.cpp +++ b/src/gui/src/DataDownloader.cpp @@ -17,18 +17,17 @@ #include "DataDownloader.h" -DataDownloader::DataDownloader(QObject *parent) - : QObject(parent), - m_pReply(nullptr), - m_IsFinished(false) { - connect( - &m_NetworkManager, &QNetworkAccessManager::finished, this, - &DataDownloader::complete); +DataDownloader::DataDownloader(QObject *parent) : QObject(parent), m_pReply(nullptr), m_IsFinished(false) +{ + connect(&m_NetworkManager, &QNetworkAccessManager::finished, this, &DataDownloader::complete); } -DataDownloader::~DataDownloader() {} +DataDownloader::~DataDownloader() +{ +} -void DataDownloader::complete(QNetworkReply *reply) { +void DataDownloader::complete(QNetworkReply *reply) +{ m_Data = reply->readAll(); reply->deleteLater(); m_pReply = nullptr; @@ -39,15 +38,20 @@ void DataDownloader::complete(QNetworkReply *reply) { } } -QByteArray DataDownloader::data() const { return m_Data; } +QByteArray DataDownloader::data() const +{ + return m_Data; +} -void DataDownloader::cancel() { +void DataDownloader::cancel() +{ if (m_pReply != nullptr) { m_pReply->abort(); } } -void DataDownloader::download(QUrl url) { +void DataDownloader::download(QUrl url) +{ QNetworkRequest request(url); m_pReply = m_NetworkManager.get(request); } diff --git a/src/gui/src/DataDownloader.h b/src/gui/src/DataDownloader.h index e37f8600d..9da3e5526 100644 --- a/src/gui/src/DataDownloader.h +++ b/src/gui/src/DataDownloader.h @@ -23,7 +23,8 @@ #include #include -class DataDownloader : public QObject { +class DataDownloader : public QObject +{ Q_OBJECT public: @@ -33,7 +34,10 @@ public: QByteArray data() const; void cancel(); void download(QUrl url); - bool isFinished() const { return m_IsFinished; } + bool isFinished() const + { + return m_IsFinished; + } signals: void isComplete(); diff --git a/src/gui/src/DeskflowApplication.cpp b/src/gui/src/DeskflowApplication.cpp index dada64d75..3cda45dac 100644 --- a/src/gui/src/DeskflowApplication.cpp +++ b/src/gui/src/DeskflowApplication.cpp @@ -23,8 +23,8 @@ #include #include -DeskflowApplication::DeskflowApplication(int &argc, char **argv) - : QApplication(argc, argv) { +DeskflowApplication::DeskflowApplication(int &argc, char **argv) : QApplication(argc, argv) +{ if (qEnvironmentVariable("XDG_CURRENT_DESKTOP") != QLatin1String("KDE")) { // causes dark mode to be used on some OS (e.g. Windows) diff --git a/src/gui/src/DeskflowApplication.h b/src/gui/src/DeskflowApplication.h index fb04e152e..caa89f87a 100644 --- a/src/gui/src/DeskflowApplication.h +++ b/src/gui/src/DeskflowApplication.h @@ -22,7 +22,8 @@ class QSessionManager; -class DeskflowApplication : public QApplication { +class DeskflowApplication : public QApplication +{ public: DeskflowApplication(int &argc, char **argv); ~DeskflowApplication() override = default; diff --git a/src/gui/src/Hotkey.cpp b/src/gui/src/Hotkey.cpp index ad492e86b..86954a173 100644 --- a/src/gui/src/Hotkey.cpp +++ b/src/gui/src/Hotkey.cpp @@ -20,9 +20,12 @@ #include -Hotkey::Hotkey() : m_KeySequence(), m_Actions() {} +Hotkey::Hotkey() : m_KeySequence(), m_Actions() +{ +} -QString Hotkey::text() const { +QString Hotkey::text() const +{ QString text = keySequence().toString(); if (keySequence().isMouseButton()) @@ -31,7 +34,8 @@ QString Hotkey::text() const { return "keystroke(" + text + ")"; } -void Hotkey::loadSettings(QSettings &settings) { +void Hotkey::loadSettings(QSettings &settings) +{ keySequence().loadSettings(settings); actions().clear(); @@ -46,7 +50,8 @@ void Hotkey::loadSettings(QSettings &settings) { settings.endArray(); } -void Hotkey::saveSettings(QSettings &settings) const { +void Hotkey::saveSettings(QSettings &settings) const +{ keySequence().saveSettings(settings); settings.beginWriteArray("actions"); @@ -57,14 +62,15 @@ void Hotkey::saveSettings(QSettings &settings) const { settings.endArray(); } -bool Hotkey::operator==(const Hotkey &hk) const { +bool Hotkey::operator==(const Hotkey &hk) const +{ return m_KeySequence == hk.m_KeySequence && m_Actions == hk.m_Actions; } -QTextStream &operator<<(QTextStream &outStream, const Hotkey &hotkey) { +QTextStream &operator<<(QTextStream &outStream, const Hotkey &hotkey) +{ for (int i = 0; i < hotkey.actions().size(); i++) - outStream << "\t" << hotkey.text() << " = " << hotkey.actions()[i] - << Qt::endl; + outStream << "\t" << hotkey.text() << " = " << hotkey.actions()[i] << Qt::endl; return outStream; } diff --git a/src/gui/src/Hotkey.h b/src/gui/src/Hotkey.h index 4f2037a2b..7ffa216d7 100644 --- a/src/gui/src/Hotkey.h +++ b/src/gui/src/Hotkey.h @@ -28,7 +28,8 @@ class HotkeyDialog; class ServerConfigDialog; class QSettings; -class Hotkey { +class Hotkey +{ friend class HotkeyDialog; friend class ServerConfigDialog; friend QTextStream &operator<<(QTextStream &outStream, const Hotkey &hotkey); @@ -38,8 +39,14 @@ public: public: QString text() const; - const KeySequence &keySequence() const { return m_KeySequence; } - const ActionList &actions() const { return m_Actions; } + const KeySequence &keySequence() const + { + return m_KeySequence; + } + const ActionList &actions() const + { + return m_Actions; + } void loadSettings(QSettings &settings); void saveSettings(QSettings &settings) const; @@ -47,9 +54,18 @@ public: bool operator==(const Hotkey &hk) const; protected: - KeySequence &keySequence() { return m_KeySequence; } - void setKeySequence(const KeySequence &seq) { m_KeySequence = seq; } - ActionList &actions() { return m_Actions; } + KeySequence &keySequence() + { + return m_KeySequence; + } + void setKeySequence(const KeySequence &seq) + { + m_KeySequence = seq; + } + ActionList &actions() + { + return m_Actions; + } private: KeySequence m_KeySequence; diff --git a/src/gui/src/HotkeyDialog.cpp b/src/gui/src/HotkeyDialog.cpp index b78872fc2..b77e0d243 100644 --- a/src/gui/src/HotkeyDialog.cpp +++ b/src/gui/src/HotkeyDialog.cpp @@ -24,13 +24,15 @@ HotkeyDialog::HotkeyDialog(QWidget *parent, Hotkey &hotkey) : QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint), Ui::HotkeyDialogBase(), - m_Hotkey(hotkey) { + m_Hotkey(hotkey) +{ setupUi(this); m_pKeySequenceWidgetHotkey->setText(m_Hotkey.text()); } -void HotkeyDialog::accept() { +void HotkeyDialog::accept() +{ if (!sequenceWidget()->valid()) return; diff --git a/src/gui/src/HotkeyDialog.h b/src/gui/src/HotkeyDialog.h index d13e220b6..5bc490a1e 100644 --- a/src/gui/src/HotkeyDialog.h +++ b/src/gui/src/HotkeyDialog.h @@ -22,23 +22,31 @@ #include -class HotkeyDialog : public QDialog, public Ui::HotkeyDialogBase { +class HotkeyDialog : public QDialog, public Ui::HotkeyDialogBase +{ Q_OBJECT public: HotkeyDialog(QWidget *parent, Hotkey &hotkey); public: - const Hotkey &hotkey() const { return m_Hotkey; } + const Hotkey &hotkey() const + { + return m_Hotkey; + } protected slots: void accept(); protected: - const KeySequenceWidget *sequenceWidget() const { + const KeySequenceWidget *sequenceWidget() const + { return m_pKeySequenceWidgetHotkey; } - Hotkey &hotkey() { return m_Hotkey; } + Hotkey &hotkey() + { + return m_Hotkey; + } private: Hotkey &m_Hotkey; diff --git a/src/gui/src/KeySequence.cpp b/src/gui/src/KeySequence.cpp index 5ed4425a6..2e0e3035f 100644 --- a/src/gui/src/KeySequence.cpp +++ b/src/gui/src/KeySequence.cpp @@ -23,7 +23,8 @@ // this table originally comes from Qt sources (gui/kernel/qkeysequence.cpp) // and is heavily modified for Deskflow -static const struct { +static const struct +{ int key; const char *name; } keyname[] = { @@ -75,15 +76,20 @@ static const struct { {Qt::Key_Launch1, "AppUser2"}, {Qt::Key_Select, "Select"}, - {0, 0}}; + {0, 0} +}; -KeySequence::KeySequence() : m_Sequence(), m_Modifiers(0), m_IsValid(false) {} +KeySequence::KeySequence() : m_Sequence(), m_Modifiers(0), m_IsValid(false) +{ +} -bool KeySequence::isMouseButton() const { +bool KeySequence::isMouseButton() const +{ return !m_Sequence.isEmpty() && m_Sequence.last() < Qt::Key_Space; } -QString KeySequence::toString() const { +QString KeySequence::toString() const +{ QString result; for (int i = 0; i < m_Sequence.size(); i++) { @@ -96,9 +102,13 @@ QString KeySequence::toString() const { return result; } -bool KeySequence::appendMouseButton(int button) { return appendKey(button, 0); } +bool KeySequence::appendMouseButton(int button) +{ + return appendKey(button, 0); +} -bool KeySequence::appendKey(int key, int modifiers) { +bool KeySequence::appendKey(int key, int modifiers) +{ if (m_Sequence.size() == 4) return true; @@ -131,7 +141,8 @@ bool KeySequence::appendKey(int key, int modifiers) { return false; } -void KeySequence::loadSettings(QSettings &settings) { +void KeySequence::loadSettings(QSettings &settings) +{ sequence().clear(); int num = settings.beginReadArray("keys"); for (int i = 0; i < num; i++) { @@ -144,7 +155,8 @@ void KeySequence::loadSettings(QSettings &settings) { setValid(true); } -void KeySequence::saveSettings(QSettings &settings) const { +void KeySequence::saveSettings(QSettings &settings) const +{ settings.beginWriteArray("keys"); for (int i = 0; i < sequence().size(); i++) { settings.setArrayIndex(i); @@ -153,7 +165,8 @@ void KeySequence::saveSettings(QSettings &settings) const { settings.endArray(); } -QString KeySequence::keyToString(int key) { +QString KeySequence::keyToString(int key) +{ // nothing there? if (key == 0) return ""; @@ -208,14 +221,13 @@ QString KeySequence::keyToString(int key) { // representable in ucs2? if (key < 0x10000) - return QString("\\u%1").arg( - QChar(key).toLower().unicode(), 4, 16, QChar('0')); + return QString("\\u%1").arg(QChar(key).toLower().unicode(), 4, 16, QChar('0')); // give up, deskflow probably won't handle this return ""; } -bool KeySequence::operator==(const KeySequence &ks) const { - return m_Sequence == ks.m_Sequence && m_Modifiers == ks.m_Modifiers && - m_IsValid == ks.m_IsValid; +bool KeySequence::operator==(const KeySequence &ks) const +{ + return m_Sequence == ks.m_Sequence && m_Modifiers == ks.m_Modifiers && m_IsValid == ks.m_IsValid; } diff --git a/src/gui/src/KeySequence.h b/src/gui/src/KeySequence.h index 712aa3f14..4faa2551d 100644 --- a/src/gui/src/KeySequence.h +++ b/src/gui/src/KeySequence.h @@ -23,7 +23,8 @@ class QSettings; -class KeySequence { +class KeySequence +{ public: KeySequence(); @@ -32,18 +33,36 @@ public: bool appendKey(int modifiers, int key); bool appendMouseButton(int button); bool isMouseButton() const; - bool valid() const { return m_IsValid; } - int modifiers() const { return m_Modifiers; } + bool valid() const + { + return m_IsValid; + } + int modifiers() const + { + return m_Modifiers; + } void saveSettings(QSettings &settings) const; void loadSettings(QSettings &settings); - const QList &sequence() const { return m_Sequence; } + const QList &sequence() const + { + return m_Sequence; + } bool operator==(const KeySequence &ks) const; private: - void setValid(bool b) { m_IsValid = b; } - void setModifiers(int i) { m_Modifiers = i; } - QList &sequence() { return m_Sequence; } + void setValid(bool b) + { + m_IsValid = b; + } + void setModifiers(int i) + { + m_Modifiers = i; + } + QList &sequence() + { + return m_Sequence; + } private: QList m_Sequence; diff --git a/src/gui/src/KeySequenceWidget.cpp b/src/gui/src/KeySequenceWidget.cpp index 4d7837379..f3aabc74f 100644 --- a/src/gui/src/KeySequenceWidget.cpp +++ b/src/gui/src/KeySequenceWidget.cpp @@ -29,12 +29,14 @@ KeySequenceWidget::KeySequenceWidget(QWidget *parent, const KeySequence &seq) m_MousePrefix("mousebutton("), m_MousePostfix(")"), m_KeyPrefix("keystroke("), - m_KeyPostfix(")") { + m_KeyPostfix(")") +{ setFocusPolicy(Qt::NoFocus); updateOutput(); } -void KeySequenceWidget::setKeySequence(const KeySequence &seq) { +void KeySequenceWidget::setKeySequence(const KeySequence &seq) +{ keySequence() = seq; backupSequence() = seq; @@ -42,7 +44,8 @@ void KeySequenceWidget::setKeySequence(const KeySequence &seq) { updateOutput(); } -void KeySequenceWidget::mousePressEvent(QMouseEvent *event) { +void KeySequenceWidget::mousePressEvent(QMouseEvent *event) +{ event->accept(); if (status() == Stopped) { @@ -56,7 +59,8 @@ void KeySequenceWidget::mousePressEvent(QMouseEvent *event) { updateOutput(); } -void KeySequenceWidget::startRecording() { +void KeySequenceWidget::startRecording() +{ keySequence() = KeySequence(); setDown(true); setFocus(); @@ -64,7 +68,8 @@ void KeySequenceWidget::startRecording() { setStatus(Recording); } -void KeySequenceWidget::stopRecording() { +void KeySequenceWidget::stopRecording() +{ if (!keySequence().valid()) { keySequence() = backupSequence(); updateOutput(); @@ -77,7 +82,8 @@ void KeySequenceWidget::stopRecording() { emit keySequenceChanged(); } -bool KeySequenceWidget::event(QEvent *event) { +bool KeySequenceWidget::event(QEvent *event) +{ if (status() == Recording) { switch (event->type()) { case QEvent::KeyPress: @@ -108,7 +114,8 @@ bool KeySequenceWidget::event(QEvent *event) { return QPushButton::event(event); } -void KeySequenceWidget::keyPressEvent(QKeyEvent *event) { +void KeySequenceWidget::keyPressEvent(QKeyEvent *event) +{ event->accept(); if (status() == Stopped) @@ -120,7 +127,8 @@ void KeySequenceWidget::keyPressEvent(QKeyEvent *event) { updateOutput(); } -void KeySequenceWidget::updateOutput() { +void KeySequenceWidget::updateOutput() +{ QString s; if (m_KeySequence.isMouseButton()) diff --git a/src/gui/src/KeySequenceWidget.h b/src/gui/src/KeySequenceWidget.h index 2f66037a3..7974da4b0 100644 --- a/src/gui/src/KeySequenceWidget.h +++ b/src/gui/src/KeySequenceWidget.h @@ -21,7 +21,8 @@ #include "KeySequence.h" -class KeySequenceWidget : public QPushButton { +class KeySequenceWidget : public QPushButton +{ Q_OBJECT public: @@ -31,21 +32,54 @@ signals: void keySequenceChanged(); public: - const QString &mousePrefix() const { return m_MousePrefix; } - const QString &mousePostfix() const { return m_MousePostfix; } - const QString &keyPrefix() const { return m_KeyPrefix; } - const QString &keyPostfix() const { return m_KeyPostfix; } + const QString &mousePrefix() const + { + return m_MousePrefix; + } + const QString &mousePostfix() const + { + return m_MousePostfix; + } + const QString &keyPrefix() const + { + return m_KeyPrefix; + } + const QString &keyPostfix() const + { + return m_KeyPostfix; + } - void setMousePrefix(const QString &s) { m_MousePrefix = s; } - void setMousePostfix(const QString &s) { m_MousePostfix = s; } - void setKeyPrefix(const QString &s) { m_KeyPrefix = s; } - void setKeyPostfix(const QString &s) { m_KeyPostfix = s; } + void setMousePrefix(const QString &s) + { + m_MousePrefix = s; + } + void setMousePostfix(const QString &s) + { + m_MousePostfix = s; + } + void setKeyPrefix(const QString &s) + { + m_KeyPrefix = s; + } + void setKeyPostfix(const QString &s) + { + m_KeyPostfix = s; + } - const KeySequence &keySequence() const { return m_KeySequence; } - const KeySequence &backupSequence() const { return m_BackupSequence; } + const KeySequence &keySequence() const + { + return m_KeySequence; + } + const KeySequence &backupSequence() const + { + return m_BackupSequence; + } void setKeySequence(const KeySequence &seq); - bool valid() const { return keySequence().valid(); } + bool valid() const + { + return keySequence().valid(); + } protected: void mousePressEvent(QMouseEvent *); @@ -55,13 +89,29 @@ protected: void updateOutput(); void startRecording(); void stopRecording(); - KeySequence &keySequence() { return m_KeySequence; } - KeySequence &backupSequence() { return m_BackupSequence; } + KeySequence &keySequence() + { + return m_KeySequence; + } + KeySequence &backupSequence() + { + return m_BackupSequence; + } private: - enum Status { Stopped, Recording }; - void setStatus(Status s) { m_Status = s; } - Status status() const { return m_Status; } + enum Status + { + Stopped, + Recording + }; + void setStatus(Status s) + { + m_Status = s; + } + Status status() const + { + return m_Status; + } private: KeySequence m_KeySequence; diff --git a/src/gui/src/MainWindow.cpp b/src/gui/src/MainWindow.cpp index 5f88e2ddc..8f9eaf02b 100644 --- a/src/gui/src/MainWindow.cpp +++ b/src/gui/src/MainWindow.cpp @@ -76,11 +76,11 @@ MainWindow::MainWindow(ConfigScopes &configScopes, AppConfig &appConfig) m_AppConfig(appConfig), m_ServerConfig(appConfig, *this), m_CoreProcess(appConfig, m_ServerConfig), - m_ServerConnection( - this, appConfig, m_ServerConfig, m_ServerConfigDialogState), + m_ServerConnection(this, appConfig, m_ServerConfig, m_ServerConfigDialogState), m_ClientConnection(this, appConfig), m_TlsUtility(appConfig), - m_WindowSaveTimer(this) { + m_WindowSaveTimer(this) +{ setupUi(this); createMenuBar(); @@ -91,9 +91,13 @@ MainWindow::MainWindow(ConfigScopes &configScopes, AppConfig &appConfig) emit created(); } -MainWindow::~MainWindow() { m_CoreProcess.cleanup(); } +MainWindow::~MainWindow() +{ + m_CoreProcess.cleanup(); +} -void MainWindow::restoreWindow() { +void MainWindow::restoreWindow() +{ const auto &windowSize = m_AppConfig.mainWindowSize(); if (windowSize.has_value()) { @@ -118,7 +122,8 @@ void MainWindow::restoreWindow() { m_SaveWindow = true; } -void MainWindow::saveWindow() { +void MainWindow::saveWindow() +{ if (!m_SaveWindow) { qDebug("not yet ready to save window size and position, skipping"); return; @@ -130,7 +135,8 @@ void MainWindow::saveWindow() { m_ConfigScopes.save(); } -void MainWindow::setupControls() { +void MainWindow::setupControls() +{ setWindowTitle(kAppName); m_pActionHelp->setText(DESKFLOW_HELP_TEXT); @@ -144,8 +150,7 @@ void MainWindow::setupControls() { m_pLabelNotice->setStyleSheet(kStyleNoticeLabel); m_pLabelNotice->hide(); - m_pLabelIpAddresses->setText( - QString("This computer's IP addresses: %1").arg(getIPAddresses())); + m_pLabelIpAddresses->setText(QString("This computer's IP addresses: %1").arg(getIPAddresses())); if (m_AppConfig.lastVersion() != DESKFLOW_VERSION) { m_AppConfig.setLastVersion(DESKFLOW_VERSION); @@ -166,63 +171,47 @@ void MainWindow::setupControls() { // remember: using queued connection allows the render loop to run before // executing the slot. the default is to instantly call the slot when the // signal is emitted from the thread that owns the receiver's object. -void MainWindow::connectSlots() { +void MainWindow::connectSlots() +{ connect( &Logger::instance(), &Logger::newLine, this, // - [this](const QString &line) { handleLogLine(line); }); + [this](const QString &line) { handleLogLine(line); } + ); connect(this, &MainWindow::created, this, &MainWindow::onCreated); - connect( - this, &MainWindow::shown, this, &MainWindow::onShown, - Qt::QueuedConnection); + connect(this, &MainWindow::shown, this, &MainWindow::onShown, Qt::QueuedConnection); - connect( - &m_ConfigScopes, &ConfigScopes::saving, this, - &MainWindow::onConfigScopesSaving, Qt::DirectConnection); + connect(&m_ConfigScopes, &ConfigScopes::saving, this, &MainWindow::onConfigScopesSaving, Qt::DirectConnection); - connect( - &m_AppConfig, &AppConfig::tlsChanged, this, - &MainWindow::onAppConfigTlsChanged); + connect(&m_AppConfig, &AppConfig::tlsChanged, this, &MainWindow::onAppConfigTlsChanged); - connect( - &m_AppConfig, &AppConfig::screenNameChanged, this, - &MainWindow::onAppConfigScreenNameChanged); + connect(&m_AppConfig, &AppConfig::screenNameChanged, this, &MainWindow::onAppConfigScreenNameChanged); - connect( - &m_AppConfig, &AppConfig::invertConnectionChanged, this, - &MainWindow::onAppConfigInvertConnection); + connect(&m_AppConfig, &AppConfig::invertConnectionChanged, this, &MainWindow::onAppConfigInvertConnection); - connect( - &m_CoreProcess, &CoreProcess::starting, this, - &MainWindow::onCoreProcessStarting, Qt::DirectConnection); + connect(&m_CoreProcess, &CoreProcess::starting, this, &MainWindow::onCoreProcessStarting, Qt::DirectConnection); - connect( - &m_CoreProcess, &CoreProcess::error, this, - &MainWindow::onCoreProcessError); + connect(&m_CoreProcess, &CoreProcess::error, this, &MainWindow::onCoreProcessError); connect( &m_CoreProcess, &CoreProcess::logLine, // - [this](const QString &line) { handleLogLine(line); }); + [this](const QString &line) { handleLogLine(line); } + ); - connect( - &m_CoreProcess, &CoreProcess::processStateChanged, this, - &MainWindow::onCoreProcessStateChanged); + connect(&m_CoreProcess, &CoreProcess::processStateChanged, this, &MainWindow::onCoreProcessStateChanged); - connect( - &m_CoreProcess, &CoreProcess::connectionStateChanged, this, - &MainWindow::onCoreConnectionStateChanged); + connect(&m_CoreProcess, &CoreProcess::connectionStateChanged, this, &MainWindow::onCoreConnectionStateChanged); - connect( - &m_CoreProcess, &CoreProcess::secureSocket, this, - &MainWindow::onCoreProcessSecureSocket); + connect(&m_CoreProcess, &CoreProcess::secureSocket, this, &MainWindow::onCoreProcessSecureSocket); connect(m_pActionMinimize, &QAction::triggered, this, &MainWindow::hide); connect( m_pActionRestore, &QAction::triggered, // - [this]() { showAndActivate(); }); + [this]() { showAndActivate(); } + ); connect(m_pActionQuit, &QAction::triggered, qApp, [this] { qDebug("quitting application"); @@ -230,38 +219,30 @@ void MainWindow::connectSlots() { QApplication::quit(); }); - connect( - &m_VersionChecker, &VersionChecker::updateFound, this, - &MainWindow::onVersionCheckerUpdateFound); + connect(&m_VersionChecker, &VersionChecker::updateFound, this, &MainWindow::onVersionCheckerUpdateFound); + + connect(&m_WindowSaveTimer, &QTimer::timeout, this, &MainWindow::onWindowSaveTimerTimeout); + + connect(&m_TrayIcon, &TrayIcon::activated, this, &MainWindow::onTrayIconActivated); connect( - &m_WindowSaveTimer, &QTimer::timeout, this, - &MainWindow::onWindowSaveTimerTimeout); + &m_ServerConnection, &ServerConnection::configureClient, this, &MainWindow::onServerConnectionConfigureClient + ); - connect( - &m_TrayIcon, &TrayIcon::activated, this, - &MainWindow::onTrayIconActivated); + connect(&m_ServerConnection, &ServerConnection::messageShowing, this, [this]() { showAndActivate(); }); - connect( - &m_ServerConnection, &ServerConnection::configureClient, this, - &MainWindow::onServerConnectionConfigureClient); - - connect( - &m_ServerConnection, &ServerConnection::messageShowing, this, - [this]() { showAndActivate(); }); - - connect( - &m_ClientConnection, &ClientConnection::messageShowing, this, - [this]() { showAndActivate(); }); + connect(&m_ClientConnection, &ClientConnection::messageShowing, this, [this]() { showAndActivate(); }); } -void MainWindow::onAppAboutToQuit() { +void MainWindow::onAppAboutToQuit() +{ if (m_SaveOnExit) { m_ConfigScopes.save(); } } -void MainWindow::onCreated() { +void MainWindow::onCreated() +{ setIcon(); @@ -273,11 +254,11 @@ void MainWindow::onCreated() { applyConfig(); restoreWindow(); - qDebug().noquote() << "active settings path:" - << m_ConfigScopes.activeFilePath(); + qDebug().noquote() << "active settings path:" << m_ConfigScopes.activeFilePath(); } -void MainWindow::onShown() { +void MainWindow::onShown() +{ // if a critical error was shown just before the main window (i.e. on app // load), it will be hidden behind the main window. therefore we need to raise // it up in front of the main window. @@ -286,20 +267,24 @@ void MainWindow::onShown() { // this we delay the error dialog raise by a split second. this seems a bit // hacky and fragile, so maybe there's a better approach. const auto kCriticalDialogDelay = 100; - QTimer::singleShot( - kCriticalDialogDelay, [] { messages::raiseCriticalDialog(); }); + QTimer::singleShot(kCriticalDialogDelay, [] { messages::raiseCriticalDialog(); }); } -void MainWindow::onConfigScopesSaving() { m_ServerConfig.commit(); } +void MainWindow::onConfigScopesSaving() +{ + m_ServerConfig.commit(); +} -void MainWindow::onAppConfigTlsChanged() { +void MainWindow::onAppConfigTlsChanged() +{ updateLocalFingerprint(); if (m_TlsUtility.isEnabled()) { m_TlsUtility.generateCertificate(); } } -void MainWindow::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason) { +void MainWindow::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason) +{ if (reason == QSystemTrayIcon::DoubleClick) { if (isVisible()) { @@ -310,54 +295,66 @@ void MainWindow::onTrayIconActivated(QSystemTrayIcon::ActivationReason reason) { } } -void MainWindow::onVersionCheckerUpdateFound(const QString &version) { +void MainWindow::onVersionCheckerUpdateFound(const QString &version) +{ const auto link = QString(kLinkDownload).arg(kUrlDownload, kColorWhite); - const auto text = - QString("A new version is available (v%1). %2").arg(version, link); + const auto text = QString("A new version is available (v%1). %2").arg(version, link); m_pLabelUpdate->show(); m_pLabelUpdate->setText(text); } -void MainWindow::onAppConfigScreenNameChanged() { updateScreenName(); } +void MainWindow::onAppConfigScreenNameChanged() +{ + updateScreenName(); +} -void MainWindow::onAppConfigInvertConnection() { applyConfig(); } +void MainWindow::onAppConfigInvertConnection() +{ + applyConfig(); +} -void MainWindow::onCoreProcessError(CoreProcess::Error error) { +void MainWindow::onCoreProcessError(CoreProcess::Error error) +{ if (error == CoreProcess::Error::AddressMissing) { QMessageBox::warning( - this, QString("Address missing"), - QString( - "Please enter the hostname or IP address of the other computer.")); + this, QString("Address missing"), QString("Please enter the hostname or IP address of the other computer.") + ); } else if (error == CoreProcess::Error::StartFailed) { show(); QMessageBox::warning( this, QString("Core cannot be started"), "The Core executable could not be successfully started, " "although it does exist. " - "Please check if you have sufficient permissions to run this program."); + "Please check if you have sufficient permissions to run this program." + ); } } -void MainWindow::on_m_pActionStartCore_triggered() { +void MainWindow::on_m_pActionStartCore_triggered() +{ m_ClientConnection.setShowMessage(); m_CoreProcess.start(); } -void MainWindow::on_m_pActionStopCore_triggered() { +void MainWindow::on_m_pActionStopCore_triggered() +{ qDebug("stopping core process"); m_CoreProcess.stop(); } -void MainWindow::on_m_pActionTestFatalError_triggered() const { +void MainWindow::on_m_pActionTestFatalError_triggered() const +{ qFatal("test fatal error"); } -void MainWindow::on_m_pActionTestCriticalError_triggered() const { +void MainWindow::on_m_pActionTestCriticalError_triggered() const +{ qCritical("test critical error"); } -void MainWindow::on_m_pActionClearSettings_triggered() { +void MainWindow::on_m_pActionClearSettings_triggered() +{ if (!messages::showClearSettings(this)) { qDebug("clear settings cancelled"); return; @@ -370,32 +367,32 @@ void MainWindow::on_m_pActionClearSettings_triggered() { diagnostic::clearSettings(m_ConfigScopes, true); } -bool MainWindow::on_m_pActionSave_triggered() { - QString fileName = - QFileDialog::getSaveFileName(this, QString("Save configuration as...")); +bool MainWindow::on_m_pActionSave_triggered() +{ + QString fileName = QFileDialog::getSaveFileName(this, QString("Save configuration as...")); if (!fileName.isEmpty() && !m_ServerConfig.save(fileName)) { - QMessageBox::warning( - this, QString("Save failed"), - QString("Could not save configuration to file.")); + QMessageBox::warning(this, QString("Save failed"), QString("Could not save configuration to file.")); return true; } return false; } -void MainWindow::on_m_pActionAbout_triggered() { +void MainWindow::on_m_pActionAbout_triggered() +{ AboutDialog about(this); about.exec(); } -void MainWindow::on_m_pActionHelp_triggered() const { +void MainWindow::on_m_pActionHelp_triggered() const +{ QDesktopServices::openUrl(QUrl(kUrlHelp)); } -void MainWindow::on_m_pActionSettings_triggered() { - auto dialog = - SettingsDialog(this, m_AppConfig, m_ServerConfig, m_CoreProcess); +void MainWindow::on_m_pActionSettings_triggered() +{ + auto dialog = SettingsDialog(this, m_AppConfig, m_ServerConfig, m_CoreProcess); if (dialog.exec() == QDialog::Accepted) { m_ConfigScopes.save(); @@ -409,61 +406,78 @@ void MainWindow::on_m_pActionSettings_triggered() { } } -void MainWindow::on_m_pButtonConfigureServer_clicked() { +void MainWindow::on_m_pButtonConfigureServer_clicked() +{ showConfigureServer(); } -void MainWindow::on_m_pLineEditHostname_returnPressed() { +void MainWindow::on_m_pLineEditHostname_returnPressed() +{ m_pButtonConnect->click(); } -void MainWindow::on_m_pLineEditClientIp_returnPressed() { +void MainWindow::on_m_pLineEditClientIp_returnPressed() +{ m_pButtonConnectToClient->click(); } -void MainWindow::on_m_pLineEditHostname_textChanged(const QString &text) { +void MainWindow::on_m_pLineEditHostname_textChanged(const QString &text) +{ m_CoreProcess.setAddress(text); } -void MainWindow::on_m_pLineEditClientIp_textChanged(const QString &text) { +void MainWindow::on_m_pLineEditClientIp_textChanged(const QString &text) +{ m_CoreProcess.setAddress(text); } -void MainWindow::on_m_pButtonApply_clicked() { +void MainWindow::on_m_pButtonApply_clicked() +{ m_ClientConnection.setShowMessage(); m_CoreProcess.restart(); } -void MainWindow::on_m_pLabelComputerName_linkActivated(const QString &) { +void MainWindow::on_m_pLabelComputerName_linkActivated(const QString &) +{ m_pActionSettings->trigger(); } -void MainWindow::on_m_pLabelFingerprint_linkActivated(const QString &) { - QMessageBox::information( - this, "TLS fingerprint", TlsFingerprint::local().readFirst()); +void MainWindow::on_m_pLabelFingerprint_linkActivated(const QString &) +{ + QMessageBox::information(this, "TLS fingerprint", TlsFingerprint::local().readFirst()); } -void MainWindow::on_m_pRadioGroupServer_clicked(bool) { +void MainWindow::on_m_pRadioGroupServer_clicked(bool) +{ enableServer(true); enableClient(false); m_ConfigScopes.save(); } -void MainWindow::on_m_pRadioGroupClient_clicked(bool) { +void MainWindow::on_m_pRadioGroupClient_clicked(bool) +{ enableClient(true); enableServer(false); m_ConfigScopes.save(); } -void MainWindow::on_m_pButtonConnect_clicked() { on_m_pButtonApply_clicked(); } - -void MainWindow::on_m_pButtonConnectToClient_clicked() { +void MainWindow::on_m_pButtonConnect_clicked() +{ on_m_pButtonApply_clicked(); } -void MainWindow::onWindowSaveTimerTimeout() { saveWindow(); } +void MainWindow::on_m_pButtonConnectToClient_clicked() +{ + on_m_pButtonApply_clicked(); +} -void MainWindow::onServerConnectionConfigureClient(const QString &clientName) { +void MainWindow::onWindowSaveTimerTimeout() +{ + saveWindow(); +} + +void MainWindow::onServerConnectionConfigureClient(const QString &clientName) +{ m_ServerConfigDialogState.setVisible(true); ServerConfigDialog dialog(this, m_ServerConfig, m_AppConfig); if (dialog.addClient(clientName) && dialog.exec() == QDialog::Accepted) { @@ -476,7 +490,8 @@ void MainWindow::onServerConnectionConfigureClient(const QString &clientName) { // End slots ////////////////////////////////////////////////////////////////////////////// -void MainWindow::resizeEvent(QResizeEvent *event) { +void MainWindow::resizeEvent(QResizeEvent *event) +{ QMainWindow::resizeEvent(event); // postpone save so that settings are not written every delta change. @@ -484,7 +499,8 @@ void MainWindow::resizeEvent(QResizeEvent *event) { m_WindowSaveTimer.start(1000); } -void MainWindow::moveEvent(QMoveEvent *event) { +void MainWindow::moveEvent(QMoveEvent *event) +{ QMainWindow::moveEvent(event); // postpone save so that settings are not written every delta change. @@ -492,11 +508,11 @@ void MainWindow::moveEvent(QMoveEvent *event) { m_WindowSaveTimer.start(1000); } -void MainWindow::open() { +void MainWindow::open() +{ - std::vector trayMenu = { - m_pActionStartCore, m_pActionStopCore, nullptr, m_pActionMinimize, - m_pActionRestore, nullptr, m_pActionQuit}; + std::vector trayMenu = {m_pActionStartCore, m_pActionStopCore, nullptr, m_pActionMinimize, + m_pActionRestore, nullptr, m_pActionQuit}; m_TrayIcon.create(trayMenu); @@ -521,7 +537,8 @@ void MainWindow::open() { } } -void MainWindow::onCoreProcessStarting() { +void MainWindow::onCoreProcessStarting() +{ #if defined(WINAPI_XWINDOWS) or defined(WINAPI_LIBEI) if (deskflow::platform::isWayland()) { @@ -532,11 +549,13 @@ void MainWindow::onCoreProcessStarting() { saveSettings(); } -void MainWindow::setStatus(const QString &status) { +void MainWindow::setStatus(const QString &status) +{ m_pStatusLabel->setText(status); } -void MainWindow::createMenuBar() { +void MainWindow::createMenuBar() +{ m_pMenuBar = new QMenuBar(this); m_pMenuFile = new QMenu("File", m_pMenuBar); m_pMenuEdit = new QMenu("Edit", m_pMenuBar); @@ -569,8 +588,7 @@ void MainWindow::createMenuBar() { m_pActionAbout->setText(QString("About %1...").arg(kAppName)); - const auto enableTestMenu = - strToTrue(qEnvironmentVariable("DESKFLOW_TEST_MENU")); + const auto enableTestMenu = strToTrue(qEnvironmentVariable("DESKFLOW_TEST_MENU")); if (enableTestMenu || kDebugBuild) { auto testMenu = new QMenu("Test", m_pMenuBar); @@ -582,7 +600,8 @@ void MainWindow::createMenuBar() { setMenuBar(m_pMenuBar); } -void MainWindow::applyConfig() { +void MainWindow::applyConfig() +{ enableServer(m_AppConfig.serverGroupChecked()); enableClient(m_AppConfig.clientGroupChecked()); @@ -590,11 +609,13 @@ void MainWindow::applyConfig() { m_pLineEditClientIp->setText(m_ServerConfig.getClientAddress()); } -void MainWindow::applyCloseToTray() const { +void MainWindow::applyCloseToTray() const +{ QApplication::setQuitOnLastWindowClosed(!m_AppConfig.closeToTray()); } -void MainWindow::saveSettings() { +void MainWindow::saveSettings() +{ m_AppConfig.setServerGroupChecked(m_pRadioGroupServer->isChecked()); m_AppConfig.setClientGroupChecked(m_pRadioGroupClient->isChecked()); m_AppConfig.setServerHostname(m_pLineEditHostname->text()); @@ -603,7 +624,8 @@ void MainWindow::saveSettings() { m_ConfigScopes.save(); } -void MainWindow::setIcon() { +void MainWindow::setIcon() +{ QIcon icon; #ifdef Q_OS_MAC switch (getOSXIconsTheme()) { @@ -626,14 +648,14 @@ void MainWindow::setIcon() { m_TrayIcon.setIcon(icon); } -void MainWindow::handleLogLine(const QString &line) { +void MainWindow::handleLogLine(const QString &line) +{ const int kScrollBottomThreshold = 2; QScrollBar *verticalScroll = m_pLogOutput->verticalScrollBar(); int currentScroll = verticalScroll->value(); int maxScroll = verticalScroll->maximum(); - const auto scrollAtBottom = - qAbs(currentScroll - maxScroll) <= kScrollBottomThreshold; + const auto scrollAtBottom = qAbs(currentScroll - maxScroll) <= kScrollBottomThreshold; // only trim end instead of the whole line to prevent tab-indented debug // filenames from losing their indentation. @@ -647,12 +669,14 @@ void MainWindow::handleLogLine(const QString &line) { updateFromLogLine(line); } -void MainWindow::updateFromLogLine(const QString &line) { +void MainWindow::updateFromLogLine(const QString &line) +{ checkConnected(line); checkFingerprint(line); } -void MainWindow::checkConnected(const QString &line) { +void MainWindow::checkConnected(const QString &line) +{ if (m_pRadioGroupServer->isChecked()) { m_ServerConnection.handleLogLine(line); m_pLabelServerState->updateServerState(line); @@ -662,7 +686,8 @@ void MainWindow::checkConnected(const QString &line) { } } -void MainWindow::checkFingerprint(const QString &line) { +void MainWindow::checkFingerprint(const QString &line) +{ QRegularExpression re(".*server fingerprint: ([A-F0-9:]+)"); auto match = re.match(line); if (!match.hasMatch()) { @@ -682,17 +707,17 @@ void MainWindow::checkFingerprint(const QString &line) { messageBoxAlreadyShown = true; QMessageBox::StandardButton fingerprintReply = QMessageBox::information( this, QString("Security question"), - QString( - "

You are connecting to a server.

" - "

Here is it's TLS fingerprint:

" - "

%1

" - "

Compare this fingerprint to the one on your server's screen. " - "If the two don't match exactly, then it's probably not the server " - "you're expecting (it could be a malicious user).

" - "

Do you want to trust this fingerprint for future " - "connections? If you don't, a connection cannot be made.

") + QString("

You are connecting to a server.

" + "

Here is it's TLS fingerprint:

" + "

%1

" + "

Compare this fingerprint to the one on your server's screen. " + "If the two don't match exactly, then it's probably not the server " + "you're expecting (it could be a malicious user).

" + "

Do you want to trust this fingerprint for future " + "connections? If you don't, a connection cannot be made.

") .arg(fingerprint), - QMessageBox::Yes | QMessageBox::No); + QMessageBox::Yes | QMessageBox::No + ); if (fingerprintReply == QMessageBox::Yes) { // start core process again after trusting fingerprint. @@ -704,17 +729,20 @@ void MainWindow::checkFingerprint(const QString &line) { } } -QString MainWindow::getTimeStamp() const { +QString MainWindow::getTimeStamp() const +{ QDateTime current = QDateTime::currentDateTime(); return '[' + current.toString(Qt::ISODate) + ']'; } -void MainWindow::showEvent(QShowEvent *event) { +void MainWindow::showEvent(QShowEvent *event) +{ QMainWindow::showEvent(event); emit shown(); } -void MainWindow::closeEvent(QCloseEvent *event) { +void MainWindow::closeEvent(QCloseEvent *event) +{ if (m_Quitting) { qDebug("skipping close event handle on quit"); return; @@ -734,7 +762,8 @@ void MainWindow::closeEvent(QCloseEvent *event) { qDebug("window should hide to tray"); } -void MainWindow::showFirstConnectedMessage() { +void MainWindow::showFirstConnectedMessage() +{ if (m_AppConfig.startedBefore()) { return; } @@ -743,11 +772,11 @@ void MainWindow::showFirstConnectedMessage() { m_ConfigScopes.save(); const auto isServer = m_CoreProcess.mode() == CoreMode::Server; - messages::showFirstConnectedMessage( - this, m_AppConfig.closeToTray(), m_AppConfig.enableService(), isServer); + messages::showFirstConnectedMessage(this, m_AppConfig.closeToTray(), m_AppConfig.enableService(), isServer); } -void MainWindow::showDevThanksMessage() { +void MainWindow::showDevThanksMessage() +{ if (!m_AppConfig.showDevThanks()) { qDebug("skipping dev thanks message"); return; @@ -759,11 +788,13 @@ void MainWindow::showDevThanksMessage() { messages::showDevThanks(this, kAppName); } -void MainWindow::onCoreProcessSecureSocket(bool enabled) { +void MainWindow::onCoreProcessSecureSocket(bool enabled) +{ secureSocket(enabled); } -void MainWindow::updateStatus() { +void MainWindow::updateStatus() +{ const auto connection = m_CoreProcess.connectionState(); const auto process = m_CoreProcess.processState(); @@ -804,11 +835,9 @@ void MainWindow::updateStatus() { case Connected: { if (m_SecureSocket) { - setStatus(QString("%1 is connected (with %2)") - .arg(kAppName, m_CoreProcess.secureSocketVersion())); + setStatus(QString("%1 is connected (with %2)").arg(kAppName, m_CoreProcess.secureSocketVersion())); } else { - setStatus( - QString("%1 is connected (without TLS encryption)").arg(kAppName)); + setStatus(QString("%1 is connected (without TLS encryption)").arg(kAppName)); } break; } @@ -821,7 +850,8 @@ void MainWindow::updateStatus() { } } -void MainWindow::onCoreProcessStateChanged(CoreProcessState state) { +void MainWindow::onCoreProcessStateChanged(CoreProcessState state) +{ updateStatus(); if (state == CoreProcessState::Started) { @@ -830,15 +860,10 @@ void MainWindow::onCoreProcessStateChanged(CoreProcessState state) { m_ConfigScopes.save(); } - if (state == CoreProcessState::Started || - state == CoreProcessState::Starting || + if (state == CoreProcessState::Started || state == CoreProcessState::Starting || state == CoreProcessState::RetryPending) { - disconnect( - m_pButtonToggleStart, &QPushButton::clicked, m_pActionStartCore, - &QAction::trigger); - connect( - m_pButtonToggleStart, &QPushButton::clicked, m_pActionStopCore, - &QAction::trigger); + disconnect(m_pButtonToggleStart, &QPushButton::clicked, m_pActionStartCore, &QAction::trigger); + connect(m_pButtonToggleStart, &QPushButton::clicked, m_pActionStopCore, &QAction::trigger); m_pButtonToggleStart->setText(QString("&Stop")); m_pButtonApply->setEnabled(true); @@ -847,12 +872,8 @@ void MainWindow::onCoreProcessStateChanged(CoreProcessState state) { m_pActionStopCore->setEnabled(true); } else { - disconnect( - m_pButtonToggleStart, &QPushButton::clicked, m_pActionStopCore, - &QAction::trigger); - connect( - m_pButtonToggleStart, &QPushButton::clicked, m_pActionStartCore, - &QAction::trigger); + disconnect(m_pButtonToggleStart, &QPushButton::clicked, m_pActionStopCore, &QAction::trigger); + connect(m_pButtonToggleStart, &QPushButton::clicked, m_pActionStartCore, &QAction::trigger); m_pButtonToggleStart->setText(QString("&Start")); m_pButtonApply->setEnabled(false); @@ -862,7 +883,8 @@ void MainWindow::onCoreProcessStateChanged(CoreProcessState state) { } } -void MainWindow::onCoreConnectionStateChanged(CoreConnectionState state) { +void MainWindow::onCoreConnectionStateChanged(CoreConnectionState state) +{ qDebug("core connection state changed: %d", static_cast(state)); updateStatus(); @@ -878,7 +900,8 @@ void MainWindow::onCoreConnectionStateChanged(CoreConnectionState state) { } } -void MainWindow::setVisible(bool visible) { +void MainWindow::setVisible(bool visible) +{ QMainWindow::setVisible(visible); m_pActionMinimize->setEnabled(visible); m_pActionRestore->setEnabled(!visible); @@ -897,15 +920,15 @@ void MainWindow::setVisible(bool visible) { #endif } -QString MainWindow::getIPAddresses() const { +QString MainWindow::getIPAddresses() const +{ QStringList result; bool hinted = false; const auto localnet = QHostAddress::parseSubnet("192.168.0.0/16"); const QList addresses = QNetworkInterface::allAddresses(); for (const auto &address : addresses) { - if (address.protocol() == QAbstractSocket::IPv4Protocol && - address != QHostAddress(QHostAddress::LocalHost) && + if (address.protocol() == QAbstractSocket::IPv4Protocol && address != QHostAddress(QHostAddress::LocalHost) && !address.isInSubnet(QHostAddress::parseSubnet("169.254.0.0/16"))) { // usually 192.168.x.x is a useful ip for the user, so indicate @@ -927,7 +950,8 @@ QString MainWindow::getIPAddresses() const { return result.join(", "); } -void MainWindow::updateLocalFingerprint() { +void MainWindow::updateLocalFingerprint() +{ bool fingerprintExists = false; try { fingerprintExists = TlsFingerprint::local().fileExists(); @@ -936,22 +960,21 @@ void MainWindow::updateLocalFingerprint() { qFatal("failed to check if fingerprint exists"); } - if (m_AppConfig.tlsEnabled() && fingerprintExists && - m_pRadioGroupServer->isChecked()) { + if (m_AppConfig.tlsEnabled() && fingerprintExists && m_pRadioGroupServer->isChecked()) { m_pLabelFingerprint->setVisible(true); } else { m_pLabelFingerprint->setVisible(false); } } -void MainWindow::autoAddScreen(const QString name) { +void MainWindow::autoAddScreen(const QString name) +{ int r = m_ServerConfig.autoAddScreen(name); if (r != kAutoAddScreenOk) { switch (r) { case kAutoAddScreenManualServer: - showConfigureServer(QString("Please add the server (%1) to the grid.") - .arg(m_AppConfig.screenName())); + showConfigureServer(QString("Please add the server (%1) to the grid.").arg(m_AppConfig.screenName())); break; case kAutoAddScreenManualClient: @@ -963,7 +986,8 @@ void MainWindow::autoAddScreen(const QString name) { } } -void MainWindow::showConfigureServer(const QString &message) { +void MainWindow::showConfigureServer(const QString &message) +{ ServerConfigDialog dialog(this, serverConfig(), m_AppConfig); dialog.message(message); if ((dialog.exec() == QDialog::Accepted) && m_CoreProcess.isStarted()) { @@ -971,7 +995,8 @@ void MainWindow::showConfigureServer(const QString &message) { } } -void MainWindow::secureSocket(bool secureSocket) { +void MainWindow::secureSocket(bool secureSocket) +{ m_SecureSocket = secureSocket; if (secureSocket) { m_pLabelPadlock->show(); @@ -980,16 +1005,17 @@ void MainWindow::secureSocket(bool secureSocket) { } } -void MainWindow::updateScreenName() { - m_pLabelComputerName->setText( - QString("This computer's name: %1 " - R"((change))") - .arg(m_AppConfig.screenName()) - .arg(kColorSecondary)); +void MainWindow::updateScreenName() +{ + m_pLabelComputerName->setText(QString("This computer's name: %1 " + R"((change))") + .arg(m_AppConfig.screenName()) + .arg(kColorSecondary)); m_ServerConfig.updateServerName(); } -void MainWindow::enableServer(bool enable) { +void MainWindow::enableServer(bool enable) +{ qDebug(enable ? "server enabled" : "server disabled"); m_AppConfig.setServerGroupChecked(enable); m_pRadioGroupServer->setChecked(enable); @@ -1012,7 +1038,8 @@ void MainWindow::enableServer(bool enable) { } } -void MainWindow::enableClient(bool enable) { +void MainWindow::enableClient(bool enable) +{ qDebug(enable ? "client enabled" : "client disabled"); m_AppConfig.setClientGroupChecked(enable); m_pRadioGroupClient->setChecked(enable); @@ -1026,7 +1053,8 @@ void MainWindow::enableClient(bool enable) { } } -void MainWindow::showAndActivate() { +void MainWindow::showAndActivate() +{ if (!isMinimized() && !isHidden()) { qDebug("window already visible"); return; diff --git a/src/gui/src/MainWindow.h b/src/gui/src/MainWindow.h index 5602cb695..febc47e5c 100644 --- a/src/gui/src/MainWindow.h +++ b/src/gui/src/MainWindow.h @@ -55,7 +55,8 @@ class QAbstractButton; class DeskflowApplication; class SetupWizard; -class MainWindow : public QMainWindow, public Ui::MainWindowBase { +class MainWindow : public QMainWindow, public Ui::MainWindowBase +{ using CoreMode = deskflow::gui::CoreProcess::Mode; using CoreProcess = deskflow::gui::CoreProcess; @@ -66,18 +67,27 @@ class MainWindow : public QMainWindow, public Ui::MainWindowBase { friend class SettingsDialog; public: - enum class LogLevel { Error, Info }; + enum class LogLevel + { + Error, + Info + }; public: - explicit MainWindow( - deskflow::gui::ConfigScopes &configScopes, AppConfig &appConfig); + explicit MainWindow(deskflow::gui::ConfigScopes &configScopes, AppConfig &appConfig); ~MainWindow() override; void setVisible(bool visible) override; - CoreMode coreMode() const { return m_CoreProcess.mode(); } + CoreMode coreMode() const + { + return m_CoreProcess.mode(); + } QString address() const; void open(); - ServerConfig &serverConfig() { return m_ServerConfig; } + ServerConfig &serverConfig() + { + return m_ServerConfig; + } void autoAddScreen(const QString name); signals: @@ -133,8 +143,14 @@ private slots: void on_m_pLineEditClientIp_textChanged(const QString &text); private: - AppConfig &appConfig() { return m_AppConfig; } - AppConfig const &appConfig() const { return m_AppConfig; } + AppConfig &appConfig() + { + return m_AppConfig; + } + AppConfig const &appConfig() const + { + return m_AppConfig; + } void createMenuBar(); void createStatusBar(); void createTrayIcon(); @@ -163,7 +179,10 @@ private: void saveSettings(); QString configFilename(); void showConfigureServer(const QString &message); - void showConfigureServer() { showConfigureServer(""); } + void showConfigureServer() + { + showConfigureServer(""); + } void restoreWindow(); void saveWindow(); void setupControls(); diff --git a/src/gui/src/ProcessorArch.h b/src/gui/src/ProcessorArch.h index f690f2a81..b385a8f50 100644 --- a/src/gui/src/ProcessorArch.h +++ b/src/gui/src/ProcessorArch.h @@ -17,7 +17,8 @@ #pragma once -enum qProcessorArch { +enum qProcessorArch +{ kProcessorArchWin32, kProcessorArchWin64, kProcessorArchMac32, diff --git a/src/gui/src/QUtility.cpp b/src/gui/src/QUtility.cpp index 7cd9227d0..1d827202f 100644 --- a/src/gui/src/QUtility.cpp +++ b/src/gui/src/QUtility.cpp @@ -29,7 +29,8 @@ #include #endif -void setIndexFromItemData(QComboBox *comboBox, const QVariant &itemData) { +void setIndexFromItemData(QComboBox *comboBox, const QVariant &itemData) +{ for (int i = 0; i < comboBox->count(); ++i) { if (comboBox->itemData(i) == itemData) { comboBox->setCurrentIndex(i); @@ -38,13 +39,15 @@ void setIndexFromItemData(QComboBox *comboBox, const QVariant &itemData) { } } -QString hash(const QString &string) { +QString hash(const QString &string) +{ QByteArray data = string.toUtf8(); QByteArray hash = QCryptographicHash::hash(data, QCryptographicHash::Md5); return hash.toHex(); } -qProcessorArch getProcessorArch() { +qProcessorArch getProcessorArch() +{ #if defined(Q_OS_WIN) SYSTEM_INFO systemInfo; GetNativeSystemInfo(&systemInfo); diff --git a/src/gui/src/ScreenSettingsDialog.cpp b/src/gui/src/ScreenSettingsDialog.cpp index b77643bff..2bd7e9593 100644 --- a/src/gui/src/ScreenSettingsDialog.cpp +++ b/src/gui/src/ScreenSettingsDialog.cpp @@ -33,11 +33,11 @@ using enum ScreenConfig::Modifier; using enum ScreenConfig::SwitchCorner; using enum ScreenConfig::Fix; -ScreenSettingsDialog::ScreenSettingsDialog( - QWidget *parent, Screen *pScreen, const ScreenList *pScreens) +ScreenSettingsDialog::ScreenSettingsDialog(QWidget *parent, Screen *pScreen, const ScreenList *pScreens) : QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint), Ui::ScreenSettingsDialogBase(), - m_pScreen(pScreen) { + m_pScreen(pScreen) +{ setupUi(this); @@ -46,33 +46,27 @@ ScreenSettingsDialog::ScreenSettingsDialog( m_pLineEditName->setText(m_pScreen->name()); m_pLineEditName->setValidator(new validators::ScreenNameValidator( - m_pLineEditName, new validators::ValidationError(this, m_pLabelNameError), - pScreens)); + m_pLineEditName, new validators::ValidationError(this, m_pLabelNameError), pScreens + )); m_pLineEditName->selectAll(); - m_pLineEditAlias->setValidator(new validators::AliasValidator( - m_pLineEditAlias, - new validators::ValidationError(this, m_pLabelAliasError))); + m_pLineEditAlias->setValidator( + new validators::AliasValidator(m_pLineEditAlias, new validators::ValidationError(this, m_pLabelAliasError)) + ); for (int i = 0; i < m_pScreen->aliases().count(); i++) new QListWidgetItem(m_pScreen->aliases()[i], m_pListAliases); - m_pComboBoxShift->setCurrentIndex( - m_pScreen->modifier(static_cast(Shift))); + m_pComboBoxShift->setCurrentIndex(m_pScreen->modifier(static_cast(Shift))); m_pComboBoxCtrl->setCurrentIndex(m_pScreen->modifier(static_cast(Ctrl))); m_pComboBoxAlt->setCurrentIndex(m_pScreen->modifier(static_cast(Alt))); m_pComboBoxMeta->setCurrentIndex(m_pScreen->modifier(static_cast(Meta))); - m_pComboBoxSuper->setCurrentIndex( - m_pScreen->modifier(static_cast(Super))); + m_pComboBoxSuper->setCurrentIndex(m_pScreen->modifier(static_cast(Super))); - m_pCheckBoxCornerTopLeft->setChecked( - m_pScreen->switchCorner(static_cast(TopLeft))); - m_pCheckBoxCornerTopRight->setChecked( - m_pScreen->switchCorner(static_cast(TopRight))); - m_pCheckBoxCornerBottomLeft->setChecked( - m_pScreen->switchCorner(static_cast(BottomLeft))); - m_pCheckBoxCornerBottomRight->setChecked( - m_pScreen->switchCorner(static_cast(BottomRight))); + m_pCheckBoxCornerTopLeft->setChecked(m_pScreen->switchCorner(static_cast(TopLeft))); + m_pCheckBoxCornerTopRight->setChecked(m_pScreen->switchCorner(static_cast(TopRight))); + m_pCheckBoxCornerBottomLeft->setChecked(m_pScreen->switchCorner(static_cast(BottomLeft))); + m_pCheckBoxCornerBottomRight->setChecked(m_pScreen->switchCorner(static_cast(BottomRight))); m_pSpinBoxSwitchCornerSize->setValue(m_pScreen->switchCornerSize()); m_pCheckBoxCapsLock->setChecked(m_pScreen->fix(CapsLock)); @@ -81,12 +75,14 @@ ScreenSettingsDialog::ScreenSettingsDialog( m_pCheckBoxXTest->setChecked(m_pScreen->fix(XTest)); } -void ScreenSettingsDialog::accept() { +void ScreenSettingsDialog::accept() +{ if (m_pLineEditName->text().isEmpty()) { QMessageBox::warning( this, tr("Screen name is empty"), tr("The screen name cannot be empty. " - "Please either fill in a name or cancel the dialog.")); + "Please either fill in a name or cancel the dialog.") + ); return; } else if (!m_pLabelNameError->text().isEmpty()) { return; @@ -102,64 +98,56 @@ void ScreenSettingsDialog::accept() { QMessageBox::warning( this, tr("Screen name matches alias"), tr("The screen name cannot be the same as an alias. " - "Please either remove the alias or change the screen name.")); + "Please either remove the alias or change the screen name.") + ); return; } m_pScreen->addAlias(alias); } - m_pScreen->setModifier( - static_cast(Shift), m_pComboBoxShift->currentIndex()); - m_pScreen->setModifier( - static_cast(Ctrl), m_pComboBoxCtrl->currentIndex()); + m_pScreen->setModifier(static_cast(Shift), m_pComboBoxShift->currentIndex()); + m_pScreen->setModifier(static_cast(Ctrl), m_pComboBoxCtrl->currentIndex()); m_pScreen->setModifier(static_cast(Alt), m_pComboBoxAlt->currentIndex()); - m_pScreen->setModifier( - static_cast(Meta), m_pComboBoxMeta->currentIndex()); - m_pScreen->setModifier( - static_cast(Super), m_pComboBoxSuper->currentIndex()); + m_pScreen->setModifier(static_cast(Meta), m_pComboBoxMeta->currentIndex()); + m_pScreen->setModifier(static_cast(Super), m_pComboBoxSuper->currentIndex()); - m_pScreen->setSwitchCorner( - static_cast(TopLeft), m_pCheckBoxCornerTopLeft->isChecked()); - m_pScreen->setSwitchCorner( - static_cast(TopRight), m_pCheckBoxCornerTopRight->isChecked()); - m_pScreen->setSwitchCorner( - static_cast(BottomLeft), m_pCheckBoxCornerBottomLeft->isChecked()); - m_pScreen->setSwitchCorner( - static_cast(BottomRight), m_pCheckBoxCornerBottomRight->isChecked()); + m_pScreen->setSwitchCorner(static_cast(TopLeft), m_pCheckBoxCornerTopLeft->isChecked()); + m_pScreen->setSwitchCorner(static_cast(TopRight), m_pCheckBoxCornerTopRight->isChecked()); + m_pScreen->setSwitchCorner(static_cast(BottomLeft), m_pCheckBoxCornerBottomLeft->isChecked()); + m_pScreen->setSwitchCorner(static_cast(BottomRight), m_pCheckBoxCornerBottomRight->isChecked()); m_pScreen->setSwitchCornerSize(m_pSpinBoxSwitchCornerSize->value()); - m_pScreen->setFix( - static_cast(CapsLock), m_pCheckBoxCapsLock->isChecked()); + m_pScreen->setFix(static_cast(CapsLock), m_pCheckBoxCapsLock->isChecked()); m_pScreen->setFix(static_cast(NumLock), m_pCheckBoxNumLock->isChecked()); - m_pScreen->setFix( - static_cast(ScrollLock), m_pCheckBoxScrollLock->isChecked()); + m_pScreen->setFix(static_cast(ScrollLock), m_pCheckBoxScrollLock->isChecked()); m_pScreen->setFix(static_cast(XTest), m_pCheckBoxXTest->isChecked()); QDialog::accept(); } -void ScreenSettingsDialog::on_m_pButtonAddAlias_clicked() { +void ScreenSettingsDialog::on_m_pButtonAddAlias_clicked() +{ if (!m_pLineEditAlias->text().isEmpty() && - m_pListAliases->findItems(m_pLineEditAlias->text(), Qt::MatchFixedString) - .isEmpty()) { + m_pListAliases->findItems(m_pLineEditAlias->text(), Qt::MatchFixedString).isEmpty()) { new QListWidgetItem(m_pLineEditAlias->text(), m_pListAliases); m_pLineEditAlias->clear(); } } -void ScreenSettingsDialog::on_m_pLineEditAlias_textChanged( - const QString &text) { - m_pButtonAddAlias->setEnabled( - !text.isEmpty() && m_pLabelAliasError->text().isEmpty()); +void ScreenSettingsDialog::on_m_pLineEditAlias_textChanged(const QString &text) +{ + m_pButtonAddAlias->setEnabled(!text.isEmpty() && m_pLabelAliasError->text().isEmpty()); } -void ScreenSettingsDialog::on_m_pButtonRemoveAlias_clicked() { +void ScreenSettingsDialog::on_m_pButtonRemoveAlias_clicked() +{ QList items = m_pListAliases->selectedItems(); for (int i = 0; i < items.count(); i++) delete items[i]; } -void ScreenSettingsDialog::on_m_pListAliases_itemSelectionChanged() { +void ScreenSettingsDialog::on_m_pListAliases_itemSelectionChanged() +{ m_pButtonRemoveAlias->setEnabled(!m_pListAliases->selectedItems().isEmpty()); } diff --git a/src/gui/src/ScreenSettingsDialog.h b/src/gui/src/ScreenSettingsDialog.h index e6dd25ffd..1200bae13 100644 --- a/src/gui/src/ScreenSettingsDialog.h +++ b/src/gui/src/ScreenSettingsDialog.h @@ -28,14 +28,12 @@ class QString; class Screen; class ScreenList; -class ScreenSettingsDialog : public QDialog, - public Ui::ScreenSettingsDialogBase { +class ScreenSettingsDialog : public QDialog, public Ui::ScreenSettingsDialogBase +{ Q_OBJECT public: - ScreenSettingsDialog( - QWidget *parent, Screen *pScreen = nullptr, - const ScreenList *pScreens = nullptr); + ScreenSettingsDialog(QWidget *parent, Screen *pScreen = nullptr, const ScreenList *pScreens = nullptr); public slots: void accept(); diff --git a/src/gui/src/ScreenSetupModel.cpp b/src/gui/src/ScreenSetupModel.cpp index d11307874..ef7a8e611 100644 --- a/src/gui/src/ScreenSetupModel.cpp +++ b/src/gui/src/ScreenSetupModel.cpp @@ -23,35 +23,30 @@ #include #include -const QString ScreenSetupModel::m_MimeType = - "application/x-" DESKFLOW_APP_ID "-screen"; +const QString ScreenSetupModel::m_MimeType = "application/x-" DESKFLOW_APP_ID "-screen"; -ScreenSetupModel::ScreenSetupModel( - ScreenList &screens, int numColumns, int numRows) +ScreenSetupModel::ScreenSetupModel(ScreenList &screens, int numColumns, int numRows) : QAbstractTableModel(NULL), m_Screens(screens), m_NumColumns(numColumns), - m_NumRows(numRows) { + m_NumRows(numRows) +{ // bound rows and columns to prevent multiply overflow. // this is unlikely to happen, as the grid size is only 3x9. if (m_NumColumns > 100 || m_NumRows > 100) { - qFatal( - "grid size out of bounds: %d columns x %d rows", m_NumColumns, - m_NumRows); + qFatal("grid size out of bounds: %d columns x %d rows", m_NumColumns, m_NumRows); return; } if (m_NumColumns * m_NumRows > screens.size()) { - qFatal( - "scrren list (%lld) too small for %d columns x %d rows", screens.size(), - m_NumColumns, m_NumRows); + qFatal("scrren list (%lld) too small for %d columns x %d rows", screens.size(), m_NumColumns, m_NumRows); } } -QVariant ScreenSetupModel::data(const QModelIndex &index, int role) const { - if (index.isValid() && index.row() < m_NumRows && - index.column() < m_NumColumns) { +QVariant ScreenSetupModel::data(const QModelIndex &index, int role) const +{ + if (index.isValid() && index.row() < m_NumRows && index.column() < m_NumColumns) { switch (role) { case Qt::DecorationRole: if (screen(index).isNull()) @@ -76,27 +71,29 @@ QVariant ScreenSetupModel::data(const QModelIndex &index, int role) const { return QVariant(); } -Qt::ItemFlags ScreenSetupModel::flags(const QModelIndex &index) const { - if (!index.isValid() || index.row() >= m_NumRows || - index.column() >= m_NumColumns) +Qt::ItemFlags ScreenSetupModel::flags(const QModelIndex &index) const +{ + if (!index.isValid() || index.row() >= m_NumRows || index.column() >= m_NumColumns) return Qt::NoItemFlags; if (!screen(index).isNull()) - return Qt::ItemIsEnabled | Qt::ItemIsDragEnabled | Qt::ItemIsSelectable | - Qt::ItemIsDropEnabled; + return Qt::ItemIsEnabled | Qt::ItemIsDragEnabled | Qt::ItemIsSelectable | Qt::ItemIsDropEnabled; return Qt::ItemIsDropEnabled; } -Qt::DropActions ScreenSetupModel::supportedDropActions() const { +Qt::DropActions ScreenSetupModel::supportedDropActions() const +{ return Qt::MoveAction | Qt::CopyAction; } -QStringList ScreenSetupModel::mimeTypes() const { +QStringList ScreenSetupModel::mimeTypes() const +{ return QStringList() << m_MimeType; } -QMimeData *ScreenSetupModel::mimeData(const QModelIndexList &indexes) const { +QMimeData *ScreenSetupModel::mimeData(const QModelIndexList &indexes) const +{ QMimeData *pMimeData = new QMimeData(); QByteArray encodedData; @@ -112,8 +109,9 @@ QMimeData *ScreenSetupModel::mimeData(const QModelIndexList &indexes) const { } bool ScreenSetupModel::dropMimeData( - const QMimeData *data, Qt::DropAction action, int row, int column, - const QModelIndex &parent) { + const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent +) +{ if (action == Qt::IgnoreAction) return true; @@ -154,15 +152,16 @@ bool ScreenSetupModel::dropMimeData( return true; } -void ScreenSetupModel::addScreen(const Screen &newScreen) { +void ScreenSetupModel::addScreen(const Screen &newScreen) +{ m_Screens.addScreenByPriority(newScreen); emit screensChanged(); } -bool ScreenSetupModel::isFull() const { - auto emptyScreen = std::find_if( - m_Screens.cbegin(), m_Screens.cend(), - [](const Screen &item) { return item.isNull(); }); +bool ScreenSetupModel::isFull() const +{ + auto emptyScreen = + std::find_if(m_Screens.cbegin(), m_Screens.cend(), [](const Screen &item) { return item.isNull(); }); return (emptyScreen == m_Screens.cend()); } diff --git a/src/gui/src/ScreenSetupModel.h b/src/gui/src/ScreenSetupModel.h index dee4ae183..9d9c2d2e4 100644 --- a/src/gui/src/ScreenSetupModel.h +++ b/src/gui/src/ScreenSetupModel.h @@ -28,7 +28,8 @@ class ScreenSetupView; class ServerConfigDialog; -class ScreenSetupModel : public QAbstractTableModel { +class ScreenSetupModel : public QAbstractTableModel +{ Q_OBJECT friend class ScreenSetupView; @@ -38,12 +39,27 @@ public: ScreenSetupModel(ScreenList &screens, int numColumns, int numRows); public: - static const QString &mimeType() { return m_MimeType; } + static const QString &mimeType() + { + return m_MimeType; + } QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const; - int rowCount() const { return m_NumRows; } - int columnCount() const { return m_NumColumns; } - int rowCount(const QModelIndex &) const { return rowCount(); } - int columnCount(const QModelIndex &) const { return columnCount(); } + int rowCount() const + { + return m_NumRows; + } + int columnCount() const + { + return m_NumColumns; + } + int rowCount(const QModelIndex &) const + { + return rowCount(); + } + int columnCount(const QModelIndex &) const + { + return columnCount(); + } Qt::DropActions supportedDropActions() const; Qt::ItemFlags flags(const QModelIndex &index) const; QStringList mimeTypes() const; @@ -54,19 +70,21 @@ signals: void screensChanged(); protected: - bool dropMimeData( - const QMimeData *data, Qt::DropAction action, int row, int column, - const QModelIndex &parent); - const Screen &screen(const QModelIndex &index) const { + bool dropMimeData(const QMimeData *data, Qt::DropAction action, int row, int column, const QModelIndex &parent); + const Screen &screen(const QModelIndex &index) const + { return screen(index.column(), index.row()); } - Screen &screen(const QModelIndex &index) { + Screen &screen(const QModelIndex &index) + { return screen(index.column(), index.row()); } - const Screen &screen(int column, int row) const { + const Screen &screen(int column, int row) const + { return m_Screens[row * m_NumColumns + column]; } - Screen &screen(int column, int row) { + Screen &screen(int column, int row) + { return m_Screens[row * m_NumColumns + column]; } void addScreen(const Screen &newScreen); diff --git a/src/gui/src/ScreenSetupView.cpp b/src/gui/src/ScreenSetupView.cpp index db15fe3eb..d7a283202 100644 --- a/src/gui/src/ScreenSetupView.cpp +++ b/src/gui/src/ScreenSetupView.cpp @@ -25,7 +25,8 @@ #include #include -ScreenSetupView::ScreenSetupView(QWidget *parent) : QTableView(parent) { +ScreenSetupView::ScreenSetupView(QWidget *parent) : QTableView(parent) +{ setDropIndicatorShown(true); setDragDropMode(DragDrop); setSelectionMode(SingleSelection); @@ -38,16 +39,19 @@ ScreenSetupView::ScreenSetupView(QWidget *parent) : QTableView(parent) { verticalHeader()->hide(); } -void ScreenSetupView::setModel(QAbstractItemModel *model) { +void ScreenSetupView::setModel(QAbstractItemModel *model) +{ QTableView::setModel(model); setTableSize(); } -ScreenSetupModel *ScreenSetupView::model() const { +ScreenSetupModel *ScreenSetupView::model() const +{ return qobject_cast(QTableView::model()); } -void ScreenSetupView::setTableSize() { +void ScreenSetupView::setTableSize() +{ for (int i = 0; i < model()->columnCount(); i++) setColumnWidth(i, width() / model()->columnCount()); @@ -55,19 +59,20 @@ void ScreenSetupView::setTableSize() { setRowHeight(i, height() / model()->rowCount()); } -void ScreenSetupView::resizeEvent(QResizeEvent *event) { +void ScreenSetupView::resizeEvent(QResizeEvent *event) +{ setTableSize(); event->ignore(); } -void ScreenSetupView::mouseDoubleClickEvent(QMouseEvent *event) { +void ScreenSetupView::mouseDoubleClickEvent(QMouseEvent *event) +{ if (event->buttons() & Qt::LeftButton) { int col = columnAt(event->pos().x()); int row = rowAt(event->pos().y()); if (!model()->screen(col, row).isNull()) { - ScreenSettingsDialog dlg( - this, &model()->screen(col, row), &model()->m_Screens); + ScreenSettingsDialog dlg(this, &model()->screen(col, row), &model()->m_Screens); dlg.exec(); emit model() -> screensChanged(); } @@ -75,7 +80,8 @@ void ScreenSetupView::mouseDoubleClickEvent(QMouseEvent *event) { event->ignore(); } -void ScreenSetupView::dragEnterEvent(QDragEnterEvent *event) { +void ScreenSetupView::dragEnterEvent(QDragEnterEvent *event) +{ // we accept anything that enters us by a drag as long as the // mime type is okay. anything else is dealt with in dragMoveEvent() if (event->mimeData()->hasFormat(ScreenSetupModel::mimeType())) @@ -84,7 +90,8 @@ void ScreenSetupView::dragEnterEvent(QDragEnterEvent *event) { event->ignore(); } -void ScreenSetupView::dragMoveEvent(QDragMoveEvent *event) { +void ScreenSetupView::dragMoveEvent(QDragMoveEvent *event) +{ if (event->mimeData()->hasFormat(ScreenSetupModel::mimeType())) { // where does the event come from? myself or someone else? if (event->source() == this) { @@ -107,7 +114,8 @@ void ScreenSetupView::dragMoveEvent(QDragMoveEvent *event) { } // this is reimplemented from QAbstractItemView::startDrag() -void ScreenSetupView::startDrag(Qt::DropActions) { +void ScreenSetupView::startDrag(Qt::DropActions) +{ QModelIndexList indexes = selectedIndexes(); if (indexes.count() != 1) @@ -137,7 +145,8 @@ void ScreenSetupView::startDrag(Qt::DropActions) { } } -void ScreenSetupView::initViewItemOption(QStyleOptionViewItem *option) const { +void ScreenSetupView::initViewItemOption(QStyleOptionViewItem *option) const +{ option->showDecorationSelected = true; option->decorationPosition = QStyleOptionViewItem::Top; option->displayAlignment = Qt::AlignCenter; diff --git a/src/gui/src/ScreenSetupView.h b/src/gui/src/ScreenSetupView.h index 38c8f8d64..10f672a60 100644 --- a/src/gui/src/ScreenSetupView.h +++ b/src/gui/src/ScreenSetupView.h @@ -29,7 +29,8 @@ class QResizeEvent; class QDragEnterEvent; class ScreenSetupModel; -class ScreenSetupView : public QTableView { +class ScreenSetupView : public QTableView +{ Q_OBJECT public: @@ -47,5 +48,7 @@ protected: void dragMoveEvent(QDragMoveEvent *event) override; void startDrag(Qt::DropActions supportedActions) override; void initViewItemOption(QStyleOptionViewItem *option) const override; - void scrollTo(const QModelIndex &, ScrollHint) override {} + void scrollTo(const QModelIndex &, ScrollHint) override + { + } }; diff --git a/src/gui/src/ServerConfig.cpp b/src/gui/src/ServerConfig.cpp index fb7ff5f9e..9ca099f48 100644 --- a/src/gui/src/ServerConfig.cpp +++ b/src/gui/src/ServerConfig.cpp @@ -32,7 +32,8 @@ using enum ScreenConfig::Modifier; using enum ScreenConfig::SwitchCorner; using enum ScreenConfig::Fix; -static const struct { +static const struct +{ int x; int y; const char *name; @@ -46,18 +47,19 @@ static const struct { const int serverDefaultIndex = 7; -ServerConfig::ServerConfig( - AppConfig &appConfig, MainWindow &mainWindow, int columns, int rows) +ServerConfig::ServerConfig(AppConfig &appConfig, MainWindow &mainWindow, int columns, int rows) : m_pAppConfig(&appConfig), m_pMainWindow(&mainWindow), m_Screens(columns), m_Columns(columns), m_Rows(rows), - m_ClipboardSharingSize(defaultClipboardSharingSize()) { + m_ClipboardSharingSize(defaultClipboardSharingSize()) +{ recall(); } -bool ServerConfig::save(const QString &fileName) const { +bool ServerConfig::save(const QString &fileName) const +{ QFile file(fileName); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) return false; @@ -68,32 +70,28 @@ bool ServerConfig::save(const QString &fileName) const { return true; } -bool ServerConfig::operator==(const ServerConfig &sc) const { - return m_Screens == sc.m_Screens && m_Columns == sc.m_Columns && - m_Rows == sc.m_Rows && m_HasHeartbeat == sc.m_HasHeartbeat && - m_Heartbeat == sc.m_Heartbeat && - m_RelativeMouseMoves == sc.m_RelativeMouseMoves && - m_Win32KeepForeground == sc.m_Win32KeepForeground && - m_HasSwitchDelay == sc.m_HasSwitchDelay && - m_SwitchDelay == sc.m_SwitchDelay && - m_HasSwitchDoubleTap == sc.m_HasSwitchDoubleTap && - m_SwitchDoubleTap == sc.m_SwitchDoubleTap && - m_SwitchCornerSize == sc.m_SwitchCornerSize && - m_SwitchCorners == sc.m_SwitchCorners && m_Hotkeys == sc.m_Hotkeys && - m_pAppConfig == sc.m_pAppConfig && - m_EnableDragAndDrop == sc.m_EnableDragAndDrop && - m_DisableLockToScreen == sc.m_DisableLockToScreen && - m_ClipboardSharing == sc.m_ClipboardSharing && - m_ClipboardSharingSize == sc.m_ClipboardSharingSize && +bool ServerConfig::operator==(const ServerConfig &sc) const +{ + return m_Screens == sc.m_Screens && m_Columns == sc.m_Columns && m_Rows == sc.m_Rows && + m_HasHeartbeat == sc.m_HasHeartbeat && m_Heartbeat == sc.m_Heartbeat && + m_RelativeMouseMoves == sc.m_RelativeMouseMoves && m_Win32KeepForeground == sc.m_Win32KeepForeground && + m_HasSwitchDelay == sc.m_HasSwitchDelay && m_SwitchDelay == sc.m_SwitchDelay && + m_HasSwitchDoubleTap == sc.m_HasSwitchDoubleTap && m_SwitchDoubleTap == sc.m_SwitchDoubleTap && + m_SwitchCornerSize == sc.m_SwitchCornerSize && m_SwitchCorners == sc.m_SwitchCorners && + m_Hotkeys == sc.m_Hotkeys && m_pAppConfig == sc.m_pAppConfig && + m_EnableDragAndDrop == sc.m_EnableDragAndDrop && m_DisableLockToScreen == sc.m_DisableLockToScreen && + m_ClipboardSharing == sc.m_ClipboardSharing && m_ClipboardSharingSize == sc.m_ClipboardSharingSize && m_pMainWindow == sc.m_pMainWindow; } -void ServerConfig::save(QFile &file) const { +void ServerConfig::save(QFile &file) const +{ QTextStream outStream(&file); outStream << *this; } -void ServerConfig::setupScreens() { +void ServerConfig::setupScreens() +{ switchCorners().clear(); screens().clear(); hotkeys().clear(); @@ -108,7 +106,8 @@ void ServerConfig::setupScreens() { addScreen(Screen()); } -void ServerConfig::commit() { +void ServerConfig::commit() +{ qDebug("committing server config"); settings().beginGroup("internalConfig"); @@ -129,8 +128,7 @@ void ServerConfig::commit() { settings().setValue("disableLockToScreen", disableLockToScreen()); settings().setValue("enableDragAndDrop", enableDragAndDrop()); settings().setValue("clipboardSharing", clipboardSharing()); - settings().setValue( - "clipboardSharingSize", QVariant::fromValue(clipboardSharingSize())); + settings().setValue("clipboardSharingSize", QVariant::fromValue(clipboardSharingSize())); if (!getClientAddress().isEmpty()) { settings().setValue("clientAddress", getClientAddress()); @@ -159,7 +157,8 @@ void ServerConfig::commit() { settings().endGroup(); } -void ServerConfig::recall() { +void ServerConfig::recall() +{ qDebug("recalling server config"); settings().beginGroup("internalConfig"); @@ -174,28 +173,21 @@ void ServerConfig::recall() { haveHeartbeat(settings().value("hasHeartbeat", false).toBool()); setHeartbeat(settings().value("heartbeat", 5000).toInt()); setRelativeMouseMoves(settings().value("relativeMouseMoves", false).toBool()); - setWin32KeepForeground( - settings().value("win32KeepForeground", false).toBool()); + setWin32KeepForeground(settings().value("win32KeepForeground", false).toBool()); haveSwitchDelay(settings().value("hasSwitchDelay", false).toBool()); setSwitchDelay(settings().value("switchDelay", 250).toInt()); haveSwitchDoubleTap(settings().value("hasSwitchDoubleTap", false).toBool()); setSwitchDoubleTap(settings().value("switchDoubleTap", 250).toInt()); setSwitchCornerSize(settings().value("switchCornerSize").toInt()); - setDisableLockToScreen( - settings().value("disableLockToScreen", false).toBool()); + setDisableLockToScreen(settings().value("disableLockToScreen", false).toBool()); setEnableDragAndDrop(settings().value("enableDragAndDrop", false).toBool()); setClipboardSharingSize( - settings() - .value( - "clipboardSharingSize", - (int)ServerConfig::defaultClipboardSharingSize()) - .toULongLong()); + settings().value("clipboardSharingSize", (int)ServerConfig::defaultClipboardSharingSize()).toULongLong() + ); setClipboardSharing(settings().value("clipboardSharing", true).toBool()); setClientAddress(settings().value("clientAddress", "").toString()); - readSettings( - settings(), switchCorners(), "switchCorner", 0, - static_cast(NumSwitchCorners)); + readSettings(settings(), switchCorners(), "switchCorner", 0, static_cast(NumSwitchCorners)); int numScreens = settings().beginReadArray("screens"); Q_ASSERT(numScreens <= screens().size()); @@ -220,15 +212,14 @@ void ServerConfig::recall() { settings().endGroup(); } -int ServerConfig::adjacentScreenIndex( - int idx, int deltaColumn, int deltaRow) const { +int ServerConfig::adjacentScreenIndex(int idx, int deltaColumn, int deltaRow) const +{ if (screens()[idx].isNull()) return -1; // if we're at the left or right end of the table, don't find results going // further left or right - if ((deltaColumn > 0 && (idx + 1) % numColumns() == 0) || - (deltaColumn < 0 && idx % numColumns() == 0)) + if ((deltaColumn > 0 && (idx + 1) % numColumns() == 0) || (deltaColumn < 0 && idx % numColumns() == 0)) return -1; int arrayPos = idx + deltaColumn + deltaRow * numColumns(); @@ -239,7 +230,8 @@ int ServerConfig::adjacentScreenIndex( return arrayPos; } -QTextStream &operator<<(QTextStream &outStream, const ServerConfig &config) { +QTextStream &operator<<(QTextStream &outStream, const ServerConfig &config) +{ outStream << "section: screens" << Qt::endl; foreach (const Screen &s, config.screens()) @@ -262,13 +254,10 @@ QTextStream &operator<<(QTextStream &outStream, const ServerConfig &config) { if (!config.screens()[i].isNull()) { outStream << "\t" << config.screens()[i].name() << ":" << Qt::endl; - for (unsigned int j = 0; - j < sizeof(neighbourDirs) / sizeof(neighbourDirs[0]); j++) { - int idx = config.adjacentScreenIndex( - i, neighbourDirs[j].x, neighbourDirs[j].y); + for (unsigned int j = 0; j < sizeof(neighbourDirs) / sizeof(neighbourDirs[0]); j++) { + int idx = config.adjacentScreenIndex(i, neighbourDirs[j].x, neighbourDirs[j].y); if (idx != -1 && !config.screens()[idx].isNull()) - outStream << "\t\t" << neighbourDirs[j].name << " = " - << config.screens()[idx].name() << Qt::endl; + outStream << "\t\t" << neighbourDirs[j].name << " = " << config.screens()[idx].name() << Qt::endl; } } @@ -281,20 +270,15 @@ QTextStream &operator<<(QTextStream &outStream, const ServerConfig &config) { << "heartbeat = " << config.heartbeat() << Qt::endl; outStream << "\t" - << "relativeMouseMoves = " - << (config.relativeMouseMoves() ? "true" : "false") << Qt::endl; + << "relativeMouseMoves = " << (config.relativeMouseMoves() ? "true" : "false") << Qt::endl; outStream << "\t" - << "win32KeepForeground = " - << (config.win32KeepForeground() ? "true" : "false") << Qt::endl; + << "win32KeepForeground = " << (config.win32KeepForeground() ? "true" : "false") << Qt::endl; outStream << "\t" - << "disableLockToScreen = " - << (config.disableLockToScreen() ? "true" : "false") << Qt::endl; + << "disableLockToScreen = " << (config.disableLockToScreen() ? "true" : "false") << Qt::endl; outStream << "\t" - << "clipboardSharing = " - << (config.clipboardSharing() ? "true" : "false") << Qt::endl; + << "clipboardSharing = " << (config.clipboardSharing() ? "true" : "false") << Qt::endl; outStream << "\t" - << "clipboardSharingSize = " << config.clipboardSharingSize() - << Qt::endl; + << "clipboardSharingSize = " << config.clipboardSharingSize() << Qt::endl; if (!config.getClientAddress().isEmpty()) { outStream << "\t" @@ -327,7 +311,8 @@ QTextStream &operator<<(QTextStream &outStream, const ServerConfig &config) { return outStream; } -int ServerConfig::numScreens() const { +int ServerConfig::numScreens() const +{ int rval = 0; foreach (const Screen &s, screens()) @@ -337,7 +322,8 @@ int ServerConfig::numScreens() const { return rval; } -int ServerConfig::autoAddScreen(const QString name) { +int ServerConfig::autoAddScreen(const QString name) +{ int serverIndex = -1; int targetIndex = -1; if (!findScreenName(m_pAppConfig->screenName(), serverIndex) && @@ -377,8 +363,7 @@ int ServerConfig::autoAddScreen(const QString name) { dirIndex = 3; } - int idx = adjacentScreenIndex( - startIndex, neighbourDirs[dirIndex].x, neighbourDirs[dirIndex].y); + int idx = adjacentScreenIndex(startIndex, neighbourDirs[dirIndex].x, neighbourDirs[dirIndex].y); while (idx != -1) { if (screens()[idx].isNull()) { m_Screens[idx].setName(name); @@ -387,8 +372,7 @@ int ServerConfig::autoAddScreen(const QString name) { } startIndex += offset; - idx = adjacentScreenIndex( - startIndex, neighbourDirs[dirIndex].x, neighbourDirs[dirIndex].y); + idx = adjacentScreenIndex(startIndex, neighbourDirs[dirIndex].x, neighbourDirs[dirIndex].y); } if (!success) { @@ -399,11 +383,13 @@ int ServerConfig::autoAddScreen(const QString name) { return kAutoAddScreenOk; } -const QString &ServerConfig::getServerName() const { +const QString &ServerConfig::getServerName() const +{ return m_pAppConfig->screenName(); } -void ServerConfig::updateServerName() { +void ServerConfig::updateServerName() +{ for (auto &screen : screens()) { if (screen.isServer()) { screen.setName(m_pAppConfig->screenName()); @@ -412,15 +398,18 @@ void ServerConfig::updateServerName() { } } -const QString &ServerConfig::configFile() const { +const QString &ServerConfig::configFile() const +{ return m_pAppConfig->configFile(); } -bool ServerConfig::useExternalConfig() const { +bool ServerConfig::useExternalConfig() const +{ return m_pAppConfig->useExternalConfig(); } -bool ServerConfig::isFull() const { +bool ServerConfig::isFull() const +{ bool isFull = true; for (const auto &screen : screens()) { @@ -433,7 +422,8 @@ bool ServerConfig::isFull() const { return isFull; } -bool ServerConfig::screenExists(const QString &screenName) const { +bool ServerConfig::screenExists(const QString &screenName) const +{ bool isExists = false; for (const auto &screen : screens()) { @@ -446,7 +436,8 @@ bool ServerConfig::screenExists(const QString &screenName) const { return isExists; } -void ServerConfig::addClient(const QString &clientName) { +void ServerConfig::addClient(const QString &clientName) +{ int serverIndex = -1; if (findScreenName(m_pAppConfig->screenName(), serverIndex)) { @@ -458,15 +449,18 @@ void ServerConfig::addClient(const QString &clientName) { m_Screens.addScreenByPriority(Screen(clientName)); } -void ServerConfig::setConfigFile(const QString &configFile) { +void ServerConfig::setConfigFile(const QString &configFile) +{ m_pAppConfig->setConfigFile(configFile); } -void ServerConfig::setUseExternalConfig(bool useExternalConfig) { +void ServerConfig::setUseExternalConfig(bool useExternalConfig) +{ m_pAppConfig->setUseExternalConfig(useExternalConfig); } -bool ServerConfig::findScreenName(const QString &name, int &index) { +bool ServerConfig::findScreenName(const QString &name, int &index) +{ bool found = false; for (int i = 0; i < screens().size(); i++) { if (!screens()[i].isNull() && screens()[i].name().compare(name) == 0) { @@ -478,7 +472,8 @@ bool ServerConfig::findScreenName(const QString &name, int &index) { return found; } -bool ServerConfig::fixNoServer(const QString &name, int &index) { +bool ServerConfig::fixNoServer(const QString &name, int &index) +{ bool fixed = false; if (screens()[serverDefaultIndex].isNull()) { m_Screens[serverDefaultIndex].setName(name); @@ -490,7 +485,8 @@ bool ServerConfig::fixNoServer(const QString &name, int &index) { return fixed; } -int ServerConfig::showAddClientDialog(const QString &clientName) { +int ServerConfig::showAddClientDialog(const QString &clientName) +{ int result = kAddClientIgnore; if (!m_pMainWindow->isActiveWindow()) { @@ -505,7 +501,8 @@ int ServerConfig::showAddClientDialog(const QString &clientName) { return result; } -void ::ServerConfig::addToFirstEmptyGrid(const QString &clientName) { +void ::ServerConfig::addToFirstEmptyGrid(const QString &clientName) +{ for (int i = 0; i < screens().size(); i++) { if (screens()[i].isNull()) { m_Screens[i].setName(clientName); @@ -514,11 +511,13 @@ void ::ServerConfig::addToFirstEmptyGrid(const QString &clientName) { } } -size_t ServerConfig::defaultClipboardSharingSize() { +size_t ServerConfig::defaultClipboardSharingSize() +{ return 3 * 1024; // 3 MiB } -size_t ServerConfig::setClipboardSharingSize(size_t size) { +size_t ServerConfig::setClipboardSharingSize(size_t size) +{ if (size) { size += 512; // Round up to the nearest megabyte size /= 1024; @@ -532,13 +531,15 @@ size_t ServerConfig::setClipboardSharingSize(size_t size) { return size; } -void ServerConfig::setClientAddress(const QString &address) { +void ServerConfig::setClientAddress(const QString &address) +{ if (m_pAppConfig->invertConnection()) { m_ClientAddress = address; } } -QString ServerConfig::getClientAddress() const { +QString ServerConfig::getClientAddress() const +{ QString clientAddress; if (m_pAppConfig->invertConnection()) { @@ -548,6 +549,7 @@ QString ServerConfig::getClientAddress() const { return clientAddress; } -QSettingsProxy &ServerConfig::settings() { +QSettingsProxy &ServerConfig::settings() +{ return m_pAppConfig->scopes().activeSettings(); } diff --git a/src/gui/src/ServerConfig.h b/src/gui/src/ServerConfig.h index c154899b8..ff16c1473 100644 --- a/src/gui/src/ServerConfig.h +++ b/src/gui/src/ServerConfig.h @@ -36,17 +36,15 @@ class ServerConfigDialog; class MainWindow; class AppConfig; -class ServerConfig : public ScreenConfig, public deskflow::gui::IServerConfig { +class ServerConfig : public ScreenConfig, public deskflow::gui::IServerConfig +{ using QSettingsProxy = deskflow::gui::proxy::QSettingsProxy; friend class ServerConfigDialog; - friend QTextStream & - operator<<(QTextStream &outStream, const ServerConfig &config); + friend QTextStream &operator<<(QTextStream &outStream, const ServerConfig &config); public: - ServerConfig( - AppConfig &appConfig, MainWindow &mainWindow, - int columns = kDefaultColumns, int rows = kDefaultRows); + ServerConfig(AppConfig &appConfig, MainWindow &mainWindow, int columns = kDefaultColumns, int rows = kDefaultRows); ~ServerConfig() override = default; bool operator==(const ServerConfig &sc) const; @@ -54,29 +52,86 @@ public: // // Overrides // - const ScreenList &screens() const override { return m_Screens; } - bool enableDragAndDrop() const override { return m_EnableDragAndDrop; } + const ScreenList &screens() const override + { + return m_Screens; + } + bool enableDragAndDrop() const override + { + return m_EnableDragAndDrop; + } // // New methods // - int numColumns() const { return m_Columns; } - int numRows() const { return m_Rows; } - bool hasHeartbeat() const { return m_HasHeartbeat; } - int heartbeat() const { return m_Heartbeat; } - bool relativeMouseMoves() const { return m_RelativeMouseMoves; } - bool win32KeepForeground() const { return m_Win32KeepForeground; } - bool hasSwitchDelay() const { return m_HasSwitchDelay; } - int switchDelay() const { return m_SwitchDelay; } - bool hasSwitchDoubleTap() const { return m_HasSwitchDoubleTap; } - int switchDoubleTap() const { return m_SwitchDoubleTap; } - bool switchCorner(int c) const { return m_SwitchCorners[c]; } - int switchCornerSize() const { return m_SwitchCornerSize; } - const QList &switchCorners() const { return m_SwitchCorners; } - const HotkeyList &hotkeys() const { return m_Hotkeys; } - bool disableLockToScreen() const { return m_DisableLockToScreen; } - bool clipboardSharing() const { return m_ClipboardSharing; } - size_t clipboardSharingSize() const { return m_ClipboardSharingSize; } + int numColumns() const + { + return m_Columns; + } + int numRows() const + { + return m_Rows; + } + bool hasHeartbeat() const + { + return m_HasHeartbeat; + } + int heartbeat() const + { + return m_Heartbeat; + } + bool relativeMouseMoves() const + { + return m_RelativeMouseMoves; + } + bool win32KeepForeground() const + { + return m_Win32KeepForeground; + } + bool hasSwitchDelay() const + { + return m_HasSwitchDelay; + } + int switchDelay() const + { + return m_SwitchDelay; + } + bool hasSwitchDoubleTap() const + { + return m_HasSwitchDoubleTap; + } + int switchDoubleTap() const + { + return m_SwitchDoubleTap; + } + bool switchCorner(int c) const + { + return m_SwitchCorners[c]; + } + int switchCornerSize() const + { + return m_SwitchCornerSize; + } + const QList &switchCorners() const + { + return m_SwitchCorners; + } + const HotkeyList &hotkeys() const + { + return m_Hotkeys; + } + bool disableLockToScreen() const + { + return m_DisableLockToScreen; + } + bool clipboardSharing() const + { + return m_ClipboardSharing; + } + size_t clipboardSharingSize() const + { + return m_ClipboardSharingSize; + } static size_t defaultClipboardSharingSize(); // @@ -105,29 +160,89 @@ private: void recall(); void setupScreens(); QSettingsProxy &settings(); - ScreenList &screens() { return m_Screens; } - void setScreens(const ScreenList &screens) { m_Screens = screens; } - void addScreen(const Screen &screen) { m_Screens.append(screen); } - void setNumColumns(int n) { m_Columns = n; } - void setNumRows(int n) { m_Rows = n; } - void haveHeartbeat(bool on) { m_HasHeartbeat = on; } - void setHeartbeat(int val) { m_Heartbeat = val; } - void setRelativeMouseMoves(bool on) { m_RelativeMouseMoves = on; } - void setWin32KeepForeground(bool on) { m_Win32KeepForeground = on; } - void haveSwitchDelay(bool on) { m_HasSwitchDelay = on; } - void setSwitchDelay(int val) { m_SwitchDelay = val; } - void haveSwitchDoubleTap(bool on) { m_HasSwitchDoubleTap = on; } - void setSwitchDoubleTap(int val) { m_SwitchDoubleTap = val; } - void setSwitchCorner(int c, bool on) { m_SwitchCorners[c] = on; } - void setSwitchCornerSize(int val) { m_SwitchCornerSize = val; } - void setEnableDragAndDrop(bool on) { m_EnableDragAndDrop = on; } - void setDisableLockToScreen(bool on) { m_DisableLockToScreen = on; } - void setClipboardSharing(bool on) { m_ClipboardSharing = on; } + ScreenList &screens() + { + return m_Screens; + } + void setScreens(const ScreenList &screens) + { + m_Screens = screens; + } + void addScreen(const Screen &screen) + { + m_Screens.append(screen); + } + void setNumColumns(int n) + { + m_Columns = n; + } + void setNumRows(int n) + { + m_Rows = n; + } + void haveHeartbeat(bool on) + { + m_HasHeartbeat = on; + } + void setHeartbeat(int val) + { + m_Heartbeat = val; + } + void setRelativeMouseMoves(bool on) + { + m_RelativeMouseMoves = on; + } + void setWin32KeepForeground(bool on) + { + m_Win32KeepForeground = on; + } + void haveSwitchDelay(bool on) + { + m_HasSwitchDelay = on; + } + void setSwitchDelay(int val) + { + m_SwitchDelay = val; + } + void haveSwitchDoubleTap(bool on) + { + m_HasSwitchDoubleTap = on; + } + void setSwitchDoubleTap(int val) + { + m_SwitchDoubleTap = val; + } + void setSwitchCorner(int c, bool on) + { + m_SwitchCorners[c] = on; + } + void setSwitchCornerSize(int val) + { + m_SwitchCornerSize = val; + } + void setEnableDragAndDrop(bool on) + { + m_EnableDragAndDrop = on; + } + void setDisableLockToScreen(bool on) + { + m_DisableLockToScreen = on; + } + void setClipboardSharing(bool on) + { + m_ClipboardSharing = on; + } void setConfigFile(const QString &configFile); void setUseExternalConfig(bool useExternalConfig); size_t setClipboardSharingSize(size_t size); - QList &switchCorners() { return m_SwitchCorners; } - HotkeyList &hotkeys() { return m_Hotkeys; } + QList &switchCorners() + { + return m_SwitchCorners; + } + HotkeyList &hotkeys() + { + return m_Hotkeys; + } int adjacentScreenIndex(int idx, int deltaColumn, int deltaRow) const; bool findScreenName(const QString &name, int &index); bool fixNoServer(const QString &name, int &index); @@ -161,7 +276,8 @@ private: QTextStream &operator<<(QTextStream &outStream, const ServerConfig &config); -enum { +enum +{ kAutoAddScreenOk, kAutoAddScreenManualServer, kAutoAddScreenManualClient, diff --git a/src/gui/src/ServerConfigDialog.cpp b/src/gui/src/ServerConfigDialog.cpp index 6d2d11a3b..473156559 100644 --- a/src/gui/src/ServerConfigDialog.cpp +++ b/src/gui/src/ServerConfigDialog.cpp @@ -30,19 +30,17 @@ using enum ScreenConfig::SwitchCorner; -ServerConfigDialog::ServerConfigDialog( - QWidget *parent, ServerConfig &config, AppConfig &appConfig) +ServerConfigDialog::ServerConfigDialog(QWidget *parent, ServerConfig &config, AppConfig &appConfig) : QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint), Ui::ServerConfigDialogBase(), m_OriginalServerConfig(config), m_OriginalServerConfigIsExternal(config.useExternalConfig()), m_OriginalServerConfigUsesExternalFile(config.configFile()), m_ServerConfig(config), - m_ScreenSetupModel( - serverConfig().screens(), serverConfig().numColumns(), - serverConfig().numRows()), + m_ScreenSetupModel(serverConfig().screens(), serverConfig().numColumns(), serverConfig().numRows()), m_Message(""), - m_appConfig(appConfig) { + m_appConfig(appConfig) +{ setupUi(this); @@ -55,10 +53,8 @@ ServerConfigDialog::ServerConfigDialog( m_pCheckBoxHeartbeat->setChecked(serverConfig().hasHeartbeat()); m_pSpinBoxHeartbeat->setValue(serverConfig().heartbeat()); - m_pCheckBoxRelativeMouseMoves->setChecked( - serverConfig().relativeMouseMoves()); - m_pCheckBoxWin32KeepForeground->setChecked( - serverConfig().win32KeepForeground()); + m_pCheckBoxRelativeMouseMoves->setChecked(serverConfig().relativeMouseMoves()); + m_pCheckBoxWin32KeepForeground->setChecked(serverConfig().win32KeepForeground()); m_pCheckBoxSwitchDelay->setChecked(serverConfig().hasSwitchDelay()); m_pSpinBoxSwitchDelay->setValue(serverConfig().switchDelay()); @@ -66,21 +62,15 @@ ServerConfigDialog::ServerConfigDialog( m_pCheckBoxSwitchDoubleTap->setChecked(serverConfig().hasSwitchDoubleTap()); m_pSpinBoxSwitchDoubleTap->setValue(serverConfig().switchDoubleTap()); - m_pCheckBoxCornerTopLeft->setChecked( - serverConfig().switchCorner(static_cast(TopLeft))); - m_pCheckBoxCornerTopRight->setChecked( - serverConfig().switchCorner(static_cast(TopRight))); - m_pCheckBoxCornerBottomLeft->setChecked( - serverConfig().switchCorner(static_cast(BottomLeft))); - m_pCheckBoxCornerBottomRight->setChecked( - serverConfig().switchCorner(static_cast(BottomRight))); + m_pCheckBoxCornerTopLeft->setChecked(serverConfig().switchCorner(static_cast(TopLeft))); + m_pCheckBoxCornerTopRight->setChecked(serverConfig().switchCorner(static_cast(TopRight))); + m_pCheckBoxCornerBottomLeft->setChecked(serverConfig().switchCorner(static_cast(BottomLeft))); + m_pCheckBoxCornerBottomRight->setChecked(serverConfig().switchCorner(static_cast(BottomRight))); m_pSpinBoxSwitchCornerSize->setValue(serverConfig().switchCornerSize()); - m_pCheckBoxDisableLockToScreen->setChecked( - serverConfig().disableLockToScreen()); + m_pCheckBoxDisableLockToScreen->setChecked(serverConfig().disableLockToScreen()); m_pCheckBoxEnableClipboard->setChecked(serverConfig().clipboardSharing()); - int clipboardSharingSizeM = - static_cast(serverConfig().clipboardSharingSize() / 1024); + int clipboardSharingSizeM = static_cast(serverConfig().clipboardSharingSize() / 1024); m_pSpinBoxClipboardSizeLimit->setValue(clipboardSharingSizeM); m_pSpinBoxClipboardSizeLimit->setEnabled(serverConfig().clipboardSharing()); @@ -90,223 +80,164 @@ ServerConfigDialog::ServerConfigDialog( m_pScreenSetupView->setModel(&m_ScreenSetupModel); auto &screens = serverConfig().screens(); - auto server = std::find_if( - screens.begin(), screens.end(), [this](const Screen &screen) { - return (screen.name() == serverConfig().getServerName()); - }); + auto server = std::find_if(screens.begin(), screens.end(), [this](const Screen &screen) { + return (screen.name() == serverConfig().getServerName()); + }); if (server == screens.end()) { Screen serverScreen(serverConfig().getServerName()); serverScreen.markAsServer(); - model().screen( - serverConfig().numColumns() / 2, serverConfig().numRows() / 2) = - serverScreen; + model().screen(serverConfig().numColumns() / 2, serverConfig().numRows() / 2) = serverScreen; } else { server->markAsServer(); } m_pButtonAddComputer->setEnabled(!model().isFull()); - connect( - m_pTrashScreenWidget, &TrashScreenWidget::screenRemoved, this, - &ServerConfigDialog::onScreenRemoved); + connect(m_pTrashScreenWidget, &TrashScreenWidget::screenRemoved, this, &ServerConfigDialog::onScreenRemoved); onChange(); // computers - connect( - &m_ScreenSetupModel, &ScreenSetupModel::screensChanged, this, - &ServerConfigDialog::onChange); + connect(&m_ScreenSetupModel, &ScreenSetupModel::screensChanged, this, &ServerConfigDialog::onChange); #if QT_VERSION <= QT_VERSION_CHECK(6, 7, 0) // advanced - connect( - m_pCheckBoxSwitchDelay, &QCheckBox::stateChanged, this, - [this](const int &v) { - serverConfig().haveSwitchDelay(v); - onChange(); - }); - connect( - m_pCheckBoxSwitchDoubleTap, &QCheckBox::stateChanged, this, - [this](const int &v) { - serverConfig().haveSwitchDoubleTap(v); - onChange(); - }); - connect( - m_pCheckBoxEnableClipboard, &QCheckBox::stateChanged, this, - [this](const int &v) { - serverConfig().setClipboardSharing(v); - onChange(); - }); - connect( - m_pCheckBoxHeartbeat, &QCheckBox::stateChanged, this, - [this](const int &v) { - serverConfig().haveHeartbeat(v); - onChange(); - }); - connect( - m_pCheckBoxRelativeMouseMoves, &QCheckBox::stateChanged, this, - [this](const int &v) { - serverConfig().setRelativeMouseMoves(v); - onChange(); - }); - connect( - m_pCheckBoxWin32KeepForeground, &QCheckBox::stateChanged, this, - [this](const int &v) { - serverConfig().setWin32KeepForeground(v); - onChange(); - }); - connect( - m_pCheckBoxDisableLockToScreen, &QCheckBox::stateChanged, this, - [this](const int &v) { - serverConfig().setDisableLockToScreen(v); - onChange(); - }); - connect( - m_pCheckBoxCornerTopLeft, &QCheckBox::stateChanged, this, - [this](const int &v) { - serverConfig().setSwitchCorner(static_cast(TopLeft), v); - onChange(); - }); - connect( - m_pCheckBoxCornerTopRight, &QCheckBox::stateChanged, this, - [this](const int &v) { - serverConfig().setSwitchCorner(static_cast(TopRight), v); - onChange(); - }); - connect( - m_pCheckBoxCornerBottomLeft, &QCheckBox::stateChanged, this, - [this](const int &v) { - serverConfig().setSwitchCorner(static_cast(BottomLeft), v); - onChange(); - }); - connect( - m_pCheckBoxCornerBottomRight, &QCheckBox::stateChanged, this, - [this](const int &v) { - serverConfig().setSwitchCorner(static_cast(BottomRight), v); - onChange(); - }); + connect(m_pCheckBoxSwitchDelay, &QCheckBox::stateChanged, this, [this](const int &v) { + serverConfig().haveSwitchDelay(v); + onChange(); + }); + connect(m_pCheckBoxSwitchDoubleTap, &QCheckBox::stateChanged, this, [this](const int &v) { + serverConfig().haveSwitchDoubleTap(v); + onChange(); + }); + connect(m_pCheckBoxEnableClipboard, &QCheckBox::stateChanged, this, [this](const int &v) { + serverConfig().setClipboardSharing(v); + onChange(); + }); + connect(m_pCheckBoxHeartbeat, &QCheckBox::stateChanged, this, [this](const int &v) { + serverConfig().haveHeartbeat(v); + onChange(); + }); + connect(m_pCheckBoxRelativeMouseMoves, &QCheckBox::stateChanged, this, [this](const int &v) { + serverConfig().setRelativeMouseMoves(v); + onChange(); + }); + connect(m_pCheckBoxWin32KeepForeground, &QCheckBox::stateChanged, this, [this](const int &v) { + serverConfig().setWin32KeepForeground(v); + onChange(); + }); + connect(m_pCheckBoxDisableLockToScreen, &QCheckBox::stateChanged, this, [this](const int &v) { + serverConfig().setDisableLockToScreen(v); + onChange(); + }); + connect(m_pCheckBoxCornerTopLeft, &QCheckBox::stateChanged, this, [this](const int &v) { + serverConfig().setSwitchCorner(static_cast(TopLeft), v); + onChange(); + }); + connect(m_pCheckBoxCornerTopRight, &QCheckBox::stateChanged, this, [this](const int &v) { + serverConfig().setSwitchCorner(static_cast(TopRight), v); + onChange(); + }); + connect(m_pCheckBoxCornerBottomLeft, &QCheckBox::stateChanged, this, [this](const int &v) { + serverConfig().setSwitchCorner(static_cast(BottomLeft), v); + onChange(); + }); + connect(m_pCheckBoxCornerBottomRight, &QCheckBox::stateChanged, this, [this](const int &v) { + serverConfig().setSwitchCorner(static_cast(BottomRight), v); + onChange(); + }); // config - connect( - m_pCheckBoxUseExternalConfig, &QCheckBox::stateChanged, this, - [this](const int &v) { - serverConfig().setUseExternalConfig(v); - onChange(); - }); + connect(m_pCheckBoxUseExternalConfig, &QCheckBox::stateChanged, this, [this](const int &v) { + serverConfig().setUseExternalConfig(v); + onChange(); + }); #else - connect( - m_pCheckBoxSwitchDelay, &QCheckBox::checkStateChanged, this, - [this](const Qt::CheckState &v) { - serverConfig().haveSwitchDelay(v == Qt::Checked); - onChange(); - }); - connect( - m_pCheckBoxSwitchDoubleTap, &QCheckBox::checkStateChanged, this, - [this](const Qt::CheckState &v) { - serverConfig().haveSwitchDoubleTap(v == Qt::Checked); - onChange(); - }); - connect( - m_pCheckBoxEnableClipboard, &QCheckBox::checkStateChanged, this, - [this](const Qt::CheckState &v) { - serverConfig().setClipboardSharing(v == Qt::Checked); - onChange(); - }); - connect( - m_pCheckBoxHeartbeat, &QCheckBox::checkStateChanged, this, - [this](const Qt::CheckState &v) { - serverConfig().haveHeartbeat(v == Qt::Checked); - onChange(); - }); - connect( - m_pCheckBoxRelativeMouseMoves, &QCheckBox::checkStateChanged, this, - [this](const Qt::CheckState &v) { - serverConfig().setRelativeMouseMoves(v == Qt::Checked); - onChange(); - }); - connect( - m_pCheckBoxWin32KeepForeground, &QCheckBox::checkStateChanged, this, - [this](const Qt::CheckState &v) { - serverConfig().setWin32KeepForeground(v == Qt::Checked); - onChange(); - }); - connect( - m_pCheckBoxDisableLockToScreen, &QCheckBox::checkStateChanged, this, - [this](const Qt::CheckState &v) { - serverConfig().setDisableLockToScreen(v == Qt::Checked); - onChange(); - }); - connect( - m_pCheckBoxCornerTopLeft, &QCheckBox::checkStateChanged, this, - [this](const Qt::CheckState &v) { - serverConfig().setSwitchCorner( - static_cast(TopLeft), v == Qt::Checked); - onChange(); - }); - connect( - m_pCheckBoxCornerTopRight, &QCheckBox::checkStateChanged, this, - [this](const Qt::CheckState &v) { - serverConfig().setSwitchCorner( - static_cast(TopRight), v == Qt::Checked); - onChange(); - }); - connect( - m_pCheckBoxCornerBottomLeft, &QCheckBox::checkStateChanged, this, - [this](const Qt::CheckState &v) { - serverConfig().setSwitchCorner( - static_cast(BottomLeft), v == Qt::Checked); - onChange(); - }); - connect( - m_pCheckBoxCornerBottomRight, &QCheckBox::checkStateChanged, this, - [this](const Qt::CheckState &v) { - serverConfig().setSwitchCorner( - static_cast(BottomRight), v == Qt::Checked); - onChange(); - }); + connect(m_pCheckBoxSwitchDelay, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) { + serverConfig().haveSwitchDelay(v == Qt::Checked); + onChange(); + }); + connect(m_pCheckBoxSwitchDoubleTap, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) { + serverConfig().haveSwitchDoubleTap(v == Qt::Checked); + onChange(); + }); + connect(m_pCheckBoxEnableClipboard, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) { + serverConfig().setClipboardSharing(v == Qt::Checked); + onChange(); + }); + connect(m_pCheckBoxHeartbeat, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) { + serverConfig().haveHeartbeat(v == Qt::Checked); + onChange(); + }); + connect(m_pCheckBoxRelativeMouseMoves, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) { + serverConfig().setRelativeMouseMoves(v == Qt::Checked); + onChange(); + }); + connect(m_pCheckBoxWin32KeepForeground, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) { + serverConfig().setWin32KeepForeground(v == Qt::Checked); + onChange(); + }); + connect(m_pCheckBoxDisableLockToScreen, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) { + serverConfig().setDisableLockToScreen(v == Qt::Checked); + onChange(); + }); + connect(m_pCheckBoxCornerTopLeft, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) { + serverConfig().setSwitchCorner(static_cast(TopLeft), v == Qt::Checked); + onChange(); + }); + connect(m_pCheckBoxCornerTopRight, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) { + serverConfig().setSwitchCorner(static_cast(TopRight), v == Qt::Checked); + onChange(); + }); + connect(m_pCheckBoxCornerBottomLeft, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) { + serverConfig().setSwitchCorner(static_cast(BottomLeft), v == Qt::Checked); + onChange(); + }); + connect(m_pCheckBoxCornerBottomRight, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) { + serverConfig().setSwitchCorner(static_cast(BottomRight), v == Qt::Checked); + onChange(); + }); // config - connect( - m_pCheckBoxUseExternalConfig, &QCheckBox::checkStateChanged, this, - [this](const Qt::CheckState &v) { - serverConfig().setUseExternalConfig(v == Qt::Checked); - onChange(); - }); + connect(m_pCheckBoxUseExternalConfig, &QCheckBox::checkStateChanged, this, [this](const Qt::CheckState &v) { + serverConfig().setUseExternalConfig(v == Qt::Checked); + onChange(); + }); #endif connect( - m_pSpinBoxSwitchDelay, - static_cast(&QSpinBox::valueChanged), this, + m_pSpinBoxSwitchDelay, static_cast(&QSpinBox::valueChanged), this, [this](const int &v) { serverConfig().setSwitchDelay(v); onChange(); - }); + } + ); connect( - m_pSpinBoxSwitchDoubleTap, - static_cast(&QSpinBox::valueChanged), this, + m_pSpinBoxSwitchDoubleTap, static_cast(&QSpinBox::valueChanged), this, [this](const int &v) { serverConfig().setSwitchDoubleTap(v); onChange(); - }); + } + ); connect( - m_pSpinBoxClipboardSizeLimit, - static_cast(&QSpinBox::valueChanged), this, + m_pSpinBoxClipboardSizeLimit, static_cast(&QSpinBox::valueChanged), this, [this](const int &v) { serverConfig().setClipboardSharingSize(v * 1024); onChange(); - }); + } + ); connect( - m_pSpinBoxHeartbeat, - static_cast(&QSpinBox::valueChanged), this, + m_pSpinBoxHeartbeat, static_cast(&QSpinBox::valueChanged), this, [this](const int &v) { serverConfig().setHeartbeat(v); onChange(); - }); + } + ); connect( - m_pSpinBoxSwitchCornerSize, - static_cast(&QSpinBox::valueChanged), this, + m_pSpinBoxSwitchCornerSize, static_cast(&QSpinBox::valueChanged), this, [this](const int &v) { serverConfig().setSwitchCornerSize(v); onChange(); - }); + } + ); connect(m_pEditConfigFile, &QLineEdit::textChanged, this, [this]() { serverConfig().setConfigFile(m_pEditConfigFile->text()); @@ -314,11 +245,13 @@ ServerConfigDialog::ServerConfigDialog( }); } -bool ServerConfigDialog::addClient(const QString &clientName) { +bool ServerConfigDialog::addClient(const QString &clientName) +{ return addComputer(clientName, true); } -void ServerConfigDialog::showEvent(QShowEvent *event) { +void ServerConfigDialog::showEvent(QShowEvent *event) +{ QDialog::show(); if (!m_Message.isEmpty()) { @@ -327,16 +260,15 @@ void ServerConfigDialog::showEvent(QShowEvent *event) { } } -void ServerConfigDialog::accept() { - if (m_pCheckBoxUseExternalConfig->isChecked() && - !QFile::exists(m_pEditConfigFile->text())) { +void ServerConfigDialog::accept() +{ + if (m_pCheckBoxUseExternalConfig->isChecked() && !QFile::exists(m_pEditConfigFile->text())) { auto selectedButton = QMessageBox::warning( - this, "Filename invalid", "Please select a valid configuration file.", - QMessageBox::Ok | QMessageBox::Ignore); + this, "Filename invalid", "Please select a valid configuration file.", QMessageBox::Ok | QMessageBox::Ignore + ); - if (selectedButton != QMessageBox::Ok || - !on_m_pButtonBrowseConfigFile_clicked()) { + if (selectedButton != QMessageBox::Ok || !on_m_pButtonBrowseConfigFile_clicked()) { return; } } @@ -348,14 +280,16 @@ void ServerConfigDialog::accept() { QDialog::accept(); } -void ServerConfigDialog::reject() { +void ServerConfigDialog::reject() +{ serverConfig().setUseExternalConfig(m_OriginalServerConfigIsExternal); serverConfig().setConfigFile(m_OriginalServerConfigUsesExternalFile); QDialog::reject(); } -void ServerConfigDialog::on_m_pButtonNewHotkey_clicked() { +void ServerConfigDialog::on_m_pButtonNewHotkey_clicked() +{ Hotkey hotkey; HotkeyDialog dlg(this, hotkey); if (dlg.exec() == QDialog::Accepted) { @@ -365,7 +299,8 @@ void ServerConfigDialog::on_m_pButtonNewHotkey_clicked() { } } -void ServerConfigDialog::on_m_pButtonEditHotkey_clicked() { +void ServerConfigDialog::on_m_pButtonEditHotkey_clicked() +{ int idx = m_pListHotkeys->currentRow(); Q_ASSERT(idx >= 0 && idx < serverConfig().hotkeys().size()); Hotkey &hotkey = serverConfig().hotkeys()[idx]; @@ -376,7 +311,8 @@ void ServerConfigDialog::on_m_pButtonEditHotkey_clicked() { } } -void ServerConfigDialog::on_m_pButtonRemoveHotkey_clicked() { +void ServerConfigDialog::on_m_pButtonRemoveHotkey_clicked() +{ int idx = m_pListHotkeys->currentRow(); Q_ASSERT(idx >= 0 && idx < serverConfig().hotkeys().size()); serverConfig().hotkeys().removeAt(idx); @@ -385,7 +321,8 @@ void ServerConfigDialog::on_m_pButtonRemoveHotkey_clicked() { onChange(); } -void ServerConfigDialog::on_m_pListHotkeys_itemSelectionChanged() { +void ServerConfigDialog::on_m_pListHotkeys_itemSelectionChanged() +{ bool itemsSelected = !m_pListHotkeys->selectedItems().isEmpty(); m_pButtonEditHotkey->setEnabled(itemsSelected); m_pButtonRemoveHotkey->setEnabled(itemsSelected); @@ -413,7 +350,8 @@ void ServerConfigDialog::on_m_pListHotkeys_itemSelectionChanged() { } } -void ServerConfigDialog::on_m_pButtonNewAction_clicked() { +void ServerConfigDialog::on_m_pButtonNewAction_clicked() +{ int idx = m_pListHotkeys->currentRow(); Q_ASSERT(idx >= 0 && idx < serverConfig().hotkeys().size()); Hotkey &hotkey = serverConfig().hotkeys()[idx]; @@ -427,7 +365,8 @@ void ServerConfigDialog::on_m_pButtonNewAction_clicked() { } } -void ServerConfigDialog::on_m_pButtonEditAction_clicked() { +void ServerConfigDialog::on_m_pButtonEditAction_clicked() +{ int idxHotkey = m_pListHotkeys->currentRow(); Q_ASSERT(idxHotkey >= 0 && idxHotkey < serverConfig().hotkeys().size()); Hotkey &hotkey = serverConfig().hotkeys()[idxHotkey]; @@ -443,7 +382,8 @@ void ServerConfigDialog::on_m_pButtonEditAction_clicked() { } } -void ServerConfigDialog::on_m_pButtonRemoveAction_clicked() { +void ServerConfigDialog::on_m_pButtonRemoveAction_clicked() +{ int idxHotkey = m_pListHotkeys->currentRow(); Q_ASSERT(idxHotkey >= 0 && idxHotkey < serverConfig().hotkeys().size()); Hotkey &hotkey = serverConfig().hotkeys()[idxHotkey]; @@ -456,31 +396,34 @@ void ServerConfigDialog::on_m_pButtonRemoveAction_clicked() { onChange(); } -void ServerConfigDialog::on_m_pCheckBoxEnableClipboard_stateChanged( - int const state) { +void ServerConfigDialog::on_m_pCheckBoxEnableClipboard_stateChanged(int const state) +{ m_pSpinBoxClipboardSizeLimit->setEnabled(state == Qt::Checked); if ((state == Qt::Checked) && (!m_pSpinBoxClipboardSizeLimit->value())) { - int size = static_cast( - (serverConfig().defaultClipboardSharingSize() + 512) / 1024); + int size = static_cast((serverConfig().defaultClipboardSharingSize() + 512) / 1024); m_pSpinBoxClipboardSizeLimit->setValue(size ? size : 1); } } -void ServerConfigDialog::on_m_pListActions_itemSelectionChanged() { +void ServerConfigDialog::on_m_pListActions_itemSelectionChanged() +{ m_pButtonEditAction->setEnabled(!m_pListActions->selectedItems().isEmpty()); m_pButtonRemoveAction->setEnabled(!m_pListActions->selectedItems().isEmpty()); } -void ServerConfigDialog::on_m_pButtonAddComputer_clicked() { +void ServerConfigDialog::on_m_pButtonAddComputer_clicked() +{ addComputer("", false); } -void ServerConfigDialog::onScreenRemoved() { +void ServerConfigDialog::onScreenRemoved() +{ m_pButtonAddComputer->setEnabled(true); onChange(); } -void ServerConfigDialog::on_m_pCheckBoxUseExternalConfig_toggled(bool checked) { +void ServerConfigDialog::on_m_pCheckBoxUseExternalConfig_toggled(bool checked) +{ m_pLabelConfigFile->setEnabled(checked); m_pEditConfigFile->setEnabled(checked); m_pButtonBrowseConfigFile->setEnabled(checked); @@ -490,19 +433,15 @@ void ServerConfigDialog::on_m_pCheckBoxUseExternalConfig_toggled(bool checked) { m_pTabWidget->setTabEnabled(2, !checked); } -bool ServerConfigDialog::on_m_pButtonBrowseConfigFile_clicked() { +bool ServerConfigDialog::on_m_pButtonBrowseConfigFile_clicked() +{ #if defined(Q_OS_WIN) - const QString deskflowConfigFilter( - QString("%1 Configurations (*.sgc);;All files (*.*)") - .arg(DESKFLOW_APP_NAME)); + const QString deskflowConfigFilter(QString("%1 Configurations (*.sgc);;All files (*.*)").arg(DESKFLOW_APP_NAME)); #else - const QString deskflowConfigFilter( - QString("%1 Configurations (*.conf);;All files (*.*)") - .arg(DESKFLOW_APP_NAME)); + const QString deskflowConfigFilter(QString("%1 Configurations (*.conf);;All files (*.*)").arg(DESKFLOW_APP_NAME)); #endif - QString fileName = QFileDialog::getOpenFileName( - this, "Browse for a config file", "", deskflowConfigFilter); + QString fileName = QFileDialog::getOpenFileName(this, "Browse for a config file", "", deskflowConfigFilter); if (!fileName.isEmpty()) { m_pEditConfigFile->setText(fileName); @@ -512,7 +451,8 @@ bool ServerConfigDialog::on_m_pButtonBrowseConfigFile_clicked() { return false; } -bool ServerConfigDialog::addComputer(const QString &clientName, bool doSilent) { +bool ServerConfigDialog::addComputer(const QString &clientName, bool doSilent) +{ bool isAccepted = false; Screen newScreen(clientName); @@ -526,11 +466,10 @@ bool ServerConfigDialog::addComputer(const QString &clientName, bool doSilent) { return isAccepted; } -void ServerConfigDialog::onChange() { - bool isAppConfigDataEqual = - m_OriginalServerConfigIsExternal == serverConfig().useExternalConfig() && - m_OriginalServerConfigUsesExternalFile == serverConfig().configFile(); +void ServerConfigDialog::onChange() +{ + bool isAppConfigDataEqual = m_OriginalServerConfigIsExternal == serverConfig().useExternalConfig() && + m_OriginalServerConfigUsesExternalFile == serverConfig().configFile(); m_pButtonBox->button(QDialogButtonBox::Ok) - ->setEnabled( - !isAppConfigDataEqual || !(m_OriginalServerConfig == m_ServerConfig)); + ->setEnabled(!isAppConfigDataEqual || !(m_OriginalServerConfig == m_ServerConfig)); } diff --git a/src/gui/src/ServerConfigDialog.h b/src/gui/src/ServerConfigDialog.h index bf6d55a04..af195d69a 100644 --- a/src/gui/src/ServerConfigDialog.h +++ b/src/gui/src/ServerConfigDialog.h @@ -25,19 +25,22 @@ #include -class ServerConfigDialog : public QDialog, public Ui::ServerConfigDialogBase { +class ServerConfigDialog : public QDialog, public Ui::ServerConfigDialogBase +{ Q_OBJECT public: - ServerConfigDialog( - QWidget *parent, ServerConfig &config, AppConfig &appConfig); + ServerConfigDialog(QWidget *parent, ServerConfig &config, AppConfig &appConfig); bool addClient(const QString &clientName); public slots: void accept() override; void reject() override; void showEvent(QShowEvent *event) override; - void message(const QString &message) { m_Message = message; } + void message(const QString &message) + { + m_Message = message; + } protected slots: void on_m_pButtonNewHotkey_clicked(); @@ -57,12 +60,22 @@ protected slots: protected: bool addComputer(const QString &clientName, bool doSilent); - ServerConfig &serverConfig() { return m_ServerConfig; } - void setOriginalServerConfig(const ServerConfig &s) { + ServerConfig &serverConfig() + { + return m_ServerConfig; + } + void setOriginalServerConfig(const ServerConfig &s) + { m_OriginalServerConfig = s; } - ScreenSetupModel &model() { return m_ScreenSetupModel; } - AppConfig &appConfig() { return m_appConfig; } + ScreenSetupModel &model() + { + return m_ScreenSetupModel; + } + AppConfig &appConfig() + { + return m_appConfig; + } private: ServerConfig &m_OriginalServerConfig; diff --git a/src/gui/src/SetupWizard.cpp b/src/gui/src/SetupWizard.cpp index 6da725d53..03dbbf13e 100644 --- a/src/gui/src/SetupWizard.cpp +++ b/src/gui/src/SetupWizard.cpp @@ -23,7 +23,8 @@ using namespace deskflow::gui; -SetupWizard::SetupWizard(AppConfig &appConfig) : m_appConfig(appConfig) { +SetupWizard::SetupWizard(AppConfig &appConfig) : m_appConfig(appConfig) +{ setupUi(this); setWindowTitle(QString("Setup %1").arg(DESKFLOW_APP_NAME)); @@ -31,26 +32,28 @@ SetupWizard::SetupWizard(AppConfig &appConfig) : m_appConfig(appConfig) { m_pLabelError->setStyleSheet(kStyleErrorActiveLabel); m_pLineEditName->setText(appConfig.screenName()); - m_pLineEditName->setValidator(new validators::ScreenNameValidator( - m_pLineEditName, new validators::ValidationError(this, m_pLabelError))); + m_pLineEditName->setValidator( + new validators::ScreenNameValidator(m_pLineEditName, new validators::ValidationError(this, m_pLabelError)) + ); connect(m_pButtonApply, &QPushButton::clicked, this, &SetupWizard::accept); - connect( - m_pLineEditName, &QLineEdit::textChanged, this, - &SetupWizard::onLineEditNameChanged); + connect(m_pLineEditName, &QLineEdit::textChanged, this, &SetupWizard::onLineEditNameChanged); } -void SetupWizard::accept() { +void SetupWizard::accept() +{ m_appConfig.setWizardHasRun(); m_appConfig.setScreenName(m_pLineEditName->text()); QDialog::accept(); } -void SetupWizard::onLineEditNameChanged(const QString &error) { +void SetupWizard::onLineEditNameChanged(const QString &error) +{ m_pButtonApply->setEnabled(m_pLineEditName->hasAcceptableInput()); } -void SetupWizard::reject() { +void SetupWizard::reject() +{ QDialog::reject(); QApplication::exit(); } diff --git a/src/gui/src/SetupWizard.h b/src/gui/src/SetupWizard.h index 3fbc89f0a..30fdb666b 100644 --- a/src/gui/src/SetupWizard.h +++ b/src/gui/src/SetupWizard.h @@ -26,7 +26,8 @@ class MainWindow; -class SetupWizard : public QDialog, public Ui::SetupWizardBase { +class SetupWizard : public QDialog, public Ui::SetupWizardBase +{ Q_OBJECT public: diff --git a/src/gui/src/TrashScreenWidget.cpp b/src/gui/src/TrashScreenWidget.cpp index 7b9a277a7..a3ff49816 100644 --- a/src/gui/src/TrashScreenWidget.cpp +++ b/src/gui/src/TrashScreenWidget.cpp @@ -22,7 +22,8 @@ #include #include -void TrashScreenWidget::dragEnterEvent(QDragEnterEvent *event) { +void TrashScreenWidget::dragEnterEvent(QDragEnterEvent *event) +{ if (event->mimeData()->hasFormat(ScreenSetupModel::mimeType())) { event->setDropAction(Qt::MoveAction); event->accept(); @@ -30,7 +31,8 @@ void TrashScreenWidget::dragEnterEvent(QDragEnterEvent *event) { event->ignore(); } -void TrashScreenWidget::dropEvent(QDropEvent *event) { +void TrashScreenWidget::dropEvent(QDropEvent *event) +{ if (event->mimeData()->hasFormat(ScreenSetupModel::mimeType())) { event->acceptProposedAction(); emit screenRemoved(); diff --git a/src/gui/src/TrashScreenWidget.h b/src/gui/src/TrashScreenWidget.h index 29879a338..1f12f3320 100644 --- a/src/gui/src/TrashScreenWidget.h +++ b/src/gui/src/TrashScreenWidget.h @@ -23,11 +23,14 @@ class QWidget; class QDragEnterEvent; class QDropEvent; -class TrashScreenWidget : public QLabel { +class TrashScreenWidget : public QLabel +{ Q_OBJECT public: - TrashScreenWidget(QWidget *parent) : QLabel(parent) {} + TrashScreenWidget(QWidget *parent) : QLabel(parent) + { + } public: void dragEnterEvent(QDragEnterEvent *event); diff --git a/src/gui/src/main.cpp b/src/gui/src/main.cpp index 040846c7b..e610abe16 100644 --- a/src/gui/src/main.cpp +++ b/src/gui/src/main.cpp @@ -51,21 +51,26 @@ using namespace deskflow::gui; -class QThreadImpl : public QThread { +class QThreadImpl : public QThread +{ public: - static void msleep(unsigned long msecs) { QThread::msleep(msecs); } + static void msleep(unsigned long msecs) + { + QThread::msleep(msecs); + } }; #if defined(Q_OS_MAC) bool checkMacAssistiveDevices(); #endif -bool hasArg(const QString &arg, const QStringList &args) { - return std::ranges::any_of( - args, [&arg](const QString &a) { return a == arg; }); +bool hasArg(const QString &arg, const QStringList &args) +{ + return std::ranges::any_of(args, [&arg](const QString &a) { return a == arg; }); } -int main(int argc, char *argv[]) { +int main(int argc, char *argv[]) +{ #if defined(Q_OS_MAC) /* Workaround for QTBUG-40332 - "High ping when QNetworkAccessManager is @@ -95,7 +100,8 @@ int main(int argc, char *argv[]) { QMessageBox::information( NULL, DESKFLOW_APP_NAME, "Please drag " DESKFLOW_APP_NAME " to the Applications folder, " - "and open it from there."); + "and open it from there." + ); return 1; } @@ -109,8 +115,7 @@ int main(int argc, char *argv[]) { // --no-reset QStringList arguments = QCoreApplication::arguments(); const auto noReset = hasArg("--no-reset", arguments); - const auto resetEnvVar = - strToTrue(qEnvironmentVariable("DESKFLOW_RESET_ALL")); + const auto resetEnvVar = strToTrue(qEnvironmentVariable("DESKFLOW_RESET_ALL")); if (resetEnvVar && !noReset) { diagnostic::clearSettings(configScopes, false); } @@ -118,8 +123,8 @@ int main(int argc, char *argv[]) { AppConfig appConfig(configScopes); QObject::connect( - &configScopes, &ConfigScopes::saving, &appConfig, - [&appConfig]() { appConfig.commit(); }, Qt::DirectConnection); + &configScopes, &ConfigScopes::saving, &appConfig, [&appConfig]() { appConfig.commit(); }, Qt::DirectConnection + ); if (appConfig.wizardShouldRun()) { SetupWizard wizard(appConfig); @@ -134,9 +139,7 @@ int main(int argc, char *argv[]) { MainWindow mainWindow(configScopes, appConfig); - QObject::connect( - &app, &DeskflowApplication::aboutToQuit, &mainWindow, - &MainWindow::onAppAboutToQuit); + QObject::connect(&app, &DeskflowApplication::aboutToQuit, &mainWindow, &MainWindow::onAppAboutToQuit); mainWindow.open(); @@ -148,7 +151,8 @@ int main(int argc, char *argv[]) { } #if defined(Q_OS_MAC) -bool checkMacAssistiveDevices() { +bool checkMacAssistiveDevices() +{ #if __MAC_OS_X_VERSION_MIN_REQUIRED >= 1090 // mavericks // new in mavericks, applications are trusted individually @@ -163,8 +167,7 @@ bool checkMacAssistiveDevices() { const void *keys[] = {kAXTrustedCheckOptionPrompt}; const void *trueValue[] = {kCFBooleanTrue}; - CFDictionaryRef options = - CFDictionaryCreate(NULL, keys, trueValue, 1, NULL, NULL); + CFDictionaryRef options = CFDictionaryCreate(NULL, keys, trueValue, 1, NULL, NULL); bool result = AXIsProcessTrustedWithOptions(options); CFRelease(options); @@ -179,7 +182,8 @@ bool checkMacAssistiveDevices() { NULL, DESKFLOW_APP_NAME, "Please enable access to assistive devices " "System Preferences -> Security & Privacy -> " - "Privacy -> Accessibility, then re-open " DESKFLOW_APP_NAME "."); + "Privacy -> Accessibility, then re-open " DESKFLOW_APP_NAME "." + ); } return result; diff --git a/src/lib/arch/Arch.cpp b/src/lib/arch/Arch.cpp index 6100ad18a..dd5bbf149 100644 --- a/src/lib/arch/Arch.cpp +++ b/src/lib/arch/Arch.cpp @@ -28,20 +28,26 @@ Arch *Arch::s_instance = NULL; -Arch::Arch() { +Arch::Arch() +{ assert(s_instance == NULL); s_instance = this; } -Arch::Arch(Arch *arch) { s_instance = arch; } +Arch::Arch(Arch *arch) +{ + s_instance = arch; +} -Arch::~Arch() { +Arch::~Arch() +{ #if SYSAPI_WIN32 ArchMiscWindows::cleanup(); #endif } -void Arch::init() { +void Arch::init() +{ ARCH_NETWORK::init(); #if SYSAPI_WIN32 ARCH_TASKBAR::init(); @@ -49,7 +55,8 @@ void Arch::init() { #endif } -Arch *Arch::getInstance() { +Arch *Arch::getInstance() +{ assert(s_instance != NULL); return s_instance; } diff --git a/src/lib/arch/Arch.h b/src/lib/arch/Arch.h index 560b2113b..c0be36f03 100644 --- a/src/lib/arch/Arch.h +++ b/src/lib/arch/Arch.h @@ -96,7 +96,8 @@ class Arch : public ARCH_CONSOLE, public ARCH_STRING, public ARCH_SYSTEM, public ARCH_TASKBAR, - public ARCH_TIME { + public ARCH_TIME +{ public: Arch(); Arch(Arch *arch); @@ -120,19 +121,29 @@ public: */ static Arch *getInstance(); - static void setInstance(Arch *s) { s_instance = s; } + static void setInstance(Arch *s) + { + s_instance = s; + } private: static Arch *s_instance; }; //! Convenience object to lock/unlock an arch mutex -class ArchMutexLock { +class ArchMutexLock +{ public: - ArchMutexLock(ArchMutex mutex) : m_mutex(mutex) { ARCH->lockMutex(m_mutex); } + ArchMutexLock(ArchMutex mutex) : m_mutex(mutex) + { + ARCH->lockMutex(m_mutex); + } ArchMutexLock(ArchMutexLock const &) = delete; ArchMutexLock(ArchMutexLock &&) = delete; - ~ArchMutexLock() { ARCH->unlockMutex(m_mutex); } + ~ArchMutexLock() + { + ARCH->unlockMutex(m_mutex); + } ArchMutexLock &operator=(ArchMutexLock const &) = delete; ArchMutexLock &operator=(ArchMutexLock &&) = delete; diff --git a/src/lib/arch/ArchConsoleStd.cpp b/src/lib/arch/ArchConsoleStd.cpp index 1cf33fe24..47548ac71 100644 --- a/src/lib/arch/ArchConsoleStd.cpp +++ b/src/lib/arch/ArchConsoleStd.cpp @@ -21,7 +21,8 @@ #include -void ArchConsoleStd::writeConsole(ELevel level, const char *str) { +void ArchConsoleStd::writeConsole(ELevel level, const char *str) +{ if ((level >= kFATAL) && (level <= kWARNING)) std::cerr << str << std::endl; else diff --git a/src/lib/arch/ArchConsoleStd.h b/src/lib/arch/ArchConsoleStd.h index 5955611ee..929437391 100644 --- a/src/lib/arch/ArchConsoleStd.h +++ b/src/lib/arch/ArchConsoleStd.h @@ -21,14 +21,25 @@ #include "arch/IArchConsole.h" //! Cross platform implementation of IArchConsole -class ArchConsoleStd : public IArchConsole { +class ArchConsoleStd : public IArchConsole +{ public: - ArchConsoleStd() {} - virtual ~ArchConsoleStd() {} + ArchConsoleStd() + { + } + virtual ~ArchConsoleStd() + { + } // IArchConsole overrides - virtual void openConsole(const char *title) {} - virtual void closeConsole() {} - virtual void showConsole(bool) {} + virtual void openConsole(const char *title) + { + } + virtual void closeConsole() + { + } + virtual void showConsole(bool) + { + } virtual void writeConsole(ELevel level, const char *); }; diff --git a/src/lib/arch/ArchDaemonNone.cpp b/src/lib/arch/ArchDaemonNone.cpp index 601c90675..a5fa38194 100644 --- a/src/lib/arch/ArchDaemonNone.cpp +++ b/src/lib/arch/ArchDaemonNone.cpp @@ -22,35 +22,52 @@ // ArchDaemonNone // -ArchDaemonNone::ArchDaemonNone() { +ArchDaemonNone::ArchDaemonNone() +{ // do nothing } -ArchDaemonNone::~ArchDaemonNone() { +ArchDaemonNone::~ArchDaemonNone() +{ // do nothing } -void ArchDaemonNone::installDaemon( - const char *, const char *, const char *, const char *, const char *) { +void ArchDaemonNone::installDaemon(const char *, const char *, const char *, const char *, const char *) +{ // do nothing } -void ArchDaemonNone::uninstallDaemon(const char *) { +void ArchDaemonNone::uninstallDaemon(const char *) +{ // do nothing } -int ArchDaemonNone::daemonize(const char *name, DaemonFunc func) { +int ArchDaemonNone::daemonize(const char *name, DaemonFunc func) +{ // simply forward the call to func. obviously, this doesn't // do any daemonizing. return func(1, &name); } -bool ArchDaemonNone::canInstallDaemon(const char *) { return false; } +bool ArchDaemonNone::canInstallDaemon(const char *) +{ + return false; +} -bool ArchDaemonNone::isDaemonInstalled(const char *) { return false; } +bool ArchDaemonNone::isDaemonInstalled(const char *) +{ + return false; +} -void ArchDaemonNone::installDaemon() {} +void ArchDaemonNone::installDaemon() +{ +} -void ArchDaemonNone::uninstallDaemon() {} +void ArchDaemonNone::uninstallDaemon() +{ +} -std::string ArchDaemonNone::commandLine() const { return ""; } +std::string ArchDaemonNone::commandLine() const +{ + return ""; +} diff --git a/src/lib/arch/ArchDaemonNone.h b/src/lib/arch/ArchDaemonNone.h index 1d7658c08..b2ba752bb 100644 --- a/src/lib/arch/ArchDaemonNone.h +++ b/src/lib/arch/ArchDaemonNone.h @@ -29,15 +29,16 @@ daemons. The install and uninstall functions do nothing, the query functions return false, and \c daemonize() simply calls the passed function and returns its result. */ -class ArchDaemonNone : public IArchDaemon { +class ArchDaemonNone : public IArchDaemon +{ public: ArchDaemonNone(); virtual ~ArchDaemonNone(); // IArchDaemon overrides virtual void installDaemon( - const char *name, const char *description, const char *pathname, - const char *commandLine, const char *dependencies); + const char *name, const char *description, const char *pathname, const char *commandLine, const char *dependencies + ); virtual void uninstallDaemon(const char *name); virtual int daemonize(const char *name, DaemonFunc func); virtual bool canInstallDaemon(const char *name); diff --git a/src/lib/arch/IArchConsole.h b/src/lib/arch/IArchConsole.h index d552f77ca..9f29bcf2f 100644 --- a/src/lib/arch/IArchConsole.h +++ b/src/lib/arch/IArchConsole.h @@ -26,7 +26,8 @@ This interface defines the console operations required by deskflow. Each architecture must implement this interface. */ -class IArchConsole : public IInterface { +class IArchConsole : public IInterface +{ public: //! @name manipulators //@{ diff --git a/src/lib/arch/IArchDaemon.h b/src/lib/arch/IArchDaemon.h index 111038602..4c9ccf115 100644 --- a/src/lib/arch/IArchDaemon.h +++ b/src/lib/arch/IArchDaemon.h @@ -27,7 +27,8 @@ This interface defines the operations required by deskflow for installing uninstalling daeamons and daemonizing a process. Each architecture must implement this interface. */ -class IArchDaemon : public IInterface { +class IArchDaemon : public IInterface +{ public: typedef int (*DaemonFunc)(int argc, const char **argv); @@ -48,8 +49,8 @@ public: the listed daemons. Throws an \c XArchDaemon exception on failure. */ virtual void installDaemon( - const char *name, const char *description, const char *pathname, - const char *commandLine, const char *dependencies) = 0; + const char *name, const char *description, const char *pathname, const char *commandLine, const char *dependencies + ) = 0; //! Uninstall daemon /*! diff --git a/src/lib/arch/IArchFile.h b/src/lib/arch/IArchFile.h index 62d543dac..80f63651d 100644 --- a/src/lib/arch/IArchFile.h +++ b/src/lib/arch/IArchFile.h @@ -27,7 +27,8 @@ This interface defines the file system operations required by deskflow. Each architecture must implement this interface. */ -class IArchFile : public IInterface { +class IArchFile : public IInterface +{ public: //! @name manipulators //@{ @@ -85,8 +86,7 @@ public: is longer than allowed by the system; we'll rely on the system calls to tell us that. */ - virtual std::string - concatPath(const std::string &prefix, const std::string &suffix) = 0; + virtual std::string concatPath(const std::string &prefix, const std::string &suffix) = 0; //@} //! Set the user's profile directory diff --git a/src/lib/arch/IArchLog.h b/src/lib/arch/IArchLog.h index c35a5aa80..3f9c8cd82 100644 --- a/src/lib/arch/IArchLog.h +++ b/src/lib/arch/IArchLog.h @@ -26,7 +26,8 @@ This interface defines the logging operations required by deskflow. Each architecture must implement this interface. */ -class IArchLog : public IInterface { +class IArchLog : public IInterface +{ public: //! @name manipulators //@{ diff --git a/src/lib/arch/IArchMultithread.h b/src/lib/arch/IArchMultithread.h index d7f6a78e1..85b3f8ba0 100644 --- a/src/lib/arch/IArchMultithread.h +++ b/src/lib/arch/IArchMultithread.h @@ -68,7 +68,8 @@ typedef ArchThreadImpl *ArchThread; This interface defines the multithreading operations required by deskflow. Each architecture must implement this interface. */ -class IArchMultithread : public IInterface { +class IArchMultithread : public IInterface +{ public: //! Type of thread entry point typedef void *(*ThreadFunc)(void *); @@ -79,7 +80,8 @@ public: Not all platforms support all signals. Unsupported signals are ignored. */ - enum ESignal { + enum ESignal + { kINTERRUPT, //!< Interrupt (e.g. Ctrl+C) kTERMINATE, //!< Terminate (e.g. Ctrl+Break) kHANGUP, //!< Hangup (SIGHUP) diff --git a/src/lib/arch/IArchNetwork.h b/src/lib/arch/IArchNetwork.h index af53400f3..e7202b7ff 100644 --- a/src/lib/arch/IArchNetwork.h +++ b/src/lib/arch/IArchNetwork.h @@ -60,24 +60,31 @@ typedef ArchNetAddressImpl *ArchNetAddress; This interface defines the networking operations required by deskflow. Each architecture must implement this interface. */ -class IArchNetwork : public IInterface { +class IArchNetwork : public IInterface +{ public: //! Supported address families - enum EAddressFamily { + enum EAddressFamily + { kUNKNOWN, kINET, kINET6, }; //! Supported socket types - enum ESocketType { kDGRAM, kSTREAM }; + enum ESocketType + { + kDGRAM, + kSTREAM + }; //! Events for \c poll() /*! Events for \c poll() are bitmasks and can be combined using the bitwise operators. */ - enum { + enum + { kPOLLIN = 1, //!< Socket is readable kPOLLOUT = 2, //!< Socket is writable kPOLLERR = 4, //!< The socket is in an error state @@ -85,7 +92,8 @@ public: }; //! A socket query for \c poll() - class PollEntry { + class PollEntry + { public: //! The socket to query ArchSocket m_socket; diff --git a/src/lib/arch/IArchSleep.h b/src/lib/arch/IArchSleep.h index c3628770e..44cd40db0 100644 --- a/src/lib/arch/IArchSleep.h +++ b/src/lib/arch/IArchSleep.h @@ -25,7 +25,8 @@ This interface defines the sleep operations required by deskflow. Each architecture must implement this interface. */ -class IArchSleep : public IInterface { +class IArchSleep : public IInterface +{ public: //! @name manipulators //@{ diff --git a/src/lib/arch/IArchString.cpp b/src/lib/arch/IArchString.cpp index 8b8dab336..4af3bc05a 100644 --- a/src/lib/arch/IArchString.cpp +++ b/src/lib/arch/IArchString.cpp @@ -30,15 +30,16 @@ static ArchMutex s_mutex = NULL; // use C library non-reentrant multibyte conversion with mutex // -IArchString::~IArchString() { +IArchString::~IArchString() +{ if (s_mutex != NULL) { ARCH->closeMutex(s_mutex); s_mutex = NULL; } } -int IArchString::convStringWCToMB( - char *dst, const wchar_t *src, UInt32 n, bool *errors) { +int IArchString::convStringWCToMB(char *dst, const wchar_t *src, UInt32 n, bool *errors) +{ ptrdiff_t len = 0; bool dummyErrors; @@ -94,8 +95,8 @@ int IArchString::convStringWCToMB( return static_cast(len); } -int IArchString::convStringMBToWC( - wchar_t *dst, const char *src, UInt32 n, bool *errors) { +int IArchString::convStringMBToWC(wchar_t *dst, const char *src, UInt32 n, bool *errors) +{ ptrdiff_t len = 0; wchar_t dummy; diff --git a/src/lib/arch/IArchString.h b/src/lib/arch/IArchString.h index 02c6c56e2..2ebf6bcb9 100644 --- a/src/lib/arch/IArchString.h +++ b/src/lib/arch/IArchString.h @@ -28,7 +28,8 @@ This interface defines the string operations required by deskflow. Each architecture must implement this interface. */ -class IArchString : public IInterface { +class IArchString : public IInterface +{ public: IArchString() = default; IArchString(const IArchString &) = delete; @@ -42,7 +43,8 @@ public: /*! The known wide character encodings */ - enum EWideCharEncoding { + enum EWideCharEncoding + { kUCS2, //!< The UCS-2 encoding kUCS4, //!< The UCS-4 encoding kUTF16, //!< The UTF-16 encoding diff --git a/src/lib/arch/IArchSystem.h b/src/lib/arch/IArchSystem.h index 76d00f560..0a3696f6d 100644 --- a/src/lib/arch/IArchSystem.h +++ b/src/lib/arch/IArchSystem.h @@ -25,7 +25,8 @@ /*! This interface defines operations for querying system info. */ -class IArchSystem : public IInterface { +class IArchSystem : public IInterface +{ public: //! @name accessors //@{ @@ -54,7 +55,6 @@ public: /*! Writes a Deskflow setting from the system. */ - virtual void setting( - const std::string &valueName, const std::string &valueString) const = 0; + virtual void setting(const std::string &valueName, const std::string &valueString) const = 0; //@} }; diff --git a/src/lib/arch/IArchTaskBar.h b/src/lib/arch/IArchTaskBar.h index 26e72d9c4..73173b10f 100644 --- a/src/lib/arch/IArchTaskBar.h +++ b/src/lib/arch/IArchTaskBar.h @@ -28,7 +28,8 @@ This interface defines the task bar icon operations required by deskflow. Each architecture must implement this interface though each operation can be a no-op. */ -class IArchTaskBar : public IInterface { +class IArchTaskBar : public IInterface +{ public: //! @name manipulators //@{ diff --git a/src/lib/arch/IArchTaskBarReceiver.h b/src/lib/arch/IArchTaskBarReceiver.h index ad5242124..110b08507 100644 --- a/src/lib/arch/IArchTaskBarReceiver.h +++ b/src/lib/arch/IArchTaskBarReceiver.h @@ -30,7 +30,8 @@ This interface defines the task bar icon event handlers required by deskflow. Each architecture must implement this interface though each operation can be a no-op. */ -class IArchTaskBarReceiver : public IInterface { +class IArchTaskBarReceiver : public IInterface +{ public: // Icon data is architecture dependent typedef void *Icon; @@ -92,7 +93,9 @@ public: virtual void updateStatus(INode *, const String &errorMsg) = 0; - virtual void cleanup() {} + virtual void cleanup() + { + } //@} }; diff --git a/src/lib/arch/IArchTime.h b/src/lib/arch/IArchTime.h index f11432c03..1f57374ac 100644 --- a/src/lib/arch/IArchTime.h +++ b/src/lib/arch/IArchTime.h @@ -25,7 +25,8 @@ This interface defines the time operations required by deskflow. Each architecture must implement this interface. */ -class IArchTime : public IInterface { +class IArchTime : public IInterface +{ public: //! @name manipulators //@{ diff --git a/src/lib/arch/XArch.h b/src/lib/arch/XArch.h index b56ffb915..3ab91fad4 100644 --- a/src/lib/arch/XArch.h +++ b/src/lib/arch/XArch.h @@ -28,14 +28,18 @@ Exceptions derived from this class are used by the multithreading library to perform stack unwinding when a thread terminates. These exceptions must always be rethrown by clients when caught. */ -class XThread {}; +class XThread +{ +}; //! Thread exception to cancel /*! Thrown to cancel a thread. Clients must not throw this type, but must rethrow it if caught (by XThreadCancel, XThread, or ...). */ -class XThreadCancel : public XThread {}; +class XThreadCancel : public XThread +{ +}; /*! \def RETHROW_XTHREAD @@ -43,12 +47,12 @@ Convenience macro to rethrow an XThread exception but ignore other exceptions. Put this in your catch (...) handler after necessary cleanup but before leaving or returning from the handler. */ -#define RETHROW_XTHREAD \ - try { \ - throw; \ - } catch (XThread &) { \ - throw; \ - } catch (...) { \ +#define RETHROW_XTHREAD \ + try { \ + throw; \ + } catch (XThread &) { \ + throw; \ + } catch (...) { \ } //! Lazy error message string evaluation @@ -58,30 +62,46 @@ Platforms subclass this type, taking an appropriate error code type in the c'tor and overriding eval() to return the error string for that error code. */ -class XArchEval { +class XArchEval +{ public: - XArchEval() {} - virtual ~XArchEval() _NOEXCEPT {} + XArchEval() + { + } + virtual ~XArchEval() _NOEXCEPT + { + } virtual std::string eval() const = 0; }; //! Generic exception architecture dependent library -class XArch : public std::runtime_error { +class XArch : public std::runtime_error +{ public: - XArch(XArchEval *adopted) : std::runtime_error(adopted->eval()) { + XArch(XArchEval *adopted) : std::runtime_error(adopted->eval()) + { delete adopted; } - XArch(const std::string &msg) : std::runtime_error(msg) {} - virtual ~XArch() _NOEXCEPT {} + XArch(const std::string &msg) : std::runtime_error(msg) + { + } + virtual ~XArch() _NOEXCEPT + { + } }; // Macro to declare XArch derived types -#define XARCH_SUBCLASS(name_, super_) \ - class name_ : public super_ { \ - public: \ - name_(XArchEval *adoptedEvaluator) : super_(adoptedEvaluator) {} \ - name_(const std::string &msg) : super_(msg) {} \ +#define XARCH_SUBCLASS(name_, super_) \ + class name_ : public super_ \ + { \ + public: \ + name_(XArchEval *adoptedEvaluator) : super_(adoptedEvaluator) \ + { \ + } \ + name_(const std::string &msg) : super_(msg) \ + { \ + } \ } //! Generic network exception diff --git a/src/lib/arch/multibyte.h b/src/lib/arch/multibyte.h index 8bb5085e0..d662d5acf 100644 --- a/src/lib/arch/multibyte.h +++ b/src/lib/arch/multibyte.h @@ -37,12 +37,14 @@ // implementations. hopefully at least the C++ compiler has // a built-in wchar_t type. -static inline int mbtowc(wchar_t *dst, const char *src, int n) { +static inline int mbtowc(wchar_t *dst, const char *src, int n) +{ *dst = static_cast(*src); return 1; } -static inline int wctomb(char *dst, wchar_t src) { +static inline int wctomb(char *dst, wchar_t src) +{ *dst = static_cast(src); return 1; } diff --git a/src/lib/arch/unix/ArchConsoleUnix.cpp b/src/lib/arch/unix/ArchConsoleUnix.cpp index f2851abbe..312e1aeb3 100644 --- a/src/lib/arch/unix/ArchConsoleUnix.cpp +++ b/src/lib/arch/unix/ArchConsoleUnix.cpp @@ -18,6 +18,10 @@ #include "arch/unix/ArchConsoleUnix.h" -ArchConsoleUnix::ArchConsoleUnix() {} +ArchConsoleUnix::ArchConsoleUnix() +{ +} -ArchConsoleUnix::~ArchConsoleUnix() {} +ArchConsoleUnix::~ArchConsoleUnix() +{ +} diff --git a/src/lib/arch/unix/ArchConsoleUnix.h b/src/lib/arch/unix/ArchConsoleUnix.h index a39619c0f..be5326d22 100644 --- a/src/lib/arch/unix/ArchConsoleUnix.h +++ b/src/lib/arch/unix/ArchConsoleUnix.h @@ -22,7 +22,8 @@ #define ARCH_CONSOLE ArchConsoleUnix -class ArchConsoleUnix : public ArchConsoleStd { +class ArchConsoleUnix : public ArchConsoleStd +{ public: ArchConsoleUnix(); virtual ~ArchConsoleUnix(); diff --git a/src/lib/arch/unix/ArchDaemonUnix.cpp b/src/lib/arch/unix/ArchDaemonUnix.cpp index 84d15fae3..7e789a018 100644 --- a/src/lib/arch/unix/ArchDaemonUnix.cpp +++ b/src/lib/arch/unix/ArchDaemonUnix.cpp @@ -32,11 +32,13 @@ // ArchDaemonUnix // -ArchDaemonUnix::ArchDaemonUnix() { +ArchDaemonUnix::ArchDaemonUnix() +{ // do nothing } -ArchDaemonUnix::~ArchDaemonUnix() { +ArchDaemonUnix::~ArchDaemonUnix() +{ // do nothing } @@ -45,7 +47,8 @@ ArchDaemonUnix::~ArchDaemonUnix() { // In Mac OS X, fork()'d child processes can't use most APIs (the frameworks // that Deskflow uses in fact prevent it and make the process just up and die), // so need to exec a copy of the program that doesn't fork so isn't limited. -int execSelfNonDaemonized() { +int execSelfNonDaemonized() +{ extern char **NXArgv; char **selfArgv = NXArgv; @@ -55,11 +58,15 @@ int execSelfNonDaemonized() { return 0; } -bool alreadyDaemonized() { return getenv("_DESKFLOW_DAEMONIZED") != NULL; } +bool alreadyDaemonized() +{ + return getenv("_DESKFLOW_DAEMONIZED") != NULL; +} #endif -int ArchDaemonUnix::daemonize(const char *name, DaemonFunc func) { +int ArchDaemonUnix::daemonize(const char *name, DaemonFunc func) +{ #ifdef __APPLE__ if (alreadyDaemonized()) return func(1, &name); diff --git a/src/lib/arch/unix/ArchDaemonUnix.h b/src/lib/arch/unix/ArchDaemonUnix.h index bdcf36edc..171a56102 100644 --- a/src/lib/arch/unix/ArchDaemonUnix.h +++ b/src/lib/arch/unix/ArchDaemonUnix.h @@ -24,7 +24,8 @@ #define ARCH_DAEMON ArchDaemonUnix //! Unix implementation of IArchDaemon -class ArchDaemonUnix : public ArchDaemonNone { +class ArchDaemonUnix : public ArchDaemonNone +{ public: ArchDaemonUnix(); virtual ~ArchDaemonUnix(); diff --git a/src/lib/arch/unix/ArchFileUnix.cpp b/src/lib/arch/unix/ArchFileUnix.cpp index 1363ce8ba..652704229 100644 --- a/src/lib/arch/unix/ArchFileUnix.cpp +++ b/src/lib/arch/unix/ArchFileUnix.cpp @@ -29,15 +29,18 @@ // ArchFileUnix // -ArchFileUnix::ArchFileUnix() { +ArchFileUnix::ArchFileUnix() +{ // do nothing } -ArchFileUnix::~ArchFileUnix() { +ArchFileUnix::~ArchFileUnix() +{ // do nothing } -const char *ArchFileUnix::getBasename(const char *pathname) { +const char *ArchFileUnix::getBasename(const char *pathname) +{ if (pathname == NULL) { return NULL; } @@ -50,7 +53,8 @@ const char *ArchFileUnix::getBasename(const char *pathname) { } } -std::string ArchFileUnix::getUserDirectory() { +std::string ArchFileUnix::getUserDirectory() +{ char *buffer = NULL; std::string dir; #if HAVE_GETPWUID_R @@ -76,9 +80,13 @@ std::string ArchFileUnix::getUserDirectory() { return dir; } -std::string ArchFileUnix::getSystemDirectory() { return "/etc"; } +std::string ArchFileUnix::getSystemDirectory() +{ + return "/etc"; +} -std::string ArchFileUnix::getInstalledDirectory() { +std::string ArchFileUnix::getInstalledDirectory() +{ #if WINAPI_XWINDOWS return "/usr/bin"; #else @@ -86,9 +94,13 @@ std::string ArchFileUnix::getInstalledDirectory() { #endif } -std::string ArchFileUnix::getLogDirectory() { return "/var/log"; } +std::string ArchFileUnix::getLogDirectory() +{ + return "/var/log"; +} -std::string ArchFileUnix::getPluginDirectory() { +std::string ArchFileUnix::getPluginDirectory() +{ if (!m_pluginDirectory.empty()) { return m_pluginDirectory; } @@ -100,7 +112,8 @@ std::string ArchFileUnix::getPluginDirectory() { #endif } -std::string ArchFileUnix::getProfileDirectory() { +std::string ArchFileUnix::getProfileDirectory() +{ if (!m_profileDirectory.empty()) { return m_profileDirectory; } else { @@ -118,8 +131,8 @@ std::string ArchFileUnix::getProfileDirectory() { } } -std::string -ArchFileUnix::concatPath(const std::string &prefix, const std::string &suffix) { +std::string ArchFileUnix::concatPath(const std::string &prefix, const std::string &suffix) +{ std::string path; path.reserve(prefix.size() + 1 + suffix.size()); path += prefix; @@ -130,10 +143,12 @@ ArchFileUnix::concatPath(const std::string &prefix, const std::string &suffix) { return path; } -void ArchFileUnix::setProfileDirectory(const String &s) { +void ArchFileUnix::setProfileDirectory(const String &s) +{ m_profileDirectory = s; } -void ArchFileUnix::setPluginDirectory(const String &s) { +void ArchFileUnix::setPluginDirectory(const String &s) +{ m_pluginDirectory = s; } diff --git a/src/lib/arch/unix/ArchFileUnix.h b/src/lib/arch/unix/ArchFileUnix.h index 14744d43b..d30f5f846 100644 --- a/src/lib/arch/unix/ArchFileUnix.h +++ b/src/lib/arch/unix/ArchFileUnix.h @@ -23,7 +23,8 @@ #define ARCH_FILE ArchFileUnix //! Unix implementation of IArchFile -class ArchFileUnix : public IArchFile { +class ArchFileUnix : public IArchFile +{ public: ArchFileUnix(); virtual ~ArchFileUnix(); @@ -36,8 +37,7 @@ public: virtual std::string getLogDirectory(); virtual std::string getPluginDirectory(); virtual std::string getProfileDirectory(); - virtual std::string - concatPath(const std::string &prefix, const std::string &suffix); + virtual std::string concatPath(const std::string &prefix, const std::string &suffix); virtual void setProfileDirectory(const String &s); virtual void setPluginDirectory(const String &s); diff --git a/src/lib/arch/unix/ArchLogUnix.cpp b/src/lib/arch/unix/ArchLogUnix.cpp index b9aadf0aa..d3e34df8f 100644 --- a/src/lib/arch/unix/ArchLogUnix.cpp +++ b/src/lib/arch/unix/ArchLogUnix.cpp @@ -24,23 +24,33 @@ // ArchLogUnix // -ArchLogUnix::ArchLogUnix() { +ArchLogUnix::ArchLogUnix() +{ // do nothing } -ArchLogUnix::~ArchLogUnix() { +ArchLogUnix::~ArchLogUnix() +{ // do nothing } -void ArchLogUnix::openLog(const char *name) { openlog(name, 0, LOG_DAEMON); } +void ArchLogUnix::openLog(const char *name) +{ + openlog(name, 0, LOG_DAEMON); +} -void ArchLogUnix::closeLog() { closelog(); } +void ArchLogUnix::closeLog() +{ + closelog(); +} -void ArchLogUnix::showLog(bool) { +void ArchLogUnix::showLog(bool) +{ // do nothing } -void ArchLogUnix::writeLog(ELevel level, const char *msg) { +void ArchLogUnix::writeLog(ELevel level, const char *msg) +{ // convert level int priority; switch (level) { diff --git a/src/lib/arch/unix/ArchLogUnix.h b/src/lib/arch/unix/ArchLogUnix.h index 85f5cfe03..287a26355 100644 --- a/src/lib/arch/unix/ArchLogUnix.h +++ b/src/lib/arch/unix/ArchLogUnix.h @@ -23,7 +23,8 @@ #define ARCH_LOG ArchLogUnix //! Unix implementation of IArchLog -class ArchLogUnix : public IArchLog { +class ArchLogUnix : public IArchLog +{ public: ArchLogUnix(); virtual ~ArchLogUnix(); diff --git a/src/lib/arch/unix/ArchMultithreadPosix.cpp b/src/lib/arch/unix/ArchMultithreadPosix.cpp index d21900d1e..dd4899513 100644 --- a/src/lib/arch/unix/ArchMultithreadPosix.cpp +++ b/src/lib/arch/unix/ArchMultithreadPosix.cpp @@ -47,7 +47,8 @@ #define HAVE_POSIX_SIGWAIT 1 #endif -static void setSignalSet(sigset_t *sigset) { +static void setSignalSet(sigset_t *sigset) +{ sigemptyset(sigset); sigaddset(sigset, SIGHUP); sigaddset(sigset, SIGINT); @@ -59,7 +60,8 @@ static void setSignalSet(sigset_t *sigset) { // ArchThreadImpl // -class ArchThreadImpl { +class ArchThreadImpl +{ public: ArchThreadImpl(); @@ -85,7 +87,8 @@ ArchThreadImpl::ArchThreadImpl() m_cancelling(false), m_exited(false), m_result(NULL), - m_networkData(NULL) { + m_networkData(NULL) +{ // do nothing } @@ -95,9 +98,8 @@ ArchThreadImpl::ArchThreadImpl() ArchMultithreadPosix *ArchMultithreadPosix::s_instance = NULL; -ArchMultithreadPosix::ArchMultithreadPosix() - : m_newThreadCalled(false), - m_nextID(0) { +ArchMultithreadPosix::ArchMultithreadPosix() : m_newThreadCalled(false), m_nextID(0) +{ assert(s_instance == NULL); s_instance = this; @@ -143,30 +145,37 @@ ArchMultithreadPosix::ArchMultithreadPosix() pthread_sigmask(SIG_BLOCK, &sigset, NULL); } -ArchMultithreadPosix::~ArchMultithreadPosix() { +ArchMultithreadPosix::~ArchMultithreadPosix() +{ assert(s_instance != NULL); closeMutex(m_threadMutex); s_instance = NULL; } -void ArchMultithreadPosix::setNetworkDataForCurrentThread(void *data) { +void ArchMultithreadPosix::setNetworkDataForCurrentThread(void *data) +{ lockMutex(m_threadMutex); ArchThreadImpl *thread = find(pthread_self()); thread->m_networkData = data; unlockMutex(m_threadMutex); } -void *ArchMultithreadPosix::getNetworkDataForThread(ArchThread thread) { +void *ArchMultithreadPosix::getNetworkDataForThread(ArchThread thread) +{ lockMutex(m_threadMutex); void *data = thread->m_networkData; unlockMutex(m_threadMutex); return data; } -ArchMultithreadPosix *ArchMultithreadPosix::getInstance() { return s_instance; } +ArchMultithreadPosix *ArchMultithreadPosix::getInstance() +{ + return s_instance; +} -ArchCond ArchMultithreadPosix::newCondVar() { +ArchCond ArchMultithreadPosix::newCondVar() +{ ArchCondImpl *cond = new ArchCondImpl; int status = pthread_cond_init(&cond->m_cond, NULL); (void)status; @@ -174,27 +183,30 @@ ArchCond ArchMultithreadPosix::newCondVar() { return cond; } -void ArchMultithreadPosix::closeCondVar(ArchCond cond) { +void ArchMultithreadPosix::closeCondVar(ArchCond cond) +{ int status = pthread_cond_destroy(&cond->m_cond); (void)status; assert(status == 0); delete cond; } -void ArchMultithreadPosix::signalCondVar(ArchCond cond) { +void ArchMultithreadPosix::signalCondVar(ArchCond cond) +{ int status = pthread_cond_signal(&cond->m_cond); (void)status; assert(status == 0); } -void ArchMultithreadPosix::broadcastCondVar(ArchCond cond) { +void ArchMultithreadPosix::broadcastCondVar(ArchCond cond) +{ int status = pthread_cond_broadcast(&cond->m_cond); (void)status; assert(status == 0); } -bool ArchMultithreadPosix::waitCondVar( - ArchCond cond, ArchMutex mutex, double timeout) { +bool ArchMultithreadPosix::waitCondVar(ArchCond cond, ArchMutex mutex, double timeout) +{ // we can't wait on a condition variable and also wake it up for // cancellation since we don't use posix cancellation. so we // must wake up periodically to check for cancellation. we @@ -227,8 +239,7 @@ bool ArchMultithreadPosix::waitCondVar( } // wait - int status = - pthread_cond_timedwait(&cond->m_cond, &mutex->m_mutex, &finalTime); + int status = pthread_cond_timedwait(&cond->m_cond, &mutex->m_mutex, &finalTime); // check for cancel again testCancelThread(); @@ -247,7 +258,8 @@ bool ArchMultithreadPosix::waitCondVar( } } -ArchMutex ArchMultithreadPosix::newMutex() { +ArchMutex ArchMultithreadPosix::newMutex() +{ pthread_mutexattr_t attr; int status = pthread_mutexattr_init(&attr); assert(status == 0); @@ -257,14 +269,16 @@ ArchMutex ArchMultithreadPosix::newMutex() { return mutex; } -void ArchMultithreadPosix::closeMutex(ArchMutex mutex) { +void ArchMultithreadPosix::closeMutex(ArchMutex mutex) +{ int status = pthread_mutex_destroy(&mutex->m_mutex); (void)status; assert(status == 0); delete mutex; } -void ArchMultithreadPosix::lockMutex(ArchMutex mutex) { +void ArchMultithreadPosix::lockMutex(ArchMutex mutex) +{ int status = pthread_mutex_lock(&mutex->m_mutex); switch (status) { @@ -286,7 +300,8 @@ void ArchMultithreadPosix::lockMutex(ArchMutex mutex) { } } -void ArchMultithreadPosix::unlockMutex(ArchMutex mutex) { +void ArchMultithreadPosix::unlockMutex(ArchMutex mutex) +{ // TODO: S1-1767, we should use raii c++17 mutex instead of archaeic pthread // to solve possible lock order reversal. int status = pthread_mutex_unlock(&mutex->m_mutex); @@ -306,7 +321,8 @@ void ArchMultithreadPosix::unlockMutex(ArchMutex mutex) { } } -ArchThread ArchMultithreadPosix::newThread(ThreadFunc func, void *data) { +ArchThread ArchMultithreadPosix::newThread(ThreadFunc func, void *data) +{ assert(func != NULL); // initialize signal handler. we do this here instead of the @@ -335,8 +351,7 @@ ArchThread ArchMultithreadPosix::newThread(ThreadFunc func, void *data) { pthread_attr_t attr; int status = pthread_attr_init(&attr); if (status == 0) { - status = pthread_create( - &thread->m_thread, &attr, &ArchMultithreadPosix::threadFunc, thread); + status = pthread_create(&thread->m_thread, &attr, &ArchMultithreadPosix::threadFunc, thread); pthread_attr_destroy(&attr); } @@ -359,7 +374,8 @@ ArchThread ArchMultithreadPosix::newThread(ThreadFunc func, void *data) { return thread; } -ArchThread ArchMultithreadPosix::newCurrentThread() { +ArchThread ArchMultithreadPosix::newCurrentThread() +{ lockMutex(m_threadMutex); ArchThreadImpl *thread = find(pthread_self()); unlockMutex(m_threadMutex); @@ -367,7 +383,8 @@ ArchThread ArchMultithreadPosix::newCurrentThread() { return thread; } -void ArchMultithreadPosix::closeThread(ArchThread thread) { +void ArchMultithreadPosix::closeThread(ArchThread thread) +{ assert(thread != NULL); // decrement ref count and clean up thread if no more references @@ -388,12 +405,14 @@ void ArchMultithreadPosix::closeThread(ArchThread thread) { } } -ArchThread ArchMultithreadPosix::copyThread(ArchThread thread) { +ArchThread ArchMultithreadPosix::copyThread(ArchThread thread) +{ refThread(thread); return thread; } -void ArchMultithreadPosix::cancelThread(ArchThread thread) { +void ArchMultithreadPosix::cancelThread(ArchThread thread) +{ assert(thread != NULL); // set cancel and wakeup flags if thread can be cancelled @@ -411,13 +430,15 @@ void ArchMultithreadPosix::cancelThread(ArchThread thread) { } } -void ArchMultithreadPosix::setPriorityOfThread(ArchThread thread, int /*n*/) { +void ArchMultithreadPosix::setPriorityOfThread(ArchThread thread, int /*n*/) +{ assert(thread != NULL); // FIXME } -void ArchMultithreadPosix::testCancelThread() { +void ArchMultithreadPosix::testCancelThread() +{ // find current thread lockMutex(m_threadMutex); ArchThreadImpl *thread = findNoRef(pthread_self()); @@ -427,7 +448,8 @@ void ArchMultithreadPosix::testCancelThread() { testCancelThreadImpl(thread); } -bool ArchMultithreadPosix::wait(ArchThread target, double timeout) { +bool ArchMultithreadPosix::wait(ArchThread target, double timeout) +{ assert(target != NULL); lockMutex(m_threadMutex); @@ -480,39 +502,42 @@ bool ArchMultithreadPosix::wait(ArchThread target, double timeout) { } } -bool ArchMultithreadPosix::isSameThread( - ArchThread thread1, ArchThread thread2) { +bool ArchMultithreadPosix::isSameThread(ArchThread thread1, ArchThread thread2) +{ return (thread1 == thread2); } -bool ArchMultithreadPosix::isExitedThread(ArchThread thread) { +bool ArchMultithreadPosix::isExitedThread(ArchThread thread) +{ lockMutex(m_threadMutex); bool exited = thread->m_exited; unlockMutex(m_threadMutex); return exited; } -void *ArchMultithreadPosix::getResultOfThread(ArchThread thread) { +void *ArchMultithreadPosix::getResultOfThread(ArchThread thread) +{ lockMutex(m_threadMutex); void *result = thread->m_result; unlockMutex(m_threadMutex); return result; } -IArchMultithread::ThreadID -ArchMultithreadPosix::getIDOfThread(ArchThread thread) { +IArchMultithread::ThreadID ArchMultithreadPosix::getIDOfThread(ArchThread thread) +{ return thread->m_id; } -void ArchMultithreadPosix::setSignalHandler( - ESignal signal, SignalFunc func, void *userData) { +void ArchMultithreadPosix::setSignalHandler(ESignal signal, SignalFunc func, void *userData) +{ lockMutex(m_threadMutex); m_signalFunc[signal] = func; m_signalUserData[signal] = userData; unlockMutex(m_threadMutex); } -void ArchMultithreadPosix::raiseSignal(ESignal signal) { +void ArchMultithreadPosix::raiseSignal(ESignal signal) +{ lockMutex(m_threadMutex); if (m_signalFunc[signal] != NULL) { m_signalFunc[signal](signal, m_signalUserData[signal]); @@ -523,7 +548,8 @@ void ArchMultithreadPosix::raiseSignal(ESignal signal) { unlockMutex(m_threadMutex); } -void ArchMultithreadPosix::startSignalHandler() { +void ArchMultithreadPosix::startSignalHandler() +{ // set signal mask. the main thread blocks these signals and // the signal handler thread will listen for them. sigset_t sigset, oldsigset; @@ -537,9 +563,7 @@ void ArchMultithreadPosix::startSignalHandler() { pthread_attr_t attr; int status = pthread_attr_init(&attr); if (status == 0) { - status = pthread_create( - &m_signalThread, &attr, &ArchMultithreadPosix::threadSignalHandler, - NULL); + status = pthread_create(&m_signalThread, &attr, &ArchMultithreadPosix::threadSignalHandler, NULL); pthread_attr_destroy(&attr); } if (status != 0) { @@ -549,7 +573,8 @@ void ArchMultithreadPosix::startSignalHandler() { } } -ArchThreadImpl *ArchMultithreadPosix::find(pthread_t thread) { +ArchThreadImpl *ArchMultithreadPosix::find(pthread_t thread) +{ ArchThreadImpl *impl = findNoRef(thread); if (impl != NULL) { refThread(impl); @@ -557,10 +582,10 @@ ArchThreadImpl *ArchMultithreadPosix::find(pthread_t thread) { return impl; } -ArchThreadImpl *ArchMultithreadPosix::findNoRef(pthread_t thread) { +ArchThreadImpl *ArchMultithreadPosix::findNoRef(pthread_t thread) +{ // linear search - for (ThreadList::const_iterator index = m_threadList.begin(); - index != m_threadList.end(); ++index) { + for (ThreadList::const_iterator index = m_threadList.begin(); index != m_threadList.end(); ++index) { if ((*index)->m_thread == thread) { return *index; } @@ -568,7 +593,8 @@ ArchThreadImpl *ArchMultithreadPosix::findNoRef(pthread_t thread) { return NULL; } -void ArchMultithreadPosix::insert(ArchThreadImpl *thread) { +void ArchMultithreadPosix::insert(ArchThreadImpl *thread) +{ assert(thread != NULL); // thread shouldn't already be on the list @@ -584,9 +610,9 @@ void ArchMultithreadPosix::insert(ArchThreadImpl *thread) { m_threadList.push_back(thread); } -void ArchMultithreadPosix::erase(ArchThreadImpl *thread) { - for (ThreadList::iterator index = m_threadList.begin(); - index != m_threadList.end(); ++index) { +void ArchMultithreadPosix::erase(ArchThreadImpl *thread) +{ + for (ThreadList::iterator index = m_threadList.begin(); index != m_threadList.end(); ++index) { if (*index == thread) { m_threadList.erase(index); break; @@ -594,13 +620,15 @@ void ArchMultithreadPosix::erase(ArchThreadImpl *thread) { } } -void ArchMultithreadPosix::refThread(ArchThreadImpl *thread) { +void ArchMultithreadPosix::refThread(ArchThreadImpl *thread) +{ assert(thread != NULL); assert(findNoRef(thread->m_thread) != NULL); ++thread->m_refCount; } -void ArchMultithreadPosix::testCancelThreadImpl(ArchThreadImpl *thread) { +void ArchMultithreadPosix::testCancelThreadImpl(ArchThreadImpl *thread) +{ assert(thread != NULL); // update cancel state @@ -619,7 +647,8 @@ void ArchMultithreadPosix::testCancelThreadImpl(ArchThreadImpl *thread) { } } -void *ArchMultithreadPosix::threadFunc(void *vrep) { +void *ArchMultithreadPosix::threadFunc(void *vrep) +{ // get the thread ArchThreadImpl *thread = static_cast(vrep); @@ -634,7 +663,8 @@ void *ArchMultithreadPosix::threadFunc(void *vrep) { return NULL; } -void ArchMultithreadPosix::doThreadFunc(ArchThread thread) { +void ArchMultithreadPosix::doThreadFunc(ArchThread thread) +{ // default priority is slightly below normal setPriorityOfThread(thread, 1); @@ -671,11 +701,13 @@ void ArchMultithreadPosix::doThreadFunc(ArchThread thread) { closeThread(thread); } -void ArchMultithreadPosix::threadCancel(int) { +void ArchMultithreadPosix::threadCancel(int) +{ // do nothing } -void *ArchMultithreadPosix::threadSignalHandler(void *) { +void *ArchMultithreadPosix::threadSignalHandler(void *) +{ // detach pthread_detach(pthread_self()); diff --git a/src/lib/arch/unix/ArchMultithreadPosix.h b/src/lib/arch/unix/ArchMultithreadPosix.h index 0b230dc4a..5991b457b 100644 --- a/src/lib/arch/unix/ArchMultithreadPosix.h +++ b/src/lib/arch/unix/ArchMultithreadPosix.h @@ -25,18 +25,21 @@ #define ARCH_MULTITHREAD ArchMultithreadPosix -class ArchCondImpl { +class ArchCondImpl +{ public: pthread_cond_t m_cond; }; -class ArchMutexImpl { +class ArchMutexImpl +{ public: pthread_mutex_t m_mutex; }; //! Posix implementation of IArchMultithread -class ArchMultithreadPosix : public IArchMultithread { +class ArchMultithreadPosix : public IArchMultithread +{ public: ArchMultithreadPosix(); ArchMultithreadPosix(ArchMultithreadPosix const &) = delete; diff --git a/src/lib/arch/unix/ArchNetworkBSD.cpp b/src/lib/arch/unix/ArchNetworkBSD.cpp index 504627b92..e256f4e37 100644 --- a/src/lib/arch/unix/ArchNetworkBSD.cpp +++ b/src/lib/arch/unix/ArchNetworkBSD.cpp @@ -52,7 +52,8 @@ static const int s_type[] = {SOCK_DGRAM, SOCK_STREAM}; #if !HAVE_INET_ATON // parse dotted quad addresses. we don't bother with the weird BSD'ism // of handling octal and hex and partial forms. -static in_addr_t inet_aton(const char *cp, struct in_addr *inp) { +static in_addr_t inet_aton(const char *cp, struct in_addr *inp) +{ unsigned int a, b, c, d; if (sscanf(cp, "%u.%u.%u.%u", &a, &b, &c, &d) != 4) { return 0; @@ -73,44 +74,53 @@ static in_addr_t inet_aton(const char *cp, struct in_addr *inp) { // ArchNetworkBSD::Deps // -void ArchNetworkBSD::Deps::sleep(double seconds) { +void ArchNetworkBSD::Deps::sleep(double seconds) +{ // ARCH->sleep(seconds); } -int ArchNetworkBSD::Deps::poll(struct pollfd *fds, nfds_t nfds, int timeout) { +int ArchNetworkBSD::Deps::poll(struct pollfd *fds, nfds_t nfds, int timeout) +{ return ::poll(fds, nfds, timeout); } -std::shared_ptr ArchNetworkBSD::Deps::makePollFD(nfds_t n) { +std::shared_ptr ArchNetworkBSD::Deps::makePollFD(nfds_t n) +{ // C++20 supports std::make_shared(n) but this is not // implemented on the compiler that comes with Ubuntu 22 and a few other // distros, so use the manual new and delete until we drop those distros. - return std::shared_ptr( - new struct pollfd[n], std::default_delete()); + return std::shared_ptr(new struct pollfd[n], std::default_delete()); } -ssize_t ArchNetworkBSD::Deps::read(int fd, void *buf, size_t len) { +ssize_t ArchNetworkBSD::Deps::read(int fd, void *buf, size_t len) +{ return ::read(fd, buf, len); } -void ArchNetworkBSD::Deps::testCancelThread() { ARCH->testCancelThread(); } +void ArchNetworkBSD::Deps::testCancelThread() +{ + ARCH->testCancelThread(); +} // // ArchNetworkBSD // -ArchNetworkBSD::~ArchNetworkBSD() { +ArchNetworkBSD::~ArchNetworkBSD() +{ if (m_mutex) ARCH->closeMutex(m_mutex); } -void ArchNetworkBSD::init() { +void ArchNetworkBSD::init() +{ // create mutex to make some calls thread safe m_mutex = ARCH->newMutex(); } -ArchSocket ArchNetworkBSD::newSocket(EAddressFamily family, ESocketType type) { +ArchSocket ArchNetworkBSD::newSocket(EAddressFamily family, ESocketType type) +{ // create socket int fd = socket(s_family[family], s_type[type], 0); if (fd == -1) { @@ -130,7 +140,8 @@ ArchSocket ArchNetworkBSD::newSocket(EAddressFamily family, ESocketType type) { return newSocket; } -ArchSocket ArchNetworkBSD::copySocket(ArchSocket s) { +ArchSocket ArchNetworkBSD::copySocket(ArchSocket s) +{ assert(s != NULL); // ref the socket and return it @@ -140,7 +151,8 @@ ArchSocket ArchNetworkBSD::copySocket(ArchSocket s) { return s; } -void ArchNetworkBSD::closeSocket(ArchSocket s) { +void ArchNetworkBSD::closeSocket(ArchSocket s) +{ assert(s != NULL); // unref the socket and note if it should be released @@ -162,7 +174,8 @@ void ArchNetworkBSD::closeSocket(ArchSocket s) { } } -void ArchNetworkBSD::closeSocketForRead(ArchSocket s) { +void ArchNetworkBSD::closeSocketForRead(ArchSocket s) +{ assert(s != NULL); if (shutdown(s->m_fd, 0) == -1) { @@ -172,7 +185,8 @@ void ArchNetworkBSD::closeSocketForRead(ArchSocket s) { } } -void ArchNetworkBSD::closeSocketForWrite(ArchSocket s) { +void ArchNetworkBSD::closeSocketForWrite(ArchSocket s) +{ assert(s != NULL); if (shutdown(s->m_fd, 1) == -1) { @@ -182,7 +196,8 @@ void ArchNetworkBSD::closeSocketForWrite(ArchSocket s) { } } -void ArchNetworkBSD::bindSocket(ArchSocket s, ArchNetAddress addr) { +void ArchNetworkBSD::bindSocket(ArchSocket s, ArchNetAddress addr) +{ assert(s != NULL); assert(addr != NULL); @@ -191,7 +206,8 @@ void ArchNetworkBSD::bindSocket(ArchSocket s, ArchNetAddress addr) { } } -void ArchNetworkBSD::listenOnSocket(ArchSocket s) { +void ArchNetworkBSD::listenOnSocket(ArchSocket s) +{ assert(s != NULL); // hardcoding backlog @@ -200,7 +216,8 @@ void ArchNetworkBSD::listenOnSocket(ArchSocket s) { } } -ArchSocket ArchNetworkBSD::acceptSocket(ArchSocket s, ArchNetAddress *addr) { +ArchSocket ArchNetworkBSD::acceptSocket(ArchSocket s, ArchNetAddress *addr) +{ assert(s != NULL); // if user passed NULL in addr then use scratch space @@ -250,7 +267,8 @@ ArchSocket ArchNetworkBSD::acceptSocket(ArchSocket s, ArchNetAddress *addr) { return newSocket; } -bool ArchNetworkBSD::connectSocket(ArchSocket s, ArchNetAddress addr) { +bool ArchNetworkBSD::connectSocket(ArchSocket s, ArchNetAddress addr) +{ assert(s != NULL); assert(addr != NULL); @@ -266,7 +284,8 @@ bool ArchNetworkBSD::connectSocket(ArchSocket s, ArchNetAddress addr) { return true; } -int ArchNetworkBSD::pollSocket(PollEntry pe[], int num, double timeout) { +int ArchNetworkBSD::pollSocket(PollEntry pe[], int num, double timeout) +{ assert((pe != nullptr && num > 0) || num == 0); // return if nothing to do @@ -351,7 +370,8 @@ int ArchNetworkBSD::pollSocket(PollEntry pe[], int num, double timeout) { return n; } -void ArchNetworkBSD::unblockPollSocket(ArchThread thread) { +void ArchNetworkBSD::unblockPollSocket(ArchThread thread) +{ const int *unblockPipe = getUnblockPipeForThread(thread); if (unblockPipe != nullptr) { char dummy = 0; @@ -361,7 +381,8 @@ void ArchNetworkBSD::unblockPollSocket(ArchThread thread) { } } -size_t ArchNetworkBSD::readSocket(ArchSocket s, void *buf, size_t len) { +size_t ArchNetworkBSD::readSocket(ArchSocket s, void *buf, size_t len) +{ assert(s != NULL); ssize_t n = read(s->m_fd, buf, len); @@ -374,7 +395,8 @@ size_t ArchNetworkBSD::readSocket(ArchSocket s, void *buf, size_t len) { return n; } -size_t ArchNetworkBSD::writeSocket(ArchSocket s, const void *buf, size_t len) { +size_t ArchNetworkBSD::writeSocket(ArchSocket s, const void *buf, size_t len) +{ assert(s != NULL); ssize_t n = write(s->m_fd, buf, len); @@ -387,15 +409,14 @@ size_t ArchNetworkBSD::writeSocket(ArchSocket s, const void *buf, size_t len) { return n; } -void ArchNetworkBSD::throwErrorOnSocket(ArchSocket s) { +void ArchNetworkBSD::throwErrorOnSocket(ArchSocket s) +{ assert(s != NULL); // get the error from the socket layer int err = 0; auto size = static_cast(sizeof(err)); - if (getsockopt( - s->m_fd, SOL_SOCKET, SO_ERROR, reinterpret_cast(&err), - &size) == -1) { + if (getsockopt(s->m_fd, SOL_SOCKET, SO_ERROR, reinterpret_cast(&err), &size) == -1) { err = errno; } @@ -405,7 +426,8 @@ void ArchNetworkBSD::throwErrorOnSocket(ArchSocket s) { } } -void ArchNetworkBSD::setBlockingOnSocket(int fd, bool blocking) { +void ArchNetworkBSD::setBlockingOnSocket(int fd, bool blocking) +{ assert(fd != -1); int mode = fcntl(fd, F_GETFL, 0); @@ -422,53 +444,48 @@ void ArchNetworkBSD::setBlockingOnSocket(int fd, bool blocking) { } } -bool ArchNetworkBSD::setNoDelayOnSocket(ArchSocket s, bool noDelay) { +bool ArchNetworkBSD::setNoDelayOnSocket(ArchSocket s, bool noDelay) +{ assert(s != NULL); // get old state int oflag; auto size = static_cast(sizeof(oflag)); - if (getsockopt( - s->m_fd, IPPROTO_TCP, TCP_NODELAY, - reinterpret_cast(&oflag), &size) == -1) { + if (getsockopt(s->m_fd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&oflag), &size) == -1) { throwError(errno); } int flag = noDelay ? 1 : 0; size = static_cast(sizeof(flag)); - if (setsockopt( - s->m_fd, IPPROTO_TCP, TCP_NODELAY, - reinterpret_cast(&flag), size) == -1) { + if (setsockopt(s->m_fd, IPPROTO_TCP, TCP_NODELAY, reinterpret_cast(&flag), size) == -1) { throwError(errno); } return (oflag != 0); } -bool ArchNetworkBSD::setReuseAddrOnSocket(ArchSocket s, bool reuse) { +bool ArchNetworkBSD::setReuseAddrOnSocket(ArchSocket s, bool reuse) +{ assert(s != NULL); // get old state int oflag; auto size = static_cast(sizeof(oflag)); - if (getsockopt( - s->m_fd, SOL_SOCKET, SO_REUSEADDR, - reinterpret_cast(&oflag), &size) == -1) { + if (getsockopt(s->m_fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&oflag), &size) == -1) { throwError(errno); } int flag = reuse ? 1 : 0; size = static_cast(sizeof(flag)); - if (setsockopt( - s->m_fd, SOL_SOCKET, SO_REUSEADDR, - reinterpret_cast(&flag), size) == -1) { + if (setsockopt(s->m_fd, SOL_SOCKET, SO_REUSEADDR, reinterpret_cast(&flag), size) == -1) { throwError(errno); } return (oflag != 0); } -std::string ArchNetworkBSD::getHostName() { +std::string ArchNetworkBSD::getHostName() +{ char name[256]; if (gethostname(name, sizeof(name)) == -1) { name[0] = '\0'; @@ -478,7 +495,8 @@ std::string ArchNetworkBSD::getHostName() { return name; } -ArchNetAddress ArchNetworkBSD::newAnyAddr(EAddressFamily family) { +ArchNetAddress ArchNetworkBSD::newAnyAddr(EAddressFamily family) +{ // allocate address auto *addr = new ArchNetAddressImpl; @@ -509,15 +527,16 @@ ArchNetAddress ArchNetworkBSD::newAnyAddr(EAddressFamily family) { return addr; } -ArchNetAddress ArchNetworkBSD::copyAddr(ArchNetAddress addr) { +ArchNetAddress ArchNetworkBSD::copyAddr(ArchNetAddress addr) +{ assert(addr != NULL); // allocate and copy address return new ArchNetAddressImpl(*addr); } -std::vector -ArchNetworkBSD::nameToAddr(const std::string &name) { +std::vector ArchNetworkBSD::nameToAddr(const std::string &name) +{ struct addrinfo hints; struct in6_addr serveraddr; @@ -553,8 +572,7 @@ ArchNetworkBSD::nameToAddr(const std::string &name) { addresses.back()->m_len = (socklen_t)sizeof(struct sockaddr_in6); } - memcpy( - &addresses.back()->m_addr, address->ai_addr, addresses.back()->m_len); + memcpy(&addresses.back()->m_addr, address->ai_addr, addresses.back()->m_len); } freeaddrinfo(pResult); @@ -563,22 +581,23 @@ ArchNetworkBSD::nameToAddr(const std::string &name) { return addresses; } -void ArchNetworkBSD::closeAddr(ArchNetAddress addr) { +void ArchNetworkBSD::closeAddr(ArchNetAddress addr) +{ assert(addr != NULL); delete addr; } -std::string ArchNetworkBSD::addrToName(ArchNetAddress addr) { +std::string ArchNetworkBSD::addrToName(ArchNetAddress addr) +{ assert(addr != NULL); // mutexed name lookup (ugh) ARCH->lockMutex(m_mutex); char host[1024]; char service[20]; - int ret = getnameinfo( - TYPED_ADDR(struct sockaddr, addr), addr->m_len, host, sizeof(host), - service, sizeof(service), 0); + int ret = + getnameinfo(TYPED_ADDR(struct sockaddr, addr), addr->m_len, host, sizeof(host), service, sizeof(service), 0); if (ret != 0) { ARCH->unlockMutex(m_mutex); throwNameError(ret); @@ -593,7 +612,8 @@ std::string ArchNetworkBSD::addrToName(ArchNetAddress addr) { return name; } -std::string ArchNetworkBSD::addrToString(ArchNetAddress addr) { +std::string ArchNetworkBSD::addrToString(ArchNetAddress addr) +{ assert(addr != NULL); switch (getAddrFamily(addr)) { @@ -620,8 +640,8 @@ std::string ArchNetworkBSD::addrToString(ArchNetAddress addr) { } } -IArchNetwork::EAddressFamily -ArchNetworkBSD::getAddrFamily(ArchNetAddress addr) { +IArchNetwork::EAddressFamily ArchNetworkBSD::getAddrFamily(ArchNetAddress addr) +{ assert(addr != NULL); switch (addr->m_addr.ss_family) { @@ -635,7 +655,8 @@ ArchNetworkBSD::getAddrFamily(ArchNetAddress addr) { } } -void ArchNetworkBSD::setAddrPort(ArchNetAddress addr, int port) { +void ArchNetworkBSD::setAddrPort(ArchNetAddress addr, int port) +{ assert(addr != NULL); switch (getAddrFamily(addr)) { @@ -657,7 +678,8 @@ void ArchNetworkBSD::setAddrPort(ArchNetAddress addr, int port) { } } -int ArchNetworkBSD::getAddrPort(ArchNetAddress addr) { +int ArchNetworkBSD::getAddrPort(ArchNetAddress addr) +{ assert(addr != NULL); switch (getAddrFamily(addr)) { @@ -677,15 +699,14 @@ int ArchNetworkBSD::getAddrPort(ArchNetAddress addr) { } } -bool ArchNetworkBSD::isAnyAddr(ArchNetAddress addr) { +bool ArchNetworkBSD::isAnyAddr(ArchNetAddress addr) +{ assert(addr != NULL); switch (getAddrFamily(addr)) { case kINET: { auto *ipAddr = TYPED_ADDR(struct sockaddr_in, addr); - return ( - ipAddr->sin_addr.s_addr == INADDR_ANY && - addr->m_len == static_cast(sizeof(struct sockaddr_in))); + return (ipAddr->sin_addr.s_addr == INADDR_ANY && addr->m_len == static_cast(sizeof(struct sockaddr_in))); } case kINET6: { @@ -693,8 +714,9 @@ bool ArchNetworkBSD::isAnyAddr(ArchNetAddress addr) { return ( addr->m_len == (socklen_t)sizeof(struct sockaddr_in6) && memcmp( - static_cast(&ipAddr->sin6_addr), - static_cast(&in6addr_any), sizeof(in6_addr)) == 0); + static_cast(&ipAddr->sin6_addr), static_cast(&in6addr_any), sizeof(in6_addr) + ) == 0 + ); } default: @@ -703,12 +725,13 @@ bool ArchNetworkBSD::isAnyAddr(ArchNetAddress addr) { } } -bool ArchNetworkBSD::isEqualAddr(ArchNetAddress a, ArchNetAddress b) { - return ( - a->m_len == b->m_len && memcmp(&a->m_addr, &b->m_addr, a->m_len) == 0); +bool ArchNetworkBSD::isEqualAddr(ArchNetAddress a, ArchNetAddress b) +{ + return (a->m_len == b->m_len && memcmp(&a->m_addr, &b->m_addr, a->m_len) == 0); } -const int *ArchNetworkBSD::getUnblockPipe() { +const int *ArchNetworkBSD::getUnblockPipe() +{ ArchMultithreadPosix *mt = ArchMultithreadPosix::getInstance(); ArchThread thread = mt->newCurrentThread(); const int *p = getUnblockPipeForThread(thread); @@ -716,7 +739,8 @@ const int *ArchNetworkBSD::getUnblockPipe() { return p; } -const int *ArchNetworkBSD::getUnblockPipeForThread(ArchThread thread) { +const int *ArchNetworkBSD::getUnblockPipeForThread(ArchThread thread) +{ ArchMultithreadPosix *mt = ArchMultithreadPosix::getInstance(); auto *unblockPipe = static_cast(mt->getNetworkDataForThread(thread)); if (unblockPipe == nullptr) { @@ -737,7 +761,8 @@ const int *ArchNetworkBSD::getUnblockPipeForThread(ArchThread thread) { return unblockPipe; } -void ArchNetworkBSD::throwError(int err) { +void ArchNetworkBSD::throwError(int err) +{ switch (err) { case EINTR: ARCH->testCancelThread(); @@ -807,13 +832,13 @@ void ArchNetworkBSD::throwError(int err) { } } -void ArchNetworkBSD::throwNameError(int err) { +void ArchNetworkBSD::throwNameError(int err) +{ static const char *s_msg[] = { - "The specified host is unknown", - "The requested name is valid but does not have an IP address", - "A non-recoverable name server error occurred", - "A temporary error occurred on an authoritative name server", - "An unknown name server error occurred"}; + "The specified host is unknown", "The requested name is valid but does not have an IP address", + "A non-recoverable name server error occurred", "A temporary error occurred on an authoritative name server", + "An unknown name server error occurred" + }; switch (err) { case HOST_NOT_FOUND: diff --git a/src/lib/arch/unix/ArchNetworkBSD.h b/src/lib/arch/unix/ArchNetworkBSD.h index 2809af656..0a11b8a79 100644 --- a/src/lib/arch/unix/ArchNetworkBSD.h +++ b/src/lib/arch/unix/ArchNetworkBSD.h @@ -30,7 +30,8 @@ #if HAVE_SYS_SOCKET_H #include #else -struct sockaddr_storage { +struct sockaddr_storage +{ unsigned char ss_len; /* address length */ unsigned char ss_family; /* [XSI] address family */ char __ss_pad1[_SS_PAD1SIZE]; @@ -53,15 +54,19 @@ typedef int socklen_t; // compatible so we always use it. typedef char optval_t; -class ArchSocketImpl { +class ArchSocketImpl +{ public: int m_fd; int m_refCount; }; -class ArchNetAddressImpl { +class ArchNetAddressImpl +{ public: - ArchNetAddressImpl() : m_len(sizeof(m_addr)) {} + ArchNetAddressImpl() : m_len(sizeof(m_addr)) + { + } public: struct sockaddr_storage m_addr; @@ -69,10 +74,12 @@ public: }; //! Berkeley (BSD) sockets implementation of IArchNetwork -class ArchNetworkBSD : public IArchNetwork { +class ArchNetworkBSD : public IArchNetwork +{ public: - struct Deps { + struct Deps + { virtual ~Deps() = default; virtual void sleep(double); virtual int poll(struct pollfd *, nfds_t, int); @@ -81,8 +88,9 @@ public: virtual void testCancelThread(); }; - explicit ArchNetworkBSD(std::shared_ptr deps = std::make_shared()) - : m_pDeps(deps) {} + explicit ArchNetworkBSD(std::shared_ptr deps = std::make_shared()) : m_pDeps(deps) + { + } ArchNetworkBSD(ArchNetworkBSD const &) = delete; ArchNetworkBSD(ArchNetworkBSD &&) = delete; ~ArchNetworkBSD() override; diff --git a/src/lib/arch/unix/ArchSleepUnix.cpp b/src/lib/arch/unix/ArchSleepUnix.cpp index 95ccef74e..72738d61d 100644 --- a/src/lib/arch/unix/ArchSleepUnix.cpp +++ b/src/lib/arch/unix/ArchSleepUnix.cpp @@ -46,15 +46,18 @@ // ArchSleepUnix // -ArchSleepUnix::ArchSleepUnix() { +ArchSleepUnix::ArchSleepUnix() +{ // do nothing } -ArchSleepUnix::~ArchSleepUnix() { +ArchSleepUnix::~ArchSleepUnix() +{ // do nothing } -void ArchSleepUnix::sleep(double timeout) { +void ArchSleepUnix::sleep(double timeout) +{ ARCH->testCancelThread(); if (timeout < 0.0) { return; @@ -78,8 +81,9 @@ void ArchSleepUnix::sleep(double timeout) { timeout2.tv_sec = static_cast(timeLeft); timeout2.tv_usec = static_cast(1.0e+6 * (timeLeft - timeout2.tv_sec)); select( - (SELECT_TYPE_ARG1)0, SELECT_TYPE_ARG234 NULL, SELECT_TYPE_ARG234 NULL, - SELECT_TYPE_ARG234 NULL, SELECT_TYPE_ARG5 & timeout2); + (SELECT_TYPE_ARG1)0, SELECT_TYPE_ARG234 NULL, SELECT_TYPE_ARG234 NULL, SELECT_TYPE_ARG234 NULL, + SELECT_TYPE_ARG5 & timeout2 + ); ARCH->testCancelThread(); timeLeft = timeout - (ARCH->time() - startTime); } diff --git a/src/lib/arch/unix/ArchSleepUnix.h b/src/lib/arch/unix/ArchSleepUnix.h index dbff2055a..41d8b3e4e 100644 --- a/src/lib/arch/unix/ArchSleepUnix.h +++ b/src/lib/arch/unix/ArchSleepUnix.h @@ -23,7 +23,8 @@ #define ARCH_SLEEP ArchSleepUnix //! Unix implementation of IArchSleep -class ArchSleepUnix : public IArchSleep { +class ArchSleepUnix : public IArchSleep +{ public: ArchSleepUnix(); virtual ~ArchSleepUnix(); diff --git a/src/lib/arch/unix/ArchStringUnix.cpp b/src/lib/arch/unix/ArchStringUnix.cpp index 81e0c275e..215249eb9 100644 --- a/src/lib/arch/unix/ArchStringUnix.cpp +++ b/src/lib/arch/unix/ArchStringUnix.cpp @@ -27,10 +27,15 @@ #include "arch/multibyte.h" #include "arch/vsnprintf.h" -ArchStringUnix::ArchStringUnix() {} +ArchStringUnix::ArchStringUnix() +{ +} -ArchStringUnix::~ArchStringUnix() {} +ArchStringUnix::~ArchStringUnix() +{ +} -IArchString::EWideCharEncoding ArchStringUnix::getWideCharEncoding() { +IArchString::EWideCharEncoding ArchStringUnix::getWideCharEncoding() +{ return kUCS4; } diff --git a/src/lib/arch/unix/ArchStringUnix.h b/src/lib/arch/unix/ArchStringUnix.h index d543ac53f..a86e4dbb6 100644 --- a/src/lib/arch/unix/ArchStringUnix.h +++ b/src/lib/arch/unix/ArchStringUnix.h @@ -23,7 +23,8 @@ #define ARCH_STRING ArchStringUnix //! Unix implementation of IArchString -class ArchStringUnix : public IArchString { +class ArchStringUnix : public IArchString +{ public: ArchStringUnix(); virtual ~ArchStringUnix(); diff --git a/src/lib/arch/unix/ArchSystemUnix.cpp b/src/lib/arch/unix/ArchSystemUnix.cpp index b172d870c..2d7a2e80e 100644 --- a/src/lib/arch/unix/ArchSystemUnix.cpp +++ b/src/lib/arch/unix/ArchSystemUnix.cpp @@ -28,15 +28,18 @@ // ArchSystemUnix // -ArchSystemUnix::ArchSystemUnix() { +ArchSystemUnix::ArchSystemUnix() +{ // do nothing } -ArchSystemUnix::~ArchSystemUnix() { +ArchSystemUnix::~ArchSystemUnix() +{ // do nothing } -std::string ArchSystemUnix::getOSName() const { +std::string ArchSystemUnix::getOSName() const +{ #if defined(HAVE_SYS_UTSNAME_H) struct utsname info; if (uname(&info) == 0) { @@ -50,7 +53,8 @@ std::string ArchSystemUnix::getOSName() const { return "Unix"; } -std::string ArchSystemUnix::getPlatformName() const { +std::string ArchSystemUnix::getPlatformName() const +{ #if defined(HAVE_SYS_UTSNAME_H) struct utsname info; if (uname(&info) == 0) { @@ -60,22 +64,26 @@ std::string ArchSystemUnix::getPlatformName() const { return "unknown"; } -std::string ArchSystemUnix::setting(const std::string &) const { return ""; } +std::string ArchSystemUnix::setting(const std::string &) const +{ + return ""; +} -void ArchSystemUnix::setting(const std::string &, const std::string &) const {} +void ArchSystemUnix::setting(const std::string &, const std::string &) const +{ +} -std::string ArchSystemUnix::getLibsUsed(void) const { +std::string ArchSystemUnix::getLibsUsed(void) const +{ return "not implemented.\nuse lsof on shell"; } #ifndef __APPLE__ -bool ArchSystemUnix::DBusInhibitScreenCall( - InhibitScreenServices serviceID, bool state, std::string &error) { +bool ArchSystemUnix::DBusInhibitScreenCall(InhibitScreenServices serviceID, bool state, std::string &error) +{ error = ""; - static const std::array services = { - "org.freedesktop.ScreenSaver", "org.gnome.SessionManager"}; - static const std::array paths = { - "/org/freedesktop/ScreenSaver", "/org/gnome/SessionManager"}; + static const std::array services = {"org.freedesktop.ScreenSaver", "org.gnome.SessionManager"}; + static const std::array paths = {"/org/freedesktop/ScreenSaver", "/org/gnome/SessionManager"}; static std::array cookies; auto serviceNum = static_cast(serviceID); @@ -86,8 +94,7 @@ bool ArchSystemUnix::DBusInhibitScreenCall( return false; } - QDBusInterface screenSaverInterface( - services[serviceNum], paths[serviceNum], services[serviceNum], bus); + QDBusInterface screenSaverInterface(services[serviceNum], paths[serviceNum], services[serviceNum], bus); if (!screenSaverInterface.isValid()) { error = "screen saver interface failed to initialize"; @@ -102,8 +109,8 @@ bool ArchSystemUnix::DBusInhibitScreenCall( } reply = screenSaverInterface.call( - "Inhibit", DESKFLOW_APP_NAME, - "Sleep is manually prevented by the " DESKFLOW_APP_NAME " preferences"); + "Inhibit", DESKFLOW_APP_NAME, "Sleep is manually prevented by the " DESKFLOW_APP_NAME " preferences" + ); if (reply.isValid()) cookies[serviceNum] = reply.value(); } else { @@ -117,8 +124,7 @@ bool ArchSystemUnix::DBusInhibitScreenCall( if (!reply.isValid()) { QDBusError qerror = reply.error(); - error = - qerror.name().toStdString() + " : " + qerror.message().toStdString(); + error = qerror.name().toStdString() + " : " + qerror.message().toStdString(); return false; } diff --git a/src/lib/arch/unix/ArchSystemUnix.h b/src/lib/arch/unix/ArchSystemUnix.h index 656dca585..e7d740708 100644 --- a/src/lib/arch/unix/ArchSystemUnix.h +++ b/src/lib/arch/unix/ArchSystemUnix.h @@ -23,7 +23,8 @@ #define ARCH_SYSTEM ArchSystemUnix //! Unix implementation of IArchString -class ArchSystemUnix : public IArchSystem { +class ArchSystemUnix : public IArchSystem +{ public: ArchSystemUnix(); virtual ~ArchSystemUnix(); @@ -36,8 +37,11 @@ public: virtual std::string getLibsUsed(void) const; #ifndef __APPLE__ - enum class InhibitScreenServices { kScreenSaver, kSessionManager }; - static bool DBusInhibitScreenCall( - InhibitScreenServices serviceID, bool state, std::string &error); + enum class InhibitScreenServices + { + kScreenSaver, + kSessionManager + }; + static bool DBusInhibitScreenCall(InhibitScreenServices serviceID, bool state, std::string &error); #endif }; diff --git a/src/lib/arch/unix/ArchTaskBarXWindows.cpp b/src/lib/arch/unix/ArchTaskBarXWindows.cpp index cfcb6b8fe..6773bba28 100644 --- a/src/lib/arch/unix/ArchTaskBarXWindows.cpp +++ b/src/lib/arch/unix/ArchTaskBarXWindows.cpp @@ -22,22 +22,27 @@ // ArchTaskBarXWindows // -ArchTaskBarXWindows::ArchTaskBarXWindows() { +ArchTaskBarXWindows::ArchTaskBarXWindows() +{ // do nothing } -ArchTaskBarXWindows::~ArchTaskBarXWindows() { +ArchTaskBarXWindows::~ArchTaskBarXWindows() +{ // do nothing } -void ArchTaskBarXWindows::addReceiver(IArchTaskBarReceiver * /*receiver*/) { +void ArchTaskBarXWindows::addReceiver(IArchTaskBarReceiver * /*receiver*/) +{ // do nothing } -void ArchTaskBarXWindows::removeReceiver(IArchTaskBarReceiver * /*receiver*/) { +void ArchTaskBarXWindows::removeReceiver(IArchTaskBarReceiver * /*receiver*/) +{ // do nothing } -void ArchTaskBarXWindows::updateReceiver(IArchTaskBarReceiver * /*receiver*/) { +void ArchTaskBarXWindows::updateReceiver(IArchTaskBarReceiver * /*receiver*/) +{ // do nothing } diff --git a/src/lib/arch/unix/ArchTaskBarXWindows.h b/src/lib/arch/unix/ArchTaskBarXWindows.h index 3e30788c4..98fd40ef1 100644 --- a/src/lib/arch/unix/ArchTaskBarXWindows.h +++ b/src/lib/arch/unix/ArchTaskBarXWindows.h @@ -23,7 +23,8 @@ #define ARCH_TASKBAR ArchTaskBarXWindows //! X11 implementation of IArchTaskBar -class ArchTaskBarXWindows : public IArchTaskBar { +class ArchTaskBarXWindows : public IArchTaskBar +{ public: ArchTaskBarXWindows(); virtual ~ArchTaskBarXWindows(); diff --git a/src/lib/arch/unix/ArchTimeUnix.cpp b/src/lib/arch/unix/ArchTimeUnix.cpp index ad58a9033..7332261c0 100644 --- a/src/lib/arch/unix/ArchTimeUnix.cpp +++ b/src/lib/arch/unix/ArchTimeUnix.cpp @@ -33,15 +33,18 @@ // ArchTimeUnix // -ArchTimeUnix::ArchTimeUnix() { +ArchTimeUnix::ArchTimeUnix() +{ // do nothing } -ArchTimeUnix::~ArchTimeUnix() { +ArchTimeUnix::~ArchTimeUnix() +{ // do nothing } -double ArchTimeUnix::time() { +double ArchTimeUnix::time() +{ struct timeval t; gettimeofday(&t, NULL); return (double)t.tv_sec + 1.0e-6 * (double)t.tv_usec; diff --git a/src/lib/arch/unix/ArchTimeUnix.h b/src/lib/arch/unix/ArchTimeUnix.h index 64e7602cb..64691fb3a 100644 --- a/src/lib/arch/unix/ArchTimeUnix.h +++ b/src/lib/arch/unix/ArchTimeUnix.h @@ -23,7 +23,8 @@ #define ARCH_TIME ArchTimeUnix //! Generic Unix implementation of IArchTime -class ArchTimeUnix : public IArchTime { +class ArchTimeUnix : public IArchTime +{ public: ArchTimeUnix(); virtual ~ArchTimeUnix(); diff --git a/src/lib/arch/unix/XArchUnix.cpp b/src/lib/arch/unix/XArchUnix.cpp index d078934fa..ed992f39e 100644 --- a/src/lib/arch/unix/XArchUnix.cpp +++ b/src/lib/arch/unix/XArchUnix.cpp @@ -24,7 +24,8 @@ // XArchEvalUnix // -std::string XArchEvalUnix::eval() const { +std::string XArchEvalUnix::eval() const +{ // FIXME -- not thread safe return strerror(m_error); } diff --git a/src/lib/arch/unix/XArchUnix.h b/src/lib/arch/unix/XArchUnix.h index b00b26394..8dc619984 100644 --- a/src/lib/arch/unix/XArchUnix.h +++ b/src/lib/arch/unix/XArchUnix.h @@ -21,10 +21,15 @@ #include "arch/XArch.h" //! Lazy error message string evaluation for unix -class XArchEvalUnix : public XArchEval { +class XArchEvalUnix : public XArchEval +{ public: - XArchEvalUnix(int error) : m_error(error) {} - virtual ~XArchEvalUnix() _NOEXCEPT {} + XArchEvalUnix(int error) : m_error(error) + { + } + virtual ~XArchEvalUnix() _NOEXCEPT + { + } virtual std::string eval() const; diff --git a/src/lib/arch/vsnprintf.h b/src/lib/arch/vsnprintf.h index 2db258ccf..40ea87e61 100644 --- a/src/lib/arch/vsnprintf.h +++ b/src/lib/arch/vsnprintf.h @@ -26,7 +26,8 @@ #define ARCH_VSNPRINTF vsnprintf #endif -int IArchString::vsnprintf(char *str, int size, const char *fmt, va_list ap) { +int IArchString::vsnprintf(char *str, int size, const char *fmt, va_list ap) +{ int n = ::ARCH_VSNPRINTF(str, size, fmt, ap); if (n > size) { n = -1; @@ -38,7 +39,8 @@ int IArchString::vsnprintf(char *str, int size, const char *fmt, va_list ap) { #include -int IArchString::vsnprintf(char *str, int size, const char *fmt, va_list ap) { +int IArchString::vsnprintf(char *str, int size, const char *fmt, va_list ap) +{ static FILE *bitbucket = fopen("/dev/null", "w"); if (bitbucket == NULL) { // uh oh diff --git a/src/lib/arch/win32/ArchConsoleWindows.cpp b/src/lib/arch/win32/ArchConsoleWindows.cpp index 6b965fd81..dc90ee747 100644 --- a/src/lib/arch/win32/ArchConsoleWindows.cpp +++ b/src/lib/arch/win32/ArchConsoleWindows.cpp @@ -18,6 +18,10 @@ #include "arch/win32/ArchConsoleWindows.h" -ArchConsoleWindows::ArchConsoleWindows() {} +ArchConsoleWindows::ArchConsoleWindows() +{ +} -ArchConsoleWindows::~ArchConsoleWindows() {} +ArchConsoleWindows::~ArchConsoleWindows() +{ +} diff --git a/src/lib/arch/win32/ArchConsoleWindows.h b/src/lib/arch/win32/ArchConsoleWindows.h index 6d0e14662..fd6389bb3 100644 --- a/src/lib/arch/win32/ArchConsoleWindows.h +++ b/src/lib/arch/win32/ArchConsoleWindows.h @@ -22,7 +22,8 @@ #define ARCH_CONSOLE ArchConsoleWindows -class ArchConsoleWindows : public ArchConsoleStd { +class ArchConsoleWindows : public ArchConsoleStd +{ public: ArchConsoleWindows(); virtual ~ArchConsoleWindows(); diff --git a/src/lib/arch/win32/ArchDaemonWindows.cpp b/src/lib/arch/win32/ArchDaemonWindows.cpp index c0af0406f..17c8d6d57 100644 --- a/src/lib/arch/win32/ArchDaemonWindows.cpp +++ b/src/lib/arch/win32/ArchDaemonWindows.cpp @@ -30,26 +30,31 @@ ArchDaemonWindows *ArchDaemonWindows::s_daemon = NULL; -ArchDaemonWindows::ArchDaemonWindows() : m_daemonThreadID(0) { +ArchDaemonWindows::ArchDaemonWindows() : m_daemonThreadID(0) +{ m_quitMessage = RegisterWindowMessage("DeskflowDaemonExit"); } -ArchDaemonWindows::~ArchDaemonWindows() { +ArchDaemonWindows::~ArchDaemonWindows() +{ // do nothing } -int ArchDaemonWindows::runDaemon(RunFunc runFunc) { +int ArchDaemonWindows::runDaemon(RunFunc runFunc) +{ assert(s_daemon != NULL); return s_daemon->doRunDaemon(runFunc); } -void ArchDaemonWindows::daemonRunning(bool running) { +void ArchDaemonWindows::daemonRunning(bool running) +{ if (s_daemon != NULL) { s_daemon->doDaemonRunning(running); } } -UINT ArchDaemonWindows::getDaemonQuitMessage() { +UINT ArchDaemonWindows::getDaemonQuitMessage() +{ if (s_daemon != NULL) { return s_daemon->doGetDaemonQuitMessage(); } else { @@ -57,14 +62,16 @@ UINT ArchDaemonWindows::getDaemonQuitMessage() { } } -void ArchDaemonWindows::daemonFailed(int result) { +void ArchDaemonWindows::daemonFailed(int result) +{ assert(s_daemon != NULL); throw XArchDaemonRunFailed(result); } void ArchDaemonWindows::installDaemon( - const char *name, const char *description, const char *pathname, - const char *commandLine, const char *dependencies) { + const char *name, const char *description, const char *pathname, const char *commandLine, const char *dependencies +) +{ // open service manager SC_HANDLE mgr = OpenSCManager(NULL, NULL, GENERIC_WRITE); if (mgr == NULL) { @@ -74,10 +81,9 @@ void ArchDaemonWindows::installDaemon( // create the service SC_HANDLE service = CreateService( - mgr, name, name, 0, - SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS, - SERVICE_AUTO_START, SERVICE_ERROR_NORMAL, pathname, NULL, NULL, - dependencies, NULL, NULL); + mgr, name, name, 0, SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS, SERVICE_AUTO_START, + SERVICE_ERROR_NORMAL, pathname, NULL, NULL, dependencies, NULL, NULL + ); if (service == NULL) { // can't create service @@ -130,7 +136,8 @@ void ArchDaemonWindows::installDaemon( ArchMiscWindows::closeKey(key); } -void ArchDaemonWindows::uninstallDaemon(const char *name) { +void ArchDaemonWindows::uninstallDaemon(const char *name) +{ // remove parameters for this service. ignore failures. HKEY key = openNTServicesKey(); key = ArchMiscWindows::openKey(key, name); @@ -192,7 +199,8 @@ void ArchDaemonWindows::uninstallDaemon(const char *name) { } } -int ArchDaemonWindows::daemonize(const char *name, DaemonFunc func) { +int ArchDaemonWindows::daemonize(const char *name, DaemonFunc func) +{ assert(name != NULL); assert(func != NULL); @@ -219,7 +227,8 @@ int ArchDaemonWindows::daemonize(const char *name, DaemonFunc func) { return m_daemonResult; } -bool ArchDaemonWindows::canInstallDaemon(const char * /*name*/) { +bool ArchDaemonWindows::canInstallDaemon(const char * /*name*/) +{ // check if we can open service manager for write SC_HANDLE mgr = OpenSCManager(NULL, NULL, GENERIC_WRITE); if (mgr == NULL) { @@ -234,7 +243,8 @@ bool ArchDaemonWindows::canInstallDaemon(const char * /*name*/) { return (key != NULL); } -bool ArchDaemonWindows::isDaemonInstalled(const char *name) { +bool ArchDaemonWindows::isDaemonInstalled(const char *name) +{ // open service manager SC_HANDLE mgr = OpenSCManager(NULL, NULL, GENERIC_READ); if (mgr == NULL) { @@ -253,14 +263,15 @@ bool ArchDaemonWindows::isDaemonInstalled(const char *name) { return (service != NULL); } -HKEY ArchDaemonWindows::openNTServicesKey() { - static const char *s_keyNames[] = { - _T("SYSTEM"), _T("CurrentControlSet"), _T("Services"), NULL}; +HKEY ArchDaemonWindows::openNTServicesKey() +{ + static const char *s_keyNames[] = {_T("SYSTEM"), _T("CurrentControlSet"), _T("Services"), NULL}; return ArchMiscWindows::addKey(HKEY_LOCAL_MACHINE, s_keyNames); } -bool ArchDaemonWindows::isRunState(DWORD state) { +bool ArchDaemonWindows::isRunState(DWORD state) +{ switch (state) { case SERVICE_START_PENDING: case SERVICE_CONTINUE_PENDING: @@ -272,7 +283,8 @@ bool ArchDaemonWindows::isRunState(DWORD state) { } } -int ArchDaemonWindows::doRunDaemon(RunFunc run) { +int ArchDaemonWindows::doRunDaemon(RunFunc run) +{ // should only be called from DaemonFunc assert(m_serviceMutex != NULL); assert(run != NULL); @@ -286,8 +298,7 @@ int ArchDaemonWindows::doRunDaemon(RunFunc run) { m_daemonThreadID = GetCurrentThreadId(); while (m_serviceState != SERVICE_STOPPED) { // wait until we're told to start - while (!isRunState(m_serviceState) && - m_serviceState != SERVICE_STOP_PENDING) { + while (!isRunState(m_serviceState) && m_serviceState != SERVICE_STOP_PENDING) { ARCH->waitCondVar(m_serviceCondVar, m_serviceMutex, -1.0); } @@ -321,7 +332,8 @@ int ArchDaemonWindows::doRunDaemon(RunFunc run) { return result; } -void ArchDaemonWindows::doDaemonRunning(bool running) { +void ArchDaemonWindows::doDaemonRunning(bool running) +{ ARCH->lockMutex(m_serviceMutex); if (running) { m_serviceState = SERVICE_RUNNING; @@ -331,20 +343,24 @@ void ArchDaemonWindows::doDaemonRunning(bool running) { ARCH->unlockMutex(m_serviceMutex); } -UINT ArchDaemonWindows::doGetDaemonQuitMessage() { return m_quitMessage; } +UINT ArchDaemonWindows::doGetDaemonQuitMessage() +{ + return m_quitMessage; +} -void ArchDaemonWindows::setStatus(DWORD state) { setStatus(state, 0, 0); } +void ArchDaemonWindows::setStatus(DWORD state) +{ + setStatus(state, 0, 0); +} -void ArchDaemonWindows::setStatus(DWORD state, DWORD step, DWORD waitHint) { +void ArchDaemonWindows::setStatus(DWORD state, DWORD step, DWORD waitHint) +{ assert(s_daemon != NULL); SERVICE_STATUS status; - status.dwServiceType = - SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS; + status.dwServiceType = SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS; status.dwCurrentState = state; - status.dwControlsAccepted = SERVICE_ACCEPT_STOP | - SERVICE_ACCEPT_PAUSE_CONTINUE | - SERVICE_ACCEPT_SHUTDOWN; + status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE | SERVICE_ACCEPT_SHUTDOWN; status.dwWin32ExitCode = NO_ERROR; status.dwServiceSpecificExitCode = 0; status.dwCheckPoint = step; @@ -352,16 +368,14 @@ void ArchDaemonWindows::setStatus(DWORD state, DWORD step, DWORD waitHint) { SetServiceStatus(s_daemon->m_statusHandle, &status); } -void ArchDaemonWindows::setStatusError(DWORD error) { +void ArchDaemonWindows::setStatusError(DWORD error) +{ assert(s_daemon != NULL); SERVICE_STATUS status; - status.dwServiceType = - SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS; + status.dwServiceType = SERVICE_WIN32_OWN_PROCESS | SERVICE_INTERACTIVE_PROCESS; status.dwCurrentState = SERVICE_STOPPED; - status.dwControlsAccepted = SERVICE_ACCEPT_STOP | - SERVICE_ACCEPT_PAUSE_CONTINUE | - SERVICE_ACCEPT_SHUTDOWN; + status.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_PAUSE_CONTINUE | SERVICE_ACCEPT_SHUTDOWN; status.dwWin32ExitCode = ERROR_SERVICE_SPECIFIC_ERROR; status.dwServiceSpecificExitCode = error; status.dwCheckPoint = 0; @@ -369,7 +383,8 @@ void ArchDaemonWindows::setStatusError(DWORD error) { SetServiceStatus(s_daemon->m_statusHandle, &status); } -void ArchDaemonWindows::serviceMain(DWORD argc, LPTSTR *argvIn) { +void ArchDaemonWindows::serviceMain(DWORD argc, LPTSTR *argvIn) +{ typedef std::vector ArgList; typedef std::vector Arguments; const char **argv = const_cast(argvIn); @@ -379,8 +394,7 @@ void ArchDaemonWindows::serviceMain(DWORD argc, LPTSTR *argvIn) { m_serviceCondVar = ARCH->newCondVar(); // register our service handler function - m_statusHandle = RegisterServiceCtrlHandler( - argv[0], &ArchDaemonWindows::serviceHandlerEntry); + m_statusHandle = RegisterServiceCtrlHandler(argv[0], &ArchDaemonWindows::serviceHandlerEntry); if (m_statusHandle == 0) { // cannot start as service m_daemonResult = -1; @@ -422,8 +436,7 @@ void ArchDaemonWindows::serviceMain(DWORD argc, LPTSTR *argvIn) { // whitespace must follow closing quote if (e == std::string::npos || - (e + 1 != commandLine.size() && commandLine[e + 1] != ' ' && - commandLine[e + 1] != '\t')) { + (e + 1 != commandLine.size() && commandLine[e + 1] != ' ' && commandLine[e + 1] != '\t')) { args.clear(); break; } @@ -483,11 +496,13 @@ void ArchDaemonWindows::serviceMain(DWORD argc, LPTSTR *argvIn) { setStatus(m_serviceState, 0, 10000); } -void WINAPI ArchDaemonWindows::serviceMainEntry(DWORD argc, LPTSTR *argv) { +void WINAPI ArchDaemonWindows::serviceMainEntry(DWORD argc, LPTSTR *argv) +{ s_daemon->serviceMain(argc, argv); } -void ArchDaemonWindows::serviceHandler(DWORD ctrl) { +void ArchDaemonWindows::serviceHandler(DWORD ctrl) +{ assert(m_serviceMutex != NULL); assert(m_serviceCondVar != NULL); @@ -542,11 +557,13 @@ void ArchDaemonWindows::serviceHandler(DWORD ctrl) { ARCH->unlockMutex(m_serviceMutex); } -void WINAPI ArchDaemonWindows::serviceHandlerEntry(DWORD ctrl) { +void WINAPI ArchDaemonWindows::serviceHandlerEntry(DWORD ctrl) +{ s_daemon->serviceHandler(ctrl); } -void ArchDaemonWindows::start(const char *name) { +void ArchDaemonWindows::start(const char *name) +{ // open service manager SC_HANDLE mgr = OpenSCManager(NULL, NULL, GENERIC_READ); if (mgr == NULL) { @@ -567,7 +584,8 @@ void ArchDaemonWindows::start(const char *name) { } } -void ArchDaemonWindows::stop(const char *name) { +void ArchDaemonWindows::stop(const char *name) +{ // open service manager SC_HANDLE mgr = OpenSCManager(NULL, NULL, GENERIC_READ); if (mgr == NULL) { @@ -575,8 +593,7 @@ void ArchDaemonWindows::stop(const char *name) { } // open the service - SC_HANDLE service = - OpenService(mgr, name, SERVICE_STOP | SERVICE_QUERY_STATUS); + SC_HANDLE service = OpenService(mgr, name, SERVICE_STOP | SERVICE_QUERY_STATUS); if (service == NULL) { CloseServiceHandle(mgr); @@ -593,7 +610,8 @@ void ArchDaemonWindows::stop(const char *name) { } } -void ArchDaemonWindows::installDaemon() { +void ArchDaemonWindows::installDaemon() +{ // install default daemon if not already installed. if (!isDaemonInstalled(DEFAULT_DAEMON_NAME)) { char path[MAX_PATH]; @@ -605,14 +623,14 @@ void ArchDaemonWindows::installDaemon() { ss << path; ss << '"'; - installDaemon( - DEFAULT_DAEMON_NAME, DEFAULT_DAEMON_INFO, ss.str().c_str(), "", ""); + installDaemon(DEFAULT_DAEMON_NAME, DEFAULT_DAEMON_INFO, ss.str().c_str(), "", ""); } start(DEFAULT_DAEMON_NAME); } -void ArchDaemonWindows::uninstallDaemon() { +void ArchDaemonWindows::uninstallDaemon() +{ // remove legacy services if installed. if (isDaemonInstalled(LEGACY_SERVER_DAEMON_NAME)) { uninstallDaemon(LEGACY_SERVER_DAEMON_NAME); diff --git a/src/lib/arch/win32/ArchDaemonWindows.h b/src/lib/arch/win32/ArchDaemonWindows.h index 2089ecdbb..0e6f11a7c 100644 --- a/src/lib/arch/win32/ArchDaemonWindows.h +++ b/src/lib/arch/win32/ArchDaemonWindows.h @@ -29,7 +29,8 @@ #define ARCH_DAEMON ArchDaemonWindows //! Win32 implementation of IArchDaemon -class ArchDaemonWindows : public IArchDaemon { +class ArchDaemonWindows : public IArchDaemon +{ public: typedef int (*RunFunc)(void); @@ -76,15 +77,18 @@ public: // IArchDaemon overrides virtual void installDaemon( - const char *name, const char *description, const char *pathname, - const char *commandLine, const char *dependencies); + const char *name, const char *description, const char *pathname, const char *commandLine, const char *dependencies + ); virtual void uninstallDaemon(const char *name); virtual void installDaemon(); virtual void uninstallDaemon(); virtual int daemonize(const char *name, DaemonFunc func); virtual bool canInstallDaemon(const char *name); virtual bool isDaemonInstalled(const char *name); - std::string commandLine() const { return m_commandLine; } + std::string commandLine() const + { + return m_commandLine; + } private: static HKEY openNTServicesKey(); @@ -109,9 +113,12 @@ private: void stop(const char *name); private: - class XArchDaemonRunFailed { + class XArchDaemonRunFailed + { public: - XArchDaemonRunFailed(int result) : m_result(result) {} + XArchDaemonRunFailed(int result) : m_result(result) + { + } public: int m_result; @@ -138,8 +145,7 @@ private: }; #define DEFAULT_DAEMON_NAME _T(DESKFLOW_APP_NAME) -#define DEFAULT_DAEMON_INFO \ - _T("Manages the " DESKFLOW_APP_NAME " foreground processes.") +#define DEFAULT_DAEMON_INFO _T("Manages the " DESKFLOW_APP_NAME " foreground processes.") #define LEGACY_SERVER_DAEMON_NAME _T(DESKFLOW_APP_NAME " Server") #define LEGACY_CLIENT_DAEMON_NAME _T(DESKFLOW_APP_NAME " Client") diff --git a/src/lib/arch/win32/ArchFileWindows.cpp b/src/lib/arch/win32/ArchFileWindows.cpp index ffaf7cd8d..1cf59ca96 100644 --- a/src/lib/arch/win32/ArchFileWindows.cpp +++ b/src/lib/arch/win32/ArchFileWindows.cpp @@ -28,15 +28,18 @@ // ArchFileWindows // -ArchFileWindows::ArchFileWindows() { +ArchFileWindows::ArchFileWindows() +{ // do nothing } -ArchFileWindows::~ArchFileWindows() { +ArchFileWindows::~ArchFileWindows() +{ // do nothing } -const char *ArchFileWindows::getBasename(const char *pathname) { +const char *ArchFileWindows::getBasename(const char *pathname) +{ if (pathname == NULL) { return NULL; } @@ -58,7 +61,8 @@ const char *ArchFileWindows::getBasename(const char *pathname) { return basename; } -std::string ArchFileWindows::getUserDirectory() { +std::string ArchFileWindows::getUserDirectory() +{ // try %HOMEPATH% TCHAR dir[MAX_PATH]; DWORD size = sizeof(dir) / sizeof(TCHAR); @@ -67,9 +71,7 @@ std::string ArchFileWindows::getUserDirectory() { // sanity check -- if dir doesn't appear to start with a // drive letter and isn't a UNC name then don't use it // FIXME -- allow UNC names - if (dir[0] != '\0' && - (dir[1] == ':' || ((dir[0] == '\\' || dir[0] == '/') && - (dir[1] == '\\' || dir[1] == '/')))) { + if (dir[0] != '\0' && (dir[1] == ':' || ((dir[0] == '\\' || dir[0] == '/') && (dir[1] == '\\' || dir[1] == '/')))) { return dir; } } @@ -100,7 +102,8 @@ std::string ArchFileWindows::getUserDirectory() { return "C:"; } -std::string ArchFileWindows::getSystemDirectory() { +std::string ArchFileWindows::getSystemDirectory() +{ // get windows directory char dir[MAX_PATH]; if (GetWindowsDirectory(dir, sizeof(dir)) != 0) { @@ -111,7 +114,8 @@ std::string ArchFileWindows::getSystemDirectory() { } } -std::string ArchFileWindows::getInstalledDirectory() { +std::string ArchFileWindows::getInstalledDirectory() +{ char fileNameBuffer[MAX_PATH]; GetModuleFileName(NULL, fileNameBuffer, MAX_PATH); std::string fileName(fileNameBuffer); @@ -121,11 +125,13 @@ std::string ArchFileWindows::getInstalledDirectory() { return fileName; } -std::string ArchFileWindows::getLogDirectory() { +std::string ArchFileWindows::getLogDirectory() +{ return getInstalledDirectory(); } -std::string ArchFileWindows::getPluginDirectory() { +std::string ArchFileWindows::getPluginDirectory() +{ if (!m_pluginDirectory.empty()) { return m_pluginDirectory; } @@ -135,14 +141,14 @@ std::string ArchFileWindows::getPluginDirectory() { return dir; } -std::string ArchFileWindows::getProfileDirectory() { +std::string ArchFileWindows::getProfileDirectory() +{ String dir; if (!m_profileDirectory.empty()) { dir = m_profileDirectory; } else { TCHAR result[MAX_PATH]; - if (SUCCEEDED( - SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, result))) { + if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_LOCAL_APPDATA, NULL, 0, result))) { dir = result; } else { dir = getUserDirectory(); @@ -155,23 +161,24 @@ std::string ArchFileWindows::getProfileDirectory() { return dir; } -std::string ArchFileWindows::concatPath( - const std::string &prefix, const std::string &suffix) { +std::string ArchFileWindows::concatPath(const std::string &prefix, const std::string &suffix) +{ std::string path; path.reserve(prefix.size() + 1 + suffix.size()); path += prefix; - if (path.size() == 0 || - (path[path.size() - 1] != '\\' && path[path.size() - 1] != '/')) { + if (path.size() == 0 || (path[path.size() - 1] != '\\' && path[path.size() - 1] != '/')) { path += '\\'; } path += suffix; return path; } -void ArchFileWindows::setProfileDirectory(const String &s) { +void ArchFileWindows::setProfileDirectory(const String &s) +{ m_profileDirectory = s; } -void ArchFileWindows::setPluginDirectory(const String &s) { +void ArchFileWindows::setPluginDirectory(const String &s) +{ m_pluginDirectory = s; } diff --git a/src/lib/arch/win32/ArchFileWindows.h b/src/lib/arch/win32/ArchFileWindows.h index 6d2428147..ff1ed8d31 100644 --- a/src/lib/arch/win32/ArchFileWindows.h +++ b/src/lib/arch/win32/ArchFileWindows.h @@ -23,7 +23,8 @@ #define ARCH_FILE ArchFileWindows //! Win32 implementation of IArchFile -class ArchFileWindows : public IArchFile { +class ArchFileWindows : public IArchFile +{ public: ArchFileWindows(); virtual ~ArchFileWindows(); @@ -36,8 +37,7 @@ public: virtual std::string getLogDirectory(); virtual std::string getPluginDirectory(); virtual std::string getProfileDirectory(); - virtual std::string - concatPath(const std::string &prefix, const std::string &suffix); + virtual std::string concatPath(const std::string &prefix, const std::string &suffix); virtual void setProfileDirectory(const String &s); virtual void setPluginDirectory(const String &s); diff --git a/src/lib/arch/win32/ArchLogWindows.cpp b/src/lib/arch/win32/ArchLogWindows.cpp index 77deb8b50..c91247da0 100644 --- a/src/lib/arch/win32/ArchLogWindows.cpp +++ b/src/lib/arch/win32/ArchLogWindows.cpp @@ -25,32 +25,38 @@ // ArchLogWindows // -ArchLogWindows::ArchLogWindows() : m_eventLog(NULL) { +ArchLogWindows::ArchLogWindows() : m_eventLog(NULL) +{ // do nothing } -ArchLogWindows::~ArchLogWindows() { +ArchLogWindows::~ArchLogWindows() +{ // do nothing } -void ArchLogWindows::openLog(const char *name) { +void ArchLogWindows::openLog(const char *name) +{ if (m_eventLog == NULL) { m_eventLog = RegisterEventSource(NULL, name); } } -void ArchLogWindows::closeLog() { +void ArchLogWindows::closeLog() +{ if (m_eventLog != NULL) { DeregisterEventSource(m_eventLog); m_eventLog = NULL; } } -void ArchLogWindows::showLog(bool) { +void ArchLogWindows::showLog(bool) +{ // do nothing } -void ArchLogWindows::writeLog(ELevel level, const char *msg) { +void ArchLogWindows::writeLog(ELevel level, const char *msg) +{ if (m_eventLog != NULL) { // convert priority WORD type; @@ -80,6 +86,7 @@ void ArchLogWindows::writeLog(ELevel level, const char *msg) { NULL, 0, (DWORD)strlen(msg) + 1, // raw data size NULL, - const_cast(msg)); // raw data + const_cast(msg) + ); // raw data } } diff --git a/src/lib/arch/win32/ArchLogWindows.h b/src/lib/arch/win32/ArchLogWindows.h index dcf2f91c3..91d863742 100644 --- a/src/lib/arch/win32/ArchLogWindows.h +++ b/src/lib/arch/win32/ArchLogWindows.h @@ -26,7 +26,8 @@ #define ARCH_LOG ArchLogWindows //! Win32 implementation of IArchLog -class ArchLogWindows : public IArchLog { +class ArchLogWindows : public IArchLog +{ public: ArchLogWindows(); virtual ~ArchLogWindows(); diff --git a/src/lib/arch/win32/ArchMiscWindows.cpp b/src/lib/arch/win32/ArchMiscWindows.cpp index 8a24463c9..ea5df3e49 100644 --- a/src/lib/arch/win32/ArchMiscWindows.cpp +++ b/src/lib/arch/win32/ArchMiscWindows.cpp @@ -51,58 +51,73 @@ HICON ArchMiscWindows::s_largeIcon = NULL; HICON ArchMiscWindows::s_smallIcon = NULL; HINSTANCE ArchMiscWindows::s_instanceWin32 = NULL; -void ArchMiscWindows::cleanup() { delete s_dialogs; } +void ArchMiscWindows::cleanup() +{ + delete s_dialogs; +} -void ArchMiscWindows::init() { +void ArchMiscWindows::init() +{ // stop windows system error dialogs from showing. SetErrorMode(SEM_FAILCRITICALERRORS); s_dialogs = new Dialogs; } -void ArchMiscWindows::setIcons(HICON largeIcon, HICON smallIcon) { +void ArchMiscWindows::setIcons(HICON largeIcon, HICON smallIcon) +{ s_largeIcon = largeIcon; s_smallIcon = smallIcon; } -void ArchMiscWindows::getIcons(HICON &largeIcon, HICON &smallIcon) { +void ArchMiscWindows::getIcons(HICON &largeIcon, HICON &smallIcon) +{ largeIcon = s_largeIcon; smallIcon = s_smallIcon; } -int ArchMiscWindows::runDaemon(RunFunc runFunc) { +int ArchMiscWindows::runDaemon(RunFunc runFunc) +{ return ArchDaemonWindows::runDaemon(runFunc); } -void ArchMiscWindows::daemonRunning(bool running) { +void ArchMiscWindows::daemonRunning(bool running) +{ ArchDaemonWindows::daemonRunning(running); } -void ArchMiscWindows::daemonFailed(int result) { +void ArchMiscWindows::daemonFailed(int result) +{ ArchDaemonWindows::daemonFailed(result); } -UINT ArchMiscWindows::getDaemonQuitMessage() { +UINT ArchMiscWindows::getDaemonQuitMessage() +{ return ArchDaemonWindows::getDaemonQuitMessage(); } -HKEY ArchMiscWindows::openKey(HKEY key, const TCHAR *keyName) { +HKEY ArchMiscWindows::openKey(HKEY key, const TCHAR *keyName) +{ return openKey(key, keyName, false); } -HKEY ArchMiscWindows::openKey(HKEY key, const TCHAR *const *keyNames) { +HKEY ArchMiscWindows::openKey(HKEY key, const TCHAR *const *keyNames) +{ return openKey(key, keyNames, false); } -HKEY ArchMiscWindows::addKey(HKEY key, const TCHAR *keyName) { +HKEY ArchMiscWindows::addKey(HKEY key, const TCHAR *keyName) +{ return openKey(key, keyName, true); } -HKEY ArchMiscWindows::addKey(HKEY key, const TCHAR *const *keyNames) { +HKEY ArchMiscWindows::addKey(HKEY key, const TCHAR *const *keyNames) +{ return openKey(key, keyNames, true); } -HKEY ArchMiscWindows::openKey(HKEY key, const TCHAR *keyName, bool create) { +HKEY ArchMiscWindows::openKey(HKEY key, const TCHAR *keyName, bool create) +{ // ignore if parent is NULL if (key == NULL) { return NULL; @@ -110,13 +125,10 @@ HKEY ArchMiscWindows::openKey(HKEY key, const TCHAR *keyName, bool create) { // open next key HKEY newKey; - LSTATUS result = - RegOpenKeyEx(key, keyName, 0, KEY_WRITE | KEY_QUERY_VALUE, &newKey); + LSTATUS result = RegOpenKeyEx(key, keyName, 0, KEY_WRITE | KEY_QUERY_VALUE, &newKey); if (result != ERROR_SUCCESS && create) { DWORD disp; - result = RegCreateKeyEx( - key, keyName, 0, NULL, 0, KEY_WRITE | KEY_QUERY_VALUE, NULL, &newKey, - &disp); + result = RegCreateKeyEx(key, keyName, 0, NULL, 0, KEY_WRITE | KEY_QUERY_VALUE, NULL, &newKey, &disp); } if (result != ERROR_SUCCESS) { RegCloseKey(key); @@ -128,8 +140,8 @@ HKEY ArchMiscWindows::openKey(HKEY key, const TCHAR *keyName, bool create) { return newKey; } -HKEY ArchMiscWindows::openKey( - HKEY key, const TCHAR *const *keyNames, bool create) { +HKEY ArchMiscWindows::openKey(HKEY key, const TCHAR *const *keyNames, bool create) +{ for (size_t i = 0; key != NULL && keyNames[i] != NULL; ++i) { // open next key key = openKey(key, keyNames[i], create); @@ -137,14 +149,16 @@ HKEY ArchMiscWindows::openKey( return key; } -void ArchMiscWindows::closeKey(HKEY key) { +void ArchMiscWindows::closeKey(HKEY key) +{ assert(key != NULL); if (key == NULL) return; RegCloseKey(key); } -void ArchMiscWindows::deleteKey(HKEY key, const TCHAR *name) { +void ArchMiscWindows::deleteKey(HKEY key, const TCHAR *name) +{ assert(key != NULL); assert(name != NULL); if (key == NULL || name == NULL) @@ -152,7 +166,8 @@ void ArchMiscWindows::deleteKey(HKEY key, const TCHAR *name) { RegDeleteKey(key, name); } -void ArchMiscWindows::deleteValue(HKEY key, const TCHAR *name) { +void ArchMiscWindows::deleteValue(HKEY key, const TCHAR *name) +{ assert(key != NULL); assert(name != NULL); if (key == NULL || name == NULL) @@ -160,14 +175,15 @@ void ArchMiscWindows::deleteValue(HKEY key, const TCHAR *name) { RegDeleteValue(key, name); } -bool ArchMiscWindows::hasValue(HKEY key, const TCHAR *name) { +bool ArchMiscWindows::hasValue(HKEY key, const TCHAR *name) +{ DWORD type; LONG result = RegQueryValueEx(key, name, 0, &type, NULL, NULL); return (result == ERROR_SUCCESS && (type == REG_DWORD || type == REG_SZ)); } -ArchMiscWindows::EValueType -ArchMiscWindows::typeOfValue(HKEY key, const TCHAR *name) { +ArchMiscWindows::EValueType ArchMiscWindows::typeOfValue(HKEY key, const TCHAR *name) +{ DWORD type; LONG result = RegQueryValueEx(key, name, 0, &type, NULL, NULL); if (result != ERROR_SUCCESS) { @@ -188,44 +204,39 @@ ArchMiscWindows::typeOfValue(HKEY key, const TCHAR *name) { } } -void ArchMiscWindows::setValue( - HKEY key, const TCHAR *name, const std::string &value) { +void ArchMiscWindows::setValue(HKEY key, const TCHAR *name, const std::string &value) +{ assert(key != NULL); if (key == NULL) { // TODO: throw exception return; } - RegSetValueEx( - key, name, 0, REG_SZ, reinterpret_cast(value.c_str()), - (DWORD)value.size() + 1); + RegSetValueEx(key, name, 0, REG_SZ, reinterpret_cast(value.c_str()), (DWORD)value.size() + 1); } -void ArchMiscWindows::setValue(HKEY key, const TCHAR *name, DWORD value) { +void ArchMiscWindows::setValue(HKEY key, const TCHAR *name, DWORD value) +{ assert(key != NULL); if (key == NULL) { // TODO: throw exception return; } - RegSetValueEx( - key, name, 0, REG_DWORD, reinterpret_cast(&value), - sizeof(DWORD)); + RegSetValueEx(key, name, 0, REG_DWORD, reinterpret_cast(&value), sizeof(DWORD)); } -void ArchMiscWindows::setValueBinary( - HKEY key, const TCHAR *name, const std::string &value) { +void ArchMiscWindows::setValueBinary(HKEY key, const TCHAR *name, const std::string &value) +{ assert(key != NULL); assert(name != NULL); if (key == NULL || name == NULL) { // TODO: throw exception return; } - RegSetValueEx( - key, name, 0, REG_BINARY, reinterpret_cast(value.data()), - (DWORD)value.size()); + RegSetValueEx(key, name, 0, REG_BINARY, reinterpret_cast(value.data()), (DWORD)value.size()); } -std::string -ArchMiscWindows::readBinaryOrString(HKEY key, const TCHAR *name, DWORD type) { +std::string ArchMiscWindows::readBinaryOrString(HKEY key, const TCHAR *name, DWORD type) +{ // get the size of the string DWORD actualType; DWORD size = 0; @@ -243,8 +254,7 @@ ArchMiscWindows::readBinaryOrString(HKEY key, const TCHAR *name, DWORD type) { char *buffer = new char[size]; // read it - result = RegQueryValueEx( - key, name, 0, &actualType, reinterpret_cast(buffer), &size); + result = RegQueryValueEx(key, name, 0, &actualType, reinterpret_cast(buffer), &size); if (result != ERROR_SUCCESS || actualType != type) { delete[] buffer; return std::string(); @@ -260,34 +270,42 @@ ArchMiscWindows::readBinaryOrString(HKEY key, const TCHAR *name, DWORD type) { return value; } -std::string ArchMiscWindows::readValueString(HKEY key, const TCHAR *name) { +std::string ArchMiscWindows::readValueString(HKEY key, const TCHAR *name) +{ return readBinaryOrString(key, name, REG_SZ); } -std::string ArchMiscWindows::readValueBinary(HKEY key, const TCHAR *name) { +std::string ArchMiscWindows::readValueBinary(HKEY key, const TCHAR *name) +{ return readBinaryOrString(key, name, REG_BINARY); } DWORD -ArchMiscWindows::readValueInt(HKEY key, const TCHAR *name) { +ArchMiscWindows::readValueInt(HKEY key, const TCHAR *name) +{ DWORD type; DWORD value; DWORD size = sizeof(value); - LONG result = RegQueryValueEx( - key, name, 0, &type, reinterpret_cast(&value), &size); + LONG result = RegQueryValueEx(key, name, 0, &type, reinterpret_cast(&value), &size); if (result != ERROR_SUCCESS || type != REG_DWORD) { return 0; } return value; } -void ArchMiscWindows::addDialog(HWND hwnd) { s_dialogs->insert(hwnd); } +void ArchMiscWindows::addDialog(HWND hwnd) +{ + s_dialogs->insert(hwnd); +} -void ArchMiscWindows::removeDialog(HWND hwnd) { s_dialogs->erase(hwnd); } +void ArchMiscWindows::removeDialog(HWND hwnd) +{ + s_dialogs->erase(hwnd); +} -bool ArchMiscWindows::processDialog(MSG *msg) { - for (Dialogs::const_iterator index = s_dialogs->begin(); - index != s_dialogs->end(); ++index) { +bool ArchMiscWindows::processDialog(MSG *msg) +{ + for (Dialogs::const_iterator index = s_dialogs->begin(); index != s_dialogs->end(); ++index) { if (IsDialogMessage(*index, msg)) { return true; } @@ -295,23 +313,25 @@ bool ArchMiscWindows::processDialog(MSG *msg) { return false; } -void ArchMiscWindows::addBusyState(DWORD busyModes) { +void ArchMiscWindows::addBusyState(DWORD busyModes) +{ s_busyState |= busyModes; setThreadExecutionState(s_busyState); } -void ArchMiscWindows::removeBusyState(DWORD busyModes) { +void ArchMiscWindows::removeBusyState(DWORD busyModes) +{ s_busyState &= ~busyModes; setThreadExecutionState(s_busyState); } -void ArchMiscWindows::setThreadExecutionState(DWORD busyModes) { +void ArchMiscWindows::setThreadExecutionState(DWORD busyModes) +{ // look up function dynamically so we work on older systems if (s_stes == NULL) { HINSTANCE kernel = LoadLibrary("kernel32.dll"); if (kernel != NULL) { - s_stes = reinterpret_cast( - GetProcAddress(kernel, "SetThreadExecutionState")); + s_stes = reinterpret_cast(GetProcAddress(kernel, "SetThreadExecutionState")); } if (s_stes == NULL) { s_stes = &ArchMiscWindows::dummySetThreadExecutionState; @@ -335,20 +355,21 @@ void ArchMiscWindows::setThreadExecutionState(DWORD busyModes) { } DWORD -ArchMiscWindows::dummySetThreadExecutionState(DWORD) { +ArchMiscWindows::dummySetThreadExecutionState(DWORD) +{ // do nothing return 0; } -void ArchMiscWindows::wakeupDisplay() { +void ArchMiscWindows::wakeupDisplay() +{ // We can't use ::setThreadExecutionState here because it sets // ES_CONTINUOUS, which we don't want. if (s_stes == NULL) { HINSTANCE kernel = LoadLibrary("kernel32.dll"); if (kernel != NULL) { - s_stes = reinterpret_cast( - GetProcAddress(kernel, "SetThreadExecutionState")); + s_stes = reinterpret_cast(GetProcAddress(kernel, "SetThreadExecutionState")); } if (s_stes == NULL) { s_stes = &ArchMiscWindows::dummySetThreadExecutionState; @@ -361,7 +382,8 @@ void ArchMiscWindows::wakeupDisplay() { setThreadExecutionState(s_busyState); } -bool ArchMiscWindows::wasLaunchedAsService() { +bool ArchMiscWindows::wasLaunchedAsService() +{ String name; if (!getParentProcessName(name)) { LOG((CLOG_ERR "cannot determine if process was launched as service")); @@ -371,7 +393,8 @@ bool ArchMiscWindows::wasLaunchedAsService() { return (name == SERVICE_LAUNCHER); } -bool ArchMiscWindows::getParentProcessName(String &name) { +bool ArchMiscWindows::getParentProcessName(String &name) +{ PROCESSENTRY32 parentEntry; if (!getParentProcessEntry(parentEntry)) { LOG((CLOG_ERR "could not get entry for parent process")); @@ -382,12 +405,14 @@ bool ArchMiscWindows::getParentProcessName(String &name) { return true; } -BOOL WINAPI ArchMiscWindows::getSelfProcessEntry(PROCESSENTRY32 &entry) { +BOOL WINAPI ArchMiscWindows::getSelfProcessEntry(PROCESSENTRY32 &entry) +{ // get entry from current PID return getProcessEntry(entry, GetCurrentProcessId()); } -BOOL WINAPI ArchMiscWindows::getParentProcessEntry(PROCESSENTRY32 &entry) { +BOOL WINAPI ArchMiscWindows::getParentProcessEntry(PROCESSENTRY32 &entry) +{ // get the current process, so we can get parent PID PROCESSENTRY32 selfEntry; if (!getSelfProcessEntry(selfEntry)) { @@ -398,13 +423,12 @@ BOOL WINAPI ArchMiscWindows::getParentProcessEntry(PROCESSENTRY32 &entry) { return getProcessEntry(entry, selfEntry.th32ParentProcessID); } -BOOL WINAPI -ArchMiscWindows::getProcessEntry(PROCESSENTRY32 &entry, DWORD processID) { +BOOL WINAPI ArchMiscWindows::getProcessEntry(PROCESSENTRY32 &entry, DWORD processID) +{ // first we need to take a snapshot of the running processes HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snapshot == INVALID_HANDLE_VALUE) { - LOG(( - CLOG_ERR "could not get process snapshot (error: %i)", GetLastError())); + LOG((CLOG_ERR "could not get process snapshot (error: %i)", GetLastError())); return FALSE; } @@ -414,9 +438,7 @@ ArchMiscWindows::getProcessEntry(PROCESSENTRY32 &entry, DWORD processID) { // unlikely we can go any further BOOL gotEntry = Process32First(snapshot, &entry); if (!gotEntry) { - LOG( - (CLOG_ERR "could not get first process entry (error: %i)", - GetLastError())); + LOG((CLOG_ERR "could not get first process entry (error: %i)", GetLastError())); return FALSE; } @@ -435,12 +457,14 @@ ArchMiscWindows::getProcessEntry(PROCESSENTRY32 &entry, DWORD processID) { } HINSTANCE -ArchMiscWindows::instanceWin32() { +ArchMiscWindows::instanceWin32() +{ assert(s_instanceWin32 != NULL); return s_instanceWin32; } -void ArchMiscWindows::setInstanceWin32(HINSTANCE instance) { +void ArchMiscWindows::setInstanceWin32(HINSTANCE instance) +{ assert(instance != NULL); s_instanceWin32 = instance; } \ No newline at end of file diff --git a/src/lib/arch/win32/ArchMiscWindows.h b/src/lib/arch/win32/ArchMiscWindows.h index e272460bb..3e8cbe190 100644 --- a/src/lib/arch/win32/ArchMiscWindows.h +++ b/src/lib/arch/win32/ArchMiscWindows.h @@ -28,10 +28,23 @@ #include //! Miscellaneous win32 functions. -class ArchMiscWindows { +class ArchMiscWindows +{ public: - enum EValueType { kUNKNOWN, kNO_VALUE, kUINT, kSTRING, kBINARY }; - enum EBusyModes { kIDLE = 0x0000, kSYSTEM = 0x0001, kDISPLAY = 0x0002 }; + enum EValueType + { + kUNKNOWN, + kNO_VALUE, + kUINT, + kSTRING, + kBINARY + }; + enum EBusyModes + { + kIDLE = 0x0000, + kSYSTEM = 0x0001, + kDISPLAY = 0x0002 + }; typedef int (*RunFunc)(void); @@ -114,8 +127,7 @@ public: /*! Sets the \p name value of \p key to \p value.data(). */ - static void - setValueBinary(HKEY key, const TCHAR *name, const std::string &value); + static void setValueBinary(HKEY key, const TCHAR *name, const std::string &value); //! Read a string value from the registry static std::string readValueString(HKEY, const TCHAR *name); diff --git a/src/lib/arch/win32/ArchMultithreadWindows.cpp b/src/lib/arch/win32/ArchMultithreadWindows.cpp index 56933028b..78d189632 100644 --- a/src/lib/arch/win32/ArchMultithreadWindows.cpp +++ b/src/lib/arch/win32/ArchMultithreadWindows.cpp @@ -40,7 +40,8 @@ // ArchThreadImpl // -class ArchThreadImpl { +class ArchThreadImpl +{ public: ArchThreadImpl(); ~ArchThreadImpl(); @@ -66,12 +67,14 @@ ArchThreadImpl::ArchThreadImpl() m_userData(NULL), m_cancelling(false), m_result(NULL), - m_networkData(NULL) { + m_networkData(NULL) +{ m_exit = CreateEvent(NULL, TRUE, FALSE, NULL); m_cancel = CreateEvent(NULL, TRUE, FALSE, NULL); } -ArchThreadImpl::~ArchThreadImpl() { +ArchThreadImpl::~ArchThreadImpl() +{ CloseHandle(m_exit); CloseHandle(m_cancel); } @@ -82,7 +85,8 @@ ArchThreadImpl::~ArchThreadImpl() { ArchMultithreadWindows *ArchMultithreadWindows::s_instance = NULL; -ArchMultithreadWindows::ArchMultithreadWindows() { +ArchMultithreadWindows::ArchMultithreadWindows() +{ assert(s_instance == NULL); s_instance = this; @@ -103,12 +107,12 @@ ArchMultithreadWindows::ArchMultithreadWindows() { insert(m_mainThread); } -ArchMultithreadWindows::~ArchMultithreadWindows() { +ArchMultithreadWindows::~ArchMultithreadWindows() +{ s_instance = NULL; // clean up thread list - for (ThreadList::iterator index = m_threadList.begin(); - index != m_threadList.end(); ++index) { + for (ThreadList::iterator index = m_threadList.begin(); index != m_threadList.end(); ++index) { delete *index; } @@ -116,14 +120,16 @@ ArchMultithreadWindows::~ArchMultithreadWindows() { delete m_threadMutex; } -void ArchMultithreadWindows::setNetworkDataForCurrentThread(void *data) { +void ArchMultithreadWindows::setNetworkDataForCurrentThread(void *data) +{ lockMutex(m_threadMutex); ArchThreadImpl *thread = findNoRef(GetCurrentThreadId()); thread->m_networkData = data; unlockMutex(m_threadMutex); } -void *ArchMultithreadWindows::getNetworkDataForThread(ArchThread thread) { +void *ArchMultithreadWindows::getNetworkDataForThread(ArchThread thread) +{ lockMutex(m_threadMutex); void *data = thread->m_networkData; unlockMutex(m_threadMutex); @@ -131,35 +137,39 @@ void *ArchMultithreadWindows::getNetworkDataForThread(ArchThread thread) { } HANDLE -ArchMultithreadWindows::getCancelEventForCurrentThread() { +ArchMultithreadWindows::getCancelEventForCurrentThread() +{ lockMutex(m_threadMutex); ArchThreadImpl *thread = findNoRef(GetCurrentThreadId()); unlockMutex(m_threadMutex); return thread->m_cancel; } -ArchMultithreadWindows *ArchMultithreadWindows::getInstance() { +ArchMultithreadWindows *ArchMultithreadWindows::getInstance() +{ return s_instance; } -ArchCond ArchMultithreadWindows::newCondVar() { +ArchCond ArchMultithreadWindows::newCondVar() +{ ArchCondImpl *cond = new ArchCondImpl; cond->m_events[ArchCondImpl::kSignal] = CreateEvent(NULL, FALSE, FALSE, NULL); - cond->m_events[ArchCondImpl::kBroadcast] = - CreateEvent(NULL, TRUE, FALSE, NULL); + cond->m_events[ArchCondImpl::kBroadcast] = CreateEvent(NULL, TRUE, FALSE, NULL); cond->m_waitCountMutex = newMutex(); cond->m_waitCount = 0; return cond; } -void ArchMultithreadWindows::closeCondVar(ArchCond cond) { +void ArchMultithreadWindows::closeCondVar(ArchCond cond) +{ CloseHandle(cond->m_events[ArchCondImpl::kSignal]); CloseHandle(cond->m_events[ArchCondImpl::kBroadcast]); closeMutex(cond->m_waitCountMutex); delete cond; } -void ArchMultithreadWindows::signalCondVar(ArchCond cond) { +void ArchMultithreadWindows::signalCondVar(ArchCond cond) +{ // is anybody waiting? lockMutex(cond->m_waitCountMutex); const bool hasWaiter = (cond->m_waitCount > 0); @@ -171,7 +181,8 @@ void ArchMultithreadWindows::signalCondVar(ArchCond cond) { } } -void ArchMultithreadWindows::broadcastCondVar(ArchCond cond) { +void ArchMultithreadWindows::broadcastCondVar(ArchCond cond) +{ // is anybody waiting? lockMutex(cond->m_waitCountMutex); const bool hasWaiter = (cond->m_waitCount > 0); @@ -183,11 +194,10 @@ void ArchMultithreadWindows::broadcastCondVar(ArchCond cond) { } } -bool ArchMultithreadWindows::waitCondVar( - ArchCond cond, ArchMutex mutex, double timeout) { +bool ArchMultithreadWindows::waitCondVar(ArchCond cond, ArchMutex mutex, double timeout) +{ // prepare to wait - const DWORD winTimeout = - (timeout < 0.0) ? INFINITE : static_cast(1000.0 * timeout); + const DWORD winTimeout = (timeout < 0.0) ? INFINITE : static_cast(1000.0 * timeout); // make a list of the condition variable events and the cancel event // for the current thread. @@ -212,8 +222,7 @@ bool ArchMultithreadWindows::waitCondVar( DWORD result = WaitForMultipleObjects(3, handles, FALSE, winTimeout); // cancel takes priority - if (result != WAIT_OBJECT_0 + 2 && - WaitForSingleObject(handles[2], 0) == WAIT_OBJECT_0) { + if (result != WAIT_OBJECT_0 + 2 && WaitForSingleObject(handles[2], 0) == WAIT_OBJECT_0) { result = WAIT_OBJECT_0 + 2; } @@ -240,26 +249,31 @@ bool ArchMultithreadWindows::waitCondVar( return (result == WAIT_OBJECT_0 + 0 || result == WAIT_OBJECT_0 + 1); } -ArchMutex ArchMultithreadWindows::newMutex() { +ArchMutex ArchMultithreadWindows::newMutex() +{ ArchMutexImpl *mutex = new ArchMutexImpl; InitializeCriticalSection(&mutex->m_mutex); return mutex; } -void ArchMultithreadWindows::closeMutex(ArchMutex mutex) { +void ArchMultithreadWindows::closeMutex(ArchMutex mutex) +{ DeleteCriticalSection(&mutex->m_mutex); delete mutex; } -void ArchMultithreadWindows::lockMutex(ArchMutex mutex) { +void ArchMultithreadWindows::lockMutex(ArchMutex mutex) +{ EnterCriticalSection(&mutex->m_mutex); } -void ArchMultithreadWindows::unlockMutex(ArchMutex mutex) { +void ArchMultithreadWindows::unlockMutex(ArchMutex mutex) +{ LeaveCriticalSection(&mutex->m_mutex); } -ArchThread ArchMultithreadWindows::newThread(ThreadFunc func, void *data) { +ArchThread ArchMultithreadWindows::newThread(ThreadFunc func, void *data) +{ lockMutex(m_threadMutex); // create thread impl for new thread @@ -269,8 +283,7 @@ ArchThread ArchMultithreadWindows::newThread(ThreadFunc func, void *data) { // create thread unsigned int id = 0; - thread->m_thread = reinterpret_cast( - _beginthreadex(NULL, 0, threadFunc, (void *)thread, 0, &id)); + thread->m_thread = reinterpret_cast(_beginthreadex(NULL, 0, threadFunc, (void *)thread, 0, &id)); thread->m_id = static_cast(id); // check if thread was started @@ -292,7 +305,8 @@ ArchThread ArchMultithreadWindows::newThread(ThreadFunc func, void *data) { return thread; } -ArchThread ArchMultithreadWindows::newCurrentThread() { +ArchThread ArchMultithreadWindows::newCurrentThread() +{ lockMutex(m_threadMutex); ArchThreadImpl *thread = find(GetCurrentThreadId()); unlockMutex(m_threadMutex); @@ -300,7 +314,8 @@ ArchThread ArchMultithreadWindows::newCurrentThread() { return thread; } -void ArchMultithreadWindows::closeThread(ArchThread thread) { +void ArchMultithreadWindows::closeThread(ArchThread thread) +{ assert(thread != NULL); // decrement ref count and clean up thread if no more references @@ -321,20 +336,24 @@ void ArchMultithreadWindows::closeThread(ArchThread thread) { } } -ArchThread ArchMultithreadWindows::copyThread(ArchThread thread) { +ArchThread ArchMultithreadWindows::copyThread(ArchThread thread) +{ refThread(thread); return thread; } -void ArchMultithreadWindows::cancelThread(ArchThread thread) { +void ArchMultithreadWindows::cancelThread(ArchThread thread) +{ assert(thread != NULL); // set cancel flag SetEvent(thread->m_cancel); } -void ArchMultithreadWindows::setPriorityOfThread(ArchThread thread, int n) { - struct PriorityInfo { +void ArchMultithreadWindows::setPriorityOfThread(ArchThread thread, int n) +{ + struct PriorityInfo + { public: DWORD m_class; int m_level; @@ -362,7 +381,8 @@ void ArchMultithreadWindows::setPriorityOfThread(ArchThread thread, int n) { {REALTIME_PRIORITY_CLASS, THREAD_PRIORITY_NORMAL}, {REALTIME_PRIORITY_CLASS, THREAD_PRIORITY_ABOVE_NORMAL}, {REALTIME_PRIORITY_CLASS, THREAD_PRIORITY_HIGHEST}, - {REALTIME_PRIORITY_CLASS, THREAD_PRIORITY_TIME_CRITICAL}}; + {REALTIME_PRIORITY_CLASS, THREAD_PRIORITY_TIME_CRITICAL} + }; #if defined(_DEBUG) // don't use really high priorities when debugging static const size_t s_pMax = 13; @@ -388,7 +408,8 @@ void ArchMultithreadWindows::setPriorityOfThread(ArchThread thread, int n) { SetThreadPriority(thread->m_thread, s_pClass[index].m_level); } -void ArchMultithreadWindows::testCancelThread() { +void ArchMultithreadWindows::testCancelThread() +{ // find current thread lockMutex(m_threadMutex); ArchThreadImpl *thread = findNoRef(GetCurrentThreadId()); @@ -398,7 +419,8 @@ void ArchMultithreadWindows::testCancelThread() { testCancelThreadImpl(thread); } -bool ArchMultithreadWindows::wait(ArchThread target, double timeout) { +bool ArchMultithreadWindows::wait(ArchThread target, double timeout) +{ assert(target != NULL); lockMutex(m_threadMutex); @@ -433,8 +455,7 @@ bool ArchMultithreadWindows::wait(ArchThread target, double timeout) { DWORD result = WaitForMultipleObjects(2, handles, FALSE, t); // cancel takes priority - if (result != WAIT_OBJECT_0 + 1 && - WaitForSingleObject(handles[1], 0) == WAIT_OBJECT_0) { + if (result != WAIT_OBJECT_0 + 1 && WaitForSingleObject(handles[1], 0) == WAIT_OBJECT_0) { result = WAIT_OBJECT_0 + 1; } @@ -457,37 +478,40 @@ bool ArchMultithreadWindows::wait(ArchThread target, double timeout) { } } -bool ArchMultithreadWindows::isSameThread( - ArchThread thread1, ArchThread thread2) { +bool ArchMultithreadWindows::isSameThread(ArchThread thread1, ArchThread thread2) +{ return (thread1 == thread2); } -bool ArchMultithreadWindows::isExitedThread(ArchThread thread) { +bool ArchMultithreadWindows::isExitedThread(ArchThread thread) +{ // poll exit event return (WaitForSingleObject(thread->m_exit, 0) == WAIT_OBJECT_0); } -void *ArchMultithreadWindows::getResultOfThread(ArchThread thread) { +void *ArchMultithreadWindows::getResultOfThread(ArchThread thread) +{ lockMutex(m_threadMutex); void *result = thread->m_result; unlockMutex(m_threadMutex); return result; } -IArchMultithread::ThreadID -ArchMultithreadWindows::getIDOfThread(ArchThread thread) { +IArchMultithread::ThreadID ArchMultithreadWindows::getIDOfThread(ArchThread thread) +{ return static_cast(thread->m_id); } -void ArchMultithreadWindows::setSignalHandler( - ESignal signal, SignalFunc func, void *userData) { +void ArchMultithreadWindows::setSignalHandler(ESignal signal, SignalFunc func, void *userData) +{ lockMutex(m_threadMutex); m_signalFunc[signal] = func; m_signalUserData[signal] = userData; unlockMutex(m_threadMutex); } -void ArchMultithreadWindows::raiseSignal(ESignal signal) { +void ArchMultithreadWindows::raiseSignal(ESignal signal) +{ lockMutex(m_threadMutex); if (m_signalFunc[signal] != NULL) { m_signalFunc[signal](signal, m_signalUserData[signal]); @@ -498,7 +522,8 @@ void ArchMultithreadWindows::raiseSignal(ESignal signal) { unlockMutex(m_threadMutex); } -ArchThreadImpl *ArchMultithreadWindows::find(DWORD id) { +ArchThreadImpl *ArchMultithreadWindows::find(DWORD id) +{ ArchThreadImpl *impl = findNoRef(id); if (impl != NULL) { refThread(impl); @@ -506,7 +531,8 @@ ArchThreadImpl *ArchMultithreadWindows::find(DWORD id) { return impl; } -ArchThreadImpl *ArchMultithreadWindows::findNoRef(DWORD id) { +ArchThreadImpl *ArchMultithreadWindows::findNoRef(DWORD id) +{ ArchThreadImpl *impl = findNoRefOrCreate(id); if (impl == NULL) { // create thread for calling thread which isn't in our list and @@ -521,10 +547,10 @@ ArchThreadImpl *ArchMultithreadWindows::findNoRef(DWORD id) { return impl; } -ArchThreadImpl *ArchMultithreadWindows::findNoRefOrCreate(DWORD id) { +ArchThreadImpl *ArchMultithreadWindows::findNoRefOrCreate(DWORD id) +{ // linear search - for (ThreadList::const_iterator index = m_threadList.begin(); - index != m_threadList.end(); ++index) { + for (ThreadList::const_iterator index = m_threadList.begin(); index != m_threadList.end(); ++index) { if ((*index)->m_id == id) { return *index; } @@ -532,7 +558,8 @@ ArchThreadImpl *ArchMultithreadWindows::findNoRefOrCreate(DWORD id) { return NULL; } -void ArchMultithreadWindows::insert(ArchThreadImpl *thread) { +void ArchMultithreadWindows::insert(ArchThreadImpl *thread) +{ assert(thread != NULL); // thread shouldn't already be on the list @@ -542,9 +569,9 @@ void ArchMultithreadWindows::insert(ArchThreadImpl *thread) { m_threadList.push_back(thread); } -void ArchMultithreadWindows::erase(ArchThreadImpl *thread) { - for (ThreadList::iterator index = m_threadList.begin(); - index != m_threadList.end(); ++index) { +void ArchMultithreadWindows::erase(ArchThreadImpl *thread) +{ + for (ThreadList::iterator index = m_threadList.begin(); index != m_threadList.end(); ++index) { if (*index == thread) { m_threadList.erase(index); break; @@ -552,13 +579,15 @@ void ArchMultithreadWindows::erase(ArchThreadImpl *thread) { } } -void ArchMultithreadWindows::refThread(ArchThreadImpl *thread) { +void ArchMultithreadWindows::refThread(ArchThreadImpl *thread) +{ assert(thread != NULL); assert(findNoRefOrCreate(thread->m_id) != NULL); ++thread->m_refCount; } -void ArchMultithreadWindows::testCancelThreadImpl(ArchThreadImpl *thread) { +void ArchMultithreadWindows::testCancelThreadImpl(ArchThreadImpl *thread) +{ assert(thread != NULL); // poll cancel event. return if not set. @@ -580,7 +609,8 @@ void ArchMultithreadWindows::testCancelThreadImpl(ArchThreadImpl *thread) { } } -unsigned int __stdcall ArchMultithreadWindows::threadFunc(void *vrep) { +unsigned int __stdcall ArchMultithreadWindows::threadFunc(void *vrep) +{ // get the thread ArchThreadImpl *thread = static_cast(vrep); @@ -591,7 +621,8 @@ unsigned int __stdcall ArchMultithreadWindows::threadFunc(void *vrep) { return 0; } -void ArchMultithreadWindows::doThreadFunc(ArchThread thread) { +void ArchMultithreadWindows::doThreadFunc(ArchThread thread) +{ // wait for parent to initialize this object lockMutex(m_threadMutex); unlockMutex(m_threadMutex); diff --git a/src/lib/arch/win32/ArchMultithreadWindows.h b/src/lib/arch/win32/ArchMultithreadWindows.h index 474d4419f..4099adcdd 100644 --- a/src/lib/arch/win32/ArchMultithreadWindows.h +++ b/src/lib/arch/win32/ArchMultithreadWindows.h @@ -26,22 +26,29 @@ #define ARCH_MULTITHREAD ArchMultithreadWindows -class ArchCondImpl { +class ArchCondImpl +{ public: - enum { kSignal = 0, kBroadcast }; + enum + { + kSignal = 0, + kBroadcast + }; HANDLE m_events[2]; mutable int m_waitCount; ArchMutex m_waitCountMutex; }; -class ArchMutexImpl { +class ArchMutexImpl +{ public: CRITICAL_SECTION m_mutex; }; //! Win32 implementation of IArchMultithread -class ArchMultithreadWindows : public IArchMultithread { +class ArchMultithreadWindows : public IArchMultithread +{ public: ArchMultithreadWindows(); virtual ~ArchMultithreadWindows(); diff --git a/src/lib/arch/win32/ArchNetworkWinsock.cpp b/src/lib/arch/win32/ArchNetworkWinsock.cpp index 29629a12d..2623e99db 100644 --- a/src/lib/arch/win32/ArchNetworkWinsock.cpp +++ b/src/lib/arch/win32/ArchNetworkWinsock.cpp @@ -31,38 +31,29 @@ static const int s_family[] = { }; static const int s_type[] = {SOCK_DGRAM, SOCK_STREAM}; -static SOCKET(PASCAL FAR *accept_winsock)( - SOCKET s, struct sockaddr FAR *addr, int FAR *addrlen); -static int(PASCAL FAR *bind_winsock)( - SOCKET s, const struct sockaddr FAR *addr, int namelen); +static SOCKET(PASCAL FAR *accept_winsock)(SOCKET s, struct sockaddr FAR *addr, int FAR *addrlen); +static int(PASCAL FAR *bind_winsock)(SOCKET s, const struct sockaddr FAR *addr, int namelen); static int(PASCAL FAR *close_winsock)(SOCKET s); -static int(PASCAL FAR *connect_winsock)( - SOCKET s, const struct sockaddr FAR *name, int namelen); +static int(PASCAL FAR *connect_winsock)(SOCKET s, const struct sockaddr FAR *name, int namelen); static int(PASCAL FAR *gethostname_winsock)(char FAR *name, int namelen); static int(PASCAL FAR *getsockerror_winsock)(void); -static int(PASCAL FAR *getsockopt_winsock)( - SOCKET s, int level, int optname, void FAR *optval, int FAR *optlen); +static int(PASCAL FAR *getsockopt_winsock)(SOCKET s, int level, int optname, void FAR *optval, int FAR *optlen); static u_short(PASCAL FAR *htons_winsock)(u_short v); static char FAR *(PASCAL FAR *inet_ntoa_winsock)(struct in_addr in); static unsigned long(PASCAL FAR *inet_addr_winsock)(const char FAR *cp); static int(PASCAL FAR *ioctl_winsock)(SOCKET s, int cmd, void FAR *data); static int(PASCAL FAR *listen_winsock)(SOCKET s, int backlog); static u_short(PASCAL FAR *ntohs_winsock)(u_short v); -static int(PASCAL FAR *recv_winsock)( - SOCKET s, void FAR *buf, int len, int flags); +static int(PASCAL FAR *recv_winsock)(SOCKET s, void FAR *buf, int len, int flags); static int(PASCAL FAR *select_winsock)( - int nfds, fd_set FAR *readfds, fd_set FAR *writefds, fd_set FAR *exceptfds, - const struct timeval FAR *timeout); -static int(PASCAL FAR *send_winsock)( - SOCKET s, const void FAR *buf, int len, int flags); -static int(PASCAL FAR *setsockopt_winsock)( - SOCKET s, int level, int optname, const void FAR *optval, int optlen); + int nfds, fd_set FAR *readfds, fd_set FAR *writefds, fd_set FAR *exceptfds, const struct timeval FAR *timeout +); +static int(PASCAL FAR *send_winsock)(SOCKET s, const void FAR *buf, int len, int flags); +static int(PASCAL FAR *setsockopt_winsock)(SOCKET s, int level, int optname, const void FAR *optval, int optlen); static int(PASCAL FAR *shutdown_winsock)(SOCKET s, int how); static SOCKET(PASCAL FAR *socket_winsock)(int af, int type, int protocol); -static struct hostent FAR *(PASCAL FAR *gethostbyaddr_winsock)( - const char FAR *addr, int len, int type); -static struct hostent FAR *(PASCAL FAR *gethostbyname_winsock)( - const char FAR *name); +static struct hostent FAR *(PASCAL FAR *gethostbyaddr_winsock)(const char FAR *addr, int len, int type); +static struct hostent FAR *(PASCAL FAR *gethostbyname_winsock)(const char FAR *name); static int(PASCAL FAR *WSACleanup_winsock)(void); static int(PASCAL FAR *WSAFDIsSet_winsock)(SOCKET, fd_set FAR *fdset); static WSAEVENT(PASCAL FAR *WSACreateEvent_winsock)(void); @@ -70,10 +61,8 @@ static BOOL(PASCAL FAR *WSACloseEvent_winsock)(WSAEVENT); static BOOL(PASCAL FAR *WSASetEvent_winsock)(WSAEVENT); static BOOL(PASCAL FAR *WSAResetEvent_winsock)(WSAEVENT); static int(PASCAL FAR *WSAEventSelect_winsock)(SOCKET, WSAEVENT, long); -static DWORD(PASCAL FAR *WSAWaitForMultipleEvents_winsock)( - DWORD, const WSAEVENT FAR *, BOOL, DWORD, BOOL); -static int(PASCAL FAR *WSAEnumNetworkEvents_winsock)( - SOCKET, WSAEVENT, LPWSANETWORKEVENTS); +static DWORD(PASCAL FAR *WSAWaitForMultipleEvents_winsock)(DWORD, const WSAEVENT FAR *, BOOL, DWORD, BOOL); +static int(PASCAL FAR *WSAEnumNetworkEvents_winsock)(SOCKET, WSAEVENT, LPWSANETWORKEVENTS); #undef FD_ISSET #define FD_ISSET(fd, set) WSAFDIsSet_winsock((SOCKET)(fd), (fd_set FAR *)(set)) @@ -82,7 +71,8 @@ static int(PASCAL FAR *WSAEnumNetworkEvents_winsock)( static HMODULE s_networkModule = NULL; -static FARPROC netGetProcAddress(HMODULE module, LPCSTR name) { +static FARPROC netGetProcAddress(HMODULE module, LPCSTR name) +{ FARPROC func = ::GetProcAddress(module, name); if (!func) { throw XArchNetworkSupport(""); @@ -90,7 +80,8 @@ static FARPROC netGetProcAddress(HMODULE module, LPCSTR name) { return func; } -ArchNetAddressImpl *ArchNetAddressImpl::alloc(size_t size) { +ArchNetAddressImpl *ArchNetAddressImpl::alloc(size_t size) +{ size_t totalSize = size + ADDR_HDR_SIZE; ArchNetAddressImpl *addr = (ArchNetAddressImpl *)malloc(totalSize); addr->m_len = (int)size; @@ -101,9 +92,12 @@ ArchNetAddressImpl *ArchNetAddressImpl::alloc(size_t size) { // ArchNetworkWinsock // -ArchNetworkWinsock::ArchNetworkWinsock() : m_mutex(NULL) {} +ArchNetworkWinsock::ArchNetworkWinsock() : m_mutex(NULL) +{ +} -ArchNetworkWinsock::~ArchNetworkWinsock() { +ArchNetworkWinsock::~ArchNetworkWinsock() +{ if (s_networkModule != NULL) { WSACleanup_winsock(); ::FreeLibrary(s_networkModule); @@ -121,7 +115,8 @@ ArchNetworkWinsock::~ArchNetworkWinsock() { } } -void ArchNetworkWinsock::init() { +void ArchNetworkWinsock::init() +{ static const char *s_library[] = {"ws2_32.dll"}; assert(WSACleanup_winsock == NULL); @@ -142,7 +137,8 @@ void ArchNetworkWinsock::init() { throw XArchNetworkSupport("Cannot load winsock library"); } -void ArchNetworkWinsock::initModule(HMODULE module) { +void ArchNetworkWinsock::initModule(HMODULE module) +{ if (module == NULL) { throw XArchNetworkSupport(""); } @@ -164,89 +160,58 @@ void ArchNetworkWinsock::initModule(HMODULE module) { } // get function addresses - setfunc( - accept_winsock, accept, - SOCKET(PASCAL FAR *)( - SOCKET s, struct sockaddr FAR * addr, int FAR *addrlen)); - setfunc( - bind_winsock, bind, - int(PASCAL FAR *)( - SOCKET s, const struct sockaddr FAR *addr, int namelen)); + setfunc(accept_winsock, accept, SOCKET(PASCAL FAR *)(SOCKET s, struct sockaddr FAR * addr, int FAR *addrlen)); + setfunc(bind_winsock, bind, int(PASCAL FAR *)(SOCKET s, const struct sockaddr FAR *addr, int namelen)); setfunc(close_winsock, closesocket, int(PASCAL FAR *)(SOCKET s)); - setfunc( - connect_winsock, connect, - int(PASCAL FAR *)( - SOCKET s, const struct sockaddr FAR *name, int namelen)); - setfunc( - gethostname_winsock, gethostname, - int(PASCAL FAR *)(char FAR *name, int namelen)); + setfunc(connect_winsock, connect, int(PASCAL FAR *)(SOCKET s, const struct sockaddr FAR *name, int namelen)); + setfunc(gethostname_winsock, gethostname, int(PASCAL FAR *)(char FAR *name, int namelen)); setfunc(getsockerror_winsock, WSAGetLastError, int(PASCAL FAR *)(void)); setfunc( getsockopt_winsock, getsockopt, - int(PASCAL FAR *)( - SOCKET s, int level, int optname, void FAR *optval, int FAR *optlen)); + int(PASCAL FAR *)(SOCKET s, int level, int optname, void FAR *optval, int FAR *optlen) + ); setfunc(htons_winsock, htons, u_short(PASCAL FAR *)(u_short v)); - setfunc( - inet_ntoa_winsock, inet_ntoa, - char FAR *(PASCAL FAR *)(struct in_addr in)); - setfunc( - inet_addr_winsock, inet_addr, - unsigned long(PASCAL FAR *)(const char FAR *cp)); - setfunc( - ioctl_winsock, ioctlsocket, - int(PASCAL FAR *)(SOCKET s, int cmd, void FAR *)); + setfunc(inet_ntoa_winsock, inet_ntoa, char FAR *(PASCAL FAR *)(struct in_addr in)); + setfunc(inet_addr_winsock, inet_addr, unsigned long(PASCAL FAR *)(const char FAR *cp)); + setfunc(ioctl_winsock, ioctlsocket, int(PASCAL FAR *)(SOCKET s, int cmd, void FAR *)); setfunc(listen_winsock, listen, int(PASCAL FAR *)(SOCKET s, int backlog)); setfunc(ntohs_winsock, ntohs, u_short(PASCAL FAR *)(u_short v)); - setfunc( - recv_winsock, recv, - int(PASCAL FAR *)(SOCKET s, void FAR *buf, int len, int flags)); + setfunc(recv_winsock, recv, int(PASCAL FAR *)(SOCKET s, void FAR *buf, int len, int flags)); setfunc( select_winsock, select, int(PASCAL FAR *)( - int nfds, fd_set FAR *readfds, fd_set FAR *writefds, - fd_set FAR *exceptfds, const struct timeval FAR *timeout)); - setfunc( - send_winsock, send, - int(PASCAL FAR *)(SOCKET s, const void FAR *buf, int len, int flags)); + int nfds, fd_set FAR *readfds, fd_set FAR *writefds, fd_set FAR *exceptfds, const struct timeval FAR *timeout + ) + ); + setfunc(send_winsock, send, int(PASCAL FAR *)(SOCKET s, const void FAR *buf, int len, int flags)); setfunc( setsockopt_winsock, setsockopt, - int(PASCAL FAR *)( - SOCKET s, int level, int optname, const void FAR *optval, - int optlen)); + int(PASCAL FAR *)(SOCKET s, int level, int optname, const void FAR *optval, int optlen) + ); setfunc(shutdown_winsock, shutdown, int(PASCAL FAR *)(SOCKET s, int how)); + setfunc(socket_winsock, socket, SOCKET(PASCAL FAR *)(int af, int type, int protocol)); setfunc( - socket_winsock, socket, - SOCKET(PASCAL FAR *)(int af, int type, int protocol)); - setfunc( - gethostbyaddr_winsock, gethostbyaddr, - struct hostent FAR * - (PASCAL FAR *)(const char FAR *addr, int len, int type)); - setfunc( - gethostbyname_winsock, gethostbyname, - struct hostent FAR * (PASCAL FAR *)(const char FAR *name)); + gethostbyaddr_winsock, gethostbyaddr, struct hostent FAR * (PASCAL FAR *)(const char FAR *addr, int len, int type) + ); + setfunc(gethostbyname_winsock, gethostbyname, struct hostent FAR * (PASCAL FAR *)(const char FAR *name)); setfunc(WSACleanup_winsock, WSACleanup, int(PASCAL FAR *)(void)); - setfunc( - WSAFDIsSet_winsock, __WSAFDIsSet, - int(PASCAL FAR *)(SOCKET, fd_set FAR *)); + setfunc(WSAFDIsSet_winsock, __WSAFDIsSet, int(PASCAL FAR *)(SOCKET, fd_set FAR *)); setfunc(WSACreateEvent_winsock, WSACreateEvent, WSAEVENT(PASCAL FAR *)(void)); setfunc(WSACloseEvent_winsock, WSACloseEvent, BOOL(PASCAL FAR *)(WSAEVENT)); setfunc(WSASetEvent_winsock, WSASetEvent, BOOL(PASCAL FAR *)(WSAEVENT)); setfunc(WSAResetEvent_winsock, WSAResetEvent, BOOL(PASCAL FAR *)(WSAEVENT)); - setfunc( - WSAEventSelect_winsock, WSAEventSelect, - int(PASCAL FAR *)(SOCKET, WSAEVENT, long)); + setfunc(WSAEventSelect_winsock, WSAEventSelect, int(PASCAL FAR *)(SOCKET, WSAEVENT, long)); setfunc( WSAWaitForMultipleEvents_winsock, WSAWaitForMultipleEvents, - DWORD(PASCAL FAR *)(DWORD, const WSAEVENT FAR *, BOOL, DWORD, BOOL)); - setfunc( - WSAEnumNetworkEvents_winsock, WSAEnumNetworkEvents, - int(PASCAL FAR *)(SOCKET, WSAEVENT, LPWSANETWORKEVENTS)); + DWORD(PASCAL FAR *)(DWORD, const WSAEVENT FAR *, BOOL, DWORD, BOOL) + ); + setfunc(WSAEnumNetworkEvents_winsock, WSAEnumNetworkEvents, int(PASCAL FAR *)(SOCKET, WSAEVENT, LPWSANETWORKEVENTS)); s_networkModule = module; } -ArchSocket -ArchNetworkWinsock::newSocket(EAddressFamily family, ESocketType type) { +ArchSocket ArchNetworkWinsock::newSocket(EAddressFamily family, ESocketType type) +{ // create socket SOCKET fd = socket_winsock(s_family[family], s_type[type], 0); if (fd == INVALID_SOCKET) { @@ -256,8 +221,7 @@ ArchNetworkWinsock::newSocket(EAddressFamily family, ESocketType type) { setBlockingOnSocket(fd, false); BOOL flag = 0; int size = sizeof(flag); - if (setsockopt_winsock(fd, IPPROTO_IPV6, IPV6_V6ONLY, &flag, size) == - SOCKET_ERROR) { + if (setsockopt_winsock(fd, IPPROTO_IPV6, IPV6_V6ONLY, &flag, size) == SOCKET_ERROR) { throwError(getsockerror_winsock()); } } catch (...) { @@ -274,7 +238,8 @@ ArchNetworkWinsock::newSocket(EAddressFamily family, ESocketType type) { return socket; } -ArchSocket ArchNetworkWinsock::copySocket(ArchSocket s) { +ArchSocket ArchNetworkWinsock::copySocket(ArchSocket s) +{ assert(s != NULL); // ref the socket and return it @@ -284,7 +249,8 @@ ArchSocket ArchNetworkWinsock::copySocket(ArchSocket s) { return s; } -void ArchNetworkWinsock::closeSocket(ArchSocket s) { +void ArchNetworkWinsock::closeSocket(ArchSocket s) +{ assert(s != NULL); // unref the socket and note if it should be released @@ -307,7 +273,8 @@ void ArchNetworkWinsock::closeSocket(ArchSocket s) { } } -void ArchNetworkWinsock::closeSocketForRead(ArchSocket s) { +void ArchNetworkWinsock::closeSocketForRead(ArchSocket s) +{ assert(s != NULL); if (shutdown_winsock(s->m_socket, SD_RECEIVE) == SOCKET_ERROR) { @@ -317,7 +284,8 @@ void ArchNetworkWinsock::closeSocketForRead(ArchSocket s) { } } -void ArchNetworkWinsock::closeSocketForWrite(ArchSocket s) { +void ArchNetworkWinsock::closeSocketForWrite(ArchSocket s) +{ assert(s != NULL); if (shutdown_winsock(s->m_socket, SD_SEND) == SOCKET_ERROR) { @@ -327,18 +295,18 @@ void ArchNetworkWinsock::closeSocketForWrite(ArchSocket s) { } } -void ArchNetworkWinsock::bindSocket(ArchSocket s, ArchNetAddress addr) { +void ArchNetworkWinsock::bindSocket(ArchSocket s, ArchNetAddress addr) +{ assert(s != NULL); assert(addr != NULL); - if (bind_winsock( - s->m_socket, TYPED_ADDR(struct sockaddr, addr), addr->m_len) == - SOCKET_ERROR) { + if (bind_winsock(s->m_socket, TYPED_ADDR(struct sockaddr, addr), addr->m_len) == SOCKET_ERROR) { throwError(getsockerror_winsock()); } } -void ArchNetworkWinsock::listenOnSocket(ArchSocket s) { +void ArchNetworkWinsock::listenOnSocket(ArchSocket s) +{ assert(s != NULL); // hardcoding backlog @@ -347,8 +315,8 @@ void ArchNetworkWinsock::listenOnSocket(ArchSocket s) { } } -ArchSocket -ArchNetworkWinsock::acceptSocket(ArchSocket s, ArchNetAddress *const addr) { +ArchSocket ArchNetworkWinsock::acceptSocket(ArchSocket s, ArchNetAddress *const addr) +{ assert(s != NULL); // create new socket and temporary address @@ -356,8 +324,7 @@ ArchNetworkWinsock::acceptSocket(ArchSocket s, ArchNetAddress *const addr) { ArchNetAddress tmp = ArchNetAddressImpl::alloc(sizeof(struct sockaddr_in6)); // accept on socket - SOCKET fd = accept_winsock( - s->m_socket, TYPED_ADDR(struct sockaddr, tmp), &tmp->m_len); + SOCKET fd = accept_winsock(s->m_socket, TYPED_ADDR(struct sockaddr, tmp), &tmp->m_len); if (fd == INVALID_SOCKET) { int err = getsockerror_winsock(); delete socket; @@ -398,13 +365,12 @@ ArchNetworkWinsock::acceptSocket(ArchSocket s, ArchNetAddress *const addr) { return socket; } -bool ArchNetworkWinsock::connectSocket(ArchSocket s, ArchNetAddress addr) { +bool ArchNetworkWinsock::connectSocket(ArchSocket s, ArchNetAddress addr) +{ assert(s != NULL); assert(addr != NULL); - if (connect_winsock( - s->m_socket, TYPED_ADDR(struct sockaddr, addr), addr->m_len) == - SOCKET_ERROR) { + if (connect_winsock(s->m_socket, TYPED_ADDR(struct sockaddr, addr), addr->m_len) == SOCKET_ERROR) { if (getsockerror_winsock() == WSAEISCONN) { return true; } @@ -416,7 +382,8 @@ bool ArchNetworkWinsock::connectSocket(ArchSocket s, ArchNetAddress addr) { return true; } -int ArchNetworkWinsock::pollSocket(PollEntry pe[], int num, double timeout) { +int ArchNetworkWinsock::pollSocket(PollEntry pe[], int num, double timeout) +{ int i; DWORD n; @@ -456,8 +423,7 @@ int ArchNetworkWinsock::pollSocket(PollEntry pe[], int num, double timeout) { } // select socket for desired events - WSAEventSelect_winsock( - pe[i].m_socket->m_socket, pe[i].m_socket->m_event, socketEvents); + WSAEventSelect_winsock(pe[i].m_socket->m_socket, pe[i].m_socket->m_event, socketEvents); // add socket event to wait list events[n++] = pe[i].m_socket->m_event; @@ -512,16 +478,13 @@ int ArchNetworkWinsock::pollSocket(PollEntry pe[], int num, double timeout) { } for (i = 0, n = 0; i < num; ++i) { // skip events we didn't check - if (pe[i].m_socket == NULL || - (pe[i].m_events & (kPOLLIN | kPOLLOUT)) == 0) { + if (pe[i].m_socket == NULL || (pe[i].m_events & (kPOLLIN | kPOLLOUT)) == 0) { continue; } // get events WSANETWORKEVENTS info; - if (WSAEnumNetworkEvents_winsock( - pe[i].m_socket->m_socket, pe[i].m_socket->m_event, &info) == - SOCKET_ERROR) { + if (WSAEnumNetworkEvents_winsock(pe[i].m_socket->m_socket, pe[i].m_socket->m_event, &info) == SOCKET_ERROR) { continue; } if ((info.lNetworkEvents & FD_READ) != 0) { @@ -565,7 +528,8 @@ int ArchNetworkWinsock::pollSocket(PollEntry pe[], int num, double timeout) { return (int)n; } -void ArchNetworkWinsock::unblockPollSocket(ArchThread thread) { +void ArchNetworkWinsock::unblockPollSocket(ArchThread thread) +{ // set the unblock event ArchMultithreadWindows *mt = ArchMultithreadWindows::getInstance(); WSAEVENT *unblockEvent = (WSAEVENT *)mt->getNetworkDataForThread(thread); @@ -574,7 +538,8 @@ void ArchNetworkWinsock::unblockPollSocket(ArchThread thread) { } } -size_t ArchNetworkWinsock::readSocket(ArchSocket s, void *buf, size_t len) { +size_t ArchNetworkWinsock::readSocket(ArchSocket s, void *buf, size_t len) +{ assert(s != NULL); int n = recv_winsock(s->m_socket, buf, (int)len, 0); @@ -588,8 +553,8 @@ size_t ArchNetworkWinsock::readSocket(ArchSocket s, void *buf, size_t len) { return static_cast(n); } -size_t -ArchNetworkWinsock::writeSocket(ArchSocket s, const void *buf, size_t len) { +size_t ArchNetworkWinsock::writeSocket(ArchSocket s, const void *buf, size_t len) +{ assert(s != NULL); int n = send_winsock(s->m_socket, buf, (int)len, 0); @@ -607,14 +572,14 @@ ArchNetworkWinsock::writeSocket(ArchSocket s, const void *buf, size_t len) { return static_cast(n); } -void ArchNetworkWinsock::throwErrorOnSocket(ArchSocket s) { +void ArchNetworkWinsock::throwErrorOnSocket(ArchSocket s) +{ assert(s != NULL); // get the error from the socket layer int err = 0; int size = sizeof(err); - if (getsockopt_winsock(s->m_socket, SOL_SOCKET, SO_ERROR, &err, &size) == - SOCKET_ERROR) { + if (getsockopt_winsock(s->m_socket, SOL_SOCKET, SO_ERROR, &err, &size) == SOCKET_ERROR) { err = getsockerror_winsock(); } @@ -624,7 +589,8 @@ void ArchNetworkWinsock::throwErrorOnSocket(ArchSocket s) { } } -void ArchNetworkWinsock::setBlockingOnSocket(SOCKET s, bool blocking) { +void ArchNetworkWinsock::setBlockingOnSocket(SOCKET s, bool blocking) +{ assert(s != 0); int flag = blocking ? 0 : 1; @@ -633,53 +599,50 @@ void ArchNetworkWinsock::setBlockingOnSocket(SOCKET s, bool blocking) { } } -bool ArchNetworkWinsock::setNoDelayOnSocket(ArchSocket s, bool noDelay) { +bool ArchNetworkWinsock::setNoDelayOnSocket(ArchSocket s, bool noDelay) +{ assert(s != NULL); // get old state BOOL oflag; int size = sizeof(oflag); - if (getsockopt_winsock( - s->m_socket, IPPROTO_TCP, TCP_NODELAY, &oflag, &size) == - SOCKET_ERROR) { + if (getsockopt_winsock(s->m_socket, IPPROTO_TCP, TCP_NODELAY, &oflag, &size) == SOCKET_ERROR) { throwError(getsockerror_winsock()); } // set new state BOOL flag = noDelay ? 1 : 0; size = sizeof(flag); - if (setsockopt_winsock(s->m_socket, IPPROTO_TCP, TCP_NODELAY, &flag, size) == - SOCKET_ERROR) { + if (setsockopt_winsock(s->m_socket, IPPROTO_TCP, TCP_NODELAY, &flag, size) == SOCKET_ERROR) { throwError(getsockerror_winsock()); } return (oflag != 0); } -bool ArchNetworkWinsock::setReuseAddrOnSocket(ArchSocket s, bool reuse) { +bool ArchNetworkWinsock::setReuseAddrOnSocket(ArchSocket s, bool reuse) +{ assert(s != NULL); // get old state BOOL oflag; int size = sizeof(oflag); - if (getsockopt_winsock( - s->m_socket, SOL_SOCKET, SO_REUSEADDR, &oflag, &size) == - SOCKET_ERROR) { + if (getsockopt_winsock(s->m_socket, SOL_SOCKET, SO_REUSEADDR, &oflag, &size) == SOCKET_ERROR) { throwError(getsockerror_winsock()); } // set new state BOOL flag = reuse ? 1 : 0; size = sizeof(flag); - if (setsockopt_winsock(s->m_socket, SOL_SOCKET, SO_REUSEADDR, &flag, size) == - SOCKET_ERROR) { + if (setsockopt_winsock(s->m_socket, SOL_SOCKET, SO_REUSEADDR, &flag, size) == SOCKET_ERROR) { throwError(getsockerror_winsock()); } return (oflag != 0); } -std::string ArchNetworkWinsock::getHostName() { +std::string ArchNetworkWinsock::getHostName() +{ char name[256]; if (gethostname_winsock(name, sizeof(name)) == -1) { name[0] = '\0'; @@ -689,7 +652,8 @@ std::string ArchNetworkWinsock::getHostName() { return name; } -ArchNetAddress ArchNetworkWinsock::newAnyAddr(EAddressFamily family) { +ArchNetAddress ArchNetworkWinsock::newAnyAddr(EAddressFamily family) +{ ArchNetAddressImpl *addr = NULL; switch (family) { case kINET: { @@ -716,7 +680,8 @@ ArchNetAddress ArchNetworkWinsock::newAnyAddr(EAddressFamily family) { return addr; } -ArchNetAddress ArchNetworkWinsock::copyAddr(ArchNetAddress addr) { +ArchNetAddress ArchNetworkWinsock::copyAddr(ArchNetAddress addr) +{ assert(addr != NULL); ArchNetAddressImpl *copy = ArchNetAddressImpl::alloc(addr->m_len); @@ -724,8 +689,8 @@ ArchNetAddress ArchNetworkWinsock::copyAddr(ArchNetAddress addr) { return copy; } -std::vector -ArchNetworkWinsock::nameToAddr(const std::string &name) { +std::vector ArchNetworkWinsock::nameToAddr(const std::string &name) +{ // allocate address std::vector addresses; @@ -749,8 +714,7 @@ ArchNetworkWinsock::nameToAddr(const std::string &name) { addresses.back()->m_len = (socklen_t)sizeof(struct sockaddr_in6); } - memcpy( - &addresses.back()->m_addr, address->ai_addr, addresses.back()->m_len); + memcpy(&addresses.back()->m_addr, address->ai_addr, addresses.back()->m_len); } freeaddrinfo(pResult); @@ -758,20 +722,21 @@ ArchNetworkWinsock::nameToAddr(const std::string &name) { return addresses; } -void ArchNetworkWinsock::closeAddr(ArchNetAddress addr) { +void ArchNetworkWinsock::closeAddr(ArchNetAddress addr) +{ assert(addr != NULL); free(addr); } -std::string ArchNetworkWinsock::addrToName(ArchNetAddress addr) { +std::string ArchNetworkWinsock::addrToName(ArchNetAddress addr) +{ assert(addr != NULL); char host[1024]; char service[20]; - int ret = getnameinfo( - TYPED_ADDR(struct sockaddr, addr), addr->m_len, host, sizeof(host), - service, sizeof(service), 0); + int ret = + getnameinfo(TYPED_ADDR(struct sockaddr, addr), addr->m_len, host, sizeof(host), service, sizeof(service), 0); if (ret != NULL) { throwNameError(ret); @@ -782,7 +747,8 @@ std::string ArchNetworkWinsock::addrToName(ArchNetAddress addr) { return name; } -std::string ArchNetworkWinsock::addrToString(ArchNetAddress addr) { +std::string ArchNetworkWinsock::addrToString(ArchNetAddress addr) +{ assert(addr != NULL); switch (getAddrFamily(addr)) { @@ -804,8 +770,8 @@ std::string ArchNetworkWinsock::addrToString(ArchNetAddress addr) { } } -IArchNetwork::EAddressFamily -ArchNetworkWinsock::getAddrFamily(ArchNetAddress addr) { +IArchNetwork::EAddressFamily ArchNetworkWinsock::getAddrFamily(ArchNetAddress addr) +{ assert(addr != NULL); switch (addr->m_addr.ss_family) { @@ -820,7 +786,8 @@ ArchNetworkWinsock::getAddrFamily(ArchNetAddress addr) { } } -void ArchNetworkWinsock::setAddrPort(ArchNetAddress addr, int port) { +void ArchNetworkWinsock::setAddrPort(ArchNetAddress addr, int port) +{ assert(addr != NULL); switch (getAddrFamily(addr)) { @@ -842,7 +809,8 @@ void ArchNetworkWinsock::setAddrPort(ArchNetAddress addr, int port) { } } -int ArchNetworkWinsock::getAddrPort(ArchNetAddress addr) { +int ArchNetworkWinsock::getAddrPort(ArchNetAddress addr) +{ assert(addr != NULL); switch (getAddrFamily(addr)) { @@ -862,22 +830,21 @@ int ArchNetworkWinsock::getAddrPort(ArchNetAddress addr) { } } -bool ArchNetworkWinsock::isAnyAddr(ArchNetAddress addr) { +bool ArchNetworkWinsock::isAnyAddr(ArchNetAddress addr) +{ assert(addr != NULL); switch (getAddrFamily(addr)) { case kINET: { struct sockaddr_in *ipAddr = TYPED_ADDR(struct sockaddr_in, addr); - return ( - addr->m_len == sizeof(struct sockaddr_in) && - ipAddr->sin_addr.s_addr == INADDR_ANY); + return (addr->m_len == sizeof(struct sockaddr_in) && ipAddr->sin_addr.s_addr == INADDR_ANY); } case kINET6: { struct sockaddr_in6 *ipAddr = TYPED_ADDR(struct sockaddr_in6, addr); return ( - addr->m_len == sizeof(struct sockaddr_in) && - memcmp(&ipAddr->sin6_addr, &in6addr_any, sizeof(in6addr_any)) == 0); + addr->m_len == sizeof(struct sockaddr_in) && memcmp(&ipAddr->sin6_addr, &in6addr_any, sizeof(in6addr_any)) == 0 + ); } default: @@ -886,13 +853,13 @@ bool ArchNetworkWinsock::isAnyAddr(ArchNetAddress addr) { } } -bool ArchNetworkWinsock::isEqualAddr(ArchNetAddress a, ArchNetAddress b) { - return ( - a == b || - (a->m_len == b->m_len && memcmp(&a->m_addr, &b->m_addr, a->m_len) == 0)); +bool ArchNetworkWinsock::isEqualAddr(ArchNetAddress a, ArchNetAddress b) +{ + return (a == b || (a->m_len == b->m_len && memcmp(&a->m_addr, &b->m_addr, a->m_len) == 0)); } -void ArchNetworkWinsock::throwError(int err) { +void ArchNetworkWinsock::throwError(int err) +{ switch (err) { case WSAEACCES: throw XArchNetworkAccess(new XArchEvalWinsock(err)); @@ -961,7 +928,8 @@ void ArchNetworkWinsock::throwError(int err) { } } -void ArchNetworkWinsock::throwNameError(int err) { +void ArchNetworkWinsock::throwNameError(int err) +{ switch (err) { case WSAHOST_NOT_FOUND: throw XArchNetworkNameUnknown(new XArchEvalWinsock(err)); diff --git a/src/lib/arch/win32/ArchNetworkWinsock.h b/src/lib/arch/win32/ArchNetworkWinsock.h index 909c26c2a..f75acfa84 100644 --- a/src/lib/arch/win32/ArchNetworkWinsock.h +++ b/src/lib/arch/win32/ArchNetworkWinsock.h @@ -37,7 +37,8 @@ #define ARCH_NETWORK ArchNetworkWinsock -class ArchSocketImpl { +class ArchSocketImpl +{ public: SOCKET m_socket; int m_refCount; @@ -45,7 +46,8 @@ public: bool m_pollWrite; }; -class ArchNetAddressImpl { +class ArchNetAddressImpl +{ public: static ArchNetAddressImpl *alloc(size_t); @@ -57,7 +59,8 @@ public: #define TYPED_ADDR(type_, addr_) (reinterpret_cast(&addr_->m_addr)) //! Win32 implementation of IArchNetwork -class ArchNetworkWinsock : public IArchNetwork { +class ArchNetworkWinsock : public IArchNetwork +{ public: ArchNetworkWinsock(); virtual ~ArchNetworkWinsock(); diff --git a/src/lib/arch/win32/ArchSleepWindows.cpp b/src/lib/arch/win32/ArchSleepWindows.cpp index cede9bbfe..097aaf16e 100644 --- a/src/lib/arch/win32/ArchSleepWindows.cpp +++ b/src/lib/arch/win32/ArchSleepWindows.cpp @@ -24,15 +24,18 @@ // ArchSleepWindows // -ArchSleepWindows::ArchSleepWindows() { +ArchSleepWindows::ArchSleepWindows() +{ // do nothing } -ArchSleepWindows::~ArchSleepWindows() { +ArchSleepWindows::~ArchSleepWindows() +{ // do nothing } -void ArchSleepWindows::sleep(double timeout) { +void ArchSleepWindows::sleep(double timeout) +{ ARCH->testCancelThread(); if (timeout < 0.0) { return; diff --git a/src/lib/arch/win32/ArchSleepWindows.h b/src/lib/arch/win32/ArchSleepWindows.h index c554b5122..2d99886db 100644 --- a/src/lib/arch/win32/ArchSleepWindows.h +++ b/src/lib/arch/win32/ArchSleepWindows.h @@ -23,7 +23,8 @@ #define ARCH_SLEEP ArchSleepWindows //! Win32 implementation of IArchSleep -class ArchSleepWindows : public IArchSleep { +class ArchSleepWindows : public IArchSleep +{ public: ArchSleepWindows(); virtual ~ArchSleepWindows(); diff --git a/src/lib/arch/win32/ArchStringWindows.cpp b/src/lib/arch/win32/ArchStringWindows.cpp index bbe069279..3ab322929 100644 --- a/src/lib/arch/win32/ArchStringWindows.cpp +++ b/src/lib/arch/win32/ArchStringWindows.cpp @@ -31,10 +31,15 @@ #define ARCH_VSNPRINTF _vsnprintf #include "arch/vsnprintf.h" -ArchStringWindows::ArchStringWindows() {} +ArchStringWindows::ArchStringWindows() +{ +} -ArchStringWindows::~ArchStringWindows() {} +ArchStringWindows::~ArchStringWindows() +{ +} -IArchString::EWideCharEncoding ArchStringWindows::getWideCharEncoding() { +IArchString::EWideCharEncoding ArchStringWindows::getWideCharEncoding() +{ return kUTF16; } diff --git a/src/lib/arch/win32/ArchStringWindows.h b/src/lib/arch/win32/ArchStringWindows.h index d62bd0e61..c6b1f3f8a 100644 --- a/src/lib/arch/win32/ArchStringWindows.h +++ b/src/lib/arch/win32/ArchStringWindows.h @@ -23,7 +23,8 @@ #define ARCH_STRING ArchStringWindows //! Win32 implementation of IArchString -class ArchStringWindows : public IArchString { +class ArchStringWindows : public IArchString +{ public: ArchStringWindows(); virtual ~ArchStringWindows(); diff --git a/src/lib/arch/win32/ArchSystemWindows.cpp b/src/lib/arch/win32/ArchSystemWindows.cpp index 7b1b08e38..0be455c4c 100644 --- a/src/lib/arch/win32/ArchSystemWindows.cpp +++ b/src/lib/arch/win32/ArchSystemWindows.cpp @@ -27,35 +27,35 @@ #include #include -static const char *s_settingsKeyNames[] = { - _T("SOFTWARE"), _T(DESKFLOW_APP_NAME), NULL}; +static const char *s_settingsKeyNames[] = {_T("SOFTWARE"), _T(DESKFLOW_APP_NAME), NULL}; // // ArchSystemWindows // -ArchSystemWindows::ArchSystemWindows() { +ArchSystemWindows::ArchSystemWindows() +{ // do nothing } -ArchSystemWindows::~ArchSystemWindows() { +ArchSystemWindows::~ArchSystemWindows() +{ // do nothing } -std::string ArchSystemWindows::getOSName() const { +std::string ArchSystemWindows::getOSName() const +{ std::string osName("Microsoft Windows "); static const TCHAR *const windowsVersionKeyNames[] = { - _T("SOFTWARE"), _T("Microsoft"), _T("Windows NT"), _T("CurrentVersion"), - NULL}; + _T("SOFTWARE"), _T("Microsoft"), _T("Windows NT"), _T("CurrentVersion"), NULL + }; - HKEY key = - ArchMiscWindows::openKey(HKEY_LOCAL_MACHINE, windowsVersionKeyNames); + HKEY key = ArchMiscWindows::openKey(HKEY_LOCAL_MACHINE, windowsVersionKeyNames); if (key == NULL) { return osName; } - std::string productName = - ArchMiscWindows::readValueString(key, "ProductName"); + std::string productName = ArchMiscWindows::readValueString(key, "ProductName"); if (osName.empty()) { return osName; } @@ -63,7 +63,8 @@ std::string ArchSystemWindows::getOSName() const { return "Microsoft " + productName; } -std::string ArchSystemWindows::getPlatformName() const { +std::string ArchSystemWindows::getPlatformName() const +{ #ifdef _X86_ if (isWOW64()) return "x86 (WOW64)"; @@ -78,7 +79,8 @@ std::string ArchSystemWindows::getPlatformName() const { #endif } -std::string ArchSystemWindows::setting(const std::string &valueName) const { +std::string ArchSystemWindows::setting(const std::string &valueName) const +{ HKEY key = ArchMiscWindows::openKey(HKEY_LOCAL_MACHINE, s_settingsKeyNames); if (key == NULL) return ""; @@ -86,27 +88,26 @@ std::string ArchSystemWindows::setting(const std::string &valueName) const { return ArchMiscWindows::readValueString(key, valueName.c_str()); } -void ArchSystemWindows::setting( - const std::string &valueName, const std::string &valueString) const { +void ArchSystemWindows::setting(const std::string &valueName, const std::string &valueString) const +{ HKEY key = ArchMiscWindows::addKey(HKEY_LOCAL_MACHINE, s_settingsKeyNames); if (key == NULL) throw XArch(std::string("could not access registry key: ") + valueName); ArchMiscWindows::setValue(key, valueName.c_str(), valueString.c_str()); } -bool ArchSystemWindows::isWOW64() const { +bool ArchSystemWindows::isWOW64() const +{ #if WINVER >= _WIN32_WINNT_WINXP typedef BOOL(WINAPI * LPFN_ISWOW64PROCESS)(HANDLE, PBOOL); HMODULE hModule = GetModuleHandle(TEXT("kernel32")); if (!hModule) return FALSE; - LPFN_ISWOW64PROCESS fnIsWow64Process = - (LPFN_ISWOW64PROCESS)GetProcAddress(hModule, "IsWow64Process"); + LPFN_ISWOW64PROCESS fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress(hModule, "IsWow64Process"); BOOL bIsWow64 = FALSE; - if (NULL != fnIsWow64Process && - fnIsWow64Process(GetCurrentProcess(), &bIsWow64) && bIsWow64) { + if (NULL != fnIsWow64Process && fnIsWow64Process(GetCurrentProcess(), &bIsWow64) && bIsWow64) { return true; } #endif diff --git a/src/lib/arch/win32/ArchSystemWindows.h b/src/lib/arch/win32/ArchSystemWindows.h index 99edcb10f..e0c89e76c 100644 --- a/src/lib/arch/win32/ArchSystemWindows.h +++ b/src/lib/arch/win32/ArchSystemWindows.h @@ -23,7 +23,8 @@ #define ARCH_SYSTEM ArchSystemWindows //! Win32 implementation of IArchString -class ArchSystemWindows : public IArchSystem { +class ArchSystemWindows : public IArchSystem +{ public: ArchSystemWindows(); virtual ~ArchSystemWindows(); @@ -32,8 +33,7 @@ public: virtual std::string getOSName() const; virtual std::string getPlatformName() const; virtual std::string setting(const std::string &valueName) const; - virtual void - setting(const std::string &valueName, const std::string &valueString) const; + virtual void setting(const std::string &valueName, const std::string &valueString) const; bool isWOW64() const; }; diff --git a/src/lib/arch/win32/ArchTaskBarWindows.cpp b/src/lib/arch/win32/ArchTaskBarWindows.cpp index 85e2e2858..23de5fd39 100644 --- a/src/lib/arch/win32/ArchTaskBarWindows.cpp +++ b/src/lib/arch/win32/ArchTaskBarWindows.cpp @@ -46,12 +46,14 @@ ArchTaskBarWindows::ArchTaskBarWindows() m_thread(NULL), m_hwnd(NULL), m_taskBarRestart(0), - m_nextID(kFirstReceiverID) { + m_nextID(kFirstReceiverID) +{ // save the singleton instance s_instance = this; } -ArchTaskBarWindows::~ArchTaskBarWindows() { +ArchTaskBarWindows::~ArchTaskBarWindows() +{ if (m_thread != NULL) { PostMessage(m_hwnd, WM_QUIT, 0, 0); ARCH->wait(m_thread, -1.0); @@ -66,7 +68,8 @@ ArchTaskBarWindows::~ArchTaskBarWindows() { s_instance = NULL; } -void ArchTaskBarWindows::init() { +void ArchTaskBarWindows::init() +{ // we need a mutex m_mutex = ARCH->newMutex(); @@ -95,15 +98,18 @@ void ArchTaskBarWindows::init() { ARCH->unlockMutex(m_mutex); } -void ArchTaskBarWindows::addDialog(HWND hwnd) { +void ArchTaskBarWindows::addDialog(HWND hwnd) +{ ArchMiscWindows::addDialog(hwnd); } -void ArchTaskBarWindows::removeDialog(HWND hwnd) { +void ArchTaskBarWindows::removeDialog(HWND hwnd) +{ ArchMiscWindows::removeDialog(hwnd); } -void ArchTaskBarWindows::addReceiver(IArchTaskBarReceiver *receiver) { +void ArchTaskBarWindows::addReceiver(IArchTaskBarReceiver *receiver) +{ // ignore bogus receiver if (receiver == NULL) { return; @@ -125,7 +131,8 @@ void ArchTaskBarWindows::addReceiver(IArchTaskBarReceiver *receiver) { PostMessage(m_hwnd, kAddReceiver, index->second.m_id, 0); } -void ArchTaskBarWindows::removeReceiver(IArchTaskBarReceiver *receiver) { +void ArchTaskBarWindows::removeReceiver(IArchTaskBarReceiver *receiver) +{ // find receiver ReceiverToInfoMap::iterator index = m_receivers.find(receiver); if (index == m_receivers.end()) { @@ -143,7 +150,8 @@ void ArchTaskBarWindows::removeReceiver(IArchTaskBarReceiver *receiver) { m_receivers.erase(index); } -void ArchTaskBarWindows::updateReceiver(IArchTaskBarReceiver *receiver) { +void ArchTaskBarWindows::updateReceiver(IArchTaskBarReceiver *receiver) +{ // find receiver ReceiverToInfoMap::const_iterator index = m_receivers.find(receiver); if (index == m_receivers.end()) { @@ -154,7 +162,8 @@ void ArchTaskBarWindows::updateReceiver(IArchTaskBarReceiver *receiver) { PostMessage(m_hwnd, kUpdateReceiver, index->second.m_id, 0); } -UINT ArchTaskBarWindows::getNextID() { +UINT ArchTaskBarWindows::getNextID() +{ if (m_oldIDs.empty()) { return m_nextID++; } @@ -163,9 +172,13 @@ UINT ArchTaskBarWindows::getNextID() { return id; } -void ArchTaskBarWindows::recycleID(UINT id) { m_oldIDs.push_back(id); } +void ArchTaskBarWindows::recycleID(UINT id) +{ + m_oldIDs.push_back(id); +} -void ArchTaskBarWindows::addIcon(UINT id) { +void ArchTaskBarWindows::addIcon(UINT id) +{ ARCH->lockMutex(m_mutex); CIDToReceiverMap::const_iterator index = m_idTable.find(id); if (index != m_idTable.end()) { @@ -174,13 +187,15 @@ void ArchTaskBarWindows::addIcon(UINT id) { ARCH->unlockMutex(m_mutex); } -void ArchTaskBarWindows::removeIcon(UINT id) { +void ArchTaskBarWindows::removeIcon(UINT id) +{ ARCH->lockMutex(m_mutex); removeIconNoLock(id); ARCH->unlockMutex(m_mutex); } -void ArchTaskBarWindows::updateIcon(UINT id) { +void ArchTaskBarWindows::updateIcon(UINT id) +{ ARCH->lockMutex(m_mutex); CIDToReceiverMap::const_iterator index = m_idTable.find(id); if (index != m_idTable.end()) { @@ -189,26 +204,26 @@ void ArchTaskBarWindows::updateIcon(UINT id) { ARCH->unlockMutex(m_mutex); } -void ArchTaskBarWindows::addAllIcons() { +void ArchTaskBarWindows::addAllIcons() +{ ARCH->lockMutex(m_mutex); - for (ReceiverToInfoMap::const_iterator index = m_receivers.begin(); - index != m_receivers.end(); ++index) { + for (ReceiverToInfoMap::const_iterator index = m_receivers.begin(); index != m_receivers.end(); ++index) { modifyIconNoLock(index, NIM_ADD); } ARCH->unlockMutex(m_mutex); } -void ArchTaskBarWindows::removeAllIcons() { +void ArchTaskBarWindows::removeAllIcons() +{ ARCH->lockMutex(m_mutex); - for (ReceiverToInfoMap::const_iterator index = m_receivers.begin(); - index != m_receivers.end(); ++index) { + for (ReceiverToInfoMap::const_iterator index = m_receivers.begin(); index != m_receivers.end(); ++index) { removeIconNoLock(index->second.m_id); } ARCH->unlockMutex(m_mutex); } -void ArchTaskBarWindows::modifyIconNoLock( - ReceiverToInfoMap::const_iterator index, DWORD taskBarMessage) { +void ArchTaskBarWindows::modifyIconNoLock(ReceiverToInfoMap::const_iterator index, DWORD taskBarMessage) +{ // get receiver UINT id = index->second.m_id; IArchTaskBarReceiver *receiver = index->first; @@ -217,8 +232,7 @@ void ArchTaskBarWindows::modifyIconNoLock( receiver->lock(); // get icon data - HICON icon = static_cast( - const_cast(receiver->getIcon())); + HICON icon = static_cast(const_cast(receiver->getIcon())); // get tool tip std::string toolTip = receiver->getToolTip(); @@ -251,7 +265,8 @@ void ArchTaskBarWindows::modifyIconNoLock( } } -void ArchTaskBarWindows::removeIconNoLock(UINT id) { +void ArchTaskBarWindows::removeIconNoLock(UINT id) +{ NOTIFYICONDATA data; data.cbSize = sizeof(NOTIFYICONDATA); data.hWnd = m_hwnd; @@ -261,8 +276,8 @@ void ArchTaskBarWindows::removeIconNoLock(UINT id) { } } -void ArchTaskBarWindows::handleIconMessage( - IArchTaskBarReceiver *receiver, LPARAM lParam) { +void ArchTaskBarWindows::handleIconMessage(IArchTaskBarReceiver *receiver, LPARAM lParam) +{ // process message switch (lParam) { case WM_LBUTTONDOWN: @@ -290,7 +305,8 @@ void ArchTaskBarWindows::handleIconMessage( } } -bool ArchTaskBarWindows::processDialogs(MSG *msg) { +bool ArchTaskBarWindows::processDialogs(MSG *msg) +{ // only one thread can be in this method on any particular object // at any given time. that's not a problem since only our event // loop calls this method and there's just one of those. @@ -313,8 +329,7 @@ bool ArchTaskBarWindows::processDialogs(MSG *msg) { } // merge added dialogs into the dialog list - for (Dialogs::const_iterator index = m_addedDialogs.begin(); - index != m_addedDialogs.end(); ++index) { + for (Dialogs::const_iterator index = m_addedDialogs.begin(); index != m_addedDialogs.end(); ++index) { m_dialogs.insert(std::make_pair(index->first, index->second)); } m_addedDialogs.clear(); @@ -328,8 +343,7 @@ bool ArchTaskBarWindows::processDialogs(MSG *msg) { // removeDialog() don't change the map itself (just the // values of some elements). ARCH->lockMutex(m_mutex); - for (Dialogs::const_iterator index = m_dialogs.begin(); - index != m_dialogs.end(); ++index) { + for (Dialogs::const_iterator index = m_dialogs.begin(); index != m_dialogs.end(); ++index) { if (index->second) { ARCH->unlockMutex(m_mutex); if (IsDialogMessage(index->first, msg)) { @@ -344,7 +358,8 @@ bool ArchTaskBarWindows::processDialogs(MSG *msg) { } LRESULT -ArchTaskBarWindows::wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { +ArchTaskBarWindows::wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ switch (msg) { case kNotifyReceiver: { // lookup receiver @@ -380,8 +395,8 @@ ArchTaskBarWindows::wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { return DefWindowProc(hwnd, msg, wParam, lParam); } -LRESULT CALLBACK ArchTaskBarWindows::staticWndProc( - HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { +LRESULT CALLBACK ArchTaskBarWindows::staticWndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ // if msg is WM_NCCREATE, extract the ArchTaskBarWindows* and put // it in the extra window data then forward the call. ArchTaskBarWindows *self = NULL; @@ -389,8 +404,7 @@ LRESULT CALLBACK ArchTaskBarWindows::staticWndProc( CREATESTRUCT *createInfo; createInfo = reinterpret_cast(lParam); self = static_cast(createInfo->lpCreateParams); - SetWindowLongPtr( - hwnd, 0, reinterpret_cast(createInfo->lpCreateParams)); + SetWindowLongPtr(hwnd, 0, reinterpret_cast(createInfo->lpCreateParams)); } else { // get the extra window data and forward the call LONG_PTR data = GetWindowLongPtr(hwnd, 0); @@ -407,7 +421,8 @@ LRESULT CALLBACK ArchTaskBarWindows::staticWndProc( } } -void ArchTaskBarWindows::threadMainLoop() { +void ArchTaskBarWindows::threadMainLoop() +{ // register the task bar restart message m_taskBarRestart = RegisterWindowMessage(TEXT("TaskbarCreated")); @@ -430,8 +445,9 @@ void ArchTaskBarWindows::threadMainLoop() { // create window m_hwnd = CreateWindowEx( - WS_EX_TOOLWINDOW, className, TEXT("Deskflow Task Bar"), WS_POPUP, 0, 0, 1, - 1, NULL, NULL, instanceWin32(), static_cast(this)); + WS_EX_TOOLWINDOW, className, TEXT("Deskflow Task Bar"), WS_POPUP, 0, 0, 1, 1, NULL, NULL, instanceWin32(), + static_cast(this) + ); // signal ready ARCH->lockMutex(m_mutex); @@ -460,11 +476,13 @@ void ArchTaskBarWindows::threadMainLoop() { UnregisterClass(className, instanceWin32()); } -void *ArchTaskBarWindows::threadEntry(void *self) { +void *ArchTaskBarWindows::threadEntry(void *self) +{ static_cast(self)->threadMainLoop(); return NULL; } -HINSTANCE ArchTaskBarWindows::instanceWin32() { +HINSTANCE ArchTaskBarWindows::instanceWin32() +{ return ArchMiscWindows::instanceWin32(); } diff --git a/src/lib/arch/win32/ArchTaskBarWindows.h b/src/lib/arch/win32/ArchTaskBarWindows.h index e53b65ba5..ac70d4624 100644 --- a/src/lib/arch/win32/ArchTaskBarWindows.h +++ b/src/lib/arch/win32/ArchTaskBarWindows.h @@ -29,7 +29,8 @@ #define ARCH_TASKBAR ArchTaskBarWindows //! Win32 implementation of IArchTaskBar -class ArchTaskBarWindows : public IArchTaskBar { +class ArchTaskBarWindows : public IArchTaskBar +{ public: ArchTaskBarWindows(); virtual ~ArchTaskBarWindows(); @@ -56,7 +57,8 @@ public: virtual void updateReceiver(IArchTaskBarReceiver *); private: - class ReceiverInfo { + class ReceiverInfo + { public: UINT m_id; }; @@ -74,8 +76,7 @@ private: void updateIcon(UINT); void addAllIcons(); void removeAllIcons(); - void - modifyIconNoLock(ReceiverToInfoMap::const_iterator, DWORD taskBarMessage); + void modifyIconNoLock(ReceiverToInfoMap::const_iterator, DWORD taskBarMessage); void removeIconNoLock(UINT id); void handleIconMessage(IArchTaskBarReceiver *, LPARAM); diff --git a/src/lib/arch/win32/ArchTimeWindows.cpp b/src/lib/arch/win32/ArchTimeWindows.cpp index 51e55543a..f9b8074e1 100644 --- a/src/lib/arch/win32/ArchTimeWindows.cpp +++ b/src/lib/arch/win32/ArchTimeWindows.cpp @@ -43,7 +43,8 @@ static PTimeGetTime s_tgt = NULL; // ArchTimeWindows // -ArchTimeWindows::ArchTimeWindows() { +ArchTimeWindows::ArchTimeWindows() +{ assert(s_freq == 0.0 || s_mmInstance == NULL); LARGE_INTEGER freq; @@ -58,7 +59,8 @@ ArchTimeWindows::ArchTimeWindows() { } } -ArchTimeWindows::~ArchTimeWindows() { +ArchTimeWindows::~ArchTimeWindows() +{ s_freq = 0.0; if (s_mmInstance == NULL) { FreeLibrary(static_cast(s_mmInstance)); @@ -67,7 +69,8 @@ ArchTimeWindows::~ArchTimeWindows() { } } -double ArchTimeWindows::time() { +double ArchTimeWindows::time() +{ // get time. we try three ways, in order of descending precision if (s_freq != 0.0) { LARGE_INTEGER c; diff --git a/src/lib/arch/win32/ArchTimeWindows.h b/src/lib/arch/win32/ArchTimeWindows.h index 95c1363cd..b9a7092be 100644 --- a/src/lib/arch/win32/ArchTimeWindows.h +++ b/src/lib/arch/win32/ArchTimeWindows.h @@ -23,7 +23,8 @@ #define ARCH_TIME ArchTimeWindows //! Win32 implementation of IArchTime -class ArchTimeWindows : public IArchTime { +class ArchTimeWindows : public IArchTime +{ public: ArchTimeWindows(); virtual ~ArchTimeWindows(); diff --git a/src/lib/arch/win32/XArchWindows.cpp b/src/lib/arch/win32/XArchWindows.cpp index 9fe8bd670..1815de86d 100644 --- a/src/lib/arch/win32/XArchWindows.cpp +++ b/src/lib/arch/win32/XArchWindows.cpp @@ -24,13 +24,13 @@ // XArchEvalWindows // -std::string XArchEvalWindows::eval() const throw() { +std::string XArchEvalWindows::eval() const throw() +{ char *cmsg; if (FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | - FORMAT_MESSAGE_FROM_SYSTEM, - 0, m_error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&cmsg, - 0, NULL) == 0) { + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, 0, m_error, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&cmsg, 0, NULL + ) == 0) { cmsg = NULL; return deskflow::string::sprintf("Unknown error, code %d", m_error); } @@ -43,17 +43,17 @@ std::string XArchEvalWindows::eval() const throw() { // XArchEvalWinsock // -std::string XArchEvalWinsock::eval() const throw() { +std::string XArchEvalWinsock::eval() const throw() +{ // built-in windows function for looking up error message strings // may not look up network error messages correctly. we'll have // to do it ourself. - static const struct { + static const struct + { int m_code; const char *m_msg; } s_netErrorCodes[] = { - /* 10004 */ { - WSAEINTR, - "The (blocking) call was canceled via WSACancelBlockingCall"}, + /* 10004 */ {WSAEINTR, "The (blocking) call was canceled via WSACancelBlockingCall"}, /* 10009 */ {WSAEBADF, "Bad file handle"}, /* 10013 */ {WSAEACCES, "The requested address is a broadcast address, but the " @@ -67,44 +67,37 @@ std::string XArchEvalWinsock::eval() const throw() { /* 10036 */ {WSAEINPROGRESS, "A blocking Windows Sockets operation is in progress"}, /* 10037 */ - {WSAEALREADY, - "The asynchronous routine being canceled has already completed"}, + {WSAEALREADY, "The asynchronous routine being canceled has already completed"}, /* 10038 */ {WSAENOTSOCK, "At least on descriptor is not a socket"}, /* 10039 */ {WSAEDESTADDRREQ, "A destination address is required"}, /* 10040 */ {WSAEMSGSIZE, "The datagram was too large to fit into the specified " "buffer and was truncated"}, /* 10041 */ - {WSAEPROTOTYPE, - "The specified protocol is the wrong type for this socket"}, + {WSAEPROTOTYPE, "The specified protocol is the wrong type for this socket"}, /* 10042 */ {WSAENOPROTOOPT, "The option is unknown or unsupported"}, /* 10043 */ {WSAEPROTONOSUPPORT, "The specified protocol is not supported"}, /* 10044 */ - {WSAESOCKTNOSUPPORT, - "The specified socket type is not supported by this address family"}, + {WSAESOCKTNOSUPPORT, "The specified socket type is not supported by this address family"}, /* 10045 */ - {WSAEOPNOTSUPP, - "The referenced socket is not a type that supports that operation"}, + {WSAEOPNOTSUPP, "The referenced socket is not a type that supports that operation"}, /* 10046 */ {WSAEPFNOSUPPORT, "BSD: Protocol family not supported"}, /* 10047 */ {WSAEAFNOSUPPORT, "The specified address family is not supported"}, /* 10048 */ {WSAEADDRINUSE, "The specified address is already in use"}, /* 10049 */ - {WSAEADDRNOTAVAIL, - "The specified address is not available from the local machine"}, + {WSAEADDRNOTAVAIL, "The specified address is not available from the local machine"}, /* 10050 */ {WSAENETDOWN, "The Windows Sockets implementation has detected that the " "network subsystem has failed"}, /* 10051 */ - {WSAENETUNREACH, - "The network can't be reached from this host at this time"}, + {WSAENETUNREACH, "The network can't be reached from this host at this time"}, /* 10052 */ {WSAENETRESET, "The connection must be reset because the Windows Sockets " "implementation dropped it"}, /* 10053 */ - {WSAECONNABORTED, - "The virtual circuit was aborted due to timeout or other failure"}, + {WSAECONNABORTED, "The virtual circuit was aborted due to timeout or other failure"}, /* 10054 */ {WSAECONNRESET, "The virtual circuit was reset by the remote side"}, /* 10055 */ @@ -115,8 +108,7 @@ std::string XArchEvalWinsock::eval() const throw() { /* 10058 */ {WSAESHUTDOWN, "The socket has been shutdown"}, /* 10059 */ {WSAETOOMANYREFS, "BSD: Too many references"}, /* 10060 */ - {WSAETIMEDOUT, - "Attempt to connect timed out without establishing a connection"}, + {WSAETIMEDOUT, "Attempt to connect timed out without establishing a connection"}, /* 10061 */ {WSAECONNREFUSED, "Connection was refused"}, /* 10062 */ {WSAELOOP, "Undocumented WinSock error code used in BSD"}, /* 10063 */ @@ -130,8 +122,7 @@ std::string XArchEvalWinsock::eval() const throw() { /* 10070 */ {WSAESTALE, "Undocumented WinSock error code"}, /* 10071 */ {WSAEREMOTE, "Undocumented WinSock error code"}, /* 10091 */ - {WSASYSNOTREADY, - "Underlying network subsytem is not ready for network communication"}, + {WSASYSNOTREADY, "Underlying network subsytem is not ready for network communication"}, /* 10092 */ {WSAVERNOTSUPPORTED, "The version of WinSock API support requested is " "not provided in this implementation"}, @@ -141,14 +132,13 @@ std::string XArchEvalWinsock::eval() const throw() { {WSAEDISCON, "Virtual circuit has gracefully terminated connection"}, /* 11001 */ {WSAHOST_NOT_FOUND, "The specified host is unknown"}, /* 11002 */ - {WSATRY_AGAIN, - "A temporary error occurred on an authoritative name server"}, + {WSATRY_AGAIN, "A temporary error occurred on an authoritative name server"}, /* 11003 */ {WSANO_RECOVERY, "A non-recoverable name server error occurred"}, /* 11004 */ - {WSANO_DATA, - "The requested name is valid but does not have an IP address"}, - /* end */ {0, NULL}}; + {WSANO_DATA, "The requested name is valid but does not have an IP address"}, + /* end */ {0, NULL} + }; for (unsigned int i = 0; s_netErrorCodes[i].m_code != 0; ++i) { if (s_netErrorCodes[i].m_code == m_error) { diff --git a/src/lib/arch/win32/XArchWindows.h b/src/lib/arch/win32/XArchWindows.h index 4f5a41501..a68596a60 100644 --- a/src/lib/arch/win32/XArchWindows.h +++ b/src/lib/arch/win32/XArchWindows.h @@ -24,11 +24,18 @@ #include //! Lazy error message string evaluation for windows -class XArchEvalWindows : public XArchEval { +class XArchEvalWindows : public XArchEval +{ public: - XArchEvalWindows() : m_error(GetLastError()) {} - XArchEvalWindows(DWORD error) : m_error(error) {} - virtual ~XArchEvalWindows() {} + XArchEvalWindows() : m_error(GetLastError()) + { + } + XArchEvalWindows(DWORD error) : m_error(error) + { + } + virtual ~XArchEvalWindows() + { + } virtual std::string eval() const throw(); @@ -37,10 +44,15 @@ private: }; //! Lazy error message string evaluation for winsock -class XArchEvalWinsock : public XArchEval { +class XArchEvalWinsock : public XArchEval +{ public: - XArchEvalWinsock(int error) : m_error(error) {} - virtual ~XArchEvalWinsock() {} + XArchEvalWinsock(int error) : m_error(error) + { + } + virtual ~XArchEvalWinsock() + { + } virtual std::string eval() const throw(); diff --git a/src/lib/base/ELevel.h b/src/lib/base/ELevel.h index f39c47dae..46b24e707 100644 --- a/src/lib/base/ELevel.h +++ b/src/lib/base/ELevel.h @@ -22,7 +22,8 @@ /*! The logging priority levels in order of highest to lowest priority. */ -enum ELevel { +enum ELevel +{ kPRINT = -1, //!< For print only (no file or time) kFATAL, //!< For fatal errors kERROR, //!< For serious errors diff --git a/src/lib/base/Event.cpp b/src/lib/base/Event.cpp index eaeb15070..a5d22a2d6 100644 --- a/src/lib/base/Event.cpp +++ b/src/lib/base/Event.cpp @@ -23,12 +23,8 @@ // Event // -Event::Event() - : m_type(kUnknown), - m_target(NULL), - m_data(NULL), - m_flags(0), - m_dataObject(nullptr) { +Event::Event() : m_type(kUnknown), m_target(NULL), m_data(NULL), m_flags(0), m_dataObject(nullptr) +{ // do nothing } @@ -37,7 +33,8 @@ Event::Event(Type type, void *target, void *data, Flags flags) m_target(target), m_data(data), m_flags(flags), - m_dataObject(nullptr) { + m_dataObject(nullptr) +{ // do nothing } @@ -46,19 +43,37 @@ Event::Event(Type type, void *target, EventData *dataObject) m_target(target), m_data(nullptr), m_flags(kNone), - m_dataObject(dataObject) {} + m_dataObject(dataObject) +{ +} -Event::Type Event::getType() const { return m_type; } +Event::Type Event::getType() const +{ + return m_type; +} -void *Event::getTarget() const { return m_target; } +void *Event::getTarget() const +{ + return m_target; +} -void *Event::getData() const { return m_data; } +void *Event::getData() const +{ + return m_data; +} -EventData *Event::getDataObject() const { return m_dataObject; } +EventData *Event::getDataObject() const +{ + return m_dataObject; +} -Event::Flags Event::getFlags() const { return m_flags; } +Event::Flags Event::getFlags() const +{ + return m_flags; +} -void Event::deleteData(const Event &event) { +void Event::deleteData(const Event &event) +{ switch (event.getType()) { case kUnknown: case kQuit: @@ -75,7 +90,8 @@ void Event::deleteData(const Event &event) { } } -void Event::setDataObject(EventData *dataObject) { +void Event::setDataObject(EventData *dataObject) +{ assert(m_dataObject == nullptr); m_dataObject = dataObject; } diff --git a/src/lib/base/Event.h b/src/lib/base/Event.h index 86033bd2f..1babd8850 100644 --- a/src/lib/base/Event.h +++ b/src/lib/base/Event.h @@ -21,20 +21,27 @@ #include "common/basic_types.h" #include "common/stdmap.h" -class EventData { +class EventData +{ public: - EventData() {} - virtual ~EventData() {} + EventData() + { + } + virtual ~EventData() + { + } }; //! Event /*! A \c Event holds an event type and a pointer to event data. */ -class Event { +class Event +{ public: typedef UInt32 Type; - enum { + enum + { kUnknown, //!< The event type is unknown kQuit, //!< The quit event kSystem, //!< The data points to a system event type @@ -43,7 +50,8 @@ public: }; typedef UInt32 Flags; - enum { + enum + { kNone = 0x00, //!< No flags kDeliverImmediately = 0x01, //!< Dispatch and free event immediately kDontFreeData = 0x02 //!< Don't free data in deleteData diff --git a/src/lib/base/EventQueue.cpp b/src/lib/base/EventQueue.cpp index 61dc9348c..fa9df6f3d 100644 --- a/src/lib/base/EventQueue.cpp +++ b/src/lib/base/EventQueue.cpp @@ -51,7 +51,8 @@ EVENT_TYPE_ACCESSOR(File) EVENT_TYPE_ACCESSOR(Ei) // interrupt handler. this just adds a quit event to the queue. -static void interrupt(Arch::ESignal, void *data) { +static void interrupt(Arch::ESignal, void *data) +{ EventQueue *events = static_cast(data); events->addEvent(Event(Event::kQuit)); } @@ -85,14 +86,16 @@ EventQueue::EventQueue() m_typesForFile(NULL), m_typesForEi(NULL), m_readyMutex(new Mutex), - m_readyCondVar(new CondVar(m_readyMutex, false)) { + m_readyCondVar(new CondVar(m_readyMutex, false)) +{ m_mutex = ARCH->newMutex(); ARCH->setSignalHandler(Arch::kINTERRUPT, &interrupt, this); ARCH->setSignalHandler(Arch::kTERMINATE, &interrupt, this); m_buffer = new SimpleEventQueueBuffer; } -EventQueue::~EventQueue() { +EventQueue::~EventQueue() +{ delete m_buffer; delete m_readyCondVar; delete m_readyMutex; @@ -102,7 +105,8 @@ EventQueue::~EventQueue() { ARCH->closeMutex(m_mutex); } -void EventQueue::loop() { +void EventQueue::loop() +{ m_buffer->init(); { Lock lock(m_readyMutex); @@ -126,7 +130,8 @@ void EventQueue::loop() { } } -Event::Type EventQueue::registerTypeOnce(Event::Type &type, const char *name) { +Event::Type EventQueue::registerTypeOnce(Event::Type &type, const char *name) +{ ArchMutexLock lock(m_mutex); if (type == Event::kUnknown) { m_typeMap.insert(std::make_pair(m_nextType, name)); @@ -137,7 +142,8 @@ Event::Type EventQueue::registerTypeOnce(Event::Type &type, const char *name) { return type; } -const char *EventQueue::getTypeName(Event::Type type) { +const char *EventQueue::getTypeName(Event::Type type) +{ switch (type) { case Event::kUnknown: return "nil"; @@ -161,7 +167,8 @@ const char *EventQueue::getTypeName(Event::Type type) { } } -void EventQueue::adoptBuffer(IEventQueueBuffer *buffer) { +void EventQueue::adoptBuffer(IEventQueueBuffer *buffer) +{ ArchMutexLock lock(m_mutex); LOG((CLOG_DEBUG "adopting new buffer")); @@ -187,7 +194,8 @@ void EventQueue::adoptBuffer(IEventQueueBuffer *buffer) { } } -bool EventQueue::getEvent(Event &event, double timeout) { +bool EventQueue::getEvent(Event &event, double timeout) +{ Stopwatch timer(true); retry: // if no events are waiting then handle timers and then wait @@ -243,7 +251,8 @@ retry: } } -bool EventQueue::dispatchEvent(const Event &event) { +bool EventQueue::dispatchEvent(const Event &event) +{ void *target = event.getTarget(); IEventJob *job = getHandler(event.getType(), target); if (job == NULL) { @@ -256,7 +265,8 @@ bool EventQueue::dispatchEvent(const Event &event) { return false; } -void EventQueue::addEvent(const Event &event) { +void EventQueue::addEvent(const Event &event) +{ // discard bogus event types switch (event.getType()) { case Event::kUnknown: @@ -278,7 +288,8 @@ void EventQueue::addEvent(const Event &event) { } } -void EventQueue::addEventToBuffer(const Event &event) { +void EventQueue::addEventToBuffer(const Event &event) +{ ArchMutexLock lock(m_mutex); // store the event's data locally @@ -292,7 +303,8 @@ void EventQueue::addEventToBuffer(const Event &event) { } } -EventQueueTimer *EventQueue::newTimer(double duration, void *target) { +EventQueueTimer *EventQueue::newTimer(double duration, void *target) +{ assert(duration > 0.0); EventQueueTimer *timer = m_buffer->newTimer(duration, false); @@ -304,12 +316,12 @@ EventQueueTimer *EventQueue::newTimer(double duration, void *target) { // initial duration is requested duration plus whatever's on // the clock currently because the latter will be subtracted // the next time we check for timers. - m_timerQueue.push( - Timer(timer, duration, duration + m_time.getTime(), target, false)); + m_timerQueue.push(Timer(timer, duration, duration + m_time.getTime(), target, false)); return timer; } -EventQueueTimer *EventQueue::newOneShotTimer(double duration, void *target) { +EventQueueTimer *EventQueue::newOneShotTimer(double duration, void *target) +{ assert(duration > 0.0); EventQueueTimer *timer = m_buffer->newTimer(duration, true); @@ -321,15 +333,14 @@ EventQueueTimer *EventQueue::newOneShotTimer(double duration, void *target) { // initial duration is requested duration plus whatever's on // the clock currently because the latter will be subtracted // the next time we check for timers. - m_timerQueue.push( - Timer(timer, duration, duration + m_time.getTime(), target, true)); + m_timerQueue.push(Timer(timer, duration, duration + m_time.getTime(), target, true)); return timer; } -void EventQueue::deleteTimer(EventQueueTimer *timer) { +void EventQueue::deleteTimer(EventQueueTimer *timer) +{ ArchMutexLock lock(m_mutex); - for (TimerQueue::iterator index = m_timerQueue.begin(); - index != m_timerQueue.end(); ++index) { + for (TimerQueue::iterator index = m_timerQueue.begin(); index != m_timerQueue.end(); ++index) { if (index->getTimer() == timer) { m_timerQueue.erase(index); break; @@ -342,15 +353,16 @@ void EventQueue::deleteTimer(EventQueueTimer *timer) { m_buffer->deleteTimer(timer); } -void EventQueue::adoptHandler( - Event::Type type, void *target, IEventJob *handler) { +void EventQueue::adoptHandler(Event::Type type, void *target, IEventJob *handler) +{ ArchMutexLock lock(m_mutex); IEventJob *&job = m_handlers[target][type]; delete job; job = handler; } -void EventQueue::removeHandler(Event::Type type, void *target) { +void EventQueue::removeHandler(Event::Type type, void *target) +{ IEventJob *handler = NULL; { ArchMutexLock lock(m_mutex); @@ -367,7 +379,8 @@ void EventQueue::removeHandler(Event::Type type, void *target) { delete handler; } -void EventQueue::removeHandlers(void *target) { +void EventQueue::removeHandlers(void *target) +{ std::vector handlers; { ArchMutexLock lock(m_mutex); @@ -375,8 +388,7 @@ void EventQueue::removeHandlers(void *target) { if (index != m_handlers.end()) { // copy to handlers array and clear table for target TypeHandlerTable &typeHandlers = index->second; - for (TypeHandlerTable::iterator index2 = typeHandlers.begin(); - index2 != typeHandlers.end(); ++index2) { + for (TypeHandlerTable::iterator index2 = typeHandlers.begin(); index2 != typeHandlers.end(); ++index2) { handlers.push_back(index2->second); } typeHandlers.clear(); @@ -384,17 +396,18 @@ void EventQueue::removeHandlers(void *target) { } // delete handlers - for (std::vector::iterator index = handlers.begin(); - index != handlers.end(); ++index) { + for (std::vector::iterator index = handlers.begin(); index != handlers.end(); ++index) { delete *index; } } -bool EventQueue::isEmpty() const { +bool EventQueue::isEmpty() const +{ return (m_buffer->isEmpty() && getNextTimerTimeout() != 0.0); } -IEventJob *EventQueue::getHandler(Event::Type type, void *target) const { +IEventJob *EventQueue::getHandler(Event::Type type, void *target) const +{ ArchMutexLock lock(m_mutex); HandlerTable::const_iterator index = m_handlers.find(target); if (index != m_handlers.end()) { @@ -407,7 +420,8 @@ IEventJob *EventQueue::getHandler(Event::Type type, void *target) const { return NULL; } -UInt32 EventQueue::saveEvent(const Event &event) { +UInt32 EventQueue::saveEvent(const Event &event) +{ // choose id UInt32 id; if (!m_oldEventIDs.empty()) { @@ -424,7 +438,8 @@ UInt32 EventQueue::saveEvent(const Event &event) { return id; } -Event EventQueue::removeEvent(UInt32 eventID) { +Event EventQueue::removeEvent(UInt32 eventID) +{ // look up id EventTable::iterator index = m_events.find(eventID); if (index == m_events.end()) { @@ -441,7 +456,8 @@ Event EventQueue::removeEvent(UInt32 eventID) { return event; } -bool EventQueue::hasTimerExpired(Event &event) { +bool EventQueue::hasTimerExpired(Event &event) +{ // return true if there's a timer in the timer priority queue that // has expired. if returning true then fill in event appropriately // and reset and reinsert the timer. @@ -454,8 +470,7 @@ bool EventQueue::hasTimerExpired(Event &event) { m_time.reset(); // countdown elapsed time - for (TimerQueue::iterator index = m_timerQueue.begin(); - index != m_timerQueue.end(); ++index) { + for (TimerQueue::iterator index = m_timerQueue.begin(); index != m_timerQueue.end(); ++index) { (*index) -= time; } @@ -481,7 +496,8 @@ bool EventQueue::hasTimerExpired(Event &event) { return true; } -double EventQueue::getNextTimerTimeout() const { +double EventQueue::getNextTimerTimeout() const +{ // return -1 if no timers, 0 if the top timer has expired, otherwise // the time until the top timer in the timer priority queue will // expire. @@ -494,7 +510,8 @@ double EventQueue::getNextTimerTimeout() const { return m_timerQueue.top(); } -Event::Type EventQueue::getRegisteredType(const String &name) const { +Event::Type EventQueue::getRegisteredType(const String &name) const +{ NameMap::const_iterator found = m_nameMap.find(name); if (found != m_nameMap.end()) return found->second; @@ -502,12 +519,14 @@ Event::Type EventQueue::getRegisteredType(const String &name) const { return Event::kUnknown; } -void *EventQueue::getSystemTarget() { +void *EventQueue::getSystemTarget() +{ // any unique arbitrary pointer will do return &m_systemTarget; } -void EventQueue::waitForReady() const { +void EventQueue::waitForReady() const +{ double timeout = ARCH->time() + 10; Lock lock(m_readyMutex); @@ -522,37 +541,54 @@ void EventQueue::waitForReady() const { // EventQueue::Timer // -EventQueue::Timer::Timer( - EventQueueTimer *timer, double timeout, double initialTime, void *target, - bool oneShot) +EventQueue::Timer::Timer(EventQueueTimer *timer, double timeout, double initialTime, void *target, bool oneShot) : m_timer(timer), m_timeout(timeout), m_target(target), m_oneShot(oneShot), - m_time(initialTime) { + m_time(initialTime) +{ assert(m_timeout > 0.0); } -EventQueue::Timer::~Timer() { +EventQueue::Timer::~Timer() +{ // do nothing } -void EventQueue::Timer::reset() { m_time = m_timeout; } +void EventQueue::Timer::reset() +{ + m_time = m_timeout; +} -EventQueue::Timer &EventQueue::Timer::operator-=(double dt) { +EventQueue::Timer &EventQueue::Timer::operator-=(double dt) +{ m_time -= dt; return *this; } -EventQueue::Timer::operator double() const { return m_time; } +EventQueue::Timer::operator double() const +{ + return m_time; +} -bool EventQueue::Timer::isOneShot() const { return m_oneShot; } +bool EventQueue::Timer::isOneShot() const +{ + return m_oneShot; +} -EventQueueTimer *EventQueue::Timer::getTimer() const { return m_timer; } +EventQueueTimer *EventQueue::Timer::getTimer() const +{ + return m_timer; +} -void *EventQueue::Timer::getTarget() const { return m_target; } +void *EventQueue::Timer::getTarget() const +{ + return m_target; +} -void EventQueue::Timer::fillEvent(TimerEvent &event) const { +void EventQueue::Timer::fillEvent(TimerEvent &event) const +{ event.m_timer = m_timer; event.m_count = 0; if (m_time <= 0.0) { @@ -560,6 +596,7 @@ void EventQueue::Timer::fillEvent(TimerEvent &event) const { } } -bool EventQueue::Timer::operator<(const Timer &t) const { +bool EventQueue::Timer::operator<(const Timer &t) const +{ return m_time < t.m_time; } diff --git a/src/lib/base/EventQueue.h b/src/lib/base/EventQueue.h index c5b2bd7e6..8b7180240 100644 --- a/src/lib/base/EventQueue.h +++ b/src/lib/base/EventQueue.h @@ -37,7 +37,8 @@ class Mutex; An event queue that implements the platform independent parts and delegates the platform dependent parts to a subclass. */ -class EventQueue : public IEventQueue { +class EventQueue : public IEventQueue +{ public: EventQueue(); EventQueue(EventQueue const &) = delete; @@ -74,11 +75,10 @@ private: void addEventToBuffer(const Event &event); private: - class Timer { + class Timer + { public: - Timer( - EventQueueTimer *, double timeout, double initialTime, void *target, - bool oneShot); + Timer(EventQueueTimer *, double timeout, double initialTime, void *target, bool oneShot); ~Timer(); void reset(); @@ -188,12 +188,13 @@ private: std::queue m_pending; }; -#define EVENT_TYPE_ACCESSOR(type_) \ +#define EVENT_TYPE_ACCESSOR(type_) \ type_##Events& \ -EventQueue::for##type_() { \ - if (m_typesFor##type_ == NULL) { \ - m_typesFor##type_ = new type_##Events(); \ - m_typesFor##type_->setEvents(dynamic_cast(this)); \ - } \ - return *m_typesFor##type_; \ +EventQueue::for##type_() \ + { \ + if (m_typesFor##type_ == NULL) { \ + m_typesFor##type_ = new type_##Events(); \ + m_typesFor##type_->setEvents(dynamic_cast(this)); \ + } \ + return *m_typesFor##type_; \ } diff --git a/src/lib/base/EventTypes.cpp b/src/lib/base/EventTypes.cpp index d7d9ac94a..1c0d990b1 100644 --- a/src/lib/base/EventTypes.cpp +++ b/src/lib/base/EventTypes.cpp @@ -21,14 +21,20 @@ #include #include -EventTypes::EventTypes() : m_events(NULL) {} +EventTypes::EventTypes() : m_events(NULL) +{ +} -IEventQueue *EventTypes::getEvents() const { +IEventQueue *EventTypes::getEvents() const +{ assert(m_events != NULL); return m_events; } -void EventTypes::setEvents(IEventQueue *events) { m_events = events; } +void EventTypes::setEvents(IEventQueue *events) +{ + m_events = events; +} // // Client diff --git a/src/lib/base/EventTypes.h b/src/lib/base/EventTypes.h index 17d4af8dd..6ddfe8adf 100644 --- a/src/lib/base/EventTypes.h +++ b/src/lib/base/EventTypes.h @@ -21,7 +21,8 @@ class IEventQueue; -class EventTypes { +class EventTypes +{ public: EventTypes(); void setEvents(IEventQueue *events); @@ -33,12 +34,14 @@ private: IEventQueue *m_events; }; -#define REGISTER_EVENT(type_, name_) \ - Event::Type type_##Events::name_() { \ - return getEvents()->registerTypeOnce(m_##name_, __FUNCTION__); \ +#define REGISTER_EVENT(type_, name_) \ + Event::Type type_##Events::name_() \ + { \ + return getEvents()->registerTypeOnce(m_##name_, __FUNCTION__); \ } -class ClientEvents : public EventTypes { +class ClientEvents : public EventTypes +{ public: //! @name accessors //@{ @@ -81,14 +84,17 @@ private: Event::Type m_disconnected = Event::kUnknown; }; -class IStreamEvents : public EventTypes { +class IStreamEvents : public EventTypes +{ public: IStreamEvents() : m_inputReady(Event::kUnknown), m_outputFlushed(Event::kUnknown), m_outputError(Event::kUnknown), m_inputShutdown(Event::kUnknown), - m_outputShutdown(Event::kUnknown) {} + m_outputShutdown(Event::kUnknown) + { + } //! @name accessors //@{ @@ -144,11 +150,12 @@ private: Event::Type m_outputShutdown; }; -class IpcClientEvents : public EventTypes { +class IpcClientEvents : public EventTypes +{ public: - IpcClientEvents() - : m_connected(Event::kUnknown), - m_messageReceived(Event::kUnknown) {} + IpcClientEvents() : m_connected(Event::kUnknown), m_messageReceived(Event::kUnknown) + { + } //! @name accessors //@{ @@ -166,11 +173,12 @@ private: Event::Type m_messageReceived; }; -class IpcClientProxyEvents : public EventTypes { +class IpcClientProxyEvents : public EventTypes +{ public: - IpcClientProxyEvents() - : m_messageReceived(Event::kUnknown), - m_disconnected(Event::kUnknown) {} + IpcClientProxyEvents() : m_messageReceived(Event::kUnknown), m_disconnected(Event::kUnknown) + { + } //! @name accessors //@{ @@ -188,11 +196,12 @@ private: Event::Type m_disconnected; }; -class IpcServerEvents : public EventTypes { +class IpcServerEvents : public EventTypes +{ public: - IpcServerEvents() - : m_clientConnected(Event::kUnknown), - m_messageReceived(Event::kUnknown) {} + IpcServerEvents() : m_clientConnected(Event::kUnknown), m_messageReceived(Event::kUnknown) + { + } //! @name accessors //@{ @@ -210,9 +219,12 @@ private: Event::Type m_messageReceived; }; -class IpcServerProxyEvents : public EventTypes { +class IpcServerProxyEvents : public EventTypes +{ public: - IpcServerProxyEvents() : m_messageReceived(Event::kUnknown) {} + IpcServerProxyEvents() : m_messageReceived(Event::kUnknown) + { + } //! @name accessors //@{ @@ -226,12 +238,15 @@ private: Event::Type m_messageReceived; }; -class IDataSocketEvents : public EventTypes { +class IDataSocketEvents : public EventTypes +{ public: IDataSocketEvents() : m_connected(Event::kUnknown), m_secureConnected(Event::kUnknown), - m_connectionFailed(Event::kUnknown) {} + m_connectionFailed(Event::kUnknown) + { + } //! @name accessors //@{ @@ -266,9 +281,12 @@ private: Event::Type m_connectionFailed; }; -class IListenSocketEvents : public EventTypes { +class IListenSocketEvents : public EventTypes +{ public: - IListenSocketEvents() : m_connecting(Event::kUnknown) {} + IListenSocketEvents() : m_connecting(Event::kUnknown) + { + } //! @name accessors //@{ @@ -286,11 +304,12 @@ private: Event::Type m_connecting; }; -class ISocketEvents : public EventTypes { +class ISocketEvents : public EventTypes +{ public: - ISocketEvents() - : m_disconnected(Event::kUnknown), - m_stopRetry(Event::kUnknown) {} + ISocketEvents() : m_disconnected(Event::kUnknown), m_stopRetry(Event::kUnknown) + { + } //! @name accessors //@{ @@ -317,9 +336,12 @@ private: Event::Type m_stopRetry; }; -class OSXScreenEvents : public EventTypes { +class OSXScreenEvents : public EventTypes +{ public: - OSXScreenEvents() : m_confirmSleep(Event::kUnknown) {} + OSXScreenEvents() : m_confirmSleep(Event::kUnknown) + { + } //! @name accessors //@{ @@ -332,11 +354,12 @@ private: Event::Type m_confirmSleep; }; -class ClientListenerEvents : public EventTypes { +class ClientListenerEvents : public EventTypes +{ public: - ClientListenerEvents() - : m_accepted(Event::kUnknown), - m_connected(Event::kUnknown) {} + ClientListenerEvents() : m_accepted(Event::kUnknown), m_connected(Event::kUnknown) + { + } //! @name accessors //@{ @@ -362,11 +385,12 @@ private: Event::Type m_connected; }; -class ClientProxyEvents : public EventTypes { +class ClientProxyEvents : public EventTypes +{ public: - ClientProxyEvents() - : m_ready(Event::kUnknown), - m_disconnected(Event::kUnknown) {} + ClientProxyEvents() : m_ready(Event::kUnknown), m_disconnected(Event::kUnknown) + { + } //! @name accessors //@{ @@ -393,11 +417,12 @@ private: Event::Type m_disconnected; }; -class ClientProxyUnknownEvents : public EventTypes { +class ClientProxyUnknownEvents : public EventTypes +{ public: - ClientProxyUnknownEvents() - : m_success(Event::kUnknown), - m_failure(Event::kUnknown) {} + ClientProxyUnknownEvents() : m_success(Event::kUnknown), m_failure(Event::kUnknown) + { + } //! @name accessors //@{ @@ -423,7 +448,8 @@ private: Event::Type m_failure; }; -class ServerEvents : public EventTypes { +class ServerEvents : public EventTypes +{ public: ServerEvents() : m_error(Event::kUnknown), @@ -433,7 +459,9 @@ public: m_switchInDirection(Event::kUnknown), m_keyboardBroadcast(Event::kUnknown), m_lockCursorToScreen(Event::kUnknown), - m_screenSwitched(Event::kUnknown) {} + m_screenSwitched(Event::kUnknown) + { + } //! @name accessors //@{ @@ -512,12 +540,12 @@ private: Event::Type m_screenSwitched; }; -class ServerAppEvents : public EventTypes { +class ServerAppEvents : public EventTypes +{ public: - ServerAppEvents() - : m_reloadConfig(Event::kUnknown), - m_forceReconnect(Event::kUnknown), - m_resetServer(Event::kUnknown) {} + ServerAppEvents() : m_reloadConfig(Event::kUnknown), m_forceReconnect(Event::kUnknown), m_resetServer(Event::kUnknown) + { + } //! @name accessors //@{ @@ -534,12 +562,12 @@ private: Event::Type m_resetServer; }; -class IKeyStateEvents : public EventTypes { +class IKeyStateEvents : public EventTypes +{ public: - IKeyStateEvents() - : m_keyDown(Event::kUnknown), - m_keyUp(Event::kUnknown), - m_keyRepeat(Event::kUnknown) {} + IKeyStateEvents() : m_keyDown(Event::kUnknown), m_keyUp(Event::kUnknown), m_keyRepeat(Event::kUnknown) + { + } //! @name accessors //@{ @@ -561,7 +589,8 @@ private: Event::Type m_keyRepeat; }; -class IPrimaryScreenEvents : public EventTypes { +class IPrimaryScreenEvents : public EventTypes +{ public: IPrimaryScreenEvents() : m_buttonDown(Event::kUnknown), @@ -574,7 +603,9 @@ public: m_hotKeyDown(Event::kUnknown), m_hotKeyUp(Event::kUnknown), m_fakeInputBegin(Event::kUnknown), - m_fakeInputEnd(Event::kUnknown) {} + m_fakeInputEnd(Event::kUnknown) + { + } //! @name accessors //@{ @@ -635,13 +666,16 @@ private: Event::Type m_fakeInputEnd; }; -class IScreenEvents : public EventTypes { +class IScreenEvents : public EventTypes +{ public: IScreenEvents() : m_error(Event::kUnknown), m_shapeChanged(Event::kUnknown), m_suspend(Event::kUnknown), - m_resume(Event::kUnknown) {} + m_resume(Event::kUnknown) + { + } //! @name accessors //@{ @@ -683,12 +717,15 @@ private: Event::Type m_resume; }; -class ClipboardEvents : public EventTypes { +class ClipboardEvents : public EventTypes +{ public: ClipboardEvents() : m_clipboardGrabbed(Event::kUnknown), m_clipboardChanged(Event::kUnknown), - m_clipboardSending(Event::kUnknown) {} + m_clipboardSending(Event::kUnknown) + { + } //! @name accessors //@{ @@ -724,12 +761,15 @@ private: Event::Type m_clipboardSending; }; -class FileEvents : public EventTypes { +class FileEvents : public EventTypes +{ public: FileEvents() : m_fileChunkSending(Event::kUnknown), m_fileRecieveCompleted(Event::kUnknown), - m_keepAlive(Event::kUnknown) {} + m_keepAlive(Event::kUnknown) + { + } //! @name accessors //@{ @@ -751,9 +791,12 @@ private: Event::Type m_keepAlive; }; -class EiEvents : public EventTypes { +class EiEvents : public EventTypes +{ public: - EiEvents() : m_connected(Event::kUnknown), m_sessionClosed(Event::kUnknown) {} + EiEvents() : m_connected(Event::kUnknown), m_sessionClosed(Event::kUnknown) + { + } //! @name accessors //@{ diff --git a/src/lib/base/FunctionEventJob.cpp b/src/lib/base/FunctionEventJob.cpp index f75096820..083c3eeb6 100644 --- a/src/lib/base/FunctionEventJob.cpp +++ b/src/lib/base/FunctionEventJob.cpp @@ -22,18 +22,18 @@ // FunctionEventJob // -FunctionEventJob::FunctionEventJob( - void (*func)(const Event &, void *), void *arg) - : m_func(func), - m_arg(arg) { +FunctionEventJob::FunctionEventJob(void (*func)(const Event &, void *), void *arg) : m_func(func), m_arg(arg) +{ // do nothing } -FunctionEventJob::~FunctionEventJob() { +FunctionEventJob::~FunctionEventJob() +{ // do nothing } -void FunctionEventJob::run(const Event &event) { +void FunctionEventJob::run(const Event &event) +{ if (m_func != NULL) { m_func(event, m_arg); } diff --git a/src/lib/base/FunctionEventJob.h b/src/lib/base/FunctionEventJob.h index 1af60b493..8f50e8dd1 100644 --- a/src/lib/base/FunctionEventJob.h +++ b/src/lib/base/FunctionEventJob.h @@ -24,7 +24,8 @@ /*! An event job class that invokes a function. */ -class FunctionEventJob : public IEventJob { +class FunctionEventJob : public IEventJob +{ public: //! run() invokes \c func(arg) FunctionEventJob(void (*func)(const Event &, void *), void *arg = NULL); diff --git a/src/lib/base/FunctionJob.cpp b/src/lib/base/FunctionJob.cpp index 582c9e2fd..c708abccc 100644 --- a/src/lib/base/FunctionJob.cpp +++ b/src/lib/base/FunctionJob.cpp @@ -22,17 +22,18 @@ // FunctionJob // -FunctionJob::FunctionJob(void (*func)(void *), void *arg) - : m_func(func), - m_arg(arg) { +FunctionJob::FunctionJob(void (*func)(void *), void *arg) : m_func(func), m_arg(arg) +{ // do nothing } -FunctionJob::~FunctionJob() { +FunctionJob::~FunctionJob() +{ // do nothing } -void FunctionJob::run() { +void FunctionJob::run() +{ if (m_func != NULL) { m_func(m_arg); } diff --git a/src/lib/base/FunctionJob.h b/src/lib/base/FunctionJob.h index df06a28ef..5cf881ca4 100644 --- a/src/lib/base/FunctionJob.h +++ b/src/lib/base/FunctionJob.h @@ -24,7 +24,8 @@ /*! A job class that invokes a function. */ -class FunctionJob : public IJob { +class FunctionJob : public IJob +{ public: //! run() invokes \c func(arg) FunctionJob(void (*func)(void *), void *arg = NULL); diff --git a/src/lib/base/IEventJob.h b/src/lib/base/IEventJob.h index 528035ecd..e86149bd5 100644 --- a/src/lib/base/IEventJob.h +++ b/src/lib/base/IEventJob.h @@ -26,7 +26,8 @@ class Event; /*! An event job is an interface for executing a event handler. */ -class IEventJob : public IInterface { +class IEventJob : public IInterface +{ public: //! Run the job virtual void run(const Event &) = 0; diff --git a/src/lib/base/IEventQueue.h b/src/lib/base/IEventQueue.h index 6be5ad88d..8175cd273 100644 --- a/src/lib/base/IEventQueue.h +++ b/src/lib/base/IEventQueue.h @@ -59,9 +59,11 @@ on any event becoming available at the head of the queue and can place new events at the end of the queue. Clients can also add and remove timers which generate events periodically. */ -class IEventQueue : public IInterface { +class IEventQueue : public IInterface +{ public: - class TimerEvent { + class TimerEvent + { public: EventQueueTimer *m_timer; //!< The timer UInt32 m_count; //!< Number of repeats @@ -150,8 +152,7 @@ public: of type \p type. If no such handler exists it will use the handler for \p target and type \p kUnknown if it exists. */ - virtual void - adoptHandler(Event::Type type, void *target, IEventJob *handler) = 0; + virtual void adoptHandler(Event::Type type, void *target, IEventJob *handler) = 0; //! Unregister an event handler for an event type /*! diff --git a/src/lib/base/IEventQueueBuffer.h b/src/lib/base/IEventQueueBuffer.h index 824b1496c..c34c322c2 100644 --- a/src/lib/base/IEventQueueBuffer.h +++ b/src/lib/base/IEventQueueBuffer.h @@ -28,9 +28,11 @@ class EventQueueTimer; /*! An event queue buffer provides a queue of events for an IEventQueue. */ -class IEventQueueBuffer : public IInterface { +class IEventQueueBuffer : public IInterface +{ public: - enum Type { + enum Type + { kNone, //!< No event is available kSystem, //!< Event is a system event kUser //!< Event is a user event diff --git a/src/lib/base/IJob.h b/src/lib/base/IJob.h index 7cc15b7ae..b2cec91ed 100644 --- a/src/lib/base/IJob.h +++ b/src/lib/base/IJob.h @@ -24,7 +24,8 @@ /*! A job is an interface for executing some function. */ -class IJob : public IInterface { +class IJob : public IInterface +{ public: //! Run the job virtual void run() = 0; diff --git a/src/lib/base/ILogOutputter.h b/src/lib/base/ILogOutputter.h index 34f404e71..d14ca0cd8 100644 --- a/src/lib/base/ILogOutputter.h +++ b/src/lib/base/ILogOutputter.h @@ -28,7 +28,8 @@ Type of outputter interface. The logger performs all output through outputters. ILogOutputter overrides must not call any log functions directly or indirectly. */ -class ILogOutputter : public IInterface { +class ILogOutputter : public IInterface +{ public: //! @name manipulators //@{ diff --git a/src/lib/base/Log.cpp b/src/lib/base/Log.cpp index 09e00af1f..438d7e75a 100644 --- a/src/lib/base/Log.cpp +++ b/src/lib/base/Log.cpp @@ -31,13 +31,11 @@ const int kPriorityPrefixLength = 3; // names of priorities -static const char *g_priority[] = {"FATAL", "ERROR", "WARNING", "NOTE", - "INFO", "DEBUG", "DEBUG1", "DEBUG2", - "DEBUG3", "DEBUG4", "DEBUG5"}; +static const char *g_priority[] = {"FATAL", "ERROR", "WARNING", "NOTE", "INFO", "DEBUG", + "DEBUG1", "DEBUG2", "DEBUG3", "DEBUG4", "DEBUG5"}; // number of priorities -static const int g_numPriority = - (int)(sizeof(g_priority) / sizeof(g_priority[0])); +static const int g_numPriority = (int)(sizeof(g_priority) / sizeof(g_priority[0])); // if NDEBUG (not debug) is not specified, i.e. you're building in debug, // then set default log level to DEBUG, otherwise the max level is INFO. @@ -53,7 +51,8 @@ static const int g_defaultMaxPriority = kINFO; namespace { -ELevel getPriority(const char *&fmt) { +ELevel getPriority(const char *&fmt) +{ if (strnlen(fmt, SIZE_MAX) < kPriorityPrefixLength) { throw std::invalid_argument("invalid format string, too short"); } @@ -65,7 +64,8 @@ ELevel getPriority(const char *&fmt) { return static_cast(fmt[2] - '0'); } -void makeTimeString(std::vector &buffer) { +void makeTimeString(std::vector &buffer) +{ const int yearOffset = 1900; const int monthOffset = 1; @@ -80,14 +80,13 @@ void makeTimeString(std::vector &buffer) { #endif snprintf( - buffer.data(), buffer.size(), "%04i-%02i-%02iT%02i:%02i:%02i", - tm.tm_year + yearOffset, tm.tm_mon + monthOffset, tm.tm_mday, tm.tm_hour, - tm.tm_min, tm.tm_sec); + buffer.data(), buffer.size(), "%04i-%02i-%02iT%02i:%02i:%02i", tm.tm_year + yearOffset, tm.tm_mon + monthOffset, + tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec + ); } -std::vector makeMessage( - const char *filename, int lineNumber, const char *message, - ELevel priority) { +std::vector makeMessage(const char *filename, int lineNumber, const char *message, ELevel priority) +{ // base size includes null terminator, colon, space, etc. const int baseSize = 10; @@ -101,8 +100,7 @@ std::vector makeMessage( size_t timestampLength = strnlen(timeBuffer.data(), timeBufferSize); size_t priorityLength = strnlen(g_priority[priority], priorityMaxSize); size_t messageLength = strnlen(message, SIZE_MAX); - size_t bufferSize = - baseSize + timestampLength + priorityLength + messageLength; + size_t bufferSize = baseSize + timestampLength + priorityLength + messageLength; const auto filenameSet = filename != nullptr && filename[0] != '\0'; if (filenameSet) { @@ -112,14 +110,13 @@ std::vector makeMessage( std::vector buffer(bufferSize); snprintf( - buffer.data(), bufferSize, "[%s] %s: %s\n\t%s:%d", timeBuffer.data(), - g_priority[priority], message, filename, lineNumber); + buffer.data(), bufferSize, "[%s] %s: %s\n\t%s:%d", timeBuffer.data(), g_priority[priority], message, filename, + lineNumber + ); return buffer; } else { std::vector buffer(bufferSize); - snprintf( - buffer.data(), bufferSize, "[%s] %s: %s", timeBuffer.data(), - g_priority[priority], message); + snprintf(buffer.data(), bufferSize, "[%s] %s: %s", timeBuffer.data(), g_priority[priority], message); return buffer; } } @@ -131,7 +128,8 @@ std::vector makeMessage( Log *Log::s_log = NULL; -Log::Log(bool singleton) { +Log::Log(bool singleton) +{ if (singleton) { assert(s_log == NULL); } @@ -148,36 +146,44 @@ Log::Log(bool singleton) { } } -Log::Log(Log *src) { s_log = src; } +Log::Log(Log *src) +{ + s_log = src; +} -Log::~Log() { +Log::~Log() +{ // clean up - for (OutputterList::iterator index = m_outputters.begin(); - index != m_outputters.end(); ++index) { + for (OutputterList::iterator index = m_outputters.begin(); index != m_outputters.end(); ++index) { delete *index; } - for (OutputterList::iterator index = m_alwaysOutputters.begin(); - index != m_alwaysOutputters.end(); ++index) { + for (OutputterList::iterator index = m_alwaysOutputters.begin(); index != m_alwaysOutputters.end(); ++index) { delete *index; } ARCH->closeMutex(m_mutex); } -Log *Log::getInstance() { +Log *Log::getInstance() +{ assert(s_log != NULL); return s_log; } -const char *Log::getFilterName() const { return getFilterName(getFilter()); } +const char *Log::getFilterName() const +{ + return getFilterName(getFilter()); +} -const char *Log::getFilterName(int level) const { +const char *Log::getFilterName(int level) const +{ if (level < 0) { return "Message"; } return g_priority[level]; } -void Log::print(const char *file, int line, const char *fmt, ...) { +void Log::print(const char *file, int line, const char *fmt, ...) +{ const int initBufferSize = 1024; const int bufferResizeScale = 2; @@ -213,7 +219,8 @@ void Log::print(const char *file, int line, const char *fmt, ...) { } } -void Log::insert(ILogOutputter *outputter, bool alwaysAtHead) { +void Log::insert(ILogOutputter *outputter, bool alwaysAtHead) +{ assert(outputter != NULL); ArchMutexLock lock(m_mutex); @@ -235,13 +242,15 @@ void Log::insert(ILogOutputter *outputter, bool alwaysAtHead) { // outputter->show(false); } -void Log::remove(ILogOutputter *outputter) { +void Log::remove(ILogOutputter *outputter) +{ ArchMutexLock lock(m_mutex); m_outputters.remove(outputter); m_alwaysOutputters.remove(outputter); } -void Log::pop_front(bool alwaysAtHead) { +void Log::pop_front(bool alwaysAtHead) +{ ArchMutexLock lock(m_mutex); OutputterList *list = alwaysAtHead ? &m_alwaysOutputters : &m_outputters; if (!list->empty()) { @@ -250,7 +259,8 @@ void Log::pop_front(bool alwaysAtHead) { } } -bool Log::setFilter(const char *maxPriority) { +bool Log::setFilter(const char *maxPriority) +{ if (maxPriority != NULL) { for (int i = 0; i < g_numPriority; ++i) { if (strcmp(maxPriority, g_priority[i]) == 0) { @@ -263,17 +273,20 @@ bool Log::setFilter(const char *maxPriority) { return true; } -void Log::setFilter(int maxPriority) { +void Log::setFilter(int maxPriority) +{ ArchMutexLock lock(m_mutex); m_maxPriority = maxPriority; } -int Log::getFilter() const { +int Log::getFilter() const +{ ArchMutexLock lock(m_mutex); return m_maxPriority; } -void Log::output(ELevel priority, char *msg) { +void Log::output(ELevel priority, char *msg) +{ assert(priority >= -1 && priority < g_numPriority); assert(msg != NULL); if (!msg) diff --git a/src/lib/base/Log.h b/src/lib/base/Log.h index 8bbabf310..9337dcb77 100644 --- a/src/lib/base/Log.h +++ b/src/lib/base/Log.h @@ -38,7 +38,8 @@ It supports multithread safe operation, several message priority levels, filtering by priority, and output redirection. The macros LOG() and LOGC() provide convenient access. */ -class Log { +class Log +{ public: Log(bool singleton = true); Log(Log *src); @@ -124,7 +125,10 @@ public: //! Get the console filter level (messages above this are not sent to //! console). - int getConsoleMaxLevel() const { return kDEBUG2; } + int getConsoleMaxLevel() const + { + return kDEBUG2; + } //@} @@ -187,14 +191,14 @@ otherwise it expands to a call that doesn't. #define CLOG_TRACE #elif defined(NDEBUG) #define LOG(_a1) CLOG->print _a1 -#define LOGC(_a1, _a2) \ - if (_a1) \ +#define LOGC(_a1, _a2) \ + if (_a1) \ CLOG->print _a2 #define CLOG_TRACE NULL, 0, #else #define LOG(_a1) CLOG->print _a1 -#define LOGC(_a1, _a2) \ - if (_a1) \ +#define LOGC(_a1, _a2) \ + if (_a1) \ CLOG->print _a2 #define CLOG_TRACE __FILE__, __LINE__, #endif diff --git a/src/lib/base/Path.cpp b/src/lib/base/Path.cpp index 668364718..b3d812fbb 100644 --- a/src/lib/base/Path.cpp +++ b/src/lib/base/Path.cpp @@ -26,24 +26,24 @@ namespace filesystem { #ifdef SYSAPI_WIN32 -std::wstring path(const String &filePath) { +std::wstring path(const String &filePath) +{ std::wstring result; - auto length = MultiByteToWideChar( - CP_UTF8, 0, filePath.c_str(), static_cast(filePath.length()), NULL, - 0); + auto length = MultiByteToWideChar(CP_UTF8, 0, filePath.c_str(), static_cast(filePath.length()), NULL, 0); if (length > 0) { result.resize(length); - MultiByteToWideChar( - CP_UTF8, 0, filePath.c_str(), static_cast(filePath.length()), - &result[0], length); + MultiByteToWideChar(CP_UTF8, 0, filePath.c_str(), static_cast(filePath.length()), &result[0], length); } return result; } #else -std::string path(const String &filePath) { return filePath; } +std::string path(const String &filePath) +{ + return filePath; +} #endif } // namespace filesystem diff --git a/src/lib/base/PriorityQueue.h b/src/lib/base/PriorityQueue.h index c1bf6f7ad..de61c9b18 100644 --- a/src/lib/base/PriorityQueue.h +++ b/src/lib/base/PriorityQueue.h @@ -36,7 +36,8 @@ template < #else class Compare = std::greater> #endif -class PriorityQueue { +class PriorityQueue +{ public: typedef typename Container::value_type value_type; typedef typename Container::size_type size_type; @@ -44,42 +45,62 @@ public: typedef typename Container::const_iterator const_iterator; typedef Container container_type; - PriorityQueue() {} - PriorityQueue(Container &swappedIn) { swap(swappedIn); } - ~PriorityQueue() {} + PriorityQueue() + { + } + PriorityQueue(Container &swappedIn) + { + swap(swappedIn); + } + ~PriorityQueue() + { + } //! @name manipulators //@{ //! Add element - void push(const value_type &v) { + void push(const value_type &v) + { c.push_back(v); std::push_heap(c.begin(), c.end(), comp); } //! Remove head element - void pop() { + void pop() + { std::pop_heap(c.begin(), c.end(), comp); c.pop_back(); } //! Erase element - void erase(iterator i) { + void erase(iterator i) + { c.erase(i); std::make_heap(c.begin(), c.end(), comp); } //! Get start iterator - iterator begin() { return c.begin(); } + iterator begin() + { + return c.begin(); + } //! Get end iterator - iterator end() { return c.end(); } + iterator end() + { + return c.end(); + } //! Swap contents with another priority queue - void swap(PriorityQueue &q) { c.swap(q.c); } + void swap(PriorityQueue &q) + { + c.swap(q.c); + } //! Swap contents with another container - void swap(Container &c2) { + void swap(Container &c2) + { c.swap(c2); std::make_heap(c.begin(), c.end(), comp); } @@ -89,19 +110,34 @@ public: //@{ //! Returns true if there are no elements - bool empty() const { return c.empty(); } + bool empty() const + { + return c.empty(); + } //! Returns the number of elements - size_type size() const { return c.size(); } + size_type size() const + { + return c.size(); + } //! Returns the head element - const value_type &top() const { return c.front(); } + const value_type &top() const + { + return c.front(); + } //! Get start iterator - const_iterator begin() const { return c.begin(); } + const_iterator begin() const + { + return c.begin(); + } //! Get end iterator - const_iterator end() const { return c.end(); } + const_iterator end() const + { + return c.end(); + } //@} diff --git a/src/lib/base/SimpleEventQueueBuffer.cpp b/src/lib/base/SimpleEventQueueBuffer.cpp index aa512cb1c..b8130eb8a 100644 --- a/src/lib/base/SimpleEventQueueBuffer.cpp +++ b/src/lib/base/SimpleEventQueueBuffer.cpp @@ -20,24 +20,29 @@ #include "arch/Arch.h" #include "base/Stopwatch.h" -class EventQueueTimer {}; +class EventQueueTimer +{ +}; // // SimpleEventQueueBuffer // -SimpleEventQueueBuffer::SimpleEventQueueBuffer() { +SimpleEventQueueBuffer::SimpleEventQueueBuffer() +{ m_queueMutex = ARCH->newMutex(); m_queueReadyCond = ARCH->newCondVar(); m_queueReady = false; } -SimpleEventQueueBuffer::~SimpleEventQueueBuffer() { +SimpleEventQueueBuffer::~SimpleEventQueueBuffer() +{ ARCH->closeCondVar(m_queueReadyCond); ARCH->closeMutex(m_queueMutex); } -void SimpleEventQueueBuffer::waitForEvent(double timeout) { +void SimpleEventQueueBuffer::waitForEvent(double timeout) +{ ArchMutexLock lock(m_queueMutex); Stopwatch timer(true); while (!m_queueReady) { @@ -52,8 +57,8 @@ void SimpleEventQueueBuffer::waitForEvent(double timeout) { } } -IEventQueueBuffer::Type -SimpleEventQueueBuffer::getEvent(Event &, UInt32 &dataID) { +IEventQueueBuffer::Type SimpleEventQueueBuffer::getEvent(Event &, UInt32 &dataID) +{ ArchMutexLock lock(m_queueMutex); if (!m_queueReady) { return kNone; @@ -64,7 +69,8 @@ SimpleEventQueueBuffer::getEvent(Event &, UInt32 &dataID) { return kUser; } -bool SimpleEventQueueBuffer::addEvent(UInt32 dataID) { +bool SimpleEventQueueBuffer::addEvent(UInt32 dataID) +{ ArchMutexLock lock(m_queueMutex); m_queue.push_front(dataID); if (!m_queueReady) { @@ -74,15 +80,18 @@ bool SimpleEventQueueBuffer::addEvent(UInt32 dataID) { return true; } -bool SimpleEventQueueBuffer::isEmpty() const { +bool SimpleEventQueueBuffer::isEmpty() const +{ ArchMutexLock lock(m_queueMutex); return !m_queueReady; } -EventQueueTimer *SimpleEventQueueBuffer::newTimer(double, bool) const { +EventQueueTimer *SimpleEventQueueBuffer::newTimer(double, bool) const +{ return new EventQueueTimer; } -void SimpleEventQueueBuffer::deleteTimer(EventQueueTimer *timer) const { +void SimpleEventQueueBuffer::deleteTimer(EventQueueTimer *timer) const +{ delete timer; } diff --git a/src/lib/base/SimpleEventQueueBuffer.h b/src/lib/base/SimpleEventQueueBuffer.h index d8f460315..b4432682b 100644 --- a/src/lib/base/SimpleEventQueueBuffer.h +++ b/src/lib/base/SimpleEventQueueBuffer.h @@ -26,7 +26,8 @@ /*! An event queue buffer provides a queue of events for an IEventQueue. */ -class SimpleEventQueueBuffer : public IEventQueueBuffer { +class SimpleEventQueueBuffer : public IEventQueueBuffer +{ public: SimpleEventQueueBuffer(); SimpleEventQueueBuffer(SimpleEventQueueBuffer const &) = delete; @@ -37,7 +38,9 @@ public: SimpleEventQueueBuffer &operator=(SimpleEventQueueBuffer &&) = delete; // IEventQueueBuffer overrides - void init() {} + void init() + { + } virtual void waitForEvent(double timeout); virtual Type getEvent(Event &event, UInt32 &dataID); virtual bool addEvent(UInt32 dataID); diff --git a/src/lib/base/Stopwatch.cpp b/src/lib/base/Stopwatch.cpp index 758f09f2c..f7f25d65b 100644 --- a/src/lib/base/Stopwatch.cpp +++ b/src/lib/base/Stopwatch.cpp @@ -23,20 +23,20 @@ // Stopwatch // -Stopwatch::Stopwatch(bool triggered) - : m_mark(0.0), - m_triggered(triggered), - m_stopped(triggered) { +Stopwatch::Stopwatch(bool triggered) : m_mark(0.0), m_triggered(triggered), m_stopped(triggered) +{ if (!triggered) { m_mark = ARCH->time(); } } -Stopwatch::~Stopwatch() { +Stopwatch::~Stopwatch() +{ // do nothing } -double Stopwatch::reset() { +double Stopwatch::reset() +{ if (m_stopped) { const double dt = m_mark; m_mark = 0.0; @@ -49,7 +49,8 @@ double Stopwatch::reset() { } } -void Stopwatch::stop() { +void Stopwatch::stop() +{ if (m_stopped) { return; } @@ -59,7 +60,8 @@ void Stopwatch::stop() { m_stopped = true; } -void Stopwatch::start() { +void Stopwatch::start() +{ m_triggered = false; if (!m_stopped) { return; @@ -70,12 +72,14 @@ void Stopwatch::start() { m_stopped = false; } -void Stopwatch::setTrigger() { +void Stopwatch::setTrigger() +{ stop(); m_triggered = true; } -double Stopwatch::getTime() { +double Stopwatch::getTime() +{ if (m_triggered) { const double dt = m_mark; start(); @@ -87,11 +91,18 @@ double Stopwatch::getTime() { } } -Stopwatch::operator double() { return getTime(); } +Stopwatch::operator double() +{ + return getTime(); +} -bool Stopwatch::isStopped() const { return m_stopped; } +bool Stopwatch::isStopped() const +{ + return m_stopped; +} -double Stopwatch::getTime() const { +double Stopwatch::getTime() const +{ if (m_stopped) { return m_mark; } else { @@ -99,4 +110,7 @@ double Stopwatch::getTime() const { } } -Stopwatch::operator double() const { return getTime(); } +Stopwatch::operator double() const +{ + return getTime(); +} diff --git a/src/lib/base/Stopwatch.h b/src/lib/base/Stopwatch.h index e4816ed4b..e280e53dd 100644 --- a/src/lib/base/Stopwatch.h +++ b/src/lib/base/Stopwatch.h @@ -25,7 +25,8 @@ This class measures time intervals. All time interval measurement should use this class. */ -class Stopwatch { +class Stopwatch +{ public: /*! The default constructor does an implicit reset() or setTrigger(). diff --git a/src/lib/base/String.cpp b/src/lib/base/String.cpp index a060dbd7a..9b73883f1 100644 --- a/src/lib/base/String.cpp +++ b/src/lib/base/String.cpp @@ -34,7 +34,8 @@ namespace deskflow { namespace string { -String format(const char *fmt, ...) { +String format(const char *fmt, ...) +{ va_list args; va_start(args, fmt); String result = vformat(fmt, args); @@ -42,7 +43,8 @@ String format(const char *fmt, ...) { return result; } -String vformat(const char *fmt, va_list args) { +String vformat(const char *fmt, va_list args) +{ // find highest indexed substitution and the locations of substitutions std::vector pos; std::vector width; @@ -119,7 +121,8 @@ String vformat(const char *fmt, va_list args) { return result; } -String sprintf(const char *fmt, ...) { +String sprintf(const char *fmt, ...) +{ char tmp[1024]; char *buffer = tmp; int len = (int)(sizeof(tmp) / sizeof(tmp[0])); @@ -153,8 +156,8 @@ String sprintf(const char *fmt, ...) { return result; } -void findReplaceAll( - String &subject, const String &find, const String &replace) { +void findReplaceAll(String &subject, const String &find, const String &replace) +{ size_t pos = 0; while ((pos = subject.find(find, pos)) != String::npos) { subject.replace(pos, find.length(), replace); @@ -162,7 +165,8 @@ void findReplaceAll( } } -String removeFileExt(String filename) { +String removeFileExt(String filename) +{ size_t dot = filename.find_last_of('.'); if (dot == String::npos) { @@ -172,39 +176,44 @@ String removeFileExt(String filename) { return filename.substr(0, dot); } -void toHex(String &subject, int width, const char fill) { +void toHex(String &subject, int width, const char fill) +{ std::stringstream ss; ss << std::hex; for (unsigned int i = 0; i < subject.length(); i++) { - ss << std::setw(width) << std::setfill(fill) - << (int)(unsigned char)subject[i]; + ss << std::setw(width) << std::setfill(fill) << (int)(unsigned char)subject[i]; } subject = ss.str(); } -void uppercase(String &subject) { +void uppercase(String &subject) +{ std::transform(subject.begin(), subject.end(), subject.begin(), ::toupper); } -void removeChar(String &subject, const char c) { +void removeChar(String &subject, const char c) +{ subject.erase(std::remove(subject.begin(), subject.end(), c), subject.end()); } -String sizeTypeToString(size_t n) { +String sizeTypeToString(size_t n) +{ std::stringstream ss; ss << n; return ss.str(); } -size_t stringToSizeType(String string) { +size_t stringToSizeType(String string) +{ std::istringstream iss(string); size_t value; iss >> value; return value; } -std::vector splitString(String string, const char c) { +std::vector splitString(String string, const char c) +{ std::vector results; size_t head = 0; @@ -228,29 +237,30 @@ std::vector splitString(String string, const char c) { // CaselessCmp // -bool CaselessCmp::cmpEqual( - const String::value_type &a, const String::value_type &b) { +bool CaselessCmp::cmpEqual(const String::value_type &a, const String::value_type &b) +{ // should use std::tolower but not in all versions of libstdc++ have it return tolower(a) == tolower(b); } -bool CaselessCmp::cmpLess( - const String::value_type &a, const String::value_type &b) { +bool CaselessCmp::cmpLess(const String::value_type &a, const String::value_type &b) +{ // should use std::tolower but not in all versions of libstdc++ have it return tolower(a) < tolower(b); } -bool CaselessCmp::less(const String &a, const String &b) { - return std::lexicographical_compare( - a.begin(), a.end(), b.begin(), b.end(), - &deskflow::string::CaselessCmp::cmpLess); +bool CaselessCmp::less(const String &a, const String &b) +{ + return std::lexicographical_compare(a.begin(), a.end(), b.begin(), b.end(), &deskflow::string::CaselessCmp::cmpLess); } -bool CaselessCmp::equal(const String &a, const String &b) { +bool CaselessCmp::equal(const String &a, const String &b) +{ return !(less(a, b) || less(b, a)); } -bool CaselessCmp::operator()(const String &a, const String &b) const { +bool CaselessCmp::operator()(const String &a, const String &b) const +{ return less(a, b); } diff --git a/src/lib/base/String.h b/src/lib/base/String.h index d2b5b5019..6bd53f41a 100644 --- a/src/lib/base/String.h +++ b/src/lib/base/String.h @@ -111,7 +111,8 @@ std::vector splitString(String string, const char c); /*! This class provides case-insensitve comparison functions. */ -class CaselessCmp { +class CaselessCmp +{ public: //! Same as less() bool operator()(const String &a, const String &b) const; @@ -126,8 +127,7 @@ public: static bool cmpLess(const String::value_type &a, const String::value_type &b); //! Returns true iff \c a is lexicographically equal to \c b - static bool - cmpEqual(const String::value_type &a, const String::value_type &b); + static bool cmpEqual(const String::value_type &a, const String::value_type &b); }; } // namespace string diff --git a/src/lib/base/TMethodEventJob.h b/src/lib/base/TMethodEventJob.h index 16a524d72..db3df2fa0 100644 --- a/src/lib/base/TMethodEventJob.h +++ b/src/lib/base/TMethodEventJob.h @@ -24,11 +24,11 @@ /*! An event job class that invokes a member function. */ -template class TMethodEventJob : public IEventJob { +template class TMethodEventJob : public IEventJob +{ public: //! run(event) invokes \c object->method(event, arg) - TMethodEventJob( - T *object, void (T::*method)(const Event &, void *), void *arg = NULL); + TMethodEventJob(T *object, void (T::*method)(const Event &, void *), void *arg = NULL); virtual ~TMethodEventJob(); // IJob overrides @@ -41,19 +41,21 @@ private: }; template -inline TMethodEventJob::TMethodEventJob( - T *object, void (T::*method)(const Event &, void *), void *arg) +inline TMethodEventJob::TMethodEventJob(T *object, void (T::*method)(const Event &, void *), void *arg) : m_object(object), m_method(method), - m_arg(arg) { + m_arg(arg) +{ // do nothing } -template inline TMethodEventJob::~TMethodEventJob() { +template inline TMethodEventJob::~TMethodEventJob() +{ // do nothing } -template inline void TMethodEventJob::run(const Event &event) { +template inline void TMethodEventJob::run(const Event &event) +{ if (m_object != NULL) { (m_object->*m_method)(event, m_arg); } diff --git a/src/lib/base/TMethodJob.h b/src/lib/base/TMethodJob.h index dd9b508d8..e900a0420 100644 --- a/src/lib/base/TMethodJob.h +++ b/src/lib/base/TMethodJob.h @@ -24,7 +24,8 @@ /*! A job class that invokes a member function. */ -template class TMethodJob : public IJob { +template class TMethodJob : public IJob +{ public: //! run() invokes \c object->method(arg) TMethodJob(T *object, void (T::*method)(void *), void *arg = NULL); @@ -40,19 +41,21 @@ private: }; template -inline TMethodJob::TMethodJob( - T *object, void (T::*method)(void *), void *arg) +inline TMethodJob::TMethodJob(T *object, void (T::*method)(void *), void *arg) : m_object(object), m_method(method), - m_arg(arg) { + m_arg(arg) +{ // do nothing } -template inline TMethodJob::~TMethodJob() { +template inline TMethodJob::~TMethodJob() +{ // do nothing } -template inline void TMethodJob::run() { +template inline void TMethodJob::run() +{ if (m_object != NULL) { (m_object->*m_method)(m_arg); } diff --git a/src/lib/base/Unicode.cpp b/src/lib/base/Unicode.cpp index 35ab791d9..585bcad30 100644 --- a/src/lib/base/Unicode.cpp +++ b/src/lib/base/Unicode.cpp @@ -25,8 +25,10 @@ // local utility functions // -inline static UInt16 decode16(const UInt8 *n, bool byteSwapped) { - union x16 { +inline static UInt16 decode16(const UInt8 *n, bool byteSwapped) +{ + union x16 + { UInt8 n8[2]; UInt16 n16; } c; @@ -40,8 +42,10 @@ inline static UInt16 decode16(const UInt8 *n, bool byteSwapped) { return c.n16; } -inline static UInt32 decode32(const UInt8 *n, bool byteSwapped) { - union x32 { +inline static UInt32 decode32(const UInt8 *n, bool byteSwapped) +{ + union x32 + { UInt8 n8[4]; UInt32 n32; } c; @@ -59,13 +63,15 @@ inline static UInt32 decode32(const UInt8 *n, bool byteSwapped) { return c.n32; } -inline static void resetError(bool *errors) { +inline static void resetError(bool *errors) +{ if (errors != NULL) { *errors = false; } } -inline static void setError(bool *errors) { +inline static void setError(bool *errors) +{ if (errors != NULL) { *errors = true; } @@ -78,7 +84,8 @@ inline static void setError(bool *errors) { UInt32 Unicode::s_invalid = 0x0000ffff; UInt32 Unicode::s_replacement = 0x0000fffd; -bool Unicode::isUTF8(const String &src) { +bool Unicode::isUTF8(const String &src) +{ // convert and test each character const UInt8 *data = reinterpret_cast(src.c_str()); for (UInt32 n = (UInt32)src.size(); n > 0;) { @@ -89,7 +96,8 @@ bool Unicode::isUTF8(const String &src) { return true; } -String Unicode::UTF8ToUCS2(const String &src, bool *errors) { +String Unicode::UTF8ToUCS2(const String &src, bool *errors) +{ // default to success resetError(errors); @@ -115,7 +123,8 @@ String Unicode::UTF8ToUCS2(const String &src, bool *errors) { return dst; } -String Unicode::UTF8ToUCS4(const String &src, bool *errors) { +String Unicode::UTF8ToUCS4(const String &src, bool *errors) +{ // default to success resetError(errors); @@ -137,7 +146,8 @@ String Unicode::UTF8ToUCS4(const String &src, bool *errors) { return dst; } -String Unicode::UTF8ToUTF16(const String &src, bool *errors) { +String Unicode::UTF8ToUTF16(const String &src, bool *errors) +{ // default to success resetError(errors); @@ -171,7 +181,8 @@ String Unicode::UTF8ToUTF16(const String &src, bool *errors) { return dst; } -String Unicode::UTF8ToUTF32(const String &src, bool *errors) { +String Unicode::UTF8ToUTF32(const String &src, bool *errors) +{ // default to success resetError(errors); @@ -196,7 +207,8 @@ String Unicode::UTF8ToUTF32(const String &src, bool *errors) { return dst; } -String Unicode::UTF8ToText(const String &src, bool *errors) { +String Unicode::UTF8ToText(const String &src, bool *errors) +{ // default to success resetError(errors); @@ -217,7 +229,8 @@ String Unicode::UTF8ToText(const String &src, bool *errors) { return text; } -String Unicode::UCS2ToUTF8(const String &src, bool *errors) { +String Unicode::UCS2ToUTF8(const String &src, bool *errors) +{ // default to success resetError(errors); @@ -226,7 +239,8 @@ String Unicode::UCS2ToUTF8(const String &src, bool *errors) { return doUCS2ToUTF8(reinterpret_cast(src.data()), n, errors); } -String Unicode::UCS4ToUTF8(const String &src, bool *errors) { +String Unicode::UCS4ToUTF8(const String &src, bool *errors) +{ // default to success resetError(errors); @@ -235,7 +249,8 @@ String Unicode::UCS4ToUTF8(const String &src, bool *errors) { return doUCS4ToUTF8(reinterpret_cast(src.data()), n, errors); } -String Unicode::UTF16ToUTF8(const String &src, bool *errors) { +String Unicode::UTF16ToUTF8(const String &src, bool *errors) +{ // default to success resetError(errors); @@ -244,7 +259,8 @@ String Unicode::UTF16ToUTF8(const String &src, bool *errors) { return doUTF16ToUTF8(reinterpret_cast(src.data()), n, errors); } -String Unicode::UTF32ToUTF8(const String &src, bool *errors) { +String Unicode::UTF32ToUTF8(const String &src, bool *errors) +{ // default to success resetError(errors); @@ -253,8 +269,8 @@ String Unicode::UTF32ToUTF8(const String &src, bool *errors) { return doUTF32ToUTF8(reinterpret_cast(src.data()), n, errors); } -String Unicode::textToUTF8( - const String &src, bool *errors, IArchString::EWideCharEncoding encoding) { +String Unicode::textToUTF8(const String &src, bool *errors, IArchString::EWideCharEncoding encoding) +{ // default to success resetError(errors); @@ -273,8 +289,8 @@ String Unicode::textToUTF8( return utf8; } -wchar_t * -Unicode::UTF8ToWideChar(const String &src, UInt32 &size, bool *errors) { +wchar_t *Unicode::UTF8ToWideChar(const String &src, UInt32 &size, bool *errors) +{ // convert to platform's wide character encoding String tmp; switch (ARCH->getWideCharEncoding()) { @@ -308,9 +324,8 @@ Unicode::UTF8ToWideChar(const String &src, UInt32 &size, bool *errors) { return dst; } -String Unicode::wideCharToUTF8( - const wchar_t *src, UInt32 size, bool *errors, - IArchString::EWideCharEncoding encoding) { +String Unicode::wideCharToUTF8(const wchar_t *src, UInt32 size, bool *errors, IArchString::EWideCharEncoding encoding) +{ if (encoding == IArchString::kPlatformDetermined) { encoding = ARCH->getWideCharEncoding(); } @@ -336,7 +351,8 @@ String Unicode::wideCharToUTF8( } } -String Unicode::doUCS2ToUTF8(const UInt8 *data, UInt32 n, bool *errors) { +String Unicode::doUCS2ToUTF8(const UInt8 *data, UInt32 n, bool *errors) +{ // make some space String dst; dst.reserve(n); @@ -371,7 +387,8 @@ String Unicode::doUCS2ToUTF8(const UInt8 *data, UInt32 n, bool *errors) { return dst; } -String Unicode::doUCS4ToUTF8(const UInt8 *data, UInt32 n, bool *errors) { +String Unicode::doUCS4ToUTF8(const UInt8 *data, UInt32 n, bool *errors) +{ // make some space String dst; dst.reserve(n); @@ -406,7 +423,8 @@ String Unicode::doUCS4ToUTF8(const UInt8 *data, UInt32 n, bool *errors) { return dst; } -String Unicode::doUTF16ToUTF8(const UInt8 *data, UInt32 n, bool *errors) { +String Unicode::doUTF16ToUTF8(const UInt8 *data, UInt32 n, bool *errors) +{ // make some space String dst; dst.reserve(n); @@ -464,7 +482,8 @@ String Unicode::doUTF16ToUTF8(const UInt8 *data, UInt32 n, bool *errors) { return dst; } -String Unicode::doUTF32ToUTF8(const UInt8 *data, UInt32 n, bool *errors) { +String Unicode::doUTF32ToUTF8(const UInt8 *data, UInt32 n, bool *errors) +{ // make some space String dst; dst.reserve(n); @@ -503,7 +522,8 @@ String Unicode::doUTF32ToUTF8(const UInt8 *data, UInt32 n, bool *errors) { return dst; } -UInt32 Unicode::fromUTF8(const UInt8 *&data, UInt32 &n) { +UInt32 Unicode::fromUTF8(const UInt8 *&data, UInt32 &n) +{ assert(data != NULL); assert(n != 0); @@ -557,38 +577,29 @@ UInt32 Unicode::fromUTF8(const UInt8 *&data, UInt32 &n) { break; case 2: - c = ((static_cast(data[0]) & 0x1f) << 6) | - ((static_cast(data[1]) & 0x3f)); + c = ((static_cast(data[0]) & 0x1f) << 6) | ((static_cast(data[1]) & 0x3f)); break; case 3: - c = ((static_cast(data[0]) & 0x0f) << 12) | - ((static_cast(data[1]) & 0x3f) << 6) | + c = ((static_cast(data[0]) & 0x0f) << 12) | ((static_cast(data[1]) & 0x3f) << 6) | ((static_cast(data[2]) & 0x3f)); break; case 4: - c = ((static_cast(data[0]) & 0x07) << 18) | - ((static_cast(data[1]) & 0x3f) << 12) | - ((static_cast(data[2]) & 0x3f) << 6) | - ((static_cast(data[3]) & 0x3f)); + c = ((static_cast(data[0]) & 0x07) << 18) | ((static_cast(data[1]) & 0x3f) << 12) | + ((static_cast(data[2]) & 0x3f) << 6) | ((static_cast(data[3]) & 0x3f)); break; case 5: - c = ((static_cast(data[0]) & 0x03) << 24) | - ((static_cast(data[1]) & 0x3f) << 18) | - ((static_cast(data[2]) & 0x3f) << 12) | - ((static_cast(data[3]) & 0x3f) << 6) | + c = ((static_cast(data[0]) & 0x03) << 24) | ((static_cast(data[1]) & 0x3f) << 18) | + ((static_cast(data[2]) & 0x3f) << 12) | ((static_cast(data[3]) & 0x3f) << 6) | ((static_cast(data[4]) & 0x3f)); break; case 6: - c = ((static_cast(data[0]) & 0x01) << 30) | - ((static_cast(data[1]) & 0x3f) << 24) | - ((static_cast(data[2]) & 0x3f) << 18) | - ((static_cast(data[3]) & 0x3f) << 12) | - ((static_cast(data[4]) & 0x3f) << 6) | - ((static_cast(data[5]) & 0x3f)); + c = ((static_cast(data[0]) & 0x01) << 30) | ((static_cast(data[1]) & 0x3f) << 24) | + ((static_cast(data[2]) & 0x3f) << 18) | ((static_cast(data[3]) & 0x3f) << 12) | + ((static_cast(data[4]) & 0x3f) << 6) | ((static_cast(data[5]) & 0x3f)); break; default: @@ -645,8 +656,7 @@ UInt32 Unicode::fromUTF8(const UInt8 *&data, UInt32 &n) { } // check for characters that didn't use the smallest possible encoding - static UInt32 s_minChar[] = {0, 0x00000000, 0x00000080, 0x00000800, - 0x00010000, 0x00200000, 0x04000000}; + static UInt32 s_minChar[] = {0, 0x00000000, 0x00000080, 0x00000800, 0x00010000, 0x00200000, 0x04000000}; if (c < s_minChar[size]) { return s_invalid; } @@ -662,7 +672,8 @@ UInt32 Unicode::fromUTF8(const UInt8 *&data, UInt32 &n) { return c; } -void Unicode::toUTF8(String &dst, UInt32 c, bool *errors) { +void Unicode::toUTF8(String &dst, UInt32 c, bool *errors) +{ UInt8 data[6]; // handle characters outside the valid range diff --git a/src/lib/base/Unicode.h b/src/lib/base/Unicode.h index f3a2b603b..bd076934a 100644 --- a/src/lib/base/Unicode.h +++ b/src/lib/base/Unicode.h @@ -27,7 +27,8 @@ This class provides functions for converting between various Unicode encodings and the current locale encoding. */ -class Unicode { +class Unicode +{ public: //! @name accessors //@{ @@ -113,9 +114,8 @@ public: NULL then *errors is set to true iff any character could not be decoded. */ static String textToUTF8( - const String &, bool *errors = nullptr, - IArchString::EWideCharEncoding encoding = - IArchString::kPlatformDetermined); + const String &, bool *errors = nullptr, IArchString::EWideCharEncoding encoding = IArchString::kPlatformDetermined + ); //@} @@ -130,8 +130,8 @@ private: // encoding) to UTF8. static String wideCharToUTF8( const wchar_t *, UInt32 size, bool *errors, - IArchString::EWideCharEncoding encoding = - IArchString::kPlatformDetermined); + IArchString::EWideCharEncoding encoding = IArchString::kPlatformDetermined + ); // internal conversion to UTF8 static String doUCS2ToUTF8(const UInt8 *src, UInt32 n, bool *errors); diff --git a/src/lib/base/XBase.cpp b/src/lib/base/XBase.cpp index 45a305888..8dd1bd12d 100644 --- a/src/lib/base/XBase.cpp +++ b/src/lib/base/XBase.cpp @@ -27,21 +27,24 @@ // XBase // -XBase::XBase() : std::runtime_error("") { +XBase::XBase() : std::runtime_error("") +{ // do nothing } -XBase::XBase(const String &msg) : std::runtime_error(msg) { +XBase::XBase(const String &msg) : std::runtime_error(msg) +{ // do nothing } -XBase::~XBase() _NOEXCEPT { +XBase::~XBase() _NOEXCEPT +{ // do nothing } -const char *XBase::what() const _NOEXCEPT { - if (const char *what = std::runtime_error::what(); - what != nullptr && what[0] != '\0') { +const char *XBase::what() const _NOEXCEPT +{ + if (const char *what = std::runtime_error::what(); what != nullptr && what[0] != '\0') { return what; } @@ -49,7 +52,8 @@ const char *XBase::what() const _NOEXCEPT { return m_what.c_str(); } -String XBase::format(const char * /*id*/, const char *fmt, ...) const throw() { +String XBase::format(const char * /*id*/, const char *fmt, ...) const throw() +{ // FIXME -- lookup message string using id as an index. set // fmt to that string if it exists. diff --git a/src/lib/base/XBase.h b/src/lib/base/XBase.h index 21e167b39..496cc1bcf 100644 --- a/src/lib/base/XBase.h +++ b/src/lib/base/XBase.h @@ -25,7 +25,8 @@ /*! This is the base class of most exception types. */ -class XBase : public std::runtime_error { +class XBase : public std::runtime_error +{ public: //! Use getWhat() as the result of what() XBase(); @@ -38,7 +39,10 @@ public: protected: //! Get a human readable string describing the exception - virtual String getWhat() const throw() { return ""; } + virtual String getWhat() const throw() + { + return ""; + } //! Format a string /*! @@ -46,8 +50,7 @@ protected: no format can be found, then replaces positional parameters in the format string and returns the result. */ - virtual String format(const char *id, const char *defaultFormat, ...) const - throw(); + virtual String format(const char *id, const char *defaultFormat, ...) const throw(); private: mutable String m_what; @@ -59,12 +62,19 @@ Convenience macro to subclass from XBase (or a subclass of it), providing the c'tor taking a const String&. getWhat() is not declared. */ -#define XBASE_SUBCLASS(name_, super_) \ - class name_ : public super_ { \ - public: \ - name_() : super_() {} \ - name_(const String &msg) : super_(msg) {} \ - virtual ~name_() _NOEXCEPT {} \ +#define XBASE_SUBCLASS(name_, super_) \ + class name_ : public super_ \ + { \ + public: \ + name_() : super_() \ + { \ + } \ + name_(const String &msg) : super_(msg) \ + { \ + } \ + virtual ~name_() _NOEXCEPT \ + { \ + } \ } /*! @@ -73,15 +83,22 @@ Convenience macro to subclass from XBase (or a subclass of it), providing the c'tor taking a const String&. getWhat() must be implemented. */ -#define XBASE_SUBCLASS_WHAT(name_, super_) \ - class name_ : public super_ { \ - public: \ - name_() : super_() {} \ - name_(const String &msg) : super_(msg) {} \ - virtual ~name_() _NOEXCEPT {} \ - \ - protected: \ - virtual String getWhat() const throw(); \ +#define XBASE_SUBCLASS_WHAT(name_, super_) \ + class name_ : public super_ \ + { \ + public: \ + name_() : super_() \ + { \ + } \ + name_(const String &msg) : super_(msg) \ + { \ + } \ + virtual ~name_() _NOEXCEPT \ + { \ + } \ + \ + protected: \ + virtual String getWhat() const throw(); \ } /*! @@ -92,33 +109,46 @@ to call getWhat() when first called; getWhat() can format the error message and can call what() to get the message passed to the c'tor. */ -#define XBASE_SUBCLASS_FORMAT(name_, super_) \ - class name_ : public super_ { \ - private: \ - enum EState { kFirst, kFormat, kDone }; \ - \ - public: \ - name_() : super_(), m_state(kDone) {} \ - name_(const String &msg) : super_(msg), m_state(kFirst) {} \ - virtual ~name_() _NOEXCEPT {} \ - \ - virtual const char *what() const _NOEXCEPT { \ - if (m_state == kFirst) { \ - m_state = kFormat; \ - m_formatted = getWhat(); \ - m_state = kDone; \ - } \ - if (m_state == kDone) { \ - return m_formatted.c_str(); \ - } else { \ - return super_::what(); \ - } \ - } \ - \ - protected: \ - virtual String getWhat() const throw(); \ - \ - private: \ - mutable EState m_state; \ - mutable std::string m_formatted; \ +#define XBASE_SUBCLASS_FORMAT(name_, super_) \ + class name_ : public super_ \ + { \ + private: \ + enum EState \ + { \ + kFirst, \ + kFormat, \ + kDone \ + }; \ + \ + public: \ + name_() : super_(), m_state(kDone) \ + { \ + } \ + name_(const String &msg) : super_(msg), m_state(kFirst) \ + { \ + } \ + virtual ~name_() _NOEXCEPT \ + { \ + } \ + \ + virtual const char *what() const _NOEXCEPT \ + { \ + if (m_state == kFirst) { \ + m_state = kFormat; \ + m_formatted = getWhat(); \ + m_state = kDone; \ + } \ + if (m_state == kDone) { \ + return m_formatted.c_str(); \ + } else { \ + return super_::what(); \ + } \ + } \ + \ + protected: \ + virtual String getWhat() const throw(); \ + \ + private: \ + mutable EState m_state; \ + mutable std::string m_formatted; \ } diff --git a/src/lib/base/log_outputters.cpp b/src/lib/base/log_outputters.cpp index 7af10fd1d..081a1d4a7 100644 --- a/src/lib/base/log_outputters.cpp +++ b/src/lib/base/log_outputters.cpp @@ -23,7 +23,8 @@ #include -enum EFileLogOutputter { +enum EFileLogOutputter +{ kFileSizeLimit = 1024 // kb }; @@ -31,70 +32,104 @@ enum EFileLogOutputter { // StopLogOutputter // -StopLogOutputter::StopLogOutputter() { +StopLogOutputter::StopLogOutputter() +{ // do nothing } -StopLogOutputter::~StopLogOutputter() { +StopLogOutputter::~StopLogOutputter() +{ // do nothing } -void StopLogOutputter::open(const char *) { +void StopLogOutputter::open(const char *) +{ // do nothing } -void StopLogOutputter::close() { +void StopLogOutputter::close() +{ // do nothing } -void StopLogOutputter::show(bool) { +void StopLogOutputter::show(bool) +{ // do nothing } -bool StopLogOutputter::write(ELevel, const char *) { return false; } +bool StopLogOutputter::write(ELevel, const char *) +{ + return false; +} // // ConsoleLogOutputter // -ConsoleLogOutputter::ConsoleLogOutputter() {} +ConsoleLogOutputter::ConsoleLogOutputter() +{ +} -ConsoleLogOutputter::~ConsoleLogOutputter() {} +ConsoleLogOutputter::~ConsoleLogOutputter() +{ +} -void ConsoleLogOutputter::open(const char *title) { ARCH->openConsole(title); } +void ConsoleLogOutputter::open(const char *title) +{ + ARCH->openConsole(title); +} -void ConsoleLogOutputter::close() { ARCH->closeConsole(); } +void ConsoleLogOutputter::close() +{ + ARCH->closeConsole(); +} -void ConsoleLogOutputter::show(bool showIfEmpty) { +void ConsoleLogOutputter::show(bool showIfEmpty) +{ ARCH->showConsole(showIfEmpty); } -bool ConsoleLogOutputter::write(ELevel level, const char *msg) { +bool ConsoleLogOutputter::write(ELevel level, const char *msg) +{ ARCH->writeConsole(level, msg); return true; } -void ConsoleLogOutputter::flush() {} +void ConsoleLogOutputter::flush() +{ +} // // SystemLogOutputter // -SystemLogOutputter::SystemLogOutputter() { +SystemLogOutputter::SystemLogOutputter() +{ // do nothing } -SystemLogOutputter::~SystemLogOutputter() { +SystemLogOutputter::~SystemLogOutputter() +{ // do nothing } -void SystemLogOutputter::open(const char *title) { ARCH->openLog(title); } +void SystemLogOutputter::open(const char *title) +{ + ARCH->openLog(title); +} -void SystemLogOutputter::close() { ARCH->closeLog(); } +void SystemLogOutputter::close() +{ + ARCH->closeLog(); +} -void SystemLogOutputter::show(bool showIfEmpty) { ARCH->showLog(showIfEmpty); } +void SystemLogOutputter::show(bool showIfEmpty) +{ + ARCH->showLog(showIfEmpty); +} -bool SystemLogOutputter::write(ELevel level, const char *msg) { +bool SystemLogOutputter::write(ELevel level, const char *msg) +{ ARCH->writeLog(level, msg); return true; } @@ -103,8 +138,8 @@ bool SystemLogOutputter::write(ELevel level, const char *msg) { // SystemLogger // -SystemLogger::SystemLogger(const char *title, bool blockConsole) - : m_stop(NULL) { +SystemLogger::SystemLogger(const char *title, bool blockConsole) : m_stop(NULL) +{ // redirect log messages if (blockConsole) { m_stop = new StopLogOutputter; @@ -115,7 +150,8 @@ SystemLogger::SystemLogger(const char *title, bool blockConsole) CLOG->insert(m_syslog); } -SystemLogger::~SystemLogger() { +SystemLogger::~SystemLogger() +{ CLOG->remove(m_syslog); delete m_syslog; if (m_stop != NULL) { @@ -128,37 +164,44 @@ SystemLogger::~SystemLogger() { // BufferedLogOutputter // -BufferedLogOutputter::BufferedLogOutputter(UInt32 maxBufferSize) - : m_maxBufferSize(maxBufferSize) { +BufferedLogOutputter::BufferedLogOutputter(UInt32 maxBufferSize) : m_maxBufferSize(maxBufferSize) +{ // do nothing } -BufferedLogOutputter::~BufferedLogOutputter() { +BufferedLogOutputter::~BufferedLogOutputter() +{ // do nothing } -BufferedLogOutputter::const_iterator BufferedLogOutputter::begin() const { +BufferedLogOutputter::const_iterator BufferedLogOutputter::begin() const +{ return m_buffer.begin(); } -BufferedLogOutputter::const_iterator BufferedLogOutputter::end() const { +BufferedLogOutputter::const_iterator BufferedLogOutputter::end() const +{ return m_buffer.end(); } -void BufferedLogOutputter::open(const char *) { +void BufferedLogOutputter::open(const char *) +{ // do nothing } -void BufferedLogOutputter::close() { +void BufferedLogOutputter::close() +{ // remove all elements from the buffer m_buffer.clear(); } -void BufferedLogOutputter::show(bool) { +void BufferedLogOutputter::show(bool) +{ // do nothing } -bool BufferedLogOutputter::write(ELevel, const char *message) { +bool BufferedLogOutputter::write(ELevel, const char *message) +{ while (m_buffer.size() >= m_maxBufferSize) { m_buffer.pop_front(); } @@ -170,18 +213,23 @@ bool BufferedLogOutputter::write(ELevel, const char *message) { // FileLogOutputter // -FileLogOutputter::FileLogOutputter(const char *logFile) { +FileLogOutputter::FileLogOutputter(const char *logFile) +{ setLogFilename(logFile); } -FileLogOutputter::~FileLogOutputter() {} +FileLogOutputter::~FileLogOutputter() +{ +} -void FileLogOutputter::setLogFilename(const char *logFile) { +void FileLogOutputter::setLogFilename(const char *logFile) +{ assert(logFile != NULL); m_fileName = logFile; } -bool FileLogOutputter::write(ELevel level, const char *message) { +bool FileLogOutputter::write(ELevel level, const char *message) +{ bool moveFile = false; std::ofstream m_handle; @@ -198,8 +246,7 @@ bool FileLogOutputter::write(ELevel level, const char *message) { m_handle.close(); if (moveFile) { - String oldLogFilename = - deskflow::string::sprintf("%s.1", m_fileName.c_str()); + String oldLogFilename = deskflow::string::sprintf("%s.1", m_fileName.c_str()); remove(oldLogFilename.c_str()); rename(m_fileName.c_str(), oldLogFilename.c_str()); } @@ -207,8 +254,14 @@ bool FileLogOutputter::write(ELevel level, const char *message) { return true; } -void FileLogOutputter::open(const char *title) {} +void FileLogOutputter::open(const char *title) +{ +} -void FileLogOutputter::close() {} +void FileLogOutputter::close() +{ +} -void FileLogOutputter::show(bool showIfEmpty) {} +void FileLogOutputter::show(bool showIfEmpty) +{ +} diff --git a/src/lib/base/log_outputters.h b/src/lib/base/log_outputters.h index 79ffe69e2..24bb2ab81 100644 --- a/src/lib/base/log_outputters.h +++ b/src/lib/base/log_outputters.h @@ -33,7 +33,8 @@ This outputter performs no output and returns false from \c write(), causing the logger to stop traversing the outputter chain. Insert this to prevent already inserted outputters from writing. */ -class StopLogOutputter : public ILogOutputter { +class StopLogOutputter : public ILogOutputter +{ public: StopLogOutputter(); virtual ~StopLogOutputter(); @@ -50,7 +51,8 @@ public: This outputter writes output to the console. The level for each message is ignored. */ -class ConsoleLogOutputter : public ILogOutputter { +class ConsoleLogOutputter : public ILogOutputter +{ public: ConsoleLogOutputter(); virtual ~ConsoleLogOutputter(); @@ -69,7 +71,8 @@ This outputter writes output to the file. The level for each message is ignored. */ -class FileLogOutputter : public ILogOutputter { +class FileLogOutputter : public ILogOutputter +{ public: FileLogOutputter(const char *logFile); virtual ~FileLogOutputter(); @@ -90,7 +93,8 @@ private: /*! This outputter writes output to the system log. */ -class SystemLogOutputter : public ILogOutputter { +class SystemLogOutputter : public ILogOutputter +{ public: SystemLogOutputter(); virtual ~SystemLogOutputter(); @@ -110,7 +114,8 @@ outputters. Add one of these to any scope that needs to write to the system log (only) and restore the old outputters when exiting the scope. */ -class SystemLogger { +class SystemLogger +{ public: SystemLogger(const char *title, bool blockConsole); SystemLogger(SystemLogger const &) = delete; @@ -129,7 +134,8 @@ private: /*! This outputter records the last N log messages. */ -class BufferedLogOutputter : public ILogOutputter { +class BufferedLogOutputter : public ILogOutputter +{ private: typedef std::deque Buffer; diff --git a/src/lib/client/Client.cpp b/src/lib/client/Client.cpp index e1fa6f625..88568ff96 100644 --- a/src/lib/client/Client.cpp +++ b/src/lib/client/Client.cpp @@ -54,9 +54,9 @@ // Client::Client( - IEventQueue *events, const String &name, const NetworkAddress &address, - ISocketFactory *socketFactory, deskflow::Screen *screen, - deskflow::ClientArgs const &args) + IEventQueue *events, const String &name, const NetworkAddress &address, ISocketFactory *socketFactory, + deskflow::Screen *screen, deskflow::ClientArgs const &args +) : m_mock(false), m_name(name), m_serverAddress(address), @@ -75,29 +75,32 @@ Client::Client( m_useSecureNetwork(args.m_enableCrypto), m_args(args), m_enableClipboard(true), - m_maximumClipboardSize(INT_MAX) { + m_maximumClipboardSize(INT_MAX) +{ assert(m_socketFactory != NULL); assert(m_screen != NULL); // register suspend/resume event handlers m_events->adoptHandler( - m_events->forIScreen().suspend(), getEventTarget(), - new TMethodEventJob(this, &Client::handleSuspend)); + m_events->forIScreen().suspend(), getEventTarget(), new TMethodEventJob(this, &Client::handleSuspend) + ); m_events->adoptHandler( - m_events->forIScreen().resume(), getEventTarget(), - new TMethodEventJob(this, &Client::handleResume)); + m_events->forIScreen().resume(), getEventTarget(), new TMethodEventJob(this, &Client::handleResume) + ); if (m_args.m_enableDragDrop) { m_events->adoptHandler( - m_events->forFile().fileChunkSending(), this, - new TMethodEventJob(this, &Client::handleFileChunkSending)); + m_events->forFile().fileChunkSending(), this, new TMethodEventJob(this, &Client::handleFileChunkSending) + ); m_events->adoptHandler( m_events->forFile().fileRecieveCompleted(), this, - new TMethodEventJob(this, &Client::handleFileRecieveCompleted)); + new TMethodEventJob(this, &Client::handleFileRecieveCompleted) + ); } } -Client::~Client() { +Client::~Client() +{ if (m_mock) { return; } @@ -112,7 +115,8 @@ Client::~Client() { delete m_socketFactory; } -void Client::connect(size_t addressIndex) { +void Client::connect(size_t addressIndex) +{ if (m_stream != NULL) { return; } @@ -123,9 +127,7 @@ void Client::connect(size_t addressIndex) { try { if (m_args.m_hostMode) { - LOG( - (CLOG_NOTE "waiting for server connection on %i port", - m_serverAddress.getPort())); + LOG((CLOG_NOTE "waiting for server connection on %i port", m_serverAddress.getPort())); } else { // resolve the server hostname. do this every time we connect // in case we couldn't resolve the address earlier or the address @@ -138,16 +140,15 @@ void Client::connect(size_t addressIndex) { if (m_serverAddress.getAddress() != nullptr) { // to help users troubleshoot, show server host name (issue: 60) LOG( - (CLOG_NOTE "connecting to '%s': %s:%i", - m_serverAddress.getHostname().c_str(), - ARCH->addrToString(m_serverAddress.getAddress()).c_str(), - m_serverAddress.getPort())); + (CLOG_NOTE "connecting to '%s': %s:%i", m_serverAddress.getHostname().c_str(), + ARCH->addrToString(m_serverAddress.getAddress()).c_str(), m_serverAddress.getPort()) + ); } } // create the socket - IDataSocket *socket = m_socketFactory->create( - m_useSecureNetwork, ARCH->getAddrFamily(m_serverAddress.getAddress())); + IDataSocket *socket = + m_socketFactory->create(m_useSecureNetwork, ARCH->getAddrFamily(m_serverAddress.getAddress())); bindNetworkInterface(socket); // filter socket messages, including a packetizing filter @@ -168,7 +169,8 @@ void Client::connect(size_t addressIndex) { } } -void Client::disconnect(const char *msg) { +void Client::disconnect(const char *msg) +{ cleanup(); if (msg) { @@ -178,47 +180,62 @@ void Client::disconnect(const char *msg) { } } -void Client::refuseConnection(const char *msg) { +void Client::refuseConnection(const char *msg) +{ cleanup(); if (msg) { auto info = new FailInfo(msg); info->m_retry = true; - Event event( - m_events->forClient().connectionRefused(), getEventTarget(), info, - Event::kDontFreeData); + Event event(m_events->forClient().connectionRefused(), getEventTarget(), info, Event::kDontFreeData); m_events->addEvent(event); } } -void Client::handshakeComplete() { +void Client::handshakeComplete() +{ m_ready = true; m_screen->enable(); sendEvent(m_events->forClient().connected(), NULL); } -bool Client::isConnected() const { return (m_server != NULL); } +bool Client::isConnected() const +{ + return (m_server != NULL); +} -bool Client::isConnecting() const { return (m_timer != NULL); } +bool Client::isConnecting() const +{ + return (m_timer != NULL); +} -NetworkAddress Client::getServerAddress() const { return m_serverAddress; } +NetworkAddress Client::getServerAddress() const +{ + return m_serverAddress; +} -void *Client::getEventTarget() const { return m_screen->getEventTarget(); } +void *Client::getEventTarget() const +{ + return m_screen->getEventTarget(); +} -bool Client::getClipboard(ClipboardID id, IClipboard *clipboard) const { +bool Client::getClipboard(ClipboardID id, IClipboard *clipboard) const +{ return m_screen->getClipboard(id, clipboard); } -void Client::getShape(SInt32 &x, SInt32 &y, SInt32 &w, SInt32 &h) const { +void Client::getShape(SInt32 &x, SInt32 &y, SInt32 &w, SInt32 &h) const +{ m_screen->getShape(x, y, w, h); } -void Client::getCursorPos(SInt32 &x, SInt32 &y) const { +void Client::getCursorPos(SInt32 &x, SInt32 &y) const +{ m_screen->getCursorPos(x, y); } -void Client::enter( - SInt32 xAbs, SInt32 yAbs, UInt32, KeyModifierMask mask, bool) { +void Client::enter(SInt32 xAbs, SInt32 yAbs, UInt32, KeyModifierMask mask, bool) +{ m_active = true; m_screen->mouseMove(xAbs, yAbs); m_screen->enter(mask); @@ -229,7 +246,8 @@ void Client::enter( } } -bool Client::leave() { +bool Client::leave() +{ m_active = false; m_screen->leave(); @@ -246,58 +264,78 @@ bool Client::leave() { return true; } -void Client::setClipboard(ClipboardID id, const IClipboard *clipboard) { +void Client::setClipboard(ClipboardID id, const IClipboard *clipboard) +{ m_screen->setClipboard(id, clipboard); m_ownClipboard[id] = false; m_sentClipboard[id] = false; } -void Client::grabClipboard(ClipboardID id) { +void Client::grabClipboard(ClipboardID id) +{ m_screen->grabClipboard(id); m_ownClipboard[id] = false; m_sentClipboard[id] = false; } -void Client::setClipboardDirty(ClipboardID, bool) { +void Client::setClipboardDirty(ClipboardID, bool) +{ assert(0 && "shouldn't be called"); } -void Client::keyDown( - KeyID id, KeyModifierMask mask, KeyButton button, const String &lang) { +void Client::keyDown(KeyID id, KeyModifierMask mask, KeyButton button, const String &lang) +{ m_screen->keyDown(id, mask, button, lang); } -void Client::keyRepeat( - KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, - const String &lang) { +void Client::keyRepeat(KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang) +{ m_screen->keyRepeat(id, mask, count, button, lang); } -void Client::keyUp(KeyID id, KeyModifierMask mask, KeyButton button) { +void Client::keyUp(KeyID id, KeyModifierMask mask, KeyButton button) +{ m_screen->keyUp(id, mask, button); } -void Client::mouseDown(ButtonID id) { m_screen->mouseDown(id); } +void Client::mouseDown(ButtonID id) +{ + m_screen->mouseDown(id); +} -void Client::mouseUp(ButtonID id) { m_screen->mouseUp(id); } +void Client::mouseUp(ButtonID id) +{ + m_screen->mouseUp(id); +} -void Client::mouseMove(SInt32 x, SInt32 y) { m_screen->mouseMove(x, y); } +void Client::mouseMove(SInt32 x, SInt32 y) +{ + m_screen->mouseMove(x, y); +} -void Client::mouseRelativeMove(SInt32 dx, SInt32 dy) { +void Client::mouseRelativeMove(SInt32 dx, SInt32 dy) +{ m_screen->mouseRelativeMove(dx, dy); } -void Client::mouseWheel(SInt32 xDelta, SInt32 yDelta) { +void Client::mouseWheel(SInt32 xDelta, SInt32 yDelta) +{ m_screen->mouseWheel(xDelta, yDelta); } -void Client::screensaver(bool activate) { m_screen->screensaver(activate); } +void Client::screensaver(bool activate) +{ + m_screen->screensaver(activate); +} -void Client::resetOptions() { m_screen->resetOptions(); } +void Client::resetOptions() +{ + m_screen->resetOptions(); +} -void Client::setOptions(const OptionsList &options) { - for (OptionsList::const_iterator index = options.begin(); - index != options.end(); ++index) { +void Client::setOptions(const OptionsList &options) +{ + for (OptionsList::const_iterator index = options.begin(); index != options.end(); ++index) { const OptionID id = *index; if (id == kOptionClipboardSharing) { index++; @@ -324,9 +362,13 @@ void Client::setOptions(const OptionsList &options) { m_screen->setOptions(options); } -String Client::getName() const { return m_name; } +String Client::getName() const +{ + return m_name; +} -void Client::sendClipboard(ClipboardID id) { +void Client::sendClipboard(ClipboardID id) +{ // note -- m_mutex must be locked on entry assert(m_screen != NULL); assert(m_server != NULL); @@ -349,7 +391,8 @@ void Client::sendClipboard(ClipboardID id) { LOG( (CLOG_NOTE "skipping clipboard transfer because the clipboard" " contents exceeds the %i MB size limit set by the server", - m_maximumClipboardSize / 1024)); + m_maximumClipboardSize / 1024) + ); return; } @@ -364,97 +407,110 @@ void Client::sendClipboard(ClipboardID id) { } } -void Client::sendEvent(Event::Type type, void *data) { +void Client::sendEvent(Event::Type type, void *data) +{ m_events->addEvent(Event(type, getEventTarget(), data)); } -void Client::sendConnectionFailedEvent(const char *msg) { +void Client::sendConnectionFailedEvent(const char *msg) +{ FailInfo *info = new FailInfo(msg); 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); } -void Client::sendFileChunk(const void *data) { +void Client::sendFileChunk(const void *data) +{ FileChunk *chunk = static_cast(const_cast(data)); LOG((CLOG_DEBUG1 "send file chunk")); assert(m_server != NULL); // relay - m_server->fileChunkSending( - chunk->m_chunk[0], &chunk->m_chunk[1], chunk->m_dataSize); + m_server->fileChunkSending(chunk->m_chunk[0], &chunk->m_chunk[1], chunk->m_dataSize); } -void Client::setupConnecting() { +void Client::setupConnecting() +{ assert(m_stream != NULL); if (m_args.m_enableCrypto) { m_events->adoptHandler( - m_events->forIDataSocket().secureConnected(), - m_stream->getEventTarget(), - new TMethodEventJob(this, &Client::handleConnected)); + m_events->forIDataSocket().secureConnected(), m_stream->getEventTarget(), + new TMethodEventJob(this, &Client::handleConnected) + ); } else { m_events->adoptHandler( m_events->forIDataSocket().connected(), m_stream->getEventTarget(), - new TMethodEventJob(this, &Client::handleConnected)); + new TMethodEventJob(this, &Client::handleConnected) + ); } m_events->adoptHandler( m_events->forIDataSocket().connectionFailed(), m_stream->getEventTarget(), - new TMethodEventJob(this, &Client::handleConnectionFailed)); + new TMethodEventJob(this, &Client::handleConnectionFailed) + ); } -void Client::setupConnection() { +void Client::setupConnection() +{ assert(m_stream != NULL); m_events->adoptHandler( m_events->forISocket().disconnected(), m_stream->getEventTarget(), - new TMethodEventJob(this, &Client::handleDisconnected)); + new TMethodEventJob(this, &Client::handleDisconnected) + ); m_events->adoptHandler( m_events->forIStream().inputReady(), m_stream->getEventTarget(), - new TMethodEventJob(this, &Client::handleHello)); + new TMethodEventJob(this, &Client::handleHello) + ); m_events->adoptHandler( m_events->forIStream().outputError(), m_stream->getEventTarget(), - new TMethodEventJob(this, &Client::handleOutputError)); + new TMethodEventJob(this, &Client::handleOutputError) + ); m_events->adoptHandler( m_events->forIStream().inputShutdown(), m_stream->getEventTarget(), - new TMethodEventJob(this, &Client::handleDisconnected)); + new TMethodEventJob(this, &Client::handleDisconnected) + ); m_events->adoptHandler( m_events->forIStream().outputShutdown(), m_stream->getEventTarget(), - new TMethodEventJob(this, &Client::handleDisconnected)); + new TMethodEventJob(this, &Client::handleDisconnected) + ); m_events->adoptHandler( m_events->forISocket().stopRetry(), m_stream->getEventTarget(), - new TMethodEventJob(this, &Client::handleStopRetry)); + new TMethodEventJob(this, &Client::handleStopRetry) + ); } -void Client::setupScreen() { +void Client::setupScreen() +{ assert(m_server == NULL); m_ready = false; m_server = new ServerProxy(this, m_stream, m_events); m_events->adoptHandler( m_events->forIScreen().shapeChanged(), getEventTarget(), - new TMethodEventJob(this, &Client::handleShapeChanged)); + new TMethodEventJob(this, &Client::handleShapeChanged) + ); m_events->adoptHandler( m_events->forClipboard().clipboardGrabbed(), getEventTarget(), - new TMethodEventJob(this, &Client::handleClipboardGrabbed)); + new TMethodEventJob(this, &Client::handleClipboardGrabbed) + ); } -void Client::setupTimer() { +void Client::setupTimer() +{ assert(m_timer == NULL); if (!m_args.m_hostMode) { m_timer = m_events->newOneShotTimer(2.0, NULL); - m_events->adoptHandler( - Event::kTimer, m_timer, - new TMethodEventJob(this, &Client::handleConnectTimeout)); + m_events->adoptHandler(Event::kTimer, m_timer, new TMethodEventJob(this, &Client::handleConnectTimeout)); } } -void Client::cleanup() { +void Client::cleanup() +{ m_connectOnResume = false; cleanupTimer(); cleanupScreen(); @@ -462,50 +518,43 @@ void Client::cleanup() { cleanupConnection(); } -void Client::cleanupConnecting() { +void Client::cleanupConnecting() +{ if (m_stream != NULL) { - m_events->removeHandler( - m_events->forIDataSocket().connected(), m_stream->getEventTarget()); - m_events->removeHandler( - m_events->forIDataSocket().connectionFailed(), - m_stream->getEventTarget()); + m_events->removeHandler(m_events->forIDataSocket().connected(), m_stream->getEventTarget()); + m_events->removeHandler(m_events->forIDataSocket().connectionFailed(), m_stream->getEventTarget()); } } -void Client::cleanupConnection() { +void Client::cleanupConnection() +{ if (m_stream != NULL) { - m_events->removeHandler( - m_events->forIStream().inputReady(), m_stream->getEventTarget()); - m_events->removeHandler( - m_events->forIStream().outputError(), m_stream->getEventTarget()); - m_events->removeHandler( - m_events->forIStream().inputShutdown(), m_stream->getEventTarget()); - m_events->removeHandler( - m_events->forIStream().outputShutdown(), m_stream->getEventTarget()); - m_events->removeHandler( - m_events->forISocket().disconnected(), m_stream->getEventTarget()); - m_events->removeHandler( - m_events->forISocket().stopRetry(), m_stream->getEventTarget()); + m_events->removeHandler(m_events->forIStream().inputReady(), m_stream->getEventTarget()); + m_events->removeHandler(m_events->forIStream().outputError(), m_stream->getEventTarget()); + m_events->removeHandler(m_events->forIStream().inputShutdown(), m_stream->getEventTarget()); + m_events->removeHandler(m_events->forIStream().outputShutdown(), m_stream->getEventTarget()); + m_events->removeHandler(m_events->forISocket().disconnected(), m_stream->getEventTarget()); + m_events->removeHandler(m_events->forISocket().stopRetry(), m_stream->getEventTarget()); cleanupStream(); } } -void Client::cleanupScreen() { +void Client::cleanupScreen() +{ if (m_server != NULL) { if (m_ready) { m_screen->disable(); m_ready = false; } - m_events->removeHandler( - m_events->forIScreen().shapeChanged(), getEventTarget()); - m_events->removeHandler( - m_events->forClipboard().clipboardGrabbed(), getEventTarget()); + m_events->removeHandler(m_events->forIScreen().shapeChanged(), getEventTarget()); + m_events->removeHandler(m_events->forClipboard().clipboardGrabbed(), getEventTarget()); delete m_server; m_server = NULL; } } -void Client::cleanupTimer() { +void Client::cleanupTimer() +{ if (m_timer != NULL) { m_events->removeHandler(Event::kTimer, m_timer); m_events->deleteTimer(m_timer); @@ -513,12 +562,14 @@ void Client::cleanupTimer() { } } -void Client::cleanupStream() { +void Client::cleanupStream() +{ delete m_stream; m_stream = NULL; } -void Client::handleConnected(const Event &, void *) { +void Client::handleConnected(const Event &, void *) +{ LOG((CLOG_DEBUG1 "connected; wait for hello")); cleanupConnecting(); setupConnection(); @@ -531,9 +582,9 @@ void Client::handleConnected(const Event &, void *) { } } -void Client::handleConnectionFailed(const Event &event, void *) { - IDataSocket::ConnectionFailedInfo *info = - static_cast(event.getData()); +void Client::handleConnectionFailed(const Event &event, void *) +{ + IDataSocket::ConnectionFailedInfo *info = static_cast(event.getData()); cleanupTimer(); cleanupConnecting(); @@ -543,7 +594,8 @@ void Client::handleConnectionFailed(const Event &event, void *) { delete info; } -void Client::handleConnectTimeout(const Event &, void *) { +void Client::handleConnectTimeout(const Event &, void *) +{ cleanupTimer(); cleanupConnecting(); cleanupConnection(); @@ -552,7 +604,8 @@ void Client::handleConnectTimeout(const Event &, void *) { sendConnectionFailedEvent("Timed out"); } -void Client::handleOutputError(const Event &, void *) { +void Client::handleOutputError(const Event &, void *) +{ cleanupTimer(); cleanupScreen(); cleanupConnection(); @@ -560,7 +613,8 @@ void Client::handleOutputError(const Event &, void *) { sendEvent(m_events->forClient().disconnected(), NULL); } -void Client::handleDisconnected(const Event &, void *) { +void Client::handleDisconnected(const Event &, void *) +{ cleanupTimer(); cleanupScreen(); cleanupConnection(); @@ -568,18 +622,19 @@ void Client::handleDisconnected(const Event &, void *) { sendEvent(m_events->forClient().disconnected(), NULL); } -void Client::handleShapeChanged(const Event &, void *) { +void Client::handleShapeChanged(const Event &, void *) +{ LOG((CLOG_DEBUG "resolution changed")); m_server->onInfoChanged(); } -void Client::handleClipboardGrabbed(const Event &event, void *) { +void Client::handleClipboardGrabbed(const Event &event, void *) +{ if (!m_enableClipboard || (m_maximumClipboardSize == 0)) { return; } - const IScreen::ClipboardInfo *info = - static_cast(event.getData()); + const IScreen::ClipboardInfo *info = static_cast(event.getData()); // grab ownership m_server->onGrabClipboard(info->m_id); @@ -596,7 +651,8 @@ void Client::handleClipboardGrabbed(const Event &event, void *) { } } -bool Client::isCompatible(int major, int minor) const { +bool Client::isCompatible(int major, int minor) const +{ const std::map> compatibleTable{ {6, {7, 8}}, // 1.6 is compatible with 1.7 and 1.8 {7, {8}} // 1.7 is compatible with 1.8 @@ -608,19 +664,18 @@ bool Client::isCompatible(int major, int minor) const { auto versions = compatibleTable.find(minor); if (versions != compatibleTable.end()) { auto compatibleVersions = versions->second; - isCompatible = compatibleVersions.find(kProtocolMinorVersion) != - compatibleVersions.end(); + isCompatible = compatibleVersions.find(kProtocolMinorVersion) != compatibleVersions.end(); } } return isCompatible; } -void Client::handleHello(const Event &, void *) { +void Client::handleHello(const Event &, void *) +{ SInt16 major, minor; if (!ProtocolUtil::readf(m_stream, kMsgHello, &major, &minor)) { - sendConnectionFailedEvent( - "Protocol error from server, check encryption settings"); + sendConnectionFailedEvent("Protocol error from server, check encryption settings"); cleanupTimer(); cleanupConnection(); return; @@ -636,9 +691,7 @@ void Client::handleHello(const Event &, void *) { // server LOG((CLOG_NOTE "downgrading protocol version for server")); helloBackMinor = minor; - } else if ( - major < kProtocolMajorVersion || - (major == kProtocolMajorVersion && minor < kProtocolMinorVersion)) { + } else if (major < kProtocolMajorVersion || (major == kProtocolMajorVersion && minor < kProtocolMinorVersion)) { sendConnectionFailedEvent(XIncompatibleClient(major, minor).what()); cleanupTimer(); cleanupConnection(); @@ -647,8 +700,7 @@ void Client::handleHello(const Event &, void *) { // say hello back LOG((CLOG_DEBUG1 "say hello version %d.%d", helloBackMajor, helloBackMinor)); - ProtocolUtil::writef( - m_stream, kMsgHelloBack, helloBackMajor, helloBackMinor, &m_name); + ProtocolUtil::writef(m_stream, kMsgHelloBack, helloBackMajor, helloBackMinor, &m_name); // now connected but waiting to complete handshake setupScreen(); @@ -658,12 +710,12 @@ void Client::handleHello(const Event &, void *) { // receive another event for already pending messages so we fake // one. if (m_stream->isReady()) { - m_events->addEvent( - Event(m_events->forIStream().inputReady(), m_stream->getEventTarget())); + m_events->addEvent(Event(m_events->forIStream().inputReady(), m_stream->getEventTarget())); } } -void Client::handleSuspend(const Event &, void *) { +void Client::handleSuspend(const Event &, void *) +{ if (!m_suspended) { LOG((CLOG_INFO "suspend")); m_suspended = true; @@ -673,7 +725,8 @@ void Client::handleSuspend(const Event &, void *) { } } -void Client::handleResume(const Event &, void *) { +void Client::handleResume(const Event &, void *) +{ if (m_suspended) { LOG((CLOG_INFO "resume")); m_suspended = false; @@ -684,27 +737,29 @@ void Client::handleResume(const Event &, void *) { } } -void Client::handleFileChunkSending(const Event &event, void *) { +void Client::handleFileChunkSending(const Event &event, void *) +{ sendFileChunk(event.getDataObject()); } -void Client::handleFileRecieveCompleted(const Event &event, void *) { +void Client::handleFileRecieveCompleted(const Event &event, void *) +{ onFileRecieveCompleted(); } -void Client::onFileRecieveCompleted() { +void Client::onFileRecieveCompleted() +{ if (isReceivedFileSizeValid()) { auto method = new TMethodJob(this, &Client::writeToDropDirThread); m_writeToDropDirThread.reset(new Thread(method)); } } -void Client::bindNetworkInterface(IDataSocket *socket) const { +void Client::bindNetworkInterface(IDataSocket *socket) const +{ try { if (!m_args.m_deskflowAddress.empty()) { - LOG( - (CLOG_DEBUG1 "bind to network interface: %s", - m_args.m_deskflowAddress.c_str())); + LOG((CLOG_DEBUG1 "bind to network interface: %s", m_args.m_deskflowAddress.c_str())); NetworkAddress bindAddress(m_args.m_deskflowAddress); bindAddress.resolve(); @@ -713,27 +768,28 @@ void Client::bindNetworkInterface(IDataSocket *socket) const { } } catch (XBase &e) { LOG((CLOG_WARN "%s", e.what())); - LOG((CLOG_WARN - "operating system will select network interface automatically")); + LOG((CLOG_WARN "operating system will select network interface automatically")); } } -void Client::handleStopRetry(const Event &, void *) { +void Client::handleStopRetry(const Event &, void *) +{ m_args.m_restartable = false; } -void Client::writeToDropDirThread(void *) { +void Client::writeToDropDirThread(void *) +{ LOG((CLOG_DEBUG "starting write to drop dir thread")); while (m_screen->isFakeDraggingStarted()) { ARCH->sleep(.1f); } - DropHelper::writeToDir( - m_screen->getDropTarget(), m_dragFileList, m_receivedFileData); + DropHelper::writeToDir(m_screen->getDropTarget(), m_dragFileList, m_receivedFileData); } -void Client::dragInfoReceived(UInt32 fileNum, String data) { +void Client::dragInfoReceived(UInt32 fileNum, String data) +{ // TODO: fix duplicate function from CServer if (!m_args.m_enableDragDrop) { LOG((CLOG_DEBUG "drag drop not enabled, ignoring drag info.")); @@ -745,11 +801,13 @@ void Client::dragInfoReceived(UInt32 fileNum, String data) { m_screen->startDraggingFiles(m_dragFileList); } -bool Client::isReceivedFileSizeValid() { +bool Client::isReceivedFileSizeValid() +{ return m_expectedFileSize == m_receivedFileData.size(); } -void Client::sendFileToServer(const char *filename) { +void Client::sendFileToServer(const char *filename) +{ if (m_sendFileThread) { StreamChunker::interruptFile(); } @@ -759,7 +817,8 @@ void Client::sendFileToServer(const char *filename) { m_sendFileThread.reset(new Thread(method)); } -void Client::sendFileThread(void *filename) { +void Client::sendFileThread(void *filename) +{ try { char *name = static_cast(filename); StreamChunker::sendFile(name, m_events, this); @@ -770,6 +829,7 @@ void Client::sendFileThread(void *filename) { m_sendFileThread.reset(nullptr); } -void Client::sendDragInfo(UInt32 fileCount, String &info, size_t size) { +void Client::sendDragInfo(UInt32 fileCount, String &info, size_t size) +{ m_server->sendDragInfo(fileCount, info.c_str(), size); } diff --git a/src/lib/client/Client.h b/src/lib/client/Client.h index 1c0b13e71..7460b0bb1 100644 --- a/src/lib/client/Client.h +++ b/src/lib/client/Client.h @@ -47,11 +47,15 @@ class TCPSocket; /*! This class implements the top-level client algorithms for deskflow. */ -class Client : public IClient, public INode { +class Client : public IClient, public INode +{ public: - class FailInfo { + class FailInfo + { public: - FailInfo(const char *what) : m_retry(false), m_what(what) {} + FailInfo(const char *what) : m_retry(false), m_what(what) + { + } bool m_retry; String m_what; }; @@ -63,9 +67,9 @@ public: to create the socket. \p screen is the local screen. */ Client( - IEventQueue *events, const String &name, const NetworkAddress &address, - ISocketFactory *socketFactory, deskflow::Screen *screen, - deskflow::ClientArgs const &args); + IEventQueue *events, const String &name, const NetworkAddress &address, ISocketFactory *socketFactory, + deskflow::Screen *screen, deskflow::ClientArgs const &args + ); Client(Client const &) = delete; Client(Client &&) = delete; ~Client(); @@ -139,16 +143,26 @@ public: bool isReceivedFileSizeValid(); //! Return expected file size - size_t &getExpectedFileSize() { return m_expectedFileSize; } + size_t &getExpectedFileSize() + { + return m_expectedFileSize; + } //! Return received file data - String &getReceivedFileData() { return m_receivedFileData; } + String &getReceivedFileData() + { + return m_receivedFileData; + } //! Return drag file list - DragFileList getDragFileList() { return m_dragFileList; } + DragFileList getDragFileList() + { + return m_dragFileList; + } //! Return last resolved adresses count - size_t getLastResolvedAddressesCount() const { + size_t getLastResolvedAddressesCount() const + { return m_resolvedAddressesCount; } @@ -157,21 +171,17 @@ public: // IScreen overrides virtual void *getEventTarget() const; virtual bool getClipboard(ClipboardID id, IClipboard *) const; - virtual void - getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const; + virtual void getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const; virtual void getCursorPos(SInt32 &x, SInt32 &y) const; // IClient overrides - virtual void enter( - SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, - bool forScreensaver); + virtual void enter(SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, bool forScreensaver); virtual bool leave(); virtual void setClipboard(ClipboardID, const IClipboard *); virtual void grabClipboard(ClipboardID); virtual void setClipboardDirty(ClipboardID, bool); virtual void keyDown(KeyID, KeyModifierMask, KeyButton, const String &); - virtual void keyRepeat( - KeyID, KeyModifierMask, SInt32 count, KeyButton, const String &lang); + virtual void keyRepeat(KeyID, KeyModifierMask, SInt32 count, KeyButton, const String &lang); virtual void keyUp(KeyID, KeyModifierMask, KeyButton); virtual void mouseDown(ButtonID); virtual void mouseUp(ButtonID); diff --git a/src/lib/client/ServerProxy.cpp b/src/lib/client/ServerProxy.cpp index 2ffb8d999..5b34f54b5 100644 --- a/src/lib/client/ServerProxy.cpp +++ b/src/lib/client/ServerProxy.cpp @@ -41,8 +41,7 @@ // ServerProxy // -ServerProxy::ServerProxy( - Client *client, deskflow::IStream *stream, IEventQueue *events) +ServerProxy::ServerProxy(Client *client, deskflow::IStream *stream, IEventQueue *events) : m_client(client), m_stream(stream), m_seqNum(0), @@ -56,7 +55,8 @@ ServerProxy::ServerProxy( m_keepAliveAlarm(0.0), m_keepAliveAlarmTimer(NULL), m_parser(&ServerProxy::parseHandshakeMessage), - m_events(events) { + m_events(events) +{ assert(m_client != NULL); assert(m_stream != NULL); @@ -67,24 +67,26 @@ ServerProxy::ServerProxy( // handle data on stream m_events->adoptHandler( m_events->forIStream().inputReady(), m_stream->getEventTarget(), - new TMethodEventJob(this, &ServerProxy::handleData)); + new TMethodEventJob(this, &ServerProxy::handleData) + ); m_events->adoptHandler( m_events->forClipboard().clipboardSending(), this, - new TMethodEventJob( - this, &ServerProxy::handleClipboardSendingEvent)); + new TMethodEventJob(this, &ServerProxy::handleClipboardSendingEvent) + ); // send heartbeat setKeepAliveRate(kKeepAliveRate); } -ServerProxy::~ServerProxy() { +ServerProxy::~ServerProxy() +{ setKeepAliveRate(-1.0); - m_events->removeHandler( - m_events->forIStream().inputReady(), m_stream->getEventTarget()); + m_events->removeHandler(m_events->forIStream().inputReady(), m_stream->getEventTarget()); } -void ServerProxy::resetKeepAliveAlarm() { +void ServerProxy::resetKeepAliveAlarm() +{ if (m_keepAliveAlarmTimer != NULL) { m_events->removeHandler(Event::kTimer, m_keepAliveAlarmTimer); m_events->deleteTimer(m_keepAliveAlarmTimer); @@ -93,18 +95,19 @@ void ServerProxy::resetKeepAliveAlarm() { if (m_keepAliveAlarm > 0.0) { m_keepAliveAlarmTimer = m_events->newOneShotTimer(m_keepAliveAlarm, NULL); m_events->adoptHandler( - Event::kTimer, m_keepAliveAlarmTimer, - new TMethodEventJob( - this, &ServerProxy::handleKeepAliveAlarm)); + Event::kTimer, m_keepAliveAlarmTimer, new TMethodEventJob(this, &ServerProxy::handleKeepAliveAlarm) + ); } } -void ServerProxy::setKeepAliveRate(double rate) { +void ServerProxy::setKeepAliveRate(double rate) +{ m_keepAliveAlarm = rate * kKeepAlivesUntilDeath; resetKeepAliveAlarm(); } -void ServerProxy::handleData(const Event &, void *) { +void ServerProxy::handleData(const Event &, void *) +{ // handle messages until there are no more. first read message code. UInt8 code[4]; UInt32 n = m_stream->read(code, 4); @@ -117,17 +120,13 @@ void ServerProxy::handleData(const Event &, void *) { } // parse message - LOG( - (CLOG_DEBUG2 "msg from server: %c%c%c%c", code[0], code[1], code[2], - code[3])); + LOG((CLOG_DEBUG2 "msg from server: %c%c%c%c", code[0], code[1], code[2], code[3])); switch ((this->*m_parser)(code)) { case kOkay: break; case kUnknown: - LOG( - (CLOG_ERR "invalid message from server: %c%c%c%c", code[0], code[1], - code[2], code[3])); + LOG((CLOG_ERR "invalid message from server: %c%c%c%c", code[0], code[1], code[2], code[3])); // not possible to determine message boundaries // read the whole stream to discard unkonwn data while (m_stream->read(nullptr, 4)) @@ -145,7 +144,8 @@ void ServerProxy::handleData(const Event &, void *) { flushCompressedMouse(); } -ServerProxy::EResult ServerProxy::parseHandshakeMessage(const UInt8 *code) { +ServerProxy::EResult ServerProxy::parseHandshakeMessage(const UInt8 *code) +{ if (memcmp(code, kMsgQInfo, 4) == 0) { queryInfo(); } @@ -193,18 +193,13 @@ ServerProxy::EResult ServerProxy::parseHandshakeMessage(const UInt8 *code) { } else if (memcmp(code, kMsgEBusy, 4) == 0) { - LOG( - (CLOG_ERR "server already has a connected client with name \"%s\"", - m_client->getName().c_str())); - m_client->refuseConnection( - "server already has a connected client with our name"); + LOG((CLOG_ERR "server already has a connected client with name \"%s\"", m_client->getName().c_str())); + m_client->refuseConnection("server already has a connected client with our name"); return kDisconnect; } else if (memcmp(code, kMsgEUnknown, 4) == 0) { - LOG( - (CLOG_ERR "server refused client with name \"%s\"", - m_client->getName().c_str())); + LOG((CLOG_ERR "server refused client with name \"%s\"", m_client->getName().c_str())); m_client->refuseConnection("server refused client with our name"); return kDisconnect; } @@ -222,7 +217,8 @@ ServerProxy::EResult ServerProxy::parseHandshakeMessage(const UInt8 *code) { return kOkay; } -ServerProxy::EResult ServerProxy::parseMessage(const UInt8 *code) { +ServerProxy::EResult ServerProxy::parseMessage(const UInt8 *code) +{ if (memcmp(code, kMsgDMouseMove, 4) == 0) { mouseMove(); } @@ -240,9 +236,7 @@ ServerProxy::EResult ServerProxy::parseMessage(const UInt8 *code) { UInt16 mask = 0; UInt16 button = 0; ProtocolUtil::readf(m_stream, kMsgDKeyDown + 4, &id, &mask, &button); - LOG( - (CLOG_DEBUG1 "recv key down id=0x%08x, mask=0x%04x, button=0x%04x", id, - mask, button)); + LOG((CLOG_DEBUG1 "recv key down id=0x%08x, mask=0x%04x, button=0x%04x", id, mask, button)); keyDown(id, mask, button, ""); } @@ -253,12 +247,9 @@ ServerProxy::EResult ServerProxy::parseMessage(const UInt8 *code) { UInt16 mask = 0; UInt16 button = 0; - ProtocolUtil::readf( - m_stream, kMsgDKeyDownLang + 4, &id, &mask, &button, &lang); - LOG( - (CLOG_DEBUG1 - "recv key down id=0x%08x, mask=0x%04x, button=0x%04x, lang=\"%s\"", - id, mask, button, lang.c_str())); + ProtocolUtil::readf(m_stream, kMsgDKeyDownLang + 4, &id, &mask, &button, &lang); + LOG((CLOG_DEBUG1 "recv key down id=0x%08x, mask=0x%04x, button=0x%04x, lang=\"%s\"", id, mask, button, lang.c_str()) + ); keyDown(id, mask, button, lang); } @@ -358,12 +349,14 @@ ServerProxy::EResult ServerProxy::parseMessage(const UInt8 *code) { return kOkay; } -void ServerProxy::handleKeepAliveAlarm(const Event &, void *) { +void ServerProxy::handleKeepAliveAlarm(const Event &, void *) +{ LOG((CLOG_NOTE "server is dead")); m_client->disconnect("server is not responding"); } -void ServerProxy::onInfoChanged() { +void ServerProxy::onInfoChanged() +{ // ignore mouse motion until we receive acknowledgment of our info // change message. m_ignoreMouse = true; @@ -372,21 +365,23 @@ void ServerProxy::onInfoChanged() { queryInfo(); } -bool ServerProxy::onGrabClipboard(ClipboardID id) { +bool ServerProxy::onGrabClipboard(ClipboardID id) +{ LOG((CLOG_DEBUG1 "sending clipboard %d changed", id)); ProtocolUtil::writef(m_stream, kMsgCClipboard, id, m_seqNum); return true; } -void ServerProxy::onClipboardChanged( - ClipboardID id, const IClipboard *clipboard) { +void ServerProxy::onClipboardChanged(ClipboardID id, const IClipboard *clipboard) +{ String data = IClipboard::marshall(clipboard); LOG((CLOG_DEBUG "sending clipboard %d seqnum=%d", id, m_seqNum)); StreamChunker::sendClipboard(data, data.size(), id, m_seqNum, m_events, this); } -void ServerProxy::flushCompressedMouse() { +void ServerProxy::flushCompressedMouse() +{ if (m_compressMouse) { m_compressMouse = false; m_client->mouseMove(m_xMouse, m_yMouse); @@ -399,21 +394,18 @@ void ServerProxy::flushCompressedMouse() { } } -void ServerProxy::sendInfo(const ClientInfo &info) { - LOG( - (CLOG_DEBUG1 "sending info shape=%d,%d %dx%d", info.m_x, info.m_y, - info.m_w, info.m_h)); - ProtocolUtil::writef( - m_stream, kMsgDInfo, info.m_x, info.m_y, info.m_w, info.m_h, 0, info.m_mx, - info.m_my); +void ServerProxy::sendInfo(const ClientInfo &info) +{ + LOG((CLOG_DEBUG1 "sending info shape=%d,%d %dx%d", info.m_x, info.m_y, info.m_w, info.m_h)); + ProtocolUtil::writef(m_stream, kMsgDInfo, info.m_x, info.m_y, info.m_w, info.m_h, 0, info.m_mx, info.m_my); } -KeyID ServerProxy::translateKey(KeyID id) const { +KeyID ServerProxy::translateKey(KeyID id) const +{ static const KeyID s_translationTable[kKeyModifierIDLast][2] = { - {kKeyNone, kKeyNone}, {kKeyShift_L, kKeyShift_R}, - {kKeyControl_L, kKeyControl_R}, {kKeyAlt_L, kKeyAlt_R}, - {kKeyMeta_L, kKeyMeta_R}, {kKeySuper_L, kKeySuper_R}, - {kKeyAltGr, kKeyAltGr}}; + {kKeyNone, kKeyNone}, {kKeyShift_L, kKeyShift_R}, {kKeyControl_L, kKeyControl_R}, {kKeyAlt_L, kKeyAlt_R}, + {kKeyMeta_L, kKeyMeta_R}, {kKeySuper_L, kKeySuper_R}, {kKeyAltGr, kKeyAltGr} + }; KeyModifierID id2 = kKeyModifierIDNull; UInt32 side = 0; @@ -481,14 +473,14 @@ KeyID ServerProxy::translateKey(KeyID id) const { } } -KeyModifierMask ServerProxy::translateModifierMask(KeyModifierMask mask) const { - static const KeyModifierMask s_masks[kKeyModifierIDLast] = { - 0x0000, KeyModifierShift, KeyModifierControl, KeyModifierAlt, - KeyModifierMeta, KeyModifierSuper, KeyModifierAltGr}; +KeyModifierMask ServerProxy::translateModifierMask(KeyModifierMask mask) const +{ + static const KeyModifierMask s_masks[kKeyModifierIDLast] = {0x0000, KeyModifierShift, KeyModifierControl, + KeyModifierAlt, KeyModifierMeta, KeyModifierSuper, + KeyModifierAltGr}; - KeyModifierMask newMask = - mask & ~(KeyModifierShift | KeyModifierControl | KeyModifierAlt | - KeyModifierMeta | KeyModifierSuper | KeyModifierAltGr); + KeyModifierMask newMask = mask & ~(KeyModifierShift | KeyModifierControl | KeyModifierAlt | KeyModifierMeta | + KeyModifierSuper | KeyModifierAltGr); if ((mask & KeyModifierShift) != 0) { newMask |= s_masks[m_modifierTranslationTable[kKeyModifierIDShift]]; } @@ -510,7 +502,8 @@ KeyModifierMask ServerProxy::translateModifierMask(KeyModifierMask mask) const { return newMask; } -void ServerProxy::enter() { +void ServerProxy::enter() +{ // parse SInt16 x, y; UInt16 mask; @@ -531,7 +524,8 @@ void ServerProxy::enter() { m_client->enter(x, y, seqNum, static_cast(mask), false); } -void ServerProxy::leave() { +void ServerProxy::leave() +{ // parse LOG((CLOG_DEBUG1 "recv leave")); @@ -542,7 +536,8 @@ void ServerProxy::leave() { m_client->leave(); } -void ServerProxy::setClipboard() { +void ServerProxy::setClipboard() +{ // parse static String dataCached; ClipboardID id; @@ -565,7 +560,8 @@ void ServerProxy::setClipboard() { } } -void ServerProxy::grabClipboard() { +void ServerProxy::grabClipboard() +{ // parse ClipboardID id; UInt32 seqNum; @@ -581,79 +577,69 @@ void ServerProxy::grabClipboard() { m_client->grabClipboard(id); } -void ServerProxy::keyDown( - UInt16 id, UInt16 mask, UInt16 button, const String &lang) { +void ServerProxy::keyDown(UInt16 id, UInt16 mask, UInt16 button, const String &lang) +{ // get mouse up to date flushCompressedMouse(); setActiveServerLanguage(lang); // translate KeyID id2 = translateKey(static_cast(id)); - KeyModifierMask mask2 = - translateModifierMask(static_cast(mask)); - if (id2 != static_cast(id) || - mask2 != static_cast(mask)) - LOG( - (CLOG_DEBUG1 "key down translated to id=0x%08x, mask=0x%04x", id2, - mask2)); + KeyModifierMask mask2 = translateModifierMask(static_cast(mask)); + if (id2 != static_cast(id) || mask2 != static_cast(mask)) + LOG((CLOG_DEBUG1 "key down translated to id=0x%08x, mask=0x%04x", id2, mask2)); // forward m_client->keyDown(id2, mask2, button, lang); } -void ServerProxy::keyRepeat() { +void ServerProxy::keyRepeat() +{ // get mouse up to date flushCompressedMouse(); // parse UInt16 id, mask, count, button; String lang; - ProtocolUtil::readf( - m_stream, kMsgDKeyRepeat + 4, &id, &mask, &count, &button, &lang); + ProtocolUtil::readf(m_stream, kMsgDKeyRepeat + 4, &id, &mask, &count, &button, &lang); LOG( (CLOG_DEBUG1 "recv key repeat id=0x%08x, mask=0x%04x, count=%d, " "button=0x%04x, lang=\"%s\"", - id, mask, count, button, lang.c_str())); + id, mask, count, button, lang.c_str()) + ); // translate KeyID id2 = translateKey(static_cast(id)); - KeyModifierMask mask2 = - translateModifierMask(static_cast(mask)); - if (id2 != static_cast(id) || - mask2 != static_cast(mask)) - LOG( - (CLOG_DEBUG1 "key repeat translated to id=0x%08x, mask=0x%04x", id2, - mask2)); + KeyModifierMask mask2 = translateModifierMask(static_cast(mask)); + if (id2 != static_cast(id) || mask2 != static_cast(mask)) + LOG((CLOG_DEBUG1 "key repeat translated to id=0x%08x, mask=0x%04x", id2, mask2)); // forward m_client->keyRepeat(id2, mask2, count, button, lang); } -void ServerProxy::keyUp() { +void ServerProxy::keyUp() +{ // get mouse up to date flushCompressedMouse(); // parse UInt16 id, mask, button; ProtocolUtil::readf(m_stream, kMsgDKeyUp + 4, &id, &mask, &button); - LOG( - (CLOG_DEBUG1 "recv key up id=0x%08x, mask=0x%04x, button=0x%04x", id, - mask, button)); + LOG((CLOG_DEBUG1 "recv key up id=0x%08x, mask=0x%04x, button=0x%04x", id, mask, button)); // translate KeyID id2 = translateKey(static_cast(id)); - KeyModifierMask mask2 = - translateModifierMask(static_cast(mask)); - if (id2 != static_cast(id) || - mask2 != static_cast(mask)) - LOG(( - CLOG_DEBUG1 "key up translated to id=0x%08x, mask=0x%04x", id2, mask2)); + KeyModifierMask mask2 = translateModifierMask(static_cast(mask)); + if (id2 != static_cast(id) || mask2 != static_cast(mask)) + LOG((CLOG_DEBUG1 "key up translated to id=0x%08x, mask=0x%04x", id2, mask2)); // forward m_client->keyUp(id2, mask2, button); } -void ServerProxy::mouseDown() { +void ServerProxy::mouseDown() +{ // get mouse up to date flushCompressedMouse(); @@ -666,7 +652,8 @@ void ServerProxy::mouseDown() { m_client->mouseDown(static_cast(id)); } -void ServerProxy::mouseUp() { +void ServerProxy::mouseUp() +{ // get mouse up to date flushCompressedMouse(); @@ -679,7 +666,8 @@ void ServerProxy::mouseUp() { m_client->mouseUp(static_cast(id)); } -void ServerProxy::mouseMove() { +void ServerProxy::mouseMove() +{ // parse bool ignore; SInt16 x, y; @@ -710,7 +698,8 @@ void ServerProxy::mouseMove() { } } -void ServerProxy::mouseRelativeMove() { +void ServerProxy::mouseRelativeMove() +{ // parse bool ignore; SInt16 dx, dy; @@ -738,7 +727,8 @@ void ServerProxy::mouseRelativeMove() { } } -void ServerProxy::mouseWheel() { +void ServerProxy::mouseWheel() +{ // get mouse up to date flushCompressedMouse(); @@ -751,7 +741,8 @@ void ServerProxy::mouseWheel() { m_client->mouseWheel(xDelta, yDelta); } -void ServerProxy::screensaver() { +void ServerProxy::screensaver() +{ // parse SInt8 on; ProtocolUtil::readf(m_stream, kMsgCScreenSaver + 4, &on); @@ -761,7 +752,8 @@ void ServerProxy::screensaver() { m_client->screensaver(on != 0); } -void ServerProxy::resetOptions() { +void ServerProxy::resetOptions() +{ // parse LOG((CLOG_DEBUG1 "recv reset options")); @@ -777,7 +769,8 @@ void ServerProxy::resetOptions() { } } -void ServerProxy::setOptions() { +void ServerProxy::setOptions() +{ // parse OptionsList options; ProtocolUtil::readf(m_stream, kMsgDSetOptions + 4, &options); @@ -807,35 +800,32 @@ void ServerProxy::setOptions() { } if (id != kKeyModifierIDNull) { - m_modifierTranslationTable[id] = - static_cast(options[i + 1]); - LOG( - (CLOG_DEBUG1 "modifier %d mapped to %d", id, - m_modifierTranslationTable[id])); + m_modifierTranslationTable[id] = static_cast(options[i + 1]); + LOG((CLOG_DEBUG1 "modifier %d mapped to %d", id, m_modifierTranslationTable[id])); } } } -void ServerProxy::queryInfo() { +void ServerProxy::queryInfo() +{ ClientInfo info; m_client->getShape(info.m_x, info.m_y, info.m_w, info.m_h); m_client->getCursorPos(info.m_mx, info.m_my); sendInfo(info); } -void ServerProxy::infoAcknowledgment() { +void ServerProxy::infoAcknowledgment() +{ LOG((CLOG_DEBUG1 "recv info acknowledgment")); m_ignoreMouse = false; } -void ServerProxy::fileChunkReceived() { - int result = FileChunk::assemble( - m_stream, m_client->getReceivedFileData(), - m_client->getExpectedFileSize()); +void ServerProxy::fileChunkReceived() +{ + int result = FileChunk::assemble(m_stream, m_client->getReceivedFileData(), m_client->getExpectedFileSize()); if (result == kFinish) { - m_events->addEvent( - Event(m_events->forFile().fileRecieveCompleted(), m_client)); + m_events->addEvent(Event(m_events->forFile().fileRecieveCompleted(), m_client)); } else if (result == kStart) { if (m_client->getDragFileList().size() > 0) { String filename = m_client->getDragFileList().at(0).getFilename(); @@ -844,7 +834,8 @@ void ServerProxy::fileChunkReceived() { } } -void ServerProxy::dragInfoReceived() { +void ServerProxy::dragInfoReceived() +{ // parse UInt32 fileNum = 0; String content; @@ -853,21 +844,24 @@ void ServerProxy::dragInfoReceived() { m_client->dragInfoReceived(fileNum, content); } -void ServerProxy::handleClipboardSendingEvent(const Event &event, void *) { +void ServerProxy::handleClipboardSendingEvent(const Event &event, void *) +{ ClipboardChunk::send(m_stream, event.getDataObject()); } -void ServerProxy::fileChunkSending(UInt8 mark, char *data, size_t dataSize) { +void ServerProxy::fileChunkSending(UInt8 mark, char *data, size_t dataSize) +{ FileChunk::send(m_stream, mark, data, dataSize); } -void ServerProxy::sendDragInfo( - UInt32 fileCount, const char *info, size_t size) { +void ServerProxy::sendDragInfo(UInt32 fileCount, const char *info, size_t size) +{ String data(info, size); ProtocolUtil::writef(m_stream, kMsgDDragInfo, fileCount, &data); } -void ServerProxy::secureInputNotification() { +void ServerProxy::secureInputNotification() +{ String app; ProtocolUtil::readf(m_stream, kMsgDSecureInputNotification + 4, &app); @@ -877,23 +871,25 @@ void ServerProxy::secureInputNotification() { "The keyboard may stop working.", "'Secure input' enabled by " + app + " on the server. " "To fix the keyboard, " + - app + " must be closed."); + app + " must be closed." + ); } else { AppUtil::instance().showNotification( - "The keyboard may stop working.", - "'Secure input' enabled by an application on the server. " - "To fix the keyboard, the application must be closed."); + "The keyboard may stop working.", "'Secure input' enabled by an application on the server. " + "To fix the keyboard, the application must be closed." + ); } } -void ServerProxy::setServerLanguages() { +void ServerProxy::setServerLanguages() +{ String serverLanguages; - ProtocolUtil::readf( - m_stream, kMsgDLanguageSynchronisation + 4, &serverLanguages); + ProtocolUtil::readf(m_stream, kMsgDLanguageSynchronisation + 4, &serverLanguages); m_languageManager.setRemoteLanguages(serverLanguages); } -void ServerProxy::setActiveServerLanguage(const String &language) { +void ServerProxy::setActiveServerLanguage(const String &language) +{ if (!language.empty() && std::strlen(language.c_str()) > 0) { if (m_serverLanguage != language) { m_isUserNotifiedAboutLanguageSyncError = false; @@ -913,13 +909,14 @@ void ServerProxy::setActiveServerLanguage(const String &language) { } } -void ServerProxy::checkMissedLanguages() const { +void ServerProxy::checkMissedLanguages() const +{ auto missedLanguages = m_languageManager.getMissedLanguages(); if (!missedLanguages.empty()) { LOG( - (CLOG_WARN - "You need to install these languages on this computer and restart " - "Deskflow to enable support for multiple languages: %s", - missedLanguages.c_str())); + (CLOG_WARN "You need to install these languages on this computer and restart " + "Deskflow to enable support for multiple languages: %s", + missedLanguages.c_str()) + ); } } diff --git a/src/lib/client/ServerProxy.h b/src/lib/client/ServerProxy.h index 378f7d35b..743c3393f 100644 --- a/src/lib/client/ServerProxy.h +++ b/src/lib/client/ServerProxy.h @@ -39,7 +39,8 @@ class IEventQueue; This class acts a proxy for the server, converting calls into messages to the server and messages from the server to calls on the client. */ -class ServerProxy { +class ServerProxy +{ public: /*! Process messages from the server on \p stream and forward to @@ -69,11 +70,19 @@ public: void sendDragInfo(UInt32 fileCount, const char *info, size_t size); #ifdef TEST_ENV - void handleDataForTest() { handleData(Event(), NULL); } + void handleDataForTest() + { + handleData(Event(), NULL); + } #endif protected: - enum EResult { kOkay, kUnknown, kDisconnect }; + enum EResult + { + kOkay, + kUnknown, + kDisconnect + }; EResult parseHandshakeMessage(const UInt8 *code); EResult parseMessage(const UInt8 *code); diff --git a/src/lib/common/IInterface.h b/src/lib/common/IInterface.h index 3fce440cb..125f2a6ab 100644 --- a/src/lib/common/IInterface.h +++ b/src/lib/common/IInterface.h @@ -25,8 +25,11 @@ This is the base class of all interface classes. An interface class has only pure virtual methods. */ -class IInterface { +class IInterface +{ public: //! Interface destructor does nothing - virtual ~IInterface() {} + virtual ~IInterface() + { + } }; diff --git a/src/lib/common/common.h b/src/lib/common/common.h index 184a732da..fe98313d6 100644 --- a/src/lib/common/common.h +++ b/src/lib/common/common.h @@ -35,7 +35,8 @@ #include #include -enum { +enum +{ kExitSuccess = 0, // successful completion kExitFailed = 1, // general failure kExitTerminated = 2, // killed by signal diff --git a/src/lib/common/copyright.h b/src/lib/common/copyright.h index d20e248b9..0865155a0 100644 --- a/src/lib/common/copyright.h +++ b/src/lib/common/copyright.h @@ -28,13 +28,15 @@ const auto kCopyrightFormat = // "Copyright (C) 2009-2012 Nick Bolton\n" "Copyright (C) 2002-2009 Chris Schoeneman"; -inline std::string copyright() { +inline std::string copyright() +{ const std::string date = BUILD_DATE; const auto year = date.substr(0, 4); const auto kBufferLength = 256; std::vector buffer(kBufferLength); std::snprintf( // NOSONAR - buffer.data(), kBufferLength, kCopyrightFormat, year.c_str()); + buffer.data(), kBufferLength, kCopyrightFormat, year.c_str() + ); return std::string(buffer.data()); } diff --git a/src/lib/common/ipc.h b/src/lib/common/ipc.h index e9531ea69..33cf88b0c 100644 --- a/src/lib/common/ipc.h +++ b/src/lib/common/ipc.h @@ -19,7 +19,8 @@ #include "common/basic_types.h" -enum class IpcMessageType : UInt8 { +enum class IpcMessageType : UInt8 +{ Hello, HelloBack, LogLine, @@ -28,7 +29,12 @@ enum class IpcMessageType : UInt8 { Setting }; -enum class IpcClientType { Unknown, GUI, Node }; +enum class IpcClientType +{ + Unknown, + GUI, + Node +}; const auto kIpcHost = "127.0.0.1"; const auto kIpcPort = 24801; diff --git a/src/lib/common/stdistream.h b/src/lib/common/stdistream.h index 154d1a80c..3525f6bdd 100644 --- a/src/lib/common/stdistream.h +++ b/src/lib/common/stdistream.h @@ -29,22 +29,28 @@ #if defined(_MSC_VER) && _MSC_VER <= 1200 // VC++6 istream has no overloads for __int* types, .NET does -inline std::istream &operator>>(std::istream &s, SInt8 &i) { +inline std::istream &operator>>(std::istream &s, SInt8 &i) +{ return s >> (signed char &)i; } -inline std::istream &operator>>(std::istream &s, SInt16 &i) { +inline std::istream &operator>>(std::istream &s, SInt16 &i) +{ return s >> (short &)i; } -inline std::istream &operator>>(std::istream &s, SInt32 &i) { +inline std::istream &operator>>(std::istream &s, SInt32 &i) +{ return s >> (int &)i; } -inline std::istream &operator>>(std::istream &s, UInt8 &i) { +inline std::istream &operator>>(std::istream &s, UInt8 &i) +{ return s >> (unsigned char &)i; } -inline std::istream &operator>>(std::istream &s, UInt16 &i) { +inline std::istream &operator>>(std::istream &s, UInt16 &i) +{ return s >> (unsigned short &)i; } -inline std::istream &operator>>(std::istream &s, UInt32 &i) { +inline std::istream &operator>>(std::istream &s, UInt32 &i) +{ return s >> (unsigned int &)i; } #endif diff --git a/src/lib/common/stdsstream.h b/src/lib/common/stdsstream.h index 3f7c8c630..18e64b830 100644 --- a/src/lib/common/stdsstream.h +++ b/src/lib/common/stdsstream.h @@ -60,7 +60,8 @@ the executable file might be covered by the GNU General Public License. */ #include namespace std { -class stringbuf : public streambuf { +class stringbuf : public streambuf +{ public: typedef char char_type; typedef int int_type; @@ -71,7 +72,8 @@ public: : streambuf(), mode(static_cast(which)), stream(NULL), - stream_len(0) { + stream_len(0) + { stringbuf_init(); } @@ -79,7 +81,8 @@ public: : streambuf(), mode(static_cast(which)), stream(NULL), - stream_len(0) { + stream_len(0) + { if (mode & (ios::in | ios::out)) { stream_len = str.size(); stream = new char_type[stream_len]; @@ -88,16 +91,21 @@ public: stringbuf_init(); } - virtual ~stringbuf() { delete[] stream; } + virtual ~stringbuf() + { + delete[] stream; + } - string str() const { + string str() const + { if (pbase() != 0) return string(stream, pptr() - pbase()); else return string(); } - void str(const string &str) { + void str(const string &str) + { delete[] stream; stream_len = str.size(); stream = new char_type[stream_len]; @@ -107,9 +115,13 @@ public: protected: // The buffer is already in gptr, so if it ends then it is out of data. - virtual int underflow() { return EOF; } + virtual int underflow() + { + return EOF; + } - virtual int overflow(int c = EOF) { + virtual int overflow(int c = EOF) + { int res; if (mode & ios::out) { if (c != EOF) { @@ -129,7 +141,8 @@ protected: return res; } - virtual streambuf *setbuf(char_type *s, streamsize n) { + virtual streambuf *setbuf(char_type *s, streamsize n) + { if (n != 0) { delete[] stream; stream = new char_type[n]; @@ -140,8 +153,8 @@ protected: return this; } - virtual pos_type - seekoff(off_type off, ios::seek_dir way, int which = ios::in | ios::out) { + virtual pos_type seekoff(off_type off, ios::seek_dir way, int which = ios::in | ios::out) + { pos_type ret = pos_type(off_type(-1)); bool testin = which & ios::in && mode & ios::in; bool testout = which & ios::out && mode & ios::out; @@ -173,13 +186,11 @@ protected: newoffo = endo - curo; } - if (testin && newoffi + off + curi - beg >= 0 && - endi - beg >= newoffi + off + curi - beg) { + if (testin && newoffi + off + curi - beg >= 0 && endi - beg >= newoffi + off + curi - beg) { gbump(newoffi + off); ret = pos_type(newoffi + off + curi); } - if (testout && newoffo + off + curo - beg >= 0 && - endo - beg >= newoffo + off + curo - beg) { + if (testout && newoffo + off + curo - beg >= 0 && endo - beg >= newoffo + off + curo - beg) { pbump(newoffo + off); ret = pos_type(newoffo + off + curo); } @@ -187,13 +198,15 @@ protected: return ret; } - virtual pos_type seekpos(pos_type sp, int which = ios::in | ios::out) { + virtual pos_type seekpos(pos_type sp, int which = ios::in | ios::out) + { pos_type ret = seekoff(sp, ios::beg, which); return ret; } private: - void stringbuf_sync(streamsize i, streamsize o) { + void stringbuf_sync(streamsize i, streamsize o) + { if (mode & ios::in) setg(stream, stream + i, stream + stream_len); if (mode & ios::out) { @@ -201,7 +214,8 @@ private: pbump(o); } } - void stringbuf_init() { + void stringbuf_init() + { if (mode & ios::ate) stringbuf_sync(0, stream_len); else @@ -214,75 +228,105 @@ private: streamsize stream_len; }; -class istringstream : public istream { +class istringstream : public istream +{ public: typedef char char_type; typedef int int_type; typedef streampos pos_type; typedef streamoff off_type; - explicit istringstream(int which = ios::in) - : istream(&sb), - sb(which | ios::in) {} + explicit istringstream(int which = ios::in) : istream(&sb), sb(which | ios::in) + { + } - explicit istringstream(const string &str, int which = ios::in) - : istream(&sb), - sb(str, which | ios::in) {} + explicit istringstream(const string &str, int which = ios::in) : istream(&sb), sb(str, which | ios::in) + { + } - stringbuf *rdbuf() const { return const_cast(&sb); } + stringbuf *rdbuf() const + { + return const_cast(&sb); + } - string str() const { return rdbuf()->str(); } - void str(const string &s) { rdbuf()->str(s); } + string str() const + { + return rdbuf()->str(); + } + void str(const string &s) + { + rdbuf()->str(s); + } private: stringbuf sb; }; -class ostringstream : public ostream { +class ostringstream : public ostream +{ public: typedef char char_type; typedef int int_type; typedef streampos pos_type; typedef streamoff off_type; - explicit ostringstream(int which = ios::out) - : ostream(&sb), - sb(which | ios::out) {} + explicit ostringstream(int which = ios::out) : ostream(&sb), sb(which | ios::out) + { + } - explicit ostringstream(const string &str, int which = ios::out) - : ostream(&sb), - sb(str, which | ios::out) {} + explicit ostringstream(const string &str, int which = ios::out) : ostream(&sb), sb(str, which | ios::out) + { + } - stringbuf *rdbuf() const { return const_cast(&sb); } + stringbuf *rdbuf() const + { + return const_cast(&sb); + } - string str() const { return rdbuf()->str(); } + string str() const + { + return rdbuf()->str(); + } - void str(const string &s) { rdbuf()->str(s); } + void str(const string &s) + { + rdbuf()->str(s); + } private: stringbuf sb; }; -class stringstream : public iostream { +class stringstream : public iostream +{ public: typedef char char_type; typedef int int_type; typedef streampos pos_type; typedef streamoff off_type; - explicit stringstream(int which = ios::out | ios::in) - : iostream(&sb), - sb(which) {} + explicit stringstream(int which = ios::out | ios::in) : iostream(&sb), sb(which) + { + } - explicit stringstream(const string &str, int which = ios::out | ios::in) - : iostream(&sb), - sb(str, which) {} + explicit stringstream(const string &str, int which = ios::out | ios::in) : iostream(&sb), sb(str, which) + { + } - stringbuf *rdbuf() const { return const_cast(&sb); } + stringbuf *rdbuf() const + { + return const_cast(&sb); + } - string str() const { return rdbuf()->str(); } + string str() const + { + return rdbuf()->str(); + } - void str(const string &s) { rdbuf()->str(s); } + void str(const string &s) + { + rdbuf()->str(s); + } private: stringbuf sb; diff --git a/src/lib/common/version.h b/src/lib/common/version.h index 883ff2056..9e718ccfd 100644 --- a/src/lib/common/version.h +++ b/src/lib/common/version.h @@ -23,7 +23,8 @@ namespace deskflow { -inline std::string version() { +inline std::string version() +{ std::string result = kVersion; std::string gitSha = kVersionGitSha; if (!gitSha.empty()) { diff --git a/src/lib/deskflow/App.cpp b/src/lib/deskflow/App.cpp index e907b7a80..8b06e3111 100644 --- a/src/lib/deskflow/App.cpp +++ b/src/lib/deskflow/App.cpp @@ -71,9 +71,7 @@ App *App::s_instance = nullptr; // App // -App::App( - IEventQueue *events, CreateTaskBarReceiverFunc createTaskBarReceiver, - deskflow::ArgsBase *args) +App::App(IEventQueue *events, CreateTaskBarReceiverFunc createTaskBarReceiver, deskflow::ArgsBase *args) : m_bye(&exit), m_taskBarReceiver(NULL), m_suspended(false), @@ -83,17 +81,20 @@ App::App( m_createTaskBarReceiver(createTaskBarReceiver), m_appUtil(events), m_ipcClient(nullptr), - m_socketMultiplexer(nullptr) { + m_socketMultiplexer(nullptr) +{ assert(s_instance == nullptr); s_instance = this; } -App::~App() { +App::~App() +{ s_instance = nullptr; delete m_args; } -void App::version() { +void App::version() +{ const auto version = deskflow::version(); const auto copyright = deskflow::copyright(); @@ -101,13 +102,14 @@ void App::version() { std::vector buffer(kBufferLength); std::snprintf( // NOSONAR buffer.data(), kBufferLength, "%s v%s, protocol v%d.%d\n%s", // - argsBase().m_pname, version.c_str(), kProtocolMajorVersion, - kProtocolMinorVersion, copyright.c_str()); + argsBase().m_pname, version.c_str(), kProtocolMajorVersion, kProtocolMinorVersion, copyright.c_str() + ); std::cout << std::string(buffer.data()) << std::endl; } -int App::run(int argc, char **argv) { +int App::run(int argc, char **argv) +{ #if MAC_OS_X_VERSION_10_7 // dock hide only supported on lion :( ProcessSerialNumber psn = {0, kCurrentProcess}; @@ -134,9 +136,7 @@ int App::run(int argc, char **argv) { // using the exit(int) function! result = e.getCode(); } catch (DisplayInvalidException &die) { - LOG( - (CLOG_CRIT "a display invalid exception error occurred: %s\n", - die.what())); + LOG((CLOG_CRIT "a display invalid exception error occurred: %s\n", die.what())); // display invalid exceptions can occur when going to sleep. When this // process exits, the UI will restart us instantly. We don't really want // that behevior, so we quies for a bit @@ -154,7 +154,8 @@ int App::run(int argc, char **argv) { return result; } -int App::daemonMainLoop(int, const char **) { +int App::daemonMainLoop(int, const char **) +{ #if SYSAPI_WIN32 SystemLogger sysLogger(daemonName(), false); #else @@ -163,7 +164,8 @@ int App::daemonMainLoop(int, const char **) { return mainLoop(); } -void App::setupFileLogging() { +void App::setupFileLogging() +{ if (argsBase().m_logFile != NULL) { m_fileLog = new FileLogOutputter(argsBase().m_logFile); CLOG->insert(m_fileLog); @@ -171,24 +173,25 @@ void App::setupFileLogging() { } } -void App::loggingFilterWarning() { +void App::loggingFilterWarning() +{ if (CLOG->getFilter() > CLOG->getConsoleMaxLevel()) { if (argsBase().m_logFile == NULL) { LOG( - (CLOG_WARN - "log messages above %s are NOT sent to console (use file logging)", - CLOG->getFilterName(CLOG->getConsoleMaxLevel()))); + (CLOG_WARN "log messages above %s are NOT sent to console (use file logging)", + CLOG->getFilterName(CLOG->getConsoleMaxLevel())) + ); } } } -void App::initApp(int argc, const char **argv) { +void App::initApp(int argc, const char **argv) +{ std::string configFilename; #if HAVE_CLI11 CLI::App cliApp{kAppDescription, kAppName}; - cliApp.add_option( - "--config-toml", configFilename, "Use TOML configuration file"); + cliApp.add_option("--config-toml", configFilename, "Use TOML configuration file"); // Allow legacy args. cliApp.allow_extras(); @@ -210,9 +213,9 @@ void App::initApp(int argc, const char **argv) { // set log filter if (!CLOG->setFilter(argsBase().m_logFilter)) { - LOG( - (CLOG_CRIT "%s: unrecognized log level `%s'" BYE, argsBase().m_pname, - argsBase().m_logFilter, argsBase().m_pname)); + LOG(( + CLOG_CRIT "%s: unrecognized log level `%s'" BYE, argsBase().m_pname, argsBase().m_logFilter, argsBase().m_pname + )); m_bye(kExitArgs); } loggingFilterWarning(); @@ -236,23 +239,25 @@ void App::initApp(int argc, const char **argv) { } } -void App::initIpcClient() { +void App::initIpcClient() +{ m_ipcClient = new IpcClient(m_events, m_socketMultiplexer); m_ipcClient->connect(); m_events->adoptHandler( - m_events->forIpcClient().messageReceived(), m_ipcClient, - new TMethodEventJob(this, &App::handleIpcMessage)); + m_events->forIpcClient().messageReceived(), m_ipcClient, new TMethodEventJob(this, &App::handleIpcMessage) + ); } -void App::cleanupIpcClient() { +void App::cleanupIpcClient() +{ m_ipcClient->disconnect(); - m_events->removeHandler( - m_events->forIpcClient().messageReceived(), m_ipcClient); + m_events->removeHandler(m_events->forIpcClient().messageReceived(), m_ipcClient); delete m_ipcClient; } -void App::handleIpcMessage(const Event &e, void *) { +void App::handleIpcMessage(const Event &e, void *) +{ IpcMessage *m = static_cast(e.getDataObject()); if (m->type() == IpcMessageType::Shutdown) { LOG((CLOG_INFO "got ipc shutdown message")); @@ -260,7 +265,8 @@ void App::handleIpcMessage(const Event &e, void *) { } } -void App::runEventsLoop(void *) { +void App::runEventsLoop(void *) +{ m_events->loop(); #if defined(MAC_OS_X_VERSION_10_7) @@ -274,34 +280,64 @@ void App::runEventsLoop(void *) { // MinimalApp // -MinimalApp::MinimalApp() : App(NULL, NULL, new deskflow::ArgsBase()) { +MinimalApp::MinimalApp() : App(NULL, NULL, new deskflow::ArgsBase()) +{ m_arch.init(); setEvents(m_events); } -MinimalApp::~MinimalApp() {} +MinimalApp::~MinimalApp() +{ +} -int MinimalApp::standardStartup(int argc, char **argv) { return 0; } - -int MinimalApp::runInner( - int argc, char **argv, ILogOutputter *outputter, StartupFunc startup) { +int MinimalApp::standardStartup(int argc, char **argv) +{ return 0; } -void MinimalApp::startNode() {} +int MinimalApp::runInner(int argc, char **argv, ILogOutputter *outputter, StartupFunc startup) +{ + return 0; +} -int MinimalApp::mainLoop() { return 0; } +void MinimalApp::startNode() +{ +} -int MinimalApp::foregroundStartup(int argc, char **argv) { return 0; } +int MinimalApp::mainLoop() +{ + return 0; +} -deskflow::Screen *MinimalApp::createScreen() { return NULL; } +int MinimalApp::foregroundStartup(int argc, char **argv) +{ + return 0; +} -void MinimalApp::loadConfig() {} +deskflow::Screen *MinimalApp::createScreen() +{ + return NULL; +} -bool MinimalApp::loadConfig(const String &pathname) { return false; } +void MinimalApp::loadConfig() +{ +} -const char *MinimalApp::daemonInfo() const { return ""; } +bool MinimalApp::loadConfig(const String &pathname) +{ + return false; +} -const char *MinimalApp::daemonName() const { return ""; } +const char *MinimalApp::daemonInfo() const +{ + return ""; +} -void MinimalApp::parseArgs(int argc, const char *const *argv) {} +const char *MinimalApp::daemonName() const +{ + return ""; +} + +void MinimalApp::parseArgs(int argc, const char *const *argv) +{ +} diff --git a/src/lib/deskflow/App.h b/src/lib/deskflow/App.h index f3f97e49d..d58016af4 100644 --- a/src/lib/deskflow/App.h +++ b/src/lib/deskflow/App.h @@ -43,18 +43,20 @@ class Screen; class IEventQueue; class SocketMultiplexer; -typedef IArchTaskBarReceiver *(*CreateTaskBarReceiverFunc)( - const BufferedLogOutputter *, IEventQueue *events); +typedef IArchTaskBarReceiver *(*CreateTaskBarReceiverFunc)(const BufferedLogOutputter *, IEventQueue *events); -class App : public IApp { +class App : public IApp +{ public: - class XNoEiSupport : public std::runtime_error { + class XNoEiSupport : public std::runtime_error + { public: - XNoEiSupport() : std::runtime_error("libei is not supported") {} + XNoEiSupport() : std::runtime_error("libei is not supported") + { + } }; - App(IEventQueue *events, CreateTaskBarReceiverFunc createTaskBarReceiver, - deskflow::ArgsBase *args); + App(IEventQueue *events, CreateTaskBarReceiverFunc createTaskBarReceiver, deskflow::ArgsBase *args); App(App const &) = delete; App(App &&) = delete; virtual ~App(); @@ -70,30 +72,57 @@ public: virtual std::string configSection() const = 0; virtual void version(); - virtual void setByeFunc(void (*bye)(int)) { m_bye = bye; } - virtual void bye(int error) { m_bye(error); } - virtual IEventQueue *getEvents() const { return m_events; } + virtual void setByeFunc(void (*bye)(int)) + { + m_bye = bye; + } + virtual void bye(int error) + { + m_bye(error); + } + virtual IEventQueue *getEvents() const + { + return m_events; + } - ARCH_APP_UTIL &appUtil() { return m_appUtil; } - deskflow::ArgsBase &argsBase() const { return *m_args; } + ARCH_APP_UTIL &appUtil() + { + return m_appUtil; + } + deskflow::ArgsBase &argsBase() const + { + return *m_args; + } int run(int argc, char **argv); int daemonMainLoop(int, const char **); void setupFileLogging(); void loggingFilterWarning(); void initApp(int argc, const char **argv); - void initApp(int argc, char **argv) { initApp(argc, (const char **)argv); } - void setEvents(EventQueue &events) { m_events = &events; } - void setSocketMultiplexer(SocketMultiplexer *sm) { m_socketMultiplexer = sm; } + void initApp(int argc, char **argv) + { + initApp(argc, (const char **)argv); + } + void setEvents(EventQueue &events) + { + m_events = &events; + } + void setSocketMultiplexer(SocketMultiplexer *sm) + { + m_socketMultiplexer = sm; + } - virtual IArchTaskBarReceiver *taskBarReceiver() const { + virtual IArchTaskBarReceiver *taskBarReceiver() const + { return m_taskBarReceiver; } - SocketMultiplexer *getSocketMultiplexer() const { + SocketMultiplexer *getSocketMultiplexer() const + { return m_socketMultiplexer; } - static App &instance() { + static App &instance() + { assert(s_instance != nullptr); return *s_instance; } @@ -122,16 +151,15 @@ private: SocketMultiplexer *m_socketMultiplexer; }; -class MinimalApp : public App { +class MinimalApp : public App +{ public: MinimalApp(); virtual ~MinimalApp(); // IApp overrides virtual int standardStartup(int argc, char **argv) override; - virtual int runInner( - int argc, char **argv, ILogOutputter *outputter, - StartupFunc startup) override; + virtual int runInner(int argc, char **argv, ILogOutputter *outputter, StartupFunc startup) override; virtual void startNode() override; virtual int mainLoop() override; virtual int foregroundStartup(int argc, char **argv) override; @@ -145,7 +173,10 @@ public: // // App overrides // - std::string configSection() const override { return ""; } + std::string configSection() const override + { + return ""; + } private: Arch m_arch; @@ -159,30 +190,30 @@ private: #define DAEMON_RUNNING(running_) #endif -#define HELP_COMMON_INFO_1 \ - " -d, --debug filter out log messages with priority below " \ - "level.\n" \ - " level may be: FATAL, ERROR, WARNING, NOTE, " \ - "INFO,\n" \ - " DEBUG, DEBUG1, DEBUG2.\n" \ - " -n, --name use screen-name instead the hostname to " \ - "identify\n" \ - " this screen in the configuration.\n" \ - " -1, --no-restart do not try to restart on failure.\n" \ - "* --restart restart the server automatically if it fails.\n" \ - " -l --log write log messages to file.\n" \ - " --no-tray disable the system tray icon.\n" \ - " --enable-drag-drop enable file drag & drop.\n" \ - " --enable-crypto enable TLS encryption.\n" \ +#define HELP_COMMON_INFO_1 \ + " -d, --debug filter out log messages with priority below " \ + "level.\n" \ + " level may be: FATAL, ERROR, WARNING, NOTE, " \ + "INFO,\n" \ + " DEBUG, DEBUG1, DEBUG2.\n" \ + " -n, --name use screen-name instead the hostname to " \ + "identify\n" \ + " this screen in the configuration.\n" \ + " -1, --no-restart do not try to restart on failure.\n" \ + "* --restart restart the server automatically if it fails.\n" \ + " -l --log write log messages to file.\n" \ + " --no-tray disable the system tray icon.\n" \ + " --enable-drag-drop enable file drag & drop.\n" \ + " --enable-crypto enable TLS encryption.\n" \ " --tls-cert specify the path to the TLS certificate file.\n" -#define HELP_COMMON_INFO_2 \ - " -h, --help display this help and exit.\n" \ +#define HELP_COMMON_INFO_2 \ + " -h, --help display this help and exit.\n" \ " --version display version information and exit.\n" -#define HELP_COMMON_ARGS \ - " [--name ]" \ - " [--restart|--no-restart]" \ +#define HELP_COMMON_ARGS \ + " [--name ]" \ + " [--restart|--no-restart]" \ " [--debug ]" // system args (windows/unix) @@ -190,31 +221,30 @@ private: // unix daemon mode args #define HELP_SYS_ARGS " [--daemon|--no-daemon]" -#define HELP_SYS_INFO \ - " -f, --no-daemon run in the foreground.\n" \ +#define HELP_SYS_INFO \ + " -f, --no-daemon run in the foreground.\n" \ "* --daemon run as a daemon.\n" #elif SYSAPI_WIN32 // windows args #define HELP_SYS_ARGS " [--service ] [--relaunch] [--exit-pause]" -#define HELP_SYS_INFO \ - " --service manage the windows service, valid options " \ - "are:\n" \ - " install/uninstall/start/stop\n" \ - " --relaunch persistently relaunches process in current " \ - "user \n" \ - " session (useful for vista and upward).\n" \ - " --exit-pause wait for key press on exit, can be useful for\n" \ +#define HELP_SYS_INFO \ + " --service manage the windows service, valid options " \ + "are:\n" \ + " install/uninstall/start/stop\n" \ + " --relaunch persistently relaunches process in current " \ + "user \n" \ + " session (useful for vista and upward).\n" \ + " --exit-pause wait for key press on exit, can be useful for\n" \ " reading error messages that occur on exit.\n" #endif #if !defined(WINAPI_LIBEI) && WINAPI_XWINDOWS -const auto kHelpNoWayland = - "\n" - "Your Linux distribution does not support Wayland EI (emulated input)\n" - "which is required for Wayland support. Please use a Linux distribution\n" - "that supports Wayland EI.\n"; +const auto kHelpNoWayland = "\n" + "Your Linux distribution does not support Wayland EI (emulated input)\n" + "which is required for Wayland support. Please use a Linux distribution\n" + "that supports Wayland EI.\n"; #else const auto kHelpNoWayland = ""; diff --git a/src/lib/deskflow/AppUtil.cpp b/src/lib/deskflow/AppUtil.cpp index e586c283d..9b7f43b85 100644 --- a/src/lib/deskflow/AppUtil.cpp +++ b/src/lib/deskflow/AppUtil.cpp @@ -22,21 +22,29 @@ AppUtil *AppUtil::s_instance = nullptr; -AppUtil::AppUtil() : m_app(nullptr) { s_instance = this; } +AppUtil::AppUtil() : m_app(nullptr) +{ + s_instance = this; +} -AppUtil::~AppUtil() {} +AppUtil::~AppUtil() +{ +} -void AppUtil::adoptApp(IApp *app) { +void AppUtil::adoptApp(IApp *app) +{ app->setByeFunc(&exitAppStatic); m_app = app; } -IApp &AppUtil::app() const { +IApp &AppUtil::app() const +{ assert(m_app != nullptr); return *m_app; } -AppUtil &AppUtil::instance() { +AppUtil &AppUtil::instance() +{ assert(s_instance != nullptr); return *s_instance; } diff --git a/src/lib/deskflow/AppUtil.h b/src/lib/deskflow/AppUtil.h index c0887e4b1..6e70aff4e 100644 --- a/src/lib/deskflow/AppUtil.h +++ b/src/lib/deskflow/AppUtil.h @@ -21,18 +21,27 @@ #include "deskflow/IAppUtil.h" #include "deskflow/XDeskflow.h" -class AppUtil : public IAppUtil { +class AppUtil : public IAppUtil +{ public: AppUtil(); virtual ~AppUtil(); virtual void adoptApp(IApp *app); IApp &app() const; - virtual void exitApp(int code) { throw XExitApp(code); } + virtual void exitApp(int code) + { + throw XExitApp(code); + } static AppUtil &instance(); - static void exitAppStatic(int code) { instance().exitApp(code); } - virtual void beforeAppExit() {} + static void exitAppStatic(int code) + { + instance().exitApp(code); + } + virtual void beforeAppExit() + { + } private: IApp *m_app; diff --git a/src/lib/deskflow/ArgParser.cpp b/src/lib/deskflow/ArgParser.cpp index 731d27dc6..28ab11eef 100644 --- a/src/lib/deskflow/ArgParser.cpp +++ b/src/lib/deskflow/ArgParser.cpp @@ -31,10 +31,12 @@ deskflow::ArgsBase *ArgParser::m_argsBase = nullptr; -ArgParser::ArgParser(App *app) : m_app(app) {} +ArgParser::ArgParser(App *app) : m_app(app) +{ +} -bool ArgParser::parseServerArgs( - deskflow::ServerArgs &args, int argc, const char *const *argv) { +bool ArgParser::parseServerArgs(deskflow::ServerArgs &args, int argc, const char *const *argv) +{ setArgsBase(args); updateCommonArgs(argv); int i = 1; @@ -55,9 +57,7 @@ bool ArgParser::parseServerArgs( ++i; continue; } else { - LOG( - (CLOG_CRIT "%s: unrecognized option `%s'" BYE, args.m_pname, argv[i], - args.m_pname)); + LOG((CLOG_CRIT "%s: unrecognized option `%s'" BYE, args.m_pname, argv[i], args.m_pname)); return false; } ++i; @@ -70,8 +70,8 @@ bool ArgParser::parseServerArgs( return true; } -bool ArgParser::parseClientArgs( - deskflow::ClientArgs &args, int argc, const char *const *argv) { +bool ArgParser::parseClientArgs(deskflow::ClientArgs &args, int argc, const char *const *argv) +{ setArgsBase(args); updateCommonArgs(argv); @@ -96,8 +96,7 @@ bool ArgParser::parseClientArgs( } else if (isArg(i, argc, argv, nullptr, "--sync-language")) { args.m_enableLangSync = true; } else if (isArg(i, argc, argv, nullptr, "--invert-scroll")) { - args.m_clientScrollDirection = - deskflow::ClientScrollDirection::INVERT_SERVER; + args.m_clientScrollDirection = deskflow::ClientScrollDirection::INVERT_SERVER; } else if (isArg(i, argc, argv, nullptr, "--host")) { args.m_hostMode = true; } else if (isArg(i, argc, argv, nullptr, "client")) { @@ -109,9 +108,7 @@ bool ArgParser::parseClientArgs( return true; } - LOG( - (CLOG_CRIT "%s: unrecognized option `%s'" BYE, args.m_pname, argv[i], - args.m_pname)); + LOG((CLOG_CRIT "%s: unrecognized option `%s'" BYE, args.m_pname, argv[i], args.m_pname)); return false; } ++i; @@ -119,9 +116,7 @@ bool ArgParser::parseClientArgs( // exactly one non-option argument (server-address) if (i == argc && !args.m_shouldExitFail && !args.m_shouldExitOk) { - LOG( - (CLOG_CRIT "%s: a server address or name is required" BYE, args.m_pname, - args.m_pname)); + LOG((CLOG_CRIT "%s: a server address or name is required" BYE, args.m_pname, args.m_pname)); return false; } @@ -133,8 +128,9 @@ bool ArgParser::parseClientArgs( } bool ArgParser::parsePlatformArgs( - deskflow::ArgsBase &argsBase, const int &argc, const char *const *argv, - int &i, bool isServer) { + deskflow::ArgsBase &argsBase, const int &argc, const char *const *argv, int &i, bool isServer +) +{ #if WINAPI_MSWINDOWS if (isArg(i, argc, argv, nullptr, "--exit-pause")) { argsBase.m_pauseOnExit = true; @@ -169,8 +165,8 @@ bool ArgParser::parsePlatformArgs( #endif } -bool ArgParser::parseToolArgs( - ToolArgs &args, int argc, const char *const *argv) { +bool ArgParser::parseToolArgs(ToolArgs &args, int argc, const char *const *argv) +{ // We support exactly one argument at a fix position static const int only_index{1}; if (isArg(only_index, argc, argv, nullptr, "--get-active-desktop", 0)) { @@ -189,7 +185,8 @@ bool ArgParser::parseToolArgs( return false; } -bool ArgParser::parseGenericArgs(int argc, const char *const *argv, int &i) { +bool ArgParser::parseGenericArgs(int argc, const char *const *argv, int &i) +{ if (isArg(i, argc, argv, "-a", "--address", 1)) { argsBase().m_deskflowAddress = argv[++i]; } else if (isArg(i, argc, argv, "-d", "--debug", 1)) { @@ -246,8 +243,7 @@ bool ArgParser::parseGenericArgs(int argc, const char *const *argv, int &i) { if (!IsWindowsVistaOrGreater()) { useDragDrop = false; - LOG((CLOG_INFO - "ignoring --enable-drag-drop, not supported below vista.")); + LOG((CLOG_INFO "ignoring --enable-drag-drop, not supported below vista.")); } #endif @@ -272,9 +268,11 @@ bool ArgParser::parseGenericArgs(int argc, const char *const *argv, int &i) { return true; } -bool ArgParser::parseDeprecatedArgs(int argc, const char *const *argv, int &i) { +bool ArgParser::parseDeprecatedArgs(int argc, const char *const *argv, int &i) +{ static const std::vector deprecatedArgs = { - "--crypto-pass", "--res-w", "--res-h", "--prm-wc", "--prm-hc"}; + "--crypto-pass", "--res-w", "--res-h", "--prm-wc", "--prm-hc" + }; for (auto &arg : deprecatedArgs) { if (isArg(i, argc, argv, nullptr, arg)) { @@ -288,16 +286,15 @@ bool ArgParser::parseDeprecatedArgs(int argc, const char *const *argv, int &i) { } bool ArgParser::isArg( - int argi, int argc, const char *const *argv, const char *name1, - const char *name2, int minRequiredParameters) { + int argi, int argc, const char *const *argv, const char *name1, const char *name2, int minRequiredParameters +) +{ const auto match1 = (name1 != nullptr && strcmp(argv[argi], name1) == 0); const auto match2 = (name2 != nullptr && strcmp(argv[argi], name2) == 0); if (match1 || match2) { // match. check args left. if (argi + minRequiredParameters >= argc) { - LOG( - (CLOG_PRINT "%s: missing arguments for `%s'" BYE, argsBase().m_pname, - argv[argi], argsBase().m_pname)); + LOG((CLOG_PRINT "%s: missing arguments for `%s'" BYE, argsBase().m_pname, argv[argi], argsBase().m_pname)); argsBase().m_shouldExitFail = true; return false; } @@ -308,7 +305,8 @@ bool ArgParser::isArg( return false; } -void ArgParser::splitCommandString(String &command, std::vector &argv) { +void ArgParser::splitCommandString(String &command, std::vector &argv) +{ if (command.empty()) { return; } @@ -327,8 +325,7 @@ void ArgParser::splitCommandString(String &command, std::vector &argv) { if (space > leftDoubleQuote && space < rightDoubleQuote) { ignoreThisSpace = true; } else if (space > rightDoubleQuote) { - searchDoubleQuotes( - command, leftDoubleQuote, rightDoubleQuote, rightDoubleQuote + 1); + searchDoubleQuotes(command, leftDoubleQuote, rightDoubleQuote, rightDoubleQuote + 1); } if (!ignoreThisSpace) { @@ -352,8 +349,8 @@ void ArgParser::splitCommandString(String &command, std::vector &argv) { argv.push_back(subString); } -bool ArgParser::searchDoubleQuotes( - String &command, size_t &left, size_t &right, size_t startPos) { +bool ArgParser::searchDoubleQuotes(String &command, size_t &left, size_t &right, size_t startPos) +{ bool result = false; left = String::npos; right = String::npos; @@ -374,14 +371,16 @@ bool ArgParser::searchDoubleQuotes( return result; } -void ArgParser::removeDoubleQuotes(String &arg) { +void ArgParser::removeDoubleQuotes(String &arg) +{ // if string is surrounded by double quotes, remove them if (arg[0] == '\"' && arg[arg.size() - 1] == '\"') { arg = arg.substr(1, arg.size() - 2); } } -const char **ArgParser::getArgv(std::vector &argsArray) { +const char **ArgParser::getArgv(std::vector &argsArray) +{ size_t argc = argsArray.size(); // caller is responsible for deleting the outer array only @@ -397,12 +396,11 @@ const char **ArgParser::getArgv(std::vector &argsArray) { return argv; } -String ArgParser::assembleCommand( - std::vector &argsArray, String ignoreArg, int parametersRequired) { +String ArgParser::assembleCommand(std::vector &argsArray, String ignoreArg, int parametersRequired) +{ String result; - for (std::vector::iterator it = argsArray.begin(); - it != argsArray.end(); ++it) { + for (std::vector::iterator it = argsArray.begin(); it != argsArray.end(); ++it) { if (it->compare(ignoreArg) == 0) { it = it + parametersRequired; continue; @@ -427,12 +425,14 @@ String ArgParser::assembleCommand( return result; } -void ArgParser::updateCommonArgs(const char *const *argv) { +void ArgParser::updateCommonArgs(const char *const *argv) +{ argsBase().m_name = ARCH->getHostName(); argsBase().m_pname = ARCH->getBasename(argv[0]); } -bool ArgParser::checkUnexpectedArgs() { +bool ArgParser::checkUnexpectedArgs() +{ #if SYSAPI_WIN32 // suggest that user installs as a windows service. when launched as // service, process should automatically detect that it should run in @@ -441,7 +441,8 @@ bool ArgParser::checkUnexpectedArgs() { LOG( (CLOG_ERR "the --daemon argument is not supported on windows. " "instead, install %s as a service (--service install)", - argsBase().m_pname)); + argsBase().m_pname) + ); return true; } #endif diff --git a/src/lib/deskflow/ArgParser.h b/src/lib/deskflow/ArgParser.h index 7d6fd92f1..171c5f436 100644 --- a/src/lib/deskflow/ArgParser.h +++ b/src/lib/deskflow/ArgParser.h @@ -29,36 +29,36 @@ class ClientArgs; class ToolArgs; class App; -class ArgParser { +class ArgParser +{ public: ArgParser(App *app); - bool parseServerArgs( - deskflow::ServerArgs &args, int argc, const char *const *argv); - bool parseClientArgs( - deskflow::ClientArgs &args, int argc, const char *const *argv); - bool parsePlatformArgs( - deskflow::ArgsBase &argsBase, const int &argc, const char *const *argv, - int &i, bool isServer); + bool parseServerArgs(deskflow::ServerArgs &args, int argc, const char *const *argv); + bool parseClientArgs(deskflow::ClientArgs &args, int argc, const char *const *argv); + bool parsePlatformArgs(deskflow::ArgsBase &argsBase, const int &argc, const char *const *argv, int &i, bool isServer); bool parseToolArgs(ToolArgs &args, int argc, const char *const *argv); bool parseGenericArgs(int argc, const char *const *argv, int &i); bool parseDeprecatedArgs(int argc, const char *const *argv, int &i); - void setArgsBase(deskflow::ArgsBase &argsBase) { m_argsBase = &argsBase; } + void setArgsBase(deskflow::ArgsBase &argsBase) + { + m_argsBase = &argsBase; + } static bool isArg( - int argi, int argc, const char *const *argv, const char *name1, - const char *name2, int minRequiredParameters = 0); + int argi, int argc, const char *const *argv, const char *name1, const char *name2, int minRequiredParameters = 0 + ); static void splitCommandString(String &command, std::vector &argv); - static bool searchDoubleQuotes( - String &command, size_t &left, size_t &right, size_t startPos = 0); + static bool searchDoubleQuotes(String &command, size_t &left, size_t &right, size_t startPos = 0); static void removeDoubleQuotes(String &arg); static const char **getArgv(std::vector &argsArray); - static String assembleCommand( - std::vector &argsArray, String ignoreArg = "", - int parametersRequired = 0); + static String assembleCommand(std::vector &argsArray, String ignoreArg = "", int parametersRequired = 0); - static deskflow::ArgsBase &argsBase() { return *m_argsBase; } + static deskflow::ArgsBase &argsBase() + { + return *m_argsBase; + } private: void updateCommonArgs(const char *const *argv); diff --git a/src/lib/deskflow/ArgsBase.cpp b/src/lib/deskflow/ArgsBase.cpp index 5c5218a18..dd0a43e2e 100644 --- a/src/lib/deskflow/ArgsBase.cpp +++ b/src/lib/deskflow/ArgsBase.cpp @@ -19,7 +19,8 @@ #include "ArgsBase.h" namespace deskflow { -ArgsBase::~ArgsBase() { +ArgsBase::~ArgsBase() +{ // } } // namespace deskflow diff --git a/src/lib/deskflow/ArgsBase.h b/src/lib/deskflow/ArgsBase.h index ce3463b32..4d2911d8b 100644 --- a/src/lib/deskflow/ArgsBase.h +++ b/src/lib/deskflow/ArgsBase.h @@ -26,13 +26,19 @@ namespace deskflow { * arguments passed into the applications this will be derived * from and expanded to include application specific arguments */ -class ArgsBase { +class ArgsBase +{ public: ArgsBase() = default; virtual ~ArgsBase(); /// @brief This sets the type of the derived class - enum Type { kBase, kServer, kClient }; + enum Type + { + kBase, + kServer, + kClient + }; /// @brief Stores what type of object this is Type m_classType = kBase; @@ -106,7 +112,8 @@ public: protected: /// @brief deletes pointers and sets the value to null - template static inline void destroy(T *&p) { + template static inline void destroy(T *&p) + { delete p; p = 0; } diff --git a/src/lib/deskflow/Chunk.cpp b/src/lib/deskflow/Chunk.cpp index bf2cabd0b..9d1d5afb1 100644 --- a/src/lib/deskflow/Chunk.cpp +++ b/src/lib/deskflow/Chunk.cpp @@ -18,9 +18,13 @@ #include "deskflow/Chunk.h" #include "base/String.h" -Chunk::Chunk(size_t size) : m_dataSize(0) { +Chunk::Chunk(size_t size) : m_dataSize(0) +{ m_chunk = new char[size]; memset(m_chunk, 0, size); } -Chunk::~Chunk() { delete[] m_chunk; } +Chunk::~Chunk() +{ + delete[] m_chunk; +} diff --git a/src/lib/deskflow/Chunk.h b/src/lib/deskflow/Chunk.h index 11c2de8be..2d2725197 100644 --- a/src/lib/deskflow/Chunk.h +++ b/src/lib/deskflow/Chunk.h @@ -20,7 +20,8 @@ #include "common/basic_types.h" #include -class Chunk : public EventData { +class Chunk : public EventData +{ public: Chunk(size_t size); Chunk(Chunk const &) = delete; diff --git a/src/lib/deskflow/ClientApp.cpp b/src/lib/deskflow/ClientApp.cpp index 7dcdc1602..bb7bb5871 100644 --- a/src/lib/deskflow/ClientApp.cpp +++ b/src/lib/deskflow/ClientApp.cpp @@ -74,16 +74,20 @@ #define RETRY_TIME 1.0 -ClientApp::ClientApp( - IEventQueue *events, CreateTaskBarReceiverFunc createTaskBarReceiver) +ClientApp::ClientApp(IEventQueue *events, CreateTaskBarReceiverFunc createTaskBarReceiver) : App(events, createTaskBarReceiver, new deskflow::ClientArgs()), m_client(NULL), m_clientScreen(NULL), - m_serverAddress(NULL) {} + m_serverAddress(NULL) +{ +} -ClientApp::~ClientApp() {} +ClientApp::~ClientApp() +{ +} -void ClientApp::parseArgs(int argc, const char *const *argv) { +void ClientApp::parseArgs(int argc, const char *const *argv) +{ ArgParser argParser(this); bool result = argParser.parseClientArgs(args(), argc, argv); @@ -105,9 +109,7 @@ void ClientApp::parseArgs(int argc, const char *const *argv) { // server. a bad port will never get better. patch by Brent // Priddy. if (!args().m_restartable || e.getError() == XSocketAddress::kBadPort) { - LOG( - (CLOG_CRIT "%s: %s" BYE, args().m_pname, e.what(), - args().m_pname)); + LOG((CLOG_CRIT "%s: %s" BYE, args().m_pname, e.what(), args().m_pname)); m_bye(kExitFailed); } } @@ -115,53 +117,53 @@ void ClientApp::parseArgs(int argc, const char *const *argv) { } } -void ClientApp::help() { +void ClientApp::help() +{ std::stringstream help; - help - << "Usage: " << args().m_pname << " [--address
]" - << " [--yscroll ]" - << " [--sync-language]" - << " [--invert-scroll]" - << " [--host]" + help << "Usage: " << args().m_pname << " [--address
]" + << " [--yscroll ]" + << " [--sync-language]" + << " [--invert-scroll]" + << " [--host]" #ifdef WINAPI_XWINDOWS - << " [--display ]" - << " [--no-xinitthreads]" + << " [--display ]" + << " [--no-xinitthreads]" #endif #ifdef WINAPI_LIBEI - << " [--use-x-window]" + << " [--use-x-window]" #endif - << HELP_SYS_ARGS << HELP_COMMON_ARGS << " " - << "\n\n" - << "Connect to a " DESKFLOW_APP_NAME " mouse/keyboard sharing server.\n" - << "\n" - << " -a, --address
local network interface address.\n" - << HELP_COMMON_INFO_1 << HELP_SYS_INFO - << " --yscroll defines the vertical scrolling delta,\n" - << " which is 120 by default.\n" - << " --sync-language enable language synchronization.\n" - << " --invert-scroll invert scroll direction on this\n" - << " computer.\n" - << " --host act as a host; invert server/client mode\n" - << " and listen instead of connecting.\n" + << HELP_SYS_ARGS << HELP_COMMON_ARGS << " " + << "\n\n" + << "Connect to a " DESKFLOW_APP_NAME " mouse/keyboard sharing server.\n" + << "\n" + << " -a, --address
local network interface address.\n" + << HELP_COMMON_INFO_1 << HELP_SYS_INFO << " --yscroll defines the vertical scrolling delta,\n" + << " which is 120 by default.\n" + << " --sync-language enable language synchronization.\n" + << " --invert-scroll invert scroll direction on this\n" + << " computer.\n" + << " --host act as a host; invert server/client mode\n" + << " and listen instead of connecting.\n" #if WINAPI_XWINDOWS - << " --display when in X mode, connect to the X server\n" - << " at .\n" - << " --no-xinitthreads do not call XInitThreads()\n" + << " --display when in X mode, connect to the X server\n" + << " at .\n" + << " --no-xinitthreads do not call XInitThreads()\n" #endif - << HELP_COMMON_INFO_2 << "\n" - << "* marks defaults.\n" + << HELP_COMMON_INFO_2 << "\n" + << "* marks defaults.\n" - << kHelpNoWayland + << kHelpNoWayland - << "\n" - << "The server address is of the form: [][:].\n" - << "The hostname must be the address or hostname of the server.\n" - << "The port overrides the default port, " << kDefaultPort << ".\n"; + << "\n" + << "The server address is of the form: [][:].\n" + << "The hostname must be the address or hostname of the server.\n" + << "The port overrides the default port, " << kDefaultPort << ".\n"; LOG((CLOG_PRINT "%s", help.str().c_str())); } -const char *ClientApp::daemonName() const { +const char *ClientApp::daemonName() const +{ #if SYSAPI_WIN32 return DESKFLOW_APP_NAME " Client"; #elif SYSAPI_UNIX @@ -169,7 +171,8 @@ const char *ClientApp::daemonName() const { #endif } -const char *ClientApp::daemonInfo() const { +const char *ClientApp::daemonInfo() const +{ #if SYSAPI_WIN32 return "Allows another computer to share it's keyboard and mouse with this " "computer."; @@ -178,21 +181,23 @@ const char *ClientApp::daemonInfo() const { #endif } -deskflow::Screen *ClientApp::createScreen() { +deskflow::Screen *ClientApp::createScreen() +{ #if WINAPI_MSWINDOWS return new deskflow::Screen( new MSWindowsScreen( - false, args().m_noHooks, args().m_stopOnDeskSwitch, m_events, - args().m_enableLangSync, args().m_clientScrollDirection), - m_events); + false, args().m_noHooks, args().m_stopOnDeskSwitch, m_events, args().m_enableLangSync, + args().m_clientScrollDirection + ), + m_events + ); #endif #if defined(WINAPI_XWINDOWS) or defined(WINAPI_LIBEI) if (deskflow::platform::isWayland()) { #if WINAPI_LIBEI LOG((CLOG_INFO "using ei screen for wayland")); - return new deskflow::Screen( - new deskflow::EiScreen(false, m_events, true), m_events); + return new deskflow::Screen(new deskflow::EiScreen(false, m_events, true), m_events); #else throw XNoEiSupport(); #endif @@ -203,35 +208,41 @@ deskflow::Screen *ClientApp::createScreen() { LOG((CLOG_INFO "using legacy x windows screen")); return new deskflow::Screen( new XWindowsScreen( - args().m_display, false, args().m_disableXInitThreads, - args().m_yscroll, m_events, args().m_clientScrollDirection), - m_events); + args().m_display, false, args().m_disableXInitThreads, args().m_yscroll, m_events, + args().m_clientScrollDirection + ), + m_events + ); #endif #if WINAPI_CARBON return new deskflow::Screen( - new OSXScreen( - m_events, false, args().m_enableLangSync, - args().m_clientScrollDirection), - m_events); + new OSXScreen(m_events, false, args().m_enableLangSync, args().m_clientScrollDirection), m_events + ); #endif } -void ClientApp::updateStatus() { updateStatus(""); } +void ClientApp::updateStatus() +{ + updateStatus(""); +} -void ClientApp::updateStatus(const String &msg) { +void ClientApp::updateStatus(const String &msg) +{ if (m_taskBarReceiver) { m_taskBarReceiver->updateStatus(m_client, msg); } } -void ClientApp::resetRestartTimeout() { +void ClientApp::resetRestartTimeout() +{ // retry time can nolonger be changed // s_retryTime = 0.0; } -double ClientApp::nextRestartTimeout() { +double ClientApp::nextRestartTimeout() +{ // retry at a constant rate (Issue 52) return RETRY_TIME; @@ -251,29 +262,33 @@ double ClientApp::nextRestartTimeout() { */ } -void ClientApp::handleScreenError(const Event &, void *) { +void ClientApp::handleScreenError(const Event &, void *) +{ LOG((CLOG_CRIT "error on screen")); m_events->addEvent(Event(Event::kQuit)); } -deskflow::Screen *ClientApp::openClientScreen() { +deskflow::Screen *ClientApp::openClientScreen() +{ deskflow::Screen *screen = createScreen(); screen->setEnableDragDrop(argsBase().m_enableDragDrop); m_events->adoptHandler( m_events->forIScreen().error(), screen->getEventTarget(), - new TMethodEventJob(this, &ClientApp::handleScreenError)); + new TMethodEventJob(this, &ClientApp::handleScreenError) + ); return screen; } -void ClientApp::closeClientScreen(deskflow::Screen *screen) { +void ClientApp::closeClientScreen(deskflow::Screen *screen) +{ if (screen != NULL) { - m_events->removeHandler( - m_events->forIScreen().error(), screen->getEventTarget()); + m_events->removeHandler(m_events->forIScreen().error(), screen->getEventTarget()); delete screen; } } -void ClientApp::handleClientRestart(const Event &, void *vtimer) { +void ClientApp::handleClientRestart(const Event &, void *vtimer) +{ // discard old timer EventQueueTimer *timer = static_cast(vtimer); m_events->deleteTimer(timer); @@ -283,34 +298,30 @@ void ClientApp::handleClientRestart(const Event &, void *vtimer) { startClient(); } -void ClientApp::scheduleClientRestart(double retryTime) { +void ClientApp::scheduleClientRestart(double retryTime) +{ // install a timer and handler to retry later LOG((CLOG_DEBUG "retry in %.0f seconds", retryTime)); EventQueueTimer *timer = m_events->newOneShotTimer(retryTime, NULL); m_events->adoptHandler( - Event::kTimer, timer, - new TMethodEventJob( - this, &ClientApp::handleClientRestart, timer)); + Event::kTimer, timer, new TMethodEventJob(this, &ClientApp::handleClientRestart, timer) + ); } -void ClientApp::handleClientConnected(const Event &, void *) { +void ClientApp::handleClientConnected(const Event &, void *) +{ LOG((CLOG_NOTE "connected to server")); resetRestartTimeout(); updateStatus(); } -void ClientApp::handleClientFailed(const Event &e, void *) { - if ((++m_lastServerAddressIndex) < - m_client->getLastResolvedAddressesCount()) { - std::unique_ptr info( - static_cast(e.getData())); +void ClientApp::handleClientFailed(const Event &e, void *) +{ + if ((++m_lastServerAddressIndex) < m_client->getLastResolvedAddressesCount()) { + std::unique_ptr info(static_cast(e.getData())); - updateStatus( - String("Failed to connect to server: ") + info->m_what + - " Trying next address..."); - LOG( - (CLOG_NOTE "failed to connect to server=%s, trying next address", - info->m_what.c_str())); + updateStatus(String("Failed to connect to server: ") + info->m_what + " Trying next address..."); + LOG((CLOG_NOTE "failed to connect to server=%s, trying next address", info->m_what.c_str())); if (!m_suspended) { scheduleClientRestart(nextRestartTimeout()); } @@ -320,9 +331,9 @@ void ClientApp::handleClientFailed(const Event &e, void *) { } } -void ClientApp::handleClientRefused(const Event &e, void *) { - std::unique_ptr info( - static_cast(e.getData())); +void ClientApp::handleClientRefused(const Event &e, void *) +{ + std::unique_ptr info(static_cast(e.getData())); updateStatus(String("Failed to connect to server: ") + info->m_what); if (!args().m_restartable || !info->m_retry) { @@ -336,7 +347,8 @@ void ClientApp::handleClientRefused(const Event &e, void *) { } } -void ClientApp::handleClientDisconnected(const Event &, void *) { +void ClientApp::handleClientDisconnected(const Event &, void *) +{ LOG((CLOG_NOTE "disconnected from server")); if (!args().m_restartable) { m_events->addEvent(Event(Event::kQuit)); @@ -346,30 +358,30 @@ void ClientApp::handleClientDisconnected(const Event &, void *) { updateStatus(); } -Client *ClientApp::openClient( - const String &name, const NetworkAddress &address, - deskflow::Screen *screen) { - Client *client = - new Client(m_events, name, address, getSocketFactory(), screen, args()); +Client *ClientApp::openClient(const String &name, const NetworkAddress &address, deskflow::Screen *screen) +{ + Client *client = new Client(m_events, name, address, getSocketFactory(), screen, args()); try { m_events->adoptHandler( m_events->forClient().connected(), client->getEventTarget(), - new TMethodEventJob( - this, &ClientApp::handleClientConnected)); + new TMethodEventJob(this, &ClientApp::handleClientConnected) + ); m_events->adoptHandler( m_events->forClient().connectionFailed(), client->getEventTarget(), - new TMethodEventJob(this, &ClientApp::handleClientFailed)); + new TMethodEventJob(this, &ClientApp::handleClientFailed) + ); m_events->adoptHandler( m_events->forClient().connectionRefused(), client->getEventTarget(), - new TMethodEventJob(this, &ClientApp::handleClientRefused)); + new TMethodEventJob(this, &ClientApp::handleClientRefused) + ); m_events->adoptHandler( m_events->forClient().disconnected(), client->getEventTarget(), - new TMethodEventJob( - this, &ClientApp::handleClientDisconnected)); + new TMethodEventJob(this, &ClientApp::handleClientDisconnected) + ); } catch (std::bad_alloc &ba) { delete client; @@ -379,7 +391,8 @@ Client *ClientApp::openClient( return client; } -void ClientApp::closeClient(Client *client) { +void ClientApp::closeClient(Client *client) +{ if (client == NULL) { return; } @@ -391,14 +404,16 @@ void ClientApp::closeClient(Client *client) { delete client; } -int ClientApp::foregroundStartup(int argc, char **argv) { +int ClientApp::foregroundStartup(int argc, char **argv) +{ initApp(argc, argv); // never daemonize return mainLoop(); } -bool ClientApp::startClient() { +bool ClientApp::startClient() +{ double retryTime; deskflow::Screen *clientScreen = NULL; try { @@ -437,14 +452,16 @@ bool ClientApp::startClient() { } } -void ClientApp::stopClient() { +void ClientApp::stopClient() +{ closeClient(m_client); closeClientScreen(m_clientScreen); m_client = NULL; m_clientScreen = NULL; } -int ClientApp::mainLoop() { +int ClientApp::mainLoop() +{ // create socket multiplexer. this must happen after daemonization // on unix because threads evaporate across a fork(). SocketMultiplexer multiplexer; @@ -466,12 +483,10 @@ int ClientApp::mainLoop() { #if defined(MAC_OS_X_VERSION_10_7) - Thread thread( - new TMethodJob(this, &ClientApp::runEventsLoop, NULL)); + Thread thread(new TMethodJob(this, &ClientApp::runEventsLoop, NULL)); // wait until carbon loop is ready - OSXScreen *screen = - dynamic_cast(m_clientScreen->getPlatformScreen()); + OSXScreen *screen = dynamic_cast(m_clientScreen->getPlatformScreen()); screen->waitForCarbonLoop(); runCocoaApp(); @@ -494,11 +509,13 @@ int ClientApp::mainLoop() { return kExitSuccess; } -static int daemonMainLoopStatic(int argc, const char **argv) { +static int daemonMainLoopStatic(int argc, const char **argv) +{ return ClientApp::instance().daemonMainLoop(argc, argv); } -int ClientApp::standardStartup(int argc, char **argv) { +int ClientApp::standardStartup(int argc, char **argv) +{ initApp(argc, argv); // daemonize if requested @@ -509,8 +526,8 @@ int ClientApp::standardStartup(int argc, char **argv) { } } -int ClientApp::runInner( - int argc, char **argv, ILogOutputter *outputter, StartupFunc startup) { +int ClientApp::runInner(int argc, char **argv, ILogOutputter *outputter, StartupFunc startup) +{ // general initialization m_serverAddress = new NetworkAddress; args().m_pname = ARCH->getBasename(argv[0]); @@ -538,7 +555,8 @@ int ClientApp::runInner( return result; } -void ClientApp::startNode() { +void ClientApp::startNode() +{ // start the client. if this return false then we've failed and // we shouldn't retry. LOG((CLOG_DEBUG1 "starting client")); @@ -547,7 +565,8 @@ void ClientApp::startNode() { } } -ISocketFactory *ClientApp::getSocketFactory() const { +ISocketFactory *ClientApp::getSocketFactory() const +{ ISocketFactory *socketFactory = nullptr; if (args().m_hostMode) { diff --git a/src/lib/deskflow/ClientApp.h b/src/lib/deskflow/ClientApp.h index a6ffbe222..2d9cb0e48 100644 --- a/src/lib/deskflow/ClientApp.h +++ b/src/lib/deskflow/ClientApp.h @@ -33,10 +33,10 @@ namespace deskflow { class ClientArgs; } -class ClientApp : public App { +class ClientApp : public App +{ public: - ClientApp( - IEventQueue *events, CreateTaskBarReceiverFunc createTaskBarReceiver); + ClientApp(IEventQueue *events, CreateTaskBarReceiverFunc createTaskBarReceiver); virtual ~ClientApp(); // @@ -47,13 +47,16 @@ public: void help() override; const char *daemonName() const override; const char *daemonInfo() const override; - void loadConfig() override {} - bool loadConfig(const String &pathname) override { return false; } + void loadConfig() override + { + } + bool loadConfig(const String &pathname) override + { + return false; + } int foregroundStartup(int argc, char **argv) override; int standardStartup(int argc, char **argv) override; - int runInner( - int argc, char **argv, ILogOutputter *outputter, - StartupFunc startup) override; + int runInner(int argc, char **argv, ILogOutputter *outputter, StartupFunc startup) override; deskflow::Screen *createScreen() override; int mainLoop() override; void startNode() override; @@ -62,7 +65,10 @@ public: // App overrides // - std::string configSection() const override { return "client"; } + std::string configSection() const override + { + return "client"; + } // // Regular functions @@ -81,15 +87,17 @@ public: void handleClientFailed(const Event &e, void *); void handleClientRefused(const Event &e, void *); void handleClientDisconnected(const Event &, void *); - Client *openClient( - const String &name, const NetworkAddress &address, - deskflow::Screen *screen); + Client *openClient(const String &name, const NetworkAddress &address, deskflow::Screen *screen); void closeClient(Client *client); bool startClient(); void stopClient(); - Client *getClientPtr() { return m_client; } + Client *getClientPtr() + { + return m_client; + } - deskflow::ClientArgs &args() const { + deskflow::ClientArgs &args() const + { return (deskflow::ClientArgs &)argsBase(); } @@ -97,7 +105,10 @@ public: // Static functions // - static ClientApp &instance() { return (ClientApp &)App::instance(); } + static ClientApp &instance() + { + return (ClientApp &)App::instance(); + } private: ISocketFactory *getSocketFactory() const; diff --git a/src/lib/deskflow/ClientArgs.cpp b/src/lib/deskflow/ClientArgs.cpp index cd33744a8..2a868a4f6 100644 --- a/src/lib/deskflow/ClientArgs.cpp +++ b/src/lib/deskflow/ClientArgs.cpp @@ -19,7 +19,12 @@ namespace deskflow { -ClientArgs::~ClientArgs() {} +ClientArgs::~ClientArgs() +{ +} -ClientArgs::ClientArgs() { m_classType = kClient; } +ClientArgs::ClientArgs() +{ + m_classType = kClient; +} } // namespace deskflow diff --git a/src/lib/deskflow/ClientArgs.h b/src/lib/deskflow/ClientArgs.h index 55ec465c2..6a329e9bd 100644 --- a/src/lib/deskflow/ClientArgs.h +++ b/src/lib/deskflow/ClientArgs.h @@ -20,9 +20,14 @@ #include "ArgsBase.h" namespace deskflow { -enum ClientScrollDirection { SERVER = 1, INVERT_SERVER = -1 }; +enum ClientScrollDirection +{ + SERVER = 1, + INVERT_SERVER = -1 +}; -class ClientArgs : public ArgsBase { +class ClientArgs : public ArgsBase +{ /// Public functions public: @@ -32,8 +37,7 @@ public: public: int m_yscroll = 0; - bool m_enableLangSync = - false; /// @brief Should keyboard input be in same language as on server + bool m_enableLangSync = false; /// @brief Should keyboard input be in same language as on server /** * @brief m_clientScrollDirection diff --git a/src/lib/deskflow/ClientTaskBarReceiver.cpp b/src/lib/deskflow/ClientTaskBarReceiver.cpp index d11f6e023..83a8346be 100644 --- a/src/lib/deskflow/ClientTaskBarReceiver.cpp +++ b/src/lib/deskflow/ClientTaskBarReceiver.cpp @@ -28,18 +28,18 @@ // ClientTaskBarReceiver // -ClientTaskBarReceiver::ClientTaskBarReceiver(IEventQueue *events) - : m_state(kNotRunning), - m_events(events) { +ClientTaskBarReceiver::ClientTaskBarReceiver(IEventQueue *events) : m_state(kNotRunning), m_events(events) +{ // do nothing } -ClientTaskBarReceiver::~ClientTaskBarReceiver() { +ClientTaskBarReceiver::~ClientTaskBarReceiver() +{ // do nothing } -void ClientTaskBarReceiver::updateStatus( - Client *client, const String &errorMsg) { +void ClientTaskBarReceiver::updateStatus(Client *client, const String &errorMsg) +{ { // update our status m_errorMessage = errorMsg; @@ -69,48 +69,53 @@ void ClientTaskBarReceiver::updateStatus( ARCH->updateReceiver(this); } -ClientTaskBarReceiver::EState ClientTaskBarReceiver::getStatus() const { +ClientTaskBarReceiver::EState ClientTaskBarReceiver::getStatus() const +{ return m_state; } -const String &ClientTaskBarReceiver::getErrorMessage() const { +const String &ClientTaskBarReceiver::getErrorMessage() const +{ return m_errorMessage; } -void ClientTaskBarReceiver::quit() { m_events->addEvent(Event(Event::kQuit)); } +void ClientTaskBarReceiver::quit() +{ + m_events->addEvent(Event(Event::kQuit)); +} -void ClientTaskBarReceiver::onStatusChanged(Client *) { +void ClientTaskBarReceiver::onStatusChanged(Client *) +{ // do nothing } -void ClientTaskBarReceiver::lock() const { +void ClientTaskBarReceiver::lock() const +{ // do nothing } -void ClientTaskBarReceiver::unlock() const { +void ClientTaskBarReceiver::unlock() const +{ // do nothing } -std::string ClientTaskBarReceiver::getToolTip() const { +std::string ClientTaskBarReceiver::getToolTip() const +{ switch (m_state) { case kNotRunning: return deskflow::string::sprintf("%s: Not running", kAppName); case kNotWorking: - return deskflow::string::sprintf( - "%s: %s", kAppName, m_errorMessage.c_str()); + return deskflow::string::sprintf("%s: %s", kAppName, m_errorMessage.c_str()); case kNotConnected: - return deskflow::string::sprintf( - "%s: Not connected: %s", kAppName, m_errorMessage.c_str()); + return deskflow::string::sprintf("%s: Not connected: %s", kAppName, m_errorMessage.c_str()); case kConnecting: - return deskflow::string::sprintf( - "%s: Connecting to %s...", kAppName, m_server.c_str()); + return deskflow::string::sprintf("%s: Connecting to %s...", kAppName, m_server.c_str()); case kConnected: - return deskflow::string::sprintf( - "%s: Connected to %s", kAppName, m_server.c_str()); + return deskflow::string::sprintf("%s: Connected to %s", kAppName, m_server.c_str()); default: return ""; diff --git a/src/lib/deskflow/ClientTaskBarReceiver.h b/src/lib/deskflow/ClientTaskBarReceiver.h index fb5277ea0..afaa7107c 100644 --- a/src/lib/deskflow/ClientTaskBarReceiver.h +++ b/src/lib/deskflow/ClientTaskBarReceiver.h @@ -26,7 +26,8 @@ class IEventQueue; //! Implementation of IArchTaskBarReceiver for the deskflow server -class ClientTaskBarReceiver : public IArchTaskBarReceiver { +class ClientTaskBarReceiver : public IArchTaskBarReceiver +{ public: ClientTaskBarReceiver(IEventQueue *events); virtual ~ClientTaskBarReceiver(); @@ -40,7 +41,8 @@ public: */ void updateStatus(Client *, const String &errorMsg); - void updateStatus(INode *n, const String &errorMsg) { + void updateStatus(INode *n, const String &errorMsg) + { updateStatus((Client *)n, errorMsg); } @@ -54,10 +56,13 @@ public: virtual void unlock() const; virtual const Icon getIcon() const = 0; virtual std::string getToolTip() const; - virtual void cleanup() {} + virtual void cleanup() + { + } protected: - enum EState { + enum EState + { kNotRunning, kNotWorking, kNotConnected, @@ -91,5 +96,4 @@ private: IEventQueue *m_events; }; -IArchTaskBarReceiver *createTaskBarReceiver( - const BufferedLogOutputter *logBuffer, IEventQueue *events); +IArchTaskBarReceiver *createTaskBarReceiver(const BufferedLogOutputter *logBuffer, IEventQueue *events); diff --git a/src/lib/deskflow/Clipboard.cpp b/src/lib/deskflow/Clipboard.cpp index 344570e3e..859764997 100644 --- a/src/lib/deskflow/Clipboard.cpp +++ b/src/lib/deskflow/Clipboard.cpp @@ -22,17 +22,20 @@ // Clipboard // -Clipboard::Clipboard() : m_open(false), m_owner(false) { +Clipboard::Clipboard() : m_open(false), m_owner(false) +{ open(0); empty(); close(); } -Clipboard::~Clipboard() { +Clipboard::~Clipboard() +{ // do nothing } -bool Clipboard::empty() { +bool Clipboard::empty() +{ assert(m_open); // clear all data @@ -50,7 +53,8 @@ bool Clipboard::empty() { return true; } -void Clipboard::add(EFormat format, const String &data) { +void Clipboard::add(EFormat format, const String &data) +{ assert(m_open); assert(m_owner); @@ -58,7 +62,8 @@ void Clipboard::add(EFormat format, const String &data) { m_added[format] = true; } -bool Clipboard::open(Time time) const { +bool Clipboard::open(Time time) const +{ assert(!m_open); m_open = true; @@ -67,26 +72,36 @@ bool Clipboard::open(Time time) const { return true; } -void Clipboard::close() const { +void Clipboard::close() const +{ assert(m_open); m_open = false; } -Clipboard::Time Clipboard::getTime() const { return m_timeOwned; } +Clipboard::Time Clipboard::getTime() const +{ + return m_timeOwned; +} -bool Clipboard::has(EFormat format) const { +bool Clipboard::has(EFormat format) const +{ assert(m_open); return m_added[format]; } -String Clipboard::get(EFormat format) const { +String Clipboard::get(EFormat format) const +{ assert(m_open); return m_data[format]; } -void Clipboard::unmarshall(const String &data, Time time) { +void Clipboard::unmarshall(const String &data, Time time) +{ IClipboard::unmarshall(this, data, time); } -String Clipboard::marshall() const { return IClipboard::marshall(this); } +String Clipboard::marshall() const +{ + return IClipboard::marshall(this); +} diff --git a/src/lib/deskflow/Clipboard.h b/src/lib/deskflow/Clipboard.h index 2cd6db676..8d9436fb2 100644 --- a/src/lib/deskflow/Clipboard.h +++ b/src/lib/deskflow/Clipboard.h @@ -24,7 +24,8 @@ /*! This class implements a clipboard that stores data in memory. */ -class Clipboard : public IClipboard { +class Clipboard : public IClipboard +{ public: Clipboard(); virtual ~Clipboard(); diff --git a/src/lib/deskflow/ClipboardChunk.cpp b/src/lib/deskflow/ClipboardChunk.cpp index a46d70044..b5962638e 100644 --- a/src/lib/deskflow/ClipboardChunk.cpp +++ b/src/lib/deskflow/ClipboardChunk.cpp @@ -25,15 +25,15 @@ size_t ClipboardChunk::s_expectedSize = 0; -ClipboardChunk::ClipboardChunk(size_t size) : Chunk(size) { +ClipboardChunk::ClipboardChunk(size_t size) : Chunk(size) +{ m_dataSize = size - CLIPBOARD_CHUNK_META_SIZE; } -ClipboardChunk * -ClipboardChunk::start(ClipboardID id, UInt32 sequence, const String &size) { +ClipboardChunk *ClipboardChunk::start(ClipboardID id, UInt32 sequence, const String &size) +{ size_t sizeLength = size.size(); - ClipboardChunk *start = - new ClipboardChunk(sizeLength + CLIPBOARD_CHUNK_META_SIZE); + ClipboardChunk *start = new ClipboardChunk(sizeLength + CLIPBOARD_CHUNK_META_SIZE); char *chunk = start->m_chunk; chunk[0] = id; @@ -45,11 +45,10 @@ ClipboardChunk::start(ClipboardID id, UInt32 sequence, const String &size) { return start; } -ClipboardChunk * -ClipboardChunk::data(ClipboardID id, UInt32 sequence, const String &data) { +ClipboardChunk *ClipboardChunk::data(ClipboardID id, UInt32 sequence, const String &data) +{ size_t dataSize = data.size(); - ClipboardChunk *chunk = - new ClipboardChunk(dataSize + CLIPBOARD_CHUNK_META_SIZE); + ClipboardChunk *chunk = new ClipboardChunk(dataSize + CLIPBOARD_CHUNK_META_SIZE); char *chunkData = chunk->m_chunk; chunkData[0] = id; @@ -61,7 +60,8 @@ ClipboardChunk::data(ClipboardID id, UInt32 sequence, const String &data) { return chunk; } -ClipboardChunk *ClipboardChunk::end(ClipboardID id, UInt32 sequence) { +ClipboardChunk *ClipboardChunk::end(ClipboardID id, UInt32 sequence) +{ ClipboardChunk *end = new ClipboardChunk(CLIPBOARD_CHUNK_META_SIZE); char *chunk = end->m_chunk; @@ -73,14 +73,12 @@ ClipboardChunk *ClipboardChunk::end(ClipboardID id, UInt32 sequence) { return end; } -int ClipboardChunk::assemble( - deskflow::IStream *stream, String &dataCached, ClipboardID &id, - UInt32 &sequence) { +int ClipboardChunk::assemble(deskflow::IStream *stream, String &dataCached, ClipboardID &id, UInt32 &sequence) +{ UInt8 mark; String data; - if (!ProtocolUtil::readf( - stream, kMsgDClipboard + 4, &id, &sequence, &mark, &data)) { + if (!ProtocolUtil::readf(stream, kMsgDClipboard + 4, &id, &sequence, &mark, &data)) { return kError; } @@ -97,9 +95,7 @@ int ClipboardChunk::assemble( if (id >= kClipboardEnd) { return kError; } else 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 kFinish; @@ -109,7 +105,8 @@ int ClipboardChunk::assemble( return kError; } -void ClipboardChunk::send(deskflow::IStream *stream, void *data) { +void ClipboardChunk::send(deskflow::IStream *stream, void *data) +{ ClipboardChunk *clipboardData = static_cast(data); LOG((CLOG_DEBUG1 "sending clipboard chunk")); @@ -123,14 +120,11 @@ void ClipboardChunk::send(deskflow::IStream *stream, void *data) { switch (mark) { case kDataStart: - LOG( - (CLOG_DEBUG2 "sending clipboard chunk start: size=%s", - dataChunk.c_str())); + LOG((CLOG_DEBUG2 "sending clipboard chunk start: size=%s", dataChunk.c_str())); break; case kDataChunk: - LOG(( - CLOG_DEBUG2 "sending clipboard chunk data: size=%i", dataChunk.size())); + LOG((CLOG_DEBUG2 "sending clipboard chunk data: size=%i", dataChunk.size())); break; case kDataEnd: diff --git a/src/lib/deskflow/ClipboardChunk.h b/src/lib/deskflow/ClipboardChunk.h index 28932e4e6..61594cbef 100644 --- a/src/lib/deskflow/ClipboardChunk.h +++ b/src/lib/deskflow/ClipboardChunk.h @@ -28,23 +28,23 @@ namespace deskflow { class IStream; }; -class ClipboardChunk : public Chunk { +class ClipboardChunk : public Chunk +{ public: ClipboardChunk(size_t size); - static ClipboardChunk * - start(ClipboardID id, UInt32 sequence, const String &size); - static ClipboardChunk * - data(ClipboardID id, UInt32 sequence, const String &data); + static ClipboardChunk *start(ClipboardID id, UInt32 sequence, const String &size); + static ClipboardChunk *data(ClipboardID id, UInt32 sequence, const String &data); static ClipboardChunk *end(ClipboardID id, UInt32 sequence); - static int assemble( - deskflow::IStream *stream, String &dataCached, ClipboardID &id, - UInt32 &sequence); + static int assemble(deskflow::IStream *stream, String &dataCached, ClipboardID &id, UInt32 &sequence); static void send(deskflow::IStream *stream, void *data); - static size_t getExpectedSize() { return s_expectedSize; } + static size_t getExpectedSize() + { + return s_expectedSize; + } private: static size_t s_expectedSize; diff --git a/src/lib/deskflow/Config.cpp b/src/lib/deskflow/Config.cpp index 990499b30..76036f860 100644 --- a/src/lib/deskflow/Config.cpp +++ b/src/lib/deskflow/Config.cpp @@ -30,15 +30,22 @@ namespace deskflow { -Config::Config(const std::string &filename, const std::string §ion) - : m_filename(filename), - m_section(section) {} +Config::Config(const std::string &filename, const std::string §ion) : m_filename(filename), m_section(section) +{ +} -const char *const *Config::argv() const { return m_argv.data(); } +const char *const *Config::argv() const +{ + return m_argv.data(); +} -int Config::argc() const { return static_cast(m_argv.size()); } +int Config::argc() const +{ + return static_cast(m_argv.size()); +} -bool Config::load(const std::string &firstArg) { +bool Config::load(const std::string &firstArg) +{ #if HAVE_TOMLPLUSPLUS if (!firstArg.empty()) { diff --git a/src/lib/deskflow/Config.h b/src/lib/deskflow/Config.h index e46501d69..2f316c9a2 100644 --- a/src/lib/deskflow/Config.h +++ b/src/lib/deskflow/Config.h @@ -31,17 +31,23 @@ configuration options in future. The configuration file is in TOML format. Initially this class was created to as a developer convenience; it is a convenient place to specify args without needing to fiddle with IDE configs. */ -class Config { +class Config +{ public: - class ParseError : public std::runtime_error { + class ParseError : public std::runtime_error + { public: - explicit ParseError() : std::runtime_error("failed to parse config file") {} + explicit ParseError() : std::runtime_error("failed to parse config file") + { + } }; - class NoConfigFilenameError : public std::runtime_error { + class NoConfigFilenameError : public std::runtime_error + { public: - explicit NoConfigFilenameError() - : std::runtime_error("no config file specified") {} + explicit NoConfigFilenameError() : std::runtime_error("no config file specified") + { + } }; explicit Config(const std::string &filename, const std::string §ion); diff --git a/src/lib/deskflow/DaemonApp.cpp b/src/lib/deskflow/DaemonApp.cpp index 730fa87ac..d9af19f96 100644 --- a/src/lib/deskflow/DaemonApp.cpp +++ b/src/lib/deskflow/DaemonApp.cpp @@ -62,7 +62,8 @@ using namespace std; const char *const kLogFilename = DAEMON_BINARY_NAME ".log"; namespace { -void updateSetting(const IpcMessage &message) { +void updateSetting(const IpcMessage &message) +{ try { auto setting = static_cast(message); ARCH->setting(setting.getName(), setting.getValue()); @@ -71,13 +72,13 @@ void updateSetting(const IpcMessage &message) { } } -bool isServerCommandLine(const std::vector &cmd) { +bool isServerCommandLine(const std::vector &cmd) +{ auto isServer = false; if (cmd.size() > 1) { - isServer = - (cmd[0].find(SERVER_BINARY_NAME) != String::npos) || - (cmd[0].find(CORE_BINARY_NAME) != String::npos && cmd[1] == "server"); + isServer = (cmd[0].find(SERVER_BINARY_NAME) != String::npos) || + (cmd[0].find(CORE_BINARY_NAME) != String::npos && cmd[1] == "server"); } return isServer; @@ -87,24 +88,36 @@ bool isServerCommandLine(const std::vector &cmd) { DaemonApp *DaemonApp::s_instance = nullptr; -int mainLoopStatic() { +int mainLoopStatic() +{ DaemonApp::s_instance->mainLoop(true); return kExitSuccess; } -int unixMainLoopStatic(int, const char **) { return mainLoopStatic(); } +int unixMainLoopStatic(int, const char **) +{ + return mainLoopStatic(); +} #if SYSAPI_WIN32 -int winMainLoopStatic(int, const char **) { +int winMainLoopStatic(int, const char **) +{ return ArchMiscWindows::runDaemon(mainLoopStatic); } #endif -DaemonApp::DaemonApp() { s_instance = this; } +DaemonApp::DaemonApp() +{ + s_instance = this; +} -DaemonApp::~DaemonApp() { s_instance = nullptr; } +DaemonApp::~DaemonApp() +{ + s_instance = nullptr; +} -int DaemonApp::run(int argc, char **argv) { +int DaemonApp::run(int argc, char **argv) +{ #if SYSAPI_WIN32 // win32 instance needed for threading, etc. ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL)); @@ -175,8 +188,7 @@ int DaemonApp::run(int argc, char **argv) { return kExitSuccess; } catch (XArch &e) { 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?!). // HACK: this message happens intermittently, not sure where from but // it's quite misleading for the user. they thing something has gone @@ -195,13 +207,13 @@ int DaemonApp::run(int argc, char **argv) { } } -void DaemonApp::mainLoop(bool logToFile, bool foreground) { +void DaemonApp::mainLoop(bool logToFile, bool foreground) +{ try { DAEMON_RUNNING(true); if (logToFile) { - m_fileLogOutputter = - std::make_unique(logFilename().c_str()); + m_fileLogOutputter = std::make_unique(logFilename().c_str()); CLOG->insert(m_fileLogOutputter.get()); } @@ -213,19 +225,18 @@ void DaemonApp::mainLoop(bool logToFile, bool foreground) { m_ipcServer = std::make_unique(m_events.get(), &multiplexer); // send logging to gui via ipc, log system adopts outputter. - m_ipcLogOutputter = std::make_unique( - *m_ipcServer, IpcClientType::GUI, true); + m_ipcLogOutputter = std::make_unique(*m_ipcServer, IpcClientType::GUI, true); CLOG->insert(m_ipcLogOutputter.get()); #if SYSAPI_WIN32 - m_watchdog = std::make_unique( - false, *m_ipcServer, *m_ipcLogOutputter, foreground); + m_watchdog = std::make_unique(false, *m_ipcServer, *m_ipcLogOutputter, foreground); m_watchdog->setFileLogOutputter(m_fileLogOutputter.get()); #endif m_events->adoptHandler( m_events->forIpcServer().messageReceived(), m_ipcServer.get(), - new TMethodEventJob(this, &DaemonApp::handleIpcMessage)); + new TMethodEventJob(this, &DaemonApp::handleIpcMessage) + ); m_ipcServer->listen(); @@ -249,8 +260,7 @@ void DaemonApp::mainLoop(bool logToFile, bool foreground) { m_watchdog->stop(); #endif - m_events->removeHandler( - m_events->forIpcServer().messageReceived(), m_ipcServer.get()); + m_events->removeHandler(m_events->forIpcServer().messageReceived(), m_ipcServer.get()); CLOG->remove(m_ipcLogOutputter.get()); @@ -262,7 +272,8 @@ void DaemonApp::mainLoop(bool logToFile, bool foreground) { } } -void DaemonApp::foregroundError(const char *message) { +void DaemonApp::foregroundError(const char *message) +{ #if SYSAPI_WIN32 MessageBox(NULL, message, "Deskflow Service", MB_OK | MB_ICONERROR); #elif SYSAPI_UNIX @@ -270,7 +281,8 @@ void DaemonApp::foregroundError(const char *message) { #endif } -std::string DaemonApp::logFilename() { +std::string DaemonApp::logFilename() +{ string logFilename; logFilename = ARCH->setting("LogFilename"); if (logFilename.empty()) { @@ -282,7 +294,8 @@ std::string DaemonApp::logFilename() { return logFilename; } -void DaemonApp::handleIpcMessage(const Event &e, void *) { +void DaemonApp::handleIpcMessage(const Event &e, void *) +{ IpcMessage *m = static_cast(e.getDataObject()); switch (m->type()) { case IpcMessageType::Command: { @@ -296,9 +309,7 @@ void DaemonApp::handleIpcMessage(const Event &e, void *) { if (!command.empty()) { LOG((CLOG_DEBUG "daemon got new core command")); - LOG( - (CLOG_DEBUG2 "new command, elevate=%d command=%s", cm->elevate(), - command.c_str())); + LOG((CLOG_DEBUG2 "new command, elevate=%d command=%s", cm->elevate(), command.c_str())); std::vector argsArray; ArgParser::splitCommandString(command, argsArray); diff --git a/src/lib/deskflow/DaemonApp.h b/src/lib/deskflow/DaemonApp.h index 3710290a7..e157cdc9d 100644 --- a/src/lib/deskflow/DaemonApp.h +++ b/src/lib/deskflow/DaemonApp.h @@ -32,7 +32,8 @@ class MSWindowsWatchdog; extern const char *const kLogFilename; -class DaemonApp { +class DaemonApp +{ public: DaemonApp(); diff --git a/src/lib/deskflow/DisplayInvalidException.h b/src/lib/deskflow/DisplayInvalidException.h index 7ae5ddc9a..4c8e275a2 100644 --- a/src/lib/deskflow/DisplayInvalidException.h +++ b/src/lib/deskflow/DisplayInvalidException.h @@ -20,9 +20,14 @@ #include #include -class DisplayInvalidException : public std::runtime_error { +class DisplayInvalidException : public std::runtime_error +{ public: - DisplayInvalidException(const char *msg) : std::runtime_error(msg) {} + DisplayInvalidException(const char *msg) : std::runtime_error(msg) + { + } - DisplayInvalidException(std::string msg) : std::runtime_error(msg) {} + DisplayInvalidException(std::string msg) : std::runtime_error(msg) + { + } }; diff --git a/src/lib/deskflow/DragInformation.cpp b/src/lib/deskflow/DragInformation.cpp index 0ab653846..98b169a01 100644 --- a/src/lib/deskflow/DragInformation.cpp +++ b/src/lib/deskflow/DragInformation.cpp @@ -24,10 +24,12 @@ using namespace std; -DragInformation::DragInformation() : m_filename(), m_filesize(0) {} +DragInformation::DragInformation() : m_filename(), m_filesize(0) +{ +} -void DragInformation::parseDragInfo( - DragFileList &dragFileList, UInt32 fileNum, String data) { +void DragInformation::parseDragInfo(DragFileList &dragFileList, UInt32 fileNum, String data) +{ size_t startPos = 0; size_t findResult1 = 0; size_t findResult2 = 0; @@ -49,8 +51,7 @@ void DragInformation::parseDragInfo( // set filename if (findResult1 - findResult2 > 1) { - String filename = - data.substr(findResult2 + 1, findResult1 - findResult2 - 1); + String filename = data.substr(findResult2 + 1, findResult1 - findResult2 - 1); DragInformation di; di.setFilename(filename); dragFileList.push_back(di); @@ -60,8 +61,7 @@ void DragInformation::parseDragInfo( // set filesize findResult2 = data.find(',', startPos); if (findResult2 - findResult1 > 1) { - String filesize = - data.substr(findResult1 + 1, findResult2 - findResult1 - 1); + String filesize = data.substr(findResult1 + 1, findResult2 - findResult1 - 1); size_t size = stringToNum(filesize); dragFileList.at(index).setFilesize(size); } @@ -70,18 +70,15 @@ void DragInformation::parseDragInfo( ++index; } - LOG( - (CLOG_DEBUG "drag info received, total drag file number: %i", - dragFileList.size())); + LOG((CLOG_DEBUG "drag info received, total drag file number: %i", dragFileList.size())); for (size_t i = 0; i < dragFileList.size(); ++i) { - LOG( - (CLOG_DEBUG "dragging file %i name: %s", i + 1, - dragFileList.at(i).getFilename().c_str())); + LOG((CLOG_DEBUG "dragging file %i name: %s", i + 1, dragFileList.at(i).getFilename().c_str())); } } -String DragInformation::getDragFileExtension(String filename) { +String DragInformation::getDragFileExtension(String filename) +{ size_t findResult = string::npos; findResult = filename.find_last_of(".", filename.size()); if (findResult != string::npos) { @@ -91,7 +88,8 @@ String DragInformation::getDragFileExtension(String filename) { } } -int DragInformation::setupDragInfo(DragFileList &fileList, String &output) { +int DragInformation::setupDragInfo(DragFileList &fileList, String &output) +{ int size = static_cast(fileList.size()); for (int i = 0; i < size; ++i) { output.append(fileList.at(i).getFilename()); @@ -103,7 +101,8 @@ int DragInformation::setupDragInfo(DragFileList &fileList, String &output) { return size; } -bool DragInformation::isFileValid(String filename) { +bool DragInformation::isFileValid(String filename) +{ bool result = false; std::fstream file(filename.c_str(), ios::in | ios::binary); @@ -116,14 +115,16 @@ bool DragInformation::isFileValid(String filename) { return result; } -size_t DragInformation::stringToNum(String &str) { +size_t DragInformation::stringToNum(String &str) +{ istringstream iss(str.c_str()); size_t size; iss >> size; return size; } -String DragInformation::getFileSize(String &filename) { +String DragInformation::getFileSize(String &filename) +{ std::fstream file(filename.c_str(), ios::in | ios::binary); if (!file.is_open()) { diff --git a/src/lib/deskflow/DragInformation.h b/src/lib/deskflow/DragInformation.h index bc33a2501..2d5caba6f 100644 --- a/src/lib/deskflow/DragInformation.h +++ b/src/lib/deskflow/DragInformation.h @@ -24,18 +24,32 @@ class DragInformation; typedef std::vector DragFileList; -class DragInformation { +class DragInformation +{ public: DragInformation(); - ~DragInformation() {} + ~DragInformation() + { + } - String &getFilename() { return m_filename; } - void setFilename(String &name) { m_filename = name; } - size_t getFilesize() { return m_filesize; } - void setFilesize(size_t size) { m_filesize = size; } + String &getFilename() + { + return m_filename; + } + void setFilename(String &name) + { + m_filename = name; + } + size_t getFilesize() + { + return m_filesize; + } + void setFilesize(size_t size) + { + m_filesize = size; + } - static void - parseDragInfo(DragFileList &dragFileList, UInt32 fileNum, String data); + static void parseDragInfo(DragFileList &dragFileList, UInt32 fileNum, String data); static String getDragFileExtension(String filename); // helper function to setup drag info // example: filename1,filesize1,filename2,filesize2, diff --git a/src/lib/deskflow/DropHelper.cpp b/src/lib/deskflow/DropHelper.cpp index a77db88fb..ee55ef421 100644 --- a/src/lib/deskflow/DropHelper.cpp +++ b/src/lib/deskflow/DropHelper.cpp @@ -21,11 +21,9 @@ #include -void DropHelper::writeToDir( - const String &destination, DragFileList &fileList, String &data) { - LOG( - (CLOG_DEBUG "dropping file, files=%i target=%s", fileList.size(), - destination.c_str())); +void DropHelper::writeToDir(const String &destination, DragFileList &fileList, String &data) +{ + LOG((CLOG_DEBUG "dropping file, files=%i target=%s", fileList.size(), destination.c_str())); if (!destination.empty() && fileList.size() > 0) { std::fstream file; @@ -44,9 +42,7 @@ void DropHelper::writeToDir( file.write(data.c_str(), data.size()); file.close(); - LOG( - (CLOG_DEBUG "%s is saved to %s", fileList.at(0).getFilename().c_str(), - destination.c_str())); + LOG((CLOG_DEBUG "%s is saved to %s", fileList.at(0).getFilename().c_str(), destination.c_str())); fileList.clear(); } else { diff --git a/src/lib/deskflow/DropHelper.h b/src/lib/deskflow/DropHelper.h index 71961ddfc..d6576036b 100644 --- a/src/lib/deskflow/DropHelper.h +++ b/src/lib/deskflow/DropHelper.h @@ -20,8 +20,8 @@ #include "base/String.h" #include "deskflow/DragInformation.h" -class DropHelper { +class DropHelper +{ public: - static void - writeToDir(const String &destination, DragFileList &fileList, String &data); + static void writeToDir(const String &destination, DragFileList &fileList, String &data); }; diff --git a/src/lib/deskflow/FileChunk.cpp b/src/lib/deskflow/FileChunk.cpp index 58d04306e..bcc2b2125 100644 --- a/src/lib/deskflow/FileChunk.cpp +++ b/src/lib/deskflow/FileChunk.cpp @@ -25,11 +25,13 @@ static const UInt16 kIntervalThreshold = 1; -FileChunk::FileChunk(size_t size) : Chunk(size) { +FileChunk::FileChunk(size_t size) : Chunk(size) +{ m_dataSize = size - FILE_CHUNK_META_SIZE; } -FileChunk *FileChunk::start(const String &size) { +FileChunk *FileChunk::start(const String &size) +{ size_t sizeLength = size.size(); FileChunk *start = new FileChunk(sizeLength + FILE_CHUNK_META_SIZE); char *chunk = start->m_chunk; @@ -40,7 +42,8 @@ FileChunk *FileChunk::start(const String &size) { return start; } -FileChunk *FileChunk::data(UInt8 *data, size_t dataSize) { +FileChunk *FileChunk::data(UInt8 *data, size_t dataSize) +{ FileChunk *chunk = new FileChunk(dataSize + FILE_CHUNK_META_SIZE); char *chunkData = chunk->m_chunk; chunkData[0] = kDataChunk; @@ -50,7 +53,8 @@ FileChunk *FileChunk::data(UInt8 *data, size_t dataSize) { return chunk; } -FileChunk *FileChunk::end() { +FileChunk *FileChunk::end() +{ FileChunk *end = new FileChunk(FILE_CHUNK_META_SIZE); char *chunk = end->m_chunk; chunk[0] = kDataEnd; @@ -59,8 +63,8 @@ FileChunk *FileChunk::end() { return end; } -int FileChunk::assemble( - deskflow::IStream *stream, String &dataReceived, size_t &expectedSize) { +int FileChunk::assemble(deskflow::IStream *stream, String &dataReceived, size_t &expectedSize) +{ // parse UInt8 mark = 0; String content; @@ -106,9 +110,7 @@ int FileChunk::assemble( case kDataEnd: if (expectedSize != dataReceived.size()) { - LOG( - (CLOG_ERR "corrupted clipboard data, expected size=%d actual size=%d", - expectedSize, dataReceived.size())); + LOG((CLOG_ERR "corrupted clipboard data, expected size=%d actual size=%d", expectedSize, dataReceived.size())); return kError; } @@ -116,15 +118,9 @@ int FileChunk::assemble( LOG((CLOG_DEBUG2 "file transfer finished")); elapsedTime += stopwatch.getTime(); double averageSpeed = expectedSize / elapsedTime / 1000; - LOG( - (CLOG_DEBUG2 "file transfer finished: total time consumed=%f s", - elapsedTime)); - LOG( - (CLOG_DEBUG2 "file transfer finished: total data received=%i kb", - expectedSize / 1000)); - LOG( - (CLOG_DEBUG2 "file transfer finished: total average speed=%f kb/s", - averageSpeed)); + LOG((CLOG_DEBUG2 "file transfer finished: total time consumed=%f s", elapsedTime)); + LOG((CLOG_DEBUG2 "file transfer finished: total data received=%i kb", expectedSize / 1000)); + LOG((CLOG_DEBUG2 "file transfer finished: total average speed=%f kb/s", averageSpeed)); } return kFinish; } @@ -132,8 +128,8 @@ int FileChunk::assemble( return kError; } -void FileChunk::send( - deskflow::IStream *stream, UInt8 mark, char *data, size_t dataSize) { +void FileChunk::send(deskflow::IStream *stream, UInt8 mark, char *data, size_t dataSize) +{ String chunk(data, dataSize); switch (mark) { diff --git a/src/lib/deskflow/FileChunk.h b/src/lib/deskflow/FileChunk.h index 668221abc..38159445c 100644 --- a/src/lib/deskflow/FileChunk.h +++ b/src/lib/deskflow/FileChunk.h @@ -27,15 +27,14 @@ namespace deskflow { class IStream; }; -class FileChunk : public Chunk { +class FileChunk : public Chunk +{ public: FileChunk(size_t size); static FileChunk *start(const String &size); static FileChunk *data(UInt8 *data, size_t dataSize); static FileChunk *end(); - static int - assemble(deskflow::IStream *stream, String &dataCached, size_t &expectedSize); - static void - send(deskflow::IStream *stream, UInt8 mark, char *data, size_t dataSize); + static int assemble(deskflow::IStream *stream, String &dataCached, size_t &expectedSize); + static void send(deskflow::IStream *stream, UInt8 mark, char *data, size_t dataSize); }; diff --git a/src/lib/deskflow/IApp.h b/src/lib/deskflow/IApp.h index 6f63a8f9a..802d56178 100644 --- a/src/lib/deskflow/IApp.h +++ b/src/lib/deskflow/IApp.h @@ -33,13 +33,13 @@ class Screen; } class IEventQueue; -class IApp : public IInterface { +class IApp : public IInterface +{ public: virtual void setByeFunc(void (*bye)(int)) = 0; virtual deskflow::ArgsBase &argsBase() const = 0; virtual int standardStartup(int argc, char **argv) = 0; - virtual int runInner( - int argc, char **argv, ILogOutputter *outputter, StartupFunc startup) = 0; + virtual int runInner(int argc, char **argv, ILogOutputter *outputter, StartupFunc startup) = 0; virtual void startNode() = 0; virtual IArchTaskBarReceiver *taskBarReceiver() const = 0; virtual void bye(int error) = 0; diff --git a/src/lib/deskflow/IAppUtil.h b/src/lib/deskflow/IAppUtil.h index c607ecf9f..32236a4e5 100644 --- a/src/lib/deskflow/IAppUtil.h +++ b/src/lib/deskflow/IAppUtil.h @@ -22,7 +22,8 @@ #include "common/IInterface.h" #include "deskflow/IApp.h" -class IAppUtil : public IInterface { +class IAppUtil : public IInterface +{ public: virtual void adoptApp(IApp *app) = 0; virtual IApp &app() const = 0; @@ -31,6 +32,5 @@ public: virtual void startNode() = 0; virtual std::vector getKeyboardLayoutList() = 0; virtual String getCurrentLanguageCode() = 0; - virtual void - showNotification(const String &title, const String &text) const = 0; + virtual void showNotification(const String &title, const String &text) const = 0; }; diff --git a/src/lib/deskflow/IClient.h b/src/lib/deskflow/IClient.h index 5b59f91f4..234507d6f 100644 --- a/src/lib/deskflow/IClient.h +++ b/src/lib/deskflow/IClient.h @@ -30,7 +30,8 @@ This interface defines the methods necessary for the server to communicate with a client. */ -class IClient : public IScreen { +class IClient : public IScreen +{ public: //! @name manipulators //@{ @@ -43,9 +44,7 @@ public: screen is being entered because the screen saver is starting. Subsequent clipboard events should report \p seqNum. */ - virtual void enter( - SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, - bool forScreensaver) = 0; + virtual void enter(SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, bool forScreensaver) = 0; //! Leave screen /*! @@ -87,17 +86,14 @@ public: synthesize an up or repeat for the same client key synthesized by keyDown(). */ - virtual void - keyDown(KeyID id, KeyModifierMask, KeyButton, const String &) = 0; + virtual void keyDown(KeyID id, KeyModifierMask, KeyButton, const String &) = 0; //! Notify of key repeat /*! Synthesize key events to generate a press and release of key \c id \c count times. If possible match the given modifier mask. */ - virtual void keyRepeat( - KeyID id, KeyModifierMask, SInt32 count, KeyButton, - const String &lang) = 0; + virtual void keyRepeat(KeyID id, KeyModifierMask, SInt32 count, KeyButton, const String &lang) = 0; //! Notify of key release /*! @@ -172,7 +168,6 @@ public: // IScreen overrides virtual void *getEventTarget() const = 0; virtual bool getClipboard(ClipboardID id, IClipboard *) const = 0; - virtual void - getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const = 0; + virtual void getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const = 0; virtual void getCursorPos(SInt32 &x, SInt32 &y) const = 0; }; diff --git a/src/lib/deskflow/IClipboard.cpp b/src/lib/deskflow/IClipboard.cpp index 54a61765f..02a044d5b 100644 --- a/src/lib/deskflow/IClipboard.cpp +++ b/src/lib/deskflow/IClipboard.cpp @@ -23,8 +23,8 @@ // IClipboard // -void IClipboard::unmarshall( - IClipboard *clipboard, const String &data, Time time) { +void IClipboard::unmarshall(IClipboard *clipboard, const String &data, Time time) +{ assert(clipboard != NULL); const char *index = data.data(); @@ -40,8 +40,7 @@ void IClipboard::unmarshall( // read each format for (UInt32 i = 0; i < numFormats; ++i) { // get the format id - IClipboard::EFormat format = - static_cast(readUInt32(index)); + IClipboard::EFormat format = static_cast(readUInt32(index)); index += 4; // get the size of the format data @@ -62,7 +61,8 @@ void IClipboard::unmarshall( } } -String IClipboard::marshall(const IClipboard *clipboard) { +String IClipboard::marshall(const IClipboard *clipboard) +{ // return data format: // 4 bytes => number of formats included // 4 bytes => format enum @@ -85,8 +85,7 @@ String IClipboard::marshall(const IClipboard *clipboard) { for (UInt32 format = 0; format != IClipboard::kNumFormats; ++format) { if (clipboard->has(static_cast(format))) { ++numFormats; - formatData[format] = - clipboard->get(static_cast(format)); + formatData[format] = clipboard->get(static_cast(format)); size += 4 + 4 + (UInt32)formatData[format].size(); } } @@ -109,14 +108,16 @@ String IClipboard::marshall(const IClipboard *clipboard) { return data; } -bool IClipboard::copy(IClipboard *dst, const IClipboard *src) { +bool IClipboard::copy(IClipboard *dst, const IClipboard *src) +{ assert(dst != NULL); assert(src != NULL); return copy(dst, src, src->getTime()); } -bool IClipboard::copy(IClipboard *dst, const IClipboard *src, Time time) { +bool IClipboard::copy(IClipboard *dst, const IClipboard *src, Time time) +{ assert(dst != NULL); assert(src != NULL); @@ -140,14 +141,15 @@ bool IClipboard::copy(IClipboard *dst, const IClipboard *src, Time time) { return success; } -UInt32 IClipboard::readUInt32(const char *buf) { +UInt32 IClipboard::readUInt32(const char *buf) +{ const unsigned char *ubuf = reinterpret_cast(buf); - return (static_cast(ubuf[0]) << 24) | - (static_cast(ubuf[1]) << 16) | + return (static_cast(ubuf[0]) << 24) | (static_cast(ubuf[1]) << 16) | (static_cast(ubuf[2]) << 8) | static_cast(ubuf[3]); } -void IClipboard::writeUInt32(String *buf, UInt32 v) { +void IClipboard::writeUInt32(String *buf, UInt32 v) +{ *buf += static_cast((v >> 24) & 0xff); *buf += static_cast((v >> 16) & 0xff); *buf += static_cast((v >> 8) & 0xff); diff --git a/src/lib/deskflow/IClipboard.h b/src/lib/deskflow/IClipboard.h index 09442fe64..403f601fc 100644 --- a/src/lib/deskflow/IClipboard.h +++ b/src/lib/deskflow/IClipboard.h @@ -26,7 +26,8 @@ /*! This interface defines the methods common to all clipboards. */ -class IClipboard : public IInterface { +class IClipboard : public IInterface +{ public: //! Timestamp type /*! @@ -55,7 +56,8 @@ public: HTML fragment (but not necessarily a complete HTML document). Newlines are LF. */ - enum EFormat { + enum EFormat + { kText, //!< Text format, UTF-8, newline is LF kHTML, //!< HTML format, HTML fragment, UTF-8, newline is LF kBitmap, //!< Bitmap format, BMP 24/32bpp, BI_RGB diff --git a/src/lib/deskflow/IKeyState.cpp b/src/lib/deskflow/IKeyState.cpp index 332e6610d..01976f97a 100644 --- a/src/lib/deskflow/IKeyState.cpp +++ b/src/lib/deskflow/IKeyState.cpp @@ -26,14 +26,16 @@ // IKeyState // -IKeyState::IKeyState(IEventQueue *events) {} +IKeyState::IKeyState(IEventQueue *events) +{ +} // // IKeyState::KeyInfo // -IKeyState::KeyInfo *IKeyState::KeyInfo::alloc( - KeyID id, KeyModifierMask mask, KeyButton button, SInt32 count) { +IKeyState::KeyInfo *IKeyState::KeyInfo::alloc(KeyID id, KeyModifierMask mask, KeyButton button, SInt32 count) +{ KeyInfo *info = (KeyInfo *)malloc(sizeof(KeyInfo)); info->m_key = id; info->m_mask = mask; @@ -45,8 +47,9 @@ IKeyState::KeyInfo *IKeyState::KeyInfo::alloc( } IKeyState::KeyInfo *IKeyState::KeyInfo::alloc( - KeyID id, KeyModifierMask mask, KeyButton button, SInt32 count, - const std::set &destinations) { + KeyID id, KeyModifierMask mask, KeyButton button, SInt32 count, const std::set &destinations +) +{ String screens = join(destinations); const char *buffer = screens.c_str(); @@ -61,7 +64,8 @@ IKeyState::KeyInfo *IKeyState::KeyInfo::alloc( return info; } -IKeyState::KeyInfo *IKeyState::KeyInfo::alloc(const KeyInfo &x) { +IKeyState::KeyInfo *IKeyState::KeyInfo::alloc(const KeyInfo &x) +{ auto bufferLen = strnlen(x.m_screensBuffer, SIZE_MAX); auto info = (KeyInfo *)malloc(sizeof(KeyInfo) + bufferLen); info->m_key = x.m_key; @@ -73,11 +77,13 @@ IKeyState::KeyInfo *IKeyState::KeyInfo::alloc(const KeyInfo &x) { return info; } -bool IKeyState::KeyInfo::isDefault(const char *screens) { +bool IKeyState::KeyInfo::isDefault(const char *screens) +{ return (screens == NULL || screens[0] == '\0'); } -bool IKeyState::KeyInfo::contains(const char *screens, const String &name) { +bool IKeyState::KeyInfo::contains(const char *screens, const String &name) +{ // special cases if (isDefault(screens)) { return false; @@ -95,14 +101,16 @@ bool IKeyState::KeyInfo::contains(const char *screens, const String &name) { return (strstr(screens, match.c_str()) != NULL); } -bool IKeyState::KeyInfo::equal(const KeyInfo *a, const KeyInfo *b) { +bool IKeyState::KeyInfo::equal(const KeyInfo *a, const KeyInfo *b) +{ return ( - a->m_key == b->m_key && a->m_mask == b->m_mask && - a->m_button == b->m_button && a->m_count == b->m_count && - strcmp(a->m_screensBuffer, b->m_screensBuffer) == 0); + a->m_key == b->m_key && a->m_mask == b->m_mask && a->m_button == b->m_button && a->m_count == b->m_count && + strcmp(a->m_screensBuffer, b->m_screensBuffer) == 0 + ); } -String IKeyState::KeyInfo::join(const std::set &destinations) { +String IKeyState::KeyInfo::join(const std::set &destinations) +{ // collect destinations into a string. names are surrounded by ':' // which makes searching easy. the string is empty if there are no // destinations and "*" means all destinations. @@ -122,7 +130,8 @@ String IKeyState::KeyInfo::join(const std::set &destinations) { return screens; } -void IKeyState::KeyInfo::split(const char *screens, std::set &dst) { +void IKeyState::KeyInfo::split(const char *screens, std::set &dst) +{ dst.clear(); if (isDefault(screens)) { return; diff --git a/src/lib/deskflow/IKeyState.h b/src/lib/deskflow/IKeyState.h index f0f8e1bea..210cb3d50 100644 --- a/src/lib/deskflow/IKeyState.h +++ b/src/lib/deskflow/IKeyState.h @@ -31,19 +31,22 @@ This interface provides access to set and query the keyboard state and to synthesize key events. */ -class IKeyState : public IInterface { +class IKeyState : public IInterface +{ public: IKeyState(IEventQueue *events); - enum { kNumButtons = 0x200 }; + enum + { + kNumButtons = 0x200 + }; //! Key event data - class KeyInfo { + class KeyInfo + { public: static KeyInfo *alloc(KeyID, KeyModifierMask, KeyButton, SInt32 count); - static KeyInfo *alloc( - KeyID, KeyModifierMask, KeyButton, SInt32 count, - const std::set &destinations); + static KeyInfo *alloc(KeyID, KeyModifierMask, KeyButton, SInt32 count, const std::set &destinations); static KeyInfo *alloc(const KeyInfo &); static bool isDefault(const char *screens); @@ -92,16 +95,13 @@ public: /*! Synthesizes a key press event and updates the key state. */ - virtual void fakeKeyDown( - KeyID id, KeyModifierMask mask, KeyButton button, const String &lang) = 0; + virtual void fakeKeyDown(KeyID id, KeyModifierMask mask, KeyButton button, const String &lang) = 0; //! Fake a key repeat /*! Synthesizes a key repeat event and updates the key state. */ - virtual bool fakeKeyRepeat( - KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, - const String &lang) = 0; + virtual bool fakeKeyRepeat(KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang) = 0; //! Fake a key release /*! diff --git a/src/lib/deskflow/INode.h b/src/lib/deskflow/INode.h index 8e667a3ed..19b889bc0 100644 --- a/src/lib/deskflow/INode.h +++ b/src/lib/deskflow/INode.h @@ -20,4 +20,6 @@ #include "common/IInterface.h" -class INode : IInterface {}; +class INode : IInterface +{ +}; diff --git a/src/lib/deskflow/IPlatformScreen.cpp b/src/lib/deskflow/IPlatformScreen.cpp index 1776e8458..f78ce78df 100644 --- a/src/lib/deskflow/IPlatformScreen.cpp +++ b/src/lib/deskflow/IPlatformScreen.cpp @@ -17,4 +17,7 @@ #include "deskflow/IPlatformScreen.h" -bool IPlatformScreen::fakeMediaKey(KeyID id) { return false; } +bool IPlatformScreen::fakeMediaKey(KeyID id) +{ + return false; +} diff --git a/src/lib/deskflow/IPlatformScreen.h b/src/lib/deskflow/IPlatformScreen.h index dca999718..4c66bbba0 100644 --- a/src/lib/deskflow/IPlatformScreen.h +++ b/src/lib/deskflow/IPlatformScreen.h @@ -34,15 +34,15 @@ This interface defines the methods common to all platform dependent screen implementations that are used by both primary and secondary screens. */ -class IPlatformScreen : public IScreen, - public IPrimaryScreen, - public ISecondaryScreen, - public IKeyState { +class IPlatformScreen : public IScreen, public IPrimaryScreen, public ISecondaryScreen, public IKeyState +{ public: //! @name manipulators //@{ - IPlatformScreen(IEventQueue *events) : IKeyState(events) {} + IPlatformScreen(IEventQueue *events) : IKeyState(events) + { + } //! Enable screen /*! @@ -163,8 +163,7 @@ public: // IScreen overrides virtual void *getEventTarget() const = 0; virtual bool getClipboard(ClipboardID id, IClipboard *) const = 0; - virtual void - getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const = 0; + virtual void getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const = 0; virtual void getCursorPos(SInt32 &x, SInt32 &y) const = 0; // IPrimaryScreen overrides @@ -188,11 +187,8 @@ public: virtual void updateKeyMap() = 0; virtual void updateKeyState() = 0; virtual void setHalfDuplexMask(KeyModifierMask) = 0; - virtual void fakeKeyDown( - KeyID id, KeyModifierMask mask, KeyButton button, const String &lang) = 0; - virtual bool fakeKeyRepeat( - KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, - const String &lang) = 0; + virtual void fakeKeyDown(KeyID id, KeyModifierMask mask, KeyButton button, const String &lang) = 0; + virtual bool fakeKeyRepeat(KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang) = 0; virtual bool fakeKeyUp(KeyButton button) = 0; virtual void fakeAllKeysUp() = 0; virtual bool fakeCtrlAltDel() = 0; diff --git a/src/lib/deskflow/IPrimaryScreen.cpp b/src/lib/deskflow/IPrimaryScreen.cpp index ae6e3aa52..255f7a590 100644 --- a/src/lib/deskflow/IPrimaryScreen.cpp +++ b/src/lib/deskflow/IPrimaryScreen.cpp @@ -25,24 +25,24 @@ // IPrimaryScreen::ButtonInfo // -IPrimaryScreen::ButtonInfo * -IPrimaryScreen::ButtonInfo::alloc(ButtonID id, KeyModifierMask mask) { +IPrimaryScreen::ButtonInfo *IPrimaryScreen::ButtonInfo::alloc(ButtonID id, KeyModifierMask mask) +{ ButtonInfo *info = (ButtonInfo *)malloc(sizeof(ButtonInfo)); info->m_button = id; info->m_mask = mask; return info; } -IPrimaryScreen::ButtonInfo * -IPrimaryScreen::ButtonInfo::alloc(const ButtonInfo &x) { +IPrimaryScreen::ButtonInfo *IPrimaryScreen::ButtonInfo::alloc(const ButtonInfo &x) +{ ButtonInfo *info = (ButtonInfo *)malloc(sizeof(ButtonInfo)); info->m_button = x.m_button; info->m_mask = x.m_mask; return info; } -bool IPrimaryScreen::ButtonInfo::equal( - const ButtonInfo *a, const ButtonInfo *b) { +bool IPrimaryScreen::ButtonInfo::equal(const ButtonInfo *a, const ButtonInfo *b) +{ return (a->m_button == b->m_button && a->m_mask == b->m_mask); } @@ -50,8 +50,8 @@ bool IPrimaryScreen::ButtonInfo::equal( // IPrimaryScreen::MotionInfo // -IPrimaryScreen::MotionInfo * -IPrimaryScreen::MotionInfo::alloc(SInt32 x, SInt32 y) { +IPrimaryScreen::MotionInfo *IPrimaryScreen::MotionInfo::alloc(SInt32 x, SInt32 y) +{ MotionInfo *info = (MotionInfo *)malloc(sizeof(MotionInfo)); info->m_x = x; info->m_y = y; @@ -62,8 +62,8 @@ IPrimaryScreen::MotionInfo::alloc(SInt32 x, SInt32 y) { // IPrimaryScreen::WheelInfo // -IPrimaryScreen::WheelInfo * -IPrimaryScreen::WheelInfo::alloc(SInt32 xDelta, SInt32 yDelta) { +IPrimaryScreen::WheelInfo *IPrimaryScreen::WheelInfo::alloc(SInt32 xDelta, SInt32 yDelta) +{ WheelInfo *info = (WheelInfo *)malloc(sizeof(WheelInfo)); info->m_xDelta = xDelta; info->m_yDelta = yDelta; @@ -74,7 +74,8 @@ IPrimaryScreen::WheelInfo::alloc(SInt32 xDelta, SInt32 yDelta) { // IPrimaryScreen::HotKeyInfo // -IPrimaryScreen::HotKeyInfo *IPrimaryScreen::HotKeyInfo::alloc(UInt32 id) { +IPrimaryScreen::HotKeyInfo *IPrimaryScreen::HotKeyInfo::alloc(UInt32 id) +{ HotKeyInfo *info = (HotKeyInfo *)malloc(sizeof(HotKeyInfo)); info->m_id = id; return info; @@ -84,7 +85,8 @@ IPrimaryScreen::HotKeyInfo *IPrimaryScreen::HotKeyInfo::alloc(UInt32 id) { // IPrimaryScreen::EiConnectInfo // -IPrimaryScreen::EiConnectInfo *IPrimaryScreen::EiConnectInfo::alloc(int fd) { +IPrimaryScreen::EiConnectInfo *IPrimaryScreen::EiConnectInfo::alloc(int fd) +{ EiConnectInfo *info = (EiConnectInfo *)malloc(sizeof(EiConnectInfo)); info->m_fd = fd; return info; diff --git a/src/lib/deskflow/IPrimaryScreen.h b/src/lib/deskflow/IPrimaryScreen.h index 22f7d3ba6..428083e64 100644 --- a/src/lib/deskflow/IPrimaryScreen.h +++ b/src/lib/deskflow/IPrimaryScreen.h @@ -29,10 +29,12 @@ This interface defines the methods common to all platform dependent primary screen implementations. */ -class IPrimaryScreen : public IInterface { +class IPrimaryScreen : public IInterface +{ public: //! Button event data - class ButtonInfo { + class ButtonInfo + { public: static ButtonInfo *alloc(ButtonID, KeyModifierMask); static ButtonInfo *alloc(const ButtonInfo &); @@ -44,7 +46,8 @@ public: KeyModifierMask m_mask; }; //! Motion event data - class MotionInfo { + class MotionInfo + { public: static MotionInfo *alloc(SInt32 x, SInt32 y); @@ -53,7 +56,8 @@ public: SInt32 m_y; }; //! Wheel motion event data - class WheelInfo { + class WheelInfo + { public: static WheelInfo *alloc(SInt32 xDelta, SInt32 yDelta); @@ -62,7 +66,8 @@ public: SInt32 m_yDelta; }; //! Hot key event data - class HotKeyInfo { + class HotKeyInfo + { public: static HotKeyInfo *alloc(UInt32 id); @@ -70,7 +75,8 @@ public: UInt32 m_id; }; - class EiConnectInfo { + class EiConnectInfo + { public: static EiConnectInfo *alloc(int fd); diff --git a/src/lib/deskflow/IScreen.h b/src/lib/deskflow/IScreen.h index 5a1df2038..53ae66f1f 100644 --- a/src/lib/deskflow/IScreen.h +++ b/src/lib/deskflow/IScreen.h @@ -29,9 +29,11 @@ class IClipboard; /*! This interface defines the methods common to all screens. */ -class IScreen : public IInterface { +class IScreen : public IInterface +{ public: - struct ClipboardInfo { + struct ClipboardInfo + { public: ClipboardID m_id; UInt32 m_sequenceNumber; @@ -58,8 +60,7 @@ public: Return the position of the upper-left corner of the screen in \c x and \c y and the size of the screen in \c width and \c height. */ - virtual void - getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const = 0; + virtual void getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const = 0; //! Get cursor position /*! diff --git a/src/lib/deskflow/IScreenSaver.h b/src/lib/deskflow/IScreenSaver.h index d1d01a56c..78d9a114b 100644 --- a/src/lib/deskflow/IScreenSaver.h +++ b/src/lib/deskflow/IScreenSaver.h @@ -25,7 +25,8 @@ /*! This interface defines the methods common to all screen savers. */ -class IScreenSaver : public IInterface { +class IScreenSaver : public IInterface +{ public: // note -- the c'tor/d'tor must *not* enable/disable the screen saver diff --git a/src/lib/deskflow/ISecondaryScreen.h b/src/lib/deskflow/ISecondaryScreen.h index dd70bc2ab..70a7e84a9 100644 --- a/src/lib/deskflow/ISecondaryScreen.h +++ b/src/lib/deskflow/ISecondaryScreen.h @@ -28,7 +28,8 @@ This interface defines the methods common to all platform dependent secondary screen implementations. */ -class ISecondaryScreen : public IInterface { +class ISecondaryScreen : public IInterface +{ public: //! @name accessors //@{ diff --git a/src/lib/deskflow/KeyMap.cpp b/src/lib/deskflow/KeyMap.cpp index e60f234db..d80d84934 100644 --- a/src/lib/deskflow/KeyMap.cpp +++ b/src/lib/deskflow/KeyMap.cpp @@ -33,7 +33,8 @@ KeyMap::NameToModifierMap *KeyMap::s_nameToModifierMap = NULL; KeyMap::KeyToNameMap *KeyMap::s_keyToNameMap = NULL; KeyMap::ModifierToNameMap *KeyMap::s_modifierToNameMap = NULL; -KeyMap::KeyMap() : m_numGroups(0), m_composeAcrossGroups(false) { +KeyMap::KeyMap() : m_numGroups(0), m_composeAcrossGroups(false) +{ m_modifierKeyItem.m_id = kKeyNone; m_modifierKeyItem.m_group = 0; m_modifierKeyItem.m_button = 0; @@ -45,11 +46,13 @@ KeyMap::KeyMap() : m_numGroups(0), m_composeAcrossGroups(false) { m_modifierKeyItem.m_client = 0; } -KeyMap::~KeyMap() { +KeyMap::~KeyMap() +{ // do nothing } -void KeyMap::swap(KeyMap &x) { +void KeyMap::swap(KeyMap &x) +{ m_keyIDMap.swap(x.m_keyIDMap); m_modifierKeys.swap(x.m_modifierKeys); m_halfDuplex.swap(x.m_halfDuplex); @@ -62,7 +65,8 @@ void KeyMap::swap(KeyMap &x) { x.m_composeAcrossGroups = tmp2; } -void KeyMap::addKeyEntry(const KeyItem &item) { +void KeyMap::addKeyEntry(const KeyItem &item) +{ // ignore kKeyNone if (item.m_id == kKeyNone) { return; @@ -99,27 +103,26 @@ void KeyMap::addKeyEntry(const KeyItem &item) { // add item list entries.push_back(items); - LOG(( - CLOG_DEBUG5 "add key: %04x %d %03x %04x (%04x %04x %04x)%s", newItem.m_id, - newItem.m_group, newItem.m_button, newItem.m_client, newItem.m_required, - newItem.m_sensitive, newItem.m_generates, newItem.m_dead ? " dead" : "")); + LOG( + (CLOG_DEBUG5 "add key: %04x %d %03x %04x (%04x %04x %04x)%s", newItem.m_id, newItem.m_group, newItem.m_button, + newItem.m_client, newItem.m_required, newItem.m_sensitive, newItem.m_generates, newItem.m_dead ? " dead" : "") + ); } void KeyMap::addKeyAliasEntry( - KeyID targetID, SInt32 group, KeyModifierMask targetRequired, - KeyModifierMask targetSensitive, KeyID sourceID, - KeyModifierMask sourceRequired, KeyModifierMask sourceSensitive) { + KeyID targetID, SInt32 group, KeyModifierMask targetRequired, KeyModifierMask targetSensitive, KeyID sourceID, + KeyModifierMask sourceRequired, KeyModifierMask sourceSensitive +) +{ // if we can already generate the target as desired then we're done. - if (findCompatibleKey(targetID, group, targetRequired, targetSensitive) != - NULL) { + if (findCompatibleKey(targetID, group, targetRequired, targetSensitive) != NULL) { return; } // find a compatible source, preferably in the same group for (SInt32 gd = 0, n = getNumGroups(); gd < n; ++gd) { SInt32 eg = getEffectiveGroup(group, gd); - const KeyItemList *sourceEntry = - findCompatibleKey(sourceID, eg, sourceRequired, sourceSensitive); + const KeyItemList *sourceEntry = findCompatibleKey(sourceID, eg, sourceRequired, sourceSensitive); if (sourceEntry != NULL && sourceEntry->size() == 1) { KeyMap::KeyItem targetItem = sourceEntry->back(); targetItem.m_id = targetID; @@ -130,8 +133,8 @@ void KeyMap::addKeyAliasEntry( } } -bool KeyMap::addKeyCombinationEntry( - KeyID id, SInt32 group, const KeyID *keys, UInt32 numKeys) { +bool KeyMap::addKeyCombinationEntry(KeyID id, SInt32 group, const KeyID *keys, UInt32 numKeys) +{ // disallow kKeyNone if (id == kKeyNone) { return false; @@ -189,17 +192,28 @@ bool KeyMap::addKeyCombinationEntry( return true; } -void KeyMap::allowGroupSwitchDuringCompose() { m_composeAcrossGroups = true; } +void KeyMap::allowGroupSwitchDuringCompose() +{ + m_composeAcrossGroups = true; +} -void KeyMap::addHalfDuplexButton(KeyButton button) { +void KeyMap::addHalfDuplexButton(KeyButton button) +{ m_halfDuplex.insert(button); } -void KeyMap::clearHalfDuplexModifiers() { m_halfDuplexMods.clear(); } +void KeyMap::clearHalfDuplexModifiers() +{ + m_halfDuplexMods.clear(); +} -void KeyMap::addHalfDuplexModifier(KeyID key) { m_halfDuplexMods.insert(key); } +void KeyMap::addHalfDuplexModifier(KeyID key) +{ + m_halfDuplexMods.insert(key); +} -void KeyMap::finish() { +void KeyMap::finish() +{ m_numGroups = findNumGroups(); // make sure every key has the same number of groups @@ -211,7 +225,8 @@ void KeyMap::finish() { setModifierKeys(); } -void KeyMap::foreachKey(ForeachKeyCallback cb, void *userData) { +void KeyMap::foreachKey(ForeachKeyCallback cb, void *userData) +{ for (KeyIDMap::iterator i = m_keyIDMap.begin(); i != m_keyIDMap.end(); ++i) { KeyGroupTable &groupTable = i->second; for (size_t group = 0; group < groupTable.size(); ++group) { @@ -227,13 +242,14 @@ void KeyMap::foreachKey(ForeachKeyCallback cb, void *userData) { } const KeyMap::KeyItem *KeyMap::mapKey( - Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, - KeyModifierMask ¤tState, KeyModifierMask desiredMask, - bool isAutoRepeat, const String &lang) const { + Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState, + KeyModifierMask desiredMask, bool isAutoRepeat, const String &lang +) const +{ LOG( - (CLOG_DEBUG1 - "mapKey %04x (%d) with mask %04x, start state: %04x, group: %d", - id, id, desiredMask, currentState, group)); + (CLOG_DEBUG1 "mapKey %04x (%d) with mask %04x, start state: %04x, group: %d", id, id, desiredMask, currentState, + group) + ); // handle group change if (id == kKeyNextGroup) { @@ -260,15 +276,11 @@ const KeyMap::KeyItem *KeyMap::mapKey( case kKeyCapsLock: case kKeyNumLock: case kKeyScrollLock: - item = mapModifierKey( - keys, id, group, activeModifiers, currentState, desiredMask, - isAutoRepeat, lang); + item = mapModifierKey(keys, id, group, activeModifiers, currentState, desiredMask, isAutoRepeat, lang); break; case kKeySetModifiers: - if (!keysForModifierState( - 0, group, activeModifiers, currentState, desiredMask, desiredMask, - 0, keys)) { + if (!keysForModifierState(0, group, activeModifiers, currentState, desiredMask, desiredMask, 0, keys)) { LOG((CLOG_DEBUG1 "unable to set modifiers %04x", desiredMask)); return NULL; } @@ -276,8 +288,8 @@ const KeyMap::KeyItem *KeyMap::mapKey( case kKeyClearModifiers: if (!keysForModifierState( - 0, group, activeModifiers, currentState, - currentState & ~desiredMask, desiredMask, 0, keys)) { + 0, group, activeModifiers, currentState, currentState & ~desiredMask, desiredMask, 0, keys + )) { LOG((CLOG_DEBUG1 "unable to clear modifiers %04x", desiredMask)); return NULL; } @@ -285,30 +297,26 @@ const KeyMap::KeyItem *KeyMap::mapKey( default: if (isCommand(desiredMask)) { - item = mapCommandKey( - keys, id, group, activeModifiers, currentState, desiredMask, - isAutoRepeat, lang); + item = mapCommandKey(keys, id, group, activeModifiers, currentState, desiredMask, isAutoRepeat, lang); } else { - item = mapCharacterKey( - keys, id, group, activeModifiers, currentState, desiredMask, - isAutoRepeat, lang); + item = mapCharacterKey(keys, id, group, activeModifiers, currentState, desiredMask, isAutoRepeat, lang); } break; } if (item != NULL) { - 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; } -void KeyMap::setLanguageData(std::vector layouts) { +void KeyMap::setLanguageData(std::vector layouts) +{ m_keyboardLayouts = std::move(layouts); } -SInt32 KeyMap::getLanguageGroupID(SInt32 group, const String &lang) const { +SInt32 KeyMap::getLanguageGroupID(SInt32 group, const String &lang) const +{ SInt32 id = group; auto it = std::find(m_keyboardLayouts.begin(), m_keyboardLayouts.end(), lang); @@ -322,15 +330,19 @@ SInt32 KeyMap::getLanguageGroupID(SInt32 group, const String &lang) const { return id; } -SInt32 KeyMap::getNumGroups() const { return m_numGroups; } +SInt32 KeyMap::getNumGroups() const +{ + return m_numGroups; +} -SInt32 KeyMap::getEffectiveGroup(SInt32 group, SInt32 offset) const { +SInt32 KeyMap::getEffectiveGroup(SInt32 group, SInt32 offset) const +{ return (group + offset + getNumGroups()) % getNumGroups(); } -const KeyMap::KeyItemList *KeyMap::findCompatibleKey( - KeyID id, SInt32 group, KeyModifierMask required, - KeyModifierMask sensitive) const { +const KeyMap::KeyItemList * +KeyMap::findCompatibleKey(KeyID id, SInt32 group, KeyModifierMask required, KeyModifierMask sensitive) const +{ assert(group >= 0 && group < getNumGroups()); KeyIDMap::const_iterator i = m_keyIDMap.find(id); @@ -349,30 +361,34 @@ const KeyMap::KeyItemList *KeyMap::findCompatibleKey( return NULL; } -bool KeyMap::isHalfDuplex(KeyID key, KeyButton button) const { +bool KeyMap::isHalfDuplex(KeyID key, KeyButton button) const +{ return (m_halfDuplex.count(button) + m_halfDuplexMods.count(key) > 0); } -bool KeyMap::isCommand(KeyModifierMask mask) const { +bool KeyMap::isCommand(KeyModifierMask mask) const +{ return ((mask & getCommandModifiers()) != 0); } -KeyModifierMask KeyMap::getCommandModifiers() const { +KeyModifierMask KeyMap::getCommandModifiers() const +{ // we currently treat ctrl, alt, meta and super as command modifiers. // some platforms may have a more limited set (OS X only needs Alt) // but this works anyway. - return KeyModifierControl | KeyModifierAlt | KeyModifierAltGr | - KeyModifierMeta | KeyModifierSuper; + return KeyModifierControl | KeyModifierAlt | KeyModifierAltGr | KeyModifierMeta | KeyModifierSuper; } -void KeyMap::collectButtons(const ModifierToKeys &mods, ButtonToKeyMap &keys) { +void KeyMap::collectButtons(const ModifierToKeys &mods, ButtonToKeyMap &keys) +{ keys.clear(); for (ModifierToKeys::const_iterator i = mods.begin(); i != mods.end(); ++i) { keys.insert(std::make_pair(i->second.m_button, &i->second)); } } -void KeyMap::initModifierKey(KeyItem &item) { +void KeyMap::initModifierKey(KeyItem &item) +{ item.m_generates = 0; item.m_lock = false; switch (item.m_id) { @@ -426,10 +442,10 @@ void KeyMap::initModifierKey(KeyItem &item) { } } -SInt32 KeyMap::findNumGroups() const { +SInt32 KeyMap::findNumGroups() const +{ size_t max = 0; - for (KeyIDMap::const_iterator i = m_keyIDMap.begin(); i != m_keyIDMap.end(); - ++i) { + for (KeyIDMap::const_iterator i = m_keyIDMap.begin(); i != m_keyIDMap.end(); ++i) { if (i->second.size() > max) { max = i->second.size(); } @@ -437,11 +453,11 @@ SInt32 KeyMap::findNumGroups() const { return static_cast(max); } -void KeyMap::setModifierKeys() { +void KeyMap::setModifierKeys() +{ m_modifierKeys.clear(); m_modifierKeys.resize(kKeyModifierNumBits * getNumGroups()); - for (KeyIDMap::const_iterator i = m_keyIDMap.begin(); i != m_keyIDMap.end(); - ++i) { + for (KeyIDMap::const_iterator i = m_keyIDMap.begin(); i != m_keyIDMap.end(); ++i) { const KeyGroupTable &groupTable = i->second; for (size_t g = 0; g < groupTable.size(); ++g) { const KeyEntryList &entries = groupTable[g]; @@ -471,9 +487,10 @@ void KeyMap::setModifierKeys() { } const KeyMap::KeyItem *KeyMap::mapCommandKey( - Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, - KeyModifierMask ¤tState, KeyModifierMask desiredMask, - bool isAutoRepeat, const String &lang) const { + Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState, + KeyModifierMask desiredMask, bool isAutoRepeat, const String &lang +) const +{ static const KeyModifierMask s_overrideModifiers = 0xffffu; // find KeySym in table @@ -504,12 +521,9 @@ const KeyMap::KeyItem *KeyMap::mapCommandKey( // modifiers, when synthesizing this button. const KeyItem &item = entryList[i].back(); KeyModifierMask desiredShiftMask = KeyModifierShift & desiredMask; - KeyModifierMask requiredIgnoreShiftMask = - item.m_required & ~KeyModifierShift; - if ((item.m_required & desiredShiftMask) == - (item.m_sensitive & desiredShiftMask) && - ((requiredIgnoreShiftMask & desiredMask) == - requiredIgnoreShiftMask)) { + KeyModifierMask requiredIgnoreShiftMask = item.m_required & ~KeyModifierShift; + if ((item.m_required & desiredShiftMask) == (item.m_sensitive & desiredShiftMask) && + ((requiredIgnoreShiftMask & desiredMask) == requiredIgnoreShiftMask)) { LOG((CLOG_DEBUG1 "found key in group %d", effectiveGroup)); keyItem = &item; break; @@ -531,21 +545,19 @@ const KeyMap::KeyItem *KeyMap::mapCommandKey( SInt32 newGroup = group; // don't try to change CapsLock - desiredMask = (desiredMask & ~KeyModifierCapsLock) | - (currentState & KeyModifierCapsLock); + desiredMask = (desiredMask & ~KeyModifierCapsLock) | (currentState & KeyModifierCapsLock); // add the key if (!keysForKeyItem( - *keyItem, newGroup, newModifiers, newState, desiredMask, - s_overrideModifiers, isAutoRepeat, keys, lang)) { + *keyItem, newGroup, newModifiers, newState, desiredMask, s_overrideModifiers, isAutoRepeat, keys, lang + )) { LOG((CLOG_DEBUG1 "can't map key")); keys.clear(); return NULL; } // add keystrokes to restore modifier keys - if (!keysToRestoreModifiers( - *keyItem, group, newModifiers, newState, activeModifiers, keys)) { + if (!keysToRestoreModifiers(*keyItem, group, newModifiers, newState, activeModifiers, keys)) { LOG((CLOG_DEBUG1 "failed to restore modifiers")); keys.clear(); return NULL; @@ -558,9 +570,9 @@ const KeyMap::KeyItem *KeyMap::mapCommandKey( return keyItem; } -const KeyMap::KeyItemList *KeyMap::getKeyItemList( - const KeyMap::KeyGroupTable &keyGroupTable, SInt32 group, - KeyModifierMask desiredMask) const { +const KeyMap::KeyItemList * +KeyMap::getKeyItemList(const KeyMap::KeyGroupTable &keyGroupTable, SInt32 group, KeyModifierMask desiredMask) const +{ const KeyItemList *itemList = nullptr; // find best key in any group, starting with the active group @@ -578,9 +590,10 @@ const KeyMap::KeyItemList *KeyMap::getKeyItemList( } const KeyMap::KeyItem *KeyMap::mapCharacterKey( - Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, - KeyModifierMask ¤tState, KeyModifierMask desiredMask, - bool isAutoRepeat, const String &lang) const { + Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState, + KeyModifierMask desiredMask, bool isAutoRepeat, const String &lang +) const +{ // find KeySym in table KeyIDMap::const_iterator i = m_keyIDMap.find(id); if (i == m_keyIDMap.end()) { @@ -591,8 +604,7 @@ const KeyMap::KeyItem *KeyMap::mapCharacterKey( } // get keys to press for key - auto itemList = - getKeyItemList(i->second, getLanguageGroupID(group, lang), desiredMask); + auto itemList = getKeyItemList(i->second, getLanguageGroupID(group, lang), desiredMask); if (!itemList || itemList->empty()) { // no mapping for this keysym LOG((CLOG_DEBUG1 "no mapping for key %04x", id)); @@ -608,9 +620,7 @@ const KeyMap::KeyItem *KeyMap::mapCharacterKey( // add each key for (size_t j = 0; j < itemList->size(); ++j) { - if (!keysForKeyItem( - itemList->at(j), newGroup, newModifiers, newState, desiredMask, 0, - isAutoRepeat, keys, lang)) { + if (!keysForKeyItem(itemList->at(j), newGroup, newModifiers, newState, desiredMask, 0, isAutoRepeat, keys, lang)) { LOG((CLOG_DEBUG1 "can't map key")); keys.clear(); return NULL; @@ -618,8 +628,7 @@ const KeyMap::KeyItem *KeyMap::mapCharacterKey( } // add keystrokes to restore modifier keys - if (!keysToRestoreModifiers( - keyItem, group, newModifiers, newState, activeModifiers, keys)) { + if (!keysToRestoreModifiers(keyItem, group, newModifiers, newState, activeModifiers, keys)) { LOG((CLOG_DEBUG1 "failed to restore modifiers")); keys.clear(); return NULL; @@ -632,31 +641,28 @@ const KeyMap::KeyItem *KeyMap::mapCharacterKey( return &keyItem; } -void KeyMap::addGroupToKeystroke( - Keystrokes &keys, SInt32 &group, const String &lang) const { +void KeyMap::addGroupToKeystroke(Keystrokes &keys, SInt32 &group, const String &lang) const +{ group = getLanguageGroupID(group, lang); keys.push_back(Keystroke(group, true, false)); } const KeyMap::KeyItem *KeyMap::mapModifierKey( - Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, - KeyModifierMask ¤tState, KeyModifierMask desiredMask, - bool isAutoRepeat, const String &lang) const { - return mapCharacterKey( - keys, id, group, activeModifiers, currentState, desiredMask, isAutoRepeat, - lang); + Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState, + KeyModifierMask desiredMask, bool isAutoRepeat, const String &lang +) const +{ + return mapCharacterKey(keys, id, group, activeModifiers, currentState, desiredMask, isAutoRepeat, lang); } -SInt32 KeyMap::findBestKey( - const KeyEntryList &entryList, KeyModifierMask desiredState) const { +SInt32 KeyMap::findBestKey(const KeyEntryList &entryList, KeyModifierMask desiredState) const +{ // check for an item that can accommodate the desiredState exactly for (SInt32 i = 0; i < (SInt32)entryList.size(); ++i) { const KeyItem &item = entryList[i].back(); if ((item.m_required & desiredState) == item.m_required && (item.m_required & desiredState) == (item.m_sensitive & desiredState)) { - LOG( - (CLOG_DEBUG1 "best key index %d of %d (exact)", i + 1, - entryList.size())); + LOG((CLOG_DEBUG1 "best key index %d of %d (exact)", i + 1, entryList.size())); return i; } } @@ -666,8 +672,7 @@ SInt32 KeyMap::findBestKey( SInt32 bestIndex = -1; for (SInt32 i = 0; i < (SInt32)entryList.size(); ++i) { const KeyItem &item = entryList[i].back(); - KeyModifierMask change = - ((item.m_required ^ desiredState) & item.m_sensitive); + KeyModifierMask change = ((item.m_required ^ desiredState) & item.m_sensitive); SInt32 n = getNumModifiers(change); if (n < bestCount) { bestCount = n; @@ -675,16 +680,14 @@ SInt32 KeyMap::findBestKey( } } if (bestIndex != -1) { - LOG( - (CLOG_DEBUG1 "best key index %d of %d (%d modifiers)", bestIndex + 1, - entryList.size(), bestCount)); + LOG((CLOG_DEBUG1 "best key index %d of %d (%d modifiers)", bestIndex + 1, entryList.size(), bestCount)); } return bestIndex; } -const KeyMap::KeyItem *KeyMap::keyForModifier( - KeyButton button, SInt32 group, SInt32 modifierBit) const { +const KeyMap::KeyItem *KeyMap::keyForModifier(KeyButton button, SInt32 group, SInt32 modifierBit) const +{ assert(modifierBit >= 0 && modifierBit < kKeyModifierNumBits); assert(group >= 0 && group < getNumGroups()); @@ -693,10 +696,8 @@ const KeyMap::KeyItem *KeyMap::keyForModifier( // to generate a KeyID that's only bound the the given button. // this is important when a shift button is modified by shift; we // must use the other shift button to do the shifting. - const ModifierKeyItemList &items = - m_modifierKeys[group * kKeyModifierNumBits + modifierBit]; - for (ModifierKeyItemList::const_iterator i = items.begin(); i != items.end(); - ++i) { + const ModifierKeyItemList &items = m_modifierKeys[group * kKeyModifierNumBits + modifierBit]; + for (ModifierKeyItemList::const_iterator i = items.begin(); i != items.end(); ++i) { if ((*i)->m_button != button) { return (*i); } @@ -705,12 +706,12 @@ const KeyMap::KeyItem *KeyMap::keyForModifier( } bool KeyMap::keysForKeyItem( - const KeyItem &keyItem, SInt32 &group, ModifierToKeys &activeModifiers, - KeyModifierMask ¤tState, KeyModifierMask desiredState, - KeyModifierMask overrideModifiers, bool isAutoRepeat, - Keystrokes &keystrokes, const String &lang) const { - static const KeyModifierMask s_notRequiredMask = - KeyModifierAltGr | KeyModifierNumLock | KeyModifierScrollLock; + const KeyItem &keyItem, SInt32 &group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState, + KeyModifierMask desiredState, KeyModifierMask overrideModifiers, bool isAutoRepeat, Keystrokes &keystrokes, + const String &lang +) const +{ + static const KeyModifierMask s_notRequiredMask = KeyModifierAltGr | KeyModifierNumLock | KeyModifierScrollLock; // add keystrokes to adjust the group if (group != keyItem.m_group) { @@ -722,11 +723,10 @@ bool KeyMap::keysForKeyItem( if (keyItem.m_dead) { // adjust modifiers for dead key if (!keysForModifierState( - keyItem.m_button, group, activeModifiers, currentState, - keyItem.m_required, keyItem.m_sensitive, 0, keystrokes)) { - LOG( - (CLOG_DEBUG1 "unable to match modifier state for dead key %d", - keyItem.m_button)); + keyItem.m_button, group, activeModifiers, currentState, keyItem.m_required, keyItem.m_sensitive, 0, + keystrokes + )) { + LOG((CLOG_DEBUG1 "unable to match modifier state for dead key %d", keyItem.m_button)); return false; } @@ -744,15 +744,14 @@ bool KeyMap::keysForKeyItem( // button (any other button) mapped to the shift modifier and then // the Shift_L button. // match key's required state - LOG( - (CLOG_DEBUG1 "state: %04x,%04x,%04x", currentState, keyItem.m_required, - sensitive)); + LOG((CLOG_DEBUG1 "state: %04x,%04x,%04x", currentState, keyItem.m_required, sensitive)); if (!keysForModifierState( - keyItem.m_button, group, activeModifiers, currentState, - keyItem.m_required, sensitive, 0, keystrokes)) { + keyItem.m_button, group, activeModifiers, currentState, keyItem.m_required, sensitive, 0, keystrokes + )) { LOG( - (CLOG_DEBUG1 "unable to match modifier state (%04x,%04x) for key %d", - keyItem.m_required, keyItem.m_sensitive, keyItem.m_button)); + (CLOG_DEBUG1 "unable to match modifier state (%04x,%04x) for key %d", keyItem.m_required, keyItem.m_sensitive, + keyItem.m_button) + ); return false; } @@ -760,16 +759,17 @@ bool KeyMap::keysForKeyItem( // change any modifiers in keyItem.m_sensitive. and if the key // is a modifier, we don't want to change that modifier. LOG( - (CLOG_DEBUG1 "desired state: %04x %04x,%04x,%04x", desiredState, - currentState, keyItem.m_required, keyItem.m_sensitive)); + (CLOG_DEBUG1 "desired state: %04x %04x,%04x,%04x", desiredState, currentState, keyItem.m_required, + keyItem.m_sensitive) + ); if (!keysForModifierState( - keyItem.m_button, group, activeModifiers, currentState, - desiredState, ~(sensitive | keyItem.m_generates), s_notRequiredMask, - keystrokes)) { + keyItem.m_button, group, activeModifiers, currentState, desiredState, ~(sensitive | keyItem.m_generates), + s_notRequiredMask, keystrokes + )) { LOG( - (CLOG_DEBUG1 - "unable to match desired modifier state (%04x,%04x) for key %d", - desiredState, ~keyItem.m_sensitive & 0xffffu, keyItem.m_button)); + (CLOG_DEBUG1 "unable to match desired modifier state (%04x,%04x) for key %d", desiredState, + ~keyItem.m_sensitive & 0xffffu, keyItem.m_button) + ); return false; } @@ -782,9 +782,10 @@ bool KeyMap::keysForKeyItem( } bool KeyMap::keysToRestoreModifiers( - const KeyItem &keyItem, SInt32, ModifierToKeys &activeModifiers, - KeyModifierMask ¤tState, const ModifierToKeys &desiredModifiers, - Keystrokes &keystrokes) const { + const KeyItem &keyItem, SInt32, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState, + const ModifierToKeys &desiredModifiers, Keystrokes &keystrokes +) const +{ // XXX -- we're not considering modified modifiers here ModifierToKeys oldModifiers = activeModifiers; @@ -795,8 +796,7 @@ bool KeyMap::keysToRestoreModifiers( collectButtons(desiredModifiers, newKeys); // release unwanted keys - for (ModifierToKeys::const_iterator i = oldModifiers.begin(); - i != oldModifiers.end(); ++i) { + for (ModifierToKeys::const_iterator i = oldModifiers.begin(); i != oldModifiers.end(); ++i) { KeyButton button = i->second.m_button; if (button != keyItem.m_button && newKeys.count(button) == 0) { EKeystroke type = kKeystrokeRelease; @@ -808,8 +808,7 @@ bool KeyMap::keysToRestoreModifiers( } // press wanted keys - for (ModifierToKeys::const_iterator i = desiredModifiers.begin(); - i != desiredModifiers.end(); ++i) { + for (ModifierToKeys::const_iterator i = desiredModifiers.begin(); i != desiredModifiers.end(); ++i) { KeyButton button = i->second.m_button; if (button != keyItem.m_button && oldKeys.count(button) == 0) { EKeystroke type = kKeystrokePress; @@ -824,10 +823,11 @@ bool KeyMap::keysToRestoreModifiers( } bool KeyMap::keysForModifierState( - KeyButton button, SInt32 group, ModifierToKeys &activeModifiers, - KeyModifierMask ¤tState, KeyModifierMask requiredState, - KeyModifierMask sensitiveMask, KeyModifierMask notRequiredMask, - Keystrokes &keystrokes) const { + KeyButton button, SInt32 group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState, + KeyModifierMask requiredState, KeyModifierMask sensitiveMask, KeyModifierMask notRequiredMask, + Keystrokes &keystrokes +) const +{ // compute which modifiers need changing KeyModifierMask flipMask = ((currentState ^ requiredState) & sensitiveMask); // if a modifier is not required then don't even try to match it. if @@ -837,9 +837,9 @@ bool KeyMap::keysForModifierState( // interfere) so we don't try to match at all. flipMask &= ~notRequiredMask; LOG( - (CLOG_DEBUG1 "flip: %04x (%04x vs %04x in %04x - %04x)", flipMask, - currentState, requiredState, sensitiveMask & 0xffffu, - notRequiredMask & 0xffffu)); + (CLOG_DEBUG1 "flip: %04x (%04x vs %04x in %04x - %04x)", flipMask, currentState, requiredState, + sensitiveMask & 0xffffu, notRequiredMask & 0xffffu) + ); if (flipMask == 0) { return true; } @@ -890,8 +890,8 @@ bool KeyMap::keysForModifierState( } if (active && !keysForModifierState( - button, group, activeModifiers, currentState, keyItem->m_required, - sensitive, notRequiredMask, keystrokes)) { + button, group, activeModifiers, currentState, keyItem->m_required, sensitive, notRequiredMask, keystrokes + )) { return false; } else if (!active) { // release the modifier @@ -907,7 +907,8 @@ bool KeyMap::keysForModifierState( LOG( (CLOG_DEBUG1 "unable to match modifier state for modifier %04x (%04x " "vs %04x in %04x)", - mask, currentState, keyItem->m_required, sensitive)); + mask, currentState, keyItem->m_required, sensitive) + ); return false; } @@ -920,8 +921,10 @@ bool KeyMap::keysForModifierState( } void KeyMap::addKeystrokes( - EKeystroke type, const KeyItem &keyItem, ModifierToKeys &activeModifiers, - KeyModifierMask ¤tState, Keystrokes &keystrokes) const { + EKeystroke type, const KeyItem &keyItem, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState, + Keystrokes &keystrokes +) const +{ KeyButton button = keyItem.m_button; UInt32 data = keyItem.m_client; switch (type) { @@ -995,12 +998,10 @@ void KeyMap::addKeystrokes( } else { // release all the keys that generate the modifier that are // currently down - std::pair - range = activeModifiers.equal_range(keyItem.m_generates); - for (ModifierToKeys::const_iterator i = range.first; i != range.second; - ++i) { - keystrokes.push_back( - Keystroke(i->second.m_button, false, false, i->second.m_client)); + std::pair range = + activeModifiers.equal_range(keyItem.m_generates); + for (ModifierToKeys::const_iterator i = range.first; i != range.second; ++i) { + keystrokes.push_back(Keystroke(i->second.m_button, false, false, i->second.m_client)); } } @@ -1015,7 +1016,8 @@ void KeyMap::addKeystrokes( } } -SInt32 KeyMap::getNumModifiers(KeyModifierMask state) { +SInt32 KeyMap::getNumModifiers(KeyModifierMask state) +{ SInt32 n = 0; for (; state != 0; state >>= 1) { if ((state & 1) != 0) { @@ -1025,11 +1027,13 @@ SInt32 KeyMap::getNumModifiers(KeyModifierMask state) { return n; } -bool KeyMap::isDeadKey(KeyID key) { +bool KeyMap::isDeadKey(KeyID key) +{ return (key == kKeyCompose || (key >= 0x0300 && key <= 0x036f)); } -KeyID KeyMap::getDeadKey(KeyID key) { +KeyID KeyMap::getDeadKey(KeyID key) +{ if (isDeadKey(key)) { // already dead return key; @@ -1086,7 +1090,8 @@ KeyID KeyMap::getDeadKey(KeyID key) { } } -String KeyMap::formatKey(KeyID key, KeyModifierMask mask) { +String KeyMap::formatKey(KeyID key, KeyModifierMask mask) +{ // initialize tables initKeyNameMaps(); @@ -1115,7 +1120,8 @@ String KeyMap::formatKey(KeyID key, KeyModifierMask mask) { return x; } -bool KeyMap::parseKey(const String &x, KeyID &key) { +bool KeyMap::parseKey(const String &x, KeyID &key) +{ // initialize tables initKeyNameMaps(); @@ -1146,7 +1152,8 @@ bool KeyMap::parseKey(const String &x, KeyID &key) { return true; } -bool KeyMap::parseModifiers(String &x, KeyModifierMask &mask) { +bool KeyMap::parseModifiers(String &x, KeyModifierMask &mask) +{ // initialize tables initKeyNameMaps(); @@ -1200,7 +1207,8 @@ bool KeyMap::parseModifiers(String &x, KeyModifierMask &mask) { return true; } -void KeyMap::initKeyNameMaps() { +void KeyMap::initKeyNameMaps() +{ // initialize tables if (s_nameToKeyMap == NULL) { s_nameToKeyMap = new NameToKeyMap; @@ -1213,8 +1221,7 @@ void KeyMap::initKeyNameMaps() { if (s_nameToModifierMap == NULL) { s_nameToModifierMap = new NameToModifierMap; s_modifierToNameMap = new ModifierToNameMap; - for (const KeyModifierNameMapEntry *i = kModifierNameMap; i->m_name != NULL; - ++i) { + for (const KeyModifierNameMapEntry *i = kModifierNameMap; i->m_name != NULL; ++i) { (*s_nameToModifierMap)[i->m_name] = i->m_mask; (*s_modifierToNameMap)[i->m_mask] = i->m_name; } @@ -1225,29 +1232,29 @@ void KeyMap::initKeyNameMaps() { // KeyMap::KeyItem // -bool KeyMap::KeyItem::operator==(const KeyItem &x) const { +bool KeyMap::KeyItem::operator==(const KeyItem &x) const +{ return ( - m_id == x.m_id && m_group == x.m_group && m_button == x.m_button && - m_required == x.m_required && m_sensitive == x.m_sensitive && - m_generates == x.m_generates && m_dead == x.m_dead && - m_lock == x.m_lock && m_client == x.m_client); + m_id == x.m_id && m_group == x.m_group && m_button == x.m_button && m_required == x.m_required && + m_sensitive == x.m_sensitive && m_generates == x.m_generates && m_dead == x.m_dead && m_lock == x.m_lock && + m_client == x.m_client + ); } // // KeyMap::Keystroke // -KeyMap::Keystroke::Keystroke( - KeyButton button, bool press, bool repeat, UInt32 data) - : m_type(kButton) { +KeyMap::Keystroke::Keystroke(KeyButton button, bool press, bool repeat, UInt32 data) : m_type(kButton) +{ m_data.m_button.m_button = button; m_data.m_button.m_press = press; m_data.m_button.m_repeat = repeat; m_data.m_button.m_client = data; } -KeyMap::Keystroke::Keystroke(SInt32 group, bool absolute, bool restore) - : m_type(kGroup) { +KeyMap::Keystroke::Keystroke(SInt32 group, bool absolute, bool restore) : m_type(kGroup) +{ m_data.m_group.m_group = group; m_data.m_group.m_absolute = absolute; m_data.m_group.m_restore = restore; diff --git a/src/lib/deskflow/KeyMap.h b/src/lib/deskflow/KeyMap.h index eddf77c53..32729a41b 100644 --- a/src/lib/deskflow/KeyMap.h +++ b/src/lib/deskflow/KeyMap.h @@ -34,7 +34,8 @@ namespace deskflow { /*! This class provides a keyboard mapping. */ -class KeyMap { +class KeyMap +{ public: KeyMap(); virtual ~KeyMap(); @@ -48,7 +49,8 @@ public: key is mapped to a modifier, that modifier is in \c m_generates and is not in \c m_sensitive. */ - struct KeyItem { + struct KeyItem + { public: KeyID m_id{}; //!< KeyID SInt32 m_group{}; //!< Group for key @@ -77,9 +79,11 @@ public: typedef std::vector KeyItemList; //! A keystroke - class Keystroke { + class Keystroke + { public: - enum EType { + enum EType + { kButton, //!< Synthesize button kGroup //!< Set new group }; @@ -88,20 +92,23 @@ public: Keystroke(SInt32 group, bool absolute, bool restore); public: - struct Button { + struct Button + { public: KeyButton m_button{}; //!< Button to synthesize bool m_press{}; //!< \c true iff press bool m_repeat{}; //!< \c true iff for an autorepeat UInt32 m_client{}; //!< Client data }; - struct Group { + struct Group + { public: SInt32 m_group{}; //!< Group/offset to change to/by bool m_absolute{}; //!< \c true iff change to, else by bool m_restore{}; //!< \c true iff for restoring state }; - union Data { + union Data + { public: Button m_button; Group m_group; @@ -121,8 +128,7 @@ public: typedef std::map ButtonToKeyMap; //! Callback type for \c foreachKey - typedef void (*ForeachKeyCallback)( - KeyID, SInt32 group, KeyItem &, void *userData); + typedef void (*ForeachKeyCallback)(KeyID, SInt32 group, KeyItem &, void *userData); //! @name manipulators //@{ @@ -148,9 +154,9 @@ public: can generate \p targetID using \p sourceID). */ void addKeyAliasEntry( - KeyID targetID, SInt32 group, KeyModifierMask targetRequired, - KeyModifierMask targetSensitive, KeyID sourceID, - KeyModifierMask sourceRequired, KeyModifierMask sourceSensitive); + KeyID targetID, SInt32 group, KeyModifierMask targetRequired, KeyModifierMask targetSensitive, KeyID sourceID, + KeyModifierMask sourceRequired, KeyModifierMask sourceSensitive + ); //! Add a key sequence entry /*! @@ -162,8 +168,7 @@ public: least one key in \p keys is not in the map then nothing is added and this returns \c false, otherwise it returns \c true. */ - bool addKeyCombinationEntry( - KeyID id, SInt32 group, const KeyID *keys, UInt32 numKeys); + bool addKeyCombinationEntry(KeyID id, SInt32 group, const KeyID *keys, UInt32 numKeys); //! Enable composition across groups /*! @@ -219,9 +224,9 @@ public: pressed/repeated, or NULL if the key cannot be mapped. */ virtual const KeyItem *mapKey( - Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, - KeyModifierMask ¤tState, KeyModifierMask desiredMask, - bool isAutoRepeat, const String &lang) const; + Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState, + KeyModifierMask desiredMask, bool isAutoRepeat, const String &lang + ) const; void setLanguageData(std::vector layouts); @@ -246,9 +251,8 @@ public: it requires the modifiers to be in the state indicated by \p required for every modifier indicated by \p sensitive. */ - const KeyItemList *findCompatibleKey( - KeyID id, SInt32 group, KeyModifierMask required, - KeyModifierMask sensitive) const; + const KeyItemList * + findCompatibleKey(KeyID id, SInt32 group, KeyModifierMask required, KeyModifierMask sensitive) const; //! Test if modifier is half-duplex /*! @@ -279,8 +283,7 @@ public: /*! Put all the keys in \p modifiers into \p keys. */ - static void - collectButtons(const ModifierToKeys &modifiers, ButtonToKeyMap &keys); + static void collectButtons(const ModifierToKeys &modifiers, ButtonToKeyMap &keys); //! Set modifier key state /*! @@ -330,22 +333,17 @@ public: #ifdef TEST_ENV private: FRIEND_TEST(KeyMapTests, findBestKey_requiredDown_matchExactFirstItem); - FRIEND_TEST( - KeyMapTests, - findBestKey_requiredAndExtraSensitiveDown_matchExactFirstItem); - FRIEND_TEST( - KeyMapTests, - findBestKey_requiredAndExtraSensitiveDown_matchExactSecondItem); + FRIEND_TEST(KeyMapTests, findBestKey_requiredAndExtraSensitiveDown_matchExactFirstItem); + FRIEND_TEST(KeyMapTests, findBestKey_requiredAndExtraSensitiveDown_matchExactSecondItem); FRIEND_TEST(KeyMapTests, findBestKey_extraSensitiveDown_matchExactSecondItem); - FRIEND_TEST( - KeyMapTests, findBestKey_noRequiredDown_matchOneRequiredChangeItem); - FRIEND_TEST( - KeyMapTests, findBestKey_onlyOneRequiredDown_matchTwoRequiredChangesItem); + FRIEND_TEST(KeyMapTests, findBestKey_noRequiredDown_matchOneRequiredChangeItem); + FRIEND_TEST(KeyMapTests, findBestKey_onlyOneRequiredDown_matchTwoRequiredChangesItem); FRIEND_TEST(KeyMapTests, findBestKey_noRequiredDown_cannotMatch); #endif private: //! Ways to synthesize a key - enum EKeystroke { + enum EKeystroke + { kKeystrokePress, //!< Synthesize a press kKeystrokeRelease, //!< Synthesize a release kKeystrokeRepeat, //!< Synthesize an autorepeat @@ -370,54 +368,52 @@ private: // to what character they would synthesize. we disallow multikey // entries since they don't make sense as hotkeys. const KeyItem *mapCommandKey( - Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, - KeyModifierMask ¤tState, KeyModifierMask desiredMask, - bool isAutoRepeat, const String &lang) const; + Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState, + KeyModifierMask desiredMask, bool isAutoRepeat, const String &lang + ) const; // maps a character key. a character key is trying to synthesize a // particular KeyID and isn't entirely concerned with the modifiers // used to do it. const KeyItem *mapCharacterKey( - Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, - KeyModifierMask ¤tState, KeyModifierMask desiredMask, - bool isAutoRepeat, const String &lang) const; + Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState, + KeyModifierMask desiredMask, bool isAutoRepeat, const String &lang + ) const; // maps a modifier key const KeyItem *mapModifierKey( - Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, - KeyModifierMask ¤tState, KeyModifierMask desiredMask, - bool isAutoRepeat, const String &lang) const; + Keystrokes &keys, KeyID id, SInt32 group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState, + KeyModifierMask desiredMask, bool isAutoRepeat, const String &lang + ) const; // returns the index into \p entryList of the KeyItemList requiring // the fewest modifier changes between \p currentState and // \p desiredState. - SInt32 findBestKey( - const KeyEntryList &entryList, KeyModifierMask desiredState) const; + SInt32 findBestKey(const KeyEntryList &entryList, KeyModifierMask desiredState) const; // gets the \c KeyItem used to synthesize the modifier who's bit is // given by \p modifierBit in group \p group and does not synthesize // the key \p button. - const KeyItem * - keyForModifier(KeyButton button, SInt32 group, SInt32 modifierBit) const; + const KeyItem *keyForModifier(KeyButton button, SInt32 group, SInt32 modifierBit) const; // fills \p keystrokes with the keys to synthesize the key in // \p keyItem taking the modifiers into account. returns \c true // iff successful and sets \p currentState to the // resulting modifier state. bool keysForKeyItem( - const KeyItem &keyItem, SInt32 &group, ModifierToKeys &activeModifiers, - KeyModifierMask ¤tState, KeyModifierMask desiredState, - KeyModifierMask overrideModifiers, bool isAutoRepeat, - Keystrokes &keystrokes, const String &lang) const; + const KeyItem &keyItem, SInt32 &group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState, + KeyModifierMask desiredState, KeyModifierMask overrideModifiers, bool isAutoRepeat, Keystrokes &keystrokes, + const String &lang + ) const; // fills \p keystrokes with the keys to synthesize the modifiers // in \p desiredModifiers from the active modifiers listed in // \p activeModifiers not including the key in \p keyItem. // returns \c true iff successful. bool keysToRestoreModifiers( - const KeyItem &keyItem, SInt32 group, ModifierToKeys &activeModifiers, - KeyModifierMask ¤tState, const ModifierToKeys &desiredModifiers, - Keystrokes &keystrokes) const; + const KeyItem &keyItem, SInt32 group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState, + const ModifierToKeys &desiredModifiers, Keystrokes &keystrokes + ) const; // fills \p keystrokes and \p undo with the keys to change the // current modifier state in \p currentState to match the state in @@ -425,16 +421,17 @@ private: // returns \c true iff successful and sets \p currentState to the // resulting modifier state. bool keysForModifierState( - KeyButton button, SInt32 group, ModifierToKeys &activeModifiers, - KeyModifierMask ¤tState, KeyModifierMask requiredState, - KeyModifierMask sensitiveMask, KeyModifierMask notRequiredMask, - Keystrokes &keystrokes) const; + KeyButton button, SInt32 group, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState, + KeyModifierMask requiredState, KeyModifierMask sensitiveMask, KeyModifierMask notRequiredMask, + Keystrokes &keystrokes + ) const; // Adds keystrokes to synthesize key \p keyItem in mode \p type to // \p keystrokes and to undo the synthesis to \p undo. void addKeystrokes( - EKeystroke type, const KeyItem &keyItem, ModifierToKeys &activeModifiers, - KeyModifierMask ¤tState, Keystrokes &keystrokes) const; + EKeystroke type, const KeyItem &keyItem, ModifierToKeys &activeModifiers, KeyModifierMask ¤tState, + Keystrokes &keystrokes + ) const; // Returns the number of modifiers indicated in \p state. static SInt32 getNumModifiers(KeyModifierMask state); @@ -445,13 +442,11 @@ private: // Ways to synthesize a KeyID over multiple keyboard groups typedef std::vector KeyGroupTable; - void addGroupToKeystroke( - Keystrokes &keys, SInt32 &group, const String &lang) const; + void addGroupToKeystroke(Keystrokes &keys, SInt32 &group, const String &lang) const; SInt32 getLanguageGroupID(SInt32 group, const String &lang) const; - const KeyItemList *getKeyItemList( - const KeyGroupTable &keyGroupTable, SInt32 group, - KeyModifierMask desiredMask) const; + const KeyItemList * + getKeyItemList(const KeyGroupTable &keyGroupTable, SInt32 group, KeyModifierMask desiredMask) const; // not implemented KeyMap(const KeyMap &); @@ -475,8 +470,7 @@ private: // Key maps for parsing/formatting typedef std::map NameToKeyMap; - typedef std::map - NameToModifierMap; + typedef std::map NameToModifierMap; typedef std::map KeyToNameMap; typedef std::map ModifierToNameMap; diff --git a/src/lib/deskflow/KeyState.cpp b/src/lib/deskflow/KeyState.cpp index 3e159cb75..b3dc5d914 100644 --- a/src/lib/deskflow/KeyState.cpp +++ b/src/lib/deskflow/KeyState.cpp @@ -634,70 +634,65 @@ static const KeyID s_decomposeTable[] = { 0, // yen, y, equal // end of table - 0}; + 0 +}; static const KeyID s_numpadTable[] = { - kKeyKP_Space, 0x0020, kKeyKP_Tab, kKeyTab, - kKeyKP_Enter, kKeyReturn, kKeyKP_F1, kKeyF1, - kKeyKP_F2, kKeyF2, kKeyKP_F3, kKeyF3, - kKeyKP_F4, kKeyF4, kKeyKP_Home, kKeyHome, - kKeyKP_Left, kKeyLeft, kKeyKP_Up, kKeyUp, - kKeyKP_Right, kKeyRight, kKeyKP_Down, kKeyDown, - kKeyKP_PageUp, kKeyPageUp, kKeyKP_PageDown, kKeyPageDown, - kKeyKP_End, kKeyEnd, kKeyKP_Begin, kKeyBegin, - kKeyKP_Insert, kKeyInsert, kKeyKP_Delete, kKeyDelete, - kKeyKP_Equal, 0x003d, kKeyKP_Multiply, 0x002a, - kKeyKP_Add, 0x002b, kKeyKP_Separator, 0x002c, - kKeyKP_Subtract, 0x002d, kKeyKP_Decimal, 0x002e, - kKeyKP_Divide, 0x002f, kKeyKP_0, 0x0030, - kKeyKP_1, 0x0031, kKeyKP_2, 0x0032, - kKeyKP_3, 0x0033, kKeyKP_4, 0x0034, - kKeyKP_5, 0x0035, kKeyKP_6, 0x0036, - kKeyKP_7, 0x0037, kKeyKP_8, 0x0038, - kKeyKP_9, 0x0039}; + kKeyKP_Space, 0x0020, kKeyKP_Tab, kKeyTab, kKeyKP_Enter, kKeyReturn, kKeyKP_F1, kKeyF1, + kKeyKP_F2, kKeyF2, kKeyKP_F3, kKeyF3, kKeyKP_F4, kKeyF4, kKeyKP_Home, kKeyHome, + kKeyKP_Left, kKeyLeft, kKeyKP_Up, kKeyUp, kKeyKP_Right, kKeyRight, kKeyKP_Down, kKeyDown, + kKeyKP_PageUp, kKeyPageUp, kKeyKP_PageDown, kKeyPageDown, kKeyKP_End, kKeyEnd, kKeyKP_Begin, kKeyBegin, + kKeyKP_Insert, kKeyInsert, kKeyKP_Delete, kKeyDelete, kKeyKP_Equal, 0x003d, kKeyKP_Multiply, 0x002a, + kKeyKP_Add, 0x002b, kKeyKP_Separator, 0x002c, kKeyKP_Subtract, 0x002d, kKeyKP_Decimal, 0x002e, + kKeyKP_Divide, 0x002f, kKeyKP_0, 0x0030, kKeyKP_1, 0x0031, kKeyKP_2, 0x0032, + kKeyKP_3, 0x0033, kKeyKP_4, 0x0034, kKeyKP_5, 0x0035, kKeyKP_6, 0x0036, + kKeyKP_7, 0x0037, kKeyKP_8, 0x0038, kKeyKP_9, 0x0039 +}; // // KeyState // -KeyState::KeyState( - IEventQueue *events, std::vector layouts, bool isLangSyncEnabled) +KeyState::KeyState(IEventQueue *events, std::vector layouts, bool isLangSyncEnabled) : IKeyState(events), m_keyMapPtr(new deskflow::KeyMap()), m_keyMap(*m_keyMapPtr), m_mask(0), m_events(events), - m_isLangSyncEnabled(isLangSyncEnabled) { + m_isLangSyncEnabled(isLangSyncEnabled) +{ m_keyMap.setLanguageData(std::move(layouts)); init(); } -KeyState::KeyState( - IEventQueue *events, deskflow::KeyMap &keyMap, std::vector layouts, - bool isLangSyncEnabled) +KeyState::KeyState(IEventQueue *events, deskflow::KeyMap &keyMap, std::vector layouts, bool isLangSyncEnabled) : IKeyState(events), m_keyMapPtr(0), m_keyMap(keyMap), m_mask(0), m_events(events), - m_isLangSyncEnabled(isLangSyncEnabled) { + m_isLangSyncEnabled(isLangSyncEnabled) +{ m_keyMap.setLanguageData(std::move(layouts)); init(); } -KeyState::~KeyState() { +KeyState::~KeyState() +{ if (m_keyMapPtr) delete m_keyMapPtr; } -void KeyState::init() { +void KeyState::init() +{ memset(&m_keys, 0, sizeof(m_keys)); memset(&m_syntheticKeys, 0, sizeof(m_syntheticKeys)); memset(&m_keyClientData, 0, sizeof(m_keyClientData)); memset(&m_serverKeys, 0, sizeof(m_serverKeys)); } -void KeyState::onKey(KeyButton button, bool down, KeyModifierMask newState) { +void KeyState::onKey(KeyButton button, bool down, KeyModifierMask newState) +{ // update modifier state m_mask = newState; LOG((CLOG_DEBUG1 "new mask: 0x%04x", m_mask)); @@ -719,37 +714,29 @@ void KeyState::onKey(KeyButton button, bool down, KeyModifierMask newState) { } void KeyState::sendKeyEvent( - void *target, bool press, bool isAutoRepeat, KeyID key, - KeyModifierMask mask, SInt32 count, KeyButton button) { + void *target, bool press, bool isAutoRepeat, KeyID key, KeyModifierMask mask, SInt32 count, KeyButton button +) +{ if (m_keyMap.isHalfDuplex(key, button)) { if (isAutoRepeat) { // ignore auto-repeat on half-duplex keys } else { - m_events->addEvent(Event( - m_events->forIKeyState().keyDown(), target, - KeyInfo::alloc(key, mask, button, 1))); - m_events->addEvent(Event( - m_events->forIKeyState().keyUp(), target, - KeyInfo::alloc(key, mask, button, 1))); + m_events->addEvent(Event(m_events->forIKeyState().keyDown(), target, KeyInfo::alloc(key, mask, button, 1))); + m_events->addEvent(Event(m_events->forIKeyState().keyUp(), target, KeyInfo::alloc(key, mask, button, 1))); } } else { if (isAutoRepeat) { - m_events->addEvent(Event( - m_events->forIKeyState().keyRepeat(), target, - KeyInfo::alloc(key, mask, button, count))); + m_events->addEvent(Event(m_events->forIKeyState().keyRepeat(), target, KeyInfo::alloc(key, mask, button, count))); } else if (press) { - m_events->addEvent(Event( - m_events->forIKeyState().keyDown(), target, - KeyInfo::alloc(key, mask, button, 1))); + m_events->addEvent(Event(m_events->forIKeyState().keyDown(), target, KeyInfo::alloc(key, mask, button, 1))); } else { - m_events->addEvent(Event( - m_events->forIKeyState().keyUp(), target, - KeyInfo::alloc(key, mask, button, 1))); + m_events->addEvent(Event(m_events->forIKeyState().keyUp(), target, KeyInfo::alloc(key, mask, button, 1))); } } } -void KeyState::updateKeyMap(deskflow::KeyMap *existing) { +void KeyState::updateKeyMap(deskflow::KeyMap *existing) +{ if (existing) { m_keyMap.swap(*existing); } else { @@ -766,7 +753,8 @@ void KeyState::updateKeyMap(deskflow::KeyMap *existing) { addAliasEntries(); } -void KeyState::updateKeyState() { +void KeyState::updateKeyState() +{ // reset our state memset(&m_keys, 0, sizeof(m_keys)); memset(&m_syntheticKeys, 0, sizeof(m_syntheticKeys)); @@ -777,8 +765,7 @@ void KeyState::updateKeyState() { // get the current keyboard state KeyButtonSet keysDown; pollPressedKeys(keysDown); - for (KeyButtonSet::const_iterator i = keysDown.begin(); i != keysDown.end(); - ++i) { + for (KeyButtonSet::const_iterator i = keysDown.begin(); i != keysDown.end(); ++i) { m_keys[*i] = 1; } @@ -786,25 +773,22 @@ void KeyState::updateKeyState() { m_mask = pollActiveModifiers(); // set active modifiers - AddActiveModifierContext addModifierContext( - pollActiveGroup(), m_mask, m_activeModifiers); + AddActiveModifierContext addModifierContext(pollActiveGroup(), m_mask, m_activeModifiers); m_keyMap.foreachKey(&KeyState::addActiveModifierCB, &addModifierContext); LOG((CLOG_DEBUG1 "modifiers on update: 0x%04x", m_mask)); } -void KeyState::addActiveModifierCB( - KeyID, SInt32 group, deskflow::KeyMap::KeyItem &keyItem, void *vcontext) { - AddActiveModifierContext *context = - static_cast(vcontext); - if (group == context->m_activeGroup && - (keyItem.m_generates & context->m_mask) != 0) { - context->m_activeModifiers.insert( - std::make_pair(keyItem.m_generates, keyItem)); +void KeyState::addActiveModifierCB(KeyID, SInt32 group, deskflow::KeyMap::KeyItem &keyItem, void *vcontext) +{ + AddActiveModifierContext *context = static_cast(vcontext); + if (group == context->m_activeGroup && (keyItem.m_generates & context->m_mask) != 0) { + context->m_activeModifiers.insert(std::make_pair(keyItem.m_generates, keyItem)); } } -void KeyState::setHalfDuplexMask(KeyModifierMask mask) { +void KeyState::setHalfDuplexMask(KeyModifierMask mask) +{ m_keyMap.clearHalfDuplexModifiers(); if ((mask & KeyModifierCapsLock) != 0) { m_keyMap.addHalfDuplexModifier(kKeyCapsLock); @@ -817,8 +801,8 @@ void KeyState::setHalfDuplexMask(KeyModifierMask mask) { } } -void KeyState::fakeKeyDown( - KeyID id, KeyModifierMask mask, KeyButton serverID, const String &lang) { +void KeyState::fakeKeyDown(KeyID id, KeyModifierMask mask, KeyButton serverID, const String &lang) +{ // if this server key is already down then this is probably a // mis-reported autorepeat. serverID &= kButtonMask; @@ -835,16 +819,14 @@ void KeyState::fakeKeyDown( Keystrokes keys; ModifierToKeys oldActiveModifiers = m_activeModifiers; - const deskflow::KeyMap::KeyItem *keyItem = m_keyMap.mapKey( - keys, id, pollActiveGroup(), m_activeModifiers, - getActiveModifiersRValue(), mask, false, lang); + const deskflow::KeyMap::KeyItem *keyItem = + m_keyMap.mapKey(keys, id, pollActiveGroup(), m_activeModifiers, getActiveModifiersRValue(), mask, false, lang); if (keyItem == nullptr) { // a media key won't be mapped on mac, so we need to fake it in a // special way - if (id == kKeyAudioDown || id == kKeyAudioUp || id == kKeyAudioMute || - id == kKeyAudioPlay || id == kKeyAudioPrev || id == kKeyAudioNext || - id == kKeyBrightnessDown || id == kKeyBrightnessUp) { + if (id == kKeyAudioDown || id == kKeyAudioUp || id == kKeyAudioMute || id == kKeyAudioPlay || id == kKeyAudioPrev || + id == kKeyAudioNext || id == kKeyBrightnessDown || id == kKeyBrightnessUp) { LOG((CLOG_DEBUG1 "emulating media key")); fakeMediaKey(id); } @@ -866,9 +848,8 @@ void KeyState::fakeKeyDown( fakeKeys(keys, 1); } -bool KeyState::fakeKeyRepeat( - KeyID id, KeyModifierMask mask, SInt32 count, KeyButton serverID, - const String &lang) { +bool KeyState::fakeKeyRepeat(KeyID id, KeyModifierMask mask, SInt32 count, KeyButton serverID, const String &lang) +{ LOG((CLOG_DEBUG2 "fakeKeyRepeat")); serverID &= kButtonMask; @@ -881,9 +862,8 @@ bool KeyState::fakeKeyRepeat( // get keys for key repeat Keystrokes keys; ModifierToKeys oldActiveModifiers = m_activeModifiers; - const deskflow::KeyMap::KeyItem *keyItem = m_keyMap.mapKey( - keys, id, pollActiveGroup(), m_activeModifiers, - getActiveModifiersRValue(), mask, true, lang); + const deskflow::KeyMap::KeyItem *keyItem = + m_keyMap.mapKey(keys, id, pollActiveGroup(), m_activeModifiers, getActiveModifiersRValue(), mask, true, lang); if (keyItem == NULL) { return false; } @@ -901,10 +881,8 @@ bool KeyState::fakeKeyRepeat( if (localID != oldLocalID) { // replace key up with previous KeyButton but leave key down // alone so it uses the new KeyButton. - for (Keystrokes::iterator index = keys.begin(); index != keys.end(); - ++index) { - if (index->m_type == Keystroke::kButton && - index->m_data.m_button.m_button == localID) { + for (Keystrokes::iterator index = keys.begin(); index != keys.end(); ++index) { + if (index->m_type == Keystroke::kButton && index->m_data.m_button.m_button == localID) { index->m_data.m_button.m_button = oldLocalID; break; } @@ -927,7 +905,8 @@ bool KeyState::fakeKeyRepeat( return true; } -bool KeyState::fakeKeyUp(KeyButton serverID) { +bool KeyState::fakeKeyUp(KeyButton serverID) +{ // if we haven't seen this button go down then ignore it KeyButton localID = m_serverKeys[serverID & kButtonMask]; if (localID == 0) { @@ -969,7 +948,8 @@ bool KeyState::fakeKeyUp(KeyButton serverID) { return true; } -void KeyState::fakeAllKeysUp() { +void KeyState::fakeAllKeysUp() +{ Keystrokes keys; for (KeyButton i = 0; i < IKeyState::kNumButtons; ++i) { if (m_syntheticKeys[i] > 0) { @@ -984,21 +964,33 @@ void KeyState::fakeAllKeysUp() { m_mask = pollActiveModifiers(); } -bool KeyState::fakeMediaKey(KeyID id) { return false; } +bool KeyState::fakeMediaKey(KeyID id) +{ + return false; +} -bool KeyState::isKeyDown(KeyButton button) const { +bool KeyState::isKeyDown(KeyButton button) const +{ return (m_keys[button & kButtonMask] > 0); } -KeyModifierMask KeyState::getActiveModifiers() const { return m_mask; } +KeyModifierMask KeyState::getActiveModifiers() const +{ + return m_mask; +} -KeyModifierMask &KeyState::getActiveModifiersRValue() { return m_mask; } +KeyModifierMask &KeyState::getActiveModifiersRValue() +{ + return m_mask; +} -SInt32 KeyState::getEffectiveGroup(SInt32 group, SInt32 offset) const { +SInt32 KeyState::getEffectiveGroup(SInt32 group, SInt32 offset) const +{ return m_keyMap.getEffectiveGroup(group, offset); } -bool KeyState::isIgnoredKey(KeyID key, KeyModifierMask) const { +bool KeyState::isIgnoredKey(KeyID key, KeyModifierMask) const +{ switch (key) { case kKeyCapsLock: case kKeyNumLock: @@ -1010,9 +1002,9 @@ bool KeyState::isIgnoredKey(KeyID key, KeyModifierMask) const { } } -KeyButton KeyState::getButton(KeyID id, SInt32 group) const { - const deskflow::KeyMap::KeyItemList *items = - m_keyMap.findCompatibleKey(id, group, 0, 0); +KeyButton KeyState::getButton(KeyID id, SInt32 group) const +{ + const deskflow::KeyMap::KeyItemList *items = m_keyMap.findCompatibleKey(id, group, 0, 0); if (items == NULL) { return 0; } else { @@ -1020,39 +1012,38 @@ KeyButton KeyState::getButton(KeyID id, SInt32 group) const { } } -void KeyState::addAliasEntries() { +void KeyState::addAliasEntries() +{ for (SInt32 g = 0, n = m_keyMap.getNumGroups(); g < n; ++g) { // if we can't shift any kKeyTab key in a particular group but we can // shift kKeyLeftTab then add a shifted kKeyTab entry that matches a // shifted kKeyLeftTab entry. m_keyMap.addKeyAliasEntry( - kKeyTab, g, KeyModifierShift, KeyModifierShift, kKeyLeftTab, - KeyModifierShift, KeyModifierShift); + kKeyTab, g, KeyModifierShift, KeyModifierShift, kKeyLeftTab, KeyModifierShift, KeyModifierShift + ); // if we have no kKeyLeftTab but we do have a kKeyTab that can be // shifted then add kKeyLeftTab that matches a kKeyTab. - m_keyMap.addKeyAliasEntry( - kKeyLeftTab, g, KeyModifierShift, KeyModifierShift, kKeyTab, 0, - KeyModifierShift); + m_keyMap.addKeyAliasEntry(kKeyLeftTab, g, KeyModifierShift, KeyModifierShift, kKeyTab, 0, KeyModifierShift); // map non-breaking space to space m_keyMap.addKeyAliasEntry(0x20, g, 0, 0, 0xa0, 0, 0); } } -void KeyState::addKeypadEntries() { +void KeyState::addKeypadEntries() +{ // map every numpad key to its equivalent non-numpad key if it's not // on the keyboard. for (SInt32 g = 0, n = m_keyMap.getNumGroups(); g < n; ++g) { - for (size_t i = 0; i < sizeof(s_numpadTable) / sizeof(s_numpadTable[0]); - i += 2) { - m_keyMap.addKeyCombinationEntry( - s_numpadTable[i], g, s_numpadTable + i + 1, 1); + for (size_t i = 0; i < sizeof(s_numpadTable) / sizeof(s_numpadTable[0]); i += 2) { + m_keyMap.addKeyCombinationEntry(s_numpadTable[i], g, s_numpadTable + i + 1, 1); } } } -void KeyState::addCombinationEntries() { +void KeyState::addCombinationEntries() +{ for (SInt32 g = 0, n = m_keyMap.getNumGroups(); g < n; ++g) { // add dead and compose key composition sequences const KeyID *i = s_decomposeTable; @@ -1074,7 +1065,8 @@ void KeyState::addCombinationEntries() { } } -void KeyState::fakeKeys(const Keystrokes &keys, UInt32 count) { +void KeyState::fakeKeys(const Keystrokes &keys, UInt32 count) +{ // do nothing if no keys or no repeats if (count == 0 || keys.empty()) { return; @@ -1089,18 +1081,14 @@ void KeyState::fakeKeys(const Keystrokes &keys, UInt32 count) { Keystrokes::const_iterator start = k; while (count-- > 0) { // send repeating events - for (k = start; k != keys.end() && k->m_type == Keystroke::kButton && - k->m_data.m_button.m_repeat; - ++k) { + for (k = start; k != keys.end() && k->m_type == Keystroke::kButton && k->m_data.m_button.m_repeat; ++k) { fakeKey(*k); } } // note -- k is now on the first non-repeat key after the // repeat keys, exactly where we'd like to continue from. - } else if ( - k->m_type != Keystroke::kGroup || - (!k->m_data.m_group.m_restore && m_isLangSyncEnabled)) { + } else if (k->m_type != Keystroke::kGroup || (!k->m_data.m_group.m_restore && m_isLangSyncEnabled)) { // send event fakeKey(*k); @@ -1114,38 +1102,37 @@ void KeyState::fakeKeys(const Keystrokes &keys, UInt32 count) { } void KeyState::updateModifierKeyState( - KeyButton button, const ModifierToKeys &oldModifiers, - const ModifierToKeys &newModifiers) { + KeyButton button, const ModifierToKeys &oldModifiers, const ModifierToKeys &newModifiers +) +{ // get the pressed modifier buttons before and after deskflow::KeyMap::ButtonToKeyMap oldKeys, newKeys; - for (ModifierToKeys::const_iterator i = oldModifiers.begin(); - i != oldModifiers.end(); ++i) { + for (ModifierToKeys::const_iterator i = oldModifiers.begin(); i != oldModifiers.end(); ++i) { oldKeys.insert(std::make_pair(i->second.m_button, &i->second)); } - for (ModifierToKeys::const_iterator i = newModifiers.begin(); - i != newModifiers.end(); ++i) { + for (ModifierToKeys::const_iterator i = newModifiers.begin(); i != newModifiers.end(); ++i) { newKeys.insert(std::make_pair(i->second.m_button, &i->second)); } // get the modifier buttons that were pressed or released deskflow::KeyMap::ButtonToKeyMap pressed, released; std::set_difference( - oldKeys.begin(), oldKeys.end(), newKeys.begin(), newKeys.end(), - std::inserter(released, released.end()), ButtonToKeyLess()); + oldKeys.begin(), oldKeys.end(), newKeys.begin(), newKeys.end(), std::inserter(released, released.end()), + ButtonToKeyLess() + ); std::set_difference( - newKeys.begin(), newKeys.end(), oldKeys.begin(), oldKeys.end(), - std::inserter(pressed, pressed.end()), ButtonToKeyLess()); + newKeys.begin(), newKeys.end(), oldKeys.begin(), oldKeys.end(), std::inserter(pressed, pressed.end()), + ButtonToKeyLess() + ); // update state - for (deskflow::KeyMap::ButtonToKeyMap::const_iterator i = released.begin(); - i != released.end(); ++i) { + for (deskflow::KeyMap::ButtonToKeyMap::const_iterator i = released.begin(); i != released.end(); ++i) { if (i->first != button) { m_keys[i->first] = 0; m_syntheticKeys[i->first] = 0; } } - for (deskflow::KeyMap::ButtonToKeyMap::const_iterator i = pressed.begin(); - i != pressed.end(); ++i) { + for (deskflow::KeyMap::ButtonToKeyMap::const_iterator i = pressed.begin(); i != pressed.end(); ++i) { if (i->first != button) { m_keys[i->first] = 1; m_syntheticKeys[i->first] = 1; @@ -1159,9 +1146,11 @@ void KeyState::updateModifierKeyState( // KeyState::AddActiveModifierContext::AddActiveModifierContext( - SInt32 group, KeyModifierMask mask, ModifierToKeys &activeModifiers) + SInt32 group, KeyModifierMask mask, ModifierToKeys &activeModifiers +) : m_activeGroup(group), m_mask(mask), - m_activeModifiers(activeModifiers) { + m_activeModifiers(activeModifiers) +{ // do nothing } diff --git a/src/lib/deskflow/KeyState.h b/src/lib/deskflow/KeyState.h index db80fff3b..c87fa3265 100644 --- a/src/lib/deskflow/KeyState.h +++ b/src/lib/deskflow/KeyState.h @@ -26,13 +26,11 @@ This class provides key state services. Subclasses must implement a few platform specific methods. */ -class KeyState : public IKeyState { +class KeyState : public IKeyState +{ public: - KeyState( - IEventQueue *events, std::vector layouts, bool isLangSyncEnabled); - KeyState( - IEventQueue *events, deskflow::KeyMap &keyMap, - std::vector layouts, bool isLangSyncEnabled); + KeyState(IEventQueue *events, std::vector layouts, bool isLangSyncEnabled); + KeyState(IEventQueue *events, deskflow::KeyMap &keyMap, std::vector layouts, bool isLangSyncEnabled); virtual ~KeyState(); //! @name manipulators @@ -54,8 +52,8 @@ public: to the superclass. */ virtual void sendKeyEvent( - void *target, bool press, bool isAutoRepeat, KeyID key, - KeyModifierMask mask, SInt32 count, KeyButton button); + void *target, bool press, bool isAutoRepeat, KeyID key, KeyModifierMask mask, SInt32 count, KeyButton button + ); //@} //! @name accessors @@ -65,15 +63,14 @@ public: void updateKeyMap(deskflow::KeyMap *existing); // IKeyState overrides - void updateKeyMap() override { this->updateKeyMap(nullptr); } + void updateKeyMap() override + { + this->updateKeyMap(nullptr); + } void updateKeyState() override; void setHalfDuplexMask(KeyModifierMask) override; - void fakeKeyDown( - KeyID id, KeyModifierMask mask, KeyButton button, - const String &lang) override; - bool fakeKeyRepeat( - KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, - const String &lang) override; + void fakeKeyDown(KeyID id, KeyModifierMask mask, KeyButton button, const String &lang) override; + bool fakeKeyRepeat(KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang) override; bool fakeKeyUp(KeyButton button) override; void fakeAllKeysUp() override; bool fakeMediaKey(KeyID id) override; @@ -86,7 +83,10 @@ public: virtual SInt32 pollActiveGroup() const override = 0; virtual void pollPressedKeys(KeyButtonSet &pressedKeys) const override = 0; - SInt32 getKeyState(KeyButton keyButton) { return m_keys[keyButton]; } + SInt32 getKeyState(KeyButton keyButton) + { + return m_keys[keyButton]; + } protected: typedef deskflow::KeyMap::Keystroke Keystroke; @@ -144,10 +144,10 @@ private: typedef deskflow::KeyMap::ModifierToKeys ModifierToKeys; public: - struct AddActiveModifierContext { + struct AddActiveModifierContext + { public: - AddActiveModifierContext( - SInt32 group, KeyModifierMask mask, ModifierToKeys &activeModifiers); + AddActiveModifierContext(SInt32 group, KeyModifierMask mask, ModifierToKeys &activeModifiers); public: SInt32 m_activeGroup; @@ -161,11 +161,13 @@ public: }; private: - class ButtonToKeyLess { + class ButtonToKeyLess + { public: bool operator()( - const deskflow::KeyMap::ButtonToKeyMap::value_type &a, - const deskflow::KeyMap::ButtonToKeyMap::value_type b) const { + const deskflow::KeyMap::ButtonToKeyMap::value_type &a, const deskflow::KeyMap::ButtonToKeyMap::value_type b + ) const + { return (a.first < b.first); } }; @@ -192,14 +194,10 @@ private: void fakeKeys(const Keystrokes &, UInt32 count); // update key state to match changes to modifiers - void updateModifierKeyState( - KeyButton button, const ModifierToKeys &oldModifiers, - const ModifierToKeys &newModifiers); + void updateModifierKeyState(KeyButton button, const ModifierToKeys &oldModifiers, const ModifierToKeys &newModifiers); // active modifiers collection callback - static void addActiveModifierCB( - KeyID id, SInt32 group, deskflow::KeyMap::KeyItem &keyItem, - void *vcontext); + static void addActiveModifierCB(KeyID id, SInt32 group, deskflow::KeyMap::KeyItem &keyItem, void *vcontext); private: // must be declared before m_keyMap. used when this class owns the key map. diff --git a/src/lib/deskflow/PacketStreamFilter.cpp b/src/lib/deskflow/PacketStreamFilter.cpp index 5effb78af..d4db25005 100644 --- a/src/lib/deskflow/PacketStreamFilter.cpp +++ b/src/lib/deskflow/PacketStreamFilter.cpp @@ -28,27 +28,30 @@ // PacketStreamFilter // -PacketStreamFilter::PacketStreamFilter( - IEventQueue *events, deskflow::IStream *stream, bool adoptStream) +PacketStreamFilter::PacketStreamFilter(IEventQueue *events, deskflow::IStream *stream, bool adoptStream) : StreamFilter(events, stream, adoptStream), m_size(0), m_inputShutdown(false), - m_events(events) { + m_events(events) +{ // do nothing } -PacketStreamFilter::~PacketStreamFilter() { +PacketStreamFilter::~PacketStreamFilter() +{ // do nothing } -void PacketStreamFilter::close() { +void PacketStreamFilter::close() +{ Lock lock(&m_mutex); m_size = 0; m_buffer.pop(m_buffer.getSize()); StreamFilter::close(); } -UInt32 PacketStreamFilter::read(void *buffer, UInt32 n) { +UInt32 PacketStreamFilter::read(void *buffer, UInt32 n) +{ if (n == 0) { return 0; } @@ -77,14 +80,14 @@ UInt32 PacketStreamFilter::read(void *buffer, UInt32 n) { readPacketSize(); if (m_inputShutdown && m_size == 0) { - m_events->addEvent( - Event(m_events->forIStream().inputShutdown(), getEventTarget())); + m_events->addEvent(Event(m_events->forIStream().inputShutdown(), getEventTarget())); } return n; } -void PacketStreamFilter::write(const void *buffer, UInt32 count) { +void PacketStreamFilter::write(const void *buffer, UInt32 count) +{ // write the length of the payload UInt8 length[4]; length[0] = (UInt8)((count >> 24) & 0xff); @@ -97,40 +100,45 @@ void PacketStreamFilter::write(const void *buffer, UInt32 count) { getStream()->write(buffer, count); } -void PacketStreamFilter::shutdownInput() { +void PacketStreamFilter::shutdownInput() +{ Lock lock(&m_mutex); m_size = 0; m_buffer.pop(m_buffer.getSize()); StreamFilter::shutdownInput(); } -bool PacketStreamFilter::isReady() const { +bool PacketStreamFilter::isReady() const +{ Lock lock(&m_mutex); return isReadyNoLock(); } -UInt32 PacketStreamFilter::getSize() const { +UInt32 PacketStreamFilter::getSize() const +{ Lock lock(&m_mutex); return isReadyNoLock() ? m_size : 0; } -bool PacketStreamFilter::isReadyNoLock() const { +bool PacketStreamFilter::isReadyNoLock() const +{ return (m_size != 0 && m_buffer.getSize() >= m_size); } -void PacketStreamFilter::readPacketSize() { +void PacketStreamFilter::readPacketSize() +{ // note -- m_mutex must be locked on entry if (m_size == 0 && m_buffer.getSize() >= 4) { UInt8 buffer[4]; memcpy(buffer, m_buffer.peek(sizeof(buffer)), sizeof(buffer)); m_buffer.pop(sizeof(buffer)); - m_size = ((UInt32)buffer[0] << 24) | ((UInt32)buffer[1] << 16) | - ((UInt32)buffer[2] << 8) | (UInt32)buffer[3]; + m_size = ((UInt32)buffer[0] << 24) | ((UInt32)buffer[1] << 16) | ((UInt32)buffer[2] << 8) | (UInt32)buffer[3]; } } -bool PacketStreamFilter::readMore() { +bool PacketStreamFilter::readMore() +{ // note if we have whole packet bool wasReady = isReadyNoLock(); @@ -154,7 +162,8 @@ bool PacketStreamFilter::readMore() { return (wasReady != isReady); } -void PacketStreamFilter::filterEvent(const Event &event) { +void PacketStreamFilter::filterEvent(const Event &event) +{ if (event.getType() == m_events->forIStream().inputReady()) { Lock lock(&m_mutex); if (!readMore()) { diff --git a/src/lib/deskflow/PacketStreamFilter.h b/src/lib/deskflow/PacketStreamFilter.h index 7df5a47b9..aa40793a3 100644 --- a/src/lib/deskflow/PacketStreamFilter.h +++ b/src/lib/deskflow/PacketStreamFilter.h @@ -28,10 +28,10 @@ class IEventQueue; /*! Filters a stream to read and write packets. */ -class PacketStreamFilter : public StreamFilter { +class PacketStreamFilter : public StreamFilter +{ public: - PacketStreamFilter( - IEventQueue *events, deskflow::IStream *stream, bool adoptStream = true); + PacketStreamFilter(IEventQueue *events, deskflow::IStream *stream, bool adoptStream = true); ~PacketStreamFilter(); // IStream overrides diff --git a/src/lib/deskflow/PlatformScreen.cpp b/src/lib/deskflow/PlatformScreen.cpp index 536aa1524..7046ce300 100644 --- a/src/lib/deskflow/PlatformScreen.cpp +++ b/src/lib/deskflow/PlatformScreen.cpp @@ -20,76 +20,94 @@ #include "deskflow/App.h" #include "deskflow/ArgsBase.h" -PlatformScreen::PlatformScreen( - IEventQueue *events, deskflow::ClientScrollDirection scrollDirection) +PlatformScreen::PlatformScreen(IEventQueue *events, deskflow::ClientScrollDirection scrollDirection) : IPlatformScreen(events), m_draggingStarted(false), m_fakeDraggingStarted(false), - m_clientScrollDirection(scrollDirection) {} + m_clientScrollDirection(scrollDirection) +{ +} -PlatformScreen::~PlatformScreen() { +PlatformScreen::~PlatformScreen() +{ // do nothing } -void PlatformScreen::updateKeyMap() { getKeyState()->updateKeyMap(); } +void PlatformScreen::updateKeyMap() +{ + getKeyState()->updateKeyMap(); +} -void PlatformScreen::updateKeyState() { +void PlatformScreen::updateKeyState() +{ getKeyState()->updateKeyState(); updateButtons(); } -void PlatformScreen::setHalfDuplexMask(KeyModifierMask mask) { +void PlatformScreen::setHalfDuplexMask(KeyModifierMask mask) +{ getKeyState()->setHalfDuplexMask(mask); } -void PlatformScreen::fakeKeyDown( - KeyID id, KeyModifierMask mask, KeyButton button, const String &lang) { +void PlatformScreen::fakeKeyDown(KeyID id, KeyModifierMask mask, KeyButton button, const String &lang) +{ getKeyState()->fakeKeyDown(id, mask, button, lang); } -bool PlatformScreen::fakeKeyRepeat( - KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, - const String &lang) { +bool PlatformScreen::fakeKeyRepeat(KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang) +{ return getKeyState()->fakeKeyRepeat(id, mask, count, button, lang); } -bool PlatformScreen::fakeKeyUp(KeyButton button) { +bool PlatformScreen::fakeKeyUp(KeyButton button) +{ return getKeyState()->fakeKeyUp(button); } -void PlatformScreen::fakeAllKeysUp() { getKeyState()->fakeAllKeysUp(); } +void PlatformScreen::fakeAllKeysUp() +{ + getKeyState()->fakeAllKeysUp(); +} -bool PlatformScreen::fakeCtrlAltDel() { +bool PlatformScreen::fakeCtrlAltDel() +{ return getKeyState()->fakeCtrlAltDel(); } -bool PlatformScreen::isKeyDown(KeyButton button) const { +bool PlatformScreen::isKeyDown(KeyButton button) const +{ return getKeyState()->isKeyDown(button); } -KeyModifierMask PlatformScreen::getActiveModifiers() const { +KeyModifierMask PlatformScreen::getActiveModifiers() const +{ return getKeyState()->getActiveModifiers(); } -KeyModifierMask PlatformScreen::pollActiveModifiers() const { +KeyModifierMask PlatformScreen::pollActiveModifiers() const +{ return getKeyState()->pollActiveModifiers(); } -SInt32 PlatformScreen::pollActiveGroup() const { +SInt32 PlatformScreen::pollActiveGroup() const +{ return getKeyState()->pollActiveGroup(); } -void PlatformScreen::pollPressedKeys(KeyButtonSet &pressedKeys) const { +void PlatformScreen::pollPressedKeys(KeyButtonSet &pressedKeys) const +{ getKeyState()->pollPressedKeys(pressedKeys); } -bool PlatformScreen::isDraggingStarted() { +bool PlatformScreen::isDraggingStarted() +{ if (App::instance().argsBase().m_enableDragDrop) { return m_draggingStarted; } return false; } -SInt32 PlatformScreen::mapClientScrollDirection(SInt32 x) const { +SInt32 PlatformScreen::mapClientScrollDirection(SInt32 x) const +{ return (x * m_clientScrollDirection); } diff --git a/src/lib/deskflow/PlatformScreen.h b/src/lib/deskflow/PlatformScreen.h index cf363b86f..69e65ffeb 100644 --- a/src/lib/deskflow/PlatformScreen.h +++ b/src/lib/deskflow/PlatformScreen.h @@ -29,18 +29,18 @@ This screen implementation is the superclass of all other screen implementations. It implements a handful of methods and requires subclasses to implement the rest. */ -class PlatformScreen : public IPlatformScreen { +class PlatformScreen : public IPlatformScreen +{ public: PlatformScreen( - IEventQueue *events, deskflow::ClientScrollDirection scrollDirection = - deskflow::ClientScrollDirection::SERVER); + IEventQueue *events, deskflow::ClientScrollDirection scrollDirection = deskflow::ClientScrollDirection::SERVER + ); virtual ~PlatformScreen(); // IScreen overrides virtual void *getEventTarget() const = 0; virtual bool getClipboard(ClipboardID id, IClipboard *) const = 0; - virtual void - getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const = 0; + virtual void getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const = 0; virtual void getCursorPos(SInt32 &x, SInt32 &y) const = 0; // IPrimaryScreen overrides @@ -64,11 +64,8 @@ public: virtual void updateKeyMap(); virtual void updateKeyState(); virtual void setHalfDuplexMask(KeyModifierMask); - virtual void - fakeKeyDown(KeyID id, KeyModifierMask mask, KeyButton button, const String &); - virtual bool fakeKeyRepeat( - KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, - const String &lang); + virtual void fakeKeyDown(KeyID id, KeyModifierMask mask, KeyButton button, const String &); + virtual bool fakeKeyRepeat(KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang); virtual bool fakeKeyUp(KeyButton button); virtual void fakeAllKeysUp(); virtual bool fakeCtrlAltDel(); @@ -78,11 +75,22 @@ public: virtual SInt32 pollActiveGroup() const; virtual void pollPressedKeys(KeyButtonSet &pressedKeys) const; - virtual void setDraggingStarted(bool started) { m_draggingStarted = started; } + virtual void setDraggingStarted(bool started) + { + m_draggingStarted = started; + } virtual bool isDraggingStarted(); - virtual bool isFakeDraggingStarted() { return m_fakeDraggingStarted; } - virtual String &getDraggingFilename() { return m_draggingFilename; } - virtual void clearDraggingFilename() {} + virtual bool isFakeDraggingStarted() + { + return m_fakeDraggingStarted; + } + virtual String &getDraggingFilename() + { + return m_draggingFilename; + } + virtual void clearDraggingFilename() + { + } // IPlatformScreen overrides virtual void enable() = 0; @@ -100,10 +108,12 @@ public: virtual void setSequenceNumber(UInt32) = 0; virtual bool isPrimary() const = 0; - virtual void fakeDraggingFiles(DragFileList fileList) { + virtual void fakeDraggingFiles(DragFileList fileList) + { throw std::runtime_error("fakeDraggingFiles not implemented"); } - virtual const String &getDropTarget() const { + virtual const String &getDropTarget() const + { throw std::runtime_error("getDropTarget not implemented"); } @@ -143,6 +153,5 @@ private: * This member contains client scroll direction. * This member is used only on client side. */ - deskflow::ClientScrollDirection m_clientScrollDirection = - deskflow::ClientScrollDirection::SERVER; + deskflow::ClientScrollDirection m_clientScrollDirection = deskflow::ClientScrollDirection::SERVER; }; diff --git a/src/lib/deskflow/ProtocolUtil.cpp b/src/lib/deskflow/ProtocolUtil.cpp index fabd088cd..a431134bc 100644 --- a/src/lib/deskflow/ProtocolUtil.cpp +++ b/src/lib/deskflow/ProtocolUtil.cpp @@ -32,7 +32,8 @@ namespace { -void writeInt(UInt32 Value, UInt32 Length, std::vector &Buffer) { +void writeInt(UInt32 Value, UInt32 Length, std::vector &Buffer) +{ switch (Length) { case 1: Buffer.push_back(static_cast(Value & 0xffU)); @@ -53,9 +54,8 @@ void writeInt(UInt32 Value, UInt32 Length, std::vector &Buffer) { } } -template -void writeVectorInt( - const std::vector *VectorData, std::vector &Buffer) { +template void writeVectorInt(const std::vector *VectorData, std::vector &Buffer) +{ if (VectorData) { const std::vector &Vector = *VectorData; writeInt((UInt32)Vector.size(), sizeof(UInt32), Buffer); @@ -65,18 +65,19 @@ void writeVectorInt( } } -void writeString(const String *StringData, std::vector &Buffer) { +void writeString(const String *StringData, std::vector &Buffer) +{ const UInt32 len = (StringData != NULL) ? (UInt32)StringData->size() : 0; writeInt(len, sizeof(len), Buffer); if (len != 0) { - std::copy( - StringData->begin(), StringData->end(), std::back_inserter(Buffer)); + std::copy(StringData->begin(), StringData->end(), std::back_inserter(Buffer)); } } } // namespace -void ProtocolUtil::writef(deskflow::IStream *stream, const char *fmt, ...) { +void ProtocolUtil::writef(deskflow::IStream *stream, const char *fmt, ...) +{ assert(stream != NULL); assert(fmt != NULL); LOG((CLOG_DEBUG2 "writef(%s)", fmt)); @@ -90,7 +91,8 @@ void ProtocolUtil::writef(deskflow::IStream *stream, const char *fmt, ...) { va_end(args); } -bool ProtocolUtil::readf(deskflow::IStream *stream, const char *fmt, ...) { +bool ProtocolUtil::readf(deskflow::IStream *stream, const char *fmt, ...) +{ bool result = false; if (stream && fmt) { @@ -111,8 +113,8 @@ bool ProtocolUtil::readf(deskflow::IStream *stream, const char *fmt, ...) { return result; } -void ProtocolUtil::vwritef( - deskflow::IStream *stream, const char *fmt, UInt32 size, va_list args) { +void ProtocolUtil::vwritef(deskflow::IStream *stream, const char *fmt, UInt32 size, va_list args) +{ assert(stream != NULL); assert(fmt != NULL); @@ -130,15 +132,13 @@ void ProtocolUtil::vwritef( stream->write(Buffer.data(), size); LOG((CLOG_DEBUG2 "wrote %d bytes", size)); } catch (const XBase &exception) { - LOG( - (CLOG_DEBUG2 "exception <%s> during wrote %d bytes into stream", - exception.what(), size)); + LOG((CLOG_DEBUG2 "exception <%s> during wrote %d bytes into stream", exception.what(), size)); throw; } } -void ProtocolUtil::vreadf( - deskflow::IStream *stream, const char *fmt, va_list args) { +void ProtocolUtil::vreadf(deskflow::IStream *stream, const char *fmt, va_list args) +{ assert(stream != NULL); assert(fmt != NULL); @@ -166,10 +166,7 @@ void ProtocolUtil::vreadf( break; default: // the length is wrong - LOG( - (CLOG_ERR - "read: length to be read is wrong: '%d' should be 1,2, or 4", - len)); + LOG((CLOG_ERR "read: length to be read is wrong: '%d' should be 1,2, or 4", len)); assert(false); // assert for debugging break; } @@ -181,25 +178,19 @@ void ProtocolUtil::vreadf( switch (len) { case 1: // 1 byte integer - readVector1ByteInt( - stream, *static_cast *>(destination)); + readVector1ByteInt(stream, *static_cast *>(destination)); break; case 2: // 2 byte integer - readVector2BytesInt( - stream, *static_cast *>(destination)); + readVector2BytesInt(stream, *static_cast *>(destination)); break; case 4: // 4 byte integer - readVector4BytesInt( - stream, *static_cast *>(destination)); + readVector4BytesInt(stream, *static_cast *>(destination)); break; default: // the length is wrong - LOG( - (CLOG_ERR - "read: length to be read is wrong: '%d' should be 1,2, or 4", - len)); + LOG((CLOG_ERR "read: length to be read is wrong: '%d' should be 1,2, or 4", len)); assert(false); // assert for debugging break; } @@ -239,7 +230,8 @@ void ProtocolUtil::vreadf( } } -UInt32 ProtocolUtil::getLength(const char *fmt, va_list args) { +UInt32 ProtocolUtil::getLength(const char *fmt, va_list args) +{ UInt32 n = 0; while (*fmt) { if (*fmt == '%') { @@ -300,8 +292,8 @@ UInt32 ProtocolUtil::getLength(const char *fmt, va_list args) { return n; } -void ProtocolUtil::writef( - std::vector &buffer, const char *fmt, va_list args) { +void ProtocolUtil::writef(std::vector &buffer, const char *fmt, va_list args) +{ while (*fmt) { if (*fmt == '%') { // format specifier. determine argument size. @@ -318,24 +310,21 @@ void ProtocolUtil::writef( switch (len) { case 1: { // 1 byte integers - const std::vector *list = - va_arg(args, const std::vector *); + const std::vector *list = va_arg(args, const std::vector *); writeVectorInt(list, buffer); break; } case 2: { // 2 byte integers - const std::vector *list = - va_arg(args, const std::vector *); + const std::vector *list = va_arg(args, const std::vector *); writeVectorInt(list, buffer); break; } case 4: { // 4 byte integers - const std::vector *list = - va_arg(args, const std::vector *); + const std::vector *list = va_arg(args, const std::vector *); writeVectorInt(list, buffer); break; } @@ -381,7 +370,8 @@ void ProtocolUtil::writef( } } -UInt32 ProtocolUtil::eatLength(const char **pfmt) { +UInt32 ProtocolUtil::eatLength(const char **pfmt) +{ const char *fmt = *pfmt; UInt32 n = 0; for (;;) { @@ -426,8 +416,8 @@ UInt32 ProtocolUtil::eatLength(const char **pfmt) { } } -void ProtocolUtil::read( - deskflow::IStream *stream, void *vbuffer, UInt32 count) { +void ProtocolUtil::read(deskflow::IStream *stream, void *vbuffer, UInt32 count) +{ assert(stream != NULL); assert(vbuffer != NULL); @@ -438,9 +428,7 @@ void ProtocolUtil::read( // bail if stream has hungup if (n == 0) { - LOG( - (CLOG_DEBUG2 "unexpected disconnect in readf(), %d bytes left", - count)); + LOG((CLOG_DEBUG2 "unexpected disconnect in readf(), %d bytes left", count)); throw XIOEndOfStream(); } @@ -450,7 +438,8 @@ void ProtocolUtil::read( } } -UInt8 ProtocolUtil::read1ByteInt(deskflow::IStream *stream) { +UInt8 ProtocolUtil::read1ByteInt(deskflow::IStream *stream) +{ const UInt32 BufferSize = 1; std::array buffer = {}; read(stream, buffer.data(), BufferSize); @@ -461,59 +450,58 @@ UInt8 ProtocolUtil::read1ByteInt(deskflow::IStream *stream) { return Result; } -UInt16 ProtocolUtil::read2BytesInt(deskflow::IStream *stream) { +UInt16 ProtocolUtil::read2BytesInt(deskflow::IStream *stream) +{ const UInt32 BufferSize = 2; std::array buffer = {}; read(stream, buffer.data(), BufferSize); - UInt16 Result = static_cast( - (static_cast(buffer[0]) << 8) | static_cast(buffer[1])); + UInt16 Result = static_cast((static_cast(buffer[0]) << 8) | static_cast(buffer[1])); LOG((CLOG_DEBUG2 "readf: read 2 byte integer: %d (0x%x)", Result, Result)); return Result; } -UInt32 ProtocolUtil::read4BytesInt(deskflow::IStream *stream) { +UInt32 ProtocolUtil::read4BytesInt(deskflow::IStream *stream) +{ const int BufferSize = 4; std::array buffer = {}; read(stream, buffer.data(), BufferSize); - UInt32 Result = (static_cast(buffer[0]) << 24) | - (static_cast(buffer[1]) << 16) | - (static_cast(buffer[2]) << 8) | - (static_cast(buffer[3])); + UInt32 Result = (static_cast(buffer[0]) << 24) | (static_cast(buffer[1]) << 16) | + (static_cast(buffer[2]) << 8) | (static_cast(buffer[3])); LOG((CLOG_DEBUG2 "readf: read 4 byte integer: %d (0x%x)", Result, Result)); return Result; } -void ProtocolUtil::readVector1ByteInt( - deskflow::IStream *stream, std::vector &destination) { +void ProtocolUtil::readVector1ByteInt(deskflow::IStream *stream, std::vector &destination) +{ UInt32 size = read4BytesInt(stream); for (UInt32 i = 0; i < size; ++i) { destination.push_back(read1ByteInt(stream)); } } -void ProtocolUtil::readVector2BytesInt( - deskflow::IStream *stream, std::vector &destination) { +void ProtocolUtil::readVector2BytesInt(deskflow::IStream *stream, std::vector &destination) +{ UInt32 size = read4BytesInt(stream); for (UInt32 i = 0; i < size; ++i) { destination.push_back(read2BytesInt(stream)); } } -void ProtocolUtil::readVector4BytesInt( - deskflow::IStream *stream, std::vector &destination) { +void ProtocolUtil::readVector4BytesInt(deskflow::IStream *stream, std::vector &destination) +{ UInt32 size = read4BytesInt(stream); for (UInt32 i = 0; i < size; ++i) { destination.push_back(read4BytesInt(stream)); } } -void ProtocolUtil::readBytes( - deskflow::IStream *stream, UInt32 len, String *destination) { +void ProtocolUtil::readBytes(deskflow::IStream *stream, UInt32 len, String *destination) +{ assert(len == 0); // read the string length @@ -563,6 +551,7 @@ void ProtocolUtil::readBytes( // XIOReadMismatch // -String XIOReadMismatch::getWhat() const throw() { +String XIOReadMismatch::getWhat() const throw() +{ return format("XIOReadMismatch", "ProtocolUtil::readf() mismatch"); } diff --git a/src/lib/deskflow/ProtocolUtil.h b/src/lib/deskflow/ProtocolUtil.h index 3309eb52a..1a2ee4923 100644 --- a/src/lib/deskflow/ProtocolUtil.h +++ b/src/lib/deskflow/ProtocolUtil.h @@ -32,7 +32,8 @@ class IStream; This class provides various functions for implementing the deskflow protocol. */ -class ProtocolUtil { +class ProtocolUtil +{ public: //! Write formatted data /*! @@ -73,8 +74,7 @@ public: static bool readf(deskflow::IStream *, const char *fmt, ...); private: - static void - vwritef(deskflow::IStream *, const char *fmt, UInt32 size, va_list); + static void vwritef(deskflow::IStream *, const char *fmt, UInt32 size, va_list); static void vreadf(deskflow::IStream *, const char *fmt, va_list); static UInt32 getLength(const char *fmt, va_list); @@ -107,7 +107,8 @@ private: Thrown by ProtocolUtil::readf() when the data being read does not match the format. */ -class XIOReadMismatch : public XIO { +class XIOReadMismatch : public XIO +{ public: // XBase overrides virtual String getWhat() const throw(); diff --git a/src/lib/deskflow/Screen.cpp b/src/lib/deskflow/Screen.cpp index 9a0f3f1d9..84dfcdf84 100644 --- a/src/lib/deskflow/Screen.cpp +++ b/src/lib/deskflow/Screen.cpp @@ -38,7 +38,8 @@ Screen::Screen(IPlatformScreen *platformScreen, IEventQueue *events) m_fakeInput(false), m_events(events), m_mock(false), - m_enableDragDrop(false) { + m_enableDragDrop(false) +{ assert(m_screen != NULL); // reset options @@ -47,7 +48,8 @@ Screen::Screen(IPlatformScreen *platformScreen, IEventQueue *events) LOG((CLOG_DEBUG "opened display")); } -Screen::~Screen() { +Screen::~Screen() +{ if (m_mock) { return; } @@ -71,7 +73,8 @@ Screen::~Screen() { if (m_entered == m_isPrimary) { LOG( (CLOG_DEBUG "current screen: entered=%s, primary=%s", // - m_entered ? "yes" : "no", m_isPrimary ? "yes" : "no")); + m_entered ? "yes" : "no", m_isPrimary ? "yes" : "no") + ); if (m_isPrimary) { LOG((CLOG_WARN "current primary screen is not entered on shutdown")); } else { @@ -83,7 +86,8 @@ Screen::~Screen() { LOG((CLOG_DEBUG "closed display")); } -void Screen::enable() { +void Screen::enable() +{ assert(!m_enabled); m_screen->updateKeyMap(); @@ -99,7 +103,8 @@ void Screen::enable() { m_enabled = true; } -void Screen::disable() { +void Screen::disable() +{ assert(m_enabled); if (!m_isPrimary && m_entered) { @@ -118,7 +123,8 @@ void Screen::disable() { m_enabled = false; } -void Screen::enter(KeyModifierMask toggleMask) { +void Screen::enter(KeyModifierMask toggleMask) +{ assert(m_entered == false); LOG((CLOG_INFO "entering screen")); @@ -133,7 +139,8 @@ void Screen::enter(KeyModifierMask toggleMask) { } } -bool Screen::leave() { +bool Screen::leave() +{ assert(m_entered == true); LOG((CLOG_INFO "leaving screen")); @@ -158,31 +165,37 @@ bool Screen::leave() { return true; } -void Screen::reconfigure(UInt32 activeSides) { +void Screen::reconfigure(UInt32 activeSides) +{ assert(m_isPrimary); m_screen->reconfigure(activeSides); } -void Screen::warpCursor(SInt32 x, SInt32 y) { +void Screen::warpCursor(SInt32 x, SInt32 y) +{ assert(m_isPrimary); m_screen->warpCursor(x, y); } -void Screen::setClipboard(ClipboardID id, const IClipboard *clipboard) { +void Screen::setClipboard(ClipboardID id, const IClipboard *clipboard) +{ m_screen->setClipboard(id, clipboard); } -void Screen::grabClipboard(ClipboardID id) { m_screen->setClipboard(id, NULL); } +void Screen::grabClipboard(ClipboardID id) +{ + m_screen->setClipboard(id, NULL); +} -void Screen::screensaver(bool) const { +void Screen::screensaver(bool) const +{ // do nothing } -void Screen::keyDown( - KeyID id, KeyModifierMask mask, KeyButton button, const String &lang) { +void Screen::keyDown(KeyID id, KeyModifierMask mask, KeyButton button, const String &lang) +{ // check for ctrl+alt+del emulation - if (id == kKeyDelete && (mask & (KeyModifierControl | KeyModifierAlt)) == - (KeyModifierControl | KeyModifierAlt)) { + if (id == kKeyDelete && (mask & (KeyModifierControl | KeyModifierAlt)) == (KeyModifierControl | KeyModifierAlt)) { LOG((CLOG_DEBUG "emulating ctrl+alt+del press")); if (m_screen->fakeCtrlAltDel()) { return; @@ -191,41 +204,47 @@ void Screen::keyDown( m_screen->fakeKeyDown(id, mask, button, lang); } -void Screen::keyRepeat( - KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, - const String &lang) { +void Screen::keyRepeat(KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang) +{ assert(!m_isPrimary); m_screen->fakeKeyRepeat(id, mask, count, button, lang); } -void Screen::keyUp(KeyID, KeyModifierMask, KeyButton button) { +void Screen::keyUp(KeyID, KeyModifierMask, KeyButton button) +{ m_screen->fakeKeyUp(button); } -void Screen::mouseDown(ButtonID button) { +void Screen::mouseDown(ButtonID button) +{ m_screen->fakeMouseButton(button, true); } -void Screen::mouseUp(ButtonID button) { +void Screen::mouseUp(ButtonID button) +{ m_screen->fakeMouseButton(button, false); } -void Screen::mouseMove(SInt32 x, SInt32 y) { +void Screen::mouseMove(SInt32 x, SInt32 y) +{ assert(!m_isPrimary); m_screen->fakeMouseMove(x, y); } -void Screen::mouseRelativeMove(SInt32 dx, SInt32 dy) { +void Screen::mouseRelativeMove(SInt32 dx, SInt32 dy) +{ assert(!m_isPrimary); m_screen->fakeMouseRelativeMove(dx, dy); } -void Screen::mouseWheel(SInt32 xDelta, SInt32 yDelta) const { +void Screen::mouseWheel(SInt32 xDelta, SInt32 yDelta) const +{ assert(!m_isPrimary); m_screen->fakeMouseWheel(xDelta, yDelta); } -void Screen::resetOptions() { +void Screen::resetOptions() +{ // reset options m_halfDuplex = 0; @@ -233,7 +252,8 @@ void Screen::resetOptions() { m_screen->resetOptions(); } -void Screen::setOptions(const OptionsList &options) { +void Screen::setOptions(const OptionsList &options) +{ // update options for (UInt32 i = 0, n = (UInt32)options.size(); i < n; i += 2) { if (options[i] == kOptionHalfDuplexCapsLock) { @@ -242,27 +262,21 @@ void Screen::setOptions(const OptionsList &options) { } else { m_halfDuplex &= ~KeyModifierCapsLock; } - LOG( - (CLOG_DEBUG1 "half-duplex caps-lock %s", - ((m_halfDuplex & KeyModifierCapsLock) != 0) ? "on" : "off")); + LOG((CLOG_DEBUG1 "half-duplex caps-lock %s", ((m_halfDuplex & KeyModifierCapsLock) != 0) ? "on" : "off")); } else if (options[i] == kOptionHalfDuplexNumLock) { if (options[i + 1] != 0) { m_halfDuplex |= KeyModifierNumLock; } else { m_halfDuplex &= ~KeyModifierNumLock; } - LOG( - (CLOG_DEBUG1 "half-duplex num-lock %s", - ((m_halfDuplex & KeyModifierNumLock) != 0) ? "on" : "off")); + LOG((CLOG_DEBUG1 "half-duplex num-lock %s", ((m_halfDuplex & KeyModifierNumLock) != 0) ? "on" : "off")); } else if (options[i] == kOptionHalfDuplexScrollLock) { if (options[i + 1] != 0) { m_halfDuplex |= KeyModifierScrollLock; } else { m_halfDuplex &= ~KeyModifierScrollLock; } - LOG( - (CLOG_DEBUG1 "half-duplex scroll-lock %s", - ((m_halfDuplex & KeyModifierScrollLock) != 0) ? "on" : "off")); + LOG((CLOG_DEBUG1 "half-duplex scroll-lock %s", ((m_halfDuplex & KeyModifierScrollLock) != 0) ? "on" : "off")); } } @@ -273,33 +287,44 @@ void Screen::setOptions(const OptionsList &options) { m_screen->setOptions(options); } -void Screen::setSequenceNumber(UInt32 seqNum) { +void Screen::setSequenceNumber(UInt32 seqNum) +{ m_screen->setSequenceNumber(seqNum); } -UInt32 Screen::registerHotKey(KeyID key, KeyModifierMask mask) { +UInt32 Screen::registerHotKey(KeyID key, KeyModifierMask mask) +{ return m_screen->registerHotKey(key, mask); } -void Screen::unregisterHotKey(UInt32 id) { m_screen->unregisterHotKey(id); } +void Screen::unregisterHotKey(UInt32 id) +{ + m_screen->unregisterHotKey(id); +} -void Screen::fakeInputBegin() { +void Screen::fakeInputBegin() +{ assert(!m_fakeInput); m_fakeInput = true; m_screen->fakeInputBegin(); } -void Screen::fakeInputEnd() { +void Screen::fakeInputEnd() +{ assert(m_fakeInput); m_fakeInput = false; m_screen->fakeInputEnd(); } -bool Screen::isOnScreen() const { return m_entered; } +bool Screen::isOnScreen() const +{ + return m_entered; +} -bool Screen::isLockedToScreen() const { +bool Screen::isLockedToScreen() const +{ // check for pressed mouse buttons // HACK: commented out as it breaks new drag drop feature UInt32 buttonID = 0; @@ -320,7 +345,8 @@ bool Screen::isLockedToScreen() const { return false; } -SInt32 Screen::getJumpZoneSize() const { +SInt32 Screen::getJumpZoneSize() const +{ if (!m_isPrimary) { return 0; } else { @@ -328,105 +354,136 @@ SInt32 Screen::getJumpZoneSize() const { } } -void Screen::getCursorCenter(SInt32 &x, SInt32 &y) const { +void Screen::getCursorCenter(SInt32 &x, SInt32 &y) const +{ m_screen->getCursorCenter(x, y); } -KeyModifierMask Screen::getActiveModifiers() const { +KeyModifierMask Screen::getActiveModifiers() const +{ return m_screen->getActiveModifiers(); } -KeyModifierMask Screen::pollActiveModifiers() const { +KeyModifierMask Screen::pollActiveModifiers() const +{ return m_screen->pollActiveModifiers(); } -bool Screen::isDraggingStarted() const { return m_screen->isDraggingStarted(); } +bool Screen::isDraggingStarted() const +{ + return m_screen->isDraggingStarted(); +} -bool Screen::isFakeDraggingStarted() const { +bool Screen::isFakeDraggingStarted() const +{ return m_screen->isFakeDraggingStarted(); } -void Screen::setDraggingStarted(bool started) { +void Screen::setDraggingStarted(bool started) +{ m_screen->setDraggingStarted(started); } -void Screen::startDraggingFiles(DragFileList &fileList) { +void Screen::startDraggingFiles(DragFileList &fileList) +{ m_screen->fakeDraggingFiles(fileList); } -void Screen::setEnableDragDrop(bool enabled) { m_enableDragDrop = enabled; } +void Screen::setEnableDragDrop(bool enabled) +{ + m_enableDragDrop = enabled; +} -String &Screen::getDraggingFilename() const { +String &Screen::getDraggingFilename() const +{ return m_screen->getDraggingFilename(); } -void Screen::clearDraggingFilename() { m_screen->clearDraggingFilename(); } +void Screen::clearDraggingFilename() +{ + m_screen->clearDraggingFilename(); +} -const String &Screen::getDropTarget() const { +const String &Screen::getDropTarget() const +{ return m_screen->getDropTarget(); } -void *Screen::getEventTarget() const { return m_screen; } +void *Screen::getEventTarget() const +{ + return m_screen; +} -bool Screen::getClipboard(ClipboardID id, IClipboard *clipboard) const { +bool Screen::getClipboard(ClipboardID id, IClipboard *clipboard) const +{ return m_screen->getClipboard(id, clipboard); } -void Screen::getShape(SInt32 &x, SInt32 &y, SInt32 &w, SInt32 &h) const { +void Screen::getShape(SInt32 &x, SInt32 &y, SInt32 &w, SInt32 &h) const +{ m_screen->getShape(x, y, w, h); } -void Screen::getCursorPos(SInt32 &x, SInt32 &y) const { +void Screen::getCursorPos(SInt32 &x, SInt32 &y) const +{ m_screen->getCursorPos(x, y); } -void Screen::enablePrimary() { +void Screen::enablePrimary() +{ // get notified of screen saver activation/deactivation m_screen->openScreensaver(true); // claim screen changed size - m_events->addEvent( - Event(m_events->forIScreen().shapeChanged(), getEventTarget())); + m_events->addEvent(Event(m_events->forIScreen().shapeChanged(), getEventTarget())); } -void Screen::enableSecondary() { +void Screen::enableSecondary() +{ // assume primary has all clipboards for (ClipboardID id = 0; id < kClipboardEnd; ++id) { grabClipboard(id); } } -void Screen::disablePrimary() { +void Screen::disablePrimary() +{ // done with screen saver m_screen->closeScreensaver(); } -void Screen::disableSecondary() { +void Screen::disableSecondary() +{ // done with screen saver m_screen->closeScreensaver(); } -void Screen::enterPrimary() { +void Screen::enterPrimary() +{ // do nothing } -void Screen::enterSecondary(KeyModifierMask) { +void Screen::enterSecondary(KeyModifierMask) +{ // do nothing } -void Screen::leavePrimary() { +void Screen::leavePrimary() +{ // we don't track keys while on the primary screen so update our // idea of them now. this is particularly to update the state of // the toggle modifiers. m_screen->updateKeyState(); } -void Screen::leaveSecondary() { +void Screen::leaveSecondary() +{ // release any keys we think are still down m_screen->fakeAllKeysUp(); } -String Screen::getSecureInputApp() const { +String Screen::getSecureInputApp() const +{ return m_screen->getSecureInputApp(); } diff --git a/src/lib/deskflow/Screen.h b/src/lib/deskflow/Screen.h index e9d7c5a40..9e4c3ef63 100644 --- a/src/lib/deskflow/Screen.h +++ b/src/lib/deskflow/Screen.h @@ -37,7 +37,8 @@ namespace deskflow { This is a platform independent screen. It can work as either a primary or secondary screen. */ -class Screen : public IScreen { +class Screen : public IScreen +{ public: Screen(IPlatformScreen *platformScreen, IEventQueue *events); Screen(Screen const &) = delete; @@ -48,7 +49,9 @@ public: Screen &operator&(Screen &&) = delete; #ifdef TEST_ENV - Screen() : m_mock(true) {} + Screen() : m_mock(true) + { + } #endif //! @name manipulators @@ -134,8 +137,7 @@ public: Synthesize key events to generate a press and release of key \c id \c count times. If possible match the given modifier mask. */ - void keyRepeat( - KeyID id, KeyModifierMask, SInt32 count, KeyButton, const String &lang); + void keyRepeat(KeyID id, KeyModifierMask, SInt32 count, KeyButton, const String &lang); //! Notify of key release /*! @@ -309,11 +311,13 @@ public: // IScreen overrides virtual void *getEventTarget() const; virtual bool getClipboard(ClipboardID id, IClipboard *) const; - virtual void - getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const; + virtual void getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const; virtual void getCursorPos(SInt32 &x, SInt32 &y) const; - IPlatformScreen *getPlatformScreen() { return m_screen; } + IPlatformScreen *getPlatformScreen() + { + return m_screen; + } protected: void enablePrimary(); diff --git a/src/lib/deskflow/ServerApp.cpp b/src/lib/deskflow/ServerApp.cpp index cf7f5b9a7..bb3782f54 100644 --- a/src/lib/deskflow/ServerApp.cpp +++ b/src/lib/deskflow/ServerApp.cpp @@ -80,8 +80,7 @@ using namespace deskflow::server; // ServerApp // -ServerApp::ServerApp( - IEventQueue *events, CreateTaskBarReceiverFunc createTaskBarReceiver) +ServerApp::ServerApp(IEventQueue *events, CreateTaskBarReceiverFunc createTaskBarReceiver) : App(events, createTaskBarReceiver, new deskflow::ServerArgs()), m_server(NULL), m_serverState(kUninitialized), @@ -89,11 +88,16 @@ ServerApp::ServerApp( m_primaryClient(NULL), m_listener(NULL), m_timer(NULL), - m_deskflowAddress(NULL) {} + m_deskflowAddress(NULL) +{ +} -ServerApp::~ServerApp() {} +ServerApp::~ServerApp() +{ +} -void ServerApp::parseArgs(int argc, const char *const *argv) { +void ServerApp::parseArgs(int argc, const char *const *argv) +{ ArgParser argParser(this); bool result = argParser.parseServerArgs(args(), argc, argv); @@ -107,8 +111,7 @@ void ServerApp::parseArgs(int argc, const char *const *argv) { } else { if (!args().m_deskflowAddress.empty()) { try { - *m_deskflowAddress = - NetworkAddress(args().m_deskflowAddress, kDefaultPort); + *m_deskflowAddress = NetworkAddress(args().m_deskflowAddress, kDefaultPort); m_deskflowAddress->resolve(); } catch (XSocketAddress &e) { LOG((CLOG_CRIT "%s: %s" BYE, args().m_pname, e.what(), args().m_pname)); @@ -118,68 +121,67 @@ void ServerApp::parseArgs(int argc, const char *const *argv) { } } -void ServerApp::help() { - const auto userConfig = - ARCH->concatPath(ARCH->getUserDirectory(), USER_CONFIG_NAME); - const auto sysConfig = - ARCH->concatPath(ARCH->getSystemDirectory(), SYSTEM_CONFIG_NAME); +void ServerApp::help() +{ + const auto userConfig = ARCH->concatPath(ARCH->getUserDirectory(), USER_CONFIG_NAME); + const auto sysConfig = ARCH->concatPath(ARCH->getSystemDirectory(), SYSTEM_CONFIG_NAME); std::stringstream help; - help - << "Usage: " << args().m_pname + help << "Usage: " << args().m_pname - << " [--address
]" - << " [--config ]" + << " [--address
]" + << " [--config ]" #if WINAPI_XWINDOWS - << " [--display ] [--no-xinitthreads]" + << " [--display ] [--no-xinitthreads]" #endif #ifdef WINAPI_LIBEI - << " [--no-wayland-ei]" + << " [--no-wayland-ei]" #endif - << HELP_SYS_ARGS HELP_COMMON_ARGS "\n\n" - << "Start the " DESKFLOW_APP_NAME " mouse/keyboard sharing server.\n" - << "\n" - << " -a, --address
listen for clients on the given address.\n" - << " -c, --config use the named configuration file " - << "instead.\n" HELP_COMMON_INFO_1 + << HELP_SYS_ARGS HELP_COMMON_ARGS "\n\n" + << "Start the " DESKFLOW_APP_NAME " mouse/keyboard sharing server.\n" + << "\n" + << " -a, --address
listen for clients on the given address.\n" + << " -c, --config use the named configuration file " + << "instead.\n" HELP_COMMON_INFO_1 #if WINAPI_XWINDOWS - << " --display when in X mode, connect to the X server\n" - << " at .\n" - << " --no-xinitthreads do not call XInitThreads()\n" + << " --display when in X mode, connect to the X server\n" + << " at .\n" + << " --no-xinitthreads do not call XInitThreads()\n" #endif - << HELP_SYS_INFO HELP_COMMON_INFO_2 "\n" - << "* marks defaults.\n" + << HELP_SYS_INFO HELP_COMMON_INFO_2 "\n" + << "* marks defaults.\n" - << kHelpNoWayland + << kHelpNoWayland - << "\n" - << "The argument for --address is of the form: [][:]. " - "The\n" - << "hostname must be the address or hostname of an interface on the " - << "system.\n" - << "The default is to listen on all interfaces. The port overrides the\n" - << "default port, " << kDefaultPort << ".\n" - << "\n" - << "If no configuration file pathname is provided then the first of the\n" - << "following to load successfully sets the configuration:\n" - << " " << userConfig << "\n" - << " " << sysConfig << "\n"; + << "\n" + << "The argument for --address is of the form: [][:]. " + "The\n" + << "hostname must be the address or hostname of an interface on the " + << "system.\n" + << "The default is to listen on all interfaces. The port overrides the\n" + << "default port, " << kDefaultPort << ".\n" + << "\n" + << "If no configuration file pathname is provided then the first of the\n" + << "following to load successfully sets the configuration:\n" + << " " << userConfig << "\n" + << " " << sysConfig << "\n"; LOG((CLOG_PRINT "%s", help.str().c_str())); } -void ServerApp::reloadSignalHandler(Arch::ESignal, void *) { +void ServerApp::reloadSignalHandler(Arch::ESignal, void *) +{ IEventQueue *events = App::instance().getEvents(); - events->addEvent( - Event(events->forServerApp().reloadConfig(), events->getSystemTarget())); + events->addEvent(Event(events->forServerApp().reloadConfig(), events->getSystemTarget())); } -void ServerApp::reloadConfig(const Event &, void *) { +void ServerApp::reloadConfig(const Event &, void *) +{ LOG((CLOG_DEBUG "reload configuration")); if (loadConfig(args().m_configFile)) { if (m_server != NULL) { @@ -189,7 +191,8 @@ void ServerApp::reloadConfig(const Event &, void *) { } } -void ServerApp::loadConfig() { +void ServerApp::loadConfig() +{ bool loaded = false; std::string path; @@ -227,14 +230,13 @@ void ServerApp::loadConfig() { } if (!loaded) { - LOG( - (CLOG_CRIT "%s: failed to load config: %s", args().m_pname, - path.c_str())); + LOG((CLOG_CRIT "%s: failed to load config: %s", args().m_pname, path.c_str())); m_bye(kExitConfig); } } -bool ServerApp::loadConfig(const String &pathname) { +bool ServerApp::loadConfig(const String &pathname) +{ try { // load configuration LOG((CLOG_DEBUG "opening configuration \"%s\"", pathname.c_str())); @@ -251,20 +253,20 @@ bool ServerApp::loadConfig(const String &pathname) { return true; } catch (XConfigRead &e) { // report error in configuration file - LOG( - (CLOG_ERR "cannot read configuration \"%s\": %s", pathname.c_str(), - e.what())); + LOG((CLOG_ERR "cannot read configuration \"%s\": %s", pathname.c_str(), e.what())); } return false; } -void ServerApp::forceReconnect(const Event &, void *) { +void ServerApp::forceReconnect(const Event &, void *) +{ if (m_server != NULL) { m_server->disconnect(); } } -void ServerApp::handleClientConnected(const Event &, void *vlistener) { +void ServerApp::handleClientConnected(const Event &, void *vlistener) +{ ClientListener *listener = static_cast(vlistener); ClientProxy *client = listener->getNextClient(); if (client != NULL) { @@ -273,11 +275,13 @@ void ServerApp::handleClientConnected(const Event &, void *vlistener) { } } -void ServerApp::handleClientsDisconnected(const Event &, void *) { +void ServerApp::handleClientsDisconnected(const Event &, void *) +{ m_events->addEvent(Event(Event::kQuit)); } -void ServerApp::closeServer(Server *server) { +void ServerApp::closeServer(Server *server) +{ if (server == NULL) { return; } @@ -289,13 +293,12 @@ void ServerApp::closeServer(Server *server) { double timeout = 3.0; EventQueueTimer *timer = m_events->newOneShotTimer(timeout, NULL); m_events->adoptHandler( - Event::kTimer, timer, - new TMethodEventJob( - this, &ServerApp::handleClientsDisconnected)); + Event::kTimer, timer, new TMethodEventJob(this, &ServerApp::handleClientsDisconnected) + ); m_events->adoptHandler( m_events->forServer().disconnected(), server, - new TMethodEventJob( - this, &ServerApp::handleClientsDisconnected)); + new TMethodEventJob(this, &ServerApp::handleClientsDisconnected) + ); m_events->loop(); @@ -307,7 +310,8 @@ void ServerApp::closeServer(Server *server) { delete server; } -void ServerApp::stopRetryTimer() { +void ServerApp::stopRetryTimer() +{ if (m_timer != NULL) { m_events->removeHandler(Event::kTimer, m_timer); m_events->deleteTimer(m_timer); @@ -315,22 +319,28 @@ void ServerApp::stopRetryTimer() { } } -void ServerApp::updateStatus() { updateStatus(""); } +void ServerApp::updateStatus() +{ + updateStatus(""); +} -void ServerApp::updateStatus(const String &msg) { +void ServerApp::updateStatus(const String &msg) +{ if (m_taskBarReceiver) { m_taskBarReceiver->updateStatus(m_server, msg); } } -void ServerApp::closeClientListener(ClientListener *listen) { +void ServerApp::closeClientListener(ClientListener *listen) +{ if (listen != NULL) { m_events->removeHandler(m_events->forClientListener().connected(), listen); delete listen; } } -void ServerApp::stopServer() { +void ServerApp::stopServer() +{ if (m_serverState == kStarted) { closeServer(m_server); closeClientListener(m_listener); @@ -345,23 +355,23 @@ void ServerApp::stopServer() { assert(m_listener == NULL); } -void ServerApp::closePrimaryClient(PrimaryClient *primaryClient) { +void ServerApp::closePrimaryClient(PrimaryClient *primaryClient) +{ delete primaryClient; } -void ServerApp::closeServerScreen(deskflow::Screen *screen) { +void ServerApp::closeServerScreen(deskflow::Screen *screen) +{ if (screen != NULL) { - m_events->removeHandler( - m_events->forIScreen().error(), screen->getEventTarget()); - m_events->removeHandler( - m_events->forIScreen().suspend(), screen->getEventTarget()); - m_events->removeHandler( - m_events->forIScreen().resume(), screen->getEventTarget()); + m_events->removeHandler(m_events->forIScreen().error(), screen->getEventTarget()); + m_events->removeHandler(m_events->forIScreen().suspend(), screen->getEventTarget()); + m_events->removeHandler(m_events->forIScreen().resume(), screen->getEventTarget()); delete screen; } } -void ServerApp::cleanupServer() { +void ServerApp::cleanupServer() +{ stopServer(); if (m_serverState == kInitialized) { closePrimaryClient(m_primaryClient); @@ -369,8 +379,7 @@ void ServerApp::cleanupServer() { m_primaryClient = NULL; m_serverScreen = NULL; m_serverState = kUninitialized; - } else if ( - m_serverState == kInitializing || m_serverState == kInitializingToStart) { + } else if (m_serverState == kInitializing || m_serverState == kInitializingToStart) { stopRetryTimer(); m_serverState = kUninitialized; } @@ -379,7 +388,8 @@ void ServerApp::cleanupServer() { assert(m_serverState == kUninitialized); } -void ServerApp::retryHandler(const Event &, void *) { +void ServerApp::retryHandler(const Event &, void *) +{ // discard old timer assert(m_timer != NULL); stopRetryTimer(); @@ -423,7 +433,8 @@ void ServerApp::retryHandler(const Event &, void *) { } } -bool ServerApp::initServer() { +bool ServerApp::initServer() +{ // skip if already initialized or initializing if (m_serverState != kUninitialized) { return true; @@ -464,9 +475,7 @@ bool ServerApp::initServer() { assert(m_timer == NULL); LOG((CLOG_DEBUG "retry in %.0f seconds", retryTime)); m_timer = m_events->newOneShotTimer(retryTime, NULL); - m_events->adoptHandler( - Event::kTimer, m_timer, - new TMethodEventJob(this, &ServerApp::retryHandler)); + m_events->adoptHandler(Event::kTimer, m_timer, new TMethodEventJob(this, &ServerApp::retryHandler)); m_serverState = kInitializing; return true; } else { @@ -475,22 +484,27 @@ bool ServerApp::initServer() { } } -deskflow::Screen *ServerApp::openServerScreen() { +deskflow::Screen *ServerApp::openServerScreen() +{ deskflow::Screen *screen = createScreen(); screen->setEnableDragDrop(argsBase().m_enableDragDrop); m_events->adoptHandler( m_events->forIScreen().error(), screen->getEventTarget(), - new TMethodEventJob(this, &ServerApp::handleScreenError)); + new TMethodEventJob(this, &ServerApp::handleScreenError) + ); m_events->adoptHandler( m_events->forIScreen().suspend(), screen->getEventTarget(), - new TMethodEventJob(this, &ServerApp::handleSuspend)); + new TMethodEventJob(this, &ServerApp::handleSuspend) + ); m_events->adoptHandler( m_events->forIScreen().resume(), screen->getEventTarget(), - new TMethodEventJob(this, &ServerApp::handleResume)); + new TMethodEventJob(this, &ServerApp::handleResume) + ); return screen; } -bool ServerApp::startServer() { +bool ServerApp::startServer() +{ // skip if already started or starting if (m_serverState == kStarting || m_serverState == kStarted) { return true; @@ -541,9 +555,7 @@ bool ServerApp::startServer() { const auto retryTime = 10.0; LOG((CLOG_DEBUG "retry in %.0f seconds", retryTime)); m_timer = m_events->newOneShotTimer(retryTime, NULL); - m_events->adoptHandler( - Event::kTimer, m_timer, - new TMethodEventJob(this, &ServerApp::retryHandler)); + m_events->adoptHandler(Event::kTimer, m_timer, new TMethodEventJob(this, &ServerApp::retryHandler)); m_serverState = kStarting; return true; } else { @@ -552,20 +564,19 @@ bool ServerApp::startServer() { } } -deskflow::Screen *ServerApp::createScreen() { +deskflow::Screen *ServerApp::createScreen() +{ #if WINAPI_MSWINDOWS return new deskflow::Screen( - new MSWindowsScreen( - true, args().m_noHooks, args().m_stopOnDeskSwitch, m_events), - m_events); + new MSWindowsScreen(true, args().m_noHooks, args().m_stopOnDeskSwitch, m_events), m_events + ); #endif #if defined(WINAPI_XWINDOWS) or defined(WINAPI_LIBEI) if (deskflow::platform::isWayland()) { #if WINAPI_LIBEI LOG((CLOG_INFO "using ei screen for wayland")); - return new deskflow::Screen( - new deskflow::EiScreen(true, m_events, true), m_events); + return new deskflow::Screen(new deskflow::EiScreen(true, m_events, true), m_events); #else throw XNoEiSupport(); #endif @@ -575,26 +586,27 @@ deskflow::Screen *ServerApp::createScreen() { #if WINAPI_XWINDOWS LOG((CLOG_INFO "using legacy x windows screen")); return new deskflow::Screen( - new XWindowsScreen( - args().m_display, true, args().m_disableXInitThreads, 0, m_events), - m_events); + new XWindowsScreen(args().m_display, true, args().m_disableXInitThreads, 0, m_events), m_events + ); #elif WINAPI_CARBON return new deskflow::Screen(new OSXScreen(m_events, true), m_events); #endif } -PrimaryClient * -ServerApp::openPrimaryClient(const String &name, deskflow::Screen *screen) { +PrimaryClient *ServerApp::openPrimaryClient(const String &name, deskflow::Screen *screen) +{ LOG((CLOG_DEBUG1 "creating primary screen")); return new PrimaryClient(name, screen); } -void ServerApp::handleScreenError(const Event &, void *) { +void ServerApp::handleScreenError(const Event &, void *) +{ LOG((CLOG_CRIT "error on screen")); m_events->addEvent(Event(Event::kQuit)); } -void ServerApp::handleSuspend(const Event &, void *) { +void ServerApp::handleSuspend(const Event &, void *) +{ if (!m_suspended) { LOG((CLOG_INFO "suspend")); stopServer(); @@ -602,7 +614,8 @@ void ServerApp::handleSuspend(const Event &, void *) { } } -void ServerApp::handleResume(const Event &, void *) { +void ServerApp::handleResume(const Event &, void *) +{ if (m_suspended) { LOG((CLOG_INFO "resume")); startServer(); @@ -610,30 +623,30 @@ void ServerApp::handleResume(const Event &, void *) { } } -ClientListener *ServerApp::openClientListener(const NetworkAddress &address) { - ClientListener *listen = new ClientListener( - getAddress(address), getSocketFactory(), m_events, args().m_enableCrypto); +ClientListener *ServerApp::openClientListener(const NetworkAddress &address) +{ + ClientListener *listen = new ClientListener(getAddress(address), getSocketFactory(), m_events, args().m_enableCrypto); m_events->adoptHandler( m_events->forClientListener().connected(), listen, - new TMethodEventJob( - this, &ServerApp::handleClientConnected, listen)); + new TMethodEventJob(this, &ServerApp::handleClientConnected, listen) + ); return listen; } -Server * -ServerApp::openServer(ServerConfig &config, PrimaryClient *primaryClient) { - Server *server = - new Server(config, primaryClient, m_serverScreen, m_events, args()); +Server *ServerApp::openServer(ServerConfig &config, PrimaryClient *primaryClient) +{ + Server *server = new Server(config, primaryClient, m_serverScreen, m_events, args()); try { m_events->adoptHandler( - m_events->forServer().disconnected(), server, - new TMethodEventJob(this, &ServerApp::handleNoClients)); + m_events->forServer().disconnected(), server, new TMethodEventJob(this, &ServerApp::handleNoClients) + ); m_events->adoptHandler( m_events->forServer().screenSwitched(), server, - new TMethodEventJob(this, &ServerApp::handleScreenSwitched)); + new TMethodEventJob(this, &ServerApp::handleScreenSwitched) + ); } catch (std::bad_alloc &ba) { delete server; @@ -643,11 +656,17 @@ ServerApp::openServer(ServerConfig &config, PrimaryClient *primaryClient) { return server; } -void ServerApp::handleNoClients(const Event &, void *) { updateStatus(); } +void ServerApp::handleNoClients(const Event &, void *) +{ + updateStatus(); +} -void ServerApp::handleScreenSwitched(const Event &e, void *) {} +void ServerApp::handleScreenSwitched(const Event &e, void *) +{ +} -ISocketFactory *ServerApp::getSocketFactory() const { +ISocketFactory *ServerApp::getSocketFactory() const +{ ISocketFactory *socketFactory = nullptr; if (args().m_config->isClientMode()) { @@ -659,7 +678,8 @@ ISocketFactory *ServerApp::getSocketFactory() const { return socketFactory; } -NetworkAddress ServerApp::getAddress(const NetworkAddress &address) const { +NetworkAddress ServerApp::getAddress(const NetworkAddress &address) const +{ if (args().m_config->isClientMode()) { const auto clientAddress = args().m_config->getClientAddress(); NetworkAddress addr(clientAddress.c_str(), kDefaultPort); @@ -670,7 +690,8 @@ NetworkAddress ServerApp::getAddress(const NetworkAddress &address) const { } } -int ServerApp::mainLoop() { +int ServerApp::mainLoop() +{ // create socket multiplexer. this must happen after daemonization // on unix because threads evaporate across a fork(). SocketMultiplexer multiplexer; @@ -711,19 +732,22 @@ int ServerApp::mainLoop() { ARCH->setSignalHandler(Arch::kHANGUP, &reloadSignalHandler, NULL); m_events->adoptHandler( m_events->forServerApp().reloadConfig(), m_events->getSystemTarget(), - new TMethodEventJob(this, &ServerApp::reloadConfig)); + new TMethodEventJob(this, &ServerApp::reloadConfig) + ); // handle force reconnect event by disconnecting clients. they'll // reconnect automatically. m_events->adoptHandler( m_events->forServerApp().forceReconnect(), m_events->getSystemTarget(), - new TMethodEventJob(this, &ServerApp::forceReconnect)); + new TMethodEventJob(this, &ServerApp::forceReconnect) + ); // to work around the sticky meta keys problem, we'll give users // the option to reset the state of the server. m_events->adoptHandler( m_events->forServerApp().resetServer(), m_events->getSystemTarget(), - new TMethodEventJob(this, &ServerApp::resetServer)); + new TMethodEventJob(this, &ServerApp::resetServer) + ); // run event loop. if startServer() failed we're supposed to retry // later. the timer installed by startServer() will take care of @@ -732,12 +756,10 @@ int ServerApp::mainLoop() { #if defined(MAC_OS_X_VERSION_10_7) - Thread thread( - new TMethodJob(this, &ServerApp::runEventsLoop, NULL)); + Thread thread(new TMethodJob(this, &ServerApp::runEventsLoop, NULL)); // wait until carbon loop is ready - OSXScreen *screen = - dynamic_cast(m_serverScreen->getPlatformScreen()); + OSXScreen *screen = dynamic_cast(m_serverScreen->getPlatformScreen()); screen->waitForCarbonLoop(); runCocoaApp(); @@ -749,10 +771,8 @@ int ServerApp::mainLoop() { // close down LOG((CLOG_DEBUG1 "stopping server")); - m_events->removeHandler( - m_events->forServerApp().forceReconnect(), m_events->getSystemTarget()); - m_events->removeHandler( - m_events->forServerApp().reloadConfig(), m_events->getSystemTarget()); + m_events->removeHandler(m_events->forServerApp().forceReconnect(), m_events->getSystemTarget()); + m_events->removeHandler(m_events->forServerApp().reloadConfig(), m_events->getSystemTarget()); cleanupServer(); updateStatus(); LOG((CLOG_NOTE "stopped server")); @@ -764,15 +784,16 @@ int ServerApp::mainLoop() { return kExitSuccess; } -void ServerApp::resetServer(const Event &, void *) { +void ServerApp::resetServer(const Event &, void *) +{ LOG((CLOG_DEBUG1 "resetting server")); stopServer(); cleanupServer(); startServer(); } -int ServerApp::runInner( - int argc, char **argv, ILogOutputter *outputter, StartupFunc startup) { +int ServerApp::runInner(int argc, char **argv, ILogOutputter *outputter, StartupFunc startup) +{ // general initialization m_deskflowAddress = new NetworkAddress; args().m_config = std::make_shared(m_events); @@ -795,11 +816,13 @@ int ServerApp::runInner( return result; } -int daemonMainLoopStatic(int argc, const char **argv) { +int daemonMainLoopStatic(int argc, const char **argv) +{ return ServerApp::instance().daemonMainLoop(argc, argv); } -int ServerApp::standardStartup(int argc, char **argv) { +int ServerApp::standardStartup(int argc, char **argv) +{ initApp(argc, argv); // daemonize if requested @@ -810,14 +833,16 @@ int ServerApp::standardStartup(int argc, char **argv) { } } -int ServerApp::foregroundStartup(int argc, char **argv) { +int ServerApp::foregroundStartup(int argc, char **argv) +{ initApp(argc, argv); // never daemonize return mainLoop(); } -const char *ServerApp::daemonName() const { +const char *ServerApp::daemonName() const +{ #if SYSAPI_WIN32 return DESKFLOW_APP_NAME " Server"; #elif SYSAPI_UNIX @@ -825,7 +850,8 @@ const char *ServerApp::daemonName() const { #endif } -const char *ServerApp::daemonInfo() const { +const char *ServerApp::daemonInfo() const +{ #if SYSAPI_WIN32 return "Shares this computers mouse and keyboard with other computers."; #elif SYSAPI_UNIX @@ -833,7 +859,8 @@ const char *ServerApp::daemonInfo() const { #endif } -void ServerApp::startNode() { +void ServerApp::startNode() +{ // start the server. if this return false then we've failed and // we shouldn't retry. LOG((CLOG_DEBUG1 "starting server")); diff --git a/src/lib/deskflow/ServerApp.h b/src/lib/deskflow/ServerApp.h index 4577b2894..1c5eb8054 100644 --- a/src/lib/deskflow/ServerApp.h +++ b/src/lib/deskflow/ServerApp.h @@ -26,7 +26,8 @@ #include "net/NetworkAddress.h" #include "server/Config.h" -enum EServerState { +enum EServerState +{ kUninitialized, kInitializing, kInitializingToStart, @@ -49,12 +50,12 @@ namespace deskflow { class ServerArgs; } -class ServerApp : public App { +class ServerApp : public App +{ using ServerConfig = deskflow::server::Config; public: - ServerApp( - IEventQueue *events, CreateTaskBarReceiverFunc createTaskBarReceiver); + ServerApp(IEventQueue *events, CreateTaskBarReceiverFunc createTaskBarReceiver); virtual ~ServerApp(); // @@ -69,9 +70,7 @@ public: bool loadConfig(const String &pathname) override; deskflow::Screen *createScreen() override; int mainLoop() override; - int runInner( - int argc, char **argv, ILogOutputter *outputter, - StartupFunc startup) override; + int runInner(int argc, char **argv, ILogOutputter *outputter, StartupFunc startup) override; int standardStartup(int argc, char **argv) override; int foregroundStartup(int argc, char **argv) override; void startNode() override; @@ -80,7 +79,10 @@ public: // App overrides // - std::string configSection() const override { return "server"; } + std::string configSection() const override + { + return "server"; + } // // Regular functions @@ -103,8 +105,7 @@ public: bool initServer(); void retryHandler(const Event &, void *); deskflow::Screen *openServerScreen(); - PrimaryClient * - openPrimaryClient(const String &name, deskflow::Screen *screen); + PrimaryClient *openPrimaryClient(const String &name, deskflow::Screen *screen); void handleScreenError(const Event &, void *); void handleSuspend(const Event &, void *); void handleResume(const Event &, void *); @@ -112,9 +113,13 @@ public: Server *openServer(ServerConfig &config, PrimaryClient *primaryClient); void handleNoClients(const Event &, void *); bool startServer(); - Server *getServerPtr() { return m_server; } + Server *getServerPtr() + { + return m_server; + } - deskflow::ServerArgs &args() const { + deskflow::ServerArgs &args() const + { return (deskflow::ServerArgs &)argsBase(); } @@ -123,7 +128,10 @@ public: // static void reloadSignalHandler(Arch::ESignal, void *); - static ServerApp &instance() { return (ServerApp &)App::instance(); } + static ServerApp &instance() + { + return (ServerApp &)App::instance(); + } private: void handleScreenSwitched(const Event &, void *data); diff --git a/src/lib/deskflow/ServerArgs.cpp b/src/lib/deskflow/ServerArgs.cpp index 5163beb40..1cc4412ef 100644 --- a/src/lib/deskflow/ServerArgs.cpp +++ b/src/lib/deskflow/ServerArgs.cpp @@ -19,7 +19,12 @@ namespace deskflow { -ServerArgs::~ServerArgs() {} +ServerArgs::~ServerArgs() +{ +} -ServerArgs::ServerArgs() { m_classType = kServer; } +ServerArgs::ServerArgs() +{ + m_classType = kServer; +} } // namespace deskflow diff --git a/src/lib/deskflow/ServerArgs.h b/src/lib/deskflow/ServerArgs.h index bcae78923..f01c2377b 100644 --- a/src/lib/deskflow/ServerArgs.h +++ b/src/lib/deskflow/ServerArgs.h @@ -24,7 +24,8 @@ namespace deskflow { -class ServerArgs : public ArgsBase { +class ServerArgs : public ArgsBase +{ using Config = deskflow::server::Config; public: diff --git a/src/lib/deskflow/ServerTaskBarReceiver.cpp b/src/lib/deskflow/ServerTaskBarReceiver.cpp index 4a4d1eba9..3fdfd4aee 100644 --- a/src/lib/deskflow/ServerTaskBarReceiver.cpp +++ b/src/lib/deskflow/ServerTaskBarReceiver.cpp @@ -28,18 +28,18 @@ // ServerTaskBarReceiver // -ServerTaskBarReceiver::ServerTaskBarReceiver(IEventQueue *events) - : m_state(kNotRunning), - m_events(events) { +ServerTaskBarReceiver::ServerTaskBarReceiver(IEventQueue *events) : m_state(kNotRunning), m_events(events) +{ // do nothing } -ServerTaskBarReceiver::~ServerTaskBarReceiver() { +ServerTaskBarReceiver::~ServerTaskBarReceiver() +{ // do nothing } -void ServerTaskBarReceiver::updateStatus( - Server *server, const String &errorMsg) { +void ServerTaskBarReceiver::updateStatus(Server *server, const String &errorMsg) +{ { // update our status m_errorMessage = errorMsg; @@ -67,41 +67,49 @@ void ServerTaskBarReceiver::updateStatus( ARCH->updateReceiver(this); } -ServerTaskBarReceiver::EState ServerTaskBarReceiver::getStatus() const { +ServerTaskBarReceiver::EState ServerTaskBarReceiver::getStatus() const +{ return m_state; } -const String &ServerTaskBarReceiver::getErrorMessage() const { +const String &ServerTaskBarReceiver::getErrorMessage() const +{ return m_errorMessage; } -const ServerTaskBarReceiver::Clients & -ServerTaskBarReceiver::getClients() const { +const ServerTaskBarReceiver::Clients &ServerTaskBarReceiver::getClients() const +{ return m_clients; } -void ServerTaskBarReceiver::quit() { m_events->addEvent(Event(Event::kQuit)); } +void ServerTaskBarReceiver::quit() +{ + m_events->addEvent(Event(Event::kQuit)); +} -void ServerTaskBarReceiver::onStatusChanged(Server *) { +void ServerTaskBarReceiver::onStatusChanged(Server *) +{ // do nothing } -void ServerTaskBarReceiver::lock() const { +void ServerTaskBarReceiver::lock() const +{ // do nothing } -void ServerTaskBarReceiver::unlock() const { +void ServerTaskBarReceiver::unlock() const +{ // do nothing } -std::string ServerTaskBarReceiver::getToolTip() const { +std::string ServerTaskBarReceiver::getToolTip() const +{ switch (m_state) { case kNotRunning: return deskflow::string::sprintf("%s: Not running", kAppName); case kNotWorking: - return deskflow::string::sprintf( - "%s: %s", kAppName, m_errorMessage.c_str()); + return deskflow::string::sprintf("%s: %s", kAppName, m_errorMessage.c_str()); case kNotConnected: return deskflow::string::sprintf("%s: Waiting for clients", kAppName); diff --git a/src/lib/deskflow/ServerTaskBarReceiver.h b/src/lib/deskflow/ServerTaskBarReceiver.h index 0227631d6..34f760dd2 100644 --- a/src/lib/deskflow/ServerTaskBarReceiver.h +++ b/src/lib/deskflow/ServerTaskBarReceiver.h @@ -29,7 +29,8 @@ class IEventQueue; //! Implementation of IArchTaskBarReceiver for the deskflow server -class ServerTaskBarReceiver : public IArchTaskBarReceiver { +class ServerTaskBarReceiver : public IArchTaskBarReceiver +{ public: ServerTaskBarReceiver(IEventQueue *events); virtual ~ServerTaskBarReceiver(); @@ -43,7 +44,8 @@ public: */ void updateStatus(Server *, const String &errorMsg); - void updateStatus(INode *n, const String &errorMsg) { + void updateStatus(INode *n, const String &errorMsg) + { updateStatus((Server *)n, errorMsg); } @@ -60,7 +62,8 @@ public: protected: typedef std::vector Clients; - enum EState { + enum EState + { kNotRunning, kNotWorking, kNotConnected, @@ -97,5 +100,4 @@ private: IEventQueue *m_events; }; -IArchTaskBarReceiver *createTaskBarReceiver( - const BufferedLogOutputter *logBuffer, IEventQueue *events); +IArchTaskBarReceiver *createTaskBarReceiver(const BufferedLogOutputter *logBuffer, IEventQueue *events); diff --git a/src/lib/deskflow/StreamChunker.cpp b/src/lib/deskflow/StreamChunker.cpp index 548a0a629..f4e0980ec 100644 --- a/src/lib/deskflow/StreamChunker.cpp +++ b/src/lib/deskflow/StreamChunker.cpp @@ -40,12 +40,11 @@ bool StreamChunker::s_isChunkingFile = false; bool StreamChunker::s_interruptFile = false; Mutex *StreamChunker::s_interruptMutex = NULL; -void StreamChunker::sendFile( - char *filename, IEventQueue *events, void *eventTarget) { +void StreamChunker::sendFile(char *filename, IEventQueue *events, void *eventTarget) +{ s_isChunkingFile = true; - std::fstream file( - static_cast(filename), std::ios::in | std::ios::binary); + std::fstream file(static_cast(filename), std::ios::in | std::ios::binary); if (!file.is_open()) { throw runtime_error("failed to open file"); @@ -59,8 +58,7 @@ void StreamChunker::sendFile( String fileSize = deskflow::string::sizeTypeToString(size); FileChunk *sizeMessage = FileChunk::start(fileSize); - events->addEvent( - Event(events->forFile().fileChunkSending(), eventTarget, sizeMessage)); + events->addEvent(Event(events->forFile().fileChunkSending(), eventTarget, sizeMessage)); // send chunk messages with a fixed chunk size size_t sentLength = 0; @@ -87,8 +85,7 @@ void StreamChunker::sendFile( FileChunk *fileChunk = FileChunk::data(data, chunkSize); delete[] chunkData; - events->addEvent( - Event(events->forFile().fileChunkSending(), eventTarget, fileChunk)); + events->addEvent(Event(events->forFile().fileChunkSending(), eventTarget, fileChunk)); sentLength += chunkSize; file.seekg(sentLength, std::ios::beg); @@ -101,8 +98,7 @@ void StreamChunker::sendFile( // send last message FileChunk *end = FileChunk::end(); - events->addEvent( - Event(events->forFile().fileChunkSending(), eventTarget, end)); + events->addEvent(Event(events->forFile().fileChunkSending(), eventTarget, end)); file.close(); @@ -110,14 +106,14 @@ void StreamChunker::sendFile( } void StreamChunker::sendClipboard( - String &data, size_t size, ClipboardID id, UInt32 sequence, - IEventQueue *events, void *eventTarget) { + String &data, size_t size, ClipboardID id, UInt32 sequence, IEventQueue *events, void *eventTarget +) +{ // send first message (data size) String dataSize = deskflow::string::sizeTypeToString(size); ClipboardChunk *sizeMessage = ClipboardChunk::start(id, sequence, dataSize); - events->addEvent(Event( - events->forClipboard().clipboardSending(), eventTarget, sizeMessage)); + events->addEvent(Event(events->forClipboard().clipboardSending(), eventTarget, sizeMessage)); // send clipboard chunk with a fixed size size_t sentLength = 0; @@ -134,8 +130,7 @@ void StreamChunker::sendClipboard( String chunk(data.substr(sentLength, chunkSize).c_str(), chunkSize); ClipboardChunk *dataChunk = ClipboardChunk::data(id, sequence, chunk); - events->addEvent(Event( - events->forClipboard().clipboardSending(), eventTarget, dataChunk)); + events->addEvent(Event(events->forClipboard().clipboardSending(), eventTarget, dataChunk)); sentLength += chunkSize; if (sentLength == size) { @@ -146,13 +141,13 @@ void StreamChunker::sendClipboard( // send last message ClipboardChunk *end = ClipboardChunk::end(id, sequence); - events->addEvent( - Event(events->forClipboard().clipboardSending(), eventTarget, end)); + events->addEvent(Event(events->forClipboard().clipboardSending(), eventTarget, end)); LOG((CLOG_DEBUG "sent clipboard size=%d", sentLength)); } -void StreamChunker::interruptFile() { +void StreamChunker::interruptFile() +{ if (s_isChunkingFile) { s_interruptFile = true; LOG((CLOG_INFO "previous dragged file has become invalid")); diff --git a/src/lib/deskflow/StreamChunker.h b/src/lib/deskflow/StreamChunker.h index 9624feaac..9b12f21c7 100644 --- a/src/lib/deskflow/StreamChunker.h +++ b/src/lib/deskflow/StreamChunker.h @@ -23,12 +23,12 @@ class IEventQueue; class Mutex; -class StreamChunker { +class StreamChunker +{ public: static void sendFile(char *filename, IEventQueue *events, void *eventTarget); - static void sendClipboard( - String &data, size_t size, ClipboardID id, UInt32 sequence, - IEventQueue *events, void *eventTarget); + static void + sendClipboard(String &data, size_t size, ClipboardID id, UInt32 sequence, IEventQueue *events, void *eventTarget); static void interruptFile(); private: diff --git a/src/lib/deskflow/ToolApp.cpp b/src/lib/deskflow/ToolApp.cpp index b8bc7e0db..80fce9345 100644 --- a/src/lib/deskflow/ToolApp.cpp +++ b/src/lib/deskflow/ToolApp.cpp @@ -28,9 +28,16 @@ #include "platform/MSWindowsSession.h" #endif -enum { kErrorOk, kErrorArgs, kErrorException, kErrorUnknown }; +enum +{ + kErrorOk, + kErrorArgs, + kErrorException, + kErrorUnknown +}; -UInt32 ToolApp::run(int argc, char **argv) { +UInt32 ToolApp::run(int argc, char **argv) +{ if (argc <= 1) { std::cerr << "no args" << std::endl; return kErrorArgs; @@ -52,8 +59,7 @@ UInt32 ToolApp::run(int argc, char **argv) { LOG((CLOG_CRIT "failed to get active desktop name")); return kExitFailed; } else { - String output = - deskflow::string::sprintf("activeDesktop:%s", name.c_str()); + String output = deskflow::string::sprintf("activeDesktop:%s", name.c_str()); LOG((CLOG_INFO "%s", output.c_str())); } #endif @@ -82,4 +88,6 @@ UInt32 ToolApp::run(int argc, char **argv) { return kErrorOk; } -void ToolApp::help() {} +void ToolApp::help() +{ +} diff --git a/src/lib/deskflow/ToolApp.h b/src/lib/deskflow/ToolApp.h index 8eb2eae6b..69f73071c 100644 --- a/src/lib/deskflow/ToolApp.h +++ b/src/lib/deskflow/ToolApp.h @@ -21,7 +21,8 @@ #include "deskflow/App.h" #include "deskflow/ToolArgs.h" -class ToolApp : public MinimalApp { +class ToolApp : public MinimalApp +{ public: UInt32 run(int argc, char **argv); void help(); diff --git a/src/lib/deskflow/ToolArgs.cpp b/src/lib/deskflow/ToolArgs.cpp index 03e215844..7860883e1 100644 --- a/src/lib/deskflow/ToolArgs.cpp +++ b/src/lib/deskflow/ToolArgs.cpp @@ -21,4 +21,6 @@ ToolArgs::ToolArgs() : m_printActiveDesktopName(false), m_getInstalledDir(false), m_getProfileDir(false), - m_getArch(false) {} + m_getArch(false) +{ +} diff --git a/src/lib/deskflow/ToolArgs.h b/src/lib/deskflow/ToolArgs.h index 80028183c..8af13c34a 100644 --- a/src/lib/deskflow/ToolArgs.h +++ b/src/lib/deskflow/ToolArgs.h @@ -19,7 +19,8 @@ #include "base/String.h" -class ToolArgs { +class ToolArgs +{ public: ToolArgs(); diff --git a/src/lib/deskflow/XDeskflow.cpp b/src/lib/deskflow/XDeskflow.cpp index 2747d3279..11b3fb338 100644 --- a/src/lib/deskflow/XDeskflow.cpp +++ b/src/lib/deskflow/XDeskflow.cpp @@ -23,40 +23,54 @@ // XBadClient // -String XBadClient::getWhat() const throw() { return "XBadClient"; } +String XBadClient::getWhat() const throw() +{ + return "XBadClient"; +} // // XIncompatibleClient // -XIncompatibleClient::XIncompatibleClient(int major, int minor) - : m_major(major), - m_minor(minor) { +XIncompatibleClient::XIncompatibleClient(int major, int minor) : m_major(major), m_minor(minor) +{ // do nothing } -int XIncompatibleClient::getMajor() const throw() { return m_major; } +int XIncompatibleClient::getMajor() const throw() +{ + return m_major; +} -int XIncompatibleClient::getMinor() const throw() { return m_minor; } +int XIncompatibleClient::getMinor() const throw() +{ + return m_minor; +} -String XIncompatibleClient::getWhat() const throw() { +String XIncompatibleClient::getWhat() const throw() +{ return format( - "XIncompatibleClient", "incompatible client %{1}.%{2}", - deskflow::string::sprintf("%d", m_major).c_str(), - deskflow::string::sprintf("%d", m_minor).c_str()); + "XIncompatibleClient", "incompatible client %{1}.%{2}", deskflow::string::sprintf("%d", m_major).c_str(), + deskflow::string::sprintf("%d", m_minor).c_str() + ); } // // XDuplicateClient // -XDuplicateClient::XDuplicateClient(const String &name) : m_name(name) { +XDuplicateClient::XDuplicateClient(const String &name) : m_name(name) +{ // do nothing } -const String &XDuplicateClient::getName() const throw() { return m_name; } +const String &XDuplicateClient::getName() const throw() +{ + return m_name; +} -String XDuplicateClient::getWhat() const throw() { +String XDuplicateClient::getWhat() const throw() +{ return format("XDuplicateClient", "duplicate client %{1}", m_name.c_str()); } @@ -64,13 +78,18 @@ String XDuplicateClient::getWhat() const throw() { // XUnknownClient // -XUnknownClient::XUnknownClient(const String &name) : m_name(name) { +XUnknownClient::XUnknownClient(const String &name) : m_name(name) +{ // do nothing } -const String &XUnknownClient::getName() const throw() { return m_name; } +const String &XUnknownClient::getName() const throw() +{ + return m_name; +} -String XUnknownClient::getWhat() const throw() { +String XUnknownClient::getWhat() const throw() +{ return format("XUnknownClient", "unknown client %{1}", m_name.c_str()); } @@ -78,14 +97,17 @@ String XUnknownClient::getWhat() const throw() { // XExitApp // -XExitApp::XExitApp(int code) : m_code(code) { +XExitApp::XExitApp(int code) : m_code(code) +{ // do nothing } -int XExitApp::getCode() const throw() { return m_code; } - -String XExitApp::getWhat() const throw() { - return format( - "XExitApp", "exiting with code %{1}", - deskflow::string::sprintf("%d", m_code).c_str()); +int XExitApp::getCode() const throw() +{ + return m_code; +} + +String XExitApp::getWhat() const throw() +{ + return format("XExitApp", "exiting with code %{1}", deskflow::string::sprintf("%d", m_code).c_str()); } diff --git a/src/lib/deskflow/XDeskflow.h b/src/lib/deskflow/XDeskflow.h index e749b7c8f..b691f99e0 100644 --- a/src/lib/deskflow/XDeskflow.h +++ b/src/lib/deskflow/XDeskflow.h @@ -39,7 +39,8 @@ XBASE_SUBCLASS_WHAT(XBadClient, XDeskflow); /*! Thrown when a client attempting to connect has an incompatible version. */ -class XIncompatibleClient : public XDeskflow { +class XIncompatibleClient : public XDeskflow +{ public: XIncompatibleClient(int major, int minor); @@ -66,10 +67,13 @@ private: Thrown when a client attempting to connect is using the same name as a client that is already connected. */ -class XDuplicateClient : public XDeskflow { +class XDuplicateClient : public XDeskflow +{ public: XDuplicateClient(const String &name); - virtual ~XDuplicateClient() _NOEXCEPT {} + virtual ~XDuplicateClient() _NOEXCEPT + { + } //! @name accessors //@{ @@ -91,10 +95,13 @@ private: Thrown when a client attempting to connect is using a name that is unknown to the server. */ -class XUnknownClient : public XDeskflow { +class XUnknownClient : public XDeskflow +{ public: XUnknownClient(const String &name); - virtual ~XUnknownClient() _NOEXCEPT {} + virtual ~XUnknownClient() _NOEXCEPT + { + } //! @name accessors //@{ @@ -117,10 +124,13 @@ Thrown when we want to abort, with the opportunity to clean up. This is a little bit of a hack, but it's a better way of exiting, than just calling exit(int). */ -class XExitApp : public XDeskflow { +class XExitApp : public XDeskflow +{ public: XExitApp(int code); - virtual ~XExitApp() _NOEXCEPT {} + virtual ~XExitApp() _NOEXCEPT + { + } //! Get the exit code int getCode() const throw(); diff --git a/src/lib/deskflow/XScreen.cpp b/src/lib/deskflow/XScreen.cpp index 662700840..c7dc1899d 100644 --- a/src/lib/deskflow/XScreen.cpp +++ b/src/lib/deskflow/XScreen.cpp @@ -22,7 +22,8 @@ // XScreenOpenFailure // -String XScreenOpenFailure::getWhat() const throw() { +String XScreenOpenFailure::getWhat() const throw() +{ return format("XScreenOpenFailure", "unable to open screen"); } @@ -30,23 +31,31 @@ String XScreenOpenFailure::getWhat() const throw() { // XScreenXInputFailure // -String XScreenXInputFailure::getWhat() const throw() { return ""; } +String XScreenXInputFailure::getWhat() const throw() +{ + return ""; +} // // XScreenUnavailable // -XScreenUnavailable::XScreenUnavailable(double timeUntilRetry) - : m_timeUntilRetry(timeUntilRetry) { +XScreenUnavailable::XScreenUnavailable(double timeUntilRetry) : m_timeUntilRetry(timeUntilRetry) +{ // do nothing } -XScreenUnavailable::~XScreenUnavailable() _NOEXCEPT { +XScreenUnavailable::~XScreenUnavailable() _NOEXCEPT +{ // do nothing } -double XScreenUnavailable::getRetryTime() const { return m_timeUntilRetry; } +double XScreenUnavailable::getRetryTime() const +{ + return m_timeUntilRetry; +} -String XScreenUnavailable::getWhat() const throw() { +String XScreenUnavailable::getWhat() const throw() +{ return format("XScreenUnavailable", "unable to open screen"); } diff --git a/src/lib/deskflow/XScreen.h b/src/lib/deskflow/XScreen.h index 56121ac0d..e36507546 100644 --- a/src/lib/deskflow/XScreen.h +++ b/src/lib/deskflow/XScreen.h @@ -40,7 +40,8 @@ XBASE_SUBCLASS_WHAT(XScreenXInputFailure, XScreen); Thrown when a screen cannot be opened or initialized but retrying later may be successful. */ -class XScreenUnavailable : public XScreenOpenFailure { +class XScreenUnavailable : public XScreenOpenFailure +{ public: /*! \c timeUntilRetry is the suggested time the caller should wait until diff --git a/src/lib/deskflow/key_types.h b/src/lib/deskflow/key_types.h index 813ae054d..f623a5288 100644 --- a/src/lib/deskflow/key_types.h +++ b/src/lib/deskflow/key_types.h @@ -289,11 +289,13 @@ static const KeyID kKeyLaunchpad = 0xE0C1; //@} -struct KeyNameMapEntry { +struct KeyNameMapEntry +{ const char *m_name; KeyID m_id; }; -struct KeyModifierNameMapEntry { +struct KeyModifierNameMapEntry +{ const char *m_name; KeyModifierMask m_mask; }; diff --git a/src/lib/deskflow/languages/LanguageManager.cpp b/src/lib/deskflow/languages/LanguageManager.cpp index bbcfe3ccb..50b4b3fb6 100644 --- a/src/lib/deskflow/languages/LanguageManager.cpp +++ b/src/lib/deskflow/languages/LanguageManager.cpp @@ -21,8 +21,8 @@ namespace { -String vectorToString( - const std::vector &vector, const String &delimiter = "") { +String vectorToString(const std::vector &vector, const String &delimiter = "") +{ String string; for (const auto &item : vector) { if (&item != &vector[0]) { @@ -39,34 +39,34 @@ namespace deskflow { namespace languages { -LanguageManager::LanguageManager(const std::vector &localLanguages) - : m_localLanguages(localLanguages) { - LOG( - (CLOG_INFO "local languages: %s", - vectorToString(m_localLanguages, ", ").c_str())); +LanguageManager::LanguageManager(const std::vector &localLanguages) : m_localLanguages(localLanguages) +{ + LOG((CLOG_INFO "local languages: %s", vectorToString(m_localLanguages, ", ").c_str())); } -void LanguageManager::setRemoteLanguages(const String &remoteLanguages) { +void LanguageManager::setRemoteLanguages(const String &remoteLanguages) +{ m_remoteLanguages.clear(); if (!remoteLanguages.empty()) { for (size_t i = 0; i <= remoteLanguages.size() - 2; i += 2) { m_remoteLanguages.push_back(remoteLanguages.substr(i, 2)); } } - LOG( - (CLOG_INFO "remote languages: %s", - vectorToString(m_remoteLanguages, ", ").c_str())); + LOG((CLOG_INFO "remote languages: %s", vectorToString(m_remoteLanguages, ", ").c_str())); } -const std::vector &LanguageManager::getRemoteLanguages() const { +const std::vector &LanguageManager::getRemoteLanguages() const +{ return m_remoteLanguages; } -const std::vector &LanguageManager::getLocalLanguages() const { +const std::vector &LanguageManager::getLocalLanguages() const +{ return m_localLanguages; } -String LanguageManager::getMissedLanguages() const { +String LanguageManager::getMissedLanguages() const +{ String missedLanguages; for (const auto &language : m_remoteLanguages) { @@ -81,18 +81,17 @@ String LanguageManager::getMissedLanguages() const { return missedLanguages; } -String LanguageManager::getSerializedLocalLanguages() const { +String LanguageManager::getSerializedLocalLanguages() const +{ return vectorToString(m_localLanguages); } -bool LanguageManager::isLanguageInstalled(const String &language) const { +bool LanguageManager::isLanguageInstalled(const String &language) const +{ bool isInstalled = true; if (!m_localLanguages.empty()) { - isInstalled = - (std::find( - m_localLanguages.begin(), m_localLanguages.end(), language) != - m_localLanguages.end()); + isInstalled = (std::find(m_localLanguages.begin(), m_localLanguages.end(), language) != m_localLanguages.end()); } return isInstalled; diff --git a/src/lib/deskflow/languages/LanguageManager.h b/src/lib/deskflow/languages/LanguageManager.h index 675a35d66..832a41659 100644 --- a/src/lib/deskflow/languages/LanguageManager.h +++ b/src/lib/deskflow/languages/LanguageManager.h @@ -24,14 +24,13 @@ namespace deskflow { namespace languages { -class LanguageManager { +class LanguageManager +{ std::vector m_remoteLanguages; std::vector m_localLanguages; public: - explicit LanguageManager( - const std::vector &localLanguages = - AppUtil::instance().getKeyboardLayoutList()); + explicit LanguageManager(const std::vector &localLanguages = AppUtil::instance().getKeyboardLayoutList()); /** * @brief setRemoteLanguages sets remote languages diff --git a/src/lib/deskflow/option_types.h b/src/lib/deskflow/option_types.h index 7896ec546..99db87a47 100644 --- a/src/lib/deskflow/option_types.h +++ b/src/lib/deskflow/option_types.h @@ -37,10 +37,10 @@ typedef SInt32 OptionValue; typedef std::vector OptionsList; // macro for packing 4 character strings into 4 byte integers -#define OPTION_CODE(_s) \ - (static_cast(static_cast(_s[0]) << 24) | \ - static_cast(static_cast(_s[1]) << 16) | \ - static_cast(static_cast(_s[2]) << 8) | \ +#define OPTION_CODE(_s) \ + (static_cast(static_cast(_s[0]) << 24) | \ + static_cast(static_cast(_s[1]) << 16) | \ + static_cast(static_cast(_s[2]) << 8) | \ static_cast(static_cast(_s[3]))) //! @name Option identifiers @@ -73,7 +73,8 @@ static const OptionID kOptionClipboardSharingSize = OPTION_CODE("CLSZ"); //! @name Screen switch corner enumeration //@{ -enum EScreenSwitchCorners { +enum EScreenSwitchCorners +{ kNoCorner, kTopLeft, kTopRight, @@ -86,14 +87,14 @@ enum EScreenSwitchCorners { //! @name Screen switch corner masks //@{ -enum EScreenSwitchCornerMasks { +enum EScreenSwitchCornerMasks +{ kNoCornerMask = 0, kTopLeftMask = 1 << (kTopLeft - kFirstCorner), kTopRightMask = 1 << (kTopRight - kFirstCorner), kBottomLeftMask = 1 << (kBottomLeft - kFirstCorner), kBottomRightMask = 1 << (kBottomRight - kFirstCorner), - kAllCornersMask = - kTopLeftMask | kTopRightMask | kBottomLeftMask | kBottomRightMask + kAllCornersMask = kTopLeftMask | kTopRightMask | kBottomLeftMask | kBottomRightMask }; //@} diff --git a/src/lib/deskflow/protocol_types.h b/src/lib/deskflow/protocol_types.h index 759d23196..5c67bb161 100644 --- a/src/lib/deskflow/protocol_types.h +++ b/src/lib/deskflow/protocol_types.h @@ -54,7 +54,8 @@ static const double kHeartRate = -1.0; static const double kHeartBeatsUntilDeath = 3.0; // direction constants -enum EDirection { +enum EDirection +{ kNoDirection, kLeft, kRight, @@ -64,7 +65,8 @@ enum EDirection { kLastDirection = kBottom, kNumDirections = kLastDirection - kFirstDirection + 1 }; -enum EDirectionMask { +enum EDirectionMask +{ kNoDirMask = 0, kLeftMask = 1 << kLeft, kRightMask = 1 << kRight, @@ -73,10 +75,21 @@ enum EDirectionMask { }; // Data transfer constants -enum EDataTransfer { kDataStart = 1, kDataChunk = 2, kDataEnd = 3 }; +enum EDataTransfer +{ + kDataStart = 1, + kDataChunk = 2, + kDataEnd = 3 +}; // Data received constants -enum EDataReceived { kStart, kNotFinish, kFinish, kError }; +enum EDataReceived +{ + kStart, + kNotFinish, + kFinish, + kError +}; // // message codes (trailing NUL is not part of code). in comments, $n @@ -317,7 +330,8 @@ extern const char *const kMsgEBad; /*! This class contains information about a screen. */ -class ClientInfo { +class ClientInfo +{ public: //! Screen position /*! diff --git a/src/lib/deskflow/unix/AppUtilUnix.cpp b/src/lib/deskflow/unix/AppUtilUnix.cpp index 4f3bb0ec6..80bdcba03 100644 --- a/src/lib/deskflow/unix/AppUtilUnix.cpp +++ b/src/lib/deskflow/unix/AppUtilUnix.cpp @@ -36,55 +36,54 @@ #include #endif -AppUtilUnix::AppUtilUnix(IEventQueue *events) {} +AppUtilUnix::AppUtilUnix(IEventQueue *events) +{ +} -AppUtilUnix::~AppUtilUnix() {} +AppUtilUnix::~AppUtilUnix() +{ +} -int standardStartupStatic(int argc, char **argv) { +int standardStartupStatic(int argc, char **argv) +{ return AppUtil::instance().app().standardStartup(argc, argv); } -int AppUtilUnix::run(int argc, char **argv) { +int AppUtilUnix::run(int argc, char **argv) +{ return app().runInner(argc, argv, NULL, &standardStartupStatic); } -void AppUtilUnix::startNode() { app().startNode(); } +void AppUtilUnix::startNode() +{ + app().startNode(); +} -std::vector AppUtilUnix::getKeyboardLayoutList() { +std::vector AppUtilUnix::getKeyboardLayoutList() +{ std::vector layoutLangCodes; #if WINAPI_XWINDOWS - layoutLangCodes = X11LayoutsParser::getX11LanguageList( - "/usr/share/X11/xkb/rules/evdev.xml"); + layoutLangCodes = X11LayoutsParser::getX11LanguageList("/usr/share/X11/xkb/rules/evdev.xml"); #elif WINAPI_CARBON CFStringRef keys[] = {kTISPropertyInputSourceCategory}; CFStringRef values[] = {kTISCategoryKeyboardInputSource}; - AutoCFDictionary dict( - CFDictionaryCreate( - NULL, (const void **)keys, (const void **)values, 1, NULL, NULL), - CFRelease); + AutoCFDictionary dict(CFDictionaryCreate(NULL, (const void **)keys, (const void **)values, 1, NULL, NULL), CFRelease); AutoCFArray kbds(TISCreateInputSourceList(dict.get(), false), CFRelease); for (CFIndex i = 0; i < CFArrayGetCount(kbds.get()); ++i) { - TISInputSourceRef keyboardLayout = - (TISInputSourceRef)CFArrayGetValueAtIndex(kbds.get(), i); - auto layoutLanguages = (CFArrayRef)TISGetInputSourceProperty( - keyboardLayout, kTISPropertyInputSourceLanguages); + TISInputSourceRef keyboardLayout = (TISInputSourceRef)CFArrayGetValueAtIndex(kbds.get(), i); + auto layoutLanguages = (CFArrayRef)TISGetInputSourceProperty(keyboardLayout, kTISPropertyInputSourceLanguages); char temporaryCString[128] = {0}; - for (CFIndex index = 0; - index < CFArrayGetCount(layoutLanguages) && layoutLanguages; index++) { - auto languageCode = - (CFStringRef)CFArrayGetValueAtIndex(layoutLanguages, index); - if (!languageCode || - !CFStringGetCString( - languageCode, temporaryCString, 128, kCFStringEncodingUTF8)) { + for (CFIndex index = 0; index < CFArrayGetCount(layoutLanguages) && layoutLanguages; index++) { + auto languageCode = (CFStringRef)CFArrayGetValueAtIndex(layoutLanguages, index); + if (!languageCode || !CFStringGetCString(languageCode, temporaryCString, 128, kCFStringEncodingUTF8)) { continue; } std::string langCode(temporaryCString); if (langCode.size() == 2 && - std::find(layoutLangCodes.begin(), layoutLangCodes.end(), langCode) == - layoutLangCodes.end()) { + std::find(layoutLangCodes.begin(), layoutLangCodes.end(), langCode) == layoutLangCodes.end()) { layoutLangCodes.push_back(langCode); } @@ -97,7 +96,8 @@ std::vector AppUtilUnix::getKeyboardLayoutList() { return layoutLangCodes; } -String AppUtilUnix::getCurrentLanguageCode() { +String AppUtilUnix::getCurrentLanguageCode() +{ String result = ""; #if WINAPI_XWINDOWS @@ -129,12 +129,10 @@ String AppUtilUnix::getCurrentLanguageCode() { } auto group = rawLayouts.substr(groupStartI, strI - groupStartI); - if (group.find("group", 0, 5) == std::string::npos && - group.find("inet", 0, 4) == std::string::npos && + if (group.find("group", 0, 5) == std::string::npos && group.find("inet", 0, 4) == std::string::npos && group.find("pc", 0, 2) == std::string::npos) { if (nedeedGroupIndex == groupIdx) { - result = - group.substr(0, std::min(group.find('(', 0), group.find(':', 0))); + result = group.substr(0, std::min(group.find('(', 0), group.find(':', 0))); break; } groupIdx++; @@ -147,20 +145,15 @@ String AppUtilUnix::getCurrentLanguageCode() { XFree(kbdDescr); XCloseDisplay(display); - result = X11LayoutsParser::convertLayotToISO( - "/usr/share/X11/xkb/rules/evdev.xml", result); + result = X11LayoutsParser::convertLayotToISO("/usr/share/X11/xkb/rules/evdev.xml", result); #elif WINAPI_CARBON - auto layoutLanguages = (CFArrayRef)TISGetInputSourceProperty( - TISCopyCurrentKeyboardInputSource(), kTISPropertyInputSourceLanguages); + auto layoutLanguages = + (CFArrayRef)TISGetInputSourceProperty(TISCopyCurrentKeyboardInputSource(), kTISPropertyInputSourceLanguages); char temporaryCString[128] = {0}; - for (CFIndex index = 0; - index < CFArrayGetCount(layoutLanguages) && layoutLanguages; index++) { - auto languageCode = - (CFStringRef)CFArrayGetValueAtIndex(layoutLanguages, index); - if (!languageCode || - !CFStringGetCString( - languageCode, temporaryCString, 128, kCFStringEncodingUTF8)) { + for (CFIndex index = 0; index < CFArrayGetCount(layoutLanguages) && layoutLanguages; index++) { + auto languageCode = (CFStringRef)CFArrayGetValueAtIndex(layoutLanguages, index); + if (!languageCode || !CFStringGetCString(languageCode, temporaryCString, 128, kCFStringEncodingUTF8)) { continue; } @@ -171,19 +164,16 @@ String AppUtilUnix::getCurrentLanguageCode() { return result; } -void AppUtilUnix::showNotification( - const String &title, const String &text) const { +void AppUtilUnix::showNotification(const String &title, const String &text) const +{ #if HAVE_LIBNOTIFY - LOG( - (CLOG_INFO "showing notification, title=\"%s\", text=\"%s\"", - title.c_str(), text.c_str())); + LOG((CLOG_INFO "showing notification, title=\"%s\", text=\"%s\"", title.c_str(), text.c_str())); if (!notify_init(DESKFLOW_APP_NAME)) { LOG((CLOG_INFO "failed to initialize libnotify")); return; } - auto notification = - notify_notification_new(title.c_str(), text.c_str(), nullptr); + auto notification = notify_notification_new(title.c_str(), text.c_str(), nullptr); if (notification == nullptr) { LOG((CLOG_INFO "failed to create notification")); return; diff --git a/src/lib/deskflow/unix/AppUtilUnix.h b/src/lib/deskflow/unix/AppUtilUnix.h index 1cbe96bad..07a32ad84 100644 --- a/src/lib/deskflow/unix/AppUtilUnix.h +++ b/src/lib/deskflow/unix/AppUtilUnix.h @@ -24,7 +24,8 @@ class IEventQueue; -class AppUtilUnix : public AppUtil { +class AppUtilUnix : public AppUtil +{ public: AppUtilUnix(IEventQueue *events); virtual ~AppUtilUnix(); diff --git a/src/lib/deskflow/unix/DeskflowXkbKeyboard.cpp b/src/lib/deskflow/unix/DeskflowXkbKeyboard.cpp index 9d952467d..c9d172f6f 100644 --- a/src/lib/deskflow/unix/DeskflowXkbKeyboard.cpp +++ b/src/lib/deskflow/unix/DeskflowXkbKeyboard.cpp @@ -26,11 +26,10 @@ namespace deskflow { namespace linux { -DeskflowXkbKeyboard::DeskflowXkbKeyboard() { +DeskflowXkbKeyboard::DeskflowXkbKeyboard() +{ using XkbDisplay = std::unique_ptr; - XkbDisplay display( - XkbOpenDisplay(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr), - &XCloseDisplay); + XkbDisplay display(XkbOpenDisplay(nullptr, nullptr, nullptr, nullptr, nullptr, nullptr), &XCloseDisplay); if (display) { if (!XkbRF_GetNamesProp(display.get(), nullptr, &m_data)) { @@ -41,15 +40,18 @@ DeskflowXkbKeyboard::DeskflowXkbKeyboard() { } } -const char *DeskflowXkbKeyboard::getLayout() const { +const char *DeskflowXkbKeyboard::getLayout() const +{ return m_data.layout ? m_data.layout : "us"; } -const char *DeskflowXkbKeyboard::getVariant() const { +const char *DeskflowXkbKeyboard::getVariant() const +{ return m_data.variant ? m_data.variant : ""; } -DeskflowXkbKeyboard::~DeskflowXkbKeyboard() { +DeskflowXkbKeyboard::~DeskflowXkbKeyboard() +{ std::free(m_data.model); std::free(m_data.layout); std::free(m_data.variant); diff --git a/src/lib/deskflow/unix/DeskflowXkbKeyboard.h b/src/lib/deskflow/unix/DeskflowXkbKeyboard.h index c0f0b807a..dc38519ab 100644 --- a/src/lib/deskflow/unix/DeskflowXkbKeyboard.h +++ b/src/lib/deskflow/unix/DeskflowXkbKeyboard.h @@ -27,7 +27,8 @@ namespace deskflow { namespace linux { -class DeskflowXkbKeyboard { +class DeskflowXkbKeyboard +{ XkbRF_VarDefsRec m_data = {}; public: diff --git a/src/lib/deskflow/unix/ISO639Table.h b/src/lib/deskflow/unix/ISO639Table.h index b79a70f6d..34868c714 100644 --- a/src/lib/deskflow/unix/ISO639Table.h +++ b/src/lib/deskflow/unix/ISO639Table.h @@ -25,106 +25,55 @@ // 10.06.2021 // first param - ISO 639-2, second param - 639-1 const std::vector> ISO_Table = { - std::make_pair("aar", "aa"), std::make_pair("abk", "ab"), - std::make_pair("afr", "af"), std::make_pair("aka", "ak"), - std::make_pair("sqi", "sq"), std::make_pair("amh", "am"), - std::make_pair("ara", "ar"), std::make_pair("arg", "an"), - std::make_pair("hye", "hy"), std::make_pair("asm", "as"), - std::make_pair("ava", "av"), std::make_pair("ave", "ae"), - std::make_pair("aym", "ay"), std::make_pair("aze", "az"), - std::make_pair("bak", "ba"), std::make_pair("bam", "bm"), - std::make_pair("eus", "eu"), std::make_pair("bel", "be"), - std::make_pair("ben", "bn"), std::make_pair("bih", "bh"), - std::make_pair("bis", "bi"), std::make_pair("bod", "bo"), - std::make_pair("bos", "bs"), std::make_pair("bre", "br"), - std::make_pair("bul", "bg"), std::make_pair("mya", "my"), - std::make_pair("cat", "ca"), std::make_pair("ces", "cs"), - std::make_pair("cha", "ch"), std::make_pair("che", "ce"), - std::make_pair("zho", "zh"), std::make_pair("chu", "cu"), - std::make_pair("chv", "cv"), std::make_pair("cor", "kw"), - std::make_pair("cos", "co"), std::make_pair("cre", "cr"), - std::make_pair("cym", "cy"), std::make_pair("ces", "cs"), - std::make_pair("dan", "da"), std::make_pair("deu", "de"), - std::make_pair("div", "dv"), std::make_pair("nld", "nl"), - std::make_pair("dzo", "dz"), std::make_pair("ell", "el"), - std::make_pair("eng", "en"), std::make_pair("epo", "eo"), - std::make_pair("est", "et"), std::make_pair("eus", "eu"), - std::make_pair("ewe", "ee"), std::make_pair("fao", "fo"), - std::make_pair("fas", "fa"), std::make_pair("fij", "fj"), - std::make_pair("fin", "fi"), std::make_pair("fra", "fr"), - std::make_pair("fra", "fr"), std::make_pair("fry", "fy"), - std::make_pair("ful", "ff"), std::make_pair("kat", "ka"), - std::make_pair("deu", "de"), std::make_pair("gla", "gd"), - std::make_pair("gle", "ga"), std::make_pair("glg", "gl"), - std::make_pair("glv", "gv"), std::make_pair("ell", "el"), - std::make_pair("grn", "gn"), std::make_pair("guj", "gu"), - std::make_pair("hat", "ht"), std::make_pair("hau", "ha"), - std::make_pair("heb", "he"), std::make_pair("her", "hz"), - std::make_pair("hin", "hi"), std::make_pair("hmo", "ho"), - std::make_pair("hrv", "hr"), std::make_pair("hun", "hu"), - std::make_pair("hye", "hy"), std::make_pair("ibo", "ig"), - std::make_pair("isl", "is"), std::make_pair("ido", "io"), - std::make_pair("iii", "ii"), std::make_pair("iku", "iu"), - std::make_pair("ile", "ie"), std::make_pair("ina", "ia"), - std::make_pair("ind", "id"), std::make_pair("ipk", "ik"), - std::make_pair("isl", "is"), std::make_pair("ita", "it"), - std::make_pair("jav", "jv"), std::make_pair("jpn", "ja"), - std::make_pair("kal", "kl"), std::make_pair("kan", "kn"), - std::make_pair("kas", "ks"), std::make_pair("kat", "ka"), - std::make_pair("kau", "kr"), std::make_pair("kaz", "kk"), - std::make_pair("khm", "km"), std::make_pair("kik", "ki"), - std::make_pair("kin", "rw"), std::make_pair("kir", "ky"), - std::make_pair("kom", "kv"), std::make_pair("kon", "kg"), - std::make_pair("kor", "ko"), std::make_pair("kua", "kj"), - std::make_pair("kur", "ku"), std::make_pair("lao", "lo"), - std::make_pair("lat", "la"), std::make_pair("lav", "lv"), - std::make_pair("lim", "li"), std::make_pair("lin", "ln"), - std::make_pair("lit", "lt"), std::make_pair("ltz", "lb"), - std::make_pair("lub", "lu"), std::make_pair("lug", "lg"), - std::make_pair("mkd", "mk"), std::make_pair("mah", "mh"), - std::make_pair("mal", "ml"), std::make_pair("mri", "mi"), - std::make_pair("mar", "mr"), std::make_pair("msa", "ms"), - std::make_pair("mkd", "mk"), std::make_pair("mlg", "mg"), - std::make_pair("mlt", "mt"), std::make_pair("mon", "mn"), - std::make_pair("mri", "mi"), std::make_pair("msa", "ms"), - std::make_pair("mya", "my"), std::make_pair("nau", "na"), - std::make_pair("nav", "nv"), std::make_pair("nbl", "nr"), - std::make_pair("nde", "nd"), std::make_pair("ndo", "ng"), - std::make_pair("nep", "ne"), std::make_pair("nld", "nl"), - std::make_pair("nno", "nn"), std::make_pair("nob", "nb"), - std::make_pair("nor", "no"), std::make_pair("nya", "ny"), - std::make_pair("oci", "oc"), std::make_pair("oji", "oj"), - std::make_pair("ori", "or"), std::make_pair("orm", "om"), - std::make_pair("oss", "os"), std::make_pair("pan", "pa"), - std::make_pair("fas", "fa"), std::make_pair("pli", "pi"), - std::make_pair("pol", "pl"), std::make_pair("por", "pt"), - std::make_pair("pus", "ps"), std::make_pair("que", "qu"), - std::make_pair("roh", "rm"), std::make_pair("ron", "ro"), - std::make_pair("ron", "ro"), std::make_pair("run", "rn"), - std::make_pair("rus", "ru"), std::make_pair("sag", "sg"), - std::make_pair("san", "sa"), std::make_pair("sin", "si"), - std::make_pair("slk", "sk"), std::make_pair("slk", "sk"), - std::make_pair("slv", "sl"), std::make_pair("sme", "se"), - std::make_pair("smo", "sm"), std::make_pair("sna", "sn"), - std::make_pair("snd", "sd"), std::make_pair("som", "so"), - std::make_pair("sot", "st"), std::make_pair("spa", "es"), - std::make_pair("sqi", "sq"), std::make_pair("srd", "sc"), - std::make_pair("srp", "sr"), std::make_pair("ssw", "ss"), - std::make_pair("sun", "su"), std::make_pair("swa", "sw"), - std::make_pair("swe", "sv"), std::make_pair("tah", "ty"), - std::make_pair("tam", "ta"), std::make_pair("tat", "tt"), - std::make_pair("tel", "te"), std::make_pair("tgk", "tg"), - std::make_pair("tgl", "tl"), std::make_pair("tha", "th"), - std::make_pair("bod", "bo"), std::make_pair("tir", "ti"), - std::make_pair("ton", "to"), std::make_pair("tsn", "tn"), - std::make_pair("tso", "ts"), std::make_pair("tuk", "tk"), - std::make_pair("tur", "tr"), std::make_pair("twi", "tw"), - std::make_pair("uig", "ug"), std::make_pair("ukr", "uk"), - std::make_pair("urd", "ur"), std::make_pair("uzb", "uz"), - std::make_pair("ven", "ve"), std::make_pair("vie", "vi"), - std::make_pair("vol", "vo"), std::make_pair("cym", "cy"), - std::make_pair("wln", "wa"), std::make_pair("wol", "wo"), - std::make_pair("xho", "xh"), std::make_pair("yid", "yi"), - std::make_pair("yor", "yo"), std::make_pair("zha", "za"), - std::make_pair("zho", "zh"), std::make_pair("zul", "zu"), + std::make_pair("aar", "aa"), std::make_pair("abk", "ab"), std::make_pair("afr", "af"), std::make_pair("aka", "ak"), + std::make_pair("sqi", "sq"), std::make_pair("amh", "am"), std::make_pair("ara", "ar"), std::make_pair("arg", "an"), + std::make_pair("hye", "hy"), std::make_pair("asm", "as"), std::make_pair("ava", "av"), std::make_pair("ave", "ae"), + std::make_pair("aym", "ay"), std::make_pair("aze", "az"), std::make_pair("bak", "ba"), std::make_pair("bam", "bm"), + std::make_pair("eus", "eu"), std::make_pair("bel", "be"), std::make_pair("ben", "bn"), std::make_pair("bih", "bh"), + std::make_pair("bis", "bi"), std::make_pair("bod", "bo"), std::make_pair("bos", "bs"), std::make_pair("bre", "br"), + std::make_pair("bul", "bg"), std::make_pair("mya", "my"), std::make_pair("cat", "ca"), std::make_pair("ces", "cs"), + std::make_pair("cha", "ch"), std::make_pair("che", "ce"), std::make_pair("zho", "zh"), std::make_pair("chu", "cu"), + std::make_pair("chv", "cv"), std::make_pair("cor", "kw"), std::make_pair("cos", "co"), std::make_pair("cre", "cr"), + std::make_pair("cym", "cy"), std::make_pair("ces", "cs"), std::make_pair("dan", "da"), std::make_pair("deu", "de"), + std::make_pair("div", "dv"), std::make_pair("nld", "nl"), std::make_pair("dzo", "dz"), std::make_pair("ell", "el"), + std::make_pair("eng", "en"), std::make_pair("epo", "eo"), std::make_pair("est", "et"), std::make_pair("eus", "eu"), + std::make_pair("ewe", "ee"), std::make_pair("fao", "fo"), std::make_pair("fas", "fa"), std::make_pair("fij", "fj"), + std::make_pair("fin", "fi"), std::make_pair("fra", "fr"), std::make_pair("fra", "fr"), std::make_pair("fry", "fy"), + std::make_pair("ful", "ff"), std::make_pair("kat", "ka"), std::make_pair("deu", "de"), std::make_pair("gla", "gd"), + std::make_pair("gle", "ga"), std::make_pair("glg", "gl"), std::make_pair("glv", "gv"), std::make_pair("ell", "el"), + std::make_pair("grn", "gn"), std::make_pair("guj", "gu"), std::make_pair("hat", "ht"), std::make_pair("hau", "ha"), + std::make_pair("heb", "he"), std::make_pair("her", "hz"), std::make_pair("hin", "hi"), std::make_pair("hmo", "ho"), + std::make_pair("hrv", "hr"), std::make_pair("hun", "hu"), std::make_pair("hye", "hy"), std::make_pair("ibo", "ig"), + std::make_pair("isl", "is"), std::make_pair("ido", "io"), std::make_pair("iii", "ii"), std::make_pair("iku", "iu"), + std::make_pair("ile", "ie"), std::make_pair("ina", "ia"), std::make_pair("ind", "id"), std::make_pair("ipk", "ik"), + std::make_pair("isl", "is"), std::make_pair("ita", "it"), std::make_pair("jav", "jv"), std::make_pair("jpn", "ja"), + std::make_pair("kal", "kl"), std::make_pair("kan", "kn"), std::make_pair("kas", "ks"), std::make_pair("kat", "ka"), + std::make_pair("kau", "kr"), std::make_pair("kaz", "kk"), std::make_pair("khm", "km"), std::make_pair("kik", "ki"), + std::make_pair("kin", "rw"), std::make_pair("kir", "ky"), std::make_pair("kom", "kv"), std::make_pair("kon", "kg"), + std::make_pair("kor", "ko"), std::make_pair("kua", "kj"), std::make_pair("kur", "ku"), std::make_pair("lao", "lo"), + std::make_pair("lat", "la"), std::make_pair("lav", "lv"), std::make_pair("lim", "li"), std::make_pair("lin", "ln"), + std::make_pair("lit", "lt"), std::make_pair("ltz", "lb"), std::make_pair("lub", "lu"), std::make_pair("lug", "lg"), + std::make_pair("mkd", "mk"), std::make_pair("mah", "mh"), std::make_pair("mal", "ml"), std::make_pair("mri", "mi"), + std::make_pair("mar", "mr"), std::make_pair("msa", "ms"), std::make_pair("mkd", "mk"), std::make_pair("mlg", "mg"), + std::make_pair("mlt", "mt"), std::make_pair("mon", "mn"), std::make_pair("mri", "mi"), std::make_pair("msa", "ms"), + std::make_pair("mya", "my"), std::make_pair("nau", "na"), std::make_pair("nav", "nv"), std::make_pair("nbl", "nr"), + std::make_pair("nde", "nd"), std::make_pair("ndo", "ng"), std::make_pair("nep", "ne"), std::make_pair("nld", "nl"), + std::make_pair("nno", "nn"), std::make_pair("nob", "nb"), std::make_pair("nor", "no"), std::make_pair("nya", "ny"), + std::make_pair("oci", "oc"), std::make_pair("oji", "oj"), std::make_pair("ori", "or"), std::make_pair("orm", "om"), + std::make_pair("oss", "os"), std::make_pair("pan", "pa"), std::make_pair("fas", "fa"), std::make_pair("pli", "pi"), + std::make_pair("pol", "pl"), std::make_pair("por", "pt"), std::make_pair("pus", "ps"), std::make_pair("que", "qu"), + std::make_pair("roh", "rm"), std::make_pair("ron", "ro"), std::make_pair("ron", "ro"), std::make_pair("run", "rn"), + std::make_pair("rus", "ru"), std::make_pair("sag", "sg"), std::make_pair("san", "sa"), std::make_pair("sin", "si"), + std::make_pair("slk", "sk"), std::make_pair("slk", "sk"), std::make_pair("slv", "sl"), std::make_pair("sme", "se"), + std::make_pair("smo", "sm"), std::make_pair("sna", "sn"), std::make_pair("snd", "sd"), std::make_pair("som", "so"), + std::make_pair("sot", "st"), std::make_pair("spa", "es"), std::make_pair("sqi", "sq"), std::make_pair("srd", "sc"), + std::make_pair("srp", "sr"), std::make_pair("ssw", "ss"), std::make_pair("sun", "su"), std::make_pair("swa", "sw"), + std::make_pair("swe", "sv"), std::make_pair("tah", "ty"), std::make_pair("tam", "ta"), std::make_pair("tat", "tt"), + std::make_pair("tel", "te"), std::make_pair("tgk", "tg"), std::make_pair("tgl", "tl"), std::make_pair("tha", "th"), + std::make_pair("bod", "bo"), std::make_pair("tir", "ti"), std::make_pair("ton", "to"), std::make_pair("tsn", "tn"), + std::make_pair("tso", "ts"), std::make_pair("tuk", "tk"), std::make_pair("tur", "tr"), std::make_pair("twi", "tw"), + std::make_pair("uig", "ug"), std::make_pair("ukr", "uk"), std::make_pair("urd", "ur"), std::make_pair("uzb", "uz"), + std::make_pair("ven", "ve"), std::make_pair("vie", "vi"), std::make_pair("vol", "vo"), std::make_pair("cym", "cy"), + std::make_pair("wln", "wa"), std::make_pair("wol", "wo"), std::make_pair("xho", "xh"), std::make_pair("yid", "yi"), + std::make_pair("yor", "yo"), std::make_pair("zha", "za"), std::make_pair("zho", "zh"), std::make_pair("zul", "zu"), }; diff --git a/src/lib/deskflow/unix/X11LayoutsParser.cpp b/src/lib/deskflow/unix/X11LayoutsParser.cpp index dc2af1a80..dd2f49add 100644 --- a/src/lib/deskflow/unix/X11LayoutsParser.cpp +++ b/src/lib/deskflow/unix/X11LayoutsParser.cpp @@ -28,7 +28,8 @@ namespace { -void splitLine(std::vector &parts, const String &line, char delimiter) { +void splitLine(std::vector &parts, const String &line, char delimiter) +{ std::stringstream stream(line); while (stream.good()) { String part; @@ -39,8 +40,8 @@ void splitLine(std::vector &parts, const String &line, char delimiter) { } // namespace -bool X11LayoutsParser::readXMLConfigItemElem( - const pugi::xml_node *root, std::vector &langList) { +bool X11LayoutsParser::readXMLConfigItemElem(const pugi::xml_node *root, std::vector &langList) +{ auto configItemElem = root->child("configItem"); if (!configItemElem) { LOG((CLOG_WARN "failed to read \"configItem\" in xml file")); @@ -56,16 +57,15 @@ bool X11LayoutsParser::readXMLConfigItemElem( auto languageListElem = configItemElem.child("languageList"); if (languageListElem) { for (pugi::xml_node isoElem : languageListElem.children("iso639Id")) { - langList.back().layoutBaseISO639_2.emplace_back( - isoElem.text().as_string()); + langList.back().layoutBaseISO639_2.emplace_back(isoElem.text().as_string()); } } return true; } -std::vector -X11LayoutsParser::getAllLanguageData(const String &pathToEvdevFile) { +std::vector X11LayoutsParser::getAllLanguageData(const String &pathToEvdevFile) +{ std::vector allCodes; pugi::xml_document doc; if (!doc.load_file(pathToEvdevFile.c_str())) { @@ -75,9 +75,7 @@ X11LayoutsParser::getAllLanguageData(const String &pathToEvdevFile) { auto xkbConfigElem = doc.child("xkbConfigRegistry"); if (!xkbConfigElem) { - LOG( - (CLOG_WARN "failed to read xkbConfigRegistry in %s", - pathToEvdevFile.c_str())); + LOG((CLOG_WARN "failed to read xkbConfigRegistry in %s", pathToEvdevFile.c_str())); return allCodes; } @@ -103,25 +101,22 @@ X11LayoutsParser::getAllLanguageData(const String &pathToEvdevFile) { return allCodes; } -void X11LayoutsParser::appendVectorUniq( - const std::vector &source, std::vector &dst) { +void X11LayoutsParser::appendVectorUniq(const std::vector &source, std::vector &dst) +{ for (const auto &elem : source) { - if (std::find_if(dst.begin(), dst.end(), [elem](const String &s) { - return s == elem; - }) == dst.end()) { + if (std::find_if(dst.begin(), dst.end(), [elem](const String &s) { return s == elem; }) == dst.end()) { dst.push_back(elem); } } }; void X11LayoutsParser::convertLayoutToISO639_2( - const String &pathToEvdevFile, bool needToReloadEvdev, - const std::vector &layoutNames, - const std::vector &layoutVariantNames, - std::vector &iso639_2Codes) { + const String &pathToEvdevFile, bool needToReloadEvdev, const std::vector &layoutNames, + const std::vector &layoutVariantNames, std::vector &iso639_2Codes +) +{ if (layoutNames.size() != layoutVariantNames.size()) { - LOG((CLOG_WARN - "error in language layout or language layout variants list")); + LOG((CLOG_WARN "error in language layout or language layout variants list")); return; } @@ -131,9 +126,8 @@ void X11LayoutsParser::convertLayoutToISO639_2( } for (size_t i = 0; i < layoutNames.size(); i++) { const auto &layoutName = layoutNames[i]; - auto langIter = std::find_if( - allLang.begin(), allLang.end(), - [&layoutName](const Lang &l) { return l.name == layoutName; }); + auto langIter = + std::find_if(allLang.begin(), allLang.end(), [&layoutName](const Lang &l) { return l.name == layoutName; }); if (langIter == allLang.end()) { LOG((CLOG_WARN "language \"%s\" is unknown", layoutNames[i].c_str())); continue; @@ -144,13 +138,15 @@ void X11LayoutsParser::convertLayoutToISO639_2( toCopy = &langIter->layoutBaseISO639_2; } else { const auto &variantName = layoutVariantNames[i]; - auto langVariantIter = std::find_if( - langIter->variants.begin(), langIter->variants.end(), - [&variantName](const Lang &l) { return l.name == variantName; }); + auto langVariantIter = + std::find_if(langIter->variants.begin(), langIter->variants.end(), [&variantName](const Lang &l) { + return l.name == variantName; + }); if (langVariantIter == langIter->variants.end()) { LOG( - (CLOG_WARN "variant \"%s\" of language \"%s\" is unknown", - layoutVariantNames[i].c_str(), layoutNames[i].c_str())); + (CLOG_WARN "variant \"%s\" of language \"%s\" is unknown", layoutVariantNames[i].c_str(), + layoutNames[i].c_str()) + ); continue; } @@ -167,8 +163,8 @@ void X11LayoutsParser::convertLayoutToISO639_2( } } -std::vector -X11LayoutsParser::getX11LanguageList(const String &pathToEvdevFile) { +std::vector X11LayoutsParser::getX11LanguageList(const String &pathToEvdevFile) +{ std::vector layoutNames; std::vector layoutVariantNames; @@ -178,22 +174,17 @@ X11LayoutsParser::getX11LanguageList(const String &pathToEvdevFile) { std::vector iso639_2Codes; iso639_2Codes.reserve(layoutNames.size()); - convertLayoutToISO639_2( - pathToEvdevFile, true, layoutNames, layoutVariantNames, iso639_2Codes); + convertLayoutToISO639_2(pathToEvdevFile, true, layoutNames, layoutVariantNames, iso639_2Codes); return convertISO639_2ToISO639_1(iso639_2Codes); } -String X11LayoutsParser::convertLayotToISO( - const String &pathToEvdevFile, const String &layoutLangCode, - bool needToReloadFiles) { +String +X11LayoutsParser::convertLayotToISO(const String &pathToEvdevFile, const String &layoutLangCode, bool needToReloadFiles) +{ std::vector iso639_2Codes; - convertLayoutToISO639_2( - pathToEvdevFile, needToReloadFiles, {layoutLangCode}, {""}, - iso639_2Codes); + convertLayoutToISO639_2(pathToEvdevFile, needToReloadFiles, {layoutLangCode}, {""}, iso639_2Codes); if (iso639_2Codes.empty()) { - LOG( - (CLOG_WARN "failed to convert layout lang code: \"%s\"", - layoutLangCode.c_str())); + LOG((CLOG_WARN "failed to convert layout lang code: \"%s\"", layoutLangCode.c_str())); return ""; } @@ -206,19 +197,16 @@ String X11LayoutsParser::convertLayotToISO( return *iso639_1Codes.begin(); } -std::vector X11LayoutsParser::convertISO639_2ToISO639_1( - const std::vector &iso639_2Codes) { +std::vector X11LayoutsParser::convertISO639_2ToISO639_1(const std::vector &iso639_2Codes) +{ std::vector result; for (const auto &isoCode : iso639_2Codes) { - const auto &tableIter = std::find_if( - ISO_Table.begin(), ISO_Table.end(), - [&isoCode](const std::pair &c) { + const auto &tableIter = + std::find_if(ISO_Table.begin(), ISO_Table.end(), [&isoCode](const std::pair &c) { return c.first == isoCode; }); if (tableIter == ISO_Table.end()) { - LOG( - (CLOG_WARN "the ISO 639-2 code \"%s\" is missed in table", - isoCode.c_str())); + LOG((CLOG_WARN "the ISO 639-2 code \"%s\" is missed in table", isoCode.c_str())); continue; } diff --git a/src/lib/deskflow/unix/X11LayoutsParser.h b/src/lib/deskflow/unix/X11LayoutsParser.h index fab08b188..01947c25a 100644 --- a/src/lib/deskflow/unix/X11LayoutsParser.h +++ b/src/lib/deskflow/unix/X11LayoutsParser.h @@ -24,36 +24,33 @@ namespace pugi { class xml_node; } -class X11LayoutsParser { +class X11LayoutsParser +{ public: static std::vector getX11LanguageList(const String &pathToEvdevFile); - static String convertLayotToISO( - const String &pathToEvdevFile, const String &layoutLangCode, - bool needToReloadFiles = false); + static String + convertLayotToISO(const String &pathToEvdevFile, const String &layoutLangCode, bool needToReloadFiles = false); private: - struct Lang { + struct Lang + { String name = ""; std::vector layoutBaseISO639_2; std::vector variants; }; - static bool readXMLConfigItemElem( - const pugi::xml_node *root, std::vector &langList); + static bool readXMLConfigItemElem(const pugi::xml_node *root, std::vector &langList); static std::vector getAllLanguageData(const String &pathToEvdevFile); - static void - appendVectorUniq(const std::vector &source, std::vector &dst); + static void appendVectorUniq(const std::vector &source, std::vector &dst); static void convertLayoutToISO639_2( - const String &pathToEvdevFile, bool needToReloadEvdev, - const std::vector &layoutNames, - const std::vector &layoutVariantNames, - std::vector &iso639_2Codes); + const String &pathToEvdevFile, bool needToReloadEvdev, const std::vector &layoutNames, + const std::vector &layoutVariantNames, std::vector &iso639_2Codes + ); - static std::vector - convertISO639_2ToISO639_1(const std::vector &iso639_2Codes); + static std::vector convertISO639_2ToISO639_1(const std::vector &iso639_2Codes); }; #endif // WINAPI_XWINDOWS diff --git a/src/lib/deskflow/win32/AppUtilWindows.cpp b/src/lib/deskflow/win32/AppUtilWindows.cpp index 0ea74aa4f..fe668d626 100644 --- a/src/lib/deskflow/win32/AppUtilWindows.cpp +++ b/src/lib/deskflow/win32/AppUtilWindows.cpp @@ -44,33 +44,40 @@ #include "wintoastlib.h" #endif -AppUtilWindows::AppUtilWindows(IEventQueue *events) - : m_events(events), - m_exitMode(kExitModeNormal) { +AppUtilWindows::AppUtilWindows(IEventQueue *events) : m_events(events), m_exitMode(kExitModeNormal) +{ if (SetConsoleCtrlHandler((PHANDLER_ROUTINE)consoleHandler, TRUE) == FALSE) { throw XArch(new XArchEvalWindows()); } } -AppUtilWindows::~AppUtilWindows() {} +AppUtilWindows::~AppUtilWindows() +{ +} -BOOL WINAPI AppUtilWindows::consoleHandler(DWORD) { +BOOL WINAPI AppUtilWindows::consoleHandler(DWORD) +{ LOG((CLOG_INFO "got shutdown signal")); IEventQueue *events = AppUtil::instance().app().getEvents(); events->addEvent(Event(Event::kQuit)); return TRUE; } -static int mainLoopStatic() { return AppUtil::instance().app().mainLoop(); } +static int mainLoopStatic() +{ + return AppUtil::instance().app().mainLoop(); +} -int AppUtilWindows::daemonNTMainLoop(int argc, const char **argv) { +int AppUtilWindows::daemonNTMainLoop(int argc, const char **argv) +{ app().initApp(argc, argv); debugServiceWait(); return ArchMiscWindows::runDaemon(mainLoopStatic); } -void AppUtilWindows::exitApp(int code) { +void AppUtilWindows::exitApp(int code) +{ switch (m_exitMode) { case kExitModeDaemon: @@ -82,25 +89,30 @@ void AppUtilWindows::exitApp(int code) { } } -int daemonNTMainLoopStatic(int argc, const char **argv) { +int daemonNTMainLoopStatic(int argc, const char **argv) +{ return AppUtilWindows::instance().daemonNTMainLoop(argc, argv); } -int AppUtilWindows::daemonNTStartup(int, char **) { +int AppUtilWindows::daemonNTStartup(int, char **) +{ SystemLogger sysLogger(app().daemonName(), false); m_exitMode = kExitModeDaemon; return ARCH->daemonize(app().daemonName(), daemonNTMainLoopStatic); } -static int daemonNTStartupStatic(int argc, char **argv) { +static int daemonNTStartupStatic(int argc, char **argv) +{ return AppUtilWindows::instance().daemonNTStartup(argc, argv); } -static int foregroundStartupStatic(int argc, char **argv) { +static int foregroundStartupStatic(int argc, char **argv) +{ return AppUtil::instance().app().foregroundStartup(argc, argv); } -void AppUtilWindows::beforeAppExit() { +void AppUtilWindows::beforeAppExit() +{ // this can be handy for debugging, since the application is launched in // a new console window, and will normally close on exit (making it so // that we can't see error messages). @@ -110,10 +122,10 @@ void AppUtilWindows::beforeAppExit() { } } -int AppUtilWindows::run(int argc, char **argv) { +int AppUtilWindows::run(int argc, char **argv) +{ if (!IsWindowsXPSP3OrGreater()) { - throw std::runtime_error( - "unsupported os version, xp sp3 or greater required"); + throw std::runtime_error("unsupported os version, xp sp3 or greater required"); } // record window instance for tray icon, etc @@ -133,11 +145,13 @@ int AppUtilWindows::run(int argc, char **argv) { return app().runInner(argc, argv, NULL, startup); } -AppUtilWindows &AppUtilWindows::instance() { +AppUtilWindows &AppUtilWindows::instance() +{ return (AppUtilWindows &)AppUtil::instance(); } -void AppUtilWindows::debugServiceWait() { +void AppUtilWindows::debugServiceWait() +{ if (app().argsBase().m_debugServiceWait) { while (true) { // this code is only executed when the process is launched via the @@ -150,9 +164,13 @@ void AppUtilWindows::debugServiceWait() { } } -void AppUtilWindows::startNode() { app().startNode(); } +void AppUtilWindows::startNode() +{ + app().startNode(); +} -std::vector AppUtilWindows::getKeyboardLayoutList() { +std::vector AppUtilWindows::getKeyboardLayoutList() +{ std::vector layoutLangCodes; { auto uLayouts = GetKeyboardLayoutList(0, NULL); @@ -162,8 +180,9 @@ std::vector AppUtilWindows::getKeyboardLayoutList() { for (int i = 0; i < uLayouts; ++i) { String code("", 2); GetLocaleInfoA( - MAKELCID(((ULONG_PTR)lpList[i] & 0xffffffff), SORT_DEFAULT), - LOCALE_SISO639LANGNAME, &code[0], static_cast(code.size())); + MAKELCID(((ULONG_PTR)lpList[i] & 0xffffffff), SORT_DEFAULT), LOCALE_SISO639LANGNAME, &code[0], + static_cast(code.size()) + ); layoutLangCodes.push_back(code); } @@ -174,21 +193,21 @@ std::vector AppUtilWindows::getKeyboardLayoutList() { return layoutLangCodes; } -String AppUtilWindows::getCurrentLanguageCode() { +String AppUtilWindows::getCurrentLanguageCode() +{ String code("", 2); auto hklLayout = getCurrentKeyboardLayout(); if (hklLayout) { auto localLayoutID = MAKELCID(LOWORD(hklLayout), SORT_DEFAULT); - GetLocaleInfoA( - localLayoutID, LOCALE_SISO639LANGNAME, &code[0], - static_cast(code.size())); + GetLocaleInfoA(localLayoutID, LOCALE_SISO639LANGNAME, &code[0], static_cast(code.size())); } return code; } -HKL AppUtilWindows::getCurrentKeyboardLayout() const { +HKL AppUtilWindows::getCurrentKeyboardLayout() const +{ HKL layout = nullptr; GUITHREADINFO gti = {sizeof(GUITHREADINFO)}; @@ -202,23 +221,32 @@ HKL AppUtilWindows::getCurrentKeyboardLayout() const { } #if HAVE_WINTOAST -class WinToastHandler : public WinToastLib::IWinToastHandler { +class WinToastHandler : public WinToastLib::IWinToastHandler +{ public: - WinToastHandler() {} + WinToastHandler() + { + } // Public interfaces - void toastActivated() const override {} - void toastActivated(int actionIndex) const override {} - void toastDismissed(WinToastDismissalReason state) const override {} - void toastFailed() const override {} + void toastActivated() const override + { + } + void toastActivated(int actionIndex) const override + { + } + void toastDismissed(WinToastDismissalReason state) const override + { + } + void toastFailed() const override + { + } }; #endif -void AppUtilWindows::showNotification( - const String &title, const String &text) const { +void AppUtilWindows::showNotification(const String &title, const String &text) const +{ #if HAVE_WINTOAST - LOG( - (CLOG_INFO "showing notification, title=\"%s\", text=\"%s\"", - title.c_str(), text.c_str())); + LOG((CLOG_INFO "showing notification, title=\"%s\", text=\"%s\"", title.c_str(), text.c_str())); if (!WinToastLib::WinToast::isCompatible()) { LOG((CLOG_INFO "this system does not support toast notifications")); return; @@ -226,8 +254,8 @@ void AppUtilWindows::showNotification( if (!WinToastLib::WinToast::instance()->isInitialized()) { WinToastLib::WinToast::instance()->setAppName(L"" DESKFLOW_APP_NAME); const auto aumi = WinToastLib::WinToast::configureAUMI( - L"" DESKFLOW_AUTHOR_NAME, L"" DESKFLOW_APP_NAME, L"" DESKFLOW_APP_NAME, - L"1.14.1+"); + L"" DESKFLOW_AUTHOR_NAME, L"" DESKFLOW_APP_NAME, L"" DESKFLOW_APP_NAME, L"1.14.1+" + ); WinToastLib::WinToast::instance()->setAppUserModelId(aumi); if (!WinToastLib::WinToast::instance()->initialize()) { @@ -238,20 +266,13 @@ void AppUtilWindows::showNotification( WinToastLib::WinToast::WinToastError error; auto handler = std::make_unique(); - WinToastLib::WinToastTemplate templ = - WinToastLib::WinToastTemplate(WinToastLib::WinToastTemplate::Text02); - templ.setTextField( - std::wstring(title.begin(), title.end()), - WinToastLib::WinToastTemplate::FirstLine); - templ.setTextField( - std::wstring(text.begin(), text.end()), - WinToastLib::WinToastTemplate::SecondLine); + WinToastLib::WinToastTemplate templ = WinToastLib::WinToastTemplate(WinToastLib::WinToastTemplate::Text02); + templ.setTextField(std::wstring(title.begin(), title.end()), WinToastLib::WinToastTemplate::FirstLine); + templ.setTextField(std::wstring(text.begin(), text.end()), WinToastLib::WinToastTemplate::SecondLine); - const bool launched = WinToastLib::WinToast::instance()->showToast( - templ, handler.get(), &error); + const bool launched = WinToastLib::WinToast::instance()->showToast(templ, handler.get(), &error); if (!launched) { - LOG(( - CLOG_DEBUG "failed to show toast notification, error code: %d", error)); + LOG((CLOG_DEBUG "failed to show toast notification, error code: %d", error)); return; } #else diff --git a/src/lib/deskflow/win32/AppUtilWindows.h b/src/lib/deskflow/win32/AppUtilWindows.h index c9382b9fa..46230beca 100644 --- a/src/lib/deskflow/win32/AppUtilWindows.h +++ b/src/lib/deskflow/win32/AppUtilWindows.h @@ -27,9 +27,14 @@ class IEventQueue; -enum AppExitMode { kExitModeNormal, kExitModeDaemon }; +enum AppExitMode +{ + kExitModeNormal, + kExitModeDaemon +}; -class AppUtilWindows : public AppUtil { +class AppUtilWindows : public AppUtil +{ public: AppUtilWindows(IEventQueue *events); virtual ~AppUtilWindows(); diff --git a/src/lib/gui/Logger.cpp b/src/lib/gui/Logger.cpp index c979974c9..bc968a9b8 100644 --- a/src/lib/gui/Logger.cpp +++ b/src/lib/gui/Logger.cpp @@ -32,14 +32,14 @@ namespace deskflow::gui { const auto kForceDebugMessages = QStringList{ "No functional TLS backend was found", "No TLS backend is available", - "QSslSocket::connectToHostEncrypted: TLS initialization failed", - "Retrying to obtain clipboard.", "Unable to obtain clipboard."}; + "QSslSocket::connectToHostEncrypted: TLS initialization failed", "Retrying to obtain clipboard.", + "Unable to obtain clipboard." +}; Logger Logger::s_instance; -QString printLine( - FILE *out, const QString &type, const QString &message, - const QString &fileLine = "") { +QString printLine(FILE *out, const QString &type, const QString &message, const QString &fileLine = "") +{ auto datetime = QDateTime::currentDateTime().toString("yyyy-MM-ddTHH:mm:ss"); auto logLine = QString("[%1] %2: %3").arg(datetime).arg(type).arg(message); @@ -68,7 +68,8 @@ QString printLine( return logLine; } -void Logger::loadEnvVars() { +void Logger::loadEnvVars() +{ const auto debugEnvVar = qEnvironmentVariable("DESKFLOW_GUI_DEBUG"); if (!debugEnvVar.isEmpty()) { m_debug = strToTrue(debugEnvVar); @@ -80,14 +81,15 @@ void Logger::loadEnvVars() { } } -void Logger::logVerbose(const QString &message) const { +void Logger::logVerbose(const QString &message) const +{ if (m_verbose) { printLine(stdout, "VERBOSE", message); } } -void Logger::handleMessage( - const QtMsgType type, const QString &fileLine, const QString &message) { +void Logger::handleMessage(const QtMsgType type, const QString &fileLine, const QString &message) +{ auto mutatedType = type; if (kForceDebugMessages.contains(message)) { diff --git a/src/lib/gui/Logger.h b/src/lib/gui/Logger.h index 7d53cb68e..5cab51e9d 100644 --- a/src/lib/gui/Logger.h +++ b/src/lib/gui/Logger.h @@ -27,15 +27,18 @@ const bool kDebug = true; namespace deskflow::gui { -class Logger : public QObject { +class Logger : public QObject +{ Q_OBJECT public: - static Logger &instance() { return s_instance; } + static Logger &instance() + { + return s_instance; + } void loadEnvVars(); - void handleMessage( - const QtMsgType type, const QString &fileLine, const QString &message); + void handleMessage(const QtMsgType type, const QString &fileLine, const QString &message); void logVerbose(const QString &message) const; signals: @@ -47,7 +50,8 @@ private: bool m_verbose = false; }; -inline void logVerbose(const QString &message) { +inline void logVerbose(const QString &message) +{ Logger::instance().logVerbose(message); } diff --git a/src/lib/gui/OSXHelpers.h b/src/lib/gui/OSXHelpers.h index a2db5cd9f..b6c3ab978 100644 --- a/src/lib/gui/OSXHelpers.h +++ b/src/lib/gui/OSXHelpers.h @@ -19,7 +19,12 @@ #include -enum class IconsTheme { ICONS_DARK, ICONS_LIGHT, ICONS_TEMPLATE }; +enum class IconsTheme +{ + ICONS_DARK, + ICONS_LIGHT, + ICONS_TEMPLATE +}; void requestOSXNotificationPermission(); bool isOSXDevelopmentBuild(); diff --git a/src/lib/gui/TrayIcon.cpp b/src/lib/gui/TrayIcon.cpp index b59dde8f8..b2f0b0af7 100644 --- a/src/lib/gui/TrayIcon.cpp +++ b/src/lib/gui/TrayIcon.cpp @@ -24,14 +24,16 @@ namespace deskflow::gui { const auto kShowRetryInterval = 1000; -void TrayIcon::setIcon(const QIcon &icon) { +void TrayIcon::setIcon(const QIcon &icon) +{ m_icon = icon; if (m_pTrayIcon && !icon.isNull()) { m_pTrayIcon->setIcon(icon); } } -void TrayIcon::showRetryLoop() { +void TrayIcon::showRetryLoop() +{ // HACK: apparently this is needed to create a dbus connection, and the hide // is needed to make use of the object so the dbus connection doesn't get // optimized away by the compiler. @@ -44,13 +46,13 @@ void TrayIcon::showRetryLoop() { } else { // on some platforms, it's not always possible to create the tray when the // app starts, so keep trying until it is possible. - logVerbose(QString("system tray not ready yet, retrying in %1 ms") - .arg(kShowRetryInterval)); + logVerbose(QString("system tray not ready yet, retrying in %1 ms").arg(kShowRetryInterval)); QTimer::singleShot(kShowRetryInterval, this, &TrayIcon::showRetryLoop); } } -void TrayIcon::create(std::vector const &actions) { +void TrayIcon::create(std::vector const &actions) +{ m_pTrayIconMenu = std::make_unique(); for (auto action : actions) { @@ -64,9 +66,7 @@ void TrayIcon::create(std::vector const &actions) { m_pTrayIcon = std::make_unique(); setIcon(m_icon); - connect( - m_pTrayIcon.get(), &QSystemTrayIcon::activated, this, - &TrayIcon::activated); + connect(m_pTrayIcon.get(), &QSystemTrayIcon::activated, this, &TrayIcon::activated); m_pTrayIcon->setContextMenu(m_pTrayIconMenu.get()); m_pTrayIcon->setToolTip(kAppName); diff --git a/src/lib/gui/TrayIcon.h b/src/lib/gui/TrayIcon.h index 70322f058..1fc617315 100644 --- a/src/lib/gui/TrayIcon.h +++ b/src/lib/gui/TrayIcon.h @@ -26,7 +26,8 @@ namespace deskflow::gui { -class TrayIcon : public QObject { +class TrayIcon : public QObject +{ Q_OBJECT public: explicit TrayIcon() = default; diff --git a/src/lib/gui/VersionChecker.cpp b/src/lib/gui/VersionChecker.cpp index ceff1b3f8..c69d4a179 100644 --- a/src/lib/gui/VersionChecker.cpp +++ b/src/lib/gui/VersionChecker.cpp @@ -30,38 +30,30 @@ using namespace deskflow::gui; -VersionChecker::VersionChecker( - std::shared_ptr network) - : m_network( - network ? network : std::make_shared()) { +VersionChecker::VersionChecker(std::shared_ptr network) + : m_network(network ? network : std::make_shared()) +{ m_network->init(); - connect( - m_network.get(), &QNetworkAccessManagerProxy::finished, this, - &VersionChecker::replyFinished); + connect(m_network.get(), &QNetworkAccessManagerProxy::finished, this, &VersionChecker::replyFinished); } -void VersionChecker::checkLatest() const { +void VersionChecker::checkLatest() const +{ const QString url = env_vars::versionUrl(); qDebug("checking for updates at: %s", qPrintable(url)); auto request = QNetworkRequest(url); - auto userAgent = QString("%1 %2 on %3") - .arg(kAppName) - .arg(kVersion) - .arg(QSysInfo::prettyProductName()); + auto userAgent = QString("%1 %2 on %3").arg(kAppName).arg(kVersion).arg(QSysInfo::prettyProductName()); request.setHeader(QNetworkRequest::UserAgentHeader, userAgent); request.setRawHeader("X-" DESKFLOW_APP_NAME "-Version", kVersion); - request.setRawHeader( - "X-" DESKFLOW_APP_NAME "-Language", - QLocale::system().name().toStdString().c_str()); + request.setRawHeader("X-" DESKFLOW_APP_NAME "-Language", QLocale::system().name().toStdString().c_str()); m_network->get(request); } -void VersionChecker::replyFinished(QNetworkReply *reply) { - const auto httpStatus = - reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); +void VersionChecker::replyFinished(QNetworkReply *reply) +{ + const auto httpStatus = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute).toInt(); if (reply->error() != QNetworkReply::NoError) { - qWarning( - "version check server error: %s", qPrintable(reply->errorString())); + qWarning("version check server error: %s", qPrintable(reply->errorString())); qWarning("error checking for updates, http status: %d", httpStatus); return; } @@ -71,8 +63,7 @@ void VersionChecker::replyFinished(QNetworkReply *reply) { const auto newestVersion = QString(reply->readAll()); qDebug("version check response: %s", qPrintable(newestVersion)); - if (!newestVersion.isEmpty() && - compareVersions(DESKFLOW_VERSION, newestVersion) > 0) { + if (!newestVersion.isEmpty() && compareVersions(DESKFLOW_VERSION, newestVersion) > 0) { qDebug("update found"); emit updateFound(newestVersion); } else { @@ -80,7 +71,8 @@ void VersionChecker::replyFinished(QNetworkReply *reply) { } } -int VersionChecker::getStageVersion(QString stage) { +int VersionChecker::getStageVersion(QString stage) +{ const char *stableName = "stable"; const char *rcName = "rc"; const char *betaName = "beta"; @@ -107,7 +99,8 @@ int VersionChecker::getStageVersion(QString stage) { return otherValue; } -int VersionChecker::compareVersions(const QString &left, const QString &right) { +int VersionChecker::compareVersions(const QString &left, const QString &right) +{ if (left.compare(right) == 0) return 0; // versions are same. @@ -134,12 +127,9 @@ int VersionChecker::compareVersions(const QString &left, const QString &right) { const int rightStage = getStageVersion(rightStagePart); const bool rightWins = - (rightMajor > leftMajor) || - ((rightMajor >= leftMajor) && (rightMinor > leftMinor)) || - ((rightMajor >= leftMajor) && (rightMinor >= leftMinor) && - (rightPatch > leftPatch)) || - ((rightMajor >= leftMajor) && (rightMinor >= leftMinor) && - (rightPatch >= leftPatch) && (rightStage > leftStage)); + (rightMajor > leftMajor) || ((rightMajor >= leftMajor) && (rightMinor > leftMinor)) || + ((rightMajor >= leftMajor) && (rightMinor >= leftMinor) && (rightPatch > leftPatch)) || + ((rightMajor >= leftMajor) && (rightMinor >= leftMinor) && (rightPatch >= leftPatch) && (rightStage > leftStage)); return rightWins ? 1 : -1; } diff --git a/src/lib/gui/VersionChecker.h b/src/lib/gui/VersionChecker.h index f99e32dc5..912819ef2 100644 --- a/src/lib/gui/VersionChecker.h +++ b/src/lib/gui/VersionChecker.h @@ -27,17 +27,16 @@ class QNetworkAccessManager; class QNetworkReply; class VersionCheckerTests; -class VersionChecker : public QObject { - using QNetworkAccessManagerProxy = - deskflow::gui::proxy::QNetworkAccessManagerProxy; +class VersionChecker : public QObject +{ + using QNetworkAccessManagerProxy = deskflow::gui::proxy::QNetworkAccessManagerProxy; Q_OBJECT friend class VersionCheckerTests; public: - explicit VersionChecker( - std::shared_ptr network = nullptr); + explicit VersionChecker(std::shared_ptr network = nullptr); void checkLatest() const; public slots: void replyFinished(QNetworkReply *reply); diff --git a/src/lib/gui/byte_utils.h b/src/lib/gui/byte_utils.h index 70a7dbc9d..b1992f9f8 100644 --- a/src/lib/gui/byte_utils.h +++ b/src/lib/gui/byte_utils.h @@ -24,7 +24,8 @@ namespace deskflow::gui { -inline int bytesToInt(const char *buffer, size_t size) { +inline int bytesToInt(const char *buffer, size_t size) +{ QByteArray byteArray(buffer, static_cast(size)); QDataStream stream(byteArray); int result; @@ -32,7 +33,8 @@ inline int bytesToInt(const char *buffer, size_t size) { return result; } -inline QByteArray intToBytes(int value) { +inline QByteArray intToBytes(int value) +{ QByteArray bytes; QDataStream stream(&bytes, QIODevice::WriteOnly); stream << value; diff --git a/src/lib/gui/config/AppConfig.cpp b/src/lib/gui/config/AppConfig.cpp index d4f800f94..99fc081b9 100644 --- a/src/lib/gui/config/AppConfig.cpp +++ b/src/lib/gui/config/AppConfig.cpp @@ -34,8 +34,7 @@ using namespace deskflow::gui; // which will force it to re-run for existing installations. const int kWizardVersion = 8; -static const char *const kLogLevelNames[] = { - "INFO", "DEBUG", "DEBUG1", "DEBUG2"}; +static const char *const kLogLevelNames[] = {"INFO", "DEBUG", "DEBUG1", "DEBUG2"}; #if defined(Q_OS_WIN) const char AppConfig::m_CoreServerName[] = SERVER_BINARY_NAME ".exe"; @@ -97,17 +96,18 @@ const char *const AppConfig::m_SettingsName[] = { "enableUpdateCheck", }; -AppConfig::AppConfig( - deskflow::gui::IConfigScopes &scopes, std::shared_ptr deps) +AppConfig::AppConfig(deskflow::gui::IConfigScopes &scopes, std::shared_ptr deps) : m_Scopes(scopes), m_pDeps(deps), m_ScreenName(deps->hostname()), - m_TlsCertPath(deps->defaultTlsCertPath()) { + m_TlsCertPath(deps->defaultTlsCertPath()) +{ determineScope(); recall(); } -void AppConfig::recall() { +void AppConfig::recall() +{ using enum AppConfig::Setting; qDebug("recalling app config"); @@ -116,15 +116,16 @@ void AppConfig::recall() { recallFromCurrentScope(); } -void AppConfig::recallFromAllScopes() { +void AppConfig::recallFromAllScopes() +{ using enum Setting; m_WizardLastRun = findInAllScopes(kWizardLastRun, m_WizardLastRun).toInt(); - m_LoadFromSystemScope = - findInAllScopes(kLoadSystemSettings, m_LoadFromSystemScope).toBool(); + m_LoadFromSystemScope = findInAllScopes(kLoadSystemSettings, m_LoadFromSystemScope).toBool(); } -void AppConfig::recallFromCurrentScope() { +void AppConfig::recallFromCurrentScope() +{ using enum Setting; recallScreenName(); @@ -135,51 +136,37 @@ void AppConfig::recallFromCurrentScope() { m_LogLevel = getFromCurrentScope(kLogLevel, m_LogLevel).toInt(); m_LogToFile = getFromCurrentScope(kLogToFile, m_LogToFile).toBool(); m_LogFilename = getFromCurrentScope(kLogFilename, m_LogFilename).toString(); - m_StartedBefore = - getFromCurrentScope(kStartedBefore, m_StartedBefore).toBool(); + m_StartedBefore = getFromCurrentScope(kStartedBefore, m_StartedBefore).toBool(); m_AutoHide = getFromCurrentScope(kAutoHide, m_AutoHide).toBool(); m_LastVersion = getFromCurrentScope(kLastVersion, m_LastVersion).toString(); - m_ServerGroupChecked = - getFromCurrentScope(kServerGroupChecked, m_ServerGroupChecked).toBool(); - m_UseExternalConfig = - getFromCurrentScope(kUseExternalConfig, m_UseExternalConfig).toBool(); + m_ServerGroupChecked = getFromCurrentScope(kServerGroupChecked, m_ServerGroupChecked).toBool(); + m_UseExternalConfig = getFromCurrentScope(kUseExternalConfig, m_UseExternalConfig).toBool(); m_ConfigFile = getFromCurrentScope(kConfigFile, m_ConfigFile).toString(); - m_UseInternalConfig = - getFromCurrentScope(kUseInternalConfig, m_UseInternalConfig).toBool(); - m_ClientGroupChecked = - getFromCurrentScope(kClientGroupChecked, m_ClientGroupChecked).toBool(); - m_ServerHostname = - getFromCurrentScope(kServerHostname, m_ServerHostname).toString(); + m_UseInternalConfig = getFromCurrentScope(kUseInternalConfig, m_UseInternalConfig).toBool(); + m_ClientGroupChecked = getFromCurrentScope(kClientGroupChecked, m_ClientGroupChecked).toBool(); + m_ServerHostname = getFromCurrentScope(kServerHostname, m_ServerHostname).toString(); m_PreventSleep = getFromCurrentScope(kPreventSleep, m_PreventSleep).toBool(); m_LanguageSync = getFromCurrentScope(kLanguageSync, m_LanguageSync).toBool(); - m_InvertScrollDirection = - getFromCurrentScope(kInvertScrollDirection, m_InvertScrollDirection) - .toBool(); - m_InvertConnection = - getFromCurrentScope(kInvertConnection, m_InvertConnection).toBool(); - m_EnableService = - getFromCurrentScope(kEnableService, m_EnableService).toBool(); + m_InvertScrollDirection = getFromCurrentScope(kInvertScrollDirection, m_InvertScrollDirection).toBool(); + m_InvertConnection = getFromCurrentScope(kInvertConnection, m_InvertConnection).toBool(); + m_EnableService = getFromCurrentScope(kEnableService, m_EnableService).toBool(); m_CloseToTray = getFromCurrentScope(kCloseToTray, m_CloseToTray).toBool(); m_TlsEnabled = getFromCurrentScope(kTlsEnabled, m_TlsEnabled).toBool(); m_TlsCertPath = getFromCurrentScope(kTlsCertPath, m_TlsCertPath).toString(); m_TlsKeyLength = getFromCurrentScope(kTlsKeyLength, m_TlsKeyLength).toInt(); - m_MainWindowPosition = getFromCurrentScope( - kMainWindowPosition, [](const QVariant &v) { return v.toPoint(); }); - m_MainWindowSize = getFromCurrentScope( - kMainWindowSize, [](const QVariant &v) { return v.toSize(); }); - m_ShowDevThanks = - getFromCurrentScope(kShowDevThanks, m_ShowDevThanks).toBool(); - m_ShowCloseReminder = - getFromCurrentScope(kShowCloseReminder, m_ShowCloseReminder).toBool(); - m_EnableUpdateCheck = getFromCurrentScope( - kEnableUpdateCheck, [](const QVariant &v) { return v.toBool(); }); + m_MainWindowPosition = + getFromCurrentScope(kMainWindowPosition, [](const QVariant &v) { return v.toPoint(); }); + m_MainWindowSize = getFromCurrentScope(kMainWindowSize, [](const QVariant &v) { return v.toSize(); }); + m_ShowDevThanks = getFromCurrentScope(kShowDevThanks, m_ShowDevThanks).toBool(); + m_ShowCloseReminder = getFromCurrentScope(kShowCloseReminder, m_ShowCloseReminder).toBool(); + m_EnableUpdateCheck = getFromCurrentScope(kEnableUpdateCheck, [](const QVariant &v) { return v.toBool(); }); } -void AppConfig::recallScreenName() { +void AppConfig::recallScreenName() +{ using enum Setting; - const auto &screenName = - getFromCurrentScope(kScreenName, m_ScreenName).toString().trimmed(); + const auto &screenName = getFromCurrentScope(kScreenName, m_ScreenName).toString().trimmed(); // for some reason, the screen name can be saved as an empty string // in the config file. this is probably a bug. if this happens, then default @@ -192,7 +179,8 @@ void AppConfig::recallScreenName() { } } -void AppConfig::commit() { +void AppConfig::commit() +{ using enum Setting; qDebug("committing app config"); @@ -211,8 +199,7 @@ void AppConfig::commit() { setInCurrentScope(kLogFilename, m_LogFilename); setInCurrentScope(kStartedBefore, m_StartedBefore); setInCurrentScope(kElevateMode, static_cast(m_ElevateMode)); - setInCurrentScope( - kElevateModeLegacy, m_ElevateMode == ElevateMode::kAlways); + setInCurrentScope(kElevateModeLegacy, m_ElevateMode == ElevateMode::kAlways); setInCurrentScope(kTlsEnabled, m_TlsEnabled); setInCurrentScope(kAutoHide, m_AutoHide); setInCurrentScope(kLastVersion, m_LastVersion); @@ -239,20 +226,17 @@ void AppConfig::commit() { } } -void AppConfig::determineScope() { +void AppConfig::determineScope() +{ qDebug("determining config scope"); // first, try to determine if the system scope should be used according to the // user scope... - if (m_Scopes.scopeContains( - settingName(Setting::kLoadSystemSettings), - ConfigScopes::Scope::User)) { + if (m_Scopes.scopeContains(settingName(Setting::kLoadSystemSettings), ConfigScopes::Scope::User)) { auto loadFromSystemScope = m_Scopes - .getFromScope( - settingName(Setting::kLoadSystemSettings), - m_LoadFromSystemScope, ConfigScopes::Scope::User) + .getFromScope(settingName(Setting::kLoadSystemSettings), m_LoadFromSystemScope, ConfigScopes::Scope::User) .toBool(); if (loadFromSystemScope) { qDebug("user settings indicates system scope should be used"); @@ -265,15 +249,14 @@ void AppConfig::determineScope() { // ...failing that, check the system scope instead to see if an arbitrary // required setting is present. if it is, then we can assume that the system // scope should be used. - else if (m_Scopes.scopeContains( - settingName(Setting::kScreenName), - ConfigScopes::Scope::System)) { + else if (m_Scopes.scopeContains(settingName(Setting::kScreenName), ConfigScopes::Scope::System)) { qDebug("system settings scope contains screen name, using system scope"); setLoadFromSystemScope(true); } } -void AppConfig::recallElevateMode() { +void AppConfig::recallElevateMode() +{ using enum Setting; if (!m_Scopes.scopeContains(settingName(kElevateMode))) { @@ -284,35 +267,37 @@ void AppConfig::recallElevateMode() { QVariant elevateMode = getFromCurrentScope(kElevateMode); if (!elevateMode.isValid()) { qDebug("elevate mode not valid, loading legacy setting"); - elevateMode = getFromCurrentScope( - kElevateModeLegacy, QVariant(static_cast(kDefaultElevateMode))); + elevateMode = getFromCurrentScope(kElevateModeLegacy, QVariant(static_cast(kDefaultElevateMode))); } m_ElevateMode = static_cast(elevateMode.toInt()); } -QString AppConfig::settingName(Setting name) { +QString AppConfig::settingName(Setting name) +{ auto index = static_cast(name); return m_SettingsName[index]; } -template void AppConfig::setInCurrentScope(Setting name, T value) { +template void AppConfig::setInCurrentScope(Setting name, T value) +{ m_Scopes.setInScope(settingName(name), value); } -template void AppConfig::saveToAllScopes(Setting name, T value) { +template void AppConfig::saveToAllScopes(Setting name, T value) +{ m_Scopes.setInScope(settingName(name), value, ConfigScopes::Scope::User); m_Scopes.setInScope(settingName(name), value, ConfigScopes::Scope::System); } -QVariant AppConfig::getFromCurrentScope( - Setting name, const QVariant &defaultValue) const { +QVariant AppConfig::getFromCurrentScope(Setting name, const QVariant &defaultValue) const +{ return m_Scopes.getFromScope(settingName(name), defaultValue); } template -std::optional AppConfig::getFromCurrentScope( - Setting name, std::function toType) const { +std::optional AppConfig::getFromCurrentScope(Setting name, std::function toType) const +{ if (m_Scopes.scopeContains(settingName(name))) { return toType(m_Scopes.getFromScope(settingName(name))); } else { @@ -320,15 +305,15 @@ std::optional AppConfig::getFromCurrentScope( } } -template -void AppConfig::setInCurrentScope(Setting name, const std::optional &value) { +template void AppConfig::setInCurrentScope(Setting name, const std::optional &value) +{ if (value.has_value()) { m_Scopes.setInScope(settingName(name), value.value()); } } -QVariant -AppConfig::findInAllScopes(Setting name, const QVariant &defaultValue) const { +QVariant AppConfig::findInAllScopes(Setting name, const QVariant &defaultValue) const +{ using enum ConfigScopes::Scope; QVariant result(defaultValue); @@ -347,7 +332,8 @@ AppConfig::findInAllScopes(Setting name, const QVariant &defaultValue) const { return result; } -void AppConfig::loadScope(ConfigScopes::Scope scope) { +void AppConfig::loadScope(ConfigScopes::Scope scope) +{ using enum ConfigScopes::Scope; switch (scope) { @@ -374,15 +360,15 @@ void AppConfig::loadScope(ConfigScopes::Scope scope) { // only signal ready if there is at least one setting in the required scope. // this prevents the current settings from being set back to default. - if (m_Scopes.scopeContains( - settingName(Setting::kScreenName), m_Scopes.activeScope())) { + if (m_Scopes.scopeContains(settingName(Setting::kScreenName), m_Scopes.activeScope())) { m_Scopes.signalReady(); } else { qDebug("no screen name in scope, skipping"); } } -void AppConfig::setLoadFromSystemScope(bool value) { +void AppConfig::setLoadFromSystemScope(bool value) +{ using enum ConfigScopes::Scope; if (value) { @@ -395,20 +381,24 @@ void AppConfig::setLoadFromSystemScope(bool value) { m_LoadFromSystemScope = value; } -bool AppConfig::isActiveScopeWritable() const { +bool AppConfig::isActiveScopeWritable() const +{ return m_Scopes.isActiveScopeWritable(); } -bool AppConfig::isActiveScopeSystem() const { +bool AppConfig::isActiveScopeSystem() const +{ return m_Scopes.activeScope() == ConfigScopes::Scope::System; } -QString AppConfig::logDir() const { +QString AppConfig::logDir() const +{ // by default log to home dir return QDir::home().absolutePath() + "/"; } -void AppConfig::persistLogDir() const { +void AppConfig::persistLogDir() const +{ QDir dir = logDir(); // persist the log directory @@ -421,87 +411,183 @@ void AppConfig::persistLogDir() const { // Begin getters /////////////////////////////////////////////////////////////////////////////// -IConfigScopes &AppConfig::scopes() const { return m_Scopes; } +IConfigScopes &AppConfig::scopes() const +{ + return m_Scopes; +} -const QString &AppConfig::screenName() const { return m_ScreenName; } +const QString &AppConfig::screenName() const +{ + return m_ScreenName; +} -int AppConfig::port() const { return m_Port; } +int AppConfig::port() const +{ + return m_Port; +} -const QString &AppConfig::networkInterface() const { return m_Interface; } +const QString &AppConfig::networkInterface() const +{ + return m_Interface; +} -int AppConfig::logLevel() const { return m_LogLevel; } +int AppConfig::logLevel() const +{ + return m_LogLevel; +} -bool AppConfig::logToFile() const { return m_LogToFile; } +bool AppConfig::logToFile() const +{ + return m_LogToFile; +} -const QString &AppConfig::logFilename() const { return m_LogFilename; } +const QString &AppConfig::logFilename() const +{ + return m_LogFilename; +} -QString AppConfig::logLevelText() const { return kLogLevelNames[logLevel()]; } +QString AppConfig::logLevelText() const +{ + return kLogLevelNames[logLevel()]; +} -ProcessMode AppConfig::processMode() const { +ProcessMode AppConfig::processMode() const +{ return m_EnableService ? ProcessMode::kService : ProcessMode::kDesktop; } -bool AppConfig::wizardShouldRun() const { +bool AppConfig::wizardShouldRun() const +{ return m_WizardLastRun < kWizardVersion; } -bool AppConfig::startedBefore() const { return m_StartedBefore; } +bool AppConfig::startedBefore() const +{ + return m_StartedBefore; +} -QString AppConfig::lastVersion() const { return m_LastVersion; } +QString AppConfig::lastVersion() const +{ + return m_LastVersion; +} -QString AppConfig::coreServerName() const { return m_CoreServerName; } +QString AppConfig::coreServerName() const +{ + return m_CoreServerName; +} -QString AppConfig::coreClientName() const { return m_CoreClientName; } +QString AppConfig::coreClientName() const +{ + return m_CoreClientName; +} -ElevateMode AppConfig::elevateMode() const { return m_ElevateMode; } +ElevateMode AppConfig::elevateMode() const +{ + return m_ElevateMode; +} -bool AppConfig::tlsEnabled() const { return m_TlsEnabled; } +bool AppConfig::tlsEnabled() const +{ + return m_TlsEnabled; +} -bool AppConfig::autoHide() const { return m_AutoHide; } +bool AppConfig::autoHide() const +{ + return m_AutoHide; +} -bool AppConfig::invertScrollDirection() const { +bool AppConfig::invertScrollDirection() const +{ return m_InvertScrollDirection; } -bool AppConfig::languageSync() const { return m_LanguageSync; } +bool AppConfig::languageSync() const +{ + return m_LanguageSync; +} -bool AppConfig::preventSleep() const { return m_PreventSleep; } +bool AppConfig::preventSleep() const +{ + return m_PreventSleep; +} -bool AppConfig::invertConnection() const { return m_InvertConnection; } +bool AppConfig::invertConnection() const +{ + return m_InvertConnection; +} -QString AppConfig::tlsCertPath() const { return m_TlsCertPath; } +QString AppConfig::tlsCertPath() const +{ + return m_TlsCertPath; +} -int AppConfig::tlsKeyLength() const { return m_TlsKeyLength; } +int AppConfig::tlsKeyLength() const +{ + return m_TlsKeyLength; +} -bool AppConfig::enableService() const { return m_EnableService; } +bool AppConfig::enableService() const +{ + return m_EnableService; +} -bool AppConfig::closeToTray() const { return m_CloseToTray; } +bool AppConfig::closeToTray() const +{ + return m_CloseToTray; +} -bool AppConfig::serverGroupChecked() const { return m_ServerGroupChecked; } +bool AppConfig::serverGroupChecked() const +{ + return m_ServerGroupChecked; +} -bool AppConfig::useExternalConfig() const { return m_UseExternalConfig; } +bool AppConfig::useExternalConfig() const +{ + return m_UseExternalConfig; +} -const QString &AppConfig::configFile() const { return m_ConfigFile; } +const QString &AppConfig::configFile() const +{ + return m_ConfigFile; +} -bool AppConfig::useInternalConfig() const { return m_UseInternalConfig; } +bool AppConfig::useInternalConfig() const +{ + return m_UseInternalConfig; +} -bool AppConfig::clientGroupChecked() const { return m_ClientGroupChecked; } +bool AppConfig::clientGroupChecked() const +{ + return m_ClientGroupChecked; +} -const QString &AppConfig::serverHostname() const { return m_ServerHostname; } +const QString &AppConfig::serverHostname() const +{ + return m_ServerHostname; +} -std::optional AppConfig::mainWindowSize() const { +std::optional AppConfig::mainWindowSize() const +{ return m_MainWindowSize; } -std::optional AppConfig::mainWindowPosition() const { +std::optional AppConfig::mainWindowPosition() const +{ return m_MainWindowPosition; } -bool AppConfig::showDevThanks() const { return m_ShowDevThanks; } +bool AppConfig::showDevThanks() const +{ + return m_ShowDevThanks; +} -bool AppConfig::showCloseReminder() const { return m_ShowCloseReminder; } +bool AppConfig::showCloseReminder() const +{ + return m_ShowCloseReminder; +} -std::optional AppConfig::enableUpdateCheck() const { +std::optional AppConfig::enableUpdateCheck() const +{ return m_EnableUpdateCheck; } @@ -513,7 +599,8 @@ std::optional AppConfig::enableUpdateCheck() const { // Begin setters /////////////////////////////////////////////////////////////////////////////// -void AppConfig::setTlsEnabled(bool value) { +void AppConfig::setTlsEnabled(bool value) +{ // we purposefully do not set the 'tls changed' flag when enabling/disabling // tls, since that would cause the certificate to regenerate, which could get // pretty annoying. @@ -521,7 +608,8 @@ void AppConfig::setTlsEnabled(bool value) { m_TlsEnabled = value; } -void AppConfig::setTlsCertPath(const QString &value) { +void AppConfig::setTlsCertPath(const QString &value) +{ if (m_TlsCertPath != value) { // deliberately only set the changed flag if there was a change. // it's important not to set this flag to false here. @@ -530,7 +618,8 @@ void AppConfig::setTlsCertPath(const QString &value) { m_TlsCertPath = value; } -void AppConfig::setTlsKeyLength(int value) { +void AppConfig::setTlsKeyLength(int value) +{ if (m_TlsKeyLength != value) { // deliberately only set the changed flag if there was a change. // it's important not to set this flag to false here. @@ -539,88 +628,144 @@ void AppConfig::setTlsKeyLength(int value) { m_TlsKeyLength = value; } -void AppConfig::setServerGroupChecked(bool newValue) { +void AppConfig::setServerGroupChecked(bool newValue) +{ m_ServerGroupChecked = newValue; } -void AppConfig::setUseExternalConfig(bool newValue) { +void AppConfig::setUseExternalConfig(bool newValue) +{ m_UseExternalConfig = newValue; } -void AppConfig::setConfigFile(const QString &newValue) { +void AppConfig::setConfigFile(const QString &newValue) +{ m_ConfigFile = newValue; } -void AppConfig::setUseInternalConfig(bool newValue) { +void AppConfig::setUseInternalConfig(bool newValue) +{ m_UseInternalConfig = newValue; } -void AppConfig::setClientGroupChecked(bool newValue) { +void AppConfig::setClientGroupChecked(bool newValue) +{ m_ClientGroupChecked = newValue; } -void AppConfig::setServerHostname(const QString &newValue) { +void AppConfig::setServerHostname(const QString &newValue) +{ m_ServerHostname = newValue; } -void AppConfig::setLastVersion(const QString &version) { +void AppConfig::setLastVersion(const QString &version) +{ m_LastVersion = version; } -void AppConfig::setScreenName(const QString &s) { +void AppConfig::setScreenName(const QString &s) +{ m_ScreenName = s; emit screenNameChanged(); } -void AppConfig::setPort(int i) { m_Port = i; } +void AppConfig::setPort(int i) +{ + m_Port = i; +} -void AppConfig::setNetworkInterface(const QString &s) { m_Interface = s; } +void AppConfig::setNetworkInterface(const QString &s) +{ + m_Interface = s; +} -void AppConfig::setLogLevel(int i) { m_LogLevel = i; } +void AppConfig::setLogLevel(int i) +{ + m_LogLevel = i; +} -void AppConfig::setLogToFile(bool b) { m_LogToFile = b; } +void AppConfig::setLogToFile(bool b) +{ + m_LogToFile = b; +} -void AppConfig::setLogFilename(const QString &s) { m_LogFilename = s; } +void AppConfig::setLogFilename(const QString &s) +{ + m_LogFilename = s; +} -void AppConfig::setWizardHasRun() { m_WizardLastRun = kWizardVersion; } +void AppConfig::setWizardHasRun() +{ + m_WizardLastRun = kWizardVersion; +} -void AppConfig::setStartedBefore(bool b) { m_StartedBefore = b; } +void AppConfig::setStartedBefore(bool b) +{ + m_StartedBefore = b; +} -void AppConfig::setElevateMode(ElevateMode em) { m_ElevateMode = em; } +void AppConfig::setElevateMode(ElevateMode em) +{ + m_ElevateMode = em; +} -void AppConfig::setAutoHide(bool b) { m_AutoHide = b; } +void AppConfig::setAutoHide(bool b) +{ + m_AutoHide = b; +} -void AppConfig::setInvertScrollDirection(bool newValue) { +void AppConfig::setInvertScrollDirection(bool newValue) +{ m_InvertScrollDirection = newValue; } -void AppConfig::setLanguageSync(bool newValue) { m_LanguageSync = newValue; } +void AppConfig::setLanguageSync(bool newValue) +{ + m_LanguageSync = newValue; +} -void AppConfig::setPreventSleep(bool newValue) { m_PreventSleep = newValue; } +void AppConfig::setPreventSleep(bool newValue) +{ + m_PreventSleep = newValue; +} -void AppConfig::setEnableService(bool enabled) { m_EnableService = enabled; } +void AppConfig::setEnableService(bool enabled) +{ + m_EnableService = enabled; +} -void AppConfig::setCloseToTray(bool minimize) { m_CloseToTray = minimize; } +void AppConfig::setCloseToTray(bool minimize) +{ + m_CloseToTray = minimize; +} -void AppConfig::setInvertConnection(bool value) { +void AppConfig::setInvertConnection(bool value) +{ m_InvertConnection = value; emit invertConnectionChanged(); } -void AppConfig::setMainWindowSize(const QSize &size) { +void AppConfig::setMainWindowSize(const QSize &size) +{ m_MainWindowSize = size; } -void AppConfig::setMainWindowPosition(const QPoint &position) { +void AppConfig::setMainWindowPosition(const QPoint &position) +{ m_MainWindowPosition = position; } -void AppConfig::setShowDevThanks(bool value) { m_ShowDevThanks = value; } +void AppConfig::setShowDevThanks(bool value) +{ + m_ShowDevThanks = value; +} -void AppConfig::setShowCloseReminder(bool value) { +void AppConfig::setShowCloseReminder(bool value) +{ m_ShowCloseReminder = value; } -void AppConfig::setEnableUpdateCheck(bool value) { +void AppConfig::setEnableUpdateCheck(bool value) +{ m_EnableUpdateCheck = value; } diff --git a/src/lib/gui/config/AppConfig.h b/src/lib/gui/config/AppConfig.h index 422121d51..3fe4bb8d9 100644 --- a/src/lib/gui/config/AppConfig.h +++ b/src/lib/gui/config/AppConfig.h @@ -60,14 +60,16 @@ const ProcessMode kDefaultProcessMode = ProcessMode::kDesktop; * instance is widely accessible, but that has previously led to this class * becoming a god object. */ -class AppConfig : public QObject, public deskflow::gui::IAppConfig { +class AppConfig : public QObject, public deskflow::gui::IAppConfig +{ using ProcessMode = deskflow::gui::ProcessMode; using IConfigScopes = deskflow::gui::IConfigScopes; Q_OBJECT private: - enum class Setting { + enum class Setting + { kScreenName = 0, kPort = 1, kInterface = 2, @@ -115,17 +117,20 @@ private: }; public: - struct Deps { + struct Deps + { virtual ~Deps() = default; - virtual QString defaultTlsCertPath() const { + virtual QString defaultTlsCertPath() const + { return deskflow::gui::paths::defaultTlsCertPath(); } - virtual QString hostname() const { return QHostInfo::localHostName(); } + virtual QString hostname() const + { + return QHostInfo::localHostName(); + } }; - explicit AppConfig( - IConfigScopes &scopes, - std::shared_ptr deps = std::make_shared()); + explicit AppConfig(IConfigScopes &scopes, std::shared_ptr deps = std::make_shared()); void determineScope(); @@ -248,20 +253,17 @@ private: * @param toType A function to convert the QVariant to the desired type. */ template - std::optional getFromCurrentScope( - Setting name, std::function toType) const; + std::optional getFromCurrentScope(Setting name, std::function toType) const; /** * @brief Sets a setting if the value is not `std::nullopt`. */ - template - void setInCurrentScope(Setting name, const std::optional &value); + template void setInCurrentScope(Setting name, const std::optional &value); /// @brief Sets the value of a setting /// @param [in] name The Setting to be saved /// @param [in] value The Value to be saved - template - void setInCurrentScope(AppConfig::Setting name, T value); + template void setInCurrentScope(AppConfig::Setting name, T value); /// @brief Sets the value of a common setting /// which should have the same value for all scopes @@ -269,15 +271,13 @@ private: /// @param [in] value The Value to be saved template void saveToAllScopes(AppConfig::Setting name, T value); - QVariant getFromCurrentScope( - AppConfig::Setting name, const QVariant &defaultValue = QVariant()) const; + QVariant getFromCurrentScope(AppConfig::Setting name, const QVariant &defaultValue = QVariant()) const; /** * @brief Finds a value by searching each scope starting with the current * scope. */ - QVariant findInAllScopes( - AppConfig::Setting name, const QVariant &defaultValue = QVariant()) const; + QVariant findInAllScopes(AppConfig::Setting name, const QVariant &defaultValue = QVariant()) const; /// @brief This method loads config from specified scope /// @param [in] scope which should be loaded. @@ -319,8 +319,7 @@ private: bool m_UseInternalConfig = false; bool m_ClientGroupChecked = false; QString m_ServerHostname = ""; - bool m_EnableService = - deskflow::gui::kDefaultProcessMode == ProcessMode::kService; + bool m_EnableService = deskflow::gui::kDefaultProcessMode == ProcessMode::kService; bool m_CloseToTray = true; int m_TlsKeyLength = deskflow::gui::kDefaultTlsKeyLength; std::optional m_MainWindowSize; diff --git a/src/lib/gui/config/ConfigScopes.cpp b/src/lib/gui/config/ConfigScopes.cpp index 51431698b..aa685e231 100644 --- a/src/lib/gui/config/ConfigScopes.cpp +++ b/src/lib/gui/config/ConfigScopes.cpp @@ -34,11 +34,13 @@ using namespace proxy; // ConfigScopes::Deps // -std::shared_ptr ConfigScopes::Deps::makeUserSettings() { +std::shared_ptr ConfigScopes::Deps::makeUserSettings() +{ return std::make_shared(); } -std::shared_ptr ConfigScopes::Deps::makeSystemSettings() { +std::shared_ptr ConfigScopes::Deps::makeSystemSettings() +{ return std::make_shared(); } @@ -48,20 +50,26 @@ std::shared_ptr ConfigScopes::Deps::makeSystemSettings() { ConfigScopes::ConfigScopes(std::shared_ptr deps) : m_pUserSettingsProxy(deps->makeUserSettings()), - m_pSystemSettingsProxy(deps->makeSystemSettings()) { + m_pSystemSettingsProxy(deps->makeSystemSettings()) +{ m_pUserSettingsProxy->loadUser(); m_pSystemSettingsProxy->loadSystem(); } -void ConfigScopes::clear() const { +void ConfigScopes::clear() const +{ m_pUserSettingsProxy->clear(); m_pSystemSettingsProxy->clear(); } -void ConfigScopes::signalReady() { emit ready(); } +void ConfigScopes::signalReady() +{ + emit ready(); +} -void ConfigScopes::save(bool emitSaving) { +void ConfigScopes::save(bool emitSaving) +{ if (emitSaving) { qDebug("emitting config saving signal"); emit saving(); @@ -72,17 +80,23 @@ void ConfigScopes::save(bool emitSaving) { m_pSystemSettingsProxy->sync(); } -bool ConfigScopes::isActiveScopeWritable() const { +bool ConfigScopes::isActiveScopeWritable() const +{ return activeSettings().isWritable(); } -void ConfigScopes::setActiveScope(ConfigScopes::Scope scope) { +void ConfigScopes::setActiveScope(ConfigScopes::Scope scope) +{ m_currentScope = scope; } -ConfigScopes::Scope ConfigScopes::activeScope() const { return m_currentScope; } +ConfigScopes::Scope ConfigScopes::activeScope() const +{ + return m_currentScope; +} -bool ConfigScopes::scopeContains(const QString &name, Scope scope) const { +bool ConfigScopes::scopeContains(const QString &name, Scope scope) const +{ switch (scope) { case Scope::User: return m_pUserSettingsProxy->contains(name); @@ -93,7 +107,8 @@ bool ConfigScopes::scopeContains(const QString &name, Scope scope) const { } } -QSettingsProxy &ConfigScopes::activeSettings() { +QSettingsProxy &ConfigScopes::activeSettings() +{ if (m_currentScope == Scope::User) { return *m_pUserSettingsProxy; } else { @@ -101,7 +116,8 @@ QSettingsProxy &ConfigScopes::activeSettings() { } } -const QSettingsProxy &ConfigScopes::activeSettings() const { +const QSettingsProxy &ConfigScopes::activeSettings() const +{ if (m_currentScope == Scope::User) { return *m_pUserSettingsProxy; } else { @@ -109,12 +125,13 @@ const QSettingsProxy &ConfigScopes::activeSettings() const { } } -QString ConfigScopes::activeFilePath() const { +QString ConfigScopes::activeFilePath() const +{ return activeSettings().fileName(); } -QVariant ConfigScopes::getFromScope( - const QString &name, const QVariant &defaultValue, Scope scope) const { +QVariant ConfigScopes::getFromScope(const QString &name, const QVariant &defaultValue, Scope scope) const +{ switch (scope) { case Scope::User: return m_pUserSettingsProxy->value(name, defaultValue); @@ -125,8 +142,8 @@ QVariant ConfigScopes::getFromScope( } } -void ConfigScopes::setInScope( - const QString &name, const QVariant &value, Scope scope) { +void ConfigScopes::setInScope(const QString &name, const QVariant &value, Scope scope) +{ switch (scope) { case Scope::User: m_pUserSettingsProxy->setValue(name, value); diff --git a/src/lib/gui/config/ConfigScopes.h b/src/lib/gui/config/ConfigScopes.h index ff9d519b4..86ae37943 100644 --- a/src/lib/gui/config/ConfigScopes.h +++ b/src/lib/gui/config/ConfigScopes.h @@ -27,13 +27,15 @@ namespace deskflow::gui { /// @brief Encapsulates Qt config for both user and global scopes. -class ConfigScopes : public QObject, public IConfigScopes { +class ConfigScopes : public QObject, public IConfigScopes +{ using QSettingsProxy = deskflow::gui::proxy::QSettingsProxy; Q_OBJECT public: - struct Deps { + struct Deps + { virtual ~Deps() = default; virtual std::shared_ptr makeUserSettings(); virtual std::shared_ptr makeSystemSettings(); @@ -46,15 +48,11 @@ public: void signalReady() override; void save(bool emitSaving = true) override; - bool scopeContains( - const QString &name, Scope scope = Scope::Current) const override; + bool scopeContains(const QString &name, Scope scope = Scope::Current) const override; bool isActiveScopeWritable() const override; - void setInScope( - const QString &name, const QVariant &value, - Scope scope = Scope::Current) override; - QVariant getFromScope( - const QString &name, const QVariant &defaultValue = QVariant(), - Scope scope = Scope::Current) const override; + void setInScope(const QString &name, const QVariant &value, Scope scope = Scope::Current) override; + QVariant getFromScope(const QString &name, const QVariant &defaultValue = QVariant(), Scope scope = Scope::Current) + const override; void setActiveScope(Scope scope = Scope::User) override; Scope activeScope() const override; QSettingsProxy &activeSettings() override; diff --git a/src/lib/gui/config/ElevateMode.h b/src/lib/gui/config/ElevateMode.h index 3ec6a34b6..169d139cd 100644 --- a/src/lib/gui/config/ElevateMode.h +++ b/src/lib/gui/config/ElevateMode.h @@ -35,4 +35,9 @@ * kAlways | false | true | * kNever | false | false | */ -enum class ElevateMode { kAutomatic = 0, kAlways = 1, kNever = 2 }; +enum class ElevateMode +{ + kAutomatic = 0, + kAlways = 1, + kNever = 2 +}; diff --git a/src/lib/gui/config/IAppConfig.h b/src/lib/gui/config/IAppConfig.h index 107e90fa3..69407b884 100644 --- a/src/lib/gui/config/IAppConfig.h +++ b/src/lib/gui/config/IAppConfig.h @@ -25,9 +25,14 @@ namespace deskflow::gui { -enum class ProcessMode { kService, kDesktop }; +enum class ProcessMode +{ + kService, + kDesktop +}; -class IAppConfig { +class IAppConfig +{ using IConfigScopes = deskflow::gui::IConfigScopes; public: diff --git a/src/lib/gui/config/IConfigScopes.h b/src/lib/gui/config/IConfigScopes.h index 3243810b4..6756aadbe 100644 --- a/src/lib/gui/config/IConfigScopes.h +++ b/src/lib/gui/config/IConfigScopes.h @@ -25,11 +25,17 @@ namespace deskflow::gui { -class IConfigScopes { +class IConfigScopes +{ using QSettingsProxy = deskflow::gui::proxy::QSettingsProxy; public: - enum class Scope { Current, System, User }; + enum class Scope + { + Current, + System, + User + }; virtual ~IConfigScopes() = default; @@ -57,22 +63,18 @@ public: /** * @brief Check a scope for a config value (default is current scope). */ - virtual bool - scopeContains(const QString &name, Scope scope = Scope::Current) const = 0; + virtual bool scopeContains(const QString &name, Scope scope = Scope::Current) const = 0; /** * @brief Load a config value from a scope (default is current scope). */ - virtual QVariant getFromScope( - const QString &name, const QVariant &defaultValue = QVariant(), - Scope scope = Scope::Current) const = 0; + virtual QVariant + getFromScope(const QString &name, const QVariant &defaultValue = QVariant(), Scope scope = Scope::Current) const = 0; /** * @brief Set a config value in a scope (default is current scope). */ - virtual void setInScope( - const QString &name, const QVariant &value, - Scope scope = Scope::Current) = 0; + virtual void setInScope(const QString &name, const QVariant &value, Scope scope = Scope::Current) = 0; }; } // namespace deskflow::gui diff --git a/src/lib/gui/config/IServerConfig.h b/src/lib/gui/config/IServerConfig.h index 12c6ff605..499a744b1 100644 --- a/src/lib/gui/config/IServerConfig.h +++ b/src/lib/gui/config/IServerConfig.h @@ -24,7 +24,8 @@ namespace deskflow::gui { -class IServerConfig { +class IServerConfig +{ public: virtual ~IServerConfig() = default; virtual bool isFull() const = 0; diff --git a/src/lib/gui/config/Screen.cpp b/src/lib/gui/config/Screen.cpp index b6290b067..f19899064 100644 --- a/src/lib/gui/config/Screen.cpp +++ b/src/lib/gui/config/Screen.cpp @@ -27,14 +27,19 @@ using enum ScreenConfig::Modifier; using enum ScreenConfig::SwitchCorner; using enum ScreenConfig::Fix; -Screen::Screen() { init(); } +Screen::Screen() +{ + init(); +} -Screen::Screen(const QString &name) { +Screen::Screen(const QString &name) +{ init(); setName(name); } -void Screen::init() { +void Screen::init() +{ name().clear(); aliases().clear(); modifiers().clear(); @@ -55,7 +60,8 @@ void Screen::init() { fixes() << false; } -void Screen::loadSettings(QSettingsProxy &settings) { +void Screen::loadSettings(QSettingsProxy &settings) +{ setName(settings.value("name").toString()); if (name().isEmpty()) @@ -64,16 +70,13 @@ void Screen::loadSettings(QSettingsProxy &settings) { setSwitchCornerSize(settings.value("switchCornerSize").toInt()); readSettings(settings, aliases(), "alias", QString("")); - readSettings( - settings, modifiers(), "modifier", static_cast(DefaultMod), - static_cast(NumModifiers)); - readSettings( - settings, switchCorners(), "switchCorner", 0, - static_cast(NumSwitchCorners)); + readSettings(settings, modifiers(), "modifier", static_cast(DefaultMod), static_cast(NumModifiers)); + readSettings(settings, switchCorners(), "switchCorner", 0, static_cast(NumSwitchCorners)); readSettings(settings, fixes(), "fix", 0, static_cast(NumFixes)); } -void Screen::saveSettings(QSettingsProxy &settings) const { +void Screen::saveSettings(QSettingsProxy &settings) const +{ settings.setValue("name", name()); if (name().isEmpty()) @@ -87,17 +90,16 @@ void Screen::saveSettings(QSettingsProxy &settings) const { writeSettings(settings, fixes(), "fix"); } -QTextStream &Screen::writeScreensSection(QTextStream &outStream) const { +QTextStream &Screen::writeScreensSection(QTextStream &outStream) const +{ outStream << "\t" << name() << ":" << Qt::endl; for (int i = 0; i < modifiers().size(); i++) if (modifier(i) != i) - outStream << "\t\t" << modifierName(i) << " = " - << modifierName(modifier(i)) << Qt::endl; + outStream << "\t\t" << modifierName(i) << " = " << modifierName(modifier(i)) << Qt::endl; for (int i = 0; i < fixes().size(); i++) - outStream << "\t\t" << fixName(i) << " = " - << (fixes()[i] ? "true" : "false") << Qt::endl; + outStream << "\t\t" << fixName(i) << " = " << (fixes()[i] ? "true" : "false") << Qt::endl; outStream << "\t\t" << "switchCorners = none "; @@ -112,7 +114,8 @@ QTextStream &Screen::writeScreensSection(QTextStream &outStream) const { return outStream; } -QTextStream &Screen::writeAliasesSection(QTextStream &outStream) const { +QTextStream &Screen::writeAliasesSection(QTextStream &outStream) const +{ if (!aliases().isEmpty()) { outStream << "\t" << name() << ":" << Qt::endl; @@ -123,11 +126,9 @@ QTextStream &Screen::writeAliasesSection(QTextStream &outStream) const { return outStream; } -bool Screen::operator==(const Screen &screen) const { - return m_Name == screen.m_Name && m_Aliases == screen.m_Aliases && - m_Modifiers == screen.m_Modifiers && - m_SwitchCorners == screen.m_SwitchCorners && - m_SwitchCornerSize == screen.m_SwitchCornerSize && - m_Fixes == screen.m_Fixes && m_Swapped == screen.m_Swapped && - m_isServer == screen.m_isServer; +bool Screen::operator==(const Screen &screen) const +{ + return m_Name == screen.m_Name && m_Aliases == screen.m_Aliases && m_Modifiers == screen.m_Modifiers && + m_SwitchCorners == screen.m_SwitchCorners && m_SwitchCornerSize == screen.m_SwitchCornerSize && + m_Fixes == screen.m_Fixes && m_Swapped == screen.m_Swapped && m_isServer == screen.m_isServer; } diff --git a/src/lib/gui/config/Screen.h b/src/lib/gui/config/Screen.h index 241fa1fd7..f5f7cf4a9 100644 --- a/src/lib/gui/config/Screen.h +++ b/src/lib/gui/config/Screen.h @@ -31,74 +31,147 @@ class QSettings; class QTextStream; class ScreenSettingsDialog; -class Screen : public ScreenConfig { +class Screen : public ScreenConfig +{ using QSettingsProxy = deskflow::gui::proxy::QSettingsProxy; friend class ScreenSettingsDialog; friend class ScreenSetupModel; friend class ScreenSetupView; - friend QDataStream &operator<<(QDataStream &outStream, const Screen &screen) { - return outStream << screen.name() << screen.switchCornerSize() - << screen.aliases() << screen.modifiers() - << screen.switchCorners() << screen.fixes() - << screen.isServer(); + friend QDataStream &operator<<(QDataStream &outStream, const Screen &screen) + { + return outStream << screen.name() << screen.switchCornerSize() << screen.aliases() << screen.modifiers() + << screen.switchCorners() << screen.fixes() << screen.isServer(); } - friend QDataStream &operator>>(QDataStream &inStream, Screen &screen) { - return inStream >> screen.m_Name >> screen.m_SwitchCornerSize >> - screen.m_Aliases >> screen.m_Modifiers >> screen.m_SwitchCorners >> - screen.m_Fixes >> screen.m_isServer; + friend QDataStream &operator>>(QDataStream &inStream, Screen &screen) + { + return inStream >> screen.m_Name >> screen.m_SwitchCornerSize >> screen.m_Aliases >> screen.m_Modifiers >> + screen.m_SwitchCorners >> screen.m_Fixes >> screen.m_isServer; } public: explicit Screen(); explicit Screen(const QString &name); - const QPixmap &pixmap() const { return m_Pixmap; } - const QString &name() const { return m_Name; } - const QStringList &aliases() const { return m_Aliases; } - - bool isNull() const { return m_Name.isEmpty(); } - int modifier(int m) const { - return m_Modifiers[m] == - static_cast(ScreenConfig::Modifier::DefaultMod) - ? m - : m_Modifiers[m]; + const QPixmap &pixmap() const + { + return m_Pixmap; + } + const QString &name() const + { + return m_Name; + } + const QStringList &aliases() const + { + return m_Aliases; + } + + bool isNull() const + { + return m_Name.isEmpty(); + } + int modifier(int m) const + { + return m_Modifiers[m] == static_cast(ScreenConfig::Modifier::DefaultMod) ? m : m_Modifiers[m]; + } + const QList &modifiers() const + { + return m_Modifiers; + } + bool switchCorner(int c) const + { + return m_SwitchCorners[c]; + } + const QList &switchCorners() const + { + return m_SwitchCorners; + } + int switchCornerSize() const + { + return m_SwitchCornerSize; + } + bool fix(Fix f) const + { + return m_Fixes[static_cast(f)]; + } + const QList &fixes() const + { + return m_Fixes; } - const QList &modifiers() const { return m_Modifiers; } - bool switchCorner(int c) const { return m_SwitchCorners[c]; } - const QList &switchCorners() const { return m_SwitchCorners; } - int switchCornerSize() const { return m_SwitchCornerSize; } - bool fix(Fix f) const { return m_Fixes[static_cast(f)]; } - const QList &fixes() const { return m_Fixes; } void loadSettings(QSettingsProxy &settings); void saveSettings(QSettingsProxy &settings) const; QTextStream &writeScreensSection(QTextStream &outStream) const; QTextStream &writeAliasesSection(QTextStream &outStream) const; - bool swapped() const { return m_Swapped; } - QString &name() { return m_Name; } - void setName(const QString &name) { m_Name = name; } - bool isServer() const { return m_isServer; } - void markAsServer() { m_isServer = true; } + bool swapped() const + { + return m_Swapped; + } + QString &name() + { + return m_Name; + } + void setName(const QString &name) + { + m_Name = name; + } + bool isServer() const + { + return m_isServer; + } + void markAsServer() + { + m_isServer = true; + } bool operator==(const Screen &screen) const; protected: void init(); - QStringList &aliases() { return m_Aliases; } - void setModifier(int m, int n) { m_Modifiers[m] = n; } - QList &modifiers() { return m_Modifiers; } - void addAlias(const QString &alias) { m_Aliases.append(alias); } - void setSwitchCorner(int c, bool on) { m_SwitchCorners[c] = on; } - QList &switchCorners() { return m_SwitchCorners; } - void setSwitchCornerSize(int val) { m_SwitchCornerSize = val; } - void setFix(int f, bool on) { m_Fixes[f] = on; } - QList &fixes() { return m_Fixes; } - void setSwapped(bool on) { m_Swapped = on; } + QStringList &aliases() + { + return m_Aliases; + } + void setModifier(int m, int n) + { + m_Modifiers[m] = n; + } + QList &modifiers() + { + return m_Modifiers; + } + void addAlias(const QString &alias) + { + m_Aliases.append(alias); + } + void setSwitchCorner(int c, bool on) + { + m_SwitchCorners[c] = on; + } + QList &switchCorners() + { + return m_SwitchCorners; + } + void setSwitchCornerSize(int val) + { + m_SwitchCornerSize = val; + } + void setFix(int f, bool on) + { + m_Fixes[f] = on; + } + QList &fixes() + { + return m_Fixes; + } + void setSwapped(bool on) + { + m_Swapped = on; + } private: QPixmap m_Pixmap = QPixmap(":res/icons/64x64/video-display.png"); diff --git a/src/lib/gui/config/ScreenConfig.cpp b/src/lib/gui/config/ScreenConfig.cpp index 1b97785ce..979701f59 100644 --- a/src/lib/gui/config/ScreenConfig.cpp +++ b/src/lib/gui/config/ScreenConfig.cpp @@ -18,12 +18,10 @@ #include "ScreenConfig.h" -const char *ScreenConfig::m_ModifierNames[] = {"shift", "ctrl", "alt", - "meta", "super", "none"}; +const char *ScreenConfig::m_ModifierNames[] = {"shift", "ctrl", "alt", "meta", "super", "none"}; const char *ScreenConfig::m_FixNames[] = { - "halfDuplexCapsLock", "halfDuplexNumLock", "halfDuplexScrollLock", - "xtestIsXineramaUnaware"}; + "halfDuplexCapsLock", "halfDuplexNumLock", "halfDuplexScrollLock", "xtestIsXineramaUnaware" +}; -const char *ScreenConfig::m_SwitchCornerNames[] = { - "top-left", "top-right", "bottom-left", "bottom-right"}; +const char *ScreenConfig::m_SwitchCornerNames[] = {"top-left", "top-right", "bottom-left", "bottom-right"}; diff --git a/src/lib/gui/config/ScreenConfig.h b/src/lib/gui/config/ScreenConfig.h index 1214778f1..df6221f30 100644 --- a/src/lib/gui/config/ScreenConfig.h +++ b/src/lib/gui/config/ScreenConfig.h @@ -24,11 +24,13 @@ #include "gui/proxy/QSettingsProxy.h" /// @brief Screen configuration base class -class ScreenConfig { +class ScreenConfig +{ using QSettingsProxy = deskflow::gui::proxy::QSettingsProxy; public: - enum class Modifier { + enum class Modifier + { DefaultMod = -1, Shift, Ctrl, @@ -38,23 +40,30 @@ public: None, NumModifiers }; - enum class SwitchCorner { + enum class SwitchCorner + { TopLeft, TopRight, BottomLeft, BottomRight, NumSwitchCorners }; - enum class Fix { CapsLock, NumLock, ScrollLock, XTest, NumFixes }; + enum class Fix + { + CapsLock, + NumLock, + ScrollLock, + XTest, + NumFixes + }; protected: explicit ScreenConfig() = default; ~ScreenConfig() = default; template - void readSettings( - QSettingsProxy &settings, T1 &array, const QString &arrayName, - const T2 &defaultValue) { + void readSettings(QSettingsProxy &settings, T1 &array, const QString &arrayName, const T2 &defaultValue) + { int entries = settings.beginReadArray(arrayName + "Array"); array.clear(); for (int i = 0; i < entries; i++) { @@ -66,9 +75,8 @@ protected: } template - void readSettings( - QSettingsProxy &settings, T1 &array, const QString &arrayName, - const T2 &defaultValue, int entries) { + void readSettings(QSettingsProxy &settings, T1 &array, const QString &arrayName, const T2 &defaultValue, int entries) + { Q_ASSERT(array.size() >= entries); settings.beginReadArray(arrayName + "Array"); for (int i = 0; i < entries; i++) { @@ -79,10 +87,8 @@ protected: settings.endArray(); } - template - void writeSettings( - QSettingsProxy &settings, const T &array, - const QString &arrayName) const { + template void writeSettings(QSettingsProxy &settings, const T &array, const QString &arrayName) const + { settings.beginWriteArray(arrayName + "Array"); for (int i = 0; i < array.size(); i++) { settings.setArrayIndex(i); @@ -92,9 +98,16 @@ protected: } public: - static const char *modifierName(int idx) { return m_ModifierNames[idx]; } - static const char *fixName(int idx) { return m_FixNames[idx]; } - static const char *switchCornerName(int idx) { + static const char *modifierName(int idx) + { + return m_ModifierNames[idx]; + } + static const char *fixName(int idx) + { + return m_FixNames[idx]; + } + static const char *switchCornerName(int idx) + { return m_SwitchCornerNames[idx]; } diff --git a/src/lib/gui/config/ScreenList.cpp b/src/lib/gui/config/ScreenList.cpp index b5d489238..4fb8df848 100644 --- a/src/lib/gui/config/ScreenList.cpp +++ b/src/lib/gui/config/ScreenList.cpp @@ -28,7 +28,8 @@ namespace { * @param size of the grid * @return indexes for server neighbors */ -std::array getNeighborsIndexes(int serverIndex, int width, int size) { +std::array getNeighborsIndexes(int serverIndex, int width, int size) +{ const int UNSET = -1; const int LEFT = 0; const int RIGHT = 1; @@ -42,25 +43,14 @@ std::array getNeighborsIndexes(int serverIndex, int width, int size) { std::array indexes = {UNSET}; if (serverIndex >= 0 && serverIndex < size) { - indexes[LEFT] = - (serverIndex - 1) % width != width - 1 ? (serverIndex - 1) : UNSET; + indexes[LEFT] = (serverIndex - 1) % width != width - 1 ? (serverIndex - 1) : UNSET; indexes[RIGHT] = (serverIndex + 1) % width != 0 ? (serverIndex + 1) : UNSET; indexes[TOP] = (serverIndex - width) >= 0 ? (serverIndex - width) : UNSET; - indexes[BOTTOM] = - (serverIndex + width) < size ? (serverIndex + width) : UNSET; - indexes[TOP_LEFT] = (indexes[TOP] != UNSET && indexes[LEFT] != UNSET) - ? indexes[TOP] - 1 - : UNSET; - indexes[TOP_RIGHT] = (indexes[TOP] != UNSET && indexes[RIGHT] != UNSET) - ? indexes[TOP] + 1 - : UNSET; - indexes[BOTTOM_RIGHT] = - (indexes[BOTTOM] != UNSET && indexes[RIGHT] != UNSET) - ? indexes[BOTTOM] + 1 - : UNSET; - indexes[BOTTOM_LEFT] = (indexes[BOTTOM] != UNSET && indexes[LEFT] != UNSET) - ? indexes[BOTTOM] - 1 - : UNSET; + indexes[BOTTOM] = (serverIndex + width) < size ? (serverIndex + width) : UNSET; + indexes[TOP_LEFT] = (indexes[TOP] != UNSET && indexes[LEFT] != UNSET) ? indexes[TOP] - 1 : UNSET; + indexes[TOP_RIGHT] = (indexes[TOP] != UNSET && indexes[RIGHT] != UNSET) ? indexes[TOP] + 1 : UNSET; + indexes[BOTTOM_RIGHT] = (indexes[BOTTOM] != UNSET && indexes[RIGHT] != UNSET) ? indexes[BOTTOM] + 1 : UNSET; + indexes[BOTTOM_LEFT] = (indexes[BOTTOM] != UNSET && indexes[LEFT] != UNSET) ? indexes[BOTTOM] - 1 : UNSET; } return indexes; @@ -71,7 +61,8 @@ std::array getNeighborsIndexes(int serverIndex, int width, int size) { * @param screens list to find server * @return server index */ -int getServerIndex(const ScreenList &screens) { +int getServerIndex(const ScreenList &screens) +{ int serverIndex = -1; for (int i = 0; i < screens.size(); ++i) { @@ -86,12 +77,14 @@ int getServerIndex(const ScreenList &screens) { } // namespace -ScreenList::ScreenList(int width) : QList(), m_width(width) {} +ScreenList::ScreenList(int width) : QList(), m_width(width) +{ +} -void ScreenList::addScreenByPriority(const Screen &newScreen) { +void ScreenList::addScreenByPriority(const Screen &newScreen) +{ int serverIndex = getServerIndex(*this); - auto indexes = - getNeighborsIndexes(serverIndex, m_width, static_cast(size())); + auto indexes = getNeighborsIndexes(serverIndex, m_width, static_cast(size())); bool isAdded = false; for (const auto &index : indexes) { @@ -110,7 +103,8 @@ void ScreenList::addScreenByPriority(const Screen &newScreen) { } } -void ScreenList::addScreenToFirstEmpty(const Screen &newScreen) { +void ScreenList::addScreenToFirstEmpty(const Screen &newScreen) +{ for (int i = 0; i < size(); ++i) { auto &screen = operator[](i); if (screen.isNull()) { @@ -120,6 +114,7 @@ void ScreenList::addScreenToFirstEmpty(const Screen &newScreen) { } } -bool ScreenList::operator==(const ScreenList &sc) const { +bool ScreenList::operator==(const ScreenList &sc) const +{ return m_width == sc.m_width && QList::operator==(sc); } diff --git a/src/lib/gui/config/ScreenList.h b/src/lib/gui/config/ScreenList.h index a99abf665..de26b0117 100644 --- a/src/lib/gui/config/ScreenList.h +++ b/src/lib/gui/config/ScreenList.h @@ -19,7 +19,8 @@ #include "Screen.h" -class ScreenList : public QList { +class ScreenList : public QList +{ int m_width = 5; public: diff --git a/src/lib/gui/config/ServerConfigDialogState.h b/src/lib/gui/config/ServerConfigDialogState.h index 43a23f46d..7f37a9c2a 100644 --- a/src/lib/gui/config/ServerConfigDialogState.h +++ b/src/lib/gui/config/ServerConfigDialogState.h @@ -26,10 +26,17 @@ namespace deskflow::gui::config { * lib, we can probably just pass a reference to that rather than needing an * object to track it's state. */ -class ServerConfigDialogState { +class ServerConfigDialogState +{ public: - bool isVisible() const { return m_isVisible; } - void setVisible(bool isVisible) { m_isVisible = isVisible; } + bool isVisible() const + { + return m_isVisible; + } + void setVisible(bool isVisible) + { + m_isVisible = isVisible; + } private: bool m_isVisible = false; diff --git a/src/lib/gui/constants.h b/src/lib/gui/constants.h index 2ef562f4d..b910ca489 100644 --- a/src/lib/gui/constants.h +++ b/src/lib/gui/constants.h @@ -31,12 +31,10 @@ const auto kLinkDownload = R"(Download now)"; const auto kUrlSourceQuery = "source=gui"; const auto kUrlApp = DESKFLOW_WEBSITE_URL; const auto kUrlHelp = QString("%1/help?%2").arg(kUrlApp, kUrlSourceQuery); -const auto kUrlDownload = - QString("%1/download?%2").arg(kUrlApp, kUrlSourceQuery); +const auto kUrlDownload = QString("%1/download?%2").arg(kUrlApp, kUrlSourceQuery); #if defined(Q_OS_LINUX) -const auto kUrlGnomeTrayFix = - "https://extensions.gnome.org/extension/2890/tray-icons-reloaded/"; +const auto kUrlGnomeTrayFix = "https://extensions.gnome.org/extension/2890/tray-icons-reloaded/"; #endif } // namespace deskflow::gui diff --git a/src/lib/gui/core/ClientConnection.cpp b/src/lib/gui/core/ClientConnection.cpp index eeb5ef963..9435aa7b3 100644 --- a/src/lib/gui/core/ClientConnection.cpp +++ b/src/lib/gui/core/ClientConnection.cpp @@ -28,9 +28,8 @@ namespace deskflow::gui { // ClientConnection::Deps // -void ClientConnection::Deps::showError( - QWidget *parent, messages::ClientError error, - const QString &address) const { +void ClientConnection::Deps::showError(QWidget *parent, messages::ClientError error, const QString &address) const +{ messages::showClientConnectError(parent, error, address); } @@ -38,7 +37,8 @@ void ClientConnection::Deps::showError( // ClientConnection // -void ClientConnection::handleLogLine(const QString &logLine) { +void ClientConnection::handleLogLine(const QString &logLine) +{ if (logLine.contains("failed to connect to server")) { @@ -62,14 +62,14 @@ void ClientConnection::handleLogLine(const QString &logLine) { } } -void ClientConnection::showMessage(const QString &logLine) { +void ClientConnection::showMessage(const QString &logLine) +{ using enum messages::ClientError; emit messageShowing(); const auto address = m_appConfig.serverHostname(); - auto message = - QString("

The connection to server '%1' didn't work.

").arg(address); + auto message = QString("

The connection to server '%1' didn't work.

").arg(address); if (logLine.contains("server already has a connected client with our name")) { m_deps->showError(m_pParent, AlreadyConnected, address); diff --git a/src/lib/gui/core/ClientConnection.h b/src/lib/gui/core/ClientConnection.h index e51ca8907..ebbda1854 100644 --- a/src/lib/gui/core/ClientConnection.h +++ b/src/lib/gui/core/ClientConnection.h @@ -30,26 +30,31 @@ class QWidget; namespace deskflow::gui { -class ClientConnection : public QObject { +class ClientConnection : public QObject +{ Q_OBJECT public: - struct Deps { + struct Deps + { virtual ~Deps() = default; - virtual void showError( - QWidget *parent, messages::ClientError error, - const QString &address) const; + virtual void showError(QWidget *parent, messages::ClientError error, const QString &address) const; }; explicit ClientConnection( - QWidget *parent, IAppConfig &appConfig, - std::shared_ptr deps = std::make_shared()) + QWidget *parent, IAppConfig &appConfig, std::shared_ptr deps = std::make_shared() + ) : m_pParent(parent), m_appConfig(appConfig), - m_deps(deps) {} + m_deps(deps) + { + } void handleLogLine(const QString &line); - void setShowMessage() { m_showMessage = true; } + void setShowMessage() + { + m_showMessage = true; + } signals: void messageShowing(); diff --git a/src/lib/gui/core/CommandProcess.cpp b/src/lib/gui/core/CommandProcess.cpp index 0b125306d..4ecf3ee92 100644 --- a/src/lib/gui/core/CommandProcess.cpp +++ b/src/lib/gui/core/CommandProcess.cpp @@ -19,13 +19,15 @@ #include -CommandProcess::CommandProcess( - QString command, QStringList arguments, QString input) +CommandProcess::CommandProcess(QString command, QStringList arguments, QString input) : m_Command(command), m_Arguments(arguments), - m_Input(input) {} + m_Input(input) +{ +} -QString CommandProcess::run() { +QString CommandProcess::run() +{ QProcess process; process.setReadChannel(QProcess::StandardOutput); process.start(m_Command, m_Arguments); @@ -46,9 +48,9 @@ QString CommandProcess::run() { if (int code = process.exitCode(); !success || code != 0) { qFatal( - "command failed: %s %s\ncode: %d\nerror: %s", qUtf8Printable(m_Command), - qUtf8Printable(m_Arguments.join(" ")), code, - error.isEmpty() ? "none" : qUtf8Printable(error)); + "command failed: %s %s\ncode: %d\nerror: %s", qUtf8Printable(m_Command), qUtf8Printable(m_Arguments.join(" ")), + code, error.isEmpty() ? "none" : qUtf8Printable(error) + ); } emit finished(); diff --git a/src/lib/gui/core/CommandProcess.h b/src/lib/gui/core/CommandProcess.h index 8fa6de1c4..e8d1f171e 100644 --- a/src/lib/gui/core/CommandProcess.h +++ b/src/lib/gui/core/CommandProcess.h @@ -20,7 +20,8 @@ #include #include -class CommandProcess : public QObject { +class CommandProcess : public QObject +{ Q_OBJECT public: diff --git a/src/lib/gui/core/CoreProcess.cpp b/src/lib/gui/core/CoreProcess.cpp index 0cb33e4c4..de75286bb 100644 --- a/src/lib/gui/core/CoreProcess.cpp +++ b/src/lib/gui/core/CoreProcess.cpp @@ -46,7 +46,8 @@ const auto kLineSplitRegex = QRegularExpression("\r|\n|\r\n"); // free functions // -QString processModeToString(ProcessMode mode) { +QString processModeToString(ProcessMode mode) +{ using enum ProcessMode; switch (mode) { @@ -60,7 +61,8 @@ QString processModeToString(ProcessMode mode) { } } -QString processStateToString(CoreProcess::ProcessState state) { +QString processStateToString(CoreProcess::ProcessState state) +{ using enum CoreProcess::ProcessState; switch (state) { @@ -88,7 +90,8 @@ QString processStateToString(CoreProcess::ProcessState state) { * Can also be used to create a representation of a command that can be pasted * into a terminal. */ -QString makeQuotedArgs(const QString &app, const QStringList &args) { +QString makeQuotedArgs(const QString &app, const QStringList &args) +{ QStringList command; command << app; command << args; @@ -108,7 +111,8 @@ QString makeQuotedArgs(const QString &app, const QStringList &args) { /** * @brief If IPv6, ensures the IP is surround in square brackets. */ -QString wrapIpv6(const QString &address) { +QString wrapIpv6(const QString &address) +{ if (!address.contains(':') || address.isEmpty()) { return address; } @@ -130,16 +134,19 @@ QString wrapIpv6(const QString &address) { // CoreProcess::Deps // -QString CoreProcess::Deps::appPath(const QString &name) const { +QString CoreProcess::Deps::appPath(const QString &name) const +{ QDir dir(QCoreApplication::applicationDirPath()); return dir.filePath(name); } -bool CoreProcess::Deps::fileExists(const QString &path) const { +bool CoreProcess::Deps::fileExists(const QString &path) const +{ return QFile::exists(path); } -QString CoreProcess::Deps::getProfileRoot() const { +QString CoreProcess::Deps::getProfileRoot() const +{ CoreTool coreTool; QDir appDir = coreTool.getProfileDir(); @@ -155,32 +162,31 @@ QString CoreProcess::Deps::getProfileRoot() const { // CoreProcess // -CoreProcess::CoreProcess( - const IAppConfig &appConfig, const IServerConfig &serverConfig, - std::shared_ptr deps) +CoreProcess::CoreProcess(const IAppConfig &appConfig, const IServerConfig &serverConfig, std::shared_ptr deps) : m_appConfig(appConfig), m_serverConfig(serverConfig), - m_pDeps(deps) { + m_pDeps(deps) +{ connect( &m_pDeps->ipcClient(), &QIpcClient::read, this, // - &CoreProcess::onIpcClientRead); + &CoreProcess::onIpcClientRead + ); connect( &m_pDeps->ipcClient(), &QIpcClient::serviceReady, this, // - &CoreProcess::onIpcClientServiceReady); + &CoreProcess::onIpcClientServiceReady + ); + + connect(&m_pDeps->process(), &QProcessProxy::finished, this, &CoreProcess::onProcessFinished); connect( - &m_pDeps->process(), &QProcessProxy::finished, this, - &CoreProcess::onProcessFinished); + &m_pDeps->process(), &QProcessProxy::readyReadStandardOutput, this, &CoreProcess::onProcessReadyReadStandardOutput + ); connect( - &m_pDeps->process(), &QProcessProxy::readyReadStandardOutput, this, - &CoreProcess::onProcessReadyReadStandardOutput); - - connect( - &m_pDeps->process(), &QProcessProxy::readyReadStandardError, this, - &CoreProcess::onProcessReadyReadStandardError); + &m_pDeps->process(), &QProcessProxy::readyReadStandardError, this, &CoreProcess::onProcessReadyReadStandardError + ); connect(&m_retryTimer, &QTimer::timeout, [this] { if (m_processState == ProcessState::RetryPending) { @@ -191,7 +197,8 @@ CoreProcess::CoreProcess( }); } -void CoreProcess::onIpcClientServiceReady() { +void CoreProcess::onIpcClientServiceReady() +{ if (m_processState == ProcessState::Starting) { qDebug("service ready, continuing core process start"); start(); @@ -200,12 +207,12 @@ void CoreProcess::onIpcClientServiceReady() { stop(); } else { // This may happen when the IPC connection fails and then reconnects. - qWarning( - "ignoring service ready, process state is not starting or stopping"); + qWarning("ignoring service ready, process state is not starting or stopping"); } } -void CoreProcess::onIpcClientError(const QString &text) const { +void CoreProcess::onIpcClientError(const QString &text) const +{ qCritical().noquote() << text; if (m_appConfig.processMode() != ProcessMode::kService) { @@ -215,21 +222,27 @@ void CoreProcess::onIpcClientError(const QString &text) const { } } -void CoreProcess::onIpcClientRead(const QString &text) { handleLogLines(text); } +void CoreProcess::onIpcClientRead(const QString &text) +{ + handleLogLines(text); +} -void CoreProcess::onProcessReadyReadStandardOutput() { +void CoreProcess::onProcessReadyReadStandardOutput() +{ if (m_pDeps->process()) { handleLogLines(m_pDeps->process().readAllStandardOutput()); } } -void CoreProcess::onProcessReadyReadStandardError() { +void CoreProcess::onProcessReadyReadStandardError() +{ if (m_pDeps->process()) { handleLogLines(m_pDeps->process().readAllStandardError()); } } -void CoreProcess::onProcessFinished(int exitCode, QProcess::ExitStatus) { +void CoreProcess::onProcessFinished(int exitCode, QProcess::ExitStatus) +{ const auto wasStarted = m_processState == ProcessState::Started; setConnectionState(ConnectionState::Disconnected); @@ -255,7 +268,8 @@ void CoreProcess::onProcessFinished(int exitCode, QProcess::ExitStatus) { } } -void CoreProcess::startDesktop(const QString &app, const QStringList &args) { +void CoreProcess::startDesktop(const QString &app, const QStringList &args) +{ using enum ProcessState; if (m_processState != Starting) { @@ -277,7 +291,8 @@ void CoreProcess::startDesktop(const QString &app, const QStringList &args) { } } -void CoreProcess::startService(const QString &app, const QStringList &args) { +void CoreProcess::startService(const QString &app, const QStringList &args) +{ using enum ProcessState; if (m_processState != Starting) { @@ -298,7 +313,8 @@ void CoreProcess::startService(const QString &app, const QStringList &args) { setProcessState(Started); } -void CoreProcess::stopDesktop() const { +void CoreProcess::stopDesktop() const +{ if (m_processState != ProcessState::Stopping) { qFatal("core process must be in stopping state"); } @@ -317,7 +333,8 @@ void CoreProcess::stopDesktop() const { } } -void CoreProcess::stopService() { +void CoreProcess::stopService() +{ if (m_processState != ProcessState::Stopping) { qFatal("core process must be in stopping state"); } @@ -331,7 +348,8 @@ void CoreProcess::stopService() { setProcessState(ProcessState::Stopped); } -void CoreProcess::handleLogLines(const QString &text) { +void CoreProcess::handleLogLines(const QString &text) +{ for (const auto &line : text.split(kLineSplitRegex)) { if (line.isEmpty()) { continue; @@ -350,15 +368,13 @@ void CoreProcess::handleLogLines(const QString &text) { } } -void CoreProcess::start(std::optional processModeOption) { +void CoreProcess::start(std::optional processModeOption) +{ QMutexLocker locker(&m_processMutex); - const auto processMode = - processModeOption.value_or(m_appConfig.processMode()); + const auto processMode = processModeOption.value_or(m_appConfig.processMode()); - qInfo( - "starting core %s process (%s mode)", qPrintable(modeString()), - qPrintable(processModeToString(processMode))); + qInfo("starting core %s process (%s mode)", qPrintable(modeString()), qPrintable(processModeToString(processMode))); if (m_processState == ProcessState::Started) { qCritical("core process already started"); @@ -409,15 +425,13 @@ void CoreProcess::start(std::optional processModeOption) { m_lastProcessMode = processMode; } -void CoreProcess::stop(std::optional processModeOption) { +void CoreProcess::stop(std::optional processModeOption) +{ QMutexLocker locker(&m_processMutex); - const auto processMode = - processModeOption.value_or(m_appConfig.processMode()); + const auto processMode = processModeOption.value_or(m_appConfig.processMode()); - qInfo( - "stopping core process (%s mode)", - qPrintable(processModeToString(processMode))); + qInfo("stopping core process (%s mode)", qPrintable(processModeToString(processMode))); if (m_processState == ProcessState::Starting) { qDebug("core process is starting, cancelling"); @@ -438,7 +452,8 @@ void CoreProcess::stop(std::optional processModeOption) { setConnectionState(ConnectionState::Disconnected); } -void CoreProcess::restart() { +void CoreProcess::restart() +{ using enum ProcessMode; qDebug("restarting core process"); @@ -465,7 +480,8 @@ void CoreProcess::restart() { start(); } -void CoreProcess::cleanup() { +void CoreProcess::cleanup() +{ qInfo("cleaning up core process"); const auto isDesktop = m_appConfig.processMode() == ProcessMode::kDesktop; @@ -477,8 +493,8 @@ void CoreProcess::cleanup() { m_pDeps->ipcClient().disconnectFromHost(); } -bool CoreProcess::addGenericArgs( - QStringList &args, const ProcessMode processMode) const { +bool CoreProcess::addGenericArgs(QStringList &args, const ProcessMode processMode) const +{ args << "-f" << "--no-tray" << "--debug" << m_appConfig.logLevelText(); @@ -532,7 +548,8 @@ bool CoreProcess::addGenericArgs( return true; } -bool CoreProcess::addServerArgs(QStringList &args, QString &app) { +bool CoreProcess::addServerArgs(QStringList &args, QString &app) +{ app = m_pDeps->appPath(m_appConfig.coreServerName()); if (!m_pDeps->fileExists(app)) { @@ -585,7 +602,8 @@ bool CoreProcess::addServerArgs(QStringList &args, QString &app) { return true; } -bool CoreProcess::addClientArgs(QStringList &args, QString &app) { +bool CoreProcess::addClientArgs(QStringList &args, QString &app) +{ app = m_pDeps->appPath(m_appConfig.coreClientName()); if (!m_pDeps->fileExists(app)) { @@ -624,7 +642,8 @@ bool CoreProcess::addClientArgs(QStringList &args, QString &app) { return true; } -QString CoreProcess::persistServerConfig() const { +QString CoreProcess::persistServerConfig() const +{ QString configFullPath; if (m_appConfig.useExternalConfig()) { return m_appConfig.configFile(); @@ -635,9 +654,7 @@ QString CoreProcess::persistServerConfig() const { QFile configFile(configDirPath + "/" + kServerConfigFilename); if (!configFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) { - qFatal( - "failed to open core config file for write: %s", - qPrintable(configFile.fileName())); + qFatal("failed to open core config file for write: %s", qPrintable(configFile.fileName())); } m_serverConfig.save(configFile); @@ -645,7 +662,8 @@ QString CoreProcess::persistServerConfig() const { return configFile.fileName(); } -QString CoreProcess::modeString() const { +QString CoreProcess::modeString() const +{ using enum Mode; switch (m_mode) { @@ -659,7 +677,8 @@ QString CoreProcess::modeString() const { } } -void CoreProcess::setConnectionState(ConnectionState state) { +void CoreProcess::setConnectionState(ConnectionState state) +{ if (m_connectionState == state) { return; } @@ -668,20 +687,22 @@ void CoreProcess::setConnectionState(ConnectionState state) { emit connectionStateChanged(state); } -void CoreProcess::setProcessState(ProcessState state) { +void CoreProcess::setProcessState(ProcessState state) +{ if (m_processState == state) { return; } qDebug( "core process state changed: %s -> %s", // - qPrintable(processStateToString(m_processState)), - qPrintable(processStateToString(state))); + qPrintable(processStateToString(m_processState)), qPrintable(processStateToString(state)) + ); m_processState = state; emit processStateChanged(state); } -void CoreProcess::checkLogLine(const QString &line) { +void CoreProcess::checkLogLine(const QString &line) +{ using enum ConnectionState; if (line.contains("connected to server") || line.contains("has connected")) { @@ -689,9 +710,7 @@ void CoreProcess::checkLogLine(const QString &line) { } else if (line.contains("started server")) { setConnectionState(Listening); - } else if ( - line.contains("disconnected from server") || - line.contains("process exited")) { + } else if (line.contains("disconnected from server") || line.contains("process exited")) { setConnectionState(Disconnected); } else if (line.contains("connecting to")) { setConnectionState(Connecting); @@ -706,7 +725,8 @@ void CoreProcess::checkLogLine(const QString &line) { #endif } -bool CoreProcess::checkSecureSocket(const QString &line) { +bool CoreProcess::checkSecureSocket(const QString &line) +{ static const QString tlsCheckString = "network encryption protocol: "; const auto index = line.indexOf(tlsCheckString, 0, Qt::CaseInsensitive); if (index == -1) { @@ -719,15 +739,14 @@ bool CoreProcess::checkSecureSocket(const QString &line) { } #ifdef Q_OS_MAC -void CoreProcess::checkOSXNotification(const QString &line) { +void CoreProcess::checkOSXNotification(const QString &line) +{ static const QString needle = "OSX Notification: "; if (line.contains(needle) && line.contains('|')) { int delimiterPosition = line.indexOf('|'); int start = line.indexOf(needle); - QString title = line.mid( - start + needle.length(), delimiterPosition - start - needle.length()); - QString body = - line.mid(delimiterPosition + 1, line.length() - delimiterPosition); + QString title = line.mid(start + needle.length(), delimiterPosition - start - needle.length()); + QString body = line.mid(delimiterPosition + 1, line.length() - delimiterPosition); if (!showOSXNotification(title, body)) { qDebug("osx notification was not shown"); } @@ -735,11 +754,15 @@ void CoreProcess::checkOSXNotification(const QString &line) { } #endif -QString CoreProcess::correctedInterface() const { +QString CoreProcess::correctedInterface() const +{ QString interface = wrapIpv6(m_appConfig.networkInterface()); return interface + ":" + QString::number(m_appConfig.port()); } -QString CoreProcess::correctedAddress() const { return wrapIpv6(m_address); } +QString CoreProcess::correctedAddress() const +{ + return wrapIpv6(m_address); +} } // namespace deskflow::gui diff --git a/src/lib/gui/core/CoreProcess.h b/src/lib/gui/core/CoreProcess.h index a1a32e119..05b216b01 100644 --- a/src/lib/gui/core/CoreProcess.h +++ b/src/lib/gui/core/CoreProcess.h @@ -31,7 +31,8 @@ namespace deskflow::gui { -class CoreProcess : public QObject { +class CoreProcess : public QObject +{ using IServerConfig = deskflow::gui::IServerConfig; using QProcessProxy = deskflow::gui::proxy::QProcessProxy; using IQIpcClient = deskflow::gui::ipc::IQIpcClient; @@ -39,10 +40,17 @@ class CoreProcess : public QObject { Q_OBJECT public: - struct Deps { + struct Deps + { virtual ~Deps() = default; - virtual QProcessProxy &process() { return m_process; } - virtual IQIpcClient &ipcClient() { return m_ipcClient; } + virtual QProcessProxy &process() + { + return m_process; + } + virtual IQIpcClient &ipcClient() + { + return m_ipcClient; + } virtual QString appPath(const QString &name) const; virtual bool fileExists(const QString &path) const; virtual QString getProfileRoot() const; @@ -52,20 +60,37 @@ public: QIpcClient m_ipcClient; }; - enum class Mode { None, Client, Server }; - enum class Error { AddressMissing, StartFailed }; - enum class ProcessState { + enum class Mode + { + None, + Client, + Server + }; + enum class Error + { + AddressMissing, + StartFailed + }; + enum class ProcessState + { Starting, Started, Stopping, Stopped, RetryPending }; - enum class ConnectionState { Disconnected, Connecting, Connected, Listening }; + enum class ConnectionState + { + Disconnected, + Connecting, + Connected, + Listening + }; explicit CoreProcess( const IAppConfig &appConfig, const IServerConfig &serverConfig, - std::shared_ptr deps = std::make_shared()); + std::shared_ptr deps = std::make_shared() + ); void extracted(QString &app, QStringList &args); void start(std::optional processMode = std::nullopt); @@ -74,15 +99,36 @@ public: void cleanup(); // getters - Mode mode() const { return m_mode; } - QString secureSocketVersion() const { return m_secureSocketVersion; } - bool isStarted() const { return m_processState == ProcessState::Started; } - ProcessState processState() const { return m_processState; } - ConnectionState connectionState() const { return m_connectionState; } + Mode mode() const + { + return m_mode; + } + QString secureSocketVersion() const + { + return m_secureSocketVersion; + } + bool isStarted() const + { + return m_processState == ProcessState::Started; + } + ProcessState processState() const + { + return m_processState; + } + ConnectionState connectionState() const + { + return m_connectionState; + } // setters - void setAddress(const QString &address) { m_address = address.trimmed(); } - void setMode(Mode mode) { m_mode = mode; } + void setAddress(const QString &address) + { + m_address = address.trimmed(); + } + void setMode(Mode mode) + { + m_mode = mode; + } signals: void starting(); diff --git a/src/lib/gui/core/CoreTool.cpp b/src/lib/gui/core/CoreTool.cpp index 30922a050..a4d927691 100644 --- a/src/lib/gui/core/CoreTool.cpp +++ b/src/lib/gui/core/CoreTool.cpp @@ -26,22 +26,26 @@ static const char kCoreBinary[] = LEGACY_BINARY_NAME; -QString CoreTool::getProfileDir() const { +QString CoreTool::getProfileDir() const +{ QStringList args("--get-profile-dir"); return QDir::cleanPath(run(args)); } -QString CoreTool::getInstalledDir() const { +QString CoreTool::getInstalledDir() const +{ QStringList args("--get-installed-dir"); return QDir::cleanPath(run(args)); } -QString CoreTool::getArch() const { +QString CoreTool::getArch() const +{ QStringList args("--get-arch"); return run(args); } -QString CoreTool::run(const QStringList &args, const QString &input) const { +QString CoreTool::run(const QStringList &args, const QString &input) const +{ QString program(QCoreApplication::applicationDirPath() + "/" + kCoreBinary); CommandProcess commandProcess(program, args, input); diff --git a/src/lib/gui/core/CoreTool.h b/src/lib/gui/core/CoreTool.h index 1fba40abd..228e1fe27 100644 --- a/src/lib/gui/core/CoreTool.h +++ b/src/lib/gui/core/CoreTool.h @@ -19,7 +19,8 @@ #include -class CoreTool { +class CoreTool +{ public: QString getProfileDir() const; QString getInstalledDir() const; diff --git a/src/lib/gui/core/ServerConnection.cpp b/src/lib/gui/core/ServerConnection.cpp index 0d7b8e59f..205bb7581 100644 --- a/src/lib/gui/core/ServerConnection.cpp +++ b/src/lib/gui/core/ServerConnection.cpp @@ -30,8 +30,9 @@ namespace deskflow::gui { // ServerConnection::Deps // -messages::NewClientPromptResult ServerConnection::Deps::showNewClientPrompt( - QWidget *parent, const QString &clientName) const { +messages::NewClientPromptResult +ServerConnection::Deps::showNewClientPrompt(QWidget *parent, const QString &clientName) const +{ return messages::showNewClientPrompt(parent, clientName); } @@ -41,15 +42,18 @@ messages::NewClientPromptResult ServerConnection::Deps::showNewClientPrompt( ServerConnection::ServerConnection( QWidget *parent, IAppConfig &appConfig, IServerConfig &serverConfig, - const config::ServerConfigDialogState &serverConfigDialogState, - std::shared_ptr deps) + const config::ServerConfigDialogState &serverConfigDialogState, std::shared_ptr deps +) : m_pParent(parent), m_appConfig(appConfig), m_serverConfig(serverConfig), m_serverConfigDialogState(serverConfigDialogState), - m_pDeps(deps) {} + m_pDeps(deps) +{ +} -void ServerConnection::handleLogLine(const QString &logLine) { +void ServerConnection::handleLogLine(const QString &logLine) +{ ServerMessage message(logLine); if (!message.isNewClientMessage()) { @@ -74,31 +78,26 @@ void ServerConnection::handleLogLine(const QString &logLine) { const auto client = message.getClientName(); if (m_receivedClients.contains(client)) { - qDebug( - "already got request, skipping new client prompt for: %s", - qPrintable(client)); + qDebug("already got request, skipping new client prompt for: %s", qPrintable(client)); return; } handleNewClient(message.getClientName()); } -void ServerConnection::handleNewClient(const QString &clientName) { +void ServerConnection::handleNewClient(const QString &clientName) +{ using enum messages::NewClientPromptResult; m_receivedClients.append(clientName); if (m_serverConfig.isFull()) { - qDebug( - "server config full, skipping new client prompt for: %s", - qPrintable(clientName)); + qDebug("server config full, skipping new client prompt for: %s", qPrintable(clientName)); return; } if (m_serverConfig.screenExists(clientName)) { - qDebug( - "client already added, skipping new client prompt for: %s", - qPrintable(clientName)); + qDebug("client already added, skipping new client prompt for: %s", qPrintable(clientName)); return; } diff --git a/src/lib/gui/core/ServerConnection.h b/src/lib/gui/core/ServerConnection.h index da58cd810..412532ff7 100644 --- a/src/lib/gui/core/ServerConnection.h +++ b/src/lib/gui/core/ServerConnection.h @@ -27,21 +27,23 @@ namespace deskflow::gui { -class ServerConnection : public QObject { +class ServerConnection : public QObject +{ Q_OBJECT using IServerConfig = deskflow::gui::IServerConfig; public: - struct Deps { + struct Deps + { virtual ~Deps() = default; - virtual messages::NewClientPromptResult - showNewClientPrompt(QWidget *parent, const QString &clientName) const; + virtual messages::NewClientPromptResult showNewClientPrompt(QWidget *parent, const QString &clientName) const; }; explicit ServerConnection( QWidget *parent, IAppConfig &appConfig, IServerConfig &serverConfig, const config::ServerConfigDialogState &serverConfigDialogState, - std::shared_ptr deps = std::make_shared()); + std::shared_ptr deps = std::make_shared() + ); void handleLogLine(const QString &logLine); signals: diff --git a/src/lib/gui/core/ServerMessage.cpp b/src/lib/gui/core/ServerMessage.cpp index 118db30d2..3201b8e69 100644 --- a/src/lib/gui/core/ServerMessage.cpp +++ b/src/lib/gui/core/ServerMessage.cpp @@ -19,29 +19,37 @@ namespace deskflow::gui { -ServerMessage::ServerMessage(const QString &message) - : m_message(message), - m_clientName(parseClientName(message)) {} +ServerMessage::ServerMessage(const QString &message) : m_message(message), m_clientName(parseClientName(message)) +{ +} -bool ServerMessage::isNewClientMessage() const { +bool ServerMessage::isNewClientMessage() const +{ return m_message.contains("unrecognised client name"); } -bool ServerMessage::isExitMessage() const { +bool ServerMessage::isExitMessage() const +{ return m_message.contains("process exited"); } -bool ServerMessage::isConnectedMessage() const { +bool ServerMessage::isConnectedMessage() const +{ return m_message.contains("has connected"); } -bool ServerMessage::isDisconnectedMessage() const { +bool ServerMessage::isDisconnectedMessage() const +{ return m_message.contains("has disconnected"); } -const QString &ServerMessage::getClientName() const { return m_clientName; } +const QString &ServerMessage::getClientName() const +{ + return m_clientName; +} -QString ServerMessage::parseClientName(const QString &line) const { +QString ServerMessage::parseClientName(const QString &line) const +{ QString clientName("Unknown"); auto nameStart = line.indexOf('"') + 1; auto nameEnd = line.indexOf('"', nameStart); diff --git a/src/lib/gui/core/ServerMessage.h b/src/lib/gui/core/ServerMessage.h index a5acab033..b06016a61 100644 --- a/src/lib/gui/core/ServerMessage.h +++ b/src/lib/gui/core/ServerMessage.h @@ -21,7 +21,8 @@ namespace deskflow::gui { -class ServerMessage { +class ServerMessage +{ QString m_message; QString m_clientName; diff --git a/src/lib/gui/core/WaylandWarnings.cpp b/src/lib/gui/core/WaylandWarnings.cpp index beea755b1..7c01f6b13 100644 --- a/src/lib/gui/core/WaylandWarnings.cpp +++ b/src/lib/gui/core/WaylandWarnings.cpp @@ -27,7 +27,8 @@ namespace deskflow::gui::core { // WaylandWarnings::Deps // -void WaylandWarnings::Deps::showWaylandLibraryError(QWidget *parent) { +void WaylandWarnings::Deps::showWaylandLibraryError(QWidget *parent) +{ messages::showWaylandLibraryError(parent); } @@ -36,11 +37,11 @@ void WaylandWarnings::Deps::showWaylandLibraryError(QWidget *parent) { // void WaylandWarnings::showOnce( - QWidget *parent, CoreProcess::Mode mode, bool hasEi, bool hasPortal, - bool hasPortalInputCapture) { + QWidget *parent, CoreProcess::Mode mode, bool hasEi, bool hasPortal, bool hasPortalInputCapture +) +{ - const auto portalIcProblem = - !hasPortalInputCapture && mode == CoreProcess::Mode::Server; + const auto portalIcProblem = !hasPortalInputCapture && mode == CoreProcess::Mode::Server; if (!hasEi || !hasPortal || portalIcProblem) { if (!m_errorShown) { diff --git a/src/lib/gui/core/WaylandWarnings.h b/src/lib/gui/core/WaylandWarnings.h index 21e952427..0c2b2690c 100644 --- a/src/lib/gui/core/WaylandWarnings.h +++ b/src/lib/gui/core/WaylandWarnings.h @@ -25,21 +25,23 @@ namespace deskflow::gui::core { -class WaylandWarnings { +class WaylandWarnings +{ public: - struct Deps { + struct Deps + { virtual ~Deps() = default; virtual void showWaylandLibraryError(QWidget *parent); }; - explicit WaylandWarnings( - std::shared_ptr deps = std::make_shared()) - : m_pDeps(deps) {} + explicit WaylandWarnings(std::shared_ptr deps = std::make_shared()) : m_pDeps(deps) + { + } void showOnce( - QWidget *parent, CoreProcess::Mode mode, bool hasEi = platform::kHasEi, - bool hasPortal = platform::kHasPortal, - bool hasPortalInputCapture = platform::kHasPortalInputCapture); + QWidget *parent, CoreProcess::Mode mode, bool hasEi = platform::kHasEi, bool hasPortal = platform::kHasPortal, + bool hasPortalInputCapture = platform::kHasPortalInputCapture + ); private: bool m_errorShown{false}; diff --git a/src/lib/gui/diagnostic.cpp b/src/lib/gui/diagnostic.cpp index 5b1e666f3..3b6006af3 100644 --- a/src/lib/gui/diagnostic.cpp +++ b/src/lib/gui/diagnostic.cpp @@ -26,7 +26,8 @@ namespace deskflow::gui::diagnostic { -void restart() { +void restart() +{ QString program = QCoreApplication::applicationFilePath(); QStringList arguments = QCoreApplication::arguments(); @@ -40,7 +41,8 @@ void restart() { QApplication::exit(); } -void clearSettings(ConfigScopes &scopes, bool enableRestart) { +void clearSettings(ConfigScopes &scopes, bool enableRestart) +{ qDebug("clearing settings"); scopes.clear(); diff --git a/src/lib/gui/dialogs/AboutDialog.cpp b/src/lib/gui/dialogs/AboutDialog.cpp index 437ba5576..e876fb790 100644 --- a/src/lib/gui/dialogs/AboutDialog.cpp +++ b/src/lib/gui/dialogs/AboutDialog.cpp @@ -32,7 +32,10 @@ using namespace deskflow::gui; // AboutDialog::Deps // -bool AboutDialog::Deps::isDarkMode() const { return ::isDarkMode(); } +bool AboutDialog::Deps::isDarkMode() const +{ + return ::isDarkMode(); +} // // AboutDialog @@ -41,7 +44,8 @@ bool AboutDialog::Deps::isDarkMode() const { return ::isDarkMode(); } AboutDialog::AboutDialog(QMainWindow *parent, std::shared_ptr deps) : QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint), Ui::AboutDialogBase(), - m_pDeps(deps) { + m_pDeps(deps) +{ setupUi(this); @@ -54,13 +58,13 @@ AboutDialog::AboutDialog(QMainWindow *parent, std::shared_ptr deps) QString buildDateString = QString::fromLocal8Bit(BUILD_DATE).simplified(); QDate buildDate = QLocale("en_US").toDate(buildDateString, "yyyy-MM-dd"); m_pLabelBuildDate->setTextInteractionFlags(Qt::TextSelectableByMouse); - m_pLabelBuildDate->setText( - buildDate.toString(QLocale::system().dateFormat(QLocale::LongFormat))); + m_pLabelBuildDate->setText(buildDate.toString(QLocale::system().dateFormat(QLocale::LongFormat))); this->setWindowTitle(QString("About %1").arg(DESKFLOW_APP_NAME)); } -int AboutDialog::exec() { +int AboutDialog::exec() +{ m_pDevelopersLabel->setText(importantDevelopers()); m_pCopyrightLabel->setText(QString::fromStdString(deskflow::copyright())); updateLogo(); @@ -68,7 +72,8 @@ int AboutDialog::exec() { return QDialog::exec(); } -void AboutDialog::setLogo(const char *const &filename) const { +void AboutDialog::setLogo(const char *const &filename) const +{ QPixmap logo(filename); if (!logo.isNull()) { m_pLabel_Logo->setPixmap(logo); @@ -77,7 +82,8 @@ void AboutDialog::setLogo(const char *const &filename) const { } } -void AboutDialog::updateLogo() const { +void AboutDialog::updateLogo() const +{ if (m_pDeps->isDarkMode()) { qDebug("showing dark logo"); setLogo(":/image/logo-dark.png"); @@ -87,7 +93,8 @@ void AboutDialog::updateLogo() const { } } -QString AboutDialog::importantDevelopers() const { +QString AboutDialog::importantDevelopers() const +{ QStringList awesomePeople; awesomePeople diff --git a/src/lib/gui/dialogs/AboutDialog.h b/src/lib/gui/dialogs/AboutDialog.h index 53d7c9df7..045acd9ba 100644 --- a/src/lib/gui/dialogs/AboutDialog.h +++ b/src/lib/gui/dialogs/AboutDialog.h @@ -26,18 +26,18 @@ class QWidget; class QString; -class AboutDialog : public QDialog, public Ui::AboutDialogBase { +class AboutDialog : public QDialog, public Ui::AboutDialogBase +{ Q_OBJECT public: - struct Deps { + struct Deps + { virtual ~Deps() = default; virtual bool isDarkMode() const; }; - explicit AboutDialog( - QMainWindow *parent, - std::shared_ptr deps = std::make_shared()); + explicit AboutDialog(QMainWindow *parent, std::shared_ptr deps = std::make_shared()); int exec() override; private: diff --git a/src/lib/gui/dialogs/SettingsDialog.cpp b/src/lib/gui/dialogs/SettingsDialog.cpp index b840fd44a..6c2d74091 100644 --- a/src/lib/gui/dialogs/SettingsDialog.cpp +++ b/src/lib/gui/dialogs/SettingsDialog.cpp @@ -39,14 +39,15 @@ using namespace deskflow::gui; SettingsDialog::SettingsDialog( - QWidget *parent, IAppConfig &appConfig, const IServerConfig &serverConfig, - const CoreProcess &coreProcess) + QWidget *parent, IAppConfig &appConfig, const IServerConfig &serverConfig, const CoreProcess &coreProcess +) : QDialog(parent, Qt::WindowTitleHint | Qt::WindowSystemMenuHint), Ui::SettingsDialogBase(), m_appConfig(appConfig), m_serverConfig(serverConfig), m_coreProcess(coreProcess), - m_tlsUtility(appConfig) { + m_tlsUtility(appConfig) +{ setupUi(this); @@ -59,12 +60,11 @@ SettingsDialog::SettingsDialog( updateControls(); m_pScreenNameError = new validators::ValidationError(this); - m_pLineEditScreenName->setValidator(new validators::ScreenNameValidator( - m_pLineEditScreenName, m_pScreenNameError, &serverConfig.screens())); + m_pLineEditScreenName->setValidator( + new validators::ScreenNameValidator(m_pLineEditScreenName, m_pScreenNameError, &serverConfig.screens()) + ); - connect( - m_pCheckBoxEnableTls, &QCheckBox::toggled, this, - &SettingsDialog::updateTlsControlsEnabled); + connect(m_pCheckBoxEnableTls, &QCheckBox::toggled, this, &SettingsDialog::updateTlsControlsEnabled); connect( this, &SettingsDialog::shown, this, @@ -73,7 +73,8 @@ SettingsDialog::SettingsDialog( showReadOnlyMessage(); } }, - Qt::QueuedConnection); + Qt::QueuedConnection + ); #ifdef DESKFLOW_GUI_HOOK_SETTINGS DESKFLOW_GUI_HOOK_SETTINGS @@ -84,7 +85,8 @@ SettingsDialog::SettingsDialog( // Auto-connect slots // -void SettingsDialog::on_m_pCheckBoxLogToFile_stateChanged(int i) { +void SettingsDialog::on_m_pCheckBoxLogToFile_stateChanged(int i) +{ bool checked = i == 2; m_pLabelLogPath->setEnabled(checked); @@ -92,21 +94,24 @@ void SettingsDialog::on_m_pCheckBoxLogToFile_stateChanged(int i) { m_pButtonBrowseLog->setEnabled(checked); } -void SettingsDialog::on_m_pButtonBrowseLog_clicked() { +void SettingsDialog::on_m_pButtonBrowseLog_clicked() +{ QString fileName = QFileDialog::getSaveFileName( - this, tr("Save log file to..."), m_pLineEditLogFilename->text(), - "Logs (*.log *.txt)"); + this, tr("Save log file to..."), m_pLineEditLogFilename->text(), "Logs (*.log *.txt)" + ); if (!fileName.isEmpty()) { m_pLineEditLogFilename->setText(fileName); } } -void SettingsDialog::on_m_pCheckBoxEnableTls_clicked(bool) { +void SettingsDialog::on_m_pCheckBoxEnableTls_clicked(bool) +{ updateTlsControlsEnabled(); } -void SettingsDialog::on_m_pRadioSystemScope_toggled(bool checked) { +void SettingsDialog::on_m_pRadioSystemScope_toggled(bool checked) +{ // We only need to test the System scoped Radio as they are connected m_appConfig.setLoadFromSystemScope(checked); loadFromConfig(); @@ -117,11 +122,12 @@ void SettingsDialog::on_m_pRadioSystemScope_toggled(bool checked) { } } -void SettingsDialog::on_m_pPushButtonTlsCertPath_clicked() { +void SettingsDialog::on_m_pPushButtonTlsCertPath_clicked() +{ QString fileName = QFileDialog::getSaveFileName( - this, tr("Select a TLS certificate to use..."), - m_pLineEditTlsCertPath->text(), "Cert (*.pem)", nullptr, - QFileDialog::DontConfirmOverwrite); + this, tr("Select a TLS certificate to use..."), m_pLineEditTlsCertPath->text(), "Cert (*.pem)", nullptr, + QFileDialog::DontConfirmOverwrite + ); if (!fileName.isEmpty()) { m_pLineEditTlsCertPath->setText(fileName); @@ -134,15 +140,15 @@ void SettingsDialog::on_m_pPushButtonTlsCertPath_clicked() { } } -void SettingsDialog::on_m_pPushButtonTlsRegenCert_clicked() { +void SettingsDialog::on_m_pPushButtonTlsRegenCert_clicked() +{ if (m_tlsUtility.generateCertificate()) { - QMessageBox::information( - this, tr("TLS Certificate Regenerated"), - tr("TLS certificate regenerated successfully.")); + QMessageBox::information(this, tr("TLS Certificate Regenerated"), tr("TLS certificate regenerated successfully.")); } } -void SettingsDialog::on_m_pCheckBoxServiceEnabled_toggled(bool) { +void SettingsDialog::on_m_pCheckBoxServiceEnabled_toggled(bool) +{ updateControls(); } @@ -150,20 +156,22 @@ void SettingsDialog::on_m_pCheckBoxServiceEnabled_toggled(bool) { // End of auto-connect slots // -void SettingsDialog::showEvent(QShowEvent *event) { +void SettingsDialog::showEvent(QShowEvent *event) +{ QDialog::showEvent(event); emit shown(); } -void SettingsDialog::showReadOnlyMessage() { +void SettingsDialog::showReadOnlyMessage() +{ const auto activeScopeFilename = m_appConfig.scopes().activeFilePath(); messages::showReadOnlySettings(this, activeScopeFilename); } -void SettingsDialog::accept() { +void SettingsDialog::accept() +{ if (!m_pLineEditScreenName->hasAcceptableInput()) { - QMessageBox::warning( - this, tr("Invalid screen name"), m_pScreenNameError->message()); + QMessageBox::warning(this, tr("Invalid screen name"), m_pScreenNameError->message()); return; } @@ -174,8 +182,7 @@ void SettingsDialog::accept() { m_appConfig.setLogLevel(m_pComboLogLevel->currentIndex()); m_appConfig.setLogToFile(m_pCheckBoxLogToFile->isChecked()); m_appConfig.setLogFilename(m_pLineEditLogFilename->text()); - m_appConfig.setElevateMode( - static_cast(m_pComboElevate->currentIndex())); + m_appConfig.setElevateMode(static_cast(m_pComboElevate->currentIndex())); m_appConfig.setAutoHide(m_pCheckBoxAutoHide->isChecked()); m_appConfig.setPreventSleep(m_pCheckBoxPreventSleep->isChecked()); m_appConfig.setTlsCertPath(m_pLineEditTlsCertPath->text()); @@ -190,7 +197,8 @@ void SettingsDialog::accept() { QDialog::accept(); } -void SettingsDialog::reject() { +void SettingsDialog::reject() +{ // restore original system scope value on reject. if (m_appConfig.isActiveScopeSystem() != m_wasOriginallySystemScope) { m_appConfig.setLoadFromSystemScope(m_wasOriginallySystemScope); @@ -199,7 +207,8 @@ void SettingsDialog::reject() { QDialog::reject(); } -void SettingsDialog::loadFromConfig() { +void SettingsDialog::loadFromConfig() +{ m_pLineEditScreenName->setText(m_appConfig.screenName()); m_pSpinBoxPort->setValue(m_appConfig.port()); @@ -226,14 +235,14 @@ void SettingsDialog::loadFromConfig() { updateTlsControls(); } -void SettingsDialog::updateTlsControls() { +void SettingsDialog::updateTlsControls() +{ if (QFile(m_appConfig.tlsCertPath()).exists()) { updateKeyLengthOnFile(m_appConfig.tlsCertPath()); } else { const auto keyLengthText = QString::number(m_appConfig.tlsKeyLength()); - m_pComboBoxTlsKeyLength->setCurrentIndex( - m_pComboBoxTlsKeyLength->findText(keyLengthText)); + m_pComboBoxTlsKeyLength->setCurrentIndex(m_pComboBoxTlsKeyLength->findText(keyLengthText)); } const auto tlsEnabled = m_tlsUtility.isEnabled(); @@ -244,7 +253,8 @@ void SettingsDialog::updateTlsControls() { m_pLineEditTlsCertPath->setText(m_appConfig.tlsCertPath()); } -void SettingsDialog::updateTlsControlsEnabled() { +void SettingsDialog::updateTlsControlsEnabled() +{ const auto writable = m_appConfig.isActiveScopeWritable(); const auto clientMode = m_appConfig.clientGroupChecked(); const auto tlsChecked = m_pCheckBoxEnableTls->isChecked(); @@ -258,11 +268,13 @@ void SettingsDialog::updateTlsControlsEnabled() { m_pPushButtonTlsRegenCert->setEnabled(enabled); } -bool SettingsDialog::isClientMode() const { +bool SettingsDialog::isClientMode() const +{ return m_coreProcess.mode() == deskflow::gui::CoreProcess::Mode::Client; } -void SettingsDialog::updateKeyLengthOnFile(const QString &path) { +void SettingsDialog::updateKeyLengthOnFile(const QString &path) +{ TlsCertificate ssl; if (!QFile(path).exists()) { qFatal("tls certificate file not found: %s", qUtf8Printable(path)); @@ -274,7 +286,8 @@ void SettingsDialog::updateKeyLengthOnFile(const QString &path) { m_appConfig.setTlsKeyLength(length); } -void SettingsDialog::updateControls() { +void SettingsDialog::updateControls() +{ #if defined(Q_OS_WIN) const auto serviceAvailable = true; diff --git a/src/lib/gui/dialogs/SettingsDialog.h b/src/lib/gui/dialogs/SettingsDialog.h index c96685b3e..4cd29c7cf 100644 --- a/src/lib/gui/dialogs/SettingsDialog.h +++ b/src/lib/gui/dialogs/SettingsDialog.h @@ -29,7 +29,8 @@ #include -class SettingsDialog : public QDialog, public Ui::SettingsDialogBase { +class SettingsDialog : public QDialog, public Ui::SettingsDialogBase +{ using IAppConfig = deskflow::gui::IAppConfig; using IServerConfig = deskflow::gui::IServerConfig; using CoreProcess = deskflow::gui::CoreProcess; @@ -39,8 +40,8 @@ class SettingsDialog : public QDialog, public Ui::SettingsDialogBase { public: void extracted(); SettingsDialog( - QWidget *parent, IAppConfig &appConfig, const IServerConfig &serverConfig, - const CoreProcess &coreProcess); + QWidget *parent, IAppConfig &appConfig, const IServerConfig &serverConfig, const CoreProcess &coreProcess + ); signals: void shown(); diff --git a/src/lib/gui/dotenv.cpp b/src/lib/gui/dotenv.cpp index 7a9aa9286..4e9c22177 100644 --- a/src/lib/gui/dotenv.cpp +++ b/src/lib/gui/dotenv.cpp @@ -33,7 +33,8 @@ namespace deskflow::gui { QPair getPair(const QString &line); -bool open(QFile &file, const QString &filePath) { +bool open(QFile &file, const QString &filePath) +{ file.setFileName(filePath); return file.open(QIODevice::ReadOnly | QIODevice::Text); } @@ -48,14 +49,13 @@ bool open(QFile &file, const QString &filePath) { * If this function is not sufficient, replace it with a library such as: * https://github.com/adeharo9/cpp-dotenv */ -void dotenv(const QString &filename) { +void dotenv(const QString &filename) +{ QString filePath = filename; QFile file; if (!open(file, filePath)) { QFileInfo fileInfo(filePath); - qInfo( - "no %s file in dir: %s", qPrintable(filename), - qPrintable(fileInfo.absolutePath())); + qInfo("no %s file in dir: %s", qPrintable(filename), qPrintable(fileInfo.absolutePath())); // if nothing in current dir, then try the config dir. // this makes it a bit easier for engineers in the field to have an easily @@ -64,9 +64,7 @@ void dotenv(const QString &filename) { filePath = orgDir.filePath(filename); if (!open(file, filePath)) { - qInfo( - "no %s file in app config dir: %s", qPrintable(filename), - qPrintable(orgDir.absolutePath())); + qInfo("no %s file in app config dir: %s", qPrintable(filename), qPrintable(orgDir.absolutePath())); return; } } @@ -94,7 +92,8 @@ void dotenv(const QString &filename) { } } -QString stripQuotes(const QString &value) { +QString stripQuotes(const QString &value) +{ QString result = value; if (result.startsWith('"') && result.endsWith('"')) { result = result.mid(1, result.length() - 2); @@ -102,7 +101,8 @@ QString stripQuotes(const QString &value) { return result; } -QPair getPair(const QString &line) { +QPair getPair(const QString &line) +{ auto pos = line.indexOf('='); if (pos == -1) { return QPair("", ""); diff --git a/src/lib/gui/env_vars.h b/src/lib/gui/env_vars.h index 0ca7e54eb..77b3d212f 100644 --- a/src/lib/gui/env_vars.h +++ b/src/lib/gui/env_vars.h @@ -22,7 +22,8 @@ namespace deskflow::gui::env_vars { -inline QString versionUrl() { +inline QString versionUrl() +{ if (QString(DESKFLOW_VERSION_URL).isEmpty()) { qFatal("version url is not set"); } diff --git a/src/lib/gui/ipc/IQIpcClient.h b/src/lib/gui/ipc/IQIpcClient.h index e9c0b1eac..a3e9cf8d9 100644 --- a/src/lib/gui/ipc/IQIpcClient.h +++ b/src/lib/gui/ipc/IQIpcClient.h @@ -24,13 +24,13 @@ namespace deskflow::gui::ipc { -class IQIpcClient : public QObject { +class IQIpcClient : public QObject +{ Q_OBJECT public: ~IQIpcClient() override = default; virtual void sendHello() const = 0; - virtual void - sendCommand(const QString &command, ElevateMode elevate) const = 0; + virtual void sendCommand(const QString &command, ElevateMode elevate) const = 0; virtual void connectToHost() = 0; virtual void disconnectFromHost() = 0; virtual bool isConnected() const = 0; diff --git a/src/lib/gui/ipc/IpcReader.cpp b/src/lib/gui/ipc/IpcReader.cpp index e1b1ec343..10198c6c1 100644 --- a/src/lib/gui/ipc/IpcReader.cpp +++ b/src/lib/gui/ipc/IpcReader.cpp @@ -27,19 +27,22 @@ using namespace deskflow::gui; -IpcReader::IpcReader(QTcpSocket *socket) : m_Socket(socket) {} - -void IpcReader::start() const { - connect( - m_Socket, &QTcpSocket::readyRead, this, &IpcReader::onSocketReadyRead); +IpcReader::IpcReader(QTcpSocket *socket) : m_Socket(socket) +{ } -void IpcReader::stop() const { - disconnect( - m_Socket, &QTcpSocket::readyRead, this, &IpcReader::onSocketReadyRead); +void IpcReader::start() const +{ + connect(m_Socket, &QTcpSocket::readyRead, this, &IpcReader::onSocketReadyRead); } -void IpcReader::onSocketReadyRead() { +void IpcReader::stop() const +{ + disconnect(m_Socket, &QTcpSocket::readyRead, this, &IpcReader::onSocketReadyRead); +} + +void IpcReader::onSocketReadyRead() +{ QMutexLocker locker(&m_Mutex); logVerbose("ready read"); @@ -75,7 +78,8 @@ void IpcReader::onSocketReadyRead() { logVerbose("read done"); } -bool IpcReader::readStream(char *buffer, int length) { +bool IpcReader::readStream(char *buffer, int length) +{ logVerbose("reading stream"); int read = 0; diff --git a/src/lib/gui/ipc/IpcReader.h b/src/lib/gui/ipc/IpcReader.h index 7ec4ed344..2cc562156 100644 --- a/src/lib/gui/ipc/IpcReader.h +++ b/src/lib/gui/ipc/IpcReader.h @@ -22,7 +22,8 @@ class QTcpSocket; -class IpcReader : public QObject { +class IpcReader : public QObject +{ Q_OBJECT; public: diff --git a/src/lib/gui/ipc/QDataStreamProxy.h b/src/lib/gui/ipc/QDataStreamProxy.h index db0c0e7ef..fbdd610b7 100644 --- a/src/lib/gui/ipc/QDataStreamProxy.h +++ b/src/lib/gui/ipc/QDataStreamProxy.h @@ -21,14 +21,17 @@ /** * @brief Useful for overriding QDataStream. */ -class QDataStreamProxy { +class QDataStreamProxy +{ public: explicit QDataStreamProxy() = default; - explicit QDataStreamProxy(QTcpSocket *socket) - : m_Stream(std::make_unique(socket)) {} + explicit QDataStreamProxy(QTcpSocket *socket) : m_Stream(std::make_unique(socket)) + { + } virtual ~QDataStreamProxy() = default; - virtual qint64 writeRawData(const char *data, int len) { + virtual qint64 writeRawData(const char *data, int len) + { assert(m_Stream); return m_Stream->writeRawData(data, len); } diff --git a/src/lib/gui/ipc/QIpcClient.cpp b/src/lib/gui/ipc/QIpcClient.cpp index 8b05e7e45..d82504b3a 100644 --- a/src/lib/gui/ipc/QIpcClient.cpp +++ b/src/lib/gui/ipc/QIpcClient.cpp @@ -31,36 +31,33 @@ const auto kConnectTimeout = 5000; using namespace deskflow::gui; -QIpcClient::QIpcClient(const StreamProvider &streamProvider) - : m_streamProvider(streamProvider) { +QIpcClient::QIpcClient(const StreamProvider &streamProvider) : m_streamProvider(streamProvider) +{ m_pSocket = std::make_unique(); if (!m_streamProvider) { - m_streamProvider = [this]() { - return std::make_shared(m_pSocket.get()); - }; + m_streamProvider = [this]() { return std::make_shared(m_pSocket.get()); }; } - connect( - m_pSocket.get(), &QTcpSocket::connected, this, - &QIpcClient::onSocketConnected); - connect( - m_pSocket.get(), &QTcpSocket::errorOccurred, this, - &QIpcClient::onSocketError); + connect(m_pSocket.get(), &QTcpSocket::connected, this, &QIpcClient::onSocketConnected); + connect(m_pSocket.get(), &QTcpSocket::errorOccurred, this, &QIpcClient::onSocketError); m_pReader = std::make_unique(m_pSocket.get()); connect( m_pReader.get(), &IpcReader::read, this, // - &QIpcClient::onIpcReaderRead); - connect( - m_pReader.get(), &IpcReader::helloBack, this, - &QIpcClient::onIpcReaderHelloBack); + &QIpcClient::onIpcReaderRead + ); + connect(m_pReader.get(), &IpcReader::helloBack, this, &QIpcClient::onIpcReaderHelloBack); } -void QIpcClient::onSocketConnected() const { sendHello(); } +void QIpcClient::onSocketConnected() const +{ + sendHello(); +} -void QIpcClient::connectToHost() { +void QIpcClient::connectToHost() +{ m_isConnecting = true; qInfo("connecting to background service..."); const auto port = static_cast(kIpcPort); @@ -78,7 +75,8 @@ void QIpcClient::connectToHost() { }); } -void QIpcClient::disconnectFromHost() { +void QIpcClient::disconnectFromHost() +{ m_pReader->stop(); m_pSocket->flush(); m_pSocket->close(); @@ -89,7 +87,8 @@ void QIpcClient::disconnectFromHost() { qInfo("disconnected from background service"); } -void QIpcClient::onSocketError(QAbstractSocket::SocketError socketError) { +void QIpcClient::onSocketError(QAbstractSocket::SocketError socketError) +{ QString text; switch (socketError) { case 0: @@ -109,7 +108,8 @@ void QIpcClient::onSocketError(QAbstractSocket::SocketError socketError) { QTimer::singleShot(kRetryInterval, this, &QIpcClient::onRetryConnect); } -void QIpcClient::onRetryConnect() { +void QIpcClient::onRetryConnect() +{ if (m_isConnected) { qDebug("ipc already connected, skipping retry"); return; @@ -122,7 +122,8 @@ void QIpcClient::onRetryConnect() { connectToHost(); } -void QIpcClient::sendHello() const { +void QIpcClient::sendHello() const +{ qDebug("sending ipc hello message"); auto stream = m_streamProvider(); stream->writeRawData(kIpcMsgHello, 4); @@ -132,8 +133,8 @@ void QIpcClient::sendHello() const { stream->writeRawData(typeBuf, 1); } -void QIpcClient::sendCommand( - const QString &command, ElevateMode const elevate) const { +void QIpcClient::sendCommand(const QString &command, ElevateMode const elevate) const +{ qDebug("sending ipc command: %s", qUtf8Printable(command)); auto stream = m_streamProvider(); @@ -156,7 +157,8 @@ void QIpcClient::sendCommand( stream->writeRawData(elevateBuf, 1); } -void QIpcClient::onIpcReaderHelloBack() { +void QIpcClient::onIpcReaderHelloBack() +{ qDebug("ipc hello back received"); if (m_isConnected) { @@ -168,4 +170,7 @@ void QIpcClient::onIpcReaderHelloBack() { serviceReady(); } -void QIpcClient::onIpcReaderRead(const QString &text) { emit read(text); } +void QIpcClient::onIpcReaderRead(const QString &text) +{ + emit read(text); +} diff --git a/src/lib/gui/ipc/QIpcClient.h b/src/lib/gui/ipc/QIpcClient.h index 8268edebe..56f2ab5e4 100644 --- a/src/lib/gui/ipc/QIpcClient.h +++ b/src/lib/gui/ipc/QIpcClient.h @@ -30,7 +30,8 @@ class IpcReader; -class QIpcClient : public deskflow::gui::ipc::IQIpcClient { +class QIpcClient : public deskflow::gui::ipc::IQIpcClient +{ Q_OBJECT public: @@ -42,7 +43,10 @@ public: void sendCommand(const QString &command, ElevateMode elevate) const override; void connectToHost() override; void disconnectFromHost() override; - bool isConnected() const override { return m_isConnected; } + bool isConnected() const override + { + return m_isConnected; + } private slots: void onRetryConnect(); diff --git a/src/lib/gui/messages.cpp b/src/lib/gui/messages.cpp index 1620eb0ed..b8b2fb73e 100644 --- a/src/lib/gui/messages.cpp +++ b/src/lib/gui/messages.cpp @@ -34,7 +34,8 @@ namespace deskflow::gui::messages { -struct Errors { +struct Errors +{ static std::unique_ptr s_criticalMessage; static QStringList s_ignoredErrors; }; @@ -42,14 +43,15 @@ struct Errors { std::unique_ptr Errors::s_criticalMessage; QStringList Errors::s_ignoredErrors; -void raiseCriticalDialog() { +void raiseCriticalDialog() +{ if (Errors::s_criticalMessage) { Errors::s_criticalMessage->raise(); } } -void showErrorDialog( - const QString &message, const QString &fileLine, QtMsgType type) { +void showErrorDialog(const QString &message, const QString &fileLine, QtMsgType type) +{ auto title = type == QtFatalMsg ? "Fatal error" : "Critical error"; QString text; @@ -70,8 +72,7 @@ void showErrorDialog( if (type == QtFatalMsg) { // create a blocking message box for fatal errors, as we want to wait // until the dialog is dismissed before aborting the app. - QMessageBox critical( - QMessageBox::Critical, title, text, QMessageBox::Abort); + QMessageBox critical(QMessageBox::Critical, title, text, QMessageBox::Abort); critical.exec(); } else if (!Errors::s_ignoredErrors.contains(message)) { // prevent message boxes piling up by deleting the last one if it exists. @@ -82,9 +83,8 @@ void showErrorDialog( // message box. this is so that we don't block the message handler; if we // did, we would prevent new messages from being logged properly. // the memory will stay allocated until the app exits, which is acceptable. - Errors::s_criticalMessage = std::make_unique( - QMessageBox::Critical, title, text, - QMessageBox::Ok | QMessageBox::Ignore); + Errors::s_criticalMessage = + std::make_unique(QMessageBox::Critical, title, text, QMessageBox::Ok | QMessageBox::Ignore); Errors::s_criticalMessage->open(); @@ -94,19 +94,21 @@ void showErrorDialog( if (result == QMessageBox::Ignore) { Errors::s_ignoredErrors.append(message); } - }); + } + ); } } -QString fileLine(const QMessageLogContext &context) { +QString fileLine(const QMessageLogContext &context) +{ if (!context.file) { return ""; } return QString("%1:%2").arg(context.file).arg(context.line); } -void messageHandler( - QtMsgType type, const QMessageLogContext &context, const QString &message) { +void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &message) +{ const auto fileLine = messages::fileLine(context); Logger::instance().handleMessage(type, fileLine, message); @@ -128,14 +130,13 @@ void messageHandler( } } -void showCloseReminder(QWidget *parent) { - QString message = - QString( - "

%1 will continue to run in the background and can be accessed " - "via the %1 icon in your system notifications area. This " - "setting " - "can be disabled.

") - .arg(kAppName); +void showCloseReminder(QWidget *parent) +{ + QString message = QString("

%1 will continue to run in the background and can be accessed " + "via the %1 icon in your system notifications area. This " + "setting " + "can be disabled.

") + .arg(kAppName); #if defined(Q_OS_LINUX) message += QString("

On some Linux systems such as GNOME 3, the " @@ -149,49 +150,47 @@ void showCloseReminder(QWidget *parent) { QMessageBox::information(parent, "Notification area icon", message); } -void showFirstServerStartMessage(QWidget *parent) { +void showFirstServerStartMessage(QWidget *parent) +{ QMessageBox::information( parent, "Server is running", QString("

Great, the %1 server is now running.

" "

Now you can connect your client computers to this server. " "You should see a prompt here on the server when a new client " "tries to connect.

") - .arg(kAppName)); + .arg(kAppName) + ); } -void showFirstConnectedMessage( - QWidget *parent, bool closeToTray, bool enableService, bool isServer) { +void showFirstConnectedMessage(QWidget *parent, bool closeToTray, bool enableService, bool isServer) +{ auto message = QString("

%1 is now connected!

").arg(kAppName); if (isServer) { - message += - "

Try moving your mouse to your other computer. Once there, go ahead " - "and type something.

" - "

Don't forget, you can copy and paste between computers too.

"; + message += "

Try moving your mouse to your other computer. Once there, go ahead " + "and type something.

" + "

Don't forget, you can copy and paste between computers too.

"; } else { message += "

Try controlling this computer remotely.

"; } if (!closeToTray && !enableService) { - message += - QString( - "

As you do not have the setting enabled to keep %1 running in " - "the background, you'll need to keep this window open or minimized " - "to keep %1 running.

") - .arg(kAppName); + message += QString("

As you do not have the setting enabled to keep %1 running in " + "the background, you'll need to keep this window open or minimized " + "to keep %1 running.

") + .arg(kAppName); } else { - message += - QString( - "

You can now close this window and %1 will continue to run in " - "the background. This setting can be disabled.

") - .arg(kAppName); + message += QString("

You can now close this window and %1 will continue to run in " + "the background. This setting can be disabled.

") + .arg(kAppName); } QMessageBox::information(parent, "Connected", message); } -void showDevThanks(QWidget *parent, const QString &productName) { +void showDevThanks(QWidget *parent, const QString &productName) +{ if (productName.isEmpty()) { qFatal("product name not set"); } @@ -203,15 +202,15 @@ void showDevThanks(QWidget *parent, const QString &productName) { R"(

%2

)" "

Please report bugs and consider contributing code.

" "

This message will only appear once.

") - .arg(productName, kUrlApp, kColorSecondary)); + .arg(productName, kUrlApp, kColorSecondary) + ); } -void showClientConnectError( - QWidget *parent, ClientError error, const QString &address) { +void showClientConnectError(QWidget *parent, ClientError error, const QString &address) +{ using enum ClientError; - auto message = - QString("

The connection to server '%1' didn't work.

").arg(address); + auto message = QString("

The connection to server '%1' didn't work.

").arg(address); if (error == AlreadyConnected) { message += // @@ -238,17 +237,14 @@ void showClientConnectError( dialog.exec(); } -NewClientPromptResult -showNewClientPrompt(QWidget *parent, const QString &clientName) { +NewClientPromptResult showNewClientPrompt(QWidget *parent, const QString &clientName) +{ using enum NewClientPromptResult; QMessageBox message(parent); - const QPushButton *ignore = - message.addButton("Ignore", QMessageBox::RejectRole); - const QPushButton *add = - message.addButton("Add client", QMessageBox::AcceptRole); - message.setText( - QString("A new client called '%1' wants to connect").arg(clientName)); + const QPushButton *ignore = message.addButton("Ignore", QMessageBox::RejectRole); + const QPushButton *add = message.addButton("Add client", QMessageBox::AcceptRole); + message.setText(QString("A new client called '%1' wants to connect").arg(clientName)); message.exec(); if (message.clickedButton() == add) { @@ -261,55 +257,55 @@ showNewClientPrompt(QWidget *parent, const QString &clientName) { } } -bool showClearSettings(QWidget *parent) { +bool showClearSettings(QWidget *parent) +{ QMessageBox message(parent); message.addButton(QObject::tr("Cancel"), QMessageBox::RejectRole); - const auto clear = - message.addButton(QObject::tr("Clear settings"), QMessageBox::AcceptRole); - message.setText( - QString( - "

Are you sure you want to clear all settings and restart %1?

" - "

This action cannot be undone.

") - .arg(kAppName)); + const auto clear = message.addButton(QObject::tr("Clear settings"), QMessageBox::AcceptRole); + message.setText(QString("

Are you sure you want to clear all settings and restart %1?

" + "

This action cannot be undone.

") + .arg(kAppName)); message.exec(); return message.clickedButton() == clear; } -void showReadOnlySettings(QWidget *parent, const QString &systemSettingsPath) { +void showReadOnlySettings(QWidget *parent, const QString &systemSettingsPath) +{ QString nativePath = QDir::toNativeSeparators(systemSettingsPath); QMessageBox::information( parent, "Read-only settings", QString("

Settings are read-only because you only have read access " "to the file:

%1

") - .arg(nativePath)); + .arg(nativePath) + ); } -void showWaylandLibraryError(QWidget *parent) { +void showWaylandLibraryError(QWidget *parent) +{ QMessageBox::critical( parent, "Library problem", - QString( - "

Sorry, while this version of %1 does support Wayland, " - "this build was not linked with one or more of the required " - "libraries.

" - "

Please either switch to X from your login screen or use a build " - "that uses the correct libraries.

" - "

If you think this is incorrect, please " - R"(report a bug.

)" - "

Please check the logs for more information.

") - .arg(kAppName, kUrlHelp, kColorSecondary)); + QString("

Sorry, while this version of %1 does support Wayland, " + "this build was not linked with one or more of the required " + "libraries.

" + "

Please either switch to X from your login screen or use a build " + "that uses the correct libraries.

" + "

If you think this is incorrect, please " + R"(report a bug.

)" + "

Please check the logs for more information.

") + .arg(kAppName, kUrlHelp, kColorSecondary) + ); } -bool showUpdateCheckOption(QWidget *parent) { +bool showUpdateCheckOption(QWidget *parent) +{ QMessageBox message(parent); message.addButton(QObject::tr("No thanks"), QMessageBox::RejectRole); - const auto checkButton = message.addButton( - QObject::tr("Check for updates"), QMessageBox::AcceptRole); - message.setText( - QString("

Would you like to check for updates when %1 starts?

" - "

Checking for updates requires an Internet connection.

" - "

URL:

%2

") - .arg(kAppName, env_vars::versionUrl())); + const auto checkButton = message.addButton(QObject::tr("Check for updates"), QMessageBox::AcceptRole); + message.setText(QString("

Would you like to check for updates when %1 starts?

" + "

Checking for updates requires an Internet connection.

" + "

URL:

%2

") + .arg(kAppName, env_vars::versionUrl())); message.exec(); return message.clickedButton() == checkButton; diff --git a/src/lib/gui/messages.h b/src/lib/gui/messages.h index 15cd0fd62..6e2bf0b07 100644 --- a/src/lib/gui/messages.h +++ b/src/lib/gui/messages.h @@ -24,29 +24,34 @@ class QWidget; namespace deskflow::gui::messages { -enum class ClientError { AlreadyConnected, HostnameError, GenericError }; +enum class ClientError +{ + AlreadyConnected, + HostnameError, + GenericError +}; -enum class NewClientPromptResult { Add, Ignore }; +enum class NewClientPromptResult +{ + Add, + Ignore +}; -void messageHandler( - QtMsgType type, const QMessageLogContext &context, const QString &msg); +void messageHandler(QtMsgType type, const QMessageLogContext &context, const QString &msg); void raiseCriticalDialog(); void showFirstServerStartMessage(QWidget *parent); -void showFirstConnectedMessage( - QWidget *parent, bool closeToTray, bool enableService, bool isServer); +void showFirstConnectedMessage(QWidget *parent, bool closeToTray, bool enableService, bool isServer); void showCloseReminder(QWidget *parent); void showDevThanks(QWidget *parent, const QString &productName); -void showClientConnectError( - QWidget *parent, ClientError error, const QString &address); +void showClientConnectError(QWidget *parent, ClientError error, const QString &address); -NewClientPromptResult -showNewClientPrompt(QWidget *parent, const QString &clientName); +NewClientPromptResult showNewClientPrompt(QWidget *parent, const QString &clientName); bool showClearSettings(QWidget *parent); diff --git a/src/lib/gui/paths.h b/src/lib/gui/paths.h index cfcb79aa6..1b59a3fb5 100644 --- a/src/lib/gui/paths.h +++ b/src/lib/gui/paths.h @@ -32,9 +32,9 @@ namespace deskflow::gui::paths { /** * @brief Gets the org config dir (parent of app config dir). */ -inline QDir configDir(const bool persist = false) { - const QDir configDir( - QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)); +inline QDir configDir(const bool persist = false) +{ + const QDir configDir(QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation)); // HACK: since we have the org name set to the app name, the config dir is // confusing. make this simple by using the org dir instead. @@ -54,12 +54,14 @@ inline QDir configDir(const bool persist = false) { /** * @brief Uses the Core tool to get the profile dir. */ -inline QDir coreProfileDir() { +inline QDir coreProfileDir() +{ CoreTool coreTool; return QDir(coreTool.getProfileDir()); } -inline QString defaultTlsCertPath() { +inline QString defaultTlsCertPath() +{ const auto root = coreProfileDir(); const auto sslDirPath = QDir(root.filePath(kSslDir)); return sslDirPath.filePath(kCertificateFilename); diff --git a/src/lib/gui/proxy/QNetworkAccessManagerProxy.cpp b/src/lib/gui/proxy/QNetworkAccessManagerProxy.cpp index d49086ac3..99a237f1f 100644 --- a/src/lib/gui/proxy/QNetworkAccessManagerProxy.cpp +++ b/src/lib/gui/proxy/QNetworkAccessManagerProxy.cpp @@ -22,15 +22,17 @@ namespace deskflow::gui::proxy { -void QNetworkAccessManagerProxy::init() { +void QNetworkAccessManagerProxy::init() +{ m_network = std::make_shared(); - connect( - m_network.get(), &QNetworkAccessManager::finished, this, - [this](QNetworkReply *reply) { emit finished(reply); }); + connect(m_network.get(), &QNetworkAccessManager::finished, this, [this](QNetworkReply *reply) { + emit finished(reply); + }); } -void QNetworkAccessManagerProxy::get(const QNetworkRequest &request) const { +void QNetworkAccessManagerProxy::get(const QNetworkRequest &request) const +{ m_network->get(request); } diff --git a/src/lib/gui/proxy/QNetworkAccessManagerProxy.h b/src/lib/gui/proxy/QNetworkAccessManagerProxy.h index 78df4c938..eeb038e80 100644 --- a/src/lib/gui/proxy/QNetworkAccessManagerProxy.h +++ b/src/lib/gui/proxy/QNetworkAccessManagerProxy.h @@ -22,7 +22,8 @@ namespace deskflow::gui::proxy { -class QNetworkAccessManagerProxy : public QObject { +class QNetworkAccessManagerProxy : public QObject +{ Q_OBJECT public: diff --git a/src/lib/gui/proxy/QProcessProxy.cpp b/src/lib/gui/proxy/QProcessProxy.cpp index e99da4c7d..a0b96b271 100644 --- a/src/lib/gui/proxy/QProcessProxy.cpp +++ b/src/lib/gui/proxy/QProcessProxy.cpp @@ -19,44 +19,57 @@ namespace deskflow::gui::proxy { -void QProcessProxy::create() { +void QProcessProxy::create() +{ m_pProcess = std::make_unique(); - connect( - m_pProcess.get(), &QProcess::finished, this, - [this](int exitCode, QProcess::ExitStatus exitStatus) { - emit finished(exitCode, exitStatus); - }); + connect(m_pProcess.get(), &QProcess::finished, this, [this](int exitCode, QProcess::ExitStatus exitStatus) { + emit finished(exitCode, exitStatus); + }); connect( m_pProcess.get(), &QProcess::readyReadStandardOutput, // - this, [this]() { emit readyReadStandardOutput(); }); + this, [this]() { emit readyReadStandardOutput(); } + ); connect( m_pProcess.get(), &QProcess::readyReadStandardError, // - this, [this]() { emit readyReadStandardError(); }); + this, [this]() { emit readyReadStandardError(); } + ); } -QProcessProxy::operator bool() const { return m_pProcess.get(); } +QProcessProxy::operator bool() const +{ + return m_pProcess.get(); +} -void QProcessProxy::start( - const QString &program, const QStringList &arguments) { +void QProcessProxy::start(const QString &program, const QStringList &arguments) +{ m_pProcess->start(program, arguments); } -bool QProcessProxy::waitForStarted() { return m_pProcess->waitForStarted(); } +bool QProcessProxy::waitForStarted() +{ + return m_pProcess->waitForStarted(); +} -QProcess::ProcessState QProcessProxy::state() const { +QProcess::ProcessState QProcessProxy::state() const +{ return m_pProcess->state(); } -void QProcessProxy::close() { m_pProcess->close(); } +void QProcessProxy::close() +{ + m_pProcess->close(); +} -QString QProcessProxy::readAllStandardOutput() { +QString QProcessProxy::readAllStandardOutput() +{ return m_pProcess->readAllStandardOutput(); } -QString QProcessProxy::readAllStandardError() { +QString QProcessProxy::readAllStandardError() +{ return m_pProcess->readAllStandardError(); } diff --git a/src/lib/gui/proxy/QProcessProxy.h b/src/lib/gui/proxy/QProcessProxy.h index 8ef1170e5..1be769161 100644 --- a/src/lib/gui/proxy/QProcessProxy.h +++ b/src/lib/gui/proxy/QProcessProxy.h @@ -22,7 +22,8 @@ namespace deskflow::gui::proxy { -class QProcessProxy : public QObject { +class QProcessProxy : public QObject +{ Q_OBJECT public: diff --git a/src/lib/gui/proxy/QSettingsProxy.cpp b/src/lib/gui/proxy/QSettingsProxy.cpp index 7602d9700..3f79b3568 100644 --- a/src/lib/gui/proxy/QSettingsProxy.cpp +++ b/src/lib/gui/proxy/QSettingsProxy.cpp @@ -45,7 +45,8 @@ const auto kUnixSystemConfigPath = "/usr/local/etc/"; * Important: Qt will append the org name as a dir, and the app name as the * settings filename, i.e.: `{base-dir}/Deskflow/Deskflow.ini` */ -QString getSystemSettingsBaseDir() { +QString getSystemSettingsBaseDir() +{ #if defined(Q_OS_WIN) return QCoreApplication::applicationDirPath(); #elif defined(Q_OS_UNIX) @@ -58,19 +59,18 @@ QString getSystemSettingsBaseDir() { #endif } -void migrateLegacySystemSettings(QSettings &settings) { +void migrateLegacySystemSettings(QSettings &settings) +{ if (QFile(settings.fileName()).exists()) { qDebug("system settings already exist, skipping migration"); return; } - QSettings::setPath( - QSettings::IniFormat, QSettings::SystemScope, - kLegacySystemConfigFilename); + QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope, kLegacySystemConfigFilename); QSettings oldSystemSettings( - QSettings::IniFormat, QSettings::SystemScope, - QCoreApplication::organizationName(), - QCoreApplication::applicationName()); + QSettings::IniFormat, QSettings::SystemScope, QCoreApplication::organizationName(), + QCoreApplication::applicationName() + ); if (QFile(oldSystemSettings.fileName()).exists()) { for (const auto &key : oldSystemSettings.allKeys()) { @@ -78,11 +78,11 @@ void migrateLegacySystemSettings(QSettings &settings) { } } - QSettings::setPath( - QSettings::IniFormat, QSettings::SystemScope, getSystemSettingsBaseDir()); + QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope, getSystemSettingsBaseDir()); } -void migrateLegacyUserSettings(QSettings &newSettings) { +void migrateLegacyUserSettings(QSettings &newSettings) +{ QString newPath = newSettings.fileName(); QFile newFile(newPath); if (newFile.exists()) { @@ -108,14 +108,14 @@ void migrateLegacyUserSettings(QSettings &newSettings) { qDebug( "migrating legacy settings: '%s' -> '%s'", // - qPrintable(oldFileInfo.fileName()), qPrintable(newFileInfo.fileName())); + qPrintable(oldFileInfo.fileName()), qPrintable(newFileInfo.fileName()) + ); QStringList keys = oldSettings.allKeys(); for (const QString &key : keys) { QVariant oldValue = oldSettings.value(key); newSettings.setValue(key, oldValue); - logVerbose( - QString("migrating setting '%1' = '%2'").arg(key, oldValue.toString())); + logVerbose(QString("migrating setting '%1' = '%2'").arg(key, oldValue.toString())); } newSettings.sync(); @@ -125,7 +125,8 @@ void migrateLegacyUserSettings(QSettings &newSettings) { // QSettingsProxy // -void QSettingsProxy::loadUser() { +void QSettingsProxy::loadUser() +{ m_pSettings = std::make_unique(); #if defined(Q_OS_MAC) @@ -136,7 +137,8 @@ void QSettingsProxy::loadUser() { #endif // Q_OS_MAC } -void QSettingsProxy::loadSystem() { +void QSettingsProxy::loadSystem() +{ auto orgName = QCoreApplication::organizationName(); if (orgName.isEmpty()) { qFatal("unable to load config, organization name is empty"); @@ -153,55 +155,73 @@ void QSettingsProxy::loadSystem() { qDebug() << "app name for config:" << appName; } - QSettings::setPath( - QSettings::Format::IniFormat, QSettings::Scope::SystemScope, - getSystemSettingsBaseDir()); + QSettings::setPath(QSettings::Format::IniFormat, QSettings::Scope::SystemScope, getSystemSettingsBaseDir()); - m_pSettings = std::make_unique( - QSettings::Format::IniFormat, QSettings::Scope::SystemScope, orgName, - appName); + m_pSettings = + std::make_unique(QSettings::Format::IniFormat, QSettings::Scope::SystemScope, orgName, appName); #if defined(Q_OS_WIN) migrateLegacySystemSettings(*m_pSettings); #endif // Q_OS_WIN } -int QSettingsProxy::beginReadArray(const QString &prefix) { +int QSettingsProxy::beginReadArray(const QString &prefix) +{ return m_pSettings->beginReadArray(prefix); } -void QSettingsProxy::setArrayIndex(int i) { m_pSettings->setArrayIndex(i); } +void QSettingsProxy::setArrayIndex(int i) +{ + m_pSettings->setArrayIndex(i); +} -QVariant QSettingsProxy::value(const QString &key) const { +QVariant QSettingsProxy::value(const QString &key) const +{ return m_pSettings->value(key); } -QVariant -QSettingsProxy::value(const QString &key, const QVariant &defaultValue) const { +QVariant QSettingsProxy::value(const QString &key, const QVariant &defaultValue) const +{ return m_pSettings->value(key, defaultValue); } -void QSettingsProxy::endArray() { m_pSettings->endArray(); } +void QSettingsProxy::endArray() +{ + m_pSettings->endArray(); +} -void QSettingsProxy::beginWriteArray(const QString &prefix) { +void QSettingsProxy::beginWriteArray(const QString &prefix) +{ m_pSettings->beginWriteArray(prefix); } -void QSettingsProxy::setValue(const QString &key, const QVariant &value) { +void QSettingsProxy::setValue(const QString &key, const QVariant &value) +{ m_pSettings->setValue(key, value); } -void QSettingsProxy::beginGroup(const QString &prefix) { +void QSettingsProxy::beginGroup(const QString &prefix) +{ m_pSettings->beginGroup(prefix); } -void QSettingsProxy::remove(const QString &key) { m_pSettings->remove(key); } +void QSettingsProxy::remove(const QString &key) +{ + m_pSettings->remove(key); +} -void QSettingsProxy::endGroup() { m_pSettings->endGroup(); } +void QSettingsProxy::endGroup() +{ + m_pSettings->endGroup(); +} -bool QSettingsProxy::isWritable() const { return m_pSettings->isWritable(); } +bool QSettingsProxy::isWritable() const +{ + return m_pSettings->isWritable(); +} -bool QSettingsProxy::contains(const QString &key) const { +bool QSettingsProxy::contains(const QString &key) const +{ return m_pSettings->contains(key); } diff --git a/src/lib/gui/proxy/QSettingsProxy.h b/src/lib/gui/proxy/QSettingsProxy.h index e59060551..ca8b58f25 100644 --- a/src/lib/gui/proxy/QSettingsProxy.h +++ b/src/lib/gui/proxy/QSettingsProxy.h @@ -23,20 +23,26 @@ namespace deskflow::gui::proxy { QString getSystemSettingBaseDir(); -class QSettingsProxy { +class QSettingsProxy +{ public: virtual ~QSettingsProxy() = default; virtual void loadUser(); virtual void loadSystem(); - virtual void clear() { m_pSettings->clear(); } - virtual void sync() { m_pSettings->sync(); } + virtual void clear() + { + m_pSettings->clear(); + } + virtual void sync() + { + m_pSettings->sync(); + } virtual int beginReadArray(const QString &prefix); virtual void beginWriteArray(const QString &prefix); virtual void setArrayIndex(int i); virtual QVariant value(const QString &key) const; - virtual QVariant - value(const QString &key, const QVariant &defaultValue) const; + virtual QVariant value(const QString &key, const QVariant &defaultValue) const; virtual void endArray(); virtual void setValue(const QString &key, const QVariant &value); virtual void beginGroup(const QString &prefix); @@ -44,9 +50,15 @@ public: virtual void remove(const QString &key); virtual bool isWritable() const; virtual bool contains(const QString &key) const; - virtual QString fileName() const { return m_pSettings->fileName(); } + virtual QString fileName() const + { + return m_pSettings->fileName(); + } - QSettings &get() const { return *m_pSettings; } + QSettings &get() const + { + return *m_pSettings; + } private: std::unique_ptr m_pSettings; diff --git a/src/lib/gui/string_utils.h b/src/lib/gui/string_utils.h index 5d6d52e77..0defda5b6 100644 --- a/src/lib/gui/string_utils.h +++ b/src/lib/gui/string_utils.h @@ -22,11 +22,13 @@ /** * @brief Useful for environment variables that have string boolean values. */ -inline bool strToTrue(const QString &str) { +inline bool strToTrue(const QString &str) +{ return str.toLower() == "true" || str == "1"; } -inline QString trimEnd(const QString &str) { +inline QString trimEnd(const QString &str) +{ QString result = str; while (!result.isEmpty() && result.at(result.size() - 1).isSpace()) { result.chop(1); diff --git a/src/lib/gui/style_utils.h b/src/lib/gui/style_utils.h index 4d9c5407c..a9c2d4e99 100644 --- a/src/lib/gui/style_utils.h +++ b/src/lib/gui/style_utils.h @@ -27,7 +27,8 @@ namespace deskflow::gui { * @brief Detects dark mode depending on Qt version. * https://www.qt.io/blog/dark-mode-on-windows-11-with-qt-6.5 */ -inline bool isDarkMode() { +inline bool isDarkMode() +{ #if QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) const auto scheme = QGuiApplication::styleHints()->colorScheme(); return scheme == Qt::ColorScheme::Dark; diff --git a/src/lib/gui/styles.h b/src/lib/gui/styles.h index 27c610acf..3757e444e 100644 --- a/src/lib/gui/styles.h +++ b/src/lib/gui/styles.h @@ -33,8 +33,7 @@ const auto kStyleLink = // QString("color: %1").arg(kColorSecondary); const auto kStyleLineEditErrorBorder = - QString("border: 1px solid %1; border-radius: 2px; padding: 2px;") - .arg(kColorError); + QString("border: 1px solid %1; border-radius: 2px; padding: 2px;").arg(kColorError); const auto kStyleErrorActiveLabel = // QString("padding: 3px 5px; border-radius: 3px; " diff --git a/src/lib/gui/tls/TlsCertificate.cpp b/src/lib/gui/tls/TlsCertificate.cpp index 115ddd872..00373b2e7 100644 --- a/src/lib/gui/tls/TlsCertificate.cpp +++ b/src/lib/gui/tls/TlsCertificate.cpp @@ -40,7 +40,8 @@ static const char *const kUnixOpenSslCommand = "openssl"; namespace deskflow::gui { -QString openSslWindowsDir() { +QString openSslWindowsDir() +{ auto appDir = QDir(QCoreApplication::applicationDirPath()); auto openSslDir = QDir(appDir.filePath(kWinOpenSslDir)); @@ -62,7 +63,8 @@ QString openSslWindowsDir() { return QDir::cleanPath(path); } -QString openSslWindowsBinary() { +QString openSslWindowsBinary() +{ auto dir = QDir(openSslWindowsDir()); auto path = dir.filePath(kWinOpenSslBinary); @@ -87,9 +89,12 @@ using namespace deskflow::gui; #endif -TlsCertificate::TlsCertificate(QObject *parent) : QObject(parent) {} +TlsCertificate::TlsCertificate(QObject *parent) : QObject(parent) +{ +} -bool TlsCertificate::runTool(const QStringList &args) { +bool TlsCertificate::runTool(const QStringList &args) +{ #if defined(Q_OS_WIN) const auto program = openSslWindowsBinary(); #else @@ -115,9 +120,7 @@ bool TlsCertificate::runTool(const QStringList &args) { qDebug("set env var: %s", qUtf8Printable(envVar)); } - qDebug( - "running: %s %s", qUtf8Printable(program), - qUtf8Printable(args.join(" "))); + qDebug("running: %s %s", qUtf8Printable(program), qUtf8Printable(args.join(" "))); process.start(program, args); bool success = process.waitForStarted(); @@ -130,16 +133,15 @@ bool TlsCertificate::runTool(const QStringList &args) { if (int code = process.exitCode(); !success || code != 0) { qDebug("openssl failed with code %d: %s", code, qUtf8Printable(toolStderr)); - qCritical( - "failed to generate tls certificate:\n\n%s", - qUtf8Printable(toolStderr)); + qCritical("failed to generate tls certificate:\n\n%s", qUtf8Printable(toolStderr)); return false; } return true; } -bool TlsCertificate::generateCertificate(const QString &path, int keyLength) { +bool TlsCertificate::generateCertificate(const QString &path, int keyLength) +{ qDebug("generating tls certificate: %s", qUtf8Printable(path)); QFileInfo info(path); @@ -190,7 +192,8 @@ bool TlsCertificate::generateCertificate(const QString &path, int keyLength) { } } -bool TlsCertificate::generateFingerprint(const QString &certificateFilename) { +bool TlsCertificate::generateFingerprint(const QString &certificateFilename) +{ qDebug("generating tls fingerprint"); QStringList arguments; @@ -221,7 +224,8 @@ bool TlsCertificate::generateFingerprint(const QString &certificateFilename) { } } -int TlsCertificate::getCertKeyLength(const QString &path) { +int TlsCertificate::getCertKeyLength(const QString &path) +{ QStringList arguments; arguments.append("rsa"); diff --git a/src/lib/gui/tls/TlsCertificate.h b/src/lib/gui/tls/TlsCertificate.h index 27a0913c5..2b427ccc0 100644 --- a/src/lib/gui/tls/TlsCertificate.h +++ b/src/lib/gui/tls/TlsCertificate.h @@ -21,7 +21,8 @@ #include -class TlsCertificate : public QObject { +class TlsCertificate : public QObject +{ Q_OBJECT public: diff --git a/src/lib/gui/tls/TlsFingerprint.cpp b/src/lib/gui/tls/TlsFingerprint.cpp index 0592a2266..9f485d05f 100644 --- a/src/lib/gui/tls/TlsFingerprint.cpp +++ b/src/lib/gui/tls/TlsFingerprint.cpp @@ -28,10 +28,12 @@ static const char kLocalFilename[] = "local-fingerprint"; static const char kTrustedServersFilename[] = "trusted-servers"; static const char kTrustedClientsFilename[] = "trusted-clients"; -TlsFingerprint::TlsFingerprint(const QString &filename) - : m_Filename(filename) {} +TlsFingerprint::TlsFingerprint(const QString &filename) : m_Filename(filename) +{ +} -void TlsFingerprint::trust(const QString &fingerprintText, bool append) const { +void TlsFingerprint::trust(const QString &fingerprintText, bool append) const +{ TlsFingerprint::persistDirectory(); QIODevice::OpenMode openMode; @@ -49,7 +51,8 @@ void TlsFingerprint::trust(const QString &fingerprintText, bool append) const { } } -bool TlsFingerprint::fileExists() const { +bool TlsFingerprint::fileExists() const +{ QString dirName = TlsFingerprint::directoryPath(); if (!QDir(dirName).exists()) { return false; @@ -59,7 +62,8 @@ bool TlsFingerprint::fileExists() const { return file.exists(); } -bool TlsFingerprint::isTrusted(const QString &fingerprintText) const { +bool TlsFingerprint::isTrusted(const QString &fingerprintText) const +{ QStringList list = readList(); foreach (QString trusted, list) { if (trusted == fingerprintText) { @@ -69,7 +73,8 @@ bool TlsFingerprint::isTrusted(const QString &fingerprintText) const { return false; } -QStringList TlsFingerprint::readList(const int readTo) const { +QStringList TlsFingerprint::readList(const int readTo) const +{ QStringList list; QString dirName = TlsFingerprint::directoryPath(); @@ -93,38 +98,45 @@ QStringList TlsFingerprint::readList(const int readTo) const { return list; } -QString TlsFingerprint::readFirst() const { +QString TlsFingerprint::readFirst() const +{ QStringList list = readList(1); return list.at(0); } -QString TlsFingerprint::filePath() const { +QString TlsFingerprint::filePath() const +{ QString dir = TlsFingerprint::directoryPath(); return QString("%1/%2").arg(dir).arg(m_Filename); } -void TlsFingerprint::persistDirectory() { +void TlsFingerprint::persistDirectory() +{ QDir dir(TlsFingerprint::directoryPath()); if (!dir.exists()) { dir.mkpath("."); } } -QString TlsFingerprint::directoryPath() { +QString TlsFingerprint::directoryPath() +{ CoreTool coreTool; QString profileDir = coreTool.getProfileDir(); return QString("%1/%2").arg(profileDir).arg(kDirName); } -TlsFingerprint TlsFingerprint::local() { +TlsFingerprint TlsFingerprint::local() +{ return TlsFingerprint(kLocalFilename); } -TlsFingerprint TlsFingerprint::trustedServers() { +TlsFingerprint TlsFingerprint::trustedServers() +{ return TlsFingerprint(kTrustedServersFilename); } -TlsFingerprint TlsFingerprint::trustedClients() { +TlsFingerprint TlsFingerprint::trustedClients() +{ return TlsFingerprint(kTrustedClientsFilename); } diff --git a/src/lib/gui/tls/TlsFingerprint.h b/src/lib/gui/tls/TlsFingerprint.h index 6ca294966..1843ddf43 100644 --- a/src/lib/gui/tls/TlsFingerprint.h +++ b/src/lib/gui/tls/TlsFingerprint.h @@ -19,7 +19,8 @@ #include -class TlsFingerprint { +class TlsFingerprint +{ private: explicit TlsFingerprint(const QString &filename); diff --git a/src/lib/gui/tls/TlsUtility.cpp b/src/lib/gui/tls/TlsUtility.cpp index c2ff57375..3ca8299b2 100644 --- a/src/lib/gui/tls/TlsUtility.cpp +++ b/src/lib/gui/tls/TlsUtility.cpp @@ -24,14 +24,18 @@ namespace deskflow::gui { -TlsUtility::TlsUtility(const IAppConfig &appConfig) : m_appConfig(appConfig) {} +TlsUtility::TlsUtility(const IAppConfig &appConfig) : m_appConfig(appConfig) +{ +} -bool TlsUtility::isEnabled() const { +bool TlsUtility::isEnabled() const +{ const auto &config = m_appConfig; return config.tlsEnabled(); } -bool TlsUtility::generateCertificate() { +bool TlsUtility::generateCertificate() +{ qDebug("generating tls certificate, " "all clients must trust the new fingerprint"); @@ -46,7 +50,8 @@ bool TlsUtility::generateCertificate() { return m_certificate.generateCertificate(m_appConfig.tlsCertPath(), length); } -bool TlsUtility::persistCertificate() { +bool TlsUtility::persistCertificate() +{ qDebug("persisting tls certificate"); if (QFile::exists(m_appConfig.tlsCertPath())) { diff --git a/src/lib/gui/tls/TlsUtility.h b/src/lib/gui/tls/TlsUtility.h index 6619dfcb3..622085991 100644 --- a/src/lib/gui/tls/TlsUtility.h +++ b/src/lib/gui/tls/TlsUtility.h @@ -25,7 +25,8 @@ namespace deskflow::gui { -class TlsUtility : public QObject { +class TlsUtility : public QObject +{ Q_OBJECT public: diff --git a/src/lib/gui/validators/AliasValidator.cpp b/src/lib/gui/validators/AliasValidator.cpp index 1193e08a8..5c7921dc1 100644 --- a/src/lib/gui/validators/AliasValidator.cpp +++ b/src/lib/gui/validators/AliasValidator.cpp @@ -24,12 +24,10 @@ namespace validators { -AliasValidator::AliasValidator(QLineEdit *parent, ValidationError *error) - : LineEditValidator(parent, error) { - addValidator( - std::make_unique("Computer name cannot contain spaces")); - addValidator(std::make_unique( - "Contains invalid characters or is too long")); +AliasValidator::AliasValidator(QLineEdit *parent, ValidationError *error) : LineEditValidator(parent, error) +{ + addValidator(std::make_unique("Computer name cannot contain spaces")); + addValidator(std::make_unique("Contains invalid characters or is too long")); } } // namespace validators diff --git a/src/lib/gui/validators/AliasValidator.h b/src/lib/gui/validators/AliasValidator.h index c7323ba00..c76cc8437 100644 --- a/src/lib/gui/validators/AliasValidator.h +++ b/src/lib/gui/validators/AliasValidator.h @@ -22,10 +22,10 @@ namespace validators { -class AliasValidator : public LineEditValidator { +class AliasValidator : public LineEditValidator +{ public: - explicit AliasValidator( - QLineEdit *parent = nullptr, ValidationError *error = nullptr); + explicit AliasValidator(QLineEdit *parent = nullptr, ValidationError *error = nullptr); }; } // namespace validators diff --git a/src/lib/gui/validators/ComputerNameValidator.cpp b/src/lib/gui/validators/ComputerNameValidator.cpp index 92a3a594b..3410c7672 100644 --- a/src/lib/gui/validators/ComputerNameValidator.cpp +++ b/src/lib/gui/validators/ComputerNameValidator.cpp @@ -21,12 +21,13 @@ namespace validators { -ComputerNameValidator::ComputerNameValidator(const QString &message) - : IStringValidator(message) {} +ComputerNameValidator::ComputerNameValidator(const QString &message) : IStringValidator(message) +{ +} -bool ComputerNameValidator::validate(const QString &input) const { - const QRegularExpression re( - "^[\\w\\._-]{0,255}$", QRegularExpression::CaseInsensitiveOption); +bool ComputerNameValidator::validate(const QString &input) const +{ + const QRegularExpression re("^[\\w\\._-]{0,255}$", QRegularExpression::CaseInsensitiveOption); auto match = re.match(input); auto result = match.hasMatch(); return result; diff --git a/src/lib/gui/validators/ComputerNameValidator.h b/src/lib/gui/validators/ComputerNameValidator.h index 6f38fc11a..a8b66201b 100644 --- a/src/lib/gui/validators/ComputerNameValidator.h +++ b/src/lib/gui/validators/ComputerNameValidator.h @@ -23,7 +23,8 @@ namespace validators { -class ComputerNameValidator : public IStringValidator { +class ComputerNameValidator : public IStringValidator +{ public: explicit ComputerNameValidator(const QString &message); bool validate(const QString &input) const override; diff --git a/src/lib/gui/validators/EmptyStringValidator.cpp b/src/lib/gui/validators/EmptyStringValidator.cpp index c84fbeea2..8aa5c634e 100644 --- a/src/lib/gui/validators/EmptyStringValidator.cpp +++ b/src/lib/gui/validators/EmptyStringValidator.cpp @@ -19,10 +19,12 @@ namespace validators { -EmptyStringValidator::EmptyStringValidator(const QString &message) - : IStringValidator(message) {} +EmptyStringValidator::EmptyStringValidator(const QString &message) : IStringValidator(message) +{ +} -bool EmptyStringValidator::validate(const QString &input) const { +bool EmptyStringValidator::validate(const QString &input) const +{ return !input.isEmpty(); } diff --git a/src/lib/gui/validators/EmptyStringValidator.h b/src/lib/gui/validators/EmptyStringValidator.h index 238588e36..ec32a2d06 100644 --- a/src/lib/gui/validators/EmptyStringValidator.h +++ b/src/lib/gui/validators/EmptyStringValidator.h @@ -21,7 +21,8 @@ namespace validators { -class EmptyStringValidator : public IStringValidator { +class EmptyStringValidator : public IStringValidator +{ public: explicit EmptyStringValidator(const QString &message); bool validate(const QString &input) const override; diff --git a/src/lib/gui/validators/IStringValidator.cpp b/src/lib/gui/validators/IStringValidator.cpp index d98051fa7..5fc2a9b82 100644 --- a/src/lib/gui/validators/IStringValidator.cpp +++ b/src/lib/gui/validators/IStringValidator.cpp @@ -19,9 +19,13 @@ namespace validators { -IStringValidator::IStringValidator(const QString &message) - : m_Message(message) {} +IStringValidator::IStringValidator(const QString &message) : m_Message(message) +{ +} -const QString &IStringValidator::getMessage() const { return m_Message; } +const QString &IStringValidator::getMessage() const +{ + return m_Message; +} } // namespace validators diff --git a/src/lib/gui/validators/IStringValidator.h b/src/lib/gui/validators/IStringValidator.h index 3f35833ab..87c78b5f5 100644 --- a/src/lib/gui/validators/IStringValidator.h +++ b/src/lib/gui/validators/IStringValidator.h @@ -21,7 +21,8 @@ namespace validators { -class IStringValidator { +class IStringValidator +{ QString m_Message; public: diff --git a/src/lib/gui/validators/LineEditValidator.cpp b/src/lib/gui/validators/LineEditValidator.cpp index c8cf69eba..e405163e4 100644 --- a/src/lib/gui/validators/LineEditValidator.cpp +++ b/src/lib/gui/validators/LineEditValidator.cpp @@ -25,22 +25,23 @@ using namespace deskflow::gui; namespace validators { -LineEditValidator::LineEditValidator( - QLineEdit *lineEdit, ValidationError *error) +LineEditValidator::LineEditValidator(QLineEdit *lineEdit, ValidationError *error) : m_pError(error), - m_pLineEdit(lineEdit) { + m_pLineEdit(lineEdit) +{ if (!m_pLineEdit) { qFatal("validator line edit not set"); } } -void LineEditValidator::addValidator( - std::unique_ptr validator) { +void LineEditValidator::addValidator(std::unique_ptr validator) +{ m_Validators.push_back(std::move(validator)); } -QValidator::State LineEditValidator::validate(QString &input, int &pos) const { +QValidator::State LineEditValidator::validate(QString &input, int &pos) const +{ assert(m_pLineEdit); QString errorMessage; diff --git a/src/lib/gui/validators/LineEditValidator.h b/src/lib/gui/validators/LineEditValidator.h index 4d4c999bb..d156a2b00 100644 --- a/src/lib/gui/validators/LineEditValidator.h +++ b/src/lib/gui/validators/LineEditValidator.h @@ -29,10 +29,10 @@ namespace validators { -class LineEditValidator : public QValidator { +class LineEditValidator : public QValidator +{ public: - explicit LineEditValidator( - QLineEdit *lineEdit = nullptr, ValidationError *error = nullptr); + explicit LineEditValidator(QLineEdit *lineEdit = nullptr, ValidationError *error = nullptr); QValidator::State validate(QString &input, int &pos) const override; void addValidator(std::unique_ptr validator); diff --git a/src/lib/gui/validators/ScreenDuplicationsValidator.cpp b/src/lib/gui/validators/ScreenDuplicationsValidator.cpp index 67d0ec350..2849a6ebd 100644 --- a/src/lib/gui/validators/ScreenDuplicationsValidator.cpp +++ b/src/lib/gui/validators/ScreenDuplicationsValidator.cpp @@ -20,19 +20,21 @@ namespace validators { ScreenDuplicationsValidator::ScreenDuplicationsValidator( - const QString &message, const QString &defaultName, - const ScreenList *pScreens) + const QString &message, const QString &defaultName, const ScreenList *pScreens +) : IStringValidator(message), m_defaultName(defaultName), - m_pScreenList(pScreens) {} + m_pScreenList(pScreens) +{ +} -bool ScreenDuplicationsValidator::validate(const QString &input) const { +bool ScreenDuplicationsValidator::validate(const QString &input) const +{ bool result = true; if (m_pScreenList) { for (const auto &screen : (*m_pScreenList)) { - if (!screen.isNull() && !screen.isServer() && input != m_defaultName && - input == screen.name()) { + if (!screen.isNull() && !screen.isServer() && input != m_defaultName && input == screen.name()) { result = false; break; } diff --git a/src/lib/gui/validators/ScreenDuplicationsValidator.h b/src/lib/gui/validators/ScreenDuplicationsValidator.h index e3d1867c6..cbae2ce24 100644 --- a/src/lib/gui/validators/ScreenDuplicationsValidator.h +++ b/src/lib/gui/validators/ScreenDuplicationsValidator.h @@ -23,14 +23,13 @@ namespace validators { -class ScreenDuplicationsValidator : public IStringValidator { +class ScreenDuplicationsValidator : public IStringValidator +{ const QString m_defaultName; const ScreenList *m_pScreenList = nullptr; public: - ScreenDuplicationsValidator( - const QString &message, const QString &defaultName, - const ScreenList *pScreens); + ScreenDuplicationsValidator(const QString &message, const QString &defaultName, const ScreenList *pScreens); bool validate(const QString &input) const override; }; diff --git a/src/lib/gui/validators/ScreenNameValidator.cpp b/src/lib/gui/validators/ScreenNameValidator.cpp index 402a1c88d..f42c98914 100644 --- a/src/lib/gui/validators/ScreenNameValidator.cpp +++ b/src/lib/gui/validators/ScreenNameValidator.cpp @@ -28,18 +28,15 @@ namespace validators { -ScreenNameValidator::ScreenNameValidator( - QLineEdit *lineEdit, ValidationError *error, const ScreenList *pScreens) - : LineEditValidator(lineEdit, error) { - addValidator( - std::make_unique("Computer name cannot be empty")); - addValidator( - std::make_unique("Computer name cannot contain spaces")); - addValidator(std::make_unique( - "Contains invalid characters or is too long")); +ScreenNameValidator::ScreenNameValidator(QLineEdit *lineEdit, ValidationError *error, const ScreenList *pScreens) + : LineEditValidator(lineEdit, error) +{ + addValidator(std::make_unique("Computer name cannot be empty")); + addValidator(std::make_unique("Computer name cannot contain spaces")); + addValidator(std::make_unique("Contains invalid characters or is too long")); addValidator(std::make_unique( - "A computer with this name already exists", - lineEdit ? lineEdit->text() : "", pScreens)); + "A computer with this name already exists", lineEdit ? lineEdit->text() : "", pScreens + )); } } // namespace validators diff --git a/src/lib/gui/validators/ScreenNameValidator.h b/src/lib/gui/validators/ScreenNameValidator.h index a0859aed0..148c5e498 100644 --- a/src/lib/gui/validators/ScreenNameValidator.h +++ b/src/lib/gui/validators/ScreenNameValidator.h @@ -23,11 +23,12 @@ namespace validators { -class ScreenNameValidator : public LineEditValidator { +class ScreenNameValidator : public LineEditValidator +{ public: explicit ScreenNameValidator( - QLineEdit *lineEdit = nullptr, ValidationError *error = nullptr, - const ScreenList *pScreens = nullptr); + QLineEdit *lineEdit = nullptr, ValidationError *error = nullptr, const ScreenList *pScreens = nullptr + ); }; } // namespace validators diff --git a/src/lib/gui/validators/SpacesValidator.cpp b/src/lib/gui/validators/SpacesValidator.cpp index 080e113f1..5546aef35 100644 --- a/src/lib/gui/validators/SpacesValidator.cpp +++ b/src/lib/gui/validators/SpacesValidator.cpp @@ -19,10 +19,12 @@ namespace validators { -SpacesValidator::SpacesValidator(const QString &message) - : IStringValidator(message) {} +SpacesValidator::SpacesValidator(const QString &message) : IStringValidator(message) +{ +} -bool SpacesValidator::validate(const QString &input) const { +bool SpacesValidator::validate(const QString &input) const +{ return !input.contains(' '); } diff --git a/src/lib/gui/validators/SpacesValidator.h b/src/lib/gui/validators/SpacesValidator.h index ca3213141..3d273870c 100644 --- a/src/lib/gui/validators/SpacesValidator.h +++ b/src/lib/gui/validators/SpacesValidator.h @@ -21,7 +21,8 @@ namespace validators { -class SpacesValidator : public IStringValidator { +class SpacesValidator : public IStringValidator +{ public: explicit SpacesValidator(const QString &message); bool validate(const QString &input) const override; diff --git a/src/lib/gui/validators/ValidationError.cpp b/src/lib/gui/validators/ValidationError.cpp index 9f3050dc6..6f40b4b2a 100644 --- a/src/lib/gui/validators/ValidationError.cpp +++ b/src/lib/gui/validators/ValidationError.cpp @@ -23,25 +23,29 @@ using namespace deskflow::gui; namespace validators { -void clear(QLabel *label) { +void clear(QLabel *label) +{ if (label) { label->setStyleSheet(kStyleErrorInactiveLabel); label->setText(""); } } -ValidationError::ValidationError(QObject *parent, QLabel *label) - : QObject(parent), - m_pLabel(label) { +ValidationError::ValidationError(QObject *parent, QLabel *label) : QObject(parent), m_pLabel(label) +{ if (m_pLabel) { clear(m_pLabel); } } -const QString &ValidationError::message() const { return m_message; } +const QString &ValidationError::message() const +{ + return m_message; +} -void ValidationError::setMessage(const QString &message) { +void ValidationError::setMessage(const QString &message) +{ m_message = message; if (m_pLabel) { diff --git a/src/lib/gui/validators/ValidationError.h b/src/lib/gui/validators/ValidationError.h index fd65c04ed..c32db6264 100644 --- a/src/lib/gui/validators/ValidationError.h +++ b/src/lib/gui/validators/ValidationError.h @@ -23,7 +23,8 @@ namespace validators { -class ValidationError : public QObject { +class ValidationError : public QObject +{ QString m_message; QLabel *m_pLabel = nullptr; diff --git a/src/lib/gui/widgets/ClientStateLabel.cpp b/src/lib/gui/widgets/ClientStateLabel.cpp index fc95d2245..72370e87a 100644 --- a/src/lib/gui/widgets/ClientStateLabel.cpp +++ b/src/lib/gui/widgets/ClientStateLabel.cpp @@ -19,14 +19,16 @@ namespace deskflow::gui::widgets { -ClientStateLabel::ClientStateLabel(QWidget *parent) : QLabel(parent) { hide(); } +ClientStateLabel::ClientStateLabel(QWidget *parent) : QLabel(parent) +{ + hide(); +} -void ClientStateLabel::updateClientState(const QString &line) { +void ClientStateLabel::updateClientState(const QString &line) +{ if (line.contains("connected to server")) { show(); - } else if ( - line.contains("disconnected from server") || - line.contains("process exited")) { + } else if (line.contains("disconnected from server") || line.contains("process exited")) { hide(); } } diff --git a/src/lib/gui/widgets/ClientStateLabel.h b/src/lib/gui/widgets/ClientStateLabel.h index b8082000d..375fce445 100644 --- a/src/lib/gui/widgets/ClientStateLabel.h +++ b/src/lib/gui/widgets/ClientStateLabel.h @@ -21,7 +21,8 @@ namespace deskflow::gui::widgets { -class ClientStateLabel : public QLabel { +class ClientStateLabel : public QLabel +{ public: explicit ClientStateLabel(QWidget *parent = nullptr); void updateClientState(const QString &line); diff --git a/src/lib/gui/widgets/ServerStateLabel.cpp b/src/lib/gui/widgets/ServerStateLabel.cpp index 4ab2d0729..ff2533efd 100644 --- a/src/lib/gui/widgets/ServerStateLabel.cpp +++ b/src/lib/gui/widgets/ServerStateLabel.cpp @@ -23,9 +23,12 @@ using namespace deskflow::gui; namespace deskflow::gui::widgets { -ServerStateLabel::ServerStateLabel(QWidget *parent) : QLabel(parent) {} +ServerStateLabel::ServerStateLabel(QWidget *parent) : QLabel(parent) +{ +} -void ServerStateLabel::updateServerState(const QString &line) { +void ServerStateLabel::updateServerState(const QString &line) +{ ServerMessage message(line); if (message.isExitMessage()) { diff --git a/src/lib/gui/widgets/ServerStateLabel.h b/src/lib/gui/widgets/ServerStateLabel.h index 62bf492b7..23d23ee5f 100644 --- a/src/lib/gui/widgets/ServerStateLabel.h +++ b/src/lib/gui/widgets/ServerStateLabel.h @@ -22,7 +22,8 @@ namespace deskflow::gui::widgets { -class ServerStateLabel : public QLabel { +class ServerStateLabel : public QLabel +{ public: explicit ServerStateLabel(QWidget *parent = nullptr); void updateServerState(const QString &line); diff --git a/src/lib/io/IStream.h b/src/lib/io/IStream.h index 51a303ffd..8e9d78619 100644 --- a/src/lib/io/IStream.h +++ b/src/lib/io/IStream.h @@ -31,9 +31,12 @@ namespace deskflow { /*! Defines the interface for all streams. */ -class IStream : public IInterface { +class IStream : public IInterface +{ public: - IStream() {} + IStream() + { + } //! @name manipulators //@{ diff --git a/src/lib/io/StreamBuffer.cpp b/src/lib/io/StreamBuffer.cpp index 88c49360e..96dc1257e 100644 --- a/src/lib/io/StreamBuffer.cpp +++ b/src/lib/io/StreamBuffer.cpp @@ -25,15 +25,18 @@ const UInt32 StreamBuffer::kChunkSize = 4096; -StreamBuffer::StreamBuffer() : m_size(0), m_headUsed(0) { +StreamBuffer::StreamBuffer() : m_size(0), m_headUsed(0) +{ // do nothing } -StreamBuffer::~StreamBuffer() { +StreamBuffer::~StreamBuffer() +{ // do nothing } -const void *StreamBuffer::peek(UInt32 n) { +const void *StreamBuffer::peek(UInt32 n) +{ assert(n <= m_size); // if requesting no data then return NULL so we don't try to access @@ -57,7 +60,8 @@ const void *StreamBuffer::peek(UInt32 n) { return static_cast(&(head->begin()[m_headUsed])); } -void StreamBuffer::pop(UInt32 n) { +void StreamBuffer::pop(UInt32 n) +{ // discard all chunks if n is greater than or equal to m_size if (n >= m_size) { m_size = 0; @@ -85,7 +89,8 @@ void StreamBuffer::pop(UInt32 n) { } } -void StreamBuffer::write(const void *vdata, UInt32 n) { +void StreamBuffer::write(const void *vdata, UInt32 n) +{ assert(vdata != NULL); // ignore if no data, otherwise update size @@ -130,4 +135,7 @@ void StreamBuffer::write(const void *vdata, UInt32 n) { } } -UInt32 StreamBuffer::getSize() const { return m_size; } +UInt32 StreamBuffer::getSize() const +{ + return m_size; +} diff --git a/src/lib/io/StreamBuffer.h b/src/lib/io/StreamBuffer.h index b58722778..afe309eda 100644 --- a/src/lib/io/StreamBuffer.h +++ b/src/lib/io/StreamBuffer.h @@ -26,7 +26,8 @@ /*! This class maintains a FIFO (first-in, last-out) buffer of bytes. */ -class StreamBuffer { +class StreamBuffer +{ public: StreamBuffer(); ~StreamBuffer(); diff --git a/src/lib/io/StreamFilter.cpp b/src/lib/io/StreamFilter.cpp index f57690779..6fa902cdd 100644 --- a/src/lib/io/StreamFilter.cpp +++ b/src/lib/io/StreamFilter.cpp @@ -24,57 +24,83 @@ // StreamFilter // -StreamFilter::StreamFilter( - IEventQueue *events, deskflow::IStream *stream, bool adoptStream) +StreamFilter::StreamFilter(IEventQueue *events, deskflow::IStream *stream, bool adoptStream) : m_stream(stream), m_adopted(adoptStream), - m_events(events) { + m_events(events) +{ // replace handlers for m_stream m_events->removeHandlers(m_stream->getEventTarget()); m_events->adoptHandler( Event::kUnknown, m_stream->getEventTarget(), - new TMethodEventJob( - this, &StreamFilter::handleUpstreamEvent)); + new TMethodEventJob(this, &StreamFilter::handleUpstreamEvent) + ); } -StreamFilter::~StreamFilter() { +StreamFilter::~StreamFilter() +{ m_events->removeHandler(Event::kUnknown, m_stream->getEventTarget()); if (m_adopted) { delete m_stream; } } -void StreamFilter::close() { getStream()->close(); } +void StreamFilter::close() +{ + getStream()->close(); +} -UInt32 StreamFilter::read(void *buffer, UInt32 n) { +UInt32 StreamFilter::read(void *buffer, UInt32 n) +{ return getStream()->read(buffer, n); } -void StreamFilter::write(const void *buffer, UInt32 n) { +void StreamFilter::write(const void *buffer, UInt32 n) +{ getStream()->write(buffer, n); } -void StreamFilter::flush() { getStream()->flush(); } +void StreamFilter::flush() +{ + getStream()->flush(); +} -void StreamFilter::shutdownInput() { getStream()->shutdownInput(); } +void StreamFilter::shutdownInput() +{ + getStream()->shutdownInput(); +} -void StreamFilter::shutdownOutput() { getStream()->shutdownOutput(); } +void StreamFilter::shutdownOutput() +{ + getStream()->shutdownOutput(); +} -void *StreamFilter::getEventTarget() const { +void *StreamFilter::getEventTarget() const +{ return const_cast(static_cast(this)); } -bool StreamFilter::isReady() const { return getStream()->isReady(); } - -UInt32 StreamFilter::getSize() const { return getStream()->getSize(); } - -deskflow::IStream *StreamFilter::getStream() const { return m_stream; } - -void StreamFilter::filterEvent(const Event &event) { - m_events->dispatchEvent( - Event(event.getType(), getEventTarget(), event.getData())); +bool StreamFilter::isReady() const +{ + return getStream()->isReady(); } -void StreamFilter::handleUpstreamEvent(const Event &event, void *) { +UInt32 StreamFilter::getSize() const +{ + return getStream()->getSize(); +} + +deskflow::IStream *StreamFilter::getStream() const +{ + return m_stream; +} + +void StreamFilter::filterEvent(const Event &event) +{ + m_events->dispatchEvent(Event(event.getType(), getEventTarget(), event.getData())); +} + +void StreamFilter::handleUpstreamEvent(const Event &event, void *) +{ filterEvent(event); } diff --git a/src/lib/io/StreamFilter.h b/src/lib/io/StreamFilter.h index 8cc99491e..adfebbc0b 100644 --- a/src/lib/io/StreamFilter.h +++ b/src/lib/io/StreamFilter.h @@ -26,15 +26,15 @@ This class wraps a stream. Subclasses provide indirect access to the wrapped stream, typically performing some filtering. */ -class StreamFilter : public deskflow::IStream { +class StreamFilter : public deskflow::IStream +{ public: /*! Create a wrapper around \c stream. Iff \c adoptStream is true then this object takes ownership of the stream and will delete it in the d'tor. */ - StreamFilter( - IEventQueue *events, deskflow::IStream *stream, bool adoptStream = true); + StreamFilter(IEventQueue *events, deskflow::IStream *stream, bool adoptStream = true); StreamFilter(StreamFilter const &) = delete; StreamFilter(StreamFilter &&) = delete; virtual ~StreamFilter(); diff --git a/src/lib/io/XIO.cpp b/src/lib/io/XIO.cpp index 12b222e50..f09541435 100644 --- a/src/lib/io/XIO.cpp +++ b/src/lib/io/XIO.cpp @@ -22,7 +22,8 @@ // XIOClosed // -String XIOClosed::getWhat() const throw() { +String XIOClosed::getWhat() const throw() +{ return format("XIOClosed", "already closed"); } @@ -30,7 +31,8 @@ String XIOClosed::getWhat() const throw() { // XIOEndOfStream // -String XIOEndOfStream::getWhat() const throw() { +String XIOEndOfStream::getWhat() const throw() +{ return format("XIOEndOfStream", "reached end of stream"); } @@ -38,6 +40,7 @@ String XIOEndOfStream::getWhat() const throw() { // XIOWouldBlock // -String XIOWouldBlock::getWhat() const throw() { +String XIOWouldBlock::getWhat() const throw() +{ return format("XIOWouldBlock", "stream operation would block"); } diff --git a/src/lib/ipc/IpcClient.cpp b/src/lib/ipc/IpcClient.cpp index b6cb13c78..5183b1956 100644 --- a/src/lib/ipc/IpcClient.cpp +++ b/src/lib/ipc/IpcClient.cpp @@ -29,62 +29,71 @@ IpcClient::IpcClient(IEventQueue *events, SocketMultiplexer *socketMultiplexer) : m_serverAddress(NetworkAddress(kIpcHost, kIpcPort)), m_socket(events, socketMultiplexer), m_server(nullptr), - m_events(events) { + m_events(events) +{ init(); } -IpcClient::IpcClient( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, int port) +IpcClient::IpcClient(IEventQueue *events, SocketMultiplexer *socketMultiplexer, int port) : m_serverAddress(NetworkAddress(kIpcHost, port)), m_socket(events, socketMultiplexer), m_server(nullptr), - m_events(events) { + m_events(events) +{ init(); } -void IpcClient::init() { m_serverAddress.resolve(); } +void IpcClient::init() +{ + m_serverAddress.resolve(); +} -IpcClient::~IpcClient() {} +IpcClient::~IpcClient() +{ +} -void IpcClient::connect() { +void IpcClient::connect() +{ m_events->adoptHandler( m_events->forIDataSocket().connected(), m_socket.getEventTarget(), - new TMethodEventJob(this, &IpcClient::handleConnected)); + new TMethodEventJob(this, &IpcClient::handleConnected) + ); m_socket.connect(m_serverAddress); m_server = new IpcServerProxy(m_socket, m_events); m_events->adoptHandler( m_events->forIpcServerProxy().messageReceived(), m_server, - new TMethodEventJob(this, &IpcClient::handleMessageReceived)); + new TMethodEventJob(this, &IpcClient::handleMessageReceived) + ); } -void IpcClient::disconnect() { - m_events->removeHandler( - m_events->forIDataSocket().connected(), m_socket.getEventTarget()); - m_events->removeHandler( - m_events->forIpcServerProxy().messageReceived(), m_server); +void IpcClient::disconnect() +{ + m_events->removeHandler(m_events->forIDataSocket().connected(), m_socket.getEventTarget()); + m_events->removeHandler(m_events->forIpcServerProxy().messageReceived(), m_server); m_server->disconnect(); delete m_server; m_server = nullptr; } -void IpcClient::send(const IpcMessage &message) { +void IpcClient::send(const IpcMessage &message) +{ assert(m_server != nullptr); m_server->send(message); } -void IpcClient::handleConnected(const Event &, void *) { - m_events->addEvent(Event( - m_events->forIpcClient().connected(), this, m_server, - Event::kDontFreeData)); +void IpcClient::handleConnected(const Event &, void *) +{ + m_events->addEvent(Event(m_events->forIpcClient().connected(), this, m_server, Event::kDontFreeData)); IpcHelloMessage message(IpcClientType::Node); send(message); } -void IpcClient::handleMessageReceived(const Event &e, void *) { +void IpcClient::handleMessageReceived(const Event &e, void *) +{ Event event(m_events->forIpcClient().messageReceived(), this); event.setDataObject(e.getDataObject()); m_events->addEvent(event); diff --git a/src/lib/ipc/IpcClient.h b/src/lib/ipc/IpcClient.h index 80be77a8c..6fd0e1c08 100644 --- a/src/lib/ipc/IpcClient.h +++ b/src/lib/ipc/IpcClient.h @@ -31,11 +31,11 @@ class SocketMultiplexer; /*! * See \ref IpcServer description. */ -class IpcClient { +class IpcClient +{ public: IpcClient(IEventQueue *events, SocketMultiplexer *socketMultiplexer); - IpcClient( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, int port); + IpcClient(IEventQueue *events, SocketMultiplexer *socketMultiplexer, int port); virtual ~IpcClient(); //! @name manipulators diff --git a/src/lib/ipc/IpcClientProxy.cpp b/src/lib/ipc/IpcClientProxy.cpp index 35317cd99..8f27ccbdd 100644 --- a/src/lib/ipc/IpcClientProxy.cpp +++ b/src/lib/ipc/IpcClientProxy.cpp @@ -29,38 +29,35 @@ // IpcClientProxy // -IpcClientProxy::IpcClientProxy(deskflow::IStream &stream, IEventQueue *events) - : m_stream(stream), - m_events(events) { +IpcClientProxy::IpcClientProxy(deskflow::IStream &stream, IEventQueue *events) : m_stream(stream), m_events(events) +{ m_events->adoptHandler( m_events->forIStream().inputReady(), stream.getEventTarget(), - new TMethodEventJob(this, &IpcClientProxy::handleData)); + new TMethodEventJob(this, &IpcClientProxy::handleData) + ); m_events->adoptHandler( m_events->forIStream().outputError(), stream.getEventTarget(), - new TMethodEventJob( - this, &IpcClientProxy::handleWriteError)); + new TMethodEventJob(this, &IpcClientProxy::handleWriteError) + ); m_events->adoptHandler( m_events->forIStream().inputShutdown(), stream.getEventTarget(), - new TMethodEventJob( - this, &IpcClientProxy::handleDisconnect)); + new TMethodEventJob(this, &IpcClientProxy::handleDisconnect) + ); m_events->adoptHandler( m_events->forIStream().outputShutdown(), stream.getEventTarget(), - new TMethodEventJob( - this, &IpcClientProxy::handleWriteError)); + new TMethodEventJob(this, &IpcClientProxy::handleWriteError) + ); } -IpcClientProxy::~IpcClientProxy() { - m_events->removeHandler( - m_events->forIStream().inputReady(), m_stream.getEventTarget()); - m_events->removeHandler( - m_events->forIStream().outputError(), m_stream.getEventTarget()); - m_events->removeHandler( - m_events->forIStream().inputShutdown(), m_stream.getEventTarget()); - m_events->removeHandler( - m_events->forIStream().outputShutdown(), m_stream.getEventTarget()); +IpcClientProxy::~IpcClientProxy() +{ + m_events->removeHandler(m_events->forIStream().inputReady(), m_stream.getEventTarget()); + m_events->removeHandler(m_events->forIStream().outputError(), m_stream.getEventTarget()); + m_events->removeHandler(m_events->forIStream().inputShutdown(), m_stream.getEventTarget()); + m_events->removeHandler(m_events->forIStream().outputShutdown(), m_stream.getEventTarget()); // don't delete the stream while it's being used. ARCH->lockMutex(m_readMutex); @@ -73,17 +70,20 @@ IpcClientProxy::~IpcClientProxy() { ARCH->closeMutex(m_writeMutex); } -void IpcClientProxy::handleDisconnect(const Event &, void *) { +void IpcClientProxy::handleDisconnect(const Event &, void *) +{ disconnect(); LOG((CLOG_DEBUG "ipc client disconnected")); } -void IpcClientProxy::handleWriteError(const Event &, void *) { +void IpcClientProxy::handleWriteError(const Event &, void *) +{ disconnect(); LOG((CLOG_DEBUG "ipc client write error")); } -void IpcClientProxy::handleData(const Event &, void *) { +void IpcClientProxy::handleData(const Event &, void *) +{ // don't allow the dtor to destroy the stream while we're using it. ArchMutexLock lock(m_readMutex); @@ -108,9 +108,7 @@ void IpcClientProxy::handleData(const Event &, void *) { } // don't delete with this event; the data is passed to a new event. - Event e( - m_events->forIpcClientProxy().messageReceived(), this, NULL, - Event::kDontFreeData); + Event e(m_events->forIpcClientProxy().messageReceived(), this, NULL, Event::kDontFreeData); e.setDataObject(m); m_events->addEvent(e); @@ -120,7 +118,8 @@ void IpcClientProxy::handleData(const Event &, void *) { LOG((CLOG_DEBUG "finished ipc handle data")); } -void IpcClientProxy::send(const IpcMessage &message) { +void IpcClientProxy::send(const IpcMessage &message) +{ // don't allow other threads to write until we've finished the entire // message. stream write is locked, but only for that single write. // also, don't allow the dtor to destroy the stream while we're using it. @@ -130,8 +129,7 @@ void IpcClientProxy::send(const IpcMessage &message) { switch (message.type()) { case IpcMessageType::LogLine: { - const IpcLogLineMessage &llm = - static_cast(message); + const IpcLogLineMessage &llm = static_cast(message); const String logLine = llm.logLine(); ProtocolUtil::writef(&m_stream, kIpcMsgLogLine, &logLine); break; @@ -151,7 +149,8 @@ void IpcClientProxy::send(const IpcMessage &message) { } } -IpcHelloMessage *IpcClientProxy::parseHello() { +IpcHelloMessage *IpcClientProxy::parseHello() +{ UInt8 type; ProtocolUtil::readf(&m_stream, kIpcMsgHello + 4, &type); @@ -161,7 +160,8 @@ IpcHelloMessage *IpcClientProxy::parseHello() { return new IpcHelloMessage(m_clientType); } -IpcCommandMessage *IpcClientProxy::parseCommand() { +IpcCommandMessage *IpcClientProxy::parseCommand() +{ String command; UInt8 elevate; ProtocolUtil::readf(&m_stream, kIpcMsgCommand + 4, &command, &elevate); @@ -170,7 +170,8 @@ IpcCommandMessage *IpcClientProxy::parseCommand() { return new IpcCommandMessage(command, elevate != 0); } -IpcSettingMessage *IpcClientProxy::parseSetting() const { +IpcSettingMessage *IpcClientProxy::parseSetting() const +{ String name; String value; @@ -180,7 +181,8 @@ IpcSettingMessage *IpcClientProxy::parseSetting() const { return new IpcSettingMessage(name, value); } -void IpcClientProxy::disconnect() { +void IpcClientProxy::disconnect() +{ LOG((CLOG_DEBUG "ipc disconnect, closing stream")); m_disconnecting = true; m_stream.close(); diff --git a/src/lib/ipc/IpcClientProxy.h b/src/lib/ipc/IpcClientProxy.h index 94295585b..2cf5599fc 100644 --- a/src/lib/ipc/IpcClientProxy.h +++ b/src/lib/ipc/IpcClientProxy.h @@ -32,7 +32,8 @@ class IpcSettingMessage; class IpcHelloMessage; class IEventQueue; -class IpcClientProxy { +class IpcClientProxy +{ friend class IpcServer; public: diff --git a/src/lib/ipc/IpcLogOutputter.cpp b/src/lib/ipc/IpcLogOutputter.cpp index a8a08c569..401fa3aa5 100644 --- a/src/lib/ipc/IpcLogOutputter.cpp +++ b/src/lib/ipc/IpcLogOutputter.cpp @@ -30,15 +30,15 @@ #include "ipc/IpcServer.h" #include "mt/Thread.h" -enum EIpcLogOutputter { +enum EIpcLogOutputter +{ kBufferMaxSize = 1000, kMaxSendLines = 100, kBufferRateWriteLimit = 1000, // writes per kBufferRateTime kBufferRateTimeLimit = 1 // seconds }; -IpcLogOutputter::IpcLogOutputter( - IpcServer &ipcServer, IpcClientType clientType, bool useThread) +IpcLogOutputter::IpcLogOutputter(IpcServer &ipcServer, IpcClientType clientType, bool useThread) : m_ipcServer(ipcServer), m_bufferMutex(ARCH->newMutex()), m_sending(false), @@ -54,14 +54,15 @@ IpcLogOutputter::IpcLogOutputter( m_bufferWriteCount(0), m_bufferRateStart(ARCH->time()), m_clientType(clientType), - m_runningMutex(ARCH->newMutex()) { + m_runningMutex(ARCH->newMutex()) +{ if (useThread) { - m_bufferThread = new Thread( - new TMethodJob(this, &IpcLogOutputter::bufferThread)); + m_bufferThread = new Thread(new TMethodJob(this, &IpcLogOutputter::bufferThread)); } } -IpcLogOutputter::~IpcLogOutputter() { +IpcLogOutputter::~IpcLogOutputter() +{ close(); ARCH->closeMutex(m_bufferMutex); @@ -76,9 +77,12 @@ IpcLogOutputter::~IpcLogOutputter() { ARCH->closeMutex(m_notifyMutex); } -void IpcLogOutputter::open(const char *title) {} +void IpcLogOutputter::open(const char *title) +{ +} -void IpcLogOutputter::close() { +void IpcLogOutputter::close() +{ if (m_bufferThread != nullptr) { ArchMutexLock lock(m_runningMutex); m_running = false; @@ -87,12 +91,14 @@ void IpcLogOutputter::close() { } } -void IpcLogOutputter::show(bool showIfEmpty) {} +void IpcLogOutputter::show(bool showIfEmpty) +{ +} -bool IpcLogOutputter::write(ELevel, const char *text) { +bool IpcLogOutputter::write(ELevel, const char *text) +{ // ignore events from the buffer thread (would cause recursion). - if (m_bufferThread != nullptr && - Thread::getCurrentThread().getID() == m_bufferThreadId) { + if (m_bufferThread != nullptr && Thread::getCurrentThread().getID() == m_bufferThreadId) { return true; } @@ -102,7 +108,8 @@ bool IpcLogOutputter::write(ELevel, const char *text) { return true; } -void IpcLogOutputter::appendBuffer(const String &text) { +void IpcLogOutputter::appendBuffer(const String &text) +{ ArchMutexLock lock(m_bufferMutex); double elapsed = ARCH->time() - m_bufferRateStart; @@ -126,12 +133,14 @@ void IpcLogOutputter::appendBuffer(const String &text) { m_bufferWriteCount++; } -bool IpcLogOutputter::isRunning() { +bool IpcLogOutputter::isRunning() +{ ArchMutexLock lock(m_runningMutex); return m_running; } -void IpcLogOutputter::bufferThread(void *) { +void IpcLogOutputter::bufferThread(void *) +{ m_bufferThreadId = m_bufferThread->getID(); m_running = true; @@ -151,12 +160,14 @@ void IpcLogOutputter::bufferThread(void *) { LOG((CLOG_DEBUG "ipc log buffer thread finished")); } -void IpcLogOutputter::notifyBuffer() { +void IpcLogOutputter::notifyBuffer() +{ ArchMutexLock lock(m_notifyMutex); ARCH->broadcastCondVar(m_notifyCond); } -String IpcLogOutputter::getChunk(size_t count) { +String IpcLogOutputter::getChunk(size_t count) +{ ArchMutexLock lock(m_bufferMutex); if (m_buffer.size() < count) { @@ -172,7 +183,8 @@ String IpcLogOutputter::getChunk(size_t count) { return chunk; } -void IpcLogOutputter::sendBuffer() { +void IpcLogOutputter::sendBuffer() +{ if (m_buffer.empty() || !m_ipcServer.hasClients(m_clientType)) { return; } @@ -183,13 +195,18 @@ void IpcLogOutputter::sendBuffer() { m_sending = false; } -void IpcLogOutputter::bufferMaxSize(UInt16 bufferMaxSize) { +void IpcLogOutputter::bufferMaxSize(UInt16 bufferMaxSize) +{ m_bufferMaxSize = bufferMaxSize; } -UInt16 IpcLogOutputter::bufferMaxSize() const { return m_bufferMaxSize; } +UInt16 IpcLogOutputter::bufferMaxSize() const +{ + return m_bufferMaxSize; +} -void IpcLogOutputter::bufferRateLimit(UInt16 writeLimit, double timeLimit) { +void IpcLogOutputter::bufferRateLimit(UInt16 writeLimit, double timeLimit) +{ m_bufferRateWriteLimit = writeLimit; m_bufferRateTimeLimit = timeLimit; } diff --git a/src/lib/ipc/IpcLogOutputter.h b/src/lib/ipc/IpcLogOutputter.h index 00242e8d3..a354489fc 100644 --- a/src/lib/ipc/IpcLogOutputter.h +++ b/src/lib/ipc/IpcLogOutputter.h @@ -33,15 +33,15 @@ class IpcClientProxy; /*! This outputter writes output to the GUI via IPC. */ -class IpcLogOutputter : public ILogOutputter { +class IpcLogOutputter : public ILogOutputter +{ public: /*! If \p useThread is \c true, the buffer will be sent using a thread. If \p useThread is \c false, then the buffer needs to be sent manually using the \c sendBuffer() function. */ - IpcLogOutputter( - IpcServer &ipcServer, IpcClientType clientType, bool useThread); + IpcLogOutputter(IpcServer &ipcServer, IpcClientType clientType, bool useThread); IpcLogOutputter(IpcLogOutputter const &) = delete; virtual ~IpcLogOutputter(); diff --git a/src/lib/ipc/IpcMessage.cpp b/src/lib/ipc/IpcMessage.cpp index 4749925da..474af9532 100644 --- a/src/lib/ipc/IpcMessage.cpp +++ b/src/lib/ipc/IpcMessage.cpp @@ -19,23 +19,29 @@ #include "ipc/IpcMessage.h" #include "common/ipc.h" -IpcMessage::IpcMessage(IpcMessageType type) : m_type(type) {} +IpcMessage::IpcMessage(IpcMessageType type) : m_type(type) +{ +} -IpcHelloMessage::IpcHelloMessage(IpcClientType clientType) - : IpcMessage(IpcMessageType::Hello), - m_clientType(clientType) {} +IpcHelloMessage::IpcHelloMessage(IpcClientType clientType) : IpcMessage(IpcMessageType::Hello), m_clientType(clientType) +{ +} -IpcHelloBackMessage::IpcHelloBackMessage() - : IpcMessage(IpcMessageType::HelloBack) {} +IpcHelloBackMessage::IpcHelloBackMessage() : IpcMessage(IpcMessageType::HelloBack) +{ +} -IpcShutdownMessage::IpcShutdownMessage() - : IpcMessage(IpcMessageType::Shutdown) {} +IpcShutdownMessage::IpcShutdownMessage() : IpcMessage(IpcMessageType::Shutdown) +{ +} -IpcLogLineMessage::IpcLogLineMessage(const String &logLine) - : IpcMessage(IpcMessageType::LogLine), - m_logLine(logLine) {} +IpcLogLineMessage::IpcLogLineMessage(const String &logLine) : IpcMessage(IpcMessageType::LogLine), m_logLine(logLine) +{ +} IpcCommandMessage::IpcCommandMessage(const String &command, bool elevate) : IpcMessage(IpcMessageType::Command), m_command(command), - m_elevate(elevate) {} + m_elevate(elevate) +{ +} diff --git a/src/lib/ipc/IpcMessage.h b/src/lib/ipc/IpcMessage.h index 8b4707b46..5d043ef49 100644 --- a/src/lib/ipc/IpcMessage.h +++ b/src/lib/ipc/IpcMessage.h @@ -21,12 +21,16 @@ #include "base/String.h" #include "common/ipc.h" -class IpcMessage : public EventData { +class IpcMessage : public EventData +{ public: ~IpcMessage() override = default; //! Gets the message type ID. - IpcMessageType type() const { return m_type; } + IpcMessageType type() const + { + return m_type; + } protected: explicit IpcMessage(IpcMessageType type); @@ -35,52 +39,69 @@ private: IpcMessageType m_type; }; -class IpcHelloMessage : public IpcMessage { +class IpcHelloMessage : public IpcMessage +{ public: explicit IpcHelloMessage(IpcClientType clientType); ~IpcHelloMessage() override = default; //! Gets the message type ID. - IpcClientType clientType() const { return m_clientType; } + IpcClientType clientType() const + { + return m_clientType; + } private: IpcClientType m_clientType; }; -class IpcHelloBackMessage : public IpcMessage { +class IpcHelloBackMessage : public IpcMessage +{ public: explicit IpcHelloBackMessage(); ~IpcHelloBackMessage() override = default; }; -class IpcShutdownMessage : public IpcMessage { +class IpcShutdownMessage : public IpcMessage +{ public: explicit IpcShutdownMessage(); ~IpcShutdownMessage() override = default; }; -class IpcLogLineMessage : public IpcMessage { +class IpcLogLineMessage : public IpcMessage +{ public: explicit IpcLogLineMessage(const String &logLine); ~IpcLogLineMessage() override = default; //! Gets the log line. - String logLine() const { return m_logLine; } + String logLine() const + { + return m_logLine; + } private: String m_logLine; }; -class IpcCommandMessage : public IpcMessage { +class IpcCommandMessage : public IpcMessage +{ public: explicit IpcCommandMessage(const String &command, bool elevate); ~IpcCommandMessage() override = default; //! Gets the command. - String command() const { return m_command; } + String command() const + { + return m_command; + } //! Gets whether or not the process should be elevated on MS Windows. - bool elevate() const { return m_elevate; } + bool elevate() const + { + return m_elevate; + } private: String m_command; diff --git a/src/lib/ipc/IpcServer.cpp b/src/lib/ipc/IpcServer.cpp index de74a821c..d8a3e4375 100644 --- a/src/lib/ipc/IpcServer.cpp +++ b/src/lib/ipc/IpcServer.cpp @@ -37,32 +37,35 @@ IpcServer::IpcServer(IEventQueue *events, SocketMultiplexer *socketMultiplexer) m_events(events), m_socketMultiplexer(socketMultiplexer), m_socket(nullptr), - m_address(NetworkAddress(kIpcHost, kIpcPort)) { + m_address(NetworkAddress(kIpcHost, kIpcPort)) +{ init(); } -IpcServer::IpcServer( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, int port) +IpcServer::IpcServer(IEventQueue *events, SocketMultiplexer *socketMultiplexer, int port) : m_mock(false), m_events(events), m_socketMultiplexer(socketMultiplexer), - m_address(NetworkAddress(kIpcHost, port)) { + m_address(NetworkAddress(kIpcHost, port)) +{ init(); } -void IpcServer::init() { - m_socket = new TCPListenSocket( - m_events, m_socketMultiplexer, IArchNetwork::EAddressFamily::kINET); +void IpcServer::init() +{ + m_socket = new TCPListenSocket(m_events, m_socketMultiplexer, IArchNetwork::EAddressFamily::kINET); m_clientsMutex = ARCH->newMutex(); m_address.resolve(); m_events->adoptHandler( m_events->forIListenSocket().connecting(), m_socket, - new TMethodEventJob(this, &IpcServer::handleClientConnecting)); + new TMethodEventJob(this, &IpcServer::handleClientConnecting) + ); } -IpcServer::~IpcServer() { +IpcServer::~IpcServer() +{ if (m_mock) { return; } @@ -83,9 +86,13 @@ IpcServer::~IpcServer() { m_events->removeHandler(m_events->forIListenSocket().connecting(), m_socket); } -void IpcServer::listen() { m_socket->bind(m_address); } +void IpcServer::listen() +{ + m_socket->bind(m_address); +} -void IpcServer::handleClientConnecting(const Event &, void *) { +void IpcServer::handleClientConnecting(const Event &, void *) +{ deskflow::IStream *stream = m_socket->accept(); if (stream == NULL) { return; @@ -100,19 +107,19 @@ void IpcServer::handleClientConnecting(const Event &, void *) { m_events->adoptHandler( m_events->forIpcClientProxy().disconnected(), proxy, - new TMethodEventJob( - this, &IpcServer::handleClientDisconnected)); + new TMethodEventJob(this, &IpcServer::handleClientDisconnected) + ); m_events->adoptHandler( m_events->forIpcClientProxy().messageReceived(), proxy, - new TMethodEventJob(this, &IpcServer::handleMessageReceived)); + new TMethodEventJob(this, &IpcServer::handleMessageReceived) + ); - m_events->addEvent(Event( - m_events->forIpcServer().clientConnected(), this, proxy, - Event::kDontFreeData)); + m_events->addEvent(Event(m_events->forIpcServer().clientConnected(), this, proxy, Event::kDontFreeData)); } -void IpcServer::handleClientDisconnected(const Event &e, void *) { +void IpcServer::handleClientDisconnected(const Event &e, void *) +{ IpcClientProxy *proxy = static_cast(e.getTarget()); ArchMutexLock lock(m_clientsMutex); @@ -122,20 +129,22 @@ void IpcServer::handleClientDisconnected(const Event &e, void *) { LOG((CLOG_DEBUG "ipc client proxy removed, connected=%d", m_clients.size())); } -void IpcServer::handleMessageReceived(const Event &e, void *) { +void IpcServer::handleMessageReceived(const Event &e, void *) +{ Event event(m_events->forIpcServer().messageReceived(), this); event.setDataObject(e.getDataObject()); m_events->addEvent(event); } -void IpcServer::deleteClient(IpcClientProxy *proxy) { - m_events->removeHandler( - m_events->forIpcClientProxy().messageReceived(), proxy); +void IpcServer::deleteClient(IpcClientProxy *proxy) +{ + m_events->removeHandler(m_events->forIpcClientProxy().messageReceived(), proxy); m_events->removeHandler(m_events->forIpcClientProxy().disconnected(), proxy); delete proxy; } -bool IpcServer::hasClients(IpcClientType clientType) const { +bool IpcServer::hasClients(IpcClientType clientType) const +{ ArchMutexLock lock(m_clientsMutex); if (m_clients.empty()) { @@ -155,7 +164,8 @@ bool IpcServer::hasClients(IpcClientType clientType) const { return false; } -void IpcServer::send(const IpcMessage &message, IpcClientType filterType) { +void IpcServer::send(const IpcMessage &message, IpcClientType filterType) +{ ArchMutexLock lock(m_clientsMutex); ClientList::iterator it; diff --git a/src/lib/ipc/IpcServer.h b/src/lib/ipc/IpcServer.h index 677691c36..1bb1f9845 100644 --- a/src/lib/ipc/IpcServer.h +++ b/src/lib/ipc/IpcServer.h @@ -39,11 +39,11 @@ client/server process or the GUI. The IPC server runs on the daemon process. This allows the GUI to send config changes to the daemon and client/server, and allows the daemon and client/server to send log data to the GUI. */ -class IpcServer { +class IpcServer +{ public: IpcServer(IEventQueue *events, SocketMultiplexer *socketMultiplexer); - IpcServer( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, int port); + IpcServer(IEventQueue *events, SocketMultiplexer *socketMultiplexer, int port); IpcServer(IpcServer const &) = delete; IpcServer(IpcServer &&) = delete; virtual ~IpcServer(); @@ -89,10 +89,8 @@ private: #ifdef TEST_ENV public: - IpcServer() - : m_mock(true), - m_events(nullptr), - m_socketMultiplexer(nullptr), - m_socket(nullptr) {} + IpcServer() : m_mock(true), m_events(nullptr), m_socketMultiplexer(nullptr), m_socket(nullptr) + { + } #endif }; diff --git a/src/lib/ipc/IpcServerProxy.cpp b/src/lib/ipc/IpcServerProxy.cpp index cd4e6968d..ab27814f1 100644 --- a/src/lib/ipc/IpcServerProxy.cpp +++ b/src/lib/ipc/IpcServerProxy.cpp @@ -29,20 +29,21 @@ // IpcServerProxy // -IpcServerProxy::IpcServerProxy(deskflow::IStream &stream, IEventQueue *events) - : m_stream(stream), - m_events(events) { +IpcServerProxy::IpcServerProxy(deskflow::IStream &stream, IEventQueue *events) : m_stream(stream), m_events(events) +{ m_events->adoptHandler( m_events->forIStream().inputReady(), stream.getEventTarget(), - new TMethodEventJob(this, &IpcServerProxy::handleData)); + new TMethodEventJob(this, &IpcServerProxy::handleData) + ); } -IpcServerProxy::~IpcServerProxy() { - m_events->removeHandler( - m_events->forIStream().inputReady(), m_stream.getEventTarget()); +IpcServerProxy::~IpcServerProxy() +{ + m_events->removeHandler(m_events->forIStream().inputReady(), m_stream.getEventTarget()); } -void IpcServerProxy::handleData(const Event &, void *) { +void IpcServerProxy::handleData(const Event &, void *) +{ LOG((CLOG_DEBUG "start ipc handle data")); UInt8 code[4]; @@ -62,9 +63,7 @@ void IpcServerProxy::handleData(const Event &, void *) { } // don't delete with this event; the data is passed to a new event. - Event e( - m_events->forIpcServerProxy().messageReceived(), this, NULL, - Event::kDontFreeData); + Event e(m_events->forIpcServerProxy().messageReceived(), this, NULL, Event::kDontFreeData); e.setDataObject(m); m_events->addEvent(e); @@ -74,7 +73,8 @@ void IpcServerProxy::handleData(const Event &, void *) { LOG((CLOG_DEBUG "finished ipc handle data")); } -void IpcServerProxy::send(const IpcMessage &message) { +void IpcServerProxy::send(const IpcMessage &message) +{ LOG((CLOG_DEBUG4 "ipc write: %d", message.type())); switch (message.type()) { @@ -85,8 +85,7 @@ void IpcServerProxy::send(const IpcMessage &message) { } case IpcMessageType::Command: { - const IpcCommandMessage &cm = - static_cast(message); + const IpcCommandMessage &cm = static_cast(message); const String command = cm.command(); ProtocolUtil::writef(&m_stream, kIpcMsgCommand, &command); break; @@ -98,7 +97,8 @@ void IpcServerProxy::send(const IpcMessage &message) { } } -IpcLogLineMessage *IpcServerProxy::parseLogLine() { +IpcLogLineMessage *IpcServerProxy::parseLogLine() +{ String logLine; ProtocolUtil::readf(&m_stream, kIpcMsgLogLine + 4, &logLine); @@ -106,7 +106,8 @@ IpcLogLineMessage *IpcServerProxy::parseLogLine() { return new IpcLogLineMessage(logLine); } -void IpcServerProxy::disconnect() { +void IpcServerProxy::disconnect() +{ LOG((CLOG_DEBUG "ipc disconnect, closing stream")); m_stream.close(); } diff --git a/src/lib/ipc/IpcServerProxy.h b/src/lib/ipc/IpcServerProxy.h index 47a07d3b1..e0bad7990 100644 --- a/src/lib/ipc/IpcServerProxy.h +++ b/src/lib/ipc/IpcServerProxy.h @@ -28,7 +28,8 @@ class IpcMessage; class IpcLogLineMessage; class IEventQueue; -class IpcServerProxy { +class IpcServerProxy +{ friend class IpcClient; public: diff --git a/src/lib/ipc/IpcSettingMessage.cpp b/src/lib/ipc/IpcSettingMessage.cpp index 83834db5c..5c1663f92 100644 --- a/src/lib/ipc/IpcSettingMessage.cpp +++ b/src/lib/ipc/IpcSettingMessage.cpp @@ -18,12 +18,19 @@ #include "IpcSettingMessage.h" -IpcSettingMessage::IpcSettingMessage( - const std::string &name, const std::string &value) +IpcSettingMessage::IpcSettingMessage(const std::string &name, const std::string &value) : IpcMessage(IpcMessageType::Setting), m_name(name), - m_value(value) {} + m_value(value) +{ +} -const std::string &IpcSettingMessage::getName() const { return m_name; } +const std::string &IpcSettingMessage::getName() const +{ + return m_name; +} -const std::string &IpcSettingMessage::getValue() const { return m_value; } +const std::string &IpcSettingMessage::getValue() const +{ + return m_value; +} diff --git a/src/lib/ipc/IpcSettingMessage.h b/src/lib/ipc/IpcSettingMessage.h index 9956ec723..1e54f4cdc 100644 --- a/src/lib/ipc/IpcSettingMessage.h +++ b/src/lib/ipc/IpcSettingMessage.h @@ -21,7 +21,8 @@ #include "IpcMessage.h" #include -class IpcSettingMessage : public IpcMessage { +class IpcSettingMessage : public IpcMessage +{ public: //! //! \brief IpcSettingMessage constructor diff --git a/src/lib/mt/CondVar.cpp b/src/lib/mt/CondVar.cpp index 152b62adc..a7ce42c17 100644 --- a/src/lib/mt/CondVar.cpp +++ b/src/lib/mt/CondVar.cpp @@ -24,22 +24,39 @@ // CondVarBase // -CondVarBase::CondVarBase(Mutex *mutex) : m_mutex(mutex) { +CondVarBase::CondVarBase(Mutex *mutex) : m_mutex(mutex) +{ assert(m_mutex != NULL); m_cond = ARCH->newCondVar(); } -CondVarBase::~CondVarBase() { ARCH->closeCondVar(m_cond); } +CondVarBase::~CondVarBase() +{ + ARCH->closeCondVar(m_cond); +} -void CondVarBase::lock() const { m_mutex->lock(); } +void CondVarBase::lock() const +{ + m_mutex->lock(); +} -void CondVarBase::unlock() const { m_mutex->unlock(); } +void CondVarBase::unlock() const +{ + m_mutex->unlock(); +} -void CondVarBase::signal() { ARCH->signalCondVar(m_cond); } +void CondVarBase::signal() +{ + ARCH->signalCondVar(m_cond); +} -void CondVarBase::broadcast() { ARCH->broadcastCondVar(m_cond); } +void CondVarBase::broadcast() +{ + ARCH->broadcastCondVar(m_cond); +} -bool CondVarBase::wait(Stopwatch &timer, double timeout) const { +bool CondVarBase::wait(Stopwatch &timer, double timeout) const +{ double remain = timeout - timer.getTime(); // Some ARCH wait()s return prematurely, retry until really timed out // In particular, ArchMultithreadPosix::waitCondVar() returns every 100ms @@ -56,8 +73,12 @@ bool CondVarBase::wait(Stopwatch &timer, double timeout) const { return false; } -bool CondVarBase::wait(double timeout) const { +bool CondVarBase::wait(double timeout) const +{ return ARCH->waitCondVar(m_cond, m_mutex->m_mutex, timeout); } -Mutex *CondVarBase::getMutex() const { return m_mutex; } +Mutex *CondVarBase::getMutex() const +{ + return m_mutex; +} diff --git a/src/lib/mt/CondVar.h b/src/lib/mt/CondVar.h index 2a897c816..3ebbdf818 100644 --- a/src/lib/mt/CondVar.h +++ b/src/lib/mt/CondVar.h @@ -30,7 +30,8 @@ but doesn't provide the actual variable storage. A condition variable is a multiprocessing primitive that can be waited on. Every condition variable has an associated mutex. */ -class CondVarBase { +class CondVarBase +{ public: /*! \c mutex must not be NULL. All condition variables have an @@ -128,7 +129,8 @@ private: /*! A condition variable with storage for type \c T. */ -template class CondVar : public CondVarBase { +template class CondVar : public CondVarBase +{ public: //! Initialize using \c value CondVar(Mutex *mutex, const T &value); @@ -170,35 +172,34 @@ private: volatile T m_data; }; -template -inline CondVar::CondVar(Mutex *mutex, const T &data) - : CondVarBase(mutex), - m_data(data) { +template inline CondVar::CondVar(Mutex *mutex, const T &data) : CondVarBase(mutex), m_data(data) +{ // do nothing } -template -inline CondVar::CondVar(const CondVar &cv) - : CondVarBase(cv.getMutex()), - m_data(cv.m_data) { +template inline CondVar::CondVar(const CondVar &cv) : CondVarBase(cv.getMutex()), m_data(cv.m_data) +{ // do nothing } -template inline CondVar::~CondVar() { +template inline CondVar::~CondVar() +{ // do nothing } -template -inline CondVar &CondVar::operator=(const CondVar &cv) { +template inline CondVar &CondVar::operator=(const CondVar &cv) +{ m_data = cv.m_data; return *this; } -template inline CondVar &CondVar::operator=(const T &data) { +template inline CondVar &CondVar::operator=(const T &data) +{ m_data = data; return *this; } -template inline CondVar::operator const volatile T &() const { +template inline CondVar::operator const volatile T &() const +{ return m_data; } diff --git a/src/lib/mt/Lock.cpp b/src/lib/mt/Lock.cpp index eacc865eb..14c0c50f1 100644 --- a/src/lib/mt/Lock.cpp +++ b/src/lib/mt/Lock.cpp @@ -24,8 +24,17 @@ // Lock // -Lock::Lock(const Mutex *mutex) : m_mutex(mutex) { m_mutex->lock(); } +Lock::Lock(const Mutex *mutex) : m_mutex(mutex) +{ + m_mutex->lock(); +} -Lock::Lock(const CondVarBase *cv) : m_mutex(cv->getMutex()) { m_mutex->lock(); } +Lock::Lock(const CondVarBase *cv) : m_mutex(cv->getMutex()) +{ + m_mutex->lock(); +} -Lock::~Lock() { m_mutex->unlock(); } +Lock::~Lock() +{ + m_mutex->unlock(); +} diff --git a/src/lib/mt/Lock.h b/src/lib/mt/Lock.h index b8679bc25..26d5f8ffa 100644 --- a/src/lib/mt/Lock.h +++ b/src/lib/mt/Lock.h @@ -30,7 +30,8 @@ it in the d'tor. It's easier and safer than manually locking and unlocking since unlocking must usually be done no matter how a function exits (including by unwinding due to an exception). */ -class Lock { +class Lock +{ public: //! Lock the mutex \c mutex Lock(const Mutex *mutex); diff --git a/src/lib/mt/Mutex.cpp b/src/lib/mt/Mutex.cpp index 55a4d855b..568941abb 100644 --- a/src/lib/mt/Mutex.cpp +++ b/src/lib/mt/Mutex.cpp @@ -24,14 +24,32 @@ // Mutex // -Mutex::Mutex() { m_mutex = ARCH->newMutex(); } +Mutex::Mutex() +{ + m_mutex = ARCH->newMutex(); +} -Mutex::Mutex(const Mutex &) { m_mutex = ARCH->newMutex(); } +Mutex::Mutex(const Mutex &) +{ + m_mutex = ARCH->newMutex(); +} -Mutex::~Mutex() { ARCH->closeMutex(m_mutex); } +Mutex::~Mutex() +{ + ARCH->closeMutex(m_mutex); +} -Mutex &Mutex::operator=(const Mutex &) { return *this; } +Mutex &Mutex::operator=(const Mutex &) +{ + return *this; +} -void Mutex::lock() const { ARCH->lockMutex(m_mutex); } +void Mutex::lock() const +{ + ARCH->lockMutex(m_mutex); +} -void Mutex::unlock() const { ARCH->unlockMutex(m_mutex); } +void Mutex::unlock() const +{ + ARCH->unlockMutex(m_mutex); +} diff --git a/src/lib/mt/Mutex.h b/src/lib/mt/Mutex.h index f592f64d5..7dd60bcd8 100644 --- a/src/lib/mt/Mutex.h +++ b/src/lib/mt/Mutex.h @@ -29,7 +29,8 @@ blocked, exactly one waiting thread will acquire the lock and continue running. A thread may not lock a mutex it already owns the lock on; if it tries it will deadlock itself. */ -class Mutex { +class Mutex +{ public: Mutex(); //! Equivalent to default c'tor diff --git a/src/lib/mt/Thread.cpp b/src/lib/mt/Thread.cpp index a90a57fd8..5b4f89ddd 100644 --- a/src/lib/mt/Thread.cpp +++ b/src/lib/mt/Thread.cpp @@ -29,7 +29,8 @@ // Thread // -Thread::Thread(IJob *job) { +Thread::Thread(IJob *job) +{ m_thread = ARCH->newThread(&Thread::threadFunc, job); if (m_thread == NULL) { // couldn't create thread @@ -38,15 +39,23 @@ Thread::Thread(IJob *job) { } } -Thread::Thread(const Thread &thread) { +Thread::Thread(const Thread &thread) +{ m_thread = ARCH->copyThread(thread.m_thread); } -Thread::Thread(ArchThread adoptedThread) { m_thread = adoptedThread; } +Thread::Thread(ArchThread adoptedThread) +{ + m_thread = adoptedThread; +} -Thread::~Thread() { ARCH->closeThread(m_thread); } +Thread::~Thread() +{ + ARCH->closeThread(m_thread); +} -Thread &Thread::operator=(const Thread &thread) { +Thread &Thread::operator=(const Thread &thread) +{ // copy given thread and release ours ArchThread copy = ARCH->copyThread(thread.m_thread); ARCH->closeThread(m_thread); @@ -57,42 +66,66 @@ Thread &Thread::operator=(const Thread &thread) { return *this; } -void Thread::exit(void *result) { throw XThreadExit(result); } +void Thread::exit(void *result) +{ + throw XThreadExit(result); +} -void Thread::cancel() { ARCH->cancelThread(m_thread); } +void Thread::cancel() +{ + ARCH->cancelThread(m_thread); +} -void Thread::setPriority(int n) { ARCH->setPriorityOfThread(m_thread, n); } +void Thread::setPriority(int n) +{ + ARCH->setPriorityOfThread(m_thread, n); +} -void Thread::unblockPollSocket() { ARCH->unblockPollSocket(m_thread); } +void Thread::unblockPollSocket() +{ + ARCH->unblockPollSocket(m_thread); +} -Thread Thread::getCurrentThread() { return Thread(ARCH->newCurrentThread()); } +Thread Thread::getCurrentThread() +{ + return Thread(ARCH->newCurrentThread()); +} -void Thread::testCancel() { ARCH->testCancelThread(); } +void Thread::testCancel() +{ + ARCH->testCancelThread(); +} -bool Thread::wait(double timeout) const { +bool Thread::wait(double timeout) const +{ return ARCH->wait(m_thread, timeout); } -void *Thread::getResult() const { +void *Thread::getResult() const +{ if (wait()) return ARCH->getResultOfThread(m_thread); else return NULL; } -IArchMultithread::ThreadID Thread::getID() const { +IArchMultithread::ThreadID Thread::getID() const +{ return ARCH->getIDOfThread(m_thread); } -bool Thread::operator==(const Thread &thread) const { +bool Thread::operator==(const Thread &thread) const +{ return ARCH->isSameThread(m_thread, thread.m_thread); } -bool Thread::operator!=(const Thread &thread) const { +bool Thread::operator!=(const Thread &thread) const +{ return !ARCH->isSameThread(m_thread, thread.m_thread); } -void *Thread::threadFunc(void *vjob) { +void *Thread::threadFunc(void *vjob) +{ // get this thread's id for logging IArchMultithread::ThreadID id; { diff --git a/src/lib/mt/Thread.h b/src/lib/mt/Thread.h index 7f18e15cf..7ae915acf 100644 --- a/src/lib/mt/Thread.h +++ b/src/lib/mt/Thread.h @@ -40,7 +40,8 @@ a request to cancel the thread. Cancellation points are noted in the documentation. */ // note -- do not derive from this class -class Thread { +class Thread +{ public: //! Run \c adoptedJob in a new thread /*! diff --git a/src/lib/mt/XMT.cpp b/src/lib/mt/XMT.cpp index 3fd7d5e3d..876031ba2 100644 --- a/src/lib/mt/XMT.cpp +++ b/src/lib/mt/XMT.cpp @@ -22,6 +22,7 @@ // XMTThreadUnavailable // -String XMTThreadUnavailable::getWhat() const throw() { +String XMTThreadUnavailable::getWhat() const throw() +{ return format("XMTThreadUnavailable", "cannot create thread"); } diff --git a/src/lib/mt/XThread.h b/src/lib/mt/XThread.h index ec5cbfb46..4beca1710 100644 --- a/src/lib/mt/XThread.h +++ b/src/lib/mt/XThread.h @@ -26,11 +26,16 @@ Thrown by Thread::exit() to exit a thread. Clients of Thread must not throw this type but must rethrow it if caught (by XThreadExit, XThread, or ...). */ -class XThreadExit : public XThread { +class XThreadExit : public XThread +{ public: //! \c result is the result of the thread - XThreadExit(void *result) : m_result(result) {} - ~XThreadExit() {} + XThreadExit(void *result) : m_result(result) + { + } + ~XThreadExit() + { + } public: void *m_result; diff --git a/src/lib/net/IDataSocket.cpp b/src/lib/net/IDataSocket.cpp index 1d4f9f1ad..a232bc526 100644 --- a/src/lib/net/IDataSocket.cpp +++ b/src/lib/net/IDataSocket.cpp @@ -23,12 +23,14 @@ // IDataSocket // -void IDataSocket::close() { +void IDataSocket::close() +{ // this is here to work around a VC++6 bug. see the header file. assert(0 && "bad call"); } -void *IDataSocket::getEventTarget() const { +void *IDataSocket::getEventTarget() const +{ // this is here to work around a VC++6 bug. see the header file. assert(0 && "bad call"); return NULL; diff --git a/src/lib/net/IDataSocket.h b/src/lib/net/IDataSocket.h index 46fd7c65a..5c7b79df3 100644 --- a/src/lib/net/IDataSocket.h +++ b/src/lib/net/IDataSocket.h @@ -28,15 +28,21 @@ This interface defines the methods common to all network sockets that represent a full-duplex data stream. */ -class IDataSocket : public ISocket, public deskflow::IStream { +class IDataSocket : public ISocket, public deskflow::IStream +{ public: - class ConnectionFailedInfo { + class ConnectionFailedInfo + { public: - ConnectionFailedInfo(const char *what) : m_what(what) {} + ConnectionFailedInfo(const char *what) : m_what(what) + { + } String m_what; }; - IDataSocket(IEventQueue *events) {} + IDataSocket(IEventQueue *events) + { + } //! @name manipulators //@{ diff --git a/src/lib/net/IListenSocket.h b/src/lib/net/IListenSocket.h index b839879cc..4ba8dc0af 100644 --- a/src/lib/net/IListenSocket.h +++ b/src/lib/net/IListenSocket.h @@ -28,7 +28,8 @@ class IDataSocket; This interface defines the methods common to all network sockets that listen for incoming connections. */ -class IListenSocket : public ISocket { +class IListenSocket : public ISocket +{ public: //! @name manipulators //@{ diff --git a/src/lib/net/ISocket.h b/src/lib/net/ISocket.h index f23b23460..1a2493b5a 100644 --- a/src/lib/net/ISocket.h +++ b/src/lib/net/ISocket.h @@ -29,7 +29,8 @@ class NetworkAddress; This interface defines the methods common to all network sockets. Generated events use \c this as the target. */ -class ISocket : public IInterface { +class ISocket : public IInterface +{ public: //! @name manipulators //@{ diff --git a/src/lib/net/ISocketFactory.h b/src/lib/net/ISocketFactory.h index f8de4807d..5333c18c1 100644 --- a/src/lib/net/ISocketFactory.h +++ b/src/lib/net/ISocketFactory.h @@ -29,20 +29,17 @@ class IListenSocket; This interface defines the methods common to all factories used to create sockets. */ -class ISocketFactory : public IInterface { +class ISocketFactory : public IInterface +{ public: //! @name accessors //@{ //! Create data socket - virtual IDataSocket *create( - bool secure, - IArchNetwork::EAddressFamily family = IArchNetwork::kINET) const = 0; + virtual IDataSocket *create(bool secure, IArchNetwork::EAddressFamily family = IArchNetwork::kINET) const = 0; //! Create listen socket - virtual IListenSocket *createListen( - bool secure, - IArchNetwork::EAddressFamily family = IArchNetwork::kINET) const = 0; + virtual IListenSocket *createListen(bool secure, IArchNetwork::EAddressFamily family = IArchNetwork::kINET) const = 0; //@} }; diff --git a/src/lib/net/ISocketMultiplexerJob.h b/src/lib/net/ISocketMultiplexerJob.h index dcb795318..3344b890d 100644 --- a/src/lib/net/ISocketMultiplexerJob.h +++ b/src/lib/net/ISocketMultiplexerJob.h @@ -25,7 +25,8 @@ /*! A socket multiplexer job handles events on a socket. */ -class ISocketMultiplexerJob : public IInterface { +class ISocketMultiplexerJob : public IInterface +{ public: //! @name manipulators //@{ @@ -45,8 +46,7 @@ public: multiplexer. It must instead return the new job. It can, however, add or remove jobs for other sockets. */ - virtual ISocketMultiplexerJob * - run(bool readable, bool writable, bool error) = 0; + virtual ISocketMultiplexerJob *run(bool readable, bool writable, bool error) = 0; //@} //! @name accessors diff --git a/src/lib/net/InverseSockets/AutoArchSocket.cpp b/src/lib/net/InverseSockets/AutoArchSocket.cpp index becfea65e..0ded92291 100644 --- a/src/lib/net/InverseSockets/AutoArchSocket.cpp +++ b/src/lib/net/InverseSockets/AutoArchSocket.cpp @@ -22,7 +22,8 @@ #include "base/Log.h" #include "net/XSocket.h" -AutoArchSocket::AutoArchSocket(IArchNetwork::EAddressFamily family) { +AutoArchSocket::AutoArchSocket(IArchNetwork::EAddressFamily family) +{ try { m_socket = ARCH->newSocket(family, IArchNetwork::kSTREAM); LOG((CLOG_DEBUG "opening new socket: %08X", m_socket)); @@ -31,21 +32,27 @@ AutoArchSocket::AutoArchSocket(IArchNetwork::EAddressFamily family) { } } -AutoArchSocket::~AutoArchSocket() { closeSocket(); } +AutoArchSocket::~AutoArchSocket() +{ + closeSocket(); +} -void AutoArchSocket::setNoDelayOnSocket(bool value) { +void AutoArchSocket::setNoDelayOnSocket(bool value) +{ if (isValid()) { ARCH->setNoDelayOnSocket(m_socket, value); } } -void AutoArchSocket::setReuseAddrOnSocket(bool value) { +void AutoArchSocket::setReuseAddrOnSocket(bool value) +{ if (isValid()) { ARCH->setReuseAddrOnSocket(m_socket, value); } } -void AutoArchSocket::closeSocket() { +void AutoArchSocket::closeSocket() +{ if (isValid()) { try { LOG((CLOG_DEBUG "closing socket: %08X", m_socket)); @@ -60,7 +67,8 @@ void AutoArchSocket::closeSocket() { } } -void AutoArchSocket::bindSocket(const NetworkAddress &addr) { +void AutoArchSocket::bindSocket(const NetworkAddress &addr) +{ if (isValid()) { try { ARCH->bindSocket(m_socket, addr.getAddress()); @@ -72,7 +80,8 @@ void AutoArchSocket::bindSocket(const NetworkAddress &addr) { } } -void AutoArchSocket::bindAndListen(const NetworkAddress &addr) { +void AutoArchSocket::bindAndListen(const NetworkAddress &addr) +{ try { setReuseAddrOnSocket(); bindSocket(addr); @@ -84,17 +93,20 @@ void AutoArchSocket::bindAndListen(const NetworkAddress &addr) { } } -void AutoArchSocket::listenOnSocket() { +void AutoArchSocket::listenOnSocket() +{ if (isValid()) { ARCH->listenOnSocket(m_socket); } } -ArchSocket AutoArchSocket::acceptSocket() { +ArchSocket AutoArchSocket::acceptSocket() +{ return ARCH->acceptSocket(m_socket, nullptr); } -void AutoArchSocket::closeSocketForRead() { +void AutoArchSocket::closeSocketForRead() +{ if (isValid()) { try { ARCH->closeSocketForRead(m_socket); @@ -105,7 +117,8 @@ void AutoArchSocket::closeSocketForRead() { } } -void AutoArchSocket::closeSocketForWrite() { +void AutoArchSocket::closeSocketForWrite() +{ if (isValid()) { try { ARCH->closeSocketForWrite(m_socket); @@ -116,7 +129,8 @@ void AutoArchSocket::closeSocketForWrite() { } } -bool AutoArchSocket::connectSocket(const NetworkAddress &addr) { +bool AutoArchSocket::connectSocket(const NetworkAddress &addr) +{ bool result = false; if (isValid()) { @@ -130,7 +144,8 @@ bool AutoArchSocket::connectSocket(const NetworkAddress &addr) { return result; } -size_t AutoArchSocket::readSocket(UInt8 *buffer, size_t size) { +size_t AutoArchSocket::readSocket(UInt8 *buffer, size_t size) +{ size_t result = 0; if (isValid()) { @@ -140,7 +155,8 @@ size_t AutoArchSocket::readSocket(UInt8 *buffer, size_t size) { return result; } -size_t AutoArchSocket::writeSocket(const UInt8 *buffer, size_t size) { +size_t AutoArchSocket::writeSocket(const UInt8 *buffer, size_t size) +{ size_t result = 0; if (isValid()) { @@ -150,17 +166,25 @@ size_t AutoArchSocket::writeSocket(const UInt8 *buffer, size_t size) { return result; } -void AutoArchSocket::throwErrorOnSocket() { +void AutoArchSocket::throwErrorOnSocket() +{ if (isValid()) { ARCH->throwErrorOnSocket(m_socket); } } -ArchSocket AutoArchSocket::getRawSocket() const { return m_socket; } +ArchSocket AutoArchSocket::getRawSocket() const +{ + return m_socket; +} -bool AutoArchSocket::isValid() const { return (m_socket != nullptr); } +bool AutoArchSocket::isValid() const +{ + return (m_socket != nullptr); +} -void AutoArchSocket::operator=(ArchSocket socket) { +void AutoArchSocket::operator=(ArchSocket socket) +{ if (isValid()) { closeSocket(); } diff --git a/src/lib/net/InverseSockets/AutoArchSocket.h b/src/lib/net/InverseSockets/AutoArchSocket.h index 7e99d3dbf..ba2483c28 100644 --- a/src/lib/net/InverseSockets/AutoArchSocket.h +++ b/src/lib/net/InverseSockets/AutoArchSocket.h @@ -18,7 +18,8 @@ #pragma once #include "net/NetworkAddress.h" -class AutoArchSocket { +class AutoArchSocket +{ public: explicit AutoArchSocket(IArchNetwork::EAddressFamily family); ~AutoArchSocket(); diff --git a/src/lib/net/InverseSockets/InverseClientSocket.cpp b/src/lib/net/InverseSockets/InverseClientSocket.cpp index a5dba7e53..64795d3fa 100644 --- a/src/lib/net/InverseSockets/InverseClientSocket.cpp +++ b/src/lib/net/InverseSockets/InverseClientSocket.cpp @@ -38,16 +38,19 @@ // InverseClientSocket::InverseClientSocket( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, - IArchNetwork::EAddressFamily family) + IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family +) : IDataSocket(events), m_events(events), m_socket(family), m_listener(family), m_flushed(&m_mutex, true), - m_socketMultiplexer(socketMultiplexer) {} + m_socketMultiplexer(socketMultiplexer) +{ +} -InverseClientSocket::~InverseClientSocket() { +InverseClientSocket::~InverseClientSocket() +{ try { // warning virtual function in destructor is very danger practice InverseClientSocket::close(); @@ -56,22 +59,26 @@ InverseClientSocket::~InverseClientSocket() { } } -void InverseClientSocket::bind(const NetworkAddress &addr) { +void InverseClientSocket::bind(const NetworkAddress &addr) +{ m_socket.bindSocket(addr); } -void InverseClientSocket::close() { +void InverseClientSocket::close() +{ setJob(nullptr); Lock lock(&m_mutex); onDisconnected(); } -void *InverseClientSocket::getEventTarget() const { +void *InverseClientSocket::getEventTarget() const +{ return const_cast(static_cast(this)); } -UInt32 InverseClientSocket::read(void *buffer, UInt32 n) { +UInt32 InverseClientSocket::read(void *buffer, UInt32 n) +{ // copy data directly from our input buffer Lock lock(&m_mutex); UInt32 size = m_inputBuffer.getSize(); @@ -92,7 +99,8 @@ UInt32 InverseClientSocket::read(void *buffer, UInt32 n) { return n; } -void InverseClientSocket::write(const void *buffer, UInt32 n) { +void InverseClientSocket::write(const void *buffer, UInt32 n) +{ bool wasEmpty; { Lock lock(&m_mutex); @@ -122,14 +130,16 @@ void InverseClientSocket::write(const void *buffer, UInt32 n) { } } -void InverseClientSocket::flush() { +void InverseClientSocket::flush() +{ Lock lock(&m_mutex); while (m_flushed == false) { m_flushed.wait(); } } -void InverseClientSocket::shutdownInput() { +void InverseClientSocket::shutdownInput() +{ bool useNewJob = false; { Lock lock(&m_mutex); @@ -149,7 +159,8 @@ void InverseClientSocket::shutdownInput() { } } -void InverseClientSocket::shutdownOutput() { +void InverseClientSocket::shutdownOutput() +{ bool useNewJob = false; { Lock lock(&m_mutex); @@ -169,23 +180,27 @@ void InverseClientSocket::shutdownOutput() { } } -bool InverseClientSocket::isReady() const { +bool InverseClientSocket::isReady() const +{ Lock lock(&m_mutex); return (m_inputBuffer.getSize() > 0); } -bool InverseClientSocket::isFatal() const { +bool InverseClientSocket::isFatal() const +{ // TCP sockets aren't ever left in a fatal state. LOG((CLOG_ERR "isFatal() not valid for non-secure connections")); return false; } -UInt32 InverseClientSocket::getSize() const { +UInt32 InverseClientSocket::getSize() const +{ Lock lock(&m_mutex); return m_inputBuffer.getSize(); } -void InverseClientSocket::connect(const NetworkAddress &addr) { +void InverseClientSocket::connect(const NetworkAddress &addr) +{ { Lock lock(&m_mutex); m_listener.bindAndListen(addr); @@ -195,7 +210,8 @@ void InverseClientSocket::connect(const NetworkAddress &addr) { setJob(newJob(m_listener.getRawSocket())); } -InverseClientSocket::EJobResult InverseClientSocket::doRead() { +InverseClientSocket::EJobResult InverseClientSocket::doRead() +{ UInt8 buffer[4096] = {0}; size_t bytesRead = m_socket.readSocket(buffer, sizeof(buffer)); @@ -229,11 +245,11 @@ InverseClientSocket::EJobResult InverseClientSocket::doRead() { return InverseClientSocket::EJobResult::kRetry; } -InverseClientSocket::EJobResult InverseClientSocket::doWrite() { +InverseClientSocket::EJobResult InverseClientSocket::doWrite() +{ UInt32 bufferSize = m_outputBuffer.getSize(); auto buffer = static_cast(m_outputBuffer.peek(bufferSize)); - const auto bytesWrote = - static_cast(m_socket.writeSocket(buffer, bufferSize)); + const auto bytesWrote = static_cast(m_socket.writeSocket(buffer, bufferSize)); if (bytesWrote > 0) { discardWrittenData(bytesWrote); @@ -243,7 +259,8 @@ InverseClientSocket::EJobResult InverseClientSocket::doWrite() { return InverseClientSocket::EJobResult::kRetry; } -void InverseClientSocket::setJob(ISocketMultiplexerJob *job) { +void InverseClientSocket::setJob(ISocketMultiplexerJob *job) +{ // multiplexer will delete the old job if (job == nullptr) { m_socketMultiplexer->removeSocket(this); @@ -252,7 +269,8 @@ void InverseClientSocket::setJob(ISocketMultiplexerJob *job) { } } -ISocketMultiplexerJob *InverseClientSocket::newJob(ArchSocket socket) { +ISocketMultiplexerJob *InverseClientSocket::newJob(ArchSocket socket) +{ // note -- must have m_mutex locked on entry ISocketMultiplexerJob *result = nullptr; @@ -267,26 +285,27 @@ ISocketMultiplexerJob *InverseClientSocket::newJob(ArchSocket socket) { } if (m_readable || isWritable) { - result = new TSocketMultiplexerMethodJob( - this, handler, socket, m_readable, isWritable); + result = new TSocketMultiplexerMethodJob(this, handler, socket, m_readable, isWritable); } } return result; } -void InverseClientSocket::sendConnectionFailedEvent(const char *msg) { +void InverseClientSocket::sendConnectionFailedEvent(const char *msg) +{ auto info = new ConnectionFailedInfo(msg); - m_events->addEvent(Event( - m_events->forIDataSocket().connectionFailed(), getEventTarget(), info, - Event::kDontFreeData)); + m_events->addEvent(Event(m_events->forIDataSocket().connectionFailed(), getEventTarget(), info, Event::kDontFreeData) + ); } -void InverseClientSocket::sendEvent(Event::Type type) { +void InverseClientSocket::sendEvent(Event::Type type) +{ m_events->addEvent(Event(type, getEventTarget())); } -void InverseClientSocket::discardWrittenData(int bytesWrote) { +void InverseClientSocket::discardWrittenData(int bytesWrote) +{ m_outputBuffer.pop(bytesWrote); if (m_outputBuffer.getSize() == 0) { sendEvent(m_events->forIStream().outputFlushed()); @@ -295,19 +314,22 @@ void InverseClientSocket::discardWrittenData(int bytesWrote) { } } -void InverseClientSocket::onConnected() { +void InverseClientSocket::onConnected() +{ sendEvent(m_events->forIDataSocket().connected()); m_connected = true; m_readable = true; m_writable = true; } -void InverseClientSocket::onInputShutdown() { +void InverseClientSocket::onInputShutdown() +{ m_inputBuffer.pop(m_inputBuffer.getSize()); m_readable = false; } -void InverseClientSocket::onOutputShutdown() { +void InverseClientSocket::onOutputShutdown() +{ m_outputBuffer.pop(m_outputBuffer.getSize()); m_writable = false; @@ -316,7 +338,8 @@ void InverseClientSocket::onOutputShutdown() { m_flushed.broadcast(); } -void InverseClientSocket::onDisconnected() { +void InverseClientSocket::onDisconnected() +{ if (m_connected) { sendEvent(m_events->forISocket().disconnected()); } @@ -326,8 +349,8 @@ void InverseClientSocket::onDisconnected() { m_connected = false; } -ISocketMultiplexerJob *InverseClientSocket::serviceConnecting( - ISocketMultiplexerJob *job, bool read, bool, bool) { +ISocketMultiplexerJob *InverseClientSocket::serviceConnecting(ISocketMultiplexerJob *job, bool read, bool, bool) +{ Lock lock(&m_mutex); if (read) { @@ -339,8 +362,9 @@ ISocketMultiplexerJob *InverseClientSocket::serviceConnecting( return job; } -ISocketMultiplexerJob *InverseClientSocket::serviceConnected( - ISocketMultiplexerJob *job, bool read, bool write, bool error) { +ISocketMultiplexerJob * +InverseClientSocket::serviceConnected(ISocketMultiplexerJob *job, bool read, bool write, bool error) +{ Lock lock(&m_mutex); if (error) { @@ -392,7 +416,5 @@ ISocketMultiplexerJob *InverseClientSocket::serviceConnected( return nullptr; } - return result == InverseClientSocket::EJobResult::kNew - ? newJob(m_socket.getRawSocket()) - : job; + return result == InverseClientSocket::EJobResult::kNew ? newJob(m_socket.getRawSocket()) : job; } diff --git a/src/lib/net/InverseSockets/InverseClientSocket.h b/src/lib/net/InverseSockets/InverseClientSocket.h index fd0383df9..59de91a77 100644 --- a/src/lib/net/InverseSockets/InverseClientSocket.h +++ b/src/lib/net/InverseSockets/InverseClientSocket.h @@ -29,11 +29,13 @@ class ISocketMultiplexerJob; class IEventQueue; class SocketMultiplexer; -class InverseClientSocket : public IDataSocket { +class InverseClientSocket : public IDataSocket +{ public: InverseClientSocket( IEventQueue *events, SocketMultiplexer *socketMultiplexer, - IArchNetwork::EAddressFamily family = IArchNetwork::kINET); + IArchNetwork::EAddressFamily family = IArchNetwork::kINET + ); InverseClientSocket(InverseClientSocket const &) = delete; InverseClientSocket(InverseClientSocket &&) = delete; ~InverseClientSocket() override; @@ -62,23 +64,39 @@ public: virtual ISocketMultiplexerJob *newJob(ArchSocket socket); protected: - enum class EJobResult { + enum class EJobResult + { kBreak = -1, //!< Break the Job chain kRetry, //!< Retry the same job kNew //!< Require a new job }; - ArchSocket getSocket() { return m_socket.getRawSocket(); } - IEventQueue *getEvents() { return m_events; } + ArchSocket getSocket() + { + return m_socket.getRawSocket(); + } + IEventQueue *getEvents() + { + return m_events; + } virtual EJobResult doRead(); virtual EJobResult doWrite(); void setJob(ISocketMultiplexerJob *); - bool isReadable() const { return m_readable; } - bool isWritable() const { return m_writable; } + bool isReadable() const + { + return m_readable; + } + bool isWritable() const + { + return m_writable; + } - Mutex &getMutex() { return m_mutex; } + Mutex &getMutex() + { + return m_mutex; + } void sendEvent(Event::Type); void discardWrittenData(int bytesWrote); @@ -90,10 +108,8 @@ private: void onOutputShutdown(); void onDisconnected(); - ISocketMultiplexerJob * - serviceConnecting(ISocketMultiplexerJob *, bool, bool, bool); - ISocketMultiplexerJob * - serviceConnected(ISocketMultiplexerJob *, bool, bool, bool); + ISocketMultiplexerJob *serviceConnecting(ISocketMultiplexerJob *, bool, bool, bool); + ISocketMultiplexerJob *serviceConnected(ISocketMultiplexerJob *, bool, bool, bool); protected: bool m_readable = false; diff --git a/src/lib/net/InverseSockets/InverseServerSocket.cpp b/src/lib/net/InverseSockets/InverseServerSocket.cpp index c4a447adf..771c4b319 100644 --- a/src/lib/net/InverseSockets/InverseServerSocket.cpp +++ b/src/lib/net/InverseSockets/InverseServerSocket.cpp @@ -36,38 +36,44 @@ // InverseServerSocket::InverseServerSocket( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, - IArchNetwork::EAddressFamily family) + IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family +) : m_socket(family), m_events(events), - m_socketMultiplexer(socketMultiplexer) {} + m_socketMultiplexer(socketMultiplexer) +{ +} -InverseServerSocket::~InverseServerSocket() { +InverseServerSocket::~InverseServerSocket() +{ m_socketMultiplexer->removeSocket(this); } -void InverseServerSocket::bind(const NetworkAddress &addr) { +void InverseServerSocket::bind(const NetworkAddress &addr) +{ Lock lock(&m_mutex); m_address = addr; m_socket.connectSocket(m_address); setListeningJob(true); } -void InverseServerSocket::close() { +void InverseServerSocket::close() +{ Lock lock(&m_mutex); m_socketMultiplexer->removeSocket(this); m_socket.closeSocket(); } -void *InverseServerSocket::getEventTarget() const { +void *InverseServerSocket::getEventTarget() const +{ return const_cast(static_cast(this)); } -IDataSocket *InverseServerSocket::accept() { +IDataSocket *InverseServerSocket::accept() +{ IDataSocket *socket = nullptr; try { - socket = - new TCPSocket(m_events, m_socketMultiplexer, m_socket.getRawSocket()); + socket = new TCPSocket(m_events, m_socketMultiplexer, m_socket.getRawSocket()); if (socket != nullptr) { setListeningJob(); } @@ -87,15 +93,17 @@ IDataSocket *InverseServerSocket::accept() { } } -void InverseServerSocket::setListeningJob(bool read) { +void InverseServerSocket::setListeningJob(bool read) +{ m_socketMultiplexer->addSocket( this, new TSocketMultiplexerMethodJob( - this, &InverseServerSocket::serviceListening, - m_socket.getRawSocket(), true, read)); + this, &InverseServerSocket::serviceListening, m_socket.getRawSocket(), true, read + ) + ); } -ISocketMultiplexerJob *InverseServerSocket::serviceListening( - ISocketMultiplexerJob *job, bool, bool write, bool error) { +ISocketMultiplexerJob *InverseServerSocket::serviceListening(ISocketMultiplexerJob *job, bool, bool write, bool error) +{ if (error) { m_socket.connectSocket(m_address); return job; diff --git a/src/lib/net/InverseSockets/InverseServerSocket.h b/src/lib/net/InverseSockets/InverseServerSocket.h index f1eb7089f..a0f88a41b 100644 --- a/src/lib/net/InverseSockets/InverseServerSocket.h +++ b/src/lib/net/InverseSockets/InverseServerSocket.h @@ -27,11 +27,10 @@ class ISocketMultiplexerJob; class IEventQueue; class SocketMultiplexer; -class InverseServerSocket : public IListenSocket { +class InverseServerSocket : public IListenSocket +{ public: - InverseServerSocket( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, - IArchNetwork::EAddressFamily family); + InverseServerSocket(IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family); InverseServerSocket(InverseServerSocket const &) = delete; InverseServerSocket(InverseServerSocket &&) = delete; ~InverseServerSocket() override; @@ -51,8 +50,7 @@ protected: void setListeningJob(bool read = false); public: - ISocketMultiplexerJob * - serviceListening(ISocketMultiplexerJob *, bool, bool, bool); + ISocketMultiplexerJob *serviceListening(ISocketMultiplexerJob *, bool, bool, bool); protected: AutoArchSocket m_socket; diff --git a/src/lib/net/InverseSockets/InverseSocketFactory.cpp b/src/lib/net/InverseSockets/InverseSocketFactory.cpp index 4c4331596..727d2bd82 100644 --- a/src/lib/net/InverseSockets/InverseSocketFactory.cpp +++ b/src/lib/net/InverseSockets/InverseSocketFactory.cpp @@ -24,24 +24,24 @@ // InverseSocketFactory // -InverseSocketFactory::InverseSocketFactory( - IEventQueue *events, SocketMultiplexer *socketMultiplexer) +InverseSocketFactory::InverseSocketFactory(IEventQueue *events, SocketMultiplexer *socketMultiplexer) : m_events(events), - m_socketMultiplexer(socketMultiplexer) {} + m_socketMultiplexer(socketMultiplexer) +{ +} -IDataSocket *InverseSocketFactory::create( - bool secure, IArchNetwork::EAddressFamily family) const { +IDataSocket *InverseSocketFactory::create(bool secure, IArchNetwork::EAddressFamily family) const +{ if (secure) { - auto secureSocket = - new SecureClientSocket(m_events, m_socketMultiplexer, family); + auto secureSocket = new SecureClientSocket(m_events, m_socketMultiplexer, family); return secureSocket; } else { return new InverseClientSocket(m_events, m_socketMultiplexer, family); } } -IListenSocket *InverseSocketFactory::createListen( - bool secure, IArchNetwork::EAddressFamily family) const { +IListenSocket *InverseSocketFactory::createListen(bool secure, IArchNetwork::EAddressFamily family) const +{ IListenSocket *socket = nullptr; if (secure) { diff --git a/src/lib/net/InverseSockets/InverseSocketFactory.h b/src/lib/net/InverseSockets/InverseSocketFactory.h index d32df6f3f..38b2153ce 100644 --- a/src/lib/net/InverseSockets/InverseSocketFactory.h +++ b/src/lib/net/InverseSockets/InverseSocketFactory.h @@ -20,18 +20,14 @@ class IEventQueue; class SocketMultiplexer; -class InverseSocketFactory : public ISocketFactory { +class InverseSocketFactory : public ISocketFactory +{ public: - InverseSocketFactory( - IEventQueue *events, SocketMultiplexer *socketMultiplexer); + InverseSocketFactory(IEventQueue *events, SocketMultiplexer *socketMultiplexer); // ISocketFactory overrides - IDataSocket *create( - bool secure, - IArchNetwork::EAddressFamily family = IArchNetwork::kINET) const override; - IListenSocket *createListen( - bool secure, - IArchNetwork::EAddressFamily family = IArchNetwork::kINET) const override; + IDataSocket *create(bool secure, IArchNetwork::EAddressFamily family = IArchNetwork::kINET) const override; + IListenSocket *createListen(bool secure, IArchNetwork::EAddressFamily family = IArchNetwork::kINET) const override; private: IEventQueue *m_events = nullptr; diff --git a/src/lib/net/InverseSockets/SecureClientSocket.cpp b/src/lib/net/InverseSockets/SecureClientSocket.cpp index 846dda90a..adbf3edaa 100644 --- a/src/lib/net/InverseSockets/SecureClientSocket.cpp +++ b/src/lib/net/InverseSockets/SecureClientSocket.cpp @@ -41,20 +41,24 @@ constexpr float s_retryDelay = 0.01f; SecureClientSocket::SecureClientSocket( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, - IArchNetwork::EAddressFamily family) - : InverseClientSocket(events, socketMultiplexer, family) {} + IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family +) + : InverseClientSocket(events, socketMultiplexer, family) +{ +} -void SecureClientSocket::connect(const NetworkAddress &addr) { +void SecureClientSocket::connect(const NetworkAddress &addr) +{ m_events->adoptHandler( m_events->forIDataSocket().connected(), getEventTarget(), - new TMethodEventJob( - this, &SecureClientSocket::handleTCPConnected)); + new TMethodEventJob(this, &SecureClientSocket::handleTCPConnected) + ); InverseClientSocket::connect(addr); } -ISocketMultiplexerJob *SecureClientSocket::newJob() { +ISocketMultiplexerJob *SecureClientSocket::newJob() +{ // after TCP connection is established, SecureClientSocket will pick up // connected event and do secureConnect if (m_connected && !m_secureReady) { @@ -64,19 +68,22 @@ ISocketMultiplexerJob *SecureClientSocket::newJob() { return InverseClientSocket::newJob(getSocket()); } -void SecureClientSocket::secureConnect() { +void SecureClientSocket::secureConnect() +{ setJob(new TSocketMultiplexerMethodJob( - this, &SecureClientSocket::serviceConnect, getSocket(), isReadable(), - isWritable())); + this, &SecureClientSocket::serviceConnect, getSocket(), isReadable(), isWritable() + )); } -void SecureClientSocket::secureAccept() { +void SecureClientSocket::secureAccept() +{ setJob(new TSocketMultiplexerMethodJob( - this, &SecureClientSocket::serviceAccept, getSocket(), isReadable(), - isWritable())); + this, &SecureClientSocket::serviceAccept, getSocket(), isReadable(), isWritable() + )); } -InverseClientSocket::EJobResult SecureClientSocket::doRead() { +InverseClientSocket::EJobResult SecureClientSocket::doRead() +{ UInt8 buffer[4096] = {0}; int bytesRead = 0; int status = 0; @@ -126,7 +133,8 @@ InverseClientSocket::EJobResult SecureClientSocket::doRead() { return InverseClientSocket::EJobResult::kRetry; } -InverseClientSocket::EJobResult SecureClientSocket::doWrite() { +InverseClientSocket::EJobResult SecureClientSocket::doWrite() +{ static bool s_retry = false; static int s_retrySize = 0; static int s_staticBufferSize = 0; @@ -177,7 +185,8 @@ InverseClientSocket::EJobResult SecureClientSocket::doWrite() { return InverseClientSocket::EJobResult::kRetry; } -int SecureClientSocket::secureRead(void *buffer, int size, int &read) { +int SecureClientSocket::secureRead(void *buffer, int size, int &read) +{ LOG((CLOG_DEBUG2 "reading secure socket")); read = m_ssl.read(static_cast(buffer), size); @@ -199,7 +208,8 @@ int SecureClientSocket::secureRead(void *buffer, int size, int &read) { return read; } -int SecureClientSocket::secureWrite(const void *buffer, int size, int &wrote) { +int SecureClientSocket::secureWrite(const void *buffer, int size, int &wrote) +{ LOG((CLOG_DEBUG2 "writing secure socket: %p", this)); wrote = m_ssl.write(static_cast(buffer), size); @@ -222,13 +232,18 @@ int SecureClientSocket::secureWrite(const void *buffer, int size, int &wrote) { return wrote; } -bool SecureClientSocket::isSecureReady() const { return m_secureReady; } +bool SecureClientSocket::isSecureReady() const +{ + return m_secureReady; +} -bool SecureClientSocket::loadCertificates(const std::string &filename) { +bool SecureClientSocket::loadCertificates(const std::string &filename) +{ return m_ssl.loadCertificate(filename); } -int SecureClientSocket::secureAccept(int socket) { +int SecureClientSocket::secureAccept(int socket) +{ LOG((CLOG_DEBUG2 "accepting secure socket")); static int retry = 0; checkResult(m_ssl.accept(socket), retry); @@ -264,7 +279,8 @@ int SecureClientSocket::secureAccept(int socket) { return -1; } -int SecureClientSocket::secureConnect(int socket) { +int SecureClientSocket::secureConnect(int socket) +{ LOG((CLOG_DEBUG2 "connecting secure socket")); static int retry = 0; checkResult(m_ssl.connect(socket), retry); @@ -302,17 +318,19 @@ int SecureClientSocket::secureConnect(int socket) { } } -void SecureClientSocket::setFatal(int code) { +void SecureClientSocket::setFatal(int code) +{ const std::set nonFatal{ - SSL_ERROR_NONE, SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE, - SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT}; + SSL_ERROR_NONE, SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT + }; m_fatal = nonFatal.find(code) == nonFatal.end(); } -int SecureClientSocket::getRetry(int errorCode, int retry) const { +int SecureClientSocket::getRetry(int errorCode, int retry) const +{ const std::set retryCodes{ - SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_CONNECT, - SSL_ERROR_WANT_ACCEPT}; + SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT + }; if (errorCode == SSL_ERROR_NONE || isFatal()) { retry = 0; @@ -323,7 +341,8 @@ int SecureClientSocket::getRetry(int errorCode, int retry) const { return retry; } -void SecureClientSocket::checkResult(int status, int &retry) { +void SecureClientSocket::checkResult(int status, int &retry) +{ // ssl errors are a little quirky. the "want" errors are normal and // should result in a retry. int errorCode = m_ssl.getErrorCode(status); @@ -364,14 +383,15 @@ void SecureClientSocket::checkResult(int status, int &retry) { } } -void SecureClientSocket::disconnect() { +void SecureClientSocket::disconnect() +{ sendEvent(getEvents()->forISocket().stopRetry()); sendEvent(getEvents()->forISocket().disconnected()); sendEvent(getEvents()->forIStream().inputShutdown()); } -ISocketMultiplexerJob * -SecureClientSocket::serviceConnect(ISocketMultiplexerJob *, bool, bool, bool) { +ISocketMultiplexerJob *SecureClientSocket::serviceConnect(ISocketMultiplexerJob *, bool, bool, bool) +{ Lock lock(&getMutex()); int status = 0; @@ -395,12 +415,12 @@ SecureClientSocket::serviceConnect(ISocketMultiplexerJob *, bool, bool, bool) { // Retry case return new TSocketMultiplexerMethodJob( - this, &SecureClientSocket::serviceConnect, getSocket(), isReadable(), - isWritable()); + this, &SecureClientSocket::serviceConnect, getSocket(), isReadable(), isWritable() + ); } -ISocketMultiplexerJob * -SecureClientSocket::serviceAccept(ISocketMultiplexerJob *, bool, bool, bool) { +ISocketMultiplexerJob *SecureClientSocket::serviceAccept(ISocketMultiplexerJob *, bool, bool, bool) +{ Lock lock(&getMutex()); int status = 0; @@ -422,11 +442,12 @@ SecureClientSocket::serviceAccept(ISocketMultiplexerJob *, bool, bool, bool) { // Retry case return new TSocketMultiplexerMethodJob( - this, &SecureClientSocket::serviceAccept, getSocket(), isReadable(), - isWritable()); + this, &SecureClientSocket::serviceAccept, getSocket(), isReadable(), isWritable() + ); } -void SecureClientSocket::handleTCPConnected(const Event &, void *) { +void SecureClientSocket::handleTCPConnected(const Event &, void *) +{ if (getSocket()) { secureConnect(); } else { diff --git a/src/lib/net/InverseSockets/SecureClientSocket.h b/src/lib/net/InverseSockets/SecureClientSocket.h index cd3b3a2c7..fd2eaa7ff 100644 --- a/src/lib/net/InverseSockets/SecureClientSocket.h +++ b/src/lib/net/InverseSockets/SecureClientSocket.h @@ -22,11 +22,10 @@ /*! A secure socket using SSL. */ -class SecureClientSocket : public InverseClientSocket { +class SecureClientSocket : public InverseClientSocket +{ public: - SecureClientSocket( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, - IArchNetwork::EAddressFamily family); + SecureClientSocket(IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family); SecureClientSocket(SecureClientSocket const &) = delete; SecureClientSocket(SecureClientSocket &&) = delete; @@ -37,7 +36,10 @@ public: void connect(const NetworkAddress &) override; ISocketMultiplexerJob *newJob(); - bool isFatal() const override { return m_fatal; } + bool isFatal() const override + { + return m_fatal; + } void setFatal(int code); int getRetry(int errorCode, int retry) const; bool isSecureReady() const; @@ -57,11 +59,9 @@ private: void checkResult(int n, int &retry); void disconnect(); - ISocketMultiplexerJob * - serviceConnect(ISocketMultiplexerJob *, bool, bool, bool); + ISocketMultiplexerJob *serviceConnect(ISocketMultiplexerJob *, bool, bool, bool); - ISocketMultiplexerJob * - serviceAccept(ISocketMultiplexerJob *, bool, bool, bool); + ISocketMultiplexerJob *serviceAccept(ISocketMultiplexerJob *, bool, bool, bool); void handleTCPConnected(const Event &, void *); diff --git a/src/lib/net/InverseSockets/SecureServerSocket.cpp b/src/lib/net/InverseSockets/SecureServerSocket.cpp index f152f4687..923feab80 100644 --- a/src/lib/net/InverseSockets/SecureServerSocket.cpp +++ b/src/lib/net/InverseSockets/SecureServerSocket.cpp @@ -27,16 +27,18 @@ // SecureServerSocket // SecureServerSocket::SecureServerSocket( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, - IArchNetwork::EAddressFamily family) - : InverseServerSocket(events, socketMultiplexer, family) {} + IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family +) + : InverseServerSocket(events, socketMultiplexer, family) +{ +} -IDataSocket *SecureServerSocket::accept() { +IDataSocket *SecureServerSocket::accept() +{ SecureSocket *socket = nullptr; try { - socket = new SecureSocket( - m_events, m_socketMultiplexer, m_socket.getRawSocket()); + socket = new SecureSocket(m_events, m_socketMultiplexer, m_socket.getRawSocket()); socket->initSsl(true); setListeningJob(); @@ -64,15 +66,16 @@ IDataSocket *SecureServerSocket::accept() { return dynamic_cast(socket); } -std::string SecureServerSocket::getCertificateFileName() const { +std::string SecureServerSocket::getCertificateFileName() const +{ // if the tls cert option is set use that for the certificate file auto certificateFilename = ArgParser::argsBase().m_tlsCertFile; if (certificateFilename.empty()) { // TODO: Reduce duplication of these strings between here and // SecureSocket.cpp - certificateFilename = deskflow::string::sprintf( - "%s/tls/" DESKFLOW_APP_ID ".pem", ARCH->getProfileDirectory().c_str()); + certificateFilename = + deskflow::string::sprintf("%s/tls/" DESKFLOW_APP_ID ".pem", ARCH->getProfileDirectory().c_str()); } return certificateFilename; diff --git a/src/lib/net/InverseSockets/SecureServerSocket.h b/src/lib/net/InverseSockets/SecureServerSocket.h index e70c90ab1..958b8fa93 100644 --- a/src/lib/net/InverseSockets/SecureServerSocket.h +++ b/src/lib/net/InverseSockets/SecureServerSocket.h @@ -17,11 +17,10 @@ #pragma once #include "InverseServerSocket.h" -class SecureServerSocket : public InverseServerSocket { +class SecureServerSocket : public InverseServerSocket +{ public: - SecureServerSocket( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, - IArchNetwork::EAddressFamily family); + SecureServerSocket(IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family); // IListenSocket overrides IDataSocket *accept() override; diff --git a/src/lib/net/InverseSockets/SslApi.cpp b/src/lib/net/InverseSockets/SslApi.cpp index b593c7eb0..3a8d51dc5 100644 --- a/src/lib/net/InverseSockets/SslApi.cpp +++ b/src/lib/net/InverseSockets/SslApi.cpp @@ -13,7 +13,8 @@ namespace ssl { using AutoX509 = std::unique_ptr; -SslApi::SslApi(bool isServer) { +SslApi::SslApi(bool isServer) +{ SSL_library_init(); // load & register all cryptos, etc. OpenSSL_add_all_algorithms(); @@ -23,7 +24,8 @@ SslApi::SslApi(bool isServer) { SslLogger::logSecureLibInfo(); } -SslApi::~SslApi() { +SslApi::~SslApi() +{ if (m_ssl) { SSL_shutdown(m_ssl); SSL_free(m_ssl); @@ -36,7 +38,8 @@ SslApi::~SslApi() { } } -int SslApi::read(char *buffer, int size) { +int SslApi::read(char *buffer, int size) +{ auto read = 0; if (m_ssl) { @@ -46,7 +49,8 @@ int SslApi::read(char *buffer, int size) { return read; } -int SslApi::write(const char *buffer, int size) { +int SslApi::write(const char *buffer, int size) +{ auto wrote = 0; if (m_ssl) { @@ -56,7 +60,8 @@ int SslApi::write(const char *buffer, int size) { return wrote; } -int SslApi::accept(int socket) { +int SslApi::accept(int socket) +{ int result = 0; if (m_ssl) { @@ -68,7 +73,8 @@ int SslApi::accept(int socket) { return result; } -int SslApi::connect(int socket) { +int SslApi::connect(int socket) +{ auto result = 0; if (m_ssl) { @@ -80,25 +86,25 @@ int SslApi::connect(int socket) { return result; } -void SslApi::createSSL() { +void SslApi::createSSL() +{ if (m_ssl == nullptr && m_context != nullptr) { m_ssl = SSL_new(m_context); } } -bool SslApi::loadCertificate(const std::string &filename) { +bool SslApi::loadCertificate(const std::string &filename) +{ bool result = false; if (isCertificateExists(filename)) { - auto r = SSL_CTX_use_certificate_file( - m_context, filename.c_str(), SSL_FILETYPE_PEM); + auto r = SSL_CTX_use_certificate_file(m_context, filename.c_str(), SSL_FILETYPE_PEM); if (r <= 0) { SslLogger::logError("could not use tls certificate"); return false; } - r = SSL_CTX_use_PrivateKey_file( - m_context, filename.c_str(), SSL_FILETYPE_PEM); + r = SSL_CTX_use_PrivateKey_file(m_context, filename.c_str(), SSL_FILETYPE_PEM); if (r <= 0) { SslLogger::logError("could not use tls private key"); return false; @@ -114,15 +120,15 @@ bool SslApi::loadCertificate(const std::string &filename) { return result; } -bool SslApi::showCertificate() const { +bool SslApi::showCertificate() const +{ bool result = false; if (m_ssl) { // get the server's certificate AutoX509 cert(SSL_get_peer_certificate(m_ssl), &X509_free); if (cert) { - auto line = - X509_NAME_oneline(X509_get_subject_name(cert.get()), nullptr, 0); + auto line = X509_NAME_oneline(X509_get_subject_name(cert.get()), nullptr, 0); LOG((CLOG_INFO "server tls certificate info: %s", line)); OPENSSL_free(line); result = true; @@ -134,34 +140,31 @@ bool SslApi::showCertificate() const { return result; } -std::string SslApi::getFingerprint() const { +std::string SslApi::getFingerprint() const +{ // calculate received certificate fingerprint AutoX509 cert(SSL_get_peer_certificate(m_ssl), &X509_free); unsigned int tempFingerprintLen = 0; unsigned char tempFingerprint[EVP_MAX_MD_SIZE] = {0}; - int digestResult = X509_digest( - cert.get(), EVP_sha256(), tempFingerprint, &tempFingerprintLen); + int digestResult = X509_digest(cert.get(), EVP_sha256(), tempFingerprint, &tempFingerprintLen); if (digestResult <= 0) { - LOG( - (CLOG_ERR "failed to calculate fingerprint, digest result: %d", - digestResult)); + LOG((CLOG_ERR "failed to calculate fingerprint, digest result: %d", digestResult)); return ""; } // format fingerprint into hexdecimal format with colon separator - std::string fingerprint( - static_cast(static_cast(tempFingerprint)), - tempFingerprintLen); + std::string fingerprint(static_cast(static_cast(tempFingerprint)), tempFingerprintLen); formatFingerprint(fingerprint); return fingerprint; } -bool SslApi::isTrustedFingerprint(const std::string &fingerprint) const { +bool SslApi::isTrustedFingerprint(const std::string &fingerprint) const +{ // TODO: Reduce duplication of these strings between here and SecureSocket.cpp - auto trustedServersFilename = deskflow::string::sprintf( - "%s/tls/trusted-servers", ARCH->getProfileDirectory().c_str()); + auto trustedServersFilename = + deskflow::string::sprintf("%s/tls/trusted-servers", ARCH->getProfileDirectory().c_str()); // check if this fingerprint exist std::ifstream file; @@ -178,15 +181,14 @@ bool SslApi::isTrustedFingerprint(const std::string &fingerprint) const { } } } else { - LOG( - (CLOG_ERR "failed to open trusted fingerprints file: %s", - trustedServersFilename.c_str())); + LOG((CLOG_ERR "failed to open trusted fingerprints file: %s", trustedServersFilename.c_str())); } return (isValid && showCertificate()); } -void SslApi::createContext(bool isServer) { +void SslApi::createContext(bool isServer) +{ // create new context from method if (isServer) { m_context = SSL_CTX_new(SSLv23_server_method()); @@ -195,9 +197,7 @@ void SslApi::createContext(bool isServer) { } // Prevent the usage of of all version prior to TLSv1.2 as they are known to // be vulnerable - SSL_CTX_set_options( - m_context, - SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1); + SSL_CTX_set_options(m_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1); if (m_context) { m_ssl = SSL_new(m_context); @@ -206,16 +206,19 @@ void SslApi::createContext(bool isServer) { } } -void SslApi::logSecureInfo() const { +void SslApi::logSecureInfo() const +{ SslLogger::logSecureCipherInfo(m_ssl); SslLogger::logSecureConnectInfo(m_ssl); } -int SslApi::getErrorCode(int status) const { +int SslApi::getErrorCode(int status) const +{ return SSL_get_error(m_ssl, status); } -void SslApi::formatFingerprint(std::string &fingerprint) const { +void SslApi::formatFingerprint(std::string &fingerprint) const +{ // to hexidecimal deskflow::string::toHex(fingerprint, 2); // all uppercase @@ -227,7 +230,8 @@ void SslApi::formatFingerprint(std::string &fingerprint) const { } } -bool SslApi::isCertificateExists(const std::string &filename) const { +bool SslApi::isCertificateExists(const std::string &filename) const +{ bool result = (!filename.empty()); if (result) { diff --git a/src/lib/net/InverseSockets/SslApi.h b/src/lib/net/InverseSockets/SslApi.h index c28a84a2e..7bb707b6a 100644 --- a/src/lib/net/InverseSockets/SslApi.h +++ b/src/lib/net/InverseSockets/SslApi.h @@ -21,7 +21,8 @@ namespace deskflow { namespace ssl { -class SslApi { +class SslApi +{ public: explicit SslApi(bool isServer = false); SslApi(SslApi const &) = delete; diff --git a/src/lib/net/InverseSockets/SslLogger.cpp b/src/lib/net/InverseSockets/SslLogger.cpp index 47c406639..bc29245ab 100644 --- a/src/lib/net/InverseSockets/SslLogger.cpp +++ b/src/lib/net/InverseSockets/SslLogger.cpp @@ -24,7 +24,8 @@ namespace { -void showCipherStackDesc(STACK_OF(SSL_CIPHER) * stack) { +void showCipherStackDesc(STACK_OF(SSL_CIPHER) * stack) +{ char msg[128] = {0}; for (int i = 0; i < sk_SSL_CIPHER_num(stack); ++i) { auto cipher = sk_SSL_CIPHER_value(stack, i); @@ -40,7 +41,8 @@ void showCipherStackDesc(STACK_OF(SSL_CIPHER) * stack) { } } -void logLocalSecureCipherInfo(const SSL *ssl) { +void logLocalSecureCipherInfo(const SSL *ssl) +{ auto sStack = SSL_get_ciphers(ssl); if (sStack) { @@ -51,7 +53,8 @@ void logLocalSecureCipherInfo(const SSL *ssl) { } } -void logRemoteSecureCipherInfo(const SSL *ssl) { +void logRemoteSecureCipherInfo(const SSL *ssl) +{ #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER) // ssl->session->ciphers is not forward compatable, // In future release of OpenSSL, it's not visible, @@ -71,7 +74,8 @@ void logRemoteSecureCipherInfo(const SSL *ssl) { } // namespace -void SslLogger::logSecureLibInfo() { +void SslLogger::logSecureLibInfo() +{ if (CLOG->getFilter() >= kDEBUG) { LOG((CLOG_DEBUG "openssl version: %s", SSLeay_version(SSLEAY_VERSION))); LOG((CLOG_DEBUG1 "openssl flags: %s", SSLeay_version(SSLEAY_CFLAGS))); @@ -81,14 +85,16 @@ void SslLogger::logSecureLibInfo() { } } -void SslLogger::logSecureCipherInfo(const SSL *ssl) { +void SslLogger::logSecureCipherInfo(const SSL *ssl) +{ if (ssl && CLOG->getFilter() >= kDEBUG1) { logLocalSecureCipherInfo(ssl); logRemoteSecureCipherInfo(ssl); } } -void SslLogger::logSecureConnectInfo(const SSL *ssl) { +void SslLogger::logSecureConnectInfo(const SSL *ssl) +{ if (ssl) { auto cipher = SSL_get_current_cipher(ssl); @@ -107,8 +113,8 @@ void SslLogger::logSecureConnectInfo(const SSL *ssl) { // Take the stream input and splits it into a vetor directly const std::vector parts{ - std::istream_iterator{iss}, - std::istream_iterator{}}; + std::istream_iterator{iss}, std::istream_iterator{} + }; if (parts.size() > 2) { // log the section containing the protocol version LOG((CLOG_INFO "network encryption protocol: %s", parts[1].c_str())); @@ -124,7 +130,8 @@ void SslLogger::logSecureConnectInfo(const SSL *ssl) { } } -void SslLogger::logError(const std::string &reason) { +void SslLogger::logError(const std::string &reason) +{ if (!reason.empty()) { LOG((CLOG_ERR "secure socket error: %s", reason.c_str())); } @@ -137,7 +144,8 @@ void SslLogger::logError(const std::string &reason) { } } -void SslLogger::logErrorByCode(int code, int retry) { +void SslLogger::logErrorByCode(int code, int retry) +{ switch (code) { case SSL_ERROR_NONE: break; diff --git a/src/lib/net/InverseSockets/SslLogger.h b/src/lib/net/InverseSockets/SslLogger.h index d698b63e7..86c5b9397 100644 --- a/src/lib/net/InverseSockets/SslLogger.h +++ b/src/lib/net/InverseSockets/SslLogger.h @@ -18,7 +18,8 @@ #include #include -class SslLogger { +class SslLogger +{ public: static void logSecureLibInfo(); static void logSecureCipherInfo(const SSL *ssl); diff --git a/src/lib/net/NetworkAddress.cpp b/src/lib/net/NetworkAddress.cpp index e96debb6f..e747d72d0 100644 --- a/src/lib/net/NetworkAddress.cpp +++ b/src/lib/net/NetworkAddress.cpp @@ -31,25 +31,23 @@ // name re-resolution adapted from a patch by Brent Priddy. -NetworkAddress::NetworkAddress(int port) : m_port(port) { +NetworkAddress::NetworkAddress(int port) : m_port(port) +{ checkPort(); m_address = ARCH->newAnyAddr(IArchNetwork::kINET); ARCH->setAddrPort(m_address, m_port); } -NetworkAddress::NetworkAddress(const NetworkAddress &addr) - : m_hostname(addr.m_hostname), - m_port(addr.m_port) { +NetworkAddress::NetworkAddress(const NetworkAddress &addr) : m_hostname(addr.m_hostname), m_port(addr.m_port) +{ *this = addr; } -NetworkAddress::NetworkAddress(const String &hostname, int port) - : m_hostname(hostname), - m_port(port) { +NetworkAddress::NetworkAddress(const String &hostname, int port) : m_hostname(hostname), m_port(port) +{ // detect internet protocol version with colom count auto isColomPredicate = [](char c) { return c == ':'; }; - auto colomCount = - std::count_if(m_hostname.begin(), m_hostname.end(), isColomPredicate); + auto colomCount = std::count_if(m_hostname.begin(), m_hostname.end(), isColomPredicate); if (colomCount == 1) { // ipv4 with port part @@ -91,8 +89,7 @@ NetworkAddress::NetworkAddress(const String &hostname, int port) } // ensure that ipv6 link-local adress ended with scope id - if (m_hostname.rfind("fe80:", 0) == 0 && - m_hostname.find('%') == String::npos) { + if (m_hostname.rfind("fe80:", 0) == 0 && m_hostname.find('%') == String::npos) { throw XSocketAddress(XSocketAddress::kUnknown, m_hostname, m_port); } } @@ -101,14 +98,16 @@ NetworkAddress::NetworkAddress(const String &hostname, int port) checkPort(); } -NetworkAddress::~NetworkAddress() { +NetworkAddress::~NetworkAddress() +{ if (m_address != nullptr) { ARCH->closeAddr(m_address); m_address = nullptr; } } -NetworkAddress &NetworkAddress::operator=(const NetworkAddress &addr) { +NetworkAddress &NetworkAddress::operator=(const NetworkAddress &addr) +{ if (m_address != nullptr) { ARCH->closeAddr(m_address); m_address = nullptr; @@ -125,7 +124,8 @@ NetworkAddress &NetworkAddress::operator=(const NetworkAddress &addr) { return *this; } -size_t NetworkAddress::resolve(size_t index) { +size_t NetworkAddress::resolve(size_t index) +{ size_t resolvedAddressesCount = 0; // discard previous address if (m_address != nullptr) { @@ -183,24 +183,38 @@ size_t NetworkAddress::resolve(size_t index) { return resolvedAddressesCount; } -bool NetworkAddress::operator==(const NetworkAddress &addr) const { - return m_address == addr.m_address || - ARCH->isEqualAddr(m_address, addr.m_address); +bool NetworkAddress::operator==(const NetworkAddress &addr) const +{ + return m_address == addr.m_address || ARCH->isEqualAddr(m_address, addr.m_address); } -bool NetworkAddress::operator!=(const NetworkAddress &addr) const { +bool NetworkAddress::operator!=(const NetworkAddress &addr) const +{ return !operator==(addr); } -bool NetworkAddress::isValid() const { return (m_address != nullptr); } +bool NetworkAddress::isValid() const +{ + return (m_address != nullptr); +} -const ArchNetAddress &NetworkAddress::getAddress() const { return m_address; } +const ArchNetAddress &NetworkAddress::getAddress() const +{ + return m_address; +} -int NetworkAddress::getPort() const { return m_port; } +int NetworkAddress::getPort() const +{ + return m_port; +} -String NetworkAddress::getHostname() const { return m_hostname; } +String NetworkAddress::getHostname() const +{ + return m_hostname; +} -void NetworkAddress::checkPort() { +void NetworkAddress::checkPort() +{ // check port number if (m_port < 0 || m_port > 65535) { throw XSocketAddress(XSocketAddress::kBadPort, m_hostname, m_port); diff --git a/src/lib/net/NetworkAddress.h b/src/lib/net/NetworkAddress.h index ad6d15b79..3cd7b6dc5 100644 --- a/src/lib/net/NetworkAddress.h +++ b/src/lib/net/NetworkAddress.h @@ -26,7 +26,8 @@ /*! This class represents a network address. */ -class NetworkAddress { +class NetworkAddress +{ public: /*! Constructs the invalid address diff --git a/src/lib/net/SecureListenSocket.cpp b/src/lib/net/SecureListenSocket.cpp index fabc22b08..00dfe4c3b 100644 --- a/src/lib/net/SecureListenSocket.cpp +++ b/src/lib/net/SecureListenSocket.cpp @@ -34,15 +34,17 @@ static const char s_certificateFilename[] = {DESKFLOW_APP_ID ".pem"}; // SecureListenSocket::SecureListenSocket( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, - IArchNetwork::EAddressFamily family) - : TCPListenSocket(events, socketMultiplexer, family) {} + IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family +) + : TCPListenSocket(events, socketMultiplexer, family) +{ +} -IDataSocket *SecureListenSocket::accept() { +IDataSocket *SecureListenSocket::accept() +{ SecureSocket *socket = NULL; try { - socket = new SecureSocket( - m_events, m_socketMultiplexer, ARCH->acceptSocket(m_socket, NULL)); + socket = new SecureSocket(m_events, m_socketMultiplexer, ARCH->acceptSocket(m_socket, NULL)); socket->initSsl(true); if (socket != NULL) { @@ -51,8 +53,8 @@ IDataSocket *SecureListenSocket::accept() { // default location of the TLS cert file in users dir String certificateFilename = deskflow::string::sprintf( - "%s/%s/%s", ARCH->getProfileDirectory().c_str(), s_certificateDir, - s_certificateFilename); + "%s/%s/%s", ARCH->getProfileDirectory().c_str(), s_certificateDir, s_certificateFilename + ); // if the tls cert option is set use that for the certificate file if (!ArgParser::argsBase().m_tlsCertFile.empty()) { diff --git a/src/lib/net/SecureListenSocket.h b/src/lib/net/SecureListenSocket.h index de15a103e..3d8dada27 100644 --- a/src/lib/net/SecureListenSocket.h +++ b/src/lib/net/SecureListenSocket.h @@ -24,11 +24,10 @@ class IEventQueue; class SocketMultiplexer; class IDataSocket; -class SecureListenSocket : public TCPListenSocket { +class SecureListenSocket : public TCPListenSocket +{ public: - SecureListenSocket( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, - IArchNetwork::EAddressFamily family); + SecureListenSocket(IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family); // IListenSocket overrides virtual IDataSocket *accept(); diff --git a/src/lib/net/SecureSocket.cpp b/src/lib/net/SecureSocket.cpp index fd40718ed..4779a5513 100644 --- a/src/lib/net/SecureSocket.cpp +++ b/src/lib/net/SecureSocket.cpp @@ -43,50 +43,62 @@ static const float s_retryDelay = 0.01f; -enum { kMsgSize = 128 }; +enum +{ + kMsgSize = 128 +}; // TODO: Reduce duplication of these strings between here and TlsFingerprint.cpp static const char kFingerprintDirName[] = "tls"; static const char kFingerprintTrustedServersFilename[] = "trusted-servers"; -struct Ssl { +struct Ssl +{ SSL_CTX *m_context; SSL *m_ssl; }; SecureSocket::SecureSocket( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, - IArchNetwork::EAddressFamily family) + IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family +) : TCPSocket(events, socketMultiplexer, family), m_ssl(nullptr), m_secureReady(false), - m_fatal(false) {} + m_fatal(false) +{ +} -SecureSocket::SecureSocket( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, - ArchSocket socket) +SecureSocket::SecureSocket(IEventQueue *events, SocketMultiplexer *socketMultiplexer, ArchSocket socket) : TCPSocket(events, socketMultiplexer, socket), m_ssl(nullptr), m_secureReady(false), - m_fatal(false) {} + m_fatal(false) +{ +} -SecureSocket::~SecureSocket() { freeSSL(); } +SecureSocket::~SecureSocket() +{ + freeSSL(); +} -void SecureSocket::close() { +void SecureSocket::close() +{ freeSSL(); TCPSocket::close(); } -void SecureSocket::connect(const NetworkAddress &addr) { +void SecureSocket::connect(const NetworkAddress &addr) +{ m_events->adoptHandler( m_events->forIDataSocket().connected(), getEventTarget(), - new TMethodEventJob( - this, &SecureSocket::handleTCPConnected)); + new TMethodEventJob(this, &SecureSocket::handleTCPConnected) + ); TCPSocket::connect(addr); } -ISocketMultiplexerJob *SecureSocket::newJob() { +ISocketMultiplexerJob *SecureSocket::newJob() +{ // after TCP connection is established, SecureSocket will pick up // connected event and do secureConnect if (m_connected && !m_secureReady) { @@ -96,19 +108,22 @@ ISocketMultiplexerJob *SecureSocket::newJob() { return TCPSocket::newJob(); } -void SecureSocket::secureConnect() { +void SecureSocket::secureConnect() +{ setJob(new TSocketMultiplexerMethodJob( - this, &SecureSocket::serviceConnect, getSocket(), isReadable(), - isWritable())); + this, &SecureSocket::serviceConnect, getSocket(), isReadable(), isWritable() + )); } -void SecureSocket::secureAccept() { +void SecureSocket::secureAccept() +{ setJob(new TSocketMultiplexerMethodJob( - this, &SecureSocket::serviceAccept, getSocket(), isReadable(), - isWritable())); + this, &SecureSocket::serviceAccept, getSocket(), isReadable(), isWritable() + )); } -TCPSocket::EJobResult SecureSocket::doRead() { +TCPSocket::EJobResult SecureSocket::doRead() +{ static UInt8 buffer[4096]; memset(buffer, 0, sizeof(buffer)); int bytesRead = 0; @@ -158,7 +173,8 @@ TCPSocket::EJobResult SecureSocket::doRead() { return kRetry; } -TCPSocket::EJobResult SecureSocket::doWrite() { +TCPSocket::EJobResult SecureSocket::doWrite() +{ static bool s_retry = false; static int s_retrySize = 0; static int s_staticBufferSize = 0; @@ -210,7 +226,8 @@ TCPSocket::EJobResult SecureSocket::doWrite() { return kRetry; } -int SecureSocket::secureRead(void *buffer, int size, int &read) { +int SecureSocket::secureRead(void *buffer, int size, int &read) +{ if (m_ssl->m_ssl != NULL) { LOG((CLOG_DEBUG2 "reading secure socket")); read = SSL_read(m_ssl->m_ssl, buffer, size); @@ -234,7 +251,8 @@ int SecureSocket::secureRead(void *buffer, int size, int &read) { return read; } -int SecureSocket::secureWrite(const void *buffer, int size, int &wrote) { +int SecureSocket::secureWrite(const void *buffer, int size, int &wrote) +{ if (m_ssl->m_ssl != NULL) { LOG((CLOG_DEBUG2 "writing secure socket: %p", this)); @@ -259,9 +277,13 @@ int SecureSocket::secureWrite(const void *buffer, int size, int &wrote) { return wrote; } -bool SecureSocket::isSecureReady() { return m_secureReady; } +bool SecureSocket::isSecureReady() +{ + return m_secureReady; +} -void SecureSocket::initSsl(bool server) { +void SecureSocket::initSsl(bool server) +{ m_ssl = new Ssl(); m_ssl->m_context = NULL; m_ssl->m_ssl = NULL; @@ -269,7 +291,8 @@ void SecureSocket::initSsl(bool server) { initContext(server); } -bool SecureSocket::loadCertificates(String &filename) { +bool SecureSocket::loadCertificates(String &filename) +{ if (filename.empty()) { SslLogger::logError("tls certificate is not specified"); return false; @@ -287,15 +310,13 @@ bool SecureSocket::loadCertificates(String &filename) { } int r = 0; - r = SSL_CTX_use_certificate_file( - m_ssl->m_context, filename.c_str(), SSL_FILETYPE_PEM); + r = SSL_CTX_use_certificate_file(m_ssl->m_context, filename.c_str(), SSL_FILETYPE_PEM); if (r <= 0) { SslLogger::logError("could not use tls certificate"); return false; } - r = SSL_CTX_use_PrivateKey_file( - m_ssl->m_context, filename.c_str(), SSL_FILETYPE_PEM); + r = SSL_CTX_use_PrivateKey_file(m_ssl->m_context, filename.c_str(), SSL_FILETYPE_PEM); if (r <= 0) { SslLogger::logError("could not use tls private key"); return false; @@ -310,7 +331,8 @@ bool SecureSocket::loadCertificates(String &filename) { return true; } -void SecureSocket::initContext(bool server) { +void SecureSocket::initContext(bool server) +{ SSL_library_init(); const SSL_METHOD *method; @@ -334,16 +356,15 @@ void SecureSocket::initContext(bool server) { // Prevent the usage of of all version prior to TLSv1.2 as they are known to // be vulnerable - SSL_CTX_set_options( - m_ssl->m_context, - SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1); + SSL_CTX_set_options(m_ssl->m_context, SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 | SSL_OP_NO_TLSv1 | SSL_OP_NO_TLSv1_1); if (m_ssl->m_context == NULL) { SslLogger::logError(); } } -void SecureSocket::createSSL() { +void SecureSocket::createSSL() +{ // I assume just one instance is needed // get new SSL state with context if (m_ssl->m_ssl == NULL) { @@ -352,7 +373,8 @@ void SecureSocket::createSSL() { } } -void SecureSocket::freeSSL() { +void SecureSocket::freeSSL() +{ isFatal(true); // take socket from multiplexer ASAP otherwise the race condition // could cause events to get called on a dead object. TCPSocket @@ -374,7 +396,8 @@ void SecureSocket::freeSSL() { } } -int SecureSocket::secureAccept(int socket) { +int SecureSocket::secureAccept(int socket) +{ createSSL(); // set connection socket to SSL state @@ -419,7 +442,8 @@ int SecureSocket::secureAccept(int socket) { return -1; } -int SecureSocket::secureConnect(int socket) { +int SecureSocket::secureConnect(int socket) +{ createSSL(); // attach the socket descriptor @@ -470,7 +494,8 @@ int SecureSocket::secureConnect(int socket) { return 1; } -bool SecureSocket::showCertificate() const { +bool SecureSocket::showCertificate() const +{ X509 *cert; char *line; @@ -489,7 +514,8 @@ bool SecureSocket::showCertificate() const { return true; } -void SecureSocket::checkResult(int status, int &retry) { +void SecureSocket::checkResult(int status, int &retry) +{ // ssl errors are a little quirky. the "want" errors are normal and // should result in a retry. @@ -523,8 +549,7 @@ void SecureSocket::checkResult(int status, int &retry) { case SSL_ERROR_WANT_CONNECT: retry++; - LOG(( - CLOG_DEBUG2 "want to connect, error=%d, attempt=%d", errorCode, retry)); + LOG((CLOG_DEBUG2 "want to connect, error=%d, attempt=%d", errorCode, retry)); break; case SSL_ERROR_WANT_ACCEPT: @@ -568,14 +593,15 @@ void SecureSocket::checkResult(int status, int &retry) { } } -void SecureSocket::disconnect() { +void SecureSocket::disconnect() +{ sendEvent(getEvents()->forISocket().stopRetry()); sendEvent(getEvents()->forISocket().disconnected()); sendEvent(getEvents()->forIStream().inputShutdown()); } -void SecureSocket::formatFingerprint( - String &fingerprint, bool hex, bool separator) { +void SecureSocket::formatFingerprint(String &fingerprint, bool hex, bool separator) +{ if (hex) { // to hexidecimal deskflow::string::toHex(fingerprint, 2); @@ -593,34 +619,30 @@ void SecureSocket::formatFingerprint( } } -bool SecureSocket::verifyCertFingerprint() { +bool SecureSocket::verifyCertFingerprint() +{ // calculate received certificate fingerprint using AutoX509 = std::unique_ptr; AutoX509 cert(SSL_get_peer_certificate(m_ssl->m_ssl), &X509_free); unsigned char tempFingerprint[EVP_MAX_MD_SIZE]; unsigned int tempFingerprintLen; - int digestResult = X509_digest( - cert.get(), EVP_sha256(), tempFingerprint, &tempFingerprintLen); + int digestResult = X509_digest(cert.get(), EVP_sha256(), tempFingerprint, &tempFingerprintLen); if (digestResult <= 0) { - LOG( - (CLOG_ERR "failed to calculate fingerprint, digest result: %d", - digestResult)); + LOG((CLOG_ERR "failed to calculate fingerprint, digest result: %d", digestResult)); return false; } // format fingerprint into hexdecimal format with colon separator - String fingerprint( - static_cast(static_cast(tempFingerprint)), - tempFingerprintLen); + String fingerprint(static_cast(static_cast(tempFingerprint)), tempFingerprintLen); formatFingerprint(fingerprint); LOG((CLOG_NOTE "server fingerprint: %s", fingerprint.c_str())); String trustedServersFilename; trustedServersFilename = deskflow::string::sprintf( - "%s/%s/%s", ARCH->getProfileDirectory().c_str(), kFingerprintDirName, - kFingerprintTrustedServersFilename); + "%s/%s/%s", ARCH->getProfileDirectory().c_str(), kFingerprintDirName, kFingerprintTrustedServersFilename + ); // check if this fingerprint exist String fileLine; @@ -637,17 +659,15 @@ bool SecureSocket::verifyCertFingerprint() { } } } else { - LOG( - (CLOG_ERR "fail to open trusted fingerprints file: %s", - trustedServersFilename.c_str())); + LOG((CLOG_ERR "fail to open trusted fingerprints file: %s", trustedServersFilename.c_str())); } file.close(); return isValid; } -ISocketMultiplexerJob *SecureSocket::serviceConnect( - ISocketMultiplexerJob *job, bool, bool write, bool error) { +ISocketMultiplexerJob *SecureSocket::serviceConnect(ISocketMultiplexerJob *job, bool, bool write, bool error) +{ Lock lock(&getMutex()); int status = 0; @@ -670,12 +690,12 @@ ISocketMultiplexerJob *SecureSocket::serviceConnect( // Retry case return new TSocketMultiplexerMethodJob( - this, &SecureSocket::serviceConnect, getSocket(), isReadable(), - isWritable()); + this, &SecureSocket::serviceConnect, getSocket(), isReadable(), isWritable() + ); } -ISocketMultiplexerJob *SecureSocket::serviceAccept( - ISocketMultiplexerJob *job, bool, bool write, bool error) { +ISocketMultiplexerJob *SecureSocket::serviceAccept(ISocketMultiplexerJob *job, bool, bool write, bool error) +{ Lock lock(&getMutex()); int status = 0; @@ -697,11 +717,12 @@ ISocketMultiplexerJob *SecureSocket::serviceAccept( // Retry case return new TSocketMultiplexerMethodJob( - this, &SecureSocket::serviceAccept, getSocket(), isReadable(), - isWritable()); + this, &SecureSocket::serviceAccept, getSocket(), isReadable(), isWritable() + ); } -void SecureSocket::handleTCPConnected(const Event &, void *) { +void SecureSocket::handleTCPConnected(const Event &, void *) +{ if (getSocket() == nullptr) { LOG((CLOG_DEBUG "disregarding stale connect event")); return; diff --git a/src/lib/net/SecureSocket.h b/src/lib/net/SecureSocket.h index 82d3094c4..13756da11 100644 --- a/src/lib/net/SecureSocket.h +++ b/src/lib/net/SecureSocket.h @@ -30,14 +30,11 @@ struct Ssl; /*! A secure socket using SSL. */ -class SecureSocket : public TCPSocket { +class SecureSocket : public TCPSocket +{ public: - SecureSocket( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, - IArchNetwork::EAddressFamily family); - SecureSocket( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, - ArchSocket socket); + SecureSocket(IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family); + SecureSocket(IEventQueue *events, SocketMultiplexer *socketMultiplexer, ArchSocket socket); SecureSocket(SecureSocket const &) = delete; SecureSocket(SecureSocket &&) = delete; ~SecureSocket(); @@ -52,8 +49,14 @@ public: virtual void connect(const NetworkAddress &) override; ISocketMultiplexerJob *newJob() override; - bool isFatal() const override { return m_fatal; } - void isFatal(bool b) { m_fatal = b; } + bool isFatal() const override + { + return m_fatal; + } + void isFatal(bool b) + { + m_fatal = b; + } bool isSecureReady(); void secureConnect(); void secureAccept(); @@ -74,15 +77,12 @@ private: bool showCertificate() const; void checkResult(int n, int &retry); void disconnect(); - void formatFingerprint( - String &fingerprint, bool hex = true, bool separator = true); + void formatFingerprint(String &fingerprint, bool hex = true, bool separator = true); bool verifyCertFingerprint(); - ISocketMultiplexerJob * - serviceConnect(ISocketMultiplexerJob *, bool, bool, bool); + ISocketMultiplexerJob *serviceConnect(ISocketMultiplexerJob *, bool, bool, bool); - ISocketMultiplexerJob * - serviceAccept(ISocketMultiplexerJob *, bool, bool, bool); + ISocketMultiplexerJob *serviceAccept(ISocketMultiplexerJob *, bool, bool, bool); void handleTCPConnected(const Event &event, void *); diff --git a/src/lib/net/SocketMultiplexer.cpp b/src/lib/net/SocketMultiplexer.cpp index 384854d35..7d077e267 100644 --- a/src/lib/net/SocketMultiplexer.cpp +++ b/src/lib/net/SocketMultiplexer.cpp @@ -41,7 +41,8 @@ SocketMultiplexer::SocketMultiplexer() m_jobListLock(new CondVar(m_mutex, false)), m_jobListLockLocked(new CondVar(m_mutex, false)), m_jobListLocker(NULL), - m_jobListLockLocker(NULL) { + m_jobListLockLocker(NULL) +{ // this pointer just has to be unique and not NULL. it will // never be dereferenced. it's used to identify cursor nodes // in the jobs list. @@ -49,11 +50,11 @@ SocketMultiplexer::SocketMultiplexer() m_cursorMark = reinterpret_cast(this); // start thread - m_thread = new Thread(new TMethodJob( - this, &SocketMultiplexer::serviceThread)); + m_thread = new Thread(new TMethodJob(this, &SocketMultiplexer::serviceThread)); } -SocketMultiplexer::~SocketMultiplexer() { +SocketMultiplexer::~SocketMultiplexer() +{ m_thread->cancel(); m_thread->unblockPollSocket(); m_thread->wait(); @@ -66,13 +67,13 @@ SocketMultiplexer::~SocketMultiplexer() { delete m_mutex; // clean up jobs - for (SocketJobMap::iterator i = m_socketJobMap.begin(); - i != m_socketJobMap.end(); ++i) { + for (SocketJobMap::iterator i = m_socketJobMap.begin(); i != m_socketJobMap.end(); ++i) { delete *(i->second); } } -void SocketMultiplexer::addSocket(ISocket *socket, ISocketMultiplexerJob *job) { +void SocketMultiplexer::addSocket(ISocket *socket, ISocketMultiplexerJob *job) +{ assert(socket != NULL); assert(job != NULL); @@ -107,7 +108,8 @@ void SocketMultiplexer::addSocket(ISocket *socket, ISocketMultiplexerJob *job) { unlockJobList(); } -void SocketMultiplexer::removeSocket(ISocket *socket) { +void SocketMultiplexer::removeSocket(ISocket *socket) +{ assert(socket != NULL); // prevent other threads from locking the job list @@ -135,7 +137,8 @@ void SocketMultiplexer::removeSocket(ISocket *socket) { unlockJobList(); } -void SocketMultiplexer::serviceThread(void *) { +void SocketMultiplexer::serviceThread(void *) +{ std::vector pfds; IArchNetwork::PollEntry pfd; @@ -206,9 +209,7 @@ void SocketMultiplexer::serviceThread(void *) { unsigned short revents = pfds[i].m_revents; bool read = ((revents & IArchNetwork::kPOLLIN) != 0); bool write = ((revents & IArchNetwork::kPOLLOUT) != 0); - bool error = - ((revents & (IArchNetwork::kPOLLERR | IArchNetwork::kPOLLNVAL)) != - 0); + bool error = ((revents & (IArchNetwork::kPOLLERR | IArchNetwork::kPOLLNVAL)) != 0); // run job ISocketMultiplexerJob *job = *jobCursor; @@ -231,8 +232,7 @@ void SocketMultiplexer::serviceThread(void *) { } // delete any removed socket jobs - for (SocketJobMap::iterator i = m_socketJobMap.begin(); - i != m_socketJobMap.end();) { + for (SocketJobMap::iterator i = m_socketJobMap.begin(); i != m_socketJobMap.end();) { if (*(i->second) == NULL) { m_socketJobs.erase(i->second); m_socketJobMap.erase(i++); @@ -247,12 +247,14 @@ void SocketMultiplexer::serviceThread(void *) { } } -SocketMultiplexer::JobCursor SocketMultiplexer::newCursor() { +SocketMultiplexer::JobCursor SocketMultiplexer::newCursor() +{ Lock lock(m_mutex); return m_socketJobs.insert(m_socketJobs.begin(), m_cursorMark); } -SocketMultiplexer::JobCursor SocketMultiplexer::nextCursor(JobCursor cursor) { +SocketMultiplexer::JobCursor SocketMultiplexer::nextCursor(JobCursor cursor) +{ Lock lock(m_mutex); JobCursor j = m_socketJobs.end(); JobCursor i = cursor; @@ -269,12 +271,14 @@ SocketMultiplexer::JobCursor SocketMultiplexer::nextCursor(JobCursor cursor) { return j; } -void SocketMultiplexer::deleteCursor(JobCursor cursor) { +void SocketMultiplexer::deleteCursor(JobCursor cursor) +{ Lock lock(m_mutex); m_socketJobs.erase(cursor); } -void SocketMultiplexer::lockJobListLock() { +void SocketMultiplexer::lockJobListLock() +{ Lock lock(m_mutex); // wait for the lock on the lock @@ -287,7 +291,8 @@ void SocketMultiplexer::lockJobListLock() { m_jobListLockLocker = new Thread(Thread::getCurrentThread()); } -void SocketMultiplexer::lockJobList() { +void SocketMultiplexer::lockJobList() +{ Lock lock(m_mutex); // make sure we're the one that called lockJobListLock() @@ -308,7 +313,8 @@ void SocketMultiplexer::lockJobList() { m_jobListLockLocked->broadcast(); } -void SocketMultiplexer::unlockJobList() { +void SocketMultiplexer::unlockJobList() +{ Lock lock(m_mutex); // make sure we're the one that called lockJobList() diff --git a/src/lib/net/SocketMultiplexer.h b/src/lib/net/SocketMultiplexer.h index ff1d663e8..6b78738e3 100644 --- a/src/lib/net/SocketMultiplexer.h +++ b/src/lib/net/SocketMultiplexer.h @@ -32,7 +32,8 @@ class ISocketMultiplexerJob; /*! A socket multiplexer services multiple sockets simultaneously. */ -class SocketMultiplexer { +class SocketMultiplexer +{ public: SocketMultiplexer(); SocketMultiplexer(SocketMultiplexer const &) = delete; diff --git a/src/lib/net/TCPListenSocket.cpp b/src/lib/net/TCPListenSocket.cpp index 9ee35df94..96a92a43b 100644 --- a/src/lib/net/TCPListenSocket.cpp +++ b/src/lib/net/TCPListenSocket.cpp @@ -36,10 +36,11 @@ // TCPListenSocket::TCPListenSocket( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, - IArchNetwork::EAddressFamily family) + IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family +) : m_events(events), - m_socketMultiplexer(socketMultiplexer) { + m_socketMultiplexer(socketMultiplexer) +{ m_mutex = new Mutex; try { m_socket = ARCH->newSocket(family, IArchNetwork::kSTREAM); @@ -48,7 +49,8 @@ TCPListenSocket::TCPListenSocket( } } -TCPListenSocket::~TCPListenSocket() { +TCPListenSocket::~TCPListenSocket() +{ try { if (m_socket != NULL) { m_socketMultiplexer->removeSocket(this); @@ -61,16 +63,18 @@ TCPListenSocket::~TCPListenSocket() { delete m_mutex; } -void TCPListenSocket::bind(const NetworkAddress &addr) { +void TCPListenSocket::bind(const NetworkAddress &addr) +{ try { Lock lock(m_mutex); ARCH->setReuseAddrOnSocket(m_socket, true); ARCH->bindSocket(m_socket, addr.getAddress()); ARCH->listenOnSocket(m_socket); m_socketMultiplexer->addSocket( - this, - new TSocketMultiplexerMethodJob( - this, &TCPListenSocket::serviceListening, m_socket, true, false)); + this, new TSocketMultiplexerMethodJob( + this, &TCPListenSocket::serviceListening, m_socket, true, false + ) + ); } catch (XArchNetworkAddressInUse &e) { throw XSocketAddressInUse(e.what()); } catch (XArchNetwork &e) { @@ -78,7 +82,8 @@ void TCPListenSocket::bind(const NetworkAddress &addr) { } } -void TCPListenSocket::close() { +void TCPListenSocket::close() +{ Lock lock(m_mutex); if (m_socket == NULL) { throw XIOClosed(); @@ -92,15 +97,16 @@ void TCPListenSocket::close() { } } -void *TCPListenSocket::getEventTarget() const { +void *TCPListenSocket::getEventTarget() const +{ return const_cast(static_cast(this)); } -IDataSocket *TCPListenSocket::accept() { +IDataSocket *TCPListenSocket::accept() +{ IDataSocket *socket = NULL; try { - socket = new TCPSocket( - m_events, m_socketMultiplexer, ARCH->acceptSocket(m_socket, NULL)); + socket = new TCPSocket(m_events, m_socketMultiplexer, ARCH->acceptSocket(m_socket, NULL)); if (socket != NULL) { setListeningJob(); } @@ -120,15 +126,16 @@ IDataSocket *TCPListenSocket::accept() { } } -void TCPListenSocket::setListeningJob() { +void TCPListenSocket::setListeningJob() +{ m_socketMultiplexer->addSocket( this, - new TSocketMultiplexerMethodJob( - this, &TCPListenSocket::serviceListening, m_socket, true, false)); + new TSocketMultiplexerMethodJob(this, &TCPListenSocket::serviceListening, m_socket, true, false) + ); } -ISocketMultiplexerJob *TCPListenSocket::serviceListening( - ISocketMultiplexerJob *job, bool read, bool, bool error) { +ISocketMultiplexerJob *TCPListenSocket::serviceListening(ISocketMultiplexerJob *job, bool read, bool, bool error) +{ if (error) { close(); return NULL; diff --git a/src/lib/net/TCPListenSocket.h b/src/lib/net/TCPListenSocket.h index bf6965596..59b07dab7 100644 --- a/src/lib/net/TCPListenSocket.h +++ b/src/lib/net/TCPListenSocket.h @@ -30,11 +30,10 @@ class SocketMultiplexer; /*! A listen socket using TCP. */ -class TCPListenSocket : public IListenSocket { +class TCPListenSocket : public IListenSocket +{ public: - TCPListenSocket( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, - IArchNetwork::EAddressFamily family); + TCPListenSocket(IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family); TCPListenSocket(TCPListenSocket const &) = delete; TCPListenSocket(TCPListenSocket &&) = delete; virtual ~TCPListenSocket(); @@ -54,8 +53,7 @@ protected: void setListeningJob(); public: - ISocketMultiplexerJob * - serviceListening(ISocketMultiplexerJob *, bool, bool, bool); + ISocketMultiplexerJob *serviceListening(ISocketMultiplexerJob *, bool, bool, bool); protected: ArchSocket m_socket; diff --git a/src/lib/net/TCPSocket.cpp b/src/lib/net/TCPSocket.cpp index f3f4d7494..b145dae3a 100644 --- a/src/lib/net/TCPSocket.cpp +++ b/src/lib/net/TCPSocket.cpp @@ -37,14 +37,13 @@ // TCPSocket // -TCPSocket::TCPSocket( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, - IArchNetwork::EAddressFamily family) +TCPSocket::TCPSocket(IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family) : IDataSocket(events), m_events(events), m_mutex(), m_flushed(&m_mutex, true), - m_socketMultiplexer(socketMultiplexer) { + m_socketMultiplexer(socketMultiplexer) +{ try { m_socket = ARCH->newSocket(family, IArchNetwork::kSTREAM); } catch (const XArchNetwork &e) { @@ -56,15 +55,14 @@ TCPSocket::TCPSocket( init(); } -TCPSocket::TCPSocket( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, - ArchSocket socket) +TCPSocket::TCPSocket(IEventQueue *events, SocketMultiplexer *socketMultiplexer, ArchSocket socket) : IDataSocket(events), m_events(events), m_mutex(), m_socket(socket), m_flushed(&m_mutex, true), - m_socketMultiplexer(socketMultiplexer) { + m_socketMultiplexer(socketMultiplexer) +{ assert(m_socket != nullptr); LOG((CLOG_DEBUG "opening new socket: %08X", m_socket)); @@ -75,7 +73,8 @@ TCPSocket::TCPSocket( setJob(newJob()); } -TCPSocket::~TCPSocket() { +TCPSocket::~TCPSocket() +{ try { // warning virtual function in destructor is very danger practice close(); @@ -84,7 +83,8 @@ TCPSocket::~TCPSocket() { } } -void TCPSocket::bind(const NetworkAddress &addr) { +void TCPSocket::bind(const NetworkAddress &addr) +{ try { ARCH->bindSocket(m_socket, addr.getAddress()); } catch (const XArchNetworkAddressInUse &e) { @@ -94,7 +94,8 @@ void TCPSocket::bind(const NetworkAddress &addr) { } } -void TCPSocket::close() { +void TCPSocket::close() +{ LOG((CLOG_DEBUG "closing socket: %08X", m_socket)); // remove ourself from the multiplexer @@ -121,11 +122,13 @@ void TCPSocket::close() { } } -void *TCPSocket::getEventTarget() const { +void *TCPSocket::getEventTarget() const +{ return const_cast(static_cast(this)); } -UInt32 TCPSocket::read(void *buffer, UInt32 n) { +UInt32 TCPSocket::read(void *buffer, UInt32 n) +{ // copy data directly from our input buffer Lock lock(&m_mutex); UInt32 size = m_inputBuffer.getSize(); @@ -146,7 +149,8 @@ UInt32 TCPSocket::read(void *buffer, UInt32 n) { return n; } -void TCPSocket::write(const void *buffer, UInt32 n) { +void TCPSocket::write(const void *buffer, UInt32 n) +{ bool wasEmpty; { Lock lock(&m_mutex); @@ -176,14 +180,16 @@ void TCPSocket::write(const void *buffer, UInt32 n) { } } -void TCPSocket::flush() { +void TCPSocket::flush() +{ Lock lock(&m_mutex); while (m_flushed == false) { m_flushed.wait(); } } -void TCPSocket::shutdownInput() { +void TCPSocket::shutdownInput() +{ bool useNewJob = false; { Lock lock(&m_mutex); @@ -208,7 +214,8 @@ void TCPSocket::shutdownInput() { } } -void TCPSocket::shutdownOutput() { +void TCPSocket::shutdownOutput() +{ bool useNewJob = false; { Lock lock(&m_mutex); @@ -233,23 +240,27 @@ void TCPSocket::shutdownOutput() { } } -bool TCPSocket::isReady() const { +bool TCPSocket::isReady() const +{ Lock lock(&m_mutex); return (m_inputBuffer.getSize() > 0); } -bool TCPSocket::isFatal() const { +bool TCPSocket::isFatal() const +{ // TCP sockets aren't ever left in a fatal state. LOG((CLOG_ERR "isFatal() not valid for non-secure connections")); return false; } -UInt32 TCPSocket::getSize() const { +UInt32 TCPSocket::getSize() const +{ Lock lock(&m_mutex); return m_inputBuffer.getSize(); } -void TCPSocket::connect(const NetworkAddress &addr) { +void TCPSocket::connect(const NetworkAddress &addr) +{ { Lock lock(&m_mutex); @@ -274,7 +285,8 @@ void TCPSocket::connect(const NetworkAddress &addr) { setJob(newJob()); } -void TCPSocket::init() { +void TCPSocket::init() +{ // default state m_connected = false; m_readable = false; @@ -297,7 +309,8 @@ void TCPSocket::init() { } } -TCPSocket::EJobResult TCPSocket::doRead() { +TCPSocket::EJobResult TCPSocket::doRead() +{ UInt8 buffer[4096]; memset(buffer, 0, sizeof(buffer)); size_t bytesRead = 0; @@ -334,7 +347,8 @@ TCPSocket::EJobResult TCPSocket::doRead() { return kRetry; } -TCPSocket::EJobResult TCPSocket::doWrite() { +TCPSocket::EJobResult TCPSocket::doWrite() +{ // write data UInt32 bufferSize = 0; int bytesWrote = 0; @@ -351,7 +365,8 @@ TCPSocket::EJobResult TCPSocket::doWrite() { return kRetry; } -void TCPSocket::setJob(ISocketMultiplexerJob *job) { +void TCPSocket::setJob(ISocketMultiplexerJob *job) +{ // multiplexer will delete the old job if (job == nullptr) { m_socketMultiplexer->removeSocket(this); @@ -360,7 +375,8 @@ void TCPSocket::setJob(ISocketMultiplexerJob *job) { } } -ISocketMultiplexerJob *TCPSocket::newJob() { +ISocketMultiplexerJob *TCPSocket::newJob() +{ // note -- must have m_mutex locked on entry if (m_socket == nullptr) { @@ -371,29 +387,32 @@ ISocketMultiplexerJob *TCPSocket::newJob() { return nullptr; } return new TSocketMultiplexerMethodJob( - this, &TCPSocket::serviceConnecting, m_socket, m_readable, m_writable); + this, &TCPSocket::serviceConnecting, m_socket, m_readable, m_writable + ); } else { if (!(m_readable || (m_writable && (m_outputBuffer.getSize() > 0)))) { return nullptr; } return new TSocketMultiplexerMethodJob( - this, &TCPSocket::serviceConnected, m_socket, m_readable, - m_writable && (m_outputBuffer.getSize() > 0)); + this, &TCPSocket::serviceConnected, m_socket, m_readable, m_writable && (m_outputBuffer.getSize() > 0) + ); } } -void TCPSocket::sendConnectionFailedEvent(const char *msg) { +void TCPSocket::sendConnectionFailedEvent(const char *msg) +{ ConnectionFailedInfo *info = new ConnectionFailedInfo(msg); - m_events->addEvent(Event( - m_events->forIDataSocket().connectionFailed(), getEventTarget(), info, - Event::kDontFreeData)); + m_events->addEvent(Event(m_events->forIDataSocket().connectionFailed(), getEventTarget(), info, Event::kDontFreeData) + ); } -void TCPSocket::sendEvent(Event::Type type) { +void TCPSocket::sendEvent(Event::Type type) +{ m_events->addEvent(Event(type, getEventTarget())); } -void TCPSocket::discardWrittenData(int bytesWrote) { +void TCPSocket::discardWrittenData(int bytesWrote) +{ m_outputBuffer.pop(bytesWrote); if (m_outputBuffer.getSize() == 0) { sendEvent(m_events->forIStream().outputFlushed()); @@ -402,18 +421,21 @@ void TCPSocket::discardWrittenData(int bytesWrote) { } } -void TCPSocket::onConnected() { +void TCPSocket::onConnected() +{ m_connected = true; m_readable = true; m_writable = true; } -void TCPSocket::onInputShutdown() { +void TCPSocket::onInputShutdown() +{ m_inputBuffer.pop(m_inputBuffer.getSize()); m_readable = false; } -void TCPSocket::onOutputShutdown() { +void TCPSocket::onOutputShutdown() +{ m_outputBuffer.pop(m_outputBuffer.getSize()); m_writable = false; @@ -422,15 +444,16 @@ void TCPSocket::onOutputShutdown() { m_flushed.broadcast(); } -void TCPSocket::onDisconnected() { +void TCPSocket::onDisconnected() +{ // disconnected onInputShutdown(); onOutputShutdown(); m_connected = false; } -ISocketMultiplexerJob *TCPSocket::serviceConnecting( - ISocketMultiplexerJob *job, bool, bool write, bool error) { +ISocketMultiplexerJob *TCPSocket::serviceConnecting(ISocketMultiplexerJob *job, bool, bool write, bool error) +{ Lock lock(&m_mutex); // should only check for errors if error is true but checking a new @@ -470,8 +493,8 @@ ISocketMultiplexerJob *TCPSocket::serviceConnecting( return job; } -ISocketMultiplexerJob *TCPSocket::serviceConnected( - ISocketMultiplexerJob *job, bool read, bool write, bool error) { +ISocketMultiplexerJob *TCPSocket::serviceConnected(ISocketMultiplexerJob *job, bool read, bool write, bool error) +{ Lock lock(&m_mutex); if (error) { diff --git a/src/lib/net/TCPSocket.h b/src/lib/net/TCPSocket.h index a78baa675..8dd783bc8 100644 --- a/src/lib/net/TCPSocket.h +++ b/src/lib/net/TCPSocket.h @@ -34,14 +34,14 @@ class SocketMultiplexer; /*! A data socket using TCP. */ -class TCPSocket : public IDataSocket { +class TCPSocket : public IDataSocket +{ public: TCPSocket( IEventQueue *events, SocketMultiplexer *socketMultiplexer, - IArchNetwork::EAddressFamily family = IArchNetwork::kINET); - TCPSocket( - IEventQueue *events, SocketMultiplexer *socketMultiplexer, - ArchSocket socket); + IArchNetwork::EAddressFamily family = IArchNetwork::kINET + ); + TCPSocket(IEventQueue *events, SocketMultiplexer *socketMultiplexer, ArchSocket socket); TCPSocket(TCPSocket const &) = delete; TCPSocket(TCPSocket &&) = delete; virtual ~TCPSocket(); @@ -70,23 +70,39 @@ public: virtual ISocketMultiplexerJob *newJob(); protected: - enum EJobResult { + enum EJobResult + { kBreak = -1, //!< Break the Job chain kRetry, //!< Retry the same job kNew //!< Require a new job }; - ArchSocket getSocket() { return m_socket; } - IEventQueue *getEvents() { return m_events; } + ArchSocket getSocket() + { + return m_socket; + } + IEventQueue *getEvents() + { + return m_events; + } virtual EJobResult doRead(); virtual EJobResult doWrite(); void setJob(ISocketMultiplexerJob *); - bool isReadable() { return m_readable; } - bool isWritable() { return m_writable; } + bool isReadable() + { + return m_readable; + } + bool isWritable() + { + return m_writable; + } - Mutex &getMutex() { return m_mutex; } + Mutex &getMutex() + { + return m_mutex; + } void sendEvent(Event::Type); void discardWrittenData(int bytesWrote); @@ -100,10 +116,8 @@ private: void onOutputShutdown(); void onDisconnected(); - ISocketMultiplexerJob * - serviceConnecting(ISocketMultiplexerJob *, bool, bool, bool); - ISocketMultiplexerJob * - serviceConnected(ISocketMultiplexerJob *, bool, bool, bool); + ISocketMultiplexerJob *serviceConnecting(ISocketMultiplexerJob *, bool, bool, bool); + ISocketMultiplexerJob *serviceConnected(ISocketMultiplexerJob *, bool, bool, bool); protected: bool m_readable; diff --git a/src/lib/net/TCPSocketFactory.cpp b/src/lib/net/TCPSocketFactory.cpp index 20afebfa4..4b664be91 100644 --- a/src/lib/net/TCPSocketFactory.cpp +++ b/src/lib/net/TCPSocketFactory.cpp @@ -28,22 +28,22 @@ // TCPSocketFactory // -TCPSocketFactory::TCPSocketFactory( - IEventQueue *events, SocketMultiplexer *socketMultiplexer) +TCPSocketFactory::TCPSocketFactory(IEventQueue *events, SocketMultiplexer *socketMultiplexer) : m_events(events), - m_socketMultiplexer(socketMultiplexer) { + m_socketMultiplexer(socketMultiplexer) +{ // do nothing } -TCPSocketFactory::~TCPSocketFactory() { +TCPSocketFactory::~TCPSocketFactory() +{ // do nothing } -IDataSocket *TCPSocketFactory::create( - bool secure, IArchNetwork::EAddressFamily family) const { +IDataSocket *TCPSocketFactory::create(bool secure, IArchNetwork::EAddressFamily family) const +{ if (secure) { - SecureSocket *secureSocket = - new SecureSocket(m_events, m_socketMultiplexer, family); + SecureSocket *secureSocket = new SecureSocket(m_events, m_socketMultiplexer, family); secureSocket->initSsl(false); return secureSocket; } else { @@ -51,8 +51,8 @@ IDataSocket *TCPSocketFactory::create( } } -IListenSocket *TCPSocketFactory::createListen( - bool secure, IArchNetwork::EAddressFamily family) const { +IListenSocket *TCPSocketFactory::createListen(bool secure, IArchNetwork::EAddressFamily family) const +{ IListenSocket *socket = NULL; if (secure) { socket = new SecureListenSocket(m_events, m_socketMultiplexer, family); diff --git a/src/lib/net/TCPSocketFactory.h b/src/lib/net/TCPSocketFactory.h index 05e229b11..47741b512 100644 --- a/src/lib/net/TCPSocketFactory.h +++ b/src/lib/net/TCPSocketFactory.h @@ -25,18 +25,15 @@ class IEventQueue; class SocketMultiplexer; //! Socket factory for TCP sockets -class TCPSocketFactory : public ISocketFactory { +class TCPSocketFactory : public ISocketFactory +{ public: TCPSocketFactory(IEventQueue *events, SocketMultiplexer *socketMultiplexer); virtual ~TCPSocketFactory(); // ISocketFactory overrides - virtual IDataSocket *create( - bool secure, - IArchNetwork::EAddressFamily family = IArchNetwork::kINET) const; - virtual IListenSocket *createListen( - bool secure, - IArchNetwork::EAddressFamily family = IArchNetwork::kINET) const; + virtual IDataSocket *create(bool secure, IArchNetwork::EAddressFamily family = IArchNetwork::kINET) const; + virtual IListenSocket *createListen(bool secure, IArchNetwork::EAddressFamily family = IArchNetwork::kINET) const; private: IEventQueue *m_events; diff --git a/src/lib/net/TSocketMultiplexerMethodJob.h b/src/lib/net/TSocketMultiplexerMethodJob.h index 20adb8168..64e6519df 100644 --- a/src/lib/net/TSocketMultiplexerMethodJob.h +++ b/src/lib/net/TSocketMultiplexerMethodJob.h @@ -25,24 +25,19 @@ /*! A socket multiplexer job class that invokes a member function. */ -template -class TSocketMultiplexerMethodJob : public ISocketMultiplexerJob { +template class TSocketMultiplexerMethodJob : public ISocketMultiplexerJob +{ public: - typedef ISocketMultiplexerJob *(T::*Method)( - ISocketMultiplexerJob *, bool, bool, bool); + typedef ISocketMultiplexerJob *(T::*Method)(ISocketMultiplexerJob *, bool, bool, bool); //! run() invokes \c object->method(arg) - TSocketMultiplexerMethodJob( - T *object, Method method, ArchSocket socket, bool readable, - bool writeable); + TSocketMultiplexerMethodJob(T *object, Method method, ArchSocket socket, bool readable, bool writeable); TSocketMultiplexerMethodJob(TSocketMultiplexerMethodJob const &) = delete; TSocketMultiplexerMethodJob(TSocketMultiplexerMethodJob &&) = delete; virtual ~TSocketMultiplexerMethodJob(); - TSocketMultiplexerMethodJob & - operator=(TSocketMultiplexerMethodJob const &) = delete; - TSocketMultiplexerMethodJob & - operator=(TSocketMultiplexerMethodJob &&) = delete; + TSocketMultiplexerMethodJob &operator=(TSocketMultiplexerMethodJob const &) = delete; + TSocketMultiplexerMethodJob &operator=(TSocketMultiplexerMethodJob &&) = delete; // IJob overrides virtual ISocketMultiplexerJob *run(bool readable, bool writable, bool error); @@ -61,40 +56,41 @@ private: template inline TSocketMultiplexerMethodJob::TSocketMultiplexerMethodJob( - T *object, Method method, ArchSocket socket, bool readable, bool writable) + T *object, Method method, ArchSocket socket, bool readable, bool writable +) : m_object(object), m_method(method), m_socket(ARCH->copySocket(socket)), m_readable(readable), - m_writable(writable) { + m_writable(writable) +{ // do nothing } -template -inline TSocketMultiplexerMethodJob::~TSocketMultiplexerMethodJob() { +template inline TSocketMultiplexerMethodJob::~TSocketMultiplexerMethodJob() +{ ARCH->closeSocket(m_socket); } -template -inline ISocketMultiplexerJob * -TSocketMultiplexerMethodJob::run(bool read, bool write, bool error) { +template inline ISocketMultiplexerJob *TSocketMultiplexerMethodJob::run(bool read, bool write, bool error) +{ if (m_object != NULL) { return (m_object->*m_method)(this, read, write, error); } return NULL; } -template -inline ArchSocket TSocketMultiplexerMethodJob::getSocket() const { +template inline ArchSocket TSocketMultiplexerMethodJob::getSocket() const +{ return m_socket; } -template -inline bool TSocketMultiplexerMethodJob::isReadable() const { +template inline bool TSocketMultiplexerMethodJob::isReadable() const +{ return m_readable; } -template -inline bool TSocketMultiplexerMethodJob::isWritable() const { +template inline bool TSocketMultiplexerMethodJob::isWritable() const +{ return m_writable; } diff --git a/src/lib/net/XSocket.cpp b/src/lib/net/XSocket.cpp index c68de4aa8..61039810b 100644 --- a/src/lib/net/XSocket.cpp +++ b/src/lib/net/XSocket.cpp @@ -23,41 +23,50 @@ // XSocketAddress // -XSocketAddress::XSocketAddress(EError error, const String &hostname, int port) - _NOEXCEPT : m_error(error), - m_hostname(hostname), - m_port(port) { +XSocketAddress::XSocketAddress(EError error, const String &hostname, int port) _NOEXCEPT : m_error(error), + m_hostname(hostname), + m_port(port) +{ // do nothing } -XSocketAddress::EError XSocketAddress::getError() const throw() { +XSocketAddress::EError XSocketAddress::getError() const throw() +{ return m_error; } -String XSocketAddress::getHostname() const throw() { return m_hostname; } +String XSocketAddress::getHostname() const throw() +{ + return m_hostname; +} -int XSocketAddress::getPort() const throw() { return m_port; } +int XSocketAddress::getPort() const throw() +{ + return m_port; +} -String XSocketAddress::getWhat() const throw() { +String XSocketAddress::getWhat() const throw() +{ static const char *s_errorID[] = { - "XSocketAddressUnknown", "XSocketAddressNotFound", - "XSocketAddressNoAddress", "XSocketAddressUnsupported", - "XSocketAddressBadPort"}; + "XSocketAddressUnknown", "XSocketAddressNotFound", "XSocketAddressNoAddress", "XSocketAddressUnsupported", + "XSocketAddressBadPort" + }; static const char *s_errorMsg[] = { - "unknown error for: %{1}:%{2}", "address not found for: %{1}", - "no address for: %{1}", "unsupported address for: %{1}", + "unknown error for: %{1}:%{2}", "address not found for: %{1}", "no address for: %{1}", + "unsupported address for: %{1}", "invalid port" // m_port may not be set to the bad port }; return format( - s_errorID[m_error], s_errorMsg[m_error], m_hostname.c_str(), - deskflow::string::sprintf("%d", m_port).c_str()); + s_errorID[m_error], s_errorMsg[m_error], m_hostname.c_str(), deskflow::string::sprintf("%d", m_port).c_str() + ); } // // XSocketIOClose // -String XSocketIOClose::getWhat() const throw() { +String XSocketIOClose::getWhat() const throw() +{ return format("XSocketIOClose", "close: %{1}", what()); } @@ -65,7 +74,8 @@ String XSocketIOClose::getWhat() const throw() { // XSocketBind // -String XSocketBind::getWhat() const throw() { +String XSocketBind::getWhat() const throw() +{ return format("XSocketBind", "cannot bind address: %{1}", what()); } @@ -73,7 +83,8 @@ String XSocketBind::getWhat() const throw() { // XSocketConnect // -String XSocketConnect::getWhat() const throw() { +String XSocketConnect::getWhat() const throw() +{ return format("XSocketConnect", "cannot connect socket: %{1}", what()); } @@ -81,6 +92,7 @@ String XSocketConnect::getWhat() const throw() { // XSocketCreate // -String XSocketCreate::getWhat() const throw() { +String XSocketCreate::getWhat() const throw() +{ return format("XSocketCreate", "cannot create socket: %{1}", what()); } diff --git a/src/lib/net/XSocket.h b/src/lib/net/XSocket.h index 28c4cc977..f678de6e8 100644 --- a/src/lib/net/XSocket.h +++ b/src/lib/net/XSocket.h @@ -30,10 +30,12 @@ XBASE_SUBCLASS(XSocket, XBase); /*! Thrown when attempting to create an invalid network address. */ -class XSocketAddress : public XSocket { +class XSocketAddress : public XSocket +{ public: //! Failure codes - enum EError { + enum EError + { kUnknown, //!< Unknown error kNotFound, //!< The hostname is unknown kNoAddress, //!< The hostname is valid but has no IP address @@ -42,7 +44,9 @@ public: }; XSocketAddress(EError, const String &hostname, int port) _NOEXCEPT; - virtual ~XSocketAddress() _NOEXCEPT {} + virtual ~XSocketAddress() _NOEXCEPT + { + } //! @name accessors //@{ diff --git a/src/lib/platform/EiEventQueueBuffer.cpp b/src/lib/platform/EiEventQueueBuffer.cpp index c3f3d6f09..082a141dd 100644 --- a/src/lib/platform/EiEventQueueBuffer.cpp +++ b/src/lib/platform/EiEventQueueBuffer.cpp @@ -30,14 +30,14 @@ #include #include -class EventQueueTimer {}; +class EventQueueTimer +{ +}; namespace deskflow { -EiEventQueueBuffer::EiEventQueueBuffer( - EiScreen *screen, ei *ei, IEventQueue *events) - : ei_(ei_ref(ei)), - events_(events) { +EiEventQueueBuffer::EiEventQueueBuffer(EiScreen *screen, ei *ei, IEventQueue *events) : ei_(ei_ref(ei)), events_(events) +{ // We need a pipe to signal ourselves when addEvent() is called int pipefd[2]; int result = pipe2(pipefd, O_NONBLOCK); @@ -47,16 +47,19 @@ EiEventQueueBuffer::EiEventQueueBuffer( pipe_w_ = pipefd[1]; } -EiEventQueueBuffer::~EiEventQueueBuffer() { +EiEventQueueBuffer::~EiEventQueueBuffer() +{ ei_unref(ei_); close(pipe_r_); close(pipe_w_); } -void EiEventQueueBuffer::waitForEvent(double timeout_in_ms) { +void EiEventQueueBuffer::waitForEvent(double timeout_in_ms) +{ Thread::testCancel(); - enum { + enum + { EIFD, PIPEFD, POLLFD_COUNT, // Last element @@ -68,8 +71,7 @@ void EiEventQueueBuffer::waitForEvent(double timeout_in_ms) { pfds[PIPEFD].fd = pipe_r_; pfds[PIPEFD].events = POLLIN; - int timeout = - (timeout_in_ms < 0.0) ? -1 : static_cast(1000.0 * timeout_in_ms); + int timeout = (timeout_in_ms < 0.0) ? -1 : static_cast(1000.0 * timeout_in_ms); int retval = poll(pfds, POLLFD_COUNT, timeout); if (retval > 0) { @@ -97,8 +99,8 @@ void EiEventQueueBuffer::waitForEvent(double timeout_in_ms) { Thread::testCancel(); } -IEventQueueBuffer::Type -EiEventQueueBuffer::getEvent(Event &event, uint32_t &dataID) { +IEventQueueBuffer::Type EiEventQueueBuffer::getEvent(Event &event, uint32_t &dataID) +{ // the addEvent/getEvent pair is a bit awkward for libei. // // it assumes that there's a nice queue of events sitting there that we can @@ -127,7 +129,8 @@ EiEventQueueBuffer::getEvent(Event &event, uint32_t &dataID) { return kSystem; } -bool EiEventQueueBuffer::addEvent(uint32_t dataID) { +bool EiEventQueueBuffer::addEvent(uint32_t dataID) +{ std::lock_guard lock(mutex_); queue_.push({false, dataID}); @@ -138,18 +141,20 @@ bool EiEventQueueBuffer::addEvent(uint32_t dataID) { return true; } -bool EiEventQueueBuffer::isEmpty() const { +bool EiEventQueueBuffer::isEmpty() const +{ std::lock_guard lock(mutex_); return queue_.empty(); } -EventQueueTimer * -EiEventQueueBuffer::newTimer(double duration, bool oneShot) const { +EventQueueTimer *EiEventQueueBuffer::newTimer(double duration, bool oneShot) const +{ return new EventQueueTimer; } -void EiEventQueueBuffer::deleteTimer(EventQueueTimer *timer) const { +void EiEventQueueBuffer::deleteTimer(EventQueueTimer *timer) const +{ delete timer; } diff --git a/src/lib/platform/EiEventQueueBuffer.h b/src/lib/platform/EiEventQueueBuffer.h index bef8eea60..1b9a9f733 100644 --- a/src/lib/platform/EiEventQueueBuffer.h +++ b/src/lib/platform/EiEventQueueBuffer.h @@ -33,13 +33,16 @@ namespace deskflow { //! Event queue buffer for Ei -class EiEventQueueBuffer : public IEventQueueBuffer { +class EiEventQueueBuffer : public IEventQueueBuffer +{ public: EiEventQueueBuffer(EiScreen *screen, ei *ei, IEventQueue *events); ~EiEventQueueBuffer(); // IEventQueueBuffer overrides - void init() override {} + void init() override + { + } void waitForEvent(double timeout_in_ms) override; Type getEvent(Event &event, uint32_t &dataID) override; bool addEvent(uint32_t dataID) override; diff --git a/src/lib/platform/EiKeyState.cpp b/src/lib/platform/EiKeyState.cpp index 2d4d55d4f..f155d4455 100644 --- a/src/lib/platform/EiKeyState.cpp +++ b/src/lib/platform/EiKeyState.cpp @@ -32,10 +32,9 @@ namespace deskflow { EiKeyState::EiKeyState(EiScreen *screen, IEventQueue *events) - : KeyState( - events, AppUtil::instance().getKeyboardLayoutList(), - ClientApp::instance().args().m_enableLangSync), - screen_{screen} { + : KeyState(events, AppUtil::instance().getKeyboardLayoutList(), ClientApp::instance().args().m_enableLangSync), + screen_{screen} +{ xkb_ = xkb_context_new(XKB_CONTEXT_NO_FLAGS); // FIXME: PrimaryClient->enable() calls into our keymap, so we must have @@ -45,12 +44,12 @@ EiKeyState::EiKeyState(EiScreen *screen, IEventQueue *events) init_default_keymap(); } -void EiKeyState::init_default_keymap() { +void EiKeyState::init_default_keymap() +{ if (xkb_keymap_) { xkb_keymap_unref(xkb_keymap_); } - xkb_keymap_ = - xkb_keymap_new_from_names(xkb_, nullptr, XKB_KEYMAP_COMPILE_NO_FLAGS); + xkb_keymap_ = xkb_keymap_new_from_names(xkb_, nullptr, XKB_KEYMAP_COMPILE_NO_FLAGS); if (xkb_state_) { xkb_state_unref(xkb_state_); @@ -58,7 +57,8 @@ void EiKeyState::init_default_keymap() { xkb_state_ = xkb_state_new(xkb_keymap_); } -void EiKeyState::init(int fd, size_t len) { +void EiKeyState::init(int fd, size_t len) +{ auto buffer = std::make_unique(len + 1); auto sz = read(fd, buffer.get(), len); @@ -73,9 +73,7 @@ void EiKeyState::init(int fd, size_t len) { // whole thing as string. buffer[len] = '\0'; // guarantee null-termination - auto keymap = xkb_keymap_new_from_string( - xkb_, buffer.get(), XKB_KEYMAP_FORMAT_TEXT_V1, - XKB_KEYMAP_COMPILE_NO_FLAGS); + auto keymap = xkb_keymap_new_from_string(xkb_, buffer.get(), XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS); if (!keymap) { LOG_NOTE("failed to compile keymap, falling back to defaults"); // Falling back to layout "us" is a lot more useful than segfaulting @@ -94,37 +92,41 @@ void EiKeyState::init(int fd, size_t len) { xkb_state_ = xkb_state_new(xkb_keymap_); } -EiKeyState::~EiKeyState() { +EiKeyState::~EiKeyState() +{ xkb_context_unref(xkb_); xkb_keymap_unref(xkb_keymap_); xkb_state_unref(xkb_state_); } -bool EiKeyState::fakeCtrlAltDel() { +bool EiKeyState::fakeCtrlAltDel() +{ // pass keys through unchanged return false; } -KeyModifierMask EiKeyState::pollActiveModifiers() const { - std::uint32_t xkb_mask = - xkb_state_serialize_mods(xkb_state_, XKB_STATE_MODS_EFFECTIVE); +KeyModifierMask EiKeyState::pollActiveModifiers() const +{ + std::uint32_t xkb_mask = xkb_state_serialize_mods(xkb_state_, XKB_STATE_MODS_EFFECTIVE); return convert_mod_mask(xkb_mask); } -std::int32_t EiKeyState::pollActiveGroup() const { +std::int32_t EiKeyState::pollActiveGroup() const +{ return xkb_state_serialize_layout(xkb_state_, XKB_STATE_LAYOUT_EFFECTIVE); } -void EiKeyState::pollPressedKeys(KeyButtonSet &pressedKeys) const { +void EiKeyState::pollPressedKeys(KeyButtonSet &pressedKeys) const +{ // FIXME return; } -std::uint32_t EiKeyState::convert_mod_mask(std::uint32_t xkb_mask) const { +std::uint32_t EiKeyState::convert_mod_mask(std::uint32_t xkb_mask) const +{ std::uint32_t barrier_mask = 0; - for (xkb_mod_index_t xkbmod = 0; xkbmod < xkb_keymap_num_mods(xkb_keymap_); - xkbmod++) { + for (xkb_mod_index_t xkbmod = 0; xkbmod < xkb_keymap_num_mods(xkb_keymap_); xkbmod++) { if ((xkb_mask & (1 << xkbmod)) == 0) continue; @@ -147,12 +149,11 @@ std::uint32_t EiKeyState::convert_mod_mask(std::uint32_t xkb_mask) const { // Only way to figure out whether a key is a modifier key is to press it, // check if a modifier changed state and then release it again. // Luckily xkbcommon allows us to do this in a separate state. -void EiKeyState::assign_generated_modifiers( - std::uint32_t keycode, deskflow::KeyMap::KeyItem &item) { +void EiKeyState::assign_generated_modifiers(std::uint32_t keycode, deskflow::KeyMap::KeyItem &item) +{ std::uint32_t mods_generates = 0; auto state = xkb_state_new(xkb_keymap_); - enum xkb_state_component changed = - xkb_state_update_key(state, keycode, XKB_KEY_DOWN); + enum xkb_state_component changed = xkb_state_update_key(state, keycode, XKB_KEY_DOWN); if (changed) { for (xkb_mod_index_t m = 0; m < xkb_keymap_num_mods(xkb_keymap_); m++) { @@ -170,7 +171,8 @@ void EiKeyState::assign_generated_modifiers( item.m_generates = convert_mod_mask(mods_generates); } -void EiKeyState::getKeyMap(deskflow::KeyMap &keyMap) { +void EiKeyState::getKeyMap(deskflow::KeyMap &keyMap) +{ auto min_keycode = xkb_keymap_min_keycode(xkb_keymap_); auto max_keycode = xkb_keymap_max_keycode(xkb_keymap_); @@ -181,25 +183,18 @@ void EiKeyState::getKeyMap(deskflow::KeyMap &keyMap) { if (xkb_keymap_num_layouts_for_key(xkb_keymap_, keycode) == 0) continue; - for (auto group = 0U; group < xkb_keymap_num_layouts(xkb_keymap_); - group++) { - for (auto level = 0U; - level < xkb_keymap_num_levels_for_key(xkb_keymap_, keycode, group); - level++) { + for (auto group = 0U; group < xkb_keymap_num_layouts(xkb_keymap_); group++) { + for (auto level = 0U; level < xkb_keymap_num_levels_for_key(xkb_keymap_, keycode, group); level++) { const xkb_keysym_t *syms; xkb_mod_mask_t masks[64]; - auto nmasks = xkb_keymap_key_get_mods_for_level( - xkb_keymap_, keycode, group, level, masks, 64); - auto nsyms = xkb_keymap_key_get_syms_by_level( - xkb_keymap_, keycode, group, level, &syms); + auto nmasks = xkb_keymap_key_get_mods_for_level(xkb_keymap_, keycode, group, level, masks, 64); + auto nsyms = xkb_keymap_key_get_syms_by_level(xkb_keymap_, keycode, group, level, &syms); if (nsyms == 0) continue; if (nsyms > 1) - LOG_WARN( - "multiple keysyms per keycode are not supported, keycode %d", - keycode); + LOG_WARN("multiple keysyms per keycode are not supported, keycode %d", keycode); deskflow::KeyMap::KeyItem item{}; xkb_keysym_t keysym = syms[0]; @@ -228,8 +223,7 @@ void EiKeyState::getKeyMap(deskflow::KeyMap &keyMap) { assign_generated_modifiers(keycode, item); // add capslock version of key is sensitive to capslock - if (item.m_sensitive & KeyModifierShift && - item.m_sensitive & KeyModifierCapsLock) { + if (item.m_sensitive & KeyModifierShift && item.m_sensitive & KeyModifierCapsLock) { item.m_required &= ~KeyModifierShift; item.m_required |= KeyModifierCapsLock; keyMap.addKeyEntry(item); @@ -246,37 +240,37 @@ void EiKeyState::getKeyMap(deskflow::KeyMap &keyMap) { keyMap.allowGroupSwitchDuringCompose(); } -void EiKeyState::fakeKey(const Keystroke &keystroke) { +void EiKeyState::fakeKey(const Keystroke &keystroke) +{ switch (keystroke.m_type) { case Keystroke::kButton: LOG_DEBUG1( - "fake key: %03x (%08x) %s", keystroke.m_data.m_button.m_button, - keystroke.m_data.m_button.m_client, - keystroke.m_data.m_button.m_press ? "down" : "up"); - screen_->fakeKey( - keystroke.m_data.m_button.m_button, keystroke.m_data.m_button.m_press); + "fake key: %03x (%08x) %s", keystroke.m_data.m_button.m_button, keystroke.m_data.m_button.m_client, + keystroke.m_data.m_button.m_press ? "down" : "up" + ); + screen_->fakeKey(keystroke.m_data.m_button.m_button, keystroke.m_data.m_button.m_press); break; default: break; } } -KeyID EiKeyState::map_key_from_keyval(uint32_t keyval) const { +KeyID EiKeyState::map_key_from_keyval(uint32_t keyval) const +{ // FIXME: That might be a bit crude...? xkb_keysym_t xkb_keysym = xkb_state_key_get_one_sym(xkb_state_, keyval); KeySym keysym = static_cast(xkb_keysym); KeyID keyid = XWindowsUtil::mapKeySymToKeyID(keysym); - LOG_DEBUG1( - "mapped key: code=%d keysym=0x%04lx to keyID=%d", keyval, keysym, keyid); + LOG_DEBUG1("mapped key: code=%d keysym=0x%04lx to keyID=%d", keyval, keysym, keyid); return keyid; } -void EiKeyState::update_xkb_state(uint32_t keyval, bool is_pressed) { +void EiKeyState::update_xkb_state(uint32_t keyval, bool is_pressed) +{ LOG_DEBUG1("update key state: keyval=%d pressed=%i", keyval, is_pressed); - xkb_state_update_key( - xkb_state_, keyval, is_pressed ? XKB_KEY_DOWN : XKB_KEY_UP); + xkb_state_update_key(xkb_state_, keyval, is_pressed ? XKB_KEY_DOWN : XKB_KEY_UP); } } // namespace deskflow diff --git a/src/lib/platform/EiKeyState.h b/src/lib/platform/EiKeyState.h index d894456dc..379394230 100644 --- a/src/lib/platform/EiKeyState.h +++ b/src/lib/platform/EiKeyState.h @@ -28,7 +28,8 @@ struct xkb_state; namespace deskflow { /// A key state for Ei -class EiKeyState : public KeyState { +class EiKeyState : public KeyState +{ public: EiKeyState(EiScreen *screen, IEventQueue *events); ~EiKeyState(); diff --git a/src/lib/platform/EiScreen.cpp b/src/lib/platform/EiScreen.cpp index f6221ab84..ae0630695 100644 --- a/src/lib/platform/EiScreen.cpp +++ b/src/lib/platform/EiScreen.cpp @@ -42,7 +42,8 @@ #include #include -struct ScrollRemainder { +struct ScrollRemainder +{ double x, y; // scroll remainder in pixels }; @@ -54,19 +55,20 @@ EiScreen::EiScreen(bool is_primary, IEventQueue *events, bool use_portal) events_(events), w_(1), h_(1), - is_on_screen_(is_primary) { + is_on_screen_(is_primary) +{ init_ei(); key_state_ = new EiKeyState(this, events); // install event handlers events_->adoptHandler( - Event::kSystem, events_->getSystemTarget(), - new TMethodEventJob(this, &EiScreen::handleSystemEvent)); + Event::kSystem, events_->getSystemTarget(), new TMethodEventJob(this, &EiScreen::handleSystemEvent) + ); if (use_portal) { events_->adoptHandler( events_->forEi().connected(), getEventTarget(), - new TMethodEventJob( - this, &EiScreen::handle_connected_to_eis_event)); + new TMethodEventJob(this, &EiScreen::handle_connected_to_eis_event) + ); if (is_primary) { #if HAVE_LIBPORTAL_INPUTCAPTURE portal_input_capture_ = new PortalInputCapture(this, events_); @@ -77,8 +79,8 @@ EiScreen::EiScreen(bool is_primary, IEventQueue *events, bool use_portal) #if WINAPI_LIBPORTAL events_->adoptHandler( events_->forEi().sessionClosed(), getEventTarget(), - new TMethodEventJob( - this, &EiScreen::handle_portal_session_closed)); + new TMethodEventJob(this, &EiScreen::handle_portal_session_closed) + ); portal_remote_desktop_ = new PortalRemoteDesktop(this, events_); #else throw std::invalid_argument("missing libportal remote desktop support"); @@ -94,7 +96,8 @@ EiScreen::EiScreen(bool is_primary, IEventQueue *events, bool use_portal) } } -EiScreen::~EiScreen() { +EiScreen::~EiScreen() +{ events_->adoptBuffer(nullptr); events_->removeHandler(Event::kSystem, events_->getSystemTarget()); @@ -110,9 +113,8 @@ EiScreen::~EiScreen() { #endif } -void EiScreen::handle_ei_log_event( - ei *ei, ei_log_priority priority, const char *message, - ei_log_context *context) { +void EiScreen::handle_ei_log_event(ei *ei, ei_log_priority priority, const char *message, ei_log_context *context) +{ switch (priority) { case EI_LOG_PRIORITY_DEBUG: LOG_DEBUG1("ei: %s", message); @@ -132,7 +134,8 @@ void EiScreen::handle_ei_log_event( } } -void EiScreen::init_ei() { +void EiScreen::init_ei() +{ if (is_primary_) { ei_ = ei_new_receiver(nullptr); // we receive from the display server } else { @@ -148,7 +151,8 @@ void EiScreen::init_ei() { events_->adoptBuffer(new EiEventQueueBuffer(this, ei_, events_)); } -void EiScreen::cleanup_ei() { +void EiScreen::cleanup_ei() +{ if (ei_pointer_) { free(ei_device_get_user_data(ei_pointer_)); ei_device_set_user_data(ei_pointer_, nullptr); @@ -174,36 +178,43 @@ void EiScreen::cleanup_ei() { ei_ = ei_unref(ei_); } -void *EiScreen::getEventTarget() const { +void *EiScreen::getEventTarget() const +{ return const_cast(static_cast(this)); } -bool EiScreen::getClipboard(ClipboardID id, IClipboard *clipboard) const { +bool EiScreen::getClipboard(ClipboardID id, IClipboard *clipboard) const +{ return false; } -void EiScreen::getShape(int32_t &x, int32_t &y, int32_t &w, int32_t &h) const { +void EiScreen::getShape(int32_t &x, int32_t &y, int32_t &w, int32_t &h) const +{ x = x_; y = y_; w = w_; h = h_; } -void EiScreen::getCursorPos(int32_t &x, int32_t &y) const { +void EiScreen::getCursorPos(int32_t &x, int32_t &y) const +{ x = cursor_x_; y = cursor_y_; } -void EiScreen::reconfigure(uint32_t) { +void EiScreen::reconfigure(uint32_t) +{ // do nothing } -void EiScreen::warpCursor(int32_t x, int32_t y) { +void EiScreen::warpCursor(int32_t x, int32_t y) +{ cursor_x_ = x; cursor_y_ = y; } -std::uint32_t EiScreen::registerHotKey(KeyID key, KeyModifierMask mask) { +std::uint32_t EiScreen::registerHotKey(KeyID key, KeyModifierMask mask) +{ static std::uint32_t next_id; std::uint32_t id = std::min(++next_id, 1u); @@ -219,7 +230,8 @@ std::uint32_t EiScreen::registerHotKey(KeyID key, KeyModifierMask mask) { return id; } -void EiScreen::unregisterHotKey(uint32_t id) { +void EiScreen::unregisterHotKey(uint32_t id) +{ for (auto &set : hotkeys_) { if (set.second.remove_by_id(id)) { break; @@ -227,24 +239,34 @@ void EiScreen::unregisterHotKey(uint32_t id) { } } -void EiScreen::fakeInputBegin() { +void EiScreen::fakeInputBegin() +{ // FIXME -- not implemented } -void EiScreen::fakeInputEnd() { +void EiScreen::fakeInputEnd() +{ // FIXME -- not implemented } -std::int32_t EiScreen::getJumpZoneSize() const { return 1; } +std::int32_t EiScreen::getJumpZoneSize() const +{ + return 1; +} -bool EiScreen::isAnyMouseButtonDown(uint32_t &buttonID) const { return false; } +bool EiScreen::isAnyMouseButtonDown(uint32_t &buttonID) const +{ + return false; +} -void EiScreen::getCursorCenter(int32_t &x, int32_t &y) const { +void EiScreen::getCursorCenter(int32_t &x, int32_t &y) const +{ x = x_ + w_ / 2; y = y_ + h_ / 2; } -void EiScreen::fakeMouseButton(ButtonID button, bool press) { +void EiScreen::fakeMouseButton(ButtonID button, bool press) +{ uint32_t code; if (!ei_pointer_) @@ -269,7 +291,8 @@ void EiScreen::fakeMouseButton(ButtonID button, bool press) { ei_device_frame(ei_pointer_, ei_now(ei_)); } -void EiScreen::fakeMouseMove(int32_t x, int32_t y) { +void EiScreen::fakeMouseMove(int32_t x, int32_t y) +{ // We get one motion event before enter() with the target position if (!is_on_screen_) { cursor_x_ = x; @@ -284,7 +307,8 @@ void EiScreen::fakeMouseMove(int32_t x, int32_t y) { ei_device_frame(ei_abs_, ei_now(ei_)); } -void EiScreen::fakeMouseRelativeMove(int32_t dx, int32_t dy) const { +void EiScreen::fakeMouseRelativeMove(int32_t dx, int32_t dy) const +{ if (!ei_pointer_) return; @@ -292,7 +316,8 @@ void EiScreen::fakeMouseRelativeMove(int32_t dx, int32_t dy) const { ei_device_frame(ei_pointer_, ei_now(ei_)); } -void EiScreen::fakeMouseWheel(int32_t xDelta, int32_t yDelta) const { +void EiScreen::fakeMouseWheel(int32_t xDelta, int32_t yDelta) const +{ if (!ei_pointer_) return; @@ -303,7 +328,8 @@ void EiScreen::fakeMouseWheel(int32_t xDelta, int32_t yDelta) const { ei_device_frame(ei_pointer_, ei_now(ei_)); } -void EiScreen::fakeKey(uint32_t keycode, bool is_down) const { +void EiScreen::fakeKey(uint32_t keycode, bool is_down) const +{ if (!ei_keyboard_) return; @@ -313,16 +339,19 @@ void EiScreen::fakeKey(uint32_t keycode, bool is_down) const { ei_device_frame(ei_keyboard_, ei_now(ei_)); } -void EiScreen::enable() { +void EiScreen::enable() +{ // Nothing really to be done here } -void EiScreen::disable() { +void EiScreen::disable() +{ // Nothing really to be done here, maybe cleanup in the future but ideally // that's handled elsewhere } -void EiScreen::enter() { +void EiScreen::enter() +{ is_on_screen_ = true; if (!is_primary_) { ++sequence_number_; @@ -345,9 +374,13 @@ void EiScreen::enter() { #endif } -bool EiScreen::canLeave() { return true; } +bool EiScreen::canLeave() +{ + return true; +} -void EiScreen::leave() { +void EiScreen::leave() +{ if (!is_primary_) { if (ei_pointer_) { ei_device_stop_emulating(ei_pointer_); @@ -363,42 +396,54 @@ void EiScreen::leave() { is_on_screen_ = false; } -bool EiScreen::setClipboard(ClipboardID id, const IClipboard *clipboard) { +bool EiScreen::setClipboard(ClipboardID id, const IClipboard *clipboard) +{ return false; } -void EiScreen::checkClipboards() { +void EiScreen::checkClipboards() +{ // do nothing, we're always up to date } -void EiScreen::openScreensaver(bool notify) { +void EiScreen::openScreensaver(bool notify) +{ // FIXME } -void EiScreen::closeScreensaver() { +void EiScreen::closeScreensaver() +{ // FIXME } -void EiScreen::screensaver(bool activate) { +void EiScreen::screensaver(bool activate) +{ // FIXME } -void EiScreen::resetOptions() { +void EiScreen::resetOptions() +{ // Should reset options to neutral, see setOptions(). // We don't have ei-specific options, nothing to do here } -void EiScreen::setOptions(const OptionsList &options) { +void EiScreen::setOptions(const OptionsList &options) +{ // We don't have ei-specific options, nothing to do here } -void EiScreen::setSequenceNumber(uint32_t seqNum) { +void EiScreen::setSequenceNumber(uint32_t seqNum) +{ // FIXME: what is this used for? } -bool EiScreen::isPrimary() const { return is_primary_; } +bool EiScreen::isPrimary() const +{ + return is_primary_; +} -void EiScreen::update_shape() { +void EiScreen::update_shape() +{ for (auto it = ei_devices_.begin(); it != ei_devices_.end(); it++) { auto idx = 0; @@ -418,7 +463,8 @@ void EiScreen::update_shape() { sendEvent(events_->forIScreen().shapeChanged(), nullptr); } -void EiScreen::add_device(struct ei_device *device) { +void EiScreen::add_device(struct ei_device *device) +{ LOG_DEBUG("adding device %s", ei_device_get_name(device)); // Noteworthy: EI in principle supports multiple devices with multiple @@ -433,8 +479,7 @@ void EiScreen::add_device(struct ei_device *device) { ei_pointer_ = ei_device_ref(device); } - if (!ei_keyboard_ && - ei_device_has_capability(device, EI_DEVICE_CAP_KEYBOARD)) { + if (!ei_keyboard_ && ei_device_has_capability(device, EI_DEVICE_CAP_KEYBOARD)) { ei_keyboard_ = ei_device_ref(device); struct ei_keymap *keymap = ei_device_keyboard_get_keymap(device); @@ -448,16 +493,13 @@ void EiScreen::add_device(struct ei_device *device) { // code) Where the EIS implementation does not tell us, we just default to // whatever libxkbcommon thinks is default. At least this way we can // influence with env vars what we get - LOG_WARN( - "keyboard device %s does not have a keymap, we are guessing", - ei_device_get_name(device)); + LOG_WARN("keyboard device %s does not have a keymap, we are guessing", ei_device_get_name(device)); key_state_->init_default_keymap(); } key_state_->updateKeyMap(); } - if (!ei_abs_ && - ei_device_has_capability(device, EI_DEVICE_CAP_POINTER_ABSOLUTE) && + if (!ei_abs_ && ei_device_has_capability(device, EI_DEVICE_CAP_POINTER_ABSOLUTE) && ei_device_has_capability(device, EI_DEVICE_CAP_BUTTON) && ei_device_has_capability(device, EI_DEVICE_CAP_SCROLL)) { ei_abs_ = ei_device_ref(device); @@ -468,7 +510,8 @@ void EiScreen::add_device(struct ei_device *device) { update_shape(); } -void EiScreen::remove_device(struct ei_device *device) { +void EiScreen::remove_device(struct ei_device *device) +{ LOG_DEBUG("removing device %s", ei_device_get_name(device)); if (device == ei_pointer_) @@ -489,11 +532,13 @@ void EiScreen::remove_device(struct ei_device *device) { update_shape(); } -void EiScreen::sendEvent(Event::Type type, void *data) { +void EiScreen::sendEvent(Event::Type type, void *data) +{ events_->addEvent(Event(type, getEventTarget(), data)); } -ButtonID EiScreen::map_button_from_evdev(ei_event *event) const { +ButtonID EiScreen::map_button_from_evdev(ei_event *event) const +{ uint32_t button = ei_event_button_get_button(event); switch (button) { @@ -514,7 +559,8 @@ ButtonID EiScreen::map_button_from_evdev(ei_event *event) const { return kButtonNone; } -bool EiScreen::on_hotkey(KeyID keyid, bool is_pressed, KeyModifierMask mask) { +bool EiScreen::on_hotkey(KeyID keyid, bool is_pressed, KeyModifierMask mask) +{ auto it = hotkeys_.find(keyid); if (it == hotkeys_.end()) { @@ -526,8 +572,7 @@ bool EiScreen::on_hotkey(KeyID keyid, bool is_pressed, KeyModifierMask mask) { // key combinations may not work correctly, more effort is needed here. auto id = it->second.find_by_mask(mask); if (id != 0) { - Event::Type type = is_pressed ? events_->forIPrimaryScreen().hotKeyDown() - : events_->forIPrimaryScreen().hotKeyUp(); + Event::Type type = is_pressed ? events_->forIPrimaryScreen().hotKeyDown() : events_->forIPrimaryScreen().hotKeyUp(); sendEvent(type, HotKeyInfo::alloc(id)); return true; } @@ -535,7 +580,8 @@ bool EiScreen::on_hotkey(KeyID keyid, bool is_pressed, KeyModifierMask mask) { return false; } -void EiScreen::on_key_event(ei_event *event) { +void EiScreen::on_key_event(ei_event *event) +{ uint32_t keycode = ei_event_keyboard_get_key(event); uint32_t keyval = keycode + 8; bool pressed = ei_event_keyboard_get_key_is_press(event); @@ -545,43 +591,39 @@ void EiScreen::on_key_event(ei_event *event) { key_state_->update_xkb_state(keyval, pressed); KeyModifierMask mask = key_state_->pollActiveModifiers(); - LOG_DEBUG1( - "event: key %s keycode=%d keyid=%d mask=0x%x", - pressed ? "press" : "release", keycode, keyid, mask); + LOG_DEBUG1("event: key %s keycode=%d keyid=%d mask=0x%x", pressed ? "press" : "release", keycode, keyid, mask); if (is_primary_ && on_hotkey(keyid, pressed, mask)) { return; } if (keyid != kKeyNone) { - key_state_->sendKeyEvent( - getEventTarget(), pressed, false, keyid, mask, 1, keybutton); + key_state_->sendKeyEvent(getEventTarget(), pressed, false, keyid, mask, 1, keybutton); } } -void EiScreen::on_button_event(ei_event *event) { +void EiScreen::on_button_event(ei_event *event) +{ assert(is_primary_); ButtonID button = map_button_from_evdev(event); bool pressed = ei_event_button_get_is_press(event); KeyModifierMask mask = key_state_->pollActiveModifiers(); - LOG_DEBUG1( - "event: button %s button=%d mask=0x%x", pressed ? "press" : "release", - button, mask); + LOG_DEBUG1("event: button %s button=%d mask=0x%x", pressed ? "press" : "release", button, mask); if (button == kButtonNone) { LOG_DEBUG("event: button not recognized"); return; } - auto eventType = pressed ? events_->forIPrimaryScreen().buttonDown() - : events_->forIPrimaryScreen().buttonUp(); + auto eventType = pressed ? events_->forIPrimaryScreen().buttonDown() : events_->forIPrimaryScreen().buttonUp(); sendEvent(eventType, ButtonInfo::alloc(button, mask)); } -void EiScreen::on_pointer_scroll_event(ei_event *event) { +void EiScreen::on_pointer_scroll_event(ei_event *event) +{ // Ratio of 10 pixels == one wheel click because that's what mutter/gtk // use (for historical reasons). const int PIXELS_PER_WHEEL_CLICK = 10; @@ -599,8 +641,7 @@ void EiScreen::on_pointer_scroll_event(ei_event *event) { LOG_DEBUG1("event: scroll (%.2f, %.2f)", dx, dy); - struct ScrollRemainder *remainder = - static_cast(ei_device_get_user_data(device)); + struct ScrollRemainder *remainder = static_cast(ei_device_get_user_data(device)); if (!remainder) { remainder = new ScrollRemainder(); ei_device_set_user_data(device, remainder); @@ -622,15 +663,15 @@ void EiScreen::on_pointer_scroll_event(ei_event *event) { if (x != 0 || y != 0) sendEvent( events_->forIPrimaryScreen().wheel(), - WheelInfo::alloc( - (int32_t)-x * PIXEL_TO_WHEEL_RATIO, - (int32_t)-y * PIXEL_TO_WHEEL_RATIO)); + WheelInfo::alloc((int32_t)-x * PIXEL_TO_WHEEL_RATIO, (int32_t)-y * PIXEL_TO_WHEEL_RATIO) + ); remainder->x = rx; remainder->y = ry; } -void EiScreen::on_pointer_scroll_discrete_event(ei_event *event) { +void EiScreen::on_pointer_scroll_discrete_event(ei_event *event) +{ // both libei and deskflow use multiples of 120 to represent // one scroll wheel click event so we can just forward things // as-is. @@ -648,7 +689,8 @@ void EiScreen::on_pointer_scroll_discrete_event(ei_event *event) { sendEvent(events_->forIPrimaryScreen().wheel(), WheelInfo::alloc(-dx, -dy)); } -void EiScreen::on_motion_event(ei_event *event) { +void EiScreen::on_motion_event(ei_event *event) +{ assert(is_primary_); double dx = ei_event_pointer_get_dx(event); @@ -656,9 +698,7 @@ void EiScreen::on_motion_event(ei_event *event) { if (is_on_screen_) { LOG_DEBUG("event: motion on primary x=%i y=%i)", cursor_x_, cursor_y_); - sendEvent( - events_->forIPrimaryScreen().motionOnPrimary(), - MotionInfo::alloc(cursor_x_, cursor_y_)); + sendEvent(events_->forIPrimaryScreen().motionOnPrimary(), MotionInfo::alloc(cursor_x_, cursor_y_)); #if HAVE_LIBPORTAL_INPUTCAPTURE if (portal_input_capture_->is_active()) { @@ -672,18 +712,20 @@ void EiScreen::on_motion_event(ei_event *event) { auto pixel_dy = static_cast(buffer_dy); if (pixel_dx || pixel_dy) { LOG_DEBUG1("event: motion on secondary x=%d y=%d", pixel_dx, pixel_dy); - sendEvent( - events_->forIPrimaryScreen().motionOnSecondary(), - MotionInfo::alloc(pixel_dx, pixel_dy)); + sendEvent(events_->forIPrimaryScreen().motionOnSecondary(), MotionInfo::alloc(pixel_dx, pixel_dy)); buffer_dx -= pixel_dx; buffer_dy -= pixel_dy; } } } -void EiScreen::on_abs_motion_event(ei_event *event) { assert(is_primary_); } +void EiScreen::on_abs_motion_event(ei_event *event) +{ + assert(is_primary_); +} -void EiScreen::handle_connected_to_eis_event(const Event &event, void *) { +void EiScreen::handle_connected_to_eis_event(const Event &event, void *) +{ int fd = static_cast(event.getData())->m_fd; LOG_DEBUG("eis connection established, fd=%d", fd); @@ -693,14 +735,16 @@ void EiScreen::handle_connected_to_eis_event(const Event &event, void *) { } } -void EiScreen::handle_portal_session_closed(const Event &event, void *) { +void EiScreen::handle_portal_session_closed(const Event &event, void *) +{ // Portal may or may EI_EVENT_DISCONNECT us before sending the DBus Closed // signal Let's clean up either way. cleanup_ei(); init_ei(); } -void EiScreen::handleSystemEvent(const Event &sysevent, void *) { +void EiScreen::handleSystemEvent(const Event &sysevent, void *) +{ std::lock_guard lock(mutex_); bool disconnected = false; @@ -722,9 +766,9 @@ void EiScreen::handleSystemEvent(const Event &sysevent, void *) { if (!ei_seat_) { ei_seat_ = ei_seat_ref(seat); ei_seat_bind_capabilities( - ei_seat_, EI_DEVICE_CAP_POINTER, EI_DEVICE_CAP_POINTER_ABSOLUTE, - EI_DEVICE_CAP_KEYBOARD, EI_DEVICE_CAP_BUTTON, EI_DEVICE_CAP_SCROLL, - nullptr); + ei_seat_, EI_DEVICE_CAP_POINTER, EI_DEVICE_CAP_POINTER_ABSOLUTE, EI_DEVICE_CAP_KEYBOARD, + EI_DEVICE_CAP_BUTTON, EI_DEVICE_CAP_SCROLL, nullptr + ); LOG_DEBUG("ei: using seat %s", ei_seat_get_name(ei_seat_)); // we don't care about touch } @@ -810,24 +854,32 @@ void EiScreen::handleSystemEvent(const Event &sysevent, void *) { ei_ = ei_unref(ei_); } -void EiScreen::updateButtons() { +void EiScreen::updateButtons() +{ // libei relies on the EIS implementation to keep our button count correct, // so there's not much we need to/can do here. } -IKeyState *EiScreen::getKeyState() const { return key_state_; } +IKeyState *EiScreen::getKeyState() const +{ + return key_state_; +} -String EiScreen::getSecureInputApp() const { +String EiScreen::getSecureInputApp() const +{ throw std::runtime_error("get security input app not implemented"); } -EiScreen::HotKeyItem::HotKeyItem(std::uint32_t mask, std::uint32_t id) - : mask_(mask), - id_(id) {} +EiScreen::HotKeyItem::HotKeyItem(std::uint32_t mask, std::uint32_t id) : mask_(mask), id_(id) +{ +} -EiScreen::HotKeySet::HotKeySet(KeyID key) : id_(key) {} +EiScreen::HotKeySet::HotKeySet(KeyID key) : id_(key) +{ +} -bool EiScreen::HotKeySet::remove_by_id(std::uint32_t id) { +bool EiScreen::HotKeySet::remove_by_id(std::uint32_t id) +{ for (auto it = set_.begin(); it != set_.end(); ++it) { if (it->id_ == id) { set_.erase(it); @@ -837,9 +889,13 @@ bool EiScreen::HotKeySet::remove_by_id(std::uint32_t id) { return false; } -void EiScreen::HotKeySet::add_item(HotKeyItem item) { set_.push_back(item); } +void EiScreen::HotKeySet::add_item(HotKeyItem item) +{ + set_.push_back(item); +} -std::uint32_t EiScreen::HotKeySet::find_by_mask(std::uint32_t mask) const { +std::uint32_t EiScreen::HotKeySet::find_by_mask(std::uint32_t mask) const +{ for (const auto &item : set_) { if (item.mask_ == mask) { return item.id_; diff --git a/src/lib/platform/EiScreen.h b/src/lib/platform/EiScreen.h index 08f88e787..1d031a027 100644 --- a/src/lib/platform/EiScreen.h +++ b/src/lib/platform/EiScreen.h @@ -42,7 +42,8 @@ class PortalInputCapture; #endif //! Implementation of IPlatformScreen for X11 -class EiScreen : public PlatformScreen { +class EiScreen : public PlatformScreen +{ public: EiScreen(bool is_primary, IEventQueue *events, bool use_portal); ~EiScreen(); @@ -50,9 +51,7 @@ public: // IScreen overrides void *getEventTarget() const override; bool getClipboard(ClipboardID id, IClipboard *) const override; - void getShape( - std::int32_t &x, std::int32_t &y, std::int32_t &width, - std::int32_t &height) const override; + void getShape(std::int32_t &x, std::int32_t &y, std::int32_t &width, std::int32_t &height) const override; void getCursorPos(std::int32_t &x, std::int32_t &y) const override; // IPrimaryScreen overrides @@ -107,23 +106,18 @@ private: ButtonID map_button_from_evdev(ei_event *event) const; void on_key_event(ei_event *event); void on_button_event(ei_event *event); - void send_wheel_events( - ei_device *device, const int threshold, double dx, double dy, - bool is_discrete); + void send_wheel_events(ei_device *device, const int threshold, double dx, double dy, bool is_discrete); void on_pointer_scroll_event(ei_event *event); void on_pointer_scroll_discrete_event(ei_event *event); void on_motion_event(ei_event *event); void on_abs_motion_event(ei_event *event); bool on_hotkey(KeyID key, bool is_press, KeyModifierMask mask); - void handle_ei_log_event( - ei *ei, ei_log_priority priority, const char *message, - ei_log_context *context); + void handle_ei_log_event(ei *ei, ei_log_priority priority, const char *message, ei_log_context *context); void handle_connected_to_eis_event(const Event &event, void *); void handle_portal_session_closed(const Event &event, void *); - static void cb_handle_ei_log_event( - ei *ei, ei_log_priority priority, const char *message, - ei_log_context *context) { + static void cb_handle_ei_log_event(ei *ei, ei_log_priority priority, const char *message, ei_log_context *context) + { auto screen = reinterpret_cast(ei_get_user_data(ei)); screen->handle_ei_log_event(ei, priority, message, context); } @@ -169,10 +163,12 @@ private: PortalInputCapture *portal_input_capture_ = nullptr; #endif - struct HotKeyItem { + struct HotKeyItem + { public: HotKeyItem(std::uint32_t mask, std::uint32_t id); - bool operator<(const HotKeyItem &other) const { + bool operator<(const HotKeyItem &other) const + { return mask_ < other.mask_; }; @@ -181,10 +177,14 @@ private: std::uint32_t id_ = 0; // for registering the hotkey }; - class HotKeySet { + class HotKeySet + { public: HotKeySet(KeyID keyid); - KeyID keyid() const { return id_; }; + KeyID keyid() const + { + return id_; + }; bool remove_by_id(std::uint32_t id); void add_item(HotKeyItem item); std::uint32_t find_by_mask(std::uint32_t mask) const; diff --git a/src/lib/platform/IMSWindowsClipboardFacade.h b/src/lib/platform/IMSWindowsClipboardFacade.h index 0d5ac0639..be1328f40 100644 --- a/src/lib/platform/IMSWindowsClipboardFacade.h +++ b/src/lib/platform/IMSWindowsClipboardFacade.h @@ -25,8 +25,11 @@ class IMSWindowsClipboardConverter; -class IMSWindowsClipboardFacade : public IInterface { +class IMSWindowsClipboardFacade : public IInterface +{ public: virtual void write(HANDLE win32Data, UINT win32Format) = 0; - virtual ~IMSWindowsClipboardFacade() {} + virtual ~IMSWindowsClipboardFacade() + { + } }; diff --git a/src/lib/platform/IOSXKeyResource.cpp b/src/lib/platform/IOSXKeyResource.cpp index 9b7eb0975..af6f70282 100644 --- a/src/lib/platform/IOSXKeyResource.cpp +++ b/src/lib/platform/IOSXKeyResource.cpp @@ -19,7 +19,8 @@ #include -KeyID IOSXKeyResource::getKeyID(UInt8 c) { +KeyID IOSXKeyResource::getKeyID(UInt8 c) +{ if (c == 0) { return kKeyNone; } else if (c >= 32 && c < 127) { @@ -112,13 +113,10 @@ KeyID IOSXKeyResource::getKeyID(UInt8 c) { // get current keyboard script TISInputSourceRef isref = TISCopyCurrentKeyboardInputSource(); - CFArrayRef langs = (CFArrayRef)TISGetInputSourceProperty( - isref, kTISPropertyInputSourceLanguages); - CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding( - (CFStringRef)CFArrayGetValueAtIndex(langs, 0)); + CFArrayRef langs = (CFArrayRef)TISGetInputSourceProperty(isref, kTISPropertyInputSourceLanguages); + CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)CFArrayGetValueAtIndex(langs, 0)); // convert to unicode - CFStringRef cfString = CFStringCreateWithCStringNoCopy( - kCFAllocatorDefault, str, encoding, kCFAllocatorNull); + CFStringRef cfString = CFStringCreateWithCStringNoCopy(kCFAllocatorDefault, str, encoding, kCFAllocatorNull); // sometimes CFStringCreate...() returns NULL (e.g. Apple Korean // encoding with char value 214). if it did then make no key, @@ -128,8 +126,7 @@ KeyID IOSXKeyResource::getKeyID(UInt8 c) { } // convert to precomposed - CFMutableStringRef mcfString = - CFStringCreateMutableCopy(kCFAllocatorDefault, 0, cfString); + CFMutableStringRef mcfString = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, cfString); CFRelease(cfString); CFStringNormalize(mcfString, kCFStringNormalizationFormC); @@ -154,7 +151,8 @@ KeyID IOSXKeyResource::getKeyID(UInt8 c) { } } -KeyID IOSXKeyResource::unicharToKeyID(UniChar c) { +KeyID IOSXKeyResource::unicharToKeyID(UniChar c) +{ switch (c) { case 3: return kKeyKP_Enter; diff --git a/src/lib/platform/IOSXKeyResource.h b/src/lib/platform/IOSXKeyResource.h index 2d6db36e0..366800571 100644 --- a/src/lib/platform/IOSXKeyResource.h +++ b/src/lib/platform/IOSXKeyResource.h @@ -19,7 +19,8 @@ #include "deskflow/KeyState.h" -class IOSXKeyResource : public IInterface { +class IOSXKeyResource : public IInterface +{ public: virtual bool isValid() const = 0; virtual UInt32 getNumModifierCombinations() const = 0; diff --git a/src/lib/platform/MSWindowsClipboard.cpp b/src/lib/platform/MSWindowsClipboard.cpp index 263a3eba6..f40c2d49e 100644 --- a/src/lib/platform/MSWindowsClipboard.cpp +++ b/src/lib/platform/MSWindowsClipboard.cpp @@ -36,14 +36,16 @@ MSWindowsClipboard::MSWindowsClipboard(HWND window) : m_window(window), m_time(0), m_facade(new MSWindowsClipboardFacade()), - m_deleteFacade(true) { + m_deleteFacade(true) +{ // add converters, most desired first m_converters.push_back(new MSWindowsClipboardUTF16Converter); m_converters.push_back(new MSWindowsClipboardBitmapConverter); m_converters.push_back(new MSWindowsClipboardHTMLConverter); } -MSWindowsClipboard::~MSWindowsClipboard() { +MSWindowsClipboard::~MSWindowsClipboard() +{ clearConverters(); // dependency injection causes confusion over ownership, so we need @@ -53,13 +55,15 @@ MSWindowsClipboard::~MSWindowsClipboard() { delete m_facade; } -void MSWindowsClipboard::setFacade(IMSWindowsClipboardFacade &facade) { +void MSWindowsClipboard::setFacade(IMSWindowsClipboardFacade &facade) +{ delete m_facade; m_facade = &facade; m_deleteFacade = false; } -bool MSWindowsClipboard::emptyUnowned() { +bool MSWindowsClipboard::emptyUnowned() +{ LOG((CLOG_DEBUG "empty clipboard")); // empty the clipboard (and take ownership) @@ -73,7 +77,8 @@ bool MSWindowsClipboard::emptyUnowned() { return true; } -bool MSWindowsClipboard::empty() { +bool MSWindowsClipboard::empty() +{ if (!emptyUnowned()) { return false; } @@ -89,20 +94,18 @@ bool MSWindowsClipboard::empty() { return true; } -void MSWindowsClipboard::add(EFormat format, const String &data) { +void MSWindowsClipboard::add(EFormat format, const String &data) +{ bool isSucceeded = false; // convert data to win32 form - for (ConverterList::const_iterator index = m_converters.begin(); - index != m_converters.end(); ++index) { + for (ConverterList::const_iterator index = m_converters.begin(); index != m_converters.end(); ++index) { IMSWindowsClipboardConverter *converter = *index; // skip converters for other formats if (converter->getFormat() == format) { HANDLE win32Data = converter->fromIClipboard(data); if (win32Data != NULL) { - LOG( - (CLOG_DEBUG "add %d bytes to clipboard format: %d", data.size(), - format)); + LOG((CLOG_DEBUG "add %d bytes to clipboard format: %d", data.size(), format)); m_facade->write(win32Data, converter->getWin32Format()); isSucceeded = true; break; @@ -117,7 +120,8 @@ void MSWindowsClipboard::add(EFormat format, const String &data) { } } -bool MSWindowsClipboard::open(Time time) const { +bool MSWindowsClipboard::open(Time time) const +{ LOG((CLOG_DEBUG "open clipboard")); if (!OpenClipboard(m_window)) { @@ -130,16 +134,20 @@ bool MSWindowsClipboard::open(Time time) const { return true; } -void MSWindowsClipboard::close() const { +void MSWindowsClipboard::close() const +{ LOG((CLOG_DEBUG "close clipboard")); CloseClipboard(); } -IClipboard::Time MSWindowsClipboard::getTime() const { return m_time; } +IClipboard::Time MSWindowsClipboard::getTime() const +{ + return m_time; +} -bool MSWindowsClipboard::has(EFormat format) const { - for (ConverterList::const_iterator index = m_converters.begin(); - index != m_converters.end(); ++index) { +bool MSWindowsClipboard::has(EFormat format) const +{ + for (ConverterList::const_iterator index = m_converters.begin(); index != m_converters.end(); ++index) { IMSWindowsClipboardConverter *converter = *index; if (converter->getFormat() == format) { if (IsClipboardFormatAvailable(converter->getWin32Format())) { @@ -150,11 +158,11 @@ bool MSWindowsClipboard::has(EFormat format) const { return false; } -String MSWindowsClipboard::get(EFormat format) const { +String MSWindowsClipboard::get(EFormat format) const +{ // find the converter for the first clipboard format we can handle IMSWindowsClipboardConverter *converter = NULL; - for (ConverterList::const_iterator index = m_converters.begin(); - index != m_converters.end(); ++index) { + for (ConverterList::const_iterator index = m_converters.begin(); index != m_converters.end(); ++index) { converter = *index; if (converter->getFormat() == format) { @@ -182,28 +190,28 @@ String MSWindowsClipboard::get(EFormat format) const { return converter->toIClipboard(win32Data); } -void MSWindowsClipboard::clearConverters() { - for (ConverterList::iterator index = m_converters.begin(); - index != m_converters.end(); ++index) { +void MSWindowsClipboard::clearConverters() +{ + for (ConverterList::iterator index = m_converters.begin(); index != m_converters.end(); ++index) { delete *index; } m_converters.clear(); } -bool MSWindowsClipboard::isOwnedByDeskflow() { +bool MSWindowsClipboard::isOwnedByDeskflow() +{ // create ownership format if we haven't yet if (s_ownershipFormat == 0) { - s_ownershipFormat = - RegisterClipboardFormat(TEXT(DESKFLOW_APP_NAME "Ownership")); + s_ownershipFormat = RegisterClipboardFormat(TEXT(DESKFLOW_APP_NAME "Ownership")); } return (IsClipboardFormatAvailable(getOwnershipFormat()) != 0); } -UINT MSWindowsClipboard::getOwnershipFormat() { +UINT MSWindowsClipboard::getOwnershipFormat() +{ // create ownership format if we haven't yet if (s_ownershipFormat == 0) { - s_ownershipFormat = - RegisterClipboardFormat(TEXT(DESKFLOW_APP_NAME "Ownership")); + s_ownershipFormat = RegisterClipboardFormat(TEXT(DESKFLOW_APP_NAME "Ownership")); } // return the format diff --git a/src/lib/platform/MSWindowsClipboard.h b/src/lib/platform/MSWindowsClipboard.h index fd5ce9844..92a32b601 100644 --- a/src/lib/platform/MSWindowsClipboard.h +++ b/src/lib/platform/MSWindowsClipboard.h @@ -29,7 +29,8 @@ class IMSWindowsClipboardConverter; class IMSWindowsClipboardFacade; //! Microsoft windows clipboard implementation -class MSWindowsClipboard : public IClipboard { +class MSWindowsClipboard : public IClipboard +{ public: MSWindowsClipboard(HWND window); MSWindowsClipboard(HWND window, IMSWindowsClipboardFacade &facade); @@ -89,7 +90,8 @@ private: This interface defines the methods common to all win32 clipboard format converters. */ -class IMSWindowsClipboardConverter : public IInterface { +class IMSWindowsClipboardConverter : public IInterface +{ public: // accessors diff --git a/src/lib/platform/MSWindowsClipboardAnyTextConverter.cpp b/src/lib/platform/MSWindowsClipboardAnyTextConverter.cpp index 65c6bdd47..56c80d3f7 100644 --- a/src/lib/platform/MSWindowsClipboardAnyTextConverter.cpp +++ b/src/lib/platform/MSWindowsClipboardAnyTextConverter.cpp @@ -22,20 +22,24 @@ // MSWindowsClipboardAnyTextConverter // -MSWindowsClipboardAnyTextConverter::MSWindowsClipboardAnyTextConverter() { +MSWindowsClipboardAnyTextConverter::MSWindowsClipboardAnyTextConverter() +{ // do nothing } -MSWindowsClipboardAnyTextConverter::~MSWindowsClipboardAnyTextConverter() { +MSWindowsClipboardAnyTextConverter::~MSWindowsClipboardAnyTextConverter() +{ // do nothing } -IClipboard::EFormat MSWindowsClipboardAnyTextConverter::getFormat() const { +IClipboard::EFormat MSWindowsClipboardAnyTextConverter::getFormat() const +{ return IClipboard::kText; } HANDLE -MSWindowsClipboardAnyTextConverter::fromIClipboard(const String &data) const { +MSWindowsClipboardAnyTextConverter::fromIClipboard(const String &data) const +{ // convert linefeeds and then convert to desired encoding String text = doFromIClipboard(convertLinefeedToWin32(data)); UInt32 size = (UInt32)text.size(); @@ -57,7 +61,8 @@ MSWindowsClipboardAnyTextConverter::fromIClipboard(const String &data) const { return gData; } -String MSWindowsClipboardAnyTextConverter::toIClipboard(HANDLE data) const { +String MSWindowsClipboardAnyTextConverter::toIClipboard(HANDLE data) const +{ // get datator const char *src = (const char *)GlobalLock(data); UInt32 srcSize = (UInt32)GlobalSize(data); @@ -75,8 +80,8 @@ String MSWindowsClipboardAnyTextConverter::toIClipboard(HANDLE data) const { return convertLinefeedToUnix(text); } -String MSWindowsClipboardAnyTextConverter::convertLinefeedToWin32( - const String &src) const { +String MSWindowsClipboardAnyTextConverter::convertLinefeedToWin32(const String &src) const +{ // note -- we assume src is a valid UTF-8 string // count newlines in string @@ -107,8 +112,8 @@ String MSWindowsClipboardAnyTextConverter::convertLinefeedToWin32( return dst; } -String MSWindowsClipboardAnyTextConverter::convertLinefeedToUnix( - const String &src) const { +String MSWindowsClipboardAnyTextConverter::convertLinefeedToUnix(const String &src) const +{ // count newlines in string UInt32 numNewlines = 0; UInt32 n = (UInt32)src.size(); diff --git a/src/lib/platform/MSWindowsClipboardAnyTextConverter.h b/src/lib/platform/MSWindowsClipboardAnyTextConverter.h index af854adb7..383a134e7 100644 --- a/src/lib/platform/MSWindowsClipboardAnyTextConverter.h +++ b/src/lib/platform/MSWindowsClipboardAnyTextConverter.h @@ -21,7 +21,8 @@ #include "platform/MSWindowsClipboard.h" //! Convert to/from some text encoding -class MSWindowsClipboardAnyTextConverter : public IMSWindowsClipboardConverter { +class MSWindowsClipboardAnyTextConverter : public IMSWindowsClipboardConverter +{ public: MSWindowsClipboardAnyTextConverter(); virtual ~MSWindowsClipboardAnyTextConverter(); diff --git a/src/lib/platform/MSWindowsClipboardBitmapConverter.cpp b/src/lib/platform/MSWindowsClipboardBitmapConverter.cpp index bfac10b22..c6477b211 100644 --- a/src/lib/platform/MSWindowsClipboardBitmapConverter.cpp +++ b/src/lib/platform/MSWindowsClipboardBitmapConverter.cpp @@ -24,24 +24,29 @@ // MSWindowsClipboardBitmapConverter // -MSWindowsClipboardBitmapConverter::MSWindowsClipboardBitmapConverter() { +MSWindowsClipboardBitmapConverter::MSWindowsClipboardBitmapConverter() +{ // do nothing } -MSWindowsClipboardBitmapConverter::~MSWindowsClipboardBitmapConverter() { +MSWindowsClipboardBitmapConverter::~MSWindowsClipboardBitmapConverter() +{ // do nothing } -IClipboard::EFormat MSWindowsClipboardBitmapConverter::getFormat() const { +IClipboard::EFormat MSWindowsClipboardBitmapConverter::getFormat() const +{ return IClipboard::kBitmap; } -UINT MSWindowsClipboardBitmapConverter::getWin32Format() const { +UINT MSWindowsClipboardBitmapConverter::getWin32Format() const +{ return CF_DIB; } HANDLE -MSWindowsClipboardBitmapConverter::fromIClipboard(const String &data) const { +MSWindowsClipboardBitmapConverter::fromIClipboard(const String &data) const +{ // copy to memory handle HGLOBAL gData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, data.size()); if (gData != NULL) { @@ -59,7 +64,8 @@ MSWindowsClipboardBitmapConverter::fromIClipboard(const String &data) const { return gData; } -String MSWindowsClipboardBitmapConverter::toIClipboard(HANDLE data) const { +String MSWindowsClipboardBitmapConverter::toIClipboard(HANDLE data) const +{ // get datator LPVOID src = GlobalLock(data); if (src == NULL) { @@ -70,11 +76,10 @@ String MSWindowsClipboardBitmapConverter::toIClipboard(HANDLE data) const { // check image type const BITMAPINFO *bitmap = static_cast(src); LOG( - (CLOG_INFO "bitmap: %dx%d %d", bitmap->bmiHeader.biWidth, - bitmap->bmiHeader.biHeight, (int)bitmap->bmiHeader.biBitCount)); - if (bitmap->bmiHeader.biPlanes == 1 && - (bitmap->bmiHeader.biBitCount == 24 || - bitmap->bmiHeader.biBitCount == 32) && + (CLOG_INFO "bitmap: %dx%d %d", bitmap->bmiHeader.biWidth, bitmap->bmiHeader.biHeight, + (int)bitmap->bmiHeader.biBitCount) + ); + if (bitmap->bmiHeader.biPlanes == 1 && (bitmap->bmiHeader.biBitCount == 24 || bitmap->bmiHeader.biBitCount == 32) && bitmap->bmiHeader.biCompression == BI_RGB) { // already in canonical form String image(static_cast(src), srcSize); @@ -83,9 +88,8 @@ String MSWindowsClipboardBitmapConverter::toIClipboard(HANDLE data) const { } // create a destination DIB section - LOG( - (CLOG_INFO "convert image from: depth=%d comp=%d", - bitmap->bmiHeader.biBitCount, bitmap->bmiHeader.biCompression)); + LOG((CLOG_INFO "convert image from: depth=%d comp=%d", bitmap->bmiHeader.biBitCount, bitmap->bmiHeader.biCompression) + ); void *raw; BITMAPINFOHEADER info; LONG w = bitmap->bmiHeader.biWidth; @@ -102,15 +106,13 @@ String MSWindowsClipboardBitmapConverter::toIClipboard(HANDLE data) const { info.biClrUsed = 0; info.biClrImportant = 0; HDC dc = GetDC(NULL); - HBITMAP dst = - CreateDIBSection(dc, (BITMAPINFO *)&info, DIB_RGB_COLORS, &raw, NULL, 0); + HBITMAP dst = CreateDIBSection(dc, (BITMAPINFO *)&info, DIB_RGB_COLORS, &raw, NULL, 0); // find the start of the pixel data const char *srcBits = (const char *)bitmap + bitmap->bmiHeader.biSize; if (bitmap->bmiHeader.biBitCount >= 16) { if (bitmap->bmiHeader.biCompression == BI_BITFIELDS && - (bitmap->bmiHeader.biBitCount == 16 || - bitmap->bmiHeader.biBitCount == 32)) { + (bitmap->bmiHeader.biBitCount == 16 || bitmap->bmiHeader.biBitCount == 32)) { srcBits += 3 * sizeof(DWORD); } } else if (bitmap->bmiHeader.biClrUsed != 0) { @@ -123,8 +125,7 @@ String MSWindowsClipboardBitmapConverter::toIClipboard(HANDLE data) const { // copy source image to destination image HDC dstDC = CreateCompatibleDC(dc); HGDIOBJ oldBitmap = SelectObject(dstDC, dst); - SetDIBitsToDevice( - dstDC, 0, 0, w, h, 0, 0, 0, h, srcBits, bitmap, DIB_RGB_COLORS); + SetDIBitsToDevice(dstDC, 0, 0, w, h, 0, 0, 0, h, srcBits, bitmap, DIB_RGB_COLORS); SelectObject(dstDC, oldBitmap); DeleteDC(dstDC); GdiFlush(); diff --git a/src/lib/platform/MSWindowsClipboardBitmapConverter.h b/src/lib/platform/MSWindowsClipboardBitmapConverter.h index d32cc47fe..3ef05cc28 100644 --- a/src/lib/platform/MSWindowsClipboardBitmapConverter.h +++ b/src/lib/platform/MSWindowsClipboardBitmapConverter.h @@ -21,7 +21,8 @@ #include "platform/MSWindowsClipboard.h" //! Convert to/from some text encoding -class MSWindowsClipboardBitmapConverter : public IMSWindowsClipboardConverter { +class MSWindowsClipboardBitmapConverter : public IMSWindowsClipboardConverter +{ public: MSWindowsClipboardBitmapConverter(); virtual ~MSWindowsClipboardBitmapConverter(); diff --git a/src/lib/platform/MSWindowsClipboardFacade.cpp b/src/lib/platform/MSWindowsClipboardFacade.cpp index e1a048f4b..447469bb1 100644 --- a/src/lib/platform/MSWindowsClipboardFacade.cpp +++ b/src/lib/platform/MSWindowsClipboardFacade.cpp @@ -20,7 +20,8 @@ #include "platform/MSWindowsClipboard.h" -void MSWindowsClipboardFacade::write(HANDLE win32Data, UINT win32Format) { +void MSWindowsClipboardFacade::write(HANDLE win32Data, UINT win32Format) +{ if (SetClipboardData(win32Format, win32Data) == NULL) { // free converted data if we couldn't put it on // the clipboard. diff --git a/src/lib/platform/MSWindowsClipboardFacade.h b/src/lib/platform/MSWindowsClipboardFacade.h index 274ce08f4..6e9d4881d 100644 --- a/src/lib/platform/MSWindowsClipboardFacade.h +++ b/src/lib/platform/MSWindowsClipboardFacade.h @@ -22,7 +22,8 @@ #include "deskflow/IClipboard.h" -class MSWindowsClipboardFacade : public IMSWindowsClipboardFacade { +class MSWindowsClipboardFacade : public IMSWindowsClipboardFacade +{ public: virtual void write(HANDLE win32Data, UINT win32Format); }; diff --git a/src/lib/platform/MSWindowsClipboardHTMLConverter.cpp b/src/lib/platform/MSWindowsClipboardHTMLConverter.cpp index fe1c81d4f..060e2f9aa 100644 --- a/src/lib/platform/MSWindowsClipboardHTMLConverter.cpp +++ b/src/lib/platform/MSWindowsClipboardHTMLConverter.cpp @@ -24,24 +24,28 @@ // MSWindowsClipboardHTMLConverter // -MSWindowsClipboardHTMLConverter::MSWindowsClipboardHTMLConverter() { +MSWindowsClipboardHTMLConverter::MSWindowsClipboardHTMLConverter() +{ m_format = RegisterClipboardFormat("HTML Format"); } -MSWindowsClipboardHTMLConverter::~MSWindowsClipboardHTMLConverter() { +MSWindowsClipboardHTMLConverter::~MSWindowsClipboardHTMLConverter() +{ // do nothing } -IClipboard::EFormat MSWindowsClipboardHTMLConverter::getFormat() const { +IClipboard::EFormat MSWindowsClipboardHTMLConverter::getFormat() const +{ return IClipboard::kHTML; } -UINT MSWindowsClipboardHTMLConverter::getWin32Format() const { +UINT MSWindowsClipboardHTMLConverter::getWin32Format() const +{ return m_format; } -String -MSWindowsClipboardHTMLConverter::doFromIClipboard(const String &data) const { +String MSWindowsClipboardHTMLConverter::doFromIClipboard(const String &data) const +{ // prepare to CF_HTML format prefix and suffix String prefix("Version:0.9\r\nStartHTML:0000000105\r\n" "EndHTML:ZZZZZZZZZZ\r\n" @@ -55,15 +59,9 @@ MSWindowsClipboardHTMLConverter::doFromIClipboard(const String &data) const { // StartHTML is constant by the design of the prefix UInt32 EndHTML = EndFragment + (UInt32)suffix.size(); - prefix.replace( - prefix.find("XXXXXXXXXX"), 10, - deskflow::string::sprintf("%010u", StartFragment)); - prefix.replace( - prefix.find("YYYYYYYYYY"), 10, - deskflow::string::sprintf("%010u", EndFragment)); - prefix.replace( - prefix.find("ZZZZZZZZZZ"), 10, - deskflow::string::sprintf("%010u", EndHTML)); + prefix.replace(prefix.find("XXXXXXXXXX"), 10, deskflow::string::sprintf("%010u", StartFragment)); + prefix.replace(prefix.find("YYYYYYYYYY"), 10, deskflow::string::sprintf("%010u", EndFragment)); + prefix.replace(prefix.find("ZZZZZZZZZZ"), 10, deskflow::string::sprintf("%010u", EndHTML)); // concatenate prefix += data; @@ -71,8 +69,8 @@ MSWindowsClipboardHTMLConverter::doFromIClipboard(const String &data) const { return prefix; } -String -MSWindowsClipboardHTMLConverter::doToIClipboard(const String &data) const { +String MSWindowsClipboardHTMLConverter::doToIClipboard(const String &data) const +{ // get fragment start/end args String startArg = findArg(data, "StartFragment"); String endArg = findArg(data, "EndFragment"); @@ -91,8 +89,8 @@ MSWindowsClipboardHTMLConverter::doToIClipboard(const String &data) const { return data.substr(start, end - start); } -String MSWindowsClipboardHTMLConverter::findArg( - const String &data, const String &name) const { +String MSWindowsClipboardHTMLConverter::findArg(const String &data, const String &name) const +{ String::size_type i = data.find(name); if (i == String::npos) { return String(); diff --git a/src/lib/platform/MSWindowsClipboardHTMLConverter.h b/src/lib/platform/MSWindowsClipboardHTMLConverter.h index 71406acf4..e978e4760 100644 --- a/src/lib/platform/MSWindowsClipboardHTMLConverter.h +++ b/src/lib/platform/MSWindowsClipboardHTMLConverter.h @@ -21,8 +21,8 @@ #include "platform/MSWindowsClipboardAnyTextConverter.h" //! Convert to/from HTML encoding -class MSWindowsClipboardHTMLConverter - : public MSWindowsClipboardAnyTextConverter { +class MSWindowsClipboardHTMLConverter : public MSWindowsClipboardAnyTextConverter +{ public: MSWindowsClipboardHTMLConverter(); virtual ~MSWindowsClipboardHTMLConverter(); diff --git a/src/lib/platform/MSWindowsClipboardTextConverter.cpp b/src/lib/platform/MSWindowsClipboardTextConverter.cpp index 4d5f4f864..a678d00f8 100644 --- a/src/lib/platform/MSWindowsClipboardTextConverter.cpp +++ b/src/lib/platform/MSWindowsClipboardTextConverter.cpp @@ -24,24 +24,29 @@ // MSWindowsClipboardTextConverter // -MSWindowsClipboardTextConverter::MSWindowsClipboardTextConverter() { +MSWindowsClipboardTextConverter::MSWindowsClipboardTextConverter() +{ // do nothing } -MSWindowsClipboardTextConverter::~MSWindowsClipboardTextConverter() { +MSWindowsClipboardTextConverter::~MSWindowsClipboardTextConverter() +{ // do nothing } -UINT MSWindowsClipboardTextConverter::getWin32Format() const { return CF_TEXT; } +UINT MSWindowsClipboardTextConverter::getWin32Format() const +{ + return CF_TEXT; +} -String -MSWindowsClipboardTextConverter::doFromIClipboard(const String &data) const { +String MSWindowsClipboardTextConverter::doFromIClipboard(const String &data) const +{ // convert and add nul terminator return Unicode::UTF8ToText(data) += '\0'; } -String -MSWindowsClipboardTextConverter::doToIClipboard(const String &data) const { +String MSWindowsClipboardTextConverter::doToIClipboard(const String &data) const +{ // convert and truncate at first nul terminator String dst = Unicode::textToUTF8(data); String::size_type n = dst.find('\0'); diff --git a/src/lib/platform/MSWindowsClipboardTextConverter.h b/src/lib/platform/MSWindowsClipboardTextConverter.h index 0f98a2bdf..5e42b3e5d 100644 --- a/src/lib/platform/MSWindowsClipboardTextConverter.h +++ b/src/lib/platform/MSWindowsClipboardTextConverter.h @@ -21,8 +21,8 @@ #include "platform/MSWindowsClipboardAnyTextConverter.h" //! Convert to/from locale text encoding -class MSWindowsClipboardTextConverter - : public MSWindowsClipboardAnyTextConverter { +class MSWindowsClipboardTextConverter : public MSWindowsClipboardAnyTextConverter +{ public: MSWindowsClipboardTextConverter(); virtual ~MSWindowsClipboardTextConverter(); diff --git a/src/lib/platform/MSWindowsClipboardUTF16Converter.cpp b/src/lib/platform/MSWindowsClipboardUTF16Converter.cpp index 388287ea8..f521d84a0 100644 --- a/src/lib/platform/MSWindowsClipboardUTF16Converter.cpp +++ b/src/lib/platform/MSWindowsClipboardUTF16Converter.cpp @@ -24,26 +24,29 @@ // MSWindowsClipboardUTF16Converter // -MSWindowsClipboardUTF16Converter::MSWindowsClipboardUTF16Converter() { +MSWindowsClipboardUTF16Converter::MSWindowsClipboardUTF16Converter() +{ // do nothing } -MSWindowsClipboardUTF16Converter::~MSWindowsClipboardUTF16Converter() { +MSWindowsClipboardUTF16Converter::~MSWindowsClipboardUTF16Converter() +{ // do nothing } -UINT MSWindowsClipboardUTF16Converter::getWin32Format() const { +UINT MSWindowsClipboardUTF16Converter::getWin32Format() const +{ return CF_UNICODETEXT; } -String -MSWindowsClipboardUTF16Converter::doFromIClipboard(const String &data) const { +String MSWindowsClipboardUTF16Converter::doFromIClipboard(const String &data) const +{ // convert and add nul terminator return Unicode::UTF8ToUTF16(data).append(sizeof(wchar_t), 0); } -String -MSWindowsClipboardUTF16Converter::doToIClipboard(const String &data) const { +String MSWindowsClipboardUTF16Converter::doToIClipboard(const String &data) const +{ // convert and strip nul terminator String dst = Unicode::UTF16ToUTF8(data); String::size_type n = dst.find('\0'); diff --git a/src/lib/platform/MSWindowsClipboardUTF16Converter.h b/src/lib/platform/MSWindowsClipboardUTF16Converter.h index 8407bb724..6eae650f9 100644 --- a/src/lib/platform/MSWindowsClipboardUTF16Converter.h +++ b/src/lib/platform/MSWindowsClipboardUTF16Converter.h @@ -21,8 +21,8 @@ #include "platform/MSWindowsClipboardAnyTextConverter.h" //! Convert to/from UTF-16 encoding -class MSWindowsClipboardUTF16Converter - : public MSWindowsClipboardAnyTextConverter { +class MSWindowsClipboardUTF16Converter : public MSWindowsClipboardAnyTextConverter +{ public: MSWindowsClipboardUTF16Converter(); virtual ~MSWindowsClipboardUTF16Converter(); diff --git a/src/lib/platform/MSWindowsDebugOutputter.cpp b/src/lib/platform/MSWindowsDebugOutputter.cpp index e8b7a8dfd..1449fc6e5 100644 --- a/src/lib/platform/MSWindowsDebugOutputter.cpp +++ b/src/lib/platform/MSWindowsDebugOutputter.cpp @@ -22,19 +22,32 @@ #include #include -MSWindowsDebugOutputter::MSWindowsDebugOutputter() {} +MSWindowsDebugOutputter::MSWindowsDebugOutputter() +{ +} -MSWindowsDebugOutputter::~MSWindowsDebugOutputter() {} +MSWindowsDebugOutputter::~MSWindowsDebugOutputter() +{ +} -void MSWindowsDebugOutputter::open(const char *title) {} +void MSWindowsDebugOutputter::open(const char *title) +{ +} -void MSWindowsDebugOutputter::close() {} +void MSWindowsDebugOutputter::close() +{ +} -void MSWindowsDebugOutputter::show(bool showIfEmpty) {} +void MSWindowsDebugOutputter::show(bool showIfEmpty) +{ +} -bool MSWindowsDebugOutputter::write(ELevel level, const char *msg) { +bool MSWindowsDebugOutputter::write(ELevel level, const char *msg) +{ OutputDebugString((std::string(msg) + "\n").c_str()); return true; } -void MSWindowsDebugOutputter::flush() {} +void MSWindowsDebugOutputter::flush() +{ +} diff --git a/src/lib/platform/MSWindowsDebugOutputter.h b/src/lib/platform/MSWindowsDebugOutputter.h index ac0d197d1..e33a03cc7 100644 --- a/src/lib/platform/MSWindowsDebugOutputter.h +++ b/src/lib/platform/MSWindowsDebugOutputter.h @@ -25,7 +25,8 @@ This outputter writes output to the debugger. In Visual Studio, this can be seen in the Output window. */ -class MSWindowsDebugOutputter : public ILogOutputter { +class MSWindowsDebugOutputter : public ILogOutputter +{ public: MSWindowsDebugOutputter(); virtual ~MSWindowsDebugOutputter(); diff --git a/src/lib/platform/MSWindowsDesks.cpp b/src/lib/platform/MSWindowsDesks.cpp index 67ce88abb..4c91ae002 100644 --- a/src/lib/platform/MSWindowsDesks.cpp +++ b/src/lib/platform/MSWindowsDesks.cpp @@ -88,11 +88,11 @@ // enable; #define DESKFLOW_MSG_FAKE_INPUT DESKFLOW_HOOK_LAST_MSG + 12 -static void send_keyboard_input(WORD wVk, WORD wScan, DWORD dwFlags) { +static void send_keyboard_input(WORD wVk, WORD wScan, DWORD dwFlags) +{ INPUT inp; inp.type = INPUT_KEYBOARD; - inp.ki.wVk = - (dwFlags & KEYEVENTF_UNICODE) ? 0 : wVk; // 1..254 inclusive otherwise + inp.ki.wVk = (dwFlags & KEYEVENTF_UNICODE) ? 0 : wVk; // 1..254 inclusive otherwise inp.ki.wScan = wScan; inp.ki.dwFlags = dwFlags & 0xF; inp.ki.time = 0; @@ -100,7 +100,8 @@ static void send_keyboard_input(WORD wVk, WORD wScan, DWORD dwFlags) { SendInput(1, &inp, sizeof(inp)); } -static void send_mouse_input(DWORD dwFlags, DWORD dx, DWORD dy, DWORD dwData) { +static void send_mouse_input(DWORD dwFlags, DWORD dx, DWORD dy, DWORD dwData) +{ INPUT inp; inp.type = INPUT_MOUSE; inp.mi.dwFlags = dwFlags; @@ -117,8 +118,9 @@ static void send_mouse_input(DWORD dwFlags, DWORD dx, DWORD dy, DWORD dwData) { // MSWindowsDesks::MSWindowsDesks( - bool isPrimary, bool noHooks, const IScreenSaver *screensaver, - IEventQueue *events, IJob *updateKeys, bool stopOnDeskSwitch) + bool isPrimary, bool noHooks, const IScreenSaver *screensaver, IEventQueue *events, IJob *updateKeys, + bool stopOnDeskSwitch +) : m_isPrimary(isPrimary), m_noHooks(noHooks), m_isOnScreen(m_isPrimary), @@ -138,7 +140,8 @@ MSWindowsDesks::MSWindowsDesks( m_deskReady(&m_mutex, false), m_updateKeys(updateKeys), m_events(events), - m_stopOnDeskSwitch(stopOnDeskSwitch) { + m_stopOnDeskSwitch(stopOnDeskSwitch) +{ m_cursor = createBlankCursor(); m_deskClass = createDeskWindowClass(m_isPrimary); @@ -146,14 +149,16 @@ MSWindowsDesks::MSWindowsDesks( resetOptions(); } -MSWindowsDesks::~MSWindowsDesks() { +MSWindowsDesks::~MSWindowsDesks() +{ disable(); destroyClass(m_deskClass); destroyCursor(m_cursor); delete m_updateKeys; } -void MSWindowsDesks::enable() { +void MSWindowsDesks::enable() +{ m_threadID = GetCurrentThreadId(); // set the active desk and (re)install the hooks @@ -165,14 +170,14 @@ void MSWindowsDesks::enable() { // change but as far as i can tell it doesn't. m_timer = m_events->newTimer(0.2, NULL); m_events->adoptHandler( - Event::kTimer, m_timer, - new TMethodEventJob( - this, &MSWindowsDesks::handleCheckDesk)); + Event::kTimer, m_timer, new TMethodEventJob(this, &MSWindowsDesks::handleCheckDesk) + ); updateKeys(); } -void MSWindowsDesks::disable() { +void MSWindowsDesks::disable() +{ // remove timer if (m_timer != NULL) { m_events->removeHandler(Event::kTimer, m_timer); @@ -186,30 +191,40 @@ void MSWindowsDesks::disable() { m_isOnScreen = m_isPrimary; } -void MSWindowsDesks::enter() { sendMessage(DESKFLOW_MSG_ENTER, 0, 0); } +void MSWindowsDesks::enter() +{ + sendMessage(DESKFLOW_MSG_ENTER, 0, 0); +} -void MSWindowsDesks::leave(HKL keyLayout) { +void MSWindowsDesks::leave(HKL keyLayout) +{ sendMessage(DESKFLOW_MSG_LEAVE, (WPARAM)keyLayout, 0); } -void MSWindowsDesks::resetOptions() { m_leaveForegroundOption = false; } +void MSWindowsDesks::resetOptions() +{ + m_leaveForegroundOption = false; +} -void MSWindowsDesks::setOptions(const OptionsList &options) { +void MSWindowsDesks::setOptions(const OptionsList &options) +{ for (UInt32 i = 0, n = (UInt32)options.size(); i < n; i += 2) { if (options[i] == kOptionWin32KeepForeground) { m_leaveForegroundOption = (options[i + 1] != 0); - LOG( - (CLOG_DEBUG1 "%s the foreground window", - m_leaveForegroundOption ? "don\'t grab" : "grab")); + LOG((CLOG_DEBUG1 "%s the foreground window", m_leaveForegroundOption ? "don\'t grab" : "grab")); } } } -void MSWindowsDesks::updateKeys() { sendMessage(DESKFLOW_MSG_SYNC_KEYS, 0, 0); } +void MSWindowsDesks::updateKeys() +{ + sendMessage(DESKFLOW_MSG_SYNC_KEYS, 0, 0); +} void MSWindowsDesks::setShape( - SInt32 x, SInt32 y, SInt32 width, SInt32 height, SInt32 xCenter, - SInt32 yCenter, bool isMultimon) { + SInt32 x, SInt32 y, SInt32 width, SInt32 height, SInt32 xCenter, SInt32 yCenter, bool isMultimon +) +{ m_x = x; m_y = y; m_w = width; @@ -219,34 +234,39 @@ void MSWindowsDesks::setShape( m_multimon = isMultimon; } -void MSWindowsDesks::installScreensaverHooks(bool install) { +void MSWindowsDesks::installScreensaverHooks(bool install) +{ if (m_isPrimary && m_screensaverNotify != install) { m_screensaverNotify = install; sendMessage(DESKFLOW_MSG_SCREENSAVER, install, 0); } } -void MSWindowsDesks::fakeInputBegin() { +void MSWindowsDesks::fakeInputBegin() +{ sendMessage(DESKFLOW_MSG_FAKE_INPUT, 1, 0); } -void MSWindowsDesks::fakeInputEnd() { +void MSWindowsDesks::fakeInputEnd() +{ sendMessage(DESKFLOW_MSG_FAKE_INPUT, 0, 0); } -void MSWindowsDesks::getCursorPos(SInt32 &x, SInt32 &y) const { +void MSWindowsDesks::getCursorPos(SInt32 &x, SInt32 &y) const +{ POINT pos; sendMessage(DESKFLOW_MSG_CURSOR_POS, reinterpret_cast(&pos), 0); x = pos.x; y = pos.y; } -void MSWindowsDesks::fakeKeyEvent( - WORD virtualKey, WORD scanCode, DWORD flags, bool /*isAutoRepeat*/) const { +void MSWindowsDesks::fakeKeyEvent(WORD virtualKey, WORD scanCode, DWORD flags, bool /*isAutoRepeat*/) const +{ sendMessage(DESKFLOW_MSG_FAKE_KEY, flags, MAKELPARAM(scanCode, virtualKey)); } -void MSWindowsDesks::fakeMouseButton(ButtonID button, bool press) { +void MSWindowsDesks::fakeMouseButton(ButtonID button, bool press) +{ // the system will swap the meaning of left/right for us if // the user has configured a left-handed mouse but we don't // want it to swap since we want the handedness of the @@ -297,22 +317,23 @@ void MSWindowsDesks::fakeMouseButton(ButtonID button, bool press) { sendMessage(DESKFLOW_MSG_FAKE_BUTTON, flags, data); } -void MSWindowsDesks::fakeMouseMove(SInt32 x, SInt32 y) const { - sendMessage( - DESKFLOW_MSG_FAKE_MOVE, static_cast(x), static_cast(y)); +void MSWindowsDesks::fakeMouseMove(SInt32 x, SInt32 y) const +{ + sendMessage(DESKFLOW_MSG_FAKE_MOVE, static_cast(x), static_cast(y)); } -void MSWindowsDesks::fakeMouseRelativeMove(SInt32 dx, SInt32 dy) const { - sendMessage( - DESKFLOW_MSG_FAKE_REL_MOVE, static_cast(dx), - static_cast(dy)); +void MSWindowsDesks::fakeMouseRelativeMove(SInt32 dx, SInt32 dy) const +{ + sendMessage(DESKFLOW_MSG_FAKE_REL_MOVE, static_cast(dx), static_cast(dy)); } -void MSWindowsDesks::fakeMouseWheel(SInt32 xDelta, SInt32 yDelta) const { +void MSWindowsDesks::fakeMouseWheel(SInt32 xDelta, SInt32 yDelta) const +{ sendMessage(DESKFLOW_MSG_FAKE_WHEEL, xDelta, yDelta); } -void MSWindowsDesks::sendMessage(UINT msg, WPARAM wParam, LPARAM lParam) const { +void MSWindowsDesks::sendMessage(UINT msg, WPARAM wParam, LPARAM lParam) const +{ if (m_activeDesk != NULL && m_activeDesk->m_window != NULL) { PostThreadMessage(m_activeDesk->m_threadID, msg, wParam, lParam); waitForDesk(); @@ -320,7 +341,8 @@ void MSWindowsDesks::sendMessage(UINT msg, WPARAM wParam, LPARAM lParam) const { } HCURSOR -MSWindowsDesks::createBlankCursor() const { +MSWindowsDesks::createBlankCursor() const +{ // create a transparent cursor int cw = GetSystemMetrics(SM_CXCURSOR); int ch = GetSystemMetrics(SM_CYCURSOR); @@ -328,25 +350,25 @@ MSWindowsDesks::createBlankCursor() const { UInt8 *cursorXOR = new UInt8[ch * ((cw + 31) >> 2)]; memset(cursorAND, 0xff, ch * ((cw + 31) >> 2)); memset(cursorXOR, 0x00, ch * ((cw + 31) >> 2)); - HCURSOR c = CreateCursor( - MSWindowsScreen::getWindowInstance(), 0, 0, cw, ch, cursorAND, cursorXOR); + HCURSOR c = CreateCursor(MSWindowsScreen::getWindowInstance(), 0, 0, cw, ch, cursorAND, cursorXOR); delete[] cursorXOR; delete[] cursorAND; return c; } -void MSWindowsDesks::destroyCursor(HCURSOR cursor) const { +void MSWindowsDesks::destroyCursor(HCURSOR cursor) const +{ if (cursor != NULL) { DestroyCursor(cursor); } } -ATOM MSWindowsDesks::createDeskWindowClass(bool isPrimary) const { +ATOM MSWindowsDesks::createDeskWindowClass(bool isPrimary) const +{ WNDCLASSEX classInfo; classInfo.cbSize = sizeof(classInfo); classInfo.style = CS_DBLCLKS | CS_NOCLOSE; - classInfo.lpfnWndProc = isPrimary ? &MSWindowsDesks::primaryDeskProc - : &MSWindowsDesks::secondaryDeskProc; + classInfo.lpfnWndProc = isPrimary ? &MSWindowsDesks::primaryDeskProc : &MSWindowsDesks::secondaryDeskProc; classInfo.cbClsExtra = 0; classInfo.cbWndExtra = 0; classInfo.hInstance = MSWindowsScreen::getWindowInstance(); @@ -359,18 +381,19 @@ ATOM MSWindowsDesks::createDeskWindowClass(bool isPrimary) const { return RegisterClassEx(&classInfo); } -void MSWindowsDesks::destroyClass(ATOM windowClass) const { +void MSWindowsDesks::destroyClass(ATOM windowClass) const +{ if (windowClass != 0) { - UnregisterClass( - MAKEINTATOM(windowClass), MSWindowsScreen::getWindowInstance()); + UnregisterClass(MAKEINTATOM(windowClass), MSWindowsScreen::getWindowInstance()); } } -HWND MSWindowsDesks::createWindow(ATOM windowClass, const char *name) const { +HWND MSWindowsDesks::createWindow(ATOM windowClass, const char *name) const +{ HWND window = CreateWindowEx( - WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW, MAKEINTATOM(windowClass), name, - WS_POPUP, 0, 0, 1, 1, NULL, NULL, MSWindowsScreen::getWindowInstance(), - NULL); + WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW, MAKEINTATOM(windowClass), name, WS_POPUP, 0, 0, 1, 1, NULL, NULL, + MSWindowsScreen::getWindowInstance(), NULL + ); if (window == NULL) { LOG((CLOG_ERR "failed to create window: %d", GetLastError())); throw XScreenOpenFailure(); @@ -378,19 +401,20 @@ HWND MSWindowsDesks::createWindow(ATOM windowClass, const char *name) const { return window; } -void MSWindowsDesks::destroyWindow(HWND hwnd) const { +void MSWindowsDesks::destroyWindow(HWND hwnd) const +{ if (hwnd != NULL) { DestroyWindow(hwnd); } } -LRESULT CALLBACK MSWindowsDesks::primaryDeskProc( - HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { +LRESULT CALLBACK MSWindowsDesks::primaryDeskProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ return DefWindowProc(hwnd, msg, wParam, lParam); } -LRESULT CALLBACK MSWindowsDesks::secondaryDeskProc( - HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { +LRESULT CALLBACK MSWindowsDesks::secondaryDeskProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ // would like to detect any local user input and hide the hider // window but for now we just detect mouse motion. bool hide = false; @@ -404,27 +428,27 @@ LRESULT CALLBACK MSWindowsDesks::secondaryDeskProc( if (hide && IsWindowVisible(hwnd)) { ReleaseCapture(); - SetWindowPos( - hwnd, HWND_BOTTOM, 0, 0, 0, 0, - SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_HIDEWINDOW); + SetWindowPos(hwnd, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_HIDEWINDOW); } return DefWindowProc(hwnd, msg, wParam, lParam); } -void MSWindowsDesks::deskMouseMove(SInt32 x, SInt32 y) const { +void MSWindowsDesks::deskMouseMove(SInt32 x, SInt32 y) const +{ // when using absolute positioning with mouse_event(), // the normalized device coordinates range over only // the primary screen. SInt32 w = GetSystemMetrics(SM_CXSCREEN); SInt32 h = GetSystemMetrics(SM_CYSCREEN); send_mouse_input( - MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, - (DWORD)((65535.0f * x) / (w - 1) + 0.5f), - (DWORD)((65535.0f * y) / (h - 1) + 0.5f), 0); + MOUSEEVENTF_MOVE | MOUSEEVENTF_ABSOLUTE, (DWORD)((65535.0f * x) / (w - 1) + 0.5f), + (DWORD)((65535.0f * y) / (h - 1) + 0.5f), 0 + ); } -void MSWindowsDesks::deskMouseRelativeMove(SInt32 dx, SInt32 dy) const { +void MSWindowsDesks::deskMouseRelativeMove(SInt32 dx, SInt32 dy) const +{ // relative moves are subject to cursor acceleration which we don't // want.so we disable acceleration, do the relative move, then // restore acceleration. there's a slight chance we'll end up in @@ -437,8 +461,7 @@ void MSWindowsDesks::deskMouseRelativeMove(SInt32 dx, SInt32 dy) const { // save mouse speed & acceleration int oldSpeed[4]; bool accelChanged = - SystemParametersInfo(SPI_GETMOUSE, 0, oldSpeed, 0) && - SystemParametersInfo(SPI_GETMOUSESPEED, 0, oldSpeed + 3, 0); + SystemParametersInfo(SPI_GETMOUSE, 0, oldSpeed, 0) && SystemParametersInfo(SPI_GETMOUSESPEED, 0, oldSpeed + 3, 0); // use 1:1 motion if (accelChanged) { @@ -457,14 +480,13 @@ void MSWindowsDesks::deskMouseRelativeMove(SInt32 dx, SInt32 dy) const { } } -void MSWindowsDesks::deskEnter(Desk *desk) { +void MSWindowsDesks::deskEnter(Desk *desk) +{ if (!m_isPrimary) { ReleaseCapture(); } ShowCursor(TRUE); - SetWindowPos( - desk->m_window, HWND_BOTTOM, 0, 0, 0, 0, - SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_HIDEWINDOW); + SetWindowPos(desk->m_window, HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE | SWP_HIDEWINDOW); // restore the foreground window // XXX -- this raises the window to the top of the Z-order. we @@ -481,7 +503,8 @@ void MSWindowsDesks::deskEnter(Desk *desk) { desk->m_foregroundWindow = NULL; } -void MSWindowsDesks::deskLeave(Desk *desk, HKL keyLayout) { +void MSWindowsDesks::deskLeave(Desk *desk, HKL keyLayout) +{ ShowCursor(FALSE); if (m_isPrimary) { // map a window to hide the cursor and to use whatever keyboard @@ -504,8 +527,7 @@ void MSWindowsDesks::deskLeave(Desk *desk, HKL keyLayout) { w = m_w; h = m_h; } - SetWindowPos( - desk->m_window, HWND_TOP, x, y, w, h, SWP_NOACTIVATE | SWP_SHOWWINDOW); + SetWindowPos(desk->m_window, HWND_TOP, x, y, w, h, SWP_NOACTIVATE | SWP_SHOWWINDOW); // switch to requested keyboard layout ActivateKeyboardLayout(keyLayout, 0); @@ -532,8 +554,7 @@ void MSWindowsDesks::deskLeave(Desk *desk, HKL keyLayout) { EnableWindow(desk->m_window, TRUE); SetActiveWindow(desk->m_window); DWORD thisThread = GetWindowThreadProcessId(desk->m_window, NULL); - DWORD thatThread = - GetWindowThreadProcessId(desk->m_foregroundWindow, NULL); + DWORD thatThread = GetWindowThreadProcessId(desk->m_foregroundWindow, NULL); AttachThreadInput(thatThread, thisThread, TRUE); SetForegroundWindow(desk->m_window); @@ -542,9 +563,7 @@ void MSWindowsDesks::deskLeave(Desk *desk, HKL keyLayout) { } } else { // move hider window under the cursor center, raise, and show it - SetWindowPos( - desk->m_window, HWND_TOP, m_xCenter, m_yCenter, 1, 1, - SWP_NOACTIVATE | SWP_SHOWWINDOW); + SetWindowPos(desk->m_window, HWND_TOP, m_xCenter, m_yCenter, 1, 1, SWP_NOACTIVATE | SWP_SHOWWINDOW); // watch for mouse motion. if we see any then we hide the // hider window so the user can use the physically attached @@ -553,13 +572,13 @@ void MSWindowsDesks::deskLeave(Desk *desk, HKL keyLayout) { SetCapture(desk->m_window); // warp the mouse to the cursor center - LOG(( - CLOG_DEBUG2 "warping cursor to center: %+d,%+d", m_xCenter, m_yCenter)); + LOG((CLOG_DEBUG2 "warping cursor to center: %+d,%+d", m_xCenter, m_yCenter)); deskMouseMove(m_xCenter, m_yCenter); } } -void MSWindowsDesks::deskThread(void *vdesk) { +void MSWindowsDesks::deskThread(void *vdesk) +{ MSG msg; // use given desktop for this thread @@ -574,9 +593,7 @@ void MSWindowsDesks::deskThread(void *vdesk) { // create a window. we use this window to hide the cursor. try { desk->m_window = createWindow(m_deskClass, DESKFLOW_APP_NAME "Desk"); - LOG( - (CLOG_DEBUG "desk %s window is 0x%08x", desk->m_name.c_str(), - desk->m_window)); + LOG((CLOG_DEBUG "desk %s window is 0x%08x", desk->m_name.c_str(), desk->m_window)); } catch (...) { // ignore LOG((CLOG_DEBUG "can't create desk window for %s", desk->m_name.c_str())); @@ -639,8 +656,7 @@ void MSWindowsDesks::deskThread(void *vdesk) { case DESKFLOW_MSG_FAKE_KEY: // Note, this is intended to be HI/LOWORD and not HI/LOBYTE - send_keyboard_input( - HIWORD(msg.lParam), LOWORD(msg.lParam), (DWORD)msg.wParam); + send_keyboard_input(HIWORD(msg.lParam), LOWORD(msg.lParam), (DWORD)msg.wParam); break; case DESKFLOW_MSG_FAKE_BUTTON: @@ -650,13 +666,11 @@ void MSWindowsDesks::deskThread(void *vdesk) { break; case DESKFLOW_MSG_FAKE_MOVE: - deskMouseMove( - static_cast(msg.wParam), static_cast(msg.lParam)); + deskMouseMove(static_cast(msg.wParam), static_cast(msg.lParam)); break; case DESKFLOW_MSG_FAKE_REL_MOVE: - deskMouseRelativeMove( - static_cast(msg.wParam), static_cast(msg.lParam)); + deskMouseRelativeMove(static_cast(msg.wParam), static_cast(msg.lParam)); break; case DESKFLOW_MSG_FAKE_WHEEL: @@ -691,8 +705,8 @@ void MSWindowsDesks::deskThread(void *vdesk) { case DESKFLOW_MSG_FAKE_INPUT: send_keyboard_input( - DESKFLOW_HOOK_FAKE_INPUT_VIRTUAL_KEY, - DESKFLOW_HOOK_FAKE_INPUT_SCANCODE, msg.wParam ? 0 : KEYEVENTF_KEYUP); + DESKFLOW_HOOK_FAKE_INPUT_VIRTUAL_KEY, DESKFLOW_HOOK_FAKE_INPUT_SCANCODE, msg.wParam ? 0 : KEYEVENTF_KEYUP + ); break; } @@ -712,21 +726,21 @@ void MSWindowsDesks::deskThread(void *vdesk) { } } -MSWindowsDesks::Desk *MSWindowsDesks::addDesk(const String &name, HDESK hdesk) { +MSWindowsDesks::Desk *MSWindowsDesks::addDesk(const String &name, HDESK hdesk) +{ Desk *desk = new Desk; desk->m_name = name; desk->m_desk = hdesk; desk->m_targetID = GetCurrentThreadId(); - desk->m_thread = new Thread( - new TMethodJob(this, &MSWindowsDesks::deskThread, desk)); + desk->m_thread = new Thread(new TMethodJob(this, &MSWindowsDesks::deskThread, desk)); waitForDesk(); m_desks.insert(std::make_pair(name, desk)); return desk; } -void MSWindowsDesks::removeDesks() { - for (Desks::iterator index = m_desks.begin(); index != m_desks.end(); - ++index) { +void MSWindowsDesks::removeDesks() +{ + for (Desks::iterator index = m_desks.begin(); index != m_desks.end(); ++index) { Desk *desk = index->second; PostThreadMessage(desk->m_threadID, WM_QUIT, 0, 0); desk->m_thread->wait(); @@ -738,7 +752,8 @@ void MSWindowsDesks::removeDesks() { m_activeDeskName = ""; } -void MSWindowsDesks::checkDesk() { +void MSWindowsDesks::checkDesk() +{ // get current desktop. if we already know about it then return. Desk *desk; HDESK hdesk = openInputDesktop(); @@ -756,9 +771,7 @@ void MSWindowsDesks::checkDesk() { // if we are told to shut down on desk switch, and this is not the // first switch, then shut down. if (m_stopOnDeskSwitch && m_activeDesk != NULL && name != m_activeDeskName) { - LOG( - (CLOG_DEBUG "shutting down because of desk switch to \"%s\"", - name.c_str())); + LOG((CLOG_DEBUG "shutting down because of desk switch to \"%s\"", name.c_str())); m_events->addEvent(Event(Event::kQuit)); return; } @@ -811,11 +824,13 @@ void MSWindowsDesks::checkDesk() { } } -bool MSWindowsDesks::isDeskAccessible(const Desk *desk) const { +bool MSWindowsDesks::isDeskAccessible(const Desk *desk) const +{ return (desk != NULL && desk->m_desk != NULL); } -void MSWindowsDesks::waitForDesk() const { +void MSWindowsDesks::waitForDesk() const +{ MSWindowsDesks *self = const_cast(this); Lock lock(&m_mutex); @@ -825,7 +840,8 @@ void MSWindowsDesks::waitForDesk() const { self->m_deskReady = false; } -void MSWindowsDesks::handleCheckDesk(const Event &, void *) { +void MSWindowsDesks::handleCheckDesk(const Event &, void *) +{ checkDesk(); // also check if screen saver is running if on a modern OS and @@ -838,19 +854,20 @@ void MSWindowsDesks::handleCheckDesk(const Event &, void *) { } HDESK -MSWindowsDesks::openInputDesktop() { - return OpenInputDesktop( - DF_ALLOWOTHERACCOUNTHOOK, TRUE, - DESKTOP_CREATEWINDOW | DESKTOP_HOOKCONTROL | GENERIC_WRITE); +MSWindowsDesks::openInputDesktop() +{ + return OpenInputDesktop(DF_ALLOWOTHERACCOUNTHOOK, TRUE, DESKTOP_CREATEWINDOW | DESKTOP_HOOKCONTROL | GENERIC_WRITE); } -void MSWindowsDesks::closeDesktop(HDESK desk) { +void MSWindowsDesks::closeDesktop(HDESK desk) +{ if (desk != NULL) { CloseDesktop(desk); } } -String MSWindowsDesks::getDesktopName(HDESK desk) { +String MSWindowsDesks::getDesktopName(HDESK desk) +{ if (desk == NULL) { return String(); } else { @@ -863,7 +880,8 @@ String MSWindowsDesks::getDesktopName(HDESK desk) { } } -HWND MSWindowsDesks::getForegroundWindow() const { +HWND MSWindowsDesks::getForegroundWindow() const +{ // Ideally we'd return NULL as much as possible, only returning // the actual foreground window when we know it's going to mess // up our keyboard input. For now we'll just let the user diff --git a/src/lib/platform/MSWindowsDesks.h b/src/lib/platform/MSWindowsDesks.h index edadfa072..eb225a381 100644 --- a/src/lib/platform/MSWindowsDesks.h +++ b/src/lib/platform/MSWindowsDesks.h @@ -53,7 +53,8 @@ deskflow should work on those too. This class encapsulates all the desk nastiness. Clients of this object don't have to know anything about desks. */ -class MSWindowsDesks { +class MSWindowsDesks +{ public: //! Constructor /*! @@ -65,8 +66,9 @@ public: \p hookLibrary must be a handle to the hook library. */ MSWindowsDesks( - bool isPrimary, bool noHooks, const IScreenSaver *screensaver, - IEventQueue *events, IJob *updateKeys, bool stopOnDeskSwitch); + bool isPrimary, bool noHooks, const IScreenSaver *screensaver, IEventQueue *events, IJob *updateKeys, + bool stopOnDeskSwitch + ); ~MSWindowsDesks(); //! @name manipulators @@ -123,9 +125,7 @@ public: /*! This tells the desks that the display size has changed. */ - void setShape( - SInt32 x, SInt32 y, SInt32 width, SInt32 height, SInt32 xCenter, - SInt32 yCenter, bool isMultimon); + void setShape(SInt32 x, SInt32 y, SInt32 width, SInt32 height, SInt32 xCenter, SInt32 yCenter, bool isMultimon); //! Install/uninstall screensaver hooks /*! @@ -161,8 +161,7 @@ public: /*! Synthesize a press or release of key \c button. */ - void fakeKeyEvent( - WORD virtualKey, WORD scanCode, DWORD flags, bool isAutoRepeat) const; + void fakeKeyEvent(WORD virtualKey, WORD scanCode, DWORD flags, bool isAutoRepeat) const; //! Fake mouse press/release /*! @@ -191,7 +190,8 @@ public: //@} private: - class Desk { + class Desk + { public: String m_name; Thread *m_thread; diff --git a/src/lib/platform/MSWindowsDropTarget.cpp b/src/lib/platform/MSWindowsDropTarget.cpp index 60abc9f31..b124fe8f9 100644 --- a/src/lib/platform/MSWindowsDropTarget.cpp +++ b/src/lib/platform/MSWindowsDropTarget.cpp @@ -27,20 +27,24 @@ void getDropData(IDataObject *pDataObject); MSWindowsDropTarget *MSWindowsDropTarget::s_instance = NULL; -MSWindowsDropTarget::MSWindowsDropTarget() : m_refCount(1), m_allowDrop(false) { +MSWindowsDropTarget::MSWindowsDropTarget() : m_refCount(1), m_allowDrop(false) +{ s_instance = this; } -MSWindowsDropTarget::~MSWindowsDropTarget() {} +MSWindowsDropTarget::~MSWindowsDropTarget() +{ +} -MSWindowsDropTarget &MSWindowsDropTarget::instance() { +MSWindowsDropTarget &MSWindowsDropTarget::instance() +{ assert(s_instance != NULL); return *s_instance; } HRESULT -MSWindowsDropTarget::DragEnter( - IDataObject *dataObject, DWORD keyState, POINTL point, DWORD *effect) { +MSWindowsDropTarget::DragEnter(IDataObject *dataObject, DWORD keyState, POINTL point, DWORD *effect) +{ // check if data object contain drop m_allowDrop = queryDataObject(dataObject); if (m_allowDrop) { @@ -53,41 +57,52 @@ MSWindowsDropTarget::DragEnter( } HRESULT -MSWindowsDropTarget::DragOver(DWORD keyState, POINTL point, DWORD *effect) { +MSWindowsDropTarget::DragOver(DWORD keyState, POINTL point, DWORD *effect) +{ *effect = DROPEFFECT_NONE; return S_OK; } HRESULT -MSWindowsDropTarget::DragLeave(void) { return S_OK; } +MSWindowsDropTarget::DragLeave(void) +{ + return S_OK; +} HRESULT -MSWindowsDropTarget::Drop( - IDataObject *dataObject, DWORD keyState, POINTL point, DWORD *effect) { +MSWindowsDropTarget::Drop(IDataObject *dataObject, DWORD keyState, POINTL point, DWORD *effect) +{ *effect = DROPEFFECT_NONE; return S_OK; } -bool MSWindowsDropTarget::queryDataObject(IDataObject *dataObject) { +bool MSWindowsDropTarget::queryDataObject(IDataObject *dataObject) +{ // check if it supports CF_HDROP using a HGLOBAL FORMATETC fmtetc = {CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL}; return dataObject->QueryGetData(&fmtetc) == S_OK ? true : false; } -void MSWindowsDropTarget::setDraggingFilename(char *const filename) { +void MSWindowsDropTarget::setDraggingFilename(char *const filename) +{ m_dragFilename = filename; } -std::string MSWindowsDropTarget::getDraggingFilename() { +std::string MSWindowsDropTarget::getDraggingFilename() +{ return m_dragFilename; } -void MSWindowsDropTarget::clearDraggingFilename() { m_dragFilename.clear(); } +void MSWindowsDropTarget::clearDraggingFilename() +{ + m_dragFilename.clear(); +} -void getDropData(IDataObject *dataObject) { +void getDropData(IDataObject *dataObject) +{ // construct a FORMATETC object FORMATETC fmtEtc = {CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL}; STGMEDIUM stgMed; @@ -120,8 +135,8 @@ void getDropData(IDataObject *dataObject) { } } -HRESULT __stdcall MSWindowsDropTarget::QueryInterface( - REFIID iid, void **object) { +HRESULT __stdcall MSWindowsDropTarget::QueryInterface(REFIID iid, void **object) +{ if (iid == IID_IDropTarget || iid == IID_IUnknown) { AddRef(); *object = this; @@ -132,11 +147,13 @@ HRESULT __stdcall MSWindowsDropTarget::QueryInterface( } } -ULONG __stdcall MSWindowsDropTarget::AddRef(void) { +ULONG __stdcall MSWindowsDropTarget::AddRef(void) +{ return InterlockedIncrement(&m_refCount); } -ULONG __stdcall MSWindowsDropTarget::Release(void) { +ULONG __stdcall MSWindowsDropTarget::Release(void) +{ LONG count = InterlockedDecrement(&m_refCount); if (count == 0) { diff --git a/src/lib/platform/MSWindowsDropTarget.h b/src/lib/platform/MSWindowsDropTarget.h index c12c6faf7..5cf2120c9 100644 --- a/src/lib/platform/MSWindowsDropTarget.h +++ b/src/lib/platform/MSWindowsDropTarget.h @@ -24,7 +24,8 @@ class MSWindowsScreen; -class MSWindowsDropTarget : public IDropTarget { +class MSWindowsDropTarget : public IDropTarget +{ public: MSWindowsDropTarget(); ~MSWindowsDropTarget(); @@ -35,12 +36,10 @@ public: ULONG __stdcall Release(void); // IDropTarget implementation - HRESULT __stdcall DragEnter( - IDataObject *dataObject, DWORD keyState, POINTL point, DWORD *effect); + HRESULT __stdcall DragEnter(IDataObject *dataObject, DWORD keyState, POINTL point, DWORD *effect); HRESULT __stdcall DragOver(DWORD keyState, POINTL point, DWORD *effect); HRESULT __stdcall DragLeave(void); - HRESULT __stdcall Drop( - IDataObject *dataObject, DWORD keyState, POINTL point, DWORD *effect); + HRESULT __stdcall Drop(IDataObject *dataObject, DWORD keyState, POINTL point, DWORD *effect); void setDraggingFilename(char *const); std::string getDraggingFilename(); diff --git a/src/lib/platform/MSWindowsEventQueueBuffer.cpp b/src/lib/platform/MSWindowsEventQueueBuffer.cpp index 86fcf344b..d02ad2a98 100644 --- a/src/lib/platform/MSWindowsEventQueueBuffer.cpp +++ b/src/lib/platform/MSWindowsEventQueueBuffer.cpp @@ -26,14 +26,16 @@ // EventQueueTimer // -class EventQueueTimer {}; +class EventQueueTimer +{ +}; // // MSWindowsEventQueueBuffer // -MSWindowsEventQueueBuffer::MSWindowsEventQueueBuffer(IEventQueue *events) - : m_events(events) { +MSWindowsEventQueueBuffer::MSWindowsEventQueueBuffer(IEventQueue *events) : m_events(events) +{ // remember thread. we'll be posting messages to it. m_thread = GetCurrentThreadId(); @@ -48,11 +50,13 @@ MSWindowsEventQueueBuffer::MSWindowsEventQueueBuffer(IEventQueue *events) PeekMessage(&dummy, NULL, WM_USER, WM_USER, PM_NOREMOVE); } -MSWindowsEventQueueBuffer::~MSWindowsEventQueueBuffer() { +MSWindowsEventQueueBuffer::~MSWindowsEventQueueBuffer() +{ // do nothing } -void MSWindowsEventQueueBuffer::waitForEvent(double timeout) { +void MSWindowsEventQueueBuffer::waitForEvent(double timeout) +{ // check if messages are available first. if we don't do this then // MsgWaitForMultipleObjects() will block even if the queue isn't // empty if the messages in the queue were there before the last @@ -76,16 +80,15 @@ void MSWindowsEventQueueBuffer::waitForEvent(double timeout) { MsgWaitForMultipleObjects(0, dummy, FALSE, t, QS_ALLPOSTMESSAGE); } -IEventQueueBuffer::Type -MSWindowsEventQueueBuffer::getEvent(Event &event, UInt32 &dataID) { +IEventQueueBuffer::Type MSWindowsEventQueueBuffer::getEvent(Event &event, UInt32 &dataID) +{ // NOTE: QS_ALLINPUT was replaced with QS_ALLPOSTMESSAGE. // // peek at messages first. waiting for QS_ALLINPUT will return // if a message has been sent to our window but GetMessage will // dispatch that message behind our backs and block. PeekMessage // will also dispatch behind our backs but won't block. - if (!PeekMessage(&m_event, NULL, 0, 0, PM_NOREMOVE) && - !PeekMessage(&m_event, (HWND)-1, 0, 0, PM_NOREMOVE)) { + if (!PeekMessage(&m_event, NULL, 0, 0, PM_NOREMOVE) && !PeekMessage(&m_event, (HWND)-1, 0, 0, PM_NOREMOVE)) { return kNone; } @@ -108,20 +111,22 @@ MSWindowsEventQueueBuffer::getEvent(Event &event, UInt32 &dataID) { } } -bool MSWindowsEventQueueBuffer::addEvent(UInt32 dataID) { - return ( - PostThreadMessage( - m_thread, m_userEvent, static_cast(dataID), 0) != 0); +bool MSWindowsEventQueueBuffer::addEvent(UInt32 dataID) +{ + return (PostThreadMessage(m_thread, m_userEvent, static_cast(dataID), 0) != 0); } -bool MSWindowsEventQueueBuffer::isEmpty() const { +bool MSWindowsEventQueueBuffer::isEmpty() const +{ return (HIWORD(GetQueueStatus(QS_ALLPOSTMESSAGE)) == 0); } -EventQueueTimer *MSWindowsEventQueueBuffer::newTimer(double, bool) const { +EventQueueTimer *MSWindowsEventQueueBuffer::newTimer(double, bool) const +{ return new EventQueueTimer; } -void MSWindowsEventQueueBuffer::deleteTimer(EventQueueTimer *timer) const { +void MSWindowsEventQueueBuffer::deleteTimer(EventQueueTimer *timer) const +{ delete timer; } diff --git a/src/lib/platform/MSWindowsEventQueueBuffer.h b/src/lib/platform/MSWindowsEventQueueBuffer.h index d340e8934..e4b03c6d5 100644 --- a/src/lib/platform/MSWindowsEventQueueBuffer.h +++ b/src/lib/platform/MSWindowsEventQueueBuffer.h @@ -26,13 +26,16 @@ class IEventQueue; //! Event queue buffer for Win32 -class MSWindowsEventQueueBuffer : public IEventQueueBuffer { +class MSWindowsEventQueueBuffer : public IEventQueueBuffer +{ public: MSWindowsEventQueueBuffer(IEventQueue *events); virtual ~MSWindowsEventQueueBuffer(); // IEventQueueBuffer overrides - virtual void init() {} + virtual void init() + { + } virtual void waitForEvent(double timeout); virtual Type getEvent(Event &event, UInt32 &dataID); virtual bool addEvent(UInt32 dataID); diff --git a/src/lib/platform/MSWindowsHook.cpp b/src/lib/platform/MSWindowsHook.cpp index 5d92ab715..b51b1a734 100644 --- a/src/lib/platform/MSWindowsHook.cpp +++ b/src/lib/platform/MSWindowsHook.cpp @@ -45,9 +45,12 @@ static DWORD g_hookThread = 0; static bool g_fakeServerInput = false; static BOOL g_isPrimary = TRUE; -MSWindowsHook::MSWindowsHook() {} +MSWindowsHook::MSWindowsHook() +{ +} -MSWindowsHook::~MSWindowsHook() { +MSWindowsHook::~MSWindowsHook() +{ cleanup(); if (g_processID == GetCurrentProcessId()) { @@ -57,22 +60,22 @@ MSWindowsHook::~MSWindowsHook() { } } -void MSWindowsHook::loadLibrary() { +void MSWindowsHook::loadLibrary() +{ if (g_processID == 0) { g_processID = GetCurrentProcessId(); } // initialize library if (init(GetCurrentThreadId()) == 0) { - LOG( - (CLOG_ERR "failed to init %s.dll, another program may be using it", - g_name)); + LOG((CLOG_ERR "failed to init %s.dll, another program may be using it", g_name)); LOG((CLOG_INFO "restarting your computer may solve this error")); throw XScreenOpenFailure(); } } -int MSWindowsHook::init(DWORD threadID) { +int MSWindowsHook::init(DWORD threadID) +{ // try to open process that last called init() to see if it's // still running or if it died without cleaning up. if (g_processID != 0 && g_processID != GetCurrentProcessId()) { @@ -113,7 +116,8 @@ int MSWindowsHook::init(DWORD threadID) { return 1; } -int MSWindowsHook::cleanup() { +int MSWindowsHook::cleanup() +{ if (g_processID == GetCurrentProcessId()) { g_threadID = 0; } @@ -121,10 +125,13 @@ int MSWindowsHook::cleanup() { return 1; } -void MSWindowsHook::setSides(UInt32 sides) { g_zoneSides = sides; } +void MSWindowsHook::setSides(UInt32 sides) +{ + g_zoneSides = sides; +} -void MSWindowsHook::setZone( - SInt32 x, SInt32 y, SInt32 w, SInt32 h, SInt32 jumpZoneSize) { +void MSWindowsHook::setZone(SInt32 x, SInt32 y, SInt32 w, SInt32 h, SInt32 jumpZoneSize) +{ g_zoneSize = jumpZoneSize; g_xScreen = x; g_yScreen = y; @@ -132,7 +139,8 @@ void MSWindowsHook::setZone( g_hScreen = h; } -void MSWindowsHook::setMode(EHookMode mode) { +void MSWindowsHook::setMode(EHookMode mode) +{ if (mode == g_mode) { // no change return; @@ -140,7 +148,8 @@ void MSWindowsHook::setMode(EHookMode mode) { g_mode = mode; } -static void keyboardGetState(BYTE keys[256], DWORD vkCode, bool kf_up) { +static void keyboardGetState(BYTE keys[256], DWORD vkCode, bool kf_up) +{ // we have to use GetAsyncKeyState() rather than GetKeyState() because // we don't pass through most keys so the event synchronous state // doesn't get updated. we do that because certain modifier keys have @@ -178,11 +187,13 @@ static void keyboardGetState(BYTE keys[256], DWORD vkCode, bool kf_up) { keys[VK_CAPITAL] = (BYTE)(((key < 0) ? 0x80 : 0) | (key & 1)); } -static WPARAM makeKeyMsg(UINT virtKey, WCHAR wc, bool noAltGr) { +static WPARAM makeKeyMsg(UINT virtKey, WCHAR wc, bool noAltGr) +{ return MAKEWPARAM((WORD)wc, MAKEWORD(virtKey & 0xff, noAltGr ? 1 : 0)); } -static void setDeadKey(WCHAR wc[], int size, UINT flags) { +static void setDeadKey(WCHAR wc[], int size, UINT flags) +{ if (g_deadVirtKey != 0) { auto virtualKey = static_cast(g_deadVirtKey); auto scanCode = static_cast((g_deadLParam & 0x10ff0000u) >> 16); @@ -201,7 +212,8 @@ static void setDeadKey(WCHAR wc[], int size, UINT flags) { } } -static bool keyboardHookHandler(WPARAM wParam, LPARAM lParam) { +static bool keyboardHookHandler(WPARAM wParam, LPARAM lParam) +{ DWORD vkCode = static_cast(wParam); bool kf_up = (lParam & (KF_UP << 16)) != 0; @@ -209,12 +221,10 @@ static bool keyboardHookHandler(WPARAM wParam, LPARAM lParam) { // passing events through and not report them to the server. this // is used to allow the server to synthesize events locally but // not pick them up as user events. - if (wParam == DESKFLOW_HOOK_FAKE_INPUT_VIRTUAL_KEY && - ((lParam >> 16) & 0xffu) == DESKFLOW_HOOK_FAKE_INPUT_SCANCODE) { + if (wParam == DESKFLOW_HOOK_FAKE_INPUT_VIRTUAL_KEY && ((lParam >> 16) & 0xffu) == DESKFLOW_HOOK_FAKE_INPUT_SCANCODE) { // update flag g_fakeServerInput = ((lParam & 0x80000000u) == 0); - PostThreadMessage( - g_threadID, DESKFLOW_MSG_DEBUG, 0xff000000u | wParam, lParam); + PostThreadMessage(g_threadID, DESKFLOW_MSG_DEBUG, 0xff000000u | wParam, lParam); // discard event return true; @@ -223,8 +233,7 @@ static bool keyboardHookHandler(WPARAM wParam, LPARAM lParam) { // if we're expecting fake input then just pass the event through // and do not forward to the server if (g_fakeServerInput) { - PostThreadMessage( - g_threadID, DESKFLOW_MSG_DEBUG, 0xfe000000u | wParam, lParam); + PostThreadMessage(g_threadID, DESKFLOW_MSG_DEBUG, 0xfe000000u | wParam, lParam); return false; } @@ -238,11 +247,9 @@ static bool keyboardHookHandler(WPARAM wParam, LPARAM lParam) { PostThreadMessage(g_threadID, DESKFLOW_MSG_DEBUG, wParam, lParam); // ignore dead key release - if ((g_deadVirtKey == wParam || g_deadRelease == wParam) && - (lParam & 0x80000000u) != 0) { + if ((g_deadVirtKey == wParam || g_deadRelease == wParam) && (lParam & 0x80000000u) != 0) { g_deadRelease = 0; - PostThreadMessage( - g_threadID, DESKFLOW_MSG_DEBUG, wParam | 0x04000000, lParam); + PostThreadMessage(g_threadID, DESKFLOW_MSG_DEBUG, wParam | 0x04000000, lParam); return false; } @@ -310,8 +317,7 @@ static bool keyboardHookHandler(WPARAM wParam, LPARAM lParam) { bool noAltGr = false; if (n == 0 && (control & 0x80) != 0 && (menu & 0x80) != 0) { noAltGr = true; - PostThreadMessage( - g_threadID, DESKFLOW_MSG_DEBUG, wParam | 0x05000000, lParam); + PostThreadMessage(g_threadID, DESKFLOW_MSG_DEBUG, wParam | 0x05000000, lParam); setDeadKey(wc, 2, flags); BYTE keys2[256]; @@ -328,10 +334,9 @@ static bool keyboardHookHandler(WPARAM wParam, LPARAM lParam) { } PostThreadMessage( - g_threadID, DESKFLOW_MSG_DEBUG, - (wc[0] & 0xffff) | ((wParam & 0xff) << 16) | ((n & 0xf) << 24) | - 0x60000000, - lParam); + g_threadID, DESKFLOW_MSG_DEBUG, (wc[0] & 0xffff) | ((wParam & 0xff) << 16) | ((n & 0xf) << 24) | 0x60000000, + lParam + ); WPARAM charAndVirtKey = 0; bool clearDeadKey = false; switch (n) { @@ -369,12 +374,8 @@ static bool keyboardHookHandler(WPARAM wParam, LPARAM lParam) { // previous dead key not composed. send a fake key press // and release for the dead key to our window. WPARAM deadCharAndVirtKey = makeKeyMsg((UINT)g_deadVirtKey, wc[0], noAltGr); - PostThreadMessage( - g_threadID, DESKFLOW_MSG_KEY, deadCharAndVirtKey, - g_deadLParam & 0x7fffffffu); - PostThreadMessage( - g_threadID, DESKFLOW_MSG_KEY, deadCharAndVirtKey, - g_deadLParam | 0x80000000u); + PostThreadMessage(g_threadID, DESKFLOW_MSG_KEY, deadCharAndVirtKey, g_deadLParam & 0x7fffffffu); + PostThreadMessage(g_threadID, DESKFLOW_MSG_KEY, deadCharAndVirtKey, g_deadLParam | 0x80000000u); // use uncomposed character charAndVirtKey = makeKeyMsg((UINT)wParam, wc[1], noAltGr); @@ -385,9 +386,7 @@ static bool keyboardHookHandler(WPARAM wParam, LPARAM lParam) { // put back the dead key, if any, for the application to use if (g_deadVirtKey != 0) { - ToUnicode( - (UINT)g_deadVirtKey, (g_deadLParam & 0x10ff0000u) >> 16, g_deadKeyState, - wc, 2, flags); + ToUnicode((UINT)g_deadVirtKey, (g_deadLParam & 0x10ff0000u) >> 16, g_deadKeyState, wc, 2, flags); } // clear out old dead key state @@ -403,8 +402,7 @@ static bool keyboardHookHandler(WPARAM wParam, LPARAM lParam) { // XXX -- with hot keys for actions we may only need to do this when // forwarding. if (charAndVirtKey != 0) { - PostThreadMessage( - g_threadID, DESKFLOW_MSG_DEBUG, charAndVirtKey | 0x07000000, lParam); + PostThreadMessage(g_threadID, DESKFLOW_MSG_DEBUG, charAndVirtKey | 0x07000000, lParam); PostThreadMessage(g_threadID, DESKFLOW_MSG_KEY, charAndVirtKey, lParam); } @@ -437,7 +435,8 @@ static bool keyboardHookHandler(WPARAM wParam, LPARAM lParam) { } #if !NO_GRAB_KEYBOARD -static LRESULT CALLBACK keyboardLLHook(int code, WPARAM wParam, LPARAM lParam) { +static LRESULT CALLBACK keyboardLLHook(int code, WPARAM wParam, LPARAM lParam) +{ if (code >= 0) { // decode the message KBDLLHOOKSTRUCT *info = reinterpret_cast(lParam); @@ -478,7 +477,8 @@ static LRESULT CALLBACK keyboardLLHook(int code, WPARAM wParam, LPARAM lParam) { // events very early. the earlier the better. // -static bool mouseHookHandler(WPARAM wParam, SInt32 x, SInt32 y, SInt32 data) { +static bool mouseHookHandler(WPARAM wParam, SInt32 x, SInt32 y, SInt32 data) +{ switch (wParam) { case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: @@ -574,7 +574,8 @@ static bool mouseHookHandler(WPARAM wParam, SInt32 x, SInt32 y, SInt32 data) { return false; } -static LRESULT CALLBACK mouseLLHook(int code, WPARAM wParam, LPARAM lParam) { +static LRESULT CALLBACK mouseLLHook(int code, WPARAM wParam, LPARAM lParam) +{ if (code >= 0) { // decode the message MSLLHOOKSTRUCT *info = reinterpret_cast(lParam); @@ -597,7 +598,8 @@ static LRESULT CALLBACK mouseLLHook(int code, WPARAM wParam, LPARAM lParam) { return CallNextHookEx(g_mouseLL, code, wParam, lParam); } -EHookResult MSWindowsHook::install() { +EHookResult MSWindowsHook::install() +{ assert(g_getMessage == NULL || g_screenSaver); // must be initialized @@ -646,7 +648,8 @@ EHookResult MSWindowsHook::install() { return kHOOK_OKAY; } -int MSWindowsHook::uninstall() { +int MSWindowsHook::uninstall() +{ // discard old dead keys g_deadVirtKey = 0; g_deadLParam = 0; @@ -668,7 +671,8 @@ int MSWindowsHook::uninstall() { return 1; } -static LRESULT CALLBACK getMessageHook(int code, WPARAM wParam, LPARAM lParam) { +static LRESULT CALLBACK getMessageHook(int code, WPARAM wParam, LPARAM lParam) +{ if (code >= 0) { if (g_screenSaver) { MSG *msg = reinterpret_cast(lParam); @@ -682,7 +686,8 @@ static LRESULT CALLBACK getMessageHook(int code, WPARAM wParam, LPARAM lParam) { return CallNextHookEx(g_getMessage, code, wParam, lParam); } -int MSWindowsHook::installScreenSaver() { +int MSWindowsHook::installScreenSaver() +{ // must be initialized if (g_threadID == 0) { return 0; @@ -699,7 +704,8 @@ int MSWindowsHook::installScreenSaver() { return (g_getMessage != NULL) ? 1 : 0; } -int MSWindowsHook::uninstallScreenSaver() { +int MSWindowsHook::uninstallScreenSaver() +{ // uninstall hook unless the mouse wheel hook is installed if (g_getMessage != NULL) { UnhookWindowsHookEx(g_getMessage); diff --git a/src/lib/platform/MSWindowsHook.h b/src/lib/platform/MSWindowsHook.h index 0a9bb0b48..51684395f 100644 --- a/src/lib/platform/MSWindowsHook.h +++ b/src/lib/platform/MSWindowsHook.h @@ -24,7 +24,8 @@ #include //! Loads and provides functions for the Windows hook -class MSWindowsHook { +class MSWindowsHook +{ public: MSWindowsHook(); virtual ~MSWindowsHook(); diff --git a/src/lib/platform/MSWindowsKeyState.cpp b/src/lib/platform/MSWindowsKeyState.cpp index 5d56b2460..917767dab 100644 --- a/src/lib/platform/MSWindowsKeyState.cpp +++ b/src/lib/platform/MSWindowsKeyState.cpp @@ -554,23 +554,23 @@ const KeyID MSWindowsKeyState::s_virtualKey[] = { /* 0x1ff */ {kKeyNone} // reserved }; -struct Win32Modifiers { +struct Win32Modifiers +{ public: UINT m_vk; KeyModifierMask m_mask; }; -static const Win32Modifiers s_modifiers[] = { - {VK_SHIFT, KeyModifierShift}, {VK_LSHIFT, KeyModifierShift}, - {VK_RSHIFT, KeyModifierShift}, {VK_CONTROL, KeyModifierControl}, - {VK_LCONTROL, KeyModifierControl}, {VK_RCONTROL, KeyModifierControl}, - {VK_MENU, KeyModifierAlt}, {VK_LMENU, KeyModifierAlt}, - {VK_RMENU, KeyModifierAlt}, {VK_LWIN, KeyModifierSuper}, - {VK_RWIN, KeyModifierSuper}}; +static const Win32Modifiers s_modifiers[] = {{VK_SHIFT, KeyModifierShift}, {VK_LSHIFT, KeyModifierShift}, + {VK_RSHIFT, KeyModifierShift}, {VK_CONTROL, KeyModifierControl}, + {VK_LCONTROL, KeyModifierControl}, {VK_RCONTROL, KeyModifierControl}, + {VK_MENU, KeyModifierAlt}, {VK_LMENU, KeyModifierAlt}, + {VK_RMENU, KeyModifierAlt}, {VK_LWIN, KeyModifierSuper}, + {VK_RWIN, KeyModifierSuper}}; MSWindowsKeyState::MSWindowsKeyState( - MSWindowsDesks *desks, void *eventTarget, IEventQueue *events, - std::vector layouts, bool isLangSyncEnabled) + MSWindowsDesks *desks, void *eventTarget, IEventQueue *events, std::vector layouts, bool isLangSyncEnabled +) : KeyState(events, std::move(layouts), isLangSyncEnabled), m_eventTarget(eventTarget), m_desks(desks), @@ -580,14 +580,15 @@ MSWindowsKeyState::MSWindowsKeyState( m_useSavedModifiers(false), m_savedModifiers(0), m_originalSavedModifiers(0), - m_events(events) { + m_events(events) +{ init(); } MSWindowsKeyState::MSWindowsKeyState( - MSWindowsDesks *desks, void *eventTarget, IEventQueue *events, - deskflow::KeyMap &keyMap, std::vector layouts, - bool isLangSyncEnabled) + MSWindowsDesks *desks, void *eventTarget, IEventQueue *events, deskflow::KeyMap &keyMap, + std::vector layouts, bool isLangSyncEnabled +) : KeyState(events, keyMap, std::move(layouts), isLangSyncEnabled), m_eventTarget(eventTarget), m_desks(desks), @@ -597,19 +598,25 @@ MSWindowsKeyState::MSWindowsKeyState( m_useSavedModifiers(false), m_savedModifiers(0), m_originalSavedModifiers(0), - m_events(events) { + m_events(events) +{ init(); } -MSWindowsKeyState::~MSWindowsKeyState() { disable(); } +MSWindowsKeyState::~MSWindowsKeyState() +{ + disable(); +} -void MSWindowsKeyState::init() { +void MSWindowsKeyState::init() +{ // look up symbol that's available on winNT family but not win95 HMODULE userModule = GetModuleHandle("user32.dll"); m_ToUnicodeEx = (ToUnicodeEx_t)GetProcAddress(userModule, "ToUnicodeEx"); } -void MSWindowsKeyState::disable() { +void MSWindowsKeyState::disable() +{ if (m_fixTimer != NULL) { m_events->removeHandler(Event::kTimer, m_fixTimer); m_events->deleteTimer(m_fixTimer); @@ -618,14 +625,18 @@ void MSWindowsKeyState::disable() { m_lastDown = 0; } -KeyButton MSWindowsKeyState::virtualKeyToButton(UINT virtualKey) const { +KeyButton MSWindowsKeyState::virtualKeyToButton(UINT virtualKey) const +{ return m_virtualKeyToButton[virtualKey & 0xffu]; } -void MSWindowsKeyState::setKeyLayout(HKL keyLayout) { m_keyLayout = keyLayout; } +void MSWindowsKeyState::setKeyLayout(HKL keyLayout) +{ + m_keyLayout = keyLayout; +} -bool MSWindowsKeyState::testAutoRepeat( - bool press, bool isRepeat, KeyButton button) { +bool MSWindowsKeyState::testAutoRepeat(bool press, bool isRepeat, KeyButton button) +{ if (!isRepeat) { isRepeat = (press && m_lastDown != 0 && button == m_lastDown); } @@ -637,27 +648,27 @@ bool MSWindowsKeyState::testAutoRepeat( return isRepeat; } -void MSWindowsKeyState::saveModifiers() { +void MSWindowsKeyState::saveModifiers() +{ m_savedModifiers = getActiveModifiers(); m_originalSavedModifiers = m_savedModifiers; } -void MSWindowsKeyState::useSavedModifiers(bool enable) { +void MSWindowsKeyState::useSavedModifiers(bool enable) +{ if (enable != m_useSavedModifiers) { m_useSavedModifiers = enable; if (!m_useSavedModifiers) { // transfer any modifier state changes to KeyState's state KeyModifierMask mask = m_originalSavedModifiers ^ m_savedModifiers; - getActiveModifiersRValue() = - (getActiveModifiers() & ~mask) | (m_savedModifiers & mask); + getActiveModifiersRValue() = (getActiveModifiers() & ~mask) | (m_savedModifiers & mask); } } } -KeyID MSWindowsKeyState::mapKeyFromEvent( - WPARAM charAndVirtKey, LPARAM info, KeyModifierMask *maskOut) const { - static const KeyModifierMask s_controlAlt = - KeyModifierControl | KeyModifierAlt; +KeyID MSWindowsKeyState::mapKeyFromEvent(WPARAM charAndVirtKey, LPARAM info, KeyModifierMask *maskOut) const +{ + static const KeyModifierMask s_controlAlt = KeyModifierControl | KeyModifierAlt; // extract character, virtual key, and if we didn't use AltGr auto wc = static_cast((charAndVirtKey & 0xffffu)); @@ -693,12 +704,14 @@ KeyID MSWindowsKeyState::mapKeyFromEvent( return id; } -bool MSWindowsKeyState::didGroupsChange() const { +bool MSWindowsKeyState::didGroupsChange() const +{ GroupList groups; return (getGroups(groups) && groups != m_groups); } -UINT MSWindowsKeyState::mapKeyToVirtualKey(KeyID key) const { +UINT MSWindowsKeyState::mapKeyToVirtualKey(KeyID key) const +{ if (key == kKeyNone) { return 0; } @@ -710,14 +723,15 @@ UINT MSWindowsKeyState::mapKeyToVirtualKey(KeyID key) const { } } -void MSWindowsKeyState::onKey( - KeyButton button, bool down, KeyModifierMask newState) { +void MSWindowsKeyState::onKey(KeyButton button, bool down, KeyModifierMask newState) +{ KeyState::onKey(button, down, newState); } void MSWindowsKeyState::sendKeyEvent( - void *target, bool press, bool isAutoRepeat, KeyID key, - KeyModifierMask mask, SInt32 count, KeyButton button) { + void *target, bool press, bool isAutoRepeat, KeyID key, KeyModifierMask mask, SInt32 count, KeyButton button +) +{ if (press || isAutoRepeat) { // send key if (press && !isAutoRepeat) { @@ -735,18 +749,20 @@ void MSWindowsKeyState::sendKeyEvent( } } -void MSWindowsKeyState::fakeKeyDown( - KeyID id, KeyModifierMask mask, KeyButton button, const String &lang) { +void MSWindowsKeyState::fakeKeyDown(KeyID id, KeyModifierMask mask, KeyButton button, const String &lang) +{ KeyState::fakeKeyDown(id, mask, button, lang); } bool MSWindowsKeyState::fakeKeyRepeat( - KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, - const String &lang) { + KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang +) +{ return KeyState::fakeKeyRepeat(id, mask, count, button, lang); } -bool MSWindowsKeyState::fakeCtrlAltDel() { +bool MSWindowsKeyState::fakeCtrlAltDel() +{ // to fake ctrl+alt+del on the NT family we broadcast a suitable // hotkey to all windows on the winlogon desktop. however, the // current thread must be on that desktop to do the broadcast @@ -766,14 +782,13 @@ bool MSWindowsKeyState::fakeCtrlAltDel() { return true; } -void MSWindowsKeyState::ctrlAltDelThread(void *) { +void MSWindowsKeyState::ctrlAltDelThread(void *) +{ // get the Winlogon desktop at whatever privilege we can HDESK desk = OpenDesktop("Winlogon", 0, FALSE, MAXIMUM_ALLOWED); if (desk != NULL) { if (SetThreadDesktop(desk)) { - PostMessage( - HWND_BROADCAST, WM_HOTKEY, 0, - MAKELPARAM(MOD_CONTROL | MOD_ALT, VK_DELETE)); + PostMessage(HWND_BROADCAST, WM_HOTKEY, 0, MAKELPARAM(MOD_CONTROL | MOD_ALT, VK_DELETE)); } else { LOG((CLOG_DEBUG "can't switch to Winlogon desk: %d", GetLastError())); } @@ -783,7 +798,8 @@ void MSWindowsKeyState::ctrlAltDelThread(void *) { } } -KeyModifierMask MSWindowsKeyState::pollActiveModifiers() const { +KeyModifierMask MSWindowsKeyState::pollActiveModifiers() const +{ KeyModifierMask state = 0; // get non-toggle modifiers from our own shadow key state @@ -808,7 +824,8 @@ KeyModifierMask MSWindowsKeyState::pollActiveModifiers() const { return state; } -SInt32 MSWindowsKeyState::pollActiveGroup() const { +SInt32 MSWindowsKeyState::pollActiveGroup() const +{ // determine the thread that'll receive this event HWND targetWindow = GetForegroundWindow(); DWORD targetThread = GetWindowThreadProcessId(targetWindow, NULL); @@ -834,12 +851,12 @@ SInt32 MSWindowsKeyState::pollActiveGroup() const { return i->second; } -void MSWindowsKeyState::pollPressedKeys(KeyButtonSet &pressedKeys) const { +void MSWindowsKeyState::pollPressedKeys(KeyButtonSet &pressedKeys) const +{ BYTE keyState[256]; if (!GetKeyboardState(keyState)) { LOG((CLOG_WARN "keyboard state is unexpected")); - LOG((CLOG_DEBUG - "function 'GetKeyboardState' returned false on 'pollPressedKeys'")); + LOG((CLOG_DEBUG "function 'GetKeyboardState' returned false on 'pollPressedKeys'")); return; } for (KeyButton i = 1; i < 256; ++i) { @@ -852,7 +869,8 @@ void MSWindowsKeyState::pollPressedKeys(KeyButtonSet &pressedKeys) const { } } -void MSWindowsKeyState::getKeyMap(deskflow::KeyMap &keyMap) { +void MSWindowsKeyState::getKeyMap(deskflow::KeyMap &keyMap) +{ // update keyboard groups if (getGroups(m_groups)) { m_groupMap.clear(); @@ -1057,7 +1075,8 @@ void MSWindowsKeyState::getKeyMap(deskflow::KeyMap &keyMap) { if (item.m_id == 0) { // translate virtual key to a character with and without // shift, caps lock, and AltGr. - struct Modifier { + struct Modifier + { UINT m_vk1; UINT m_vk2; BYTE m_state; @@ -1066,10 +1085,9 @@ void MSWindowsKeyState::getKeyMap(deskflow::KeyMap &keyMap) { static const Modifier modifiers[] = { {VK_SHIFT, VK_SHIFT, 0x80u, KeyModifierShift}, {VK_CAPITAL, VK_CAPITAL, 0x01u, KeyModifierCapsLock}, - {VK_CONTROL, VK_MENU, 0x80u, - KeyModifierControl | KeyModifierAlt}}; - static const size_t s_numModifiers = - sizeof(modifiers) / sizeof(modifiers[0]); + {VK_CONTROL, VK_MENU, 0x80u, KeyModifierControl | KeyModifierAlt} + }; + static const size_t s_numModifiers = sizeof(modifiers) / sizeof(modifiers[0]); static const size_t s_numCombinations = 1 << s_numModifiers; KeyID id[s_numCombinations]; @@ -1087,8 +1105,7 @@ void MSWindowsKeyState::getKeyMap(deskflow::KeyMap &keyMap) { keys[modifiers[k].m_vk2] = 0; } } - id[j] = - getIDForKey(item, button, m_buttonToVK[i], keys, m_groups[g]); + id[j] = getIDForKey(item, button, m_buttonToVK[i], keys, m_groups[g]); if (id[j] != 0) { anyFound = true; } @@ -1153,18 +1170,18 @@ void MSWindowsKeyState::getKeyMap(deskflow::KeyMap &keyMap) { ActivateKeyboardLayout(activeLayout, 0); } -void MSWindowsKeyState::fakeKey(const Keystroke &keystroke) { +void MSWindowsKeyState::fakeKey(const Keystroke &keystroke) +{ switch (keystroke.m_type) { case Keystroke::kButton: { LOG( - (CLOG_DEBUG1 " %03x (%08x) %s", keystroke.m_data.m_button.m_button, - keystroke.m_data.m_button.m_client, - keystroke.m_data.m_button.m_press ? "down" : "up")); + (CLOG_DEBUG1 " %03x (%08x) %s", keystroke.m_data.m_button.m_button, keystroke.m_data.m_button.m_client, + keystroke.m_data.m_button.m_press ? "down" : "up") + ); KeyButton scanCode = keystroke.m_data.m_button.m_button; // windows doesn't send key ups for key repeats - if (keystroke.m_data.m_button.m_repeat && - !keystroke.m_data.m_button.m_press) { + if (keystroke.m_data.m_button.m_repeat && !keystroke.m_data.m_button.m_press) { LOG((CLOG_DEBUG1 " discard key repeat release")); break; } @@ -1185,8 +1202,7 @@ void MSWindowsKeyState::fakeKey(const Keystroke &keystroke) { // vk,sc,flags,keystroke.m_data.m_button.m_repeat - m_desks->fakeKeyEvent( - vk, scanCode, flags, keystroke.m_data.m_button.m_repeat); + m_desks->fakeKeyEvent(vk, scanCode, flags, keystroke.m_data.m_button.m_repeat); // synthesize event // m_desks->fakeKeyEvent(button, vk, @@ -1205,15 +1221,15 @@ void MSWindowsKeyState::fakeKey(const Keystroke &keystroke) { setWindowGroup(keystroke.m_data.m_group.m_group); } else { LOG((CLOG_DEBUG1 " group %+d", keystroke.m_data.m_group.m_group)); - setWindowGroup(getEffectiveGroup( - pollActiveGroup(), keystroke.m_data.m_group.m_group)); + setWindowGroup(getEffectiveGroup(pollActiveGroup(), keystroke.m_data.m_group.m_group)); } } break; } } -KeyModifierMask &MSWindowsKeyState::getActiveModifiersRValue() { +KeyModifierMask &MSWindowsKeyState::getActiveModifiersRValue() +{ if (m_useSavedModifiers) { return m_savedModifiers; } else { @@ -1221,7 +1237,8 @@ KeyModifierMask &MSWindowsKeyState::getActiveModifiersRValue() { } } -bool MSWindowsKeyState::getGroups(GroupList &groups) const { +bool MSWindowsKeyState::getGroups(GroupList &groups) const +{ // get keyboard layouts UInt32 newNumLayouts = GetKeyboardLayoutList(0, NULL); if (newNumLayouts == 0) { @@ -1242,16 +1259,15 @@ bool MSWindowsKeyState::getGroups(GroupList &groups) const { return true; } -void MSWindowsKeyState::setWindowGroup(SInt32 group) { +void MSWindowsKeyState::setWindowGroup(SInt32 group) +{ HWND targetWindow = GetForegroundWindow(); bool sysCharSet = true; // XXX -- determine if m_groups[group] can be used with the system // character set. - if (!PostMessage( - targetWindow, WM_INPUTLANGCHANGEREQUEST, sysCharSet ? 1 : 0, - (LPARAM)m_groups[group])) { + if (!PostMessage(targetWindow, WM_INPUTLANGCHANGEREQUEST, sysCharSet ? 1 : 0, (LPARAM)m_groups[group])) { LOG((CLOG_WARN "failed to post change language message")); } @@ -1262,7 +1278,8 @@ void MSWindowsKeyState::setWindowGroup(SInt32 group) { Sleep(100); } -KeyID MSWindowsKeyState::getKeyID(UINT virtualKey, KeyButton button) const { +KeyID MSWindowsKeyState::getKeyID(UINT virtualKey, KeyButton button) const +{ // Some virtual keycodes have same values. // VK_HANGUL == VK_KANA, VK_HANJA == NK_KANJI // which are used to change the input mode of IME. @@ -1281,17 +1298,17 @@ KeyID MSWindowsKeyState::getKeyID(UINT virtualKey, KeyButton button) const { return s_virtualKey[virtualKey]; } -UINT MSWindowsKeyState::mapButtonToVirtualKey(KeyButton button) const { +UINT MSWindowsKeyState::mapButtonToVirtualKey(KeyButton button) const +{ return m_buttonToVK[button]; } KeyID MSWindowsKeyState::getIDForKey( - deskflow::KeyMap::KeyItem &item, KeyButton button, UINT virtualKey, - PBYTE keyState, HKL hkl) const { + deskflow::KeyMap::KeyItem &item, KeyButton button, UINT virtualKey, PBYTE keyState, HKL hkl +) const +{ WCHAR unicode[2]; - int n = m_ToUnicodeEx( - virtualKey, button, keyState, unicode, - sizeof(unicode) / sizeof(unicode[0]), 0, hkl); + int n = m_ToUnicodeEx(virtualKey, button, keyState, unicode, sizeof(unicode) / sizeof(unicode[0]), 0, hkl); KeyID id = static_cast(unicode[0]); switch (n) { @@ -1301,9 +1318,7 @@ KeyID MSWindowsKeyState::getIDForKey( // with different modifiers are not affected. BYTE emptyState[256] = {}; - n = m_ToUnicodeEx( - VK_SPACE, 0, emptyState, unicode, sizeof(unicode) / sizeof(unicode[0]), - 0, hkl); + n = m_ToUnicodeEx(VK_SPACE, 0, emptyState, unicode, sizeof(unicode) / sizeof(unicode[0]), 0, hkl); // as an alternative, we could use the returned // buffer in unicode to look at the dead key character @@ -1326,8 +1341,8 @@ KeyID MSWindowsKeyState::getIDForKey( } } -void MSWindowsKeyState::addKeyEntry( - deskflow::KeyMap &keyMap, deskflow::KeyMap::KeyItem &item) { +void MSWindowsKeyState::addKeyEntry(deskflow::KeyMap &keyMap, deskflow::KeyMap::KeyItem &item) +{ keyMap.addKeyEntry(item); if (item.m_group == 0) { m_keyToVKMap[item.m_id] = static_cast(item.m_client); diff --git a/src/lib/platform/MSWindowsKeyState.h b/src/lib/platform/MSWindowsKeyState.h index 7dadc5af1..c0a6bf1dd 100644 --- a/src/lib/platform/MSWindowsKeyState.h +++ b/src/lib/platform/MSWindowsKeyState.h @@ -34,15 +34,16 @@ class IEventQueue; /*! This class maps KeyIDs to keystrokes. */ -class MSWindowsKeyState : public KeyState { +class MSWindowsKeyState : public KeyState +{ public: MSWindowsKeyState( - MSWindowsDesks *desks, void *eventTarget, IEventQueue *events, - std::vector layouts, bool isLangSyncEnabled); + MSWindowsDesks *desks, void *eventTarget, IEventQueue *events, std::vector layouts, bool isLangSyncEnabled + ); MSWindowsKeyState( - MSWindowsDesks *desks, void *eventTarget, IEventQueue *events, - deskflow::KeyMap &keyMap, std::vector layouts, - bool isLangSyncEnabled); + MSWindowsDesks *desks, void *eventTarget, IEventQueue *events, deskflow::KeyMap &keyMap, + std::vector layouts, bool isLangSyncEnabled + ); virtual ~MSWindowsKeyState(); //! @name manipulators @@ -104,8 +105,7 @@ public: Converts a key event into a KeyID and the shadow modifier state to a modifier mask. */ - KeyID mapKeyFromEvent( - WPARAM charAndVirtKey, LPARAM info, KeyModifierMask *maskOut) const; + KeyID mapKeyFromEvent(WPARAM charAndVirtKey, LPARAM info, KeyModifierMask *maskOut) const; //! Check if keyboard groups have changed /*! @@ -140,11 +140,8 @@ public: //@} // IKeyState overrides - virtual void fakeKeyDown( - KeyID id, KeyModifierMask mask, KeyButton button, const String &lang); - virtual bool fakeKeyRepeat( - KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, - const String &lang); + virtual void fakeKeyDown(KeyID id, KeyModifierMask mask, KeyButton button, const String &lang); + virtual bool fakeKeyRepeat(KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang); virtual bool fakeCtrlAltDel(); virtual KeyModifierMask pollActiveModifiers() const; virtual SInt32 pollActiveGroup() const; @@ -153,14 +150,26 @@ public: // KeyState overrides virtual void onKey(KeyButton button, bool down, KeyModifierMask newState); virtual void sendKeyEvent( - void *target, bool press, bool isAutoRepeat, KeyID key, - KeyModifierMask mask, SInt32 count, KeyButton button); + void *target, bool press, bool isAutoRepeat, KeyID key, KeyModifierMask mask, SInt32 count, KeyButton button + ); // Unit test accessors - KeyButton getLastDown() const { return m_lastDown; } - void setLastDown(KeyButton value) { m_lastDown = value; } - KeyModifierMask getSavedModifiers() const { return m_savedModifiers; } - void setSavedModifiers(KeyModifierMask value) { m_savedModifiers = value; } + KeyButton getLastDown() const + { + return m_lastDown; + } + void setLastDown(KeyButton value) + { + m_lastDown = value; + } + KeyModifierMask getSavedModifiers() const + { + return m_savedModifiers; + } + void setSavedModifiers(KeyModifierMask value) + { + m_savedModifiers = value; + } protected: // KeyState overrides @@ -177,9 +186,7 @@ private: bool getGroups(GroupList &) const; void setWindowGroup(SInt32 group); - KeyID getIDForKey( - deskflow::KeyMap::KeyItem &item, KeyButton button, UINT virtualKey, - PBYTE keyState, HKL hkl) const; + KeyID getIDForKey(deskflow::KeyMap::KeyItem &item, KeyButton button, UINT virtualKey, PBYTE keyState, HKL hkl) const; void addKeyEntry(deskflow::KeyMap &keyMap, deskflow::KeyMap::KeyItem &item); @@ -223,8 +230,8 @@ private: // pointer to ToUnicodeEx. on win95 family this will be NULL. typedef int(WINAPI *ToUnicodeEx_t)( - UINT wVirtKey, UINT wScanCode, PBYTE lpKeyState, LPWSTR pwszBuff, - int cchBuff, UINT wFlags, HKL dwhkl); + UINT wVirtKey, UINT wScanCode, PBYTE lpKeyState, LPWSTR pwszBuff, int cchBuff, UINT wFlags, HKL dwhkl + ); ToUnicodeEx_t m_ToUnicodeEx; static const KeyID s_virtualKey[]; diff --git a/src/lib/platform/MSWindowsPowerManager.cpp b/src/lib/platform/MSWindowsPowerManager.cpp index 02ab7fc8f..6ebaa98ae 100644 --- a/src/lib/platform/MSWindowsPowerManager.cpp +++ b/src/lib/platform/MSWindowsPowerManager.cpp @@ -18,14 +18,19 @@ #include "MSWindowsPowerManager.h" #include "arch/win32/ArchMiscWindows.h" -MSWindowsPowerManager::~MSWindowsPowerManager() { enableSleep(); } +MSWindowsPowerManager::~MSWindowsPowerManager() +{ + enableSleep(); +} -void MSWindowsPowerManager::disableSleep() { +void MSWindowsPowerManager::disableSleep() +{ ArchMiscWindows::addBusyState(ArchMiscWindows::kSYSTEM); ArchMiscWindows::addBusyState(ArchMiscWindows::kDISPLAY); } -void MSWindowsPowerManager::enableSleep() { +void MSWindowsPowerManager::enableSleep() +{ // allow the system to enter power saving mode ArchMiscWindows::removeBusyState(ArchMiscWindows::kSYSTEM); ArchMiscWindows::removeBusyState(ArchMiscWindows::kDISPLAY); diff --git a/src/lib/platform/MSWindowsPowerManager.h b/src/lib/platform/MSWindowsPowerManager.h index 77484d156..286563ddb 100644 --- a/src/lib/platform/MSWindowsPowerManager.h +++ b/src/lib/platform/MSWindowsPowerManager.h @@ -17,7 +17,8 @@ */ #pragma once -class MSWindowsPowerManager { +class MSWindowsPowerManager +{ public: ~MSWindowsPowerManager(); diff --git a/src/lib/platform/MSWindowsScreen.cpp b/src/lib/platform/MSWindowsScreen.cpp index 5a2d6ce82..d6576adc9 100644 --- a/src/lib/platform/MSWindowsScreen.cpp +++ b/src/lib/platform/MSWindowsScreen.cpp @@ -92,8 +92,9 @@ HINSTANCE MSWindowsScreen::s_windowInstance = NULL; MSWindowsScreen *MSWindowsScreen::s_screen = NULL; MSWindowsScreen::MSWindowsScreen( - bool isPrimary, bool noHooks, bool stopOnDeskSwitch, IEventQueue *events, - bool enableLangSync, deskflow::ClientScrollDirection scrollDirection) + bool isPrimary, bool noHooks, bool stopOnDeskSwitch, IEventQueue *events, bool enableLangSync, + deskflow::ClientScrollDirection scrollDirection +) : PlatformScreen(events, scrollDirection), m_isPrimary(isPrimary), m_noHooks(noHooks), @@ -125,7 +126,8 @@ MSWindowsScreen::MSWindowsScreen( m_showingMouse(false), m_events(events), m_dropWindow(NULL), - m_dropWindowSize(20) { + m_dropWindowSize(20) +{ assert(s_windowInstance != NULL); assert(s_screen == NULL); @@ -138,32 +140,26 @@ MSWindowsScreen::MSWindowsScreen( m_screensaver = new MSWindowsScreenSaver(); m_desks = new MSWindowsDesks( m_isPrimary, m_noHooks, m_screensaver, m_events, - new TMethodJob(this, &MSWindowsScreen::updateKeysCB), - stopOnDeskSwitch); + new TMethodJob(this, &MSWindowsScreen::updateKeysCB), stopOnDeskSwitch + ); m_keyState = new MSWindowsKeyState( - m_desks, getEventTarget(), m_events, - AppUtil::instance().getKeyboardLayoutList(), enableLangSync); + m_desks, getEventTarget(), m_events, AppUtil::instance().getKeyboardLayoutList(), enableLangSync + ); updateScreenShape(); m_class = createWindowClass(); m_window = createWindow(m_class, DESKFLOW_APP_NAME); forceShowCursor(); - LOG( - (CLOG_DEBUG "screen shape: %d,%d %dx%d %s", m_x, m_y, m_w, m_h, - m_multimon ? "(multi-monitor)" : "")); + LOG((CLOG_DEBUG "screen shape: %d,%d %dx%d %s", m_x, m_y, m_w, m_h, m_multimon ? "(multi-monitor)" : "")); LOG((CLOG_DEBUG "window is 0x%08x", m_window)); // SHGetFolderPath is deprecated in vista, but use it for xp support. char desktopPath[MAX_PATH]; if (SUCCEEDED(SHGetFolderPath(NULL, CSIDL_DESKTOP, NULL, 0, desktopPath))) { m_desktopPath = String(desktopPath); - LOG( - (CLOG_DEBUG "using desktop for file drag-drop target: %s", - m_desktopPath.c_str())); + LOG((CLOG_DEBUG "using desktop for file drag-drop target: %s", m_desktopPath.c_str())); } else { - LOG( - (CLOG_DEBUG "unable to use desktop as file drag-drop target, code=%d", - GetLastError())); + LOG((CLOG_DEBUG "unable to use desktop as file drag-drop target, code=%d", GetLastError())); } if (App::instance().argsBase().m_preventSleep) { @@ -187,14 +183,15 @@ MSWindowsScreen::MSWindowsScreen( // install event handlers m_events->adoptHandler( Event::kSystem, m_events->getSystemTarget(), - new TMethodEventJob( - this, &MSWindowsScreen::handleSystemEvent)); + new TMethodEventJob(this, &MSWindowsScreen::handleSystemEvent) + ); // install the platform event queue m_events->adoptBuffer(new MSWindowsEventQueueBuffer(m_events)); } -MSWindowsScreen::~MSWindowsScreen() { +MSWindowsScreen::~MSWindowsScreen() +{ assert(s_screen != NULL); disable(); @@ -214,7 +211,8 @@ MSWindowsScreen::~MSWindowsScreen() { s_screen = NULL; } -void MSWindowsScreen::init(HINSTANCE windowInstance) { +void MSWindowsScreen::init(HINSTANCE windowInstance) +{ assert(s_windowInstance == NULL); assert(windowInstance != NULL); @@ -222,17 +220,20 @@ void MSWindowsScreen::init(HINSTANCE windowInstance) { } HINSTANCE -MSWindowsScreen::getWindowInstance() { return s_windowInstance; } +MSWindowsScreen::getWindowInstance() +{ + return s_windowInstance; +} -void MSWindowsScreen::enable() { +void MSWindowsScreen::enable() +{ assert(m_isOnScreen == m_isPrimary); // we need to poll some things to fix them m_fixTimer = m_events->newTimer(1.0, NULL); m_events->adoptHandler( - Event::kTimer, m_fixTimer, - new TMethodEventJob( - this, &MSWindowsScreen::handleFixes)); + Event::kTimer, m_fixTimer, new TMethodEventJob(this, &MSWindowsScreen::handleFixes) + ); // install our clipboard snooper m_nextClipboardWindow = SetClipboardViewer(m_window); @@ -249,7 +250,8 @@ void MSWindowsScreen::enable() { } } -void MSWindowsScreen::disable() { +void MSWindowsScreen::disable() +{ // stop tracking the active desk m_desks->disable(); @@ -279,7 +281,8 @@ void MSWindowsScreen::disable() { forceShowCursor(); } -void MSWindowsScreen::enter() { +void MSWindowsScreen::enter() +{ m_desks->enter(); if (m_isPrimary) { // enable special key sequences on win95 family @@ -308,7 +311,8 @@ void MSWindowsScreen::enter() { forceShowCursor(); } -bool MSWindowsScreen::canLeave() { +bool MSWindowsScreen::canLeave() +{ POINT pos; if (!getThisCursorPos(&pos)) { LOG((CLOG_DEBUG "unable to leave screen as windows security has disabled " @@ -321,7 +325,8 @@ bool MSWindowsScreen::canLeave() { return true; } -void MSWindowsScreen::leave() { +void MSWindowsScreen::leave() +{ // get keyboard layout of foreground window. we'll use this // keyboard layout for translating keys sent to clients. m_keyLayout = AppUtilWindows::instance().getCurrentKeyboardLayout(); @@ -335,9 +340,7 @@ void MSWindowsScreen::leave() { if (m_isPrimary) { // warp to center - LOG( - (CLOG_DEBUG1 "warping cursor to center: %+d, %+d", m_xCenter, - m_yCenter)); + LOG((CLOG_DEBUG1 "warping cursor to center: %+d, %+d", m_xCenter, m_yCenter)); warpCursor(m_xCenter, m_yCenter); // disable special key sequences on win95 family @@ -356,10 +359,7 @@ void MSWindowsScreen::leave() { for (KeyButton i = 0; i < IKeyState::kNumButtons; ++i) { if (m_keyState->isKeyDown(i)) { m_primaryKeyDownList.push_back(i); - LOG( - (CLOG_DEBUG1 - "key button %d is down before leaving to another screen", - i)); + LOG((CLOG_DEBUG1 "key button %d is down before leaving to another screen", i)); } } } @@ -369,12 +369,12 @@ void MSWindowsScreen::leave() { forceShowCursor(); if (isDraggingStarted() && !m_isPrimary) { - m_sendDragThread = new Thread(new TMethodJob( - this, &MSWindowsScreen::sendDragThread)); + m_sendDragThread = new Thread(new TMethodJob(this, &MSWindowsScreen::sendDragThread)); } } -void MSWindowsScreen::sendDragThread(void *) { +void MSWindowsScreen::sendDragThread(void *) +{ String &draggingFilename = getDraggingFilename(); size_t size = draggingFilename.size(); @@ -382,9 +382,7 @@ void MSWindowsScreen::sendDragThread(void *) { ClientApp &app = ClientApp::instance(); Client *client = app.getClientPtr(); UInt32 fileCount = 1; - LOG( - (CLOG_DEBUG "send dragging info to server: %s", - draggingFilename.c_str())); + LOG((CLOG_DEBUG "send dragging info to server: %s", draggingFilename.c_str())); client->sendDragInfo(fileCount, draggingFilename, size); LOG((CLOG_DEBUG "send dragging file to server")); client->sendFileToServer(draggingFilename.c_str()); @@ -393,7 +391,8 @@ void MSWindowsScreen::sendDragThread(void *) { m_draggingStarted = false; } -bool MSWindowsScreen::setClipboard(ClipboardID, const IClipboard *src) { +bool MSWindowsScreen::setClipboard(ClipboardID, const IClipboard *src) +{ MSWindowsClipboard dst(m_window); if (src != NULL) { // save clipboard data @@ -409,7 +408,8 @@ bool MSWindowsScreen::setClipboard(ClipboardID, const IClipboard *src) { } } -void MSWindowsScreen::checkClipboards() { +void MSWindowsScreen::checkClipboards() +{ // if we think we own the clipboard but we don't then somebody // grabbed the clipboard on this screen without us knowing. // tell the server that this screen grabbed the clipboard. @@ -422,17 +422,15 @@ void MSWindowsScreen::checkClipboards() { // won't be reflected on other screens until we leave but at // least the clipboard itself will work. if (m_ownClipboard && !MSWindowsClipboard::isOwnedByDeskflow()) { - LOG((CLOG_DEBUG - "clipboard changed: lost ownership and no notification received")); + LOG((CLOG_DEBUG "clipboard changed: lost ownership and no notification received")); m_ownClipboard = false; - sendClipboardEvent( - m_events->forClipboard().clipboardGrabbed(), kClipboardClipboard); - sendClipboardEvent( - m_events->forClipboard().clipboardGrabbed(), kClipboardSelection); + sendClipboardEvent(m_events->forClipboard().clipboardGrabbed(), kClipboardClipboard); + sendClipboardEvent(m_events->forClipboard().clipboardGrabbed(), kClipboardSelection); } } -void MSWindowsScreen::openScreensaver(bool notify) { +void MSWindowsScreen::openScreensaver(bool notify) +{ assert(m_screensaver != NULL); m_screensaverNotify = notify; @@ -443,7 +441,8 @@ void MSWindowsScreen::openScreensaver(bool notify) { } } -void MSWindowsScreen::closeScreensaver() { +void MSWindowsScreen::closeScreensaver() +{ if (m_screensaver != NULL) { if (m_screensaverNotify) { m_desks->installScreensaverHooks(false); @@ -454,7 +453,8 @@ void MSWindowsScreen::closeScreensaver() { m_screensaverNotify = false; } -void MSWindowsScreen::screensaver(bool activate) { +void MSWindowsScreen::screensaver(bool activate) +{ assert(m_screensaver != NULL); if (m_screensaver == NULL) return; @@ -466,30 +466,40 @@ void MSWindowsScreen::screensaver(bool activate) { } } -void MSWindowsScreen::resetOptions() { m_desks->resetOptions(); } +void MSWindowsScreen::resetOptions() +{ + m_desks->resetOptions(); +} -void MSWindowsScreen::setOptions(const OptionsList &options) { +void MSWindowsScreen::setOptions(const OptionsList &options) +{ m_desks->setOptions(options); } -void MSWindowsScreen::setSequenceNumber(UInt32 seqNum) { +void MSWindowsScreen::setSequenceNumber(UInt32 seqNum) +{ m_sequenceNumber = seqNum; } -bool MSWindowsScreen::isPrimary() const { return m_isPrimary; } +bool MSWindowsScreen::isPrimary() const +{ + return m_isPrimary; +} -void *MSWindowsScreen::getEventTarget() const { +void *MSWindowsScreen::getEventTarget() const +{ return const_cast(this); } -bool MSWindowsScreen::getClipboard(ClipboardID, IClipboard *dst) const { +bool MSWindowsScreen::getClipboard(ClipboardID, IClipboard *dst) const +{ MSWindowsClipboard src(m_window); Clipboard::copy(dst, &src); return true; } -void MSWindowsScreen::getShape( - SInt32 &x, SInt32 &y, SInt32 &w, SInt32 &h) const { +void MSWindowsScreen::getShape(SInt32 &x, SInt32 &y, SInt32 &w, SInt32 &h) const +{ assert(m_class != 0); x = m_x; @@ -498,7 +508,8 @@ void MSWindowsScreen::getShape( h = m_h; } -void MSWindowsScreen::getCursorPos(SInt32 &x, SInt32 &y) const { +void MSWindowsScreen::getCursorPos(SInt32 &x, SInt32 &y) const +{ m_desks->getCursorPos(x, y); } @@ -509,42 +520,37 @@ void MSWindowsScreen::getCursorPos(SInt32 &x, SInt32 &y) const { * Although these functions did not fix the issue at hand (#5294) its worth * keeping them here anyway. */ -bool MSWindowsScreen::getThisCursorPos(LPPOINT pos) { +bool MSWindowsScreen::getThisCursorPos(LPPOINT pos) +{ auto result = GetCursorPos(pos); auto error = GetLastError(); - LOG( - (CLOG_DEBUG3 "%s Attempt: 1 , status %d, code: %d Pos {%d, %d}", __func__, - result, error, pos->x, pos->y)); + LOG((CLOG_DEBUG3 "%s Attempt: 1 , status %d, code: %d Pos {%d, %d}", __func__, result, error, pos->x, pos->y)); if (!result) { result = GetCursorPos(pos); error = GetLastError(); - LOG( - (CLOG_DEBUG3 "%s Attempt: 2, status %d, code: %d Pos {%d, %d}", - __func__, result, error, pos->x, pos->y)); + LOG((CLOG_DEBUG3 "%s Attempt: 2, status %d, code: %d Pos {%d, %d}", __func__, result, error, pos->x, pos->y)); updateDesktopThread(); } return result; } -bool MSWindowsScreen::setThisCursorPos(int x, int y) { +bool MSWindowsScreen::setThisCursorPos(int x, int y) +{ auto result = SetCursorPos(x, y); auto error = GetLastError(); - LOG( - (CLOG_DEBUG3 "%s Attempt: 1, status %d, code: %d", __func__, result, - error)); + LOG((CLOG_DEBUG3 "%s Attempt: 1, status %d, code: %d", __func__, result, error)); if (!result) { result = SetCursorPos(x, y); error = GetLastError(); - LOG( - (CLOG_DEBUG3 "%s Attempt: 2, status %d, code: %d", __func__, result, - error)); + LOG((CLOG_DEBUG3 "%s Attempt: 2, status %d, code: %d", __func__, result, error)); updateDesktopThread(); } return result; } -void MSWindowsScreen::updateDesktopThread() { +void MSWindowsScreen::updateDesktopThread() +{ LOG((CLOG_DEBUG3 "failed to set cursor while attempting to switch desktop")); SetLastError(0); HDESK cur_hdesk = OpenInputDesktop(0, true, GENERIC_ALL); @@ -553,29 +559,27 @@ void MSWindowsScreen::updateDesktopThread() { LOG((CLOG_DEBUG3 "current desktop, handle=%p code=%d", cur_hdesk, error)); error = GetLastError(); - LOG( - (CLOG_DEBUG3 "setting desktop, return=%d code=%d", - SetThreadDesktop(cur_hdesk), GetLastError())); + LOG((CLOG_DEBUG3 "setting desktop, return=%d code=%d", SetThreadDesktop(cur_hdesk), GetLastError())); CloseDesktop(cur_hdesk); } -void MSWindowsScreen::reconfigure(UInt32 activeSides) { +void MSWindowsScreen::reconfigure(UInt32 activeSides) +{ assert(m_isPrimary); LOG((CLOG_DEBUG "active sides: %x", activeSides)); m_hook.setSides(activeSides); } -void MSWindowsScreen::warpCursor(SInt32 x, SInt32 y) { +void MSWindowsScreen::warpCursor(SInt32 x, SInt32 y) +{ // warp mouse warpCursorNoFlush(x, y); // remove all input events before and including warp MSG msg; - while (PeekMessage( - &msg, NULL, DESKFLOW_MSG_INPUT_FIRST, DESKFLOW_MSG_INPUT_LAST, - PM_REMOVE)) { + while (PeekMessage(&msg, NULL, DESKFLOW_MSG_INPUT_FIRST, DESKFLOW_MSG_INPUT_LAST, PM_REMOVE)) { // do nothing } @@ -583,17 +587,18 @@ void MSWindowsScreen::warpCursor(SInt32 x, SInt32 y) { saveMousePosition(x, y); } -void MSWindowsScreen::saveMousePosition(SInt32 x, SInt32 y) { +void MSWindowsScreen::saveMousePosition(SInt32 x, SInt32 y) +{ m_xCursor = x; m_yCursor = y; LOG((CLOG_DEBUG5 "saved mouse position for next delta: %+d,%+d", x, y)); } -UInt32 MSWindowsScreen::registerHotKey(KeyID key, KeyModifierMask mask) { +UInt32 MSWindowsScreen::registerHotKey(KeyID key, KeyModifierMask mask) +{ // only allow certain modifiers - if ((mask & ~(KeyModifierShift | KeyModifierControl | KeyModifierAlt | - KeyModifierSuper)) != 0) { + if ((mask & ~(KeyModifierShift | KeyModifierControl | KeyModifierAlt | KeyModifierSuper)) != 0) { // this should be a warning, but this can confuse users, // as this warning happens almost always. LOG((CLOG_DEBUG "could not map hotkey id=%04x mask=%04x", key, mask)); @@ -655,18 +660,21 @@ UInt32 MSWindowsScreen::registerHotKey(KeyID key, KeyModifierMask mask) { m_oldHotKeyIDs.push_back(id); m_hotKeys.erase(id); LOG( - (CLOG_WARN "failed to register hotkey %s (id=%04x mask=%04x)", - deskflow::KeyMap::formatKey(key, mask).c_str(), key, mask)); + (CLOG_WARN "failed to register hotkey %s (id=%04x mask=%04x)", deskflow::KeyMap::formatKey(key, mask).c_str(), + key, mask) + ); return 0; } LOG( - (CLOG_DEBUG "registered hotkey %s (id=%04x mask=%04x) as id=%d", - deskflow::KeyMap::formatKey(key, mask).c_str(), key, mask, id)); + (CLOG_DEBUG "registered hotkey %s (id=%04x mask=%04x) as id=%d", deskflow::KeyMap::formatKey(key, mask).c_str(), + key, mask, id) + ); return id; } -void MSWindowsScreen::unregisterHotKey(UInt32 id) { +void MSWindowsScreen::unregisterHotKey(UInt32 id) +{ // look up hotkey HotKeyMap::iterator i = m_hotKeys.find(id); if (i == m_hotKeys.end()) { @@ -692,7 +700,8 @@ void MSWindowsScreen::unregisterHotKey(UInt32 id) { m_oldHotKeyIDs.push_back(id); } -void MSWindowsScreen::fakeInputBegin() { +void MSWindowsScreen::fakeInputBegin() +{ assert(m_isPrimary); if (!m_isOnScreen) { @@ -701,7 +710,8 @@ void MSWindowsScreen::fakeInputBegin() { m_desks->fakeInputBegin(); } -void MSWindowsScreen::fakeInputEnd() { +void MSWindowsScreen::fakeInputEnd() +{ assert(m_isPrimary); m_desks->fakeInputEnd(); @@ -710,12 +720,15 @@ void MSWindowsScreen::fakeInputEnd() { } } -SInt32 MSWindowsScreen::getJumpZoneSize() const { return 1; } +SInt32 MSWindowsScreen::getJumpZoneSize() const +{ + return 1; +} -bool MSWindowsScreen::isAnyMouseButtonDown(UInt32 &buttonID) const { - static const char *buttonToName[] = {"", "Left Button", - "Middle Button", "Right Button", - "X Button 1", "X Button 2"}; +bool MSWindowsScreen::isAnyMouseButtonDown(UInt32 &buttonID) const +{ + static const char *buttonToName[] = {"", "Left Button", "Middle Button", + "Right Button", "X Button 1", "X Button 2"}; for (UInt32 i = 1; i < sizeof(m_buttons) / sizeof(m_buttons[0]); ++i) { if (m_buttons[i]) { @@ -728,12 +741,14 @@ bool MSWindowsScreen::isAnyMouseButtonDown(UInt32 &buttonID) const { return false; } -void MSWindowsScreen::getCursorCenter(SInt32 &x, SInt32 &y) const { +void MSWindowsScreen::getCursorCenter(SInt32 &x, SInt32 &y) const +{ x = m_xCenter; y = m_yCenter; } -void MSWindowsScreen::fakeMouseButton(ButtonID id, bool press) { +void MSWindowsScreen::fakeMouseButton(ButtonID id, bool press) +{ m_desks->fakeMouseButton(id, press); if (id == kButtonLeft) { @@ -747,52 +762,60 @@ void MSWindowsScreen::fakeMouseButton(ButtonID id, bool press) { } } -void MSWindowsScreen::fakeMouseMove(SInt32 x, SInt32 y) { +void MSWindowsScreen::fakeMouseMove(SInt32 x, SInt32 y) +{ m_desks->fakeMouseMove(x, y); if (m_buttons[kButtonLeft]) { m_draggingStarted = true; } } -void MSWindowsScreen::fakeMouseRelativeMove(SInt32 dx, SInt32 dy) const { +void MSWindowsScreen::fakeMouseRelativeMove(SInt32 dx, SInt32 dy) const +{ m_desks->fakeMouseRelativeMove(dx, dy); } -void MSWindowsScreen::fakeMouseWheel(SInt32 xDelta, SInt32 yDelta) const { +void MSWindowsScreen::fakeMouseWheel(SInt32 xDelta, SInt32 yDelta) const +{ xDelta = mapClientScrollDirection(xDelta); yDelta = mapClientScrollDirection(yDelta); m_desks->fakeMouseWheel(xDelta, yDelta); } -void MSWindowsScreen::updateKeys() { m_desks->updateKeys(); } +void MSWindowsScreen::updateKeys() +{ + m_desks->updateKeys(); +} -void MSWindowsScreen::fakeKeyDown( - KeyID id, KeyModifierMask mask, KeyButton button, const String &lang) { +void MSWindowsScreen::fakeKeyDown(KeyID id, KeyModifierMask mask, KeyButton button, const String &lang) +{ PlatformScreen::fakeKeyDown(id, mask, button, lang); updateForceShowCursor(); } -bool MSWindowsScreen::fakeKeyRepeat( - KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, - const String &lang) { +bool MSWindowsScreen::fakeKeyRepeat(KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang) +{ bool result = PlatformScreen::fakeKeyRepeat(id, mask, count, button, lang); updateForceShowCursor(); return result; } -bool MSWindowsScreen::fakeKeyUp(KeyButton button) { +bool MSWindowsScreen::fakeKeyUp(KeyButton button) +{ bool result = PlatformScreen::fakeKeyUp(button); updateForceShowCursor(); return result; } -void MSWindowsScreen::fakeAllKeysUp() { +void MSWindowsScreen::fakeAllKeysUp() +{ PlatformScreen::fakeAllKeysUp(); updateForceShowCursor(); } HCURSOR -MSWindowsScreen::createBlankCursor() const { +MSWindowsScreen::createBlankCursor() const +{ // create a transparent cursor int cw = GetSystemMetrics(SM_CXCURSOR); int ch = GetSystemMetrics(SM_CYCURSOR); @@ -801,20 +824,21 @@ MSWindowsScreen::createBlankCursor() const { UInt8 *cursorXOR = new UInt8[ch * ((cw + 31) >> 2)]; memset(cursorAND, 0xff, ch * ((cw + 31) >> 2)); memset(cursorXOR, 0x00, ch * ((cw + 31) >> 2)); - HCURSOR c = - CreateCursor(s_windowInstance, 0, 0, cw, ch, cursorAND, cursorXOR); + HCURSOR c = CreateCursor(s_windowInstance, 0, 0, cw, ch, cursorAND, cursorXOR); delete[] cursorXOR; delete[] cursorAND; return c; } -void MSWindowsScreen::destroyCursor(HCURSOR cursor) const { +void MSWindowsScreen::destroyCursor(HCURSOR cursor) const +{ if (cursor != NULL) { DestroyCursor(cursor); } } -ATOM MSWindowsScreen::createWindowClass() const { +ATOM MSWindowsScreen::createWindowClass() const +{ WNDCLASSEX classInfo; classInfo.cbSize = sizeof(classInfo); classInfo.style = CS_DBLCLKS | CS_NOCLOSE; @@ -831,17 +855,19 @@ ATOM MSWindowsScreen::createWindowClass() const { return RegisterClassEx(&classInfo); } -void MSWindowsScreen::destroyClass(ATOM windowClass) const { +void MSWindowsScreen::destroyClass(ATOM windowClass) const +{ if (windowClass != 0) { UnregisterClass(MAKEINTATOM(windowClass), s_windowInstance); } } -HWND MSWindowsScreen::createWindow(ATOM windowClass, const char *name) const { +HWND MSWindowsScreen::createWindow(ATOM windowClass, const char *name) const +{ HWND window = CreateWindowEx( - WS_EX_TOPMOST | WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW, - MAKEINTATOM(windowClass), name, WS_POPUP, 0, 0, 1, 1, NULL, NULL, - s_windowInstance, NULL); + WS_EX_TOPMOST | WS_EX_TRANSPARENT | WS_EX_TOOLWINDOW, MAKEINTATOM(windowClass), name, WS_POPUP, 0, 0, 1, 1, NULL, + NULL, s_windowInstance, NULL + ); if (window == NULL) { LOG((CLOG_ERR "failed to create window: %d", GetLastError())); throw XScreenOpenFailure(); @@ -849,12 +875,12 @@ HWND MSWindowsScreen::createWindow(ATOM windowClass, const char *name) const { return window; } -HWND MSWindowsScreen::createDropWindow( - ATOM windowClass, const char *name) const { +HWND MSWindowsScreen::createDropWindow(ATOM windowClass, const char *name) const +{ HWND window = CreateWindowEx( - WS_EX_TOPMOST | WS_EX_TRANSPARENT | WS_EX_ACCEPTFILES, - MAKEINTATOM(m_class), name, WS_POPUP, 0, 0, m_dropWindowSize, - m_dropWindowSize, NULL, NULL, s_windowInstance, NULL); + WS_EX_TOPMOST | WS_EX_TRANSPARENT | WS_EX_ACCEPTFILES, MAKEINTATOM(m_class), name, WS_POPUP, 0, 0, + m_dropWindowSize, m_dropWindowSize, NULL, NULL, s_windowInstance, NULL + ); if (window == NULL) { LOG((CLOG_ERR "failed to create drop window: %d", GetLastError())); @@ -864,17 +890,20 @@ HWND MSWindowsScreen::createDropWindow( return window; } -void MSWindowsScreen::destroyWindow(HWND hwnd) const { +void MSWindowsScreen::destroyWindow(HWND hwnd) const +{ if (hwnd != NULL) { DestroyWindow(hwnd); } } -void MSWindowsScreen::sendEvent(Event::Type type, void *data) { +void MSWindowsScreen::sendEvent(Event::Type type, void *data) +{ m_events->addEvent(Event(type, getEventTarget(), data)); } -void MSWindowsScreen::sendClipboardEvent(Event::Type type, ClipboardID id) { +void MSWindowsScreen::sendClipboardEvent(Event::Type type, ClipboardID id) +{ ClipboardInfo *info = (ClipboardInfo *)malloc(sizeof(ClipboardInfo)); if (info == NULL) { LOG((CLOG_ERR "malloc failed on %s:%s", __FILE__, __LINE__)); @@ -885,7 +914,8 @@ void MSWindowsScreen::sendClipboardEvent(Event::Type type, ClipboardID id) { sendEvent(type, info); } -void MSWindowsScreen::handleSystemEvent(const Event &event, void *) { +void MSWindowsScreen::handleSystemEvent(const Event &event, void *) +{ MSG *msg = static_cast(event.getData()); assert(msg != NULL); @@ -899,22 +929,24 @@ void MSWindowsScreen::handleSystemEvent(const Event &event, void *) { DispatchMessage(msg); } -void MSWindowsScreen::updateButtons() { +void MSWindowsScreen::updateButtons() +{ int numButtons = GetSystemMetrics(SM_CMOUSEBUTTONS); m_buttons[kButtonNone] = false; m_buttons[kButtonLeft] = (GetKeyState(VK_LBUTTON) < 0); m_buttons[kButtonRight] = (GetKeyState(VK_RBUTTON) < 0); m_buttons[kButtonMiddle] = (GetKeyState(VK_MBUTTON) < 0); - m_buttons[kButtonExtra0 + 0] = - (numButtons >= 4) && (GetKeyState(VK_XBUTTON1) < 0); - m_buttons[kButtonExtra0 + 1] = - (numButtons >= 5) && (GetKeyState(VK_XBUTTON2) < 0); + m_buttons[kButtonExtra0 + 0] = (numButtons >= 4) && (GetKeyState(VK_XBUTTON1) < 0); + m_buttons[kButtonExtra0 + 1] = (numButtons >= 5) && (GetKeyState(VK_XBUTTON2) < 0); } -IKeyState *MSWindowsScreen::getKeyState() const { return m_keyState; } +IKeyState *MSWindowsScreen::getKeyState() const +{ + return m_keyState; +} -bool MSWindowsScreen::onPreDispatch( - HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { +bool MSWindowsScreen::onPreDispatch(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) +{ // handle event switch (message) { case DESKFLOW_MSG_SCREEN_SAVER: @@ -932,8 +964,8 @@ bool MSWindowsScreen::onPreDispatch( return false; } -bool MSWindowsScreen::onPreDispatchPrimary( - HWND, UINT message, WPARAM wParam, LPARAM lParam) { +bool MSWindowsScreen::onPreDispatchPrimary(HWND, UINT message, WPARAM wParam, LPARAM lParam) +{ LOG((CLOG_DEBUG5 "handling pre-dispatch primary")); // handle event @@ -948,8 +980,7 @@ bool MSWindowsScreen::onPreDispatchPrimary( return onMouseButton(wParam, lParam); case DESKFLOW_MSG_MOUSE_MOVE: - return onMouseMove( - static_cast(wParam), static_cast(lParam)); + return onMouseMove(static_cast(wParam), static_cast(lParam)); case DESKFLOW_MSG_MOUSE_WHEEL: // XXX -- support x-axis scrolling @@ -986,8 +1017,8 @@ bool MSWindowsScreen::onPreDispatchPrimary( return false; } -bool MSWindowsScreen::onEvent( - HWND, UINT msg, WPARAM wParam, LPARAM lParam, LRESULT *result) { +bool MSWindowsScreen::onEvent(HWND, UINT msg, WPARAM wParam, LPARAM lParam, LRESULT *result) +{ switch (msg) { case WM_DRAWCLIPBOARD: // first pass on the message @@ -1001,9 +1032,7 @@ bool MSWindowsScreen::onEvent( case WM_CHANGECBCHAIN: if (m_nextClipboardWindow == (HWND)wParam) { m_nextClipboardWindow = (HWND)lParam; - LOG( - (CLOG_DEBUG "clipboard chain: new next: 0x%08x", - m_nextClipboardWindow)); + LOG((CLOG_DEBUG "clipboard chain: new next: 0x%08x", m_nextClipboardWindow)); } else if (m_nextClipboardWindow != NULL) { SendMessage(m_nextClipboardWindow, msg, wParam, lParam); } @@ -1015,9 +1044,7 @@ bool MSWindowsScreen::onEvent( /* On windows 10 we don't receive WM_POWERBROADCAST after sleep. We receive only WM_TIMECHANGE hence this message is used to resume.*/ case WM_TIMECHANGE: - m_events->addEvent(Event( - m_events->forIScreen().resume(), getEventTarget(), NULL, - Event::kDeliverImmediately)); + m_events->addEvent(Event(m_events->forIScreen().resume(), getEventTarget(), NULL, Event::kDeliverImmediately)); break; case WM_POWERBROADCAST: @@ -1025,15 +1052,11 @@ bool MSWindowsScreen::onEvent( case PBT_APMRESUMEAUTOMATIC: case PBT_APMRESUMECRITICAL: case PBT_APMRESUMESUSPEND: - m_events->addEvent(Event( - m_events->forIScreen().resume(), getEventTarget(), NULL, - Event::kDeliverImmediately)); + m_events->addEvent(Event(m_events->forIScreen().resume(), getEventTarget(), NULL, Event::kDeliverImmediately)); break; case PBT_APMSUSPEND: - m_events->addEvent(Event( - m_events->forIScreen().suspend(), getEventTarget(), NULL, - Event::kDeliverImmediately)); + m_events->addEvent(Event(m_events->forIScreen().suspend(), getEventTarget(), NULL, Event::kDeliverImmediately)); break; } *result = TRUE; @@ -1053,18 +1076,20 @@ bool MSWindowsScreen::onEvent( return false; } -bool MSWindowsScreen::onMark(UInt32 mark) { +bool MSWindowsScreen::onMark(UInt32 mark) +{ m_markReceived = mark; return true; } -bool MSWindowsScreen::onKey(WPARAM wParam, LPARAM lParam) { +bool MSWindowsScreen::onKey(WPARAM wParam, LPARAM lParam) +{ static const KeyModifierMask s_ctrlAlt = KeyModifierControl | KeyModifierAlt; LOG( - (CLOG_DEBUG1 "event: Key char=%d, vk=0x%02x, nagr=%d, lParam=0x%08x", - (wParam & 0xffffu), (wParam >> 16) & 0xffu, - (wParam & 0x1000000u) ? 1 : 0, lParam)); + (CLOG_DEBUG1 "event: Key char=%d, vk=0x%02x, nagr=%d, lParam=0x%08x", (wParam & 0xffffu), (wParam >> 16) & 0xffu, + (wParam & 0x1000000u) ? 1 : 0, lParam) + ); // get event info KeyButton button = (KeyButton)((lParam & 0x01ff0000) >> 16); @@ -1093,8 +1118,7 @@ bool MSWindowsScreen::onKey(WPARAM wParam, LPARAM lParam) { m_keyState->onKey(button, down, oldState); if (!down && m_isPrimary && !m_isOnScreen) { - PrimaryKeyDownList::iterator find = std::find( - m_primaryKeyDownList.begin(), m_primaryKeyDownList.end(), button); + PrimaryKeyDownList::iterator find = std::find(m_primaryKeyDownList.begin(), m_primaryKeyDownList.end(), button); if (find != m_primaryKeyDownList.end()) { LOG((CLOG_DEBUG1 "release key button %d on primary", *find)); m_hook.setMode(kHOOK_WATCH_JUMP_ZONE); @@ -1155,8 +1179,7 @@ bool MSWindowsScreen::onKey(WPARAM wParam, LPARAM lParam) { } // check for ctrl+alt+del emulation - if ((virtKey == VK_PAUSE || virtKey == VK_CANCEL) && - (state & s_ctrlAlt) == s_ctrlAlt) { + if ((virtKey == VK_PAUSE || virtKey == VK_CANCEL) && (state & s_ctrlAlt) == s_ctrlAlt) { LOG((CLOG_DEBUG "emulate ctrl+alt+del")); // switch wParam and lParam to be as if VK_DELETE was // pressed or released. when mapping the key we require that @@ -1175,9 +1198,9 @@ bool MSWindowsScreen::onKey(WPARAM wParam, LPARAM lParam) { if (key != kKeyNone) { // do it m_keyState->sendKeyEvent( - getEventTarget(), ((lParam & 0x80000000u) == 0), - ((lParam & 0x40000000u) != 0), key, mask, (SInt32)(lParam & 0xffff), - button); + getEventTarget(), ((lParam & 0x80000000u) == 0), ((lParam & 0x40000000u) != 0), key, mask, + (SInt32)(lParam & 0xffff), button + ); } else { LOG((CLOG_DEBUG1 "cannot map key")); } @@ -1186,7 +1209,8 @@ bool MSWindowsScreen::onKey(WPARAM wParam, LPARAM lParam) { return true; } -bool MSWindowsScreen::onHotKey(WPARAM wParam, LPARAM lParam) { +bool MSWindowsScreen::onHotKey(WPARAM wParam, LPARAM lParam) +{ // get the key info KeyModifierMask state = getActiveModifiers(); UINT virtKey = ((wParam >> 16) & 0xffu); @@ -1205,8 +1229,7 @@ bool MSWindowsScreen::onHotKey(WPARAM wParam, LPARAM lParam) { } // find the hot key id - HotKeyToIDMap::const_iterator i = - m_hotKeyToIDMap.find(HotKeyItem(virtKey, modifiers)); + HotKeyToIDMap::const_iterator i = m_hotKeyToIDMap.find(HotKeyItem(virtKey, modifiers)); if (i == m_hotKeyToIDMap.end()) { return false; } @@ -1224,13 +1247,13 @@ bool MSWindowsScreen::onHotKey(WPARAM wParam, LPARAM lParam) { } // generate event - m_events->addEvent( - Event(type, getEventTarget(), HotKeyInfo::alloc(i->second))); + m_events->addEvent(Event(type, getEventTarget(), HotKeyInfo::alloc(i->second))); return true; } -bool MSWindowsScreen::onMouseButton(WPARAM wParam, LPARAM lParam) { +bool MSWindowsScreen::onMouseButton(WPARAM wParam, LPARAM lParam) +{ // get which button bool pressed = mapPressFromEvent(wParam, lParam); ButtonID button = mapButtonFromEvent(wParam, lParam); @@ -1257,16 +1280,12 @@ bool MSWindowsScreen::onMouseButton(WPARAM wParam, LPARAM lParam) { if (pressed) { LOG((CLOG_DEBUG1 "event: button press button=%d", button)); if (button != kButtonNone) { - sendEvent( - m_events->forIPrimaryScreen().buttonDown(), - ButtonInfo::alloc(button, mask)); + sendEvent(m_events->forIPrimaryScreen().buttonDown(), ButtonInfo::alloc(button, mask)); } } else { LOG((CLOG_DEBUG1 "event: button release button=%d", button)); if (button != kButtonNone) { - sendEvent( - m_events->forIPrimaryScreen().buttonUp(), - ButtonInfo::alloc(button, mask)); + sendEvent(m_events->forIPrimaryScreen().buttonUp(), ButtonInfo::alloc(button, mask)); } } } @@ -1284,15 +1303,14 @@ bool MSWindowsScreen::onMouseButton(WPARAM wParam, LPARAM lParam) { // seems) // 5. sends the delta movement to the client (could be +1,+1 or -1,+4 for // example) -bool MSWindowsScreen::onMouseMove(SInt32 mx, SInt32 my) { +bool MSWindowsScreen::onMouseMove(SInt32 mx, SInt32 my) +{ // compute motion delta (relative to the last known // mouse position) SInt32 x = mx - m_xCursor; SInt32 y = my - m_yCursor; - LOG( - (CLOG_DEBUG3 "mouse move - motion delta: %+d=(%+d - %+d),%+d=(%+d - %+d)", - x, mx, m_xCursor, y, my, m_yCursor)); + LOG((CLOG_DEBUG3 "mouse move - motion delta: %+d=(%+d - %+d),%+d=(%+d - %+d)", x, mx, m_xCursor, y, my, m_yCursor)); // ignore if the mouse didn't move or if message posted prior // to last mark change. @@ -1306,9 +1324,7 @@ bool MSWindowsScreen::onMouseMove(SInt32 mx, SInt32 my) { if (m_isOnScreen) { // motion on primary screen - sendEvent( - m_events->forIPrimaryScreen().motionOnPrimary(), - MotionInfo::alloc(m_xCursor, m_yCursor)); + sendEvent(m_events->forIPrimaryScreen().motionOnPrimary(), MotionInfo::alloc(m_xCursor, m_yCursor)); if (m_buttons[kButtonLeft] == true && m_draggingStarted == false) { m_draggingStarted = true; @@ -1318,9 +1334,7 @@ bool MSWindowsScreen::onMouseMove(SInt32 mx, SInt32 my) { // center on the server screen. if we don't do this, then the mouse // will always try to return to the original entry point on the // secondary screen. - LOG( - (CLOG_DEBUG5 "warping server cursor to center: %+d,%+d", m_xCenter, - m_yCenter)); + LOG((CLOG_DEBUG5 "warping server cursor to center: %+d,%+d", m_xCenter, m_yCenter)); warpCursorNoFlush(m_xCenter, m_yCenter); // examine the motion. if it's about the distance @@ -1329,35 +1343,31 @@ bool MSWindowsScreen::onMouseMove(SInt32 mx, SInt32 my) { // ignore (see warpCursorNoFlush() for a further // description). static SInt32 bogusZoneSize = 10; - if (-x + bogusZoneSize > m_xCenter - m_x || - x + bogusZoneSize > m_x + m_w - m_xCenter || - -y + bogusZoneSize > m_yCenter - m_y || - y + bogusZoneSize > m_y + m_h - m_yCenter) { + if (-x + bogusZoneSize > m_xCenter - m_x || x + bogusZoneSize > m_x + m_w - m_xCenter || + -y + bogusZoneSize > m_yCenter - m_y || y + bogusZoneSize > m_y + m_h - m_yCenter) { LOG((CLOG_DEBUG "dropped bogus delta motion: %+d,%+d", x, y)); } else { // send motion - sendEvent( - m_events->forIPrimaryScreen().motionOnSecondary(), - MotionInfo::alloc(x, y)); + sendEvent(m_events->forIPrimaryScreen().motionOnSecondary(), MotionInfo::alloc(x, y)); } } return true; } -bool MSWindowsScreen::onMouseWheel(SInt32 xDelta, SInt32 yDelta) { +bool MSWindowsScreen::onMouseWheel(SInt32 xDelta, SInt32 yDelta) +{ // ignore message if posted prior to last mark change if (!ignore()) { LOG((CLOG_DEBUG1 "event: button wheel delta=%+d,%+d", xDelta, yDelta)); - sendEvent( - m_events->forIPrimaryScreen().wheel(), - WheelInfo::alloc(xDelta, yDelta)); + sendEvent(m_events->forIPrimaryScreen().wheel(), WheelInfo::alloc(xDelta, yDelta)); } return true; } -bool MSWindowsScreen::onScreensaver(bool activated) { +bool MSWindowsScreen::onScreensaver(bool activated) +{ // ignore this message if there are any other screen saver // messages already in the queue. this is important because // our checkStarted() function has a deliberate delay, so it @@ -1367,15 +1377,12 @@ bool MSWindowsScreen::onScreensaver(bool activated) { // send SC_SCREENSAVE until the screen saver starts, even if // the screen saver is disabled! MSG msg; - if (PeekMessage( - &msg, NULL, DESKFLOW_MSG_SCREEN_SAVER, DESKFLOW_MSG_SCREEN_SAVER, - PM_NOREMOVE)) { + if (PeekMessage(&msg, NULL, DESKFLOW_MSG_SCREEN_SAVER, DESKFLOW_MSG_SCREEN_SAVER, PM_NOREMOVE)) { return true; } if (activated) { - if (!m_screensaverActive && - m_screensaver->checkStarted(DESKFLOW_MSG_SCREEN_SAVER, FALSE, 0)) { + if (!m_screensaverActive && m_screensaver->checkStarted(DESKFLOW_MSG_SCREEN_SAVER, FALSE, 0)) { m_screensaverActive = true; sendEvent(m_events->forIPrimaryScreen().screensaverActivated()); } @@ -1389,7 +1396,8 @@ bool MSWindowsScreen::onScreensaver(bool activated) { return true; } -bool MSWindowsScreen::onDisplayChange() { +bool MSWindowsScreen::onDisplayChange() +{ // screen resolution may have changed. save old shape. SInt32 xOld = m_x, yOld = m_y, wOld = m_w, hOld = m_h; @@ -1402,9 +1410,7 @@ bool MSWindowsScreen::onDisplayChange() { // warp mouse to center if off screen if (!m_isOnScreen) { - LOG( - (CLOG_DEBUG1 "warping cursor to center: %+d, %+d", m_xCenter, - m_yCenter)); + LOG((CLOG_DEBUG1 "warping cursor to center: %+d, %+d", m_xCenter, m_yCenter)); warpCursor(m_xCenter, m_yCenter); } @@ -1417,25 +1423,22 @@ bool MSWindowsScreen::onDisplayChange() { // send new screen info sendEvent(m_events->forIScreen().shapeChanged()); - LOG( - (CLOG_DEBUG "screen shape: %d,%d %dx%d %s", m_x, m_y, m_w, m_h, - m_multimon ? "(multi-monitor)" : "")); + LOG((CLOG_DEBUG "screen shape: %d,%d %dx%d %s", m_x, m_y, m_w, m_h, m_multimon ? "(multi-monitor)" : "")); } return true; } -bool MSWindowsScreen::onClipboardChange() { +bool MSWindowsScreen::onClipboardChange() +{ // now notify client that somebody changed the clipboard (unless // we're the owner). if (!MSWindowsClipboard::isOwnedByDeskflow()) { if (m_ownClipboard) { LOG((CLOG_DEBUG "clipboard changed: lost ownership")); m_ownClipboard = false; - sendClipboardEvent( - m_events->forClipboard().clipboardGrabbed(), kClipboardClipboard); - sendClipboardEvent( - m_events->forClipboard().clipboardGrabbed(), kClipboardSelection); + sendClipboardEvent(m_events->forClipboard().clipboardGrabbed(), kClipboardClipboard); + sendClipboardEvent(m_events->forClipboard().clipboardGrabbed(), kClipboardSelection); } } else if (!m_ownClipboard) { LOG((CLOG_DEBUG "clipboard changed: " DESKFLOW_APP_ID " owned")); @@ -1445,7 +1448,8 @@ bool MSWindowsScreen::onClipboardChange() { return true; } -void MSWindowsScreen::warpCursorNoFlush(SInt32 x, SInt32 y) { +void MSWindowsScreen::warpCursorNoFlush(SInt32 x, SInt32 y) +{ // send an event that we can recognize before the mouse warp PostThreadMessage(GetCurrentThreadId(), DESKFLOW_MSG_PRE_WARP, x, y); @@ -1462,11 +1466,8 @@ void MSWindowsScreen::warpCursorNoFlush(SInt32 x, SInt32 y) { // since this feature is mainly for client, so only check on client. if (!isPrimary()) { if ((cursorPos.x != x) && (cursorPos.y != y)) { - LOG((CLOG_DEBUG - "function 'SetCursorPos' failed; trying 'fakeMouseMove'")); - LOG( - (CLOG_DEBUG "cursor pos %d, %d expected pos %d, %d", cursorPos.x, - cursorPos.y, x, y)); + LOG((CLOG_DEBUG "function 'SetCursorPos' failed; trying 'fakeMouseMove'")); + LOG((CLOG_DEBUG "cursor pos %d, %d expected pos %d, %d", cursorPos.x, cursorPos.y, x, y)); // when at Vista/7 login screen, SetCursorPos does not work (which could // be an MS security feature). instead we can use fakeMouseMove, which // calls mouse_event. IMPORTANT: as of implementing this function, it has @@ -1500,7 +1501,8 @@ void MSWindowsScreen::warpCursorNoFlush(SInt32 x, SInt32 y) { PostThreadMessage(GetCurrentThreadId(), DESKFLOW_MSG_POST_WARP, 0, 0); } -void MSWindowsScreen::nextMark() { +void MSWindowsScreen::nextMark() +{ // next mark ++m_mark; @@ -1508,9 +1510,13 @@ void MSWindowsScreen::nextMark() { PostThreadMessage(GetCurrentThreadId(), DESKFLOW_MSG_MARK, m_mark, 0); } -bool MSWindowsScreen::ignore() const { return (m_mark != m_markReceived); } +bool MSWindowsScreen::ignore() const +{ + return (m_mark != m_markReceived); +} -void MSWindowsScreen::updateScreenShape() { +void MSWindowsScreen::updateScreenShape() +{ // get shape and center m_w = GetSystemMetrics(SM_CXVIRTUALSCREEN); m_h = GetSystemMetrics(SM_CYVIRTUALSCREEN); @@ -1520,15 +1526,14 @@ void MSWindowsScreen::updateScreenShape() { m_yCenter = GetSystemMetrics(SM_CYSCREEN) >> 1; // check for multiple monitors - m_multimon = - (m_w != GetSystemMetrics(SM_CXSCREEN) || - m_h != GetSystemMetrics(SM_CYSCREEN)); + m_multimon = (m_w != GetSystemMetrics(SM_CXSCREEN) || m_h != GetSystemMetrics(SM_CYSCREEN)); // tell the desks m_desks->setShape(m_x, m_y, m_w, m_h, m_xCenter, m_yCenter, m_multimon); } -void MSWindowsScreen::handleFixes(const Event &, void *) { +void MSWindowsScreen::handleFixes(const Event &, void *) +{ // fix clipboard chain fixClipboardViewer(); @@ -1538,7 +1543,8 @@ void MSWindowsScreen::handleFixes(const Event &, void *) { } } -void MSWindowsScreen::fixClipboardViewer() { +void MSWindowsScreen::fixClipboardViewer() +{ // XXX -- disable this code for now. somehow it can cause an infinite // recursion in the WM_DRAWCLIPBOARD handler. either we're sending // the message to our own window or some window farther down the chain @@ -1553,9 +1559,12 @@ void MSWindowsScreen::fixClipboardViewer() { */ } -void MSWindowsScreen::enableSpecialKeys(bool enable) const {} +void MSWindowsScreen::enableSpecialKeys(bool enable) const +{ +} -ButtonID MSWindowsScreen::mapButtonFromEvent(WPARAM msg, LPARAM button) const { +ButtonID MSWindowsScreen::mapButtonFromEvent(WPARAM msg, LPARAM button) const +{ switch (msg) { case WM_LBUTTONDOWN: case WM_LBUTTONDBLCLK: @@ -1607,7 +1616,8 @@ ButtonID MSWindowsScreen::mapButtonFromEvent(WPARAM msg, LPARAM button) const { } } -bool MSWindowsScreen::mapPressFromEvent(WPARAM msg, LPARAM) const { +bool MSWindowsScreen::mapPressFromEvent(WPARAM msg, LPARAM) const +{ switch (msg) { case WM_LBUTTONDOWN: case WM_MBUTTONDOWN: @@ -1642,7 +1652,8 @@ bool MSWindowsScreen::mapPressFromEvent(WPARAM msg, LPARAM) const { } } -void MSWindowsScreen::updateKeysCB(void *) { +void MSWindowsScreen::updateKeysCB(void *) +{ // record which keys we think are down bool down[IKeyState::kNumButtons]; bool sendFixes = (isPrimary() && !m_isOnScreen); @@ -1666,14 +1677,14 @@ void MSWindowsScreen::updateKeysCB(void *) { KeyModifierMask mask = pollActiveModifiers(); for (KeyButton i = 0; i < IKeyState::kNumButtons; ++i) { if (down[i] && !m_keyState->isKeyDown(i)) { - m_keyState->sendKeyEvent( - getEventTarget(), false, false, kKeyNone, mask, 1, i); + m_keyState->sendKeyEvent(getEventTarget(), false, false, kKeyNone, mask, 1, i); } } } } -void MSWindowsScreen::forceShowCursor() { +void MSWindowsScreen::forceShowCursor() +{ // check for mouse m_hasMouse = (GetSystemMetrics(SM_MOUSEPRESENT) != 0); @@ -1684,10 +1695,7 @@ void MSWindowsScreen::forceShowCursor() { if (showMouse != m_showingMouse) { if (showMouse) { m_oldMouseKeys.cbSize = sizeof(m_oldMouseKeys); - m_gotOldMouseKeys = - (SystemParametersInfo( - SPI_GETMOUSEKEYS, m_oldMouseKeys.cbSize, &m_oldMouseKeys, 0) != - 0); + m_gotOldMouseKeys = (SystemParametersInfo(SPI_GETMOUSEKEYS, m_oldMouseKeys.cbSize, &m_oldMouseKeys, 0) != 0); if (m_gotOldMouseKeys) { m_mouseKeys = m_oldMouseKeys; m_showingMouse = true; @@ -1695,16 +1703,15 @@ void MSWindowsScreen::forceShowCursor() { } } else { if (m_gotOldMouseKeys) { - SystemParametersInfo( - SPI_SETMOUSEKEYS, m_oldMouseKeys.cbSize, &m_oldMouseKeys, - SPIF_SENDCHANGE); + SystemParametersInfo(SPI_SETMOUSEKEYS, m_oldMouseKeys.cbSize, &m_oldMouseKeys, SPIF_SENDCHANGE); m_showingMouse = false; } } } } -void MSWindowsScreen::updateForceShowCursor() { +void MSWindowsScreen::updateForceShowCursor() +{ DWORD oldFlags = m_mouseKeys.dwFlags; // turn on MouseKeys @@ -1718,13 +1725,12 @@ void MSWindowsScreen::updateForceShowCursor() { // update MouseKeys if (oldFlags != m_mouseKeys.dwFlags) { - SystemParametersInfo( - SPI_SETMOUSEKEYS, m_mouseKeys.cbSize, &m_mouseKeys, SPIF_SENDCHANGE); + SystemParametersInfo(SPI_SETMOUSEKEYS, m_mouseKeys.cbSize, &m_mouseKeys, SPIF_SENDCHANGE); } } -LRESULT CALLBACK -MSWindowsScreen::wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { +LRESULT CALLBACK MSWindowsScreen::wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) +{ assert(s_screen != NULL); LRESULT result = 0; @@ -1735,7 +1741,8 @@ MSWindowsScreen::wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { return result; } -void MSWindowsScreen::fakeLocalKey(KeyButton button, bool press) const { +void MSWindowsScreen::fakeLocalKey(KeyButton button, bool press) const +{ INPUT input; input.type = INPUT_KEYBOARD; input.ki.wVk = m_keyState->mapButtonToVirtualKey(button); @@ -1750,26 +1757,29 @@ void MSWindowsScreen::fakeLocalKey(KeyButton button, bool press) const { // MSWindowsScreen::HotKeyItem // -MSWindowsScreen::HotKeyItem::HotKeyItem(UINT keycode, UINT mask) - : m_keycode(keycode), - m_mask(mask) { +MSWindowsScreen::HotKeyItem::HotKeyItem(UINT keycode, UINT mask) : m_keycode(keycode), m_mask(mask) +{ // do nothing } -UINT MSWindowsScreen::HotKeyItem::getVirtualKey() const { return m_keycode; } - -bool MSWindowsScreen::HotKeyItem::operator<(const HotKeyItem &x) const { - return ( - m_keycode < x.m_keycode || - (m_keycode == x.m_keycode && m_mask < x.m_mask)); +UINT MSWindowsScreen::HotKeyItem::getVirtualKey() const +{ + return m_keycode; } -void MSWindowsScreen::fakeDraggingFiles(DragFileList fileList) { +bool MSWindowsScreen::HotKeyItem::operator<(const HotKeyItem &x) const +{ + return (m_keycode < x.m_keycode || (m_keycode == x.m_keycode && m_mask < x.m_mask)); +} + +void MSWindowsScreen::fakeDraggingFiles(DragFileList fileList) +{ // possible design flaw: this function stops a "not implemented" // exception from being thrown. } -String &MSWindowsScreen::getDraggingFilename() { +String &MSWindowsScreen::getDraggingFilename() +{ if (m_draggingStarted) { m_dropTarget->clearDraggingFilename(); m_draggingFilename.clear(); @@ -1780,13 +1790,10 @@ String &MSWindowsScreen::getDraggingFilename() { SInt32 yPos = m_isPrimary ? m_yCursor : m_yCenter; xPos = (xPos - halfSize) < 0 ? 0 : xPos - halfSize; yPos = (yPos - halfSize) < 0 ? 0 : yPos - halfSize; - SetWindowPos( - m_dropWindow, HWND_TOPMOST, xPos, yPos, m_dropWindowSize, - m_dropWindowSize, SWP_SHOWWINDOW); + SetWindowPos(m_dropWindow, HWND_TOPMOST, xPos, yPos, m_dropWindowSize, m_dropWindowSize, SWP_SHOWWINDOW); // TODO: fake these keys properly - fakeKeyDown( - kKeyEscape, 8192, 1, AppUtil::instance().getCurrentLanguageCode()); + fakeKeyDown(kKeyEscape, 8192, 1, AppUtil::instance().getCurrentLanguageCode()); fakeKeyUp(1); fakeMouseButton(kButtonLeft, false); @@ -1818,33 +1825,33 @@ String &MSWindowsScreen::getDraggingFilename() { return m_draggingFilename; } -const String &MSWindowsScreen::getDropTarget() const { return m_desktopPath; } +const String &MSWindowsScreen::getDropTarget() const +{ + return m_desktopPath; +} -String MSWindowsScreen::getSecureInputApp() const { +String MSWindowsScreen::getSecureInputApp() const +{ // ignore on Windows return ""; } -bool MSWindowsScreen::isModifierRepeat( - KeyModifierMask oldState, KeyModifierMask state, WPARAM wParam) const { +bool MSWindowsScreen::isModifierRepeat(KeyModifierMask oldState, KeyModifierMask state, WPARAM wParam) const +{ bool result = false; if (oldState == state && state != 0) { UINT virtKey = ((wParam >> 16) & 0xffu); - if ((state & KeyModifierShift) != 0 && - (virtKey == VK_LSHIFT || virtKey == VK_RSHIFT)) { + if ((state & KeyModifierShift) != 0 && (virtKey == VK_LSHIFT || virtKey == VK_RSHIFT)) { result = true; } - if ((state & KeyModifierControl) != 0 && - (virtKey == VK_LCONTROL || virtKey == VK_RCONTROL)) { + if ((state & KeyModifierControl) != 0 && (virtKey == VK_LCONTROL || virtKey == VK_RCONTROL)) { result = true; } - if ((state & KeyModifierAlt) != 0 && - (virtKey == VK_LMENU || virtKey == VK_RMENU)) { + if ((state & KeyModifierAlt) != 0 && (virtKey == VK_LMENU || virtKey == VK_RMENU)) { result = true; } - if ((state & KeyModifierSuper) != 0 && - (virtKey == VK_LWIN || virtKey == VK_RWIN)) { + if ((state & KeyModifierSuper) != 0 && (virtKey == VK_LWIN || virtKey == VK_RWIN)) { result = true; } } diff --git a/src/lib/platform/MSWindowsScreen.h b/src/lib/platform/MSWindowsScreen.h index 423cafd1d..1a9852e16 100644 --- a/src/lib/platform/MSWindowsScreen.h +++ b/src/lib/platform/MSWindowsScreen.h @@ -39,13 +39,13 @@ class Thread; class MSWindowsDropTarget; //! Implementation of IPlatformScreen for Microsoft Windows -class MSWindowsScreen : public PlatformScreen { +class MSWindowsScreen : public PlatformScreen +{ public: MSWindowsScreen( - bool isPrimary, bool noHooks, bool stopOnDeskSwitch, IEventQueue *events, - bool enableLangSync = false, - deskflow::ClientScrollDirection scrollDirection = - deskflow::ClientScrollDirection::SERVER); + bool isPrimary, bool noHooks, bool stopOnDeskSwitch, IEventQueue *events, bool enableLangSync = false, + deskflow::ClientScrollDirection scrollDirection = deskflow::ClientScrollDirection::SERVER + ); virtual ~MSWindowsScreen(); //! @name manipulators @@ -73,8 +73,7 @@ public: // IScreen overrides virtual void *getEventTarget() const; virtual bool getClipboard(ClipboardID id, IClipboard *) const; - virtual void - getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const; + virtual void getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const; virtual void getCursorPos(SInt32 &x, SInt32 &y) const; /** @@ -116,11 +115,8 @@ public: // IKeyState overrides virtual void updateKeys(); - virtual void fakeKeyDown( - KeyID id, KeyModifierMask mask, KeyButton button, const String &lang); - virtual bool fakeKeyRepeat( - KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, - const String &lang); + virtual void fakeKeyDown(KeyID id, KeyModifierMask mask, KeyButton button, const String &lang); + virtual bool fakeKeyRepeat(KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang); virtual bool fakeKeyUp(KeyButton button); virtual void fakeAllKeysUp(); @@ -245,14 +241,14 @@ private: // HACK void saveMousePosition(SInt32 x, SInt32 y); // check if it is a modifier key repeating message - bool isModifierRepeat( - KeyModifierMask oldState, KeyModifierMask state, WPARAM wParam) const; + bool isModifierRepeat(KeyModifierMask oldState, KeyModifierMask state, WPARAM wParam) const; // send drag info and data back to server void sendDragThread(void *); private: - struct HotKeyItem { + struct HotKeyItem + { public: HotKeyItem(UINT vk, UINT modifiers); diff --git a/src/lib/platform/MSWindowsScreenSaver.cpp b/src/lib/platform/MSWindowsScreenSaver.cpp index 94f91f7bf..fa9153c5f 100644 --- a/src/lib/platform/MSWindowsScreenSaver.cpp +++ b/src/lib/platform/MSWindowsScreenSaver.cpp @@ -34,8 +34,7 @@ static const TCHAR *g_isSecureNT = "ScreenSaverIsSecure"; static const TCHAR *g_isSecure9x = "ScreenSaveUsePassword"; -static const TCHAR *const g_pathScreenSaverIsSecure[] = { - "Control Panel", "Desktop", NULL}; +static const TCHAR *const g_pathScreenSaverIsSecure[] = {"Control Panel", "Desktop", NULL}; // // MSWindowsScreenSaver @@ -50,15 +49,19 @@ MSWindowsScreenSaver::MSWindowsScreenSaver() m_msg(0), m_wParam(0), m_lParam(0), - m_active(false) { + m_active(false) +{ // check if screen saver is enabled SystemParametersInfo(SPI_GETSCREENSAVEACTIVE, 0, &m_wasEnabled, 0); } -MSWindowsScreenSaver::~MSWindowsScreenSaver() { unwatchProcess(); } +MSWindowsScreenSaver::~MSWindowsScreenSaver() +{ + unwatchProcess(); +} -bool MSWindowsScreenSaver::checkStarted( - UINT msg, WPARAM wParam, LPARAM lParam) { +bool MSWindowsScreenSaver::checkStarted(UINT msg, WPARAM wParam, LPARAM lParam) +{ // if already started then say it didn't just start if (m_active) { return false; @@ -96,7 +99,8 @@ bool MSWindowsScreenSaver::checkStarted( return true; } -void MSWindowsScreenSaver::enable() { +void MSWindowsScreenSaver::enable() +{ SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, m_wasEnabled, 0, 0); // restore password protection @@ -105,7 +109,8 @@ void MSWindowsScreenSaver::enable() { } } -void MSWindowsScreenSaver::disable() { +void MSWindowsScreenSaver::disable() +{ SystemParametersInfo(SPI_GETSCREENSAVEACTIVE, 0, &m_wasEnabled, 0); SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, FALSE, 0, 0); @@ -116,7 +121,8 @@ void MSWindowsScreenSaver::disable() { } } -void MSWindowsScreenSaver::activate() { +void MSWindowsScreenSaver::activate() +{ // don't activate if already active if (!isActive()) { // activate @@ -130,16 +136,14 @@ void MSWindowsScreenSaver::activate() { } } -void MSWindowsScreenSaver::deactivate() { +void MSWindowsScreenSaver::deactivate() +{ bool killed = false; // NT runs screen saver in another desktop - HDESK desktop = OpenDesktop( - "Screen-saver", 0, FALSE, DESKTOP_READOBJECTS | DESKTOP_WRITEOBJECTS); + HDESK desktop = OpenDesktop("Screen-saver", 0, FALSE, DESKTOP_READOBJECTS | DESKTOP_WRITEOBJECTS); if (desktop != NULL) { - EnumDesktopWindows( - desktop, &MSWindowsScreenSaver::killScreenSaverFunc, - reinterpret_cast(&killed)); + EnumDesktopWindows(desktop, &MSWindowsScreenSaver::killScreenSaverFunc, reinterpret_cast(&killed)); CloseDesktop(desktop); } @@ -158,19 +162,19 @@ void MSWindowsScreenSaver::deactivate() { // force timer to restart SystemParametersInfo(SPI_GETSCREENSAVEACTIVE, 0, &m_wasEnabled, 0); - SystemParametersInfo( - SPI_SETSCREENSAVEACTIVE, !m_wasEnabled, 0, SPIF_SENDWININICHANGE); - SystemParametersInfo( - SPI_SETSCREENSAVEACTIVE, m_wasEnabled, 0, SPIF_SENDWININICHANGE); + SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, !m_wasEnabled, 0, SPIF_SENDWININICHANGE); + SystemParametersInfo(SPI_SETSCREENSAVEACTIVE, m_wasEnabled, 0, SPIF_SENDWININICHANGE); } -bool MSWindowsScreenSaver::isActive() const { +bool MSWindowsScreenSaver::isActive() const +{ BOOL running; SystemParametersInfo(SPI_GETSCREENSAVERRUNNING, 0, &running, 0); return (running != FALSE); } -BOOL CALLBACK MSWindowsScreenSaver::killScreenSaverFunc(HWND hwnd, LPARAM arg) { +BOOL CALLBACK MSWindowsScreenSaver::killScreenSaverFunc(HWND hwnd, LPARAM arg) +{ if (IsWindowVisible(hwnd)) { HINSTANCE instance = (HINSTANCE)GetWindowLongPtr(hwnd, GWLP_HINSTANCE); if (instance != MSWindowsScreen::getWindowInstance()) { @@ -181,18 +185,19 @@ BOOL CALLBACK MSWindowsScreenSaver::killScreenSaverFunc(HWND hwnd, LPARAM arg) { return TRUE; } -void MSWindowsScreenSaver::watchDesktop() { +void MSWindowsScreenSaver::watchDesktop() +{ // stop watching previous process/desktop unwatchProcess(); // watch desktop in another thread LOG((CLOG_DEBUG "watching screen saver desktop")); m_active = true; - m_watch = new Thread(new TMethodJob( - this, &MSWindowsScreenSaver::watchDesktopThread)); + m_watch = new Thread(new TMethodJob(this, &MSWindowsScreenSaver::watchDesktopThread)); } -void MSWindowsScreenSaver::watchProcess(HANDLE process) { +void MSWindowsScreenSaver::watchProcess(HANDLE process) +{ // stop watching previous process/desktop unwatchProcess(); @@ -201,12 +206,12 @@ void MSWindowsScreenSaver::watchProcess(HANDLE process) { LOG((CLOG_DEBUG "watching screen saver process")); m_process = process; m_active = true; - m_watch = new Thread(new TMethodJob( - this, &MSWindowsScreenSaver::watchProcessThread)); + m_watch = new Thread(new TMethodJob(this, &MSWindowsScreenSaver::watchProcessThread)); } } -void MSWindowsScreenSaver::unwatchProcess() { +void MSWindowsScreenSaver::unwatchProcess() +{ if (m_watch != NULL) { LOG((CLOG_DEBUG "stopped watching screen saver process/desktop")); m_watch->cancel(); @@ -221,7 +226,8 @@ void MSWindowsScreenSaver::unwatchProcess() { } } -void MSWindowsScreenSaver::watchDesktopThread(void *) { +void MSWindowsScreenSaver::watchDesktopThread(void *) +{ DWORD reserved = 0; TCHAR *name = NULL; @@ -242,7 +248,8 @@ void MSWindowsScreenSaver::watchDesktopThread(void *) { } } -void MSWindowsScreenSaver::watchProcessThread(void *) { +void MSWindowsScreenSaver::watchProcessThread(void *) +{ for (;;) { Thread::testCancel(); if (WaitForSingleObject(m_process, 50) == WAIT_OBJECT_0) { @@ -257,9 +264,9 @@ void MSWindowsScreenSaver::watchProcessThread(void *) { } } -void MSWindowsScreenSaver::setSecure(bool secure, bool saveSecureAsInt) { - HKEY hkey = - ArchMiscWindows::addKey(HKEY_CURRENT_USER, g_pathScreenSaverIsSecure); +void MSWindowsScreenSaver::setSecure(bool secure, bool saveSecureAsInt) +{ + HKEY hkey = ArchMiscWindows::addKey(HKEY_CURRENT_USER, g_pathScreenSaverIsSecure); if (hkey == NULL) { return; } @@ -273,10 +280,10 @@ void MSWindowsScreenSaver::setSecure(bool secure, bool saveSecureAsInt) { ArchMiscWindows::closeKey(hkey); } -bool MSWindowsScreenSaver::isSecure(bool *wasSecureFlagAnInt) const { +bool MSWindowsScreenSaver::isSecure(bool *wasSecureFlagAnInt) const +{ // get the password protection setting key - HKEY hkey = - ArchMiscWindows::openKey(HKEY_CURRENT_USER, g_pathScreenSaverIsSecure); + HKEY hkey = ArchMiscWindows::openKey(HKEY_CURRENT_USER, g_pathScreenSaverIsSecure); if (hkey == NULL) { return false; } diff --git a/src/lib/platform/MSWindowsScreenSaver.h b/src/lib/platform/MSWindowsScreenSaver.h index 6483dc545..9303c7a27 100644 --- a/src/lib/platform/MSWindowsScreenSaver.h +++ b/src/lib/platform/MSWindowsScreenSaver.h @@ -27,7 +27,8 @@ class Thread; //! Microsoft windows screen saver implementation -class MSWindowsScreenSaver : public IScreenSaver { +class MSWindowsScreenSaver : public IScreenSaver +{ public: MSWindowsScreenSaver(); virtual ~MSWindowsScreenSaver(); @@ -54,7 +55,8 @@ public: virtual bool isActive() const; private: - class FindScreenSaverInfo { + class FindScreenSaverInfo + { public: HDESK m_desktop; HWND m_window; diff --git a/src/lib/platform/MSWindowsSession.cpp b/src/lib/platform/MSWindowsSession.cpp index 894654350..4419cf442 100644 --- a/src/lib/platform/MSWindowsSession.cpp +++ b/src/lib/platform/MSWindowsSession.cpp @@ -23,12 +23,16 @@ #include -MSWindowsSession::MSWindowsSession() : m_activeSessionId(-1) {} +MSWindowsSession::MSWindowsSession() : m_activeSessionId(-1) +{ +} -MSWindowsSession::~MSWindowsSession() {} +MSWindowsSession::~MSWindowsSession() +{ +} -bool MSWindowsSession::isProcessInSession( - const char *name, PHANDLE process = NULL) { +bool MSWindowsSession::isProcessInSession(const char *name, PHANDLE process = NULL) +{ // first we need to take a snapshot of the running processes HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (snapshot == INVALID_HANDLE_VALUE) { @@ -58,15 +62,15 @@ bool MSWindowsSession::isProcessInSession( if (entry.th32ProcessID != 0) { DWORD processSessionId; - BOOL pidToSidRet = - ProcessIdToSessionId(entry.th32ProcessID, &processSessionId); + BOOL pidToSidRet = ProcessIdToSessionId(entry.th32ProcessID, &processSessionId); if (!pidToSidRet) { // if we can not acquire session associated with a specified process, // simply ignore it LOG( - (CLOG_DEBUG2 "could not get session id for process: %i %s, code=%i", - entry.th32ProcessID, entry.szExeFile, GetLastError())); + (CLOG_DEBUG2 "could not get session id for process: %i %s, code=%i", entry.th32ProcessID, entry.szExeFile, + GetLastError()) + ); gotEntry = nextProcessEntry(snapshot, &entry); continue; } else { @@ -88,15 +92,12 @@ bool MSWindowsSession::isProcessInSession( } std::string nameListJoin; - for (std::list::iterator it = nameList.begin(); - it != nameList.end(); it++) { + for (std::list::iterator it = nameList.begin(); it != nameList.end(); it++) { nameListJoin.append(*it); nameListJoin.append(", "); } - LOG( - (CLOG_DEBUG2 "processes in session %d: %s", m_activeSessionId, - nameListJoin.c_str())); + LOG((CLOG_DEBUG2 "processes in session %d: %s", m_activeSessionId, nameListJoin.c_str())); CloseHandle(snapshot); @@ -114,7 +115,8 @@ bool MSWindowsSession::isProcessInSession( } HANDLE -MSWindowsSession::getUserToken(LPSECURITY_ATTRIBUTES security) { +MSWindowsSession::getUserToken(LPSECURITY_ATTRIBUTES security) +{ HANDLE sourceToken; if (!WTSQueryUserToken(m_activeSessionId, &sourceToken)) { LOG((CLOG_ERR "could not get token from session %d", m_activeSessionId)); @@ -123,8 +125,8 @@ MSWindowsSession::getUserToken(LPSECURITY_ATTRIBUTES security) { HANDLE newToken; if (!DuplicateTokenEx( - sourceToken, TOKEN_ASSIGN_PRIMARY | TOKEN_ALL_ACCESS, security, - SecurityImpersonation, TokenPrimary, &newToken)) { + sourceToken, TOKEN_ASSIGN_PRIMARY | TOKEN_ALL_ACCESS, security, SecurityImpersonation, TokenPrimary, &newToken + )) { LOG((CLOG_ERR "could not duplicate token")); throw XArch(new XArchEvalWindows); @@ -134,16 +136,18 @@ MSWindowsSession::getUserToken(LPSECURITY_ATTRIBUTES security) { return newToken; } -BOOL MSWindowsSession::hasChanged() { +BOOL MSWindowsSession::hasChanged() +{ return (m_activeSessionId != WTSGetActiveConsoleSessionId()); } -void MSWindowsSession::updateActiveSession() { +void MSWindowsSession::updateActiveSession() +{ m_activeSessionId = WTSGetActiveConsoleSessionId(); } -BOOL MSWindowsSession::nextProcessEntry( - HANDLE snapshot, LPPROCESSENTRY32 entry) { +BOOL MSWindowsSession::nextProcessEntry(HANDLE snapshot, LPPROCESSENTRY32 entry) +{ // TODO: issue S3-2021 // resetting the error state here is acceptable, but having to do so indicates // that a different win32 function call has failed beforehand. we should @@ -166,7 +170,8 @@ BOOL MSWindowsSession::nextProcessEntry( return gotEntry; } -String MSWindowsSession::getActiveDesktopName() { +String MSWindowsSession::getActiveDesktopName() +{ String result; try { HDESK hd = OpenInputDesktop(0, TRUE, GENERIC_READ); diff --git a/src/lib/platform/MSWindowsSession.h b/src/lib/platform/MSWindowsSession.h index 0f3056598..3cf450ad9 100644 --- a/src/lib/platform/MSWindowsSession.h +++ b/src/lib/platform/MSWindowsSession.h @@ -24,7 +24,8 @@ #include -class MSWindowsSession { +class MSWindowsSession +{ public: MSWindowsSession(); ~MSWindowsSession(); @@ -40,7 +41,10 @@ public: HANDLE getUserToken(LPSECURITY_ATTRIBUTES security); - DWORD getActiveSessionId() { return m_activeSessionId; } + DWORD getActiveSessionId() + { + return m_activeSessionId; + } void updateActiveSession(); diff --git a/src/lib/platform/MSWindowsUtil.cpp b/src/lib/platform/MSWindowsUtil.cpp index bf0c0f420..dd6adecf7 100644 --- a/src/lib/platform/MSWindowsUtil.cpp +++ b/src/lib/platform/MSWindowsUtil.cpp @@ -26,7 +26,8 @@ // MSWindowsUtil // -String MSWindowsUtil::getString(HINSTANCE instance, DWORD id) { +String MSWindowsUtil::getString(HINSTANCE instance, DWORD id) +{ char *msg = NULL; int n = LoadString(instance, id, reinterpret_cast(&msg), 0); @@ -37,17 +38,15 @@ String MSWindowsUtil::getString(HINSTANCE instance, DWORD id) { return String(msg, n); } -String -MSWindowsUtil::getErrorString(HINSTANCE hinstance, DWORD error, DWORD id) { +String MSWindowsUtil::getErrorString(HINSTANCE hinstance, DWORD error, DWORD id) +{ char *buffer; if (FormatMessage( - FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | - FORMAT_MESSAGE_FROM_SYSTEM, - 0, error, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buffer, - 0, NULL) == 0) { + FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_FROM_SYSTEM, 0, error, + MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&buffer, 0, NULL + ) == 0) { String errorString = deskflow::string::sprintf("%d", error); - return deskflow::string::format( - getString(hinstance, id).c_str(), errorString.c_str()); + return deskflow::string::format(getString(hinstance, id).c_str(), errorString.c_str()); } else { String result(buffer); LocalFree(buffer); diff --git a/src/lib/platform/MSWindowsUtil.h b/src/lib/platform/MSWindowsUtil.h index 39156d138..bb0fadad5 100644 --- a/src/lib/platform/MSWindowsUtil.h +++ b/src/lib/platform/MSWindowsUtil.h @@ -23,7 +23,8 @@ #define WINDOWS_LEAN_AND_MEAN #include -class MSWindowsUtil { +class MSWindowsUtil +{ public: //! Get message string /*! diff --git a/src/lib/platform/MSWindowsWatchdog.cpp b/src/lib/platform/MSWindowsWatchdog.cpp index f85d4785d..372bab28a 100644 --- a/src/lib/platform/MSWindowsWatchdog.cpp +++ b/src/lib/platform/MSWindowsWatchdog.cpp @@ -45,7 +45,8 @@ static char g_desktopName[] = "winsta0\\Default"; namespace { -std::string trimDesktopName(const std::string &nameFromTraces) { +std::string trimDesktopName(const std::string &nameFromTraces) +{ std::string name; for (const auto &symbol : nameFromTraces) { @@ -59,10 +60,10 @@ std::string trimDesktopName(const std::string &nameFromTraces) { return name; } -bool isDesktopRunnable(const std::string &desktopName) { +bool isDesktopRunnable(const std::string &desktopName) +{ const std::string winlogon = "Winlogon"; - bool isNotLoginScreen = - std::strncmp(desktopName.c_str(), winlogon.c_str(), winlogon.length()); + bool isNotLoginScreen = std::strncmp(desktopName.c_str(), winlogon.c_str(), winlogon.length()); const auto setting = ARCH->setting("runOnLoginScreen"); bool runOnLoginScreen = (setting.empty() || setting == "true"); @@ -72,15 +73,18 @@ bool isDesktopRunnable(const std::string &desktopName) { } // namespace -enum { kOutputBufferSize = 4096 }; +enum +{ + kOutputBufferSize = 4096 +}; typedef VOID(WINAPI *SendSas)(BOOL asUser); const char g_activeDesktop[] = {"activeDesktop:"}; MSWindowsWatchdog::MSWindowsWatchdog( - bool autoDetectCommand, IpcServer &ipcServer, - IpcLogOutputter &ipcLogOutputter, bool foreground) + bool autoDetectCommand, IpcServer &ipcServer, IpcLogOutputter &ipcLogOutputter, bool foreground +) : m_thread(NULL), m_autoDetectCommand(autoDetectCommand), m_monitoring(true), @@ -95,12 +99,14 @@ MSWindowsWatchdog::MSWindowsWatchdog( m_fileLogOutputter(NULL), m_autoElevated(false), m_ready(false), - m_foreground(foreground) { + m_foreground(foreground) +{ m_mutex = ARCH->newMutex(); m_condVar = ARCH->newCondVar(); } -MSWindowsWatchdog::~MSWindowsWatchdog() { +MSWindowsWatchdog::~MSWindowsWatchdog() +{ if (m_condVar != NULL) { ARCH->closeCondVar(m_condVar); } @@ -110,15 +116,15 @@ MSWindowsWatchdog::~MSWindowsWatchdog() { } } -void MSWindowsWatchdog::startAsync() { - m_thread = new Thread(new TMethodJob( - this, &MSWindowsWatchdog::mainLoop, nullptr)); +void MSWindowsWatchdog::startAsync() +{ + m_thread = new Thread(new TMethodJob(this, &MSWindowsWatchdog::mainLoop, nullptr)); - m_outputThread = new Thread(new TMethodJob( - this, &MSWindowsWatchdog::outputLoop, nullptr)); + m_outputThread = new Thread(new TMethodJob(this, &MSWindowsWatchdog::outputLoop, nullptr)); } -void MSWindowsWatchdog::stop() { +void MSWindowsWatchdog::stop() +{ m_monitoring = false; m_thread->wait(5); @@ -129,12 +135,11 @@ void MSWindowsWatchdog::stop() { } HANDLE -MSWindowsWatchdog::duplicateProcessToken( - HANDLE process, LPSECURITY_ATTRIBUTES security) { +MSWindowsWatchdog::duplicateProcessToken(HANDLE process, LPSECURITY_ATTRIBUTES security) +{ HANDLE sourceToken; - BOOL tokenRet = OpenProcessToken( - process, TOKEN_ASSIGN_PRIMARY | TOKEN_ALL_ACCESS, &sourceToken); + BOOL tokenRet = OpenProcessToken(process, TOKEN_ASSIGN_PRIMARY | TOKEN_ALL_ACCESS, &sourceToken); if (!tokenRet) { LOG((CLOG_ERR "could not open token, process handle: %d", process)); @@ -145,8 +150,8 @@ MSWindowsWatchdog::duplicateProcessToken( HANDLE newToken; BOOL duplicateRet = DuplicateTokenEx( - sourceToken, TOKEN_ASSIGN_PRIMARY | TOKEN_ALL_ACCESS, security, - SecurityImpersonation, TokenPrimary, &newToken); + sourceToken, TOKEN_ASSIGN_PRIMARY | TOKEN_ALL_ACCESS, security, SecurityImpersonation, TokenPrimary, &newToken + ); if (!duplicateRet) { LOG((CLOG_ERR "could not duplicate token %i", sourceToken)); @@ -158,22 +163,19 @@ MSWindowsWatchdog::duplicateProcessToken( } HANDLE -MSWindowsWatchdog::getUserToken(LPSECURITY_ATTRIBUTES security) { +MSWindowsWatchdog::getUserToken(LPSECURITY_ATTRIBUTES security) +{ // always elevate if we are at the vista/7 login screen. we could also // elevate for the uac dialog (consent.exe) but this would be pointless, // since deskflow would re-launch as non-elevated after the desk switch, // and so would be unusable with the new elevated process taking focus. - if (m_elevateProcess || m_autoElevated || - m_session.isProcessInSession("logonui.exe", NULL)) { + if (m_elevateProcess || m_autoElevated || m_session.isProcessInSession("logonui.exe", NULL)) { - LOG( - (CLOG_DEBUG "getting elevated token, %s", - (m_elevateProcess ? "elevation required" : "at login screen"))); + LOG((CLOG_DEBUG "getting elevated token, %s", (m_elevateProcess ? "elevation required" : "at login screen"))); HANDLE process; if (!m_session.isProcessInSession("winlogon.exe", &process)) { - throw XMSWindowsWatchdogError( - "cannot get user token without winlogon.exe"); + throw XMSWindowsWatchdogError("cannot get user token without winlogon.exe"); } return duplicateProcessToken(process, security); @@ -183,7 +185,8 @@ MSWindowsWatchdog::getUserToken(LPSECURITY_ATTRIBUTES security) { } } -void MSWindowsWatchdog::mainLoop(void *) { +void MSWindowsWatchdog::mainLoop(void *) +{ shutdownExistingProcesses(); SendSas sendSasFunc = NULL; @@ -216,11 +219,8 @@ void MSWindowsWatchdog::mainLoop(void *) { if (m_processFailures != 0) { // increasing backoff period, maximum of 10 seconds. - int timeout = - (m_processFailures * 2) < 10 ? (m_processFailures * 2) : 10; - LOG( - (CLOG_INFO "backing off, wait=%ds, failures=%d", timeout, - m_processFailures)); + int timeout = (m_processFailures * 2) < 10 ? (m_processFailures * 2) : 10; + LOG((CLOG_INFO "backing off, wait=%ds, failures=%d", timeout, m_processFailures)); ARCH->sleep(timeout); } @@ -245,15 +245,12 @@ void MSWindowsWatchdog::mainLoop(void *) { m_processFailures++; m_processRunning = false; - LOG( - (CLOG_WARN "detected application not running, pid=%d", - m_processInfo.dwProcessId)); + LOG((CLOG_WARN "detected application not running, pid=%d", m_processInfo.dwProcessId)); } if (sendSasFunc != NULL) { - HANDLE sendSasEvent = - CreateEvent(NULL, FALSE, FALSE, "Global\\SendSAS"); + HANDLE sendSasEvent = CreateEvent(NULL, FALSE, FALSE, "Global\\SendSAS"); if (sendSasEvent != NULL) { // use SendSAS event to wait for next session (timeout 1 second). @@ -291,17 +288,20 @@ void MSWindowsWatchdog::mainLoop(void *) { LOG((CLOG_DEBUG "watchdog main thread finished")); } -bool MSWindowsWatchdog::isProcessActive() { +bool MSWindowsWatchdog::isProcessActive() +{ DWORD exitCode; GetExitCodeProcess(m_processInfo.hProcess, &exitCode); return exitCode == STILL_ACTIVE; } -void MSWindowsWatchdog::setFileLogOutputter(FileLogOutputter *outputter) { +void MSWindowsWatchdog::setFileLogOutputter(FileLogOutputter *outputter) +{ m_fileLogOutputter = outputter; } -void MSWindowsWatchdog::startProcess() { +void MSWindowsWatchdog::startProcess() +{ if (m_command.empty()) { throw XMSWindowsWatchdogError("cannot start process, command is empty"); } @@ -364,13 +364,14 @@ void MSWindowsWatchdog::startProcess() { LOG((CLOG_DEBUG "started core process from daemon")); LOG( - (CLOG_DEBUG2 "process info, session=%i, elevated: %s, command=%s", - m_session.getActiveSessionId(), m_elevateProcess ? "yes" : "no", - m_command.c_str())); + (CLOG_DEBUG2 "process info, session=%i, elevated: %s, command=%s", m_session.getActiveSessionId(), + m_elevateProcess ? "yes" : "no", m_command.c_str()) + ); } } -void MSWindowsWatchdog::setStartupInfo(STARTUPINFO &si) { +void MSWindowsWatchdog::setStartupInfo(STARTUPINFO &si) +{ ZeroMemory(&si, sizeof(STARTUPINFO)); si.cb = sizeof(STARTUPINFO); si.lpDesktop = g_desktopName; @@ -379,7 +380,8 @@ void MSWindowsWatchdog::setStartupInfo(STARTUPINFO &si) { si.dwFlags |= STARTF_USESTDHANDLES; } -BOOL MSWindowsWatchdog::startProcessInForeground(String &command) { +BOOL MSWindowsWatchdog::startProcessInForeground(String &command) +{ // clear, as we're reusing process info struct ZeroMemory(&m_processInfo, sizeof(PROCESS_INFORMATION)); @@ -391,17 +393,15 @@ BOOL MSWindowsWatchdog::startProcessInForeground(String &command) { si.dwFlags |= STARTF_USESHOWWINDOW; si.wShowWindow = SW_MINIMIZE; - BOOL result = CreateProcess( - NULL, LPSTR(command.c_str()), NULL, NULL, TRUE, 0, NULL, NULL, &si, - &m_processInfo); + BOOL result = CreateProcess(NULL, LPSTR(command.c_str()), NULL, NULL, TRUE, 0, NULL, NULL, &si, &m_processInfo); m_children.insert(std::make_pair(m_processInfo.dwProcessId, m_processInfo)); return result; } -BOOL MSWindowsWatchdog::startProcessAsUser( - String &command, HANDLE userToken, LPSECURITY_ATTRIBUTES sa) { +BOOL MSWindowsWatchdog::startProcessAsUser(String &command, HANDLE userToken, LPSECURITY_ATTRIBUTES sa) +{ // clear, as we're reusing process info struct ZeroMemory(&m_processInfo, sizeof(PROCESS_INFORMATION)); @@ -415,14 +415,13 @@ BOOL MSWindowsWatchdog::startProcessAsUser( throw XArch(new XArchEvalWindows); } - DWORD creationFlags = - NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT; + DWORD creationFlags = NORMAL_PRIORITY_CLASS | CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT; // re-launch in current active user session LOG((CLOG_INFO "starting new process")); BOOL createRet = CreateProcessAsUser( - userToken, NULL, LPSTR(command.c_str()), sa, NULL, TRUE, creationFlags, - environment, NULL, &si, &m_processInfo); + userToken, NULL, LPSTR(command.c_str()), sa, NULL, TRUE, creationFlags, environment, NULL, &si, &m_processInfo + ); m_children.insert(std::make_pair(m_processInfo.dwProcessId, m_processInfo)); @@ -432,7 +431,8 @@ BOOL MSWindowsWatchdog::startProcessAsUser( return createRet; } -void MSWindowsWatchdog::setCommand(const std::string &command, bool elevate) { +void MSWindowsWatchdog::setCommand(const std::string &command, bool elevate) +{ LOG((CLOG_INFO "service command updated")); m_command = command; m_elevateProcess = elevate; @@ -440,7 +440,8 @@ void MSWindowsWatchdog::setCommand(const std::string &command, bool elevate) { m_processFailures = 0; } -std::string MSWindowsWatchdog::getCommand() const { +std::string MSWindowsWatchdog::getCommand() const +{ if (!m_autoDetectCommand) { return m_command; } @@ -464,15 +465,15 @@ std::string MSWindowsWatchdog::getCommand() const { return cmd; } -void MSWindowsWatchdog::outputLoop(void *) { +void MSWindowsWatchdog::outputLoop(void *) +{ // +1 char for \0 CHAR buffer[kOutputBufferSize + 1]; while (m_monitoring) { DWORD bytesRead; - BOOL success = - ReadFile(m_stdOutRead, buffer, kOutputBufferSize, &bytesRead, NULL); + BOOL success = ReadFile(m_stdOutRead, buffer, kOutputBufferSize, &bytesRead, NULL); // assume the process has gone away? slow down // the reads until another one turns up. @@ -502,7 +503,8 @@ void MSWindowsWatchdog::outputLoop(void *) { } } -void MSWindowsWatchdog::shutdownProcess(HANDLE handle, DWORD pid, int timeout) { +void MSWindowsWatchdog::shutdownProcess(HANDLE handle, DWORD pid, int timeout) +{ DWORD exitCode; GetExitCodeProcess(handle, &exitCode); if (exitCode != STILL_ACTIVE) { @@ -529,10 +531,7 @@ void MSWindowsWatchdog::shutdownProcess(HANDLE handle, DWORD pid, int timeout) { // calling TerminateProcess on deskflow is very bad! // it causes the hook DLL to stay loaded in some apps, // making it impossible to start deskflow again. - LOG( - (CLOG_WARN - "shutdown timed out after %d secs, forcefully terminating", - (int)elapsed)); + LOG((CLOG_WARN "shutdown timed out after %d secs, forcefully terminating", (int)elapsed)); TerminateProcess(handle, kExitSuccess); break; } @@ -544,10 +543,10 @@ void MSWindowsWatchdog::shutdownProcess(HANDLE handle, DWORD pid, int timeout) { closeProcessHandles(pid); } -void MSWindowsWatchdog::shutdownExistingProcesses() { +void MSWindowsWatchdog::shutdownExistingProcesses() +{ // first we need to take a snapshot of the running processes - HANDLE snapshot = - CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, CURRENT_PROCESS_ID); + HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, CURRENT_PROCESS_ID); if (snapshot == INVALID_HANDLE_VALUE) { LOG((CLOG_ERR "could not get process snapshot")); throw XArch(new XArchEvalWindows); @@ -575,8 +574,7 @@ void MSWindowsWatchdog::shutdownExistingProcesses() { _stricmp(entry.szExeFile, SERVER_BINARY_NAME ".exe") == 0 || _stricmp(entry.szExeFile, CORE_BINARY_NAME ".exe") == 0) { - HANDLE handle = - OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID); + HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID); shutdownProcess(handle, entry.th32ProcessID, 10); CloseHandle(handle); } @@ -601,15 +599,12 @@ void MSWindowsWatchdog::shutdownExistingProcesses() { m_processRunning = false; } -void MSWindowsWatchdog::getActiveDesktop(LPSECURITY_ATTRIBUTES security) { +void MSWindowsWatchdog::getActiveDesktop(LPSECURITY_ATTRIBUTES security) +{ String installedDir = ARCH->getInstalledDirectory(); if (!installedDir.empty()) { String deskflowLegacyCommand; - deskflowLegacyCommand.append("\"") - .append(installedDir) - .append("\\") - .append(LEGACY_BINARY_NAME) - .append("\""); + deskflowLegacyCommand.append("\"").append(installedDir).append("\\").append(LEGACY_BINARY_NAME).append("\""); deskflowLegacyCommand.append(" --get-active-desktop"); m_session.updateActiveSession(); @@ -618,16 +613,13 @@ void MSWindowsWatchdog::getActiveDesktop(LPSECURITY_ATTRIBUTES security) { HANDLE userToken = getUserToken(security); m_elevateProcess = elevateProcess; - BOOL createRet = - startProcessAsUser(deskflowLegacyCommand, userToken, security); + BOOL createRet = startProcessAsUser(deskflowLegacyCommand, userToken, security); auto pid = m_processInfo.dwProcessId; if (!createRet) { DWORD rc = GetLastError(); RevertToSelf(); } else { - LOG( - (CLOG_DEBUG "launched %s to check active desktop", - LEGACY_BINARY_NAME)); + LOG((CLOG_DEBUG "launched %s to check active desktop", LEGACY_BINARY_NAME)); } ARCH->lockMutex(m_mutex); @@ -646,15 +638,15 @@ void MSWindowsWatchdog::getActiveDesktop(LPSECURITY_ATTRIBUTES security) { } } -void MSWindowsWatchdog::testOutput(String buffer) { +void MSWindowsWatchdog::testOutput(String buffer) +{ // HACK: check standard output seems hacky. size_t i = buffer.find(g_activeDesktop); if (i != String::npos) { size_t s = sizeof(g_activeDesktop); std::string defaultScreen = "Default"; m_activeDesktop = trimDesktopName(buffer.substr(i + s - 1)); - m_autoElevated = std::strncmp( - m_activeDesktop.c_str(), defaultScreen.c_str(), defaultScreen.length()); + m_autoElevated = std::strncmp(m_activeDesktop.c_str(), defaultScreen.c_str(), defaultScreen.length()); ARCH->lockMutex(m_mutex); m_ready = true; @@ -663,8 +655,8 @@ void MSWindowsWatchdog::testOutput(String buffer) { } } -void MSWindowsWatchdog::closeProcessHandles( - unsigned long pid, bool removeFromMap) { +void MSWindowsWatchdog::closeProcessHandles(unsigned long pid, bool removeFromMap) +{ auto processInfo = m_children.find(pid); if (processInfo != m_children.end()) { CloseHandle(processInfo->second.hProcess); @@ -675,7 +667,8 @@ void MSWindowsWatchdog::closeProcessHandles( } } -void MSWindowsWatchdog::clearAllChildren() { +void MSWindowsWatchdog::clearAllChildren() +{ for (auto it = m_children.begin(); it != m_children.end(); ++it) { closeProcessHandles(it->second.dwThreadId, false); } diff --git a/src/lib/platform/MSWindowsWatchdog.h b/src/lib/platform/MSWindowsWatchdog.h index 698ffbaca..be94c0f25 100644 --- a/src/lib/platform/MSWindowsWatchdog.h +++ b/src/lib/platform/MSWindowsWatchdog.h @@ -33,11 +33,10 @@ class IpcLogOutputter; class IpcServer; class FileLogOutputter; -class MSWindowsWatchdog { +class MSWindowsWatchdog +{ public: - MSWindowsWatchdog( - bool autoDetectCommand, IpcServer &ipcServer, - IpcLogOutputter &ipcLogOutputter, bool foreground); + MSWindowsWatchdog(bool autoDetectCommand, IpcServer &ipcServer, IpcLogOutputter &ipcLogOutputter, bool foreground); virtual ~MSWindowsWatchdog(); void startAsync(); @@ -55,8 +54,7 @@ private: HANDLE duplicateProcessToken(HANDLE process, LPSECURITY_ATTRIBUTES security); HANDLE getUserToken(LPSECURITY_ATTRIBUTES security); void startProcess(); - BOOL startProcessAsUser( - String &command, HANDLE userToken, LPSECURITY_ATTRIBUTES sa); + BOOL startProcessAsUser(String &command, HANDLE userToken, LPSECURITY_ATTRIBUTES sa); BOOL startProcessInForeground(String &command); void sendSas(); void getActiveDesktop(LPSECURITY_ATTRIBUTES security); @@ -110,10 +108,16 @@ private: /*! An error occured in the process watchdog. */ -class XMSWindowsWatchdogError : public XDeskflow { +class XMSWindowsWatchdogError : public XDeskflow +{ public: - XMSWindowsWatchdogError(const String &msg) : XDeskflow(msg) {} + XMSWindowsWatchdogError(const String &msg) : XDeskflow(msg) + { + } // XBase overrides - virtual String getWhat() const throw() { return what(); } + virtual String getWhat() const throw() + { + return what(); + } }; diff --git a/src/lib/platform/OSXClipboard.cpp b/src/lib/platform/OSXClipboard.cpp index 81dba2530..b31f71b0e 100644 --- a/src/lib/platform/OSXClipboard.cpp +++ b/src/lib/platform/OSXClipboard.cpp @@ -31,7 +31,8 @@ // OSXClipboard // -OSXClipboard::OSXClipboard() : m_time(0), m_pboard(NULL) { +OSXClipboard::OSXClipboard() : m_time(0), m_pboard(NULL) +{ m_converters.push_back(new OSXClipboardHTMLConverter); m_converters.push_back(new OSXClipboardBMPConverter); m_converters.push_back(new OSXClipboardUTF8Converter); @@ -40,12 +41,8 @@ OSXClipboard::OSXClipboard() : m_time(0), m_pboard(NULL) { OSStatus createErr = PasteboardCreate(kPasteboardClipboard, &m_pboard); if (createErr != noErr) { - LOG( - (CLOG_DEBUG "failed to create clipboard reference: error %i", - createErr)); - LOG( - (CLOG_ERR "unable to connect to pasteboard, clipboard sharing disabled", - createErr)); + LOG((CLOG_DEBUG "failed to create clipboard reference: error %i", createErr)); + LOG((CLOG_ERR "unable to connect to pasteboard, clipboard sharing disabled", createErr)); m_pboard = NULL; return; } @@ -56,9 +53,13 @@ OSXClipboard::OSXClipboard() : m_time(0), m_pboard(NULL) { } } -OSXClipboard::~OSXClipboard() { clearConverters(); } +OSXClipboard::~OSXClipboard() +{ + clearConverters(); +} -bool OSXClipboard::empty() { +bool OSXClipboard::empty() +{ LOG((CLOG_DEBUG "emptying clipboard")); if (m_pboard == NULL) return false; @@ -72,7 +73,8 @@ bool OSXClipboard::empty() { return true; } -bool OSXClipboard::synchronize() { +bool OSXClipboard::synchronize() +{ if (m_pboard == NULL) return false; @@ -85,7 +87,8 @@ bool OSXClipboard::synchronize() { return false; } -void OSXClipboard::add(EFormat format, const String &data) { +void OSXClipboard::add(EFormat format, const String &data) +{ if (m_pboard == NULL) return; @@ -98,8 +101,7 @@ void OSXClipboard::add(EFormat format, const String &data) { LOG((CLOG_DEBUG "format of data to be added to clipboard was kHTML")); } - for (ConverterList::const_iterator index = m_converters.begin(); - index != m_converters.end(); ++index) { + for (ConverterList::const_iterator index = m_converters.begin(); index != m_converters.end(); ++index) { IOSXClipboardConverter *converter = *index; @@ -107,24 +109,21 @@ void OSXClipboard::add(EFormat format, const String &data) { if (converter->getFormat() == format) { String osXData = converter->fromIClipboard(data); CFStringRef flavorType = converter->getOSXFormat(); - CFDataRef dataRef = CFDataCreate( - kCFAllocatorDefault, (UInt8 *)osXData.data(), osXData.size()); + CFDataRef dataRef = CFDataCreate(kCFAllocatorDefault, (UInt8 *)osXData.data(), osXData.size()); PasteboardItemID itemID = 0; if (dataRef) { - PasteboardPutItemFlavor( - m_pboard, itemID, flavorType, dataRef, kPasteboardFlavorNoFlags); + PasteboardPutItemFlavor(m_pboard, itemID, flavorType, dataRef, kPasteboardFlavorNoFlags); CFRelease(dataRef); - LOG( - (CLOG_DEBUG "added %d bytes to clipboard format: %d", data.size(), - format)); + LOG((CLOG_DEBUG "added %d bytes to clipboard format: %d", data.size(), format)); } } } } -bool OSXClipboard::open(Time time) const { +bool OSXClipboard::open(Time time) const +{ if (m_pboard == NULL) return false; @@ -133,22 +132,26 @@ bool OSXClipboard::open(Time time) const { return true; } -void OSXClipboard::close() const { +void OSXClipboard::close() const +{ LOG((CLOG_DEBUG "closing clipboard")); /* not needed */ } -IClipboard::Time OSXClipboard::getTime() const { return m_time; } +IClipboard::Time OSXClipboard::getTime() const +{ + return m_time; +} -bool OSXClipboard::has(EFormat format) const { +bool OSXClipboard::has(EFormat format) const +{ if (m_pboard == NULL) return false; PasteboardItemID item; PasteboardGetItemIdentifier(m_pboard, (CFIndex)1, &item); - for (ConverterList::const_iterator index = m_converters.begin(); - index != m_converters.end(); ++index) { + for (ConverterList::const_iterator index = m_converters.begin(); index != m_converters.end(); ++index) { IOSXClipboardConverter *converter = *index; if (converter->getFormat() == format) { PasteboardFlavorFlags flags; @@ -156,8 +159,7 @@ bool OSXClipboard::has(EFormat format) const { OSStatus res; - if ((res = PasteboardGetItemFlavorFlags(m_pboard, item, type, &flags)) == - noErr) { + if ((res = PasteboardGetItemFlavorFlags(m_pboard, item, type, &flags)) == noErr) { return true; } } @@ -166,7 +168,8 @@ bool OSXClipboard::has(EFormat format) const { return false; } -String OSXClipboard::get(EFormat format) const { +String OSXClipboard::get(EFormat format) const +{ CFStringRef type; PasteboardItemID item; String result; @@ -178,15 +181,13 @@ String OSXClipboard::get(EFormat format) const { // find the converter for the first clipboard format we can handle IOSXClipboardConverter *converter = NULL; - for (ConverterList::const_iterator index = m_converters.begin(); - index != m_converters.end(); ++index) { + for (ConverterList::const_iterator index = m_converters.begin(); index != m_converters.end(); ++index) { converter = *index; PasteboardFlavorFlags flags; type = converter->getOSXFormat(); - if (converter->getFormat() == format && - PasteboardGetItemFlavorFlags(m_pboard, item, type, &flags) == noErr) { + if (converter->getFormat() == format && PasteboardGetItemFlavorFlags(m_pboard, item, type, &flags) == noErr) { break; } converter = NULL; @@ -209,8 +210,7 @@ String OSXClipboard::get(EFormat format) const { result = String((char *)CFDataGetBytePtr(buffer), CFDataGetLength(buffer)); } catch (OSStatus err) { - LOG(( - CLOG_DEBUG "exception thrown in OSXClipboard::get MacError (%d)", err)); + LOG((CLOG_DEBUG "exception thrown in OSXClipboard::get MacError (%d)", err)); } catch (...) { LOG((CLOG_DEBUG "unknown exception in OSXClipboard::get")); RETHROW_XTHREAD @@ -222,12 +222,12 @@ String OSXClipboard::get(EFormat format) const { return converter->toIClipboard(result); } -void OSXClipboard::clearConverters() { +void OSXClipboard::clearConverters() +{ if (m_pboard == NULL) return; - for (ConverterList::iterator index = m_converters.begin(); - index != m_converters.end(); ++index) { + for (ConverterList::iterator index = m_converters.begin(); index != m_converters.end(); ++index) { delete *index; } m_converters.clear(); diff --git a/src/lib/platform/OSXClipboard.h b/src/lib/platform/OSXClipboard.h index b3c8f4980..505b61a43 100644 --- a/src/lib/platform/OSXClipboard.h +++ b/src/lib/platform/OSXClipboard.h @@ -26,7 +26,8 @@ class IOSXClipboardConverter; //! OS X clipboard implementation -class OSXClipboard : public IClipboard { +class OSXClipboard : public IClipboard +{ public: OSXClipboard(); virtual ~OSXClipboard(); @@ -60,7 +61,8 @@ private: /*! This interface defines the methods common to all Scrap book format */ -class IOSXClipboardConverter : public IInterface { +class IOSXClipboardConverter : public IInterface +{ public: //! @name accessors //@{ diff --git a/src/lib/platform/OSXClipboardAnyBitmapConverter.cpp b/src/lib/platform/OSXClipboardAnyBitmapConverter.cpp index 8a9e11fdf..400b09716 100644 --- a/src/lib/platform/OSXClipboardAnyBitmapConverter.cpp +++ b/src/lib/platform/OSXClipboardAnyBitmapConverter.cpp @@ -19,23 +19,27 @@ #include "platform/OSXClipboardAnyBitmapConverter.h" #include -OSXClipboardAnyBitmapConverter::OSXClipboardAnyBitmapConverter() { +OSXClipboardAnyBitmapConverter::OSXClipboardAnyBitmapConverter() +{ // do nothing } -OSXClipboardAnyBitmapConverter::~OSXClipboardAnyBitmapConverter() { +OSXClipboardAnyBitmapConverter::~OSXClipboardAnyBitmapConverter() +{ // do nothing } -IClipboard::EFormat OSXClipboardAnyBitmapConverter::getFormat() const { +IClipboard::EFormat OSXClipboardAnyBitmapConverter::getFormat() const +{ return IClipboard::kBitmap; } -String -OSXClipboardAnyBitmapConverter::fromIClipboard(const String &data) const { +String OSXClipboardAnyBitmapConverter::fromIClipboard(const String &data) const +{ return doFromIClipboard(data); } -String OSXClipboardAnyBitmapConverter::toIClipboard(const String &data) const { +String OSXClipboardAnyBitmapConverter::toIClipboard(const String &data) const +{ return doToIClipboard(data); } diff --git a/src/lib/platform/OSXClipboardAnyBitmapConverter.h b/src/lib/platform/OSXClipboardAnyBitmapConverter.h index c2bec9518..f5e5b0898 100644 --- a/src/lib/platform/OSXClipboardAnyBitmapConverter.h +++ b/src/lib/platform/OSXClipboardAnyBitmapConverter.h @@ -21,7 +21,8 @@ #include "platform/OSXClipboard.h" //! Convert to/from some text encoding -class OSXClipboardAnyBitmapConverter : public IOSXClipboardConverter { +class OSXClipboardAnyBitmapConverter : public IOSXClipboardConverter +{ public: OSXClipboardAnyBitmapConverter(); virtual ~OSXClipboardAnyBitmapConverter(); diff --git a/src/lib/platform/OSXClipboardAnyTextConverter.cpp b/src/lib/platform/OSXClipboardAnyTextConverter.cpp index 7a91c5110..3c8721dd4 100644 --- a/src/lib/platform/OSXClipboardAnyTextConverter.cpp +++ b/src/lib/platform/OSXClipboardAnyTextConverter.cpp @@ -24,33 +24,45 @@ // OSXClipboardAnyTextConverter // -OSXClipboardAnyTextConverter::OSXClipboardAnyTextConverter() { +OSXClipboardAnyTextConverter::OSXClipboardAnyTextConverter() +{ // do nothing } -OSXClipboardAnyTextConverter::~OSXClipboardAnyTextConverter() { +OSXClipboardAnyTextConverter::~OSXClipboardAnyTextConverter() +{ // do nothing } -IClipboard::EFormat OSXClipboardAnyTextConverter::getFormat() const { +IClipboard::EFormat OSXClipboardAnyTextConverter::getFormat() const +{ return IClipboard::kText; } -String OSXClipboardAnyTextConverter::fromIClipboard(const String &data) const { +String OSXClipboardAnyTextConverter::fromIClipboard(const String &data) const +{ // convert linefeeds and then convert to desired encoding return doFromIClipboard(convertLinefeedToMacOS(data)); } -String OSXClipboardAnyTextConverter::toIClipboard(const String &data) const { +String OSXClipboardAnyTextConverter::toIClipboard(const String &data) const +{ // convert text then newlines return convertLinefeedToUnix(doToIClipboard(data)); } -static bool isLF(char ch) { return (ch == '\n'); } +static bool isLF(char ch) +{ + return (ch == '\n'); +} -static bool isCR(char ch) { return (ch == '\r'); } +static bool isCR(char ch) +{ + return (ch == '\r'); +} -String OSXClipboardAnyTextConverter::convertLinefeedToMacOS(const String &src) { +String OSXClipboardAnyTextConverter::convertLinefeedToMacOS(const String &src) +{ // note -- we assume src is a valid UTF-8 string String copy = src; @@ -59,7 +71,8 @@ String OSXClipboardAnyTextConverter::convertLinefeedToMacOS(const String &src) { return copy; } -String OSXClipboardAnyTextConverter::convertLinefeedToUnix(const String &src) { +String OSXClipboardAnyTextConverter::convertLinefeedToUnix(const String &src) +{ String copy = src; std::replace_if(copy.begin(), copy.end(), isCR, '\n'); diff --git a/src/lib/platform/OSXClipboardAnyTextConverter.h b/src/lib/platform/OSXClipboardAnyTextConverter.h index 918395747..9d7a18da3 100644 --- a/src/lib/platform/OSXClipboardAnyTextConverter.h +++ b/src/lib/platform/OSXClipboardAnyTextConverter.h @@ -21,7 +21,8 @@ #include "platform/OSXClipboard.h" //! Convert to/from some text encoding -class OSXClipboardAnyTextConverter : public IOSXClipboardConverter { +class OSXClipboardAnyTextConverter : public IOSXClipboardConverter +{ public: OSXClipboardAnyTextConverter(); virtual ~OSXClipboardAnyTextConverter(); diff --git a/src/lib/platform/OSXClipboardBMPConverter.cpp b/src/lib/platform/OSXClipboardBMPConverter.cpp index d4cdd5a4a..076bdabe4 100644 --- a/src/lib/platform/OSXClipboardBMPConverter.cpp +++ b/src/lib/platform/OSXClipboardBMPConverter.cpp @@ -20,7 +20,8 @@ #include "base/Log.h" // BMP file header structure -struct CBMPHeader { +struct CBMPHeader +{ public: UInt16 type; UInt32 size; @@ -30,24 +31,27 @@ public: }; // BMP is little-endian -static inline UInt32 fromLEU32(const UInt8 *data) { - return static_cast(data[0]) | (static_cast(data[1]) << 8) | - (static_cast(data[2]) << 16) | +static inline UInt32 fromLEU32(const UInt8 *data) +{ + return static_cast(data[0]) | (static_cast(data[1]) << 8) | (static_cast(data[2]) << 16) | (static_cast(data[3]) << 24); } -static void toLE(UInt8 *&dst, char src) { +static void toLE(UInt8 *&dst, char src) +{ dst[0] = static_cast(src); dst += 1; } -static void toLE(UInt8 *&dst, UInt16 src) { +static void toLE(UInt8 *&dst, UInt16 src) +{ dst[0] = static_cast(src & 0xffu); dst[1] = static_cast((src >> 8) & 0xffu); dst += 2; } -static void toLE(UInt8 *&dst, UInt32 src) { +static void toLE(UInt8 *&dst, UInt32 src) +{ dst[0] = static_cast(src & 0xffu); dst[1] = static_cast((src >> 8) & 0xffu); dst[2] = static_cast((src >> 16) & 0xffu); @@ -55,24 +59,29 @@ static void toLE(UInt8 *&dst, UInt32 src) { dst += 4; } -OSXClipboardBMPConverter::OSXClipboardBMPConverter() { +OSXClipboardBMPConverter::OSXClipboardBMPConverter() +{ // do nothing } -OSXClipboardBMPConverter::~OSXClipboardBMPConverter() { +OSXClipboardBMPConverter::~OSXClipboardBMPConverter() +{ // do nothing } -IClipboard::EFormat OSXClipboardBMPConverter::getFormat() const { +IClipboard::EFormat OSXClipboardBMPConverter::getFormat() const +{ return IClipboard::kBitmap; } -CFStringRef OSXClipboardBMPConverter::getOSXFormat() const { +CFStringRef OSXClipboardBMPConverter::getOSXFormat() const +{ // TODO: does this only work with Windows? return CFSTR("com.microsoft.bmp"); } -String OSXClipboardBMPConverter::fromIClipboard(const String &bmp) const { +String OSXClipboardBMPConverter::fromIClipboard(const String &bmp) const +{ LOG((CLOG_DEBUG1 "getting data from clipboard")); // create BMP image UInt8 header[14]; @@ -86,7 +95,8 @@ String OSXClipboardBMPConverter::fromIClipboard(const String &bmp) const { return String(reinterpret_cast(header), 14) + bmp; } -String OSXClipboardBMPConverter::toIClipboard(const String &bmp) const { +String OSXClipboardBMPConverter::toIClipboard(const String &bmp) const +{ // make sure data is big enough for a BMP file if (bmp.size() <= 14 + 40) { return String(); diff --git a/src/lib/platform/OSXClipboardBMPConverter.h b/src/lib/platform/OSXClipboardBMPConverter.h index ece5db86a..21ff5656d 100644 --- a/src/lib/platform/OSXClipboardBMPConverter.h +++ b/src/lib/platform/OSXClipboardBMPConverter.h @@ -21,7 +21,8 @@ #include "platform/OSXClipboard.h" //! Convert to/from some text encoding -class OSXClipboardBMPConverter : public IOSXClipboardConverter { +class OSXClipboardBMPConverter : public IOSXClipboardConverter +{ public: OSXClipboardBMPConverter(); virtual ~OSXClipboardBMPConverter(); @@ -36,7 +37,5 @@ public: virtual String toIClipboard(const String &) const; // generic encoding converter - static String convertString( - const String &data, CFStringEncoding fromEncoding, - CFStringEncoding toEncoding); + static String convertString(const String &data, CFStringEncoding fromEncoding, CFStringEncoding toEncoding); }; diff --git a/src/lib/platform/OSXClipboardHTMLConverter.cpp b/src/lib/platform/OSXClipboardHTMLConverter.cpp index bac81e6d7..5a4685dc5 100644 --- a/src/lib/platform/OSXClipboardHTMLConverter.cpp +++ b/src/lib/platform/OSXClipboardHTMLConverter.cpp @@ -20,27 +20,30 @@ #include "base/Unicode.h" -OSXClipboardHTMLConverter::OSXClipboardHTMLConverter() { +OSXClipboardHTMLConverter::OSXClipboardHTMLConverter() +{ // do nothing } -OSXClipboardHTMLConverter::~OSXClipboardHTMLConverter() { +OSXClipboardHTMLConverter::~OSXClipboardHTMLConverter() +{ // do nothing } -IClipboard::EFormat OSXClipboardHTMLConverter::getFormat() const { +IClipboard::EFormat OSXClipboardHTMLConverter::getFormat() const +{ return IClipboard::kHTML; } -CFStringRef OSXClipboardHTMLConverter::getOSXFormat() const { +CFStringRef OSXClipboardHTMLConverter::getOSXFormat() const +{ return CFSTR("public.html"); } -String OSXClipboardHTMLConverter::convertString( - const String &data, CFStringEncoding fromEncoding, - CFStringEncoding toEncoding) { - CFStringRef stringRef = CFStringCreateWithCString( - kCFAllocatorDefault, data.c_str(), fromEncoding); +String +OSXClipboardHTMLConverter::convertString(const String &data, CFStringEncoding fromEncoding, CFStringEncoding toEncoding) +{ + CFStringRef stringRef = CFStringCreateWithCString(kCFAllocatorDefault, data.c_str(), fromEncoding); if (stringRef == NULL) { return String(); @@ -49,8 +52,7 @@ String OSXClipboardHTMLConverter::convertString( CFIndex buffSize; CFRange entireString = CFRangeMake(0, CFStringGetLength(stringRef)); - CFStringGetBytes( - stringRef, entireString, toEncoding, 0, false, NULL, 0, &buffSize); + CFStringGetBytes(stringRef, entireString, toEncoding, 0, false, NULL, 0, &buffSize); char *buffer = new char[buffSize]; @@ -59,9 +61,7 @@ String OSXClipboardHTMLConverter::convertString( return String(); } - CFStringGetBytes( - stringRef, entireString, toEncoding, 0, false, (UInt8 *)buffer, buffSize, - NULL); + CFStringGetBytes(stringRef, entireString, toEncoding, 0, false, (UInt8 *)buffer, buffSize, NULL); String result(buffer, buffSize); @@ -71,15 +71,16 @@ String OSXClipboardHTMLConverter::convertString( return result; } -String OSXClipboardHTMLConverter::doFromIClipboard(const String &data) const { +String OSXClipboardHTMLConverter::doFromIClipboard(const String &data) const +{ return data; } -String OSXClipboardHTMLConverter::doToIClipboard(const String &data) const { +String OSXClipboardHTMLConverter::doToIClipboard(const String &data) const +{ if (Unicode::isUTF8(data)) { return data; } else { - return convertString( - data, CFStringGetSystemEncoding(), kCFStringEncodingUTF8); + return convertString(data, CFStringGetSystemEncoding(), kCFStringEncodingUTF8); } } diff --git a/src/lib/platform/OSXClipboardHTMLConverter.h b/src/lib/platform/OSXClipboardHTMLConverter.h index e57596467..e3a687a6a 100644 --- a/src/lib/platform/OSXClipboardHTMLConverter.h +++ b/src/lib/platform/OSXClipboardHTMLConverter.h @@ -21,7 +21,8 @@ #include "OSXClipboardAnyTextConverter.h" //! Convert to/from HTML encoding -class OSXClipboardHTMLConverter : public OSXClipboardAnyTextConverter { +class OSXClipboardHTMLConverter : public OSXClipboardAnyTextConverter +{ public: OSXClipboardHTMLConverter(); virtual ~OSXClipboardHTMLConverter(); @@ -37,7 +38,5 @@ protected: virtual String doToIClipboard(const String &) const; // generic encoding converter - static String convertString( - const String &data, CFStringEncoding fromEncoding, - CFStringEncoding toEncoding); + static String convertString(const String &data, CFStringEncoding fromEncoding, CFStringEncoding toEncoding); }; diff --git a/src/lib/platform/OSXClipboardTextConverter.cpp b/src/lib/platform/OSXClipboardTextConverter.cpp index ba36c214e..5d5e1acc0 100644 --- a/src/lib/platform/OSXClipboardTextConverter.cpp +++ b/src/lib/platform/OSXClipboardTextConverter.cpp @@ -24,23 +24,25 @@ // OSXClipboardTextConverter // -OSXClipboardTextConverter::OSXClipboardTextConverter() { +OSXClipboardTextConverter::OSXClipboardTextConverter() +{ // do nothing } -OSXClipboardTextConverter::~OSXClipboardTextConverter() { +OSXClipboardTextConverter::~OSXClipboardTextConverter() +{ // do nothing } -CFStringRef OSXClipboardTextConverter::getOSXFormat() const { +CFStringRef OSXClipboardTextConverter::getOSXFormat() const +{ return CFSTR("public.plain-text"); } -String OSXClipboardTextConverter::convertString( - const String &data, CFStringEncoding fromEncoding, - CFStringEncoding toEncoding) { - CFStringRef stringRef = CFStringCreateWithCString( - kCFAllocatorDefault, data.c_str(), fromEncoding); +String +OSXClipboardTextConverter::convertString(const String &data, CFStringEncoding fromEncoding, CFStringEncoding toEncoding) +{ + CFStringRef stringRef = CFStringCreateWithCString(kCFAllocatorDefault, data.c_str(), fromEncoding); if (stringRef == NULL) { return String(); @@ -49,8 +51,7 @@ String OSXClipboardTextConverter::convertString( CFIndex buffSize; CFRange entireString = CFRangeMake(0, CFStringGetLength(stringRef)); - CFStringGetBytes( - stringRef, entireString, toEncoding, 0, false, NULL, 0, &buffSize); + CFStringGetBytes(stringRef, entireString, toEncoding, 0, false, NULL, 0, &buffSize); char *buffer = new char[buffSize]; @@ -59,9 +60,7 @@ String OSXClipboardTextConverter::convertString( return String(); } - CFStringGetBytes( - stringRef, entireString, toEncoding, 0, false, (UInt8 *)buffer, buffSize, - NULL); + CFStringGetBytes(stringRef, entireString, toEncoding, 0, false, (UInt8 *)buffer, buffSize, NULL); String result(buffer, buffSize); @@ -71,12 +70,12 @@ String OSXClipboardTextConverter::convertString( return result; } -String OSXClipboardTextConverter::doFromIClipboard(const String &data) const { - return convertString( - data, kCFStringEncodingUTF8, CFStringGetSystemEncoding()); +String OSXClipboardTextConverter::doFromIClipboard(const String &data) const +{ + return convertString(data, kCFStringEncodingUTF8, CFStringGetSystemEncoding()); } -String OSXClipboardTextConverter::doToIClipboard(const String &data) const { - return convertString( - data, CFStringGetSystemEncoding(), kCFStringEncodingUTF8); +String OSXClipboardTextConverter::doToIClipboard(const String &data) const +{ + return convertString(data, CFStringGetSystemEncoding(), kCFStringEncodingUTF8); } diff --git a/src/lib/platform/OSXClipboardTextConverter.h b/src/lib/platform/OSXClipboardTextConverter.h index abaaa4920..ff048f3fe 100644 --- a/src/lib/platform/OSXClipboardTextConverter.h +++ b/src/lib/platform/OSXClipboardTextConverter.h @@ -21,7 +21,8 @@ #include "platform/OSXClipboardAnyTextConverter.h" //! Convert to/from locale text encoding -class OSXClipboardTextConverter : public OSXClipboardAnyTextConverter { +class OSXClipboardTextConverter : public OSXClipboardAnyTextConverter +{ public: OSXClipboardTextConverter(); virtual ~OSXClipboardTextConverter(); @@ -35,7 +36,5 @@ protected: virtual String doToIClipboard(const String &) const; // generic encoding converter - static String convertString( - const String &data, CFStringEncoding fromEncoding, - CFStringEncoding toEncoding); + static String convertString(const String &data, CFStringEncoding fromEncoding, CFStringEncoding toEncoding); }; diff --git a/src/lib/platform/OSXClipboardUTF16Converter.cpp b/src/lib/platform/OSXClipboardUTF16Converter.cpp index d44d32818..f9c707091 100644 --- a/src/lib/platform/OSXClipboardUTF16Converter.cpp +++ b/src/lib/platform/OSXClipboardUTF16Converter.cpp @@ -24,24 +24,29 @@ // OSXClipboardUTF16Converter // -OSXClipboardUTF16Converter::OSXClipboardUTF16Converter() { +OSXClipboardUTF16Converter::OSXClipboardUTF16Converter() +{ // do nothing } -OSXClipboardUTF16Converter::~OSXClipboardUTF16Converter() { +OSXClipboardUTF16Converter::~OSXClipboardUTF16Converter() +{ // do nothing } -CFStringRef OSXClipboardUTF16Converter::getOSXFormat() const { +CFStringRef OSXClipboardUTF16Converter::getOSXFormat() const +{ return CFSTR("public.utf16-plain-text"); } -String OSXClipboardUTF16Converter::doFromIClipboard(const String &data) const { +String OSXClipboardUTF16Converter::doFromIClipboard(const String &data) const +{ // convert and add nul terminator return Unicode::UTF8ToUTF16(data); } -String OSXClipboardUTF16Converter::doToIClipboard(const String &data) const { +String OSXClipboardUTF16Converter::doToIClipboard(const String &data) const +{ // convert and strip nul terminator return Unicode::UTF16ToUTF8(data); } diff --git a/src/lib/platform/OSXClipboardUTF16Converter.h b/src/lib/platform/OSXClipboardUTF16Converter.h index 0cc054a34..052837000 100644 --- a/src/lib/platform/OSXClipboardUTF16Converter.h +++ b/src/lib/platform/OSXClipboardUTF16Converter.h @@ -21,7 +21,8 @@ #include "platform/OSXClipboardAnyTextConverter.h" //! Convert to/from UTF-16 encoding -class OSXClipboardUTF16Converter : public OSXClipboardAnyTextConverter { +class OSXClipboardUTF16Converter : public OSXClipboardAnyTextConverter +{ public: OSXClipboardUTF16Converter(); virtual ~OSXClipboardUTF16Converter(); diff --git a/src/lib/platform/OSXClipboardUTF8Converter.cpp b/src/lib/platform/OSXClipboardUTF8Converter.cpp index e5abf1a81..0aeb97432 100644 --- a/src/lib/platform/OSXClipboardUTF8Converter.cpp +++ b/src/lib/platform/OSXClipboardUTF8Converter.cpp @@ -1,13 +1,16 @@ #include "OSXClipboardUTF8Converter.h" -CFStringRef OSXClipboardUTF8Converter::getOSXFormat() const { +CFStringRef OSXClipboardUTF8Converter::getOSXFormat() const +{ return CFSTR("public.utf8-plain-text"); } -String OSXClipboardUTF8Converter::doFromIClipboard(const String &data) const { +String OSXClipboardUTF8Converter::doFromIClipboard(const String &data) const +{ return data; } -String OSXClipboardUTF8Converter::doToIClipboard(const String &data) const { +String OSXClipboardUTF8Converter::doToIClipboard(const String &data) const +{ return data; } diff --git a/src/lib/platform/OSXClipboardUTF8Converter.h b/src/lib/platform/OSXClipboardUTF8Converter.h index 3e55378af..fb97ff72a 100644 --- a/src/lib/platform/OSXClipboardUTF8Converter.h +++ b/src/lib/platform/OSXClipboardUTF8Converter.h @@ -19,7 +19,8 @@ #include "platform/OSXClipboardAnyTextConverter.h" -class OSXClipboardUTF8Converter : public OSXClipboardAnyTextConverter { +class OSXClipboardUTF8Converter : public OSXClipboardAnyTextConverter +{ public: virtual CFStringRef getOSXFormat() const; diff --git a/src/lib/platform/OSXDragSimulator.h b/src/lib/platform/OSXDragSimulator.h index 310a9cd94..150e4cae4 100644 --- a/src/lib/platform/OSXDragSimulator.h +++ b/src/lib/platform/OSXDragSimulator.h @@ -22,12 +22,13 @@ #import #if defined(__cplusplus) -extern "C" { +extern "C" +{ #endif -void runCocoaApp(); -void stopCocoaLoop(); -void fakeDragging(const char *str, int cursorX, int cursorY); -CFStringRef getCocoaDropTarget(); + void runCocoaApp(); + void stopCocoaLoop(); + void fakeDragging(const char *str, int cursorX, int cursorY); + CFStringRef getCocoaDropTarget(); #if defined(__cplusplus) } diff --git a/src/lib/platform/OSXEventQueueBuffer.cpp b/src/lib/platform/OSXEventQueueBuffer.cpp index fb6af3a65..5b2aeb2d3 100644 --- a/src/lib/platform/OSXEventQueueBuffer.cpp +++ b/src/lib/platform/OSXEventQueueBuffer.cpp @@ -25,7 +25,9 @@ // EventQueueTimer // -class EventQueueTimer {}; +class EventQueueTimer +{ +}; // // OSXEventQueueBuffer @@ -34,28 +36,32 @@ class EventQueueTimer {}; OSXEventQueueBuffer::OSXEventQueueBuffer(IEventQueue *events) : m_event(NULL), m_eventQueue(events), - m_carbonEventQueue(NULL) { + m_carbonEventQueue(NULL) +{ // do nothing } -OSXEventQueueBuffer::~OSXEventQueueBuffer() { +OSXEventQueueBuffer::~OSXEventQueueBuffer() +{ // release the last event if (m_event != NULL) { ReleaseEvent(m_event); } } -void OSXEventQueueBuffer::init() { +void OSXEventQueueBuffer::init() +{ m_carbonEventQueue = GetCurrentEventQueue(); } -void OSXEventQueueBuffer::waitForEvent(double timeout) { +void OSXEventQueueBuffer::waitForEvent(double timeout) +{ EventRef event; ReceiveNextEvent(0, NULL, timeout, false, &event); } -IEventQueueBuffer::Type -OSXEventQueueBuffer::getEvent(Event &event, UInt32 &dataID) { +IEventQueueBuffer::Type OSXEventQueueBuffer::getEvent(Event &event, UInt32 &dataID) +{ // release the previous event if (m_event != NULL) { ReleaseEvent(m_event); @@ -85,10 +91,10 @@ OSXEventQueueBuffer::getEvent(Event &event, UInt32 &dataID) { } } -bool OSXEventQueueBuffer::addEvent(UInt32 dataID) { +bool OSXEventQueueBuffer::addEvent(UInt32 dataID) +{ EventRef event; - OSStatus error = CreateEvent( - kCFAllocatorDefault, 'Syne', dataID, 0, kEventAttributeNone, &event); + OSStatus error = CreateEvent(kCFAllocatorDefault, 'Syne', dataID, 0, kEventAttributeNone, &event); if (error == noErr) { @@ -102,16 +108,19 @@ bool OSXEventQueueBuffer::addEvent(UInt32 dataID) { return (error == noErr); } -bool OSXEventQueueBuffer::isEmpty() const { +bool OSXEventQueueBuffer::isEmpty() const +{ EventRef event; OSStatus status = ReceiveNextEvent(0, NULL, 0.0, false, &event); return (status == eventLoopTimedOutErr); } -EventQueueTimer *OSXEventQueueBuffer::newTimer(double, bool) const { +EventQueueTimer *OSXEventQueueBuffer::newTimer(double, bool) const +{ return new EventQueueTimer; } -void OSXEventQueueBuffer::deleteTimer(EventQueueTimer *timer) const { +void OSXEventQueueBuffer::deleteTimer(EventQueueTimer *timer) const +{ delete timer; } diff --git a/src/lib/platform/OSXEventQueueBuffer.h b/src/lib/platform/OSXEventQueueBuffer.h index 07b14485e..749f52eca 100644 --- a/src/lib/platform/OSXEventQueueBuffer.h +++ b/src/lib/platform/OSXEventQueueBuffer.h @@ -25,7 +25,8 @@ class IEventQueue; //! Event queue buffer for OS X -class OSXEventQueueBuffer : public IEventQueueBuffer { +class OSXEventQueueBuffer : public IEventQueueBuffer +{ public: OSXEventQueueBuffer(IEventQueue *eventQueue); virtual ~OSXEventQueueBuffer(); diff --git a/src/lib/platform/OSXKeyState.cpp b/src/lib/platform/OSXKeyState.cpp index e4bc50b23..0852c6d22 100644 --- a/src/lib/platform/OSXKeyState.cpp +++ b/src/lib/platform/OSXKeyState.cpp @@ -46,7 +46,8 @@ static const UInt32 s_launchpadVK = 131; static const UInt32 s_osxNumLock = 1 << 16; -struct KeyEntry { +struct KeyEntry +{ public: KeyID m_keyID; UInt32 m_virtualKey; @@ -132,24 +133,26 @@ static const KeyEntry s_controlKeys[] = { {kKeyMissionControl, s_missionControlVK}, {kKeyLaunchpad, s_launchpadVK}, {kKeyBrightnessUp, s_brightnessUp}, - {kKeyBrightnessDown, s_brightnessDown}}; + {kKeyBrightnessDown, s_brightnessDown} +}; namespace { -io_connect_t getService(io_iterator_t iter) { +io_connect_t getService(io_iterator_t iter) +{ io_connect_t service = 0; auto nextIterator = IOIteratorNext(iter); if (nextIterator) { - IOServiceOpen( - nextIterator, mach_task_self(), kIOHIDParamConnectType, &service); + IOServiceOpen(nextIterator, mach_task_self(), kIOHIDParamConnectType, &service); IOObjectRelease(nextIterator); } return service; } -io_connect_t getEventDriver() { +io_connect_t getEventDriver() +{ static io_connect_t sEventDrvrRef = 0; if (!sEventDrvrRef) { @@ -174,9 +177,9 @@ io_connect_t getEventDriver() { return sEventDrvrRef; } -bool isModifier(UInt8 virtualKey) { - static std::set modifiers{ - s_shiftVK, s_superVK, s_altVK, s_controlVK, s_capsLockVK}; +bool isModifier(UInt8 virtualKey) +{ + static std::set modifiers{s_shiftVK, s_superVK, s_altVK, s_controlVK, s_capsLockVK}; return (modifiers.find(virtualKey) != modifiers.end()); } @@ -187,22 +190,26 @@ bool isModifier(UInt8 virtualKey) { // OSXKeyState // -OSXKeyState::OSXKeyState( - IEventQueue *events, std::vector layouts, bool isLangSyncEnabled) - : KeyState(events, std::move(layouts), isLangSyncEnabled) { +OSXKeyState::OSXKeyState(IEventQueue *events, std::vector layouts, bool isLangSyncEnabled) + : KeyState(events, std::move(layouts), isLangSyncEnabled) +{ init(); } OSXKeyState::OSXKeyState( - IEventQueue *events, deskflow::KeyMap &keyMap, std::vector layouts, - bool isLangSyncEnabled) - : KeyState(events, keyMap, std::move(layouts), isLangSyncEnabled) { + IEventQueue *events, deskflow::KeyMap &keyMap, std::vector layouts, bool isLangSyncEnabled +) + : KeyState(events, keyMap, std::move(layouts), isLangSyncEnabled) +{ init(); } -OSXKeyState::~OSXKeyState() {} +OSXKeyState::~OSXKeyState() +{ +} -void OSXKeyState::init() { +void OSXKeyState::init() +{ m_deadKeyState = 0; m_shiftPressed = false; m_controlPressed = false; @@ -211,14 +218,14 @@ void OSXKeyState::init() { m_capsPressed = false; // build virtual key map - for (size_t i = 0; i < sizeof(s_controlKeys) / sizeof(s_controlKeys[0]); - ++i) { + for (size_t i = 0; i < sizeof(s_controlKeys) / sizeof(s_controlKeys[0]); ++i) { m_virtualKeyMap[s_controlKeys[i].m_virtualKey] = s_controlKeys[i].m_keyID; } } -KeyModifierMask OSXKeyState::mapModifiersFromOSX(UInt32 mask) const { +KeyModifierMask OSXKeyState::mapModifiersFromOSX(UInt32 mask) const +{ KeyModifierMask outMask = 0; if ((mask & kCGEventFlagMaskShift) != 0) { outMask |= KeyModifierShift; @@ -243,7 +250,8 @@ KeyModifierMask OSXKeyState::mapModifiersFromOSX(UInt32 mask) const { return outMask; } -KeyModifierMask OSXKeyState::mapModifiersToCarbon(UInt32 mask) const { +KeyModifierMask OSXKeyState::mapModifiersToCarbon(UInt32 mask) const +{ KeyModifierMask outMask = 0; if ((mask & kCGEventFlagMaskShift) != 0) { outMask |= shiftKey; @@ -267,8 +275,8 @@ KeyModifierMask OSXKeyState::mapModifiersToCarbon(UInt32 mask) const { return outMask; } -KeyButton OSXKeyState::mapKeyFromEvent( - KeyIDs &ids, KeyModifierMask *maskOut, CGEventRef event) const { +KeyButton OSXKeyState::mapKeyFromEvent(KeyIDs &ids, KeyModifierMask *maskOut, CGEventRef event) const +{ ids.clear(); // map modifier key @@ -300,8 +308,7 @@ KeyButton OSXKeyState::mapKeyFromEvent( } // get keyboard info - AutoTISInputSourceRef currentKeyboardLayout( - TISCopyCurrentKeyboardLayoutInputSource(), CFRelease); + AutoTISInputSourceRef currentKeyboardLayout(TISCopyCurrentKeyboardLayoutInputSource(), CFRelease); if (!currentKeyboardLayout) { return kKeyNone; @@ -312,8 +319,7 @@ KeyButton OSXKeyState::mapKeyFromEvent( // UCKeyTranslate expects old-style Carbon modifiers, so convert. UInt32 modifiers; modifiers = mapModifiersToCarbon(CGEventGetFlags(event)); - static const UInt32 s_commandModifiers = - cmdKey | controlKey | rightControlKey; + static const UInt32 s_commandModifiers = cmdKey | controlKey | rightControlKey; bool isCommand = ((modifiers & s_commandModifiers) != 0); modifiers &= ~s_commandModifiers; @@ -327,18 +333,15 @@ KeyButton OSXKeyState::mapKeyFromEvent( UInt16 action; if (eventKind == kCGEventKeyDown) { action = kUCKeyActionDown; - } else if ( - CGEventGetIntegerValueField(event, kCGKeyboardEventAutorepeat) == 1) { + } else if (CGEventGetIntegerValueField(event, kCGKeyboardEventAutorepeat) == 1) { action = kUCKeyActionAutoKey; } else { return 0; } // translate via uchr resource - CFDataRef ref = (CFDataRef)TISGetInputSourceProperty( - currentKeyboardLayout.get(), kTISPropertyUnicodeKeyLayoutData); - const UCKeyboardLayout *layout = - (const UCKeyboardLayout *)CFDataGetBytePtr(ref); + CFDataRef ref = (CFDataRef)TISGetInputSourceProperty(currentKeyboardLayout.get(), kTISPropertyUnicodeKeyLayoutData); + const UCKeyboardLayout *layout = (const UCKeyboardLayout *)CFDataGetBytePtr(ref); const bool layoutValid = (layout != NULL); if (layoutValid) { @@ -347,9 +350,9 @@ KeyButton OSXKeyState::mapKeyFromEvent( UniChar chars[2]; LOG((CLOG_DEBUG2 "modifiers: %08x", modifiers & 0xffu)); OSStatus status = UCKeyTranslate( - layout, vkCode & 0xffu, action, (modifiers >> 8) & 0xffu, - LMGetKbdType(), 0, &m_deadKeyState, sizeof(chars) / sizeof(chars[0]), - &count, chars); + layout, vkCode & 0xffu, action, (modifiers >> 8) & 0xffu, LMGetKbdType(), 0, &m_deadKeyState, + sizeof(chars) / sizeof(chars[0]), &count, chars + ); // get the characters if (status == 0) { @@ -368,14 +371,19 @@ KeyButton OSXKeyState::mapKeyFromEvent( return 0; } -bool OSXKeyState::fakeCtrlAltDel() { +bool OSXKeyState::fakeCtrlAltDel() +{ // pass keys through unchanged return false; } -bool OSXKeyState::fakeMediaKey(KeyID id) { return fakeNativeMediaKey(id); } +bool OSXKeyState::fakeMediaKey(KeyID id) +{ + return fakeNativeMediaKey(id); +} -CGEventFlags OSXKeyState::getModifierStateAsOSXFlags() const { +CGEventFlags OSXKeyState::getModifierStateAsOSXFlags() const +{ CGEventFlags modifiers = 0; if (m_shiftPressed) { @@ -401,7 +409,8 @@ CGEventFlags OSXKeyState::getModifierStateAsOSXFlags() const { return modifiers; } -KeyModifierMask OSXKeyState::pollActiveModifiers() const { +KeyModifierMask OSXKeyState::pollActiveModifiers() const +{ // falsely assumed that the mask returned by GetCurrentKeyModifiers() // was the same as a CGEventFlags (which is what mapModifiersFromOSX // expects). patch by Marc @@ -431,11 +440,10 @@ KeyModifierMask OSXKeyState::pollActiveModifiers() const { return outMask; } -SInt32 OSXKeyState::pollActiveGroup() const { - AutoTISInputSourceRef keyboardLayout( - TISCopyCurrentKeyboardLayoutInputSource(), CFRelease); - CFDataRef id = (CFDataRef)TISGetInputSourceProperty( - keyboardLayout.get(), kTISPropertyInputSourceID); +SInt32 OSXKeyState::pollActiveGroup() const +{ + AutoTISInputSourceRef keyboardLayout(TISCopyCurrentKeyboardLayoutInputSource(), CFRelease); + CFDataRef id = (CFDataRef)TISGetInputSourceProperty(keyboardLayout.get(), kTISPropertyInputSourceID); GroupMap::const_iterator i = m_groupMap.find(id); if (i != m_groupMap.end()) { @@ -447,7 +455,8 @@ SInt32 OSXKeyState::pollActiveGroup() const { return 0; } -void OSXKeyState::pollPressedKeys(KeyButtonSet &pressedKeys) const { +void OSXKeyState::pollPressedKeys(KeyButtonSet &pressedKeys) const +{ ::KeyMap km; GetKeys(km); const UInt8 *m = reinterpret_cast(km); @@ -460,17 +469,16 @@ void OSXKeyState::pollPressedKeys(KeyButtonSet &pressedKeys) const { } } -void OSXKeyState::getKeyMap(deskflow::KeyMap &keyMap) { +void OSXKeyState::getKeyMap(deskflow::KeyMap &keyMap) +{ // update keyboard groups SInt32 numGroups{0}; if (getGroups(m_groups)) { m_groupMap.clear(); numGroups = CFArrayGetCount(m_groups.get()); for (SInt32 g = 0; g < numGroups; ++g) { - TISInputSourceRef keyboardLayout = - (TISInputSourceRef)CFArrayGetValueAtIndex(m_groups.get(), g); - CFDataRef id = (CFDataRef)TISGetInputSourceProperty( - keyboardLayout, kTISPropertyInputSourceID); + TISInputSourceRef keyboardLayout = (TISInputSourceRef)CFArrayGetValueAtIndex(m_groups.get(), g); + CFDataRef id = (CFDataRef)TISGetInputSourceProperty(keyboardLayout, kTISPropertyInputSourceID); m_groupMap[id] = g; } } @@ -485,10 +493,8 @@ void OSXKeyState::getKeyMap(deskflow::KeyMap &keyMap) { // add regular keys // try uchr resource first - TISInputSourceRef keyboardLayout = - (TISInputSourceRef)CFArrayGetValueAtIndex(m_groups.get(), g); - CFDataRef resourceRef = (CFDataRef)TISGetInputSourceProperty( - keyboardLayout, kTISPropertyUnicodeKeyLayoutData); + TISInputSourceRef keyboardLayout = (TISInputSourceRef)CFArrayGetValueAtIndex(m_groups.get(), g); + CFDataRef resourceRef = (CFDataRef)TISGetInputSourceProperty(keyboardLayout, kTISPropertyUnicodeKeyLayoutData); layoutValid = resourceRef != NULL; if (layoutValid) @@ -507,7 +513,8 @@ void OSXKeyState::getKeyMap(deskflow::KeyMap &keyMap) { } } -CGEventFlags OSXKeyState::getDeviceDependedFlags() const { +CGEventFlags OSXKeyState::getDeviceDependedFlags() const +{ CGEventFlags modifiers = 0; if (m_shiftPressed) { @@ -529,7 +536,8 @@ CGEventFlags OSXKeyState::getDeviceDependedFlags() const { return modifiers; } -CGEventFlags OSXKeyState::getKeyboardEventFlags() const { +CGEventFlags OSXKeyState::getKeyboardEventFlags() const +{ // set the event flags for special keys // http://tinyurl.com/pxl742y CGEventFlags modifiers = getModifierStateAsOSXFlags(); @@ -541,7 +549,8 @@ CGEventFlags OSXKeyState::getKeyboardEventFlags() const { return modifiers; } -void OSXKeyState::setKeyboardModifiers(CGKeyCode virtualKey, bool keyDown) { +void OSXKeyState::setKeyboardModifiers(CGKeyCode virtualKey, bool keyDown) +{ switch (virtualKey) { case s_shiftVK: m_shiftPressed = keyDown; @@ -564,7 +573,8 @@ void OSXKeyState::setKeyboardModifiers(CGKeyCode virtualKey, bool keyDown) { } } -kern_return_t OSXKeyState::postHIDVirtualKey(UInt8 virtualKey, bool postDown) { +kern_return_t OSXKeyState::postHIDVirtualKey(UInt8 virtualKey, bool postDown) +{ NXEventData event; bzero(&event, sizeof(NXEventData)); auto driver = getEventDriver(); @@ -572,21 +582,20 @@ kern_return_t OSXKeyState::postHIDVirtualKey(UInt8 virtualKey, bool postDown) { if (driver) { if (isModifier(virtualKey)) { - result = IOHIDPostEvent( - driver, NX_FLAGSCHANGED, {0, 0}, &event, kNXEventDataVersion, - getKeyboardEventFlags(), true); + result = + IOHIDPostEvent(driver, NX_FLAGSCHANGED, {0, 0}, &event, kNXEventDataVersion, getKeyboardEventFlags(), true); } else { event.key.keyCode = virtualKey; const auto eventType = postDown ? NX_KEYDOWN : NX_KEYUP; - result = IOHIDPostEvent( - driver, eventType, {0, 0}, &event, kNXEventDataVersion, 0, false); + result = IOHIDPostEvent(driver, eventType, {0, 0}, &event, kNXEventDataVersion, 0, false); } } return result; } -void OSXKeyState::postKeyboardKey(CGKeyCode virtualKey, bool keyDown) { +void OSXKeyState::postKeyboardKey(CGKeyCode virtualKey, bool keyDown) +{ CGEventRef event = CGEventCreateKeyboardEvent(nullptr, virtualKey, keyDown); if (event) { CGEventSetFlags(event, getKeyboardEventFlags()); @@ -597,7 +606,8 @@ void OSXKeyState::postKeyboardKey(CGKeyCode virtualKey, bool keyDown) { } } -void OSXKeyState::fakeKey(const Keystroke &keystroke) { +void OSXKeyState::fakeKey(const Keystroke &keystroke) +{ switch (keystroke.m_type) { case Keystroke::kButton: { bool keyDown = keystroke.m_data.m_button.m_press; @@ -606,9 +616,9 @@ void OSXKeyState::fakeKey(const Keystroke &keystroke) { CGKeyCode virtualKey = mapKeyButtonToVirtualKey(button); LOG( - (CLOG_DEBUG1 - " button=0x%04x virtualKey=0x%04x keyDown=%s client=0x%04x", - button, virtualKey, keyDown ? "down" : "up", client)); + (CLOG_DEBUG1 " button=0x%04x virtualKey=0x%04x keyDown=%s client=0x%04x", button, virtualKey, + keyDown ? "down" : "up", client) + ); setKeyboardModifiers(virtualKey, keyDown); if (postHIDVirtualKey(virtualKey, keyDown) != KERN_SUCCESS) { @@ -639,12 +649,11 @@ void OSXKeyState::fakeKey(const Keystroke &keystroke) { } } -void OSXKeyState::getKeyMapForSpecialKeys( - deskflow::KeyMap &keyMap, SInt32 group) const { +void OSXKeyState::getKeyMapForSpecialKeys(deskflow::KeyMap &keyMap, SInt32 group) const +{ // special keys are insensitive to modifers and none are dead keys deskflow::KeyMap::KeyItem item; - for (size_t i = 0; i < sizeof(s_controlKeys) / sizeof(s_controlKeys[0]); - ++i) { + for (size_t i = 0; i < sizeof(s_controlKeys) / sizeof(s_controlKeys[0]); ++i) { const KeyEntry &entry = s_controlKeys[i]; item.m_id = entry.m_keyID; item.m_group = group; @@ -669,8 +678,8 @@ void OSXKeyState::getKeyMapForSpecialKeys( // anyway. } -bool OSXKeyState::getKeyMap( - deskflow::KeyMap &keyMap, SInt32 group, const IOSXKeyResource &r) const { +bool OSXKeyState::getKeyMap(deskflow::KeyMap &keyMap, SInt32 group, const IOSXKeyResource &r) const +{ if (!r.isValid()) { return false; } @@ -749,8 +758,7 @@ bool OSXKeyState::getKeyMap( UInt32 sensitive = 0; for (UInt32 k = 0; (1u << k) < r.getNumModifierCombinations(); ++k) { UInt32 bit = (1u << k); - if ((bit << 8) == cmdKey || (bit << 8) == controlKey || - (bit << 8) == rightControlKey) { + if ((bit << 8) == cmdKey || (bit << 8) == controlKey || (bit << 8) == rightControlKey) { continue; } for (UInt32 m = 0; m < r.getNumModifierCombinations(); ++m) { @@ -772,8 +780,7 @@ bool OSXKeyState::getKeyMap( // now add a key entry for each key/required modifier pair. item.m_sensitive = mapModifiersFromOSX(sensitive << 16); - for (std::set::iterator k = required.begin(); k != required.end(); - ++k) { + for (std::set::iterator k = required.begin(); k != required.end(); ++k) { item.m_required = mapModifiersFromOSX(*k << 16); keyMap.addKeyEntry(item); } @@ -784,8 +791,9 @@ bool OSXKeyState::getKeyMap( } bool OSXKeyState::mapDeskflowHotKeyToMac( - KeyID key, KeyModifierMask mask, UInt32 &macVirtualKey, - UInt32 &macModifierMask) const { + KeyID key, KeyModifierMask mask, UInt32 &macVirtualKey, UInt32 &macModifierMask +) const +{ // look up button for key KeyButton button = getButton(key, pollActiveGroup()); if (button == 0 && key != kKeyNone) { @@ -817,59 +825,45 @@ bool OSXKeyState::mapDeskflowHotKeyToMac( return true; } -void OSXKeyState::handleModifierKeys( - void *target, KeyModifierMask oldMask, KeyModifierMask newMask) { +void OSXKeyState::handleModifierKeys(void *target, KeyModifierMask oldMask, KeyModifierMask newMask) +{ // compute changed modifiers KeyModifierMask changed = (oldMask ^ newMask); // synthesize changed modifier keys if ((changed & KeyModifierShift) != 0) { - handleModifierKey( - target, s_shiftVK, kKeyShift_L, (newMask & KeyModifierShift) != 0, - newMask); + handleModifierKey(target, s_shiftVK, kKeyShift_L, (newMask & KeyModifierShift) != 0, newMask); } if ((changed & KeyModifierControl) != 0) { - handleModifierKey( - target, s_controlVK, kKeyControl_L, (newMask & KeyModifierControl) != 0, - newMask); + handleModifierKey(target, s_controlVK, kKeyControl_L, (newMask & KeyModifierControl) != 0, newMask); } if ((changed & KeyModifierAlt) != 0) { - handleModifierKey( - target, s_altVK, kKeyAlt_L, (newMask & KeyModifierAlt) != 0, newMask); + handleModifierKey(target, s_altVK, kKeyAlt_L, (newMask & KeyModifierAlt) != 0, newMask); } if ((changed & KeyModifierSuper) != 0) { - handleModifierKey( - target, s_superVK, kKeySuper_L, (newMask & KeyModifierSuper) != 0, - newMask); + handleModifierKey(target, s_superVK, kKeySuper_L, (newMask & KeyModifierSuper) != 0, newMask); } if ((changed & KeyModifierCapsLock) != 0) { - handleModifierKey( - target, s_capsLockVK, kKeyCapsLock, - (newMask & KeyModifierCapsLock) != 0, newMask); + handleModifierKey(target, s_capsLockVK, kKeyCapsLock, (newMask & KeyModifierCapsLock) != 0, newMask); } if ((changed & KeyModifierNumLock) != 0) { - handleModifierKey( - target, s_numLockVK, kKeyNumLock, (newMask & KeyModifierNumLock) != 0, - newMask); + handleModifierKey(target, s_numLockVK, kKeyNumLock, (newMask & KeyModifierNumLock) != 0, newMask); } } -void OSXKeyState::handleModifierKey( - void *target, UInt32 virtualKey, KeyID id, bool down, - KeyModifierMask newMask) { +void OSXKeyState::handleModifierKey(void *target, UInt32 virtualKey, KeyID id, bool down, KeyModifierMask newMask) +{ KeyButton button = mapVirtualKeyToKeyButton(virtualKey); onKey(button, down, newMask); sendKeyEvent(target, down, false, id, newMask, 0, button); } -bool OSXKeyState::getGroups(AutoCFArray &groups) const { +bool OSXKeyState::getGroups(AutoCFArray &groups) const +{ // get number of layouts CFStringRef keys[] = {kTISPropertyInputSourceCategory}; CFStringRef values[] = {kTISCategoryKeyboardInputSource}; - AutoCFDictionary dict( - CFDictionaryCreate( - NULL, (const void **)keys, (const void **)values, 1, NULL, NULL), - CFRelease); + AutoCFDictionary dict(CFDictionaryCreate(NULL, (const void **)keys, (const void **)values, 1, NULL, NULL), CFRelease); AutoCFArray kbds(TISCreateInputSourceList(dict.get(), false), CFRelease); if (CFArrayGetCount(kbds.get()) > 0) { @@ -882,19 +876,17 @@ bool OSXKeyState::getGroups(AutoCFArray &groups) const { return true; } -void OSXKeyState::setGroup(SInt32 group) { - TISInputSourceRef keyboardLayout = - (TISInputSourceRef)CFArrayGetValueAtIndex(m_groups.get(), group); +void OSXKeyState::setGroup(SInt32 group) +{ + TISInputSourceRef keyboardLayout = (TISInputSourceRef)CFArrayGetValueAtIndex(m_groups.get(), group); if (!keyboardLayout) { LOG((CLOG_WARN "nedeed keyboard layout is null")); return; } - auto canBeSetted = (CFBooleanRef)TISGetInputSourceProperty( - TISCopyCurrentKeyboardInputSource(), - kTISPropertyInputSourceIsEnableCapable); + auto canBeSetted = (CFBooleanRef + )TISGetInputSourceProperty(TISCopyCurrentKeyboardInputSource(), kTISPropertyInputSourceIsEnableCapable); if (!canBeSetted) { - LOG((CLOG_WARN - "nedeed keyboard layout is disabled for programmatically selection")); + LOG((CLOG_WARN "nedeed keyboard layout is disabled for programmatically selection")); return; } @@ -913,13 +905,12 @@ void OSXKeyState::setGroup(SInt32 group) { ARCH->sleep(.01); } -void OSXKeyState::adjustAltGrModifier( - const KeyIDs &ids, KeyModifierMask *mask, bool isCommand) const { +void OSXKeyState::adjustAltGrModifier(const KeyIDs &ids, KeyModifierMask *mask, bool isCommand) const +{ if (!isCommand) { for (KeyIDs::const_iterator i = ids.begin(); i != ids.end(); ++i) { KeyID id = *i; - if (id != kKeyNone && ((id < 0xe000u || id > 0xefffu) || - (id >= kKeyKP_Equal && id <= kKeyKP_9))) { + if (id != kKeyNone && ((id < 0xe000u || id > 0xefffu) || (id >= kKeyKP_Equal && id <= kKeyKP_9))) { *mask |= KeyModifierAltGr; return; } @@ -927,11 +918,13 @@ void OSXKeyState::adjustAltGrModifier( } } -KeyButton OSXKeyState::mapVirtualKeyToKeyButton(UInt32 keyCode) { +KeyButton OSXKeyState::mapVirtualKeyToKeyButton(UInt32 keyCode) +{ // 'A' maps to 0 so shift every id return static_cast(keyCode + KeyButtonOffset); } -UInt32 OSXKeyState::mapKeyButtonToVirtualKey(KeyButton keyButton) { +UInt32 OSXKeyState::mapKeyButtonToVirtualKey(KeyButton keyButton) +{ return static_cast(keyButton - KeyButtonOffset); } diff --git a/src/lib/platform/OSXKeyState.h b/src/lib/platform/OSXKeyState.h index 28f25df31..25251a148 100644 --- a/src/lib/platform/OSXKeyState.h +++ b/src/lib/platform/OSXKeyState.h @@ -32,15 +32,13 @@ class IOSXKeyResource; /*! A key state for OS X. */ -class OSXKeyState : public KeyState { +class OSXKeyState : public KeyState +{ public: typedef std::vector KeyIDs; - OSXKeyState( - IEventQueue *events, std::vector layouts, bool isLangSyncEnabled); - OSXKeyState( - IEventQueue *events, deskflow::KeyMap &keyMap, - std::vector layouts, bool isLangSyncEnabled); + OSXKeyState(IEventQueue *events, std::vector layouts, bool isLangSyncEnabled); + OSXKeyState(IEventQueue *events, deskflow::KeyMap &keyMap, std::vector layouts, bool isLangSyncEnabled); virtual ~OSXKeyState(); //! @name modifiers @@ -51,8 +49,7 @@ public: Determines which modifier keys have changed and updates the modifier state and sends key events as appropriate. */ - void handleModifierKeys( - void *target, KeyModifierMask oldMask, KeyModifierMask newMask); + void handleModifierKeys(void *target, KeyModifierMask oldMask, KeyModifierMask newMask); //@} //! @name accessors @@ -79,17 +76,14 @@ public: that was pressed or released, or 0 if the button doesn't map to a known KeyID. */ - KeyButton mapKeyFromEvent( - KeyIDs &ids, KeyModifierMask *maskOut, CGEventRef event) const; + KeyButton mapKeyFromEvent(KeyIDs &ids, KeyModifierMask *maskOut, CGEventRef event) const; //! Map key and mask to native values /*! Calculates mac virtual key and mask for a key \p key and modifiers \p mask. Returns \c true if the key can be mapped, \c false otherwise. */ - bool mapDeskflowHotKeyToMac( - KeyID key, KeyModifierMask mask, UInt32 &macVirtualKey, - UInt32 &macModifierMask) const; + bool mapDeskflowHotKeyToMac(KeyID key, KeyModifierMask mask, UInt32 &macVirtualKey, UInt32 &macModifierMask) const; //@} @@ -114,8 +108,7 @@ private: void getKeyMapForSpecialKeys(deskflow::KeyMap &keyMap, SInt32 group) const; // Convert keyboard resource to a key map - bool getKeyMap( - deskflow::KeyMap &keyMap, SInt32 group, const IOSXKeyResource &r) const; + bool getKeyMap(deskflow::KeyMap &keyMap, SInt32 group, const IOSXKeyResource &r) const; // Get the available keyboard groups bool getGroups(AutoCFArray &) const; @@ -124,9 +117,7 @@ private: void setGroup(SInt32 group); // Send an event for the given modifier key - void handleModifierKey( - void *target, UInt32 virtualKey, KeyID id, bool down, - KeyModifierMask newMask); + void handleModifierKey(void *target, UInt32 virtualKey, KeyID id, bool down, KeyModifierMask newMask); // Checks if any in \p ids is a glyph key and if \p isCommand is false. // If so it adds the AltGr modifier to \p mask. This allows OS X @@ -134,8 +125,7 @@ private: // option is acting as AltGr (i.e. it generates a glyph and there are // no command modifiers active) then we don't send the super modifier // to clients because they'd try to match it as a command modifier. - void adjustAltGrModifier( - const KeyIDs &ids, KeyModifierMask *mask, bool isCommand) const; + void adjustAltGrModifier(const KeyIDs &ids, KeyModifierMask *mask, bool isCommand) const; // Maps an OS X virtual key id to a KeyButton. This simply remaps // the ids so we don't use KeyButton 0. @@ -165,7 +155,10 @@ private: // KeyButton 0 so we offset all OS X physical key ids by this much // when used as a KeyButton and by minus this much to map a KeyButton // to a physical button. - enum { KeyButtonOffset = 1 }; + enum + { + KeyButtonOffset = 1 + }; typedef std::map GroupMap; typedef std::map VirtualKeyMap; diff --git a/src/lib/platform/OSXMediaKeySupport.h b/src/lib/platform/OSXMediaKeySupport.h index d6a699c09..af8ab3439 100644 --- a/src/lib/platform/OSXMediaKeySupport.h +++ b/src/lib/platform/OSXMediaKeySupport.h @@ -23,12 +23,12 @@ #include "deskflow/key_types.h" #if defined(__cplusplus) -extern "C" { +extern "C" +{ #endif -bool fakeNativeMediaKey(KeyID id); -bool isMediaKeyEvent(CGEventRef event); -bool getMediaKeyEventInfo( - CGEventRef event, KeyID *keyId, bool *down, bool *isRepeat); + bool fakeNativeMediaKey(KeyID id); + bool isMediaKeyEvent(CGEventRef event); + bool getMediaKeyEventInfo(CGEventRef event, KeyID *keyId, bool *down, bool *isRepeat); #if defined(__cplusplus) } #endif diff --git a/src/lib/platform/OSXPasteboardPeeker.h b/src/lib/platform/OSXPasteboardPeeker.h index 7c67d4ed0..57a58875a 100644 --- a/src/lib/platform/OSXPasteboardPeeker.h +++ b/src/lib/platform/OSXPasteboardPeeker.h @@ -22,10 +22,11 @@ #import #if defined(__cplusplus) -extern "C" { +extern "C" +{ #endif -CFStringRef getDraggedFileURL(); + CFStringRef getDraggedFileURL(); #if defined(__cplusplus) } diff --git a/src/lib/platform/OSXPowerManager.cpp b/src/lib/platform/OSXPowerManager.cpp index b0e413678..36b46eaca 100644 --- a/src/lib/platform/OSXPowerManager.cpp +++ b/src/lib/platform/OSXPowerManager.cpp @@ -19,16 +19,22 @@ #include "OSXPowerManager.h" #include "base/Log.h" -OSXPowerManager::OSXPowerManager() {} +OSXPowerManager::OSXPowerManager() +{ +} -OSXPowerManager::~OSXPowerManager() { enableSleep(); } +OSXPowerManager::~OSXPowerManager() +{ + enableSleep(); +} -void OSXPowerManager::disableSleep() { +void OSXPowerManager::disableSleep() +{ if (!m_sleepPreventionAssertionID) { CFStringRef reasonForActivity = CFSTR(DESKFLOW_APP_NAME " application"); IOReturn result = IOPMAssertionCreateWithName( - kIOPMAssertPreventUserIdleDisplaySleep, kIOPMAssertionLevelOn, - reasonForActivity, &m_sleepPreventionAssertionID); + kIOPMAssertPreventUserIdleDisplaySleep, kIOPMAssertionLevelOn, reasonForActivity, &m_sleepPreventionAssertionID + ); if (result != kIOReturnSuccess) { m_sleepPreventionAssertionID = 0; LOG((CLOG_ERR "failed to disable system idle sleep")); @@ -36,7 +42,8 @@ void OSXPowerManager::disableSleep() { } } -void OSXPowerManager::enableSleep() { +void OSXPowerManager::enableSleep() +{ if (m_sleepPreventionAssertionID) { IOPMAssertionRelease(m_sleepPreventionAssertionID); } diff --git a/src/lib/platform/OSXPowerManager.h b/src/lib/platform/OSXPowerManager.h index 2190af803..92e10db1a 100644 --- a/src/lib/platform/OSXPowerManager.h +++ b/src/lib/platform/OSXPowerManager.h @@ -20,7 +20,8 @@ #include -class OSXPowerManager { +class OSXPowerManager +{ public: OSXPowerManager(); ~OSXPowerManager(); diff --git a/src/lib/platform/OSXScreen.h b/src/lib/platform/OSXScreen.h index 48c6066fe..90ccfe3a3 100644 --- a/src/lib/platform/OSXScreen.h +++ b/src/lib/platform/OSXScreen.h @@ -34,12 +34,11 @@ #include #include -extern "C" { -typedef int CGSConnectionID; -CGError CGSSetConnectionProperty( - CGSConnectionID cid, CGSConnectionID targetCID, CFStringRef key, - CFTypeRef value); -int _CGSDefaultConnection(); +extern "C" +{ + typedef int CGSConnectionID; + CGError CGSSetConnectionProperty(CGSConnectionID cid, CGSConnectionID targetCID, CFStringRef key, CFTypeRef value); + int _CGSDefaultConnection(); } template class CondVar; @@ -52,22 +51,25 @@ class IEventQueue; class Mutex; //! Implementation of IPlatformScreen for OS X -class OSXScreen : public PlatformScreen { +class OSXScreen : public PlatformScreen +{ public: OSXScreen( IEventQueue *events, bool isPrimary, bool enableLangSync = false, - deskflow::ClientScrollDirection scrollDirection = - deskflow::ClientScrollDirection::SERVER); + deskflow::ClientScrollDirection scrollDirection = deskflow::ClientScrollDirection::SERVER + ); virtual ~OSXScreen(); - IEventQueue *getEvents() const { return m_events; } + IEventQueue *getEvents() const + { + return m_events; + } // IScreen overrides void *getEventTarget() const override; bool getClipboard(ClipboardID id, IClipboard *) const override; - void - getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const override; + void getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const override; void getCursorPos(SInt32 &x, SInt32 &y) const override; // IPrimaryScreen overrides @@ -106,7 +108,10 @@ public: String &getDraggingFilename() override; String getSecureInputApp() const override; - const String &getDropTarget() const override { return m_dropTarget; } + const String &getDropTarget() const override + { + return m_dropTarget; + } void waitForCarbonLoop() const; protected: @@ -117,8 +122,7 @@ protected: private: bool updateScreenShape(); - bool - updateScreenShape(const CGDirectDisplayID, const CGDisplayChangeSummaryFlags); + bool updateScreenShape(const CGDirectDisplayID, const CGDisplayChangeSummaryFlags); void postMouseEvent(CGPoint &) const; // convenience function to send events @@ -170,19 +174,15 @@ private: void handleClipboardCheck(const Event &, void *); // Resolution switch callback - static void displayReconfigurationCallback( - CGDirectDisplayID, CGDisplayChangeSummaryFlags, void *); + static void displayReconfigurationCallback(CGDirectDisplayID, CGDisplayChangeSummaryFlags, void *); // fast user switch callback - static pascal OSStatus userSwitchCallback( - EventHandlerCallRef nextHandler, EventRef theEvent, void *inUserData); + static pascal OSStatus userSwitchCallback(EventHandlerCallRef nextHandler, EventRef theEvent, void *inUserData); // sleep / wakeup support void watchSystemPowerThread(void *); static void testCanceled(CFRunLoopTimerRef timer, void *info); - static void powerChangeCallback( - void *refcon, io_service_t service, natural_t messageType, - void *messageArgument); + static void powerChangeCallback(void *refcon, io_service_t service, natural_t messageType, void *messageArgument); void handlePowerChangeRequest(natural_t messageType, void *messageArgument); void handleConfirmSleep(const Event &event, void *); @@ -193,10 +193,9 @@ private: static bool getGlobalHotKeysEnabled(); // Quartz event tap support - static CGEventRef handleCGInputEvent( - CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon); - static CGEventRef handleCGInputEventSecondary( - CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon); + static CGEventRef handleCGInputEvent(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon); + static CGEventRef + handleCGInputEventSecondary(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon); // convert CFString to char* static char *CFStringRefToUTF8String(CFStringRef aString); @@ -204,7 +203,8 @@ private: void getDropTargetThread(void *); private: - struct HotKeyItem { + struct HotKeyItem + { public: HotKeyItem(UInt32, UInt32); HotKeyItem(EventHotKeyRef, UInt32, UInt32); @@ -219,14 +219,16 @@ private: UInt32 m_mask; }; - enum EMouseButtonState { + enum EMouseButtonState + { kMouseButtonUp = 0, kMouseButtonDragged, kMouseButtonDown, kMouseButtonStateMax }; - class MouseButtonState { + class MouseButtonState + { public: void set(UInt32 button, EMouseButtonState state); bool any(); diff --git a/src/lib/platform/OSXScreenSaver.cpp b/src/lib/platform/OSXScreenSaver.cpp index b2b34558c..22dac106e 100644 --- a/src/lib/platform/OSXScreenSaver.cpp +++ b/src/lib/platform/OSXScreenSaver.cpp @@ -37,7 +37,8 @@ bool isScreenSaverEngine(const ProcessSerialNumber &psn); OSXScreenSaver::OSXScreenSaver(IEventQueue *events, void *eventTarget) : m_eventTarget(eventTarget), m_enabled(true), - m_events(events) { + m_events(events) +{ m_autoReleasePool = screenSaverUtilCreatePool(); m_screenSaverController = screenSaverUtilCreateController(); @@ -48,11 +49,10 @@ OSXScreenSaver::OSXScreenSaver(IEventQueue *events, void *eventTarget) launchEventTypes[1].eventClass = kEventClassApplication; launchEventTypes[1].eventKind = kEventAppTerminated; - EventHandlerUPP launchTerminationEventHandler = - NewEventHandlerUPP(launchTerminationCallback); + EventHandlerUPP launchTerminationEventHandler = NewEventHandlerUPP(launchTerminationCallback); InstallApplicationEventHandler( - launchTerminationEventHandler, 2, launchEventTypes, this, - &m_launchTerminationEventHandlerRef); + launchTerminationEventHandler, 2, launchEventTypes, this, &m_launchTerminationEventHandlerRef + ); DisposeEventHandlerUPP(launchTerminationEventHandler); m_screenSaverPSN.highLongOfPSN = 0; @@ -63,53 +63,57 @@ OSXScreenSaver::OSXScreenSaver(IEventQueue *events, void *eventTarget) } } -OSXScreenSaver::~OSXScreenSaver() { +OSXScreenSaver::~OSXScreenSaver() +{ RemoveEventHandler(m_launchTerminationEventHandlerRef); // screenSaverUtilReleaseController(m_screenSaverController); screenSaverUtilReleasePool(m_autoReleasePool); } -void OSXScreenSaver::enable() { +void OSXScreenSaver::enable() +{ m_enabled = true; screenSaverUtilEnable(m_screenSaverController); } -void OSXScreenSaver::disable() { +void OSXScreenSaver::disable() +{ m_enabled = false; screenSaverUtilDisable(m_screenSaverController); } -void OSXScreenSaver::activate() { +void OSXScreenSaver::activate() +{ screenSaverUtilActivate(m_screenSaverController); } -void OSXScreenSaver::deactivate() { +void OSXScreenSaver::deactivate() +{ screenSaverUtilDeactivate(m_screenSaverController, m_enabled); } -bool OSXScreenSaver::isActive() const { +bool OSXScreenSaver::isActive() const +{ return (screenSaverUtilIsActive(m_screenSaverController) != 0); } -void OSXScreenSaver::processLaunched(ProcessSerialNumber psn) { +void OSXScreenSaver::processLaunched(ProcessSerialNumber psn) +{ if (isScreenSaverEngine(psn)) { m_screenSaverPSN = psn; LOG((CLOG_DEBUG1 "screen saver engine launched, enabled=%d", m_enabled)); if (m_enabled) { - m_events->addEvent(Event( - m_events->forIPrimaryScreen().screensaverActivated(), m_eventTarget)); + m_events->addEvent(Event(m_events->forIPrimaryScreen().screensaverActivated(), m_eventTarget)); } } } -void OSXScreenSaver::processTerminated(ProcessSerialNumber psn) { - if (m_screenSaverPSN.highLongOfPSN == psn.highLongOfPSN && - m_screenSaverPSN.lowLongOfPSN == psn.lowLongOfPSN) { +void OSXScreenSaver::processTerminated(ProcessSerialNumber psn) +{ + if (m_screenSaverPSN.highLongOfPSN == psn.highLongOfPSN && m_screenSaverPSN.lowLongOfPSN == psn.lowLongOfPSN) { LOG((CLOG_DEBUG1 "screen saver engine terminated, enabled=%d", m_enabled)); if (m_enabled) { - m_events->addEvent(Event( - m_events->forIPrimaryScreen().screensaverDeactivated(), - m_eventTarget)); + m_events->addEvent(Event(m_events->forIPrimaryScreen().screensaverDeactivated(), m_eventTarget)); } m_screenSaverPSN.highLongOfPSN = 0; @@ -117,19 +121,19 @@ void OSXScreenSaver::processTerminated(ProcessSerialNumber psn) { } } -pascal OSStatus OSXScreenSaver::launchTerminationCallback( - EventHandlerCallRef nextHandler, EventRef theEvent, void *userData) { +pascal OSStatus +OSXScreenSaver::launchTerminationCallback(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData) +{ OSStatus result; ProcessSerialNumber psn; EventParamType actualType; ByteCount actualSize; result = GetEventParameter( - theEvent, kEventParamProcessID, typeProcessSerialNumber, &actualType, - sizeof(psn), &actualSize, &psn); + theEvent, kEventParamProcessID, typeProcessSerialNumber, &actualType, sizeof(psn), &actualSize, &psn + ); - if ((result == noErr) && (actualSize > 0) && - (actualType == typeProcessSerialNumber)) { + if ((result == noErr) && (actualSize > 0) && (actualType == typeProcessSerialNumber)) { OSXScreenSaver *screenSaver = (OSXScreenSaver *)userData; UInt32 eventKind = GetEventKind(theEvent); if (eventKind == kEventAppLaunched) { @@ -143,7 +147,8 @@ pascal OSStatus OSXScreenSaver::launchTerminationCallback( #pragma GCC diagnostic ignored "-Wdeprecated-declarations" -void getProcessSerialNumber(const char *name, ProcessSerialNumber &psn) { +void getProcessSerialNumber(const char *name, ProcessSerialNumber &psn) +{ ProcessInfoRec procInfo; Str31 procName; // pascal string. first byte holds length. memset(&procInfo, 0, sizeof(procInfo)); @@ -166,7 +171,8 @@ void getProcessSerialNumber(const char *name, ProcessSerialNumber &psn) { } } -bool isScreenSaverEngine(const ProcessSerialNumber &psn) { +bool isScreenSaverEngine(const ProcessSerialNumber &psn) +{ CFStringRef processName; OSStatus err = CopyProcessName(&psn, &processName); bool result = (err == 0 && CFEqual(CFSTR("ScreenSaverEngine"), processName)); diff --git a/src/lib/platform/OSXScreenSaver.h b/src/lib/platform/OSXScreenSaver.h index 803d0e2d4..207620b9e 100644 --- a/src/lib/platform/OSXScreenSaver.h +++ b/src/lib/platform/OSXScreenSaver.h @@ -25,7 +25,8 @@ class IEventQueue; //! OSX screen saver implementation -class OSXScreenSaver : public IScreenSaver { +class OSXScreenSaver : public IScreenSaver +{ public: OSXScreenSaver(IEventQueue *events, void *eventTarget); virtual ~OSXScreenSaver(); @@ -41,8 +42,7 @@ private: void processLaunched(ProcessSerialNumber psn); void processTerminated(ProcessSerialNumber psn); - static pascal OSStatus launchTerminationCallback( - EventHandlerCallRef nextHandler, EventRef theEvent, void *userData); + static pascal OSStatus launchTerminationCallback(EventHandlerCallRef nextHandler, EventRef theEvent, void *userData); private: // the target for the events we generate diff --git a/src/lib/platform/OSXScreenSaverUtil.h b/src/lib/platform/OSXScreenSaverUtil.h index d842b53d5..65076fc1f 100644 --- a/src/lib/platform/OSXScreenSaverUtil.h +++ b/src/lib/platform/OSXScreenSaverUtil.h @@ -21,19 +21,20 @@ #include "common/common.h" #if defined(__cplusplus) -extern "C" { +extern "C" +{ #endif -void *screenSaverUtilCreatePool(); -void screenSaverUtilReleasePool(void *); + void *screenSaverUtilCreatePool(); + void screenSaverUtilReleasePool(void *); -void *screenSaverUtilCreateController(); -void screenSaverUtilReleaseController(void *); -void screenSaverUtilEnable(void *); -void screenSaverUtilDisable(void *); -void screenSaverUtilActivate(void *); -void screenSaverUtilDeactivate(void *, int isEnabled); -int screenSaverUtilIsActive(void *); + void *screenSaverUtilCreateController(); + void screenSaverUtilReleaseController(void *); + void screenSaverUtilEnable(void *); + void screenSaverUtilDisable(void *); + void screenSaverUtilActivate(void *); + void screenSaverUtilDeactivate(void *, int isEnabled); + int screenSaverUtilIsActive(void *); #if defined(__cplusplus) } diff --git a/src/lib/platform/OSXUchrKeyResource.cpp b/src/lib/platform/OSXUchrKeyResource.cpp index 94297b07e..247e84d70 100644 --- a/src/lib/platform/OSXUchrKeyResource.cpp +++ b/src/lib/platform/OSXUchrKeyResource.cpp @@ -23,13 +23,13 @@ // OSXUchrKeyResource // -OSXUchrKeyResource::OSXUchrKeyResource( - const void *resource, UInt32 keyboardType) +OSXUchrKeyResource::OSXUchrKeyResource(const void *resource, UInt32 keyboardType) : m_m(NULL), m_cti(NULL), m_sdi(NULL), m_sri(NULL), - m_st(NULL) { + m_st(NULL) +{ m_resource = static_cast(resource); if (m_resource == NULL) { return; @@ -56,19 +56,14 @@ OSXUchrKeyResource::OSXUchrKeyResource( // get tables for keyboard type const UInt8 *const base = reinterpret_cast(m_resource); - m_m = reinterpret_cast( - base + th->keyModifiersToTableNumOffset); - m_cti = reinterpret_cast( - base + th->keyToCharTableIndexOffset); - m_sdi = reinterpret_cast( - base + th->keySequenceDataIndexOffset); + m_m = reinterpret_cast(base + th->keyModifiersToTableNumOffset); + m_cti = reinterpret_cast(base + th->keyToCharTableIndexOffset); + m_sdi = reinterpret_cast(base + th->keySequenceDataIndexOffset); if (th->keyStateRecordsIndexOffset != 0) { - m_sri = reinterpret_cast( - base + th->keyStateRecordsIndexOffset); + m_sri = reinterpret_cast(base + th->keyStateRecordsIndexOffset); } if (th->keyStateTerminatorsOffset != 0) { - m_st = reinterpret_cast( - base + th->keyStateTerminatorsOffset); + m_st = reinterpret_cast(base + th->keyStateTerminatorsOffset); } // find the space key, but only if it can combine with dead keys. @@ -79,8 +74,7 @@ OSXUchrKeyResource::OSXUchrKeyResource( for (UInt32 button = 0, n = getNumButtons(); button < n; ++button) { KeyID id = getKey(table, button); if (id == 0x20) { - UCKeyOutput c = reinterpret_cast( - base + m_cti->keyToCharTableOffsets[table])[button]; + UCKeyOutput c = reinterpret_cast(base + m_cti->keyToCharTableOffsets[table])[button]; if ((c & kUCKeyOutputTestForIndexMask) == kUCKeyOutputStateIndexMask) { m_spaceOutput = (c & kUCKeyOutputGetIndexMask); break; @@ -89,22 +83,29 @@ OSXUchrKeyResource::OSXUchrKeyResource( } } -bool OSXUchrKeyResource::isValid() const { return (m_m != NULL); } +bool OSXUchrKeyResource::isValid() const +{ + return (m_m != NULL); +} -UInt32 OSXUchrKeyResource::getNumModifierCombinations() const { +UInt32 OSXUchrKeyResource::getNumModifierCombinations() const +{ // only 32 (not 256) because the righthanded modifier bits are ignored return 32; } -UInt32 OSXUchrKeyResource::getNumTables() const { +UInt32 OSXUchrKeyResource::getNumTables() const +{ return m_cti->keyToCharTableCount; } -UInt32 OSXUchrKeyResource::getNumButtons() const { +UInt32 OSXUchrKeyResource::getNumButtons() const +{ return m_cti->keyToCharTableSize; } -UInt32 OSXUchrKeyResource::getTableForModifier(UInt32 mask) const { +UInt32 OSXUchrKeyResource::getTableForModifier(UInt32 mask) const +{ if (mask >= m_m->modifiersCount) { return m_m->defaultTableNum; } else { @@ -112,13 +113,13 @@ UInt32 OSXUchrKeyResource::getTableForModifier(UInt32 mask) const { } } -KeyID OSXUchrKeyResource::getKey(UInt32 table, UInt32 button) const { +KeyID OSXUchrKeyResource::getKey(UInt32 table, UInt32 button) const +{ assert(table < getNumTables()); assert(button < getNumButtons()); const UInt8 *const base = reinterpret_cast(m_resource); - const UCKeyOutput *cPtr = reinterpret_cast( - base + m_cti->keyToCharTableOffsets[table]); + const UCKeyOutput *cPtr = reinterpret_cast(base + m_cti->keyToCharTableOffsets[table]); const UCKeyOutput c = cPtr[button]; @@ -146,7 +147,8 @@ KeyID OSXUchrKeyResource::getKey(UInt32 table, UInt32 button) const { return keys.front(); } -bool OSXUchrKeyResource::getDeadKey(KeySequence &keys, UInt16 index) const { +bool OSXUchrKeyResource::getDeadKey(KeySequence &keys, UInt16 index) const +{ if (m_sri == NULL || index >= m_sri->keyStateRecordCount) { // XXX -- should we be using some other fallback? return false; @@ -186,13 +188,11 @@ bool OSXUchrKeyResource::getDeadKey(KeySequence &keys, UInt16 index) const { return true; } -bool OSXUchrKeyResource::getKeyRecord( - KeySequence &keys, UInt16 index, UInt16 &state) const { +bool OSXUchrKeyResource::getKeyRecord(KeySequence &keys, UInt16 index, UInt16 &state) const +{ const UInt8 *const base = reinterpret_cast(m_resource); - const UCKeyStateRecord *sr = reinterpret_cast( - base + m_sri->keyStateRecordOffsets[index]); - const UCKeyStateEntryTerminal *kset = - reinterpret_cast(sr->stateEntryData); + const UCKeyStateRecord *sr = reinterpret_cast(base + m_sri->keyStateRecordOffsets[index]); + const UCKeyStateEntryTerminal *kset = reinterpret_cast(sr->stateEntryData); UInt16 nextState = 0; bool found = false; @@ -246,12 +246,12 @@ bool OSXUchrKeyResource::getKeyRecord( return true; } -bool OSXUchrKeyResource::addSequence(KeySequence &keys, UCKeyCharSeq c) const { +bool OSXUchrKeyResource::addSequence(KeySequence &keys, UCKeyCharSeq c) const +{ if ((c & kUCKeyOutputTestForIndexMask) == kUCKeyOutputSequenceIndexMask) { UInt16 index = (c & kUCKeyOutputGetIndexMask); if (index < m_sdi->charSequenceCount && - m_sdi->charSequenceOffsets[index] != - m_sdi->charSequenceOffsets[index + 1]) { + m_sdi->charSequenceOffsets[index] != m_sdi->charSequenceOffsets[index + 1]) { // XXX -- sequences not supported yet return false; } diff --git a/src/lib/platform/OSXUchrKeyResource.h b/src/lib/platform/OSXUchrKeyResource.h index 01c5aeac0..487ef584d 100644 --- a/src/lib/platform/OSXUchrKeyResource.h +++ b/src/lib/platform/OSXUchrKeyResource.h @@ -24,7 +24,8 @@ typedef TISInputSourceRef KeyLayout; -class OSXUchrKeyResource : public IOSXKeyResource { +class OSXUchrKeyResource : public IOSXKeyResource +{ public: OSXUchrKeyResource(const void *, UInt32 keyboardType); diff --git a/src/lib/platform/PortalInputCapture.cpp b/src/lib/platform/PortalInputCapture.cpp index ae664143f..3101ac128 100644 --- a/src/lib/platform/PortalInputCapture.cpp +++ b/src/lib/platform/PortalInputCapture.cpp @@ -30,7 +30,8 @@ namespace deskflow { -enum signals { +enum signals +{ SESSION_CLOSED, DISABLED, ACTIVATED, @@ -43,20 +44,20 @@ PortalInputCapture::PortalInputCapture(EiScreen *screen, IEventQueue *events) : screen_(screen), events_(events), portal_(xdp_portal_new()), - signals_(_N_SIGNALS) { + signals_(_N_SIGNALS) +{ glib_main_loop_ = g_main_loop_new(nullptr, true); - glib_thread_ = new Thread(new TMethodJob( - this, &PortalInputCapture::glib_thread)); + glib_thread_ = new Thread(new TMethodJob(this, &PortalInputCapture::glib_thread)); auto init_capture_cb = [](gpointer data) -> gboolean { - return reinterpret_cast(data) - ->init_input_capture_session(); + return reinterpret_cast(data)->init_input_capture_session(); }; g_idle_add(init_capture_cb, this); } -PortalInputCapture::~PortalInputCapture() { +PortalInputCapture::~PortalInputCapture() +{ if (g_main_loop_is_running(glib_main_loop_)) g_main_loop_quit(glib_main_loop_); @@ -70,10 +71,8 @@ PortalInputCapture::~PortalInputCapture() { } if (session_) { - XdpSession *parent_session = - xdp_input_capture_session_get_session(session_); - g_signal_handler_disconnect( - G_OBJECT(parent_session), signals_[SESSION_CLOSED]); + XdpSession *parent_session = xdp_input_capture_session_get_session(session_); + g_signal_handler_disconnect(G_OBJECT(parent_session), signals_[SESSION_CLOSED]); g_signal_handler_disconnect(session_, signals_[DISABLED]); g_signal_handler_disconnect(session_, signals_[ACTIVATED]); g_signal_handler_disconnect(session_, signals_[DEACTIVATED]); @@ -88,11 +87,13 @@ PortalInputCapture::~PortalInputCapture() { g_object_unref(portal_); } -gboolean PortalInputCapture::timeout_handler() { +gboolean PortalInputCapture::timeout_handler() +{ return true; // keep re-triggering } -int PortalInputCapture::fake_eis_fd() { +int PortalInputCapture::fake_eis_fd() +{ auto path = std::getenv("LIBEI_SOCKET"); if (!path) { @@ -119,7 +120,8 @@ int PortalInputCapture::fake_eis_fd() { return sock; } -void PortalInputCapture::cb_session_closed(XdpSession *session) { +void PortalInputCapture::cb_session_closed(XdpSession *session) +{ LOG_ERR("portal input capture session was closed, exiting"); g_main_loop_quit(glib_main_loop_); events_->addEvent(Event::kQuit); @@ -128,17 +130,14 @@ void PortalInputCapture::cb_session_closed(XdpSession *session) { signals_[SESSION_CLOSED] = 0; } -void PortalInputCapture::cb_init_input_capture_session( - GObject *object, GAsyncResult *res) { +void PortalInputCapture::cb_init_input_capture_session(GObject *object, GAsyncResult *res) +{ LOG_DEBUG("portal input capture session initialized"); g_autoptr(GError) error = nullptr; - auto session = xdp_portal_create_input_capture_session_finish( - XDP_PORTAL(object), res, &error); + auto session = xdp_portal_create_input_capture_session_finish(XDP_PORTAL(object), res, &error); if (!session) { - LOG_ERR( - "failed to initialize input capture session, quitting: %s", - error->message); + LOG_ERR("failed to initialize input capture session, quitting: %s", error->message); g_main_loop_quit(glib_main_loop_); events_->addEvent(Event::kQuit); return; @@ -161,35 +160,27 @@ void PortalInputCapture::cb_init_input_capture_session( } } // Socket ownership is transferred to the EiScreen - events_->addEvent(Event( - events_->forEi().connected(), screen_->getEventTarget(), - EiScreen::EiConnectInfo::alloc(fd))); + events_->addEvent(Event(events_->forEi().connected(), screen_->getEventTarget(), EiScreen::EiConnectInfo::alloc(fd))); // FIXME: the lambda trick doesn't work here for unknown reasons, we need // the static function - signals_[DISABLED] = g_signal_connect( - G_OBJECT(session), "disabled", G_CALLBACK(cb_disabled_cb), this); - signals_[ACTIVATED] = g_signal_connect( - G_OBJECT(session_), "activated", G_CALLBACK(cb_activated_cb), this); - signals_[DEACTIVATED] = g_signal_connect( - G_OBJECT(session_), "deactivated", G_CALLBACK(cb_deactivated_cb), this); - signals_[ZONES_CHANGED] = g_signal_connect( - G_OBJECT(session_), "zones-changed", G_CALLBACK(cb_zones_changed_cb), - this); + signals_[DISABLED] = g_signal_connect(G_OBJECT(session), "disabled", G_CALLBACK(cb_disabled_cb), this); + signals_[ACTIVATED] = g_signal_connect(G_OBJECT(session_), "activated", G_CALLBACK(cb_activated_cb), this); + signals_[DEACTIVATED] = g_signal_connect(G_OBJECT(session_), "deactivated", G_CALLBACK(cb_deactivated_cb), this); + signals_[ZONES_CHANGED] = + g_signal_connect(G_OBJECT(session_), "zones-changed", G_CALLBACK(cb_zones_changed_cb), this); XdpSession *parent_session = xdp_input_capture_session_get_session(session); - signals_[SESSION_CLOSED] = g_signal_connect( - G_OBJECT(parent_session), "closed", G_CALLBACK(cb_session_closed_cb), - this); + signals_[SESSION_CLOSED] = + g_signal_connect(G_OBJECT(parent_session), "closed", G_CALLBACK(cb_session_closed_cb), this); cb_zones_changed(session_, nullptr); } -void PortalInputCapture::cb_set_pointer_barriers( - GObject *object, GAsyncResult *res) { +void PortalInputCapture::cb_set_pointer_barriers(GObject *object, GAsyncResult *res) +{ g_autoptr(GError) error = nullptr; - auto failed_list = xdp_input_capture_session_set_pointer_barriers_finish( - session_, res, &error); + auto failed_list = xdp_input_capture_session_set_pointer_barriers_finish(session_, res, &error); if (failed_list) { auto it = failed_list; while (it) { @@ -200,12 +191,9 @@ void PortalInputCapture::cb_set_pointer_barriers( if (*elem == it->data) { int x1, x2, y1, y2; - g_object_get( - G_OBJECT(*elem), "x1", &x1, "x2", &x2, "y1", &y1, "y2", &y2, - nullptr); + g_object_get(G_OBJECT(*elem), "x1", &x1, "x2", &x2, "y1", &y1, "y2", &y2, nullptr); - LOG_WARN( - "failed to apply barrier %d (%d/%d-%d/%d)", id, x1, y1, x2, y2); + LOG_WARN("failed to apply barrier %d (%d/%d-%d/%d)", id, x1, y1, x2, y2); g_object_unref(*elem); barriers_.erase(elem); break; @@ -219,24 +207,25 @@ void PortalInputCapture::cb_set_pointer_barriers( enable(); } -gboolean PortalInputCapture::init_input_capture_session() { +gboolean PortalInputCapture::init_input_capture_session() +{ LOG_DEBUG("setting up input capture session"); xdp_portal_create_input_capture_session( portal_, nullptr, // parent - static_cast( - XDP_INPUT_CAPABILITY_KEYBOARD | XDP_INPUT_CAPABILITY_POINTER), + static_cast(XDP_INPUT_CAPABILITY_KEYBOARD | XDP_INPUT_CAPABILITY_POINTER), nullptr, // cancellable [](GObject *obj, GAsyncResult *res, gpointer data) { - reinterpret_cast(data) - ->cb_init_input_capture_session(obj, res); + reinterpret_cast(data)->cb_init_input_capture_session(obj, res); }, - this); + this + ); return false; } -void PortalInputCapture::enable() { +void PortalInputCapture::enable() +{ if (!enabled_) { LOG_DEBUG("enabling the portal input capture session"); xdp_input_capture_session_enable(session_); @@ -244,7 +233,8 @@ void PortalInputCapture::enable() { } } -void PortalInputCapture::disable() { +void PortalInputCapture::disable() +{ if (enabled_) { LOG_DEBUG("disabling the portal input capture session"); xdp_input_capture_session_disable(session_); @@ -252,21 +242,22 @@ void PortalInputCapture::disable() { } } -void PortalInputCapture::release() { +void PortalInputCapture::release() +{ LOG_DEBUG("releasing input capture session, id=%d", activation_id_); xdp_input_capture_session_release(session_, activation_id_); is_active_ = false; } -void PortalInputCapture::release(double x, double y) { - LOG_DEBUG( - "releasing input capture session, id=%d x=%.1f y=%.1f", activation_id_, x, - y); +void PortalInputCapture::release(double x, double y) +{ + LOG_DEBUG("releasing input capture session, id=%d x=%.1f y=%.1f", activation_id_, x, y); xdp_input_capture_session_release_at(session_, activation_id_, x, y); is_active_ = false; } -void PortalInputCapture::cb_disabled(XdpInputCaptureSession *session) { +void PortalInputCapture::cb_disabled(XdpInputCaptureSession *session) +{ LOG_DEBUG("portal cb disabled"); if (!enabled_) @@ -286,12 +277,12 @@ void PortalInputCapture::cb_disabled(XdpInputCaptureSession *session) { reinterpret_cast(data)->enable(); return false; }, - this); + this + ); } -void PortalInputCapture::cb_activated( - XdpInputCaptureSession *session, std::uint32_t activation_id, - GVariant *options) { +void PortalInputCapture::cb_activated(XdpInputCaptureSession *session, std::uint32_t activation_id, GVariant *options) +{ LOG_DEBUG("portal cb activated, id=%d", activation_id); if (options) { @@ -308,15 +299,14 @@ void PortalInputCapture::cb_activated( is_active_ = true; } -void PortalInputCapture::cb_deactivated( - XdpInputCaptureSession *session, std::uint32_t activation_id, - GVariant *options) { +void PortalInputCapture::cb_deactivated(XdpInputCaptureSession *session, std::uint32_t activation_id, GVariant *options) +{ LOG_DEBUG("cb deactivated, id=%i", activation_id); is_active_ = false; } -void PortalInputCapture::cb_zones_changed( - XdpInputCaptureSession *session, GVariant *options) { +void PortalInputCapture::cb_zones_changed(XdpInputCaptureSession *session, GVariant *options) +{ for (auto b : barriers_) g_object_unref(b); barriers_.clear(); @@ -325,8 +315,7 @@ void PortalInputCapture::cb_zones_changed( while (zones != nullptr) { guint w, h; gint x, y; - g_object_get( - zones->data, "width", &w, "height", &h, "x", &x, "y", &y, nullptr); + g_object_get(zones->data, "width", &w, "height", &h, "x", &x, "y", &y, nullptr); LOG_DEBUG("input capture zone, %dx%d@%d,%d", w, h, x, y); @@ -343,36 +332,36 @@ void PortalInputCapture::cb_zones_changed( x2 = x + w - 1; y2 = y; LOG_DEBUG("barrier (top) %zd at %d,%d-%d,%d", id, x1, y1, x2, y2); - barriers_.push_back(XDP_INPUT_CAPTURE_POINTER_BARRIER(g_object_new( - XDP_TYPE_INPUT_CAPTURE_POINTER_BARRIER, "id", id, "x1", x1, "y1", y1, - "x2", x2, "y2", y2, nullptr))); + barriers_.push_back(XDP_INPUT_CAPTURE_POINTER_BARRIER( + g_object_new(XDP_TYPE_INPUT_CAPTURE_POINTER_BARRIER, "id", id, "x1", x1, "y1", y1, "x2", x2, "y2", y2, nullptr) + )); id = barriers_.size() + 1; x1 = x + w; y1 = y; x2 = x + w; y2 = y + h - 1; LOG_DEBUG("barrier (right) %zd at %d,%d-%d,%d", id, x1, y1, x2, y2); - barriers_.push_back(XDP_INPUT_CAPTURE_POINTER_BARRIER(g_object_new( - XDP_TYPE_INPUT_CAPTURE_POINTER_BARRIER, "id", id, "x1", x1, "y1", y1, - "x2", x2, "y2", y2, nullptr))); + barriers_.push_back(XDP_INPUT_CAPTURE_POINTER_BARRIER( + g_object_new(XDP_TYPE_INPUT_CAPTURE_POINTER_BARRIER, "id", id, "x1", x1, "y1", y1, "x2", x2, "y2", y2, nullptr) + )); id = barriers_.size() + 1; x1 = x; y1 = y; x2 = x; y2 = y + h - 1; LOG_DEBUG("barrier (left) %zd at %d,%d-%d,%d", id, x1, y1, x2, y2); - barriers_.push_back(XDP_INPUT_CAPTURE_POINTER_BARRIER(g_object_new( - XDP_TYPE_INPUT_CAPTURE_POINTER_BARRIER, "id", id, "x1", x1, "y1", y1, - "x2", x2, "y2", y2, nullptr))); + barriers_.push_back(XDP_INPUT_CAPTURE_POINTER_BARRIER( + g_object_new(XDP_TYPE_INPUT_CAPTURE_POINTER_BARRIER, "id", id, "x1", x1, "y1", y1, "x2", x2, "y2", y2, nullptr) + )); id = barriers_.size() + 1; x1 = x; y1 = y + h; x2 = x + w - 1; y2 = y + h; LOG_DEBUG("barrier (bottom) %zd at %d,%d-%d,%d", id, x1, y1, x2, y2); - barriers_.push_back(XDP_INPUT_CAPTURE_POINTER_BARRIER(g_object_new( - XDP_TYPE_INPUT_CAPTURE_POINTER_BARRIER, "id", id, "x1", x1, "y1", y1, - "x2", x2, "y2", y2, nullptr))); + barriers_.push_back(XDP_INPUT_CAPTURE_POINTER_BARRIER( + g_object_new(XDP_TYPE_INPUT_CAPTURE_POINTER_BARRIER, "id", id, "x1", x1, "y1", y1, "x2", x2, "y2", y2, nullptr) + )); zones = zones->next; } @@ -385,13 +374,14 @@ void PortalInputCapture::cb_zones_changed( session_, list, nullptr, // cancellable [](GObject *obj, GAsyncResult *res, gpointer data) { - reinterpret_cast(data)->cb_set_pointer_barriers( - obj, res); + reinterpret_cast(data)->cb_set_pointer_barriers(obj, res); }, - this); + this + ); } -void PortalInputCapture::glib_thread(void *) { +void PortalInputCapture::glib_thread(void *) +{ auto context = g_main_loop_get_context(glib_main_loop_); LOG_DEBUG("glib thread running"); diff --git a/src/lib/platform/PortalInputCapture.h b/src/lib/platform/PortalInputCapture.h index 3e9301faf..3030cdb50 100644 --- a/src/lib/platform/PortalInputCapture.h +++ b/src/lib/platform/PortalInputCapture.h @@ -32,7 +32,8 @@ namespace deskflow { -class PortalInputCapture { +class PortalInputCapture +{ public: PortalInputCapture(EiScreen *screen, IEventQueue *events); ~PortalInputCapture(); @@ -40,7 +41,10 @@ public: void disable(); void release(); void release(double x, double y); - bool is_active() const { return is_active_; } + bool is_active() const + { + return is_active_; + } private: void glib_thread(void *); @@ -50,37 +54,32 @@ private: void cb_set_pointer_barriers(GObject *object, GAsyncResult *res); void cb_session_closed(XdpSession *session); void cb_disabled(XdpInputCaptureSession *session); - void cb_activated( - XdpInputCaptureSession *session, std::uint32_t activation_id, - GVariant *options); - void cb_deactivated( - XdpInputCaptureSession *session, std::uint32_t activation_id, - GVariant *options); + void cb_activated(XdpInputCaptureSession *session, std::uint32_t activation_id, GVariant *options); + void cb_deactivated(XdpInputCaptureSession *session, std::uint32_t activation_id, GVariant *options); void cb_zones_changed(XdpInputCaptureSession *session, GVariant *options); /// g_signal_connect callback wrapper - static void cb_session_closed_cb(XdpSession *session, gpointer data) { + static void cb_session_closed_cb(XdpSession *session, gpointer data) + { reinterpret_cast(data)->cb_session_closed(session); } - static void cb_disabled_cb(XdpInputCaptureSession *session, gpointer data) { + static void cb_disabled_cb(XdpInputCaptureSession *session, gpointer data) + { reinterpret_cast(data)->cb_disabled(session); } - static void cb_activated_cb( - XdpInputCaptureSession *session, std::uint32_t activation_id, - GVariant *options, gpointer data) { - reinterpret_cast(data)->cb_activated( - session, activation_id, options); + static void + cb_activated_cb(XdpInputCaptureSession *session, std::uint32_t activation_id, GVariant *options, gpointer data) + { + reinterpret_cast(data)->cb_activated(session, activation_id, options); } - static void cb_deactivated_cb( - XdpInputCaptureSession *session, std::uint32_t activation_id, - GVariant *options, gpointer data) { - reinterpret_cast(data)->cb_deactivated( - session, activation_id, options); + static void + cb_deactivated_cb(XdpInputCaptureSession *session, std::uint32_t activation_id, GVariant *options, gpointer data) + { + reinterpret_cast(data)->cb_deactivated(session, activation_id, options); } - static void cb_zones_changed_cb( - XdpInputCaptureSession *session, GVariant *options, gpointer data) { - reinterpret_cast(data)->cb_zones_changed( - session, options); + static void cb_zones_changed_cb(XdpInputCaptureSession *session, GVariant *options, gpointer data) + { + reinterpret_cast(data)->cb_zones_changed(session, options); } int fake_eis_fd(); diff --git a/src/lib/platform/PortalRemoteDesktop.cpp b/src/lib/platform/PortalRemoteDesktop.cpp old mode 100755 new mode 100644 index d178ca87e..4fbca8586 --- a/src/lib/platform/PortalRemoteDesktop.cpp +++ b/src/lib/platform/PortalRemoteDesktop.cpp @@ -28,15 +28,16 @@ namespace deskflow { PortalRemoteDesktop::PortalRemoteDesktop(EiScreen *screen, IEventQueue *events) : screen_(screen), events_(events), - portal_(xdp_portal_new()) { + portal_(xdp_portal_new()) +{ glib_main_loop_ = g_main_loop_new(nullptr, true); - glib_thread_ = new Thread(new TMethodJob( - this, &PortalRemoteDesktop::glib_thread)); + glib_thread_ = new Thread(new TMethodJob(this, &PortalRemoteDesktop::glib_thread)); reconnect(0); } -PortalRemoteDesktop::~PortalRemoteDesktop() { +PortalRemoteDesktop::~PortalRemoteDesktop() +{ if (g_main_loop_is_running(glib_main_loop_)) g_main_loop_quit(glib_main_loop_); @@ -59,14 +60,15 @@ PortalRemoteDesktop::~PortalRemoteDesktop() { free(session_restore_token_); } -gboolean PortalRemoteDesktop::timeout_handler() { +gboolean PortalRemoteDesktop::timeout_handler() +{ return true; // keep re-triggering } -void PortalRemoteDesktop::reconnect(unsigned int timeout) { +void PortalRemoteDesktop::reconnect(unsigned int timeout) +{ auto init_cb = [](gpointer data) -> gboolean { - return reinterpret_cast(data) - ->init_remote_desktop_session(); + return reinterpret_cast(data)->init_remote_desktop_session(); }; if (timeout > 0) @@ -75,12 +77,12 @@ void PortalRemoteDesktop::reconnect(unsigned int timeout) { g_idle_add(init_cb, this); } -void PortalRemoteDesktop::cb_session_closed(XdpSession *session) { +void PortalRemoteDesktop::cb_session_closed(XdpSession *session) +{ LOG_ERR("portal remote desktop session was closed, reconnecting"); g_signal_handler_disconnect(session, session_signal_id_); session_signal_id_ = 0; - events_->addEvent( - Event(events_->forEi().sessionClosed(), screen_->getEventTarget())); + events_->addEvent(Event(events_->forEi().sessionClosed(), screen_->getEventTarget())); // gcc warning "Suspicious usage of 'sizeof(A*)'" can be ignored g_clear_object(&session_); @@ -88,15 +90,13 @@ void PortalRemoteDesktop::cb_session_closed(XdpSession *session) { reconnect(1000); } -void PortalRemoteDesktop::cb_session_started( - GObject *object, GAsyncResult *res) { +void PortalRemoteDesktop::cb_session_started(GObject *object, GAsyncResult *res) +{ g_autoptr(GError) error = nullptr; auto session = XDP_SESSION(object); auto success = xdp_session_start_finish(session, res, &error); if (!success) { - LOG_ERR( - "failed to start portal remote desktop session, quitting: %s", - error->message); + LOG_ERR("failed to start portal remote desktop session, quitting: %s", error->message); g_main_loop_quit(glib_main_loop_); events_->addEvent(Event::kQuit); return; @@ -118,18 +118,15 @@ void PortalRemoteDesktop::cb_session_started( } // Socket ownership is transferred to the EiScreen - events_->addEvent(Event( - events_->forEi().connected(), screen_->getEventTarget(), - EiScreen::EiConnectInfo::alloc(fd))); + events_->addEvent(Event(events_->forEi().connected(), screen_->getEventTarget(), EiScreen::EiConnectInfo::alloc(fd))); } -void PortalRemoteDesktop::cb_init_remote_desktop_session( - GObject *object, GAsyncResult *res) { +void PortalRemoteDesktop::cb_init_remote_desktop_session(GObject *object, GAsyncResult *res) +{ LOG_DEBUG("portal remote desktop session initialized"); g_autoptr(GError) error = nullptr; - auto session = xdp_portal_create_remote_desktop_session_finish( - XDP_PORTAL(object), res, &error); + auto session = xdp_portal_create_remote_desktop_session_finish(XDP_PORTAL(object), res, &error); if (!session) { LOG_ERR("failed to initialize remote desktop session: %s", error->message); // This was the first attempt to connect to the RD portal - quit if that @@ -148,8 +145,7 @@ void PortalRemoteDesktop::cb_init_remote_desktop_session( // FIXME: the lambda trick doesn't work here for unknown reasons, we need // the static function - session_signal_id_ = g_signal_connect( - G_OBJECT(session), "closed", G_CALLBACK(cb_session_closed_cb), this); + session_signal_id_ = g_signal_connect(G_OBJECT(session), "closed", G_CALLBACK(cb_session_closed_cb), this); LOG_DEBUG("portal remote desktop session starting"); xdp_session_start( @@ -157,44 +153,41 @@ void PortalRemoteDesktop::cb_init_remote_desktop_session( nullptr, // parent nullptr, // cancellable [](GObject *obj, GAsyncResult *res, gpointer data) { - reinterpret_cast(data)->cb_session_started( - obj, res); + reinterpret_cast(data)->cb_session_started(obj, res); }, - this); + this + ); } #if !defined(HAVE_LIBPORTAL_CREATE_REMOTE_DESKTOP_SESSION_FULL) static inline void xdp_portal_create_remote_desktop_session_full( - XdpPortal *portal, XdpDeviceType devices, XdpOutputType outputs, - XdpRemoteDesktopFlags flags, XdpCursorMode cursor_mode, - XdpPersistMode _unused1, const char *_unused2, GCancellable *cancellable, - GAsyncReadyCallback callback, gpointer data) { - xdp_portal_create_remote_desktop_session( - portal, devices, outputs, flags, cursor_mode, cancellable, callback, - data); + XdpPortal *portal, XdpDeviceType devices, XdpOutputType outputs, XdpRemoteDesktopFlags flags, + XdpCursorMode cursor_mode, XdpPersistMode _unused1, const char *_unused2, GCancellable *cancellable, + GAsyncReadyCallback callback, gpointer data +) +{ + xdp_portal_create_remote_desktop_session(portal, devices, outputs, flags, cursor_mode, cancellable, callback, data); } #endif -gboolean PortalRemoteDesktop::init_remote_desktop_session() { - LOG_DEBUG( - "setting up remote desktop session with restore token %s", - session_restore_token_); +gboolean PortalRemoteDesktop::init_remote_desktop_session() +{ + LOG_DEBUG("setting up remote desktop session with restore token %s", session_restore_token_); xdp_portal_create_remote_desktop_session_full( - portal_, - static_cast(XDP_DEVICE_POINTER | XDP_DEVICE_KEYBOARD), - XDP_OUTPUT_NONE, XDP_REMOTE_DESKTOP_FLAG_NONE, XDP_CURSOR_MODE_HIDDEN, - XDP_PERSIST_MODE_TRANSIENT, session_restore_token_, + portal_, static_cast(XDP_DEVICE_POINTER | XDP_DEVICE_KEYBOARD), XDP_OUTPUT_NONE, + XDP_REMOTE_DESKTOP_FLAG_NONE, XDP_CURSOR_MODE_HIDDEN, XDP_PERSIST_MODE_TRANSIENT, session_restore_token_, nullptr, // cancellable [](GObject *obj, GAsyncResult *res, gpointer data) { - reinterpret_cast(data) - ->cb_init_remote_desktop_session(obj, res); + reinterpret_cast(data)->cb_init_remote_desktop_session(obj, res); }, - this); + this + ); return false; // don't reschedule } -void PortalRemoteDesktop::glib_thread(void *) { +void PortalRemoteDesktop::glib_thread(void *) +{ auto context = g_main_loop_get_context(glib_main_loop_); while (g_main_loop_is_running(glib_main_loop_)) { diff --git a/src/lib/platform/PortalRemoteDesktop.h b/src/lib/platform/PortalRemoteDesktop.h index 3d314e4af..6dd098727 100644 --- a/src/lib/platform/PortalRemoteDesktop.h +++ b/src/lib/platform/PortalRemoteDesktop.h @@ -34,7 +34,8 @@ namespace deskflow { -class PortalRemoteDesktop { +class PortalRemoteDesktop +{ public: PortalRemoteDesktop(EiScreen *screen, IEventQueue *events); ~PortalRemoteDesktop(); @@ -49,7 +50,8 @@ private: void reconnect(unsigned int timeout = 1000); /// g_signal_connect callback wrapper - static void cb_session_closed_cb(XdpSession *session, gpointer data) { + static void cb_session_closed_cb(XdpSession *session, gpointer data) + { reinterpret_cast(data)->cb_session_closed(session); } diff --git a/src/lib/platform/XWindowsClipboard.cpp b/src/lib/platform/XWindowsClipboard.cpp index 1793988d3..7538a4806 100644 --- a/src/lib/platform/XWindowsClipboard.cpp +++ b/src/lib/platform/XWindowsClipboard.cpp @@ -39,8 +39,7 @@ // XWindowsClipboard // -XWindowsClipboard::XWindowsClipboard( - Display *display, Window window, ClipboardID id) +XWindowsClipboard::XWindowsClipboard(Display *display, Window window, ClipboardID id) : m_display(display), m_window(window), m_id(id), @@ -48,7 +47,8 @@ XWindowsClipboard::XWindowsClipboard( m_time(0), m_owner(false), m_timeOwned(0), - m_timeLost(0) { + m_timeLost(0) +{ // get some atoms m_atomTargets = XInternAtom(m_display, "TARGETS", False); m_atomMultiple = XInternAtom(m_display, "MULTIPLE", False); @@ -60,8 +60,7 @@ XWindowsClipboard::XWindowsClipboard( m_atomINCR = XInternAtom(m_display, "INCR", False); m_atomMotifClipLock = XInternAtom(m_display, "_MOTIF_CLIP_LOCK", False); m_atomMotifClipHeader = XInternAtom(m_display, "_MOTIF_CLIP_HEADER", False); - m_atomMotifClipAccess = - XInternAtom(m_display, "_MOTIF_CLIP_LOCK_ACCESS_VALID", False); + m_atomMotifClipAccess = XInternAtom(m_display, "_MOTIF_CLIP_LOCK_ACCESS_VALID", False); m_atomGDKSelection = XInternAtom(m_display, "GDK_SELECTION", False); // set selection atom based on clipboard id @@ -76,36 +75,29 @@ XWindowsClipboard::XWindowsClipboard( } // add converters, most desired first - m_converters.push_back( - new XWindowsClipboardHTMLConverter(m_display, "text/html")); - m_converters.push_back(new XWindowsClipboardHTMLConverter( - m_display, "application/x-moz-nativehtml")); + m_converters.push_back(new XWindowsClipboardHTMLConverter(m_display, "text/html")); + m_converters.push_back(new XWindowsClipboardHTMLConverter(m_display, "application/x-moz-nativehtml")); m_converters.push_back(new XWindowsClipboardBMPConverter(m_display)); - m_converters.push_back(new XWindowsClipboardUTF8Converter( - m_display, "text/plain;charset=UTF-8", true)); - m_converters.push_back(new XWindowsClipboardUTF8Converter( - m_display, "text/plain;charset=utf-8", true)); - m_converters.push_back( - new XWindowsClipboardUTF8Converter(m_display, "UTF8_STRING")); - m_converters.push_back(new XWindowsClipboardUCS2Converter( - m_display, "text/plain;charset=ISO-10646-UCS-2")); - m_converters.push_back( - new XWindowsClipboardUCS2Converter(m_display, "text/unicode")); - m_converters.push_back( - new XWindowsClipboardTextConverter(m_display, "text/plain")); - m_converters.push_back( - new XWindowsClipboardTextConverter(m_display, "STRING")); + m_converters.push_back(new XWindowsClipboardUTF8Converter(m_display, "text/plain;charset=UTF-8", true)); + m_converters.push_back(new XWindowsClipboardUTF8Converter(m_display, "text/plain;charset=utf-8", true)); + m_converters.push_back(new XWindowsClipboardUTF8Converter(m_display, "UTF8_STRING")); + m_converters.push_back(new XWindowsClipboardUCS2Converter(m_display, "text/plain;charset=ISO-10646-UCS-2")); + m_converters.push_back(new XWindowsClipboardUCS2Converter(m_display, "text/unicode")); + m_converters.push_back(new XWindowsClipboardTextConverter(m_display, "text/plain")); + m_converters.push_back(new XWindowsClipboardTextConverter(m_display, "STRING")); // we have no data clearCache(); } -XWindowsClipboard::~XWindowsClipboard() { +XWindowsClipboard::~XWindowsClipboard() +{ clearReplies(); clearConverters(); } -void XWindowsClipboard::lost(Time time) { +void XWindowsClipboard::lost(Time time) +{ LOG((CLOG_DEBUG "lost clipboard %d ownership at %d", m_id, time)); if (m_owner) { m_owner = false; @@ -114,17 +106,17 @@ void XWindowsClipboard::lost(Time time) { } } -void XWindowsClipboard::addRequest( - Window owner, Window requestor, Atom target, ::Time time, Atom property) { +void XWindowsClipboard::addRequest(Window owner, Window requestor, Atom target, ::Time time, Atom property) +{ // must be for our window and we must have owned the selection // at the given time. bool success = false; if (owner == m_window) { LOG( - (CLOG_DEBUG1 - "request for clipboard %d, target %s by 0x%08x (property=%s)", - m_selection, XWindowsUtil::atomToString(m_display, target).c_str(), - requestor, XWindowsUtil::atomToString(m_display, property).c_str())); + (CLOG_DEBUG1 "request for clipboard %d, target %s by 0x%08x (property=%s)", m_selection, + XWindowsUtil::atomToString(m_display, target).c_str(), requestor, + XWindowsUtil::atomToString(m_display, property).c_str()) + ); if (wasOwnedAtTime(time)) { if (target == m_atomMultiple && property != None) { // add a multiple request. property may not be None @@ -151,8 +143,8 @@ void XWindowsClipboard::addRequest( pushReplies(); } -bool XWindowsClipboard::addSimpleRequest( - Window requestor, Atom target, ::Time time, Atom property) { +bool XWindowsClipboard::addSimpleRequest(Window requestor, Atom target, ::Time time, Atom property) +{ // obsolete requestors may supply a None property. in // that case we use the target as the property to store // the conversion. @@ -188,8 +180,7 @@ bool XWindowsClipboard::addSimpleRequest( if (type != None) { // success LOG((CLOG_DEBUG1 "success")); - insertReply( - new Reply(requestor, target, time, property, data, type, format)); + insertReply(new Reply(requestor, target, time, property, data, type, format)); return true; } else { // failure @@ -199,22 +190,22 @@ bool XWindowsClipboard::addSimpleRequest( } } -bool XWindowsClipboard::processRequest( - Window requestor, ::Time /*time*/, Atom property) { +bool XWindowsClipboard::processRequest(Window requestor, ::Time /*time*/, Atom property) +{ ReplyMap::iterator index = m_replies.find(requestor); if (index == m_replies.end()) { // unknown requestor window return false; } LOG( - (CLOG_DEBUG1 "received property %s delete from 0x08%x", - XWindowsUtil::atomToString(m_display, property).c_str(), requestor)); + (CLOG_DEBUG1 "received property %s delete from 0x08%x", XWindowsUtil::atomToString(m_display, property).c_str(), + requestor) + ); // find the property in the known requests. it should be the // first property but we'll check 'em all if we have to. ReplyList &replies = index->second; - for (ReplyList::iterator index2 = replies.begin(); index2 != replies.end(); - ++index2) { + for (ReplyList::iterator index2 = replies.begin(); index2 != replies.end(); ++index2) { Reply *reply = *index2; if (reply->m_replied && reply->m_property == property) { // if reply is complete then remove it and start the @@ -227,7 +218,8 @@ bool XWindowsClipboard::processRequest( return false; } -bool XWindowsClipboard::destroyRequest(Window requestor) { +bool XWindowsClipboard::destroyRequest(Window requestor) +{ ReplyMap::iterator index = m_replies.find(requestor); if (index == m_replies.end()) { // unknown requestor window @@ -244,11 +236,18 @@ bool XWindowsClipboard::destroyRequest(Window requestor) { return true; } -Window XWindowsClipboard::getWindow() const { return m_window; } +Window XWindowsClipboard::getWindow() const +{ + return m_window; +} -Atom XWindowsClipboard::getSelection() const { return m_selection; } +Atom XWindowsClipboard::getSelection() const +{ + return m_selection; +} -bool XWindowsClipboard::empty() { +bool XWindowsClipboard::empty() +{ assert(m_open); LOG((CLOG_DEBUG "empty clipboard %d", m_id)); @@ -279,13 +278,12 @@ bool XWindowsClipboard::empty() { return true; } -void XWindowsClipboard::add(EFormat format, const String &data) { +void XWindowsClipboard::add(EFormat format, const String &data) +{ assert(m_open); assert(m_owner); - LOG( - (CLOG_DEBUG "add %d bytes to clipboard %d format: %d", data.size(), m_id, - format)); + LOG((CLOG_DEBUG "add %d bytes to clipboard %d format: %d", data.size(), m_id, format)); m_data[format] = data; m_added[format] = true; @@ -293,7 +291,8 @@ void XWindowsClipboard::add(EFormat format, const String &data) { // FIXME -- set motif clipboard item? } -bool XWindowsClipboard::open(Time time) const { +bool XWindowsClipboard::open(Time time) const +{ if (m_open) { LOG((CLOG_DEBUG "failed to open clipboard: already opened")); return false; @@ -329,7 +328,8 @@ bool XWindowsClipboard::open(Time time) const { return true; } -void XWindowsClipboard::close() const { +void XWindowsClipboard::close() const +{ assert(m_open); LOG((CLOG_DEBUG "close clipboard %d", m_id)); @@ -343,47 +343,47 @@ void XWindowsClipboard::close() const { m_open = false; } -IClipboard::Time XWindowsClipboard::getTime() const { +IClipboard::Time XWindowsClipboard::getTime() const +{ checkCache(); return m_timeOwned; } -bool XWindowsClipboard::has(EFormat format) const { +bool XWindowsClipboard::has(EFormat format) const +{ assert(m_open); fillCache(); return m_added[format]; } -String XWindowsClipboard::get(EFormat format) const { +String XWindowsClipboard::get(EFormat format) const +{ assert(m_open); fillCache(); return m_data[format]; } -void XWindowsClipboard::clearConverters() { - for (ConverterList::iterator index = m_converters.begin(); - index != m_converters.end(); ++index) { +void XWindowsClipboard::clearConverters() +{ + for (ConverterList::iterator index = m_converters.begin(); index != m_converters.end(); ++index) { delete *index; } m_converters.clear(); } -IXWindowsClipboardConverter * -XWindowsClipboard::getConverter(Atom target, bool onlyIfNotAdded) const { +IXWindowsClipboardConverter *XWindowsClipboard::getConverter(Atom target, bool onlyIfNotAdded) const +{ IXWindowsClipboardConverter *converter = nullptr; - for (ConverterList::const_iterator index = m_converters.begin(); - index != m_converters.end(); ++index) { + for (ConverterList::const_iterator index = m_converters.begin(); index != m_converters.end(); ++index) { converter = *index; if (converter->getAtom() == target) { break; } } if (converter == nullptr) { - LOG( - (CLOG_DEBUG1 " no converter for target %s", - XWindowsUtil::atomToString(m_display, target).c_str())); + LOG((CLOG_DEBUG1 " no converter for target %s", XWindowsUtil::atomToString(m_display, target).c_str())); return nullptr; } @@ -396,7 +396,8 @@ XWindowsClipboard::getConverter(Atom target, bool onlyIfNotAdded) const { return converter; } -void XWindowsClipboard::checkCache() const { +void XWindowsClipboard::checkCache() const +{ if (!m_checkCache) { return; } @@ -421,11 +422,13 @@ void XWindowsClipboard::checkCache() const { } } -void XWindowsClipboard::clearCache() const { +void XWindowsClipboard::clearCache() const +{ const_cast(this)->doClearCache(); } -void XWindowsClipboard::doClearCache() { +void XWindowsClipboard::doClearCache() +{ m_checkCache = false; m_cached = false; for (SInt32 index = 0; index < kNumFormats; ++index) { @@ -434,7 +437,8 @@ void XWindowsClipboard::doClearCache() { } } -void XWindowsClipboard::fillCache() const { +void XWindowsClipboard::fillCache() const +{ // get the selection data if not already cached checkCache(); if (!m_cached) { @@ -442,7 +446,8 @@ void XWindowsClipboard::fillCache() const { } } -void XWindowsClipboard::doFillCache() { +void XWindowsClipboard::doFillCache() +{ if (m_motif) { motifFillCache(); } else { @@ -453,7 +458,8 @@ void XWindowsClipboard::doFillCache() { m_cacheTime = m_timeOwned; } -void XWindowsClipboard::icccmFillCache() { +void XWindowsClipboard::icccmFillCache() +{ LOG((CLOG_DEBUG "icccm fill clipboard %d", m_id)); // see if we can get the list of available formats from the selection. @@ -463,25 +469,20 @@ void XWindowsClipboard::icccmFillCache() { const Atom atomTargets = m_atomTargets; Atom target; String data; - if (!icccmGetSelection(atomTargets, &target, &data) || - (target != m_atomAtom && target != m_atomTargets)) { + if (!icccmGetSelection(atomTargets, &target, &data) || (target != m_atomAtom && target != m_atomTargets)) { LOG((CLOG_DEBUG1 "selection doesn't support TARGETS")); data = ""; XWindowsUtil::appendAtomData(data, XA_STRING); } XWindowsUtil::convertAtomProperty(data); - auto targets = - static_cast(static_cast(data.data())); + auto targets = static_cast(static_cast(data.data())); const UInt32 numTargets = data.size() / sizeof(Atom); - LOG( - (CLOG_DEBUG " available targets: %s", - XWindowsUtil::atomsToString(m_display, targets, numTargets).c_str())); + LOG((CLOG_DEBUG " available targets: %s", XWindowsUtil::atomsToString(m_display, targets, numTargets).c_str())); // try each converter in order (because they're in order of // preference). - for (ConverterList::const_iterator index = m_converters.begin(); - index != m_converters.end(); ++index) { + for (ConverterList::const_iterator index = m_converters.begin(); index != m_converters.end(); ++index) { IXWindowsClipboardConverter *converter = *index; // skip already handled targets @@ -511,9 +512,7 @@ void XWindowsClipboard::icccmFillCache() { Atom actualTarget; String targetData; if (!icccmGetSelection(target, &actualTarget, &targetData)) { - LOG( - (CLOG_DEBUG1 " no data for target %s", - XWindowsUtil::atomToString(m_display, target).c_str())); + LOG((CLOG_DEBUG1 " no data for target %s", XWindowsUtil::atomToString(m_display, target).c_str())); continue; } @@ -523,41 +522,37 @@ void XWindowsClipboard::icccmFillCache() { m_added[format] = true; LOG( (CLOG_DEBUG "added format %d for target %s (%u %s)", format, - XWindowsUtil::atomToString(m_display, target).c_str(), - targetData.size(), targetData.size() == 1 ? "byte" : "bytes")); + XWindowsUtil::atomToString(m_display, target).c_str(), targetData.size(), + targetData.size() == 1 ? "byte" : "bytes") + ); } } -bool XWindowsClipboard::icccmGetSelection( - Atom target, Atom *actualTarget, String *data) const { +bool XWindowsClipboard::icccmGetSelection(Atom target, Atom *actualTarget, String *data) const +{ assert(actualTarget != nullptr); assert(data != nullptr); // request data conversion if (CICCCMGetClipboard getter(m_window, m_time, m_atomData); - !getter.readClipboard( - m_display, m_selection, target, actualTarget, data)) { - LOG( - (CLOG_DEBUG1 "can't get data for selection target %s", - XWindowsUtil::atomToString(m_display, target).c_str())); + !getter.readClipboard(m_display, m_selection, target, actualTarget, data)) { + LOG((CLOG_DEBUG1 "can't get data for selection target %s", XWindowsUtil::atomToString(m_display, target).c_str())); LOGC(getter.error(), (CLOG_WARN "icccm violation by clipboard owner")); return false; } else if (*actualTarget == None) { - LOG( - (CLOG_DEBUG1 "selection conversion failed for target %s", - XWindowsUtil::atomToString(m_display, target).c_str())); + LOG((CLOG_DEBUG1 "selection conversion failed for target %s", XWindowsUtil::atomToString(m_display, target).c_str()) + ); return false; } return true; } -IClipboard::Time XWindowsClipboard::icccmGetTime() const { +IClipboard::Time XWindowsClipboard::icccmGetTime() const +{ Atom actualTarget; String data; - if (icccmGetSelection(m_atomTimestamp, &actualTarget, &data) && - actualTarget == m_atomInteger) { - Time time = - *static_cast(static_cast(data.data())); + if (icccmGetSelection(m_atomTimestamp, &actualTarget, &data) && actualTarget == m_atomInteger) { + Time time = *static_cast(static_cast(data.data())); LOG((CLOG_DEBUG1 "got ICCCM time %d", time)); return time; } else { @@ -567,7 +562,8 @@ IClipboard::Time XWindowsClipboard::icccmGetTime() const { } } -bool XWindowsClipboard::motifLockClipboard() const { +bool XWindowsClipboard::motifLockClipboard() const +{ // fail if anybody owns the lock (even us, so this is non-recursive) Window lockOwner = XGetSelectionOwner(m_display, m_atomMotifClipLock); if (lockOwner != None) { @@ -591,7 +587,8 @@ bool XWindowsClipboard::motifLockClipboard() const { return true; } -void XWindowsClipboard::motifUnlockClipboard() const { +void XWindowsClipboard::motifUnlockClipboard() const +{ LOG((CLOG_DEBUG1 "unlocked motif clipboard")); // fail if we don't own the lock @@ -605,7 +602,8 @@ void XWindowsClipboard::motifUnlockClipboard() const { XSetSelectionOwner(m_display, m_atomMotifClipLock, None, time); } -bool XWindowsClipboard::motifOwnsClipboard() const { +bool XWindowsClipboard::motifOwnsClipboard() const +{ // get the current selection owner // FIXME -- this can't be right. even if the window is destroyed // Motif will still have a valid clipboard. how can we tell if @@ -620,9 +618,7 @@ bool XWindowsClipboard::motifOwnsClipboard() const { SInt32 format; String data; Window root = RootWindow(m_display, DefaultScreen(m_display)); - if (!XWindowsUtil::getWindowProperty( - m_display, root, m_atomMotifClipHeader, &data, &target, &format, - False)) { + if (!XWindowsUtil::getWindowProperty(m_display, root, m_atomMotifClipHeader, &data, &target, &format, False)) { return false; } @@ -630,8 +626,7 @@ bool XWindowsClipboard::motifOwnsClipboard() const { if (data.size() >= sizeof(MotifClipHeader)) { MotifClipHeader header; std::memcpy(&header, data.data(), sizeof(header)); - if ((header.m_id == MotifClip::Header) && - (static_cast(header.m_selectionOwner) == owner)) { + if ((header.m_id == MotifClip::Header) && (static_cast(header.m_selectionOwner) == owner)) { return true; } } @@ -639,7 +634,8 @@ bool XWindowsClipboard::motifOwnsClipboard() const { return false; } -void XWindowsClipboard::motifFillCache() { +void XWindowsClipboard::motifFillCache() +{ LOG((CLOG_DEBUG "motif fill clipboard %d", m_id)); // get the Motif clipboard header property from the root window @@ -647,9 +643,7 @@ void XWindowsClipboard::motifFillCache() { SInt32 format; String data; Window root = RootWindow(m_display, DefaultScreen(m_display)); - if (!XWindowsUtil::getWindowProperty( - m_display, root, m_atomMotifClipHeader, &data, &target, &format, - False)) { + if (!XWindowsUtil::getWindowProperty(m_display, root, m_atomMotifClipHeader, &data, &target, &format, False)) { return; } @@ -668,8 +662,7 @@ void XWindowsClipboard::motifFillCache() { snprintf(name, buffer_size, "_MOTIF_CLIP_ITEM_%d", header.m_item); Atom atomItem = XInternAtom(m_display, name, False); data = ""; - if (!XWindowsUtil::getWindowProperty( - m_display, root, atomItem, &data, &target, &format, False)) { + if (!XWindowsUtil::getWindowProperty(m_display, root, atomItem, &data, &target, &format, False)) { return; } @@ -678,15 +671,13 @@ void XWindowsClipboard::motifFillCache() { return; } std::memcpy(&item, data.data(), sizeof(item)); - if (item.m_id != MotifClip::Item || - item.m_numFormats - item.m_numDeletedFormats < 1) { + if (item.m_id != MotifClip::Item || item.m_numFormats - item.m_numDeletedFormats < 1) { return; } // format list is after static item structure elements const SInt32 numFormats = item.m_numFormats - item.m_numDeletedFormats; - auto formats = static_cast( - static_cast(item.m_size + data.data())); + auto formats = static_cast(static_cast(item.m_size + data.data())); // get the available formats typedef std::map MotifFormatMap; @@ -696,8 +687,7 @@ void XWindowsClipboard::motifFillCache() { snprintf(name, buffer_size, "_MOTIF_CLIP_ITEM_%d", formats[i]); Atom atomFormat = XInternAtom(m_display, name, False); String data; - if (!XWindowsUtil::getWindowProperty( - m_display, root, atomFormat, &data, &target, &format, False)) { + if (!XWindowsUtil::getWindowProperty(m_display, root, atomFormat, &data, &target, &format, False)) { continue; } @@ -707,8 +697,8 @@ void XWindowsClipboard::motifFillCache() { continue; } std::memcpy(&motifFormat, data.data(), sizeof(motifFormat)); - if (motifFormat.m_id != MotifClip::Format || motifFormat.m_length < 0 || - motifFormat.m_type == None || motifFormat.m_deleted != 0) { + if (motifFormat.m_id != MotifClip::Format || motifFormat.m_length < 0 || motifFormat.m_type == None || + motifFormat.m_deleted != 0) { continue; } @@ -719,8 +709,7 @@ void XWindowsClipboard::motifFillCache() { // try each converter in order (because they're in order of // preference). - for (ConverterList::const_iterator index = m_converters.begin(); - index != m_converters.end(); ++index) { + for (ConverterList::const_iterator index = m_converters.begin(); index != m_converters.end(); ++index) { IXWindowsClipboardConverter *converter = *index; // skip already handled targets @@ -729,8 +718,7 @@ void XWindowsClipboard::motifFillCache() { } // see if atom is in target list - MotifFormatMap::const_iterator index2 = - motifFormats.find(converter->getAtom()); + MotifFormatMap::const_iterator index2 = motifFormats.find(converter->getAtom()); if (index2 == motifFormats.end()) { continue; } @@ -744,9 +732,7 @@ void XWindowsClipboard::motifFillCache() { Atom actualTarget; String targetData; if (!motifGetSelection(&motifFormat, &actualTarget, &targetData)) { - LOG( - (CLOG_DEBUG1 " no data for target %s", - XWindowsUtil::atomToString(m_display, target).c_str())); + LOG((CLOG_DEBUG1 " no data for target %s", XWindowsUtil::atomToString(m_display, target).c_str())); continue; } @@ -754,14 +740,12 @@ void XWindowsClipboard::motifFillCache() { IClipboard::EFormat format = converter->getFormat(); m_data[format] = converter->toIClipboard(targetData); m_added[format] = true; - LOG( - (CLOG_DEBUG "added format %d for target %s", format, - XWindowsUtil::atomToString(m_display, target).c_str())); + LOG((CLOG_DEBUG "added format %d for target %s", format, XWindowsUtil::atomToString(m_display, target).c_str())); } } -bool XWindowsClipboard::motifGetSelection( - const MotifClipFormat *format, Atom *actualTarget, String *data) const { +bool XWindowsClipboard::motifGetSelection(const MotifClipFormat *format, Atom *actualTarget, String *data) const +{ // if the current clipboard owner and the owner indicated by the // motif clip header are the same then transfer via a property on // the root window, otherwise transfer as a normal ICCCM client. @@ -779,22 +763,21 @@ bool XWindowsClipboard::motifGetSelection( snprintf(name, buffer_size, "_MOTIF_CLIP_ITEM_%d", format->m_data); Atom target = XInternAtom(m_display, name, False); Window root = RootWindow(m_display, DefaultScreen(m_display)); - return XWindowsUtil::getWindowProperty( - m_display, root, target, data, actualTarget, nullptr, False); + return XWindowsUtil::getWindowProperty(m_display, root, target, data, actualTarget, nullptr, False); } -IClipboard::Time XWindowsClipboard::motifGetTime() const { +IClipboard::Time XWindowsClipboard::motifGetTime() const +{ return icccmGetTime(); } -bool XWindowsClipboard::insertMultipleReply( - Window requestor, ::Time time, Atom property) { +bool XWindowsClipboard::insertMultipleReply(Window requestor, ::Time time, Atom property) +{ // get the requested targets Atom target; SInt32 format; String data; - if (!XWindowsUtil::getWindowProperty( - m_display, requestor, property, &data, &target, &format, False)) { + if (!XWindowsUtil::getWindowProperty(m_display, requestor, property, &data, &target, &format, False)) { // can't get the requested targets return false; } @@ -806,8 +789,7 @@ bool XWindowsClipboard::insertMultipleReply( // data is a list of atom pairs: target, property XWindowsUtil::convertAtomProperty(data); - auto targets = - static_cast(static_cast(data.data())); + auto targets = static_cast(static_cast(data.data())); const UInt32 numTargets = data.size() / sizeof(Atom); // add replies for each target @@ -824,19 +806,17 @@ bool XWindowsClipboard::insertMultipleReply( // update the targets property if we changed it if (changed) { - XWindowsUtil::setWindowProperty( - m_display, requestor, property, data.data(), data.size(), target, - format); + XWindowsUtil::setWindowProperty(m_display, requestor, property, data.data(), data.size(), target, format); } // add reply for MULTIPLE request - insertReply( - new Reply(requestor, m_atomMultiple, time, property, String(), None, 32)); + insertReply(new Reply(requestor, m_atomMultiple, time, property, String(), None, 32)); return true; } -void XWindowsClipboard::insertReply(Reply *reply) { +void XWindowsClipboard::insertReply(Reply *reply) +{ assert(reply != nullptr); // note -- we must respond to requests in order if requestor,target,time @@ -870,9 +850,7 @@ void XWindowsClipboard::insertReply(Reply *reply) { m_eventMasks[reply->m_requestor] = attr.your_event_mask; // add the events we want - XSelectInput( - m_display, reply->m_requestor, - attr.your_event_mask | StructureNotifyMask | PropertyChangeMask); + XSelectInput(m_display, reply->m_requestor, attr.your_event_mask | StructureNotifyMask | PropertyChangeMask); } // if we failed then the window has already been destroyed @@ -883,11 +861,11 @@ void XWindowsClipboard::insertReply(Reply *reply) { } } -void XWindowsClipboard::pushReplies() { +void XWindowsClipboard::pushReplies() +{ // send the first reply for each window if that reply hasn't // been sent yet. - for (ReplyMap::iterator index = m_replies.begin(); - index != m_replies.end();) { + for (ReplyMap::iterator index = m_replies.begin(); index != m_replies.end();) { assert(!index->second.empty()); ReplyList::iterator listit = index->second.begin(); while (listit != index->second.end()) { @@ -903,9 +881,8 @@ void XWindowsClipboard::pushReplies() { } } -void XWindowsClipboard::pushReplies( - ReplyMap::iterator &mapIndex, ReplyList &replies, - ReplyList::iterator index) { +void XWindowsClipboard::pushReplies(ReplyMap::iterator &mapIndex, ReplyList &replies, ReplyList::iterator index) +{ Reply *reply = *index; while (sendReply(reply)) { // reply is complete. discard it and send the next reply, @@ -931,14 +908,15 @@ void XWindowsClipboard::pushReplies( } } -bool XWindowsClipboard::sendReply(Reply *reply) { +bool XWindowsClipboard::sendReply(Reply *reply) +{ assert(reply != nullptr); // bail out immediately if reply is done if (reply->m_done) { - LOG( - (CLOG_DEBUG1 "clipboard: finished reply to 0x%08x,%d,%d", - reply->m_requestor, reply->m_target, reply->m_property)); + LOG(( + CLOG_DEBUG1 "clipboard: finished reply to 0x%08x,%d,%d", reply->m_requestor, reply->m_target, reply->m_property + )); return true; } @@ -946,8 +924,9 @@ bool XWindowsClipboard::sendReply(Reply *reply) { bool failed = (reply->m_property == None); if (!failed) { LOG( - (CLOG_DEBUG1 "clipboard: setting property on 0x%08x,%d,%d", - reply->m_requestor, reply->m_target, reply->m_property)); + (CLOG_DEBUG1 "clipboard: setting property on 0x%08x,%d,%d", reply->m_requestor, reply->m_target, + reply->m_property) + ); // send using INCR if already sending incrementally or if reply // is too large, otherwise just send it. @@ -958,8 +937,8 @@ bool XWindowsClipboard::sendReply(Reply *reply) { if (useINCR && !reply->m_replied) { UInt32 size = reply->m_data.size(); if (!XWindowsUtil::setWindowProperty( - m_display, reply->m_requestor, reply->m_property, &size, 4, - m_atomINCR, 32)) { + m_display, reply->m_requestor, reply->m_property, &size, 4, m_atomINCR, 32 + )) { failed = true; } } @@ -973,9 +952,9 @@ bool XWindowsClipboard::sendReply(Reply *reply) { // send it if (!XWindowsUtil::setWindowProperty( - m_display, reply->m_requestor, reply->m_property, - reply->m_data.data() + reply->m_ptr, size, reply->m_type, - reply->m_format)) { + m_display, reply->m_requestor, reply->m_property, reply->m_data.data() + reply->m_ptr, size, + reply->m_type, reply->m_format + )) { failed = true; } else { reply->m_ptr += size; @@ -994,9 +973,9 @@ bool XWindowsClipboard::sendReply(Reply *reply) { // the final zero-length property. // FIXME -- how do you gracefully cancel an incremental transfer? if (failed) { - LOG( - (CLOG_DEBUG1 "clipboard: sending failure to 0x%08x,%d,%d", - reply->m_requestor, reply->m_target, reply->m_property)); + LOG(( + CLOG_DEBUG1 "clipboard: sending failure to 0x%08x,%d,%d", reply->m_requestor, reply->m_target, reply->m_property + )); reply->m_done = true; if (reply->m_property != None) { XWindowsUtil::ErrorLock lock(m_display); @@ -1004,17 +983,15 @@ bool XWindowsClipboard::sendReply(Reply *reply) { } if (!reply->m_replied) { - sendNotify( - reply->m_requestor, m_selection, reply->m_target, None, - reply->m_time); + sendNotify(reply->m_requestor, m_selection, reply->m_target, None, reply->m_time); // don't wait for any reply (because we're not expecting one) return true; } else { static const char dummy = 0; XWindowsUtil::setWindowProperty( - m_display, reply->m_requestor, reply->m_property, &dummy, 0, - reply->m_type, reply->m_format); + m_display, reply->m_requestor, reply->m_property, &dummy, 0, reply->m_type, reply->m_format + ); // wait for delete notify return false; @@ -1026,16 +1003,15 @@ bool XWindowsClipboard::sendReply(Reply *reply) { return false; } - LOG( - (CLOG_DEBUG1 "clipboard: sending notify to 0x%08x,%d,%d", - reply->m_requestor, reply->m_target, reply->m_property)); + LOG((CLOG_DEBUG1 "clipboard: sending notify to 0x%08x,%d,%d", reply->m_requestor, reply->m_target, reply->m_property) + ); reply->m_replied = true; // nothing to log if (CLOG->getFilter() < kDEBUG2) { sendNotify( - reply->m_requestor, m_selection, reply->m_target, reply->m_property, - static_cast(reply->m_time)); + reply->m_requestor, m_selection, reply->m_target, reply->m_property, static_cast(reply->m_time) + ); // wait for delete notify return false; @@ -1053,25 +1029,20 @@ bool XWindowsClipboard::sendReply(Reply *reply) { Atom target; String data; char *name = XGetAtomName(m_display, props[i]); - if (!XWindowsUtil::getWindowProperty( - m_display, reply->m_requestor, props[i], &data, &target, nullptr, - False)) { + if (!XWindowsUtil::getWindowProperty(m_display, reply->m_requestor, props[i], &data, &target, nullptr, False)) { LOG((CLOG_DEBUG2 " %s: ", name)); } else { // convert to hex if contains non ascii symbols - if (std::find_if(data.begin(), data.end(), [](const unsigned char &c) { - return c < 32 || c > 126; - }) != data.end()) { + if (std::find_if(data.begin(), data.end(), [](const unsigned char &c) { return c < 32 || c > 126; }) != + data.end()) { const String hex_digits = "0123456789abcdef"; String tmp; tmp.reserve(data.length() * 3); - std::for_each( - data.begin(), data.end(), - [hex_digits, &tmp](const unsigned char &c) { - tmp += hex_digits[c >> 16]; - tmp += hex_digits[c & 15]; - tmp += ' '; - }); + std::for_each(data.begin(), data.end(), [hex_digits, &tmp](const unsigned char &c) { + tmp += hex_digits[c >> 16]; + tmp += hex_digits[c & 15]; + tmp += ' '; + }); data = tmp; } char *type = XGetAtomName(m_display, target); @@ -1088,33 +1059,31 @@ bool XWindowsClipboard::sendReply(Reply *reply) { XFree(props); } - sendNotify( - reply->m_requestor, m_selection, reply->m_target, reply->m_property, - reply->m_time); + sendNotify(reply->m_requestor, m_selection, reply->m_target, reply->m_property, reply->m_time); // wait for delete notify return false; } -void XWindowsClipboard::clearReplies() { - for (ReplyMap::iterator index = m_replies.begin(); index != m_replies.end(); - ++index) { +void XWindowsClipboard::clearReplies() +{ + for (ReplyMap::iterator index = m_replies.begin(); index != m_replies.end(); ++index) { clearReplies(index->second); } m_replies.clear(); m_eventMasks.clear(); } -void XWindowsClipboard::clearReplies(ReplyList &replies) { - for (ReplyList::iterator index = replies.begin(); index != replies.end(); - ++index) { +void XWindowsClipboard::clearReplies(ReplyList &replies) +{ + for (ReplyList::iterator index = replies.begin(); index != replies.end(); ++index) { delete *index; } replies.clear(); } -void XWindowsClipboard::sendNotify( - Window requestor, Atom selection, Atom target, Atom property, Time time) { +void XWindowsClipboard::sendNotify(Window requestor, Atom selection, Atom target, Atom property, Time time) +{ XEvent event; event.xselection.type = SelectionNotify; event.xselection.display = m_display; @@ -1127,7 +1096,8 @@ void XWindowsClipboard::sendNotify( XSendEvent(m_display, requestor, False, 0, &event); } -bool XWindowsClipboard::wasOwnedAtTime(::Time time) const { +bool XWindowsClipboard::wasOwnedAtTime(::Time time) const +{ // not owned if we've never owned the selection checkCache(); if (m_timeOwned == 0) { @@ -1157,7 +1127,8 @@ bool XWindowsClipboard::wasOwnedAtTime(::Time time) const { return (/*when >= 0 &&*/ when <= duration); } -Atom XWindowsClipboard::getTargetsData(String &data, int *format) const { +Atom XWindowsClipboard::getTargetsData(String &data, int *format) const +{ assert(format != nullptr); // add standard targets @@ -1166,8 +1137,7 @@ Atom XWindowsClipboard::getTargetsData(String &data, int *format) const { XWindowsUtil::appendAtomData(data, m_atomTimestamp); // add targets we can convert to - for (ConverterList::const_iterator index = m_converters.begin(); - index != m_converters.end(); ++index) { + for (ConverterList::const_iterator index = m_converters.begin(); index != m_converters.end(); ++index) { IXWindowsClipboardConverter *converter = *index; // skip formats we don't have @@ -1180,7 +1150,8 @@ Atom XWindowsClipboard::getTargetsData(String &data, int *format) const { return m_atomAtom; } -Atom XWindowsClipboard::getTimestampData(String &data, int *format) const { +Atom XWindowsClipboard::getTimestampData(String &data, int *format) const +{ assert(format != nullptr); checkCache(); @@ -1193,22 +1164,24 @@ Atom XWindowsClipboard::getTimestampData(String &data, int *format) const { // XWindowsClipboard::CICCCMGetClipboard // -XWindowsClipboard::CICCCMGetClipboard::CICCCMGetClipboard( - Window requestor, Time time, Atom property) +XWindowsClipboard::CICCCMGetClipboard::CICCCMGetClipboard(Window requestor, Time time, Atom property) : m_requestor(requestor), m_time(time), - m_property(property) {} + m_property(property) +{ +} bool XWindowsClipboard::CICCCMGetClipboard::readClipboard( - Display *display, Atom selection, Atom target, Atom *actualTarget, - String *data) { + Display *display, Atom selection, Atom target, Atom *actualTarget, String *data +) +{ assert(actualTarget != nullptr); assert(data != nullptr); LOG( - (CLOG_DEBUG1 "request selection=%s, target=%s, window=%x", - XWindowsUtil::atomToString(display, selection).c_str(), - XWindowsUtil::atomToString(display, target).c_str(), m_requestor)); + (CLOG_DEBUG1 "request selection=%s, target=%s, window=%x", XWindowsUtil::atomToString(display, selection).c_str(), + XWindowsUtil::atomToString(display, target).c_str(), m_requestor) + ); m_atomNone = XInternAtom(display, "NONE", False); m_atomIncr = XInternAtom(display, "INCR", False); @@ -1230,8 +1203,7 @@ bool XWindowsClipboard::CICCCMGetClipboard::readClipboard( XSelectInput(display, m_requestor, attr.your_event_mask | PropertyChangeMask); // request data conversion - XConvertSelection( - display, selection, target, m_property, m_requestor, m_time); + XConvertSelection(display, selection, target, m_property, m_requestor, m_time); // synchronize with server before we start following timeout countdown XSync(display, False); @@ -1291,14 +1263,12 @@ bool XWindowsClipboard::CICCCMGetClipboard::readClipboard( XSelectInput(display, m_requestor, attr.your_event_mask); // return success or failure - LOG( - (CLOG_DEBUG1 "request %s after %fs", m_failed ? "failed" : "succeeded", - timeout.getTime())); + LOG((CLOG_DEBUG1 "request %s after %fs", m_failed ? "failed" : "succeeded", timeout.getTime())); return !m_failed; } -bool XWindowsClipboard::CICCCMGetClipboard::processEvent( - Display *display, XEvent *xevent) { +bool XWindowsClipboard::CICCCMGetClipboard::processEvent(Display *display, XEvent *xevent) +{ // process event switch (xevent->type) { case DestroyNotify: @@ -1313,8 +1283,7 @@ bool XWindowsClipboard::CICCCMGetClipboard::processEvent( case SelectionNotify: if (xevent->xselection.requestor == m_requestor) { // done if we can't convert - if (xevent->xselection.property == None || - xevent->xselection.property == m_atomNone) { + if (xevent->xselection.property == None || xevent->xselection.property == m_atomNone) { m_done = true; return true; } @@ -1331,8 +1300,7 @@ bool XWindowsClipboard::CICCCMGetClipboard::processEvent( case PropertyNotify: // proceed if conversion successful and we're receiving more data - if (xevent->xproperty.window == m_requestor && - xevent->xproperty.atom == m_property && + if (xevent->xproperty.window == m_requestor && xevent->xproperty.atom == m_property && xevent->xproperty.state == PropertyNewValue) { if (!m_reading) { // we haven't gotten the SelectionNotify yet @@ -1352,8 +1320,7 @@ bool XWindowsClipboard::CICCCMGetClipboard::processEvent( // get the data from the property Atom target; const String::size_type oldSize = m_data->size(); - if (!XWindowsUtil::getWindowProperty( - display, m_requestor, m_property, m_data, &target, nullptr, True)) { + if (!XWindowsUtil::getWindowProperty(display, m_requestor, m_property, m_data, &target, nullptr, True)) { // unable to read property m_failed = true; return true; @@ -1378,9 +1345,7 @@ bool XWindowsClipboard::CICCCMGetClipboard::processEvent( else if (m_incr) { // if first incremental chunk then save target if (oldSize == 0) { - LOG( - (CLOG_DEBUG1 " INCR first chunk, target %s", - XWindowsUtil::atomToString(display, target).c_str())); + LOG((CLOG_DEBUG1 " INCR first chunk, target %s", XWindowsUtil::atomToString(display, target).c_str())); *m_actualTarget = target; } @@ -1402,9 +1367,7 @@ bool XWindowsClipboard::CICCCMGetClipboard::processEvent( // not incremental; save the target. else { - LOG( - (CLOG_DEBUG1 " target %s", - XWindowsUtil::atomToString(display, target).c_str())); + LOG((CLOG_DEBUG1 " target %s", XWindowsUtil::atomToString(display, target).c_str())); *m_actualTarget = target; m_done = true; } @@ -1428,13 +1391,14 @@ XWindowsClipboard::Reply::Reply(Window requestor, Atom target, ::Time time) m_data(), m_type(None), m_format(32), - m_ptr(0) { + m_ptr(0) +{ // do nothing } XWindowsClipboard::Reply::Reply( - Window requestor, Atom target, ::Time time, Atom property, - const String &data, Atom type, int format) + Window requestor, Atom target, ::Time time, Atom property, const String &data, Atom type, int format +) : m_requestor(requestor), m_target(target), m_time(time), @@ -1444,6 +1408,7 @@ XWindowsClipboard::Reply::Reply( m_data(data), m_type(type), m_format(format), - m_ptr(0) { + m_ptr(0) +{ // do nothing } diff --git a/src/lib/platform/XWindowsClipboard.h b/src/lib/platform/XWindowsClipboard.h index cf58ec54a..c65aa2bf5 100644 --- a/src/lib/platform/XWindowsClipboard.h +++ b/src/lib/platform/XWindowsClipboard.h @@ -33,7 +33,8 @@ class IXWindowsClipboardConverter; //! X11 clipboard implementation -class XWindowsClipboard : public IClipboard { +class XWindowsClipboard : public IClipboard +{ public: /*! Use \c window as the window that owns or interacts with the @@ -59,8 +60,7 @@ public: owner window isn't this clipboard's window then this simply sends a failure event to the requestor. */ - void addRequest( - Window owner, Window requestor, Atom target, ::Time time, Atom property); + void addRequest(Window owner, Window requestor, Atom target, ::Time time, Atom property); //! Process clipboard request /*! @@ -106,8 +106,7 @@ private: // suitable converter. iff onlyIfNotAdded is true then also // return NULL if a suitable converter was found but we already // have data of the converter's clipboard format. - IXWindowsClipboardConverter * - getConverter(Atom target, bool onlyIfNotAdded = false) const; + IXWindowsClipboardConverter *getConverter(Atom target, bool onlyIfNotAdded = false) const; // convert target atom to clipboard format EFormat getFormat(Atom target) const; @@ -116,8 +115,7 @@ private: // was owned at the given time. returns true if the conversion // could be performed, false otherwise. in either case, the // reply is inserted. - bool - addSimpleRequest(Window requestor, Atom target, ::Time time, Atom property); + bool addSimpleRequest(Window requestor, Atom target, ::Time time, Atom property); // if not already checked then see if the cache is stale and, if so, // clear it. this has the side effect of updating m_timeOwned. @@ -138,7 +136,8 @@ protected: // // read an ICCCM conforming selection - class CICCCMGetClipboard { + class CICCCMGetClipboard + { public: CICCCMGetClipboard(Window requestor, Time time, Atom property); ~CICCCMGetClipboard() = default; @@ -146,9 +145,7 @@ protected: // convert the given selection to the given type. returns // true iff the conversion was successful or the conversion // cannot be performed (in which case *actualTarget == None). - bool readClipboard( - Display *display, Atom selection, Atom target, Atom *actualTarget, - String *data); + bool readClipboard(Display *display, Atom selection, Atom target, Atom *actualTarget, String *data); private: bool processEvent(Display *display, XEvent *event); @@ -179,14 +176,23 @@ protected: bool m_error = false; public: - bool error() const { return m_error; } + bool error() const + { + return m_error; + } }; // Motif structure IDs - enum class MotifClip : SInt32 { Format = 1, Item = 2, Header = 3 }; + enum class MotifClip : SInt32 + { + Format = 1, + Item = 2, + Header = 3 + }; // _MOTIF_CLIP_HEADER structure - class MotifClipHeader { + class MotifClipHeader + { public: MotifClip m_id; SInt32 m_pad1[3]; @@ -199,7 +205,8 @@ protected: }; // Motif clip item structure - class MotifClipItem { + class MotifClipItem + { public: MotifClip m_id; SInt32 m_pad1[5]; @@ -210,7 +217,8 @@ protected: }; // Motif clip format structure - class MotifClipFormat { + class MotifClipFormat + { public: MotifClip m_id; SInt32 m_pad1[6]; @@ -223,12 +231,11 @@ protected: }; // stores data needed to respond to a selection request - class Reply { + class Reply + { public: Reply(Window, Atom target, ::Time); - Reply( - Window, Atom target, ::Time, Atom property, const String &data, - Atom type, int format); + Reply(Window, Atom target, ::Time, Atom property, const String &data, Atom type, int format); public: // information about the request @@ -265,8 +272,7 @@ protected: void motifUnlockClipboard() const; bool motifOwnsClipboard() const; void motifFillCache(); - bool motifGetSelection( - const MotifClipFormat *, Atom *actualTarget, String *data) const; + bool motifGetSelection(const MotifClipFormat *, Atom *actualTarget, String *data) const; Time motifGetTime() const; // reply methods @@ -277,8 +283,7 @@ protected: bool sendReply(Reply *); void clearReplies(); void clearReplies(ReplyList &); - void sendNotify( - Window requestor, Atom selection, Atom target, Atom property, Time time); + void sendNotify(Window requestor, Atom selection, Atom target, Atom property, Time time); bool wasOwnedAtTime(::Time) const; // data conversion methods @@ -335,7 +340,8 @@ private: This interface defines the methods common to all X11 clipboard format converters. */ -class IXWindowsClipboardConverter : public IInterface { +class IXWindowsClipboardConverter : public IInterface +{ public: //! @name accessors //@{ diff --git a/src/lib/platform/XWindowsClipboardAnyBitmapConverter.cpp b/src/lib/platform/XWindowsClipboardAnyBitmapConverter.cpp index cb23783a7..0f527d612 100644 --- a/src/lib/platform/XWindowsClipboardAnyBitmapConverter.cpp +++ b/src/lib/platform/XWindowsClipboardAnyBitmapConverter.cpp @@ -19,7 +19,8 @@ #include "platform/XWindowsClipboardAnyBitmapConverter.h" // BMP info header structure -struct CBMPInfoHeader { +struct CBMPInfoHeader +{ public: UInt32 biSize; SInt32 biWidth; @@ -36,13 +37,15 @@ public: // BMP is little-endian -static void toLE(UInt8 *&dst, UInt16 src) { +static void toLE(UInt8 *&dst, UInt16 src) +{ dst[0] = static_cast(src & 0xffu); dst[1] = static_cast((src >> 8) & 0xffu); dst += 2; } -static void toLE(UInt8 *&dst, SInt32 src) { +static void toLE(UInt8 *&dst, SInt32 src) +{ dst[0] = static_cast(src & 0xffu); dst[1] = static_cast((src >> 8) & 0xffu); dst[2] = static_cast((src >> 16) & 0xffu); @@ -50,7 +53,8 @@ static void toLE(UInt8 *&dst, SInt32 src) { dst += 4; } -static void toLE(UInt8 *&dst, UInt32 src) { +static void toLE(UInt8 *&dst, UInt32 src) +{ dst[0] = static_cast(src & 0xffu); dst[1] = static_cast((src >> 8) & 0xffu); dst[2] = static_cast((src >> 16) & 0xffu); @@ -58,20 +62,22 @@ static void toLE(UInt8 *&dst, UInt32 src) { dst += 4; } -static inline UInt16 fromLEU16(const UInt8 *data) { +static inline UInt16 fromLEU16(const UInt8 *data) +{ return static_cast(data[0]) | (static_cast(data[1]) << 8); } -static inline SInt32 fromLES32(const UInt8 *data) { +static inline SInt32 fromLES32(const UInt8 *data) +{ return static_cast( - static_cast(data[0]) | (static_cast(data[1]) << 8) | - (static_cast(data[2]) << 16) | - (static_cast(data[3]) << 24)); + static_cast(data[0]) | (static_cast(data[1]) << 8) | (static_cast(data[2]) << 16) | + (static_cast(data[3]) << 24) + ); } -static inline UInt32 fromLEU32(const UInt8 *data) { - return static_cast(data[0]) | (static_cast(data[1]) << 8) | - (static_cast(data[2]) << 16) | +static inline UInt32 fromLEU32(const UInt8 *data) +{ + return static_cast(data[0]) | (static_cast(data[1]) << 8) | (static_cast(data[2]) << 16) | (static_cast(data[3]) << 24); } @@ -79,22 +85,28 @@ static inline UInt32 fromLEU32(const UInt8 *data) { // XWindowsClipboardAnyBitmapConverter // -XWindowsClipboardAnyBitmapConverter::XWindowsClipboardAnyBitmapConverter() { +XWindowsClipboardAnyBitmapConverter::XWindowsClipboardAnyBitmapConverter() +{ // do nothing } -XWindowsClipboardAnyBitmapConverter::~XWindowsClipboardAnyBitmapConverter() { +XWindowsClipboardAnyBitmapConverter::~XWindowsClipboardAnyBitmapConverter() +{ // do nothing } -IClipboard::EFormat XWindowsClipboardAnyBitmapConverter::getFormat() const { +IClipboard::EFormat XWindowsClipboardAnyBitmapConverter::getFormat() const +{ return IClipboard::kBitmap; } -int XWindowsClipboardAnyBitmapConverter::getDataSize() const { return 8; } +int XWindowsClipboardAnyBitmapConverter::getDataSize() const +{ + return 8; +} -String -XWindowsClipboardAnyBitmapConverter::fromIClipboard(const String &bmp) const { +String XWindowsClipboardAnyBitmapConverter::fromIClipboard(const String &bmp) const +{ // fill BMP info header with native-endian data CBMPInfoHeader infoHeader; const UInt8 *rawBMPInfoHeader = reinterpret_cast(bmp.data()); @@ -111,26 +123,22 @@ XWindowsClipboardAnyBitmapConverter::fromIClipboard(const String &bmp) const { infoHeader.biClrImportant = fromLEU32(rawBMPInfoHeader + 36); // check that format is acceptable - if (infoHeader.biSize != 40 || infoHeader.biWidth == 0 || - infoHeader.biHeight == 0 || infoHeader.biPlanes != 0 || - infoHeader.biCompression != 0 || - (infoHeader.biBitCount != 24 && infoHeader.biBitCount != 32)) { + if (infoHeader.biSize != 40 || infoHeader.biWidth == 0 || infoHeader.biHeight == 0 || infoHeader.biPlanes != 0 || + infoHeader.biCompression != 0 || (infoHeader.biBitCount != 24 && infoHeader.biBitCount != 32)) { return String(); } // convert to image format const UInt8 *rawBMPPixels = rawBMPInfoHeader + 40; if (infoHeader.biBitCount == 24) { - return doBGRFromIClipboard( - rawBMPPixels, infoHeader.biWidth, infoHeader.biHeight); + return doBGRFromIClipboard(rawBMPPixels, infoHeader.biWidth, infoHeader.biHeight); } else { - return doBGRAFromIClipboard( - rawBMPPixels, infoHeader.biWidth, infoHeader.biHeight); + return doBGRAFromIClipboard(rawBMPPixels, infoHeader.biWidth, infoHeader.biHeight); } } -String -XWindowsClipboardAnyBitmapConverter::toIClipboard(const String &image) const { +String XWindowsClipboardAnyBitmapConverter::toIClipboard(const String &image) const +{ // convert to raw BMP data UInt32 w, h, depth; String rawBMP = doToIClipboard(image, w, h, depth); @@ -154,7 +162,5 @@ XWindowsClipboardAnyBitmapConverter::toIClipboard(const String &image) const { toLE(dst, static_cast(0)); // construct image - return String( - reinterpret_cast(infoHeader), sizeof(infoHeader)) + - rawBMP; + return String(reinterpret_cast(infoHeader), sizeof(infoHeader)) + rawBMP; } diff --git a/src/lib/platform/XWindowsClipboardAnyBitmapConverter.h b/src/lib/platform/XWindowsClipboardAnyBitmapConverter.h index 6f44a3654..0216ff2a1 100644 --- a/src/lib/platform/XWindowsClipboardAnyBitmapConverter.h +++ b/src/lib/platform/XWindowsClipboardAnyBitmapConverter.h @@ -21,7 +21,8 @@ #include "platform/XWindowsClipboard.h" //! Convert to/from some text encoding -class XWindowsClipboardAnyBitmapConverter : public IXWindowsClipboardConverter { +class XWindowsClipboardAnyBitmapConverter : public IXWindowsClipboardConverter +{ public: XWindowsClipboardAnyBitmapConverter(); virtual ~XWindowsClipboardAnyBitmapConverter(); @@ -38,21 +39,18 @@ protected: /*! Convert raw BGR pixel data to another image format. */ - virtual String - doBGRFromIClipboard(const UInt8 *bgrData, UInt32 w, UInt32 h) const = 0; + virtual String doBGRFromIClipboard(const UInt8 *bgrData, UInt32 w, UInt32 h) const = 0; //! Convert from IClipboard format /*! Convert raw BGRA pixel data to another image format. */ - virtual String - doBGRAFromIClipboard(const UInt8 *bgrData, UInt32 w, UInt32 h) const = 0; + virtual String doBGRAFromIClipboard(const UInt8 *bgrData, UInt32 w, UInt32 h) const = 0; //! Convert to IClipboard format /*! Convert an image into raw BGR or BGRA image data and store the width, height, and image depth (24 or 32). */ - virtual String - doToIClipboard(const String &, UInt32 &w, UInt32 &h, UInt32 &depth) const = 0; + virtual String doToIClipboard(const String &, UInt32 &w, UInt32 &h, UInt32 &depth) const = 0; }; diff --git a/src/lib/platform/XWindowsClipboardBMPConverter.cpp b/src/lib/platform/XWindowsClipboardBMPConverter.cpp index c30d4f763..a8886752e 100644 --- a/src/lib/platform/XWindowsClipboardBMPConverter.cpp +++ b/src/lib/platform/XWindowsClipboardBMPConverter.cpp @@ -19,7 +19,8 @@ #include "platform/XWindowsClipboardBMPConverter.h" // BMP file header structure -struct CBMPHeader { +struct CBMPHeader +{ public: UInt16 type; UInt32 size; @@ -29,24 +30,27 @@ public: }; // BMP is little-endian -static inline UInt32 fromLEU32(const UInt8 *data) { - return static_cast(data[0]) | (static_cast(data[1]) << 8) | - (static_cast(data[2]) << 16) | +static inline UInt32 fromLEU32(const UInt8 *data) +{ + return static_cast(data[0]) | (static_cast(data[1]) << 8) | (static_cast(data[2]) << 16) | (static_cast(data[3]) << 24); } -static void toLE(UInt8 *&dst, char src) { +static void toLE(UInt8 *&dst, char src) +{ dst[0] = static_cast(src); dst += 1; } -static void toLE(UInt8 *&dst, UInt16 src) { +static void toLE(UInt8 *&dst, UInt16 src) +{ dst[0] = static_cast(src & 0xffu); dst[1] = static_cast((src >> 8) & 0xffu); dst += 2; } -static void toLE(UInt8 *&dst, UInt32 src) { +static void toLE(UInt8 *&dst, UInt32 src) +{ dst[0] = static_cast(src & 0xffu); dst[1] = static_cast((src >> 8) & 0xffu); dst[2] = static_cast((src >> 16) & 0xffu); @@ -59,23 +63,33 @@ static void toLE(UInt8 *&dst, UInt32 src) { // XWindowsClipboardBMPConverter::XWindowsClipboardBMPConverter(Display *display) - : m_atom(XInternAtom(display, "image/bmp", False)) { + : m_atom(XInternAtom(display, "image/bmp", False)) +{ // do nothing } -XWindowsClipboardBMPConverter::~XWindowsClipboardBMPConverter() { +XWindowsClipboardBMPConverter::~XWindowsClipboardBMPConverter() +{ // do nothing } -IClipboard::EFormat XWindowsClipboardBMPConverter::getFormat() const { +IClipboard::EFormat XWindowsClipboardBMPConverter::getFormat() const +{ return IClipboard::kBitmap; } -Atom XWindowsClipboardBMPConverter::getAtom() const { return m_atom; } +Atom XWindowsClipboardBMPConverter::getAtom() const +{ + return m_atom; +} -int XWindowsClipboardBMPConverter::getDataSize() const { return 8; } +int XWindowsClipboardBMPConverter::getDataSize() const +{ + return 8; +} -String XWindowsClipboardBMPConverter::fromIClipboard(const String &bmp) const { +String XWindowsClipboardBMPConverter::fromIClipboard(const String &bmp) const +{ // create BMP image UInt8 header[14]; UInt8 *dst = header; @@ -88,7 +102,8 @@ String XWindowsClipboardBMPConverter::fromIClipboard(const String &bmp) const { return String(reinterpret_cast(header), 14) + bmp; } -String XWindowsClipboardBMPConverter::toIClipboard(const String &bmp) const { +String XWindowsClipboardBMPConverter::toIClipboard(const String &bmp) const +{ // make sure data is big enough for a BMP file if (bmp.size() <= 14 + 40) { return String(); diff --git a/src/lib/platform/XWindowsClipboardBMPConverter.h b/src/lib/platform/XWindowsClipboardBMPConverter.h index afe093f6e..ba7d913b8 100644 --- a/src/lib/platform/XWindowsClipboardBMPConverter.h +++ b/src/lib/platform/XWindowsClipboardBMPConverter.h @@ -21,7 +21,8 @@ #include "platform/XWindowsClipboard.h" //! Convert to/from some text encoding -class XWindowsClipboardBMPConverter : public IXWindowsClipboardConverter { +class XWindowsClipboardBMPConverter : public IXWindowsClipboardConverter +{ public: XWindowsClipboardBMPConverter(Display *display); virtual ~XWindowsClipboardBMPConverter(); diff --git a/src/lib/platform/XWindowsClipboardHTMLConverter.cpp b/src/lib/platform/XWindowsClipboardHTMLConverter.cpp index a5be4b277..2a7b6e3e8 100644 --- a/src/lib/platform/XWindowsClipboardHTMLConverter.cpp +++ b/src/lib/platform/XWindowsClipboardHTMLConverter.cpp @@ -24,30 +24,39 @@ // XWindowsClipboardHTMLConverter // -XWindowsClipboardHTMLConverter::XWindowsClipboardHTMLConverter( - Display *display, const char *name) - : m_atom(XInternAtom(display, name, False)) { +XWindowsClipboardHTMLConverter::XWindowsClipboardHTMLConverter(Display *display, const char *name) + : m_atom(XInternAtom(display, name, False)) +{ // do nothing } -XWindowsClipboardHTMLConverter::~XWindowsClipboardHTMLConverter() { +XWindowsClipboardHTMLConverter::~XWindowsClipboardHTMLConverter() +{ // do nothing } -IClipboard::EFormat XWindowsClipboardHTMLConverter::getFormat() const { +IClipboard::EFormat XWindowsClipboardHTMLConverter::getFormat() const +{ return IClipboard::kHTML; } -Atom XWindowsClipboardHTMLConverter::getAtom() const { return m_atom; } +Atom XWindowsClipboardHTMLConverter::getAtom() const +{ + return m_atom; +} -int XWindowsClipboardHTMLConverter::getDataSize() const { return 8; } +int XWindowsClipboardHTMLConverter::getDataSize() const +{ + return 8; +} -String -XWindowsClipboardHTMLConverter::fromIClipboard(const String &data) const { +String XWindowsClipboardHTMLConverter::fromIClipboard(const String &data) const +{ return data; } -String XWindowsClipboardHTMLConverter::toIClipboard(const String &data) const { +String XWindowsClipboardHTMLConverter::toIClipboard(const String &data) const +{ if (Unicode::isUTF8(data)) { return data; } else { diff --git a/src/lib/platform/XWindowsClipboardHTMLConverter.h b/src/lib/platform/XWindowsClipboardHTMLConverter.h index ca8dd8e4b..add6ec7ea 100644 --- a/src/lib/platform/XWindowsClipboardHTMLConverter.h +++ b/src/lib/platform/XWindowsClipboardHTMLConverter.h @@ -21,7 +21,8 @@ #include "platform/XWindowsClipboard.h" //! Convert to/from HTML encoding -class XWindowsClipboardHTMLConverter : public IXWindowsClipboardConverter { +class XWindowsClipboardHTMLConverter : public IXWindowsClipboardConverter +{ public: /*! \c name is converted to an atom and that is reported by getAtom(). diff --git a/src/lib/platform/XWindowsClipboardTextConverter.cpp b/src/lib/platform/XWindowsClipboardTextConverter.cpp index 4cff76c24..066becf34 100644 --- a/src/lib/platform/XWindowsClipboardTextConverter.cpp +++ b/src/lib/platform/XWindowsClipboardTextConverter.cpp @@ -24,30 +24,39 @@ // XWindowsClipboardTextConverter // -XWindowsClipboardTextConverter::XWindowsClipboardTextConverter( - Display *display, const char *name) - : m_atom(XInternAtom(display, name, False)) { +XWindowsClipboardTextConverter::XWindowsClipboardTextConverter(Display *display, const char *name) + : m_atom(XInternAtom(display, name, False)) +{ // do nothing } -XWindowsClipboardTextConverter::~XWindowsClipboardTextConverter() { +XWindowsClipboardTextConverter::~XWindowsClipboardTextConverter() +{ // do nothing } -IClipboard::EFormat XWindowsClipboardTextConverter::getFormat() const { +IClipboard::EFormat XWindowsClipboardTextConverter::getFormat() const +{ return IClipboard::kText; } -Atom XWindowsClipboardTextConverter::getAtom() const { return m_atom; } +Atom XWindowsClipboardTextConverter::getAtom() const +{ + return m_atom; +} -int XWindowsClipboardTextConverter::getDataSize() const { return 8; } +int XWindowsClipboardTextConverter::getDataSize() const +{ + return 8; +} -String -XWindowsClipboardTextConverter::fromIClipboard(const String &data) const { +String XWindowsClipboardTextConverter::fromIClipboard(const String &data) const +{ return Unicode::UTF8ToText(data); } -String XWindowsClipboardTextConverter::toIClipboard(const String &data) const { +String XWindowsClipboardTextConverter::toIClipboard(const String &data) const +{ // convert to UTF-8 bool errors; String utf8 = Unicode::textToUTF8(data, &errors); diff --git a/src/lib/platform/XWindowsClipboardTextConverter.h b/src/lib/platform/XWindowsClipboardTextConverter.h index 1de8a78dd..ad7097838 100644 --- a/src/lib/platform/XWindowsClipboardTextConverter.h +++ b/src/lib/platform/XWindowsClipboardTextConverter.h @@ -21,7 +21,8 @@ #include "platform/XWindowsClipboard.h" //! Convert to/from locale text encoding -class XWindowsClipboardTextConverter : public IXWindowsClipboardConverter { +class XWindowsClipboardTextConverter : public IXWindowsClipboardConverter +{ public: /*! \c name is converted to an atom and that is reported by getAtom(). diff --git a/src/lib/platform/XWindowsClipboardUCS2Converter.cpp b/src/lib/platform/XWindowsClipboardUCS2Converter.cpp index 93e68dc7c..3c2317ba4 100644 --- a/src/lib/platform/XWindowsClipboardUCS2Converter.cpp +++ b/src/lib/platform/XWindowsClipboardUCS2Converter.cpp @@ -24,29 +24,38 @@ // XWindowsClipboardUCS2Converter // -XWindowsClipboardUCS2Converter::XWindowsClipboardUCS2Converter( - Display *display, const char *name) - : m_atom(XInternAtom(display, name, False)) { +XWindowsClipboardUCS2Converter::XWindowsClipboardUCS2Converter(Display *display, const char *name) + : m_atom(XInternAtom(display, name, False)) +{ // do nothing } -XWindowsClipboardUCS2Converter::~XWindowsClipboardUCS2Converter() { +XWindowsClipboardUCS2Converter::~XWindowsClipboardUCS2Converter() +{ // do nothing } -IClipboard::EFormat XWindowsClipboardUCS2Converter::getFormat() const { +IClipboard::EFormat XWindowsClipboardUCS2Converter::getFormat() const +{ return IClipboard::kText; } -Atom XWindowsClipboardUCS2Converter::getAtom() const { return m_atom; } +Atom XWindowsClipboardUCS2Converter::getAtom() const +{ + return m_atom; +} -int XWindowsClipboardUCS2Converter::getDataSize() const { return 16; } +int XWindowsClipboardUCS2Converter::getDataSize() const +{ + return 16; +} -String -XWindowsClipboardUCS2Converter::fromIClipboard(const String &data) const { +String XWindowsClipboardUCS2Converter::fromIClipboard(const String &data) const +{ return Unicode::UTF8ToUCS2(data); } -String XWindowsClipboardUCS2Converter::toIClipboard(const String &data) const { +String XWindowsClipboardUCS2Converter::toIClipboard(const String &data) const +{ return Unicode::UCS2ToUTF8(data); } diff --git a/src/lib/platform/XWindowsClipboardUCS2Converter.h b/src/lib/platform/XWindowsClipboardUCS2Converter.h index e5283b53f..7115d48e8 100644 --- a/src/lib/platform/XWindowsClipboardUCS2Converter.h +++ b/src/lib/platform/XWindowsClipboardUCS2Converter.h @@ -21,7 +21,8 @@ #include "platform/XWindowsClipboard.h" //! Convert to/from UCS-2 encoding -class XWindowsClipboardUCS2Converter : public IXWindowsClipboardConverter { +class XWindowsClipboardUCS2Converter : public IXWindowsClipboardConverter +{ public: /*! \c name is converted to an atom and that is reported by getAtom(). diff --git a/src/lib/platform/XWindowsClipboardUTF8Converter.cpp b/src/lib/platform/XWindowsClipboardUTF8Converter.cpp index e06628f86..fcf7287b8 100644 --- a/src/lib/platform/XWindowsClipboardUTF8Converter.cpp +++ b/src/lib/platform/XWindowsClipboardUTF8Converter.cpp @@ -24,33 +24,45 @@ // XWindowsClipboardUTF8Converter // -XWindowsClipboardUTF8Converter::XWindowsClipboardUTF8Converter( - Display *display, const char *name, bool normalize) +XWindowsClipboardUTF8Converter::XWindowsClipboardUTF8Converter(Display *display, const char *name, bool normalize) : m_atom(XInternAtom(display, name, False)), - m_normalize(normalize) { + m_normalize(normalize) +{ // do nothing } -XWindowsClipboardUTF8Converter::~XWindowsClipboardUTF8Converter() { +XWindowsClipboardUTF8Converter::~XWindowsClipboardUTF8Converter() +{ // do nothing } -IClipboard::EFormat XWindowsClipboardUTF8Converter::getFormat() const { +IClipboard::EFormat XWindowsClipboardUTF8Converter::getFormat() const +{ return IClipboard::kText; } -Atom XWindowsClipboardUTF8Converter::getAtom() const { return m_atom; } +Atom XWindowsClipboardUTF8Converter::getAtom() const +{ + return m_atom; +} -int XWindowsClipboardUTF8Converter::getDataSize() const { return 8; } +int XWindowsClipboardUTF8Converter::getDataSize() const +{ + return 8; +} -static bool isCR(char ch) { return (ch == '\r'); } +static bool isCR(char ch) +{ + return (ch == '\r'); +} -String -XWindowsClipboardUTF8Converter::fromIClipboard(const String &data) const { +String XWindowsClipboardUTF8Converter::fromIClipboard(const String &data) const +{ return data; } -String XWindowsClipboardUTF8Converter::toIClipboard(const String &data) const { +String XWindowsClipboardUTF8Converter::toIClipboard(const String &data) const +{ // https://bugzilla.mozilla.org/show_bug.cgi?id=1547595 // GTK normalizes the clipboard's line endings to CRLF (\r\n) internally. // When sending the raw data to other systems, like Windows, where \n is diff --git a/src/lib/platform/XWindowsClipboardUTF8Converter.h b/src/lib/platform/XWindowsClipboardUTF8Converter.h index 63ad5cac2..af7dc9509 100644 --- a/src/lib/platform/XWindowsClipboardUTF8Converter.h +++ b/src/lib/platform/XWindowsClipboardUTF8Converter.h @@ -21,13 +21,13 @@ #include "platform/XWindowsClipboard.h" //! Convert to/from UTF-8 encoding -class XWindowsClipboardUTF8Converter : public IXWindowsClipboardConverter { +class XWindowsClipboardUTF8Converter : public IXWindowsClipboardConverter +{ public: /*! \c name is converted to an atom and that is reported by getAtom(). */ - XWindowsClipboardUTF8Converter( - Display *display, const char *name, bool normalize = false); + XWindowsClipboardUTF8Converter(Display *display, const char *name, bool normalize = false); virtual ~XWindowsClipboardUTF8Converter(); // IXWindowsClipboardConverter overrides diff --git a/src/lib/platform/XWindowsEventQueueBuffer.cpp b/src/lib/platform/XWindowsEventQueueBuffer.cpp index b16fb1931..6d5820148 100644 --- a/src/lib/platform/XWindowsEventQueueBuffer.cpp +++ b/src/lib/platform/XWindowsEventQueueBuffer.cpp @@ -34,18 +34,20 @@ // EventQueueTimer // -class EventQueueTimer {}; +class EventQueueTimer +{ +}; // // XWindowsEventQueueBuffer // -XWindowsEventQueueBuffer::XWindowsEventQueueBuffer( - Display *display, Window window, IEventQueue *events) +XWindowsEventQueueBuffer::XWindowsEventQueueBuffer(Display *display, Window window, IEventQueue *events) : m_events(events), m_display(display), m_window(window), - m_waiting(false) { + m_waiting(false) +{ assert(m_display != NULL); assert(m_window != None); @@ -55,18 +57,21 @@ XWindowsEventQueueBuffer::XWindowsEventQueueBuffer( assert(result == 0); } -XWindowsEventQueueBuffer::~XWindowsEventQueueBuffer() { +XWindowsEventQueueBuffer::~XWindowsEventQueueBuffer() +{ // release pipe hack resources close(m_pipefd[0]); close(m_pipefd[1]); } -int XWindowsEventQueueBuffer::getPendingCountLocked() { +int XWindowsEventQueueBuffer::getPendingCountLocked() +{ Lock lock(&m_mutex); return XPending(m_display); } -void XWindowsEventQueueBuffer::waitForEvent(double dtimeout) { +void XWindowsEventQueueBuffer::waitForEvent(double dtimeout) +{ Thread::testCancel(); // clear out the pipe in preparation for waiting. @@ -117,8 +122,7 @@ void XWindowsEventQueueBuffer::waitForEvent(double dtimeout) { // we want to give the cpu a chance s owe up this to 25ms #define TIMEOUT_DELAY 25 - while (((dtimeout < 0.0) || (remaining > 0)) && - getPendingCountLocked() == 0 && retval == 0) { + while (((dtimeout < 0.0) || (remaining > 0)) && getPendingCountLocked() == 0 && retval == 0) { retval = poll(pfds, 2, TIMEOUT_DELAY); // 16ms = 60hz, but we make it > to // play nicely with the cpu @@ -142,8 +146,8 @@ void XWindowsEventQueueBuffer::waitForEvent(double dtimeout) { Thread::testCancel(); } -IEventQueueBuffer::Type -XWindowsEventQueueBuffer::getEvent(Event &event, UInt32 &dataID) { +IEventQueueBuffer::Type XWindowsEventQueueBuffer::getEvent(Event &event, UInt32 &dataID) +{ Lock lock(&m_mutex); // push out pending events @@ -153,8 +157,7 @@ XWindowsEventQueueBuffer::getEvent(Event &event, UInt32 &dataID) { XNextEvent(m_display, &m_event); // process event - if (m_event.xany.type == ClientMessage && - m_event.xclient.message_type == m_userEvent) { + if (m_event.xany.type == ClientMessage && m_event.xclient.message_type == m_userEvent) { dataID = static_cast(m_event.xclient.data.l[0]); return kUser; } else { @@ -163,7 +166,8 @@ XWindowsEventQueueBuffer::getEvent(Event &event, UInt32 &dataID) { } } -bool XWindowsEventQueueBuffer::addEvent(UInt32 dataID) { +bool XWindowsEventQueueBuffer::addEvent(UInt32 dataID) +{ // prepare a message XEvent xevent; xevent.xclient.type = ClientMessage; @@ -197,20 +201,24 @@ bool XWindowsEventQueueBuffer::addEvent(UInt32 dataID) { return true; } -bool XWindowsEventQueueBuffer::isEmpty() const { +bool XWindowsEventQueueBuffer::isEmpty() const +{ Lock lock(&m_mutex); return (XPending(m_display) == 0); } -EventQueueTimer *XWindowsEventQueueBuffer::newTimer(double, bool) const { +EventQueueTimer *XWindowsEventQueueBuffer::newTimer(double, bool) const +{ return new EventQueueTimer; } -void XWindowsEventQueueBuffer::deleteTimer(EventQueueTimer *timer) const { +void XWindowsEventQueueBuffer::deleteTimer(EventQueueTimer *timer) const +{ delete timer; } -void XWindowsEventQueueBuffer::flush() { +void XWindowsEventQueueBuffer::flush() +{ // note -- m_mutex must be locked on entry // flush the posted event list to the X server diff --git a/src/lib/platform/XWindowsEventQueueBuffer.h b/src/lib/platform/XWindowsEventQueueBuffer.h index ae3f3bf97..94e24e095 100644 --- a/src/lib/platform/XWindowsEventQueueBuffer.h +++ b/src/lib/platform/XWindowsEventQueueBuffer.h @@ -31,19 +31,21 @@ class IEventQueue; //! Event queue buffer for X11 -class XWindowsEventQueueBuffer : public IEventQueueBuffer { +class XWindowsEventQueueBuffer : public IEventQueueBuffer +{ public: XWindowsEventQueueBuffer(Display *, Window, IEventQueue *events); XWindowsEventQueueBuffer(XWindowsEventQueueBuffer const &) = delete; XWindowsEventQueueBuffer(XWindowsEventQueueBuffer &&) = delete; virtual ~XWindowsEventQueueBuffer(); - XWindowsEventQueueBuffer & - operator=(XWindowsEventQueueBuffer const &) = delete; + XWindowsEventQueueBuffer &operator=(XWindowsEventQueueBuffer const &) = delete; XWindowsEventQueueBuffer &operator=(XWindowsEventQueueBuffer &&) = delete; // IEventQueueBuffer overrides - virtual void init() {} + virtual void init() + { + } virtual void waitForEvent(double timeout); virtual Type getEvent(Event &event, UInt32 &dataID); virtual bool addEvent(UInt32 dataID); diff --git a/src/lib/platform/XWindowsKeyState.cpp b/src/lib/platform/XWindowsKeyState.cpp index 79ac1f0d8..5044e9a87 100644 --- a/src/lib/platform/XWindowsKeyState.cpp +++ b/src/lib/platform/XWindowsKeyState.cpp @@ -47,28 +47,26 @@ static const size_t ModifiersFromXDefaultSize = 32; -XWindowsKeyState::XWindowsKeyState( - Display *display, bool useXKB, IEventQueue *events) - : KeyState( - events, AppUtil::instance().getKeyboardLayoutList(), - ClientApp::instance().args().m_enableLangSync), +XWindowsKeyState::XWindowsKeyState(Display *display, bool useXKB, IEventQueue *events) + : KeyState(events, AppUtil::instance().getKeyboardLayoutList(), ClientApp::instance().args().m_enableLangSync), m_display(display), - m_modifierFromX(ModifiersFromXDefaultSize) { + m_modifierFromX(ModifiersFromXDefaultSize) +{ init(display, useXKB); } -XWindowsKeyState::XWindowsKeyState( - Display *display, bool useXKB, IEventQueue *events, - deskflow::KeyMap &keyMap) +XWindowsKeyState::XWindowsKeyState(Display *display, bool useXKB, IEventQueue *events, deskflow::KeyMap &keyMap) : KeyState( - events, keyMap, AppUtil::instance().getKeyboardLayoutList(), - ClientApp::instance().args().m_enableLangSync), + events, keyMap, AppUtil::instance().getKeyboardLayoutList(), ClientApp::instance().args().m_enableLangSync + ), m_display(display), - m_modifierFromX(ModifiersFromXDefaultSize) { + m_modifierFromX(ModifiersFromXDefaultSize) +{ init(display, useXKB); } -XWindowsKeyState::~XWindowsKeyState() { +XWindowsKeyState::~XWindowsKeyState() +{ #if HAVE_XKB_EXTENSION if (m_xkb != NULL) { XkbFreeKeyboard(m_xkb, 0, True); @@ -76,14 +74,12 @@ XWindowsKeyState::~XWindowsKeyState() { #endif } -void XWindowsKeyState::init(Display *display, bool useXKB) { +void XWindowsKeyState::init(Display *display, bool useXKB) +{ XGetKeyboardControl(m_display, &m_keyboardState); #if HAVE_XKB_EXTENSION if (useXKB) { - m_xkb = XkbGetMap( - m_display, - XkbKeyActionsMask | XkbKeyBehaviorsMask | XkbAllClientInfoMask, - XkbUseCoreKbd); + m_xkb = XkbGetMap(m_display, XkbKeyActionsMask | XkbKeyBehaviorsMask | XkbAllClientInfoMask, XkbUseCoreKbd); } else { m_xkb = NULL; } @@ -91,7 +87,8 @@ void XWindowsKeyState::init(Display *display, bool useXKB) { setActiveGroup(kGroupPoll); } -void XWindowsKeyState::setActiveGroup(SInt32 group) { +void XWindowsKeyState::setActiveGroup(SInt32 group) +{ if (group == kGroupPollAndSet) { // we need to set the group to -1 in order for pollActiveGroup() to // actually poll for the group @@ -105,11 +102,13 @@ void XWindowsKeyState::setActiveGroup(SInt32 group) { } } -void XWindowsKeyState::setAutoRepeat(const XKeyboardState &state) { +void XWindowsKeyState::setAutoRepeat(const XKeyboardState &state) +{ m_keyboardState = state; } -KeyModifierMask XWindowsKeyState::mapModifiersFromX(unsigned int state) const { +KeyModifierMask XWindowsKeyState::mapModifiersFromX(unsigned int state) const +{ LOG((CLOG_DEBUG2 "mapping state: %i", state)); UInt32 offset = 8 * getGroupFromState(state); KeyModifierMask mask = 0; @@ -120,7 +119,8 @@ KeyModifierMask XWindowsKeyState::mapModifiersFromX(unsigned int state) const { LOG( (CLOG_ERR "m_modifierFromX is too small (%d) for the " "requested offset (%d)", - m_modifierFromX.size(), offset + i)); + m_modifierFromX.size(), offset + i) + ); } else { mask |= m_modifierFromX[offset + i]; } @@ -129,8 +129,8 @@ KeyModifierMask XWindowsKeyState::mapModifiersFromX(unsigned int state) const { return mask; } -bool XWindowsKeyState::mapModifiersToX( - KeyModifierMask mask, unsigned int &modifiers) const { +bool XWindowsKeyState::mapModifiersToX(KeyModifierMask mask, unsigned int &modifiers) const +{ modifiers = 0; for (SInt32 i = 0; i < kKeyModifierNumBits; ++i) { @@ -148,35 +148,34 @@ bool XWindowsKeyState::mapModifiersToX( return true; } -void XWindowsKeyState::mapKeyToKeycodes( - KeyID key, KeycodeList &keycodes) const { +void XWindowsKeyState::mapKeyToKeycodes(KeyID key, KeycodeList &keycodes) const +{ keycodes.clear(); - std::pair - range = m_keyCodeFromKey.equal_range(key); - for (KeyToKeyCodeMap::const_iterator i = range.first; i != range.second; - ++i) { + std::pair range = m_keyCodeFromKey.equal_range(key); + for (KeyToKeyCodeMap::const_iterator i = range.first; i != range.second; ++i) { keycodes.push_back(i->second); } } -bool XWindowsKeyState::fakeCtrlAltDel() { +bool XWindowsKeyState::fakeCtrlAltDel() +{ // pass keys through unchanged return false; } -KeyModifierMask XWindowsKeyState::pollActiveModifiers() const { +KeyModifierMask XWindowsKeyState::pollActiveModifiers() const +{ Window root = DefaultRootWindow(m_display), window; int xRoot, yRoot, xWindow, yWindow; unsigned int state = 0; - if (XQueryPointer( - m_display, root, &root, &window, &xRoot, &yRoot, &xWindow, &yWindow, - &state) == False) { + if (XQueryPointer(m_display, root, &root, &window, &xRoot, &yRoot, &xWindow, &yWindow, &state) == False) { state = 0; } return mapModifiersFromX(state); } -SInt32 XWindowsKeyState::pollActiveGroup() const { +SInt32 XWindowsKeyState::pollActiveGroup() const +{ // fixed condition where any group < -1 would have undetermined behaviour if (m_group >= 0) { return m_group; @@ -196,7 +195,8 @@ SInt32 XWindowsKeyState::pollActiveGroup() const { return 0; } -void XWindowsKeyState::pollPressedKeys(KeyButtonSet &pressedKeys) const { +void XWindowsKeyState::pollPressedKeys(KeyButtonSet &pressedKeys) const +{ char keys[32]; XQueryKeymap(m_display, keys); for (UInt32 i = 0; i < 32; ++i) { @@ -208,7 +208,8 @@ void XWindowsKeyState::pollPressedKeys(KeyButtonSet &pressedKeys) const { } } -void XWindowsKeyState::getKeyMap(deskflow::KeyMap &keyMap) { +void XWindowsKeyState::getKeyMap(deskflow::KeyMap &keyMap) +{ // get autorepeat info. we must use the global_auto_repeat told to // us because it may have modified by deskflow. int oldGlobalAutoRepeat = m_keyboardState.global_auto_repeat; @@ -217,10 +218,7 @@ void XWindowsKeyState::getKeyMap(deskflow::KeyMap &keyMap) { #if HAVE_XKB_EXTENSION if (m_xkb != NULL) { - if (XkbGetUpdatedMap( - m_display, - XkbKeyActionsMask | XkbKeyBehaviorsMask | XkbAllClientInfoMask, - m_xkb) == Success) { + if (XkbGetUpdatedMap(m_display, XkbKeyActionsMask | XkbKeyBehaviorsMask | XkbAllClientInfoMask, m_xkb) == Success) { updateKeysymMapXKB(keyMap); return; } @@ -229,13 +227,13 @@ void XWindowsKeyState::getKeyMap(deskflow::KeyMap &keyMap) { updateKeysymMap(keyMap); } -bool XWindowsKeyState::setCurrentLanguageWithDBus(SInt32 group) const { +bool XWindowsKeyState::setCurrentLanguageWithDBus(SInt32 group) const +{ QString service = "org.gnome.Shell"; QString path = "/org/gnome/Shell"; QString method = "Eval"; QString param = - "imports.ui.status.keyboard.getInputSourceManager().inputSources[" + - QString::number(group) + "].activate()"; + "imports.ui.status.keyboard.getInputSourceManager().inputSources[" + QString::number(group) + "].activate()"; auto bus = QDBusConnection::sessionBus(); if (!bus.isConnected()) { @@ -248,16 +246,15 @@ bool XWindowsKeyState::setCurrentLanguageWithDBus(SInt32 group) const { return false; } - QDBusPendingReply reply = - screenSaverInterface.call(method, param); + QDBusPendingReply reply = screenSaverInterface.call(method, param); reply.waitForFinished(); if (!reply.isValid()) { auto qerror = reply.error(); LOG( - (CLOG_WARN "keyboard layout fail %s : %s", - qerror.name().toStdString().c_str(), - qerror.message().toStdString().c_str())); + (CLOG_WARN "keyboard layout fail %s : %s", qerror.name().toStdString().c_str(), + qerror.message().toStdString().c_str()) + ); return true; } @@ -274,7 +271,8 @@ bool XWindowsKeyState::setCurrentLanguageWithDBus(SInt32 group) const { return true; } -void XWindowsKeyState::fakeKey(const Keystroke &keystroke) { +void XWindowsKeyState::fakeKey(const Keystroke &keystroke) +{ switch (keystroke.m_type) { case Keystroke::kButton: if (keystroke.m_data.m_button.m_repeat) { @@ -282,15 +280,14 @@ void XWindowsKeyState::fakeKey(const Keystroke &keystroke) { int i = (c >> 3); int b = 1 << (c & 7); if (m_keyboardState.global_auto_repeat == AutoRepeatModeOff || - (c != 113 && c != 116 && - (m_keyboardState.auto_repeats[i] & b) == 0)) { + (c != 113 && c != 116 && (m_keyboardState.auto_repeats[i] & b) == 0)) { LOG((CLOG_DEBUG1 " discard autorepeat")); break; } } XTestFakeKeyEvent( - m_display, keystroke.m_data.m_button.m_button, - keystroke.m_data.m_button.m_press ? True : False, CurrentTime); + m_display, keystroke.m_data.m_button.m_button, keystroke.m_data.m_button.m_press ? True : False, CurrentTime + ); break; case Keystroke::kGroup: @@ -307,9 +304,7 @@ void XWindowsKeyState::fakeKey(const Keystroke &keystroke) { #endif #if HAVE_XKB_EXTENSION if (m_xkb != NULL) { - if (XkbLockGroup( - m_display, XkbUseCoreKbd, keystroke.m_data.m_group.m_group) == - False) { + if (XkbLockGroup(m_display, XkbUseCoreKbd, keystroke.m_data.m_group.m_group) == False) { LOG((CLOG_DEBUG1 "xkb lock group request not sent")); } } else @@ -327,10 +322,8 @@ void XWindowsKeyState::fakeKey(const Keystroke &keystroke) { #if HAVE_XKB_EXTENSION if (m_xkb != NULL) { if (XkbLockGroup( - m_display, XkbUseCoreKbd, - getEffectiveGroup( - pollActiveGroup(), keystroke.m_data.m_group.m_group)) == - False) { + m_display, XkbUseCoreKbd, getEffectiveGroup(pollActiveGroup(), keystroke.m_data.m_group.m_group) + ) == False) { LOG((CLOG_DEBUG1 "xkb lock group request not sent")); } } else @@ -345,7 +338,8 @@ void XWindowsKeyState::fakeKey(const Keystroke &keystroke) { XFlush(m_display); } -void XWindowsKeyState::updateKeysymMap(deskflow::KeyMap &keyMap) { +void XWindowsKeyState::updateKeysymMap(deskflow::KeyMap &keyMap) +{ // there are up to 4 keysyms per keycode static const int maxKeysyms = 4; @@ -372,8 +366,7 @@ void XWindowsKeyState::updateKeysymMap(deskflow::KeyMap &keyMap) { // get the keyboard mapping for all keys int keysymsPerKeycode; - KeySym *allKeysyms = XGetKeyboardMapping( - m_display, minKeycode, numKeycodes, &keysymsPerKeycode); + KeySym *allKeysyms = XGetKeyboardMapping(m_display, minKeycode, numKeycodes, &keysymsPerKeycode); // it's more convenient to always have maxKeysyms KeySyms per key { @@ -381,8 +374,7 @@ void XWindowsKeyState::updateKeysymMap(deskflow::KeyMap &keyMap) { for (int i = 0; i < numKeycodes; ++i) { for (int j = 0; j < maxKeysyms; ++j) { if (j < keysymsPerKeycode) { - tmpKeysyms[maxKeysyms * i + j] = - allKeysyms[keysymsPerKeycode * i + j]; + tmpKeysyms[maxKeysyms * i + j] = allKeysyms[keysymsPerKeycode * i + j]; } else { tmpKeysyms[maxKeysyms * i + j] = NoSymbol; } @@ -412,8 +404,7 @@ void XWindowsKeyState::updateKeysymMap(deskflow::KeyMap &keyMap) { std::map modifierButtons; XModifierKeymap *modifiers = XGetModifierMapping(m_display); for (unsigned int i = 0; i < 8; ++i) { - const KeyCode *buttons = - modifiers->modifiermap + i * modifiers->max_keypermod; + const KeyCode *buttons = modifiers->modifiermap + i * modifiers->max_keypermod; for (int j = 0; j < modifiers->max_keypermod; ++j) { modifierButtons.insert(std::make_pair(buttons[j], i)); } @@ -447,16 +438,14 @@ void XWindowsKeyState::updateKeysymMap(deskflow::KeyMap &keyMap) { // if the keysyms in levels 2 or 3 exist and differ from levels // 0 and 1 then the key is sensitive AltGr (Mode_switch) - if ((keysyms[2] != NoSymbol && keysyms[2] != keysyms[0]) || - (keysyms[3] != NoSymbol && keysyms[2] != keysyms[1])) { + if ((keysyms[2] != NoSymbol && keysyms[2] != keysyms[0]) || (keysyms[3] != NoSymbol && keysyms[2] != keysyms[1])) { item.m_sensitive |= KeyModifierAltGr; } // check if the key is caps-lock sensitive. some systems only // provide one keysym for keys sensitive to caps-lock. if we // find that then fill in the missing keysym. - if (keysyms[0] != NoSymbol && keysyms[1] == NoSymbol && - keysyms[2] == NoSymbol && keysyms[3] == NoSymbol) { + if (keysyms[0] != NoSymbol && keysyms[1] == NoSymbol && keysyms[2] == NoSymbol && keysyms[3] == NoSymbol) { KeySym lKeysym, uKeysym; XConvertCase(keysyms[0], &lKeysym, &uKeysym); if (lKeysym != uKeysym) { @@ -467,13 +456,11 @@ void XWindowsKeyState::updateKeysymMap(deskflow::KeyMap &keyMap) { } else if (keysyms[0] != NoSymbol && keysyms[1] != NoSymbol) { KeySym lKeysym, uKeysym; XConvertCase(keysyms[0], &lKeysym, &uKeysym); - if (lKeysym != uKeysym && lKeysym == keysyms[0] && - uKeysym == keysyms[1]) { + if (lKeysym != uKeysym && lKeysym == keysyms[0] && uKeysym == keysyms[1]) { item.m_sensitive |= KeyModifierCapsLock; } else if (keysyms[2] != NoSymbol && keysyms[3] != NoSymbol) { XConvertCase(keysyms[2], &lKeysym, &uKeysym); - if (lKeysym != uKeysym && lKeysym == keysyms[2] && - uKeysym == keysyms[3]) { + if (lKeysym != uKeysym && lKeysym == keysyms[2] && uKeysym == keysyms[3]) { item.m_sensitive |= KeyModifierCapsLock; } } @@ -484,18 +471,14 @@ void XWindowsKeyState::updateKeysymMap(deskflow::KeyMap &keyMap) { // if it's sensitive to caps-lock. if ((item.m_sensitive & KeyModifierCapsLock) != 0) { item.m_sensitive |= KeyModifierShift; - } else if ( - (keysyms[0] != NoSymbol && keysyms[1] != NoSymbol && - keysyms[0] != keysyms[1]) || - (keysyms[2] != NoSymbol && keysyms[3] != NoSymbol && - keysyms[2] != keysyms[3])) { + } else if ((keysyms[0] != NoSymbol && keysyms[1] != NoSymbol && keysyms[0] != keysyms[1]) || + (keysyms[2] != NoSymbol && keysyms[3] != NoSymbol && keysyms[2] != keysyms[3])) { item.m_sensitive |= KeyModifierShift; } // key is sensitive to numlock if any keysym on it is - if (IsKeypadKey(keysyms[0]) || IsPrivateKeypadKey(keysyms[0]) || - IsKeypadKey(keysyms[1]) || IsPrivateKeypadKey(keysyms[1]) || - IsKeypadKey(keysyms[2]) || IsPrivateKeypadKey(keysyms[2]) || + if (IsKeypadKey(keysyms[0]) || IsPrivateKeypadKey(keysyms[0]) || IsKeypadKey(keysyms[1]) || + IsPrivateKeypadKey(keysyms[1]) || IsKeypadKey(keysyms[2]) || IsPrivateKeypadKey(keysyms[2]) || IsKeypadKey(keysyms[3]) || IsPrivateKeypadKey(keysyms[3])) { item.m_sensitive |= KeyModifierNumLock; } @@ -555,8 +538,7 @@ void XWindowsKeyState::updateKeysymMap(deskflow::KeyMap &keyMap) { // add capslock version of key is sensitive to capslock KeySym lKeysym, uKeysym; XConvertCase(keysyms[j], &lKeysym, &uKeysym); - if (lKeysym != uKeysym && lKeysym == keysyms[j - 1] && - uKeysym == keysyms[j]) { + if (lKeysym != uKeysym && lKeysym == keysyms[j - 1] && uKeysym == keysyms[j]) { item.m_required &= ~KeyModifierShift; item.m_required |= KeyModifierCapsLock; keyMap.addKeyEntry(item); @@ -580,7 +562,8 @@ void XWindowsKeyState::updateKeysymMap(deskflow::KeyMap &keyMap) { } #if HAVE_XKB_EXTENSION -void XWindowsKeyState::updateKeysymMapXKB(deskflow::KeyMap &keyMap) { +void XWindowsKeyState::updateKeysymMapXKB(deskflow::KeyMap &keyMap) +{ static const XkbKTMapEntryRec defMapEntry = { True, // active 0, // level @@ -588,7 +571,8 @@ void XWindowsKeyState::updateKeysymMapXKB(deskflow::KeyMap &keyMap) { 0, // mods.mask 0, // mods.real_mods 0 // mods.vmods - }}; + } + }; LOG((CLOG_DEBUG1 "xkb mapping")); @@ -654,8 +638,7 @@ void XWindowsKeyState::updateKeysymMapXKB(deskflow::KeyMap &keyMap) { // iterate over all shift levels for the button (including none) for (int j = -1; j < type->map_count; ++j) { - const XkbKTMapEntryRec *mapEntry = - ((j == -1) ? &defMapEntry : type->map + j); + const XkbKTMapEntryRec *mapEntry = ((j == -1) ? &defMapEntry : type->map + j); if (!mapEntry->active) { continue; } @@ -663,8 +646,7 @@ void XWindowsKeyState::updateKeysymMapXKB(deskflow::KeyMap &keyMap) { // set required modifiers for this item item.m_required = mapEntry->mods.mask; - if ((item.m_required & LockMask) != 0 && j != -1 && - type->preserve != NULL && + if ((item.m_required & LockMask) != 0 && j != -1 && type->preserve != NULL && (type->preserve[j].mask & LockMask) != 0) { // sensitive caps lock and we preserve caps-lock. // preserving caps-lock means we Xlib functions would @@ -695,10 +677,8 @@ void XWindowsKeyState::updateKeysymMapXKB(deskflow::KeyMap &keyMap) { if ((action->mods.flags & XkbSA_UseModMapMods) == 0) { modifierMask = action->mods.mask; } - } else if ( - action->type == XkbSA_SetGroup || - action->type == XkbSA_LatchGroup || - action->type == XkbSA_LockGroup) { + } else if (action->type == XkbSA_SetGroup || action->type == XkbSA_LatchGroup || + action->type == XkbSA_LockGroup) { // ignore group change key continue; } @@ -707,8 +687,7 @@ void XWindowsKeyState::updateKeysymMapXKB(deskflow::KeyMap &keyMap) { // VMware modifier hack if (useLastGoodModifiers) { - XKBModifierMap::const_iterator k = - m_lastGoodXKBModifiers.find(eGroup * 256 + keycode); + XKBModifierMap::const_iterator k = m_lastGoodXKBModifiers.find(eGroup * 256 + keycode); if (k != m_lastGoodXKBModifiers.end()) { // Use last known good modifier isModifier = true; @@ -718,8 +697,7 @@ void XWindowsKeyState::updateKeysymMapXKB(deskflow::KeyMap &keyMap) { } } else if (isModifier) { // Save known good modifier - XKBModifierInfo &info = - m_lastGoodXKBModifiers[eGroup * 256 + keycode]; + XKBModifierInfo &info = m_lastGoodXKBModifiers[eGroup * 256 + keycode]; info.m_level = level; info.m_mask = modifierMask; info.m_lock = item.m_lock; @@ -809,16 +787,15 @@ void XWindowsKeyState::updateKeysymMapXKB(deskflow::KeyMap &keyMap) { } #endif -void XWindowsKeyState::remapKeyModifiers( - KeyID id, SInt32 group, deskflow::KeyMap::KeyItem &item, void *vself) { +void XWindowsKeyState::remapKeyModifiers(KeyID id, SInt32 group, deskflow::KeyMap::KeyItem &item, void *vself) +{ XWindowsKeyState *self = static_cast(vself); - item.m_required = - self->mapModifiersFromX(XkbBuildCoreState(item.m_required, group)); - item.m_sensitive = - self->mapModifiersFromX(XkbBuildCoreState(item.m_sensitive, group)); + item.m_required = self->mapModifiersFromX(XkbBuildCoreState(item.m_required, group)); + item.m_sensitive = self->mapModifiersFromX(XkbBuildCoreState(item.m_sensitive, group)); } -bool XWindowsKeyState::hasModifiersXKB() const { +bool XWindowsKeyState::hasModifiersXKB() const +{ #if HAVE_XKB_EXTENSION // iterate over all keycodes for (int i = m_xkb->min_key_code; i <= m_xkb->max_key_code; ++i) { @@ -846,7 +823,8 @@ bool XWindowsKeyState::hasModifiersXKB() const { return false; } -int XWindowsKeyState::getEffectiveGroup(KeyCode keycode, int group) const { +int XWindowsKeyState::getEffectiveGroup(KeyCode keycode, int group) const +{ (void)keycode; #if HAVE_XKB_EXTENSION // get effective group for key @@ -875,7 +853,8 @@ int XWindowsKeyState::getEffectiveGroup(KeyCode keycode, int group) const { return group; } -UInt32 XWindowsKeyState::getGroupFromState(unsigned int state) const { +UInt32 XWindowsKeyState::getGroupFromState(unsigned int state) const +{ #if HAVE_XKB_EXTENSION if (m_xkb != NULL) { return XkbGroupForCoreState(state); diff --git a/src/lib/platform/XWindowsKeyState.h b/src/lib/platform/XWindowsKeyState.h index 2fb4602da..834fc0d60 100644 --- a/src/lib/platform/XWindowsKeyState.h +++ b/src/lib/platform/XWindowsKeyState.h @@ -42,14 +42,18 @@ class IEventQueue; /*! A key state for X Windows. */ -class XWindowsKeyState : public KeyState { +class XWindowsKeyState : public KeyState +{ public: typedef std::vector KeycodeList; - enum { kGroupPoll = -1, kGroupPollAndSet = -2 }; + enum + { + kGroupPoll = -1, + kGroupPollAndSet = -2 + }; XWindowsKeyState(Display *, bool useXKB, IEventQueue *events); - XWindowsKeyState( - Display *, bool useXKB, IEventQueue *events, deskflow::KeyMap &keyMap); + XWindowsKeyState(Display *, bool useXKB, IEventQueue *events, deskflow::KeyMap &keyMap); ~XWindowsKeyState(); //! @name modifiers @@ -124,11 +128,11 @@ private: */ bool setCurrentLanguageWithDBus(SInt32 group) const; - static void - remapKeyModifiers(KeyID, SInt32, deskflow::KeyMap::KeyItem &, void *); + static void remapKeyModifiers(KeyID, SInt32, deskflow::KeyMap::KeyItem &, void *); private: - struct XKBModifierInfo { + struct XKBModifierInfo + { public: unsigned char m_level; UInt32 m_mask; @@ -168,8 +172,17 @@ private: #ifdef TEST_ENV public: - SInt32 group() const { return m_group; } - void group(const SInt32 &group) { m_group = group; } - KeyModifierMaskList modifierFromX() const { return m_modifierFromX; } + SInt32 group() const + { + return m_group; + } + void group(const SInt32 &group) + { + m_group = group; + } + KeyModifierMaskList modifierFromX() const + { + return m_modifierFromX; + } #endif }; diff --git a/src/lib/platform/XWindowsPowerManager.cpp b/src/lib/platform/XWindowsPowerManager.cpp index 2f82a8664..adee06e17 100644 --- a/src/lib/platform/XWindowsPowerManager.cpp +++ b/src/lib/platform/XWindowsPowerManager.cpp @@ -21,8 +21,8 @@ namespace { -bool sleepInhibitCall( - bool state, ArchSystemUnix::InhibitScreenServices serviceID) { +bool sleepInhibitCall(bool state, ArchSystemUnix::InhibitScreenServices serviceID) +{ std::string error; if (!ArchSystemUnix::DBusInhibitScreenCall(serviceID, state, error)) { @@ -35,22 +35,23 @@ bool sleepInhibitCall( } // namespace -XWindowsPowerManager::~XWindowsPowerManager() { enableSleep(); } +XWindowsPowerManager::~XWindowsPowerManager() +{ + enableSleep(); +} -void XWindowsPowerManager::disableSleep() const { - if (!sleepInhibitCall( - true, ArchSystemUnix::InhibitScreenServices::kScreenSaver) && - !sleepInhibitCall( - true, ArchSystemUnix::InhibitScreenServices::kSessionManager)) { +void XWindowsPowerManager::disableSleep() const +{ + if (!sleepInhibitCall(true, ArchSystemUnix::InhibitScreenServices::kScreenSaver) && + !sleepInhibitCall(true, ArchSystemUnix::InhibitScreenServices::kSessionManager)) { LOG((CLOG_INFO "failed to prevent system from going to sleep")); } } -void XWindowsPowerManager::enableSleep() const { - if (!sleepInhibitCall( - false, ArchSystemUnix::InhibitScreenServices::kScreenSaver) && - !sleepInhibitCall( - false, ArchSystemUnix::InhibitScreenServices::kSessionManager)) { +void XWindowsPowerManager::enableSleep() const +{ + if (!sleepInhibitCall(false, ArchSystemUnix::InhibitScreenServices::kScreenSaver) && + !sleepInhibitCall(false, ArchSystemUnix::InhibitScreenServices::kSessionManager)) { LOG((CLOG_INFO "failed to enable system idle sleep")); } } diff --git a/src/lib/platform/XWindowsPowerManager.h b/src/lib/platform/XWindowsPowerManager.h index c6742c3ec..bf2e2c979 100644 --- a/src/lib/platform/XWindowsPowerManager.h +++ b/src/lib/platform/XWindowsPowerManager.h @@ -17,7 +17,8 @@ */ #pragma once -class XWindowsPowerManager { +class XWindowsPowerManager +{ public: XWindowsPowerManager() = default; ~XWindowsPowerManager(); diff --git a/src/lib/platform/XWindowsScreen.cpp b/src/lib/platform/XWindowsScreen.cpp index c9bf0283a..c41105f1b 100644 --- a/src/lib/platform/XWindowsScreen.cpp +++ b/src/lib/platform/XWindowsScreen.cpp @@ -50,7 +50,8 @@ #define XK_XKB_KEYS #include #if HAVE_X11_EXTENSIONS_DPMS_H -extern "C" { +extern "C" +{ #include } #endif @@ -61,7 +62,8 @@ extern "C" { #endif #if HAVE_X11_EXTENSIONS_XINERAMA_H // Xinerama.h may lack extern "C" for inclusion by C++ -extern "C" { +extern "C" +{ #include } #endif @@ -96,9 +98,9 @@ static int xi_opcode; XWindowsScreen *XWindowsScreen::s_screen = NULL; XWindowsScreen::XWindowsScreen( - const char *displayName, bool isPrimary, bool disableXInitThreads, - int mouseScrollDelta, IEventQueue *events, - deskflow::ClientScrollDirection scrollDirection) + const char *displayName, bool isPrimary, bool disableXInitThreads, int mouseScrollDelta, IEventQueue *events, + deskflow::ClientScrollDirection scrollDirection +) : PlatformScreen(events, scrollDirection), m_isPrimary(isPrimary), m_mouseScrollDelta(mouseScrollDelta), @@ -128,7 +130,8 @@ XWindowsScreen::XWindowsScreen( m_xkb(false), m_xi2detected(false), m_xrandr(false), - m_events(events) { + m_events(events) +{ assert(s_screen == NULL); if (mouseScrollDelta == 0) @@ -151,12 +154,9 @@ XWindowsScreen::XWindowsScreen( m_root = DefaultRootWindow(m_display); saveShape(); m_window = openWindow(); - m_screensaver = - new XWindowsScreenSaver(m_display, m_window, getEventTarget(), events); + m_screensaver = new XWindowsScreenSaver(m_display, m_window, getEventTarget(), events); m_keyState = new XWindowsKeyState(m_display, m_xkb, events, m_keyMap); - LOG( - (CLOG_DEBUG "screen shape: %d,%d %dx%d %s", m_x, m_y, m_w, m_h, - m_xinerama ? "(xinerama)" : "")); + LOG((CLOG_DEBUG "screen shape: %d,%d %dx%d %s", m_x, m_y, m_w, m_h, m_xinerama ? "(xinerama)" : "")); LOG((CLOG_DEBUG "window is 0x%08x", m_window)); } catch (...) { if (m_display != NULL) { @@ -198,15 +198,15 @@ XWindowsScreen::XWindowsScreen( // install event handlers m_events->adoptHandler( Event::kSystem, m_events->getSystemTarget(), - new TMethodEventJob( - this, &XWindowsScreen::handleSystemEvent)); + new TMethodEventJob(this, &XWindowsScreen::handleSystemEvent) + ); // install the platform event queue - m_events->adoptBuffer( - new XWindowsEventQueueBuffer(m_display, m_window, m_events)); + m_events->adoptBuffer(new XWindowsEventQueueBuffer(m_display, m_window, m_events)); } -XWindowsScreen::~XWindowsScreen() { +XWindowsScreen::~XWindowsScreen() +{ assert(s_screen != NULL); assert(m_display != NULL); @@ -235,7 +235,8 @@ XWindowsScreen::~XWindowsScreen() { s_screen = NULL; } -void XWindowsScreen::enable() { +void XWindowsScreen::enable() +{ if (!m_isPrimary) { // get the keyboard control state XKeyboardState keyControl; @@ -255,7 +256,8 @@ void XWindowsScreen::enable() { } } -void XWindowsScreen::disable() { +void XWindowsScreen::disable() +{ // release input context focus if (m_ic != NULL) { XUnsetICFocus(m_ic); @@ -271,7 +273,8 @@ void XWindowsScreen::disable() { } } -void XWindowsScreen::enter() { +void XWindowsScreen::enter() +{ screensaver(false); // release input context focus @@ -326,7 +329,8 @@ void XWindowsScreen::enter() { m_isOnScreen = true; } -bool XWindowsScreen::canLeave() { +bool XWindowsScreen::canLeave() +{ // raise and show the window, required to grab mouse and keyboard XMapRaised(m_display, m_window); @@ -334,7 +338,8 @@ bool XWindowsScreen::canLeave() { return !(m_isPrimary && !grabMouseAndKeyboard()); } -void XWindowsScreen::leave() { +void XWindowsScreen::leave() +{ if (!m_isPrimary) { // restore the previous keyboard auto-repeat state. if the user // changed the auto-repeat configuration while on the client then @@ -385,15 +390,15 @@ void XWindowsScreen::leave() { m_isOnScreen = false; } -bool XWindowsScreen::setClipboard(ClipboardID id, const IClipboard *clipboard) { +bool XWindowsScreen::setClipboard(ClipboardID id, const IClipboard *clipboard) +{ // fail if we don't have the requested clipboard if (m_clipboard[id] == NULL) { return false; } // get the actual time. ICCCM does not allow CurrentTime. - Time timestamp = - XWindowsUtil::getCurrentTime(m_display, m_clipboard[id]->getWindow()); + Time timestamp = XWindowsUtil::getCurrentTime(m_display, m_clipboard[id]->getWindow()); if (clipboard != NULL) { // save clipboard data @@ -409,24 +414,28 @@ bool XWindowsScreen::setClipboard(ClipboardID id, const IClipboard *clipboard) { } } -void XWindowsScreen::checkClipboards() { +void XWindowsScreen::checkClipboards() +{ // do nothing, we're always up to date } -void XWindowsScreen::openScreensaver(bool notify) { +void XWindowsScreen::openScreensaver(bool notify) +{ m_screensaverNotify = notify; if (!m_screensaverNotify) { m_screensaver->disable(); } } -void XWindowsScreen::closeScreensaver() { +void XWindowsScreen::closeScreensaver() +{ if (!m_screensaverNotify) { m_screensaver->enable(); } } -void XWindowsScreen::screensaver(bool activate) { +void XWindowsScreen::screensaver(bool activate) +{ if (activate) { m_screensaver->activate(); } else { @@ -434,43 +443,48 @@ void XWindowsScreen::screensaver(bool activate) { } } -void XWindowsScreen::resetOptions() { +void XWindowsScreen::resetOptions() +{ m_xtestIsXineramaUnaware = true; m_preserveFocus = false; } -void XWindowsScreen::setOptions(const OptionsList &options) { +void XWindowsScreen::setOptions(const OptionsList &options) +{ for (UInt32 i = 0, n = options.size(); i < n; i += 2) { if (options[i] == kOptionXTestXineramaUnaware) { m_xtestIsXineramaUnaware = (options[i + 1] != 0); - LOG( - (CLOG_DEBUG1 "library, XTest is Xinerama unaware %s", - m_xtestIsXineramaUnaware ? "true" : "false")); + LOG((CLOG_DEBUG1 "library, XTest is Xinerama unaware %s", m_xtestIsXineramaUnaware ? "true" : "false")); } else if (options[i] == kOptionScreenPreserveFocus) { m_preserveFocus = (options[i + 1] != 0); - LOG( - (CLOG_DEBUG1 "preserve focus: %s", - m_preserveFocus ? "true" : "false")); + LOG((CLOG_DEBUG1 "preserve focus: %s", m_preserveFocus ? "true" : "false")); } } } -void XWindowsScreen::setSequenceNumber(UInt32 seqNum) { +void XWindowsScreen::setSequenceNumber(UInt32 seqNum) +{ m_sequenceNumber = seqNum; } -bool XWindowsScreen::isPrimary() const { return m_isPrimary; } +bool XWindowsScreen::isPrimary() const +{ + return m_isPrimary; +} -String XWindowsScreen::getSecureInputApp() const { +String XWindowsScreen::getSecureInputApp() const +{ // ignore on Linux return ""; } -void *XWindowsScreen::getEventTarget() const { +void *XWindowsScreen::getEventTarget() const +{ return const_cast(this); } -bool XWindowsScreen::getClipboard(ClipboardID id, IClipboard *clipboard) const { +bool XWindowsScreen::getClipboard(ClipboardID id, IClipboard *clipboard) const +{ assert(clipboard != NULL); // fail if we don't have the requested clipboard @@ -479,28 +493,26 @@ bool XWindowsScreen::getClipboard(ClipboardID id, IClipboard *clipboard) const { } // get the actual time. ICCCM does not allow CurrentTime. - Time timestamp = - XWindowsUtil::getCurrentTime(m_display, m_clipboard[id]->getWindow()); + Time timestamp = XWindowsUtil::getCurrentTime(m_display, m_clipboard[id]->getWindow()); // copy the clipboard return Clipboard::copy(clipboard, m_clipboard[id], timestamp); } -void XWindowsScreen::getShape( - SInt32 &x, SInt32 &y, SInt32 &w, SInt32 &h) const { +void XWindowsScreen::getShape(SInt32 &x, SInt32 &y, SInt32 &w, SInt32 &h) const +{ x = m_x; y = m_y; w = m_w; h = m_h; } -void XWindowsScreen::getCursorPos(SInt32 &x, SInt32 &y) const { +void XWindowsScreen::getCursorPos(SInt32 &x, SInt32 &y) const +{ Window root, window; int mx, my, xWindow, yWindow; unsigned int mask; - if (XQueryPointer( - m_display, m_root, &root, &window, &mx, &my, &xWindow, &yWindow, - &mask)) { + if (XQueryPointer(m_display, m_root, &root, &window, &mx, &my, &xWindow, &yWindow, &mask)) { x = mx; y = my; } else { @@ -509,11 +521,13 @@ void XWindowsScreen::getCursorPos(SInt32 &x, SInt32 &y) const { } } -void XWindowsScreen::reconfigure(UInt32) { +void XWindowsScreen::reconfigure(UInt32) +{ // do nothing } -void XWindowsScreen::warpCursor(SInt32 x, SInt32 y) { +void XWindowsScreen::warpCursor(SInt32 x, SInt32 y) +{ // warp mouse warpCursorNoFlush(x, y); @@ -521,9 +535,8 @@ void XWindowsScreen::warpCursor(SInt32 x, SInt32 y) { XEvent event; while (XCheckMaskEvent( m_display, - PointerMotionMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | - KeyReleaseMask | KeymapStateMask, - &event)) { + PointerMotionMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask | KeymapStateMask, &event + )) { // do nothing } @@ -532,10 +545,10 @@ void XWindowsScreen::warpCursor(SInt32 x, SInt32 y) { m_yCursor = y; } -UInt32 XWindowsScreen::registerHotKey(KeyID key, KeyModifierMask mask) { +UInt32 XWindowsScreen::registerHotKey(KeyID key, KeyModifierMask mask) +{ // only allow certain modifiers - if ((mask & ~(KeyModifierShift | KeyModifierControl | KeyModifierAlt | - KeyModifierSuper)) != 0) { + if ((mask & ~(KeyModifierShift | KeyModifierControl | KeyModifierAlt | KeyModifierSuper)) != 0) { LOG((CLOG_DEBUG "could not map hotkey id=%04x mask=%04x", key, mask)); return 0; } @@ -578,13 +591,11 @@ UInt32 XWindowsScreen::registerHotKey(KeyID key, KeyModifierMask mask) { XWindowsUtil::ErrorLock lock(m_display, &err); if (key == kKeyNone) { static const KeyModifierMask s_hotKeyModifiers[] = { - KeyModifierShift, KeyModifierControl, KeyModifierAlt, KeyModifierMeta, - KeyModifierSuper}; + KeyModifierShift, KeyModifierControl, KeyModifierAlt, KeyModifierMeta, KeyModifierSuper + }; XModifierKeymap *modKeymap = XGetModifierMapping(m_display); - for (size_t j = 0; - j < sizeof(s_hotKeyModifiers) / sizeof(s_hotKeyModifiers[0]) && !err; - ++j) { + for (size_t j = 0; j < sizeof(s_hotKeyModifiers) / sizeof(s_hotKeyModifiers[0]) && !err; ++j) { // skip modifier if not in mask if ((mask & s_hotKeyModifiers[j]) == 0) { continue; @@ -640,14 +651,11 @@ UInt32 XWindowsScreen::registerHotKey(KeyID key, KeyModifierMask mask) { } // grab each key for the modifier - const KeyCode *modifiermap = - modKeymap->modifiermap + index * modKeymap->max_keypermod; + const KeyCode *modifiermap = modKeymap->modifiermap + index * modKeymap->max_keypermod; for (int k = 0; k < modKeymap->max_keypermod && !err; ++k) { KeyCode code = modifiermap[k]; if (modifiermap[k] != 0) { - XGrabKey( - m_display, code, modifiers2, m_root, False, GrabModeAsync, - GrabModeAsync); + XGrabKey(m_display, code, modifiers2, m_root, False, GrabModeAsync, GrabModeAsync); if (!err) { hotKeys.push_back(std::make_pair(code, modifiers2)); m_hotKeyToIDMap[HotKeyItem(code, modifiers2)] = id; @@ -676,8 +684,7 @@ UInt32 XWindowsScreen::registerHotKey(KeyID key, KeyModifierMask mask) { toggleModifiers[numToggleModifiers++] = modifier; } - for (XWindowsKeyState::KeycodeList::iterator j = keycodes.begin(); - j != keycodes.end() && !err; ++j) { + for (XWindowsKeyState::KeycodeList::iterator j = keycodes.begin(); j != keycodes.end() && !err; ++j) { for (size_t i = 0; i < (1u << numToggleModifiers); ++i) { // add toggle modifiers for index i unsigned int tmpModifiers = modifiers; @@ -692,9 +699,7 @@ UInt32 XWindowsScreen::registerHotKey(KeyID key, KeyModifierMask mask) { } // add grab - XGrabKey( - m_display, *j, tmpModifiers, m_root, False, GrabModeAsync, - GrabModeAsync); + XGrabKey(m_display, *j, tmpModifiers, m_root, False, GrabModeAsync, GrabModeAsync); if (!err) { hotKeys.push_back(std::make_pair(*j, tmpModifiers)); m_hotKeyToIDMap[HotKeyItem(*j, tmpModifiers)] = id; @@ -714,18 +719,21 @@ UInt32 XWindowsScreen::registerHotKey(KeyID key, KeyModifierMask mask) { m_oldHotKeyIDs.push_back(id); m_hotKeys.erase(id); LOG( - (CLOG_WARN "failed to register hotkey %s (id=%04x mask=%04x)", - deskflow::KeyMap::formatKey(key, mask).c_str(), key, mask)); + (CLOG_WARN "failed to register hotkey %s (id=%04x mask=%04x)", deskflow::KeyMap::formatKey(key, mask).c_str(), + key, mask) + ); return 0; } LOG( - (CLOG_DEBUG "registered hotkey %s (id=%04x mask=%04x) as id=%d", - deskflow::KeyMap::formatKey(key, mask).c_str(), key, mask, id)); + (CLOG_DEBUG "registered hotkey %s (id=%04x mask=%04x) as id=%d", deskflow::KeyMap::formatKey(key, mask).c_str(), + key, mask, id) + ); return id; } -void XWindowsScreen::unregisterHotKey(UInt32 id) { +void XWindowsScreen::unregisterHotKey(UInt32 id) +{ // look up hotkey HotKeyMap::iterator i = m_hotKeys.find(id); if (i == m_hotKeys.end()) { @@ -753,38 +761,42 @@ void XWindowsScreen::unregisterHotKey(UInt32 id) { m_oldHotKeyIDs.push_back(id); } -void XWindowsScreen::fakeInputBegin() { +void XWindowsScreen::fakeInputBegin() +{ // FIXME -- not implemented } -void XWindowsScreen::fakeInputEnd() { +void XWindowsScreen::fakeInputEnd() +{ // FIXME -- not implemented } -SInt32 XWindowsScreen::getJumpZoneSize() const { return 1; } +SInt32 XWindowsScreen::getJumpZoneSize() const +{ + return 1; +} -bool XWindowsScreen::isAnyMouseButtonDown(UInt32 &buttonID) const { +bool XWindowsScreen::isAnyMouseButtonDown(UInt32 &buttonID) const +{ // query the pointer to get the button state Window root, window; int xRoot, yRoot, xWindow, yWindow; unsigned int state; - if (XQueryPointer( - m_display, m_root, &root, &window, &xRoot, &yRoot, &xWindow, &yWindow, - &state)) { - return ( - (state & (Button1Mask | Button2Mask | Button3Mask | Button4Mask | - Button5Mask)) != 0); + if (XQueryPointer(m_display, m_root, &root, &window, &xRoot, &yRoot, &xWindow, &yWindow, &state)) { + return ((state & (Button1Mask | Button2Mask | Button3Mask | Button4Mask | Button5Mask)) != 0); } return false; } -void XWindowsScreen::getCursorCenter(SInt32 &x, SInt32 &y) const { +void XWindowsScreen::getCursorCenter(SInt32 &x, SInt32 &y) const +{ x = m_xCenter; y = m_yCenter; } -void XWindowsScreen::fakeMouseButton(ButtonID button, bool press) { +void XWindowsScreen::fakeMouseButton(ButtonID button, bool press) +{ const unsigned int xButton = mapButtonToX(button); if (xButton > 0 && xButton < 11) { XTestFakeButtonEvent(m_display, xButton, press ? True : False, CurrentTime); @@ -792,23 +804,25 @@ void XWindowsScreen::fakeMouseButton(ButtonID button, bool press) { } } -void XWindowsScreen::fakeMouseMove(SInt32 x, SInt32 y) { +void XWindowsScreen::fakeMouseMove(SInt32 x, SInt32 y) +{ if (m_xinerama && m_xtestIsXineramaUnaware) { XWarpPointer(m_display, None, m_root, 0, 0, 0, 0, x, y); } else { - XTestFakeMotionEvent( - m_display, DefaultScreen(m_display), x, y, CurrentTime); + XTestFakeMotionEvent(m_display, DefaultScreen(m_display), x, y, CurrentTime); } XFlush(m_display); } -void XWindowsScreen::fakeMouseRelativeMove(SInt32 dx, SInt32 dy) const { +void XWindowsScreen::fakeMouseRelativeMove(SInt32 dx, SInt32 dy) const +{ // FIXME -- ignore xinerama for now XTestFakeRelativeMotionEvent(m_display, dx, dy, CurrentTime); XFlush(m_display); } -void XWindowsScreen::fakeMouseWheel(SInt32, SInt32 yDelta) const { +void XWindowsScreen::fakeMouseWheel(SInt32, SInt32 yDelta) const +{ // XXX -- support x-axis scrolling if (yDelta == 0) { return; @@ -817,8 +831,7 @@ void XWindowsScreen::fakeMouseWheel(SInt32, SInt32 yDelta) const { yDelta = mapClientScrollDirection(yDelta); // choose button depending on rotation direction - const unsigned int xButton = - mapButtonToX(static_cast((yDelta >= 0) ? -1 : -2)); + const unsigned int xButton = mapButtonToX(static_cast((yDelta >= 0) ? -1 : -2)); if (xButton == 0) { // If we get here, then the XServer does not support the scroll // wheel buttons, so send PageUp/PageDown keystrokes instead. @@ -842,9 +855,7 @@ void XWindowsScreen::fakeMouseWheel(SInt32, SInt32 yDelta) const { } if (yDelta < m_mouseScrollDelta) { - LOG( - (CLOG_WARN "wheel scroll delta (%d) smaller than threshold (%d)", - yDelta, m_mouseScrollDelta)); + LOG((CLOG_WARN "wheel scroll delta (%d) smaller than threshold (%d)", yDelta, m_mouseScrollDelta)); } // send as many clicks as necessary @@ -855,7 +866,8 @@ void XWindowsScreen::fakeMouseWheel(SInt32, SInt32 yDelta) const { XFlush(m_display); } -Display *XWindowsScreen::openDisplay(const char *displayName) { +Display *XWindowsScreen::openDisplay(const char *displayName) +{ // get the DISPLAY if (displayName == NULL) { displayName = getenv("DISPLAY"); @@ -874,9 +886,7 @@ Display *XWindowsScreen::openDisplay(const char *displayName) { // verify the availability of the XTest extension if (!m_isPrimary) { int majorOpcode, firstEvent, firstError; - if (!XQueryExtension( - display, XTestExtensionName, &majorOpcode, &firstEvent, - &firstError)) { + if (!XQueryExtension(display, XTestExtensionName, &majorOpcode, &firstEvent, &firstError)) { LOG((CLOG_ERR "the XTest extension is not available")); XCloseDisplay(display); throw XScreenOpenFailure(); @@ -889,14 +899,10 @@ Display *XWindowsScreen::openDisplay(const char *displayName) { int major = XkbMajorVersion, minor = XkbMinorVersion; if (XkbLibraryVersion(&major, &minor)) { int opcode, firstError; - if (XkbQueryExtension( - display, &opcode, &m_xkbEventBase, &firstError, &major, &minor)) { + if (XkbQueryExtension(display, &opcode, &m_xkbEventBase, &firstError, &major, &minor)) { m_xkb = true; - XkbSelectEvents( - display, XkbUseCoreKbd, XkbMapNotifyMask, XkbMapNotifyMask); - XkbSelectEventDetails( - display, XkbUseCoreKbd, XkbStateNotifyMask, XkbGroupStateMask, - XkbGroupStateMask); + XkbSelectEvents(display, XkbUseCoreKbd, XkbMapNotifyMask, XkbMapNotifyMask); + XkbSelectEventDetails(display, XkbUseCoreKbd, XkbStateNotifyMask, XkbGroupStateMask, XkbGroupStateMask); } } } @@ -908,16 +914,15 @@ Display *XWindowsScreen::openDisplay(const char *displayName) { m_xrandr = XRRQueryExtension(display, &m_xrandrEventBase, &dummyError); if (m_xrandr) { // enable XRRScreenChangeNotifyEvent - XRRSelectInput( - display, DefaultRootWindow(display), - RRScreenChangeNotifyMask | RRCrtcChangeNotifyMask); + XRRSelectInput(display, DefaultRootWindow(display), RRScreenChangeNotifyMask | RRCrtcChangeNotifyMask); } #endif return display; } -void XWindowsScreen::saveShape() { +void XWindowsScreen::saveShape() +{ // get shape of default screen m_x = 0; m_y = 0; @@ -945,8 +950,7 @@ void XWindowsScreen::saveShape() { m_xinerama = false; #if HAVE_X11_EXTENSIONS_XINERAMA_H int eventBase, errorBase; - if (XineramaQueryExtension(m_display, &eventBase, &errorBase) && - XineramaIsActive(m_display)) { + if (XineramaQueryExtension(m_display, &eventBase, &errorBase) && XineramaIsActive(m_display)) { int numScreens; XineramaScreenInfo *screens; screens = XineramaQueryScreens(m_display, &numScreens); @@ -962,7 +966,8 @@ void XWindowsScreen::saveShape() { #endif } -void XWindowsScreen::setShape(SInt32 width, SInt32 height) { +void XWindowsScreen::setShape(SInt32 width, SInt32 height) +{ // set shape m_x = 0; m_y = 0; @@ -990,8 +995,7 @@ void XWindowsScreen::setShape(SInt32 width, SInt32 height) { m_xinerama = false; #if HAVE_X11_EXTENSIONS_XINERAMA_H int eventBase, errorBase; - if ((XineramaQueryExtension(m_display, &eventBase, &errorBase) != 0) && - (XineramaIsActive(m_display) != 0)) { + if ((XineramaQueryExtension(m_display, &eventBase, &errorBase) != 0) && (XineramaIsActive(m_display) != 0)) { int numScreens; XineramaScreenInfo *screens; screens = XineramaQueryScreens(m_display, &numScreens); @@ -1007,7 +1011,8 @@ void XWindowsScreen::setShape(SInt32 width, SInt32 height) { #endif } -Window XWindowsScreen::openWindow() const { +Window XWindowsScreen::openWindow() const +{ // default window attributes. we don't want the window manager // messing with our window and we don't want the cursor to be // visible inside the window. @@ -1022,9 +1027,8 @@ Window XWindowsScreen::openWindow() const { // grab window attributes. this window is used to capture user // input when the user is focused on another client. it covers // the whole screen. - attr.event_mask = PointerMotionMask | ButtonPressMask | ButtonReleaseMask | - KeyPressMask | KeyReleaseMask | KeymapStateMask | - PropertyChangeMask; + attr.event_mask = PointerMotionMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask | + KeymapStateMask | PropertyChangeMask; x = m_x; y = m_y; w = m_w; @@ -1046,14 +1050,16 @@ Window XWindowsScreen::openWindow() const { // create and return the window Window window = XCreateWindow( m_display, m_root, x, y, w, h, 0, 0, InputOnly, CopyFromParent, - CWDontPropagate | CWEventMask | CWOverrideRedirect | CWCursor, &attr); + CWDontPropagate | CWEventMask | CWOverrideRedirect | CWCursor, &attr + ); if (window == None) { throw XScreenOpenFailure(); } return window; } -void XWindowsScreen::openIM() { +void XWindowsScreen::openIM() +{ // open the input methods XIM im = XOpenIM(m_display, NULL, NULL, NULL); if (im == NULL) { @@ -1064,8 +1070,7 @@ void XWindowsScreen::openIM() { // find the appropriate style. deskflow supports XIMPreeditNothing // only at the moment. XIMStyles *styles; - if (XGetIMValues(im, XNQueryInputStyle, &styles, NULL) != NULL || - styles == NULL) { + if (XGetIMValues(im, XNQueryInputStyle, &styles, NULL) != NULL || styles == NULL) { LOG((CLOG_WARN "cannot get IM styles")); XCloseIM(im); return; @@ -1117,30 +1122,35 @@ void XWindowsScreen::openIM() { XSelectInput(m_display, m_root, StructureNotifyMask); } -void XWindowsScreen::sendEvent(Event::Type type, void *data) { +void XWindowsScreen::sendEvent(Event::Type type, void *data) +{ m_events->addEvent(Event(type, getEventTarget(), data)); } -void XWindowsScreen::sendClipboardEvent(Event::Type type, ClipboardID id) { +void XWindowsScreen::sendClipboardEvent(Event::Type type, ClipboardID id) +{ ClipboardInfo *info = (ClipboardInfo *)malloc(sizeof(ClipboardInfo)); info->m_id = id; info->m_sequenceNumber = m_sequenceNumber; sendEvent(type, info); } -IKeyState *XWindowsScreen::getKeyState() const { return m_keyState; } +IKeyState *XWindowsScreen::getKeyState() const +{ + return m_keyState; +} -Bool XWindowsScreen::findKeyEvent(Display *, XEvent *xevent, XPointer arg) { +Bool XWindowsScreen::findKeyEvent(Display *, XEvent *xevent, XPointer arg) +{ KeyEventFilter *filter = reinterpret_cast(arg); - return (xevent->type == filter->m_event && - xevent->xkey.window == filter->m_window && - xevent->xkey.time == filter->m_time && - xevent->xkey.keycode == filter->m_keycode) + return (xevent->type == filter->m_event && xevent->xkey.window == filter->m_window && + xevent->xkey.time == filter->m_time && xevent->xkey.keycode == filter->m_keycode) ? True : False; } -void XWindowsScreen::handleSystemEvent(const Event &event, void *) { +void XWindowsScreen::handleSystemEvent(const Event &event, void *) +{ XEvent *xevent = static_cast(event.getData()); assert(xevent != NULL); @@ -1158,10 +1168,7 @@ void XWindowsScreen::handleSystemEvent(const Event &event, void *) { filter.m_time = xevent->xkey.time; filter.m_keycode = xevent->xkey.keycode; XEvent xevent2; - isRepeat = - (XCheckIfEvent( - m_display, &xevent2, &XWindowsScreen::findKeyEvent, - (XPointer)&filter) == True); + isRepeat = (XCheckIfEvent(m_display, &xevent2, &XWindowsScreen::findKeyEvent, (XPointer)&filter) == True); } if (xevent->type == KeyPress || xevent->type == KeyRelease) { @@ -1195,8 +1202,7 @@ void XWindowsScreen::handleSystemEvent(const Event &event, void *) { // KeyRelease) so we have a keycode for a synthesized KeyPress. if (xevent->type == KeyPress && xevent->xkey.keycode != 0) { m_lastKeycode = xevent->xkey.keycode; - } else if ( - xevent->type == KeyRelease && xevent->xkey.keycode == m_lastKeycode) { + } else if (xevent->type == KeyRelease && xevent->xkey.keycode == m_lastKeycode) { m_lastKeycode = 0; } @@ -1211,9 +1217,7 @@ void XWindowsScreen::handleSystemEvent(const Event &event, void *) { // discard matching key releases for key presses that were // filtered and remove them from our filtered list. - else if ( - xevent->type == KeyRelease && - m_filtered.count(xevent->xkey.keycode) > 0) { + else if (xevent->type == KeyRelease && m_filtered.count(xevent->xkey.keycode) > 0) { m_filtered.erase(xevent->xkey.keycode); return; } @@ -1229,8 +1233,7 @@ void XWindowsScreen::handleSystemEvent(const Event &event, void *) { if (m_xi2detected) { // Process RawMotion XGenericEventCookie *cookie = (XGenericEventCookie *)&xevent->xcookie; - if (XGetEventData(m_display, cookie) && cookie->type == GenericEvent && - cookie->extension == xi_opcode) { + if (XGetEventData(m_display, cookie) && cookie->type == GenericEvent && cookie->extension == xi_opcode) { if (cookie->evtype == XI_RawMotion) { // Get current pointer's position Window root, child; @@ -1242,8 +1245,9 @@ void XWindowsScreen::handleSystemEvent(const Event &event, void *) { /* xmotion's time, state and is_hint are not used */ unsigned int msk; xmotion.same_screen = XQueryPointer( - m_display, m_root, &xmotion.root, &xmotion.subwindow, - &xmotion.x_root, &xmotion.y_root, &xmotion.x, &xmotion.y, &msk); + m_display, m_root, &xmotion.root, &xmotion.subwindow, &xmotion.x_root, &xmotion.y_root, &xmotion.x, + &xmotion.y, &msk + ); onMouseMove(xmotion); XFreeEventData(m_display, cookie); return; @@ -1291,8 +1295,7 @@ void XWindowsScreen::handleSystemEvent(const Event &event, void *) { // retrieval methods. we'll just delete the property // with the data (satisfying the usual ICCCM protocol). if (xevent->xselection.property != None) { - XDeleteProperty( - m_display, xevent->xselection.requestor, xevent->xselection.property); + XDeleteProperty(m_display, xevent->xselection.requestor, xevent->xselection.property); } break; @@ -1301,9 +1304,9 @@ void XWindowsScreen::handleSystemEvent(const Event &event, void *) { ClipboardID id = getClipboardID(xevent->xselectionrequest.selection); if (id != kClipboardEnd) { m_clipboard[id]->addRequest( - xevent->xselectionrequest.owner, xevent->xselectionrequest.requestor, - xevent->xselectionrequest.target, xevent->xselectionrequest.time, - xevent->xselectionrequest.property); + xevent->xselectionrequest.owner, xevent->xselectionrequest.requestor, xevent->xselectionrequest.target, + xevent->xselectionrequest.time, xevent->xselectionrequest.property + ); return; } } break; @@ -1311,9 +1314,7 @@ void XWindowsScreen::handleSystemEvent(const Event &event, void *) { case PropertyNotify: // property delete may be part of a selection conversion if (xevent->xproperty.state == PropertyDelete) { - processClipboardRequest( - xevent->xproperty.window, xevent->xproperty.time, - xevent->xproperty.atom); + processClipboardRequest(xevent->xproperty.window, xevent->xproperty.time, xevent->xproperty.atom); } break; @@ -1381,8 +1382,7 @@ void XWindowsScreen::handleSystemEvent(const Event &event, void *) { if (m_xrandr) { if (xevent->type == m_xrandrEventBase + RRScreenChangeNotify || xevent->type == m_xrandrEventBase + RRNotify && - reinterpret_cast(xevent)->subtype == - RRNotify_CrtcChange) { + reinterpret_cast(xevent)->subtype == RRNotify_CrtcChange) { LOG((CLOG_INFO "either XRRScreenChangeNotifyEvent or " "RRNotify_CrtcChange received")); @@ -1411,17 +1411,15 @@ void XWindowsScreen::handleSystemEvent(const Event &event, void *) { } } -void XWindowsScreen::onKeyPress(XKeyEvent &xkey) { - LOG( - (CLOG_DEBUG1 "event: KeyPress code=%d, state=0x%04x", xkey.keycode, - xkey.state)); +void XWindowsScreen::onKeyPress(XKeyEvent &xkey) +{ + LOG((CLOG_DEBUG1 "event: KeyPress code=%d, state=0x%04x", xkey.keycode, xkey.state)); const KeyModifierMask mask = m_keyState->mapModifiersFromX(xkey.state); KeyID key = mapKeyFromX(&xkey); if (key != kKeyNone) { // check for ctrl+alt+del emulation if ((key == kKeyPause || key == kKeyBreak) && - (mask & (KeyModifierControl | KeyModifierAlt)) == - (KeyModifierControl | KeyModifierAlt)) { + (mask & (KeyModifierControl | KeyModifierAlt)) == (KeyModifierControl | KeyModifierAlt)) { // pretend it's ctrl+alt+del LOG((CLOG_DEBUG "emulate ctrl+alt+del")); key = kKeyDelete; @@ -1442,27 +1440,25 @@ void XWindowsScreen::onKeyPress(XKeyEvent &xkey) { } // handle key - m_keyState->sendKeyEvent( - getEventTarget(), true, false, key, mask, 1, keycode); + m_keyState->sendKeyEvent(getEventTarget(), true, false, key, mask, 1, keycode); // do fake release if this is a fake press if (isFake) { - m_keyState->sendKeyEvent( - getEventTarget(), false, false, key, mask, 1, keycode); + m_keyState->sendKeyEvent(getEventTarget(), false, false, key, mask, 1, keycode); } } else { LOG((CLOG_DEBUG1 "can't map keycode to key id")); } } -void XWindowsScreen::onKeyRelease(XKeyEvent &xkey, bool isRepeat) { +void XWindowsScreen::onKeyRelease(XKeyEvent &xkey, bool isRepeat) +{ const KeyModifierMask mask = m_keyState->mapModifiersFromX(xkey.state); KeyID key = mapKeyFromX(&xkey); if (key != kKeyNone) { // check for ctrl+alt+del emulation if ((key == kKeyPause || key == kKeyBreak) && - (mask & (KeyModifierControl | KeyModifierAlt)) == - (KeyModifierControl | KeyModifierAlt)) { + (mask & (KeyModifierControl | KeyModifierAlt)) == (KeyModifierControl | KeyModifierAlt)) { // pretend it's ctrl+alt+del and ignore autorepeat LOG((CLOG_DEBUG "emulate ctrl+alt+del")); key = kKeyDelete; @@ -1472,29 +1468,23 @@ void XWindowsScreen::onKeyRelease(XKeyEvent &xkey, bool isRepeat) { KeyButton keycode = static_cast(xkey.keycode); if (!isRepeat) { // no press event follows so it's a plain release - LOG( - (CLOG_DEBUG1 "event: KeyRelease code=%d, state=0x%04x", keycode, - xkey.state)); - m_keyState->sendKeyEvent( - getEventTarget(), false, false, key, mask, 1, keycode); + LOG((CLOG_DEBUG1 "event: KeyRelease code=%d, state=0x%04x", keycode, xkey.state)); + m_keyState->sendKeyEvent(getEventTarget(), false, false, key, mask, 1, keycode); } else { // found a press event following so it's a repeat. // we could attempt to count the already queued // repeats but we'll just send a repeat of 1. // note that we discard the press event. - LOG( - (CLOG_DEBUG1 "event: repeat code=%d, state=0x%04x", keycode, - xkey.state)); - m_keyState->sendKeyEvent( - getEventTarget(), false, true, key, mask, 1, keycode); + LOG((CLOG_DEBUG1 "event: repeat code=%d, state=0x%04x", keycode, xkey.state)); + m_keyState->sendKeyEvent(getEventTarget(), false, true, key, mask, 1, keycode); } } } -bool XWindowsScreen::onHotKey(XKeyEvent &xkey, bool isRepeat) { +bool XWindowsScreen::onHotKey(XKeyEvent &xkey, bool isRepeat) +{ // find the hot key id - HotKeyToIDMap::const_iterator i = - m_hotKeyToIDMap.find(HotKeyItem(xkey.keycode, xkey.state)); + HotKeyToIDMap::const_iterator i = m_hotKeyToIDMap.find(HotKeyItem(xkey.keycode, xkey.state)); if (i == m_hotKeyToIDMap.end()) { return false; } @@ -1511,31 +1501,28 @@ bool XWindowsScreen::onHotKey(XKeyEvent &xkey, bool isRepeat) { // generate event (ignore key repeats) if (!isRepeat) { - m_events->addEvent( - Event(type, getEventTarget(), HotKeyInfo::alloc(i->second))); + m_events->addEvent(Event(type, getEventTarget(), HotKeyInfo::alloc(i->second))); } return true; } -void XWindowsScreen::onMousePress(const XButtonEvent &xbutton) { +void XWindowsScreen::onMousePress(const XButtonEvent &xbutton) +{ LOG((CLOG_DEBUG1 "event: ButtonPress button=%d", xbutton.button)); ButtonID button = mapButtonFromX(&xbutton); KeyModifierMask mask = m_keyState->mapModifiersFromX(xbutton.state); if (button != kButtonNone) { - sendEvent( - m_events->forIPrimaryScreen().buttonDown(), - ButtonInfo::alloc(button, mask)); + sendEvent(m_events->forIPrimaryScreen().buttonDown(), ButtonInfo::alloc(button, mask)); } } -void XWindowsScreen::onMouseRelease(const XButtonEvent &xbutton) { +void XWindowsScreen::onMouseRelease(const XButtonEvent &xbutton) +{ LOG((CLOG_DEBUG1 "event: ButtonRelease button=%d", xbutton.button)); ButtonID button = mapButtonFromX(&xbutton); KeyModifierMask mask = m_keyState->mapModifiersFromX(xbutton.state); if (button != kButtonNone) { - sendEvent( - m_events->forIPrimaryScreen().buttonUp(), - ButtonInfo::alloc(button, mask)); + sendEvent(m_events->forIPrimaryScreen().buttonUp(), ButtonInfo::alloc(button, mask)); } else if (xbutton.button == 4) { // wheel forward (away from user) sendEvent(m_events->forIPrimaryScreen().wheel(), WheelInfo::alloc(0, 120)); @@ -1546,9 +1533,9 @@ void XWindowsScreen::onMouseRelease(const XButtonEvent &xbutton) { // XXX -- support x-axis scrolling } -void XWindowsScreen::onMouseMove(const XMotionEvent &xmotion) { - LOG(( - CLOG_DEBUG2 "event: MotionNotify %d,%d", xmotion.x_root, xmotion.y_root)); +void XWindowsScreen::onMouseMove(const XMotionEvent &xmotion) +{ + LOG((CLOG_DEBUG2 "event: MotionNotify %d,%d", xmotion.x_root, xmotion.y_root)); // compute motion delta (relative to the last known // mouse position) @@ -1577,9 +1564,7 @@ void XWindowsScreen::onMouseMove(const XMotionEvent &xmotion) { cntr = 0; } else if (m_isOnScreen) { // motion on primary screen - sendEvent( - m_events->forIPrimaryScreen().motionOnPrimary(), - MotionInfo::alloc(m_xCursor, m_yCursor)); + sendEvent(m_events->forIPrimaryScreen().motionOnPrimary(), MotionInfo::alloc(m_xCursor, m_yCursor)); } else { // motion on secondary screen. warp mouse back to // center. @@ -1594,10 +1579,8 @@ void XWindowsScreen::onMouseMove(const XMotionEvent &xmotion) { // it we only warp when the mouse has moved more // than s_size pixels from the center. static const SInt32 s_size = 32; - if (xmotion.x_root - m_xCenter < -s_size || - xmotion.x_root - m_xCenter > s_size || - xmotion.y_root - m_yCenter < -s_size || - xmotion.y_root - m_yCenter > s_size) { + if (xmotion.x_root - m_xCenter < -s_size || xmotion.x_root - m_xCenter > s_size || + xmotion.y_root - m_yCenter < -s_size || xmotion.y_root - m_yCenter > s_size) { warpCursorNoFlush(m_xCenter, m_yCenter); } @@ -1608,14 +1591,13 @@ void XWindowsScreen::onMouseMove(const XMotionEvent &xmotion) { // warping to the primary screen's enter position, // effectively overriding it. if (x != 0 || y != 0) { - sendEvent( - m_events->forIPrimaryScreen().motionOnSecondary(), - MotionInfo::alloc(x, y)); + sendEvent(m_events->forIPrimaryScreen().motionOnSecondary(), MotionInfo::alloc(x, y)); } } } -Cursor XWindowsScreen::createBlankCursor() const { +Cursor XWindowsScreen::createBlankCursor() const +{ // this seems just a bit more complicated than really necessary // get the closet cursor size to 1x1 @@ -1641,8 +1623,7 @@ Cursor XWindowsScreen::createBlankCursor() const { color.flags = DoRed | DoGreen | DoBlue; // make cursor from bitmap - Cursor cursor = - XCreatePixmapCursor(m_display, bitmap, bitmap, &color, &color, 0, 0); + Cursor cursor = XCreatePixmapCursor(m_display, bitmap, bitmap, &color, &color, 0, 0); // don't need bitmap or the data anymore delete[] data; @@ -1651,28 +1632,28 @@ Cursor XWindowsScreen::createBlankCursor() const { return cursor; } -ClipboardID XWindowsScreen::getClipboardID(Atom selection) const { +ClipboardID XWindowsScreen::getClipboardID(Atom selection) const +{ for (ClipboardID id = 0; id < kClipboardEnd; ++id) { - if (m_clipboard[id] != NULL && - m_clipboard[id]->getSelection() == selection) { + if (m_clipboard[id] != NULL && m_clipboard[id]->getSelection() == selection) { return id; } } return kClipboardEnd; } -void XWindowsScreen::processClipboardRequest( - Window requestor, Time time, Atom property) { +void XWindowsScreen::processClipboardRequest(Window requestor, Time time, Atom property) +{ // check every clipboard until one returns success for (ClipboardID id = 0; id < kClipboardEnd; ++id) { - if (m_clipboard[id] != NULL && - m_clipboard[id]->processRequest(requestor, time, property)) { + if (m_clipboard[id] != NULL && m_clipboard[id]->processRequest(requestor, time, property)) { break; } } } -void XWindowsScreen::destroyClipboardRequest(Window requestor) { +void XWindowsScreen::destroyClipboardRequest(Window requestor) +{ // check every clipboard until one returns success for (ClipboardID id = 0; id < kClipboardEnd; ++id) { if (m_clipboard[id] != NULL && m_clipboard[id]->destroyRequest(requestor)) { @@ -1681,7 +1662,8 @@ void XWindowsScreen::destroyClipboardRequest(Window requestor) { } } -void XWindowsScreen::onError() { +void XWindowsScreen::onError() +{ // prevent further access to the X display m_events->adoptBuffer(NULL); m_screensaver->destroy(); @@ -1701,7 +1683,8 @@ void XWindowsScreen::onError() { // don't use X11. on error, we'd switch to the latter. } -int XWindowsScreen::ioErrorHandler(Display *) { +int XWindowsScreen::ioErrorHandler(Display *) +{ // the display has disconnected, probably because X is shutting // down. X forces us to exit at this point which is annoying. // we'll pretend as if we won't exit so we try to make sure we @@ -1711,7 +1694,8 @@ int XWindowsScreen::ioErrorHandler(Display *) { return 0; } -void XWindowsScreen::selectEvents(Window w) const { +void XWindowsScreen::selectEvents(Window w) const +{ // ignore errors while we adjust event masks. windows could be // destroyed at any time after the XQueryTree() in doSelectEvents() // so we must ignore BadWindow errors. @@ -1721,7 +1705,8 @@ void XWindowsScreen::selectEvents(Window w) const { doSelectEvents(w); } -void XWindowsScreen::doSelectEvents(Window w) const { +void XWindowsScreen::doSelectEvents(Window w) const +{ // we want to track the mouse everywhere on the display. to achieve // that we select PointerMotionMask on every window. we also select // SubstructureNotifyMask in order to get CreateNotify events so we @@ -1764,7 +1749,8 @@ void XWindowsScreen::doSelectEvents(Window w) const { } } -KeyID XWindowsScreen::mapKeyFromX(XKeyEvent *event) const { +KeyID XWindowsScreen::mapKeyFromX(XKeyEvent *event) const +{ // convert to a keysym KeySym keysym; if (event->type == KeyPress && m_ic != NULL) { @@ -1809,7 +1795,8 @@ KeyID XWindowsScreen::mapKeyFromX(XKeyEvent *event) const { return result; } -ButtonID XWindowsScreen::mapButtonFromX(const XButtonEvent *event) const { +ButtonID XWindowsScreen::mapButtonFromX(const XButtonEvent *event) const +{ unsigned int button = event->button; // first three buttons map to 1, 2, 3 (kButtonLeft, Middle, Right) @@ -1829,7 +1816,8 @@ ButtonID XWindowsScreen::mapButtonFromX(const XButtonEvent *event) const { } } -unsigned int XWindowsScreen::mapButtonToX(ButtonID id) const { +unsigned int XWindowsScreen::mapButtonToX(ButtonID id) const +{ // map button -1 to button 4 (+wheel) if (id == static_cast(-1)) { id = 4; @@ -1856,7 +1844,8 @@ unsigned int XWindowsScreen::mapButtonToX(ButtonID id) const { return static_cast(id); } -void XWindowsScreen::warpCursorNoFlush(SInt32 x, SInt32 y) { +void XWindowsScreen::warpCursorNoFlush(SInt32 x, SInt32 y) +{ assert(m_window != None); // send an event that we can recognize before the mouse warp @@ -1887,7 +1876,8 @@ void XWindowsScreen::warpCursorNoFlush(SInt32 x, SInt32 y) { LOG((CLOG_DEBUG2 "warped to %d,%d", x, y)); } -void XWindowsScreen::updateButtons() { +void XWindowsScreen::updateButtons() +{ // query the button mapping UInt32 numButtons = XGetPointerMapping(m_display, NULL, 0); unsigned char *tmpButtons = new unsigned char[numButtons]; @@ -1917,10 +1907,9 @@ void XWindowsScreen::updateButtons() { delete[] tmpButtons; } -bool XWindowsScreen::grabMouseAndKeyboard() { - unsigned int event_mask = ButtonPressMask | ButtonReleaseMask | - EnterWindowMask | LeaveWindowMask | - PointerMotionMask; +bool XWindowsScreen::grabMouseAndKeyboard() +{ + unsigned int event_mask = ButtonPressMask | ButtonReleaseMask | EnterWindowMask | LeaveWindowMask | PointerMotionMask; // grab the mouse and keyboard. keep trying until we get them. // if we can't grab one after grabbing the other then ungrab @@ -1931,8 +1920,7 @@ bool XWindowsScreen::grabMouseAndKeyboard() { do { // keyboard first do { - result = XGrabKeyboard( - m_display, m_window, True, GrabModeAsync, GrabModeAsync, CurrentTime); + result = XGrabKeyboard(m_display, m_window, True, GrabModeAsync, GrabModeAsync, CurrentTime); assert(result != GrabNotViewable); if (result != GrabSuccess) { LOG((CLOG_DEBUG2 "waiting to grab keyboard")); @@ -1946,9 +1934,8 @@ bool XWindowsScreen::grabMouseAndKeyboard() { LOG((CLOG_DEBUG2 "grabbed keyboard")); // now the mouse --- use event_mask to get EnterNotify, LeaveNotify events - result = XGrabPointer( - m_display, m_window, False, event_mask, GrabModeAsync, GrabModeAsync, - m_window, None, CurrentTime); + result = + XGrabPointer(m_display, m_window, False, event_mask, GrabModeAsync, GrabModeAsync, m_window, None, CurrentTime); assert(result != GrabNotViewable); if (result != GrabSuccess) { // back off to avoid grab deadlock @@ -1966,7 +1953,8 @@ bool XWindowsScreen::grabMouseAndKeyboard() { return true; } -void XWindowsScreen::refreshKeyboard(XEvent *event) { +void XWindowsScreen::refreshKeyboard(XEvent *event) +{ if (XPending(m_display) > 0) { XEvent tmpEvent; XPeekEvent(m_display, &tmpEvent); @@ -1995,26 +1983,25 @@ void XWindowsScreen::refreshKeyboard(XEvent *event) { // XWindowsScreen::HotKeyItem // -XWindowsScreen::HotKeyItem::HotKeyItem(int keycode, unsigned int mask) - : m_keycode(keycode), - m_mask(mask) { +XWindowsScreen::HotKeyItem::HotKeyItem(int keycode, unsigned int mask) : m_keycode(keycode), m_mask(mask) +{ // do nothing } -bool XWindowsScreen::HotKeyItem::operator<(const HotKeyItem &x) const { - return ( - m_keycode < x.m_keycode || - (m_keycode == x.m_keycode && m_mask < x.m_mask)); +bool XWindowsScreen::HotKeyItem::operator<(const HotKeyItem &x) const +{ + return (m_keycode < x.m_keycode || (m_keycode == x.m_keycode && m_mask < x.m_mask)); } -bool XWindowsScreen::detectXI2() { +bool XWindowsScreen::detectXI2() +{ int event, error; - return XQueryExtension( - m_display, "XInputExtension", &xi_opcode, &event, &error); + return XQueryExtension(m_display, "XInputExtension", &xi_opcode, &event, &error); } #ifdef HAVE_XI2 -void XWindowsScreen::selectXIRawMotion() { +void XWindowsScreen::selectXIRawMotion() +{ XIEventMask mask; mask.deviceid = XIAllDevices; diff --git a/src/lib/platform/XWindowsScreen.h b/src/lib/platform/XWindowsScreen.h index ab4b7f4ec..e140d215e 100644 --- a/src/lib/platform/XWindowsScreen.h +++ b/src/lib/platform/XWindowsScreen.h @@ -37,13 +37,13 @@ class XWindowsKeyState; class XWindowsScreenSaver; //! Implementation of IPlatformScreen for X11 -class XWindowsScreen : public PlatformScreen { +class XWindowsScreen : public PlatformScreen +{ public: XWindowsScreen( - const char *displayName, bool isPrimary, bool disableXInitThreads, - int mouseScrollDelta, IEventQueue *events, - deskflow::ClientScrollDirection m_clientScrollDirection = - deskflow::ClientScrollDirection::SERVER); + const char *displayName, bool isPrimary, bool disableXInitThreads, int mouseScrollDelta, IEventQueue *events, + deskflow::ClientScrollDirection m_clientScrollDirection = deskflow::ClientScrollDirection::SERVER + ); virtual ~XWindowsScreen() override; //! @name manipulators @@ -54,8 +54,7 @@ public: // IScreen overrides void *getEventTarget() const override; bool getClipboard(ClipboardID id, IClipboard *) const override; - void - getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const override; + void getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const override; void getCursorPos(SInt32 &x, SInt32 &y) const override; // IPrimaryScreen overrides @@ -121,7 +120,8 @@ private: static int ioErrorHandler(Display *); private: - class KeyEventFilter { + class KeyEventFilter + { public: int m_event; Window m_window; @@ -161,7 +161,8 @@ private: static Bool findKeyEvent(Display *, XEvent *xevent, XPointer arg); private: - struct HotKeyItem { + struct HotKeyItem + { public: HotKeyItem(int, unsigned int); diff --git a/src/lib/platform/XWindowsScreenSaver.cpp b/src/lib/platform/XWindowsScreenSaver.cpp index 12e3f5761..cb7028efd 100644 --- a/src/lib/platform/XWindowsScreenSaver.cpp +++ b/src/lib/platform/XWindowsScreenSaver.cpp @@ -32,7 +32,8 @@ #error The XTest extension is required to build deskflow #endif #if HAVE_X11_EXTENSIONS_DPMS_H -extern "C" { +extern "C" +{ #include #include #if !HAVE_DPMS_PROTOTYPES @@ -44,12 +45,12 @@ extern "C" { #define DPMSModeStandby 1 #define DPMSModeSuspend 2 #define DPMSModeOff 3 -extern Bool DPMSQueryExtension(Display *, int *, int *); -extern Bool DPMSCapable(Display *); -extern Status DPMSEnable(Display *); -extern Status DPMSDisable(Display *); -extern Status DPMSForceLevel(Display *, CARD16); -extern Status DPMSInfo(Display *, CARD16 *, BOOL *); + extern Bool DPMSQueryExtension(Display *, int *, int *); + extern Bool DPMSCapable(Display *); + extern Status DPMSEnable(Display *); + extern Status DPMSDisable(Display *); + extern Status DPMSForceLevel(Display *, CARD16); + extern Status DPMSInfo(Display *, CARD16 *, BOOL *); #endif } #endif @@ -58,8 +59,7 @@ extern Status DPMSInfo(Display *, CARD16 *, BOOL *); // XWindowsScreenSaver // -XWindowsScreenSaver::XWindowsScreenSaver( - Display *display, Window window, void *eventTarget, IEventQueue *events) +XWindowsScreenSaver::XWindowsScreenSaver(Display *display, Window window, void *eventTarget, IEventQueue *events) : m_display(display), m_xscreensaverSink(window), m_eventTarget(eventTarget), @@ -70,11 +70,11 @@ XWindowsScreenSaver::XWindowsScreenSaver( m_suppressDisable(false), m_disableTimer(NULL), m_disablePos(0), - m_events(events) { + m_events(events) +{ // get atoms m_atomScreenSaver = XInternAtom(m_display, "SCREENSAVER", False); - m_atomScreenSaverVersion = - XInternAtom(m_display, "_SCREENSAVER_VERSION", False); + m_atomScreenSaverVersion = XInternAtom(m_display, "_SCREENSAVER_VERSION", False); m_atomScreenSaverActivate = XInternAtom(m_display, "ACTIVATE", False); m_atomScreenSaverDeactivate = XInternAtom(m_display, "DEACTIVATE", False); @@ -106,8 +106,7 @@ XWindowsScreenSaver::XWindowsScreenSaver( } // get the built-in settings - XGetScreenSaver( - m_display, &m_timeout, &m_interval, &m_preferBlanking, &m_allowExposures); + XGetScreenSaver(m_display, &m_timeout, &m_interval, &m_preferBlanking, &m_allowExposures); // get the DPMS settings m_dpmsEnabled = isDPMSEnabled(); @@ -119,12 +118,12 @@ XWindowsScreenSaver::XWindowsScreenSaver( // install disable timer event handler m_events->adoptHandler( - Event::kTimer, this, - new TMethodEventJob( - this, &XWindowsScreenSaver::handleDisableTimer)); + Event::kTimer, this, new TMethodEventJob(this, &XWindowsScreenSaver::handleDisableTimer) + ); } -XWindowsScreenSaver::~XWindowsScreenSaver() { +XWindowsScreenSaver::~XWindowsScreenSaver() +{ // done with disable job if (m_disableTimer != NULL) { m_events->deleteTimer(m_disableTimer); @@ -133,20 +132,21 @@ XWindowsScreenSaver::~XWindowsScreenSaver() { if (m_display != NULL) { enableDPMS(m_dpmsEnabled); - XSetScreenSaver( - m_display, m_timeout, m_interval, m_preferBlanking, m_allowExposures); + XSetScreenSaver(m_display, m_timeout, m_interval, m_preferBlanking, m_allowExposures); clearWatchForXScreenSaver(); XWindowsUtil::ErrorLock lock(m_display); XSelectInput(m_display, DefaultRootWindow(m_display), m_rootEventMask); } } -void XWindowsScreenSaver::destroy() { +void XWindowsScreenSaver::destroy() +{ m_display = NULL; delete this; } -bool XWindowsScreenSaver::handleXEvent(const XEvent *xevent) { +bool XWindowsScreenSaver::handleXEvent(const XEvent *xevent) +{ switch (xevent->type) { case CreateNotify: if (m_xscreensaver == None) { @@ -204,27 +204,27 @@ bool XWindowsScreenSaver::handleXEvent(const XEvent *xevent) { return false; } -void XWindowsScreenSaver::enable() { +void XWindowsScreenSaver::enable() +{ // for xscreensaver m_disabled = false; updateDisableTimer(); // for built-in X screen saver - XSetScreenSaver( - m_display, m_timeout, m_interval, m_preferBlanking, m_allowExposures); + XSetScreenSaver(m_display, m_timeout, m_interval, m_preferBlanking, m_allowExposures); // for DPMS enableDPMS(m_dpmsEnabled); } -void XWindowsScreenSaver::disable() { +void XWindowsScreenSaver::disable() +{ // for xscreensaver m_disabled = true; updateDisableTimer(); // use built-in X screen saver - XGetScreenSaver( - m_display, &m_timeout, &m_interval, &m_preferBlanking, &m_allowExposures); + XGetScreenSaver(m_display, &m_timeout, &m_interval, &m_preferBlanking, &m_allowExposures); XSetScreenSaver(m_display, 0, m_interval, m_preferBlanking, m_allowExposures); // for DPMS @@ -234,7 +234,8 @@ void XWindowsScreenSaver::disable() { // FIXME -- now deactivate? } -void XWindowsScreenSaver::activate() { +void XWindowsScreenSaver::activate() +{ // remove disable job timer m_suppressDisable = true; updateDisableTimer(); @@ -258,7 +259,8 @@ void XWindowsScreenSaver::activate() { activateDPMS(true); } -void XWindowsScreenSaver::deactivate() { +void XWindowsScreenSaver::deactivate() +{ // reinstall disable job timer m_suppressDisable = false; updateDisableTimer(); @@ -282,7 +284,8 @@ void XWindowsScreenSaver::deactivate() { XForceScreenSaver(m_display, ScreenSaverReset); } -bool XWindowsScreenSaver::isActive() const { +bool XWindowsScreenSaver::isActive() const +{ // check xscreensaver if (m_xscreensaver != None) { return m_xscreensaverActive; @@ -297,7 +300,8 @@ bool XWindowsScreenSaver::isActive() const { return false; } -bool XWindowsScreenSaver::findXScreenSaver() { +bool XWindowsScreenSaver::findXScreenSaver() +{ // do nothing if we've already got the xscreensaver window if (m_xscreensaver == None) { // find top-level window xscreensaver window @@ -318,7 +322,8 @@ bool XWindowsScreenSaver::findXScreenSaver() { return (m_xscreensaver != None); } -void XWindowsScreenSaver::setXScreenSaver(Window window) { +void XWindowsScreenSaver::setXScreenSaver(Window window) +{ LOG((CLOG_DEBUG "xscreensaver window: 0x%08x", window)); // save window @@ -348,20 +353,20 @@ void XWindowsScreenSaver::setXScreenSaver(Window window) { } } -bool XWindowsScreenSaver::isXScreenSaver(Window w) const { +bool XWindowsScreenSaver::isXScreenSaver(Window w) const +{ // check for m_atomScreenSaverVersion string property Atom type; return ( - XWindowsUtil::getWindowProperty( - m_display, w, m_atomScreenSaverVersion, NULL, &type, NULL, False) && - type == XA_STRING); + XWindowsUtil::getWindowProperty(m_display, w, m_atomScreenSaverVersion, NULL, &type, NULL, False) && + type == XA_STRING + ); } -void XWindowsScreenSaver::setXScreenSaverActive(bool activated) { +void XWindowsScreenSaver::setXScreenSaverActive(bool activated) +{ if (m_xscreensaverActive != activated) { - LOG( - (CLOG_DEBUG "xscreensaver %s on window 0x%08x", - activated ? "activated" : "deactivated", m_xscreensaver)); + LOG((CLOG_DEBUG "xscreensaver %s on window 0x%08x", activated ? "activated" : "deactivated", m_xscreensaver)); m_xscreensaverActive = activated; // if screen saver was activated forcefully (i.e. against @@ -372,18 +377,15 @@ void XWindowsScreenSaver::setXScreenSaverActive(bool activated) { updateDisableTimer(); if (activated) { - m_events->addEvent(Event( - m_events->forIPrimaryScreen().screensaverActivated(), m_eventTarget)); + m_events->addEvent(Event(m_events->forIPrimaryScreen().screensaverActivated(), m_eventTarget)); } else { - m_events->addEvent(Event( - m_events->forIPrimaryScreen().screensaverDeactivated(), - m_eventTarget)); + m_events->addEvent(Event(m_events->forIPrimaryScreen().screensaverDeactivated(), m_eventTarget)); } } } -void XWindowsScreenSaver::sendXScreenSaverCommand( - Atom cmd, long arg1, long arg2) { +void XWindowsScreenSaver::sendXScreenSaverCommand(Atom cmd, long arg1, long arg2) +{ XEvent event; event.xclient.type = ClientMessage; event.xclient.display = m_display; @@ -396,8 +398,7 @@ void XWindowsScreenSaver::sendXScreenSaverCommand( event.xclient.data.l[3] = 0; event.xclient.data.l[4] = 0; - LOG(( - CLOG_DEBUG "send xscreensaver command: %d %d %d", (long)cmd, arg1, arg2)); + LOG((CLOG_DEBUG "send xscreensaver command: %d %d %d", (long)cmd, arg1, arg2)); bool error = false; { XWindowsUtil::ErrorLock lock(m_display, &error); @@ -408,7 +409,8 @@ void XWindowsScreenSaver::sendXScreenSaverCommand( } } -void XWindowsScreenSaver::watchForXScreenSaver() { +void XWindowsScreenSaver::watchForXScreenSaver() +{ // clear old watch list clearWatchForXScreenSaver(); @@ -431,17 +433,18 @@ void XWindowsScreenSaver::watchForXScreenSaver() { } } -void XWindowsScreenSaver::clearWatchForXScreenSaver() { +void XWindowsScreenSaver::clearWatchForXScreenSaver() +{ // stop watching all windows XWindowsUtil::ErrorLock lock(m_display); - for (WatchList::iterator index = m_watchWindows.begin(); - index != m_watchWindows.end(); ++index) { + for (WatchList::iterator index = m_watchWindows.begin(); index != m_watchWindows.end(); ++index) { XSelectInput(m_display, index->first, index->second); } m_watchWindows.clear(); } -void XWindowsScreenSaver::addWatchXScreenSaver(Window window) { +void XWindowsScreenSaver::addWatchXScreenSaver(Window window) +{ // get window attributes bool error = false; XWindowAttributes attr; @@ -456,8 +459,7 @@ void XWindowsScreenSaver::addWatchXScreenSaver(Window window) { error = false; { XWindowsUtil::ErrorLock lock(m_display, &error); - XSelectInput( - m_display, window, attr.your_event_mask | PropertyChangeMask); + XSelectInput(m_display, window, attr.your_event_mask | PropertyChangeMask); } if (!error) { // if successful then add the window to our list @@ -466,7 +468,8 @@ void XWindowsScreenSaver::addWatchXScreenSaver(Window window) { } } -void XWindowsScreenSaver::updateDisableTimer() { +void XWindowsScreenSaver::updateDisableTimer() +{ if (m_disabled && !m_suppressDisable && m_disableTimer == NULL) { // 5 seconds should be plenty often to suppress the screen saver m_disableTimer = m_events->newTimer(5.0, this); @@ -476,7 +479,8 @@ void XWindowsScreenSaver::updateDisableTimer() { } } -void XWindowsScreenSaver::handleDisableTimer(const Event &, void *) { +void XWindowsScreenSaver::handleDisableTimer(const Event &, void *) +{ // send fake mouse motion directly to xscreensaver if (m_xscreensaver != None) { XEvent event; @@ -501,7 +505,8 @@ void XWindowsScreenSaver::handleDisableTimer(const Event &, void *) { } } -void XWindowsScreenSaver::activateDPMS(bool activate) { +void XWindowsScreenSaver::activateDPMS(bool activate) +{ #if HAVE_X11_EXTENSIONS_DPMS_H if (m_dpms) { // DPMSForceLevel will generate a BadMatch if DPMS is disabled @@ -511,7 +516,8 @@ void XWindowsScreenSaver::activateDPMS(bool activate) { #endif } -void XWindowsScreenSaver::enableDPMS(bool enable) { +void XWindowsScreenSaver::enableDPMS(bool enable) +{ #if HAVE_X11_EXTENSIONS_DPMS_H if (m_dpms) { if (enable) { @@ -523,7 +529,8 @@ void XWindowsScreenSaver::enableDPMS(bool enable) { #endif } -bool XWindowsScreenSaver::isDPMSEnabled() const { +bool XWindowsScreenSaver::isDPMSEnabled() const +{ #if HAVE_X11_EXTENSIONS_DPMS_H if (m_dpms) { CARD16 level; @@ -538,7 +545,8 @@ bool XWindowsScreenSaver::isDPMSEnabled() const { #endif } -bool XWindowsScreenSaver::isDPMSActivated() const { +bool XWindowsScreenSaver::isDPMSActivated() const +{ #if HAVE_X11_EXTENSIONS_DPMS_H if (m_dpms) { CARD16 level; diff --git a/src/lib/platform/XWindowsScreenSaver.h b/src/lib/platform/XWindowsScreenSaver.h index 624513ad9..2bff7e51b 100644 --- a/src/lib/platform/XWindowsScreenSaver.h +++ b/src/lib/platform/XWindowsScreenSaver.h @@ -32,10 +32,10 @@ class Event; class EventQueueTimer; //! X11 screen saver implementation -class XWindowsScreenSaver : public IScreenSaver { +class XWindowsScreenSaver : public IScreenSaver +{ public: - XWindowsScreenSaver( - Display *, Window, void *eventTarget, IEventQueue *events); + XWindowsScreenSaver(Display *, Window, void *eventTarget, IEventQueue *events); XWindowsScreenSaver(XWindowsScreenSaver const &) = delete; XWindowsScreenSaver(XWindowsScreenSaver &&) = delete; virtual ~XWindowsScreenSaver(); diff --git a/src/lib/platform/XWindowsUtil.cpp b/src/lib/platform/XWindowsUtil.cpp index 66564d76f..f5226c702 100644 --- a/src/lib/platform/XWindowsUtil.cpp +++ b/src/lib/platform/XWindowsUtil.cpp @@ -76,7 +76,8 @@ * This software is in the public domain. Share and enjoy! */ -struct codepair { +struct codepair +{ KeySym keysym; UInt32 ucs4; } s_keymap[] = { @@ -239,55 +240,55 @@ struct codepair { {XK_kana_yu, 0x30e5}, /* KATAKANA LETTER SMALL YU */ {XK_kana_yo, 0x30e7}, /* KATAKANA LETTER SMALL YO */ {XK_kana_tsu, 0x30c3}, /* KATAKANA LETTER SMALL TU */ - {XK_prolongedsound, 0x30fc}, /* KATAKANA-HIRAGANA PROLONGED SOUND MARK */ - {XK_kana_A, 0x30a2}, /* KATAKANA LETTER A */ - {XK_kana_I, 0x30a4}, /* KATAKANA LETTER I */ - {XK_kana_U, 0x30a6}, /* KATAKANA LETTER U */ - {XK_kana_E, 0x30a8}, /* KATAKANA LETTER E */ - {XK_kana_O, 0x30aa}, /* KATAKANA LETTER O */ - {XK_kana_KA, 0x30ab}, /* KATAKANA LETTER KA */ - {XK_kana_KI, 0x30ad}, /* KATAKANA LETTER KI */ - {XK_kana_KU, 0x30af}, /* KATAKANA LETTER KU */ - {XK_kana_KE, 0x30b1}, /* KATAKANA LETTER KE */ - {XK_kana_KO, 0x30b3}, /* KATAKANA LETTER KO */ - {XK_kana_SA, 0x30b5}, /* KATAKANA LETTER SA */ - {XK_kana_SHI, 0x30b7}, /* KATAKANA LETTER SI */ - {XK_kana_SU, 0x30b9}, /* KATAKANA LETTER SU */ - {XK_kana_SE, 0x30bb}, /* KATAKANA LETTER SE */ - {XK_kana_SO, 0x30bd}, /* KATAKANA LETTER SO */ - {XK_kana_TA, 0x30bf}, /* KATAKANA LETTER TA */ - {XK_kana_CHI, 0x30c1}, /* KATAKANA LETTER TI */ - {XK_kana_TSU, 0x30c4}, /* KATAKANA LETTER TU */ - {XK_kana_TE, 0x30c6}, /* KATAKANA LETTER TE */ - {XK_kana_TO, 0x30c8}, /* KATAKANA LETTER TO */ - {XK_kana_NA, 0x30ca}, /* KATAKANA LETTER NA */ - {XK_kana_NI, 0x30cb}, /* KATAKANA LETTER NI */ - {XK_kana_NU, 0x30cc}, /* KATAKANA LETTER NU */ - {XK_kana_NE, 0x30cd}, /* KATAKANA LETTER NE */ - {XK_kana_NO, 0x30ce}, /* KATAKANA LETTER NO */ - {XK_kana_HA, 0x30cf}, /* KATAKANA LETTER HA */ - {XK_kana_HI, 0x30d2}, /* KATAKANA LETTER HI */ - {XK_kana_FU, 0x30d5}, /* KATAKANA LETTER HU */ - {XK_kana_HE, 0x30d8}, /* KATAKANA LETTER HE */ - {XK_kana_HO, 0x30db}, /* KATAKANA LETTER HO */ - {XK_kana_MA, 0x30de}, /* KATAKANA LETTER MA */ - {XK_kana_MI, 0x30df}, /* KATAKANA LETTER MI */ - {XK_kana_MU, 0x30e0}, /* KATAKANA LETTER MU */ - {XK_kana_ME, 0x30e1}, /* KATAKANA LETTER ME */ - {XK_kana_MO, 0x30e2}, /* KATAKANA LETTER MO */ - {XK_kana_YA, 0x30e4}, /* KATAKANA LETTER YA */ - {XK_kana_YU, 0x30e6}, /* KATAKANA LETTER YU */ - {XK_kana_YO, 0x30e8}, /* KATAKANA LETTER YO */ - {XK_kana_RA, 0x30e9}, /* KATAKANA LETTER RA */ - {XK_kana_RI, 0x30ea}, /* KATAKANA LETTER RI */ - {XK_kana_RU, 0x30eb}, /* KATAKANA LETTER RU */ - {XK_kana_RE, 0x30ec}, /* KATAKANA LETTER RE */ - {XK_kana_RO, 0x30ed}, /* KATAKANA LETTER RO */ - {XK_kana_WA, 0x30ef}, /* KATAKANA LETTER WA */ - {XK_kana_N, 0x30f3}, /* KATAKANA LETTER N */ - {XK_voicedsound, 0x309b}, /* KATAKANA-HIRAGANA VOICED SOUND MARK */ - {XK_semivoicedsound, 0x309c}, /* KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK */ -#endif // defined(XK_overline) + {XK_prolongedsound, 0x30fc}, /* KATAKANA-HIRAGANA PROLONGED SOUND MARK */ + {XK_kana_A, 0x30a2}, /* KATAKANA LETTER A */ + {XK_kana_I, 0x30a4}, /* KATAKANA LETTER I */ + {XK_kana_U, 0x30a6}, /* KATAKANA LETTER U */ + {XK_kana_E, 0x30a8}, /* KATAKANA LETTER E */ + {XK_kana_O, 0x30aa}, /* KATAKANA LETTER O */ + {XK_kana_KA, 0x30ab}, /* KATAKANA LETTER KA */ + {XK_kana_KI, 0x30ad}, /* KATAKANA LETTER KI */ + {XK_kana_KU, 0x30af}, /* KATAKANA LETTER KU */ + {XK_kana_KE, 0x30b1}, /* KATAKANA LETTER KE */ + {XK_kana_KO, 0x30b3}, /* KATAKANA LETTER KO */ + {XK_kana_SA, 0x30b5}, /* KATAKANA LETTER SA */ + {XK_kana_SHI, 0x30b7}, /* KATAKANA LETTER SI */ + {XK_kana_SU, 0x30b9}, /* KATAKANA LETTER SU */ + {XK_kana_SE, 0x30bb}, /* KATAKANA LETTER SE */ + {XK_kana_SO, 0x30bd}, /* KATAKANA LETTER SO */ + {XK_kana_TA, 0x30bf}, /* KATAKANA LETTER TA */ + {XK_kana_CHI, 0x30c1}, /* KATAKANA LETTER TI */ + {XK_kana_TSU, 0x30c4}, /* KATAKANA LETTER TU */ + {XK_kana_TE, 0x30c6}, /* KATAKANA LETTER TE */ + {XK_kana_TO, 0x30c8}, /* KATAKANA LETTER TO */ + {XK_kana_NA, 0x30ca}, /* KATAKANA LETTER NA */ + {XK_kana_NI, 0x30cb}, /* KATAKANA LETTER NI */ + {XK_kana_NU, 0x30cc}, /* KATAKANA LETTER NU */ + {XK_kana_NE, 0x30cd}, /* KATAKANA LETTER NE */ + {XK_kana_NO, 0x30ce}, /* KATAKANA LETTER NO */ + {XK_kana_HA, 0x30cf}, /* KATAKANA LETTER HA */ + {XK_kana_HI, 0x30d2}, /* KATAKANA LETTER HI */ + {XK_kana_FU, 0x30d5}, /* KATAKANA LETTER HU */ + {XK_kana_HE, 0x30d8}, /* KATAKANA LETTER HE */ + {XK_kana_HO, 0x30db}, /* KATAKANA LETTER HO */ + {XK_kana_MA, 0x30de}, /* KATAKANA LETTER MA */ + {XK_kana_MI, 0x30df}, /* KATAKANA LETTER MI */ + {XK_kana_MU, 0x30e0}, /* KATAKANA LETTER MU */ + {XK_kana_ME, 0x30e1}, /* KATAKANA LETTER ME */ + {XK_kana_MO, 0x30e2}, /* KATAKANA LETTER MO */ + {XK_kana_YA, 0x30e4}, /* KATAKANA LETTER YA */ + {XK_kana_YU, 0x30e6}, /* KATAKANA LETTER YU */ + {XK_kana_YO, 0x30e8}, /* KATAKANA LETTER YO */ + {XK_kana_RA, 0x30e9}, /* KATAKANA LETTER RA */ + {XK_kana_RI, 0x30ea}, /* KATAKANA LETTER RI */ + {XK_kana_RU, 0x30eb}, /* KATAKANA LETTER RU */ + {XK_kana_RE, 0x30ec}, /* KATAKANA LETTER RE */ + {XK_kana_RO, 0x30ed}, /* KATAKANA LETTER RO */ + {XK_kana_WA, 0x30ef}, /* KATAKANA LETTER WA */ + {XK_kana_N, 0x30f3}, /* KATAKANA LETTER N */ + {XK_voicedsound, 0x309b}, /* KATAKANA-HIRAGANA VOICED SOUND MARK */ + {XK_semivoicedsound, 0x309c}, /* KATAKANA-HIRAGANA SEMI-VOICED SOUND MARK */ +#endif // defined(XK_overline) #if defined(XK_Farsi_0) {XK_Farsi_0, 0x06f0}, /* EXTENDED ARABIC-INDIC DIGIT 0 */ {XK_Farsi_1, 0x06f1}, /* EXTENDED ARABIC-INDIC DIGIT 1 */ @@ -321,72 +322,70 @@ struct codepair { {XK_Arabic_9, 0x0669}, /* ARABIC 9 */ {XK_Arabic_question_mark, 0x061f}, /* ARABIC QUESTION MARK */ {XK_Arabic_hamza, 0x0621}, /* ARABIC LETTER HAMZA */ - {XK_Arabic_maddaonalef, 0x0622}, /* ARABIC LETTER ALEF WITH MADDA ABOVE */ - {XK_Arabic_hamzaonalef, 0x0623}, /* ARABIC LETTER ALEF WITH HAMZA ABOVE */ - {XK_Arabic_hamzaonwaw, 0x0624}, /* ARABIC LETTER WAW WITH HAMZA ABOVE */ - {XK_Arabic_hamzaunderalef, - 0x0625}, /* ARABIC LETTER ALEF WITH HAMZA BELOW */ - {XK_Arabic_hamzaonyeh, 0x0626}, /* ARABIC LETTER YEH WITH HAMZA ABOVE */ - {XK_Arabic_alef, 0x0627}, /* ARABIC LETTER ALEF */ - {XK_Arabic_beh, 0x0628}, /* ARABIC LETTER BEH */ - {XK_Arabic_tehmarbuta, 0x0629}, /* ARABIC LETTER TEH MARBUTA */ - {XK_Arabic_teh, 0x062a}, /* ARABIC LETTER TEH */ - {XK_Arabic_theh, 0x062b}, /* ARABIC LETTER THEH */ - {XK_Arabic_jeem, 0x062c}, /* ARABIC LETTER JEEM */ - {XK_Arabic_hah, 0x062d}, /* ARABIC LETTER HAH */ - {XK_Arabic_khah, 0x062e}, /* ARABIC LETTER KHAH */ - {XK_Arabic_dal, 0x062f}, /* ARABIC LETTER DAL */ - {XK_Arabic_thal, 0x0630}, /* ARABIC LETTER THAL */ - {XK_Arabic_ra, 0x0631}, /* ARABIC LETTER REH */ - {XK_Arabic_zain, 0x0632}, /* ARABIC LETTER ZAIN */ - {XK_Arabic_seen, 0x0633}, /* ARABIC LETTER SEEN */ - {XK_Arabic_sheen, 0x0634}, /* ARABIC LETTER SHEEN */ - {XK_Arabic_sad, 0x0635}, /* ARABIC LETTER SAD */ - {XK_Arabic_dad, 0x0636}, /* ARABIC LETTER DAD */ - {XK_Arabic_tah, 0x0637}, /* ARABIC LETTER TAH */ - {XK_Arabic_zah, 0x0638}, /* ARABIC LETTER ZAH */ - {XK_Arabic_ain, 0x0639}, /* ARABIC LETTER AIN */ - {XK_Arabic_ghain, 0x063a}, /* ARABIC LETTER GHAIN */ - {XK_Arabic_tatweel, 0x0640}, /* ARABIC TATWEEL */ - {XK_Arabic_feh, 0x0641}, /* ARABIC LETTER FEH */ - {XK_Arabic_qaf, 0x0642}, /* ARABIC LETTER QAF */ - {XK_Arabic_kaf, 0x0643}, /* ARABIC LETTER KAF */ - {XK_Arabic_lam, 0x0644}, /* ARABIC LETTER LAM */ - {XK_Arabic_meem, 0x0645}, /* ARABIC LETTER MEEM */ - {XK_Arabic_noon, 0x0646}, /* ARABIC LETTER NOON */ - {XK_Arabic_ha, 0x0647}, /* ARABIC LETTER HEH */ - {XK_Arabic_waw, 0x0648}, /* ARABIC LETTER WAW */ - {XK_Arabic_alefmaksura, 0x0649}, /* ARABIC LETTER ALEF MAKSURA */ - {XK_Arabic_yeh, 0x064a}, /* ARABIC LETTER YEH */ - {XK_Arabic_fathatan, 0x064b}, /* ARABIC FATHATAN */ - {XK_Arabic_dammatan, 0x064c}, /* ARABIC DAMMATAN */ - {XK_Arabic_kasratan, 0x064d}, /* ARABIC KASRATAN */ - {XK_Arabic_fatha, 0x064e}, /* ARABIC FATHA */ - {XK_Arabic_damma, 0x064f}, /* ARABIC DAMMA */ - {XK_Arabic_kasra, 0x0650}, /* ARABIC KASRA */ - {XK_Arabic_shadda, 0x0651}, /* ARABIC SHADDA */ - {XK_Arabic_sukun, 0x0652}, /* ARABIC SUKUN */ - {XK_Arabic_madda_above, 0x0653}, /* ARABIC MADDA ABOVE */ - {XK_Arabic_hamza_above, 0x0654}, /* ARABIC HAMZA ABOVE */ - {XK_Arabic_hamza_below, 0x0655}, /* ARABIC HAMZA BELOW */ - {XK_Arabic_jeh, 0x0698}, /* ARABIC LETTER JEH */ - {XK_Arabic_veh, 0x06a4}, /* ARABIC LETTER VEH */ - {XK_Arabic_keheh, 0x06a9}, /* ARABIC LETTER KEHEH */ - {XK_Arabic_gaf, 0x06af}, /* ARABIC LETTER GAF */ - {XK_Arabic_noon_ghunna, 0x06ba}, /* ARABIC LETTER NOON GHUNNA */ - {XK_Arabic_heh_doachashmee, 0x06be}, /* ARABIC LETTER HEH DOACHASHMEE */ - {XK_Arabic_farsi_yeh, 0x06cc}, /* ARABIC LETTER FARSI YEH */ - {XK_Arabic_yeh_baree, 0x06d2}, /* ARABIC LETTER YEH BAREE */ - {XK_Arabic_heh_goal, 0x06c1}, /* ARABIC LETTER HEH GOAL */ -#endif // defined(XK_Farsi_0) + {XK_Arabic_maddaonalef, 0x0622}, /* ARABIC LETTER ALEF WITH MADDA ABOVE */ + {XK_Arabic_hamzaonalef, 0x0623}, /* ARABIC LETTER ALEF WITH HAMZA ABOVE */ + {XK_Arabic_hamzaonwaw, 0x0624}, /* ARABIC LETTER WAW WITH HAMZA ABOVE */ + {XK_Arabic_hamzaunderalef, 0x0625}, /* ARABIC LETTER ALEF WITH HAMZA BELOW */ + {XK_Arabic_hamzaonyeh, 0x0626}, /* ARABIC LETTER YEH WITH HAMZA ABOVE */ + {XK_Arabic_alef, 0x0627}, /* ARABIC LETTER ALEF */ + {XK_Arabic_beh, 0x0628}, /* ARABIC LETTER BEH */ + {XK_Arabic_tehmarbuta, 0x0629}, /* ARABIC LETTER TEH MARBUTA */ + {XK_Arabic_teh, 0x062a}, /* ARABIC LETTER TEH */ + {XK_Arabic_theh, 0x062b}, /* ARABIC LETTER THEH */ + {XK_Arabic_jeem, 0x062c}, /* ARABIC LETTER JEEM */ + {XK_Arabic_hah, 0x062d}, /* ARABIC LETTER HAH */ + {XK_Arabic_khah, 0x062e}, /* ARABIC LETTER KHAH */ + {XK_Arabic_dal, 0x062f}, /* ARABIC LETTER DAL */ + {XK_Arabic_thal, 0x0630}, /* ARABIC LETTER THAL */ + {XK_Arabic_ra, 0x0631}, /* ARABIC LETTER REH */ + {XK_Arabic_zain, 0x0632}, /* ARABIC LETTER ZAIN */ + {XK_Arabic_seen, 0x0633}, /* ARABIC LETTER SEEN */ + {XK_Arabic_sheen, 0x0634}, /* ARABIC LETTER SHEEN */ + {XK_Arabic_sad, 0x0635}, /* ARABIC LETTER SAD */ + {XK_Arabic_dad, 0x0636}, /* ARABIC LETTER DAD */ + {XK_Arabic_tah, 0x0637}, /* ARABIC LETTER TAH */ + {XK_Arabic_zah, 0x0638}, /* ARABIC LETTER ZAH */ + {XK_Arabic_ain, 0x0639}, /* ARABIC LETTER AIN */ + {XK_Arabic_ghain, 0x063a}, /* ARABIC LETTER GHAIN */ + {XK_Arabic_tatweel, 0x0640}, /* ARABIC TATWEEL */ + {XK_Arabic_feh, 0x0641}, /* ARABIC LETTER FEH */ + {XK_Arabic_qaf, 0x0642}, /* ARABIC LETTER QAF */ + {XK_Arabic_kaf, 0x0643}, /* ARABIC LETTER KAF */ + {XK_Arabic_lam, 0x0644}, /* ARABIC LETTER LAM */ + {XK_Arabic_meem, 0x0645}, /* ARABIC LETTER MEEM */ + {XK_Arabic_noon, 0x0646}, /* ARABIC LETTER NOON */ + {XK_Arabic_ha, 0x0647}, /* ARABIC LETTER HEH */ + {XK_Arabic_waw, 0x0648}, /* ARABIC LETTER WAW */ + {XK_Arabic_alefmaksura, 0x0649}, /* ARABIC LETTER ALEF MAKSURA */ + {XK_Arabic_yeh, 0x064a}, /* ARABIC LETTER YEH */ + {XK_Arabic_fathatan, 0x064b}, /* ARABIC FATHATAN */ + {XK_Arabic_dammatan, 0x064c}, /* ARABIC DAMMATAN */ + {XK_Arabic_kasratan, 0x064d}, /* ARABIC KASRATAN */ + {XK_Arabic_fatha, 0x064e}, /* ARABIC FATHA */ + {XK_Arabic_damma, 0x064f}, /* ARABIC DAMMA */ + {XK_Arabic_kasra, 0x0650}, /* ARABIC KASRA */ + {XK_Arabic_shadda, 0x0651}, /* ARABIC SHADDA */ + {XK_Arabic_sukun, 0x0652}, /* ARABIC SUKUN */ + {XK_Arabic_madda_above, 0x0653}, /* ARABIC MADDA ABOVE */ + {XK_Arabic_hamza_above, 0x0654}, /* ARABIC HAMZA ABOVE */ + {XK_Arabic_hamza_below, 0x0655}, /* ARABIC HAMZA BELOW */ + {XK_Arabic_jeh, 0x0698}, /* ARABIC LETTER JEH */ + {XK_Arabic_veh, 0x06a4}, /* ARABIC LETTER VEH */ + {XK_Arabic_keheh, 0x06a9}, /* ARABIC LETTER KEHEH */ + {XK_Arabic_gaf, 0x06af}, /* ARABIC LETTER GAF */ + {XK_Arabic_noon_ghunna, 0x06ba}, /* ARABIC LETTER NOON GHUNNA */ + {XK_Arabic_heh_doachashmee, 0x06be}, /* ARABIC LETTER HEH DOACHASHMEE */ + {XK_Arabic_farsi_yeh, 0x06cc}, /* ARABIC LETTER FARSI YEH */ + {XK_Arabic_yeh_baree, 0x06d2}, /* ARABIC LETTER YEH BAREE */ + {XK_Arabic_heh_goal, 0x06c1}, /* ARABIC LETTER HEH GOAL */ +#endif // defined(XK_Farsi_0) #if defined(XK_Serbian_dje) {XK_Serbian_dje, 0x0452}, /* CYRILLIC SMALL LETTER DJE */ {XK_Macedonia_gje, 0x0453}, /* CYRILLIC SMALL LETTER GJE */ {XK_Cyrillic_io, 0x0451}, /* CYRILLIC SMALL LETTER IO */ {XK_Ukrainian_ie, 0x0454}, /* CYRILLIC SMALL LETTER UKRAINIAN IE */ {XK_Macedonia_dse, 0x0455}, /* CYRILLIC SMALL LETTER DZE */ - {XK_Ukrainian_i, - 0x0456}, /* CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I */ + {XK_Ukrainian_i, 0x0456}, /* CYRILLIC SMALL LETTER BYELORUSSIAN-UKRAINIAN I */ {XK_Ukrainian_yi, 0x0457}, /* CYRILLIC SMALL LETTER YI */ {XK_Cyrillic_je, 0x0458}, /* CYRILLIC SMALL LETTER JE */ {XK_Cyrillic_lje, 0x0459}, /* CYRILLIC SMALL LETTER LJE */ @@ -394,8 +393,7 @@ struct codepair { {XK_Serbian_tshe, 0x045b}, /* CYRILLIC SMALL LETTER TSHE */ {XK_Macedonia_kje, 0x045c}, /* CYRILLIC SMALL LETTER KJE */ #if defined(XK_Ukrainian_ghe_with_upturn) - {XK_Ukrainian_ghe_with_upturn, - 0x0491}, /* CYRILLIC SMALL LETTER GHE WITH UPTURN */ + {XK_Ukrainian_ghe_with_upturn, 0x0491}, /* CYRILLIC SMALL LETTER GHE WITH UPTURN */ #endif {XK_Byelorussian_shortu, 0x045e}, /* CYRILLIC SMALL LETTER SHORT U */ {XK_Cyrillic_dzhe, 0x045f}, /* CYRILLIC SMALL LETTER DZHE */ @@ -405,17 +403,15 @@ struct codepair { {XK_Cyrillic_IO, 0x0401}, /* CYRILLIC CAPITAL LETTER IO */ {XK_Ukrainian_IE, 0x0404}, /* CYRILLIC CAPITAL LETTER UKRAINIAN IE */ {XK_Macedonia_DSE, 0x0405}, /* CYRILLIC CAPITAL LETTER DZE */ - {XK_Ukrainian_I, - 0x0406}, /* CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I */ - {XK_Ukrainian_YI, 0x0407}, /* CYRILLIC CAPITAL LETTER YI */ - {XK_Cyrillic_JE, 0x0408}, /* CYRILLIC CAPITAL LETTER JE */ - {XK_Cyrillic_LJE, 0x0409}, /* CYRILLIC CAPITAL LETTER LJE */ - {XK_Cyrillic_NJE, 0x040a}, /* CYRILLIC CAPITAL LETTER NJE */ - {XK_Serbian_TSHE, 0x040b}, /* CYRILLIC CAPITAL LETTER TSHE */ - {XK_Macedonia_KJE, 0x040c}, /* CYRILLIC CAPITAL LETTER KJE */ + {XK_Ukrainian_I, 0x0406}, /* CYRILLIC CAPITAL LETTER BYELORUSSIAN-UKRAINIAN I */ + {XK_Ukrainian_YI, 0x0407}, /* CYRILLIC CAPITAL LETTER YI */ + {XK_Cyrillic_JE, 0x0408}, /* CYRILLIC CAPITAL LETTER JE */ + {XK_Cyrillic_LJE, 0x0409}, /* CYRILLIC CAPITAL LETTER LJE */ + {XK_Cyrillic_NJE, 0x040a}, /* CYRILLIC CAPITAL LETTER NJE */ + {XK_Serbian_TSHE, 0x040b}, /* CYRILLIC CAPITAL LETTER TSHE */ + {XK_Macedonia_KJE, 0x040c}, /* CYRILLIC CAPITAL LETTER KJE */ #if defined(XK_Ukrainian_GHE_WITH_UPTURN) - {XK_Ukrainian_GHE_WITH_UPTURN, - 0x0490}, /* CYRILLIC CAPITAL LETTER GHE WITH UPTURN */ + {XK_Ukrainian_GHE_WITH_UPTURN, 0x0490}, /* CYRILLIC CAPITAL LETTER GHE WITH UPTURN */ #endif {XK_Byelorussian_SHORTU, 0x040e}, /* CYRILLIC CAPITAL LETTER SHORT U */ {XK_Cyrillic_DZHE, 0x040f}, /* CYRILLIC CAPITAL LETTER DZHE */ @@ -485,132 +481,120 @@ struct codepair { {XK_Cyrillic_HARDSIGN, 0x042a}, /* CYRILLIC CAPITAL LETTER HARD SIGN */ #endif // defined(XK_Serbian_dje) #if defined(XK_Greek_ALPHAaccent) - {XK_Greek_ALPHAaccent, 0x0386}, /* GREEK CAPITAL LETTER ALPHA WITH TONOS */ - {XK_Greek_EPSILONaccent, - 0x0388}, /* GREEK CAPITAL LETTER EPSILON WITH TONOS */ - {XK_Greek_ETAaccent, 0x0389}, /* GREEK CAPITAL LETTER ETA WITH TONOS */ - {XK_Greek_IOTAaccent, 0x038a}, /* GREEK CAPITAL LETTER IOTA WITH TONOS */ - {XK_Greek_IOTAdiaeresis, - 0x03aa}, /* GREEK CAPITAL LETTER IOTA WITH DIALYTIKA */ - {XK_Greek_OMICRONaccent, - 0x038c}, /* GREEK CAPITAL LETTER OMICRON WITH TONOS */ - {XK_Greek_UPSILONaccent, - 0x038e}, /* GREEK CAPITAL LETTER UPSILON WITH TONOS */ - {XK_Greek_UPSILONdieresis, - 0x03ab}, /* GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA */ - {XK_Greek_OMEGAaccent, 0x038f}, /* GREEK CAPITAL LETTER OMEGA WITH TONOS */ - {XK_Greek_accentdieresis, 0x0385}, /* GREEK DIALYTIKA TONOS */ - {XK_Greek_horizbar, 0x2015}, /* HORIZONTAL BAR */ - {XK_Greek_alphaaccent, 0x03ac}, /* GREEK SMALL LETTER ALPHA WITH TONOS */ - {XK_Greek_epsilonaccent, - 0x03ad}, /* GREEK SMALL LETTER EPSILON WITH TONOS */ - {XK_Greek_etaaccent, 0x03ae}, /* GREEK SMALL LETTER ETA WITH TONOS */ - {XK_Greek_iotaaccent, 0x03af}, /* GREEK SMALL LETTER IOTA WITH TONOS */ - {XK_Greek_iotadieresis, - 0x03ca}, /* GREEK SMALL LETTER IOTA WITH DIALYTIKA */ - {XK_Greek_iotaaccentdieresis, - 0x0390}, /* GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS */ - {XK_Greek_omicronaccent, - 0x03cc}, /* GREEK SMALL LETTER OMICRON WITH TONOS */ - {XK_Greek_upsilonaccent, - 0x03cd}, /* GREEK SMALL LETTER UPSILON WITH TONOS */ - {XK_Greek_upsilondieresis, - 0x03cb}, /* GREEK SMALL LETTER UPSILON WITH DIALYTIKA */ - {XK_Greek_upsilonaccentdieresis, - 0x03b0}, /* GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS */ - {XK_Greek_omegaaccent, 0x03ce}, /* GREEK SMALL LETTER OMEGA WITH TONOS */ - {XK_Greek_ALPHA, 0x0391}, /* GREEK CAPITAL LETTER ALPHA */ - {XK_Greek_BETA, 0x0392}, /* GREEK CAPITAL LETTER BETA */ - {XK_Greek_GAMMA, 0x0393}, /* GREEK CAPITAL LETTER GAMMA */ - {XK_Greek_DELTA, 0x0394}, /* GREEK CAPITAL LETTER DELTA */ - {XK_Greek_EPSILON, 0x0395}, /* GREEK CAPITAL LETTER EPSILON */ - {XK_Greek_ZETA, 0x0396}, /* GREEK CAPITAL LETTER ZETA */ - {XK_Greek_ETA, 0x0397}, /* GREEK CAPITAL LETTER ETA */ - {XK_Greek_THETA, 0x0398}, /* GREEK CAPITAL LETTER THETA */ - {XK_Greek_IOTA, 0x0399}, /* GREEK CAPITAL LETTER IOTA */ - {XK_Greek_KAPPA, 0x039a}, /* GREEK CAPITAL LETTER KAPPA */ - {XK_Greek_LAMBDA, 0x039b}, /* GREEK CAPITAL LETTER LAMDA */ - {XK_Greek_MU, 0x039c}, /* GREEK CAPITAL LETTER MU */ - {XK_Greek_NU, 0x039d}, /* GREEK CAPITAL LETTER NU */ - {XK_Greek_XI, 0x039e}, /* GREEK CAPITAL LETTER XI */ - {XK_Greek_OMICRON, 0x039f}, /* GREEK CAPITAL LETTER OMICRON */ - {XK_Greek_PI, 0x03a0}, /* GREEK CAPITAL LETTER PI */ - {XK_Greek_RHO, 0x03a1}, /* GREEK CAPITAL LETTER RHO */ - {XK_Greek_SIGMA, 0x03a3}, /* GREEK CAPITAL LETTER SIGMA */ - {XK_Greek_TAU, 0x03a4}, /* GREEK CAPITAL LETTER TAU */ - {XK_Greek_UPSILON, 0x03a5}, /* GREEK CAPITAL LETTER UPSILON */ - {XK_Greek_PHI, 0x03a6}, /* GREEK CAPITAL LETTER PHI */ - {XK_Greek_CHI, 0x03a7}, /* GREEK CAPITAL LETTER CHI */ - {XK_Greek_PSI, 0x03a8}, /* GREEK CAPITAL LETTER PSI */ - {XK_Greek_OMEGA, 0x03a9}, /* GREEK CAPITAL LETTER OMEGA */ - {XK_Greek_alpha, 0x03b1}, /* GREEK SMALL LETTER ALPHA */ - {XK_Greek_beta, 0x03b2}, /* GREEK SMALL LETTER BETA */ - {XK_Greek_gamma, 0x03b3}, /* GREEK SMALL LETTER GAMMA */ - {XK_Greek_delta, 0x03b4}, /* GREEK SMALL LETTER DELTA */ - {XK_Greek_epsilon, 0x03b5}, /* GREEK SMALL LETTER EPSILON */ - {XK_Greek_zeta, 0x03b6}, /* GREEK SMALL LETTER ZETA */ - {XK_Greek_eta, 0x03b7}, /* GREEK SMALL LETTER ETA */ - {XK_Greek_theta, 0x03b8}, /* GREEK SMALL LETTER THETA */ - {XK_Greek_iota, 0x03b9}, /* GREEK SMALL LETTER IOTA */ - {XK_Greek_kappa, 0x03ba}, /* GREEK SMALL LETTER KAPPA */ - {XK_Greek_lambda, 0x03bb}, /* GREEK SMALL LETTER LAMDA */ - {XK_Greek_mu, 0x03bc}, /* GREEK SMALL LETTER MU */ - {XK_Greek_nu, 0x03bd}, /* GREEK SMALL LETTER NU */ - {XK_Greek_xi, 0x03be}, /* GREEK SMALL LETTER XI */ - {XK_Greek_omicron, 0x03bf}, /* GREEK SMALL LETTER OMICRON */ - {XK_Greek_pi, 0x03c0}, /* GREEK SMALL LETTER PI */ - {XK_Greek_rho, 0x03c1}, /* GREEK SMALL LETTER RHO */ - {XK_Greek_sigma, 0x03c3}, /* GREEK SMALL LETTER SIGMA */ - {XK_Greek_finalsmallsigma, 0x03c2}, /* GREEK SMALL LETTER FINAL SIGMA */ - {XK_Greek_tau, 0x03c4}, /* GREEK SMALL LETTER TAU */ - {XK_Greek_upsilon, 0x03c5}, /* GREEK SMALL LETTER UPSILON */ - {XK_Greek_phi, 0x03c6}, /* GREEK SMALL LETTER PHI */ - {XK_Greek_chi, 0x03c7}, /* GREEK SMALL LETTER CHI */ - {XK_Greek_psi, 0x03c8}, /* GREEK SMALL LETTER PSI */ - {XK_Greek_omega, 0x03c9}, /* GREEK SMALL LETTER OMEGA */ -#endif // defined(XK_Greek_ALPHAaccent) - {XK_leftradical, 0x23b7}, /* ??? */ - {XK_topleftradical, 0x250c}, /* BOX DRAWINGS LIGHT DOWN AND RIGHT */ - {XK_horizconnector, 0x2500}, /* BOX DRAWINGS LIGHT HORIZONTAL */ - {XK_topintegral, 0x2320}, /* TOP HALF INTEGRAL */ - {XK_botintegral, 0x2321}, /* BOTTOM HALF INTEGRAL */ - {XK_vertconnector, 0x2502}, /* BOX DRAWINGS LIGHT VERTICAL */ - {XK_topleftsqbracket, 0x23a1}, /* ??? */ - {XK_botleftsqbracket, 0x23a3}, /* ??? */ - {XK_toprightsqbracket, 0x23a4}, /* ??? */ - {XK_botrightsqbracket, 0x23a6}, /* ??? */ - {XK_topleftparens, 0x239b}, /* ??? */ - {XK_botleftparens, 0x239d}, /* ??? */ - {XK_toprightparens, 0x239e}, /* ??? */ - {XK_botrightparens, 0x23a0}, /* ??? */ - {XK_leftmiddlecurlybrace, 0x23a8}, /* ??? */ - {XK_rightmiddlecurlybrace, 0x23ac}, /* ??? */ - {XK_lessthanequal, 0x2264}, /* LESS-THAN OR EQUAL TO */ - {XK_notequal, 0x2260}, /* NOT EQUAL TO */ - {XK_greaterthanequal, 0x2265}, /* GREATER-THAN OR EQUAL TO */ - {XK_integral, 0x222b}, /* INTEGRAL */ - {XK_therefore, 0x2234}, /* THEREFORE */ - {XK_variation, 0x221d}, /* PROPORTIONAL TO */ - {XK_infinity, 0x221e}, /* INFINITY */ - {XK_nabla, 0x2207}, /* NABLA */ - {XK_approximate, 0x223c}, /* TILDE OPERATOR */ - {XK_similarequal, 0x2243}, /* ASYMPTOTICALLY EQUAL TO */ - {XK_ifonlyif, 0x21d4}, /* LEFT RIGHT DOUBLE ARROW */ - {XK_implies, 0x21d2}, /* RIGHTWARDS DOUBLE ARROW */ - {XK_identical, 0x2261}, /* IDENTICAL TO */ - {XK_radical, 0x221a}, /* SQUARE ROOT */ - {XK_includedin, 0x2282}, /* SUBSET OF */ - {XK_includes, 0x2283}, /* SUPERSET OF */ - {XK_intersection, 0x2229}, /* INTERSECTION */ - {XK_union, 0x222a}, /* UNION */ - {XK_logicaland, 0x2227}, /* LOGICAL AND */ - {XK_logicalor, 0x2228}, /* LOGICAL OR */ - {XK_partialderivative, 0x2202}, /* PARTIAL DIFFERENTIAL */ - {XK_function, 0x0192}, /* LATIN SMALL LETTER F WITH HOOK */ - {XK_leftarrow, 0x2190}, /* LEFTWARDS ARROW */ - {XK_uparrow, 0x2191}, /* UPWARDS ARROW */ - {XK_rightarrow, 0x2192}, /* RIGHTWARDS ARROW */ - {XK_downarrow, 0x2193}, /* DOWNWARDS ARROW */ + {XK_Greek_ALPHAaccent, 0x0386}, /* GREEK CAPITAL LETTER ALPHA WITH TONOS */ + {XK_Greek_EPSILONaccent, 0x0388}, /* GREEK CAPITAL LETTER EPSILON WITH TONOS */ + {XK_Greek_ETAaccent, 0x0389}, /* GREEK CAPITAL LETTER ETA WITH TONOS */ + {XK_Greek_IOTAaccent, 0x038a}, /* GREEK CAPITAL LETTER IOTA WITH TONOS */ + {XK_Greek_IOTAdiaeresis, 0x03aa}, /* GREEK CAPITAL LETTER IOTA WITH DIALYTIKA */ + {XK_Greek_OMICRONaccent, 0x038c}, /* GREEK CAPITAL LETTER OMICRON WITH TONOS */ + {XK_Greek_UPSILONaccent, 0x038e}, /* GREEK CAPITAL LETTER UPSILON WITH TONOS */ + {XK_Greek_UPSILONdieresis, 0x03ab}, /* GREEK CAPITAL LETTER UPSILON WITH DIALYTIKA */ + {XK_Greek_OMEGAaccent, 0x038f}, /* GREEK CAPITAL LETTER OMEGA WITH TONOS */ + {XK_Greek_accentdieresis, 0x0385}, /* GREEK DIALYTIKA TONOS */ + {XK_Greek_horizbar, 0x2015}, /* HORIZONTAL BAR */ + {XK_Greek_alphaaccent, 0x03ac}, /* GREEK SMALL LETTER ALPHA WITH TONOS */ + {XK_Greek_epsilonaccent, 0x03ad}, /* GREEK SMALL LETTER EPSILON WITH TONOS */ + {XK_Greek_etaaccent, 0x03ae}, /* GREEK SMALL LETTER ETA WITH TONOS */ + {XK_Greek_iotaaccent, 0x03af}, /* GREEK SMALL LETTER IOTA WITH TONOS */ + {XK_Greek_iotadieresis, 0x03ca}, /* GREEK SMALL LETTER IOTA WITH DIALYTIKA */ + {XK_Greek_iotaaccentdieresis, 0x0390}, /* GREEK SMALL LETTER IOTA WITH DIALYTIKA AND TONOS */ + {XK_Greek_omicronaccent, 0x03cc}, /* GREEK SMALL LETTER OMICRON WITH TONOS */ + {XK_Greek_upsilonaccent, 0x03cd}, /* GREEK SMALL LETTER UPSILON WITH TONOS */ + {XK_Greek_upsilondieresis, 0x03cb}, /* GREEK SMALL LETTER UPSILON WITH DIALYTIKA */ + {XK_Greek_upsilonaccentdieresis, 0x03b0}, /* GREEK SMALL LETTER UPSILON WITH DIALYTIKA AND TONOS */ + {XK_Greek_omegaaccent, 0x03ce}, /* GREEK SMALL LETTER OMEGA WITH TONOS */ + {XK_Greek_ALPHA, 0x0391}, /* GREEK CAPITAL LETTER ALPHA */ + {XK_Greek_BETA, 0x0392}, /* GREEK CAPITAL LETTER BETA */ + {XK_Greek_GAMMA, 0x0393}, /* GREEK CAPITAL LETTER GAMMA */ + {XK_Greek_DELTA, 0x0394}, /* GREEK CAPITAL LETTER DELTA */ + {XK_Greek_EPSILON, 0x0395}, /* GREEK CAPITAL LETTER EPSILON */ + {XK_Greek_ZETA, 0x0396}, /* GREEK CAPITAL LETTER ZETA */ + {XK_Greek_ETA, 0x0397}, /* GREEK CAPITAL LETTER ETA */ + {XK_Greek_THETA, 0x0398}, /* GREEK CAPITAL LETTER THETA */ + {XK_Greek_IOTA, 0x0399}, /* GREEK CAPITAL LETTER IOTA */ + {XK_Greek_KAPPA, 0x039a}, /* GREEK CAPITAL LETTER KAPPA */ + {XK_Greek_LAMBDA, 0x039b}, /* GREEK CAPITAL LETTER LAMDA */ + {XK_Greek_MU, 0x039c}, /* GREEK CAPITAL LETTER MU */ + {XK_Greek_NU, 0x039d}, /* GREEK CAPITAL LETTER NU */ + {XK_Greek_XI, 0x039e}, /* GREEK CAPITAL LETTER XI */ + {XK_Greek_OMICRON, 0x039f}, /* GREEK CAPITAL LETTER OMICRON */ + {XK_Greek_PI, 0x03a0}, /* GREEK CAPITAL LETTER PI */ + {XK_Greek_RHO, 0x03a1}, /* GREEK CAPITAL LETTER RHO */ + {XK_Greek_SIGMA, 0x03a3}, /* GREEK CAPITAL LETTER SIGMA */ + {XK_Greek_TAU, 0x03a4}, /* GREEK CAPITAL LETTER TAU */ + {XK_Greek_UPSILON, 0x03a5}, /* GREEK CAPITAL LETTER UPSILON */ + {XK_Greek_PHI, 0x03a6}, /* GREEK CAPITAL LETTER PHI */ + {XK_Greek_CHI, 0x03a7}, /* GREEK CAPITAL LETTER CHI */ + {XK_Greek_PSI, 0x03a8}, /* GREEK CAPITAL LETTER PSI */ + {XK_Greek_OMEGA, 0x03a9}, /* GREEK CAPITAL LETTER OMEGA */ + {XK_Greek_alpha, 0x03b1}, /* GREEK SMALL LETTER ALPHA */ + {XK_Greek_beta, 0x03b2}, /* GREEK SMALL LETTER BETA */ + {XK_Greek_gamma, 0x03b3}, /* GREEK SMALL LETTER GAMMA */ + {XK_Greek_delta, 0x03b4}, /* GREEK SMALL LETTER DELTA */ + {XK_Greek_epsilon, 0x03b5}, /* GREEK SMALL LETTER EPSILON */ + {XK_Greek_zeta, 0x03b6}, /* GREEK SMALL LETTER ZETA */ + {XK_Greek_eta, 0x03b7}, /* GREEK SMALL LETTER ETA */ + {XK_Greek_theta, 0x03b8}, /* GREEK SMALL LETTER THETA */ + {XK_Greek_iota, 0x03b9}, /* GREEK SMALL LETTER IOTA */ + {XK_Greek_kappa, 0x03ba}, /* GREEK SMALL LETTER KAPPA */ + {XK_Greek_lambda, 0x03bb}, /* GREEK SMALL LETTER LAMDA */ + {XK_Greek_mu, 0x03bc}, /* GREEK SMALL LETTER MU */ + {XK_Greek_nu, 0x03bd}, /* GREEK SMALL LETTER NU */ + {XK_Greek_xi, 0x03be}, /* GREEK SMALL LETTER XI */ + {XK_Greek_omicron, 0x03bf}, /* GREEK SMALL LETTER OMICRON */ + {XK_Greek_pi, 0x03c0}, /* GREEK SMALL LETTER PI */ + {XK_Greek_rho, 0x03c1}, /* GREEK SMALL LETTER RHO */ + {XK_Greek_sigma, 0x03c3}, /* GREEK SMALL LETTER SIGMA */ + {XK_Greek_finalsmallsigma, 0x03c2}, /* GREEK SMALL LETTER FINAL SIGMA */ + {XK_Greek_tau, 0x03c4}, /* GREEK SMALL LETTER TAU */ + {XK_Greek_upsilon, 0x03c5}, /* GREEK SMALL LETTER UPSILON */ + {XK_Greek_phi, 0x03c6}, /* GREEK SMALL LETTER PHI */ + {XK_Greek_chi, 0x03c7}, /* GREEK SMALL LETTER CHI */ + {XK_Greek_psi, 0x03c8}, /* GREEK SMALL LETTER PSI */ + {XK_Greek_omega, 0x03c9}, /* GREEK SMALL LETTER OMEGA */ +#endif // defined(XK_Greek_ALPHAaccent) + {XK_leftradical, 0x23b7}, /* ??? */ + {XK_topleftradical, 0x250c}, /* BOX DRAWINGS LIGHT DOWN AND RIGHT */ + {XK_horizconnector, 0x2500}, /* BOX DRAWINGS LIGHT HORIZONTAL */ + {XK_topintegral, 0x2320}, /* TOP HALF INTEGRAL */ + {XK_botintegral, 0x2321}, /* BOTTOM HALF INTEGRAL */ + {XK_vertconnector, 0x2502}, /* BOX DRAWINGS LIGHT VERTICAL */ + {XK_topleftsqbracket, 0x23a1}, /* ??? */ + {XK_botleftsqbracket, 0x23a3}, /* ??? */ + {XK_toprightsqbracket, 0x23a4}, /* ??? */ + {XK_botrightsqbracket, 0x23a6}, /* ??? */ + {XK_topleftparens, 0x239b}, /* ??? */ + {XK_botleftparens, 0x239d}, /* ??? */ + {XK_toprightparens, 0x239e}, /* ??? */ + {XK_botrightparens, 0x23a0}, /* ??? */ + {XK_leftmiddlecurlybrace, 0x23a8}, /* ??? */ + {XK_rightmiddlecurlybrace, 0x23ac}, /* ??? */ + {XK_lessthanequal, 0x2264}, /* LESS-THAN OR EQUAL TO */ + {XK_notequal, 0x2260}, /* NOT EQUAL TO */ + {XK_greaterthanequal, 0x2265}, /* GREATER-THAN OR EQUAL TO */ + {XK_integral, 0x222b}, /* INTEGRAL */ + {XK_therefore, 0x2234}, /* THEREFORE */ + {XK_variation, 0x221d}, /* PROPORTIONAL TO */ + {XK_infinity, 0x221e}, /* INFINITY */ + {XK_nabla, 0x2207}, /* NABLA */ + {XK_approximate, 0x223c}, /* TILDE OPERATOR */ + {XK_similarequal, 0x2243}, /* ASYMPTOTICALLY EQUAL TO */ + {XK_ifonlyif, 0x21d4}, /* LEFT RIGHT DOUBLE ARROW */ + {XK_implies, 0x21d2}, /* RIGHTWARDS DOUBLE ARROW */ + {XK_identical, 0x2261}, /* IDENTICAL TO */ + {XK_radical, 0x221a}, /* SQUARE ROOT */ + {XK_includedin, 0x2282}, /* SUBSET OF */ + {XK_includes, 0x2283}, /* SUPERSET OF */ + {XK_intersection, 0x2229}, /* INTERSECTION */ + {XK_union, 0x222a}, /* UNION */ + {XK_logicaland, 0x2227}, /* LOGICAL AND */ + {XK_logicalor, 0x2228}, /* LOGICAL OR */ + {XK_partialderivative, 0x2202}, /* PARTIAL DIFFERENTIAL */ + {XK_function, 0x0192}, /* LATIN SMALL LETTER F WITH HOOK */ + {XK_leftarrow, 0x2190}, /* LEFTWARDS ARROW */ + {XK_uparrow, 0x2191}, /* UPWARDS ARROW */ + {XK_rightarrow, 0x2192}, /* RIGHTWARDS ARROW */ + {XK_downarrow, 0x2193}, /* DOWNWARDS ARROW */ /*{ XK_blank, ??? }, */ {XK_soliddiamond, 0x25c6}, /* BLACK DIAMOND */ {XK_checkerboard, 0x2592}, /* MEDIUM SHADE */ @@ -624,31 +608,27 @@ struct codepair { {XK_uprightcorner, 0x2510}, /* BOX DRAWINGS LIGHT DOWN AND LEFT */ {XK_upleftcorner, 0x250c}, /* BOX DRAWINGS LIGHT DOWN AND RIGHT */ {XK_lowleftcorner, 0x2514}, /* BOX DRAWINGS LIGHT UP AND RIGHT */ - {XK_crossinglines, 0x253c}, /* BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL */ - {XK_horizlinescan1, - 0x23ba}, /* HORIZONTAL SCAN LINE-1 (Unicode 3.2 draft) */ - {XK_horizlinescan3, - 0x23bb}, /* HORIZONTAL SCAN LINE-3 (Unicode 3.2 draft) */ + {XK_crossinglines, 0x253c}, /* BOX DRAWINGS LIGHT VERTICAL AND HORIZONTAL */ + {XK_horizlinescan1, 0x23ba}, /* HORIZONTAL SCAN LINE-1 (Unicode 3.2 draft) */ + {XK_horizlinescan3, 0x23bb}, /* HORIZONTAL SCAN LINE-3 (Unicode 3.2 draft) */ {XK_horizlinescan5, 0x2500}, /* BOX DRAWINGS LIGHT HORIZONTAL */ - {XK_horizlinescan7, - 0x23bc}, /* HORIZONTAL SCAN LINE-7 (Unicode 3.2 draft) */ - {XK_horizlinescan9, - 0x23bd}, /* HORIZONTAL SCAN LINE-9 (Unicode 3.2 draft) */ - {XK_leftt, 0x251c}, /* BOX DRAWINGS LIGHT VERTICAL AND RIGHT */ - {XK_rightt, 0x2524}, /* BOX DRAWINGS LIGHT VERTICAL AND LEFT */ - {XK_bott, 0x2534}, /* BOX DRAWINGS LIGHT UP AND HORIZONTAL */ - {XK_topt, 0x252c}, /* BOX DRAWINGS LIGHT DOWN AND HORIZONTAL */ - {XK_vertbar, 0x2502}, /* BOX DRAWINGS LIGHT VERTICAL */ - {XK_emspace, 0x2003}, /* EM SPACE */ - {XK_enspace, 0x2002}, /* EN SPACE */ - {XK_em3space, 0x2004}, /* THREE-PER-EM SPACE */ - {XK_em4space, 0x2005}, /* FOUR-PER-EM SPACE */ - {XK_digitspace, 0x2007}, /* FIGURE SPACE */ - {XK_punctspace, 0x2008}, /* PUNCTUATION SPACE */ - {XK_thinspace, 0x2009}, /* THIN SPACE */ - {XK_hairspace, 0x200a}, /* HAIR SPACE */ - {XK_emdash, 0x2014}, /* EM DASH */ - {XK_endash, 0x2013}, /* EN DASH */ + {XK_horizlinescan7, 0x23bc}, /* HORIZONTAL SCAN LINE-7 (Unicode 3.2 draft) */ + {XK_horizlinescan9, 0x23bd}, /* HORIZONTAL SCAN LINE-9 (Unicode 3.2 draft) */ + {XK_leftt, 0x251c}, /* BOX DRAWINGS LIGHT VERTICAL AND RIGHT */ + {XK_rightt, 0x2524}, /* BOX DRAWINGS LIGHT VERTICAL AND LEFT */ + {XK_bott, 0x2534}, /* BOX DRAWINGS LIGHT UP AND HORIZONTAL */ + {XK_topt, 0x252c}, /* BOX DRAWINGS LIGHT DOWN AND HORIZONTAL */ + {XK_vertbar, 0x2502}, /* BOX DRAWINGS LIGHT VERTICAL */ + {XK_emspace, 0x2003}, /* EM SPACE */ + {XK_enspace, 0x2002}, /* EN SPACE */ + {XK_em3space, 0x2004}, /* THREE-PER-EM SPACE */ + {XK_em4space, 0x2005}, /* FOUR-PER-EM SPACE */ + {XK_digitspace, 0x2007}, /* FIGURE SPACE */ + {XK_punctspace, 0x2008}, /* PUNCTUATION SPACE */ + {XK_thinspace, 0x2009}, /* THIN SPACE */ + {XK_hairspace, 0x200a}, /* HAIR SPACE */ + {XK_emdash, 0x2014}, /* EM DASH */ + {XK_endash, 0x2013}, /* EN DASH */ /*{ XK_signifblank, ??? }, */ {XK_ellipsis, 0x2026}, /* HORIZONTAL ELLIPSIS */ {XK_doubbaselinedot, 0x2025}, /* TWO DOT LEADER */ @@ -858,89 +838,89 @@ struct codepair { {XK_Thai_lekkao, 0x0e59}, /* THAI DIGIT NINE */ #endif // defined(XK_Thai_kokai) #if defined(XK_Hangul_Kiyeog) - {XK_Hangul_Kiyeog, 0x3131}, /* HANGUL LETTER KIYEOK */ - {XK_Hangul_SsangKiyeog, 0x3132}, /* HANGUL LETTER SSANGKIYEOK */ - {XK_Hangul_KiyeogSios, 0x3133}, /* HANGUL LETTER KIYEOK-SIOS */ - {XK_Hangul_Nieun, 0x3134}, /* HANGUL LETTER NIEUN */ - {XK_Hangul_NieunJieuj, 0x3135}, /* HANGUL LETTER NIEUN-CIEUC */ - {XK_Hangul_NieunHieuh, 0x3136}, /* HANGUL LETTER NIEUN-HIEUH */ - {XK_Hangul_Dikeud, 0x3137}, /* HANGUL LETTER TIKEUT */ - {XK_Hangul_SsangDikeud, 0x3138}, /* HANGUL LETTER SSANGTIKEUT */ - {XK_Hangul_Rieul, 0x3139}, /* HANGUL LETTER RIEUL */ - {XK_Hangul_RieulKiyeog, 0x313a}, /* HANGUL LETTER RIEUL-KIYEOK */ - {XK_Hangul_RieulMieum, 0x313b}, /* HANGUL LETTER RIEUL-MIEUM */ - {XK_Hangul_RieulPieub, 0x313c}, /* HANGUL LETTER RIEUL-PIEUP */ - {XK_Hangul_RieulSios, 0x313d}, /* HANGUL LETTER RIEUL-SIOS */ - {XK_Hangul_RieulTieut, 0x313e}, /* HANGUL LETTER RIEUL-THIEUTH */ - {XK_Hangul_RieulPhieuf, 0x313f}, /* HANGUL LETTER RIEUL-PHIEUPH */ - {XK_Hangul_RieulHieuh, 0x3140}, /* HANGUL LETTER RIEUL-HIEUH */ - {XK_Hangul_Mieum, 0x3141}, /* HANGUL LETTER MIEUM */ - {XK_Hangul_Pieub, 0x3142}, /* HANGUL LETTER PIEUP */ - {XK_Hangul_SsangPieub, 0x3143}, /* HANGUL LETTER SSANGPIEUP */ - {XK_Hangul_PieubSios, 0x3144}, /* HANGUL LETTER PIEUP-SIOS */ - {XK_Hangul_Sios, 0x3145}, /* HANGUL LETTER SIOS */ - {XK_Hangul_SsangSios, 0x3146}, /* HANGUL LETTER SSANGSIOS */ - {XK_Hangul_Ieung, 0x3147}, /* HANGUL LETTER IEUNG */ - {XK_Hangul_Jieuj, 0x3148}, /* HANGUL LETTER CIEUC */ - {XK_Hangul_SsangJieuj, 0x3149}, /* HANGUL LETTER SSANGCIEUC */ - {XK_Hangul_Cieuc, 0x314a}, /* HANGUL LETTER CHIEUCH */ - {XK_Hangul_Khieuq, 0x314b}, /* HANGUL LETTER KHIEUKH */ - {XK_Hangul_Tieut, 0x314c}, /* HANGUL LETTER THIEUTH */ - {XK_Hangul_Phieuf, 0x314d}, /* HANGUL LETTER PHIEUPH */ - {XK_Hangul_Hieuh, 0x314e}, /* HANGUL LETTER HIEUH */ - {XK_Hangul_A, 0x314f}, /* HANGUL LETTER A */ - {XK_Hangul_AE, 0x3150}, /* HANGUL LETTER AE */ - {XK_Hangul_YA, 0x3151}, /* HANGUL LETTER YA */ - {XK_Hangul_YAE, 0x3152}, /* HANGUL LETTER YAE */ - {XK_Hangul_EO, 0x3153}, /* HANGUL LETTER EO */ - {XK_Hangul_E, 0x3154}, /* HANGUL LETTER E */ - {XK_Hangul_YEO, 0x3155}, /* HANGUL LETTER YEO */ - {XK_Hangul_YE, 0x3156}, /* HANGUL LETTER YE */ - {XK_Hangul_O, 0x3157}, /* HANGUL LETTER O */ - {XK_Hangul_WA, 0x3158}, /* HANGUL LETTER WA */ - {XK_Hangul_WAE, 0x3159}, /* HANGUL LETTER WAE */ - {XK_Hangul_OE, 0x315a}, /* HANGUL LETTER OE */ - {XK_Hangul_YO, 0x315b}, /* HANGUL LETTER YO */ - {XK_Hangul_U, 0x315c}, /* HANGUL LETTER U */ - {XK_Hangul_WEO, 0x315d}, /* HANGUL LETTER WEO */ - {XK_Hangul_WE, 0x315e}, /* HANGUL LETTER WE */ - {XK_Hangul_WI, 0x315f}, /* HANGUL LETTER WI */ - {XK_Hangul_YU, 0x3160}, /* HANGUL LETTER YU */ - {XK_Hangul_EU, 0x3161}, /* HANGUL LETTER EU */ - {XK_Hangul_YI, 0x3162}, /* HANGUL LETTER YI */ - {XK_Hangul_I, 0x3163}, /* HANGUL LETTER I */ - {XK_Hangul_J_Kiyeog, 0x11a8}, /* HANGUL JONGSEONG KIYEOK */ - {XK_Hangul_J_SsangKiyeog, 0x11a9}, /* HANGUL JONGSEONG SSANGKIYEOK */ - {XK_Hangul_J_KiyeogSios, 0x11aa}, /* HANGUL JONGSEONG KIYEOK-SIOS */ - {XK_Hangul_J_Nieun, 0x11ab}, /* HANGUL JONGSEONG NIEUN */ - {XK_Hangul_J_NieunJieuj, 0x11ac}, /* HANGUL JONGSEONG NIEUN-CIEUC */ - {XK_Hangul_J_NieunHieuh, 0x11ad}, /* HANGUL JONGSEONG NIEUN-HIEUH */ - {XK_Hangul_J_Dikeud, 0x11ae}, /* HANGUL JONGSEONG TIKEUT */ - {XK_Hangul_J_Rieul, 0x11af}, /* HANGUL JONGSEONG RIEUL */ - {XK_Hangul_J_RieulKiyeog, 0x11b0}, /* HANGUL JONGSEONG RIEUL-KIYEOK */ - {XK_Hangul_J_RieulMieum, 0x11b1}, /* HANGUL JONGSEONG RIEUL-MIEUM */ - {XK_Hangul_J_RieulPieub, 0x11b2}, /* HANGUL JONGSEONG RIEUL-PIEUP */ - {XK_Hangul_J_RieulSios, 0x11b3}, /* HANGUL JONGSEONG RIEUL-SIOS */ - {XK_Hangul_J_RieulTieut, 0x11b4}, /* HANGUL JONGSEONG RIEUL-THIEUTH */ - {XK_Hangul_J_RieulPhieuf, 0x11b5}, /* HANGUL JONGSEONG RIEUL-PHIEUPH */ - {XK_Hangul_J_RieulHieuh, 0x11b6}, /* HANGUL JONGSEONG RIEUL-HIEUH */ - {XK_Hangul_J_Mieum, 0x11b7}, /* HANGUL JONGSEONG MIEUM */ - {XK_Hangul_J_Pieub, 0x11b8}, /* HANGUL JONGSEONG PIEUP */ - {XK_Hangul_J_PieubSios, 0x11b9}, /* HANGUL JONGSEONG PIEUP-SIOS */ - {XK_Hangul_J_Sios, 0x11ba}, /* HANGUL JONGSEONG SIOS */ - {XK_Hangul_J_SsangSios, 0x11bb}, /* HANGUL JONGSEONG SSANGSIOS */ - {XK_Hangul_J_Ieung, 0x11bc}, /* HANGUL JONGSEONG IEUNG */ - {XK_Hangul_J_Jieuj, 0x11bd}, /* HANGUL JONGSEONG CIEUC */ - {XK_Hangul_J_Cieuc, 0x11be}, /* HANGUL JONGSEONG CHIEUCH */ - {XK_Hangul_J_Khieuq, 0x11bf}, /* HANGUL JONGSEONG KHIEUKH */ - {XK_Hangul_J_Tieut, 0x11c0}, /* HANGUL JONGSEONG THIEUTH */ - {XK_Hangul_J_Phieuf, 0x11c1}, /* HANGUL JONGSEONG PHIEUPH */ - {XK_Hangul_J_Hieuh, 0x11c2}, /* HANGUL JONGSEONG HIEUH */ - {XK_Hangul_RieulYeorinHieuh, 0x316d}, /* HANGUL LETTER RIEUL-YEORINHIEUH */ - {XK_Hangul_SunkyeongeumMieum, 0x3171}, /* HANGUL LETTER KAPYEOUNMIEUM */ - {XK_Hangul_SunkyeongeumPieub, 0x3178}, /* HANGUL LETTER KAPYEOUNPIEUP */ - {XK_Hangul_PanSios, 0x317f}, /* HANGUL LETTER PANSIOS */ - {XK_Hangul_KkogjiDalrinIeung, 0x3181}, /* HANGUL LETTER YESIEUNG */ + {XK_Hangul_Kiyeog, 0x3131}, /* HANGUL LETTER KIYEOK */ + {XK_Hangul_SsangKiyeog, 0x3132}, /* HANGUL LETTER SSANGKIYEOK */ + {XK_Hangul_KiyeogSios, 0x3133}, /* HANGUL LETTER KIYEOK-SIOS */ + {XK_Hangul_Nieun, 0x3134}, /* HANGUL LETTER NIEUN */ + {XK_Hangul_NieunJieuj, 0x3135}, /* HANGUL LETTER NIEUN-CIEUC */ + {XK_Hangul_NieunHieuh, 0x3136}, /* HANGUL LETTER NIEUN-HIEUH */ + {XK_Hangul_Dikeud, 0x3137}, /* HANGUL LETTER TIKEUT */ + {XK_Hangul_SsangDikeud, 0x3138}, /* HANGUL LETTER SSANGTIKEUT */ + {XK_Hangul_Rieul, 0x3139}, /* HANGUL LETTER RIEUL */ + {XK_Hangul_RieulKiyeog, 0x313a}, /* HANGUL LETTER RIEUL-KIYEOK */ + {XK_Hangul_RieulMieum, 0x313b}, /* HANGUL LETTER RIEUL-MIEUM */ + {XK_Hangul_RieulPieub, 0x313c}, /* HANGUL LETTER RIEUL-PIEUP */ + {XK_Hangul_RieulSios, 0x313d}, /* HANGUL LETTER RIEUL-SIOS */ + {XK_Hangul_RieulTieut, 0x313e}, /* HANGUL LETTER RIEUL-THIEUTH */ + {XK_Hangul_RieulPhieuf, 0x313f}, /* HANGUL LETTER RIEUL-PHIEUPH */ + {XK_Hangul_RieulHieuh, 0x3140}, /* HANGUL LETTER RIEUL-HIEUH */ + {XK_Hangul_Mieum, 0x3141}, /* HANGUL LETTER MIEUM */ + {XK_Hangul_Pieub, 0x3142}, /* HANGUL LETTER PIEUP */ + {XK_Hangul_SsangPieub, 0x3143}, /* HANGUL LETTER SSANGPIEUP */ + {XK_Hangul_PieubSios, 0x3144}, /* HANGUL LETTER PIEUP-SIOS */ + {XK_Hangul_Sios, 0x3145}, /* HANGUL LETTER SIOS */ + {XK_Hangul_SsangSios, 0x3146}, /* HANGUL LETTER SSANGSIOS */ + {XK_Hangul_Ieung, 0x3147}, /* HANGUL LETTER IEUNG */ + {XK_Hangul_Jieuj, 0x3148}, /* HANGUL LETTER CIEUC */ + {XK_Hangul_SsangJieuj, 0x3149}, /* HANGUL LETTER SSANGCIEUC */ + {XK_Hangul_Cieuc, 0x314a}, /* HANGUL LETTER CHIEUCH */ + {XK_Hangul_Khieuq, 0x314b}, /* HANGUL LETTER KHIEUKH */ + {XK_Hangul_Tieut, 0x314c}, /* HANGUL LETTER THIEUTH */ + {XK_Hangul_Phieuf, 0x314d}, /* HANGUL LETTER PHIEUPH */ + {XK_Hangul_Hieuh, 0x314e}, /* HANGUL LETTER HIEUH */ + {XK_Hangul_A, 0x314f}, /* HANGUL LETTER A */ + {XK_Hangul_AE, 0x3150}, /* HANGUL LETTER AE */ + {XK_Hangul_YA, 0x3151}, /* HANGUL LETTER YA */ + {XK_Hangul_YAE, 0x3152}, /* HANGUL LETTER YAE */ + {XK_Hangul_EO, 0x3153}, /* HANGUL LETTER EO */ + {XK_Hangul_E, 0x3154}, /* HANGUL LETTER E */ + {XK_Hangul_YEO, 0x3155}, /* HANGUL LETTER YEO */ + {XK_Hangul_YE, 0x3156}, /* HANGUL LETTER YE */ + {XK_Hangul_O, 0x3157}, /* HANGUL LETTER O */ + {XK_Hangul_WA, 0x3158}, /* HANGUL LETTER WA */ + {XK_Hangul_WAE, 0x3159}, /* HANGUL LETTER WAE */ + {XK_Hangul_OE, 0x315a}, /* HANGUL LETTER OE */ + {XK_Hangul_YO, 0x315b}, /* HANGUL LETTER YO */ + {XK_Hangul_U, 0x315c}, /* HANGUL LETTER U */ + {XK_Hangul_WEO, 0x315d}, /* HANGUL LETTER WEO */ + {XK_Hangul_WE, 0x315e}, /* HANGUL LETTER WE */ + {XK_Hangul_WI, 0x315f}, /* HANGUL LETTER WI */ + {XK_Hangul_YU, 0x3160}, /* HANGUL LETTER YU */ + {XK_Hangul_EU, 0x3161}, /* HANGUL LETTER EU */ + {XK_Hangul_YI, 0x3162}, /* HANGUL LETTER YI */ + {XK_Hangul_I, 0x3163}, /* HANGUL LETTER I */ + {XK_Hangul_J_Kiyeog, 0x11a8}, /* HANGUL JONGSEONG KIYEOK */ + {XK_Hangul_J_SsangKiyeog, 0x11a9}, /* HANGUL JONGSEONG SSANGKIYEOK */ + {XK_Hangul_J_KiyeogSios, 0x11aa}, /* HANGUL JONGSEONG KIYEOK-SIOS */ + {XK_Hangul_J_Nieun, 0x11ab}, /* HANGUL JONGSEONG NIEUN */ + {XK_Hangul_J_NieunJieuj, 0x11ac}, /* HANGUL JONGSEONG NIEUN-CIEUC */ + {XK_Hangul_J_NieunHieuh, 0x11ad}, /* HANGUL JONGSEONG NIEUN-HIEUH */ + {XK_Hangul_J_Dikeud, 0x11ae}, /* HANGUL JONGSEONG TIKEUT */ + {XK_Hangul_J_Rieul, 0x11af}, /* HANGUL JONGSEONG RIEUL */ + {XK_Hangul_J_RieulKiyeog, 0x11b0}, /* HANGUL JONGSEONG RIEUL-KIYEOK */ + {XK_Hangul_J_RieulMieum, 0x11b1}, /* HANGUL JONGSEONG RIEUL-MIEUM */ + {XK_Hangul_J_RieulPieub, 0x11b2}, /* HANGUL JONGSEONG RIEUL-PIEUP */ + {XK_Hangul_J_RieulSios, 0x11b3}, /* HANGUL JONGSEONG RIEUL-SIOS */ + {XK_Hangul_J_RieulTieut, 0x11b4}, /* HANGUL JONGSEONG RIEUL-THIEUTH */ + {XK_Hangul_J_RieulPhieuf, 0x11b5}, /* HANGUL JONGSEONG RIEUL-PHIEUPH */ + {XK_Hangul_J_RieulHieuh, 0x11b6}, /* HANGUL JONGSEONG RIEUL-HIEUH */ + {XK_Hangul_J_Mieum, 0x11b7}, /* HANGUL JONGSEONG MIEUM */ + {XK_Hangul_J_Pieub, 0x11b8}, /* HANGUL JONGSEONG PIEUP */ + {XK_Hangul_J_PieubSios, 0x11b9}, /* HANGUL JONGSEONG PIEUP-SIOS */ + {XK_Hangul_J_Sios, 0x11ba}, /* HANGUL JONGSEONG SIOS */ + {XK_Hangul_J_SsangSios, 0x11bb}, /* HANGUL JONGSEONG SSANGSIOS */ + {XK_Hangul_J_Ieung, 0x11bc}, /* HANGUL JONGSEONG IEUNG */ + {XK_Hangul_J_Jieuj, 0x11bd}, /* HANGUL JONGSEONG CIEUC */ + {XK_Hangul_J_Cieuc, 0x11be}, /* HANGUL JONGSEONG CHIEUCH */ + {XK_Hangul_J_Khieuq, 0x11bf}, /* HANGUL JONGSEONG KHIEUKH */ + {XK_Hangul_J_Tieut, 0x11c0}, /* HANGUL JONGSEONG THIEUTH */ + {XK_Hangul_J_Phieuf, 0x11c1}, /* HANGUL JONGSEONG PHIEUPH */ + {XK_Hangul_J_Hieuh, 0x11c2}, /* HANGUL JONGSEONG HIEUH */ + {XK_Hangul_RieulYeorinHieuh, 0x316d}, /* HANGUL LETTER RIEUL-YEORINHIEUH */ + {XK_Hangul_SunkyeongeumMieum, 0x3171}, /* HANGUL LETTER KAPYEOUNMIEUM */ + {XK_Hangul_SunkyeongeumPieub, 0x3178}, /* HANGUL LETTER KAPYEOUNPIEUP */ + {XK_Hangul_PanSios, 0x317f}, /* HANGUL LETTER PANSIOS */ + {XK_Hangul_KkogjiDalrinIeung, 0x3181}, /* HANGUL LETTER YESIEUNG */ {XK_Hangul_SunkyeongeumPhieuf, 0x3184}, /* HANGUL LETTER KAPYEOUNPHIEUPH */ {XK_Hangul_YeorinHieuh, 0x3186}, /* HANGUL LETTER YEORINHIEUH */ {XK_Hangul_AraeA, 0x318d}, /* HANGUL LETTER ARAEA */ @@ -952,8 +932,8 @@ struct codepair { #endif // defined(XK_Hangul_Kiyeog) {XK_OE, 0x0152}, /* LATIN CAPITAL LIGATURE OE */ {XK_oe, 0x0153}, /* LATIN SMALL LIGATURE OE */ - {XK_Ydiaeresis, 0x0178}, /* LATIN CAPITAL LETTER Y WITH DIAERESIS */ - {XK_EuroSign, 0x20ac}, /* EURO SIGN */ + {XK_Ydiaeresis, 0x0178}, /* LATIN CAPITAL LETTER Y WITH DIAERESIS */ + {XK_EuroSign, 0x20ac}, /* EURO SIGN */ /* combining dead keys */ {XK_dead_abovedot, 0x0307}, /* COMBINING DOT ABOVE */ @@ -1525,7 +1505,8 @@ static const KeySym s_map1008FF[] = { 0, 0, 0, - 0}; + 0 +}; // // XWindowsUtil @@ -1534,8 +1515,9 @@ static const KeySym s_map1008FF[] = { XWindowsUtil::KeySymMap XWindowsUtil::s_keySymToUCS4; bool XWindowsUtil::getWindowProperty( - Display *display, Window window, Atom property, String *data, Atom *type, - SInt32 *format, bool deleteProperty) { + Display *display, Window window, Atom property, String *data, Atom *type, SInt32 *format, bool deleteProperty +) +{ assert(display != NULL); Atom actualType; @@ -1554,9 +1536,9 @@ bool XWindowsUtil::getWindowProperty( unsigned long numItems; unsigned char *rawData; if (XGetWindowProperty( - display, window, property, offset, length, False, AnyPropertyType, - &actualType, &actualDatumSize, &numItems, &bytesLeft, - &rawData) != Success || + display, window, property, offset, length, False, AnyPropertyType, &actualType, &actualDatumSize, &numItems, + &bytesLeft, &rawData + ) != Success || actualType == None || actualDatumSize == 0) { // failed okay = false; @@ -1609,21 +1591,19 @@ bool XWindowsUtil::getWindowProperty( } if (okay) { - LOG( - (CLOG_DEBUG2 "read property %d on window 0x%08x: bytes=%d", property, - window, (data == NULL) ? 0 : data->size())); + LOG((CLOG_DEBUG2 "read property %d on window 0x%08x: bytes=%d", property, window, (data == NULL) ? 0 : data->size()) + ); return true; } else { - LOG( - (CLOG_DEBUG2 "can't read property %d on window 0x%08x", property, - window)); + LOG((CLOG_DEBUG2 "can't read property %d on window 0x%08x", property, window)); return false; } } bool XWindowsUtil::setWindowProperty( - Display *display, Window window, Atom property, const void *vdata, - UInt32 size, Atom type, SInt32 format) { + Display *display, Window window, Atom property, const void *vdata, UInt32 size, Atom type, SInt32 format +) +{ const UInt32 length = 4 * XMaxRequestSize(display); const unsigned char *data = static_cast(vdata); UInt32 datumSize = static_cast(format / 8); @@ -1643,9 +1623,7 @@ bool XWindowsUtil::setWindowProperty( } // send first chunk - XChangeProperty( - display, window, property, type, format, PropModeReplace, data, - chunkSize / datumSize); + XChangeProperty(display, window, property, type, format, PropModeReplace, data, chunkSize / datumSize); // append remaining chunks data += chunkSize; @@ -1655,9 +1633,7 @@ bool XWindowsUtil::setWindowProperty( if (chunkSize > length) { chunkSize = length; } - XChangeProperty( - display, window, property, type, format, PropModeAppend, data, - chunkSize / datumSize); + XChangeProperty(display, window, property, type, format, PropModeAppend, data, chunkSize / datumSize); data += chunkSize; size -= chunkSize; } @@ -1665,7 +1641,8 @@ bool XWindowsUtil::setWindowProperty( return !error; } -Time XWindowsUtil::getCurrentTime(Display *display, Window window) { +Time XWindowsUtil::getCurrentTime(Display *display, Window window) +{ XLockDisplay(display); // select property events on window XWindowAttributes attr; @@ -1677,8 +1654,7 @@ Time XWindowsUtil::getCurrentTime(Display *display, Window window) { // do a zero-length append to get the current time unsigned char dummy; - XChangeProperty( - display, window, atom, XA_INTEGER, 8, PropModeAppend, &dummy, 0); + XChangeProperty(display, window, atom, XA_INTEGER, 8, PropModeAppend, &dummy, 0); // look for property notify events with the following PropertyNotifyPredicateInfo filter; @@ -1687,9 +1663,7 @@ Time XWindowsUtil::getCurrentTime(Display *display, Window window) { // wait for reply XEvent xevent; - XIfEvent( - display, &xevent, &XWindowsUtil::propertyNotifyPredicate, - (XPointer)&filter); + XIfEvent(display, &xevent, &XWindowsUtil::propertyNotifyPredicate, (XPointer)&filter); assert(xevent.type == PropertyNotify); assert(xevent.xproperty.window == window); assert(xevent.xproperty.atom == atom); @@ -1701,7 +1675,8 @@ Time XWindowsUtil::getCurrentTime(Display *display, Window window) { return xevent.xproperty.time; } -KeyID XWindowsUtil::mapKeySymToKeyID(KeySym k) { +KeyID XWindowsUtil::mapKeySymToKeyID(KeySym k) +{ initKeyMaps(); switch (k & 0xffffff00) { @@ -1793,7 +1768,8 @@ KeyID XWindowsUtil::mapKeySymToKeyID(KeySym k) { } } -UInt32 XWindowsUtil::getModifierBitForKeySym(KeySym keysym) { +UInt32 XWindowsUtil::getModifierBitForKeySym(KeySym keysym) +{ switch (keysym) { case XK_Shift_L: case XK_Shift_R: @@ -1840,7 +1816,8 @@ UInt32 XWindowsUtil::getModifierBitForKeySym(KeySym keysym) { } } -String XWindowsUtil::atomToString(Display *display, Atom atom) { +String XWindowsUtil::atomToString(Display *display, Atom atom) +{ if (atom == 0) { return "None"; } @@ -1857,8 +1834,8 @@ String XWindowsUtil::atomToString(Display *display, Atom atom) { } } -String -XWindowsUtil::atomsToString(Display *display, const Atom *atom, UInt32 num) { +String XWindowsUtil::atomsToString(Display *display, const Atom *atom, UInt32 num) +{ char **names = new char *[num]; bool error = false; XWindowsUtil::ErrorLock lock(display, &error); @@ -1881,7 +1858,8 @@ XWindowsUtil::atomsToString(Display *display, const Atom *atom, UInt32 num) { return msg; } -void XWindowsUtil::convertAtomProperty(String &data) { +void XWindowsUtil::convertAtomProperty(String &data) +{ // as best i can tell, 64-bit systems don't pack Atoms into properties // as 32-bit numbers but rather as the 64-bit numbers they are. that // seems wrong but we have to cope. sometimes we'll get a list of @@ -1894,33 +1872,32 @@ void XWindowsUtil::convertAtomProperty(String &data) { } } -void XWindowsUtil::appendAtomData(String &data, Atom atom) { +void XWindowsUtil::appendAtomData(String &data, Atom atom) +{ data.append(reinterpret_cast(&atom), sizeof(Atom)); } -void XWindowsUtil::replaceAtomData(String &data, UInt32 index, Atom atom) { - data.replace( - index * sizeof(Atom), sizeof(Atom), reinterpret_cast(&atom), - sizeof(Atom)); +void XWindowsUtil::replaceAtomData(String &data, UInt32 index, Atom atom) +{ + data.replace(index * sizeof(Atom), sizeof(Atom), reinterpret_cast(&atom), sizeof(Atom)); } -void XWindowsUtil::appendTimeData(String &data, Time time) { +void XWindowsUtil::appendTimeData(String &data, Time time) +{ data.append(reinterpret_cast(&time), sizeof(Time)); } -Bool XWindowsUtil::propertyNotifyPredicate( - Display *, XEvent *xevent, XPointer arg) { - PropertyNotifyPredicateInfo *filter = - reinterpret_cast(arg); - return (xevent->type == PropertyNotify && - xevent->xproperty.window == filter->m_window && - xevent->xproperty.atom == filter->m_property && - xevent->xproperty.state == PropertyNewValue) +Bool XWindowsUtil::propertyNotifyPredicate(Display *, XEvent *xevent, XPointer arg) +{ + PropertyNotifyPredicateInfo *filter = reinterpret_cast(arg); + return (xevent->type == PropertyNotify && xevent->xproperty.window == filter->m_window && + xevent->xproperty.atom == filter->m_property && xevent->xproperty.state == PropertyNewValue) ? True : False; } -void XWindowsUtil::initKeyMaps() { +void XWindowsUtil::initKeyMaps() +{ if (s_keySymToUCS4.empty()) { for (size_t i = 0; i < sizeof(s_keymap) / sizeof(s_keymap[0]); ++i) { s_keySymToUCS4[s_keymap[i].keysym] = s_keymap[i].ucs4; @@ -1934,22 +1911,23 @@ void XWindowsUtil::initKeyMaps() { XWindowsUtil::ErrorLock *XWindowsUtil::ErrorLock::s_top = NULL; -XWindowsUtil::ErrorLock::ErrorLock(Display *display) : m_display(display) { +XWindowsUtil::ErrorLock::ErrorLock(Display *display) : m_display(display) +{ install(&XWindowsUtil::ErrorLock::ignoreHandler, NULL); } -XWindowsUtil::ErrorLock::ErrorLock(Display *display, bool *flag) - : m_display(display) { +XWindowsUtil::ErrorLock::ErrorLock(Display *display, bool *flag) : m_display(display) +{ install(&XWindowsUtil::ErrorLock::saveHandler, flag); } -XWindowsUtil::ErrorLock::ErrorLock( - Display *display, ErrorHandler handler, void *data) - : m_display(display) { +XWindowsUtil::ErrorLock::ErrorLock(Display *display, ErrorHandler handler, void *data) : m_display(display) +{ install(handler, data); } -XWindowsUtil::ErrorLock::~ErrorLock() { +XWindowsUtil::ErrorLock::~ErrorLock() +{ // make sure everything finishes before uninstalling handler if (m_display != NULL) { XSync(m_display, False); @@ -1960,7 +1938,8 @@ XWindowsUtil::ErrorLock::~ErrorLock() { s_top = m_next; } -void XWindowsUtil::ErrorLock::install(ErrorHandler handler, void *data) { +void XWindowsUtil::ErrorLock::install(ErrorHandler handler, void *data) +{ // make sure everything finishes before installing handler if (m_display != NULL) { XSync(m_display, False); @@ -1974,20 +1953,21 @@ void XWindowsUtil::ErrorLock::install(ErrorHandler handler, void *data) { s_top = this; } -int XWindowsUtil::ErrorLock::internalHandler( - Display *display, XErrorEvent *event) { +int XWindowsUtil::ErrorLock::internalHandler(Display *display, XErrorEvent *event) +{ if (s_top != NULL && s_top->m_handler != NULL) { s_top->m_handler(display, event, s_top->m_userData); } return 0; } -void XWindowsUtil::ErrorLock::ignoreHandler(Display *, XErrorEvent *e, void *) { +void XWindowsUtil::ErrorLock::ignoreHandler(Display *, XErrorEvent *e, void *) +{ LOG((CLOG_DEBUG1 "ignoring X error: %d", e->error_code)); } -void XWindowsUtil::ErrorLock::saveHandler( - Display *display, XErrorEvent *e, void *flag) { +void XWindowsUtil::ErrorLock::saveHandler(Display *display, XErrorEvent *e, void *flag) +{ char errtxt[1024]; XGetErrorText(display, e->error_code, errtxt, 1023); LOG((CLOG_DEBUG1 "flagging X error: %d - %.1023s", e->error_code, errtxt)); diff --git a/src/lib/platform/XWindowsUtil.h b/src/lib/platform/XWindowsUtil.h index 479f597e2..0631041b0 100644 --- a/src/lib/platform/XWindowsUtil.h +++ b/src/lib/platform/XWindowsUtil.h @@ -30,7 +30,8 @@ #endif //! X11 utility functions -class XWindowsUtil { +class XWindowsUtil +{ public: typedef std::vector KeySyms; @@ -43,17 +44,16 @@ public: property is deleted after being read. */ static bool getWindowProperty( - Display *, Window window, Atom property, String *data, Atom *type, - SInt32 *format, bool deleteProperty); + Display *, Window window, Atom property, String *data, Atom *type, SInt32 *format, bool deleteProperty + ); //! Set property /*! Sets property \c property on \c window to \c size bytes of data from \c data. */ - static bool setWindowProperty( - Display *, Window window, Atom property, const void *data, UInt32 size, - Atom type, SInt32 format); + static bool + setWindowProperty(Display *, Window window, Atom property, const void *data, UInt32 size, Atom type, SInt32 format); //! Get X server time /*! @@ -125,7 +125,8 @@ public: ErrorLock() ignores errors ErrorLock(bool* flag) sets *flag to true if any error occurs */ - class ErrorLock { + class ErrorLock + { public: //! Error handler type typedef void (*ErrorHandler)(Display *, XErrorEvent *, void *userData); @@ -170,7 +171,8 @@ public: }; private: - class PropertyNotifyPredicateInfo { + class PropertyNotifyPredicateInfo + { public: Window m_window; Atom m_property; diff --git a/src/lib/platform/dfwhook.h b/src/lib/platform/dfwhook.h index 266c64c86..8822663ae 100644 --- a/src/lib/platform/dfwhook.h +++ b/src/lib/platform/dfwhook.h @@ -53,9 +53,20 @@ #define DESKFLOW_HOOK_FAKE_INPUT_VIRTUAL_KEY VK_CANCEL #define DESKFLOW_HOOK_FAKE_INPUT_SCANCODE 0 -extern "C" { +extern "C" +{ -enum EHookResult { kHOOK_FAILED, kHOOK_OKAY, kHOOK_OKAY_LL }; + enum EHookResult + { + kHOOK_FAILED, + kHOOK_OKAY, + kHOOK_OKAY_LL + }; -enum EHookMode { kHOOK_DISABLE, kHOOK_WATCH_JUMP_ZONE, kHOOK_RELAY_EVENTS }; + enum EHookMode + { + kHOOK_DISABLE, + kHOOK_WATCH_JUMP_ZONE, + kHOOK_RELAY_EVENTS + }; } diff --git a/src/lib/platform/wayland.h b/src/lib/platform/wayland.h index 2db0528f6..269629815 100644 --- a/src/lib/platform/wayland.h +++ b/src/lib/platform/wayland.h @@ -39,7 +39,8 @@ const auto kHasPortalInputCapture = true; const auto kHasPortalInputCapture = false; #endif -inline bool isWayland() { +inline bool isWayland() +{ const auto session = getenv("XDG_SESSION_TYPE"); return session != nullptr && std::string(session) == "wayland"; } diff --git a/src/lib/server/BaseClientProxy.cpp b/src/lib/server/BaseClientProxy.cpp index 7cc9aca16..434403574 100644 --- a/src/lib/server/BaseClientProxy.cpp +++ b/src/lib/server/BaseClientProxy.cpp @@ -22,25 +22,29 @@ // BaseClientProxy // -BaseClientProxy::BaseClientProxy(const String &name) - : m_name(name), - m_x(0), - m_y(0) { +BaseClientProxy::BaseClientProxy(const String &name) : m_name(name), m_x(0), m_y(0) +{ // do nothing } -BaseClientProxy::~BaseClientProxy() { +BaseClientProxy::~BaseClientProxy() +{ // do nothing } -void BaseClientProxy::setJumpCursorPos(SInt32 x, SInt32 y) { +void BaseClientProxy::setJumpCursorPos(SInt32 x, SInt32 y) +{ m_x = x; m_y = y; } -void BaseClientProxy::getJumpCursorPos(SInt32 &x, SInt32 &y) const { +void BaseClientProxy::getJumpCursorPos(SInt32 &x, SInt32 &y) const +{ x = m_x; y = m_y; } -String BaseClientProxy::getName() const { return m_name; } +String BaseClientProxy::getName() const +{ + return m_name; +} diff --git a/src/lib/server/BaseClientProxy.h b/src/lib/server/BaseClientProxy.h index 7cf92712d..fbbfe75bc 100644 --- a/src/lib/server/BaseClientProxy.h +++ b/src/lib/server/BaseClientProxy.h @@ -26,7 +26,8 @@ class IStream; } //! Generic proxy for client or primary -class BaseClientProxy : public IClient { +class BaseClientProxy : public IClient +{ public: /*! \c name is the name of the client. @@ -57,28 +58,27 @@ public: /*! Return if this proxy is for client or primary. */ - virtual bool isPrimary() const { return false; } + virtual bool isPrimary() const + { + return false; + } //@} // IScreen virtual void *getEventTarget() const = 0; virtual bool getClipboard(ClipboardID id, IClipboard *) const = 0; - virtual void - getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const = 0; + virtual void getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const = 0; virtual void getCursorPos(SInt32 &x, SInt32 &y) const = 0; // IClient overrides - virtual void enter( - SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, - bool forScreensaver) = 0; + virtual void enter(SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, bool forScreensaver) = 0; virtual bool leave() = 0; virtual void setClipboard(ClipboardID, const IClipboard *) = 0; virtual void grabClipboard(ClipboardID) = 0; virtual void setClipboardDirty(ClipboardID, bool) = 0; virtual void keyDown(KeyID, KeyModifierMask, KeyButton, const String &) = 0; - virtual void keyRepeat( - KeyID, KeyModifierMask, SInt32 count, KeyButton, const String &lang) = 0; + virtual void keyRepeat(KeyID, KeyModifierMask, SInt32 count, KeyButton, const String &lang) = 0; virtual void keyUp(KeyID, KeyModifierMask, KeyButton) = 0; virtual void mouseDown(ButtonID) = 0; virtual void mouseUp(ButtonID) = 0; @@ -88,8 +88,7 @@ public: virtual void screensaver(bool activate) = 0; virtual void resetOptions() = 0; virtual void setOptions(const OptionsList &options) = 0; - virtual void - sendDragInfo(UInt32 fileCount, const char *info, size_t size) = 0; + virtual void sendDragInfo(UInt32 fileCount, const char *info, size_t size) = 0; virtual void fileChunkSending(UInt8 mark, char *data, size_t dataSize) = 0; virtual String getSecureInputApp() const = 0; virtual void secureInputNotification(const String &app) const = 0; diff --git a/src/lib/server/ClientListener.cpp b/src/lib/server/ClientListener.cpp index 0f9993434..c1599dcd7 100644 --- a/src/lib/server/ClientListener.cpp +++ b/src/lib/server/ClientListener.cpp @@ -35,13 +35,14 @@ // ClientListener::ClientListener( - const NetworkAddress &address, ISocketFactory *socketFactory, - IEventQueue *events, bool enableCrypto) + const NetworkAddress &address, ISocketFactory *socketFactory, IEventQueue *events, bool enableCrypto +) : m_socketFactory(socketFactory), m_server(NULL), m_events(events), m_useSecureNetwork(enableCrypto), - m_address(address) { + m_address(address) +{ assert(m_socketFactory != NULL); try { @@ -58,17 +59,20 @@ ClientListener::ClientListener( LOG((CLOG_DEBUG1 "listening for clients")); } -ClientListener::~ClientListener() { +ClientListener::~ClientListener() +{ stop(); delete m_socketFactory; } -void ClientListener::setServer(Server *server) { +void ClientListener::setServer(Server *server) +{ assert(server != NULL); m_server = server; } -ClientProxy *ClientListener::getNextClient() { +ClientProxy *ClientListener::getNextClient() +{ ClientProxy *client = NULL; if (!m_waitingClients.empty()) { client = m_waitingClients.front(); @@ -78,32 +82,30 @@ ClientProxy *ClientListener::getNextClient() { return client; } -void ClientListener::start() { - m_listen = m_socketFactory->createListen( - m_useSecureNetwork, ARCH->getAddrFamily(m_address.getAddress())); +void ClientListener::start() +{ + m_listen = m_socketFactory->createListen(m_useSecureNetwork, ARCH->getAddrFamily(m_address.getAddress())); // setup event handler m_events->adoptHandler( m_events->forIListenSocket().connecting(), m_listen, - new TMethodEventJob( - this, &ClientListener::handleClientConnecting)); + new TMethodEventJob(this, &ClientListener::handleClientConnecting) + ); // bind listen address LOG((CLOG_DEBUG1 "binding listen socket")); m_listen->bind(m_address); } -void ClientListener::stop() { +void ClientListener::stop() +{ LOG((CLOG_DEBUG1 "stop listening for clients")); // discard already connected clients - for (NewClients::iterator index = m_newClients.begin(); - index != m_newClients.end(); ++index) { + for (NewClients::iterator index = m_newClients.begin(); index != m_newClients.end(); ++index) { ClientProxyUnknown *client = *index; - m_events->removeHandler( - m_events->forClientProxyUnknown().success(), client); - m_events->removeHandler( - m_events->forClientProxyUnknown().failure(), client); + m_events->removeHandler(m_events->forClientProxyUnknown().success(), client); + m_events->removeHandler(m_events->forClientProxyUnknown().failure(), client); m_events->removeHandler(m_events->forClientProxy().disconnected(), client); delete client; } @@ -120,25 +122,26 @@ void ClientListener::stop() { cleanupClientSockets(); } -void ClientListener::removeUnknownClient(ClientProxyUnknown *unknownClient) { +void ClientListener::removeUnknownClient(ClientProxyUnknown *unknownClient) +{ if (unknownClient) { - m_events->removeHandler( - m_events->forClientProxyUnknown().success(), unknownClient); - m_events->removeHandler( - m_events->forClientProxyUnknown().failure(), unknownClient); + m_events->removeHandler(m_events->forClientProxyUnknown().success(), unknownClient); + m_events->removeHandler(m_events->forClientProxyUnknown().failure(), unknownClient); m_newClients.erase(unknownClient); delete unknownClient; } } -void ClientListener::restart() { +void ClientListener::restart() +{ if (m_server && m_server->isClientMode()) { stop(); start(); } } -void ClientListener::handleClientConnecting(const Event &, void *) { +void ClientListener::handleClientConnecting(const Event &, void *) +{ // accept client connection IDataSocket *socket = m_listen->accept(); @@ -150,18 +153,18 @@ void ClientListener::handleClientConnecting(const Event &, void *) { m_events->adoptHandler( m_events->forClientListener().accepted(), socket->getEventTarget(), - new TMethodEventJob( - this, &ClientListener::handleClientAccepted, socket)); + new TMethodEventJob(this, &ClientListener::handleClientAccepted, socket) + ); // When using non SSL, server accepts clients immediately, while SSL // has to call secure accept which may require retry if (!m_useSecureNetwork) { - m_events->addEvent(Event( - m_events->forClientListener().accepted(), socket->getEventTarget())); + m_events->addEvent(Event(m_events->forClientListener().accepted(), socket->getEventTarget())); } } -void ClientListener::handleClientAccepted(const Event &, void *vsocket) { +void ClientListener::handleClientAccepted(const Event &, void *vsocket) +{ LOG((CLOG_NOTE "accepted client connection")); IDataSocket *socket = static_cast(vsocket); @@ -171,23 +174,23 @@ void ClientListener::handleClientAccepted(const Event &, void *vsocket) { assert(m_server != NULL); // create proxy for unknown client - ClientProxyUnknown *client = - new ClientProxyUnknown(stream, 30.0, m_server, m_events); + ClientProxyUnknown *client = new ClientProxyUnknown(stream, 30.0, m_server, m_events); m_newClients.insert(client); // watch for events from unknown client m_events->adoptHandler( m_events->forClientProxyUnknown().success(), client, - new TMethodEventJob( - this, &ClientListener::handleUnknownClient, client)); + new TMethodEventJob(this, &ClientListener::handleUnknownClient, client) + ); m_events->adoptHandler( m_events->forClientProxyUnknown().failure(), client, - new TMethodEventJob( - this, &ClientListener::handleUnknownClientFailure, client)); + new TMethodEventJob(this, &ClientListener::handleUnknownClientFailure, client) + ); } -void ClientListener::handleUnknownClient(const Event &, void *vclient) { +void ClientListener::handleUnknownClient(const Event &, void *vclient) +{ auto unknownClient = static_cast(vclient); // we should have the client in our new client list @@ -203,31 +206,30 @@ void ClientListener::handleUnknownClient(const Event &, void *vclient) { // watch for client to disconnect while it's in our queue m_events->adoptHandler( m_events->forClientProxy().disconnected(), client, - new TMethodEventJob( - this, &ClientListener::handleClientDisconnected, client)); + new TMethodEventJob(this, &ClientListener::handleClientDisconnected, client) + ); } // now finished with unknown client removeUnknownClient(unknownClient); } -void ClientListener::handleUnknownClientFailure(const Event &, void *vclient) { +void ClientListener::handleUnknownClientFailure(const Event &, void *vclient) +{ auto unknownClient = static_cast(vclient); removeUnknownClient(unknownClient); restart(); } -void ClientListener::handleClientDisconnected(const Event &, void *vclient) { +void ClientListener::handleClientDisconnected(const Event &, void *vclient) +{ ClientProxy *client = static_cast(vclient); // find client in waiting clients queue - for (WaitingClients::iterator i = m_waitingClients.begin(), - n = m_waitingClients.end(); - i != n; ++i) { + for (WaitingClients::iterator i = m_waitingClients.begin(), n = m_waitingClients.end(); i != n; ++i) { if (*i == client) { m_waitingClients.erase(i); - m_events->removeHandler( - m_events->forClientProxy().disconnected(), client); + m_events->removeHandler(m_events->forClientProxy().disconnected(), client); // pull out the socket before deleting the client so // we know which socket we no longer need @@ -241,9 +243,13 @@ void ClientListener::handleClientDisconnected(const Event &, void *vclient) { } } -void ClientListener::cleanupListenSocket() { delete m_listen; } +void ClientListener::cleanupListenSocket() +{ + delete m_listen; +} -void ClientListener::cleanupClientSockets() { +void ClientListener::cleanupClientSockets() +{ ClientSockets::iterator it; for (it = m_clientSockets.begin(); it != m_clientSockets.end(); it++) { delete *it; diff --git a/src/lib/server/ClientListener.h b/src/lib/server/ClientListener.h index de4960d04..55ec09242 100644 --- a/src/lib/server/ClientListener.h +++ b/src/lib/server/ClientListener.h @@ -33,12 +33,11 @@ class Server; class IEventQueue; class IDataSocket; -class ClientListener { +class ClientListener +{ public: // The factories are adopted. - ClientListener( - const NetworkAddress &, ISocketFactory *, IEventQueue *events, - bool enableCrypto); + ClientListener(const NetworkAddress &, ISocketFactory *, IEventQueue *events, bool enableCrypto); ClientListener(ClientListener const &) = delete; ClientListener(ClientListener &&) = delete; ~ClientListener(); @@ -65,7 +64,10 @@ public: ClientProxy *getNextClient(); //! Get server which owns this listener - Server *getServer() { return m_server; } + Server *getServer() + { + return m_server; + } //! This method restarts the listener void restart(); diff --git a/src/lib/server/ClientProxy.cpp b/src/lib/server/ClientProxy.cpp index b914822dd..6848ee185 100644 --- a/src/lib/server/ClientProxy.cpp +++ b/src/lib/server/ClientProxy.cpp @@ -27,13 +27,17 @@ // ClientProxy // -ClientProxy::ClientProxy(const String &name, deskflow::IStream *stream) - : BaseClientProxy(name), - m_stream(stream) {} +ClientProxy::ClientProxy(const String &name, deskflow::IStream *stream) : BaseClientProxy(name), m_stream(stream) +{ +} -ClientProxy::~ClientProxy() { delete m_stream; } +ClientProxy::~ClientProxy() +{ + delete m_stream; +} -void ClientProxy::close(const char *msg) { +void ClientProxy::close(const char *msg) +{ LOG((CLOG_DEBUG1 "send close \"%s\" to \"%s\"", msg, getName().c_str())); ProtocolUtil::writef(getStream(), msg); @@ -41,8 +45,12 @@ void ClientProxy::close(const char *msg) { getStream()->flush(); } -deskflow::IStream *ClientProxy::getStream() const { return m_stream; } +deskflow::IStream *ClientProxy::getStream() const +{ + return m_stream; +} -void *ClientProxy::getEventTarget() const { +void *ClientProxy::getEventTarget() const +{ return static_cast(const_cast(this)); } diff --git a/src/lib/server/ClientProxy.h b/src/lib/server/ClientProxy.h index 54262529f..fca45008d 100644 --- a/src/lib/server/ClientProxy.h +++ b/src/lib/server/ClientProxy.h @@ -28,7 +28,8 @@ class IStream; } //! Generic proxy for client -class ClientProxy : public BaseClientProxy { +class ClientProxy : public BaseClientProxy +{ public: /*! \c name is the name of the client. @@ -65,22 +66,17 @@ public: // IScreen void *getEventTarget() const override; bool getClipboard(ClipboardID id, IClipboard *) const override = 0; - void getShape( - SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const override = 0; + void getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const override = 0; void getCursorPos(SInt32 &x, SInt32 &y) const override = 0; // IClient overrides - void enter( - SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, - bool forScreensaver) override = 0; + void enter(SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, bool forScreensaver) override = 0; bool leave() override = 0; void setClipboard(ClipboardID, const IClipboard *) override = 0; void grabClipboard(ClipboardID) override = 0; void setClipboardDirty(ClipboardID, bool) override = 0; void keyDown(KeyID, KeyModifierMask, KeyButton, const String &) override = 0; - void keyRepeat( - KeyID, KeyModifierMask, SInt32 count, KeyButton, - const String &lang) override = 0; + void keyRepeat(KeyID, KeyModifierMask, SInt32 count, KeyButton, const String &lang) override = 0; void keyUp(KeyID, KeyModifierMask, KeyButton) override = 0; void mouseDown(ButtonID) override = 0; void mouseUp(ButtonID) override = 0; @@ -90,8 +86,7 @@ public: void screensaver(bool activate) override = 0; void resetOptions() override = 0; void setOptions(const OptionsList &options) override = 0; - void - sendDragInfo(UInt32 fileCount, const char *info, size_t size) override = 0; + void sendDragInfo(UInt32 fileCount, const char *info, size_t size) override = 0; void fileChunkSending(UInt8 mark, char *data, size_t dataSize) override = 0; void secureInputNotification(const String &app) const override = 0; diff --git a/src/lib/server/ClientProxy1_0.cpp b/src/lib/server/ClientProxy1_0.cpp index d87ccdb74..31b51020f 100644 --- a/src/lib/server/ClientProxy1_0.cpp +++ b/src/lib/server/ClientProxy1_0.cpp @@ -31,33 +31,32 @@ // ClientProxy1_0 // -ClientProxy1_0::ClientProxy1_0( - const String &name, deskflow::IStream *stream, IEventQueue *events) +ClientProxy1_0::ClientProxy1_0(const String &name, deskflow::IStream *stream, IEventQueue *events) : ClientProxy(name, stream), m_heartbeatTimer(NULL), m_parser(&ClientProxy1_0::parseHandshakeMessage), - m_events(events) { + m_events(events) +{ // install event handlers m_events->adoptHandler( m_events->forIStream().inputReady(), stream->getEventTarget(), - new TMethodEventJob( - this, &ClientProxy1_0::handleData, NULL)); + new TMethodEventJob(this, &ClientProxy1_0::handleData, NULL) + ); m_events->adoptHandler( m_events->forIStream().outputError(), stream->getEventTarget(), - new TMethodEventJob( - this, &ClientProxy1_0::handleWriteError, NULL)); + new TMethodEventJob(this, &ClientProxy1_0::handleWriteError, NULL) + ); m_events->adoptHandler( m_events->forIStream().inputShutdown(), stream->getEventTarget(), - new TMethodEventJob( - this, &ClientProxy1_0::handleDisconnect, NULL)); + new TMethodEventJob(this, &ClientProxy1_0::handleDisconnect, NULL) + ); m_events->adoptHandler( m_events->forIStream().outputShutdown(), stream->getEventTarget(), - new TMethodEventJob( - this, &ClientProxy1_0::handleWriteError, NULL)); + new TMethodEventJob(this, &ClientProxy1_0::handleWriteError, NULL) + ); m_events->adoptHandler( - Event::kTimer, this, - new TMethodEventJob( - this, &ClientProxy1_0::handleFlatline, NULL)); + Event::kTimer, this, new TMethodEventJob(this, &ClientProxy1_0::handleFlatline, NULL) + ); setHeartbeatRate(kHeartRate, kHeartRate * kHeartBeatsUntilDeath); @@ -65,80 +64,82 @@ ClientProxy1_0::ClientProxy1_0( ProtocolUtil::writef(getStream(), kMsgQInfo); } -ClientProxy1_0::~ClientProxy1_0() { removeHandlers(); } - -void ClientProxy1_0::disconnect() { +ClientProxy1_0::~ClientProxy1_0() +{ removeHandlers(); - getStream()->close(); - m_events->addEvent( - Event(m_events->forClientProxy().disconnected(), getEventTarget())); } -void ClientProxy1_0::removeHandlers() { +void ClientProxy1_0::disconnect() +{ + removeHandlers(); + getStream()->close(); + m_events->addEvent(Event(m_events->forClientProxy().disconnected(), getEventTarget())); +} + +void ClientProxy1_0::removeHandlers() +{ // uninstall event handlers - m_events->removeHandler( - m_events->forIStream().inputReady(), getStream()->getEventTarget()); - m_events->removeHandler( - m_events->forIStream().outputError(), getStream()->getEventTarget()); - m_events->removeHandler( - m_events->forIStream().inputShutdown(), getStream()->getEventTarget()); - m_events->removeHandler( - m_events->forIStream().outputShutdown(), getStream()->getEventTarget()); + m_events->removeHandler(m_events->forIStream().inputReady(), getStream()->getEventTarget()); + m_events->removeHandler(m_events->forIStream().outputError(), getStream()->getEventTarget()); + m_events->removeHandler(m_events->forIStream().inputShutdown(), getStream()->getEventTarget()); + m_events->removeHandler(m_events->forIStream().outputShutdown(), getStream()->getEventTarget()); m_events->removeHandler(Event::kTimer, this); // remove timer removeHeartbeatTimer(); } -void ClientProxy1_0::addHeartbeatTimer() { +void ClientProxy1_0::addHeartbeatTimer() +{ if (m_heartbeatAlarm > 0.0) { m_heartbeatTimer = m_events->newOneShotTimer(m_heartbeatAlarm, this); } } -void ClientProxy1_0::removeHeartbeatTimer() { +void ClientProxy1_0::removeHeartbeatTimer() +{ if (m_heartbeatTimer != NULL) { m_events->deleteTimer(m_heartbeatTimer); m_heartbeatTimer = NULL; } } -void ClientProxy1_0::resetHeartbeatTimer() { +void ClientProxy1_0::resetHeartbeatTimer() +{ // reset the alarm removeHeartbeatTimer(); addHeartbeatTimer(); } -void ClientProxy1_0::resetHeartbeatRate() { +void ClientProxy1_0::resetHeartbeatRate() +{ setHeartbeatRate(kHeartRate, kHeartRate * kHeartBeatsUntilDeath); } -void ClientProxy1_0::setHeartbeatRate(double, double alarm) { +void ClientProxy1_0::setHeartbeatRate(double, double alarm) +{ m_heartbeatAlarm = alarm; } -void ClientProxy1_0::handleData(const Event &, void *) { +void ClientProxy1_0::handleData(const Event &, void *) +{ // handle messages until there are no more. first read message code. UInt8 code[4]; UInt32 n = getStream()->read(code, 4); while (n != 0) { // verify we got an entire code if (n != 4) { - LOG( - (CLOG_ERR "incomplete message from \"%s\": %d bytes", - getName().c_str(), n)); + LOG((CLOG_ERR "incomplete message from \"%s\": %d bytes", getName().c_str(), n)); disconnect(); return; } // parse message - LOG( - (CLOG_DEBUG2 "msg from \"%s\": %c%c%c%c", getName().c_str(), code[0], - code[1], code[2], code[3])); + LOG((CLOG_DEBUG2 "msg from \"%s\": %c%c%c%c", getName().c_str(), code[0], code[1], code[2], code[3])); if (!(this->*m_parser)(code)) { - LOG( - (CLOG_ERR "invalid message from client \"%s\": %c%c%c%c", - getName().c_str(), code[0], code[1], code[2], code[3])); + LOG(( + CLOG_ERR "invalid message from client \"%s\": %c%c%c%c", getName().c_str(), code[0], code[1], code[2], code[3] + )); // not possible to determine message boundaries // read the whole stream to discard unkonwn data while (getStream()->read(nullptr, 4)) @@ -153,7 +154,8 @@ void ClientProxy1_0::handleData(const Event &, void *) { resetHeartbeatTimer(); } -bool ClientProxy1_0::parseHandshakeMessage(const UInt8 *code) { +bool ClientProxy1_0::parseHandshakeMessage(const UInt8 *code) +{ if (memcmp(code, kMsgCNoop, 4) == 0) { // discard no-ops LOG((CLOG_DEBUG2 "no-op from", getName().c_str())); @@ -162,8 +164,7 @@ bool ClientProxy1_0::parseHandshakeMessage(const UInt8 *code) { // future messages get parsed by parseMessage m_parser = &ClientProxy1_0::parseMessage; if (recvInfo()) { - m_events->addEvent( - Event(m_events->forClientProxy().ready(), getEventTarget())); + m_events->addEvent(Event(m_events->forClientProxy().ready(), getEventTarget())); addHeartbeatTimer(); return true; } @@ -171,11 +172,11 @@ bool ClientProxy1_0::parseHandshakeMessage(const UInt8 *code) { return false; } -bool ClientProxy1_0::parseMessage(const UInt8 *code) { +bool ClientProxy1_0::parseMessage(const UInt8 *code) +{ if (memcmp(code, kMsgDInfo, 4) == 0) { if (recvInfo()) { - m_events->addEvent( - Event(m_events->forIScreen().shapeChanged(), getEventTarget())); + m_events->addEvent(Event(m_events->forIScreen().shapeChanged(), getEventTarget())); return true; } return false; @@ -191,50 +192,54 @@ bool ClientProxy1_0::parseMessage(const UInt8 *code) { return false; } -void ClientProxy1_0::handleDisconnect(const Event &, void *) { +void ClientProxy1_0::handleDisconnect(const Event &, void *) +{ LOG((CLOG_NOTE "client \"%s\" has disconnected", getName().c_str())); disconnect(); } -void ClientProxy1_0::handleWriteError(const Event &, void *) { +void ClientProxy1_0::handleWriteError(const Event &, void *) +{ LOG((CLOG_WARN "error writing to client \"%s\"", getName().c_str())); disconnect(); } -void ClientProxy1_0::handleFlatline(const Event &, void *) { +void ClientProxy1_0::handleFlatline(const Event &, void *) +{ // didn't get a heartbeat fast enough. assume client is dead. LOG((CLOG_NOTE "client \"%s\" is dead", getName().c_str())); disconnect(); } -bool ClientProxy1_0::getClipboard(ClipboardID id, IClipboard *clipboard) const { +bool ClientProxy1_0::getClipboard(ClipboardID id, IClipboard *clipboard) const +{ Clipboard::copy(clipboard, &m_clipboard[id].m_clipboard); return true; } -void ClientProxy1_0::getShape( - SInt32 &x, SInt32 &y, SInt32 &w, SInt32 &h) const { +void ClientProxy1_0::getShape(SInt32 &x, SInt32 &y, SInt32 &w, SInt32 &h) const +{ x = m_info.m_x; y = m_info.m_y; w = m_info.m_w; h = m_info.m_h; } -void ClientProxy1_0::getCursorPos(SInt32 &x, SInt32 &y) const { +void ClientProxy1_0::getCursorPos(SInt32 &x, SInt32 &y) const +{ // note -- this returns the cursor pos from when we last got client info x = m_info.m_mx; y = m_info.m_my; } -void ClientProxy1_0::enter( - SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, bool) { - LOG( - (CLOG_DEBUG1 "send enter to \"%s\", %d,%d %d %04x", getName().c_str(), - xAbs, yAbs, seqNum, mask)); +void ClientProxy1_0::enter(SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, bool) +{ + LOG((CLOG_DEBUG1 "send enter to \"%s\", %d,%d %d %04x", getName().c_str(), xAbs, yAbs, seqNum, mask)); ProtocolUtil::writef(getStream(), kMsgCEnter, xAbs, yAbs, seqNum, mask); } -bool ClientProxy1_0::leave() { +bool ClientProxy1_0::leave() +{ LOG((CLOG_DEBUG1 "send leave to \"%s\"", getName().c_str())); ProtocolUtil::writef(getStream(), kMsgCLeave); @@ -242,11 +247,13 @@ bool ClientProxy1_0::leave() { return true; } -void ClientProxy1_0::setClipboard(ClipboardID id, const IClipboard *clipboard) { +void ClientProxy1_0::setClipboard(ClipboardID id, const IClipboard *clipboard) +{ // ignore -- deprecated in protocol 1.0 } -void ClientProxy1_0::grabClipboard(ClipboardID id) { +void ClientProxy1_0::grabClipboard(ClipboardID id) +{ LOG((CLOG_DEBUG "send grab clipboard %d to \"%s\"", id, getName().c_str())); ProtocolUtil::writef(getStream(), kMsgCClipboard, id, 0); @@ -254,93 +261,92 @@ void ClientProxy1_0::grabClipboard(ClipboardID id) { m_clipboard[id].m_dirty = true; } -void ClientProxy1_0::setClipboardDirty(ClipboardID id, bool dirty) { +void ClientProxy1_0::setClipboardDirty(ClipboardID id, bool dirty) +{ m_clipboard[id].m_dirty = dirty; } -void ClientProxy1_0::keyDown( - KeyID key, KeyModifierMask mask, KeyButton, const String &) { - LOG( - (CLOG_DEBUG1 "send key down to \"%s\" id=%d, mask=0x%04x", - getName().c_str(), key, mask)); +void ClientProxy1_0::keyDown(KeyID key, KeyModifierMask mask, KeyButton, const String &) +{ + LOG((CLOG_DEBUG1 "send key down to \"%s\" id=%d, mask=0x%04x", getName().c_str(), key, mask)); ProtocolUtil::writef(getStream(), kMsgDKeyDown1_0, key, mask); } -void ClientProxy1_0::keyRepeat( - KeyID key, KeyModifierMask mask, SInt32 count, KeyButton, const String &) { - LOG( - (CLOG_DEBUG1 "send key repeat to \"%s\" id=%d, mask=0x%04x, count=%d", - getName().c_str(), key, mask, count)); +void ClientProxy1_0::keyRepeat(KeyID key, KeyModifierMask mask, SInt32 count, KeyButton, const String &) +{ + LOG((CLOG_DEBUG1 "send key repeat to \"%s\" id=%d, mask=0x%04x, count=%d", getName().c_str(), key, mask, count)); ProtocolUtil::writef(getStream(), kMsgDKeyRepeat1_0, key, mask, count); } -void ClientProxy1_0::keyUp(KeyID key, KeyModifierMask mask, KeyButton) { - LOG( - (CLOG_DEBUG1 "send key up to \"%s\" id=%d, mask=0x%04x", - getName().c_str(), key, mask)); +void ClientProxy1_0::keyUp(KeyID key, KeyModifierMask mask, KeyButton) +{ + LOG((CLOG_DEBUG1 "send key up to \"%s\" id=%d, mask=0x%04x", getName().c_str(), key, mask)); ProtocolUtil::writef(getStream(), kMsgDKeyUp1_0, key, mask); } -void ClientProxy1_0::mouseDown(ButtonID button) { - LOG( - (CLOG_DEBUG1 "send mouse down to \"%s\" id=%d", getName().c_str(), - button)); +void ClientProxy1_0::mouseDown(ButtonID button) +{ + LOG((CLOG_DEBUG1 "send mouse down to \"%s\" id=%d", getName().c_str(), button)); ProtocolUtil::writef(getStream(), kMsgDMouseDown, button); } -void ClientProxy1_0::mouseUp(ButtonID button) { +void ClientProxy1_0::mouseUp(ButtonID button) +{ LOG((CLOG_DEBUG1 "send mouse up to \"%s\" id=%d", getName().c_str(), button)); ProtocolUtil::writef(getStream(), kMsgDMouseUp, button); } -void ClientProxy1_0::mouseMove(SInt32 xAbs, SInt32 yAbs) { - LOG( - (CLOG_DEBUG2 "send mouse move to \"%s\" %d,%d", getName().c_str(), xAbs, - yAbs)); +void ClientProxy1_0::mouseMove(SInt32 xAbs, SInt32 yAbs) +{ + LOG((CLOG_DEBUG2 "send mouse move to \"%s\" %d,%d", getName().c_str(), xAbs, yAbs)); ProtocolUtil::writef(getStream(), kMsgDMouseMove, xAbs, yAbs); } -void ClientProxy1_0::mouseRelativeMove(SInt32, SInt32) { +void ClientProxy1_0::mouseRelativeMove(SInt32, SInt32) +{ // ignore -- not supported in protocol 1.0 } -void ClientProxy1_0::mouseWheel(SInt32, SInt32 yDelta) { +void ClientProxy1_0::mouseWheel(SInt32, SInt32 yDelta) +{ // clients prior to 1.3 only support the y axis - LOG(( - CLOG_DEBUG2 "send mouse wheel to \"%s\" %+d", getName().c_str(), yDelta)); + LOG((CLOG_DEBUG2 "send mouse wheel to \"%s\" %+d", getName().c_str(), yDelta)); ProtocolUtil::writef(getStream(), kMsgDMouseWheel1_0, yDelta); } -void ClientProxy1_0::sendDragInfo( - UInt32 fileCount, const char *info, size_t size) { +void ClientProxy1_0::sendDragInfo(UInt32 fileCount, const char *info, size_t size) +{ // ignore -- not supported in protocol 1.0 LOG((CLOG_DEBUG "draggingInfoSending not supported")); } -void ClientProxy1_0::fileChunkSending(UInt8 mark, char *data, size_t dataSize) { +void ClientProxy1_0::fileChunkSending(UInt8 mark, char *data, size_t dataSize) +{ // ignore -- not supported in protocol 1.0 LOG((CLOG_DEBUG "fileChunkSending not supported")); } -String ClientProxy1_0::getSecureInputApp() const { +String ClientProxy1_0::getSecureInputApp() const +{ // ignore -- not supported on clients LOG((CLOG_DEBUG "getSecureInputApp not supported")); return ""; } -void ClientProxy1_0::secureInputNotification(const String &app) const { +void ClientProxy1_0::secureInputNotification(const String &app) const +{ // ignore -- not supported in protocol 1.0 LOG((CLOG_DEBUG "secureInputNotification not supported")); } -void ClientProxy1_0::screensaver(bool on) { - LOG( - (CLOG_DEBUG1 "send screen saver to \"%s\" on=%d", getName().c_str(), - on ? 1 : 0)); +void ClientProxy1_0::screensaver(bool on) +{ + LOG((CLOG_DEBUG1 "send screen saver to \"%s\" on=%d", getName().c_str(), on ? 1 : 0)); ProtocolUtil::writef(getStream(), kMsgCScreenSaver, on ? 1 : 0); } -void ClientProxy1_0::resetOptions() { +void ClientProxy1_0::resetOptions() +{ LOG((CLOG_DEBUG1 "send reset options to \"%s\"", getName().c_str())); ProtocolUtil::writef(getStream(), kMsgCResetOptions); @@ -350,10 +356,9 @@ void ClientProxy1_0::resetOptions() { addHeartbeatTimer(); } -void ClientProxy1_0::setOptions(const OptionsList &options) { - LOG( - (CLOG_DEBUG1 "send set options to \"%s\" size=%d", getName().c_str(), - options.size())); +void ClientProxy1_0::setOptions(const OptionsList &options) +{ + LOG((CLOG_DEBUG1 "send set options to \"%s\" size=%d", getName().c_str(), options.size())); ProtocolUtil::writef(getStream(), kMsgDSetOptions, &options); // check options @@ -370,16 +375,14 @@ void ClientProxy1_0::setOptions(const OptionsList &options) { } } -bool ClientProxy1_0::recvInfo() { +bool ClientProxy1_0::recvInfo() +{ // parse the message SInt16 x, y, w, h, dummy1, mx, my; - if (!ProtocolUtil::readf( - getStream(), kMsgDInfo + 4, &x, &y, &w, &h, &dummy1, &mx, &my)) { + if (!ProtocolUtil::readf(getStream(), kMsgDInfo + 4, &x, &y, &w, &h, &dummy1, &mx, &my)) { return false; } - LOG( - (CLOG_DEBUG "received client \"%s\" info shape=%d,%d %dx%d at %d,%d", - getName().c_str(), x, y, w, h, mx, my)); + LOG((CLOG_DEBUG "received client \"%s\" info shape=%d,%d %dx%d at %d,%d", getName().c_str(), x, y, w, h, mx, my)); // validate if (w <= 0 || h <= 0) { @@ -404,21 +407,21 @@ bool ClientProxy1_0::recvInfo() { return true; } -bool ClientProxy1_0::recvClipboard() { +bool ClientProxy1_0::recvClipboard() +{ // deprecated in protocol 1.0 return false; } -bool ClientProxy1_0::recvGrabClipboard() { +bool ClientProxy1_0::recvGrabClipboard() +{ // parse message ClipboardID id; UInt32 seqNum; if (!ProtocolUtil::readf(getStream(), kMsgCClipboard + 4, &id, &seqNum)) { return false; } - LOG( - (CLOG_DEBUG "received client \"%s\" grabbed clipboard %d seqnum=%d", - getName().c_str(), id, seqNum)); + LOG((CLOG_DEBUG "received client \"%s\" grabbed clipboard %d seqnum=%d", getName().c_str(), id, seqNum)); // validate if (id >= kClipboardEnd) { @@ -429,8 +432,7 @@ bool ClientProxy1_0::recvGrabClipboard() { ClipboardInfo *info = new ClipboardInfo; info->m_id = id; info->m_sequenceNumber = seqNum; - m_events->addEvent(Event( - m_events->forClipboard().clipboardGrabbed(), getEventTarget(), info)); + m_events->addEvent(Event(m_events->forClipboard().clipboardGrabbed(), getEventTarget(), info)); return true; } @@ -439,9 +441,7 @@ bool ClientProxy1_0::recvGrabClipboard() { // ClientProxy1_0::ClientClipboard // -ClientProxy1_0::ClientClipboard::ClientClipboard() - : m_clipboard(), - m_sequenceNumber(0), - m_dirty(true) { +ClientProxy1_0::ClientClipboard::ClientClipboard() : m_clipboard(), m_sequenceNumber(0), m_dirty(true) +{ // do nothing } diff --git a/src/lib/server/ClientProxy1_0.h b/src/lib/server/ClientProxy1_0.h index b3d05ad16..0339b44e6 100644 --- a/src/lib/server/ClientProxy1_0.h +++ b/src/lib/server/ClientProxy1_0.h @@ -27,11 +27,10 @@ class EventQueueTimer; class IEventQueue; //! Proxy for client implementing protocol version 1.0 -class ClientProxy1_0 : public ClientProxy { +class ClientProxy1_0 : public ClientProxy +{ public: - ClientProxy1_0( - const String &name, deskflow::IStream *adoptedStream, - IEventQueue *events); + ClientProxy1_0(const String &name, deskflow::IStream *adoptedStream, IEventQueue *events); ClientProxy1_0(ClientProxy1_0 const &) = delete; ClientProxy1_0(ClientProxy1_0 &&) = delete; ~ClientProxy1_0(); @@ -41,21 +40,17 @@ public: // IScreen bool getClipboard(ClipboardID id, IClipboard *) const override; - void - getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const override; + void getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const override; void getCursorPos(SInt32 &x, SInt32 &y) const override; // IClient overrides - void enter( - SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, - bool forScreensaver) override; + void enter(SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, bool forScreensaver) override; bool leave() override; void setClipboard(ClipboardID, const IClipboard *) override; void grabClipboard(ClipboardID) override; void setClipboardDirty(ClipboardID, bool) override; void keyDown(KeyID, KeyModifierMask, KeyButton, const String &) override; - void keyRepeat( - KeyID, KeyModifierMask, SInt32 count, KeyButton, const String &) override; + void keyRepeat(KeyID, KeyModifierMask, SInt32 count, KeyButton, const String &) override; void keyUp(KeyID, KeyModifierMask, KeyButton) override; void mouseDown(ButtonID) override; void mouseUp(ButtonID) override; @@ -94,7 +89,8 @@ private: bool recvGrabClipboard(); protected: - struct ClientClipboard { + struct ClientClipboard + { public: ClientClipboard(); diff --git a/src/lib/server/ClientProxy1_1.cpp b/src/lib/server/ClientProxy1_1.cpp index e22b276dc..16c71ec02 100644 --- a/src/lib/server/ClientProxy1_1.cpp +++ b/src/lib/server/ClientProxy1_1.cpp @@ -28,38 +28,35 @@ // ClientProxy1_1 // -ClientProxy1_1::ClientProxy1_1( - const String &name, deskflow::IStream *stream, IEventQueue *events) - : ClientProxy1_0(name, stream, events) { +ClientProxy1_1::ClientProxy1_1(const String &name, deskflow::IStream *stream, IEventQueue *events) + : ClientProxy1_0(name, stream, events) +{ // do nothing } -ClientProxy1_1::~ClientProxy1_1() { +ClientProxy1_1::~ClientProxy1_1() +{ // do nothing } -void ClientProxy1_1::keyDown( - KeyID key, KeyModifierMask mask, KeyButton button, const String &) { - LOG( - (CLOG_DEBUG1 "send key down to \"%s\" id=%d, mask=0x%04x, button=0x%04x", - getName().c_str(), key, mask, button)); +void ClientProxy1_1::keyDown(KeyID key, KeyModifierMask mask, KeyButton button, const String &) +{ + LOG((CLOG_DEBUG1 "send key down to \"%s\" id=%d, mask=0x%04x, button=0x%04x", getName().c_str(), key, mask, button)); ProtocolUtil::writef(getStream(), kMsgDKeyDown, key, mask, button); } -void ClientProxy1_1::keyRepeat( - KeyID key, KeyModifierMask mask, SInt32 count, KeyButton button, - const String &lang) { +void ClientProxy1_1::keyRepeat(KeyID key, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang) +{ LOG( (CLOG_DEBUG1 "send key repeat to \"%s\" id=%d, mask=0x%04x, count=%d, " "button=0x%04x, lang=\"%s\"", - getName().c_str(), key, mask, count, button, lang.c_str())); - ProtocolUtil::writef( - getStream(), kMsgDKeyRepeat, key, mask, count, button, &lang); + getName().c_str(), key, mask, count, button, lang.c_str()) + ); + ProtocolUtil::writef(getStream(), kMsgDKeyRepeat, key, mask, count, button, &lang); } -void ClientProxy1_1::keyUp(KeyID key, KeyModifierMask mask, KeyButton button) { - LOG( - (CLOG_DEBUG1 "send key up to \"%s\" id=%d, mask=0x%04x, button=0x%04x", - getName().c_str(), key, mask, button)); +void ClientProxy1_1::keyUp(KeyID key, KeyModifierMask mask, KeyButton button) +{ + LOG((CLOG_DEBUG1 "send key up to \"%s\" id=%d, mask=0x%04x, button=0x%04x", getName().c_str(), key, mask, button)); ProtocolUtil::writef(getStream(), kMsgDKeyUp, key, mask, button); } diff --git a/src/lib/server/ClientProxy1_1.h b/src/lib/server/ClientProxy1_1.h index 489dc78a1..0f22bb3c0 100644 --- a/src/lib/server/ClientProxy1_1.h +++ b/src/lib/server/ClientProxy1_1.h @@ -21,16 +21,14 @@ #include "server/ClientProxy1_0.h" //! Proxy for client implementing protocol version 1.1 -class ClientProxy1_1 : public ClientProxy1_0 { +class ClientProxy1_1 : public ClientProxy1_0 +{ public: - ClientProxy1_1( - const String &name, deskflow::IStream *adoptedStream, - IEventQueue *events); + ClientProxy1_1(const String &name, deskflow::IStream *adoptedStream, IEventQueue *events); ~ClientProxy1_1(); // IClient overrides virtual void keyDown(KeyID, KeyModifierMask, KeyButton, const String &); - virtual void - keyRepeat(KeyID, KeyModifierMask, SInt32 count, KeyButton, const String &); + virtual void keyRepeat(KeyID, KeyModifierMask, SInt32 count, KeyButton, const String &); virtual void keyUp(KeyID, KeyModifierMask, KeyButton); }; diff --git a/src/lib/server/ClientProxy1_2.cpp b/src/lib/server/ClientProxy1_2.cpp index 4da79b567..7d65d9ed6 100644 --- a/src/lib/server/ClientProxy1_2.cpp +++ b/src/lib/server/ClientProxy1_2.cpp @@ -25,19 +25,19 @@ // ClientProxy1_1 // -ClientProxy1_2::ClientProxy1_2( - const String &name, deskflow::IStream *stream, IEventQueue *events) - : ClientProxy1_1(name, stream, events) { +ClientProxy1_2::ClientProxy1_2(const String &name, deskflow::IStream *stream, IEventQueue *events) + : ClientProxy1_1(name, stream, events) +{ // do nothing } -ClientProxy1_2::~ClientProxy1_2() { +ClientProxy1_2::~ClientProxy1_2() +{ // do nothing } -void ClientProxy1_2::mouseRelativeMove(SInt32 xRel, SInt32 yRel) { - LOG( - (CLOG_DEBUG2 "send mouse relative move to \"%s\" %d,%d", - getName().c_str(), xRel, yRel)); +void ClientProxy1_2::mouseRelativeMove(SInt32 xRel, SInt32 yRel) +{ + LOG((CLOG_DEBUG2 "send mouse relative move to \"%s\" %d,%d", getName().c_str(), xRel, yRel)); ProtocolUtil::writef(getStream(), kMsgDMouseRelMove, xRel, yRel); } diff --git a/src/lib/server/ClientProxy1_2.h b/src/lib/server/ClientProxy1_2.h index 8829588bd..5ebd73a3a 100644 --- a/src/lib/server/ClientProxy1_2.h +++ b/src/lib/server/ClientProxy1_2.h @@ -23,11 +23,10 @@ class IEventQueue; //! Proxy for client implementing protocol version 1.2 -class ClientProxy1_2 : public ClientProxy1_1 { +class ClientProxy1_2 : public ClientProxy1_1 +{ public: - ClientProxy1_2( - const String &name, deskflow::IStream *adoptedStream, - IEventQueue *events); + ClientProxy1_2(const String &name, deskflow::IStream *adoptedStream, IEventQueue *events); ~ClientProxy1_2(); // IClient overrides diff --git a/src/lib/server/ClientProxy1_3.cpp b/src/lib/server/ClientProxy1_3.cpp index 84d833846..e52ab6d81 100644 --- a/src/lib/server/ClientProxy1_3.cpp +++ b/src/lib/server/ClientProxy1_3.cpp @@ -30,28 +30,29 @@ // ClientProxy1_3 // -ClientProxy1_3::ClientProxy1_3( - const String &name, deskflow::IStream *stream, IEventQueue *events) +ClientProxy1_3::ClientProxy1_3(const String &name, deskflow::IStream *stream, IEventQueue *events) : ClientProxy1_2(name, stream, events), m_keepAliveRate(kKeepAliveRate), m_keepAliveTimer(NULL), - m_events(events) { + m_events(events) +{ setHeartbeatRate(kKeepAliveRate, kKeepAliveRate * kKeepAlivesUntilDeath); } -ClientProxy1_3::~ClientProxy1_3() { +ClientProxy1_3::~ClientProxy1_3() +{ // cannot do this in superclass or our override wouldn't get called removeHeartbeatTimer(); } -void ClientProxy1_3::mouseWheel(SInt32 xDelta, SInt32 yDelta) { - LOG( - (CLOG_DEBUG2 "send mouse wheel to \"%s\" %+d,%+d", getName().c_str(), - xDelta, yDelta)); +void ClientProxy1_3::mouseWheel(SInt32 xDelta, SInt32 yDelta) +{ + LOG((CLOG_DEBUG2 "send mouse wheel to \"%s\" %+d,%+d", getName().c_str(), xDelta, yDelta)); ProtocolUtil::writef(getStream(), kMsgDMouseWheel, xDelta, yDelta); } -bool ClientProxy1_3::parseMessage(const UInt8 *code) { +bool ClientProxy1_3::parseMessage(const UInt8 *code) +{ // process message if (memcmp(code, kMsgCKeepAlive, 4) == 0) { // reset alarm @@ -62,36 +63,41 @@ bool ClientProxy1_3::parseMessage(const UInt8 *code) { } } -void ClientProxy1_3::resetHeartbeatRate() { +void ClientProxy1_3::resetHeartbeatRate() +{ setHeartbeatRate(kKeepAliveRate, kKeepAliveRate * kKeepAlivesUntilDeath); } -void ClientProxy1_3::setHeartbeatRate(double rate, double) { +void ClientProxy1_3::setHeartbeatRate(double rate, double) +{ m_keepAliveRate = rate; ClientProxy1_2::setHeartbeatRate(rate, rate * kKeepAlivesUntilDeath); } -void ClientProxy1_3::resetHeartbeatTimer() { +void ClientProxy1_3::resetHeartbeatTimer() +{ // reset the alarm but not the keep alive timer ClientProxy1_2::removeHeartbeatTimer(); ClientProxy1_2::addHeartbeatTimer(); } -void ClientProxy1_3::addHeartbeatTimer() { +void ClientProxy1_3::addHeartbeatTimer() +{ // create and install a timer to periodically send keep alives if (m_keepAliveRate > 0.0) { m_keepAliveTimer = m_events->newTimer(m_keepAliveRate, NULL); m_events->adoptHandler( Event::kTimer, m_keepAliveTimer, - new TMethodEventJob( - this, &ClientProxy1_3::handleKeepAlive, NULL)); + new TMethodEventJob(this, &ClientProxy1_3::handleKeepAlive, NULL) + ); } // superclass does the alarm ClientProxy1_2::addHeartbeatTimer(); } -void ClientProxy1_3::removeHeartbeatTimer() { +void ClientProxy1_3::removeHeartbeatTimer() +{ // remove the timer that sends keep alives periodically if (m_keepAliveTimer != NULL) { m_events->removeHandler(Event::kTimer, m_keepAliveTimer); @@ -103,8 +109,12 @@ void ClientProxy1_3::removeHeartbeatTimer() { ClientProxy1_2::removeHeartbeatTimer(); } -void ClientProxy1_3::handleKeepAlive(const Event &, void *) { keepAlive(); } +void ClientProxy1_3::handleKeepAlive(const Event &, void *) +{ + keepAlive(); +} -void ClientProxy1_3::keepAlive() { +void ClientProxy1_3::keepAlive() +{ ProtocolUtil::writef(getStream(), kMsgCKeepAlive); } diff --git a/src/lib/server/ClientProxy1_3.h b/src/lib/server/ClientProxy1_3.h index c3f7529fa..118d06d4c 100644 --- a/src/lib/server/ClientProxy1_3.h +++ b/src/lib/server/ClientProxy1_3.h @@ -21,11 +21,10 @@ #include "server/ClientProxy1_2.h" //! Proxy for client implementing protocol version 1.3 -class ClientProxy1_3 : public ClientProxy1_2 { +class ClientProxy1_3 : public ClientProxy1_2 +{ public: - ClientProxy1_3( - const String &name, deskflow::IStream *adoptedStream, - IEventQueue *events); + ClientProxy1_3(const String &name, deskflow::IStream *adoptedStream, IEventQueue *events); ClientProxy1_3(ClientProxy1_3 const &) = delete; ClientProxy1_3(ClientProxy1_3 &&) = delete; ~ClientProxy1_3(); diff --git a/src/lib/server/ClientProxy1_4.cpp b/src/lib/server/ClientProxy1_4.cpp index bd189920f..e6fefef1f 100644 --- a/src/lib/server/ClientProxy1_4.cpp +++ b/src/lib/server/ClientProxy1_4.cpp @@ -31,29 +31,33 @@ // ClientProxy1_4 // -ClientProxy1_4::ClientProxy1_4( - const String &name, deskflow::IStream *stream, Server *server, - IEventQueue *events) +ClientProxy1_4::ClientProxy1_4(const String &name, deskflow::IStream *stream, Server *server, IEventQueue *events) : ClientProxy1_3(name, stream, events), - m_server(server) { + m_server(server) +{ assert(m_server != NULL); } -ClientProxy1_4::~ClientProxy1_4() {} +ClientProxy1_4::~ClientProxy1_4() +{ +} -void ClientProxy1_4::keyDown( - KeyID key, KeyModifierMask mask, KeyButton button, const String &lang) { +void ClientProxy1_4::keyDown(KeyID key, KeyModifierMask mask, KeyButton button, const String &lang) +{ ClientProxy1_3::keyDown(key, mask, button, lang); } -void ClientProxy1_4::keyRepeat( - KeyID key, KeyModifierMask mask, SInt32 count, KeyButton button, - const String &lang) { +void ClientProxy1_4::keyRepeat(KeyID key, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang) +{ ClientProxy1_3::keyRepeat(key, mask, count, button, lang); } -void ClientProxy1_4::keyUp(KeyID key, KeyModifierMask mask, KeyButton button) { +void ClientProxy1_4::keyUp(KeyID key, KeyModifierMask mask, KeyButton button) +{ ClientProxy1_3::keyUp(key, mask, button); } -void ClientProxy1_4::keepAlive() { ClientProxy1_3::keepAlive(); } +void ClientProxy1_4::keepAlive() +{ + ClientProxy1_3::keepAlive(); +} diff --git a/src/lib/server/ClientProxy1_4.h b/src/lib/server/ClientProxy1_4.h index 19d0f5660..21e9ced4a 100644 --- a/src/lib/server/ClientProxy1_4.h +++ b/src/lib/server/ClientProxy1_4.h @@ -23,27 +23,26 @@ class Server; //! Proxy for client implementing protocol version 1.4 -class ClientProxy1_4 : public ClientProxy1_3 { +class ClientProxy1_4 : public ClientProxy1_3 +{ public: - ClientProxy1_4( - const String &name, deskflow::IStream *adoptedStream, Server *server, - IEventQueue *events); + ClientProxy1_4(const String &name, deskflow::IStream *adoptedStream, Server *server, IEventQueue *events); ~ClientProxy1_4(); //! @name accessors //@{ //! get server pointer - Server *getServer() { return m_server; } + Server *getServer() + { + return m_server; + } //@} // IClient overrides - virtual void - keyDown(KeyID key, KeyModifierMask mask, KeyButton button, const String &); - virtual void keyRepeat( - KeyID key, KeyModifierMask mask, SInt32 count, KeyButton button, - const String &lang); + virtual void keyDown(KeyID key, KeyModifierMask mask, KeyButton button, const String &); + virtual void keyRepeat(KeyID key, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang); virtual void keyUp(KeyID key, KeyModifierMask mask, KeyButton button); virtual void keepAlive(); diff --git a/src/lib/server/ClientProxy1_5.cpp b/src/lib/server/ClientProxy1_5.cpp index 3a544f4a4..ab470a3d5 100644 --- a/src/lib/server/ClientProxy1_5.cpp +++ b/src/lib/server/ClientProxy1_5.cpp @@ -31,34 +31,36 @@ // ClientProxy1_5 // -ClientProxy1_5::ClientProxy1_5( - const String &name, deskflow::IStream *stream, Server *server, - IEventQueue *events) +ClientProxy1_5::ClientProxy1_5(const String &name, deskflow::IStream *stream, Server *server, IEventQueue *events) : ClientProxy1_4(name, stream, server, events), - m_events(events) { + m_events(events) +{ m_events->adoptHandler( m_events->forFile().keepAlive(), this, - new TMethodEventJob( - this, &ClientProxy1_3::handleKeepAlive, NULL)); + new TMethodEventJob(this, &ClientProxy1_3::handleKeepAlive, NULL) + ); } -ClientProxy1_5::~ClientProxy1_5() { +ClientProxy1_5::~ClientProxy1_5() +{ m_events->removeHandler(m_events->forFile().keepAlive(), this); } -void ClientProxy1_5::sendDragInfo( - UInt32 fileCount, const char *info, size_t size) { +void ClientProxy1_5::sendDragInfo(UInt32 fileCount, const char *info, size_t size) +{ String data(info, size); ProtocolUtil::writef(getStream(), kMsgDDragInfo, fileCount, &data); } -void ClientProxy1_5::fileChunkSending(UInt8 mark, char *data, size_t dataSize) { +void ClientProxy1_5::fileChunkSending(UInt8 mark, char *data, size_t dataSize) +{ FileChunk::send(getStream(), mark, data, dataSize); } -bool ClientProxy1_5::parseMessage(const UInt8 *code) { +bool ClientProxy1_5::parseMessage(const UInt8 *code) +{ if (memcmp(code, kMsgDFileTransfer, 4) == 0) { fileChunkReceived(); } else if (memcmp(code, kMsgDDragInfo, 4) == 0) { @@ -70,15 +72,13 @@ bool ClientProxy1_5::parseMessage(const UInt8 *code) { return true; } -void ClientProxy1_5::fileChunkReceived() { +void ClientProxy1_5::fileChunkReceived() +{ Server *server = getServer(); - int result = FileChunk::assemble( - getStream(), server->getReceivedFileData(), - server->getExpectedFileSize()); + int result = FileChunk::assemble(getStream(), server->getReceivedFileData(), server->getExpectedFileSize()); if (result == kFinish) { - m_events->addEvent( - Event(m_events->forFile().fileRecieveCompleted(), server)); + m_events->addEvent(Event(m_events->forFile().fileRecieveCompleted(), server)); } else if (result == kStart) { if (server->getFakeDragFileList().size() > 0) { String filename = server->getFakeDragFileList().at(0).getFilename(); @@ -87,7 +87,8 @@ void ClientProxy1_5::fileChunkReceived() { } } -void ClientProxy1_5::dragInfoReceived() { +void ClientProxy1_5::dragInfoReceived() +{ // parse UInt32 fileNum = 0; String content; diff --git a/src/lib/server/ClientProxy1_5.h b/src/lib/server/ClientProxy1_5.h index b860edb83..74d07dce5 100644 --- a/src/lib/server/ClientProxy1_5.h +++ b/src/lib/server/ClientProxy1_5.h @@ -25,11 +25,10 @@ class Server; class IEventQueue; //! Proxy for client implementing protocol version 1.5 -class ClientProxy1_5 : public ClientProxy1_4 { +class ClientProxy1_5 : public ClientProxy1_4 +{ public: - ClientProxy1_5( - const String &name, deskflow::IStream *adoptedStream, Server *server, - IEventQueue *events); + ClientProxy1_5(const String &name, deskflow::IStream *adoptedStream, Server *server, IEventQueue *events); ClientProxy1_5(ClientProxy1_5 const &) = delete; ClientProxy1_5(ClientProxy1_5 &&) = delete; ~ClientProxy1_5(); diff --git a/src/lib/server/ClientProxy1_6.cpp b/src/lib/server/ClientProxy1_6.cpp index 915fdb35b..289757657 100644 --- a/src/lib/server/ClientProxy1_6.cpp +++ b/src/lib/server/ClientProxy1_6.cpp @@ -29,20 +29,22 @@ // ClientProxy1_6 // -ClientProxy1_6::ClientProxy1_6( - const String &name, deskflow::IStream *stream, Server *server, - IEventQueue *events) +ClientProxy1_6::ClientProxy1_6(const String &name, deskflow::IStream *stream, Server *server, IEventQueue *events) : ClientProxy1_5(name, stream, server, events), - m_events(events) { + m_events(events) +{ m_events->adoptHandler( m_events->forClipboard().clipboardSending(), this, - new TMethodEventJob( - this, &ClientProxy1_6::handleClipboardSendingEvent)); + new TMethodEventJob(this, &ClientProxy1_6::handleClipboardSendingEvent) + ); } -ClientProxy1_6::~ClientProxy1_6() {} +ClientProxy1_6::~ClientProxy1_6() +{ +} -void ClientProxy1_6::setClipboard(ClipboardID id, const IClipboard *clipboard) { +void ClientProxy1_6::setClipboard(ClipboardID id, const IClipboard *clipboard) +{ // ignore if this clipboard is already clean if (m_clipboard[id].m_dirty) { // this clipboard is now clean @@ -58,11 +60,13 @@ void ClientProxy1_6::setClipboard(ClipboardID id, const IClipboard *clipboard) { } } -void ClientProxy1_6::handleClipboardSendingEvent(const Event &event, void *) { +void ClientProxy1_6::handleClipboardSendingEvent(const Event &event, void *) +{ ClipboardChunk::send(getStream(), event.getDataObject()); } -bool ClientProxy1_6::recvClipboard() { +bool ClientProxy1_6::recvClipboard() +{ // parse message static String dataCached; ClipboardID id; @@ -75,8 +79,9 @@ bool ClientProxy1_6::recvClipboard() { LOG((CLOG_DEBUG "receiving clipboard %d size=%d", id, size)); } else if (r == kFinish) { LOG( - (CLOG_DEBUG "received client \"%s\" clipboard %d seqnum=%d, size=%d", - getName().c_str(), id, seq, dataCached.size())); + (CLOG_DEBUG "received client \"%s\" clipboard %d seqnum=%d, size=%d", getName().c_str(), id, seq, + dataCached.size()) + ); // save clipboard m_clipboard[id].m_clipboard.unmarshall(dataCached, 0); m_clipboard[id].m_sequenceNumber = seq; @@ -85,8 +90,7 @@ bool ClientProxy1_6::recvClipboard() { ClipboardInfo *info = new ClipboardInfo; info->m_id = id; info->m_sequenceNumber = seq; - m_events->addEvent(Event( - m_events->forClipboard().clipboardChanged(), getEventTarget(), info)); + m_events->addEvent(Event(m_events->forClipboard().clipboardChanged(), getEventTarget(), info)); } return true; diff --git a/src/lib/server/ClientProxy1_6.h b/src/lib/server/ClientProxy1_6.h index 7af9a5a4a..b619ffacf 100644 --- a/src/lib/server/ClientProxy1_6.h +++ b/src/lib/server/ClientProxy1_6.h @@ -23,11 +23,10 @@ class Server; class IEventQueue; //! Proxy for client implementing protocol version 1.6 -class ClientProxy1_6 : public ClientProxy1_5 { +class ClientProxy1_6 : public ClientProxy1_5 +{ public: - ClientProxy1_6( - const String &name, deskflow::IStream *adoptedStream, Server *server, - IEventQueue *events); + ClientProxy1_6(const String &name, deskflow::IStream *adoptedStream, Server *server, IEventQueue *events); ~ClientProxy1_6(); virtual void setClipboard(ClipboardID id, const IClipboard *clipboard); diff --git a/src/lib/server/ClientProxy1_7.cpp b/src/lib/server/ClientProxy1_7.cpp index 985e120b9..5f0f10b6c 100644 --- a/src/lib/server/ClientProxy1_7.cpp +++ b/src/lib/server/ClientProxy1_7.cpp @@ -26,15 +26,14 @@ // ClientProxy1_7 // -ClientProxy1_7::ClientProxy1_7( - const String &name, deskflow::IStream *stream, Server *server, - IEventQueue *events) +ClientProxy1_7::ClientProxy1_7(const String &name, deskflow::IStream *stream, Server *server, IEventQueue *events) : ClientProxy1_6(name, stream, server, events), - m_events(events) {} + m_events(events) +{ +} -void ClientProxy1_7::secureInputNotification(const String &app) const { - LOG( - (CLOG_DEBUG2 "send secure input notification to \"%s\" %s", - getName().c_str(), app.c_str())); +void ClientProxy1_7::secureInputNotification(const String &app) const +{ + LOG((CLOG_DEBUG2 "send secure input notification to \"%s\" %s", getName().c_str(), app.c_str())); ProtocolUtil::writef(getStream(), kMsgDSecureInputNotification, &app); } diff --git a/src/lib/server/ClientProxy1_7.h b/src/lib/server/ClientProxy1_7.h index 5db41185c..a0a5ea6b8 100644 --- a/src/lib/server/ClientProxy1_7.h +++ b/src/lib/server/ClientProxy1_7.h @@ -20,11 +20,10 @@ #include "server/ClientProxy1_6.h" //! Proxy for client implementing protocol version 1.7 -class ClientProxy1_7 : public ClientProxy1_6 { +class ClientProxy1_7 : public ClientProxy1_6 +{ public: - ClientProxy1_7( - const String &name, deskflow::IStream *adoptedStream, Server *server, - IEventQueue *events); + ClientProxy1_7(const String &name, deskflow::IStream *adoptedStream, Server *server, IEventQueue *events); ~ClientProxy1_7() override = default; void secureInputNotification(const String &app) const override; diff --git a/src/lib/server/ClientProxy1_8.cpp b/src/lib/server/ClientProxy1_8.cpp index e7f15515e..8a563a89e 100644 --- a/src/lib/server/ClientProxy1_8.cpp +++ b/src/lib/server/ClientProxy1_8.cpp @@ -21,32 +21,30 @@ #include "ClientProxy1_8.h" ClientProxy1_8::ClientProxy1_8( - const String &name, deskflow::IStream *adoptedStream, Server *server, - IEventQueue *events) - : ClientProxy1_7(name, adoptedStream, server, events) { + const String &name, deskflow::IStream *adoptedStream, Server *server, IEventQueue *events +) + : ClientProxy1_7(name, adoptedStream, server, events) +{ synchronizeLanguages(); } -void ClientProxy1_8::synchronizeLanguages() const { +void ClientProxy1_8::synchronizeLanguages() const +{ deskflow::languages::LanguageManager languageManager; auto localLanguages = languageManager.getSerializedLocalLanguages(); if (!localLanguages.empty()) { - LOG( - (CLOG_DEBUG1 "send server languages to the client: %s", - localLanguages.c_str())); - ProtocolUtil::writef( - getStream(), kMsgDLanguageSynchronisation, &localLanguages); + LOG((CLOG_DEBUG1 "send server languages to the client: %s", localLanguages.c_str())); + ProtocolUtil::writef(getStream(), kMsgDLanguageSynchronisation, &localLanguages); } else { LOG((CLOG_ERR "failed to read server languages")); } } -void ClientProxy1_8::keyDown( - KeyID key, KeyModifierMask mask, KeyButton button, const String &language) { +void ClientProxy1_8::keyDown(KeyID key, KeyModifierMask mask, KeyButton button, const String &language) +{ LOG( - (CLOG_DEBUG1 - "send key down to \"%s\" id=%d, mask=0x%04x, button=0x%04x, language=%s", - getName().c_str(), key, mask, button, language.c_str())); - ProtocolUtil::writef( - getStream(), kMsgDKeyDownLang, key, mask, button, &language); + (CLOG_DEBUG1 "send key down to \"%s\" id=%d, mask=0x%04x, button=0x%04x, language=%s", getName().c_str(), key, + mask, button, language.c_str()) + ); + ProtocolUtil::writef(getStream(), kMsgDKeyDownLang, key, mask, button, &language); } diff --git a/src/lib/server/ClientProxy1_8.h b/src/lib/server/ClientProxy1_8.h index b2574ef0f..6d0807dd2 100644 --- a/src/lib/server/ClientProxy1_8.h +++ b/src/lib/server/ClientProxy1_8.h @@ -18,11 +18,10 @@ #include "server/ClientProxy1_7.h" -class ClientProxy1_8 : public ClientProxy1_7 { +class ClientProxy1_8 : public ClientProxy1_7 +{ public: - ClientProxy1_8( - const String &name, deskflow::IStream *adoptedStream, Server *server, - IEventQueue *events); + ClientProxy1_8(const String &name, deskflow::IStream *adoptedStream, Server *server, IEventQueue *events); ~ClientProxy1_8() override = default; void keyDown(KeyID, KeyModifierMask, KeyButton, const String &) override; diff --git a/src/lib/server/ClientProxyUnknown.cpp b/src/lib/server/ClientProxyUnknown.cpp index 2d9c7582c..36b1bf586 100644 --- a/src/lib/server/ClientProxyUnknown.cpp +++ b/src/lib/server/ClientProxyUnknown.cpp @@ -45,36 +45,35 @@ // ClientProxyUnknown // -ClientProxyUnknown::ClientProxyUnknown( - deskflow::IStream *stream, double timeout, Server *server, - IEventQueue *events) +ClientProxyUnknown::ClientProxyUnknown(deskflow::IStream *stream, double timeout, Server *server, IEventQueue *events) : m_stream(stream), m_proxy(NULL), m_ready(false), m_server(server), - m_events(events) { + m_events(events) +{ assert(m_server != NULL); m_events->adoptHandler( - Event::kTimer, this, - new TMethodEventJob( - this, &ClientProxyUnknown::handleTimeout, NULL)); + Event::kTimer, this, new TMethodEventJob(this, &ClientProxyUnknown::handleTimeout, NULL) + ); m_timer = m_events->newOneShotTimer(timeout, this); addStreamHandlers(); LOG((CLOG_DEBUG1 "saying hello")); - ProtocolUtil::writef( - m_stream, kMsgHello, kProtocolMajorVersion, kProtocolMinorVersion); + ProtocolUtil::writef(m_stream, kMsgHello, kProtocolMajorVersion, kProtocolMinorVersion); } -ClientProxyUnknown::~ClientProxyUnknown() { +ClientProxyUnknown::~ClientProxyUnknown() +{ removeHandlers(); removeTimer(); delete m_stream; delete m_proxy; } -ClientProxy *ClientProxyUnknown::orphanClientProxy() { +ClientProxy *ClientProxyUnknown::orphanClientProxy() +{ if (m_ready) { removeHandlers(); ClientProxy *proxy = m_proxy; @@ -85,13 +84,15 @@ ClientProxy *ClientProxyUnknown::orphanClientProxy() { } } -void ClientProxyUnknown::sendSuccess() { +void ClientProxyUnknown::sendSuccess() +{ m_ready = true; removeTimer(); m_events->addEvent(Event(m_events->forClientProxyUnknown().success(), this)); } -void ClientProxyUnknown::sendFailure() { +void ClientProxyUnknown::sendFailure() +{ delete m_proxy; m_proxy = NULL; m_ready = false; @@ -100,50 +101,49 @@ void ClientProxyUnknown::sendFailure() { m_events->addEvent(Event(m_events->forClientProxyUnknown().failure(), this)); } -void ClientProxyUnknown::addStreamHandlers() { +void ClientProxyUnknown::addStreamHandlers() +{ assert(m_stream != NULL); m_events->adoptHandler( m_events->forIStream().inputReady(), m_stream->getEventTarget(), - new TMethodEventJob( - this, &ClientProxyUnknown::handleData)); + new TMethodEventJob(this, &ClientProxyUnknown::handleData) + ); m_events->adoptHandler( m_events->forIStream().outputError(), m_stream->getEventTarget(), - new TMethodEventJob( - this, &ClientProxyUnknown::handleWriteError)); + new TMethodEventJob(this, &ClientProxyUnknown::handleWriteError) + ); m_events->adoptHandler( m_events->forIStream().inputShutdown(), m_stream->getEventTarget(), - new TMethodEventJob( - this, &ClientProxyUnknown::handleDisconnect)); + new TMethodEventJob(this, &ClientProxyUnknown::handleDisconnect) + ); m_events->adoptHandler( m_events->forIStream().outputShutdown(), m_stream->getEventTarget(), - new TMethodEventJob( - this, &ClientProxyUnknown::handleWriteError)); + new TMethodEventJob(this, &ClientProxyUnknown::handleWriteError) + ); } -void ClientProxyUnknown::addProxyHandlers() { +void ClientProxyUnknown::addProxyHandlers() +{ assert(m_proxy != NULL); m_events->adoptHandler( m_events->forClientProxy().ready(), m_proxy, - new TMethodEventJob( - this, &ClientProxyUnknown::handleReady)); + new TMethodEventJob(this, &ClientProxyUnknown::handleReady) + ); m_events->adoptHandler( m_events->forClientProxy().disconnected(), m_proxy, - new TMethodEventJob( - this, &ClientProxyUnknown::handleDisconnect)); + new TMethodEventJob(this, &ClientProxyUnknown::handleDisconnect) + ); } -void ClientProxyUnknown::removeHandlers() { +void ClientProxyUnknown::removeHandlers() +{ if (m_stream != NULL) { - m_events->removeHandler( - m_events->forIStream().inputReady(), m_stream->getEventTarget()); - m_events->removeHandler( - m_events->forIStream().outputError(), m_stream->getEventTarget()); - m_events->removeHandler( - m_events->forIStream().inputShutdown(), m_stream->getEventTarget()); - m_events->removeHandler( - m_events->forIStream().outputShutdown(), m_stream->getEventTarget()); + m_events->removeHandler(m_events->forIStream().inputReady(), m_stream->getEventTarget()); + m_events->removeHandler(m_events->forIStream().outputError(), m_stream->getEventTarget()); + m_events->removeHandler(m_events->forIStream().inputShutdown(), m_stream->getEventTarget()); + m_events->removeHandler(m_events->forIStream().outputShutdown(), m_stream->getEventTarget()); } if (m_proxy != NULL) { m_events->removeHandler(m_events->forClientProxy().ready(), m_proxy); @@ -151,7 +151,8 @@ void ClientProxyUnknown::removeHandlers() { } } -void ClientProxyUnknown::removeTimer() { +void ClientProxyUnknown::removeTimer() +{ if (m_timer != NULL) { m_events->deleteTimer(m_timer); m_events->removeHandler(Event::kTimer, this); @@ -159,7 +160,8 @@ void ClientProxyUnknown::removeTimer() { } } -void ClientProxyUnknown::initProxy(const String &name, int major, int minor) { +void ClientProxyUnknown::initProxy(const String &name, int major, int minor) +{ if (major == 1) { switch (minor) { case 0: @@ -206,7 +208,8 @@ void ClientProxyUnknown::initProxy(const String &name, int major, int minor) { } } -void ClientProxyUnknown::handleData(const Event &, void *) { +void ClientProxyUnknown::handleData(const Event &, void *) +{ LOG((CLOG_DEBUG1 "parsing hello reply")); String name(""); @@ -239,9 +242,7 @@ void ClientProxyUnknown::handleData(const Event &, void *) { initProxy(name, major, minor); // the proxy is created and now proxy now owns the stream - LOG( - (CLOG_DEBUG1 "created proxy for client \"%s\" version %d.%d", - name.c_str(), major, minor)); + LOG((CLOG_DEBUG1 "created proxy for client \"%s\" version %d.%d", name.c_str(), major, minor)); m_stream = NULL; // wait until the proxy signals that it's ready or has disconnected @@ -249,38 +250,38 @@ void ClientProxyUnknown::handleData(const Event &, void *) { return; } catch (XIncompatibleClient &e) { // client is incompatible - LOG( - (CLOG_WARN "client \"%s\" has incompatible version %d.%d)", - name.c_str(), e.getMajor(), e.getMinor())); - ProtocolUtil::writef( - m_stream, kMsgEIncompatible, kProtocolMajorVersion, - kProtocolMinorVersion); + LOG((CLOG_WARN "client \"%s\" has incompatible version %d.%d)", name.c_str(), e.getMajor(), e.getMinor())); + ProtocolUtil::writef(m_stream, kMsgEIncompatible, kProtocolMajorVersion, kProtocolMinorVersion); } catch (XBadClient &) { // client not behaving LOG((CLOG_WARN "protocol error from client \"%s\"", name.c_str())); ProtocolUtil::writef(m_stream, kMsgEBad); } catch (XBase &e) { // misc error - LOG( - (CLOG_WARN "error communicating with client \"%s\": %s", name.c_str(), - e.what())); + LOG((CLOG_WARN "error communicating with client \"%s\": %s", name.c_str(), e.what())); } sendFailure(); } -void ClientProxyUnknown::handleWriteError(const Event &, void *) { +void ClientProxyUnknown::handleWriteError(const Event &, void *) +{ LOG((CLOG_NOTE "error communicating with new client")); sendFailure(); } -void ClientProxyUnknown::handleTimeout(const Event &, void *) { +void ClientProxyUnknown::handleTimeout(const Event &, void *) +{ LOG((CLOG_NOTE "new client is unresponsive")); sendFailure(); } -void ClientProxyUnknown::handleDisconnect(const Event &, void *) { +void ClientProxyUnknown::handleDisconnect(const Event &, void *) +{ LOG((CLOG_NOTE "new client disconnected")); sendFailure(); } -void ClientProxyUnknown::handleReady(const Event &, void *) { sendSuccess(); } +void ClientProxyUnknown::handleReady(const Event &, void *) +{ + sendSuccess(); +} diff --git a/src/lib/server/ClientProxyUnknown.h b/src/lib/server/ClientProxyUnknown.h index bb6811803..07e4649c1 100644 --- a/src/lib/server/ClientProxyUnknown.h +++ b/src/lib/server/ClientProxyUnknown.h @@ -30,11 +30,10 @@ class IStream; class Server; class IEventQueue; -class ClientProxyUnknown { +class ClientProxyUnknown +{ public: - ClientProxyUnknown( - deskflow::IStream *stream, double timeout, Server *server, - IEventQueue *events); + ClientProxyUnknown(deskflow::IStream *stream, double timeout, Server *server, IEventQueue *events); ClientProxyUnknown(ClientProxyUnknown const &) = delete; ClientProxyUnknown(ClientProxyUnknown &&) = delete; ~ClientProxyUnknown(); @@ -54,7 +53,10 @@ public: ClientProxy *orphanClientProxy(); //! Get the stream - deskflow::IStream *getStream() { return m_stream; } + deskflow::IStream *getStream() + { + return m_stream; + } //@} diff --git a/src/lib/server/Config.cpp b/src/lib/server/Config.cpp index d9637fa30..aeeef31b4 100644 --- a/src/lib/server/Config.cpp +++ b/src/lib/server/Config.cpp @@ -36,18 +36,18 @@ namespace deskflow::server { // Config // -Config::Config(IEventQueue *events) - : m_inputFilter(events), - m_hasLockToScreenAction(false), - m_events(events) { +Config::Config(IEventQueue *events) : m_inputFilter(events), m_hasLockToScreenAction(false), m_events(events) +{ // do nothing } -Config::~Config() { +Config::~Config() +{ // do nothing } -bool Config::addScreen(const String &name) { +bool Config::addScreen(const String &name) +{ // alias name must not exist if (m_nameToCanonicalName.find(name) != m_nameToCanonicalName.end()) { return false; @@ -62,7 +62,8 @@ bool Config::addScreen(const String &name) { return true; } -bool Config::renameScreen(const String &oldName, const String &newName) { +bool Config::renameScreen(const String &oldName, const String &newName) +{ // get canonical name and find cell String oldCanonical = getCanonicalName(oldName); CellMap::iterator index = m_map.find(oldCanonical); @@ -72,8 +73,7 @@ bool Config::renameScreen(const String &oldName, const String &newName) { // accept if names are equal but replace with new name to maintain // case. otherwise, the new name must not exist. - if (!CaselessCmp::equal(oldName, newName) && - m_nameToCanonicalName.find(newName) != m_nameToCanonicalName.end()) { + if (!CaselessCmp::equal(oldName, newName) && m_nameToCanonicalName.find(newName) != m_nameToCanonicalName.end()) { return false; } @@ -94,8 +94,7 @@ bool Config::renameScreen(const String &oldName, const String &newName) { // update alias targets if (CaselessCmp::equal(oldName, oldCanonical)) { - for (NameMap::iterator iter = m_nameToCanonicalName.begin(); - iter != m_nameToCanonicalName.end(); ++iter) { + for (NameMap::iterator iter = m_nameToCanonicalName.begin(); iter != m_nameToCanonicalName.end(); ++iter) { if (CaselessCmp::equal(iter->second, oldCanonical)) { iter->second = newName; } @@ -105,7 +104,8 @@ bool Config::renameScreen(const String &oldName, const String &newName) { return true; } -void Config::removeScreen(const String &name) { +void Config::removeScreen(const String &name) +{ // get canonical name and find cell String canonical = getCanonicalName(name); CellMap::iterator index = m_map.find(canonical); @@ -123,8 +123,7 @@ void Config::removeScreen(const String &name) { } // remove aliases (and canonical name) - for (NameMap::iterator iter = m_nameToCanonicalName.begin(); - iter != m_nameToCanonicalName.end();) { + for (NameMap::iterator iter = m_nameToCanonicalName.begin(); iter != m_nameToCanonicalName.end();) { if (iter->second == canonical) { m_nameToCanonicalName.erase(iter++); } else { @@ -133,12 +132,14 @@ void Config::removeScreen(const String &name) { } } -void Config::removeAllScreens() { +void Config::removeAllScreens() +{ m_map.clear(); m_nameToCanonicalName.clear(); } -bool Config::addAlias(const String &canonical, const String &alias) { +bool Config::addAlias(const String &canonical, const String &alias) +{ // alias name must not exist if (m_nameToCanonicalName.find(alias) != m_nameToCanonicalName.end()) { return false; @@ -155,7 +156,8 @@ bool Config::addAlias(const String &canonical, const String &alias) { return true; } -bool Config::removeAlias(const String &alias) { +bool Config::removeAlias(const String &alias) +{ // must not be a canonical name if (m_map.find(alias) != m_map.end()) { return false; @@ -173,15 +175,15 @@ bool Config::removeAlias(const String &alias) { return true; } -bool Config::removeAliases(const String &canonical) { +bool Config::removeAliases(const String &canonical) +{ // must be a canonical name if (m_map.find(canonical) == m_map.end()) { return false; } // find and removing matching aliases - for (NameMap::iterator index = m_nameToCanonicalName.begin(); - index != m_nameToCanonicalName.end();) { + for (NameMap::iterator index = m_nameToCanonicalName.begin(); index != m_nameToCanonicalName.end();) { if (index->second == canonical && index->first != canonical) { m_nameToCanonicalName.erase(index++); } else { @@ -192,7 +194,8 @@ bool Config::removeAliases(const String &canonical) { return true; } -void Config::removeAllAliases() { +void Config::removeAllAliases() +{ // remove all names m_nameToCanonicalName.clear(); @@ -203,8 +206,10 @@ void Config::removeAllAliases() { } bool Config::connect( - const String &srcName, EDirection srcSide, float srcStart, float srcEnd, - const String &dstName, float dstStart, float dstEnd) { + const String &srcName, EDirection srcSide, float srcStart, float srcEnd, const String &dstName, float dstStart, + float dstEnd +) +{ assert(srcSide >= kFirstDirection && srcSide <= kLastDirection); // find source cell @@ -219,7 +224,8 @@ bool Config::connect( return index->second.add(srcEdge, dstEdge); } -bool Config::disconnect(const String &srcName, EDirection srcSide) { +bool Config::disconnect(const String &srcName, EDirection srcSide) +{ assert(srcSide >= kFirstDirection && srcSide <= kLastDirection); // find source cell @@ -234,8 +240,8 @@ bool Config::disconnect(const String &srcName, EDirection srcSide) { return true; } -bool Config::disconnect( - const String &srcName, EDirection srcSide, float position) { +bool Config::disconnect(const String &srcName, EDirection srcSide, float position) +{ assert(srcSide >= kFirstDirection && srcSide <= kLastDirection); // find source cell @@ -250,11 +256,13 @@ bool Config::disconnect( return true; } -void Config::setDeskflowAddress(const NetworkAddress &addr) { +void Config::setDeskflowAddress(const NetworkAddress &addr) +{ m_deskflowAddress = addr; } -bool Config::addOption(const String &name, OptionID option, OptionValue value) { +bool Config::addOption(const String &name, OptionID option, OptionValue value) +{ // find options ScreenOptions *options = NULL; if (name.empty()) { @@ -274,7 +282,8 @@ bool Config::addOption(const String &name, OptionID option, OptionValue value) { return true; } -bool Config::removeOption(const String &name, OptionID option) { +bool Config::removeOption(const String &name, OptionID option) +{ // find options ScreenOptions *options = NULL; if (name.empty()) { @@ -294,7 +303,8 @@ bool Config::removeOption(const String &name, OptionID option) { return true; } -bool Config::removeOptions(const String &name) { +bool Config::removeOptions(const String &name) +{ // find options ScreenOptions *options = NULL; if (name.empty()) { @@ -314,7 +324,8 @@ bool Config::removeOptions(const String &name) { return true; } -bool Config::isValidScreenName(const String &name) const { +bool Config::isValidScreenName(const String &name) const +{ // name is valid if matches validname // name ::= [_A-Za-z0-9] | [_A-Za-z0-9][-_A-Za-z0-9]*[_A-Za-z0-9] // domain ::= . name @@ -347,8 +358,7 @@ bool Config::isValidScreenName(const String &name) const { } // check first and last characters - if (!(isalnum(name[b]) || name[b] == '_') || - !(isalnum(name[e - 1]) || name[e - 1] == '_')) { + if (!(isalnum(name[b]) || name[b] == '_') || !(isalnum(name[e - 1]) || name[e - 1] == '_')) { return false; } @@ -370,31 +380,38 @@ bool Config::isValidScreenName(const String &name) const { return true; } -Config::const_iterator Config::begin() const { +Config::const_iterator Config::begin() const +{ return const_iterator(m_map.begin()); } -Config::const_iterator Config::end() const { +Config::const_iterator Config::end() const +{ return const_iterator(m_map.end()); } -Config::all_const_iterator Config::beginAll() const { +Config::all_const_iterator Config::beginAll() const +{ return m_nameToCanonicalName.begin(); } -Config::all_const_iterator Config::endAll() const { +Config::all_const_iterator Config::endAll() const +{ return m_nameToCanonicalName.end(); } -bool Config::isScreen(const String &name) const { +bool Config::isScreen(const String &name) const +{ return (m_nameToCanonicalName.count(name) > 0); } -bool Config::isCanonicalName(const String &name) const { +bool Config::isCanonicalName(const String &name) const +{ return (!name.empty() && CaselessCmp::equal(getCanonicalName(name), name)); } -String Config::getCanonicalName(const String &name) const { +String Config::getCanonicalName(const String &name) const +{ NameMap::const_iterator index = m_nameToCanonicalName.find(name); if (index == m_nameToCanonicalName.end()) { return String(); @@ -403,9 +420,8 @@ String Config::getCanonicalName(const String &name) const { } } -String Config::getNeighbor( - const String &srcName, EDirection srcSide, float position, - float *positionOut) const { +String Config::getNeighbor(const String &srcName, EDirection srcSide, float position, float *positionOut) const +{ assert(srcSide >= kFirstDirection && srcSide <= kLastDirection); // find source cell @@ -430,12 +446,13 @@ String Config::getNeighbor( } } -bool Config::hasNeighbor(const String &srcName, EDirection srcSide) const { +bool Config::hasNeighbor(const String &srcName, EDirection srcSide) const +{ return hasNeighbor(srcName, srcSide, 0.0f, 1.0f); } -bool Config::hasNeighbor( - const String &srcName, EDirection srcSide, float start, float end) const { +bool Config::hasNeighbor(const String &srcName, EDirection srcSide, float start, float end) const +{ assert(srcSide >= kFirstDirection && srcSide <= kLastDirection); // find source cell @@ -447,23 +464,27 @@ bool Config::hasNeighbor( return index->second.overlaps(CellEdge(srcSide, Interval(start, end))); } -Config::link_const_iterator Config::beginNeighbor(const String &srcName) const { +Config::link_const_iterator Config::beginNeighbor(const String &srcName) const +{ CellMap::const_iterator index = m_map.find(getCanonicalName(srcName)); assert(index != m_map.end()); return index->second.begin(); } -Config::link_const_iterator Config::endNeighbor(const String &srcName) const { +Config::link_const_iterator Config::endNeighbor(const String &srcName) const +{ CellMap::const_iterator index = m_map.find(getCanonicalName(srcName)); assert(index != m_map.end()); return index->second.end(); } -const NetworkAddress &Config::getDeskflowAddress() const { +const NetworkAddress &Config::getDeskflowAddress() const +{ return m_deskflowAddress; } -const Config::ScreenOptions *Config::getOptions(const String &name) const { +const Config::ScreenOptions *Config::getOptions(const String &name) const +{ // find options const ScreenOptions *options = NULL; if (name.empty()) { @@ -479,9 +500,13 @@ const Config::ScreenOptions *Config::getOptions(const String &name) const { return options; } -bool Config::hasLockToScreenAction() const { return m_hasLockToScreenAction; } +bool Config::hasLockToScreenAction() const +{ + return m_hasLockToScreenAction; +} -bool Config::operator==(const Config &x) const { +bool Config::operator==(const Config &x) const +{ if (m_deskflowAddress != x.m_deskflowAddress) { return false; } @@ -516,8 +541,7 @@ bool Config::operator==(const Config &x) const { if (index2 == x.m_nameToCanonicalName.cend()) { return false; // second source ended } - if (!CaselessCmp::equal(index1.first, index2->first) || - !CaselessCmp::equal(index1.second, index2->second)) { + if (!CaselessCmp::equal(index1.first, index2->first) || !CaselessCmp::equal(index1.second, index2->second)) { return false; } ++index2; @@ -531,9 +555,13 @@ bool Config::operator==(const Config &x) const { return true; } -bool Config::operator!=(const Config &x) const { return !operator==(x); } +bool Config::operator!=(const Config &x) const +{ + return !operator==(x); +} -void Config::read(ConfigReadContext &context) { +void Config::read(ConfigReadContext &context) +{ Config tmp(m_events); while (context.getStream()) { tmp.readSection(context); @@ -541,7 +569,8 @@ void Config::read(ConfigReadContext &context) { *this = tmp; } -const char *Config::dirName(EDirection dir) { +const char *Config::dirName(EDirection dir) +{ static const char *s_name[] = {"left", "right", "up", "down"}; assert(dir >= kFirstDirection && dir <= kLastDirection); @@ -549,22 +578,31 @@ const char *Config::dirName(EDirection dir) { return s_name[dir - kFirstDirection]; } -InputFilter *Config::getInputFilter() { return &m_inputFilter; } +InputFilter *Config::getInputFilter() +{ + return &m_inputFilter; +} -String Config::formatInterval(const Interval &x) { +String Config::formatInterval(const Interval &x) +{ if (x.first == 0.0f && x.second == 1.0f) { return ""; } - return deskflow::string::sprintf( - "(%d,%d)", (int)(x.first * 100.0f + 0.5f), - (int)(x.second * 100.0f + 0.5f)); + return deskflow::string::sprintf("(%d,%d)", (int)(x.first * 100.0f + 0.5f), (int)(x.second * 100.0f + 0.5f)); } -String Config::getClientAddress() const { return m_ClientAddress; } +String Config::getClientAddress() const +{ + return m_ClientAddress; +} -bool Config::isClientMode() const { return (!m_ClientAddress.empty()); } +bool Config::isClientMode() const +{ + return (!m_ClientAddress.empty()); +} -void Config::readSection(ConfigReadContext &s) { +void Config::readSection(ConfigReadContext &s) +{ static const char s_section[] = "section:"; static const char s_options[] = "options"; static const char s_screens[] = "screens"; @@ -607,7 +645,8 @@ void Config::readSection(ConfigReadContext &s) { } } -void Config::readSectionOptions(ConfigReadContext &s) { +void Config::readSectionOptions(ConfigReadContext &s) +{ String line; while (s.readLine(line)) { // check for end of section @@ -712,7 +751,8 @@ void Config::readSectionOptions(ConfigReadContext &s) { throw XConfigRead(s, "unexpected end of options section"); } -void Config::readSectionScreens(ConfigReadContext &s) { +void Config::readSectionScreens(ConfigReadContext &s) +{ String line; String screen; while (s.readLine(line)) { @@ -765,21 +805,17 @@ void Config::readSectionScreens(ConfigReadContext &s) { } else if (name == "halfDuplexScrollLock") { addOption(screen, kOptionHalfDuplexScrollLock, s.parseBoolean(value)); } else if (name == "shift") { - addOption( - screen, kOptionModifierMapForShift, s.parseModifierKey(value)); + addOption(screen, kOptionModifierMapForShift, s.parseModifierKey(value)); } else if (name == "ctrl") { - addOption( - screen, kOptionModifierMapForControl, s.parseModifierKey(value)); + addOption(screen, kOptionModifierMapForControl, s.parseModifierKey(value)); } else if (name == "alt") { addOption(screen, kOptionModifierMapForAlt, s.parseModifierKey(value)); } else if (name == "altgr") { - addOption( - screen, kOptionModifierMapForAltGr, s.parseModifierKey(value)); + addOption(screen, kOptionModifierMapForAltGr, s.parseModifierKey(value)); } else if (name == "meta") { addOption(screen, kOptionModifierMapForMeta, s.parseModifierKey(value)); } else if (name == "super") { - addOption( - screen, kOptionModifierMapForSuper, s.parseModifierKey(value)); + addOption(screen, kOptionModifierMapForSuper, s.parseModifierKey(value)); } else if (name == "xtestIsXineramaUnaware") { addOption(screen, kOptionXTestXineramaUnaware, s.parseBoolean(value)); } else if (name == "switchCorners") { @@ -797,7 +833,8 @@ void Config::readSectionScreens(ConfigReadContext &s) { throw XConfigRead(s, "unexpected end of screens section"); } -void Config::readSectionLinks(ConfigReadContext &s) { +void Config::readSectionLinks(ConfigReadContext &s) +{ String line; String screen; while (s.readLine(line)) { @@ -852,8 +889,8 @@ void Config::readSectionLinks(ConfigReadContext &s) { throw XConfigRead(s, "unknown screen name \"%{1}\"", dstScreen); } if (!connect( - screen, dir, srcInterval.first, srcInterval.second, dstScreen, - dstInterval.first, dstInterval.second)) { + screen, dir, srcInterval.first, srcInterval.second, dstScreen, dstInterval.first, dstInterval.second + )) { throw XConfigRead(s, "overlapping range"); } } @@ -861,7 +898,8 @@ void Config::readSectionLinks(ConfigReadContext &s) { throw XConfigRead(s, "unexpected end of links section"); } -void Config::readSectionAliases(ConfigReadContext &s) { +void Config::readSectionAliases(ConfigReadContext &s) +{ String line; String screen; while (s.readLine(line)) { @@ -899,8 +937,9 @@ void Config::readSectionAliases(ConfigReadContext &s) { throw XConfigRead(s, "unexpected end of aliases section"); } -InputFilter::Condition *Config::parseCondition( - ConfigReadContext &s, const String &name, const std::vector &args) { +InputFilter::Condition * +Config::parseCondition(ConfigReadContext &s, const String &name, const std::vector &args) +{ if (name == "keystroke") { if (args.size() != 1) { throw XConfigRead(s, "syntax for condition: keystroke(modifiers+key)"); @@ -913,8 +952,7 @@ InputFilter::Condition *Config::parseCondition( if (name == "mousebutton") { if (args.size() != 1) { - throw XConfigRead( - s, "syntax for condition: mousebutton(modifiers+button)"); + throw XConfigRead(s, "syntax for condition: mousebutton(modifiers+button)"); } IPlatformScreen::ButtonInfo *mouseInfo = s.parseMouse(args[0]); @@ -941,14 +979,14 @@ InputFilter::Condition *Config::parseCondition( } void Config::parseAction( - ConfigReadContext &s, const String &name, const std::vector &args, - InputFilter::Rule &rule, bool activate) { + ConfigReadContext &s, const String &name, const std::vector &args, InputFilter::Rule &rule, bool activate +) +{ InputFilter::Action *action; if (name == "keystroke" || name == "keyDown" || name == "keyUp") { if (args.size() < 1 || args.size() > 2) { - throw XConfigRead( - s, "syntax for action: keystroke(modifiers+key[,screens])"); + throw XConfigRead(s, "syntax for action: keystroke(modifiers+key[,screens])"); } IPlatformScreen::KeyInfo *keyInfo; @@ -981,8 +1019,7 @@ void Config::parseAction( IPlatformScreen::ButtonInfo *mouseInfo = s.parseMouse(args[0]); if (name == "mousebutton") { - IPlatformScreen::ButtonInfo *mouseInfo2 = - IPlatformScreen::ButtonInfo::alloc(*mouseInfo); + IPlatformScreen::ButtonInfo *mouseInfo2 = IPlatformScreen::ButtonInfo::alloc(*mouseInfo); action = new InputFilter::MouseButtonAction(m_events, mouseInfo2, true); rule.adoptAction(action, true); action = new InputFilter::MouseButtonAction(m_events, mouseInfo, false); @@ -1024,8 +1061,7 @@ void Config::parseAction( else if (name == "switchInDirection") { if (args.size() != 1) { - throw XConfigRead( - s, "syntax for action: switchInDirection()"); + throw XConfigRead(s, "syntax for action: switchInDirection()"); } EDirection direction; @@ -1038,8 +1074,7 @@ void Config::parseAction( } else if (args[0] == "down") { direction = kBottom; } else { - throw XConfigRead( - s, "unknown direction \"%{1}\" in switchToScreen", args[0]); + throw XConfigRead(s, "unknown direction \"%{1}\" in switchToScreen", args[0]); } action = new InputFilter::SwitchInDirectionAction(m_events, direction); @@ -1047,12 +1082,10 @@ void Config::parseAction( else if (name == "lockCursorToScreen") { if (args.size() > 1) { - throw XConfigRead( - s, "syntax for action: lockCursorToScreen([{off|on|toggle}])"); + throw XConfigRead(s, "syntax for action: lockCursorToScreen([{off|on|toggle}])"); } - InputFilter::LockCursorToScreenAction::Mode mode = - InputFilter::LockCursorToScreenAction::kToggle; + InputFilter::LockCursorToScreenAction::Mode mode = InputFilter::LockCursorToScreenAction::kToggle; if (args.size() == 1) { if (args[0] == "off") { mode = InputFilter::LockCursorToScreenAction::kOff; @@ -1061,8 +1094,7 @@ void Config::parseAction( } else if (args[0] == "toggle") { mode = InputFilter::LockCursorToScreenAction::kToggle; } else { - throw XConfigRead( - s, "syntax for action: lockCursorToScreen([{off|on|toggle}])"); + throw XConfigRead(s, "syntax for action: lockCursorToScreen([{off|on|toggle}])"); } } @@ -1093,13 +1125,10 @@ void Config::parseAction( else if (name == "keyboardBroadcast") { if (args.size() > 2) { - throw XConfigRead( - s, - "syntax for action: keyboardBroadcast([{off|on|toggle}[,screens]])"); + throw XConfigRead(s, "syntax for action: keyboardBroadcast([{off|on|toggle}[,screens]])"); } - InputFilter::KeyboardBroadcastAction::Mode mode = - InputFilter::KeyboardBroadcastAction::kToggle; + InputFilter::KeyboardBroadcastAction::Mode mode = InputFilter::KeyboardBroadcastAction::kToggle; if (args.size() >= 1) { if (args[0] == "off") { mode = InputFilter::KeyboardBroadcastAction::kOff; @@ -1110,7 +1139,8 @@ void Config::parseAction( } else { throw XConfigRead( s, "syntax for action: " - "keyboardBroadcast([{off|on|toggle}[,screens]])"); + "keyboardBroadcast([{off|on|toggle}[,screens]])" + ); } } @@ -1129,8 +1159,8 @@ void Config::parseAction( rule.adoptAction(action, activate); } -void Config::parseScreens( - ConfigReadContext &c, const String &s, std::set &screens) const { +void Config::parseScreens(ConfigReadContext &c, const String &s, std::set &screens) const +{ screens.clear(); String::size_type i = 0; @@ -1164,7 +1194,8 @@ void Config::parseScreens( } } -const char *Config::getOptionName(OptionID id) { +const char *Config::getOptionName(OptionID id) +{ if (id == kOptionHalfDuplexCapsLock) { return "halfDuplexCapsLock"; } @@ -1240,20 +1271,17 @@ const char *Config::getOptionName(OptionID id) { return NULL; } -String Config::getOptionValue(OptionID id, OptionValue value) { - if (id == kOptionHalfDuplexCapsLock || id == kOptionHalfDuplexNumLock || - id == kOptionHalfDuplexScrollLock || - id == kOptionScreenSwitchNeedsShift || - id == kOptionScreenSwitchNeedsControl || - id == kOptionScreenSwitchNeedsAlt || id == kOptionXTestXineramaUnaware || - id == kOptionRelativeMouseMoves || id == kOptionWin32KeepForeground || - id == kOptionScreenPreserveFocus || id == kOptionClipboardSharing || +String Config::getOptionValue(OptionID id, OptionValue value) +{ + if (id == kOptionHalfDuplexCapsLock || id == kOptionHalfDuplexNumLock || id == kOptionHalfDuplexScrollLock || + id == kOptionScreenSwitchNeedsShift || id == kOptionScreenSwitchNeedsControl || + id == kOptionScreenSwitchNeedsAlt || id == kOptionXTestXineramaUnaware || id == kOptionRelativeMouseMoves || + id == kOptionWin32KeepForeground || id == kOptionScreenPreserveFocus || id == kOptionClipboardSharing || id == kOptionClipboardSharingSize) { return (value != 0) ? "true" : "false"; } - if (id == kOptionModifierMapForShift || id == kOptionModifierMapForControl || - id == kOptionModifierMapForAlt || id == kOptionModifierMapForAltGr || - id == kOptionModifierMapForMeta || id == kOptionModifierMapForSuper) { + if (id == kOptionModifierMapForShift || id == kOptionModifierMapForControl || id == kOptionModifierMapForAlt || + id == kOptionModifierMapForAltGr || id == kOptionModifierMapForMeta || id == kOptionModifierMapForSuper) { switch (value) { case kKeyModifierIDShift: return "shift"; @@ -1277,8 +1305,8 @@ String Config::getOptionValue(OptionID id, OptionValue value) { return "none"; } } - if (id == kOptionHeartbeat || id == kOptionScreenSwitchCornerSize || - id == kOptionScreenSwitchDelay || id == kOptionScreenSwitchTwoTap) { + if (id == kOptionHeartbeat || id == kOptionScreenSwitchCornerSize || id == kOptionScreenSwitchDelay || + id == kOptionScreenSwitchTwoTap) { return deskflow::string::sprintf("%d", value); } if (id == kOptionScreenSwitchCorners) { @@ -1305,13 +1333,13 @@ String Config::getOptionValue(OptionID id, OptionValue value) { // Config::Name // -Config::Name::Name(Config *config, const String &name) - : m_config(config), - m_name(config->getCanonicalName(name)) { +Config::Name::Name(Config *config, const String &name) : m_config(config), m_name(config->getCanonicalName(name)) +{ // do nothing } -bool Config::Name::operator==(const String &name) const { +bool Config::Name::operator==(const String &name) const +{ String canonical = m_config->getCanonicalName(name); return CaselessCmp::equal(canonical, m_name); } @@ -1320,11 +1348,13 @@ bool Config::Name::operator==(const String &name) const { // Config::CellEdge // -Config::CellEdge::CellEdge(EDirection side, float position) { +Config::CellEdge::CellEdge(EDirection side, float position) +{ init("", side, Interval(position, position)); } -Config::CellEdge::CellEdge(EDirection side, const Interval &interval) { +Config::CellEdge::CellEdge(EDirection side, const Interval &interval) +{ assert(interval.first >= 0.0f); assert(interval.second <= 1.0f); assert(interval.first < interval.second); @@ -1332,8 +1362,8 @@ Config::CellEdge::CellEdge(EDirection side, const Interval &interval) { init("", side, interval); } -Config::CellEdge::CellEdge( - const String &name, EDirection side, const Interval &interval) { +Config::CellEdge::CellEdge(const String &name, EDirection side, const Interval &interval) +{ assert(interval.first >= 0.0f); assert(interval.second <= 1.0f); assert(interval.first < interval.second); @@ -1341,12 +1371,13 @@ Config::CellEdge::CellEdge( init(name, side, interval); } -Config::CellEdge::~CellEdge() { +Config::CellEdge::~CellEdge() +{ // do nothing } -void Config::CellEdge::init( - const String &name, EDirection side, const Interval &interval) { +void Config::CellEdge::init(const String &name, EDirection side, const Interval &interval) +{ assert(side != kNoDirection); m_name = name; @@ -1354,39 +1385,54 @@ void Config::CellEdge::init( m_interval = interval; } -Config::Interval Config::CellEdge::getInterval() const { return m_interval; } +Config::Interval Config::CellEdge::getInterval() const +{ + return m_interval; +} -void Config::CellEdge::setName(const String &newName) { m_name = newName; } +void Config::CellEdge::setName(const String &newName) +{ + m_name = newName; +} -String Config::CellEdge::getName() const { return m_name; } +String Config::CellEdge::getName() const +{ + return m_name; +} -EDirection Config::CellEdge::getSide() const { return m_side; } +EDirection Config::CellEdge::getSide() const +{ + return m_side; +} -bool Config::CellEdge::overlaps(const CellEdge &edge) const { +bool Config::CellEdge::overlaps(const CellEdge &edge) const +{ const Interval &x = m_interval; const Interval &y = edge.m_interval; if (m_side != edge.m_side) { return false; } - return (x.first >= y.first && x.first < y.second) || - (x.second > y.first && x.second <= y.second) || - (y.first >= x.first && y.first < x.second) || - (y.second > x.first && y.second <= x.second); + return (x.first >= y.first && x.first < y.second) || (x.second > y.first && x.second <= y.second) || + (y.first >= x.first && y.first < x.second) || (y.second > x.first && y.second <= x.second); } -bool Config::CellEdge::isInside(float x) const { +bool Config::CellEdge::isInside(float x) const +{ return (x >= m_interval.first && x < m_interval.second); } -float Config::CellEdge::transform(float x) const { +float Config::CellEdge::transform(float x) const +{ return (x - m_interval.first) / (m_interval.second - m_interval.first); } -float Config::CellEdge::inverseTransform(float x) const { +float Config::CellEdge::inverseTransform(float x) const +{ return x * (m_interval.second - m_interval.first) + m_interval.first; } -bool Config::CellEdge::operator<(const CellEdge &o) const { +bool Config::CellEdge::operator<(const CellEdge &o) const +{ if (static_cast(m_side) < static_cast(o.m_side)) { return true; } else if (static_cast(m_side) > static_cast(o.m_side)) { @@ -1396,11 +1442,13 @@ bool Config::CellEdge::operator<(const CellEdge &o) const { return (m_interval.first < o.m_interval.first); } -bool Config::CellEdge::operator==(const CellEdge &x) const { +bool Config::CellEdge::operator==(const CellEdge &x) const +{ return (m_side == x.m_side && m_interval == x.m_interval); } -bool Config::CellEdge::operator!=(const CellEdge &x) const { +bool Config::CellEdge::operator!=(const CellEdge &x) const +{ return !operator==(x); } @@ -1408,7 +1456,8 @@ bool Config::CellEdge::operator!=(const CellEdge &x) const { // Config::Cell // -bool Config::Cell::add(const CellEdge &src, const CellEdge &dst) { +bool Config::Cell::add(const CellEdge &src, const CellEdge &dst) +{ // cannot add an edge that overlaps other existing edges but we // can exactly replace an edge. if (!hasEdge(src) && overlaps(src)) { @@ -1420,7 +1469,8 @@ bool Config::Cell::add(const CellEdge &src, const CellEdge &dst) { return true; } -void Config::Cell::remove(EDirection side) { +void Config::Cell::remove(EDirection side) +{ for (EdgeLinks::iterator j = m_neighbors.begin(); j != m_neighbors.end();) { if (j->first.getSide() == side) { m_neighbors.erase(j++); @@ -1430,16 +1480,17 @@ void Config::Cell::remove(EDirection side) { } } -void Config::Cell::remove(EDirection side, float position) { - for (EdgeLinks::iterator j = m_neighbors.begin(); j != m_neighbors.end(); - ++j) { +void Config::Cell::remove(EDirection side, float position) +{ + for (EdgeLinks::iterator j = m_neighbors.begin(); j != m_neighbors.end(); ++j) { if (j->first.getSide() == side && j->first.isInside(position)) { m_neighbors.erase(j); break; } } } -void Config::Cell::remove(const Name &name) { +void Config::Cell::remove(const Name &name) +{ for (EdgeLinks::iterator j = m_neighbors.begin(); j != m_neighbors.end();) { if (name == j->second.getName()) { m_neighbors.erase(j++); @@ -1449,21 +1500,23 @@ void Config::Cell::remove(const Name &name) { } } -void Config::Cell::rename(const Name &oldName, const String &newName) { - for (EdgeLinks::iterator j = m_neighbors.begin(); j != m_neighbors.end(); - ++j) { +void Config::Cell::rename(const Name &oldName, const String &newName) +{ + for (EdgeLinks::iterator j = m_neighbors.begin(); j != m_neighbors.end(); ++j) { if (oldName == j->second.getName()) { j->second.setName(newName); } } } -bool Config::Cell::hasEdge(const CellEdge &edge) const { +bool Config::Cell::hasEdge(const CellEdge &edge) const +{ EdgeLinks::const_iterator i = m_neighbors.find(edge); return (i != m_neighbors.end() && i->first == edge); } -bool Config::Cell::overlaps(const CellEdge &edge) const { +bool Config::Cell::overlaps(const CellEdge &edge) const +{ EdgeLinks::const_iterator i = m_neighbors.upper_bound(edge); if (i != m_neighbors.end() && i->first.overlaps(edge)) { return true; @@ -1474,9 +1527,8 @@ bool Config::Cell::overlaps(const CellEdge &edge) const { return false; } -bool Config::Cell::getLink( - EDirection side, float position, const CellEdge *&src, - const CellEdge *&dst) const { +bool Config::Cell::getLink(EDirection side, float position, const CellEdge *&src, const CellEdge *&dst) const +{ CellEdge edge(side, position); EdgeLinks::const_iterator i = m_neighbors.upper_bound(edge); if (i == m_neighbors.begin()) { @@ -1491,7 +1543,8 @@ bool Config::Cell::getLink( return false; } -bool Config::Cell::operator==(const Cell &x) const { +bool Config::Cell::operator==(const Cell &x) const +{ // compare options if (m_options != x.m_options) { return false; @@ -1513,8 +1566,7 @@ bool Config::Cell::operator==(const Cell &x) const { // operator== doesn't compare names. only compare destination // names. - if (!CaselessCmp::equal( - index1.second.getName(), index2neighbors->second.getName())) { + if (!CaselessCmp::equal(index1.second.getName(), index2neighbors->second.getName())) { return false; } ++index2neighbors; @@ -1523,13 +1575,18 @@ bool Config::Cell::operator==(const Cell &x) const { return true; } -bool Config::Cell::operator!=(const Cell &x) const { return !operator==(x); } +bool Config::Cell::operator!=(const Cell &x) const +{ + return !operator==(x); +} -Config::Cell::const_iterator Config::Cell::begin() const { +Config::Cell::const_iterator Config::Cell::begin() const +{ return m_neighbors.begin(); } -Config::Cell::const_iterator Config::Cell::end() const { +Config::Cell::const_iterator Config::Cell::end() const +{ return m_neighbors.end(); } @@ -1537,22 +1594,22 @@ Config::Cell::const_iterator Config::Cell::end() const { // Config I/O // -std::istream &operator>>(std::istream &s, Config &config) { +std::istream &operator>>(std::istream &s, Config &config) +{ ConfigReadContext context(s); config.read(context); return s; } -std::ostream &operator<<(std::ostream &s, const Config &config) { +std::ostream &operator<<(std::ostream &s, const Config &config) +{ // screens section s << "section: screens" << std::endl; - for (Config::const_iterator screen = config.begin(); screen != config.end(); - ++screen) { + for (Config::const_iterator screen = config.begin(); screen != config.end(); ++screen) { s << "\t" << screen->c_str() << ":" << std::endl; const Config::ScreenOptions *options = config.getOptions(*screen); if (options != NULL && options->size() > 0) { - for (Config::ScreenOptions::const_iterator option = options->begin(); - option != options->end(); ++option) { + for (Config::ScreenOptions::const_iterator option = options->begin(); option != options->end(); ++option) { const char *name = Config::getOptionName(option->first); String value = Config::getOptionValue(option->first, option->second); if (name != NULL && !value.empty()) { @@ -1566,17 +1623,13 @@ std::ostream &operator<<(std::ostream &s, const Config &config) { // links section String neighbor; s << "section: links" << std::endl; - for (Config::const_iterator screen = config.begin(); screen != config.end(); - ++screen) { + for (Config::const_iterator screen = config.begin(); screen != config.end(); ++screen) { s << "\t" << screen->c_str() << ":" << std::endl; - for (Config::link_const_iterator link = config.beginNeighbor(*screen), - nend = config.endNeighbor(*screen); + for (Config::link_const_iterator link = config.beginNeighbor(*screen), nend = config.endNeighbor(*screen); link != nend; ++link) { - s << "\t\t" << Config::dirName(link->first.getSide()) - << Config::formatInterval(link->first.getInterval()) << " = " - << link->second.getName().c_str() - << Config::formatInterval(link->second.getInterval()) << std::endl; + s << "\t\t" << Config::dirName(link->first.getSide()) << Config::formatInterval(link->first.getInterval()) + << " = " << link->second.getName().c_str() << Config::formatInterval(link->second.getInterval()) << std::endl; } } s << "end" << std::endl; @@ -1586,8 +1639,7 @@ std::ostream &operator<<(std::ostream &s, const Config &config) { // map canonical to alias typedef std::multimap CMNameMap; CMNameMap aliases; - for (Config::NameMap::const_iterator index = - config.m_nameToCanonicalName.begin(); + for (Config::NameMap::const_iterator index = config.m_nameToCanonicalName.begin(); index != config.m_nameToCanonicalName.end(); ++index) { if (index->first != index->second) { aliases.insert(std::make_pair(index->second, index->first)); @@ -1597,8 +1649,7 @@ std::ostream &operator<<(std::ostream &s, const Config &config) { // dump it String screen; s << "section: aliases" << std::endl; - for (CMNameMap::const_iterator index = aliases.begin(); - index != aliases.end(); ++index) { + for (CMNameMap::const_iterator index = aliases.begin(); index != aliases.end(); ++index) { if (index->first != screen) { screen = index->first; s << "\t" << screen.c_str() << ":" << std::endl; @@ -1612,8 +1663,7 @@ std::ostream &operator<<(std::ostream &s, const Config &config) { s << "section: options" << std::endl; const Config::ScreenOptions *options = config.getOptions(""); if (options != NULL && options->size() > 0) { - for (Config::ScreenOptions::const_iterator option = options->begin(); - option != options->end(); ++option) { + for (Config::ScreenOptions::const_iterator option = options->begin(); option != options->end(); ++option) { const char *name = Config::getOptionName(option->first); String value = Config::getOptionValue(option->first, option->second); if (name != NULL && !value.empty()) { @@ -1622,8 +1672,7 @@ std::ostream &operator<<(std::ostream &s, const Config &config) { } } if (config.m_deskflowAddress.isValid()) { - s << "\taddress = " << config.m_deskflowAddress.getHostname().c_str() - << std::endl; + s << "\taddress = " << config.m_deskflowAddress.getHostname().c_str() << std::endl; } s << config.m_inputFilter.format("\t"); s << "end" << std::endl; @@ -1635,17 +1684,18 @@ std::ostream &operator<<(std::ostream &s, const Config &config) { // ConfigReadContext // -ConfigReadContext::ConfigReadContext(std::istream &s, SInt32 firstLine) - : m_stream(s), - m_line(firstLine - 1) { +ConfigReadContext::ConfigReadContext(std::istream &s, SInt32 firstLine) : m_stream(s), m_line(firstLine - 1) +{ // do nothing } -ConfigReadContext::~ConfigReadContext() { +ConfigReadContext::~ConfigReadContext() +{ // do nothing } -bool ConfigReadContext::readLine(String &line) { +bool ConfigReadContext::readLine(String &line) +{ ++m_line; while (std::getline(m_stream, line)) { // strip leading whitespace @@ -1669,9 +1719,7 @@ bool ConfigReadContext::readLine(String &line) { // make sure there are no invalid characters for (i = 0; i < line.length(); ++i) { if (!isgraph(line[i]) && line[i] != ' ' && line[i] != '\t') { - throw XConfigRead( - *this, "invalid character %{1}", - deskflow::string::sprintf("%#2x", line[i])); + throw XConfigRead(*this, "invalid character %{1}", deskflow::string::sprintf("%#2x", line[i])); } } @@ -1684,11 +1732,18 @@ bool ConfigReadContext::readLine(String &line) { return false; } -UInt32 ConfigReadContext::getLineNumber() const { return m_line; } +UInt32 ConfigReadContext::getLineNumber() const +{ + return m_line; +} -bool ConfigReadContext::operator!() const { return !m_stream; } +bool ConfigReadContext::operator!() const +{ + return !m_stream; +} -OptionValue ConfigReadContext::parseBoolean(const String &arg) const { +OptionValue ConfigReadContext::parseBoolean(const String &arg) const +{ if (CaselessCmp::equal(arg, "true")) { return static_cast(true); } @@ -1698,7 +1753,8 @@ OptionValue ConfigReadContext::parseBoolean(const String &arg) const { throw XConfigRead(*this, "invalid boolean argument \"%{1}\"", arg); } -OptionValue ConfigReadContext::parseInt(const String &arg) const { +OptionValue ConfigReadContext::parseInt(const String &arg) const +{ const char *s = arg.c_str(); char *end; long tmp = strtol(s, &end, 10); @@ -1714,7 +1770,8 @@ OptionValue ConfigReadContext::parseInt(const String &arg) const { return value; } -OptionValue ConfigReadContext::parseModifierKey(const String &arg) const { +OptionValue ConfigReadContext::parseModifierKey(const String &arg) const +{ if (CaselessCmp::equal(arg, "shift")) { return static_cast(kKeyModifierIDShift); } @@ -1739,7 +1796,8 @@ OptionValue ConfigReadContext::parseModifierKey(const String &arg) const { throw XConfigRead(*this, "invalid argument \"%{1}\"", arg); } -OptionValue ConfigReadContext::parseCorner(const String &arg) const { +OptionValue ConfigReadContext::parseCorner(const String &arg) const +{ if (CaselessCmp::equal(arg, "left")) { return kTopLeftMask | kBottomLeftMask; } else if (CaselessCmp::equal(arg, "right")) { @@ -1764,7 +1822,8 @@ OptionValue ConfigReadContext::parseCorner(const String &arg) const { throw XConfigRead(*this, "invalid argument \"%{1}\"", arg); } -OptionValue ConfigReadContext::parseCorners(const String &args) const { +OptionValue ConfigReadContext::parseCorners(const String &args) const +{ // find first token String::size_type i = args.find_first_not_of(" \t", 0); if (i == String::npos) { @@ -1785,9 +1844,7 @@ OptionValue ConfigReadContext::parseCorners(const String &args) const { } else if (args[i] == '+') { add = true; } else { - throw XConfigRead( - *this, "invalid corner operator \"%{1}\"", - String(args.c_str() + i, 1)); + throw XConfigRead(*this, "invalid corner operator \"%{1}\"", String(args.c_str() + i, 1)); } // get next corner token @@ -1809,7 +1866,8 @@ OptionValue ConfigReadContext::parseCorners(const String &args) const { return corners; } -Config::Interval ConfigReadContext::parseInterval(const ArgList &args) const { +Config::Interval ConfigReadContext::parseInterval(const ArgList &args) const +{ if (args.size() == 0) { return Config::Interval(0.0f, 1.0f); } @@ -1827,8 +1885,7 @@ Config::Interval ConfigReadContext::parseInterval(const ArgList &args) const { throw XConfigRead(*this, "invalid interval \"%{1}\"", concatArgs(args)); } - if (startValue < 0 || startValue > 100 || endValue < 0 || endValue > 100 || - startValue >= endValue) { + if (startValue < 0 || startValue > 100 || endValue < 0 || endValue > 100 || startValue >= endValue) { throw XConfigRead(*this, "invalid interval \"%{1}\"", concatArgs(args)); } @@ -1838,8 +1895,9 @@ Config::Interval ConfigReadContext::parseInterval(const ArgList &args) const { } void ConfigReadContext::parseNameWithArgs( - const String &type, const String &line, const String &delim, - String::size_type &index, String &name, ArgList &args) const { + const String &type, const String &line, const String &delim, String::size_type &index, String &name, ArgList &args +) const +{ // skip leading whitespace String::size_type i = line.find_first_not_of(" \t", index); if (i == String::npos) { @@ -1940,13 +1998,14 @@ void ConfigReadContext::parseNameWithArgs( return; } -IPlatformScreen::KeyInfo * -ConfigReadContext::parseKeystroke(const String &keystroke) const { +IPlatformScreen::KeyInfo *ConfigReadContext::parseKeystroke(const String &keystroke) const +{ return parseKeystroke(keystroke, std::set()); } -IPlatformScreen::KeyInfo *ConfigReadContext::parseKeystroke( - const String &keystroke, const std::set &screens) const { +IPlatformScreen::KeyInfo * +ConfigReadContext::parseKeystroke(const String &keystroke, const std::set &screens) const +{ String s = keystroke; KeyModifierMask mask; @@ -1966,8 +2025,8 @@ IPlatformScreen::KeyInfo *ConfigReadContext::parseKeystroke( return IPlatformScreen::KeyInfo::alloc(key, mask, 0, 0, screens); } -IPlatformScreen::ButtonInfo * -ConfigReadContext::parseMouse(const String &mouse) const { +IPlatformScreen::ButtonInfo *ConfigReadContext::parseMouse(const String &mouse) const +{ String s = mouse; KeyModifierMask mask; @@ -1987,8 +2046,8 @@ ConfigReadContext::parseMouse(const String &mouse) const { return IPlatformScreen::ButtonInfo::alloc(button, mask); } -KeyModifierMask -ConfigReadContext::parseModifier(const String &modifiers) const { +KeyModifierMask ConfigReadContext::parseModifier(const String &modifiers) const +{ String s = modifiers; KeyModifierMask mask; @@ -2003,7 +2062,8 @@ ConfigReadContext::parseModifier(const String &modifiers) const { return mask; } -String ConfigReadContext::concatArgs(const ArgList &args) { +String ConfigReadContext::concatArgs(const ArgList &args) +{ String s("("); for (size_t i = 0; i < args.size(); ++i) { if (i != 0) { @@ -2020,24 +2080,27 @@ String ConfigReadContext::concatArgs(const ArgList &args) { // XConfigRead::XConfigRead(const ConfigReadContext &context, const String &error) - : m_error(deskflow::string::sprintf( - "line %d: %s", context.getLineNumber(), error.c_str())) { + : m_error(deskflow::string::sprintf("line %d: %s", context.getLineNumber(), error.c_str())) +{ // do nothing } -XConfigRead::XConfigRead( - const ConfigReadContext &context, const char *errorFmt, const String &arg) +XConfigRead::XConfigRead(const ConfigReadContext &context, const char *errorFmt, const String &arg) : m_error( deskflow::string::sprintf("line %d: ", context.getLineNumber()) + - deskflow::string::format(errorFmt, arg.c_str())) { + deskflow::string::format(errorFmt, arg.c_str()) + ) +{ // do nothing } -XConfigRead::~XConfigRead() _NOEXCEPT { +XConfigRead::~XConfigRead() _NOEXCEPT +{ // do nothing } -String XConfigRead::getWhat() const throw() { +String XConfigRead::getWhat() const throw() +{ return format("XConfigRead", "read error: %{1}", m_error.c_str()); } diff --git a/src/lib/server/Config.h b/src/lib/server/Config.h index 76bf6bfa4..25c04fb62 100644 --- a/src/lib/server/Config.h +++ b/src/lib/server/Config.h @@ -38,7 +38,8 @@ class ConfigReadContext; class IEventQueue; namespace std { -template <> struct iterator_traits { +template <> struct iterator_traits +{ typedef String value_type; typedef ptrdiff_t difference_type; typedef bidirectional_iterator_tag iterator_category; @@ -59,12 +60,14 @@ Note that case is preserved in screen names but is ignored when comparing names. Screen names and their aliases share a namespace and must be unique. */ -class Config { +class Config +{ public: typedef std::map ScreenOptions; typedef std::pair Interval; - class CellEdge { + class CellEdge + { public: CellEdge(EDirection side, float position); CellEdge(EDirection side, const Interval &); @@ -101,7 +104,8 @@ public: }; private: - class Name { + class Name + { public: Name(Config *, const String &name); @@ -112,7 +116,8 @@ private: String m_name; }; - class Cell { + class Cell + { private: typedef std::map EdgeLinks; @@ -128,9 +133,7 @@ private: bool hasEdge(const CellEdge &) const; bool overlaps(const CellEdge &) const; - bool getLink( - EDirection side, float position, const CellEdge *&src, - const CellEdge *&dst) const; + bool getLink(EDirection side, float position, const CellEdge *&src, const CellEdge *&dst) const; bool operator==(const Cell &) const; bool operator!=(const Cell &) const; @@ -151,31 +154,57 @@ public: typedef Cell::const_iterator link_const_iterator; typedef CellMap::const_iterator internal_const_iterator; typedef NameMap::const_iterator all_const_iterator; - class const_iterator : std::iterator_traits { + class const_iterator : std::iterator_traits + { public: - explicit const_iterator() : m_i() {} - explicit const_iterator(const internal_const_iterator &i) : m_i(i) {} + explicit const_iterator() : m_i() + { + } + explicit const_iterator(const internal_const_iterator &i) : m_i(i) + { + } const_iterator(const const_iterator &src) = default; ~const_iterator() = default; - const_iterator &operator=(const const_iterator &i) { + const_iterator &operator=(const const_iterator &i) + { m_i = i.m_i; return *this; } - String operator*() { return m_i->first; } - const String *operator->() { return &(m_i->first); } - const_iterator &operator++() { + String operator*() + { + return m_i->first; + } + const String *operator->() + { + return &(m_i->first); + } + const_iterator &operator++() + { ++m_i; return *this; } - const_iterator operator++(int) { return const_iterator(m_i++); } - const_iterator &operator--() { + const_iterator operator++(int) + { + return const_iterator(m_i++); + } + const_iterator &operator--() + { --m_i; return *this; } - const_iterator operator--(int) { return const_iterator(m_i--); } - bool operator==(const const_iterator &i) const { return (m_i == i.m_i); } - bool operator!=(const const_iterator &i) const { return (m_i != i.m_i); } + const_iterator operator--(int) + { + return const_iterator(m_i--); + } + bool operator==(const const_iterator &i) const + { + return (m_i == i.m_i); + } + bool operator!=(const const_iterator &i) const + { + return (m_i != i.m_i); + } private: internal_const_iterator m_i; @@ -185,7 +214,9 @@ public: virtual ~Config(); #ifdef TEST_ENV - Config() : m_inputFilter(NULL) {} + Config() : m_inputFilter(NULL) + { + } #endif //! @name manipulators @@ -265,8 +296,9 @@ public: be inside the range [0,1]. */ bool connect( - const String &srcName, EDirection srcSide, float srcStart, float srcEnd, - const String &dstName, float dstStart, float dstEnd); + const String &srcName, EDirection srcSide, float srcStart, float srcEnd, const String &dstName, float dstStart, + float dstEnd + ); //! Disconnect screens /*! @@ -367,8 +399,7 @@ public: saves the position on the neighbor in \c positionOut if it's not \c NULL. */ - String getNeighbor( - const String &, EDirection, float position, float *positionOut) const; + String getNeighbor(const String &, EDirection, float position, float *positionOut) const; //! Check for neighbor /*! @@ -464,15 +495,12 @@ private: void readSectionLinks(ConfigReadContext &); void readSectionAliases(ConfigReadContext &); - InputFilter::Condition *parseCondition( - ConfigReadContext &, const String &condition, - const std::vector &args); + InputFilter::Condition *parseCondition(ConfigReadContext &, const String &condition, const std::vector &args); void parseAction( - ConfigReadContext &, const String &action, - const std::vector &args, InputFilter::Rule &, bool activate); + ConfigReadContext &, const String &action, const std::vector &args, InputFilter::Rule &, bool activate + ); - void parseScreens( - ConfigReadContext &, const String &, std::set &screens) const; + void parseScreens(ConfigReadContext &, const String &, std::set &screens) const; static const char *getOptionName(OptionID); static String getOptionValue(OptionID, OptionValue); @@ -491,7 +519,8 @@ private: /*! Maintains a context when reading a configuration from a stream. */ -class ConfigReadContext { +class ConfigReadContext +{ public: typedef std::vector ArgList; @@ -510,14 +539,16 @@ public: OptionValue parseCorners(const String &) const; Config::Interval parseInterval(const ArgList &args) const; void parseNameWithArgs( - const String &type, const String &line, const String &delim, - String::size_type &index, String &name, ArgList &args) const; + const String &type, const String &line, const String &delim, String::size_type &index, String &name, ArgList &args + ) const; IPlatformScreen::KeyInfo *parseKeystroke(const String &keystroke) const; - IPlatformScreen::KeyInfo *parseKeystroke( - const String &keystroke, const std::set &screens) const; + IPlatformScreen::KeyInfo *parseKeystroke(const String &keystroke, const std::set &screens) const; IPlatformScreen::ButtonInfo *parseMouse(const String &mouse) const; KeyModifierMask parseModifier(const String &modifiers) const; - std::istream &getStream() const { return m_stream; }; + std::istream &getStream() const + { + return m_stream; + }; private: // not implemented @@ -534,12 +565,11 @@ private: /*! Thrown when a configuration stream cannot be parsed. */ -class XConfigRead : public XBase { +class XConfigRead : public XBase +{ public: XConfigRead(const ConfigReadContext &context, const String &); - XConfigRead( - const ConfigReadContext &context, const char *errorFmt, - const String &arg); + XConfigRead(const ConfigReadContext &context, const char *errorFmt, const String &arg); virtual ~XConfigRead() _NOEXCEPT; protected: diff --git a/src/lib/server/InputFilter.cpp b/src/lib/server/InputFilter.cpp index 15e4be636..0c94b9086 100644 --- a/src/lib/server/InputFilter.cpp +++ b/src/lib/server/InputFilter.cpp @@ -30,61 +30,71 @@ // ----------------------------------------------------------------------------- // Input Filter Condition Classes // ----------------------------------------------------------------------------- -InputFilter::Condition::Condition() { +InputFilter::Condition::Condition() +{ // do nothing } -InputFilter::Condition::~Condition() { +InputFilter::Condition::~Condition() +{ // do nothing } -void InputFilter::Condition::enablePrimary(PrimaryClient *) { +void InputFilter::Condition::enablePrimary(PrimaryClient *) +{ // do nothing } -void InputFilter::Condition::disablePrimary(PrimaryClient *) { +void InputFilter::Condition::disablePrimary(PrimaryClient *) +{ // do nothing } -InputFilter::KeystrokeCondition::KeystrokeCondition( - IEventQueue *events, IPlatformScreen::KeyInfo *info) +InputFilter::KeystrokeCondition::KeystrokeCondition(IEventQueue *events, IPlatformScreen::KeyInfo *info) : m_id(0), m_key(info->m_key), m_mask(info->m_mask), - m_events(events) { + m_events(events) +{ free(info); } -InputFilter::KeystrokeCondition::KeystrokeCondition( - IEventQueue *events, KeyID key, KeyModifierMask mask) +InputFilter::KeystrokeCondition::KeystrokeCondition(IEventQueue *events, KeyID key, KeyModifierMask mask) : m_id(0), m_key(key), m_mask(mask), - m_events(events) { + m_events(events) +{ // do nothing } -InputFilter::KeystrokeCondition::~KeystrokeCondition() { +InputFilter::KeystrokeCondition::~KeystrokeCondition() +{ // do nothing } -KeyID InputFilter::KeystrokeCondition::getKey() const { return m_key; } +KeyID InputFilter::KeystrokeCondition::getKey() const +{ + return m_key; +} -KeyModifierMask InputFilter::KeystrokeCondition::getMask() const { +KeyModifierMask InputFilter::KeystrokeCondition::getMask() const +{ return m_mask; } -InputFilter::Condition *InputFilter::KeystrokeCondition::clone() const { +InputFilter::Condition *InputFilter::KeystrokeCondition::clone() const +{ return new KeystrokeCondition(m_events, m_key, m_mask); } -String InputFilter::KeystrokeCondition::format() const { - return deskflow::string::sprintf( - "keystroke(%s)", deskflow::KeyMap::formatKey(m_key, m_mask).c_str()); +String InputFilter::KeystrokeCondition::format() const +{ + return deskflow::string::sprintf("keystroke(%s)", deskflow::KeyMap::formatKey(m_key, m_mask).c_str()); } -InputFilter::EFilterStatus -InputFilter::KeystrokeCondition::match(const Event &event) { +InputFilter::EFilterStatus InputFilter::KeystrokeCondition::match(const Event &event) +{ EFilterStatus status; // check for hotkey events @@ -98,8 +108,7 @@ InputFilter::KeystrokeCondition::match(const Event &event) { } // check if it's our hotkey - IPrimaryScreen::HotKeyInfo *kinfo = - static_cast(event.getData()); + IPrimaryScreen::HotKeyInfo *kinfo = static_cast(event.getData()); if (kinfo->m_id != m_id) { return kNoMatch; } @@ -107,48 +116,55 @@ InputFilter::KeystrokeCondition::match(const Event &event) { return status; } -void InputFilter::KeystrokeCondition::enablePrimary(PrimaryClient *primary) { +void InputFilter::KeystrokeCondition::enablePrimary(PrimaryClient *primary) +{ m_id = primary->registerHotKey(m_key, m_mask); } -void InputFilter::KeystrokeCondition::disablePrimary(PrimaryClient *primary) { +void InputFilter::KeystrokeCondition::disablePrimary(PrimaryClient *primary) +{ primary->unregisterHotKey(m_id); m_id = 0; } -InputFilter::MouseButtonCondition::MouseButtonCondition( - IEventQueue *events, IPlatformScreen::ButtonInfo *info) +InputFilter::MouseButtonCondition::MouseButtonCondition(IEventQueue *events, IPlatformScreen::ButtonInfo *info) : m_button(info->m_button), m_mask(info->m_mask), - m_events(events) { + m_events(events) +{ free(info); } -InputFilter::MouseButtonCondition::MouseButtonCondition( - IEventQueue *events, ButtonID button, KeyModifierMask mask) +InputFilter::MouseButtonCondition::MouseButtonCondition(IEventQueue *events, ButtonID button, KeyModifierMask mask) : m_button(button), m_mask(mask), - m_events(events) { + m_events(events) +{ // do nothing } -InputFilter::MouseButtonCondition::~MouseButtonCondition() { +InputFilter::MouseButtonCondition::~MouseButtonCondition() +{ // do nothing } -ButtonID InputFilter::MouseButtonCondition::getButton() const { +ButtonID InputFilter::MouseButtonCondition::getButton() const +{ return m_button; } -KeyModifierMask InputFilter::MouseButtonCondition::getMask() const { +KeyModifierMask InputFilter::MouseButtonCondition::getMask() const +{ return m_mask; } -InputFilter::Condition *InputFilter::MouseButtonCondition::clone() const { +InputFilter::Condition *InputFilter::MouseButtonCondition::clone() const +{ return new MouseButtonCondition(m_events, m_button, m_mask); } -String InputFilter::MouseButtonCondition::format() const { +String InputFilter::MouseButtonCondition::format() const +{ String key = deskflow::KeyMap::formatKey(kKeyNone, m_mask); if (!key.empty()) { key += "+"; @@ -156,11 +172,10 @@ String InputFilter::MouseButtonCondition::format() const { return deskflow::string::sprintf("mousebutton(%s%d)", key.c_str(), m_button); } -InputFilter::EFilterStatus -InputFilter::MouseButtonCondition::match(const Event &event) { +InputFilter::EFilterStatus InputFilter::MouseButtonCondition::match(const Event &event) +{ static const KeyModifierMask s_ignoreMask = - KeyModifierAltGr | KeyModifierCapsLock | KeyModifierNumLock | - KeyModifierScrollLock; + KeyModifierAltGr | KeyModifierCapsLock | KeyModifierNumLock | KeyModifierScrollLock; EFilterStatus status; @@ -176,40 +191,40 @@ InputFilter::MouseButtonCondition::match(const Event &event) { // check if it's the right button and modifiers. ignore modifiers // that cannot be combined with a mouse button. - IPlatformScreen::ButtonInfo *minfo = - static_cast(event.getData()); - if (minfo->m_button != m_button || - (minfo->m_mask & ~s_ignoreMask) != m_mask) { + IPlatformScreen::ButtonInfo *minfo = static_cast(event.getData()); + if (minfo->m_button != m_button || (minfo->m_mask & ~s_ignoreMask) != m_mask) { return kNoMatch; } return status; } -InputFilter::ScreenConnectedCondition::ScreenConnectedCondition( - IEventQueue *events, const String &screen) +InputFilter::ScreenConnectedCondition::ScreenConnectedCondition(IEventQueue *events, const String &screen) : m_screen(screen), - m_events(events) { + m_events(events) +{ // do nothing } -InputFilter::ScreenConnectedCondition::~ScreenConnectedCondition() { +InputFilter::ScreenConnectedCondition::~ScreenConnectedCondition() +{ // do nothing } -InputFilter::Condition *InputFilter::ScreenConnectedCondition::clone() const { +InputFilter::Condition *InputFilter::ScreenConnectedCondition::clone() const +{ return new ScreenConnectedCondition(m_events, m_screen); } -String InputFilter::ScreenConnectedCondition::format() const { +String InputFilter::ScreenConnectedCondition::format() const +{ return deskflow::string::sprintf("connect(%s)", m_screen.c_str()); } -InputFilter::EFilterStatus -InputFilter::ScreenConnectedCondition::match(const Event &event) { +InputFilter::EFilterStatus InputFilter::ScreenConnectedCondition::match(const Event &event) +{ if (event.getType() == m_events->forServer().connected()) { - Server::ScreenConnectedInfo *info = - static_cast(event.getData()); + Server::ScreenConnectedInfo *info = static_cast(event.getData()); if (m_screen == info->m_screen || m_screen.empty()) { return kActivate; } @@ -221,169 +236,187 @@ InputFilter::ScreenConnectedCondition::match(const Event &event) { // ----------------------------------------------------------------------------- // Input Filter Action Classes // ----------------------------------------------------------------------------- -InputFilter::Action::Action() { +InputFilter::Action::Action() +{ // do nothing } -InputFilter::Action::~Action() { +InputFilter::Action::~Action() +{ // do nothing } -InputFilter::LockCursorToScreenAction::LockCursorToScreenAction( - IEventQueue *events, Mode mode) +InputFilter::LockCursorToScreenAction::LockCursorToScreenAction(IEventQueue *events, Mode mode) : m_mode(mode), - m_events(events) { + m_events(events) +{ // do nothing } -InputFilter::LockCursorToScreenAction::Mode -InputFilter::LockCursorToScreenAction::getMode() const { +InputFilter::LockCursorToScreenAction::Mode InputFilter::LockCursorToScreenAction::getMode() const +{ return m_mode; } -InputFilter::Action *InputFilter::LockCursorToScreenAction::clone() const { +InputFilter::Action *InputFilter::LockCursorToScreenAction::clone() const +{ return new LockCursorToScreenAction(*this); } -String InputFilter::LockCursorToScreenAction::format() const { +String InputFilter::LockCursorToScreenAction::format() const +{ static const char *s_mode[] = {"off", "on", "toggle"}; return deskflow::string::sprintf("lockCursorToScreen(%s)", s_mode[m_mode]); } -void InputFilter::LockCursorToScreenAction::perform(const Event &event) { +void InputFilter::LockCursorToScreenAction::perform(const Event &event) +{ static const Server::LockCursorToScreenInfo::State s_state[] = { - Server::LockCursorToScreenInfo::kOff, Server::LockCursorToScreenInfo::kOn, - Server::LockCursorToScreenInfo::kToggle}; + Server::LockCursorToScreenInfo::kOff, Server::LockCursorToScreenInfo::kOn, Server::LockCursorToScreenInfo::kToggle + }; // send event - Server::LockCursorToScreenInfo *info = - Server::LockCursorToScreenInfo::alloc(s_state[m_mode]); - m_events->addEvent(Event( - m_events->forServer().lockCursorToScreen(), event.getTarget(), info, - Event::kDeliverImmediately)); + Server::LockCursorToScreenInfo *info = Server::LockCursorToScreenInfo::alloc(s_state[m_mode]); + m_events->addEvent( + Event(m_events->forServer().lockCursorToScreen(), event.getTarget(), info, Event::kDeliverImmediately) + ); } -InputFilter::RestartServer::RestartServer(IEventQueue *events, Mode mode) - : m_mode(mode), - m_events(events) { +InputFilter::RestartServer::RestartServer(IEventQueue *events, Mode mode) : m_mode(mode), m_events(events) +{ // do nothing } -InputFilter::RestartServer::Mode InputFilter::RestartServer::getMode() const { +InputFilter::RestartServer::Mode InputFilter::RestartServer::getMode() const +{ return m_mode; } -InputFilter::Action *InputFilter::RestartServer::clone() const { +InputFilter::Action *InputFilter::RestartServer::clone() const +{ return new RestartServer(*this); } -String InputFilter::RestartServer::format() const { +String InputFilter::RestartServer::format() const +{ static const char *s_mode[] = {"restart"}; return deskflow::string::sprintf("restartServer(%s)", s_mode[m_mode]); } -void InputFilter::RestartServer::perform(const Event &event) { +void InputFilter::RestartServer::perform(const Event &event) +{ // HACK Super hack we should gracefully exit exit(0); } -InputFilter::SwitchToScreenAction::SwitchToScreenAction( - IEventQueue *events, const String &screen) +InputFilter::SwitchToScreenAction::SwitchToScreenAction(IEventQueue *events, const String &screen) : m_screen(screen), - m_events(events) { + m_events(events) +{ // do nothing } -String InputFilter::SwitchToScreenAction::getScreen() const { return m_screen; } +String InputFilter::SwitchToScreenAction::getScreen() const +{ + return m_screen; +} -InputFilter::Action *InputFilter::SwitchToScreenAction::clone() const { +InputFilter::Action *InputFilter::SwitchToScreenAction::clone() const +{ return new SwitchToScreenAction(*this); } -String InputFilter::SwitchToScreenAction::format() const { +String InputFilter::SwitchToScreenAction::format() const +{ return deskflow::string::sprintf("switchToScreen(%s)", m_screen.c_str()); } -void InputFilter::SwitchToScreenAction::perform(const Event &event) { +void InputFilter::SwitchToScreenAction::perform(const Event &event) +{ // pick screen name. if m_screen is empty then use the screen from // event if it has one. String screen = m_screen; if (screen.empty() && event.getType() == m_events->forServer().connected()) { - Server::ScreenConnectedInfo *info = - static_cast(event.getData()); + Server::ScreenConnectedInfo *info = static_cast(event.getData()); screen = info->m_screen; } // send event Server::SwitchToScreenInfo *info = Server::SwitchToScreenInfo::alloc(screen); - m_events->addEvent(Event( - m_events->forServer().switchToScreen(), event.getTarget(), info, - Event::kDeliverImmediately)); + m_events->addEvent(Event(m_events->forServer().switchToScreen(), event.getTarget(), info, Event::kDeliverImmediately) + ); } -InputFilter::SwitchInDirectionAction::SwitchInDirectionAction( - IEventQueue *events, EDirection direction) +InputFilter::SwitchInDirectionAction::SwitchInDirectionAction(IEventQueue *events, EDirection direction) : m_direction(direction), - m_events(events) { + m_events(events) +{ // do nothing } -EDirection InputFilter::SwitchInDirectionAction::getDirection() const { +EDirection InputFilter::SwitchInDirectionAction::getDirection() const +{ return m_direction; } -InputFilter::Action *InputFilter::SwitchInDirectionAction::clone() const { +InputFilter::Action *InputFilter::SwitchInDirectionAction::clone() const +{ return new SwitchInDirectionAction(*this); } -String InputFilter::SwitchInDirectionAction::format() const { +String InputFilter::SwitchInDirectionAction::format() const +{ static const char *s_names[] = {"", "left", "right", "up", "down"}; - return deskflow::string::sprintf( - "switchInDirection(%s)", s_names[m_direction]); + return deskflow::string::sprintf("switchInDirection(%s)", s_names[m_direction]); } -void InputFilter::SwitchInDirectionAction::perform(const Event &event) { - Server::SwitchInDirectionInfo *info = - Server::SwitchInDirectionInfo::alloc(m_direction); - m_events->addEvent(Event( - m_events->forServer().switchInDirection(), event.getTarget(), info, - Event::kDeliverImmediately)); +void InputFilter::SwitchInDirectionAction::perform(const Event &event) +{ + Server::SwitchInDirectionInfo *info = Server::SwitchInDirectionInfo::alloc(m_direction); + m_events->addEvent( + Event(m_events->forServer().switchInDirection(), event.getTarget(), info, Event::kDeliverImmediately) + ); } -InputFilter::KeyboardBroadcastAction::KeyboardBroadcastAction( - IEventQueue *events, Mode mode) +InputFilter::KeyboardBroadcastAction::KeyboardBroadcastAction(IEventQueue *events, Mode mode) : m_mode(mode), - m_events(events) { + m_events(events) +{ // do nothing } InputFilter::KeyboardBroadcastAction::KeyboardBroadcastAction( - IEventQueue *events, Mode mode, const std::set &screens) + IEventQueue *events, Mode mode, const std::set &screens +) : m_mode(mode), m_screens(IKeyState::KeyInfo::join(screens)), - m_events(events) { + m_events(events) +{ // do nothing } -InputFilter::KeyboardBroadcastAction::Mode -InputFilter::KeyboardBroadcastAction::getMode() const { +InputFilter::KeyboardBroadcastAction::Mode InputFilter::KeyboardBroadcastAction::getMode() const +{ return m_mode; } -std::set InputFilter::KeyboardBroadcastAction::getScreens() const { +std::set InputFilter::KeyboardBroadcastAction::getScreens() const +{ std::set screens; IKeyState::KeyInfo::split(m_screens.c_str(), screens); return screens; } -InputFilter::Action *InputFilter::KeyboardBroadcastAction::clone() const { +InputFilter::Action *InputFilter::KeyboardBroadcastAction::clone() const +{ return new KeyboardBroadcastAction(*this); } -String InputFilter::KeyboardBroadcastAction::format() const { +String InputFilter::KeyboardBroadcastAction::format() const +{ static const char *s_mode[] = {"off", "on", "toggle"}; static const char *s_name = "keyboardBroadcast"; @@ -391,123 +424,133 @@ String InputFilter::KeyboardBroadcastAction::format() const { return deskflow::string::sprintf("%s(%s)", s_name, s_mode[m_mode]); } else { return deskflow::string::sprintf( - "%s(%s,%.*s)", s_name, s_mode[m_mode], - static_cast(m_screens.size() >= 2 ? m_screens.size() - 2 : 0), - m_screens.c_str() + 1); + "%s(%s,%.*s)", s_name, s_mode[m_mode], static_cast(m_screens.size() >= 2 ? m_screens.size() - 2 : 0), + m_screens.c_str() + 1 + ); } } -void InputFilter::KeyboardBroadcastAction::perform(const Event &event) { +void InputFilter::KeyboardBroadcastAction::perform(const Event &event) +{ static const Server::KeyboardBroadcastInfo::State s_state[] = { - Server::KeyboardBroadcastInfo::kOff, Server::KeyboardBroadcastInfo::kOn, - Server::KeyboardBroadcastInfo::kToggle}; + Server::KeyboardBroadcastInfo::kOff, Server::KeyboardBroadcastInfo::kOn, Server::KeyboardBroadcastInfo::kToggle + }; // send event - Server::KeyboardBroadcastInfo *info = - Server::KeyboardBroadcastInfo::alloc(s_state[m_mode], m_screens); - m_events->addEvent(Event( - m_events->forServer().keyboardBroadcast(), event.getTarget(), info, - Event::kDeliverImmediately)); + Server::KeyboardBroadcastInfo *info = Server::KeyboardBroadcastInfo::alloc(s_state[m_mode], m_screens); + m_events->addEvent( + Event(m_events->forServer().keyboardBroadcast(), event.getTarget(), info, Event::kDeliverImmediately) + ); } -InputFilter::KeystrokeAction::KeystrokeAction( - IEventQueue *events, IPlatformScreen::KeyInfo *info, bool press) +InputFilter::KeystrokeAction::KeystrokeAction(IEventQueue *events, IPlatformScreen::KeyInfo *info, bool press) : m_keyInfo(info), m_press(press), - m_events(events) { + m_events(events) +{ // do nothing } -InputFilter::KeystrokeAction::~KeystrokeAction() { free(m_keyInfo); } +InputFilter::KeystrokeAction::~KeystrokeAction() +{ + free(m_keyInfo); +} -void InputFilter::KeystrokeAction::adoptInfo(IPlatformScreen::KeyInfo *info) { +void InputFilter::KeystrokeAction::adoptInfo(IPlatformScreen::KeyInfo *info) +{ free(m_keyInfo); m_keyInfo = info; } -const IPlatformScreen::KeyInfo *InputFilter::KeystrokeAction::getInfo() const { +const IPlatformScreen::KeyInfo *InputFilter::KeystrokeAction::getInfo() const +{ return m_keyInfo; } -bool InputFilter::KeystrokeAction::isOnPress() const { return m_press; } +bool InputFilter::KeystrokeAction::isOnPress() const +{ + return m_press; +} -InputFilter::Action *InputFilter::KeystrokeAction::clone() const { +InputFilter::Action *InputFilter::KeystrokeAction::clone() const +{ IKeyState::KeyInfo *info = IKeyState::KeyInfo::alloc(*m_keyInfo); return new KeystrokeAction(m_events, info, m_press); } -String InputFilter::KeystrokeAction::format() const { +String InputFilter::KeystrokeAction::format() const +{ const char *type = formatName(); if (m_keyInfo->m_screens[0] == '\0') { return deskflow::string::sprintf( - "%s(%s)", type, - deskflow::KeyMap::formatKey(m_keyInfo->m_key, m_keyInfo->m_mask) - .c_str()); + "%s(%s)", type, deskflow::KeyMap::formatKey(m_keyInfo->m_key, m_keyInfo->m_mask).c_str() + ); } else if (m_keyInfo->m_screens[0] == '*') { return deskflow::string::sprintf( - "%s(%s,*)", type, - deskflow::KeyMap::formatKey(m_keyInfo->m_key, m_keyInfo->m_mask) - .c_str()); + "%s(%s,*)", type, deskflow::KeyMap::formatKey(m_keyInfo->m_key, m_keyInfo->m_mask).c_str() + ); } else { return deskflow::string::sprintf( - "%s(%s,%.*s)", type, - deskflow::KeyMap::formatKey(m_keyInfo->m_key, m_keyInfo->m_mask) - .c_str(), - strnlen(m_keyInfo->m_screens + 1, SIZE_MAX) - 1, - m_keyInfo->m_screens + 1); + "%s(%s,%.*s)", type, deskflow::KeyMap::formatKey(m_keyInfo->m_key, m_keyInfo->m_mask).c_str(), + strnlen(m_keyInfo->m_screens + 1, SIZE_MAX) - 1, m_keyInfo->m_screens + 1 + ); } } -void InputFilter::KeystrokeAction::perform(const Event &event) { - Event::Type type = m_press ? m_events->forIKeyState().keyDown() - : m_events->forIKeyState().keyUp(); +void InputFilter::KeystrokeAction::perform(const Event &event) +{ + Event::Type type = m_press ? m_events->forIKeyState().keyDown() : m_events->forIKeyState().keyUp(); - m_events->addEvent(Event( - m_events->forIPrimaryScreen().fakeInputBegin(), event.getTarget(), NULL, - Event::kDeliverImmediately)); - m_events->addEvent(Event( - type, event.getTarget(), m_keyInfo, - Event::kDeliverImmediately | Event::kDontFreeData)); - m_events->addEvent(Event( - m_events->forIPrimaryScreen().fakeInputEnd(), event.getTarget(), NULL, - Event::kDeliverImmediately)); + m_events->addEvent( + Event(m_events->forIPrimaryScreen().fakeInputBegin(), event.getTarget(), NULL, Event::kDeliverImmediately) + ); + m_events->addEvent(Event(type, event.getTarget(), m_keyInfo, Event::kDeliverImmediately | Event::kDontFreeData)); + m_events->addEvent( + Event(m_events->forIPrimaryScreen().fakeInputEnd(), event.getTarget(), NULL, Event::kDeliverImmediately) + ); } -const char *InputFilter::KeystrokeAction::formatName() const { +const char *InputFilter::KeystrokeAction::formatName() const +{ return (m_press ? "keyDown" : "keyUp"); } -InputFilter::MouseButtonAction::MouseButtonAction( - IEventQueue *events, IPlatformScreen::ButtonInfo *info, bool press) +InputFilter::MouseButtonAction::MouseButtonAction(IEventQueue *events, IPlatformScreen::ButtonInfo *info, bool press) : m_buttonInfo(info), m_press(press), - m_events(events) { + m_events(events) +{ // do nothing } -InputFilter::MouseButtonAction::~MouseButtonAction() { free(m_buttonInfo); } +InputFilter::MouseButtonAction::~MouseButtonAction() +{ + free(m_buttonInfo); +} -const IPlatformScreen::ButtonInfo * -InputFilter::MouseButtonAction::getInfo() const { +const IPlatformScreen::ButtonInfo *InputFilter::MouseButtonAction::getInfo() const +{ return m_buttonInfo; } -bool InputFilter::MouseButtonAction::isOnPress() const { return m_press; } +bool InputFilter::MouseButtonAction::isOnPress() const +{ + return m_press; +} -InputFilter::Action *InputFilter::MouseButtonAction::clone() const { - IPlatformScreen::ButtonInfo *info = - IPrimaryScreen::ButtonInfo::alloc(*m_buttonInfo); +InputFilter::Action *InputFilter::MouseButtonAction::clone() const +{ + IPlatformScreen::ButtonInfo *info = IPrimaryScreen::ButtonInfo::alloc(*m_buttonInfo); return new MouseButtonAction(m_events, info, m_press); } -String InputFilter::MouseButtonAction::format() const { +String InputFilter::MouseButtonAction::format() const +{ const char *type = formatName(); String key = deskflow::KeyMap::formatKey(kKeyNone, m_buttonInfo->m_mask); - return deskflow::string::sprintf( - "%s(%s%s%d)", type, key.c_str(), key.empty() ? "" : "+", - m_buttonInfo->m_button); + return deskflow::string::sprintf("%s(%s%s%d)", type, key.c_str(), key.empty() ? "" : "+", m_buttonInfo->m_button); } void InputFilter::MouseButtonAction::perform(const Event &event) @@ -518,20 +561,18 @@ void InputFilter::MouseButtonAction::perform(const Event &event) if (m_buttonInfo->m_mask != 0) { KeyID key = m_press ? kKeySetModifiers : kKeyClearModifiers; modifierInfo = IKeyState::KeyInfo::alloc(key, m_buttonInfo->m_mask, 0, 1); - m_events->addEvent(Event( - m_events->forIKeyState().keyDown(), event.getTarget(), modifierInfo, - Event::kDeliverImmediately)); + m_events->addEvent( + Event(m_events->forIKeyState().keyDown(), event.getTarget(), modifierInfo, Event::kDeliverImmediately) + ); } // send button - Event::Type type = m_press ? m_events->forIPrimaryScreen().buttonDown() - : m_events->forIPrimaryScreen().buttonUp(); - m_events->addEvent(Event( - type, event.getTarget(), m_buttonInfo, - Event::kDeliverImmediately | Event::kDontFreeData)); + Event::Type type = m_press ? m_events->forIPrimaryScreen().buttonDown() : m_events->forIPrimaryScreen().buttonUp(); + m_events->addEvent(Event(type, event.getTarget(), m_buttonInfo, Event::kDeliverImmediately | Event::kDontFreeData)); } -const char *InputFilter::MouseButtonAction::formatName() const { +const char *InputFilter::MouseButtonAction::formatName() const +{ return (m_press ? "mouseDown" : "mouseUp"); } @@ -539,34 +580,41 @@ const char *InputFilter::MouseButtonAction::formatName() const { // InputFilter::Rule // -InputFilter::Rule::Rule() : m_condition(NULL) { +InputFilter::Rule::Rule() : m_condition(NULL) +{ // do nothing } -InputFilter::Rule::Rule(Condition *adoptedCondition) - : m_condition(adoptedCondition) { +InputFilter::Rule::Rule(Condition *adoptedCondition) : m_condition(adoptedCondition) +{ // do nothing } -InputFilter::Rule::Rule(const Rule &rule) : m_condition(NULL) { copy(rule); } +InputFilter::Rule::Rule(const Rule &rule) : m_condition(NULL) +{ + copy(rule); +} -InputFilter::Rule::~Rule() { clear(); } +InputFilter::Rule::~Rule() +{ + clear(); +} -InputFilter::Rule &InputFilter::Rule::operator=(const Rule &rule) { +InputFilter::Rule &InputFilter::Rule::operator=(const Rule &rule) +{ if (&rule != this) { copy(rule); } return *this; } -void InputFilter::Rule::clear() { +void InputFilter::Rule::clear() +{ delete m_condition; - for (ActionList::iterator i = m_activateActions.begin(); - i != m_activateActions.end(); ++i) { + for (ActionList::iterator i = m_activateActions.begin(); i != m_activateActions.end(); ++i) { delete *i; } - for (ActionList::iterator i = m_deactivateActions.begin(); - i != m_deactivateActions.end(); ++i) { + for (ActionList::iterator i = m_deactivateActions.begin(); i != m_deactivateActions.end(); ++i) { delete *i; } @@ -575,27 +623,28 @@ void InputFilter::Rule::clear() { m_deactivateActions.clear(); } -void InputFilter::Rule::copy(const Rule &rule) { +void InputFilter::Rule::copy(const Rule &rule) +{ clear(); if (rule.m_condition != NULL) { m_condition = rule.m_condition->clone(); } - for (ActionList::const_iterator i = rule.m_activateActions.begin(); - i != rule.m_activateActions.end(); ++i) { + for (ActionList::const_iterator i = rule.m_activateActions.begin(); i != rule.m_activateActions.end(); ++i) { m_activateActions.push_back((*i)->clone()); } - for (ActionList::const_iterator i = rule.m_deactivateActions.begin(); - i != rule.m_deactivateActions.end(); ++i) { + for (ActionList::const_iterator i = rule.m_deactivateActions.begin(); i != rule.m_deactivateActions.end(); ++i) { m_deactivateActions.push_back((*i)->clone()); } } -void InputFilter::Rule::setCondition(Condition *adopted) { +void InputFilter::Rule::setCondition(Condition *adopted) +{ delete m_condition; m_condition = adopted; } -void InputFilter::Rule::adoptAction(Action *action, bool onActivation) { +void InputFilter::Rule::adoptAction(Action *action, bool onActivation) +{ if (action != NULL) { if (onActivation) { m_activateActions.push_back(action); @@ -605,7 +654,8 @@ void InputFilter::Rule::adoptAction(Action *action, bool onActivation) { } } -void InputFilter::Rule::removeAction(bool onActivation, UInt32 index) { +void InputFilter::Rule::removeAction(bool onActivation, UInt32 index) +{ if (onActivation) { delete m_activateActions[index]; m_activateActions.erase(m_activateActions.begin() + index); @@ -615,8 +665,8 @@ void InputFilter::Rule::removeAction(bool onActivation, UInt32 index) { } } -void InputFilter::Rule::replaceAction( - Action *adopted, bool onActivation, UInt32 index) { +void InputFilter::Rule::replaceAction(Action *adopted, bool onActivation, UInt32 index) +{ if (adopted == NULL) { removeAction(onActivation, index); } else if (onActivation) { @@ -628,19 +678,22 @@ void InputFilter::Rule::replaceAction( } } -void InputFilter::Rule::enable(PrimaryClient *primaryClient) { +void InputFilter::Rule::enable(PrimaryClient *primaryClient) +{ if (m_condition != NULL) { m_condition->enablePrimary(primaryClient); } } -void InputFilter::Rule::disable(PrimaryClient *primaryClient) { +void InputFilter::Rule::disable(PrimaryClient *primaryClient) +{ if (m_condition != NULL) { m_condition->disablePrimary(primaryClient); } } -bool InputFilter::Rule::handleEvent(const Event &event) { +bool InputFilter::Rule::handleEvent(const Event &event) +{ // NULL condition never matches if (m_condition == NULL) { return false; @@ -665,8 +718,7 @@ bool InputFilter::Rule::handleEvent(const Event &event) { } // perform actions - for (ActionList::const_iterator i = actions->begin(); i != actions->end(); - ++i) { + for (ActionList::const_iterator i = actions->begin(); i != actions->end(); ++i) { LOG((CLOG_DEBUG1 "hotkey: %s", (*i)->format().c_str())); (*i)->perform(event); } @@ -674,7 +726,8 @@ bool InputFilter::Rule::handleEvent(const Event &event) { return true; } -String InputFilter::Rule::format() const { +String InputFilter::Rule::format() const +{ String s; if (m_condition != NULL) { // condition @@ -707,11 +760,13 @@ String InputFilter::Rule::format() const { return s; } -const InputFilter::Condition *InputFilter::Rule::getCondition() const { +const InputFilter::Condition *InputFilter::Rule::getCondition() const +{ return m_condition; } -UInt32 InputFilter::Rule::getNumActions(bool onActivation) const { +UInt32 InputFilter::Rule::getNumActions(bool onActivation) const +{ if (onActivation) { return static_cast(m_activateActions.size()); } else { @@ -719,8 +774,8 @@ UInt32 InputFilter::Rule::getNumActions(bool onActivation) const { } } -const InputFilter::Action & -InputFilter::Rule::getAction(bool onActivation, UInt32 index) const { +const InputFilter::Action &InputFilter::Rule::getAction(bool onActivation, UInt32 index) const +{ if (onActivation) { return *m_activateActions[index]; } else { @@ -731,22 +786,23 @@ InputFilter::Rule::getAction(bool onActivation, UInt32 index) const { // ----------------------------------------------------------------------------- // Input Filter Class // ----------------------------------------------------------------------------- -InputFilter::InputFilter(IEventQueue *events) - : m_primaryClient(NULL), - m_events(events) { +InputFilter::InputFilter(IEventQueue *events) : m_primaryClient(NULL), m_events(events) +{ // do nothing } -InputFilter::InputFilter(const InputFilter &x) - : m_ruleList(x.m_ruleList), - m_primaryClient(NULL), - m_events(x.m_events) { +InputFilter::InputFilter(const InputFilter &x) : m_ruleList(x.m_ruleList), m_primaryClient(NULL), m_events(x.m_events) +{ setPrimaryClient(x.m_primaryClient); } -InputFilter::~InputFilter() { setPrimaryClient(NULL); } +InputFilter::~InputFilter() +{ + setPrimaryClient(NULL); +} -InputFilter &InputFilter::operator=(const InputFilter &x) { +InputFilter &InputFilter::operator=(const InputFilter &x) +{ if (&x != this) { PrimaryClient *oldClient = m_primaryClient; setPrimaryClient(NULL); @@ -758,56 +814,46 @@ InputFilter &InputFilter::operator=(const InputFilter &x) { return *this; } -void InputFilter::addFilterRule(const Rule &rule) { +void InputFilter::addFilterRule(const Rule &rule) +{ m_ruleList.push_back(rule); if (m_primaryClient != NULL) { m_ruleList.back().enable(m_primaryClient); } } -void InputFilter::removeFilterRule(UInt32 index) { +void InputFilter::removeFilterRule(UInt32 index) +{ if (m_primaryClient != NULL) { m_ruleList[index].disable(m_primaryClient); } m_ruleList.erase(m_ruleList.begin() + index); } -InputFilter::Rule &InputFilter::getRule(UInt32 index) { +InputFilter::Rule &InputFilter::getRule(UInt32 index) +{ return m_ruleList[index]; } -void InputFilter::setPrimaryClient(PrimaryClient *client) { +void InputFilter::setPrimaryClient(PrimaryClient *client) +{ if (m_primaryClient == client) { return; } if (m_primaryClient != NULL) { - for (RuleList::iterator rule = m_ruleList.begin(); rule != m_ruleList.end(); - ++rule) { + for (RuleList::iterator rule = m_ruleList.begin(); rule != m_ruleList.end(); ++rule) { rule->disable(m_primaryClient); } - m_events->removeHandler( - m_events->forIKeyState().keyDown(), m_primaryClient->getEventTarget()); - m_events->removeHandler( - m_events->forIKeyState().keyUp(), m_primaryClient->getEventTarget()); - m_events->removeHandler( - m_events->forIKeyState().keyRepeat(), - m_primaryClient->getEventTarget()); - m_events->removeHandler( - m_events->forIPrimaryScreen().buttonDown(), - m_primaryClient->getEventTarget()); - m_events->removeHandler( - m_events->forIPrimaryScreen().buttonUp(), - m_primaryClient->getEventTarget()); - m_events->removeHandler( - m_events->forIPrimaryScreen().hotKeyDown(), - m_primaryClient->getEventTarget()); - m_events->removeHandler( - m_events->forIPrimaryScreen().hotKeyUp(), - m_primaryClient->getEventTarget()); - m_events->removeHandler( - m_events->forServer().connected(), m_primaryClient->getEventTarget()); + m_events->removeHandler(m_events->forIKeyState().keyDown(), m_primaryClient->getEventTarget()); + m_events->removeHandler(m_events->forIKeyState().keyUp(), m_primaryClient->getEventTarget()); + m_events->removeHandler(m_events->forIKeyState().keyRepeat(), m_primaryClient->getEventTarget()); + m_events->removeHandler(m_events->forIPrimaryScreen().buttonDown(), m_primaryClient->getEventTarget()); + m_events->removeHandler(m_events->forIPrimaryScreen().buttonUp(), m_primaryClient->getEventTarget()); + m_events->removeHandler(m_events->forIPrimaryScreen().hotKeyDown(), m_primaryClient->getEventTarget()); + m_events->removeHandler(m_events->forIPrimaryScreen().hotKeyUp(), m_primaryClient->getEventTarget()); + m_events->removeHandler(m_events->forServer().connected(), m_primaryClient->getEventTarget()); } m_primaryClient = client; @@ -815,44 +861,47 @@ void InputFilter::setPrimaryClient(PrimaryClient *client) { if (m_primaryClient != NULL) { m_events->adoptHandler( m_events->forIKeyState().keyDown(), m_primaryClient->getEventTarget(), - new TMethodEventJob(this, &InputFilter::handleEvent)); + new TMethodEventJob(this, &InputFilter::handleEvent) + ); m_events->adoptHandler( m_events->forIKeyState().keyUp(), m_primaryClient->getEventTarget(), - new TMethodEventJob(this, &InputFilter::handleEvent)); + new TMethodEventJob(this, &InputFilter::handleEvent) + ); m_events->adoptHandler( m_events->forIKeyState().keyRepeat(), m_primaryClient->getEventTarget(), - new TMethodEventJob(this, &InputFilter::handleEvent)); + new TMethodEventJob(this, &InputFilter::handleEvent) + ); m_events->adoptHandler( - m_events->forIPrimaryScreen().buttonDown(), - m_primaryClient->getEventTarget(), - new TMethodEventJob(this, &InputFilter::handleEvent)); + m_events->forIPrimaryScreen().buttonDown(), m_primaryClient->getEventTarget(), + new TMethodEventJob(this, &InputFilter::handleEvent) + ); m_events->adoptHandler( - m_events->forIPrimaryScreen().buttonUp(), - m_primaryClient->getEventTarget(), - new TMethodEventJob(this, &InputFilter::handleEvent)); + m_events->forIPrimaryScreen().buttonUp(), m_primaryClient->getEventTarget(), + new TMethodEventJob(this, &InputFilter::handleEvent) + ); m_events->adoptHandler( - m_events->forIPrimaryScreen().hotKeyDown(), - m_primaryClient->getEventTarget(), - new TMethodEventJob(this, &InputFilter::handleEvent)); + m_events->forIPrimaryScreen().hotKeyDown(), m_primaryClient->getEventTarget(), + new TMethodEventJob(this, &InputFilter::handleEvent) + ); m_events->adoptHandler( - m_events->forIPrimaryScreen().hotKeyUp(), - m_primaryClient->getEventTarget(), - new TMethodEventJob(this, &InputFilter::handleEvent)); + m_events->forIPrimaryScreen().hotKeyUp(), m_primaryClient->getEventTarget(), + new TMethodEventJob(this, &InputFilter::handleEvent) + ); m_events->adoptHandler( m_events->forServer().connected(), m_primaryClient->getEventTarget(), - new TMethodEventJob(this, &InputFilter::handleEvent)); + new TMethodEventJob(this, &InputFilter::handleEvent) + ); - for (RuleList::iterator rule = m_ruleList.begin(); rule != m_ruleList.end(); - ++rule) { + for (RuleList::iterator rule = m_ruleList.begin(); rule != m_ruleList.end(); ++rule) { rule->enable(m_primaryClient); } } } -String InputFilter::format(const String &linePrefix) const { +String InputFilter::format(const String &linePrefix) const +{ String s; - for (RuleList::const_iterator i = m_ruleList.begin(); i != m_ruleList.end(); - ++i) { + for (RuleList::const_iterator i = m_ruleList.begin(); i != m_ruleList.end(); ++i) { s += linePrefix; s += i->format(); s += "\n"; @@ -860,11 +909,13 @@ String InputFilter::format(const String &linePrefix) const { return s; } -UInt32 InputFilter::getNumRules() const { +UInt32 InputFilter::getNumRules() const +{ return static_cast(m_ruleList.size()); } -bool InputFilter::operator==(const InputFilter &x) const { +bool InputFilter::operator==(const InputFilter &x) const +{ // if there are different numbers of rules then we can't be equal if (m_ruleList.size() != x.m_ruleList.size()) { return false; @@ -873,12 +924,10 @@ bool InputFilter::operator==(const InputFilter &x) const { // compare rule lists. the easiest way to do that is to format each // rule into a string, sort the strings, then compare the results. std::vector aList, bList; - for (RuleList::const_iterator i = m_ruleList.begin(); i != m_ruleList.end(); - ++i) { + for (RuleList::const_iterator i = m_ruleList.begin(); i != m_ruleList.end(); ++i) { aList.push_back(i->format()); } - for (RuleList::const_iterator i = x.m_ruleList.begin(); - i != x.m_ruleList.end(); ++i) { + for (RuleList::const_iterator i = x.m_ruleList.begin(); i != x.m_ruleList.end(); ++i) { bList.push_back(i->format()); } std::partial_sort(aList.begin(), aList.end(), aList.end()); @@ -886,19 +935,20 @@ bool InputFilter::operator==(const InputFilter &x) const { return (aList == bList); } -bool InputFilter::operator!=(const InputFilter &x) const { +bool InputFilter::operator!=(const InputFilter &x) const +{ return !operator==(x); } -void InputFilter::handleEvent(const Event &event, void *) { +void InputFilter::handleEvent(const Event &event, void *) +{ // copy event and adjust target Event myEvent( - event.getType(), this, event.getData(), - event.getFlags() | Event::kDontFreeData | Event::kDeliverImmediately); + event.getType(), this, event.getData(), event.getFlags() | Event::kDontFreeData | Event::kDeliverImmediately + ); // let each rule try to match the event until one does - for (RuleList::iterator rule = m_ruleList.begin(); rule != m_ruleList.end(); - ++rule) { + for (RuleList::iterator rule = m_ruleList.begin(); rule != m_ruleList.end(); ++rule) { if (rule->handleEvent(myEvent)) { // handled return; diff --git a/src/lib/server/InputFilter.h b/src/lib/server/InputFilter.h index b8950c103..63c4467ee 100644 --- a/src/lib/server/InputFilter.h +++ b/src/lib/server/InputFilter.h @@ -30,14 +30,21 @@ class PrimaryClient; class Event; class IEventQueue; -class InputFilter { +class InputFilter +{ public: // ------------------------------------------------------------------------- // Input Filter Condition Classes // ------------------------------------------------------------------------- - enum EFilterStatus { kNoMatch, kActivate, kDeactivate }; + enum EFilterStatus + { + kNoMatch, + kActivate, + kDeactivate + }; - class Condition { + class Condition + { public: Condition(); virtual ~Condition(); @@ -52,7 +59,8 @@ public: }; // KeystrokeCondition - class KeystrokeCondition : public Condition { + class KeystrokeCondition : public Condition + { public: KeystrokeCondition(IEventQueue *events, IPlatformScreen::KeyInfo *); KeystrokeCondition(IEventQueue *events, KeyID key, KeyModifierMask mask); @@ -76,7 +84,8 @@ public: }; // MouseButtonCondition - class MouseButtonCondition : public Condition { + class MouseButtonCondition : public Condition + { public: MouseButtonCondition(IEventQueue *events, IPlatformScreen::ButtonInfo *); MouseButtonCondition(IEventQueue *events, ButtonID, KeyModifierMask mask); @@ -97,7 +106,8 @@ public: }; // ScreenConnectedCondition - class ScreenConnectedCondition : public Condition { + class ScreenConnectedCondition : public Condition + { public: ScreenConnectedCondition(IEventQueue *events, const String &screen); virtual ~ScreenConnectedCondition(); @@ -116,7 +126,8 @@ public: // Input Filter Action Classes // ------------------------------------------------------------------------- - class Action { + class Action + { public: Action(); virtual ~Action(); @@ -128,9 +139,15 @@ public: }; // LockCursorToScreenAction - class LockCursorToScreenAction : public Action { + class LockCursorToScreenAction : public Action + { public: - enum Mode { kOff, kOn, kToggle }; + enum Mode + { + kOff, + kOn, + kToggle + }; LockCursorToScreenAction(IEventQueue *events, Mode = kToggle); @@ -146,9 +163,13 @@ public: IEventQueue *m_events; }; - class RestartServer : public Action { + class RestartServer : public Action + { public: - enum Mode { restart }; + enum Mode + { + restart + }; RestartServer(IEventQueue *events, Mode = restart); @@ -165,7 +186,8 @@ public: }; // SwitchToScreenAction - class SwitchToScreenAction : public Action { + class SwitchToScreenAction : public Action + { public: SwitchToScreenAction(IEventQueue *events, const String &screen); @@ -182,7 +204,8 @@ public: }; // SwitchInDirectionAction - class SwitchInDirectionAction : public Action { + class SwitchInDirectionAction : public Action + { public: SwitchInDirectionAction(IEventQueue *events, EDirection); @@ -199,13 +222,18 @@ public: }; // KeyboardBroadcastAction - class KeyboardBroadcastAction : public Action { + class KeyboardBroadcastAction : public Action + { public: - enum Mode { kOff, kOn, kToggle }; + enum Mode + { + kOff, + kOn, + kToggle + }; KeyboardBroadcastAction(IEventQueue *events, Mode = kToggle); - KeyboardBroadcastAction( - IEventQueue *events, Mode, const std::set &screens); + KeyboardBroadcastAction(IEventQueue *events, Mode, const std::set &screens); Mode getMode() const; std::set getScreens() const; @@ -222,10 +250,10 @@ public: }; // KeystrokeAction - class KeystrokeAction : public Action { + class KeystrokeAction : public Action + { public: - KeystrokeAction( - IEventQueue *events, IPlatformScreen::KeyInfo *adoptedInfo, bool press); + KeystrokeAction(IEventQueue *events, IPlatformScreen::KeyInfo *adoptedInfo, bool press); KeystrokeAction(KeystrokeAction const &) = delete; KeystrokeAction(KeystrokeAction &&) = delete; ~KeystrokeAction(); @@ -252,11 +280,10 @@ public: }; // MouseButtonAction -- modifier combinations not implemented yet - class MouseButtonAction : public Action { + class MouseButtonAction : public Action + { public: - MouseButtonAction( - IEventQueue *events, IPlatformScreen::ButtonInfo *adoptedInfo, - bool press); + MouseButtonAction(IEventQueue *events, IPlatformScreen::ButtonInfo *adoptedInfo, bool press); MouseButtonAction(MouseButtonAction const &) = delete; MouseButtonAction(MouseButtonAction &&) = delete; ~MouseButtonAction(); @@ -281,7 +308,8 @@ public: IEventQueue *m_events; }; - class Rule { + class Rule + { public: Rule(); Rule(Condition *adopted); @@ -343,7 +371,9 @@ public: virtual ~InputFilter(); #ifdef TEST_ENV - InputFilter() : m_primaryClient(NULL) {} + InputFilter() : m_primaryClient(NULL) + { + } #endif InputFilter &operator=(const InputFilter &); diff --git a/src/lib/server/PrimaryClient.cpp b/src/lib/server/PrimaryClient.cpp index 63ae13942..a7024daec 100644 --- a/src/lib/server/PrimaryClient.cpp +++ b/src/lib/server/PrimaryClient.cpp @@ -29,81 +29,100 @@ PrimaryClient::PrimaryClient(const String &name, deskflow::Screen *screen) : BaseClientProxy(name), m_screen(screen), - m_fakeInputCount(0) { + m_fakeInputCount(0) +{ // all clipboards are clean for (UInt32 i = 0; i < kClipboardEnd; ++i) { m_clipboardDirty[i] = false; } } -PrimaryClient::~PrimaryClient() { +PrimaryClient::~PrimaryClient() +{ // do nothing } -void PrimaryClient::reconfigure(UInt32 activeSides) { +void PrimaryClient::reconfigure(UInt32 activeSides) +{ m_screen->reconfigure(activeSides); } -UInt32 PrimaryClient::registerHotKey(KeyID key, KeyModifierMask mask) { +UInt32 PrimaryClient::registerHotKey(KeyID key, KeyModifierMask mask) +{ return m_screen->registerHotKey(key, mask); } -void PrimaryClient::unregisterHotKey(UInt32 id) { +void PrimaryClient::unregisterHotKey(UInt32 id) +{ m_screen->unregisterHotKey(id); } -void PrimaryClient::fakeInputBegin() { +void PrimaryClient::fakeInputBegin() +{ if (++m_fakeInputCount == 1) { m_screen->fakeInputBegin(); } } -void PrimaryClient::fakeInputEnd() { +void PrimaryClient::fakeInputEnd() +{ if (--m_fakeInputCount == 0) { m_screen->fakeInputEnd(); } } -SInt32 PrimaryClient::getJumpZoneSize() const { +SInt32 PrimaryClient::getJumpZoneSize() const +{ return m_screen->getJumpZoneSize(); } -void PrimaryClient::getCursorCenter(SInt32 &x, SInt32 &y) const { +void PrimaryClient::getCursorCenter(SInt32 &x, SInt32 &y) const +{ m_screen->getCursorCenter(x, y); } -KeyModifierMask PrimaryClient::getToggleMask() const { +KeyModifierMask PrimaryClient::getToggleMask() const +{ return m_screen->pollActiveModifiers(); } -bool PrimaryClient::isLockedToScreen() const { +bool PrimaryClient::isLockedToScreen() const +{ return m_screen->isLockedToScreen(); } -void *PrimaryClient::getEventTarget() const { +void *PrimaryClient::getEventTarget() const +{ return m_screen->getEventTarget(); } -bool PrimaryClient::getClipboard(ClipboardID id, IClipboard *clipboard) const { +bool PrimaryClient::getClipboard(ClipboardID id, IClipboard *clipboard) const +{ return m_screen->getClipboard(id, clipboard); } -void PrimaryClient::getShape( - SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const { +void PrimaryClient::getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const +{ m_screen->getShape(x, y, width, height); } -void PrimaryClient::getCursorPos(SInt32 &x, SInt32 &y) const { +void PrimaryClient::getCursorPos(SInt32 &x, SInt32 &y) const +{ m_screen->getCursorPos(x, y); } -void PrimaryClient::enable() { m_screen->enable(); } +void PrimaryClient::enable() +{ + m_screen->enable(); +} -void PrimaryClient::disable() { m_screen->disable(); } +void PrimaryClient::disable() +{ + m_screen->disable(); +} -void PrimaryClient::enter( - SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, - bool screensaver) { +void PrimaryClient::enter(SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, bool screensaver) +{ m_screen->setSequenceNumber(seqNum); if (!screensaver) { m_screen->warpCursor(xAbs, yAbs); @@ -111,9 +130,13 @@ void PrimaryClient::enter( m_screen->enter(mask); } -bool PrimaryClient::leave() { return m_screen->leave(); } +bool PrimaryClient::leave() +{ + return m_screen->leave(); +} -void PrimaryClient::setClipboard(ClipboardID id, const IClipboard *clipboard) { +void PrimaryClient::setClipboard(ClipboardID id, const IClipboard *clipboard) +{ // ignore if this clipboard is already clean if (m_clipboardDirty[id]) { // this clipboard is now clean @@ -124,7 +147,8 @@ void PrimaryClient::setClipboard(ClipboardID id, const IClipboard *clipboard) { } } -void PrimaryClient::grabClipboard(ClipboardID id) { +void PrimaryClient::grabClipboard(ClipboardID id) +{ // grab clipboard m_screen->grabClipboard(id); @@ -132,12 +156,13 @@ void PrimaryClient::grabClipboard(ClipboardID id) { m_clipboardDirty[id] = true; } -void PrimaryClient::setClipboardDirty(ClipboardID id, bool dirty) { +void PrimaryClient::setClipboardDirty(ClipboardID id, bool dirty) +{ m_clipboardDirty[id] = dirty; } -void PrimaryClient::keyDown( - KeyID key, KeyModifierMask mask, KeyButton button, const String &) { +void PrimaryClient::keyDown(KeyID key, KeyModifierMask mask, KeyButton button, const String &) +{ if (m_fakeInputCount > 0) { // XXX -- don't forward keystrokes to primary screen for now (void)key; @@ -147,12 +172,13 @@ void PrimaryClient::keyDown( } } -void PrimaryClient::keyRepeat( - KeyID, KeyModifierMask, SInt32, KeyButton, const String &) { +void PrimaryClient::keyRepeat(KeyID, KeyModifierMask, SInt32, KeyButton, const String &) +{ // ignore } -void PrimaryClient::keyUp(KeyID key, KeyModifierMask mask, KeyButton button) { +void PrimaryClient::keyUp(KeyID key, KeyModifierMask mask, KeyButton button) +{ if (m_fakeInputCount > 0) { // XXX -- don't forward keystrokes to primary screen for now (void)key; @@ -162,61 +188,74 @@ void PrimaryClient::keyUp(KeyID key, KeyModifierMask mask, KeyButton button) { } } -void PrimaryClient::mouseDown(ButtonID) { +void PrimaryClient::mouseDown(ButtonID) +{ // ignore } -void PrimaryClient::mouseUp(ButtonID) { +void PrimaryClient::mouseUp(ButtonID) +{ // ignore } -void PrimaryClient::mouseMove(SInt32 x, SInt32 y) { +void PrimaryClient::mouseMove(SInt32 x, SInt32 y) +{ m_screen->warpCursor(x, y); } -void PrimaryClient::mouseRelativeMove(SInt32, SInt32) { +void PrimaryClient::mouseRelativeMove(SInt32, SInt32) +{ // ignore } -void PrimaryClient::mouseWheel(SInt32, SInt32) { +void PrimaryClient::mouseWheel(SInt32, SInt32) +{ // ignore } -void PrimaryClient::screensaver(bool) { +void PrimaryClient::screensaver(bool) +{ // ignore } -void PrimaryClient::sendDragInfo( - UInt32 fileCount, const char *info, size_t size) { +void PrimaryClient::sendDragInfo(UInt32 fileCount, const char *info, size_t size) +{ // ignore } -void PrimaryClient::fileChunkSending(UInt8 mark, char *data, size_t dataSize) { +void PrimaryClient::fileChunkSending(UInt8 mark, char *data, size_t dataSize) +{ // ignore } -String PrimaryClient::getSecureInputApp() const { +String PrimaryClient::getSecureInputApp() const +{ return m_screen->getSecureInputApp(); } -void PrimaryClient::secureInputNotification(const String &app) const { +void PrimaryClient::secureInputNotification(const String &app) const +{ if (app != "unknown") { AppUtil::instance().showNotification( - "The client keyboards may stop working.", - "'Secure input' enabled by " + app + - ". " - "Close " + - app + " to continue using keyboards on the clients."); + "The client keyboards may stop working.", "'Secure input' enabled by " + app + + ". " + "Close " + + app + " to continue using keyboards on the clients." + ); } else { AppUtil::instance().showNotification( - "The client keyboards may stop working.", - "'Secure input' enabled by an application. " - "Close the application to continue using keyboards on the clients."); + "The client keyboards may stop working.", "'Secure input' enabled by an application. " + "Close the application to continue using keyboards on the clients." + ); } } -void PrimaryClient::resetOptions() { m_screen->resetOptions(); } +void PrimaryClient::resetOptions() +{ + m_screen->resetOptions(); +} -void PrimaryClient::setOptions(const OptionsList &options) { +void PrimaryClient::setOptions(const OptionsList &options) +{ m_screen->setOptions(options); } diff --git a/src/lib/server/PrimaryClient.h b/src/lib/server/PrimaryClient.h index d922ebae2..dfab74c7f 100644 --- a/src/lib/server/PrimaryClient.h +++ b/src/lib/server/PrimaryClient.h @@ -31,7 +31,8 @@ The primary screen does not have a client associated with it. This class provides a pseudo-client to allow the primary screen to be treated as if it was a client. */ -class PrimaryClient : public BaseClientProxy { +class PrimaryClient : public BaseClientProxy +{ public: /*! \c name is the name of the server and \p screen is primary screen. @@ -40,7 +41,9 @@ public: ~PrimaryClient(); #ifdef TEST_ENV - PrimaryClient() : BaseClientProxy("") {} + PrimaryClient() : BaseClientProxy("") + { + } #endif //! @name manipulators @@ -120,21 +123,17 @@ public: // IScreen overrides void *getEventTarget() const override; bool getClipboard(ClipboardID id, IClipboard *) const override; - void - getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const override; + void getShape(SInt32 &x, SInt32 &y, SInt32 &width, SInt32 &height) const override; void getCursorPos(SInt32 &x, SInt32 &y) const override; // IClient overrides - void enter( - SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, - bool forScreensaver) override; + void enter(SInt32 xAbs, SInt32 yAbs, UInt32 seqNum, KeyModifierMask mask, bool forScreensaver) override; bool leave() override; void setClipboard(ClipboardID, const IClipboard *) override; void grabClipboard(ClipboardID) override; void setClipboardDirty(ClipboardID, bool) override; void keyDown(KeyID, KeyModifierMask, KeyButton, const String &) override; - void keyRepeat( - KeyID, KeyModifierMask, SInt32 count, KeyButton, const String &) override; + void keyRepeat(KeyID, KeyModifierMask, SInt32 count, KeyButton, const String &) override; void keyUp(KeyID, KeyModifierMask, KeyButton) override; void mouseDown(ButtonID) override; void mouseUp(ButtonID) override; @@ -149,8 +148,14 @@ public: String getSecureInputApp() const override; void secureInputNotification(const String &app) const override; - deskflow::IStream *getStream() const override { return nullptr; } - bool isPrimary() const override { return true; } + deskflow::IStream *getStream() const override + { + return nullptr; + } + bool isPrimary() const override + { + return true; + } private: deskflow::Screen *m_screen; diff --git a/src/lib/server/Server.cpp b/src/lib/server/Server.cpp index 6300028c4..8e79c03fd 100644 --- a/src/lib/server/Server.cpp +++ b/src/lib/server/Server.cpp @@ -53,9 +53,9 @@ using namespace deskflow::server; // Server::Server( - ServerConfig &config, PrimaryClient *primaryClient, - deskflow::Screen *screen, IEventQueue *events, - deskflow::ServerArgs const &args) + ServerConfig &config, PrimaryClient *primaryClient, deskflow::Screen *screen, IEventQueue *events, + deskflow::ServerArgs const &args +) : m_mock(false), m_primaryClient(primaryClient), m_active(primaryClient), @@ -91,7 +91,8 @@ Server::Server( m_maximumClipboardSize(INT_MAX), m_sendDragInfoThread(nullptr), m_waitDragInfoThread(true), - m_args(args) { + m_args(args) +{ // must have a primary client and it must have a canonical name assert(m_primaryClient != NULL); assert(config.isScreen(primaryClient->getName())); @@ -112,74 +113,79 @@ Server::Server( } // install event handlers + m_events->adoptHandler(Event::kTimer, this, new TMethodEventJob(this, &Server::handleSwitchWaitTimeout)); m_events->adoptHandler( - Event::kTimer, this, - new TMethodEventJob(this, &Server::handleSwitchWaitTimeout)); + m_events->forIKeyState().keyDown(), m_inputFilter, new TMethodEventJob(this, &Server::handleKeyDownEvent) + ); m_events->adoptHandler( - m_events->forIKeyState().keyDown(), m_inputFilter, - new TMethodEventJob(this, &Server::handleKeyDownEvent)); - m_events->adoptHandler( - m_events->forIKeyState().keyUp(), m_inputFilter, - new TMethodEventJob(this, &Server::handleKeyUpEvent)); + m_events->forIKeyState().keyUp(), m_inputFilter, new TMethodEventJob(this, &Server::handleKeyUpEvent) + ); m_events->adoptHandler( m_events->forIKeyState().keyRepeat(), m_inputFilter, - new TMethodEventJob(this, &Server::handleKeyRepeatEvent)); + new TMethodEventJob(this, &Server::handleKeyRepeatEvent) + ); m_events->adoptHandler( m_events->forIPrimaryScreen().buttonDown(), m_inputFilter, - new TMethodEventJob(this, &Server::handleButtonDownEvent)); + new TMethodEventJob(this, &Server::handleButtonDownEvent) + ); m_events->adoptHandler( m_events->forIPrimaryScreen().buttonUp(), m_inputFilter, - new TMethodEventJob(this, &Server::handleButtonUpEvent)); + new TMethodEventJob(this, &Server::handleButtonUpEvent) + ); m_events->adoptHandler( - m_events->forIPrimaryScreen().motionOnPrimary(), - m_primaryClient->getEventTarget(), - new TMethodEventJob(this, &Server::handleMotionPrimaryEvent)); + m_events->forIPrimaryScreen().motionOnPrimary(), m_primaryClient->getEventTarget(), + new TMethodEventJob(this, &Server::handleMotionPrimaryEvent) + ); m_events->adoptHandler( - m_events->forIPrimaryScreen().motionOnSecondary(), - m_primaryClient->getEventTarget(), - new TMethodEventJob(this, &Server::handleMotionSecondaryEvent)); + m_events->forIPrimaryScreen().motionOnSecondary(), m_primaryClient->getEventTarget(), + new TMethodEventJob(this, &Server::handleMotionSecondaryEvent) + ); m_events->adoptHandler( m_events->forIPrimaryScreen().wheel(), m_primaryClient->getEventTarget(), - new TMethodEventJob(this, &Server::handleWheelEvent)); + new TMethodEventJob(this, &Server::handleWheelEvent) + ); m_events->adoptHandler( - m_events->forIPrimaryScreen().screensaverActivated(), - m_primaryClient->getEventTarget(), - new TMethodEventJob( - this, &Server::handleScreensaverActivatedEvent)); + m_events->forIPrimaryScreen().screensaverActivated(), m_primaryClient->getEventTarget(), + new TMethodEventJob(this, &Server::handleScreensaverActivatedEvent) + ); m_events->adoptHandler( - m_events->forIPrimaryScreen().screensaverDeactivated(), - m_primaryClient->getEventTarget(), - new TMethodEventJob( - this, &Server::handleScreensaverDeactivatedEvent)); + m_events->forIPrimaryScreen().screensaverDeactivated(), m_primaryClient->getEventTarget(), + new TMethodEventJob(this, &Server::handleScreensaverDeactivatedEvent) + ); m_events->adoptHandler( m_events->forServer().switchToScreen(), m_inputFilter, - new TMethodEventJob(this, &Server::handleSwitchToScreenEvent)); + new TMethodEventJob(this, &Server::handleSwitchToScreenEvent) + ); m_events->adoptHandler( m_events->forServer().switchInDirection(), m_inputFilter, - new TMethodEventJob(this, &Server::handleSwitchInDirectionEvent)); + new TMethodEventJob(this, &Server::handleSwitchInDirectionEvent) + ); m_events->adoptHandler( m_events->forServer().keyboardBroadcast(), m_inputFilter, - new TMethodEventJob(this, &Server::handleKeyboardBroadcastEvent)); + new TMethodEventJob(this, &Server::handleKeyboardBroadcastEvent) + ); m_events->adoptHandler( m_events->forServer().lockCursorToScreen(), m_inputFilter, - new TMethodEventJob( - this, &Server::handleLockCursorToScreenEvent)); + new TMethodEventJob(this, &Server::handleLockCursorToScreenEvent) + ); m_events->adoptHandler( m_events->forIPrimaryScreen().fakeInputBegin(), m_inputFilter, - new TMethodEventJob(this, &Server::handleFakeInputBeginEvent)); + new TMethodEventJob(this, &Server::handleFakeInputBeginEvent) + ); m_events->adoptHandler( m_events->forIPrimaryScreen().fakeInputEnd(), m_inputFilter, - new TMethodEventJob(this, &Server::handleFakeInputEndEvent)); + new TMethodEventJob(this, &Server::handleFakeInputEndEvent) + ); if (m_args.m_enableDragDrop) { m_events->adoptHandler( m_events->forFile().fileChunkSending(), this, - new TMethodEventJob( - this, &Server::handleFileChunkSendingEvent)); + new TMethodEventJob(this, &Server::handleFileChunkSendingEvent) + ); m_events->adoptHandler( m_events->forFile().fileRecieveCompleted(), this, - new TMethodEventJob( - this, &Server::handleFileRecieveCompletedEvent)); + new TMethodEventJob(this, &Server::handleFileRecieveCompletedEvent) + ); } // add connection @@ -200,7 +206,8 @@ Server::Server( } } -Server::~Server() { +Server::~Server() +{ if (m_mock) { return; } @@ -209,28 +216,15 @@ Server::~Server() { m_events->removeHandler(m_events->forIKeyState().keyDown(), m_inputFilter); m_events->removeHandler(m_events->forIKeyState().keyUp(), m_inputFilter); m_events->removeHandler(m_events->forIKeyState().keyRepeat(), m_inputFilter); - m_events->removeHandler( - m_events->forIPrimaryScreen().buttonDown(), m_inputFilter); - m_events->removeHandler( - m_events->forIPrimaryScreen().buttonUp(), m_inputFilter); - m_events->removeHandler( - m_events->forIPrimaryScreen().motionOnPrimary(), - m_primaryClient->getEventTarget()); - m_events->removeHandler( - m_events->forIPrimaryScreen().motionOnSecondary(), - m_primaryClient->getEventTarget()); - m_events->removeHandler( - m_events->forIPrimaryScreen().wheel(), m_primaryClient->getEventTarget()); - m_events->removeHandler( - m_events->forIPrimaryScreen().screensaverActivated(), - m_primaryClient->getEventTarget()); - m_events->removeHandler( - m_events->forIPrimaryScreen().screensaverDeactivated(), - m_primaryClient->getEventTarget()); - m_events->removeHandler( - m_events->forIPrimaryScreen().fakeInputBegin(), m_inputFilter); - m_events->removeHandler( - m_events->forIPrimaryScreen().fakeInputEnd(), m_inputFilter); + m_events->removeHandler(m_events->forIPrimaryScreen().buttonDown(), m_inputFilter); + m_events->removeHandler(m_events->forIPrimaryScreen().buttonUp(), m_inputFilter); + m_events->removeHandler(m_events->forIPrimaryScreen().motionOnPrimary(), m_primaryClient->getEventTarget()); + m_events->removeHandler(m_events->forIPrimaryScreen().motionOnSecondary(), m_primaryClient->getEventTarget()); + m_events->removeHandler(m_events->forIPrimaryScreen().wheel(), m_primaryClient->getEventTarget()); + m_events->removeHandler(m_events->forIPrimaryScreen().screensaverActivated(), m_primaryClient->getEventTarget()); + m_events->removeHandler(m_events->forIPrimaryScreen().screensaverDeactivated(), m_primaryClient->getEventTarget()); + m_events->removeHandler(m_events->forIPrimaryScreen().fakeInputBegin(), m_inputFilter); + m_events->removeHandler(m_events->forIPrimaryScreen().fakeInputEnd(), m_inputFilter); m_events->removeHandler(Event::kTimer, this); stopSwitch(); @@ -241,8 +235,7 @@ Server::~Server() { LOG((CLOG_ERR "failed to disconnect: %s", e.what())); } - for (OldClients::iterator index = m_oldClients.begin(); - index != m_oldClients.end(); ++index) { + for (OldClients::iterator index = m_oldClients.begin(); index != m_oldClients.end(); ++index) { BaseClientProxy *client = index->first; m_events->deleteTimer(index->second); m_events->removeHandler(Event::kTimer, client); @@ -258,7 +251,8 @@ Server::~Server() { removeClient(m_primaryClient); } -bool Server::setConfig(const ServerConfig &config) { +bool Server::setConfig(const ServerConfig &config) +{ // refuse configuration if it doesn't include the primary screen if (!config.isScreen(m_primaryClient->getName())) { return false; @@ -279,8 +273,7 @@ bool Server::setConfig(const ServerConfig &config) { // configured a LockCursorToScreenAction then we don't add // ScrollLock as a hotkey. if (!m_disableLockToScreen && !m_config->hasLockToScreenAction()) { - IPlatformScreen::KeyInfo *key = - IPlatformScreen::KeyInfo::alloc(kKeyScrollLock, 0, 0, 0); + IPlatformScreen::KeyInfo *key = IPlatformScreen::KeyInfo::alloc(kKeyScrollLock, 0, 0, 0); InputFilter::Rule rule(new InputFilter::KeystrokeCondition(m_events, key)); rule.adoptAction(new InputFilter::LockCursorToScreenAction(m_events), true); m_inputFilter->addFilterRule(rule); @@ -290,8 +283,7 @@ bool Server::setConfig(const ServerConfig &config) { m_primaryClient->reconfigure(getActivePrimarySides()); // tell all (connected) clients about current options - for (ClientList::const_iterator index = m_clients.begin(); - index != m_clients.end(); ++index) { + for (ClientList::const_iterator index = m_clients.begin(); index != m_clients.end(); ++index) { BaseClientProxy *client = index->second; sendOptions(client); } @@ -299,20 +291,19 @@ bool Server::setConfig(const ServerConfig &config) { return true; } -void Server::adoptClient(BaseClientProxy *client) { +void Server::adoptClient(BaseClientProxy *client) +{ assert(client != NULL); // watch for client disconnection m_events->adoptHandler( m_events->forClientProxy().disconnected(), client, - new TMethodEventJob( - this, &Server::handleClientDisconnected, client)); + new TMethodEventJob(this, &Server::handleClientDisconnected, client) + ); // name must be in our configuration if (!m_config->isScreen(client->getName())) { - LOG( - (CLOG_WARN "unrecognised client name \"%s\", check server config", - client->getName().c_str())); + LOG((CLOG_WARN "unrecognised client name \"%s\", check server config", client->getName().c_str())); closeClient(client, kMsgEUnknown); return; } @@ -320,9 +311,7 @@ void Server::adoptClient(BaseClientProxy *client) { // add client to client list if (!addClient(client)) { // can only have one screen with a given name at any given time - LOG( - (CLOG_WARN "a client with name \"%s\" is already connected", - getName(client).c_str())); + LOG((CLOG_WARN "a client with name \"%s\" is already connected", getName(client).c_str())); closeClient(client, kMsgEBusy); return; } @@ -337,14 +326,12 @@ void Server::adoptClient(BaseClientProxy *client) { } // send notification - Server::ScreenConnectedInfo *info = - new Server::ScreenConnectedInfo(getName(client)); - m_events->addEvent(Event( - m_events->forServer().connected(), m_primaryClient->getEventTarget(), - info)); + Server::ScreenConnectedInfo *info = new Server::ScreenConnectedInfo(getName(client)); + m_events->addEvent(Event(m_events->forServer().connected(), m_primaryClient->getEventTarget(), info)); } -void Server::disconnect() { +void Server::disconnect() +{ // close all secondary clients if (m_clients.size() > 1 || !m_oldClients.empty()) { Config emptyConfig(m_events); @@ -354,17 +341,21 @@ void Server::disconnect() { } } -UInt32 Server::getNumClients() const { return (SInt32)m_clients.size(); } +UInt32 Server::getNumClients() const +{ + return (SInt32)m_clients.size(); +} -void Server::getClients(std::vector &list) const { +void Server::getClients(std::vector &list) const +{ list.clear(); - for (ClientList::const_iterator index = m_clients.begin(); - index != m_clients.end(); ++index) { + for (ClientList::const_iterator index = m_clients.begin(); index != m_clients.end(); ++index) { list.push_back(index->first); } } -String Server::getName(const BaseClientProxy *client) const { +String Server::getName(const BaseClientProxy *client) const +{ String name = m_config->getCanonicalName(client->getName()); if (name.empty()) { name = client->getName(); @@ -372,7 +363,8 @@ String Server::getName(const BaseClientProxy *client) const { return name; } -UInt32 Server::getActivePrimarySides() const { +UInt32 Server::getActivePrimarySides() const +{ UInt32 sides = 0; if (!isLockedToScreenServer()) { if (hasAnyNeighbor(m_primaryClient, kLeft)) { @@ -391,12 +383,14 @@ UInt32 Server::getActivePrimarySides() const { return sides; } -bool Server::isLockedToScreenServer() const { +bool Server::isLockedToScreenServer() const +{ // locked if scroll-lock is toggled on return m_lockedToScreen; } -bool Server::isLockedToScreen() const { +bool Server::isLockedToScreen() const +{ if (m_disableLockToScreen) { return false; } @@ -416,7 +410,8 @@ bool Server::isLockedToScreen() const { return false; } -SInt32 Server::getJumpZoneSize(BaseClientProxy *client) const { +SInt32 Server::getJumpZoneSize(BaseClientProxy *client) const +{ if (client == m_primaryClient) { return m_primaryClient->getJumpZoneSize(); } else { @@ -424,8 +419,8 @@ SInt32 Server::getJumpZoneSize(BaseClientProxy *client) const { } } -void Server::switchScreen( - BaseClientProxy *dst, SInt32 x, SInt32 y, bool forScreensaver) { +void Server::switchScreen(BaseClientProxy *dst, SInt32 x, SInt32 y, bool forScreensaver) +{ assert(dst != NULL); SInt32 dx, dy, dw, dh; @@ -438,29 +433,31 @@ void Server::switchScreen( if (x < dx) { LOG_WARN( "on switch, x (%d) is less than the left boundary dx (%d)", // - x, dx); + x, dx + ); } if (y < dy) { LOG_WARN( "on switch, y (%d) is less than the top boundary dy (%d)", // - y, dy); + y, dy + ); } if (x >= dx + dw) { LOG_WARN( "on switch, x (%d) exceeds the right boundary (dx + width = %d)", // - x, dx + dw); + x, dx + dw + ); } if (y >= dy + dh) { LOG_WARN( "on switch, y (%d) exceeds the bottom boundary (dy + height = %d)", // - y, dy + dh); + y, dy + dh + ); } assert(m_active != NULL); - LOG( - (CLOG_INFO "switch from \"%s\" to \"%s\" at %d,%d", - getName(m_active).c_str(), getName(dst).c_str(), x, y)); + LOG((CLOG_INFO "switch from \"%s\" to \"%s\" at %d,%d", getName(m_active).c_str(), getName(dst).c_str(), x, y)); // stop waiting to switch stopSwitch(); @@ -514,31 +511,28 @@ void Server::switchScreen( ++m_seqNum; // enter new screen - m_active->enter( - x, y, m_seqNum, m_primaryClient->getToggleMask(), forScreensaver); + m_active->enter(x, y, m_seqNum, m_primaryClient->getToggleMask(), forScreensaver); if (m_enableClipboard) { // send the clipboard data to new active screen for (ClipboardID id = 0; id < kClipboardEnd; ++id) { // Hackity hackity hack - if (m_clipboards[id].m_clipboard.marshall().size() > - (m_maximumClipboardSize * 1024)) { + if (m_clipboards[id].m_clipboard.marshall().size() > (m_maximumClipboardSize * 1024)) { continue; } m_active->setClipboard(id, &m_clipboards[id].m_clipboard); } } - Server::SwitchToScreenInfo *info = - Server::SwitchToScreenInfo::alloc(m_active->getName()); - m_events->addEvent( - Event(m_events->forServer().screenSwitched(), this, info)); + Server::SwitchToScreenInfo *info = Server::SwitchToScreenInfo::alloc(m_active->getName()); + m_events->addEvent(Event(m_events->forServer().screenSwitched(), this, info)); } else { m_active->mouseMove(x, y); } } -void Server::jumpToScreen(BaseClientProxy *newScreen) { +void Server::jumpToScreen(BaseClientProxy *newScreen) +{ assert(newScreen != NULL); // record the current cursor position on the active screen @@ -551,8 +545,8 @@ void Server::jumpToScreen(BaseClientProxy *newScreen) { switchScreen(newScreen, x, y, false); } -float Server::mapToFraction( - BaseClientProxy *client, EDirection dir, SInt32 x, SInt32 y) const { +float Server::mapToFraction(BaseClientProxy *client, EDirection dir, SInt32 x, SInt32 y) const +{ SInt32 sx, sy, sw, sh; client->getShape(sx, sy, sw, sh); switch (dir) { @@ -571,9 +565,8 @@ float Server::mapToFraction( return 0.0f; } -void Server::mapToPixel( - BaseClientProxy *client, EDirection dir, float f, SInt32 &x, - SInt32 &y) const { +void Server::mapToPixel(BaseClientProxy *client, EDirection dir, float f, SInt32 &x, SInt32 &y) const +{ SInt32 sx, sy, sw, sh; client->getShape(sx, sy, sw, sh); switch (dir) { @@ -593,14 +586,15 @@ void Server::mapToPixel( } } -bool Server::hasAnyNeighbor(BaseClientProxy *client, EDirection dir) const { +bool Server::hasAnyNeighbor(BaseClientProxy *client, EDirection dir) const +{ assert(client != NULL); return m_config->hasNeighbor(getName(client), dir); } -BaseClientProxy *Server::getNeighbor( - BaseClientProxy *src, EDirection dir, SInt32 &x, SInt32 &y) const { +BaseClientProxy *Server::getNeighbor(BaseClientProxy *src, EDirection dir, SInt32 &x, SInt32 &y) const +{ // note -- must be locked on entry assert(src != NULL); @@ -608,9 +602,7 @@ BaseClientProxy *Server::getNeighbor( // get source screen name String srcName = getName(src); assert(!srcName.empty()); - LOG( - (CLOG_DEBUG2 "find neighbor on %s of \"%s\"", Config::dirName(dir), - srcName.c_str())); + LOG((CLOG_DEBUG2 "find neighbor on %s of \"%s\"", Config::dirName(dir), srcName.c_str())); // convert position to fraction float t = mapToFraction(src, dir, x, y); @@ -625,9 +617,7 @@ BaseClientProxy *Server::getNeighbor( // progress in this direction. since we haven't found a // connected neighbor we return NULL. if (dstName.empty()) { - LOG( - (CLOG_DEBUG2 "no neighbor on %s of \"%s\"", Config::dirName(dir), - srcName.c_str())); + LOG((CLOG_DEBUG2 "no neighbor on %s of \"%s\"", Config::dirName(dir), srcName.c_str())); return NULL; } @@ -635,17 +625,13 @@ BaseClientProxy *Server::getNeighbor( // ready then we can stop. ClientList::const_iterator index = m_clients.find(dstName); if (index != m_clients.end()) { - LOG( - (CLOG_DEBUG2 "\"%s\" is on %s of \"%s\" at %f", dstName.c_str(), - Config::dirName(dir), srcName.c_str(), t)); + LOG((CLOG_DEBUG2 "\"%s\" is on %s of \"%s\" at %f", dstName.c_str(), Config::dirName(dir), srcName.c_str(), t)); mapToPixel(index->second, dir, tTmp, x, y); return index->second; } // skip over unconnected screen - LOG( - (CLOG_DEBUG2 "ignored \"%s\" on %s of \"%s\"", dstName.c_str(), - Config::dirName(dir), srcName.c_str())); + LOG((CLOG_DEBUG2 "ignored \"%s\" on %s of \"%s\"", dstName.c_str(), Config::dirName(dir), srcName.c_str())); srcName = dstName; // use position on skipped screen @@ -653,8 +639,8 @@ BaseClientProxy *Server::getNeighbor( } } -BaseClientProxy *Server::mapToNeighbor( - BaseClientProxy *src, EDirection srcSide, SInt32 &x, SInt32 &y) const { +BaseClientProxy *Server::mapToNeighbor(BaseClientProxy *src, EDirection srcSide, SInt32 &x, SInt32 &y) const +{ // note -- must be locked on entry assert(src != NULL); @@ -758,8 +744,8 @@ BaseClientProxy *Server::mapToNeighbor( return dst; } -void Server::avoidJumpZone( - BaseClientProxy *dst, EDirection dir, SInt32 &x, SInt32 &y) const { +void Server::avoidJumpZone(BaseClientProxy *dst, EDirection dir, SInt32 &x, SInt32 &y) const +{ // we only need to avoid jump zones on the primary screen if (dst != m_primaryClient) { return; @@ -776,8 +762,7 @@ void Server::avoidJumpZone( // don't need to move inwards because that side can't provoke a jump. switch (dir) { case kLeft: - if (!m_config->getNeighbor(dstName, kRight, t, NULL).empty() && - x > dx + dw - 1 - z) + if (!m_config->getNeighbor(dstName, kRight, t, NULL).empty() && x > dx + dw - 1 - z) x = dx + dw - 1 - z; break; @@ -787,8 +772,7 @@ void Server::avoidJumpZone( break; case kTop: - if (!m_config->getNeighbor(dstName, kBottom, t, NULL).empty() && - y > dy + dh - 1 - z) + if (!m_config->getNeighbor(dstName, kBottom, t, NULL).empty() && y > dy + dh - 1 - z) y = dy + dh - 1 - z; break; @@ -803,11 +787,10 @@ void Server::avoidJumpZone( } bool Server::isSwitchOkay( - BaseClientProxy *newScreen, EDirection dir, SInt32 x, SInt32 y, - SInt32 xActive, SInt32 yActive) { - LOG( - (CLOG_DEBUG1 "try to leave \"%s\" on %s", getName(m_active).c_str(), - Config::dirName(dir))); + BaseClientProxy *newScreen, EDirection dir, SInt32 x, SInt32 y, SInt32 xActive, SInt32 yActive +) +{ + LOG((CLOG_DEBUG1 "try to leave \"%s\" on %s", getName(m_active).c_str(), Config::dirName(dir))); // is there a neighbor? if (newScreen == NULL) { @@ -853,15 +836,13 @@ bool Server::isSwitchOkay( // are we in a locked corner? first check if screen has the option set // and, if not, check the global options. - const Config::ScreenOptions *options = - m_config->getOptions(getName(m_active)); + const Config::ScreenOptions *options = m_config->getOptions(getName(m_active)); if (options == NULL || options->count(kOptionScreenSwitchCorners) == 0) { options = m_config->getOptions(""); } if (options != NULL && options->count(kOptionScreenSwitchCorners) > 0) { // get corner mask and size - Config::ScreenOptions::const_iterator i = - options->find(kOptionScreenSwitchCorners); + Config::ScreenOptions::const_iterator i = options->find(kOptionScreenSwitchCorners); UInt32 corners = static_cast(i->second); i = options->find(kOptionScreenSwitchCornerSize); SInt32 size = 0; @@ -888,13 +869,9 @@ bool Server::isSwitchOkay( // check for optional needed modifiers KeyModifierMask mods = this->m_primaryClient->getToggleMask(); - if (!preventSwitch && - ((this->m_switchNeedsShift && - ((mods & KeyModifierShift) != KeyModifierShift)) || - (this->m_switchNeedsControl && - ((mods & KeyModifierControl) != KeyModifierControl)) || - (this->m_switchNeedsAlt && - ((mods & KeyModifierAlt) != KeyModifierAlt)))) { + if (!preventSwitch && ((this->m_switchNeedsShift && ((mods & KeyModifierShift) != KeyModifierShift)) || + (this->m_switchNeedsControl && ((mods & KeyModifierControl) != KeyModifierControl)) || + (this->m_switchNeedsAlt && ((mods & KeyModifierAlt) != KeyModifierAlt)))) { LOG((CLOG_DEBUG1 "need modifiers to switch")); preventSwitch = true; stopSwitch(); @@ -903,12 +880,14 @@ bool Server::isSwitchOkay( return !preventSwitch; } -void Server::noSwitch(SInt32 x, SInt32 y) { +void Server::noSwitch(SInt32 x, SInt32 y) +{ armSwitchTwoTap(x, y); stopSwitchWait(); } -void Server::stopSwitch() { +void Server::stopSwitch() +{ if (m_switchScreen != NULL) { m_switchScreen = NULL; m_switchDir = kNoDirection; @@ -917,14 +896,16 @@ void Server::stopSwitch() { } } -void Server::startSwitchTwoTap() { +void Server::startSwitchTwoTap() +{ m_switchTwoTapEngaged = true; m_switchTwoTapArmed = false; m_switchTwoTapTimer.reset(); LOG((CLOG_DEBUG1 "waiting for second tap")); } -void Server::armSwitchTwoTap(SInt32 x, SInt32 y) { +void Server::armSwitchTwoTap(SInt32 x, SInt32 y) +{ if (m_switchTwoTapEngaged) { if (m_switchTwoTapTimer.getTime() > m_switchTwoTapDelay) { // second tap took too long. disengage. @@ -938,8 +919,7 @@ void Server::armSwitchTwoTap(SInt32 x, SInt32 y) { if (tapZone < m_switchTwoTapZone) { tapZone = m_switchTwoTapZone; } - if (x >= ax + tapZone && x < ax + aw - tapZone && y >= ay + tapZone && - y < ay + ah - tapZone) { + if (x >= ax + tapZone && x < ax + aw - tapZone && y >= ay + tapZone && y < ay + ah - tapZone) { // win32 can generate bogus mouse events that appear to // move in the opposite direction that the mouse actually // moved. try to ignore that crap here. @@ -968,22 +948,26 @@ void Server::armSwitchTwoTap(SInt32 x, SInt32 y) { } } -void Server::stopSwitchTwoTap() { +void Server::stopSwitchTwoTap() +{ m_switchTwoTapEngaged = false; m_switchTwoTapArmed = false; } -bool Server::isSwitchTwoTapStarted() const { return m_switchTwoTapEngaged; } - -bool Server::shouldSwitchTwoTap() const { - // this is the second tap if two-tap is armed and this tap - // came fast enough - return ( - m_switchTwoTapArmed && - m_switchTwoTapTimer.getTime() <= m_switchTwoTapDelay); +bool Server::isSwitchTwoTapStarted() const +{ + return m_switchTwoTapEngaged; } -void Server::startSwitchWait(SInt32 x, SInt32 y) { +bool Server::shouldSwitchTwoTap() const +{ + // this is the second tap if two-tap is armed and this tap + // came fast enough + return (m_switchTwoTapArmed && m_switchTwoTapTimer.getTime() <= m_switchTwoTapDelay); +} + +void Server::startSwitchWait(SInt32 x, SInt32 y) +{ stopSwitchWait(); m_switchWaitX = x; m_switchWaitY = y; @@ -991,17 +975,21 @@ void Server::startSwitchWait(SInt32 x, SInt32 y) { LOG((CLOG_DEBUG1 "waiting to switch")); } -void Server::stopSwitchWait() { +void Server::stopSwitchWait() +{ if (m_switchWaitTimer != NULL) { m_events->deleteTimer(m_switchWaitTimer); m_switchWaitTimer = NULL; } } -bool Server::isSwitchWaitStarted() const { return (m_switchWaitTimer != NULL); } +bool Server::isSwitchWaitStarted() const +{ + return (m_switchWaitTimer != NULL); +} -UInt32 Server::getCorner( - BaseClientProxy *client, SInt32 x, SInt32 y, SInt32 size) const { +UInt32 Server::getCorner(BaseClientProxy *client, SInt32 x, SInt32 y, SInt32 size) const +{ assert(client != NULL); // get client screen shape @@ -1049,7 +1037,8 @@ UInt32 Server::getCorner( return kNoCornerMask; } -void Server::stopRelativeMoves() { +void Server::stopRelativeMoves() +{ if (m_relativeMoves && m_active != m_primaryClient) { // warp to the center of the active client so we know where we are SInt32 ax, ay, aw, ah; @@ -1060,14 +1049,13 @@ void Server::stopRelativeMoves() { m_yDelta = 0; m_xDelta2 = 0; m_yDelta2 = 0; - LOG( - (CLOG_DEBUG2 "synchronize move on %s by %d,%d", - getName(m_active).c_str(), m_x, m_y)); + LOG((CLOG_DEBUG2 "synchronize move on %s by %d,%d", getName(m_active).c_str(), m_x, m_y)); m_active->mouseMove(m_x, m_y); } } -void Server::sendOptions(BaseClientProxy *client) const { +void Server::sendOptions(BaseClientProxy *client) const +{ OptionsList optionsList; // look up options for client @@ -1075,8 +1063,7 @@ void Server::sendOptions(BaseClientProxy *client) const { if (options != NULL) { // convert options to a more convenient form for sending optionsList.reserve(2 * options->size()); - for (Config::ScreenOptions::const_iterator index = options->begin(); - index != options->end(); ++index) { + for (Config::ScreenOptions::const_iterator index = options->begin(); index != options->end(); ++index) { optionsList.push_back(index->first); optionsList.push_back(static_cast(index->second)); } @@ -1087,8 +1074,7 @@ void Server::sendOptions(BaseClientProxy *client) const { if (options != NULL) { // convert options to a more convenient form for sending optionsList.reserve(optionsList.size() + 2 * options->size()); - for (Config::ScreenOptions::const_iterator index = options->begin(); - index != options->end(); ++index) { + for (Config::ScreenOptions::const_iterator index = options->begin(); index != options->end(); ++index) { optionsList.push_back(index->first); optionsList.push_back(static_cast(index->second)); } @@ -1099,7 +1085,8 @@ void Server::sendOptions(BaseClientProxy *client) const { client->setOptions(optionsList); } -void Server::processOptions() { +void Server::processOptions() +{ const Config::ScreenOptions *options = m_config->getOptions(""); if (options == NULL) { return; @@ -1110,8 +1097,7 @@ void Server::processOptions() { m_switchNeedsAlt = false; // doesnt' work correct. bool newRelativeMoves = m_relativeMoves; - for (Config::ScreenOptions::const_iterator index = options->begin(); - index != options->end(); ++index) { + for (Config::ScreenOptions::const_iterator index = options->begin(); index != options->end(); ++index) { const OptionID id = index->first; const OptionValue value = index->second; if (id == kOptionScreenSwitchDelay) { @@ -1157,7 +1143,8 @@ void Server::processOptions() { m_relativeMoves = newRelativeMoves; } -void Server::handleShapeChanged(const Event &, void *vclient) { +void Server::handleShapeChanged(const Event &, void *vclient) +{ // ignore events from unknown clients BaseClientProxy *client = static_cast(vclient); if (m_clientSet.count(client) == 0) { @@ -1187,7 +1174,8 @@ void Server::handleShapeChanged(const Event &, void *vclient) { } } -void Server::handleClipboardGrabbed(const Event &event, void *vclient) { +void Server::handleClipboardGrabbed(const Event &event, void *vclient) +{ if (!m_enableClipboard || (m_maximumClipboardSize == 0)) { return; } @@ -1197,25 +1185,21 @@ void Server::handleClipboardGrabbed(const Event &event, void *vclient) { if (m_clientSet.count(grabber) == 0) { return; } - const IScreen::ClipboardInfo *info = - static_cast(event.getData()); + const IScreen::ClipboardInfo *info = static_cast(event.getData()); // ignore grab if sequence number is old. always allow primary // screen to grab. ClipboardInfo &clipboard = m_clipboards[info->m_id]; - if (grabber != m_primaryClient && - info->m_sequenceNumber < clipboard.m_clipboardSeqNum) { - LOG( - (CLOG_INFO "ignored screen \"%s\" grab of clipboard %d", - getName(grabber).c_str(), info->m_id)); + if (grabber != m_primaryClient && info->m_sequenceNumber < clipboard.m_clipboardSeqNum) { + LOG((CLOG_INFO "ignored screen \"%s\" grab of clipboard %d", getName(grabber).c_str(), info->m_id)); return; } // mark screen as owning clipboard LOG( - (CLOG_INFO "screen \"%s\" grabbed clipboard %d from \"%s\"", - getName(grabber).c_str(), info->m_id, - clipboard.m_clipboardOwner.c_str())); + (CLOG_INFO "screen \"%s\" grabbed clipboard %d from \"%s\"", getName(grabber).c_str(), info->m_id, + clipboard.m_clipboardOwner.c_str()) + ); clipboard.m_clipboardOwner = getName(grabber); clipboard.m_clipboardSeqNum = info->m_sequenceNumber; @@ -1228,8 +1212,7 @@ void Server::handleClipboardGrabbed(const Event &event, void *vclient) { // tell all other screens to take ownership of clipboard. tell the // grabber that it's clipboard isn't dirty. - for (ClientList::iterator index = m_clients.begin(); index != m_clients.end(); - ++index) { + for (ClientList::iterator index = m_clients.begin(); index != m_clients.end(); ++index) { BaseClientProxy *client = index->second; if (client == grabber) { client->setClipboardDirty(info->m_id, false); @@ -1242,82 +1225,84 @@ void Server::handleClipboardGrabbed(const Event &event, void *vclient) { LOG((CLOG_INFO "clipboard grabbed, but we are already changed active " "screen. Resend clipboard data")); for (ClipboardID id = 0; id < kClipboardEnd; ++id) { - onClipboardChanged( - m_primaryClient, id, m_clipboards[id].m_clipboardSeqNum); + onClipboardChanged(m_primaryClient, id, m_clipboards[id].m_clipboardSeqNum); } } } -void Server::handleClipboardChanged(const Event &event, void *vclient) { +void Server::handleClipboardChanged(const Event &event, void *vclient) +{ // ignore events from unknown clients BaseClientProxy *sender = static_cast(vclient); if (m_clientSet.count(sender) == 0) { return; } - const IScreen::ClipboardInfo *info = - static_cast(event.getData()); + const IScreen::ClipboardInfo *info = static_cast(event.getData()); onClipboardChanged(sender, info->m_id, info->m_sequenceNumber); } -void Server::handleKeyDownEvent(const Event &event, void *) { - IPlatformScreen::KeyInfo *info = - static_cast(event.getData()); +void Server::handleKeyDownEvent(const Event &event, void *) +{ + IPlatformScreen::KeyInfo *info = static_cast(event.getData()); auto lang = AppUtil::instance().getCurrentLanguageCode(); onKeyDown(info->m_key, info->m_mask, info->m_button, lang, info->m_screens); } -void Server::handleKeyUpEvent(const Event &event, void *) { - IPlatformScreen::KeyInfo *info = - static_cast(event.getData()); +void Server::handleKeyUpEvent(const Event &event, void *) +{ + IPlatformScreen::KeyInfo *info = static_cast(event.getData()); onKeyUp(info->m_key, info->m_mask, info->m_button, info->m_screens); } -void Server::handleKeyRepeatEvent(const Event &event, void *) { - IPlatformScreen::KeyInfo *info = - static_cast(event.getData()); +void Server::handleKeyRepeatEvent(const Event &event, void *) +{ + IPlatformScreen::KeyInfo *info = static_cast(event.getData()); auto lang = AppUtil::instance().getCurrentLanguageCode(); onKeyRepeat(info->m_key, info->m_mask, info->m_count, info->m_button, lang); } -void Server::handleButtonDownEvent(const Event &event, void *) { - IPlatformScreen::ButtonInfo *info = - static_cast(event.getData()); +void Server::handleButtonDownEvent(const Event &event, void *) +{ + IPlatformScreen::ButtonInfo *info = static_cast(event.getData()); onMouseDown(info->m_button); } -void Server::handleButtonUpEvent(const Event &event, void *) { - IPlatformScreen::ButtonInfo *info = - static_cast(event.getData()); +void Server::handleButtonUpEvent(const Event &event, void *) +{ + IPlatformScreen::ButtonInfo *info = static_cast(event.getData()); onMouseUp(info->m_button); } -void Server::handleMotionPrimaryEvent(const Event &event, void *) { - IPlatformScreen::MotionInfo *info = - static_cast(event.getData()); +void Server::handleMotionPrimaryEvent(const Event &event, void *) +{ + IPlatformScreen::MotionInfo *info = static_cast(event.getData()); onMouseMovePrimary(info->m_x, info->m_y); } -void Server::handleMotionSecondaryEvent(const Event &event, void *) { - IPlatformScreen::MotionInfo *info = - static_cast(event.getData()); +void Server::handleMotionSecondaryEvent(const Event &event, void *) +{ + IPlatformScreen::MotionInfo *info = static_cast(event.getData()); onMouseMoveSecondary(info->m_x, info->m_y); } -void Server::handleWheelEvent(const Event &event, void *) { - IPlatformScreen::WheelInfo *info = - static_cast(event.getData()); +void Server::handleWheelEvent(const Event &event, void *) +{ + IPlatformScreen::WheelInfo *info = static_cast(event.getData()); onMouseWheel(info->m_xDelta, info->m_yDelta); } -void Server::handleScreensaverActivatedEvent(const Event &, void *) { +void Server::handleScreensaverActivatedEvent(const Event &, void *) +{ onScreensaver(true); } -void Server::handleScreensaverDeactivatedEvent(const Event &, void *) { +void Server::handleScreensaverDeactivatedEvent(const Event &, void *) +{ onScreensaver(false); } -void Server::handleSwitchWaitTimeout(const Event &, void *) { +void Server::handleSwitchWaitTimeout(const Event &, void *) +{ // ignore if mouse is locked to screen if (isLockedToScreen()) { LOG((CLOG_DEBUG1 "locked to screen")); @@ -1329,7 +1314,8 @@ void Server::handleSwitchWaitTimeout(const Event &, void *) { switchScreen(m_switchScreen, m_switchWaitX, m_switchWaitY, false); } -void Server::handleClientDisconnected(const Event &, void *vclient) { +void Server::handleClientDisconnected(const Event &, void *vclient) +{ // client has disconnected. it might be an old client or an // active client. we don't care so just handle it both ways. BaseClientProxy *client = static_cast(vclient); @@ -1340,18 +1326,18 @@ void Server::handleClientDisconnected(const Event &, void *vclient) { m_clientListener->restart(); } -void Server::handleClientCloseTimeout(const Event &, void *vclient) { +void Server::handleClientCloseTimeout(const Event &, void *vclient) +{ // client took too long to disconnect. just dump it. BaseClientProxy *client = static_cast(vclient); - LOG( - (CLOG_NOTE "forced disconnection of client \"%s\"", - getName(client).c_str())); + LOG((CLOG_NOTE "forced disconnection of client \"%s\"", getName(client).c_str())); removeOldClient(client); delete client; } -void Server::handleSwitchToScreenEvent(const Event &event, void *) { +void Server::handleSwitchToScreenEvent(const Event &event, void *) +{ SwitchToScreenInfo *info = static_cast(event.getData()); ClientList::const_iterator index = m_clients.find(info->m_screen); @@ -1362,9 +1348,9 @@ void Server::handleSwitchToScreenEvent(const Event &event, void *) { } } -void Server::handleSwitchInDirectionEvent(const Event &event, void *) { - SwitchInDirectionInfo *info = - static_cast(event.getData()); +void Server::handleSwitchInDirectionEvent(const Event &event, void *) +{ + SwitchInDirectionInfo *info = static_cast(event.getData()); // jump to screen in chosen direction from center of this screen SInt32 x = m_x, y = m_y; @@ -1376,7 +1362,8 @@ void Server::handleSwitchInDirectionEvent(const Event &event, void *) { } } -void Server::handleKeyboardBroadcastEvent(const Event &event, void *) { +void Server::handleKeyboardBroadcastEvent(const Event &event, void *) +{ KeyboardBroadcastInfo *info = (KeyboardBroadcastInfo *)event.getData(); // choose new state @@ -1397,18 +1384,18 @@ void Server::handleKeyboardBroadcastEvent(const Event &event, void *) { } // enter new state - if (newState != m_keyboardBroadcasting || - info->m_screens != m_keyboardBroadcastingScreens) { + if (newState != m_keyboardBroadcasting || info->m_screens != m_keyboardBroadcastingScreens) { m_keyboardBroadcasting = newState; m_keyboardBroadcastingScreens = info->m_screens; LOG( - (CLOG_DEBUG "keyboard broadcasting %s: %s", - m_keyboardBroadcasting ? "on" : "off", - m_keyboardBroadcastingScreens.c_str())); + (CLOG_DEBUG "keyboard broadcasting %s: %s", m_keyboardBroadcasting ? "on" : "off", + m_keyboardBroadcastingScreens.c_str()) + ); } } -void Server::handleLockCursorToScreenEvent(const Event &event, void *) { +void Server::handleLockCursorToScreenEvent(const Event &event, void *) +{ LockCursorToScreenInfo *info = (LockCursorToScreenInfo *)event.getData(); // choose new state @@ -1431,9 +1418,7 @@ void Server::handleLockCursorToScreenEvent(const Event &event, void *) { // enter new state if (newState != m_lockedToScreen) { m_lockedToScreen = newState; - LOG( - (CLOG_NOTE "cursor %s current screen", - m_lockedToScreen ? "locked to" : "unlocked from")); + LOG((CLOG_NOTE "cursor %s current screen", m_lockedToScreen ? "locked to" : "unlocked from")); m_primaryClient->reconfigure(getActivePrimarySides()); if (!isLockedToScreenServer()) { @@ -1442,31 +1427,33 @@ void Server::handleLockCursorToScreenEvent(const Event &event, void *) { } } -void Server::handleFakeInputBeginEvent(const Event &, void *) { +void Server::handleFakeInputBeginEvent(const Event &, void *) +{ m_primaryClient->fakeInputBegin(); } -void Server::handleFakeInputEndEvent(const Event &, void *) { +void Server::handleFakeInputEndEvent(const Event &, void *) +{ m_primaryClient->fakeInputEnd(); } -void Server::handleFileChunkSendingEvent(const Event &event, void *) { +void Server::handleFileChunkSendingEvent(const Event &event, void *) +{ onFileChunkSending(event.getDataObject()); } -void Server::handleFileRecieveCompletedEvent(const Event &event, void *) { +void Server::handleFileRecieveCompletedEvent(const Event &event, void *) +{ onFileRecieveCompleted(); } -void Server::onClipboardChanged( - BaseClientProxy *sender, ClipboardID id, UInt32 seqNum) { +void Server::onClipboardChanged(BaseClientProxy *sender, ClipboardID id, UInt32 seqNum) +{ ClipboardInfo &clipboard = m_clipboards[id]; // ignore update if sequence number is old if (seqNum < clipboard.m_clipboardSeqNum) { - LOG(( - CLOG_INFO "ignored screen \"%s\" update of clipboard %d (missequenced)", - getName(sender).c_str(), id)); + LOG((CLOG_INFO "ignored screen \"%s\" update of clipboard %d (missequenced)", getName(sender).c_str(), id)); return; } @@ -1481,27 +1468,24 @@ void Server::onClipboardChanged( LOG( (CLOG_NOTE "not updating clipboard because it's over the size limit " "(%i KB) configured by the server", - m_maximumClipboardSize)); + m_maximumClipboardSize) + ); return; } // ignore if data hasn't changed if (data == clipboard.m_clipboardData) { - LOG( - (CLOG_DEBUG "ignored screen \"%s\" update of clipboard %d (unchanged)", - clipboard.m_clipboardOwner.c_str(), id)); + LOG((CLOG_DEBUG "ignored screen \"%s\" update of clipboard %d (unchanged)", clipboard.m_clipboardOwner.c_str(), id) + ); return; } // got new data - LOG( - (CLOG_INFO "screen \"%s\" updated clipboard %d", - clipboard.m_clipboardOwner.c_str(), id)); + LOG((CLOG_INFO "screen \"%s\" updated clipboard %d", clipboard.m_clipboardOwner.c_str(), id)); clipboard.m_clipboardData = data; // tell all clients except the sender that the clipboard is dirty - for (ClientList::const_iterator index = m_clients.begin(); - index != m_clients.end(); ++index) { + for (ClientList::const_iterator index = m_clients.begin(); index != m_clients.end(); ++index) { BaseClientProxy *client = index->second; client->setClipboardDirty(id, client != sender); } @@ -1510,7 +1494,8 @@ void Server::onClipboardChanged( m_active->setClipboard(id, &clipboard.m_clipboard); } -void Server::onScreensaver(bool activated) { +void Server::onScreensaver(bool activated) +{ LOG((CLOG_DEBUG "onScreenSaver %s", activated ? "activated" : "deactivated")); if (activated) { @@ -1553,19 +1538,15 @@ void Server::onScreensaver(bool activated) { } // send message to all clients - for (ClientList::const_iterator index = m_clients.begin(); - index != m_clients.end(); ++index) { + for (ClientList::const_iterator index = m_clients.begin(); index != m_clients.end(); ++index) { BaseClientProxy *client = index->second; client->screensaver(activated); } } -void Server::onKeyDown( - KeyID id, KeyModifierMask mask, KeyButton button, const String &lang, - const char *screens) { - LOG( - (CLOG_DEBUG1 "onKeyDown id=%d mask=0x%04x button=0x%04x lang=%s", id, - mask, button, lang.c_str())); +void Server::onKeyDown(KeyID id, KeyModifierMask mask, KeyButton button, const String &lang, const char *screens) +{ + LOG((CLOG_DEBUG1 "onKeyDown id=%d mask=0x%04x button=0x%04x lang=%s", id, mask, button, lang.c_str())); assert(m_active != NULL); // relay @@ -1578,8 +1559,7 @@ void Server::onKeyDown( screens = "*"; } } - for (ClientList::const_iterator index = m_clients.begin(); - index != m_clients.end(); ++index) { + for (ClientList::const_iterator index = m_clients.begin(); index != m_clients.end(); ++index) { if (IKeyState::KeyInfo::contains(screens, index->first)) { index->second->keyDown(id, mask, button, lang); } @@ -1587,10 +1567,9 @@ void Server::onKeyDown( } } -void Server::onKeyUp( - KeyID id, KeyModifierMask mask, KeyButton button, const char *screens) { - LOG(( - CLOG_DEBUG1 "onKeyUp id=%d mask=0x%04x button=0x%04x", id, mask, button)); +void Server::onKeyUp(KeyID id, KeyModifierMask mask, KeyButton button, const char *screens) +{ + LOG((CLOG_DEBUG1 "onKeyUp id=%d mask=0x%04x button=0x%04x", id, mask, button)); assert(m_active != NULL); // relay @@ -1603,8 +1582,7 @@ void Server::onKeyUp( screens = "*"; } } - for (ClientList::const_iterator index = m_clients.begin(); - index != m_clients.end(); ++index) { + for (ClientList::const_iterator index = m_clients.begin(); index != m_clients.end(); ++index) { if (IKeyState::KeyInfo::contains(screens, index->first)) { index->second->keyUp(id, mask, button); } @@ -1612,20 +1590,20 @@ void Server::onKeyUp( } } -void Server::onKeyRepeat( - KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, - const String &lang) { +void Server::onKeyRepeat(KeyID id, KeyModifierMask mask, SInt32 count, KeyButton button, const String &lang) +{ LOG( - (CLOG_DEBUG1 - "onKeyRepeat id=%d mask=0x%04x count=%d button=0x%04x lang=\"%s\"", - id, mask, count, button, lang.c_str())); + (CLOG_DEBUG1 "onKeyRepeat id=%d mask=0x%04x count=%d button=0x%04x lang=\"%s\"", id, mask, count, button, + lang.c_str()) + ); assert(m_active != NULL); // relay m_active->keyRepeat(id, mask, count, button, lang); } -void Server::onMouseDown(ButtonID id) { +void Server::onMouseDown(ButtonID id) +{ LOG((CLOG_DEBUG1 "onMouseDown id=%d", id)); assert(m_active != NULL); @@ -1636,7 +1614,8 @@ void Server::onMouseDown(ButtonID id) { m_waitDragInfoThread = true; } -void Server::onMouseUp(ButtonID id) { +void Server::onMouseUp(ButtonID id) +{ LOG((CLOG_DEBUG1 "onMouseUp id=%d", id)); assert(m_active != NULL); @@ -1661,7 +1640,8 @@ void Server::onMouseUp(ButtonID id) { } } -bool Server::onMouseMovePrimary(SInt32 x, SInt32 y) { +bool Server::onMouseMovePrimary(SInt32 x, SInt32 y) +{ LOG((CLOG_DEBUG4 "onMouseMovePrimary %d,%d", x, y)); // mouse move on primary (server's) screen @@ -1740,11 +1720,9 @@ bool Server::onMouseMovePrimary(SInt32 x, SInt32 y) { // should we switch or not? if (isSwitchOkay(newScreen, dir, x, y, xc, yc)) { - if (m_args.m_enableDragDrop && m_screen->isDraggingStarted() && - m_active != newScreen && m_waitDragInfoThread) { + if (m_args.m_enableDragDrop && m_screen->isDraggingStarted() && m_active != newScreen && m_waitDragInfoThread) { if (!m_sendDragInfoThread) { - m_sendDragInfoThread.reset(new Thread(new TMethodJob( - this, &Server::sendDragInfoThread, newScreen))); + m_sendDragInfoThread.reset(new Thread(new TMethodJob(this, &Server::sendDragInfoThread, newScreen))); } return false; @@ -1760,7 +1738,8 @@ bool Server::onMouseMovePrimary(SInt32 x, SInt32 y) { return false; } -void Server::sendDragInfoThread(void *arg) { +void Server::sendDragInfoThread(void *arg) +{ BaseClientProxy *newScreen = static_cast(arg); m_dragFileList.clear(); @@ -1788,7 +1767,8 @@ void Server::sendDragInfoThread(void *arg) { m_sendDragInfoThread.reset(nullptr); } -void Server::sendDragInfo(BaseClientProxy *newScreen) { +void Server::sendDragInfo(BaseClientProxy *newScreen) +{ String infoString; UInt32 fileCount = DragInformation::setupDragInfo(m_dragFileList, infoString); @@ -1800,31 +1780,24 @@ void Server::sendDragInfo(BaseClientProxy *newScreen) { } } -void Server::onMouseMoveSecondary(SInt32 dx, SInt32 dy) { +void Server::onMouseMoveSecondary(SInt32 dx, SInt32 dy) +{ LOG((CLOG_DEBUG2 "onMouseMoveSecondary initial %+d,%+d", dx, dy)); const char *envVal = std::getenv("DESKFLOW_MOUSE_ADJUSTMENT"); if (envVal != nullptr) { try { - double multiplier = std::stod(envVal); // Convert to double - SInt32 adjustedDx = static_cast( - std::round(dx * multiplier)); // Apply multiplier and round + double multiplier = std::stod(envVal); // Convert to double + SInt32 adjustedDx = static_cast(std::round(dx * multiplier)); // Apply multiplier and round SInt32 adjustedDy = static_cast(std::round(dy * multiplier)); - LOG( - (CLOG_DEBUG2 "Adjusted to %+d,%+d using multiplier %.2f", adjustedDx, - adjustedDy, multiplier)); + LOG((CLOG_DEBUG2 "Adjusted to %+d,%+d using multiplier %.2f", adjustedDx, adjustedDy, multiplier)); dx = adjustedDx; // Update dx and dy to adjusted values dy = adjustedDy; } catch (const std::exception &e) { // Log the error message from the exception - LOG(( - CLOG_ERR "Invalid DESKFLOW_MOUSE_ADJUSTMENT value: %s. Exception: %s", - envVal, e.what())); + LOG((CLOG_ERR "Invalid DESKFLOW_MOUSE_ADJUSTMENT value: %s. Exception: %s", envVal, e.what())); } } else { - LOG( - (CLOG_DEBUG1 - "DESKFLOW_MOUSE_ADJUSTMENT not set, using original values %+d,%+d", - dx, dy)); + LOG((CLOG_DEBUG1 "DESKFLOW_MOUSE_ADJUSTMENT not set, using original values %+d,%+d", dx, dy)); } // mouse move on secondary (client's) screen @@ -1841,9 +1814,7 @@ void Server::onMouseMoveSecondary(SInt32 dx, SInt32 dy) { // program on the secondary screen to warp the mouse on us, so we // have no idea where it really is. if (m_relativeMoves && isLockedToScreenServer()) { - LOG( - (CLOG_DEBUG2 "relative move on %s by %d,%d", getName(m_active).c_str(), - dx, dy)); + LOG((CLOG_DEBUG2 "relative move on %s by %d,%d", getName(m_active).c_str(), dx, dy)); m_active->mouseRelativeMove(dx, dy); return; } @@ -1978,15 +1949,14 @@ void Server::onMouseMoveSecondary(SInt32 dx, SInt32 dy) { // warp cursor if it moved. if (m_x != xOld || m_y != yOld) { - LOG( - (CLOG_DEBUG2 "move on %s to %d,%d", getName(m_active).c_str(), m_x, - m_y)); + LOG((CLOG_DEBUG2 "move on %s to %d,%d", getName(m_active).c_str(), m_x, m_y)); m_active->mouseMove(m_x, m_y); } } } -void Server::onMouseWheel(SInt32 xDelta, SInt32 yDelta) { +void Server::onMouseWheel(SInt32 xDelta, SInt32 yDelta) +{ LOG((CLOG_DEBUG1 "onMouseWheel %+d,%+d", xDelta, yDelta)); assert(m_active != NULL); @@ -1994,36 +1964,38 @@ void Server::onMouseWheel(SInt32 xDelta, SInt32 yDelta) { m_active->mouseWheel(xDelta, yDelta); } -void Server::onFileChunkSending(const void *data) { +void Server::onFileChunkSending(const void *data) +{ FileChunk *chunk = static_cast(const_cast(data)); LOG((CLOG_DEBUG1 "sending file chunk")); assert(m_active != NULL); // relay - m_active->fileChunkSending( - chunk->m_chunk[0], &chunk->m_chunk[1], chunk->m_dataSize); + m_active->fileChunkSending(chunk->m_chunk[0], &chunk->m_chunk[1], chunk->m_dataSize); } -void Server::onFileRecieveCompleted() { +void Server::onFileRecieveCompleted() +{ if (isReceivedFileSizeValid()) { auto method = new TMethodJob(this, &Server::writeToDropDirThread); m_writeToDropDirThread.reset(new Thread(method)); } } -void Server::writeToDropDirThread(void *) { +void Server::writeToDropDirThread(void *) +{ LOG((CLOG_DEBUG "starting write to drop dir thread")); while (m_screen->isFakeDraggingStarted()) { ARCH->sleep(.1f); } - DropHelper::writeToDir( - m_screen->getDropTarget(), m_fakeDragFileList, m_receivedFileData); + DropHelper::writeToDir(m_screen->getDropTarget(), m_fakeDragFileList, m_receivedFileData); } -bool Server::addClient(BaseClientProxy *client) { +bool Server::addClient(BaseClientProxy *client) +{ String name = getName(client); if (m_clients.count(name) != 0) { return false; @@ -2032,15 +2004,16 @@ bool Server::addClient(BaseClientProxy *client) { // add event handlers m_events->adoptHandler( m_events->forIScreen().shapeChanged(), client->getEventTarget(), - new TMethodEventJob(this, &Server::handleShapeChanged, client)); + new TMethodEventJob(this, &Server::handleShapeChanged, client) + ); m_events->adoptHandler( m_events->forClipboard().clipboardGrabbed(), client->getEventTarget(), - new TMethodEventJob( - this, &Server::handleClipboardGrabbed, client)); + new TMethodEventJob(this, &Server::handleClipboardGrabbed, client) + ); m_events->adoptHandler( m_events->forClipboard().clipboardChanged(), client->getEventTarget(), - new TMethodEventJob( - this, &Server::handleClipboardChanged, client)); + new TMethodEventJob(this, &Server::handleClipboardChanged, client) + ); // add to list m_clientSet.insert(client); @@ -2057,7 +2030,8 @@ bool Server::addClient(BaseClientProxy *client) { return true; } -bool Server::removeClient(BaseClientProxy *client) { +bool Server::removeClient(BaseClientProxy *client) +{ // return false if not in list ClientSet::iterator i = m_clientSet.find(client); if (i == m_clientSet.end()) { @@ -2065,12 +2039,9 @@ bool Server::removeClient(BaseClientProxy *client) { } // remove event handlers - m_events->removeHandler( - m_events->forIScreen().shapeChanged(), client->getEventTarget()); - m_events->removeHandler( - m_events->forClipboard().clipboardGrabbed(), client->getEventTarget()); - m_events->removeHandler( - m_events->forClipboard().clipboardChanged(), client->getEventTarget()); + m_events->removeHandler(m_events->forIScreen().shapeChanged(), client->getEventTarget()); + m_events->removeHandler(m_events->forClipboard().clipboardGrabbed(), client->getEventTarget()); + m_events->removeHandler(m_events->forClipboard().clipboardChanged(), client->getEventTarget()); // remove from list m_clients.erase(getName(client)); @@ -2079,7 +2050,8 @@ bool Server::removeClient(BaseClientProxy *client) { return true; } -void Server::closeClient(BaseClientProxy *client, const char *msg) { +void Server::closeClient(BaseClientProxy *client, const char *msg) +{ assert(client != m_primaryClient); assert(msg != NULL); @@ -2101,9 +2073,8 @@ void Server::closeClient(BaseClientProxy *client, const char *msg) { double timeout = 5.0; EventQueueTimer *timer = m_events->newOneShotTimer(timeout, NULL); m_events->adoptHandler( - Event::kTimer, timer, - new TMethodEventJob( - this, &Server::handleClientCloseTimeout, client)); + Event::kTimer, timer, new TMethodEventJob(this, &Server::handleClientCloseTimeout, client) + ); // move client to closing list removeClient(client); @@ -2115,13 +2086,13 @@ void Server::closeClient(BaseClientProxy *client, const char *msg) { forceLeaveClient(client); } -void Server::closeClients(const ServerConfig &config) { +void Server::closeClients(const ServerConfig &config) +{ // collect the clients that are connected but are being dropped // from the configuration (or who's canonical name is changing). typedef std::set RemovedClients; RemovedClients removed; - for (ClientList::iterator index = m_clients.begin(); index != m_clients.end(); - ++index) { + for (ClientList::iterator index = m_clients.begin(); index != m_clients.end(); ++index) { if (!config.isCanonicalName(index->first)) { removed.insert(index->second); } @@ -2132,13 +2103,13 @@ void Server::closeClients(const ServerConfig &config) { // now close them. we collect the list then close in two steps // because closeClient() modifies the collection we iterate over. - for (RemovedClients::iterator index = removed.begin(); index != removed.end(); - ++index) { + for (RemovedClients::iterator index = removed.begin(); index != removed.end(); ++index) { closeClient(*index, kMsgCClose); } } -void Server::removeActiveClient(BaseClientProxy *client) { +void Server::removeActiveClient(BaseClientProxy *client) +{ if (removeClient(client)) { forceLeaveClient(client); m_events->removeHandler(m_events->forClientProxy().disconnected(), client); @@ -2148,7 +2119,8 @@ void Server::removeActiveClient(BaseClientProxy *client) { } } -void Server::removeOldClient(BaseClientProxy *client) { +void Server::removeOldClient(BaseClientProxy *client) +{ OldClients::iterator i = m_oldClients.find(client); if (i != m_oldClients.end()) { m_events->removeHandler(m_events->forClientProxy().disconnected(), client); @@ -2161,7 +2133,8 @@ void Server::removeOldClient(BaseClientProxy *client) { } } -void Server::forceLeaveClient(BaseClientProxy *client) { +void Server::forceLeaveClient(BaseClientProxy *client) +{ BaseClientProxy *active = (m_activeSaver != NULL) ? m_activeSaver : m_active; if (active == client) { // record new position (center of primary screen) @@ -2175,8 +2148,9 @@ void Server::forceLeaveClient(BaseClientProxy *client) { // don't notify active screen since it has probably already // disconnected. LOG( - (CLOG_INFO "jump from \"%s\" to \"%s\" at %d,%d", - getName(active).c_str(), getName(m_primaryClient).c_str(), m_x, m_y)); + (CLOG_INFO "jump from \"%s\" to \"%s\" at %d,%d", getName(active).c_str(), getName(m_primaryClient).c_str(), + m_x, m_y) + ); // cut over m_active = m_primaryClient; @@ -2184,8 +2158,7 @@ void Server::forceLeaveClient(BaseClientProxy *client) { // enter new screen (unless we already have because of the // screen saver) if (m_activeSaver == NULL) { - m_primaryClient->enter( - m_x, m_y, m_seqNum, m_primaryClient->getToggleMask(), false); + m_primaryClient->enter(m_x, m_y, m_seqNum, m_primaryClient->getToggleMask(), false); } } @@ -2204,11 +2177,8 @@ void Server::forceLeaveClient(BaseClientProxy *client) { // Server::ClipboardInfo // -Server::ClipboardInfo::ClipboardInfo() - : m_clipboard(), - m_clipboardData(), - m_clipboardOwner(), - m_clipboardSeqNum(0) { +Server::ClipboardInfo::ClipboardInfo() : m_clipboard(), m_clipboardData(), m_clipboardOwner(), m_clipboardSeqNum(0) +{ // do nothing } @@ -2216,10 +2186,9 @@ Server::ClipboardInfo::ClipboardInfo() // Server::LockCursorToScreenInfo // -Server::LockCursorToScreenInfo * -Server::LockCursorToScreenInfo::alloc(State state) { - LockCursorToScreenInfo *info = - (LockCursorToScreenInfo *)malloc(sizeof(LockCursorToScreenInfo)); +Server::LockCursorToScreenInfo *Server::LockCursorToScreenInfo::alloc(State state) +{ + LockCursorToScreenInfo *info = (LockCursorToScreenInfo *)malloc(sizeof(LockCursorToScreenInfo)); info->m_state = state; return info; } @@ -2228,10 +2197,9 @@ Server::LockCursorToScreenInfo::alloc(State state) { // Server::SwitchToScreenInfo // -Server::SwitchToScreenInfo * -Server::SwitchToScreenInfo::alloc(const String &screen) { - SwitchToScreenInfo *info = - (SwitchToScreenInfo *)malloc(sizeof(SwitchToScreenInfo) + screen.size()); +Server::SwitchToScreenInfo *Server::SwitchToScreenInfo::alloc(const String &screen) +{ + SwitchToScreenInfo *info = (SwitchToScreenInfo *)malloc(sizeof(SwitchToScreenInfo) + screen.size()); std::copy(screen.c_str(), screen.c_str() + screen.size() + 1, info->m_screen); return info; } @@ -2240,10 +2208,9 @@ Server::SwitchToScreenInfo::alloc(const String &screen) { // Server::SwitchInDirectionInfo // -Server::SwitchInDirectionInfo * -Server::SwitchInDirectionInfo::alloc(EDirection direction) { - SwitchInDirectionInfo *info = - (SwitchInDirectionInfo *)malloc(sizeof(SwitchInDirectionInfo)); +Server::SwitchInDirectionInfo *Server::SwitchInDirectionInfo::alloc(EDirection direction) +{ + SwitchInDirectionInfo *info = (SwitchInDirectionInfo *)malloc(sizeof(SwitchInDirectionInfo)); info->m_direction = direction; return info; } @@ -2252,32 +2219,34 @@ Server::SwitchInDirectionInfo::alloc(EDirection direction) { // Server::KeyboardBroadcastInfo // -Server::KeyboardBroadcastInfo * -Server::KeyboardBroadcastInfo::alloc(State state) { - KeyboardBroadcastInfo *info = - (KeyboardBroadcastInfo *)malloc(sizeof(KeyboardBroadcastInfo)); +Server::KeyboardBroadcastInfo *Server::KeyboardBroadcastInfo::alloc(State state) +{ + KeyboardBroadcastInfo *info = (KeyboardBroadcastInfo *)malloc(sizeof(KeyboardBroadcastInfo)); info->m_state = state; info->m_screens[0] = '\0'; return info; } -Server::KeyboardBroadcastInfo * -Server::KeyboardBroadcastInfo::alloc(State state, const String &screens) { - KeyboardBroadcastInfo *info = (KeyboardBroadcastInfo *)malloc( - sizeof(KeyboardBroadcastInfo) + screens.size()); +Server::KeyboardBroadcastInfo *Server::KeyboardBroadcastInfo::alloc(State state, const String &screens) +{ + KeyboardBroadcastInfo *info = (KeyboardBroadcastInfo *)malloc(sizeof(KeyboardBroadcastInfo) + screens.size()); info->m_state = state; - std::copy( - screens.c_str(), screens.c_str() + screens.size() + 1, info->m_screens); + std::copy(screens.c_str(), screens.c_str() + screens.size() + 1, info->m_screens); return info; } -bool Server::isReceivedFileSizeValid() { +bool Server::isReceivedFileSizeValid() +{ return m_expectedFileSize == m_receivedFileData.size(); } -bool Server::isClientMode() const { return m_args.m_config->isClientMode(); } +bool Server::isClientMode() const +{ + return m_args.m_config->isClientMode(); +} -void Server::sendFileToClient(const char *filename) { +void Server::sendFileToClient(const char *filename) +{ if (m_sendFileThread != NULL) { StreamChunker::interruptFile(); } @@ -2287,7 +2256,8 @@ void Server::sendFileToClient(const char *filename) { m_sendFileThread.reset(new Thread(method)); } -void Server::sendFileThread(void *data) { +void Server::sendFileThread(void *data) +{ try { char *filename = static_cast(data); LOG((CLOG_DEBUG "sending file to client, filename=%s", filename)); @@ -2299,7 +2269,8 @@ void Server::sendFileThread(void *data) { m_sendFileThread.reset(nullptr); } -void Server::dragInfoReceived(UInt32 fileNum, String content) { +void Server::dragInfoReceived(UInt32 fileNum, String content) +{ if (!m_args.m_enableDragDrop) { LOG((CLOG_DEBUG "drag drop not enabled, ignoring drag info.")); return; diff --git a/src/lib/server/Server.h b/src/lib/server/Server.h index ff9b41555..352539cbc 100644 --- a/src/lib/server/Server.h +++ b/src/lib/server/Server.h @@ -49,14 +49,21 @@ class ClientListener; /*! This class implements the top-level server algorithms for deskflow. */ -class Server : public INode { +class Server : public INode +{ using ServerConfig = deskflow::server::Config; public: //! Lock cursor to screen data - class LockCursorToScreenInfo { + class LockCursorToScreenInfo + { public: - enum State { kOff, kOn, kToggle }; + enum State + { + kOff, + kOn, + kToggle + }; static LockCursorToScreenInfo *alloc(State state = kToggle); @@ -65,7 +72,8 @@ public: }; //! Switch to screen data - class SwitchToScreenInfo { + class SwitchToScreenInfo + { public: static SwitchToScreenInfo *alloc(const String &screen); @@ -75,7 +83,8 @@ public: }; //! Switch in direction data - class SwitchInDirectionInfo { + class SwitchInDirectionInfo + { public: static SwitchInDirectionInfo *alloc(EDirection direction); @@ -84,18 +93,27 @@ public: }; //! Screen connected data - class ScreenConnectedInfo { + class ScreenConnectedInfo + { public: - ScreenConnectedInfo(String screen) : m_screen(screen) {} + ScreenConnectedInfo(String screen) : m_screen(screen) + { + } public: String m_screen; // was char[1] }; //! Keyboard broadcast data - class KeyboardBroadcastInfo { + class KeyboardBroadcastInfo + { public: - enum State { kOff, kOn, kToggle }; + enum State + { + kOff, + kOn, + kToggle + }; static KeyboardBroadcastInfo *alloc(State state = kToggle); static KeyboardBroadcastInfo *alloc(State state, const String &screens); @@ -111,9 +129,9 @@ public: ownership of \p primaryClient. */ Server( - ServerConfig &config, PrimaryClient *primaryClient, - deskflow::Screen *screen, IEventQueue *events, - deskflow::ServerArgs const &args); + ServerConfig &config, PrimaryClient *primaryClient, deskflow::Screen *screen, IEventQueue *events, + deskflow::ServerArgs const &args + ); Server(Server const &) = delete; Server(Server &&) = delete; ~Server(); @@ -122,8 +140,13 @@ public: Server &operator=(Server &&) = delete; #ifdef TEST_ENV - Server() : m_mock(true), m_config(NULL) {} - void setActive(BaseClientProxy *active) { m_active = active; } + Server() : m_mock(true), m_config(NULL) + { + } + void setActive(BaseClientProxy *active) + { + m_active = active; + } #endif //! @name manipulators @@ -160,7 +183,10 @@ public: void dragInfoReceived(UInt32 fileNum, String content); //! Store ClientListener pointer - void setListener(ClientListener *p) { m_clientListener = p; } + void setListener(ClientListener *p) + { + m_clientListener = p; + } //@} //! @name accessors @@ -182,13 +208,22 @@ public: bool isReceivedFileSizeValid(); //! Return expected file data size - size_t &getExpectedFileSize() { return m_expectedFileSize; } + size_t &getExpectedFileSize() + { + return m_expectedFileSize; + } //! Return received file data - String &getReceivedFileData() { return m_receivedFileData; } + String &getReceivedFileData() + { + return m_receivedFileData; + } //! Return fake drag file list - DragFileList getFakeDragFileList() { return m_fakeDragFileList; } + DragFileList getFakeDragFileList() + { + return m_fakeDragFileList; + } //! Returns true if it's client mode and server initiates connection bool isClientMode() const; @@ -226,8 +261,7 @@ private: // convert fraction to pixel position, writing only x or y depending // on the direction. - void mapToPixel( - BaseClientProxy *, EDirection, float f, SInt32 &x, SInt32 &y) const; + void mapToPixel(BaseClientProxy *, EDirection, float f, SInt32 &x, SInt32 &y) const; // returns true if the client has a neighbor anywhere along the edge // indicated by the direction. @@ -235,16 +269,14 @@ private: // lookup neighboring screen, mapping the coordinate independent of // the direction to the neighbor's coordinate space. - BaseClientProxy * - getNeighbor(BaseClientProxy *, EDirection, SInt32 &x, SInt32 &y) const; + BaseClientProxy *getNeighbor(BaseClientProxy *, EDirection, SInt32 &x, SInt32 &y) const; // lookup neighboring screen. given a position relative to the // source screen, find the screen we should move onto and where. // if the position is sufficiently far from the source then we // cross multiple screens. if there is no suitable screen then // return NULL and x,y are not modified. - BaseClientProxy * - mapToNeighbor(BaseClientProxy *, EDirection, SInt32 &x, SInt32 &y) const; + BaseClientProxy *mapToNeighbor(BaseClientProxy *, EDirection, SInt32 &x, SInt32 &y) const; // adjusts x and y or neither to avoid ending up in a jump zone // after entering the client in the given direction. @@ -253,9 +285,7 @@ private: // test if a switch is permitted. this includes testing user // options like switch delay and tracking any state required to // implement them. returns true iff a switch is permitted. - bool isSwitchOkay( - BaseClientProxy *dst, EDirection, SInt32 x, SInt32 y, SInt32 xActive, - SInt32 yActive); + bool isSwitchOkay(BaseClientProxy *dst, EDirection, SInt32 x, SInt32 y, SInt32 xActive, SInt32 yActive); // update switch state due to a mouse move at \p x, \p y that // doesn't switch screens. @@ -328,11 +358,9 @@ private: void handleFileRecieveCompletedEvent(const Event &, void *); // event processing - void - onClipboardChanged(BaseClientProxy *sender, ClipboardID id, UInt32 seqNum); + void onClipboardChanged(BaseClientProxy *sender, ClipboardID id, UInt32 seqNum); void onScreensaver(bool activated); - void onKeyDown( - KeyID, KeyModifierMask, KeyButton, const String &, const char *screens); + void onKeyDown(KeyID, KeyModifierMask, KeyButton, const String &, const char *screens); void onKeyUp(KeyID, KeyModifierMask, KeyButton, const char *screens); void onKeyRepeat(KeyID, KeyModifierMask, SInt32, KeyButton, const String &); void onMouseDown(ButtonID); @@ -382,7 +410,8 @@ public: bool m_mock; private: - class ClipboardInfo { + class ClipboardInfo + { public: ClipboardInfo(); diff --git a/src/test/integtests/deskflow/ConfigTests.cpp b/src/test/integtests/deskflow/ConfigTests.cpp index c19edb6cd..8feb3ce4c 100644 --- a/src/test/integtests/deskflow/ConfigTests.cpp +++ b/src/test/integtests/deskflow/ConfigTests.cpp @@ -26,7 +26,8 @@ using namespace deskflow; const auto kTestFilename = "tmp/test/test.toml"; -TEST(ConfigTests, load_fileExists_loadsConfig) { +TEST(ConfigTests, load_fileExists_loadsConfig) +{ std::ofstream testFile(kTestFilename); testFile << "[test.args]\n" R"(test-arg = "test opt")"; @@ -42,17 +43,20 @@ TEST(ConfigTests, load_fileExists_loadsConfig) { ASSERT_STREQ(config.argv()[2], "test opt"); } -TEST(ConfigTests, load_filenameEmpty_throwsException) { +TEST(ConfigTests, load_filenameEmpty_throwsException) +{ EXPECT_THROW( { Config config("", "test"); config.load("test"); }, - Config::NoConfigFilenameError); + Config::NoConfigFilenameError + ); } -TEST(ConfigTests, load_fileDoesNotExist_returnsFalse) { +TEST(ConfigTests, load_fileDoesNotExist_returnsFalse) +{ Config config("nonexistent.toml", "test"); const auto result = config.load("test"); @@ -60,7 +64,8 @@ TEST(ConfigTests, load_fileDoesNotExist_returnsFalse) { ASSERT_FALSE(result); } -TEST(ConfigTests, load_invalidConfig_throwsException) { +TEST(ConfigTests, load_invalidConfig_throwsException) +{ EXPECT_THROW( { std::ofstream testFile(kTestFilename); @@ -71,10 +76,12 @@ TEST(ConfigTests, load_invalidConfig_throwsException) { config.load("test"); }, - Config::ParseError); + Config::ParseError + ); } -TEST(ConfigTests, load_sectionMissing_returnsFalse) { +TEST(ConfigTests, load_sectionMissing_returnsFalse) +{ std::ofstream testFile(kTestFilename); testFile.close(); Config config(kTestFilename, "missing"); @@ -84,7 +91,8 @@ TEST(ConfigTests, load_sectionMissing_returnsFalse) { ASSERT_FALSE(result); } -TEST(ConfigTests, load_notTable_returnsFalse) { +TEST(ConfigTests, load_notTable_returnsFalse) +{ std::ofstream testFile(kTestFilename); testFile << "[test]"; testFile.close(); @@ -95,7 +103,8 @@ TEST(ConfigTests, load_notTable_returnsFalse) { ASSERT_FALSE(result); } -TEST(ConfigTests, load_lastArg_returnsLast) { +TEST(ConfigTests, load_lastArg_returnsLast) +{ std::ofstream testFile(kTestFilename); testFile << "[test.args]\n" R"(_last = "test last")" @@ -113,7 +122,8 @@ TEST(ConfigTests, load_lastArg_returnsLast) { ASSERT_STREQ(config.argv()[2], "test last"); } -TEST(ConfigTests, load_noArgs_returnsFalse) { +TEST(ConfigTests, load_noArgs_returnsFalse) +{ std::ofstream testFile(kTestFilename); testFile << "[test.args]"; testFile.close(); diff --git a/src/test/integtests/gui/core/CommandProcessTests.cpp b/src/test/integtests/gui/core/CommandProcessTests.cpp index e3463cc5b..57b332f4c 100644 --- a/src/test/integtests/gui/core/CommandProcessTests.cpp +++ b/src/test/integtests/gui/core/CommandProcessTests.cpp @@ -19,7 +19,8 @@ #include -TEST(CommandProcessTests, run_commandSucceeds_returnsOutput) { +TEST(CommandProcessTests, run_commandSucceeds_returnsOutput) +{ // it seems that on windows, you can sometimes just call echo (this worked // with windows 2022), but on windows 10 you can't call echo directly. diff --git a/src/test/integtests/gui/core/CoreToolTests.cpp b/src/test/integtests/gui/core/CoreToolTests.cpp index 24b979a8a..e124e3467 100644 --- a/src/test/integtests/gui/core/CoreToolTests.cpp +++ b/src/test/integtests/gui/core/CoreToolTests.cpp @@ -20,7 +20,8 @@ #include -TEST(CoreToolTests, getProfileDir_noMock_returnsNonEmpty) { +TEST(CoreToolTests, getProfileDir_noMock_returnsNonEmpty) +{ TestQtCoreApp app; CoreTool coreTool; @@ -29,7 +30,8 @@ TEST(CoreToolTests, getProfileDir_noMock_returnsNonEmpty) { EXPECT_FALSE(profileDir.isEmpty()); } -TEST(CoreToolTests, getInstalledDir_noMock_returnsNonEmpty) { +TEST(CoreToolTests, getInstalledDir_noMock_returnsNonEmpty) +{ TestQtCoreApp app; CoreTool coreTool; @@ -38,7 +40,8 @@ TEST(CoreToolTests, getInstalledDir_noMock_returnsNonEmpty) { EXPECT_FALSE(installedDir.isEmpty()); } -TEST(CoreToolTests, getArch_noMock_returnsNonEmpty) { +TEST(CoreToolTests, getArch_noMock_returnsNonEmpty) +{ TestQtCoreApp app; CoreTool coreTool; diff --git a/src/test/integtests/gui/dotenv_tests.cpp b/src/test/integtests/gui/dotenv_tests.cpp index 9ca316c25..fd1d8165e 100644 --- a/src/test/integtests/gui/dotenv_tests.cpp +++ b/src/test/integtests/gui/dotenv_tests.cpp @@ -22,7 +22,8 @@ #include -TEST(dotenv_tests, dotenv_fileDoesNotExist_doesNotLoadEnvVar) { +TEST(dotenv_tests, dotenv_fileDoesNotExist_doesNotLoadEnvVar) +{ const QString envFile = "tmp/test/.env"; deskflow::gui::dotenv(envFile); @@ -31,7 +32,8 @@ TEST(dotenv_tests, dotenv_fileDoesNotExist_doesNotLoadEnvVar) { EXPECT_TRUE(actualValue.isEmpty()); } -TEST(dotenv_tests, dotenv_envFileWithEntry_loadsEnvVar) { +TEST(dotenv_tests, dotenv_envFileWithEntry_loadsEnvVar) +{ const QString envFile = "tmp/test/.env"; QFile file(envFile); if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) { diff --git a/src/test/integtests/ipc/IpcTests.cpp b/src/test/integtests/ipc/IpcTests.cpp index 438f5ff2a..a29152e37 100644 --- a/src/test/integtests/ipc/IpcTests.cpp +++ b/src/test/integtests/ipc/IpcTests.cpp @@ -41,7 +41,8 @@ const int kTestPort = 24802; -class IpcTests : public ::testing::Test { +class IpcTests : public ::testing::Test +{ public: IpcTests(); virtual ~IpcTests(); @@ -63,7 +64,8 @@ public: TestEventQueue m_events; }; -TEST_F(IpcTests, connectToServer) { +TEST_F(IpcTests, connectToServer) +{ SocketMultiplexer socketMultiplexer; IpcServer server(&m_events, &socketMultiplexer, kTestPort); server.listen(); @@ -71,8 +73,8 @@ TEST_F(IpcTests, connectToServer) { m_events.adoptHandler( m_events.forIpcServer().messageReceived(), &server, - new TMethodEventJob( - this, &IpcTests::connectToServer_handleMessageReceived)); + new TMethodEventJob(this, &IpcTests::connectToServer_handleMessageReceived) + ); IpcClient client(&m_events, &socketMultiplexer, kTestPort); client.connect(); @@ -86,7 +88,8 @@ TEST_F(IpcTests, connectToServer) { EXPECT_EQ(true, m_connectToServer_hasClientNode); } -TEST_F(IpcTests, sendMessageToServer) { +TEST_F(IpcTests, sendMessageToServer) +{ SocketMultiplexer socketMultiplexer; IpcServer server(&m_events, &socketMultiplexer, kTestPort); server.listen(); @@ -94,8 +97,8 @@ TEST_F(IpcTests, sendMessageToServer) { // event handler sends "test" command to server. m_events.adoptHandler( m_events.forIpcServer().messageReceived(), &server, - new TMethodEventJob( - this, &IpcTests::sendMessageToServer_serverHandleMessageReceived)); + new TMethodEventJob(this, &IpcTests::sendMessageToServer_serverHandleMessageReceived) + ); IpcClient client(&m_events, &socketMultiplexer, kTestPort); client.connect(); @@ -109,7 +112,8 @@ TEST_F(IpcTests, sendMessageToServer) { EXPECT_EQ("test", m_sendMessageToServer_receivedString); } -TEST_F(IpcTests, sendMessageToClient) { +TEST_F(IpcTests, sendMessageToClient) +{ SocketMultiplexer socketMultiplexer; IpcServer server(&m_events, &socketMultiplexer, kTestPort); server.listen(); @@ -118,16 +122,16 @@ TEST_F(IpcTests, sendMessageToClient) { // event handler sends "test" log line to client. m_events.adoptHandler( m_events.forIpcServer().messageReceived(), &server, - new TMethodEventJob( - this, &IpcTests::sendMessageToClient_serverHandleClientConnected)); + new TMethodEventJob(this, &IpcTests::sendMessageToClient_serverHandleClientConnected) + ); IpcClient client(&m_events, &socketMultiplexer, kTestPort); client.connect(); m_events.adoptHandler( m_events.forIpcClient().messageReceived(), &client, - new TMethodEventJob( - this, &IpcTests::sendMessageToClient_clientHandleMessageReceived)); + new TMethodEventJob(this, &IpcTests::sendMessageToClient_clientHandleMessageReceived) + ); m_events.initQuitTimeout(5); m_events.loop(); @@ -143,22 +147,26 @@ IpcTests::IpcTests() m_connectToServer_hasClientNode(false), m_connectToServer_server(nullptr), m_sendMessageToClient_server(nullptr), - m_sendMessageToServer_client(nullptr) {} + m_sendMessageToServer_client(nullptr) +{ +} -IpcTests::~IpcTests() {} +IpcTests::~IpcTests() +{ +} -void IpcTests::connectToServer_handleMessageReceived(const Event &e, void *) { +void IpcTests::connectToServer_handleMessageReceived(const Event &e, void *) +{ IpcMessage *m = static_cast(e.getDataObject()); if (m->type() == IpcMessageType::Hello) { - m_connectToServer_hasClientNode = - m_connectToServer_server->hasClients(IpcClientType::Node); + m_connectToServer_hasClientNode = m_connectToServer_server->hasClients(IpcClientType::Node); m_connectToServer_helloMessageReceived = true; m_events.raiseQuitEvent(); } } -void IpcTests::sendMessageToServer_serverHandleMessageReceived( - const Event &e, void *) { +void IpcTests::sendMessageToServer_serverHandleMessageReceived(const Event &e, void *) +{ IpcMessage *m = static_cast(e.getDataObject()); if (m->type() == IpcMessageType::Hello) { LOG((CLOG_DEBUG "client said hello, sending test to server")); @@ -172,8 +180,8 @@ void IpcTests::sendMessageToServer_serverHandleMessageReceived( } } -void IpcTests::sendMessageToClient_serverHandleClientConnected( - const Event &e, void *) { +void IpcTests::sendMessageToClient_serverHandleClientConnected(const Event &e, void *) +{ IpcMessage *m = static_cast(e.getDataObject()); if (m->type() == IpcMessageType::Hello) { LOG((CLOG_DEBUG "client said hello, sending test to client")); @@ -182,8 +190,8 @@ void IpcTests::sendMessageToClient_serverHandleClientConnected( } } -void IpcTests::sendMessageToClient_clientHandleMessageReceived( - const Event &e, void *) { +void IpcTests::sendMessageToClient_clientHandleMessageReceived(const Event &e, void *) +{ IpcMessage *m = static_cast(e.getDataObject()); if (m->type() == IpcMessageType::LogLine) { IpcLogLineMessage *llm = static_cast(m); diff --git a/src/test/integtests/main.cpp b/src/test/integtests/main.cpp index c6f057efb..4c1711ed7 100644 --- a/src/test/integtests/main.cpp +++ b/src/test/integtests/main.cpp @@ -31,7 +31,8 @@ using deskflow::test::ExitTimeout; const auto testDir = "tmp/test"; -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ // HACK: Unit tests should not use the filesystem. std::filesystem::create_directories(testDir); diff --git a/src/test/integtests/platform/MSWindowsClipboardTests.cpp b/src/test/integtests/platform/MSWindowsClipboardTests.cpp index 0c3d95b66..1af57a53c 100644 --- a/src/test/integtests/platform/MSWindowsClipboardTests.cpp +++ b/src/test/integtests/platform/MSWindowsClipboardTests.cpp @@ -22,26 +22,36 @@ #include #include -class MSWindowsClipboardTests : public ::testing::Test { +class MSWindowsClipboardTests : public ::testing::Test +{ protected: - virtual void SetUp() { emptyClipboard(); } + virtual void SetUp() + { + emptyClipboard(); + } - virtual void TearDown() { emptyClipboard(); } + virtual void TearDown() + { + emptyClipboard(); + } private: - void emptyClipboard() { + void emptyClipboard() + { MSWindowsClipboard clipboard(NULL); clipboard.open(0); clipboard.empty(); } }; -class MockFacade : public IMSWindowsClipboardFacade { +class MockFacade : public IMSWindowsClipboardFacade +{ public: MOCK_METHOD2(write, void(HANDLE, UINT)); }; -TEST_F(MSWindowsClipboardTests, emptyUnowned_openCalled_returnsTrue) { +TEST_F(MSWindowsClipboardTests, emptyUnowned_openCalled_returnsTrue) +{ MSWindowsClipboard clipboard(NULL); clipboard.open(0); @@ -50,7 +60,8 @@ TEST_F(MSWindowsClipboardTests, emptyUnowned_openCalled_returnsTrue) { EXPECT_EQ(true, actual); } -TEST_F(MSWindowsClipboardTests, empty_openCalled_returnsTrue) { +TEST_F(MSWindowsClipboardTests, empty_openCalled_returnsTrue) +{ MSWindowsClipboard clipboard(NULL); clipboard.open(0); @@ -59,7 +70,8 @@ TEST_F(MSWindowsClipboardTests, empty_openCalled_returnsTrue) { EXPECT_EQ(true, actual); } -TEST_F(MSWindowsClipboardTests, empty_singleFormat_hasReturnsFalse) { +TEST_F(MSWindowsClipboardTests, empty_singleFormat_hasReturnsFalse) +{ MSWindowsClipboard clipboard(NULL); clipboard.open(0); clipboard.add(MSWindowsClipboard::kText, "synergy rocks!"); @@ -70,7 +82,8 @@ TEST_F(MSWindowsClipboardTests, empty_singleFormat_hasReturnsFalse) { EXPECT_EQ(false, actual); } -TEST_F(MSWindowsClipboardTests, add_newValue_valueWasStored) { +TEST_F(MSWindowsClipboardTests, add_newValue_valueWasStored) +{ MSWindowsClipboard clipboard(NULL); clipboard.open(0); @@ -80,7 +93,8 @@ TEST_F(MSWindowsClipboardTests, add_newValue_valueWasStored) { EXPECT_EQ("synergy rocks!", actual); } -TEST_F(MSWindowsClipboardTests, add_newValue_writeWasCalled) { +TEST_F(MSWindowsClipboardTests, add_newValue_writeWasCalled) +{ MockFacade facade; EXPECT_CALL(facade, write(testing::_, testing::_)); @@ -91,7 +105,8 @@ TEST_F(MSWindowsClipboardTests, add_newValue_writeWasCalled) { clipboard.add(IClipboard::kText, "synergy rocks!"); } -TEST_F(MSWindowsClipboardTests, add_replaceValue_valueWasReplaced) { +TEST_F(MSWindowsClipboardTests, add_replaceValue_valueWasReplaced) +{ MSWindowsClipboard clipboard(NULL); clipboard.open(0); @@ -102,7 +117,8 @@ TEST_F(MSWindowsClipboardTests, add_replaceValue_valueWasReplaced) { EXPECT_EQ("maxivista sucks", actual); } -TEST_F(MSWindowsClipboardTests, open_timeIsZero_returnsTrue) { +TEST_F(MSWindowsClipboardTests, open_timeIsZero_returnsTrue) +{ MSWindowsClipboard clipboard(NULL); bool actual = clipboard.open(0); @@ -110,7 +126,8 @@ TEST_F(MSWindowsClipboardTests, open_timeIsZero_returnsTrue) { EXPECT_EQ(true, actual); } -TEST_F(MSWindowsClipboardTests, open_timeIsOne_returnsTrue) { +TEST_F(MSWindowsClipboardTests, open_timeIsOne_returnsTrue) +{ MSWindowsClipboard clipboard(NULL); bool actual = clipboard.open(1); @@ -118,7 +135,8 @@ TEST_F(MSWindowsClipboardTests, open_timeIsOne_returnsTrue) { EXPECT_EQ(true, actual); } -TEST_F(MSWindowsClipboardTests, close_isOpen_noErrors) { +TEST_F(MSWindowsClipboardTests, close_isOpen_noErrors) +{ MSWindowsClipboard clipboard(NULL); clipboard.open(0); @@ -153,7 +171,8 @@ TEST_F(MSWindowsClipboardTests, getTime_openAndEmpty_returnsOne) } #endif -TEST_F(MSWindowsClipboardTests, has_withFormatAdded_returnsTrue) { +TEST_F(MSWindowsClipboardTests, has_withFormatAdded_returnsTrue) +{ MSWindowsClipboard clipboard(NULL); clipboard.open(0); clipboard.empty(); @@ -164,7 +183,8 @@ TEST_F(MSWindowsClipboardTests, has_withFormatAdded_returnsTrue) { EXPECT_EQ(true, actual); } -TEST_F(MSWindowsClipboardTests, has_withNoFormats_returnsFalse) { +TEST_F(MSWindowsClipboardTests, has_withNoFormats_returnsFalse) +{ MSWindowsClipboard clipboard(NULL); clipboard.open(0); clipboard.empty(); @@ -174,7 +194,8 @@ TEST_F(MSWindowsClipboardTests, has_withNoFormats_returnsFalse) { EXPECT_EQ(false, actual); } -TEST_F(MSWindowsClipboardTests, get_withNoFormats_returnsEmpty) { +TEST_F(MSWindowsClipboardTests, get_withNoFormats_returnsEmpty) +{ MSWindowsClipboard clipboard(NULL); clipboard.open(0); clipboard.empty(); @@ -184,7 +205,8 @@ TEST_F(MSWindowsClipboardTests, get_withNoFormats_returnsEmpty) { EXPECT_EQ("", actual); } -TEST_F(MSWindowsClipboardTests, get_withFormatAdded_returnsExpected) { +TEST_F(MSWindowsClipboardTests, get_withFormatAdded_returnsExpected) +{ MSWindowsClipboard clipboard(NULL); clipboard.open(0); clipboard.empty(); @@ -195,7 +217,8 @@ TEST_F(MSWindowsClipboardTests, get_withFormatAdded_returnsExpected) { EXPECT_EQ("synergy rocks!", actual); } -TEST_F(MSWindowsClipboardTests, isOwnedByDeskflow_defaultState_noError) { +TEST_F(MSWindowsClipboardTests, isOwnedByDeskflow_defaultState_noError) +{ MSWindowsClipboard clipboard(NULL); clipboard.open(0); diff --git a/src/test/integtests/platform/OSXKeyStateTests.cpp b/src/test/integtests/platform/OSXKeyStateTests.cpp index 460c28bea..55d1bc9d1 100644 --- a/src/test/integtests/platform/OSXKeyStateTests.cpp +++ b/src/test/integtests/platform/OSXKeyStateTests.cpp @@ -30,7 +30,8 @@ #define A_CHAR_ID 0x00000061 #define A_CHAR_BUTTON 001 -class OSXKeyStateTests : public ::testing::Test { +class OSXKeyStateTests : public ::testing::Test +{ public: static bool isKeyPressed(const OSXKeyState &keyState, KeyButton button); }; @@ -38,7 +39,8 @@ public: // fakeAndPoll_shift seems to always fail on osx10.6 #if __MAC_OS_X_VERSION_MIN_REQUIRED > 1060 -TEST_F(OSXKeyStateTests, fakeAndPoll_shift) { +TEST_F(OSXKeyStateTests, fakeAndPoll_shift) +{ deskflow::KeyMap keyMap; MockEventQueue eventQueue; OSXKeyState keyState(&eventQueue, keyMap, {"en"}, true); @@ -57,7 +59,8 @@ TEST_F(OSXKeyStateTests, fakeAndPoll_shift) { EXPECT_TRUE(!isKeyPressed(keyState, SHIFT_BUTTON)); } -TEST_F(OSXKeyStateTests, fakeAndPoll_charKey) { +TEST_F(OSXKeyStateTests, fakeAndPoll_charKey) +{ deskflow::KeyMap keyMap; MockEventQueue eventQueue; OSXKeyState keyState(&eventQueue, keyMap, {"en"}, true); @@ -75,7 +78,8 @@ TEST_F(OSXKeyStateTests, fakeAndPoll_charKey) { keyState.fakeKeyUp(2); } -TEST_F(OSXKeyStateTests, fakeAndPoll_charKeyAndModifier) { +TEST_F(OSXKeyStateTests, fakeAndPoll_charKeyAndModifier) +{ deskflow::KeyMap keyMap; MockEventQueue eventQueue; OSXKeyState keyState(&eventQueue, keyMap, {"en"}, true); @@ -93,8 +97,8 @@ TEST_F(OSXKeyStateTests, fakeAndPoll_charKeyAndModifier) { keyState.fakeKeyUp(2); } -bool OSXKeyStateTests::isKeyPressed( - const OSXKeyState &keyState, KeyButton button) { +bool OSXKeyStateTests::isKeyPressed(const OSXKeyState &keyState, KeyButton button) +{ // HACK: allow os to realize key state changes. ARCH->sleep(.2); diff --git a/src/test/mock/deskflow/MockApp.h b/src/test/mock/deskflow/MockApp.h index 10b2e9b36..49ae7ba96 100644 --- a/src/test/mock/deskflow/MockApp.h +++ b/src/test/mock/deskflow/MockApp.h @@ -23,9 +23,12 @@ #include -class MockApp : public App { +class MockApp : public App +{ public: - MockApp() : App(NULL, NULL, NULL) {} + MockApp() : App(NULL, NULL, NULL) + { + } MOCK_METHOD(void, help, (), (override)); MOCK_METHOD(void, loadConfig, (), (override)); @@ -35,8 +38,7 @@ public: MOCK_METHOD(void, parseArgs, (int, const char *const *), (override)); MOCK_METHOD(void, version, (), (override)); MOCK_METHOD(int, standardStartup, (int, char **), (override)); - MOCK_METHOD( - int, runInner, (int, char **, ILogOutputter *, StartupFunc), (override)); + MOCK_METHOD(int, runInner, (int, char **, ILogOutputter *, StartupFunc), (override)); MOCK_METHOD(void, startNode, (), (override)); MOCK_METHOD(int, mainLoop, (), (override)); MOCK_METHOD(int, foregroundStartup, (int, char **), (override)); diff --git a/src/test/mock/deskflow/MockArgParser.h b/src/test/mock/deskflow/MockArgParser.h index e3c8f0833..ba2cd7d75 100644 --- a/src/test/mock/deskflow/MockArgParser.h +++ b/src/test/mock/deskflow/MockArgParser.h @@ -23,9 +23,12 @@ #include -class MockArgParser : public ArgParser { +class MockArgParser : public ArgParser +{ public: - MockArgParser() : ArgParser(NULL) {} + MockArgParser() : ArgParser(NULL) + { + } MOCK_METHOD(bool, parseGenericArgs, (int, const char *const *, int &)); MOCK_METHOD(bool, checkUnexpectedArgs, ()); diff --git a/src/test/mock/deskflow/MockEventQueue.h b/src/test/mock/deskflow/MockEventQueue.h index 9ec018625..e3094bd27 100644 --- a/src/test/mock/deskflow/MockEventQueue.h +++ b/src/test/mock/deskflow/MockEventQueue.h @@ -22,29 +22,26 @@ #include -class MockEventQueue : public IEventQueue { +class MockEventQueue : public IEventQueue +{ public: MOCK_METHOD(void, loop, (), (override)); MOCK_METHOD(EventQueueTimer *, newOneShotTimer, (double, void *), (override)); MOCK_METHOD(EventQueueTimer *, newTimer, (double, void *), (override)); MOCK_METHOD(bool, getEvent, (Event &, double), (override)); MOCK_METHOD(void, adoptBuffer, (IEventQueueBuffer *), (override)); - MOCK_METHOD( - Event::Type, registerTypeOnce, (Event::Type &, const char *), (override)); + MOCK_METHOD(Event::Type, registerTypeOnce, (Event::Type &, const char *), (override)); MOCK_METHOD(void, removeHandlers, (void *), (override)); MOCK_METHOD(Event::Type, registerType, (const char *)); MOCK_METHOD(bool, isEmpty, (), (const, override)); - MOCK_METHOD( - void, adoptHandler, (Event::Type, void *, IEventJob *), (override)); + MOCK_METHOD(void, adoptHandler, (Event::Type, void *, IEventJob *), (override)); MOCK_METHOD(const char *, getTypeName, (Event::Type), (override)); MOCK_METHOD(void, addEvent, (const Event &), (override)); MOCK_METHOD(void, removeHandler, (Event::Type, void *), (override)); MOCK_METHOD(bool, dispatchEvent, (const Event &), (override)); - MOCK_METHOD( - IEventJob *, getHandler, (Event::Type, void *), (const, override)); + MOCK_METHOD(IEventJob *, getHandler, (Event::Type, void *), (const, override)); MOCK_METHOD(void, deleteTimer, (EventQueueTimer *), (override)); - MOCK_METHOD( - Event::Type, getRegisteredType, (const String &), (const, override)); + MOCK_METHOD(Event::Type, getRegisteredType, (const String &), (const, override)); MOCK_METHOD(void *, getSystemTarget, (), (override)); MOCK_METHOD(ClientEvents &, forClient, (), (override)); MOCK_METHOD(IStreamEvents &, forIStream, (), (override)); @@ -58,8 +55,7 @@ public: MOCK_METHOD(OSXScreenEvents &, forOSXScreen, (), (override)); MOCK_METHOD(ClientListenerEvents &, forClientListener, (), (override)); MOCK_METHOD(ClientProxyEvents &, forClientProxy, (), (override)); - MOCK_METHOD( - ClientProxyUnknownEvents &, forClientProxyUnknown, (), (override)); + MOCK_METHOD(ClientProxyUnknownEvents &, forClientProxyUnknown, (), (override)); MOCK_METHOD(ServerEvents &, forServer, (), (override)); MOCK_METHOD(ServerAppEvents &, forServerApp, (), (override)); MOCK_METHOD(IKeyStateEvents &, forIKeyState, (), (override)); diff --git a/src/test/mock/deskflow/MockKeyMap.h b/src/test/mock/deskflow/MockKeyMap.h index 5efc73db1..195e7366e 100644 --- a/src/test/mock/deskflow/MockKeyMap.h +++ b/src/test/mock/deskflow/MockKeyMap.h @@ -22,7 +22,8 @@ #include -class MockKeyMap : public deskflow::KeyMap { +class MockKeyMap : public deskflow::KeyMap +{ public: MOCK_METHOD(void, swap, (KeyMap &), (override)); MOCK_METHOD(void, finish, (), (override)); @@ -31,7 +32,7 @@ public: MOCK_METHOD(bool, isHalfDuplex, (KeyID, KeyButton), (const, override)); MOCK_METHOD( const KeyMap::KeyItem *, mapKey, - (Keystrokes &, KeyID, SInt32, ModifierToKeys &, KeyModifierMask &, - KeyModifierMask, bool, const String &), - (const, override)); + (Keystrokes &, KeyID, SInt32, ModifierToKeys &, KeyModifierMask &, KeyModifierMask, bool, const String &), + (const, override) + ); }; diff --git a/src/test/mock/deskflow/MockKeyState.h b/src/test/mock/deskflow/MockKeyState.h index e613a8baf..417439761 100644 --- a/src/test/mock/deskflow/MockKeyState.h +++ b/src/test/mock/deskflow/MockKeyState.h @@ -27,15 +27,17 @@ class MockEventQueue; // NOTE: do not mock methods that are not pure virtual. this mock exists only // to provide an implementation of the KeyState abstract class. -class MockKeyState : public KeyState { +class MockKeyState : public KeyState +{ public: - MockKeyState(const MockEventQueue &eventQueue) - : KeyState((IEventQueue *)&eventQueue, {"en"}, true) {} + MockKeyState(const MockEventQueue &eventQueue) : KeyState((IEventQueue *)&eventQueue, {"en"}, true) + { + } MockKeyState(const MockEventQueue &eventQueue, const deskflow::KeyMap &keyMap) - : KeyState( - (IEventQueue *)&eventQueue, (deskflow::KeyMap &)keyMap, {"en"}, - true) {} + : KeyState((IEventQueue *)&eventQueue, (deskflow::KeyMap &)keyMap, {"en"}, true) + { + } MOCK_METHOD(SInt32, pollActiveGroup, (), (const, override)); MOCK_METHOD(KeyModifierMask, pollActiveModifiers, (), (const, override)); @@ -50,5 +52,4 @@ typedef ::testing::NiceMock KeyStateImpl; typedef UInt32 KeyID; -typedef void (*ForeachKeyCallback)( - KeyID, SInt32 group, deskflow::KeyMap::KeyItem &, void *userData); +typedef void (*ForeachKeyCallback)(KeyID, SInt32 group, deskflow::KeyMap::KeyItem &, void *userData); diff --git a/src/test/mock/deskflow/MockScreen.h b/src/test/mock/deskflow/MockScreen.h index cab9673ab..d1ecbfbb2 100644 --- a/src/test/mock/deskflow/MockScreen.h +++ b/src/test/mock/deskflow/MockScreen.h @@ -23,13 +23,14 @@ #include -class MockScreen : public deskflow::Screen { +class MockScreen : public deskflow::Screen +{ public: - MockScreen() : deskflow::Screen() {} + MockScreen() : deskflow::Screen() + { + } MOCK_METHOD(void, disable, (), (override)); - MOCK_METHOD( - void, getShape, (SInt32 &, SInt32 &, SInt32 &, SInt32 &), - (const, override)); + MOCK_METHOD(void, getShape, (SInt32 &, SInt32 &, SInt32 &, SInt32 &), (const, override)); MOCK_METHOD(void, getCursorPos, (SInt32 &, SInt32 &), (const, override)); MOCK_METHOD(void, resetOptions, (), (override)); MOCK_METHOD(void, setOptions, (const OptionsList &), (override)); diff --git a/src/test/mock/io/MockStream.h b/src/test/mock/io/MockStream.h index 5e21c8758..9c4aca6f6 100644 --- a/src/test/mock/io/MockStream.h +++ b/src/test/mock/io/MockStream.h @@ -24,9 +24,12 @@ class IEventQueue; -class MockStream : public deskflow::IStream { +class MockStream : public deskflow::IStream +{ public: - MockStream() {} + MockStream() + { + } MOCK_METHOD(void, close, (), (override)); MOCK_METHOD(UInt32, read, (void *, UInt32), (override)); MOCK_METHOD(void, write, (const void *, UInt32), (override)); diff --git a/src/test/mock/ipc/MockIpcServer.h b/src/test/mock/ipc/MockIpcServer.h index e4dcbde00..996fde3ad 100644 --- a/src/test/mock/ipc/MockIpcServer.h +++ b/src/test/mock/ipc/MockIpcServer.h @@ -28,13 +28,15 @@ using ::testing::Invoke; class IEventQueue; -class MockIpcServer : public IpcServer { +class MockIpcServer : public IpcServer +{ public: - MockIpcServer() - : m_sendCond(ARCH->newCondVar()), - m_sendMutex(ARCH->newMutex()) {} + MockIpcServer() : m_sendCond(ARCH->newCondVar()), m_sendMutex(ARCH->newMutex()) + { + } - ~MockIpcServer() { + ~MockIpcServer() + { if (m_sendCond != NULL) { ARCH->closeCondVar(m_sendCond); } @@ -48,15 +50,19 @@ public: MOCK_METHOD(void, send, (const IpcMessage &, IpcClientType), (override)); MOCK_METHOD(bool, hasClients, (IpcClientType), (const, override)); - void delegateToFake() { - ON_CALL(*this, send(_, _)) - .WillByDefault(Invoke(this, &MockIpcServer::mockSend)); + void delegateToFake() + { + ON_CALL(*this, send(_, _)).WillByDefault(Invoke(this, &MockIpcServer::mockSend)); } - void waitForSend() { ARCH->waitCondVar(m_sendCond, m_sendMutex, 5); } + void waitForSend() + { + ARCH->waitCondVar(m_sendCond, m_sendMutex, 5); + } private: - void mockSend(const IpcMessage &, IpcClientType) { + void mockSend(const IpcMessage &, IpcClientType) + { ArchMutexLock lock(m_sendMutex); ARCH->broadcastCondVar(m_sendCond); } diff --git a/src/test/mock/server/MockConfig.h b/src/test/mock/server/MockConfig.h index 697adcfee..95288bf95 100644 --- a/src/test/mock/server/MockConfig.h +++ b/src/test/mock/server/MockConfig.h @@ -23,9 +23,12 @@ #include -class MockConfig : public Config { +class MockConfig : public Config +{ public: - MockConfig() : Config() {} + MockConfig() : Config() + { + } MOCK_METHOD(InputFilter *, getInputFilter, (), (override)); MOCK_METHOD(bool, isScreen, (const String &), (const, override)); }; diff --git a/src/test/mock/server/MockInputFilter.h b/src/test/mock/server/MockInputFilter.h index 7b4eb544d..81be93a1c 100644 --- a/src/test/mock/server/MockInputFilter.h +++ b/src/test/mock/server/MockInputFilter.h @@ -23,7 +23,8 @@ #include -class MockInputFilter : public InputFilter { +class MockInputFilter : public InputFilter +{ public: MOCK_METHOD(void, setPrimaryClient, (PrimaryClient *), (override)); }; diff --git a/src/test/mock/server/MockPrimaryClient.h b/src/test/mock/server/MockPrimaryClient.h index 0de76fa6a..67033471a 100644 --- a/src/test/mock/server/MockPrimaryClient.h +++ b/src/test/mock/server/MockPrimaryClient.h @@ -24,7 +24,8 @@ #include -class MockPrimaryClient : public PrimaryClient { +class MockPrimaryClient : public PrimaryClient +{ public: MOCK_METHOD(void *, getEventTarget, (), (const, override)); MOCK_METHOD(void, getCursorPos, (SInt32 &, SInt32 &), (const, override)); diff --git a/src/test/mock/server/MockServer.h b/src/test/mock/server/MockServer.h index 866b55dc7..9a8fd865e 100644 --- a/src/test/mock/server/MockServer.h +++ b/src/test/mock/server/MockServer.h @@ -25,7 +25,10 @@ class IEventQueue; -class MockServer : public Server { +class MockServer : public Server +{ public: - MockServer() : Server() {} + MockServer() : Server() + { + } }; diff --git a/src/test/shared/ExitTimeout.cpp b/src/test/shared/ExitTimeout.cpp index d72873b92..97c6a8e1b 100644 --- a/src/test/shared/ExitTimeout.cpp +++ b/src/test/shared/ExitTimeout.cpp @@ -30,7 +30,8 @@ const auto checkMilliseconds = std::chrono::milliseconds(100); using std::chrono::duration_cast; using std::chrono::steady_clock; -bool timeoutReached(const steady_clock::time_point &start, const int minutes) { +bool timeoutReached(const steady_clock::time_point &start, const int minutes) +{ auto now = steady_clock::now(); auto duration = duration_cast(now - start); return duration.count() >= minutes; @@ -39,20 +40,23 @@ bool timeoutReached(const steady_clock::time_point &start, const int minutes) { ExitTimeout::ExitTimeout(const int minutes, const std::string_view &name) : m_minutes(minutes), m_name(name), - m_thread(std::make_unique([this]() { run(); })) {} + m_thread(std::make_unique([this]() { run(); })) +{ +} -ExitTimeout::~ExitTimeout() { +ExitTimeout::~ExitTimeout() +{ m_running = false; m_thread->join(); } -void ExitTimeout::run() const { +void ExitTimeout::run() const +{ auto start = steady_clock::now(); while (m_running) { std::this_thread::sleep_for(checkMilliseconds); if (timeoutReached(start, m_minutes)) { - std::cerr << m_name << " timed out after " << m_minutes << " minute(s)" - << std::endl; + std::cerr << m_name << " timed out after " << m_minutes << " minute(s)" << std::endl; std::exit(EXIT_FAILURE); } } diff --git a/src/test/shared/ExitTimeout.h b/src/test/shared/ExitTimeout.h index 93cd3301c..6a380a86d 100644 --- a/src/test/shared/ExitTimeout.h +++ b/src/test/shared/ExitTimeout.h @@ -31,7 +31,8 @@ namespace deskflow::test { * TODO: Switch to regular Clang instead of Apple Clang: * https://symless.atlassian.net/browse/S1-1754 */ -class ExitTimeout { +class ExitTimeout +{ public: ExitTimeout(const int minutes, const std::string_view &name); ~ExitTimeout(); diff --git a/src/test/shared/TestEventQueue.cpp b/src/test/shared/TestEventQueue.cpp index 8bfa199d8..5f9cba107 100644 --- a/src/test/shared/TestEventQueue.cpp +++ b/src/test/shared/TestEventQueue.cpp @@ -20,23 +20,28 @@ #include "base/TMethodEventJob.h" #include "common/stdexcept.h" -void TestEventQueue::raiseQuitEvent() { addEvent(Event(Event::kQuit)); } +void TestEventQueue::raiseQuitEvent() +{ + addEvent(Event(Event::kQuit)); +} -void TestEventQueue::initQuitTimeout(double timeout) { +void TestEventQueue::initQuitTimeout(double timeout) +{ assert(m_pQuitTimeoutTimer == nullptr); m_pQuitTimeoutTimer = newOneShotTimer(timeout, NULL); adoptHandler( - Event::kTimer, m_pQuitTimeoutTimer, - new TMethodEventJob( - this, &TestEventQueue::handleQuitTimeout)); + Event::kTimer, m_pQuitTimeoutTimer, new TMethodEventJob(this, &TestEventQueue::handleQuitTimeout) + ); } -void TestEventQueue::cleanupQuitTimeout() { +void TestEventQueue::cleanupQuitTimeout() +{ removeHandler(Event::kTimer, m_pQuitTimeoutTimer); deleteTimer(m_pQuitTimeoutTimer); m_pQuitTimeoutTimer = nullptr; } -void TestEventQueue::handleQuitTimeout(const Event &, void *vclient) { +void TestEventQueue::handleQuitTimeout(const Event &, void *vclient) +{ throw std::runtime_error("test event queue timeout"); } diff --git a/src/test/shared/TestEventQueue.h b/src/test/shared/TestEventQueue.h index a4ed56753..a23e182e1 100644 --- a/src/test/shared/TestEventQueue.h +++ b/src/test/shared/TestEventQueue.h @@ -21,9 +21,12 @@ class EventQueueTimer; -class TestEventQueue : public EventQueue { +class TestEventQueue : public EventQueue +{ public: - TestEventQueue() : m_pQuitTimeoutTimer(nullptr) {} + TestEventQueue() : m_pQuitTimeoutTimer(nullptr) + { + } void handleQuitTimeout(const Event &, void *vclient); void raiseQuitEvent(); diff --git a/src/test/shared/gui/TestQtCoreApp.h b/src/test/shared/gui/TestQtCoreApp.h index f63da5cc5..b8809574b 100644 --- a/src/test/shared/gui/TestQtCoreApp.h +++ b/src/test/shared/gui/TestQtCoreApp.h @@ -22,7 +22,10 @@ static int argc = 0; // NOLINT NOSONAR static char **argv = nullptr; // NOLINT NOSONAR -class TestQtCoreApp : public QCoreApplication { +class TestQtCoreApp : public QCoreApplication +{ public: - explicit TestQtCoreApp() : QCoreApplication(argc, argv) {} + explicit TestQtCoreApp() : QCoreApplication(argc, argv) + { + } }; diff --git a/src/test/shared/gui/TestQtFullApp.h b/src/test/shared/gui/TestQtFullApp.h index fb6b3ae85..f68970537 100644 --- a/src/test/shared/gui/TestQtFullApp.h +++ b/src/test/shared/gui/TestQtFullApp.h @@ -25,9 +25,11 @@ static char **argv = nullptr; // NOLINT NOSONAR /** * Prefer using `TestQtCoreApp` instead. */ -class TestQtFullApp : public QApplication { +class TestQtFullApp : public QApplication +{ public: - explicit TestQtFullApp() : QApplication(argc, argv) { + explicit TestQtFullApp() : QApplication(argc, argv) + { #if defined(Q_OS_WIN) #error "this object causes windows ci to freeze" #endif diff --git a/src/test/shared/gui/mocks/AppConfigMock.h b/src/test/shared/gui/mocks/AppConfigMock.h index e62915ab3..36feb6c40 100644 --- a/src/test/shared/gui/mocks/AppConfigMock.h +++ b/src/test/shared/gui/mocks/AppConfigMock.h @@ -23,15 +23,16 @@ #include -class AppConfigMock : public deskflow::gui::IAppConfig { +class AppConfigMock : public deskflow::gui::IAppConfig +{ using ProcessMode = deskflow::gui::ProcessMode; public: - AppConfigMock() { + AppConfigMock() + { ON_CALL(*this, screenName()).WillByDefault(testing::ReturnRef(m_stub)); - ON_CALL(*this, networkInterface()) - .WillByDefault(testing::ReturnRef(m_stub)); + ON_CALL(*this, networkInterface()).WillByDefault(testing::ReturnRef(m_stub)); ON_CALL(*this, logLevelText()).WillByDefault(testing::Return(m_stub)); @@ -76,12 +77,10 @@ public: // Setters // - MOCK_METHOD( - void, setLoadFromSystemScope, (bool loadFromSystemScope), (override)); + MOCK_METHOD(void, setLoadFromSystemScope, (bool loadFromSystemScope), (override)); MOCK_METHOD(void, setScreenName, (const QString &screenName), (override)); MOCK_METHOD(void, setPort, (int port), (override)); - MOCK_METHOD( - void, setNetworkInterface, (const QString &networkInterface), (override)); + MOCK_METHOD(void, setNetworkInterface, (const QString &networkInterface), (override)); MOCK_METHOD(void, setLogLevel, (int logLevel), (override)); MOCK_METHOD(void, setLogToFile, (bool logToFile), (override)); MOCK_METHOD(void, setLogFilename, (const QString &logFilename), (override)); @@ -92,8 +91,7 @@ public: MOCK_METHOD(void, setTlsKeyLength, (int tlsKeyLength), (override)); MOCK_METHOD(void, setTlsEnabled, (bool tlsEnabled), (override)); MOCK_METHOD(void, setLanguageSync, (bool languageSync), (override)); - MOCK_METHOD( - void, setInvertScrollDirection, (bool invertScrollDirection), (override)); + MOCK_METHOD(void, setInvertScrollDirection, (bool invertScrollDirection), (override)); MOCK_METHOD(void, setEnableService, (bool enableService), (override)); MOCK_METHOD(void, setCloseToTray, (bool closeToTray), (override)); MOCK_METHOD(void, setInvertConnection, (bool invertConnection), (override)); diff --git a/src/test/shared/gui/mocks/ServerConfigMock.h b/src/test/shared/gui/mocks/ServerConfigMock.h index 2fa46c3e8..5ecba3dea 100644 --- a/src/test/shared/gui/mocks/ServerConfigMock.h +++ b/src/test/shared/gui/mocks/ServerConfigMock.h @@ -21,15 +21,16 @@ #include -class ServerConfigMock : public deskflow::gui::IServerConfig { +class ServerConfigMock : public deskflow::gui::IServerConfig +{ public: - ServerConfigMock() { + ServerConfigMock() + { ON_CALL(*this, screens()).WillByDefault(testing::ReturnRef(m_screensStub)); } MOCK_METHOD(bool, isFull, (), (const, override)); - MOCK_METHOD( - bool, screenExists, (const QString &screenName), (const, override)); + MOCK_METHOD(bool, screenExists, (const QString &screenName), (const, override)); MOCK_METHOD(bool, save, (const QString &fileName), (const, override)); MOCK_METHOD(void, save, (QFile & file), (const, override)); MOCK_METHOD(bool, enableDragAndDrop, (), (const, override)); diff --git a/src/test/unittests/arch/IArchStringTests.cpp b/src/test/unittests/arch/IArchStringTests.cpp index d23f2d8cb..99cec1c1f 100644 --- a/src/test/unittests/arch/IArchStringTests.cpp +++ b/src/test/unittests/arch/IArchStringTests.cpp @@ -19,12 +19,17 @@ #include -class SampleIArchString : public IArchString { +class SampleIArchString : public IArchString +{ public: - EWideCharEncoding getWideCharEncoding() override { return kUTF16; } + EWideCharEncoding getWideCharEncoding() override + { + return kUTF16; + } }; -TEST(IArchStringTests, convStringWCToMB_will_work_do_simple_conversions) { +TEST(IArchStringTests, convStringWCToMB_will_work_do_simple_conversions) +{ SampleIArchString as; char buff[20]; bool errors; @@ -34,9 +39,8 @@ TEST(IArchStringTests, convStringWCToMB_will_work_do_simple_conversions) { EXPECT_EQ(errors, false); } -TEST( - IArchStringTests, - convStringWCToMB_will_work_do_simple_conversions_noresult) { +TEST(IArchStringTests, convStringWCToMB_will_work_do_simple_conversions_noresult) +{ SampleIArchString as; bool errors; auto converted = as.convStringWCToMB(nullptr, L"Hello", 6, &errors); @@ -44,7 +48,8 @@ TEST( EXPECT_EQ(errors, false); } -TEST(IArchStringTests, convStringMBToWC_will_work_do_simple_conversions) { +TEST(IArchStringTests, convStringMBToWC_will_work_do_simple_conversions) +{ SampleIArchString as; wchar_t buff[20]; bool errors; diff --git a/src/test/unittests/arch/unix/ArchNetworkBSDTests.cpp b/src/test/unittests/arch/unix/ArchNetworkBSDTests.cpp index 23b5e1cce..f528aa09e 100644 --- a/src/test/unittests/arch/unix/ArchNetworkBSDTests.cpp +++ b/src/test/unittests/arch/unix/ArchNetworkBSDTests.cpp @@ -32,17 +32,20 @@ using PollEntries = std::vector; using PollFD = struct pollfd[]; namespace { -struct MockDeps : public ArchNetworkBSD::Deps { +struct MockDeps : public ArchNetworkBSD::Deps +{ std::shared_ptr m_pollFD; - MockDeps() { + MockDeps() + { ON_CALL(*this, makePollFD(_)).WillByDefault([this](nfds_t n) { m_pollFD = ArchNetworkBSD::Deps::makePollFD(n); return m_pollFD; }); } - static std::shared_ptr> makeNice() { + static std::shared_ptr> makeNice() + { return std::make_shared>(); } @@ -54,7 +57,8 @@ struct MockDeps : public ArchNetworkBSD::Deps { }; } // namespace -TEST(ArchNetworkBSDTests, pollSocket_zeroEntries_callsSleep) { +TEST(ArchNetworkBSDTests, pollSocket_zeroEntries_callsSleep) +{ auto deps = MockDeps::makeNice(); ArchNetworkBSD networkBSD(deps); @@ -64,7 +68,8 @@ TEST(ArchNetworkBSDTests, pollSocket_zeroEntries_callsSleep) { EXPECT_EQ(result, 0); } -TEST(ArchNetworkBSDTests, pollSocket_mockAccessError_throws) { +TEST(ArchNetworkBSDTests, pollSocket_mockAccessError_throws) +{ auto deps = MockDeps::makeNice(); ON_CALL(*deps, poll(_, _, _)).WillByDefault([]() { errno = EACCES; @@ -73,14 +78,13 @@ TEST(ArchNetworkBSDTests, pollSocket_mockAccessError_throws) { ArchNetworkBSD networkBSD(deps); PollEntries entries{{nullptr, 0, 0}}; - const auto f = [&] { - networkBSD.pollSocket(entries.data(), static_cast(entries.size()), 1); - }; + const auto f = [&] { networkBSD.pollSocket(entries.data(), static_cast(entries.size()), 1); }; EXPECT_THROW({ f(); }, XArchNetworkAccess); } -TEST(ArchNetworkBSDTests, pollSocket_pfdHasRevents_copiedToEntries) { +TEST(ArchNetworkBSDTests, pollSocket_pfdHasRevents_copiedToEntries) +{ auto deps = MockDeps::makeNice(); ON_CALL(*deps, poll(_, _, _)).WillByDefault([](auto pfd, auto, auto) { pfd[0].revents = POLLIN | POLLOUT | POLLERR | POLLNVAL; @@ -91,12 +95,12 @@ TEST(ArchNetworkBSDTests, pollSocket_pfdHasRevents_copiedToEntries) { networkBSD.pollSocket(entries.data(), static_cast(entries.size()), 1); - const auto expect = IArchNetwork::kPOLLIN | IArchNetwork::kPOLLOUT | - IArchNetwork::kPOLLERR | IArchNetwork::kPOLLNVAL; + const auto expect = IArchNetwork::kPOLLIN | IArchNetwork::kPOLLOUT | IArchNetwork::kPOLLERR | IArchNetwork::kPOLLNVAL; EXPECT_EQ(entries[0].m_revents, expect); } -TEST(ArchNetworkBSDTests, pollSocket_nullSocket_fdIsNegativeOne) { +TEST(ArchNetworkBSDTests, pollSocket_nullSocket_fdIsNegativeOne) +{ auto deps = MockDeps::makeNice(); ArchNetworkBSD networkBSD(deps); PollEntries entries{{nullptr, 0, 0}}; @@ -106,7 +110,8 @@ TEST(ArchNetworkBSDTests, pollSocket_nullSocket_fdIsNegativeOne) { EXPECT_EQ(deps->m_pollFD[0].fd, -1); } -TEST(ArchNetworkBSDTests, pollSocket_socketSet_fdWasSet) { +TEST(ArchNetworkBSDTests, pollSocket_socketSet_fdWasSet) +{ auto deps = MockDeps::makeNice(); ArchNetworkBSD networkBSD(deps); ArchSocketImpl socket{1, 0}; @@ -117,7 +122,8 @@ TEST(ArchNetworkBSDTests, pollSocket_socketSet_fdWasSet) { EXPECT_EQ(deps->m_pollFD[0].fd, 1); } -TEST(ArchNetworkBSDTests, pollSocket_eventHasPollInBit_bitWasSet) { +TEST(ArchNetworkBSDTests, pollSocket_eventHasPollInBit_bitWasSet) +{ auto deps = MockDeps::makeNice(); ArchNetworkBSD networkBSD(deps); ArchSocketImpl socket{1, 0}; @@ -128,7 +134,8 @@ TEST(ArchNetworkBSDTests, pollSocket_eventHasPollInBit_bitWasSet) { EXPECT_EQ(deps->m_pollFD[0].events, POLLIN); } -TEST(ArchNetworkBSDTests, pollSocket_eventHasPollOutBit_bitWasSet) { +TEST(ArchNetworkBSDTests, pollSocket_eventHasPollOutBit_bitWasSet) +{ auto deps = MockDeps::makeNice(); ArchNetworkBSD networkBSD(deps); ArchSocketImpl socket{1, 0}; @@ -139,7 +146,8 @@ TEST(ArchNetworkBSDTests, pollSocket_eventHasPollOutBit_bitWasSet) { EXPECT_EQ(deps->m_pollFD[0].events, POLLOUT); } -TEST(ArchNetworkBSDTests, pollSocket_nullSocket_unblockPipeAppended) { +TEST(ArchNetworkBSDTests, pollSocket_nullSocket_unblockPipeAppended) +{ auto deps = MockDeps::makeNice(); ArchNetworkBSD networkBSD(deps); PollEntries entries{{nullptr, 0, 0}}; @@ -151,7 +159,8 @@ TEST(ArchNetworkBSDTests, pollSocket_nullSocket_unblockPipeAppended) { EXPECT_GT(deps->m_pollFD[1].fd, -1); } -TEST(ArchNetworkBSDTests, pollSocket_unblockPipeReventsError_readCalled) { +TEST(ArchNetworkBSDTests, pollSocket_unblockPipeReventsError_readCalled) +{ const auto unblockPipeIndex = 1; auto deps = MockDeps::makeNice(); ON_CALL(*deps, poll(_, _, _)).WillByDefault([](auto pfd, auto, auto) { @@ -169,7 +178,8 @@ TEST(ArchNetworkBSDTests, pollSocket_unblockPipeReventsError_readCalled) { networkBSD.pollSocket(entries.data(), static_cast(entries.size()), 1); } -TEST(ArchNetworkBSDTests, pollSocket_interruptSystemCall_testCancelThread) { +TEST(ArchNetworkBSDTests, pollSocket_interruptSystemCall_testCancelThread) +{ auto deps = MockDeps::makeNice(); ON_CALL(*deps, poll(_, _, _)).WillByDefault([]() { errno = EINTR; @@ -182,7 +192,8 @@ TEST(ArchNetworkBSDTests, pollSocket_interruptSystemCall_testCancelThread) { networkBSD.pollSocket(entries.data(), static_cast(entries.size()), 1); } -TEST(ArchNetworkBSDTests, isAnyAddr_goodAddress_returnsTrue) { +TEST(ArchNetworkBSDTests, isAnyAddr_goodAddress_returnsTrue) +{ auto deps = MockDeps::makeNice(); ArchNetworkBSD networkBSD(deps); std::unique_ptr addr; @@ -193,7 +204,8 @@ TEST(ArchNetworkBSDTests, isAnyAddr_goodAddress_returnsTrue) { EXPECT_TRUE(result); } -TEST(ArchNetworkBSDTests, isAnyAddr_badAddress_returnsFalse) { +TEST(ArchNetworkBSDTests, isAnyAddr_badAddress_returnsFalse) +{ auto deps = MockDeps::makeNice(); ArchNetworkBSD networkBSD(deps); std::unique_ptr addr; diff --git a/src/test/unittests/base/LogTests.cpp b/src/test/unittests/base/LogTests.cpp index 8925a4a9b..58357e751 100644 --- a/src/test/unittests/base/LogTests.cpp +++ b/src/test/unittests/base/LogTests.cpp @@ -15,7 +15,8 @@ using testing::internal::CaptureStdout; using testing::internal::GetCapturedStderr; using testing::internal::GetCapturedStdout; -TEST(LogTests, print_withErrorLevel_outputIsValid) { +TEST(LogTests, print_withErrorLevel_outputIsValid) +{ CaptureStderr(); Log log(false); @@ -24,7 +25,8 @@ TEST(LogTests, print_withErrorLevel_outputIsValid) { EXPECT_THAT(GetCapturedStderr(), EndsWith("ERROR: test message\n")); } -TEST(LogTests, print_simpleString_outputIsValid) { +TEST(LogTests, print_simpleString_outputIsValid) +{ CaptureStdout(); Log log(false); @@ -33,7 +35,8 @@ TEST(LogTests, print_simpleString_outputIsValid) { EXPECT_THAT(GetCapturedStdout(), EndsWith("test message\n")); } -TEST(LogTests, print_withArgs_outputIsValid) { +TEST(LogTests, print_withArgs_outputIsValid) +{ CaptureStdout(); Log log(false); @@ -42,7 +45,8 @@ TEST(LogTests, print_withArgs_outputIsValid) { EXPECT_THAT(GetCapturedStdout(), HasSubstr("INFO: test 1 1.23 test arg\n")); } -TEST(LogTests, print_withPrintLevel_outputIsValid) { +TEST(LogTests, print_withPrintLevel_outputIsValid) +{ CaptureStdout(); Log log(false); @@ -51,7 +55,8 @@ TEST(LogTests, print_withPrintLevel_outputIsValid) { EXPECT_THAT(GetCapturedStdout(), "test message\n"); } -TEST(LogTests, print_longMessage_outputIsValid) { +TEST(LogTests, print_longMessage_outputIsValid) +{ CaptureStdout(); Log log(false); @@ -61,7 +66,8 @@ TEST(LogTests, print_longMessage_outputIsValid) { EXPECT_THAT(GetCapturedStdout(), HasSubstr("INFO: " + longString + "\n")); } -TEST(LogTests, print_highestLevel_noOutput) { +TEST(LogTests, print_highestLevel_noOutput) +{ CaptureStdout(); Log log(false); @@ -70,22 +76,22 @@ TEST(LogTests, print_highestLevel_noOutput) { EXPECT_EQ(GetCapturedStdout(), ""); } -TEST(LogTests, print_infoWithFileAndLine_outputIsValid) { +TEST(LogTests, print_infoWithFileAndLine_outputIsValid) +{ CaptureStdout(); Log log(false); log.print("test file", 123, LEVEL_INFO "test message"); - EXPECT_THAT( - GetCapturedStdout(), EndsWith("INFO: test message\n\ttest file:123\n")); + EXPECT_THAT(GetCapturedStdout(), EndsWith("INFO: test message\n\ttest file:123\n")); } -TEST(LogTests, print_errorWithFileAndLine_outputIsValid) { +TEST(LogTests, print_errorWithFileAndLine_outputIsValid) +{ CaptureStderr(); Log log(false); log.print("test file", 123, LEVEL_ERR "test message"); - EXPECT_THAT( - GetCapturedStderr(), EndsWith("ERROR: test message\n\ttest file:123\n")); + EXPECT_THAT(GetCapturedStderr(), EndsWith("ERROR: test message\n\ttest file:123\n")); } diff --git a/src/test/unittests/base/PathTests.cpp b/src/test/unittests/base/PathTests.cpp index 35a207d15..2c024f806 100644 --- a/src/test/unittests/base/PathTests.cpp +++ b/src/test/unittests/base/PathTests.cpp @@ -23,12 +23,12 @@ const std::string testDir = "tmp/test"; const std::wstring testDirW = L"tmp/test"; -TEST(PathTests, open_file_using_path) { +TEST(PathTests, open_file_using_path) +{ std::string utf8FileName = testDir + "/тіás.txt"; #if SYSAPI_WIN32 // Windows uses UTF-16 for file path and names - std::wstring fileName = - testDirW + L"/\x0442\x0456\x00E1\x0073\x002E\x0074\x0078\x0074"; + std::wstring fileName = testDirW + L"/\x0442\x0456\x00E1\x0073\x002E\x0074\x0078\x0074"; #else std::string fileName = utf8FileName; #endif diff --git a/src/test/unittests/base/StringTests.cpp b/src/test/unittests/base/StringTests.cpp index 9b58e5b71..b029fbf2d 100644 --- a/src/test/unittests/base/StringTests.cpp +++ b/src/test/unittests/base/StringTests.cpp @@ -21,7 +21,8 @@ using namespace deskflow; -TEST(StringTests, format_formatWithArguments_formatedString) { +TEST(StringTests, format_formatWithArguments_formatedString) +{ const char *format = "%%%{1}=%{2}"; const char *arg1 = "answer"; const char *arg2 = "42"; @@ -31,7 +32,8 @@ TEST(StringTests, format_formatWithArguments_formatedString) { EXPECT_EQ("%answer=42", result); } -TEST(StringTests, findReplaceAll_inputString_replacedString) { +TEST(StringTests, findReplaceAll_inputString_replacedString) +{ String subject = "foobar"; String find = "bar"; String replace = "baz"; @@ -41,7 +43,8 @@ TEST(StringTests, findReplaceAll_inputString_replacedString) { EXPECT_EQ("foobaz", subject); } -TEST(StringTests, sprintf_formatWithArgument_formatedString) { +TEST(StringTests, sprintf_formatWithArgument_formatedString) +{ const char *format = "%s=%d"; const char *arg1 = "answer"; int arg2 = 42; @@ -51,7 +54,8 @@ TEST(StringTests, sprintf_formatWithArgument_formatedString) { EXPECT_EQ("answer=42", result); } -TEST(StringTests, toHex_plaintext_hexString) { +TEST(StringTests, toHex_plaintext_hexString) +{ String subject = "foobar"; int width = 2; @@ -60,7 +64,8 @@ TEST(StringTests, toHex_plaintext_hexString) { EXPECT_EQ("666f6f626172", subject); } -TEST(StringTests, uppercase_lowercaseInput_uppercaseOutput) { +TEST(StringTests, uppercase_lowercaseInput_uppercaseOutput) +{ String subject = "12foo3BaR"; string::uppercase(subject); @@ -68,7 +73,8 @@ TEST(StringTests, uppercase_lowercaseInput_uppercaseOutput) { EXPECT_EQ("12FOO3BAR", subject); } -TEST(StringTests, removeChar_inputString_removeAllSpecifiedCharactors) { +TEST(StringTests, removeChar_inputString_removeAllSpecifiedCharactors) +{ String subject = "foobar"; const char c = 'o'; @@ -77,7 +83,8 @@ TEST(StringTests, removeChar_inputString_removeAllSpecifiedCharactors) { EXPECT_EQ("fbar", subject); } -TEST(StringTests, intToString_inputInt_outputString) { +TEST(StringTests, intToString_inputInt_outputString) +{ size_t value = 123; String number = string::sizeTypeToString(value); @@ -85,7 +92,8 @@ TEST(StringTests, intToString_inputInt_outputString) { EXPECT_EQ("123", number); } -TEST(StringTests, stringToUint_inputString_outputInt) { +TEST(StringTests, stringToUint_inputString_outputInt) +{ String number = "123"; size_t value = string::stringToSizeType(number); @@ -93,7 +101,8 @@ TEST(StringTests, stringToUint_inputString_outputInt) { EXPECT_EQ(123, value); } -TEST(StringTests, splitString_twoSeparator_returnThreeParts) { +TEST(StringTests, splitString_twoSeparator_returnThreeParts) +{ String string = "stub1:stub2:stub3"; std::vector results = string::splitString(string, ':'); @@ -104,7 +113,8 @@ TEST(StringTests, splitString_twoSeparator_returnThreeParts) { EXPECT_EQ("stub3", results[2]); } -TEST(StringTests, splitString_oneSeparator_returnTwoParts) { +TEST(StringTests, splitString_oneSeparator_returnTwoParts) +{ String string = "stub1:stub2"; std::vector results = string::splitString(string, ':'); @@ -114,7 +124,8 @@ TEST(StringTests, splitString_oneSeparator_returnTwoParts) { EXPECT_EQ("stub2", results[1]); } -TEST(StringTests, splitString_noSeparator_returnOriginalString) { +TEST(StringTests, splitString_noSeparator_returnOriginalString) +{ String string = "stub1"; std::vector results = string::splitString(string, ':'); @@ -123,7 +134,8 @@ TEST(StringTests, splitString_noSeparator_returnOriginalString) { EXPECT_EQ("stub1", results[0]); } -TEST(StringTests, splitString_emptyString_returnEmptyVector) { +TEST(StringTests, splitString_emptyString_returnEmptyVector) +{ String string; std::vector results = string::splitString(string, ':'); @@ -131,7 +143,8 @@ TEST(StringTests, splitString_emptyString_returnEmptyVector) { EXPECT_EQ(0, results.size()); } -TEST(StringTests, splitString_tailSeparator_returnTwoParts) { +TEST(StringTests, splitString_tailSeparator_returnTwoParts) +{ String string = "stub1:stub2:"; std::vector results = string::splitString(string, ':'); @@ -141,7 +154,8 @@ TEST(StringTests, splitString_tailSeparator_returnTwoParts) { EXPECT_EQ("stub2", results[1]); } -TEST(StringTests, splitString_headSeparator_returnTwoParts) { +TEST(StringTests, splitString_headSeparator_returnTwoParts) +{ String string = ":stub1:stub2"; std::vector results = string::splitString(string, ':'); @@ -151,7 +165,8 @@ TEST(StringTests, splitString_headSeparator_returnTwoParts) { EXPECT_EQ("stub2", results[1]); } -TEST(StringTests, splitString_headAndTailSeparators_returnTwoParts) { +TEST(StringTests, splitString_headAndTailSeparators_returnTwoParts) +{ String string = ":stub1:stub2:"; std::vector results = string::splitString(string, ':'); diff --git a/src/test/unittests/base/UnicodeTests.cpp b/src/test/unittests/base/UnicodeTests.cpp index 0c4b9d5d5..2154a070c 100644 --- a/src/test/unittests/base/UnicodeTests.cpp +++ b/src/test/unittests/base/UnicodeTests.cpp @@ -20,22 +20,24 @@ #include -TEST(UnicodeTests, doUTF32ToUTF8_will_convert_simple_string) { +TEST(UnicodeTests, doUTF32ToUTF8_will_convert_simple_string) +{ bool errors; - auto result = Unicode::UTF32ToUTF8( - String("h\0\0\0e\0\0\0l\0\0\0l\0\0\0o\0\0\0", 20), &errors); + auto result = Unicode::UTF32ToUTF8(String("h\0\0\0e\0\0\0l\0\0\0l\0\0\0o\0\0\0", 20), &errors); EXPECT_FALSE(errors); EXPECT_STREQ(result.c_str(), "hello"); } -TEST(UnicodeTests, doUTF16ToUTF8_will_convert_simple_string) { +TEST(UnicodeTests, doUTF16ToUTF8_will_convert_simple_string) +{ bool errors; auto result = Unicode::UTF16ToUTF8(String("h\0e\0l\0l\0o\0", 10), &errors); EXPECT_FALSE(errors); EXPECT_STREQ(result.c_str(), "hello"); } -TEST(UnicodeTests, doUCS2ToUTF8_will_convert_simple_string_kUCS2) { +TEST(UnicodeTests, doUCS2ToUTF8_will_convert_simple_string_kUCS2) +{ bool errors; auto result = Unicode::textToUTF8("hello", &errors, IArchString::kUCS2); EXPECT_FALSE(errors); @@ -46,7 +48,8 @@ TEST(UnicodeTests, doUCS2ToUTF8_will_convert_simple_string_kUCS2) { #endif // _WIN32 } -TEST(UnicodeTests, doUCS2ToUTF8_will_convert_simple_string_any_platform) { +TEST(UnicodeTests, doUCS2ToUTF8_will_convert_simple_string_any_platform) +{ bool errors; auto result = Unicode::textToUTF8("hello", &errors); EXPECT_FALSE(errors); diff --git a/src/test/unittests/base/XBaseTests.cpp b/src/test/unittests/base/XBaseTests.cpp index dfa664675..ec7fc3ad2 100644 --- a/src/test/unittests/base/XBaseTests.cpp +++ b/src/test/unittests/base/XBaseTests.cpp @@ -2,7 +2,8 @@ #include -TEST(XBaseTests, what_emptyWhat_returnsWhatFromGetWhat) { +TEST(XBaseTests, what_emptyWhat_returnsWhatFromGetWhat) +{ XBase xbase; const char *result = xbase.what(); @@ -10,7 +11,8 @@ TEST(XBaseTests, what_emptyWhat_returnsWhatFromGetWhat) { EXPECT_STREQ("", result); } -TEST(XBaseTests, what_nonEmptyWhat_returnsWhatFromGetWhat) { +TEST(XBaseTests, what_nonEmptyWhat_returnsWhatFromGetWhat) +{ XBase xbase("test"); const char *result = xbase.what(); diff --git a/src/test/unittests/deskflow/ArgParserTests.cpp b/src/test/unittests/deskflow/ArgParserTests.cpp index 11eeae0ae..d50da3d93 100644 --- a/src/test/unittests/deskflow/ArgParserTests.cpp +++ b/src/test/unittests/deskflow/ArgParserTests.cpp @@ -26,7 +26,8 @@ #include -TEST(ArgParserTests, isArg_abbreviationsArg_returnTrue) { +TEST(ArgParserTests, isArg_abbreviationsArg_returnTrue) +{ int i = 1; const int argc = 2; const char *argv[argc] = {"stub", "-t"}; @@ -35,7 +36,8 @@ TEST(ArgParserTests, isArg_abbreviationsArg_returnTrue) { EXPECT_EQ(true, result); } -TEST(ArgParserTests, isArg_fullArg_returnTrue) { +TEST(ArgParserTests, isArg_fullArg_returnTrue) +{ int i = 1; const int argc = 2; const char *argv[argc] = {"stub", "--test"}; @@ -44,7 +46,8 @@ TEST(ArgParserTests, isArg_fullArg_returnTrue) { EXPECT_EQ(true, result); } -TEST(ArgParserTests, isArg_missingArgs_returnFalse) { +TEST(ArgParserTests, isArg_missingArgs_returnFalse) +{ int i = 1; const int argc = 2; const char *argv[argc] = {"stub", "-t"}; @@ -58,7 +61,8 @@ TEST(ArgParserTests, isArg_missingArgs_returnFalse) { EXPECT_EQ(true, argsBase.m_shouldExitFail); } -TEST(ArgParserTests, searchDoubleQuotes_doubleQuotedArg_returnTrue) { +TEST(ArgParserTests, searchDoubleQuotes_doubleQuotedArg_returnTrue) +{ String command("\"stub\""); size_t left = 0; size_t right = 0; @@ -70,7 +74,8 @@ TEST(ArgParserTests, searchDoubleQuotes_doubleQuotedArg_returnTrue) { EXPECT_EQ(5, right); } -TEST(ArgParserTests, searchDoubleQuotes_noDoubleQuotedArg_returnfalse) { +TEST(ArgParserTests, searchDoubleQuotes_noDoubleQuotedArg_returnfalse) +{ String command("stub"); size_t left = 0; size_t right = 0; @@ -82,7 +87,8 @@ TEST(ArgParserTests, searchDoubleQuotes_noDoubleQuotedArg_returnfalse) { EXPECT_EQ(0, right); } -TEST(ArgParserTests, searchDoubleQuotes_oneDoubleQuoteArg_returnfalse) { +TEST(ArgParserTests, searchDoubleQuotes_oneDoubleQuoteArg_returnfalse) +{ String command("\"stub"); size_t left = 0; size_t right = 0; @@ -94,7 +100,8 @@ TEST(ArgParserTests, searchDoubleQuotes_oneDoubleQuoteArg_returnfalse) { EXPECT_EQ(0, right); } -TEST(ArgParserTests, splitCommandString_oneArg_returnArgv) { +TEST(ArgParserTests, splitCommandString_oneArg_returnArgv) +{ String command("stub"); std::vector argv; @@ -104,7 +111,8 @@ TEST(ArgParserTests, splitCommandString_oneArg_returnArgv) { EXPECT_EQ("stub", argv.at(0)); } -TEST(ArgParserTests, splitCommandString_twoArgs_returnArgv) { +TEST(ArgParserTests, splitCommandString_twoArgs_returnArgv) +{ String command("stub1 stub2"); std::vector argv; @@ -115,7 +123,8 @@ TEST(ArgParserTests, splitCommandString_twoArgs_returnArgv) { EXPECT_EQ("stub2", argv.at(1)); } -TEST(ArgParserTests, splitCommandString_doubleQuotedArgs_returnArgv) { +TEST(ArgParserTests, splitCommandString_doubleQuotedArgs_returnArgv) +{ String command("\"stub1\" stub2 \"stub3\""); std::vector argv; @@ -127,7 +136,8 @@ TEST(ArgParserTests, splitCommandString_doubleQuotedArgs_returnArgv) { EXPECT_EQ("stub3", argv.at(2)); } -TEST(ArgParserTests, splitCommandString_spaceDoubleQuotedArgs_returnArgv) { +TEST(ArgParserTests, splitCommandString_spaceDoubleQuotedArgs_returnArgv) +{ String command("\"stub1\" stub2 \"stub3 space\""); std::vector argv; @@ -139,7 +149,8 @@ TEST(ArgParserTests, splitCommandString_spaceDoubleQuotedArgs_returnArgv) { EXPECT_EQ("stub3 space", argv.at(2)); } -TEST(ArgParserTests, getArgv_stringArray_return2DArray) { +TEST(ArgParserTests, getArgv_stringArray_return2DArray) +{ std::vector argArray; argArray.push_back("stub1"); argArray.push_back("stub2"); @@ -157,7 +168,8 @@ TEST(ArgParserTests, getArgv_stringArray_return2DArray) { delete[] argv; } -TEST(ArgParserTests, assembleCommand_stringArray_returnCommand) { +TEST(ArgParserTests, assembleCommand_stringArray_returnCommand) +{ std::vector argArray; argArray.push_back("stub1"); argArray.push_back("stub2"); @@ -166,7 +178,8 @@ TEST(ArgParserTests, assembleCommand_stringArray_returnCommand) { EXPECT_EQ("stub1 stub2", command); } -TEST(ArgParserTests, assembleCommand_ignoreSecondArg_returnCommand) { +TEST(ArgParserTests, assembleCommand_ignoreSecondArg_returnCommand) +{ std::vector argArray; argArray.push_back("stub1"); argArray.push_back("stub2"); @@ -175,9 +188,8 @@ TEST(ArgParserTests, assembleCommand_ignoreSecondArg_returnCommand) { EXPECT_EQ("stub1", command); } -TEST( - ArgParserTests, - assembleCommand_ignoreSecondArgWithOneParameter_returnCommand) { +TEST(ArgParserTests, assembleCommand_ignoreSecondArgWithOneParameter_returnCommand) +{ std::vector argArray; argArray.push_back("stub1"); argArray.push_back("stub2"); @@ -188,7 +200,8 @@ TEST( EXPECT_EQ("stub1 stub4", command); } -TEST(ArgParserTests, assembleCommand_stringArrayWithSpace_returnCommand) { +TEST(ArgParserTests, assembleCommand_stringArrayWithSpace_returnCommand) +{ std::vector argArray; argArray.push_back("stub1 space"); argArray.push_back("stub2"); @@ -198,16 +211,15 @@ TEST(ArgParserTests, assembleCommand_stringArrayWithSpace_returnCommand) { EXPECT_EQ("\"stub1 space\" stub2 \"stub3 space\"", command); } -TEST(ArgParserTests, parseToolArgs_matches_correspondingly) { +TEST(ArgParserTests, parseToolArgs_matches_correspondingly) +{ ArgParser parser(nullptr); std::map> tests = { - {"--get-active-desktop", - [](ToolArgs const &a) { return a.m_printActiveDesktopName; }}, - {"--get-installed-dir", - [](ToolArgs const &a) { return a.m_getInstalledDir; }}, - {"--get-profile-dir", - [](ToolArgs const &a) { return a.m_getProfileDir; }}, - {"--get-arch", [](ToolArgs const &a) { return a.m_getArch; }}}; + {"--get-active-desktop", [](ToolArgs const &a) { return a.m_printActiveDesktopName; }}, + {"--get-installed-dir", [](ToolArgs const &a) { return a.m_getInstalledDir; }}, + {"--get-profile-dir", [](ToolArgs const &a) { return a.m_getProfileDir; }}, + {"--get-arch", [](ToolArgs const &a) { return a.m_getArch; }} + }; for (auto const &test : tests) { ToolArgs toolArgs; EXPECT_FALSE(test.second(toolArgs)); @@ -220,7 +232,8 @@ TEST(ArgParserTests, parseToolArgs_matches_correspondingly) { EXPECT_FALSE(parser.parseToolArgs(toolArgs, 2, twoArgs.data())); } -TEST(ArgParserTests, parseServerArgs_parses_each_category) { +TEST(ArgParserTests, parseServerArgs_parses_each_category) +{ ArgParser parser(nullptr); deskflow::ServerArgs args; args.m_daemon = false; @@ -234,13 +247,14 @@ TEST(ArgParserTests, parseServerArgs_parses_each_category) { "--no-xinitthreads" #endif , - "--res-w", "888"}; - EXPECT_TRUE( - parser.parseServerArgs(args, sizeof(argv) / sizeof(argv[0]), argv)); + "--res-w", "888" + }; + EXPECT_TRUE(parser.parseServerArgs(args, sizeof(argv) / sizeof(argv[0]), argv)); EXPECT_EQ(args.m_shouldExitOk, true); } -TEST(ArgParserTests, parseClientArgs_parses_single_help) { +TEST(ArgParserTests, parseClientArgs_parses_single_help) +{ ArgParser parser(nullptr); deskflow::ClientArgs args; args.m_daemon = false; @@ -257,8 +271,8 @@ TEST(ArgParserTests, parseClientArgs_parses_single_help) { , "--res-w", "888", - "127.0.0.1"}; - EXPECT_TRUE( - parser.parseClientArgs(args, sizeof(argv) / sizeof(argv[0]), argv)); + "127.0.0.1" + }; + EXPECT_TRUE(parser.parseClientArgs(args, sizeof(argv) / sizeof(argv[0]), argv)); EXPECT_EQ(args.m_shouldExitOk, true); } diff --git a/src/test/unittests/deskflow/ClientArgsParsingTests.cpp b/src/test/unittests/deskflow/ClientArgsParsingTests.cpp index ace8e6d82..c3bf94519 100644 --- a/src/test/unittests/deskflow/ClientArgsParsingTests.cpp +++ b/src/test/unittests/deskflow/ClientArgsParsingTests.cpp @@ -27,18 +27,21 @@ using ::testing::_; using ::testing::Invoke; using ::testing::NiceMock; -bool client_stubParseGenericArgs(int, const char *const *, int &) { +bool client_stubParseGenericArgs(int, const char *const *, int &) +{ return false; } -bool client_stubCheckUnexpectedArgs() { return false; } +bool client_stubCheckUnexpectedArgs() +{ + return false; +} -TEST(ClientArgsParsingTests, parseClientArgs_yScrollArg_setYScroll) { +TEST(ClientArgsParsingTests, parseClientArgs_yScrollArg_setYScroll) +{ NiceMock argParser; - ON_CALL(argParser, parseGenericArgs(_, _, _)) - .WillByDefault(Invoke(client_stubParseGenericArgs)); - ON_CALL(argParser, checkUnexpectedArgs()) - .WillByDefault(Invoke(client_stubCheckUnexpectedArgs)); + ON_CALL(argParser, parseGenericArgs(_, _, _)).WillByDefault(Invoke(client_stubParseGenericArgs)); + ON_CALL(argParser, checkUnexpectedArgs()).WillByDefault(Invoke(client_stubCheckUnexpectedArgs)); deskflow::ClientArgs clientArgs; const int argc = 3; const char *kYScrollCmd[argc] = {"stub", "--yscroll", "1"}; @@ -48,12 +51,11 @@ TEST(ClientArgsParsingTests, parseClientArgs_yScrollArg_setYScroll) { EXPECT_EQ(1, clientArgs.m_yscroll); } -TEST(ClientArgsParsingTests, parseClientArgs_setLangSync) { +TEST(ClientArgsParsingTests, parseClientArgs_setLangSync) +{ NiceMock argParser; - ON_CALL(argParser, parseGenericArgs(_, _, _)) - .WillByDefault(Invoke(client_stubParseGenericArgs)); - ON_CALL(argParser, checkUnexpectedArgs()) - .WillByDefault(Invoke(client_stubCheckUnexpectedArgs)); + ON_CALL(argParser, parseGenericArgs(_, _, _)).WillByDefault(Invoke(client_stubParseGenericArgs)); + ON_CALL(argParser, checkUnexpectedArgs()).WillByDefault(Invoke(client_stubCheckUnexpectedArgs)); deskflow::ClientArgs clientArgs; clientArgs.m_enableLangSync = false; const int argc = 2; @@ -64,31 +66,28 @@ TEST(ClientArgsParsingTests, parseClientArgs_setLangSync) { EXPECT_TRUE(clientArgs.m_enableLangSync); } -TEST(ClientArgsParsingTests, parseClientArgs_setInvertScroll) { +TEST(ClientArgsParsingTests, parseClientArgs_setInvertScroll) +{ NiceMock argParser; deskflow::ClientArgs clientArgs; const int argc = 2; std::array kLangCmd = {"stub", "--invert-scroll"}; argParser.parseClientArgs(clientArgs, argc, kLangCmd.data()); - EXPECT_EQ( - clientArgs.m_clientScrollDirection, - deskflow::ClientScrollDirection::INVERT_SERVER); + EXPECT_EQ(clientArgs.m_clientScrollDirection, deskflow::ClientScrollDirection::INVERT_SERVER); } -TEST(ClientArgsParsingTests, parseClientArgs_setCommonArgs) { +TEST(ClientArgsParsingTests, parseClientArgs_setCommonArgs) +{ NiceMock argParser; - ON_CALL(argParser, parseGenericArgs(_, _, _)) - .WillByDefault(Invoke(client_stubParseGenericArgs)); - ON_CALL(argParser, checkUnexpectedArgs()) - .WillByDefault(Invoke(client_stubCheckUnexpectedArgs)); + ON_CALL(argParser, parseGenericArgs(_, _, _)).WillByDefault(Invoke(client_stubParseGenericArgs)); + ON_CALL(argParser, checkUnexpectedArgs()).WillByDefault(Invoke(client_stubCheckUnexpectedArgs)); deskflow::ClientArgs clientArgs; clientArgs.m_enableLangSync = false; const int argc = 9; - std::array kLangCmd = { - "stub", "--enable-crypto", "--profile-dir", - "profileDir", "--plugin-dir", "pluginDir", - "--tls-cert", "tlsCertPath", "--prevent-sleep"}; + std::array kLangCmd = {"stub", "--enable-crypto", "--profile-dir", + "profileDir", "--plugin-dir", "pluginDir", + "--tls-cert", "tlsCertPath", "--prevent-sleep"}; argParser.parseClientArgs(clientArgs, argc, kLangCmd.data()); @@ -99,12 +98,11 @@ TEST(ClientArgsParsingTests, parseClientArgs_setCommonArgs) { EXPECT_TRUE(clientArgs.m_preventSleep); } -TEST(ClientArgsParsingTests, parseClientArgs_addressArg_setDeskflowAddress) { +TEST(ClientArgsParsingTests, parseClientArgs_addressArg_setDeskflowAddress) +{ NiceMock argParser; - ON_CALL(argParser, parseGenericArgs(_, _, _)) - .WillByDefault(Invoke(client_stubParseGenericArgs)); - ON_CALL(argParser, checkUnexpectedArgs()) - .WillByDefault(Invoke(client_stubCheckUnexpectedArgs)); + ON_CALL(argParser, parseGenericArgs(_, _, _)).WillByDefault(Invoke(client_stubParseGenericArgs)); + ON_CALL(argParser, checkUnexpectedArgs()).WillByDefault(Invoke(client_stubCheckUnexpectedArgs)); deskflow::ClientArgs clientArgs; const int argc = 2; const char *kAddressCmd[argc] = {"stub", "mock_address"}; @@ -115,12 +113,11 @@ TEST(ClientArgsParsingTests, parseClientArgs_addressArg_setDeskflowAddress) { EXPECT_EQ(true, result); } -TEST(ClientArgsParsingTests, parseClientArgs_noAddressArg_returnFalse) { +TEST(ClientArgsParsingTests, parseClientArgs_noAddressArg_returnFalse) +{ NiceMock argParser; - ON_CALL(argParser, parseGenericArgs(_, _, _)) - .WillByDefault(Invoke(client_stubParseGenericArgs)); - ON_CALL(argParser, checkUnexpectedArgs()) - .WillByDefault(Invoke(client_stubCheckUnexpectedArgs)); + ON_CALL(argParser, parseGenericArgs(_, _, _)).WillByDefault(Invoke(client_stubParseGenericArgs)); + ON_CALL(argParser, checkUnexpectedArgs()).WillByDefault(Invoke(client_stubCheckUnexpectedArgs)); deskflow::ClientArgs clientArgs; const int argc = 1; const char *kNoAddressCmd[argc] = {"stub"}; @@ -130,12 +127,11 @@ TEST(ClientArgsParsingTests, parseClientArgs_noAddressArg_returnFalse) { EXPECT_FALSE(result); } -TEST(ClientArgsParsingTests, parseClientArgs_unrecognizedArg_returnFalse) { +TEST(ClientArgsParsingTests, parseClientArgs_unrecognizedArg_returnFalse) +{ NiceMock argParser; - ON_CALL(argParser, parseGenericArgs(_, _, _)) - .WillByDefault(Invoke(client_stubParseGenericArgs)); - ON_CALL(argParser, checkUnexpectedArgs()) - .WillByDefault(Invoke(client_stubCheckUnexpectedArgs)); + ON_CALL(argParser, parseGenericArgs(_, _, _)).WillByDefault(Invoke(client_stubParseGenericArgs)); + ON_CALL(argParser, checkUnexpectedArgs()).WillByDefault(Invoke(client_stubCheckUnexpectedArgs)); deskflow::ClientArgs clientArgs; const int argc = 3; const char *kUnrecognizedCmd[argc] = {"stub", "mock_arg", "mock_address"}; diff --git a/src/test/unittests/deskflow/ClipboardChunkTests.cpp b/src/test/unittests/deskflow/ClipboardChunkTests.cpp index bd567adfe..08eb204a5 100644 --- a/src/test/unittests/deskflow/ClipboardChunkTests.cpp +++ b/src/test/unittests/deskflow/ClipboardChunkTests.cpp @@ -20,7 +20,8 @@ #include -TEST(ClipboardChunkTests, start_formatStartChunk) { +TEST(ClipboardChunkTests, start_formatStartChunk) +{ ClipboardID id = 0; UInt32 sequence = 0; String mockDataSize("10"); @@ -38,7 +39,8 @@ TEST(ClipboardChunkTests, start_formatStartChunk) { delete chunk; } -TEST(ClipboardChunkTests, data_formatDataChunk) { +TEST(ClipboardChunkTests, data_formatDataChunk) +{ ClipboardID id = 0; UInt32 sequence = 1; String mockData("mock data"); @@ -61,7 +63,8 @@ TEST(ClipboardChunkTests, data_formatDataChunk) { delete chunk; } -TEST(ClipboardChunkTests, end_formatDataChunk) { +TEST(ClipboardChunkTests, end_formatDataChunk) +{ ClipboardID id = 1; UInt32 sequence = 1; ClipboardChunk *chunk = ClipboardChunk::end(id, sequence); diff --git a/src/test/unittests/deskflow/ClipboardTests.cpp b/src/test/unittests/deskflow/ClipboardTests.cpp index c2b37628a..15230f2ff 100644 --- a/src/test/unittests/deskflow/ClipboardTests.cpp +++ b/src/test/unittests/deskflow/ClipboardTests.cpp @@ -20,7 +20,8 @@ #include -TEST(ClipboardTests, empty_openCalled_returnsTrue) { +TEST(ClipboardTests, empty_openCalled_returnsTrue) +{ Clipboard clipboard; clipboard.open(0); @@ -29,7 +30,8 @@ TEST(ClipboardTests, empty_openCalled_returnsTrue) { EXPECT_EQ(true, actual); } -TEST(ClipboardTests, empty_singleFormat_hasReturnsFalse) { +TEST(ClipboardTests, empty_singleFormat_hasReturnsFalse) +{ Clipboard clipboard; clipboard.open(0); clipboard.add(Clipboard::kText, "synergy rocks!"); @@ -40,7 +42,8 @@ TEST(ClipboardTests, empty_singleFormat_hasReturnsFalse) { EXPECT_FALSE(actual); } -TEST(ClipboardTests, add_newValue_valueWasStored) { +TEST(ClipboardTests, add_newValue_valueWasStored) +{ Clipboard clipboard; clipboard.open(0); @@ -50,7 +53,8 @@ TEST(ClipboardTests, add_newValue_valueWasStored) { EXPECT_EQ("synergy rocks!", actual); } -TEST(ClipboardTests, add_replaceValue_valueWasReplaced) { +TEST(ClipboardTests, add_replaceValue_valueWasReplaced) +{ Clipboard clipboard; clipboard.open(0); @@ -61,7 +65,8 @@ TEST(ClipboardTests, add_replaceValue_valueWasReplaced) { EXPECT_EQ("maxivista sucks", actual); } -TEST(ClipboardTests, open_timeIsZero_returnsTrue) { +TEST(ClipboardTests, open_timeIsZero_returnsTrue) +{ Clipboard clipboard; bool actual = clipboard.open(0); @@ -69,7 +74,8 @@ TEST(ClipboardTests, open_timeIsZero_returnsTrue) { EXPECT_EQ(true, actual); } -TEST(ClipboardTests, open_timeIsOne_returnsTrue) { +TEST(ClipboardTests, open_timeIsOne_returnsTrue) +{ Clipboard clipboard; bool actual = clipboard.open(1); @@ -77,7 +83,8 @@ TEST(ClipboardTests, open_timeIsOne_returnsTrue) { EXPECT_EQ(true, actual); } -TEST(ClipboardTests, close_isOpen_noErrors) { +TEST(ClipboardTests, close_isOpen_noErrors) +{ Clipboard clipboard; clipboard.open(0); @@ -86,7 +93,8 @@ TEST(ClipboardTests, close_isOpen_noErrors) { // can't assert anything } -TEST(ClipboardTests, getTime_openWithNoEmpty_returnsZero) { +TEST(ClipboardTests, getTime_openWithNoEmpty_returnsZero) +{ Clipboard clipboard; clipboard.open(1); @@ -95,7 +103,8 @@ TEST(ClipboardTests, getTime_openWithNoEmpty_returnsZero) { EXPECT_EQ(0, actual); } -TEST(ClipboardTests, getTime_openAndEmpty_returnsOne) { +TEST(ClipboardTests, getTime_openAndEmpty_returnsOne) +{ Clipboard clipboard; clipboard.open(1); clipboard.empty(); @@ -105,7 +114,8 @@ TEST(ClipboardTests, getTime_openAndEmpty_returnsOne) { EXPECT_EQ(1, actual); } -TEST(ClipboardTests, has_withFormatAdded_returnsTrue) { +TEST(ClipboardTests, has_withFormatAdded_returnsTrue) +{ Clipboard clipboard; clipboard.open(0); clipboard.add(IClipboard::kText, "synergy rocks!"); @@ -115,7 +125,8 @@ TEST(ClipboardTests, has_withFormatAdded_returnsTrue) { EXPECT_EQ(true, actual); } -TEST(ClipboardTests, has_withNoFormats_returnsFalse) { +TEST(ClipboardTests, has_withNoFormats_returnsFalse) +{ Clipboard clipboard; clipboard.open(0); @@ -124,7 +135,8 @@ TEST(ClipboardTests, has_withNoFormats_returnsFalse) { EXPECT_FALSE(actual); } -TEST(ClipboardTests, get_withNoFormats_returnsEmpty) { +TEST(ClipboardTests, get_withNoFormats_returnsEmpty) +{ Clipboard clipboard; clipboard.open(0); @@ -133,7 +145,8 @@ TEST(ClipboardTests, get_withNoFormats_returnsEmpty) { EXPECT_EQ("", actual); } -TEST(ClipboardTests, get_withFormatAdded_returnsExpected) { +TEST(ClipboardTests, get_withFormatAdded_returnsExpected) +{ Clipboard clipboard; clipboard.open(0); clipboard.add(IClipboard::kText, "synergy rocks!"); @@ -143,7 +156,8 @@ TEST(ClipboardTests, get_withFormatAdded_returnsExpected) { EXPECT_EQ("synergy rocks!", actual); } -TEST(ClipboardTests, marshall_addNotCalled_firstCharIsZero) { +TEST(ClipboardTests, marshall_addNotCalled_firstCharIsZero) +{ Clipboard clipboard; String actual = clipboard.marshall(); @@ -153,7 +167,8 @@ TEST(ClipboardTests, marshall_addNotCalled_firstCharIsZero) { EXPECT_EQ(0, (int)actual[0]); } -TEST(ClipboardTests, marshall_withTextAdded_typeCharIsText) { +TEST(ClipboardTests, marshall_withTextAdded_typeCharIsText) +{ Clipboard clipboard; clipboard.open(0); clipboard.add(IClipboard::kText, "synergy rocks!"); @@ -165,7 +180,8 @@ TEST(ClipboardTests, marshall_withTextAdded_typeCharIsText) { EXPECT_EQ(IClipboard::kText, (int)actual[7]); } -TEST(ClipboardTests, marshall_withTextAdded_lastSizeCharIs14) { +TEST(ClipboardTests, marshall_withTextAdded_lastSizeCharIs14) +{ Clipboard clipboard; clipboard.open(0); clipboard.add(IClipboard::kText, "synergy rocks!"); // 14 chars @@ -179,7 +195,8 @@ TEST(ClipboardTests, marshall_withTextAdded_lastSizeCharIs14) { // TODO: there's some integer -> char encoding going on here. i find it // hard to believe that the clipboard is the only thing doing this. maybe // we should refactor this stuff out of the clipboard. -TEST(ClipboardTests, marshall_withTextSize285_sizeCharsValid) { +TEST(ClipboardTests, marshall_withTextSize285_sizeCharsValid) +{ // 285 chars String data; data.append("Synergy is Free and Open Source Software that lets you "); @@ -208,7 +225,8 @@ TEST(ClipboardTests, marshall_withTextSize285_sizeCharsValid) { EXPECT_EQ(29, actual[11]); // 285 - 256 = 29 } -TEST(ClipboardTests, marshall_withHtmlAdded_typeCharIsHtml) { +TEST(ClipboardTests, marshall_withHtmlAdded_typeCharIsHtml) +{ Clipboard clipboard; clipboard.open(0); clipboard.add(IClipboard::kHTML, "html sucks"); @@ -220,7 +238,8 @@ TEST(ClipboardTests, marshall_withHtmlAdded_typeCharIsHtml) { EXPECT_EQ(IClipboard::kHTML, (int)actual[7]); } -TEST(ClipboardTests, marshall_withHtmlAndText_has2Formats) { +TEST(ClipboardTests, marshall_withHtmlAndText_has2Formats) +{ Clipboard clipboard; clipboard.open(0); clipboard.add(IClipboard::kText, "synergy rocks"); @@ -237,7 +256,8 @@ TEST(ClipboardTests, marshall_withHtmlAndText_has2Formats) { EXPECT_EQ(2, (int)actual[3]); } -TEST(ClipboardTests, marshall_withTextAdded_endsWithAdded) { +TEST(ClipboardTests, marshall_withTextAdded_endsWithAdded) +{ Clipboard clipboard; clipboard.open(0); clipboard.add(IClipboard::kText, "synergy rocks!"); @@ -249,7 +269,8 @@ TEST(ClipboardTests, marshall_withTextAdded_endsWithAdded) { EXPECT_EQ("synergy rocks!", actual.substr(12)); } -TEST(ClipboardTests, unmarshall_emptyData_hasTextIsFalse) { +TEST(ClipboardTests, unmarshall_emptyData_hasTextIsFalse) +{ Clipboard clipboard; String data; @@ -265,7 +286,8 @@ TEST(ClipboardTests, unmarshall_emptyData_hasTextIsFalse) { EXPECT_FALSE(actual); } -TEST(ClipboardTests, unmarshall_withTextSize285_getTextIsValid) { +TEST(ClipboardTests, unmarshall_withTextSize285_getTextIsValid) +{ Clipboard clipboard; // 285 chars @@ -298,7 +320,8 @@ TEST(ClipboardTests, unmarshall_withTextSize285_getTextIsValid) { EXPECT_EQ(text, actual); } -TEST(ClipboardTests, unmarshall_withTextAndHtml_getTextIsValid) { +TEST(ClipboardTests, unmarshall_withTextAndHtml_getTextIsValid) +{ Clipboard clipboard; String data; data += (char)0; @@ -331,7 +354,8 @@ TEST(ClipboardTests, unmarshall_withTextAndHtml_getTextIsValid) { EXPECT_EQ("synergy rocks!", actual); } -TEST(ClipboardTests, unmarshall_withTextAndHtml_getHtmlIsValid) { +TEST(ClipboardTests, unmarshall_withTextAndHtml_getHtmlIsValid) +{ Clipboard clipboard; String data; data += (char)0; @@ -364,7 +388,8 @@ TEST(ClipboardTests, unmarshall_withTextAndHtml_getHtmlIsValid) { EXPECT_EQ("html sucks", actual); } -TEST(ClipboardTests, copy_withSingleText_clipboardsAreEqual) { +TEST(ClipboardTests, copy_withSingleText_clipboardsAreEqual) +{ Clipboard clipboard1; clipboard1.open(0); clipboard1.add(Clipboard::kText, "synergy rocks!"); diff --git a/src/test/unittests/deskflow/DeprecatedArgsParsingTests.cpp b/src/test/unittests/deskflow/DeprecatedArgsParsingTests.cpp index bc35c6cfe..2d95bdd71 100644 --- a/src/test/unittests/deskflow/DeprecatedArgsParsingTests.cpp +++ b/src/test/unittests/deskflow/DeprecatedArgsParsingTests.cpp @@ -21,7 +21,8 @@ using namespace deskflow; -TEST(DeprecatedArgsParsingTests, parseDeprecatedArgs_cryptoPass_returnTrue) { +TEST(DeprecatedArgsParsingTests, parseDeprecatedArgs_cryptoPass_returnTrue) +{ int i = 1; const int argc = 3; const char *kCryptoPassCmd[argc] = {"stub", "--crypto-pass", "mock_pass"}; @@ -34,7 +35,8 @@ TEST(DeprecatedArgsParsingTests, parseDeprecatedArgs_cryptoPass_returnTrue) { EXPECT_EQ(2, i); } -TEST(DeprecatedArgsParsingTests, parseDeprecatedArgs_cryptoPass_returnFalse) { +TEST(DeprecatedArgsParsingTests, parseDeprecatedArgs_cryptoPass_returnFalse) +{ int i = 1; const int argc = 3; const char *kCryptoPassCmd[argc] = {"stub", "--mock-arg", "mock_value"}; diff --git a/src/test/unittests/deskflow/GenericArgsParsingTests.cpp b/src/test/unittests/deskflow/GenericArgsParsingTests.cpp index 53fc93dc4..8eb3e38b0 100644 --- a/src/test/unittests/deskflow/GenericArgsParsingTests.cpp +++ b/src/test/unittests/deskflow/GenericArgsParsingTests.cpp @@ -29,18 +29,29 @@ using ::testing::NiceMock; bool g_helpShowed = false; bool g_versionShowed = false; -void showMockHelp() { g_helpShowed = true; } +void showMockHelp() +{ + g_helpShowed = true; +} -void showMockVersion() { g_versionShowed = true; } +void showMockVersion() +{ + g_versionShowed = true; +} -class GenericArgsParsingTests : public ::testing::Test { +class GenericArgsParsingTests : public ::testing::Test +{ public: - void SetUp() { + void SetUp() + { m_argParser = new ArgParser(nullptr); m_argParser->setArgsBase(argsBase); } - void TearDown() { delete m_argParser; } + void TearDown() + { + delete m_argParser; + } static deskflow::ArgsBase argsBase; ArgParser *m_argParser = nullptr; @@ -48,7 +59,8 @@ public: deskflow::ArgsBase GenericArgsParsingTests::argsBase; -TEST_F(GenericArgsParsingTests, parseGenericArgs_logLevelCmd_setLogLevel) { +TEST_F(GenericArgsParsingTests, parseGenericArgs_logLevelCmd_setLogLevel) +{ int i = 1; const int argc = 3; const char *kLogLevelCmd[argc] = {"stub", "--debug", "DEBUG"}; @@ -60,7 +72,8 @@ TEST_F(GenericArgsParsingTests, parseGenericArgs_logLevelCmd_setLogLevel) { EXPECT_EQ(2, i); } -TEST_F(GenericArgsParsingTests, parseGenericArgs_logFileCmd_saveLogFilename) { +TEST_F(GenericArgsParsingTests, parseGenericArgs_logFileCmd_saveLogFilename) +{ int i = 1; const int argc = 3; const char *kLogFileCmd[argc] = {"stub", "--log", "mock_filename"}; @@ -72,9 +85,8 @@ TEST_F(GenericArgsParsingTests, parseGenericArgs_logFileCmd_saveLogFilename) { EXPECT_EQ(2, i); } -TEST_F( - GenericArgsParsingTests, - parseGenericArgs_logFileCmdWithSpace_saveLogFilename) { +TEST_F(GenericArgsParsingTests, parseGenericArgs_logFileCmdWithSpace_saveLogFilename) +{ int i = 1; const int argc = 3; const char *kLogFileCmdWithSpace[argc] = {"stub", "--log", "mo ck_filename"}; @@ -86,7 +98,8 @@ TEST_F( EXPECT_EQ(2, i); } -TEST_F(GenericArgsParsingTests, parseGenericArgs_noDeamonCmd_daemonFalse) { +TEST_F(GenericArgsParsingTests, parseGenericArgs_noDeamonCmd_daemonFalse) +{ int i = 1; const int argc = 2; const char *kNoDeamonCmd[argc] = {"stub", "-f"}; @@ -97,7 +110,8 @@ TEST_F(GenericArgsParsingTests, parseGenericArgs_noDeamonCmd_daemonFalse) { EXPECT_EQ(1, i); } -TEST_F(GenericArgsParsingTests, parseGenericArgs_deamonCmd_daemonTrue) { +TEST_F(GenericArgsParsingTests, parseGenericArgs_deamonCmd_daemonTrue) +{ int i = 1; const int argc = 2; const char *kDeamonCmd[argc] = {"stub", "--daemon"}; @@ -108,7 +122,8 @@ TEST_F(GenericArgsParsingTests, parseGenericArgs_deamonCmd_daemonTrue) { EXPECT_EQ(1, i); } -TEST_F(GenericArgsParsingTests, parseGenericArgs_nameCmd_saveName) { +TEST_F(GenericArgsParsingTests, parseGenericArgs_nameCmd_saveName) +{ int i = 1; const int argc = 3; const char *kNameCmd[argc] = {"stub", "--name", "mock"}; @@ -119,7 +134,8 @@ TEST_F(GenericArgsParsingTests, parseGenericArgs_nameCmd_saveName) { EXPECT_EQ(2, i); } -TEST_F(GenericArgsParsingTests, parseGenericArgs_noRestartCmd_restartFalse) { +TEST_F(GenericArgsParsingTests, parseGenericArgs_noRestartCmd_restartFalse) +{ int i = 1; const int argc = 2; const char *kNoRestartCmd[argc] = {"stub", "--no-restart"}; @@ -130,7 +146,8 @@ TEST_F(GenericArgsParsingTests, parseGenericArgs_noRestartCmd_restartFalse) { EXPECT_EQ(1, i); } -TEST_F(GenericArgsParsingTests, parseGenericArgs_restartCmd_restartTrue) { +TEST_F(GenericArgsParsingTests, parseGenericArgs_restartCmd_restartTrue) +{ int i = 1; const int argc = 2; const char *kRestartCmd[argc] = {"stub", "--restart"}; @@ -141,7 +158,8 @@ TEST_F(GenericArgsParsingTests, parseGenericArgs_restartCmd_restartTrue) { EXPECT_EQ(1, i); } -TEST_F(GenericArgsParsingTests, parseGenericArgs_backendCmd_rejected) { +TEST_F(GenericArgsParsingTests, parseGenericArgs_backendCmd_rejected) +{ int i = 1; const int argc = 2; const char *kBackendCmd[argc] = {"stub", "-z"}; @@ -149,7 +167,8 @@ TEST_F(GenericArgsParsingTests, parseGenericArgs_backendCmd_rejected) { EXPECT_FALSE(m_argParser->parseGenericArgs(argc, kBackendCmd, i)); } -TEST_F(GenericArgsParsingTests, parseGenericArgs_noHookCmd_noHookTrue) { +TEST_F(GenericArgsParsingTests, parseGenericArgs_noHookCmd_noHookTrue) +{ int i = 1; const int argc = 2; const char *kNoHookCmd[argc] = {"stub", "--no-hooks"}; @@ -160,7 +179,8 @@ TEST_F(GenericArgsParsingTests, parseGenericArgs_noHookCmd_noHookTrue) { EXPECT_EQ(1, i); } -TEST_F(GenericArgsParsingTests, parseGenericArgs_helpCmd_showHelp) { +TEST_F(GenericArgsParsingTests, parseGenericArgs_helpCmd_showHelp) +{ g_helpShowed = false; int i = 1; const int argc = 2; @@ -177,7 +197,8 @@ TEST_F(GenericArgsParsingTests, parseGenericArgs_helpCmd_showHelp) { EXPECT_EQ(1, i); } -TEST_F(GenericArgsParsingTests, parseGenericArgs_versionCmd_showVersion) { +TEST_F(GenericArgsParsingTests, parseGenericArgs_versionCmd_showVersion) +{ g_versionShowed = false; int i = 1; const int argc = 2; @@ -195,7 +216,8 @@ TEST_F(GenericArgsParsingTests, parseGenericArgs_versionCmd_showVersion) { EXPECT_EQ(1, i); } -TEST_F(GenericArgsParsingTests, parseGenericArgs_noTrayCmd_disableTrayTrue) { +TEST_F(GenericArgsParsingTests, parseGenericArgs_noTrayCmd_disableTrayTrue) +{ int i = 1; const int argc = 2; const char *kNoTrayCmd[argc] = {"stub", "--no-tray"}; @@ -206,7 +228,8 @@ TEST_F(GenericArgsParsingTests, parseGenericArgs_noTrayCmd_disableTrayTrue) { EXPECT_EQ(1, i); } -TEST_F(GenericArgsParsingTests, parseGenericArgs_ipcCmd_enableIpcTrue) { +TEST_F(GenericArgsParsingTests, parseGenericArgs_ipcCmd_enableIpcTrue) +{ int i = 1; const int argc = 2; const char *kIpcCmd[argc] = {"stub", "--ipc"}; @@ -218,9 +241,8 @@ TEST_F(GenericArgsParsingTests, parseGenericArgs_ipcCmd_enableIpcTrue) { } #ifndef WINAPI_XWINDOWS -TEST_F( - GenericArgsParsingTests, - parseGenericArgs_dragDropCmdOnNonLinux_enableDragDropTrue) { +TEST_F(GenericArgsParsingTests, parseGenericArgs_dragDropCmdOnNonLinux_enableDragDropTrue) +{ int i = 1; const int argc = 2; const char *kDragDropCmd[argc] = {"stub", "--enable-drag-drop"}; @@ -233,9 +255,8 @@ TEST_F( #endif #ifdef WINAPI_XWINDOWS -TEST_F( - GenericArgsParsingTests, - parseGenericArgs_dragDropCmdOnLinux_enableDragDropFalse) { +TEST_F(GenericArgsParsingTests, parseGenericArgs_dragDropCmdOnLinux_enableDragDropFalse) +{ int i = 1; const int argc = 2; const char *kDragDropCmd[argc] = {"stub", "--enable-drag-drop"}; diff --git a/src/test/unittests/deskflow/IKeyStateTests.cpp b/src/test/unittests/deskflow/IKeyStateTests.cpp index 9fbc11883..bad2a55a1 100644 --- a/src/test/unittests/deskflow/IKeyStateTests.cpp +++ b/src/test/unittests/deskflow/IKeyStateTests.cpp @@ -2,7 +2,8 @@ #include -TEST(IKeyStateTests, KeyInfo_alloc_destinations) { +TEST(IKeyStateTests, KeyInfo_alloc_destinations) +{ auto info = IKeyState::KeyInfo::alloc(1, 2, 3, 4, {"test1", "test2"}); EXPECT_STREQ(info->m_screensBuffer, ":test1:test2:"); diff --git a/src/test/unittests/deskflow/KeyMapTests.cpp b/src/test/unittests/deskflow/KeyMapTests.cpp index e28871594..6883a4b21 100644 --- a/src/test/unittests/deskflow/KeyMapTests.cpp +++ b/src/test/unittests/deskflow/KeyMapTests.cpp @@ -31,7 +31,8 @@ using ::testing::SaveArg; namespace deskflow { -TEST(KeyMapTests, findBestKey_requiredDown_matchExactFirstItem) { +TEST(KeyMapTests, findBestKey_requiredDown_matchExactFirstItem) +{ KeyMap keyMap; KeyMap::KeyEntryList entryList; KeyMap::KeyItemList itemList; @@ -45,9 +46,8 @@ TEST(KeyMapTests, findBestKey_requiredDown_matchExactFirstItem) { EXPECT_EQ(0, keyMap.findBestKey(entryList, desiredState)); } -TEST( - KeyMapTests, - findBestKey_requiredAndExtraSensitiveDown_matchExactFirstItem) { +TEST(KeyMapTests, findBestKey_requiredAndExtraSensitiveDown_matchExactFirstItem) +{ KeyMap keyMap; KeyMap::KeyEntryList entryList; KeyMap::KeyItemList itemList; @@ -61,9 +61,8 @@ TEST( EXPECT_EQ(0, keyMap.findBestKey(entryList, desiredState)); } -TEST( - KeyMapTests, - findBestKey_requiredAndExtraSensitiveDown_matchExactSecondItem) { +TEST(KeyMapTests, findBestKey_requiredAndExtraSensitiveDown_matchExactSecondItem) +{ KeyMap keyMap; KeyMap::KeyEntryList entryList; KeyMap::KeyItemList itemList1; @@ -83,7 +82,8 @@ TEST( EXPECT_EQ(1, keyMap.findBestKey(entryList, desiredState)); } -TEST(KeyMapTests, findBestKey_extraSensitiveDown_matchExactSecondItem) { +TEST(KeyMapTests, findBestKey_extraSensitiveDown_matchExactSecondItem) +{ KeyMap keyMap; KeyMap::KeyEntryList entryList; KeyMap::KeyItemList itemList1; @@ -103,7 +103,8 @@ TEST(KeyMapTests, findBestKey_extraSensitiveDown_matchExactSecondItem) { EXPECT_EQ(1, keyMap.findBestKey(entryList, desiredState)); } -TEST(KeyMapTests, findBestKey_noRequiredDown_matchOneRequiredChangeItem) { +TEST(KeyMapTests, findBestKey_noRequiredDown_matchOneRequiredChangeItem) +{ KeyMap keyMap; KeyMap::KeyEntryList entryList; KeyMap::KeyItemList itemList1; @@ -123,7 +124,8 @@ TEST(KeyMapTests, findBestKey_noRequiredDown_matchOneRequiredChangeItem) { EXPECT_EQ(1, keyMap.findBestKey(entryList, desiredState)); } -TEST(KeyMapTests, findBestKey_onlyOneRequiredDown_matchTwoRequiredChangesItem) { +TEST(KeyMapTests, findBestKey_onlyOneRequiredDown_matchTwoRequiredChangesItem) +{ KeyMap keyMap; KeyMap::KeyEntryList entryList; KeyMap::KeyItemList itemList1; @@ -143,7 +145,8 @@ TEST(KeyMapTests, findBestKey_onlyOneRequiredDown_matchTwoRequiredChangesItem) { EXPECT_EQ(1, keyMap.findBestKey(entryList, desiredState)); } -TEST(KeyMapTests, findBestKey_noRequiredDown_cannotMatch) { +TEST(KeyMapTests, findBestKey_noRequiredDown_cannotMatch) +{ KeyMap keyMap; KeyMap::KeyEntryList entryList; KeyMap::KeyItemList itemList; @@ -157,49 +160,56 @@ TEST(KeyMapTests, findBestKey_noRequiredDown_cannotMatch) { EXPECT_EQ(-1, keyMap.findBestKey(entryList, desiredState)); } -TEST(KeyMapTests, isCommand_shiftMask_returnFalse) { +TEST(KeyMapTests, isCommand_shiftMask_returnFalse) +{ KeyMap keyMap; KeyModifierMask mask = KeyModifierShift; EXPECT_FALSE(keyMap.isCommand(mask)); } -TEST(KeyMapTests, isCommand_controlMask_returnTrue) { +TEST(KeyMapTests, isCommand_controlMask_returnTrue) +{ KeyMap keyMap; KeyModifierMask mask = KeyModifierControl; EXPECT_EQ(true, keyMap.isCommand(mask)); } -TEST(KeyMapTests, isCommand_alternateMask_returnTrue) { +TEST(KeyMapTests, isCommand_alternateMask_returnTrue) +{ KeyMap keyMap; KeyModifierMask mask = KeyModifierAlt; EXPECT_EQ(true, keyMap.isCommand(mask)); } -TEST(KeyMapTests, isCommand_alternateGraphicMask_returnTrue) { +TEST(KeyMapTests, isCommand_alternateGraphicMask_returnTrue) +{ KeyMap keyMap; KeyModifierMask mask = KeyModifierAltGr; EXPECT_EQ(true, keyMap.isCommand(mask)); } -TEST(KeyMapTests, isCommand_metaMask_returnTrue) { +TEST(KeyMapTests, isCommand_metaMask_returnTrue) +{ KeyMap keyMap; KeyModifierMask mask = KeyModifierMeta; EXPECT_EQ(true, keyMap.isCommand(mask)); } -TEST(KeyMapTests, isCommand_superMask_returnTrue) { +TEST(KeyMapTests, isCommand_superMask_returnTrue) +{ KeyMap keyMap; KeyModifierMask mask = KeyModifierSuper; EXPECT_EQ(true, keyMap.isCommand(mask)); } -TEST(KeyMapTests, mapkey_handles_setmodifier_with_no_mapped) { +TEST(KeyMapTests, mapkey_handles_setmodifier_with_no_mapped) +{ KeyMap keyMap{}; KeyMap::Keystroke stroke('A', true, false, 1); KeyMap::KeyItem keyItem; @@ -212,14 +222,10 @@ TEST(KeyMapTests, mapkey_handles_setmodifier_with_no_mapped) { KeyMap::ModifierToKeys activeModifiers{}; KeyModifierMask currentState{}; KeyModifierMask desiredMask{}; - auto result = keyMap.mapKey( - strokes, kKeySetModifiers, 1, activeModifiers, currentState, desiredMask, - false, "en"); + auto result = keyMap.mapKey(strokes, kKeySetModifiers, 1, activeModifiers, currentState, desiredMask, false, "en"); EXPECT_FALSE(result == nullptr); desiredMask = KeyModifierControl; - result = keyMap.mapKey( - strokes, kKeySetModifiers, 1, activeModifiers, currentState, desiredMask, - false, "en"); + result = keyMap.mapKey(strokes, kKeySetModifiers, 1, activeModifiers, currentState, desiredMask, false, "en"); EXPECT_TRUE(result == nullptr); } diff --git a/src/test/unittests/deskflow/KeyStateTests.cpp b/src/test/unittests/deskflow/KeyStateTests.cpp index c275f2d47..122a6af7f 100644 --- a/src/test/unittests/deskflow/KeyStateTests.cpp +++ b/src/test/unittests/deskflow/KeyStateTests.cpp @@ -35,15 +35,15 @@ void stubPollPressedKeys(IKeyState::KeyButtonSet &pressedKeys); void assertMaskIsOne(ForeachKeyCallback cb, void *userData); const deskflow::KeyMap::KeyItem *stubMapKey( - deskflow::KeyMap::Keystrokes &keys, KeyID id, SInt32 group, - deskflow::KeyMap::ModifierToKeys &activeModifiers, - KeyModifierMask ¤tState, KeyModifierMask desiredMask, - bool isAutoRepeat, const String &lang); + deskflow::KeyMap::Keystrokes &keys, KeyID id, SInt32 group, deskflow::KeyMap::ModifierToKeys &activeModifiers, + KeyModifierMask ¤tState, KeyModifierMask desiredMask, bool isAutoRepeat, const String &lang +); deskflow::KeyMap::Keystroke s_stubKeystroke(1, false, false); deskflow::KeyMap::KeyItem s_stubKeyItem; -TEST(CKeyStateTests, onKey_aKeyDown_keyStateOne) { +TEST(CKeyStateTests, onKey_aKeyDown_keyStateOne) +{ MockKeyMap keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -53,7 +53,8 @@ TEST(CKeyStateTests, onKey_aKeyDown_keyStateOne) { EXPECT_EQ(1, keyState.getKeyState(1)); } -TEST(KeyStateTests, onKey_aKeyUp_keyStateZero) { +TEST(KeyStateTests, onKey_aKeyUp_keyStateZero) +{ MockKeyMap keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -63,7 +64,8 @@ TEST(KeyStateTests, onKey_aKeyUp_keyStateZero) { EXPECT_EQ(0, keyState.getKeyState(1)); } -TEST(KeyStateTests, onKey_invalidKey_keyStateZero) { +TEST(KeyStateTests, onKey_invalidKey_keyStateZero) +{ MockKeyMap keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -73,7 +75,8 @@ TEST(KeyStateTests, onKey_invalidKey_keyStateZero) { EXPECT_EQ(0, keyState.getKeyState(0)); } -TEST(KeyStateTests, sendKeyEvent_halfDuplexAndRepeat_addEventNotCalled) { +TEST(KeyStateTests, sendKeyEvent_halfDuplexAndRepeat_addEventNotCalled) +{ NiceMock keyMap; NiceMock eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -85,7 +88,8 @@ TEST(KeyStateTests, sendKeyEvent_halfDuplexAndRepeat_addEventNotCalled) { keyState.sendKeyEvent(NULL, false, true, kKeyCapsLock, 0, 0, 0); } -TEST(KeyStateTests, sendKeyEvent_halfDuplex_addEventCalledTwice) { +TEST(KeyStateTests, sendKeyEvent_halfDuplex_addEventCalledTwice) +{ NiceMock keyMap; NiceMock eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -100,7 +104,8 @@ TEST(KeyStateTests, sendKeyEvent_halfDuplex_addEventCalledTwice) { keyState.sendKeyEvent(NULL, false, false, kKeyCapsLock, 0, 0, 0); } -TEST(KeyStateTests, sendKeyEvent_keyRepeat_addEventCalledOnce) { +TEST(KeyStateTests, sendKeyEvent_keyRepeat_addEventCalledOnce) +{ NiceMock keyMap; NiceMock eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -114,7 +119,8 @@ TEST(KeyStateTests, sendKeyEvent_keyRepeat_addEventCalledOnce) { keyState.sendKeyEvent(NULL, false, true, 1, 0, 0, 0); } -TEST(KeyStateTests, sendKeyEvent_keyDown_addEventCalledOnce) { +TEST(KeyStateTests, sendKeyEvent_keyDown_addEventCalledOnce) +{ NiceMock keyMap; NiceMock eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -128,7 +134,8 @@ TEST(KeyStateTests, sendKeyEvent_keyDown_addEventCalledOnce) { keyState.sendKeyEvent(NULL, true, false, 1, 0, 0, 0); } -TEST(KeyStateTests, sendKeyEvent_keyUp_addEventCalledOnce) { +TEST(KeyStateTests, sendKeyEvent_keyUp_addEventCalledOnce) +{ NiceMock keyMap; NiceMock eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -142,7 +149,8 @@ TEST(KeyStateTests, sendKeyEvent_keyUp_addEventCalledOnce) { keyState.sendKeyEvent(NULL, false, false, 1, 0, 0, 0); } -TEST(KeyStateTests, updateKeyMap_mockKeyMap_keyMapGotMock) { +TEST(KeyStateTests, updateKeyMap_mockKeyMap_keyMapGotMock) +{ NiceMock keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -153,12 +161,12 @@ TEST(KeyStateTests, updateKeyMap_mockKeyMap_keyMapGotMock) { keyState.updateKeyMap(); } -TEST(KeyStateTests, updateKeyState_pollInsertsSingleKey_keyIsDown) { +TEST(KeyStateTests, updateKeyState_pollInsertsSingleKey_keyIsDown) +{ NiceMock keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); - ON_CALL(keyState, pollPressedKeys(_)) - .WillByDefault(Invoke(stubPollPressedKeys)); + ON_CALL(keyState, pollPressedKeys(_)).WillByDefault(Invoke(stubPollPressedKeys)); keyState.updateKeyState(); @@ -166,7 +174,8 @@ TEST(KeyStateTests, updateKeyState_pollInsertsSingleKey_keyIsDown) { ASSERT_TRUE(actual); } -TEST(KeyStateTests, updateKeyState_pollDoesNothing_keyNotSet) { +TEST(KeyStateTests, updateKeyState_pollDoesNothing_keyNotSet) +{ NiceMock keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -177,12 +186,12 @@ TEST(KeyStateTests, updateKeyState_pollDoesNothing_keyNotSet) { ASSERT_FALSE(actual); } -TEST(KeyStateTests, updateKeyState_activeModifiers_maskSet) { +TEST(KeyStateTests, updateKeyState_activeModifiers_maskSet) +{ NiceMock keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); - ON_CALL(keyState, pollActiveModifiers()) - .WillByDefault(Return(KeyModifierAlt)); + ON_CALL(keyState, pollActiveModifiers()).WillByDefault(Return(KeyModifierAlt)); keyState.updateKeyState(); @@ -190,7 +199,8 @@ TEST(KeyStateTests, updateKeyState_activeModifiers_maskSet) { ASSERT_EQ(KeyModifierAlt, actual); } -TEST(KeyStateTests, updateKeyState_activeModifiers_maskNotSet) { +TEST(KeyStateTests, updateKeyState_activeModifiers_maskNotSet) +{ NiceMock keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -201,7 +211,8 @@ TEST(KeyStateTests, updateKeyState_activeModifiers_maskNotSet) { ASSERT_EQ(0, actual); } -TEST(KeyStateTests, updateKeyState_activeModifiers_keyMapGotModifers) { +TEST(KeyStateTests, updateKeyState_activeModifiers_keyMapGotModifers) +{ MockKeyMap keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -214,7 +225,8 @@ TEST(KeyStateTests, updateKeyState_activeModifiers_keyMapGotModifers) { keyState.updateKeyState(); } -TEST(KeyStateTests, setHalfDuplexMask_capsLock_halfDuplexCapsLockAdded) { +TEST(KeyStateTests, setHalfDuplexMask_capsLock_halfDuplexCapsLockAdded) +{ MockKeyMap keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -224,7 +236,8 @@ TEST(KeyStateTests, setHalfDuplexMask_capsLock_halfDuplexCapsLockAdded) { keyState.setHalfDuplexMask(KeyModifierCapsLock); } -TEST(KeyStateTests, setHalfDuplexMask_numLock_halfDuplexNumLockAdded) { +TEST(KeyStateTests, setHalfDuplexMask_numLock_halfDuplexNumLockAdded) +{ MockKeyMap keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -234,7 +247,8 @@ TEST(KeyStateTests, setHalfDuplexMask_numLock_halfDuplexNumLockAdded) { keyState.setHalfDuplexMask(KeyModifierNumLock); } -TEST(KeyStateTests, setHalfDuplexMask_scrollLock_halfDuplexScollLockAdded) { +TEST(KeyStateTests, setHalfDuplexMask_scrollLock_halfDuplexScollLockAdded) +{ MockKeyMap keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -244,14 +258,14 @@ TEST(KeyStateTests, setHalfDuplexMask_scrollLock_halfDuplexScollLockAdded) { keyState.setHalfDuplexMask(KeyModifierScrollLock); } -TEST(KeyStateTests, fakeKeyDown_serverKeyAlreadyDown_fakeKeyCalledTwice) { +TEST(KeyStateTests, fakeKeyDown_serverKeyAlreadyDown_fakeKeyCalledTwice) +{ NiceMock keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); s_stubKeyItem.m_client = 0; s_stubKeyItem.m_button = 1; - ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)) - .WillByDefault(Invoke(stubMapKey)); + ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Invoke(stubMapKey)); // 2 calls to fakeKeyDown should still call fakeKey, even though // repeated keys are handled differently. @@ -262,7 +276,8 @@ TEST(KeyStateTests, fakeKeyDown_serverKeyAlreadyDown_fakeKeyCalledTwice) { keyState.fakeKeyDown(1, 0, 0, "en"); } -TEST(KeyStateTests, fakeKeyDown_isIgnoredKey_fakeKeyNotCalled) { +TEST(KeyStateTests, fakeKeyDown_isIgnoredKey_fakeKeyNotCalled) +{ MockKeyMap keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -272,21 +287,22 @@ TEST(KeyStateTests, fakeKeyDown_isIgnoredKey_fakeKeyNotCalled) { keyState.fakeKeyDown(kKeyCapsLock, 0, 0, "en"); } -TEST(KeyStateTests, fakeKeyDown_mapReturnsKeystrokes_fakeKeyCalled) { +TEST(KeyStateTests, fakeKeyDown_mapReturnsKeystrokes_fakeKeyCalled) +{ NiceMock keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); s_stubKeyItem.m_button = 0; s_stubKeyItem.m_client = 0; - ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)) - .WillByDefault(Invoke(stubMapKey)); + ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Invoke(stubMapKey)); EXPECT_CALL(keyState, fakeKey(_)).Times(1); keyState.fakeKeyDown(1, 0, 0, "en"); } -TEST(KeyStateTests, fakeKeyRepeat_invalidKey_returnsFalse) { +TEST(KeyStateTests, fakeKeyRepeat_invalidKey_returnsFalse) +{ MockKeyMap keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -296,7 +312,8 @@ TEST(KeyStateTests, fakeKeyRepeat_invalidKey_returnsFalse) { ASSERT_FALSE(actual); } -TEST(KeyStateTests, fakeKeyRepeat_nullKey_returnsFalse) { +TEST(KeyStateTests, fakeKeyRepeat_nullKey_returnsFalse) +{ NiceMock keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -305,21 +322,20 @@ TEST(KeyStateTests, fakeKeyRepeat_nullKey_returnsFalse) { deskflow::KeyMap::KeyItem keyItem; keyItem.m_client = 0; keyItem.m_button = 1; - ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)) - .WillByDefault(Return(&keyItem)); + ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Return(&keyItem)); keyState.fakeKeyDown(1, 0, 0, "en"); // change mapKey to return NULL so that fakeKeyRepeat exits early. deskflow::KeyMap::KeyItem *nullKeyItem = NULL; - ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)) - .WillByDefault(Return(nullKeyItem)); + ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Return(nullKeyItem)); bool actual = keyState.fakeKeyRepeat(1, 0, 0, 0, "en"); ASSERT_FALSE(actual); } -TEST(KeyStateTests, fakeKeyRepeat_invalidButton_returnsFalse) { +TEST(KeyStateTests, fakeKeyRepeat_invalidButton_returnsFalse) +{ NiceMock keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -328,21 +344,20 @@ TEST(KeyStateTests, fakeKeyRepeat_invalidButton_returnsFalse) { deskflow::KeyMap::KeyItem keyItem; keyItem.m_client = 0; keyItem.m_button = 1; // set to 1 to make fakeKeyDown work. - ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)) - .WillByDefault(Return(&keyItem)); + ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Return(&keyItem)); keyState.fakeKeyDown(1, 0, 0, "en"); // change button to 0 so that fakeKeyRepeat will return early. keyItem.m_button = 0; - ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)) - .WillByDefault(Return(&keyItem)); + ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Return(&keyItem)); bool actual = keyState.fakeKeyRepeat(1, 0, 0, 0, "en"); ASSERT_FALSE(actual); } -TEST(KeyStateTests, fakeKeyRepeat_validKey_returnsTrue) { +TEST(KeyStateTests, fakeKeyRepeat_validKey_returnsTrue) +{ NiceMock keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -352,21 +367,20 @@ TEST(KeyStateTests, fakeKeyRepeat_validKey_returnsTrue) { // set the button to 1 for fakeKeyDown call s_stubKeyItem.m_button = 1; - ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)) - .WillByDefault(Invoke(stubMapKey)); + ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Invoke(stubMapKey)); keyState.fakeKeyDown(1, 0, 0, "en"); // change the button to 2 s_stubKeyItem.m_button = 2; - ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)) - .WillByDefault(Invoke(stubMapKey)); + ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Invoke(stubMapKey)); bool actual = keyState.fakeKeyRepeat(1, 0, 0, 0, "en"); ASSERT_TRUE(actual); } -TEST(KeyStateTests, fakeKeyUp_buttonNotDown_returnsFalse) { +TEST(KeyStateTests, fakeKeyUp_buttonNotDown_returnsFalse) +{ MockKeyMap keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -376,20 +390,19 @@ TEST(KeyStateTests, fakeKeyUp_buttonNotDown_returnsFalse) { ASSERT_FALSE(actual); } -TEST(KeyStateTests, fakeKeyUp_buttonAlreadyDown_returnsTrue) { +TEST(KeyStateTests, fakeKeyUp_buttonAlreadyDown_returnsTrue) +{ NiceMock keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); // press alt down so we get full coverage. - ON_CALL(keyState, pollActiveModifiers()) - .WillByDefault(Return(KeyModifierAlt)); + ON_CALL(keyState, pollActiveModifiers()).WillByDefault(Return(KeyModifierAlt)); keyState.updateKeyState(); // press button 1 down. s_stubKeyItem.m_button = 1; - ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)) - .WillByDefault(Invoke(stubMapKey)); + ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Invoke(stubMapKey)); keyState.fakeKeyDown(1, 0, 1, "en"); // this takes the button id, which is the 3rd arg of fakeKeyDown @@ -398,15 +411,15 @@ TEST(KeyStateTests, fakeKeyUp_buttonAlreadyDown_returnsTrue) { ASSERT_TRUE(actual); } -TEST(KeyStateTests, fakeAllKeysUp_keysWereDown_keysAreUp) { +TEST(KeyStateTests, fakeAllKeysUp_keysWereDown_keysAreUp) +{ NiceMock keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); // press button 1 down. s_stubKeyItem.m_button = 1; - ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)) - .WillByDefault(Invoke(stubMapKey)); + ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Invoke(stubMapKey)); keyState.fakeKeyDown(1, 0, 1, "en"); // method under test @@ -416,15 +429,15 @@ TEST(KeyStateTests, fakeAllKeysUp_keysWereDown_keysAreUp) { ASSERT_FALSE(actual); } -TEST(KeyStateTests, isKeyDown_keyDown_returnsTrue) { +TEST(KeyStateTests, isKeyDown_keyDown_returnsTrue) +{ NiceMock keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); // press button 1 down. s_stubKeyItem.m_button = 1; - ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)) - .WillByDefault(Invoke(stubMapKey)); + ON_CALL(keyMap, mapKey(_, _, _, _, _, _, _, _)).WillByDefault(Invoke(stubMapKey)); keyState.fakeKeyDown(1, 0, 1, "en"); // method under test @@ -433,7 +446,8 @@ TEST(KeyStateTests, isKeyDown_keyDown_returnsTrue) { ASSERT_TRUE(actual); } -TEST(KeyStateTests, isKeyDown_noKeysDown_returnsFalse) { +TEST(KeyStateTests, isKeyDown_noKeysDown_returnsFalse) +{ MockKeyMap keyMap; MockEventQueue eventQueue; KeyStateImpl keyState(eventQueue, keyMap); @@ -444,7 +458,8 @@ TEST(KeyStateTests, isKeyDown_noKeysDown_returnsFalse) { ASSERT_FALSE(actual); } -TEST(KeyStateTests, updateKeyMap_exercised) { +TEST(KeyStateTests, updateKeyMap_exercised) +{ deskflow::KeyMap keyMap; deskflow::KeyMap::KeyItem keyItem; keyItem.m_button = 'A'; @@ -458,18 +473,19 @@ TEST(KeyStateTests, updateKeyMap_exercised) { keyState.updateKeyMap(&keyMap); } -void stubPollPressedKeys(IKeyState::KeyButtonSet &pressedKeys) { +void stubPollPressedKeys(IKeyState::KeyButtonSet &pressedKeys) +{ pressedKeys.insert(1); } -void assertMaskIsOne(ForeachKeyCallback cb, void *userData) { +void assertMaskIsOne(ForeachKeyCallback cb, void *userData) +{ ASSERT_EQ(1, ((KeyState::AddActiveModifierContext *)userData)->m_mask); } -const deskflow::KeyMap::KeyItem *stubMapKey( - deskflow::KeyMap::Keystrokes &keys, KeyID, SInt32, - deskflow::KeyMap::ModifierToKeys &, KeyModifierMask &, KeyModifierMask, - bool, const String &) { +const deskflow::KeyMap::KeyItem * +stubMapKey(deskflow::KeyMap::Keystrokes &keys, KeyID, SInt32, deskflow::KeyMap::ModifierToKeys &, KeyModifierMask &, KeyModifierMask, bool, const String &) +{ keys.push_back(s_stubKeystroke); return &s_stubKeyItem; } diff --git a/src/test/unittests/deskflow/ProtocolUtilTests.cpp b/src/test/unittests/deskflow/ProtocolUtilTests.cpp index d414ccd27..415956065 100644 --- a/src/test/unittests/deskflow/ProtocolUtilTests.cpp +++ b/src/test/unittests/deskflow/ProtocolUtilTests.cpp @@ -31,24 +31,31 @@ using ::testing::SetArgPointee; using ::testing::StrEq; using ::testing::TypedEq; -ACTION_P2(SetValueToVoidPointerArg0, value, size) { memcpy(arg0, value, size); } +ACTION_P2(SetValueToVoidPointerArg0, value, size) +{ + memcpy(arg0, value, size); +} -MATCHER_P(EqVoidPointeeInt8, expected, "") { +MATCHER_P(EqVoidPointeeInt8, expected, "") +{ const UInt8 Actual8 = (*static_cast(arg)); return (expected == Actual8); } -MATCHER_P(EqVoidPointeeInt16, expected, "") { +MATCHER_P(EqVoidPointeeInt16, expected, "") +{ const UInt16 Actual16 = (*static_cast(arg)); return (expected == (Actual16 >> 8)); } -MATCHER_P(EqVoidPointeeInt32, expected, "") { +MATCHER_P(EqVoidPointeeInt32, expected, "") +{ const UInt32 Actual32 = (*static_cast(arg)); return (expected == (Actual32 >> 24)); } -MATCHER_P(EqVoidVectorInt1byte, expected, "") { +MATCHER_P(EqVoidVectorInt1byte, expected, "") +{ bool Result = true; const UInt8 *Actual = (static_cast(arg)) + 4; const size_t Size = *(Actual - 1); @@ -67,7 +74,8 @@ MATCHER_P(EqVoidVectorInt1byte, expected, "") { return Result; } -MATCHER_P(EqVoidVectorInt2bytes, expected, "") { +MATCHER_P(EqVoidVectorInt2bytes, expected, "") +{ bool Result = true; const UInt16 *Actual = (static_cast(arg)) + 2; const size_t Size = *(Actual - 1) >> 8; @@ -86,7 +94,8 @@ MATCHER_P(EqVoidVectorInt2bytes, expected, "") { return Result; } -MATCHER_P(EqVoidVectorInt4bytes, expected, "") { +MATCHER_P(EqVoidVectorInt4bytes, expected, "") +{ bool Result = true; const UInt32 *Actual = (static_cast(arg)) + 1; const size_t Size = *(Actual - 1) >> 24; @@ -105,7 +114,8 @@ MATCHER_P(EqVoidVectorInt4bytes, expected, "") { return Result; } -MATCHER_P(EqVectorSymbols, expected, "") { +MATCHER_P(EqVectorSymbols, expected, "") +{ bool Result = true; const UInt8 *Actual = (static_cast(arg)); @@ -119,9 +129,13 @@ MATCHER_P(EqVectorSymbols, expected, "") { return Result; } -ACTION(ThrowBadAlloc) { throw std::bad_alloc(); } +ACTION(ThrowBadAlloc) +{ + throw std::bad_alloc(); +} -class ProtocolUtilTests : public ::testing::Test { +class ProtocolUtilTests : public ::testing::Test +{ public: MockStream stream; UInt8 ActualInt8 = 0; diff --git a/src/test/unittests/deskflow/ServerAppTests.cpp b/src/test/unittests/deskflow/ServerAppTests.cpp index da5e634c7..e6f826612 100644 --- a/src/test/unittests/deskflow/ServerAppTests.cpp +++ b/src/test/unittests/deskflow/ServerAppTests.cpp @@ -26,24 +26,28 @@ using ::testing::NiceMock; -class MockServerApp : public ServerApp { +class MockServerApp : public ServerApp +{ public: - MockServerApp() : ServerApp(nullptr, nullptr) {} + MockServerApp() : ServerApp(nullptr, nullptr) + { + } }; -TEST(ServerAppTests, runInner_will_handle_configuration_lifetime) { +TEST(ServerAppTests, runInner_will_handle_configuration_lifetime) +{ NiceMock app; EXPECT_FALSE(app.args().m_config); const char *argv[]{SERVER_BINARY_NAME}; - app.runInner( - 1, const_cast(argv), nullptr, [](int, char **) { return 0; }); + app.runInner(1, const_cast(argv), nullptr, [](int, char **) { return 0; }); EXPECT_TRUE(app.args().m_config); } -TEST(ServerAppTests, version_printsYear) { +TEST(ServerAppTests, version_printsYear) +{ NiceMock app; std::stringstream buffer; std::streambuf *old = std::cout.rdbuf(buffer.rdbuf()); @@ -56,8 +60,7 @@ TEST(ServerAppTests, version_printsYear) { // regex is god awful on windows, so just check that there is a copyright EXPECT_THAT(buffer.str(), testing::HasSubstr("Symless Ltd.")); #else - std::string expectedPattern = - ".*Copyright \\(C\\) [0-9]{4}-[0-9]{4} Symless Ltd.*"; + std::string expectedPattern = ".*Copyright \\(C\\) [0-9]{4}-[0-9]{4} Symless Ltd.*"; EXPECT_THAT(buffer.str(), testing::MatchesRegex(expectedPattern)); #endif // WIN32 } diff --git a/src/test/unittests/deskflow/ServerArgsParsingTests.cpp b/src/test/unittests/deskflow/ServerArgsParsingTests.cpp index cca761917..cffb47e26 100644 --- a/src/test/unittests/deskflow/ServerArgsParsingTests.cpp +++ b/src/test/unittests/deskflow/ServerArgsParsingTests.cpp @@ -26,25 +26,29 @@ using ::testing::_; using ::testing::Invoke; using ::testing::NiceMock; -bool server_stubParseGenericArgs(int, const char *const *, int &) { +bool server_stubParseGenericArgs(int, const char *const *, int &) +{ return false; } -bool server_stubCheckUnexpectedArgs() { return false; } +bool server_stubCheckUnexpectedArgs() +{ + return false; +} -TEST(ServerArgs, ServerArgs_will_construct_from_copy) { +TEST(ServerArgs, ServerArgs_will_construct_from_copy) +{ deskflow::ServerArgs serverArgs; serverArgs.m_display = "display0"; deskflow::ServerArgs serverArgs2{serverArgs}; EXPECT_EQ(serverArgs.m_display, serverArgs2.m_display); } -TEST(ServerArgsParsingTests, parseServerArgs_addressArg_setDeskflowAddress) { +TEST(ServerArgsParsingTests, parseServerArgs_addressArg_setDeskflowAddress) +{ NiceMock argParser; - ON_CALL(argParser, parseGenericArgs(_, _, _)) - .WillByDefault(Invoke(server_stubParseGenericArgs)); - ON_CALL(argParser, checkUnexpectedArgs()) - .WillByDefault(Invoke(server_stubCheckUnexpectedArgs)); + ON_CALL(argParser, parseGenericArgs(_, _, _)).WillByDefault(Invoke(server_stubParseGenericArgs)); + ON_CALL(argParser, checkUnexpectedArgs()).WillByDefault(Invoke(server_stubCheckUnexpectedArgs)); deskflow::ServerArgs serverArgs; const int argc = 3; const char *kAddressCmd[argc] = {"stub", "--address", "mock_address"}; @@ -54,12 +58,11 @@ TEST(ServerArgsParsingTests, parseServerArgs_addressArg_setDeskflowAddress) { EXPECT_EQ("mock_address", serverArgs.m_deskflowAddress); } -TEST(ServerArgsParsingTests, parseServerArgs_configArg_setConfigFile) { +TEST(ServerArgsParsingTests, parseServerArgs_configArg_setConfigFile) +{ NiceMock argParser; - ON_CALL(argParser, parseGenericArgs(_, _, _)) - .WillByDefault(Invoke(server_stubParseGenericArgs)); - ON_CALL(argParser, checkUnexpectedArgs()) - .WillByDefault(Invoke(server_stubCheckUnexpectedArgs)); + ON_CALL(argParser, parseGenericArgs(_, _, _)).WillByDefault(Invoke(server_stubParseGenericArgs)); + ON_CALL(argParser, checkUnexpectedArgs()).WillByDefault(Invoke(server_stubCheckUnexpectedArgs)); deskflow::ServerArgs serverArgs; const int argc = 3; const char *kConfigCmd[argc] = {"stub", "--config", "mock_configFile"}; @@ -69,12 +72,11 @@ TEST(ServerArgsParsingTests, parseServerArgs_configArg_setConfigFile) { EXPECT_EQ("mock_configFile", serverArgs.m_configFile); } -TEST(ServerArgsParsingTests, parseServerArgs_checkUnexpectedParams) { +TEST(ServerArgsParsingTests, parseServerArgs_checkUnexpectedParams) +{ NiceMock argParser; - ON_CALL(argParser, parseGenericArgs(_, _, _)) - .WillByDefault(Invoke(server_stubParseGenericArgs)); - ON_CALL(argParser, checkUnexpectedArgs()) - .WillByDefault(Invoke(server_stubCheckUnexpectedArgs)); + ON_CALL(argParser, parseGenericArgs(_, _, _)).WillByDefault(Invoke(server_stubParseGenericArgs)); + ON_CALL(argParser, checkUnexpectedArgs()).WillByDefault(Invoke(server_stubCheckUnexpectedArgs)); deskflow::ServerArgs serverArgs; const int argc = 2; std::array kUnknownCmd = {"stub", "--unknown"}; diff --git a/src/test/unittests/deskflow/X11LayoutParserTests.cpp b/src/test/unittests/deskflow/X11LayoutParserTests.cpp index 6000668d5..6b58f242f 100644 --- a/src/test/unittests/deskflow/X11LayoutParserTests.cpp +++ b/src/test/unittests/deskflow/X11LayoutParserTests.cpp @@ -23,7 +23,8 @@ const std::string testDir = "tmp/test"; -void createTestFiles() { +void createTestFiles() +{ std::ofstream correctEvdevFile(testDir + "/correctEvdev.xml"); if (!correctEvdevFile.is_open()) { FAIL(); @@ -35,12 +36,9 @@ void createTestFiles() { correctEvdevFile << " " << std::endl; correctEvdevFile << " " << std::endl; correctEvdevFile << " us" << std::endl; - correctEvdevFile << " " - << std::endl; - correctEvdevFile << " en" - << std::endl; - correctEvdevFile << " English (US)" - << std::endl; + correctEvdevFile << " " << std::endl; + correctEvdevFile << " en" << std::endl; + correctEvdevFile << " English (US)" << std::endl; correctEvdevFile << " " << std::endl; correctEvdevFile << " eng" << std::endl; correctEvdevFile << " " << std::endl; @@ -49,10 +47,8 @@ void createTestFiles() { correctEvdevFile << " " << std::endl; correctEvdevFile << " " << std::endl; correctEvdevFile << " eng" << std::endl; - correctEvdevFile << " eng" - << std::endl; - correctEvdevFile << " Cherokee" - << std::endl; + correctEvdevFile << " eng" << std::endl; + correctEvdevFile << " Cherokee" << std::endl; correctEvdevFile << " " << std::endl; correctEvdevFile << " eng" << std::endl; correctEvdevFile << " " << std::endl; @@ -63,10 +59,8 @@ void createTestFiles() { correctEvdevFile << " " << std::endl; correctEvdevFile << " " << std::endl; correctEvdevFile << " ru" << std::endl; - correctEvdevFile << " " - << std::endl; - correctEvdevFile << " ru" - << std::endl; + correctEvdevFile << " " << std::endl; + correctEvdevFile << " ru" << std::endl; correctEvdevFile << " Russian" << std::endl; correctEvdevFile << " " << std::endl; correctEvdevFile << " rus" << std::endl; @@ -82,8 +76,7 @@ void createTestFiles() { FAIL(); } - evdevFromFutureFile << "" - << std::endl; + evdevFromFutureFile << "" << std::endl; evdevFromFutureFile << "" << std::endl; evdevFromFutureFile << " " << std::endl; evdevFromFutureFile << " " << std::endl; @@ -111,8 +104,7 @@ void createTestFiles() { FAIL(); } - incorrectEvdevFile2 << "" - << std::endl; + incorrectEvdevFile2 << "" << std::endl; incorrectEvdevFile2 << "" << std::endl; incorrectEvdevFile2 << "" << std::endl; incorrectEvdevFile2.close(); @@ -122,8 +114,7 @@ void createTestFiles() { FAIL(); } - incorrectEvdevFile3 << "" - << std::endl; + incorrectEvdevFile3 << "" << std::endl; incorrectEvdevFile3 << "" << std::endl; incorrectEvdevFile3 << " " << std::endl; incorrectEvdevFile3 << " " << std::endl; @@ -133,47 +124,37 @@ void createTestFiles() { incorrectEvdevFile3.close(); } -TEST(X11LayoutsParsingTests, xmlCorrectParsingTest) { +TEST(X11LayoutsParsingTests, xmlCorrectParsingTest) +{ createTestFiles(); std::vector expectedResult = {"en", "ru"}; - auto parsedResult = - X11LayoutsParser::getX11LanguageList(testDir + "/correctEvdev.xml"); + auto parsedResult = X11LayoutsParser::getX11LanguageList(testDir + "/correctEvdev.xml"); EXPECT_EQ(parsedResult, parsedResult); } -TEST(X11LayoutsParsingTests, xmlParsingMissedEvdevFileTest) { - auto parsedResult = - X11LayoutsParser::getX11LanguageList(testDir + "/missedFile"); +TEST(X11LayoutsParsingTests, xmlParsingMissedEvdevFileTest) +{ + auto parsedResult = X11LayoutsParser::getX11LanguageList(testDir + "/missedFile"); EXPECT_TRUE(parsedResult.empty()); } -TEST(X11LayoutsParsingTests, xmlParsingIncorrectEvdevFileTest) { +TEST(X11LayoutsParsingTests, xmlParsingIncorrectEvdevFileTest) +{ std::vector parsedResult; - parsedResult = - X11LayoutsParser::getX11LanguageList(testDir + "/incorrectEvdev1.xml"); + parsedResult = X11LayoutsParser::getX11LanguageList(testDir + "/incorrectEvdev1.xml"); EXPECT_TRUE(parsedResult.empty()); - parsedResult = - X11LayoutsParser::getX11LanguageList(testDir + "/incorrectEvdev2.xml"); + parsedResult = X11LayoutsParser::getX11LanguageList(testDir + "/incorrectEvdev2.xml"); EXPECT_TRUE(parsedResult.empty()); - parsedResult = - X11LayoutsParser::getX11LanguageList(testDir + "/incorrectEvdev3.xml"); + parsedResult = X11LayoutsParser::getX11LanguageList(testDir + "/incorrectEvdev3.xml"); EXPECT_TRUE(parsedResult.empty()); } -TEST(X11LayoutsParsingTests, layoutConvertTest) { - EXPECT_EQ( - X11LayoutsParser::convertLayotToISO( - testDir + "/correctEvdev.xml", "us", true), - "en"); - EXPECT_EQ( - X11LayoutsParser::convertLayotToISO( - testDir + "/incorrectEvdev1.xml", "us", true), - ""); - EXPECT_EQ( - X11LayoutsParser::convertLayotToISO( - testDir + "/evdevFromFuture.xml", "us", true), - ""); +TEST(X11LayoutsParsingTests, layoutConvertTest) +{ + EXPECT_EQ(X11LayoutsParser::convertLayotToISO(testDir + "/correctEvdev.xml", "us", true), "en"); + EXPECT_EQ(X11LayoutsParser::convertLayotToISO(testDir + "/incorrectEvdev1.xml", "us", true), ""); + EXPECT_EQ(X11LayoutsParser::convertLayotToISO(testDir + "/evdevFromFuture.xml", "us", true), ""); } #endif diff --git a/src/test/unittests/deskflow/languages/LanguageManagerTests.cpp b/src/test/unittests/deskflow/languages/LanguageManagerTests.cpp index c1990c9c1..b7448cb26 100644 --- a/src/test/unittests/deskflow/languages/LanguageManagerTests.cpp +++ b/src/test/unittests/deskflow/languages/LanguageManagerTests.cpp @@ -19,29 +19,28 @@ #include -TEST(LanguageManager, RemoteLanguagesTest) { +TEST(LanguageManager, RemoteLanguagesTest) +{ std::string remoteLanguages = "ruenuk"; deskflow::languages::LanguageManager manager({"ru", "en", "uk"}); manager.setRemoteLanguages(remoteLanguages); - EXPECT_EQ( - (std::vector{"ru", "en", "uk"}), - manager.getRemoteLanguages()); + EXPECT_EQ((std::vector{"ru", "en", "uk"}), manager.getRemoteLanguages()); manager.setRemoteLanguages(String()); EXPECT_TRUE(manager.getRemoteLanguages().empty()); } -TEST(LanguageManager, LocalLanguagesTest) { +TEST(LanguageManager, LocalLanguagesTest) +{ std::vector localLanguages = {"ru", "en", "uk"}; deskflow::languages::LanguageManager manager(localLanguages); - EXPECT_EQ( - (std::vector{"ru", "en", "uk"}), - manager.getLocalLanguages()); + EXPECT_EQ((std::vector{"ru", "en", "uk"}), manager.getLocalLanguages()); } -TEST(LanguageManager, MissedLanguagesTest) { +TEST(LanguageManager, MissedLanguagesTest) +{ String remoteLanguages = "ruenuk"; std::vector localLanguages = {"en"}; deskflow::languages::LanguageManager manager(localLanguages); @@ -50,14 +49,16 @@ TEST(LanguageManager, MissedLanguagesTest) { EXPECT_EQ("ru, uk", manager.getMissedLanguages()); } -TEST(LanguageManager, SerializeLocalLanguagesTest) { +TEST(LanguageManager, SerializeLocalLanguagesTest) +{ std::vector localLanguages = {"ru", "en", "uk"}; deskflow::languages::LanguageManager manager(localLanguages); EXPECT_EQ("ruenuk", manager.getSerializedLocalLanguages()); } -TEST(LanguageManager, LanguageInstalledTest) { +TEST(LanguageManager, LanguageInstalledTest) +{ std::vector localLanguages = {"ru", "en", "uk"}; deskflow::languages::LanguageManager manager(localLanguages); diff --git a/src/test/unittests/gui/LoggerTests.cpp b/src/test/unittests/gui/LoggerTests.cpp index 2afd01b77..e4684890b 100644 --- a/src/test/unittests/gui/LoggerTests.cpp +++ b/src/test/unittests/gui/LoggerTests.cpp @@ -23,14 +23,14 @@ using namespace testing; using namespace deskflow::gui; -TEST(LoggerTests, handleMessage_withDebugEnvVarOn_emitsNewLine) { +TEST(LoggerTests, handleMessage_withDebugEnvVarOn_emitsNewLine) +{ Logger logger; std::string newLineEmitted; QObject::connect( &logger, &Logger::newLine, // - [&newLineEmitted](const QString &line) { - newLineEmitted = line.toStdString(); - }); + [&newLineEmitted](const QString &line) { newLineEmitted = line.toStdString(); } + ); qputenv("DESKFLOW_GUI_DEBUG", "true"); logger.loadEnvVars(); @@ -41,12 +41,14 @@ TEST(LoggerTests, handleMessage_withDebugEnvVarOn_emitsNewLine) { qputenv("DESKFLOW_GUI_DEBUG", ""); } -TEST(LoggerTests, handleMessage_withDebugEnvVarOff_doesNotEmitNewLine) { +TEST(LoggerTests, handleMessage_withDebugEnvVarOff_doesNotEmitNewLine) +{ Logger logger; bool newLineEmitted = false; QObject::connect( &logger, &Logger::newLine, // - [&newLineEmitted](const QString &line) { newLineEmitted = true; }); + [&newLineEmitted](const QString &line) { newLineEmitted = true; } + ); qputenv("DESKFLOW_GUI_DEBUG", "false"); logger.loadEnvVars(); diff --git a/src/test/unittests/gui/VersionCheckerTests.cpp b/src/test/unittests/gui/VersionCheckerTests.cpp index e3505e12f..be9713c87 100644 --- a/src/test/unittests/gui/VersionCheckerTests.cpp +++ b/src/test/unittests/gui/VersionCheckerTests.cpp @@ -24,20 +24,24 @@ using namespace deskflow::gui::proxy; using namespace testing; -class VersionCheckerTests : public ::testing::Test { +class VersionCheckerTests : public ::testing::Test +{ protected: - int compareVersions(const QString &left, const QString &right) { + int compareVersions(const QString &left, const QString &right) + { return VersionChecker::compareVersions(left, right); } }; -class MockNetworkAccessManager : public QNetworkAccessManagerProxy { +class MockNetworkAccessManager : public QNetworkAccessManagerProxy +{ public: MOCK_METHOD(void, init, (), (override)); MOCK_METHOD(void, get, (const QNetworkRequest &request), (const, override)); }; -TEST_F(VersionCheckerTests, checkLatest_callsNetworkGet) { +TEST_F(VersionCheckerTests, checkLatest_callsNetworkGet) +{ TestQtCoreApp app; const auto network = std::make_shared>(); const VersionChecker checker(network); @@ -47,19 +51,22 @@ TEST_F(VersionCheckerTests, checkLatest_callsNetworkGet) { checker.checkLatest(); } -TEST_F(VersionCheckerTests, compareVersions_major_isValid) { +TEST_F(VersionCheckerTests, compareVersions_major_isValid) +{ EXPECT_EQ(compareVersions("1.0.0", "2.0.0"), 1); EXPECT_EQ(compareVersions("2.0.0", "1.0.0"), -1); EXPECT_EQ(compareVersions("1.0.0", "1.0.0"), 0); } -TEST_F(VersionCheckerTests, compareVersions_minor_isValid) { +TEST_F(VersionCheckerTests, compareVersions_minor_isValid) +{ EXPECT_EQ(compareVersions("1.1.0", "1.2.0"), 1); EXPECT_EQ(compareVersions("1.2.0", "1.1.0"), -1); EXPECT_EQ(compareVersions("1.1.0", "1.1.0"), 0); } -TEST_F(VersionCheckerTests, compareVersions_patch_isValid) { +TEST_F(VersionCheckerTests, compareVersions_patch_isValid) +{ EXPECT_EQ(compareVersions("1.0.1", "1.0.2"), 1); EXPECT_EQ(compareVersions("1.0.2", "1.0.1"), -1); EXPECT_EQ(compareVersions("1.0.1", "1.0.1"), 0); diff --git a/src/test/unittests/gui/byte_utils_tests.cpp b/src/test/unittests/gui/byte_utils_tests.cpp index 04bb87b8f..132fd9bcf 100644 --- a/src/test/unittests/gui/byte_utils_tests.cpp +++ b/src/test/unittests/gui/byte_utils_tests.cpp @@ -21,7 +21,8 @@ using namespace deskflow::gui; -TEST(byte_utils_tests, bytesToInt_size4) { +TEST(byte_utils_tests, bytesToInt_size4) +{ char buffer[4] = {0x01, 0x02, 0x03, 0x04}; const auto i = bytesToInt(buffer, 4); @@ -29,7 +30,8 @@ TEST(byte_utils_tests, bytesToInt_size4) { EXPECT_EQ(i, 0x01020304); } -TEST(byte_utils_tests, intToBytes_size4) { +TEST(byte_utils_tests, intToBytes_size4) +{ QByteArray bytes = intToBytes(0x01020304); EXPECT_EQ(bytes.size(), 4); diff --git a/src/test/unittests/gui/config/AppConfigTests.cpp b/src/test/unittests/gui/config/AppConfigTests.cpp index 75108396e..8b4fc5eb7 100644 --- a/src/test/unittests/gui/config/AppConfigTests.cpp +++ b/src/test/unittests/gui/config/AppConfigTests.cpp @@ -28,21 +28,17 @@ using namespace deskflow::gui::proxy; namespace { -class ConfigScopesMock : public deskflow::gui::IConfigScopes { +class ConfigScopesMock : public deskflow::gui::IConfigScopes +{ using QSettingsProxy = deskflow::gui::proxy::QSettingsProxy; public: MOCK_METHOD(void, signalReady, (), (override)); + MOCK_METHOD(bool, scopeContains, (const QString &name, Scope scope), (const, override)); MOCK_METHOD( - bool, scopeContains, (const QString &name, Scope scope), - (const, override)); - MOCK_METHOD( - QVariant, getFromScope, - (const QString &name, const QVariant &defaultValue, Scope scope), - (const, override)); - MOCK_METHOD( - void, setInScope, - (const QString &name, const QVariant &value, Scope scope), (override)); + QVariant, getFromScope, (const QString &name, const QVariant &defaultValue, Scope scope), (const, override) + ); + MOCK_METHOD(void, setInScope, (const QString &name, const QVariant &value, Scope scope), (override)); MOCK_METHOD(Scope, activeScope, (), (const, override)); MOCK_METHOD(void, setActiveScope, (Scope scope), (override)); MOCK_METHOD(bool, isActiveScopeWritable, (), (const, override)); @@ -52,13 +48,16 @@ public: MOCK_METHOD(QString, activeFilePath, (), (const, override)); }; -struct DepsMock : public AppConfig::Deps { - DepsMock() { +struct DepsMock : public AppConfig::Deps +{ + DepsMock() + { ON_CALL(*this, defaultTlsCertPath()).WillByDefault(Return("stub")); ON_CALL(*this, hostname()).WillByDefault(Return("stub")); } - static std::shared_ptr> makeNice() { + static std::shared_ptr> makeNice() + { return std::make_shared>(); } @@ -68,9 +67,12 @@ struct DepsMock : public AppConfig::Deps { } // namespace -class AppConfigTests : public Test {}; +class AppConfigTests : public Test +{ +}; -TEST_F(AppConfigTests, ctor_byDefault_screenNameIsHostname) { +TEST_F(AppConfigTests, ctor_byDefault_screenNameIsHostname) +{ NiceMock scopes; auto deps = DepsMock::makeNice(); ON_CALL(*deps, hostname()).WillByDefault(Return("test hostname")); @@ -80,13 +82,13 @@ TEST_F(AppConfigTests, ctor_byDefault_screenNameIsHostname) { ASSERT_EQ(appConfig.screenName().toStdString(), "test hostname"); } -TEST_F(AppConfigTests, ctor_byDefault_getsFromScope) { +TEST_F(AppConfigTests, ctor_byDefault_getsFromScope) +{ NiceMock scopes; auto deps = DepsMock::makeNice(); ON_CALL(scopes, scopeContains(_, _)).WillByDefault(Return(true)); - ON_CALL(scopes, getFromScope(_, _, _)) - .WillByDefault(Return(QVariant("test screen"))); + ON_CALL(scopes, getFromScope(_, _, _)).WillByDefault(Return(QVariant("test screen"))); EXPECT_CALL(scopes, getFromScope(_, _, _)).Times(AnyNumber()); AppConfig appConfig(scopes, deps); @@ -94,7 +96,8 @@ TEST_F(AppConfigTests, ctor_byDefault_getsFromScope) { ASSERT_EQ(appConfig.screenName().toStdString(), "test screen"); } -TEST_F(AppConfigTests, commit_byDefault_setsToScope) { +TEST_F(AppConfigTests, commit_byDefault_setsToScope) +{ NiceMock scopes; auto deps = DepsMock::makeNice(); AppConfig appConfig(scopes, deps); diff --git a/src/test/unittests/gui/config/ConfigScopesTests.cpp b/src/test/unittests/gui/config/ConfigScopesTests.cpp index ef0c153a0..6737e3953 100644 --- a/src/test/unittests/gui/config/ConfigScopesTests.cpp +++ b/src/test/unittests/gui/config/ConfigScopesTests.cpp @@ -28,7 +28,8 @@ using namespace deskflow::gui::proxy; namespace { -class QSettingsProxyMock : public QSettingsProxy { +class QSettingsProxyMock : public QSettingsProxy +{ public: MOCK_METHOD(void, loadSystem, (), (override)); MOCK_METHOD(void, loadUser, (), (override)); @@ -37,32 +38,29 @@ public: MOCK_METHOD(bool, isWritable, (), (const, override)); MOCK_METHOD(bool, contains, (const QString &), (const, override)); MOCK_METHOD(QVariant, value, (const QString &), (const, override)); - MOCK_METHOD( - QVariant, value, (const QString &, const QVariant &), (const, override)); + MOCK_METHOD(QVariant, value, (const QString &, const QVariant &), (const, override)); MOCK_METHOD(void, setValue, (const QString &, const QVariant &), (override)); }; -struct DepsMock : public ConfigScopes::Deps { - DepsMock() { +struct DepsMock : public ConfigScopes::Deps +{ + DepsMock() + { ON_CALL(*this, makeUserSettings()).WillByDefault(Return(m_pUserSettings)); - ON_CALL(*this, makeSystemSettings()) - .WillByDefault(Return(m_pSystemSettings)); + ON_CALL(*this, makeSystemSettings()).WillByDefault(Return(m_pSystemSettings)); } - MOCK_METHOD( - std::shared_ptr, makeUserSettings, (), (override)); - MOCK_METHOD( - std::shared_ptr, makeSystemSettings, (), (override)); + MOCK_METHOD(std::shared_ptr, makeUserSettings, (), (override)); + MOCK_METHOD(std::shared_ptr, makeSystemSettings, (), (override)); - std::shared_ptr m_pUserSettings = - std::make_shared>(); - std::shared_ptr m_pSystemSettings = - std::make_shared>(); + std::shared_ptr m_pUserSettings = std::make_shared>(); + std::shared_ptr m_pSystemSettings = std::make_shared>(); }; } // namespace -TEST(ConfigScopesTests, ctor_callsMakeUserSettings) { +TEST(ConfigScopesTests, ctor_callsMakeUserSettings) +{ auto deps = std::make_shared>(); EXPECT_CALL(*deps, makeUserSettings()).Times(1); @@ -70,7 +68,8 @@ TEST(ConfigScopesTests, ctor_callsMakeUserSettings) { ConfigScopes configScopes(deps); } -TEST(ConfigScopesTests, ctor_callsMakeSystemSettings) { +TEST(ConfigScopesTests, ctor_callsMakeSystemSettings) +{ auto deps = std::make_shared>(); EXPECT_CALL(*deps, makeSystemSettings()).Times(1); @@ -78,7 +77,8 @@ TEST(ConfigScopesTests, ctor_callsMakeSystemSettings) { ConfigScopes configScopes(deps); } -TEST(ConfigScopesTests, save_syncsBothScopes) { +TEST(ConfigScopesTests, save_syncsBothScopes) +{ auto deps = std::make_shared>(); ConfigScopes configScopes(deps); @@ -89,7 +89,8 @@ TEST(ConfigScopesTests, save_syncsBothScopes) { configScopes.save(); } -TEST(ConfigScopesTests, activeSettings_returnsUserSettingsByDefault) { +TEST(ConfigScopesTests, activeSettings_returnsUserSettingsByDefault) +{ auto deps = std::make_shared>(); ConfigScopes configScopes(deps); @@ -97,7 +98,8 @@ TEST(ConfigScopesTests, activeSettings_returnsUserSettingsByDefault) { EXPECT_EQ(&configScopes.activeSettings(), deps->m_pUserSettings.get()); } -TEST(ConfigScopesTests, activeSettings_returnsSystemSettingsWhenSystemScope) { +TEST(ConfigScopesTests, activeSettings_returnsSystemSettingsWhenSystemScope) +{ auto deps = std::make_shared>(); ConfigScopes configScopes(deps); @@ -106,7 +108,8 @@ TEST(ConfigScopesTests, activeSettings_returnsSystemSettingsWhenSystemScope) { EXPECT_EQ(&configScopes.activeSettings(), deps->m_pSystemSettings.get()); } -TEST(ConfigScopesTests, setActiveScope_setsCurrentScope) { +TEST(ConfigScopesTests, setActiveScope_setsCurrentScope) +{ auto deps = std::make_shared>(); ConfigScopes configScopes(deps); @@ -116,9 +119,8 @@ TEST(ConfigScopesTests, setActiveScope_setsCurrentScope) { EXPECT_EQ(configScopes.activeScope(), ConfigScopes::Scope::System); } -TEST( - ConfigScopesTests, - isActiveScopeWritable_returnsTrueWhenUserSettingsWritable) { +TEST(ConfigScopesTests, isActiveScopeWritable_returnsTrueWhenUserSettingsWritable) +{ auto deps = std::make_shared>(); ConfigScopes configScopes(deps); @@ -128,9 +130,8 @@ TEST( EXPECT_TRUE(configScopes.isActiveScopeWritable()); } -TEST( - ConfigScopesTests, - scopeContains_byDefault_returnsTrueWhenUserSettingsContainsKey) { +TEST(ConfigScopesTests, scopeContains_byDefault_returnsTrueWhenUserSettingsContainsKey) +{ auto deps = std::make_shared>(); ON_CALL(*deps->m_pUserSettings, contains(_)).WillByDefault(Return(true)); @@ -140,9 +141,8 @@ TEST( EXPECT_TRUE(configScopes.scopeContains("stub")); } -TEST( - ConfigScopesTests, - scopeContains_userScope_returnsTrueWhenUserSettingsContainsKey) { +TEST(ConfigScopesTests, scopeContains_userScope_returnsTrueWhenUserSettingsContainsKey) +{ auto deps = std::make_shared>(); ON_CALL(*deps->m_pUserSettings, contains(_)).WillByDefault(Return(true)); @@ -152,9 +152,8 @@ TEST( EXPECT_TRUE(configScopes.scopeContains("stub", ConfigScopes::Scope::User)); } -TEST( - ConfigScopesTests, - scopeContains_systemScope_returnsTrueWhenSystemSettingsContainsKey) { +TEST(ConfigScopesTests, scopeContains_systemScope_returnsTrueWhenSystemSettingsContainsKey) +{ auto deps = std::make_shared>(); ON_CALL(*deps->m_pSystemSettings, contains(_)).WillByDefault(Return(true)); @@ -164,7 +163,8 @@ TEST( EXPECT_TRUE(configScopes.scopeContains("stub", ConfigScopes::Scope::System)); } -TEST(ConfigScopesTests, activeFilePath_returnsUserSettingsFileNameByDefault) { +TEST(ConfigScopesTests, activeFilePath_returnsUserSettingsFileNameByDefault) +{ auto deps = std::make_shared>(); ON_CALL(*deps->m_pUserSettings, fileName()).WillByDefault(Return("test")); @@ -173,7 +173,8 @@ TEST(ConfigScopesTests, activeFilePath_returnsUserSettingsFileNameByDefault) { EXPECT_EQ(configScopes.activeFilePath(), "test"); } -TEST(ConfigScopesTests, getFromScope_byDefault_returnsValueFromActiveSettings) { +TEST(ConfigScopesTests, getFromScope_byDefault_returnsValueFromActiveSettings) +{ auto deps = std::make_shared>(); ON_CALL(*deps->m_pUserSettings, value(_, _)).WillByDefault(Return("test")); @@ -182,7 +183,8 @@ TEST(ConfigScopesTests, getFromScope_byDefault_returnsValueFromActiveSettings) { EXPECT_EQ(configScopes.getFromScope("stub"), "test"); } -TEST(ConfigScopesTests, setInScope_byDefault_setsValueInActiveSettings) { +TEST(ConfigScopesTests, setInScope_byDefault_setsValueInActiveSettings) +{ auto deps = std::make_shared>(); ConfigScopes configScopes(deps); diff --git a/src/test/unittests/gui/config/ScreenTests.cpp b/src/test/unittests/gui/config/ScreenTests.cpp index 277e79fbd..597274214 100644 --- a/src/test/unittests/gui/config/ScreenTests.cpp +++ b/src/test/unittests/gui/config/ScreenTests.cpp @@ -26,18 +26,16 @@ using namespace deskflow::gui::proxy; using namespace testing; -class QSettingsProxyMock : public QSettingsProxy { +class QSettingsProxyMock : public QSettingsProxy +{ public: MOCK_METHOD(int, beginReadArray, (const QString &prefix), (override)); MOCK_METHOD(void, beginWriteArray, (const QString &prefix), (override)); MOCK_METHOD(void, setArrayIndex, (int i), (override)); MOCK_METHOD(QVariant, value, (const QString &key), (const, override)); - MOCK_METHOD( - QVariant, value, (const QString &key, const QVariant &defaultValue), - (const, override)); + MOCK_METHOD(QVariant, value, (const QString &key, const QVariant &defaultValue), (const, override)); MOCK_METHOD(void, endArray, (), (override)); - MOCK_METHOD( - void, setValue, (const QString &key, const QVariant &value), (override)); + MOCK_METHOD(void, setValue, (const QString &key, const QVariant &value), (override)); MOCK_METHOD(void, beginGroup, (const QString &prefix), (override)); MOCK_METHOD(void, endGroup, (), (override)); MOCK_METHOD(void, remove, (const QString &key), (override)); @@ -45,7 +43,8 @@ public: MOCK_METHOD(bool, contains, (const QString &key), (const, override)); }; -TEST(ScreenTests, loadSettings_whenHasSetting_readsArray) { +TEST(ScreenTests, loadSettings_whenHasSetting_readsArray) +{ TestQtCoreApp app; NiceMock settings; Screen screen; @@ -56,7 +55,8 @@ TEST(ScreenTests, loadSettings_whenHasSetting_readsArray) { screen.loadSettings(settings); } -TEST(ScreenTests, saveSettings_whenNameIsSet_writesArray) { +TEST(ScreenTests, saveSettings_whenNameIsSet_writesArray) +{ TestQtCoreApp app; NiceMock settings; Screen screen; diff --git a/src/test/unittests/gui/core/ClientConnectionTests.cpp b/src/test/unittests/gui/core/ClientConnectionTests.cpp index 140bbbbb3..abc999d9c 100644 --- a/src/test/unittests/gui/core/ClientConnectionTests.cpp +++ b/src/test/unittests/gui/core/ClientConnectionTests.cpp @@ -31,20 +31,21 @@ using enum messages::ClientError; namespace { -struct DepsMock : public ClientConnection::Deps { +struct DepsMock : public ClientConnection::Deps +{ MOCK_METHOD( - void, showError, - (QWidget * parent, messages::ClientError error, const QString &address), - (const, override)); + void, showError, (QWidget * parent, messages::ClientError error, const QString &address), (const, override) + ); }; } // namespace -class ClientConnectionTests : public testing::Test { +class ClientConnectionTests : public testing::Test +{ public: - ClientConnectionTests() { - ON_CALL(m_appConfig, serverHostname()) - .WillByDefault(testing::ReturnRef(stub)); + ClientConnectionTests() + { + ON_CALL(m_appConfig, serverHostname()).WillByDefault(testing::ReturnRef(stub)); } std::shared_ptr m_pDeps = std::make_shared>(); @@ -54,42 +55,42 @@ private: const QString stub = "stub"; }; -TEST_F(ClientConnectionTests, handleLogLine_alreadyConnected_showError) { +TEST_F(ClientConnectionTests, handleLogLine_alreadyConnected_showError) +{ ClientConnection clientConnection(nullptr, m_appConfig, m_pDeps); const QString serverName = "test server"; - ON_CALL(m_appConfig, serverHostname()) - .WillByDefault(testing::ReturnRef(serverName)); + ON_CALL(m_appConfig, serverHostname()).WillByDefault(testing::ReturnRef(serverName)); EXPECT_CALL(*m_pDeps, showError(_, AlreadyConnected, serverName)); - clientConnection.handleLogLine( - "failed to connect to server\n" - "server already has a connected client with our name"); + clientConnection.handleLogLine("failed to connect to server\n" + "server already has a connected client with our name"); } -TEST_F(ClientConnectionTests, handleLogLine_withHostname_showError) { +TEST_F(ClientConnectionTests, handleLogLine_withHostname_showError) +{ ClientConnection clientConnection(nullptr, m_appConfig, m_pDeps); const QString serverName = "test-hostname"; - ON_CALL(m_appConfig, serverHostname()) - .WillByDefault(testing::ReturnRef(serverName)); + ON_CALL(m_appConfig, serverHostname()).WillByDefault(testing::ReturnRef(serverName)); EXPECT_CALL(*m_pDeps, showError(_, HostnameError, serverName)); clientConnection.handleLogLine("failed to connect to server"); } -TEST_F(ClientConnectionTests, handleLogLine_withIpAddress_showError) { +TEST_F(ClientConnectionTests, handleLogLine_withIpAddress_showError) +{ ClientConnection clientConnection(nullptr, m_appConfig, m_pDeps); const QString serverName = "1.1.1.1"; - ON_CALL(m_appConfig, serverHostname()) - .WillByDefault(testing::ReturnRef(serverName)); + ON_CALL(m_appConfig, serverHostname()).WillByDefault(testing::ReturnRef(serverName)); EXPECT_CALL(*m_pDeps, showError(_, GenericError, serverName)); clientConnection.handleLogLine("failed to connect to server"); } -TEST_F(ClientConnectionTests, handleLogLine_messageShown_shouldNotShowAgain) { +TEST_F(ClientConnectionTests, handleLogLine_messageShown_shouldNotShowAgain) +{ ClientConnection clientConnection(nullptr, m_appConfig, m_pDeps); clientConnection.handleLogLine("failed to connect to server"); @@ -99,9 +100,8 @@ TEST_F(ClientConnectionTests, handleLogLine_messageShown_shouldNotShowAgain) { clientConnection.handleLogLine("failed to connect to server"); } -TEST_F( - ClientConnectionTests, - handleLogLine_serverRefusedClient_shouldNotShowError) { +TEST_F(ClientConnectionTests, handleLogLine_serverRefusedClient_shouldNotShowError) +{ ClientConnection clientConnection(nullptr, m_appConfig, m_pDeps); EXPECT_CALL(*m_pDeps, showError(_, _, _)).Times(0); @@ -110,8 +110,8 @@ TEST_F( "server refused client with our name"); } -TEST_F( - ClientConnectionTests, handleLogLine_connected_shouldPreventFutureError) { +TEST_F(ClientConnectionTests, handleLogLine_connected_shouldPreventFutureError) +{ ClientConnection clientConnection(nullptr, m_appConfig, m_pDeps); clientConnection.handleLogLine("connected to server"); @@ -120,7 +120,8 @@ TEST_F( clientConnection.handleLogLine("failed to connect to server"); } -TEST_F(ClientConnectionTests, handleLogLine_otherMessage_shouldNotShowError) { +TEST_F(ClientConnectionTests, handleLogLine_otherMessage_shouldNotShowError) +{ ClientConnection clientConnection(nullptr, m_appConfig, m_pDeps); EXPECT_CALL(*m_pDeps, showError(_, _, _)).Times(0); diff --git a/src/test/unittests/gui/core/CoreProcessTests.cpp b/src/test/unittests/gui/core/CoreProcessTests.cpp index 01454cf72..250b4eb49 100644 --- a/src/test/unittests/gui/core/CoreProcessTests.cpp +++ b/src/test/unittests/gui/core/CoreProcessTests.cpp @@ -31,22 +31,24 @@ using namespace testing; namespace { -class QProcessProxyMock : public proxy::QProcessProxy { +class QProcessProxyMock : public proxy::QProcessProxy +{ public: - operator bool() const override { return toBool(); } + operator bool() const override + { + return toBool(); + } - QProcessProxyMock() { + QProcessProxyMock() + { ON_CALL(*this, toBool()).WillByDefault(Return(true)); - ON_CALL(*this, state()) - .WillByDefault(Return(QProcess::ProcessState::Running)); + ON_CALL(*this, state()).WillByDefault(Return(QProcess::ProcessState::Running)); ON_CALL(*this, waitForStarted()).WillByDefault(Return(true)); } MOCK_METHOD(bool, toBool, (), (const)); MOCK_METHOD(void, create, (), (override)); - MOCK_METHOD( - void, start, (const QString &program, const QStringList &arguments), - (override)); + MOCK_METHOD(void, start, (const QString &program, const QStringList &arguments), (override)); MOCK_METHOD(bool, waitForStarted, (), (override)); MOCK_METHOD(QProcess::ProcessState, state, (), (const, override)); MOCK_METHOD(void, close, (), (override)); @@ -54,24 +56,26 @@ public: MOCK_METHOD(QString, readAllStandardError, (), (override)); }; -class QIpcClientMock : public ipc::IQIpcClient { +class QIpcClientMock : public ipc::IQIpcClient +{ public: - QIpcClientMock() { + QIpcClientMock() + { ON_CALL(*this, isConnected()).WillByDefault(Return(true)); } MOCK_METHOD(void, sendHello, (), (const, override)); - MOCK_METHOD( - void, sendCommand, (const QString &command, ElevateMode elevate), - (const, override)); + MOCK_METHOD(void, sendCommand, (const QString &command, ElevateMode elevate), (const, override)); MOCK_METHOD(void, connectToHost, (), (override)); MOCK_METHOD(void, disconnectFromHost, (), (override)); MOCK_METHOD(bool, isConnected, (), (const, override)); }; -class DepsMock : public CoreProcess::Deps { +class DepsMock : public CoreProcess::Deps +{ public: - DepsMock() { + DepsMock() + { ON_CALL(*this, process()).WillByDefault(ReturnRef(m_process)); ON_CALL(*this, ipcClient()).WillByDefault(ReturnRef(m_ipcClient)); ON_CALL(*this, appPath(_)).WillByDefault(Return("stub app path")); @@ -89,20 +93,23 @@ public: NiceMock m_ipcClient; }; -class CoreProcessTests : public Test { +class CoreProcessTests : public Test +{ public: - CoreProcessTests() : m_coreProcess(m_appConfig, m_serverConfig, m_pDeps) {} + CoreProcessTests() : m_coreProcess(m_appConfig, m_serverConfig, m_pDeps) + { + } NiceMock m_appConfig; NiceMock m_serverConfig; - std::shared_ptr> m_pDeps = - std::make_shared>(); + std::shared_ptr> m_pDeps = std::make_shared>(); CoreProcess m_coreProcess; }; } // namespace -TEST_F(CoreProcessTests, start_serverDesktop_callsProcessStart) { +TEST_F(CoreProcessTests, start_serverDesktop_callsProcessStart) +{ m_coreProcess.setMode(CoreProcess::Mode::Server); EXPECT_CALL(m_pDeps->m_process, start(_, _)).Times(1); @@ -110,7 +117,8 @@ TEST_F(CoreProcessTests, start_serverDesktop_callsProcessStart) { m_coreProcess.start(ProcessMode::kDesktop); } -TEST_F(CoreProcessTests, start_serverService_callsSendCommand) { +TEST_F(CoreProcessTests, start_serverService_callsSendCommand) +{ m_coreProcess.setMode(CoreProcess::Mode::Server); EXPECT_CALL(m_pDeps->m_ipcClient, sendCommand(_, _)).Times(1); @@ -118,7 +126,8 @@ TEST_F(CoreProcessTests, start_serverService_callsSendCommand) { m_coreProcess.start(ProcessMode::kService); } -TEST_F(CoreProcessTests, start_clientDesktop_callsProcessStart) { +TEST_F(CoreProcessTests, start_clientDesktop_callsProcessStart) +{ m_coreProcess.setMode(CoreProcess::Mode::Client); m_coreProcess.setAddress("stub address"); @@ -127,7 +136,8 @@ TEST_F(CoreProcessTests, start_clientDesktop_callsProcessStart) { m_coreProcess.start(ProcessMode::kDesktop); } -TEST_F(CoreProcessTests, start_clientService_callsSendCommand) { +TEST_F(CoreProcessTests, start_clientService_callsSendCommand) +{ m_coreProcess.setMode(CoreProcess::Mode::Client); m_coreProcess.setAddress("stub address"); @@ -136,7 +146,8 @@ TEST_F(CoreProcessTests, start_clientService_callsSendCommand) { m_coreProcess.start(ProcessMode::kService); } -TEST_F(CoreProcessTests, stop_serverDesktop_callsProcessClose) { +TEST_F(CoreProcessTests, stop_serverDesktop_callsProcessClose) +{ m_coreProcess.setMode(CoreProcess::Mode::Server); m_coreProcess.start(); @@ -145,7 +156,8 @@ TEST_F(CoreProcessTests, stop_serverDesktop_callsProcessClose) { m_coreProcess.stop(ProcessMode::kDesktop); } -TEST_F(CoreProcessTests, stop_serverService_callsSendCommand) { +TEST_F(CoreProcessTests, stop_serverService_callsSendCommand) +{ m_coreProcess.setMode(CoreProcess::Mode::Server); m_coreProcess.start(); @@ -154,7 +166,8 @@ TEST_F(CoreProcessTests, stop_serverService_callsSendCommand) { m_coreProcess.stop(ProcessMode::kService); } -TEST_F(CoreProcessTests, stop_clientDesktop_callsProcessClose) { +TEST_F(CoreProcessTests, stop_clientDesktop_callsProcessClose) +{ m_coreProcess.setMode(CoreProcess::Mode::Client); m_coreProcess.setAddress("stub address"); m_coreProcess.start(); @@ -164,7 +177,8 @@ TEST_F(CoreProcessTests, stop_clientDesktop_callsProcessClose) { m_coreProcess.stop(ProcessMode::kDesktop); } -TEST_F(CoreProcessTests, stop_clientService_callsSendCommand) { +TEST_F(CoreProcessTests, stop_clientService_callsSendCommand) +{ m_coreProcess.setMode(CoreProcess::Mode::Client); m_coreProcess.setAddress("stub address"); m_coreProcess.start(); @@ -174,9 +188,9 @@ TEST_F(CoreProcessTests, stop_clientService_callsSendCommand) { m_coreProcess.stop(ProcessMode::kService); } -TEST_F(CoreProcessTests, restart_serverDesktop_callsProcessStart) { - ON_CALL(m_appConfig, processMode()) - .WillByDefault(Return(ProcessMode::kDesktop)); +TEST_F(CoreProcessTests, restart_serverDesktop_callsProcessStart) +{ + ON_CALL(m_appConfig, processMode()).WillByDefault(Return(ProcessMode::kDesktop)); m_coreProcess.setMode(CoreProcess::Mode::Server); m_coreProcess.start(); diff --git a/src/test/unittests/gui/core/ServerConnectionTests.cpp b/src/test/unittests/gui/core/ServerConnectionTests.cpp index ebd40dbcb..93eaee1f6 100644 --- a/src/test/unittests/gui/core/ServerConnectionTests.cpp +++ b/src/test/unittests/gui/core/ServerConnectionTests.cpp @@ -33,15 +33,18 @@ class QWidget; namespace { -struct DepsMock : public ServerConnection::Deps { +struct DepsMock : public ServerConnection::Deps +{ MOCK_METHOD( - messages::NewClientPromptResult, showNewClientPrompt, - (QWidget * parent, const QString &clientName), (const, override)); + messages::NewClientPromptResult, showNewClientPrompt, (QWidget * parent, const QString &clientName), + (const, override) + ); }; } // namespace -class ServerConnectionTests : public testing::Test { +class ServerConnectionTests : public testing::Test +{ public: std::shared_ptr m_pDeps = std::make_shared>(); NiceMock m_appConfig; @@ -49,9 +52,9 @@ public: config::ServerConfigDialogState m_serverConfigDialogState; }; -TEST_F(ServerConnectionTests, handleLogLine_newClient_shouldShowPrompt) { - ServerConnection serverConnection( - nullptr, m_appConfig, m_serverConfig, m_serverConfigDialogState, m_pDeps); +TEST_F(ServerConnectionTests, handleLogLine_newClient_shouldShowPrompt) +{ + ServerConnection serverConnection(nullptr, m_appConfig, m_serverConfig, m_serverConfigDialogState, m_pDeps); QString clientName = "test client"; EXPECT_CALL(*m_pDeps, showNewClientPrompt(_, clientName)); @@ -59,11 +62,10 @@ TEST_F(ServerConnectionTests, handleLogLine_newClient_shouldShowPrompt) { serverConnection.handleLogLine(R"(unrecognised client name "test client")"); } -TEST_F(ServerConnectionTests, handleLogLine_ignoredClient_shouldNotShowPrompt) { - ServerConnection serverConnection( - nullptr, m_appConfig, m_serverConfig, m_serverConfigDialogState, m_pDeps); - ON_CALL(*m_pDeps, showNewClientPrompt(_, _)) - .WillByDefault(testing::Return(messages::NewClientPromptResult::Ignore)); +TEST_F(ServerConnectionTests, handleLogLine_ignoredClient_shouldNotShowPrompt) +{ + ServerConnection serverConnection(nullptr, m_appConfig, m_serverConfig, m_serverConfigDialogState, m_pDeps); + ON_CALL(*m_pDeps, showNewClientPrompt(_, _)).WillByDefault(testing::Return(messages::NewClientPromptResult::Ignore)); serverConnection.handleLogLine(R"(unrecognised client name "stub")"); EXPECT_CALL(*m_pDeps, showNewClientPrompt(_, _)).Times(0); @@ -71,10 +73,9 @@ TEST_F(ServerConnectionTests, handleLogLine_ignoredClient_shouldNotShowPrompt) { serverConnection.handleLogLine(R"(unrecognised client name "stub")"); } -TEST_F( - ServerConnectionTests, handleLogLine_serverConfigFull_shouldNotShowPrompt) { - ServerConnection serverConnection( - nullptr, m_appConfig, m_serverConfig, m_serverConfigDialogState, m_pDeps); +TEST_F(ServerConnectionTests, handleLogLine_serverConfigFull_shouldNotShowPrompt) +{ + ServerConnection serverConnection(nullptr, m_appConfig, m_serverConfig, m_serverConfigDialogState, m_pDeps); ON_CALL(m_serverConfig, isFull()).WillByDefault(testing::Return(true)); EXPECT_CALL(*m_pDeps, showNewClientPrompt(_, _)).Times(0); @@ -82,9 +83,9 @@ TEST_F( serverConnection.handleLogLine(R"(unrecognised client name "test client")"); } -TEST_F(ServerConnectionTests, handleLogLine_screenExists_shouldNotShowPrompt) { - ServerConnection serverConnection( - nullptr, m_appConfig, m_serverConfig, m_serverConfigDialogState, m_pDeps); +TEST_F(ServerConnectionTests, handleLogLine_screenExists_shouldNotShowPrompt) +{ + ServerConnection serverConnection(nullptr, m_appConfig, m_serverConfig, m_serverConfigDialogState, m_pDeps); ON_CALL(m_serverConfig, screenExists(_)).WillByDefault(testing::Return(true)); EXPECT_CALL(*m_pDeps, showNewClientPrompt(_, _)).Times(0); diff --git a/src/test/unittests/gui/core/WaylandWarningsTests.cpp b/src/test/unittests/gui/core/WaylandWarningsTests.cpp index 73b427776..436379a4c 100644 --- a/src/test/unittests/gui/core/WaylandWarningsTests.cpp +++ b/src/test/unittests/gui/core/WaylandWarningsTests.cpp @@ -26,13 +26,15 @@ using namespace deskflow::gui; using namespace deskflow::gui::core; namespace { -struct MockDeps : public WaylandWarnings::Deps { +struct MockDeps : public WaylandWarnings::Deps +{ MOCK_METHOD(void, showWaylandLibraryError, (QWidget *), (override)); }; } // namespace -TEST(WaylandWarningsTests, showOnce_serverNoEi_showLibraryError) { +TEST(WaylandWarningsTests, showOnce_serverNoEi_showLibraryError) +{ const auto deps = std::make_shared(); const bool hasEi = false; const bool hasPortal = false; @@ -41,11 +43,11 @@ TEST(WaylandWarningsTests, showOnce_serverNoEi_showLibraryError) { EXPECT_CALL(*deps, showWaylandLibraryError(nullptr)).Times(1); - waylandWarnings.showOnce( - nullptr, CoreProcess::Mode::Server, hasEi, hasPortal, hasPortalIC); + waylandWarnings.showOnce(nullptr, CoreProcess::Mode::Server, hasEi, hasPortal, hasPortalIC); } -TEST(WaylandWarningsTests, showOnce_serverNoPortal_showLibraryError) { +TEST(WaylandWarningsTests, showOnce_serverNoPortal_showLibraryError) +{ const auto deps = std::make_shared(); const bool hasEi = true; const bool hasPortal = false; @@ -54,11 +56,11 @@ TEST(WaylandWarningsTests, showOnce_serverNoPortal_showLibraryError) { EXPECT_CALL(*deps, showWaylandLibraryError(nullptr)).Times(1); - waylandWarnings.showOnce( - nullptr, CoreProcess::Mode::Server, hasEi, hasPortal, hasPortalIC); + waylandWarnings.showOnce(nullptr, CoreProcess::Mode::Server, hasEi, hasPortal, hasPortalIC); } -TEST(WaylandWarningsTests, showOnce_serverNoPortalIc_showLibraryError) { +TEST(WaylandWarningsTests, showOnce_serverNoPortalIc_showLibraryError) +{ const auto deps = std::make_shared(); const bool hasEi = true; const bool hasPortal = true; @@ -67,11 +69,11 @@ TEST(WaylandWarningsTests, showOnce_serverNoPortalIc_showLibraryError) { EXPECT_CALL(*deps, showWaylandLibraryError(nullptr)).Times(1); - waylandWarnings.showOnce( - nullptr, CoreProcess::Mode::Server, hasEi, hasPortal, hasPortalIC); + waylandWarnings.showOnce(nullptr, CoreProcess::Mode::Server, hasEi, hasPortal, hasPortalIC); } -TEST(WaylandWarningsTests, showOnce_failureCalledTwice_messageOnlyShownOnce) { +TEST(WaylandWarningsTests, showOnce_failureCalledTwice_messageOnlyShownOnce) +{ const auto deps = std::make_shared(); const bool hasEi = false; const bool hasPortal = false; @@ -80,8 +82,6 @@ TEST(WaylandWarningsTests, showOnce_failureCalledTwice_messageOnlyShownOnce) { EXPECT_CALL(*deps, showWaylandLibraryError(nullptr)).Times(1); - waylandWarnings.showOnce( - nullptr, CoreProcess::Mode::Server, hasEi, hasPortal, hasPortalIC); - waylandWarnings.showOnce( - nullptr, CoreProcess::Mode::Server, hasEi, hasPortal, hasPortalIC); + waylandWarnings.showOnce(nullptr, CoreProcess::Mode::Server, hasEi, hasPortal, hasPortalIC); + waylandWarnings.showOnce(nullptr, CoreProcess::Mode::Server, hasEi, hasPortal, hasPortalIC); } diff --git a/src/test/unittests/gui/dialogs/AboutDialogTests.cpp b/src/test/unittests/gui/dialogs/AboutDialogTests.cpp index 065694a02..e9d75baed 100644 --- a/src/test/unittests/gui/dialogs/AboutDialogTests.cpp +++ b/src/test/unittests/gui/dialogs/AboutDialogTests.cpp @@ -31,14 +31,16 @@ using namespace testing; namespace { -class DepsMock : public AboutDialog::Deps { +class DepsMock : public AboutDialog::Deps +{ public: MOCK_METHOD(bool, isDarkMode, (), (const, override)); }; } // namespace -TEST(AboutDialogTests, exec_setsDevelopersLabel) { +TEST(AboutDialogTests, exec_setsDevelopersLabel) +{ TestQtFullApp app; const auto deps = std::make_shared>(); AboutDialog aboutDialog(nullptr, deps); @@ -50,7 +52,8 @@ TEST(AboutDialogTests, exec_setsDevelopersLabel) { EXPECT_TRUE(label->text().contains("Chris Schoeneman")); } -TEST(AboutDialogTests, exec_setsCopyrightLabel) { +TEST(AboutDialogTests, exec_setsCopyrightLabel) +{ TestQtFullApp app; const auto deps = std::make_shared>(); AboutDialog aboutDialog(nullptr, deps); @@ -59,11 +62,12 @@ TEST(AboutDialogTests, exec_setsCopyrightLabel) { aboutDialog.exec(); EXPECT_EQ( - aboutDialog.findChild("m_pCopyrightLabel")->text(), - QString::fromStdString(deskflow::copyright())); + aboutDialog.findChild("m_pCopyrightLabel")->text(), QString::fromStdString(deskflow::copyright()) + ); } -TEST(AboutDialogTests, exec_inDarkMode_usesDarkLogo) { +TEST(AboutDialogTests, exec_inDarkMode_usesDarkLogo) +{ TestQtFullApp app; const auto deps = std::make_shared>(); AboutDialog aboutDialog(nullptr, deps); @@ -73,13 +77,13 @@ TEST(AboutDialogTests, exec_inDarkMode_usesDarkLogo) { aboutDialog.exec(); const QPixmap expectedLogo(":/image/logo-dark.png"); - const auto actualLogo = - aboutDialog.findChild("m_pLabel_Logo")->pixmap(); + const auto actualLogo = aboutDialog.findChild("m_pLabel_Logo")->pixmap(); EXPECT_FALSE(actualLogo.isNull()); EXPECT_EQ(actualLogo.toImage(), expectedLogo.toImage()); } -TEST(AboutDialogTests, exec_notInDarkMode_usesLightLogo) { +TEST(AboutDialogTests, exec_notInDarkMode_usesLightLogo) +{ TestQtFullApp app; const auto deps = std::make_shared>(); AboutDialog aboutDialog(nullptr, deps); @@ -89,8 +93,7 @@ TEST(AboutDialogTests, exec_notInDarkMode_usesLightLogo) { aboutDialog.exec(); const QPixmap expectedLogo(":/image/logo-light.png"); - const auto actualLogo = - aboutDialog.findChild("m_pLabel_Logo")->pixmap(); + const auto actualLogo = aboutDialog.findChild("m_pLabel_Logo")->pixmap(); EXPECT_FALSE(actualLogo.isNull()); EXPECT_EQ(actualLogo.toImage(), expectedLogo.toImage()); } diff --git a/src/test/unittests/gui/dialogs/SettingsDialogTests.cpp b/src/test/unittests/gui/dialogs/SettingsDialogTests.cpp index 6f09741f3..b87bd2277 100644 --- a/src/test/unittests/gui/dialogs/SettingsDialogTests.cpp +++ b/src/test/unittests/gui/dialogs/SettingsDialogTests.cpp @@ -29,7 +29,8 @@ using namespace testing; using namespace deskflow::gui; -TEST(SettingsDialogTests, ctor_getsScreenName) { +TEST(SettingsDialogTests, ctor_getsScreenName) +{ TestQtFullApp app; NiceMock appConfig; NiceMock serverConfig; diff --git a/src/test/unittests/gui/ipc/QIpcClientTests.cpp b/src/test/unittests/gui/ipc/QIpcClientTests.cpp index 9797ebd8d..a13a495cd 100644 --- a/src/test/unittests/gui/ipc/QIpcClientTests.cpp +++ b/src/test/unittests/gui/ipc/QIpcClientTests.cpp @@ -23,16 +23,16 @@ using testing::_; using testing::StrEq; -class MockStream : public QDataStreamProxy { +class MockStream : public QDataStreamProxy +{ public: MOCK_METHOD(qint64, writeRawData, (const char *, int), (override)); }; -TEST(QIpcClientTests, sendCommand_anyCommand_commandSent) { +TEST(QIpcClientTests, sendCommand_anyCommand_commandSent) +{ auto mockStream = std::make_shared(); - QIpcClient::StreamProvider streamProvider = [&mockStream]() { - return mockStream; - }; + QIpcClient::StreamProvider streamProvider = [&mockStream]() { return mockStream; }; EXPECT_CALL(*mockStream, writeRawData(_, _)).Times(3); EXPECT_CALL(*mockStream, writeRawData(StrEq("test"), 4)).Times(1); diff --git a/src/test/unittests/ipc/IpcSettingMessageTests.cpp b/src/test/unittests/ipc/IpcSettingMessageTests.cpp index 5c14a7ebb..ae6930fe3 100644 --- a/src/test/unittests/ipc/IpcSettingMessageTests.cpp +++ b/src/test/unittests/ipc/IpcSettingMessageTests.cpp @@ -21,7 +21,8 @@ #include -TEST(IpcSettingMessage, testIpcSettingMessage) { +TEST(IpcSettingMessage, testIpcSettingMessage) +{ const std::string expected_name = "test"; const std::string expected_value = "test_value"; diff --git a/src/test/unittests/main.cpp b/src/test/unittests/main.cpp index 43a56fe04..634bc7467 100644 --- a/src/test/unittests/main.cpp +++ b/src/test/unittests/main.cpp @@ -31,7 +31,8 @@ using deskflow::test::ExitTimeout; const auto testDir = "tmp/test"; -int main(int argc, char **argv) { +int main(int argc, char **argv) +{ // HACK: Unit tests should not use the filesystem. std::filesystem::create_directories(testDir); diff --git a/src/test/unittests/platform/OSXClipboardUTF8ConverterTest.cpp b/src/test/unittests/platform/OSXClipboardUTF8ConverterTest.cpp index 1dc4bb6ec..70f1a88c7 100644 --- a/src/test/unittests/platform/OSXClipboardUTF8ConverterTest.cpp +++ b/src/test/unittests/platform/OSXClipboardUTF8ConverterTest.cpp @@ -20,13 +20,15 @@ #include -TEST(OSXClipboardUTF8ConverterTests, test_Format) { +TEST(OSXClipboardUTF8ConverterTests, test_Format) +{ OSXClipboardUTF8Converter converter; EXPECT_EQ(IClipboard::kText, converter.getFormat()); EXPECT_EQ(CFSTR("public.utf8-plain-text"), converter.getOSXFormat()); } -TEST(OSXClipboardUTF8ConverterTests, test_readWriteClipboard) { +TEST(OSXClipboardUTF8ConverterTests, test_readWriteClipboard) +{ OSXClipboardUTF8Converter converter; EXPECT_EQ("test data\r", converter.fromIClipboard("test data\n")); EXPECT_EQ("test data\n", converter.toIClipboard("test data\r")); diff --git a/src/test/unittests/platform/OSXKeyStateTests.cpp b/src/test/unittests/platform/OSXKeyStateTests.cpp index 7cd793c43..4610c9b4b 100644 --- a/src/test/unittests/platform/OSXKeyStateTests.cpp +++ b/src/test/unittests/platform/OSXKeyStateTests.cpp @@ -23,7 +23,8 @@ #include #include -TEST(OSXKeyStateTests, mapModifiersFromOSX_OSXMask_returnDeskflowMask) { +TEST(OSXKeyStateTests, mapModifiersFromOSX_OSXMask_returnDeskflowMask) +{ deskflow::KeyMap keyMap; MockEventQueue eventQueue; OSXKeyState keyState(&eventQueue, keyMap, {"en"}, true); diff --git a/src/test/unittests/platform/XWindowsClipboardTests.cpp b/src/test/unittests/platform/XWindowsClipboardTests.cpp index 84019fc00..e9d4bc907 100644 --- a/src/test/unittests/platform/XWindowsClipboardTests.cpp +++ b/src/test/unittests/platform/XWindowsClipboardTests.cpp @@ -23,15 +23,20 @@ const auto None = 0L; -class TestXWindowsClipboard : public XWindowsClipboard { +class TestXWindowsClipboard : public XWindowsClipboard +{ public: - class TestCICCCMGetClipboard : public CICCCMGetClipboard { + class TestCICCCMGetClipboard : public CICCCMGetClipboard + { public: - TestCICCCMGetClipboard() : CICCCMGetClipboard(None, None, None) {} + TestCICCCMGetClipboard() : CICCCMGetClipboard(None, None, None) + { + } }; }; -TEST(XWindowsClipboardTests_CICCCMGetClipboard, ctor_default_errorNone) { +TEST(XWindowsClipboardTests_CICCCMGetClipboard, ctor_default_errorNone) +{ TestXWindowsClipboard::TestCICCCMGetClipboard clipboard; EXPECT_EQ(None, clipboard.error()); diff --git a/src/test/unittests/server/ServerTests.cpp b/src/test/unittests/server/ServerTests.cpp index 09134864b..fa75c7a0e 100644 --- a/src/test/unittests/server/ServerTests.cpp +++ b/src/test/unittests/server/ServerTests.cpp @@ -2,15 +2,16 @@ #include -TEST(ServerTests, SwitchToScreenInfo_alloc_screen) { +TEST(ServerTests, SwitchToScreenInfo_alloc_screen) +{ auto info = Server::SwitchToScreenInfo::alloc("test"); EXPECT_STREQ(info->m_screen, "test"); } -TEST(ServerTests, KeyboardBroadcastInfo_alloc_stateAndSceens) { - auto info = Server::KeyboardBroadcastInfo::alloc( - Server::KeyboardBroadcastInfo::State::kOn, "test"); +TEST(ServerTests, KeyboardBroadcastInfo_alloc_stateAndSceens) +{ + auto info = Server::KeyboardBroadcastInfo::alloc(Server::KeyboardBroadcastInfo::State::kOn, "test"); EXPECT_EQ(info->m_state, Server::KeyboardBroadcastInfo::State::kOn); EXPECT_STREQ(info->m_screens, "test");