25#include "sdl_context.hpp"
26#include "sdl_config.hpp"
27#include "sdl_channels.hpp"
28#include "sdl_input_mapping.hpp"
29#include "sdl_monitor.hpp"
30#include "sdl_display_offsets.hpp"
31#include "sdl_pointer.hpp"
32#include "sdl_touch.hpp"
33#include "sdl_prefs.hpp"
34#include "sdl_utils.hpp"
36#include <sdl_common_utils.hpp>
37#include <scoped_guard.hpp>
39#include "dialogs/sdl_dialogs.hpp"
40#include "sdl_render_service.hpp"
42#include <freerdp/client/aad_helper.h>
43#include <freerdp/client/geometry.h>
44#include <freerdp/gdi/gdi.h>
45#include <freerdp/client/monitor.h>
47static constexpr auto sdl_allow_screensaver =
"sdl-allow-screensaver";
48static constexpr auto sdl_connection_dialog =
"sdl-connection-dialog";
49static constexpr auto sdl_info =
"sdl-info";
51SdlContext::SdlContext(rdpContext* context)
52 : _context(context), _log(WLog_Get(CLIENT_TAG(
"SDL"))), _cursor(nullptr, sdl_Pointer_FreeCopy),
53 _rdpThreadRunning(false), _primary(nullptr, SDL_DestroySurface), _disp(this), _input(this),
54 _clip(this), _rail(this), _dialog(_log)
56 WINPR_ASSERT(context);
59 auto instance = _context->instance;
60 WINPR_ASSERT(instance);
62 instance->PreConnect = preConnect;
63 instance->PostConnect = postConnect;
64 instance->PostDisconnect = postDisconnect;
65 instance->PostFinalDisconnect = postFinalDisconnect;
66 instance->AuthenticateEx = sdl_authenticate_ex;
67 instance->VerifyCertificateEx = sdl_verify_certificate_ex;
68 instance->VerifyChangedCertificateEx = sdl_verify_changed_certificate_ex;
69 instance->LogonErrorInfo = sdl_logon_error_info;
70 instance->PresentGatewayMessage = sdl_present_gateway_message;
71 instance->ChooseSmartcard = sdl_choose_smartcard;
72 instance->RetryDialog = sdl_retry_dialog;
73 instance->GetAccessToken = client_failsafe_get_access_token;
77 _args.push_back({ sdl_allow_screensaver, COMMAND_LINE_VALUE_BOOL,
nullptr, BoolValueFalse,
79 "Allow local screensaver to activate (default: on for RemoteApp)" });
81 _args.push_back({ sdl_connection_dialog, COMMAND_LINE_VALUE_BOOL,
nullptr,
"on",
nullptr, -1,
82 nullptr,
"the connection dialog with progress and errors" });
83 _args.push_back({ sdl_info, COMMAND_LINE_VALUE_BOOL,
nullptr, BoolValueFalse,
nullptr, -1,
85 "the stats and info overlay from the start (its hotkey SDL_Info, default "
86 "<modifier>+I, shows and hides it)" });
89 _args.push_back({
nullptr, 0,
nullptr,
nullptr,
nullptr, -1,
nullptr,
nullptr });
92 _context->windowInfoService = freerdp_client_window_info_service_new(&source);
93 if (!_context->windowInfoService)
94 WLog_Print(_log, WLOG_WARN,
"no window info service: channels won't know our windows");
95 _context->bitmapRenderService = sdl_render_service_new(
this);
96 if (!_context->bitmapRenderService)
97 WLog_Print(_log, WLOG_WARN,
"no bitmap render service: no redirected video");
100SdlContext::~SdlContext()
103 if (_context->windowInfoService)
105 freerdp_client_window_info_service_detach(_context->windowInfoService);
106 _context->windowInfoService->Release();
107 _context->windowInfoService =
nullptr;
109 if (_context->bitmapRenderService)
111 sdl_render_service_detach(_context->bitmapRenderService);
112 _context->bitmapRenderService->Release();
113 _context->bitmapRenderService =
nullptr;
116 std::scoped_lock lock(_rendererLock);
117 for (
auto& kv : _renderers)
119 if (kv.second.callback)
120 kv.second.callback->Release();
125std::optional<bool> SdlContext::allowScreenSaver()
const
127 return _allowScreenSaver;
130void SdlContext::setHasCursor(
bool val)
132 this->_cursor_visible = val;
135bool SdlContext::hasCursor()
const
137 return _cursor_visible;
140void SdlContext::setMetadata()
143 if (!wmclass || (strlen(wmclass) == 0))
144 wmclass = SDL_CLIENT_UUID;
146 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_IDENTIFIER_STRING, wmclass);
147#if !defined(__APPLE__)
151 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_NAME_STRING, SDL_CLIENT_NAME);
153 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_VERSION_STRING, SDL_CLIENT_VERSION);
154 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_CREATOR_STRING, SDL_CLIENT_VENDOR);
155 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_COPYRIGHT_STRING, SDL_CLIENT_COPYRIGHT);
156 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_URL_STRING, SDL_CLIENT_URL);
157 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_TYPE_STRING, SDL_CLIENT_TYPE);
160int SdlContext::start()
162 _thread = std::thread(rdpThreadRun,
this);
166int SdlContext::join()
170 HANDLE
event = freerdp_abort_event(context());
171 if (!SetEvent(event))
178void SdlContext::cleanup()
180 std::unique_lock lock(_critical);
186bool SdlContext::shallAbort(
bool ignoreDialogs)
188 std::unique_lock lock(_critical);
189 if (freerdp_shall_disconnect_context(context()))
193 if (_rdpThreadRunning)
195 return !getDialog().isRunning();
202BOOL SdlContext::preConnect(freerdp* instance)
204 WINPR_ASSERT(instance);
205 WINPR_ASSERT(instance->context);
207 auto sdl = get_context(instance->context);
209 auto settings = instance->context->settings;
210 WINPR_ASSERT(settings);
225 if (PubSub_SubscribeChannelConnected(instance->context->pubSub,
226 sdl_OnChannelConnectedEventHandler) < 0)
228 if (PubSub_SubscribeChannelDisconnected(instance->context->pubSub,
229 sdl_OnChannelDisconnectedEventHandler) < 0)
231 if (PubSub_SubscribeUserNotification(instance->context->pubSub,
232 sdl_OnUserNotificationEventHandler) < 0)
238 UINT32 maxHeight = 0;
240 if (!sdl_detect_monitors(sdl, &maxWidth, &maxHeight))
251 if (coversDisplays && ((overrides & FREERDP_MONITOR_OVERRIDE_DESKTOP_SCALE) == 0) &&
257 auto monitor =
static_cast<const rdpMonitor*
>(
258 freerdp_settings_get_pointer_array(settings, FreeRDP_MonitorDefArray, x));
259 if (monitor && monitor->is_primary)
260 scale = monitor->attributes.desktopScaleFactor;
262 if ((scale == 0) && !sdl->monitorIds().empty())
264 auto monitor = sdl->getDisplay(sdl->monitorIds().front());
265 sdl->applyMonitorScaleOverride(monitor);
266 scale = monitor.attributes.desktopScaleFactor;
268 if ((scale >= 100) && (scale <= 500))
276 if ((overrides == 0) &&
281 if ((maxWidth != 0) && (maxHeight != 0) &&
284 WLog_Print(sdl->getWLog(), WLOG_INFO,
"Update size to %ux%u", maxWidth, maxHeight);
299 if (sm && (sw > 0) && (sh > 0))
303 WLog_Print(sdl->getWLog(), WLOG_WARN,
304 "/smart-sizing and /multimon are currently not supported, ignoring "
323 WLog_Print(sdl->getWLog(), WLOG_INFO,
324 "auth-only, but no password set. Please provide one.");
331 WLog_Print(sdl->getWLog(), WLOG_INFO,
"Authentication only. Don't connect SDL.");
334 if (!sdl->getInputChannelContext().initialize())
337 sdl->_credentialsRead =
false;
340 auto prefs = SdlPref::instance();
341 auto dialog = prefs->get_bool(
"SDL_ConnectionDialog",
true);
342 if (sdl->_connectionDialog && prefs->is_commandline_override_allowed())
343 dialog = *sdl->_connectionDialog;
346 sdl->getDialog().create(instance->context);
350 if (!title || (strlen(title) == 0))
352 sdl->getDialog().setTitle(
"Connecting to '%s'", title);
353 sdl->getDialog().showInfo(
"The connection is being established\n\nPlease wait...");
368BOOL SdlContext::postConnect(freerdp* instance)
370 WINPR_ASSERT(instance);
372 auto context = instance->context;
373 WINPR_ASSERT(context);
375 auto sdl = get_context(context);
378 sdl->getDialog().show(
false);
385 WLog_Print(sdl->getWLog(), WLOG_INFO,
386 "auth-only, but no password set. Please provide one.");
390 WLog_Print(sdl->getWLog(), WLOG_INFO,
"Authentication only. Don't connect to X.");
394 if (!sdl->waitForWindowsCreated())
397 sdl->_sdlPixelFormat = SDL_PIXELFORMAT_BGRA32;
398 if (!gdi_init(instance, PIXEL_FORMAT_BGRA32))
401 if (!sdl->createPrimary())
404 if (!sdl_register_pointer(instance->context->graphics))
407 WINPR_ASSERT(context->update);
409 context->update->BeginPaint = beginPaint;
410 context->update->EndPaint = endPaint;
411 context->update->PlaySound = playSound;
412 context->update->DesktopResize = desktopResize;
413 context->update->SetKeyboardIndicators = sdlInput::keyboard_set_indicators;
414 context->update->SetKeyboardImeStatus = sdlInput::keyboard_set_ime_status;
416 if (!sdl->setResizeable(
false))
422 sdl->setConnected(
true);
424 return sdl->_overlay.connected();
430void SdlContext::postDisconnect(freerdp* instance)
435 if (!instance->context)
438 auto sdl = get_context(instance->context);
439 sdl->setConnected(
false);
444void SdlContext::postFinalDisconnect(freerdp* instance)
449 if (!instance->context)
452 PubSub_UnsubscribeChannelConnected(instance->context->pubSub,
453 sdl_OnChannelConnectedEventHandler);
454 PubSub_UnsubscribeChannelDisconnected(instance->context->pubSub,
455 sdl_OnChannelDisconnectedEventHandler);
456 PubSub_UnsubscribeUserNotification(instance->context->pubSub,
457 sdl_OnUserNotificationEventHandler);
461bool SdlContext::createPrimary()
463 auto gdi = context()->gdi;
466 _primary = SDLSurfacePtr(
467 SDL_CreateSurfaceFrom(
static_cast<int>(gdi->width),
static_cast<int>(gdi->height),
468 pixelFormat(), gdi->primary_buffer,
static_cast<int>(gdi->stride)),
473 SDL_SetSurfaceBlendMode(_primary.get(), SDL_BLENDMODE_NONE);
474 SDL_Rect surfaceRect = { 0, 0, gdi->width, gdi->height };
475 SDL_FillSurfaceRect(_primary.get(), &surfaceRect,
476 SDL_MapSurfaceRGBA(_primary.get(), 0, 0, 0, 0xff));
481bool SdlContext::createWindows()
483 auto settings = context()->settings;
484 const auto& title = windowTitle();
486 ScopeGuard guard1([&]() { _windowsCreatedEvent.set(); });
492 auto monitorFor = [&](UINT32 index, int64_t id)
494 for (UINT32 y = 0; y < windowCount; y++)
496 auto cur =
static_cast<rdpMonitor*
>(
497 freerdp_settings_get_pointer_array_writable(settings, FreeRDP_MonitorDefArray, y));
498 if (cur && (
static_cast<int64_t
>(cur->orig_screen) ==
id))
501 return static_cast<rdpMonitor*
>(
502 freerdp_settings_get_pointer_array_writable(settings, FreeRDP_MonitorDefArray, index));
507 for (UINT32 x = 0; x < windowCount; x++)
509 auto id = monitorId(x);
513 auto monitor = monitorFor(x,
id);
515 originX = std::min<Sint32>(monitor->x, originX);
516 originY = std::min<Sint32>(monitor->y, originY);
519 for (UINT32 x = 0; x < windowCount; x++)
521 auto id = monitorId(x);
525 auto monitor = monitorFor(x,
id);
527 Uint32 w = WINPR_ASSERTING_INT_CAST(Uint32, monitor->width);
528 Uint32 h = WINPR_ASSERTING_INT_CAST(Uint32, monitor->height);
532 if (_windowWidth > 0)
537 if (_windowHeight > 0)
543 Uint32 flags = SDL_WINDOW_HIGH_PIXEL_DENSITY;
548 flags |= SDL_WINDOW_FULLSCREEN;
553 flags |= SDL_WINDOW_BORDERLESS;
557 flags |= SDL_WINDOW_BORDERLESS;
561 flags |= SDL_WINDOW_HIDDEN;
563 auto did = WINPR_ASSERTING_INT_CAST(SDL_DisplayID,
id);
564 auto window = SdlWindow::create(did, title, flags, w, h);
568 window.setOffsetX(originX - monitor->x);
569 window.setOffsetY(originY - monitor->y);
570 window.setLayoutPosition({ monitor->x, monitor->y });
573 _windows.insert({ window.id(), std::move(window) });
580#if defined(__EMSCRIPTEN__)
582extern "C" int freerdp_web_monitors_js(int32_t* edges,
int max);
588static std::vector<rdpMonitor> sdl_web_monitors(
const rdpMonitor& canvas)
590 constexpr int max = 16;
591 std::array<int32_t, 5 * max> edges{};
592 const auto n = freerdp_web_monitors_js(edges.data(), max);
593 if ((n < 2) || (n > max))
596 const auto at = [](int32_t edge, int32_t size)
597 {
return static_cast<INT32
>(
static_cast<int64_t
>(edge) * size / 10000); };
598 std::vector<rdpMonitor> list;
599 for (
int i = 0; i < n; i++)
601 const int32_t* e = &edges.at(5 *
static_cast<size_t>(i));
602 const auto left = at(e[0], canvas.width);
603 const auto top = at(e[1], canvas.height);
604 const auto right = at(e[2], canvas.width);
605 const auto bottom = at(e[3], canvas.height);
606 if ((right <= left) || (bottom <= top))
612 m.width = right - left;
613 m.height = bottom - top;
614 m.is_primary = (e[4] != 0);
615 m.attributes.physicalWidth =
616 static_cast<UINT32
>(
static_cast<uint64_t
>(canvas.attributes.physicalWidth) *
617 static_cast<UINT32
>(m.width) /
static_cast<UINT32
>(canvas.width));
618 m.attributes.physicalHeight =
619 static_cast<UINT32
>(
static_cast<uint64_t
>(canvas.attributes.physicalHeight) *
620 static_cast<UINT32
>(m.height) /
static_cast<UINT32
>(canvas.height));
627bool SdlContext::updateWindowList()
633 std::vector<rdpMonitor> list;
634 list.reserve(_windows.size());
635 for (
const auto& win : _windows)
637 auto monitor = win.second.monitor(_windows.size() == 1);
638 applyMonitorScaleOverride(monitor);
639 list.push_back(monitor);
642#if defined(__EMSCRIPTEN__)
643 if ((list.size() == 1) && (list.at(0).width > 0) && (list.at(0).height > 0))
645 auto split = sdl_web_monitors(list.at(0));
647 list = std::move(split);
655 std::none_of(list.cbegin(), list.cend(), [](
const rdpMonitor& m) { return m.is_primary; }))
656 list.at(0).is_primary =
true;
662bool SdlContext::updateWindow(SDL_WindowID
id)
670 auto& w = _windows.at(
id);
671 auto m = w.monitor(
true);
672 applyMonitorScaleOverride(m);
677 m.attributes.desktopScaleFactor =
static_cast<UINT32
>(std::roundf(w.scale() * 100.0f));
682std::string SdlContext::windowTitle()
const
684 const char* prefix =
"FreeRDP:";
692 const auto addPort = (port != 3389);
694 std::stringstream ss;
695 ss << prefix <<
" " << name;
703bool SdlContext::waitForWindowsCreated()
706 std::unique_lock<CriticalSection> lock(_critical);
707 _windowsCreatedEvent.clear();
708 if (!sdl_push_user_event(SDL_EVENT_USER_CREATE_WINDOWS,
this))
712 HANDLE handles[] = { _windowsCreatedEvent.handle(), freerdp_abort_event(context()) };
714 const DWORD rc = WaitForMultipleObjects(ARRAYSIZE(handles), handles, FALSE, INFINITE);
728BOOL SdlContext::endPaint(rdpContext* context)
730 auto sdl = get_context(context);
733 auto gdi = context->gdi;
735 WINPR_ASSERT(gdi->primary);
737 HGDI_DC hdc = gdi->primary->hdc;
742 HGDI_WND hwnd = hdc->hwnd;
743 WINPR_ASSERT(hwnd->invalid || (hwnd->ninvalid == 0));
745 if (hwnd->invalid->null)
748 WINPR_ASSERT(hwnd->invalid);
749 if (gdi->suppressOutput || hwnd->invalid->null)
752 const INT32 ninvalid = hwnd->ninvalid;
753 const GDI_RGN* cinvalid = hwnd->cinvalid;
758 std::vector<SDL_Rect> rects;
759 for (INT32 x = 0; x < ninvalid; x++)
761 auto& rgn = cinvalid[x];
762 rects.push_back({ rgn.x, rgn.y, rgn.w, rgn.h });
765 sdl->push(std::move(rects));
766 return sdl_push_user_event(SDL_EVENT_USER_UPDATE);
769void SdlContext::sdl_client_cleanup(
int exit_code,
const std::string& error_msg)
771 rdpSettings* settings = context()->settings;
772 WINPR_ASSERT(settings);
774 _rdpThreadRunning =
false;
775 bool showError =
false;
777 WLog_Print(getWLog(), WLOG_INFO,
"Authentication only, exit status %s [%" PRId32
"]",
778 sdl::error::exitCodeToTag(exit_code), exit_code);
783 case sdl::error::SUCCESS:
784 case sdl::error::DISCONNECT:
785 case sdl::error::LOGOFF:
786 case sdl::error::DISCONNECT_BY_USER:
787 case sdl::error::CONNECT_CANCELLED:
792 getDialog().showError(error_msg);
799 getDialog().show(
false);
801 _exitCode = exit_code;
802 std::ignore = sdl_push_user_event(SDL_EVENT_USER_QUIT);
806int SdlContext::sdl_client_thread_connect(std::string& error_msg)
808 auto instance = context()->instance;
809 WINPR_ASSERT(instance);
811 _rdpThreadRunning =
true;
812 BOOL rc = freerdp_connect(instance);
814 rdpSettings* settings = context()->settings;
815 WINPR_ASSERT(settings);
817 int exit_code = sdl::error::SUCCESS;
820 UINT32 error = freerdp_get_last_error(context());
821 exit_code = sdl::error::errorToExitCode(error);
826 DWORD code = freerdp_get_last_error(context());
827 freerdp_abort_connect_context(context());
828 WLog_Print(getWLog(), WLOG_ERROR,
"Authentication only, %s [0x%08" PRIx32
"] %s",
829 freerdp_get_last_error_name(code), code, freerdp_get_last_error_string(code));
835 DWORD code = freerdp_error_info(instance);
836 if (exit_code == sdl::error::SUCCESS)
840 exit_code = error_info_to_error(&code, &msg, &len);
846 auto last = freerdp_get_last_error(context());
847 if (error_msg.empty())
851 winpr_asprintf(&msg, &len,
"%s [0x%08" PRIx32
"]\n%s",
852 freerdp_get_last_error_name(last), last,
853 freerdp_get_last_error_string(last));
859 if (exit_code == sdl::error::SUCCESS)
861 if (last == FREERDP_ERROR_AUTHENTICATION_FAILED)
862 exit_code = sdl::error::AUTH_FAILURE;
863 else if (code == ERRINFO_SUCCESS)
864 exit_code = sdl::error::CONN_FAILED;
867 getDialog().show(
false);
873int SdlContext::sdl_client_thread_run(std::string& error_msg)
875 auto instance = context()->instance;
876 WINPR_ASSERT(instance);
878 int exit_code = sdl::error::SUCCESS;
879 while (!freerdp_shall_disconnect_context(context()))
881 HANDLE handles[MAXIMUM_WAIT_OBJECTS] = {};
887 if (freerdp_focus_required(instance))
889 auto ctx = get_context(context());
892 auto& input = ctx->getInputChannelContext();
893 if (!input.keyboard_focus_in())
895 if (!input.keyboard_focus_in())
899 const DWORD nCount = freerdp_get_event_handles(context(), handles, ARRAYSIZE(handles));
903 WLog_Print(getWLog(), WLOG_ERROR,
"freerdp_get_event_handles failed");
907 const DWORD status = WaitForMultipleObjects(nCount, handles, FALSE, INFINITE);
909 if (status == WAIT_FAILED)
911 WLog_Print(getWLog(), WLOG_ERROR,
"WaitForMultipleObjects WAIT_FAILED");
915 if (!freerdp_check_event_handles(context()))
917 if (client_auto_reconnect(instance))
920 getDialog().show(
false);
929 if (freerdp_error_info(instance) == 0)
930 exit_code = sdl::error::errorToExitCode(freerdp_get_last_error(context()));
933 if (freerdp_get_last_error(context()) == FREERDP_ERROR_SUCCESS)
934 WLog_Print(getWLog(), WLOG_ERROR,
"WaitForMultipleObjects failed with %" PRIu32
"",
936 if (freerdp_get_last_error(context()) == FREERDP_ERROR_SUCCESS)
937 WLog_Print(getWLog(), WLOG_ERROR,
"Failed to check FreeRDP event handles");
942 if (exit_code == sdl::error::SUCCESS)
946 char* emsg =
nullptr;
948 exit_code = error_info_to_error(&code, &emsg, &elen);
954 if ((code == ERRINFO_LOGOFF_BY_USER) &&
955 (freerdp_get_disconnect_ultimatum(context()) == Disconnect_Ultimatum_user_requested))
957 const char* msg =
"Error info says user did not initiate but disconnect ultimatum says "
958 "they did; treat this as a user logoff";
960 char* emsg =
nullptr;
962 winpr_asprintf(&emsg, &elen,
"%s", msg);
968 WLog_Print(getWLog(), WLOG_INFO,
"%s", msg);
969 exit_code = sdl::error::LOGOFF;
973 if ((exit_code != sdl::error::SUCCESS) && error_msg.empty())
975 const auto last = freerdp_get_last_error(context());
978 winpr_asprintf(&msg, &len,
"%s [0x%08" PRIx32
"]\n%s", freerdp_get_last_error_name(last),
979 last, freerdp_get_last_error_string(last));
985 freerdp_disconnect(instance);
997 std::string error_msg;
998 int exit_code = sdl->sdl_client_thread_connect(error_msg);
999 if (exit_code == sdl::error::SUCCESS)
1000 exit_code = sdl->sdl_client_thread_run(error_msg);
1001 sdl->sdl_client_cleanup(exit_code, error_msg);
1003 return static_cast<DWORD
>(exit_code);
1006int SdlContext::error_info_to_error(DWORD* pcode,
char** msg,
size_t* len)
const
1008 const DWORD code = freerdp_error_info(context()->instance);
1009 const char* name = freerdp_get_error_info_name(code);
1010 const char* str = freerdp_get_error_info_string(code);
1011 const int exit_code = sdl::error::errorToExitCode(code);
1013 winpr_asprintf(msg, len,
"Terminate with %s due to ERROR_INFO %s [0x%08" PRIx32
"]: %s",
1014 sdl::error::errorToExitCodeTag(code), name, code, str);
1015 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"%s", *msg);
1021void SdlContext::updateMonitorDataFromOffsets()
1023 for (
auto& entry : _windows)
1025 const auto& monitor = _displays.at(entry.first);
1026 entry.second.setMonitor(monitor);
1030bool SdlContext::drawToWindow(
SdlWindow& window,
const std::vector<SDL_Rect>& rects)
1035 auto gdi = context()->gdi;
1038 auto size = window.rect();
1040 std::unique_lock lock(_critical);
1041 auto surface = _primary.get();
1043 if (useLocalScale())
1045 window.setOffsetX(0);
1046 window.setOffsetY(0);
1047 if (gdi->width < size.w)
1049 window.setOffsetX((size.w - gdi->width) / 2);
1051 if (gdi->height < size.h)
1053 window.setOffsetY((size.h - gdi->height) / 2);
1056 _localScale = {
static_cast<float>(size.w) /
static_cast<float>(gdi->width),
1057 static_cast<float>(size.h) /
static_cast<float>(gdi->height) };
1058 if (!window.drawScaledRects(surface, _localScale, rects))
1063 SDL_Point offset{ 0, 0 };
1065 offset = { window.offsetX(), window.offsetY() };
1066 if (!window.drawRects(surface, offset, rects))
1070 window.updateSurface((&window == overlayWindow()) ? &_overlay :
nullptr);
1077 if (_rail.enabled() || _windows.empty())
1079 return &_windows.begin()->second;
1084 return showOverlay(!_overlay.visible());
1087bool SdlContext::showOverlay(
bool on)
1089 if (!_overlay.
show(on))
1091 if (on || !isConnected())
1095 auto window = overlayWindow();
1097 window->updateSurface();
1101bool SdlContext::updateOverlay()
1103 auto window = overlayWindow();
1104 if (!window || !isConnected())
1109 if (!SDL_GetWindowSizeInPixels(window->window(), &w, &h))
1111 if (_overlay.update(w, h, window->rendererName()))
1112 window->updateSurface(&_overlay);
1116bool SdlContext::minimizeAllWindows()
1118 for (
auto& w : _windows)
1119 w.second.minimize();
1123int SdlContext::exitCode()
const
1128SDL_PixelFormat SdlContext::pixelFormat()
const
1130 return _sdlPixelFormat;
1133bool SdlContext::addDisplayWindow(SDL_DisplayID
id)
1136 SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS;
1137 auto title = sdl::utils::windowTitle(context()->settings);
1138 auto w = SdlWindow::create(
id, title, flags);
1139 _windows.emplace(w.id(), std::move(w));
1143bool SdlContext::removeDisplayWindow(SDL_DisplayID
id)
1145 for (
auto& w : _windows)
1147 if (w.second.displayIndex() ==
id)
1148 _windows.erase(w.first);
1153bool SdlContext::detectDisplays()
1156 auto display = SDL_GetDisplays(&count);
1159 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_GetDisplays failed: %s", SDL_GetError());
1162 for (
int x = 0; x < count; x++)
1164 const auto id = display[x];
1165 addOrUpdateDisplay(
id);
1170 if (_displays.empty())
1172 WLog_Print(getWLog(), WLOG_ERROR,
"none of the %d displays has a usable size", count);
1178rdpMonitor SdlContext::getDisplay(SDL_DisplayID
id)
const
1180 return _displays.at(
id);
1183std::vector<SDL_DisplayID> SdlContext::getDisplayIds()
const
1185 std::vector<SDL_DisplayID> keys;
1186 keys.reserve(_displays.size());
1187 for (
const auto& entry : _displays)
1189 keys.push_back(entry.first);
1194const SdlWindow* SdlContext::getWindowForId(SDL_WindowID
id)
const
1196 auto it = _windows.find(
id);
1197 if (it == _windows.end())
1202SdlWindow* SdlContext::getWindowForId(SDL_WindowID
id)
1204 auto it = _windows.find(
id);
1205 if (it == _windows.end())
1210bool SdlContext::allWindowsHidden()
const
1212 return std::all_of(_windows.begin(), _windows.end(),
1213 [](
const auto& entry)
1215 const auto flags = SDL_GetWindowFlags(entry.second.window());
1216 return (flags & (SDL_WINDOW_HIDDEN | SDL_WINDOW_MINIMIZED)) != 0;
1222 if (_windows.empty())
1224 return &_windows.begin()->second;
1230 std::scoped_lock lock(_notificationLock);
1231 _notification = message;
1234 return SDL_RunOnMainThread(
1235 [](
void* user) {
static_cast<SdlContext*
>(user)->updateNotification(); },
this,
false);
1238void SdlContext::updateNotification()
1240 std::string message;
1242 std::scoped_lock lock(_notificationLock);
1243 message = _notification;
1246 if (message.empty())
1249 if (_notificationWindow != 0)
1251 auto window = SDL_GetWindowFromID(_notificationWindow);
1253 std::ignore = SDL_SetWindowTitle(window, _notificationSavedTitle.c_str());
1255 _notificationWindow = 0;
1256 _notificationSavedTitle.clear();
1262 if (_notificationWindow == 0)
1264 auto window = getFirstWindow();
1268 auto sdlWindow = window->window();
1269 _notificationWindow = SDL_GetWindowID(sdlWindow);
1270 _notificationSavedTitle = SDL_GetWindowTitle(sdlWindow);
1273 auto window = SDL_GetWindowFromID(_notificationWindow);
1276 _notificationWindow = 0;
1277 _notificationSavedTitle.clear();
1281 const auto title = _notificationSavedTitle +
" - " + message;
1282 std::ignore = SDL_SetWindowTitle(window, title.c_str());
1290sdlInput& SdlContext::getInputChannelContext()
1295sdlClip& SdlContext::getClipboardChannelContext()
1300SdlRail& SdlContext::getRailChannelContext()
1310wLog* SdlContext::getWLog()
1315bool SdlContext::moveMouseTo(
const SDL_FPoint& pos)
1317 auto window = SDL_GetMouseFocus();
1321 const auto id = SDL_GetWindowID(window);
1322 const auto spos = pixelToScreen(
id, pos);
1323 SDL_WarpMouseInWindow(window, spos.x, spos.y);
1327static bool onWindowEdge(SDL_WindowID
id,
float x,
float y)
1331 auto* window = SDL_GetWindowFromID(
id);
1332 if (!window || !SDL_GetWindowSize(window, &w, &h))
1334 return (x <= 0.0f) || (y <= 0.0f) || (x >=
static_cast<float>(w - 1)) ||
1335 (y >=
static_cast<float>(h - 1));
1338bool SdlContext::handleEvent(
const SDL_MouseMotionEvent& ev)
1343 if (_rail.enabled() && (ev.state == 0) && (ev.windowID == _lastRelease.window) &&
1344 (ev.timestamp - _lastRelease.time < SDL_MS_TO_NS(2)) &&
1345 onWindowEdge(ev.windowID, ev.x, ev.y))
1348 if (_rail.enabled() && _rail.suppressServerMotion(ev.windowID))
1350 if (!(SDL_GetGlobalMouseState(
nullptr,
nullptr) & SDL_BUTTON_LMASK))
1351 _rail.completeLocalMoveIfPending();
1355 SDL_FPoint delta{ ev.xrel, ev.yrel };
1356 if (!screenToRdp(ev.windowID, { ev.x, ev.y }, pos, &delta))
1358 copy.motion.x = pos.x;
1359 copy.motion.y = pos.y;
1360 copy.motion.xrel = delta.x;
1361 copy.motion.yrel = delta.y;
1363 if (_rail.enabled() && _rail.ownsWindow(ev.windowID))
1365 _lastMotion = { ev.windowID, { ev.x, ev.y }, pos, _rail.pointerEpoch() };
1366 _rail.noteServerPointer(pos.x, pos.y);
1368 return SdlTouch::handleEvent(
this, copy.motion);
1371bool SdlContext::handleEvent(
const SDL_MouseWheelEvent& ev)
1376 if (!screenToRdp(ev.windowID, { ev.mouse_x, ev.mouse_y }, pos))
1378 copy.wheel.mouse_x = pos.x;
1379 copy.wheel.mouse_y = pos.y;
1380 return SdlTouch::handleEvent(
this, copy.wheel);
1383bool SdlContext::handleEvent(
const SDL_WindowEvent& ev)
1385 if (!getDisplayChannelContext().handleEvent(ev))
1388 auto window = getWindowForId(ev.windowID);
1392 if (_rail.enabled() && _rail.ownsWindow(ev.windowID))
1396 case SDL_EVENT_WINDOW_MOUSE_ENTER:
1398 if (!(SDL_GetGlobalMouseState(
nullptr,
nullptr) & SDL_BUTTON_LMASK))
1399 _rail.completeLocalMoveIfPending();
1400 _rail.completeWaylandResize();
1402 return restoreCursor();
1403 case SDL_EVENT_WINDOW_MOUSE_LEAVE:
1405 _rail.noteResizeGrab(ev.windowID);
1407 case SDL_EVENT_WINDOW_EXPOSED:
1410 if (!_rail.dragActive(ev.windowID))
1411 _rail.invalidateWindow(ev.windowID);
1413 case SDL_EVENT_WINDOW_MAXIMIZED:
1415 _rail.completeLocalMoveIfPending();
1416 _rail.handleMaximized(ev.windowID);
1418 case SDL_EVENT_WINDOW_MINIMIZED:
1419 _rail.handleMinimized(ev.windowID);
1421 case SDL_EVENT_WINDOW_RESTORED:
1422 _rail.handleRestored(ev.windowID);
1424 case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
1426 _rail.handleClose(ev.windowID);
1428 case SDL_EVENT_WINDOW_FOCUS_GAINED:
1429 _rail.handleFocus(ev.windowID,
true);
1431 case SDL_EVENT_WINDOW_FOCUS_LOST:
1432 _rail.handleFocus(ev.windowID,
false);
1434 case SDL_EVENT_WINDOW_DISPLAY_CHANGED:
1435 _rail.handleDisplayChanged(ev.windowID,
static_cast<SDL_DisplayID
>(ev.data1));
1437 case SDL_EVENT_WINDOW_MOVED:
1438 _rail.notePopupMoved(ev.windowID);
1439 if (!_rail.dragActive(ev.windowID))
1440 _rail.syncGeometry(ev.windowID);
1442 case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
1445 _rail.noteDragResize(ev.windowID, ev.data1, ev.data2);
1446 _rail.syncGeometry(ev.windowID);
1447 _rail.noteResizeGrab(ev.windowID);
1448 std::ignore = drawToWindows({});
1458 const auto& r = window->rect();
1459 const auto& b = window->bounds();
1460 const auto& scale = window->scale();
1461 const auto& orientation = window->orientation();
1462 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
1463 "%s: [%u] %dx%d-%dx%d {%dx%d-%dx%d}{scale=%f,orientation=%s}",
1464 sdl::utils::toString(ev.type).c_str(), ev.windowID, r.x, r.y, r.w, r.h, b.x,
1465 b.y, b.w, b.h,
static_cast<double>(scale),
1466 sdl::utils::toString(orientation).c_str());
1471 case SDL_EVENT_WINDOW_MOUSE_ENTER:
1472 return restoreCursor();
1473 case SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED:
1474 if (!resizeToScale(window))
1479 if (!window->fill())
1481 if (!drawToWindow(*window))
1483 if (!restoreCursor())
1487 case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
1488 if (!resizeToScale(window))
1490 if (!window->fill())
1492 if (!drawToWindow(*window))
1494 if (!restoreCursor())
1498 case SDL_EVENT_WINDOW_MOVED:
1500 auto r = window->rect();
1501 auto id = window->id();
1502 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"%u: %dx%d-%dx%d",
id, r.x, r.y, r.w, r.h);
1505 case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
1507 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"Window closed, terminating RDP session...");
1508 std::ignore = abortConnect();
1517bool SdlContext::handleEvent(
const SDL_DisplayEvent& ev)
1519 if (!getDisplayChannelContext().handleEvent(ev))
1521#if SDL_VERSION_ATLEAST(3, 3, 2)
1522 if (ev.type == SDL_EVENT_DISPLAY_USABLE_BOUNDS_CHANGED)
1523 _rail.noteUsableBoundsChanged(ev.displayID);
1528 case SDL_EVENT_DISPLAY_REMOVED:
1533 if (!SDL_GetDisplayBounds(ev.displayID, &r))
1535 const auto name = SDL_GetDisplayName(ev.displayID);
1538 const auto orientation = SDL_GetCurrentDisplayOrientation(ev.displayID);
1539 const auto scale = SDL_GetDisplayContentScale(ev.displayID);
1540 const auto mode = SDL_GetCurrentDisplayMode(ev.displayID);
1544 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
1545 "%s: [%u, %s] %dx%d-%dx%d {orientation=%s, scale=%f}%s",
1546 sdl::utils::toString(ev.type).c_str(), ev.displayID, name, r.x, r.y, r.w,
1547 r.h, sdl::utils::toString(orientation).c_str(),
static_cast<double>(scale),
1548 sdl::utils::toString(mode).c_str());
1555bool SdlContext::handleEvent(
const SDL_MouseButtonEvent& ev)
1557 SDL_Event copy = {};
1559 if (_rail.enabled())
1562 const bool suppress = _rail.dragActive(ev.windowID);
1563 if (ev.type == SDL_EVENT_MOUSE_BUTTON_UP)
1564 _rail.completeLocalMoveIfPending();
1567 if (ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN)
1568 _rail.completeWaylandResize(
true);
1570 if (ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN)
1571 _rail.ensureActive(ev.windowID);
1574 if (ev.type == SDL_EVENT_MOUSE_BUTTON_UP)
1576 _lastRelease = { ev.windowID, ev.timestamp };
1581 if (!screenToRdp(ev.windowID, { ev.x, ev.y }, pos))
1583 copy.button.x = pos.x;
1584 copy.button.y = pos.y;
1586 if (_rail.enabled() && _rail.ownsWindow(ev.windowID))
1589 if ((ev.windowID == _lastMotion.window) && (_lastMotion.epoch == _rail.pointerEpoch()) &&
1590 (fabsf(ev.x - _lastMotion.local.x) < FLT_EPSILON) &&
1591 (fabsf(ev.y - _lastMotion.local.y) < FLT_EPSILON))
1593 copy.button.x = _lastMotion.server.x;
1594 copy.button.y = _lastMotion.server.y;
1598 if ((ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN) && (ev.button == SDL_BUTTON_LEFT))
1599 _rail.noteLeftPress(copy.button.x, copy.button.y);
1601 return SdlTouch::handleEvent(
this, copy.button);
1604bool SdlContext::handleEvent(
const SDL_TouchFingerEvent& ev)
1606 if (!getWindowForId(ev.windowID))
1611 if (!SDL_GetWindowSize(SDL_GetWindowFromID(ev.windowID), &w, &h))
1613 const auto fw =
static_cast<float>(w);
1614 const auto fh =
static_cast<float>(h);
1616 SDL_FPoint delta{ ev.dx * fw, ev.dy * fh };
1617 if (!screenToRdp(ev.windowID, { ev.x * fw, ev.y * fh }, pos, &delta))
1621 copy.tfinger.x = pos.x;
1622 copy.tfinger.y = pos.y;
1623 copy.tfinger.dx = delta.x;
1624 copy.tfinger.dy = delta.y;
1625 return SdlTouch::handleEvent(
this, copy.tfinger);
1628void SdlContext::addOrUpdateDisplay(SDL_DisplayID
id)
1630 auto monitor = SdlWindow::query(
id,
false);
1631 if ((monitor.width <= 0) || (monitor.height <= 0))
1633 WLog_Print(getWLog(), WLOG_WARN,
"display %" PRIu32
" has no usable size, skipped",
id);
1636 _displays.emplace(
id, monitor);
1641 _displayBounds.clear();
1642 for (
const auto& entry : _displays)
1645 std::ignore = SDL_GetDisplayBounds(entry.first, &bounds);
1646 _displayBounds.emplace(entry.first, bounds);
1648 _primaryDisplay = SDL_GetPrimaryDisplay();
1649 updateDisplayOffsets();
1650 updateMonitorDataFromOffsets();
1653void SdlContext::updateDisplayOffsets()
1658 for (
const auto& entry : _displays)
1661 const auto found = _displayBounds.find(entry.first);
1662 if (found != _displayBounds.end())
1663 bounds = found->second;
1666 pixel.w = entry.second.width;
1667 pixel.h = entry.second.height;
1668 _offsets.emplace(entry.first, std::pair{ bounds, pixel });
1671 if (_offsets.empty())
1673 sdl_display_offsets::update(_offsets, _primaryDisplay, _monitorIds);
1674 for (
auto& entry : _displays)
1676 const auto& pixel = _offsets.at(entry.first).second;
1677 entry.second.x = pixel.x;
1678 entry.second.y = pixel.y;
1682void SdlContext::deleteDisplay(SDL_DisplayID
id)
1684 _displays.erase(
id);
1687SDL_FPoint SdlContext::applyLocalScaling(
const SDL_FPoint& val)
const
1689 if (!useLocalScale())
1693 rval.x *= _localScale.x;
1694 rval.y *= _localScale.y;
1698bool SdlContext::screenToRdp(SDL_WindowID
id,
const SDL_FPoint& pos, SDL_FPoint& rpos,
1701 const auto origin = inputOrigin();
1702 std::optional<size_t> source;
1703 const auto windows = inputWindows(
id, origin, source);
1706 const auto mapped = sdl_window_to_input(windows, *source, pos, origin);
1711 *delta = sdl_window_delta_to_input(windows[*source], *delta);
1715SDL_Point SdlContext::inputOrigin()
const
1717 auto settings = context()->settings;
1719 std::vector<SDL_Rect>
layout;
1721 for (UINT32 x = 0; x < count; x++)
1723 const auto* monitor =
static_cast<const rdpMonitor*
>(
1724 freerdp_settings_get_pointer_array(settings, FreeRDP_MonitorDefArray, x));
1726 layout.push_back({ monitor->x, monitor->y, monitor->width, monitor->height });
1728 return sdl_layout_input_origin(layout);
1731SdlInputWindow SdlContext::inputWindowGeometry(SDL_Window* window, SDL_Renderer* renderer)
1733 SdlInputWindow input{};
1738 if (!sdl::utils::isWaylandDriver())
1741 if (SDL_GetWindowPosition(window, &bounds.x, &bounds.y) &&
1742 SDL_GetWindowSize(window, &bounds.w, &bounds.h))
1743 input.local = bounds;
1748 input.density = SDL_GetWindowPixelDensity(window);
1752std::vector<SdlInputWindow> SdlContext::inputWindows(SDL_WindowID
id,
const SDL_Point& origin,
1753 std::optional<size_t>& source)
1756 std::vector<SdlInputWindow> windows;
1757 windows.reserve(_windows.size());
1760 for (
auto& entry : _windows)
1762 auto& window = entry.second;
1763 const auto isSource = (entry.first == id);
1765 if (!isSource && ((SDL_GetWindowFlags(window.window()) & SDL_WINDOW_HIDDEN) != 0))
1768 auto input = inputWindowGeometry(window.window(), window.renderer());
1769 if (window.renderer() && useLocalScale())
1770 input.scale = _localScale;
1773 input.layout = multimon ? window.layoutPosition() : origin;
1775 source = windows.size();
1776 windows.push_back(input);
1779 _rail.inputWindows(
id, windows, source);
1783SDL_FPoint SdlContext::pixelToScreen(SDL_WindowID
id,
const SDL_FPoint& pos)
1785 auto w = getWindowForId(
id);
1788 if (_rail.enabled() && _rail.ownsWindow(
id))
1794 auto renderer = w->renderer();
1799 if (!SDL_RenderCoordinatesToWindow(renderer, pos.x, pos.y, &rpos.x, &rpos.y))
1801 return applyLocalScaling(rpos);
1804SDL_FRect SdlContext::pixelToScreen(SDL_WindowID
id,
const SDL_FRect& pos,
bool round)
1806 const auto fpos = pixelToScreen(
id, SDL_FPoint{ pos.x, pos.y });
1807 const auto size = pixelToScreen(
id, SDL_FPoint{ pos.w, pos.h });
1808 SDL_FRect r{ fpos.x, fpos.y, size.x, size.y };
1811 r.w = std::ceil(r.w);
1812 r.h = std::ceil(r.h);
1813 r.x = std::floor(r.x);
1814 r.y = std::floor(r.y);
1819bool SdlContext::handleEvent(
const SDL_Event& ev)
1821 if ((ev.type >= SDL_EVENT_DISPLAY_FIRST) && (ev.type <= SDL_EVENT_DISPLAY_LAST))
1823 const auto& dev = ev.display;
1824 return handleEvent(dev);
1826 if ((ev.type >= SDL_EVENT_WINDOW_FIRST) && (ev.type <= SDL_EVENT_WINDOW_LAST))
1828 const auto& wev = ev.window;
1829 return handleEvent(wev);
1833 case SDL_EVENT_RENDER_TARGETS_RESET:
1834 case SDL_EVENT_RENDER_DEVICE_RESET:
1835 case SDL_EVENT_WILL_ENTER_FOREGROUND:
1846 case SDL_EVENT_FINGER_DOWN:
1847 case SDL_EVENT_FINGER_UP:
1848 case SDL_EVENT_FINGER_MOTION:
1850 const auto& cev = ev.tfinger;
1851 return handleEvent(cev);
1853 case SDL_EVENT_MOUSE_MOTION:
1856 const auto& cev = ev.motion;
1857 return handleEvent(cev);
1859 case SDL_EVENT_MOUSE_BUTTON_DOWN:
1860 case SDL_EVENT_MOUSE_BUTTON_UP:
1862 const auto& cev = ev.button;
1863 return handleEvent(cev);
1865 case SDL_EVENT_MOUSE_WHEEL:
1867 const auto& cev = ev.wheel;
1868 return handleEvent(cev);
1870 case SDL_EVENT_CLIPBOARD_UPDATE:
1872 const auto& cev = ev.clipboard;
1873 return getClipboardChannelContext().handleEvent(cev);
1875 case SDL_EVENT_KEY_DOWN:
1876 case SDL_EVENT_KEY_UP:
1878 const auto& cev = ev.key;
1879 return getInputChannelContext().handleEvent(cev);
1888 return _args.data();
1891size_t SdlContext::argsCount()
const
1893 if (_args.size() <= 1)
1895 return _args.size() - 1;
1900 auto sdl =
static_cast<SdlContext*
>(custom);
1906 if (strcmp(arg->Name, sdl_allow_screensaver) == 0)
1908 sdl->_allowScreenSaver = (arg->Value !=
nullptr);
1909 if (arg->Value !=
nullptr)
1911 if (!SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER,
"1"))
1913 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
1914 "SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER) failed with %s",
1920 else if (strcmp(arg->Name, sdl_connection_dialog) == 0)
1921 sdl->_connectionDialog = (arg->Value !=
nullptr);
1922 else if (strcmp(arg->Name, sdl_info) == 0)
1924 if (!sdl->_overlay.
show(arg->Value !=
nullptr))
1931void SdlContext::applyMonitorScaleOverride(
rdpMonitor& monitor)
const
1933 freerdp_client_apply_monitor_scale(context()->settings, &monitor);
1941std::vector<rdpPointer*>& SdlContext::pointers()
1943 return _valid_pointers;
1946bool SdlContext::contains(
const rdpPointer* ptr)
const
1948 for (
const auto& cur : _valid_pointers)
1956bool SdlContext::credentialsRead()
const
1958 return _credentialsRead;
1961void SdlContext::setCredentialsRead()
1963 _credentialsRead =
true;
1968 return horizontal ? _wheelX : _wheelY;
1971bool SdlContext::resizeToScale(
SdlWindow* window)
1975 if (!useLocalScale())
1979 return window->resizeToScale();
1982bool SdlContext::useLocalScale()
const
1987 const auto dynResize =
1991 return !dynResize && !fs && !multimon;
1994bool SdlContext::drawToWindows(
const std::vector<SDL_Rect>& rects)
1997 if (_rail.enabled())
1999 for (
auto& window : _windows)
2001 if ((SDL_GetWindowFlags(window.second.window()) & SDL_WINDOW_HIDDEN) == 0)
2002 SDL_HideWindow(window.second.window());
2005 std::unique_lock lock(_critical);
2006 _rail.paint(_primary.get(), pixelFormat(), rects);
2013 !_rail.desktopMayShow())
2015 bool firstShow =
false;
2016 for (
auto& window : _windows)
2018 if (SDL_GetWindowFlags(window.second.window()) & SDL_WINDOW_HIDDEN)
2020 SDL_ShowWindow(window.second.window());
2021 SDL_RaiseWindow(window.second.window());
2026 if (rects.empty() && !firstShow)
2029 std::vector<SDL_Rect> drawRects = rects;
2031 std::unique_lock lock(_critical);
2032 if ((drawRects.empty() || firstShow) && _primary)
2033 drawRects = { { 0, 0, _primary->w, _primary->h } };
2036 for (
auto& window : _windows)
2038 if (!drawToWindow(window.second, drawRects))
2045BOOL SdlContext::desktopResize(rdpContext* context)
2047 rdpGdi* gdi =
nullptr;
2048 rdpSettings* settings =
nullptr;
2049 auto sdl = get_context(context);
2052 WINPR_ASSERT(context);
2054 settings = context->settings;
2055 WINPR_ASSERT(settings);
2057 std::unique_lock lock(sdl->_critical);
2062 return sdl->createPrimary();
2066BOOL SdlContext::playSound(rdpContext* context,
const PLAY_SOUND_UPDATE* play_sound)
2069 WINPR_UNUSED(context);
2070 WINPR_UNUSED(play_sound);
2076BOOL SdlContext::beginPaint(rdpContext* context)
2078 auto gdi = context->gdi;
2080 WINPR_ASSERT(gdi->primary);
2082 HGDI_DC hdc = gdi->primary->hdc;
2087 HGDI_WND hwnd = hdc->hwnd;
2088 WINPR_ASSERT(hwnd->invalid);
2089 hwnd->invalid->null = TRUE;
2095bool SdlContext::redraw(
bool suppress)
const
2104 auto gdi = context()->gdi;
2106 return gdi_send_suppress_output(gdi, suppress);
2109void SdlContext::setConnected(
bool val)
2114bool SdlContext::isConnected()
const
2121bool SdlContext::abortConnect()
const
2123 freerdp_set_last_error(context(), FREERDP_ERROR_CONNECT_CANCELLED);
2124 return freerdp_abort_connect_context(context());
2127rdpContext* SdlContext::context()
const
2129 WINPR_ASSERT(_context);
2133rdpClientContext* SdlContext::common()
const
2135 return reinterpret_cast<rdpClientContext*
>(context());
2138bool SdlContext::setCursor(CursorType type)
2141 return restoreCursor();
2144bool SdlContext::setCursor(
const rdpPointer* cursor)
2146 std::unique_lock lock(_critical);
2147 if (!contains(cursor))
2150 _cursor = { sdl_Pointer_Copy(cursor), sdl_PointerFreeCopyAll };
2151 return setCursor(CURSOR_IMAGE);
2154rdpPointer* SdlContext::cursor()
const
2156 return _cursor.get();
2159bool SdlContext::restoreCursor()
2161 WLog_Print(getWLog(), WLOG_TRACE,
"restore cursor: %d", _cursorType);
2162 switch (_cursorType)
2165 if (!SDL_HideCursor())
2167 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_HideCursor failed");
2171 setHasCursor(
false);
2174 case CURSOR_DEFAULT:
2176 auto def = SDL_GetDefaultCursor();
2177 if (!SDL_SetCursor(def))
2179 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_SetCursor(default=%p) failed",
2180 static_cast<void*
>(def));
2183 if (!SDL_ShowCursor())
2185 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_ShowCursor failed");
2193 return sdl_Pointer_Set_Process(
this);
2195 WLog_Print(getWLog(), WLOG_ERROR,
"Unknown cursorType %s",
2196 sdl::utils::toString(_cursorType).c_str());
2201void SdlContext::setMonitorIds(
const std::vector<SDL_DisplayID>& ids)
2203 _monitorIds.clear();
2206 _monitorIds.push_back(
id);
2211 updateDisplayOffsets();
2214const std::vector<SDL_DisplayID>& SdlContext::monitorIds()
const
2219int64_t SdlContext::monitorId(uint32_t index)
const
2221 if (index >= _monitorIds.size())
2225 return _monitorIds.at(index);
2228void SdlContext::push(std::vector<SDL_Rect>&& rects)
2230 std::unique_lock lock(_queue_mux);
2231 _queue.emplace(std::move(rects));
2234std::vector<SDL_Rect> SdlContext::pop()
2236 std::unique_lock lock(_queue_mux);
2241 auto val = std::move(_queue.front());
2246bool SdlContext::setFullscreen(
bool enter,
bool forceOriginalDisplay)
2248 for (
const auto& window : _windows)
2250 if (!sdl_push_user_event(SDL_EVENT_USER_WINDOW_FULLSCREEN, &window.second, enter,
2251 forceOriginalDisplay))
2254 _fullscreen = enter;
2258bool SdlContext::setMinimized()
2260 return sdl_push_user_event(SDL_EVENT_USER_WINDOW_MINIMIZE);
2263bool SdlContext::grabMouse()
const
2268bool SdlContext::toggleGrabMouse()
2270 return setGrabMouse(!grabMouse());
2273bool SdlContext::setGrabMouse(
bool enter)
2279bool SdlContext::grabKeyboard()
const
2281 return _grabKeyboard;
2284bool SdlContext::toggleGrabKeyboard()
2286 return setGrabKeyboard(!grabKeyboard());
2289bool SdlContext::setGrabKeyboard(
bool enter)
2291 _grabKeyboard = enter;
2295bool SdlContext::setResizeable(
bool enable)
2297 const auto settings = context()->settings;
2300 bool use = (dyn && enable) || smart;
2302 for (
const auto& window : _windows)
2304 if (!sdl_push_user_event(SDL_EVENT_USER_WINDOW_RESIZEABLE, &window.second, use))
2312bool SdlContext::resizeable()
const
2317bool SdlContext::toggleResizeable()
2319 return setResizeable(!resizeable());
2322bool SdlContext::fullscreen()
const
2327bool SdlContext::toggleFullscreen()
2329 return setFullscreen(!fullscreen());
2336 const bool scale = fabsf(a.scale - b.scale) <= FLT_EPSILON;
2337 return (a.hwnd == b.hwnd) && (a.remoteWidth == b.remoteWidth) &&
2338 (a.remoteHeight == b.remoteHeight) && (a.viewWidth == b.viewWidth) &&
2339 (a.viewHeight == b.viewHeight) && (a.scrollX == b.scrollX) && (a.scrollY == b.scrollY) &&
2344static HWND native_window(SDL_Window* window)
2348 auto props = SDL_GetWindowProperties(window);
2350 return static_cast<HWND
>(
2351 SDL_GetPointerProperty(props, SDL_PROP_WINDOW_WIN32_HWND_POINTER,
nullptr));
2353 return reinterpret_cast<HWND
>(
2354 static_cast<uintptr_t
>(SDL_GetNumberProperty(props, SDL_PROP_WINDOW_X11_WINDOW_NUMBER, 0)));
2361 auto window = getFirstWindow();
2362 if (window && window->window())
2364 auto settings = _context->settings;
2365 info.hwnd = native_window(window->window());
2372 if (SDL_GetWindowSizeInPixels(window->window(), &w, &h))
2375 info.viewHeight = h;
2378 const float density = SDL_GetWindowPixelDensity(window->window());
2379 const auto p0 = pixelToScreen(window->id(), SDL_FPoint{ 0, 0 });
2380 const auto p1 = pixelToScreen(window->id(), SDL_FPoint{ 1000, 1000 });
2381 const float scale = (p1.x - p0.x) * density / 1000.0f;
2382 info.scale = (scale > 0.0f) ? scale : 1.0f;
2386 std::scoped_lock lock(_windowInfoLock);
2387 if (window_info_equal(info, _desktopWindowInfo))
2389 _desktopWindowInfo = info;
2391 if (!_rail.enabled())
2392 freerdp_client_window_info_service_changed(_context->windowInfoService, 0);
2399 std::scoped_lock lock(_windowInfoLock);
2400 first = _railWindowInfoPending.empty();
2401 _railWindowInfoPending.insert(remoteId);
2404 std::ignore = sdl_push_user_event(SDL_EVENT_USER_WINDOW_INFO);
2409 std::set<uint64_t> pending;
2411 std::scoped_lock lock(_windowInfoLock);
2412 pending.swap(_railWindowInfoPending);
2415 for (
const auto id : pending)
2418 SDL_Window* window =
nullptr;
2420 if (_rail.windowGeometry(
id, window, info.viewWidth, info.viewHeight))
2422 info.hwnd = native_window(window);
2423 info.remoteWidth = info.viewWidth;
2424 info.remoteHeight = info.viewHeight;
2427 std::scoped_lock lock(_windowInfoLock);
2428 if (info.viewWidth > 0)
2429 _railWindowInfo[id] = info;
2431 _railWindowInfo.erase(
id);
2433 if (info.viewWidth > 0)
2434 freerdp_client_window_info_service_changed(_context->windowInfoService,
id);
2438HRESULT SdlContext::windowInfoGet(
void* custom, UINT64 remoteHwnd,
WTS_WINDOW_INFO* info)
2444 std::scoped_lock lock(
sdl->_windowInfoLock);
2445 if (!
sdl->_rail.enabled())
2448 if (!
sdl->_desktopWindowInfo.hwnd && (
sdl->_desktopWindowInfo.viewWidth == 0))
2449 return E_UNEXPECTED;
2450 *info =
sdl->_desktopWindowInfo;
2453 auto it = sdl->_railWindowInfo.find(remoteHwnd);
2454 if (it == sdl->_railWindowInfo.end())
2455 return E_INVALIDARG;
2460UINT32 SdlContext::windowInfoSessionType(
void* custom)
2462 auto sdl =
static_cast<SdlContext*
>(custom);
2464 return sdl->_rail.enabled() ? WTS_RDP_SESSION_TYPE_REMOTEAPP : WTS_RDP_SESSION_TYPE_DESKTOP;
2472 std::scoped_lock lock(_rendererLock);
2473 const auto id = _nextRenderer++;
2474 auto& r = _renderers[id];
2475 r.mappingId = mappingId;
2476 r.callback = callback;
2482bool SdlContext::rendererFrame(Uint64
id,
const BYTE* data, UINT32 width, UINT32 height,
2489 std::scoped_lock lock(_rendererLock);
2490 auto it = _renderers.find(
id);
2491 if (it == _renderers.end())
2493 auto& r = it->second;
2495 const size_t row =
static_cast<size_t>(width) * 4;
2496 r.pixels.resize(row * height);
2497 for (UINT32 y = 0; y < height; y++)
2499 const auto offset = row * y;
2500 const auto end = offset + row;
2501 const auto dataoffset = 1ull * y *
static_cast<size_t>(stride);
2505 auto& ptr = r.pixels.at(offset);
2506 std::ignore = r.pixels.at(end);
2507 memcpy(&ptr, &data[dataoffset], row);
2509 catch (std::out_of_range& ex)
2511 SDL_Log(
"failed to render: %s", ex.what());
2515 r.pitch =
static_cast<int>(row);
2516 r.width =
static_cast<int>(width);
2517 r.height =
static_cast<int>(height);
2524void SdlContext::rendererRemove(Uint64
id)
2526 IWTSBitmapRendererCallback* callback =
nullptr;
2528 std::scoped_lock lock(_rendererLock);
2529 auto it = _renderers.find(
id);
2530 if (it == _renderers.end())
2532 callback = it->second.callback;
2533 _renderers.erase(it);
2536 callback->Release();
2540bool SdlContext::hasRenderers()
2542 std::scoped_lock lock(_rendererLock);
2543 return !_renderers.empty();
2546void SdlContext::renderersChanged()
2549 if (!_renderersPending.exchange(
true))
2550 std::ignore = sdl_push_user_event(SDL_EVENT_USER_RENDERER);
2555 _renderersPending =
false;
2560 std::vector<std::pair<IWTSBitmapRendererCallback*, WTS_RECT>> targets;
2562 std::scoped_lock lock(_rendererLock);
2567 bool visible =
false;
2569 std::vector<SDL_Rect> region;
2571 std::map<Uint64, Placement> placements;
2572 rdpGdi* gdi = _context->gdi;
2573 GeometryClientContext* geometry = gdi ? gdi->geometry :
nullptr;
2574 if (geometry && geometry->geometries)
2576 HashTable_Lock(geometry->geometries);
2577 for (
auto& kv : _renderers)
2579 auto g =
static_cast<const MAPPED_GEOMETRY*
>(
2580 HashTable_GetItemValue(geometry->geometries, &kv.second.mappingId));
2584 p.rect = {
static_cast<int>(g->topLevelLeft + g->left),
2585 static_cast<int>(g->topLevelTop + g->top),
2586 static_cast<int>(std::max<INT64>(0, g->right - g->left)),
2587 static_cast<int>(std::max<INT64>(0, g->bottom - g->top)) };
2588 p.visible = (p.rect.w > 0) && (p.rect.h > 0);
2591 for (UINT32 i = 0; g->geometry.rects && (i < g->geometry.nRectCount); i++)
2593 const RDP_RECT& r = g->geometry.rects[i];
2594 const int left = std::max(0,
static_cast<int>(r.x));
2595 const int top = std::max(0,
static_cast<int>(r.y));
2596 const int right = std::min(p.rect.w, r.x + r.width);
2597 const int bottom = std::min(p.rect.h, r.y + r.height);
2598 if ((right <= left) || (bottom <= top))
2600 area +=
static_cast<INT64
>(right - left) * (bottom - top);
2602 { p.rect.x + left, p.rect.y + top, right - left, bottom - top });
2604 if (area >=
static_cast<INT64
>(p.rect.w) * p.rect.h)
2606 placements[kv.first] = std::move(p);
2608 HashTable_Unlock(geometry->geometries);
2611 for (
auto& kv : _renderers)
2613 auto& r = kv.second;
2614 const auto& p = placements[kv.first];
2615 if (p.visible && r.callback && !SDL_RectsEqual(&p.rect, &r.target))
2618 r.callback->AddRef();
2619 targets.emplace_back(r.callback,
WTS_RECT{ p.rect.x, p.rect.y, p.rect.x + p.rect.w,
2620 p.rect.y + p.rect.h });
2624 for (
auto& w : _windows)
2626 auto& window = w.second;
2627 window.pruneVideoOverlays([
this](Uint64
id) {
return _renderers.count(
id) != 0; });
2628 for (
auto& kv : _renderers)
2630 auto& r = kv.second;
2631 const auto& p = placements[kv.first];
2633 SDL_Point offset{ 0, 0 };
2634 if (!useLocalScale() &&
2636 offset = { window.offsetX(), window.offsetY() };
2637 auto toWindow = [&](
const SDL_Rect& rc)
2639 if (useLocalScale())
2640 return SDL_FRect{
static_cast<float>(rc.x) * _localScale.x,
2641 static_cast<float>(rc.y) * _localScale.y,
2642 static_cast<float>(rc.w) * _localScale.x,
2643 static_cast<float>(rc.h) * _localScale.y };
2644 return SDL_FRect{
static_cast<float>(rc.x + offset.x),
2645 static_cast<float>(rc.y + offset.y),
static_cast<float>(rc.w),
2646 static_cast<float>(rc.h) };
2648 const SDL_FRect dst = toWindow(p.rect);
2649 std::vector<SDL_FRect> clip;
2650 clip.reserve(p.region.size());
2651 for (
const auto& rc : p.region)
2652 clip.push_back(toWindow(rc));
2653 const bool visible = p.visible && !r.pixels.empty();
2654 if (!window.setVideoOverlay(kv.first, r.dirty ? r.pixels.data() :
nullptr, r.pitch,
2655 r.width, r.height, dst, clip, visible))
2658 window.updateSurface();
2660 for (
auto& kv : _renderers)
2661 kv.second.dirty =
false;
2664 for (
auto& t : targets)
2666 std::ignore = t.first->OnTargetSizeChanged(t.second);
bool setNotification(const std::string &message)
void railWindowInfoChanged(uint64_t remoteId)
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 UINT64 freerdp_settings_get_uint64(const rdpSettings *settings, FreeRDP_Settings_Keys_UInt64 id)
Returns a UINT64 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.
Layout layout(float leftWidth, float leftHeight, float rightWidth, float rightHeight, float width, float margin)
what the client gives the service to answer from
same layout as Win32's RECT, which winpr doesn't have on POSIX