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