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"
35#if defined(WITH_WEBVIEW)
36#include <aad/sdl_webview.hpp>
39static constexpr auto sdl_allow_screensaver =
"sdl-allow-screensaver";
41static void sdl_PointerFreeCopyAll(rdpPointer* pointer)
43 sdl_Pointer_FreeCopy(pointer);
47SdlContext::SdlContext(rdpContext* context)
48 : _context(context), _log(WLog_Get(CLIENT_TAG(
"SDL"))), _cursor(nullptr, sdl_Pointer_FreeCopy),
49 _rdpThreadRunning(false), _primary(nullptr, SDL_DestroySurface), _disp(this), _input(this),
50 _clip(this), _dialog(_log)
52 WINPR_ASSERT(context);
55 auto instance = _context->instance;
56 WINPR_ASSERT(instance);
58 instance->PreConnect = preConnect;
59 instance->PostConnect = postConnect;
60 instance->PostDisconnect = postDisconnect;
61 instance->PostFinalDisconnect = postFinalDisconnect;
62 instance->AuthenticateEx = sdl_authenticate_ex;
63 instance->VerifyCertificateEx = sdl_verify_certificate_ex;
64 instance->VerifyChangedCertificateEx = sdl_verify_changed_certificate_ex;
65 instance->LogonErrorInfo = sdl_logon_error_info;
66 instance->PresentGatewayMessage = sdl_present_gateway_message;
67 instance->ChooseSmartcard = sdl_choose_smartcard;
68 instance->RetryDialog = sdl_retry_dialog;
71 instance->GetAccessToken = sdl_webview_get_access_token;
73 instance->GetAccessToken = client_cli_get_access_token;
77 _args.push_back({ sdl_allow_screensaver, COMMAND_LINE_VALUE_BOOL,
nullptr, BoolValueFalse,
78 nullptr, -1,
nullptr,
"Allow local screensaver to activate" });
81 _args.push_back({
nullptr, 0,
nullptr,
nullptr,
nullptr, -1,
nullptr,
nullptr });
84void SdlContext::setHasCursor(
bool val)
86 this->_cursor_visible = val;
89bool SdlContext::hasCursor()
const
91 return _cursor_visible;
94void SdlContext::setMetadata()
97 if (!wmclass || (strlen(wmclass) == 0))
98 wmclass = SDL_CLIENT_UUID;
100 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_IDENTIFIER_STRING, wmclass);
101 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_NAME_STRING, SDL_CLIENT_NAME);
102 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_VERSION_STRING, SDL_CLIENT_VERSION);
103 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_CREATOR_STRING, SDL_CLIENT_VENDOR);
104 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_COPYRIGHT_STRING, SDL_CLIENT_COPYRIGHT);
105 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_URL_STRING, SDL_CLIENT_URL);
106 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_TYPE_STRING, SDL_CLIENT_TYPE);
109int SdlContext::start()
111 _thread = std::thread(rdpThreadRun,
this);
115int SdlContext::join()
119 HANDLE
event = freerdp_abort_event(context());
120 if (!SetEvent(event))
127void SdlContext::cleanup()
129 std::unique_lock lock(_critical);
135bool SdlContext::shallAbort(
bool ignoreDialogs)
137 std::unique_lock lock(_critical);
138 if (freerdp_shall_disconnect_context(context()))
142 if (_rdpThreadRunning)
144 return !getDialog().isRunning();
151BOOL SdlContext::preConnect(freerdp* instance)
153 WINPR_ASSERT(instance);
154 WINPR_ASSERT(instance->context);
156 auto sdl = get_context(instance->context);
158 auto settings = instance->context->settings;
159 WINPR_ASSERT(settings);
174 if (PubSub_SubscribeChannelConnected(instance->context->pubSub,
175 sdl_OnChannelConnectedEventHandler) < 0)
177 if (PubSub_SubscribeChannelDisconnected(instance->context->pubSub,
178 sdl_OnChannelDisconnectedEventHandler) < 0)
180 if (PubSub_SubscribeUserNotification(instance->context->pubSub,
181 sdl_OnUserNotificationEventHandler) < 0)
187 UINT32 maxHeight = 0;
189 if (!sdl_detect_monitors(
sdl, &maxWidth, &maxHeight))
192 if ((maxWidth != 0) && (maxHeight != 0) &&
195 WLog_Print(
sdl->getWLog(), WLOG_INFO,
"Update size to %ux%u", maxWidth, maxHeight);
210 if (sm && (sw > 0) && (sh > 0))
214 WLog_Print(
sdl->getWLog(), WLOG_WARN,
215 "/smart-sizing and /multimon are currently not supported, ignoring "
234 WLog_Print(
sdl->getWLog(), WLOG_INFO,
235 "auth-only, but no password set. Please provide one.");
242 WLog_Print(
sdl->getWLog(), WLOG_INFO,
"Authentication only. Don't connect SDL.");
245 if (!
sdl->getInputChannelContext().initialize())
260BOOL SdlContext::postConnect(freerdp* instance)
262 WINPR_ASSERT(instance);
264 auto context = instance->context;
265 WINPR_ASSERT(context);
267 auto sdl = get_context(context);
270 sdl->getDialog().show(
false);
277 WLog_Print(
sdl->getWLog(), WLOG_INFO,
278 "auth-only, but no password set. Please provide one.");
282 WLog_Print(
sdl->getWLog(), WLOG_INFO,
"Authentication only. Don't connect to X.");
286 if (!
sdl->waitForWindowsCreated())
289 sdl->_sdlPixelFormat = SDL_PIXELFORMAT_BGRA32;
290 if (!gdi_init(instance, PIXEL_FORMAT_BGRA32))
293 if (!
sdl->createPrimary())
296 if (!sdl_register_pointer(instance->context->graphics))
299 WINPR_ASSERT(context->update);
301 context->update->BeginPaint = beginPaint;
302 context->update->EndPaint = endPaint;
303 context->update->PlaySound = playSound;
304 context->update->DesktopResize = desktopResize;
305 context->update->SetKeyboardIndicators = sdlInput::keyboard_set_indicators;
306 context->update->SetKeyboardImeStatus = sdlInput::keyboard_set_ime_status;
308 if (!
sdl->setResizeable(
false))
314 sdl->setConnected(
true);
321void SdlContext::postDisconnect(freerdp* instance)
326 if (!instance->context)
329 auto sdl = get_context(instance->context);
330 sdl->setConnected(
false);
335void SdlContext::postFinalDisconnect(freerdp* instance)
340 if (!instance->context)
343 PubSub_UnsubscribeChannelConnected(instance->context->pubSub,
344 sdl_OnChannelConnectedEventHandler);
345 PubSub_UnsubscribeChannelDisconnected(instance->context->pubSub,
346 sdl_OnChannelDisconnectedEventHandler);
347 PubSub_UnsubscribeUserNotification(instance->context->pubSub,
348 sdl_OnUserNotificationEventHandler);
352bool SdlContext::createPrimary()
354 auto gdi = context()->gdi;
357 _primary = SDLSurfacePtr(
358 SDL_CreateSurfaceFrom(
static_cast<int>(gdi->width),
static_cast<int>(gdi->height),
359 pixelFormat(), gdi->primary_buffer,
static_cast<int>(gdi->stride)),
364 SDL_SetSurfaceBlendMode(_primary.get(), SDL_BLENDMODE_NONE);
365 SDL_Rect surfaceRect = { 0, 0, gdi->width, gdi->height };
366 SDL_FillSurfaceRect(_primary.get(), &surfaceRect,
367 SDL_MapSurfaceRGBA(_primary.get(), 0, 0, 0, 0xff));
372bool SdlContext::createWindows()
374 auto settings = context()->settings;
375 const auto& title = windowTitle();
377 ScopeGuard guard1([&]() { _windowsCreatedEvent.set(); });
383 for (UINT32 x = 0; x < windowCount; x++)
385 auto id = monitorId(x);
390 freerdp_settings_get_pointer_array_writable(settings, FreeRDP_MonitorDefArray, x));
392 originX = std::min<Sint32>(monitor->x, originX);
393 originY = std::min<Sint32>(monitor->y, originY);
396 for (UINT32 x = 0; x < windowCount; x++)
398 auto id = monitorId(x);
403 freerdp_settings_get_pointer_array_writable(settings, FreeRDP_MonitorDefArray, x));
405 Uint32 w = WINPR_ASSERTING_INT_CAST(Uint32, monitor->width);
406 Uint32 h = WINPR_ASSERTING_INT_CAST(Uint32, monitor->height);
410 if (_windowWidth > 0)
415 if (_windowHeigth > 0)
421 Uint32 flags = SDL_WINDOW_HIGH_PIXEL_DENSITY;
426 flags |= SDL_WINDOW_FULLSCREEN;
431 flags |= SDL_WINDOW_BORDERLESS;
435 flags |= SDL_WINDOW_BORDERLESS;
437 auto did = WINPR_ASSERTING_INT_CAST(SDL_DisplayID,
id);
438 auto window = SdlWindow::create(did, title, flags, w, h);
442 window.setOffsetX(originX - monitor->x);
443 window.setOffsetY(originY - monitor->y);
446 _windows.insert({ window.id(), std::move(window) });
452bool SdlContext::updateWindowList()
454 std::vector<rdpMonitor> list;
455 list.reserve(_windows.size());
456 for (
const auto& win : _windows)
457 list.push_back(win.second.monitor(_windows.size() == 1));
463 std::none_of(list.cbegin(), list.cend(), [](
const rdpMonitor& m) { return m.is_primary; }))
464 list.at(0).is_primary =
true;
470bool SdlContext::updateWindow(SDL_WindowID
id)
476 auto& w = _windows.at(
id);
477 auto m = w.monitor(
true);
481 m.attributes.physicalWidth =
static_cast<UINT32
>(r.w);
482 m.attributes.physicalHeight =
static_cast<UINT32
>(r.h);
487std::string SdlContext::windowTitle()
const
489 const char* prefix =
"FreeRDP:";
497 const auto addPort = (port != 3389);
499 std::stringstream ss;
500 ss << prefix <<
" " << name;
508bool SdlContext::waitForWindowsCreated()
511 std::unique_lock<CriticalSection> lock(_critical);
512 _windowsCreatedEvent.clear();
513 if (!sdl_push_user_event(SDL_EVENT_USER_CREATE_WINDOWS,
this))
517 HANDLE handles[] = { _windowsCreatedEvent.handle(), freerdp_abort_event(context()) };
519 const DWORD rc = WaitForMultipleObjects(ARRAYSIZE(handles), handles, FALSE, INFINITE);
533BOOL SdlContext::endPaint(rdpContext* context)
535 auto sdl = get_context(context);
538 auto gdi = context->gdi;
540 WINPR_ASSERT(gdi->primary);
542 HGDI_DC hdc = gdi->primary->hdc;
548 WINPR_ASSERT(hwnd->invalid || (hwnd->ninvalid == 0));
550 if (hwnd->invalid->null)
553 WINPR_ASSERT(hwnd->invalid);
554 if (gdi->suppressOutput || hwnd->invalid->null)
557 const INT32 ninvalid = hwnd->ninvalid;
558 const GDI_RGN* cinvalid = hwnd->cinvalid;
563 std::vector<SDL_Rect> rects;
564 for (INT32 x = 0; x < ninvalid; x++)
566 auto& rgn = cinvalid[x];
567 rects.push_back({ rgn.x, rgn.y, rgn.w, rgn.h });
570 sdl->push(std::move(rects));
571 return sdl_push_user_event(SDL_EVENT_USER_UPDATE);
574void SdlContext::sdl_client_cleanup(
int exit_code,
const std::string& error_msg)
576 rdpSettings* settings = context()->settings;
577 WINPR_ASSERT(settings);
579 _rdpThreadRunning =
false;
580 bool showError =
false;
582 WLog_Print(getWLog(), WLOG_INFO,
"Authentication only, exit status %s [%" PRId32
"]",
583 sdl::error::exitCodeToTag(exit_code), exit_code);
588 case sdl::error::SUCCESS:
589 case sdl::error::DISCONNECT:
590 case sdl::error::LOGOFF:
591 case sdl::error::DISCONNECT_BY_USER:
592 case sdl::error::CONNECT_CANCELLED:
596 getDialog().showError(error_msg);
603 getDialog().show(
false);
605 _exitCode = exit_code;
606 std::ignore = sdl_push_user_event(SDL_EVENT_USER_QUIT);
610int SdlContext::sdl_client_thread_connect(std::string& error_msg)
612 auto instance = context()->instance;
613 WINPR_ASSERT(instance);
615 _rdpThreadRunning =
true;
616 BOOL rc = freerdp_connect(instance);
618 rdpSettings* settings = context()->settings;
619 WINPR_ASSERT(settings);
621 int exit_code = sdl::error::SUCCESS;
624 UINT32 error = freerdp_get_last_error(context());
625 exit_code = sdl::error::errorToExitCode(error);
630 DWORD code = freerdp_get_last_error(context());
631 freerdp_abort_connect_context(context());
632 WLog_Print(getWLog(), WLOG_ERROR,
"Authentication only, %s [0x%08" PRIx32
"] %s",
633 freerdp_get_last_error_name(code), code, freerdp_get_last_error_string(code));
639 DWORD code = freerdp_error_info(instance);
640 if (exit_code == sdl::error::SUCCESS)
644 exit_code = error_info_to_error(&code, &msg, &len);
650 auto last = freerdp_get_last_error(context());
651 if (error_msg.empty())
655 winpr_asprintf(&msg, &len,
"%s [0x%08" PRIx32
"]\n%s",
656 freerdp_get_last_error_name(last), last,
657 freerdp_get_last_error_string(last));
663 if (exit_code == sdl::error::SUCCESS)
665 if (last == FREERDP_ERROR_AUTHENTICATION_FAILED)
666 exit_code = sdl::error::AUTH_FAILURE;
667 else if (code == ERRINFO_SUCCESS)
668 exit_code = sdl::error::CONN_FAILED;
671 getDialog().show(
false);
677int SdlContext::sdl_client_thread_run(std::string& error_msg)
679 auto instance = context()->instance;
680 WINPR_ASSERT(instance);
682 int exit_code = sdl::error::SUCCESS;
683 while (!freerdp_shall_disconnect_context(context()))
685 HANDLE handles[MAXIMUM_WAIT_OBJECTS] = {};
691 if (freerdp_focus_required(instance))
693 auto ctx = get_context(context());
696 auto& input = ctx->getInputChannelContext();
697 if (!input.keyboard_focus_in())
699 if (!input.keyboard_focus_in())
703 const DWORD nCount = freerdp_get_event_handles(context(), handles, ARRAYSIZE(handles));
707 WLog_Print(getWLog(), WLOG_ERROR,
"freerdp_get_event_handles failed");
711 const DWORD status = WaitForMultipleObjects(nCount, handles, FALSE, INFINITE);
713 if (status == WAIT_FAILED)
715 WLog_Print(getWLog(), WLOG_ERROR,
"WaitForMultipleObjects WAIT_FAILED");
719 if (!freerdp_check_event_handles(context()))
721 if (client_auto_reconnect(instance))
724 getDialog().show(
false);
733 if (freerdp_error_info(instance) == 0)
734 exit_code = sdl::error::CONN_FAILED;
737 if (freerdp_get_last_error(context()) == FREERDP_ERROR_SUCCESS)
738 WLog_Print(getWLog(), WLOG_ERROR,
"WaitForMultipleObjects failed with %" PRIu32
"",
740 if (freerdp_get_last_error(context()) == FREERDP_ERROR_SUCCESS)
741 WLog_Print(getWLog(), WLOG_ERROR,
"Failed to check FreeRDP event handles");
746 if (exit_code == sdl::error::SUCCESS)
750 char* emsg =
nullptr;
752 exit_code = error_info_to_error(&code, &emsg, &elen);
758 if ((code == ERRINFO_LOGOFF_BY_USER) &&
759 (freerdp_get_disconnect_ultimatum(context()) == Disconnect_Ultimatum_user_requested))
761 const char* msg =
"Error info says user did not initiate but disconnect ultimatum says "
762 "they did; treat this as a user logoff";
764 char* emsg =
nullptr;
766 winpr_asprintf(&emsg, &elen,
"%s", msg);
772 WLog_Print(getWLog(), WLOG_INFO,
"%s", msg);
773 exit_code = sdl::error::LOGOFF;
777 freerdp_disconnect(instance);
789 std::string error_msg;
790 int exit_code =
sdl->sdl_client_thread_connect(error_msg);
791 if (exit_code == sdl::error::SUCCESS)
792 exit_code =
sdl->sdl_client_thread_run(error_msg);
793 sdl->sdl_client_cleanup(exit_code, error_msg);
795 return static_cast<DWORD
>(exit_code);
798int SdlContext::error_info_to_error(DWORD* pcode,
char** msg,
size_t* len)
const
800 const DWORD code = freerdp_error_info(context()->instance);
801 const char* name = freerdp_get_error_info_name(code);
802 const char* str = freerdp_get_error_info_string(code);
803 const int exit_code = sdl::error::errorToExitCode(code);
805 winpr_asprintf(msg, len,
"Terminate with %s due to ERROR_INFO %s [0x%08" PRIx32
"]: %s",
806 sdl::error::errorToExitCodeTag(code), name, code, str);
807 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"%s", *msg);
813void SdlContext::applyMonitorOffset(SDL_WindowID window,
float& x,
float& y)
const
818 auto w = getWindowForId(window);
819 x -=
static_cast<float>(w->offsetX());
820 y -=
static_cast<float>(w->offsetY());
823static bool alignX(
const SDL_Rect& a,
const SDL_Rect& b)
825 if (a.x + a.w == b.x)
827 if (b.x + b.w == a.x)
832static bool alignY(
const SDL_Rect& a,
const SDL_Rect& b)
834 if (a.y + a.h == b.y)
836 if (b.y + b.h == a.y)
841std::vector<SDL_DisplayID>
842SdlContext::updateDisplayOffsetsForNeighbours(SDL_DisplayID
id,
843 const std::vector<SDL_DisplayID>& ignore)
845 auto first = _offsets.at(
id);
846 std::vector<SDL_DisplayID> neighbours;
848 for (
auto& entry : _offsets)
850 if (entry.first ==
id)
852 if (std::find(ignore.begin(), ignore.end(), entry.first) != ignore.end())
855 bool neighbor =
false;
856 if (alignX(entry.second.first, first.first))
858 if (entry.second.first.x < first.first.x)
859 entry.second.second.x = first.second.x - entry.second.second.w;
861 entry.second.second.x = first.second.x + first.second.w;
864 if (alignY(entry.second.first, first.first))
866 if (entry.second.first.y < first.first.y)
867 entry.second.second.y = first.second.y - entry.second.second.h;
869 entry.second.second.y = first.second.y + first.second.h;
874 neighbours.push_back(entry.first);
879void SdlContext::updateMonitorDataFromOffsets()
881 for (
auto& entry : _displays)
883 auto offsets = _offsets.at(entry.first);
884 entry.second.x = offsets.second.x;
885 entry.second.y = offsets.second.y;
888 for (
auto& entry : _windows)
890 const auto& monitor = _displays.at(entry.first);
891 entry.second.setMonitor(monitor);
895bool SdlContext::drawToWindow(
SdlWindow& window,
const std::vector<SDL_Rect>& rects)
900 auto gdi = context()->gdi;
903 auto size = window.rect();
905 std::unique_lock lock(_critical);
906 auto surface = _primary.get();
910 window.setOffsetX(0);
911 window.setOffsetY(0);
912 if (gdi->width < size.w)
914 window.setOffsetX((size.w - gdi->width) / 2);
916 if (gdi->height < size.h)
918 window.setOffsetY((size.h - gdi->height) / 2);
921 _localScale = {
static_cast<float>(size.w) /
static_cast<float>(gdi->width),
922 static_cast<float>(size.h) /
static_cast<float>(gdi->height) };
923 if (!window.drawScaledRects(surface, _localScale, rects))
928 SDL_Point offset{ 0, 0 };
930 offset = { window.offsetX(), window.offsetY() };
931 if (!window.drawRects(surface, offset, rects))
935 window.updateSurface();
939bool SdlContext::minimizeAllWindows()
941 for (
auto& w : _windows)
946int SdlContext::exitCode()
const
951SDL_PixelFormat SdlContext::pixelFormat()
const
953 return _sdlPixelFormat;
956bool SdlContext::addDisplayWindow(SDL_DisplayID
id)
959 SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS;
960 auto title = sdl::utils::windowTitle(context()->settings);
961 auto w = SdlWindow::create(
id, title, flags);
962 _windows.emplace(w.id(), std::move(w));
966bool SdlContext::removeDisplayWindow(SDL_DisplayID
id)
968 for (
auto& w : _windows)
970 if (w.second.displayIndex() ==
id)
971 _windows.erase(w.first);
976bool SdlContext::detectDisplays()
979 auto display = SDL_GetDisplays(&count);
982 for (
int x = 0; x < count; x++)
984 const auto id = display[x];
985 addOrUpdateDisplay(
id);
991rdpMonitor SdlContext::getDisplay(SDL_DisplayID
id)
const
993 return _displays.at(
id);
996std::vector<SDL_DisplayID> SdlContext::getDisplayIds()
const
998 std::vector<SDL_DisplayID> keys;
999 keys.reserve(_displays.size());
1000 for (
const auto& entry : _displays)
1002 keys.push_back(entry.first);
1007const SdlWindow* SdlContext::getWindowForId(SDL_WindowID
id)
const
1009 auto it = _windows.find(
id);
1010 if (it == _windows.end())
1015SdlWindow* SdlContext::getWindowForId(SDL_WindowID
id)
1017 auto it = _windows.find(
id);
1018 if (it == _windows.end())
1025 if (_windows.empty())
1027 return &_windows.begin()->second;
1035sdlInput& SdlContext::getInputChannelContext()
1040sdlClip& SdlContext::getClipboardChannelContext()
1050wLog* SdlContext::getWLog()
1055bool SdlContext::moveMouseTo(
const SDL_FPoint& pos)
1057 auto window = SDL_GetMouseFocus();
1061 const auto id = SDL_GetWindowID(window);
1062 const auto spos = pixelToScreen(
id, pos);
1063 SDL_WarpMouseInWindow(window, spos.x, spos.y);
1067bool SdlContext::handleEvent(
const SDL_MouseMotionEvent& ev)
1069 if (!getWindowForId(ev.windowID))
1073 if (!eventToPixelCoordinates(ev.windowID, copy))
1075 removeLocalScaling(copy.motion.x, copy.motion.y);
1076 removeLocalScaling(copy.motion.xrel, copy.motion.yrel);
1077 applyMonitorOffset(copy.motion.windowID, copy.motion.x, copy.motion.y);
1079 return SdlTouch::handleEvent(
this, copy.motion);
1082bool SdlContext::handleEvent(
const SDL_MouseWheelEvent& ev)
1084 if (!getWindowForId(ev.windowID))
1088 if (!eventToPixelCoordinates(ev.windowID, copy))
1090 removeLocalScaling(copy.wheel.mouse_x, copy.wheel.mouse_y);
1091 return SdlTouch::handleEvent(
this, copy.wheel);
1094bool SdlContext::handleEvent(
const SDL_WindowEvent& ev)
1096 if (!getDisplayChannelContext().handleEvent(ev))
1099 auto window = getWindowForId(ev.windowID);
1104 const auto& r = window->rect();
1105 const auto& b = window->bounds();
1106 const auto& scale = window->scale();
1107 const auto& orientation = window->orientation();
1108 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
1109 "%s: [%u] %dx%d-%dx%d {%dx%d-%dx%d}{scale=%f,orientation=%s}",
1110 sdl::utils::toString(ev.type).c_str(), ev.windowID, r.x, r.y, r.w, r.h, b.x,
1111 b.y, b.w, b.h,
static_cast<double>(scale),
1112 sdl::utils::toString(orientation).c_str());
1117 case SDL_EVENT_WINDOW_MOUSE_ENTER:
1118 return restoreCursor();
1119 case SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED:
1120 if (!resizeToScale(window))
1124 if (!window->fill())
1126 if (!drawToWindow(*window))
1128 if (!restoreCursor())
1132 case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
1133 if (!resizeToScale(window))
1135 if (!window->fill())
1137 if (!drawToWindow(*window))
1139 if (!restoreCursor())
1142 case SDL_EVENT_WINDOW_MOVED:
1144 auto r = window->rect();
1145 auto id = window->id();
1146 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"%u: %dx%d-%dx%d",
id, r.x, r.y, r.w, r.h);
1149 case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
1151 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"Window closed, terminating RDP session...");
1152 freerdp_abort_connect_context(context());
1161bool SdlContext::handleEvent(
const SDL_DisplayEvent& ev)
1163 if (!getDisplayChannelContext().handleEvent(ev))
1168 case SDL_EVENT_DISPLAY_REMOVED:
1173 if (!SDL_GetDisplayBounds(ev.displayID, &r))
1175 const auto name = SDL_GetDisplayName(ev.displayID);
1178 const auto orientation = SDL_GetCurrentDisplayOrientation(ev.displayID);
1179 const auto scale = SDL_GetDisplayContentScale(ev.displayID);
1180 const auto mode = SDL_GetCurrentDisplayMode(ev.displayID);
1184 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
1185 "%s: [%u, %s] %dx%d-%dx%d {orientation=%s, scale=%f}%s",
1186 sdl::utils::toString(ev.type).c_str(), ev.displayID, name, r.x, r.y, r.w,
1187 r.h, sdl::utils::toString(orientation).c_str(),
static_cast<double>(scale),
1188 sdl::utils::toString(mode).c_str());
1195bool SdlContext::handleEvent(
const SDL_MouseButtonEvent& ev)
1197 if (!getWindowForId(ev.windowID))
1199 SDL_Event copy = {};
1201 if (!eventToPixelCoordinates(ev.windowID, copy))
1203 removeLocalScaling(copy.button.x, copy.button.y);
1204 applyMonitorOffset(copy.button.windowID, copy.button.x, copy.button.y);
1205 return SdlTouch::handleEvent(
this, copy.button);
1208bool SdlContext::handleEvent(
const SDL_TouchFingerEvent& ev)
1210 if (!getWindowForId(ev.windowID))
1214 if (!eventToPixelCoordinates(ev.windowID, copy))
1216 removeLocalScaling(copy.tfinger.dx, copy.tfinger.dy);
1217 removeLocalScaling(copy.tfinger.x, copy.tfinger.y);
1218 applyMonitorOffset(copy.tfinger.windowID, copy.tfinger.x, copy.tfinger.y);
1219 return SdlTouch::handleEvent(
this, copy.tfinger);
1222void SdlContext::addOrUpdateDisplay(SDL_DisplayID
id)
1224 auto monitor = SdlWindow::query(
id,
false);
1225 _displays.emplace(
id, monitor);
1235 for (
auto& entry : _displays)
1238 std::ignore = SDL_GetDisplayBounds(entry.first, &bounds);
1241 pixel.w = entry.second.width;
1242 pixel.h = entry.second.height;
1243 _offsets.emplace(entry.first, std::pair{ bounds, pixel });
1250 const auto primary = SDL_GetPrimaryDisplay();
1251 std::vector<SDL_DisplayID> handled;
1252 handled.push_back(primary);
1254 auto neighbors = updateDisplayOffsetsForNeighbours(primary);
1255 while (!neighbors.empty())
1257 auto neighbor = neighbors.front();
1258 neighbors.erase(neighbors.begin());
1260 if (std::find(handled.begin(), handled.end(), neighbor) != handled.end())
1262 handled.push_back(neighbor);
1264 auto next = updateDisplayOffsetsForNeighbours(neighbor, handled);
1265 neighbors.insert(neighbors.end(), next.begin(), next.end());
1267 updateMonitorDataFromOffsets();
1270void SdlContext::deleteDisplay(SDL_DisplayID
id)
1272 _displays.erase(
id);
1275bool SdlContext::eventToPixelCoordinates(SDL_WindowID
id, SDL_Event& ev)
1277 auto w = getWindowForId(
id);
1282 auto renderer = w->renderer();
1285 return SDL_ConvertEventToRenderCoordinates(renderer, &ev);
1288SDL_FPoint SdlContext::applyLocalScaling(
const SDL_FPoint& val)
const
1290 if (!useLocalScale())
1294 rval.x *= _localScale.x;
1295 rval.y *= _localScale.y;
1299void SdlContext::removeLocalScaling(
float& x,
float& y)
const
1301 if (!useLocalScale())
1307SDL_FPoint SdlContext::screenToPixel(SDL_WindowID
id,
const SDL_FPoint& pos)
1309 auto w = getWindowForId(
id);
1314 auto renderer = w->renderer();
1319 if (!SDL_RenderCoordinatesFromWindow(renderer, pos.x, pos.y, &rpos.x, &rpos.y))
1321 removeLocalScaling(rpos.x, rpos.y);
1325SDL_FPoint SdlContext::pixelToScreen(SDL_WindowID
id,
const SDL_FPoint& pos)
1327 auto w = getWindowForId(
id);
1332 auto renderer = w->renderer();
1337 if (!SDL_RenderCoordinatesToWindow(renderer, pos.x, pos.y, &rpos.x, &rpos.y))
1339 return applyLocalScaling(rpos);
1342SDL_FRect SdlContext::pixelToScreen(SDL_WindowID
id,
const SDL_FRect& pos,
bool round)
1344 const auto fpos = pixelToScreen(
id, SDL_FPoint{ pos.x, pos.y });
1345 const auto size = pixelToScreen(
id, SDL_FPoint{ pos.w, pos.h });
1346 SDL_FRect r{ fpos.x, fpos.y, size.x, size.y };
1349 r.w = std::ceil(r.w);
1350 r.h = std::ceil(r.h);
1351 r.x = std::floor(r.x);
1352 r.y = std::floor(r.y);
1357bool SdlContext::handleEvent(
const SDL_Event& ev)
1359 if ((ev.type >= SDL_EVENT_DISPLAY_FIRST) && (ev.type <= SDL_EVENT_DISPLAY_LAST))
1361 const auto& dev = ev.display;
1362 return handleEvent(dev);
1364 if ((ev.type >= SDL_EVENT_WINDOW_FIRST) && (ev.type <= SDL_EVENT_WINDOW_LAST))
1366 const auto& wev = ev.window;
1367 return handleEvent(wev);
1371 case SDL_EVENT_RENDER_TARGETS_RESET:
1372 case SDL_EVENT_RENDER_DEVICE_RESET:
1373 case SDL_EVENT_WILL_ENTER_FOREGROUND:
1384 case SDL_EVENT_FINGER_DOWN:
1385 case SDL_EVENT_FINGER_UP:
1386 case SDL_EVENT_FINGER_MOTION:
1388 const auto& cev = ev.tfinger;
1389 return handleEvent(cev);
1391 case SDL_EVENT_MOUSE_MOTION:
1394 const auto& cev = ev.motion;
1395 return handleEvent(cev);
1397 case SDL_EVENT_MOUSE_BUTTON_DOWN:
1398 case SDL_EVENT_MOUSE_BUTTON_UP:
1400 const auto& cev = ev.button;
1401 return handleEvent(cev);
1403 case SDL_EVENT_MOUSE_WHEEL:
1405 const auto& cev = ev.wheel;
1406 return handleEvent(cev);
1408 case SDL_EVENT_CLIPBOARD_UPDATE:
1410 const auto& cev = ev.clipboard;
1411 return getClipboardChannelContext().handleEvent(cev);
1413 case SDL_EVENT_KEY_DOWN:
1414 case SDL_EVENT_KEY_UP:
1416 const auto& cev = ev.key;
1417 return getInputChannelContext().handleEvent(cev);
1426 return _args.data();
1429size_t SdlContext::argsCount()
const
1431 if (_args.size() <= 1)
1433 return _args.size() - 1;
1444 if (strcmp(arg->Name, sdl_allow_screensaver) == 0)
1446 if (arg->Value !=
nullptr)
1448 if (!SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER,
"1"))
1450 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
1451 "SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER) failed with %s",
1466std::vector<rdpPointer*>& SdlContext::pointers()
1468 return _valid_pointers;
1471bool SdlContext::contains(
const rdpPointer* ptr)
const
1473 for (
const auto& cur : _valid_pointers)
1481bool SdlContext::resizeToScale(
SdlWindow* window)
1485 if (!useLocalScale())
1489 return window->resizeToScale();
1492bool SdlContext::useLocalScale()
const
1497 const auto dynResize =
1501 return !dynResize && !fs && !multimon;
1504bool SdlContext::drawToWindows(
const std::vector<SDL_Rect>& rects)
1506 for (
auto& window : _windows)
1508 if (!drawToWindow(window.second, rects))
1515BOOL SdlContext::desktopResize(rdpContext* context)
1517 rdpGdi* gdi =
nullptr;
1518 rdpSettings* settings =
nullptr;
1519 auto sdl = get_context(context);
1522 WINPR_ASSERT(context);
1524 settings = context->settings;
1525 WINPR_ASSERT(settings);
1527 std::unique_lock lock(
sdl->_critical);
1532 return sdl->createPrimary();
1536BOOL SdlContext::playSound(rdpContext* context,
const PLAY_SOUND_UPDATE* play_sound)
1539 WINPR_UNUSED(context);
1540 WINPR_UNUSED(play_sound);
1546BOOL SdlContext::beginPaint(rdpContext* context)
1548 auto gdi = context->gdi;
1550 WINPR_ASSERT(gdi->primary);
1552 HGDI_DC hdc = gdi->primary->hdc;
1558 WINPR_ASSERT(hwnd->invalid);
1559 hwnd->invalid->null = TRUE;
1565bool SdlContext::redraw(
bool suppress)
const
1570 auto gdi = context()->gdi;
1572 return gdi_send_suppress_output(gdi, suppress);
1575void SdlContext::setConnected(
bool val)
1580bool SdlContext::isConnected()
const
1585rdpContext* SdlContext::context()
const
1587 WINPR_ASSERT(_context);
1591rdpClientContext* SdlContext::common()
const
1593 return reinterpret_cast<rdpClientContext*
>(context());
1596bool SdlContext::setCursor(CursorType type)
1599 return restoreCursor();
1602bool SdlContext::setCursor(
const rdpPointer* cursor)
1604 std::unique_lock lock(_critical);
1605 if (!contains(cursor))
1608 _cursor = { sdl_Pointer_Copy(cursor), sdl_PointerFreeCopyAll };
1609 return setCursor(CURSOR_IMAGE);
1612rdpPointer* SdlContext::cursor()
const
1614 return _cursor.get();
1617bool SdlContext::restoreCursor()
1619 WLog_Print(getWLog(), WLOG_DEBUG,
"restore cursor: %d", _cursorType);
1620 switch (_cursorType)
1623 if (!SDL_HideCursor())
1625 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_HideCursor failed");
1629 setHasCursor(
false);
1632 case CURSOR_DEFAULT:
1634 auto def = SDL_GetDefaultCursor();
1635 if (!SDL_SetCursor(def))
1637 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_SetCursor(default=%p) failed",
1638 static_cast<void*
>(def));
1641 if (!SDL_ShowCursor())
1643 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_ShowCursor failed");
1651 return sdl_Pointer_Set_Process(
this);
1653 WLog_Print(getWLog(), WLOG_ERROR,
"Unknown cursorType %s",
1654 sdl::utils::toString(_cursorType).c_str());
1659void SdlContext::setMonitorIds(
const std::vector<SDL_DisplayID>& ids)
1661 _monitorIds.clear();
1664 _monitorIds.push_back(
id);
1668const std::vector<SDL_DisplayID>& SdlContext::monitorIds()
const
1673int64_t SdlContext::monitorId(uint32_t index)
const
1675 if (index >= _monitorIds.size())
1679 return _monitorIds.at(index);
1682void SdlContext::push(std::vector<SDL_Rect>&& rects)
1684 std::unique_lock lock(_queue_mux);
1685 _queue.emplace(std::move(rects));
1688std::vector<SDL_Rect> SdlContext::pop()
1690 std::unique_lock lock(_queue_mux);
1695 auto val = std::move(_queue.front());
1700bool SdlContext::setFullscreen(
bool enter,
bool forceOriginalDisplay)
1702 for (
const auto& window : _windows)
1704 if (!sdl_push_user_event(SDL_EVENT_USER_WINDOW_FULLSCREEN, &window.second, enter,
1705 forceOriginalDisplay))
1708 _fullscreen = enter;
1712bool SdlContext::setMinimized()
1714 return sdl_push_user_event(SDL_EVENT_USER_WINDOW_MINIMIZE);
1717bool SdlContext::grabMouse()
const
1722bool SdlContext::toggleGrabMouse()
1724 return setGrabMouse(!grabMouse());
1727bool SdlContext::setGrabMouse(
bool enter)
1733bool SdlContext::grabKeyboard()
const
1735 return _grabKeyboard;
1738bool SdlContext::toggleGrabKeyboard()
1740 return setGrabKeyboard(!grabKeyboard());
1743bool SdlContext::setGrabKeyboard(
bool enter)
1745 _grabKeyboard = enter;
1749bool SdlContext::setResizeable(
bool enable)
1751 const auto settings = context()->settings;
1754 bool use = (dyn && enable) || smart;
1756 for (
const auto& window : _windows)
1758 if (!sdl_push_user_event(SDL_EVENT_USER_WINDOW_RESIZEABLE, &window.second, use))
1766bool SdlContext::resizeable()
const
1771bool SdlContext::toggleResizeable()
1773 return setResizeable(!resizeable());
1776bool SdlContext::fullscreen()
const
1781bool SdlContext::toggleFullscreen()
1783 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.