23#include "sdl_context.hpp"
24#include "sdl_config.hpp"
25#include "sdl_channels.hpp"
26#include "sdl_monitor.hpp"
27#include "sdl_pointer.hpp"
28#include "sdl_touch.hpp"
30#include <sdl_common_utils.hpp>
31#include <scoped_guard.hpp>
33#include "dialogs/sdl_dialogs.hpp"
34#include <freerdp/client/aad_helper.h>
36static constexpr auto sdl_allow_screensaver =
"sdl-allow-screensaver";
38SdlContext::SdlContext(rdpContext* context)
39 : _context(context), _log(WLog_Get(CLIENT_TAG(
"SDL"))), _cursor(nullptr, sdl_Pointer_FreeCopy),
40 _rdpThreadRunning(false), _primary(nullptr, SDL_DestroySurface), _disp(this), _input(this),
41 _clip(this), _rail(this), _dialog(_log)
43 WINPR_ASSERT(context);
46 auto instance = _context->instance;
47 WINPR_ASSERT(instance);
49 instance->PreConnect = preConnect;
50 instance->PostConnect = postConnect;
51 instance->PostDisconnect = postDisconnect;
52 instance->PostFinalDisconnect = postFinalDisconnect;
53 instance->AuthenticateEx = sdl_authenticate_ex;
54 instance->VerifyCertificateEx = sdl_verify_certificate_ex;
55 instance->VerifyChangedCertificateEx = sdl_verify_changed_certificate_ex;
56 instance->LogonErrorInfo = sdl_logon_error_info;
57 instance->PresentGatewayMessage = sdl_present_gateway_message;
58 instance->ChooseSmartcard = sdl_choose_smartcard;
59 instance->RetryDialog = sdl_retry_dialog;
60 instance->GetAccessToken = client_failsafe_get_access_token;
64 _args.push_back({ sdl_allow_screensaver, COMMAND_LINE_VALUE_BOOL,
nullptr, BoolValueFalse,
65 nullptr, -1,
nullptr,
"Allow local screensaver to activate" });
68 _args.push_back({
nullptr, 0,
nullptr,
nullptr,
nullptr, -1,
nullptr,
nullptr });
71void SdlContext::setHasCursor(
bool val)
73 this->_cursor_visible = val;
76bool SdlContext::hasCursor()
const
78 return _cursor_visible;
81void SdlContext::setMetadata()
84 if (!wmclass || (strlen(wmclass) == 0))
85 wmclass = SDL_CLIENT_UUID;
87 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_IDENTIFIER_STRING, wmclass);
88 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_NAME_STRING, SDL_CLIENT_NAME);
89 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_VERSION_STRING, SDL_CLIENT_VERSION);
90 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_CREATOR_STRING, SDL_CLIENT_VENDOR);
91 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_COPYRIGHT_STRING, SDL_CLIENT_COPYRIGHT);
92 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_URL_STRING, SDL_CLIENT_URL);
93 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_TYPE_STRING, SDL_CLIENT_TYPE);
96int SdlContext::start()
98 _thread = std::thread(rdpThreadRun,
this);
102int SdlContext::join()
106 HANDLE
event = freerdp_abort_event(context());
107 if (!SetEvent(event))
114void SdlContext::cleanup()
116 std::unique_lock lock(_critical);
122bool SdlContext::shallAbort(
bool ignoreDialogs)
124 std::unique_lock lock(_critical);
125 if (freerdp_shall_disconnect_context(context()))
129 if (_rdpThreadRunning)
131 return !getDialog().isRunning();
138BOOL SdlContext::preConnect(freerdp* instance)
140 WINPR_ASSERT(instance);
141 WINPR_ASSERT(instance->context);
143 auto sdl = get_context(instance->context);
145 auto settings = instance->context->settings;
146 WINPR_ASSERT(settings);
161 if (PubSub_SubscribeChannelConnected(instance->context->pubSub,
162 sdl_OnChannelConnectedEventHandler) < 0)
164 if (PubSub_SubscribeChannelDisconnected(instance->context->pubSub,
165 sdl_OnChannelDisconnectedEventHandler) < 0)
167 if (PubSub_SubscribeUserNotification(instance->context->pubSub,
168 sdl_OnUserNotificationEventHandler) < 0)
174 UINT32 maxHeight = 0;
176 if (!sdl_detect_monitors(
sdl, &maxWidth, &maxHeight))
179 if ((maxWidth != 0) && (maxHeight != 0) &&
182 WLog_Print(
sdl->getWLog(), WLOG_INFO,
"Update size to %ux%u", maxWidth, maxHeight);
197 if (sm && (sw > 0) && (sh > 0))
201 WLog_Print(
sdl->getWLog(), WLOG_WARN,
202 "/smart-sizing and /multimon are currently not supported, ignoring "
221 WLog_Print(
sdl->getWLog(), WLOG_INFO,
222 "auth-only, but no password set. Please provide one.");
229 WLog_Print(
sdl->getWLog(), WLOG_INFO,
"Authentication only. Don't connect SDL.");
232 if (!
sdl->getInputChannelContext().initialize())
235 sdl->_credentialsRead =
false;
248BOOL SdlContext::postConnect(freerdp* instance)
250 WINPR_ASSERT(instance);
252 auto context = instance->context;
253 WINPR_ASSERT(context);
255 auto sdl = get_context(context);
258 sdl->getDialog().show(
false);
265 WLog_Print(
sdl->getWLog(), WLOG_INFO,
266 "auth-only, but no password set. Please provide one.");
270 WLog_Print(
sdl->getWLog(), WLOG_INFO,
"Authentication only. Don't connect to X.");
274 if (!
sdl->waitForWindowsCreated())
277 sdl->_sdlPixelFormat = SDL_PIXELFORMAT_BGRA32;
278 if (!gdi_init(instance, PIXEL_FORMAT_BGRA32))
281 if (!
sdl->createPrimary())
284 if (!sdl_register_pointer(instance->context->graphics))
287 WINPR_ASSERT(context->update);
289 context->update->BeginPaint = beginPaint;
290 context->update->EndPaint = endPaint;
291 context->update->PlaySound = playSound;
292 context->update->DesktopResize = desktopResize;
293 context->update->SetKeyboardIndicators = sdlInput::keyboard_set_indicators;
294 context->update->SetKeyboardImeStatus = sdlInput::keyboard_set_ime_status;
296 if (!
sdl->setResizeable(
false))
302 sdl->setConnected(
true);
309void SdlContext::postDisconnect(freerdp* instance)
314 if (!instance->context)
317 auto sdl = get_context(instance->context);
318 sdl->setConnected(
false);
323void SdlContext::postFinalDisconnect(freerdp* instance)
328 if (!instance->context)
331 PubSub_UnsubscribeChannelConnected(instance->context->pubSub,
332 sdl_OnChannelConnectedEventHandler);
333 PubSub_UnsubscribeChannelDisconnected(instance->context->pubSub,
334 sdl_OnChannelDisconnectedEventHandler);
335 PubSub_UnsubscribeUserNotification(instance->context->pubSub,
336 sdl_OnUserNotificationEventHandler);
340bool SdlContext::createPrimary()
342 auto gdi = context()->gdi;
345 _primary = SDLSurfacePtr(
346 SDL_CreateSurfaceFrom(
static_cast<int>(gdi->width),
static_cast<int>(gdi->height),
347 pixelFormat(), gdi->primary_buffer,
static_cast<int>(gdi->stride)),
352 SDL_SetSurfaceBlendMode(_primary.get(), SDL_BLENDMODE_NONE);
353 SDL_Rect surfaceRect = { 0, 0, gdi->width, gdi->height };
354 SDL_FillSurfaceRect(_primary.get(), &surfaceRect,
355 SDL_MapSurfaceRGBA(_primary.get(), 0, 0, 0, 0xff));
360bool SdlContext::createWindows()
362 auto settings = context()->settings;
363 const auto& title = windowTitle();
365 ScopeGuard guard1([&]() { _windowsCreatedEvent.set(); });
371 for (UINT32 x = 0; x < windowCount; x++)
373 auto id = monitorId(x);
378 freerdp_settings_get_pointer_array_writable(settings, FreeRDP_MonitorDefArray, x));
380 originX = std::min<Sint32>(monitor->x, originX);
381 originY = std::min<Sint32>(monitor->y, originY);
384 for (UINT32 x = 0; x < windowCount; x++)
386 auto id = monitorId(x);
391 freerdp_settings_get_pointer_array_writable(settings, FreeRDP_MonitorDefArray, x));
393 Uint32 w = WINPR_ASSERTING_INT_CAST(Uint32, monitor->width);
394 Uint32 h = WINPR_ASSERTING_INT_CAST(Uint32, monitor->height);
398 if (_windowWidth > 0)
403 if (_windowHeight > 0)
409 Uint32 flags = SDL_WINDOW_HIGH_PIXEL_DENSITY;
414 flags |= SDL_WINDOW_FULLSCREEN;
419 flags |= SDL_WINDOW_BORDERLESS;
423 flags |= SDL_WINDOW_BORDERLESS;
425 auto did = WINPR_ASSERTING_INT_CAST(SDL_DisplayID,
id);
426 auto window = SdlWindow::create(did, title, flags, w, h);
430 window.setOffsetX(originX - monitor->x);
431 window.setOffsetY(originY - monitor->y);
434 _windows.insert({ window.id(), std::move(window) });
440bool SdlContext::updateWindowList()
442 std::vector<rdpMonitor> list;
443 list.reserve(_windows.size());
444 for (
const auto& win : _windows)
445 list.push_back(win.second.monitor(_windows.size() == 1));
451 std::none_of(list.cbegin(), list.cend(), [](
const rdpMonitor& m) { return m.is_primary; }))
452 list.at(0).is_primary =
true;
458bool SdlContext::updateWindow(SDL_WindowID
id)
464 auto& w = _windows.at(
id);
465 auto m = w.monitor(
true);
469 m.attributes.physicalWidth =
static_cast<UINT32
>(r.w);
470 m.attributes.physicalHeight =
static_cast<UINT32
>(r.h);
475std::string SdlContext::windowTitle()
const
477 const char* prefix =
"FreeRDP:";
485 const auto addPort = (port != 3389);
487 std::stringstream ss;
488 ss << prefix <<
" " << name;
496bool SdlContext::waitForWindowsCreated()
499 std::unique_lock<CriticalSection> lock(_critical);
500 _windowsCreatedEvent.clear();
501 if (!sdl_push_user_event(SDL_EVENT_USER_CREATE_WINDOWS,
this))
505 HANDLE handles[] = { _windowsCreatedEvent.handle(), freerdp_abort_event(context()) };
507 const DWORD rc = WaitForMultipleObjects(ARRAYSIZE(handles), handles, FALSE, INFINITE);
521BOOL SdlContext::endPaint(rdpContext* context)
523 auto sdl = get_context(context);
526 auto gdi = context->gdi;
528 WINPR_ASSERT(gdi->primary);
530 HGDI_DC hdc = gdi->primary->hdc;
536 WINPR_ASSERT(hwnd->invalid || (hwnd->ninvalid == 0));
538 if (hwnd->invalid->null)
541 WINPR_ASSERT(hwnd->invalid);
542 if (gdi->suppressOutput || hwnd->invalid->null)
545 const INT32 ninvalid = hwnd->ninvalid;
546 const GDI_RGN* cinvalid = hwnd->cinvalid;
551 std::vector<SDL_Rect> rects;
552 for (INT32 x = 0; x < ninvalid; x++)
554 auto& rgn = cinvalid[x];
555 rects.push_back({ rgn.x, rgn.y, rgn.w, rgn.h });
558 sdl->push(std::move(rects));
559 return sdl_push_user_event(SDL_EVENT_USER_UPDATE);
562void SdlContext::sdl_client_cleanup(
int exit_code,
const std::string& error_msg)
564 rdpSettings* settings = context()->settings;
565 WINPR_ASSERT(settings);
567 _rdpThreadRunning =
false;
568 bool showError =
false;
570 WLog_Print(getWLog(), WLOG_INFO,
"Authentication only, exit status %s [%" PRId32
"]",
571 sdl::error::exitCodeToTag(exit_code), exit_code);
576 case sdl::error::SUCCESS:
577 case sdl::error::DISCONNECT:
578 case sdl::error::LOGOFF:
579 case sdl::error::DISCONNECT_BY_USER:
580 case sdl::error::CONNECT_CANCELLED:
584 getDialog().showError(error_msg);
591 getDialog().show(
false);
593 _exitCode = exit_code;
594 std::ignore = sdl_push_user_event(SDL_EVENT_USER_QUIT);
598int SdlContext::sdl_client_thread_connect(std::string& error_msg)
600 auto instance = context()->instance;
601 WINPR_ASSERT(instance);
603 _rdpThreadRunning =
true;
604 BOOL rc = freerdp_connect(instance);
606 rdpSettings* settings = context()->settings;
607 WINPR_ASSERT(settings);
609 int exit_code = sdl::error::SUCCESS;
612 UINT32 error = freerdp_get_last_error(context());
613 exit_code = sdl::error::errorToExitCode(error);
618 DWORD code = freerdp_get_last_error(context());
619 freerdp_abort_connect_context(context());
620 WLog_Print(getWLog(), WLOG_ERROR,
"Authentication only, %s [0x%08" PRIx32
"] %s",
621 freerdp_get_last_error_name(code), code, freerdp_get_last_error_string(code));
627 DWORD code = freerdp_error_info(instance);
628 if (exit_code == sdl::error::SUCCESS)
632 exit_code = error_info_to_error(&code, &msg, &len);
638 auto last = freerdp_get_last_error(context());
639 if (error_msg.empty())
643 winpr_asprintf(&msg, &len,
"%s [0x%08" PRIx32
"]\n%s",
644 freerdp_get_last_error_name(last), last,
645 freerdp_get_last_error_string(last));
651 if (exit_code == sdl::error::SUCCESS)
653 if (last == FREERDP_ERROR_AUTHENTICATION_FAILED)
654 exit_code = sdl::error::AUTH_FAILURE;
655 else if (code == ERRINFO_SUCCESS)
656 exit_code = sdl::error::CONN_FAILED;
659 getDialog().show(
false);
665int SdlContext::sdl_client_thread_run(std::string& error_msg)
667 auto instance = context()->instance;
668 WINPR_ASSERT(instance);
670 int exit_code = sdl::error::SUCCESS;
671 while (!freerdp_shall_disconnect_context(context()))
673 HANDLE handles[MAXIMUM_WAIT_OBJECTS] = {};
679 if (freerdp_focus_required(instance))
681 auto ctx = get_context(context());
684 auto& input = ctx->getInputChannelContext();
685 if (!input.keyboard_focus_in())
687 if (!input.keyboard_focus_in())
691 const DWORD nCount = freerdp_get_event_handles(context(), handles, ARRAYSIZE(handles));
695 WLog_Print(getWLog(), WLOG_ERROR,
"freerdp_get_event_handles failed");
699 const DWORD status = WaitForMultipleObjects(nCount, handles, FALSE, INFINITE);
701 if (status == WAIT_FAILED)
703 WLog_Print(getWLog(), WLOG_ERROR,
"WaitForMultipleObjects WAIT_FAILED");
707 if (!freerdp_check_event_handles(context()))
709 if (client_auto_reconnect(instance))
712 getDialog().show(
false);
721 if (freerdp_error_info(instance) == 0)
722 exit_code = sdl::error::CONN_FAILED;
725 if (freerdp_get_last_error(context()) == FREERDP_ERROR_SUCCESS)
726 WLog_Print(getWLog(), WLOG_ERROR,
"WaitForMultipleObjects failed with %" PRIu32
"",
728 if (freerdp_get_last_error(context()) == FREERDP_ERROR_SUCCESS)
729 WLog_Print(getWLog(), WLOG_ERROR,
"Failed to check FreeRDP event handles");
734 if (exit_code == sdl::error::SUCCESS)
738 char* emsg =
nullptr;
740 exit_code = error_info_to_error(&code, &emsg, &elen);
746 if ((code == ERRINFO_LOGOFF_BY_USER) &&
747 (freerdp_get_disconnect_ultimatum(context()) == Disconnect_Ultimatum_user_requested))
749 const char* msg =
"Error info says user did not initiate but disconnect ultimatum says "
750 "they did; treat this as a user logoff";
752 char* emsg =
nullptr;
754 winpr_asprintf(&emsg, &elen,
"%s", msg);
760 WLog_Print(getWLog(), WLOG_INFO,
"%s", msg);
761 exit_code = sdl::error::LOGOFF;
765 freerdp_disconnect(instance);
777 std::string error_msg;
778 int exit_code =
sdl->sdl_client_thread_connect(error_msg);
779 if (exit_code == sdl::error::SUCCESS)
780 exit_code =
sdl->sdl_client_thread_run(error_msg);
781 sdl->sdl_client_cleanup(exit_code, error_msg);
783 return static_cast<DWORD
>(exit_code);
786int SdlContext::error_info_to_error(DWORD* pcode,
char** msg,
size_t* len)
const
788 const DWORD code = freerdp_error_info(context()->instance);
789 const char* name = freerdp_get_error_info_name(code);
790 const char* str = freerdp_get_error_info_string(code);
791 const int exit_code = sdl::error::errorToExitCode(code);
793 winpr_asprintf(msg, len,
"Terminate with %s due to ERROR_INFO %s [0x%08" PRIx32
"]: %s",
794 sdl::error::errorToExitCodeTag(code), name, code, str);
795 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"%s", *msg);
801void SdlContext::applyMonitorOffset(SDL_WindowID window,
float& x,
float& y)
const
806 auto w = getWindowForId(window);
807 x -=
static_cast<float>(w->offsetX());
808 y -=
static_cast<float>(w->offsetY());
811static bool alignX(
const SDL_Rect& a,
const SDL_Rect& b)
813 if (a.x + a.w == b.x)
815 if (b.x + b.w == a.x)
820static bool alignY(
const SDL_Rect& a,
const SDL_Rect& b)
822 if (a.y + a.h == b.y)
824 if (b.y + b.h == a.y)
829std::vector<SDL_DisplayID>
830SdlContext::updateDisplayOffsetsForNeighbours(SDL_DisplayID
id,
831 const std::vector<SDL_DisplayID>& ignore)
833 auto first = _offsets.at(
id);
834 std::vector<SDL_DisplayID> neighbours;
836 for (
auto& entry : _offsets)
838 if (entry.first ==
id)
840 if (std::find(ignore.begin(), ignore.end(), entry.first) != ignore.end())
843 bool neighbor =
false;
844 const bool ax = alignX(entry.second.first, first.first);
845 const bool ay = alignY(entry.second.first, first.first);
853 auto crossOffset = [](
int ePos,
int fPos,
int fLogical,
int fPixel) ->
int
857 return static_cast<int>(
858 std::lround(
static_cast<double>(ePos - fPos) * fPixel / fLogical));
863 if (entry.second.first.x < first.first.x)
864 entry.second.second.x = first.second.x - entry.second.second.w;
866 entry.second.second.x = first.second.x + first.second.w;
868 entry.second.second.y =
870 crossOffset(entry.second.first.y, first.first.y, first.first.h, first.second.h);
875 if (entry.second.first.y < first.first.y)
876 entry.second.second.y = first.second.y - entry.second.second.h;
878 entry.second.second.y = first.second.y + first.second.h;
880 entry.second.second.x =
882 crossOffset(entry.second.first.x, first.first.x, first.first.w, first.second.w);
887 neighbours.push_back(entry.first);
892void SdlContext::updateMonitorDataFromOffsets()
894 for (
auto& entry : _displays)
896 auto offsets = _offsets.at(entry.first);
897 entry.second.x = offsets.second.x;
898 entry.second.y = offsets.second.y;
901 for (
auto& entry : _windows)
903 const auto& monitor = _displays.at(entry.first);
904 entry.second.setMonitor(monitor);
908bool SdlContext::drawToWindow(
SdlWindow& window,
const std::vector<SDL_Rect>& rects)
913 auto gdi = context()->gdi;
916 auto size = window.rect();
918 std::unique_lock lock(_critical);
919 auto surface = _primary.get();
923 window.setOffsetX(0);
924 window.setOffsetY(0);
925 if (gdi->width < size.w)
927 window.setOffsetX((size.w - gdi->width) / 2);
929 if (gdi->height < size.h)
931 window.setOffsetY((size.h - gdi->height) / 2);
934 _localScale = {
static_cast<float>(size.w) /
static_cast<float>(gdi->width),
935 static_cast<float>(size.h) /
static_cast<float>(gdi->height) };
936 if (!window.drawScaledRects(surface, _localScale, rects))
941 SDL_Point offset{ 0, 0 };
943 offset = { window.offsetX(), window.offsetY() };
944 if (!window.drawRects(surface, offset, rects))
948 window.updateSurface();
952bool SdlContext::minimizeAllWindows()
954 for (
auto& w : _windows)
959int SdlContext::exitCode()
const
964SDL_PixelFormat SdlContext::pixelFormat()
const
966 return _sdlPixelFormat;
969bool SdlContext::addDisplayWindow(SDL_DisplayID
id)
972 SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS;
973 auto title = sdl::utils::windowTitle(context()->settings);
974 auto w = SdlWindow::create(
id, title, flags);
975 _windows.emplace(w.id(), std::move(w));
979bool SdlContext::removeDisplayWindow(SDL_DisplayID
id)
981 for (
auto& w : _windows)
983 if (w.second.displayIndex() ==
id)
984 _windows.erase(w.first);
989bool SdlContext::detectDisplays()
992 auto display = SDL_GetDisplays(&count);
995 for (
int x = 0; x < count; x++)
997 const auto id = display[x];
998 addOrUpdateDisplay(
id);
1004rdpMonitor SdlContext::getDisplay(SDL_DisplayID
id)
const
1006 return _displays.at(
id);
1009std::vector<SDL_DisplayID> SdlContext::getDisplayIds()
const
1011 std::vector<SDL_DisplayID> keys;
1012 keys.reserve(_displays.size());
1013 for (
const auto& entry : _displays)
1015 keys.push_back(entry.first);
1020const SdlWindow* SdlContext::getWindowForId(SDL_WindowID
id)
const
1022 auto it = _windows.find(
id);
1023 if (it == _windows.end())
1028SdlWindow* SdlContext::getWindowForId(SDL_WindowID
id)
1030 auto it = _windows.find(
id);
1031 if (it == _windows.end())
1038 if (_windows.empty())
1040 return &_windows.begin()->second;
1048sdlInput& SdlContext::getInputChannelContext()
1053sdlClip& SdlContext::getClipboardChannelContext()
1058SdlRail& SdlContext::getRailChannelContext()
1068wLog* SdlContext::getWLog()
1073bool SdlContext::moveMouseTo(
const SDL_FPoint& pos)
1075 auto window = SDL_GetMouseFocus();
1079 const auto id = SDL_GetWindowID(window);
1080 const auto spos = pixelToScreen(
id, pos);
1081 SDL_WarpMouseInWindow(window, spos.x, spos.y);
1085bool SdlContext::handleEvent(
const SDL_MouseMotionEvent& ev)
1090 if (_rail.enabled() && _rail.suppressServerMotion(ev.windowID))
1092 if (!(SDL_GetGlobalMouseState(
nullptr,
nullptr) & SDL_BUTTON_LMASK))
1093 _rail.completeLocalMoveIfPending();
1096 if (_rail.enabled() && _rail.translateToServer(ev.windowID, copy.motion.x, copy.motion.y))
1098 _rail.noteServerPointer(copy.motion.x, copy.motion.y);
1099 return SdlTouch::handleEvent(
this, copy.motion);
1102 if (!getWindowForId(ev.windowID))
1104 if (!eventToPixelCoordinates(ev.windowID, copy))
1106 removeLocalScaling(copy.motion.x, copy.motion.y);
1107 removeLocalScaling(copy.motion.xrel, copy.motion.yrel);
1108 applyMonitorOffset(copy.motion.windowID, copy.motion.x, copy.motion.y);
1110 return SdlTouch::handleEvent(
this, copy.motion);
1113bool SdlContext::handleEvent(
const SDL_MouseWheelEvent& ev)
1117 if (_rail.enabled() &&
1118 _rail.translateToServer(ev.windowID, copy.wheel.mouse_x, copy.wheel.mouse_y))
1119 return SdlTouch::handleEvent(
this, copy.wheel);
1121 if (!getWindowForId(ev.windowID))
1123 if (!eventToPixelCoordinates(ev.windowID, copy))
1125 removeLocalScaling(copy.wheel.mouse_x, copy.wheel.mouse_y);
1126 return SdlTouch::handleEvent(
this, copy.wheel);
1129bool SdlContext::handleEvent(
const SDL_WindowEvent& ev)
1131 if (!getDisplayChannelContext().handleEvent(ev))
1134 auto window = getWindowForId(ev.windowID);
1138 if (_rail.enabled() && _rail.ownsWindow(ev.windowID))
1142 case SDL_EVENT_WINDOW_MOUSE_ENTER:
1144 if (!(SDL_GetGlobalMouseState(
nullptr,
nullptr) & SDL_BUTTON_LMASK))
1145 _rail.completeLocalMoveIfPending();
1146 _rail.completeWaylandResize();
1148 return restoreCursor();
1149 case SDL_EVENT_WINDOW_MOUSE_LEAVE:
1151 _rail.noteResizeGrab(ev.windowID);
1153 case SDL_EVENT_WINDOW_EXPOSED:
1156 if (!_rail.suppressServerInput(ev.windowID))
1157 _rail.invalidateWindow(ev.windowID);
1159 case SDL_EVENT_WINDOW_MAXIMIZED:
1161 _rail.completeLocalMoveIfPending();
1162 _rail.handleMaximized(ev.windowID);
1164 case SDL_EVENT_WINDOW_MINIMIZED:
1165 _rail.handleMinimized(ev.windowID);
1167 case SDL_EVENT_WINDOW_RESTORED:
1168 _rail.handleRestored(ev.windowID);
1170 case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
1172 _rail.handleClose(ev.windowID);
1174 case SDL_EVENT_WINDOW_FOCUS_GAINED:
1175 _rail.handleFocus(ev.windowID,
true);
1177 case SDL_EVENT_WINDOW_FOCUS_LOST:
1178 _rail.handleFocus(ev.windowID,
false);
1180 case SDL_EVENT_WINDOW_MOVED:
1181 if (!_rail.suppressServerInput(ev.windowID))
1182 _rail.syncGeometry(ev.windowID);
1184 case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
1187 _rail.noteDragResize(ev.windowID, ev.data1, ev.data2);
1188 _rail.syncGeometry(ev.windowID);
1189 _rail.handleWaylandResize(ev.windowID);
1190 std::ignore = drawToWindows({});
1200 const auto& r = window->rect();
1201 const auto& b = window->bounds();
1202 const auto& scale = window->scale();
1203 const auto& orientation = window->orientation();
1204 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
1205 "%s: [%u] %dx%d-%dx%d {%dx%d-%dx%d}{scale=%f,orientation=%s}",
1206 sdl::utils::toString(ev.type).c_str(), ev.windowID, r.x, r.y, r.w, r.h, b.x,
1207 b.y, b.w, b.h,
static_cast<double>(scale),
1208 sdl::utils::toString(orientation).c_str());
1213 case SDL_EVENT_WINDOW_MOUSE_ENTER:
1214 return restoreCursor();
1215 case SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED:
1216 if (!resizeToScale(window))
1220 if (!window->fill())
1222 if (!drawToWindow(*window))
1224 if (!restoreCursor())
1228 case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
1229 if (!resizeToScale(window))
1231 if (!window->fill())
1233 if (!drawToWindow(*window))
1235 if (!restoreCursor())
1238 case SDL_EVENT_WINDOW_MOVED:
1240 auto r = window->rect();
1241 auto id = window->id();
1242 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"%u: %dx%d-%dx%d",
id, r.x, r.y, r.w, r.h);
1245 case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
1247 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"Window closed, terminating RDP session...");
1248 freerdp_abort_connect_context(context());
1257bool SdlContext::handleEvent(
const SDL_DisplayEvent& ev)
1259 if (!getDisplayChannelContext().handleEvent(ev))
1264 case SDL_EVENT_DISPLAY_REMOVED:
1269 if (!SDL_GetDisplayBounds(ev.displayID, &r))
1271 const auto name = SDL_GetDisplayName(ev.displayID);
1274 const auto orientation = SDL_GetCurrentDisplayOrientation(ev.displayID);
1275 const auto scale = SDL_GetDisplayContentScale(ev.displayID);
1276 const auto mode = SDL_GetCurrentDisplayMode(ev.displayID);
1280 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
1281 "%s: [%u, %s] %dx%d-%dx%d {orientation=%s, scale=%f}%s",
1282 sdl::utils::toString(ev.type).c_str(), ev.displayID, name, r.x, r.y, r.w,
1283 r.h, sdl::utils::toString(orientation).c_str(),
static_cast<double>(scale),
1284 sdl::utils::toString(mode).c_str());
1291bool SdlContext::handleEvent(
const SDL_MouseButtonEvent& ev)
1293 SDL_Event copy = {};
1295 if (_rail.enabled())
1298 const bool suppress = _rail.suppressServerInput(ev.windowID);
1299 if (ev.type == SDL_EVENT_MOUSE_BUTTON_UP)
1300 _rail.completeLocalMoveIfPending();
1303 if (ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN)
1304 _rail.completeWaylandResize(
true);
1306 if (ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN)
1307 _rail.ensureActive(ev.windowID);
1310 if (_rail.translateToServer(ev.windowID, copy.button.x, copy.button.y))
1314 if ((ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN) && (ev.button == SDL_BUTTON_LEFT))
1315 _rail.noteLeftPress(copy.button.x, copy.button.y);
1316 return SdlTouch::handleEvent(
this, copy.button);
1320 if (!getWindowForId(ev.windowID))
1322 if (!eventToPixelCoordinates(ev.windowID, copy))
1324 removeLocalScaling(copy.button.x, copy.button.y);
1325 applyMonitorOffset(copy.button.windowID, copy.button.x, copy.button.y);
1326 return SdlTouch::handleEvent(
this, copy.button);
1329bool SdlContext::handleEvent(
const SDL_TouchFingerEvent& ev)
1331 if (!getWindowForId(ev.windowID))
1335 if (!eventToPixelCoordinates(ev.windowID, copy))
1337 removeLocalScaling(copy.tfinger.dx, copy.tfinger.dy);
1338 removeLocalScaling(copy.tfinger.x, copy.tfinger.y);
1339 applyMonitorOffset(copy.tfinger.windowID, copy.tfinger.x, copy.tfinger.y);
1340 return SdlTouch::handleEvent(
this, copy.tfinger);
1343void SdlContext::addOrUpdateDisplay(SDL_DisplayID
id)
1345 auto monitor = SdlWindow::query(
id,
false);
1346 _displays.emplace(
id, monitor);
1356 for (
auto& entry : _displays)
1359 std::ignore = SDL_GetDisplayBounds(entry.first, &bounds);
1362 pixel.w = entry.second.width;
1363 pixel.h = entry.second.height;
1364 _offsets.emplace(entry.first, std::pair{ bounds, pixel });
1371 const auto primary = SDL_GetPrimaryDisplay();
1372 std::vector<SDL_DisplayID> handled;
1373 handled.push_back(primary);
1375 auto neighbors = updateDisplayOffsetsForNeighbours(primary);
1376 while (!neighbors.empty())
1378 auto neighbor = neighbors.front();
1379 neighbors.erase(neighbors.begin());
1381 if (std::find(handled.begin(), handled.end(), neighbor) != handled.end())
1383 handled.push_back(neighbor);
1385 auto next = updateDisplayOffsetsForNeighbours(neighbor, handled);
1386 neighbors.insert(neighbors.end(), next.begin(), next.end());
1388 updateMonitorDataFromOffsets();
1391void SdlContext::deleteDisplay(SDL_DisplayID
id)
1393 _displays.erase(
id);
1396bool SdlContext::eventToPixelCoordinates(SDL_WindowID
id, SDL_Event& ev)
1398 auto w = getWindowForId(
id);
1403 auto renderer = w->renderer();
1406 return SDL_ConvertEventToRenderCoordinates(renderer, &ev);
1409SDL_FPoint SdlContext::applyLocalScaling(
const SDL_FPoint& val)
const
1411 if (!useLocalScale())
1415 rval.x *= _localScale.x;
1416 rval.y *= _localScale.y;
1420void SdlContext::removeLocalScaling(
float& x,
float& y)
const
1422 if (!useLocalScale())
1428SDL_FPoint SdlContext::screenToPixel(SDL_WindowID
id,
const SDL_FPoint& pos)
1430 auto w = getWindowForId(
id);
1434 if (_rail.enabled() && _rail.ownsWindow(
id))
1440 auto renderer = w->renderer();
1445 if (!SDL_RenderCoordinatesFromWindow(renderer, pos.x, pos.y, &rpos.x, &rpos.y))
1447 removeLocalScaling(rpos.x, rpos.y);
1451SDL_FPoint SdlContext::pixelToScreen(SDL_WindowID
id,
const SDL_FPoint& pos)
1453 auto w = getWindowForId(
id);
1456 if (_rail.enabled() && _rail.ownsWindow(
id))
1462 auto renderer = w->renderer();
1467 if (!SDL_RenderCoordinatesToWindow(renderer, pos.x, pos.y, &rpos.x, &rpos.y))
1469 return applyLocalScaling(rpos);
1472SDL_FRect SdlContext::pixelToScreen(SDL_WindowID
id,
const SDL_FRect& pos,
bool round)
1474 const auto fpos = pixelToScreen(
id, SDL_FPoint{ pos.x, pos.y });
1475 const auto size = pixelToScreen(
id, SDL_FPoint{ pos.w, pos.h });
1476 SDL_FRect r{ fpos.x, fpos.y, size.x, size.y };
1479 r.w = std::ceil(r.w);
1480 r.h = std::ceil(r.h);
1481 r.x = std::floor(r.x);
1482 r.y = std::floor(r.y);
1487bool SdlContext::handleEvent(
const SDL_Event& ev)
1489 if ((ev.type >= SDL_EVENT_DISPLAY_FIRST) && (ev.type <= SDL_EVENT_DISPLAY_LAST))
1491 const auto& dev = ev.display;
1492 return handleEvent(dev);
1494 if ((ev.type >= SDL_EVENT_WINDOW_FIRST) && (ev.type <= SDL_EVENT_WINDOW_LAST))
1496 const auto& wev = ev.window;
1497 return handleEvent(wev);
1501 case SDL_EVENT_RENDER_TARGETS_RESET:
1502 case SDL_EVENT_RENDER_DEVICE_RESET:
1503 case SDL_EVENT_WILL_ENTER_FOREGROUND:
1514 case SDL_EVENT_FINGER_DOWN:
1515 case SDL_EVENT_FINGER_UP:
1516 case SDL_EVENT_FINGER_MOTION:
1518 const auto& cev = ev.tfinger;
1519 return handleEvent(cev);
1521 case SDL_EVENT_MOUSE_MOTION:
1524 const auto& cev = ev.motion;
1525 return handleEvent(cev);
1527 case SDL_EVENT_MOUSE_BUTTON_DOWN:
1528 case SDL_EVENT_MOUSE_BUTTON_UP:
1530 const auto& cev = ev.button;
1531 return handleEvent(cev);
1533 case SDL_EVENT_MOUSE_WHEEL:
1535 const auto& cev = ev.wheel;
1536 return handleEvent(cev);
1538 case SDL_EVENT_CLIPBOARD_UPDATE:
1540 const auto& cev = ev.clipboard;
1541 return getClipboardChannelContext().handleEvent(cev);
1543 case SDL_EVENT_KEY_DOWN:
1544 case SDL_EVENT_KEY_UP:
1546 const auto& cev = ev.key;
1547 return getInputChannelContext().handleEvent(cev);
1556 return _args.data();
1559size_t SdlContext::argsCount()
const
1561 if (_args.size() <= 1)
1563 return _args.size() - 1;
1574 if (strcmp(arg->Name, sdl_allow_screensaver) == 0)
1576 if (arg->Value !=
nullptr)
1578 if (!SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER,
"1"))
1580 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
1581 "SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER) failed with %s",
1596std::vector<rdpPointer*>& SdlContext::pointers()
1598 return _valid_pointers;
1601bool SdlContext::contains(
const rdpPointer* ptr)
const
1603 for (
const auto& cur : _valid_pointers)
1611bool SdlContext::credentialsRead()
const
1613 return _credentialsRead;
1616void SdlContext::setCredentialsRead()
1618 _credentialsRead =
true;
1621bool SdlContext::resizeToScale(
SdlWindow* window)
1625 if (!useLocalScale())
1629 return window->resizeToScale();
1632bool SdlContext::useLocalScale()
const
1637 const auto dynResize =
1641 return !dynResize && !fs && !multimon;
1644bool SdlContext::drawToWindows(
const std::vector<SDL_Rect>& rects)
1647 if (_rail.enabled())
1649 for (
auto& window : _windows)
1651 if ((SDL_GetWindowFlags(window.second.window()) & SDL_WINDOW_HIDDEN) == 0)
1652 SDL_HideWindow(window.second.window());
1655 std::unique_lock lock(_critical);
1656 _rail.paint(_primary.get(), pixelFormat(), rects);
1662 bool firstShow =
false;
1663 for (
auto& window : _windows)
1665 if (SDL_GetWindowFlags(window.second.window()) & SDL_WINDOW_HIDDEN)
1667 SDL_ShowWindow(window.second.window());
1668 SDL_RaiseWindow(window.second.window());
1673 if (rects.empty() && !firstShow)
1676 std::vector<SDL_Rect> drawRects = rects;
1678 std::unique_lock lock(_critical);
1679 if ((drawRects.empty() || firstShow) && _primary)
1680 drawRects = { { 0, 0, _primary->w, _primary->h } };
1683 for (
auto& window : _windows)
1685 if (!drawToWindow(window.second, drawRects))
1692BOOL SdlContext::desktopResize(rdpContext* context)
1694 rdpGdi* gdi =
nullptr;
1695 rdpSettings* settings =
nullptr;
1696 auto sdl = get_context(context);
1699 WINPR_ASSERT(context);
1701 settings = context->settings;
1702 WINPR_ASSERT(settings);
1704 std::unique_lock lock(
sdl->_critical);
1709 return sdl->createPrimary();
1713BOOL SdlContext::playSound(rdpContext* context,
const PLAY_SOUND_UPDATE* play_sound)
1716 WINPR_UNUSED(context);
1717 WINPR_UNUSED(play_sound);
1723BOOL SdlContext::beginPaint(rdpContext* context)
1725 auto gdi = context->gdi;
1727 WINPR_ASSERT(gdi->primary);
1729 HGDI_DC hdc = gdi->primary->hdc;
1735 WINPR_ASSERT(hwnd->invalid);
1736 hwnd->invalid->null = TRUE;
1742bool SdlContext::redraw(
bool suppress)
const
1748 if (suppress && _rail.enabled())
1751 auto gdi = context()->gdi;
1753 return gdi_send_suppress_output(gdi, suppress);
1756void SdlContext::setConnected(
bool val)
1761bool SdlContext::isConnected()
const
1766rdpContext* SdlContext::context()
const
1768 WINPR_ASSERT(_context);
1772rdpClientContext* SdlContext::common()
const
1774 return reinterpret_cast<rdpClientContext*
>(context());
1777bool SdlContext::setCursor(CursorType type)
1780 return restoreCursor();
1783bool SdlContext::setCursor(
const rdpPointer* cursor)
1785 std::unique_lock lock(_critical);
1786 if (!contains(cursor))
1789 _cursor = { sdl_Pointer_Copy(cursor), sdl_PointerFreeCopyAll };
1790 return setCursor(CURSOR_IMAGE);
1793rdpPointer* SdlContext::cursor()
const
1795 return _cursor.get();
1798bool SdlContext::restoreCursor()
1800 WLog_Print(getWLog(), WLOG_TRACE,
"restore cursor: %d", _cursorType);
1801 switch (_cursorType)
1804 if (!SDL_HideCursor())
1806 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_HideCursor failed");
1810 setHasCursor(
false);
1813 case CURSOR_DEFAULT:
1815 auto def = SDL_GetDefaultCursor();
1816 if (!SDL_SetCursor(def))
1818 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_SetCursor(default=%p) failed",
1819 static_cast<void*
>(def));
1822 if (!SDL_ShowCursor())
1824 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_ShowCursor failed");
1832 return sdl_Pointer_Set_Process(
this);
1834 WLog_Print(getWLog(), WLOG_ERROR,
"Unknown cursorType %s",
1835 sdl::utils::toString(_cursorType).c_str());
1840void SdlContext::setMonitorIds(
const std::vector<SDL_DisplayID>& ids)
1842 _monitorIds.clear();
1845 _monitorIds.push_back(
id);
1849const std::vector<SDL_DisplayID>& SdlContext::monitorIds()
const
1854int64_t SdlContext::monitorId(uint32_t index)
const
1856 if (index >= _monitorIds.size())
1860 return _monitorIds.at(index);
1863void SdlContext::push(std::vector<SDL_Rect>&& rects)
1865 std::unique_lock lock(_queue_mux);
1866 _queue.emplace(std::move(rects));
1869std::vector<SDL_Rect> SdlContext::pop()
1871 std::unique_lock lock(_queue_mux);
1876 auto val = std::move(_queue.front());
1881bool SdlContext::setFullscreen(
bool enter,
bool forceOriginalDisplay)
1883 for (
const auto& window : _windows)
1885 if (!sdl_push_user_event(SDL_EVENT_USER_WINDOW_FULLSCREEN, &window.second, enter,
1886 forceOriginalDisplay))
1889 _fullscreen = enter;
1893bool SdlContext::setMinimized()
1895 return sdl_push_user_event(SDL_EVENT_USER_WINDOW_MINIMIZE);
1898bool SdlContext::grabMouse()
const
1903bool SdlContext::toggleGrabMouse()
1905 return setGrabMouse(!grabMouse());
1908bool SdlContext::setGrabMouse(
bool enter)
1914bool SdlContext::grabKeyboard()
const
1916 return _grabKeyboard;
1919bool SdlContext::toggleGrabKeyboard()
1921 return setGrabKeyboard(!grabKeyboard());
1924bool SdlContext::setGrabKeyboard(
bool enter)
1926 _grabKeyboard = enter;
1930bool SdlContext::setResizeable(
bool enable)
1932 const auto settings = context()->settings;
1935 bool use = (dyn && enable) || smart;
1937 for (
const auto& window : _windows)
1939 if (!sdl_push_user_event(SDL_EVENT_USER_WINDOW_RESIZEABLE, &window.second, use))
1947bool SdlContext::resizeable()
const
1952bool SdlContext::toggleResizeable()
1954 return setResizeable(!resizeable());
1957bool SdlContext::fullscreen()
const
1962bool SdlContext::toggleFullscreen()
1964 return setFullscreen(!fullscreen());
object that handles clipboard context for the SDL3 client
WINPR_ATTR_NODISCARD FREERDP_API const char * freerdp_settings_get_server_name(const rdpSettings *settings)
A helper function to return the correct server name.
WINPR_ATTR_NODISCARD FREERDP_API const char * freerdp_settings_get_string(const rdpSettings *settings, FreeRDP_Settings_Keys_String id)
Returns a immutable string settings value.
WINPR_ATTR_NODISCARD FREERDP_API BOOL freerdp_settings_set_bool(rdpSettings *settings, FreeRDP_Settings_Keys_Bool id, BOOL val)
Sets a BOOL settings value.
WINPR_ATTR_NODISCARD FREERDP_API BOOL freerdp_settings_set_uint32(rdpSettings *settings, FreeRDP_Settings_Keys_UInt32 id, UINT32 val)
Sets a UINT32 settings value.
WINPR_ATTR_NODISCARD FREERDP_API UINT32 freerdp_settings_get_uint32(const rdpSettings *settings, FreeRDP_Settings_Keys_UInt32 id)
Returns a UINT32 settings value.
WINPR_ATTR_NODISCARD FREERDP_API BOOL freerdp_settings_set_monitor_def_array_sorted(rdpSettings *settings, const rdpMonitor *monitors, size_t count)
Sort monitor array according to:
WINPR_ATTR_NODISCARD FREERDP_API BOOL freerdp_settings_get_bool(const rdpSettings *settings, FreeRDP_Settings_Keys_Bool id)
Returns a boolean settings value.