FreeRDP
Loading...
Searching...
No Matches
sdl_rail.cpp
1
19#include <algorithm>
20#include <tuple>
21#include <utility>
22#include <vector>
23
24#include <winpr/assert.h>
25#include <winpr/platform.h>
26#include <winpr/cast.h>
27#include <winpr/string.h>
28
29#include <freerdp/freerdp.h>
30#include <freerdp/log.h>
31#include <freerdp/codec/color.h>
32#include <freerdp/codec/region.h>
33#include <freerdp/client/rail.h>
34#include <freerdp/timer.h>
35
36#include "sdl_rail.hpp"
37#include "sdl_context.hpp"
38#include "sdl_rail_platform.hpp"
39#include "sdl_types.hpp"
40#include "sdl_utils.hpp"
41
42#define TAG CLIENT_TAG("sdl.rail")
43
44/* The compositor runs the drag (Wayland); the client only tracks the size. */
45[[nodiscard]] static bool compositorDrag()
46{
47 return railPlatformCaps().drag == RailDragModel::CompositorResize;
48}
49
50SdlRail::SdlRail(SdlContext* context) : _context(context)
51{
52}
53
54SdlRail::~SdlRail()
55{
56 railPlatformSetNativeLoopHandler({});
57}
58
59SdlRail* SdlRail::get(rdpContext* context)
60{
61 auto sdl = get_context(context);
62 if (!sdl)
63 return nullptr;
64 return &sdl->getRailChannelContext();
65}
66
67bool SdlRail::windowGeometry(uint64_t id, SDL_Window*& window, int& width, int& height)
68{
69 std::scoped_lock lock(_windowsLock);
70 auto w = getWindow(id);
71 if (!w || w->isDeleted() || !w->window())
72 return false;
73 const SDL_Rect r = w->windowRect();
74 window = w->window();
75 width = r.w;
76 height = r.h;
77 return true;
78}
79
80SdlRailWindow* SdlRail::getWindow(uint64_t id)
81{
82 auto it = _windows.find(id);
83 return (it == _windows.end()) ? nullptr : &it->second;
84}
85
86SdlRailWindow* SdlRail::getWindowBySdlId(SDL_WindowID id)
87{
88 if (id == 0)
89 return nullptr;
90 for (auto& it : _windows)
91 {
92 if (it.second.sdlId() == id)
93 return &it.second;
94 }
95 return nullptr;
96}
97
98/* Test if popup adjoins window edge from outside. */
99static bool adjoinsOutside(const SDL_Rect& popup, const SDL_Rect& win)
100{
101 SDL_Rect hit{};
102 if (SDL_GetRectIntersection(&popup, &win, &hit))
103 return false;
104 const SDL_Rect grown = { win.x - 1, win.y - 1, win.w + 2, win.h + 2 };
105 return SDL_GetRectIntersection(&popup, &grown, &hit);
106}
107
108/* Fullscreen popups (e.g. slide shows) act as toplevels and can parent popups. */
109static bool canParentPopup(const SdlRailWindow& w)
110{
111 return (!w.isPopup() || w.isFullscreen()) && (w.window() != nullptr);
112}
113
114/* Test if the SDL window of w is the one of ancestor or one of its SDL descendants. */
115[[nodiscard]]
116static bool descendsFrom(const SdlRailWindow& w, const SdlRailWindow& ancestor)
117{
118 for (SDL_Window* p = w.window(); p; p = SDL_GetWindowParent(p))
119 {
120 if (p == ancestor.window())
121 return true;
122 }
123 return false;
124}
125
126SdlRailWindow* SdlRail::resolveParent(uint64_t ownerId)
127{
128 auto* owner = getWindow(ownerId);
129 if (owner && canParentPopup(*owner))
130 return owner;
131 return nullptr;
132}
133
134/* Pick a popup's parent app window: ownerWindowId -> geometric containment -> focused -> any app.
135 */
136SdlRailWindow* SdlRail::resolvePopupParent(const SdlRailWindow& popup)
137{
138 SdlRailWindow* chosen = resolveParent(popup.owner());
139 if (!chosen)
140 {
141 const SDL_Rect pr = popup.windowRect();
142 const SDL_Point origin = { pr.x, pr.y };
143 for (uint32_t id : _zOrder)
144 {
145 auto* w = getWindow(id);
146 if (!w || !canParentPopup(*w))
147 continue;
148 const SDL_Rect wr = w->windowRect();
149 if (SDL_PointInRect(&origin, &wr))
150 {
151 chosen = w;
152 break;
153 }
154 }
155 if (!chosen)
156 {
157 for (auto& other : _windows)
158 {
159 auto& w = other.second;
160 if (!canParentPopup(w))
161 continue;
162 const SDL_Rect wr = w.windowRect();
163 if (SDL_PointInRect(&origin, &wr))
164 {
165 chosen = &w;
166 break;
167 }
168 }
169 }
170 }
171 if (!chosen)
172 chosen = resolveParent(_focusedAppId);
173 if (!chosen)
174 {
175 for (auto& other : _windows)
176 {
177 auto& w = other.second;
178 if (canParentPopup(w))
179 {
180 chosen = &w;
181 break;
182 }
183 }
184 }
185 return chosen;
186}
187
188/* Identify companion shadow frames adjoining owner window. */
189bool SdlRail::isShadowFrame(const SdlRailWindow& popup)
190{
191 if (!popup.isLayered())
192 return false;
193 const SDL_Rect pr = popup.windowRect();
194 for (auto& other : _windows)
195 {
196 auto& w = other.second;
197 if (canParentPopup(w) && adjoinsOutside(pr, w.windowRect()))
198 return true;
199 }
200 return false;
201}
202
203bool SdlRail::ownsWindow(SDL_WindowID id)
204{
205 std::unique_lock lock(_windowsLock);
206 return getWindowBySdlId(id) != nullptr;
207}
208
209void SdlRail::invalidateWindow(SDL_WindowID id)
210{
211 std::unique_lock lock(_windowsLock);
212 auto* appWindow = getWindowBySdlId(id);
213 if (!appWindow)
214 return;
215 appWindow->invalidateAll();
216
217 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
218}
219
220/* Caller holds _windowsLock. */
221void SdlRail::sendSystemCommand(SdlRailWindow* appWindow, uint16_t command)
222{
223 if (!_rail || !_rail->ClientSystemCommand)
224 return;
225 RAIL_SYSCOMMAND_ORDER syscommand = {};
226 syscommand.windowId = static_cast<UINT32>(appWindow->id());
227 syscommand.command = command;
228 std::ignore = _rail->ClientSystemCommand(_rail, &syscommand);
229}
230
231void SdlRail::sendWorkArea(const SDL_Rect& local)
232{
233 /* Convert local display coordinates to server coordinates (relative to primary monitor). */
234 const SDL_Rect area = { local.x - _displayShift.x, local.y - _displayShift.y, local.w,
235 local.h };
236 if (!_rail || !_rail->ClientSystemParam || (area.w <= 0) || (area.h <= 0))
237 return;
238 if ((area.x < 0) || (area.y < 0))
239 {
240 WLog_WARN(TAG, "work area %d,%d is outside the primary monitor, not sent", area.x, area.y);
241 return;
242 }
243 if (SDL_RectsEqual(&area, &_sentWorkArea))
244 return;
245
246 RAIL_SYSPARAM_ORDER param = {};
247 /* ClientSystemParam dispatches on the params mask, not .param. */
248 param.params = SPI_MASK_SET_WORK_AREA;
249 param.workArea.left = WINPR_ASSERTING_INT_CAST(UINT16, area.x);
250 param.workArea.top = WINPR_ASSERTING_INT_CAST(UINT16, area.y);
251 param.workArea.right = WINPR_ASSERTING_INT_CAST(UINT16, area.x + area.w);
252 param.workArea.bottom = WINPR_ASSERTING_INT_CAST(UINT16, area.y + area.h);
253 if (_rail->ClientSystemParam(_rail, &param) == CHANNEL_RC_OK)
254 _sentWorkArea = area;
255}
256
257void SdlRail::noteUsableBoundsChanged(SDL_DisplayID display)
258{
259 if (display != SDL_GetPrimaryDisplay())
260 return;
261 std::unique_lock lock(_windowsLock);
262 _sentWorkArea = {};
263 if (!sdl_push_user_event(SDL_EVENT_USER_UPDATE))
264 WLog_WARN(TAG, "sdl_push_user_event failed");
265}
266
267void SdlRail::handleMaximized(SDL_WindowID id)
268{
269 std::unique_lock lock(_windowsLock);
270 auto* appWindow = getWindowBySdlId(id);
271 if (!appWindow || appWindow->isPopup() || !appWindow->window())
272 return;
273 /* Skip echo of programmatic maximize, but trigger reconcile to update insets. */
274 if (appWindow->railMaximized())
275 {
276 WLog_DBG(TAG, "local maximize skipped id=0x%08" PRIx32 " (already rail-maximized)",
277 static_cast<UINT32>(appWindow->id()));
278
279 if (!sdl_push_user_event(SDL_EVENT_USER_UPDATE))
280 WLog_WARN(TAG, "sdl_push_user_event failed");
281 return;
282 }
283 /* Move first: the server maximizes on its window's monitor. */
284 followDisplay(appWindow, true);
285 appWindow->setRailMaximized(true);
286 /* Force full repaint (skips dirty-rect). */
287 appWindow->invalidateAll();
288 /* Defer SC_MAXIMIZE if modal move loop is still open. */
289 if (appWindow->loopEndPending())
290 {
291 appWindow->deferMaximize();
292 WLog_DBG(TAG, "local maximize deferred id=0x%08" PRIx32 " (modal loop open)",
293 static_cast<UINT32>(appWindow->id()));
294 }
295 else if (appWindow->deferMaximizeUntilEcho())
296 {
297 /* Right after a move, Windows can keep the restored size. */
298 WLog_DBG(TAG, "local maximize deferred id=0x%08" PRIx32 " (move not confirmed)",
299 static_cast<UINT32>(appWindow->id()));
300 }
301 else
302 {
303 WLog_DBG(TAG, "local maximize id=0x%08" PRIx32 " -> SC_MAXIMIZE",
304 static_cast<UINT32>(appWindow->id()));
305 sendSystemCommand(appWindow, SC_MAXIMIZE);
306 }
307
308 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
309}
310
311void SdlRail::handleMinimized(SDL_WindowID id)
312{
313 std::unique_lock lock(_windowsLock);
314 auto* appWindow = getWindowBySdlId(id);
315 if (!appWindow || appWindow->isPopup() || !appWindow->window())
316 return;
317 if (appWindow->railMinimized())
318 return; /* echo of reconcile's own SDL_MinimizeWindow */
319 appWindow->setRailMinimized(true);
320 WLog_DBG(TAG, "local minimize id=0x%08" PRIx32 " -> SC_MINIMIZE",
321 static_cast<UINT32>(appWindow->id()));
322 sendSystemCommand(appWindow, SC_MINIMIZE);
323}
324
325void SdlRail::handleClose(SDL_WindowID id)
326{
327 std::unique_lock lock(_windowsLock);
328 auto* appWindow = getWindowBySdlId(id);
329 if (!appWindow || !appWindow->window())
330 return;
331 WLog_DBG(TAG, "local close id=0x%08" PRIx32 " -> SC_CLOSE",
332 static_cast<UINT32>(appWindow->id()));
333 sendSystemCommand(appWindow, SC_CLOSE);
334}
335
336void SdlRail::handleRestored(SDL_WindowID id)
337{
338 std::unique_lock lock(_windowsLock);
339 auto* appWindow = getWindowBySdlId(id);
340 if (!appWindow || appWindow->isPopup() || !appWindow->window())
341 return;
342 /* Resolve restored state; trigger reconcile in case WM cleared flags asynchronously. */
343 if (appWindow->railMinimized())
344 {
345 appWindow->setRailMinimized(false);
346 appWindow->noteLocalRestore();
347 }
348 else if (appWindow->railMaximized())
349 appWindow->setRailMaximized(false);
350 else
351 {
352 if (!sdl_push_user_event(SDL_EVENT_USER_UPDATE))
353 WLog_WARN(TAG, "sdl_push_user_event failed");
354 return;
355 }
356 WLog_DBG(TAG, "local restore id=0x%08" PRIx32 " -> SC_RESTORE",
357 static_cast<UINT32>(appWindow->id()));
358 appWindow->invalidateAll();
359 sendSystemCommand(appWindow, SC_RESTORE);
360
361 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
362}
363
364void SdlRail::handleFocus(SDL_WindowID id, bool gained)
365{
366 std::unique_lock lock(_windowsLock);
367 auto appWindow = getWindowBySdlId(id);
368 if (!appWindow || !appWindow->activatable() || !appWindow->window())
369 return;
370
371 /* Ignore focus loss while dragging: mapping restore shadow frames can steal focus
372 * and cancel the server modal loop. */
373 if (!gained && (_localMove.id == static_cast<uint32_t>(appWindow->id())))
374 return;
375
376 /* Fallback parent for orphaned popups. */
377 if (gained)
378 _focusedAppId = appWindow->id();
379
380 /* Only report activation, never deactivation (see the X11 client, #13422).
381 * The server treats a deactivation of the owner as "no active window in
382 * this application" and closes popups/menus that have just been opened
383 * when the compositor moves focus to them. The activation that follows
384 * (or an explicit click, see ensureActive()) is enough to route input. */
385 if (!gained)
386 return;
387
388 /* A window owned by this one is currently active (e.g. a profile card or
389 * a transient dialog). On a real desktop the owner is only activated by a
390 * click; focus-follows-mouse compositors hand focus back on hover, which
391 * would make the server close the owned popup. Leave that to
392 * ensureActive() (explicit click). */
393 const auto* active = getWindow(_clientActiveId);
394 if (active && (active != appWindow) &&
395 (active->owner() == static_cast<uint32_t>(appWindow->id())))
396 return;
397
398 /* ClientActivate only. Do NOT SDL_RaiseWindow to avoid WM focus loops. */
399 const auto wid = static_cast<uint32_t>(appWindow->id());
400 sendClientActivate(wid, true);
401}
402
403/* Send RAIL_ACTIVATE_ORDER and track the active window id. Caller holds _windowsLock. */
404void SdlRail::sendClientActivate(uint32_t wid, bool enabled)
405{
406 if (!_rail || !_rail->ClientActivate)
407 return;
408 if (enabled)
409 _clientActiveId = wid;
410 RAIL_ACTIVATE_ORDER activate = {};
411 activate.windowId = wid;
412 activate.enabled = enabled;
413 std::ignore = _rail->ClientActivate(_rail, &activate);
414}
415
416/* Activate clicked window on server to route input correctly. */
417void SdlRail::ensureActive(SDL_WindowID id)
418{
419 std::unique_lock lock(_windowsLock);
420 auto* appWindow = getWindowBySdlId(id);
421 if (!appWindow || !appWindow->activatable() || !appWindow->window())
422 return;
423 const auto wid = static_cast<uint32_t>(appWindow->id());
424 if (wid == _clientActiveId)
425 return;
426 sendClientActivate(wid, true);
427}
428
429SDL_Point SdlRail::inputLayoutPosition(SdlRailWindow* appWindow)
430{
431 WINPR_ASSERT(appWindow);
432 /* Window-local to server-absolute, aligned with surface blit anchor. */
433 SDL_Point origin = appWindow->serverOrigin();
434 SDL_Point rel{};
435 if (appWindow->isPopup() && !railPlatformCaps().supportsWindowPositions &&
436 appWindow->placedRel(rel))
437 {
438 auto* sdlParent = SDL_GetWindowParent(appWindow->window());
439 if (auto* parent = sdlParent ? getWindowBySdlId(SDL_GetWindowID(sdlParent)) : nullptr)
440 {
441 const SDL_Rect pr = parent->outerRect();
442 origin = { pr.x + rel.x, pr.y + rel.y };
443 }
444 }
445 return origin;
446}
447
448void SdlRail::inputWindows(SDL_WindowID id, std::vector<SdlInputWindow>& windows,
449 std::optional<size_t>& source)
450{
451 std::unique_lock lock(_windowsLock);
452 for (auto& entry : _windows)
453 {
454 auto& appWindow = entry.second;
455 auto* window = appWindow.window();
456 if (!window)
457 continue;
458 const auto isSource = (SDL_GetWindowID(window) == id);
459 if (!isSource && ((SDL_GetWindowFlags(window) & SDL_WINDOW_HIDDEN) != 0))
460 continue;
461 /* Input is mapped with the server rect: the source window follows its display first. */
462 if (isSource && !appWindow.effectivelyMaximized())
463 followDisplay(&appWindow, true);
464
465 /* RemoteApp windows are drawn 1:1, without local scaling. */
466 auto input = SdlContext::inputWindowGeometry(window, appWindow.renderer());
467 input.layout = inputLayoutPosition(&appWindow);
468 if (isSource)
469 source = windows.size();
470 windows.push_back(input);
471 }
472}
473
474void SdlRail::notePopupMoved(SDL_WindowID id)
475{
476 /* X11 input already matches the server rect; only Wayland lags behind it. */
477 if (railPlatformCaps().supportsWindowPositions)
478 return;
479 std::unique_lock lock(_windowsLock);
480 auto* w = getWindowBySdlId(id);
481 if (!w || !w->isPopup())
482 return;
483 w->notePlaced();
484 /* Show the held frame now: that commit applies the move. */
485 if (!sdl_push_user_event(SDL_EVENT_USER_UPDATE))
486 WLog_WARN(TAG, "could not wake the paint loop for a moved popup");
487}
488
489SdlRailWindow* SdlRail::addWindow(uint64_t id, const SDL_Rect& rect)
490{
491 /* Move deleted entry aside so new window can reuse the ID. */
492 auto it = _windows.find(id);
493 if ((it != _windows.end()) && it->second.isDeleted())
494 {
495 WLog_DBG(TAG, "window recreate id=0x%08" PRIx32 " reused a deleted entry",
496 static_cast<uint32_t>(id));
497 _deadWindows.insert(_windows.extract(it));
498 }
499 /* emplace is a no-op if the id already exists; either way first->second is the window. */
500 auto res = _windows.emplace(std::piecewise_construct, std::forward_as_tuple(id),
501 std::forward_as_tuple(id, rect));
502 res.first->second.setLocalShift(_localShift);
503 return &res.first->second;
504}
505
506/* Caller holds _windowsLock or runs before any window exists. */
507void SdlRail::updateCoordinates()
508{
509 const auto* settings = _context->common()->context.settings;
510 _displayShift = { freerdp_settings_get_int32(settings, FreeRDP_MonitorLocalShiftX),
511 freerdp_settings_get_int32(settings, FreeRDP_MonitorLocalShiftY) };
512 _localShift = railPlatformCaps().supportsWindowPositions ? _displayShift : SDL_Point{ 0, 0 };
513 const auto origin = _context->inputOrigin();
514 WLog_DBG(TAG, "coordinates: display shift %d,%d window shift %d,%d input origin %d,%d",
515 _displayShift.x, _displayShift.y, _localShift.x, _localShift.y, origin.x, origin.y);
516}
517
518void SdlRail::enableRemoteAppMode(bool enable)
519{
520 _enabled = enable;
521 if (enable)
522 _desktopReleased = true;
523 queueScreenSaverUpdate();
524}
525
526/* Show the desktop anyway after this: not every logon prompt is announced. */
527static constexpr Uint32 kDesktopHoldMs = 10000;
528
529bool SdlRail::desktopMayShow()
530{
531 if (_desktopReleased)
532 return true;
533 const uint64_t now = SDL_GetTicks();
534 if (_desktopHoldUntil == 0)
535 {
536 _desktopHoldUntil = now + kDesktopHoldMs;
537 /* Frames may stop coming while the logon waits; wake up to re-check. */
538 if (!sdl_push_update_after(kDesktopHoldMs + 1))
539 WLog_WARN(TAG, "SDL_AddTimer failed: %s", SDL_GetError());
540 WLog_DBG(TAG, "RemoteApp starting: holding the logon desktop back");
541 return false;
542 }
543 if (now < _desktopHoldUntil)
544 return false;
545 WLog_DBG(TAG, "RemoteApp not started after %" PRIu32 " ms, showing the desktop",
546 kDesktopHoldMs);
547 _desktopReleased = true;
548 return true;
549}
550
551void SdlRail::noteLogonPrompt()
552{
553 if (_desktopReleased.exchange(true))
554 return;
555 WLog_DBG(TAG, "logon dialog on the server, showing the desktop");
556 if (!sdl_push_user_event(SDL_EVENT_USER_UPDATE))
557 WLog_WARN(TAG, "sdl_push_user_event failed");
558}
559
560/* Mainloop timer, so it runs on the RDP thread: a redirect or reconnect there frees the transport
561 * a PDU is sent with, the main thread must not send one itself. */
562static uint64_t refreshRectTimer(rdpContext* ctx, [[maybe_unused]] void* userdata,
563 [[maybe_unused]] FreeRDP_TimerID timerID,
564 [[maybe_unused]] uint64_t timestamp,
565 [[maybe_unused]] uint64_t interval)
566{
567 /* The session this was queued for may be gone, its successor asks again (see uninit). */
568 if (!freerdp_is_active_state(ctx))
569 return 0;
570 const auto dw =
571 static_cast<UINT16>(freerdp_settings_get_uint32(ctx->settings, FreeRDP_DesktopWidth));
572 const auto dh =
573 static_cast<UINT16>(freerdp_settings_get_uint32(ctx->settings, FreeRDP_DesktopHeight));
574 const RECTANGLE_16 all = { 0, 0, dw, dh };
575 if (ctx->update && ctx->update->RefreshRect)
576 (void)ctx->update->RefreshRect(ctx, 1, &all);
577 return 0;
578}
579
580bool SdlRail::paint(SDL_Surface* primary, SDL_PixelFormat fallbackFormat,
581 const std::vector<SDL_Rect>& damage)
582{
583 if (!_enabled)
584 return true;
585
586 std::unique_lock lock(_windowsLock);
587
588 /* Report workarea (avoids maximizing under local panels). */
589 if (_sentWorkArea.w == 0)
590 {
591 SDL_Rect usable{};
592 if (SDL_GetDisplayUsableBounds(SDL_GetPrimaryDisplay(), &usable))
593 sendWorkArea(usable);
594 }
595
596 /* Windows whose SDL parent is going away (deleted by the server, or displaced by a same-id
597 * recreate, see addWindow). Popups owned by that window die with it (the server deletes
598 * them too), and so do non-popup windows, as before. Any other popup keeps its entry: the
599 * server still owns it. A popup without an owner (e.g. a tray notification) is parented to
600 * the focused app window as a fallback; deleting it locally when that window closes
601 * desynchronizes us from the server, which keeps sending orders for it. It only drops its
602 * local SDL window here and the next pass re-creates it under a new parent.
603 * SDL destroys child windows together with their parent, so every window that is about to
604 * lose its SDL window (deleted, displaced, or under one of those) releases it here, deepest
605 * child first, before any entry is destroyed below. */
606 std::vector<std::pair<size_t, SdlRailWindow*>> release;
607 for (auto& [wid, win] : _windows)
608 {
609 if (!win.window())
610 continue;
611 size_t depth = 0;
612 bool orphan = false;
613 bool ownerDeleted = false;
614 for (SDL_Window* p = SDL_GetWindowParent(win.window()); p; p = SDL_GetWindowParent(p))
615 {
616 depth++;
617 auto* owner = getWindowBySdlId(SDL_GetWindowID(p));
618 if (!owner)
619 orphan = true;
620 else if (owner->isDeleted())
621 {
622 orphan = true;
623 if (owner->id() == win.owner())
624 ownerDeleted = true;
625 }
626 }
627 if (orphan && !win.isDeleted() && (ownerDeleted || !win.isPopup()))
628 win.markDeleted();
629 if (orphan || win.isDeleted())
630 release.emplace_back(depth, &win);
631 }
632 for (auto& [wid, win] : _deadWindows)
633 {
634 if (!win.window())
635 continue;
636 size_t depth = 0;
637 for (SDL_Window* p = SDL_GetWindowParent(win.window()); p; p = SDL_GetWindowParent(p))
638 depth++;
639 release.emplace_back(depth, &win);
640 }
641 std::sort(release.begin(), release.end(),
642 [](const auto& a, const auto& b) { return a.first > b.first; });
643 for (auto& [depth, win] : release)
644 win->releaseWindow();
645
646 /* Erase deleted windows; their SDL windows are gone already. */
647 for (auto it = _windows.begin(); it != _windows.end();)
648 it = it->second.isDeleted() ? _windows.erase(it) : std::next(it);
649 /* Windows displaced by a same-id recreate (addWindow) also die here, on the main thread. */
650 _deadWindows.clear();
651
652 /* App windows first so popup parents exist before their popups. */
653 for (auto& it : _windows)
654 {
655 auto& win = it.second;
656 if (win.isPopup())
657 continue;
658 /* Parent owned dialogs to owner. */
659 SDL_Window* parent = nullptr;
660 SDL_Rect parentRect{};
661 /* The owner is chosen by the server: never parent a window to itself or to one of its
662 * own SDL descendants (windows owning each other). SDL does not reject that and the
663 * parent chain walked above becomes a loop. */
664 auto* owner = resolveParent(win.owner());
665 if (owner && !descendsFrom(*owner, win))
666 {
667 parent = owner->window();
668 parentRect = owner->outerRect(); /* the SDL window's on-screen geometry */
669 }
670 const bool realized = win.window() != nullptr;
671 win.paint(primary, fallbackFormat, damage, parent, parentRect);
672 if (!realized && win.window())
673 _context->railWindowInfoChanged(win.id());
674 /* Adopt WM-refused geometry and update server. */
675 SDL_Rect refusedOuter{};
676 if (win.takeWmOverride(refusedOuter))
677 {
678 const SDL_Rect rect = win.serverRect(refusedOuter);
679 const SDL_Rect cur = win.windowRect();
680 WLog_DBG(TAG,
681 "wm-refused adopt id=0x%08" PRIx32
682 " outer=%dx%d -> srv=%d,%d %dx%d (was %dx%d)",
683 static_cast<uint32_t>(win.id()), refusedOuter.w, refusedOuter.h, rect.x,
684 rect.y, rect.w, rect.h, cur.w, cur.h);
685 if (!SDL_RectsEqual(&rect, &cur))
686 sendClientWindowMove(&win, rect);
687 win.adoptLocalGeometry(rect);
688 _context->railWindowInfoChanged(win.id());
689 }
690 /* Resend a size the server left unanswered. */
691 SDL_Rect unconfirmed{};
692 if (win.takeUnconfirmedReport(unconfirmed) && !win.railMinimized() &&
693 !win.effectivelyMaximized())
694 {
695 WLog_DBG(TAG, "size resent id=0x%08" PRIx32 " %dx%d (not confirmed)",
696 static_cast<uint32_t>(win.id()), unconfirmed.w, unconfirmed.h);
697 sendClientWindowMove(&win, unconfirmed);
698 }
699 if (!win.effectivelyMaximized())
700 followDisplay(&win, false);
701 if (win.takeMaximizeAfterEcho() && win.effectivelyMaximized())
702 sendSystemCommand(&win, SC_MAXIMIZE);
703 if (win.takeRestoreRetry())
704 {
705 WLog_DBG(TAG, "restore resent id=0x%08" PRIx32, static_cast<uint32_t>(win.id()));
706 sendSystemCommand(&win, SC_RESTORE);
707 }
708 }
709
710 /* Request full repaint after first window is realized (fixes reconnect blank windows). */
711 if (!_refreshSent)
712 {
713 for (auto& it : _windows)
714 {
715 if (it.second.isPopup() || !it.second.window())
716 continue;
717 auto* ctx = &_context->common()->context;
718 /* Not sent from here (main thread), the RDP thread does it as soon as it can. */
719 if (freerdp_timer_add(ctx, 1, refreshRectTimer, nullptr, true) == 0)
720 WLog_WARN(TAG, "could not queue the refresh-rect");
721 _refreshSent = true;
722 WLog_DBG(TAG, "refresh-rect queued (first app window realized)");
723 break;
724 }
725 }
726
727 for (auto& it : _windows)
728 {
729 auto& popup = it.second;
730 if (!popup.isPopup())
731 continue;
732
733 /* Latch shadow frame classification once identified. */
734 if (!popup.isFrame() && isShadowFrame(popup))
735 popup.setFrame(true);
736
737 /* Anchor drop shadow to adjoining visible popup. */
738 if (popup.isLayered())
739 {
740 constexpr int reach = 48; /* shadow offset+blur spread from its popup, server px */
741 const SDL_Rect sr = popup.windowRect();
742 bool anchored = false;
743 for (auto& other : _windows)
744 {
745 auto& cand = other.second;
746 if ((&cand == &popup) || !cand.isPopup() || cand.isLayered() || !cand.window() ||
747 ((SDL_GetWindowFlags(cand.window()) & SDL_WINDOW_HIDDEN) != 0))
748 continue;
749 SDL_Rect zone = cand.windowRect();
750 zone.x -= reach;
751 zone.y -= reach;
752 zone.w += 2 * reach;
753 zone.h += 2 * reach;
754 /* Shadow must be contained within reach zone to distinguish popup shadows from
755 * app frame edge shadows. */
756 const bool inside = (sr.x >= zone.x) && (sr.y >= zone.y) &&
757 (sr.x + sr.w <= zone.x + zone.w) &&
758 (sr.y + sr.h <= zone.y + zone.h);
759 if (inside)
760 {
761 anchored = true;
762 break;
763 }
764 }
765 popup.setShadowAnchored(anchored);
766 }
767
768 SdlRailWindow* chosen = nullptr;
769 /* Existing popups have an immutable SDL parent; position against it. */
770 if (auto* pw = popup.window())
771 {
772 SDL_Window* p = SDL_GetWindowParent(pw);
773 chosen = p ? getWindowBySdlId(SDL_GetWindowID(p)) : nullptr;
774 }
775 else
776 {
777 chosen = resolvePopupParent(popup);
778 if (!chosen)
779 WLog_DBG(TAG, "popup id=0x%08" PRIx32 " has no parent app window",
780 static_cast<UINT32>(popup.id()));
781 }
782
783 SDL_Window* parent = nullptr;
784 SDL_Rect parentRect{};
785 if (chosen)
786 {
787 parent = chosen->window();
788 parentRect = chosen->outerRect(); /* the SDL window's on-screen geometry */
789 }
790 const bool realized = popup.window() != nullptr;
791 popup.paint(primary, fallbackFormat, damage, parent, parentRect);
792 if (!realized && popup.window())
793 _context->railWindowInfoChanged(popup.id());
794 }
795
796 /* All live windows now have real X11 handles: realize the server's z-order. */
797 applyZOrder();
798 return true;
799}
800
801/* Caller holds _windowsLock (main thread). */
802void SdlRail::applyZOrder()
803{
804 if (!_zOrderDirty)
805 return;
806 /* Only backends with a focus-neutral restack (supportsRestack). */
807 if (!railPlatformCaps().supportsRestack)
808 {
809 _zOrderDirty = false;
810 return;
811 }
812 /* Never restack the window the WM is actively dragging; keep dirty and retry after the move. */
813 if (_localMove.id != 0)
814 {
815 WLog_VRB(TAG, "zorder apply deferred: local move 0x%08" PRIx32 " active", _localMove.id);
816 return;
817 }
818 /* Nor while Windows resizes one on its native frame. */
819 if (_nativeResizeId != 0)
820 {
821 const auto* resizing = getWindowBySdlId(_nativeResizeId);
822 if (resizing && !resizing->isDeleted())
823 return;
824 _nativeResizeId = 0; /* destroyed mid-resize: no end callback comes */
825 }
826 /* Restack top-level windows (skip popups and hidden windows). */
827 std::vector<SDL_Window*> stack;
828 std::vector<uint32_t> applied;
829 stack.reserve(_zOrder.size());
830 applied.reserve(_zOrder.size());
831 for (uint32_t id : _zOrder)
832 {
833 auto* w = getWindow(id);
834 if (w && !w->isPopup() && w->window() &&
835 ((SDL_GetWindowFlags(w->window()) & SDL_WINDOW_HIDDEN) == 0))
836 {
837 stack.push_back(w->window());
838 applied.push_back(id);
839 }
840 }
841 /* Dedup against the restacked set; menus and unrealized windows are filtered out. */
842 if (applied == _appliedZOrder)
843 {
844 _zOrderDirty = false;
845 return;
846 }
847 if (stack.size() >= 2)
848 {
849 std::ignore = railPlatformRestack(stack);
850 }
851
852 _appliedZOrder = std::move(applied);
853 _zOrderDirty = false;
854}
855
856UINT SdlRail::updateWindowFromSurface(gdiGfxSurface* surface)
857{
858 if (!surface)
859 return CHANNEL_RC_OK;
860
861 std::unique_lock lock(_windowsLock);
862 auto appWindow = getWindow(surface->windowId);
863 if (!appWindow)
864 {
865 /* Drop GFX surface for unknown windows (repaints later). */
866 WLog_VRB(TAG, "gfx surface for untracked id=0x%08" PRIx64, surface->windowId);
867 return CHANNEL_RC_OK;
868 }
869
870 /* Clamp mapped dimensions to allocated surface bounds. */
871 const uint32_t w =
872 std::min(surface->mappedWidth ? surface->mappedWidth : surface->width, surface->width);
873 const uint32_t h =
874 std::min(surface->mappedHeight ? surface->mappedHeight : surface->height, surface->height);
875
876 /* Consume per-frame damage. */
877 UINT32 nbRects = 0;
878 const RECTANGLE_16* rects = region16_rects(&surface->invalidRegion, &nbRects);
879 /* Skip undamaged surfaces during EndFrame. */
880 const bool remapped = appWindow->takeSurfaceChange(surface->surfaceId);
881 if ((nbRects == 0) && !remapped)
882 return CHANNEL_RC_OK;
883 appWindow->updateGfxSurface(surface->data, surface->scanline, w, h, rects, nbRects,
884 surface->format);
885 region16_clear(&surface->invalidRegion);
886
887 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
888 return CHANNEL_RC_OK;
889}
890
891UINT SdlRail::UpdateWindowFromSurface(RdpgfxClientContext* context, gdiGfxSurface* surface)
892{
893 WINPR_ASSERT(context);
894 auto gdi = static_cast<rdpGdi*>(context->custom);
895 if (!gdi || !gdi->context)
896 return CHANNEL_RC_OK;
897 auto sdl = get_context(gdi->context);
898 if (!sdl)
899 return CHANNEL_RC_OK;
900 return sdl->getRailChannelContext().updateWindowFromSurface(surface);
901}
902
903bool SdlRail::init(RailClientContext* rail)
904{
905 _rail = rail;
906 if (!rail)
907 return false;
908
909 registerUpdateCallbacks(_context->context()->update);
910
911 {
912 std::unique_lock lock(_windowsLock);
913 /* Move previous windows to deadWindows for main-thread teardown. */
914 for (auto it = _windows.begin(); it != _windows.end();)
915 {
916 auto cur = it++;
917 _deadWindows.insert(_windows.extract(cur));
918 }
919 auto* settings = _context->context()->settings;
920 const uint32_t caches =
921 freerdp_settings_get_uint32(settings, FreeRDP_RemoteAppNumIconCaches);
922 _iconCacheEntries =
923 freerdp_settings_get_uint32(settings, FreeRDP_RemoteAppNumIconCacheEntries);
924 _iconCache.assign(static_cast<size_t>(caches) * _iconCacheEntries, {});
925 }
926
927 rail->custom = this;
928 rail->ServerExecuteResult = SdlRail::server_execute_result;
929 rail->ServerGetAppIdResponse = SdlRail::server_app_id;
930 /* ServerSystemParam not implemented: the server only sends screensaver state here. */
931 rail->ServerLocalMoveSize = SdlRail::server_local_move_size;
932 rail->ServerMinMaxInfo = SdlRail::server_min_max_info;
933 rail->ServerPowerDisplayRequest = SdlRail::server_power_display_request;
934 /* Keep default ServerHandshake. */
935
936 WLog_WARN(TAG, "RemoteApp/RAIL support in the SDL client is experimental");
937 {
938 std::unique_lock lock(_windowsLock);
939 updateCoordinates();
940 }
941 const RailPlatformCaps& caps = railPlatformCaps();
942 railPlatformSetNativeLoopHandler({ this, redrawDuringSizeMove, nativeResize });
943 WLog_DBG(TAG, "RAIL channel initialized: driver=%s windowPositions=%d transparentWindows=%d",
944 SDL_GetCurrentVideoDriver(), caps.supportsWindowPositions ? 1 : 0,
945 caps.supportsTransparentWindows ? 1 : 0);
946#if SDL_VERSION_ATLEAST(3, 4, 10)
947 /* Synchronize WM-driven X11 resizes via _NET_WM_SYNC_REQUEST to prevent torn frames. */
948 if (sdl::utils::isX11Driver())
949 {
950 if (!SDL_SetHint(SDL_HINT_VIDEO_X11_ENABLE_XSYNC_EXT, "1"))
951 WLog_WARN(TAG, "SDL_SetHint(SDL_HINT_VIDEO_X11_ENABLE_XSYNC_EXT) failed: %s",
952 SDL_GetError());
953 }
954#endif
955 /* Like Windows, the click that activates a window also reaches the app. */
956 if (!SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH, "1"))
957 WLog_WARN(TAG, "SDL_SetHint(SDL_HINT_MOUSE_FOCUS_CLICKTHROUGH) failed: %s", SDL_GetError());
958 return true;
959}
960
961/* RemoteApp windows are ordinary local windows. */
962void SdlRail::updateScreenSaver()
963{
964 const bool allowed = _context->allowScreenSaver().value_or(_enabled);
965 const bool on = allowed && !_displayRequested;
966 if (!(on ? SDL_EnableScreenSaver() : SDL_DisableScreenSaver()))
967 WLog_WARN(TAG, "changing the screen saver failed: %s", SDL_GetError());
968}
969
970void SdlRail::queueScreenSaverUpdate()
971{
972 if (!SDL_RunOnMainThread([](void* rail) { static_cast<SdlRail*>(rail)->updateScreenSaver(); },
973 this, false))
974 WLog_WARN(TAG, "could not queue the screen saver change: %s", SDL_GetError());
975}
976
977bool SdlRail::uninit(WINPR_ATTR_UNUSED RailClientContext* rail)
978{
979 WINPR_ASSERT(rail);
980 /* The caller clears rail->custom next; server callbacks return early on nullptr. */
981 std::unique_lock lock(_windowsLock);
982 _refreshSent = false;
983 _appStarted = false;
984 /* Reset session and move state on reconnect. */
985 _localMove = {};
986 _sessionMargins = {};
987 _sentWorkArea = {};
988 _clientActiveId = 0;
989 _focusedAppId = 0;
990 _zOrder.clear();
991 _appliedZOrder.clear();
992 _zOrderDirty = false;
993 _iconCache.clear();
994 _iconScratch = {};
995 /* Mark windows for main-thread teardown. */
996 WLog_DBG(TAG, "RAIL channel uninit, marking %zu windows for main-thread teardown",
997 _windows.size());
998 for (auto& kv : _windows)
999 kv.second.markDeleted();
1000 _rail = nullptr;
1001 _enabled = false;
1002 /* The next connection logs on again: hold its logon desktop back too. */
1003 _desktopReleased = false;
1004 _desktopHoldUntil = 0;
1005 _displayRequested = false;
1006 queueScreenSaverUpdate();
1007
1008 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
1009 return true;
1010}
1011
1012void SdlRail::registerUpdateCallbacks(rdpUpdate* update)
1013{
1014 WINPR_ASSERT(update);
1015 auto window = update->window;
1016 WINPR_ASSERT(window);
1017
1018 window->WindowCreate = SdlRail::window_common;
1019 window->WindowUpdate = SdlRail::window_common;
1020 window->WindowIcon = SdlRail::window_icon;
1021 window->WindowCachedIcon = SdlRail::window_cached_icon;
1022 window->WindowDelete = SdlRail::window_delete;
1023 window->MonitoredDesktop = SdlRail::monitored_desktop;
1024 window->NonMonitoredDesktop = SdlRail::non_monitored_desktop;
1025}
1026
1027/* --- server callbacks --- */
1028
1029UINT SdlRail::server_app_id(RailClientContext* context, const RAIL_GET_APPID_RESP_ORDER* response)
1030{
1031 WINPR_ASSERT(context);
1032 WINPR_ASSERT(response);
1033 auto rail = static_cast<SdlRail*>(context->custom);
1034 if (!rail)
1035 return CHANNEL_RC_OK; /* late order after disconnect */
1036
1037 char* appId = ConvertWCharToUtf8Alloc(response->applicationId, nullptr);
1038 if (!appId)
1039 return CHANNEL_RC_NO_MEMORY;
1040 {
1041 std::unique_lock lock(rail->_windowsLock);
1042 if (auto window = rail->getWindow(response->windowId))
1043 window->setAppId(appId);
1044 }
1045 free(appId);
1046 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
1047 return CHANNEL_RC_OK;
1048}
1049
1050UINT SdlRail::server_execute_result(RailClientContext* context,
1051 const RAIL_EXEC_RESULT_ORDER* execResult)
1052{
1053 WINPR_ASSERT(context);
1054 WINPR_ASSERT(execResult);
1055 auto rail = static_cast<SdlRail*>(context->custom);
1056 if (!rail)
1057 return CHANNEL_RC_OK; /* late order after disconnect */
1058
1059 if (execResult->execResult != RAIL_EXEC_S_OK)
1060 {
1061 WLog_ERR(TAG, "RAIL exec error: execResult=0x%04" PRIx16 " rawResult=0x%08" PRIx32,
1062 execResult->execResult, execResult->rawResult);
1063 if (!freerdp_settings_get_bool(rail->_context->context()->settings,
1064 FreeRDP_RemoteApplicationExecFromPipe))
1065 freerdp_abort_connect_context(rail->_context->context());
1066 }
1067 else
1068 {
1069 WLog_DBG(TAG, "RemoteApp exec OK, enabling RAIL mode");
1070 rail->enableRemoteAppMode(true);
1071 }
1072 return CHANNEL_RC_OK;
1073}
1074
1075UINT SdlRail::server_local_move_size(RailClientContext* context,
1076 const RAIL_LOCALMOVESIZE_ORDER* localMoveSize)
1077{
1078 WINPR_ASSERT(context);
1079 WINPR_ASSERT(localMoveSize);
1080
1081 /* Start native move/resize to avoid dual-authority geometry races. */
1082 if (localMoveSize->isMoveSizeStart && (localMoveSize->moveSizeType >= RAIL_WMSZ_LEFT) &&
1083 (localMoveSize->moveSizeType <= RAIL_WMSZ_MOVE))
1084 {
1085 WLog_DBG(TAG, "server move/size start id=0x%08" PRIx32 " type=%" PRIu16 " pos=%d,%d",
1086 localMoveSize->windowId, localMoveSize->moveSizeType, localMoveSize->posX,
1087 localMoveSize->posY);
1088 if (auto rail = static_cast<SdlRail*>(context->custom))
1089 {
1090 std::unique_lock lock(rail->_windowsLock);
1091 rail->_moveLoop = { localMoveSize->windowId, 0 };
1092 }
1093 (void)sdl_push_user_event(SDL_EVENT_USER_RAIL_MOVE, localMoveSize->windowId,
1094 static_cast<int>(localMoveSize->moveSizeType));
1095 }
1096 else if (!localMoveSize->isMoveSizeStart)
1097 {
1098 WLog_DBG(TAG, "server move/size end id=0x%08" PRIx32, localMoveSize->windowId);
1099
1100 SDL_WindowID sdlId = 0;
1101 /* Server ended the move/size: resume applying geometry + input (covers Wayland move). */
1102 auto rail = static_cast<SdlRail*>(context->custom);
1103 if (rail)
1104 {
1105 std::unique_lock lock(rail->_windowsLock);
1106 auto* appWindow = rail->getWindow(localMoveSize->windowId);
1107 /* Ignore server END order during Wayland resize unless unstarted. */
1108 const bool ownedByWaylandResize = compositorDrag() &&
1109 (rail->_localMove.id == localMoveSize->windowId) &&
1110 rail->_localMove.sawResize;
1111 if (!ownedByWaylandResize)
1112 {
1113 if (appWindow)
1114 appWindow->setLocalMoveActive(false);
1115 if (rail->_localMove.id == localMoveSize->windowId)
1116 {
1117 if (compositorDrag())
1118 {
1119 /* Wayland drag completed. */
1120 rail->_localMove = {};
1121 if (appWindow)
1122 appWindow->invalidateAll();
1123 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
1124 }
1125 else
1126 {
1127 /* Server ended drag loop early. */
1128 rail->_localMove.serverEnded = true;
1129 }
1130 }
1131 }
1132 if (rail->_moveLoop.id == localMoveSize->windowId)
1133 {
1134 const SDL_DisplayID display = rail->_moveLoop.display;
1135 rail->_moveLoop = {};
1136 auto* moved = rail->getWindow(localMoveSize->windowId);
1137 if (moved && (display != 0) && !moved->effectivelyMaximized())
1138 rail->moveToDisplay(moved, display);
1139 }
1140 /* Execute deferred actions now that modal loop has closed. */
1141 if (appWindow && appWindow->loopEndPending())
1142 {
1143 const auto actions = appWindow->takeLoopEnd();
1144 if (actions.maximize && appWindow->railMaximized())
1145 {
1146 WLog_DBG(TAG, "deferred SC_MAXIMIZE id=0x%08" PRIx32, localMoveSize->windowId);
1147 rail->sendSystemCommand(appWindow, SC_MAXIMIZE);
1148 }
1149 if (actions.snap)
1150 {
1151 /* Send deferred snap resize. */
1152 WLog_DBG(TAG, "deferred snap resize id=0x%08" PRIx32 " rect=%d,%d %dx%d",
1153 localMoveSize->windowId, actions.snapRect.x, actions.snapRect.y,
1154 actions.snapRect.w, actions.snapRect.h);
1155 rail->sendClientWindowMove(appWindow, actions.snapRect);
1156 }
1157 /* WM resize can land after button-up (e.g. KDE tiling) while syncGeometry was
1158 * latched out. Sync post-loop geometry now; also needed for deferred snaps where
1159 * snapRect preceded the WM's final tile size. */
1160 if (appWindow->window() && !appWindow->effectivelyMaximized() &&
1161 !appWindow->localMoveSizeChanged())
1162 {
1163 sdlId = appWindow->sdlId();
1164 }
1165 }
1166 }
1167 if (sdlId != 0)
1168 rail->syncGeometry(sdlId);
1169 }
1170 return CHANNEL_RC_OK;
1171}
1172
1173/* A local move/resize runs under the WM grab (not Wayland, the compositor owns that drag). */
1174bool SdlRail::dragActive(SDL_WindowID id)
1175{
1176 return !compositorDrag() && suppressServerMotion(id);
1177}
1178
1179bool SdlRail::suppressServerMotion(SDL_WindowID id)
1180{
1181 std::unique_lock lock(_windowsLock);
1182 if (_localMove.id == 0)
1183 return false;
1184 auto* appWindow = getWindowBySdlId(id);
1185 /* Suppress motion events during active local move. */
1186 return appWindow && appWindow->localMoveActive();
1187}
1188
1189void SdlRail::redrawDuringSizeMove(void* userdata)
1190{
1191 auto* rail = static_cast<SdlRail*>(userdata);
1192 WINPR_ASSERT(rail);
1193 rail->_sizeMoveRedraws++;
1194 if (!rail->_context->drawToWindows())
1195 WLog_WARN(TAG, "redraw during the native size/move loop failed");
1196}
1197
1198void SdlRail::nativeResize(void* userdata, SDL_WindowID id, int moveType, bool end)
1199{
1200 auto* rail = static_cast<SdlRail*>(userdata);
1201 WINPR_ASSERT(rail);
1202 std::unique_lock lock(rail->_windowsLock);
1203 if (!end)
1204 {
1205 /* A server-started drag runs the same loop and already drives the frame. */
1206 if (rail->_localMove.id != 0)
1207 return;
1208 auto* appWindow = rail->getWindowBySdlId(id);
1209 if (!appWindow || appWindow->isPopup() || appWindow->effectivelyMaximized())
1210 return;
1211 WLog_DBG(TAG, "native resize start id=0x%08" PRIx64 " type=%d", appWindow->id(), moveType);
1212 appWindow->setLocalMoveActive(true);
1213 const RailEdges e = railEdges(static_cast<uint16_t>(moveType));
1214 appWindow->setResizeAnchor(e.left, e.top);
1215 rail->_nativeResizeId = id;
1216 return;
1217 }
1218 if (rail->_nativeResizeId != id)
1219 return;
1220 rail->_nativeResizeId = 0;
1221 auto* appWindow = rail->getWindowBySdlId(id);
1222 if (!appWindow || !appWindow->window() || appWindow->isDeleted())
1223 return;
1224 int x = 0;
1225 int y = 0;
1226 int w = 0;
1227 int h = 0;
1228 SDL_GetWindowSize(appWindow->window(), &w, &h);
1229 SDL_GetWindowPosition(appWindow->window(), &x, &y);
1230 WLog_DBG(TAG, "native resize end id=0x%08" PRIx64 " %d,%d %dx%d", appWindow->id(), x, y, w, h);
1231 rail->reportAndAdopt(appWindow, x, y, w, h);
1232}
1233
1234void SdlRail::handleLocalMoveRequested(uint32_t windowId, uint16_t moveType)
1235{
1236 /* Native modal loop: runs unlocked until the drag ends. */
1237 SDL_Window* sdlWindow = beginLocalMove(windowId, moveType);
1238 if (!sdlWindow)
1239 return;
1240 _sizeMoveRedraws = 0;
1241 railPlatformRunModalDrag(sdlWindow, moveType);
1242 WLog_DBG(TAG, "modal drag end id=0x%08" PRIx32 " redraws=%" PRIu32, windowId, _sizeMoveRedraws);
1243 completeLocalMoveIfPending();
1244}
1245
1246/* The WM may end a resize short of the pointer, so the release reaches none of our windows. */
1247static constexpr Uint32 kReleasePollMs = 100;
1248
1249static Uint32 releasePollTimer(void* userdata, [[maybe_unused]] SDL_TimerID timerID,
1250 [[maybe_unused]] Uint32 interval)
1251{
1252 if (!SDL_RunOnMainThread([](void* rail) { static_cast<SdlRail*>(rail)->pollDragRelease(); },
1253 userdata, false))
1254 WLog_WARN(TAG, "could not queue the drag release check: %s", SDL_GetError());
1255 return 0;
1256}
1257
1258void SdlRail::pollDragRelease()
1259{
1260 {
1261 std::unique_lock lock(_windowsLock);
1262 if ((_localMove.id == 0) || compositorDrag())
1263 return;
1264 }
1265 if (SDL_GetGlobalMouseState(nullptr, nullptr) & SDL_BUTTON_LMASK)
1266 {
1267 if (SDL_AddTimer(kReleasePollMs, releasePollTimer, this) == 0)
1268 WLog_WARN(TAG, "drag release timer failed: %s", SDL_GetError());
1269 return;
1270 }
1271 completeLocalMoveIfPending();
1272}
1273
1274SDL_Window* SdlRail::beginLocalMove(uint32_t windowId, uint16_t moveType)
1275{
1276 const RailDragModel model = railPlatformCaps().drag;
1277 if (model == RailDragModel::None)
1278 return nullptr;
1279 const bool compositor = (model == RailDragModel::CompositorResize);
1280
1281 std::unique_lock lock(_windowsLock);
1282 auto appWindow = getWindow(windowId);
1283 if (!appWindow || !appWindow->window() || appWindow->isPopup())
1284 return nullptr;
1285
1286 const bool isMove = (moveType == RAIL_WMSZ_MOVE);
1287 WLog_DBG(TAG, "local move start id=0x%08" PRIx32 " driver=%s type=%" PRIu16 " %s", windowId,
1288 SDL_GetCurrentVideoDriver(), moveType, isMove ? "move" : "resize");
1289 const bool started = railPlatformBeginDrag(appWindow->window(), moveType);
1290 /* Latch and drive the local frame; a Wayland move needs neither (the compositor owns it). */
1291 if (started && (!compositor || !isMove))
1292 {
1293 _localMove = {}; /* clear all per-drag state as a unit before latching this drag */
1294 _localMove.id = windowId;
1295 _localMove.type = moveType;
1296 if (!compositor)
1297 {
1298 /* Latch drag anchors for release calculation. */
1299 _localMove.anchor = _lastPressServer;
1300 _localMove.pointer = _lastPointerServer;
1301 /* Clear prior loop-end state on new drag. */
1302 appWindow->clearLoopEnd();
1303 /* Not for keyboard moves: no button is held. */
1304 if ((model == RailDragModel::WmMoveResize) &&
1305 (SDL_GetGlobalMouseState(nullptr, nullptr) & SDL_BUTTON_LMASK) &&
1306 (SDL_AddTimer(kReleasePollMs, releasePollTimer, this) == 0))
1307 WLog_WARN(TAG, "drag release timer failed: %s", SDL_GetError());
1308 }
1309 appWindow->setLocalMoveActive(true);
1310 if (!isMove)
1311 {
1312 /* Anchor the stale frame to the fixed edge (opposite the dragged one). */
1313 const RailEdges e = railEdges(moveType);
1314 appWindow->setResizeAnchor(e.left, e.top);
1315 }
1316 }
1317 else if (!started)
1318 {
1319 WLog_WARN(TAG, "WM move failed for RAIL window 0x%08" PRIx32, windowId);
1320 }
1321 return (started && (model == RailDragModel::ModalLoop)) ? appWindow->window() : nullptr;
1322}
1323
1324/* Wayland: keep server window position in sync with the active monitor across displays. */
1325void SdlRail::handleDisplayChanged(SDL_WindowID id, SDL_DisplayID display)
1326{
1327 if (railPlatformCaps().supportsWindowPositions)
1328 return;
1329 std::unique_lock lock(_windowsLock);
1330 auto* appWindow = getWindowBySdlId(id);
1331 if (!appWindow || appWindow->isPopup())
1332 return;
1333 WLog_DBG(TAG, "display changed id=0x%08" PRIx32 " display %" PRIu32,
1334 static_cast<uint32_t>(appWindow->id()), display);
1335 appWindow->noteDisplayChange();
1336}
1337
1338void SdlRail::followDisplay(SdlRailWindow* appWindow, bool now)
1339{
1340 if (!appWindow->takeDisplayChange(now))
1341 return;
1342 const SDL_DisplayID display = SDL_GetDisplayForWindow(appWindow->window());
1343 if (display == 0)
1344 return;
1345 /* The end of the server move loop would undo it. */
1346 if (_moveLoop.id == appWindow->id())
1347 {
1348 _moveLoop.display = display;
1349 return;
1350 }
1351 moveToDisplay(appWindow, display);
1352}
1353
1354bool SdlRail::monitorRect(SDL_DisplayID display, SDL_Rect& rect) const
1355{
1356 const auto* settings = _context->common()->context.settings;
1357 const UINT32 count = freerdp_settings_get_uint32(settings, FreeRDP_MonitorCount);
1358 for (UINT32 x = 0; x < count; x++)
1359 {
1360 const auto* mon = static_cast<const rdpMonitor*>(
1361 freerdp_settings_get_pointer_array(settings, FreeRDP_MonitorDefArray, x));
1362 if (mon && (mon->orig_screen == display))
1363 {
1364 rect = { mon->x, mon->y, mon->width, mon->height };
1365 return true;
1366 }
1367 }
1368 return false;
1369}
1370
1371void SdlRail::moveToDisplay(SdlRailWindow* appWindow, SDL_DisplayID display)
1372{
1373 SDL_Rect area{};
1374 if (!monitorRect(display, area))
1375 return;
1376 SDL_Rect rect = appWindow->windowRect();
1377 const SDL_Point center = { rect.x + rect.w / 2, rect.y + rect.h / 2 };
1378 if (SDL_PointInRect(&center, &area))
1379 return;
1380 rect.x = area.x + std::max(0, (area.w - rect.w) / 2);
1381 rect.y = area.y + std::max(0, (area.h - rect.h) / 2);
1382 WLog_DBG(TAG, "window 0x%08" PRIx32 " now on display %" PRIu32 ", server move to %d,%d",
1383 static_cast<uint32_t>(appWindow->id()), display, rect.x, rect.y);
1384 sendClientWindowMove(appWindow, rect);
1385 appWindow->adoptLocalGeometry(rect);
1386 _pointerEpoch++;
1387}
1388
1389/* Saturate a window edge to the 16 bit range of the ClientWindowMove fields. */
1390[[nodiscard]] static INT16 clampToInt16(int64_t value)
1391{
1392 return static_cast<INT16>(std::clamp<int64_t>(value, INT16_MIN, INT16_MAX));
1393}
1394
1395/* Send ClientWindowMove with full frame geometry including server margins (caller holds
1396 * _windowsLock). */
1397void SdlRail::sendClientWindowMove(SdlRailWindow* appWindow, const SDL_Rect& serverRect)
1398{
1399 const SDL_Rect fm = appWindow->frameMargins();
1400 RAIL_WINDOW_MOVE_ORDER move = {};
1401 move.windowId = static_cast<UINT32>(appWindow->id());
1402 /* Window rect and margins are 32 bit values from the server's window orders: compute the
1403 * edges in 64 bit and clamp (like xf_rail) instead of asserting on server supplied data. */
1404 const int64_t x = serverRect.x;
1405 const int64_t y = serverRect.y;
1406 move.left = clampToInt16(x - fm.x);
1407 move.top = clampToInt16(y - fm.y);
1408 move.right = clampToInt16(x + serverRect.w + fm.w);
1409 move.bottom = clampToInt16(y + serverRect.h + fm.h);
1410 if (_rail && _rail->ClientWindowMove &&
1411 (_rail->ClientWindowMove(_rail, &move) != CHANNEL_RC_OK))
1412 WLog_WARN(TAG, "ClientWindowMove failed for RAIL window 0x%08" PRIx32, move.windowId);
1413}
1414
1415/* Report final geometry and adopt locally. */
1416void SdlRail::reportAndAdopt(SdlRailWindow* appWindow, int x, int y, int w, int h)
1417{
1418 /* Local geometry -> server rect: strip the client-side band insets. */
1419 const SDL_Rect rect = appWindow->serverRect({ x, y, w, h });
1420 /* Report outer frame to server (inflate by margins). */
1421 const bool maximized = appWindow->effectivelyMaximized();
1422 /* Report geometry if changed. */
1423 const SDL_Rect cur = appWindow->windowRect();
1424 const bool unchanged = SDL_RectsEqual(&rect, &cur);
1425 if (!maximized && !unchanged)
1426 sendClientWindowMove(appWindow, rect);
1427
1428 /* Adopt WM final geometry and resume input routing. */
1429 if (maximized)
1430 appWindow->setLocalMoveActive(false); /* geometry is WM/server-owned while maximized */
1431 else
1432 appWindow->adoptLocalGeometry(rect);
1433 _context->railWindowInfoChanged(appWindow->id());
1434 /* Repaint now: the last presented frame may still be the resize placeholder. */
1435 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
1436}
1437
1438void SdlRail::clampIntoDesktop(const SdlRailWindow& appWindow, int& x, int& y, int w, int h) const
1439{
1440 auto* settings = _context->context()->settings;
1441 const int dw = static_cast<int>(freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth));
1442 const int dh = static_cast<int>(freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight));
1443 /* Clamp the content rect to the remote desktop; the resize band may extend outside. */
1444 const SDL_Rect s = appWindow.serverRect({ x, y, w, h });
1445 const auto origin = _context->inputOrigin();
1446 SDL_Rect area = { origin.x, origin.y, dw, dh };
1447 /* Wayland: keep the window on its monitor if it fits. */
1448 SDL_Rect mon{};
1449 if (!railPlatformCaps().supportsWindowPositions &&
1450 monitorRect(SDL_GetDisplayForWindow(appWindow.window()), mon) && (s.w <= mon.w) &&
1451 (s.h <= mon.h))
1452 area = mon;
1453 x += std::clamp(s.x, area.x, area.x + std::max(0, area.w - s.w)) - s.x;
1454 y += std::clamp(s.y, area.y, area.y + std::max(0, area.h - s.h)) - s.y;
1455}
1456
1457void SdlRail::noteDragResize(SDL_WindowID id, int w, int h)
1458{
1459 std::unique_lock lock(_windowsLock);
1460 if ((_localMove.id == 0) || compositorDrag() || (_localMove.type != RAIL_WMSZ_MOVE))
1461 return;
1462 auto* appWindow = getWindowBySdlId(id);
1463 if (!appWindow || (static_cast<uint32_t>(appWindow->id()) != _localMove.id))
1464 return;
1465 /* Filter out reconcile echo from server drag-restore. */
1466 if (appWindow->localMoveSizeChanged())
1467 {
1468 const SDL_Rect outer = appWindow->outerRect();
1469 if ((w == outer.w) && (h == outer.h))
1470 return;
1471 }
1472 _localMove.wmSized = true;
1473 _localMove.wmSize = { w, h };
1474}
1475
1476/* Update server work area from maximized window bounds (caller holds _windowsLock). */
1477void SdlRail::reportMaximizedWorkArea(SdlRailWindow* appWindow)
1478{
1479 /* Ignore unconfirmed maximize states that still include resize insets. */
1480 if ((SDL_GetWindowFlags(appWindow->window()) & SDL_WINDOW_MAXIMIZED) == 0)
1481 return;
1482 int w = 0;
1483 int h = 0;
1484 SDL_GetWindowSize(appWindow->window(), &w, &h);
1485 if ((w <= 0) || (h <= 0))
1486 return;
1487 /* Clip work area within primary display bounds. */
1488 SDL_Rect primary{};
1489 if (!SDL_GetDisplayBounds(SDL_GetPrimaryDisplay(), &primary))
1490 return;
1491 /* Without readable positions a maximized window is taken to be on the primary monitor. */
1492 int x = primary.x;
1493 int y = primary.y;
1494 if (railPlatformCaps().supportsWindowPositions)
1495 SDL_GetWindowPosition(appWindow->window(), &x, &y);
1496 const SDL_Rect area = { x, y, w, h };
1497 SDL_Rect overlap{};
1498 if (!SDL_GetRectIntersection(&area, &primary, &overlap) || !SDL_RectsEqual(&overlap, &area))
1499 return;
1500 sendWorkArea(area);
1501}
1502
1503void SdlRail::syncGeometry(SDL_WindowID id)
1504{
1505 std::unique_lock lock(_windowsLock);
1506 auto* w = getWindowBySdlId(id);
1507 if (!w || !w->window() || w->isDeleted() || w->isPopup())
1508 return;
1509
1510 /* Geometry is server/WM-owned when maximized or minimized. */
1511 if (w->effectivelyMaximized())
1512 {
1513 reportMaximizedWorkArea(w);
1514 return;
1515 }
1516 if (w->railMinimized())
1517 return;
1518
1519 const auto wid = static_cast<uint32_t>(w->id());
1520 /* Skip geometry sync while awaiting server restored rect. */
1521 if (w->localMoveActive() || (_localMove.id == wid) || w->loopEndPending() ||
1522 w->stateTransitionPending() || w->awaitingRestoreRect() || w->insetsStale())
1523 return;
1524
1525 int lw = 0;
1526 int lh = 0;
1527 SDL_GetWindowSize(w->window(), &lw, &lh);
1528 if ((lw <= 0) || (lh <= 0))
1529 return;
1530
1531 /* Ignore invalid zero-content window size updates. */
1532 const SDL_Rect ins = w->insets();
1533 if (((lw - ins.x - ins.w) <= 0) || ((lh - ins.y - ins.h) <= 0))
1534 {
1535 WLog_DBG(TAG, "geometry sync id=0x%08" PRIx32 " %dx%d dropped (content collapsed)", wid, lw,
1536 lh);
1537 return;
1538 }
1539
1540 const SDL_Rect vis = w->outerRect();
1541 const bool posKnown = railPlatformCaps().supportsWindowPositions;
1542 int lx = vis.x;
1543 int ly = vis.y;
1544 if (posKnown)
1545 SDL_GetWindowPosition(w->window(), &lx, &ly);
1546 else
1547 clampIntoDesktop(*w, lx, ly, lw, lh);
1548
1549 /* Check if window settled at applied target. */
1550 if ((lw == vis.w) && (lh == vis.h) && (!posKnown || ((lx == vis.x) && (ly == vis.y))))
1551 {
1552 w->clearGeomApplyPending();
1553 return; /* Ignore self-echo when geometry converged. */
1554 }
1555
1556 /* Drop transient echo events while client geometry application is in flight. */
1557 if (w->geomApplyPending())
1558 {
1559 /* Allow live Wayland compositor resize to advance beyond in-flight apply. */
1560 const bool overtaken = !posKnown && ((lw > vis.w) || (lh > vis.h));
1561 if (!overtaken)
1562 return;
1563 w->clearGeomApplyPending();
1564 }
1565
1566 WLog_DBG(TAG, "geometry sync id=0x%08" PRIx32 " local=%d,%d %dx%d (sync)", wid, lx, ly, lw, lh);
1567 reportAndAdopt(w, lx, ly, lw, lh);
1568}
1569
1570/* A release outside our windows brings no enter: finish once the size settles. */
1571static constexpr Uint32 kResizeSettleMs = 500;
1572
1573static Uint32 resizeSettleTimer(void* userdata, [[maybe_unused]] SDL_TimerID timerID,
1574 [[maybe_unused]] Uint32 interval)
1575{
1576 if (!SDL_RunOnMainThread([](void* rail) { static_cast<SdlRail*>(rail)->settleWaylandResize(); },
1577 userdata, false))
1578 WLog_WARN(TAG, "could not queue the resize settle check: %s", SDL_GetError());
1579 return 0;
1580}
1581
1582void SdlRail::settleWaylandResize()
1583{
1584 {
1585 std::unique_lock lock(_windowsLock);
1586 if ((_localMove.id == 0) || !compositorDrag() || !_localMove.sawResize ||
1587 (SDL_GetTicks() - _localMove.lastResize < kResizeSettleMs))
1588 return;
1589 }
1590 completeWaylandResize();
1591}
1592
1593void SdlRail::noteResizeGrab(SDL_WindowID id)
1594{
1595 std::unique_lock lock(_windowsLock);
1596 if (_localMove.id == 0)
1597 return;
1598 auto* appWindow = getWindowBySdlId(id);
1599 /* Mouse leave or a configure during the drag: the compositor resize is under way. */
1600 if (!appWindow || (static_cast<uint32_t>(appWindow->id()) != _localMove.id) ||
1601 !compositorDrag())
1602 return;
1603 _localMove.sawResize = true;
1604 _localMove.lastResize = SDL_GetTicks();
1605 if (SDL_AddTimer(kResizeSettleMs, resizeSettleTimer, this) == 0)
1606 WLog_WARN(TAG, "resize settle timer failed: %s", SDL_GetError());
1607}
1608
1609void SdlRail::completeWaylandResize(bool definitive)
1610{
1611 std::unique_lock lock(_windowsLock);
1612 if ((_localMove.id == 0) || !compositorDrag())
1613 return;
1614 /* Finalize drag resize on window enter if resize occurred. */
1615 if (!_localMove.sawResize)
1616 {
1617 if (definitive)
1618 {
1619 if (auto* appWindow = getWindow(_localMove.id))
1620 {
1621 appWindow->setLocalMoveActive(false);
1622 /* Repaint now: the dashed placeholder is on screen and an undamaged window would
1623 * otherwise keep it until the next server frame. */
1624 appWindow->invalidateAll();
1625 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
1626 }
1627 _localMove = {}; /* Snapshot and clear drag state under lock. */
1628 }
1629 return;
1630 }
1631
1632 /* Snapshot and clear drag state atomically under lock. */
1633 const LocalMove drag = _localMove;
1634 _localMove = {};
1635
1636 auto appWindow = getWindow(drag.id);
1637 if (!appWindow || !appWindow->window())
1638 return;
1639
1640 (void)SDL_SyncWindow(appWindow->window());
1641 int w = 0;
1642 int h = 0;
1643 SDL_GetWindowSize(appWindow->window(), &w, &h);
1644
1645 /* Derive Wayland origin from anchor edge. */
1646 const SDL_Rect start = appWindow->outerRect();
1647 const RailEdges e = railEdges(drag.type);
1648 int x = e.left ? (start.x + start.w - w) : start.x;
1649 int y = e.top ? (start.y + start.h - h) : start.y;
1650 clampIntoDesktop(*appWindow, x, y, w, h);
1651 reportAndAdopt(appWindow, x, y, w, h);
1652}
1653
1654void SdlRail::completeLocalMoveIfPending()
1655{
1656 std::unique_lock lock(_windowsLock);
1657 if (_localMove.id == 0)
1658 return;
1659 /* Skip Wayland button-up finalize. */
1660 if (compositorDrag())
1661 return;
1662
1663 /* Snapshot and clear drag state atomically under lock. */
1664 const LocalMove drag = _localMove;
1665 _localMove = {};
1666
1667 auto appWindow = getWindow(drag.id);
1668 if (!appWindow || !appWindow->window() || appWindow->isDeleted())
1669 return; /* window gone mid-drag: nothing to release into or report for */
1670
1671 /* Send synthetic button release if WM grab consumed physical release. */
1672 if ((SDL_GetMouseState(nullptr, nullptr) & SDL_BUTTON_LMASK) &&
1673 !(SDL_GetGlobalMouseState(nullptr, nullptr) & SDL_BUTTON_LMASK))
1674 if (!railPlatformReleaseButton(appWindow->window()))
1675 WLog_WARN(TAG, "synthetic button release failed");
1676
1677 /* Finalize WM resize before reading final size. */
1678 (void)SDL_SyncWindow(appWindow->window());
1679
1680 int x = 0;
1681 int y = 0;
1682 int w = 0;
1683 int h = 0;
1684 SDL_GetWindowSize(appWindow->window(), &w, &h);
1685 SDL_GetWindowPosition(appWindow->window(), &x, &y);
1686 const bool isMove = (drag.type == RAIL_WMSZ_MOVE);
1687 const SDL_Rect start = appWindow->outerRect(); /* position frozen at drag start */
1688 /* Preserve server size during move; defer WM snap/tile size sync until loop END to avoid
1689 * server drag-restore conflict. */
1690 if (isMove)
1691 {
1692 if (!appWindow->effectivelyMaximized() && drag.wmSized &&
1693 !appWindow->localMoveSizeChanged())
1694 {
1695 /* Adopt WM size if window was resized during move. */
1696 w = drag.wmSize.x;
1697 h = drag.wmSize.y;
1698 appWindow->deferSnap(appWindow->serverRect({ x, y, w, h }));
1699 }
1700 else
1701 {
1702 w = start.w;
1703 h = start.h;
1704 }
1705 }
1706 /* Finalize modal loop unless server closed it early. */
1707 if (!drag.serverEnded)
1708 {
1709 int px = drag.anchor.x;
1710 int py = drag.anchor.y;
1711 if (isMove && appWindow->localMoveSizeChanged())
1712 {
1713 /* Measure delta from server anchor on drag-restore. */
1714 const SDL_Point sp = appWindow->localMoveServerPos();
1715 const SDL_Rect now = appWindow->serverRect({ x, y, w, h });
1716 px = drag.pointer.x + now.x - sp.x;
1717 py = drag.pointer.y + now.y - sp.y;
1718 }
1719 else if (!appWindow->effectivelyMaximized())
1720 {
1721 const RailEdges e = railEdges(drag.type);
1722 if (isMove || e.left)
1723 px += x - start.x;
1724 else if (e.right)
1725 px += (x + w) - (start.x + start.w);
1726 if (isMove || e.top)
1727 py += y - start.y;
1728 else if (e.bottom)
1729 py += (y + h) - (start.y + start.h);
1730 }
1731 (void)freerdp_client_send_button_event(_context->common(), FALSE, PTR_FLAGS_BUTTON1, px,
1732 py);
1733 /* Server loop unwinding: wait for explicit END order to gate deferred SC_MAXIMIZE. */
1734 appWindow->armLoopEnd();
1735
1736 /* Adopt local geometry without sending ClientWindowMove during mouse drags. */
1737 const SDL_Rect rect = appWindow->serverRect({ x, y, w, h });
1738 const bool restoredMidDrag = appWindow->localMoveSizeChanged();
1739 appWindow->adoptLocalGeometry(rect);
1740 _context->railWindowInfoChanged(appWindow->id());
1741 /* Drag complete: apply pending server resize delayed during WM grab. */
1742 if (restoredMidDrag)
1743 appWindow->markGeometryDirty();
1744 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
1745 }
1746 else if (!isMove)
1747 {
1748 /* Sync final resize geometry if server closed loop early. */
1749 clampIntoDesktop(*appWindow, x, y, w, h);
1750 reportAndAdopt(appWindow, x, y, w, h);
1751 }
1752
1753 railPlatformEndDrag(appWindow->window());
1754}
1755
1756UINT SdlRail::server_power_display_request(RailClientContext* context,
1757 const RAIL_POWER_DISPLAY_REQUEST* power)
1758{
1759 WINPR_ASSERT(context);
1760 WINPR_ASSERT(power);
1761 auto rail = static_cast<SdlRail*>(context->custom);
1762 if (!rail)
1763 return CHANNEL_RC_OK; /* late order after disconnect */
1764
1765 WLog_DBG(TAG, "power display request %s", power->active ? "on" : "off");
1766 rail->_displayRequested = (power->active != 0);
1767 rail->queueScreenSaverUpdate();
1768 return CHANNEL_RC_OK;
1769}
1770
1771UINT SdlRail::server_min_max_info(RailClientContext* context,
1772 const RAIL_MINMAXINFO_ORDER* minMaxInfo)
1773{
1774 WINPR_ASSERT(context);
1775 WINPR_ASSERT(minMaxInfo);
1776 auto rail = static_cast<SdlRail*>(context->custom);
1777 if (!rail)
1778 return CHANNEL_RC_OK; /* late order after disconnect */
1779
1780 std::unique_lock lock(rail->_windowsLock);
1781 auto appWindow = rail->getWindow(minMaxInfo->windowId);
1782 if (appWindow)
1783 {
1784 WLog_VRB(TAG, "server minmax id=0x%08" PRIx32 " min=%dx%d max=%dx%d", minMaxInfo->windowId,
1785 minMaxInfo->minTrackWidth, minMaxInfo->minTrackHeight, minMaxInfo->maxTrackWidth,
1786 minMaxInfo->maxTrackHeight);
1787 appWindow->setMinMaxSize({ minMaxInfo->minTrackWidth, minMaxInfo->minTrackHeight },
1788 { minMaxInfo->maxTrackWidth, minMaxInfo->maxTrackHeight });
1789
1790 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
1791 }
1792 return CHANNEL_RC_OK;
1793}
1794
1795/* --- window order callbacks --- */
1796
1797/* Non-zero edge means margins exist; all-zero means "no band". */
1798static bool marginsSet(const SDL_Rect& m)
1799{
1800 return m.x || m.y || m.w || m.h;
1801}
1802
1803/* RESIZE_MARGIN fields: set this window's frame margins and seed/backfill the session BAND. */
1804void SdlRail::updateMargins(SdlRailWindow* appWindow, const WINDOW_ORDER_INFO* orderInfo,
1805 const WINDOW_STATE_ORDER* state)
1806{
1807 const UINT32 fieldFlags = orderInfo->fieldFlags;
1808 SDL_Rect m = appWindow->frameMargins(); /* raw server margins as the base */
1809 if (fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X)
1810 {
1811 m.x = static_cast<int>(state->resizeMarginLeft);
1812 m.w = static_cast<int>(state->resizeMarginRight);
1813 }
1814 if (fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y)
1815 {
1816 m.y = static_cast<int>(state->resizeMarginTop);
1817 m.h = static_cast<int>(state->resizeMarginBottom);
1818 }
1819 /* Use window's own frame margins; session margin serves as fallback for band sizing. */
1820 appWindow->setFrameMargins(m);
1821 SDL_Rect& sm = _sessionMargins;
1822 if (marginsSet(m) && !marginsSet(sm))
1823 {
1824 sm = m;
1825 /* Backfill band of earlier zero-announce windows. */
1826 for (auto& [id, w] : _windows)
1827 if (!marginsSet(w.resizeMargins()))
1828 w.setResizeMargins(m.x, m.y, m.w, m.h);
1829 }
1830 const SDL_Rect bandSrc = marginsSet(m) ? m : sm;
1831 appWindow->setResizeMargins(bandSrc.x, bandSrc.y, bandSrc.w, bandSrc.h);
1832 WLog_DBG(TAG, "margins id=0x%08" PRIx32 " raw L%d T%d R%d B%d", orderInfo->windowId, m.x, m.y,
1833 m.w, m.h);
1834}
1835
1836/* SHOW field: mirror the server's show-state (visibility + maximize/minimize) locally. */
1837void SdlRail::updateShowState(SdlRailWindow* appWindow, const WINDOW_ORDER_INFO* orderInfo,
1838 const WINDOW_STATE_ORDER* state)
1839{
1840 WLog_DBG(TAG, "server showState id=0x%08" PRIx32 " state=0x%02" PRIx32, orderInfo->windowId,
1841 state->showState);
1842 appWindow->setVisible(state->showState != WINDOW_HIDE);
1843 switch (state->showState)
1844 {
1845 case WINDOW_SHOW_MAXIMIZED:
1846 appWindow->setServerMaximized(true);
1847 appWindow->setServerMinimized(false);
1848 break;
1849 case WINDOW_SHOW_MINIMIZED:
1850 appWindow->setServerMinimized(true);
1851 break;
1852 case WINDOW_SHOW:
1853 appWindow->setServerMaximized(false);
1854 appWindow->setServerMinimized(false);
1855 break;
1856 default:
1857 break;
1858 }
1859}
1860
1861/* VISIBILITY field: convert the server's visibility rects (window-relative) and store them. */
1862void SdlRail::updateVisRects(SdlRailWindow* appWindow, const WINDOW_ORDER_INFO* orderInfo,
1863 const WINDOW_STATE_ORDER* state)
1864{
1865 std::vector<SDL_Rect> rects;
1866 rects.reserve(state->numVisibilityRects);
1867 for (UINT32 i = 0; i < state->numVisibilityRects; i++)
1868 {
1869 const RECTANGLE_16& r = state->visibilityRects[i];
1870 rects.push_back({ r.left, r.top, r.right - r.left, r.bottom - r.top });
1871 }
1872 if (rects.empty())
1873 WLog_DBG(TAG, "visrects id=0x%08" PRIx32 " n=0", orderInfo->windowId);
1874 else
1875 WLog_DBG(TAG, "visrects id=0x%08" PRIx32 " n=%zu first=%dx%d+%d+%d", orderInfo->windowId,
1876 rects.size(), rects.at(0).w, rects.at(0).h, rects.at(0).x, rects.at(0).y);
1877 appWindow->setVisibilityRects(std::move(rects));
1878}
1879
1880BOOL SdlRail::window_common(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo,
1881 const WINDOW_STATE_ORDER* windowState)
1882{
1883 WINPR_ASSERT(orderInfo);
1884 WINPR_ASSERT(windowState);
1885 auto rail = SdlRail::get(context);
1886 if (!rail)
1887 return FALSE;
1888
1889 const UINT32 fieldFlags = orderInfo->fieldFlags;
1890 std::unique_lock lock(rail->_windowsLock);
1891 auto appWindow = rail->getWindow(orderInfo->windowId);
1892
1893 if (fieldFlags & WINDOW_ORDER_STATE_NEW)
1894 {
1895 const SDL_Rect rect = { static_cast<int>(windowState->windowOffsetX),
1896 static_cast<int>(windowState->windowOffsetY),
1897 static_cast<int>(windowState->windowWidth),
1898 static_cast<int>(windowState->windowHeight) };
1899 appWindow = rail->addWindow(orderInfo->windowId, rect);
1900 if (!appWindow)
1901 return FALSE;
1902
1903 WLog_DBG(TAG,
1904 "window create id=0x%08" PRIx32 " %dx%d+%d+%d style=0x%08" PRIx32
1905 " ex=0x%08" PRIx32 " owner=0x%08" PRIx32,
1906 orderInfo->windowId, rect.w, rect.h, rect.x, rect.y, windowState->style,
1907 windowState->extendedStyle, windowState->ownerWindowId);
1908 /* Seed resize band margins from session default. */
1909 const SDL_Rect& sm = rail->_sessionMargins;
1910 if (marginsSet(sm))
1911 appWindow->setResizeMargins(sm.x, sm.y, sm.w, sm.h);
1912 /* The SDL window is created lazily on the main thread (reconcile), as SDL requires. */
1913
1914 /* Ask for the application ID, the answer is used as the window's app_id. */
1915 if (rail->_rail && rail->_rail->ClientGetAppIdRequest)
1916 {
1917 const RAIL_GET_APPID_REQ_ORDER request = { orderInfo->windowId };
1918 if (rail->_rail->ClientGetAppIdRequest(rail->_rail, &request) != CHANNEL_RC_OK)
1919 WLog_WARN(TAG, "Get AppID request failed for window 0x%08" PRIx32,
1920 orderInfo->windowId);
1921 }
1922 }
1923
1924 if (!appWindow)
1925 {
1926 /* An order for a window this client does not track, e.g. one it dropped
1927 * locally because its SDL parent went away (reconcile cascade) while the
1928 * server still has it. Failing the order tears down the whole connection
1929 * (fastpath update failure -> disconnect); ignore it instead and wait for
1930 * the next WINDOW_ORDER_STATE_NEW for this id. */
1931 WLog_WARN(TAG, "ignoring order flags=0x%08" PRIx32 " for unknown window id=0x%08" PRIx32,
1932 fieldFlags, orderInfo->windowId);
1933 return TRUE;
1934 }
1935
1936 /* Show state first: a minimized window's rect is not a placement (updateWindowRect). */
1937 if (fieldFlags & WINDOW_ORDER_FIELD_SHOW)
1938 updateShowState(appWindow, orderInfo, windowState);
1939
1940 if (fieldFlags & (WINDOW_ORDER_FIELD_WND_OFFSET | WINDOW_ORDER_FIELD_WND_SIZE))
1941 {
1942 SDL_Rect r = appWindow->windowRect();
1943 if (fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET)
1944 {
1945 r.x = static_cast<int>(windowState->windowOffsetX);
1946 r.y = static_cast<int>(windowState->windowOffsetY);
1947 }
1948 if (fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE)
1949 {
1950 r.w = static_cast<int>(windowState->windowWidth);
1951 r.h = static_cast<int>(windowState->windowHeight);
1952 }
1953 WLog_VRB(TAG, "server geom id=0x%08" PRIx32 " rect=%d,%d %dx%d", orderInfo->windowId, r.x,
1954 r.y, r.w, r.h);
1955 appWindow->updateWindowRect(r);
1956 rail->_context->railWindowInfoChanged(orderInfo->windowId);
1957 }
1958 if (fieldFlags & WINDOW_ORDER_FIELD_OWNER)
1959 appWindow->setOwner(windowState->ownerWindowId);
1960 if (fieldFlags & (WINDOW_ORDER_FIELD_RESIZE_MARGIN_X | WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y))
1961 rail->updateMargins(appWindow, orderInfo, windowState);
1962 if (fieldFlags & WINDOW_ORDER_FIELD_STYLE)
1963 appWindow->setStyle(windowState->style, windowState->extendedStyle);
1964 if (fieldFlags & WINDOW_ORDER_FIELD_TITLE)
1965 {
1966 char* title = rail_string_to_utf8_string(&windowState->titleInfo);
1967 if (title)
1968 {
1969 appWindow->setTitle(title);
1970 free(title);
1971 }
1972 }
1973
1974 if (fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET)
1975 {
1976 WLog_DBG(TAG, "visoff id=0x%08" PRIx32 " %d,%d", orderInfo->windowId,
1977 windowState->visibleOffsetX, windowState->visibleOffsetY);
1978 appWindow->setVisibleOffset({ static_cast<int>(windowState->visibleOffsetX),
1979 static_cast<int>(windowState->visibleOffsetY) });
1980 }
1981 if (fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY)
1982 updateVisRects(appWindow, orderInfo, windowState);
1983
1984 /* Wake the main thread to create/move/show/paint the SDL window(s). */
1985 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
1986 return TRUE;
1987}
1988
1989SdlRailIcon* SdlRail::iconCacheLookup(uint32_t cacheId, uint32_t cacheEntry)
1990{
1991 if (cacheId == 0xFF)
1992 return &_iconScratch;
1993 const size_t idx = static_cast<size_t>(cacheId) * _iconCacheEntries + cacheEntry;
1994 if ((_iconCacheEntries == 0) || (cacheEntry >= _iconCacheEntries) || (idx >= _iconCache.size()))
1995 return nullptr;
1996 return &_iconCache.at(idx);
1997}
1998
1999/* ICON_INFO (1/4/8/16/24/32 bpp + AND mask) -> BGRA32, like xf convert_rail_icon. */
2000static bool convertRailIcon(const ICON_INFO* info, SdlRailIcon& icon)
2001{
2002 /* width, height and cbBitsColor come straight from the wire. Every format accepted by
2003 * freerdp_image_copy_from_icon_data needs at least one byte of bitsColor per pixel, so an
2004 * icon claiming more pixels than that is rejected before the BGRA buffer is allocated
2005 * (4 * 65535 * 65535 bytes otherwise). A failed decode leaves the cache slot empty so a
2006 * later WindowCachedIcon does not pick up a half-initialized icon. */
2007 const size_t pixels = 1ULL * info->width * info->height;
2008 if (pixels > info->cbBitsColor)
2009 {
2010 icon = {};
2011 return false;
2012 }
2013
2014 icon.w = info->width;
2015 icon.h = info->height;
2016 icon.bgra.assign(4ULL * pixels, 0);
2017 if (freerdp_image_copy_from_icon_data(
2018 icon.bgra.data(), PIXEL_FORMAT_BGRA32, 0, 0, 0,
2019 WINPR_ASSERTING_INT_CAST(UINT16, info->width),
2020 WINPR_ASSERTING_INT_CAST(UINT16, info->height), info->bitsColor,
2021 WINPR_ASSERTING_INT_CAST(UINT16, info->cbBitsColor), info->bitsMask,
2022 WINPR_ASSERTING_INT_CAST(UINT16, info->cbBitsMask), info->colorTable,
2023 WINPR_ASSERTING_INT_CAST(UINT16, info->cbColorTable), info->bpp) != TRUE)
2024 {
2025 icon = {};
2026 return false;
2027 }
2028 return true;
2029}
2030
2031BOOL SdlRail::window_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo,
2032 const WINDOW_ICON_ORDER* windowIcon)
2033{
2034 WINPR_ASSERT(orderInfo);
2035 WINPR_ASSERT(windowIcon);
2036 WINPR_ASSERT(windowIcon->iconInfo);
2037 auto rail = SdlRail::get(context);
2038 if (!rail)
2039 return FALSE;
2040
2041 std::unique_lock lock(rail->_windowsLock);
2042 auto appWindow = rail->getWindow(orderInfo->windowId);
2043 if (!appWindow)
2044 return TRUE;
2045
2046 /* Decode into the cache slot so a later WindowCachedIcon can reference it. */
2047 const ICON_INFO* info = windowIcon->iconInfo;
2048 auto* icon = rail->iconCacheLookup(info->cacheId, info->cacheEntry);
2049 if (!icon || !convertRailIcon(info, *icon))
2050 {
2051 WLog_WARN(TAG, "failed to decode icon %02" PRIX32 ":%04" PRIX32 " for window 0x%08" PRIx32,
2052 info->cacheId, info->cacheEntry, orderInfo->windowId);
2053 return TRUE;
2054 }
2055 appWindow->setIcon(*icon);
2056
2057 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
2058 return TRUE;
2059}
2060
2061BOOL SdlRail::window_cached_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo,
2062 const WINDOW_CACHED_ICON_ORDER* windowCachedIcon)
2063{
2064 WINPR_ASSERT(orderInfo);
2065 WINPR_ASSERT(windowCachedIcon);
2066 auto rail = SdlRail::get(context);
2067 if (!rail)
2068 return FALSE;
2069
2070 std::unique_lock lock(rail->_windowsLock);
2071 auto appWindow = rail->getWindow(orderInfo->windowId);
2072 if (!appWindow)
2073 return TRUE;
2074
2075 const CACHED_ICON_INFO& cached = windowCachedIcon->cachedIcon;
2076 auto* icon = rail->iconCacheLookup(cached.cacheId, cached.cacheEntry);
2077 if (!icon || icon->bgra.empty())
2078 {
2079 WLog_WARN(TAG,
2080 "cached icon %02" PRIX32 ":%04" PRIX32 " not in cache (window 0x%08" PRIx32 ")",
2081 cached.cacheId, cached.cacheEntry, orderInfo->windowId);
2082 return TRUE;
2083 }
2084 appWindow->setIcon(*icon);
2085
2086 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
2087 return TRUE;
2088}
2089
2090BOOL SdlRail::window_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo)
2091{
2092 WINPR_ASSERT(orderInfo);
2093 auto rail = SdlRail::get(context);
2094 if (!rail)
2095 return FALSE;
2096
2097 /* Mark only; erased on the main thread (paint) so the SDL window dies there. */
2098 std::unique_lock lock(rail->_windowsLock);
2099 auto appWindow = rail->getWindow(orderInfo->windowId);
2100 if (appWindow)
2101 {
2102 WLog_DBG(TAG, "window delete id=0x%08" PRIx32, orderInfo->windowId);
2103 appWindow->markDeleted();
2104 rail->_context->railWindowInfoChanged(orderInfo->windowId);
2105 }
2106
2107 /* Clear cached references to deleted window id. */
2108 if (rail->_localMove.id == orderInfo->windowId)
2109 rail->_localMove = {};
2110 if (rail->_clientActiveId == orderInfo->windowId)
2111 rail->_clientActiveId = 0;
2112 if (rail->_focusedAppId == orderInfo->windowId)
2113 rail->_focusedAppId = 0;
2114
2115 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
2116 return TRUE;
2117}
2118
2119BOOL SdlRail::monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo,
2120 const MONITORED_DESKTOP_ORDER* monitoredDesktop)
2121{
2122 WINPR_ASSERT(orderInfo);
2123 WINPR_ASSERT(monitoredDesktop);
2124 auto rail = SdlRail::get(context);
2125 if (!rail)
2126 return FALSE;
2127
2128 /* Launch the RemoteApp on DESKTOP_ARC_COMPLETED, like xf_rail_monitored_desktop. */
2129 if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ARC_COMPLETED)
2130 {
2131 rail->enableRemoteAppMode(true);
2132 const char* app =
2133 freerdp_settings_get_string(context->settings, FreeRDP_RemoteApplicationProgram);
2134 /* ARC_COMPLETED also follows every secure desktop (UAC): start the app only once. */
2135 if (app && (strnlen(app, 1) > 0) && !rail->_appStarted)
2136 {
2137 WLog_DBG(TAG, "RAIL mode enabled (monitored desktop); launching '%s'", app);
2138 if (client_rail_server_start_cmd(rail->_rail) != CHANNEL_RC_OK)
2139 {
2140 WLog_ERR(TAG, "client_rail_server_start_cmd failed for '%s'", app);
2141 return FALSE;
2142 }
2143 rail->_appStarted = true;
2144 }
2145 }
2146
2147 /* Authoritative top-level z-order (windowIds[0] topmost); capture it, paint() realizes it. */
2148 if (orderInfo->fieldFlags &
2149 (WINDOW_ORDER_FIELD_DESKTOP_ZORDER | WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND))
2150 {
2151 std::unique_lock lock(rail->_windowsLock);
2152 if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND)
2153 {
2154 /* Server changed active window: sync our ClientActivate dedup to avoid skipping
2155 * re-clicks. */
2156 rail->_clientActiveId = monitoredDesktop->activeWindowId;
2157 }
2158 if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER)
2159 {
2160 if (monitoredDesktop->windowIds && (monitoredDesktop->numWindowIds > 0))
2161 rail->_zOrder.assign(monitoredDesktop->windowIds,
2162 monitoredDesktop->windowIds + monitoredDesktop->numWindowIds);
2163 else
2164 rail->_zOrder.clear();
2165 rail->_zOrderDirty = true;
2166 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE); /* wake the main thread to restack */
2167 }
2168 }
2169 return TRUE;
2170}
2171
2172BOOL SdlRail::non_monitored_desktop(rdpContext* context,
2173 WINPR_ATTR_UNUSED const WINDOW_ORDER_INFO* orderInfo)
2174{
2175 WINPR_ASSERT(orderInfo);
2176 auto rail = SdlRail::get(context);
2177 if (rail)
2178 {
2179 WLog_DBG(TAG, "RAIL mode disabled (non-monitored desktop)");
2180 rail->enableRemoteAppMode(false);
2181 }
2182 return TRUE;
2183}
bool windowGeometry(uint64_t id, SDL_Window *&window, int &width, int &height)
Definition sdl_rail.cpp:67
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 INT32 freerdp_settings_get_int32(const rdpSettings *settings, FreeRDP_Settings_Keys_Int32 id)
Returns a INT32 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_get_bool(const rdpSettings *settings, FreeRDP_Settings_Keys_Bool id)
Returns a boolean settings value.
#define TAG