FreeRDP
Loading...
Searching...
No Matches
SDL3/sdl_window.cpp
1
20#include <limits>
21#include <sstream>
22#include <cmath>
23
24#include "sdl_window.hpp"
25#include "sdl_utils.hpp"
26#include "sdl_overlay.hpp"
27
28#include <freerdp/utils/string.h>
29
30SdlWindow::SdlWindow(SDL_DisplayID id, const std::string& title, const SDL_Rect& rect,
31 [[maybe_unused]] Uint32 flags)
32 : _initialW(rect.w), _initialH(rect.h), _displayID(id)
33{
34 float pd = SDL_GetDisplayContentScale(id);
35 if (pd <= 0.0f)
36 pd = 1.0f;
37 const int createW = static_cast<int>(std::ceil(static_cast<float>(rect.w) / pd));
38 const int createH = static_cast<int>(std::ceil(static_cast<float>(rect.h) / pd));
39
40 auto props = SDL_CreateProperties();
41 SDL_SetStringProperty(props, SDL_PROP_WINDOW_CREATE_TITLE_STRING, title.c_str());
42 SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_X_NUMBER, rect.x);
43 SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_Y_NUMBER, rect.y);
44 SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, createW);
45 SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, createH);
46 SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_RESIZABLE_BOOLEAN, true);
47
48 if (flags & SDL_WINDOW_HIGH_PIXEL_DENSITY)
49 SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN, true);
50
51 if (flags & SDL_WINDOW_FULLSCREEN)
52 SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_FULLSCREEN_BOOLEAN, true);
53
54 if (flags & SDL_WINDOW_BORDERLESS)
55 SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_BORDERLESS_BOOLEAN, true);
56
57 if (flags & SDL_WINDOW_TRANSPARENT)
58 SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_TRANSPARENT_BOOLEAN, true);
59
60 /* RAIL windows are created hidden until first paint to avoid black flash. */
61 if (flags & SDL_WINDOW_HIDDEN)
62 SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_HIDDEN_BOOLEAN, true);
63
64 _window = SDL_CreateWindowWithProperties(props);
65 SDL_DestroyProperties(props);
66 SDL_SetHint(SDL_HINT_APP_NAME, "");
67 std::ignore = SDL_SyncWindow(_window);
68
69 _renderer = SDL_CreateRenderer(_window, nullptr);
70
71 std::ignore = resizeToScale();
72
73 _monitor = query(_window, id, true);
74}
75
76SdlWindow::SdlWindow(SdlWindow&& other) noexcept
77 : _window(other._window), _videoOverlays(std::move(other._videoOverlays)),
78 _renderer(other._renderer), _renderTarget(other._renderTarget),
79 _gdiTexture(other._gdiTexture), _overlayPainter(std::move(other._overlayPainter)),
80 _gdiTextureW(other._gdiTextureW), _gdiTextureH(other._gdiTextureH),
81 _initialW(other._initialW), _initialH(other._initialH), _displayID(other._displayID),
82 _layoutPosition(other._layoutPosition), _offset_x(other._offset_x),
83 _offset_y(other._offset_y), _monitor(other._monitor)
84{
85 other._videoOverlays.clear();
86 other._window = nullptr;
87 other._renderer = nullptr;
88 other._renderTarget = nullptr;
89 other._gdiTexture = nullptr;
90}
91
92SdlWindow::~SdlWindow()
93{
94 for (auto& o : _videoOverlays)
95 SDL_DestroyTexture(o.second.texture);
96 /* its text lives in the renderer */
97 _overlayPainter.reset();
98 if (_gdiTexture)
99 SDL_DestroyTexture(_gdiTexture);
100 if (_renderTarget)
101 SDL_DestroyTexture(_renderTarget);
102 if (_renderer)
103 SDL_DestroyRenderer(_renderer);
104 if (_window)
105 SDL_DestroyWindow(_window);
106}
107
108SDL_WindowID SdlWindow::id() const
109{
110 if (!_window)
111 return 0;
112 return SDL_GetWindowID(_window);
113}
114
115SDL_DisplayID SdlWindow::displayIndex() const
116{
117 if (!_window)
118 return 0;
119 return SDL_GetDisplayForWindow(_window);
120}
121
122SDL_Rect SdlWindow::rect() const
123{
124 return rect(_window);
125}
126
127SDL_Rect SdlWindow::bounds() const
128{
129 SDL_Rect rect = {};
130 if (_window)
131 {
132 if (!SDL_GetWindowPosition(_window, &rect.x, &rect.y))
133 return {};
134 if (!SDL_GetWindowSize(_window, &rect.w, &rect.h))
135 return {};
136 }
137 return rect;
138}
139
140SDL_Window* SdlWindow::window() const
141{
142 return _window;
143}
144
145SDL_Renderer* SdlWindow::renderer() const
146{
147 return _renderer;
148}
149
150Sint32 SdlWindow::offsetX() const
151{
152 return _offset_x;
153}
154
155void SdlWindow::setOffsetX(Sint32 x)
156{
157 _offset_x = x;
158}
159
160void SdlWindow::setOffsetY(Sint32 y)
161{
162 _offset_y = y;
163}
164
165Sint32 SdlWindow::offsetY() const
166{
167 return _offset_y;
168}
169
170SDL_Point SdlWindow::layoutPosition() const
171{
172 return _layoutPosition;
173}
174
175void SdlWindow::setLayoutPosition(const SDL_Point& pos)
176{
177 _layoutPosition = pos;
178}
179
180rdpMonitor SdlWindow::monitor(bool isPrimary) const
181{
182 auto m = _monitor;
183 if (isPrimary)
184 {
185 m.x = 0;
186 m.y = 0;
187 }
188 return m;
189}
190
191void SdlWindow::setMonitor(rdpMonitor monitor)
192{
193 _monitor = monitor;
194}
195
196float SdlWindow::scale() const
197{
198 return SDL_GetWindowDisplayScale(_window);
199}
200
201SDL_DisplayOrientation SdlWindow::orientation() const
202{
203 const auto did = displayIndex();
204 return SDL_GetCurrentDisplayOrientation(did);
205}
206
207bool SdlWindow::grabKeyboard(bool enable)
208{
209 if (!_window)
210 return false;
211 SDL_SetWindowKeyboardGrab(_window, enable);
212 return true;
213}
214
215bool SdlWindow::grabMouse(bool enable)
216{
217 if (!_window)
218 return false;
219 SDL_SetWindowMouseGrab(_window, enable);
220 return true;
221}
222
223void SdlWindow::setBordered(bool bordered)
224{
225 if (_window)
226 SDL_SetWindowBordered(_window, bordered);
227 /* No SDL_SyncWindow: this runs for every window event, and on macOS each one waited for SDL's
228 * sync timeout (2.5 s) while a full screen change was pending. SDL ignores an unchanged border
229 * anyway. */
230}
231
232void SdlWindow::raise()
233{
234 SDL_RaiseWindow(_window);
235 std::ignore = SDL_SyncWindow(_window);
236}
237
238void SdlWindow::resizeable(bool use)
239{
240 SDL_SetWindowResizable(_window, use);
241 std::ignore = SDL_SyncWindow(_window);
242}
243
244void SdlWindow::fullscreen(bool enter, bool forceOriginalDisplay)
245{
246 if (enter && forceOriginalDisplay && _displayID != 0)
247 {
248 /* Move the window to the desired display. We should not wait
249 * for the window to be moved, because some backends can refuse
250 * the move. The intent of moving the window is enough for SDL
251 * to decide which display will be used for fullscreen. */
252 SDL_Rect rect = {};
253 std::ignore = SDL_GetDisplayBounds(_displayID, &rect);
254 std::ignore = SDL_SetWindowPosition(_window, rect.x, rect.y);
255 }
256 std::ignore = SDL_SetWindowFullscreen(_window, enter);
257 std::ignore = SDL_SyncWindow(_window);
258}
259
260void SdlWindow::minimize()
261{
262 SDL_MinimizeWindow(_window);
263 std::ignore = SDL_SyncWindow(_window);
264}
265
266bool SdlWindow::resizeToScale()
267{
268 if (!_window || _initialW <= 0 || _initialH <= 0)
269 return false;
270 if ((SDL_GetWindowFlags(_window) & SDL_WINDOW_FULLSCREEN) != 0)
271 return true;
272
273 float pd = SDL_GetWindowPixelDensity(_window);
274 if (pd <= 0.0f)
275 pd = 1.0f;
276
277 /* On macOS window sizes are in points, and a HighDPI display has more than one pixel
278 * per point. Keep the requested size in points, like the native mac client did, and let
279 * local scaling fill the window. Dividing by the pixel density would make the window a
280 * quarter of the expected area on a Retina display. */
281 if (isHighDPIWindowsMode(_window) == MODE_MACOS)
282 pd = 1.0f;
283
284 const int targetW = static_cast<int>(std::ceil(static_cast<float>(_initialW) / pd));
285 const int targetH = static_cast<int>(std::ceil(static_cast<float>(_initialH) / pd));
286
287 int curW = 0;
288 int curH = 0;
289 if (!SDL_GetWindowSize(_window, &curW, &curH))
290 return false;
291
292 if (curW == targetW && curH == targetH)
293 return true;
294
295 return resize({ targetW, targetH });
296}
297
298bool SdlWindow::resize(const SDL_Point& size)
299{
300 return SDL_SetWindowSize(_window, size.x, size.y);
301}
302
303void SdlWindow::ensureRenderTarget()
304{
305 if (!_renderer)
306 return;
307
308 int w = 0;
309 int h = 0;
310 SDL_GetWindowSizeInPixels(_window, &w, &h);
311 if (w <= 0 || h <= 0)
312 return;
313
314 /* Recreate if missing or if window size changed */
315 if (_renderTarget)
316 {
317 float tw = 0;
318 float th = 0;
319 if (!SDL_GetTextureSize(_renderTarget, &tw, &th))
320 return;
321 if (static_cast<int>(tw) == w && static_cast<int>(th) == h)
322 return;
323 SDL_DestroyTexture(_renderTarget);
324 }
325
326 _renderTarget =
327 SDL_CreateTexture(_renderer, SDL_PIXELFORMAT_BGRA32, SDL_TEXTUREACCESS_TARGET, w, h);
328 if (!_renderTarget)
329 {
330 SDL_LogError(SDL_LOG_CATEGORY_RENDER, "SDL_CreateTexture (render target): %s",
331 SDL_GetError());
332 return;
333 }
334 /* Verbatim, never blended: a transparent window's alpha<0xFF regions would render black. */
335 std::ignore = SDL_SetTextureBlendMode(_renderTarget, SDL_BLENDMODE_NONE);
336
337 /* Clear once: transparent so windows never flash black before painting. */
338 if (SDL_SetRenderTarget(_renderer, _renderTarget))
339 {
340 std::ignore = SDL_SetRenderDrawColor(_renderer, 0x00, 0x00, 0x00, 0x00);
341 std::ignore = SDL_RenderClear(_renderer);
342 }
343}
344
345bool SdlWindow::drawRect(SDL_Surface* surface, SDL_Point offset, const SDL_Rect& srcRect)
346{
347 WINPR_ASSERT(surface);
348 SDL_Rect dstRect = { offset.x + srcRect.x, offset.y + srcRect.y, srcRect.w, srcRect.h };
349 return blit(surface, srcRect, dstRect);
350}
351
352bool SdlWindow::drawRects(SDL_Surface* surface, SDL_Point offset,
353 const std::vector<SDL_Rect>& rects)
354{
355 if (rects.empty())
356 {
357 return drawRect(surface, offset, { 0, 0, surface->w, surface->h });
358 }
359 for (auto& srcRect : rects)
360 {
361 if (!drawRect(surface, offset, srcRect))
362 return false;
363 }
364 return true;
365}
366
367static SDL_Rect scaledDstRect(const SDL_FPoint& scale, const SDL_Rect& srcRect)
368{
369 SDL_Rect dstRect = {};
370 float ix = 0.0f;
371 float iy = 0.0f;
372 const auto modx = std::modf(static_cast<float>(srcRect.x) * scale.x, &ix);
373 const auto mody = std::modf(static_cast<float>(srcRect.y) * scale.y, &iy);
374 auto sw = std::ceil(static_cast<float>(srcRect.w) * scale.x) + std::ceil(modx);
375 auto sh = std::ceil(static_cast<float>(srcRect.h) * scale.y) + std::ceil(mody);
376 dstRect.x = static_cast<Sint32>(ix);
377 dstRect.w = static_cast<Sint32>(sw);
378 dstRect.y = static_cast<Sint32>(iy);
379 dstRect.h = static_cast<Sint32>(sh);
380 return dstRect;
381}
382
383bool SdlWindow::drawScaledRect(SDL_Surface* surface, const SDL_FPoint& scale,
384 const SDL_Rect& srcRect)
385{
386 auto dstRect = scaledDstRect(scale, srcRect);
387 return blit(surface, srcRect, dstRect);
388}
389
390bool SdlWindow::drawScaledRects(SDL_Surface* surface, const SDL_FPoint& scale,
391 const std::vector<SDL_Rect>& rects)
392{
393 if (rects.empty())
394 {
395 return drawScaledRect(surface, scale, { 0, 0, surface->w, surface->h });
396 }
397
398 /* Upload every dirty rect before drawing any of them: scaling filters linearly, so the
399 * edge of each drawn rect also samples the texels just outside it. Drawn one by one,
400 * those can be a neighbouring dirty rect that is not uploaded yet, and the old picture
401 * stays behind as a faint line along the edge until that area changes again. */
402 for (const auto& srcRect : rects)
403 {
404 if (!upload(surface, srcRect))
405 return false;
406 }
407 for (const auto& srcRect : rects)
408 {
409 if (!render(srcRect, scaledDstRect(scale, srcRect)))
410 return false;
411 }
412 return true;
413}
414
415bool SdlWindow::fill(Uint8 r, Uint8 g, Uint8 b, Uint8 a)
416{
417 if (_renderer)
418 {
419 ensureRenderTarget();
420 if (!SDL_SetRenderTarget(_renderer, _renderTarget))
421 return false;
422 if (!SDL_SetRenderDrawColor(_renderer, r, g, b, a))
423 return false;
424 return SDL_RenderClear(_renderer);
425 }
426 return fill(_window, r, g, b, a);
427}
428
429bool SdlWindow::fill(SDL_Window* window, Uint8 r, Uint8 g, Uint8 b, Uint8 a)
430{
431 auto surface = SDL_GetWindowSurface(window);
432 if (!surface)
433 return false;
434 SDL_Rect rect = { 0, 0, surface->w, surface->h };
435 auto color = SDL_MapSurfaceRGBA(surface, r, g, b, a);
436
437 return SDL_FillSurfaceRect(surface, &rect, color);
438}
439
440static rdpMonitor makeMonitor(SDL_DisplayID id, const SDL_Rect& r, float factor,
441 bool forceAsPrimary)
442{
443 const float dpi = std::roundf(factor * 100.0f);
444
445 /* A compositor without an output can report a display of 0x0 (Xwayland in a headless
446 * mutter), the caller skips such a display. */
447 if ((r.w <= 0) || (r.h <= 0))
448 {
449 SDL_LogWarn(SDL_LOG_CATEGORY_VIDEO, "display %" PRIu32 ": invalid size %dx%d", id, r.w,
450 r.h);
451 return {};
452 }
453
454 const auto primary = SDL_GetPrimaryDisplay();
455 const auto orientation = SDL_GetCurrentDisplayOrientation(id);
456 const auto rdp_orientation = sdl::utils::orientaion_to_rdp(orientation);
457
458 rdpMonitor monitor{};
459 monitor.orig_screen = id;
460 monitor.x = r.x;
461 monitor.y = r.y;
462 monitor.width = r.w;
463 monitor.height = r.h;
464 monitor.is_primary = forceAsPrimary || (id == primary);
465 monitor.attributes.desktopScaleFactor = static_cast<UINT32>(dpi);
466 monitor.attributes.deviceScaleFactor = 100;
467 monitor.attributes.orientation = rdp_orientation;
468 /* The physical size is in millimetres and ignored outside 10 to 10000 ([MS-RDPBCGR]
469 * 2.2.1.3.9.1, [MS-RDPEDISP] 2.2.2.2.1). SDL3 does not know a display's physical size, so
470 * leave it at 0 (not given) instead of sending the size in pixels as millimetres. */
471 monitor.attributes.physicalWidth = 0;
472 monitor.attributes.physicalHeight = 0;
473
474 const auto cat = SDL_LOG_CATEGORY_APPLICATION;
475 SDL_LogDebug(cat, "monitor.orig_screen %" PRIu32, monitor.orig_screen);
476 SDL_LogDebug(cat, "monitor.x %" PRId32, monitor.x);
477 SDL_LogDebug(cat, "monitor.y %" PRId32, monitor.y);
478 SDL_LogDebug(cat, "monitor.width %" PRId32, monitor.width);
479 SDL_LogDebug(cat, "monitor.height %" PRId32, monitor.height);
480 SDL_LogDebug(cat, "monitor.is_primary %" PRIu32, monitor.is_primary);
481 SDL_LogDebug(cat, "monitor.attributes.desktopScaleFactor %" PRIu32,
482 monitor.attributes.desktopScaleFactor);
483 SDL_LogDebug(cat, "monitor.attributes.deviceScaleFactor %" PRIu32,
484 monitor.attributes.deviceScaleFactor);
485 SDL_LogDebug(cat, "monitor.attributes.orientation %s",
486 freerdp_desktop_rotation_flags_to_string(monitor.attributes.orientation));
487 SDL_LogDebug(cat, "monitor.attributes.physicalWidth %" PRIu32,
488 monitor.attributes.physicalWidth);
489 SDL_LogDebug(cat, "monitor.attributes.physicalHeight %" PRIu32,
490 monitor.attributes.physicalHeight);
491 return monitor;
492}
493
494rdpMonitor SdlWindow::query(SDL_Window* window, SDL_DisplayID id, bool forceAsPrimary)
495{
496 if (!window)
497 return {};
498 return makeMonitor(id, rect(window, forceAsPrimary), SDL_GetWindowDisplayScale(window),
499 forceAsPrimary);
500}
501
502/* Dummy windows report wrong sizes on Wayland and X11, use the display. */
503static rdpMonitor queryDisplay(SDL_DisplayID id, bool forceAsPrimary)
504{
505 SDL_Rect r = {};
506 const SDL_DisplayMode* mode = SDL_GetDesktopDisplayMode(id);
507 if (!mode || !SDL_GetDisplayBounds(id, &r))
508 {
509 SDL_LogWarn(SDL_LOG_CATEGORY_VIDEO, "display %" PRIu32 ": %s", id, SDL_GetError());
510 return {};
511 }
512 if (forceAsPrimary)
513 {
514 r.x = 0;
515 r.y = 0;
516 }
517 r.w = static_cast<int>(std::roundf(static_cast<float>(r.w) * mode->pixel_density));
518 r.h = static_cast<int>(std::roundf(static_cast<float>(r.h) * mode->pixel_density));
519 return makeMonitor(id, r, mode->pixel_density * SDL_GetDisplayContentScale(id), forceAsPrimary);
520}
521
522SDL_Rect SdlWindow::rect(SDL_Window* window, bool forceAsPrimary)
523{
524 SDL_Rect rect = {};
525 if (!window)
526 return {};
527
528 if (!forceAsPrimary)
529 {
530 if (!SDL_GetWindowPosition(window, &rect.x, &rect.y))
531 return {};
532 }
533
534 if (!SDL_GetWindowSizeInPixels(window, &rect.w, &rect.h))
535 return {};
536
537 const bool placeholder = (rect.w < 200) || (rect.h < 200);
538 if (placeholder && tryFallback(true))
539 {
540 /* On wlroots compositors (Sway, river, etc.), windows that are hidden/unmapped
541 * don't get their actual display dimensions. The dummy window returns its creation size
542 * (64x64) instead of the display size. This causes validation errors since we require >=
543 * 200px. Workaround: If we got dimensions that are too small, query the display directly.
544 */
545
546 const auto displayID = SDL_GetDisplayForWindow(window);
547 SDL_Rect displayBounds = {};
548 if (SDL_GetDisplayBounds(displayID, &displayBounds))
549 {
550 if (forceAsPrimary)
551 {
552 rect.x = 0;
553 rect.y = 0;
554 }
555 else
556 {
557 /* The dummy window is centered on the display by the compositor, so its
558 * position is not the display origin. Use the display bounds as for w/h. */
559 rect.x = displayBounds.x;
560 rect.y = displayBounds.y;
561 }
562 rect.w = displayBounds.w;
563 rect.h = displayBounds.h;
564
565 float factor = 1.0f;
566 const auto mode = SDL_GetCurrentDisplayMode(displayID);
567 if (mode && (mode->pixel_density > 1.0f))
568 factor = mode->pixel_density;
569 else
570 {
571 const float contentScale = SDL_GetDisplayContentScale(displayID);
572 if (contentScale > 1.0f)
573 factor = contentScale;
574 }
575 if (factor > 1.0f)
576 {
577 const auto fw = static_cast<float>(rect.w);
578 const auto fh = static_cast<float>(rect.h);
579 rect.w = static_cast<int>(std::roundf(fw * factor));
580 rect.h = static_cast<int>(std::roundf(fh * factor));
581 }
582 }
583 }
584
585 return rect;
586}
587
588SdlWindow::HighDPIMode SdlWindow::isHighDPIWindowsMode(SDL_Window* window)
589{
590 if (!window)
591 return MODE_INVALID;
592
593 const auto id = SDL_GetDisplayForWindow(window);
594 if (id == 0)
595 return MODE_INVALID;
596
597 const auto cs = SDL_GetDisplayContentScale(id);
598 const auto ds = SDL_GetWindowDisplayScale(window);
599 const auto pd = SDL_GetWindowPixelDensity(window);
600
601 /* mac os x style, but no HighDPI display */
602 if ((cs == 1.0f) && (ds == 1.0f) && (pd == 1.0f))
603 return MODE_NONE;
604
605 /* mac os x style HighDPI */
606 if ((cs == 1.0f) && (ds > 1.0f) && (pd > 1.0f))
607 return MODE_MACOS;
608
609 /* rest is windows style */
610 return MODE_WINDOWS;
611}
612
613/* Lazily create or recreate the persistent streaming GDI texture to match `surface`. */
614bool SdlWindow::ensureGdiTexture(SDL_Surface* surface)
615{
616 if (_gdiTexture && (_gdiTextureW == surface->w) && (_gdiTextureH == surface->h))
617 return true;
618 if (_gdiTexture)
619 SDL_DestroyTexture(_gdiTexture);
620 _gdiTexture = SDL_CreateTexture(_renderer, surface->format, SDL_TEXTUREACCESS_STREAMING,
621 surface->w, surface->h);
622 if (!_gdiTexture)
623 {
624 SDL_LogError(SDL_LOG_CATEGORY_RENDER, "SDL_CreateTexture: %s", SDL_GetError());
625 return false;
626 }
627 std::ignore = SDL_SetTextureBlendMode(_gdiTexture, SDL_BLENDMODE_NONE);
628 _gdiTextureW = surface->w;
629 _gdiTextureH = surface->h;
630 return true;
631}
632
633bool SdlWindow::blit(SDL_Surface* surface, const SDL_Rect& srcRect, SDL_Rect& dstRect)
634{
635 return upload(surface, srcRect) && render(srcRect, dstRect);
636}
637
638bool SdlWindow::upload(SDL_Surface* surface, const SDL_Rect& srcRect)
639{
640 if (!_renderer || !surface)
641 return false;
642
643 ensureRenderTarget();
644
645 if (!ensureGdiTexture(surface))
646 return false;
647
648 /* Upload only the dirty region */
649 const auto* details = SDL_GetPixelFormatDetails(surface->format);
650 const int bpp = details ? details->bytes_per_pixel : 4;
651 const auto* pixels = static_cast<const uint8_t*>(surface->pixels) +
652 (1ll * srcRect.y * surface->pitch) + (1ll * srcRect.x * bpp);
653 if (!SDL_UpdateTexture(_gdiTexture, &srcRect, pixels, surface->pitch))
654 {
655 SDL_LogError(SDL_LOG_CATEGORY_RENDER, "SDL_UpdateTexture: %s", SDL_GetError());
656 return false;
657 }
658 return true;
659}
660
661bool SdlWindow::render(const SDL_Rect& srcRect, const SDL_Rect& dstRect)
662{
663 if (!_renderer || !_gdiTexture)
664 return false;
665
666 /* Render onto persistent render target to accumulate dirty rects */
667 if (!SDL_SetRenderTarget(_renderer, _renderTarget))
668 return false;
669
670 SDL_FRect fsrc = { static_cast<float>(srcRect.x), static_cast<float>(srcRect.y),
671 static_cast<float>(srcRect.w), static_cast<float>(srcRect.h) };
672 SDL_FRect fdst = { static_cast<float>(dstRect.x), static_cast<float>(dstRect.y),
673 static_cast<float>(dstRect.w), static_cast<float>(dstRect.h) };
674 if (!SDL_RenderTexture(_renderer, _gdiTexture, &fsrc, &fdst))
675 {
676 SDL_LogError(SDL_LOG_CATEGORY_RENDER, "SDL_RenderTexture: %s", SDL_GetError());
677 return false;
678 }
679 return true;
680}
681
682void SdlWindow::updateSurface(const SdlOverlay* overlay)
683{
684 if (!_renderer)
685 return;
686
687 ensureRenderTarget();
688
689 /* Copy accumulated render target to screen and present */
690 if (!SDL_SetRenderTarget(_renderer, nullptr))
691 return;
692 if (!SDL_RenderTexture(_renderer, _renderTarget, nullptr, nullptr))
693 return;
694 drawVideoOverlays();
695 /* over the picture, never into it */
696 if (overlay && overlay->visible())
697 drawOverlay(*overlay);
698 if (!SDL_RenderPresent(_renderer))
699 return;
700}
701
702void SdlWindow::drawVideoOverlays()
703{
704 for (const auto& entry : _videoOverlays)
705 {
706 const auto& o = entry.second;
707 if (!o.visible || !o.texture || (o.dst.w <= 0) || (o.dst.h <= 0))
708 continue;
709 if (o.clip.empty())
710 {
711 std::ignore = SDL_RenderTexture(_renderer, o.texture, nullptr, &o.dst);
712 continue;
713 }
714 /* each visible part, with the part of the texture it shows */
715 const float sx = static_cast<float>(o.w) / o.dst.w;
716 const float sy = static_cast<float>(o.h) / o.dst.h;
717 for (const auto& c : o.clip)
718 {
719 SDL_FRect part{};
720 if (!SDL_GetRectIntersectionFloat(&c, &o.dst, &part))
721 continue;
722 const SDL_FRect src{ (part.x - o.dst.x) * sx, (part.y - o.dst.y) * sy, part.w * sx,
723 part.h * sy };
724 std::ignore = SDL_RenderTexture(_renderer, o.texture, &src, &part);
725 }
726 }
727}
728
729bool SdlWindow::setVideoOverlay(Uint64 id, const void* pixels, int pitch, int w, int h,
730 const SDL_FRect& dst, const std::vector<SDL_FRect>& clip,
731 bool visible)
732{
733 if (!_renderer || (w <= 0) || (h <= 0))
734 return false;
735 auto& o = _videoOverlays[id];
736 if (!o.texture || (o.w != w) || (o.h != h))
737 {
738 if (o.texture)
739 SDL_DestroyTexture(o.texture);
740 o.texture =
741 SDL_CreateTexture(_renderer, SDL_PIXELFORMAT_BGRA32, SDL_TEXTUREACCESS_STREAMING, w, h);
742 if (!o.texture)
743 {
744 SDL_LogError(SDL_LOG_CATEGORY_RENDER, "SDL_CreateTexture: %s", SDL_GetError());
745 _videoOverlays.erase(id);
746 return false;
747 }
748 /* the video is opaque: its alpha is not for us to blend */
749 std::ignore = SDL_SetTextureBlendMode(o.texture, SDL_BLENDMODE_NONE);
750 o.w = w;
751 o.h = h;
752 }
753 if (pixels && !SDL_UpdateTexture(o.texture, nullptr, pixels, pitch))
754 {
755 SDL_LogError(SDL_LOG_CATEGORY_RENDER, "SDL_UpdateTexture: %s", SDL_GetError());
756 return false;
757 }
758 o.dst = dst;
759 o.clip = clip;
760 o.visible = visible;
761 return true;
762}
763
764void SdlWindow::pruneVideoOverlays(const std::function<bool(Uint64)>& keep)
765{
766 for (auto it = _videoOverlays.begin(); it != _videoOverlays.end();)
767 {
768 if (keep(it->first))
769 ++it;
770 else
771 {
772 SDL_DestroyTexture(it->second.texture);
773 it = _videoOverlays.erase(it);
774 }
775 }
776}
777
778const char* SdlWindow::rendererName() const
779{
780 return _renderer ? SDL_GetRendererName(_renderer) : nullptr;
781}
782
783void SdlWindow::drawOverlay(const SdlOverlay& overlay)
784{
785 if (!_overlayPainter)
786 _overlayPainter = std::make_unique<SdlOverlayPainter>(_renderer);
787
788 int w = 0;
789 int h = 0;
790 if (!SDL_GetCurrentRenderOutputSize(_renderer, &w, &h))
791 return;
792 _overlayPainter->draw(overlay, w, h, SDL_GetWindowDisplayScale(_window));
793}
794
795bool SdlWindow::paintResizeFrame(SDL_Surface* surface, SDL_Point off, bool contentChanged,
796 const SDL_Rect& inset, bool fillRevealed, bool dashedBorder)
797{
798 if (!_renderer || !surface)
799 return false;
800 ensureRenderTarget();
801
802 const int prevW = _gdiTextureW;
803 const int prevH = _gdiTextureH;
804 if (!ensureGdiTexture(surface))
805 return false;
806 /* A recreated texture is empty, so upload even when the content did not change. */
807 const bool recreated = (_gdiTextureW != prevW) || (_gdiTextureH != prevH);
808 if ((contentChanged || recreated) &&
809 !SDL_UpdateTexture(_gdiTexture, nullptr, surface->pixels, surface->pitch))
810 return false;
811
812 if (!SDL_SetRenderTarget(_renderer, _renderTarget))
813 return false;
814
815 int ww = 0;
816 int wh = 0;
817 SDL_GetWindowSizeInPixels(_window, &ww, &wh);
818 /* The visible frame; the ring outside it (the resize band) stays fully transparent. */
819 const SDL_FRect frame = { static_cast<float>(inset.x), static_cast<float>(inset.y),
820 static_cast<float>(ww - inset.x - inset.w),
821 static_cast<float>(wh - inset.y - inset.h) };
822
823 /* Translucent fill in revealed area awaiting server frame. */
824 constexpr Uint8 kFillAlpha = 0x80;
825 std::ignore = SDL_SetRenderDrawBlendMode(_renderer, SDL_BLENDMODE_NONE);
826 std::ignore = SDL_SetRenderDrawColor(_renderer, 0, 0, 0, 0);
827 std::ignore = SDL_RenderClear(_renderer);
828 if (fillRevealed)
829 {
830 std::ignore = SDL_SetRenderDrawColor(_renderer, 0x2B, 0x2B, 0x2B, kFillAlpha);
831 std::ignore = SDL_RenderFillRect(_renderer, &frame);
832 }
833 SDL_FRect fdst = { static_cast<float>(off.x), static_cast<float>(off.y),
834 static_cast<float>(surface->w), static_cast<float>(surface->h) };
835 /* Anchored frame clipped to visible bounds. */
836 const SDL_Rect clip = { inset.x, inset.y, ww - inset.x - inset.w, wh - inset.y - inset.h };
837 std::ignore = SDL_SetRenderClipRect(_renderer, &clip);
838 std::ignore = SDL_RenderTexture(_renderer, _gdiTexture, nullptr, &fdst);
839 std::ignore = SDL_SetRenderClipRect(_renderer, nullptr);
840
841 /* Dashed border indicating pending resize target. */
842 if (dashedBorder)
843 {
844 std::ignore = SDL_SetRenderDrawColor(_renderer, 0xC8, 0xC8, 0xC8, 0xFF);
845 const float dash = 8.0F;
846 const float gap = 5.0F;
847 const float fx2 = frame.x + frame.w;
848 const float fy2 = frame.y + frame.h;
849 const float lo = frame.y + 0.5F;
850 const float by = fy2 - 0.5F;
851 const float lx = frame.x + 0.5F;
852 const float rx = fx2 - 0.5F;
853 const float step = dash + gap;
854 const auto steps = [step](float len)
855 { return (len <= 0.0F) ? 0 : static_cast<int>(std::ceil(len / step)); };
856 for (int i = 0; i < steps(fx2 - frame.x); i++)
857 {
858 const float x = frame.x + (static_cast<float>(i) * step);
859 const float x2 = (x + dash < fx2) ? (x + dash) : rx;
860 std::ignore = SDL_RenderLine(_renderer, x, lo, x2, lo);
861 std::ignore = SDL_RenderLine(_renderer, x, by, x2, by);
862 }
863 for (int i = 0; i < steps(fy2 - frame.y); i++)
864 {
865 const float y = frame.y + (static_cast<float>(i) * step);
866 const float y2 = (y + dash < fy2) ? (y + dash) : by;
867 std::ignore = SDL_RenderLine(_renderer, lx, y, lx, y2);
868 std::ignore = SDL_RenderLine(_renderer, rx, y, rx, y2);
869 }
870 }
871
872 if (!SDL_SetRenderTarget(_renderer, nullptr))
873 return false;
874 std::ignore = SDL_RenderTexture(_renderer, _renderTarget, nullptr, nullptr);
875 drawVideoOverlays();
876 std::ignore = SDL_RenderPresent(_renderer);
877 return true;
878}
879
880SdlWindow SdlWindow::create(SDL_DisplayID id, const std::string& title, Uint32 flags, Uint32 width,
881 Uint32 height)
882{
883 flags |= SDL_WINDOW_HIGH_PIXEL_DENSITY;
884
885 SDL_Rect rect = { static_cast<int>(SDL_WINDOWPOS_CENTERED_DISPLAY(id)),
886 static_cast<int>(SDL_WINDOWPOS_CENTERED_DISPLAY(id)), static_cast<int>(width),
887 static_cast<int>(height) };
888
889 if ((flags & SDL_WINDOW_FULLSCREEN) != 0)
890 {
891 std::ignore = SDL_GetDisplayBounds(id, &rect);
892 }
893
894 SdlWindow window{ id, title, rect, flags };
895
896 if ((flags & SDL_WINDOW_FULLSCREEN) != 0)
897 {
898 window.setOffsetX(rect.x);
899 window.setOffsetY(rect.y);
900 }
901
902 return window;
903}
904
905SdlWindow SdlWindow::create(SDL_DisplayID id, const std::string& title, Uint32 flags,
906 const SDL_Rect& rect)
907{
908 return SdlWindow{ id, title, rect, flags };
909}
910
911/* Popup constructor: positioned relative to the parent origin. */
912SdlWindow::SdlWindow(SDL_Window* parent, const SDL_Rect& rect, bool transparent, bool tooltip)
913 : _initialW(rect.w), _initialH(rect.h)
914{
915 auto props = SDL_CreateProperties();
916 SDL_SetPointerProperty(props, SDL_PROP_WINDOW_CREATE_PARENT_POINTER, parent);
917 SDL_SetBooleanProperty(props,
918 tooltip ? SDL_PROP_WINDOW_CREATE_TOOLTIP_BOOLEAN
919 : SDL_PROP_WINDOW_CREATE_MENU_BOOLEAN,
920 true);
921 SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_FOCUSABLE_BOOLEAN, false);
922#if defined(SDL_PROP_WINDOW_CREATE_CONSTRAIN_POPUP_BOOLEAN)
923 /* The server places RemoteApp popups; a moved one would map clicks to other points. */
924 SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_CONSTRAIN_POPUP_BOOLEAN, false);
925#endif
926 SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_BORDERLESS_BOOLEAN, true);
927 /* Transparent so menus' genuine per-pixel alpha (corners/shadow) isn't rendered black. */
928 if (transparent)
929 SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_TRANSPARENT_BOOLEAN, true);
930 SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_X_NUMBER, rect.x);
931 SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_Y_NUMBER, rect.y);
932 SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, rect.w);
933 SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, rect.h);
934 /* Hidden until first paint, like the app constructor. */
935 SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_HIDDEN_BOOLEAN, true);
936
937 auto isHighDpi = true;
938 if (parent)
939 {
940 auto flags = SDL_GetWindowFlags(parent);
941 if ((flags & SDL_WINDOW_HIGH_PIXEL_DENSITY) != 0)
942 isHighDpi = true;
943 }
944
945 SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN, isHighDpi);
946
947 _window = SDL_CreateWindowWithProperties(props);
948 SDL_DestroyProperties(props);
949 if (_window)
950 {
951 std::ignore = SDL_SyncWindow(_window);
952 _renderer = SDL_CreateRenderer(_window, nullptr);
953 _displayID = SDL_GetDisplayForWindow(_window);
954 }
955}
956
957SdlWindow SdlWindow::createPopup(SDL_Window* parent, const SDL_Rect& rect, bool transparent,
958 bool tooltip)
959{
960 return SdlWindow{ parent, rect, transparent, tooltip };
961}
962
963static SDL_Window* createDummy(SDL_DisplayID id)
964{
965 const auto x = SDL_WINDOWPOS_CENTERED_DISPLAY(id);
966 const auto y = SDL_WINDOWPOS_CENTERED_DISPLAY(id);
967 const int w = 64;
968 const int h = 64;
969
970 auto props = SDL_CreateProperties();
971 std::stringstream ss;
972 ss << "SdlWindow::query(" << id << ")";
973 SDL_SetStringProperty(props, SDL_PROP_WINDOW_CREATE_TITLE_STRING, ss.str().c_str());
974 SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_X_NUMBER, x);
975 SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_Y_NUMBER, y);
976 SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_WIDTH_NUMBER, w);
977 SDL_SetNumberProperty(props, SDL_PROP_WINDOW_CREATE_HEIGHT_NUMBER, h);
978
979 SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_HIGH_PIXEL_DENSITY_BOOLEAN, true);
980 SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_FULLSCREEN_BOOLEAN, false);
981 SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_BORDERLESS_BOOLEAN, true);
982 SDL_SetBooleanProperty(props, SDL_PROP_WINDOW_CREATE_HIDDEN_BOOLEAN, false);
983
984 auto window = SDL_CreateWindowWithProperties(props);
985 SDL_DestroyProperties(props);
986
987 /* Workaround: we need to properly position the window on the correct monitor
988 * before going fullscreen. Otherwise we will get the primary monitor details.
989 */
990 if (window)
991 {
992 SDL_Rect rect = {};
993 std::ignore = SDL_GetDisplayBounds(id, &rect);
994 std::ignore = SDL_SetWindowPosition(window, rect.x, rect.y);
995 std::ignore = SDL_SetWindowFullscreen(window, true);
996 }
997 return window;
998}
999
1000rdpMonitor SdlWindow::query(SDL_DisplayID id, bool forceAsPrimary)
1001{
1002 if (sdl::utils::isWaylandDriver() || sdl::utils::isX11Driver())
1003 return queryDisplay(id, forceAsPrimary);
1004
1005 std::unique_ptr<SDL_Window, void (*)(SDL_Window*)> window(createDummy(id), SDL_DestroyWindow);
1006 if (!window)
1007 return {};
1008
1009 std::unique_ptr<SDL_Renderer, void (*)(SDL_Renderer*)> renderer(
1010 SDL_CreateRenderer(window.get(), nullptr), SDL_DestroyRenderer);
1011
1012 if (!SDL_SyncWindow(window.get()))
1013 return {};
1014
1015 SDL_Event event{};
1016 while (SDL_PollEvent(&event))
1017 ;
1018
1019 return query(window.get(), id, forceAsPrimary);
1020}
1021
1022SDL_Rect SdlWindow::rect(SDL_DisplayID id, bool forceAsPrimary)
1023{
1024 std::unique_ptr<SDL_Window, void (*)(SDL_Window*)> window(createDummy(id), SDL_DestroyWindow);
1025 if (!window)
1026 return {};
1027
1028 std::unique_ptr<SDL_Renderer, void (*)(SDL_Renderer*)> renderer(
1029 SDL_CreateRenderer(window.get(), nullptr), SDL_DestroyRenderer);
1030
1031 if (!SDL_SyncWindow(window.get()))
1032 return {};
1033
1034 SDL_Event event{};
1035 while (SDL_PollEvent(&event))
1036 ;
1037
1038 return rect(window.get(), forceAsPrimary);
1039}
1040
1041bool SdlWindow::tryFallback(bool isFullscreen)
1042{
1043 /* If we define a custom env variable to use the wlroots hack
1044 * then enable/disable according to this setting only.
1045 */
1046 const auto wlroots_hack = SDL_getenv("FREERDP_WLROOTS_HACK");
1047 if (wlroots_hack != nullptr)
1048 {
1049 const auto enabled = strcmp(wlroots_hack, "0") != 0;
1050 if (strcmp(wlroots_hack, "force") == 0)
1051 isFullscreen = true;
1052 return enabled && isFullscreen;
1053 }
1054
1055 const auto platform = SDL_GetPlatform();
1056 if ((platform == nullptr) || (strcmp(platform, "Linux") != 0))
1057 return false;
1058
1059 const auto driver = SDL_GetCurrentVideoDriver();
1060 if ((driver == nullptr) || (strcmp(driver, "wayland") != 0))
1061 return false;
1062
1063 /* Check XDG_SESSION_DESKTOP and XDG_CURRENT_DESKTOP for wlroots-based
1064 * compositors. The original check only matched Sway, but other wlroots
1065 * compositors (Hyprland, river, etc.) have the same dummy-window sizing
1066 * behavior where hidden/unmapped windows return 64x64 instead of the
1067 * display size. Use strstr for substring matching since XDG_CURRENT_DESKTOP
1068 * can be a colon-separated list (e.g. "sway:wlroots", "Hyprland").
1069 */
1070 auto isWlrootsCompositor = [](const char* value) -> bool
1071 {
1072 if (!value)
1073 return false;
1074 if (strstr(value, "sway") || strstr(value, "Sway") || strstr(value, "Hyprland") ||
1075 strstr(value, "hyprland") || strstr(value, "river") || strstr(value, "wlroots"))
1076 return true;
1077 return false;
1078 };
1079
1080 const auto xdg_session = SDL_getenv("XDG_SESSION_DESKTOP");
1081 if (isWlrootsCompositor(xdg_session))
1082 return isFullscreen;
1083
1084 const auto xdg_desktop = SDL_getenv("XDG_CURRENT_DESKTOP");
1085 if (isWlrootsCompositor(xdg_desktop))
1086 return isFullscreen;
1087
1088 return false;
1089}
void pruneVideoOverlays(const std::function< bool(Uint64)> &keep)
drops the overlays keep returns false for
bool setVideoOverlay(Uint64 id, const void *pixels, int pitch, int w, int h, const SDL_FRect &dst, const std::vector< SDL_FRect > &clip, bool visible)
redirected video id, drawn over the session at each present at dst (render coordinates),...
SdlWindow(const std::string &title, Sint32 startupX, Sint32 startupY, Sint32 width, Sint32 height, Uint32 flags)