FreeRDP
Loading...
Searching...
No Matches
sdl_rail_window.cpp
1
19#include <algorithm>
20#include <iterator>
21#include <map>
22#include <string>
23#include <utility>
24
25#include <freerdp/codec/color.h>
26#include <freerdp/log.h>
27#include <freerdp/window.h>
28
29#include "sdl_rail_platform.hpp"
30#include "sdl_rail_window.hpp"
31#include "sdl_rail_window_style.hpp"
32#include "sdl_utils.hpp"
33#include "sdl_wayland.hpp"
34#include "sdl_window.hpp"
35
36#define TAG CLIENT_TAG("sdl.rail.window")
37
38/* Timeout bounding stale anchored frame while awaiting server surface update. */
39static constexpr uint64_t kAwaitServerFrameMs = 1000;
40
41/* Maximum timeout waiting for server restore geometry order. */
42static constexpr uint64_t kAwaitRestoreRectMs = 500;
43
44/* Reports kept to recognize late echoes. */
45static constexpr size_t kMaxReported = 16;
46
47/* Unanswered reports are sent again after this. */
48static constexpr uint64_t kReportConfirmMs = 1000;
49
50static void armDeadline(uint64_t& until, uint64_t ms)
51{
52 until = SDL_GetTicks() + ms;
53 if (!sdl_push_update_after(WINPR_ASSERTING_INT_CAST(Uint32, ms + 1)))
54 WLog_WARN(TAG, "SDL_AddTimer failed: %s", SDL_GetError());
55}
56
57/* SDL reports several displays in a row while a window maps or spans monitors. */
58static constexpr uint64_t kDisplaySettleMs = 500;
59
60/* A Wayland popup moved again within this time is still being dragged by its app. */
61static constexpr uint64_t kMoveActiveMs = 250;
62
63/* Longest a Wayland popup frame waits for the configure of its move. */
64static constexpr uint64_t kPlaceWaitMs = 50;
65
66/* Check for real per-pixel alpha in region. */
67static bool regionHasAlpha(const uint8_t* base, uint32_t stride, const SDL_Rect& r)
68{
69 for (int y = r.y; y < r.y + r.h; y++)
70 {
71 const uint8_t* row = base + static_cast<size_t>(y) * stride;
72 for (int x = r.x; x < r.x + r.w; x++)
73 if (row[static_cast<size_t>(x) * 4 + 3] != 0)
74 return true;
75 }
76 return false;
77}
78
79static bool regionIsBlank(const uint8_t* base, uint32_t stride, const SDL_Rect& r)
80{
81 for (int y = r.y; y < r.y + r.h; y++)
82 {
83 const auto* row = reinterpret_cast<const uint32_t*>(base + static_cast<size_t>(y) * stride);
84 for (int x = r.x; x < r.x + r.w; x++)
85 if (row[x] != 0)
86 return false;
87 }
88 return true;
89}
90
91SdlRailWindow::SdlRailWindow(uint64_t id, const SDL_Rect& rect) : _id(id), _windowRect(rect)
92{
93}
94
95/* Out of line: SdlWindow is only forward-declared in the header. */
96SdlRailWindow::~SdlRailWindow() = default;
97
98uint64_t SdlRailWindow::id() const
99{
100 return _id;
101}
102
103SDL_WindowID SdlRailWindow::sdlId() const
104{
105 return _win ? _win->id() : 0;
106}
107
108SDL_Window* SdlRailWindow::window() const
109{
110 return _win ? _win->window() : nullptr;
111}
112
113SDL_Renderer* SdlRailWindow::renderer() const
114{
115 return _win ? _win->renderer() : nullptr;
116}
117
118void SdlRailWindow::updateWindowRect(const SDL_Rect& rect)
119{
120 std::unique_lock lock(_gfxLock);
121 /* Minimized, Windows parks the window off screen; keep the rect to restore to. */
122 if (_minState.server)
123 return;
124 _awaitRestoreUntil = 0; /* Server geometry received. */
125 if (_localMoveActive)
126 {
127 /* Adopt server size change during local move. */
128 if (!_localMoveIsResize && ((rect.w != _windowRect.w) || (rect.h != _windowRect.h)))
129 {
130 WLog_DBG(TAG, "size adopted mid-move id=0x%08" PRIx32 " %dx%d -> %dx%d at %d,%d",
131 static_cast<uint32_t>(_id), _windowRect.w, _windowRect.h, rect.w, rect.h,
132 rect.x, rect.y);
133 _windowRect.w = rect.w;
134 _windowRect.h = rect.h;
135 /* Record server re-anchor position. */
136 _localMoveServerPos = { rect.x, rect.y };
137 _localMoveSizeChanged = true;
138 _painted = false;
139 }
140 return;
141 }
142 /* Accept post-move geometry echoes. */
143 if (SDL_RectsEqual(&rect, &_windowRect))
144 {
145 _reported.clear();
146 return;
147 }
148 /* The echo of an older report can arrive after a newer one was sent. */
149 const auto echo = std::find_if(_reported.begin(), _reported.end(),
150 [&](const SDL_Rect& r) { return SDL_RectsEqual(&r, &rect); });
151 if (echo != _reported.end())
152 {
153 WLog_DBG(TAG, "late echo id=0x%08" PRIx32 " %dx%d ignored", static_cast<uint32_t>(_id),
154 rect.w, rect.h);
155 _reported.erase(_reported.begin(), echo + 1);
156 return;
157 }
158 _reported.clear();
159 /* A resize recreates the render target, so the content needs a full re-copy. */
160 if ((rect.w != _windowRect.w) || (rect.h != _windowRect.h))
161 _painted = false;
162 _windowRect = rect;
163 /* Mark dirty even if frozen/maximized so pending restore rect applies upon unfreeze. */
164 _geometryDirty = true;
165}
166
167void SdlRailWindow::setLocalMoveActive(bool active)
168{
169 std::unique_lock lock(_gfxLock);
170 _localMoveActive = active;
171 if (active)
172 {
173 _localMoveIsResize = false; /* default to move; setResizeAnchor marks a resize */
174 _localMoveSizeChanged = false;
175 }
176}
177
178void SdlRailWindow::setResizeAnchor(bool right, bool bottom)
179{
180 std::unique_lock lock(_gfxLock);
181 _resizeAnchorRight = right;
182 _resizeAnchorBottom = bottom;
183 _localMoveIsResize = true;
184}
185
186bool SdlRailWindow::localMoveActive() const
187{
188 std::unique_lock lock(_gfxLock);
189 return _localMoveActive;
190}
191
192bool SdlRailWindow::localMoveSizeChanged() const
193{
194 std::unique_lock lock(_gfxLock);
195 return _localMoveSizeChanged;
196}
197
198SDL_Point SdlRailWindow::localMoveServerPos() const
199{
200 std::unique_lock lock(_gfxLock);
201 return _localMoveServerPos;
202}
203
204void SdlRailWindow::adoptLocalGeometry(const SDL_Rect& rect)
205{
206 /* Adopt local geometry so the server's echoing WINDOW_ORDER is a no-op (not a size snap). */
207 std::unique_lock lock(_gfxLock);
208 /* A completed local move settles geometry via the completion path, not the reporter. */
209 _geomApplyPending = false;
210 /* Translate visible offset by move delta. */
211 if (_visOffsetSet)
212 {
213 _visOffset.x += rect.x - _windowRect.x;
214 _visOffset.y += rect.y - _windowRect.y;
215 }
216 if (!SDL_RectsEqual(&rect, &_windowRect))
217 {
218 if (_reported.size() >= kMaxReported)
219 _reported.erase(_reported.begin());
220 _reported.push_back(rect);
221 armDeadline(_reportCheckAt, kReportConfirmMs);
222 }
223 _windowRect = rect;
224 _geometryDirty = false;
225 /* A resize drag ends here; the server surface still has the pre-drag size. */
226 _awaitingFrameUntil =
227 (_localMoveActive && _localMoveIsResize) ? (SDL_GetTicks() + kAwaitServerFrameMs) : 0;
228 _localMoveActive = false;
229 _needsFullBlit = true;
230 /* Repaint real content (clear placeholder). */
231 if (_hasGfx)
232 _gfxDamage.assign(1, SDL_Rect{ 0, 0, static_cast<int>(_gfxW), static_cast<int>(_gfxH) });
233}
234
235SDL_Rect SdlRailWindow::windowRect() const
236{
237 std::unique_lock lock(_gfxLock);
238 return _windowRect;
239}
240
241void SdlRailWindow::markDeleted()
242{
243 std::unique_lock lock(_gfxLock);
244 _deleted = true;
245}
246
247void SdlRailWindow::releaseWindow()
248{
249 std::unique_lock lock(_gfxLock);
250 if (!_win)
251 return;
252 WLog_DBG(TAG, "release id=0x%08" PRIx32 " %s%s", static_cast<uint32_t>(_id), role(),
253 _deleted ? "" : " (SDL parent gone, re-created on next pass)");
254 _win.reset();
255 _appIdDirty = !_appId.empty();
256 /* Back to the "never created" state: create() + first frame + map run again. */
257 _mapped = false;
258 _painted = false;
259 _gfxPresented = false;
260 _needsFullBlit = true;
261 _geometryDirty = true;
262 _parentApplied = false;
263 _fullscreen = false;
264 _appliedInsets = { 0, 0, 0, 0 };
265 _extentsApplied = { 0, 0, 0, 0 };
266 _lastWinW = _lastWinH = _lastGfxW = _lastGfxH = 0;
267}
268
269bool SdlRailWindow::isDeleted() const
270{
271 std::unique_lock lock(_gfxLock);
272 return _deleted;
273}
274
275bool SdlRailWindow::geomApplyPending() const
276{
277 std::unique_lock lock(_gfxLock);
278 return _geomApplyPending;
279}
280
281void SdlRailWindow::clearGeomApplyPending()
282{
283 std::unique_lock lock(_gfxLock);
284 _geomApplyPending = false;
285}
286
287void SdlRailWindow::armLoopEnd()
288{
289 std::unique_lock lock(_gfxLock);
290 _loopEnd.pending = true;
291}
292
293bool SdlRailWindow::loopEndPending() const
294{
295 std::unique_lock lock(_gfxLock);
296 return _loopEnd.pending;
297}
298
299void SdlRailWindow::deferMaximize()
300{
301 std::unique_lock lock(_gfxLock);
302 _loopEnd.maximize = true;
303}
304
305void SdlRailWindow::deferSnap(const SDL_Rect& serverRect)
306{
307 std::unique_lock lock(_gfxLock);
308 _loopEnd.snap = true;
309 _loopEnd.snapRect = serverRect;
310}
311
312void SdlRailWindow::clearLoopEnd()
313{
314 std::unique_lock lock(_gfxLock);
315 _loopEnd = {};
316}
317
318SdlRailWindow::LoopEndActions SdlRailWindow::takeLoopEnd()
319{
320 std::unique_lock lock(_gfxLock);
321 const LoopEndActions actions{ _loopEnd.maximize, _loopEnd.snap, _loopEnd.snapRect };
322 _loopEnd = {};
323 return actions;
324}
325
326bool SdlRailWindow::takeWmOverride(SDL_Rect& outer)
327{
328 std::unique_lock lock(_gfxLock);
329 if (!_wmRefused)
330 return false;
331 outer = _wmRefusedOuter;
332 _wmRefused = false;
333 return true;
334}
335
336/* True if no two rects share a pixel. Sweeps from top to bottom, the rects crossing the current
337 * row kept by their left edge. */
338[[nodiscard]]
339static bool rectsAreDisjoint(const std::vector<SDL_Rect>& rects)
340{
341 struct Edge
342 {
343 int y;
344 bool top;
345 const SDL_Rect* rect;
346 };
347 std::vector<Edge> edges;
348 edges.reserve(rects.size() * 2);
349 for (const auto& r : rects)
350 {
351 if (SDL_RectEmpty(&r))
352 continue;
353 edges.push_back({ r.y, true, &r });
354 edges.push_back({ r.y + r.h, false, &r });
355 }
356 /* A rect ends before the one below it starts. */
357 std::sort(edges.begin(), edges.end(), [](const Edge& a, const Edge& b)
358 { return (a.y != b.y) ? (a.y < b.y) : (!a.top && b.top); });
359
360 std::map<int, int> row; /* left -> right */
361 for (const auto& e : edges)
362 {
363 const int left = e.rect->x;
364 const int right = e.rect->x + e.rect->w;
365 if (!e.top)
366 {
367 row.erase(left);
368 continue;
369 }
370 const auto next = row.lower_bound(left);
371 if ((next != row.end()) && (next->first < right))
372 return false;
373 if ((next != row.begin()) && (std::prev(next)->second > left))
374 return false;
375 row.emplace_hint(next, left, right);
376 }
377 return true;
378}
379
380void SdlRailWindow::setVisibilityRects(std::vector<SDL_Rect> rects)
381{
382 /* The rects of a region do not overlap and painting relies on that: each rect is blitted on
383 * its own, so overlapping ones cost their number times the window area per frame. */
384 if (!rectsAreDisjoint(rects))
385 {
386 SDL_Rect extents{};
387 for (const auto& r : rects)
388 {
389 SDL_Rect u{};
390 if (SDL_GetRectUnion(&extents, &r, &u))
391 extents = u;
392 }
393 rects.assign(1, extents);
394 }
395 std::unique_lock lock(_gfxLock);
396 _visRects = std::move(rects);
397 _visDirty = true;
398}
399
400void SdlRailWindow::setVisibleOffset(SDL_Point offset)
401{
402 std::unique_lock lock(_gfxLock);
403 /* Freeze visible offset during local move. */
404 if (_localMoveActive)
405 return;
406 if (_visOffsetSet && (offset.x == _visOffset.x) && (offset.y == _visOffset.y))
407 return;
408 _visOffset = offset;
409 _visOffsetSet = true;
410 _visDirty = true;
411}
412
413void SdlRailWindow::setMinMaxSize(SDL_Point minSize, SDL_Point maxSize)
414{
415 std::unique_lock lock(_gfxLock);
416 _minSize = { std::max(0, minSize.x), std::max(0, minSize.y) };
417 _maxSize = { std::max(0, maxSize.x), std::max(0, maxSize.y) };
418 _minMaxDirty = true;
419 /* Re-apply geometry on min/max change. */
420 _geometryDirty = true;
421}
422
423void SdlRailWindow::setResizeMargins(int left, int top, int right, int bottom)
424{
425 std::unique_lock lock(_gfxLock);
426 const SDL_Rect m = { left, top, right, bottom };
427 if (SDL_RectsEqual(&m, &_resizeMargins))
428 return;
429 _resizeMargins = m;
430 /* Margins usually arrive after the first frame; the window must regrow to cover them. */
431 if (!railMaximized())
432 _geometryDirty = true;
433}
434
435SDL_Rect SdlRailWindow::resizeMargins() const
436{
437 std::unique_lock lock(_gfxLock);
438 return _resizeMargins;
439}
440
441void SdlRailWindow::setFrameMargins(const SDL_Rect& m)
442{
443 std::unique_lock lock(_gfxLock);
444 _frameMargins = m;
445}
446
447SDL_Rect SdlRailWindow::frameMargins() const
448{
449 std::unique_lock lock(_gfxLock);
450 return _frameMargins;
451}
452
453bool SdlRailWindow::takeUnconfirmedReport(SDL_Rect& rect)
454{
455 std::unique_lock lock(_gfxLock);
456 if ((_reportCheckAt == 0) || (SDL_GetTicks() < _reportCheckAt))
457 return false;
458 _reportCheckAt = 0;
459 if (_reported.empty())
460 return false;
461 rect = _reported.back();
462 _reported.clear();
463 return true;
464}
465
466void SdlRailWindow::noteDisplayChange()
467{
468 std::unique_lock lock(_gfxLock);
469 armDeadline(_displayCheckAt, kDisplaySettleMs);
470}
471
472bool SdlRailWindow::takeDisplayChange(bool now)
473{
474 std::unique_lock lock(_gfxLock);
475 if ((_displayCheckAt == 0) || (!now && (SDL_GetTicks() < _displayCheckAt)))
476 return false;
477 _displayCheckAt = 0;
478 return true;
479}
480
481bool SdlRailWindow::deferMaximizeUntilEcho()
482{
483 std::unique_lock lock(_gfxLock);
484 if (_reported.empty())
485 return false;
486 _maximizeAfterEcho = true;
487 return true;
488}
489
490bool SdlRailWindow::takeMaximizeAfterEcho()
491{
492 std::unique_lock lock(_gfxLock);
493 if (!_maximizeAfterEcho || !_reported.empty())
494 return false;
495 _maximizeAfterEcho = false;
496 return true;
497}
498
499void SdlRailWindow::setOwner(uint64_t ownerId)
500{
501 std::unique_lock lock(_gfxLock);
502 _ownerId = ownerId;
503}
504
505uint64_t SdlRailWindow::owner() const
506{
507 std::unique_lock lock(_gfxLock);
508 return _ownerId;
509}
510
511bool SdlRailWindow::isPopup() const
512{
513 std::unique_lock lock(_gfxLock);
514 return _isPopup;
515}
516
517bool SdlRailWindow::isFullscreen() const
518{
519 std::unique_lock lock(_gfxLock);
520 return _fullscreen;
521}
522
523bool SdlRailWindow::activatable() const
524{
525 std::unique_lock lock(_gfxLock);
526 return (!_isPopup || _fullscreen) && ((_exStyle & WS_EX_NOACTIVATE) == 0);
527}
528
529bool SdlRailWindow::isLayered() const
530{
531 std::unique_lock lock(_gfxLock);
532 return _layered;
533}
534
535void SdlRailWindow::setShadowAnchored(bool anchored)
536{
537 std::unique_lock lock(_gfxLock);
538 _shadowAnchored = anchored;
539}
540
541void SdlRailWindow::setFrame(bool frame)
542{
543 std::unique_lock lock(_gfxLock);
544 _frame = frame;
545}
546
547bool SdlRailWindow::isFrame() const
548{
549 std::unique_lock lock(_gfxLock);
550 return _frame;
551}
552
553bool SdlRailWindow::styleResizable() const
554{
555 /* Once resizable, keep band eligibility to avoid oscillation. */
556 return _everResizable;
557}
558
559/* Minimum grabbable width for each outside-band resize edge. */
560static constexpr int kMinGrip = 4;
561
562SDL_Rect SdlRailWindow::bandMargins() const
563{
564 if (!_visible || _isPopup || _layered || !styleResizable() || effectivelyMaximized())
565 return { 0, 0, 0, 0 };
566 /* Enforce minimum grip margins for resizable windows. */
567 const SDL_Rect& m = _resizeMargins;
568 return { std::max(m.x, kMinGrip), std::max(m.y, kMinGrip), std::max(m.w, kMinGrip),
569 std::max(m.h, kMinGrip) };
570}
571
572SDL_Rect SdlRailWindow::bandInsets() const
573{
574 /* NativeFrame: the OS adds the band outside the client area, not part of our geometry. */
575 const auto band = railPlatformCaps().band;
576 if ((band == RailBandMechanism::None) || (band == RailBandMechanism::NativeFrame))
577 return { 0, 0, 0, 0 };
578 return bandMargins();
579}
580
581/* Add edge insets (x=L y=T w=R h=B) to a server rect to get its outer (band-inclusive) rect. */
582static SDL_Rect addInsets(const SDL_Rect& r, const SDL_Rect& i)
583{
584 return { r.x - i.x, r.y - i.y, r.w + i.x + i.w, r.h + i.y + i.h };
585}
586
587/* Inverse of addInsets: strip the insets back off an outer rect to recover the server rect.
588 */
589static SDL_Rect stripInsets(const SDL_Rect& r, const SDL_Rect& i)
590{
591 return { r.x + i.x, r.y + i.y, r.w - i.x - i.w, r.h - i.y - i.h };
592}
593
594/* Caller holds _gfxLock. */
595bool SdlRailWindow::isFullDisplaySize() const
596{
597 SDL_Rect disp{};
598 return SDL_GetDisplayBounds(SDL_GetPrimaryDisplay(), &disp) && (_windowRect.w >= disp.w) &&
599 (_windowRect.h >= disp.h);
600}
601
602/* Server rect inflated by the FRESH band insets (the target the window should become); caller
603 * holds _gfxLock. Used by reconcile/create to size the window. */
604SDL_Rect SdlRailWindow::targetOuterRect() const
605{
606 SDL_Rect r = addInsets(_windowRect, bandInsets());
607 r.x += _localShift.x;
608 r.y += _localShift.y;
609 return r;
610}
611
612/* The insets baked into the window ON SCREEN (not the freshly recomputed target). */
613SDL_Rect SdlRailWindow::insets() const
614{
615 std::unique_lock lock(_gfxLock);
616 return _appliedInsets;
617}
618
619/* On-screen outer geometry: _windowRect inflated by the applied insets. */
620SDL_Rect SdlRailWindow::outerRect() const
621{
622 std::unique_lock lock(_gfxLock);
623 SDL_Rect r = addInsets(_windowRect, _appliedInsets);
624 r.x += _localShift.x;
625 r.y += _localShift.y;
626 return r;
627}
628
629SDL_Rect SdlRailWindow::serverRect(const SDL_Rect& outer) const
630{
631 SDL_Rect r = stripInsets(outer, insets());
632 r.x -= _localShift.x;
633 r.y -= _localShift.y;
634 return r;
635}
636
637void SdlRailWindow::setLocalShift(const SDL_Point& shift)
638{
639 std::unique_lock lock(_gfxLock);
640 _localShift = shift;
641}
642
643/* Surface blit offset within the local window (content anchor when maximized). */
644SDL_Point SdlRailWindow::blitOffset() const
645{
646 if (!effectivelyMaximized())
647 return { _appliedInsets.x, _appliedInsets.y };
648 /* Use frame margins as origin only when surface matches frame-inclusive geometry. */
649 const bool frameInSurface =
650 ((_frameMargins.x > 0) || (_frameMargins.y > 0)) &&
651 (static_cast<int>(_gfxW) == _windowRect.w + _frameMargins.x + _frameMargins.w) &&
652 (static_cast<int>(_gfxH) == _windowRect.h + _frameMargins.y + _frameMargins.h);
653 SDL_Point content = { 0, 0 };
654 if (frameInSurface)
655 content = { _frameMargins.x, _frameMargins.y };
656 else if (_visOffsetSet)
657 content = { _visOffset.x - _windowRect.x, _visOffset.y - _windowRect.y };
658 return { -std::clamp(content.x, 0, static_cast<int>(_gfxW)),
659 -std::clamp(content.y, 0, static_cast<int>(_gfxH)) };
660}
661
662/* Shows a held popup frame whose configure never came. */
663static Uint32 placeWaitTimer([[maybe_unused]] void* userdata, [[maybe_unused]] SDL_TimerID timerID,
664 [[maybe_unused]] Uint32 interval)
665{
666 if (!sdl_push_user_event(SDL_EVENT_USER_UPDATE))
667 WLog_WARN(TAG, "could not wake the paint loop for a held popup");
668 return 0;
669}
670
671/* Wayland input is relative to where a popup is shown. mutter shows a move at our first commit
672 * after its configure, KWin also before it: hold frames until the configure. */
673void SdlRailWindow::notePlaced()
674{
675 std::unique_lock lock(_gfxLock);
676 placeRequested();
677}
678
679/* Caller holds _gfxLock. */
680void SdlRailWindow::placeRequested()
681{
682 _pendingRel = _requestedRel;
683 _placeInFlight = false;
684}
685
686/* Caller holds _gfxLock. True while a move waits for its configure. */
687bool SdlRailWindow::holdForPlacement()
688{
689 if (!_placeInFlight)
690 return false;
691 if (SDL_GetTicks() - _requestedAt < kPlaceWaitMs)
692 return true;
693 placeRequested(); /* no configure came */
694 return false;
695}
696
697/* Caller holds _gfxLock. */
698void SdlRailWindow::placePopup(const SDL_Rect& vis, const SDL_Rect& parentRect)
699{
700 const SDL_Point rel = { vis.x - parentRect.x, vis.y - parentRect.y };
701 const bool wayland = !railPlatformCaps().supportsWindowPositions;
702 const bool moved = (rel.x != _requestedRel.x) || (rel.y != _requestedRel.y);
703 if (wayland)
704 {
705 _requestedRel = rel;
706 _requestedAt = SDL_GetTicks();
707 }
708 if (!SDL_SetWindowPosition(_win->window(), rel.x, rel.y))
709 {
710 WLog_VRB(TAG, "popup reposition unsupported id=0x%08" PRIx32 ": %s",
711 static_cast<uint32_t>(_id), SDL_GetError());
712 return;
713 }
714 if (!wayland)
715 return;
716 _needsFullBlit = true; /* Wayland applies move on next surface commit */
717 if (!moved || !_mapped)
718 return;
719 _placeInFlight = true;
720 if (SDL_AddTimer(static_cast<Uint32>(kPlaceWaitMs + 1), placeWaitTimer, nullptr) == 0)
721 WLog_WARN(TAG, "popup placement timer failed: %s", SDL_GetError());
722}
723
724/* Caller holds _gfxLock. Called after a present. */
725void SdlRailWindow::commitPlacement()
726{
727 if (!_pendingRel)
728 return;
729 _placedRel = _pendingRel;
730 _pendingRel.reset();
731}
732
733bool SdlRailWindow::placedRel(SDL_Point& rel) const
734{
735 std::unique_lock lock(_gfxLock);
736 /* Only while moving: a resting popup may sit elsewhere (off screen), map it as on X11. */
737 if (!_placedRel || (SDL_GetTicks() - _requestedAt >= kMoveActiveMs))
738 return false;
739 rel = *_placedRel;
740 return true;
741}
742
743SDL_Point SdlRailWindow::serverOrigin() const
744{
745 std::unique_lock lock(_gfxLock);
746 /* Derive server coordinate from blit offset to match on-screen pixels. */
747 const SDL_Point dst = blitOffset();
748 return { _windowRect.x - dst.x, _windowRect.y - dst.y };
749}
750
751void SdlRailWindow::setStyle(uint32_t style, uint32_t exStyle)
752{
753 std::unique_lock lock(_gfxLock);
754 const bool wasTopmost = _topmost;
755 _style = style;
756 _exStyle = exStyle;
757 _topmost = (exStyle & WS_EX_TOPMOST) != 0;
758 if (_topmost != wasTopmost)
759 _topmostDirty = true;
760 if (!_everResizable && ((style & (WS_THICKFRAME | WS_MAXIMIZEBOX)) != 0))
761 {
762 _everResizable = true;
763 _styleDirty = true;
764 }
765 /* Classify popup and layered window types once on creation. */
766 if (!_popupClassified)
767 {
768 const auto classification = classifySdlRailWindowStyle(style, exStyle, _ownerId != 0);
769 _isPopup = classification.popup;
770 _layered = classification.layered;
771 _overlay = classification.overlay;
772 _popupClassified = true;
773 }
774}
775
776void SdlRailWindow::setTitle(const std::string& title)
777{
778 std::unique_lock lock(_gfxLock);
779 _title = title;
780 _titleDirty = true;
781}
782
783void SdlRailWindow::setAppId(const std::string& appId)
784{
785 std::unique_lock lock(_gfxLock);
786 _appId = appId;
787 _appIdDirty = !appId.empty();
788}
789
790void SdlRailWindow::setVisible(bool visible)
791{
792 std::unique_lock lock(_gfxLock);
793 _visible = visible;
794}
795
796void SdlRailWindow::setIcon(const SdlRailIcon& icon)
797{
798 std::unique_lock lock(_gfxLock);
799 _icon = icon;
800 _iconDirty = true;
801}
802/* Caller holds _gfxLock. */
803bool SdlRailWindow::create(SDL_Window* parent, const SDL_Rect& parentRect)
804{
805 if (_win)
806 return true;
807
808 const RailPlatformCaps& caps = railPlatformCaps();
809
810 /* Local window = server rect + band insets (the outside resize band is part of our window). */
811 const SDL_Rect vis = targetOuterRect();
812 _appliedInsets = bandInsets(); /* the insets baked into the window we are about to create */
813 /* Realize full-display popups as fullscreen toplevels on Wayland. */
814 const bool fullscreen = _isPopup && !caps.supportsWindowPositions && isFullDisplaySize();
815 if (_isPopup && parent && !fullscreen)
816 {
817 /* SDL popups position parent-relative (works on Wayland too, via xdg_popup). */
818 const SDL_Rect rel = { vis.x - parentRect.x, vis.y - parentRect.y, vis.w, vis.h };
819 _requestedRel = { rel.x, rel.y };
820 _win = std::make_unique<SdlWindow>(
821 SdlWindow::createPopup(parent, rel, caps.supportsTransparentWindows, _overlay));
822 }
823 else if (_isPopup && !caps.supportsWindowPositions && !fullscreen)
824 {
825 /* No owner yet: a Wayland popup needs a parent; retry once an app window exists. */
826 WLog_VRB(TAG, "popup create deferred id=0x%08" PRIx32 ": no parent yet",
827 static_cast<uint32_t>(_id));
828 return false;
829 }
830 else
831 {
832 /* Transparent hides the band ring; a native frame needs a framed window. */
833 Uint32 flags = SDL_WINDOW_HIDDEN | SDL_WINDOW_HIGH_PIXEL_DENSITY;
834 if (_isPopup || (caps.band != RailBandMechanism::NativeFrame))
835 flags |= SDL_WINDOW_BORDERLESS;
836 if (caps.supportsTransparentWindows)
837 flags |= SDL_WINDOW_TRANSPARENT;
838 if ((_exStyle & WS_EX_NOACTIVATE) != 0)
839 flags |= SDL_WINDOW_NOT_FOCUSABLE;
840 /* SDL takes the app_id from this hint when it creates the window, so the compositor
841 * sees the right one from the first map. */
842 const char* hint = SDL_GetHint(SDL_HINT_APP_ID);
843 const std::string previous = hint ? hint : "";
844 if (!_appId.empty())
845 SDL_SetHint(SDL_HINT_APP_ID, _appId.c_str());
846 _win = std::make_unique<SdlWindow>(
847 SdlWindow::create(SDL_GetPrimaryDisplay(), _title, flags, vis));
848 if (!_appId.empty())
849 {
850 if (hint)
851 SDL_SetHint(SDL_HINT_APP_ID, previous.c_str());
852 else
853 SDL_ResetHint(SDL_HINT_APP_ID);
854 }
855 }
856 if (!_win || !_win->window() || !_win->renderer())
857 {
858 _win.reset();
859 WLog_WARN(TAG, "create failed id=0x%08" PRIx32 " %s", static_cast<uint32_t>(_id), role());
860 return false;
861 }
862 _win->resizeable(styleResizable());
863 if (fullscreen)
864 {
865 /* Cover the whole output (panel included) - the Wayland-correct way to reach 0,0. */
866 _fullscreen = true;
867 SDL_SetWindowFullscreen(_win->window(), true);
868 WLog_DBG(TAG, "fullscreen id=0x%08" PRIx32 " %dx%d (WS_POPUP spans display)",
869 static_cast<uint32_t>(_id), _windowRect.w, _windowRect.h);
870 }
871
872 /* Backend setup (Wayland seat, Win32 frame), then the server geometry again: dropping the
873 * Win32 caption grew the client area. */
874 if (!_isPopup)
875 {
876 railPlatformPrepareWindow(_win->window());
877 std::ignore = railPlatformSetWindowRect(_win->window(), vis);
878 }
879
880 WLog_DBG(TAG,
881 "create id=0x%08" PRIx32 " sdl=%" PRIu32 " %s vis=%dx%d+%d+%d margins=L%d,T%d,R%d,B%d "
882 "transparent=%d",
883 static_cast<uint32_t>(_id), static_cast<uint32_t>(_win->id()), role(), vis.w, vis.h,
884 vis.x, vis.y, _resizeMargins.x, _resizeMargins.y, _resizeMargins.w, _resizeMargins.h,
885 caps.supportsTransparentWindows ? 1 : 0);
886 return true;
887}
888
889bool SdlRailWindow::reconcile(SDL_Window* parent, const SDL_Rect& parentRect)
890{
891 std::unique_lock lock(_gfxLock);
892
893 /* Hidden windows get no local SDL window. Layered windows (e.g. docks) need GFX content and
894 * vis-rects to show; this hides empty DWM snap overlays. */
895 const bool popupReady = !_isPopup || _hasGfx;
896 /* Suppress server shadow frames and unparented full-display overlays. */
897 const bool unplaceable =
898 _frame || (_overlay && !railPlatformCaps().supportsWindowPositions && isFullDisplaySize());
899 /* Layered window is shown only when anchored to an adjoining visible popup or overlay. */
900 const bool drawable =
901 _visible && (_windowRect.w > 0) && (_windowRect.h > 0) && popupReady && !unplaceable &&
902 (!_layered || (_hasGfx && !_visRects.empty() && (_shadowAnchored || _overlay)));
903
904 if (!drawable)
905 {
906 /* Log standalone layered windows suppressed by popup shadow heuristic. */
907 if (_layered && _hasGfx && !_visRects.empty() && !_shadowAnchored && !_overlay &&
908 !_shadowSuppressLogged)
909 {
910 _shadowSuppressLogged = true;
911 WLog_DBG(TAG,
912 "shadow-rule suppressed id=0x%08" PRIx32 " %dx%d style=0x%08" PRIx32
913 " ex=0x%08" PRIx32,
914 static_cast<uint32_t>(_id), _windowRect.w, _windowRect.h, _style, _exStyle);
915 }
916 if (_win)
917 {
918 if ((SDL_GetWindowFlags(_win->window()) & SDL_WINDOW_HIDDEN) == 0)
919 {
920 WLog_DBG(TAG, "hide id=0x%08" PRIx32 " %s", static_cast<uint32_t>(_id), role());
921 SDL_HideWindow(_win->window());
922 _appIdDirty = !_appId.empty(); /* SDL destroys the Wayland toplevel on hide */
923 }
924 _mapped = false;
925 }
926 if (_isPopup && !_visible)
927 {
928 _gfxPresented = false;
929 _hasGfx = false;
930 }
931 return false;
932 }
933
934 if (!_win)
935 {
936 if (!create(parent, parentRect))
937 return false;
938 _geometryDirty = false;
939 /* Shown + raised in paint() after the first frame (created hidden). */
940 }
941
942 /* create() returned false on failure, so _win is non-null from here down. */
943 if (_topmostDirty)
944 {
945 _topmostDirty = false;
946 /* X11 only; Wayland has no protocol for this, the call still returns true. */
947 if (!_isPopup && !_layered)
948 std::ignore = SDL_SetWindowAlwaysOnTop(_win->window(), _topmost);
949 }
950
951 /* Resizability first: SDL refuses to maximize a non-resizable window. */
952 if (_styleDirty)
953 {
954 _win->resizeable(styleResizable());
955 _styleDirty = false;
956 /* Insets refresh on geometry updates to avoid flicker. */
957 }
958
959 /* State first: maximized/minimized gates the geometry apply below. */
960 /* Hold geometry sync until server sends restored rect to prevent re-maximizing. */
961 if (applyServerState(_maxState, "maximize", SDL_MaximizeWindow))
962 armDeadline(_awaitRestoreUntil, kAwaitRestoreRectMs);
963 /* Still minimized after our SC_RESTORE: ask once more, then follow the server. */
964 if ((_localRestoreUntil != 0) && (SDL_GetTicks() >= _localRestoreUntil))
965 {
966 _localRestoreUntil = 0;
967 if (_minState.server && !_minState.rail && !_restoreRetried)
968 {
969 _restoreRetried = true;
970 _restoreRetry = true;
971 armDeadline(_localRestoreUntil, kAwaitRestoreRectMs);
972 }
973 else if (_minState.server != _minState.rail)
974 _minState.dirty = true;
975 }
976 std::ignore = applyServerState(_minState, "minimize", SDL_MinimizeWindow);
977 const bool restorePending = restoreRectPending();
978
979 /* Update insets across maximize transitions outside active drag grab. */
980 const bool maxed = effectivelyMaximized();
981 const SDL_Rect band = bandInsets();
982 if ((maxed != _wasMaximized) && !_localMoveActive && !restorePending)
983 {
984 setAppliedInsets(band);
985 if (!maxed)
986 _geometryDirty = true;
987 _wasMaximized = maxed;
988 }
989
990 /* X11: set frame extents before the resize (KWin needs that), not while restoring. */
991 if ((railPlatformCaps().band == RailBandMechanism::FrameExtents) && !restorePending &&
992 !SDL_RectsEqual(&band, &_extentsApplied) && railPlatformSetBand(_win->window(), band))
993 {
994 _extentsApplied = band;
995 }
996 const bool wmOwnsGeometry =
997 _localMoveActive || geometryFrozen() || _fullscreen || restorePending;
998 /* Clamp min size hints to target bounds so stale hints do not block programmatic resize.
999 * Defer size hints and programmatic resize during active WM move/resize grab. */
1000 if ((_minMaxDirty || _geometryDirty) && !wmOwnsGeometry)
1001 {
1002 const SDL_Rect vis = targetOuterRect();
1003 const int bandW = band.x + band.w;
1004 const int bandH = band.y + band.h;
1005 /* Convert server track size hints (which include server margins) to outer window bounds. */
1006 const SDL_Rect& m = _resizeMargins;
1007 const int padW = bandW - m.x - m.w;
1008 const int padH = bandH - m.y - m.h;
1009 const auto toOuter = [](int track, int pad)
1010 { return (track > 0) ? std::max(1, track + pad) : 0; };
1011 const int minW = toOuter(_minSize.x, padW);
1012 const int minH = toOuter(_minSize.y, padH);
1013 SDL_SetWindowMinimumSize(_win->window(), std::clamp(minW, 0, vis.w),
1014 std::clamp(minH, 0, vis.h));
1015 int maxW = toOuter(_maxSize.x, padW);
1016 int maxH = toOuter(_maxSize.y, padH);
1017 /* Wayland: cap to the usable area - an oversized window cannot be dragged into reach. */
1018 SDL_Rect usable{};
1019 if (!railPlatformCaps().supportsWindowPositions &&
1020 SDL_GetDisplayUsableBounds(SDL_GetPrimaryDisplay(), &usable))
1021 {
1022 const int capW = usable.w + bandW;
1023 const int capH = usable.h + bandH;
1024 if ((maxW == 0) || (maxW > capW))
1025 maxW = capW;
1026 if ((maxH == 0) || (maxH > capH))
1027 maxH = capH;
1028 }
1029 SDL_SetWindowMaximumSize(_win->window(), maxW, maxH);
1030 _minMaxDirty = false;
1031 }
1032
1033 /* Skip geometry apply when maximized, minimized or WM-dragged. */
1034 if (_geometryDirty && !wmOwnsGeometry)
1035 {
1036 const SDL_Rect vis = targetOuterRect();
1037 /* Record applied insets so server coordinate mapping strips the exact offset. */
1038 setAppliedInsets(band);
1039 int cw = 0;
1040 int ch = 0;
1041 SDL_GetWindowSize(_win->window(), &cw, &ch);
1042 bool applied = false;
1043 bool placed = false; /* railPlatformSetWindowRect set position and size at once */
1044 /* Apply position and size if changed. */
1045 if (_isPopup && parent)
1046 {
1047 placePopup(vis, parentRect);
1048 applied = true;
1049 }
1050 else if (railPlatformCaps().supportsWindowPositions &&
1051 !(_isPopup && SDL_GetWindowParent(_win->window())))
1052 {
1053 int cx = 0;
1054 int cy = 0;
1055 SDL_GetWindowPosition(_win->window(), &cx, &cy);
1056 if ((cx != vis.x) || (cy != vis.y))
1057 {
1058 placed = railPlatformSetWindowRect(_win->window(), vis);
1059 if (!placed)
1060 SDL_SetWindowPosition(_win->window(), vis.x, vis.y);
1061 applied = true;
1062 }
1063 }
1064 if ((cw != vis.w) || (ch != vis.h))
1065 {
1066 if (!placed && !railPlatformSetWindowRect(_win->window(), vis))
1067 std::ignore = _win->resize({ vis.w, vis.h });
1068 applied = true;
1069 /* Settle window resize via SDL_SyncWindow before reading back geometry to avoid
1070 * adopting transient dimensions while configure events are in flight. */
1071 if (railPlatformCaps().supportsWindowPositions && !_isPopup && !_localMoveActive &&
1072 !_loopEnd.pending)
1073 {
1074 const bool settled = SDL_SyncWindow(_win->window());
1075 int aw = 0;
1076 int ah = 0;
1077 SDL_GetWindowSize(_win->window(), &aw, &ah);
1078 if (settled && ((aw != vis.w) || (ah != vis.h)))
1079 {
1080 /* Adopt WM size while preserving server origin. */
1081 _wmRefusedOuter = { vis.x, vis.y, aw, ah };
1082 _wmRefused = true;
1083 applied = false; /* Geometry refused by WM; do not await echo. */
1084 }
1085 }
1086 }
1087 _geometryDirty = false;
1088 /* Echo filtering is only tracked for top-level app windows. */
1089 _geomApplyPending = applied && !_isPopup;
1090 }
1091 /* Make dialog transient for owner. */
1092 /* Attach only to a shown owner: SDL hides child windows with their parent. */
1093 if (!_isPopup && parent && !_parentApplied &&
1094 ((SDL_GetWindowFlags(parent) & SDL_WINDOW_HIDDEN) == 0))
1095 {
1096 if (SDL_SetWindowParent(_win->window(), parent))
1097 {
1098 _parentApplied = true;
1099 /* Reattached after the owner was shown again: the owner was mapped on top. */
1100 if (((SDL_GetWindowFlags(_win->window()) & SDL_WINDOW_HIDDEN) == 0) &&
1101 !railPlatformRaiseOwned(_win->window()))
1102 WLog_WARN(TAG, "raising dialog id=0x%08" PRIx32 " failed",
1103 static_cast<uint32_t>(_id));
1104 }
1105 }
1106 if (_titleDirty)
1107 {
1108 if (!_isPopup)
1109 SDL_SetWindowTitle(_win->window(), _title.c_str());
1110 _titleDirty = false;
1111 }
1112 if (_appIdDirty)
1113 {
1114 /* The app_id can arrive after the window was created, and SDL sets its own on every show:
1115 * apply ours again, retrying until the xdg_toplevel exists. */
1116 if ((_isPopup && !_fullscreen) || !sdl::utils::isWaylandDriver() ||
1117 sdl_wayland_set_app_id(_win->window(), _appId.c_str()))
1118 _appIdDirty = false;
1119 }
1120 if (_iconDirty)
1121 {
1122 if (!_isPopup && !_icon.bgra.empty())
1123 {
1124 SDL_Surface* s = SDL_CreateSurfaceFrom(
1125 static_cast<int>(_icon.w), static_cast<int>(_icon.h), SDL_PIXELFORMAT_BGRA32,
1126 _icon.bgra.data(), static_cast<int>(_icon.w * 4));
1127 if (s)
1128 {
1129 if (!SDL_SetWindowIcon(_win->window(), s))
1130 WLog_WARN(TAG, "SDL_SetWindowIcon failed for window 0x%08" PRIx32 ": %s",
1131 static_cast<uint32_t>(_id), SDL_GetError());
1132 SDL_DestroySurface(s);
1133 }
1134 }
1135 _iconDirty = false;
1136 }
1137
1138 /* Defer show until first frame; this runs every reconcile, so skip the call once visible. */
1139 if (!_minState.rail && _gfxPresented &&
1140 (SDL_GetWindowFlags(_win->window()) & SDL_WINDOW_HIDDEN))
1141 {
1142 /* If transient-for owner was closed or hidden, show dialog standalone. */
1143 SDL_Window* owner = _isPopup ? nullptr : SDL_GetWindowParent(_win->window());
1144 if (owner && ((SDL_GetWindowFlags(owner) & SDL_WINDOW_HIDDEN) != 0))
1145 {
1146 if (SDL_SetWindowParent(_win->window(), nullptr))
1147 _parentApplied = false; /* reattach once the owner is shown again */
1148 else
1149 WLog_WARN(TAG, "detaching dialog id=0x%08" PRIx32 " failed: %s",
1150 static_cast<uint32_t>(_id), SDL_GetError());
1151 }
1152 SDL_ShowWindow(_win->window());
1153 }
1154 return true;
1155}
1156
1157bool SdlRailWindow::takeSurfaceChange(uint32_t surfaceId)
1158{
1159 std::unique_lock lock(_gfxLock);
1160 if (_surfaceId == surfaceId)
1161 return false;
1162 _surfaceId = surfaceId;
1163 return true;
1164}
1165
1166void SdlRailWindow::updateGfxSurface(const void* data, uint32_t stride, uint32_t width,
1167 uint32_t height, const RECTANGLE_16* damage, uint32_t nbDamage,
1168 WINPR_ATTR_UNUSED uint32_t format)
1169{
1170 std::unique_lock lock(_gfxLock);
1171 /* The copies below are byte-for-byte; gdi_CreateSurface yields nothing else. */
1172 WINPR_ASSERT((format == PIXEL_FORMAT_BGRA32) || (format == PIXEL_FORMAT_BGRX32));
1173 /* Deep-copy GDI pixels to prevent UAF. */
1174 const size_t bytes = static_cast<size_t>(stride) * height;
1175 if (!data || (bytes == 0) || (width == 0) || (height == 0))
1176 {
1177 if (_hasGfx)
1178 WLog_DBG(TAG, "gfx cleared id=0x%08" PRIx32 " (surface unmapped)",
1179 static_cast<uint32_t>(_id));
1180 _gfxBuffer.clear();
1181 _hasGfx = false;
1182 _gfxDamage.clear();
1183 _gfxStride = stride;
1184 _gfxW = width;
1185 _gfxH = height;
1186 _gfxVisOrigin = { 0, 0 };
1187 return;
1188 }
1189
1190 const auto* src = static_cast<const uint8_t*>(data);
1191 /* Geometry/stride change, first frame, or no damage rects: full copy + repaint. */
1192 const bool full = !_hasGfx || (_gfxBuffer.size() != bytes) || (_gfxStride != stride) ||
1193 (_gfxW != width) || (_gfxH != height) || (nbDamage == 0);
1194 if (full)
1195 {
1196 const SDL_Rect bounds{ 0, 0, static_cast<int>(width), static_cast<int>(height) };
1197 /* Check _hasGfx first to avoid redundant full-surface blank checks once content exists. */
1198 if (!_hasGfx && regionIsBlank(src, stride, bounds))
1199 return;
1200 _gfxBuffer.assign(src, src + bytes);
1201 _gfxDamage.assign(1, SDL_Rect{ 0, 0, static_cast<int>(width), static_cast<int>(height) });
1202 _needsFullBlit = true;
1203 /* Blend real alpha, force opaque otherwise. */
1204 _gfxHasAlpha = honorsAlpha() &&
1205 regionHasAlpha(_gfxBuffer.data(), stride,
1206 { 0, 0, static_cast<int>(width), static_cast<int>(height) });
1207 }
1208 else
1209 {
1210 const SDL_Rect bounds{ 0, 0, static_cast<int>(width), static_cast<int>(height) };
1211 for (uint32_t i = 0; i < nbDamage; i++)
1212 {
1213 const SDL_Rect r{ damage[i].left, damage[i].top, damage[i].right - damage[i].left,
1214 damage[i].bottom - damage[i].top };
1215 SDL_Rect clip{};
1216 if (!SDL_GetRectIntersection(&r, &bounds, &clip))
1217 continue;
1218 std::ignore = freerdp_image_copy_no_overlap(
1219 _gfxBuffer.data(), PIXEL_FORMAT_BGRA32, stride, static_cast<UINT32>(clip.x),
1220 static_cast<UINT32>(clip.y), static_cast<UINT32>(clip.w),
1221 static_cast<UINT32>(clip.h), src, PIXEL_FORMAT_BGRA32, stride,
1222 static_cast<UINT32>(clip.x), static_cast<UINT32>(clip.y), nullptr,
1223 FREERDP_FLIP_NONE);
1224 _gfxDamage.push_back(clip);
1225 /* Alpha may first appear in a later incremental frame (e.g. a menu fading in). */
1226 if (honorsAlpha() && !_gfxHasAlpha && regionHasAlpha(_gfxBuffer.data(), stride, clip))
1227 _gfxHasAlpha = true;
1228 }
1229 /* A hidden window accumulates rects without ever painting; collapse to one full repaint. */
1230 if (_gfxDamage.size() > 32)
1231 _gfxDamage.assign(1,
1232 SDL_Rect{ 0, 0, static_cast<int>(width), static_cast<int>(height) });
1233 }
1234 if ((_gfxW != width) || (_gfxH != height))
1235 {
1236 _resizeAnchorRight = false;
1237 _resizeAnchorBottom = false;
1238 _needsFullBlit = true;
1239 /* Invalidate surface origin until visibility rect matching new dimensions arrives. */
1240 _gfxVisOrigin = { 0, 0 };
1241 }
1242 _hasGfx = true;
1243 _gfxStride = stride;
1244 _gfxW = width;
1245 _gfxH = height;
1246 WLog_VRB(TAG, "gfx id=0x%08" PRIx32 " %ux%u full=%d nDamage=%u", static_cast<uint32_t>(_id),
1247 width, height, full ? 1 : 0, nbDamage);
1248}
1249
1250void SdlRailWindow::invalidateAll()
1251{
1252 std::unique_lock lock(_gfxLock);
1253 _needsFullBlit = true;
1254 if (_hasGfx)
1255 _gfxDamage.assign(1, SDL_Rect{ 0, 0, static_cast<int>(_gfxW), static_cast<int>(_gfxH) });
1256}
1257
1258void SdlRailWindow::setServerState(StateSync& s, bool m)
1259{
1260 std::unique_lock lock(_gfxLock);
1261 if (m != s.server)
1262 {
1263 s.server = m;
1264 s.dirty = true;
1265 }
1266}
1267
1268void SdlRailWindow::setServerMaximized(bool m)
1269{
1270 setServerState(_maxState, m);
1271}
1272
1273void SdlRailWindow::setServerMinimized(bool m)
1274{
1275 {
1276 std::unique_lock lock(_gfxLock);
1277 /* Late minimize of a window the user already restored. */
1278 if (m && (_localRestoreUntil != 0) && (SDL_GetTicks() < _localRestoreUntil))
1279 {
1280 _minState.server = true;
1281 return;
1282 }
1283 if (!m)
1284 _localRestoreUntil = 0;
1285 }
1286 setServerState(_minState, m);
1287}
1288
1289void SdlRailWindow::noteLocalRestore()
1290{
1291 std::unique_lock lock(_gfxLock);
1292 _restoreRetried = false;
1293 armDeadline(_localRestoreUntil, kAwaitRestoreRectMs);
1294}
1295
1296bool SdlRailWindow::takeRestoreRetry()
1297{
1298 std::unique_lock lock(_gfxLock);
1299 return std::exchange(_restoreRetry, false);
1300}
1301
1302bool SdlRailWindow::applyServerState(StateSync& s, const char* what, bool (*enter)(SDL_Window*))
1303{
1304 if (!s.dirty)
1305 return false;
1306 bool restored = false;
1307 if (s.server && !s.rail)
1308 {
1309 /* Apply server maximize/minimize state. */
1310 s.rail = true;
1311 WLog_DBG(TAG, "%s id=0x%08" PRIx32 "", what, static_cast<uint32_t>(_id));
1312 enter(_win->window());
1313 }
1314 else if (!s.server && s.rail)
1315 {
1316 restored = true;
1317 s.rail = false;
1318 WLog_DBG(TAG, "restore id=0x%08" PRIx32 " (%s)", static_cast<uint32_t>(_id), what);
1319 SDL_RestoreWindow(_win->window());
1320 }
1321 else
1322 {
1323 s.dirty = false;
1324 return false;
1325 }
1326 /* Settle WM state before reading window properties. */
1327 (void)SDL_SyncWindow(_win->window());
1328 s.dirty = false;
1329 return restored;
1330}
1331
1332/* Caller holds _gfxLock. */
1333void SdlRailWindow::setAppliedInsets(const SDL_Rect& insets)
1334{
1335 if (SDL_RectsEqual(&insets, &_appliedInsets))
1336 return;
1337 _appliedInsets = insets;
1338 _needsFullBlit = true;
1339}
1340
1341bool SdlRailWindow::insetsStale() const
1342{
1343 std::unique_lock lock(_gfxLock);
1344 return _wasMaximized != effectivelyMaximized();
1345}
1346
1347/* Caller holds _gfxLock. */
1348bool SdlRailWindow::restoreRectPending() const
1349{
1350 return (_awaitRestoreUntil != 0) && (SDL_GetTicks() < _awaitRestoreUntil);
1351}
1352
1353bool SdlRailWindow::effectivelyMaximized() const
1354{
1355 return _maxState.rail ||
1356 (_win && (SDL_GetWindowFlags(_win->window()) & SDL_WINDOW_MAXIMIZED) != 0);
1357}
1358
1359bool SdlRailWindow::paint(SDL_Surface* primary, SDL_PixelFormat fallbackFormat,
1360 const std::vector<SDL_Rect>& damage, SDL_Window* parent,
1361 const SDL_Rect& parentRect)
1362{
1363 if (!reconcile(parent, parentRect))
1364 return false;
1365
1366 auto ok = false;
1367 auto legacy = false;
1368 {
1369 std::unique_lock lock(_gfxLock);
1370 if (_hasGfx)
1371 ok = paintGfx(fallbackFormat);
1372 else
1373 legacy = true;
1374 }
1375 if (legacy)
1376 ok = paintLegacy(primary, damage);
1377
1378 /* Map in the same pass as the first frame, else the window defers a frame (menu lag). */
1379 if (_gfxPresented && !_mapped && !_minState.rail)
1380 {
1381 _mapped = true;
1382 WLog_DBG(TAG, "map id=0x%08" PRIx32 " %s", static_cast<uint32_t>(_id), role());
1383 SDL_ShowWindow(_win->window());
1384 /* Reassert target position after show to override stale events. */
1385 if (_isPopup && parent)
1386 {
1387 std::unique_lock lock(_gfxLock);
1388 const SDL_Rect vis = targetOuterRect();
1389 placePopup(vis, parentRect);
1390 }
1391 if (((!_isPopup && !_layered) || _fullscreen) && ((_exStyle & WS_EX_NOACTIVATE) == 0))
1392 _win->raise(); /* Bring app and fullscreen windows to front. */
1393 }
1394 return ok;
1395}
1396
1397/* Caller holds _gfxLock. Blits the window-mapped GFX surface via the shared SdlWindow path. */
1398bool SdlRailWindow::paintGfx(SDL_PixelFormat format)
1399{
1400 if (holdForPlacement())
1401 return true;
1402 /* Blit using applied insets to preserve resize borders. */
1403 const SDL_Rect bi = _appliedInsets;
1404 int ww = 0;
1405 int wh = 0;
1406 SDL_GetWindowSizeInPixels(_win->window(), &ww, &wh);
1407 const int cw = ww - bi.x - bi.w; /* content area inside the insets */
1408 const int ch = wh - bi.y - bi.h;
1409 const int gw =
1410 static_cast<int>(_gfxW); /* GFX surface size as int (used across the blit paths) */
1411 const int gh = static_cast<int>(_gfxH);
1412 /* Only adopt visibility origin rects that match current surface dimensions. */
1413 if ((_visRects.size() == 1) && (_visRects.at(0).w == gw) && (_visRects.at(0).h == gh))
1414 _gfxVisOrigin = { _visRects.at(0).x, _visRects.at(0).y };
1415 /* Server surface caught up with the content area: the drag is fully settled. */
1416 if (!_localMoveActive && (cw == gw) && (ch == gh))
1417 {
1418 _resizeAnchorRight = false;
1419 _resizeAnchorBottom = false;
1420 _awaitingFrameUntil = 0;
1421 }
1422 /* Timeout safety net for server resize frame anchoring. */
1423 if ((_awaitingFrameUntil != 0) && (SDL_GetTicks() > _awaitingFrameUntil))
1424 {
1425 WLog_DBG(TAG, "resize frame timeout id=0x%08" PRIx32 " win=%dx%d gfx=%dx%d",
1426 static_cast<uint32_t>(_id), cw, ch, gw, gh);
1427 _awaitingFrameUntil = 0;
1428 /* Adopt server surface dimensions if resize was clamped. */
1429 if ((cw != gw) || (ch != gh))
1430 {
1431 if (_resizeAnchorRight)
1432 _windowRect.x += _windowRect.w - gw;
1433 if (_resizeAnchorBottom)
1434 _windowRect.y += _windowRect.h - gh;
1435 _windowRect.w = gw;
1436 _windowRect.h = gh;
1437 _resizeAnchorRight = false;
1438 _resizeAnchorBottom = false;
1439 _geometryDirty = true;
1440 _needsFullBlit = true;
1441 }
1442 }
1443
1444 /* Keep stale frame anchored while awaiting server GFX surface. */
1445 const bool awaitingServerResize = (_awaitingFrameUntil != 0) && ((cw != gw) || (ch != gh));
1446 const bool localResize = awaitingServerResize ||
1447 (_localMoveActive && (_localMoveIsResize || (cw != gw) || (ch != gh)));
1448
1449 /* Window or surface size changed outside a drag: repaint once even without damage. */
1450 const bool winResized = (ww != _lastWinW) || (wh != _lastWinH);
1451 const bool gfxResized = (gw != _lastGfxW) || (gh != _lastGfxH);
1452 const bool serverResize =
1453 !_localMoveActive && !awaitingServerResize &&
1454 (winResized || gfxResized || _needsFullBlit || _pendingRel.has_value());
1455
1456 /* Skip undamaged frames. */
1457 if (!localResize && !serverResize && _gfxDamage.empty() && !(_layered && _visDirty))
1458 {
1459 WLog_VRB(TAG, "paintGfx skip id=0x%08" PRIx32 " no-damage no-resize",
1460 static_cast<uint32_t>(_id));
1461 return true;
1462 }
1463
1464 /* Gate popup mapping until initial content is presented to prevent black flash. */
1465 if (_isPopup && !_gfxPresented && (_gfxW > 0) && (_gfxH > 0))
1466 {
1467 const uint32_t first = *reinterpret_cast<const uint32_t*>(_gfxBuffer.data());
1468 /* BGRA32 as a host word: alpha on top, so mask it off and test the colour alone. */
1469 bool uniform = (first & 0x00FFFFFFu) == 0;
1470 for (uint32_t y = 0; uniform && (y < _gfxH); y++)
1471 {
1472 const auto* row = reinterpret_cast<const uint32_t*>(
1473 _gfxBuffer.data() + static_cast<size_t>(y) * _gfxStride);
1474 for (uint32_t x = 0; x < _gfxW; x++)
1475 if (row[x] != first)
1476 {
1477 uniform = false;
1478 break;
1479 }
1480 }
1481 if (uniform)
1482 {
1483 /* Disarm repaint triggers while popup surface remains blank. */
1484 _gfxDamage.clear();
1485 _needsFullBlit = false;
1486 _lastWinW = ww;
1487 _lastWinH = wh;
1488 _lastGfxW = gw;
1489 _lastGfxH = gh;
1490 return true;
1491 }
1492 }
1493
1494 /* RAIL content is mostly opaque (ignore alpha). Exception: layered app windows. */
1495 SDL_PixelFormat contentFormat = format;
1496 if (format == SDL_PIXELFORMAT_BGRA32)
1497 {
1498 const bool blend = railPlatformCaps().supportsTransparentWindows;
1499 if (!blend || (_isPopup && !_layered && !_gfxHasAlpha))
1500 contentFormat = SDL_PIXELFORMAT_BGRX32;
1501 }
1502
1503 SDL_Surface* s = SDL_CreateSurfaceFrom(gw, gh, contentFormat, _gfxBuffer.data(),
1504 static_cast<int>(_gfxStride));
1505 if (!s)
1506 {
1507 WLog_WARN(TAG, "paintGfx id=0x%08" PRIx32 " SDL_CreateSurfaceFrom failed: %s",
1508 static_cast<uint32_t>(_id), SDL_GetError());
1509 return false;
1510 }
1511
1512 /* Content blits at the inset offset; the ring outside it is the transparent resize band. */
1513 if (localResize)
1514 {
1515 /* Crop frame rows during mid-drag restore until new surface arrives. */
1516 const SDL_Point crop = { std::clamp(_gfxVisOrigin.x, 0, gw),
1517 std::clamp(_gfxVisOrigin.y, 0, gh) };
1518 /* Anchor the stale frame to the fixed corner. */
1519 const SDL_Point off = { (_resizeAnchorRight ? (ww - bi.w - gw) : bi.x) - crop.x,
1520 (_resizeAnchorBottom ? (wh - bi.h - gh) : bi.y) - crop.y };
1521 /* Show dashes only during active drag; on release, keep the clean anchored frame. */
1522 const bool showDashes = _localMoveActive && _localMoveIsResize;
1523 /* Only fill revealed area during resize, not move drag. */
1524 const bool fillRevealed = showDashes || awaitingServerResize;
1525 std::ignore =
1526 _win->paintResizeFrame(s, off, !_gfxDamage.empty(), bi, fillRevealed, showDashes);
1527 }
1528 else
1529 {
1530 /* Render accumulated damage or re-blit full surface on bare resize. */
1531 const SDL_Rect full = { 0, 0, gw, gh };
1532 const SDL_Point dst = blitOffset();
1533 const bool maxed = effectivelyMaximized();
1534 if (_layered && !_visRects.empty() && !maxed)
1535 {
1536 /* Layered shadow cutout: draw only inside visibility rects. */
1537 const bool logClip = _visDirty;
1538 /* Consume full-blit request on resize. */
1539 if (_visDirty || serverResize)
1540 {
1541 /* Wipe so newly-excluded regions don't keep stale pixels. */
1542 std::ignore = _win->fill(static_cast<Uint8>(0), 0, 0, 0);
1543 _gfxDamage.assign(1, full);
1544 _visDirty = false;
1545 _needsFullBlit = false;
1546 }
1547 const SDL_Point off = { _visOffsetSet ? (_visOffset.x - _windowRect.x) : 0,
1548 _visOffsetSet ? (_visOffset.y - _windowRect.y) : 0 };
1549 if (logClip)
1550 WLog_VRB(TAG,
1551 "clip id=0x%08" PRIx32 " off=%d,%d nVis=%zu vis0=%dx%d+%d+%d win=%dx%d "
1552 "gfx=%ux%u",
1553 static_cast<uint32_t>(_id), off.x, off.y, _visRects.size(),
1554 _visRects.at(0).w, _visRects.at(0).h, _visRects.at(0).x, _visRects.at(0).y,
1555 ww, wh, _gfxW, _gfxH);
1556 const std::vector<SDL_Rect>& damageRects = _gfxDamage;
1557 std::vector<SDL_Rect> draw;
1558 draw.reserve(damageRects.size() * _visRects.size());
1559 for (const auto& d : damageRects)
1560 {
1561 for (auto v : _visRects)
1562 {
1563 v.x += off.x;
1564 v.y += off.y;
1565 SDL_Rect part{};
1566 if (SDL_GetRectIntersection(&d, &v, &part))
1567 draw.push_back(part);
1568 }
1569 }
1570 if (!draw.empty()) /* empty vector would mean "draw everything" to drawRects */
1571 std::ignore = _win->drawRects(s, dst, draw);
1572 }
1573 else if (_gfxDamage.empty() || serverResize)
1574 {
1575 /* Clear target and redraw surface on size change. */
1576 if (serverResize)
1577 {
1578 const bool transparentWin =
1579 (SDL_GetWindowFlags(_win->window()) & SDL_WINDOW_TRANSPARENT) != 0;
1580 /* Wipe surface to avoid black border artifacts on opaque windows. */
1581 std::ignore = _win->fill(static_cast<Uint8>(0), 0, 0,
1582 static_cast<Uint8>(transparentWin ? 0x00 : 0xFF));
1583 _needsFullBlit = false;
1584 }
1585 std::ignore = _win->drawRects(s, dst, { full });
1586 }
1587 else
1588 {
1589 std::ignore = _win->drawRects(s, dst, _gfxDamage);
1590 }
1591
1592 _win->updateSurface();
1593 _gfxPresented = true; /* First frame rendered; paint() may map the window. */
1594 commitPlacement();
1595 }
1596 SDL_DestroySurface(s);
1597 WLog_VRB(TAG, "paintGfx id=0x%08" PRIx32 " mode=%s win=%dx%d dmg=%zu",
1598 static_cast<uint32_t>(_id),
1599 localResize ? "resize" : (serverResize ? "server-resize" : "gfx"), ww, wh,
1600 _gfxDamage.size());
1601 _gfxDamage.clear();
1602 /* Preserve size baseline during local resize. */
1603 if (!localResize)
1604 {
1605 _lastWinW = ww;
1606 _lastWinH = wh;
1607 _lastGfxW = gw;
1608 _lastGfxH = gh;
1609 }
1610 return true;
1611}
1612
1613bool SdlRailWindow::paintLegacy(SDL_Surface* primary, const std::vector<SDL_Rect>& damage)
1614{
1615 SDL_Rect rect{};
1616 SDL_Rect bi{};
1617 std::vector<SDL_Rect> vis;
1618 bool full = false;
1619 {
1620 std::unique_lock lock(_gfxLock);
1621 /* Layered decorations have no meaningful content in the shared primary. */
1622 if (!primary || _layered || (_windowRect.w <= 0) || (_windowRect.h <= 0) ||
1623 holdForPlacement())
1624 return true;
1625
1626 /* Damage-driven: re-copy only server-updated regions, keep the last frame elsewhere. */
1627 full = !_painted || _pendingRel.has_value();
1628 if (!full && damage.empty())
1629 {
1630 WLog_VRB(TAG, "paintLegacy skip id=0x%08" PRIx32 " no-damage",
1631 static_cast<uint32_t>(_id));
1632 return true;
1633 }
1634
1635 rect = _windowRect;
1636 bi = _appliedInsets;
1637 vis = _visRects;
1638 }
1639
1640 if (vis.empty())
1641 vis.push_back({ 0, 0, rect.w, rect.h });
1642
1643 /* Paint only the visible sub-rects (stacked windows don't bleed through), clamped and 1:1. */
1644 const SDL_Rect bounds = { 0, 0, primary->w, primary->h };
1645 bool blitted = false;
1646 for (const auto& v : vis)
1647 {
1648 SDL_Rect src = { rect.x + v.x, rect.y + v.y, v.w, v.h };
1649 SDL_Rect clipped{};
1650 if (!SDL_GetRectIntersection(&src, &bounds, &clipped))
1651 continue;
1652
1653 if (full)
1654 {
1655 SDL_Rect dst = { clipped.x - rect.x + bi.x, clipped.y - rect.y + bi.y, clipped.w,
1656 clipped.h };
1657 if (_win->blit(primary, clipped, dst))
1658 blitted = true;
1659 continue;
1660 }
1661 for (const auto& d : damage)
1662 {
1663 SDL_Rect part{};
1664 if (!SDL_GetRectIntersection(&clipped, &d, &part))
1665 continue;
1666 SDL_Rect dst = { part.x - rect.x + bi.x, part.y - rect.y + bi.y, part.w, part.h };
1667 if (_win->blit(primary, part, dst))
1668 blitted = true;
1669 }
1670 }
1671 if (blitted)
1672 {
1673 {
1674 std::unique_lock lock(_gfxLock);
1675 _painted = true;
1676 }
1677 _win->updateSurface();
1678 {
1679 std::unique_lock lock(_gfxLock);
1680 commitPlacement();
1681 }
1682 WLog_VRB(TAG, "paintLegacy id=0x%08" PRIx32 " full=%d visRects=%zu",
1683 static_cast<uint32_t>(_id), full ? 1 : 0, vis.size());
1684 /* Defer mapping until GFX frame arrives to avoid desktop flash. */
1685 }
1686 return true;
1687}
#define TAG