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