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 if (alignX(entry.second.first, first.first))
846 if (entry.second.first.x < first.first.x)
847 entry.second.second.x = first.second.x - entry.second.second.w;
849 entry.second.second.x = first.second.x + first.second.w;
852 if (alignY(entry.second.first, first.first))
854 if (entry.second.first.y < first.first.y)
855 entry.second.second.y = first.second.y - entry.second.second.h;
857 entry.second.second.y = first.second.y + first.second.h;
862 neighbours.push_back(entry.first);
867void SdlContext::updateMonitorDataFromOffsets()
869 for (
auto& entry : _displays)
871 auto offsets = _offsets.at(entry.first);
872 entry.second.x = offsets.second.x;
873 entry.second.y = offsets.second.y;
876 for (
auto& entry : _windows)
878 const auto& monitor = _displays.at(entry.first);
879 entry.second.setMonitor(monitor);
883bool SdlContext::drawToWindow(
SdlWindow& window,
const std::vector<SDL_Rect>& rects)
888 auto gdi = context()->gdi;
891 auto size = window.rect();
893 std::unique_lock lock(_critical);
894 auto surface = _primary.get();
898 window.setOffsetX(0);
899 window.setOffsetY(0);
900 if (gdi->width < size.w)
902 window.setOffsetX((size.w - gdi->width) / 2);
904 if (gdi->height < size.h)
906 window.setOffsetY((size.h - gdi->height) / 2);
909 _localScale = {
static_cast<float>(size.w) /
static_cast<float>(gdi->width),
910 static_cast<float>(size.h) /
static_cast<float>(gdi->height) };
911 if (!window.drawScaledRects(surface, _localScale, rects))
916 SDL_Point offset{ 0, 0 };
918 offset = { window.offsetX(), window.offsetY() };
919 if (!window.drawRects(surface, offset, rects))
923 window.updateSurface();
927bool SdlContext::minimizeAllWindows()
929 for (
auto& w : _windows)
934int SdlContext::exitCode()
const
939SDL_PixelFormat SdlContext::pixelFormat()
const
941 return _sdlPixelFormat;
944bool SdlContext::addDisplayWindow(SDL_DisplayID
id)
947 SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS;
948 auto title = sdl::utils::windowTitle(context()->settings);
949 auto w = SdlWindow::create(
id, title, flags);
950 _windows.emplace(w.id(), std::move(w));
954bool SdlContext::removeDisplayWindow(SDL_DisplayID
id)
956 for (
auto& w : _windows)
958 if (w.second.displayIndex() ==
id)
959 _windows.erase(w.first);
964bool SdlContext::detectDisplays()
967 auto display = SDL_GetDisplays(&count);
970 for (
int x = 0; x < count; x++)
972 const auto id = display[x];
973 addOrUpdateDisplay(
id);
979rdpMonitor SdlContext::getDisplay(SDL_DisplayID
id)
const
981 return _displays.at(
id);
984std::vector<SDL_DisplayID> SdlContext::getDisplayIds()
const
986 std::vector<SDL_DisplayID> keys;
987 keys.reserve(_displays.size());
988 for (
const auto& entry : _displays)
990 keys.push_back(entry.first);
995const SdlWindow* SdlContext::getWindowForId(SDL_WindowID
id)
const
997 auto it = _windows.find(
id);
998 if (it == _windows.end())
1003SdlWindow* SdlContext::getWindowForId(SDL_WindowID
id)
1005 auto it = _windows.find(
id);
1006 if (it == _windows.end())
1013 if (_windows.empty())
1015 return &_windows.begin()->second;
1023sdlInput& SdlContext::getInputChannelContext()
1028sdlClip& SdlContext::getClipboardChannelContext()
1033SdlRail& SdlContext::getRailChannelContext()
1043wLog* SdlContext::getWLog()
1048bool SdlContext::moveMouseTo(
const SDL_FPoint& pos)
1050 auto window = SDL_GetMouseFocus();
1054 const auto id = SDL_GetWindowID(window);
1055 const auto spos = pixelToScreen(
id, pos);
1056 SDL_WarpMouseInWindow(window, spos.x, spos.y);
1060bool SdlContext::handleEvent(
const SDL_MouseMotionEvent& ev)
1065 if (_rail.enabled() && _rail.suppressServerMotion(ev.windowID))
1067 if (!(SDL_GetGlobalMouseState(
nullptr,
nullptr) & SDL_BUTTON_LMASK))
1068 _rail.completeLocalMoveIfPending();
1071 if (_rail.enabled() && _rail.translateToServer(ev.windowID, copy.motion.x, copy.motion.y))
1073 _rail.noteServerPointer(copy.motion.x, copy.motion.y);
1074 return SdlTouch::handleEvent(
this, copy.motion);
1077 if (!getWindowForId(ev.windowID))
1079 if (!eventToPixelCoordinates(ev.windowID, copy))
1081 removeLocalScaling(copy.motion.x, copy.motion.y);
1082 removeLocalScaling(copy.motion.xrel, copy.motion.yrel);
1083 applyMonitorOffset(copy.motion.windowID, copy.motion.x, copy.motion.y);
1085 return SdlTouch::handleEvent(
this, copy.motion);
1088bool SdlContext::handleEvent(
const SDL_MouseWheelEvent& ev)
1092 if (_rail.enabled() &&
1093 _rail.translateToServer(ev.windowID, copy.wheel.mouse_x, copy.wheel.mouse_y))
1094 return SdlTouch::handleEvent(
this, copy.wheel);
1096 if (!getWindowForId(ev.windowID))
1098 if (!eventToPixelCoordinates(ev.windowID, copy))
1100 removeLocalScaling(copy.wheel.mouse_x, copy.wheel.mouse_y);
1101 return SdlTouch::handleEvent(
this, copy.wheel);
1104bool SdlContext::handleEvent(
const SDL_WindowEvent& ev)
1106 if (!getDisplayChannelContext().handleEvent(ev))
1109 auto window = getWindowForId(ev.windowID);
1113 if (_rail.enabled() && _rail.ownsWindow(ev.windowID))
1117 case SDL_EVENT_WINDOW_MOUSE_ENTER:
1119 if (!(SDL_GetGlobalMouseState(
nullptr,
nullptr) & SDL_BUTTON_LMASK))
1120 _rail.completeLocalMoveIfPending();
1121 _rail.completeWaylandResize();
1123 return restoreCursor();
1124 case SDL_EVENT_WINDOW_MOUSE_LEAVE:
1126 _rail.noteResizeGrab(ev.windowID);
1128 case SDL_EVENT_WINDOW_EXPOSED:
1131 if (!_rail.suppressServerInput(ev.windowID))
1132 _rail.invalidateWindow(ev.windowID);
1134 case SDL_EVENT_WINDOW_MAXIMIZED:
1136 _rail.completeLocalMoveIfPending();
1137 _rail.handleMaximized(ev.windowID);
1139 case SDL_EVENT_WINDOW_MINIMIZED:
1140 _rail.handleMinimized(ev.windowID);
1142 case SDL_EVENT_WINDOW_RESTORED:
1143 _rail.handleRestored(ev.windowID);
1145 case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
1147 _rail.handleClose(ev.windowID);
1149 case SDL_EVENT_WINDOW_FOCUS_GAINED:
1150 _rail.handleFocus(ev.windowID,
true);
1152 case SDL_EVENT_WINDOW_FOCUS_LOST:
1153 _rail.handleFocus(ev.windowID,
false);
1155 case SDL_EVENT_WINDOW_MOVED:
1156 if (!_rail.suppressServerInput(ev.windowID))
1157 _rail.syncGeometry(ev.windowID);
1159 case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
1162 _rail.noteDragResize(ev.windowID, ev.data1, ev.data2);
1163 _rail.syncGeometry(ev.windowID);
1164 _rail.handleWaylandResize(ev.windowID);
1165 std::ignore = drawToWindows({});
1175 const auto& r = window->rect();
1176 const auto& b = window->bounds();
1177 const auto& scale = window->scale();
1178 const auto& orientation = window->orientation();
1179 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
1180 "%s: [%u] %dx%d-%dx%d {%dx%d-%dx%d}{scale=%f,orientation=%s}",
1181 sdl::utils::toString(ev.type).c_str(), ev.windowID, r.x, r.y, r.w, r.h, b.x,
1182 b.y, b.w, b.h,
static_cast<double>(scale),
1183 sdl::utils::toString(orientation).c_str());
1188 case SDL_EVENT_WINDOW_MOUSE_ENTER:
1189 return restoreCursor();
1190 case SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED:
1191 if (!resizeToScale(window))
1195 if (!window->fill())
1197 if (!drawToWindow(*window))
1199 if (!restoreCursor())
1203 case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
1204 if (!resizeToScale(window))
1206 if (!window->fill())
1208 if (!drawToWindow(*window))
1210 if (!restoreCursor())
1213 case SDL_EVENT_WINDOW_MOVED:
1215 auto r = window->rect();
1216 auto id = window->id();
1217 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"%u: %dx%d-%dx%d",
id, r.x, r.y, r.w, r.h);
1220 case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
1222 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"Window closed, terminating RDP session...");
1223 freerdp_abort_connect_context(context());
1232bool SdlContext::handleEvent(
const SDL_DisplayEvent& ev)
1234 if (!getDisplayChannelContext().handleEvent(ev))
1239 case SDL_EVENT_DISPLAY_REMOVED:
1244 if (!SDL_GetDisplayBounds(ev.displayID, &r))
1246 const auto name = SDL_GetDisplayName(ev.displayID);
1249 const auto orientation = SDL_GetCurrentDisplayOrientation(ev.displayID);
1250 const auto scale = SDL_GetDisplayContentScale(ev.displayID);
1251 const auto mode = SDL_GetCurrentDisplayMode(ev.displayID);
1255 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
1256 "%s: [%u, %s] %dx%d-%dx%d {orientation=%s, scale=%f}%s",
1257 sdl::utils::toString(ev.type).c_str(), ev.displayID, name, r.x, r.y, r.w,
1258 r.h, sdl::utils::toString(orientation).c_str(),
static_cast<double>(scale),
1259 sdl::utils::toString(mode).c_str());
1266bool SdlContext::handleEvent(
const SDL_MouseButtonEvent& ev)
1268 SDL_Event copy = {};
1270 if (_rail.enabled())
1273 const bool suppress = _rail.suppressServerInput(ev.windowID);
1274 if (ev.type == SDL_EVENT_MOUSE_BUTTON_UP)
1275 _rail.completeLocalMoveIfPending();
1278 if (ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN)
1279 _rail.completeWaylandResize(
true);
1281 if (ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN)
1282 _rail.ensureActive(ev.windowID);
1285 if (_rail.translateToServer(ev.windowID, copy.button.x, copy.button.y))
1289 if ((ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN) && (ev.button == SDL_BUTTON_LEFT))
1290 _rail.noteLeftPress(copy.button.x, copy.button.y);
1291 return SdlTouch::handleEvent(
this, copy.button);
1295 if (!getWindowForId(ev.windowID))
1297 if (!eventToPixelCoordinates(ev.windowID, copy))
1299 removeLocalScaling(copy.button.x, copy.button.y);
1300 applyMonitorOffset(copy.button.windowID, copy.button.x, copy.button.y);
1301 return SdlTouch::handleEvent(
this, copy.button);
1304bool SdlContext::handleEvent(
const SDL_TouchFingerEvent& ev)
1306 if (!getWindowForId(ev.windowID))
1310 if (!eventToPixelCoordinates(ev.windowID, copy))
1312 removeLocalScaling(copy.tfinger.dx, copy.tfinger.dy);
1313 removeLocalScaling(copy.tfinger.x, copy.tfinger.y);
1314 applyMonitorOffset(copy.tfinger.windowID, copy.tfinger.x, copy.tfinger.y);
1315 return SdlTouch::handleEvent(
this, copy.tfinger);
1318void SdlContext::addOrUpdateDisplay(SDL_DisplayID
id)
1320 auto monitor = SdlWindow::query(
id,
false);
1321 _displays.emplace(
id, monitor);
1331 for (
auto& entry : _displays)
1334 std::ignore = SDL_GetDisplayBounds(entry.first, &bounds);
1337 pixel.w = entry.second.width;
1338 pixel.h = entry.second.height;
1339 _offsets.emplace(entry.first, std::pair{ bounds, pixel });
1346 const auto primary = SDL_GetPrimaryDisplay();
1347 std::vector<SDL_DisplayID> handled;
1348 handled.push_back(primary);
1350 auto neighbors = updateDisplayOffsetsForNeighbours(primary);
1351 while (!neighbors.empty())
1353 auto neighbor = neighbors.front();
1354 neighbors.erase(neighbors.begin());
1356 if (std::find(handled.begin(), handled.end(), neighbor) != handled.end())
1358 handled.push_back(neighbor);
1360 auto next = updateDisplayOffsetsForNeighbours(neighbor, handled);
1361 neighbors.insert(neighbors.end(), next.begin(), next.end());
1363 updateMonitorDataFromOffsets();
1366void SdlContext::deleteDisplay(SDL_DisplayID
id)
1368 _displays.erase(
id);
1371bool SdlContext::eventToPixelCoordinates(SDL_WindowID
id, SDL_Event& ev)
1373 auto w = getWindowForId(
id);
1378 auto renderer = w->renderer();
1381 return SDL_ConvertEventToRenderCoordinates(renderer, &ev);
1384SDL_FPoint SdlContext::applyLocalScaling(
const SDL_FPoint& val)
const
1386 if (!useLocalScale())
1390 rval.x *= _localScale.x;
1391 rval.y *= _localScale.y;
1395void SdlContext::removeLocalScaling(
float& x,
float& y)
const
1397 if (!useLocalScale())
1403SDL_FPoint SdlContext::screenToPixel(SDL_WindowID
id,
const SDL_FPoint& pos)
1405 auto w = getWindowForId(
id);
1409 if (_rail.enabled() && _rail.ownsWindow(
id))
1415 auto renderer = w->renderer();
1420 if (!SDL_RenderCoordinatesFromWindow(renderer, pos.x, pos.y, &rpos.x, &rpos.y))
1422 removeLocalScaling(rpos.x, rpos.y);
1426SDL_FPoint SdlContext::pixelToScreen(SDL_WindowID
id,
const SDL_FPoint& pos)
1428 auto w = getWindowForId(
id);
1431 if (_rail.enabled() && _rail.ownsWindow(
id))
1437 auto renderer = w->renderer();
1442 if (!SDL_RenderCoordinatesToWindow(renderer, pos.x, pos.y, &rpos.x, &rpos.y))
1444 return applyLocalScaling(rpos);
1447SDL_FRect SdlContext::pixelToScreen(SDL_WindowID
id,
const SDL_FRect& pos,
bool round)
1449 const auto fpos = pixelToScreen(
id, SDL_FPoint{ pos.x, pos.y });
1450 const auto size = pixelToScreen(
id, SDL_FPoint{ pos.w, pos.h });
1451 SDL_FRect r{ fpos.x, fpos.y, size.x, size.y };
1454 r.w = std::ceil(r.w);
1455 r.h = std::ceil(r.h);
1456 r.x = std::floor(r.x);
1457 r.y = std::floor(r.y);
1462bool SdlContext::handleEvent(
const SDL_Event& ev)
1464 if ((ev.type >= SDL_EVENT_DISPLAY_FIRST) && (ev.type <= SDL_EVENT_DISPLAY_LAST))
1466 const auto& dev = ev.display;
1467 return handleEvent(dev);
1469 if ((ev.type >= SDL_EVENT_WINDOW_FIRST) && (ev.type <= SDL_EVENT_WINDOW_LAST))
1471 const auto& wev = ev.window;
1472 return handleEvent(wev);
1476 case SDL_EVENT_RENDER_TARGETS_RESET:
1477 case SDL_EVENT_RENDER_DEVICE_RESET:
1478 case SDL_EVENT_WILL_ENTER_FOREGROUND:
1489 case SDL_EVENT_FINGER_DOWN:
1490 case SDL_EVENT_FINGER_UP:
1491 case SDL_EVENT_FINGER_MOTION:
1493 const auto& cev = ev.tfinger;
1494 return handleEvent(cev);
1496 case SDL_EVENT_MOUSE_MOTION:
1499 const auto& cev = ev.motion;
1500 return handleEvent(cev);
1502 case SDL_EVENT_MOUSE_BUTTON_DOWN:
1503 case SDL_EVENT_MOUSE_BUTTON_UP:
1505 const auto& cev = ev.button;
1506 return handleEvent(cev);
1508 case SDL_EVENT_MOUSE_WHEEL:
1510 const auto& cev = ev.wheel;
1511 return handleEvent(cev);
1513 case SDL_EVENT_CLIPBOARD_UPDATE:
1515 const auto& cev = ev.clipboard;
1516 return getClipboardChannelContext().handleEvent(cev);
1518 case SDL_EVENT_KEY_DOWN:
1519 case SDL_EVENT_KEY_UP:
1521 const auto& cev = ev.key;
1522 return getInputChannelContext().handleEvent(cev);
1531 return _args.data();
1534size_t SdlContext::argsCount()
const
1536 if (_args.size() <= 1)
1538 return _args.size() - 1;
1549 if (strcmp(arg->Name, sdl_allow_screensaver) == 0)
1551 if (arg->Value !=
nullptr)
1553 if (!SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER,
"1"))
1555 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
1556 "SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER) failed with %s",
1571std::vector<rdpPointer*>& SdlContext::pointers()
1573 return _valid_pointers;
1576bool SdlContext::contains(
const rdpPointer* ptr)
const
1578 for (
const auto& cur : _valid_pointers)
1586bool SdlContext::credentialsRead()
const
1588 return _credentialsRead;
1591void SdlContext::setCredentialsRead()
1593 _credentialsRead =
true;
1596bool SdlContext::resizeToScale(
SdlWindow* window)
1600 if (!useLocalScale())
1604 return window->resizeToScale();
1607bool SdlContext::useLocalScale()
const
1612 const auto dynResize =
1616 return !dynResize && !fs && !multimon;
1619bool SdlContext::drawToWindows(
const std::vector<SDL_Rect>& rects)
1622 if (_rail.enabled())
1624 for (
auto& window : _windows)
1626 if ((SDL_GetWindowFlags(window.second.window()) & SDL_WINDOW_HIDDEN) == 0)
1627 SDL_HideWindow(window.second.window());
1630 std::unique_lock lock(_critical);
1631 _rail.paint(_primary.get(), pixelFormat(), rects);
1637 bool firstShow =
false;
1638 for (
auto& window : _windows)
1640 if (SDL_GetWindowFlags(window.second.window()) & SDL_WINDOW_HIDDEN)
1642 SDL_ShowWindow(window.second.window());
1643 SDL_RaiseWindow(window.second.window());
1648 if (rects.empty() && !firstShow)
1651 std::vector<SDL_Rect> drawRects = rects;
1653 std::unique_lock lock(_critical);
1654 if ((drawRects.empty() || firstShow) && _primary)
1655 drawRects = { { 0, 0, _primary->w, _primary->h } };
1658 for (
auto& window : _windows)
1660 if (!drawToWindow(window.second, drawRects))
1667BOOL SdlContext::desktopResize(rdpContext* context)
1669 rdpGdi* gdi =
nullptr;
1670 rdpSettings* settings =
nullptr;
1671 auto sdl = get_context(context);
1674 WINPR_ASSERT(context);
1676 settings = context->settings;
1677 WINPR_ASSERT(settings);
1679 std::unique_lock lock(
sdl->_critical);
1684 return sdl->createPrimary();
1688BOOL SdlContext::playSound(rdpContext* context,
const PLAY_SOUND_UPDATE* play_sound)
1691 WINPR_UNUSED(context);
1692 WINPR_UNUSED(play_sound);
1698BOOL SdlContext::beginPaint(rdpContext* context)
1700 auto gdi = context->gdi;
1702 WINPR_ASSERT(gdi->primary);
1704 HGDI_DC hdc = gdi->primary->hdc;
1710 WINPR_ASSERT(hwnd->invalid);
1711 hwnd->invalid->null = TRUE;
1717bool SdlContext::redraw(
bool suppress)
const
1723 if (suppress && _rail.enabled())
1726 auto gdi = context()->gdi;
1728 return gdi_send_suppress_output(gdi, suppress);
1731void SdlContext::setConnected(
bool val)
1736bool SdlContext::isConnected()
const
1741rdpContext* SdlContext::context()
const
1743 WINPR_ASSERT(_context);
1747rdpClientContext* SdlContext::common()
const
1749 return reinterpret_cast<rdpClientContext*
>(context());
1752bool SdlContext::setCursor(CursorType type)
1755 return restoreCursor();
1758bool SdlContext::setCursor(
const rdpPointer* cursor)
1760 std::unique_lock lock(_critical);
1761 if (!contains(cursor))
1764 _cursor = { sdl_Pointer_Copy(cursor), sdl_PointerFreeCopyAll };
1765 return setCursor(CURSOR_IMAGE);
1768rdpPointer* SdlContext::cursor()
const
1770 return _cursor.get();
1773bool SdlContext::restoreCursor()
1775 WLog_Print(getWLog(), WLOG_TRACE,
"restore cursor: %d", _cursorType);
1776 switch (_cursorType)
1779 if (!SDL_HideCursor())
1781 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_HideCursor failed");
1785 setHasCursor(
false);
1788 case CURSOR_DEFAULT:
1790 auto def = SDL_GetDefaultCursor();
1791 if (!SDL_SetCursor(def))
1793 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_SetCursor(default=%p) failed",
1794 static_cast<void*
>(def));
1797 if (!SDL_ShowCursor())
1799 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_ShowCursor failed");
1807 return sdl_Pointer_Set_Process(
this);
1809 WLog_Print(getWLog(), WLOG_ERROR,
"Unknown cursorType %s",
1810 sdl::utils::toString(_cursorType).c_str());
1815void SdlContext::setMonitorIds(
const std::vector<SDL_DisplayID>& ids)
1817 _monitorIds.clear();
1820 _monitorIds.push_back(
id);
1824const std::vector<SDL_DisplayID>& SdlContext::monitorIds()
const
1829int64_t SdlContext::monitorId(uint32_t index)
const
1831 if (index >= _monitorIds.size())
1835 return _monitorIds.at(index);
1838void SdlContext::push(std::vector<SDL_Rect>&& rects)
1840 std::unique_lock lock(_queue_mux);
1841 _queue.emplace(std::move(rects));
1844std::vector<SDL_Rect> SdlContext::pop()
1846 std::unique_lock lock(_queue_mux);
1851 auto val = std::move(_queue.front());
1856bool SdlContext::setFullscreen(
bool enter,
bool forceOriginalDisplay)
1858 for (
const auto& window : _windows)
1860 if (!sdl_push_user_event(SDL_EVENT_USER_WINDOW_FULLSCREEN, &window.second, enter,
1861 forceOriginalDisplay))
1864 _fullscreen = enter;
1868bool SdlContext::setMinimized()
1870 return sdl_push_user_event(SDL_EVENT_USER_WINDOW_MINIMIZE);
1873bool SdlContext::grabMouse()
const
1878bool SdlContext::toggleGrabMouse()
1880 return setGrabMouse(!grabMouse());
1883bool SdlContext::setGrabMouse(
bool enter)
1889bool SdlContext::grabKeyboard()
const
1891 return _grabKeyboard;
1894bool SdlContext::toggleGrabKeyboard()
1896 return setGrabKeyboard(!grabKeyboard());
1899bool SdlContext::setGrabKeyboard(
bool enter)
1901 _grabKeyboard = enter;
1905bool SdlContext::setResizeable(
bool enable)
1907 const auto settings = context()->settings;
1910 bool use = (dyn && enable) || smart;
1912 for (
const auto& window : _windows)
1914 if (!sdl_push_user_event(SDL_EVENT_USER_WINDOW_RESIZEABLE, &window.second, use))
1922bool SdlContext::resizeable()
const
1927bool SdlContext::toggleResizeable()
1929 return setResizeable(!resizeable());
1932bool SdlContext::fullscreen()
const
1937bool SdlContext::toggleFullscreen()
1939 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.