id
int64 0
755k
| file_name
stringlengths 3
109
| file_path
stringlengths 13
185
| content
stringlengths 31
9.38M
| size
int64 31
9.38M
| language
stringclasses 1
value | extension
stringclasses 11
values | total_lines
int64 1
340k
| avg_line_length
float64 2.18
149k
| max_line_length
int64 7
2.22M
| alphanum_fraction
float64 0
1
| repo_name
stringlengths 6
65
| repo_stars
int64 100
47.3k
| repo_forks
int64 0
12k
| repo_open_issues
int64 0
3.4k
| repo_license
stringclasses 9
values | repo_extraction_date
stringclasses 92
values | exact_duplicates_redpajama
bool 2
classes | near_duplicates_redpajama
bool 2
classes | exact_duplicates_githubcode
bool 2
classes | exact_duplicates_stackv2
bool 1
class | exact_duplicates_stackv1
bool 2
classes | near_duplicates_githubcode
bool 2
classes | near_duplicates_stackv1
bool 2
classes | near_duplicates_stackv2
bool 1
class |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
13,582
|
MSWindowsHook.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsHook.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2011 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/MSWindowsHook.h"
#include "base/Log.h"
#include "deskflow/XScreen.h"
#include "deskflow/protocol_types.h"
static const char *g_name = "dfwhook";
static DWORD g_processID = 0;
static DWORD g_threadID = 0;
static HHOOK g_getMessage = NULL;
static HHOOK g_keyboardLL = NULL;
static HHOOK g_mouseLL = NULL;
static bool g_screenSaver = false;
static EHookMode g_mode = kHOOK_DISABLE;
static UInt32 g_zoneSides = 0;
static SInt32 g_zoneSize = 0;
static SInt32 g_xScreen = 0;
static SInt32 g_yScreen = 0;
static SInt32 g_wScreen = 0;
static SInt32 g_hScreen = 0;
static WPARAM g_deadVirtKey = 0;
static WPARAM g_deadRelease = 0;
static LPARAM g_deadLParam = 0;
static BYTE g_deadKeyState[256] = {0};
static BYTE g_keyState[256] = {0};
static DWORD g_hookThread = 0;
static bool g_fakeServerInput = false;
static BOOL g_isPrimary = TRUE;
MSWindowsHook::MSWindowsHook()
{
}
MSWindowsHook::~MSWindowsHook()
{
cleanup();
if (g_processID == GetCurrentProcessId()) {
uninstall();
uninstallScreenSaver();
g_processID = 0;
}
}
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_INFO "restarting your computer may solve this error"));
throw XScreenOpenFailure();
}
}
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()) {
HANDLE process = OpenProcess(STANDARD_RIGHTS_REQUIRED, FALSE, g_processID);
if (process != NULL) {
// old process (probably) still exists so refuse to
// reinitialize this DLL (and thus steal it from the
// old process).
int result = CloseHandle(process);
if (result == false) {
return 0;
}
}
// clean up after old process. the system should've already
// removed the hooks so we just need to reset our state.
g_processID = GetCurrentProcessId();
g_threadID = 0;
g_getMessage = NULL;
g_keyboardLL = NULL;
g_mouseLL = NULL;
g_screenSaver = false;
}
// save thread id. we'll post messages to this thread's
// message queue.
g_threadID = threadID;
// set defaults
g_mode = kHOOK_DISABLE;
g_zoneSides = 0;
g_zoneSize = 0;
g_xScreen = 0;
g_yScreen = 0;
g_wScreen = 0;
g_hScreen = 0;
return 1;
}
int MSWindowsHook::cleanup()
{
if (g_processID == GetCurrentProcessId()) {
g_threadID = 0;
}
return 1;
}
void MSWindowsHook::setSides(UInt32 sides)
{
g_zoneSides = sides;
}
void MSWindowsHook::setZone(SInt32 x, SInt32 y, SInt32 w, SInt32 h, SInt32 jumpZoneSize)
{
g_zoneSize = jumpZoneSize;
g_xScreen = x;
g_yScreen = y;
g_wScreen = w;
g_hScreen = h;
}
void MSWindowsHook::setMode(EHookMode mode)
{
if (mode == g_mode) {
// no change
return;
}
g_mode = mode;
}
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
// side effects, like alt and the windows key.
if (vkCode < 0 || vkCode >= 256) {
return;
}
// Keep track of key state on our own in case GetAsyncKeyState() fails
g_keyState[vkCode] = kf_up ? 0 : 0x80;
g_keyState[VK_SHIFT] = g_keyState[VK_LSHIFT] | g_keyState[VK_RSHIFT];
SHORT key;
// Test whether GetAsyncKeyState() is being honest with us
key = GetAsyncKeyState(vkCode);
if (key & 0x80) {
// The only time we know for sure that GetAsyncKeyState() is working
// is when it tells us that the current key is down.
// In this case, update g_keyState to reflect what GetAsyncKeyState()
// is telling us, just in case we have gotten out of sync
for (int i = 0; i < 256; ++i) {
key = GetAsyncKeyState(i);
g_keyState[i] = (BYTE)((key < 0) ? 0x80u : 0);
}
}
// copy g_keyState to keys
for (int i = 0; i < 256; ++i) {
keys[i] = g_keyState[i];
}
key = GetKeyState(VK_CAPITAL);
keys[VK_CAPITAL] = (BYTE)(((key < 0) ? 0x80 : 0) | (key & 1));
}
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)
{
if (g_deadVirtKey != 0) {
auto virtualKey = static_cast<UINT>(g_deadVirtKey);
auto scanCode = static_cast<UINT>((g_deadLParam & 0x10ff0000u) >> 16);
if (ToUnicode(virtualKey, scanCode, g_deadKeyState, wc, size, flags) >= 2) {
// If ToUnicode returned >=2, it means that we accidentally removed
// a double dead key instead of restoring it. Thus, we call
// ToUnicode again with the same parameters to restore the
// internal dead key state.
ToUnicode(virtualKey, scanCode, g_deadKeyState, wc, size, flags);
// We need to keep track of this because g_deadVirtKey will be
// cleared later on; this would cause the dead key release to
// incorrectly restore the dead key state.
g_deadRelease = g_deadVirtKey;
}
}
}
static bool keyboardHookHandler(WPARAM wParam, LPARAM lParam)
{
DWORD vkCode = static_cast<DWORD>(wParam);
bool kf_up = (lParam & (KF_UP << 16)) != 0;
// check for special events indicating if we should start or stop
// 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) {
// update flag
g_fakeServerInput = ((lParam & 0x80000000u) == 0);
PostThreadMessage(g_threadID, DESKFLOW_MSG_DEBUG, 0xff000000u | wParam, lParam);
// discard event
return true;
}
// 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);
return false;
}
// VK_RSHIFT may be sent with an extended scan code but right shift
// is not an extended key so we reset that bit.
if (wParam == VK_RSHIFT) {
lParam &= ~0x01000000u;
}
// tell server about event
PostThreadMessage(g_threadID, DESKFLOW_MSG_DEBUG, wParam, lParam);
// ignore dead key release
if ((g_deadVirtKey == wParam || g_deadRelease == wParam) && (lParam & 0x80000000u) != 0) {
g_deadRelease = 0;
PostThreadMessage(g_threadID, DESKFLOW_MSG_DEBUG, wParam | 0x04000000, lParam);
return false;
}
// we need the keyboard state for ToAscii()
BYTE keys[256];
keyboardGetState(keys, vkCode, kf_up);
// ToAscii() maps ctrl+letter to the corresponding control code
// and ctrl+backspace to delete. we don't want those translations
// so clear the control modifier state. however, if we want to
// simulate AltGr (which is ctrl+alt) then we must not clear it.
UINT control = keys[VK_CONTROL] | keys[VK_LCONTROL] | keys[VK_RCONTROL];
UINT menu = keys[VK_MENU] | keys[VK_LMENU] | keys[VK_RMENU];
if ((control & 0x80) == 0 || (menu & 0x80) == 0) {
keys[VK_LCONTROL] = 0;
keys[VK_RCONTROL] = 0;
keys[VK_CONTROL] = 0;
} else {
keys[VK_LCONTROL] = 0x80;
keys[VK_RCONTROL] = 0x80;
keys[VK_CONTROL] = 0x80;
keys[VK_LMENU] = 0x80;
keys[VK_RMENU] = 0x80;
keys[VK_MENU] = 0x80;
}
// ToAscii() needs to know if a menu is active for some reason.
// we don't know and there doesn't appear to be any way to find
// out. so we'll just assume a menu is active if the menu key
// is down.
// FIXME -- figure out some way to check if a menu is active
UINT flags = 0;
if ((menu & 0x80) != 0)
flags |= 1;
// if we're on the server screen then just pass numpad keys with alt
// key down as-is. we won't pick up the resulting character but the
// local app will. if on a client screen then grab keys as usual;
// if the client is a windows system it'll synthesize the expected
// character. if not then it'll probably just do nothing.
if (g_mode != kHOOK_RELAY_EVENTS) {
// we don't use virtual keys because we don't know what the
// state of the numlock key is. we'll hard code the scan codes
// instead. hopefully this works across all keyboards.
UINT sc = (lParam & 0x01ff0000u) >> 16;
if (menu && (sc >= 0x47u && sc <= 0x52u && sc != 0x4au && sc != 0x4eu)) {
return false;
}
}
// map the key event to a character. we have to put the dead
// key back first and this has the side effect of removing it.
WCHAR wc[] = {0, 0};
setDeadKey(wc, 2, flags);
UINT scanCode = ((lParam & 0x10ff0000u) >> 16);
int n = ToUnicode((UINT)wParam, scanCode, keys, wc, 2, flags);
// if mapping failed and ctrl and alt are pressed then try again
// with both not pressed. this handles the case where ctrl and
// alt are being used as individual modifiers rather than AltGr.
// we note that's the case in the message sent back to deskflow
// because there's no simple way to deduce it after the fact.
// we have to put the dead key back first, if there was one.
bool noAltGr = false;
if (n == 0 && (control & 0x80) != 0 && (menu & 0x80) != 0) {
noAltGr = true;
PostThreadMessage(g_threadID, DESKFLOW_MSG_DEBUG, wParam | 0x05000000, lParam);
setDeadKey(wc, 2, flags);
BYTE keys2[256];
for (size_t i = 0; i < sizeof(keys) / sizeof(keys[0]); ++i) {
keys2[i] = keys[i];
}
keys2[VK_LCONTROL] = 0;
keys2[VK_RCONTROL] = 0;
keys2[VK_CONTROL] = 0;
keys2[VK_LMENU] = 0;
keys2[VK_RMENU] = 0;
keys2[VK_MENU] = 0;
n = ToUnicode((UINT)wParam, scanCode, keys2, wc, 2, flags);
}
PostThreadMessage(
g_threadID, DESKFLOW_MSG_DEBUG, (wc[0] & 0xffff) | ((wParam & 0xff) << 16) | ((n & 0xf) << 24) | 0x60000000,
lParam
);
WPARAM charAndVirtKey = 0;
bool clearDeadKey = false;
switch (n) {
default:
// key is a dead key
if (lParam & 0x80000000u)
// This handles the obscure situation where a key has been
// pressed which is both a dead key and a normal character
// depending on which modifiers have been pressed. We
// break here to prevent it from being considered a dead
// key.
break;
g_deadVirtKey = wParam;
g_deadLParam = lParam;
for (size_t i = 0; i < sizeof(keys) / sizeof(keys[0]); ++i) {
g_deadKeyState[i] = keys[i];
}
break;
case 0:
// key doesn't map to a character. this can happen if
// non-character keys are pressed after a dead key.
charAndVirtKey = makeKeyMsg((UINT)wParam, 0, noAltGr);
break;
case 1:
// key maps to a character composed with dead key
charAndVirtKey = makeKeyMsg((UINT)wParam, wc[0], noAltGr);
clearDeadKey = true;
break;
case 2: {
// 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);
// use uncomposed character
charAndVirtKey = makeKeyMsg((UINT)wParam, wc[1], noAltGr);
clearDeadKey = true;
break;
}
}
// 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);
}
// clear out old dead key state
if (clearDeadKey) {
g_deadVirtKey = 0;
g_deadLParam = 0;
}
// forward message to our window. do this whether or not we're
// forwarding events to clients because this'll keep our thread's
// key state table up to date. that's important for querying
// the scroll lock toggle state.
// 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_KEY, charAndVirtKey, lParam);
}
if (g_mode == kHOOK_RELAY_EVENTS) {
// let certain keys pass through
switch (wParam) {
case VK_CAPITAL:
case VK_NUMLOCK:
case VK_SCROLL:
// pass event on. we want to let these through to
// the window proc because otherwise the keyboard
// lights may not stay synchronized.
break;
case VK_HANGUL:
// pass these modifiers if using a low level hook, discard
// them if not.
if (g_hookThread == 0) {
return true;
}
break;
default:
// discard
return true;
}
}
return false;
}
#if !NO_GRAB_KEYBOARD
static LRESULT CALLBACK keyboardLLHook(int code, WPARAM wParam, LPARAM lParam)
{
if (code >= 0) {
// decode the message
KBDLLHOOKSTRUCT *info = reinterpret_cast<KBDLLHOOKSTRUCT *>(lParam);
bool const injected = info->flags & LLKHF_INJECTED;
if (!g_isPrimary && injected) {
return CallNextHookEx(g_keyboardLL, code, wParam, lParam);
}
WPARAM wParam = info->vkCode;
LPARAM lParam = 1; // repeat code
lParam |= (info->scanCode << 16); // scan code
if (info->flags & LLKHF_EXTENDED) {
lParam |= (1lu << 24); // extended key
}
if (info->flags & LLKHF_ALTDOWN) {
lParam |= (1lu << 29); // context code
}
if (info->flags & LLKHF_UP) {
lParam |= (1lu << 31); // transition
}
// FIXME -- bit 30 should be set if key was already down but
// we don't know that info. as a result we'll never generate
// key repeat events.
// handle the message
if (keyboardHookHandler(wParam, lParam)) {
return 1;
}
}
return CallNextHookEx(g_keyboardLL, code, wParam, lParam);
}
#endif
//
// low-level mouse hook -- this allows us to capture and handle mouse
// events very early. the earlier the better.
//
static bool mouseHookHandler(WPARAM wParam, SInt32 x, SInt32 y, SInt32 data)
{
switch (wParam) {
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_XBUTTONDOWN:
case WM_LBUTTONDBLCLK:
case WM_MBUTTONDBLCLK:
case WM_RBUTTONDBLCLK:
case WM_XBUTTONDBLCLK:
case WM_LBUTTONUP:
case WM_MBUTTONUP:
case WM_RBUTTONUP:
case WM_XBUTTONUP:
case WM_NCLBUTTONDOWN:
case WM_NCMBUTTONDOWN:
case WM_NCRBUTTONDOWN:
case WM_NCXBUTTONDOWN:
case WM_NCLBUTTONDBLCLK:
case WM_NCMBUTTONDBLCLK:
case WM_NCRBUTTONDBLCLK:
case WM_NCXBUTTONDBLCLK:
case WM_NCLBUTTONUP:
case WM_NCMBUTTONUP:
case WM_NCRBUTTONUP:
case WM_NCXBUTTONUP:
// always relay the event. eat it if relaying.
PostThreadMessage(g_threadID, DESKFLOW_MSG_MOUSE_BUTTON, wParam, data);
return (g_mode == kHOOK_RELAY_EVENTS);
case WM_MOUSEWHEEL:
if (g_mode == kHOOK_RELAY_EVENTS) {
// relay event
PostThreadMessage(g_threadID, DESKFLOW_MSG_MOUSE_WHEEL, data, 0);
}
return (g_mode == kHOOK_RELAY_EVENTS);
case WM_NCMOUSEMOVE:
case WM_MOUSEMOVE:
if (g_mode == kHOOK_RELAY_EVENTS) {
// relay and eat event
PostThreadMessage(g_threadID, DESKFLOW_MSG_MOUSE_MOVE, x, y);
return true;
} else if (g_mode == kHOOK_WATCH_JUMP_ZONE) {
// low level hooks can report bogus mouse positions that are
// outside of the screen. jeez. naturally we end up getting
// fake motion in the other direction to get the position back
// on the screen, which plays havoc with switch on double tap.
// Server deals with that. we'll clamp positions onto the
// screen. also, if we discard events for positions outside
// of the screen then the mouse appears to get a bit jerky
// near the edge. we can either accept that or pass the bogus
// events. we'll try passing the events.
bool bogus = false;
if (x < g_xScreen) {
x = g_xScreen;
bogus = true;
} else if (x >= g_xScreen + g_wScreen) {
x = g_xScreen + g_wScreen - 1;
bogus = true;
}
if (y < g_yScreen) {
y = g_yScreen;
bogus = true;
} else if (y >= g_yScreen + g_hScreen) {
y = g_yScreen + g_hScreen - 1;
bogus = true;
}
// check for mouse inside jump zone
bool inside = false;
if (!inside && (g_zoneSides & kLeftMask) != 0) {
inside = (x < g_xScreen + g_zoneSize);
}
if (!inside && (g_zoneSides & kRightMask) != 0) {
inside = (x >= g_xScreen + g_wScreen - g_zoneSize);
}
if (!inside && (g_zoneSides & kTopMask) != 0) {
inside = (y < g_yScreen + g_zoneSize);
}
if (!inside && (g_zoneSides & kBottomMask) != 0) {
inside = (y >= g_yScreen + g_hScreen - g_zoneSize);
}
// relay the event
PostThreadMessage(g_threadID, DESKFLOW_MSG_MOUSE_MOVE, x, y);
// if inside and not bogus then eat the event
return inside && !bogus;
}
}
// pass the event
return false;
}
static LRESULT CALLBACK mouseLLHook(int code, WPARAM wParam, LPARAM lParam)
{
if (code >= 0) {
// decode the message
MSLLHOOKSTRUCT *info = reinterpret_cast<MSLLHOOKSTRUCT *>(lParam);
bool const injected = info->flags & LLMHF_INJECTED;
if (!g_isPrimary && injected) {
return CallNextHookEx(g_mouseLL, code, wParam, lParam);
}
SInt32 x = static_cast<SInt32>(info->pt.x);
SInt32 y = static_cast<SInt32>(info->pt.y);
SInt32 w = static_cast<SInt16>(HIWORD(info->mouseData));
// handle the message
if (mouseHookHandler(wParam, x, y, w)) {
return 1;
}
}
return CallNextHookEx(g_mouseLL, code, wParam, lParam);
}
EHookResult MSWindowsHook::install()
{
assert(g_getMessage == NULL || g_screenSaver);
// must be initialized
if (g_threadID == 0) {
return kHOOK_FAILED;
}
// discard old dead keys
g_deadVirtKey = 0;
g_deadLParam = 0;
// reset fake input flag
g_fakeServerInput = false;
// install low-level hooks. we require that they both get installed.
g_mouseLL = SetWindowsHookEx(WH_MOUSE_LL, &mouseLLHook, NULL, 0);
#if !NO_GRAB_KEYBOARD
g_keyboardLL = SetWindowsHookEx(WH_KEYBOARD_LL, &keyboardLLHook, NULL, 0);
if (g_mouseLL == NULL || g_keyboardLL == NULL) {
if (g_keyboardLL != NULL) {
UnhookWindowsHookEx(g_keyboardLL);
g_keyboardLL = NULL;
}
if (g_mouseLL != NULL) {
UnhookWindowsHookEx(g_mouseLL);
g_mouseLL = NULL;
}
}
#endif
// check that we got all the hooks we wanted
if ((g_mouseLL == NULL) ||
#if !NO_GRAB_KEYBOARD
(g_keyboardLL == NULL)
#endif
) {
uninstall();
return kHOOK_FAILED;
}
if (g_keyboardLL != NULL || g_mouseLL != NULL) {
g_hookThread = GetCurrentThreadId();
return kHOOK_OKAY_LL;
}
return kHOOK_OKAY;
}
int MSWindowsHook::uninstall()
{
// discard old dead keys
g_deadVirtKey = 0;
g_deadLParam = 0;
// uninstall hooks
if (g_keyboardLL != NULL) {
UnhookWindowsHookEx(g_keyboardLL);
g_keyboardLL = NULL;
}
if (g_mouseLL != NULL) {
UnhookWindowsHookEx(g_mouseLL);
g_mouseLL = NULL;
}
if (g_getMessage != NULL && !g_screenSaver) {
UnhookWindowsHookEx(g_getMessage);
g_getMessage = NULL;
}
return 1;
}
static LRESULT CALLBACK getMessageHook(int code, WPARAM wParam, LPARAM lParam)
{
if (code >= 0) {
if (g_screenSaver) {
MSG *msg = reinterpret_cast<MSG *>(lParam);
if (msg->message == WM_SYSCOMMAND && msg->wParam == SC_SCREENSAVE) {
// broadcast screen saver started message
PostThreadMessage(g_threadID, DESKFLOW_MSG_SCREEN_SAVER, TRUE, 0);
}
}
}
return CallNextHookEx(g_getMessage, code, wParam, lParam);
}
int MSWindowsHook::installScreenSaver()
{
// must be initialized
if (g_threadID == 0) {
return 0;
}
// generate screen saver messages
g_screenSaver = true;
// install hook unless it's already installed
if (g_getMessage == NULL) {
g_getMessage = SetWindowsHookEx(WH_GETMESSAGE, &getMessageHook, NULL, 0);
}
return (g_getMessage != NULL) ? 1 : 0;
}
int MSWindowsHook::uninstallScreenSaver()
{
// uninstall hook unless the mouse wheel hook is installed
if (g_getMessage != NULL) {
UnhookWindowsHookEx(g_getMessage);
g_getMessage = NULL;
}
// screen saver hook is no longer installed
g_screenSaver = false;
return 1;
}
| 21,474
|
C++
|
.cpp
| 624
| 30.325321
| 120
| 0.670778
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,583
|
OSXEventQueueBuffer.cpp
|
deskflow_deskflow/src/lib/platform/OSXEventQueueBuffer.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2004 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/OSXEventQueueBuffer.h"
#include "base/Event.h"
#include "base/IEventQueue.h"
//
// EventQueueTimer
//
class EventQueueTimer
{
};
//
// OSXEventQueueBuffer
//
OSXEventQueueBuffer::OSXEventQueueBuffer(IEventQueue *events)
: m_event(NULL),
m_eventQueue(events),
m_carbonEventQueue(NULL)
{
// do nothing
}
OSXEventQueueBuffer::~OSXEventQueueBuffer()
{
// release the last event
if (m_event != NULL) {
ReleaseEvent(m_event);
}
}
void OSXEventQueueBuffer::init()
{
m_carbonEventQueue = GetCurrentEventQueue();
}
void OSXEventQueueBuffer::waitForEvent(double timeout)
{
EventRef event;
ReceiveNextEvent(0, NULL, timeout, false, &event);
}
IEventQueueBuffer::Type OSXEventQueueBuffer::getEvent(Event &event, UInt32 &dataID)
{
// release the previous event
if (m_event != NULL) {
ReleaseEvent(m_event);
m_event = NULL;
}
// get the next event
OSStatus error = ReceiveNextEvent(0, NULL, 0.0, true, &m_event);
// handle the event
if (error == eventLoopQuitErr) {
event = Event(Event::kQuit);
return kSystem;
} else if (error != noErr) {
return kNone;
} else {
UInt32 eventClass = GetEventClass(m_event);
switch (eventClass) {
case 'Syne':
dataID = GetEventKind(m_event);
return kUser;
default:
event = Event(Event::kSystem, m_eventQueue->getSystemTarget(), &m_event);
return kSystem;
}
}
}
bool OSXEventQueueBuffer::addEvent(UInt32 dataID)
{
EventRef event;
OSStatus error = CreateEvent(kCFAllocatorDefault, 'Syne', dataID, 0, kEventAttributeNone, &event);
if (error == noErr) {
assert(m_carbonEventQueue != NULL);
error = PostEventToQueue(m_carbonEventQueue, event, kEventPriorityStandard);
ReleaseEvent(event);
}
return (error == noErr);
}
bool OSXEventQueueBuffer::isEmpty() const
{
EventRef event;
OSStatus status = ReceiveNextEvent(0, NULL, 0.0, false, &event);
return (status == eventLoopTimedOutErr);
}
EventQueueTimer *OSXEventQueueBuffer::newTimer(double, bool) const
{
return new EventQueueTimer;
}
void OSXEventQueueBuffer::deleteTimer(EventQueueTimer *timer) const
{
delete timer;
}
| 2,905
|
C++
|
.cpp
| 104
| 25.125
| 100
| 0.735876
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,584
|
EiScreen.cpp
|
deskflow_deskflow/src/lib/platform/EiScreen.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2022 Red Hat, Inc.
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/EiScreen.h"
#include "arch/Arch.h"
#include "arch/XArch.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/Stopwatch.h"
#include "base/TMethodEventJob.h"
#include "common/constants.h"
#include "deskflow/Clipboard.h"
#include "deskflow/KeyMap.h"
#include "deskflow/XScreen.h"
#include "platform/EiEventQueueBuffer.h"
#include "platform/EiKeyState.h"
#include "platform/PortalInputCapture.h"
#include "platform/PortalRemoteDesktop.h"
#include <algorithm>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <vector>
struct ScrollRemainder
{
double x, y; // scroll remainder in pixels
};
namespace deskflow {
EiScreen::EiScreen(bool is_primary, IEventQueue *events, bool use_portal)
: PlatformScreen(events),
is_primary_(is_primary),
events_(events),
w_(1),
h_(1),
is_on_screen_(is_primary)
{
init_ei();
key_state_ = new EiKeyState(this, events);
// install event handlers
events_->adoptHandler(
Event::kSystem, events_->getSystemTarget(), new TMethodEventJob<EiScreen>(this, &EiScreen::handleSystemEvent)
);
if (use_portal) {
events_->adoptHandler(
events_->forEi().connected(), getEventTarget(),
new TMethodEventJob<EiScreen>(this, &EiScreen::handle_connected_to_eis_event)
);
if (is_primary) {
portal_input_capture_ = new PortalInputCapture(this, events_);
} else {
events_->adoptHandler(
events_->forEi().sessionClosed(), getEventTarget(),
new TMethodEventJob<EiScreen>(this, &EiScreen::handle_portal_session_closed)
);
portal_remote_desktop_ = new PortalRemoteDesktop(this, events_);
}
} else {
// Note: socket backend does not support reconnections
auto rc = ei_setup_backend_socket(ei_, nullptr);
if (rc != 0) {
LOG_ERR("ei init error: %s", strerror(-rc));
throw std::runtime_error("failed to init ei context");
}
}
}
EiScreen::~EiScreen()
{
events_->adoptBuffer(nullptr);
events_->removeHandler(Event::kSystem, events_->getSystemTarget());
cleanup_ei();
delete key_state_;
delete portal_remote_desktop_;
delete portal_input_capture_;
}
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);
break;
case EI_LOG_PRIORITY_INFO:
LOG_INFO("ei: %s", message);
break;
case EI_LOG_PRIORITY_WARNING:
LOG_WARN("ei: %s", message);
break;
case EI_LOG_PRIORITY_ERROR:
LOG_ERR("ei: %s", message);
break;
default:
LOG_PRINT("ei: %s", message);
break;
}
}
void EiScreen::init_ei()
{
if (is_primary_) {
ei_ = ei_new_receiver(nullptr); // we receive from the display server
} else {
ei_ = ei_new_sender(nullptr); // we send to the display server
}
ei_set_user_data(ei_, this);
ei_log_set_priority(ei_, EI_LOG_PRIORITY_DEBUG);
ei_log_set_handler(ei_, cb_handle_ei_log_event);
std::string configName = kAppId;
ei_configure_name(ei_, configName.append(" client").c_str());
// install the platform event queue
events_->adoptBuffer(nullptr);
events_->adoptBuffer(new EiEventQueueBuffer(this, ei_, events_));
}
void EiScreen::cleanup_ei()
{
if (ei_pointer_) {
free(ei_device_get_user_data(ei_pointer_));
ei_device_set_user_data(ei_pointer_, nullptr);
ei_pointer_ = ei_device_unref(ei_pointer_);
}
if (ei_keyboard_) {
free(ei_device_get_user_data(ei_keyboard_));
ei_device_set_user_data(ei_keyboard_, nullptr);
ei_keyboard_ = ei_device_unref(ei_keyboard_);
}
if (ei_abs_) {
free(ei_device_get_user_data(ei_abs_));
ei_device_set_user_data(ei_abs_, nullptr);
ei_abs_ = ei_device_unref(ei_abs_);
}
ei_seat_unref(ei_seat_);
for (auto it = ei_devices_.begin(); it != ei_devices_.end(); it++) {
free(ei_device_get_user_data(*it));
ei_device_set_user_data(*it, nullptr);
ei_device_unref(*it);
}
ei_devices_.clear();
ei_ = ei_unref(ei_);
}
void *EiScreen::getEventTarget() const
{
return const_cast<void *>(static_cast<const void *>(this));
}
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
{
x = x_;
y = y_;
w = w_;
h = h_;
}
void EiScreen::getCursorPos(int32_t &x, int32_t &y) const
{
x = cursor_x_;
y = cursor_y_;
}
void EiScreen::reconfigure(uint32_t)
{
// do nothing
}
void EiScreen::warpCursor(int32_t x, int32_t y)
{
cursor_x_ = x;
cursor_y_ = y;
}
std::uint32_t EiScreen::registerHotKey(KeyID key, KeyModifierMask mask)
{
static std::uint32_t next_id;
std::uint32_t id = std::min(++next_id, 1u);
// Bug: id rollover means duplicate hotkey ids. Oh well.
auto set = hotkeys_.find(key);
if (set == hotkeys_.end()) {
hotkeys_.emplace(key, HotKeySet{key});
set = hotkeys_.find(key);
}
set->second.add_item(HotKeyItem(mask, id));
return id;
}
void EiScreen::unregisterHotKey(uint32_t id)
{
for (auto &set : hotkeys_) {
if (set.second.remove_by_id(id)) {
break;
}
}
}
void EiScreen::fakeInputBegin()
{
// FIXME -- not implemented
}
void EiScreen::fakeInputEnd()
{
// FIXME -- not implemented
}
std::int32_t EiScreen::getJumpZoneSize() const
{
return 1;
}
bool EiScreen::isAnyMouseButtonDown(uint32_t &buttonID) const
{
return false;
}
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)
{
uint32_t code;
if (!ei_pointer_)
return;
switch (button) {
case kButtonLeft:
code = 0x110; // BTN_LEFT
break;
case kButtonMiddle:
code = 0x112; // BTN_MIDDLE
break;
case kButtonRight:
code = 0x111; // BTN_RIGHT
break;
default:
code = 0x110 + (button - 1);
break;
}
ei_device_button_button(ei_pointer_, code, press);
ei_device_frame(ei_pointer_, ei_now(ei_));
}
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;
cursor_y_ = y;
return;
}
if (!ei_abs_)
return;
ei_device_pointer_motion_absolute(ei_abs_, x, y);
ei_device_frame(ei_abs_, ei_now(ei_));
}
void EiScreen::fakeMouseRelativeMove(int32_t dx, int32_t dy) const
{
if (!ei_pointer_)
return;
ei_device_pointer_motion(ei_pointer_, dx, dy);
ei_device_frame(ei_pointer_, ei_now(ei_));
}
void EiScreen::fakeMouseWheel(int32_t xDelta, int32_t yDelta) const
{
if (!ei_pointer_)
return;
// libei and deskflow seem to use opposite directions, so we have
// to send EI the opposite of the value received if we want to remain
// compatible with other platforms (including X11).
ei_device_scroll_discrete(ei_pointer_, -xDelta, -yDelta);
ei_device_frame(ei_pointer_, ei_now(ei_));
}
void EiScreen::fakeKey(uint32_t keycode, bool is_down) const
{
if (!ei_keyboard_)
return;
auto xkb_keycode = keycode + 8;
key_state_->update_xkb_state(xkb_keycode, is_down);
ei_device_keyboard_key(ei_keyboard_, keycode, is_down);
ei_device_frame(ei_keyboard_, ei_now(ei_));
}
void EiScreen::enable()
{
// Nothing really to be done here
}
void EiScreen::disable()
{
// Nothing really to be done here, maybe cleanup in the future but ideally
// that's handled elsewhere
}
void EiScreen::enter()
{
is_on_screen_ = true;
if (!is_primary_) {
++sequence_number_;
if (ei_pointer_) {
ei_device_start_emulating(ei_pointer_, sequence_number_);
}
if (ei_keyboard_) {
ei_device_start_emulating(ei_keyboard_, sequence_number_);
}
if (ei_abs_) {
ei_device_start_emulating(ei_abs_, sequence_number_);
fakeMouseMove(cursor_x_, cursor_y_);
}
} else {
LOG_DEBUG("releasing input capture at x=%i y=%i", cursor_x_, cursor_y_);
portal_input_capture_->release(cursor_x_, cursor_y_);
}
}
bool EiScreen::canLeave()
{
return true;
}
void EiScreen::leave()
{
if (!is_primary_) {
if (ei_pointer_) {
ei_device_stop_emulating(ei_pointer_);
}
if (ei_keyboard_) {
ei_device_stop_emulating(ei_keyboard_);
}
if (ei_abs_) {
ei_device_stop_emulating(ei_abs_);
}
}
is_on_screen_ = false;
}
bool EiScreen::setClipboard(ClipboardID id, const IClipboard *clipboard)
{
return false;
}
void EiScreen::checkClipboards()
{
// do nothing, we're always up to date
}
void EiScreen::openScreensaver(bool notify)
{
// FIXME
}
void EiScreen::closeScreensaver()
{
// FIXME
}
void EiScreen::screensaver(bool activate)
{
// FIXME
}
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)
{
// We don't have ei-specific options, nothing to do here
}
void EiScreen::setSequenceNumber(uint32_t seqNum)
{
// FIXME: what is this used for?
}
bool EiScreen::isPrimary() const
{
return is_primary_;
}
void EiScreen::update_shape()
{
for (auto it = ei_devices_.begin(); it != ei_devices_.end(); it++) {
auto idx = 0;
struct ei_region *r;
while ((r = ei_device_get_region(*it, idx++)) != nullptr) {
x_ = std::min(ei_region_get_x(r), x_);
y_ = std::min(ei_region_get_y(r), y_);
w_ = std::max(ei_region_get_x(r) + ei_region_get_width(r), w_);
h_ = std::max(ei_region_get_y(r) + ei_region_get_height(r), h_);
}
}
LOG_NOTE("logical output size: %dx%d@%d.%d", w_, h_, x_, y_);
cursor_x_ = x_ + w_ / 2;
cursor_y_ = y_ + h_ / 2;
sendEvent(events_->forIScreen().shapeChanged(), nullptr);
}
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
// capabilities, so there may be more than one logical pointer (or even
// multiple seats). Supporting this is ... tricky so for now we go the easy
// route: one device for each capability. Note this may be the same device
// if the first device comes with multiple capabilities.
if (!ei_pointer_ && ei_device_has_capability(device, EI_DEVICE_CAP_POINTER) &&
ei_device_has_capability(device, EI_DEVICE_CAP_BUTTON) &&
ei_device_has_capability(device, EI_DEVICE_CAP_SCROLL)) {
ei_pointer_ = ei_device_ref(device);
}
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);
if (keymap && ei_keymap_get_type(keymap) == EI_KEYMAP_TYPE_XKB) {
int fd = ei_keymap_get_fd(keymap);
size_t len = ei_keymap_get_size(keymap);
key_state_->init(fd, len);
} else {
// We rely on the EIS implementation to give us a keymap, otherwise we
// really have no idea what a keycode means (other than it's linux/input.h
// 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));
key_state_->init_default_keymap();
}
key_state_->updateKeyMap();
}
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);
}
ei_devices_.emplace_back(ei_device_ref(device));
update_shape();
}
void EiScreen::remove_device(struct ei_device *device)
{
LOG_DEBUG("removing device %s", ei_device_get_name(device));
if (device == ei_pointer_)
ei_pointer_ = ei_device_unref(ei_pointer_);
if (device == ei_keyboard_)
ei_keyboard_ = ei_device_unref(ei_keyboard_);
if (device == ei_abs_)
ei_abs_ = ei_device_unref(ei_abs_);
for (auto it = ei_devices_.begin(); it != ei_devices_.end(); it++) {
if (*it == device) {
ei_devices_.erase(it);
ei_device_unref(device);
break;
}
}
update_shape();
}
void EiScreen::sendEvent(Event::Type type, void *data)
{
events_->addEvent(Event(type, getEventTarget(), data));
}
ButtonID EiScreen::map_button_from_evdev(ei_event *event) const
{
uint32_t button = ei_event_button_get_button(event);
switch (button) {
case 0x110:
return kButtonLeft;
case 0x111:
return kButtonRight;
case 0x112:
return kButtonMiddle;
case 0x113:
return kButtonExtra0;
case 0x114:
return kButtonExtra1;
default:
return kButtonNone;
}
return kButtonNone;
}
bool EiScreen::on_hotkey(KeyID keyid, bool is_pressed, KeyModifierMask mask)
{
auto it = hotkeys_.find(keyid);
if (it == hotkeys_.end()) {
return false;
}
// Note: our mask (see on_key_event) only contains some modifiers
// but we don't put a limitation on modifiers in the hotkeys. So some
// 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();
sendEvent(type, HotKeyInfo::alloc(id));
return true;
}
return false;
}
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);
KeyID keyid = key_state_->map_key_from_keyval(keyval);
KeyButton keybutton = static_cast<KeyButton>(keyval);
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);
if (is_primary_ && on_hotkey(keyid, pressed, mask)) {
return;
}
if (keyid != kKeyNone) {
key_state_->sendKeyEvent(getEventTarget(), pressed, false, keyid, mask, 1, keybutton);
}
}
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);
if (button == kButtonNone) {
LOG_DEBUG("event: button not recognized");
return;
}
auto eventType = pressed ? events_->forIPrimaryScreen().buttonDown() : events_->forIPrimaryScreen().buttonUp();
sendEvent(eventType, ButtonInfo::alloc(button, mask));
}
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;
// Our logical wheel clicks are multiples 120, so we
// convert between the two and keep the remainders because
// we will very likely get subpixel scroll events.
// This means a single pixel is 120/PIXEL_TO_WHEEL_RATIO in wheel values.
const int PIXEL_TO_WHEEL_RATIO = 120 / PIXELS_PER_WHEEL_CLICK;
assert(is_primary_);
double dx = ei_event_scroll_get_dx(event);
double dy = ei_event_scroll_get_dy(event);
struct ei_device *device = ei_event_get_device(event);
LOG_DEBUG1("event: scroll (%.2f, %.2f)", dx, dy);
struct ScrollRemainder *remainder = static_cast<struct ScrollRemainder *>(ei_device_get_user_data(device));
if (!remainder) {
remainder = new ScrollRemainder();
ei_device_set_user_data(device, remainder);
}
dx += remainder->x;
dy += remainder->y;
double x, y;
double rx = modf(dx, &x);
double ry = modf(dy, &y);
assert(!std::isnan(x) && !std::isinf(x));
assert(!std::isnan(y) && !std::isinf(y));
// libei and deskflow seem to use opposite directions, so we have
// to send the opposite of the value reported by EI if we want to
// remain compatible with other platforms (including X11).
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)
);
remainder->x = rx;
remainder->y = ry;
}
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.
assert(is_primary_);
std::int32_t dx = ei_event_scroll_get_discrete_dx(event);
std::int32_t dy = ei_event_scroll_get_discrete_dy(event);
LOG_DEBUG1("event: scroll discrete (%d, %d)", dx, dy);
// libei and deskflow seem to use opposite directions, so we have
// to send the opposite of the value reported by EI if we want to
// remain compatible with other platforms (including X11).
sendEvent(events_->forIPrimaryScreen().wheel(), WheelInfo::alloc(-dx, -dy));
}
void EiScreen::on_motion_event(ei_event *event)
{
assert(is_primary_);
double dx = ei_event_pointer_get_dx(event);
double dy = ei_event_pointer_get_dy(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_));
if (portal_input_capture_->is_active()) {
portal_input_capture_->release();
}
} else {
buffer_dx += dx;
buffer_dy += dy;
auto pixel_dx = static_cast<std::int32_t>(buffer_dx);
auto pixel_dy = static_cast<std::int32_t>(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));
buffer_dx -= pixel_dx;
buffer_dy -= pixel_dy;
}
}
}
void EiScreen::on_abs_motion_event(ei_event *event)
{
assert(is_primary_);
}
void EiScreen::handle_connected_to_eis_event(const Event &event, void *)
{
int fd = static_cast<EiConnectInfo *>(event.getData())->m_fd;
LOG_DEBUG("eis connection established, fd=%d", fd);
auto rc = ei_setup_backend_fd(ei_, fd);
if (rc != 0) {
LOG_NOTE("failed to set up ei: %s", strerror(-rc));
}
}
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 *)
{
std::lock_guard<std::mutex> lock(mutex_);
bool disconnected = false;
// Only one ei_dispatch per system event, see the comment in
// EiEventQueueBuffer::addEvent
ei_dispatch(ei_);
struct ei_event *event;
while ((event = ei_get_event(ei_)) != nullptr) {
auto type = ei_event_get_type(event);
auto seat = ei_event_get_seat(event);
auto device = ei_event_get_device(event);
switch (type) {
case EI_EVENT_CONNECT:
LOG_DEBUG("connected to eis");
break;
case EI_EVENT_SEAT_ADDED:
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
);
LOG_DEBUG("ei: using seat %s", ei_seat_get_name(ei_seat_));
// we don't care about touch
}
break;
case EI_EVENT_DEVICE_ADDED:
if (seat == ei_seat_) {
add_device(device);
} else {
LOG_INFO("seat %s is ignored", ei_seat_get_name(ei_seat_));
}
break;
case EI_EVENT_DEVICE_REMOVED:
remove_device(device);
break;
case EI_EVENT_SEAT_REMOVED:
if (seat == ei_seat_) {
ei_seat_ = ei_seat_unref(ei_seat_);
}
break;
case EI_EVENT_DISCONNECT:
// We're using libei which emulates the various seat/device remove events
// so by the time we get here our EiScreen should be in a neutral state.
//
// We don't do anything here, we let the portal's Session.Closed signal
// handle the rest.
LOG_WARN("disconnected from eis");
disconnected = true;
break;
case EI_EVENT_DEVICE_PAUSED:
LOG_DEBUG("device %s is paused", ei_device_get_name(device));
break;
case EI_EVENT_DEVICE_RESUMED:
LOG_DEBUG("device %s is resumed", ei_device_get_name(device));
if (!is_primary_ && is_on_screen_) {
ei_device_start_emulating(device, ++sequence_number_);
}
break;
case EI_EVENT_KEYBOARD_MODIFIERS:
// FIXME
break;
// events below are for a receiver context (barriers)
case EI_EVENT_FRAME:
break;
case EI_EVENT_DEVICE_START_EMULATING:
LOG_DEBUG("device %s started emulating", ei_device_get_name(device));
break;
case EI_EVENT_DEVICE_STOP_EMULATING:
LOG_DEBUG("device %s stopped emulating", ei_device_get_name(device));
break;
case EI_EVENT_KEYBOARD_KEY:
on_key_event(event);
break;
case EI_EVENT_BUTTON_BUTTON:
on_button_event(event);
break;
case EI_EVENT_POINTER_MOTION:
on_motion_event(event);
break;
case EI_EVENT_POINTER_MOTION_ABSOLUTE:
on_abs_motion_event(event);
break;
case EI_EVENT_TOUCH_UP:
break;
case EI_EVENT_TOUCH_MOTION:
break;
case EI_EVENT_TOUCH_DOWN:
break;
case EI_EVENT_SCROLL_DELTA:
on_pointer_scroll_event(event);
break;
case EI_EVENT_SCROLL_DISCRETE:
on_pointer_scroll_discrete_event(event);
break;
case EI_EVENT_SCROLL_STOP:
case EI_EVENT_SCROLL_CANCEL:
break;
}
ei_event_unref(event);
}
if (disconnected)
ei_ = ei_unref(ei_);
}
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_;
}
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::HotKeySet::HotKeySet(KeyID key) : id_(key)
{
}
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);
return true;
}
}
return false;
}
void EiScreen::HotKeySet::add_item(HotKeyItem item)
{
set_.push_back(item);
}
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_;
}
}
return 0;
}
} // namespace deskflow
| 23,736
|
C++
|
.cpp
| 757
| 27.675033
| 120
| 0.676033
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,585
|
XWindowsScreen.cpp
|
deskflow_deskflow/src/lib/platform/XWindowsScreen.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/XWindowsScreen.h"
#include "arch/Arch.h"
#include "arch/XArch.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/Stopwatch.h"
#include "base/String.h"
#include "base/TMethodEventJob.h"
#include "deskflow/App.h"
#include "deskflow/ArgsBase.h"
#include "deskflow/ClientApp.h"
#include "deskflow/ClientArgs.h"
#include "deskflow/Clipboard.h"
#include "deskflow/KeyMap.h"
#include "deskflow/XScreen.h"
#include "platform/XWindowsClipboard.h"
#include "platform/XWindowsEventQueueBuffer.h"
#include "platform/XWindowsKeyState.h"
#include "platform/XWindowsScreenSaver.h"
#include "platform/XWindowsUtil.h"
#include <algorithm>
#include <cstdlib>
#include <cstring>
#if X_DISPLAY_MISSING
#error X11 is required to build deskflow
#else
#include <X11/X.h>
#include <X11/Xutil.h>
#define XK_MISCELLANY
#define XK_XKB_KEYS
#include <X11/keysymdef.h>
#if HAVE_X11_EXTENSIONS_DPMS_H
extern "C"
{
#include <X11/extensions/dpms.h>
}
#endif
#if HAVE_X11_EXTENSIONS_XTEST_H
#include <X11/extensions/XTest.h>
#else
#error The XTest extension is required to build deskflow
#endif
#if HAVE_X11_EXTENSIONS_XINERAMA_H
// Xinerama.h may lack extern "C" for inclusion by C++
extern "C"
{
#include <X11/extensions/Xinerama.h>
}
#endif
#if HAVE_X11_EXTENSIONS_XRANDR_H
#include <X11/extensions/Xrandr.h>
#endif
#if HAVE_XKB_EXTENSION
#include <X11/XKBlib.h>
#endif
#ifdef HAVE_XI2
#include <X11/extensions/XInput2.h>
#endif
#endif
static int xi_opcode;
//
// XWindowsScreen
//
// NOTE -- the X display is shared among several objects but is owned
// by the XWindowsScreen. Xlib is not reentrant so we must ensure
// that no two objects can simultaneously call Xlib with the display.
// this is easy since we only make X11 calls from the main thread.
// we must also ensure that these objects do not use the display in
// their destructors or, if they do, we can tell them not to. This
// is to handle unexpected disconnection of the X display, when any
// call on the display is invalid. In that situation we discard the
// display and the X11 event queue buffer, ignore any calls that try
// to use the display, and wait to be destroyed.
XWindowsScreen *XWindowsScreen::s_screen = NULL;
XWindowsScreen::XWindowsScreen(
const char *displayName, bool isPrimary, bool disableXInitThreads, int mouseScrollDelta, IEventQueue *events,
deskflow::ClientScrollDirection scrollDirection
)
: PlatformScreen(events, scrollDirection),
m_isPrimary(isPrimary),
m_mouseScrollDelta(mouseScrollDelta),
m_display(NULL),
m_root(None),
m_window(None),
m_isOnScreen(m_isPrimary),
m_x(0),
m_y(0),
m_w(0),
m_h(0),
m_xCenter(0),
m_yCenter(0),
m_xCursor(0),
m_yCursor(0),
m_keyState(NULL),
m_lastFocus(None),
m_lastFocusRevert(RevertToNone),
m_im(NULL),
m_ic(NULL),
m_lastKeycode(0),
m_sequenceNumber(0),
m_screensaver(NULL),
m_screensaverNotify(false),
m_xtestIsXineramaUnaware(true),
m_preserveFocus(false),
m_xkb(false),
m_xi2detected(false),
m_xrandr(false),
m_events(events)
{
assert(s_screen == NULL);
if (mouseScrollDelta == 0)
m_mouseScrollDelta = 120;
s_screen = this;
if (!disableXInitThreads) {
// initializes Xlib support for concurrent threads.
if (XInitThreads() == 0)
throw XArch("XInitThreads() returned zero");
} else {
LOG((CLOG_DEBUG "skipping XInitThreads()"));
}
// set the X I/O error handler so we catch the display disconnecting
XSetIOErrorHandler(&XWindowsScreen::ioErrorHandler);
try {
m_display = openDisplay(displayName);
m_root = DefaultRootWindow(m_display);
saveShape();
m_window = openWindow();
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 "window is 0x%08x", m_window));
} catch (...) {
if (m_display != NULL) {
XCloseDisplay(m_display);
}
throw;
}
// primary/secondary screen only initialization
if (m_isPrimary) {
#ifdef HAVE_XI2
m_xi2detected = detectXI2();
if (m_xi2detected) {
selectXIRawMotion();
} else
#endif
{
// start watching for events on other windows
selectEvents(m_root);
}
// prepare to use input methods
openIM();
} else {
// become impervious to server grabs
XTestGrabControl(m_display, True);
}
// disable sleep if the flag is set
if (App::instance().argsBase().m_preventSleep) {
m_powerManager.disableSleep();
}
// initialize the clipboards
for (ClipboardID id = 0; id < kClipboardEnd; ++id) {
m_clipboard[id] = new XWindowsClipboard(m_display, m_window, id);
}
// install event handlers
m_events->adoptHandler(
Event::kSystem, m_events->getSystemTarget(),
new TMethodEventJob<XWindowsScreen>(this, &XWindowsScreen::handleSystemEvent)
);
// install the platform event queue
m_events->adoptBuffer(new XWindowsEventQueueBuffer(m_display, m_window, m_events));
}
XWindowsScreen::~XWindowsScreen()
{
assert(s_screen != NULL);
assert(m_display != NULL);
m_events->adoptBuffer(NULL);
m_events->removeHandler(Event::kSystem, m_events->getSystemTarget());
for (ClipboardID id = 0; id < kClipboardEnd; ++id) {
delete m_clipboard[id];
}
delete m_keyState;
delete m_screensaver;
m_keyState = NULL;
m_screensaver = NULL;
if (m_display != NULL) {
// FIXME -- is it safe to clean up the IC and IM without a display?
if (m_ic != NULL) {
XDestroyIC(m_ic);
}
if (m_im != NULL) {
XCloseIM(m_im);
}
XDestroyWindow(m_display, m_window);
XCloseDisplay(m_display);
}
XSetIOErrorHandler(NULL);
s_screen = NULL;
}
void XWindowsScreen::enable()
{
if (!m_isPrimary) {
// get the keyboard control state
XKeyboardState keyControl;
XGetKeyboardControl(m_display, &keyControl);
m_autoRepeat = (keyControl.global_auto_repeat == AutoRepeatModeOn);
m_keyState->setAutoRepeat(keyControl);
// move hider window under the cursor center
XMoveWindow(m_display, m_window, m_xCenter, m_yCenter);
// raise and show the window
// FIXME -- take focus?
XMapRaised(m_display, m_window);
// warp the mouse to the cursor center
fakeMouseMove(m_xCenter, m_yCenter);
}
}
void XWindowsScreen::disable()
{
// release input context focus
if (m_ic != NULL) {
XUnsetICFocus(m_ic);
}
// unmap the hider/grab window. this also ungrabs the mouse and
// keyboard if they're grabbed.
XUnmapWindow(m_display, m_window);
// restore auto-repeat state
if (!m_isPrimary && m_autoRepeat) {
// XAutoRepeatOn(m_display);
}
}
void XWindowsScreen::enter()
{
screensaver(false);
// release input context focus
if (m_ic != NULL) {
XUnsetICFocus(m_ic);
}
// set the input focus to what it had been when we took it
if (m_lastFocus != None) {
// the window may not exist anymore so ignore errors
XWindowsUtil::ErrorLock lock(m_display);
XSetInputFocus(m_display, m_lastFocus, m_lastFocusRevert, CurrentTime);
}
#if HAVE_X11_EXTENSIONS_DPMS_H
// Force the DPMS to turn screen back on since we don't
// actually cause physical hardware input to trigger it
int dummy;
CARD16 powerlevel;
BOOL enabled;
if (DPMSQueryExtension(m_display, &dummy, &dummy) && DPMSCapable(m_display) &&
DPMSInfo(m_display, &powerlevel, &enabled)) {
if (enabled && powerlevel != DPMSModeOn)
DPMSForceLevel(m_display, DPMSModeOn);
}
#endif
// unmap the hider/grab window. this also ungrabs the mouse and
// keyboard if they're grabbed.
XUnmapWindow(m_display, m_window);
/* maybe call this if entering for the screensaver
// set keyboard focus to root window. the screensaver should then
// pick up key events for when the user enters a password to unlock.
XSetInputFocus(m_display, PointerRoot, PointerRoot, CurrentTime);
*/
if (!m_isPrimary) {
// get the keyboard control state
XKeyboardState keyControl;
XGetKeyboardControl(m_display, &keyControl);
m_autoRepeat = (keyControl.global_auto_repeat == AutoRepeatModeOn);
m_keyState->setAutoRepeat(keyControl);
// turn off auto-repeat. we do this so fake key press events don't
// cause the local server to generate their own auto-repeats of
// those keys.
// XAutoRepeatOff(m_display);
}
// now on screen
m_isOnScreen = true;
}
bool XWindowsScreen::canLeave()
{
// raise and show the window, required to grab mouse and keyboard
XMapRaised(m_display, m_window);
// see if grabbing the mouse and keyboard, if primary, is possible
return !(m_isPrimary && !grabMouseAndKeyboard());
}
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
// that state is lost. that's because we can't get notified by
// the X server when the auto-repeat configuration is changed so
// we can't track the desired configuration.
if (m_autoRepeat) {
// XAutoRepeatOn(m_display);
}
// move hider window under the cursor center
XMoveWindow(m_display, m_window, m_xCenter, m_yCenter);
}
// raise and show the window
XMapRaised(m_display, m_window);
// grab the mouse and keyboard, if primary and possible
if (m_isPrimary && !grabMouseAndKeyboard()) {
XUnmapWindow(m_display, m_window);
}
// save current focus
XGetInputFocus(m_display, &m_lastFocus, &m_lastFocusRevert);
// take focus
if (m_isPrimary || !m_preserveFocus) {
XSetInputFocus(m_display, m_window, RevertToPointerRoot, CurrentTime);
}
// now warp the mouse. we warp after showing the window so we're
// guaranteed to get the mouse leave event and to prevent the
// keyboard focus from changing under point-to-focus policies.
if (m_isPrimary) {
warpCursor(m_xCenter, m_yCenter);
} else {
fakeMouseMove(m_xCenter, m_yCenter);
}
// set input context focus to our window
if (m_ic != NULL) {
XmbResetIC(m_ic);
XSetICFocus(m_ic);
m_filtered.clear();
}
// now off screen
m_isOnScreen = false;
}
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());
if (clipboard != NULL) {
// save clipboard data
return Clipboard::copy(m_clipboard[id], clipboard, timestamp);
} else {
// assert clipboard ownership
if (!m_clipboard[id]->open(timestamp)) {
return false;
}
m_clipboard[id]->empty();
m_clipboard[id]->close();
return true;
}
}
void XWindowsScreen::checkClipboards()
{
// do nothing, we're always up to date
}
void XWindowsScreen::openScreensaver(bool notify)
{
m_screensaverNotify = notify;
if (!m_screensaverNotify) {
m_screensaver->disable();
}
}
void XWindowsScreen::closeScreensaver()
{
if (!m_screensaverNotify) {
m_screensaver->enable();
}
}
void XWindowsScreen::screensaver(bool activate)
{
if (activate) {
m_screensaver->activate();
} else {
m_screensaver->deactivate();
}
}
void XWindowsScreen::resetOptions()
{
m_xtestIsXineramaUnaware = true;
m_preserveFocus = false;
}
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"));
} else if (options[i] == kOptionScreenPreserveFocus) {
m_preserveFocus = (options[i + 1] != 0);
LOG((CLOG_DEBUG1 "preserve focus: %s", m_preserveFocus ? "true" : "false"));
}
}
}
void XWindowsScreen::setSequenceNumber(UInt32 seqNum)
{
m_sequenceNumber = seqNum;
}
bool XWindowsScreen::isPrimary() const
{
return m_isPrimary;
}
String XWindowsScreen::getSecureInputApp() const
{
// ignore on Linux
return "";
}
void *XWindowsScreen::getEventTarget() const
{
return const_cast<XWindowsScreen *>(this);
}
bool XWindowsScreen::getClipboard(ClipboardID id, IClipboard *clipboard) const
{
assert(clipboard != NULL);
// 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());
// copy the clipboard
return Clipboard::copy(clipboard, m_clipboard[id], timestamp);
}
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
{
Window root, window;
int mx, my, xWindow, yWindow;
unsigned int mask;
if (XQueryPointer(m_display, m_root, &root, &window, &mx, &my, &xWindow, &yWindow, &mask)) {
x = mx;
y = my;
} else {
x = m_xCenter;
y = m_yCenter;
}
}
void XWindowsScreen::reconfigure(UInt32)
{
// do nothing
}
void XWindowsScreen::warpCursor(SInt32 x, SInt32 y)
{
// warp mouse
warpCursorNoFlush(x, y);
// remove all input events before and including warp
XEvent event;
while (XCheckMaskEvent(
m_display,
PointerMotionMask | ButtonPressMask | ButtonReleaseMask | KeyPressMask | KeyReleaseMask | KeymapStateMask, &event
)) {
// do nothing
}
// save position as last position
m_xCursor = x;
m_yCursor = y;
}
UInt32 XWindowsScreen::registerHotKey(KeyID key, KeyModifierMask mask)
{
// only allow certain modifiers
if ((mask & ~(KeyModifierShift | KeyModifierControl | KeyModifierAlt | KeyModifierSuper)) != 0) {
LOG((CLOG_DEBUG "could not map hotkey id=%04x mask=%04x", key, mask));
return 0;
}
// fail if no keys
if (key == kKeyNone && mask == 0) {
return 0;
}
// convert to X
unsigned int modifiers;
if (!m_keyState->mapModifiersToX(mask, modifiers)) {
// can't map all modifiers
LOG((CLOG_DEBUG "could not map hotkey id=%04x mask=%04x", key, mask));
return 0;
}
XWindowsKeyState::KeycodeList keycodes;
m_keyState->mapKeyToKeycodes(key, keycodes);
if (key != kKeyNone && keycodes.empty()) {
// can't map key
LOG((CLOG_DEBUG "could not map hotkey id=%04x mask=%04x", key, mask));
return 0;
}
// choose hotkey id
UInt32 id;
if (!m_oldHotKeyIDs.empty()) {
id = m_oldHotKeyIDs.back();
m_oldHotKeyIDs.pop_back();
} else {
id = m_hotKeys.size() + 1;
}
HotKeyList &hotKeys = m_hotKeys[id];
// all modifier hotkey must be treated specially. for each modifier
// we need to grab the modifier key in combination with all the other
// requested modifiers.
bool err = false;
{
XWindowsUtil::ErrorLock lock(m_display, &err);
if (key == kKeyNone) {
static const KeyModifierMask s_hotKeyModifiers[] = {
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) {
// skip modifier if not in mask
if ((mask & s_hotKeyModifiers[j]) == 0) {
continue;
}
// skip with error if we can't map remaining modifiers
unsigned int modifiers2;
KeyModifierMask mask2 = (mask & ~s_hotKeyModifiers[j]);
if (!m_keyState->mapModifiersToX(mask2, modifiers2)) {
err = true;
continue;
}
// compute modifier index for modifier. there should be
// exactly one X modifier missing
int index;
switch (modifiers ^ modifiers2) {
case ShiftMask:
index = ShiftMapIndex;
break;
case LockMask:
index = LockMapIndex;
break;
case ControlMask:
index = ControlMapIndex;
break;
case Mod1Mask:
index = Mod1MapIndex;
break;
case Mod2Mask:
index = Mod2MapIndex;
break;
case Mod3Mask:
index = Mod3MapIndex;
break;
case Mod4Mask:
index = Mod4MapIndex;
break;
case Mod5Mask:
index = Mod5MapIndex;
break;
default:
err = true;
continue;
}
// grab each key for the modifier
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);
if (!err) {
hotKeys.push_back(std::make_pair(code, modifiers2));
m_hotKeyToIDMap[HotKeyItem(code, modifiers2)] = id;
}
}
}
}
XFreeModifiermap(modKeymap);
}
// a non-modifier key must be insensitive to CapsLock, NumLock and
// ScrollLock, so we have to grab the key with every combination of
// those.
else {
// collect available toggle modifiers
unsigned int modifier;
unsigned int toggleModifiers[3];
size_t numToggleModifiers = 0;
if (m_keyState->mapModifiersToX(KeyModifierCapsLock, modifier)) {
toggleModifiers[numToggleModifiers++] = modifier;
}
if (m_keyState->mapModifiersToX(KeyModifierNumLock, modifier)) {
toggleModifiers[numToggleModifiers++] = modifier;
}
if (m_keyState->mapModifiersToX(KeyModifierScrollLock, modifier)) {
toggleModifiers[numToggleModifiers++] = modifier;
}
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;
if ((i & 1) != 0) {
tmpModifiers |= toggleModifiers[0];
}
if ((i & 2) != 0) {
tmpModifiers |= toggleModifiers[1];
}
if ((i & 4) != 0) {
tmpModifiers |= toggleModifiers[2];
}
// add grab
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;
}
}
}
}
}
if (err) {
// if any failed then unregister any we did get
for (HotKeyList::iterator j = hotKeys.begin(); j != hotKeys.end(); ++j) {
XUngrabKey(m_display, j->first, j->second, m_root);
m_hotKeyToIDMap.erase(HotKeyItem(j->first, j->second));
}
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)
);
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)
);
return id;
}
void XWindowsScreen::unregisterHotKey(UInt32 id)
{
// look up hotkey
HotKeyMap::iterator i = m_hotKeys.find(id);
if (i == m_hotKeys.end()) {
return;
}
// unregister with OS
bool err = false;
{
XWindowsUtil::ErrorLock lock(m_display, &err);
HotKeyList &hotKeys = i->second;
for (HotKeyList::iterator j = hotKeys.begin(); j != hotKeys.end(); ++j) {
XUngrabKey(m_display, j->first, j->second, m_root);
m_hotKeyToIDMap.erase(HotKeyItem(j->first, j->second));
}
}
if (err) {
LOG((CLOG_WARN "failed to unregister hotkey id=%d", id));
} else {
LOG((CLOG_DEBUG "unregistered hotkey id=%d", id));
}
// discard hot key from map and record old id for reuse
m_hotKeys.erase(i);
m_oldHotKeyIDs.push_back(id);
}
void XWindowsScreen::fakeInputBegin()
{
// FIXME -- not implemented
}
void XWindowsScreen::fakeInputEnd()
{
// FIXME -- not implemented
}
SInt32 XWindowsScreen::getJumpZoneSize() const
{
return 1;
}
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);
}
return false;
}
void XWindowsScreen::getCursorCenter(SInt32 &x, SInt32 &y) const
{
x = m_xCenter;
y = m_yCenter;
}
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);
XFlush(m_display);
}
}
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);
}
XFlush(m_display);
}
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
{
// XXX -- support x-axis scrolling
if (yDelta == 0) {
return;
}
yDelta = mapClientScrollDirection(yDelta);
// choose button depending on rotation direction
const unsigned int xButton = mapButtonToX(static_cast<ButtonID>((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.
// Patch by Tom Chadwick.
KeyCode keycode = 0;
if (yDelta >= 0) {
keycode = XKeysymToKeycode(m_display, XK_Page_Up);
} else {
keycode = XKeysymToKeycode(m_display, XK_Page_Down);
}
if (keycode != 0) {
XTestFakeKeyEvent(m_display, keycode, True, CurrentTime);
XTestFakeKeyEvent(m_display, keycode, False, CurrentTime);
}
return;
}
// now use absolute value of delta
if (yDelta < 0) {
yDelta = -yDelta;
}
if (yDelta < m_mouseScrollDelta) {
LOG((CLOG_WARN "wheel scroll delta (%d) smaller than threshold (%d)", yDelta, m_mouseScrollDelta));
}
// send as many clicks as necessary
for (; yDelta >= m_mouseScrollDelta; yDelta -= m_mouseScrollDelta) {
XTestFakeButtonEvent(m_display, xButton, True, CurrentTime);
XTestFakeButtonEvent(m_display, xButton, False, CurrentTime);
}
XFlush(m_display);
}
Display *XWindowsScreen::openDisplay(const char *displayName)
{
// get the DISPLAY
if (displayName == NULL) {
displayName = getenv("DISPLAY");
if (displayName == NULL) {
displayName = ":0.0";
}
}
// open the display
LOG((CLOG_DEBUG3 "calling XOpenDisplay(\"%s\")", displayName));
Display *display = XOpenDisplay(displayName);
if (display == NULL) {
throw XScreenUnavailable(60.0);
}
// verify the availability of the XTest extension
if (!m_isPrimary) {
int majorOpcode, firstEvent, firstError;
if (!XQueryExtension(display, XTestExtensionName, &majorOpcode, &firstEvent, &firstError)) {
LOG((CLOG_ERR "the XTest extension is not available"));
XCloseDisplay(display);
throw XScreenOpenFailure();
}
}
#if HAVE_XKB_EXTENSION
{
m_xkb = false;
int major = XkbMajorVersion, minor = XkbMinorVersion;
if (XkbLibraryVersion(&major, &minor)) {
int opcode, firstError;
if (XkbQueryExtension(display, &opcode, &m_xkbEventBase, &firstError, &major, &minor)) {
m_xkb = true;
XkbSelectEvents(display, XkbUseCoreKbd, XkbMapNotifyMask, XkbMapNotifyMask);
XkbSelectEventDetails(display, XkbUseCoreKbd, XkbStateNotifyMask, XkbGroupStateMask, XkbGroupStateMask);
}
}
}
#endif
#if HAVE_X11_EXTENSIONS_XRANDR_H
// query for XRandR extension
int dummyError;
m_xrandr = XRRQueryExtension(display, &m_xrandrEventBase, &dummyError);
if (m_xrandr) {
// enable XRRScreenChangeNotifyEvent
XRRSelectInput(display, DefaultRootWindow(display), RRScreenChangeNotifyMask | RRCrtcChangeNotifyMask);
}
#endif
return display;
}
void XWindowsScreen::saveShape()
{
// get shape of default screen
m_x = 0;
m_y = 0;
m_w = WidthOfScreen(DefaultScreenOfDisplay(m_display));
m_h = HeightOfScreen(DefaultScreenOfDisplay(m_display));
// get center of default screen
m_xCenter = m_x + (m_w >> 1);
m_yCenter = m_y + (m_h >> 1);
// check if xinerama is enabled and there is more than one screen.
// get center of first Xinerama screen. Xinerama appears to have
// a bug when XWarpPointer() is used in combination with
// XGrabPointer(). in that case, the warp is successful but the
// next pointer motion warps the pointer again, apparently to
// constrain it to some unknown region, possibly the region from
// 0,0 to Wm,Hm where Wm (Hm) is the minimum width (height) over
// all physical screens. this warp only seems to happen if the
// pointer wasn't in that region before the XWarpPointer(). the
// second (unexpected) warp causes deskflow to think the pointer
// has been moved when it hasn't. to work around the problem,
// we warp the pointer to the center of the first physical
// screen instead of the logical screen.
m_xinerama = false;
#if HAVE_X11_EXTENSIONS_XINERAMA_H
int eventBase, errorBase;
if (XineramaQueryExtension(m_display, &eventBase, &errorBase) && XineramaIsActive(m_display)) {
int numScreens;
XineramaScreenInfo *screens;
screens = XineramaQueryScreens(m_display, &numScreens);
if (screens != NULL) {
if (numScreens > 1) {
m_xinerama = true;
m_xCenter = screens[0].x_org + (screens[0].width >> 1);
m_yCenter = screens[0].y_org + (screens[0].height >> 1);
}
XFree(screens);
}
}
#endif
}
void XWindowsScreen::setShape(SInt32 width, SInt32 height)
{
// set shape
m_x = 0;
m_y = 0;
m_w = width;
m_h = height;
// get center of default screen
m_xCenter = m_x + (m_w >> 1);
m_yCenter = m_y + (m_h >> 1);
// check if xinerama is enabled and there is more than one screen.
// get center of first Xinerama screen. Xinerama appears to have
// a bug when XWarpPointer() is used in combination with
// XGrabPointer(). in that case, the warp is successful but the
// next pointer motion warps the pointer again, apparently to
// constrain it to some unknown region, possibly the region from
// 0,0 to Wm,Hm where Wm (Hm) is the minimum width (height) over
// all physical screens. this warp only seems to happen if the
// pointer wasn't in that region before the XWarpPointer(). the
// second (unexpected) warp causes deskflow to think the pointer
// has been moved when it hasn't. to work around the problem,
// we warp the pointer to the center of the first physical
// screen instead of the logical screen.
m_xinerama = false;
#if HAVE_X11_EXTENSIONS_XINERAMA_H
int eventBase, errorBase;
if ((XineramaQueryExtension(m_display, &eventBase, &errorBase) != 0) && (XineramaIsActive(m_display) != 0)) {
int numScreens;
XineramaScreenInfo *screens;
screens = XineramaQueryScreens(m_display, &numScreens);
if (screens != nullptr) {
if (numScreens > 1) {
m_xinerama = true;
m_xCenter = screens[0].x_org + (screens[0].width >> 1);
m_yCenter = screens[0].y_org + (screens[0].height >> 1);
}
XFree(screens);
}
}
#endif
}
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.
XSetWindowAttributes attr;
attr.do_not_propagate_mask = 0;
attr.override_redirect = True;
attr.cursor = createBlankCursor();
// adjust attributes and get size and shape
SInt32 x, y, w, h;
if (m_isPrimary) {
// 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;
x = m_x;
y = m_y;
w = m_w;
h = m_h;
} else {
// cursor hider window attributes. this window is used to hide the
// cursor when it's not on the screen. the window is hidden as soon
// as the cursor enters the screen or the display's real mouse is
// moved. we'll reposition the window as necessary so its
// position here doesn't matter. it only needs to be 1x1 because
// it only needs to contain the cursor's hotspot.
attr.event_mask = LeaveWindowMask;
x = 0;
y = 0;
w = 1;
h = 1;
}
// 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
);
if (window == None) {
throw XScreenOpenFailure();
}
return window;
}
void XWindowsScreen::openIM()
{
// open the input methods
XIM im = XOpenIM(m_display, NULL, NULL, NULL);
if (im == NULL) {
LOG((CLOG_INFO "no support for IM"));
return;
}
// find the appropriate style. deskflow supports XIMPreeditNothing
// only at the moment.
XIMStyles *styles;
if (XGetIMValues(im, XNQueryInputStyle, &styles, NULL) != NULL || styles == NULL) {
LOG((CLOG_WARN "cannot get IM styles"));
XCloseIM(im);
return;
}
XIMStyle style = 0;
for (unsigned short i = 0; i < styles->count_styles; ++i) {
style = styles->supported_styles[i];
if ((style & XIMPreeditNothing) != 0) {
if ((style & (XIMStatusNothing | XIMStatusNone)) != 0) {
break;
}
}
}
XFree(styles);
if (style == 0) {
LOG((CLOG_INFO "no supported IM styles"));
XCloseIM(im);
return;
}
// create an input context for the style and tell it about our window
XIC ic = XCreateIC(im, XNInputStyle, style, XNClientWindow, m_window, NULL);
if (ic == NULL) {
LOG((CLOG_WARN "cannot create IC"));
XCloseIM(im);
return;
}
// find out the events we must select for and do so
unsigned long mask;
if (XGetICValues(ic, XNFilterEvents, &mask, NULL) != NULL) {
LOG((CLOG_WARN "cannot get IC filter events"));
XDestroyIC(ic);
XCloseIM(im);
return;
}
// we have IM
m_im = im;
m_ic = ic;
m_lastKeycode = 0;
// select events on our window that IM requires
XWindowAttributes attr;
XGetWindowAttributes(m_display, m_window, &attr);
XSelectInput(m_display, m_window, attr.your_event_mask | mask);
// listen for screen-resize messages
XSelectInput(m_display, m_root, StructureNotifyMask);
}
void XWindowsScreen::sendEvent(Event::Type type, void *data)
{
m_events->addEvent(Event(type, getEventTarget(), data));
}
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;
}
Bool XWindowsScreen::findKeyEvent(Display *, XEvent *xevent, XPointer arg)
{
KeyEventFilter *filter = reinterpret_cast<KeyEventFilter *>(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)
? True
: False;
}
void XWindowsScreen::handleSystemEvent(const Event &event, void *)
{
XEvent *xevent = static_cast<XEvent *>(event.getData());
assert(xevent != NULL);
// update key state
bool isRepeat = false;
if (m_isPrimary) {
if (xevent->type == KeyRelease) {
// check if this is a key repeat by getting the next
// KeyPress event that has the same key and time as
// this release event, if any. first prepare the
// filter info.
KeyEventFilter filter;
filter.m_event = KeyPress;
filter.m_window = xevent->xkey.window;
filter.m_time = xevent->xkey.time;
filter.m_keycode = xevent->xkey.keycode;
XEvent xevent2;
isRepeat = (XCheckIfEvent(m_display, &xevent2, &XWindowsScreen::findKeyEvent, (XPointer)&filter) == True);
}
if (xevent->type == KeyPress || xevent->type == KeyRelease) {
if (xevent->xkey.window == m_root) {
// this is a hot key
onHotKey(xevent->xkey, isRepeat);
return;
} else if (!m_isOnScreen) {
// this might be a hot key
if (onHotKey(xevent->xkey, isRepeat)) {
return;
}
}
bool down = (isRepeat || xevent->type == KeyPress);
KeyModifierMask state = m_keyState->mapModifiersFromX(xevent->xkey.state);
m_keyState->onKey(xevent->xkey.keycode, down, state);
}
}
// let input methods try to handle event first
if (m_ic != NULL) {
// XFilterEvent() may eat the event and generate a new KeyPress
// event with a keycode of 0 because there isn't an actual key
// associated with the keysym. but the KeyRelease may pass
// through XFilterEvent() and keep its keycode. this means
// there's a mismatch between KeyPress and KeyRelease keycodes.
// since we use the keycode on the client to detect when a key
// is released this won't do. so we remember the keycode on
// the most recent KeyPress (and clear it on a matching
// 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) {
m_lastKeycode = 0;
}
// now filter the event
if (XFilterEvent(xevent, DefaultRootWindow(m_display))) {
if (xevent->type == KeyPress) {
// add filtered presses to the filtered list
m_filtered.insert(m_lastKeycode);
}
return;
}
// discard matching key releases for key presses that were
// filtered and remove them from our filtered list.
else if (xevent->type == KeyRelease && m_filtered.count(xevent->xkey.keycode) > 0) {
m_filtered.erase(xevent->xkey.keycode);
return;
}
}
// let screen saver have a go
if (m_screensaver->handleXEvent(xevent)) {
// screen saver handled it
return;
}
#ifdef HAVE_XI2
if (m_xi2detected) {
// Process RawMotion
XGenericEventCookie *cookie = (XGenericEventCookie *)&xevent->xcookie;
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;
XMotionEvent xmotion;
xmotion.type = MotionNotify;
xmotion.send_event = False; // Raw motion
xmotion.display = m_display;
xmotion.window = m_window;
/* 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
);
onMouseMove(xmotion);
XFreeEventData(m_display, cookie);
return;
}
XFreeEventData(m_display, cookie);
}
}
#endif
// handle the event ourself
switch (xevent->type) {
case CreateNotify:
if (m_isPrimary && !m_xi2detected) {
// select events on new window
selectEvents(xevent->xcreatewindow.window);
}
break;
case MappingNotify:
refreshKeyboard(xevent);
break;
case LeaveNotify:
if (!m_isPrimary) {
// mouse moved out of hider window somehow. hide the window.
XUnmapWindow(m_display, m_window);
}
break;
case SelectionClear: {
// we just lost the selection. that means someone else
// grabbed the selection so this screen is now the
// selection owner. report that to the receiver.
ClipboardID id = getClipboardID(xevent->xselectionclear.selection);
if (id != kClipboardEnd) {
m_clipboard[id]->lost(xevent->xselectionclear.time);
sendClipboardEvent(m_events->forClipboard().clipboardGrabbed(), id);
return;
}
} break;
case SelectionNotify:
// notification of selection transferred. we shouldn't
// get this here because we handle them in the selection
// 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);
}
break;
case SelectionRequest: {
// somebody is asking for clipboard data
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
);
return;
}
} break;
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);
}
break;
case DestroyNotify:
// looks like one of the windows that requested a clipboard
// transfer has gone bye-bye.
destroyClipboardRequest(xevent->xdestroywindow.window);
break;
case KeyPress:
if (m_isPrimary) {
onKeyPress(xevent->xkey);
}
return;
case KeyRelease:
if (m_isPrimary) {
onKeyRelease(xevent->xkey, isRepeat);
}
return;
case ButtonPress:
if (m_isPrimary) {
onMousePress(xevent->xbutton);
}
return;
case ButtonRelease:
if (m_isPrimary) {
onMouseRelease(xevent->xbutton);
}
return;
case MotionNotify:
if (m_isPrimary) {
onMouseMove(xevent->xmotion);
}
return;
case ConfigureNotify:
if (!m_isPrimary && xevent->xconfigure.window == m_root) {
setShape(xevent->xconfigure.width, xevent->xconfigure.height);
sendEvent(m_events->forIScreen().shapeChanged());
}
return;
default:
#if HAVE_XKB_EXTENSION
if (m_xkb && xevent->type == m_xkbEventBase) {
XkbEvent *xkbEvent = reinterpret_cast<XkbEvent *>(xevent);
switch (xkbEvent->any.xkb_type) {
case XkbMapNotify:
refreshKeyboard(xevent);
return;
case XkbStateNotify:
LOG((CLOG_INFO "group change: %d", xkbEvent->state.group));
m_keyState->setActiveGroup((SInt32)xkbEvent->state.group);
return;
}
}
#endif
#if HAVE_X11_EXTENSIONS_XRANDR_H
if (m_xrandr) {
if (xevent->type == m_xrandrEventBase + RRScreenChangeNotify ||
xevent->type == m_xrandrEventBase + RRNotify &&
reinterpret_cast<XRRNotifyEvent *>(xevent)->subtype == RRNotify_CrtcChange) {
LOG((CLOG_INFO "either XRRScreenChangeNotifyEvent or "
"RRNotify_CrtcChange received"));
// we're required to call back into XLib so XLib can update its internal
// state
XRRUpdateConfiguration(xevent);
// requery/recalculate the screen shape
saveShape();
// we need to resize m_window, otherwise we'll get a weird problem where
// moving off the server onto the client causes the pointer to warp to
// the center of the server (so you can't move the pointer off the
// server)
if (m_isPrimary) {
XMoveWindow(m_display, m_window, m_x, m_y);
XResizeWindow(m_display, m_window, m_w, m_h);
}
sendEvent(m_events->forIScreen().shapeChanged());
}
}
#endif
break;
}
}
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)) {
// pretend it's ctrl+alt+del
LOG((CLOG_DEBUG "emulate ctrl+alt+del"));
key = kKeyDelete;
}
// get which button. see call to XFilterEvent() in onEvent()
// for more info.
bool isFake = false;
KeyButton keycode = static_cast<KeyButton>(xkey.keycode);
if (keycode == 0) {
isFake = true;
keycode = static_cast<KeyButton>(m_lastKeycode);
if (keycode == 0) {
// no keycode
LOG((CLOG_DEBUG1 "event: KeyPress no keycode"));
return;
}
}
// handle key
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);
}
} else {
LOG((CLOG_DEBUG1 "can't map keycode to key id"));
}
}
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)) {
// pretend it's ctrl+alt+del and ignore autorepeat
LOG((CLOG_DEBUG "emulate ctrl+alt+del"));
key = kKeyDelete;
isRepeat = false;
}
KeyButton keycode = static_cast<KeyButton>(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);
} 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);
}
}
}
bool XWindowsScreen::onHotKey(XKeyEvent &xkey, bool isRepeat)
{
// find the hot key id
HotKeyToIDMap::const_iterator i = m_hotKeyToIDMap.find(HotKeyItem(xkey.keycode, xkey.state));
if (i == m_hotKeyToIDMap.end()) {
return false;
}
// find what kind of event
Event::Type type;
if (xkey.type == KeyPress) {
type = m_events->forIPrimaryScreen().hotKeyDown();
} else if (xkey.type == KeyRelease) {
type = m_events->forIPrimaryScreen().hotKeyUp();
} else {
return false;
}
// generate event (ignore key repeats)
if (!isRepeat) {
m_events->addEvent(Event(type, getEventTarget(), HotKeyInfo::alloc(i->second)));
}
return true;
}
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));
}
}
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));
} else if (xbutton.button == 4) {
// wheel forward (away from user)
sendEvent(m_events->forIPrimaryScreen().wheel(), WheelInfo::alloc(0, 120));
} else if (xbutton.button == 5) {
// wheel backward (toward user)
sendEvent(m_events->forIPrimaryScreen().wheel(), WheelInfo::alloc(0, -120));
}
// XXX -- support x-axis scrolling
}
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)
SInt32 x = xmotion.x_root - m_xCursor;
SInt32 y = xmotion.y_root - m_yCursor;
// save position to compute delta of next motion
m_xCursor = xmotion.x_root;
m_yCursor = xmotion.y_root;
if (xmotion.send_event) {
// we warped the mouse. discard events until we
// find the matching sent event. see
// warpCursorNoFlush() for where the events are
// sent. we discard the matching sent event and
// can be sure we've skipped the warp event.
XEvent xevent;
char cntr = 0;
do {
XMaskEvent(m_display, PointerMotionMask, &xevent);
if (cntr++ > 10) {
LOG((CLOG_WARN "too many discarded events! %d", cntr));
break;
}
} while (!xevent.xany.send_event);
cntr = 0;
} else if (m_isOnScreen) {
// motion on primary screen
sendEvent(m_events->forIPrimaryScreen().motionOnPrimary(), MotionInfo::alloc(m_xCursor, m_yCursor));
} else {
// motion on secondary screen. warp mouse back to
// center.
//
// my lombard (powerbook g3) running linux and
// using the adbmouse driver has two problems:
// first, the driver only sends motions of +/-2
// pixels and, second, it seems to discard some
// physical input after a warp. the former isn't a
// big deal (we're just limited to every other
// pixel) but the latter is a PITA. to work around
// 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) {
warpCursorNoFlush(m_xCenter, m_yCenter);
}
// send event if mouse moved. do this after warping
// back to center in case the motion takes us onto
// the primary screen. if we sent the event first
// in that case then the warp would happen after
// 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));
}
}
}
Cursor XWindowsScreen::createBlankCursor() const
{
// this seems just a bit more complicated than really necessary
// get the closet cursor size to 1x1
unsigned int w = 0, h = 0;
XQueryBestCursor(m_display, m_root, 1, 1, &w, &h);
w = std::max(1u, w);
h = std::max(1u, h);
// make bitmap data for cursor of closet size. since the cursor
// is blank we can use the same bitmap for shape and mask: all
// zeros.
const int size = ((w + 7) >> 3) * h;
char *data = new char[size];
memset(data, 0, size);
// make bitmap
Pixmap bitmap = XCreateBitmapFromData(m_display, m_root, data, w, h);
// need an arbitrary color for the cursor
XColor color;
color.pixel = 0;
color.red = color.green = color.blue = 0;
color.flags = DoRed | DoGreen | DoBlue;
// make cursor from bitmap
Cursor cursor = XCreatePixmapCursor(m_display, bitmap, bitmap, &color, &color, 0, 0);
// don't need bitmap or the data anymore
delete[] data;
XFreePixmap(m_display, bitmap);
return cursor;
}
ClipboardID XWindowsScreen::getClipboardID(Atom selection) const
{
for (ClipboardID id = 0; id < kClipboardEnd; ++id) {
if (m_clipboard[id] != NULL && m_clipboard[id]->getSelection() == selection) {
return id;
}
}
return kClipboardEnd;
}
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)) {
break;
}
}
}
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)) {
break;
}
}
}
void XWindowsScreen::onError()
{
// prevent further access to the X display
m_events->adoptBuffer(NULL);
m_screensaver->destroy();
m_screensaver = NULL;
m_display = NULL;
// notify of failure
sendEvent(m_events->forIScreen().error(), NULL);
// FIXME -- should ensure that we ignore operations that involve
// m_display from now on. however, Xlib will simply exit the
// application in response to the X I/O error so there's no
// point in trying to really handle the error. if we did want
// to handle the error, it'd probably be easiest to delegate to
// one of two objects. one object would take the implementation
// from this class. the other object would be stub methods that
// don't use X11. on error, we'd switch to the latter.
}
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
// don't access the display anymore.
LOG((CLOG_CRIT "x display has unexpectedly disconnected"));
s_screen->onError();
return 0;
}
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.
XWindowsUtil::ErrorLock lock(m_display);
// adjust event masks
doSelectEvents(w);
}
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
// select events on new windows too.
// we don't want to adjust our grab window
if (w == m_window) {
return;
}
// X11 has a design flaw. If *no* client selected PointerMotionMask for
// a window, motion events will be delivered to that window's parent.
// If *any* client, not necessarily the owner, selects PointerMotionMask
// on such a window, X will stop propagating motion events to its
// parent. This breaks applications that rely on event propagation
// behavior.
//
// Avoid selecting PointerMotionMask unless some other client selected
// it already.
long mask = SubstructureNotifyMask;
XWindowAttributes attr;
XGetWindowAttributes(m_display, w, &attr);
if ((attr.all_event_masks & PointerMotionMask) == PointerMotionMask) {
mask |= PointerMotionMask;
}
// select events of interest. do this before querying the tree so
// we'll get notifications of children created after the XQueryTree()
// so we won't miss them.
XSelectInput(m_display, w, mask);
// recurse on child windows
Window rw, pw, *cw;
unsigned int nc;
if (XQueryTree(m_display, w, &rw, &pw, &cw, &nc)) {
for (unsigned int i = 0; i < nc; ++i) {
doSelectEvents(cw[i]);
}
XFree(cw);
}
}
KeyID XWindowsScreen::mapKeyFromX(XKeyEvent *event) const
{
// convert to a keysym
KeySym keysym;
if (event->type == KeyPress && m_ic != NULL) {
// do multibyte lookup. can only call XmbLookupString with a
// key press event and a valid XIC so we checked those above.
char scratch[32];
int n = sizeof(scratch) / sizeof(scratch[0]);
char *buffer = scratch;
int status;
n = XmbLookupString(m_ic, event, buffer, n, &keysym, &status);
if (status == XBufferOverflow) {
// not enough space. grow buffer and try again.
buffer = new char[n];
n = XmbLookupString(m_ic, event, buffer, n, &keysym, &status);
delete[] buffer;
}
// see what we got. since we don't care about the string
// we'll just look for a keysym.
switch (status) {
default:
case XLookupNone:
case XLookupChars:
keysym = 0;
break;
case XLookupKeySym:
case XLookupBoth:
break;
}
} else {
// plain old lookup
char dummy[1];
XLookupString(event, dummy, 0, &keysym, NULL);
}
LOG((CLOG_DEBUG2 "mapped code=%d to keysym=0x%04x", event->keycode, keysym));
// convert key
KeyID result = XWindowsUtil::mapKeySymToKeyID(keysym);
LOG((CLOG_DEBUG2 "mapped keysym=0x%04x to keyID=%d", keysym, result));
return result;
}
ButtonID XWindowsScreen::mapButtonFromX(const XButtonEvent *event) const
{
unsigned int button = event->button;
// first three buttons map to 1, 2, 3 (kButtonLeft, Middle, Right)
if (button >= 1 && button <= 3) {
return static_cast<ButtonID>(button);
}
// buttons 4 and 5 are ignored here. they're used for the wheel.
// buttons 6, 7, etc and up map to 4, 5, etc.
else if (button >= 6) {
return static_cast<ButtonID>(button - 2);
}
// unknown button
else {
return kButtonNone;
}
}
unsigned int XWindowsScreen::mapButtonToX(ButtonID id) const
{
// map button -1 to button 4 (+wheel)
if (id == static_cast<ButtonID>(-1)) {
id = 4;
}
// map button -2 to button 5 (-wheel)
else if (id == static_cast<ButtonID>(-2)) {
id = 5;
}
// map buttons 4, 5, etc. to 6, 7, etc. to make room for buttons
// 4 and 5 used to simulate the mouse wheel.
else if (id >= 4) {
id += 2;
}
// check button is in legal range
if (id < 1 || id > m_buttons.size()) {
// out of range
return 0;
}
// map button
return static_cast<unsigned int>(id);
}
void XWindowsScreen::warpCursorNoFlush(SInt32 x, SInt32 y)
{
assert(m_window != None);
// send an event that we can recognize before the mouse warp
XEvent eventBefore;
eventBefore.type = MotionNotify;
eventBefore.xmotion.display = m_display;
eventBefore.xmotion.window = m_window;
eventBefore.xmotion.root = m_root;
eventBefore.xmotion.subwindow = m_window;
eventBefore.xmotion.time = CurrentTime;
eventBefore.xmotion.x = x;
eventBefore.xmotion.y = y;
eventBefore.xmotion.x_root = x;
eventBefore.xmotion.y_root = y;
eventBefore.xmotion.state = 0;
eventBefore.xmotion.is_hint = NotifyNormal;
eventBefore.xmotion.same_screen = True;
XEvent eventAfter = eventBefore;
XSendEvent(m_display, m_window, False, 0, &eventBefore);
// warp mouse
XWarpPointer(m_display, None, m_root, 0, 0, 0, 0, x, y);
// send an event that we can recognize after the mouse warp
XSendEvent(m_display, m_window, False, 0, &eventAfter);
XSync(m_display, False);
LOG((CLOG_DEBUG2 "warped to %d,%d", x, y));
}
void XWindowsScreen::updateButtons()
{
// query the button mapping
UInt32 numButtons = XGetPointerMapping(m_display, NULL, 0);
unsigned char *tmpButtons = new unsigned char[numButtons];
XGetPointerMapping(m_display, tmpButtons, numButtons);
// find the largest logical button id
unsigned char maxButton = 0;
for (UInt32 i = 0; i < numButtons; ++i) {
if (tmpButtons[i] > maxButton) {
maxButton = tmpButtons[i];
}
}
// allocate button array
m_buttons.resize(maxButton);
// fill in button array values. m_buttons[i] is the physical
// button number for logical button i+1.
for (UInt32 i = 0; i < numButtons; ++i) {
m_buttons[i] = 0;
}
for (UInt32 i = 0; i < numButtons; ++i) {
m_buttons[tmpButtons[i] - 1] = i + 1;
}
// clean up
delete[] tmpButtons;
}
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
// and wait before retrying. give up after s_timeout seconds.
static const double s_timeout = 1.0;
int result;
Stopwatch timer;
do {
// keyboard first
do {
result = XGrabKeyboard(m_display, m_window, True, GrabModeAsync, GrabModeAsync, CurrentTime);
assert(result != GrabNotViewable);
if (result != GrabSuccess) {
LOG((CLOG_DEBUG2 "waiting to grab keyboard"));
ARCH->sleep(0.05);
if (timer.getTime() >= s_timeout) {
LOG((CLOG_DEBUG2 "grab keyboard timed out"));
return false;
}
}
} while (result != GrabSuccess);
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);
assert(result != GrabNotViewable);
if (result != GrabSuccess) {
// back off to avoid grab deadlock
XUngrabKeyboard(m_display, CurrentTime);
LOG((CLOG_DEBUG2 "ungrabbed keyboard, waiting to grab pointer"));
ARCH->sleep(0.05);
if (timer.getTime() >= s_timeout) {
LOG((CLOG_DEBUG2 "grab pointer timed out"));
return false;
}
}
} while (result != GrabSuccess);
LOG((CLOG_DEBUG1 "grabbed pointer and keyboard"));
return true;
}
void XWindowsScreen::refreshKeyboard(XEvent *event)
{
if (XPending(m_display) > 0) {
XEvent tmpEvent;
XPeekEvent(m_display, &tmpEvent);
if (tmpEvent.type == MappingNotify) {
// discard this event since another follows.
// we tend to get a bunch of these in a row.
return;
}
}
// keyboard mapping changed
#if HAVE_XKB_EXTENSION
if (m_xkb && event->type == m_xkbEventBase) {
XkbRefreshKeyboardMapping((XkbMapNotifyEvent *)event);
} else
#else
{
XRefreshKeyboardMapping(&event->xmapping);
}
#endif
m_keyState->updateKeyMap();
m_keyState->updateKeyState();
}
//
// XWindowsScreen::HotKeyItem
//
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::detectXI2()
{
int event, error;
return XQueryExtension(m_display, "XInputExtension", &xi_opcode, &event, &error);
}
#ifdef HAVE_XI2
void XWindowsScreen::selectXIRawMotion()
{
XIEventMask mask;
mask.deviceid = XIAllDevices;
mask.mask_len = XIMaskLen(XI_RawMotion);
mask.mask = (unsigned char *)calloc(mask.mask_len, sizeof(char));
mask.deviceid = XIAllMasterDevices;
memset(mask.mask, 0, 2);
XISetMask(mask.mask, XI_RawKeyRelease);
XISetMask(mask.mask, XI_RawMotion);
XISelectEvents(m_display, DefaultRootWindow(m_display), &mask, 1);
free(mask.mask);
}
#endif
| 60,761
|
C++
|
.cpp
| 1,772
| 29.910271
| 120
| 0.680291
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,586
|
XWindowsClipboardBMPConverter.cpp
|
deskflow_deskflow/src/lib/platform/XWindowsClipboardBMPConverter.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2004 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/XWindowsClipboardBMPConverter.h"
// BMP file header structure
struct CBMPHeader
{
public:
UInt16 type;
UInt32 size;
UInt16 reserved1;
UInt16 reserved2;
UInt32 offset;
};
// BMP is little-endian
static inline UInt32 fromLEU32(const UInt8 *data)
{
return static_cast<UInt32>(data[0]) | (static_cast<UInt32>(data[1]) << 8) | (static_cast<UInt32>(data[2]) << 16) |
(static_cast<UInt32>(data[3]) << 24);
}
static void toLE(UInt8 *&dst, char src)
{
dst[0] = static_cast<UInt8>(src);
dst += 1;
}
static void toLE(UInt8 *&dst, UInt16 src)
{
dst[0] = static_cast<UInt8>(src & 0xffu);
dst[1] = static_cast<UInt8>((src >> 8) & 0xffu);
dst += 2;
}
static void toLE(UInt8 *&dst, UInt32 src)
{
dst[0] = static_cast<UInt8>(src & 0xffu);
dst[1] = static_cast<UInt8>((src >> 8) & 0xffu);
dst[2] = static_cast<UInt8>((src >> 16) & 0xffu);
dst[3] = static_cast<UInt8>((src >> 24) & 0xffu);
dst += 4;
}
//
// XWindowsClipboardBMPConverter
//
XWindowsClipboardBMPConverter::XWindowsClipboardBMPConverter(Display *display)
: m_atom(XInternAtom(display, "image/bmp", False))
{
// do nothing
}
XWindowsClipboardBMPConverter::~XWindowsClipboardBMPConverter()
{
// do nothing
}
IClipboard::EFormat XWindowsClipboardBMPConverter::getFormat() const
{
return IClipboard::kBitmap;
}
Atom XWindowsClipboardBMPConverter::getAtom() const
{
return m_atom;
}
int XWindowsClipboardBMPConverter::getDataSize() const
{
return 8;
}
String XWindowsClipboardBMPConverter::fromIClipboard(const String &bmp) const
{
// create BMP image
UInt8 header[14];
UInt8 *dst = header;
toLE(dst, 'B');
toLE(dst, 'M');
toLE(dst, static_cast<UInt32>(14 + bmp.size()));
toLE(dst, static_cast<UInt16>(0));
toLE(dst, static_cast<UInt16>(0));
toLE(dst, static_cast<UInt32>(14 + 40));
return String(reinterpret_cast<const char *>(header), 14) + bmp;
}
String XWindowsClipboardBMPConverter::toIClipboard(const String &bmp) const
{
// make sure data is big enough for a BMP file
if (bmp.size() <= 14 + 40) {
return String();
}
// check BMP file header
const UInt8 *rawBMPHeader = reinterpret_cast<const UInt8 *>(bmp.data());
if (rawBMPHeader[0] != 'B' || rawBMPHeader[1] != 'M') {
return String();
}
// get offset to image data
UInt32 offset = fromLEU32(rawBMPHeader + 10);
// construct BMP
if (offset == 14 + 40) {
return bmp.substr(14);
} else {
return bmp.substr(14, 40) + bmp.substr(offset, bmp.size() - offset);
}
}
| 3,241
|
C++
|
.cpp
| 110
| 27.1
| 116
| 0.710019
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| true
| false
| false
| true
| false
| false
|
13,587
|
MSWindowsScreen.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsScreen.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/MSWindowsScreen.h"
#include "arch/Arch.h"
#include "arch/win32/ArchMiscWindows.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/String.h"
#include "base/TMethodEventJob.h"
#include "base/TMethodJob.h"
#include "client/Client.h"
#include "common/constants.h"
#include "deskflow/App.h"
#include "deskflow/ArgsBase.h"
#include "deskflow/ClientApp.h"
#include "deskflow/Clipboard.h"
#include "deskflow/KeyMap.h"
#include "deskflow/XScreen.h"
#include "mt/Thread.h"
#include "platform/MSWindowsClipboard.h"
#include "platform/MSWindowsDesks.h"
#include "platform/MSWindowsDropTarget.h"
#include "platform/MSWindowsEventQueueBuffer.h"
#include "platform/MSWindowsKeyState.h"
#include "platform/MSWindowsScreenSaver.h"
#include <Shlobj.h>
#include <algorithm>
#include <comutil.h>
#include <string.h>
// suppress warning about GetVersionEx, which is used indirectly in this
// compilation unit.
#pragma warning(disable : 4996)
//
// add backwards compatible multihead support (and suppress bogus warning).
// this isn't supported on MinGW yet AFAICT.
//
#if defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4706) // assignment within conditional
#define COMPILE_MULTIMON_STUBS
#include <multimon.h>
#pragma warning(pop)
#endif
// X button stuff
#if !defined(WM_XBUTTONDOWN)
#define WM_XBUTTONDOWN 0x020B
#define WM_XBUTTONUP 0x020C
#define WM_XBUTTONDBLCLK 0x020D
#define WM_NCXBUTTONDOWN 0x00AB
#define WM_NCXBUTTONUP 0x00AC
#define WM_NCXBUTTONDBLCLK 0x00AD
#define MOUSEEVENTF_XDOWN 0x0080
#define MOUSEEVENTF_XUP 0x0100
#define XBUTTON1 0x0001
#define XBUTTON2 0x0002
#endif
#if !defined(VK_XBUTTON1)
#define VK_XBUTTON1 0x05
#define VK_XBUTTON2 0x06
#endif
// WM_POWERBROADCAST stuff
#if !defined(PBT_APMRESUMEAUTOMATIC)
#define PBT_APMRESUMEAUTOMATIC 0x0012
#endif
//
// MSWindowsScreen
//
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
)
: PlatformScreen(events, scrollDirection),
m_isPrimary(isPrimary),
m_noHooks(noHooks),
m_isOnScreen(m_isPrimary),
m_class(0),
m_x(0),
m_y(0),
m_w(0),
m_h(0),
m_xCenter(0),
m_yCenter(0),
m_multimon(false),
m_xCursor(0),
m_yCursor(0),
m_sequenceNumber(0),
m_mark(0),
m_markReceived(0),
m_fixTimer(NULL),
m_keyLayout(NULL),
m_screensaver(NULL),
m_screensaverNotify(false),
m_screensaverActive(false),
m_window(NULL),
m_nextClipboardWindow(NULL),
m_ownClipboard(false),
m_desks(NULL),
m_keyState(NULL),
m_hasMouse(GetSystemMetrics(SM_MOUSEPRESENT) != 0),
m_showingMouse(false),
m_events(events),
m_dropWindow(NULL),
m_dropWindowSize(20)
{
assert(s_windowInstance != NULL);
assert(s_screen == NULL);
s_screen = this;
try {
if (m_isPrimary && !m_noHooks) {
m_hook.loadLibrary();
}
m_screensaver = new MSWindowsScreenSaver();
m_desks = new MSWindowsDesks(
m_isPrimary, m_noHooks, m_screensaver, m_events,
new TMethodJob<MSWindowsScreen>(this, &MSWindowsScreen::updateKeysCB), stopOnDeskSwitch
);
m_keyState = new MSWindowsKeyState(
m_desks, getEventTarget(), m_events, AppUtil::instance().getKeyboardLayoutList(), enableLangSync
);
updateScreenShape();
m_class = createWindowClass();
m_window = createWindow(m_class, kAppName);
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 "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()));
} else {
LOG((CLOG_DEBUG "unable to use desktop as file drag-drop target, code=%d", GetLastError()));
}
if (App::instance().argsBase().m_preventSleep) {
m_powerManager.disableSleep();
}
OleInitialize(0);
m_dropWindow = createDropWindow(m_class, "DropWindow");
m_dropTarget = new MSWindowsDropTarget();
RegisterDragDrop(m_dropWindow, m_dropTarget);
} catch (...) {
delete m_keyState;
delete m_desks;
delete m_screensaver;
destroyWindow(m_window);
destroyClass(m_class);
s_screen = NULL;
throw;
}
// install event handlers
m_events->adoptHandler(
Event::kSystem, m_events->getSystemTarget(),
new TMethodEventJob<MSWindowsScreen>(this, &MSWindowsScreen::handleSystemEvent)
);
// install the platform event queue
m_events->adoptBuffer(new MSWindowsEventQueueBuffer(m_events));
}
MSWindowsScreen::~MSWindowsScreen()
{
assert(s_screen != NULL);
disable();
m_events->adoptBuffer(NULL);
m_events->removeHandler(Event::kSystem, m_events->getSystemTarget());
delete m_keyState;
delete m_desks;
delete m_screensaver;
destroyWindow(m_window);
destroyClass(m_class);
RevokeDragDrop(m_dropWindow);
m_dropTarget->Release();
OleUninitialize();
destroyWindow(m_dropWindow);
s_screen = NULL;
}
void MSWindowsScreen::init(HINSTANCE windowInstance)
{
assert(s_windowInstance == NULL);
assert(windowInstance != NULL);
s_windowInstance = windowInstance;
}
HINSTANCE
MSWindowsScreen::getWindowInstance()
{
return s_windowInstance;
}
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<MSWindowsScreen>(this, &MSWindowsScreen::handleFixes)
);
// install our clipboard snooper
m_nextClipboardWindow = SetClipboardViewer(m_window);
// track the active desk and (re)install the hooks
m_desks->enable();
if (m_isPrimary) {
// set jump zones
m_hook.setZone(m_x, m_y, m_w, m_h, getJumpZoneSize());
// watch jump zones
m_hook.setMode(kHOOK_WATCH_JUMP_ZONE);
}
}
void MSWindowsScreen::disable()
{
// stop tracking the active desk
m_desks->disable();
if (m_isPrimary) {
// disable hooks
m_hook.setMode(kHOOK_DISABLE);
// enable special key sequences on win95 family
enableSpecialKeys(true);
}
// tell key state
m_keyState->disable();
// stop snooping the clipboard
ChangeClipboardChain(m_window, m_nextClipboardWindow);
m_nextClipboardWindow = NULL;
// uninstall fix timer
if (m_fixTimer != NULL) {
m_events->removeHandler(Event::kTimer, m_fixTimer);
m_events->deleteTimer(m_fixTimer);
m_fixTimer = NULL;
}
m_isOnScreen = m_isPrimary;
forceShowCursor();
}
void MSWindowsScreen::enter()
{
m_desks->enter();
if (m_isPrimary) {
// enable special key sequences on win95 family
enableSpecialKeys(true);
// watch jump zones
m_hook.setMode(kHOOK_WATCH_JUMP_ZONE);
// all messages prior to now are invalid
nextMark();
m_primaryKeyDownList.clear();
} else {
// Entering a secondary screen. Ensure that no screensaver is active
// and that the screen is not in powersave mode.
ArchMiscWindows::wakeupDisplay();
if (m_screensaver != NULL && m_screensaverActive) {
m_screensaver->deactivate();
m_screensaverActive = 0;
}
}
// now on screen
m_isOnScreen = true;
forceShowCursor();
}
bool MSWindowsScreen::canLeave()
{
POINT pos;
if (!getThisCursorPos(&pos)) {
LOG((CLOG_DEBUG "unable to leave screen as windows security has disabled "
"critical functions"));
// unable to get position this means deskflow will break if the cursor
// leaves the screen
return false;
}
return true;
}
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();
// tell the key mapper about the keyboard layout
m_keyState->setKeyLayout(m_keyLayout);
// tell desk that we're leaving and tell it the keyboard layout
m_desks->leave(m_keyLayout);
if (m_isPrimary) {
// warp to center
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
enableSpecialKeys(false);
// all messages prior to now are invalid
nextMark();
// remember the modifier state. this is the modifier state
// reflected in the internal keyboard state.
m_keyState->saveModifiers();
m_hook.setMode(kHOOK_RELAY_EVENTS);
m_primaryKeyDownList.clear();
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));
}
}
}
// now off screen
m_isOnScreen = false;
forceShowCursor();
if (isDraggingStarted() && !m_isPrimary) {
m_sendDragThread = new Thread(new TMethodJob<MSWindowsScreen>(this, &MSWindowsScreen::sendDragThread));
}
}
void MSWindowsScreen::sendDragThread(void *)
{
String &draggingFilename = getDraggingFilename();
size_t size = draggingFilename.size();
if (draggingFilename.empty() == false) {
ClientApp &app = ClientApp::instance();
Client *client = app.getClientPtr();
UInt32 fileCount = 1;
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());
}
m_draggingStarted = false;
}
bool MSWindowsScreen::setClipboard(ClipboardID, const IClipboard *src)
{
MSWindowsClipboard dst(m_window);
if (src != NULL) {
// save clipboard data
return Clipboard::copy(&dst, src);
} else {
// assert clipboard ownership
if (!dst.open(0)) {
return false;
}
dst.empty();
dst.close();
return true;
}
}
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.
//
// this works around bugs in the clipboard viewer chain.
// sometimes NT will simply never send WM_DRAWCLIPBOARD
// messages for no apparent reason and rebooting fixes the
// problem. since we don't want a broken clipboard until the
// next reboot we do this double check. clipboard ownership
// 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"));
m_ownClipboard = false;
sendClipboardEvent(m_events->forClipboard().clipboardGrabbed(), kClipboardClipboard);
sendClipboardEvent(m_events->forClipboard().clipboardGrabbed(), kClipboardSelection);
}
}
void MSWindowsScreen::openScreensaver(bool notify)
{
assert(m_screensaver != NULL);
m_screensaverNotify = notify;
if (m_screensaverNotify) {
m_desks->installScreensaverHooks(true);
} else if (m_screensaver) {
m_screensaver->disable();
}
}
void MSWindowsScreen::closeScreensaver()
{
if (m_screensaver != NULL) {
if (m_screensaverNotify) {
m_desks->installScreensaverHooks(false);
} else {
m_screensaver->enable();
}
}
m_screensaverNotify = false;
}
void MSWindowsScreen::screensaver(bool activate)
{
assert(m_screensaver != NULL);
if (m_screensaver == NULL)
return;
if (activate) {
m_screensaver->activate();
} else {
m_screensaver->deactivate();
}
}
void MSWindowsScreen::resetOptions()
{
m_desks->resetOptions();
}
void MSWindowsScreen::setOptions(const OptionsList &options)
{
m_desks->setOptions(options);
}
void MSWindowsScreen::setSequenceNumber(UInt32 seqNum)
{
m_sequenceNumber = seqNum;
}
bool MSWindowsScreen::isPrimary() const
{
return m_isPrimary;
}
void *MSWindowsScreen::getEventTarget() const
{
return const_cast<MSWindowsScreen *>(this);
}
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
{
assert(m_class != 0);
x = m_x;
y = m_y;
w = m_w;
h = m_h;
}
void MSWindowsScreen::getCursorPos(SInt32 &x, SInt32 &y) const
{
m_desks->getCursorPos(x, y);
}
/*
* getThisCursorPos and setThisCursorPos will attempt to negotiate with the
* system to try get the and set the mouse position, however on the logon screen
* due to hooks this process has it may unable to work around the problem.
* Although these functions did not fix the issue at hand (#5294) its worth
* keeping them here anyway.
*/
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));
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));
updateDesktopThread();
}
return result;
}
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));
if (!result) {
result = SetCursorPos(x, y);
error = GetLastError();
LOG((CLOG_DEBUG3 "%s Attempt: 2, status %d, code: %d", __func__, result, error));
updateDesktopThread();
}
return result;
}
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);
auto error = GetLastError();
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()));
CloseDesktop(cur_hdesk);
}
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)
{
// 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)) {
// do nothing
}
// save position to compute delta of next motion
saveMousePosition(x, 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)
{
// only allow certain modifiers
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));
return 0;
}
// fail if no keys
if (key == kKeyNone && mask == 0) {
return 0;
}
// convert to win32
UINT modifiers = 0;
if ((mask & KeyModifierShift) != 0) {
modifiers |= MOD_SHIFT;
}
if ((mask & KeyModifierControl) != 0) {
modifiers |= MOD_CONTROL;
}
if ((mask & KeyModifierAlt) != 0) {
modifiers |= MOD_ALT;
}
if ((mask & KeyModifierSuper) != 0) {
modifiers |= MOD_WIN;
}
UINT vk = m_keyState->mapKeyToVirtualKey(key);
if (key != kKeyNone && vk == 0) {
// can't map key
// 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));
return 0;
}
// choose hotkey id
UInt32 id;
if (!m_oldHotKeyIDs.empty()) {
id = m_oldHotKeyIDs.back();
m_oldHotKeyIDs.pop_back();
} else {
// id = m_hotKeys.size() + 1;
id = (UInt32)m_hotKeys.size() + 1;
}
// if this hot key has modifiers only then we'll handle it specially
bool err;
if (key == kKeyNone) {
// check if already registered
err = (m_hotKeyToIDMap.count(HotKeyItem(vk, modifiers)) > 0);
} else {
// register with OS
err = (RegisterHotKey(NULL, id, modifiers, vk) == 0);
}
if (!err) {
m_hotKeys.insert(std::make_pair(id, HotKeyItem(vk, modifiers)));
m_hotKeyToIDMap[HotKeyItem(vk, modifiers)] = id;
} else {
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)
);
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)
);
return id;
}
void MSWindowsScreen::unregisterHotKey(UInt32 id)
{
// look up hotkey
HotKeyMap::iterator i = m_hotKeys.find(id);
if (i == m_hotKeys.end()) {
return;
}
// unregister with OS
bool err;
if (i->second.getVirtualKey() != 0) {
err = !UnregisterHotKey(NULL, id);
} else {
err = false;
}
if (err) {
LOG((CLOG_WARN "failed to unregister hotkey id=%d", id));
} else {
LOG((CLOG_DEBUG "unregistered hotkey id=%d", id));
}
// discard hot key from map and record old id for reuse
m_hotKeyToIDMap.erase(i->second);
m_hotKeys.erase(i);
m_oldHotKeyIDs.push_back(id);
}
void MSWindowsScreen::fakeInputBegin()
{
assert(m_isPrimary);
if (!m_isOnScreen) {
m_keyState->useSavedModifiers(true);
}
m_desks->fakeInputBegin();
}
void MSWindowsScreen::fakeInputEnd()
{
assert(m_isPrimary);
m_desks->fakeInputEnd();
if (!m_isOnScreen) {
m_keyState->useSavedModifiers(false);
}
}
SInt32 MSWindowsScreen::getJumpZoneSize() const
{
return 1;
}
bool MSWindowsScreen::isAnyMouseButtonDown(UInt32 &buttonID) const
{
static const char *buttonToName[] = {"<invalid>", "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]) {
buttonID = i;
LOG((CLOG_DEBUG "locked by \"%s\"", buttonToName[i]));
return true;
}
}
return false;
}
void MSWindowsScreen::getCursorCenter(SInt32 &x, SInt32 &y) const
{
x = m_xCenter;
y = m_yCenter;
}
void MSWindowsScreen::fakeMouseButton(ButtonID id, bool press)
{
m_desks->fakeMouseButton(id, press);
if (id == kButtonLeft) {
if (press) {
m_buttons[kButtonLeft] = true;
} else {
m_buttons[kButtonLeft] = false;
m_fakeDraggingStarted = false;
m_draggingStarted = false;
}
}
}
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
{
m_desks->fakeMouseRelativeMove(dx, dy);
}
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::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 result = PlatformScreen::fakeKeyRepeat(id, mask, count, button, lang);
updateForceShowCursor();
return result;
}
bool MSWindowsScreen::fakeKeyUp(KeyButton button)
{
bool result = PlatformScreen::fakeKeyUp(button);
updateForceShowCursor();
return result;
}
void MSWindowsScreen::fakeAllKeysUp()
{
PlatformScreen::fakeAllKeysUp();
updateForceShowCursor();
}
HCURSOR
MSWindowsScreen::createBlankCursor() const
{
// create a transparent cursor
int cw = GetSystemMetrics(SM_CXCURSOR);
int ch = GetSystemMetrics(SM_CYCURSOR);
UInt8 *cursorAND = new UInt8[ch * ((cw + 31) >> 2)];
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);
delete[] cursorXOR;
delete[] cursorAND;
return c;
}
void MSWindowsScreen::destroyCursor(HCURSOR cursor) const
{
if (cursor != NULL) {
DestroyCursor(cursor);
}
}
ATOM MSWindowsScreen::createWindowClass() const
{
WNDCLASSEX classInfo;
classInfo.cbSize = sizeof(classInfo);
classInfo.style = CS_DBLCLKS | CS_NOCLOSE;
classInfo.lpfnWndProc = &MSWindowsScreen::wndProc;
classInfo.cbClsExtra = 0;
classInfo.cbWndExtra = 0;
classInfo.hInstance = s_windowInstance;
classInfo.hIcon = NULL;
classInfo.hCursor = NULL;
classInfo.hbrBackground = NULL;
classInfo.lpszMenuName = NULL;
classInfo.lpszClassName = kAppName;
classInfo.hIconSm = NULL;
return RegisterClassEx(&classInfo);
}
void MSWindowsScreen::destroyClass(ATOM windowClass) const
{
if (windowClass != 0) {
UnregisterClass(MAKEINTATOM(windowClass), s_windowInstance);
}
}
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
);
if (window == NULL) {
LOG((CLOG_ERR "failed to create window: %d", GetLastError()));
throw XScreenOpenFailure();
}
return window;
}
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
);
if (window == NULL) {
LOG((CLOG_ERR "failed to create drop window: %d", GetLastError()));
throw XScreenOpenFailure();
}
return window;
}
void MSWindowsScreen::destroyWindow(HWND hwnd) const
{
if (hwnd != NULL) {
DestroyWindow(hwnd);
}
}
void MSWindowsScreen::sendEvent(Event::Type type, void *data)
{
m_events->addEvent(Event(type, getEventTarget(), data));
}
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__));
return;
}
info->m_id = id;
info->m_sequenceNumber = m_sequenceNumber;
sendEvent(type, info);
}
void MSWindowsScreen::handleSystemEvent(const Event &event, void *)
{
MSG *msg = static_cast<MSG *>(event.getData());
assert(msg != NULL);
if (ArchMiscWindows::processDialog(msg)) {
return;
}
if (onPreDispatch(msg->hwnd, msg->message, msg->wParam, msg->lParam)) {
return;
}
TranslateMessage(msg);
DispatchMessage(msg);
}
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);
}
IKeyState *MSWindowsScreen::getKeyState() const
{
return m_keyState;
}
bool MSWindowsScreen::onPreDispatch(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam)
{
// handle event
switch (message) {
case DESKFLOW_MSG_SCREEN_SAVER:
return onScreensaver(wParam != 0);
case DESKFLOW_MSG_DEBUG:
LOG((CLOG_DEBUG1 "hook: 0x%08x 0x%08x", wParam, lParam));
return true;
}
if (m_isPrimary) {
return onPreDispatchPrimary(hwnd, message, wParam, lParam);
}
return false;
}
bool MSWindowsScreen::onPreDispatchPrimary(HWND, UINT message, WPARAM wParam, LPARAM lParam)
{
LOG((CLOG_DEBUG5 "handling pre-dispatch primary"));
// handle event
switch (message) {
case DESKFLOW_MSG_MARK:
return onMark(static_cast<UInt32>(wParam));
case DESKFLOW_MSG_KEY:
return onKey(wParam, lParam);
case DESKFLOW_MSG_MOUSE_BUTTON:
return onMouseButton(wParam, lParam);
case DESKFLOW_MSG_MOUSE_MOVE:
return onMouseMove(static_cast<SInt32>(wParam), static_cast<SInt32>(lParam));
case DESKFLOW_MSG_MOUSE_WHEEL:
// XXX -- support x-axis scrolling
return onMouseWheel(0, static_cast<SInt32>(wParam));
case DESKFLOW_MSG_PRE_WARP: {
// save position to compute delta of next motion
saveMousePosition(static_cast<SInt32>(wParam), static_cast<SInt32>(lParam));
// we warped the mouse. discard events until we find the
// matching post warp event. see warpCursorNoFlush() for
// where the events are sent. we discard the matching
// post warp event and can be sure we've skipped the warp
// event.
MSG msg;
do {
GetMessage(&msg, NULL, DESKFLOW_MSG_MOUSE_MOVE, DESKFLOW_MSG_POST_WARP);
} while (msg.message != DESKFLOW_MSG_POST_WARP);
}
return true;
case DESKFLOW_MSG_POST_WARP:
LOG((CLOG_WARN "unmatched post warp"));
return true;
case WM_HOTKEY:
// we discard these messages. we'll catch the hot key in the
// regular key event handling, where we can detect both key
// press and release. we only register the hot key so no other
// app will act on the key combination.
break;
}
return false;
}
bool MSWindowsScreen::onEvent(HWND, UINT msg, WPARAM wParam, LPARAM lParam, LRESULT *result)
{
switch (msg) {
case WM_DRAWCLIPBOARD:
// first pass on the message
if (m_nextClipboardWindow != NULL) {
SendMessage(m_nextClipboardWindow, msg, wParam, lParam);
}
// now handle the message
return onClipboardChange();
case WM_CHANGECBCHAIN:
if (m_nextClipboardWindow == (HWND)wParam) {
m_nextClipboardWindow = (HWND)lParam;
LOG((CLOG_DEBUG "clipboard chain: new next: 0x%08x", m_nextClipboardWindow));
} else if (m_nextClipboardWindow != NULL) {
SendMessage(m_nextClipboardWindow, msg, wParam, lParam);
}
return true;
case WM_DISPLAYCHANGE:
return onDisplayChange();
/* 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));
break;
case WM_POWERBROADCAST:
switch (wParam) {
case PBT_APMRESUMEAUTOMATIC:
case PBT_APMRESUMECRITICAL:
case PBT_APMRESUMESUSPEND:
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));
break;
}
*result = TRUE;
return true;
case WM_DEVICECHANGE:
forceShowCursor();
break;
case WM_SETTINGCHANGE:
if (wParam == SPI_SETMOUSEKEYS) {
forceShowCursor();
}
break;
}
return false;
}
bool MSWindowsScreen::onMark(UInt32 mark)
{
m_markReceived = mark;
return true;
}
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)
);
// get event info
KeyButton button = (KeyButton)((lParam & 0x01ff0000) >> 16);
bool down = ((lParam & 0x80000000u) == 0x00000000u);
bool wasDown = isKeyDown(button);
KeyModifierMask oldState = pollActiveModifiers();
// check for autorepeat
if (m_keyState->testAutoRepeat(down, (lParam & 0x40000000u), button)) {
lParam |= 0x40000000u;
}
// if the button is zero then guess what the button should be.
// these are badly synthesized key events and logitech software
// that maps mouse buttons to keys is known to do this.
// alternatively, we could just throw these events out.
if (button == 0) {
button = m_keyState->virtualKeyToButton((wParam >> 16) & 0xffu);
if (button == 0) {
return true;
}
wasDown = isKeyDown(button);
}
// record keyboard state
m_keyState->onKey(button, down, oldState);
if (!down && m_isPrimary && !m_isOnScreen) {
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);
fakeLocalKey(*find, false);
m_primaryKeyDownList.erase(find);
m_hook.setMode(kHOOK_RELAY_EVENTS);
return true;
}
}
// windows doesn't tell us the modifier key state on mouse or key
// events so we have to figure it out. most apps would use
// GetKeyState() or even GetAsyncKeyState() for that but we can't
// because our hook doesn't pass on key events for several modifiers.
// it can't otherwise the system would interpret them normally on
// the primary screen even when on a secondary screen. so tapping
// alt would activate menus and tapping the windows key would open
// the start menu. if you don't pass those events on in the hook
// then GetKeyState() understandably doesn't reflect the effect of
// the event. curiously, neither does GetAsyncKeyState(), which is
// surprising.
//
// so anyway, we have to track the modifier state ourselves for
// at least those modifiers we don't pass on. pollActiveModifiers()
// does that but we have to update the keyboard state before calling
// pollActiveModifiers() to get the right answer. but the only way
// to set the modifier state or to set the up/down state of a key
// is via onKey(). so we have to call onKey() twice.
KeyModifierMask state = pollActiveModifiers();
m_keyState->onKey(button, down, state);
// check for hot keys
if (oldState != state) {
// modifier key was pressed/released
if (onHotKey(0, lParam)) {
return true;
}
} else {
// non-modifier was pressed/released
if (onHotKey(wParam, lParam)) {
return true;
}
}
// stop sending modifier keys over and over again
if (isModifierRepeat(oldState, state, wParam)) {
return true;
}
// ignore message if posted prior to last mark change
if (!ignore()) {
// check for ctrl+alt+del. we do not want to pass that to the
// client. the user can use ctrl+alt+pause to emulate it.
UINT virtKey = ((wParam >> 16) & 0xffu);
if (virtKey == VK_DELETE && (state & s_ctrlAlt) == s_ctrlAlt) {
LOG((CLOG_DEBUG "discard ctrl+alt+del"));
return true;
}
// check for ctrl+alt+del emulation
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
// we not use AltGr (the 0x10000 flag in wParam) and we not
// use the keypad delete key (the 0x01000000 flag in lParam).
wParam = (VK_DELETE << 16) | 0x01000000u;
lParam &= 0xfe000000;
lParam |= m_keyState->virtualKeyToButton(VK_DELETE) << 16;
lParam |= 0x01000001;
}
// process key
KeyModifierMask mask;
KeyID key = m_keyState->mapKeyFromEvent(wParam, lParam, &mask);
button = static_cast<KeyButton>((lParam & 0x01ff0000u) >> 16);
if (key != kKeyNone) {
// do it
m_keyState->sendKeyEvent(
getEventTarget(), ((lParam & 0x80000000u) == 0), ((lParam & 0x40000000u) != 0), key, mask,
(SInt32)(lParam & 0xffff), button
);
} else {
LOG((CLOG_DEBUG1 "cannot map key"));
}
}
return true;
}
bool MSWindowsScreen::onHotKey(WPARAM wParam, LPARAM lParam)
{
// get the key info
KeyModifierMask state = getActiveModifiers();
UINT virtKey = ((wParam >> 16) & 0xffu);
UINT modifiers = 0;
if ((state & KeyModifierShift) != 0) {
modifiers |= MOD_SHIFT;
}
if ((state & KeyModifierControl) != 0) {
modifiers |= MOD_CONTROL;
}
if ((state & KeyModifierAlt) != 0) {
modifiers |= MOD_ALT;
}
if ((state & KeyModifierSuper) != 0) {
modifiers |= MOD_WIN;
}
// find the hot key id
HotKeyToIDMap::const_iterator i = m_hotKeyToIDMap.find(HotKeyItem(virtKey, modifiers));
if (i == m_hotKeyToIDMap.end()) {
return false;
}
// find what kind of event
Event::Type type;
if ((lParam & 0x80000000u) == 0u) {
if ((lParam & 0x40000000u) != 0u) {
// ignore key repeats but it counts as a hot key
return true;
}
type = m_events->forIPrimaryScreen().hotKeyDown();
} else {
type = m_events->forIPrimaryScreen().hotKeyUp();
}
// generate event
m_events->addEvent(Event(type, getEventTarget(), HotKeyInfo::alloc(i->second)));
return true;
}
bool MSWindowsScreen::onMouseButton(WPARAM wParam, LPARAM lParam)
{
// get which button
bool pressed = mapPressFromEvent(wParam, lParam);
ButtonID button = mapButtonFromEvent(wParam, lParam);
// keep our shadow key state up to date
if (button >= kButtonLeft && button <= kButtonExtra0 + 1) {
if (pressed) {
m_buttons[button] = true;
if (button == kButtonLeft) {
m_draggingFilename.clear();
LOG((CLOG_DEBUG2 "dragging filename is cleared"));
}
} else {
m_buttons[button] = false;
if (m_draggingStarted && button == kButtonLeft) {
m_draggingStarted = false;
}
}
}
// ignore message if posted prior to last mark change
if (!ignore()) {
KeyModifierMask mask = m_keyState->getActiveModifiers();
if (pressed) {
LOG((CLOG_DEBUG1 "event: button press button=%d", button));
if (button != kButtonNone) {
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));
}
}
}
return true;
}
// here's how mouse movements are sent across the network to a client:
// 1. deskflow checks the mouse position on server screen
// 2. records the delta (current x,y minus last x,y)
// 3. records the current x,y as "last" (so we can calc delta next time)
// 4. on the server, puts the cursor back to the center of the screen
// - remember the cursor is hidden on the server at this point
// - this actually records the current x,y as "last" a second time (it
// 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)
{
// 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));
// ignore if the mouse didn't move or if message posted prior
// to last mark change.
if (ignore() || (x == 0 && y == 0)) {
return true;
}
// save position to compute delta of next motion
saveMousePosition(mx, my);
if (m_isOnScreen) {
// motion on primary screen
sendEvent(m_events->forIPrimaryScreen().motionOnPrimary(), MotionInfo::alloc(m_xCursor, m_yCursor));
if (m_buttons[kButtonLeft] == true && m_draggingStarted == false) {
m_draggingStarted = true;
}
} else {
// the motion is on the secondary screen, so we warp mouse back to
// 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));
warpCursorNoFlush(m_xCenter, m_yCenter);
// examine the motion. if it's about the distance
// from the center of the screen to an edge then
// it's probably a bogus motion that we want to
// 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) {
LOG((CLOG_DEBUG "dropped bogus delta motion: %+d,%+d", x, y));
} else {
// send motion
sendEvent(m_events->forIPrimaryScreen().motionOnSecondary(), MotionInfo::alloc(x, y));
}
}
return true;
}
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));
}
return true;
}
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
// can't respond to events at full CPU speed and will fall
// behind if a lot of screen saver events are generated.
// that can easily happen because windows will continually
// 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)) {
return true;
}
if (activated) {
if (!m_screensaverActive && m_screensaver->checkStarted(DESKFLOW_MSG_SCREEN_SAVER, FALSE, 0)) {
m_screensaverActive = true;
sendEvent(m_events->forIPrimaryScreen().screensaverActivated());
}
} else {
if (m_screensaverActive) {
m_screensaverActive = false;
sendEvent(m_events->forIPrimaryScreen().screensaverDeactivated());
}
}
return true;
}
bool MSWindowsScreen::onDisplayChange()
{
// screen resolution may have changed. save old shape.
SInt32 xOld = m_x, yOld = m_y, wOld = m_w, hOld = m_h;
// update shape
updateScreenShape();
// do nothing if resolution hasn't changed
if (xOld != m_x || yOld != m_y || wOld != m_w || hOld != m_h) {
if (m_isPrimary) {
// warp mouse to center if off screen
if (!m_isOnScreen) {
LOG((CLOG_DEBUG1 "warping cursor to center: %+d, %+d", m_xCenter, m_yCenter));
warpCursor(m_xCenter, m_yCenter);
}
// tell hook about resize if on screen
else {
m_hook.setZone(m_x, m_y, m_w, m_h, getJumpZoneSize());
}
}
// 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)" : ""));
}
return true;
}
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);
}
} else if (!m_ownClipboard) {
LOG((CLOG_DEBUG "clipboard changed: %s owned", kAppId));
m_ownClipboard = true;
}
return true;
}
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);
// warp mouse. hopefully this inserts a mouse motion event
// between the previous message and the following message.
setThisCursorPos(x, y);
// check to see if the mouse pos was set correctly
POINT cursorPos;
getThisCursorPos(&cursorPos);
// there is a bug or round error in SetCursorPos and GetCursorPos on
// a high DPI setting. The check here is for Vista/7 login screen.
// 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));
// 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
// an annoying side effect; instead of the mouse returning to the correct
// exit point, it returns to the center of the screen. this could have
// something to do with the center screen warping technique used (see
// comments for onMouseMove definition).
fakeMouseMove(x, y);
}
}
// yield the CPU. there's a race condition when warping:
// a hardware mouse event occurs
// the mouse hook is not called because that process doesn't have the CPU
// we send PRE_WARP, SetCursorPos(), send POST_WARP
// we process all of those events and update m_x, m_y
// we finish our time slice
// the hook is called
// the hook sends us a mouse event from the pre-warp position
// we get the CPU
// we compute a bogus warp
// we need the hook to process all mouse events that occur
// before we warp before we do the warp but i'm not sure how
// to guarantee that. yielding the CPU here may reduce the
// chance of undesired behavior. we'll also check for very
// large motions that look suspiciously like about half width
// or height of the screen.
ARCH->sleep(0.0);
// send an event that we can recognize after the mouse warp
PostThreadMessage(GetCurrentThreadId(), DESKFLOW_MSG_POST_WARP, 0, 0);
}
void MSWindowsScreen::nextMark()
{
// next mark
++m_mark;
// mark point in message queue where the mark was changed
PostThreadMessage(GetCurrentThreadId(), DESKFLOW_MSG_MARK, m_mark, 0);
}
bool MSWindowsScreen::ignore() const
{
return (m_mark != m_markReceived);
}
void MSWindowsScreen::updateScreenShape()
{
// get shape and center
m_w = GetSystemMetrics(SM_CXVIRTUALSCREEN);
m_h = GetSystemMetrics(SM_CYVIRTUALSCREEN);
m_x = GetSystemMetrics(SM_XVIRTUALSCREEN);
m_y = GetSystemMetrics(SM_YVIRTUALSCREEN);
m_xCenter = GetSystemMetrics(SM_CXSCREEN) >> 1;
m_yCenter = GetSystemMetrics(SM_CYSCREEN) >> 1;
// check for multiple monitors
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 *)
{
// fix clipboard chain
fixClipboardViewer();
// update keys if keyboard layouts have changed
if (m_keyState->didGroupsChange()) {
updateKeys();
}
}
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
// forwards the message to our window or a window farther up the chain.
// i'm not sure how that could happen. the m_nextClipboardWindow = NULL
// was not in the code that infinite loops and may fix the bug but i
// doubt it.
/*
ChangeClipboardChain(m_window, m_nextClipboardWindow);
m_nextClipboardWindow = NULL;
m_nextClipboardWindow = SetClipboardViewer(m_window);
*/
}
void MSWindowsScreen::enableSpecialKeys(bool enable) const
{
}
ButtonID MSWindowsScreen::mapButtonFromEvent(WPARAM msg, LPARAM button) const
{
switch (msg) {
case WM_LBUTTONDOWN:
case WM_LBUTTONDBLCLK:
case WM_LBUTTONUP:
case WM_NCLBUTTONDOWN:
case WM_NCLBUTTONDBLCLK:
case WM_NCLBUTTONUP:
return kButtonLeft;
case WM_MBUTTONDOWN:
case WM_MBUTTONDBLCLK:
case WM_MBUTTONUP:
case WM_NCMBUTTONDOWN:
case WM_NCMBUTTONDBLCLK:
case WM_NCMBUTTONUP:
return kButtonMiddle;
case WM_RBUTTONDOWN:
case WM_RBUTTONDBLCLK:
case WM_RBUTTONUP:
case WM_NCRBUTTONDOWN:
case WM_NCRBUTTONDBLCLK:
case WM_NCRBUTTONUP:
return kButtonRight;
case WM_XBUTTONDOWN:
case WM_XBUTTONDBLCLK:
case WM_XBUTTONUP:
case WM_NCXBUTTONDOWN:
case WM_NCXBUTTONDBLCLK:
case WM_NCXBUTTONUP:
switch (button) {
case XBUTTON1:
if (GetSystemMetrics(SM_CMOUSEBUTTONS) >= 4) {
return kButtonExtra0 + 0;
}
break;
case XBUTTON2:
if (GetSystemMetrics(SM_CMOUSEBUTTONS) >= 5) {
return kButtonExtra0 + 1;
}
break;
}
return kButtonNone;
default:
return kButtonNone;
}
}
bool MSWindowsScreen::mapPressFromEvent(WPARAM msg, LPARAM) const
{
switch (msg) {
case WM_LBUTTONDOWN:
case WM_MBUTTONDOWN:
case WM_RBUTTONDOWN:
case WM_XBUTTONDOWN:
case WM_LBUTTONDBLCLK:
case WM_MBUTTONDBLCLK:
case WM_RBUTTONDBLCLK:
case WM_XBUTTONDBLCLK:
case WM_NCLBUTTONDOWN:
case WM_NCMBUTTONDOWN:
case WM_NCRBUTTONDOWN:
case WM_NCXBUTTONDOWN:
case WM_NCLBUTTONDBLCLK:
case WM_NCMBUTTONDBLCLK:
case WM_NCRBUTTONDBLCLK:
case WM_NCXBUTTONDBLCLK:
return true;
case WM_LBUTTONUP:
case WM_MBUTTONUP:
case WM_RBUTTONUP:
case WM_XBUTTONUP:
case WM_NCLBUTTONUP:
case WM_NCMBUTTONUP:
case WM_NCRBUTTONUP:
case WM_NCXBUTTONUP:
return false;
default:
return false;
}
}
void MSWindowsScreen::updateKeysCB(void *)
{
// record which keys we think are down
bool down[IKeyState::kNumButtons];
bool sendFixes = (isPrimary() && !m_isOnScreen);
if (sendFixes) {
for (KeyButton i = 0; i < IKeyState::kNumButtons; ++i) {
down[i] = m_keyState->isKeyDown(i);
}
}
// update layouts if necessary
if (m_keyState->didGroupsChange()) {
PlatformScreen::updateKeyMap();
}
// now update the keyboard state
PlatformScreen::updateKeyState();
// now see which keys we thought were down but now think are up.
// send key releases for these keys to the active client.
if (sendFixes) {
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);
}
}
}
}
void MSWindowsScreen::forceShowCursor()
{
// check for mouse
m_hasMouse = (GetSystemMetrics(SM_MOUSEPRESENT) != 0);
// decide if we should show the mouse
bool showMouse = (!m_hasMouse && !m_isPrimary && m_isOnScreen);
// show/hide the mouse
if (showMouse != m_showingMouse) {
if (showMouse) {
m_oldMouseKeys.cbSize = sizeof(m_oldMouseKeys);
m_gotOldMouseKeys = (SystemParametersInfo(SPI_GETMOUSEKEYS, m_oldMouseKeys.cbSize, &m_oldMouseKeys, 0) != 0);
if (m_gotOldMouseKeys) {
m_mouseKeys = m_oldMouseKeys;
m_showingMouse = true;
updateForceShowCursor();
}
} else {
if (m_gotOldMouseKeys) {
SystemParametersInfo(SPI_SETMOUSEKEYS, m_oldMouseKeys.cbSize, &m_oldMouseKeys, SPIF_SENDCHANGE);
m_showingMouse = false;
}
}
}
}
void MSWindowsScreen::updateForceShowCursor()
{
DWORD oldFlags = m_mouseKeys.dwFlags;
// turn on MouseKeys
m_mouseKeys.dwFlags = MKF_AVAILABLE | MKF_MOUSEKEYSON;
// make sure MouseKeys is active in whatever state the NumLock is
// not currently in.
if ((m_keyState->getActiveModifiers() & KeyModifierNumLock) != 0) {
m_mouseKeys.dwFlags |= MKF_REPLACENUMBERS;
}
// update MouseKeys
if (oldFlags != m_mouseKeys.dwFlags) {
SystemParametersInfo(SPI_SETMOUSEKEYS, m_mouseKeys.cbSize, &m_mouseKeys, SPIF_SENDCHANGE);
}
}
LRESULT CALLBACK MSWindowsScreen::wndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
assert(s_screen != NULL);
LRESULT result = 0;
if (!s_screen->onEvent(hwnd, msg, wParam, lParam, &result)) {
result = DefWindowProc(hwnd, msg, wParam, lParam);
}
return result;
}
void MSWindowsScreen::fakeLocalKey(KeyButton button, bool press) const
{
INPUT input;
input.type = INPUT_KEYBOARD;
input.ki.wVk = m_keyState->mapButtonToVirtualKey(button);
DWORD pressFlag = press ? KEYEVENTF_EXTENDEDKEY : KEYEVENTF_KEYUP;
input.ki.dwFlags = pressFlag;
input.ki.time = 0;
input.ki.dwExtraInfo = 0;
SendInput(1, &input, sizeof(input));
}
//
// MSWindowsScreen::HotKeyItem
//
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));
}
void MSWindowsScreen::fakeDraggingFiles(DragFileList fileList)
{
// possible design flaw: this function stops a "not implemented"
// exception from being thrown.
}
String &MSWindowsScreen::getDraggingFilename()
{
if (m_draggingStarted) {
m_dropTarget->clearDraggingFilename();
m_draggingFilename.clear();
int halfSize = m_dropWindowSize / 2;
SInt32 xPos = m_isPrimary ? m_xCursor : m_xCenter;
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);
// TODO: fake these keys properly
fakeKeyDown(kKeyEscape, 8192, 1, AppUtil::instance().getCurrentLanguageCode());
fakeKeyUp(1);
fakeMouseButton(kButtonLeft, false);
String filename;
DOUBLE timeout = ARCH->time() + .5f;
while (ARCH->time() < timeout) {
ARCH->sleep(.05f);
filename = m_dropTarget->getDraggingFilename();
if (!filename.empty()) {
break;
}
}
ShowWindow(m_dropWindow, SW_HIDE);
if (!filename.empty()) {
if (DragInformation::isFileValid(filename)) {
m_draggingFilename = filename;
} else {
LOG((CLOG_DEBUG "drag file name is invalid: %s", filename.c_str()));
}
}
if (m_draggingFilename.empty()) {
LOG((CLOG_DEBUG "failed to get drag file name from OLE"));
}
}
return m_draggingFilename;
}
const String &MSWindowsScreen::getDropTarget() const
{
return m_desktopPath;
}
String MSWindowsScreen::getSecureInputApp() const
{
// ignore on Windows
return "";
}
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)) {
result = true;
}
if ((state & KeyModifierControl) != 0 && (virtKey == VK_LCONTROL || virtKey == VK_RCONTROL)) {
result = true;
}
if ((state & KeyModifierAlt) != 0 && (virtKey == VK_LMENU || virtKey == VK_RMENU)) {
result = true;
}
if ((state & KeyModifierSuper) != 0 && (virtKey == VK_LWIN || virtKey == VK_RWIN)) {
result = true;
}
}
return result;
}
| 53,365
|
C++
|
.cpp
| 1,593
| 29.778406
| 119
| 0.698179
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,588
|
MSWindowsClipboardTextConverter.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsClipboardTextConverter.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/MSWindowsClipboardTextConverter.h"
#include "base/Unicode.h"
//
// MSWindowsClipboardTextConverter
//
MSWindowsClipboardTextConverter::MSWindowsClipboardTextConverter()
{
// do nothing
}
MSWindowsClipboardTextConverter::~MSWindowsClipboardTextConverter()
{
// do nothing
}
UINT MSWindowsClipboardTextConverter::getWin32Format() const
{
return CF_TEXT;
}
String MSWindowsClipboardTextConverter::doFromIClipboard(const String &data) const
{
// convert and add nul terminator
return Unicode::UTF8ToText(data) += '\0';
}
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');
if (n != String::npos) {
dst.erase(n);
}
return dst;
}
| 1,564
|
C++
|
.cpp
| 49
| 29.897959
| 82
| 0.774386
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,589
|
OSXClipboardUTF16Converter.cpp
|
deskflow_deskflow/src/lib/platform/OSXClipboardUTF16Converter.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2004 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/OSXClipboardUTF16Converter.h"
#include "base/Unicode.h"
//
// OSXClipboardUTF16Converter
//
OSXClipboardUTF16Converter::OSXClipboardUTF16Converter()
{
// do nothing
}
OSXClipboardUTF16Converter::~OSXClipboardUTF16Converter()
{
// do nothing
}
CFStringRef OSXClipboardUTF16Converter::getOSXFormat() const
{
return CFSTR("public.utf16-plain-text");
}
String OSXClipboardUTF16Converter::doFromIClipboard(const String &data) const
{
// convert and add nul terminator
return Unicode::UTF8ToUTF16(data);
}
String OSXClipboardUTF16Converter::doToIClipboard(const String &data) const
{
// convert and strip nul terminator
return Unicode::UTF16ToUTF8(data);
}
| 1,422
|
C++
|
.cpp
| 44
| 30.454545
| 77
| 0.788321
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| true
| false
| false
| true
| false
| false
|
13,590
|
XWindowsClipboard.cpp
|
deskflow_deskflow/src/lib/platform/XWindowsClipboard.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/XWindowsClipboard.h"
#include "arch/Arch.h"
#include "base/Log.h"
#include "base/Stopwatch.h"
#include "common/basic_types.h"
#include "common/stdvector.h"
#include "platform/XWindowsClipboardBMPConverter.h"
#include "platform/XWindowsClipboardHTMLConverter.h"
#include "platform/XWindowsClipboardTextConverter.h"
#include "platform/XWindowsClipboardUCS2Converter.h"
#include "platform/XWindowsClipboardUTF8Converter.h"
#include "platform/XWindowsUtil.h"
#include <X11/Xatom.h>
#include <algorithm>
#include <cstdio>
#include <cstring>
//
// XWindowsClipboard
//
XWindowsClipboard::XWindowsClipboard(Display *display, Window window, ClipboardID id)
: m_display(display),
m_window(window),
m_id(id),
m_open(false),
m_time(0),
m_owner(false),
m_timeOwned(0),
m_timeLost(0)
{
// get some atoms
m_atomTargets = XInternAtom(m_display, "TARGETS", False);
m_atomMultiple = XInternAtom(m_display, "MULTIPLE", False);
m_atomTimestamp = XInternAtom(m_display, "TIMESTAMP", False);
m_atomInteger = XInternAtom(m_display, "INTEGER", False);
m_atomAtom = XInternAtom(m_display, "ATOM", False);
m_atomAtomPair = XInternAtom(m_display, "ATOM_PAIR", False);
m_atomData = XInternAtom(m_display, "CLIP_TEMPORARY", False);
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_atomGDKSelection = XInternAtom(m_display, "GDK_SELECTION", False);
// set selection atom based on clipboard id
switch (id) {
case kClipboardClipboard:
m_selection = XInternAtom(m_display, "CLIPBOARD", False);
break;
default:
m_selection = XA_PRIMARY;
break;
}
// 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 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"));
// we have no data
clearCache();
}
XWindowsClipboard::~XWindowsClipboard()
{
clearReplies();
clearConverters();
}
void XWindowsClipboard::lost(Time time)
{
LOG((CLOG_DEBUG "lost clipboard %d ownership at %d", m_id, time));
if (m_owner) {
m_owner = false;
m_timeLost = time;
clearCache();
}
}
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())
);
if (wasOwnedAtTime(time)) {
if (target == m_atomMultiple && property != None) {
// add a multiple request. property may not be None
// according to ICCCM.
success = insertMultipleReply(requestor, time, property);
} else {
addSimpleRequest(requestor, target, time, property);
// addSimpleRequest() will have already handled failure
success = true;
}
} else {
LOG((CLOG_DEBUG1 "failed, not owned at time %d", time));
}
}
if (!success) {
// send failure
LOG((CLOG_DEBUG1 "failed"));
insertReply(new Reply(requestor, target, time));
}
// send notifications that are pending
pushReplies();
}
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.
if (property == None) {
property = target;
}
// handle targets
String data;
Atom type = None;
int format = 0;
if (target == m_atomTargets) {
type = getTargetsData(data, &format);
} else if (target == m_atomTimestamp) {
type = getTimestampData(data, &format);
} else {
IXWindowsClipboardConverter *converter = getConverter(target);
if (converter != nullptr) {
IClipboard::EFormat clipboardFormat = converter->getFormat();
if (m_added[clipboardFormat]) {
try {
data = converter->fromIClipboard(m_data[clipboardFormat]);
format = converter->getDataSize();
type = converter->getAtom();
} catch (...) {
// ignore -- cannot convert
LOG((CLOG_WARN "error while converting clipboard data"));
}
}
}
}
if (type != None) {
// success
LOG((CLOG_DEBUG1 "success"));
insertReply(new Reply(requestor, target, time, property, data, type, format));
return true;
} else {
// failure
LOG((CLOG_DEBUG1 "failed"));
insertReply(new Reply(requestor, target, time));
return false;
}
}
bool XWindowsClipboard::processRequest(Window requestor, ::Time /*time*/, Atom property)
{
ReplyMap::iterator index = m_replies.find(requestor);
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)
);
// 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) {
Reply *reply = *index2;
if (reply->m_replied && reply->m_property == property) {
// if reply is complete then remove it and start the
// next one.
pushReplies(index, replies, index2);
return true;
}
}
return false;
}
bool XWindowsClipboard::destroyRequest(Window requestor)
{
ReplyMap::iterator index = m_replies.find(requestor);
if (index == m_replies.end()) {
// unknown requestor window
return false;
}
// destroy all replies for this window
clearReplies(index->second);
m_replies.erase(index);
// note -- we don't stop watching the window for events because
// we're called in response to the window being destroyed.
return true;
}
Window XWindowsClipboard::getWindow() const
{
return m_window;
}
Atom XWindowsClipboard::getSelection() const
{
return m_selection;
}
bool XWindowsClipboard::empty()
{
assert(m_open);
LOG((CLOG_DEBUG "empty clipboard %d", m_id));
// assert ownership of clipboard
XSetSelectionOwner(m_display, m_selection, m_window, m_time);
if (XGetSelectionOwner(m_display, m_selection) != m_window) {
LOG((CLOG_DEBUG "failed to grab clipboard %d", m_id));
return false;
}
// clear all data. since we own the data now, the cache is up
// to date.
clearCache();
m_cached = true;
// FIXME -- actually delete motif clipboard items?
// FIXME -- do anything to motif clipboard properties?
// save time
m_timeOwned = m_time;
m_timeLost = 0;
// we're the owner now
m_owner = true;
LOG((CLOG_DEBUG "grabbed clipboard %d", m_id));
return true;
}
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));
m_data[format] = data;
m_added[format] = true;
// FIXME -- set motif clipboard item?
}
bool XWindowsClipboard::open(Time time) const
{
if (m_open) {
LOG((CLOG_DEBUG "failed to open clipboard: already opened"));
return false;
}
LOG((CLOG_DEBUG "open clipboard %d", m_id));
// assume not motif
m_motif = false;
// lock clipboard
if (m_id == kClipboardClipboard) {
if (!motifLockClipboard()) {
return false;
}
// check if motif owns the selection. unlock motif clipboard
// if it does not.
m_motif = motifOwnsClipboard();
LOG((CLOG_DEBUG1 "motif does %sown clipboard", m_motif ? "" : "not "));
if (!m_motif) {
motifUnlockClipboard();
}
}
// now open
m_open = true;
m_time = time;
// be sure to flush the cache later if it's dirty
m_checkCache = true;
return true;
}
void XWindowsClipboard::close() const
{
assert(m_open);
LOG((CLOG_DEBUG "close clipboard %d", m_id));
// unlock clipboard
if (m_motif) {
motifUnlockClipboard();
}
m_motif = false;
m_open = false;
}
IClipboard::Time XWindowsClipboard::getTime() const
{
checkCache();
return m_timeOwned;
}
bool XWindowsClipboard::has(EFormat format) const
{
assert(m_open);
fillCache();
return m_added[format];
}
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) {
delete *index;
}
m_converters.clear();
}
IXWindowsClipboardConverter *XWindowsClipboard::getConverter(Atom target, bool onlyIfNotAdded) const
{
IXWindowsClipboardConverter *converter = nullptr;
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()));
return nullptr;
}
// optionally skip already handled targets
if (onlyIfNotAdded && m_added[converter->getFormat()]) {
LOG((CLOG_DEBUG1 " skipping handled format %d", converter->getFormat()));
return nullptr;
}
return converter;
}
void XWindowsClipboard::checkCache() const
{
if (!m_checkCache) {
return;
}
m_checkCache = false;
// get the time the clipboard ownership was taken by the current
// owner.
if (m_motif) {
m_timeOwned = motifGetTime();
} else {
m_timeOwned = icccmGetTime();
}
// if we can't get the time then use the time passed to us
if (m_timeOwned == 0) {
m_timeOwned = m_time;
}
// if the cache is dirty then flush it
if (m_timeOwned != m_cacheTime) {
clearCache();
}
}
void XWindowsClipboard::clearCache() const
{
const_cast<XWindowsClipboard *>(this)->doClearCache();
}
void XWindowsClipboard::doClearCache()
{
m_checkCache = false;
m_cached = false;
for (SInt32 index = 0; index < kNumFormats; ++index) {
m_data[index] = "";
m_added[index] = false;
}
}
void XWindowsClipboard::fillCache() const
{
// get the selection data if not already cached
checkCache();
if (!m_cached) {
const_cast<XWindowsClipboard *>(this)->doFillCache();
}
}
void XWindowsClipboard::doFillCache()
{
if (m_motif) {
motifFillCache();
} else {
icccmFillCache();
}
m_checkCache = false;
m_cached = true;
m_cacheTime = m_timeOwned;
}
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.
// if not then use a default list of formats. note that some clipboard
// owners are broken and report TARGETS as the type of the TARGETS data
// instead of the correct type ATOM; allow either.
const Atom atomTargets = m_atomTargets;
Atom target;
String data;
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<const Atom *>(static_cast<const void *>(data.data()));
const UInt32 numTargets = data.size() / sizeof(Atom);
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) {
IXWindowsClipboardConverter *converter = *index;
// skip already handled targets
if (m_added[converter->getFormat()]) {
continue;
}
// see if atom is in target list
Atom target = None;
// XXX -- just ask for the converter's target to see if it's
// available rather than checking TARGETS. i've seen clipboard
// owners that don't report all the targets they support.
target = converter->getAtom();
/*
for (UInt32 i = 0; i < numTargets; ++i) {
if (converter->getAtom() == targets[i]) {
target = targets[i];
break;
}
}
*/
if (target == None) {
continue;
}
// get the data
Atom actualTarget;
String targetData;
if (!icccmGetSelection(target, &actualTarget, &targetData)) {
LOG((CLOG_DEBUG1 " no data for target %s", XWindowsUtil::atomToString(m_display, target).c_str()));
continue;
}
// add to clipboard and note we've done it
IClipboard::EFormat format = converter->getFormat();
m_data[format] = converter->toIClipboard(targetData);
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")
);
}
}
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()));
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())
);
return false;
}
return true;
}
IClipboard::Time XWindowsClipboard::icccmGetTime() const
{
Atom actualTarget;
String data;
if (icccmGetSelection(m_atomTimestamp, &actualTarget, &data) && actualTarget == m_atomInteger) {
Time time = *static_cast<const Time *>(static_cast<const void *>(data.data()));
LOG((CLOG_DEBUG1 "got ICCCM time %d", time));
return time;
} else {
// no timestamp
LOG((CLOG_DEBUG1 "can't get ICCCM time"));
return 0;
}
}
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) {
LOG((CLOG_DEBUG1 "motif lock owner 0x%08x", lockOwner));
return false;
}
// try to grab the lock
// FIXME -- is this right? there's a race condition here --
// A grabs successfully, B grabs successfully, A thinks it
// still has the grab until it gets a SelectionClear.
Time time = XWindowsUtil::getCurrentTime(m_display, m_window);
XSetSelectionOwner(m_display, m_atomMotifClipLock, m_window, time);
lockOwner = XGetSelectionOwner(m_display, m_atomMotifClipLock);
if (lockOwner != m_window) {
LOG((CLOG_DEBUG1 "motif lock owner 0x%08x", lockOwner));
return false;
}
LOG((CLOG_DEBUG1 "locked motif clipboard"));
return true;
}
void XWindowsClipboard::motifUnlockClipboard() const
{
LOG((CLOG_DEBUG1 "unlocked motif clipboard"));
// fail if we don't own the lock
Window lockOwner = XGetSelectionOwner(m_display, m_atomMotifClipLock);
if (lockOwner != m_window) {
return;
}
// release lock
Time time = XWindowsUtil::getCurrentTime(m_display, m_window);
XSetSelectionOwner(m_display, m_atomMotifClipLock, None, time);
}
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
// some other client owns CLIPBOARD?
Window owner = XGetSelectionOwner(m_display, m_selection);
if (owner == None) {
return false;
}
// get the Motif clipboard header property from the root window
Atom target;
SInt32 format;
String data;
Window root = RootWindow(m_display, DefaultScreen(m_display));
if (!XWindowsUtil::getWindowProperty(m_display, root, m_atomMotifClipHeader, &data, &target, &format, False)) {
return false;
}
// check the owner window against the current clipboard owner
if (data.size() >= sizeof(MotifClipHeader)) {
MotifClipHeader header;
std::memcpy(&header, data.data(), sizeof(header));
if ((header.m_id == MotifClip::Header) && (static_cast<Window>(header.m_selectionOwner) == owner)) {
return true;
}
}
return false;
}
void XWindowsClipboard::motifFillCache()
{
LOG((CLOG_DEBUG "motif fill clipboard %d", m_id));
// get the Motif clipboard header property from the root window
Atom target;
SInt32 format;
String data;
Window root = RootWindow(m_display, DefaultScreen(m_display));
if (!XWindowsUtil::getWindowProperty(m_display, root, m_atomMotifClipHeader, &data, &target, &format, False)) {
return;
}
MotifClipHeader header;
if (data.size() < sizeof(header)) { // check that the header is okay
return;
}
std::memcpy(&header, data.data(), sizeof(header));
if (header.m_id != MotifClip::Header || header.m_numItems < 1) {
return;
}
// get the Motif item property from the root window
static const int buffer_size = 18 + 20;
char name[buffer_size];
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)) {
return;
}
MotifClipItem item;
if (data.size() < sizeof(item)) { // check that the item is okay
return;
}
std::memcpy(&item, data.data(), sizeof(item));
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<const SInt32 *>(static_cast<const void *>(item.m_size + data.data()));
// get the available formats
typedef std::map<Atom, String> MotifFormatMap;
MotifFormatMap motifFormats;
for (SInt32 i = 0; i < numFormats; ++i) {
// get Motif format property from the root window
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)) {
continue;
}
// check that the format is okay
MotifClipFormat motifFormat;
if (data.size() < sizeof(motifFormat)) {
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) {
continue;
}
// save it
motifFormats.insert(std::make_pair(motifFormat.m_type, data));
}
// const UInt32 numMotifFormats = motifFormats.size();
// 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) {
IXWindowsClipboardConverter *converter = *index;
// skip already handled targets
if (m_added[converter->getFormat()]) {
continue;
}
// see if atom is in target list
MotifFormatMap::const_iterator index2 = motifFormats.find(converter->getAtom());
if (index2 == motifFormats.end()) {
continue;
}
// get format
MotifClipFormat motifFormat;
std::memcpy(&motifFormat, index2->second.data(), sizeof(motifFormat));
const Atom target = motifFormat.m_type;
// get the data (finally)
Atom actualTarget;
String targetData;
if (!motifGetSelection(&motifFormat, &actualTarget, &targetData)) {
LOG((CLOG_DEBUG1 " no data for target %s", XWindowsUtil::atomToString(m_display, target).c_str()));
continue;
}
// add to clipboard and note we've done it
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()));
}
}
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.
if (!motifOwnsClipboard()) {
return icccmGetSelection(format->m_type, actualTarget, data);
}
// use motif way
// FIXME -- this isn't right. it'll only work if the data is
// already stored on the root window and only if it fits in a
// property. motif has some scheme for transferring part by
// part that i don't know.
static const int buffer_size = 18 + 20;
char name[buffer_size];
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);
}
IClipboard::Time XWindowsClipboard::motifGetTime() const
{
return icccmGetTime();
}
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)) {
// can't get the requested targets
return false;
}
// fail if the requested targets isn't of the correct form
if (format != 32 || target != m_atomAtomPair) {
return false;
}
// data is a list of atom pairs: target, property
XWindowsUtil::convertAtomProperty(data);
auto targets = static_cast<const Atom *>(static_cast<const void *>(data.data()));
const UInt32 numTargets = data.size() / sizeof(Atom);
// add replies for each target
bool changed = false;
for (UInt32 i = 0; i < numTargets; i += 2) {
const Atom target = targets[i + 0];
const Atom property = targets[i + 1];
if (!addSimpleRequest(requestor, target, time, property)) {
// note that we can't perform the requested conversion
XWindowsUtil::replaceAtomData(data, i, None);
changed = true;
}
}
// update the targets property if we changed it
if (changed) {
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));
return true;
}
void XWindowsClipboard::insertReply(Reply *reply)
{
assert(reply != nullptr);
// note -- we must respond to requests in order if requestor,target,time
// are the same, otherwise we can use whatever order we like with one
// exception: each reply in a MULTIPLE reply must be handled in order
// as well. those replies will almost certainly not share targets so
// we can't simply use requestor,target,time as map index.
//
// instead we'll use just the requestor. that's more restrictive than
// necessary but we're guaranteed to do things in the right order.
// note that we could also include the time in the map index and still
// ensure the right order. but since that'll just make it harder to
// find the right reply when handling property notify events we stick
// to just the requestor.
const bool newWindow = (m_replies.count(reply->m_requestor) == 0);
m_replies[reply->m_requestor].push_back(reply);
// adjust requestor's event mask if we haven't done so already. we
// want events in case the window is destroyed or any of its
// properties change.
if (newWindow) {
// note errors while we adjust event masks
bool error = false;
{
XWindowsUtil::ErrorLock lock(m_display, &error);
// get and save the current event mask
XWindowAttributes attr;
XGetWindowAttributes(m_display, reply->m_requestor, &attr);
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);
}
// if we failed then the window has already been destroyed
if (error) {
m_replies.erase(reply->m_requestor);
delete reply;
}
}
}
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();) {
assert(!index->second.empty());
ReplyList::iterator listit = index->second.begin();
while (listit != index->second.end()) {
if (!(*listit)->m_replied)
break;
++listit;
}
if (listit != index->second.end() && !(*listit)->m_replied) {
pushReplies(index, index->second, listit);
} else {
++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,
// if any.
index = replies.erase(index);
delete reply;
if (index == replies.end()) {
break;
}
reply = *index;
}
// if there are no more replies in the list then remove the list
// and stop watching the requestor for events.
if (replies.empty()) {
XWindowsUtil::ErrorLock lock(m_display);
Window requestor = mapIndex->first;
XSelectInput(m_display, requestor, m_eventMasks[requestor]);
m_replies.erase(mapIndex++);
m_eventMasks.erase(requestor);
} else {
++mapIndex;
}
}
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
));
return true;
}
// start in failed state if property is None
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)
);
// send using INCR if already sending incrementally or if reply
// is too large, otherwise just send it.
const UInt32 maxRequestSize = 3 * XMaxRequestSize(m_display);
const bool useINCR = (reply->m_data.size() > maxRequestSize);
// send INCR reply if incremental and we haven't replied yet
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
)) {
failed = true;
}
}
// send more INCR reply or entire non-incremental reply
else {
// how much more data should we send?
UInt32 size = reply->m_data.size() - reply->m_ptr;
if (size > maxRequestSize)
size = maxRequestSize;
// 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
)) {
failed = true;
} else {
reply->m_ptr += size;
// we've finished the reply if we just sent the zero
// size incremental chunk or if we're not incremental.
reply->m_done = (size == 0 || !useINCR);
}
}
}
// if we've failed then delete the property and say we're done.
// if we haven't replied yet then we can send a failure notify,
// otherwise we've failed in the middle of an incremental
// transfer; i don't know how to cancel that so i'll just send
// 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
));
reply->m_done = true;
if (reply->m_property != None) {
XWindowsUtil::ErrorLock lock(m_display);
XDeleteProperty(m_display, reply->m_requestor, reply->m_property);
}
if (!reply->m_replied) {
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
);
// wait for delete notify
return false;
}
}
// notification already sended
if (reply->m_replied) {
return false;
}
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<unsigned int>(reply->m_time)
);
// wait for delete notify
return false;
}
// dump every property on the requestor window to the debug2
// log. we've seen what appears to be a bug in lesstif and
// knowing the properties may help design a workaround, if
// it becomes necessary.
XWindowsUtil::ErrorLock lock(m_display);
int n;
Atom *props = XListProperties(m_display, reply->m_requestor, &n);
LOG((CLOG_DEBUG2 "properties of 0x%08x:", reply->m_requestor));
for (int i = 0; i < n; ++i) {
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)) {
LOG((CLOG_DEBUG2 " %s: <can't read property>", 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()) {
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 += ' ';
});
data = tmp;
}
char *type = XGetAtomName(m_display, target);
LOG((CLOG_DEBUG2 " %s (%s): %s", name, type, data.c_str()));
if (type != nullptr) {
XFree(type);
}
}
if (name != nullptr) {
XFree(name);
}
}
if (props != nullptr) {
XFree(props);
}
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) {
clearReplies(index->second);
}
m_replies.clear();
m_eventMasks.clear();
}
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)
{
XEvent event;
event.xselection.type = SelectionNotify;
event.xselection.display = m_display;
event.xselection.requestor = requestor;
event.xselection.selection = selection;
event.xselection.target = target;
event.xselection.property = property;
event.xselection.time = time;
XWindowsUtil::ErrorLock lock(m_display);
XSendEvent(m_display, requestor, False, 0, &event);
}
bool XWindowsClipboard::wasOwnedAtTime(::Time time) const
{
// not owned if we've never owned the selection
checkCache();
if (m_timeOwned == 0) {
return false;
}
// if time is CurrentTime then return true if we still own the
// selection and false if we do not. else if we still own the
// selection then get the current time, otherwise use
// m_timeLost as the end time.
Time lost = m_timeLost;
if (m_timeLost == 0) {
if (time == CurrentTime) {
return true;
} else {
lost = XWindowsUtil::getCurrentTime(m_display, m_window);
}
} else {
if (time == CurrentTime) {
return false;
}
}
// compare time to range
Time duration = lost - m_timeOwned;
Time when = time - m_timeOwned;
return (/*when >= 0 &&*/ when <= duration);
}
Atom XWindowsClipboard::getTargetsData(String &data, int *format) const
{
assert(format != nullptr);
// add standard targets
XWindowsUtil::appendAtomData(data, m_atomTargets);
XWindowsUtil::appendAtomData(data, m_atomMultiple);
XWindowsUtil::appendAtomData(data, m_atomTimestamp);
// add targets we can convert to
for (ConverterList::const_iterator index = m_converters.begin(); index != m_converters.end(); ++index) {
IXWindowsClipboardConverter *converter = *index;
// skip formats we don't have
if (m_added[converter->getFormat()]) {
XWindowsUtil::appendAtomData(data, converter->getAtom());
}
}
*format = 32;
return m_atomAtom;
}
Atom XWindowsClipboard::getTimestampData(String &data, int *format) const
{
assert(format != nullptr);
checkCache();
XWindowsUtil::appendTimeData(data, m_timeOwned);
*format = 32;
return m_atomInteger;
}
//
// XWindowsClipboard::CICCCMGetClipboard
//
XWindowsClipboard::CICCCMGetClipboard::CICCCMGetClipboard(Window requestor, Time time, Atom property)
: m_requestor(requestor),
m_time(time),
m_property(property)
{
}
bool XWindowsClipboard::CICCCMGetClipboard::readClipboard(
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)
);
m_atomNone = XInternAtom(display, "NONE", False);
m_atomIncr = XInternAtom(display, "INCR", False);
// save output pointers
m_actualTarget = actualTarget;
m_data = data;
// assume failure
*m_actualTarget = None;
*m_data = "";
// delete target property
XDeleteProperty(display, m_requestor, m_property);
// select window for property changes
XWindowAttributes attr;
XGetWindowAttributes(display, m_requestor, &attr);
XSelectInput(display, m_requestor, attr.your_event_mask | PropertyChangeMask);
// request data conversion
XConvertSelection(display, selection, target, m_property, m_requestor, m_time);
// synchronize with server before we start following timeout countdown
XSync(display, False);
// Xlib inexplicably omits the ability to wait for an event with
// a timeout. (it's inexplicable because there's no portable way
// to do it.) we'll poll until we have what we're looking for or
// a timeout expires. we use a timeout so we don't get locked up
// by badly behaved selection owners.
XEvent xevent;
std::vector<XEvent> events;
Stopwatch timeout(false); // timer not stopped, not triggered
static const double s_timeout = 0.25; // FIXME -- is this too short?
bool noWait = false;
while (!m_done && !m_failed) {
// fail if timeout has expired
if (timeout.getTime() >= s_timeout) {
m_failed = true;
break;
}
// process events if any otherwise sleep
if (noWait || XPending(display) > 0) {
while (!m_done && !m_failed && (noWait || XPending(display) > 0)) {
// fail if timeout has expired
if (timeout.getTime() >= s_timeout) {
m_failed = true;
break;
}
XNextEvent(display, &xevent);
if (!processEvent(display, &xevent)) {
// not processed so save it
events.push_back(xevent);
} else {
// reset timer since we've made some progress
timeout.reset();
// don't sleep anymore, just block waiting for events.
// we're assuming here that the clipboard owner will
// complete the protocol correctly. if we continue to
// sleep we'll get very bad performance.
noWait = true;
}
}
} else {
ARCH->sleep(0.01);
}
}
// put unprocessed events back
for (UInt32 i = events.size(); i > 0; --i) {
XPutBackEvent(display, &events[i - 1]);
}
// restore mask
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()));
return !m_failed;
}
bool XWindowsClipboard::CICCCMGetClipboard::processEvent(Display *display, XEvent *xevent)
{
// process event
switch (xevent->type) {
case DestroyNotify:
if (xevent->xdestroywindow.window == m_requestor) {
m_failed = true;
return true;
}
// not interested
return false;
case SelectionNotify:
if (xevent->xselection.requestor == m_requestor) {
// done if we can't convert
if (xevent->xselection.property == None || xevent->xselection.property == m_atomNone) {
m_done = true;
return true;
}
// proceed if conversion successful
else if (xevent->xselection.property == m_property) {
m_reading = true;
break;
}
}
// otherwise not interested
return false;
case PropertyNotify:
// proceed if conversion successful and we're receiving more data
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
return true;
}
break;
}
// otherwise not interested
return false;
default:
// not interested
return false;
}
// 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)) {
// unable to read property
m_failed = true;
return true;
}
// note if incremental. if we're already incremental then the
// selection owner is busted. if the INCR property has no size
// then the selection owner is busted.
if (target == m_atomIncr) {
if (m_incr || m_data->size() == oldSize) {
m_failed = true;
m_error = true;
} else {
m_incr = true;
// discard INCR data
*m_data = "";
}
}
// handle incremental chunks
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()));
*m_actualTarget = target;
}
// secondary chunks must have the same target
else {
if (target != *m_actualTarget) {
LOG((CLOG_WARN " INCR target mismatch"));
m_failed = true;
m_error = true;
}
}
// note if this is the final chunk
if (m_data->size() == oldSize) {
LOG((CLOG_DEBUG1 " INCR final chunk: %d bytes total", m_data->size()));
m_done = true;
}
}
// not incremental; save the target.
else {
LOG((CLOG_DEBUG1 " target %s", XWindowsUtil::atomToString(display, target).c_str()));
*m_actualTarget = target;
m_done = true;
}
// this event has been processed
LOGC(!m_incr, (CLOG_DEBUG1 " got data, %d bytes", m_data->size()));
return true;
}
//
// XWindowsClipboard::Reply
//
XWindowsClipboard::Reply::Reply(Window requestor, Atom target, ::Time time)
: m_requestor(requestor),
m_target(target),
m_time(time),
m_property(None),
m_replied(false),
m_done(false),
m_data(),
m_type(None),
m_format(32),
m_ptr(0)
{
// do nothing
}
XWindowsClipboard::Reply::Reply(
Window requestor, Atom target, ::Time time, Atom property, const String &data, Atom type, int format
)
: m_requestor(requestor),
m_target(target),
m_time(time),
m_property(property),
m_replied(false),
m_done(false),
m_data(data),
m_type(type),
m_format(format),
m_ptr(0)
{
// do nothing
}
| 42,770
|
C++
|
.cpp
| 1,221
| 30.767404
| 120
| 0.681014
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,591
|
MSWindowsWatchdog.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsWatchdog.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2009 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/MSWindowsWatchdog.h"
#include "arch/Arch.h"
#include "arch/win32/XArchWindows.h"
#include "base/Log.h"
#include "base/TMethodJob.h"
#include "base/log_outputters.h"
#include "common/ipc.h"
#include "deskflow/App.h"
#include "deskflow/ArgsBase.h"
#include "ipc/IpcLogOutputter.h"
#include "ipc/IpcMessage.h"
#include "ipc/IpcServer.h"
#include "mt/Thread.h"
#include <Shellapi.h>
#include <UserEnv.h>
#include <sstream>
#define WIN32_LEAN_AND_MEAN
#include <Windows.h>
#define CURRENT_PROCESS_ID 0
#define MAXIMUM_WAIT_TIME 3
// TODO: maybe this should be \winlogon if we have logonui.exe?
static char g_desktopName[] = "winsta0\\Default";
namespace {
std::string trimDesktopName(const std::string &nameFromTraces)
{
std::string name;
for (const auto &symbol : nameFromTraces) {
if (std::isalpha(symbol)) {
name.push_back(symbol);
} else {
break;
}
}
return name;
}
bool isDesktopRunnable(const std::string &desktopName)
{
const std::string winlogon = "Winlogon";
bool isNotLoginScreen = std::strncmp(desktopName.c_str(), winlogon.c_str(), winlogon.length());
const auto setting = ARCH->setting("runOnLoginScreen");
bool runOnLoginScreen = (setting.empty() || setting == "true");
return (runOnLoginScreen || isNotLoginScreen);
}
} // namespace
enum
{
kOutputBufferSize = 4096
};
typedef VOID(WINAPI *SendSas)(BOOL asUser);
const char g_activeDesktop[] = {"activeDesktop:"};
MSWindowsWatchdog::MSWindowsWatchdog(
bool autoDetectCommand, IpcServer &ipcServer, IpcLogOutputter &ipcLogOutputter, bool foreground
)
: m_thread(NULL),
m_autoDetectCommand(autoDetectCommand),
m_monitoring(true),
m_commandChanged(false),
m_stdOutWrite(NULL),
m_stdOutRead(NULL),
m_ipcServer(ipcServer),
m_ipcLogOutputter(ipcLogOutputter),
m_elevateProcess(false),
m_processFailures(0),
m_processRunning(false),
m_fileLogOutputter(NULL),
m_autoElevated(false),
m_ready(false),
m_foreground(foreground)
{
m_mutex = ARCH->newMutex();
m_condVar = ARCH->newCondVar();
}
MSWindowsWatchdog::~MSWindowsWatchdog()
{
if (m_condVar != NULL) {
ARCH->closeCondVar(m_condVar);
}
if (m_mutex != NULL) {
ARCH->closeMutex(m_mutex);
}
}
void MSWindowsWatchdog::startAsync()
{
m_thread = new Thread(new TMethodJob<MSWindowsWatchdog>(this, &MSWindowsWatchdog::mainLoop, nullptr));
m_outputThread = new Thread(new TMethodJob<MSWindowsWatchdog>(this, &MSWindowsWatchdog::outputLoop, nullptr));
}
void MSWindowsWatchdog::stop()
{
m_monitoring = false;
m_thread->wait(5);
delete m_thread;
m_outputThread->wait(5);
delete m_outputThread;
}
HANDLE
MSWindowsWatchdog::duplicateProcessToken(HANDLE process, LPSECURITY_ATTRIBUTES security)
{
HANDLE 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));
throw XArch(new XArchEvalWindows());
}
LOG((CLOG_DEBUG "got token %i, duplicating", sourceToken));
HANDLE newToken;
BOOL duplicateRet = DuplicateTokenEx(
sourceToken, TOKEN_ASSIGN_PRIMARY | TOKEN_ALL_ACCESS, security, SecurityImpersonation, TokenPrimary, &newToken
);
if (!duplicateRet) {
LOG((CLOG_ERR "could not duplicate token %i", sourceToken));
throw XArch(new XArchEvalWindows());
}
LOG((CLOG_DEBUG "duplicated, new token: %i", newToken));
return newToken;
}
HANDLE
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)) {
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");
}
return duplicateProcessToken(process, security);
} else {
LOG((CLOG_DEBUG "getting non-elevated token"));
return m_session.getUserToken(security);
}
}
void MSWindowsWatchdog::mainLoop(void *)
{
shutdownExistingProcesses();
SendSas sendSasFunc = NULL;
HINSTANCE sasLib = LoadLibrary("sas.dll");
if (sasLib) {
LOG((CLOG_DEBUG "found sas.dll"));
sendSasFunc = (SendSas)GetProcAddress(sasLib, "SendSAS");
}
SECURITY_ATTRIBUTES saAttr;
saAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
saAttr.bInheritHandle = TRUE;
saAttr.lpSecurityDescriptor = NULL;
if (!CreatePipe(&m_stdOutRead, &m_stdOutWrite, &saAttr, 0)) {
throw XArch(new XArchEvalWindows());
}
ZeroMemory(&m_processInfo, sizeof(PROCESS_INFORMATION));
while (m_monitoring) {
try {
if (m_processRunning && getCommand().empty()) {
LOG((CLOG_INFO "process started but command is empty, shutting down"));
shutdownExistingProcesses();
m_processRunning = false;
continue;
}
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));
ARCH->sleep(timeout);
}
if (!getCommand().empty()) {
bool startNeeded = false;
if (m_processFailures != 0) {
startNeeded = true;
} else if (!m_foreground && m_session.hasChanged()) {
startNeeded = true;
} else if (m_commandChanged) {
startNeeded = true;
}
if (startNeeded) {
startProcess();
}
}
if (m_processRunning && !isProcessActive()) {
m_processFailures++;
m_processRunning = false;
LOG((CLOG_WARN "detected application not running, pid=%d", m_processInfo.dwProcessId));
}
if (sendSasFunc != NULL) {
HANDLE sendSasEvent = CreateEvent(NULL, FALSE, FALSE, "Global\\SendSAS");
if (sendSasEvent != NULL) {
// use SendSAS event to wait for next session (timeout 1 second).
if (WaitForSingleObject(sendSasEvent, 1000) == WAIT_OBJECT_0) {
LOG((CLOG_DEBUG "calling SendSAS"));
sendSasFunc(FALSE);
}
CloseHandle(sendSasEvent);
continue;
}
}
// if the sas event failed, wait by sleeping.
ARCH->sleep(1);
} catch (std::exception &e) {
LOG((CLOG_CRIT "failed to launch, error: %s", e.what()));
m_processFailures++;
m_processRunning = false;
continue;
} catch (...) {
LOG((CLOG_CRIT "failed to launch, unknown error."));
m_processFailures++;
m_processRunning = false;
continue;
}
}
if (m_processRunning) {
LOG((CLOG_DEBUG "terminated running process on exit"));
shutdownProcess(m_processInfo.hProcess, m_processInfo.dwProcessId, 20);
}
LOG((CLOG_DEBUG "watchdog main thread finished"));
}
bool MSWindowsWatchdog::isProcessActive()
{
DWORD exitCode;
GetExitCodeProcess(m_processInfo.hProcess, &exitCode);
return exitCode == STILL_ACTIVE;
}
void MSWindowsWatchdog::setFileLogOutputter(FileLogOutputter *outputter)
{
m_fileLogOutputter = outputter;
}
void MSWindowsWatchdog::startProcess()
{
if (m_command.empty()) {
throw XMSWindowsWatchdogError("cannot start process, command is empty");
}
m_commandChanged = false;
if (m_processRunning) {
LOG((CLOG_DEBUG "closing existing process to make way for new one"));
shutdownProcess(m_processInfo.hProcess, m_processInfo.dwProcessId, 20);
m_processRunning = false;
}
BOOL createRet;
if (m_foreground) {
LOG((CLOG_DEBUG "starting command in foreground"));
createRet = startProcessInForeground(m_command);
} else {
LOG((CLOG_DEBUG "starting command as session user"));
m_session.updateActiveSession();
SECURITY_ATTRIBUTES sa;
ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES));
getActiveDesktop(&sa);
if (!isDesktopRunnable(m_activeDesktop)) {
LOG((CLOG_INFO, "starting on the login screen is disabled"));
return;
}
ZeroMemory(&sa, sizeof(SECURITY_ATTRIBUTES));
HANDLE userToken = getUserToken(&sa);
m_elevateProcess = m_autoElevated ? m_autoElevated : m_elevateProcess;
m_autoElevated = false;
// patch by Jack Zhou and Henry Tung
// set UIAccess to fix Windows 8 GUI interaction
DWORD uiAccess = 1;
SetTokenInformation(userToken, TokenUIAccess, &uiAccess, sizeof(DWORD));
createRet = startProcessAsUser(m_command, userToken, &sa);
}
if (!createRet) {
LOG((CLOG_CRIT "could not launch command"));
DWORD exitCode = 0;
GetExitCodeProcess(m_processInfo.hProcess, &exitCode);
LOG((CLOG_ERR "exit code: %d", exitCode));
throw XArch(new XArchEvalWindows);
} else {
// wait for program to fail.
ARCH->sleep(1);
if (!isProcessActive()) {
closeProcessHandles(m_processInfo.dwProcessId);
throw XMSWindowsWatchdogError("process immediately stopped");
}
m_processRunning = true;
m_processFailures = 0;
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())
);
}
}
void MSWindowsWatchdog::setStartupInfo(STARTUPINFO &si)
{
ZeroMemory(&si, sizeof(STARTUPINFO));
si.cb = sizeof(STARTUPINFO);
si.lpDesktop = g_desktopName;
si.hStdError = m_stdOutWrite;
si.hStdOutput = m_stdOutWrite;
si.dwFlags |= STARTF_USESTDHANDLES;
}
BOOL MSWindowsWatchdog::startProcessInForeground(String &command)
{
// clear, as we're reusing process info struct
ZeroMemory(&m_processInfo, sizeof(PROCESS_INFORMATION));
// show the console window when in foreground mode,
// so we can close it gracefully, but minimize it
// so it doesn't get in the way.
STARTUPINFO si;
setStartupInfo(si);
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);
m_children.insert(std::make_pair(m_processInfo.dwProcessId, m_processInfo));
return result;
}
BOOL MSWindowsWatchdog::startProcessAsUser(String &command, HANDLE userToken, LPSECURITY_ATTRIBUTES sa)
{
// clear, as we're reusing process info struct
ZeroMemory(&m_processInfo, sizeof(PROCESS_INFORMATION));
STARTUPINFO si;
setStartupInfo(si);
LPVOID environment;
BOOL blockRet = CreateEnvironmentBlock(&environment, userToken, FALSE);
if (!blockRet) {
LOG((CLOG_ERR "could not create environment block"));
throw XArch(new XArchEvalWindows);
}
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
);
m_children.insert(std::make_pair(m_processInfo.dwProcessId, m_processInfo));
DestroyEnvironmentBlock(environment);
CloseHandle(userToken);
return createRet;
}
void MSWindowsWatchdog::setCommand(const std::string &command, bool elevate)
{
LOG((CLOG_INFO "service command updated"));
m_command = command;
m_elevateProcess = elevate;
m_commandChanged = true;
m_processFailures = 0;
}
std::string MSWindowsWatchdog::getCommand() const
{
if (!m_autoDetectCommand) {
return m_command;
}
// seems like a fairly convoluted way to get the process name
const char *launchName = App::instance().argsBase().m_pname;
std::string args = ARCH->commandLine();
// build up a full command line
std::stringstream cmdTemp;
cmdTemp << launchName << args;
std::string cmd = cmdTemp.str();
size_t i;
std::string find = "--relaunch";
while ((i = cmd.find(find)) != std::string::npos) {
cmd.replace(i, find.length(), "");
}
return cmd;
}
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);
// assume the process has gone away? slow down
// the reads until another one turns up.
if (!success || bytesRead == 0) {
ARCH->sleep(1);
} else {
buffer[bytesRead] = '\0';
testOutput(buffer);
m_ipcLogOutputter.write(kINFO, buffer);
if (m_fileLogOutputter != NULL) {
m_fileLogOutputter->write(kINFO, buffer);
}
#if SYSAPI_WIN32
if (m_foreground) {
// when in foreground mode (useful for debugging), send the core
// process output to the VS debug output window.
// we could use the MSWindowsDebugOutputter, but it's really fiddly to
// so, and there doesn't seem to be an advantage of doing that.
OutputDebugString(buffer);
}
#endif
}
}
}
void MSWindowsWatchdog::shutdownProcess(HANDLE handle, DWORD pid, int timeout)
{
DWORD exitCode;
GetExitCodeProcess(handle, &exitCode);
if (exitCode != STILL_ACTIVE) {
return;
}
IpcShutdownMessage shutdown;
m_ipcServer.send(shutdown, IpcClientType::Node);
// wait for process to exit gracefully.
double start = ARCH->time();
while (true) {
GetExitCodeProcess(handle, &exitCode);
if (exitCode != STILL_ACTIVE) {
// yay, we got a graceful shutdown. there should be no hook in use errors!
LOG((CLOG_DEBUG "process %d was shutdown gracefully", pid));
break;
} else {
double elapsed = (ARCH->time() - start);
if (elapsed > timeout) {
// if timeout reached, kill forcefully.
// 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));
TerminateProcess(handle, kExitSuccess);
break;
}
ARCH->sleep(1);
}
}
closeProcessHandles(pid);
}
void MSWindowsWatchdog::shutdownExistingProcesses()
{
// first we need to take a snapshot of the running processes
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);
}
PROCESSENTRY32 entry;
entry.dwSize = sizeof(PROCESSENTRY32);
// get the first process, and if we can't do that then it's
// unlikely we can go any further
BOOL gotEntry = Process32First(snapshot, &entry);
if (!gotEntry) {
LOG((CLOG_ERR "could not get first process entry"));
throw XArch(new XArchEvalWindows);
}
// now just iterate until we can find winlogon.exe pid
DWORD pid = 0;
while (gotEntry) {
// make sure we're not checking the system process
if (entry.th32ProcessID != 0) {
if (_stricmp(entry.szExeFile, "deskflow-client.exe") == 0 ||
_stricmp(entry.szExeFile, "deskflow-server.exe") == 0 ||
_stricmp(entry.szExeFile, "deskflow-core.exe") == 0) {
HANDLE handle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, entry.th32ProcessID);
shutdownProcess(handle, entry.th32ProcessID, 10);
CloseHandle(handle);
}
}
// now move on to the next entry (if we're not at the end)
gotEntry = Process32Next(snapshot, &entry);
if (!gotEntry) {
DWORD err = GetLastError();
if (err != ERROR_NO_MORE_FILES) {
// only worry about error if it's not the end of the snapshot
LOG((CLOG_ERR "could not get subsiquent process entry"));
throw XArch(new XArchEvalWindows);
}
}
}
clearAllChildren();
CloseHandle(snapshot);
m_processRunning = false;
}
void MSWindowsWatchdog::getActiveDesktop(LPSECURITY_ATTRIBUTES security)
{
String installedDir = ARCH->getInstalledDirectory();
if (!installedDir.empty()) {
MSWindowsSession session;
String name = session.getActiveDesktopName();
if (name.empty()) {
LOG((CLOG_CRIT "failed to get active desktop name"));
} else {
String output = deskflow::string::sprintf("activeDesktop:%s", name.c_str());
LOG((CLOG_INFO "%s", output.c_str()));
}
}
}
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());
ARCH->lockMutex(m_mutex);
m_ready = true;
ARCH->broadcastCondVar(m_condVar);
ARCH->unlockMutex(m_mutex);
}
}
void MSWindowsWatchdog::closeProcessHandles(unsigned long pid, bool removeFromMap)
{
auto processInfo = m_children.find(pid);
if (processInfo != m_children.end()) {
CloseHandle(processInfo->second.hProcess);
CloseHandle(processInfo->second.hThread);
if (removeFromMap) {
m_children.erase(processInfo);
}
}
}
void MSWindowsWatchdog::clearAllChildren()
{
for (auto it = m_children.begin(); it != m_children.end(); ++it) {
closeProcessHandles(it->second.dwThreadId, false);
}
m_children.clear();
}
| 18,625
|
C++
|
.cpp
| 528
| 30.875
| 116
| 0.699549
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,592
|
MSWindowsClipboard.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsClipboard.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/MSWindowsClipboard.h"
#include "arch/win32/ArchMiscWindows.h"
#include "base/Log.h"
#include "platform/MSWindowsClipboardBitmapConverter.h"
#include "platform/MSWindowsClipboardFacade.h"
#include "platform/MSWindowsClipboardHTMLConverter.h"
#include "platform/MSWindowsClipboardTextConverter.h"
#include "platform/MSWindowsClipboardUTF16Converter.h"
//
// MSWindowsClipboard
//
UINT MSWindowsClipboard::s_ownershipFormat = 0;
MSWindowsClipboard::MSWindowsClipboard(HWND window)
: m_window(window),
m_time(0),
m_facade(new MSWindowsClipboardFacade()),
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()
{
clearConverters();
// dependency injection causes confusion over ownership, so we need
// logic to decide whether or not we delete the facade. there must
// be a more elegant way of doing this.
if (m_deleteFacade)
delete m_facade;
}
void MSWindowsClipboard::setFacade(IMSWindowsClipboardFacade &facade)
{
delete m_facade;
m_facade = &facade;
m_deleteFacade = false;
}
bool MSWindowsClipboard::emptyUnowned()
{
LOG((CLOG_DEBUG "empty clipboard"));
// empty the clipboard (and take ownership)
if (!EmptyClipboard()) {
// unable to cause this in integ tests, but this error has never
// actually been reported by users.
LOG((CLOG_DEBUG "failed to grab clipboard"));
return false;
}
return true;
}
bool MSWindowsClipboard::empty()
{
if (!emptyUnowned()) {
return false;
}
// mark clipboard as being owned by deskflow
HGLOBAL data = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, 1);
if (NULL == SetClipboardData(getOwnershipFormat(), data)) {
LOG((CLOG_DEBUG "failed to set clipboard data"));
GlobalFree(data);
return false;
}
return true;
}
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) {
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));
m_facade->write(win32Data, converter->getWin32Format());
isSucceeded = true;
break;
} else {
LOG((CLOG_DEBUG "failed to convert clipboard data to platform format"));
}
}
}
if (!isSucceeded) {
LOG((CLOG_DEBUG "missed clipboard data convert for format: %d", format));
}
}
bool MSWindowsClipboard::open(Time time) const
{
LOG((CLOG_DEBUG "open clipboard"));
if (!OpenClipboard(m_window)) {
LOG((CLOG_WARN "failed to open clipboard: %d", GetLastError()));
return false;
}
m_time = time;
return true;
}
void MSWindowsClipboard::close() const
{
LOG((CLOG_DEBUG "close clipboard"));
CloseClipboard();
}
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) {
IMSWindowsClipboardConverter *converter = *index;
if (converter->getFormat() == format) {
if (IsClipboardFormatAvailable(converter->getWin32Format())) {
return true;
}
}
}
return false;
}
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) {
converter = *index;
if (converter->getFormat() == format) {
break;
}
converter = NULL;
}
// if no converter then we don't recognize any formats
if (converter == NULL) {
LOG((CLOG_WARN "no converter for format %d", format));
return String();
}
// get a handle to the clipboard data
HANDLE win32Data = GetClipboardData(converter->getWin32Format());
if (win32Data == NULL) {
// nb: can't cause this using integ tests; this is only caused when
// the selected converter returns an invalid format -- which you
// cannot cause using public functions.
return String();
}
// convert
return converter->toIClipboard(win32Data);
}
void MSWindowsClipboard::clearConverters()
{
for (ConverterList::iterator index = m_converters.begin(); index != m_converters.end(); ++index) {
delete *index;
}
m_converters.clear();
}
bool MSWindowsClipboard::isOwnedByDeskflow()
{
// create ownership format if we haven't yet
if (s_ownershipFormat == 0) {
s_ownershipFormat = RegisterClipboardFormat(TEXT("Deskflow Ownership"));
}
return (IsClipboardFormatAvailable(getOwnershipFormat()) != 0);
}
UINT MSWindowsClipboard::getOwnershipFormat()
{
// create ownership format if we haven't yet
if (s_ownershipFormat == 0) {
s_ownershipFormat = RegisterClipboardFormat(TEXT("Deskflow Ownership"));
}
// return the format
return s_ownershipFormat;
}
| 6,147
|
C++
|
.cpp
| 186
| 29.784946
| 106
| 0.72942
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,593
|
OSXKeyState.cpp
|
deskflow_deskflow/src/lib/platform/OSXKeyState.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2004 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/OSXKeyState.h"
#include "arch/Arch.h"
#include "base/Log.h"
#include "platform/OSXMediaKeySupport.h"
#include "platform/OSXUchrKeyResource.h"
#include <Carbon/Carbon.h>
#include <IOKit/hidsystem/IOHIDLib.h>
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
// Note that some virtual keys codes appear more than once. The
// first instance of a virtual key code maps to the KeyID that we
// want to generate for that code. The others are for mapping
// different KeyIDs to a single key code.
static const UInt32 s_shiftVK = kVK_Shift;
static const UInt32 s_controlVK = kVK_Control;
static const UInt32 s_altVK = kVK_Option;
static const UInt32 s_superVK = kVK_Command;
static const UInt32 s_capsLockVK = kVK_CapsLock;
static const UInt32 s_numLockVK = kVK_ANSI_KeypadClear; // 71
static const UInt32 s_brightnessUp = 144;
static const UInt32 s_brightnessDown = 145;
static const UInt32 s_missionControlVK = 160;
static const UInt32 s_launchpadVK = 131;
static const UInt32 s_osxNumLock = 1 << 16;
struct KeyEntry
{
public:
KeyID m_keyID;
UInt32 m_virtualKey;
};
static const KeyEntry s_controlKeys[] = {
// cursor keys. if we don't do this we'll may still get these from
// the keyboard resource but they may not correspond to the arrow
// keys.
{kKeyLeft, kVK_LeftArrow},
{kKeyRight, kVK_RightArrow},
{kKeyUp, kVK_UpArrow},
{kKeyDown, kVK_DownArrow},
{kKeyHome, kVK_Home},
{kKeyEnd, kVK_End},
{kKeyPageUp, kVK_PageUp},
{kKeyPageDown, kVK_PageDown},
{kKeyInsert, kVK_Help}, // Mac Keyboards have 'Help' on 'Insert'
// function keys
{kKeyF1, kVK_F1},
{kKeyF2, kVK_F2},
{kKeyF3, kVK_F3},
{kKeyF4, kVK_F4},
{kKeyF5, kVK_F5},
{kKeyF6, kVK_F6},
{kKeyF7, kVK_F7},
{kKeyF8, kVK_F8},
{kKeyF9, kVK_F9},
{kKeyF10, kVK_F10},
{kKeyF11, kVK_F11},
{kKeyF12, kVK_F12},
{kKeyF13, kVK_F13},
{kKeyF14, kVK_F14},
{kKeyF15, kVK_F15},
{kKeyF16, kVK_F16},
{kKeyKP_0, kVK_ANSI_Keypad0},
{kKeyKP_1, kVK_ANSI_Keypad1},
{kKeyKP_2, kVK_ANSI_Keypad2},
{kKeyKP_3, kVK_ANSI_Keypad3},
{kKeyKP_4, kVK_ANSI_Keypad4},
{kKeyKP_5, kVK_ANSI_Keypad5},
{kKeyKP_6, kVK_ANSI_Keypad6},
{kKeyKP_7, kVK_ANSI_Keypad7},
{kKeyKP_8, kVK_ANSI_Keypad8},
{kKeyKP_9, kVK_ANSI_Keypad9},
{kKeyKP_Decimal, kVK_ANSI_KeypadDecimal},
{kKeyKP_Equal, kVK_ANSI_KeypadEquals},
{kKeyKP_Multiply, kVK_ANSI_KeypadMultiply},
{kKeyKP_Add, kVK_ANSI_KeypadPlus},
{kKeyKP_Divide, kVK_ANSI_KeypadDivide},
{kKeyKP_Subtract, kVK_ANSI_KeypadMinus},
{kKeyKP_Enter, kVK_ANSI_KeypadEnter},
// virtual key 110 is fn+enter and i have no idea what that's supposed
// to map to. also the enter key with numlock on is a modifier but i
// don't know which.
// modifier keys. OS X doesn't seem to support right handed versions
// of modifier keys so we map them to the left handed versions.
{kKeyShift_L, s_shiftVK},
{kKeyShift_R, s_shiftVK}, // 60
{kKeyControl_L, s_controlVK},
{kKeyControl_R, s_controlVK}, // 62
{kKeyAlt_L, s_altVK},
{kKeyAlt_R, s_altVK},
{kKeySuper_L, s_superVK},
{kKeySuper_R, s_superVK}, // 61
{kKeyMeta_L, s_superVK},
{kKeyMeta_R, s_superVK}, // 61
// toggle modifiers
{kKeyNumLock, s_numLockVK},
{kKeyCapsLock, s_capsLockVK},
// for Apple Pro JIS Keyboard, map Kana (IME activate) to Henkan (show next
// IME conversion), and
// Eisu (IME deactivate) to Zenkaku (IME activation toggle) on Windows
// Japanese keyboard (OADG109A)
{kKeyHenkan, kVK_JIS_Kana},
{kKeyZenkaku, kVK_JIS_Eisu},
{kKeyMissionControl, s_missionControlVK},
{kKeyLaunchpad, s_launchpadVK},
{kKeyBrightnessUp, s_brightnessUp},
{kKeyBrightnessDown, s_brightnessDown}
};
namespace {
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);
IOObjectRelease(nextIterator);
}
return service;
}
io_connect_t getEventDriver()
{
static io_connect_t sEventDrvrRef = 0;
if (!sEventDrvrRef) {
// Get master device port
mach_port_t masterPort = 0;
if (!IOMasterPort(bootstrap_port, &masterPort)) {
io_iterator_t iter = 0;
auto dict = IOServiceMatching(kIOHIDSystemClass);
if (!IOServiceGetMatchingServices(masterPort, dict, &iter)) {
sEventDrvrRef = getService(iter);
} else {
LOG((CLOG_WARN, "io service not found"));
}
IOObjectRelease(iter);
} else {
LOG((CLOG_WARN, "couldn't get io master port"));
}
}
return sEventDrvrRef;
}
bool isModifier(UInt8 virtualKey)
{
static std::set<UInt8> modifiers{s_shiftVK, s_superVK, s_altVK, s_controlVK, s_capsLockVK};
return (modifiers.find(virtualKey) != modifiers.end());
}
} // namespace
//
// OSXKeyState
//
OSXKeyState::OSXKeyState(IEventQueue *events, std::vector<String> layouts, bool isLangSyncEnabled)
: KeyState(events, std::move(layouts), isLangSyncEnabled)
{
init();
}
OSXKeyState::OSXKeyState(
IEventQueue *events, deskflow::KeyMap &keyMap, std::vector<String> layouts, bool isLangSyncEnabled
)
: KeyState(events, keyMap, std::move(layouts), isLangSyncEnabled)
{
init();
}
OSXKeyState::~OSXKeyState()
{
}
void OSXKeyState::init()
{
m_deadKeyState = 0;
m_shiftPressed = false;
m_controlPressed = false;
m_altPressed = false;
m_superPressed = false;
m_capsPressed = false;
// build virtual key map
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 outMask = 0;
if ((mask & kCGEventFlagMaskShift) != 0) {
outMask |= KeyModifierShift;
}
if ((mask & kCGEventFlagMaskControl) != 0) {
outMask |= KeyModifierControl;
}
if ((mask & kCGEventFlagMaskAlternate) != 0) {
outMask |= KeyModifierAlt;
}
if ((mask & kCGEventFlagMaskCommand) != 0) {
outMask |= KeyModifierSuper;
}
if ((mask & kCGEventFlagMaskAlphaShift) != 0) {
outMask |= KeyModifierCapsLock;
}
if ((mask & kCGEventFlagMaskNumericPad) != 0) {
outMask |= KeyModifierNumLock;
}
LOG((CLOG_DEBUG1 "mask=%04x outMask=%04x", mask, outMask));
return outMask;
}
KeyModifierMask OSXKeyState::mapModifiersToCarbon(UInt32 mask) const
{
KeyModifierMask outMask = 0;
if ((mask & kCGEventFlagMaskShift) != 0) {
outMask |= shiftKey;
}
if ((mask & kCGEventFlagMaskControl) != 0) {
outMask |= controlKey;
}
if ((mask & kCGEventFlagMaskCommand) != 0) {
outMask |= cmdKey;
}
if ((mask & kCGEventFlagMaskAlternate) != 0) {
outMask |= optionKey;
}
if ((mask & kCGEventFlagMaskAlphaShift) != 0) {
outMask |= alphaLock;
}
if ((mask & kCGEventFlagMaskNumericPad) != 0) {
outMask |= s_osxNumLock;
}
return outMask;
}
KeyButton OSXKeyState::mapKeyFromEvent(KeyIDs &ids, KeyModifierMask *maskOut, CGEventRef event) const
{
ids.clear();
// map modifier key
if (maskOut != NULL) {
KeyModifierMask activeMask = getActiveModifiers();
activeMask &= ~KeyModifierAltGr;
*maskOut = activeMask;
}
// get virtual key
UInt32 vkCode = CGEventGetIntegerValueField(event, kCGKeyboardEventKeycode);
// handle up events
UInt32 eventKind = CGEventGetType(event);
if (eventKind == kCGEventKeyUp) {
// the id isn't used. we just need the same button we used on
// the key press. note that we don't use or reset the dead key
// state; up events should not affect the dead key state.
ids.push_back(kKeyNone);
return mapVirtualKeyToKeyButton(vkCode);
}
// check for special keys
VirtualKeyMap::const_iterator i = m_virtualKeyMap.find(vkCode);
if (i != m_virtualKeyMap.end()) {
m_deadKeyState = 0;
ids.push_back(i->second);
return mapVirtualKeyToKeyButton(vkCode);
}
// get keyboard info
AutoTISInputSourceRef currentKeyboardLayout(TISCopyCurrentKeyboardLayoutInputSource(), CFRelease);
if (!currentKeyboardLayout) {
return kKeyNone;
}
// get the event modifiers and remove the command and control
// keys. note if we used them though.
// UCKeyTranslate expects old-style Carbon modifiers, so convert.
UInt32 modifiers;
modifiers = mapModifiersToCarbon(CGEventGetFlags(event));
static const UInt32 s_commandModifiers = cmdKey | controlKey | rightControlKey;
bool isCommand = ((modifiers & s_commandModifiers) != 0);
modifiers &= ~s_commandModifiers;
// if we've used a command key then we want the glyph produced without
// the option key (i.e. the base glyph).
// if (isCommand) {
modifiers &= ~optionKey;
//}
// choose action
UInt16 action;
if (eventKind == kCGEventKeyDown) {
action = kUCKeyActionDown;
} 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);
const bool layoutValid = (layout != NULL);
if (layoutValid) {
// translate key
UniCharCount count;
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
);
// get the characters
if (status == 0) {
if (count != 0 || m_deadKeyState == 0) {
m_deadKeyState = 0;
for (UniCharCount i = 0; i < count; ++i) {
ids.push_back(IOSXKeyResource::unicharToKeyID(chars[i]));
}
adjustAltGrModifier(ids, maskOut, isCommand);
return mapVirtualKeyToKeyButton(vkCode);
}
return 0;
}
}
return 0;
}
bool OSXKeyState::fakeCtrlAltDel()
{
// pass keys through unchanged
return false;
}
bool OSXKeyState::fakeMediaKey(KeyID id)
{
return fakeNativeMediaKey(id);
}
CGEventFlags OSXKeyState::getModifierStateAsOSXFlags() const
{
CGEventFlags modifiers = 0;
if (m_shiftPressed) {
modifiers |= kCGEventFlagMaskShift;
}
if (m_controlPressed) {
modifiers |= kCGEventFlagMaskControl;
}
if (m_altPressed) {
modifiers |= kCGEventFlagMaskAlternate;
}
if (m_superPressed) {
modifiers |= kCGEventFlagMaskCommand;
}
if (m_capsPressed) {
modifiers |= kCGEventFlagMaskAlphaShift;
}
return modifiers;
}
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
UInt32 mask = GetCurrentKeyModifiers();
KeyModifierMask outMask = 0;
if ((mask & shiftKey) != 0) {
outMask |= KeyModifierShift;
}
if ((mask & controlKey) != 0) {
outMask |= KeyModifierControl;
}
if ((mask & optionKey) != 0) {
outMask |= KeyModifierAlt;
}
if ((mask & cmdKey) != 0) {
outMask |= KeyModifierSuper;
}
if ((mask & alphaLock) != 0) {
outMask |= KeyModifierCapsLock;
}
if ((mask & s_osxNumLock) != 0) {
outMask |= KeyModifierNumLock;
}
LOG((CLOG_DEBUG1 "mask=%04x outMask=%04x", mask, outMask));
return outMask;
}
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()) {
return i->second;
}
LOG((CLOG_WARN "can't get the active group, use the first group instead"));
return 0;
}
void OSXKeyState::pollPressedKeys(KeyButtonSet &pressedKeys) const
{
::KeyMap km;
GetKeys(km);
const UInt8 *m = reinterpret_cast<const UInt8 *>(km);
for (UInt32 i = 0; i < 16; ++i) {
for (UInt32 j = 0; j < 8; ++j) {
if ((m[i] & (1u << j)) != 0) {
pressedKeys.insert(mapVirtualKeyToKeyButton(8 * i + j));
}
}
}
}
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);
m_groupMap[id] = g;
}
}
UInt32 keyboardType = LMGetKbdType();
for (SInt32 g = 0; g < numGroups; ++g) {
// add special keys
getKeyMapForSpecialKeys(keyMap, g);
const void *resource;
bool layoutValid = false;
// add regular keys
// try uchr resource first
TISInputSourceRef keyboardLayout = (TISInputSourceRef)CFArrayGetValueAtIndex(m_groups.get(), g);
CFDataRef resourceRef = (CFDataRef)TISGetInputSourceProperty(keyboardLayout, kTISPropertyUnicodeKeyLayoutData);
layoutValid = resourceRef != NULL;
if (layoutValid)
resource = CFDataGetBytePtr(resourceRef);
if (layoutValid) {
OSXUchrKeyResource uchr(resource, keyboardType);
if (uchr.isValid()) {
LOG((CLOG_DEBUG1 "using uchr resource for group %d", g));
getKeyMap(keyMap, g, uchr);
continue;
}
}
LOG((CLOG_DEBUG1 "no keyboard resource for group %d", g));
}
}
CGEventFlags OSXKeyState::getDeviceDependedFlags() const
{
CGEventFlags modifiers = 0;
if (m_shiftPressed) {
modifiers |= NX_DEVICELSHIFTKEYMASK;
}
if (m_controlPressed) {
modifiers |= NX_DEVICELCTLKEYMASK;
}
if (m_altPressed) {
modifiers |= NX_DEVICELALTKEYMASK;
}
if (m_superPressed) {
modifiers |= NX_DEVICELCMDKEYMASK;
}
return modifiers;
}
CGEventFlags OSXKeyState::getKeyboardEventFlags() const
{
// set the event flags for special keys
// http://tinyurl.com/pxl742y
CGEventFlags modifiers = getModifierStateAsOSXFlags();
if (!m_capsPressed) {
modifiers |= getDeviceDependedFlags();
}
return modifiers;
}
void OSXKeyState::setKeyboardModifiers(CGKeyCode virtualKey, bool keyDown)
{
switch (virtualKey) {
case s_shiftVK:
m_shiftPressed = keyDown;
break;
case s_controlVK:
m_controlPressed = keyDown;
break;
case s_altVK:
m_altPressed = keyDown;
break;
case s_superVK:
m_superPressed = keyDown;
break;
case s_capsLockVK:
m_capsPressed = keyDown;
break;
default:
LOG((CLOG_DEBUG1 "the key is not a modifier"));
break;
}
}
kern_return_t OSXKeyState::postHIDVirtualKey(UInt8 virtualKey, bool postDown)
{
NXEventData event;
bzero(&event, sizeof(NXEventData));
auto driver = getEventDriver();
kern_return_t result = KERN_FAILURE;
if (driver) {
if (isModifier(virtualKey)) {
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);
}
}
return result;
}
void OSXKeyState::postKeyboardKey(CGKeyCode virtualKey, bool keyDown)
{
CGEventRef event = CGEventCreateKeyboardEvent(nullptr, virtualKey, keyDown);
if (event) {
CGEventSetFlags(event, getKeyboardEventFlags());
CGEventPost(kCGHIDEventTap, event);
CFRelease(event);
} else {
LOG((CLOG_CRIT "unable to create keyboard event for keystroke"));
}
}
void OSXKeyState::fakeKey(const Keystroke &keystroke)
{
switch (keystroke.m_type) {
case Keystroke::kButton: {
bool keyDown = keystroke.m_data.m_button.m_press;
UInt32 client = keystroke.m_data.m_button.m_client;
KeyButton button = keystroke.m_data.m_button.m_button;
CGKeyCode virtualKey = mapKeyButtonToVirtualKey(button);
LOG(
(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) {
LOG((CLOG_WARN, "fail to post hid event"));
postKeyboardKey(virtualKey, keyDown);
}
break;
}
case Keystroke::kGroup: {
SInt32 group = keystroke.m_data.m_group.m_group;
if (!keystroke.m_data.m_group.m_restore) {
if (keystroke.m_data.m_group.m_absolute) {
LOG((CLOG_DEBUG1 " group %d", group));
setGroup(group);
} else {
LOG((CLOG_DEBUG1 " group %+d", group));
setGroup(getEffectiveGroup(pollActiveGroup(), group));
}
if (pollActiveGroup() != group) {
LOG((CLOG_WARN "failed to set new keyboard layout"));
}
}
break;
}
}
}
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) {
const KeyEntry &entry = s_controlKeys[i];
item.m_id = entry.m_keyID;
item.m_group = group;
item.m_button = mapVirtualKeyToKeyButton(entry.m_virtualKey);
item.m_required = 0;
item.m_sensitive = 0;
item.m_dead = false;
item.m_client = 0;
deskflow::KeyMap::initModifierKey(item);
keyMap.addKeyEntry(item);
if (item.m_lock) {
// all locking keys are half duplex on OS X
keyMap.addHalfDuplexButton(item.m_button);
}
}
// note: we don't special case the number pad keys. querying the
// mac keyboard returns the non-keypad version of those keys but
// a KeyState always provides a mapping from keypad keys to
// non-keypad keys so we'll be able to generate the characters
// anyway.
}
bool OSXKeyState::getKeyMap(deskflow::KeyMap &keyMap, SInt32 group, const IOSXKeyResource &r) const
{
if (!r.isValid()) {
return false;
}
// space for all possible modifier combinations
std::vector<bool> modifiers(r.getNumModifierCombinations());
// make space for the keys that any single button can synthesize
std::vector<std::pair<KeyID, bool>> buttonKeys(r.getNumTables());
// iterate over each button
deskflow::KeyMap::KeyItem item;
for (UInt32 i = 0; i < r.getNumButtons(); ++i) {
item.m_button = mapVirtualKeyToKeyButton(i);
// the KeyIDs we've already handled
std::set<KeyID> keys;
// convert the entry in each table for this button to a KeyID
for (UInt32 j = 0; j < r.getNumTables(); ++j) {
buttonKeys[j].first = r.getKey(j, i);
buttonKeys[j].second = deskflow::KeyMap::isDeadKey(buttonKeys[j].first);
}
// iterate over each character table
for (UInt32 j = 0; j < r.getNumTables(); ++j) {
// get the KeyID for the button/table
KeyID id = buttonKeys[j].first;
if (id == kKeyNone) {
continue;
}
// if we've already handled the KeyID in the table then
// move on to the next table
if (keys.count(id) > 0) {
continue;
}
keys.insert(id);
// prepare item. the client state is 1 for dead keys.
item.m_id = id;
item.m_group = group;
item.m_dead = buttonKeys[j].second;
item.m_client = buttonKeys[j].second ? 1 : 0;
deskflow::KeyMap::initModifierKey(item);
if (item.m_lock) {
// all locking keys are half duplex on OS X
keyMap.addHalfDuplexButton(i);
}
// collect the tables that map to the same KeyID. we know it
// can't be any earlier tables because of the check above.
std::set<UInt8> tables;
tables.insert(static_cast<UInt8>(j));
for (UInt32 k = j + 1; k < r.getNumTables(); ++k) {
if (buttonKeys[k].first == id) {
tables.insert(static_cast<UInt8>(k));
}
}
// collect the modifier combinations that map to any of the
// tables we just collected
for (UInt32 k = 0; k < r.getNumModifierCombinations(); ++k) {
modifiers[k] = (tables.count(r.getTableForModifier(k)) > 0);
}
// figure out which modifiers the key is sensitive to. the
// key is insensitive to a modifier if for every modifier mask
// with the modifier bit unset in the modifiers we also find
// the same mask with the bit set.
//
// we ignore a few modifiers that we know aren't important
// for generating characters. in fact, we want to ignore any
// characters generated by the control key. we don't map
// those and instead expect the control modifier plus a key.
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) {
continue;
}
for (UInt32 m = 0; m < r.getNumModifierCombinations(); ++m) {
if (modifiers[m] != modifiers[m ^ bit]) {
sensitive |= bit;
break;
}
}
}
// find each required modifier mask. the key can be synthesized
// using any of the masks.
std::set<UInt32> required;
for (UInt32 k = 0; k < r.getNumModifierCombinations(); ++k) {
if ((k & sensitive) == k && modifiers[k & sensitive]) {
required.insert(k);
}
}
// now add a key entry for each key/required modifier pair.
item.m_sensitive = mapModifiersFromOSX(sensitive << 16);
for (std::set<UInt32>::iterator k = required.begin(); k != required.end(); ++k) {
item.m_required = mapModifiersFromOSX(*k << 16);
keyMap.addKeyEntry(item);
}
}
}
return true;
}
bool OSXKeyState::mapDeskflowHotKeyToMac(
KeyID key, KeyModifierMask mask, UInt32 &macVirtualKey, UInt32 &macModifierMask
) const
{
// look up button for key
KeyButton button = getButton(key, pollActiveGroup());
if (button == 0 && key != kKeyNone) {
return false;
}
macVirtualKey = mapKeyButtonToVirtualKey(button);
// calculate modifier mask
macModifierMask = 0;
if ((mask & KeyModifierShift) != 0) {
macModifierMask |= shiftKey;
}
if ((mask & KeyModifierControl) != 0) {
macModifierMask |= controlKey;
}
if ((mask & KeyModifierAlt) != 0) {
macModifierMask |= cmdKey;
}
if ((mask & KeyModifierSuper) != 0) {
macModifierMask |= optionKey;
}
if ((mask & KeyModifierCapsLock) != 0) {
macModifierMask |= alphaLock;
}
if ((mask & KeyModifierNumLock) != 0) {
macModifierMask |= s_osxNumLock;
}
return true;
}
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);
}
if ((changed & KeyModifierControl) != 0) {
handleModifierKey(target, s_controlVK, kKeyControl_L, (newMask & KeyModifierControl) != 0, newMask);
}
if ((changed & KeyModifierAlt) != 0) {
handleModifierKey(target, s_altVK, kKeyAlt_L, (newMask & KeyModifierAlt) != 0, newMask);
}
if ((changed & KeyModifierSuper) != 0) {
handleModifierKey(target, s_superVK, kKeySuper_L, (newMask & KeyModifierSuper) != 0, newMask);
}
if ((changed & KeyModifierCapsLock) != 0) {
handleModifierKey(target, s_capsLockVK, kKeyCapsLock, (newMask & KeyModifierCapsLock) != 0, newMask);
}
if ((changed & KeyModifierNumLock) != 0) {
handleModifierKey(target, s_numLockVK, kKeyNumLock, (newMask & KeyModifierNumLock) != 0, 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
{
// get number of layouts
CFStringRef keys[] = {kTISPropertyInputSourceCategory};
CFStringRef values[] = {kTISCategoryKeyboardInputSource};
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) {
groups = std::move(kbds);
} else {
LOG((CLOG_DEBUG1 "can't get keyboard layouts"));
return false;
}
return true;
}
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);
if (!canBeSetted) {
LOG((CLOG_WARN "nedeed keyboard layout is disabled for programmatically selection"));
return;
}
if (TISSelectInputSource(keyboardLayout) != noErr) {
LOG((CLOG_WARN "failed to set nedeed keyboard layout"));
}
LOG((CLOG_DEBUG1 "keyboard layout change to %d", group));
// A minimal delay is needed after a group change because the
// keyboard key event often happens immediately after.
// Language (TIS) and event (CG) systems are not in the mutual
// event queue and without a delay the subsequent key press
// event could be applied before the keyboard layout would
// actually be changed.
ARCH->sleep(.01);
}
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))) {
*mask |= KeyModifierAltGr;
return;
}
}
}
}
KeyButton OSXKeyState::mapVirtualKeyToKeyButton(UInt32 keyCode)
{
// 'A' maps to 0 so shift every id
return static_cast<KeyButton>(keyCode + KeyButtonOffset);
}
UInt32 OSXKeyState::mapKeyButtonToVirtualKey(KeyButton keyButton)
{
return static_cast<UInt32>(keyButton - KeyButtonOffset);
}
| 27,531
|
C++
|
.cpp
| 801
| 30.177278
| 120
| 0.690538
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,594
|
PortalInputCapture.cpp
|
deskflow_deskflow/src/lib/platform/PortalInputCapture.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2022 Red Hat, Inc.
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/PortalInputCapture.h"
#include "base/Event.h"
#include "base/Log.h"
#include "base/TMethodJob.h"
#include <sys/socket.h> // for EIS fd hack, remove
#include <sys/un.h> // for EIS fd hack, remove
namespace deskflow {
enum signals
{
SESSION_CLOSED,
DISABLED,
ACTIVATED,
DEACTIVATED,
ZONES_CHANGED,
_N_SIGNALS,
};
PortalInputCapture::PortalInputCapture(EiScreen *screen, IEventQueue *events)
: screen_(screen),
events_(events),
portal_(xdp_portal_new()),
signals_(_N_SIGNALS)
{
glib_main_loop_ = g_main_loop_new(nullptr, true);
glib_thread_ = new Thread(new TMethodJob<PortalInputCapture>(this, &PortalInputCapture::glib_thread));
auto init_capture_cb = [](gpointer data) -> gboolean {
return reinterpret_cast<PortalInputCapture *>(data)->init_input_capture_session();
};
g_idle_add(init_capture_cb, this);
}
PortalInputCapture::~PortalInputCapture()
{
if (g_main_loop_is_running(glib_main_loop_))
g_main_loop_quit(glib_main_loop_);
if (glib_thread_) {
glib_thread_->cancel();
glib_thread_->wait();
glib_thread_ = nullptr;
g_main_loop_unref(glib_main_loop_);
glib_main_loop_ = nullptr;
}
if (session_) {
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]);
g_signal_handler_disconnect(session_, signals_[ZONES_CHANGED]);
g_object_unref(session_);
}
for (auto b : barriers_) {
g_object_unref(b);
}
barriers_.clear();
g_object_unref(portal_);
}
gboolean PortalInputCapture::timeout_handler()
{
return true; // keep re-triggering
}
int PortalInputCapture::fake_eis_fd()
{
auto path = std::getenv("LIBEI_SOCKET");
if (!path) {
LOG_DEBUG("cannot fake eis socket, env var not set: LIBEI_SOCKET");
return -1;
}
auto sock = socket(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK, 0);
// Dealing with the socket directly because nothing in lib/... supports
// AF_UNIX and I'm too lazy to fix all this for a temporary hack
int fd = sock;
struct sockaddr_un addr = {
.sun_family = AF_UNIX,
.sun_path = {0},
};
std::snprintf(addr.sun_path, sizeof(addr.sun_path), "%s", path);
auto result = connect(fd, (struct sockaddr *)&addr, sizeof(addr));
if (result != 0) {
LOG_DEBUG("faked eis fd failed: %s", strerror(errno));
}
return sock;
}
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);
g_signal_handler_disconnect(session, signals_[SESSION_CLOSED]);
signals_[SESSION_CLOSED] = 0;
}
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);
if (!session) {
LOG_ERR("failed to initialize input capture session, quitting: %s", error->message);
g_main_loop_quit(glib_main_loop_);
events_->addEvent(Event::kQuit);
return;
}
session_ = session;
auto fd = xdp_input_capture_session_connect_to_eis(session, &error);
if (fd < 0) {
LOG_ERR("failed to connect to eis: %s", error->message);
// FIXME: Development hack to avoid having to assemble all parts just for
// testing this code.
fd = fake_eis_fd();
if (fd < 0) {
g_main_loop_quit(glib_main_loop_);
events_->addEvent(Event::kQuit);
return;
}
}
// Socket ownership is transferred to the EiScreen
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);
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);
cb_zones_changed(session_, nullptr);
}
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);
if (failed_list) {
auto it = failed_list;
while (it) {
guint id;
g_object_get(it->data, "id", &id, nullptr);
for (auto elem = barriers_.begin(); elem != barriers_.end(); elem++) {
if (*elem == it->data) {
int x1, x2, y1, y2;
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);
g_object_unref(*elem);
barriers_.erase(elem);
break;
}
}
it = it->next;
}
}
g_list_free_full(failed_list, g_object_unref);
enable();
}
gboolean PortalInputCapture::init_input_capture_session()
{
LOG_DEBUG("setting up input capture session");
xdp_portal_create_input_capture_session(
portal_,
nullptr, // parent
static_cast<XdpInputCapability>(XDP_INPUT_CAPABILITY_KEYBOARD | XDP_INPUT_CAPABILITY_POINTER),
nullptr, // cancellable
[](GObject *obj, GAsyncResult *res, gpointer data) {
reinterpret_cast<PortalInputCapture *>(data)->cb_init_input_capture_session(obj, res);
},
this
);
return false;
}
void PortalInputCapture::enable()
{
if (!enabled_) {
LOG_DEBUG("enabling the portal input capture session");
xdp_input_capture_session_enable(session_);
enabled_ = true;
}
}
void PortalInputCapture::disable()
{
if (enabled_) {
LOG_DEBUG("disabling the portal input capture session");
xdp_input_capture_session_disable(session_);
enabled_ = false;
}
}
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);
xdp_input_capture_session_release_at(session_, activation_id_, x, y);
is_active_ = false;
}
void PortalInputCapture::cb_disabled(XdpInputCaptureSession *session)
{
LOG_DEBUG("portal cb disabled");
if (!enabled_)
return; // Nothing to do
enabled_ = false;
is_active_ = false;
// FIXME: need some better heuristics here of when we want to enable again
// But we don't know *why* we got disabled (and it's doubtfull we ever
// will), so we just assume that the zones will change or something and we
// can re-enable again
// ... very soon
g_timeout_add(
1000,
[](gpointer data) -> gboolean {
reinterpret_cast<PortalInputCapture *>(data)->enable();
return false;
},
this
);
}
void PortalInputCapture::cb_activated(XdpInputCaptureSession *session, std::uint32_t activation_id, GVariant *options)
{
LOG_DEBUG("portal cb activated, id=%d", activation_id);
if (options) {
gdouble x, y;
if (g_variant_lookup(options, "cursor_position", "(dd)", &x, &y)) {
screen_->warpCursor((int)x, (int)y);
} else {
LOG_WARN("failed to get cursor position");
}
} else {
LOG_WARN("activation has no options");
}
activation_id_ = activation_id;
is_active_ = true;
}
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)
{
for (auto b : barriers_)
g_object_unref(b);
barriers_.clear();
auto zones = xdp_input_capture_session_get_zones(session);
while (zones != nullptr) {
guint w, h;
gint x, y;
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);
int x1, x2, y1, y2;
// Hardcoded behaviour: our pointer barriers are always at the edges of
// all zones. Since the implementation is supposed to reject the ones in
// the wrong place, we can just install barriers everywhere and let EIS
// figure it out. Also a lot easier to implement for now though it doesn't
// cover differently-sized screens...
auto id = barriers_.size() + 1;
x1 = x;
y1 = y;
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)
));
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)
));
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)
));
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)
));
zones = zones->next;
}
GList *list = nullptr;
for (auto const &b : barriers_) {
list = g_list_append(list, b);
}
xdp_input_capture_session_set_pointer_barriers(
session_, list,
nullptr, // cancellable
[](GObject *obj, GAsyncResult *res, gpointer data) {
reinterpret_cast<PortalInputCapture *>(data)->cb_set_pointer_barriers(obj, res);
},
this
);
}
void PortalInputCapture::glib_thread(void *)
{
auto context = g_main_loop_get_context(glib_main_loop_);
LOG_DEBUG("glib thread running");
while (g_main_loop_is_running(glib_main_loop_)) {
Thread::testCancel();
g_main_context_iteration(context, true);
}
LOG_DEBUG("shutting down glib thread");
}
} // namespace deskflow
| 12,089
|
C++
|
.cpp
| 333
| 32.282282
| 120
| 0.671597
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,595
|
XWindowsPowerManager.cpp
|
deskflow_deskflow/src/lib/platform/XWindowsPowerManager.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "XWindowsPowerManager.h"
#include "arch/Arch.h"
#include "base/Log.h"
namespace {
bool sleepInhibitCall(bool state, ArchSystemUnix::InhibitScreenServices serviceID)
{
std::string error;
if (!ArchSystemUnix::DBusInhibitScreenCall(serviceID, state, error)) {
LOG((CLOG_DEBUG "dbus inhibit error %s", error.c_str()));
return false;
}
return true;
}
} // namespace
XWindowsPowerManager::~XWindowsPowerManager()
{
enableSleep();
}
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)) {
LOG((CLOG_INFO "failed to enable system idle sleep"));
}
}
| 1,782
|
C++
|
.cpp
| 49
| 33.938776
| 89
| 0.765797
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,596
|
MSWindowsDropTarget.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsDropTarget.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/MSWindowsDropTarget.h"
#include "base/Log.h"
#include "common/common.h"
#include <Shlobj.h>
#include <stdio.h>
void getDropData(IDataObject *pDataObject);
MSWindowsDropTarget *MSWindowsDropTarget::s_instance = NULL;
MSWindowsDropTarget::MSWindowsDropTarget() : m_refCount(1), m_allowDrop(false)
{
s_instance = this;
}
MSWindowsDropTarget::~MSWindowsDropTarget()
{
}
MSWindowsDropTarget &MSWindowsDropTarget::instance()
{
assert(s_instance != NULL);
return *s_instance;
}
HRESULT
MSWindowsDropTarget::DragEnter(IDataObject *dataObject, DWORD keyState, POINTL point, DWORD *effect)
{
// check if data object contain drop
m_allowDrop = queryDataObject(dataObject);
if (m_allowDrop) {
getDropData(dataObject);
}
*effect = DROPEFFECT_NONE;
return S_OK;
}
HRESULT
MSWindowsDropTarget::DragOver(DWORD keyState, POINTL point, DWORD *effect)
{
*effect = DROPEFFECT_NONE;
return S_OK;
}
HRESULT
MSWindowsDropTarget::DragLeave(void)
{
return S_OK;
}
HRESULT
MSWindowsDropTarget::Drop(IDataObject *dataObject, DWORD keyState, POINTL point, DWORD *effect)
{
*effect = DROPEFFECT_NONE;
return S_OK;
}
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)
{
m_dragFilename = filename;
}
std::string MSWindowsDropTarget::getDraggingFilename()
{
return m_dragFilename;
}
void MSWindowsDropTarget::clearDraggingFilename()
{
m_dragFilename.clear();
}
void getDropData(IDataObject *dataObject)
{
// construct a FORMATETC object
FORMATETC fmtEtc = {CF_HDROP, 0, DVASPECT_CONTENT, -1, TYMED_HGLOBAL};
STGMEDIUM stgMed;
// See if the dataobject contains any DROP stored as a HGLOBAL
if (dataObject->QueryGetData(&fmtEtc) == S_OK) {
if (dataObject->GetData(&fmtEtc, &stgMed) == S_OK) {
// get data here
PVOID data = GlobalLock(stgMed.hGlobal);
// data object global handler contains:
// DROPFILESfilename1 filename2 two spaces as the end
// TODO: get multiple filenames
wchar_t *wcData = (wchar_t *)((LPBYTE)data + sizeof(DROPFILES));
// convert wchar to char
char *filename = new char[wcslen(wcData) + 1];
filename[wcslen(wcData)] = '\0';
wcstombs(filename, wcData, wcslen(wcData));
MSWindowsDropTarget::instance().setDraggingFilename(filename);
GlobalUnlock(stgMed.hGlobal);
// release the data using the COM API
ReleaseStgMedium(&stgMed);
delete[] filename;
}
}
}
HRESULT __stdcall MSWindowsDropTarget::QueryInterface(REFIID iid, void **object)
{
if (iid == IID_IDropTarget || iid == IID_IUnknown) {
AddRef();
*object = this;
return S_OK;
} else {
*object = 0;
return E_NOINTERFACE;
}
}
ULONG __stdcall MSWindowsDropTarget::AddRef(void)
{
return InterlockedIncrement(&m_refCount);
}
ULONG __stdcall MSWindowsDropTarget::Release(void)
{
LONG count = InterlockedDecrement(&m_refCount);
if (count == 0) {
delete this;
return 0;
} else {
return count;
}
}
| 3,946
|
C++
|
.cpp
| 132
| 27
| 100
| 0.739222
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,597
|
MSWindowsUtil.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsUtil.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2004 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/MSWindowsUtil.h"
#include "base/String.h"
#include <stdio.h>
//
// MSWindowsUtil
//
String MSWindowsUtil::getString(HINSTANCE instance, DWORD id)
{
char *msg = NULL;
int n = LoadString(instance, id, reinterpret_cast<LPSTR>(&msg), 0);
if (n <= 0) {
return String();
}
return String(msg, n);
}
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) {
String errorString = deskflow::string::sprintf("%d", error);
return deskflow::string::format(getString(hinstance, id).c_str(), errorString.c_str());
} else {
String result(buffer);
LocalFree(buffer);
return result;
}
}
| 1,633
|
C++
|
.cpp
| 47
| 31.787234
| 112
| 0.724968
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,598
|
XWindowsEventQueueBuffer.cpp
|
deskflow_deskflow/src/lib/platform/XWindowsEventQueueBuffer.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2004 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/XWindowsEventQueueBuffer.h"
#include "base/Event.h"
#include "base/IEventQueue.h"
#include "mt/Lock.h"
#include "mt/Thread.h"
#include <fcntl.h>
#if HAVE_UNISTD_H
#include <unistd.h>
#endif
#include <poll.h>
//
// EventQueueTimer
//
class EventQueueTimer
{
};
//
// XWindowsEventQueueBuffer
//
XWindowsEventQueueBuffer::XWindowsEventQueueBuffer(Display *display, Window window, IEventQueue *events)
: m_events(events),
m_display(display),
m_window(window),
m_waiting(false)
{
assert(m_display != NULL);
assert(m_window != None);
m_userEvent = XInternAtom(m_display, "DESKFLOW_USER_EVENT", False);
// set up for pipe hack
int result = pipe2(m_pipefd, O_NONBLOCK);
assert(result == 0);
}
XWindowsEventQueueBuffer::~XWindowsEventQueueBuffer()
{
// release pipe hack resources
close(m_pipefd[0]);
close(m_pipefd[1]);
}
int XWindowsEventQueueBuffer::getPendingCountLocked()
{
Lock lock(&m_mutex);
return XPending(m_display);
}
void XWindowsEventQueueBuffer::waitForEvent(double dtimeout)
{
Thread::testCancel();
// clear out the pipe in preparation for waiting.
char buf[16];
ssize_t read_response = read(m_pipefd[0], buf, 15);
// with linux automake, warnings are treated as errors by default
if (read_response < 0) {
// todo: handle read response
}
{
Lock lock(&m_mutex);
// we're now waiting for events
m_waiting = true;
// push out pending events
flush();
}
// calling flush may have queued up a new event.
if (!XWindowsEventQueueBuffer::isEmpty()) {
Thread::testCancel();
return;
}
// use poll() to wait for a message from the X server or for timeout.
// this is a good deal more efficient than polling and sleeping.
struct pollfd pfds[2];
pfds[0].fd = ConnectionNumber(m_display);
pfds[0].events = POLLIN;
pfds[1].fd = m_pipefd[0];
pfds[1].events = POLLIN;
int timeout = (dtimeout < 0.0) ? -1 : static_cast<int>(1000.0 * dtimeout);
int remaining = timeout;
int retval = 0;
// It's possible that the X server has queued events locally
// in xlib's event buffer and not pushed on to the fd. Hence we
// can't simply monitor the fd as we may never be woken up.
// ie addEvent calls flush, XFlush may not send via the fd hence
// there is an event waiting to be sent but we must exit the poll
// before it can.
// Instead we poll for a brief period of time (so if events
// queued locally in the xlib buffer can be processed)
// and continue doing this until timeout is reached.
// The human eye can notice 60hz (ansi) which is 16ms, however
// 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) {
retval = poll(pfds, 2, TIMEOUT_DELAY); // 16ms = 60hz, but we make it > to
// play nicely with the cpu
if (pfds[1].revents & POLLIN) {
ssize_t read_response = read(m_pipefd[0], buf, 15);
// with linux automake, warnings are treated as errors by default
if (read_response < 0) {
// todo: handle read response
}
}
remaining -= TIMEOUT_DELAY;
}
{
// we're no longer waiting for events
Lock lock(&m_mutex);
m_waiting = false;
}
Thread::testCancel();
}
IEventQueueBuffer::Type XWindowsEventQueueBuffer::getEvent(Event &event, UInt32 &dataID)
{
Lock lock(&m_mutex);
// push out pending events
flush();
// get next event
XNextEvent(m_display, &m_event);
// process event
if (m_event.xany.type == ClientMessage && m_event.xclient.message_type == m_userEvent) {
dataID = static_cast<UInt32>(m_event.xclient.data.l[0]);
return kUser;
} else {
event = Event(Event::kSystem, m_events->getSystemTarget(), &m_event);
return kSystem;
}
}
bool XWindowsEventQueueBuffer::addEvent(UInt32 dataID)
{
// prepare a message
XEvent xevent;
xevent.xclient.type = ClientMessage;
xevent.xclient.window = m_window;
xevent.xclient.message_type = m_userEvent;
xevent.xclient.format = 32;
xevent.xclient.data.l[0] = static_cast<long>(dataID);
// save the message
Lock lock(&m_mutex);
m_postedEvents.push_back(xevent);
// if we're currently waiting for an event then send saved events to
// the X server now. if we're not waiting then some other thread
// might be using the display connection so we can't safely use it
// too.
if (m_waiting) {
flush();
// Send a character through the round-trip pipe to wake a thread
// that is waiting for a ConnectionNumber() socket to be readable.
// The flush call can read incoming data from the socket and put
// it in Xlib's input buffer. That sneaks it past the other thread.
ssize_t write_response = write(m_pipefd[1], "!", 1);
// with linux automake, warnings are treated as errors by default
if (write_response < 0) {
// todo: handle read response
}
}
return true;
}
bool XWindowsEventQueueBuffer::isEmpty() const
{
Lock lock(&m_mutex);
return (XPending(m_display) == 0);
}
EventQueueTimer *XWindowsEventQueueBuffer::newTimer(double, bool) const
{
return new EventQueueTimer;
}
void XWindowsEventQueueBuffer::deleteTimer(EventQueueTimer *timer) const
{
delete timer;
}
void XWindowsEventQueueBuffer::flush()
{
// note -- m_mutex must be locked on entry
// flush the posted event list to the X server
for (size_t i = 0; i < m_postedEvents.size(); ++i) {
XSendEvent(m_display, m_window, False, 0, &m_postedEvents[i]);
}
XFlush(m_display);
m_postedEvents.clear();
}
| 6,372
|
C++
|
.cpp
| 192
| 29.880208
| 104
| 0.704168
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,599
|
XWindowsKeyState.cpp
|
deskflow_deskflow/src/lib/platform/XWindowsKeyState.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2003 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include <QString>
#ifndef __APPLE__
#include <QDBusConnection>
#include <QDBusInterface>
#include <QDBusPendingReply>
#endif
#include "platform/XWindowsKeyState.h"
#include "base/Log.h"
#include "base/String.h"
#include "common/stdmap.h"
#include "deskflow/AppUtil.h"
#include "deskflow/ClientApp.h"
#include "deskflow/ClientArgs.h"
#include "platform/XWindowsUtil.h"
#include <algorithm>
#include <cstddef>
#if X_DISPLAY_MISSING
#error X11 is required to build deskflow
#else
#include <X11/X.h>
#include <X11/Xutil.h>
#define XK_MISCELLANY
#define XK_XKB_KEYS
#include <X11/keysymdef.h>
#if HAVE_XKB_EXTENSION
#include <X11/XKBlib.h>
#endif
#endif
static const size_t ModifiersFromXDefaultSize = 32;
XWindowsKeyState::XWindowsKeyState(Display *display, bool useXKB, IEventQueue *events)
: KeyState(events, AppUtil::instance().getKeyboardLayoutList(), ClientApp::instance().args().m_enableLangSync),
m_display(display),
m_modifierFromX(ModifiersFromXDefaultSize)
{
init(display, useXKB);
}
XWindowsKeyState::XWindowsKeyState(Display *display, bool useXKB, IEventQueue *events, deskflow::KeyMap &keyMap)
: KeyState(
events, keyMap, AppUtil::instance().getKeyboardLayoutList(), ClientApp::instance().args().m_enableLangSync
),
m_display(display),
m_modifierFromX(ModifiersFromXDefaultSize)
{
init(display, useXKB);
}
XWindowsKeyState::~XWindowsKeyState()
{
#if HAVE_XKB_EXTENSION
if (m_xkb != NULL) {
XkbFreeKeyboard(m_xkb, 0, True);
}
#endif
}
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);
} else {
m_xkb = NULL;
}
#endif
setActiveGroup(kGroupPoll);
}
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
m_group = -1;
m_group = pollActiveGroup();
} else if (group == kGroupPoll) {
m_group = -1;
} else {
assert(group >= 0);
m_group = group;
}
}
void XWindowsKeyState::setAutoRepeat(const XKeyboardState &state)
{
m_keyboardState = state;
}
KeyModifierMask XWindowsKeyState::mapModifiersFromX(unsigned int state) const
{
LOG((CLOG_DEBUG2 "mapping state: %i", state));
UInt32 offset = 8 * getGroupFromState(state);
KeyModifierMask mask = 0;
for (int i = 0; i < 8; ++i) {
if ((state & (1u << i)) != 0) {
LOG((CLOG_DEBUG2 "|= modifier: %i", offset + i));
if (offset + i >= m_modifierFromX.size()) {
LOG(
(CLOG_ERR "m_modifierFromX is too small (%d) for the "
"requested offset (%d)",
m_modifierFromX.size(), offset + i)
);
} else {
mask |= m_modifierFromX[offset + i];
}
}
}
return mask;
}
bool XWindowsKeyState::mapModifiersToX(KeyModifierMask mask, unsigned int &modifiers) const
{
modifiers = 0;
for (SInt32 i = 0; i < kKeyModifierNumBits; ++i) {
KeyModifierMask bit = (1u << i);
if ((mask & bit) != 0) {
KeyModifierToXMask::const_iterator j = m_modifierToX.find(bit);
if (j == m_modifierToX.end()) {
return false;
} else {
modifiers |= j->second;
}
}
}
return true;
}
void XWindowsKeyState::mapKeyToKeycodes(KeyID key, KeycodeList &keycodes) const
{
keycodes.clear();
std::pair<KeyToKeyCodeMap::const_iterator, KeyToKeyCodeMap::const_iterator> 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()
{
// pass keys through unchanged
return false;
}
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) {
state = 0;
}
return mapModifiersFromX(state);
}
SInt32 XWindowsKeyState::pollActiveGroup() const
{
// fixed condition where any group < -1 would have undetermined behaviour
if (m_group >= 0) {
return m_group;
}
#if HAVE_XKB_EXTENSION
if (m_xkb != NULL) {
XkbStateRec state;
XSync(m_display, False);
if (XkbGetState(m_display, XkbUseCoreKbd, &state) == Success) {
return state.group;
}
LOG((CLOG_WARN "failed to poll active group"));
}
#endif
return 0;
}
void XWindowsKeyState::pollPressedKeys(KeyButtonSet &pressedKeys) const
{
char keys[32];
XQueryKeymap(m_display, keys);
for (UInt32 i = 0; i < 32; ++i) {
for (UInt32 j = 0; j < 8; ++j) {
if ((keys[i] & (1u << j)) != 0) {
pressedKeys.insert(8 * i + j);
}
}
}
}
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;
XGetKeyboardControl(m_display, &m_keyboardState);
m_keyboardState.global_auto_repeat = oldGlobalAutoRepeat;
#if HAVE_XKB_EXTENSION
if (m_xkb != NULL) {
if (XkbGetUpdatedMap(m_display, XkbKeyActionsMask | XkbKeyBehaviorsMask | XkbAllClientInfoMask, m_xkb) == Success) {
updateKeysymMapXKB(keyMap);
return;
}
}
#endif
updateKeysymMap(keyMap);
}
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()";
auto bus = QDBusConnection::sessionBus();
if (!bus.isConnected()) {
return false;
}
QDBusInterface screenSaverInterface(service, path, service, bus);
if (!screenSaverInterface.isValid()) {
LOG((CLOG_WARN "keyboard layout fail. dbus interface is invalid"));
return false;
}
QDBusPendingReply<bool, QString> 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())
);
return true;
}
if (reply.isError()) {
LOG((CLOG_WARN "keyboard layout fail. reply contains error"));
return true;
}
if (!reply.argumentAt<0>() || reply.argumentAt<1>() != QString("")) {
LOG((CLOG_WARN "keyboard layout fail. Reply is unexpected!"));
return true;
}
return true;
}
void XWindowsKeyState::fakeKey(const Keystroke &keystroke)
{
switch (keystroke.m_type) {
case Keystroke::kButton:
if (keystroke.m_data.m_button.m_repeat) {
int c = keystroke.m_data.m_button.m_button;
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)) {
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
);
break;
case Keystroke::kGroup:
if (keystroke.m_data.m_group.m_restore) {
break;
}
if (keystroke.m_data.m_group.m_absolute) {
#ifndef __APPLE__
if (setCurrentLanguageWithDBus(keystroke.m_data.m_group.m_group)) {
break;
}
#endif
#if HAVE_XKB_EXTENSION
if (m_xkb != NULL) {
if (XkbLockGroup(m_display, XkbUseCoreKbd, keystroke.m_data.m_group.m_group) == False) {
LOG((CLOG_DEBUG1 "xkb lock group request not sent"));
}
} else
#endif
{
LOG((CLOG_DEBUG1 " ignored"));
}
} else {
#ifndef __APPLE__
if (setCurrentLanguageWithDBus(keystroke.m_data.m_group.m_group)) {
break;
}
#endif
#if HAVE_XKB_EXTENSION
if (m_xkb != NULL) {
if (XkbLockGroup(
m_display, XkbUseCoreKbd, getEffectiveGroup(pollActiveGroup(), keystroke.m_data.m_group.m_group)
) == False) {
LOG((CLOG_DEBUG1 "xkb lock group request not sent"));
}
} else
#endif
{
LOG((CLOG_DEBUG1 " ignored"));
}
}
break;
}
XFlush(m_display);
}
void XWindowsKeyState::updateKeysymMap(deskflow::KeyMap &keyMap)
{
// there are up to 4 keysyms per keycode
static const int maxKeysyms = 4;
LOG((CLOG_DEBUG1 "non-XKB mapping"));
// prepare map from X modifier to KeyModifierMask. certain bits
// are predefined.
std::fill(m_modifierFromX.begin(), m_modifierFromX.end(), 0);
m_modifierFromX[ShiftMapIndex] = KeyModifierShift;
m_modifierFromX[LockMapIndex] = KeyModifierCapsLock;
m_modifierFromX[ControlMapIndex] = KeyModifierControl;
m_modifierToX.clear();
m_modifierToX[KeyModifierShift] = ShiftMask;
m_modifierToX[KeyModifierCapsLock] = LockMask;
m_modifierToX[KeyModifierControl] = ControlMask;
// prepare map from KeyID to KeyCode
m_keyCodeFromKey.clear();
// get the number of keycodes
int minKeycode, maxKeycode;
XDisplayKeycodes(m_display, &minKeycode, &maxKeycode);
int numKeycodes = maxKeycode - minKeycode + 1;
// get the keyboard mapping for all keys
int keysymsPerKeycode;
KeySym *allKeysyms = XGetKeyboardMapping(m_display, minKeycode, numKeycodes, &keysymsPerKeycode);
// it's more convenient to always have maxKeysyms KeySyms per key
{
KeySym *tmpKeysyms = new KeySym[maxKeysyms * numKeycodes];
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];
} else {
tmpKeysyms[maxKeysyms * i + j] = NoSymbol;
}
}
}
XFree(allKeysyms);
allKeysyms = tmpKeysyms;
}
// get the buttons assigned to modifiers. X11 does not predefine
// the meaning of any modifiers except shift, caps lock, and the
// control key. the meaning of a modifier bit (other than those)
// depends entirely on the KeySyms mapped to that bit. unfortunately
// you cannot map a bit back to the KeySym used to produce it.
// for example, let's say button 1 maps to Alt_L without shift and
// Meta_L with shift. now if mod1 is mapped to button 1 that could
// mean the user used Alt or Meta to turn on that modifier and there's
// no way to know which. it's also possible for one button to be
// mapped to multiple bits so both mod1 and mod2 could be generated
// by button 1.
//
// we're going to ignore any modifier for a button except the first.
// with the above example, that means we'll ignore the mod2 modifier
// bit unless it's also mapped to some other button. we're also
// going to ignore all KeySyms except the first modifier KeySym,
// which means button 1 above won't map to Meta, just Alt.
std::map<KeyCode, unsigned int> modifierButtons;
XModifierKeymap *modifiers = XGetModifierMapping(m_display);
for (unsigned int i = 0; i < 8; ++i) {
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));
}
}
XFreeModifiermap(modifiers);
modifierButtons.erase(0);
// Hack to deal with VMware. When a VMware client grabs input the
// player clears out the X modifier map for whatever reason. We're
// notified of the change and arrive here to discover that there
// are no modifiers at all. Since this prevents the modifiers from
// working in the VMware client we'll use the last known good set
// of modifiers when there are no modifiers. If there are modifiers
// we update the last known good set.
if (!modifierButtons.empty()) {
m_lastGoodNonXKBModifiers = modifierButtons;
} else {
modifierButtons = m_lastGoodNonXKBModifiers;
}
// add entries for each keycode
deskflow::KeyMap::KeyItem item;
for (int i = 0; i < numKeycodes; ++i) {
KeySym *keysyms = allKeysyms + maxKeysyms * i;
KeyCode keycode = static_cast<KeyCode>(i + minKeycode);
item.m_button = static_cast<KeyButton>(keycode);
item.m_client = 0;
// determine modifier sensitivity
item.m_sensitive = 0;
// 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])) {
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) {
KeySym lKeysym, uKeysym;
XConvertCase(keysyms[0], &lKeysym, &uKeysym);
if (lKeysym != uKeysym) {
keysyms[0] = lKeysym;
keysyms[1] = uKeysym;
item.m_sensitive |= KeyModifierCapsLock;
}
} 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]) {
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]) {
item.m_sensitive |= KeyModifierCapsLock;
}
}
}
// key is sensitive to shift if keysyms in levels 0 and 1 or
// levels 2 and 3 don't match. it's also sensitive to shift
// 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])) {
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]) ||
IsKeypadKey(keysyms[3]) || IsPrivateKeypadKey(keysyms[3])) {
item.m_sensitive |= KeyModifierNumLock;
}
// do each keysym (shift level)
for (int j = 0; j < maxKeysyms; ++j) {
item.m_id = XWindowsUtil::mapKeySymToKeyID(keysyms[j]);
if (item.m_id == kKeyNone) {
if (j != 0 && modifierButtons.count(keycode) > 0) {
// pretend the modifier works in other shift levels
// because it probably does.
if (keysyms[1] == NoSymbol || j != 3) {
item.m_id = XWindowsUtil::mapKeySymToKeyID(keysyms[0]);
} else {
item.m_id = XWindowsUtil::mapKeySymToKeyID(keysyms[1]);
}
}
if (item.m_id == kKeyNone) {
continue;
}
}
// group is 0 for levels 0 and 1 and 1 for levels 2 and 3
item.m_group = (j >= 2) ? 1 : 0;
// compute required modifiers
item.m_required = 0;
if ((j & 1) != 0) {
item.m_required |= KeyModifierShift;
}
if ((j & 2) != 0) {
item.m_required |= KeyModifierAltGr;
}
item.m_generates = 0;
item.m_lock = false;
if (modifierButtons.count(keycode) > 0) {
// get flags for modifier keys
deskflow::KeyMap::initModifierKey(item);
// add mapping from X (unless we already have)
if (item.m_generates != 0) {
unsigned int bit = modifierButtons[keycode];
if (m_modifierFromX[bit] == 0) {
m_modifierFromX[bit] = item.m_generates;
m_modifierToX[item.m_generates] = (1u << bit);
}
}
}
// add key
keyMap.addKeyEntry(item);
m_keyCodeFromKey.insert(std::make_pair(item.m_id, keycode));
// add other ways to synthesize the key
if ((j & 1) != 0) {
// 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]) {
item.m_required &= ~KeyModifierShift;
item.m_required |= KeyModifierCapsLock;
keyMap.addKeyEntry(item);
item.m_required |= KeyModifierShift;
item.m_required &= ~KeyModifierCapsLock;
}
// add numlock version of key if sensitive to numlock
if (IsKeypadKey(keysyms[j]) || IsPrivateKeypadKey(keysyms[j])) {
item.m_required &= ~KeyModifierShift;
item.m_required |= KeyModifierNumLock;
keyMap.addKeyEntry(item);
item.m_required |= KeyModifierShift;
item.m_required &= ~KeyModifierNumLock;
}
}
}
}
delete[] allKeysyms;
}
#if HAVE_XKB_EXTENSION
void XWindowsKeyState::updateKeysymMapXKB(deskflow::KeyMap &keyMap)
{
static const XkbKTMapEntryRec defMapEntry = {
True, // active
0, // level
{
0, // mods.mask
0, // mods.real_mods
0 // mods.vmods
}
};
LOG((CLOG_DEBUG1 "xkb mapping"));
// find the number of groups
int maxNumGroups = 0;
for (int i = m_xkb->min_key_code; i <= m_xkb->max_key_code; ++i) {
int numGroups = XkbKeyNumGroups(m_xkb, static_cast<KeyCode>(i));
if (numGroups > maxNumGroups) {
maxNumGroups = numGroups;
}
}
// prepare map from X modifier to KeyModifierMask
std::vector<int> modifierLevel(maxNumGroups * 8, 4);
m_modifierFromX.clear();
m_modifierFromX.resize(maxNumGroups * 8);
m_modifierToX.clear();
// prepare map from KeyID to KeyCode
m_keyCodeFromKey.clear();
// Hack to deal with VMware. When a VMware client grabs input the
// player clears out the X modifier map for whatever reason. We're
// notified of the change and arrive here to discover that there
// are no modifiers at all. Since this prevents the modifiers from
// working in the VMware client we'll use the last known good set
// of modifiers when there are no modifiers. If there are modifiers
// we update the last known good set.
bool useLastGoodModifiers = !hasModifiersXKB();
if (!useLastGoodModifiers) {
m_lastGoodXKBModifiers.clear();
}
// check every button. on this pass we save all modifiers as native
// X modifier masks.
deskflow::KeyMap::KeyItem item;
for (int i = m_xkb->min_key_code; i <= m_xkb->max_key_code; ++i) {
KeyCode keycode = static_cast<KeyCode>(i);
item.m_button = static_cast<KeyButton>(keycode);
item.m_client = 0;
// skip keys with no groups (they generate no symbols)
if (XkbKeyNumGroups(m_xkb, keycode) == 0) {
continue;
}
// note half-duplex keys
const XkbBehavior &b = m_xkb->server->behaviors[keycode];
if ((b.type & XkbKB_OpMask) == XkbKB_Lock) {
keyMap.addHalfDuplexButton(item.m_button);
}
// iterate over all groups
for (int group = 0; group < maxNumGroups; ++group) {
item.m_group = group;
int eGroup = getEffectiveGroup(keycode, group);
// get key info
XkbKeyTypePtr type = XkbKeyKeyType(m_xkb, keycode, eGroup);
// set modifiers the item is sensitive to
item.m_sensitive = type->mods.mask;
// 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);
if (!mapEntry->active) {
continue;
}
int level = mapEntry->level;
// set required modifiers for this item
item.m_required = mapEntry->mods.mask;
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
// yield the capitialized KeySym so we'll adjust the
// level accordingly.
if ((level ^ 1) < type->num_levels) {
level ^= 1;
}
}
// get the keysym for this item
KeySym keysym = XkbKeySymEntry(m_xkb, keycode, level, eGroup);
// check for group change actions, locking modifiers, and
// modifier masks.
item.m_lock = false;
bool isModifier = false;
UInt32 modifierMask = m_xkb->map->modmap[keycode];
if (XkbKeyHasActions(m_xkb, keycode) == True) {
XkbAction *action = XkbKeyActionEntry(m_xkb, keycode, level, eGroup);
if (action->type == XkbSA_SetMods || action->type == XkbSA_LockMods) {
isModifier = true;
// note toggles
item.m_lock = (action->type == XkbSA_LockMods);
// maybe use action's mask
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) {
// ignore group change key
continue;
}
}
level = mapEntry->level;
// VMware modifier hack
if (useLastGoodModifiers) {
XKBModifierMap::const_iterator k = m_lastGoodXKBModifiers.find(eGroup * 256 + keycode);
if (k != m_lastGoodXKBModifiers.end()) {
// Use last known good modifier
isModifier = true;
level = k->second.m_level;
modifierMask = k->second.m_mask;
item.m_lock = k->second.m_lock;
}
} else if (isModifier) {
// Save known good modifier
XKBModifierInfo &info = m_lastGoodXKBModifiers[eGroup * 256 + keycode];
info.m_level = level;
info.m_mask = modifierMask;
info.m_lock = item.m_lock;
}
// record the modifier mask for this key. don't bother
// for keys that change the group.
item.m_generates = 0;
UInt32 modifierBit = XWindowsUtil::getModifierBitForKeySym(keysym);
if (isModifier && modifierBit != kKeyModifierBitNone) {
item.m_generates = (1u << modifierBit);
for (SInt32 j = 0; j < 8; ++j) {
// skip modifiers this key doesn't generate
if ((modifierMask & (1u << j)) == 0) {
continue;
}
// skip keys that map to a modifier that we've
// already seen using fewer modifiers. that is
// if this key must combine with other modifiers
// and we know of a key that combines with fewer
// modifiers (or no modifiers) then prefer the
// other key.
if (level >= modifierLevel[8 * group + j]) {
continue;
}
modifierLevel[8 * group + j] = level;
// save modifier
m_modifierFromX[8 * group + j] |= (1u << modifierBit);
m_modifierToX.insert(std::make_pair(1u << modifierBit, 1u << j));
}
}
// handle special cases of just one keysym for the keycode
if (type->num_levels == 1) {
// if there are upper- and lowercase versions of the
// keysym then add both.
KeySym lKeysym, uKeysym;
XConvertCase(keysym, &lKeysym, &uKeysym);
if (lKeysym != uKeysym) {
if (j != -1) {
continue;
}
item.m_sensitive |= ShiftMask | LockMask;
KeyID lKeyID = XWindowsUtil::mapKeySymToKeyID(lKeysym);
KeyID uKeyID = XWindowsUtil::mapKeySymToKeyID(uKeysym);
if (lKeyID == kKeyNone || uKeyID == kKeyNone) {
continue;
}
item.m_id = lKeyID;
item.m_required = 0;
keyMap.addKeyEntry(item);
item.m_id = uKeyID;
item.m_required = ShiftMask;
keyMap.addKeyEntry(item);
item.m_required = LockMask;
keyMap.addKeyEntry(item);
if (group == 0) {
m_keyCodeFromKey.insert(std::make_pair(lKeyID, keycode));
m_keyCodeFromKey.insert(std::make_pair(uKeyID, keycode));
}
continue;
}
}
// add entry
item.m_id = XWindowsUtil::mapKeySymToKeyID(keysym);
keyMap.addKeyEntry(item);
if (group == 0) {
m_keyCodeFromKey.insert(std::make_pair(item.m_id, keycode));
}
}
}
}
// change all modifier masks to deskflow masks from X masks
keyMap.foreachKey(&XWindowsKeyState::remapKeyModifiers, this);
// allow composition across groups
keyMap.allowGroupSwitchDuringCompose();
}
#endif
void XWindowsKeyState::remapKeyModifiers(KeyID id, SInt32 group, deskflow::KeyMap::KeyItem &item, void *vself)
{
XWindowsKeyState *self = static_cast<XWindowsKeyState *>(vself);
item.m_required = self->mapModifiersFromX(XkbBuildCoreState(item.m_required, group));
item.m_sensitive = self->mapModifiersFromX(XkbBuildCoreState(item.m_sensitive, group));
}
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) {
KeyCode keycode = static_cast<KeyCode>(i);
if (XkbKeyHasActions(m_xkb, keycode) == True) {
// iterate over all groups
int numGroups = XkbKeyNumGroups(m_xkb, keycode);
for (int group = 0; group < numGroups; ++group) {
// iterate over all shift levels for the button (including none)
XkbKeyTypePtr type = XkbKeyKeyType(m_xkb, keycode, group);
for (int j = -1; j < type->map_count; ++j) {
if (j != -1 && !type->map[j].active) {
continue;
}
int level = ((j == -1) ? 0 : type->map[j].level);
XkbAction *action = XkbKeyActionEntry(m_xkb, keycode, level, group);
if (action->type == XkbSA_SetMods || action->type == XkbSA_LockMods) {
return true;
}
}
}
}
}
#endif
return false;
}
int XWindowsKeyState::getEffectiveGroup(KeyCode keycode, int group) const
{
(void)keycode;
#if HAVE_XKB_EXTENSION
// get effective group for key
int numGroups = XkbKeyNumGroups(m_xkb, keycode);
if (group >= numGroups) {
unsigned char groupInfo = XkbKeyGroupInfo(m_xkb, keycode);
switch (XkbOutOfRangeGroupAction(groupInfo)) {
case XkbClampIntoRange:
group = numGroups - 1;
break;
case XkbRedirectIntoRange:
group = XkbOutOfRangeGroupNumber(groupInfo);
if (group >= numGroups) {
group = 0;
}
break;
default:
// wrap
group %= numGroups;
break;
}
}
#endif
return group;
}
UInt32 XWindowsKeyState::getGroupFromState(unsigned int state) const
{
#if HAVE_XKB_EXTENSION
if (m_xkb != NULL) {
return XkbGroupForCoreState(state);
}
#endif
return 0;
}
| 28,377
|
C++
|
.cpp
| 768
| 30.997396
| 120
| 0.643948
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,600
|
OSXClipboard.cpp
|
deskflow_deskflow/src/lib/platform/OSXClipboard.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2004 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/OSXClipboard.h"
#include "arch/XArch.h"
#include "base/Log.h"
#include "deskflow/Clipboard.h"
#include "platform/OSXClipboardBMPConverter.h"
#include "platform/OSXClipboardHTMLConverter.h"
#include "platform/OSXClipboardTextConverter.h"
#include "platform/OSXClipboardUTF16Converter.h"
#include "platform/OSXClipboardUTF8Converter.h"
//
// OSXClipboard
//
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);
m_converters.push_back(new OSXClipboardUTF16Converter);
m_converters.push_back(new OSXClipboardTextConverter);
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));
m_pboard = NULL;
return;
}
OSStatus syncErr = PasteboardSynchronize(m_pboard);
if (syncErr != noErr) {
LOG((CLOG_DEBUG "failed to syncronize clipboard: error %i", syncErr));
}
}
OSXClipboard::~OSXClipboard()
{
clearConverters();
}
bool OSXClipboard::empty()
{
LOG((CLOG_DEBUG "emptying clipboard"));
if (m_pboard == NULL)
return false;
OSStatus err = PasteboardClear(m_pboard);
if (err != noErr) {
LOG((CLOG_DEBUG "failed to clear clipboard: error %i", err));
return false;
}
return true;
}
bool OSXClipboard::synchronize()
{
if (m_pboard == NULL)
return false;
PasteboardSyncFlags flags = PasteboardSynchronize(m_pboard);
LOG((CLOG_DEBUG2 "flags: %x", flags));
if (flags & kPasteboardModified) {
return true;
}
return false;
}
void OSXClipboard::add(EFormat format, const String &data)
{
if (m_pboard == NULL)
return;
LOG((CLOG_DEBUG "add %d bytes to clipboard format: %d", data.size(), format));
if (format == IClipboard::kText) {
LOG((CLOG_DEBUG "format of data to be added to clipboard was kText"));
} else if (format == IClipboard::kBitmap) {
LOG((CLOG_DEBUG "format of data to be added to clipboard was kBitmap"));
} else if (format == IClipboard::kHTML) {
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) {
IOSXClipboardConverter *converter = *index;
// skip converters for other formats
if (converter->getFormat() == format) {
String osXData = converter->fromIClipboard(data);
CFStringRef flavorType = converter->getOSXFormat();
CFDataRef dataRef = CFDataCreate(kCFAllocatorDefault, (UInt8 *)osXData.data(), osXData.size());
PasteboardItemID itemID = 0;
if (dataRef) {
PasteboardPutItemFlavor(m_pboard, itemID, flavorType, dataRef, kPasteboardFlavorNoFlags);
CFRelease(dataRef);
LOG((CLOG_DEBUG "added %d bytes to clipboard format: %d", data.size(), format));
}
}
}
}
bool OSXClipboard::open(Time time) const
{
if (m_pboard == NULL)
return false;
LOG((CLOG_DEBUG "opening clipboard"));
m_time = time;
return true;
}
void OSXClipboard::close() const
{
LOG((CLOG_DEBUG "closing clipboard"));
/* not needed */
}
IClipboard::Time OSXClipboard::getTime() const
{
return m_time;
}
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) {
IOSXClipboardConverter *converter = *index;
if (converter->getFormat() == format) {
PasteboardFlavorFlags flags;
CFStringRef type = converter->getOSXFormat();
OSStatus res;
if ((res = PasteboardGetItemFlavorFlags(m_pboard, item, type, &flags)) == noErr) {
return true;
}
}
}
return false;
}
String OSXClipboard::get(EFormat format) const
{
CFStringRef type;
PasteboardItemID item;
String result;
if (m_pboard == NULL)
return result;
PasteboardGetItemIdentifier(m_pboard, (CFIndex)1, &item);
// 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) {
converter = *index;
PasteboardFlavorFlags flags;
type = converter->getOSXFormat();
if (converter->getFormat() == format && PasteboardGetItemFlavorFlags(m_pboard, item, type, &flags) == noErr) {
break;
}
converter = NULL;
}
// if no converter then we don't recognize any formats
if (converter == NULL) {
LOG((CLOG_DEBUG "unable to find converter for data"));
return result;
}
// get the clipboard data.
CFDataRef buffer = NULL;
try {
OSStatus err = PasteboardCopyItemFlavorData(m_pboard, item, type, &buffer);
if (err != noErr) {
throw err;
}
result = String((char *)CFDataGetBytePtr(buffer), CFDataGetLength(buffer));
} catch (OSStatus err) {
LOG((CLOG_DEBUG "exception thrown in OSXClipboard::get MacError (%d)", err));
} catch (...) {
LOG((CLOG_DEBUG "unknown exception in OSXClipboard::get"));
RETHROW_XTHREAD
}
if (buffer != NULL)
CFRelease(buffer);
return converter->toIClipboard(result);
}
void OSXClipboard::clearConverters()
{
if (m_pboard == NULL)
return;
for (ConverterList::iterator index = m_converters.begin(); index != m_converters.end(); ++index) {
delete *index;
}
m_converters.clear();
}
| 6,455
|
C++
|
.cpp
| 190
| 30.468421
| 114
| 0.714194
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,601
|
IOSXKeyResource.cpp
|
deskflow_deskflow/src/lib/platform/IOSXKeyResource.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/IOSXKeyResource.h"
#include <Carbon/Carbon.h>
KeyID IOSXKeyResource::getKeyID(UInt8 c)
{
if (c == 0) {
return kKeyNone;
} else if (c >= 32 && c < 127) {
// ASCII
return static_cast<KeyID>(c);
} else {
// handle special keys
switch (c) {
case 0x01:
return kKeyHome;
case 0x02:
return kKeyKP_Enter;
case 0x03:
return kKeyKP_Enter;
case 0x04:
return kKeyEnd;
case 0x05:
return kKeyHelp;
case 0x08:
return kKeyBackSpace;
case 0x09:
return kKeyTab;
case 0x0b:
return kKeyPageUp;
case 0x0c:
return kKeyPageDown;
case 0x0d:
return kKeyReturn;
case 0x10:
// OS X maps all the function keys (F1, etc) to this one key.
// we can't determine the right key here so we have to do it
// some other way.
return kKeyNone;
case 0x1b:
return kKeyEscape;
case 0x1c:
return kKeyLeft;
case 0x1d:
return kKeyRight;
case 0x1e:
return kKeyUp;
case 0x1f:
return kKeyDown;
case 0x7f:
return kKeyDelete;
case 0x06:
case 0x07:
case 0x0a:
case 0x0e:
case 0x0f:
case 0x11:
case 0x12:
case 0x13:
case 0x14:
case 0x15:
case 0x16:
case 0x17:
case 0x18:
case 0x19:
case 0x1a:
// discard other control characters
return kKeyNone;
default:
// not special or unknown
break;
}
// create string with character
char str[2];
str[0] = static_cast<char>(c);
str[1] = 0;
// get current keyboard script
TISInputSourceRef isref = TISCopyCurrentKeyboardInputSource();
CFArrayRef langs = (CFArrayRef)TISGetInputSourceProperty(isref, kTISPropertyInputSourceLanguages);
CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding((CFStringRef)CFArrayGetValueAtIndex(langs, 0));
// convert to unicode
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,
// otherwise CFStringCreateMutableCopy() will crash.
if (cfString == NULL) {
return kKeyNone;
}
// convert to precomposed
CFMutableStringRef mcfString = CFStringCreateMutableCopy(kCFAllocatorDefault, 0, cfString);
CFRelease(cfString);
CFStringNormalize(mcfString, kCFStringNormalizationFormC);
// check result
int unicodeLength = CFStringGetLength(mcfString);
if (unicodeLength == 0) {
CFRelease(mcfString);
return kKeyNone;
}
if (unicodeLength > 1) {
// FIXME -- more than one character, we should handle this
CFRelease(mcfString);
return kKeyNone;
}
// get unicode character
UniChar uc = CFStringGetCharacterAtIndex(mcfString, 0);
CFRelease(mcfString);
// convert to KeyID
return static_cast<KeyID>(uc);
}
}
KeyID IOSXKeyResource::unicharToKeyID(UniChar c)
{
switch (c) {
case 3:
return kKeyKP_Enter;
case 8:
return kKeyBackSpace;
case 9:
return kKeyTab;
case 13:
return kKeyReturn;
case 27:
return kKeyEscape;
case 127:
return kKeyDelete;
default:
if (c < 32) {
return kKeyNone;
}
return static_cast<KeyID>(c);
}
}
| 4,079
|
C++
|
.cpp
| 146
| 23.006849
| 120
| 0.686506
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,602
|
MSWindowsPowerManager.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsPowerManager.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2021 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "MSWindowsPowerManager.h"
#include "arch/win32/ArchMiscWindows.h"
MSWindowsPowerManager::~MSWindowsPowerManager()
{
enableSleep();
}
void MSWindowsPowerManager::disableSleep()
{
ArchMiscWindows::addBusyState(ArchMiscWindows::kSYSTEM);
ArchMiscWindows::addBusyState(ArchMiscWindows::kDISPLAY);
}
void MSWindowsPowerManager::enableSleep()
{
// allow the system to enter power saving mode
ArchMiscWindows::removeBusyState(ArchMiscWindows::kSYSTEM);
ArchMiscWindows::removeBusyState(ArchMiscWindows::kDISPLAY);
}
| 1,272
|
C++
|
.cpp
| 34
| 35.5
| 72
| 0.787854
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,603
|
OSXClipboardAnyTextConverter.cpp
|
deskflow_deskflow/src/lib/platform/OSXClipboardAnyTextConverter.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2004 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/OSXClipboardAnyTextConverter.h"
#include <algorithm>
//
// OSXClipboardAnyTextConverter
//
OSXClipboardAnyTextConverter::OSXClipboardAnyTextConverter()
{
// do nothing
}
OSXClipboardAnyTextConverter::~OSXClipboardAnyTextConverter()
{
// do nothing
}
IClipboard::EFormat OSXClipboardAnyTextConverter::getFormat() const
{
return IClipboard::kText;
}
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
{
// convert text then newlines
return convertLinefeedToUnix(doToIClipboard(data));
}
static bool isLF(char ch)
{
return (ch == '\n');
}
static bool isCR(char ch)
{
return (ch == '\r');
}
String OSXClipboardAnyTextConverter::convertLinefeedToMacOS(const String &src)
{
// note -- we assume src is a valid UTF-8 string
String copy = src;
std::replace_if(copy.begin(), copy.end(), isLF, '\r');
return copy;
}
String OSXClipboardAnyTextConverter::convertLinefeedToUnix(const String &src)
{
String copy = src;
std::replace_if(copy.begin(), copy.end(), isCR, '\n');
return copy;
}
| 1,992
|
C++
|
.cpp
| 65
| 28.661538
| 78
| 0.77394
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,604
|
MSWindowsClipboardAnyTextConverter.cpp
|
deskflow_deskflow/src/lib/platform/MSWindowsClipboardAnyTextConverter.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "platform/MSWindowsClipboardAnyTextConverter.h"
//
// MSWindowsClipboardAnyTextConverter
//
MSWindowsClipboardAnyTextConverter::MSWindowsClipboardAnyTextConverter()
{
// do nothing
}
MSWindowsClipboardAnyTextConverter::~MSWindowsClipboardAnyTextConverter()
{
// do nothing
}
IClipboard::EFormat MSWindowsClipboardAnyTextConverter::getFormat() const
{
return IClipboard::kText;
}
HANDLE
MSWindowsClipboardAnyTextConverter::fromIClipboard(const String &data) const
{
// convert linefeeds and then convert to desired encoding
String text = doFromIClipboard(convertLinefeedToWin32(data));
UInt32 size = (UInt32)text.size();
// copy to memory handle
HGLOBAL gData = GlobalAlloc(GMEM_MOVEABLE | GMEM_DDESHARE, size);
if (gData != NULL) {
// get a pointer to the allocated memory
char *dst = (char *)GlobalLock(gData);
if (dst != NULL) {
memcpy(dst, text.data(), size);
GlobalUnlock(gData);
} else {
GlobalFree(gData);
gData = NULL;
}
}
return gData;
}
String MSWindowsClipboardAnyTextConverter::toIClipboard(HANDLE data) const
{
// get datator
const char *src = (const char *)GlobalLock(data);
UInt32 srcSize = (UInt32)GlobalSize(data);
if (src == NULL || srcSize <= 1) {
return String();
}
// convert text
String text = doToIClipboard(String(src, srcSize));
// release handle
GlobalUnlock(data);
// convert newlines
return convertLinefeedToUnix(text);
}
String MSWindowsClipboardAnyTextConverter::convertLinefeedToWin32(const String &src) const
{
// note -- we assume src is a valid UTF-8 string
// count newlines in string
UInt32 numNewlines = 0;
UInt32 n = (UInt32)src.size();
for (const char *scan = src.c_str(); n > 0; ++scan, --n) {
if (*scan == '\n') {
++numNewlines;
}
}
if (numNewlines == 0) {
return src;
}
// allocate new string
String dst;
dst.reserve(src.size() + numNewlines);
// copy string, converting newlines
n = (UInt32)src.size();
for (const char *scan = src.c_str(); n > 0; ++scan, --n) {
if (scan[0] == '\n') {
dst += '\r';
}
dst += scan[0];
}
return dst;
}
String MSWindowsClipboardAnyTextConverter::convertLinefeedToUnix(const String &src) const
{
// count newlines in string
UInt32 numNewlines = 0;
UInt32 n = (UInt32)src.size();
for (const char *scan = src.c_str(); n > 0; ++scan, --n) {
if (scan[0] == '\r' && scan[1] == '\n') {
++numNewlines;
}
}
if (numNewlines == 0) {
return src;
}
// allocate new string
String dst;
dst.reserve(src.size());
// copy string, converting newlines
n = (UInt32)src.size();
for (const char *scan = src.c_str(); n > 0; ++scan, --n) {
if (scan[0] != '\r' || scan[1] != '\n') {
dst += scan[0];
}
}
return dst;
}
| 3,544
|
C++
|
.cpp
| 121
| 26.14876
| 90
| 0.690182
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,605
|
StreamBuffer.cpp
|
deskflow_deskflow/src/lib/io/StreamBuffer.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "io/StreamBuffer.h"
#include "common/common.h"
//
// StreamBuffer
//
const UInt32 StreamBuffer::kChunkSize = 4096;
StreamBuffer::StreamBuffer() : m_size(0), m_headUsed(0)
{
// do nothing
}
StreamBuffer::~StreamBuffer()
{
// do nothing
}
const void *StreamBuffer::peek(UInt32 n)
{
assert(n <= m_size);
// if requesting no data then return NULL so we don't try to access
// an empty list.
if (n == 0) {
return NULL;
}
// reserve space in first chunk
ChunkList::iterator head = m_chunks.begin();
head->reserve(n + m_headUsed);
// consolidate chunks into the first chunk until it has n bytes
ChunkList::iterator scan = head;
++scan;
while (head->size() - m_headUsed < n && scan != m_chunks.end()) {
head->insert(head->end(), scan->begin(), scan->end());
scan = m_chunks.erase(scan);
}
return static_cast<const void *>(&(head->begin()[m_headUsed]));
}
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;
m_headUsed = 0;
m_chunks.clear();
return;
}
// update size
m_size -= n;
// discard chunks until more than n bytes would've been discarded
ChunkList::iterator scan = m_chunks.begin();
assert(scan != m_chunks.end());
while (scan->size() - m_headUsed <= n) {
n -= (UInt32)scan->size() - m_headUsed;
m_headUsed = 0;
scan = m_chunks.erase(scan);
assert(scan != m_chunks.end());
}
// remove left over bytes from the head chunk
if (n > 0) {
m_headUsed += n;
}
}
void StreamBuffer::write(const void *vdata, UInt32 n)
{
assert(vdata != NULL);
// ignore if no data, otherwise update size
if (n == 0) {
return;
}
m_size += n;
// cast data to bytes
const UInt8 *data = static_cast<const UInt8 *>(vdata);
// point to last chunk if it has space, otherwise append an empty chunk
ChunkList::iterator scan = m_chunks.end();
if (scan != m_chunks.begin()) {
--scan;
if (scan->size() >= kChunkSize) {
++scan;
}
}
if (scan == m_chunks.end()) {
scan = m_chunks.insert(scan, Chunk());
}
// append data in chunks
while (n > 0) {
// choose number of bytes for next chunk
assert(scan->size() <= kChunkSize);
UInt32 count = kChunkSize - (UInt32)scan->size();
if (count > n)
count = n;
// transfer data
scan->insert(scan->end(), data, data + count);
n -= count;
data += count;
// append another empty chunk if we're not done yet
if (n > 0) {
++scan;
scan = m_chunks.insert(scan, Chunk());
}
}
}
UInt32 StreamBuffer::getSize() const
{
return m_size;
}
| 3,387
|
C++
|
.cpp
| 119
| 25.226891
| 73
| 0.659273
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,606
|
StreamFilter.cpp
|
deskflow_deskflow/src/lib/io/StreamFilter.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2004 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "io/StreamFilter.h"
#include "base/IEventQueue.h"
#include "base/TMethodEventJob.h"
//
// StreamFilter
//
StreamFilter::StreamFilter(IEventQueue *events, deskflow::IStream *stream, bool adoptStream)
: m_stream(stream),
m_adopted(adoptStream),
m_events(events)
{
// replace handlers for m_stream
m_events->removeHandlers(m_stream->getEventTarget());
m_events->adoptHandler(
Event::kUnknown, m_stream->getEventTarget(),
new TMethodEventJob<StreamFilter>(this, &StreamFilter::handleUpstreamEvent)
);
}
StreamFilter::~StreamFilter()
{
m_events->removeHandler(Event::kUnknown, m_stream->getEventTarget());
if (m_adopted) {
delete m_stream;
}
}
void StreamFilter::close()
{
getStream()->close();
}
UInt32 StreamFilter::read(void *buffer, UInt32 n)
{
return getStream()->read(buffer, n);
}
void StreamFilter::write(const void *buffer, UInt32 n)
{
getStream()->write(buffer, n);
}
void StreamFilter::flush()
{
getStream()->flush();
}
void StreamFilter::shutdownInput()
{
getStream()->shutdownInput();
}
void StreamFilter::shutdownOutput()
{
getStream()->shutdownOutput();
}
void *StreamFilter::getEventTarget() const
{
return const_cast<void *>(static_cast<const void *>(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()));
}
void StreamFilter::handleUpstreamEvent(const Event &event, void *)
{
filterEvent(event);
}
| 2,442
|
C++
|
.cpp
| 90
| 25
| 92
| 0.747003
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,607
|
XIO.cpp
|
deskflow_deskflow/src/lib/io/XIO.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "io/XIO.h"
//
// XIOClosed
//
String XIOClosed::getWhat() const throw()
{
return format("XIOClosed", "already closed");
}
//
// XIOEndOfStream
//
String XIOEndOfStream::getWhat() const throw()
{
return format("XIOEndOfStream", "reached end of stream");
}
//
// XIOWouldBlock
//
String XIOWouldBlock::getWhat() const throw()
{
return format("XIOWouldBlock", "stream operation would block");
}
| 1,144
|
C++
|
.cpp
| 39
| 27.589744
| 72
| 0.750455
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,608
|
messages.cpp
|
deskflow_deskflow/src/lib/gui/messages.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "messages.h"
#include "Logger.h"
#include "common/constants.h"
#include "common/version.h"
#include "constants.h"
#include "env_vars.h"
#include "styles.h"
#include <QAction>
#include <QDateTime>
#include <QDir>
#include <QMessageBox>
#include <QPushButton>
#include <QTime>
#include <memory>
namespace deskflow::gui::messages {
struct Errors
{
static std::unique_ptr<QMessageBox> s_criticalMessage;
static QStringList s_ignoredErrors;
};
std::unique_ptr<QMessageBox> Errors::s_criticalMessage;
QStringList Errors::s_ignoredErrors;
void raiseCriticalDialog()
{
if (Errors::s_criticalMessage) {
Errors::s_criticalMessage->raise();
}
}
void showErrorDialog(const QString &message, const QString &fileLine, QtMsgType type)
{
auto title = type == QtFatalMsg ? "Fatal error" : "Critical error";
QString text;
if (type == QtFatalMsg) {
text = "<p>Sorry, a fatal error has occurred and the application must "
"now exit.</p>";
} else {
text = "<p>Sorry, a critical error has occurred.</p>";
}
text += QString(R"(<p>Please <a href="%1" style="color: %2">report a bug</a>)"
" and copy/paste the following error:</p>")
.arg(kUrlHelp, kColorSecondary);
const QString version = QString::fromStdString(deskflow::version());
text += QString("<pre>v%1\n%2\n%3</pre>").arg(version, message, fileLine);
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);
critical.exec();
} else if (!Errors::s_ignoredErrors.contains(message)) {
// prevent message boxes piling up by deleting the last one if it exists.
// if none exists yet, then nothing will happen.
Errors::s_criticalMessage.reset();
// as we don't abort for critical messages, create a new non-blocking
// 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>(QMessageBox::Critical, title, text, QMessageBox::Ok | QMessageBox::Ignore);
Errors::s_criticalMessage->open();
QAction::connect(
Errors::s_criticalMessage.get(), &QMessageBox::finished, //
[message](int result) {
if (result == QMessageBox::Ignore) {
Errors::s_ignoredErrors.append(message);
}
}
);
}
}
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)
{
const auto fileLine = messages::fileLine(context);
Logger::instance().handleMessage(type, fileLine, message);
if (type == QtFatalMsg || type == QtCriticalMsg) {
showErrorDialog(message, fileLine, type);
}
if (type == QtFatalMsg) {
// developers: if you hit this line in your debugger, traverse the stack
// to find the cause of the fatal error. important: crash the app on fatal
// error to prevent the app being used in a broken state.
//
// hint: if you don't want to crash, but still want to show an error
// message, use `qCritical()` instead of `qFatal()`. you should use
// fatal errors when the app is in an unrecoverable state; i.e. it cannot
// function correctly in it's current state and must be restarted.
abort();
}
}
void showCloseReminder(QWidget *parent)
{
QString message = QString("<p>%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.</p>")
.arg(kAppName);
#if defined(Q_OS_LINUX)
message += QString("<p>On some Linux systems such as GNOME 3, the "
"notification area might be disabled. "
"You may need to "
R"(<a href="%1" %2>enable an extension</a>)"
" to see the %3 tray icon.</p>")
.arg(kUrlGnomeTrayFix, kStyleLink, kAppName);
#endif
QMessageBox::information(parent, "Notification area icon", message);
}
void showFirstServerStartMessage(QWidget *parent)
{
QMessageBox::information(
parent, "Server is running",
QString("<p>Great, the %1 server is now running.</p>"
"<p>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.</p>")
.arg(kAppName)
);
}
void showFirstConnectedMessage(QWidget *parent, bool closeToTray, bool enableService, bool isServer)
{
auto message = QString("<p>%1 is now connected!</p>").arg(kAppName);
if (isServer) {
message += "<p>Try moving your mouse to your other computer. Once there, go ahead "
"and type something.</p>"
"<p>Don't forget, you can copy and paste between computers too.</p>";
} else {
message += "<p>Try controlling this computer remotely.</p>";
}
if (!closeToTray && !enableService) {
message += QString("<p>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.</p>")
.arg(kAppName);
} else {
message += QString("<p>You can now close this window and %1 will continue to run in "
"the background. This setting can be disabled.</p>")
.arg(kAppName);
}
QMessageBox::information(parent, "Connected", message);
}
void showClientConnectError(QWidget *parent, ClientError error, const QString &address)
{
using enum ClientError;
auto message = QString("<p>The connection to server '%1' didn't work.</p>").arg(address);
if (error == AlreadyConnected) {
message += //
"<p>Two of your client computers have the same name or there are "
"two instances of the client process running.</p>"
"<p>Please ensure that you're using a unique name and that only a "
"single client process is running.</p>";
} else if (error == HostnameError) {
message += //
"<p>Please try to connect to the server using the server IP address "
"instead of the hostname. </p>"
"<p>If that doesn't work, please check your TLS and "
"firewall settings.</p>";
} else if (error == GenericError) {
message += //
"<p>Please check your TLS and firewall settings.</p>";
} else {
qFatal("unknown client error");
}
QMessageBox dialog(parent);
dialog.addButton(QObject::tr("Close"), QMessageBox::RejectRole);
dialog.setText(message);
dialog.exec();
}
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));
message.exec();
if (message.clickedButton() == add) {
return Add;
} else if (message.clickedButton() == ignore) {
return Ignore;
} else {
qFatal("no expected dialog button was clicked");
abort();
}
}
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("<p>Are you sure you want to clear all settings and restart %1?</p>"
"<p>This action cannot be undone.</p>")
.arg(kAppName));
message.exec();
return message.clickedButton() == clear;
}
void showReadOnlySettings(QWidget *parent, const QString &systemSettingsPath)
{
QString nativePath = QDir::toNativeSeparators(systemSettingsPath);
QMessageBox::information(
parent, "Read-only settings",
QString("<p>Settings are read-only because you only have read access "
"to the file:</p><p>%1</p>")
.arg(nativePath)
);
}
void showWaylandLibraryError(QWidget *parent)
{
QMessageBox::critical(
parent, "Library problem",
QString("<p>Sorry, while this version of %1 does support Wayland, "
"this build was not linked with one or more of the required "
"libraries.</p>"
"<p>Please either switch to X from your login screen or use a build "
"that uses the correct libraries.</p>"
"<p>If you think this is incorrect, please "
R"(<a href="%2" style="color: %3">report a bug</a>.</p>)"
"<p>Please check the logs for more information.</p>")
.arg(kAppName, kUrlHelp, kColorSecondary)
);
}
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("<p>Would you like to check for updates when %1 starts?</p>"
"<p>Checking for updates requires an Internet connection.</p>"
"<p>URL: <pre>%2</pre></p>")
.arg(kAppName, env_vars::versionUrl()));
message.exec();
return message.clickedButton() == checkButton;
}
} // namespace deskflow::gui::messages
| 10,617
|
C++
|
.cpp
| 254
| 35.92126
| 113
| 0.667345
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,609
|
Logger.cpp
|
deskflow_deskflow/src/lib/gui/Logger.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Logger.h"
#include "string_utils.h"
#include <QDateTime>
#include <QDir>
#include <QMessageBox>
#include <QTime>
#if defined(Q_OS_WIN)
#include <Windows.h>
#endif
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."
};
Logger Logger::s_instance;
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, type, message);
QTextStream stream(&logLine);
stream << Qt::endl;
if (!fileLine.isEmpty()) {
stream << "\t" + fileLine << Qt::endl;
}
auto logLineBytes = logLine.toUtf8();
auto logLine_c = logLineBytes.constData();
#if defined(Q_OS_WIN)
// Debug output is viewable using either VS Code, Visual Studio, DebugView, or
// DbgView++ (only one can be used at once). It's important to send output to
// the debug output API, because it's difficult to view stdout and stderr from
// a Windows GUI app.
OutputDebugStringA(logLine_c);
#else
fprintf(out, "%s", logLine_c);
fflush(out);
#endif
return logLine;
}
void Logger::loadEnvVars()
{
const auto debugEnvVar = qEnvironmentVariable("DESKFLOW_GUI_DEBUG");
if (!debugEnvVar.isEmpty()) {
m_debug = strToTrue(debugEnvVar);
}
const auto verboseEnvVar = qEnvironmentVariable("DESKFLOW_GUI_VERBOSE");
if (!verboseEnvVar.isEmpty()) {
m_verbose = strToTrue(verboseEnvVar);
}
}
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)
{
auto mutatedType = type;
if (kForceDebugMessages.contains(message)) {
mutatedType = QtDebugMsg;
}
QString typeString;
auto out = stdout;
switch (mutatedType) {
case QtDebugMsg:
typeString = "DEBUG";
if (!m_debug) {
return;
}
break;
case QtInfoMsg:
typeString = "INFO";
break;
case QtWarningMsg:
typeString = "WARNING";
out = stderr;
break;
case QtCriticalMsg:
typeString = "CRITICAL";
out = stderr;
break;
case QtFatalMsg:
typeString = "FATAL";
out = stderr;
break;
}
const auto logLine = printLine(out, typeString, message, fileLine);
Q_EMIT newLine(logLine);
}
} // namespace deskflow::gui
| 3,311
|
C++
|
.cpp
| 107
| 27.971963
| 103
| 0.722816
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,610
|
dotenv.cpp
|
deskflow_deskflow/src/lib/gui/dotenv.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "dotenv.h"
#include "paths.h"
#include <QCoreApplication>
#include <QDebug>
#include <QDir>
#include <QFile>
#include <QProcess>
#include <QProcessEnvironment>
#include <QStandardPaths>
#include <QString>
#include <QTextStream>
namespace deskflow::gui {
QPair<QString, QString> getPair(const QString &line);
bool open(QFile &file, const QString &filePath)
{
file.setFileName(filePath);
return file.open(QIODevice::ReadOnly | QIODevice::Text);
}
/**
* @brief A _very_ basic Qt .env file parser.
*
* This function re-invents the wheel to save adding a library dependency.
* It does not support many things that a proper .env parser would, such as
* trailing comments, escaping characters, multiline values, etc.
*
* If this function is not sufficient, replace it with a library such as:
* https://github.com/adeharo9/cpp-dotenv
*/
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()));
// 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
// predictable location for the .env file.
const auto orgDir = paths::configDir();
filePath = orgDir.filePath(filename);
if (!open(file, filePath)) {
qInfo("no %s file in app config dir: %s", qPrintable(filename), qPrintable(orgDir.absolutePath()));
return;
}
}
qInfo("loading env vars from: %s", qPrintable(filePath));
QTextStream in(&file);
while (!in.atEnd()) {
QString line = in.readLine().trimmed();
if (line.startsWith('#'))
continue;
auto [key, value] = getPair(line);
if (key.isEmpty() || value.isEmpty())
continue;
const auto keyBytes = key.toUtf8();
const auto valueBytes = value.toUtf8();
const auto &key_c = keyBytes.constData();
const auto &value_c = valueBytes.constData();
qDebug("%s=%s", key_c, value_c);
qputenv(keyBytes, valueBytes);
}
}
QString stripQuotes(const QString &value)
{
QString result = value;
if (result.startsWith('"') && result.endsWith('"')) {
result = result.mid(1, result.length() - 2);
}
return result;
}
QPair<QString, QString> getPair(const QString &line)
{
auto pos = line.indexOf('=');
if (pos == -1) {
return QPair<QString, QString>("", "");
}
QString key = line.left(pos);
QString value = line.mid(pos + 1);
return QPair<QString, QString>(key.trimmed(), stripQuotes(value.trimmed()));
}
} // namespace deskflow::gui
| 3,320
|
C++
|
.cpp
| 97
| 31.247423
| 105
| 0.710584
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,611
|
diagnostic.cpp
|
deskflow_deskflow/src/lib/gui/diagnostic.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "diagnostic.h"
#include "config/ConfigScopes.h"
#include "paths.h"
#include <QApplication>
#include <QDir>
#include <QProcess>
namespace deskflow::gui::diagnostic {
void restart()
{
QString program = QCoreApplication::applicationFilePath();
QStringList arguments = QCoreApplication::arguments();
// prevent infinite reset loop when env var set.
arguments << "--no-reset";
qInfo("launching new process: %s", qPrintable(program));
QProcess::startDetached(program, arguments);
qDebug("exiting current process");
QApplication::exit();
}
void clearSettings(ConfigScopes &scopes, bool enableRestart)
{
qDebug("clearing settings");
scopes.clear();
// save but do not emit saving signal which will prevent the current state of
// the app config and server configs from being applied.
scopes.save(false);
auto configDir = paths::configDir();
qDebug("removing config dir: %s", qPrintable(configDir.absolutePath()));
configDir.removeRecursively();
auto profileDir = paths::coreProfileDir();
qDebug("removing profile dir: %s", qPrintable(profileDir.absolutePath()));
profileDir.removeRecursively();
if (enableRestart) {
qDebug("restarting");
restart();
} else {
qDebug("skipping restart");
}
}
} // namespace deskflow::gui::diagnostic
| 1,988
|
C++
|
.cpp
| 55
| 33.6
| 79
| 0.752475
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,612
|
VersionChecker.cpp
|
deskflow_deskflow/src/lib/gui/VersionChecker.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "VersionChecker.h"
#include "common/constants.h"
#include "env_vars.h"
#include <QLocale>
#include <QNetworkAccessManager>
#include <QNetworkReply>
#include <QNetworkRequest>
#include <QProcess>
#include <QRegularExpression>
#include <memory>
using namespace deskflow::gui;
VersionChecker::VersionChecker(std::shared_ptr<QNetworkAccessManagerProxy> network)
: m_network(network ? network : std::make_shared<QNetworkAccessManagerProxy>())
{
m_network->init();
connect(m_network.get(), &QNetworkAccessManagerProxy::finished, this, &VersionChecker::replyFinished);
}
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, kVersion, QSysInfo::prettyProductName());
request.setHeader(QNetworkRequest::UserAgentHeader, userAgent);
request.setRawHeader("X-Deskflow-Version", kVersion);
request.setRawHeader("X-Deskflow-Language", QLocale::system().name().toStdString().c_str());
m_network->get(request);
}
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("error checking for updates, http status: %d", httpStatus);
return;
}
qInfo("version check server success, http status: %d", httpStatus);
const auto newestVersion = QString(reply->readAll());
qDebug("version check response: %s", qPrintable(newestVersion));
if (!newestVersion.isEmpty() && compareVersions(DESKFLOW_VERSION, newestVersion) > 0) {
qDebug("update found");
Q_EMIT updateFound(newestVersion);
} else {
qDebug("no updates found");
}
}
int VersionChecker::getStageVersion(QString stage)
{
const char *stableName = "stable";
const char *rcName = "rc";
const char *betaName = "beta";
// use max int for stable so it's always the highest value.
const int stableValue = INT_MAX;
const int rcValue = 2;
const int betaValue = 1;
const int otherValue = 0;
if (stage.isEmpty() || stage == stableName) {
return stableValue;
} else if (stage.toLower().startsWith(rcName)) {
static QRegularExpression re("\\d*", QRegularExpression::CaseInsensitiveOption);
auto match = re.match(stage);
if (match.hasMatch()) {
// return the rc value plus the rc number (e.g. 2 + 1)
// this should be ok since stable is max int.
return rcValue + match.captured(1).toInt();
}
} else if (stage == betaName) {
return betaValue;
}
return otherValue;
}
int VersionChecker::compareVersions(const QString &left, const QString &right)
{
if (left.compare(right) == 0)
return 0; // versions are same.
QStringList leftParts = left.split("-");
QStringList rightParts = right.split("-");
QStringList leftNumberParts = left.split(".");
QStringList rightNumberParts = right.split(".");
auto leftStagePart = leftParts.size() > 1 ? leftParts.at(1) : "";
auto rightStagePart = rightParts.size() > 1 ? rightParts.at(1) : "";
const int leftMajor = leftNumberParts.at(0).toInt();
const int leftMinor = leftNumberParts.at(1).toInt();
const int leftPatch = leftNumberParts.at(2).toInt();
const int leftStage = getStageVersion(leftStagePart);
const int rightMajor = rightNumberParts.at(0).toInt();
const int rightMinor = rightNumberParts.at(1).toInt();
const int rightPatch = rightNumberParts.at(2).toInt();
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));
return rightWins ? 1 : -1;
}
| 4,733
|
C++
|
.cpp
| 111
| 39.594595
| 120
| 0.728261
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,613
|
QNetworkAccessManagerProxy.cpp
|
deskflow_deskflow/src/lib/gui/proxy/QNetworkAccessManagerProxy.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "QNetworkAccessManagerProxy.h"
#include <QNetworkAccessManager>
#include <QtNetwork/QNetworkReply>
namespace deskflow::gui::proxy {
void QNetworkAccessManagerProxy::init()
{
m_network = std::make_shared<QNetworkAccessManager>();
connect(m_network.get(), &QNetworkAccessManager::finished, this, [this](QNetworkReply *reply) {
Q_EMIT finished(reply);
});
}
void QNetworkAccessManagerProxy::get(const QNetworkRequest &request) const
{
m_network->get(request);
}
} // namespace deskflow::gui::proxy
| 1,209
|
C++
|
.cpp
| 32
| 35.71875
| 97
| 0.769231
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,614
|
QSettingsProxy.cpp
|
deskflow_deskflow/src/lib/gui/proxy/QSettingsProxy.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "QSettingsProxy.h"
#include "common/constants.h"
#include "gui/Logger.h"
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QSettings>
#include <memory>
namespace deskflow::gui::proxy {
const auto kLegacyOrgDomain = "http-symless-com";
const auto kLegacySystemConfigFilename = "SystemConfig.ini";
#if defined(Q_OS_UNIX)
const auto kUnixSystemConfigPath = "/usr/local/etc/";
#endif
//
// Free functions
//
/**
* @brief The base dir for the system settings file.
*
* 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()
{
#if defined(Q_OS_WIN)
return QCoreApplication::applicationDirPath();
#elif defined(Q_OS_UNIX)
// Qt already adds application and filename to the end of the path.
// On macOS, it would be nice to use /Library dir, but qt has no elevate
// system.
return kUnixSystemConfigPath;
#else
#error "unsupported platform"
#endif
}
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 oldSystemSettings(
QSettings::IniFormat, QSettings::SystemScope, QCoreApplication::organizationName(),
QCoreApplication::applicationName()
);
if (QFile(oldSystemSettings.fileName()).exists()) {
const auto keys = oldSystemSettings.allKeys();
for (const auto &key : keys) {
settings.setValue(key, oldSystemSettings.value(key));
}
}
QSettings::setPath(QSettings::IniFormat, QSettings::SystemScope, getSystemSettingsBaseDir());
}
void migrateLegacyUserSettings(QSettings &newSettings)
{
QString newPath = newSettings.fileName();
QFile newFile(newPath);
if (newFile.exists()) {
qInfo("user settings already exist, skipping migration");
return;
}
QSettings oldSettings(kLegacyOrgDomain, kAppName);
QString oldPath = oldSettings.fileName();
if (oldPath.isEmpty()) {
qInfo("no legacy settings to migrate, filename empty");
return;
}
if (!QFile(oldPath).exists()) {
qInfo("no legacy settings to migrate, file does not exist");
return;
}
QFileInfo oldFileInfo(oldPath);
QFileInfo newFileInfo(newPath);
qDebug(
"migrating legacy settings: '%s' -> '%s'", //
qPrintable(oldFileInfo.fileName()), qPrintable(newFileInfo.fileName())
);
QStringList keys = oldSettings.allKeys();
for (const QString &key : std::as_const(keys)) {
QVariant oldValue = oldSettings.value(key);
newSettings.setValue(key, oldValue);
logVerbose(QString("migrating setting '%1' = '%2'").arg(key, oldValue.toString()));
}
newSettings.sync();
}
//
// QSettingsProxy
//
void QSettingsProxy::loadUser()
{
m_pSettings = std::make_unique<QSettings>();
#if defined(Q_OS_MAC)
// on mac, we used to save settings to "com.http-symless-com.Deskflow.plist"
// because `setOrganizationName` was historically called using a url instead
// of an actual domain (e.g. deskflow.org).
migrateLegacyUserSettings(*m_pSettings);
#endif // Q_OS_MAC
}
void QSettingsProxy::loadSystem()
{
auto orgName = QCoreApplication::organizationName();
if (orgName.isEmpty()) {
qFatal("unable to load config, organization name is empty");
return;
} else {
qDebug() << "org name for config:" << orgName;
}
auto appName = QCoreApplication::applicationName();
if (appName.isEmpty()) {
qFatal("unable to load config, application name is empty");
return;
} else {
qDebug() << "app name for config:" << appName;
}
QSettings::setPath(QSettings::Format::IniFormat, QSettings::Scope::SystemScope, getSystemSettingsBaseDir());
m_pSettings =
std::make_unique<QSettings>(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)
{
return m_pSettings->beginReadArray(prefix);
}
void QSettingsProxy::setArrayIndex(int i)
{
m_pSettings->setArrayIndex(i);
}
QVariant QSettingsProxy::value(const QString &key) const
{
return m_pSettings->value(key);
}
QVariant QSettingsProxy::value(const QString &key, const QVariant &defaultValue) const
{
return m_pSettings->value(key, defaultValue);
}
void QSettingsProxy::endArray()
{
m_pSettings->endArray();
}
void QSettingsProxy::beginWriteArray(const QString &prefix)
{
m_pSettings->beginWriteArray(prefix);
}
void QSettingsProxy::setValue(const QString &key, const QVariant &value)
{
m_pSettings->setValue(key, value);
}
void QSettingsProxy::beginGroup(const QString &prefix)
{
m_pSettings->beginGroup(prefix);
}
void QSettingsProxy::remove(const QString &key)
{
m_pSettings->remove(key);
}
void QSettingsProxy::endGroup()
{
m_pSettings->endGroup();
}
bool QSettingsProxy::isWritable() const
{
return m_pSettings->isWritable();
}
bool QSettingsProxy::contains(const QString &key) const
{
return m_pSettings->contains(key);
}
} // namespace deskflow::gui::proxy
| 5,905
|
C++
|
.cpp
| 188
| 28.840426
| 113
| 0.747181
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,615
|
QProcessProxy.cpp
|
deskflow_deskflow/src/lib/gui/proxy/QProcessProxy.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "QProcessProxy.h"
namespace deskflow::gui::proxy {
void QProcessProxy::create()
{
m_pProcess = std::make_unique<QProcess>();
connect(m_pProcess.get(), &QProcess::finished, this, [this](int exitCode, QProcess::ExitStatus exitStatus) {
Q_EMIT finished(exitCode, exitStatus);
});
connect(
m_pProcess.get(), &QProcess::readyReadStandardOutput, //
this, [this]() { Q_EMIT readyReadStandardOutput(); }
);
connect(
m_pProcess.get(), &QProcess::readyReadStandardError, //
this, [this]() { Q_EMIT readyReadStandardError(); }
);
}
QProcessProxy::operator bool() const
{
return m_pProcess.get();
}
void QProcessProxy::start(const QString &program, const QStringList &arguments)
{
m_pProcess->start(program, arguments);
}
bool QProcessProxy::waitForStarted()
{
return m_pProcess->waitForStarted();
}
QProcess::ProcessState QProcessProxy::state() const
{
return m_pProcess->state();
}
void QProcessProxy::close()
{
m_pProcess->close();
}
QString QProcessProxy::readAllStandardOutput()
{
return m_pProcess->readAllStandardOutput();
}
QString QProcessProxy::readAllStandardError()
{
return m_pProcess->readAllStandardError();
}
} // namespace deskflow::gui::proxy
| 1,914
|
C++
|
.cpp
| 62
| 28.5
| 110
| 0.745919
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,616
|
TlsCertificate.cpp
|
deskflow_deskflow/src/lib/gui/tls/TlsCertificate.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2015 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "TlsCertificate.h"
#include "TlsFingerprint.h"
#include "common/constants.h"
#include <QCoreApplication>
#include <QDir>
#include <QProcess>
static const char *const kCertificateKeyLength = "rsa:";
static const char *const kCertificateHashAlgorithm = "-sha256";
static const char *const kCertificateLifetime = "365";
#if defined(Q_OS_WIN)
static const char *const kWinOpenSslDir = "OpenSSL";
static const char *const kWinOpenSslBinary = "openssl.exe";
static const char *const kConfigFile = "openssl.cnf";
#elif defined(Q_OS_UNIX)
static const char *const kUnixOpenSslCommand = "openssl";
#endif
#if defined(Q_OS_WIN)
namespace deskflow::gui {
QString openSslWindowsDir()
{
auto appDir = QDir(QCoreApplication::applicationDirPath());
auto openSslDir = QDir(appDir.filePath(kWinOpenSslDir));
// in production, openssl is deployed with the app.
// in development, we can use the openssl path available at compile-time.
if (!openSslDir.exists()) {
openSslDir = QDir(OPENSSL_EXE_DIR);
}
// if the path still isn't found, something is seriously wrong.
const auto path = openSslDir.absolutePath();
if (openSslDir.exists()) {
qDebug("openssl dir: %s", qUtf8Printable(path));
} else {
qFatal("openssl dir not found: %s", qUtf8Printable(path));
}
return QDir::cleanPath(path);
}
QString openSslWindowsBinary()
{
auto dir = QDir(openSslWindowsDir());
auto path = dir.filePath(kWinOpenSslBinary);
// when installed, there is no openssl bin dir; it's installed at the base.
// in development, we use the standard dir structure for openssl (bin dir).
if (!QFile::exists(path)) {
auto binDir = QDir(dir.filePath("bin"));
path = binDir.filePath(kWinOpenSslBinary);
}
// if the path still isn't found, something is seriously wrong.
if (!QFile::exists(path)) {
qFatal() << "openssl binary not found: " << path;
}
return path;
}
} // namespace deskflow::gui
using namespace deskflow::gui;
#endif
TlsCertificate::TlsCertificate(QObject *parent) : QObject(parent)
{
}
bool TlsCertificate::runTool(const QStringList &args)
{
#if defined(Q_OS_WIN)
const auto program = openSslWindowsBinary();
#else
const auto program = kUnixOpenSslCommand;
#endif
QStringList environment;
// Windows is special! :)
// For OpenSSL, it's very common to bundle the openssl.exe and openssl.cnf files
// with the application. This is made a little more complex in the Windows dev
// env, because vcpkg can't find the openssl.cnf file by default, so we need to
// give it a bit of guidance by setting the `OPENSSL_CONF` env var.
#if defined(Q_OS_WIN)
const auto openSslDir = QDir(openSslWindowsDir());
const auto config = QDir::cleanPath(openSslDir.filePath(kConfigFile));
environment << QString("OPENSSL_CONF=%1").arg(config);
#endif
QProcess process;
process.setEnvironment(environment);
for (const auto &envVar : std::as_const(environment)) {
qDebug("set env var: %s", qUtf8Printable(envVar));
}
qDebug("running: %s %s", qUtf8Printable(program), qUtf8Printable(args.join(" ")));
process.start(program, args);
bool success = process.waitForStarted();
QString toolStderr;
if (success && process.waitForFinished()) {
m_toolStdout = process.readAllStandardOutput().trimmed();
toolStderr = process.readAllStandardError().trimmed();
}
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));
return false;
}
return true;
}
bool TlsCertificate::generateCertificate(const QString &path, int keyLength)
{
qDebug("generating tls certificate: %s", qUtf8Printable(path));
QFileInfo info(path);
QDir dir(info.absolutePath());
if (!dir.exists() && !dir.mkpath(".")) {
qCritical("failed to create directory for tls certificate");
return false;
}
QString keySize = kCertificateKeyLength + QString::number(keyLength);
QStringList arguments;
// self signed certificate
arguments.append("req");
arguments.append("-x509");
arguments.append("-nodes");
// valid duration
arguments.append("-days");
arguments.append(kCertificateLifetime);
// subject information
arguments.append("-subj");
QString subInfo("/CN=%1");
arguments.append(subInfo.arg(kAppName));
// private key
arguments.append("-newkey");
arguments.append(keySize);
// key output filename
arguments.append("-keyout");
arguments.append(path);
// certificate output filename
arguments.append("-out");
arguments.append(path);
if (runTool(arguments)) {
qDebug("tls certificate generated");
return generateFingerprint(path);
} else {
qCritical("failed to generate tls certificate");
return false;
}
}
bool TlsCertificate::generateFingerprint(const QString &certificateFilename)
{
qDebug("generating tls fingerprint");
QStringList arguments;
arguments.append("x509");
arguments.append("-fingerprint");
arguments.append(kCertificateHashAlgorithm);
arguments.append("-noout");
arguments.append("-in");
arguments.append(certificateFilename);
if (!runTool(arguments)) {
qCritical("failed to generate tls fingerprint");
return false;
}
// find the fingerprint from the tool output
auto i = m_toolStdout.indexOf("=");
if (i != -1) {
i++;
QString fingerprint = m_toolStdout.mid(i, m_toolStdout.size() - i);
TlsFingerprint::local().trust(fingerprint, false);
qDebug("tls fingerprint generated");
return true;
} else {
qCritical("failed to find tls fingerprint in tls tool output");
return false;
}
}
int TlsCertificate::getCertKeyLength(const QString &path)
{
QStringList arguments;
arguments.append("rsa");
arguments.append("-in");
arguments.append(path);
arguments.append("-text");
arguments.append("-noout");
if (!runTool(arguments)) {
qFatal("failed to get key length from certificate");
return 0;
}
const QString searchStart("Private-Key: (");
const QString searchEnd(" bit");
// Get the line that contains the key length from the output
const auto indexStart = m_toolStdout.indexOf(searchStart);
const auto indexEnd = m_toolStdout.indexOf(searchEnd, indexStart);
const auto start = indexStart + searchStart.length();
const auto end = indexEnd - (indexStart + searchStart.length());
auto keyLength = m_toolStdout.mid(start, end);
return keyLength.toInt();
}
| 7,182
|
C++
|
.cpp
| 200
| 32.955
| 87
| 0.737298
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,617
|
TlsFingerprint.cpp
|
deskflow_deskflow/src/lib/gui/tls/TlsFingerprint.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2015 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "TlsFingerprint.h"
#include "gui/core/CoreTool.h"
#include <QDir>
#include <QTextStream>
// TODO: Reduce duplication of these strings between here and SecureSocket.cpp
static const char kDirName[] = "tls";
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)
{
}
void TlsFingerprint::trust(const QString &fingerprintText, bool append) const
{
TlsFingerprint::persistDirectory();
QIODevice::OpenMode openMode;
if (append) {
openMode = QIODevice::Append;
} else {
openMode = QIODevice::WriteOnly;
}
QFile file(filePath());
if (file.open(openMode)) {
QTextStream out(&file);
out << fingerprintText << "\n";
file.close();
}
}
bool TlsFingerprint::fileExists() const
{
QString dirName = TlsFingerprint::directoryPath();
if (!QDir(dirName).exists()) {
return false;
}
QFile file(filePath());
return file.exists();
}
bool TlsFingerprint::isTrusted(const QString &fingerprintText) const
{
const QStringList list = readList();
for (const auto &trusted : list) {
if (trusted == fingerprintText) {
return true;
}
}
return false;
}
QStringList TlsFingerprint::readList(const int readTo) const
{
QStringList list;
QString dirName = TlsFingerprint::directoryPath();
if (!QDir(dirName).exists()) {
return list;
}
QFile file(filePath());
if (file.open(QIODevice::ReadOnly)) {
QTextStream in(&file);
while (!in.atEnd()) {
list.append(in.readLine());
if (list.size() == readTo) {
break;
}
}
file.close();
}
return list;
}
QString TlsFingerprint::readFirst() const
{
QStringList list = readList(1);
return list.at(0);
}
QString TlsFingerprint::filePath() const
{
QString dir = TlsFingerprint::directoryPath();
return QString("%1/%2").arg(dir, m_Filename);
}
void TlsFingerprint::persistDirectory()
{
QDir dir(TlsFingerprint::directoryPath());
if (!dir.exists()) {
dir.mkpath(".");
}
}
QString TlsFingerprint::directoryPath()
{
CoreTool coreTool;
QString profileDir = coreTool.getProfileDir();
return QString("%1/%2").arg(profileDir, kDirName);
}
TlsFingerprint TlsFingerprint::local()
{
return TlsFingerprint(kLocalFilename);
}
TlsFingerprint TlsFingerprint::trustedServers()
{
return TlsFingerprint(kTrustedServersFilename);
}
TlsFingerprint TlsFingerprint::trustedClients()
{
return TlsFingerprint(kTrustedClientsFilename);
}
| 3,306
|
C++
|
.cpp
| 118
| 25.29661
| 78
| 0.737358
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,618
|
TlsUtility.cpp
|
deskflow_deskflow/src/lib/gui/tls/TlsUtility.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "TlsUtility.h"
#include "TlsCertificate.h"
#include <QFile>
#include <QString>
namespace deskflow::gui {
TlsUtility::TlsUtility(const IAppConfig &appConfig) : m_appConfig(appConfig)
{
}
bool TlsUtility::isEnabled() const
{
const auto &config = m_appConfig;
return config.tlsEnabled();
}
bool TlsUtility::generateCertificate()
{
qDebug("generating tls certificate, "
"all clients must trust the new fingerprint");
if (!isEnabled()) {
qCritical("unable to generate tls certificate, "
"tls is either not available or not enabled");
return false;
}
auto length = m_appConfig.tlsKeyLength();
return m_certificate.generateCertificate(m_appConfig.tlsCertPath(), length);
}
bool TlsUtility::persistCertificate()
{
qDebug("persisting tls certificate");
if (QFile::exists(m_appConfig.tlsCertPath())) {
qDebug("tls certificate already exists");
return true;
}
return generateCertificate();
}
} // namespace deskflow::gui
| 1,680
|
C++
|
.cpp
| 51
| 30.176471
| 78
| 0.747988
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,619
|
CommandProcess.cpp
|
deskflow_deskflow/src/lib/gui/core/CommandProcess.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "CommandProcess.h"
#include <QProcess>
CommandProcess::CommandProcess(QString command, QStringList arguments, QString input)
: m_Command(command),
m_Arguments(arguments),
m_Input(input)
{
}
QString CommandProcess::run()
{
QProcess process;
process.setReadChannel(QProcess::StandardOutput);
process.start(m_Command, m_Arguments);
bool success = process.waitForStarted();
QString output;
QString error;
if (success) {
if (!m_Input.isEmpty()) {
process.write(m_Input.toStdString().c_str());
}
if (process.waitForFinished()) {
output = process.readAllStandardOutput().trimmed();
error = process.readAllStandardError().trimmed();
}
}
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)
);
}
Q_EMIT finished();
return output;
}
| 1,707
|
C++
|
.cpp
| 50
| 30.7
| 119
| 0.715413
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,620
|
ServerMessage.cpp
|
deskflow_deskflow/src/lib/gui/core/ServerMessage.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2021 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ServerMessage.h"
namespace deskflow::gui {
ServerMessage::ServerMessage(const QString &message) : m_message(message), m_clientName(parseClientName(message))
{
}
bool ServerMessage::isNewClientMessage() const
{
return m_message.contains("unrecognised client name");
}
bool ServerMessage::isExitMessage() const
{
return m_message.contains("process exited");
}
bool ServerMessage::isConnectedMessage() const
{
return m_message.contains("has connected");
}
bool ServerMessage::isDisconnectedMessage() const
{
return m_message.contains("has disconnected");
}
const QString &ServerMessage::getClientName() const
{
return m_clientName;
}
QString ServerMessage::parseClientName(const QString &line) const
{
QString clientName("Unknown");
auto nameStart = line.indexOf('"') + 1;
auto nameEnd = line.indexOf('"', nameStart);
if (nameEnd > nameStart) {
clientName = line.mid(nameStart, nameEnd - nameStart);
}
return clientName;
}
} // namespace deskflow::gui
| 1,683
|
C++
|
.cpp
| 52
| 30.346154
| 113
| 0.767758
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,621
|
ServerConnection.cpp
|
deskflow_deskflow/src/lib/gui/core/ServerConnection.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2021 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ServerConnection.h"
#include "ServerMessage.h"
#include "gui/config/ServerConfigDialogState.h"
#include "messages.h"
#include <QMessageBox>
#include <QPushButton>
namespace deskflow::gui {
//
// ServerConnection::Deps
//
messages::NewClientPromptResult
ServerConnection::Deps::showNewClientPrompt(QWidget *parent, const QString &clientName) const
{
return messages::showNewClientPrompt(parent, clientName);
}
//
// ServerConnection
//
ServerConnection::ServerConnection(
QWidget *parent, IAppConfig &appConfig, IServerConfig &serverConfig,
const config::ServerConfigDialogState &serverConfigDialogState, std::shared_ptr<Deps> deps
)
: m_pParent(parent),
m_appConfig(appConfig),
m_serverConfig(serverConfig),
m_serverConfigDialogState(serverConfigDialogState),
m_pDeps(deps)
{
}
void ServerConnection::handleLogLine(const QString &logLine)
{
ServerMessage message(logLine);
if (!message.isNewClientMessage()) {
return;
}
if (m_messageShowing) {
qDebug("new client message already shown, skipping for now");
return;
}
if (m_serverConfigDialogState.isVisible()) {
qDebug("server config dialog visible, skipping new client prompt");
return;
}
if (m_appConfig.useExternalConfig()) {
qDebug("external config enabled, skipping new client prompt");
return;
}
const auto client = message.getClientName();
if (m_receivedClients.contains(client)) {
qDebug("already got request, skipping new client prompt for: %s", qPrintable(client));
return;
}
handleNewClient(message.getClientName());
}
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));
return;
}
if (m_serverConfig.screenExists(clientName)) {
qDebug("client already added, skipping new client prompt for: %s", qPrintable(clientName));
return;
}
Q_EMIT messageShowing();
m_messageShowing = true;
const auto result = m_pDeps->showNewClientPrompt(m_pParent, clientName);
m_messageShowing = false;
if (result == Add) {
qDebug("accepted dialog, adding client: %s", qPrintable(clientName));
Q_EMIT configureClient(clientName);
} else if (result == Ignore) {
qDebug("declined dialog, ignoring client: %s", qPrintable(clientName));
} else {
qFatal("unexpected add client result");
}
}
} // namespace deskflow::gui
| 3,250
|
C++
|
.cpp
| 96
| 30.78125
| 95
| 0.751438
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,622
|
ClientConnection.cpp
|
deskflow_deskflow/src/lib/gui/core/ClientConnection.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2021 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ClientConnection.h"
#include "messages.h"
#include <QHostAddress>
#include <QMessageBox>
namespace deskflow::gui {
//
// ClientConnection::Deps
//
void ClientConnection::Deps::showError(QWidget *parent, messages::ClientError error, const QString &address) const
{
messages::showClientConnectError(parent, error, address);
}
//
// ClientConnection
//
void ClientConnection::handleLogLine(const QString &logLine)
{
if (logLine.contains("failed to connect to server")) {
if (!m_showMessage) {
qDebug("message already shown, skipping");
return;
}
m_showMessage = false;
// ignore the message if it's about the server refusing by name as
// this will trigger the server to show an 'add client' dialog.
if (logLine.contains("server refused client with our name")) {
qDebug("ignoring client name refused message");
return;
}
showMessage(logLine);
} else if (logLine.contains("connected to server")) {
m_showMessage = false;
}
}
void ClientConnection::showMessage(const QString &logLine)
{
using enum messages::ClientError;
Q_EMIT messageShowing();
const auto address = m_appConfig.serverHostname();
if (logLine.contains("server already has a connected client with our name")) {
m_deps->showError(m_pParent, AlreadyConnected, address);
} else if (QHostAddress a(address); a.isNull()) {
qDebug("ip not detected, showing hostname error");
m_deps->showError(m_pParent, HostnameError, address);
} else {
qDebug("ip detected, showing generic error");
m_deps->showError(m_pParent, GenericError, address);
}
}
} // namespace deskflow::gui
| 2,340
|
C++
|
.cpp
| 66
| 32.409091
| 114
| 0.737589
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,623
|
CoreTool.cpp
|
deskflow_deskflow/src/lib/gui/core/CoreTool.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Chris Rizzitello <sithlord48@gmail.com>
* Copyright (C) 2015 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "gui/core/CoreTool.h"
#if defined(Q_OS_UNIX)
#include "arch/unix/ArchFileUnix.h"
#include "arch/unix/ArchSystemUnix.h"
#elif defined(Q_OS_WIN)
#include "arch/win32/ArchFileWindows.h"
#include "arch/win32/ArchSystemWindows.h"
#endif
#include <QDir>
QString CoreTool::getProfileDir() const
{
#if defined Q_OS_UNIX
ArchFileUnix sysInfo;
#elif defined Q_OS_WIN
ArchFileWindows sysInfo;
#endif
return QDir::cleanPath(QString::fromUtf8(sysInfo.getProfileDirectory()));
}
QString CoreTool::getInstalledDir() const
{
#if defined Q_OS_UNIX
ArchFileUnix sysInfo;
#elif defined Q_OS_WIN
ArchFileWindows sysInfo;
#endif
return QDir::cleanPath(QString::fromUtf8(sysInfo.getInstalledDirectory()));
}
QString CoreTool::getArch() const
{
#if defined Q_OS_UNIX
ArchSystemUnix sysInfo;
#elif defined Q_OS_WIN
ArchSystemWindows sysInfo;
#endif
return QString::fromUtf8(sysInfo.getPlatformName());
}
| 1,661
|
C++
|
.cpp
| 53
| 29.584906
| 77
| 0.782147
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,624
|
WaylandWarnings.cpp
|
deskflow_deskflow/src/lib/gui/core/WaylandWarnings.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "WaylandWarnings.h"
#include "messages.h"
using namespace deskflow::platform;
namespace deskflow::gui::core {
//
// WaylandWarnings::Deps
//
void WaylandWarnings::Deps::showWaylandLibraryError(QWidget *parent)
{
messages::showWaylandLibraryError(parent);
}
//
// WaylandWarnings
//
void WaylandWarnings::showOnce(
QWidget *parent, CoreProcess::Mode mode, bool hasEi, bool hasPortal, bool hasPortalInputCapture
)
{
const auto portalIcProblem = !hasPortalInputCapture && mode == CoreProcess::Mode::Server;
if (!hasEi || !hasPortal || portalIcProblem) {
if (!m_errorShown) {
m_errorShown = true;
m_pDeps->showWaylandLibraryError(parent);
} else {
qWarning("missing required wayland lib(s) or feature");
}
return;
}
}
} // namespace deskflow::gui::core
| 1,501
|
C++
|
.cpp
| 46
| 30.065217
| 99
| 0.74723
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,625
|
CoreProcess.cpp
|
deskflow_deskflow/src/lib/gui/core/CoreProcess.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "CoreProcess.h"
#include "common/constants.h"
#include "gui/config/IAppConfig.h"
#include "gui/core/CoreTool.h"
#include "gui/paths.h"
#include "tls/TlsUtility.h"
#if defined(Q_OS_MAC)
#include "OSXHelpers.h"
#endif
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QMessageBox>
#include <QMutexLocker>
#include <QRegularExpression>
#include <QStandardPaths>
#include <QTimer>
#include <QtGlobal>
namespace deskflow::gui {
const int kRetryDelay = 1000;
const auto kServerConfigFilename = QStringLiteral("%1-server.conf").arg(kAppId);
const auto kLineSplitRegex = QRegularExpression("\r|\n|\r\n");
//
// free functions
//
QString processModeToString(ProcessMode mode)
{
using enum ProcessMode;
switch (mode) {
case kDesktop:
return "desktop";
case kService:
return "service";
default:
qFatal("invalid process mode");
abort();
}
}
QString processStateToString(CoreProcess::ProcessState state)
{
using enum CoreProcess::ProcessState;
switch (state) {
case Starting:
return "starting";
case Started:
return "started";
case Stopping:
return "stopping";
case Stopped:
return "stopped";
case RetryPending:
return "retry pending";
default:
qFatal("invalid process state");
abort();
}
}
/**
* @brief Wraps options that contain spaces in quotes
*
* Useful to handle things like paths with spaces (e.g. "C:\Program Files").
*
* 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)
{
QStringList command;
command << app;
command << args;
QStringList quoted;
for (const auto &arg : std::as_const(command)) {
if (arg.contains(' ')) {
quoted << QString("\"%1\"").arg(arg);
} else {
quoted << arg;
}
}
return quoted.join(" ");
}
/**
* @brief If IPv6, ensures the IP is surround in square brackets.
*/
QString wrapIpv6(const QString &address)
{
if (!address.contains(':') || address.isEmpty()) {
return address;
}
QString wrapped = address;
if (address[0] != '[') {
wrapped.insert(0, '[');
}
if (address[address.size() - 1] != ']') {
wrapped.push_back(']');
}
return address;
}
//
// CoreProcess::Deps
//
QString CoreProcess::Deps::appPath(const QString &name) const
{
QDir dir(QCoreApplication::applicationDirPath());
return dir.filePath(name);
}
bool CoreProcess::Deps::fileExists(const QString &path) const
{
return QFile::exists(path);
}
QString CoreProcess::Deps::getProfileRoot() const
{
CoreTool coreTool;
QDir appDir = coreTool.getProfileDir();
// the core expects the profile root dir, not the app-specific profile dir.
if (!appDir.cdUp()) {
qFatal("failed to cd up to profile root dir");
}
return appDir.absolutePath();
}
//
// CoreProcess
//
CoreProcess::CoreProcess(const IAppConfig &appConfig, const IServerConfig &serverConfig, std::shared_ptr<Deps> deps)
: m_appConfig(appConfig),
m_serverConfig(serverConfig),
m_pDeps(deps)
{
connect(
&m_pDeps->ipcClient(), &QIpcClient::read, this, //
&CoreProcess::onIpcClientRead
);
connect(
&m_pDeps->ipcClient(), &QIpcClient::serviceReady, this, //
&CoreProcess::onIpcClientServiceReady
);
connect(&m_pDeps->process(), &QProcessProxy::finished, this, &CoreProcess::onProcessFinished);
connect(
&m_pDeps->process(), &QProcessProxy::readyReadStandardOutput, this, &CoreProcess::onProcessReadyReadStandardOutput
);
connect(
&m_pDeps->process(), &QProcessProxy::readyReadStandardError, this, &CoreProcess::onProcessReadyReadStandardError
);
connect(&m_retryTimer, &QTimer::timeout, this, [this] {
if (m_processState == ProcessState::RetryPending) {
start();
} else {
qDebug("retry cancelled, process state is not retry pending");
}
});
}
void CoreProcess::onIpcClientServiceReady()
{
if (m_processState == ProcessState::Starting) {
qDebug("service ready, continuing core process start");
start();
} else if (m_processState == ProcessState::Stopping) {
qDebug("service ready, continuing core process stop");
stop();
} else {
// This may happen when the IPC connection fails and then reconnects.
qWarning("ignoring service ready, process state is not starting or stopping");
}
}
void CoreProcess::onIpcClientError(const QString &text) const
{
qCritical().noquote() << text;
if (m_appConfig.processMode() != ProcessMode::kService) {
// if not meant to be in service mode and there is an ipc connection error,
// then abandon the ipc client connection.
m_pDeps->ipcClient().disconnectFromHost();
}
}
void CoreProcess::onIpcClientRead(const QString &text)
{
handleLogLines(text);
}
void CoreProcess::onProcessReadyReadStandardOutput()
{
if (m_pDeps->process()) {
handleLogLines(m_pDeps->process().readAllStandardOutput());
}
}
void CoreProcess::onProcessReadyReadStandardError()
{
if (m_pDeps->process()) {
handleLogLines(m_pDeps->process().readAllStandardError());
}
}
void CoreProcess::onProcessFinished(int exitCode, QProcess::ExitStatus)
{
const auto wasStarted = m_processState == ProcessState::Started;
setConnectionState(ConnectionState::Disconnected);
if (exitCode == 0) {
qDebug("desktop process exited normally");
} else {
qWarning("desktop process exited with error code: %d", exitCode);
}
if (wasStarted) {
qDebug("desktop process was running, retrying in %d ms", kRetryDelay);
if (m_retryTimer.isActive()) {
m_retryTimer.stop();
}
setProcessState(ProcessState::RetryPending);
m_retryTimer.setSingleShot(true);
m_retryTimer.start(kRetryDelay);
} else {
setProcessState(ProcessState::Stopped);
}
}
void CoreProcess::startDesktop(const QString &app, const QStringList &args)
{
using enum ProcessState;
if (m_processState != Starting) {
qFatal("core process must be in starting state");
}
// only make quoted args for printing the command for convenience; so that the
// core command can be easily copy/pasted to the terminal for testing.
const auto quoted = makeQuotedArgs(app, args);
qInfo("running command: %s", qPrintable(quoted));
m_pDeps->process().start(app, args);
if (m_pDeps->process().waitForStarted()) {
setProcessState(Started);
} else {
setProcessState(Stopped);
Q_EMIT error(Error::StartFailed);
}
}
void CoreProcess::startService(const QString &app, const QStringList &args)
{
using enum ProcessState;
if (m_processState != Starting) {
qFatal("core process must be in starting state");
}
if (!m_pDeps->ipcClient().isConnected()) {
// when service state changes, start will be called again.
qDebug("cannot start process, ipc not connected, connecting instead");
m_pDeps->ipcClient().connectToHost();
return;
}
QString commandQuoted = makeQuotedArgs(app, args);
qInfo("running command: %s", qPrintable(commandQuoted));
m_pDeps->ipcClient().sendCommand(commandQuoted, m_appConfig.elevateMode());
setProcessState(Started);
}
void CoreProcess::stopDesktop() const
{
if (m_processState != ProcessState::Stopping) {
qFatal("core process must be in stopping state");
}
if (!m_pDeps->process()) {
qFatal("process not set, cannot stop");
}
qInfo("stopping core desktop process");
if (m_pDeps->process().state() == QProcess::ProcessState::Running) {
qDebug("process is running, closing");
m_pDeps->process().close();
} else {
qDebug("process is not running, skipping terminate");
}
}
void CoreProcess::stopService()
{
if (m_processState != ProcessState::Stopping) {
qFatal("core process must be in stopping state");
}
if (!m_pDeps->ipcClient().isConnected()) {
qDebug("cannot stop process, ipc not connected");
return;
}
m_pDeps->ipcClient().sendCommand("", m_appConfig.elevateMode());
setProcessState(ProcessState::Stopped);
}
void CoreProcess::handleLogLines(const QString &text)
{
const auto lines = text.split(kLineSplitRegex);
for (const auto &line : lines) {
if (line.isEmpty()) {
continue;
}
#if defined(Q_OS_MAC)
// HACK: macOS 10.13.4+ spamming error lines in logs making them
// impossible to read and debug; giving users a red herring.
if (line.contains("calling TIS/TSM in non-main thread environment")) {
continue;
}
#endif
checkLogLine(line);
Q_EMIT logLine(line);
}
}
void CoreProcess::start(std::optional<ProcessMode> processModeOption)
{
QMutexLocker locker(&m_processMutex);
const auto processMode = processModeOption.value_or(m_appConfig.processMode());
qInfo("starting core %s process (%s mode)", qPrintable(modeString()), qPrintable(processModeToString(processMode)));
if (m_processState == ProcessState::Started) {
qCritical("core process already started");
return;
}
// allow external listeners to abort the start process (e.g. licensing issue).
setProcessState(ProcessState::Starting);
Q_EMIT starting();
if (m_processState == ProcessState::Stopped) {
qDebug("core process start was cancelled by listener");
return;
}
#ifdef Q_OS_MAC
requestOSXNotificationPermission();
#endif
setConnectionState(ConnectionState::Connecting);
if (processMode == ProcessMode::kDesktop) {
m_pDeps->process().create();
}
QString app;
QStringList args;
addGenericArgs(args, processMode);
if (mode() == Mode::Server && !addServerArgs(args, app)) {
qDebug("failed to add server args for core process, aborting start");
return;
} else if (mode() == Mode::Client && !addClientArgs(args, app)) {
qDebug("failed to add client args for core process, aborting start");
return;
}
qDebug("log level: %s", qPrintable(m_appConfig.logLevelText()));
if (m_appConfig.logToFile())
qInfo("log file: %s", qPrintable(m_appConfig.logFilename()));
if (processMode == ProcessMode::kDesktop) {
startDesktop(app, args);
} else if (processMode == ProcessMode::kService) {
startService(app, args);
}
m_lastProcessMode = processMode;
}
void CoreProcess::stop(std::optional<ProcessMode> processModeOption)
{
QMutexLocker locker(&m_processMutex);
const auto processMode = processModeOption.value_or(m_appConfig.processMode());
qInfo("stopping core process (%s mode)", qPrintable(processModeToString(processMode)));
if (m_processState == ProcessState::Starting) {
qDebug("core process is starting, cancelling");
setProcessState(ProcessState::Stopped);
} else if (m_processState != ProcessState::Stopped) {
setProcessState(ProcessState::Stopping);
if (processMode == ProcessMode::kService) {
stopService();
} else if (processMode == ProcessMode::kDesktop) {
stopDesktop();
}
} else {
qWarning("core process already stopped");
}
setConnectionState(ConnectionState::Disconnected);
}
void CoreProcess::restart()
{
using enum ProcessMode;
qDebug("restarting core process");
const auto processMode = m_appConfig.processMode();
if (m_lastProcessMode != processMode) {
if (processMode == kDesktop) {
qDebug("process mode changed to desktop, stopping service process");
stop(kService);
} else if (processMode == kService) {
qDebug("process mode changed to service, stopping desktop process");
stop(kDesktop);
} else {
qFatal("invalid process mode");
}
} else {
// in service mode: though there is technically no need to stop the service
// before restarting it, it does make for cleaner process state tracking,
// especially if something goes wrong with starting the service.
stop();
}
start();
}
void CoreProcess::cleanup()
{
qInfo("cleaning up core process");
const auto isDesktop = m_appConfig.processMode() == ProcessMode::kDesktop;
const auto isRunning = m_processState == ProcessState::Started;
if (isDesktop && isRunning) {
stop();
}
m_pDeps->ipcClient().disconnectFromHost();
}
bool CoreProcess::addGenericArgs(QStringList &args, const ProcessMode processMode) const
{
args << "-f"
<< "--no-tray"
<< "--debug" << m_appConfig.logLevelText();
args << "--name" << m_appConfig.screenName();
if (processMode != ProcessMode::kDesktop) {
// tell client/server to talk to daemon through ipc.
args << "--ipc";
#if defined(Q_OS_WIN)
// tell the client/server to shut down when a ms windows desk
// is switched; this is because we may need to elevate or not
// based on which desk the user is in (login always needs
// elevation, where as default desk does not).
// Note that this is only enabled when deskflow is set to elevate
// 'as needed' (e.g. on a UAC dialog popup) in order to prevent
// unnecessary restarts when deskflow was started elevated or
// when it is not allowed to elevate. In these cases restarting
// the server is fruitless.
if (m_appConfig.elevateMode() == ElevateMode::kAutomatic) {
args << "--stop-on-desk-switch";
}
#endif
}
#ifndef Q_OS_LINUX
if (m_serverConfig.enableDragAndDrop()) {
args << "--enable-drag-drop";
}
#endif
if (m_appConfig.tlsEnabled()) {
args << "--enable-crypto";
}
#if defined(Q_OS_WIN)
// on windows, the profile directory changes depending on the user that
// launched the process (e.g. when launched with elevation). setting the
// profile dir on launch ensures it uses the same profile dir is used
// no matter how its relaunched.
args << "--profile-dir" << m_pDeps->getProfileRoot();
#endif
if (m_appConfig.preventSleep()) {
args << "--prevent-sleep";
}
return true;
}
bool CoreProcess::addServerArgs(QStringList &args, QString &app)
{
app = m_pDeps->appPath(m_appConfig.coreServerName());
if (!m_pDeps->fileExists(app)) {
qFatal("core server binary does not exist");
return false;
}
if (m_appConfig.logToFile()) {
m_appConfig.persistLogDir();
args << "--log" << m_appConfig.logFilename();
}
QString configFilename = persistServerConfig();
if (configFilename.isEmpty()) {
qFatal("config file name empty for server args");
return false;
}
if (m_appConfig.invertConnection()) {
qDebug("inverting server connection");
if (correctedAddress().isEmpty()) {
Q_EMIT error(Error::AddressMissing);
qDebug("address is missing for server args");
return false;
}
}
// the address arg is dual purpose; when in listening mode, it's the address
// that the server listens on. when tcp sockets are inverted, it connects to
// that address. this is a bit confusing, and there should be probably be
// different args for different purposes.
args << "--address" << correctedInterface();
args << "-c" << configFilename;
qInfo("core config file: %s", qPrintable(configFilename));
// bizarrely, the tls cert path arg was being given to the core client.
// since it's not clear why (it is only needed for the server), this has now
// been moved to server args.
if (m_appConfig.tlsEnabled()) {
TlsUtility tlsUtility(m_appConfig);
if (!tlsUtility.persistCertificate()) {
qCritical("failed to persist tls certificate");
return false;
}
args << "--tls-cert" << m_appConfig.tlsCertPath();
}
return true;
}
bool CoreProcess::addClientArgs(QStringList &args, QString &app)
{
app = m_pDeps->appPath(m_appConfig.coreClientName());
if (!m_pDeps->fileExists(app)) {
qFatal("core client binary does not exist");
return false;
}
if (m_appConfig.logToFile()) {
m_appConfig.persistLogDir();
args << "--log" << m_appConfig.logFilename();
}
if (m_appConfig.languageSync()) {
args << "--sync-language";
}
if (m_appConfig.invertScrollDirection()) {
args << "--invert-scroll";
}
if (m_appConfig.invertConnection()) {
qDebug("inverting client connection");
args << "--host";
args << ":" + QString::number(m_appConfig.port());
} else {
if (correctedAddress().isEmpty()) {
Q_EMIT error(Error::AddressMissing);
qDebug("address is missing for client args");
return false;
}
args << correctedAddress() + ":" + QString::number(m_appConfig.port());
}
return true;
}
QString CoreProcess::persistServerConfig() const
{
if (m_appConfig.useExternalConfig()) {
return m_appConfig.configFile();
}
const auto configDir = paths::configDir(true);
const auto configDirPath = configDir.absolutePath();
QFile configFile(configDirPath + "/" + kServerConfigFilename);
if (!configFile.open(QIODevice::WriteOnly | QIODevice::Truncate)) {
qFatal("failed to open core config file for write: %s", qPrintable(configFile.fileName()));
}
m_serverConfig.save(configFile);
configFile.close();
return configFile.fileName();
}
QString CoreProcess::modeString() const
{
using enum Mode;
switch (m_mode) {
case Server:
return "server";
case Client:
return "client";
default:
qFatal("invalid core mode");
return "";
}
}
void CoreProcess::setConnectionState(ConnectionState state)
{
if (m_connectionState == state) {
return;
}
m_connectionState = state;
Q_EMIT connectionStateChanged(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))
);
m_processState = state;
Q_EMIT processStateChanged(state);
}
void CoreProcess::checkLogLine(const QString &line)
{
using enum ConnectionState;
if (line.contains("connected to server") || line.contains("has connected")) {
setConnectionState(Connected);
} else if (line.contains("started server")) {
setConnectionState(Listening);
} else if (line.contains("disconnected from server") || line.contains("process exited")) {
setConnectionState(Disconnected);
} else if (line.contains("connecting to")) {
setConnectionState(Connecting);
}
checkSecureSocket(line);
// server and client processes are not allowed to show notifications.
// process the log from it and show notification from deskflow instead.
#ifdef Q_OS_MAC
checkOSXNotification(line);
#endif
}
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) {
return false;
}
Q_EMIT secureSocket(true);
m_secureSocketVersion = line.mid(index + tlsCheckString.size());
return true;
}
#ifdef Q_OS_MAC
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);
if (!showOSXNotification(title, body)) {
qDebug("osx notification was not shown");
}
}
}
#endif
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);
}
} // namespace deskflow::gui
| 20,253
|
C++
|
.cpp
| 624
| 29.025641
| 120
| 0.712328
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,626
|
ComputerNameValidator.cpp
|
deskflow_deskflow/src/lib/gui/validators/ComputerNameValidator.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2021 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ComputerNameValidator.h"
#include <QRegularExpression>
namespace validators {
ComputerNameValidator::ComputerNameValidator(const QString &message) : IStringValidator(message)
{
}
bool ComputerNameValidator::validate(const QString &input) const
{
auto match = m_nameValidator.match(input);
return match.hasMatch();
}
} // namespace validators
| 1,048
|
C++
|
.cpp
| 28
| 35.535714
| 96
| 0.781065
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,627
|
IStringValidator.cpp
|
deskflow_deskflow/src/lib/gui/validators/IStringValidator.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2021 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "IStringValidator.h"
namespace validators {
IStringValidator::IStringValidator(const QString &message) : m_Message(message)
{
}
const QString &IStringValidator::getMessage() const
{
return m_Message;
}
} // namespace validators
| 930
|
C++
|
.cpp
| 26
| 33.923077
| 79
| 0.771969
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,628
|
LineEditValidator.cpp
|
deskflow_deskflow/src/lib/gui/validators/LineEditValidator.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2021 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "LineEditValidator.h"
#include "gui/styles.h"
#include <QValidator>
using namespace deskflow::gui;
namespace validators {
LineEditValidator::LineEditValidator(QLineEdit *lineEdit, ValidationError *error)
: m_pError(error),
m_pLineEdit(lineEdit)
{
if (!m_pLineEdit) {
qFatal("validator line edit not set");
}
}
void LineEditValidator::addValidator(std::unique_ptr<IStringValidator> validator)
{
m_Validators.push_back(std::move(validator));
}
QValidator::State LineEditValidator::validate(QString &input, int &pos) const
{
assert(m_pLineEdit);
QString errorMessage;
for (const auto &validator : m_Validators) {
if (!validator->validate(input)) {
errorMessage = validator->getMessage();
break;
}
}
if (errorMessage.isEmpty()) {
m_pLineEdit->setStyleSheet("");
} else {
m_pLineEdit->setStyleSheet(kStyleLineEditErrorBorder);
}
if (m_pError) {
m_pError->setMessage(errorMessage);
}
return errorMessage.isEmpty() ? Acceptable : Intermediate;
}
} // namespace validators
| 1,746
|
C++
|
.cpp
| 54
| 29.462963
| 81
| 0.744338
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,629
|
ScreenDuplicationsValidator.cpp
|
deskflow_deskflow/src/lib/gui/validators/ScreenDuplicationsValidator.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2021 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScreenDuplicationsValidator.h"
namespace validators {
ScreenDuplicationsValidator::ScreenDuplicationsValidator(
const QString &message, const QString &defaultName, const ScreenList *pScreens
)
: IStringValidator(message),
m_defaultName(defaultName),
m_pScreenList(pScreens)
{
}
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()) {
result = false;
break;
}
}
}
return result;
}
} // namespace validators
| 1,375
|
C++
|
.cpp
| 40
| 31.225
| 103
| 0.733434
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,630
|
AliasValidator.cpp
|
deskflow_deskflow/src/lib/gui/validators/AliasValidator.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2021 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "gui/validators/ComputerNameValidator.h"
#include "gui/validators/SpacesValidator.h"
#include "AliasValidator.h"
#include <QRegularExpression>
namespace validators {
AliasValidator::AliasValidator(QLineEdit *parent, ValidationError *error) : LineEditValidator(parent, error)
{
addValidator(std::make_unique<SpacesValidator>("Computer name cannot contain spaces"));
addValidator(std::make_unique<ComputerNameValidator>("Contains invalid characters or is too long"));
}
} // namespace validators
| 1,199
|
C++
|
.cpp
| 27
| 42.481481
| 108
| 0.785592
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,631
|
EmptyStringValidator.cpp
|
deskflow_deskflow/src/lib/gui/validators/EmptyStringValidator.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2021 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "EmptyStringValidator.h"
namespace validators {
EmptyStringValidator::EmptyStringValidator(const QString &message) : IStringValidator(message)
{
}
bool EmptyStringValidator::validate(const QString &input) const
{
return !input.isEmpty();
}
} // namespace validators
| 968
|
C++
|
.cpp
| 26
| 35.384615
| 94
| 0.778015
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,632
|
SpacesValidator.cpp
|
deskflow_deskflow/src/lib/gui/validators/SpacesValidator.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2021 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SpacesValidator.h"
namespace validators {
SpacesValidator::SpacesValidator(const QString &message) : IStringValidator(message)
{
}
bool SpacesValidator::validate(const QString &input) const
{
return !input.contains(' ');
}
} // namespace validators
| 952
|
C++
|
.cpp
| 26
| 34.769231
| 84
| 0.770901
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,633
|
ScreenNameValidator.cpp
|
deskflow_deskflow/src/lib/gui/validators/ScreenNameValidator.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2021 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScreenNameValidator.h"
#include "gui/validators/ComputerNameValidator.h"
#include "gui/validators/EmptyStringValidator.h"
#include "gui/validators/ScreenDuplicationsValidator.h"
#include "gui/validators/SpacesValidator.h"
#include "gui/validators/ValidationError.h"
#include <QRegularExpression>
#include <memory>
namespace validators {
ScreenNameValidator::ScreenNameValidator(QLineEdit *lineEdit, ValidationError *error, const ScreenList *pScreens)
: LineEditValidator(lineEdit, error)
{
addValidator(std::make_unique<EmptyStringValidator>("Computer name cannot be empty"));
addValidator(std::make_unique<SpacesValidator>("Computer name cannot contain spaces"));
addValidator(std::make_unique<ComputerNameValidator>("Contains invalid characters or is too long"));
addValidator(std::make_unique<ScreenDuplicationsValidator>(
"A computer with this name already exists", lineEdit ? lineEdit->text() : "", pScreens
));
}
} // namespace validators
| 1,667
|
C++
|
.cpp
| 36
| 44.166667
| 113
| 0.787692
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,634
|
ValidationError.cpp
|
deskflow_deskflow/src/lib/gui/validators/ValidationError.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ValidationError.h"
#include "gui/styles.h"
using namespace deskflow::gui;
namespace validators {
void clear(QLabel *label)
{
if (label) {
label->setStyleSheet(kStyleErrorInactiveLabel);
label->setText("");
}
}
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;
}
void ValidationError::setMessage(const QString &message)
{
m_message = message;
if (m_pLabel) {
if (message.isEmpty()) {
clear(m_pLabel);
} else {
m_pLabel->setStyleSheet(kStyleErrorActiveLabel);
m_pLabel->setText(message);
}
}
}
} // namespace validators
| 1,440
|
C++
|
.cpp
| 50
| 26.12
| 99
| 0.73459
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,635
|
IpcReader.cpp
|
deskflow_deskflow/src/lib/gui/ipc/IpcReader.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "IpcReader.h"
#include "Logger.h"
#include "byte_utils.h"
#include "common/ipc.h"
#include <QByteArray>
#include <QMutex>
#include <QTcpSocket>
using namespace deskflow::gui;
IpcReader::IpcReader(QTcpSocket *socket) : m_Socket(socket)
{
}
void IpcReader::start() const
{
connect(m_Socket, &QTcpSocket::readyRead, this, &IpcReader::onSocketReadyRead);
}
void IpcReader::stop() const
{
disconnect(m_Socket, &QTcpSocket::readyRead, this, &IpcReader::onSocketReadyRead);
}
void IpcReader::onSocketReadyRead()
{
QMutexLocker locker(&m_Mutex);
logVerbose("ready read");
while (m_Socket->bytesAvailable()) {
logVerbose("bytes available");
char codeBuf[5];
readStream(codeBuf, 4);
codeBuf[4] = 0;
logVerbose(QString("ipc read: %1").arg(codeBuf));
if (memcmp(codeBuf, kIpcMsgLogLine, 4) == 0) {
logVerbose("reading log line");
char lenBuf[4];
readStream(lenBuf, 4);
int len = bytesToInt(lenBuf, 4);
std::vector<char> dataBuf(len);
readStream(dataBuf.data(), len);
QString text = QString::fromUtf8(dataBuf.data(), len);
Q_EMIT read(text);
} else if (memcmp(codeBuf, kIpcMsgHelloBack, 4) == 0) {
logVerbose("reading hello back");
Q_EMIT helloBack();
} else {
qCritical("aborting ipc read, message invalid");
return;
}
}
logVerbose("read done");
}
bool IpcReader::readStream(char *buffer, int length)
{
logVerbose("reading stream");
int read = 0;
while (read < length) {
int ask = length - read;
if (m_Socket->bytesAvailable() < ask) {
logVerbose("buffer too short, waiting");
m_Socket->waitForReadyRead(-1);
}
auto got = m_Socket->read(buffer, ask);
read += got;
logVerbose(QString("ask=%1 got=%2 read=%3").arg(ask).arg(got).arg(read));
if (got == -1) {
logVerbose("socket ended, aborting");
return false;
} else if (length - read > 0) {
logVerbose(QString("more remains, seek to %1").arg(got));
buffer += got;
}
}
return true;
}
| 2,738
|
C++
|
.cpp
| 87
| 27.724138
| 84
| 0.685671
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,637
|
QIpcClient.cpp
|
deskflow_deskflow/src/lib/gui/ipc/QIpcClient.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "QIpcClient.h"
#include "IpcReader.h"
#include "byte_utils.h"
#include "common/ipc.h"
#include <QDataStream>
#include <QHostAddress>
#include <QTimer>
#include <memory>
const auto kRetryInterval = 1000;
const auto kConnectTimeout = 5000;
using namespace deskflow::gui;
QIpcClient::QIpcClient(const StreamProvider &streamProvider) : m_streamProvider(streamProvider)
{
m_pSocket = std::make_unique<QTcpSocket>();
if (!m_streamProvider) {
m_streamProvider = [this]() { return std::make_shared<QDataStreamProxy>(m_pSocket.get()); };
}
connect(m_pSocket.get(), &QTcpSocket::connected, this, &QIpcClient::onSocketConnected);
connect(m_pSocket.get(), &QTcpSocket::errorOccurred, this, &QIpcClient::onSocketError);
m_pReader = std::make_unique<IpcReader>(m_pSocket.get());
connect(
m_pReader.get(), &IpcReader::read, this, //
&QIpcClient::onIpcReaderRead
);
connect(m_pReader.get(), &IpcReader::helloBack, this, &QIpcClient::onIpcReaderHelloBack);
}
void QIpcClient::onSocketConnected() const
{
sendHello();
}
void QIpcClient::connectToHost()
{
m_isConnecting = true;
qInfo("connecting to background service...");
const auto port = static_cast<quint16>(kIpcPort);
m_pSocket->connectToHost(QHostAddress(QHostAddress::LocalHost), port);
if (!m_readerStarted) {
m_pReader->start();
m_readerStarted = true;
}
QTimer::singleShot(kConnectTimeout, this, [this]() {
if (!m_isConnected) {
qCritical("ipc connection timeout");
}
});
}
void QIpcClient::disconnectFromHost()
{
m_pReader->stop();
m_pSocket->flush();
m_pSocket->close();
m_isConnecting = false;
m_isConnected = false;
qInfo("disconnected from background service");
}
void QIpcClient::onSocketError(QAbstractSocket::SocketError socketError)
{
QString text;
switch (socketError) {
case 0:
text = "connection refused";
break;
case 1:
text = "remote host closed";
break;
default:
text = QString("code=%1").arg(socketError);
break;
}
qWarning("ipc connection error, %s", qUtf8Printable(text));
m_isConnected = false;
QTimer::singleShot(kRetryInterval, this, &QIpcClient::onRetryConnect);
}
void QIpcClient::onRetryConnect()
{
if (m_isConnected) {
qDebug("ipc already connected, skipping retry");
return;
} else if (!m_isConnecting) {
qDebug("ipc not connecting, skipping retry");
return;
}
qInfo("retrying connection to background service...");
connectToHost();
}
void QIpcClient::sendHello() const
{
qDebug("sending ipc hello message");
auto stream = m_streamProvider();
stream->writeRawData(kIpcMsgHello, 4);
char typeBuf[1];
typeBuf[0] = static_cast<char>(IpcClientType::GUI);
stream->writeRawData(typeBuf, 1);
}
void QIpcClient::sendCommand(const QString &command, ElevateMode const elevate) const
{
qDebug("sending ipc command: %s", qUtf8Printable(command));
auto stream = m_streamProvider();
stream->writeRawData(kIpcMsgCommand, 4);
std::string stdStringCommand = command.toStdString();
const char *charCommand = stdStringCommand.c_str();
auto length = static_cast<int>(stdStringCommand.length());
QByteArray lenBuf = intToBytes(length);
if (lenBuf.size() != 4) {
qFatal("unexpected int buffer size: %lld", lenBuf.size());
}
stream->writeRawData(lenBuf, 4);
stream->writeRawData(charCommand, length);
char elevateBuf[1];
// see enum ElevateMode documentation for why this flag is mapped this way
elevateBuf[0] = (elevate == ElevateMode::kAlways) ? 1 : 0;
stream->writeRawData(elevateBuf, 1);
}
void QIpcClient::onIpcReaderHelloBack()
{
qDebug("ipc hello back received");
if (m_isConnected) {
qWarning("ipc already connected, ignoring hello back");
return;
}
m_isConnected = true;
Q_EMIT serviceReady();
}
void QIpcClient::onIpcReaderRead(const QString &text)
{
Q_EMIT read(text);
}
| 4,576
|
C++
|
.cpp
| 143
| 29.125874
| 96
| 0.732955
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,638
|
AppConfig.cpp
|
deskflow_deskflow/src/lib/gui/config/AppConfig.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "AppConfig.h"
#include "ConfigScopes.h"
#include <QApplication>
#include <QMessageBox>
#include <QPushButton>
#include <QVariant>
#include <functional>
using namespace deskflow::gui;
// this should be incremented each time the wizard is changed,
// which will force it to re-run for existing installations.
const int kWizardVersion = 8;
static const char *const kLogLevelNames[] = {"INFO", "DEBUG", "DEBUG1", "DEBUG2"};
#if defined(Q_OS_WIN)
const char AppConfig::m_LogDir[] = "log/";
#else
const char AppConfig::m_LogDir[] = "/var/log/";
#endif
// TODO: instead, use key value pair table, which would be less fragile.
const char *const AppConfig::m_SettingsName[] = {
"screenName",
"port",
"interface",
"logLevel2",
"logToFile",
"logFilename",
"wizardLastRun",
"startedBefore",
"elevateMode",
"elevateModeEnum",
"", // 10 = edition, obsolete (using serial key instead)
"cryptoEnabled", // 11 = kTlsEnabled (retain legacy string value)
"autoHide",
"", // 13 = serialKey, obsolete
"lastVersion",
"", // 15 = lastExpiringWarningTime, obsolete
"", // 16 = activationHasRun, obsolete
"", // 17 = minimizeToTray, obsolete
"", // 18 = ActivateEmail, obsolete
"loadFromSystemScope",
"groupServerChecked", // kServerGroupChecked
"useExternalConfig",
"configFile",
"useInternalConfig",
"groupClientChecked",
"serverHostname",
"tlsCertPath",
"tlsKeyLength",
"preventSleep",
"languageSync",
"invertScrollDirection",
"", // 31 = guid, obsolete
"", // 32 = licenseRegistryUrl, obsolete
"", // 33 = licenseNextCheck, obsolete
"initiateConnectionFromServer", // kInvertConnection
"", // 35 = clientHostMode, obsolete
"", // 36 = serverClientMode, obsolete
"enableService",
"closeToTray",
"mainWindowSize",
"mainWindowPosition",
"", // 41 = Show dev thanks, obsolete
"showCloseReminder",
"enableUpdateCheck",
};
AppConfig::AppConfig(deskflow::gui::IConfigScopes &scopes, std::shared_ptr<Deps> deps)
: m_Scopes(scopes),
m_pDeps(deps),
m_ScreenName(deps->hostname()),
m_TlsCertPath(deps->defaultTlsCertPath())
{
determineScope();
recall();
}
void AppConfig::recall()
{
using enum AppConfig::Setting;
qDebug("recalling app config");
recallFromAllScopes();
recallFromCurrentScope();
}
void AppConfig::recallFromAllScopes()
{
using enum Setting;
m_WizardLastRun = findInAllScopes(kWizardLastRun, m_WizardLastRun).toInt();
m_LoadFromSystemScope = findInAllScopes(kLoadSystemSettings, m_LoadFromSystemScope).toBool();
}
void AppConfig::recallFromCurrentScope()
{
using enum Setting;
recallScreenName();
recallElevateMode();
m_Port = getFromCurrentScope(kPort, m_Port).toInt();
m_Interface = getFromCurrentScope(kInterface, m_Interface).toString();
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_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_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_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_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<QPoint>(kMainWindowPosition, [](const QVariant &v) { return v.toPoint(); });
m_MainWindowSize = getFromCurrentScope<QSize>(kMainWindowSize, [](const QVariant &v) { return v.toSize(); });
m_ShowCloseReminder = getFromCurrentScope(kShowCloseReminder, m_ShowCloseReminder).toBool();
m_EnableUpdateCheck = getFromCurrentScope<bool>(kEnableUpdateCheck, [](const QVariant &v) { return v.toBool(); });
}
void AppConfig::recallScreenName()
{
using enum Setting;
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
// back to the hostname.
if (screenName.isEmpty()) {
qWarning("screen name was empty in config, setting to hostname");
m_ScreenName = m_pDeps->hostname();
} else {
m_ScreenName = screenName;
}
}
void AppConfig::commit()
{
using enum Setting;
qDebug("committing app config");
saveToAllScopes(kWizardLastRun, m_WizardLastRun);
saveToAllScopes(kLoadSystemSettings, m_LoadFromSystemScope);
saveToAllScopes(kClientGroupChecked, m_ClientGroupChecked);
saveToAllScopes(kServerGroupChecked, m_ServerGroupChecked);
if (isActiveScopeWritable()) {
setInCurrentScope(kScreenName, m_ScreenName);
setInCurrentScope(kPort, m_Port);
setInCurrentScope(kInterface, m_Interface);
setInCurrentScope(kLogLevel, m_LogLevel);
setInCurrentScope(kLogToFile, m_LogToFile);
setInCurrentScope(kLogFilename, m_LogFilename);
setInCurrentScope(kStartedBefore, m_StartedBefore);
setInCurrentScope(kElevateMode, static_cast<int>(m_ElevateMode));
setInCurrentScope(kElevateModeLegacy, m_ElevateMode == ElevateMode::kAlways);
setInCurrentScope(kTlsEnabled, m_TlsEnabled);
setInCurrentScope(kAutoHide, m_AutoHide);
setInCurrentScope(kLastVersion, m_LastVersion);
setInCurrentScope(kUseExternalConfig, m_UseExternalConfig);
setInCurrentScope(kConfigFile, m_ConfigFile);
setInCurrentScope(kUseInternalConfig, m_UseInternalConfig);
setInCurrentScope(kServerHostname, m_ServerHostname);
setInCurrentScope(kPreventSleep, m_PreventSleep);
setInCurrentScope(kLanguageSync, m_LanguageSync);
setInCurrentScope(kInvertScrollDirection, m_InvertScrollDirection);
setInCurrentScope(kInvertConnection, m_InvertConnection);
setInCurrentScope(kEnableService, m_EnableService);
setInCurrentScope(kCloseToTray, m_CloseToTray);
setInCurrentScope(kMainWindowSize, m_MainWindowSize);
setInCurrentScope(kMainWindowPosition, m_MainWindowPosition);
setInCurrentScope(kShowCloseReminder, m_ShowCloseReminder);
setInCurrentScope(kEnableUpdateCheck, m_EnableUpdateCheck);
}
if (m_TlsChanged) {
m_TlsChanged = false;
Q_EMIT tlsChanged();
}
}
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)) {
auto loadFromSystemScope =
m_Scopes
.getFromScope(settingName(Setting::kLoadSystemSettings), m_LoadFromSystemScope, ConfigScopes::Scope::User)
.toBool();
if (loadFromSystemScope) {
qDebug("user settings indicates system scope should be used");
} else {
qDebug("user settings indicates user scope should be used");
}
setLoadFromSystemScope(loadFromSystemScope);
}
// ...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)) {
qDebug("system settings scope contains screen name, using system scope");
setLoadFromSystemScope(true);
}
}
void AppConfig::recallElevateMode()
{
using enum Setting;
if (!m_Scopes.scopeContains(settingName(kElevateMode))) {
qDebug("elevate mode not set yet, skipping");
return;
}
QVariant elevateMode = getFromCurrentScope(kElevateMode);
if (!elevateMode.isValid()) {
qDebug("elevate mode not valid, loading legacy setting");
elevateMode = getFromCurrentScope(kElevateModeLegacy, QVariant(static_cast<int>(kDefaultElevateMode)));
}
m_ElevateMode = static_cast<ElevateMode>(elevateMode.toInt());
}
QString AppConfig::settingName(Setting name)
{
auto index = static_cast<int>(name);
return m_SettingsName[index];
}
template <typename T> void AppConfig::setInCurrentScope(Setting name, T value)
{
m_Scopes.setInScope(settingName(name), value);
}
template <typename T> 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
{
return m_Scopes.getFromScope(settingName(name), defaultValue);
}
template <typename T>
std::optional<T> AppConfig::getFromCurrentScope(Setting name, std::function<T(const QVariant &)> toType) const
{
if (m_Scopes.scopeContains(settingName(name))) {
return toType(m_Scopes.getFromScope(settingName(name)));
} else {
return std::nullopt;
}
}
template <typename T> void AppConfig::setInCurrentScope(Setting name, const std::optional<T> &value)
{
if (value.has_value()) {
m_Scopes.setInScope(settingName(name), value.value());
}
}
QVariant AppConfig::findInAllScopes(Setting name, const QVariant &defaultValue) const
{
using enum ConfigScopes::Scope;
QVariant result(defaultValue);
QString setting(settingName(name));
if (m_Scopes.scopeContains(setting)) {
result = m_Scopes.getFromScope(setting, defaultValue);
} else if (m_Scopes.activeScope() == System) {
if (m_Scopes.scopeContains(setting, User)) {
result = m_Scopes.getFromScope(setting, defaultValue, User);
}
} else if (m_Scopes.scopeContains(setting, System)) {
result = m_Scopes.getFromScope(setting, defaultValue, System);
}
return result;
}
void AppConfig::loadScope(ConfigScopes::Scope scope)
{
using enum ConfigScopes::Scope;
switch (scope) {
case User:
qDebug("loading user settings scope");
break;
case System:
qDebug("loading system settings scope");
break;
default:
qFatal("invalid scope");
}
if (m_Scopes.activeScope() == scope) {
qDebug("already in required scope, skipping");
return;
}
m_Scopes.setActiveScope(scope);
qDebug("active scope file path: %s", qPrintable(m_Scopes.activeFilePath()));
// 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())) {
m_Scopes.signalReady();
} else {
qDebug("no screen name in scope, skipping");
}
}
void AppConfig::setLoadFromSystemScope(bool value)
{
using enum ConfigScopes::Scope;
if (value) {
loadScope(System);
} else {
loadScope(User);
}
// set after loading scope since it may have been overridden.
m_LoadFromSystemScope = value;
}
bool AppConfig::isActiveScopeWritable() const
{
return m_Scopes.isActiveScopeWritable();
}
bool AppConfig::isActiveScopeSystem() const
{
return m_Scopes.activeScope() == ConfigScopes::Scope::System;
}
QString AppConfig::logDir() const
{
// by default log to home dir
return QDir::home().absolutePath() + "/";
}
void AppConfig::persistLogDir() const
{
QDir dir = logDir();
// persist the log directory
if (!dir.exists()) {
dir.mkpath(dir.path());
}
}
///////////////////////////////////////////////////////////////////////////////
// Begin getters
///////////////////////////////////////////////////////////////////////////////
IConfigScopes &AppConfig::scopes() const
{
return m_Scopes;
}
const QString &AppConfig::screenName() const
{
return m_ScreenName;
}
int AppConfig::port() const
{
return m_Port;
}
const QString &AppConfig::networkInterface() const
{
return m_Interface;
}
int AppConfig::logLevel() const
{
return m_LogLevel;
}
bool AppConfig::logToFile() const
{
return m_LogToFile;
}
const QString &AppConfig::logFilename() const
{
return m_LogFilename;
}
QString AppConfig::logLevelText() const
{
return kLogLevelNames[logLevel()];
}
ProcessMode AppConfig::processMode() const
{
return m_EnableService ? ProcessMode::kService : ProcessMode::kDesktop;
}
bool AppConfig::wizardShouldRun() const
{
return m_WizardLastRun < kWizardVersion;
}
bool AppConfig::startedBefore() const
{
return m_StartedBefore;
}
QString AppConfig::lastVersion() const
{
return m_LastVersion;
}
QString AppConfig::coreServerName() const
{
#ifdef Q_OS_WIN
return s_winExeTemplate.arg(s_CoreServerName);
#else
return s_CoreServerName;
#endif
}
QString AppConfig::coreClientName() const
{
#ifdef Q_OS_WIN
return s_winExeTemplate.arg(s_CoreClientName);
#else
return s_CoreClientName;
#endif
}
ElevateMode AppConfig::elevateMode() const
{
return m_ElevateMode;
}
bool AppConfig::tlsEnabled() const
{
return m_TlsEnabled;
}
bool AppConfig::autoHide() const
{
return m_AutoHide;
}
bool AppConfig::invertScrollDirection() const
{
return m_InvertScrollDirection;
}
bool AppConfig::languageSync() const
{
return m_LanguageSync;
}
bool AppConfig::preventSleep() const
{
return m_PreventSleep;
}
bool AppConfig::invertConnection() const
{
return m_InvertConnection;
}
QString AppConfig::tlsCertPath() const
{
return m_TlsCertPath;
}
int AppConfig::tlsKeyLength() const
{
return m_TlsKeyLength;
}
bool AppConfig::enableService() const
{
return m_EnableService;
}
bool AppConfig::closeToTray() const
{
return m_CloseToTray;
}
bool AppConfig::serverGroupChecked() const
{
return m_ServerGroupChecked;
}
bool AppConfig::useExternalConfig() const
{
return m_UseExternalConfig;
}
const QString &AppConfig::configFile() const
{
return m_ConfigFile;
}
bool AppConfig::useInternalConfig() const
{
return m_UseInternalConfig;
}
bool AppConfig::clientGroupChecked() const
{
return m_ClientGroupChecked;
}
const QString &AppConfig::serverHostname() const
{
return m_ServerHostname;
}
std::optional<QSize> AppConfig::mainWindowSize() const
{
return m_MainWindowSize;
}
std::optional<QPoint> AppConfig::mainWindowPosition() const
{
return m_MainWindowPosition;
}
bool AppConfig::showCloseReminder() const
{
return m_ShowCloseReminder;
}
std::optional<bool> AppConfig::enableUpdateCheck() const
{
return m_EnableUpdateCheck;
}
///////////////////////////////////////////////////////////////////////////////
// End getters
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// Begin setters
///////////////////////////////////////////////////////////////////////////////
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.
m_TlsEnabled = 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.
m_TlsChanged = true;
}
m_TlsCertPath = 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.
m_TlsChanged = true;
}
m_TlsKeyLength = value;
}
void AppConfig::setServerGroupChecked(bool newValue)
{
m_ServerGroupChecked = newValue;
}
void AppConfig::setUseExternalConfig(bool newValue)
{
m_UseExternalConfig = newValue;
}
void AppConfig::setConfigFile(const QString &newValue)
{
m_ConfigFile = newValue;
}
void AppConfig::setUseInternalConfig(bool newValue)
{
m_UseInternalConfig = newValue;
}
void AppConfig::setClientGroupChecked(bool newValue)
{
m_ClientGroupChecked = newValue;
}
void AppConfig::setServerHostname(const QString &newValue)
{
m_ServerHostname = newValue;
}
void AppConfig::setLastVersion(const QString &version)
{
m_LastVersion = version;
}
void AppConfig::setScreenName(const QString &s)
{
m_ScreenName = s;
Q_EMIT screenNameChanged();
}
void AppConfig::setPort(int i)
{
m_Port = i;
}
void AppConfig::setNetworkInterface(const QString &s)
{
m_Interface = s;
}
void AppConfig::setLogLevel(int i)
{
m_LogLevel = i;
}
void AppConfig::setLogToFile(bool b)
{
m_LogToFile = b;
}
void AppConfig::setLogFilename(const QString &s)
{
m_LogFilename = s;
}
void AppConfig::setWizardHasRun()
{
m_WizardLastRun = kWizardVersion;
}
void AppConfig::setStartedBefore(bool b)
{
m_StartedBefore = b;
}
void AppConfig::setElevateMode(ElevateMode em)
{
m_ElevateMode = em;
}
void AppConfig::setAutoHide(bool b)
{
m_AutoHide = b;
}
void AppConfig::setInvertScrollDirection(bool newValue)
{
m_InvertScrollDirection = newValue;
}
void AppConfig::setLanguageSync(bool newValue)
{
m_LanguageSync = newValue;
}
void AppConfig::setPreventSleep(bool newValue)
{
m_PreventSleep = newValue;
}
void AppConfig::setEnableService(bool enabled)
{
m_EnableService = enabled;
}
void AppConfig::setCloseToTray(bool minimize)
{
m_CloseToTray = minimize;
}
void AppConfig::setInvertConnection(bool value)
{
m_InvertConnection = value;
Q_EMIT invertConnectionChanged();
}
void AppConfig::setMainWindowSize(const QSize &size)
{
m_MainWindowSize = size;
}
void AppConfig::setMainWindowPosition(const QPoint &position)
{
m_MainWindowPosition = position;
}
void AppConfig::setShowCloseReminder(bool value)
{
m_ShowCloseReminder = value;
}
void AppConfig::setEnableUpdateCheck(bool value)
{
m_EnableUpdateCheck = value;
}
///////////////////////////////////////////////////////////////////////////////
// End setters
///////////////////////////////////////////////////////////////////////////////
| 19,880
|
C++
|
.cpp
| 634
| 28.681388
| 118
| 0.731143
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,639
|
ScreenList.cpp
|
deskflow_deskflow/src/lib/gui/config/ScreenList.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2021 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScreenList.h"
#include <array>
namespace {
/**
* @brief getNeightborIndexes returns indexes for server neighbors
* @param serverIndex server index
* @param width of the grid
* @param size of the grid
* @return indexes for server neighbors
*/
std::array<int, 8> getNeighborsIndexes(int serverIndex, int width, int size)
{
const int UNSET = -1;
const int LEFT = 0;
const int RIGHT = 1;
const int TOP = 2;
const int BOTTOM = 3;
const int TOP_LEFT = 4;
const int TOP_RIGHT = 5;
const int BOTTOM_RIGHT = 6;
const int BOTTOM_LEFT = 7;
std::array<int, 8> indexes = {UNSET};
if (serverIndex >= 0 && serverIndex < size) {
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;
}
return indexes;
}
/**
* @brief getServerIndex finds server and returns it's index
* @param screens list to find server
* @return server index
*/
int getServerIndex(const ScreenList &screens)
{
int serverIndex = -1;
for (int i = 0; i < screens.size(); ++i) {
if (screens[i].isServer()) {
serverIndex = i;
break;
}
}
return serverIndex;
}
} // namespace
ScreenList::ScreenList(int width) : QList<Screen>(), m_width(width)
{
}
void ScreenList::addScreenByPriority(const Screen &newScreen)
{
int serverIndex = getServerIndex(*this);
auto indexes = getNeighborsIndexes(serverIndex, m_width, static_cast<int>(size()));
bool isAdded = false;
for (const auto &index : indexes) {
if (index >= 0 && index < size()) {
auto &screen = operator[](index);
if (screen.isNull()) {
screen = newScreen;
isAdded = true;
break;
}
}
}
if (!isAdded) {
addScreenToFirstEmpty(newScreen);
}
}
void ScreenList::addScreenToFirstEmpty(const Screen &newScreen)
{
for (int i = 0; i < size(); ++i) {
auto &screen = operator[](i);
if (screen.isNull()) {
screen = newScreen;
break;
}
}
}
bool ScreenList::operator==(const ScreenList &sc) const
{
return m_width == sc.m_width && QList::operator==(sc);
}
| 3,473
|
C++
|
.cpp
| 104
| 30.221154
| 112
| 0.674322
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,640
|
Screen.cpp
|
deskflow_deskflow/src/lib/gui/config/Screen.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Screen.h"
#include "config/ScreenConfig.h"
using namespace deskflow::gui::proxy;
using enum ScreenConfig::Modifier;
using enum ScreenConfig::SwitchCorner;
using enum ScreenConfig::Fix;
Screen::Screen()
{
init();
}
Screen::Screen(const QString &name)
{
init();
setName(name);
}
void Screen::init()
{
name().clear();
aliases().clear();
modifiers().clear();
switchCorners().clear();
fixes().clear();
setSwitchCornerSize(0);
// m_Modifiers, m_SwitchCorners and m_Fixes are QLists we use like fixed-size
// arrays, thus we need to make sure to fill them with the required number of
// elements.
for (int i = 0; i < static_cast<int>(NumModifiers); i++)
modifiers() << i;
for (int i = 0; i < static_cast<int>(NumSwitchCorners); i++)
switchCorners() << false;
for (int i = 0; i < static_cast<int>(NumFixes); i++)
fixes() << false;
}
void Screen::loadSettings(QSettingsProxy &settings)
{
setName(settings.value("name").toString());
if (name().isEmpty())
return;
setSwitchCornerSize(settings.value("switchCornerSize").toInt());
readSettings(settings, aliases(), "alias", QString(""));
readSettings(settings, modifiers(), "modifier", static_cast<int>(DefaultMod), static_cast<int>(NumModifiers));
readSettings(settings, switchCorners(), "switchCorner", 0, static_cast<int>(NumSwitchCorners));
readSettings(settings, fixes(), "fix", 0, static_cast<int>(NumFixes));
}
void Screen::saveSettings(QSettingsProxy &settings) const
{
settings.setValue("name", name());
if (name().isEmpty())
return;
settings.setValue("switchCornerSize", switchCornerSize());
writeSettings(settings, aliases(), "alias");
writeSettings(settings, modifiers(), "modifier");
writeSettings(settings, switchCorners(), "switchCorner");
writeSettings(settings, fixes(), "fix");
}
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;
for (int i = 0; i < fixes().size(); i++)
outStream << "\t\t" << fixName(i) << " = " << (fixes()[i] ? "true" : "false") << Qt::endl;
outStream << "\t\t"
<< "switchCorners = none ";
for (int i = 0; i < switchCorners().size(); i++)
if (switchCorners()[i])
outStream << "+" << switchCornerName(i) << " ";
outStream << Qt::endl;
outStream << "\t\t"
<< "switchCornerSize = " << switchCornerSize() << Qt::endl;
return outStream;
}
QTextStream &Screen::writeAliasesSection(QTextStream &outStream) const
{
if (!aliases().isEmpty()) {
outStream << "\t" << name() << ":" << Qt::endl;
for (const QString &alias : aliases())
outStream << "\t\t" << alias << Qt::endl;
}
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;
}
| 3,992
|
C++
|
.cpp
| 105
| 34.885714
| 112
| 0.678063
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,641
|
ScreenConfig.cpp
|
deskflow_deskflow/src/lib/gui/config/ScreenConfig.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 Symless Ltd.
* Copyright (C) 2008 Volker Lanz (vl@fidra.de)
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ScreenConfig.h"
const char *ScreenConfig::m_ModifierNames[] = {"shift", "ctrl", "alt", "meta", "super", "none"};
const char *ScreenConfig::m_FixNames[] = {
"halfDuplexCapsLock", "halfDuplexNumLock", "halfDuplexScrollLock", "xtestIsXineramaUnaware"
};
const char *ScreenConfig::m_SwitchCornerNames[] = {"top-left", "top-right", "bottom-left", "bottom-right"};
| 1,111
|
C++
|
.cpp
| 23
| 46.26087
| 107
| 0.741697
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,642
|
ConfigScopes.cpp
|
deskflow_deskflow/src/lib/gui/config/ConfigScopes.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2020 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "ConfigScopes.h"
#include "proxy/QSettingsProxy.h"
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QtCore/qfileinfo.h>
#include <QtCore/qlogging.h>
#include <memory>
namespace deskflow::gui {
using namespace proxy;
//
// ConfigScopes::Deps
//
std::shared_ptr<QSettingsProxy> ConfigScopes::Deps::makeUserSettings()
{
return std::make_shared<QSettingsProxy>();
}
std::shared_ptr<QSettingsProxy> ConfigScopes::Deps::makeSystemSettings()
{
return std::make_shared<QSettingsProxy>();
}
//
// ConfigScopes
//
ConfigScopes::ConfigScopes(std::shared_ptr<Deps> deps)
: m_pUserSettingsProxy(deps->makeUserSettings()),
m_pSystemSettingsProxy(deps->makeSystemSettings())
{
m_pUserSettingsProxy->loadUser();
m_pSystemSettingsProxy->loadSystem();
}
void ConfigScopes::clear() const
{
m_pUserSettingsProxy->clear();
m_pSystemSettingsProxy->clear();
}
void ConfigScopes::signalReady()
{
Q_EMIT ready();
}
void ConfigScopes::save(bool emitSaving)
{
if (emitSaving) {
qDebug("emitting config saving signal");
Q_EMIT saving();
}
qDebug("writing config to filesystem");
m_pUserSettingsProxy->sync();
m_pSystemSettingsProxy->sync();
}
bool ConfigScopes::isActiveScopeWritable() const
{
return activeSettings().isWritable();
}
void ConfigScopes::setActiveScope(ConfigScopes::Scope scope)
{
m_currentScope = scope;
}
ConfigScopes::Scope ConfigScopes::activeScope() const
{
return m_currentScope;
}
bool ConfigScopes::scopeContains(const QString &name, Scope scope) const
{
switch (scope) {
case Scope::User:
return m_pUserSettingsProxy->contains(name);
case Scope::System:
return m_pSystemSettingsProxy->contains(name);
default:
return activeSettings().contains(name);
}
}
QSettingsProxy &ConfigScopes::activeSettings()
{
if (m_currentScope == Scope::User) {
return *m_pUserSettingsProxy;
} else {
return *m_pSystemSettingsProxy;
}
}
const QSettingsProxy &ConfigScopes::activeSettings() const
{
if (m_currentScope == Scope::User) {
return *m_pUserSettingsProxy;
} else {
return *m_pSystemSettingsProxy;
}
}
QString ConfigScopes::activeFilePath() const
{
return activeSettings().fileName();
}
QVariant ConfigScopes::getFromScope(const QString &name, const QVariant &defaultValue, Scope scope) const
{
switch (scope) {
case Scope::User:
return m_pUserSettingsProxy->value(name, defaultValue);
case Scope::System:
return m_pSystemSettingsProxy->value(name, defaultValue);
default:
return activeSettings().value(name, defaultValue);
}
}
void ConfigScopes::setInScope(const QString &name, const QVariant &value, Scope scope)
{
switch (scope) {
case Scope::User:
m_pUserSettingsProxy->setValue(name, value);
break;
case Scope::System:
m_pSystemSettingsProxy->setValue(name, value);
break;
default:
activeSettings().setValue(name, value);
break;
}
}
} // namespace deskflow::gui
| 3,648
|
C++
|
.cpp
| 135
| 24.57037
| 105
| 0.756021
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,643
|
FunctionJob.cpp
|
deskflow_deskflow/src/lib/base/FunctionJob.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "base/FunctionJob.h"
//
// FunctionJob
//
FunctionJob::FunctionJob(void (*func)(void *), void *arg) : m_func(func), m_arg(arg)
{
// do nothing
}
FunctionJob::~FunctionJob()
{
// do nothing
}
void FunctionJob::run()
{
if (m_func != NULL) {
m_func(m_arg);
}
}
| 1,014
|
C++
|
.cpp
| 35
| 27.028571
| 84
| 0.729979
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,644
|
Stopwatch.cpp
|
deskflow_deskflow/src/lib/base/Stopwatch.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "base/Stopwatch.h"
#include "arch/Arch.h"
//
// Stopwatch
//
Stopwatch::Stopwatch(bool triggered) : m_mark(0.0), m_triggered(triggered), m_stopped(triggered)
{
if (!triggered) {
m_mark = ARCH->time();
}
}
Stopwatch::~Stopwatch()
{
// do nothing
}
double Stopwatch::reset()
{
if (m_stopped) {
const double dt = m_mark;
m_mark = 0.0;
return dt;
} else {
const double t = ARCH->time();
const double dt = t - m_mark;
m_mark = t;
return dt;
}
}
void Stopwatch::stop()
{
if (m_stopped) {
return;
}
// save the elapsed time
m_mark = ARCH->time() - m_mark;
m_stopped = true;
}
void Stopwatch::start()
{
m_triggered = false;
if (!m_stopped) {
return;
}
// set the mark such that it reports the time elapsed at stop()
m_mark = ARCH->time() - m_mark;
m_stopped = false;
}
void Stopwatch::setTrigger()
{
stop();
m_triggered = true;
}
double Stopwatch::getTime()
{
if (m_triggered) {
const double dt = m_mark;
start();
return dt;
} else if (m_stopped) {
return m_mark;
} else {
return ARCH->time() - m_mark;
}
}
Stopwatch::operator double()
{
return getTime();
}
bool Stopwatch::isStopped() const
{
return m_stopped;
}
double Stopwatch::getTime() const
{
if (m_stopped) {
return m_mark;
} else {
return ARCH->time() - m_mark;
}
}
Stopwatch::operator double() const
{
return getTime();
}
| 2,154
|
C++
|
.cpp
| 101
| 18.772277
| 96
| 0.679097
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,645
|
String.cpp
|
deskflow_deskflow/src/lib/base/String.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "base/String.h"
#include "arch/Arch.h"
#include "common/stdvector.h"
#include <algorithm>
#include <cctype>
#include <cerrno>
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <iomanip>
#include <sstream>
#include <stdio.h>
namespace deskflow {
namespace string {
String format(const char *fmt, ...)
{
va_list args;
va_start(args, fmt);
String result = vformat(fmt, args);
va_end(args);
return result;
}
String vformat(const char *fmt, va_list args)
{
// find highest indexed substitution and the locations of substitutions
std::vector<size_t> pos;
std::vector<size_t> width;
std::vector<size_t> index;
size_t maxIndex = 0;
size_t fmtLength = 0; // To store the length of fmt
const char *scan = fmt;
while (*scan) {
if (*scan == '%') {
++scan;
if (*scan == '\0') {
break;
} else if (*scan == '%') {
// literal
index.push_back(0);
pos.push_back(static_cast<size_t>((scan - 1) - fmt));
width.push_back(2);
} else if (*scan == '{') {
// get argument index
char *end;
errno = 0;
long i = strtol(scan + 1, &end, 10);
if (errno || (i < 0) || (*end != '}')) {
// invalid index -- ignore
scan = end - 1; // BUG if there are digits?
} else {
index.push_back(i);
pos.push_back(static_cast<size_t>((scan - 1) - fmt));
width.push_back(static_cast<size_t>((end - scan) + 2));
if (i > maxIndex) {
maxIndex = i;
}
scan = end;
}
} else {
// improper escape -- ignore
}
}
++scan;
++fmtLength; // Increment fmtLength for each character processed
}
// get args
std::vector<const char *> value;
std::vector<size_t> length;
value.push_back("%");
length.push_back(1);
for (int i = 0; i < maxIndex; ++i) {
const char *arg = va_arg(args, const char *);
size_t len = strnlen(arg, SIZE_MAX);
value.push_back(arg);
length.push_back(len);
}
// compute final length
size_t resultLength = fmtLength;
const int n = static_cast<int>(pos.size());
for (int i = 0; i < n; ++i) {
resultLength -= width[i];
resultLength += length[index[i]];
}
// substitute
String result;
result.reserve(resultLength);
size_t src = 0;
for (int i = 0; i < n; ++i) {
result.append(fmt + src, pos[i] - src);
result.append(value[index[i]]);
src = pos[i] + width[i];
}
result.append(fmt + src);
return result;
}
String sprintf(const char *fmt, ...)
{
char tmp[1024];
char *buffer = tmp;
int len = (int)(sizeof(tmp) / sizeof(tmp[0]));
String result;
while (buffer != NULL) {
// try printing into the buffer
va_list args;
va_start(args, fmt);
int n = ARCH->vsnprintf(buffer, len, fmt, args);
va_end(args);
// if the buffer wasn't big enough then make it bigger and try again
if (n < 0 || n > len) {
if (buffer != tmp) {
delete[] buffer;
}
len *= 2;
buffer = new char[len];
}
// if it was big enough then save the string and don't try again
else {
result = buffer;
if (buffer != tmp) {
delete[] buffer;
}
buffer = NULL;
}
}
return result;
}
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);
pos += replace.length();
}
}
String removeFileExt(String filename)
{
size_t dot = filename.find_last_of('.');
if (dot == String::npos) {
return filename;
}
return filename.substr(0, dot);
}
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];
}
subject = ss.str();
}
void uppercase(String &subject)
{
std::transform(subject.begin(), subject.end(), subject.begin(), ::toupper);
}
void removeChar(String &subject, const char c)
{
subject.erase(std::remove(subject.begin(), subject.end(), c), subject.end());
}
String sizeTypeToString(size_t n)
{
std::stringstream ss;
ss << n;
return ss.str();
}
size_t stringToSizeType(String string)
{
std::istringstream iss(string);
size_t value;
iss >> value;
return value;
}
std::vector<String> splitString(String string, const char c)
{
std::vector<String> results;
size_t head = 0;
size_t separator = string.find(c);
while (separator != String::npos) {
if (head != separator) {
results.push_back(string.substr(head, separator - head));
}
head = separator + 1;
separator = string.find(c, head);
}
if (head < string.size()) {
results.push_back(string.substr(head, string.size() - head));
}
return results;
}
//
// CaselessCmp
//
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)
{
// 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::equal(const String &a, const String &b)
{
return !(less(a, b) || less(b, a));
}
bool CaselessCmp::operator()(const String &a, const String &b) const
{
return less(a, b);
}
} // namespace string
} // namespace deskflow
| 6,499
|
C++
|
.cpp
| 234
| 24.051282
| 119
| 0.639384
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,646
|
Log.cpp
|
deskflow_deskflow/src/lib/base/Log.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "base/Log.h"
#include "arch/Arch.h"
#include "base/log_outputters.h"
#include "common/constants.h"
#include <cstdarg>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <ctime>
#include <iostream>
const int kPriorityPrefixLength = 3;
// names of priorities
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]));
// 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.
//
// GOTCHA: if `-DCMAKE_BUILD_TYPE=Debug` isn't set when configuring cmake
// for visual studio, then NDEBUG will be set (even if your VS solution
// config is Debug).
#ifndef NDEBUG
static const int g_defaultMaxPriority = kDEBUG;
#else
static const int g_defaultMaxPriority = kINFO;
#endif
namespace {
ELevel getPriority(const char *&fmt)
{
if (strnlen(fmt, SIZE_MAX) < kPriorityPrefixLength) {
throw std::invalid_argument("invalid format string, too short");
}
if (fmt[0] != '%' || fmt[1] != 'z') {
throw std::invalid_argument("invalid format string, missing priority");
}
return static_cast<ELevel>(fmt[2] - '0');
}
void makeTimeString(std::vector<char> &buffer)
{
const int yearOffset = 1900;
const int monthOffset = 1;
time_t t;
time(&t);
struct tm tm;
#if WINAPI_MSWINDOWS
localtime_s(&tm, &t);
#else
localtime_r(&t, &tm);
#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
);
}
std::vector<char> makeMessage(const char *filename, int lineNumber, const char *message, ELevel priority)
{
// base size includes null terminator, colon, space, etc.
const int baseSize = 10;
const int timeBufferSize = 50;
const int priorityMaxSize = 10;
std::vector<char> timeBuffer(timeBufferSize);
makeTimeString(timeBuffer);
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;
const auto filenameSet = filename != nullptr && filename[0] != '\0';
if (filenameSet) {
size_t filenameLength = strnlen(filename, SIZE_MAX);
size_t lineNumberLength = snprintf(nullptr, 0, "%d", lineNumber);
bufferSize += filenameLength + lineNumberLength;
std::vector<char> buffer(bufferSize);
snprintf(
buffer.data(), bufferSize, "[%s] %s: %s\n\t%s:%d", timeBuffer.data(), g_priority[priority], message, filename,
lineNumber
);
return buffer;
} else {
std::vector<char> buffer(bufferSize);
snprintf(buffer.data(), bufferSize, "[%s] %s: %s", timeBuffer.data(), g_priority[priority], message);
return buffer;
}
}
} // namespace
//
// Log
//
Log *Log::s_log = NULL;
Log::Log(bool singleton)
{
if (singleton) {
assert(s_log == NULL);
}
// create mutex for multithread safe operation
m_mutex = ARCH->newMutex();
// other initalization
m_maxPriority = g_defaultMaxPriority;
insert(new ConsoleLogOutputter);
if (singleton) {
s_log = this;
}
}
Log::Log(Log *src)
{
s_log = src;
}
Log::~Log()
{
// clean up
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) {
delete *index;
}
ARCH->closeMutex(m_mutex);
}
Log *Log::getInstance()
{
assert(s_log != NULL);
return s_log;
}
const char *Log::getFilterName() const
{
return getFilterName(getFilter());
}
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, ...)
{
const int initBufferSize = 1024;
const int bufferResizeScale = 2;
ELevel priority = getPriority(fmt);
fmt += kPriorityPrefixLength;
if (priority > getFilter()) {
return;
}
std::vector<char> buffer(initBufferSize);
auto length = static_cast<int>(buffer.size());
while (true) {
va_list args;
va_start(args, fmt);
int n = vsnprintf(buffer.data(), length, fmt, args);
va_end(args);
if (n < 0 || n > length) {
length *= bufferResizeScale;
buffer.resize(length);
} else {
break;
}
}
if (priority == kPRINT) {
output(priority, buffer.data());
} else {
auto message = makeMessage(file, line, buffer.data(), priority);
output(priority, message.data());
}
}
void Log::insert(ILogOutputter *outputter, bool alwaysAtHead)
{
assert(outputter != NULL);
ArchMutexLock lock(m_mutex);
if (alwaysAtHead) {
m_alwaysOutputters.push_front(outputter);
} else {
m_outputters.push_front(outputter);
}
outputter->open(kAppName);
// Issue 41
// don't show log unless user requests it, as some users find this
// feature irritating (i.e. when they lose network connectivity).
// in windows the log window can be displayed by selecting "show log"
// from the deskflow system tray icon.
// if this causes problems for other architectures, then a different
// work around should be attempted.
// outputter->show(false);
}
void Log::remove(ILogOutputter *outputter)
{
ArchMutexLock lock(m_mutex);
m_outputters.remove(outputter);
m_alwaysOutputters.remove(outputter);
}
void Log::pop_front(bool alwaysAtHead)
{
ArchMutexLock lock(m_mutex);
OutputterList *list = alwaysAtHead ? &m_alwaysOutputters : &m_outputters;
if (!list->empty()) {
delete list->front();
list->pop_front();
}
}
bool Log::setFilter(const char *maxPriority)
{
if (maxPriority != NULL) {
for (int i = 0; i < g_numPriority; ++i) {
if (strcmp(maxPriority, g_priority[i]) == 0) {
setFilter(i);
return true;
}
}
return false;
}
return true;
}
void Log::setFilter(int maxPriority)
{
ArchMutexLock lock(m_mutex);
m_maxPriority = maxPriority;
}
int Log::getFilter() const
{
ArchMutexLock lock(m_mutex);
return m_maxPriority;
}
void Log::output(ELevel priority, char *msg)
{
assert(priority >= -1 && priority < g_numPriority);
assert(msg != NULL);
if (!msg)
return;
ArchMutexLock lock(m_mutex);
OutputterList::const_iterator i;
for (i = m_alwaysOutputters.begin(); i != m_alwaysOutputters.end(); ++i) {
// write to outputter
(*i)->write(priority, msg);
}
for (i = m_outputters.begin(); i != m_outputters.end(); ++i) {
// write to outputter and break out of loop if it returns false
if (!(*i)->write(priority, msg)) {
break;
}
}
}
| 7,716
|
C++
|
.cpp
| 257
| 26.883268
| 118
| 0.691113
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,647
|
Path.cpp
|
deskflow_deskflow/src/lib/base/Path.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2014-2021 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "Path.h"
#if SYSAPI_WIN32
#include "arch/win32/ArchMiscWindows.h"
#endif
namespace deskflow {
namespace filesystem {
#ifdef SYSAPI_WIN32
std::wstring path(const String &filePath)
{
std::wstring result;
auto length = MultiByteToWideChar(CP_UTF8, 0, filePath.c_str(), static_cast<int>(filePath.length()), NULL, 0);
if (length > 0) {
result.resize(length);
MultiByteToWideChar(CP_UTF8, 0, filePath.c_str(), static_cast<int>(filePath.length()), &result[0], length);
}
return result;
}
#else
std::string path(const String &filePath)
{
return filePath;
}
#endif
} // namespace filesystem
} // namespace deskflow
| 1,336
|
C++
|
.cpp
| 41
| 30.487805
| 112
| 0.750195
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,648
|
Unicode.cpp
|
deskflow_deskflow/src/lib/base/Unicode.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "base/Unicode.h"
#include "arch/Arch.h"
#include <cstring>
//
// local utility functions
//
inline static UInt16 decode16(const UInt8 *n, bool byteSwapped)
{
union x16
{
UInt8 n8[2];
UInt16 n16;
} c;
if (byteSwapped) {
c.n8[0] = n[1];
c.n8[1] = n[0];
} else {
c.n8[0] = n[0];
c.n8[1] = n[1];
}
return c.n16;
}
inline static UInt32 decode32(const UInt8 *n, bool byteSwapped)
{
union x32
{
UInt8 n8[4];
UInt32 n32;
} c;
if (byteSwapped) {
c.n8[0] = n[3];
c.n8[1] = n[2];
c.n8[2] = n[1];
c.n8[3] = n[0];
} else {
c.n8[0] = n[0];
c.n8[1] = n[1];
c.n8[2] = n[2];
c.n8[3] = n[3];
}
return c.n32;
}
inline static void resetError(bool *errors)
{
if (errors != NULL) {
*errors = false;
}
}
inline static void setError(bool *errors)
{
if (errors != NULL) {
*errors = true;
}
}
//
// Unicode
//
UInt32 Unicode::s_invalid = 0x0000ffff;
UInt32 Unicode::s_replacement = 0x0000fffd;
bool Unicode::isUTF8(const String &src)
{
// convert and test each character
const UInt8 *data = reinterpret_cast<const UInt8 *>(src.c_str());
for (UInt32 n = (UInt32)src.size(); n > 0;) {
if (fromUTF8(data, n) == s_invalid) {
return false;
}
}
return true;
}
String Unicode::UTF8ToUCS2(const String &src, bool *errors)
{
// default to success
resetError(errors);
// get size of input string and reserve some space in output
UInt32 n = (UInt32)src.size();
String dst;
dst.reserve(2 * n);
// convert each character
const UInt8 *data = reinterpret_cast<const UInt8 *>(src.c_str());
while (n > 0) {
UInt32 c = fromUTF8(data, n);
if (c == s_invalid) {
c = s_replacement;
} else if (c >= 0x00010000) {
setError(errors);
c = s_replacement;
}
UInt16 ucs2 = static_cast<UInt16>(c);
dst.append(reinterpret_cast<const char *>(&ucs2), 2);
}
return dst;
}
String Unicode::UTF8ToUCS4(const String &src, bool *errors)
{
// default to success
resetError(errors);
// get size of input string and reserve some space in output
UInt32 n = (UInt32)src.size();
String dst;
dst.reserve(4 * n);
// convert each character
const UInt8 *data = reinterpret_cast<const UInt8 *>(src.c_str());
while (n > 0) {
UInt32 c = fromUTF8(data, n);
if (c == s_invalid) {
c = s_replacement;
}
dst.append(reinterpret_cast<const char *>(&c), 4);
}
return dst;
}
String Unicode::UTF8ToUTF16(const String &src, bool *errors)
{
// default to success
resetError(errors);
// get size of input string and reserve some space in output
UInt32 n = (UInt32)src.size();
String dst;
dst.reserve(2 * n);
// convert each character
const UInt8 *data = reinterpret_cast<const UInt8 *>(src.c_str());
while (n > 0) {
UInt32 c = fromUTF8(data, n);
if (c == s_invalid) {
c = s_replacement;
} else if (c >= 0x00110000) {
setError(errors);
c = s_replacement;
}
if (c < 0x00010000) {
UInt16 ucs2 = static_cast<UInt16>(c);
dst.append(reinterpret_cast<const char *>(&ucs2), 2);
} else {
c -= 0x00010000;
UInt16 utf16h = static_cast<UInt16>((c >> 10) + 0xd800);
UInt16 utf16l = static_cast<UInt16>((c & 0x03ff) + 0xdc00);
dst.append(reinterpret_cast<const char *>(&utf16h), 2);
dst.append(reinterpret_cast<const char *>(&utf16l), 2);
}
}
return dst;
}
String Unicode::UTF8ToUTF32(const String &src, bool *errors)
{
// default to success
resetError(errors);
// get size of input string and reserve some space in output
UInt32 n = (UInt32)src.size();
String dst;
dst.reserve(4 * n);
// convert each character
const UInt8 *data = reinterpret_cast<const UInt8 *>(src.c_str());
while (n > 0) {
UInt32 c = fromUTF8(data, n);
if (c == s_invalid) {
c = s_replacement;
} else if (c >= 0x00110000) {
setError(errors);
c = s_replacement;
}
dst.append(reinterpret_cast<const char *>(&c), 4);
}
return dst;
}
String Unicode::UTF8ToText(const String &src, bool *errors)
{
// default to success
resetError(errors);
// convert to wide char
UInt32 size;
wchar_t *tmp = UTF8ToWideChar(src, size, errors);
// convert string to multibyte
int len = ARCH->convStringWCToMB(NULL, tmp, size, errors);
char *mbs = new char[len + 1];
ARCH->convStringWCToMB(mbs, tmp, size, errors);
String text(mbs, len);
// clean up
delete[] mbs;
delete[] tmp;
return text;
}
String Unicode::UCS2ToUTF8(const String &src, bool *errors)
{
// default to success
resetError(errors);
// convert
UInt32 n = (UInt32)src.size() >> 1;
return doUCS2ToUTF8(reinterpret_cast<const UInt8 *>(src.data()), n, errors);
}
String Unicode::UCS4ToUTF8(const String &src, bool *errors)
{
// default to success
resetError(errors);
// convert
UInt32 n = (UInt32)src.size() >> 2;
return doUCS4ToUTF8(reinterpret_cast<const UInt8 *>(src.data()), n, errors);
}
String Unicode::UTF16ToUTF8(const String &src, bool *errors)
{
// default to success
resetError(errors);
// convert
UInt32 n = (UInt32)src.size() >> 1;
return doUTF16ToUTF8(reinterpret_cast<const UInt8 *>(src.data()), n, errors);
}
String Unicode::UTF32ToUTF8(const String &src, bool *errors)
{
// default to success
resetError(errors);
// convert
UInt32 n = (UInt32)src.size() >> 2;
return doUTF32ToUTF8(reinterpret_cast<const UInt8 *>(src.data()), n, errors);
}
String Unicode::textToUTF8(const String &src, bool *errors, IArchString::EWideCharEncoding encoding)
{
// default to success
resetError(errors);
// convert string to wide characters
UInt32 n = (UInt32)src.size();
int len = ARCH->convStringMBToWC(NULL, src.c_str(), n, errors);
wchar_t *wcs = new wchar_t[len + 1];
ARCH->convStringMBToWC(wcs, src.c_str(), n, errors);
// convert to UTF8
String utf8 = wideCharToUTF8(wcs, len, errors, encoding);
// clean up
delete[] wcs;
return utf8;
}
wchar_t *Unicode::UTF8ToWideChar(const String &src, UInt32 &size, bool *errors)
{
// convert to platform's wide character encoding
String tmp;
switch (ARCH->getWideCharEncoding()) {
case IArchString::kUCS2:
tmp = UTF8ToUCS2(src, errors);
size = (UInt32)tmp.size() >> 1;
break;
case IArchString::kUCS4:
tmp = UTF8ToUCS4(src, errors);
size = (UInt32)tmp.size() >> 2;
break;
case IArchString::kUTF16:
tmp = UTF8ToUTF16(src, errors);
size = (UInt32)tmp.size() >> 1;
break;
case IArchString::kUTF32:
tmp = UTF8ToUTF32(src, errors);
size = (UInt32)tmp.size() >> 2;
break;
default:
assert(0 && "unknown wide character encoding");
}
// copy to a wchar_t array
wchar_t *dst = new wchar_t[size];
::memcpy(dst, tmp.data(), sizeof(wchar_t) * size);
return dst;
}
String Unicode::wideCharToUTF8(const wchar_t *src, UInt32 size, bool *errors, IArchString::EWideCharEncoding encoding)
{
if (encoding == IArchString::kPlatformDetermined) {
encoding = ARCH->getWideCharEncoding();
}
// convert from platform's wide character encoding.
// note -- this must include a wide nul character (independent of
// the String's nul character).
switch (encoding) {
case IArchString::kUCS2:
return doUCS2ToUTF8(reinterpret_cast<const UInt8 *>(src), size, errors);
case IArchString::kUCS4:
return doUCS4ToUTF8(reinterpret_cast<const UInt8 *>(src), size, errors);
case IArchString::kUTF16:
return doUTF16ToUTF8(reinterpret_cast<const UInt8 *>(src), size, errors);
case IArchString::kUTF32:
return doUTF32ToUTF8(reinterpret_cast<const UInt8 *>(src), size, errors);
default:
assert(0 && "unknown wide character encoding");
return String();
}
}
String Unicode::doUCS2ToUTF8(const UInt8 *data, UInt32 n, bool *errors)
{
// make some space
String dst;
dst.reserve(n);
// check if first character is 0xfffe or 0xfeff
bool byteSwapped = false;
if (n >= 1) {
switch (decode16(data, false)) {
case 0x0000feff:
data += 2;
--n;
break;
case 0x0000fffe:
byteSwapped = true;
data += 2;
--n;
break;
default:
break;
}
}
// convert each character
for (; n > 0; --n) {
UInt32 c = decode16(data, byteSwapped);
toUTF8(dst, c, errors);
data += 2;
}
return dst;
}
String Unicode::doUCS4ToUTF8(const UInt8 *data, UInt32 n, bool *errors)
{
// make some space
String dst;
dst.reserve(n);
// check if first character is 0xfffe or 0xfeff
bool byteSwapped = false;
if (n >= 1) {
switch (decode32(data, false)) {
case 0x0000feff:
data += 4;
--n;
break;
case 0x0000fffe:
byteSwapped = true;
data += 4;
--n;
break;
default:
break;
}
}
// convert each character
for (; n > 0; --n) {
UInt32 c = decode32(data, byteSwapped);
toUTF8(dst, c, errors);
data += 4;
}
return dst;
}
String Unicode::doUTF16ToUTF8(const UInt8 *data, UInt32 n, bool *errors)
{
// make some space
String dst;
dst.reserve(n);
// check if first character is 0xfffe or 0xfeff
bool byteSwapped = false;
if (n >= 1) {
switch (decode16(data, false)) {
case 0x0000feff:
data += 2;
--n;
break;
case 0x0000fffe:
byteSwapped = true;
data += 2;
--n;
break;
default:
break;
}
}
// convert each character
while (n > 0) {
UInt32 c = decode16(data, byteSwapped);
if (c < 0x0000d800 || c > 0x0000dfff) {
toUTF8(dst, c, errors);
} else if (n == 1) {
// error -- missing second word
setError(errors);
toUTF8(dst, s_replacement, NULL);
} else if (c >= 0x0000d800 && c <= 0x0000dbff) {
UInt32 c2 = decode16(data, byteSwapped);
data += 2;
--n;
if (c2 < 0x0000dc00 || c2 > 0x0000dfff) {
// error -- [d800,dbff] not followed by [dc00,dfff]
setError(errors);
toUTF8(dst, s_replacement, NULL);
} else {
c = (((c - 0x0000d800) << 10) | (c2 - 0x0000dc00)) + 0x00010000;
toUTF8(dst, c, errors);
}
} else {
// error -- [dc00,dfff] without leading [d800,dbff]
setError(errors);
toUTF8(dst, s_replacement, NULL);
}
data += 2;
--n;
}
return dst;
}
String Unicode::doUTF32ToUTF8(const UInt8 *data, UInt32 n, bool *errors)
{
// make some space
String dst;
dst.reserve(n);
// check if first character is 0xfffe or 0xfeff
bool byteSwapped = false;
if (n >= 1) {
switch (decode32(data, false)) {
case 0x0000feff:
data += 4;
--n;
break;
case 0x0000fffe:
byteSwapped = true;
data += 4;
--n;
break;
default:
break;
}
}
// convert each character
for (; n > 0; --n) {
UInt32 c = decode32(data, byteSwapped);
if (c >= 0x00110000) {
setError(errors);
c = s_replacement;
}
toUTF8(dst, c, errors);
data += 4;
}
return dst;
}
UInt32 Unicode::fromUTF8(const UInt8 *&data, UInt32 &n)
{
assert(data != NULL);
assert(n != 0);
// compute character encoding length, checking for overlong
// sequences (i.e. characters that don't use the shortest
// possible encoding).
UInt32 size;
if (data[0] < 0x80) {
// 0xxxxxxx
size = 1;
} else if (data[0] < 0xc0) {
// 10xxxxxx -- in the middle of a multibyte character. counts
// as one invalid character.
--n;
++data;
return s_invalid;
} else if (data[0] < 0xe0) {
// 110xxxxx
size = 2;
} else if (data[0] < 0xf0) {
// 1110xxxx
size = 3;
} else if (data[0] < 0xf8) {
// 11110xxx
size = 4;
} else if (data[0] < 0xfc) {
// 111110xx
size = 5;
} else if (data[0] < 0xfe) {
// 1111110x
size = 6;
} else {
// invalid sequence. dunno how many bytes to skip so skip one.
--n;
++data;
return s_invalid;
}
// make sure we have enough data
if (size > n) {
data += n;
n = 0;
return s_invalid;
}
// extract character
UInt32 c;
switch (size) {
case 1:
c = static_cast<UInt32>(data[0]);
break;
case 2:
c = ((static_cast<UInt32>(data[0]) & 0x1f) << 6) | ((static_cast<UInt32>(data[1]) & 0x3f));
break;
case 3:
c = ((static_cast<UInt32>(data[0]) & 0x0f) << 12) | ((static_cast<UInt32>(data[1]) & 0x3f) << 6) |
((static_cast<UInt32>(data[2]) & 0x3f));
break;
case 4:
c = ((static_cast<UInt32>(data[0]) & 0x07) << 18) | ((static_cast<UInt32>(data[1]) & 0x3f) << 12) |
((static_cast<UInt32>(data[2]) & 0x3f) << 6) | ((static_cast<UInt32>(data[3]) & 0x3f));
break;
case 5:
c = ((static_cast<UInt32>(data[0]) & 0x03) << 24) | ((static_cast<UInt32>(data[1]) & 0x3f) << 18) |
((static_cast<UInt32>(data[2]) & 0x3f) << 12) | ((static_cast<UInt32>(data[3]) & 0x3f) << 6) |
((static_cast<UInt32>(data[4]) & 0x3f));
break;
case 6:
c = ((static_cast<UInt32>(data[0]) & 0x01) << 30) | ((static_cast<UInt32>(data[1]) & 0x3f) << 24) |
((static_cast<UInt32>(data[2]) & 0x3f) << 18) | ((static_cast<UInt32>(data[3]) & 0x3f) << 12) |
((static_cast<UInt32>(data[4]) & 0x3f) << 6) | ((static_cast<UInt32>(data[5]) & 0x3f));
break;
default:
assert(0 && "invalid size");
return s_invalid;
}
// check that all bytes after the first have the pattern 10xxxxxx.
// truncated sequences are treated as a single malformed character.
bool truncated = false;
switch (size) {
case 6:
if ((data[5] & 0xc0) != 0x80) {
truncated = true;
size = 5;
}
// fall through
case 5:
if ((data[4] & 0xc0) != 0x80) {
truncated = true;
size = 4;
}
// fall through
case 4:
if ((data[3] & 0xc0) != 0x80) {
truncated = true;
size = 3;
}
// fall through
case 3:
if ((data[2] & 0xc0) != 0x80) {
truncated = true;
size = 2;
}
// fall through
case 2:
if ((data[1] & 0xc0) != 0x80) {
truncated = true;
size = 1;
}
}
// update parameters
data += size;
n -= size;
// invalid if sequence was truncated
if (truncated) {
return s_invalid;
}
// check for characters that didn't use the smallest possible encoding
static UInt32 s_minChar[] = {0, 0x00000000, 0x00000080, 0x00000800, 0x00010000, 0x00200000, 0x04000000};
if (c < s_minChar[size]) {
return s_invalid;
}
// check for characters not in ISO-10646
if (c >= 0x0000d800 && c <= 0x0000dfff) {
return s_invalid;
}
if (c >= 0x0000fffe && c <= 0x0000ffff) {
return s_invalid;
}
return c;
}
void Unicode::toUTF8(String &dst, UInt32 c, bool *errors)
{
UInt8 data[6];
// handle characters outside the valid range
if ((c >= 0x0000d800 && c <= 0x0000dfff) || c >= 0x80000000) {
setError(errors);
c = s_replacement;
}
// convert to UTF-8
if (c < 0x00000080) {
data[0] = static_cast<UInt8>(c);
dst.append(reinterpret_cast<char *>(data), 1);
} else if (c < 0x00000800) {
data[0] = static_cast<UInt8>(((c >> 6) & 0x0000001f) + 0xc0);
data[1] = static_cast<UInt8>((c & 0x0000003f) + 0x80);
dst.append(reinterpret_cast<char *>(data), 2);
} else if (c < 0x00010000) {
data[0] = static_cast<UInt8>(((c >> 12) & 0x0000000f) + 0xe0);
data[1] = static_cast<UInt8>(((c >> 6) & 0x0000003f) + 0x80);
data[2] = static_cast<UInt8>((c & 0x0000003f) + 0x80);
dst.append(reinterpret_cast<char *>(data), 3);
} else if (c < 0x00200000) {
data[0] = static_cast<UInt8>(((c >> 18) & 0x00000007) + 0xf0);
data[1] = static_cast<UInt8>(((c >> 12) & 0x0000003f) + 0x80);
data[2] = static_cast<UInt8>(((c >> 6) & 0x0000003f) + 0x80);
data[3] = static_cast<UInt8>((c & 0x0000003f) + 0x80);
dst.append(reinterpret_cast<char *>(data), 4);
} else if (c < 0x04000000) {
data[0] = static_cast<UInt8>(((c >> 24) & 0x00000003) + 0xf8);
data[1] = static_cast<UInt8>(((c >> 18) & 0x0000003f) + 0x80);
data[2] = static_cast<UInt8>(((c >> 12) & 0x0000003f) + 0x80);
data[3] = static_cast<UInt8>(((c >> 6) & 0x0000003f) + 0x80);
data[4] = static_cast<UInt8>((c & 0x0000003f) + 0x80);
dst.append(reinterpret_cast<char *>(data), 5);
} else if (c < 0x80000000) {
data[0] = static_cast<UInt8>(((c >> 30) & 0x00000001) + 0xfc);
data[1] = static_cast<UInt8>(((c >> 24) & 0x0000003f) + 0x80);
data[2] = static_cast<UInt8>(((c >> 18) & 0x0000003f) + 0x80);
data[3] = static_cast<UInt8>(((c >> 12) & 0x0000003f) + 0x80);
data[4] = static_cast<UInt8>(((c >> 6) & 0x0000003f) + 0x80);
data[5] = static_cast<UInt8>((c & 0x0000003f) + 0x80);
dst.append(reinterpret_cast<char *>(data), 6);
} else {
assert(0 && "character out of range");
}
}
| 17,521
|
C++
|
.cpp
| 620
| 24.18871
| 118
| 0.622239
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,649
|
XBase.cpp
|
deskflow_deskflow/src/lib/base/XBase.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "base/XBase.h"
#include "base/String.h"
#include <cerrno>
#include <cstdarg>
#include <cstring>
//
// XBase
//
XBase::XBase() : std::runtime_error("")
{
// do nothing
}
XBase::XBase(const String &msg) : std::runtime_error(msg)
{
// do nothing
}
XBase::~XBase() _NOEXCEPT
{
// do nothing
}
const char *XBase::what() const _NOEXCEPT
{
if (const char *what = std::runtime_error::what(); what != nullptr && what[0] != '\0') {
return what;
}
m_what = getWhat();
return m_what.c_str();
}
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.
// format
String result;
va_list args;
va_start(args, fmt);
try {
result = deskflow::string::vformat(fmt, args);
} catch (...) {
// ignore
result.clear();
}
va_end(args);
return result;
}
| 1,649
|
C++
|
.cpp
| 62
| 24.322581
| 90
| 0.694162
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,650
|
Event.cpp
|
deskflow_deskflow/src/lib/base/Event.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2004 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "base/Event.h"
#include "base/EventQueue.h"
//
// Event
//
Event::Event() : m_type(kUnknown), m_target(NULL), m_data(NULL), m_flags(0), m_dataObject(nullptr)
{
// do nothing
}
Event::Event(Type type, void *target, void *data, Flags flags)
: m_type(type),
m_target(target),
m_data(data),
m_flags(flags),
m_dataObject(nullptr)
{
// do nothing
}
Event::Event(Type type, void *target, EventData *dataObject)
: m_type(type),
m_target(target),
m_data(nullptr),
m_flags(kNone),
m_dataObject(dataObject)
{
}
Event::Type Event::getType() const
{
return m_type;
}
void *Event::getTarget() const
{
return m_target;
}
void *Event::getData() const
{
return m_data;
}
EventData *Event::getDataObject() const
{
return m_dataObject;
}
Event::Flags Event::getFlags() const
{
return m_flags;
}
void Event::deleteData(const Event &event)
{
switch (event.getType()) {
case kUnknown:
case kQuit:
case kSystem:
case kTimer:
break;
default:
if ((event.getFlags() & kDontFreeData) == 0) {
free(event.getData());
delete event.getDataObject();
}
break;
}
}
void Event::setDataObject(EventData *dataObject)
{
assert(m_dataObject == nullptr);
m_dataObject = dataObject;
}
| 2,012
|
C++
|
.cpp
| 84
| 21.22619
| 98
| 0.705483
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,651
|
EventTypes.cpp
|
deskflow_deskflow/src/lib/base/EventTypes.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2013-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "base/EventTypes.h"
#include "base/IEventQueue.h"
#include <assert.h>
#include <stddef.h>
EventTypes::EventTypes() : m_events(NULL)
{
}
IEventQueue *EventTypes::getEvents() const
{
assert(m_events != NULL);
return m_events;
}
void EventTypes::setEvents(IEventQueue *events)
{
m_events = events;
}
//
// Client
//
REGISTER_EVENT(Client, connected)
REGISTER_EVENT(Client, connectionFailed)
REGISTER_EVENT(Client, connectionRefused)
REGISTER_EVENT(Client, disconnected)
//
// IStream
//
REGISTER_EVENT(IStream, inputReady)
REGISTER_EVENT(IStream, outputFlushed)
REGISTER_EVENT(IStream, outputError)
REGISTER_EVENT(IStream, inputShutdown)
REGISTER_EVENT(IStream, outputShutdown)
//
// IpcClient
//
REGISTER_EVENT(IpcClient, connected)
REGISTER_EVENT(IpcClient, messageReceived)
//
// IpcClientProxy
//
REGISTER_EVENT(IpcClientProxy, messageReceived)
REGISTER_EVENT(IpcClientProxy, disconnected)
//
// IpcServerProxy
//
REGISTER_EVENT(IpcServerProxy, messageReceived)
//
// IDataSocket
//
REGISTER_EVENT(IDataSocket, connected)
REGISTER_EVENT(IDataSocket, secureConnected)
REGISTER_EVENT(IDataSocket, connectionFailed)
//
// IListenSocket
//
REGISTER_EVENT(IListenSocket, connecting)
//
// ISocket
//
REGISTER_EVENT(ISocket, disconnected)
REGISTER_EVENT(ISocket, stopRetry)
//
// OSXScreen
//
REGISTER_EVENT(OSXScreen, confirmSleep)
//
// ClientListener
//
REGISTER_EVENT(ClientListener, accepted)
REGISTER_EVENT(ClientListener, connected)
//
// ClientProxy
//
REGISTER_EVENT(ClientProxy, ready)
REGISTER_EVENT(ClientProxy, disconnected)
//
// ClientProxyUnknown
//
REGISTER_EVENT(ClientProxyUnknown, success)
REGISTER_EVENT(ClientProxyUnknown, failure)
//
// Server
//
REGISTER_EVENT(Server, error)
REGISTER_EVENT(Server, connected)
REGISTER_EVENT(Server, disconnected)
REGISTER_EVENT(Server, switchToScreen)
REGISTER_EVENT(Server, switchInDirection)
REGISTER_EVENT(Server, keyboardBroadcast)
REGISTER_EVENT(Server, lockCursorToScreen)
REGISTER_EVENT(Server, screenSwitched)
//
// ServerApp
//
REGISTER_EVENT(ServerApp, reloadConfig)
REGISTER_EVENT(ServerApp, forceReconnect)
REGISTER_EVENT(ServerApp, resetServer)
//
// IKeyState
//
REGISTER_EVENT(IKeyState, keyDown)
REGISTER_EVENT(IKeyState, keyUp)
REGISTER_EVENT(IKeyState, keyRepeat)
//
// IPrimaryScreen
//
REGISTER_EVENT(IPrimaryScreen, buttonDown)
REGISTER_EVENT(IPrimaryScreen, buttonUp)
REGISTER_EVENT(IPrimaryScreen, motionOnPrimary)
REGISTER_EVENT(IPrimaryScreen, motionOnSecondary)
REGISTER_EVENT(IPrimaryScreen, wheel)
REGISTER_EVENT(IPrimaryScreen, screensaverActivated)
REGISTER_EVENT(IPrimaryScreen, screensaverDeactivated)
REGISTER_EVENT(IPrimaryScreen, hotKeyDown)
REGISTER_EVENT(IPrimaryScreen, hotKeyUp)
REGISTER_EVENT(IPrimaryScreen, fakeInputBegin)
REGISTER_EVENT(IPrimaryScreen, fakeInputEnd)
//
// IScreen
//
REGISTER_EVENT(IScreen, error)
REGISTER_EVENT(IScreen, shapeChanged)
REGISTER_EVENT(IScreen, suspend)
REGISTER_EVENT(IScreen, resume)
//
// IpcServer
//
REGISTER_EVENT(IpcServer, clientConnected)
REGISTER_EVENT(IpcServer, messageReceived)
//
// Clipboard
//
REGISTER_EVENT(Clipboard, clipboardGrabbed)
REGISTER_EVENT(Clipboard, clipboardChanged)
REGISTER_EVENT(Clipboard, clipboardSending)
//
// File
//
REGISTER_EVENT(File, fileChunkSending)
REGISTER_EVENT(File, fileRecieveCompleted)
REGISTER_EVENT(File, keepAlive)
//
// Ei
//
REGISTER_EVENT(Ei, connected)
REGISTER_EVENT(Ei, sessionClosed)
| 4,127
|
C++
|
.cpp
| 161
| 24.21118
| 72
| 0.818066
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,652
|
SimpleEventQueueBuffer.cpp
|
deskflow_deskflow/src/lib/base/SimpleEventQueueBuffer.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2004 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "base/SimpleEventQueueBuffer.h"
#include "arch/Arch.h"
#include "base/Stopwatch.h"
class EventQueueTimer
{
};
//
// SimpleEventQueueBuffer
//
SimpleEventQueueBuffer::SimpleEventQueueBuffer()
{
m_queueMutex = ARCH->newMutex();
m_queueReadyCond = ARCH->newCondVar();
m_queueReady = false;
}
SimpleEventQueueBuffer::~SimpleEventQueueBuffer()
{
ARCH->closeCondVar(m_queueReadyCond);
ARCH->closeMutex(m_queueMutex);
}
void SimpleEventQueueBuffer::waitForEvent(double timeout)
{
ArchMutexLock lock(m_queueMutex);
Stopwatch timer(true);
while (!m_queueReady) {
double timeLeft = timeout;
if (timeLeft >= 0.0) {
timeLeft -= timer.getTime();
if (timeLeft < 0.0) {
return;
}
}
ARCH->waitCondVar(m_queueReadyCond, m_queueMutex, timeLeft);
}
}
IEventQueueBuffer::Type SimpleEventQueueBuffer::getEvent(Event &, UInt32 &dataID)
{
ArchMutexLock lock(m_queueMutex);
if (!m_queueReady) {
return kNone;
}
dataID = m_queue.back();
m_queue.pop_back();
m_queueReady = !m_queue.empty();
return kUser;
}
bool SimpleEventQueueBuffer::addEvent(UInt32 dataID)
{
ArchMutexLock lock(m_queueMutex);
m_queue.push_front(dataID);
if (!m_queueReady) {
m_queueReady = true;
ARCH->broadcastCondVar(m_queueReadyCond);
}
return true;
}
bool SimpleEventQueueBuffer::isEmpty() const
{
ArchMutexLock lock(m_queueMutex);
return !m_queueReady;
}
EventQueueTimer *SimpleEventQueueBuffer::newTimer(double, bool) const
{
return new EventQueueTimer;
}
void SimpleEventQueueBuffer::deleteTimer(EventQueueTimer *timer) const
{
delete timer;
}
| 2,349
|
C++
|
.cpp
| 86
| 24.790698
| 81
| 0.750444
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,653
|
log_outputters.cpp
|
deskflow_deskflow/src/lib/base/log_outputters.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "base/log_outputters.h"
#include "arch/Arch.h"
#include "base/Path.h"
#include "base/TMethodJob.h"
#include <fstream>
enum EFileLogOutputter
{
kFileSizeLimit = 1024 // kb
};
//
// StopLogOutputter
//
StopLogOutputter::StopLogOutputter()
{
// do nothing
}
StopLogOutputter::~StopLogOutputter()
{
// do nothing
}
void StopLogOutputter::open(const char *)
{
// do nothing
}
void StopLogOutputter::close()
{
// do nothing
}
void StopLogOutputter::show(bool)
{
// do nothing
}
bool StopLogOutputter::write(ELevel, const char *)
{
return false;
}
//
// ConsoleLogOutputter
//
ConsoleLogOutputter::ConsoleLogOutputter()
{
}
ConsoleLogOutputter::~ConsoleLogOutputter()
{
}
void ConsoleLogOutputter::open(const char *title)
{
ARCH->openConsole(title);
}
void ConsoleLogOutputter::close()
{
ARCH->closeConsole();
}
void ConsoleLogOutputter::show(bool showIfEmpty)
{
ARCH->showConsole(showIfEmpty);
}
bool ConsoleLogOutputter::write(ELevel level, const char *msg)
{
ARCH->writeConsole(level, msg);
return true;
}
void ConsoleLogOutputter::flush()
{
}
//
// SystemLogOutputter
//
SystemLogOutputter::SystemLogOutputter()
{
// do nothing
}
SystemLogOutputter::~SystemLogOutputter()
{
// do nothing
}
void SystemLogOutputter::open(const char *title)
{
ARCH->openLog(title);
}
void SystemLogOutputter::close()
{
ARCH->closeLog();
}
void SystemLogOutputter::show(bool showIfEmpty)
{
ARCH->showLog(showIfEmpty);
}
bool SystemLogOutputter::write(ELevel level, const char *msg)
{
ARCH->writeLog(level, msg);
return true;
}
//
// SystemLogger
//
SystemLogger::SystemLogger(const char *title, bool blockConsole) : m_stop(NULL)
{
// redirect log messages
if (blockConsole) {
m_stop = new StopLogOutputter;
CLOG->insert(m_stop);
}
m_syslog = new SystemLogOutputter;
m_syslog->open(title);
CLOG->insert(m_syslog);
}
SystemLogger::~SystemLogger()
{
CLOG->remove(m_syslog);
delete m_syslog;
if (m_stop != NULL) {
CLOG->remove(m_stop);
delete m_stop;
}
}
//
// BufferedLogOutputter
//
BufferedLogOutputter::BufferedLogOutputter(UInt32 maxBufferSize) : m_maxBufferSize(maxBufferSize)
{
// do nothing
}
BufferedLogOutputter::~BufferedLogOutputter()
{
// do nothing
}
BufferedLogOutputter::const_iterator BufferedLogOutputter::begin() const
{
return m_buffer.begin();
}
BufferedLogOutputter::const_iterator BufferedLogOutputter::end() const
{
return m_buffer.end();
}
void BufferedLogOutputter::open(const char *)
{
// do nothing
}
void BufferedLogOutputter::close()
{
// remove all elements from the buffer
m_buffer.clear();
}
void BufferedLogOutputter::show(bool)
{
// do nothing
}
bool BufferedLogOutputter::write(ELevel, const char *message)
{
while (m_buffer.size() >= m_maxBufferSize) {
m_buffer.pop_front();
}
m_buffer.push_back(String(message));
return true;
}
//
// FileLogOutputter
//
FileLogOutputter::FileLogOutputter(const char *logFile)
{
setLogFilename(logFile);
}
FileLogOutputter::~FileLogOutputter()
{
}
void FileLogOutputter::setLogFilename(const char *logFile)
{
assert(logFile != NULL);
m_fileName = logFile;
}
bool FileLogOutputter::write(ELevel level, const char *message)
{
bool moveFile = false;
std::ofstream m_handle;
m_handle.open(deskflow::filesystem::path(m_fileName), std::fstream::app);
if (m_handle.is_open() && m_handle.fail() != true) {
m_handle << message << std::endl;
// when file size exceeds limits, move to 'old log' filename.
size_t p = m_handle.tellp();
if (p > (kFileSizeLimit * 1024)) {
moveFile = true;
}
}
m_handle.close();
if (moveFile) {
String oldLogFilename = deskflow::string::sprintf("%s.1", m_fileName.c_str());
remove(oldLogFilename.c_str());
rename(m_fileName.c_str(), oldLogFilename.c_str());
}
return true;
}
void FileLogOutputter::open(const char *title)
{
}
void FileLogOutputter::close()
{
}
void FileLogOutputter::show(bool showIfEmpty)
{
}
| 4,725
|
C++
|
.cpp
| 218
| 19.623853
| 97
| 0.74428
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,654
|
EventQueue.cpp
|
deskflow_deskflow/src/lib/base/EventQueue.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2004 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "base/EventQueue.h"
#include "arch/Arch.h"
#include "base/EventTypes.h"
#include "base/IEventJob.h"
#include "base/Log.h"
#include "base/SimpleEventQueueBuffer.h"
#include "base/Stopwatch.h"
#include "base/XBase.h"
#include "mt/Lock.h"
#include "mt/Mutex.h"
EVENT_TYPE_ACCESSOR(Client)
EVENT_TYPE_ACCESSOR(IStream)
EVENT_TYPE_ACCESSOR(IpcClient)
EVENT_TYPE_ACCESSOR(IpcClientProxy)
EVENT_TYPE_ACCESSOR(IpcServer)
EVENT_TYPE_ACCESSOR(IpcServerProxy)
EVENT_TYPE_ACCESSOR(IDataSocket)
EVENT_TYPE_ACCESSOR(IListenSocket)
EVENT_TYPE_ACCESSOR(ISocket)
EVENT_TYPE_ACCESSOR(OSXScreen)
EVENT_TYPE_ACCESSOR(ClientListener)
EVENT_TYPE_ACCESSOR(ClientProxy)
EVENT_TYPE_ACCESSOR(ClientProxyUnknown)
EVENT_TYPE_ACCESSOR(Server)
EVENT_TYPE_ACCESSOR(ServerApp)
EVENT_TYPE_ACCESSOR(IKeyState)
EVENT_TYPE_ACCESSOR(IPrimaryScreen)
EVENT_TYPE_ACCESSOR(IScreen)
EVENT_TYPE_ACCESSOR(Clipboard)
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)
{
EventQueue *events = static_cast<EventQueue *>(data);
events->addEvent(Event(Event::kQuit));
}
//
// EventQueue
//
EventQueue::EventQueue()
: m_systemTarget(0),
m_nextType(Event::kLast),
m_typesForClient(NULL),
m_typesForIStream(NULL),
m_typesForIpcClient(NULL),
m_typesForIpcClientProxy(NULL),
m_typesForIpcServer(NULL),
m_typesForIpcServerProxy(NULL),
m_typesForIDataSocket(NULL),
m_typesForIListenSocket(NULL),
m_typesForISocket(NULL),
m_typesForOSXScreen(NULL),
m_typesForClientListener(NULL),
m_typesForClientProxy(NULL),
m_typesForClientProxyUnknown(NULL),
m_typesForServer(NULL),
m_typesForServerApp(NULL),
m_typesForIKeyState(NULL),
m_typesForIPrimaryScreen(NULL),
m_typesForIScreen(NULL),
m_typesForClipboard(NULL),
m_typesForFile(NULL),
m_typesForEi(NULL),
m_readyMutex(new Mutex),
m_readyCondVar(new CondVar<bool>(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()
{
delete m_buffer;
delete m_readyCondVar;
delete m_readyMutex;
ARCH->setSignalHandler(Arch::kINTERRUPT, NULL, NULL);
ARCH->setSignalHandler(Arch::kTERMINATE, NULL, NULL);
ARCH->closeMutex(m_mutex);
}
void EventQueue::loop()
{
m_buffer->init();
{
Lock lock(m_readyMutex);
*m_readyCondVar = true;
m_readyCondVar->signal();
}
LOG((CLOG_DEBUG "event queue is ready"));
while (!m_pending.empty()) {
LOG((CLOG_DEBUG "add pending events to buffer"));
Event &event = m_pending.front();
addEventToBuffer(event);
m_pending.pop();
}
Event event;
getEvent(event);
while (event.getType() != Event::kQuit) {
dispatchEvent(event);
Event::deleteData(event);
getEvent(event);
}
}
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));
m_nameMap.insert(std::make_pair(name, m_nextType));
LOG((CLOG_DEBUG1 "registered event type %s as %d", name, m_nextType));
type = m_nextType++;
}
return type;
}
const char *EventQueue::getTypeName(Event::Type type)
{
switch (type) {
case Event::kUnknown:
return "nil";
case Event::kQuit:
return "quit";
case Event::kSystem:
return "system";
case Event::kTimer:
return "timer";
default:
TypeMap::const_iterator i = m_typeMap.find(type);
if (i == m_typeMap.end()) {
return "<unknown>";
} else {
return i->second;
}
}
}
void EventQueue::adoptBuffer(IEventQueueBuffer *buffer)
{
ArchMutexLock lock(m_mutex);
LOG((CLOG_DEBUG "adopting new buffer"));
if (m_events.size() != 0) {
// this can come as a nasty surprise to programmers expecting
// their events to be raised, only to have them deleted.
LOG((CLOG_DEBUG "discarding %d event(s)", m_events.size()));
}
// discard old buffer and old events
delete m_buffer;
for (EventTable::iterator i = m_events.begin(); i != m_events.end(); ++i) {
Event::deleteData(i->second);
}
m_events.clear();
m_oldEventIDs.clear();
// use new buffer
m_buffer = buffer;
if (m_buffer == NULL) {
m_buffer = new SimpleEventQueueBuffer;
}
}
bool EventQueue::getEvent(Event &event, double timeout)
{
Stopwatch timer(true);
retry:
// if no events are waiting then handle timers and then wait
while (m_buffer->isEmpty()) {
// handle timers first
if (hasTimerExpired(event)) {
return true;
}
// get time remaining in timeout
double timeLeft = timeout - timer.getTime();
if (timeout >= 0.0 && timeLeft <= 0.0) {
return false;
}
// get time until next timer expires. if there is a timer
// and it'll expire before the client's timeout then use
// that duration for our timeout instead.
double timerTimeout = getNextTimerTimeout();
if (timeout < 0.0 || (timerTimeout >= 0.0 && timerTimeout < timeLeft)) {
timeLeft = timerTimeout;
}
// wait for an event
m_buffer->waitForEvent(timeLeft);
}
// get the event
UInt32 dataID;
IEventQueueBuffer::Type type = m_buffer->getEvent(event, dataID);
switch (type) {
case IEventQueueBuffer::kNone:
if (timeout < 0.0 || timeout <= timer.getTime()) {
// don't want to fail if client isn't expecting that
// so if getEvent() fails with an infinite timeout
// then just try getting another event.
goto retry;
}
return false;
case IEventQueueBuffer::kSystem:
return true;
case IEventQueueBuffer::kUser: {
ArchMutexLock lock(m_mutex);
event = removeEvent(dataID);
return true;
}
default:
assert(0 && "invalid event type");
return false;
}
}
bool EventQueue::dispatchEvent(const Event &event)
{
void *target = event.getTarget();
IEventJob *job = getHandler(event.getType(), target);
if (job == NULL) {
job = getHandler(Event::kUnknown, target);
}
if (job != NULL) {
job->run(event);
return true;
}
return false;
}
void EventQueue::addEvent(const Event &event)
{
// discard bogus event types
switch (event.getType()) {
case Event::kUnknown:
case Event::kSystem:
case Event::kTimer:
return;
default:
break;
}
if ((event.getFlags() & Event::kDeliverImmediately) != 0) {
dispatchEvent(event);
Event::deleteData(event);
} else if (!(*m_readyCondVar)) {
m_pending.push(event);
} else {
addEventToBuffer(event);
}
}
void EventQueue::addEventToBuffer(const Event &event)
{
ArchMutexLock lock(m_mutex);
// store the event's data locally
UInt32 eventID = saveEvent(event);
// add it
if (!m_buffer->addEvent(eventID)) {
// failed to send event
removeEvent(eventID);
Event::deleteData(event);
}
}
EventQueueTimer *EventQueue::newTimer(double duration, void *target)
{
assert(duration > 0.0);
EventQueueTimer *timer = m_buffer->newTimer(duration, false);
if (target == NULL) {
target = timer;
}
ArchMutexLock lock(m_mutex);
m_timers.insert(timer);
// 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));
return timer;
}
EventQueueTimer *EventQueue::newOneShotTimer(double duration, void *target)
{
assert(duration > 0.0);
EventQueueTimer *timer = m_buffer->newTimer(duration, true);
if (target == NULL) {
target = timer;
}
ArchMutexLock lock(m_mutex);
m_timers.insert(timer);
// 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));
return timer;
}
void EventQueue::deleteTimer(EventQueueTimer *timer)
{
ArchMutexLock lock(m_mutex);
for (TimerQueue::iterator index = m_timerQueue.begin(); index != m_timerQueue.end(); ++index) {
if (index->getTimer() == timer) {
m_timerQueue.erase(index);
break;
}
}
Timers::iterator index = m_timers.find(timer);
if (index != m_timers.end()) {
m_timers.erase(index);
}
m_buffer->deleteTimer(timer);
}
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)
{
IEventJob *handler = NULL;
{
ArchMutexLock lock(m_mutex);
HandlerTable::iterator index = m_handlers.find(target);
if (index != m_handlers.end()) {
TypeHandlerTable &typeHandlers = index->second;
TypeHandlerTable::iterator index2 = typeHandlers.find(type);
if (index2 != typeHandlers.end()) {
handler = index2->second;
typeHandlers.erase(index2);
}
}
}
delete handler;
}
void EventQueue::removeHandlers(void *target)
{
std::vector<IEventJob *> handlers;
{
ArchMutexLock lock(m_mutex);
HandlerTable::iterator index = m_handlers.find(target);
if (index != m_handlers.end()) {
// copy to handlers array and clear table for target
TypeHandlerTable &typeHandlers = index->second;
for (TypeHandlerTable::iterator index2 = typeHandlers.begin(); index2 != typeHandlers.end(); ++index2) {
handlers.push_back(index2->second);
}
typeHandlers.clear();
}
}
// delete handlers
for (std::vector<IEventJob *>::iterator index = handlers.begin(); index != handlers.end(); ++index) {
delete *index;
}
}
bool EventQueue::isEmpty() const
{
return (m_buffer->isEmpty() && getNextTimerTimeout() != 0.0);
}
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()) {
const TypeHandlerTable &typeHandlers = index->second;
TypeHandlerTable::const_iterator index2 = typeHandlers.find(type);
if (index2 != typeHandlers.end()) {
return index2->second;
}
}
return NULL;
}
UInt32 EventQueue::saveEvent(const Event &event)
{
// choose id
UInt32 id;
if (!m_oldEventIDs.empty()) {
// reuse an id
id = m_oldEventIDs.back();
m_oldEventIDs.pop_back();
} else {
// make a new id
id = static_cast<UInt32>(m_events.size());
}
// save data
m_events[id] = event;
return id;
}
Event EventQueue::removeEvent(UInt32 eventID)
{
// look up id
EventTable::iterator index = m_events.find(eventID);
if (index == m_events.end()) {
return Event();
}
// get data
Event event = index->second;
m_events.erase(index);
// save old id for reuse
m_oldEventIDs.push_back(eventID);
return 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.
if (m_timerQueue.empty()) {
return false;
}
// get time elapsed since last check
const double time = m_time.getTime();
m_time.reset();
// countdown elapsed time
for (TimerQueue::iterator index = m_timerQueue.begin(); index != m_timerQueue.end(); ++index) {
(*index) -= time;
}
// done if no timers are expired
if (m_timerQueue.top() > 0.0) {
return false;
}
// remove timer from queue
Timer timer = m_timerQueue.top();
m_timerQueue.pop();
// prepare event and reset the timer's clock
timer.fillEvent(m_timerEvent);
event = Event(Event::kTimer, timer.getTarget(), &m_timerEvent);
timer.reset();
// reinsert timer into queue if it's not a one-shot
if (!timer.isOneShot()) {
m_timerQueue.push(timer);
}
return true;
}
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.
if (m_timerQueue.empty()) {
return -1.0;
}
if (m_timerQueue.top() <= 0.0) {
return 0.0;
}
return m_timerQueue.top();
}
Event::Type EventQueue::getRegisteredType(const String &name) const
{
NameMap::const_iterator found = m_nameMap.find(name);
if (found != m_nameMap.end())
return found->second;
return Event::kUnknown;
}
void *EventQueue::getSystemTarget()
{
// any unique arbitrary pointer will do
return &m_systemTarget;
}
void EventQueue::waitForReady() const
{
double timeout = ARCH->time() + 10;
Lock lock(m_readyMutex);
while (!m_readyCondVar->wait()) {
if (ARCH->time() > timeout) {
throw std::runtime_error("event queue is not ready within 5 sec");
}
}
}
//
// EventQueue::Timer
//
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)
{
assert(m_timeout > 0.0);
}
EventQueue::Timer::~Timer()
{
// do nothing
}
void EventQueue::Timer::reset()
{
m_time = m_timeout;
}
EventQueue::Timer &EventQueue::Timer::operator-=(double dt)
{
m_time -= dt;
return *this;
}
EventQueue::Timer::operator double() const
{
return m_time;
}
bool EventQueue::Timer::isOneShot() const
{
return m_oneShot;
}
EventQueueTimer *EventQueue::Timer::getTimer() const
{
return m_timer;
}
void *EventQueue::Timer::getTarget() const
{
return m_target;
}
void EventQueue::Timer::fillEvent(TimerEvent &event) const
{
event.m_timer = m_timer;
event.m_count = 0;
if (m_time <= 0.0) {
event.m_count = static_cast<UInt32>((m_timeout - m_time) / m_timeout);
}
}
bool EventQueue::Timer::operator<(const Timer &t) const
{
return m_time < t.m_time;
}
| 14,884
|
C++
|
.cpp
| 524
| 25.057252
| 112
| 0.699622
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,655
|
FunctionEventJob.cpp
|
deskflow_deskflow/src/lib/base/FunctionEventJob.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2004 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "base/FunctionEventJob.h"
//
// FunctionEventJob
//
FunctionEventJob::FunctionEventJob(void (*func)(const Event &, void *), void *arg) : m_func(func), m_arg(arg)
{
// do nothing
}
FunctionEventJob::~FunctionEventJob()
{
// do nothing
}
void FunctionEventJob::run(const Event &event)
{
if (m_func != NULL) {
m_func(event, m_arg);
}
}
| 1,089
|
C++
|
.cpp
| 35
| 29.171429
| 109
| 0.739752
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,656
|
HelloBack.cpp
|
deskflow_deskflow/src/lib/client/HelloBack.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
*
* SPDX-FileCopyrightText: Copyright (C) 2024 Symless Ltd.
* SPDX-License-Identifier: GPL-2.0
*/
#include "HelloBack.h"
#include "base/Log.h"
#include "deskflow/ProtocolUtil.h"
#include "deskflow/protocol_types.h"
#include <map>
#include <set>
namespace deskflow::client {
//
// HelloBack::Deps
//
void HelloBack::Deps::invalidHello()
{
m_invalidHello();
}
void HelloBack::Deps::incompatible(int major, int minor)
{
m_incompatible(major, minor);
}
//
// HelloBack
//
void HelloBack::handleHello(deskflow::IStream *stream, const std::string &clientName) const
{
SInt16 serverMajor;
SInt16 serverMinor;
// as luck would have it, both "Synergy" and "Barrier" are 7 chars,
// so we eat 7 chars and then test for either protocol name.
// we cannot re-use `readf` to check for various hello messages,
// as `readf` eats bytes (advances the stream position reference).
std::string protocolName;
ProtocolUtil::readf(stream, kMsgHello, &protocolName, &serverMajor, &serverMinor);
if (protocolName != kSynergyProtocolName && protocolName != kBarrierProtocolName) {
m_deps->invalidHello();
return;
}
// check versions
LOG_DEBUG("got hello from %s, protocol v%d.%d", protocolName.c_str(), serverMajor, serverMinor);
const auto helloBackMajor = m_majorVersion;
auto helloBackMinor = m_minorVersion;
if (shouldDowngrade(serverMajor, serverMinor)) {
LOG_NOTE("downgrading to %d.%d protocol for server", serverMajor, serverMinor);
helloBackMinor = serverMinor;
} else if (serverMajor < m_majorVersion || (serverMajor == m_majorVersion && serverMinor < m_minorVersion)) {
m_deps->incompatible(serverMajor, serverMinor);
return;
}
// say hello back with same protocol name and version
LOG_DEBUG(
"saying hello back with version %s %d.%d", //
protocolName.c_str(), helloBackMajor, helloBackMinor
);
// dynamically build write format for hello back since `ProtocolUtil::writef`
// doesn't support formatting fixed length strings yet.
std::string helloBackMessage = protocolName + kMsgHelloBackArgs;
ProtocolUtil::writef(stream, helloBackMessage.c_str(), helloBackMajor, helloBackMinor, &clientName);
}
bool HelloBack::shouldDowngrade(int major, int minor) const
{
const std::map<int, std::set<int>> map{
// 1.6 is compatible with 1.7 and 1.8
{6, {7, 8}},
// 1.7 is compatible with 1.8
{7, {8}},
};
if (major == m_majorVersion) {
auto versions = map.find(minor);
if (versions != map.end()) {
auto compatibleVersions = versions->second;
if (compatibleVersions.find(m_minorVersion) != compatibleVersions.end()) {
return true;
}
}
}
return false;
}
} // namespace deskflow::client
| 2,796
|
C++
|
.cpp
| 82
| 30.829268
| 111
| 0.717787
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,657
|
Client.cpp
|
deskflow_deskflow/src/lib/client/Client.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "client/Client.h"
#include "arch/Arch.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "base/TMethodJob.h"
#include "client/ServerProxy.h"
#include "common/stdexcept.h"
#include "deskflow/AppUtil.h"
#include "deskflow/DropHelper.h"
#include "deskflow/FileChunk.h"
#include "deskflow/IPlatformScreen.h"
#include "deskflow/PacketStreamFilter.h"
#include "deskflow/ProtocolUtil.h"
#include "deskflow/Screen.h"
#include "deskflow/StreamChunker.h"
#include "deskflow/XDeskflow.h"
#include "deskflow/protocol_types.h"
#include "mt/Thread.h"
#include "net/IDataSocket.h"
#include "net/ISocketFactory.h"
#include "net/SecureSocket.h"
#include "net/TCPSocket.h"
#include <algorithm>
#include <climits>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
#include <memory>
#include <sstream>
using namespace deskflow::client;
//
// Client
//
Client::Client(
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),
m_socketFactory(socketFactory),
m_screen(screen),
m_stream(NULL),
m_timer(NULL),
m_server(NULL),
m_ready(false),
m_active(false),
m_suspended(false),
m_connectOnResume(false),
m_events(events),
m_sendFileThread(nullptr),
m_writeToDropDirThread(nullptr),
m_useSecureNetwork(args.m_enableCrypto),
m_args(args),
m_enableClipboard(true),
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<Client>(this, &Client::handleSuspend)
);
m_events->adoptHandler(
m_events->forIScreen().resume(), getEventTarget(), new TMethodEventJob<Client>(this, &Client::handleResume)
);
if (m_args.m_enableDragDrop) {
m_events->adoptHandler(
m_events->forFile().fileChunkSending(), this, new TMethodEventJob<Client>(this, &Client::handleFileChunkSending)
);
m_events->adoptHandler(
m_events->forFile().fileRecieveCompleted(), this,
new TMethodEventJob<Client>(this, &Client::handleFileRecieveCompleted)
);
}
m_pHelloBack = std::make_unique<HelloBack>(std::make_shared<HelloBack::Deps>(
[this]() {
sendConnectionFailedEvent("got invalid hello message from server");
cleanupTimer();
cleanupConnection();
},
[this](int major, int minor) {
sendConnectionFailedEvent(XIncompatibleClient(major, minor).what());
cleanupTimer();
cleanupConnection();
}
));
}
Client::~Client()
{
if (m_mock) {
return;
}
m_events->removeHandler(m_events->forIScreen().suspend(), getEventTarget());
m_events->removeHandler(m_events->forIScreen().resume(), getEventTarget());
cleanupTimer();
cleanupScreen();
cleanupConnecting();
cleanupConnection();
delete m_socketFactory;
}
void Client::connect(size_t addressIndex)
{
if (m_stream != NULL) {
return;
}
if (m_suspended) {
m_connectOnResume = true;
return;
}
try {
if (m_args.m_hostMode) {
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
// has changed (which can happen frequently if this is a laptop
// being shuttled between various networks). patch by Brent
// Priddy.
m_resolvedAddressesCount = m_serverAddress.resolve(addressIndex);
// m_serverAddress will be null if the hostname address is not reolved
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())
);
}
}
// create the socket
IDataSocket *socket =
m_socketFactory->create(m_useSecureNetwork, ARCH->getAddrFamily(m_serverAddress.getAddress()));
bindNetworkInterface(socket);
// filter socket messages, including a packetizing filter
m_stream = new PacketStreamFilter(m_events, socket, true);
// connect
LOG((CLOG_DEBUG1 "connecting to server"));
setupConnecting();
setupTimer();
socket->connect(m_serverAddress);
} catch (XBase &e) {
cleanupTimer();
cleanupConnecting();
cleanupStream();
LOG((CLOG_DEBUG1 "connection failed"));
sendConnectionFailedEvent(e.what());
return;
}
}
void Client::disconnect(const char *msg)
{
cleanup();
if (msg) {
sendConnectionFailedEvent(msg);
} else {
sendEvent(m_events->forClient().disconnected(), NULL);
}
}
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);
m_events->addEvent(event);
}
}
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::isConnecting() const
{
return (m_timer != NULL);
}
NetworkAddress Client::getServerAddress() const
{
return m_serverAddress;
}
void *Client::getEventTarget() const
{
return m_screen->getEventTarget();
}
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
{
m_screen->getShape(x, y, w, h);
}
void Client::getCursorPos(SInt32 &x, SInt32 &y) const
{
m_screen->getCursorPos(x, y);
}
void Client::enter(SInt32 xAbs, SInt32 yAbs, UInt32, KeyModifierMask mask, bool)
{
m_active = true;
m_screen->mouseMove(xAbs, yAbs);
m_screen->enter(mask);
if (m_sendFileThread) {
StreamChunker::interruptFile();
m_sendFileThread.reset(nullptr);
}
}
bool Client::leave()
{
m_active = false;
m_screen->leave();
if (m_enableClipboard) {
// send clipboards that we own and that have changed
for (ClipboardID id = 0; id < kClipboardEnd; ++id) {
if (m_ownClipboard[id]) {
sendClipboard(id);
}
}
}
return true;
}
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)
{
m_screen->grabClipboard(id);
m_ownClipboard[id] = false;
m_sentClipboard[id] = false;
}
void Client::setClipboardDirty(ClipboardID, bool)
{
assert(0 && "shouldn't be called");
}
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)
{
m_screen->keyRepeat(id, mask, count, button, lang);
}
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::mouseUp(ButtonID id)
{
m_screen->mouseUp(id);
}
void Client::mouseMove(SInt32 x, SInt32 y)
{
m_screen->mouseMove(x, y);
}
void Client::mouseRelativeMove(SInt32 dx, SInt32 dy)
{
m_screen->mouseRelativeMove(dx, dy);
}
void Client::mouseWheel(SInt32 xDelta, SInt32 yDelta)
{
m_screen->mouseWheel(xDelta, yDelta);
}
void Client::screensaver(bool activate)
{
m_screen->screensaver(activate);
}
void Client::resetOptions()
{
m_screen->resetOptions();
}
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++;
if (index != options.end()) {
if (!*index) {
LOG((CLOG_NOTE "clipboard sharing disabled by server"));
}
m_enableClipboard = *index;
}
} else if (id == kOptionClipboardSharingSize) {
index++;
if (index != options.end()) {
m_maximumClipboardSize = *index;
}
}
}
if (m_enableClipboard && !m_maximumClipboardSize) {
m_enableClipboard = false;
LOG((CLOG_NOTE "clipboard sharing is disabled because the server "
"set the maximum clipboard size to 0"));
}
m_screen->setOptions(options);
}
String Client::getName() const
{
return m_name;
}
void Client::sendClipboard(ClipboardID id)
{
// note -- m_mutex must be locked on entry
assert(m_screen != NULL);
assert(m_server != NULL);
// get clipboard data. set the clipboard time to the last
// clipboard time before getting the data from the screen
// as the screen may detect an unchanged clipboard and
// avoid copying the data.
Clipboard clipboard;
if (clipboard.open(m_timeClipboard[id])) {
clipboard.close();
}
m_screen->getClipboard(id, &clipboard);
// check time
if (m_timeClipboard[id] == 0 || clipboard.getTime() != m_timeClipboard[id]) {
// marshall the data
String data = clipboard.marshall();
if (data.size() >= m_maximumClipboardSize * 1024) {
LOG(
(CLOG_NOTE "skipping clipboard transfer because the clipboard"
" contents exceeds the %i MB size limit set by the server",
m_maximumClipboardSize / 1024)
);
return;
}
// save new time
m_timeClipboard[id] = clipboard.getTime();
// save and send data if different or not yet sent
if (!m_sentClipboard[id] || data != m_dataClipboard[id]) {
m_sentClipboard[id] = true;
m_dataClipboard[id] = data;
m_server->onClipboardChanged(id, &clipboard);
}
}
}
void Client::sendEvent(Event::Type type, void *data)
{
m_events->addEvent(Event(type, getEventTarget(), data));
}
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);
m_events->addEvent(event);
}
void Client::sendFileChunk(const void *data)
{
FileChunk *chunk = static_cast<FileChunk *>(const_cast<void *>(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);
}
void Client::setupConnecting()
{
assert(m_stream != NULL);
if (m_args.m_enableCrypto) {
m_events->adoptHandler(
m_events->forIDataSocket().secureConnected(), m_stream->getEventTarget(),
new TMethodEventJob<Client>(this, &Client::handleConnected)
);
} else {
m_events->adoptHandler(
m_events->forIDataSocket().connected(), m_stream->getEventTarget(),
new TMethodEventJob<Client>(this, &Client::handleConnected)
);
}
m_events->adoptHandler(
m_events->forIDataSocket().connectionFailed(), m_stream->getEventTarget(),
new TMethodEventJob<Client>(this, &Client::handleConnectionFailed)
);
}
void Client::setupConnection()
{
assert(m_stream != NULL);
m_events->adoptHandler(
m_events->forISocket().disconnected(), m_stream->getEventTarget(),
new TMethodEventJob<Client>(this, &Client::handleDisconnected)
);
m_events->adoptHandler(
m_events->forIStream().inputReady(), m_stream->getEventTarget(),
new TMethodEventJob<Client>(this, &Client::handleHello)
);
m_events->adoptHandler(
m_events->forIStream().outputError(), m_stream->getEventTarget(),
new TMethodEventJob<Client>(this, &Client::handleOutputError)
);
m_events->adoptHandler(
m_events->forIStream().inputShutdown(), m_stream->getEventTarget(),
new TMethodEventJob<Client>(this, &Client::handleDisconnected)
);
m_events->adoptHandler(
m_events->forIStream().outputShutdown(), m_stream->getEventTarget(),
new TMethodEventJob<Client>(this, &Client::handleDisconnected)
);
m_events->adoptHandler(
m_events->forISocket().stopRetry(), m_stream->getEventTarget(),
new TMethodEventJob<Client>(this, &Client::handleStopRetry)
);
}
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<Client>(this, &Client::handleShapeChanged)
);
m_events->adoptHandler(
m_events->forClipboard().clipboardGrabbed(), getEventTarget(),
new TMethodEventJob<Client>(this, &Client::handleClipboardGrabbed)
);
}
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<Client>(this, &Client::handleConnectTimeout));
}
}
void Client::cleanup()
{
m_connectOnResume = false;
cleanupTimer();
cleanupScreen();
cleanupConnecting();
cleanupConnection();
}
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());
}
}
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());
cleanupStream();
}
}
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());
delete m_server;
m_server = NULL;
}
}
void Client::cleanupTimer()
{
if (m_timer != NULL) {
m_events->removeHandler(Event::kTimer, m_timer);
m_events->deleteTimer(m_timer);
m_timer = NULL;
}
}
void Client::cleanupStream()
{
delete m_stream;
m_stream = NULL;
}
void Client::handleConnected(const Event &, void *)
{
LOG((CLOG_DEBUG1 "connected, waiting for hello"));
cleanupConnecting();
setupConnection();
// reset clipboard state
for (ClipboardID id = 0; id < kClipboardEnd; ++id) {
m_ownClipboard[id] = false;
m_sentClipboard[id] = false;
m_timeClipboard[id] = 0;
}
}
void Client::handleConnectionFailed(const Event &event, void *)
{
IDataSocket::ConnectionFailedInfo *info = static_cast<IDataSocket::ConnectionFailedInfo *>(event.getData());
cleanupTimer();
cleanupConnecting();
cleanupStream();
LOG((CLOG_DEBUG1 "connection failed"));
sendConnectionFailedEvent(info->m_what.c_str());
delete info;
}
void Client::handleConnectTimeout(const Event &, void *)
{
cleanupTimer();
cleanupConnecting();
cleanupConnection();
cleanupStream();
LOG((CLOG_DEBUG1 "connection timed out"));
sendConnectionFailedEvent("Timed out");
}
void Client::handleOutputError(const Event &, void *)
{
cleanupTimer();
cleanupScreen();
cleanupConnection();
LOG((CLOG_WARN "error sending to server"));
sendEvent(m_events->forClient().disconnected(), NULL);
}
void Client::handleDisconnected(const Event &, void *)
{
cleanupTimer();
cleanupScreen();
cleanupConnection();
LOG((CLOG_DEBUG1 "disconnected"));
sendEvent(m_events->forClient().disconnected(), NULL);
}
void Client::handleShapeChanged(const Event &, void *)
{
LOG((CLOG_DEBUG "resolution changed"));
m_server->onInfoChanged();
}
void Client::handleClipboardGrabbed(const Event &event, void *)
{
if (!m_enableClipboard || (m_maximumClipboardSize == 0)) {
return;
}
const IScreen::ClipboardInfo *info = static_cast<const IScreen::ClipboardInfo *>(event.getData());
// grab ownership
m_server->onGrabClipboard(info->m_id);
// we now own the clipboard and it has not been sent to the server
m_ownClipboard[info->m_id] = true;
m_sentClipboard[info->m_id] = false;
m_timeClipboard[info->m_id] = 0;
// if we're not the active screen then send the clipboard now,
// otherwise we'll wait until we leave.
if (!m_active) {
sendClipboard(info->m_id);
}
}
void Client::handleHello(const Event &, void *)
{
m_pHelloBack->handleHello(m_stream, m_name);
// now connected but waiting to complete handshake
setupScreen();
cleanupTimer();
// make sure we process any remaining messages later. we won't
// 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()));
}
}
void Client::handleSuspend(const Event &, void *)
{
if (!m_suspended) {
LOG((CLOG_INFO "suspend"));
m_suspended = true;
bool wasConnected = isConnected();
disconnect(NULL);
m_connectOnResume = wasConnected;
}
}
void Client::handleResume(const Event &, void *)
{
if (m_suspended) {
LOG((CLOG_INFO "resume"));
m_suspended = false;
if (m_connectOnResume) {
m_connectOnResume = false;
connect();
}
}
}
void Client::handleFileChunkSending(const Event &event, void *)
{
sendFileChunk(event.getDataObject());
}
void Client::handleFileRecieveCompleted(const Event &event, void *)
{
onFileRecieveCompleted();
}
void Client::onFileRecieveCompleted()
{
if (isReceivedFileSizeValid()) {
auto method = new TMethodJob<Client>(this, &Client::writeToDropDirThread);
m_writeToDropDirThread.reset(new Thread(method));
}
}
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()));
NetworkAddress bindAddress(m_args.m_deskflowAddress);
bindAddress.resolve();
socket->bind(bindAddress);
}
} catch (XBase &e) {
LOG((CLOG_WARN "%s", e.what()));
LOG((CLOG_WARN "operating system will select network interface automatically"));
}
}
void Client::handleStopRetry(const Event &, void *)
{
m_args.m_restartable = false;
}
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);
}
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."));
return;
}
DragInformation::parseDragInfo(m_dragFileList, fileNum, data);
m_screen->startDraggingFiles(m_dragFileList);
}
bool Client::isReceivedFileSizeValid()
{
return m_expectedFileSize == m_receivedFileData.size();
}
void Client::sendFileToServer(const char *filename)
{
if (m_sendFileThread) {
StreamChunker::interruptFile();
}
auto data = static_cast<void *>(const_cast<char *>(filename));
auto method = new TMethodJob<Client>(this, &Client::sendFileThread, data);
m_sendFileThread.reset(new Thread(method));
}
void Client::sendFileThread(void *filename)
{
try {
char *name = static_cast<char *>(filename);
StreamChunker::sendFile(name, m_events, this);
} catch (std::runtime_error &error) {
LOG((CLOG_ERR "failed sending file chunks: %s", error.what()));
}
m_sendFileThread.reset(nullptr);
}
void Client::sendDragInfo(UInt32 fileCount, String &info, size_t size)
{
m_server->sendDragInfo(fileCount, info.c_str(), size);
}
| 21,287
|
C++
|
.cpp
| 690
| 27.326087
| 120
| 0.705072
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,658
|
ServerProxy.cpp
|
deskflow_deskflow/src/lib/client/ServerProxy.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "client/ServerProxy.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "base/TMethodEventJob.h"
#include "base/XBase.h"
#include "client/Client.h"
#include "deskflow/AppUtil.h"
#include "deskflow/Clipboard.h"
#include "deskflow/ClipboardChunk.h"
#include "deskflow/FileChunk.h"
#include "deskflow/ProtocolUtil.h"
#include "deskflow/StreamChunker.h"
#include "deskflow/option_types.h"
#include "deskflow/protocol_types.h"
#include "io/IStream.h"
#include <algorithm>
#include <cstring>
#include <memory>
//
// ServerProxy
//
ServerProxy::ServerProxy(Client *client, deskflow::IStream *stream, IEventQueue *events)
: m_client(client),
m_stream(stream),
m_seqNum(0),
m_compressMouse(false),
m_compressMouseRelative(false),
m_xMouse(0),
m_yMouse(0),
m_dxMouse(0),
m_dyMouse(0),
m_ignoreMouse(false),
m_keepAliveAlarm(0.0),
m_keepAliveAlarmTimer(NULL),
m_parser(&ServerProxy::parseHandshakeMessage),
m_events(events)
{
assert(m_client != NULL);
assert(m_stream != NULL);
// initialize modifier translation table
for (KeyModifierID id = 0; id < kKeyModifierIDLast; ++id)
m_modifierTranslationTable[id] = id;
// handle data on stream
m_events->adoptHandler(
m_events->forIStream().inputReady(), m_stream->getEventTarget(),
new TMethodEventJob<ServerProxy>(this, &ServerProxy::handleData)
);
m_events->adoptHandler(
m_events->forClipboard().clipboardSending(), this,
new TMethodEventJob<ServerProxy>(this, &ServerProxy::handleClipboardSendingEvent)
);
// send heartbeat
setKeepAliveRate(kKeepAliveRate);
}
ServerProxy::~ServerProxy()
{
setKeepAliveRate(-1.0);
m_events->removeHandler(m_events->forIStream().inputReady(), m_stream->getEventTarget());
}
void ServerProxy::resetKeepAliveAlarm()
{
if (m_keepAliveAlarmTimer != NULL) {
m_events->removeHandler(Event::kTimer, m_keepAliveAlarmTimer);
m_events->deleteTimer(m_keepAliveAlarmTimer);
m_keepAliveAlarmTimer = NULL;
}
if (m_keepAliveAlarm > 0.0) {
m_keepAliveAlarmTimer = m_events->newOneShotTimer(m_keepAliveAlarm, NULL);
m_events->adoptHandler(
Event::kTimer, m_keepAliveAlarmTimer, new TMethodEventJob<ServerProxy>(this, &ServerProxy::handleKeepAliveAlarm)
);
}
}
void ServerProxy::setKeepAliveRate(double rate)
{
m_keepAliveAlarm = rate * kKeepAlivesUntilDeath;
resetKeepAliveAlarm();
}
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);
while (n != 0) {
// verify we got an entire code
if (n != 4) {
LOG((CLOG_ERR "incomplete message from server: %d bytes", n));
m_client->disconnect("incomplete message from server");
return;
}
// parse message
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]));
// not possible to determine message boundaries
// read the whole stream to discard unkonwn data
while (m_stream->read(nullptr, 4))
;
break;
case kDisconnect:
return;
}
// next message
n = m_stream->read(code, 4);
}
flushCompressedMouse();
}
ServerProxy::EResult ServerProxy::parseHandshakeMessage(const UInt8 *code)
{
if (memcmp(code, kMsgQInfo, 4) == 0) {
queryInfo();
}
else if (memcmp(code, kMsgCInfoAck, 4) == 0) {
infoAcknowledgment();
}
else if (memcmp(code, kMsgDSetOptions, 4) == 0) {
setOptions();
// handshake is complete
m_parser = &ServerProxy::parseMessage;
checkMissedLanguages();
m_client->handshakeComplete();
}
else if (memcmp(code, kMsgCResetOptions, 4) == 0) {
resetOptions();
}
else if (memcmp(code, kMsgCKeepAlive, 4) == 0) {
// echo keep alives and reset alarm
ProtocolUtil::writef(m_stream, kMsgCKeepAlive);
resetKeepAliveAlarm();
}
else if (memcmp(code, kMsgCNoop, 4) == 0) {
// accept and discard no-op
}
else if (memcmp(code, kMsgCClose, 4) == 0) {
// server wants us to hangup
LOG((CLOG_DEBUG1 "recv close"));
m_client->disconnect(NULL);
return kDisconnect;
}
else if (memcmp(code, kMsgEIncompatible, 4) == 0) {
SInt32 major, minor;
ProtocolUtil::readf(m_stream, kMsgEIncompatible + 4, &major, &minor);
LOG((CLOG_ERR "server has incompatible version %d.%d", major, minor));
m_client->refuseConnection("server has incompatible version");
return kDisconnect;
}
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");
return kDisconnect;
}
else if (memcmp(code, kMsgEUnknown, 4) == 0) {
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;
}
else if (memcmp(code, kMsgEBad, 4) == 0) {
LOG((CLOG_ERR "server disconnected due to a protocol error"));
m_client->refuseConnection("server reported a protocol error");
return kDisconnect;
} else if (memcmp(code, kMsgDLanguageSynchronisation, 4) == 0) {
setServerLanguages();
} else {
return kUnknown;
}
return kOkay;
}
ServerProxy::EResult ServerProxy::parseMessage(const UInt8 *code)
{
if (memcmp(code, kMsgDMouseMove, 4) == 0) {
mouseMove();
}
else if (memcmp(code, kMsgDMouseRelMove, 4) == 0) {
mouseRelativeMove();
}
else if (memcmp(code, kMsgDMouseWheel, 4) == 0) {
mouseWheel();
}
else if (memcmp(code, kMsgDKeyDown, 4) == 0) {
UInt16 id = 0;
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));
keyDown(id, mask, button, "");
}
else if (memcmp(code, kMsgDKeyDownLang, 4) == 0) {
String lang;
UInt16 id = 0;
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())
);
keyDown(id, mask, button, lang);
}
else if (memcmp(code, kMsgDKeyUp, 4) == 0) {
keyUp();
}
else if (memcmp(code, kMsgDMouseDown, 4) == 0) {
mouseDown();
}
else if (memcmp(code, kMsgDMouseUp, 4) == 0) {
mouseUp();
}
else if (memcmp(code, kMsgDKeyRepeat, 4) == 0) {
keyRepeat();
}
else if (memcmp(code, kMsgCKeepAlive, 4) == 0) {
// echo keep alives and reset alarm
ProtocolUtil::writef(m_stream, kMsgCKeepAlive);
resetKeepAliveAlarm();
}
else if (memcmp(code, kMsgCNoop, 4) == 0) {
// accept and discard no-op
}
else if (memcmp(code, kMsgCEnter, 4) == 0) {
enter();
}
else if (memcmp(code, kMsgCLeave, 4) == 0) {
leave();
}
else if (memcmp(code, kMsgCClipboard, 4) == 0) {
grabClipboard();
}
else if (memcmp(code, kMsgCScreenSaver, 4) == 0) {
screensaver();
}
else if (memcmp(code, kMsgQInfo, 4) == 0) {
queryInfo();
}
else if (memcmp(code, kMsgCInfoAck, 4) == 0) {
infoAcknowledgment();
}
else if (memcmp(code, kMsgDClipboard, 4) == 0) {
setClipboard();
}
else if (memcmp(code, kMsgCResetOptions, 4) == 0) {
resetOptions();
}
else if (memcmp(code, kMsgDSetOptions, 4) == 0) {
setOptions();
}
else if (memcmp(code, kMsgDFileTransfer, 4) == 0) {
fileChunkReceived();
} else if (memcmp(code, kMsgDDragInfo, 4) == 0) {
dragInfoReceived();
} else if (memcmp(code, kMsgDSecureInputNotification, 4) == 0) {
secureInputNotification();
}
else if (memcmp(code, kMsgCClose, 4) == 0) {
// server wants us to hangup
LOG((CLOG_DEBUG1 "recv close"));
m_client->disconnect(NULL);
return kDisconnect;
} else if (memcmp(code, kMsgEBad, 4) == 0) {
LOG((CLOG_ERR "server disconnected due to a protocol error"));
m_client->disconnect("server reported a protocol error");
return kDisconnect;
} else {
return kUnknown;
}
// send a reply. this is intended to work around a delay when
// running a linux server and an OS X (any BSD?) client. the
// client waits to send an ACK (if the system control flag
// net.inet.tcp.delayed_ack is 1) in hopes of piggybacking it
// on a data packet. we provide that packet here. i don't
// know why a delayed ACK should cause the server to wait since
// TCP_NODELAY is enabled.
ProtocolUtil::writef(m_stream, kMsgCNoop);
return kOkay;
}
void ServerProxy::handleKeepAliveAlarm(const Event &, void *)
{
LOG((CLOG_NOTE "server is dead"));
m_client->disconnect("server is not responding");
}
void ServerProxy::onInfoChanged()
{
// ignore mouse motion until we receive acknowledgment of our info
// change message.
m_ignoreMouse = true;
// send info update
queryInfo();
}
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)
{
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()
{
if (m_compressMouse) {
m_compressMouse = false;
m_client->mouseMove(m_xMouse, m_yMouse);
}
if (m_compressMouseRelative) {
m_compressMouseRelative = false;
m_client->mouseRelativeMove(m_dxMouse, m_dyMouse);
m_dxMouse = 0;
m_dyMouse = 0;
}
}
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
{
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}
};
KeyModifierID id2 = kKeyModifierIDNull;
UInt32 side = 0;
switch (id) {
case kKeyShift_L:
id2 = kKeyModifierIDShift;
side = 0;
break;
case kKeyShift_R:
id2 = kKeyModifierIDShift;
side = 1;
break;
case kKeyControl_L:
id2 = kKeyModifierIDControl;
side = 0;
break;
case kKeyControl_R:
id2 = kKeyModifierIDControl;
side = 1;
break;
case kKeyAlt_L:
id2 = kKeyModifierIDAlt;
side = 0;
break;
case kKeyAlt_R:
id2 = kKeyModifierIDAlt;
side = 1;
break;
case kKeyAltGr:
id2 = kKeyModifierIDAltGr;
side = 1; // there is only one alt gr key on the right side
break;
case kKeyMeta_L:
id2 = kKeyModifierIDMeta;
side = 0;
break;
case kKeyMeta_R:
id2 = kKeyModifierIDMeta;
side = 1;
break;
case kKeySuper_L:
id2 = kKeyModifierIDSuper;
side = 0;
break;
case kKeySuper_R:
id2 = kKeyModifierIDSuper;
side = 1;
break;
}
if (id2 != kKeyModifierIDNull) {
return s_translationTable[m_modifierTranslationTable[id2]][side];
} else {
return id;
}
}
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);
if ((mask & KeyModifierShift) != 0) {
newMask |= s_masks[m_modifierTranslationTable[kKeyModifierIDShift]];
}
if ((mask & KeyModifierControl) != 0) {
newMask |= s_masks[m_modifierTranslationTable[kKeyModifierIDControl]];
}
if ((mask & KeyModifierAlt) != 0) {
newMask |= s_masks[m_modifierTranslationTable[kKeyModifierIDAlt]];
}
if ((mask & KeyModifierAltGr) != 0) {
newMask |= s_masks[m_modifierTranslationTable[kKeyModifierIDAltGr]];
}
if ((mask & KeyModifierMeta) != 0) {
newMask |= s_masks[m_modifierTranslationTable[kKeyModifierIDMeta]];
}
if ((mask & KeyModifierSuper) != 0) {
newMask |= s_masks[m_modifierTranslationTable[kKeyModifierIDSuper]];
}
return newMask;
}
void ServerProxy::enter()
{
// parse
SInt16 x, y;
UInt16 mask;
UInt32 seqNum;
ProtocolUtil::readf(m_stream, kMsgCEnter + 4, &x, &y, &seqNum, &mask);
LOG((CLOG_DEBUG1 "recv enter, %d,%d %d %04x", x, y, seqNum, mask));
// discard old compressed mouse motion, if any
m_compressMouse = false;
m_compressMouseRelative = false;
m_dxMouse = 0;
m_dyMouse = 0;
m_seqNum = seqNum;
m_serverLanguage = "";
m_isUserNotifiedAboutLanguageSyncError = false;
// forward
m_client->enter(x, y, seqNum, static_cast<KeyModifierMask>(mask), false);
}
void ServerProxy::leave()
{
// parse
LOG((CLOG_DEBUG1 "recv leave"));
// send last mouse motion
flushCompressedMouse();
// forward
m_client->leave();
}
void ServerProxy::setClipboard()
{
// parse
static String dataCached;
ClipboardID id;
UInt32 seq;
int r = ClipboardChunk::assemble(m_stream, dataCached, id, seq);
if (r == kStart) {
size_t size = ClipboardChunk::getExpectedSize();
LOG((CLOG_DEBUG "receiving clipboard %d size=%d", id, size));
} else if (r == kFinish) {
LOG((CLOG_DEBUG "received clipboard %d size=%d", id, dataCached.size()));
// forward
Clipboard clipboard;
clipboard.unmarshall(dataCached, 0);
m_client->setClipboard(id, &clipboard);
LOG((CLOG_INFO "clipboard was updated"));
}
}
void ServerProxy::grabClipboard()
{
// parse
ClipboardID id;
UInt32 seqNum;
ProtocolUtil::readf(m_stream, kMsgCClipboard + 4, &id, &seqNum);
LOG((CLOG_DEBUG "recv grab clipboard %d", id));
// validate
if (id >= kClipboardEnd) {
return;
}
// forward
m_client->grabClipboard(id);
}
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<KeyID>(id));
KeyModifierMask mask2 = translateModifierMask(static_cast<KeyModifierMask>(mask));
if (id2 != static_cast<KeyID>(id) || mask2 != static_cast<KeyModifierMask>(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()
{
// 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);
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())
);
// translate
KeyID id2 = translateKey(static_cast<KeyID>(id));
KeyModifierMask mask2 = translateModifierMask(static_cast<KeyModifierMask>(mask));
if (id2 != static_cast<KeyID>(id) || mask2 != static_cast<KeyModifierMask>(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()
{
// 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));
// translate
KeyID id2 = translateKey(static_cast<KeyID>(id));
KeyModifierMask mask2 = translateModifierMask(static_cast<KeyModifierMask>(mask));
if (id2 != static_cast<KeyID>(id) || mask2 != static_cast<KeyModifierMask>(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()
{
// get mouse up to date
flushCompressedMouse();
// parse
SInt8 id;
ProtocolUtil::readf(m_stream, kMsgDMouseDown + 4, &id);
LOG((CLOG_DEBUG1 "recv mouse down id=%d", id));
// forward
m_client->mouseDown(static_cast<ButtonID>(id));
}
void ServerProxy::mouseUp()
{
// get mouse up to date
flushCompressedMouse();
// parse
SInt8 id;
ProtocolUtil::readf(m_stream, kMsgDMouseUp + 4, &id);
LOG((CLOG_DEBUG1 "recv mouse up id=%d", id));
// forward
m_client->mouseUp(static_cast<ButtonID>(id));
}
void ServerProxy::mouseMove()
{
// parse
bool ignore;
SInt16 x, y;
ProtocolUtil::readf(m_stream, kMsgDMouseMove + 4, &x, &y);
// note if we should ignore the move
ignore = m_ignoreMouse;
// compress mouse motion events if more input follows
if (!ignore && !m_compressMouse && m_stream->isReady()) {
m_compressMouse = true;
}
// if compressing then ignore the motion but record it
if (m_compressMouse) {
m_compressMouseRelative = false;
ignore = true;
m_xMouse = x;
m_yMouse = y;
m_dxMouse = 0;
m_dyMouse = 0;
}
LOG((CLOG_DEBUG2 "recv mouse move %d,%d", x, y));
// forward
if (!ignore) {
m_client->mouseMove(x, y);
}
}
void ServerProxy::mouseRelativeMove()
{
// parse
bool ignore;
SInt16 dx, dy;
ProtocolUtil::readf(m_stream, kMsgDMouseRelMove + 4, &dx, &dy);
// note if we should ignore the move
ignore = m_ignoreMouse;
// compress mouse motion events if more input follows
if (!ignore && !m_compressMouseRelative && m_stream->isReady()) {
m_compressMouseRelative = true;
}
// if compressing then ignore the motion but record it
if (m_compressMouseRelative) {
ignore = true;
m_dxMouse += dx;
m_dyMouse += dy;
}
LOG((CLOG_DEBUG2 "recv mouse relative move %d,%d", dx, dy));
// forward
if (!ignore) {
m_client->mouseRelativeMove(dx, dy);
}
}
void ServerProxy::mouseWheel()
{
// get mouse up to date
flushCompressedMouse();
// parse
SInt16 xDelta, yDelta;
ProtocolUtil::readf(m_stream, kMsgDMouseWheel + 4, &xDelta, &yDelta);
LOG((CLOG_DEBUG2 "recv mouse wheel %+d,%+d", xDelta, yDelta));
// forward
m_client->mouseWheel(xDelta, yDelta);
}
void ServerProxy::screensaver()
{
// parse
SInt8 on;
ProtocolUtil::readf(m_stream, kMsgCScreenSaver + 4, &on);
LOG((CLOG_DEBUG1 "recv screen saver on=%d", on));
// forward
m_client->screensaver(on != 0);
}
void ServerProxy::resetOptions()
{
// parse
LOG((CLOG_DEBUG1 "recv reset options"));
// forward
m_client->resetOptions();
// reset keep alive
setKeepAliveRate(kKeepAliveRate);
// reset modifier translation table
for (KeyModifierID id = 0; id < kKeyModifierIDLast; ++id) {
m_modifierTranslationTable[id] = id;
}
}
void ServerProxy::setOptions()
{
// parse
OptionsList options;
ProtocolUtil::readf(m_stream, kMsgDSetOptions + 4, &options);
LOG((CLOG_DEBUG1 "recv set options size=%d", options.size()));
// forward
m_client->setOptions(options);
// update modifier table
for (UInt32 i = 0, n = (UInt32)options.size(); i < n; i += 2) {
KeyModifierID id = kKeyModifierIDNull;
if (options[i] == kOptionModifierMapForShift) {
id = kKeyModifierIDShift;
} else if (options[i] == kOptionModifierMapForControl) {
id = kKeyModifierIDControl;
} else if (options[i] == kOptionModifierMapForAlt) {
id = kKeyModifierIDAlt;
} else if (options[i] == kOptionModifierMapForAltGr) {
id = kKeyModifierIDAltGr;
} else if (options[i] == kOptionModifierMapForMeta) {
id = kKeyModifierIDMeta;
} else if (options[i] == kOptionModifierMapForSuper) {
id = kKeyModifierIDSuper;
} else if (options[i] == kOptionHeartbeat) {
// update keep alive
setKeepAliveRate(1.0e-3 * static_cast<double>(options[i + 1]));
}
if (id != kKeyModifierIDNull) {
m_modifierTranslationTable[id] = static_cast<KeyModifierID>(options[i + 1]);
LOG((CLOG_DEBUG1 "modifier %d mapped to %d", id, m_modifierTranslationTable[id]));
}
}
}
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()
{
LOG((CLOG_DEBUG1 "recv info acknowledgment"));
m_ignoreMouse = false;
}
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));
} else if (result == kStart) {
if (m_client->getDragFileList().size() > 0) {
String filename = m_client->getDragFileList().at(0).getFilename();
LOG((CLOG_DEBUG "start receiving %s", filename.c_str()));
}
}
}
void ServerProxy::dragInfoReceived()
{
// parse
UInt32 fileNum = 0;
String content;
ProtocolUtil::readf(m_stream, kMsgDDragInfo + 4, &fileNum, &content);
m_client->dragInfoReceived(fileNum, content);
}
void ServerProxy::handleClipboardSendingEvent(const Event &event, void *)
{
ClipboardChunk::send(m_stream, event.getDataObject());
}
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)
{
String data(info, size);
ProtocolUtil::writef(m_stream, kMsgDDragInfo, fileCount, &data);
}
void ServerProxy::secureInputNotification()
{
String app;
ProtocolUtil::readf(m_stream, kMsgDSecureInputNotification + 4, &app);
// display this notification on the client
if (app != "unknown") {
AppUtil::instance().showNotification(
"The keyboard may stop working.", "'Secure input' enabled by " + app +
" on the server. "
"To fix the keyboard, " +
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."
);
}
}
void ServerProxy::setServerLanguages()
{
String serverLanguages;
ProtocolUtil::readf(m_stream, kMsgDLanguageSynchronisation + 4, &serverLanguages);
m_languageManager.setRemoteLanguages(serverLanguages);
}
void ServerProxy::setActiveServerLanguage(const String &language)
{
if (!language.empty() && std::strlen(language.c_str()) > 0) {
if (m_serverLanguage != language) {
m_isUserNotifiedAboutLanguageSyncError = false;
m_serverLanguage = language;
}
if (!m_languageManager.isLanguageInstalled(m_serverLanguage)) {
if (!m_isUserNotifiedAboutLanguageSyncError) {
LOG((CLOG_WARN "current server language is not installed on client"));
m_isUserNotifiedAboutLanguageSyncError = true;
}
} else {
m_isUserNotifiedAboutLanguageSyncError = false;
}
} else {
LOG((CLOG_DEBUG1 "active server language is empty"));
}
}
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())
);
}
}
| 25,083
|
C++
|
.cpp
| 772
| 28.404145
| 120
| 0.680725
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,659
|
XMT.cpp
|
deskflow_deskflow/src/lib/mt/XMT.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "XMT.h"
//
// XMTThreadUnavailable
//
String XMTThreadUnavailable::getWhat() const throw()
{
return format("XMTThreadUnavailable", "cannot create thread");
}
| 902
|
C++
|
.cpp
| 25
| 34.24
| 72
| 0.762014
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,660
|
Lock.cpp
|
deskflow_deskflow/src/lib/mt/Lock.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mt/Lock.h"
#include "mt/CondVar.h"
#include "mt/Mutex.h"
//
// 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()
{
m_mutex->unlock();
}
| 1,009
|
C++
|
.cpp
| 35
| 27.057143
| 72
| 0.73065
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,661
|
Mutex.cpp
|
deskflow_deskflow/src/lib/mt/Mutex.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mt/Mutex.h"
#include "arch/Arch.h"
//
// Mutex
//
Mutex::Mutex()
{
m_mutex = ARCH->newMutex();
}
Mutex::Mutex(const Mutex &)
{
m_mutex = ARCH->newMutex();
}
Mutex::~Mutex()
{
ARCH->closeMutex(m_mutex);
}
Mutex &Mutex::operator=(const Mutex &)
{
return *this;
}
void Mutex::lock() const
{
ARCH->lockMutex(m_mutex);
}
void Mutex::unlock() const
{
ARCH->unlockMutex(m_mutex);
}
| 1,136
|
C++
|
.cpp
| 46
| 22.891304
| 72
| 0.730805
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,662
|
CondVar.cpp
|
deskflow_deskflow/src/lib/mt/CondVar.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mt/CondVar.h"
#include "arch/Arch.h"
#include "base/Stopwatch.h"
//
// CondVarBase
//
CondVarBase::CondVarBase(Mutex *mutex) : m_mutex(mutex)
{
assert(m_mutex != NULL);
m_cond = ARCH->newCondVar();
}
CondVarBase::~CondVarBase()
{
ARCH->closeCondVar(m_cond);
}
void CondVarBase::lock() const
{
m_mutex->lock();
}
void CondVarBase::unlock() const
{
m_mutex->unlock();
}
void CondVarBase::signal()
{
ARCH->signalCondVar(m_cond);
}
void CondVarBase::broadcast()
{
ARCH->broadcastCondVar(m_cond);
}
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
do {
// Always call wait at least once, even if remain is 0, to give
// other thread a chance to grab the mutex to avoid deadlocks on
// busy waiting.
if (remain < 0.0)
remain = 0.0;
if (wait(remain))
return true;
remain = timeout - timer.getTime();
} while (remain >= 0.0);
return false;
}
bool CondVarBase::wait(double timeout) const
{
return ARCH->waitCondVar(m_cond, m_mutex->m_mutex, timeout);
}
Mutex *CondVarBase::getMutex() const
{
return m_mutex;
}
| 2,021
|
C++
|
.cpp
| 73
| 25.410959
| 75
| 0.727414
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| true
| false
| false
| true
| false
| false
|
13,663
|
Thread.cpp
|
deskflow_deskflow/src/lib/mt/Thread.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mt/Thread.h"
#include "arch/Arch.h"
#include "base/IJob.h"
#include "base/Log.h"
#include "mt/XMT.h"
#include "mt/XThread.h"
#include <exception>
//
// Thread
//
Thread::Thread(IJob *job)
{
m_thread = ARCH->newThread(&Thread::threadFunc, job);
if (m_thread == NULL) {
// couldn't create thread
delete job;
throw XMTThreadUnavailable();
}
}
Thread::Thread(const Thread &thread)
{
m_thread = ARCH->copyThread(thread.m_thread);
}
Thread::Thread(ArchThread adoptedThread)
{
m_thread = adoptedThread;
}
Thread::~Thread()
{
ARCH->closeThread(m_thread);
}
Thread &Thread::operator=(const Thread &thread)
{
// copy given thread and release ours
ArchThread copy = ARCH->copyThread(thread.m_thread);
ARCH->closeThread(m_thread);
// cut over
m_thread = copy;
return *this;
}
void Thread::exit(void *result)
{
throw XThreadExit(result);
}
void Thread::cancel()
{
ARCH->cancelThread(m_thread);
}
void Thread::setPriority(int n)
{
ARCH->setPriorityOfThread(m_thread, n);
}
void Thread::unblockPollSocket()
{
ARCH->unblockPollSocket(m_thread);
}
Thread Thread::getCurrentThread()
{
return Thread(ARCH->newCurrentThread());
}
void Thread::testCancel()
{
ARCH->testCancelThread();
}
bool Thread::wait(double timeout) const
{
return ARCH->wait(m_thread, timeout);
}
void *Thread::getResult() const
{
if (wait())
return ARCH->getResultOfThread(m_thread);
else
return NULL;
}
IArchMultithread::ThreadID Thread::getID() const
{
return ARCH->getIDOfThread(m_thread);
}
bool Thread::operator==(const Thread &thread) const
{
return ARCH->isSameThread(m_thread, thread.m_thread);
}
bool Thread::operator!=(const Thread &thread) const
{
return !ARCH->isSameThread(m_thread, thread.m_thread);
}
void *Thread::threadFunc(void *vjob)
{
// get this thread's id for logging
IArchMultithread::ThreadID id;
{
ArchThread thread = ARCH->newCurrentThread();
id = ARCH->getIDOfThread(thread);
ARCH->closeThread(thread);
}
// get job
IJob *job = static_cast<IJob *>(vjob);
// run job
void *result = NULL;
try {
// go
LOG((CLOG_DEBUG1 "thread 0x%08x entry", id));
job->run();
LOG((CLOG_DEBUG1 "thread 0x%08x exit", id));
} catch (XThreadCancel &) {
// client called cancel()
LOG((CLOG_DEBUG1 "caught cancel on thread 0x%08x", id));
delete job;
throw;
} catch (XThreadExit &e) {
// client called exit()
result = e.m_result;
LOG((CLOG_DEBUG1 "caught exit on thread 0x%08x, result %p", id, result));
} catch (XBase &e) {
LOG((CLOG_ERR "exception on thread 0x%08x: %s", id, e.what()));
delete job;
throw;
} catch (std::exception &e) {
LOG((CLOG_ERR "standard exception on thread 0x%08x: %s", id, e.what()));
delete job;
throw;
} catch (...) {
LOG((CLOG_ERR "non-exception throw on thread 0x%08x: <unknown>", id));
delete job;
throw;
}
// done with job
delete job;
// return exit result
return result;
}
| 3,724
|
C++
|
.cpp
| 149
| 22.38255
| 77
| 0.70217
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,664
|
NetworkAddress.cpp
|
deskflow_deskflow/src/lib/net/NetworkAddress.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "net/NetworkAddress.h"
#include "arch/Arch.h"
#include "arch/XArch.h"
#include "net/XSocket.h"
#include <algorithm>
#include <cstdlib>
//
// NetworkAddress
//
// name re-resolution adapted from a patch by Brent Priddy.
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)
{
*this = addr;
}
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);
if (colomCount == 1) {
// ipv4 with port part
auto hostIt = m_hostname.find(':');
try {
m_port = std::stoi(m_hostname.substr(hostIt + 1));
} catch (...) {
throw XSocketAddress(XSocketAddress::kBadPort, m_hostname, m_port);
}
auto endHostnameIt = static_cast<int>(hostIt);
m_hostname = m_hostname.substr(0, endHostnameIt > 0 ? endHostnameIt : 0);
} else if (colomCount > 1) {
// ipv6 part
if (m_hostname[0] == '[') {
// ipv6 with port part
String portDelimeter = "]:";
auto hostIt = m_hostname.find(portDelimeter);
// bad syntax of ipv6 with port
if (hostIt == String::npos) {
throw XSocketAddress(XSocketAddress::kUnknown, m_hostname, m_port);
}
auto portSuffix = m_hostname.substr(hostIt + portDelimeter.size());
// port is implied but omitted
if (portSuffix.empty()) {
throw XSocketAddress(XSocketAddress::kBadPort, m_hostname, m_port);
}
try {
m_port = std::stoi(portSuffix);
} catch (...) {
// port is not a number
throw XSocketAddress(XSocketAddress::kBadPort, m_hostname, m_port);
}
auto endHostnameIt = static_cast<int>(hostIt) - 1;
m_hostname = m_hostname.substr(1, endHostnameIt > 0 ? endHostnameIt : 0);
}
// ensure that ipv6 link-local adress ended with scope id
if (m_hostname.rfind("fe80:", 0) == 0 && m_hostname.find('%') == String::npos) {
throw XSocketAddress(XSocketAddress::kUnknown, m_hostname, m_port);
}
}
// check port number
checkPort();
}
NetworkAddress::~NetworkAddress()
{
if (m_address != nullptr) {
ARCH->closeAddr(m_address);
m_address = nullptr;
}
}
NetworkAddress &NetworkAddress::operator=(const NetworkAddress &addr)
{
if (m_address != nullptr) {
ARCH->closeAddr(m_address);
m_address = nullptr;
}
ArchNetAddress newAddr = nullptr;
if (addr.m_address != nullptr) {
newAddr = ARCH->copyAddr(addr.m_address);
}
m_address = newAddr;
m_hostname = addr.m_hostname;
m_port = addr.m_port;
return *this;
}
size_t NetworkAddress::resolve(size_t index)
{
size_t resolvedAddressesCount = 0;
// discard previous address
if (m_address != nullptr) {
ARCH->closeAddr(m_address);
m_address = nullptr;
}
try {
// if hostname is empty then use wildcard address otherwise look
// up the name.
if (m_hostname.empty()) {
m_address = ARCH->newAnyAddr(IArchNetwork::kINET);
resolvedAddressesCount = 1;
} else {
// Logic for temporary filtring only ipv4 addresses
std::vector<ArchNetAddress> ipv4OnlyAddresses;
{
auto addresses = ARCH->nameToAddr(m_hostname);
for (auto address : addresses) {
if (ARCH->getAddrFamily(address) == IArchNetwork::kINET) {
ipv4OnlyAddresses.emplace_back(address);
} else {
ARCH->closeAddr(address);
}
}
}
resolvedAddressesCount = ipv4OnlyAddresses.size();
assert(resolvedAddressesCount > 0);
if (index < resolvedAddressesCount - 1) {
m_address = ipv4OnlyAddresses[index];
} else {
m_address = ipv4OnlyAddresses[resolvedAddressesCount - 1];
}
for (auto address : ipv4OnlyAddresses) {
if (m_address != address) {
ARCH->closeAddr(address);
}
}
}
} catch (XArchNetworkNameUnknown &) {
throw XSocketAddress(XSocketAddress::kNotFound, m_hostname, m_port);
} catch (XArchNetworkNameNoAddress &) {
throw XSocketAddress(XSocketAddress::kNoAddress, m_hostname, m_port);
} catch (XArchNetworkNameUnsupported &) {
throw XSocketAddress(XSocketAddress::kUnsupported, m_hostname, m_port);
} catch (XArchNetworkName &) {
throw XSocketAddress(XSocketAddress::kUnknown, m_hostname, m_port);
}
// set port in address
ARCH->setAddrPort(m_address, m_port);
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 !operator==(addr);
}
bool NetworkAddress::isValid() const
{
return (m_address != nullptr);
}
const ArchNetAddress &NetworkAddress::getAddress() const
{
return m_address;
}
int NetworkAddress::getPort() const
{
return m_port;
}
String NetworkAddress::getHostname() const
{
return m_hostname;
}
void NetworkAddress::checkPort()
{
// check port number
if (m_port < 0 || m_port > 65535) {
throw XSocketAddress(XSocketAddress::kBadPort, m_hostname, m_port);
}
}
| 6,232
|
C++
|
.cpp
| 190
| 28.621053
| 109
| 0.686023
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,665
|
TCPSocketFactory.cpp
|
deskflow_deskflow/src/lib/net/TCPSocketFactory.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "net/TCPSocketFactory.h"
#include "arch/Arch.h"
#include "base/Log.h"
#include "net/SecureListenSocket.h"
#include "net/SecureSocket.h"
#include "net/TCPListenSocket.h"
#include "net/TCPSocket.h"
//
// TCPSocketFactory
//
TCPSocketFactory::TCPSocketFactory(IEventQueue *events, SocketMultiplexer *socketMultiplexer)
: m_events(events),
m_socketMultiplexer(socketMultiplexer)
{
// do nothing
}
TCPSocketFactory::~TCPSocketFactory()
{
// do nothing
}
IDataSocket *TCPSocketFactory::create(bool secure, IArchNetwork::EAddressFamily family) const
{
if (secure) {
SecureSocket *secureSocket = new SecureSocket(m_events, m_socketMultiplexer, family);
secureSocket->initSsl(false);
return secureSocket;
} else {
return new TCPSocket(m_events, m_socketMultiplexer, family);
}
}
IListenSocket *TCPSocketFactory::createListen(bool secure, IArchNetwork::EAddressFamily family) const
{
IListenSocket *socket = NULL;
if (secure) {
socket = new SecureListenSocket(m_events, m_socketMultiplexer, family);
} else {
socket = new TCPListenSocket(m_events, m_socketMultiplexer, family);
}
return socket;
}
| 1,887
|
C++
|
.cpp
| 57
| 30.754386
| 101
| 0.765771
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,666
|
TCPListenSocket.cpp
|
deskflow_deskflow/src/lib/net/TCPListenSocket.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "net/TCPListenSocket.h"
#include "arch/Arch.h"
#include "arch/XArch.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "io/XIO.h"
#include "mt/Lock.h"
#include "mt/Mutex.h"
#include "net/NetworkAddress.h"
#include "net/SocketMultiplexer.h"
#include "net/TCPSocket.h"
#include "net/TSocketMultiplexerMethodJob.h"
#include "net/XSocket.h"
//
// TCPListenSocket
//
TCPListenSocket::TCPListenSocket(
IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family
)
: m_events(events),
m_socketMultiplexer(socketMultiplexer)
{
m_mutex = new Mutex;
try {
m_socket = ARCH->newSocket(family, IArchNetwork::kSTREAM);
} catch (XArchNetwork &e) {
throw XSocketCreate(e.what());
}
}
TCPListenSocket::~TCPListenSocket()
{
try {
if (m_socket != NULL) {
m_socketMultiplexer->removeSocket(this);
ARCH->closeSocket(m_socket);
}
} catch (...) {
// ignore
LOG((CLOG_WARN "error while closing TCP socket"));
}
delete m_mutex;
}
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<TCPListenSocket>(
this, &TCPListenSocket::serviceListening, m_socket, true, false
)
);
} catch (XArchNetworkAddressInUse &e) {
throw XSocketAddressInUse(e.what());
} catch (XArchNetwork &e) {
throw XSocketBind(e.what());
}
}
void TCPListenSocket::close()
{
Lock lock(m_mutex);
if (m_socket == NULL) {
throw XIOClosed();
}
try {
m_socketMultiplexer->removeSocket(this);
ARCH->closeSocket(m_socket);
m_socket = NULL;
} catch (XArchNetwork &e) {
throw XSocketIOClose(e.what());
}
}
void *TCPListenSocket::getEventTarget() const
{
return const_cast<void *>(static_cast<const void *>(this));
}
IDataSocket *TCPListenSocket::accept()
{
IDataSocket *socket = NULL;
try {
socket = new TCPSocket(m_events, m_socketMultiplexer, ARCH->acceptSocket(m_socket, NULL));
if (socket != NULL) {
setListeningJob();
}
return socket;
} catch (XArchNetwork &) {
if (socket != NULL) {
delete socket;
setListeningJob();
}
return NULL;
} catch (std::exception &ex) {
if (socket != NULL) {
delete socket;
setListeningJob();
}
throw ex;
}
}
void TCPListenSocket::setListeningJob()
{
m_socketMultiplexer->addSocket(
this,
new TSocketMultiplexerMethodJob<TCPListenSocket>(this, &TCPListenSocket::serviceListening, m_socket, true, false)
);
}
ISocketMultiplexerJob *TCPListenSocket::serviceListening(ISocketMultiplexerJob *job, bool read, bool, bool error)
{
if (error) {
close();
return NULL;
}
if (read) {
m_events->addEvent(Event(m_events->forIListenSocket().connecting(), this));
// stop polling on this socket until the client accepts
return NULL;
}
return job;
}
| 3,824
|
C++
|
.cpp
| 138
| 24.297101
| 119
| 0.705578
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,667
|
SecureListenSocket.cpp
|
deskflow_deskflow/src/lib/net/SecureListenSocket.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2015-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SecureListenSocket.h"
#include "SecureSocket.h"
#include "arch/XArch.h"
#include "common/constants.h"
#include "deskflow/ArgParser.h"
#include "deskflow/ArgsBase.h"
#include "net/NetworkAddress.h"
#include "net/SocketMultiplexer.h"
#include "net/TSocketMultiplexerMethodJob.h"
// TODO: Reduce duplication of these strings between here and SecureSocket.cpp
static const char s_certificateDir[] = {"tls"};
static const char s_certificateFileExt[] = {"pem"};
//
// SecureListenSocket
//
SecureListenSocket::SecureListenSocket(
IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family
)
: TCPListenSocket(events, socketMultiplexer, family)
{
}
IDataSocket *SecureListenSocket::accept()
{
SecureSocket *socket = NULL;
try {
socket = new SecureSocket(m_events, m_socketMultiplexer, ARCH->acceptSocket(m_socket, NULL));
socket->initSsl(true);
if (socket != NULL) {
setListeningJob();
}
// default location of the TLS cert file in users dir
String certificateFilename = deskflow::string::sprintf(
"%s/%s/%s.%s", ARCH->getProfileDirectory().c_str(), s_certificateDir, kAppId, s_certificateFileExt
);
// if the tls cert option is set use that for the certificate file
if (!ArgParser::argsBase().m_tlsCertFile.empty()) {
certificateFilename = ArgParser::argsBase().m_tlsCertFile;
}
bool loaded = socket->loadCertificates(certificateFilename);
if (!loaded) {
delete socket;
return NULL;
}
socket->secureAccept();
return dynamic_cast<IDataSocket *>(socket);
} catch (XArchNetwork &) {
if (socket != NULL) {
delete socket;
setListeningJob();
}
return NULL;
} catch (std::exception &ex) {
if (socket != NULL) {
delete socket;
setListeningJob();
}
throw ex;
}
}
| 2,555
|
C++
|
.cpp
| 75
| 30.6
| 106
| 0.724473
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,668
|
IDataSocket.cpp
|
deskflow_deskflow/src/lib/net/IDataSocket.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "net/IDataSocket.h"
#include "base/EventQueue.h"
//
// IDataSocket
//
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
{
// this is here to work around a VC++6 bug. see the header file.
assert(0 && "bad call");
return NULL;
}
| 1,094
|
C++
|
.cpp
| 33
| 31.242424
| 72
| 0.736991
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| true
| true
| true
| false
| false
| true
| false
| false
|
13,669
|
XSocket.cpp
|
deskflow_deskflow/src/lib/net/XSocket.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "net/XSocket.h"
#include "base/String.h"
//
// XSocketAddress
//
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()
{
return m_error;
}
String XSocketAddress::getHostname() const throw()
{
return m_hostname;
}
int XSocketAddress::getPort() const throw()
{
return m_port;
}
String XSocketAddress::getWhat() const throw()
{
static const char *s_errorID[] = {
"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}",
"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()
);
}
//
// XSocketIOClose
//
String XSocketIOClose::getWhat() const throw()
{
return format("XSocketIOClose", "close: %{1}", what());
}
//
// XSocketBind
//
String XSocketBind::getWhat() const throw()
{
return format("XSocketBind", "cannot bind address: %{1}", what());
}
//
// XSocketConnect
//
String XSocketConnect::getWhat() const throw()
{
return format("XSocketConnect", "cannot connect socket: %{1}", what());
}
//
// XSocketCreate
//
String XSocketCreate::getWhat() const throw()
{
return format("XSocketCreate", "cannot create socket: %{1}", what());
}
| 2,565
|
C++
|
.cpp
| 83
| 26.566265
| 114
| 0.665586
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| true
| false
| false
| false
| true
| false
| false
|
13,670
|
TCPSocket.cpp
|
deskflow_deskflow/src/lib/net/TCPSocket.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "net/TCPSocket.h"
#include "arch/Arch.h"
#include "arch/XArch.h"
#include "base/IEventJob.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "mt/Lock.h"
#include "net/NetworkAddress.h"
#include "net/SocketMultiplexer.h"
#include "net/TSocketMultiplexerMethodJob.h"
#include "net/XSocket.h"
#include <cstdlib>
#include <cstring>
#include <memory>
//
// TCPSocket
//
TCPSocket::TCPSocket(IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family)
: IDataSocket(events),
m_events(events),
m_mutex(),
m_flushed(&m_mutex, true),
m_socketMultiplexer(socketMultiplexer)
{
try {
m_socket = ARCH->newSocket(family, IArchNetwork::kSTREAM);
} catch (const XArchNetwork &e) {
throw XSocketCreate(e.what());
}
LOG((CLOG_DEBUG "opening new socket: %08X", m_socket));
init();
}
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)
{
assert(m_socket != nullptr);
LOG((CLOG_DEBUG "opening new socket: %08X", m_socket));
// socket starts in connected state
init();
onConnected();
setJob(newJob());
}
TCPSocket::~TCPSocket()
{
try {
// warning virtual function in destructor is very danger practice
close();
} catch (...) {
LOG((CLOG_DEBUG "error while TCP socket destruction"));
}
}
void TCPSocket::bind(const NetworkAddress &addr)
{
try {
ARCH->bindSocket(m_socket, addr.getAddress());
} catch (const XArchNetworkAddressInUse &e) {
throw XSocketAddressInUse(e.what());
} catch (const XArchNetwork &e) {
throw XSocketBind(e.what());
}
}
void TCPSocket::close()
{
LOG((CLOG_DEBUG "closing socket: %08X", m_socket));
// remove ourself from the multiplexer
setJob(nullptr);
Lock lock(&m_mutex);
// clear buffers and enter disconnected state
if (m_connected) {
sendEvent(m_events->forISocket().disconnected());
}
onDisconnected();
// close the socket
if (m_socket != nullptr) {
ArchSocket socket = m_socket;
m_socket = nullptr;
try {
ARCH->closeSocket(socket);
} catch (const XArchNetwork &e) {
// ignore, there's not much we can do
LOG((CLOG_WARN "error closing socket: %s", e.what()));
}
}
}
void *TCPSocket::getEventTarget() const
{
return const_cast<void *>(static_cast<const void *>(this));
}
UInt32 TCPSocket::read(void *buffer, UInt32 n)
{
// copy data directly from our input buffer
Lock lock(&m_mutex);
UInt32 size = m_inputBuffer.getSize();
if (n > size) {
n = size;
}
if (buffer != nullptr && n != 0) {
memcpy(buffer, m_inputBuffer.peek(n), n);
}
m_inputBuffer.pop(n);
// if no more data and we cannot read or write then send disconnected
if (n > 0 && m_inputBuffer.getSize() == 0 && !m_readable && !m_writable) {
sendEvent(m_events->forISocket().disconnected());
m_connected = false;
}
return n;
}
void TCPSocket::write(const void *buffer, UInt32 n)
{
bool wasEmpty;
{
Lock lock(&m_mutex);
// must not have shutdown output
if (!m_writable) {
sendEvent(m_events->forIStream().outputError());
return;
}
// ignore empty writes
if (n == 0) {
return;
}
// copy data to the output buffer
wasEmpty = (m_outputBuffer.getSize() == 0);
m_outputBuffer.write(buffer, n);
// there's data to write
m_flushed = false;
}
// make sure we're waiting to write
if (wasEmpty) {
setJob(newJob());
}
}
void TCPSocket::flush()
{
Lock lock(&m_mutex);
while (m_flushed == false) {
m_flushed.wait();
}
}
void TCPSocket::shutdownInput()
{
bool useNewJob = false;
{
Lock lock(&m_mutex);
// shutdown socket for reading
try {
ARCH->closeSocketForRead(m_socket);
} catch (const XArchNetwork &e) {
// ignore, there's not much we can do
LOG((CLOG_WARN "error closing socket: %s", e.what()));
}
// shutdown buffer for reading
if (m_readable) {
sendEvent(m_events->forIStream().inputShutdown());
onInputShutdown();
useNewJob = true;
}
}
if (useNewJob) {
setJob(newJob());
}
}
void TCPSocket::shutdownOutput()
{
bool useNewJob = false;
{
Lock lock(&m_mutex);
// shutdown socket for writing
try {
ARCH->closeSocketForWrite(m_socket);
} catch (const XArchNetwork &e) {
// ignore, there's not much we can do
LOG((CLOG_WARN "error closing socket: %s", e.what()));
}
// shutdown buffer for writing
if (m_writable) {
sendEvent(m_events->forIStream().outputShutdown());
onOutputShutdown();
useNewJob = true;
}
}
if (useNewJob) {
setJob(newJob());
}
}
bool TCPSocket::isReady() const
{
Lock lock(&m_mutex);
return (m_inputBuffer.getSize() > 0);
}
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
{
Lock lock(&m_mutex);
return m_inputBuffer.getSize();
}
void TCPSocket::connect(const NetworkAddress &addr)
{
{
Lock lock(&m_mutex);
// fail on attempts to reconnect
if (m_socket == nullptr || m_connected) {
sendConnectionFailedEvent("busy");
return;
}
try {
if (ARCH->connectSocket(m_socket, addr.getAddress())) {
sendEvent(m_events->forIDataSocket().connected());
onConnected();
} else {
// connection is in progress
m_writable = true;
}
} catch (const XArchNetwork &e) {
throw XSocketConnect(e.what());
}
}
setJob(newJob());
}
void TCPSocket::init()
{
// default state
m_connected = false;
m_readable = false;
m_writable = false;
try {
// turn off Nagle algorithm. we send lots of very short messages
// that should be sent without (much) delay. for example, the
// mouse motion messages are much less useful if they're delayed.
ARCH->setNoDelayOnSocket(m_socket, true);
} catch (const XArchNetwork &e) {
try {
ARCH->closeSocket(m_socket);
m_socket = nullptr;
} catch (const XArchNetwork &e) {
// ignore, there's not much we can do
LOG((CLOG_WARN "error closing socket: %s", e.what()));
}
throw XSocketCreate(e.what());
}
}
TCPSocket::EJobResult TCPSocket::doRead()
{
UInt8 buffer[4096];
memset(buffer, 0, sizeof(buffer));
size_t bytesRead = 0;
bytesRead = ARCH->readSocket(m_socket, buffer, sizeof(buffer));
if (bytesRead > 0) {
bool wasEmpty = (m_inputBuffer.getSize() == 0);
// slurp up as much as possible
do {
m_inputBuffer.write(buffer, static_cast<UInt32>(bytesRead));
bytesRead = ARCH->readSocket(m_socket, buffer, sizeof(buffer));
} while (bytesRead > 0);
// send input ready if input buffer was empty
if (wasEmpty) {
sendEvent(m_events->forIStream().inputReady());
}
} else {
// remote write end of stream hungup. our input side
// has therefore shutdown but don't flush our buffer
// since there's still data to be read.
sendEvent(m_events->forIStream().inputShutdown());
if (!m_writable && m_inputBuffer.getSize() == 0) {
sendEvent(m_events->forISocket().disconnected());
m_connected = false;
}
m_readable = false;
return kNew;
}
return kRetry;
}
TCPSocket::EJobResult TCPSocket::doWrite()
{
// write data
UInt32 bufferSize = 0;
int bytesWrote = 0;
bufferSize = m_outputBuffer.getSize();
const void *buffer = m_outputBuffer.peek(bufferSize);
bytesWrote = (UInt32)ARCH->writeSocket(m_socket, buffer, bufferSize);
if (bytesWrote > 0) {
discardWrittenData(bytesWrote);
return kNew;
}
return kRetry;
}
void TCPSocket::setJob(ISocketMultiplexerJob *job)
{
// multiplexer will delete the old job
if (job == nullptr) {
m_socketMultiplexer->removeSocket(this);
} else {
m_socketMultiplexer->addSocket(this, job);
}
}
ISocketMultiplexerJob *TCPSocket::newJob()
{
// note -- must have m_mutex locked on entry
if (m_socket == nullptr) {
return nullptr;
} else if (!m_connected) {
assert(!m_readable);
if (!(m_readable || m_writable)) {
return nullptr;
}
return new TSocketMultiplexerMethodJob<TCPSocket>(
this, &TCPSocket::serviceConnecting, m_socket, m_readable, m_writable
);
} else {
if (!(m_readable || (m_writable && (m_outputBuffer.getSize() > 0)))) {
return nullptr;
}
return new TSocketMultiplexerMethodJob<TCPSocket>(
this, &TCPSocket::serviceConnected, m_socket, m_readable, m_writable && (m_outputBuffer.getSize() > 0)
);
}
}
void TCPSocket::sendConnectionFailedEvent(const char *msg)
{
ConnectionFailedInfo *info = new ConnectionFailedInfo(msg);
m_events->addEvent(Event(m_events->forIDataSocket().connectionFailed(), getEventTarget(), info, Event::kDontFreeData)
);
}
void TCPSocket::sendEvent(Event::Type type)
{
m_events->addEvent(Event(type, getEventTarget()));
}
void TCPSocket::discardWrittenData(int bytesWrote)
{
m_outputBuffer.pop(bytesWrote);
if (m_outputBuffer.getSize() == 0) {
sendEvent(m_events->forIStream().outputFlushed());
m_flushed = true;
m_flushed.broadcast();
}
}
void TCPSocket::onConnected()
{
m_connected = true;
m_readable = true;
m_writable = true;
}
void TCPSocket::onInputShutdown()
{
m_inputBuffer.pop(m_inputBuffer.getSize());
m_readable = false;
}
void TCPSocket::onOutputShutdown()
{
m_outputBuffer.pop(m_outputBuffer.getSize());
m_writable = false;
// we're now flushed
m_flushed = true;
m_flushed.broadcast();
}
void TCPSocket::onDisconnected()
{
// disconnected
onInputShutdown();
onOutputShutdown();
m_connected = false;
}
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
// socket (and a socket that's connecting should be new) for errors
// should be safe and Mac OS X appears to have a bug where a
// non-blocking stream socket that fails to connect immediately is
// reported by select as being writable (i.e. connected) even when
// the connection has failed. this is easily demonstrated on OS X
// 10.3.4 by starting a deskflow client and telling to connect to
// another system that's not running a deskflow server. it will
// claim to have connected then quickly disconnect (i guess because
// read returns 0 bytes). unfortunately, deskflow attempts to
// reconnect immediately, the process repeats and we end up
// spinning the CPU. luckily, OS X does set SO_ERROR on the
// socket correctly when the connection has failed so checking for
// errors works. (curiously, sometimes OS X doesn't report
// connection refused. when that happens it at least doesn't
// report the socket as being writable so deskflow is able to time
// out the attempt.)
if (error || true) {
try {
// connection may have failed or succeeded
ARCH->throwErrorOnSocket(m_socket);
} catch (const XArchNetwork &e) {
sendConnectionFailedEvent(e.what());
onDisconnected();
return newJob();
}
}
if (write) {
sendEvent(m_events->forIDataSocket().connected());
onConnected();
return newJob();
}
return job;
}
ISocketMultiplexerJob *TCPSocket::serviceConnected(ISocketMultiplexerJob *job, bool read, bool write, bool error)
{
Lock lock(&m_mutex);
if (error) {
sendEvent(m_events->forISocket().disconnected());
onDisconnected();
return newJob();
}
EJobResult result = kRetry;
if (write) {
try {
result = doWrite();
} catch (XArchNetworkShutdown &) {
// remote read end of stream hungup. our output side
// has therefore shutdown.
onOutputShutdown();
sendEvent(m_events->forIStream().outputShutdown());
if (!m_readable && m_inputBuffer.getSize() == 0) {
sendEvent(m_events->forISocket().disconnected());
m_connected = false;
}
result = kNew;
} catch (XArchNetworkDisconnected &) {
// stream hungup
onDisconnected();
sendEvent(m_events->forISocket().disconnected());
result = kNew;
} catch (XArchNetwork &e) {
// other write error
LOG((CLOG_WARN "error writing socket: %s", e.what()));
onDisconnected();
sendEvent(m_events->forIStream().outputError());
sendEvent(m_events->forISocket().disconnected());
result = kNew;
}
}
if (read && m_readable) {
try {
result = doRead();
} catch (XArchNetworkDisconnected &) {
// stream hungup
sendEvent(m_events->forISocket().disconnected());
onDisconnected();
result = kNew;
} catch (XArchNetwork &e) {
// ignore other read error
LOG((CLOG_WARN "error reading socket: %s", e.what()));
}
}
if (result == kBreak) {
return nullptr;
}
return result == kNew ? newJob() : job;
}
| 13,932
|
C++
|
.cpp
| 480
| 25.133333
| 119
| 0.676932
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,671
|
SocketMultiplexer.cpp
|
deskflow_deskflow/src/lib/net/SocketMultiplexer.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2016 Symless Ltd.
* Copyright (C) 2004 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "net/SocketMultiplexer.h"
#include "arch/Arch.h"
#include "arch/XArch.h"
#include "base/Log.h"
#include "base/TMethodJob.h"
#include "common/stdvector.h"
#include "mt/CondVar.h"
#include "mt/Lock.h"
#include "mt/Mutex.h"
#include "mt/Thread.h"
#include "net/ISocketMultiplexerJob.h"
//
// SocketMultiplexer
//
SocketMultiplexer::SocketMultiplexer()
: m_mutex(new Mutex),
m_thread(NULL),
m_update(false),
m_jobsReady(new CondVar<bool>(m_mutex, false)),
m_jobListLock(new CondVar<bool>(m_mutex, false)),
m_jobListLockLocked(new CondVar<bool>(m_mutex, false)),
m_jobListLocker(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.
// TODO: Remove this evilness
m_cursorMark = reinterpret_cast<ISocketMultiplexerJob *>(this);
// start thread
m_thread = new Thread(new TMethodJob<SocketMultiplexer>(this, &SocketMultiplexer::serviceThread));
}
SocketMultiplexer::~SocketMultiplexer()
{
m_thread->cancel();
m_thread->unblockPollSocket();
m_thread->wait();
delete m_thread;
delete m_jobsReady;
delete m_jobListLock;
delete m_jobListLockLocked;
delete m_jobListLocker;
delete m_jobListLockLocker;
delete m_mutex;
// clean up jobs
for (SocketJobMap::iterator i = m_socketJobMap.begin(); i != m_socketJobMap.end(); ++i) {
delete *(i->second);
}
}
void SocketMultiplexer::addSocket(ISocket *socket, ISocketMultiplexerJob *job)
{
assert(socket != NULL);
assert(job != NULL);
// prevent other threads from locking the job list
lockJobListLock();
// break thread out of poll
m_thread->unblockPollSocket();
// lock the job list
lockJobList();
// insert/replace job
SocketJobMap::iterator i = m_socketJobMap.find(socket);
if (i == m_socketJobMap.end()) {
// we *must* put the job at the end so the order of jobs in
// the list continue to match the order of jobs in pfds in
// serviceThread().
JobCursor j = m_socketJobs.insert(m_socketJobs.end(), job);
m_update = true;
m_socketJobMap.insert(std::make_pair(socket, j));
} else {
JobCursor j = i->second;
if (*j != job) {
delete *j;
*j = job;
}
m_update = true;
}
// unlock the job list
unlockJobList();
}
void SocketMultiplexer::removeSocket(ISocket *socket)
{
assert(socket != NULL);
// prevent other threads from locking the job list
lockJobListLock();
// break thread out of poll
m_thread->unblockPollSocket();
// lock the job list
lockJobList();
// remove job. rather than removing it from the map we put NULL
// in the list instead so the order of jobs in the list continues
// to match the order of jobs in pfds in serviceThread().
SocketJobMap::iterator i = m_socketJobMap.find(socket);
if (i != m_socketJobMap.end()) {
if (*(i->second) != NULL) {
delete *(i->second);
*(i->second) = NULL;
m_update = true;
}
}
// unlock the job list
unlockJobList();
}
void SocketMultiplexer::serviceThread(void *)
{
std::vector<IArchNetwork::PollEntry> pfds;
IArchNetwork::PollEntry pfd;
// service the connections
for (;;) {
Thread::testCancel();
// wait until there are jobs to handle
{
Lock lock(m_mutex);
while (!(bool)*m_jobsReady) {
m_jobsReady->wait();
}
}
// lock the job list
lockJobListLock();
lockJobList();
// collect poll entries
if (m_update) {
m_update = false;
pfds.clear();
pfds.reserve(m_socketJobMap.size());
JobCursor cursor = newCursor();
JobCursor jobCursor = nextCursor(cursor);
while (jobCursor != m_socketJobs.end()) {
ISocketMultiplexerJob *job = *jobCursor;
if (job != NULL) {
pfd.m_socket = job->getSocket();
pfd.m_events = 0;
if (job->isReadable()) {
pfd.m_events |= IArchNetwork::kPOLLIN;
}
if (job->isWritable()) {
pfd.m_events |= IArchNetwork::kPOLLOUT;
}
pfds.push_back(pfd);
}
jobCursor = nextCursor(cursor);
}
deleteCursor(cursor);
}
int status;
try {
// check for status
if (!pfds.empty()) {
status = ARCH->pollSocket(&pfds[0], (int)pfds.size(), -1);
} else {
status = 0;
}
} catch (XArchNetwork &e) {
LOG((CLOG_WARN "error in socket multiplexer: %s", e.what()));
status = 0;
}
if (status != 0) {
// iterate over socket jobs, invoking each and saving the
// new job.
UInt32 i = 0;
JobCursor cursor = newCursor();
JobCursor jobCursor = nextCursor(cursor);
while (i < pfds.size() && jobCursor != m_socketJobs.end()) {
if (*jobCursor != NULL) {
// get poll state
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);
// run job
ISocketMultiplexerJob *job = *jobCursor;
ISocketMultiplexerJob *newJob = job->run(read, write, error);
// save job, if different
if (newJob != job) {
Lock lock(m_mutex);
delete job;
*jobCursor = newJob;
m_update = true;
}
++i;
}
// next job
jobCursor = nextCursor(cursor);
}
deleteCursor(cursor);
}
// delete any removed socket jobs
for (SocketJobMap::iterator i = m_socketJobMap.begin(); i != m_socketJobMap.end();) {
if (*(i->second) == NULL) {
m_socketJobs.erase(i->second);
m_socketJobMap.erase(i++);
m_update = true;
} else {
++i;
}
}
// unlock the job list
unlockJobList();
}
}
SocketMultiplexer::JobCursor SocketMultiplexer::newCursor()
{
Lock lock(m_mutex);
return m_socketJobs.insert(m_socketJobs.begin(), m_cursorMark);
}
SocketMultiplexer::JobCursor SocketMultiplexer::nextCursor(JobCursor cursor)
{
Lock lock(m_mutex);
JobCursor j = m_socketJobs.end();
JobCursor i = cursor;
while (++i != m_socketJobs.end()) {
if (*i != m_cursorMark) {
// found a real job (as opposed to a cursor)
j = i;
// move our cursor just past the job
m_socketJobs.splice(++i, m_socketJobs, cursor);
break;
}
}
return j;
}
void SocketMultiplexer::deleteCursor(JobCursor cursor)
{
Lock lock(m_mutex);
m_socketJobs.erase(cursor);
}
void SocketMultiplexer::lockJobListLock()
{
Lock lock(m_mutex);
// wait for the lock on the lock
while (*m_jobListLockLocked) {
m_jobListLockLocked->wait();
}
// take ownership of the lock on the lock
*m_jobListLockLocked = true;
m_jobListLockLocker = new Thread(Thread::getCurrentThread());
}
void SocketMultiplexer::lockJobList()
{
Lock lock(m_mutex);
// make sure we're the one that called lockJobListLock()
assert(*m_jobListLockLocker == Thread::getCurrentThread());
// wait for the job list lock
while (*m_jobListLock) {
m_jobListLock->wait();
}
// take ownership of the lock
*m_jobListLock = true;
m_jobListLocker = m_jobListLockLocker;
m_jobListLockLocker = NULL;
// release the lock on the lock
*m_jobListLockLocked = false;
m_jobListLockLocked->broadcast();
}
void SocketMultiplexer::unlockJobList()
{
Lock lock(m_mutex);
// make sure we're the one that called lockJobList()
assert(*m_jobListLocker == Thread::getCurrentThread());
// release the lock
delete m_jobListLocker;
m_jobListLocker = NULL;
*m_jobListLock = false;
m_jobListLock->signal();
// set new jobs ready state
bool isReady = !m_socketJobMap.empty();
if (*m_jobsReady != isReady) {
*m_jobsReady = isReady;
m_jobsReady->signal();
}
}
| 8,718
|
C++
|
.cpp
| 287
| 25.634146
| 100
| 0.654658
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,672
|
SecureSocket.cpp
|
deskflow_deskflow/src/lib/net/SecureSocket.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2015-2016 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SecureSocket.h"
#include "arch/XArch.h"
#include "base/Log.h"
#include "base/Path.h"
#include "base/TMethodEventJob.h"
#include "mt/Lock.h"
#include "net/TCPSocket.h"
#include "net/TSocketMultiplexerMethodJob.h"
#include <net/InverseSockets/SslLogger.h>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iterator>
#include <memory>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <sstream>
//
// SecureSocket
//
#define MAX_ERROR_SIZE 65535
static const float s_retryDelay = 0.01f;
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
{
SSL_CTX *m_context;
SSL *m_ssl;
};
SecureSocket::SecureSocket(
IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family
)
: TCPSocket(events, socketMultiplexer, family),
m_ssl(nullptr),
m_secureReady(false),
m_fatal(false)
{
}
SecureSocket::SecureSocket(IEventQueue *events, SocketMultiplexer *socketMultiplexer, ArchSocket socket)
: TCPSocket(events, socketMultiplexer, socket),
m_ssl(nullptr),
m_secureReady(false),
m_fatal(false)
{
}
SecureSocket::~SecureSocket()
{
freeSSL();
}
void SecureSocket::close()
{
freeSSL();
TCPSocket::close();
}
void SecureSocket::connect(const NetworkAddress &addr)
{
m_events->adoptHandler(
m_events->forIDataSocket().connected(), getEventTarget(),
new TMethodEventJob<SecureSocket>(this, &SecureSocket::handleTCPConnected)
);
TCPSocket::connect(addr);
}
ISocketMultiplexerJob *SecureSocket::newJob()
{
// after TCP connection is established, SecureSocket will pick up
// connected event and do secureConnect
if (m_connected && !m_secureReady) {
return NULL;
}
return TCPSocket::newJob();
}
void SecureSocket::secureConnect()
{
setJob(new TSocketMultiplexerMethodJob<SecureSocket>(
this, &SecureSocket::serviceConnect, getSocket(), isReadable(), isWritable()
));
}
void SecureSocket::secureAccept()
{
setJob(new TSocketMultiplexerMethodJob<SecureSocket>(
this, &SecureSocket::serviceAccept, getSocket(), isReadable(), isWritable()
));
}
TCPSocket::EJobResult SecureSocket::doRead()
{
static UInt8 buffer[4096];
memset(buffer, 0, sizeof(buffer));
int bytesRead = 0;
int status = 0;
if (isSecureReady()) {
status = secureRead(buffer, sizeof(buffer), bytesRead);
if (status < 0) {
return kBreak;
} else if (status == 0) {
return kNew;
}
} else {
return kRetry;
}
if (bytesRead > 0) {
bool wasEmpty = (m_inputBuffer.getSize() == 0);
// slurp up as much as possible
do {
m_inputBuffer.write(buffer, bytesRead);
status = secureRead(buffer, sizeof(buffer), bytesRead);
if (status < 0) {
return kBreak;
}
} while (bytesRead > 0 || status > 0);
// send input ready if input buffer was empty
if (wasEmpty) {
sendEvent(m_events->forIStream().inputReady());
}
} else {
// remote write end of stream hungup. our input side
// has therefore shutdown but don't flush our buffer
// since there's still data to be read.
sendEvent(m_events->forIStream().inputShutdown());
if (!m_writable && m_inputBuffer.getSize() == 0) {
sendEvent(m_events->forISocket().disconnected());
m_connected = false;
}
m_readable = false;
return kNew;
}
return kRetry;
}
TCPSocket::EJobResult SecureSocket::doWrite()
{
static bool s_retry = false;
static int s_retrySize = 0;
static int s_staticBufferSize = 0;
static void *s_staticBuffer = NULL;
// write data
int bufferSize = 0;
int bytesWrote = 0;
int status = 0;
if (s_retry) {
bufferSize = s_retrySize;
} else {
bufferSize = m_outputBuffer.getSize();
if (bufferSize != 0) {
if (bufferSize > s_staticBufferSize) {
s_staticBuffer = realloc(s_staticBuffer, bufferSize);
s_staticBufferSize = bufferSize;
}
memcpy(s_staticBuffer, m_outputBuffer.peek(bufferSize), bufferSize);
}
}
if (bufferSize == 0) {
return kRetry;
}
if (isSecureReady()) {
status = secureWrite(s_staticBuffer, bufferSize, bytesWrote);
if (status > 0) {
s_retry = false;
bufferSize = 0;
} else if (status < 0) {
return kBreak;
} else if (status == 0) {
s_retry = true;
s_retrySize = bufferSize;
return kNew;
}
} else {
return kRetry;
}
if (bytesWrote > 0) {
discardWrittenData(bytesWrote);
return kNew;
}
return kRetry;
}
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);
static int retry;
// Check result will cleanup the connection in the case of a fatal
checkResult(read, retry);
if (retry) {
return 0;
}
if (isFatal()) {
return -1;
}
}
// According to SSL spec, the number of bytes read must not be negative and
// not have an error code from SSL_get_error(). If this happens, it is
// itself an error. Let the parent handle the case
return read;
}
int SecureSocket::secureWrite(const void *buffer, int size, int &wrote)
{
if (m_ssl->m_ssl != NULL) {
LOG((CLOG_DEBUG2 "writing secure socket: %p", this));
wrote = SSL_write(m_ssl->m_ssl, buffer, size);
static int retry;
// Check result will cleanup the connection in the case of a fatal
checkResult(wrote, retry);
if (retry) {
return 0;
}
if (isFatal()) {
return -1;
}
}
// According to SSL spec, r must not be negative and not have an error code
// from SSL_get_error(). If this happens, it is itself an error. Let the
// parent handle the case
return wrote;
}
bool SecureSocket::isSecureReady()
{
return m_secureReady;
}
void SecureSocket::initSsl(bool server)
{
m_ssl = new Ssl();
m_ssl->m_context = NULL;
m_ssl->m_ssl = NULL;
initContext(server);
}
bool SecureSocket::loadCertificates(String &filename)
{
if (filename.empty()) {
SslLogger::logError("tls certificate is not specified");
return false;
} else {
std::ifstream file(deskflow::filesystem::path(filename));
bool exist = file.good();
file.close();
if (!exist) {
String errorMsg("tls certificate doesn't exist: ");
errorMsg.append(filename);
SslLogger::logError(errorMsg.c_str());
return false;
}
}
int r = 0;
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);
if (r <= 0) {
SslLogger::logError("could not use tls private key");
return false;
}
r = SSL_CTX_check_private_key(m_ssl->m_context);
if (!r) {
SslLogger::logError("could not verify tls private key");
return false;
}
return true;
}
void SecureSocket::initContext(bool server)
{
SSL_library_init();
const SSL_METHOD *method;
// load & register all cryptos, etc.
OpenSSL_add_all_algorithms();
// load all error messages
SSL_load_error_strings();
SslLogger::logSecureLibInfo();
if (server) {
method = SSLv23_server_method();
} else {
method = SSLv23_client_method();
}
// create new context from method
SSL_METHOD *m = const_cast<SSL_METHOD *>(method);
m_ssl->m_context = SSL_CTX_new(m);
// 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);
if (m_ssl->m_context == NULL) {
SslLogger::logError();
}
}
void SecureSocket::createSSL()
{
// I assume just one instance is needed
// get new SSL state with context
if (m_ssl->m_ssl == NULL) {
assert(m_ssl->m_context != NULL);
m_ssl->m_ssl = SSL_new(m_ssl->m_context);
}
}
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
// will do this, too, but the double-call is harmless
setJob(NULL);
if (m_ssl) {
if (m_ssl->m_ssl != NULL) {
SSL_shutdown(m_ssl->m_ssl);
SSL_free(m_ssl->m_ssl);
m_ssl->m_ssl = NULL;
}
if (m_ssl->m_context != NULL) {
SSL_CTX_free(m_ssl->m_context);
m_ssl->m_context = NULL;
}
delete m_ssl;
m_ssl = nullptr;
}
}
int SecureSocket::secureAccept(int socket)
{
createSSL();
// set connection socket to SSL state
SSL_set_fd(m_ssl->m_ssl, socket);
LOG((CLOG_DEBUG2 "accepting secure socket"));
int r = SSL_accept(m_ssl->m_ssl);
static int retry;
checkResult(r, retry);
if (isFatal()) {
// tell user and sleep so the socket isn't hammered.
LOG((CLOG_ERR "failed to accept secure socket"));
LOG((CLOG_WARN "client connection may not be secure"));
m_secureReady = false;
ARCH->sleep(1);
retry = 0;
return -1; // Failed, error out
}
// If not fatal and no retry, state is good
if (retry == 0) {
m_secureReady = true;
LOG((CLOG_INFO "accepted secure socket"));
SslLogger::logSecureCipherInfo(m_ssl->m_ssl);
SslLogger::logSecureConnectInfo(m_ssl->m_ssl);
return 1;
}
// If not fatal and retry is set, not ready, and return retry
if (retry > 0) {
LOG((CLOG_DEBUG2 "retry accepting secure socket"));
m_secureReady = false;
ARCH->sleep(s_retryDelay);
return 0;
}
// no good state exists here
LOG((CLOG_ERR "unexpected state attempting to accept connection"));
return -1;
}
int SecureSocket::secureConnect(int socket)
{
createSSL();
// attach the socket descriptor
SSL_set_fd(m_ssl->m_ssl, socket);
LOG((CLOG_DEBUG2 "connecting secure socket"));
// TODO: S1-1766, enable hostname verification.
// the cert will need to be installed in the trusted store on the client.
// we'll probably need to find a way of securely transferring the cert.
int r = SSL_connect(m_ssl->m_ssl);
static int retry;
checkResult(r, retry);
if (isFatal()) {
LOG((CLOG_ERR "failed to connect secure socket"));
retry = 0;
return -1;
}
// If we should retry, not ready and return 0
if (retry > 0) {
LOG((CLOG_DEBUG2 "retry connect secure socket"));
m_secureReady = false;
ARCH->sleep(s_retryDelay);
return 0;
}
retry = 0;
// No error, set ready, process and return ok
m_secureReady = true;
if (verifyCertFingerprint()) {
LOG((CLOG_INFO "connected to secure socket"));
if (!showCertificate()) {
disconnect();
return -1; // Cert fail, error
}
} else {
LOG((CLOG_ERR "failed to verify server certificate fingerprint"));
disconnect();
return -1; // Fingerprint failed, error
}
LOG((CLOG_DEBUG2 "connected secure socket"));
SslLogger::logSecureCipherInfo(m_ssl->m_ssl);
SslLogger::logSecureConnectInfo(m_ssl->m_ssl);
return 1;
}
bool SecureSocket::showCertificate() const
{
X509 *cert;
char *line;
// get the server's certificate
cert = SSL_get_peer_certificate(m_ssl->m_ssl);
if (cert != NULL) {
line = X509_NAME_oneline(X509_get_subject_name(cert), 0, 0);
LOG((CLOG_INFO "server tls certificate info: %s", line));
OPENSSL_free(line);
X509_free(cert);
} else {
SslLogger::logError("server has no tls certificate");
return false;
}
return true;
}
void SecureSocket::checkResult(int status, int &retry)
{
// ssl errors are a little quirky. the "want" errors are normal and
// should result in a retry.
int errorCode = SSL_get_error(m_ssl->m_ssl, status);
switch (errorCode) {
case SSL_ERROR_NONE:
retry = 0;
// operation completed
break;
case SSL_ERROR_ZERO_RETURN:
// connection closed
isFatal(true);
LOG((CLOG_DEBUG "tls connection closed"));
break;
case SSL_ERROR_WANT_READ:
retry++;
LOG((CLOG_DEBUG2 "want to read, error=%d, attempt=%d", errorCode, retry));
break;
case SSL_ERROR_WANT_WRITE:
// Need to make sure the socket is known to be writable so the impending
// select action actually triggers on a write. This isn't necessary for
// m_readable because the socket logic is always readable
m_writable = true;
retry++;
LOG((CLOG_DEBUG2 "want to write, error=%d, attempt=%d", errorCode, retry));
break;
case SSL_ERROR_WANT_CONNECT:
retry++;
LOG((CLOG_DEBUG2 "want to connect, error=%d, attempt=%d", errorCode, retry));
break;
case SSL_ERROR_WANT_ACCEPT:
retry++;
LOG((CLOG_DEBUG2 "want to accept, error=%d, attempt=%d", errorCode, retry));
break;
case SSL_ERROR_SYSCALL:
LOG((CLOG_ERR "tls error occurred (system call failure)"));
if (ERR_peek_error() == 0) {
if (status == 0) {
LOG((CLOG_ERR "eof violates tls protocol"));
} else if (status == -1) {
// underlying socket I/O reproted an error
try {
ARCH->throwErrorOnSocket(getSocket());
} catch (XArchNetwork &e) {
LOG((CLOG_ERR "%s", e.what()));
}
}
}
isFatal(true);
break;
case SSL_ERROR_SSL:
LOG((CLOG_ERR "tls error occurred (generic failure)"));
isFatal(true);
break;
default:
LOG((CLOG_ERR "tls error occurred (unknown failure)"));
isFatal(true);
break;
}
if (isFatal()) {
retry = 0;
SslLogger::logError();
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)
{
if (hex) {
// to hexidecimal
deskflow::string::toHex(fingerprint, 2);
}
// all uppercase
deskflow::string::uppercase(fingerprint);
if (separator) {
// add colon to separate each 2 charactors
size_t separators = fingerprint.size() / 2;
for (size_t i = 1; i < separators; i++) {
fingerprint.insert(i * 3 - 1, ":");
}
}
}
bool SecureSocket::verifyCertFingerprint()
{
// calculate received certificate fingerprint
using AutoX509 = std::unique_ptr<X509, decltype(&X509_free)>;
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);
if (digestResult <= 0) {
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<char *>(static_cast<void *>(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
);
// check if this fingerprint exist
String fileLine;
std::ifstream file;
file.open(deskflow::filesystem::path(trustedServersFilename));
bool isValid = false;
if (file.is_open()) {
while (!file.eof()) {
getline(file, fileLine);
if (!fileLine.empty() && !fileLine.compare(fingerprint)) {
isValid = true;
break;
}
}
} else {
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)
{
Lock lock(&getMutex());
int status = 0;
#ifdef SYSAPI_WIN32
status = secureConnect(static_cast<int>(getSocket()->m_socket));
#elif SYSAPI_UNIX
status = secureConnect(getSocket()->m_fd);
#endif
// If status < 0, error happened
if (status < 0) {
return NULL;
}
// If status > 0, success
if (status > 0) {
sendEvent(m_events->forIDataSocket().secureConnected());
return newJob();
}
// Retry case
return new TSocketMultiplexerMethodJob<SecureSocket>(
this, &SecureSocket::serviceConnect, getSocket(), isReadable(), isWritable()
);
}
ISocketMultiplexerJob *SecureSocket::serviceAccept(ISocketMultiplexerJob *job, bool, bool write, bool error)
{
Lock lock(&getMutex());
int status = 0;
#ifdef SYSAPI_WIN32
status = secureAccept(static_cast<int>(getSocket()->m_socket));
#elif SYSAPI_UNIX
status = secureAccept(getSocket()->m_fd);
#endif
// If status < 0, error happened
if (status < 0) {
return NULL;
}
// If status > 0, success
if (status > 0) {
sendEvent(m_events->forClientListener().accepted());
return newJob();
}
// Retry case
return new TSocketMultiplexerMethodJob<SecureSocket>(
this, &SecureSocket::serviceAccept, getSocket(), isReadable(), isWritable()
);
}
void SecureSocket::handleTCPConnected(const Event &, void *)
{
if (getSocket() == nullptr) {
LOG((CLOG_DEBUG "disregarding stale connect event"));
return;
}
secureConnect();
}
| 18,167
|
C++
|
.cpp
| 611
| 25.93617
| 113
| 0.681865
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,673
|
AutoArchSocket.cpp
|
deskflow_deskflow/src/lib/net/InverseSockets/AutoArchSocket.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2022 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "AutoArchSocket.h"
#include "arch/Arch.h"
#include "arch/XArch.h"
#include "base/Log.h"
#include "net/XSocket.h"
AutoArchSocket::AutoArchSocket(IArchNetwork::EAddressFamily family)
{
try {
m_socket = ARCH->newSocket(family, IArchNetwork::kSTREAM);
LOG((CLOG_DEBUG "opening new socket: %08X", m_socket));
} catch (const XArchNetwork &e) {
throw XSocketCreate(e.what());
}
}
AutoArchSocket::~AutoArchSocket()
{
closeSocket();
}
void AutoArchSocket::setNoDelayOnSocket(bool value)
{
if (isValid()) {
ARCH->setNoDelayOnSocket(m_socket, value);
}
}
void AutoArchSocket::setReuseAddrOnSocket(bool value)
{
if (isValid()) {
ARCH->setReuseAddrOnSocket(m_socket, value);
}
}
void AutoArchSocket::closeSocket()
{
if (isValid()) {
try {
LOG((CLOG_DEBUG "closing socket: %08X", m_socket));
ARCH->closeSocket(m_socket);
m_socket = nullptr;
} catch (const XArchNetwork &e) {
// ignore, there's not much we can do
LOG((CLOG_WARN "error closing socket: %s", e.what()));
}
} else {
LOG((CLOG_WARN "error closing socket because the socket already closed"));
}
}
void AutoArchSocket::bindSocket(const NetworkAddress &addr)
{
if (isValid()) {
try {
ARCH->bindSocket(m_socket, addr.getAddress());
} catch (const XArchNetworkAddressInUse &e) {
throw XSocketAddressInUse(e.what());
} catch (const XArchNetwork &e) {
throw XSocketBind(e.what());
}
}
}
void AutoArchSocket::bindAndListen(const NetworkAddress &addr)
{
try {
setReuseAddrOnSocket();
bindSocket(addr);
listenOnSocket();
} catch (const XArchNetworkAddressInUse &e) {
throw XSocketAddressInUse(e.what());
} catch (const XArchNetwork &e) {
throw XSocketBind(e.what());
}
}
void AutoArchSocket::listenOnSocket()
{
if (isValid()) {
ARCH->listenOnSocket(m_socket);
}
}
ArchSocket AutoArchSocket::acceptSocket()
{
return ARCH->acceptSocket(m_socket, nullptr);
}
void AutoArchSocket::closeSocketForRead()
{
if (isValid()) {
try {
ARCH->closeSocketForRead(m_socket);
} catch (const XArchNetwork &e) {
// ignore, there's not much we can do
LOG((CLOG_WARN "error closing socket: %s", e.what()));
}
}
}
void AutoArchSocket::closeSocketForWrite()
{
if (isValid()) {
try {
ARCH->closeSocketForWrite(m_socket);
} catch (const XArchNetwork &e) {
// ignore, there's not much we can do
LOG((CLOG_WARN "error closing socket: %s", e.what()));
}
}
}
bool AutoArchSocket::connectSocket(const NetworkAddress &addr)
{
bool result = false;
if (isValid()) {
// turn off Nagle algorithm. we send lots of very short messages
// that should be sent without (much) delay. for example, the
// mouse motion messages are much less useful if they're delayed.
setNoDelayOnSocket();
result = ARCH->connectSocket(m_socket, addr.getAddress());
}
return result;
}
size_t AutoArchSocket::readSocket(UInt8 *buffer, size_t size)
{
size_t result = 0;
if (isValid()) {
result = ARCH->readSocket(m_socket, buffer, size);
}
return result;
}
size_t AutoArchSocket::writeSocket(const UInt8 *buffer, size_t size)
{
size_t result = 0;
if (isValid()) {
result = ARCH->writeSocket(m_socket, buffer, size);
}
return result;
}
void AutoArchSocket::throwErrorOnSocket()
{
if (isValid()) {
ARCH->throwErrorOnSocket(m_socket);
}
}
ArchSocket AutoArchSocket::getRawSocket() const
{
return m_socket;
}
bool AutoArchSocket::isValid() const
{
return (m_socket != nullptr);
}
void AutoArchSocket::operator=(ArchSocket socket)
{
if (isValid()) {
closeSocket();
}
m_socket = socket;
}
| 4,430
|
C++
|
.cpp
| 167
| 23.449102
| 78
| 0.702218
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,674
|
InverseSocketFactory.cpp
|
deskflow_deskflow/src/lib/net/InverseSockets/InverseSocketFactory.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2022 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "InverseSocketFactory.h"
#include "net/InverseSockets/InverseClientSocket.h"
#include "net/InverseSockets/InverseServerSocket.h"
#include "net/InverseSockets/SecureClientSocket.h"
#include "net/InverseSockets/SecureServerSocket.h"
//
// InverseSocketFactory
//
InverseSocketFactory::InverseSocketFactory(IEventQueue *events, SocketMultiplexer *socketMultiplexer)
: m_events(events),
m_socketMultiplexer(socketMultiplexer)
{
}
IDataSocket *InverseSocketFactory::create(bool secure, IArchNetwork::EAddressFamily family) const
{
if (secure) {
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 *socket = nullptr;
if (secure) {
socket = new SecureServerSocket(m_events, m_socketMultiplexer, family);
} else {
socket = new InverseServerSocket(m_events, m_socketMultiplexer, family);
}
return socket;
}
| 1,808
|
C++
|
.cpp
| 48
| 35.270833
| 105
| 0.783352
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,675
|
SslLogger.cpp
|
deskflow_deskflow/src/lib/net/InverseSockets/SslLogger.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2015-2022 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SslLogger.h"
#include <iterator>
#include <sstream>
#include <base/Log.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
namespace {
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);
SSL_CIPHER_description(cipher, msg, sizeof(msg));
// SSL puts a newline in the description
auto pos = strnlen(msg, sizeof(msg)) - 1;
if (msg[pos] == '\n') {
msg[pos] = '\0';
}
LOG((CLOG_DEBUG1 "%s", msg));
}
}
void logLocalSecureCipherInfo(const SSL *ssl)
{
auto sStack = SSL_get_ciphers(ssl);
if (sStack) {
LOG((CLOG_DEBUG1 "available local ciphers:"));
showCipherStackDesc(sStack);
} else {
LOG((CLOG_DEBUG1 "local cipher list not available"));
}
}
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,
// however, LibreSSL still uses this.
auto cStack = ssl->session->ciphers;
#else
// Use SSL_get_client_ciphers() for newer versions of OpenSSL.
auto cStack = SSL_get_client_ciphers(ssl);
#endif
if (cStack) {
LOG((CLOG_DEBUG1 "available remote ciphers:"));
showCipherStackDesc(cStack);
} else {
LOG((CLOG_DEBUG1 "remote cipher list not available"));
}
}
} // namespace
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)));
LOG((CLOG_DEBUG1 "openssl built on: %s", SSLeay_version(SSLEAY_BUILT_ON)));
LOG((CLOG_DEBUG1 "openssl platform: %s", SSLeay_version(SSLEAY_PLATFORM)));
LOG((CLOG_DEBUG1 "openssl dir: %s", SSLeay_version(SSLEAY_DIR)));
}
}
void SslLogger::logSecureCipherInfo(const SSL *ssl)
{
if (ssl && CLOG->getFilter() >= kDEBUG1) {
logLocalSecureCipherInfo(ssl);
logRemoteSecureCipherInfo(ssl);
}
}
void SslLogger::logSecureConnectInfo(const SSL *ssl)
{
if (ssl) {
auto cipher = SSL_get_current_cipher(ssl);
if (cipher) {
char msg[128] = {0};
SSL_CIPHER_description(cipher, msg, sizeof(msg));
LOG((CLOG_DEBUG "openssl cipher: %s", msg));
// For some reason SSL_get_version is return mismatching information to
// SSL_CIPHER_description
// so grab the version out the description instead, This seems like a
// hacky way of doing it. But when the cipher says "TLSv1.2" but the
// get_version returns "TLSv1/SSLv3" we it doesn't look right For some
// reason macOS hates regex's so stringstream is used
std::istringstream iss(msg);
// Take the stream input and splits it into a vetor directly
const std::vector<std::string> parts{
std::istream_iterator<std::string>{iss}, std::istream_iterator<std::string>{}
};
if (parts.size() > 2) {
// log the section containing the protocol version
LOG((CLOG_INFO "network encryption protocol: %s", parts[1].c_str()));
} else {
// log the error in spliting then display the whole description rather
// then nothing
LOG((CLOG_ERR "could not split cipher for protocol"));
LOG((CLOG_INFO "network encryption protocol: %s", msg));
}
} else {
LOG((CLOG_ERR "could not get secure socket cipher"));
}
}
}
void SslLogger::logError(const std::string &reason)
{
if (!reason.empty()) {
LOG((CLOG_ERR "secure socket error: %s", reason.c_str()));
}
auto id = ERR_get_error();
if (id) {
char error[65535] = {0};
ERR_error_string_n(id, error, sizeof(error));
LOG((CLOG_ERR "openssl error: %s", error));
}
}
void SslLogger::logErrorByCode(int code, int retry)
{
switch (code) {
case SSL_ERROR_NONE:
break;
case SSL_ERROR_ZERO_RETURN:
LOG((CLOG_DEBUG "tls connection closed"));
break;
case SSL_ERROR_WANT_READ:
LOG((CLOG_DEBUG2 "want to read, error=%d, attempt=%d", code, retry));
break;
case SSL_ERROR_WANT_WRITE:
LOG((CLOG_DEBUG2 "want to write, error=%d, attempt=%d", code, retry));
break;
case SSL_ERROR_WANT_CONNECT:
LOG((CLOG_DEBUG2 "want to connect, error=%d, attempt=%d", code, retry));
break;
case SSL_ERROR_WANT_ACCEPT:
LOG((CLOG_DEBUG2 "want to accept, error=%d, attempt=%d", code, retry));
break;
case SSL_ERROR_SYSCALL:
LOG((CLOG_ERR "tls error occurred (system call failure)"));
break;
case SSL_ERROR_SSL:
LOG((CLOG_ERR "tls error occurred (generic failure)"));
break;
default:
LOG((CLOG_ERR "tls error occurred (unknown failure)"));
break;
}
}
| 5,493
|
C++
|
.cpp
| 159
| 30.63522
| 87
| 0.678598
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,676
|
InverseClientSocket.cpp
|
deskflow_deskflow/src/lib/net/InverseSockets/InverseClientSocket.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2022 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "InverseClientSocket.h"
#include "arch/Arch.h"
#include "arch/XArch.h"
#include "base/IEventJob.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "mt/Lock.h"
#include "net/NetworkAddress.h"
#include "net/SocketMultiplexer.h"
#include "net/TSocketMultiplexerMethodJob.h"
#include "net/XSocket.h"
#include <cstdlib>
#include <cstring>
#include <memory>
//
// InverseClientSocket
//
InverseClientSocket::InverseClientSocket(
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)
{
}
InverseClientSocket::~InverseClientSocket()
{
try {
// warning virtual function in destructor is very danger practice
InverseClientSocket::close();
} catch (...) {
LOG((CLOG_DEBUG "error while TCP socket destruction"));
}
}
void InverseClientSocket::bind(const NetworkAddress &addr)
{
m_socket.bindSocket(addr);
}
void InverseClientSocket::close()
{
setJob(nullptr);
Lock lock(&m_mutex);
onDisconnected();
}
void *InverseClientSocket::getEventTarget() const
{
return const_cast<void *>(static_cast<const void *>(this));
}
UInt32 InverseClientSocket::read(void *buffer, UInt32 n)
{
// copy data directly from our input buffer
Lock lock(&m_mutex);
UInt32 size = m_inputBuffer.getSize();
if (n > size) {
n = size;
}
if (buffer != nullptr && n != 0) {
memcpy(buffer, m_inputBuffer.peek(n), n);
}
m_inputBuffer.pop(n);
// if no more data and we cannot read or write then send disconnected
if (n > 0 && m_inputBuffer.getSize() == 0 && !m_readable && !m_writable) {
sendEvent(m_events->forISocket().disconnected());
m_connected = false;
}
return n;
}
void InverseClientSocket::write(const void *buffer, UInt32 n)
{
bool wasEmpty;
{
Lock lock(&m_mutex);
// must not have shutdown output
if (!m_writable) {
sendEvent(m_events->forIStream().outputError());
return;
}
// ignore empty writes
if (n == 0) {
return;
}
// copy data to the output buffer
wasEmpty = (m_outputBuffer.getSize() == 0);
m_outputBuffer.write(buffer, n);
// there's data to write
m_flushed = false;
}
// make sure we're waiting to write
if (wasEmpty) {
setJob(newJob(m_socket.getRawSocket()));
}
}
void InverseClientSocket::flush()
{
Lock lock(&m_mutex);
while (m_flushed == false) {
m_flushed.wait();
}
}
void InverseClientSocket::shutdownInput()
{
bool useNewJob = false;
{
Lock lock(&m_mutex);
// shutdown socket for reading
m_socket.closeSocketForRead();
// shutdown buffer for reading
if (m_readable) {
sendEvent(m_events->forIStream().inputShutdown());
onInputShutdown();
useNewJob = true;
}
}
if (useNewJob) {
setJob(newJob(m_socket.getRawSocket()));
}
}
void InverseClientSocket::shutdownOutput()
{
bool useNewJob = false;
{
Lock lock(&m_mutex);
// shutdown socket for writing
m_socket.closeSocketForWrite();
// shutdown buffer for writing
if (m_writable) {
sendEvent(m_events->forIStream().outputShutdown());
onOutputShutdown();
useNewJob = true;
}
}
if (useNewJob) {
setJob(newJob(m_socket.getRawSocket()));
}
}
bool InverseClientSocket::isReady() const
{
Lock lock(&m_mutex);
return (m_inputBuffer.getSize() > 0);
}
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
{
Lock lock(&m_mutex);
return m_inputBuffer.getSize();
}
void InverseClientSocket::connect(const NetworkAddress &addr)
{
{
Lock lock(&m_mutex);
m_listener.bindAndListen(addr);
m_writable = true;
m_readable = true;
}
setJob(newJob(m_listener.getRawSocket()));
}
InverseClientSocket::EJobResult InverseClientSocket::doRead()
{
UInt8 buffer[4096] = {0};
size_t bytesRead = m_socket.readSocket(buffer, sizeof(buffer));
if (bytesRead > 0) {
bool wasEmpty = (m_inputBuffer.getSize() == 0);
// slurp up as much as possible
do {
m_inputBuffer.write(buffer, static_cast<UInt32>(bytesRead));
bytesRead = m_socket.readSocket(buffer, sizeof(buffer));
} while (bytesRead > 0);
// send input ready if input buffer was empty
if (wasEmpty) {
sendEvent(m_events->forIStream().inputReady());
}
} else {
// remote write end of stream hungup. our input side
// has therefore shutdown but don't flush our buffer
// since there's still data to be read.
sendEvent(m_events->forIStream().inputShutdown());
if (!m_writable && m_inputBuffer.getSize() == 0) {
sendEvent(m_events->forISocket().disconnected());
m_connected = false;
}
m_readable = false;
return InverseClientSocket::EJobResult::kNew;
}
return InverseClientSocket::EJobResult::kRetry;
}
InverseClientSocket::EJobResult InverseClientSocket::doWrite()
{
UInt32 bufferSize = m_outputBuffer.getSize();
auto buffer = static_cast<const UInt8 *>(m_outputBuffer.peek(bufferSize));
const auto bytesWrote = static_cast<UInt32>(m_socket.writeSocket(buffer, bufferSize));
if (bytesWrote > 0) {
discardWrittenData(bytesWrote);
return InverseClientSocket::EJobResult::kNew;
}
return InverseClientSocket::EJobResult::kRetry;
}
void InverseClientSocket::setJob(ISocketMultiplexerJob *job)
{
// multiplexer will delete the old job
if (job == nullptr) {
m_socketMultiplexer->removeSocket(this);
} else {
m_socketMultiplexer->addSocket(this, job);
}
}
ISocketMultiplexerJob *InverseClientSocket::newJob(ArchSocket socket)
{
// note -- must have m_mutex locked on entry
ISocketMultiplexerJob *result = nullptr;
if (socket) {
auto isWritable = m_writable;
auto handler = &InverseClientSocket::serviceConnecting;
if (m_connected) {
handler = &InverseClientSocket::serviceConnected;
isWritable = (isWritable && (m_outputBuffer.getSize() > 0));
}
if (m_readable || isWritable) {
result = new TSocketMultiplexerMethodJob<InverseClientSocket>(this, handler, socket, m_readable, isWritable);
}
}
return result;
}
void InverseClientSocket::sendConnectionFailedEvent(const char *msg)
{
auto info = new ConnectionFailedInfo(msg);
m_events->addEvent(Event(m_events->forIDataSocket().connectionFailed(), getEventTarget(), info, Event::kDontFreeData)
);
}
void InverseClientSocket::sendEvent(Event::Type type)
{
m_events->addEvent(Event(type, getEventTarget()));
}
void InverseClientSocket::discardWrittenData(int bytesWrote)
{
m_outputBuffer.pop(bytesWrote);
if (m_outputBuffer.getSize() == 0) {
sendEvent(m_events->forIStream().outputFlushed());
m_flushed = true;
m_flushed.broadcast();
}
}
void InverseClientSocket::onConnected()
{
sendEvent(m_events->forIDataSocket().connected());
m_connected = true;
m_readable = true;
m_writable = true;
}
void InverseClientSocket::onInputShutdown()
{
m_inputBuffer.pop(m_inputBuffer.getSize());
m_readable = false;
}
void InverseClientSocket::onOutputShutdown()
{
m_outputBuffer.pop(m_outputBuffer.getSize());
m_writable = false;
// we're now flushed
m_flushed = true;
m_flushed.broadcast();
}
void InverseClientSocket::onDisconnected()
{
if (m_connected) {
sendEvent(m_events->forISocket().disconnected());
}
// disconnected
onInputShutdown();
onOutputShutdown();
m_connected = false;
}
ISocketMultiplexerJob *InverseClientSocket::serviceConnecting(ISocketMultiplexerJob *job, bool read, bool, bool)
{
Lock lock(&m_mutex);
if (read) {
m_socket = m_listener.acceptSocket();
onConnected();
return newJob(m_socket.getRawSocket());
}
return job;
}
ISocketMultiplexerJob *
InverseClientSocket::serviceConnected(ISocketMultiplexerJob *job, bool read, bool write, bool error)
{
Lock lock(&m_mutex);
if (error) {
onDisconnected();
return newJob(m_listener.getRawSocket());
}
EJobResult result = InverseClientSocket::EJobResult::kRetry;
if (write) {
try {
result = doWrite();
} catch (const XArchNetworkShutdown &) {
// remote read end of stream hungup. our output side
// has therefore shutdown.
onOutputShutdown();
sendEvent(m_events->forIStream().outputShutdown());
if (!m_readable && m_inputBuffer.getSize() == 0) {
sendEvent(m_events->forISocket().disconnected());
m_connected = false;
}
result = InverseClientSocket::EJobResult::kNew;
} catch (const XArchNetworkDisconnected &) {
// stream hungup
onDisconnected();
result = InverseClientSocket::EJobResult::kNew;
} catch (const XArchNetwork &e) {
// other write error
LOG((CLOG_WARN "error writing socket: %s", e.what()));
onDisconnected();
sendEvent(m_events->forIStream().outputError());
result = InverseClientSocket::EJobResult::kNew;
}
}
if (read && m_readable) {
try {
result = doRead();
} catch (const XArchNetworkDisconnected &) {
// stream hungup
onDisconnected();
result = InverseClientSocket::EJobResult::kNew;
} catch (const XArchNetwork &e) {
// ignore other read error
LOG((CLOG_WARN "error reading socket: %s", e.what()));
}
}
if (result == InverseClientSocket::EJobResult::kBreak) {
return nullptr;
}
return result == InverseClientSocket::EJobResult::kNew ? newJob(m_socket.getRawSocket()) : job;
}
| 10,438
|
C++
|
.cpp
| 357
| 25.669468
| 119
| 0.705929
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| true
| false
| false
|
13,677
|
SslApi.cpp
|
deskflow_deskflow/src/lib/net/InverseSockets/SslApi.cpp
|
#include "SslApi.h"
#include "SslLogger.h"
#include <fstream>
#include <memory>
#include <base/Log.h>
#include <base/Path.h>
#include <openssl/err.h>
namespace deskflow {
namespace ssl {
using AutoX509 = std::unique_ptr<X509, decltype(&X509_free)>;
SslApi::SslApi(bool isServer)
{
SSL_library_init();
// load & register all cryptos, etc.
OpenSSL_add_all_algorithms();
// load all error messages
SSL_load_error_strings();
createContext(isServer);
SslLogger::logSecureLibInfo();
}
SslApi::~SslApi()
{
if (m_ssl) {
SSL_shutdown(m_ssl);
SSL_free(m_ssl);
m_ssl = nullptr;
}
if (m_context) {
SSL_CTX_free(m_context);
m_context = nullptr;
}
}
int SslApi::read(char *buffer, int size)
{
auto read = 0;
if (m_ssl) {
read = SSL_read(m_ssl, buffer, size);
}
return read;
}
int SslApi::write(const char *buffer, int size)
{
auto wrote = 0;
if (m_ssl) {
wrote = SSL_write(m_ssl, buffer, size);
}
return wrote;
}
int SslApi::accept(int socket)
{
int result = 0;
if (m_ssl) {
// set connection socket to SSL state
SSL_set_fd(m_ssl, socket);
result = SSL_accept(m_ssl);
}
return result;
}
int SslApi::connect(int socket)
{
auto result = 0;
if (m_ssl) {
// attach the socket descriptor
SSL_set_fd(m_ssl, socket);
result = SSL_connect(m_ssl);
}
return result;
}
void SslApi::createSSL()
{
if (m_ssl == nullptr && m_context != nullptr) {
m_ssl = SSL_new(m_context);
}
}
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);
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);
if (r <= 0) {
SslLogger::logError("could not use tls private key");
return false;
}
r = SSL_CTX_check_private_key(m_context);
if (!r) {
SslLogger::logError("could not verify tls private key");
return false;
}
}
return result;
}
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);
LOG((CLOG_INFO "server tls certificate info: %s", line));
OPENSSL_free(line);
result = true;
} else {
SslLogger::logError("server has no tls certificate");
}
}
return result;
}
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);
if (digestResult <= 0) {
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<char *>(static_cast<void *>(tempFingerprint)), tempFingerprintLen);
formatFingerprint(fingerprint);
return fingerprint;
}
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());
// check if this fingerprint exist
std::ifstream file;
file.open(deskflow::filesystem::path(trustedServersFilename));
bool isValid = false;
if (file.is_open()) {
while (!file.eof()) {
std::string fileLine;
getline(file, fileLine);
if (!fileLine.empty() && !fileLine.compare(fingerprint)) {
isValid = true;
break;
}
}
} else {
LOG((CLOG_ERR "failed to open trusted fingerprints file: %s", trustedServersFilename.c_str()));
}
return (isValid && showCertificate());
}
void SslApi::createContext(bool isServer)
{
// create new context from method
if (isServer) {
m_context = SSL_CTX_new(SSLv23_server_method());
} else {
m_context = SSL_CTX_new(SSLv23_client_method());
}
// 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);
if (m_context) {
m_ssl = SSL_new(m_context);
} else {
SslLogger::logError();
}
}
void SslApi::logSecureInfo() const
{
SslLogger::logSecureCipherInfo(m_ssl);
SslLogger::logSecureConnectInfo(m_ssl);
}
int SslApi::getErrorCode(int status) const
{
return SSL_get_error(m_ssl, status);
}
void SslApi::formatFingerprint(std::string &fingerprint) const
{
// to hexidecimal
deskflow::string::toHex(fingerprint, 2);
// all uppercase
deskflow::string::uppercase(fingerprint);
// add colon to separate each 2 charactors
size_t separators = fingerprint.size() / 2;
for (size_t i = 1; i < separators; i++) {
fingerprint.insert(i * 3 - 1, ":");
}
}
bool SslApi::isCertificateExists(const std::string &filename) const
{
bool result = (!filename.empty());
if (result) {
std::ifstream file(deskflow::filesystem::path(filename));
result = file.good();
if (!result) {
std::string errorMsg("tls certificate doesn't exist: ");
errorMsg.append(filename);
SslLogger::logError(errorMsg.c_str());
}
} else {
SslLogger::logError("tls certificate is not specified");
}
return result;
}
} // namespace ssl
} // namespace deskflow
| 5,821
|
C++
|
.cpp
| 208
| 24.504808
| 106
| 0.682773
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,678
|
InverseServerSocket.cpp
|
deskflow_deskflow/src/lib/net/InverseSockets/InverseServerSocket.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012-2022 Symless Ltd.
* Copyright (C) 2002 Chris Schoeneman
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "InverseServerSocket.h"
#include "arch/Arch.h"
#include "arch/XArch.h"
#include "base/IEventQueue.h"
#include "base/Log.h"
#include "io/XIO.h"
#include "mt/Lock.h"
#include "mt/Mutex.h"
#include "net/NetworkAddress.h"
#include "net/SocketMultiplexer.h"
#include "net/TCPSocket.h"
#include "net/TSocketMultiplexerMethodJob.h"
#include "net/XSocket.h"
//
// InverseServerSocket
//
InverseServerSocket::InverseServerSocket(
IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family
)
: m_socket(family),
m_events(events),
m_socketMultiplexer(socketMultiplexer)
{
}
InverseServerSocket::~InverseServerSocket()
{
m_socketMultiplexer->removeSocket(this);
}
void InverseServerSocket::bind(const NetworkAddress &addr)
{
Lock lock(&m_mutex);
m_address = addr;
m_socket.connectSocket(m_address);
setListeningJob(true);
}
void InverseServerSocket::close()
{
Lock lock(&m_mutex);
m_socketMultiplexer->removeSocket(this);
m_socket.closeSocket();
}
void *InverseServerSocket::getEventTarget() const
{
return const_cast<void *>(static_cast<const void *>(this));
}
IDataSocket *InverseServerSocket::accept()
{
IDataSocket *socket = nullptr;
try {
socket = new TCPSocket(m_events, m_socketMultiplexer, m_socket.getRawSocket());
if (socket != nullptr) {
setListeningJob();
}
return socket;
} catch (const XArchNetwork &) {
if (socket != nullptr) {
delete socket;
setListeningJob();
}
return nullptr;
} catch (const std::exception &) {
if (socket != nullptr) {
delete socket;
setListeningJob();
}
throw;
}
}
void InverseServerSocket::setListeningJob(bool read)
{
m_socketMultiplexer->addSocket(
this, new TSocketMultiplexerMethodJob<InverseServerSocket>(
this, &InverseServerSocket::serviceListening, m_socket.getRawSocket(), true, read
)
);
}
ISocketMultiplexerJob *InverseServerSocket::serviceListening(ISocketMultiplexerJob *job, bool, bool write, bool error)
{
if (error) {
m_socket.connectSocket(m_address);
return job;
}
if (write) {
m_events->addEvent(Event(m_events->forIListenSocket().connecting(), this));
// stop polling on this socket until the client accepts
return nullptr;
}
return job;
}
| 3,058
|
C++
|
.cpp
| 106
| 25.839623
| 118
| 0.736484
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,679
|
SecureServerSocket.cpp
|
deskflow_deskflow/src/lib/net/InverseSockets/SecureServerSocket.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2015-2022 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SecureServerSocket.h"
#include <arch/XArch.h>
#include <common/constants.h>
#include <deskflow/ArgParser.h>
#include <deskflow/ArgsBase.h>
#include <net/SecureSocket.h>
#include <net/TSocketMultiplexerMethodJob.h>
//
// SecureServerSocket
//
SecureServerSocket::SecureServerSocket(
IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family
)
: InverseServerSocket(events, socketMultiplexer, family)
{
}
IDataSocket *SecureServerSocket::accept()
{
SecureSocket *socket = nullptr;
try {
socket = new SecureSocket(m_events, m_socketMultiplexer, m_socket.getRawSocket());
socket->initSsl(true);
setListeningJob();
auto certificateFilename = getCertificateFileName();
if (socket->loadCertificates(certificateFilename)) {
socket->secureAccept();
} else {
delete socket;
socket = nullptr;
}
} catch (const XArchNetwork &) {
if (socket) {
delete socket;
socket = nullptr;
setListeningJob();
}
} catch (const std::exception &) {
if (socket) {
delete socket;
setListeningJob();
}
throw;
}
return dynamic_cast<IDataSocket *>(socket);
}
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/%s.pem", ARCH->getProfileDirectory().c_str(), kAppId);
}
return certificateFilename;
}
| 2,367
|
C++
|
.cpp
| 72
| 29.611111
| 114
| 0.738731
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,680
|
SecureClientSocket.cpp
|
deskflow_deskflow/src/lib/net/InverseSockets/SecureClientSocket.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2015-2022 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "SecureClientSocket.h"
#include "SslLogger.h"
#include <fstream>
#include <set>
#include <sstream>
#include <base/Log.h>
#include <base/Path.h>
#include <base/TMethodEventJob.h>
#include <arch/XArch.h>
#include <mt/Lock.h>
#include <openssl/err.h>
#include <openssl/ssl.h>
#include <net/NetworkAddress.h>
#include <net/TSocketMultiplexerMethodJob.h>
//
// SecureClientSocket
//
constexpr float s_retryDelay = 0.01f;
SecureClientSocket::SecureClientSocket(
IEventQueue *events, SocketMultiplexer *socketMultiplexer, IArchNetwork::EAddressFamily family
)
: InverseClientSocket(events, socketMultiplexer, family)
{
}
void SecureClientSocket::connect(const NetworkAddress &addr)
{
m_events->adoptHandler(
m_events->forIDataSocket().connected(), getEventTarget(),
new TMethodEventJob<SecureClientSocket>(this, &SecureClientSocket::handleTCPConnected)
);
InverseClientSocket::connect(addr);
}
ISocketMultiplexerJob *SecureClientSocket::newJob()
{
// after TCP connection is established, SecureClientSocket will pick up
// connected event and do secureConnect
if (m_connected && !m_secureReady) {
return nullptr;
}
return InverseClientSocket::newJob(getSocket());
}
void SecureClientSocket::secureConnect()
{
setJob(new TSocketMultiplexerMethodJob<SecureClientSocket>(
this, &SecureClientSocket::serviceConnect, getSocket(), isReadable(), isWritable()
));
}
void SecureClientSocket::secureAccept()
{
setJob(new TSocketMultiplexerMethodJob<SecureClientSocket>(
this, &SecureClientSocket::serviceAccept, getSocket(), isReadable(), isWritable()
));
}
InverseClientSocket::EJobResult SecureClientSocket::doRead()
{
UInt8 buffer[4096] = {0};
int bytesRead = 0;
int status = 0;
if (isSecureReady()) {
status = secureRead(buffer, sizeof(buffer), bytesRead);
if (status < 0) {
return InverseClientSocket::EJobResult::kBreak;
} else if (status == 0) {
return InverseClientSocket::EJobResult::kNew;
}
} else {
return InverseClientSocket::EJobResult::kRetry;
}
if (bytesRead > 0) {
bool wasEmpty = (m_inputBuffer.getSize() == 0);
// slurp up as much as possible
do {
m_inputBuffer.write(buffer, bytesRead);
status = secureRead(buffer, sizeof(buffer), bytesRead);
if (status < 0) {
return InverseClientSocket::EJobResult::kBreak;
}
} while (bytesRead > 0 || status > 0);
// send input ready if input buffer was empty
if (wasEmpty) {
sendEvent(m_events->forIStream().inputReady());
}
} else {
// remote write end of stream hungup. our input side
// has therefore shutdown but don't flush our buffer
// since there's still data to be read.
sendEvent(m_events->forIStream().inputShutdown());
if (!m_writable && m_inputBuffer.getSize() == 0) {
sendEvent(m_events->forISocket().disconnected());
m_connected = false;
}
m_readable = false;
return InverseClientSocket::EJobResult::kNew;
}
return InverseClientSocket::EJobResult::kRetry;
}
InverseClientSocket::EJobResult SecureClientSocket::doWrite()
{
static bool s_retry = false;
static int s_retrySize = 0;
static int s_staticBufferSize = 0;
static void *s_staticBuffer = nullptr;
// write data
int bufferSize = 0;
int bytesWrote = 0;
int status = 0;
if (s_retry) {
bufferSize = s_retrySize;
} else {
bufferSize = m_outputBuffer.getSize();
if (bufferSize != 0) {
if (bufferSize > s_staticBufferSize) {
s_staticBuffer = realloc(s_staticBuffer, bufferSize);
s_staticBufferSize = bufferSize;
}
memcpy(s_staticBuffer, m_outputBuffer.peek(bufferSize), bufferSize);
}
}
if (bufferSize == 0) {
return InverseClientSocket::EJobResult::kRetry;
}
if (isSecureReady()) {
status = secureWrite(s_staticBuffer, bufferSize, bytesWrote);
if (status > 0) {
s_retry = false;
} else if (status < 0) {
return InverseClientSocket::EJobResult::kBreak;
} else if (status == 0) {
s_retry = true;
s_retrySize = bufferSize;
return InverseClientSocket::EJobResult::kNew;
}
} else {
return InverseClientSocket::EJobResult::kRetry;
}
if (bytesWrote > 0) {
discardWrittenData(bytesWrote);
return InverseClientSocket::EJobResult::kNew;
}
return InverseClientSocket::EJobResult::kRetry;
}
int SecureClientSocket::secureRead(void *buffer, int size, int &read)
{
LOG((CLOG_DEBUG2 "reading secure socket"));
read = m_ssl.read(static_cast<char *>(buffer), size);
static int retry = 0;
// Check result will cleanup the connection in the case of a fatal
checkResult(read, retry);
if (retry) {
return 0;
}
if (isFatal()) {
return -1;
}
// According to SSL spec, the number of bytes read must not be negative and
// not have an error code from SSL_get_error(). If this happens, it is
// itself an error. Let the parent handle the case
return read;
}
int SecureClientSocket::secureWrite(const void *buffer, int size, int &wrote)
{
LOG((CLOG_DEBUG2 "writing secure socket: %p", this));
wrote = m_ssl.write(static_cast<const char *>(buffer), size);
static int retry = 0;
// Check result will cleanup the connection in the case of a fatal
checkResult(wrote, retry);
if (retry) {
return 0;
}
if (isFatal()) {
return -1;
}
// According to SSL spec, r must not be negative and not have an error code
// from SSL_get_error(). If this happens, it is itself an error. Let the
// parent handle the case
return wrote;
}
bool SecureClientSocket::isSecureReady() const
{
return m_secureReady;
}
bool SecureClientSocket::loadCertificates(const std::string &filename)
{
return m_ssl.loadCertificate(filename);
}
int SecureClientSocket::secureAccept(int socket)
{
LOG((CLOG_DEBUG2 "accepting secure socket"));
static int retry = 0;
checkResult(m_ssl.accept(socket), retry);
if (isFatal()) {
// tell user and sleep so the socket isn't hammered.
LOG((CLOG_ERR "failed to accept secure socket"));
LOG((CLOG_WARN "client connection may not be secure"));
m_secureReady = false;
ARCH->sleep(1);
retry = 0;
return -1; // Failed, error out
}
// If not fatal and no retry, state is good
if (retry == 0) {
m_secureReady = true;
LOG((CLOG_INFO "accepted secure socket"));
m_ssl.logSecureInfo();
return 1;
}
// If not fatal and retry is set, not ready, and return retry
if (retry > 0) {
LOG((CLOG_DEBUG2 "retry accepting secure socket"));
m_secureReady = false;
ARCH->sleep(s_retryDelay);
return 0;
}
// no good state exists here
LOG((CLOG_ERR "unexpected state attempting to accept connection"));
return -1;
}
int SecureClientSocket::secureConnect(int socket)
{
LOG((CLOG_DEBUG2 "connecting secure socket"));
static int retry = 0;
checkResult(m_ssl.connect(socket), retry);
if (isFatal()) {
LOG((CLOG_ERR "failed to connect secure socket"));
retry = 0;
return -1;
}
// If we should retry, not ready and return 0
if (retry > 0) {
LOG((CLOG_DEBUG2 "retry connect secure socket"));
m_secureReady = false;
ARCH->sleep(s_retryDelay);
return 0;
}
retry = 0;
// No error, set ready, process and return ok
m_secureReady = true;
sendEvent(m_events->forIDataSocket().secureConnected());
auto fingerprint = m_ssl.getFingerprint();
LOG((CLOG_NOTE "server fingerprint: %s", fingerprint.c_str()));
if (m_ssl.isTrustedFingerprint(fingerprint)) {
LOG((CLOG_INFO "connected to secure socket"));
m_ssl.logSecureInfo();
return 1;
} else {
LOG((CLOG_ERR "failed to verify server certificate fingerprint"));
disconnect();
return -1; // Fingerprint failed, error
}
}
void SecureClientSocket::setFatal(int code)
{
const std::set<int> nonFatal{
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
{
const std::set<int> retryCodes{
SSL_ERROR_WANT_READ, SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT
};
if (errorCode == SSL_ERROR_NONE || isFatal()) {
retry = 0;
} else if (retryCodes.find(errorCode) != retryCodes.end()) {
++retry;
}
return 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);
setFatal(errorCode);
retry = getRetry(errorCode, retry);
switch (errorCode) {
case SSL_ERROR_WANT_WRITE:
// Need to make sure the socket is known to be writable so the impending
// select action actually triggers on a write. This isn't necessary for
// m_readable because the socket logic is always readable
m_writable = true;
break;
case SSL_ERROR_SYSCALL:
if (ERR_peek_error() == 0) {
if (status == 0) {
LOG((CLOG_ERR "eof violates tls protocol"));
} else if (status == -1) {
// underlying socket I/O reproted an error
try {
ARCH->throwErrorOnSocket(getSocket());
} catch (const XArchNetwork &e) {
LOG((CLOG_ERR "%s", e.what()));
}
}
}
break;
default:
break;
}
SslLogger::logErrorByCode(errorCode, retry);
if (isFatal()) {
SslLogger::logError();
disconnect();
}
}
void SecureClientSocket::disconnect()
{
sendEvent(getEvents()->forISocket().stopRetry());
sendEvent(getEvents()->forISocket().disconnected());
sendEvent(getEvents()->forIStream().inputShutdown());
}
ISocketMultiplexerJob *SecureClientSocket::serviceConnect(ISocketMultiplexerJob *, bool, bool, bool)
{
Lock lock(&getMutex());
int status = 0;
#ifdef SYSAPI_WIN32
status = secureConnect(static_cast<int>(getSocket()->m_socket));
#elif SYSAPI_UNIX
status = secureConnect(getSocket()->m_fd);
#endif
// If status < 0, error happened
if (status < 0) {
return nullptr;
}
// If status > 0, success
if (status > 0) {
sendEvent(m_events->forIDataSocket().secureConnected());
return newJob();
}
// Retry case
return new TSocketMultiplexerMethodJob<SecureClientSocket>(
this, &SecureClientSocket::serviceConnect, getSocket(), isReadable(), isWritable()
);
}
ISocketMultiplexerJob *SecureClientSocket::serviceAccept(ISocketMultiplexerJob *, bool, bool, bool)
{
Lock lock(&getMutex());
int status = 0;
#ifdef SYSAPI_WIN32
status = secureAccept(static_cast<int>(getSocket()->m_socket));
#elif SYSAPI_UNIX
status = secureAccept(getSocket()->m_fd);
#endif
// If status < 0, error happened
if (status < 0) {
return nullptr;
}
// If status > 0, success
if (status > 0) {
sendEvent(m_events->forClientListener().accepted());
return newJob();
}
// Retry case
return new TSocketMultiplexerMethodJob<SecureClientSocket>(
this, &SecureClientSocket::serviceAccept, getSocket(), isReadable(), isWritable()
);
}
void SecureClientSocket::handleTCPConnected(const Event &, void *)
{
if (getSocket()) {
secureConnect();
} else {
LOG((CLOG_DEBUG "disregarding stale connect event"));
}
}
| 11,994
|
C++
|
.cpp
| 382
| 27.767016
| 110
| 0.703155
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,681
|
main.cpp
|
deskflow_deskflow/src/test/integtests/main.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2012 Symless Ltd.
* Copyright (C) 2011 Nick Bolton
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "arch/Arch.h"
#include "base/Log.h"
#include "shared/ExitTimeout.h"
#if SYSAPI_WIN32
#include "arch/win32/ArchMiscWindows.h"
#endif
#include <filesystem>
#include <gtest/gtest.h>
using deskflow::test::ExitTimeout;
const auto testDir = "tmp/test";
int main(int argc, char **argv)
{
// HACK: Unit tests should not use the filesystem.
std::filesystem::create_directories(testDir);
ExitTimeout exitTimeout(1, "Integration tests");
#if SYSAPI_WIN32
// record window instance for tray icon, etc
ArchMiscWindows::setInstanceWin32(GetModuleHandle(NULL));
#endif
Arch arch;
arch.init();
Log log;
log.setFilter(kDEBUG2);
::testing::GTEST_FLAG(throw_on_failure) = true;
testing::InitGoogleTest(&argc, argv);
// return code 1 means the test failed.
// any other non-zero code is probably a memory error.
return RUN_ALL_TESTS();
}
| 1,587
|
C++
|
.cpp
| 46
| 32.282609
| 72
| 0.754742
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
13,682
|
ConfigTests.cpp
|
deskflow_deskflow/src/test/integtests/deskflow/ConfigTests.cpp
|
/*
* Deskflow -- mouse and keyboard sharing utility
* Copyright (C) 2024 Symless Ltd.
*
* This package is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* found in the file LICENSE that should have accompanied this file.
*
* This package is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "deskflow/Config.h"
#include <fstream>
#include <gtest/gtest.h>
using namespace deskflow;
const auto kTestFilename = "tmp/test/test.toml";
TEST(ConfigTests, load_fileExists_loadsConfig)
{
std::ofstream testFile(kTestFilename);
testFile << "[test.args]\n"
R"(test-arg = "test opt")";
testFile.close();
Config config(kTestFilename, "test");
const auto result = config.load("test");
ASSERT_TRUE(result);
ASSERT_EQ(config.argc(), 3);
ASSERT_STREQ(config.argv()[0], "test");
ASSERT_STREQ(config.argv()[1], "--test-arg");
ASSERT_STREQ(config.argv()[2], "test opt");
}
TEST(ConfigTests, load_filenameEmpty_throwsException)
{
EXPECT_THROW(
{
Config config("", "test");
config.load("test");
},
Config::NoConfigFilenameError
);
}
TEST(ConfigTests, load_fileDoesNotExist_returnsFalse)
{
Config config("nonexistent.toml", "test");
const auto result = config.load("test");
ASSERT_FALSE(result);
}
TEST(ConfigTests, load_invalidConfig_throwsException)
{
EXPECT_THROW(
{
std::ofstream testFile(kTestFilename);
testFile << "foobar";
testFile.close();
Config config(kTestFilename, "test");
config.load("test");
},
Config::ParseError
);
}
TEST(ConfigTests, load_sectionMissing_returnsFalse)
{
std::ofstream testFile(kTestFilename);
testFile.close();
Config config(kTestFilename, "missing");
const auto result = config.load("test");
ASSERT_FALSE(result);
}
TEST(ConfigTests, load_notTable_returnsFalse)
{
std::ofstream testFile(kTestFilename);
testFile << "[test]";
testFile.close();
Config config(kTestFilename, "test");
const auto result = config.load("test");
ASSERT_FALSE(result);
}
TEST(ConfigTests, load_lastArg_returnsLast)
{
std::ofstream testFile(kTestFilename);
testFile << "[test.args]\n"
R"(_last = "test last")"
"\n"
R"(test-second = true)";
testFile.close();
Config config(kTestFilename, "test");
const auto result = config.load("test-first");
ASSERT_TRUE(result);
ASSERT_EQ(config.argc(), 3);
ASSERT_STREQ(config.argv()[0], "test-first");
ASSERT_STREQ(config.argv()[1], "--test-second");
ASSERT_STREQ(config.argv()[2], "test last");
}
TEST(ConfigTests, load_noArgs_returnsFalse)
{
std::ofstream testFile(kTestFilename);
testFile << "[test.args]";
testFile.close();
Config config(kTestFilename, "test");
const auto result = config.load("");
ASSERT_FALSE(result);
}
| 3,218
|
C++
|
.cpp
| 106
| 26.735849
| 72
| 0.699514
|
deskflow/deskflow
| 10,364
| 3,653
| 93
|
GPL-2.0
|
9/20/2024, 9:26:25 PM (Europe/Amsterdam)
| false
| false
| false
| false
| false
| false
| false
| false
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.