FreeRDP
Loading...
Searching...
No Matches
sdl_context.cpp
1
19
20#include <algorithm>
21#include <array>
22#include <cmath>
23#include <cfloat>
24
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"
33
34#include <sdl_common_utils.hpp>
35#include <scoped_guard.hpp>
36
37#include "dialogs/sdl_dialogs.hpp"
38#include "sdl_render_service.hpp"
39
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>
44
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";
48
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)
53{
54 WINPR_ASSERT(context);
55 setMetadata();
56
57 auto instance = _context->instance;
58 WINPR_ASSERT(instance);
59
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;
72
73 /* TODO: Client display set up */
74
75 _args.push_back({ sdl_allow_screensaver, COMMAND_LINE_VALUE_BOOL, nullptr, BoolValueFalse,
76 nullptr, -1, nullptr,
77 "Allow local screensaver to activate (default: on for RemoteApp)" });
78 /* BoolValueTrue does not compile in C++, any non null default means on */
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,
82 nullptr,
83 "the stats and info overlay from the start (its hotkey SDL_Info, default "
84 "<modifier>+I, shows and hides it)" });
85
86 /* Push a null element used as abort when iterating the array */
87 _args.push_back({ nullptr, 0, nullptr, nullptr, nullptr, -1, nullptr, nullptr });
88
89 const WINDOW_INFO_SOURCE source = { this, windowInfoGet, windowInfoSessionType };
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");
96}
97
98SdlContext::~SdlContext()
99{
100 /* the channels, freed after us, may still hold the services */
101 if (_context->windowInfoService)
102 {
103 freerdp_client_window_info_service_detach(_context->windowInfoService);
104 _context->windowInfoService->Release();
105 _context->windowInfoService = nullptr;
106 }
107 if (_context->bitmapRenderService)
108 {
109 sdl_render_service_detach(_context->bitmapRenderService);
110 _context->bitmapRenderService->Release();
111 _context->bitmapRenderService = nullptr;
112 }
113 /* renderers the channels didn't remove */
114 std::scoped_lock lock(_rendererLock);
115 for (auto& kv : _renderers)
116 {
117 if (kv.second.callback)
118 kv.second.callback->Release();
119 }
120 _renderers.clear();
121}
122
123std::optional<bool> SdlContext::allowScreenSaver() const
124{
125 return _allowScreenSaver;
126}
127
128void SdlContext::setHasCursor(bool val)
129{
130 this->_cursor_visible = val;
131}
132
133bool SdlContext::hasCursor() const
134{
135 return _cursor_visible;
136}
137
138void SdlContext::setMetadata()
139{
140 auto wmclass = freerdp_settings_get_string(_context->settings, FreeRDP_WmClass);
141 if (!wmclass || (strlen(wmclass) == 0))
142 wmclass = SDL_CLIENT_UUID;
143
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);
151}
152
153int SdlContext::start()
154{
155 _thread = std::thread(rdpThreadRun, this);
156 return 0;
157}
158
159int SdlContext::join()
160{
161 /* We do not want to use freerdp_abort_connect_context here.
162 * It would change the exit code and we do not want that. */
163 HANDLE event = freerdp_abort_event(context());
164 if (!SetEvent(event))
165 return -1;
166
167 _thread.join();
168 return 0;
169}
170
171void SdlContext::cleanup()
172{
173 std::unique_lock lock(_critical);
174 _windows.clear();
175 _dialog.destroy();
176 _primary.reset();
177}
178
179bool SdlContext::shallAbort(bool ignoreDialogs)
180{
181 std::unique_lock lock(_critical);
182 if (freerdp_shall_disconnect_context(context()))
183 {
184 if (ignoreDialogs)
185 return true;
186 if (_rdpThreadRunning)
187 return false;
188 return !getDialog().isRunning();
189 }
190 return false;
191}
192
193/* Called before a connection is established.
194 * Set all configuration options to support and load channels here. */
195BOOL SdlContext::preConnect(freerdp* instance)
196{
197 WINPR_ASSERT(instance);
198 WINPR_ASSERT(instance->context);
199
200 auto sdl = get_context(instance->context);
201
202 auto settings = instance->context->settings;
203 WINPR_ASSERT(settings);
204
205 if (!freerdp_settings_set_bool(settings, FreeRDP_CertificateCallbackPreferPEM, TRUE))
206 return FALSE;
207
208 /* Optional OS identifier sent to server */
209 if (!freerdp_settings_set_uint32(settings, FreeRDP_OsMajorType, OSMAJORTYPE_UNIX))
210 return FALSE;
211 if (!freerdp_settings_set_uint32(settings, FreeRDP_OsMinorType, OSMINORTYPE_NATIVE_SDL))
212 return FALSE;
213 /* OrderSupport is initialized at this point.
214 * Only override it if you plan to implement custom order
215 * callbacks or deactivate certain features. */
216 /* Register the channel listeners.
217 * They are required to set up / tear down channels if they are loaded. */
218 if (PubSub_SubscribeChannelConnected(instance->context->pubSub,
219 sdl_OnChannelConnectedEventHandler) < 0)
220 return FALSE;
221 if (PubSub_SubscribeChannelDisconnected(instance->context->pubSub,
222 sdl_OnChannelDisconnectedEventHandler) < 0)
223 return FALSE;
224 if (PubSub_SubscribeUserNotification(instance->context->pubSub,
225 sdl_OnUserNotificationEventHandler) < 0)
226 return FALSE;
227
228 if (!freerdp_settings_get_bool(settings, FreeRDP_AuthenticationOnly))
229 {
230 UINT32 maxWidth = 0;
231 UINT32 maxHeight = 0;
232
233 if (!sdl_detect_monitors(sdl, &maxWidth, &maxHeight))
234 return FALSE;
235
236 /* The server takes the scale of a single monitor from the core data only, so put the
237 * display scale there too. Otherwise the session starts at 100% and is redone once the
238 * display channel sends the layout. */
239 const auto overrides = freerdp_settings_get_uint64(settings, FreeRDP_MonitorOverrideFlags);
240 if (((overrides & FREERDP_MONITOR_OVERRIDE_DESKTOP_SCALE) == 0) &&
241 !freerdp_settings_get_bool(settings, FreeRDP_SmartSizing))
242 {
243 UINT32 scale = 0;
244 for (UINT32 x = 0; x < freerdp_settings_get_uint32(settings, FreeRDP_MonitorCount); x++)
245 {
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;
250 }
251 if ((scale == 0) && !sdl->monitorIds().empty())
252 {
253 auto monitor = sdl->getDisplay(sdl->monitorIds().front());
254 sdl->applyMonitorScaleOverride(monitor);
255 scale = monitor.attributes.desktopScaleFactor;
256 }
257 if ((scale >= 100) && (scale <= 500))
258 {
259 if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopScaleFactor, scale))
260 return FALSE;
261 }
262
263 /* With /multimon the server also takes each monitor's own scale from the monitor
264 * attributes ([MS-RDPBCGR] 2.2.1.3.10), unless an override forces one value on all. */
265 if ((overrides == 0) &&
266 !freerdp_settings_set_bool(settings, FreeRDP_HasMonitorAttributes, TRUE))
267 return FALSE;
268 }
269
270 if ((maxWidth != 0) && (maxHeight != 0) &&
271 !freerdp_settings_get_bool(settings, FreeRDP_SmartSizing))
272 {
273 WLog_Print(sdl->getWLog(), WLOG_INFO, "Update size to %ux%u", maxWidth, maxHeight);
274 if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopWidth, maxWidth))
275 return FALSE;
276 if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopHeight, maxHeight))
277 return FALSE;
278 }
279
284
285 const uint32_t sw = freerdp_settings_get_uint32(settings, FreeRDP_SmartSizingWidth);
286 const uint32_t sh = freerdp_settings_get_uint32(settings, FreeRDP_SmartSizingHeight);
287 const BOOL sm = freerdp_settings_get_bool(settings, FreeRDP_SmartSizing);
288 if (sm && (sw > 0) && (sh > 0))
289 {
290 const BOOL mm = freerdp_settings_get_bool(settings, FreeRDP_UseMultimon);
291 if (mm)
292 WLog_Print(sdl->getWLog(), WLOG_WARN,
293 "/smart-sizing and /multimon are currently not supported, ignoring "
294 "/smart-sizing!");
295 else
296 {
297 sdl->_windowWidth = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth);
298 sdl->_windowHeight = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight);
299
300 if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopWidth, sw))
301 return FALSE;
302 if (!freerdp_settings_set_uint32(settings, FreeRDP_DesktopHeight, sh))
303 return FALSE;
304 }
305 }
306 }
307 else
308 {
309 /* Check +auth-only has a username and password. */
310 if (!freerdp_settings_get_string(settings, FreeRDP_Password))
311 {
312 WLog_Print(sdl->getWLog(), WLOG_INFO,
313 "auth-only, but no password set. Please provide one.");
314 return FALSE;
315 }
316
317 if (!freerdp_settings_set_bool(settings, FreeRDP_DeactivateClientDecoding, TRUE))
318 return FALSE;
319
320 WLog_Print(sdl->getWLog(), WLOG_INFO, "Authentication only. Don't connect SDL.");
321 }
322
323 if (!sdl->getInputChannelContext().initialize())
324 return FALSE;
325
326 sdl->_credentialsRead = false;
327
328 /* Settings are consistent at this point, the dialog can be created. */
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;
333 if (dialog && !freerdp_settings_get_bool(settings, FreeRDP_AuthenticationOnly))
334 {
335 sdl->getDialog().create(instance->context);
336 sdl->getDialog().setTitle("Connecting to '%s'", freerdp_settings_get_server_name(settings));
337 sdl->getDialog().showInfo("The connection is being established\n\nPlease wait...");
338 }
339
340 /* TODO: Any code your client requires */
341 return TRUE;
342}
343
344/* Called after a RDP connection was successfully established.
345 * Settings might have changed during negotiation of client / server feature
346 * support.
347 *
348 * Set up local framebuffers and paing callbacks.
349 * If required, register pointer callbacks to change the local mouse cursor
350 * when hovering over the RDP window
351 */
352BOOL SdlContext::postConnect(freerdp* instance)
353{
354 WINPR_ASSERT(instance);
355
356 auto context = instance->context;
357 WINPR_ASSERT(context);
358
359 auto sdl = get_context(context);
360
361 // Retry was successful, discard dialog
362 sdl->getDialog().show(false);
363
364 if (freerdp_settings_get_bool(context->settings, FreeRDP_AuthenticationOnly))
365 {
366 /* Check +auth-only has a username and password. */
367 if (!freerdp_settings_get_string(context->settings, FreeRDP_Password))
368 {
369 WLog_Print(sdl->getWLog(), WLOG_INFO,
370 "auth-only, but no password set. Please provide one.");
371 return FALSE;
372 }
373
374 WLog_Print(sdl->getWLog(), WLOG_INFO, "Authentication only. Don't connect to X.");
375 return TRUE;
376 }
377
378 if (!sdl->waitForWindowsCreated())
379 return FALSE;
380
381 sdl->_sdlPixelFormat = SDL_PIXELFORMAT_BGRA32;
382 if (!gdi_init(instance, PIXEL_FORMAT_BGRA32))
383 return FALSE;
384
385 if (!sdl->createPrimary())
386 return FALSE;
387
388 if (!sdl_register_pointer(instance->context->graphics))
389 return FALSE;
390
391 WINPR_ASSERT(context->update);
392
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;
399
400 if (!sdl->setResizeable(false))
401 return FALSE;
402 if (!sdl->setFullscreen(freerdp_settings_get_bool(context->settings, FreeRDP_Fullscreen) ||
403 freerdp_settings_get_bool(context->settings, FreeRDP_UseMultimon),
404 true))
405 return FALSE;
406 sdl->setConnected(true);
407 /* also after a reconnect: the overlay's rates and totals are this connection's */
408 return sdl->_overlay.connected();
409}
410
411/* This function is called whether a session ends by failure or success.
412 * Clean up everything allocated by pre_connect and post_connect.
413 */
414void SdlContext::postDisconnect(freerdp* instance)
415{
416 if (!instance)
417 return;
418
419 if (!instance->context)
420 return;
421
422 auto sdl = get_context(instance->context);
423 sdl->setConnected(false);
424
425 gdi_free(instance);
426}
427
428void SdlContext::postFinalDisconnect(freerdp* instance)
429{
430 if (!instance)
431 return;
432
433 if (!instance->context)
434 return;
435
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);
442}
443
444/* Create a SDL surface from the GDI buffer */
445bool SdlContext::createPrimary()
446{
447 auto gdi = context()->gdi;
448 WINPR_ASSERT(gdi);
449
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)),
453 SDL_DestroySurface);
454 if (!_primary)
455 return false;
456
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));
461
462 return true;
463}
464
465bool SdlContext::createWindows()
466{
467 auto settings = context()->settings;
468 const auto& title = windowTitle();
469
470 ScopeGuard guard1([&]() { _windowsCreatedEvent.set(); });
471
472 UINT32 windowCount = freerdp_settings_get_uint32(settings, FreeRDP_MonitorCount);
473
474 /* The monitor definitions are sorted (primary first), so they need not be in the same
475 * order as the monitor IDs. Match them by display, fall back to the index. */
476 auto monitorFor = [&](UINT32 index, int64_t id)
477 {
478 for (UINT32 y = 0; y < windowCount; y++)
479 {
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))
483 return cur;
484 }
485 return static_cast<rdpMonitor*>(
486 freerdp_settings_get_pointer_array_writable(settings, FreeRDP_MonitorDefArray, index));
487 };
488
489 Sint32 originX = 0;
490 Sint32 originY = 0;
491 for (UINT32 x = 0; x < windowCount; x++)
492 {
493 auto id = monitorId(x);
494 if (id < 0)
495 return false;
496
497 auto monitor = monitorFor(x, id);
498
499 originX = std::min<Sint32>(monitor->x, originX);
500 originY = std::min<Sint32>(monitor->y, originY);
501 }
502
503 for (UINT32 x = 0; x < windowCount; x++)
504 {
505 auto id = monitorId(x);
506 if (id < 0)
507 return false;
508
509 auto monitor = monitorFor(x, id);
510
511 Uint32 w = WINPR_ASSERTING_INT_CAST(Uint32, monitor->width);
512 Uint32 h = WINPR_ASSERTING_INT_CAST(Uint32, monitor->height);
513 if (!(freerdp_settings_get_bool(settings, FreeRDP_UseMultimon) ||
514 freerdp_settings_get_bool(settings, FreeRDP_Fullscreen)))
515 {
516 if (_windowWidth > 0)
517 w = _windowWidth;
518 else
519 w = freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth);
520
521 if (_windowHeight > 0)
522 h = _windowHeight;
523 else
524 h = freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight);
525 }
526
527 Uint32 flags = SDL_WINDOW_HIGH_PIXEL_DENSITY;
528
529 if (freerdp_settings_get_bool(settings, FreeRDP_Fullscreen) &&
530 !freerdp_settings_get_bool(settings, FreeRDP_UseMultimon))
531 {
532 flags |= SDL_WINDOW_FULLSCREEN;
533 }
534
535 if (freerdp_settings_get_bool(settings, FreeRDP_UseMultimon))
536 {
537 flags |= SDL_WINDOW_BORDERLESS;
538 }
539
540 if (!freerdp_settings_get_bool(settings, FreeRDP_Decorations))
541 flags |= SDL_WINDOW_BORDERLESS;
542
543 /* RemoteApp: the desktop only shows when needed (drawToWindows). */
544 if (freerdp_settings_get_bool(settings, FreeRDP_RemoteApplicationMode))
545 flags |= SDL_WINDOW_HIDDEN;
546
547 auto did = WINPR_ASSERTING_INT_CAST(SDL_DisplayID, id);
548 auto window = SdlWindow::create(did, title, flags, w, h);
549
550 if (freerdp_settings_get_bool(settings, FreeRDP_UseMultimon))
551 {
552 window.setOffsetX(originX - monitor->x);
553 window.setOffsetY(originY - monitor->y);
554 }
555
556 _windows.insert({ window.id(), std::move(window) });
557 }
558
560 return true;
561}
562
563#if defined(__EMSCRIPTEN__)
564/* in sdl_monitors_emscripten.js */
565extern "C" int freerdp_web_monitors_js(int32_t* edges, int max);
566
567/* A browser has one canvas, so one window. The page may show it across several screens and
568 * split it into monitors (sdl_monitors_emscripten.js): the server then places its windows,
569 * panels and maximized windows on each, as on separate physical screens. canvas is the
570 * window's monitor; returns the monitors it is split into, or none. */
571static std::vector<rdpMonitor> sdl_web_monitors(const rdpMonitor& canvas)
572{
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))
577 return {};
578
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++)
583 {
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))
590 return {};
591
592 rdpMonitor m = canvas;
593 m.x = left;
594 m.y = 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));
604 list.push_back(m);
605 }
606 return list;
607}
608#endif
609
610bool SdlContext::updateWindowList()
611{
612 /* The windows only know their own size: keep the layout from connect. */
613 if (freerdp_settings_get_bool(context()->settings, FreeRDP_UseMultimon))
614 return true;
615
616 std::vector<rdpMonitor> list;
617 list.reserve(_windows.size());
618 for (const auto& win : _windows)
619 {
620 auto monitor = win.second.monitor(_windows.size() == 1);
621 applyMonitorScaleOverride(monitor);
622 list.push_back(monitor);
623 }
624
625#if defined(__EMSCRIPTEN__)
626 if ((list.size() == 1) && (list.at(0).width > 0) && (list.at(0).height > 0))
627 {
628 auto split = sdl_web_monitors(list.at(0));
629 if (!split.empty())
630 list = std::move(split);
631 }
632#endif
633
634 // /monitors: subset may exclude the SDL primary. The library requires
635 // the array to mark one monitor as primary, so promote the first when
636 // none of the kept windows cover the original primary.
637 if (!list.empty() &&
638 std::none_of(list.cbegin(), list.cend(), [](const rdpMonitor& m) { return m.is_primary; }))
639 list.at(0).is_primary = true;
640
641 return freerdp_settings_set_monitor_def_array_sorted(context()->settings, list.data(),
642 list.size());
643}
644
645bool SdlContext::updateWindow(SDL_WindowID id)
646{
647 /* In fullscreen the monitor kept the size measured with the probe window at startup and was
648 * never updated, so a session the server started at another size stayed that way. Only the
649 * window knows its real size, so ask it in fullscreen as well. */
650 if (freerdp_settings_get_bool(_context->settings, FreeRDP_UseMultimon))
651 return true;
652
653 auto& w = _windows.at(id);
654 auto m = w.monitor(true);
655 applyMonitorScaleOverride(m);
656 auto r = w.rect();
657 m.width = r.w;
658 m.height = r.h;
659 /* The window may be on another display than the one it was created on. */
660 m.attributes.desktopScaleFactor = static_cast<UINT32>(std::roundf(w.scale() * 100.0f));
661 w.setMonitor(m);
662 return true;
663}
664
665std::string SdlContext::windowTitle() const
666{
667 const char* prefix = "FreeRDP:";
668
669 const auto windowTitle = freerdp_settings_get_string(context()->settings, FreeRDP_WindowTitle);
670 if (windowTitle)
671 return windowTitle;
672
673 const auto name = freerdp_settings_get_server_name(context()->settings);
674 const auto port = freerdp_settings_get_uint32(context()->settings, FreeRDP_ServerPort);
675 const auto addPort = (port != 3389);
676
677 std::stringstream ss;
678 ss << prefix << " " << name;
679
680 if (addPort)
681 ss << ":" << port;
682
683 return ss.str();
684}
685
686bool SdlContext::waitForWindowsCreated()
687{
688 {
689 std::unique_lock<CriticalSection> lock(_critical);
690 _windowsCreatedEvent.clear();
691 if (!sdl_push_user_event(SDL_EVENT_USER_CREATE_WINDOWS, this))
692 return false;
693 }
694
695 HANDLE handles[] = { _windowsCreatedEvent.handle(), freerdp_abort_event(context()) };
696
697 const DWORD rc = WaitForMultipleObjects(ARRAYSIZE(handles), handles, FALSE, INFINITE);
698 switch (rc)
699 {
700 case WAIT_OBJECT_0:
701 return true;
702 default:
703 return false;
704 }
705}
706
707/* This function is called when the library completed composing a new
708 * frame. Read out the changed areas and blit them to your output device.
709 * The image buffer will have the format specified by gdi_init
710 */
711BOOL SdlContext::endPaint(rdpContext* context)
712{
713 auto sdl = get_context(context);
714 WINPR_ASSERT(sdl);
715
716 auto gdi = context->gdi;
717 WINPR_ASSERT(gdi);
718 WINPR_ASSERT(gdi->primary);
719
720 HGDI_DC hdc = gdi->primary->hdc;
721 WINPR_ASSERT(hdc);
722 if (!hdc->hwnd)
723 return TRUE;
724
725 HGDI_WND hwnd = hdc->hwnd;
726 WINPR_ASSERT(hwnd->invalid || (hwnd->ninvalid == 0));
727
728 if (hwnd->invalid->null)
729 return TRUE;
730
731 WINPR_ASSERT(hwnd->invalid);
732 if (gdi->suppressOutput || hwnd->invalid->null)
733 return TRUE;
734
735 const INT32 ninvalid = hwnd->ninvalid;
736 const GDI_RGN* cinvalid = hwnd->cinvalid;
737
738 if (ninvalid < 1)
739 return TRUE;
740
741 std::vector<SDL_Rect> rects;
742 for (INT32 x = 0; x < ninvalid; x++)
743 {
744 auto& rgn = cinvalid[x];
745 rects.push_back({ rgn.x, rgn.y, rgn.w, rgn.h });
746 }
747
748 sdl->push(std::move(rects));
749 return sdl_push_user_event(SDL_EVENT_USER_UPDATE);
750}
751
752void SdlContext::sdl_client_cleanup(int exit_code, const std::string& error_msg)
753{
754 rdpSettings* settings = context()->settings;
755 WINPR_ASSERT(settings);
756
757 _rdpThreadRunning = false;
758 bool showError = false;
759 if (freerdp_settings_get_bool(settings, FreeRDP_AuthenticationOnly))
760 WLog_Print(getWLog(), WLOG_INFO, "Authentication only, exit status %s [%" PRId32 "]",
761 sdl::error::exitCodeToTag(exit_code), exit_code);
762 else
763 {
764 switch (exit_code)
765 {
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:
771 break;
772 default:
773 {
774 showError = true;
775 getDialog().showError(error_msg);
776 }
777 break;
778 }
779 }
780
781 if (!showError)
782 getDialog().show(false);
783
784 _exitCode = exit_code;
785 std::ignore = sdl_push_user_event(SDL_EVENT_USER_QUIT);
786 SDL_CleanupTLS();
787}
788
789int SdlContext::sdl_client_thread_connect(std::string& error_msg)
790{
791 auto instance = context()->instance;
792 WINPR_ASSERT(instance);
793
794 _rdpThreadRunning = true;
795 BOOL rc = freerdp_connect(instance);
796
797 rdpSettings* settings = context()->settings;
798 WINPR_ASSERT(settings);
799
800 int exit_code = sdl::error::SUCCESS;
801 if (!rc)
802 {
803 UINT32 error = freerdp_get_last_error(context());
804 exit_code = sdl::error::errorToExitCode(error);
805 }
806
807 if (freerdp_settings_get_bool(settings, FreeRDP_AuthenticationOnly))
808 {
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));
813 return exit_code;
814 }
815
816 if (!rc)
817 {
818 DWORD code = freerdp_error_info(instance);
819 if (exit_code == sdl::error::SUCCESS)
820 {
821 char* msg = nullptr;
822 size_t len = 0;
823 exit_code = error_info_to_error(&code, &msg, &len);
824 if (msg)
825 error_msg = msg;
826 free(msg);
827 }
828
829 auto last = freerdp_get_last_error(context());
830 if (error_msg.empty())
831 {
832 char* msg = nullptr;
833 size_t len = 0;
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));
837 if (msg)
838 error_msg = msg;
839 free(msg);
840 }
841
842 if (exit_code == sdl::error::SUCCESS)
843 {
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;
848 }
849
850 getDialog().show(false);
851 }
852
853 return exit_code;
854}
855
856int SdlContext::sdl_client_thread_run(std::string& error_msg)
857{
858 auto instance = context()->instance;
859 WINPR_ASSERT(instance);
860
861 int exit_code = sdl::error::SUCCESS;
862 while (!freerdp_shall_disconnect_context(context()))
863 {
864 HANDLE handles[MAXIMUM_WAIT_OBJECTS] = {};
865 /*
866 * win8 and server 2k12 seem to have some timing issue/race condition
867 * when a initial sync request is send to sync the keyboard indicators
868 * sending the sync event twice fixed this problem
869 */
870 if (freerdp_focus_required(instance))
871 {
872 auto ctx = get_context(context());
873 WINPR_ASSERT(ctx);
874
875 auto& input = ctx->getInputChannelContext();
876 if (!input.keyboard_focus_in())
877 break;
878 if (!input.keyboard_focus_in())
879 break;
880 }
881
882 const DWORD nCount = freerdp_get_event_handles(context(), handles, ARRAYSIZE(handles));
883
884 if (nCount == 0)
885 {
886 WLog_Print(getWLog(), WLOG_ERROR, "freerdp_get_event_handles failed");
887 break;
888 }
889
890 const DWORD status = WaitForMultipleObjects(nCount, handles, FALSE, INFINITE);
891
892 if (status == WAIT_FAILED)
893 {
894 WLog_Print(getWLog(), WLOG_ERROR, "WaitForMultipleObjects WAIT_FAILED");
895 break;
896 }
897
898 if (!freerdp_check_event_handles(context()))
899 {
900 if (client_auto_reconnect(instance))
901 {
902 // Retry was successful, discard dialog
903 getDialog().show(false);
904 continue;
905 }
906 else
907 {
908 /*
909 * Indicate an unsuccessful connection attempt if reconnect
910 * did not succeed and no other error was specified.
911 */
912 if (freerdp_error_info(instance) == 0)
913 exit_code = sdl::error::errorToExitCode(freerdp_get_last_error(context()));
914 }
915
916 if (freerdp_get_last_error(context()) == FREERDP_ERROR_SUCCESS)
917 WLog_Print(getWLog(), WLOG_ERROR, "WaitForMultipleObjects failed with %" PRIu32 "",
918 status);
919 if (freerdp_get_last_error(context()) == FREERDP_ERROR_SUCCESS)
920 WLog_Print(getWLog(), WLOG_ERROR, "Failed to check FreeRDP event handles");
921 break;
922 }
923 }
924
925 if (exit_code == sdl::error::SUCCESS)
926 {
927 DWORD code = 0;
928 {
929 char* emsg = nullptr;
930 size_t elen = 0;
931 exit_code = error_info_to_error(&code, &emsg, &elen);
932 if (emsg)
933 error_msg = emsg;
934 free(emsg);
935 }
936
937 if ((code == ERRINFO_LOGOFF_BY_USER) &&
938 (freerdp_get_disconnect_ultimatum(context()) == Disconnect_Ultimatum_user_requested))
939 {
940 const char* msg = "Error info says user did not initiate but disconnect ultimatum says "
941 "they did; treat this as a user logoff";
942
943 char* emsg = nullptr;
944 size_t elen = 0;
945 winpr_asprintf(&emsg, &elen, "%s", msg);
946 if (emsg)
947 error_msg = emsg;
948 free(emsg);
949
950 /* This situation might be limited to Windows XP. */
951 WLog_Print(getWLog(), WLOG_INFO, "%s", msg);
952 exit_code = sdl::error::LOGOFF;
953 }
954 }
955
956 if ((exit_code != sdl::error::SUCCESS) && error_msg.empty())
957 {
958 const auto last = freerdp_get_last_error(context());
959 char* msg = nullptr;
960 size_t len = 0;
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));
963 if (msg)
964 error_msg = msg;
965 free(msg);
966 }
967
968 freerdp_disconnect(instance);
969
970 return exit_code;
971}
972
973/* RDP main loop.
974 * Connects RDP, loops while running and handles event and dispatch, cleans up
975 * after the connection ends. */
976DWORD SdlContext::rdpThreadRun(SdlContext* sdl)
977{
978 WINPR_ASSERT(sdl);
979
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);
985
986 return static_cast<DWORD>(exit_code);
987}
988
989int SdlContext::error_info_to_error(DWORD* pcode, char** msg, size_t* len) const
990{
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);
995
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);
999 if (pcode)
1000 *pcode = code;
1001 return exit_code;
1002}
1003
1004void SdlContext::applyMonitorOffset(SDL_WindowID window, float& x, float& y) const
1005{
1006 if (!freerdp_settings_get_bool(context()->settings, FreeRDP_UseMultimon))
1007 return;
1008
1009 auto w = getWindowForId(window);
1010 x -= static_cast<float>(w->offsetX());
1011 y -= static_cast<float>(w->offsetY());
1012}
1013
1014void SdlContext::updateMonitorDataFromOffsets()
1015{
1016 for (auto& entry : _windows)
1017 {
1018 const auto& monitor = _displays.at(entry.first);
1019 entry.second.setMonitor(monitor);
1020 }
1021}
1022
1023bool SdlContext::drawToWindow(SdlWindow& window, const std::vector<SDL_Rect>& rects)
1024{
1025 if (!isConnected())
1026 return true;
1027
1028 auto gdi = context()->gdi;
1029 WINPR_ASSERT(gdi);
1030
1031 auto size = window.rect();
1032
1033 std::unique_lock lock(_critical);
1034 auto surface = _primary.get();
1035
1036 if (useLocalScale())
1037 {
1038 window.setOffsetX(0);
1039 window.setOffsetY(0);
1040 if (gdi->width < size.w)
1041 {
1042 window.setOffsetX((size.w - gdi->width) / 2);
1043 }
1044 if (gdi->height < size.h)
1045 {
1046 window.setOffsetY((size.h - gdi->height) / 2);
1047 }
1048
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))
1052 return false;
1053 }
1054 else
1055 {
1056 SDL_Point offset{ 0, 0 };
1057 if (freerdp_settings_get_bool(context()->settings, FreeRDP_UseMultimon))
1058 offset = { window.offsetX(), window.offsetY() };
1059 if (!window.drawRects(surface, offset, rects))
1060 return false;
1061 }
1062
1063 window.updateSurface((&window == overlayWindow()) ? &_overlay : nullptr);
1064 return true;
1065}
1066
1067SdlWindow* SdlContext::overlayWindow()
1068{
1069 /* RemoteApp windows are the server's, so v1 has no overlay there */
1070 if (_rail.enabled() || _windows.empty())
1071 return nullptr;
1072 return &_windows.begin()->second;
1073}
1074
1076{
1077 return showOverlay(!_overlay.visible());
1078}
1079
1080bool SdlContext::showOverlay(bool on)
1081{
1082 if (!_overlay.show(on))
1083 return false;
1084 if (on || !isConnected())
1085 return true;
1086
1087 /* hidden: present the picture once without it */
1088 auto window = overlayWindow();
1089 if (window)
1090 window->updateSurface();
1091 return true;
1092}
1093
1094bool SdlContext::updateOverlay()
1095{
1096 auto window = overlayWindow();
1097 if (!window || !isConnected())
1098 return true;
1099
1100 int w = 0;
1101 int h = 0;
1102 if (!SDL_GetWindowSizeInPixels(window->window(), &w, &h))
1103 return true;
1104 if (_overlay.update(w, h, window->rendererName()))
1105 window->updateSurface(&_overlay);
1106 return true;
1107}
1108
1109bool SdlContext::minimizeAllWindows()
1110{
1111 for (auto& w : _windows)
1112 w.second.minimize();
1113 return true;
1114}
1115
1116int SdlContext::exitCode() const
1117{
1118 return _exitCode;
1119}
1120
1121SDL_PixelFormat SdlContext::pixelFormat() const
1122{
1123 return _sdlPixelFormat;
1124}
1125
1126bool SdlContext::addDisplayWindow(SDL_DisplayID id)
1127{
1128 const auto flags =
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));
1133 return true;
1134}
1135
1136bool SdlContext::removeDisplayWindow(SDL_DisplayID id)
1137{
1138 for (auto& w : _windows)
1139 {
1140 if (w.second.displayIndex() == id)
1141 _windows.erase(w.first);
1142 }
1143 return true;
1144}
1145
1146bool SdlContext::detectDisplays()
1147{
1148 int count = 0;
1149 auto display = SDL_GetDisplays(&count);
1150 if (!display)
1151 {
1152 WLog_Print(getWLog(), WLOG_ERROR, "SDL_GetDisplays failed: %s", SDL_GetError());
1153 return false;
1154 }
1155 for (int x = 0; x < count; x++)
1156 {
1157 const auto id = display[x];
1158 addOrUpdateDisplay(id);
1159 }
1160 SDL_free(display);
1161
1162 /* The monitor setup needs at least one display. */
1163 if (_displays.empty())
1164 {
1165 WLog_Print(getWLog(), WLOG_ERROR, "none of the %d displays has a usable size", count);
1166 return false;
1167 }
1168 return true;
1169}
1170
1171rdpMonitor SdlContext::getDisplay(SDL_DisplayID id) const
1172{
1173 return _displays.at(id);
1174}
1175
1176std::vector<SDL_DisplayID> SdlContext::getDisplayIds() const
1177{
1178 std::vector<SDL_DisplayID> keys;
1179 keys.reserve(_displays.size());
1180 for (const auto& entry : _displays)
1181 {
1182 keys.push_back(entry.first);
1183 }
1184 return keys;
1185}
1186
1187const SdlWindow* SdlContext::getWindowForId(SDL_WindowID id) const
1188{
1189 auto it = _windows.find(id);
1190 if (it == _windows.end())
1191 return nullptr;
1192 return &it->second;
1193}
1194
1195SdlWindow* SdlContext::getWindowForId(SDL_WindowID id)
1196{
1197 auto it = _windows.find(id);
1198 if (it == _windows.end())
1199 return nullptr;
1200 return &it->second;
1201}
1202
1203bool SdlContext::allWindowsHidden() const
1204{
1205 return std::all_of(_windows.begin(), _windows.end(),
1206 [](const auto& entry)
1207 {
1208 const auto flags = SDL_GetWindowFlags(entry.second.window());
1209 return (flags & (SDL_WINDOW_HIDDEN | SDL_WINDOW_MINIMIZED)) != 0;
1210 });
1211}
1212
1213SdlWindow* SdlContext::getFirstWindow()
1214{
1215 if (_windows.empty())
1216 return nullptr;
1217 return &_windows.begin()->second;
1218}
1219
1220sdlDispContext& SdlContext::getDisplayChannelContext()
1221{
1222 return _disp;
1223}
1224
1225sdlInput& SdlContext::getInputChannelContext()
1226{
1227 return _input;
1228}
1229
1230sdlClip& SdlContext::getClipboardChannelContext()
1231{
1232 return _clip;
1233}
1234
1235SdlRail& SdlContext::getRailChannelContext()
1236{
1237 return _rail;
1238}
1239
1240SdlConnectionDialogWrapper& SdlContext::getDialog()
1241{
1242 return _dialog;
1243}
1244
1245wLog* SdlContext::getWLog()
1246{
1247 return _log;
1248}
1249
1250bool SdlContext::moveMouseTo(const SDL_FPoint& pos)
1251{
1252 auto window = SDL_GetMouseFocus();
1253 if (!window)
1254 return true;
1255
1256 const auto id = SDL_GetWindowID(window);
1257 const auto spos = pixelToScreen(id, pos);
1258 SDL_WarpMouseInWindow(window, spos.x, spos.y);
1259 return true;
1260}
1261
1262static bool onWindowEdge(SDL_WindowID id, float x, float y)
1263{
1264 int w = 0;
1265 int h = 0;
1266 auto* window = SDL_GetWindowFromID(id);
1267 if (!window || !SDL_GetWindowSize(window, &w, &h))
1268 return false;
1269 return (x <= 0.0f) || (y <= 0.0f) || (x >= static_cast<float>(w - 1)) ||
1270 (y >= static_cast<float>(h - 1));
1271}
1272
1273bool SdlContext::handleEvent(const SDL_MouseMotionEvent& ev)
1274{
1275 SDL_Event copy{};
1276 copy.motion = ev;
1277 /* SDL follows a release outside the window with a motion clamped to its edge: drop it. */
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))
1281 return true;
1282 /* WM owns the drag (#12447); backstop: button released but button-up swallowed by grab. */
1283 if (_rail.enabled() && _rail.suppressServerMotion(ev.windowID))
1284 {
1285 if (!(SDL_GetGlobalMouseState(nullptr, nullptr) & SDL_BUTTON_LMASK))
1286 _rail.completeLocalMoveIfPending();
1287 return true;
1288 }
1289 if (_rail.enabled() && _rail.translateToServer(ev.windowID, copy.motion.x, copy.motion.y))
1290 {
1291 _lastMotion = {
1292 ev.windowID, { ev.x, ev.y }, { copy.motion.x, copy.motion.y }, _rail.pointerEpoch()
1293 };
1294 _rail.noteServerPointer(copy.motion.x, copy.motion.y);
1295 return SdlTouch::handleEvent(this, copy.motion);
1296 }
1297
1298 if (!getWindowForId(ev.windowID))
1299 return true; /* Event for an untracked window (e.g. closed dialog) */
1300 if (!eventToPixelCoordinates(ev.windowID, copy))
1301 return true;
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);
1305
1306 return SdlTouch::handleEvent(this, copy.motion);
1307}
1308
1309bool SdlContext::handleEvent(const SDL_MouseWheelEvent& ev)
1310{
1311 SDL_Event copy{};
1312 copy.wheel = 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);
1316
1317 if (!getWindowForId(ev.windowID))
1318 return true;
1319 if (!eventToPixelCoordinates(ev.windowID, copy))
1320 return true;
1321 removeLocalScaling(copy.wheel.mouse_x, copy.wheel.mouse_y);
1322 return SdlTouch::handleEvent(this, copy.wheel);
1323}
1324
1325bool SdlContext::handleEvent(const SDL_WindowEvent& ev)
1326{
1327 if (!getDisplayChannelContext().handleEvent(ev))
1328 return false;
1329
1330 auto window = getWindowForId(ev.windowID);
1331 if (!window)
1332 {
1333 /* RAIL windows aren't in _windows; handle their events here. */
1334 if (_rail.enabled() && _rail.ownsWindow(ev.windowID))
1335 {
1336 switch (ev.type)
1337 {
1338 case SDL_EVENT_WINDOW_MOUSE_ENTER:
1339 /* Re-enter fires on move-grab end. */
1340 if (!(SDL_GetGlobalMouseState(nullptr, nullptr) & SDL_BUTTON_LMASK))
1341 _rail.completeLocalMoveIfPending(); /* X11 */
1342 _rail.completeWaylandResize(); /* Wayland: compositor grab ended */
1343 /* Restore the cursor or the pointer stays hidden over RemoteApp windows. */
1344 return restoreCursor();
1345 case SDL_EVENT_WINDOW_MOUSE_LEAVE:
1346 /* Compositor took the pointer for the pending Wayland resize grab. */
1347 _rail.noteResizeGrab(ev.windowID);
1348 return true;
1349 case SDL_EVENT_WINDOW_EXPOSED:
1350 /* Force repaint for exposed windows; skip during local drag to avoid redundant
1351 * frames. */
1352 if (!_rail.dragActive(ev.windowID))
1353 _rail.invalidateWindow(ev.windowID);
1354 return true;
1355 case SDL_EVENT_WINDOW_MAXIMIZED:
1356 /* Maximize must complete move first. */
1357 _rail.completeLocalMoveIfPending();
1358 _rail.handleMaximized(ev.windowID);
1359 return true;
1360 case SDL_EVENT_WINDOW_MINIMIZED:
1361 _rail.handleMinimized(ev.windowID);
1362 return true;
1363 case SDL_EVENT_WINDOW_RESTORED:
1364 _rail.handleRestored(ev.windowID);
1365 return true;
1366 case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
1367 /* Send SC_CLOSE, don't abort the session. */
1368 _rail.handleClose(ev.windowID);
1369 return true;
1370 case SDL_EVENT_WINDOW_FOCUS_GAINED:
1371 _rail.handleFocus(ev.windowID, true);
1372 return true;
1373 case SDL_EVENT_WINDOW_FOCUS_LOST:
1374 _rail.handleFocus(ev.windowID, false);
1375 return true;
1376 case SDL_EVENT_WINDOW_DISPLAY_CHANGED:
1377 _rail.handleDisplayChanged(ev.windowID, static_cast<SDL_DisplayID>(ev.data1));
1378 return true;
1379 case SDL_EVENT_WINDOW_MOVED:
1380 _rail.notePopupMoved(ev.windowID);
1381 if (!_rail.dragActive(ev.windowID))
1382 _rail.syncGeometry(ev.windowID);
1383 return true;
1384 case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
1385 /* No server frame during the drag: repaint synchronously each configure step;
1386 * also report the new size to catch a compositor snap/tile. */
1387 _rail.noteDragResize(ev.windowID, ev.data1, ev.data2);
1388 _rail.syncGeometry(ev.windowID);
1389 _rail.noteResizeGrab(ev.windowID);
1390 std::ignore = drawToWindows({});
1391 return true;
1392 default:
1393 break;
1394 }
1395 }
1396 return true;
1397 }
1398
1399 {
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());
1409 }
1410
1411 switch (ev.type)
1412 {
1413 case SDL_EVENT_WINDOW_MOUSE_ENTER:
1414 return restoreCursor();
1415 case SDL_EVENT_WINDOW_DISPLAY_SCALE_CHANGED:
1416 if (!resizeToScale(window))
1417 return false;
1419 if (isConnected())
1420 {
1421 if (!window->fill())
1422 return false;
1423 if (!drawToWindow(*window))
1424 return false;
1425 if (!restoreCursor())
1426 return false;
1427 }
1428 break;
1429 case SDL_EVENT_WINDOW_PIXEL_SIZE_CHANGED:
1430 if (!resizeToScale(window))
1431 return false;
1432 if (!window->fill())
1433 return false;
1434 if (!drawToWindow(*window))
1435 return false;
1436 if (!restoreCursor())
1437 return false;
1439 break;
1440 case SDL_EVENT_WINDOW_MOVED:
1441 {
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);
1445 }
1446 break;
1447 case SDL_EVENT_WINDOW_CLOSE_REQUESTED:
1448 {
1449 SDL_LogDebug(SDL_LOG_CATEGORY_APPLICATION, "Window closed, terminating RDP session...");
1450 std::ignore = abortConnect();
1451 }
1452 break;
1453 default:
1454 break;
1455 }
1456 return true;
1457}
1458
1459bool SdlContext::handleEvent(const SDL_DisplayEvent& ev)
1460{
1461 if (!getDisplayChannelContext().handleEvent(ev))
1462 return false;
1463#if SDL_VERSION_ATLEAST(3, 3, 2)
1464 if (ev.type == SDL_EVENT_DISPLAY_USABLE_BOUNDS_CHANGED)
1465 _rail.noteUsableBoundsChanged(ev.displayID);
1466#endif
1467
1468 switch (ev.type)
1469 {
1470 case SDL_EVENT_DISPLAY_REMOVED: // Can't show details for this one...
1471 break;
1472 default:
1473 {
1474 SDL_Rect r = {};
1475 if (!SDL_GetDisplayBounds(ev.displayID, &r))
1476 return false;
1477 const auto name = SDL_GetDisplayName(ev.displayID);
1478 if (!name)
1479 return false;
1480 const auto orientation = SDL_GetCurrentDisplayOrientation(ev.displayID);
1481 const auto scale = SDL_GetDisplayContentScale(ev.displayID);
1482 const auto mode = SDL_GetCurrentDisplayMode(ev.displayID);
1483 if (!mode)
1484 return false;
1485
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());
1491 }
1492 break;
1493 }
1494 return true;
1495}
1496
1497bool SdlContext::handleEvent(const SDL_MouseButtonEvent& ev)
1498{
1499 SDL_Event copy = {};
1500 copy.button = ev;
1501 if (_rail.enabled())
1502 {
1503 /* Suppress X11 raw button during WM op. */
1504 const bool suppress = _rail.dragActive(ev.windowID);
1505 if (ev.type == SDL_EVENT_MOUSE_BUTTON_UP)
1506 _rail.completeLocalMoveIfPending();
1507 /* Backstop for a Wayland resize whose MOUSE_ENTER completion never arrived; a fresh press
1508 * proves the old grab is over, so a no-op click grab is cancelled here too. */
1509 if (ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN)
1510 _rail.completeWaylandResize(true);
1511 /* activate the clicked window before forwarding, so the click routes to it. */
1512 if (ev.type == SDL_EVENT_MOUSE_BUTTON_DOWN)
1513 _rail.ensureActive(ev.windowID);
1514 if (suppress)
1515 return true;
1516 if (ev.type == SDL_EVENT_MOUSE_BUTTON_UP)
1517 {
1518 _lastRelease = { ev.windowID, ev.timestamp };
1519 }
1520 if (_rail.translateToServer(ev.windowID, copy.button.x, copy.button.y))
1521 {
1522 /* The window may have moved since the last motion: keep the server's position. */
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))
1527 {
1528 copy.button.x = _lastMotion.server.x;
1529 copy.button.y = _lastMotion.server.y;
1530 }
1531 /* Record the forwarded left press: it is the anchor of any server modal move/size
1532 * loop this press starts (the loop moves the window by release - anchor). */
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);
1536 }
1537 }
1538
1539 if (!getWindowForId(ev.windowID))
1540 return true;
1541 if (!eventToPixelCoordinates(ev.windowID, copy))
1542 return true;
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);
1546}
1547
1548bool SdlContext::handleEvent(const SDL_TouchFingerEvent& ev)
1549{
1550 if (!getWindowForId(ev.windowID))
1551 return true;
1552 SDL_Event copy{};
1553 copy.tfinger = ev;
1554 if (!eventToPixelCoordinates(ev.windowID, copy))
1555 return true;
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);
1560}
1561
1562void SdlContext::addOrUpdateDisplay(SDL_DisplayID id)
1563{
1564 auto monitor = SdlWindow::query(id, false);
1565 if ((monitor.width <= 0) || (monitor.height <= 0))
1566 {
1567 WLog_Print(getWLog(), WLOG_WARN, "display %" PRIu32 " has no usable size, skipped", id);
1568 return;
1569 }
1570 _displays.emplace(id, monitor);
1571
1572 /* The logical bounds and the primary are read here, on the thread SDL display functions
1573 * must be called from; updateDisplayOffsets() also runs when the selection is set during
1574 * connect, on another thread. */
1575 _displayBounds.clear();
1576 for (const auto& entry : _displays)
1577 {
1578 SDL_Rect bounds{};
1579 std::ignore = SDL_GetDisplayBounds(entry.first, &bounds);
1580 _displayBounds.emplace(entry.first, bounds);
1581 }
1582 _primaryDisplay = SDL_GetPrimaryDisplay();
1583 updateDisplayOffsets();
1584 updateMonitorDataFromOffsets();
1585}
1586
1587void SdlContext::updateDisplayOffsets()
1588{
1589 /* Update actual display rectangles from the logical display bounds and the known pixel
1590 * width and height of each display. */
1591 _offsets.clear();
1592 for (const auto& entry : _displays)
1593 {
1594 SDL_Rect bounds{};
1595 const auto found = _displayBounds.find(entry.first);
1596 if (found != _displayBounds.end())
1597 bounds = found->second;
1598
1599 SDL_Rect pixel{};
1600 pixel.w = entry.second.width;
1601 pixel.h = entry.second.height;
1602 _offsets.emplace(entry.first, std::pair{ bounds, pixel });
1603 }
1604
1605 if (_offsets.empty())
1606 return;
1607 sdl_display_offsets::update(_offsets, _primaryDisplay, _monitorIds);
1608 for (auto& entry : _displays)
1609 {
1610 const auto& pixel = _offsets.at(entry.first).second;
1611 entry.second.x = pixel.x;
1612 entry.second.y = pixel.y;
1613 }
1614}
1615
1616void SdlContext::deleteDisplay(SDL_DisplayID id)
1617{
1618 _displays.erase(id);
1619}
1620
1621bool SdlContext::eventToPixelCoordinates(SDL_WindowID id, SDL_Event& ev)
1622{
1623 auto w = getWindowForId(id);
1624 if (!w)
1625 return false;
1626
1627 /* Ignore errors here, sometimes SDL has no renderer */
1628 auto renderer = w->renderer();
1629 if (!renderer)
1630 return true;
1631 return SDL_ConvertEventToRenderCoordinates(renderer, &ev);
1632}
1633
1634SDL_FPoint SdlContext::applyLocalScaling(const SDL_FPoint& val) const
1635{
1636 if (!useLocalScale())
1637 return val;
1638
1639 auto rval = val;
1640 rval.x *= _localScale.x;
1641 rval.y *= _localScale.y;
1642 return rval;
1643}
1644
1645void SdlContext::removeLocalScaling(float& x, float& y) const
1646{
1647 if (!useLocalScale())
1648 return;
1649 x /= _localScale.x;
1650 y /= _localScale.y;
1651}
1652
1653SDL_FPoint SdlContext::screenToPixel(SDL_WindowID id, const SDL_FPoint& pos)
1654{
1655 auto w = getWindowForId(id);
1656 if (!w)
1657 {
1658 /* RAIL windows are server-authoritative 1:1 (no local scaling) and not in _windows. */
1659 if (_rail.enabled() && _rail.ownsWindow(id))
1660 return pos;
1661 return {};
1662 }
1663
1664 /* Ignore errors here, sometimes SDL has no renderer */
1665 auto renderer = w->renderer();
1666 if (!renderer)
1667 return pos;
1668
1669 SDL_FPoint rpos{};
1670 if (!SDL_RenderCoordinatesFromWindow(renderer, pos.x, pos.y, &rpos.x, &rpos.y))
1671 return {};
1672 removeLocalScaling(rpos.x, rpos.y);
1673 return rpos;
1674}
1675
1676SDL_FPoint SdlContext::pixelToScreen(SDL_WindowID id, const SDL_FPoint& pos)
1677{
1678 auto w = getWindowForId(id);
1679 if (!w)
1680 {
1681 if (_rail.enabled() && _rail.ownsWindow(id))
1682 return pos;
1683 return {};
1684 }
1685
1686 /* Ignore errors here, sometimes SDL has no renderer */
1687 auto renderer = w->renderer();
1688 if (!renderer)
1689 return pos;
1690
1691 SDL_FPoint rpos{};
1692 if (!SDL_RenderCoordinatesToWindow(renderer, pos.x, pos.y, &rpos.x, &rpos.y))
1693 return {};
1694 return applyLocalScaling(rpos);
1695}
1696
1697SDL_FRect SdlContext::pixelToScreen(SDL_WindowID id, const SDL_FRect& pos, bool round)
1698{
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 };
1702 if (round)
1703 {
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);
1708 }
1709 return r;
1710}
1711
1712bool SdlContext::handleEvent(const SDL_Event& ev)
1713{
1714 if ((ev.type >= SDL_EVENT_DISPLAY_FIRST) && (ev.type <= SDL_EVENT_DISPLAY_LAST))
1715 {
1716 const auto& dev = ev.display;
1717 return handleEvent(dev);
1718 }
1719 if ((ev.type >= SDL_EVENT_WINDOW_FIRST) && (ev.type <= SDL_EVENT_WINDOW_LAST))
1720 {
1721 const auto& wev = ev.window;
1722 return handleEvent(wev);
1723 }
1724 switch (ev.type)
1725 {
1726 case SDL_EVENT_RENDER_TARGETS_RESET:
1727 case SDL_EVENT_RENDER_DEVICE_RESET:
1728 case SDL_EVENT_WILL_ENTER_FOREGROUND:
1729 return redraw();
1730 default:
1731 break;
1732 }
1733
1734 if (!isConnected())
1735 return true;
1736
1737 switch (ev.type)
1738 {
1739 case SDL_EVENT_FINGER_DOWN:
1740 case SDL_EVENT_FINGER_UP:
1741 case SDL_EVENT_FINGER_MOTION:
1742 {
1743 const auto& cev = ev.tfinger;
1744 return handleEvent(cev);
1745 }
1746 case SDL_EVENT_MOUSE_MOTION:
1747
1748 {
1749 const auto& cev = ev.motion;
1750 return handleEvent(cev);
1751 }
1752 case SDL_EVENT_MOUSE_BUTTON_DOWN:
1753 case SDL_EVENT_MOUSE_BUTTON_UP:
1754 {
1755 const auto& cev = ev.button;
1756 return handleEvent(cev);
1757 }
1758 case SDL_EVENT_MOUSE_WHEEL:
1759 {
1760 const auto& cev = ev.wheel;
1761 return handleEvent(cev);
1762 }
1763 case SDL_EVENT_CLIPBOARD_UPDATE:
1764 {
1765 const auto& cev = ev.clipboard;
1766 return getClipboardChannelContext().handleEvent(cev);
1767 }
1768 case SDL_EVENT_KEY_DOWN:
1769 case SDL_EVENT_KEY_UP:
1770 {
1771 const auto& cev = ev.key;
1772 return getInputChannelContext().handleEvent(cev);
1773 }
1774 default:
1775 return true;
1776 }
1777}
1778
1779COMMAND_LINE_ARGUMENT_A* SdlContext::args()
1780{
1781 return _args.data();
1782}
1783
1784size_t SdlContext::argsCount() const
1785{
1786 if (_args.size() <= 1)
1787 return 0;
1788 return _args.size() - 1;
1789}
1790
1791int SdlContext::argumentHandler(const COMMAND_LINE_ARGUMENT_A* arg, void* custom)
1792{
1793 auto sdl = static_cast<SdlContext*>(custom);
1794 if (!sdl)
1795 return -1;
1796
1797 if (arg->Name)
1798 {
1799 if (strcmp(arg->Name, sdl_allow_screensaver) == 0)
1800 {
1801 sdl->_allowScreenSaver = (arg->Value != nullptr);
1802 if (arg->Value != nullptr)
1803 {
1804 if (!SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER, "1"))
1805 {
1806 SDL_LogError(SDL_LOG_CATEGORY_APPLICATION,
1807 "SDL_SetHint(SDL_HINT_VIDEO_ALLOW_SCREENSAVER) failed with %s",
1808 SDL_GetError());
1809 return -2;
1810 }
1811 }
1812 }
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)
1816 {
1817 if (!sdl->_overlay.show(arg->Value != nullptr))
1818 return -2;
1819 }
1820 }
1821 return 0;
1822}
1823
1824void SdlContext::applyMonitorScaleOverride(rdpMonitor& monitor) const
1825{
1826 freerdp_client_apply_monitor_scale(context()->settings, &monitor);
1827}
1828
1829CriticalSection& SdlContext::lock()
1830{
1831 return _critical;
1832}
1833
1834std::vector<rdpPointer*>& SdlContext::pointers()
1835{
1836 return _valid_pointers;
1837}
1838
1839bool SdlContext::contains(const rdpPointer* ptr) const
1840{
1841 for (const auto& cur : _valid_pointers)
1842 {
1843 if (cur == ptr)
1844 return true;
1845 }
1846 return false;
1847}
1848
1849bool SdlContext::credentialsRead() const
1850{
1851 return _credentialsRead;
1852}
1853
1854void SdlContext::setCredentialsRead()
1855{
1856 _credentialsRead = true;
1857}
1858
1859SdlWheelAxis& SdlContext::wheelAxis(bool horizontal)
1860{
1861 return horizontal ? _wheelX : _wheelY;
1862}
1863
1864bool SdlContext::resizeToScale(SdlWindow* window)
1865{
1866 if (freerdp_settings_get_bool(context()->settings, FreeRDP_SmartSizing))
1867 return true;
1868 if (!useLocalScale())
1869 return true;
1870 if (!window)
1871 return false;
1872 return window->resizeToScale();
1873}
1874
1875bool SdlContext::useLocalScale() const
1876{
1877 const auto ssize = freerdp_settings_get_bool(context()->settings, FreeRDP_SmartSizing);
1878 if (ssize)
1879 return true;
1880 const auto dynResize =
1881 freerdp_settings_get_bool(context()->settings, FreeRDP_DynamicResolutionUpdate);
1882 const auto fs = freerdp_settings_get_bool(context()->settings, FreeRDP_Fullscreen);
1883 const auto multimon = freerdp_settings_get_bool(context()->settings, FreeRDP_UseMultimon);
1884 return !dynResize && !fs && !multimon;
1885}
1886
1887bool SdlContext::drawToWindows(const std::vector<SDL_Rect>& rects)
1888{
1889 /* RAIL damage is per-window (_gfxDamage), not in the rects queue: repaint every tick. */
1890 if (_rail.enabled())
1891 {
1892 for (auto& window : _windows)
1893 {
1894 if ((SDL_GetWindowFlags(window.second.window()) & SDL_WINDOW_HIDDEN) == 0)
1895 SDL_HideWindow(window.second.window());
1896 }
1897
1898 std::unique_lock lock(_critical);
1899 _rail.paint(_primary.get(), pixelFormat(), rects);
1900 return true;
1901 }
1902
1903 /* Non-RAIL mode (e.g. Non-Monitored Desktop during UAC / Consent UI): show the desktop window.
1904 * Before the RemoteApp starts, only when the logon needs the user. */
1905 if (freerdp_settings_get_bool(context()->settings, FreeRDP_RemoteApplicationMode) &&
1906 !_rail.desktopMayShow())
1907 return true;
1908 bool firstShow = false;
1909 for (auto& window : _windows)
1910 {
1911 if (SDL_GetWindowFlags(window.second.window()) & SDL_WINDOW_HIDDEN)
1912 {
1913 SDL_ShowWindow(window.second.window());
1914 SDL_RaiseWindow(window.second.window());
1915 firstShow = true;
1916 }
1917 }
1918
1919 if (rects.empty() && !firstShow)
1920 return true;
1921
1922 std::vector<SDL_Rect> drawRects = rects;
1923 {
1924 std::unique_lock lock(_critical);
1925 if ((drawRects.empty() || firstShow) && _primary)
1926 drawRects = { { 0, 0, _primary->w, _primary->h } };
1927 }
1928
1929 for (auto& window : _windows)
1930 {
1931 if (!drawToWindow(window.second, drawRects))
1932 return false;
1933 }
1934
1935 return true;
1936}
1937
1938BOOL SdlContext::desktopResize(rdpContext* context)
1939{
1940 rdpGdi* gdi = nullptr;
1941 rdpSettings* settings = nullptr;
1942 auto sdl = get_context(context);
1943
1944 WINPR_ASSERT(sdl);
1945 WINPR_ASSERT(context);
1946
1947 settings = context->settings;
1948 WINPR_ASSERT(settings);
1949
1950 std::unique_lock lock(sdl->_critical);
1951 gdi = context->gdi;
1952 if (!gdi_resize(gdi, freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth),
1953 freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight)))
1954 return FALSE;
1955 return sdl->createPrimary();
1956}
1957
1958/* This function is called to output a System BEEP */
1959BOOL SdlContext::playSound(rdpContext* context, const PLAY_SOUND_UPDATE* play_sound)
1960{
1961 /* TODO: Implement */
1962 WINPR_UNUSED(context);
1963 WINPR_UNUSED(play_sound);
1964 return TRUE;
1965}
1966
1967/* This function is called whenever a new frame starts.
1968 * It can be used to reset invalidated areas. */
1969BOOL SdlContext::beginPaint(rdpContext* context)
1970{
1971 auto gdi = context->gdi;
1972 WINPR_ASSERT(gdi);
1973 WINPR_ASSERT(gdi->primary);
1974
1975 HGDI_DC hdc = gdi->primary->hdc;
1976 WINPR_ASSERT(hdc);
1977 if (!hdc->hwnd)
1978 return TRUE;
1979
1980 HGDI_WND hwnd = hdc->hwnd;
1981 WINPR_ASSERT(hwnd->invalid);
1982 hwnd->invalid->null = TRUE;
1983 hwnd->ninvalid = 0;
1984
1985 return TRUE;
1986}
1987
1988bool SdlContext::redraw(bool suppress) const
1989{
1990 if (!_connected)
1991 return true;
1992
1993 /* RemoteApp desktop windows are placeholders, hiding one must not stop server output. */
1994 if (suppress && freerdp_settings_get_bool(context()->settings, FreeRDP_RemoteApplicationMode))
1995 return true;
1996
1997 auto gdi = context()->gdi;
1998 WINPR_ASSERT(gdi);
1999 return gdi_send_suppress_output(gdi, suppress);
2000}
2001
2002void SdlContext::setConnected(bool val)
2003{
2004 _connected = val;
2005}
2006
2007bool SdlContext::isConnected() const
2008{
2009 return _connected;
2010}
2011
2012/* Stop requested by the user. Overwrite any earlier error with CONNECT_CANCELLED,
2013 * otherwise an auto reconnect ignores the stop. */
2014bool SdlContext::abortConnect() const
2015{
2016 freerdp_set_last_error(context(), FREERDP_ERROR_CONNECT_CANCELLED);
2017 return freerdp_abort_connect_context(context());
2018}
2019
2020rdpContext* SdlContext::context() const
2021{
2022 WINPR_ASSERT(_context);
2023 return _context;
2024}
2025
2026rdpClientContext* SdlContext::common() const
2027{
2028 return reinterpret_cast<rdpClientContext*>(context());
2029}
2030
2031bool SdlContext::setCursor(CursorType type)
2032{
2033 _cursorType = type;
2034 return restoreCursor();
2035}
2036
2037bool SdlContext::setCursor(const rdpPointer* cursor)
2038{
2039 std::unique_lock lock(_critical);
2040 if (!contains(cursor))
2041 return true;
2042
2043 _cursor = { sdl_Pointer_Copy(cursor), sdl_PointerFreeCopyAll };
2044 return setCursor(CURSOR_IMAGE);
2045}
2046
2047rdpPointer* SdlContext::cursor() const
2048{
2049 return _cursor.get();
2050}
2051
2052bool SdlContext::restoreCursor()
2053{
2054 WLog_Print(getWLog(), WLOG_TRACE, "restore cursor: %d", _cursorType);
2055 switch (_cursorType)
2056 {
2057 case CURSOR_NULL:
2058 if (!SDL_HideCursor())
2059 {
2060 WLog_Print(getWLog(), WLOG_ERROR, "SDL_HideCursor failed");
2061 return false;
2062 }
2063
2064 setHasCursor(false);
2065 return true;
2066
2067 case CURSOR_DEFAULT:
2068 {
2069 auto def = SDL_GetDefaultCursor();
2070 if (!SDL_SetCursor(def))
2071 {
2072 WLog_Print(getWLog(), WLOG_ERROR, "SDL_SetCursor(default=%p) failed",
2073 static_cast<void*>(def));
2074 return false;
2075 }
2076 if (!SDL_ShowCursor())
2077 {
2078 WLog_Print(getWLog(), WLOG_ERROR, "SDL_ShowCursor failed");
2079 return false;
2080 }
2081 setHasCursor(true);
2082 return true;
2083 }
2084 case CURSOR_IMAGE:
2085 setHasCursor(true);
2086 return sdl_Pointer_Set_Process(this);
2087 default:
2088 WLog_Print(getWLog(), WLOG_ERROR, "Unknown cursorType %s",
2089 sdl::utils::toString(_cursorType).c_str());
2090 return false;
2091 }
2092}
2093
2094void SdlContext::setMonitorIds(const std::vector<SDL_DisplayID>& ids)
2095{
2096 _monitorIds.clear();
2097 for (auto id : ids)
2098 {
2099 _monitorIds.push_back(id);
2100 }
2101 /* Only the selected displays are sent, so only they need to fit together. This runs during
2102 * connect, outside the thread that owns the windows; they are not touched here and are
2103 * created from the updated displays. */
2104 updateDisplayOffsets();
2105}
2106
2107const std::vector<SDL_DisplayID>& SdlContext::monitorIds() const
2108{
2109 return _monitorIds;
2110}
2111
2112int64_t SdlContext::monitorId(uint32_t index) const
2113{
2114 if (index >= _monitorIds.size())
2115 {
2116 return -1;
2117 }
2118 return _monitorIds.at(index);
2119}
2120
2121void SdlContext::push(std::vector<SDL_Rect>&& rects)
2122{
2123 std::unique_lock lock(_queue_mux);
2124 _queue.emplace(std::move(rects));
2125}
2126
2127std::vector<SDL_Rect> SdlContext::pop()
2128{
2129 std::unique_lock lock(_queue_mux);
2130 if (_queue.empty())
2131 {
2132 return {};
2133 }
2134 auto val = std::move(_queue.front());
2135 _queue.pop();
2136 return val;
2137}
2138
2139bool SdlContext::setFullscreen(bool enter, bool forceOriginalDisplay)
2140{
2141 for (const auto& window : _windows)
2142 {
2143 if (!sdl_push_user_event(SDL_EVENT_USER_WINDOW_FULLSCREEN, &window.second, enter,
2144 forceOriginalDisplay))
2145 return false;
2146 }
2147 _fullscreen = enter;
2148 return true;
2149}
2150
2151bool SdlContext::setMinimized()
2152{
2153 return sdl_push_user_event(SDL_EVENT_USER_WINDOW_MINIMIZE);
2154}
2155
2156bool SdlContext::grabMouse() const
2157{
2158 return _grabMouse;
2159}
2160
2161bool SdlContext::toggleGrabMouse()
2162{
2163 return setGrabMouse(!grabMouse());
2164}
2165
2166bool SdlContext::setGrabMouse(bool enter)
2167{
2168 _grabMouse = enter;
2169 return true;
2170}
2171
2172bool SdlContext::grabKeyboard() const
2173{
2174 return _grabKeyboard;
2175}
2176
2177bool SdlContext::toggleGrabKeyboard()
2178{
2179 return setGrabKeyboard(!grabKeyboard());
2180}
2181
2182bool SdlContext::setGrabKeyboard(bool enter)
2183{
2184 _grabKeyboard = enter;
2185 return true;
2186}
2187
2188bool SdlContext::setResizeable(bool enable)
2189{
2190 const auto settings = context()->settings;
2191 const bool dyn = freerdp_settings_get_bool(settings, FreeRDP_DynamicResolutionUpdate);
2192 const bool smart = freerdp_settings_get_bool(settings, FreeRDP_SmartSizing);
2193 bool use = (dyn && enable) || smart;
2194
2195 for (const auto& window : _windows)
2196 {
2197 if (!sdl_push_user_event(SDL_EVENT_USER_WINDOW_RESIZEABLE, &window.second, use))
2198 return false;
2199 }
2200 _resizeable = use;
2201
2202 return true;
2203}
2204
2205bool SdlContext::resizeable() const
2206{
2207 return _resizeable;
2208}
2209
2210bool SdlContext::toggleResizeable()
2211{
2212 return setResizeable(!resizeable());
2213}
2214
2215bool SdlContext::fullscreen() const
2216{
2217 return _fullscreen;
2218}
2219
2220bool SdlContext::toggleFullscreen()
2221{
2222 return setFullscreen(!fullscreen());
2223}
2224
2225/* ---- rdpContext::windowInfoService ---- */
2226
2227static bool window_info_equal(const WTS_WINDOW_INFO& a, const WTS_WINDOW_INFO& b)
2228{
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) &&
2233 scale;
2234}
2235
2237static HWND native_window(SDL_Window* window)
2238{
2239 if (!window)
2240 return nullptr;
2241 auto props = SDL_GetWindowProperties(window);
2242#if defined(_WIN32)
2243 return static_cast<HWND>(
2244 SDL_GetPointerProperty(props, SDL_PROP_WINDOW_WIN32_HWND_POINTER, nullptr));
2245#else
2246 return reinterpret_cast<HWND>(
2247 static_cast<uintptr_t>(SDL_GetNumberProperty(props, SDL_PROP_WINDOW_X11_WINDOW_NUMBER, 0)));
2248#endif
2249}
2250
2252{
2253 WTS_WINDOW_INFO info{};
2254 auto window = getFirstWindow();
2255 if (window && window->window())
2256 {
2257 auto settings = _context->settings;
2258 info.hwnd = native_window(window->window());
2259 info.remoteWidth =
2260 static_cast<INT32>(freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth));
2261 info.remoteHeight =
2262 static_cast<INT32>(freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight));
2263 int w = 0;
2264 int h = 0;
2265 if (SDL_GetWindowSizeInPixels(window->window(), &w, &h))
2266 {
2267 info.viewWidth = w;
2268 info.viewHeight = h;
2269 }
2270 /* session pixels to native pixels */
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;
2276 }
2277
2278 {
2279 std::scoped_lock lock(_windowInfoLock);
2280 if (window_info_equal(info, _desktopWindowInfo))
2281 return;
2282 _desktopWindowInfo = info;
2283 }
2284 if (!_rail.enabled())
2285 freerdp_client_window_info_service_changed(_context->windowInfoService, 0);
2286}
2287
2289{
2290 bool first = false;
2291 {
2292 std::scoped_lock lock(_windowInfoLock);
2293 first = _railWindowInfoPending.empty();
2294 _railWindowInfoPending.insert(remoteId);
2295 }
2296 if (first)
2297 std::ignore = sdl_push_user_event(SDL_EVENT_USER_WINDOW_INFO);
2298}
2299
2301{
2302 std::set<uint64_t> pending;
2303 {
2304 std::scoped_lock lock(_windowInfoLock);
2305 pending.swap(_railWindowInfoPending);
2306 }
2307
2308 for (const auto id : pending)
2309 {
2310 WTS_WINDOW_INFO info{};
2311 SDL_Window* window = nullptr;
2312 /* RemoteApp windows are drawn 1:1: the same remote and view size, scale left at 0 */
2313 if (_rail.windowGeometry(id, window, info.viewWidth, info.viewHeight))
2314 {
2315 info.hwnd = native_window(window);
2316 info.remoteWidth = info.viewWidth;
2317 info.remoteHeight = info.viewHeight;
2318 }
2319 {
2320 std::scoped_lock lock(_windowInfoLock);
2321 if (info.viewWidth > 0)
2322 _railWindowInfo[id] = info;
2323 else
2324 _railWindowInfo.erase(id);
2325 }
2326 if (info.viewWidth > 0)
2327 freerdp_client_window_info_service_changed(_context->windowInfoService, id);
2328 }
2329}
2330
2331HRESULT SdlContext::windowInfoGet(void* custom, UINT64 remoteHwnd, WTS_WINDOW_INFO* info)
2332{
2333 auto sdl = static_cast<SdlContext*>(custom);
2334 WINPR_ASSERT(sdl);
2335 WINPR_ASSERT(info);
2336
2337 std::scoped_lock lock(sdl->_windowInfoLock);
2338 if (!sdl->_rail.enabled())
2339 {
2340 /* remoteHwnd only means something in RemoteApp */
2341 if (!sdl->_desktopWindowInfo.hwnd && (sdl->_desktopWindowInfo.viewWidth == 0))
2342 return E_UNEXPECTED; /* no window yet */
2343 *info = sdl->_desktopWindowInfo;
2344 return S_OK;
2345 }
2346 auto it = sdl->_railWindowInfo.find(remoteHwnd);
2347 if (it == sdl->_railWindowInfo.end())
2348 return E_INVALIDARG;
2349 *info = it->second;
2350 return S_OK;
2351}
2352
2353UINT32 SdlContext::windowInfoSessionType(void* custom)
2354{
2355 auto sdl = static_cast<SdlContext*>(custom);
2356 WINPR_ASSERT(sdl);
2357 return sdl->_rail.enabled() ? WTS_RDP_SESSION_TYPE_REMOTEAPP : WTS_RDP_SESSION_TYPE_DESKTOP;
2358}
2359
2360/* ---- mapped renderers (rdpContext::bitmapRenderService): the channels' calls come from their
2361 * threads, the textures are the main thread's ---- */
2362
2363Uint64 SdlContext::rendererAdd(UINT64 mappingId, IWTSBitmapRendererCallback* callback)
2364{
2365 std::scoped_lock lock(_rendererLock);
2366 const auto id = _nextRenderer++;
2367 auto& r = _renderers[id];
2368 r.mappingId = mappingId;
2369 r.callback = callback;
2370 if (callback)
2371 callback->AddRef();
2372 return id;
2373}
2374
2375bool SdlContext::rendererFrame(Uint64 id, const BYTE* data, UINT32 width, UINT32 height,
2376 LONG stride)
2377{
2378 if (stride <= 0)
2379 return false;
2380
2381 {
2382 std::scoped_lock lock(_rendererLock);
2383 auto it = _renderers.find(id);
2384 if (it == _renderers.end())
2385 return false;
2386 auto& r = it->second;
2387 /* Render's buffer is the caller's for the call only */
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++)
2391 {
2392 const auto offset = row * y;
2393 const auto end = offset + row;
2394 const auto dataoffset = 1ull * y * static_cast<size_t>(stride);
2395
2396 try
2397 {
2398 auto& ptr = r.pixels.at(offset);
2399 std::ignore = r.pixels.at(end);
2400 memcpy(&ptr, &data[dataoffset], row);
2401 }
2402 catch (std::out_of_range& ex)
2403 {
2404 SDL_Log("failed to render: %s", ex.what());
2405 return false;
2406 }
2407 }
2408 r.pitch = static_cast<int>(row);
2409 r.width = static_cast<int>(width);
2410 r.height = static_cast<int>(height);
2411 r.dirty = true;
2412 }
2413 renderersChanged();
2414 return true;
2415}
2416
2417void SdlContext::rendererRemove(Uint64 id)
2418{
2419 IWTSBitmapRendererCallback* callback = nullptr;
2420 {
2421 std::scoped_lock lock(_rendererLock);
2422 auto it = _renderers.find(id);
2423 if (it == _renderers.end())
2424 return;
2425 callback = it->second.callback;
2426 _renderers.erase(it);
2427 }
2428 if (callback)
2429 callback->Release();
2430 renderersChanged();
2431}
2432
2433bool SdlContext::hasRenderers()
2434{
2435 std::scoped_lock lock(_rendererLock);
2436 return !_renderers.empty();
2437}
2438
2439void SdlContext::renderersChanged()
2440{
2441 /* one pending event at a time: frames coming faster than we draw are coalesced */
2442 if (!_renderersPending.exchange(true))
2443 std::ignore = sdl_push_user_event(SDL_EVENT_USER_RENDERER);
2444}
2445
2447{
2448 _renderersPending = false;
2449 if (!isConnected())
2450 return true;
2451
2452 /* OnTargetSizeChanged() calls, made once _rendererLock is released */
2453 std::vector<std::pair<IWTSBitmapRendererCallback*, WTS_RECT>> targets;
2454 {
2455 std::scoped_lock lock(_rendererLock);
2456
2457 /* a renderer is placed by its mapping's geometry (MS-RDPEGT), hidden without one */
2458 struct Placement
2459 {
2460 bool visible = false;
2461 SDL_Rect rect{};
2462 std::vector<SDL_Rect> region; /* the visible parts, empty: all of it */
2463 };
2464 std::map<Uint64, Placement> placements;
2465 rdpGdi* gdi = _context->gdi;
2466 GeometryClientContext* geometry = gdi ? gdi->geometry : nullptr;
2467 if (geometry && geometry->geometries)
2468 {
2469 HashTable_Lock(geometry->geometries);
2470 for (auto& kv : _renderers)
2471 {
2472 auto g = static_cast<const MAPPED_GEOMETRY*>(
2473 HashTable_GetItemValue(geometry->geometries, &kv.second.mappingId));
2474 if (!g)
2475 continue;
2476 Placement p;
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);
2482 /* the region's rectangles are relative to the tracked rectangle */
2483 INT64 area = 0;
2484 for (UINT32 i = 0; g->geometry.rects && (i < g->geometry.nRectCount); i++)
2485 {
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))
2492 continue;
2493 area += static_cast<INT64>(right - left) * (bottom - top);
2494 p.region.push_back(
2495 { p.rect.x + left, p.rect.y + top, right - left, bottom - top });
2496 }
2497 if (area >= static_cast<INT64>(p.rect.w) * p.rect.h)
2498 p.region.clear();
2499 placements[kv.first] = std::move(p);
2500 }
2501 HashTable_Unlock(geometry->geometries);
2502 }
2503
2504 for (auto& kv : _renderers)
2505 {
2506 auto& r = kv.second;
2507 const auto& p = placements[kv.first];
2508 if (p.visible && r.callback && !SDL_RectsEqual(&p.rect, &r.target))
2509 {
2510 r.target = p.rect;
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 });
2514 }
2515 }
2516
2517 for (auto& w : _windows)
2518 {
2519 auto& window = w.second;
2520 window.pruneVideoOverlays([this](Uint64 id) { return _renderers.count(id) != 0; });
2521 for (auto& kv : _renderers)
2522 {
2523 auto& r = kv.second;
2524 const auto& p = placements[kv.first];
2525 /* where the session is drawn in the window: as drawToWindow() does */
2526 SDL_Point offset{ 0, 0 };
2527 if (!useLocalScale() &&
2528 freerdp_settings_get_bool(context()->settings, FreeRDP_UseMultimon))
2529 offset = { window.offsetX(), window.offsetY() };
2530 auto toWindow = [&](const SDL_Rect& rc)
2531 {
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) };
2540 };
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))
2549 continue;
2550 }
2551 window.updateSurface();
2552 }
2553 for (auto& kv : _renderers)
2554 kv.second.dirty = false;
2555 }
2556
2557 for (auto& t : targets)
2558 {
2559 std::ignore = t.first->OnTargetSizeChanged(t.second);
2560 t.first->Release();
2561 }
2562 return true;
2563}
void flushWindowInfo()
void railWindowInfoChanged(uint64_t remoteId)
void updateWindowInfo()
bool presentRenderers()
bool toggleOverlay()
bool show(bool on)
object that handles clipboard context for the SDL3 client
Definition sdl_clip.hpp:78
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
40 bytes on x64