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>
44static constexpr auto sdl_allow_screensaver =
"sdl-allow-screensaver";
45static constexpr auto sdl_connection_dialog =
"sdl-connection-dialog";
46static constexpr auto sdl_info =
"sdl-info";
48SdlContext::SdlContext(rdpContext* context)
49 : _context(context), _log(WLog_Get(CLIENT_TAG(
"SDL"))), _cursor(nullptr, sdl_Pointer_FreeCopy),
50 _rdpThreadRunning(false), _primary(nullptr, SDL_DestroySurface), _disp(this), _input(this),
51 _clip(this), _rail(this), _dialog(_log)
53 WINPR_ASSERT(context);
56 auto instance = _context->instance;
57 WINPR_ASSERT(instance);
59 instance->PreConnect = preConnect;
60 instance->PostConnect = postConnect;
61 instance->PostDisconnect = postDisconnect;
62 instance->PostFinalDisconnect = postFinalDisconnect;
63 instance->AuthenticateEx = sdl_authenticate_ex;
64 instance->VerifyCertificateEx = sdl_verify_certificate_ex;
65 instance->VerifyChangedCertificateEx = sdl_verify_changed_certificate_ex;
66 instance->LogonErrorInfo = sdl_logon_error_info;
67 instance->PresentGatewayMessage = sdl_present_gateway_message;
68 instance->ChooseSmartcard = sdl_choose_smartcard;
69 instance->RetryDialog = sdl_retry_dialog;
70 instance->GetAccessToken = client_failsafe_get_access_token;
74 _args.push_back({ sdl_allow_screensaver, COMMAND_LINE_VALUE_BOOL,
nullptr, BoolValueFalse,
76 "Allow local screensaver to activate (default: on for RemoteApp)" });
78 _args.push_back({ sdl_connection_dialog, COMMAND_LINE_VALUE_BOOL,
nullptr,
"on",
nullptr, -1,
79 nullptr,
"the connection dialog with progress and errors" });
80 _args.push_back({ sdl_info, COMMAND_LINE_VALUE_BOOL,
nullptr, BoolValueFalse,
nullptr, -1,
82 "the stats and info overlay from the start (its hotkey SDL_Info, default "
83 "<modifier>+I, shows and hides it)" });
86 _args.push_back({
nullptr, 0,
nullptr,
nullptr,
nullptr, -1,
nullptr,
nullptr });
89 _context->windowInfoService = freerdp_client_window_info_service_new(&source);
90 if (!_context->windowInfoService)
91 WLog_Print(_log, WLOG_WARN,
"no window info service: channels won't know our windows");
92 _context->bitmapRenderService = sdl_render_service_new(
this);
93 if (!_context->bitmapRenderService)
94 WLog_Print(_log, WLOG_WARN,
"no bitmap render service: no redirected video");
97SdlContext::~SdlContext()
100 if (_context->windowInfoService)
102 freerdp_client_window_info_service_detach(_context->windowInfoService);
103 _context->windowInfoService->Release();
104 _context->windowInfoService =
nullptr;
106 if (_context->bitmapRenderService)
108 sdl_render_service_detach(_context->bitmapRenderService);
109 _context->bitmapRenderService->Release();
110 _context->bitmapRenderService =
nullptr;
113 std::scoped_lock lock(_rendererLock);
114 for (
auto& kv : _renderers)
116 if (kv.second.callback)
117 kv.second.callback->Release();
122std::optional<bool> SdlContext::allowScreenSaver()
const
124 return _allowScreenSaver;
127void SdlContext::setHasCursor(
bool val)
129 this->_cursor_visible = val;
132bool SdlContext::hasCursor()
const
134 return _cursor_visible;
137void SdlContext::setMetadata()
140 if (!wmclass || (strlen(wmclass) == 0))
141 wmclass = SDL_CLIENT_UUID;
143 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_IDENTIFIER_STRING, wmclass);
144 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_NAME_STRING, SDL_CLIENT_NAME);
145 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_VERSION_STRING, SDL_CLIENT_VERSION);
146 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_CREATOR_STRING, SDL_CLIENT_VENDOR);
147 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_COPYRIGHT_STRING, SDL_CLIENT_COPYRIGHT);
148 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_URL_STRING, SDL_CLIENT_URL);
149 SDL_SetAppMetadataProperty(SDL_PROP_APP_METADATA_TYPE_STRING, SDL_CLIENT_TYPE);
152int SdlContext::start()
154 _thread = std::thread(rdpThreadRun,
this);
158int SdlContext::join()
162 HANDLE
event = freerdp_abort_event(context());
163 if (!SetEvent(event))
170void SdlContext::cleanup()
172 std::unique_lock lock(_critical);
178bool SdlContext::shallAbort(
bool ignoreDialogs)
180 std::unique_lock lock(_critical);
181 if (freerdp_shall_disconnect_context(context()))
185 if (_rdpThreadRunning)
187 return !getDialog().isRunning();
194BOOL SdlContext::preConnect(freerdp* instance)
196 WINPR_ASSERT(instance);
197 WINPR_ASSERT(instance->context);
199 auto sdl = get_context(instance->context);
201 auto settings = instance->context->settings;
202 WINPR_ASSERT(settings);
217 if (PubSub_SubscribeChannelConnected(instance->context->pubSub,
218 sdl_OnChannelConnectedEventHandler) < 0)
220 if (PubSub_SubscribeChannelDisconnected(instance->context->pubSub,
221 sdl_OnChannelDisconnectedEventHandler) < 0)
223 if (PubSub_SubscribeUserNotification(instance->context->pubSub,
224 sdl_OnUserNotificationEventHandler) < 0)
230 UINT32 maxHeight = 0;
232 if (!sdl_detect_monitors(sdl, &maxWidth, &maxHeight))
239 if (((overrides & FREERDP_MONITOR_OVERRIDE_DESKTOP_SCALE) == 0) &&
245 auto monitor =
static_cast<const rdpMonitor*
>(
246 freerdp_settings_get_pointer_array(settings, FreeRDP_MonitorDefArray, x));
247 if (monitor && monitor->is_primary)
248 scale = monitor->attributes.desktopScaleFactor;
250 if ((scale == 0) && !sdl->monitorIds().empty())
251 scale = sdl->getDisplay(sdl->monitorIds().front()).attributes.desktopScaleFactor;
252 if ((scale >= 100) && (scale <= 500))
260 if ((overrides == 0) &&
265 if ((maxWidth != 0) && (maxHeight != 0) &&
268 WLog_Print(sdl->getWLog(), WLOG_INFO,
"Update size to %ux%u", maxWidth, maxHeight);
283 if (sm && (sw > 0) && (sh > 0))
287 WLog_Print(sdl->getWLog(), WLOG_WARN,
288 "/smart-sizing and /multimon are currently not supported, ignoring "
307 WLog_Print(sdl->getWLog(), WLOG_INFO,
308 "auth-only, but no password set. Please provide one.");
315 WLog_Print(sdl->getWLog(), WLOG_INFO,
"Authentication only. Don't connect SDL.");
318 if (!sdl->getInputChannelContext().initialize())
321 sdl->_credentialsRead =
false;
324 auto prefs = SdlPref::instance();
325 auto dialog = prefs->get_bool(
"SDL_ConnectionDialog",
true);
326 if (sdl->_connectionDialog && prefs->is_commandline_override_allowed())
327 dialog = *sdl->_connectionDialog;
330 sdl->getDialog().create(instance->context);
332 sdl->getDialog().showInfo(
"The connection is being established\n\nPlease wait...");
347BOOL SdlContext::postConnect(freerdp* instance)
349 WINPR_ASSERT(instance);
351 auto context = instance->context;
352 WINPR_ASSERT(context);
354 auto sdl = get_context(context);
357 sdl->getDialog().show(
false);
364 WLog_Print(sdl->getWLog(), WLOG_INFO,
365 "auth-only, but no password set. Please provide one.");
369 WLog_Print(sdl->getWLog(), WLOG_INFO,
"Authentication only. Don't connect to X.");
373 if (!sdl->waitForWindowsCreated())
376 sdl->_sdlPixelFormat = SDL_PIXELFORMAT_BGRA32;
377 if (!gdi_init(instance, PIXEL_FORMAT_BGRA32))
380 if (!sdl->createPrimary())
383 if (!sdl_register_pointer(instance->context->graphics))
386 WINPR_ASSERT(context->update);
388 context->update->BeginPaint = beginPaint;
389 context->update->EndPaint = endPaint;
390 context->update->PlaySound = playSound;
391 context->update->DesktopResize = desktopResize;
392 context->update->SetKeyboardIndicators = sdlInput::keyboard_set_indicators;
393 context->update->SetKeyboardImeStatus = sdlInput::keyboard_set_ime_status;
395 if (!sdl->setResizeable(
false))
401 sdl->setConnected(
true);
403 return sdl->_overlay.connected();
409void SdlContext::postDisconnect(freerdp* instance)
414 if (!instance->context)
417 auto sdl = get_context(instance->context);
418 sdl->setConnected(
false);
423void SdlContext::postFinalDisconnect(freerdp* instance)
428 if (!instance->context)
431 PubSub_UnsubscribeChannelConnected(instance->context->pubSub,
432 sdl_OnChannelConnectedEventHandler);
433 PubSub_UnsubscribeChannelDisconnected(instance->context->pubSub,
434 sdl_OnChannelDisconnectedEventHandler);
435 PubSub_UnsubscribeUserNotification(instance->context->pubSub,
436 sdl_OnUserNotificationEventHandler);
440bool SdlContext::createPrimary()
442 auto gdi = context()->gdi;
445 _primary = SDLSurfacePtr(
446 SDL_CreateSurfaceFrom(
static_cast<int>(gdi->width),
static_cast<int>(gdi->height),
447 pixelFormat(), gdi->primary_buffer,
static_cast<int>(gdi->stride)),
452 SDL_SetSurfaceBlendMode(_primary.get(), SDL_BLENDMODE_NONE);
453 SDL_Rect surfaceRect = { 0, 0, gdi->width, gdi->height };
454 SDL_FillSurfaceRect(_primary.get(), &surfaceRect,
455 SDL_MapSurfaceRGBA(_primary.get(), 0, 0, 0, 0xff));
460bool SdlContext::createWindows()
462 auto settings = context()->settings;
463 const auto& title = windowTitle();
465 ScopeGuard guard1([&]() { _windowsCreatedEvent.set(); });
471 auto monitorFor = [&](UINT32 index, int64_t id)
473 for (UINT32 y = 0; y < windowCount; y++)
475 auto cur =
static_cast<rdpMonitor*
>(
476 freerdp_settings_get_pointer_array_writable(settings, FreeRDP_MonitorDefArray, y));
477 if (cur && (
static_cast<int64_t
>(cur->orig_screen) ==
id))
480 return static_cast<rdpMonitor*
>(
481 freerdp_settings_get_pointer_array_writable(settings, FreeRDP_MonitorDefArray, index));
486 for (UINT32 x = 0; x < windowCount; x++)
488 auto id = monitorId(x);
492 auto monitor = monitorFor(x,
id);
494 originX = std::min<Sint32>(monitor->x, originX);
495 originY = std::min<Sint32>(monitor->y, originY);
498 for (UINT32 x = 0; x < windowCount; x++)
500 auto id = monitorId(x);
504 auto monitor = monitorFor(x,
id);
506 Uint32 w = WINPR_ASSERTING_INT_CAST(Uint32, monitor->width);
507 Uint32 h = WINPR_ASSERTING_INT_CAST(Uint32, monitor->height);
511 if (_windowWidth > 0)
516 if (_windowHeight > 0)
522 Uint32 flags = SDL_WINDOW_HIGH_PIXEL_DENSITY;
527 flags |= SDL_WINDOW_FULLSCREEN;
532 flags |= SDL_WINDOW_BORDERLESS;
536 flags |= SDL_WINDOW_BORDERLESS;
540 flags |= SDL_WINDOW_HIDDEN;
542 auto did = WINPR_ASSERTING_INT_CAST(SDL_DisplayID,
id);
543 auto window = SdlWindow::create(did, title, flags, w, h);
547 window.setOffsetX(originX - monitor->x);
548 window.setOffsetY(originY - monitor->y);
551 _windows.insert({ window.id(), std::move(window) });
558#if defined(__EMSCRIPTEN__)
560extern "C" int freerdp_web_monitors_js(int32_t* edges,
int max);
566static std::vector<rdpMonitor> sdl_web_monitors(
const rdpMonitor& canvas)
568 constexpr int max = 16;
569 std::array<int32_t, 5 * max> edges{};
570 const auto n = freerdp_web_monitors_js(edges.data(), max);
571 if ((n < 2) || (n > max))
574 const auto at = [](int32_t edge, int32_t size)
575 {
return static_cast<INT32
>(
static_cast<int64_t
>(edge) * size / 10000); };
576 std::vector<rdpMonitor> list;
577 for (
int i = 0; i < n; i++)
579 const int32_t* e = &edges.at(5 *
static_cast<size_t>(i));
580 const auto left = at(e[0], canvas.width);
581 const auto top = at(e[1], canvas.height);
582 const auto right = at(e[2], canvas.width);
583 const auto bottom = at(e[3], canvas.height);
584 if ((right <= left) || (bottom <= top))
590 m.width = right - left;
591 m.height = bottom - top;
592 m.is_primary = (e[4] != 0);
593 m.attributes.physicalWidth =
594 static_cast<UINT32
>(
static_cast<uint64_t
>(canvas.attributes.physicalWidth) *
595 static_cast<UINT32
>(m.width) /
static_cast<UINT32
>(canvas.width));
596 m.attributes.physicalHeight =
597 static_cast<UINT32
>(
static_cast<uint64_t
>(canvas.attributes.physicalHeight) *
598 static_cast<UINT32
>(m.height) /
static_cast<UINT32
>(canvas.height));
605bool SdlContext::updateWindowList()
611 std::vector<rdpMonitor> list;
612 list.reserve(_windows.size());
613 for (
const auto& win : _windows)
614 list.push_back(win.second.monitor(_windows.size() == 1));
616#if defined(__EMSCRIPTEN__)
617 if ((list.size() == 1) && (list.at(0).width > 0) && (list.at(0).height > 0))
619 auto split = sdl_web_monitors(list.at(0));
621 list = std::move(split);
629 std::none_of(list.cbegin(), list.cend(), [](
const rdpMonitor& m) { return m.is_primary; }))
630 list.at(0).is_primary =
true;
636bool SdlContext::updateWindow(SDL_WindowID
id)
644 auto& w = _windows.at(
id);
645 auto m = w.monitor(
true);
650 m.attributes.desktopScaleFactor =
static_cast<UINT32
>(std::roundf(w.scale() * 100.0f));
655std::string SdlContext::windowTitle()
const
657 const char* prefix =
"FreeRDP:";
665 const auto addPort = (port != 3389);
667 std::stringstream ss;
668 ss << prefix <<
" " << name;
676bool SdlContext::waitForWindowsCreated()
679 std::unique_lock<CriticalSection> lock(_critical);
680 _windowsCreatedEvent.clear();
681 if (!sdl_push_user_event(SDL_EVENT_USER_CREATE_WINDOWS,
this))
685 HANDLE handles[] = { _windowsCreatedEvent.handle(), freerdp_abort_event(context()) };
687 const DWORD rc = WaitForMultipleObjects(ARRAYSIZE(handles), handles, FALSE, INFINITE);
701BOOL SdlContext::endPaint(rdpContext* context)
703 auto sdl = get_context(context);
706 auto gdi = context->gdi;
708 WINPR_ASSERT(gdi->primary);
710 HGDI_DC hdc = gdi->primary->hdc;
715 HGDI_WND hwnd = hdc->hwnd;
716 WINPR_ASSERT(hwnd->invalid || (hwnd->ninvalid == 0));
718 if (hwnd->invalid->null)
721 WINPR_ASSERT(hwnd->invalid);
722 if (gdi->suppressOutput || hwnd->invalid->null)
725 const INT32 ninvalid = hwnd->ninvalid;
726 const GDI_RGN* cinvalid = hwnd->cinvalid;
731 std::vector<SDL_Rect> rects;
732 for (INT32 x = 0; x < ninvalid; x++)
734 auto& rgn = cinvalid[x];
735 rects.push_back({ rgn.x, rgn.y, rgn.w, rgn.h });
738 sdl->push(std::move(rects));
739 return sdl_push_user_event(SDL_EVENT_USER_UPDATE);
742void SdlContext::sdl_client_cleanup(
int exit_code,
const std::string& error_msg)
744 rdpSettings* settings = context()->settings;
745 WINPR_ASSERT(settings);
747 _rdpThreadRunning =
false;
748 bool showError =
false;
750 WLog_Print(getWLog(), WLOG_INFO,
"Authentication only, exit status %s [%" PRId32
"]",
751 sdl::error::exitCodeToTag(exit_code), exit_code);
756 case sdl::error::SUCCESS:
757 case sdl::error::DISCONNECT:
758 case sdl::error::LOGOFF:
759 case sdl::error::DISCONNECT_BY_USER:
760 case sdl::error::CONNECT_CANCELLED:
765 getDialog().showError(error_msg);
772 getDialog().show(
false);
774 _exitCode = exit_code;
775 std::ignore = sdl_push_user_event(SDL_EVENT_USER_QUIT);
779int SdlContext::sdl_client_thread_connect(std::string& error_msg)
781 auto instance = context()->instance;
782 WINPR_ASSERT(instance);
784 _rdpThreadRunning =
true;
785 BOOL rc = freerdp_connect(instance);
787 rdpSettings* settings = context()->settings;
788 WINPR_ASSERT(settings);
790 int exit_code = sdl::error::SUCCESS;
793 UINT32 error = freerdp_get_last_error(context());
794 exit_code = sdl::error::errorToExitCode(error);
799 DWORD code = freerdp_get_last_error(context());
800 freerdp_abort_connect_context(context());
801 WLog_Print(getWLog(), WLOG_ERROR,
"Authentication only, %s [0x%08" PRIx32
"] %s",
802 freerdp_get_last_error_name(code), code, freerdp_get_last_error_string(code));
808 DWORD code = freerdp_error_info(instance);
809 if (exit_code == sdl::error::SUCCESS)
813 exit_code = error_info_to_error(&code, &msg, &len);
819 auto last = freerdp_get_last_error(context());
820 if (error_msg.empty())
824 winpr_asprintf(&msg, &len,
"%s [0x%08" PRIx32
"]\n%s",
825 freerdp_get_last_error_name(last), last,
826 freerdp_get_last_error_string(last));
832 if (exit_code == sdl::error::SUCCESS)
834 if (last == FREERDP_ERROR_AUTHENTICATION_FAILED)
835 exit_code = sdl::error::AUTH_FAILURE;
836 else if (code == ERRINFO_SUCCESS)
837 exit_code = sdl::error::CONN_FAILED;
840 getDialog().show(
false);
846int SdlContext::sdl_client_thread_run(std::string& error_msg)
848 auto instance = context()->instance;
849 WINPR_ASSERT(instance);
851 int exit_code = sdl::error::SUCCESS;
852 while (!freerdp_shall_disconnect_context(context()))
854 HANDLE handles[MAXIMUM_WAIT_OBJECTS] = {};
860 if (freerdp_focus_required(instance))
862 auto ctx = get_context(context());
865 auto& input = ctx->getInputChannelContext();
866 if (!input.keyboard_focus_in())
868 if (!input.keyboard_focus_in())
872 const DWORD nCount = freerdp_get_event_handles(context(), handles, ARRAYSIZE(handles));
876 WLog_Print(getWLog(), WLOG_ERROR,
"freerdp_get_event_handles failed");
880 const DWORD status = WaitForMultipleObjects(nCount, handles, FALSE, INFINITE);
882 if (status == WAIT_FAILED)
884 WLog_Print(getWLog(), WLOG_ERROR,
"WaitForMultipleObjects WAIT_FAILED");
888 if (!freerdp_check_event_handles(context()))
890 if (client_auto_reconnect(instance))
893 getDialog().show(
false);
902 if (freerdp_error_info(instance) == 0)
903 exit_code = sdl::error::errorToExitCode(freerdp_get_last_error(context()));
906 if (freerdp_get_last_error(context()) == FREERDP_ERROR_SUCCESS)
907 WLog_Print(getWLog(), WLOG_ERROR,
"WaitForMultipleObjects failed with %" PRIu32
"",
909 if (freerdp_get_last_error(context()) == FREERDP_ERROR_SUCCESS)
910 WLog_Print(getWLog(), WLOG_ERROR,
"Failed to check FreeRDP event handles");
915 if (exit_code == sdl::error::SUCCESS)
919 char* emsg =
nullptr;
921 exit_code = error_info_to_error(&code, &emsg, &elen);
927 if ((code == ERRINFO_LOGOFF_BY_USER) &&
928 (freerdp_get_disconnect_ultimatum(context()) == Disconnect_Ultimatum_user_requested))
930 const char* msg =
"Error info says user did not initiate but disconnect ultimatum says "
931 "they did; treat this as a user logoff";
933 char* emsg =
nullptr;
935 winpr_asprintf(&emsg, &elen,
"%s", msg);
941 WLog_Print(getWLog(), WLOG_INFO,
"%s", msg);
942 exit_code = sdl::error::LOGOFF;
946 if ((exit_code != sdl::error::SUCCESS) && error_msg.empty())
948 const auto last = freerdp_get_last_error(context());
951 winpr_asprintf(&msg, &len,
"%s [0x%08" PRIx32
"]\n%s", freerdp_get_last_error_name(last),
952 last, freerdp_get_last_error_string(last));
958 freerdp_disconnect(instance);
970 std::string error_msg;
971 int exit_code = sdl->sdl_client_thread_connect(error_msg);
972 if (exit_code == sdl::error::SUCCESS)
973 exit_code = sdl->sdl_client_thread_run(error_msg);
974 sdl->sdl_client_cleanup(exit_code, error_msg);
976 return static_cast<DWORD
>(exit_code);
979int SdlContext::error_info_to_error(DWORD* pcode,
char** msg,
size_t* len)
const
981 const DWORD code = freerdp_error_info(context()->instance);
982 const char* name = freerdp_get_error_info_name(code);
983 const char* str = freerdp_get_error_info_string(code);
984 const int exit_code = sdl::error::errorToExitCode(code);
986 winpr_asprintf(msg, len,
"Terminate with %s due to ERROR_INFO %s [0x%08" PRIx32
"]: %s",
987 sdl::error::errorToExitCodeTag(code), name, code, str);
988 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"%s", *msg);
994void SdlContext::applyMonitorOffset(SDL_WindowID window,
float& x,
float& y)
const
999 auto w = getWindowForId(window);
1000 x -=
static_cast<float>(w->offsetX());
1001 y -=
static_cast<float>(w->offsetY());
1004void SdlContext::updateMonitorDataFromOffsets()
1006 for (
auto& entry : _windows)
1008 const auto& monitor = _displays.at(entry.first);
1009 entry.second.setMonitor(monitor);
1013bool SdlContext::drawToWindow(
SdlWindow& window,
const std::vector<SDL_Rect>& rects)
1018 auto gdi = context()->gdi;
1021 auto size = window.rect();
1023 std::unique_lock lock(_critical);
1024 auto surface = _primary.get();
1026 if (useLocalScale())
1028 window.setOffsetX(0);
1029 window.setOffsetY(0);
1030 if (gdi->width < size.w)
1032 window.setOffsetX((size.w - gdi->width) / 2);
1034 if (gdi->height < size.h)
1036 window.setOffsetY((size.h - gdi->height) / 2);
1039 _localScale = {
static_cast<float>(size.w) /
static_cast<float>(gdi->width),
1040 static_cast<float>(size.h) /
static_cast<float>(gdi->height) };
1041 if (!window.drawScaledRects(surface, _localScale, rects))
1046 SDL_Point offset{ 0, 0 };
1048 offset = { window.offsetX(), window.offsetY() };
1049 if (!window.drawRects(surface, offset, rects))
1053 window.updateSurface((&window == overlayWindow()) ? &_overlay :
nullptr);
1060 if (_rail.enabled() || _windows.empty())
1062 return &_windows.begin()->second;
1067 return showOverlay(!_overlay.visible());
1070bool SdlContext::showOverlay(
bool on)
1072 if (!_overlay.
show(on))
1074 if (on || !isConnected())
1078 auto window = overlayWindow();
1080 window->updateSurface();
1084bool SdlContext::updateOverlay()
1086 auto window = overlayWindow();
1087 if (!window || !isConnected())
1092 if (!SDL_GetWindowSizeInPixels(window->window(), &w, &h))
1094 if (_overlay.update(w, h, window->rendererName()))
1095 window->updateSurface(&_overlay);
1099bool SdlContext::minimizeAllWindows()
1101 for (
auto& w : _windows)
1102 w.second.minimize();
1106int SdlContext::exitCode()
const
1111SDL_PixelFormat SdlContext::pixelFormat()
const
1113 return _sdlPixelFormat;
1116bool SdlContext::addDisplayWindow(SDL_DisplayID
id)
1119 SDL_WINDOW_HIGH_PIXEL_DENSITY | SDL_WINDOW_FULLSCREEN | SDL_WINDOW_BORDERLESS;
1120 auto title = sdl::utils::windowTitle(context()->settings);
1121 auto w = SdlWindow::create(
id, title, flags);
1122 _windows.emplace(w.id(), std::move(w));
1126bool SdlContext::removeDisplayWindow(SDL_DisplayID
id)
1128 for (
auto& w : _windows)
1130 if (w.second.displayIndex() ==
id)
1131 _windows.erase(w.first);
1136bool SdlContext::detectDisplays()
1139 auto display = SDL_GetDisplays(&count);
1142 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_GetDisplays failed: %s", SDL_GetError());
1145 for (
int x = 0; x < count; x++)
1147 const auto id = display[x];
1148 addOrUpdateDisplay(
id);
1153 if (_displays.empty())
1155 WLog_Print(getWLog(), WLOG_ERROR,
"none of the %d displays has a usable size", count);
1161rdpMonitor SdlContext::getDisplay(SDL_DisplayID
id)
const
1163 return _displays.at(
id);
1166std::vector<SDL_DisplayID> SdlContext::getDisplayIds()
const
1168 std::vector<SDL_DisplayID> keys;
1169 keys.reserve(_displays.size());
1170 for (
const auto& entry : _displays)
1172 keys.push_back(entry.first);
1177const SdlWindow* SdlContext::getWindowForId(SDL_WindowID
id)
const
1179 auto it = _windows.find(
id);
1180 if (it == _windows.end())
1185SdlWindow* SdlContext::getWindowForId(SDL_WindowID
id)
1187 auto it = _windows.find(
id);
1188 if (it == _windows.end())
1193bool SdlContext::allWindowsHidden()
const
1195 return std::all_of(_windows.begin(), _windows.end(),
1196 [](
const auto& entry)
1198 const auto flags = SDL_GetWindowFlags(entry.second.window());
1199 return (flags & (SDL_WINDOW_HIDDEN | SDL_WINDOW_MINIMIZED)) != 0;
1205 if (_windows.empty())
1207 return &_windows.begin()->second;
1215sdlInput& SdlContext::getInputChannelContext()
1220sdlClip& SdlContext::getClipboardChannelContext()
1225SdlRail& SdlContext::getRailChannelContext()
1235wLog* SdlContext::getWLog()
1240bool SdlContext::moveMouseTo(
const SDL_FPoint& pos)
1242 auto window = SDL_GetMouseFocus();
1246 const auto id = SDL_GetWindowID(window);
1247 const auto spos = pixelToScreen(
id, pos);
1248 SDL_WarpMouseInWindow(window, spos.x, spos.y);
1252static bool onWindowEdge(SDL_WindowID
id,
float x,
float y)
1256 auto* window = SDL_GetWindowFromID(
id);
1257 if (!window || !SDL_GetWindowSize(window, &w, &h))
1259 return (x <= 0.0f) || (y <= 0.0f) || (x >=
static_cast<float>(w - 1)) ||
1260 (y >=
static_cast<float>(h - 1));
1263bool SdlContext::handleEvent(
const SDL_MouseMotionEvent& ev)
1268 if (_rail.enabled() && (ev.state == 0) && (ev.windowID == _lastRelease.window) &&
1269 (ev.timestamp - _lastRelease.time < SDL_MS_TO_NS(2)) &&
1270 onWindowEdge(ev.windowID, ev.x, ev.y))
1273 if (_rail.enabled() && _rail.suppressServerMotion(ev.windowID))
1275 if (!(SDL_GetGlobalMouseState(
nullptr,
nullptr) & SDL_BUTTON_LMASK))
1276 _rail.completeLocalMoveIfPending();
1279 if (_rail.enabled() && _rail.translateToServer(ev.windowID, copy.motion.x, copy.motion.y))
1282 ev.windowID, { ev.x, ev.y }, { copy.motion.x, copy.motion.y }, _rail.pointerEpoch()
1284 _rail.noteServerPointer(copy.motion.x, copy.motion.y);
1285 return SdlTouch::handleEvent(
this, copy.motion);
1288 if (!getWindowForId(ev.windowID))
1290 if (!eventToPixelCoordinates(ev.windowID, copy))
1292 removeLocalScaling(copy.motion.x, copy.motion.y);
1293 removeLocalScaling(copy.motion.xrel, copy.motion.yrel);
1294 applyMonitorOffset(copy.motion.windowID, copy.motion.x, copy.motion.y);
1296 return SdlTouch::handleEvent(
this, copy.motion);
1299bool SdlContext::handleEvent(
const SDL_MouseWheelEvent& ev)
1303 if (_rail.enabled() &&
1304 _rail.translateToServer(ev.windowID, copy.wheel.mouse_x, copy.wheel.mouse_y))
1305 return SdlTouch::handleEvent(
this, copy.wheel);
1307 if (!getWindowForId(ev.windowID))
1309 if (!eventToPixelCoordinates(ev.windowID, copy))
1311 removeLocalScaling(copy.wheel.mouse_x, copy.wheel.mouse_y);
1312 return SdlTouch::handleEvent(
this, copy.wheel);
1315bool SdlContext::handleEvent(
const SDL_WindowEvent& ev)
1317 if (!getDisplayChannelContext().handleEvent(ev))
1320 auto window = getWindowForId(ev.windowID);
1324 if (_rail.enabled() && _rail.ownsWindow(ev.windowID))
1328 case SDL_EVENT_WINDOW_MOUSE_ENTER:
1330 if (!(SDL_GetGlobalMouseState(
nullptr,
nullptr) & SDL_BUTTON_LMASK))
1331 _rail.completeLocalMoveIfPending();
1332 _rail.completeWaylandResize();
1334 return restoreCursor();
1335 case SDL_EVENT_WINDOW_MOUSE_LEAVE:
1337 _rail.noteResizeGrab(ev.windowID);
1339 case SDL_EVENT_WINDOW_EXPOSED:
1342 if (!_rail.dragActive(ev.windowID))
1343 _rail.invalidateWindow(ev.windowID);
1345 case SDL_EVENT_WINDOW_MAXIMIZED:
1347 _rail.completeLocalMoveIfPending();
1348 _rail.handleMaximized(ev.windowID);
1350 case SDL_EVENT_WINDOW_MINIMIZED:
1351 _rail.handleMinimized(ev.windowID);
1353 case SDL_EVENT_WINDOW_RESTORED:
1354 _rail.handleRestored(ev.windowID);
1356 case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
1358 _rail.handleClose(ev.windowID);
1360 case SDL_EVENT_WINDOW_FOCUS_GAINED:
1361 _rail.handleFocus(ev.windowID,
true);
1363 case SDL_EVENT_WINDOW_FOCUS_LOST:
1364 _rail.handleFocus(ev.windowID,
false);
1366 case SDL_EVENT_WINDOW_DISPLAY_CHANGED:
1367 _rail.handleDisplayChanged(ev.windowID,
static_cast<SDL_DisplayID
>(ev.data1));
1369 case SDL_EVENT_WINDOW_MOVED:
1370 _rail.notePopupMoved(ev.windowID);
1371 if (!_rail.dragActive(ev.windowID))
1372 _rail.syncGeometry(ev.windowID);
1374 case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
1377 _rail.noteDragResize(ev.windowID, ev.data1, ev.data2);
1378 _rail.syncGeometry(ev.windowID);
1379 _rail.noteResizeGrab(ev.windowID);
1380 std::ignore = drawToWindows({});
1390 const auto& r = window->rect();
1391 const auto& b = window->bounds();
1392 const auto& scale = window->scale();
1393 const auto& orientation = window->orientation();
1394 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
1395 "%s: [%u] %dx%d-%dx%d {%dx%d-%dx%d}{scale=%f,orientation=%s}",
1396 sdl::utils::toString(ev.type).c_str(), ev.windowID, r.x, r.y, r.w, r.h, b.x,
1397 b.y, b.w, b.h,
static_cast<double>(scale),
1398 sdl::utils::toString(orientation).c_str());
1403 case SDL_EVENT_WINDOW_MOUSE_ENTER:
1404 return restoreCursor();
1405 case SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED:
1406 if (!resizeToScale(window))
1411 if (!window->fill())
1413 if (!drawToWindow(*window))
1415 if (!restoreCursor())
1419 case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
1420 if (!resizeToScale(window))
1422 if (!window->fill())
1424 if (!drawToWindow(*window))
1426 if (!restoreCursor())
1430 case SDL_EVENT_WINDOW_MOVED:
1432 auto r = window->rect();
1433 auto id = window->id();
1434 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"%u: %dx%d-%dx%d",
id, r.x, r.y, r.w, r.h);
1437 case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
1439 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
"Window closed, terminating RDP session...");
1440 std::ignore = abortConnect();
1449bool SdlContext::handleEvent(
const SDL_DisplayEvent& ev)
1451 if (!getDisplayChannelContext().handleEvent(ev))
1453#if SDL_VERSION_ATLEAST(3, 3, 2)
1454 if (ev.type == SDL_EVENT_DISPLAY_USABLE_BOUNDS_CHANGED)
1455 _rail.noteUsableBoundsChanged(ev.displayID);
1460 case SDL_EVENT_DISPLAY_REMOVED:
1465 if (!SDL_GetDisplayBounds(ev.displayID, &r))
1467 const auto name = SDL_GetDisplayName(ev.displayID);
1470 const auto orientation = SDL_GetCurrentDisplayOrientation(ev.displayID);
1471 const auto scale = SDL_GetDisplayContentScale(ev.displayID);
1472 const auto mode = SDL_GetCurrentDisplayMode(ev.displayID);
1476 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION,
1477 "%s: [%u, %s] %dx%d-%dx%d {orientation=%s, scale=%f}%s",
1478 sdl::utils::toString(ev.type).c_str(), ev.displayID, name, r.x, r.y, r.w,
1479 r.h, sdl::utils::toString(orientation).c_str(),
static_cast<double>(scale),
1480 sdl::utils::toString(mode).c_str());
1487bool SdlContext::handleEvent(
const SDL_MouseButtonEvent& ev)
1489 SDL_Event copy = {};
1491 if (_rail.enabled())
1494 const bool suppress = _rail.dragActive(ev.windowID);
1495 if (ev.type == SDL_EVENT_MOUSE_BUTTON_UP)
1496 _rail.completeLocalMoveIfPending();
1499 if (ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN)
1500 _rail.completeWaylandResize(
true);
1502 if (ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN)
1503 _rail.ensureActive(ev.windowID);
1506 if (ev.type == SDL_EVENT_MOUSE_BUTTON_UP)
1508 _lastRelease = { ev.windowID, ev.timestamp };
1510 if (_rail.translateToServer(ev.windowID, copy.button.x, copy.button.y))
1513 if ((ev.windowID == _lastMotion.window) &&
1514 (_lastMotion.epoch == _rail.pointerEpoch()) &&
1515 (fabsf(ev.x - _lastMotion.local.x) < FLT_EPSILON) &&
1516 (fabsf(ev.y - _lastMotion.local.y) < FLT_EPSILON))
1518 copy.button.x = _lastMotion.server.x;
1519 copy.button.y = _lastMotion.server.y;
1523 if ((ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN) && (ev.button == SDL_BUTTON_LEFT))
1524 _rail.noteLeftPress(copy.button.x, copy.button.y);
1525 return SdlTouch::handleEvent(
this, copy.button);
1529 if (!getWindowForId(ev.windowID))
1531 if (!eventToPixelCoordinates(ev.windowID, copy))
1533 removeLocalScaling(copy.button.x, copy.button.y);
1534 applyMonitorOffset(copy.button.windowID, copy.button.x, copy.button.y);
1535 return SdlTouch::handleEvent(
this, copy.button);
1538bool SdlContext::handleEvent(
const SDL_TouchFingerEvent& ev)
1540 if (!getWindowForId(ev.windowID))
1544 if (!eventToPixelCoordinates(ev.windowID, copy))
1546 removeLocalScaling(copy.tfinger.dx, copy.tfinger.dy);
1547 removeLocalScaling(copy.tfinger.x, copy.tfinger.y);
1548 applyMonitorOffset(copy.tfinger.windowID, copy.tfinger.x, copy.tfinger.y);
1549 return SdlTouch::handleEvent(
this, copy.tfinger);
1552void SdlContext::addOrUpdateDisplay(SDL_DisplayID
id)
1554 auto monitor = SdlWindow::query(
id,
false);
1555 if ((monitor.width <= 0) || (monitor.height <= 0))
1557 WLog_Print(getWLog(), WLOG_WARN,
"display %" PRIu32
" has no usable size, skipped",
id);
1560 _displays.emplace(
id, monitor);
1565 _displayBounds.clear();
1566 for (
const auto& entry : _displays)
1569 std::ignore = SDL_GetDisplayBounds(entry.first, &bounds);
1570 _displayBounds.emplace(entry.first, bounds);
1572 _primaryDisplay = SDL_GetPrimaryDisplay();
1573 updateDisplayOffsets();
1574 updateMonitorDataFromOffsets();
1577void SdlContext::updateDisplayOffsets()
1582 for (
const auto& entry : _displays)
1585 const auto found = _displayBounds.find(entry.first);
1586 if (found != _displayBounds.end())
1587 bounds = found->second;
1590 pixel.w = entry.second.width;
1591 pixel.h = entry.second.height;
1592 _offsets.emplace(entry.first, std::pair{ bounds, pixel });
1595 if (_offsets.empty())
1597 sdl_display_offsets::update(_offsets, _primaryDisplay, _monitorIds);
1598 for (
auto& entry : _displays)
1600 const auto& pixel = _offsets.at(entry.first).second;
1601 entry.second.x = pixel.x;
1602 entry.second.y = pixel.y;
1606void SdlContext::deleteDisplay(SDL_DisplayID
id)
1608 _displays.erase(
id);
1611bool SdlContext::eventToPixelCoordinates(SDL_WindowID
id, SDL_Event& ev)
1613 auto w = getWindowForId(
id);
1618 auto renderer = w->renderer();
1621 return SDL_ConvertEventToRenderCoordinates(renderer, &ev);
1624SDL_FPoint SdlContext::applyLocalScaling(
const SDL_FPoint& val)
const
1626 if (!useLocalScale())
1630 rval.x *= _localScale.x;
1631 rval.y *= _localScale.y;
1635void SdlContext::removeLocalScaling(
float& x,
float& y)
const
1637 if (!useLocalScale())
1643SDL_FPoint SdlContext::screenToPixel(SDL_WindowID
id,
const SDL_FPoint& pos)
1645 auto w = getWindowForId(
id);
1649 if (_rail.enabled() && _rail.ownsWindow(
id))
1655 auto renderer = w->renderer();
1660 if (!SDL_RenderCoordinatesFromWindow(renderer, pos.x, pos.y, &rpos.x, &rpos.y))
1662 removeLocalScaling(rpos.x, rpos.y);
1666SDL_FPoint SdlContext::pixelToScreen(SDL_WindowID
id,
const SDL_FPoint& pos)
1668 auto w = getWindowForId(
id);
1671 if (_rail.enabled() && _rail.ownsWindow(
id))
1677 auto renderer = w->renderer();
1682 if (!SDL_RenderCoordinatesToWindow(renderer, pos.x, pos.y, &rpos.x, &rpos.y))
1684 return applyLocalScaling(rpos);
1687SDL_FRect SdlContext::pixelToScreen(SDL_WindowID
id,
const SDL_FRect& pos,
bool round)
1689 const auto fpos = pixelToScreen(
id, SDL_FPoint{ pos.x, pos.y });
1690 const auto size = pixelToScreen(
id, SDL_FPoint{ pos.w, pos.h });
1691 SDL_FRect r{ fpos.x, fpos.y, size.x, size.y };
1694 r.w = std::ceil(r.w);
1695 r.h = std::ceil(r.h);
1696 r.x = std::floor(r.x);
1697 r.y = std::floor(r.y);
1702bool SdlContext::handleEvent(
const SDL_Event& ev)
1704 if ((ev.type >= SDL_EVENT_DISPLAY_FIRST) && (ev.type <= SDL_EVENT_DISPLAY_LAST))
1706 const auto& dev = ev.display;
1707 return handleEvent(dev);
1709 if ((ev.type >= SDL_EVENT_WINDOW_FIRST) && (ev.type <= SDL_EVENT_WINDOW_LAST))
1711 const auto& wev = ev.window;
1712 return handleEvent(wev);
1716 case SDL_EVENT_RENDER_TARGETS_RESET:
1717 case SDL_EVENT_RENDER_DEVICE_RESET:
1718 case SDL_EVENT_WILL_ENTER_FOREGROUND:
1729 case SDL_EVENT_FINGER_DOWN:
1730 case SDL_EVENT_FINGER_UP:
1731 case SDL_EVENT_FINGER_MOTION:
1733 const auto& cev = ev.tfinger;
1734 return handleEvent(cev);
1736 case SDL_EVENT_MOUSE_MOTION:
1739 const auto& cev = ev.motion;
1740 return handleEvent(cev);
1742 case SDL_EVENT_MOUSE_BUTTON_DOWN:
1743 case SDL_EVENT_MOUSE_BUTTON_UP:
1745 const auto& cev = ev.button;
1746 return handleEvent(cev);
1748 case SDL_EVENT_MOUSE_WHEEL:
1750 const auto& cev = ev.wheel;
1751 return handleEvent(cev);
1753 case SDL_EVENT_CLIPBOARD_UPDATE:
1755 const auto& cev = ev.clipboard;
1756 return getClipboardChannelContext().handleEvent(cev);
1758 case SDL_EVENT_KEY_DOWN:
1759 case SDL_EVENT_KEY_UP:
1761 const auto& cev = ev.key;
1762 return getInputChannelContext().handleEvent(cev);
1771 return _args.data();
1774size_t SdlContext::argsCount()
const
1776 if (_args.size() <= 1)
1778 return _args.size() - 1;
1783 auto sdl =
static_cast<SdlContext*
>(custom);
1789 if (strcmp(arg->Name, sdl_allow_screensaver) == 0)
1791 sdl->_allowScreenSaver = (arg->Value !=
nullptr);
1792 if (arg->Value !=
nullptr)
1794 if (!SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER,
"1"))
1796 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
1797 "SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER) failed with %s",
1803 else if (strcmp(arg->Name, sdl_connection_dialog) == 0)
1804 sdl->_connectionDialog = (arg->Value !=
nullptr);
1805 else if (strcmp(arg->Name, sdl_info) == 0)
1807 if (!sdl->_overlay.
show(arg->Value !=
nullptr))
1819std::vector<rdpPointer*>& SdlContext::pointers()
1821 return _valid_pointers;
1824bool SdlContext::contains(
const rdpPointer* ptr)
const
1826 for (
const auto& cur : _valid_pointers)
1834bool SdlContext::credentialsRead()
const
1836 return _credentialsRead;
1839void SdlContext::setCredentialsRead()
1841 _credentialsRead =
true;
1846 return horizontal ? _wheelX : _wheelY;
1849bool SdlContext::resizeToScale(
SdlWindow* window)
1853 if (!useLocalScale())
1857 return window->resizeToScale();
1860bool SdlContext::useLocalScale()
const
1865 const auto dynResize =
1869 return !dynResize && !fs && !multimon;
1872bool SdlContext::drawToWindows(
const std::vector<SDL_Rect>& rects)
1875 if (_rail.enabled())
1877 for (
auto& window : _windows)
1879 if ((SDL_GetWindowFlags(window.second.window()) & SDL_WINDOW_HIDDEN) == 0)
1880 SDL_HideWindow(window.second.window());
1883 std::unique_lock lock(_critical);
1884 _rail.paint(_primary.get(), pixelFormat(), rects);
1891 !_rail.desktopMayShow())
1893 bool firstShow =
false;
1894 for (
auto& window : _windows)
1896 if (SDL_GetWindowFlags(window.second.window()) & SDL_WINDOW_HIDDEN)
1898 SDL_ShowWindow(window.second.window());
1899 SDL_RaiseWindow(window.second.window());
1904 if (rects.empty() && !firstShow)
1907 std::vector<SDL_Rect> drawRects = rects;
1909 std::unique_lock lock(_critical);
1910 if ((drawRects.empty() || firstShow) && _primary)
1911 drawRects = { { 0, 0, _primary->w, _primary->h } };
1914 for (
auto& window : _windows)
1916 if (!drawToWindow(window.second, drawRects))
1923BOOL SdlContext::desktopResize(rdpContext* context)
1925 rdpGdi* gdi =
nullptr;
1926 rdpSettings* settings =
nullptr;
1927 auto sdl = get_context(context);
1930 WINPR_ASSERT(context);
1932 settings = context->settings;
1933 WINPR_ASSERT(settings);
1935 std::unique_lock lock(sdl->_critical);
1940 return sdl->createPrimary();
1944BOOL SdlContext::playSound(rdpContext* context,
const PLAY_SOUND_UPDATE* play_sound)
1947 WINPR_UNUSED(context);
1948 WINPR_UNUSED(play_sound);
1954BOOL SdlContext::beginPaint(rdpContext* context)
1956 auto gdi = context->gdi;
1958 WINPR_ASSERT(gdi->primary);
1960 HGDI_DC hdc = gdi->primary->hdc;
1965 HGDI_WND hwnd = hdc->hwnd;
1966 WINPR_ASSERT(hwnd->invalid);
1967 hwnd->invalid->null = TRUE;
1973bool SdlContext::redraw(
bool suppress)
const
1982 auto gdi = context()->gdi;
1984 return gdi_send_suppress_output(gdi, suppress);
1987void SdlContext::setConnected(
bool val)
1992bool SdlContext::isConnected()
const
1999bool SdlContext::abortConnect()
const
2001 freerdp_set_last_error(context(), FREERDP_ERROR_CONNECT_CANCELLED);
2002 return freerdp_abort_connect_context(context());
2005rdpContext* SdlContext::context()
const
2007 WINPR_ASSERT(_context);
2011rdpClientContext* SdlContext::common()
const
2013 return reinterpret_cast<rdpClientContext*
>(context());
2016bool SdlContext::setCursor(CursorType type)
2019 return restoreCursor();
2022bool SdlContext::setCursor(
const rdpPointer* cursor)
2024 std::unique_lock lock(_critical);
2025 if (!contains(cursor))
2028 _cursor = { sdl_Pointer_Copy(cursor), sdl_PointerFreeCopyAll };
2029 return setCursor(CURSOR_IMAGE);
2032rdpPointer* SdlContext::cursor()
const
2034 return _cursor.get();
2037bool SdlContext::restoreCursor()
2039 WLog_Print(getWLog(), WLOG_TRACE,
"restore cursor: %d", _cursorType);
2040 switch (_cursorType)
2043 if (!SDL_HideCursor())
2045 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_HideCursor failed");
2049 setHasCursor(
false);
2052 case CURSOR_DEFAULT:
2054 auto def = SDL_GetDefaultCursor();
2055 if (!SDL_SetCursor(def))
2057 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_SetCursor(default=%p) failed",
2058 static_cast<void*
>(def));
2061 if (!SDL_ShowCursor())
2063 WLog_Print(getWLog(), WLOG_ERROR,
"SDL_ShowCursor failed");
2071 return sdl_Pointer_Set_Process(
this);
2073 WLog_Print(getWLog(), WLOG_ERROR,
"Unknown cursorType %s",
2074 sdl::utils::toString(_cursorType).c_str());
2079void SdlContext::setMonitorIds(
const std::vector<SDL_DisplayID>& ids)
2081 _monitorIds.clear();
2084 _monitorIds.push_back(
id);
2089 updateDisplayOffsets();
2092const std::vector<SDL_DisplayID>& SdlContext::monitorIds()
const
2097int64_t SdlContext::monitorId(uint32_t index)
const
2099 if (index >= _monitorIds.size())
2103 return _monitorIds.at(index);
2106void SdlContext::push(std::vector<SDL_Rect>&& rects)
2108 std::unique_lock lock(_queue_mux);
2109 _queue.emplace(std::move(rects));
2112std::vector<SDL_Rect> SdlContext::pop()
2114 std::unique_lock lock(_queue_mux);
2119 auto val = std::move(_queue.front());
2124bool SdlContext::setFullscreen(
bool enter,
bool forceOriginalDisplay)
2126 for (
const auto& window : _windows)
2128 if (!sdl_push_user_event(SDL_EVENT_USER_WINDOW_FULLSCREEN, &window.second, enter,
2129 forceOriginalDisplay))
2132 _fullscreen = enter;
2136bool SdlContext::setMinimized()
2138 return sdl_push_user_event(SDL_EVENT_USER_WINDOW_MINIMIZE);
2141bool SdlContext::grabMouse()
const
2146bool SdlContext::toggleGrabMouse()
2148 return setGrabMouse(!grabMouse());
2151bool SdlContext::setGrabMouse(
bool enter)
2157bool SdlContext::grabKeyboard()
const
2159 return _grabKeyboard;
2162bool SdlContext::toggleGrabKeyboard()
2164 return setGrabKeyboard(!grabKeyboard());
2167bool SdlContext::setGrabKeyboard(
bool enter)
2169 _grabKeyboard = enter;
2173bool SdlContext::setResizeable(
bool enable)
2175 const auto settings = context()->settings;
2178 bool use = (dyn && enable) || smart;
2180 for (
const auto& window : _windows)
2182 if (!sdl_push_user_event(SDL_EVENT_USER_WINDOW_RESIZEABLE, &window.second, use))
2190bool SdlContext::resizeable()
const
2195bool SdlContext::toggleResizeable()
2197 return setResizeable(!resizeable());
2200bool SdlContext::fullscreen()
const
2205bool SdlContext::toggleFullscreen()
2207 return setFullscreen(!fullscreen());
2214 const bool scale = fabsf(a.scale - b.scale) <= FLT_EPSILON;
2215 return (a.hwnd == b.hwnd) && (a.remoteWidth == b.remoteWidth) &&
2216 (a.remoteHeight == b.remoteHeight) && (a.viewWidth == b.viewWidth) &&
2217 (a.viewHeight == b.viewHeight) && (a.scrollX == b.scrollX) && (a.scrollY == b.scrollY) &&
2222static HWND native_window(SDL_Window* window)
2226 auto props = SDL_GetWindowProperties(window);
2228 return static_cast<HWND
>(
2229 SDL_GetPointerProperty(props, SDL_PROP_WINDOW_WIN32_HWND_POINTER,
nullptr));
2231 return reinterpret_cast<HWND
>(
2232 static_cast<uintptr_t
>(SDL_GetNumberProperty(props, SDL_PROP_WINDOW_X11_WINDOW_NUMBER, 0)));
2239 auto window = getFirstWindow();
2240 if (window && window->window())
2242 auto settings = _context->settings;
2243 info.hwnd = native_window(window->window());
2250 if (SDL_GetWindowSizeInPixels(window->window(), &w, &h))
2253 info.viewHeight = h;
2256 const float density = SDL_GetWindowPixelDensity(window->window());
2257 const auto p0 = pixelToScreen(window->id(), SDL_FPoint{ 0, 0 });
2258 const auto p1 = pixelToScreen(window->id(), SDL_FPoint{ 1000, 1000 });
2259 const float scale = (p1.x - p0.x) * density / 1000.0f;
2260 info.scale = (scale > 0.0f) ? scale : 1.0f;
2264 std::scoped_lock lock(_windowInfoLock);
2265 if (window_info_equal(info, _desktopWindowInfo))
2267 _desktopWindowInfo = info;
2269 if (!_rail.enabled())
2270 freerdp_client_window_info_service_changed(_context->windowInfoService, 0);
2277 std::scoped_lock lock(_windowInfoLock);
2278 first = _railWindowInfoPending.empty();
2279 _railWindowInfoPending.insert(remoteId);
2282 std::ignore = sdl_push_user_event(SDL_EVENT_USER_WINDOW_INFO);
2287 std::set<uint64_t> pending;
2289 std::scoped_lock lock(_windowInfoLock);
2290 pending.swap(_railWindowInfoPending);
2293 for (
const auto id : pending)
2296 SDL_Window* window =
nullptr;
2298 if (_rail.windowGeometry(
id, window, info.viewWidth, info.viewHeight))
2300 info.hwnd = native_window(window);
2301 info.remoteWidth = info.viewWidth;
2302 info.remoteHeight = info.viewHeight;
2305 std::scoped_lock lock(_windowInfoLock);
2306 if (info.viewWidth > 0)
2307 _railWindowInfo[id] = info;
2309 _railWindowInfo.erase(
id);
2311 if (info.viewWidth > 0)
2312 freerdp_client_window_info_service_changed(_context->windowInfoService,
id);
2316HRESULT SdlContext::windowInfoGet(
void* custom, UINT64 remoteHwnd,
WTS_WINDOW_INFO* info)
2322 std::scoped_lock lock(
sdl->_windowInfoLock);
2323 if (!
sdl->_rail.enabled())
2326 if (!
sdl->_desktopWindowInfo.hwnd && (
sdl->_desktopWindowInfo.viewWidth == 0))
2327 return E_UNEXPECTED;
2328 *info =
sdl->_desktopWindowInfo;
2331 auto it = sdl->_railWindowInfo.find(remoteHwnd);
2332 if (it == sdl->_railWindowInfo.end())
2333 return E_INVALIDARG;
2338UINT32 SdlContext::windowInfoSessionType(
void* custom)
2340 auto sdl =
static_cast<SdlContext*
>(custom);
2342 return sdl->_rail.enabled() ? WTS_RDP_SESSION_TYPE_REMOTEAPP : WTS_RDP_SESSION_TYPE_DESKTOP;
2350 std::scoped_lock lock(_rendererLock);
2351 const auto id = _nextRenderer++;
2352 auto& r = _renderers[id];
2353 r.mappingId = mappingId;
2354 r.callback = callback;
2360bool SdlContext::rendererFrame(Uint64
id,
const BYTE* data, UINT32 width, UINT32 height,
2367 std::scoped_lock lock(_rendererLock);
2368 auto it = _renderers.find(
id);
2369 if (it == _renderers.end())
2371 auto& r = it->second;
2373 const size_t row =
static_cast<size_t>(width) * 4;
2374 r.pixels.resize(row * height);
2375 for (UINT32 y = 0; y < height; y++)
2377 const auto offset = row * y;
2378 const auto end = offset + row;
2379 const auto dataoffset = 1ull * y *
static_cast<size_t>(stride);
2383 auto& ptr = r.pixels.at(offset);
2384 std::ignore = r.pixels.at(end);
2385 memcpy(&ptr, &data[dataoffset], row);
2387 catch (std::out_of_range& ex)
2389 SDL_Log(
"failed to render: %s", ex.what());
2393 r.pitch =
static_cast<int>(row);
2394 r.width =
static_cast<int>(width);
2395 r.height =
static_cast<int>(height);
2402void SdlContext::rendererRemove(Uint64
id)
2404 IWTSBitmapRendererCallback* callback =
nullptr;
2406 std::scoped_lock lock(_rendererLock);
2407 auto it = _renderers.find(
id);
2408 if (it == _renderers.end())
2410 callback = it->second.callback;
2411 _renderers.erase(it);
2414 callback->Release();
2418bool SdlContext::hasRenderers()
2420 std::scoped_lock lock(_rendererLock);
2421 return !_renderers.empty();
2424void SdlContext::renderersChanged()
2427 if (!_renderersPending.exchange(
true))
2428 std::ignore = sdl_push_user_event(SDL_EVENT_USER_RENDERER);
2433 _renderersPending =
false;
2438 std::vector<std::pair<IWTSBitmapRendererCallback*, WTS_RECT>> targets;
2440 std::scoped_lock lock(_rendererLock);
2445 bool visible =
false;
2447 std::vector<SDL_Rect> region;
2449 std::map<Uint64, Placement> placements;
2450 rdpGdi* gdi = _context->gdi;
2451 GeometryClientContext* geometry = gdi ? gdi->geometry :
nullptr;
2452 if (geometry && geometry->geometries)
2454 HashTable_Lock(geometry->geometries);
2455 for (
auto& kv : _renderers)
2457 auto g =
static_cast<const MAPPED_GEOMETRY*
>(
2458 HashTable_GetItemValue(geometry->geometries, &kv.second.mappingId));
2462 p.rect = {
static_cast<int>(g->topLevelLeft + g->left),
2463 static_cast<int>(g->topLevelTop + g->top),
2464 static_cast<int>(std::max<INT64>(0, g->right - g->left)),
2465 static_cast<int>(std::max<INT64>(0, g->bottom - g->top)) };
2466 p.visible = (p.rect.w > 0) && (p.rect.h > 0);
2469 for (UINT32 i = 0; g->geometry.rects && (i < g->geometry.nRectCount); i++)
2471 const RDP_RECT& r = g->geometry.rects[i];
2472 const int left = std::max(0,
static_cast<int>(r.x));
2473 const int top = std::max(0,
static_cast<int>(r.y));
2474 const int right = std::min(p.rect.w, r.x + r.width);
2475 const int bottom = std::min(p.rect.h, r.y + r.height);
2476 if ((right <= left) || (bottom <= top))
2478 area +=
static_cast<INT64
>(right - left) * (bottom - top);
2480 { p.rect.x + left, p.rect.y + top, right - left, bottom - top });
2482 if (area >=
static_cast<INT64
>(p.rect.w) * p.rect.h)
2484 placements[kv.first] = std::move(p);
2486 HashTable_Unlock(geometry->geometries);
2489 for (
auto& kv : _renderers)
2491 auto& r = kv.second;
2492 const auto& p = placements[kv.first];
2493 if (p.visible && r.callback && !SDL_RectsEqual(&p.rect, &r.target))
2496 r.callback->AddRef();
2497 targets.emplace_back(r.callback,
WTS_RECT{ p.rect.x, p.rect.y, p.rect.x + p.rect.w,
2498 p.rect.y + p.rect.h });
2502 for (
auto& w : _windows)
2504 auto& window = w.second;
2505 window.pruneVideoOverlays([
this](Uint64
id) {
return _renderers.count(
id) != 0; });
2506 for (
auto& kv : _renderers)
2508 auto& r = kv.second;
2509 const auto& p = placements[kv.first];
2511 SDL_Point offset{ 0, 0 };
2512 if (!useLocalScale() &&
2514 offset = { window.offsetX(), window.offsetY() };
2515 auto toWindow = [&](
const SDL_Rect& rc)
2517 if (useLocalScale())
2518 return SDL_FRect{
static_cast<float>(rc.x) * _localScale.x,
2519 static_cast<float>(rc.y) * _localScale.y,
2520 static_cast<float>(rc.w) * _localScale.x,
2521 static_cast<float>(rc.h) * _localScale.y };
2522 return SDL_FRect{
static_cast<float>(rc.x + offset.x),
2523 static_cast<float>(rc.y + offset.y),
static_cast<float>(rc.w),
2524 static_cast<float>(rc.h) };
2526 const SDL_FRect dst = toWindow(p.rect);
2527 std::vector<SDL_FRect> clip;
2528 clip.reserve(p.region.size());
2529 for (
const auto& rc : p.region)
2530 clip.push_back(toWindow(rc));
2531 const bool visible = p.visible && !r.pixels.empty();
2532 if (!window.setVideoOverlay(kv.first, r.dirty ? r.pixels.data() :
nullptr, r.pitch,
2533 r.width, r.height, dst, clip, visible))
2536 window.updateSurface();
2538 for (
auto& kv : _renderers)
2539 kv.second.dirty =
false;
2542 for (
auto& t : targets)
2544 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