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
28#include <freerdp/freerdp.h>
29#include <freerdp/log.h>
30#include <freerdp/codec/color.h>
31#include <freerdp/codec/region.h>
32#include <freerdp/client/rail.h>
33
34#include "sdl_rail.hpp"
35#include "sdl_context.hpp"
36#include "sdl_rail_platform.hpp"
37#include "sdl_types.hpp"
38#include "sdl_utils.hpp"
39#include "sdl_wayland.hpp"
40#include "sdl_x11.hpp"
41
42#define TAG CLIENT_TAG("sdl.rail")
43
44SdlRail::SdlRail(SdlContext* context) : _context(context)
45{
46}
47
48SdlRail::~SdlRail() = default;
49
50SdlRail* SdlRail::get(rdpContext* context)
51{
52 auto sdl = get_context(context);
53 if (!sdl)
54 return nullptr;
55 return &sdl->getRailChannelContext();
56}
57
58SdlRailWindow* SdlRail::getWindow(uint64_t id)
59{
60 auto it = _windows.find(id);
61 return (it == _windows.end()) ? nullptr : &it->second;
62}
63
64SdlRailWindow* SdlRail::getWindowBySdlId(SDL_WindowID id)
65{
66 if (id == 0)
67 return nullptr;
68 for (auto& it : _windows)
69 {
70 if (it.second.sdlId() == id)
71 return &it.second;
72 }
73 return nullptr;
74}
75
76/* Test if popup adjoins window edge from outside. */
77static bool adjoinsOutside(const SDL_Rect& popup, const SDL_Rect& win)
78{
79 SDL_Rect hit{};
80 if (SDL_GetRectIntersection(&popup, &win, &hit))
81 return false;
82 const SDL_Rect grown = { win.x - 1, win.y - 1, win.w + 2, win.h + 2 };
83 return SDL_GetRectIntersection(&popup, &grown, &hit);
84}
85
86/* Fullscreen popups (e.g. slide shows) act as toplevels and can parent popups. */
87static bool canParentPopup(const SdlRailWindow& w)
88{
89 return (!w.isPopup() || w.isFullscreen()) && (w.window() != nullptr);
90}
91
92SdlRailWindow* SdlRail::resolveParent(uint64_t ownerId)
93{
94 auto* owner = getWindow(ownerId);
95 if (owner && canParentPopup(*owner))
96 return owner;
97 return nullptr;
98}
99
100/* Pick a popup's parent app window: ownerWindowId -> geometric containment -> focused -> any app.
101 */
102SdlRailWindow* SdlRail::resolvePopupParent(const SdlRailWindow& popup)
103{
104 SdlRailWindow* chosen = resolveParent(popup.owner());
105 if (!chosen)
106 {
107 const SDL_Rect pr = popup.windowRect();
108 const SDL_Point origin = { pr.x, pr.y };
109 for (uint32_t id : _zOrder)
110 {
111 auto* w = getWindow(id);
112 if (!w || !canParentPopup(*w))
113 continue;
114 const SDL_Rect wr = w->windowRect();
115 if (SDL_PointInRect(&origin, &wr))
116 {
117 chosen = w;
118 break;
119 }
120 }
121 if (!chosen)
122 {
123 for (auto& other : _windows)
124 {
125 auto& w = other.second;
126 if (!canParentPopup(w))
127 continue;
128 const SDL_Rect wr = w.windowRect();
129 if (SDL_PointInRect(&origin, &wr))
130 {
131 chosen = &w;
132 break;
133 }
134 }
135 }
136 }
137 if (!chosen)
138 chosen = resolveParent(_focusedAppId);
139 if (!chosen)
140 {
141 for (auto& other : _windows)
142 {
143 auto& w = other.second;
144 if (canParentPopup(w))
145 {
146 chosen = &w;
147 break;
148 }
149 }
150 }
151 return chosen;
152}
153
154/* Identify companion shadow frames adjoining owner window. */
155bool SdlRail::isShadowFrame(const SdlRailWindow& popup)
156{
157 if (!popup.isLayered())
158 return false;
159 const SDL_Rect pr = popup.windowRect();
160 for (auto& other : _windows)
161 {
162 auto& w = other.second;
163 if (canParentPopup(w) && adjoinsOutside(pr, w.windowRect()))
164 return true;
165 }
166 return false;
167}
168
169bool SdlRail::ownsWindow(SDL_WindowID id)
170{
171 std::unique_lock lock(_windowsLock);
172 return getWindowBySdlId(id) != nullptr;
173}
174
175void SdlRail::invalidateWindow(SDL_WindowID id)
176{
177 std::unique_lock lock(_windowsLock);
178 auto* appWindow = getWindowBySdlId(id);
179 if (!appWindow)
180 return;
181 appWindow->invalidateAll();
182 lock.unlock();
183 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
184}
185
186/* Caller holds _windowsLock. */
187void SdlRail::sendSystemCommand(SdlRailWindow* appWindow, uint16_t command)
188{
189 if (!_rail || !_rail->ClientSystemCommand)
190 return;
191 RAIL_SYSCOMMAND_ORDER syscommand = {};
192 syscommand.windowId = static_cast<UINT32>(appWindow->id());
193 syscommand.command = command;
194 std::ignore = _rail->ClientSystemCommand(_rail, &syscommand);
195}
196
197void SdlRail::sendWorkArea(const SDL_Rect& area)
198{
199 if (!_rail || !_rail->ClientSystemParam || (area.w <= 0) || (area.h <= 0))
200 return;
201 if (SDL_RectsEqual(&area, &_sentWorkArea))
202 return;
203
204 RAIL_SYSPARAM_ORDER param = {};
205 /* ClientSystemParam dispatches on the params mask, not .param. */
206 param.params = SPI_MASK_SET_WORK_AREA;
207 param.workArea.left = WINPR_ASSERTING_INT_CAST(UINT16, area.x);
208 param.workArea.top = WINPR_ASSERTING_INT_CAST(UINT16, area.y);
209 param.workArea.right = WINPR_ASSERTING_INT_CAST(UINT16, area.x + area.w);
210 param.workArea.bottom = WINPR_ASSERTING_INT_CAST(UINT16, area.y + area.h);
211 if (_rail->ClientSystemParam(_rail, &param) == CHANNEL_RC_OK)
212 _sentWorkArea = area;
213}
214
215void SdlRail::handleMaximized(SDL_WindowID id)
216{
217 std::unique_lock lock(_windowsLock);
218 auto* appWindow = getWindowBySdlId(id);
219 if (!appWindow || appWindow->isPopup() || !appWindow->window())
220 return;
221 /* Skip the echo of reconcile's own SDL_MaximizeWindow (railMaximized already set). */
222 if (appWindow->railMaximized())
223 {
224 WLog_DBG(TAG, "local maximize skipped id=0x%08" PRIx32 " (already rail-maximized)",
225 static_cast<UINT32>(appWindow->id()));
226 return;
227 }
228 appWindow->setRailMaximized(true);
229 /* Force full repaint (skips dirty-rect). */
230 appWindow->invalidateAll();
231 /* Defer SC_MAXIMIZE if modal move loop is still open. */
232 if (appWindow->loopEndPending())
233 {
234 appWindow->deferMaximize();
235 WLog_DBG(TAG, "local maximize deferred id=0x%08" PRIx32 " (modal loop open)",
236 static_cast<UINT32>(appWindow->id()));
237 }
238 else
239 {
240 WLog_DBG(TAG, "local maximize id=0x%08" PRIx32 " -> SC_MAXIMIZE",
241 static_cast<UINT32>(appWindow->id()));
242 sendSystemCommand(appWindow, SC_MAXIMIZE);
243 }
244 lock.unlock();
245 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
246}
247
248void SdlRail::handleMinimized(SDL_WindowID id)
249{
250 std::unique_lock lock(_windowsLock);
251 auto* appWindow = getWindowBySdlId(id);
252 if (!appWindow || appWindow->isPopup() || !appWindow->window())
253 return;
254 if (appWindow->railMinimized())
255 return; /* echo of reconcile's own SDL_MinimizeWindow */
256 appWindow->setRailMinimized(true);
257 WLog_DBG(TAG, "local minimize id=0x%08" PRIx32 " -> SC_MINIMIZE",
258 static_cast<UINT32>(appWindow->id()));
259 sendSystemCommand(appWindow, SC_MINIMIZE);
260}
261
262void SdlRail::handleClose(SDL_WindowID id)
263{
264 std::unique_lock lock(_windowsLock);
265 auto* appWindow = getWindowBySdlId(id);
266 if (!appWindow || !appWindow->window())
267 return;
268 WLog_DBG(TAG, "local close id=0x%08" PRIx32 " -> SC_CLOSE",
269 static_cast<UINT32>(appWindow->id()));
270 sendSystemCommand(appWindow, SC_CLOSE);
271}
272
273void SdlRail::handleRestored(SDL_WindowID id)
274{
275 std::unique_lock lock(_windowsLock);
276 auto* appWindow = getWindowBySdlId(id);
277 if (!appWindow || appWindow->isPopup() || !appWindow->window())
278 return;
279 /* Resolve which state a RESTORED event ends; both clear = echo of our own restore, skip. */
280 if (appWindow->railMinimized())
281 appWindow->setRailMinimized(false);
282 else if (appWindow->railMaximized())
283 appWindow->setRailMaximized(false);
284 else
285 return;
286 WLog_DBG(TAG, "local restore id=0x%08" PRIx32 " -> SC_RESTORE",
287 static_cast<UINT32>(appWindow->id()));
288 appWindow->invalidateAll();
289 sendSystemCommand(appWindow, SC_RESTORE);
290 lock.unlock();
291 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
292}
293
294void SdlRail::handleFocus(SDL_WindowID id, bool gained)
295{
296 std::unique_lock lock(_windowsLock);
297 auto appWindow = getWindowBySdlId(id);
298 if (!appWindow || (appWindow->isPopup() && !appWindow->isFullscreen()) || !appWindow->window())
299 return;
300
301 /* Ignore focus loss while dragging: mapping restore shadow frames can steal focus
302 * and cancel the server modal loop. */
303 if (!gained && (_localMove.id == static_cast<uint32_t>(appWindow->id())))
304 return;
305
306 /* Fallback parent for orphaned popups. */
307 if (gained)
308 _focusedAppId = appWindow->id();
309
310 /* ClientActivate only. Do NOT SDL_RaiseWindow to avoid WM focus loops. */
311 const auto wid = static_cast<uint32_t>(appWindow->id());
312 sendClientActivate(wid, gained);
313}
314
315/* Send RAIL_ACTIVATE_ORDER and track the active window id. Caller holds _windowsLock. */
316void SdlRail::sendClientActivate(uint32_t wid, bool enabled)
317{
318 if (!_rail || !_rail->ClientActivate)
319 return;
320 if (enabled)
321 _clientActiveId = wid;
322 RAIL_ACTIVATE_ORDER activate = {};
323 activate.windowId = wid;
324 activate.enabled = enabled;
325 std::ignore = _rail->ClientActivate(_rail, &activate);
326}
327
328/* Activate clicked window on server to route input correctly. */
329void SdlRail::ensureActive(SDL_WindowID id)
330{
331 std::unique_lock lock(_windowsLock);
332 auto* appWindow = getWindowBySdlId(id);
333 if (!appWindow || (appWindow->isPopup() && !appWindow->isFullscreen()) || !appWindow->window())
334 return;
335 const auto wid = static_cast<uint32_t>(appWindow->id());
336 if (wid == _clientActiveId)
337 return;
338 sendClientActivate(wid, true);
339}
340
341bool SdlRail::translateToServer(SDL_WindowID id, float& x, float& y)
342{
343 std::unique_lock lock(_windowsLock);
344 auto* appWindow = getWindowBySdlId(id);
345 if (!appWindow)
346 return false;
347 SDL_FPoint rpos = { x, y };
348 if (auto* renderer = appWindow->renderer())
349 (void)SDL_RenderCoordinatesFromWindow(renderer, x, y, &rpos.x, &rpos.y);
350 /* Window-local to server-absolute, aligned with surface blit anchor. */
351 const SDL_Point origin = appWindow->serverOrigin();
352 x = rpos.x + static_cast<float>(origin.x);
353 y = rpos.y + static_cast<float>(origin.y);
354 return true;
355}
356
357SdlRailWindow* SdlRail::addWindow(uint64_t id, const SDL_Rect& rect)
358{
359 /* Move deleted entry aside so new window can reuse the ID. */
360 auto it = _windows.find(id);
361 if ((it != _windows.end()) && it->second.isDeleted())
362 {
363 WLog_DBG(TAG, "window recreate id=0x%08" PRIx32 " reused a deleted entry",
364 static_cast<uint32_t>(id));
365 _deadWindows.insert(_windows.extract(it));
366 }
367 /* emplace is a no-op if the id already exists; either way first->second is the window. */
368 auto res = _windows.emplace(std::piecewise_construct, std::forward_as_tuple(id),
369 std::forward_as_tuple(id, rect));
370 return &res.first->second;
371}
372
373void SdlRail::enableRemoteAppMode(bool enable)
374{
375 _enabled = enable;
376}
377
378bool SdlRail::paint(SDL_Surface* primary, SDL_PixelFormat fallbackFormat,
379 const std::vector<SDL_Rect>& damage)
380{
381 if (!_enabled)
382 return true;
383
384 std::unique_lock lock(_windowsLock);
385
386 /* Report workarea once (avoids maximizing under local panels). */
387 if (_sentWorkArea.w == 0)
388 {
389 SDL_Rect usable{};
390 if (SDL_GetDisplayUsableBounds(SDL_GetPrimaryDisplay(), &usable))
391 sendWorkArea(usable);
392 }
393
394 /* Cascade deletion to child popups whose SDL parent was deleted. */
395 for (auto& [wid, win] : _windows)
396 {
397 if (win.isDeleted() || !win.window())
398 continue;
399 for (SDL_Window* p = SDL_GetWindowParent(win.window()); p; p = SDL_GetWindowParent(p))
400 {
401 auto* owner = getWindowBySdlId(SDL_GetWindowID(p));
402 if (!owner || owner->isDeleted())
403 {
404 win.markDeleted();
405 break;
406 }
407 }
408 }
409
410 /* Erase deleted windows deepest child first to avoid SDL child double-free. */
411 std::vector<std::pair<size_t, uint64_t>> dead;
412 for (auto& [wid, win] : _windows)
413 {
414 if (!win.isDeleted())
415 continue;
416 size_t depth = 0;
417 for (SDL_Window* p = win.window() ? SDL_GetWindowParent(win.window()) : nullptr; p;
418 p = SDL_GetWindowParent(p))
419 depth++;
420 dead.emplace_back(depth, wid);
421 }
422 std::sort(dead.begin(), dead.end(),
423 [](const auto& a, const auto& b) { return a.first > b.first; });
424 for (const auto& [depth, wid] : dead)
425 _windows.erase(wid);
426 /* Windows displaced by a same-id recreate (addWindow) also die here, on the main thread. */
427 _deadWindows.clear();
428
429 /* App windows first so popup parents exist before their popups. */
430 for (auto& it : _windows)
431 {
432 auto& win = it.second;
433 if (win.isPopup())
434 continue;
435 /* Parent owned dialogs to owner. */
436 SDL_Window* parent = nullptr;
437 SDL_Rect parentRect{};
438 auto* owner = resolveParent(win.owner());
439 if (owner && (owner != &win))
440 {
441 parent = owner->window();
442 parentRect = owner->outerRect(); /* the SDL window's on-screen geometry */
443 }
444 win.paint(primary, fallbackFormat, damage, parent, parentRect);
445 /* Adopt WM-refused geometry and update server. */
446 SDL_Rect refusedOuter{};
447 if (win.takeWmOverride(refusedOuter))
448 {
449 const SDL_Rect rect = win.serverRect(refusedOuter);
450 const SDL_Rect cur = win.windowRect();
451 WLog_DBG(TAG,
452 "wm-refused adopt id=0x%08" PRIx32
453 " outer=%dx%d -> srv=%d,%d %dx%d (was %dx%d)",
454 static_cast<uint32_t>(win.id()), refusedOuter.w, refusedOuter.h, rect.x,
455 rect.y, rect.w, rect.h, cur.w, cur.h);
456 if (!SDL_RectsEqual(&rect, &cur))
457 sendClientWindowMove(&win, rect);
458 win.adoptLocalGeometry(rect);
459 }
460 }
461
462 /* Request full repaint after first window is realized (fixes reconnect blank windows). */
463 if (!_refreshSent)
464 {
465 for (auto& it : _windows)
466 {
467 if (it.second.isPopup() || !it.second.window())
468 continue;
469 auto* ctx = &_context->common()->context;
470 const auto dw = static_cast<UINT16>(
471 freerdp_settings_get_uint32(ctx->settings, FreeRDP_DesktopWidth));
472 const auto dh = static_cast<UINT16>(
473 freerdp_settings_get_uint32(ctx->settings, FreeRDP_DesktopHeight));
474 const RECTANGLE_16 all = { 0, 0, dw, dh };
475 if (ctx->update && ctx->update->RefreshRect)
476 (void)ctx->update->RefreshRect(ctx, 1, &all);
477 _refreshSent = true;
478 WLog_DBG(TAG, "refresh-rect sent (first app window realized)");
479 break;
480 }
481 }
482
483 for (auto& it : _windows)
484 {
485 auto& popup = it.second;
486 if (!popup.isPopup())
487 continue;
488
489 /* Latch shadow frame classification once identified. */
490 if (!popup.isFrame() && isShadowFrame(popup))
491 popup.setFrame(true);
492
493 /* Anchor drop shadow to adjoining visible popup. */
494 if (popup.isLayered())
495 {
496 constexpr int reach = 48; /* shadow offset+blur spread from its popup, server px */
497 const SDL_Rect sr = popup.windowRect();
498 bool anchored = false;
499 for (auto& other : _windows)
500 {
501 auto& cand = other.second;
502 if ((&cand == &popup) || !cand.isPopup() || cand.isLayered() || !cand.window() ||
503 ((SDL_GetWindowFlags(cand.window()) & SDL_WINDOW_HIDDEN) != 0))
504 continue;
505 SDL_Rect zone = cand.windowRect();
506 zone.x -= reach;
507 zone.y -= reach;
508 zone.w += 2 * reach;
509 zone.h += 2 * reach;
510 /* Shadow must be contained within reach zone to distinguish popup shadows from
511 * app frame edge shadows. */
512 const bool inside = (sr.x >= zone.x) && (sr.y >= zone.y) &&
513 (sr.x + sr.w <= zone.x + zone.w) &&
514 (sr.y + sr.h <= zone.y + zone.h);
515 if (inside)
516 {
517 anchored = true;
518 break;
519 }
520 }
521 popup.setShadowAnchored(anchored);
522 }
523
524 SdlRailWindow* chosen = nullptr;
525 /* Existing popups have an immutable SDL parent; position against it. */
526 if (auto* pw = popup.window())
527 {
528 SDL_Window* p = SDL_GetWindowParent(pw);
529 chosen = p ? getWindowBySdlId(SDL_GetWindowID(p)) : nullptr;
530 }
531 else
532 {
533 chosen = resolvePopupParent(popup);
534 if (!chosen)
535 WLog_DBG(TAG, "popup id=0x%08" PRIx32 " has no parent app window",
536 static_cast<UINT32>(popup.id()));
537 }
538
539 SDL_Window* parent = nullptr;
540 SDL_Rect parentRect{};
541 if (chosen)
542 {
543 parent = chosen->window();
544 parentRect = chosen->outerRect(); /* the SDL window's on-screen geometry */
545 }
546 popup.paint(primary, fallbackFormat, damage, parent, parentRect);
547 }
548
549 /* All live windows now have real X11 handles: realize the server's z-order. */
550 applyZOrder();
551 return true;
552}
553
554/* Caller holds _windowsLock (main thread). */
555void SdlRail::applyZOrder()
556{
557 if (!_zOrderDirty)
558 return;
559 /* X11 only: Wayland/Win/macOS have no reparenting-safe, focus-neutral restack path here. */
560 if (!railPlatformCaps().supportsRestack)
561 {
562 _zOrderDirty = false;
563 return;
564 }
565 /* Never restack the window the WM is actively dragging; keep dirty and retry after the move. */
566 if (_localMove.id != 0)
567 {
568 WLog_VRB(TAG, "zorder apply deferred: local move 0x%08" PRIx32 " active", _localMove.id);
569 return;
570 }
571 /* Restack top-level windows (skip popups and hidden windows). */
572 std::vector<SDL_Window*> stack;
573 std::vector<uint32_t> applied;
574 stack.reserve(_zOrder.size());
575 applied.reserve(_zOrder.size());
576 for (uint32_t id : _zOrder)
577 {
578 auto* w = getWindow(id);
579 if (w && !w->isPopup() && w->window() &&
580 ((SDL_GetWindowFlags(w->window()) & SDL_WINDOW_HIDDEN) == 0))
581 {
582 stack.push_back(w->window());
583 applied.push_back(id);
584 }
585 }
586 /* Dedup against the restacked set; menus and unrealized windows are filtered out. */
587 if (applied == _appliedZOrder)
588 {
589 _zOrderDirty = false;
590 return;
591 }
592 if (stack.size() >= 2)
593 {
594 std::ignore = sdl_x11_restack_windows(stack);
595 }
596
597 _appliedZOrder = std::move(applied);
598 _zOrderDirty = false;
599}
600
601UINT SdlRail::updateWindowFromSurface(gdiGfxSurface* surface)
602{
603 if (!surface)
604 return CHANNEL_RC_OK;
605
606 std::unique_lock lock(_windowsLock);
607 auto appWindow = getWindow(surface->windowId);
608 if (!appWindow)
609 {
610 /* Drop GFX surface for unknown windows (repaints later). */
611 WLog_VRB(TAG, "gfx surface for untracked id=0x%08" PRIx64, surface->windowId);
612 return CHANNEL_RC_OK;
613 }
614
615 /* Clamp mapped dimensions to allocated surface bounds. */
616 const uint32_t w =
617 std::min(surface->mappedWidth ? surface->mappedWidth : surface->width, surface->width);
618 const uint32_t h =
619 std::min(surface->mappedHeight ? surface->mappedHeight : surface->height, surface->height);
620
621 /* Consume per-frame damage. */
622 UINT32 nbRects = 0;
623 const RECTANGLE_16* rects = region16_rects(&surface->invalidRegion, &nbRects);
624 /* Skip undamaged surfaces during EndFrame. */
625 const bool remapped = appWindow->takeSurfaceChange(surface->surfaceId);
626 if ((nbRects == 0) && !remapped)
627 return CHANNEL_RC_OK;
628 appWindow->updateGfxSurface(surface->data, surface->scanline, w, h, rects, nbRects,
629 surface->format);
630 region16_clear(&surface->invalidRegion);
631
632 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
633 return CHANNEL_RC_OK;
634}
635
636UINT SdlRail::UpdateWindowFromSurface(RdpgfxClientContext* context, gdiGfxSurface* surface)
637{
638 WINPR_ASSERT(context);
639 auto gdi = static_cast<rdpGdi*>(context->custom);
640 if (!gdi || !gdi->context)
641 return CHANNEL_RC_OK;
642 auto sdl = get_context(gdi->context);
643 if (!sdl)
644 return CHANNEL_RC_OK;
645 return sdl->getRailChannelContext().updateWindowFromSurface(surface);
646}
647
648bool SdlRail::init(RailClientContext* rail)
649{
650 _rail = rail;
651 if (!rail)
652 return false;
653
654 registerUpdateCallbacks(_context->context()->update);
655
656 {
657 std::unique_lock lock(_windowsLock);
658 /* Move previous windows to deadWindows for main-thread teardown. */
659 for (auto it = _windows.begin(); it != _windows.end();)
660 {
661 auto cur = it++;
662 _deadWindows.insert(_windows.extract(cur));
663 }
664 auto* settings = _context->context()->settings;
665 const uint32_t caches =
666 freerdp_settings_get_uint32(settings, FreeRDP_RemoteAppNumIconCaches);
667 _iconCacheEntries =
668 freerdp_settings_get_uint32(settings, FreeRDP_RemoteAppNumIconCacheEntries);
669 _iconCache.assign(static_cast<size_t>(caches) * _iconCacheEntries, {});
670 }
671
672 rail->custom = this;
673 rail->ServerExecuteResult = SdlRail::server_execute_result;
674 /* ServerSystemParam not implemented: the server only sends screensaver state here. */
675 rail->ServerLocalMoveSize = SdlRail::server_local_move_size;
676 rail->ServerMinMaxInfo = SdlRail::server_min_max_info;
677 /* Keep default ServerHandshake. */
678
679 WLog_WARN(TAG, "RemoteApp/RAIL support in the SDL client is experimental");
680 const RailPlatformCaps& caps = railPlatformCaps();
681 WLog_DBG(TAG, "RAIL channel initialized: driver=%s positionsReadable=%d transparentWindows=%d",
682 sdl::utils::isWaylandDriver() ? "wayland"
683 : (sdl::utils::isX11Driver() ? "x11" : "other"),
684 caps.positionsReadable ? 1 : 0, caps.supportsTransparentWindows ? 1 : 0);
685#if SDL_VERSION_ATLEAST(3, 4, 10)
686 /* Synchronize WM-driven X11 resizes via _NET_WM_SYNC_REQUEST to prevent torn frames. */
687 if (sdl::utils::isX11Driver())
688 SDL_SetHint(SDL_HINT_VIDEO_X11_ENABLE_XSYNC_EXT, "1");
689#endif
690 return true;
691}
692
693bool SdlRail::uninit(WINPR_ATTR_UNUSED RailClientContext* rail)
694{
695 WINPR_ASSERT(rail);
696 /* Leave rail->custom set: the server callbacks only assert it, so clearing it would crash a
697 * late order in a release build. _enabled gates them instead. */
698 std::unique_lock lock(_windowsLock);
699 _refreshSent = false;
700 /* Reset session and move state on reconnect. */
701 _localMove = {};
702 _sessionMargins = {};
703 _sentWorkArea = {};
704 _clientActiveId = 0;
705 _focusedAppId = 0;
706 _zOrder.clear();
707 _appliedZOrder.clear();
708 _zOrderDirty = false;
709 _iconCache.clear();
710 _iconScratch = {};
711 /* Mark windows for main-thread teardown. */
712 WLog_DBG(TAG, "RAIL channel uninit, marking %zu windows for main-thread teardown",
713 _windows.size());
714 for (auto& kv : _windows)
715 kv.second.markDeleted();
716 _rail = nullptr;
717 _enabled = false;
718 lock.unlock();
719 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
720 return true;
721}
722
723void SdlRail::registerUpdateCallbacks(rdpUpdate* update)
724{
725 WINPR_ASSERT(update);
726 auto window = update->window;
727 WINPR_ASSERT(window);
728
729 window->WindowCreate = SdlRail::window_common;
730 window->WindowUpdate = SdlRail::window_common;
731 window->WindowIcon = SdlRail::window_icon;
732 window->WindowCachedIcon = SdlRail::window_cached_icon;
733 window->WindowDelete = SdlRail::window_delete;
734 window->MonitoredDesktop = SdlRail::monitored_desktop;
735 window->NonMonitoredDesktop = SdlRail::non_monitored_desktop;
736}
737
738/* --- server callbacks --- */
739
740UINT SdlRail::server_execute_result(RailClientContext* context,
741 const RAIL_EXEC_RESULT_ORDER* execResult)
742{
743 WINPR_ASSERT(context);
744 WINPR_ASSERT(execResult);
745 auto rail = static_cast<SdlRail*>(context->custom);
746 WINPR_ASSERT(rail);
747
748 if (execResult->execResult != RAIL_EXEC_S_OK)
749 {
750 WLog_ERR(TAG, "RAIL exec error: execResult=0x%04" PRIx16 " rawResult=0x%08" PRIx32,
751 execResult->execResult, execResult->rawResult);
752 freerdp_abort_connect_context(rail->_context->context());
753 }
754 else
755 {
756 WLog_DBG(TAG, "RemoteApp exec OK, enabling RAIL mode");
757 rail->enableRemoteAppMode(true);
758 }
759 return CHANNEL_RC_OK;
760}
761
762UINT SdlRail::server_local_move_size(RailClientContext* context,
763 const RAIL_LOCALMOVESIZE_ORDER* localMoveSize)
764{
765 WINPR_ASSERT(context);
766 WINPR_ASSERT(localMoveSize);
767
768 /* Start native move/resize to avoid dual-authority geometry races. */
769 if (localMoveSize->isMoveSizeStart && (localMoveSize->moveSizeType >= RAIL_WMSZ_LEFT) &&
770 (localMoveSize->moveSizeType <= RAIL_WMSZ_MOVE))
771 {
772 WLog_DBG(TAG, "server move/size start id=0x%08" PRIx32 " type=%" PRIu16 " pos=%d,%d",
773 localMoveSize->windowId, localMoveSize->moveSizeType, localMoveSize->posX,
774 localMoveSize->posY);
775 (void)sdl_push_user_event(SDL_EVENT_USER_RAIL_MOVE, localMoveSize->windowId,
776 static_cast<int>(localMoveSize->moveSizeType));
777 }
778 else if (!localMoveSize->isMoveSizeStart)
779 {
780 WLog_DBG(TAG, "server move/size end id=0x%08" PRIx32, localMoveSize->windowId);
781 /* Server ended the move/size: resume applying geometry + input (covers Wayland move). */
782 auto rail = static_cast<SdlRail*>(context->custom);
783 if (rail)
784 {
785 std::unique_lock lock(rail->_windowsLock);
786 /* Ignore server END order during Wayland resize unless unstarted. */
787 const bool ownedByWaylandResize = rail->_localMove.wayland &&
788 (rail->_localMove.id == localMoveSize->windowId) &&
789 rail->_localMove.sawResize;
790 if (!ownedByWaylandResize)
791 {
792 if (auto* appWindow = rail->getWindow(localMoveSize->windowId))
793 appWindow->setLocalMoveActive(false);
794 if (rail->_localMove.id == localMoveSize->windowId)
795 {
796 if (rail->_localMove.wayland)
797 {
798 /* Wayland drag completed. */
799 rail->_localMove = {};
800 if (auto* appWindow = rail->getWindow(localMoveSize->windowId))
801 appWindow->invalidateAll();
802 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
803 }
804 else
805 {
806 /* Server ended drag loop early. */
807 rail->_localMove.serverEnded = true;
808 }
809 }
810 }
811 /* Execute deferred actions now that modal loop has closed. */
812 auto* appWindow = rail->getWindow(localMoveSize->windowId);
813 if (appWindow && appWindow->loopEndPending())
814 {
815 const auto actions = appWindow->takeLoopEnd();
816 if (actions.maximize && appWindow->railMaximized())
817 {
818 WLog_DBG(TAG, "deferred SC_MAXIMIZE id=0x%08" PRIx32, localMoveSize->windowId);
819 rail->sendSystemCommand(appWindow, SC_MAXIMIZE);
820 }
821 if (actions.snap)
822 {
823 /* Send deferred snap resize. */
824 WLog_DBG(TAG, "deferred snap resize id=0x%08" PRIx32 " rect=%d,%d %dx%d",
825 localMoveSize->windowId, actions.snapRect.x, actions.snapRect.y,
826 actions.snapRect.w, actions.snapRect.h);
827 rail->sendClientWindowMove(appWindow, actions.snapRect);
828 }
829 /* WM resize can land after button-up (e.g. KDE tiling) while syncGeometry was
830 * latched out. Sync post-loop geometry now; also needed for deferred snaps where
831 * snapRect preceded the WM's final tile size. */
832 if (appWindow->window() && !appWindow->effectivelyMaximized() &&
833 !appWindow->localMoveSizeChanged())
834 {
835 const SDL_WindowID sdlId = appWindow->sdlId();
836 lock.unlock();
837 rail->syncGeometry(sdlId);
838 }
839 }
840 }
841 }
842 return CHANNEL_RC_OK;
843}
844
845/* X11 only: suppress button-up during modal loop. */
846bool SdlRail::suppressServerInput(SDL_WindowID id)
847{
848 std::unique_lock lock(_windowsLock);
849 if (_localMove.id == 0)
850 return false;
851 auto* appWindow = getWindowBySdlId(id);
852 return appWindow && appWindow->localMoveActive() && !_localMove.wayland;
853}
854
855bool SdlRail::suppressServerMotion(SDL_WindowID id)
856{
857 std::unique_lock lock(_windowsLock);
858 if (_localMove.id == 0)
859 return false;
860 auto* appWindow = getWindowBySdlId(id);
861 /* Suppress motion events during active local move. */
862 return appWindow && appWindow->localMoveActive();
863}
864
865/* RAIL_WMSZ_* -> _NET_WM_MOVERESIZE direction (0..7 = resize edges, 8 = move). */
866static int railToNetDirection(uint16_t moveType)
867{
868 switch (moveType)
869 {
870 case RAIL_WMSZ_TOPLEFT:
871 return 0;
872 case RAIL_WMSZ_TOP:
873 return 1;
874 case RAIL_WMSZ_TOPRIGHT:
875 return 2;
876 case RAIL_WMSZ_RIGHT:
877 return 3;
878 case RAIL_WMSZ_BOTTOMRIGHT:
879 return 4;
880 case RAIL_WMSZ_BOTTOM:
881 return 5;
882 case RAIL_WMSZ_BOTTOMLEFT:
883 return 6;
884 case RAIL_WMSZ_LEFT:
885 return 7;
886 case RAIL_WMSZ_MOVE:
887 default:
888 return 8;
889 }
890}
891
892/* RAIL_WMSZ_* <-> XDG_TOPLEVEL_RESIZE_EDGE_* edge mappings. */
893static constexpr struct
894{
895 uint16_t rail;
896 uint32_t xdg;
897} kRailXdgEdges[] = {
898 { RAIL_WMSZ_TOP, 1 }, { RAIL_WMSZ_BOTTOM, 2 }, { RAIL_WMSZ_LEFT, 4 },
899 { RAIL_WMSZ_TOPLEFT, 5 }, { RAIL_WMSZ_BOTTOMLEFT, 6 }, { RAIL_WMSZ_RIGHT, 8 },
900 { RAIL_WMSZ_TOPRIGHT, 9 }, { RAIL_WMSZ_BOTTOMRIGHT, 10 },
901};
902
903/* RAIL_WMSZ_* -> XDG_TOPLEVEL_RESIZE_EDGE_* (0 = none, e.g. RAIL_WMSZ_MOVE). */
904static uint32_t railToXdgEdge(uint16_t moveType)
905{
906 for (const auto& e : kRailXdgEdges)
907 if (e.rail == moveType)
908 return e.xdg;
909 return 0;
910}
911
912/* Which window edges a RAIL_WMSZ_* drag moves; the opposite edges stay anchored. */
913struct RailEdges
914{
915 bool left = false;
916 bool right = false;
917 bool top = false;
918 bool bottom = false;
919};
920static RailEdges railEdges(uint16_t t)
921{
922 return { (t == RAIL_WMSZ_TOPLEFT) || (t == RAIL_WMSZ_LEFT) || (t == RAIL_WMSZ_BOTTOMLEFT),
923 (t == RAIL_WMSZ_TOPRIGHT) || (t == RAIL_WMSZ_RIGHT) || (t == RAIL_WMSZ_BOTTOMRIGHT),
924 (t == RAIL_WMSZ_TOPLEFT) || (t == RAIL_WMSZ_TOP) || (t == RAIL_WMSZ_TOPRIGHT),
925 (t == RAIL_WMSZ_BOTTOMLEFT) || (t == RAIL_WMSZ_BOTTOM) ||
926 (t == RAIL_WMSZ_BOTTOMRIGHT) };
927}
928
929void SdlRail::handleLocalMoveRequested(uint32_t windowId, uint16_t moveType)
930{
931 const bool wayland = sdl::utils::isWaylandDriver();
932 const bool x11 = sdl::utils::isX11Driver();
933 if (!wayland && !x11)
934 return;
935
936 std::unique_lock lock(_windowsLock);
937 auto appWindow = getWindow(windowId);
938 if (!appWindow || !appWindow->window() || appWindow->isPopup())
939 return;
940
941 const bool isMove = (moveType == RAIL_WMSZ_MOVE);
942 WLog_DBG(TAG, "local move start id=0x%08" PRIx32 " driver=%s type=%" PRIu16 " %s", windowId,
943 wayland ? "wayland" : "x11", moveType, isMove ? "move" : "resize");
944 bool started = false;
945 if (wayland)
946 {
947 /* Wayland: positions unreadable, sizes readable. */
948 if (isMove)
949 started = sdl_wayland_begin_move(appWindow->window());
950 else
951 started = sdl_wayland_begin_resize(appWindow->window(), railToXdgEdge(moveType));
952 if (started && !isMove)
953 {
954 _localMove = {}; /* clear all per-drag state as a unit before latching this drag */
955 _localMove.id = windowId;
956 _localMove.wayland = true;
957 _localMove.type = moveType;
958 }
959 }
960 else
961 {
962 /* X11: hand resize to WM, suppress input. */
963 started = sdl_x11_begin_move_size(appWindow->window(), railToNetDirection(moveType));
964 if (started)
965 {
966 _localMove = {}; /* clear all per-drag state as a unit before latching this drag */
967 _localMove.id = windowId;
968 _localMove.type = moveType;
969 /* Latch drag anchors for release calculation. */
970 _localMove.anchor = _lastPressServer;
971 _localMove.pointer = _lastPointerServer;
972 /* Clear prior loop-end state on new drag. */
973 appWindow->clearLoopEnd();
974 /* Set bit gravity to fixed edge. */
975 const RailEdges e = railEdges(moveType);
976 const int row = e.top ? 2 : (e.bottom ? 0 : 1);
977 const int col = e.left ? 2 : (e.right ? 0 : 1);
978 (void)sdl_x11_set_bit_gravity(appWindow->window(), row * 3 + col + 1);
979 }
980 }
981 /* Drive local frame during X11/Wayland drag. */
982 if (started && (!wayland || !isMove))
983 {
984 appWindow->setLocalMoveActive(true);
985 if (!isMove)
986 {
987 /* Anchor the stale frame to the fixed edge (opposite the dragged one). */
988 const RailEdges e = railEdges(moveType);
989 appWindow->setResizeAnchor(e.left, e.top);
990 }
991 }
992 else if (!started)
993 {
994 WLog_WARN(TAG, "WM move failed for RAIL window 0x%08" PRIx32, windowId);
995 }
996}
997
998/* Send ClientWindowMove with full frame geometry including server margins (caller holds
999 * _windowsLock). */
1000void SdlRail::sendClientWindowMove(SdlRailWindow* appWindow, const SDL_Rect& serverRect)
1001{
1002 const SDL_Rect fm = appWindow->frameMargins();
1003 RAIL_WINDOW_MOVE_ORDER move = {};
1004 move.windowId = static_cast<UINT32>(appWindow->id());
1005 move.left = WINPR_ASSERTING_INT_CAST(INT16, serverRect.x - fm.x);
1006 move.top = WINPR_ASSERTING_INT_CAST(INT16, serverRect.y - fm.y);
1007 move.right = WINPR_ASSERTING_INT_CAST(INT16, serverRect.x + serverRect.w + fm.w);
1008 move.bottom = WINPR_ASSERTING_INT_CAST(INT16, serverRect.y + serverRect.h + fm.h);
1009 if (_rail && _rail->ClientWindowMove &&
1010 (_rail->ClientWindowMove(_rail, &move) != CHANNEL_RC_OK))
1011 WLog_WARN(TAG, "ClientWindowMove failed for RAIL window 0x%08" PRIx32, move.windowId);
1012}
1013
1014/* Report final geometry and adopt locally. */
1015void SdlRail::reportAndAdopt(SdlRailWindow* appWindow, int x, int y, int w, int h)
1016{
1017 /* Local geometry -> server rect: strip the client-side band insets. */
1018 const SDL_Rect rect = appWindow->serverRect({ x, y, w, h });
1019 /* Report outer frame to server (inflate by margins). */
1020 const bool maximized = appWindow->effectivelyMaximized();
1021 /* Report geometry if changed. */
1022 const SDL_Rect cur = appWindow->windowRect();
1023 const bool unchanged = SDL_RectsEqual(&rect, &cur);
1024 if (!maximized && !unchanged)
1025 sendClientWindowMove(appWindow, rect);
1026
1027 /* Adopt WM final geometry and resume input routing. */
1028 if (maximized)
1029 appWindow->setLocalMoveActive(false); /* geometry is WM/server-owned while maximized */
1030 else
1031 appWindow->adoptLocalGeometry(rect);
1032 /* Repaint now: the last presented frame may still be the resize placeholder. */
1033 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
1034}
1035
1036void SdlRail::clampIntoDesktop(int& x, int& y, int w, int h) const
1037{
1038 auto* settings = _context->context()->settings;
1039 const int dw = static_cast<int>(freerdp_settings_get_uint32(settings, FreeRDP_DesktopWidth));
1040 const int dh = static_cast<int>(freerdp_settings_get_uint32(settings, FreeRDP_DesktopHeight));
1041 x = std::clamp(x, 0, std::max(0, dw - w));
1042 y = std::clamp(y, 0, std::max(0, dh - h));
1043}
1044
1045void SdlRail::noteDragResize(SDL_WindowID id, int w, int h)
1046{
1047 std::unique_lock lock(_windowsLock);
1048 if ((_localMove.id == 0) || _localMove.wayland || (_localMove.type != RAIL_WMSZ_MOVE))
1049 return;
1050 auto* appWindow = getWindowBySdlId(id);
1051 if (!appWindow || (static_cast<uint32_t>(appWindow->id()) != _localMove.id))
1052 return;
1053 /* Filter out reconcile echo from server drag-restore. */
1054 if (appWindow->localMoveSizeChanged())
1055 {
1056 const SDL_Rect outer = appWindow->outerRect();
1057 if ((w == outer.w) && (h == outer.h))
1058 return;
1059 }
1060 _localMove.wmSized = true;
1061 _localMove.wmSize = { w, h };
1062}
1063
1064/* Update server work area from maximized window bounds (caller holds _windowsLock). */
1065void SdlRail::reportMaximizedWorkArea(SdlRailWindow* appWindow)
1066{
1067 int w = 0;
1068 int h = 0;
1069 SDL_GetWindowSize(appWindow->window(), &w, &h);
1070 if ((w <= 0) || (h <= 0))
1071 return;
1072 int x = 0;
1073 int y = 0;
1074 if (railPlatformCaps().positionsReadable)
1075 SDL_GetWindowPosition(appWindow->window(), &x, &y);
1076
1077 /* Clip work area within primary display bounds. */
1078 SDL_Rect primary{};
1079 if (!SDL_GetDisplayBounds(SDL_GetPrimaryDisplay(), &primary))
1080 return;
1081 const SDL_Rect area = { x, y, w, h };
1082 SDL_Rect overlap{};
1083 if (!SDL_GetRectIntersection(&area, &primary, &overlap) || !SDL_RectsEqual(&overlap, &area))
1084 return;
1085 sendWorkArea(area);
1086}
1087
1088void SdlRail::syncGeometry(SDL_WindowID id)
1089{
1090 std::unique_lock lock(_windowsLock);
1091 auto* w = getWindowBySdlId(id);
1092 if (!w || !w->window() || w->isDeleted() || w->isPopup())
1093 return;
1094
1095 /* Geometry is server/WM-owned when maximized or minimized. */
1096 if (w->effectivelyMaximized())
1097 {
1098 reportMaximizedWorkArea(w);
1099 return;
1100 }
1101 if (w->railMinimized())
1102 return;
1103
1104 const auto wid = static_cast<uint32_t>(w->id());
1105 /* Skip geometry sync while awaiting server restored rect. */
1106 if (w->localMoveActive() || (_localMove.id == wid) || w->loopEndPending() ||
1107 w->stateTransitionPending() || w->awaitingRestoreRect())
1108 return;
1109
1110 int lw = 0;
1111 int lh = 0;
1112 SDL_GetWindowSize(w->window(), &lw, &lh);
1113 if ((lw <= 0) || (lh <= 0))
1114 return;
1115
1116 /* Ignore invalid zero-content window size updates. */
1117 const SDL_Rect ins = w->insets();
1118 if (((lw - ins.x - ins.w) <= 0) || ((lh - ins.y - ins.h) <= 0))
1119 {
1120 WLog_DBG(TAG, "geometry sync id=0x%08" PRIx32 " %dx%d dropped (content collapsed)", wid, lw,
1121 lh);
1122 return;
1123 }
1124
1125 const SDL_Rect vis = w->outerRect();
1126 const bool posKnown = railPlatformCaps().positionsReadable;
1127 int lx = vis.x;
1128 int ly = vis.y;
1129 if (posKnown)
1130 SDL_GetWindowPosition(w->window(), &lx, &ly);
1131 else
1132 clampIntoDesktop(lx, ly, lw, lh);
1133
1134 /* Check if window settled at applied target. */
1135 if ((lw == vis.w) && (lh == vis.h) && (!posKnown || ((lx == vis.x) && (ly == vis.y))))
1136 {
1137 w->clearGeomApplyPending();
1138 return; /* Ignore self-echo when geometry converged. */
1139 }
1140
1141 /* Drop transient echo events while client geometry application is in flight. */
1142 if (w->geomApplyPending())
1143 {
1144 /* Allow live Wayland compositor resize to advance beyond in-flight apply. */
1145 const bool overtaken = !posKnown && ((lw > vis.w) || (lh > vis.h));
1146 if (!overtaken)
1147 return;
1148 w->clearGeomApplyPending();
1149 }
1150
1151 WLog_DBG(TAG, "geometry sync id=0x%08" PRIx32 " local=%d,%d %dx%d (sync)", wid, lx, ly, lw, lh);
1152 reportAndAdopt(w, lx, ly, lw, lh);
1153}
1154
1155void SdlRail::noteResizeGrab(SDL_WindowID id)
1156{
1157 std::unique_lock lock(_windowsLock);
1158 if (_localMove.id == 0)
1159 return;
1160 auto* appWindow = getWindowBySdlId(id);
1161 /* Confirm compositor pointer grab on mouse leave during active drag resize. */
1162 if (appWindow && (static_cast<uint32_t>(appWindow->id()) == _localMove.id) &&
1163 _localMove.wayland)
1164 _localMove.sawResize = true;
1165}
1166
1167void SdlRail::handleWaylandResize(SDL_WindowID id)
1168{
1169 if (!sdl::utils::isWaylandDriver())
1170 return;
1171 std::unique_lock lock(_windowsLock);
1172 auto* appWindow = getWindowBySdlId(id);
1173 if (!appWindow || appWindow->isPopup() || !appWindow->window())
1174 return;
1175 /* Track resize for active dragged window. */
1176 if (static_cast<uint32_t>(appWindow->id()) == _localMove.id)
1177 {
1178 if (_localMove.wayland)
1179 _localMove.sawResize = true;
1180 return;
1181 }
1182
1183 int w = 0;
1184 int h = 0;
1185 SDL_GetWindowSize(appWindow->window(), &w, &h);
1186 if ((w <= 0) || (h <= 0))
1187 return;
1188
1189 /* Local window size is the OUTER frame (rect + insets; identical off the inset paths). */
1190 const SDL_Rect vis = appWindow->outerRect();
1191 if ((w == vis.w) && (h == vis.h))
1192 return; /* echo of a size we already reported/applied - nothing new */
1193
1194 /* Compositor snap/tile: report via the debounced sync (never from transitional state). */
1195 lock.unlock();
1196 syncGeometry(id);
1197}
1198
1199void SdlRail::completeWaylandResize(bool definitive)
1200{
1201 std::unique_lock lock(_windowsLock);
1202 if ((_localMove.id == 0) || !_localMove.wayland)
1203 return;
1204 /* Finalize drag resize on window enter if resize occurred. */
1205 if (!_localMove.sawResize)
1206 {
1207 if (definitive)
1208 {
1209 if (auto* appWindow = getWindow(_localMove.id))
1210 {
1211 appWindow->setLocalMoveActive(false);
1212 /* Repaint now: the dashed placeholder is on screen and an undamaged window would
1213 * otherwise keep it until the next server frame. */
1214 appWindow->invalidateAll();
1215 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
1216 }
1217 _localMove = {}; /* Snapshot and clear drag state under lock. */
1218 }
1219 return;
1220 }
1221
1222 /* Snapshot and clear drag state atomically under lock. */
1223 const LocalMove drag = _localMove;
1224 _localMove = {};
1225
1226 auto appWindow = getWindow(drag.id);
1227 if (!appWindow || !appWindow->window())
1228 return;
1229
1230 (void)SDL_SyncWindow(appWindow->window());
1231 int w = 0;
1232 int h = 0;
1233 SDL_GetWindowSize(appWindow->window(), &w, &h);
1234
1235 /* Derive Wayland origin from anchor edge. */
1236 const SDL_Rect start = appWindow->windowRect();
1237 const RailEdges e = railEdges(drag.type);
1238 int x = e.left ? (start.x + start.w - w) : start.x;
1239 int y = e.top ? (start.y + start.h - h) : start.y;
1240 clampIntoDesktop(x, y, w, h);
1241 reportAndAdopt(appWindow, x, y, w, h);
1242}
1243
1244void SdlRail::completeLocalMoveIfPending()
1245{
1246 std::unique_lock lock(_windowsLock);
1247 if (_localMove.id == 0)
1248 return;
1249 /* Skip Wayland button-up finalize. */
1250 if (_localMove.wayland)
1251 return;
1252
1253 /* Snapshot and clear drag state atomically under lock. */
1254 const LocalMove drag = _localMove;
1255 _localMove = {};
1256
1257 auto appWindow = getWindow(drag.id);
1258 if (!appWindow || !appWindow->window() || appWindow->isDeleted())
1259 return; /* window gone mid-drag: nothing to release into or report for */
1260
1261 /* Send synthetic button release if WM grab consumed physical release. */
1262 if ((SDL_GetMouseState(nullptr, nullptr) & SDL_BUTTON_LMASK) &&
1263 !(SDL_GetGlobalMouseState(nullptr, nullptr) & SDL_BUTTON_LMASK))
1264 (void)sdl_x11_send_left_button_release(appWindow->window());
1265
1266 /* Finalize WM resize before reading final size. */
1267 (void)SDL_SyncWindow(appWindow->window());
1268
1269 int x = 0;
1270 int y = 0;
1271 int w = 0;
1272 int h = 0;
1273 SDL_GetWindowSize(appWindow->window(), &w, &h);
1274 SDL_GetWindowPosition(appWindow->window(), &x, &y);
1275 const bool isMove = (drag.type == RAIL_WMSZ_MOVE);
1276 const SDL_Rect start = appWindow->outerRect(); /* position frozen at drag start */
1277 /* Preserve server size during move; defer WM snap/tile size sync until loop END to avoid
1278 * server drag-restore conflict. */
1279 if (isMove)
1280 {
1281 if (!appWindow->effectivelyMaximized() && drag.wmSized &&
1282 !appWindow->localMoveSizeChanged())
1283 {
1284 /* Adopt WM size if window was resized during move. */
1285 w = drag.wmSize.x;
1286 h = drag.wmSize.y;
1287 appWindow->deferSnap(appWindow->serverRect({ x, y, w, h }));
1288 }
1289 else
1290 {
1291 w = start.w;
1292 h = start.h;
1293 }
1294 }
1295 /* Finalize modal loop unless server closed it early. */
1296 if (!drag.serverEnded)
1297 {
1298 int px = drag.anchor.x;
1299 int py = drag.anchor.y;
1300 if (isMove && appWindow->localMoveSizeChanged())
1301 {
1302 /* Measure delta from server anchor on drag-restore. */
1303 const SDL_Point sp = appWindow->localMoveServerPos();
1304 const SDL_Rect ii = appWindow->insets();
1305 px = drag.pointer.x + (x + ii.x) - sp.x;
1306 py = drag.pointer.y + (y + ii.y) - sp.y;
1307 }
1308 else if (!appWindow->effectivelyMaximized())
1309 {
1310 const RailEdges e = railEdges(drag.type);
1311 if (isMove || e.left)
1312 px += x - start.x;
1313 else if (e.right)
1314 px += (x + w) - (start.x + start.w);
1315 if (isMove || e.top)
1316 py += y - start.y;
1317 else if (e.bottom)
1318 py += (y + h) - (start.y + start.h);
1319 }
1320 (void)freerdp_client_send_button_event(_context->common(), FALSE, PTR_FLAGS_BUTTON1, px,
1321 py);
1322 /* Server loop unwinding: wait for explicit END order to gate deferred SC_MAXIMIZE. */
1323 appWindow->armLoopEnd();
1324
1325 /* Adopt local geometry without sending ClientWindowMove during mouse drags. */
1326 const SDL_Rect rect = appWindow->serverRect({ x, y, w, h });
1327 const bool restoredMidDrag = appWindow->localMoveSizeChanged();
1328 appWindow->adoptLocalGeometry(rect);
1329 /* Drag complete: apply pending server resize delayed during WM grab. */
1330 if (restoredMidDrag)
1331 appWindow->markGeometryDirty();
1332 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
1333 }
1334 else if (!isMove)
1335 {
1336 /* Sync final resize geometry if server closed loop early. */
1337 clampIntoDesktop(x, y, w, h);
1338 reportAndAdopt(appWindow, x, y, w, h);
1339 }
1340
1341 (void)sdl_x11_set_bit_gravity(appWindow->window(), 0 /* reset to default */);
1342}
1343
1344UINT SdlRail::server_min_max_info(RailClientContext* context,
1345 const RAIL_MINMAXINFO_ORDER* minMaxInfo)
1346{
1347 WINPR_ASSERT(context);
1348 WINPR_ASSERT(minMaxInfo);
1349 auto rail = static_cast<SdlRail*>(context->custom);
1350 WINPR_ASSERT(rail);
1351
1352 std::unique_lock lock(rail->_windowsLock);
1353 auto appWindow = rail->getWindow(minMaxInfo->windowId);
1354 if (appWindow)
1355 {
1356 WLog_VRB(TAG, "server minmax id=0x%08" PRIx32 " min=%dx%d max=%dx%d", minMaxInfo->windowId,
1357 minMaxInfo->minTrackWidth, minMaxInfo->minTrackHeight, minMaxInfo->maxTrackWidth,
1358 minMaxInfo->maxTrackHeight);
1359 appWindow->setMinMaxSize({ minMaxInfo->minTrackWidth, minMaxInfo->minTrackHeight },
1360 { minMaxInfo->maxTrackWidth, minMaxInfo->maxTrackHeight });
1361 lock.unlock();
1362 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
1363 }
1364 return CHANNEL_RC_OK;
1365}
1366
1367/* --- window order callbacks --- */
1368
1369/* Non-zero edge means margins exist; all-zero means "no band". */
1370static bool marginsSet(const SDL_Rect& m)
1371{
1372 return m.x || m.y || m.w || m.h;
1373}
1374
1375/* RESIZE_MARGIN fields: set this window's frame margins and seed/backfill the session BAND. */
1376void SdlRail::updateMargins(SdlRailWindow* appWindow, const WINDOW_ORDER_INFO* orderInfo,
1377 const WINDOW_STATE_ORDER* state)
1378{
1379 const UINT32 fieldFlags = orderInfo->fieldFlags;
1380 SDL_Rect m = appWindow->frameMargins(); /* raw server margins as the base */
1381 if (fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_X)
1382 {
1383 m.x = static_cast<int>(state->resizeMarginLeft);
1384 m.w = static_cast<int>(state->resizeMarginRight);
1385 }
1386 if (fieldFlags & WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y)
1387 {
1388 m.y = static_cast<int>(state->resizeMarginTop);
1389 m.h = static_cast<int>(state->resizeMarginBottom);
1390 }
1391 /* Use window's own frame margins; session margin serves as fallback for band sizing. */
1392 appWindow->setFrameMargins(m);
1393 SDL_Rect& sm = _sessionMargins;
1394 if (marginsSet(m) && !marginsSet(sm))
1395 {
1396 sm = m;
1397 /* Backfill band of earlier zero-announce windows. */
1398 for (auto& [id, w] : _windows)
1399 if (!marginsSet(w.resizeMargins()))
1400 w.setResizeMargins(m.x, m.y, m.w, m.h);
1401 }
1402 const SDL_Rect bandSrc = marginsSet(m) ? m : sm;
1403 appWindow->setResizeMargins(bandSrc.x, bandSrc.y, bandSrc.w, bandSrc.h);
1404 WLog_DBG(TAG, "margins id=0x%08" PRIx32 " raw L%d T%d R%d B%d", orderInfo->windowId, m.x, m.y,
1405 m.w, m.h);
1406}
1407
1408/* SHOW field: mirror the server's show-state (visibility + maximize/minimize) locally. */
1409void SdlRail::updateShowState(SdlRailWindow* appWindow, const WINDOW_ORDER_INFO* orderInfo,
1410 const WINDOW_STATE_ORDER* state)
1411{
1412 WLog_DBG(TAG, "server showState id=0x%08" PRIx32 " state=0x%02" PRIx32, orderInfo->windowId,
1413 state->showState);
1414 appWindow->setVisible(state->showState != WINDOW_HIDE);
1415 switch (state->showState)
1416 {
1417 case WINDOW_SHOW_MAXIMIZED:
1418 appWindow->setServerMaximized(true);
1419 appWindow->setServerMinimized(false);
1420 break;
1421 case WINDOW_SHOW_MINIMIZED:
1422 appWindow->setServerMinimized(true);
1423 break;
1424 case WINDOW_SHOW:
1425 appWindow->setServerMaximized(false);
1426 appWindow->setServerMinimized(false);
1427 break;
1428 default:
1429 break;
1430 }
1431}
1432
1433/* VISIBILITY field: convert the server's visibility rects (window-relative) and store them. */
1434void SdlRail::updateVisRects(SdlRailWindow* appWindow, const WINDOW_ORDER_INFO* orderInfo,
1435 const WINDOW_STATE_ORDER* state)
1436{
1437 std::vector<SDL_Rect> rects;
1438 rects.reserve(state->numVisibilityRects);
1439 for (UINT32 i = 0; i < state->numVisibilityRects; i++)
1440 {
1441 const RECTANGLE_16& r = state->visibilityRects[i];
1442 rects.push_back({ r.left, r.top, r.right - r.left, r.bottom - r.top });
1443 }
1444 if (rects.empty())
1445 WLog_DBG(TAG, "visrects id=0x%08" PRIx32 " n=0", orderInfo->windowId);
1446 else
1447 WLog_DBG(TAG, "visrects id=0x%08" PRIx32 " n=%zu first=%dx%d+%d+%d", orderInfo->windowId,
1448 rects.size(), rects.at(0).w, rects.at(0).h, rects.at(0).x, rects.at(0).y);
1449 appWindow->setVisibilityRects(std::move(rects));
1450}
1451
1452BOOL SdlRail::window_common(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo,
1453 const WINDOW_STATE_ORDER* windowState)
1454{
1455 WINPR_ASSERT(orderInfo);
1456 WINPR_ASSERT(windowState);
1457 auto rail = SdlRail::get(context);
1458 if (!rail)
1459 return FALSE;
1460
1461 const UINT32 fieldFlags = orderInfo->fieldFlags;
1462 std::unique_lock lock(rail->_windowsLock);
1463 auto appWindow = rail->getWindow(orderInfo->windowId);
1464
1465 if (fieldFlags & WINDOW_ORDER_STATE_NEW)
1466 {
1467 const SDL_Rect rect = { static_cast<int>(windowState->windowOffsetX),
1468 static_cast<int>(windowState->windowOffsetY),
1469 static_cast<int>(windowState->windowWidth),
1470 static_cast<int>(windowState->windowHeight) };
1471 appWindow = rail->addWindow(orderInfo->windowId, rect);
1472 if (!appWindow)
1473 return FALSE;
1474
1475 WLog_DBG(TAG,
1476 "window create id=0x%08" PRIx32 " %dx%d+%d+%d style=0x%08" PRIx32
1477 " ex=0x%08" PRIx32 " owner=0x%08" PRIx32,
1478 orderInfo->windowId, rect.w, rect.h, rect.x, rect.y, windowState->style,
1479 windowState->extendedStyle, windowState->ownerWindowId);
1480 /* Seed resize band margins from session default. */
1481 const SDL_Rect& sm = rail->_sessionMargins;
1482 if (marginsSet(sm))
1483 appWindow->setResizeMargins(sm.x, sm.y, sm.w, sm.h);
1484 /* The SDL window is created lazily on the main thread (reconcile), as SDL requires. */
1485 }
1486
1487 if (!appWindow)
1488 return FALSE;
1489
1490 if (fieldFlags & (WINDOW_ORDER_FIELD_WND_OFFSET | WINDOW_ORDER_FIELD_WND_SIZE))
1491 {
1492 SDL_Rect r = appWindow->windowRect();
1493 if (fieldFlags & WINDOW_ORDER_FIELD_WND_OFFSET)
1494 {
1495 r.x = static_cast<int>(windowState->windowOffsetX);
1496 r.y = static_cast<int>(windowState->windowOffsetY);
1497 }
1498 if (fieldFlags & WINDOW_ORDER_FIELD_WND_SIZE)
1499 {
1500 r.w = static_cast<int>(windowState->windowWidth);
1501 r.h = static_cast<int>(windowState->windowHeight);
1502 }
1503 WLog_VRB(TAG, "server geom id=0x%08" PRIx32 " rect=%d,%d %dx%d", orderInfo->windowId, r.x,
1504 r.y, r.w, r.h);
1505 appWindow->updateWindowRect(r);
1506 }
1507 if (fieldFlags & WINDOW_ORDER_FIELD_OWNER)
1508 appWindow->setOwner(windowState->ownerWindowId);
1509 if (fieldFlags & (WINDOW_ORDER_FIELD_RESIZE_MARGIN_X | WINDOW_ORDER_FIELD_RESIZE_MARGIN_Y))
1510 rail->updateMargins(appWindow, orderInfo, windowState);
1511 if (fieldFlags & WINDOW_ORDER_FIELD_STYLE)
1512 appWindow->setStyle(windowState->style, windowState->extendedStyle);
1513 if (fieldFlags & WINDOW_ORDER_FIELD_TITLE)
1514 {
1515 char* title = rail_string_to_utf8_string(&windowState->titleInfo);
1516 if (title)
1517 {
1518 appWindow->setTitle(title);
1519 free(title);
1520 }
1521 }
1522
1523 if (fieldFlags & WINDOW_ORDER_FIELD_SHOW)
1524 updateShowState(appWindow, orderInfo, windowState);
1525
1526 if (fieldFlags & WINDOW_ORDER_FIELD_VIS_OFFSET)
1527 {
1528 WLog_DBG(TAG, "visoff id=0x%08" PRIx32 " %d,%d", orderInfo->windowId,
1529 windowState->visibleOffsetX, windowState->visibleOffsetY);
1530 appWindow->setVisibleOffset({ static_cast<int>(windowState->visibleOffsetX),
1531 static_cast<int>(windowState->visibleOffsetY) });
1532 }
1533 if (fieldFlags & WINDOW_ORDER_FIELD_VISIBILITY)
1534 updateVisRects(appWindow, orderInfo, windowState);
1535
1536 /* Wake the main thread to create/move/show/paint the SDL window(s). */
1537 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
1538 return TRUE;
1539}
1540
1541SdlRailIcon* SdlRail::iconCacheLookup(uint32_t cacheId, uint32_t cacheEntry)
1542{
1543 if (cacheId == 0xFF)
1544 return &_iconScratch;
1545 const size_t idx = static_cast<size_t>(cacheId) * _iconCacheEntries + cacheEntry;
1546 if ((_iconCacheEntries == 0) || (cacheEntry >= _iconCacheEntries) || (idx >= _iconCache.size()))
1547 return nullptr;
1548 return &_iconCache.at(idx);
1549}
1550
1551/* ICON_INFO (1/4/8/16/24/32 bpp + AND mask) -> BGRA32, like xf convert_rail_icon. */
1552static bool convertRailIcon(const ICON_INFO* info, SdlRailIcon& icon)
1553{
1554 icon.w = info->width;
1555 icon.h = info->height;
1556 icon.bgra.assign(4ULL * info->width * info->height, 0);
1557 return freerdp_image_copy_from_icon_data(
1558 icon.bgra.data(), PIXEL_FORMAT_BGRA32, 0, 0, 0,
1559 WINPR_ASSERTING_INT_CAST(UINT16, info->width),
1560 WINPR_ASSERTING_INT_CAST(UINT16, info->height), info->bitsColor,
1561 WINPR_ASSERTING_INT_CAST(UINT16, info->cbBitsColor), info->bitsMask,
1562 WINPR_ASSERTING_INT_CAST(UINT16, info->cbBitsMask), info->colorTable,
1563 WINPR_ASSERTING_INT_CAST(UINT16, info->cbColorTable), info->bpp) == TRUE;
1564}
1565
1566BOOL SdlRail::window_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo,
1567 const WINDOW_ICON_ORDER* windowIcon)
1568{
1569 WINPR_ASSERT(orderInfo);
1570 WINPR_ASSERT(windowIcon);
1571 WINPR_ASSERT(windowIcon->iconInfo);
1572 auto rail = SdlRail::get(context);
1573 if (!rail)
1574 return FALSE;
1575
1576 std::unique_lock lock(rail->_windowsLock);
1577 auto appWindow = rail->getWindow(orderInfo->windowId);
1578 if (!appWindow)
1579 return TRUE;
1580
1581 /* Decode into the cache slot so a later WindowCachedIcon can reference it. */
1582 const ICON_INFO* info = windowIcon->iconInfo;
1583 auto* icon = rail->iconCacheLookup(info->cacheId, info->cacheEntry);
1584 if (!icon || !convertRailIcon(info, *icon))
1585 {
1586 WLog_WARN(TAG, "failed to decode icon %02" PRIX32 ":%04" PRIX32 " for window 0x%08" PRIx32,
1587 info->cacheId, info->cacheEntry, orderInfo->windowId);
1588 return TRUE;
1589 }
1590 appWindow->setIcon(*icon);
1591 lock.unlock();
1592 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
1593 return TRUE;
1594}
1595
1596BOOL SdlRail::window_cached_icon(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo,
1597 const WINDOW_CACHED_ICON_ORDER* windowCachedIcon)
1598{
1599 WINPR_ASSERT(orderInfo);
1600 WINPR_ASSERT(windowCachedIcon);
1601 auto rail = SdlRail::get(context);
1602 if (!rail)
1603 return FALSE;
1604
1605 std::unique_lock lock(rail->_windowsLock);
1606 auto appWindow = rail->getWindow(orderInfo->windowId);
1607 if (!appWindow)
1608 return TRUE;
1609
1610 const CACHED_ICON_INFO& cached = windowCachedIcon->cachedIcon;
1611 auto* icon = rail->iconCacheLookup(cached.cacheId, cached.cacheEntry);
1612 if (!icon || icon->bgra.empty())
1613 {
1614 WLog_WARN(TAG,
1615 "cached icon %02" PRIX32 ":%04" PRIX32 " not in cache (window 0x%08" PRIx32 ")",
1616 cached.cacheId, cached.cacheEntry, orderInfo->windowId);
1617 return TRUE;
1618 }
1619 appWindow->setIcon(*icon);
1620 lock.unlock();
1621 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
1622 return TRUE;
1623}
1624
1625BOOL SdlRail::window_delete(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo)
1626{
1627 WINPR_ASSERT(orderInfo);
1628 auto rail = SdlRail::get(context);
1629 if (!rail)
1630 return FALSE;
1631
1632 /* Mark only; erased on the main thread (paint) so the SDL window dies there. */
1633 std::unique_lock lock(rail->_windowsLock);
1634 auto appWindow = rail->getWindow(orderInfo->windowId);
1635 if (appWindow)
1636 {
1637 WLog_DBG(TAG, "window delete id=0x%08" PRIx32, orderInfo->windowId);
1638 appWindow->markDeleted();
1639 }
1640
1641 /* Clear cached references to deleted window id. */
1642 if (rail->_localMove.id == orderInfo->windowId)
1643 rail->_localMove = {};
1644 if (rail->_clientActiveId == orderInfo->windowId)
1645 rail->_clientActiveId = 0;
1646 if (rail->_focusedAppId == orderInfo->windowId)
1647 rail->_focusedAppId = 0;
1648 lock.unlock();
1649
1650 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE);
1651 return TRUE;
1652}
1653
1654BOOL SdlRail::monitored_desktop(rdpContext* context, const WINDOW_ORDER_INFO* orderInfo,
1655 const MONITORED_DESKTOP_ORDER* monitoredDesktop)
1656{
1657 WINPR_ASSERT(orderInfo);
1658 WINPR_ASSERT(monitoredDesktop);
1659 auto rail = SdlRail::get(context);
1660 if (!rail)
1661 return FALSE;
1662
1663 /* Launch the RemoteApp on DESKTOP_ARC_COMPLETED, like xf_rail_monitored_desktop. */
1664 if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ARC_COMPLETED)
1665 {
1666 rail->enableRemoteAppMode(true);
1667 const char* app =
1668 freerdp_settings_get_string(context->settings, FreeRDP_RemoteApplicationProgram);
1669 if (app && (strnlen(app, 1) > 0))
1670 {
1671 WLog_DBG(TAG, "RAIL mode enabled (monitored desktop); launching '%s'", app);
1672 if (client_rail_server_start_cmd(rail->_rail) != CHANNEL_RC_OK)
1673 {
1674 WLog_ERR(TAG, "client_rail_server_start_cmd failed for '%s'", app);
1675 return FALSE;
1676 }
1677 }
1678 }
1679
1680 /* Authoritative top-level z-order (windowIds[0] topmost); capture it, paint() realizes it. */
1681 if (orderInfo->fieldFlags &
1682 (WINDOW_ORDER_FIELD_DESKTOP_ZORDER | WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND))
1683 {
1684 std::unique_lock lock(rail->_windowsLock);
1685 if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ACTIVE_WND)
1686 {
1687 /* Server changed active window: sync our ClientActivate dedup to avoid skipping
1688 * re-clicks. */
1689 rail->_clientActiveId = monitoredDesktop->activeWindowId;
1690 }
1691 if (orderInfo->fieldFlags & WINDOW_ORDER_FIELD_DESKTOP_ZORDER)
1692 {
1693 if (monitoredDesktop->windowIds && (monitoredDesktop->numWindowIds > 0))
1694 rail->_zOrder.assign(monitoredDesktop->windowIds,
1695 monitoredDesktop->windowIds + monitoredDesktop->numWindowIds);
1696 else
1697 rail->_zOrder.clear();
1698 rail->_zOrderDirty = true;
1699 lock.unlock();
1700 (void)sdl_push_user_event(SDL_EVENT_USER_UPDATE); /* wake the main thread to restack */
1701 }
1702 }
1703 return TRUE;
1704}
1705
1706BOOL SdlRail::non_monitored_desktop(rdpContext* context,
1707 WINPR_ATTR_UNUSED const WINDOW_ORDER_INFO* orderInfo)
1708{
1709 WINPR_ASSERT(orderInfo);
1710 auto rail = SdlRail::get(context);
1711 if (rail)
1712 {
1713 WLog_DBG(TAG, "RAIL mode disabled (non-monitored desktop)");
1714 rail->enableRemoteAppMode(false);
1715 }
1716 return TRUE;
1717}
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 UINT32 freerdp_settings_get_uint32(const rdpSettings *settings, FreeRDP_Settings_Keys_UInt32 id)
Returns a UINT32 settings value.
-aad-helper