25#include "sdl_context.hpp"
26#include "sdl_config.hpp"
27#include "sdl_channels.hpp"
28#include "sdl_monitor.hpp"
29#include "sdl_display_offsets.hpp"
30#include "sdl_pointer.hpp"
31#include "sdl_touch.hpp"
32#include "sdl_prefs.hpp"
34#include <sdl_common_utils.hpp>
35#include <scoped_guard.hpp>
37#include "dialogs/sdl_dialogs.hpp"
38#include "sdl_render_service.hpp"
40#include <freerdp/client/aad_helper.h>
41#include <freerdp/client/geometry.h>
42#include <freerdp/gdi/gdi.h>
43#include <freerdp/client/monitor.h>
45static constexpr auto sdl_allow_screensaver =
"sdl-allow-screensaver";
46static constexpr auto sdl_connection_dialog =
"sdl-connection-dialog";
47static constexpr auto sdl_info =
"sdl-info";
49SdlContext::SdlContext(rdpContext* context)
50 : _context(context), _log(WLog_Get(CLIENT_TAG(
"SDL"))), _cursor(nullptr, sdl_Pointer_FreeCopy),
51 _rdpThreadRunning(false), _primary(nullptr, SDL_DestroySurface), _disp(this), _input(this),
52 _clip(this), _rail(this), _dialog(_log)
54 WINPR_ASSERT(context);
57 auto instance = _context->instance;
58 WINPR_ASSERT(instance);
60 instance->PreConnect = preConnect;
61 instance->PostConnect = postConnect;
62 instance->PostDisconnect = postDisconnect;
63 instance->PostFinalDisconnect = postFinalDisconnect;
64 instance->AuthenticateEx = sdl_authenticate_ex;
65 instance->VerifyCertificateEx = sdl_verify_certificate_ex;
66 instance->VerifyChangedCertificateEx = sdl_verify_changed_certificate_ex;
67 instance->LogonErrorInfo = sdl_logon_error_info;
68 instance->PresentGatewayMessage = sdl_present_gateway_message;
69 instance->ChooseSmartcard = sdl_choose_smartcard;
70 instance->RetryDialog = sdl_retry_dialog;
71 instance->GetAccessToken = client_failsafe_get_access_token;
75 _args.push_back({ sdl_allow_screensaver, COMMAND_LINE_VALUE_BOOL,
nullptr, BoolValueFalse,
77 "Allow local screensaver to activate (default: on for RemoteApp)" });
79 _args.push_back({ sdl_connection_dialog, COMMAND_LINE_VALUE_BOOL,
nullptr,
"on",
nullptr, -1,
80 nullptr,
"the connection dialog with progress and errors" });
81 _args.push_back({ sdl_info, COMMAND_LINE_VALUE_BOOL,
nullptr, BoolValueFalse,
nullptr, -1,
83 "the stats and info overlay from the start (its hotkey SDL_Info, default "
84 "<modifier>+I, shows and hides it)" });
87 _args.push_back({
nullptr, 0,
nullptr,
nullptr,
nullptr, -1,
nullptr,
nullptr });
90 _context->windowInfoService = freerdp_client_window_info_service_new(&source);
91 if (!_context->windowInfoService)
92 WLog_Print(_log, WLOG_WARN,
"no window info service: channels won't know our windows");
93 _context->bitmapRenderService = sdl_render_service_new(
this);
94 if (!_context->bitmapRenderService)
95 WLog_Print(_log, WLOG_WARN,
"no bitmap render service: no redirected video");
98SdlContext::~SdlContext()
101 if (_context->windowInfoService)
103 freerdp_client_window_info_service_detach(_context->windowInfoService);
104 _context->windowInfoService->Release();
105 _context->windowInfoService =
nullptr;
107 if (_context->bitmapRenderService)
109 sdl_render_service_detach(_context->bitmapRenderService);
110 _context->bitmapRenderService->Release();
111 _context->bitmapRenderService =
nullptr;
114 std::scoped_lock lock(_rendererLock);
115 for (
auto& kv : _renderers)
117 if (kv.second.callback)
118 kv.second.callback->Release();
123std::optional<bool> SdlContext::allowScreenSaver()
const
125 return _allowScreenSaver;
128void SdlContext::setHasCursor(
bool val)
130 this->_cursor_visible = val;
133bool SdlContext::hasCursor()
const
135 return _cursor_visible;
138void SdlContext::setMetadata()
141 if (!wmclass || (strlen(wmclass) == 0))
142 wmclass = SDL_CLIENT_UUID;
144 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_IDENTIFIER_STRING, wmclass);
145 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_NAME_STRING, SDL_CLIENT_NAME);
146 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_VERSION_STRING, SDL_CLIENT_VERSION);
147 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_CREATOR_STRING, SDL_CLIENT_VENDOR);
148 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_COPYRIGHT_STRING, SDL_CLIENT_COPYRIGHT);
149 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_URL_STRING, SDL_CLIENT_URL);
150 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_TYPE_STRING, SDL_CLIENT_TYPE);
153int SdlContext::start()
155 _thread = std::thread(rdpThreadRun,
this);
159int SdlContext::join()
163 HANDLE
event = freerdp_abort_event(context());
164 if (!SetEvent(event))
171void SdlContext::cleanup()
173 std::unique_lock lock(_critical);
179bool SdlContext::shallAbort(
bool ignoreDialogs)
181 std::unique_lock lock(_critical);
182 if (freerdp_shall_disconnect_context(context()))
186 if (_rdpThreadRunning)
188 return !getDialog().isRunning();
195BOOL SdlContext::preConnect(freerdp* instance)
197 WINPR_ASSERT(instance);
198 WINPR_ASSERT(instance->context);
200 auto sdl = get_context(instance->context);
202 auto settings = instance->context->settings;
203 WINPR_ASSERT(settings);
218 if (PubSub_SubscribeChannelConnected(instance->context->pubSub,
219 sdl_OnChannelConnectedEventHandler) < 0)
221 if (PubSub_SubscribeChannelDisconnected(instance->context->pubSub,
222 sdl_OnChannelDisconnectedEventHandler) < 0)
224 if (PubSub_SubscribeUserNotification(instance->context->pubSub,
225 sdl_OnUserNotificationEventHandler) < 0)
231 UINT32 maxHeight = 0;
233 if (!sdl_detect_monitors(sdl, &maxWidth, &maxHeight))
240 if (((overrides & FREERDP_MONITOR_OVERRIDE_DESKTOP_SCALE) == 0) &&
246 auto monitor =
static_cast<const rdpMonitor*
>(
247 freerdp_settings_get_pointer_array(settings, FreeRDP_MonitorDefArray, x));
248 if (monitor && monitor->is_primary)
249 scale = monitor->attributes.desktopScaleFactor;
251 if ((scale == 0) && !sdl->monitorIds().empty())
253 auto monitor = sdl->getDisplay(sdl->monitorIds().front());
254 sdl->applyMonitorScaleOverride(monitor);
255 scale = monitor.attributes.desktopScaleFactor;
257 if ((scale >= 100) && (scale <= 500))
265 if ((overrides == 0) &&
270 if ((maxWidth != 0) && (maxHeight != 0) &&
273 WLog_Print(sdl->getWLog(), WLOG_INFO,
"Update size to %ux%u", maxWidth, maxHeight);
288 if (sm && (sw > 0) && (sh > 0))
292 WLog_Print(sdl->getWLog(), WLOG_WARN,
293 "/smart-sizing and /multimon are currently not supported, ignoring "
312 WLog_Print(sdl->getWLog(), WLOG_INFO,
313 "auth-only, but no password set. Please provide one.");
320 WLog_Print(sdl->getWLog(), WLOG_INFO,
"Authentication only. Don't connect SDL.");
323 if (!sdl->getInputChannelContext().initialize())
326 sdl->_credentialsRead =
false;
329 auto prefs = SdlPref::instance();
330 auto dialog = prefs->get_bool(
"SDL_ConnectionDialog",
true);
331 if (sdl->_connectionDialog && prefs->is_commandline_override_allowed())
332 dialog = *sdl->_connectionDialog;
335 sdl->getDialog().create(instance->context);
337 sdl->getDialog().showInfo(
"The connection is being established\n\nPlease wait...");
352BOOL SdlContext::postConnect(freerdp* instance)
354 WINPR_ASSERT(instance);
356 auto context = instance->context;
357 WINPR_ASSERT(context);
359 auto sdl = get_context(context);
362 sdl->getDialog().show(
false);
369 WLog_Print(sdl->getWLog(), WLOG_INFO,
370 "auth-only, but no password set. Please provide one.");
374 WLog_Print(sdl->getWLog(), WLOG_INFO,
"Authentication only. Don't connect to X.");
378 if (!sdl->waitForWindowsCreated())
381 sdl->_sdlPixelFormat = SDL_PIXELFORMAT_BGRA32;
382 if (!gdi_init(instance, PIXEL_FORMAT_BGRA32))
385 if (!sdl->createPrimary())
388 if (!sdl_register_pointer(instance->context->graphics))
391 WINPR_ASSERT(context->update);
393 context->update->BeginPaint = beginPaint;
394 context->update->EndPaint = endPaint;
395 context->update->PlaySound = playSound;
396 context->update->DesktopResize = desktopResize;
397 context->update->SetKeyboardIndicators = sdlInput::keyboard_set_indicators;
398 context->update->SetKeyboardImeStatus = sdlInput::keyboard_set_ime_status;
400 if (!sdl->setResizeable(
false))
406 sdl->setConnected(
true);
408 return sdl->_overlay.connected();
414void SdlContext::postDisconnect(freerdp* instance)
419 if (!instance->context)
422 auto sdl = get_context(instance->context);
423 sdl->setConnected(
false);
428void SdlContext::postFinalDisconnect(freerdp* instance)
433 if (!instance->context)
436 PubSub_UnsubscribeChannelConnected(instance->context->pubSub,
437 sdl_OnChannelConnectedEventHandler);
438 PubSub_UnsubscribeChannelDisconnected(instance->context->pubSub,
439 sdl_OnChannelDisconnectedEventHandler);
440 PubSub_UnsubscribeUserNotification(instance->context->pubSub,
441 sdl_OnUserNotificationEventHandler);
445bool SdlContext::createPrimary()
447 auto gdi = context()->gdi;
450 _primary = SDLSurfacePtr(
451 SDL_CreateSurfaceFrom(
static_cast<int>(gdi->width),
static_cast<int>(gdi->height),
452 pixelFormat(), gdi->primary_buffer,
static_cast<int>(gdi->stride)),
457 SDL_SetSurfaceBlendMode(_primary.get(), SDL_BLENDMODE_NONE);
458 SDL_Rect surfaceRect = { 0, 0, gdi->width, gdi->height };
459 SDL_FillSurfaceRect(_primary.get(), &surfaceRect,
460 SDL_MapSurfaceRGBA(_primary.get(), 0, 0, 0, 0xff));
465bool SdlContext::createWindows()
467 auto settings = context()->settings;
468 const auto& title = windowTitle();
470 ScopeGuard guard1([&]() { _windowsCreatedEvent.set(); });
476 auto monitorFor = [&](UINT32 index, int64_t id)
478 for (UINT32 y = 0; y < windowCount; y++)
480 auto cur =
static_cast<rdpMonitor*
>(
481 freerdp_settings_get_pointer_array_writable(settings, FreeRDP_MonitorDefArray, y));
482 if (cur && (
static_cast<int64_t
>(cur->orig_screen) ==
id))
485 return static_cast<rdpMonitor*
>(
486 freerdp_settings_get_pointer_array_writable(settings, FreeRDP_MonitorDefArray, index));
491 for (UINT32 x = 0; x < windowCount; x++)
493 auto id = monitorId(x);
497 auto monitor = monitorFor(x,
id);
499 originX = std::min<Sint32>(monitor->x, originX);
500 originY = std::min<Sint32>(monitor->y, originY);
503 for (UINT32 x = 0; x < windowCount; x++)
505 auto id = monitorId(x);
509 auto monitor = monitorFor(x,
id);
511 Uint32 w = WINPR_ASSERTING_INT_CAST(Uint32, monitor->width);
512 Uint32 h = WINPR_ASSERTING_INT_CAST(Uint32, monitor->height);
516 if (_windowWidth > 0)
521 if (_windowHeight > 0)
527 Uint32 flags = SDL_WINDOW_HIGH_PIXEL_DENSITY;
532 flags |= SDL_WINDOW_FULLSCREEN;
537 flags |= SDL_WINDOW_BORDERLESS;
541 flags |= SDL_WINDOW_BORDERLESS;
545 flags |= SDL_WINDOW_HIDDEN;
547 auto did = WINPR_ASSERTING_INT_CAST(SDL_DisplayID,
id);
548 auto window = SdlWindow::create(did, title, flags, w, h);
552 window.setOffsetX(originX - monitor->x);
553 window.setOffsetY(originY - monitor->y);
556 _windows.insert({ window.id(), std::move(window) });
563#if defined(__EMSCRIPTEN__)
565extern "C" int freerdp_web_monitors_js(int32_t* edges,
int max);
571static std::vector<rdpMonitor> sdl_web_monitors(
const rdpMonitor& canvas)
573 constexpr int max = 16;
574 std::array<int32_t, 5 * max> edges{};
575 const auto n = freerdp_web_monitors_js(edges.data(), max);
576 if ((n < 2) || (n > max))
579 const auto at = [](int32_t edge, int32_t size)
580 {
return static_cast<INT32
>(
static_cast<int64_t
>(edge) * size / 10000); };
581 std::vector<rdpMonitor> list;
582 for (
int i = 0; i < n; i++)
584 const int32_t* e = &edges.at(5 *
static_cast<size_t>(i));
585 const auto left = at(e[0], canvas.width);
586 const auto top = at(e[1], canvas.height);
587 const auto right = at(e[2], canvas.width);
588 const auto bottom = at(e[3], canvas.height);
589 if ((right <= left) || (bottom <= top))
595 m.width = right - left;
596 m.height = bottom - top;
597 m.is_primary = (e[4] != 0);
598 m.attributes.physicalWidth =
599 static_cast<UINT32
>(
static_cast<uint64_t
>(canvas.attributes.physicalWidth) *
600 static_cast<UINT32
>(m.width) /
static_cast<UINT32
>(canvas.width));
601 m.attributes.physicalHeight =
602 static_cast<UINT32
>(
static_cast<uint64_t
>(canvas.attributes.physicalHeight) *
603 static_cast<UINT32
>(m.height) /
static_cast<UINT32
>(canvas.height));
610bool SdlContext::updateWindowList()
616 std::vector<rdpMonitor> list;
617 list.reserve(_windows.size());
618 for (
const auto& win : _windows)
620 auto monitor = win.second.monitor(_windows.size() == 1);
621 applyMonitorScaleOverride(monitor);
622 list.push_back(monitor);
625#if defined(__EMSCRIPTEN__)
626 if ((list.size() == 1) && (list.at(0).width > 0) && (list.at(0).height > 0))
628 auto split = sdl_web_monitors(list.at(0));
630 list = std::move(split);
638 std::none_of(list.cbegin(), list.cend(), [](
const rdpMonitor& m) { return m.is_primary; }))
639 list.at(0).is_primary =
true;
645bool SdlContext::updateWindow(SDL_WindowID
id)
653 auto& w = _windows.at(
id);
654 auto m = w.monitor(
true);
655 applyMonitorScaleOverride(m);
660 m.attributes.desktopScaleFactor =
static_cast<UINT32
>(std::roundf(w.scale() * 100.0f));
665std::string SdlContext::windowTitle()
const
667 const char* prefix =
"FreeRDP:";
675 const auto addPort = (port != 3389);
677 std::stringstream ss;
678 ss << prefix <<
" " << name;
686bool SdlContext::waitForWindowsCreated()
689 std::unique_lock<CriticalSection> lock(_critical);
690 _windowsCreatedEvent.clear();
691 if (!sdl_push_user_event(SDL_EVENT_USER_CREATE_WINDOWS,
this))
695 HANDLE handles[] = { _windowsCreatedEvent.handle(), freerdp_abort_event(context()) };
697 const DWORD rc = WaitForMultipleObjects(ARRAYSIZE(handles), handles, FALSE, INFINITE);
711BOOL SdlContext::endPaint(rdpContext* context)
713 auto sdl = get_context(context);
716 auto gdi = context->gdi;
718 WINPR_ASSERT(gdi->primary);
720 HGDI_DC hdc = gdi->primary->hdc;
725 HGDI_WND hwnd = hdc->hwnd;
726 WINPR_ASSERT(hwnd->invalid || (hwnd->ninvalid == 0));
728 if (hwnd->invalid->null)
731 WINPR_ASSERT(hwnd->invalid);
732 if (gdi->suppressOutput || hwnd->invalid->null)
735 const INT32 ninvalid = hwnd->ninvalid;
736 const GDI_RGN* cinvalid = hwnd->cinvalid;
741 std::vector<SDL_Rect> rects;
742 for (INT32 x = 0; x < ninvalid; x++)
744 auto& rgn = cinvalid[x];
745 rects.push_back({ rgn.x, rgn.y, rgn.w, rgn.h });
748 sdl->push(std::move(rects));
749 return sdl_push_user_event(SDL_EVENT_USER_UPDATE);
752void SdlContext::sdl_client_cleanup(
int exit_code,
const std::string& error_msg)
754 rdpSettings* settings = context()->settings;
755 WINPR_ASSERT(settings);
757 _rdpThreadRunning =
false;
758 bool showError =
false;
760 WLog_Print(getWLog(), WLOG_INFO,
"Authentication only, exit status %s [%" PRId32
"]",
761 sdl::error::exitCodeToTag(exit_code), exit_code);
766 case sdl::error::SUCCESS:
767 case sdl::error::DISCONNECT:
768 case sdl::error::LOGOFF:
769 case sdl::error::DISCONNECT_BY_USER:
770 case sdl::error::CONNECT_CANCELLED:
775 getDialog().showError(error_msg);
782 getDialog().show(
false);
784 _exitCode = exit_code;
785 std::ignore = sdl_push_user_event(SDL_EVENT_USER_QUIT);
789int SdlContext::sdl_client_thread_connect(std::string& error_msg)
791 auto instance = context()->instance;
792 WINPR_ASSERT(instance);
794 _rdpThreadRunning =
true;
795 BOOL rc = freerdp_connect(instance);
797 rdpSettings* settings = context()->settings;
798 WINPR_ASSERT(settings);
800 int exit_code = sdl::error::SUCCESS;
803 UINT32 error = freerdp_get_last_error(context());
804 exit_code = sdl::error::errorToExitCode(error);
809 DWORD code = freerdp_get_last_error(context());
810 freerdp_abort_connect_context(context());
811 WLog_Print(getWLog(), WLOG_ERROR,
"Authentication only, %s [0x%08" PRIx32
"] %s",
812 freerdp_get_last_error_name(code), code, freerdp_get_last_error_string(code));
818 DWORD code = freerdp_error_info(instance);
819 if (exit_code == sdl::error::SUCCESS)
823 exit_code = error_info_to_error(&code, &msg, &len);
829 auto last = freerdp_get_last_error(context());
830 if (error_msg.empty())
834 winpr_asprintf(&msg, &len,
"%s [0x%08" PRIx32
"]\n%s",
835 freerdp_get_last_error_name(last), last,
836 freerdp_get_last_error_string(last));
842 if (exit_code == sdl::error::SUCCESS)
844 if (last == FREERDP_ERROR_AUTHENTICATION_FAILED)
845 exit_code = sdl::error::AUTH_FAILURE;
846 else if (code == ERRINFO_SUCCESS)
847 exit_code = sdl::error::CONN_FAILED;
850 getDialog().show(
false);
856int SdlContext::sdl_client_thread_run(std::string& error_msg)
858 auto instance = context()->instance;
859 WINPR_ASSERT(instance);
861 int exit_code = sdl::error::SUCCESS;
862 while (!freerdp_shall_disconnect_context(context()))
864 HANDLE handles[MAXIMUM_WAIT_OBJECTS] = {};
870 if (freerdp_focus_required(instance))
872 auto ctx = get_context(context());
875 auto& input = ctx->getInputChannelContext();
876 if (!input.keyboard_focus_in())
878 if (!input.keyboard_focus_in())
882 const DWORD nCount = freerdp_get_event_handles(context(), handles, ARRAYSIZE(handles));
886 WLog_Print(getWLog(), WLOG_ERROR,
"freerdp_get_event_handles failed");
890 const DWORD status = WaitForMultipleObjects(nCount, handles, FALSE, INFINITE);
892 if (status == WAIT_FAILED)
894 WLog_Print(getWLog(), WLOG_ERROR,
"WaitForMultipleObjects WAIT_FAILED");
898 if (!freerdp_check_event_handles(context()))
900 if (client_auto_reconnect(instance))
903 getDialog().show(
false);
912 if (freerdp_error_info(instance) == 0)
913 exit_code = sdl::error::errorToExitCode(freerdp_get_last_error(context()));
916 if (freerdp_get_last_error(context()) == FREERDP_ERROR_SUCCESS)
917 WLog_Print(getWLog(), WLOG_ERROR,
"WaitForMultipleObjects failed with %" PRIu32
"",
919 if (freerdp_get_last_error(context()) == FREERDP_ERROR_SUCCESS)
920 WLog_Print(getWLog(), WLOG_ERROR,
"Failed to check FreeRDP event handles");
925 if (exit_code == sdl::error::SUCCESS)
929 char* emsg =
nullptr;
931 exit_code = error_info_to_error(&code, &emsg, &elen);
937 if ((code == ERRINFO_LOGOFF_BY_USER) &&
938 (freerdp_get_disconnect_ultimatum(context()) == Disconnect_Ultimatum_user_requested))
940 const char* msg =
"Error info says user did not initiate but disconnect ultimatum says "
941 "they did; treat this as a user logoff";
943 char* emsg =
nullptr;
945 winpr_asprintf(&emsg, &elen,
"%s", msg);
951 WLog_Print(getWLog(), WLOG_INFO,
"%s", msg);
952 exit_code = sdl::error::LOGOFF;
956 if ((exit_code != sdl::error::SUCCESS) && error_msg.empty())
958 const auto last = freerdp_get_last_error(context());
961 winpr_asprintf(&msg, &len,
"%s [0x%08" PRIx32
"]\n%s", freerdp_get_last_error_name(last),
962 last, freerdp_get_last_error_string(last));
968 freerdp_disconnect(instance);
980 std::string error_msg;
981 int exit_code = sdl->sdl_client_thread_connect(error_msg);
982 if (exit_code == sdl::error::SUCCESS)
983 exit_code = sdl->sdl_client_thread_run(error_msg);
984 sdl->sdl_client_cleanup(exit_code, error_msg);
986 return static_cast<DWORD
>(exit_code);
989int SdlContext::error_info_to_error(DWORD* pcode,
char** msg,
size_t* len)
const
991 const DWORD code = freerdp_error_info(context()->instance);
992 const char* name = freerdp_get_error_info_name(code);
993 const char* str = freerdp_get_error_info_string(code);
994 const int exit_code = sdl::error::errorToExitCode(code);
996 winpr_asprintf(msg, len,
"Terminate with %s due to ERROR_INFO %s [0x%08" PRIx32
"]: %s",
997 sdl::error::errorToExitCodeTag(code), name, code, str);
998 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"%s", *msg);
1004void SdlContext::applyMonitorOffset(SDL_WindowID window,
float& x,
float& y)
const
1009 auto w = getWindowForId(window);
1010 x -=
static_cast<float>(w->offsetX());
1011 y -=
static_cast<float>(w->offsetY());
1014void SdlContext::updateMonitorDataFromOffsets()
1016 for (
auto& entry : _windows)
1018 const auto& monitor = _displays.at(entry.first);
1019 entry.second.setMonitor(monitor);
1023bool SdlContext::drawToWindow(
SdlWindow& window,
const std::vector<SDL_Rect>& rects)
1028 auto gdi = context()->gdi;
1031 auto size = window.rect();
1033 std::unique_lock lock(_critical);
1034 auto surface = _primary.get();
1036 if (useLocalScale())
1038 window.setOffsetX(0);
1039 window.setOffsetY(0);
1040 if (gdi->width < size.w)
1042 window.setOffsetX((size.w - gdi->width) / 2);
1044 if (gdi->height < size.h)
1046 window.setOffsetY((size.h - gdi->height) / 2);
1049 _localScale = {
static_cast<float>(size.w) /
static_cast<float>(gdi->width),
1050 static_cast<float>(size.h) /
static_cast<float>(gdi->height) };
1051 if (!window.drawScaledRects(surface, _localScale, rects))
1056 SDL_Point offset{ 0, 0 };
1058 offset = { window.offsetX(), window.offsetY() };
1059 if (!window.drawRects(surface, offset, rects))
1063 window.updateSurface((&window == overlayWindow()) ? &_overlay :
nullptr);
1070 if (_rail.enabled() || _windows.empty())
1072 return &_windows.begin()->second;
1077 return showOverlay(!_overlay.visible());
1080bool SdlContext::showOverlay(
bool on)
1082 if (!_overlay.
show(on))
1084 if (on || !isConnected())
1088 auto window = overlayWindow();
1090 window->updateSurface();
1094bool SdlContext::updateOverlay()
1096 auto window = overlayWindow();
1097 if (!window || !isConnected())
1102 if (!SDL_GetWindowSizeInPixels(window->window(), &w, &h))
1104 if (_overlay.update(w, h, window->rendererName()))
1105 window->updateSurface(&_overlay);
1109bool SdlContext::minimizeAllWindows()
1111 for (
auto& w : _windows)
1112 w.second.minimize();
1116int SdlContext::exitCode()
const
1121SDL_PixelFormat SdlContext::pixelFormat()
const
1123 return _sdlPixelFormat;
1126bool SdlContext::addDisplayWindow(SDL_DisplayID
id)
1129 SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS;
1130 auto title = sdl::utils::windowTitle(context()->settings);
1131 auto w = SdlWindow::create(
id, title, flags);
1132 _windows.emplace(w.id(), std::move(w));
1136bool SdlContext::removeDisplayWindow(SDL_DisplayID
id)
1138 for (
auto& w : _windows)
1140 if (w.second.displayIndex() ==
id)
1141 _windows.erase(w.first);
1146bool SdlContext::detectDisplays()
1149 auto display = SDL_GetDisplays(&count);
1152 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_GetDisplays failed: %s", SDL_GetError());
1155 for (
int x = 0; x < count; x++)
1157 const auto id = display[x];
1158 addOrUpdateDisplay(
id);
1163 if (_displays.empty())
1165 WLog_Print(getWLog(), WLOG_ERROR,
"none of the %d displays has a usable size", count);
1171rdpMonitor SdlContext::getDisplay(SDL_DisplayID
id)
const
1173 return _displays.at(
id);
1176std::vector<SDL_DisplayID> SdlContext::getDisplayIds()
const
1178 std::vector<SDL_DisplayID> keys;
1179 keys.reserve(_displays.size());
1180 for (
const auto& entry : _displays)
1182 keys.push_back(entry.first);
1187const SdlWindow* SdlContext::getWindowForId(SDL_WindowID
id)
const
1189 auto it = _windows.find(
id);
1190 if (it == _windows.end())
1195SdlWindow* SdlContext::getWindowForId(SDL_WindowID
id)
1197 auto it = _windows.find(
id);
1198 if (it == _windows.end())
1203bool SdlContext::allWindowsHidden()
const
1205 return std::all_of(_windows.begin(), _windows.end(),
1206 [](
const auto& entry)
1208 const auto flags = SDL_GetWindowFlags(entry.second.window());
1209 return (flags & (SDL_WINDOW_HIDDEN | SDL_WINDOW_MINIMIZED)) != 0;
1215 if (_windows.empty())
1217 return &_windows.begin()->second;
1225sdlInput& SdlContext::getInputChannelContext()
1230sdlClip& SdlContext::getClipboardChannelContext()
1235SdlRail& SdlContext::getRailChannelContext()
1245wLog* SdlContext::getWLog()
1250bool SdlContext::moveMouseTo(
const SDL_FPoint& pos)
1252 auto window = SDL_GetMouseFocus();
1256 const auto id = SDL_GetWindowID(window);
1257 const auto spos = pixelToScreen(
id, pos);
1258 SDL_WarpMouseInWindow(window, spos.x, spos.y);
1262static bool onWindowEdge(SDL_WindowID
id,
float x,
float y)
1266 auto* window = SDL_GetWindowFromID(
id);
1267 if (!window || !SDL_GetWindowSize(window, &w, &h))
1269 return (x <= 0.0f) || (y <= 0.0f) || (x >=
static_cast<float>(w - 1)) ||
1270 (y >=
static_cast<float>(h - 1));
1273bool SdlContext::handleEvent(
const SDL_MouseMotionEvent& ev)
1278 if (_rail.enabled() && (ev.state == 0) && (ev.windowID == _lastRelease.window) &&
1279 (ev.timestamp - _lastRelease.time < SDL_MS_TO_NS(2)) &&
1280 onWindowEdge(ev.windowID, ev.x, ev.y))
1283 if (_rail.enabled() && _rail.suppressServerMotion(ev.windowID))
1285 if (!(SDL_GetGlobalMouseState(
nullptr,
nullptr) & SDL_BUTTON_LMASK))
1286 _rail.completeLocalMoveIfPending();
1289 if (_rail.enabled() && _rail.translateToServer(ev.windowID, copy.motion.x, copy.motion.y))
1292 ev.windowID, { ev.x, ev.y }, { copy.motion.x, copy.motion.y }, _rail.pointerEpoch()
1294 _rail.noteServerPointer(copy.motion.x, copy.motion.y);
1295 return SdlTouch::handleEvent(
this, copy.motion);
1298 if (!getWindowForId(ev.windowID))
1300 if (!eventToPixelCoordinates(ev.windowID, copy))
1302 removeLocalScaling(copy.motion.x, copy.motion.y);
1303 removeLocalScaling(copy.motion.xrel, copy.motion.yrel);
1304 applyMonitorOffset(copy.motion.windowID, copy.motion.x, copy.motion.y);
1306 return SdlTouch::handleEvent(
this, copy.motion);
1309bool SdlContext::handleEvent(
const SDL_MouseWheelEvent& ev)
1313 if (_rail.enabled() &&
1314 _rail.translateToServer(ev.windowID, copy.wheel.mouse_x, copy.wheel.mouse_y))
1315 return SdlTouch::handleEvent(
this, copy.wheel);
1317 if (!getWindowForId(ev.windowID))
1319 if (!eventToPixelCoordinates(ev.windowID, copy))
1321 removeLocalScaling(copy.wheel.mouse_x, copy.wheel.mouse_y);
1322 return SdlTouch::handleEvent(
this, copy.wheel);
1325bool SdlContext::handleEvent(
const SDL_WindowEvent& ev)
1327 if (!getDisplayChannelContext().handleEvent(ev))
1330 auto window = getWindowForId(ev.windowID);
1334 if (_rail.enabled() && _rail.ownsWindow(ev.windowID))
1338 case SDL_EVENT_WINDOW_MOUSE_ENTER:
1340 if (!(SDL_GetGlobalMouseState(
nullptr,
nullptr) & SDL_BUTTON_LMASK))
1341 _rail.completeLocalMoveIfPending();
1342 _rail.completeWaylandResize();
1344 return restoreCursor();
1345 case SDL_EVENT_WINDOW_MOUSE_LEAVE:
1347 _rail.noteResizeGrab(ev.windowID);
1349 case SDL_EVENT_WINDOW_EXPOSED:
1352 if (!_rail.dragActive(ev.windowID))
1353 _rail.invalidateWindow(ev.windowID);
1355 case SDL_EVENT_WINDOW_MAXIMIZED:
1357 _rail.completeLocalMoveIfPending();
1358 _rail.handleMaximized(ev.windowID);
1360 case SDL_EVENT_WINDOW_MINIMIZED:
1361 _rail.handleMinimized(ev.windowID);
1363 case SDL_EVENT_WINDOW_RESTORED:
1364 _rail.handleRestored(ev.windowID);
1366 case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
1368 _rail.handleClose(ev.windowID);
1370 case SDL_EVENT_WINDOW_FOCUS_GAINED:
1371 _rail.handleFocus(ev.windowID,
true);
1373 case SDL_EVENT_WINDOW_FOCUS_LOST:
1374 _rail.handleFocus(ev.windowID,
false);
1376 case SDL_EVENT_WINDOW_DISPLAY_CHANGED:
1377 _rail.handleDisplayChanged(ev.windowID,
static_cast<SDL_DisplayID
>(ev.data1));
1379 case SDL_EVENT_WINDOW_MOVED:
1380 _rail.notePopupMoved(ev.windowID);
1381 if (!_rail.dragActive(ev.windowID))
1382 _rail.syncGeometry(ev.windowID);
1384 case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
1387 _rail.noteDragResize(ev.windowID, ev.data1, ev.data2);
1388 _rail.syncGeometry(ev.windowID);
1389 _rail.noteResizeGrab(ev.windowID);
1390 std::ignore = drawToWindows({});
1400 const auto& r = window->rect();
1401 const auto& b = window->bounds();
1402 const auto& scale = window->scale();
1403 const auto& orientation = window->orientation();
1404 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
1405 "%s: [%u] %dx%d-%dx%d {%dx%d-%dx%d}{scale=%f,orientation=%s}",
1406 sdl::utils::toString(ev.type).c_str(), ev.windowID, r.x, r.y, r.w, r.h, b.x,
1407 b.y, b.w, b.h,
static_cast<double>(scale),
1408 sdl::utils::toString(orientation).c_str());
1413 case SDL_EVENT_WINDOW_MOUSE_ENTER:
1414 return restoreCursor();
1415 case SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED:
1416 if (!resizeToScale(window))
1421 if (!window->fill())
1423 if (!drawToWindow(*window))
1425 if (!restoreCursor())
1429 case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
1430 if (!resizeToScale(window))
1432 if (!window->fill())
1434 if (!drawToWindow(*window))
1436 if (!restoreCursor())
1440 case SDL_EVENT_WINDOW_MOVED:
1442 auto r = window->rect();
1443 auto id = window->id();
1444 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"%u: %dx%d-%dx%d",
id, r.x, r.y, r.w, r.h);
1447 case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
1449 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"Window closed, terminating RDP session...");
1450 std::ignore = abortConnect();
1459bool SdlContext::handleEvent(
const SDL_DisplayEvent& ev)
1461 if (!getDisplayChannelContext().handleEvent(ev))
1463#if SDL_VERSION_ATLEAST(3, 3, 2)
1464 if (ev.type == SDL_EVENT_DISPLAY_USABLE_BOUNDS_CHANGED)
1465 _rail.noteUsableBoundsChanged(ev.displayID);
1470 case SDL_EVENT_DISPLAY_REMOVED:
1475 if (!SDL_GetDisplayBounds(ev.displayID, &r))
1477 const auto name = SDL_GetDisplayName(ev.displayID);
1480 const auto orientation = SDL_GetCurrentDisplayOrientation(ev.displayID);
1481 const auto scale = SDL_GetDisplayContentScale(ev.displayID);
1482 const auto mode = SDL_GetCurrentDisplayMode(ev.displayID);
1486 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
1487 "%s: [%u, %s] %dx%d-%dx%d {orientation=%s, scale=%f}%s",
1488 sdl::utils::toString(ev.type).c_str(), ev.displayID, name, r.x, r.y, r.w,
1489 r.h, sdl::utils::toString(orientation).c_str(),
static_cast<double>(scale),
1490 sdl::utils::toString(mode).c_str());
1497bool SdlContext::handleEvent(
const SDL_MouseButtonEvent& ev)
1499 SDL_Event copy = {};
1501 if (_rail.enabled())
1504 const bool suppress = _rail.dragActive(ev.windowID);
1505 if (ev.type == SDL_EVENT_MOUSE_BUTTON_UP)
1506 _rail.completeLocalMoveIfPending();
1509 if (ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN)
1510 _rail.completeWaylandResize(
true);
1512 if (ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN)
1513 _rail.ensureActive(ev.windowID);
1516 if (ev.type == SDL_EVENT_MOUSE_BUTTON_UP)
1518 _lastRelease = { ev.windowID, ev.timestamp };
1520 if (_rail.translateToServer(ev.windowID, copy.button.x, copy.button.y))
1523 if ((ev.windowID == _lastMotion.window) &&
1524 (_lastMotion.epoch == _rail.pointerEpoch()) &&
1525 (fabsf(ev.x - _lastMotion.local.x) < FLT_EPSILON) &&
1526 (fabsf(ev.y - _lastMotion.local.y) < FLT_EPSILON))
1528 copy.button.x = _lastMotion.server.x;
1529 copy.button.y = _lastMotion.server.y;
1533 if ((ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN) && (ev.button == SDL_BUTTON_LEFT))
1534 _rail.noteLeftPress(copy.button.x, copy.button.y);
1535 return SdlTouch::handleEvent(
this, copy.button);
1539 if (!getWindowForId(ev.windowID))
1541 if (!eventToPixelCoordinates(ev.windowID, copy))
1543 removeLocalScaling(copy.button.x, copy.button.y);
1544 applyMonitorOffset(copy.button.windowID, copy.button.x, copy.button.y);
1545 return SdlTouch::handleEvent(
this, copy.button);
1548bool SdlContext::handleEvent(
const SDL_TouchFingerEvent& ev)
1550 if (!getWindowForId(ev.windowID))
1554 if (!eventToPixelCoordinates(ev.windowID, copy))
1556 removeLocalScaling(copy.tfinger.dx, copy.tfinger.dy);
1557 removeLocalScaling(copy.tfinger.x, copy.tfinger.y);
1558 applyMonitorOffset(copy.tfinger.windowID, copy.tfinger.x, copy.tfinger.y);
1559 return SdlTouch::handleEvent(
this, copy.tfinger);
1562void SdlContext::addOrUpdateDisplay(SDL_DisplayID
id)
1564 auto monitor = SdlWindow::query(
id,
false);
1565 if ((monitor.width <= 0) || (monitor.height <= 0))
1567 WLog_Print(getWLog(), WLOG_WARN,
"display %" PRIu32
" has no usable size, skipped",
id);
1570 _displays.emplace(
id, monitor);
1575 _displayBounds.clear();
1576 for (
const auto& entry : _displays)
1579 std::ignore = SDL_GetDisplayBounds(entry.first, &bounds);
1580 _displayBounds.emplace(entry.first, bounds);
1582 _primaryDisplay = SDL_GetPrimaryDisplay();
1583 updateDisplayOffsets();
1584 updateMonitorDataFromOffsets();
1587void SdlContext::updateDisplayOffsets()
1592 for (
const auto& entry : _displays)
1595 const auto found = _displayBounds.find(entry.first);
1596 if (found != _displayBounds.end())
1597 bounds = found->second;
1600 pixel.w = entry.second.width;
1601 pixel.h = entry.second.height;
1602 _offsets.emplace(entry.first, std::pair{ bounds, pixel });
1605 if (_offsets.empty())
1607 sdl_display_offsets::update(_offsets, _primaryDisplay, _monitorIds);
1608 for (
auto& entry : _displays)
1610 const auto& pixel = _offsets.at(entry.first).second;
1611 entry.second.x = pixel.x;
1612 entry.second.y = pixel.y;
1616void SdlContext::deleteDisplay(SDL_DisplayID
id)
1618 _displays.erase(
id);
1621bool SdlContext::eventToPixelCoordinates(SDL_WindowID
id, SDL_Event& ev)
1623 auto w = getWindowForId(
id);
1628 auto renderer = w->renderer();
1631 return SDL_ConvertEventToRenderCoordinates(renderer, &ev);
1634SDL_FPoint SdlContext::applyLocalScaling(
const SDL_FPoint& val)
const
1636 if (!useLocalScale())
1640 rval.x *= _localScale.x;
1641 rval.y *= _localScale.y;
1645void SdlContext::removeLocalScaling(
float& x,
float& y)
const
1647 if (!useLocalScale())
1653SDL_FPoint SdlContext::screenToPixel(SDL_WindowID
id,
const SDL_FPoint& pos)
1655 auto w = getWindowForId(
id);
1659 if (_rail.enabled() && _rail.ownsWindow(
id))
1665 auto renderer = w->renderer();
1670 if (!SDL_RenderCoordinatesFromWindow(renderer, pos.x, pos.y, &rpos.x, &rpos.y))
1672 removeLocalScaling(rpos.x, rpos.y);
1676SDL_FPoint SdlContext::pixelToScreen(SDL_WindowID
id,
const SDL_FPoint& pos)
1678 auto w = getWindowForId(
id);
1681 if (_rail.enabled() && _rail.ownsWindow(
id))
1687 auto renderer = w->renderer();
1692 if (!SDL_RenderCoordinatesToWindow(renderer, pos.x, pos.y, &rpos.x, &rpos.y))
1694 return applyLocalScaling(rpos);
1697SDL_FRect SdlContext::pixelToScreen(SDL_WindowID
id,
const SDL_FRect& pos,
bool round)
1699 const auto fpos = pixelToScreen(
id, SDL_FPoint{ pos.x, pos.y });
1700 const auto size = pixelToScreen(
id, SDL_FPoint{ pos.w, pos.h });
1701 SDL_FRect r{ fpos.x, fpos.y, size.x, size.y };
1704 r.w = std::ceil(r.w);
1705 r.h = std::ceil(r.h);
1706 r.x = std::floor(r.x);
1707 r.y = std::floor(r.y);
1712bool SdlContext::handleEvent(
const SDL_Event& ev)
1714 if ((ev.type >= SDL_EVENT_DISPLAY_FIRST) && (ev.type <= SDL_EVENT_DISPLAY_LAST))
1716 const auto& dev = ev.display;
1717 return handleEvent(dev);
1719 if ((ev.type >= SDL_EVENT_WINDOW_FIRST) && (ev.type <= SDL_EVENT_WINDOW_LAST))
1721 const auto& wev = ev.window;
1722 return handleEvent(wev);
1726 case SDL_EVENT_RENDER_TARGETS_RESET:
1727 case SDL_EVENT_RENDER_DEVICE_RESET:
1728 case SDL_EVENT_WILL_ENTER_FOREGROUND:
1739 case SDL_EVENT_FINGER_DOWN:
1740 case SDL_EVENT_FINGER_UP:
1741 case SDL_EVENT_FINGER_MOTION:
1743 const auto& cev = ev.tfinger;
1744 return handleEvent(cev);
1746 case SDL_EVENT_MOUSE_MOTION:
1749 const auto& cev = ev.motion;
1750 return handleEvent(cev);
1752 case SDL_EVENT_MOUSE_BUTTON_DOWN:
1753 case SDL_EVENT_MOUSE_BUTTON_UP:
1755 const auto& cev = ev.button;
1756 return handleEvent(cev);
1758 case SDL_EVENT_MOUSE_WHEEL:
1760 const auto& cev = ev.wheel;
1761 return handleEvent(cev);
1763 case SDL_EVENT_CLIPBOARD_UPDATE:
1765 const auto& cev = ev.clipboard;
1766 return getClipboardChannelContext().handleEvent(cev);
1768 case SDL_EVENT_KEY_DOWN:
1769 case SDL_EVENT_KEY_UP:
1771 const auto& cev = ev.key;
1772 return getInputChannelContext().handleEvent(cev);
1781 return _args.data();
1784size_t SdlContext::argsCount()
const
1786 if (_args.size() <= 1)
1788 return _args.size() - 1;
1793 auto sdl =
static_cast<SdlContext*
>(custom);
1799 if (strcmp(arg->Name, sdl_allow_screensaver) == 0)
1801 sdl->_allowScreenSaver = (arg->Value !=
nullptr);
1802 if (arg->Value !=
nullptr)
1804 if (!SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER,
"1"))
1806 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
1807 "SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER) failed with %s",
1813 else if (strcmp(arg->Name, sdl_connection_dialog) == 0)
1814 sdl->_connectionDialog = (arg->Value !=
nullptr);
1815 else if (strcmp(arg->Name, sdl_info) == 0)
1817 if (!sdl->_overlay.
show(arg->Value !=
nullptr))
1824void SdlContext::applyMonitorScaleOverride(
rdpMonitor& monitor)
const
1826 freerdp_client_apply_monitor_scale(context()->settings, &monitor);
1834std::vector<rdpPointer*>& SdlContext::pointers()
1836 return _valid_pointers;
1839bool SdlContext::contains(
const rdpPointer* ptr)
const
1841 for (
const auto& cur : _valid_pointers)
1849bool SdlContext::credentialsRead()
const
1851 return _credentialsRead;
1854void SdlContext::setCredentialsRead()
1856 _credentialsRead =
true;
1861 return horizontal ? _wheelX : _wheelY;
1864bool SdlContext::resizeToScale(
SdlWindow* window)
1868 if (!useLocalScale())
1872 return window->resizeToScale();
1875bool SdlContext::useLocalScale()
const
1880 const auto dynResize =
1884 return !dynResize && !fs && !multimon;
1887bool SdlContext::drawToWindows(
const std::vector<SDL_Rect>& rects)
1890 if (_rail.enabled())
1892 for (
auto& window : _windows)
1894 if ((SDL_GetWindowFlags(window.second.window()) & SDL_WINDOW_HIDDEN) == 0)
1895 SDL_HideWindow(window.second.window());
1898 std::unique_lock lock(_critical);
1899 _rail.paint(_primary.get(), pixelFormat(), rects);
1906 !_rail.desktopMayShow())
1908 bool firstShow =
false;
1909 for (
auto& window : _windows)
1911 if (SDL_GetWindowFlags(window.second.window()) & SDL_WINDOW_HIDDEN)
1913 SDL_ShowWindow(window.second.window());
1914 SDL_RaiseWindow(window.second.window());
1919 if (rects.empty() && !firstShow)
1922 std::vector<SDL_Rect> drawRects = rects;
1924 std::unique_lock lock(_critical);
1925 if ((drawRects.empty() || firstShow) && _primary)
1926 drawRects = { { 0, 0, _primary->w, _primary->h } };
1929 for (
auto& window : _windows)
1931 if (!drawToWindow(window.second, drawRects))
1938BOOL SdlContext::desktopResize(rdpContext* context)
1940 rdpGdi* gdi =
nullptr;
1941 rdpSettings* settings =
nullptr;
1942 auto sdl = get_context(context);
1945 WINPR_ASSERT(context);
1947 settings = context->settings;
1948 WINPR_ASSERT(settings);
1950 std::unique_lock lock(sdl->_critical);
1955 return sdl->createPrimary();
1959BOOL SdlContext::playSound(rdpContext* context,
const PLAY_SOUND_UPDATE* play_sound)
1962 WINPR_UNUSED(context);
1963 WINPR_UNUSED(play_sound);
1969BOOL SdlContext::beginPaint(rdpContext* context)
1971 auto gdi = context->gdi;
1973 WINPR_ASSERT(gdi->primary);
1975 HGDI_DC hdc = gdi->primary->hdc;
1980 HGDI_WND hwnd = hdc->hwnd;
1981 WINPR_ASSERT(hwnd->invalid);
1982 hwnd->invalid->null = TRUE;
1988bool SdlContext::redraw(
bool suppress)
const
1997 auto gdi = context()->gdi;
1999 return gdi_send_suppress_output(gdi, suppress);
2002void SdlContext::setConnected(
bool val)
2007bool SdlContext::isConnected()
const
2014bool SdlContext::abortConnect()
const
2016 freerdp_set_last_error(context(), FREERDP_ERROR_CONNECT_CANCELLED);
2017 return freerdp_abort_connect_context(context());
2020rdpContext* SdlContext::context()
const
2022 WINPR_ASSERT(_context);
2026rdpClientContext* SdlContext::common()
const
2028 return reinterpret_cast<rdpClientContext*
>(context());
2031bool SdlContext::setCursor(CursorType type)
2034 return restoreCursor();
2037bool SdlContext::setCursor(
const rdpPointer* cursor)
2039 std::unique_lock lock(_critical);
2040 if (!contains(cursor))
2043 _cursor = { sdl_Pointer_Copy(cursor), sdl_PointerFreeCopyAll };
2044 return setCursor(CURSOR_IMAGE);
2047rdpPointer* SdlContext::cursor()
const
2049 return _cursor.get();
2052bool SdlContext::restoreCursor()
2054 WLog_Print(getWLog(), WLOG_TRACE,
"restore cursor: %d", _cursorType);
2055 switch (_cursorType)
2058 if (!SDL_HideCursor())
2060 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_HideCursor failed");
2064 setHasCursor(
false);
2067 case CURSOR_DEFAULT:
2069 auto def = SDL_GetDefaultCursor();
2070 if (!SDL_SetCursor(def))
2072 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_SetCursor(default=%p) failed",
2073 static_cast<void*
>(def));
2076 if (!SDL_ShowCursor())
2078 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_ShowCursor failed");
2086 return sdl_Pointer_Set_Process(
this);
2088 WLog_Print(getWLog(), WLOG_ERROR,
"Unknown cursorType %s",
2089 sdl::utils::toString(_cursorType).c_str());
2094void SdlContext::setMonitorIds(
const std::vector<SDL_DisplayID>& ids)
2096 _monitorIds.clear();
2099 _monitorIds.push_back(
id);
2104 updateDisplayOffsets();
2107const std::vector<SDL_DisplayID>& SdlContext::monitorIds()
const
2112int64_t SdlContext::monitorId(uint32_t index)
const
2114 if (index >= _monitorIds.size())
2118 return _monitorIds.at(index);
2121void SdlContext::push(std::vector<SDL_Rect>&& rects)
2123 std::unique_lock lock(_queue_mux);
2124 _queue.emplace(std::move(rects));
2127std::vector<SDL_Rect> SdlContext::pop()
2129 std::unique_lock lock(_queue_mux);
2134 auto val = std::move(_queue.front());
2139bool SdlContext::setFullscreen(
bool enter,
bool forceOriginalDisplay)
2141 for (
const auto& window : _windows)
2143 if (!sdl_push_user_event(SDL_EVENT_USER_WINDOW_FULLSCREEN, &window.second, enter,
2144 forceOriginalDisplay))
2147 _fullscreen = enter;
2151bool SdlContext::setMinimized()
2153 return sdl_push_user_event(SDL_EVENT_USER_WINDOW_MINIMIZE);
2156bool SdlContext::grabMouse()
const
2161bool SdlContext::toggleGrabMouse()
2163 return setGrabMouse(!grabMouse());
2166bool SdlContext::setGrabMouse(
bool enter)
2172bool SdlContext::grabKeyboard()
const
2174 return _grabKeyboard;
2177bool SdlContext::toggleGrabKeyboard()
2179 return setGrabKeyboard(!grabKeyboard());
2182bool SdlContext::setGrabKeyboard(
bool enter)
2184 _grabKeyboard = enter;
2188bool SdlContext::setResizeable(
bool enable)
2190 const auto settings = context()->settings;
2193 bool use = (dyn && enable) || smart;
2195 for (
const auto& window : _windows)
2197 if (!sdl_push_user_event(SDL_EVENT_USER_WINDOW_RESIZEABLE, &window.second, use))
2205bool SdlContext::resizeable()
const
2210bool SdlContext::toggleResizeable()
2212 return setResizeable(!resizeable());
2215bool SdlContext::fullscreen()
const
2220bool SdlContext::toggleFullscreen()
2222 return setFullscreen(!fullscreen());
2229 const bool scale = fabsf(a.scale - b.scale) <= FLT_EPSILON;
2230 return (a.hwnd == b.hwnd) && (a.remoteWidth == b.remoteWidth) &&
2231 (a.remoteHeight == b.remoteHeight) && (a.viewWidth == b.viewWidth) &&
2232 (a.viewHeight == b.viewHeight) && (a.scrollX == b.scrollX) && (a.scrollY == b.scrollY) &&
2237static HWND native_window(SDL_Window* window)
2241 auto props = SDL_GetWindowProperties(window);
2243 return static_cast<HWND
>(
2244 SDL_GetPointerProperty(props, SDL_PROP_WINDOW_WIN32_HWND_POINTER,
nullptr));
2246 return reinterpret_cast<HWND
>(
2247 static_cast<uintptr_t
>(SDL_GetNumberProperty(props, SDL_PROP_WINDOW_X11_WINDOW_NUMBER, 0)));
2254 auto window = getFirstWindow();
2255 if (window && window->window())
2257 auto settings = _context->settings;
2258 info.hwnd = native_window(window->window());
2265 if (SDL_GetWindowSizeInPixels(window->window(), &w, &h))
2268 info.viewHeight = h;
2271 const float density = SDL_GetWindowPixelDensity(window->window());
2272 const auto p0 = pixelToScreen(window->id(), SDL_FPoint{ 0, 0 });
2273 const auto p1 = pixelToScreen(window->id(), SDL_FPoint{ 1000, 1000 });
2274 const float scale = (p1.x - p0.x) * density / 1000.0f;
2275 info.scale = (scale > 0.0f) ? scale : 1.0f;
2279 std::scoped_lock lock(_windowInfoLock);
2280 if (window_info_equal(info, _desktopWindowInfo))
2282 _desktopWindowInfo = info;
2284 if (!_rail.enabled())
2285 freerdp_client_window_info_service_changed(_context->windowInfoService, 0);
2292 std::scoped_lock lock(_windowInfoLock);
2293 first = _railWindowInfoPending.empty();
2294 _railWindowInfoPending.insert(remoteId);
2297 std::ignore = sdl_push_user_event(SDL_EVENT_USER_WINDOW_INFO);
2302 std::set<uint64_t> pending;
2304 std::scoped_lock lock(_windowInfoLock);
2305 pending.swap(_railWindowInfoPending);
2308 for (
const auto id : pending)
2311 SDL_Window* window =
nullptr;
2313 if (_rail.windowGeometry(
id, window, info.viewWidth, info.viewHeight))
2315 info.hwnd = native_window(window);
2316 info.remoteWidth = info.viewWidth;
2317 info.remoteHeight = info.viewHeight;
2320 std::scoped_lock lock(_windowInfoLock);
2321 if (info.viewWidth > 0)
2322 _railWindowInfo[id] = info;
2324 _railWindowInfo.erase(
id);
2326 if (info.viewWidth > 0)
2327 freerdp_client_window_info_service_changed(_context->windowInfoService,
id);
2331HRESULT SdlContext::windowInfoGet(
void* custom, UINT64 remoteHwnd,
WTS_WINDOW_INFO* info)
2337 std::scoped_lock lock(
sdl->_windowInfoLock);
2338 if (!
sdl->_rail.enabled())
2341 if (!
sdl->_desktopWindowInfo.hwnd && (
sdl->_desktopWindowInfo.viewWidth == 0))
2342 return E_UNEXPECTED;
2343 *info =
sdl->_desktopWindowInfo;
2346 auto it = sdl->_railWindowInfo.find(remoteHwnd);
2347 if (it == sdl->_railWindowInfo.end())
2348 return E_INVALIDARG;
2353UINT32 SdlContext::windowInfoSessionType(
void* custom)
2355 auto sdl =
static_cast<SdlContext*
>(custom);
2357 return sdl->_rail.enabled() ? WTS_RDP_SESSION_TYPE_REMOTEAPP : WTS_RDP_SESSION_TYPE_DESKTOP;
2365 std::scoped_lock lock(_rendererLock);
2366 const auto id = _nextRenderer++;
2367 auto& r = _renderers[id];
2368 r.mappingId = mappingId;
2369 r.callback = callback;
2375bool SdlContext::rendererFrame(Uint64
id,
const BYTE* data, UINT32 width, UINT32 height,
2382 std::scoped_lock lock(_rendererLock);
2383 auto it = _renderers.find(
id);
2384 if (it == _renderers.end())
2386 auto& r = it->second;
2388 const size_t row =
static_cast<size_t>(width) * 4;
2389 r.pixels.resize(row * height);
2390 for (UINT32 y = 0; y < height; y++)
2392 const auto offset = row * y;
2393 const auto end = offset + row;
2394 const auto dataoffset = 1ull * y *
static_cast<size_t>(stride);
2398 auto& ptr = r.pixels.at(offset);
2399 std::ignore = r.pixels.at(end);
2400 memcpy(&ptr, &data[dataoffset], row);
2402 catch (std::out_of_range& ex)
2404 SDL_Log(
"failed to render: %s", ex.what());
2408 r.pitch =
static_cast<int>(row);
2409 r.width =
static_cast<int>(width);
2410 r.height =
static_cast<int>(height);
2417void SdlContext::rendererRemove(Uint64
id)
2419 IWTSBitmapRendererCallback* callback =
nullptr;
2421 std::scoped_lock lock(_rendererLock);
2422 auto it = _renderers.find(
id);
2423 if (it == _renderers.end())
2425 callback = it->second.callback;
2426 _renderers.erase(it);
2429 callback->Release();
2433bool SdlContext::hasRenderers()
2435 std::scoped_lock lock(_rendererLock);
2436 return !_renderers.empty();
2439void SdlContext::renderersChanged()
2442 if (!_renderersPending.exchange(
true))
2443 std::ignore = sdl_push_user_event(SDL_EVENT_USER_RENDERER);
2448 _renderersPending =
false;
2453 std::vector<std::pair<IWTSBitmapRendererCallback*, WTS_RECT>> targets;
2455 std::scoped_lock lock(_rendererLock);
2460 bool visible =
false;
2462 std::vector<SDL_Rect> region;
2464 std::map<Uint64, Placement> placements;
2465 rdpGdi* gdi = _context->gdi;
2466 GeometryClientContext* geometry = gdi ? gdi->geometry :
nullptr;
2467 if (geometry && geometry->geometries)
2469 HashTable_Lock(geometry->geometries);
2470 for (
auto& kv : _renderers)
2472 auto g =
static_cast<const MAPPED_GEOMETRY*
>(
2473 HashTable_GetItemValue(geometry->geometries, &kv.second.mappingId));
2477 p.rect = {
static_cast<int>(g->topLevelLeft + g->left),
2478 static_cast<int>(g->topLevelTop + g->top),
2479 static_cast<int>(std::max<INT64>(0, g->right - g->left)),
2480 static_cast<int>(std::max<INT64>(0, g->bottom - g->top)) };
2481 p.visible = (p.rect.w > 0) && (p.rect.h > 0);
2484 for (UINT32 i = 0; g->geometry.rects && (i < g->geometry.nRectCount); i++)
2486 const RDP_RECT& r = g->geometry.rects[i];
2487 const int left = std::max(0,
static_cast<int>(r.x));
2488 const int top = std::max(0,
static_cast<int>(r.y));
2489 const int right = std::min(p.rect.w, r.x + r.width);
2490 const int bottom = std::min(p.rect.h, r.y + r.height);
2491 if ((right <= left) || (bottom <= top))
2493 area +=
static_cast<INT64
>(right - left) * (bottom - top);
2495 { p.rect.x + left, p.rect.y + top, right - left, bottom - top });
2497 if (area >=
static_cast<INT64
>(p.rect.w) * p.rect.h)
2499 placements[kv.first] = std::move(p);
2501 HashTable_Unlock(geometry->geometries);
2504 for (
auto& kv : _renderers)
2506 auto& r = kv.second;
2507 const auto& p = placements[kv.first];
2508 if (p.visible && r.callback && !SDL_RectsEqual(&p.rect, &r.target))
2511 r.callback->AddRef();
2512 targets.emplace_back(r.callback,
WTS_RECT{ p.rect.x, p.rect.y, p.rect.x + p.rect.w,
2513 p.rect.y + p.rect.h });
2517 for (
auto& w : _windows)
2519 auto& window = w.second;
2520 window.pruneVideoOverlays([
this](Uint64
id) {
return _renderers.count(
id) != 0; });
2521 for (
auto& kv : _renderers)
2523 auto& r = kv.second;
2524 const auto& p = placements[kv.first];
2526 SDL_Point offset{ 0, 0 };
2527 if (!useLocalScale() &&
2529 offset = { window.offsetX(), window.offsetY() };
2530 auto toWindow = [&](
const SDL_Rect& rc)
2532 if (useLocalScale())
2533 return SDL_FRect{
static_cast<float>(rc.x) * _localScale.x,
2534 static_cast<float>(rc.y) * _localScale.y,
2535 static_cast<float>(rc.w) * _localScale.x,
2536 static_cast<float>(rc.h) * _localScale.y };
2537 return SDL_FRect{
static_cast<float>(rc.x + offset.x),
2538 static_cast<float>(rc.y + offset.y),
static_cast<float>(rc.w),
2539 static_cast<float>(rc.h) };
2541 const SDL_FRect dst = toWindow(p.rect);
2542 std::vector<SDL_FRect> clip;
2543 clip.reserve(p.region.size());
2544 for (
const auto& rc : p.region)
2545 clip.push_back(toWindow(rc));
2546 const bool visible = p.visible && !r.pixels.empty();
2547 if (!window.setVideoOverlay(kv.first, r.dirty ? r.pixels.data() :
nullptr, r.pitch,
2548 r.width, r.height, dst, clip, visible))
2551 window.updateSurface();
2553 for (
auto& kv : _renderers)
2554 kv.second.dirty =
false;
2557 for (
auto& t : targets)
2559 std::ignore = t.first->OnTargetSizeChanged(t.second);
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.
what the client gives the service to answer from
same layout as Win32's RECT, which winpr doesn't have on POSIX