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";
41SdlContext::SdlContext(rdpContext* context)
42 : _context(context), _log(WLog_Get(CLIENT_TAG(
"SDL"))), _cursor(nullptr, sdl_Pointer_FreeCopy),
43 _rdpThreadRunning(false), _primary(nullptr, SDL_DestroySurface), _disp(this), _input(this),
44 _clip(this), _dialog(_log)
46 WINPR_ASSERT(context);
49 auto instance = _context->instance;
50 WINPR_ASSERT(instance);
52 instance->PreConnect = preConnect;
53 instance->PostConnect = postConnect;
54 instance->PostDisconnect = postDisconnect;
55 instance->PostFinalDisconnect = postFinalDisconnect;
56 instance->AuthenticateEx = sdl_authenticate_ex;
57 instance->VerifyCertificateEx = sdl_verify_certificate_ex;
58 instance->VerifyChangedCertificateEx = sdl_verify_changed_certificate_ex;
59 instance->LogonErrorInfo = sdl_logon_error_info;
60 instance->PresentGatewayMessage = sdl_present_gateway_message;
61 instance->ChooseSmartcard = sdl_choose_smartcard;
62 instance->RetryDialog = sdl_retry_dialog;
65 instance->GetAccessToken = sdl_webview_get_access_token;
67 instance->GetAccessToken = client_cli_get_access_token;
71 _args.push_back({ sdl_allow_screensaver, COMMAND_LINE_VALUE_BOOL,
nullptr, BoolValueFalse,
72 nullptr, -1,
nullptr,
"Allow local screensaver to activate" });
75 _args.push_back({
nullptr, 0,
nullptr,
nullptr,
nullptr, -1,
nullptr,
nullptr });
78void SdlContext::setHasCursor(
bool val)
80 this->_cursor_visible = val;
83bool SdlContext::hasCursor()
const
85 return _cursor_visible;
88void SdlContext::setMetadata()
91 if (!wmclass || (strlen(wmclass) == 0))
92 wmclass = SDL_CLIENT_UUID;
94 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_IDENTIFIER_STRING, wmclass);
95 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_NAME_STRING, SDL_CLIENT_NAME);
96 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_VERSION_STRING, SDL_CLIENT_VERSION);
97 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_CREATOR_STRING, SDL_CLIENT_VENDOR);
98 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_COPYRIGHT_STRING, SDL_CLIENT_COPYRIGHT);
99 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_URL_STRING, SDL_CLIENT_URL);
100 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_TYPE_STRING, SDL_CLIENT_TYPE);
103int SdlContext::start()
105 _thread = std::thread(rdpThreadRun,
this);
109int SdlContext::join()
113 HANDLE
event = freerdp_abort_event(context());
114 if (!SetEvent(event))
121void SdlContext::cleanup()
123 std::unique_lock lock(_critical);
129bool SdlContext::shallAbort(
bool ignoreDialogs)
131 std::unique_lock lock(_critical);
132 if (freerdp_shall_disconnect_context(context()))
136 if (_rdpThreadRunning)
138 return !getDialog().isRunning();
145BOOL SdlContext::preConnect(freerdp* instance)
147 WINPR_ASSERT(instance);
148 WINPR_ASSERT(instance->context);
150 auto sdl = get_context(instance->context);
152 auto settings = instance->context->settings;
153 WINPR_ASSERT(settings);
168 if (PubSub_SubscribeChannelConnected(instance->context->pubSub,
169 sdl_OnChannelConnectedEventHandler) < 0)
171 if (PubSub_SubscribeChannelDisconnected(instance->context->pubSub,
172 sdl_OnChannelDisconnectedEventHandler) < 0)
174 if (PubSub_SubscribeUserNotification(instance->context->pubSub,
175 sdl_OnUserNotificationEventHandler) < 0)
181 UINT32 maxHeight = 0;
183 if (!sdl_detect_monitors(
sdl, &maxWidth, &maxHeight))
186 if ((maxWidth != 0) && (maxHeight != 0) &&
189 WLog_Print(
sdl->getWLog(), WLOG_INFO,
"Update size to %ux%u", maxWidth, maxHeight);
204 if (sm && (sw > 0) && (sh > 0))
208 WLog_Print(
sdl->getWLog(), WLOG_WARN,
209 "/smart-sizing and /multimon are currently not supported, ignoring "
228 WLog_Print(
sdl->getWLog(), WLOG_INFO,
229 "auth-only, but no password set. Please provide one.");
236 WLog_Print(
sdl->getWLog(), WLOG_INFO,
"Authentication only. Don't connect SDL.");
239 if (!
sdl->getInputChannelContext().initialize())
242 sdl->_credentialsRead =
false;
255BOOL SdlContext::postConnect(freerdp* instance)
257 WINPR_ASSERT(instance);
259 auto context = instance->context;
260 WINPR_ASSERT(context);
262 auto sdl = get_context(context);
265 sdl->getDialog().show(
false);
272 WLog_Print(
sdl->getWLog(), WLOG_INFO,
273 "auth-only, but no password set. Please provide one.");
277 WLog_Print(
sdl->getWLog(), WLOG_INFO,
"Authentication only. Don't connect to X.");
281 if (!
sdl->waitForWindowsCreated())
284 sdl->_sdlPixelFormat = SDL_PIXELFORMAT_BGRA32;
285 if (!gdi_init(instance, PIXEL_FORMAT_BGRA32))
288 if (!
sdl->createPrimary())
291 if (!sdl_register_pointer(instance->context->graphics))
294 WINPR_ASSERT(context->update);
296 context->update->BeginPaint = beginPaint;
297 context->update->EndPaint = endPaint;
298 context->update->PlaySound = playSound;
299 context->update->DesktopResize = desktopResize;
300 context->update->SetKeyboardIndicators = sdlInput::keyboard_set_indicators;
301 context->update->SetKeyboardImeStatus = sdlInput::keyboard_set_ime_status;
303 if (!
sdl->setResizeable(
false))
309 sdl->setConnected(
true);
316void SdlContext::postDisconnect(freerdp* instance)
321 if (!instance->context)
324 auto sdl = get_context(instance->context);
325 sdl->setConnected(
false);
330void SdlContext::postFinalDisconnect(freerdp* instance)
335 if (!instance->context)
338 PubSub_UnsubscribeChannelConnected(instance->context->pubSub,
339 sdl_OnChannelConnectedEventHandler);
340 PubSub_UnsubscribeChannelDisconnected(instance->context->pubSub,
341 sdl_OnChannelDisconnectedEventHandler);
342 PubSub_UnsubscribeUserNotification(instance->context->pubSub,
343 sdl_OnUserNotificationEventHandler);
347bool SdlContext::createPrimary()
349 auto gdi = context()->gdi;
352 _primary = SDLSurfacePtr(
353 SDL_CreateSurfaceFrom(
static_cast<int>(gdi->width),
static_cast<int>(gdi->height),
354 pixelFormat(), gdi->primary_buffer,
static_cast<int>(gdi->stride)),
359 SDL_SetSurfaceBlendMode(_primary.get(), SDL_BLENDMODE_NONE);
360 SDL_Rect surfaceRect = { 0, 0, gdi->width, gdi->height };
361 SDL_FillSurfaceRect(_primary.get(), &surfaceRect,
362 SDL_MapSurfaceRGBA(_primary.get(), 0, 0, 0, 0xff));
367bool SdlContext::createWindows()
369 auto settings = context()->settings;
370 const auto& title = windowTitle();
372 ScopeGuard guard1([&]() { _windowsCreatedEvent.set(); });
378 for (UINT32 x = 0; x < windowCount; x++)
380 auto id = monitorId(x);
385 freerdp_settings_get_pointer_array_writable(settings, FreeRDP_MonitorDefArray, x));
387 originX = std::min<Sint32>(monitor->x, originX);
388 originY = std::min<Sint32>(monitor->y, originY);
391 for (UINT32 x = 0; x < windowCount; x++)
393 auto id = monitorId(x);
398 freerdp_settings_get_pointer_array_writable(settings, FreeRDP_MonitorDefArray, x));
400 Uint32 w = WINPR_ASSERTING_INT_CAST(Uint32, monitor->width);
401 Uint32 h = WINPR_ASSERTING_INT_CAST(Uint32, monitor->height);
405 if (_windowWidth > 0)
410 if (_windowHeigth > 0)
416 Uint32 flags = SDL_WINDOW_HIGH_PIXEL_DENSITY;
421 flags |= SDL_WINDOW_FULLSCREEN;
426 flags |= SDL_WINDOW_BORDERLESS;
430 flags |= SDL_WINDOW_BORDERLESS;
432 auto did = WINPR_ASSERTING_INT_CAST(SDL_DisplayID,
id);
433 auto window = SdlWindow::create(did, title, flags, w, h);
437 window.setOffsetX(originX - monitor->x);
438 window.setOffsetY(originY - monitor->y);
441 _windows.insert({ window.id(), std::move(window) });
447bool SdlContext::updateWindowList()
449 std::vector<rdpMonitor> list;
450 list.reserve(_windows.size());
451 for (
const auto& win : _windows)
452 list.push_back(win.second.monitor(_windows.size() == 1));
458 std::none_of(list.cbegin(), list.cend(), [](
const rdpMonitor& m) { return m.is_primary; }))
459 list.at(0).is_primary =
true;
465bool SdlContext::updateWindow(SDL_WindowID
id)
471 auto& w = _windows.at(
id);
472 auto m = w.monitor(
true);
476 m.attributes.physicalWidth =
static_cast<UINT32
>(r.w);
477 m.attributes.physicalHeight =
static_cast<UINT32
>(r.h);
482std::string SdlContext::windowTitle()
const
484 const char* prefix =
"FreeRDP:";
492 const auto addPort = (port != 3389);
494 std::stringstream ss;
495 ss << prefix <<
" " << name;
503bool SdlContext::waitForWindowsCreated()
506 std::unique_lock<CriticalSection> lock(_critical);
507 _windowsCreatedEvent.clear();
508 if (!sdl_push_user_event(SDL_EVENT_USER_CREATE_WINDOWS,
this))
512 HANDLE handles[] = { _windowsCreatedEvent.handle(), freerdp_abort_event(context()) };
514 const DWORD rc = WaitForMultipleObjects(ARRAYSIZE(handles), handles, FALSE, INFINITE);
528BOOL SdlContext::endPaint(rdpContext* context)
530 auto sdl = get_context(context);
533 auto gdi = context->gdi;
535 WINPR_ASSERT(gdi->primary);
537 HGDI_DC hdc = gdi->primary->hdc;
543 WINPR_ASSERT(hwnd->invalid || (hwnd->ninvalid == 0));
545 if (hwnd->invalid->null)
548 WINPR_ASSERT(hwnd->invalid);
549 if (gdi->suppressOutput || hwnd->invalid->null)
552 const INT32 ninvalid = hwnd->ninvalid;
553 const GDI_RGN* cinvalid = hwnd->cinvalid;
558 std::vector<SDL_Rect> rects;
559 for (INT32 x = 0; x < ninvalid; x++)
561 auto& rgn = cinvalid[x];
562 rects.push_back({ rgn.x, rgn.y, rgn.w, rgn.h });
565 sdl->push(std::move(rects));
566 return sdl_push_user_event(SDL_EVENT_USER_UPDATE);
569void SdlContext::sdl_client_cleanup(
int exit_code,
const std::string& error_msg)
571 rdpSettings* settings = context()->settings;
572 WINPR_ASSERT(settings);
574 _rdpThreadRunning =
false;
575 bool showError =
false;
577 WLog_Print(getWLog(), WLOG_INFO,
"Authentication only, exit status %s [%" PRId32
"]",
578 sdl::error::exitCodeToTag(exit_code), exit_code);
583 case sdl::error::SUCCESS:
584 case sdl::error::DISCONNECT:
585 case sdl::error::LOGOFF:
586 case sdl::error::DISCONNECT_BY_USER:
587 case sdl::error::CONNECT_CANCELLED:
591 getDialog().showError(error_msg);
598 getDialog().show(
false);
600 _exitCode = exit_code;
601 std::ignore = sdl_push_user_event(SDL_EVENT_USER_QUIT);
605int SdlContext::sdl_client_thread_connect(std::string& error_msg)
607 auto instance = context()->instance;
608 WINPR_ASSERT(instance);
610 _rdpThreadRunning =
true;
611 BOOL rc = freerdp_connect(instance);
613 rdpSettings* settings = context()->settings;
614 WINPR_ASSERT(settings);
616 int exit_code = sdl::error::SUCCESS;
619 UINT32 error = freerdp_get_last_error(context());
620 exit_code = sdl::error::errorToExitCode(error);
625 DWORD code = freerdp_get_last_error(context());
626 freerdp_abort_connect_context(context());
627 WLog_Print(getWLog(), WLOG_ERROR,
"Authentication only, %s [0x%08" PRIx32
"] %s",
628 freerdp_get_last_error_name(code), code, freerdp_get_last_error_string(code));
634 DWORD code = freerdp_error_info(instance);
635 if (exit_code == sdl::error::SUCCESS)
639 exit_code = error_info_to_error(&code, &msg, &len);
645 auto last = freerdp_get_last_error(context());
646 if (error_msg.empty())
650 winpr_asprintf(&msg, &len,
"%s [0x%08" PRIx32
"]\n%s",
651 freerdp_get_last_error_name(last), last,
652 freerdp_get_last_error_string(last));
658 if (exit_code == sdl::error::SUCCESS)
660 if (last == FREERDP_ERROR_AUTHENTICATION_FAILED)
661 exit_code = sdl::error::AUTH_FAILURE;
662 else if (code == ERRINFO_SUCCESS)
663 exit_code = sdl::error::CONN_FAILED;
666 getDialog().show(
false);
672int SdlContext::sdl_client_thread_run(std::string& error_msg)
674 auto instance = context()->instance;
675 WINPR_ASSERT(instance);
677 int exit_code = sdl::error::SUCCESS;
678 while (!freerdp_shall_disconnect_context(context()))
680 HANDLE handles[MAXIMUM_WAIT_OBJECTS] = {};
686 if (freerdp_focus_required(instance))
688 auto ctx = get_context(context());
691 auto& input = ctx->getInputChannelContext();
692 if (!input.keyboard_focus_in())
694 if (!input.keyboard_focus_in())
698 const DWORD nCount = freerdp_get_event_handles(context(), handles, ARRAYSIZE(handles));
702 WLog_Print(getWLog(), WLOG_ERROR,
"freerdp_get_event_handles failed");
706 const DWORD status = WaitForMultipleObjects(nCount, handles, FALSE, INFINITE);
708 if (status == WAIT_FAILED)
710 WLog_Print(getWLog(), WLOG_ERROR,
"WaitForMultipleObjects WAIT_FAILED");
714 if (!freerdp_check_event_handles(context()))
716 if (client_auto_reconnect(instance))
719 getDialog().show(
false);
728 if (freerdp_error_info(instance) == 0)
729 exit_code = sdl::error::CONN_FAILED;
732 if (freerdp_get_last_error(context()) == FREERDP_ERROR_SUCCESS)
733 WLog_Print(getWLog(), WLOG_ERROR,
"WaitForMultipleObjects failed with %" PRIu32
"",
735 if (freerdp_get_last_error(context()) == FREERDP_ERROR_SUCCESS)
736 WLog_Print(getWLog(), WLOG_ERROR,
"Failed to check FreeRDP event handles");
741 if (exit_code == sdl::error::SUCCESS)
745 char* emsg =
nullptr;
747 exit_code = error_info_to_error(&code, &emsg, &elen);
753 if ((code == ERRINFO_LOGOFF_BY_USER) &&
754 (freerdp_get_disconnect_ultimatum(context()) == Disconnect_Ultimatum_user_requested))
756 const char* msg =
"Error info says user did not initiate but disconnect ultimatum says "
757 "they did; treat this as a user logoff";
759 char* emsg =
nullptr;
761 winpr_asprintf(&emsg, &elen,
"%s", msg);
767 WLog_Print(getWLog(), WLOG_INFO,
"%s", msg);
768 exit_code = sdl::error::LOGOFF;
772 freerdp_disconnect(instance);
784 std::string error_msg;
785 int exit_code =
sdl->sdl_client_thread_connect(error_msg);
786 if (exit_code == sdl::error::SUCCESS)
787 exit_code =
sdl->sdl_client_thread_run(error_msg);
788 sdl->sdl_client_cleanup(exit_code, error_msg);
790 return static_cast<DWORD
>(exit_code);
793int SdlContext::error_info_to_error(DWORD* pcode,
char** msg,
size_t* len)
const
795 const DWORD code = freerdp_error_info(context()->instance);
796 const char* name = freerdp_get_error_info_name(code);
797 const char* str = freerdp_get_error_info_string(code);
798 const int exit_code = sdl::error::errorToExitCode(code);
800 winpr_asprintf(msg, len,
"Terminate with %s due to ERROR_INFO %s [0x%08" PRIx32
"]: %s",
801 sdl::error::errorToExitCodeTag(code), name, code, str);
802 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"%s", *msg);
808void SdlContext::applyMonitorOffset(SDL_WindowID window,
float& x,
float& y)
const
813 auto w = getWindowForId(window);
814 x -=
static_cast<float>(w->offsetX());
815 y -=
static_cast<float>(w->offsetY());
818static bool alignX(
const SDL_Rect& a,
const SDL_Rect& b)
820 if (a.x + a.w == b.x)
822 if (b.x + b.w == a.x)
827static bool alignY(
const SDL_Rect& a,
const SDL_Rect& b)
829 if (a.y + a.h == b.y)
831 if (b.y + b.h == a.y)
836std::vector<SDL_DisplayID>
837SdlContext::updateDisplayOffsetsForNeighbours(SDL_DisplayID
id,
838 const std::vector<SDL_DisplayID>& ignore)
840 auto first = _offsets.at(
id);
841 std::vector<SDL_DisplayID> neighbours;
843 for (
auto& entry : _offsets)
845 if (entry.first ==
id)
847 if (std::find(ignore.begin(), ignore.end(), entry.first) != ignore.end())
850 bool neighbor =
false;
851 if (alignX(entry.second.first, first.first))
853 if (entry.second.first.x < first.first.x)
854 entry.second.second.x = first.second.x - entry.second.second.w;
856 entry.second.second.x = first.second.x + first.second.w;
859 if (alignY(entry.second.first, first.first))
861 if (entry.second.first.y < first.first.y)
862 entry.second.second.y = first.second.y - entry.second.second.h;
864 entry.second.second.y = first.second.y + first.second.h;
869 neighbours.push_back(entry.first);
874void SdlContext::updateMonitorDataFromOffsets()
876 for (
auto& entry : _displays)
878 auto offsets = _offsets.at(entry.first);
879 entry.second.x = offsets.second.x;
880 entry.second.y = offsets.second.y;
883 for (
auto& entry : _windows)
885 const auto& monitor = _displays.at(entry.first);
886 entry.second.setMonitor(monitor);
890bool SdlContext::drawToWindow(
SdlWindow& window,
const std::vector<SDL_Rect>& rects)
895 auto gdi = context()->gdi;
898 auto size = window.rect();
900 std::unique_lock lock(_critical);
901 auto surface = _primary.get();
905 window.setOffsetX(0);
906 window.setOffsetY(0);
907 if (gdi->width < size.w)
909 window.setOffsetX((size.w - gdi->width) / 2);
911 if (gdi->height < size.h)
913 window.setOffsetY((size.h - gdi->height) / 2);
916 _localScale = {
static_cast<float>(size.w) /
static_cast<float>(gdi->width),
917 static_cast<float>(size.h) /
static_cast<float>(gdi->height) };
918 if (!window.drawScaledRects(surface, _localScale, rects))
923 SDL_Point offset{ 0, 0 };
925 offset = { window.offsetX(), window.offsetY() };
926 if (!window.drawRects(surface, offset, rects))
930 window.updateSurface();
934bool SdlContext::minimizeAllWindows()
936 for (
auto& w : _windows)
941int SdlContext::exitCode()
const
946SDL_PixelFormat SdlContext::pixelFormat()
const
948 return _sdlPixelFormat;
951bool SdlContext::addDisplayWindow(SDL_DisplayID
id)
954 SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS;
955 auto title = sdl::utils::windowTitle(context()->settings);
956 auto w = SdlWindow::create(
id, title, flags);
957 _windows.emplace(w.id(), std::move(w));
961bool SdlContext::removeDisplayWindow(SDL_DisplayID
id)
963 for (
auto& w : _windows)
965 if (w.second.displayIndex() ==
id)
966 _windows.erase(w.first);
971bool SdlContext::detectDisplays()
974 auto display = SDL_GetDisplays(&count);
977 for (
int x = 0; x < count; x++)
979 const auto id = display[x];
980 addOrUpdateDisplay(
id);
986rdpMonitor SdlContext::getDisplay(SDL_DisplayID
id)
const
988 return _displays.at(
id);
991std::vector<SDL_DisplayID> SdlContext::getDisplayIds()
const
993 std::vector<SDL_DisplayID> keys;
994 keys.reserve(_displays.size());
995 for (
const auto& entry : _displays)
997 keys.push_back(entry.first);
1002const SdlWindow* SdlContext::getWindowForId(SDL_WindowID
id)
const
1004 auto it = _windows.find(
id);
1005 if (it == _windows.end())
1010SdlWindow* SdlContext::getWindowForId(SDL_WindowID
id)
1012 auto it = _windows.find(
id);
1013 if (it == _windows.end())
1020 if (_windows.empty())
1022 return &_windows.begin()->second;
1030sdlInput& SdlContext::getInputChannelContext()
1035sdlClip& SdlContext::getClipboardChannelContext()
1045wLog* SdlContext::getWLog()
1050bool SdlContext::moveMouseTo(
const SDL_FPoint& pos)
1052 auto window = SDL_GetMouseFocus();
1056 const auto id = SDL_GetWindowID(window);
1057 const auto spos = pixelToScreen(
id, pos);
1058 SDL_WarpMouseInWindow(window, spos.x, spos.y);
1062bool SdlContext::handleEvent(
const SDL_MouseMotionEvent& ev)
1064 if (!getWindowForId(ev.windowID))
1068 if (!eventToPixelCoordinates(ev.windowID, copy))
1070 removeLocalScaling(copy.motion.x, copy.motion.y);
1071 removeLocalScaling(copy.motion.xrel, copy.motion.yrel);
1072 applyMonitorOffset(copy.motion.windowID, copy.motion.x, copy.motion.y);
1074 return SdlTouch::handleEvent(
this, copy.motion);
1077bool SdlContext::handleEvent(
const SDL_MouseWheelEvent& ev)
1079 if (!getWindowForId(ev.windowID))
1083 if (!eventToPixelCoordinates(ev.windowID, copy))
1085 removeLocalScaling(copy.wheel.mouse_x, copy.wheel.mouse_y);
1086 return SdlTouch::handleEvent(
this, copy.wheel);
1089bool SdlContext::handleEvent(
const SDL_WindowEvent& ev)
1091 if (!getDisplayChannelContext().handleEvent(ev))
1094 auto window = getWindowForId(ev.windowID);
1099 const auto& r = window->rect();
1100 const auto& b = window->bounds();
1101 const auto& scale = window->scale();
1102 const auto& orientation = window->orientation();
1103 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
1104 "%s: [%u] %dx%d-%dx%d {%dx%d-%dx%d}{scale=%f,orientation=%s}",
1105 sdl::utils::toString(ev.type).c_str(), ev.windowID, r.x, r.y, r.w, r.h, b.x,
1106 b.y, b.w, b.h,
static_cast<double>(scale),
1107 sdl::utils::toString(orientation).c_str());
1112 case SDL_EVENT_WINDOW_MOUSE_ENTER:
1113 return restoreCursor();
1114 case SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED:
1115 if (!resizeToScale(window))
1119 if (!window->fill())
1121 if (!drawToWindow(*window))
1123 if (!restoreCursor())
1127 case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
1128 if (!resizeToScale(window))
1130 if (!window->fill())
1132 if (!drawToWindow(*window))
1134 if (!restoreCursor())
1137 case SDL_EVENT_WINDOW_MOVED:
1139 auto r = window->rect();
1140 auto id = window->id();
1141 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"%u: %dx%d-%dx%d",
id, r.x, r.y, r.w, r.h);
1144 case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
1146 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"Window closed, terminating RDP session...");
1147 freerdp_abort_connect_context(context());
1156bool SdlContext::handleEvent(
const SDL_DisplayEvent& ev)
1158 if (!getDisplayChannelContext().handleEvent(ev))
1163 case SDL_EVENT_DISPLAY_REMOVED:
1168 if (!SDL_GetDisplayBounds(ev.displayID, &r))
1170 const auto name = SDL_GetDisplayName(ev.displayID);
1173 const auto orientation = SDL_GetCurrentDisplayOrientation(ev.displayID);
1174 const auto scale = SDL_GetDisplayContentScale(ev.displayID);
1175 const auto mode = SDL_GetCurrentDisplayMode(ev.displayID);
1179 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
1180 "%s: [%u, %s] %dx%d-%dx%d {orientation=%s, scale=%f}%s",
1181 sdl::utils::toString(ev.type).c_str(), ev.displayID, name, r.x, r.y, r.w,
1182 r.h, sdl::utils::toString(orientation).c_str(),
static_cast<double>(scale),
1183 sdl::utils::toString(mode).c_str());
1190bool SdlContext::handleEvent(
const SDL_MouseButtonEvent& ev)
1192 if (!getWindowForId(ev.windowID))
1194 SDL_Event copy = {};
1196 if (!eventToPixelCoordinates(ev.windowID, copy))
1198 removeLocalScaling(copy.button.x, copy.button.y);
1199 applyMonitorOffset(copy.button.windowID, copy.button.x, copy.button.y);
1200 return SdlTouch::handleEvent(
this, copy.button);
1203bool SdlContext::handleEvent(
const SDL_TouchFingerEvent& ev)
1205 if (!getWindowForId(ev.windowID))
1209 if (!eventToPixelCoordinates(ev.windowID, copy))
1211 removeLocalScaling(copy.tfinger.dx, copy.tfinger.dy);
1212 removeLocalScaling(copy.tfinger.x, copy.tfinger.y);
1213 applyMonitorOffset(copy.tfinger.windowID, copy.tfinger.x, copy.tfinger.y);
1214 return SdlTouch::handleEvent(
this, copy.tfinger);
1217void SdlContext::addOrUpdateDisplay(SDL_DisplayID
id)
1219 auto monitor = SdlWindow::query(
id,
false);
1220 _displays.emplace(
id, monitor);
1230 for (
auto& entry : _displays)
1233 std::ignore = SDL_GetDisplayBounds(entry.first, &bounds);
1236 pixel.w = entry.second.width;
1237 pixel.h = entry.second.height;
1238 _offsets.emplace(entry.first, std::pair{ bounds, pixel });
1245 const auto primary = SDL_GetPrimaryDisplay();
1246 std::vector<SDL_DisplayID> handled;
1247 handled.push_back(primary);
1249 auto neighbors = updateDisplayOffsetsForNeighbours(primary);
1250 while (!neighbors.empty())
1252 auto neighbor = neighbors.front();
1253 neighbors.erase(neighbors.begin());
1255 if (std::find(handled.begin(), handled.end(), neighbor) != handled.end())
1257 handled.push_back(neighbor);
1259 auto next = updateDisplayOffsetsForNeighbours(neighbor, handled);
1260 neighbors.insert(neighbors.end(), next.begin(), next.end());
1262 updateMonitorDataFromOffsets();
1265void SdlContext::deleteDisplay(SDL_DisplayID
id)
1267 _displays.erase(
id);
1270bool SdlContext::eventToPixelCoordinates(SDL_WindowID
id, SDL_Event& ev)
1272 auto w = getWindowForId(
id);
1277 auto renderer = w->renderer();
1280 return SDL_ConvertEventToRenderCoordinates(renderer, &ev);
1283SDL_FPoint SdlContext::applyLocalScaling(
const SDL_FPoint& val)
const
1285 if (!useLocalScale())
1289 rval.x *= _localScale.x;
1290 rval.y *= _localScale.y;
1294void SdlContext::removeLocalScaling(
float& x,
float& y)
const
1296 if (!useLocalScale())
1302SDL_FPoint SdlContext::screenToPixel(SDL_WindowID
id,
const SDL_FPoint& pos)
1304 auto w = getWindowForId(
id);
1309 auto renderer = w->renderer();
1314 if (!SDL_RenderCoordinatesFromWindow(renderer, pos.x, pos.y, &rpos.x, &rpos.y))
1316 removeLocalScaling(rpos.x, rpos.y);
1320SDL_FPoint SdlContext::pixelToScreen(SDL_WindowID
id,
const SDL_FPoint& pos)
1322 auto w = getWindowForId(
id);
1327 auto renderer = w->renderer();
1332 if (!SDL_RenderCoordinatesToWindow(renderer, pos.x, pos.y, &rpos.x, &rpos.y))
1334 return applyLocalScaling(rpos);
1337SDL_FRect SdlContext::pixelToScreen(SDL_WindowID
id,
const SDL_FRect& pos,
bool round)
1339 const auto fpos = pixelToScreen(
id, SDL_FPoint{ pos.x, pos.y });
1340 const auto size = pixelToScreen(
id, SDL_FPoint{ pos.w, pos.h });
1341 SDL_FRect r{ fpos.x, fpos.y, size.x, size.y };
1344 r.w = std::ceil(r.w);
1345 r.h = std::ceil(r.h);
1346 r.x = std::floor(r.x);
1347 r.y = std::floor(r.y);
1352bool SdlContext::handleEvent(
const SDL_Event& ev)
1354 if ((ev.type >= SDL_EVENT_DISPLAY_FIRST) && (ev.type <= SDL_EVENT_DISPLAY_LAST))
1356 const auto& dev = ev.display;
1357 return handleEvent(dev);
1359 if ((ev.type >= SDL_EVENT_WINDOW_FIRST) && (ev.type <= SDL_EVENT_WINDOW_LAST))
1361 const auto& wev = ev.window;
1362 return handleEvent(wev);
1366 case SDL_EVENT_RENDER_TARGETS_RESET:
1367 case SDL_EVENT_RENDER_DEVICE_RESET:
1368 case SDL_EVENT_WILL_ENTER_FOREGROUND:
1379 case SDL_EVENT_FINGER_DOWN:
1380 case SDL_EVENT_FINGER_UP:
1381 case SDL_EVENT_FINGER_MOTION:
1383 const auto& cev = ev.tfinger;
1384 return handleEvent(cev);
1386 case SDL_EVENT_MOUSE_MOTION:
1389 const auto& cev = ev.motion;
1390 return handleEvent(cev);
1392 case SDL_EVENT_MOUSE_BUTTON_DOWN:
1393 case SDL_EVENT_MOUSE_BUTTON_UP:
1395 const auto& cev = ev.button;
1396 return handleEvent(cev);
1398 case SDL_EVENT_MOUSE_WHEEL:
1400 const auto& cev = ev.wheel;
1401 return handleEvent(cev);
1403 case SDL_EVENT_CLIPBOARD_UPDATE:
1405 const auto& cev = ev.clipboard;
1406 return getClipboardChannelContext().handleEvent(cev);
1408 case SDL_EVENT_KEY_DOWN:
1409 case SDL_EVENT_KEY_UP:
1411 const auto& cev = ev.key;
1412 return getInputChannelContext().handleEvent(cev);
1421 return _args.data();
1424size_t SdlContext::argsCount()
const
1426 if (_args.size() <= 1)
1428 return _args.size() - 1;
1439 if (strcmp(arg->Name, sdl_allow_screensaver) == 0)
1441 if (arg->Value !=
nullptr)
1443 if (!SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER,
"1"))
1445 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
1446 "SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER) failed with %s",
1461std::vector<rdpPointer*>& SdlContext::pointers()
1463 return _valid_pointers;
1466bool SdlContext::contains(
const rdpPointer* ptr)
const
1468 for (
const auto& cur : _valid_pointers)
1476bool SdlContext::credentialsRead()
const
1478 return _credentialsRead;
1481void SdlContext::setCredentialsRead()
1483 _credentialsRead =
true;
1486bool SdlContext::resizeToScale(
SdlWindow* window)
1490 if (!useLocalScale())
1494 return window->resizeToScale();
1497bool SdlContext::useLocalScale()
const
1502 const auto dynResize =
1506 return !dynResize && !fs && !multimon;
1509bool SdlContext::drawToWindows(
const std::vector<SDL_Rect>& rects)
1511 for (
auto& window : _windows)
1513 if (!drawToWindow(window.second, rects))
1520BOOL SdlContext::desktopResize(rdpContext* context)
1522 rdpGdi* gdi =
nullptr;
1523 rdpSettings* settings =
nullptr;
1524 auto sdl = get_context(context);
1527 WINPR_ASSERT(context);
1529 settings = context->settings;
1530 WINPR_ASSERT(settings);
1532 std::unique_lock lock(
sdl->_critical);
1537 return sdl->createPrimary();
1541BOOL SdlContext::playSound(rdpContext* context,
const PLAY_SOUND_UPDATE* play_sound)
1544 WINPR_UNUSED(context);
1545 WINPR_UNUSED(play_sound);
1551BOOL SdlContext::beginPaint(rdpContext* context)
1553 auto gdi = context->gdi;
1555 WINPR_ASSERT(gdi->primary);
1557 HGDI_DC hdc = gdi->primary->hdc;
1563 WINPR_ASSERT(hwnd->invalid);
1564 hwnd->invalid->null = TRUE;
1570bool SdlContext::redraw(
bool suppress)
const
1575 auto gdi = context()->gdi;
1577 return gdi_send_suppress_output(gdi, suppress);
1580void SdlContext::setConnected(
bool val)
1585bool SdlContext::isConnected()
const
1590rdpContext* SdlContext::context()
const
1592 WINPR_ASSERT(_context);
1596rdpClientContext* SdlContext::common()
const
1598 return reinterpret_cast<rdpClientContext*
>(context());
1601bool SdlContext::setCursor(CursorType type)
1604 return restoreCursor();
1607bool SdlContext::setCursor(
const rdpPointer* cursor)
1609 std::unique_lock lock(_critical);
1610 if (!contains(cursor))
1613 _cursor = { sdl_Pointer_Copy(cursor), sdl_PointerFreeCopyAll };
1614 return setCursor(CURSOR_IMAGE);
1617rdpPointer* SdlContext::cursor()
const
1619 return _cursor.get();
1622bool SdlContext::restoreCursor()
1624 WLog_Print(getWLog(), WLOG_DEBUG,
"restore cursor: %d", _cursorType);
1625 switch (_cursorType)
1628 if (!SDL_HideCursor())
1630 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_HideCursor failed");
1634 setHasCursor(
false);
1637 case CURSOR_DEFAULT:
1639 auto def = SDL_GetDefaultCursor();
1640 if (!SDL_SetCursor(def))
1642 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_SetCursor(default=%p) failed",
1643 static_cast<void*
>(def));
1646 if (!SDL_ShowCursor())
1648 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_ShowCursor failed");
1656 return sdl_Pointer_Set_Process(
this);
1658 WLog_Print(getWLog(), WLOG_ERROR,
"Unknown cursorType %s",
1659 sdl::utils::toString(_cursorType).c_str());
1664void SdlContext::setMonitorIds(
const std::vector<SDL_DisplayID>& ids)
1666 _monitorIds.clear();
1669 _monitorIds.push_back(
id);
1673const std::vector<SDL_DisplayID>& SdlContext::monitorIds()
const
1678int64_t SdlContext::monitorId(uint32_t index)
const
1680 if (index >= _monitorIds.size())
1684 return _monitorIds.at(index);
1687void SdlContext::push(std::vector<SDL_Rect>&& rects)
1689 std::unique_lock lock(_queue_mux);
1690 _queue.emplace(std::move(rects));
1693std::vector<SDL_Rect> SdlContext::pop()
1695 std::unique_lock lock(_queue_mux);
1700 auto val = std::move(_queue.front());
1705bool SdlContext::setFullscreen(
bool enter,
bool forceOriginalDisplay)
1707 for (
const auto& window : _windows)
1709 if (!sdl_push_user_event(SDL_EVENT_USER_WINDOW_FULLSCREEN, &window.second, enter,
1710 forceOriginalDisplay))
1713 _fullscreen = enter;
1717bool SdlContext::setMinimized()
1719 return sdl_push_user_event(SDL_EVENT_USER_WINDOW_MINIMIZE);
1722bool SdlContext::grabMouse()
const
1727bool SdlContext::toggleGrabMouse()
1729 return setGrabMouse(!grabMouse());
1732bool SdlContext::setGrabMouse(
bool enter)
1738bool SdlContext::grabKeyboard()
const
1740 return _grabKeyboard;
1743bool SdlContext::toggleGrabKeyboard()
1745 return setGrabKeyboard(!grabKeyboard());
1748bool SdlContext::setGrabKeyboard(
bool enter)
1750 _grabKeyboard = enter;
1754bool SdlContext::setResizeable(
bool enable)
1756 const auto settings = context()->settings;
1759 bool use = (dyn && enable) || smart;
1761 for (
const auto& window : _windows)
1763 if (!sdl_push_user_event(SDL_EVENT_USER_WINDOW_RESIZEABLE, &window.second, use))
1771bool SdlContext::resizeable()
const
1776bool SdlContext::toggleResizeable()
1778 return setResizeable(!resizeable());
1781bool SdlContext::fullscreen()
const
1786bool SdlContext::toggleFullscreen()
1788 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.