Debian Codegraph @

xbmc/windowing/wayland/WinSystemWayland.cpp

raw
1 /*
2 * Copyright (C) 2017-2018 Team Kodi
3 * This file is part of Kodi - https://kodi.tv
4 *
5 * SPDX-License-Identifier: GPL-2.0-or-later
6 * See LICENSES/README.md for more information.
7 */
8
9 #include "WinSystemWayland.h"
10
11 #include "CompileInfo.h"
12 #include "Connection.h"
13 #include "OSScreenSaverIdleInhibitUnstableV1.h"
14 #include "OptionalsReg.h"
15 #include "Registry.h"
16 #include "ServiceBroker.h"
17 #include "ShellSurfaceWlShell.h"
18 #include "ShellSurfaceXdgShell.h"
19 #include "ShellSurfaceXdgShellUnstableV6.h"
20 #include "Util.h"
21 #include "VideoSyncWpPresentation.h"
22 #include "WinEventsWayland.h"
23 #include "WindowDecorator.h"
24 #include "application/Application.h"
25 #include "cores/RetroPlayer/process/wayland/RPProcessInfoWayland.h"
26 #include "cores/VideoPlayer/Process/wayland/ProcessInfoWayland.h"
27 #include "cores/VideoPlayer/VideoReferenceClock.h"
28 #include "guilib/DispResource.h"
29 #include "guilib/LocalizeStrings.h"
30 #include "input/InputManager.h"
31 #include "input/touch/generic/GenericTouchActionHandler.h"
32 #include "input/touch/generic/GenericTouchInputHandler.h"
33 #include "messaging/ApplicationMessenger.h"
34 #include "settings/AdvancedSettings.h"
35 #include "settings/DisplaySettings.h"
36 #include "settings/Settings.h"
37 #include "settings/SettingsComponent.h"
38 #include "settings/lib/Setting.h"
39 #include "utils/ActorProtocol.h"
40 #include "utils/MathUtils.h"
41 #include "utils/StringUtils.h"
42 #include "utils/TimeUtils.h"
43 #include "utils/log.h"
44 #include "windowing/linux/OSScreenSaverFreedesktop.h"
45
46 #include "platform/linux/TimeUtils.h"
47
48 #include <algorithm>
49 #include <limits>
50 #include <memory>
51 #include <mutex>
52 #include <numeric>
53
54 using namespace KODI::WINDOWING;
55 using namespace KODI::WINDOWING::WAYLAND;
56 using namespace std::placeholders;
57 using namespace std::chrono_literals;
58
59 namespace
60 {
61
62 RESOLUTION FindMatchingCustomResolution(CSizeInt size, float refreshRate)
63 {
64 for (size_t res{RES_DESKTOP}; res < CDisplaySettings::GetInstance().ResolutionInfoSize(); ++res)
65 {
66 auto const& resInfo = CDisplaySettings::GetInstance().GetResolutionInfo(res);
67 if (resInfo.iWidth == size.Width() && resInfo.iHeight == size.Height() && MathUtils::FloatEquals(resInfo.fRefreshRate, refreshRate, 0.0005f))
68 {
69 return static_cast<RESOLUTION> (res);
70 }
71 }
72 return RES_INVALID;
73 }
74
75 struct OutputScaleComparer
76 {
77 bool operator()(std::shared_ptr<COutput> const& output1, std::shared_ptr<COutput> const& output2)
78 {
79 return output1->GetScale() < output2->GetScale();
80 }
81 };
82
83 struct OutputCurrentRefreshRateComparer
84 {
85 bool operator()(std::shared_ptr<COutput> const& output1, std::shared_ptr<COutput> const& output2)
86 {
87 return output1->GetCurrentMode().refreshMilliHz < output2->GetCurrentMode().refreshMilliHz;
88 }
89 };
90
91 /// Scope guard for Actor::Message
92 class MessageHandle : public KODI::UTILS::CScopeGuard<Actor::Message*, nullptr, void(Actor::Message*)>
93 {
94 public:
95 MessageHandle() : CScopeGuard{std::bind(&Actor::Message::Release, std::placeholders::_1), nullptr} {}
96 explicit MessageHandle(Actor::Message* message) : CScopeGuard{std::bind(&Actor::Message::Release, std::placeholders::_1), message} {}
97 Actor::Message* Get() { return static_cast<Actor::Message*> (*this); }
98 };
99
100 /**
101 * Protocol for communication between Wayland event thread and main thread
102 *
103 * Many messages received from the Wayland compositor must be processed at a
104 * defined time between frame rendering, such as resolution switches. Thus
105 * they are pushed to the main thread for processing.
106 *
107 * The protocol is strictly uni-directional from event to main thread at the moment,
108 * so \ref Actor::Protocol is mainly used as an event queue.
109 */
110 namespace WinSystemWaylandProtocol
111 {
112
113 enum OutMessage
114 {
115 CONFIGURE,
116 OUTPUT_HOTPLUG,
117 BUFFER_SCALE
118 };
119
120 struct MsgConfigure
121 {
122 std::uint32_t serial;
123 CSizeInt surfaceSize;
124 IShellSurface::StateBitset state;
125 };
126
127 struct MsgBufferScale
128 {
129 int scale;
130 };
131
132 };
133
134 }
135
136 CWinSystemWayland::CWinSystemWayland()
137 : CWinSystemBase{}, m_protocol{"WinSystemWaylandInternal"}
138 {
139 m_winEvents = std::make_unique<CWinEventsWayland>();
140 }
141
142 CWinSystemWayland::~CWinSystemWayland() noexcept
143 {
144 DestroyWindowSystem();
145 }
146
147 bool CWinSystemWayland::InitWindowSystem()
148 {
149 const char* env = getenv("WAYLAND_DISPLAY");
150 if (!env)
151 {
152 CLog::Log(LOGDEBUG, "CWinSystemWayland::{} - WAYLAND_DISPLAY env not set", __FUNCTION__);
153 return false;
154 }
155
156 wayland::set_log_handler([](const std::string& message)
157 { CLog::Log(LOGWARNING, "wayland-client log message: {}", message); });
158
159 CLog::LogF(LOGINFO, "Connecting to Wayland server");
160 m_connection = std::make_unique<CConnection>();
161 if (!m_connection->HasDisplay())
162 return false;
163
164 VIDEOPLAYER::CProcessInfoWayland::Register();
165 RETRO::CRPProcessInfoWayland::Register();
166
167 m_registry = std::make_unique<CRegistry>(*m_connection);
168
169 m_registry->RequestSingleton(m_compositor, 1, 4);
170 m_registry->RequestSingleton(m_shm, 1, 1);
171 m_registry->RequestSingleton(m_presentation, 1, 1, false);
172 // version 2 adds done() -> required
173 // version 3 adds destructor -> optional
174 m_registry->Request<wayland::output_t>(2, 3, std::bind(&CWinSystemWayland::OnOutputAdded, this, _1, _2), std::bind(&CWinSystemWayland::OnOutputRemoved, this, _1));
175
176 m_registry->Bind();
177
178 if (m_presentation)
179 {
180 m_presentation.on_clock_id() = [this](std::uint32_t clockId)
181 {
182 CLog::Log(LOGINFO, "Wayland presentation clock: {}", clockId);
183 m_presentationClock = static_cast<clockid_t> (clockId);
184 };
185 }
186
187 // Do another roundtrip to get initial wl_output information
188 m_connection->GetDisplay().roundtrip();
189 if (m_outputs.empty())
190 {
191 throw std::runtime_error("No outputs received from compositor");
192 }
193
194 // Event loop is started in CreateWindow
195
196 // pointer is by default not on this window, will be immediately rectified
197 // by the enter() events if it is
198 CServiceBroker::GetInputManager().SetMouseActive(false);
199 // Always use the generic touch action handler
200 CGenericTouchInputHandler::GetInstance().RegisterHandler(&CGenericTouchActionHandler::GetInstance());
201
202 CServiceBroker::GetSettingsComponent()
203 ->GetSettings()
204 ->GetSetting(CSettings::SETTING_VIDEOSCREEN_LIMITEDRANGE)
205 ->SetVisible(true);
206
207 return CWinSystemBase::InitWindowSystem();
208 }
209
210 bool CWinSystemWayland::DestroyWindowSystem()
211 {
212 DestroyWindow();
213 // wl_display_disconnect frees all proxy objects, so we have to make sure
214 // all stuff is gone on the C++ side before that
215 m_cursorSurface = wayland::surface_t{};
216 m_cursorBuffer = wayland::buffer_t{};
217 m_cursorImage = wayland::cursor_image_t{};
218 m_cursorTheme = wayland::cursor_theme_t{};
219 m_outputsInPreparation.clear();
220 m_outputs.clear();
221 m_frameCallback = wayland::callback_t{};
222 m_screenSaverManager.reset();
223
224 m_seatInputProcessing.reset();
225
226 if (m_registry)
227 {
228 m_registry->UnbindSingletons();
229 }
230 m_registry.reset();
231 m_connection.reset();
232
233 CGenericTouchInputHandler::GetInstance().UnregisterHandler();
234
235 return CWinSystemBase::DestroyWindowSystem();
236 }
237
238 bool CWinSystemWayland::CreateNewWindow(const std::string& name,
239 bool fullScreen,
240 RESOLUTION_INFO& res)
241 {
242 CLog::LogF(LOGINFO, "Starting {} size {}x{}", fullScreen ? "full screen" : "windowed", res.iWidth,
243 res.iHeight);
244
245 m_surface = m_compositor.create_surface();
246 m_surface.on_enter() = [this](const wayland::output_t& wloutput) {
247 if (auto output = FindOutputByWaylandOutput(wloutput))
248 {
249 CLog::Log(LOGDEBUG, "Entering output \"{}\" with scale {} and {:.3f} dpi",
250 UserFriendlyOutputName(output), output->GetScale(), output->GetCurrentDpi());
251 std::unique_lock<CCriticalSection> lock(m_surfaceOutputsMutex);
252 m_surfaceOutputs.emplace(output);
253 lock.unlock();
254 UpdateBufferScale();
255 UpdateTouchDpi();
256 }
257 else
258 {
259 CLog::Log(LOGWARNING, "Entering output that was not configured yet, ignoring");
260 }
261 };
262 m_surface.on_leave() = [this](const wayland::output_t& wloutput) {
263 if (auto output = FindOutputByWaylandOutput(wloutput))
264 {
265 CLog::Log(LOGDEBUG, "Leaving output \"{}\" with scale {}", UserFriendlyOutputName(output),
266 output->GetScale());
267 std::unique_lock<CCriticalSection> lock(m_surfaceOutputsMutex);
268 m_surfaceOutputs.erase(output);
269 lock.unlock();
270 UpdateBufferScale();
271 UpdateTouchDpi();
272 }
273 else
274 {
275 CLog::Log(LOGWARNING, "Leaving output that was not configured yet, ignoring");
276 }
277 };
278
279 m_windowDecorator = std::make_unique<CWindowDecorator>(*this, *m_connection, m_surface);
280
281 m_seatInputProcessing = std::make_unique<CSeatInputProcessing>(m_surface, *this);
282 m_seatRegistry = std::make_unique<CRegistry>(*m_connection);
283 // version 2 adds name event -> optional
284 // version 4 adds wl_keyboard repeat_info -> optional
285 // version 5 adds discrete axis events in wl_pointer -> unused
286 m_seatRegistry->Request<wayland::seat_t>(1, 5, std::bind(&CWinSystemWayland::OnSeatAdded, this, _1, _2), std::bind(&CWinSystemWayland::OnSeatRemoved, this, _1));
287 m_seatRegistry->Bind();
288
289 if (m_seats.empty())
290 {
291 CLog::Log(LOGWARNING, "Wayland compositor did not announce a wl_seat - you will not have any input devices for the time being");
292 }
293
294 if (fullScreen)
295 {
296 m_shellSurfaceState.set(IShellSurface::STATE_FULLSCREEN);
297 }
298 // Assume we're active on startup until someone tells us otherwise
299 m_shellSurfaceState.set(IShellSurface::STATE_ACTIVATED);
300 // Try with this resolution if compositor does not say otherwise
301 UpdateSizeVariables({res.iWidth, res.iHeight}, m_scale, m_shellSurfaceState, false);
302
303 // Use AppName as the desktop file name. This is required to lookup the app icon of the same name.
304 m_shellSurface.reset(CreateShellSurface(name));
305
306 if (fullScreen)
307 {
308 // Try to start on correct monitor and with correct buffer scale
309 auto output = FindOutputByUserFriendlyName(CServiceBroker::GetSettingsComponent()->GetSettings()->GetString(CSettings::SETTING_VIDEOSCREEN_MONITOR));
310 auto wlOutput = output ? output->GetWaylandOutput() : wayland::output_t{};
311 m_lastSetOutput = wlOutput;
312 m_shellSurface->SetFullScreen(wlOutput, res.fRefreshRate);
313 if (output && m_surface.can_set_buffer_scale())
314 {
315 m_scale = output->GetScale();
316 ApplyBufferScale();
317 }
318 }
319
320 // Just remember initial width/height for context creation in OnConfigure
321 // This is used for sizing the EGLSurface
322 m_shellSurfaceInitializing = true;
323 m_shellSurface->Initialize();
324 m_shellSurfaceInitializing = false;
325
326 // Apply window decorations if necessary
327 m_windowDecorator->SetState(m_configuredSize, m_scale, m_shellSurfaceState);
328
329 // Set initial opaque region and window geometry
330 ApplyOpaqueRegion();
331 ApplyWindowGeometry();
332
333 // Update resolution with real size as it could have changed due to configure()
334 UpdateDesktopResolution(res, res.strOutput, m_bufferSize.Width(), m_bufferSize.Height(), res.fRefreshRate, 0);
335 res.bFullScreen = fullScreen;
336
337 // Now start processing events
338 //
339 // There are two stages to the event handling:
340 // * Initialization (which ends here): Everything runs synchronously and init
341 // code that needs events processed must call roundtrip().
342 // This is done for simplicity because it is a lot easier than to make
343 // everything event-based and thread-safe everywhere in the startup code,
344 // which is also not really necessary.
345 // * Runtime (which starts here): Every object creation from now on
346 // needs to take great care to be thread-safe:
347 // Since the event pump is always running now, there is a tiny window between
348 // creating an object and attaching the C++ event handlers during which
349 // events can get queued and dispatched for the object but the handlers have
350 // not been set yet. Consequently, the events would get lost.
351 // However, this does not apply to objects that are created in response to
352 // compositor events. Since the callbacks are called from the event processing
353 // thread and ran strictly sequentially, no other events are dispatched during
354 // the runtime of a callback. Luckily this applies to global binding like
355 // wl_output and wl_seat and thus to most if not all runtime object creation
356 // cases we have to support.
357 // There is another problem when Wayland objects are destructed from the main
358 // thread: An event handler could be running in parallel, resulting in certain
359 // doom. So objects should only be deleted in response to compositor events, too.
360 // They might be hiding behind class member variables, so be wary.
361 // Note that this does not apply to global teardown since the event pump is
362 // stopped then.
363 CWinEventsWayland::SetDisplay(&m_connection->GetDisplay());
364
365 return true;
366 }
367
368 IShellSurface* CWinSystemWayland::CreateShellSurface(const std::string& name)
369 {
370 IShellSurface* shell = CShellSurfaceXdgShell::TryCreate(*this, *m_connection, m_surface, name,
371 std::string(CCompileInfo::GetAppName()));
372 if (!shell)
373 {
374 shell = CShellSurfaceXdgShellUnstableV6::TryCreate(*this, *m_connection, m_surface, name,
375 std::string(CCompileInfo::GetAppName()));
376 }
377 if (!shell)
378 {
379 CLog::LogF(LOGWARNING, "Compositor does not support xdg_shell protocol (stable or unstable v6) "
380 "- falling back to wl_shell, not all features might work");
381 shell = new CShellSurfaceWlShell(*this, *m_connection, m_surface, name,
382 std::string(CCompileInfo::GetAppName()));
383 }
384
385 return shell;
386 }
387
388 bool CWinSystemWayland::DestroyWindow()
389 {
390 // Make sure no more events get processed when we kill the instances
391 CWinEventsWayland::SetDisplay(nullptr);
392
393 m_shellSurface.reset();
394 // waylandpp automatically calls wl_surface_destroy when the last reference is removed
395 m_surface = wayland::surface_t();
396 m_windowDecorator.reset();
397 m_seats.clear();
398 m_lastSetOutput.proxy_release();
399 m_surfaceOutputs.clear();
400 m_surfaceSubmissions.clear();
401 m_seatRegistry.reset();
402
403 return true;
404 }
405
406 bool CWinSystemWayland::CanDoWindowed()
407 {
408 return true;
409 }
410
411 std::vector<std::string> CWinSystemWayland::GetConnectedOutputs()
412 {
413 std::unique_lock<CCriticalSection> lock(m_outputsMutex);
414 std::vector<std::string> outputs;
415 std::transform(m_outputs.cbegin(), m_outputs.cend(), std::back_inserter(outputs),
416 [this](decltype(m_outputs)::value_type const& pair)
417 { return UserFriendlyOutputName(pair.second); });
418
419 return outputs;
420 }
421
422 bool CWinSystemWayland::UseLimitedColor()
423 {
424 return CServiceBroker::GetSettingsComponent()->GetSettings()->GetBool(CSettings::SETTING_VIDEOSCREEN_LIMITEDRANGE);
425 }
426
427 void CWinSystemWayland::UpdateResolutions()
428 {
429 CWinSystemBase::UpdateResolutions();
430
431 CDisplaySettings::GetInstance().ClearCustomResolutions();
432
433 // Mimic X11:
434 // Only show resolutions for the currently selected output
435 std::string userOutput = CServiceBroker::GetSettingsComponent()->GetSettings()->GetString(CSettings::SETTING_VIDEOSCREEN_MONITOR);
436
437 std::unique_lock<CCriticalSection> lock(m_outputsMutex);
438
439 if (m_outputs.empty())
440 {
441 // *Usually* this should not happen - just give up
442 return;
443 }
444
445 auto output = FindOutputByUserFriendlyName(userOutput);
446 if (!output && m_lastSetOutput)
447 {
448 // Fallback to current output
449 output = FindOutputByWaylandOutput(m_lastSetOutput);
450 }
451 if (!output)
452 {
453 // Well just use the first one
454 output = m_outputs.begin()->second;
455 }
456
457 std::string outputName = UserFriendlyOutputName(output);
458
459 auto const& modes = output->GetModes();
460 auto const& currentMode = output->GetCurrentMode();
461 auto physicalSize = output->GetPhysicalSize();
462 CLog::LogF(LOGINFO,
463 "User wanted output \"{}\", we now have \"{}\" size {}x{} mm with {} mode(s):",
464 userOutput, outputName, physicalSize.Width(), physicalSize.Height(), modes.size());
465
466 for (auto const& mode : modes)
467 {
468 bool isCurrent = (mode == currentMode);
469 float pixelRatio = output->GetPixelRatioForMode(mode);
470 CLog::LogF(LOGINFO, "- {}x{} @{:.3f} Hz pixel ratio {:.3f}{}", mode.size.Width(),
471 mode.size.Height(), mode.refreshMilliHz / 1000.0f, pixelRatio,
472 isCurrent ? " current" : "");
473
474 RESOLUTION_INFO res;
475 UpdateDesktopResolution(res, outputName, mode.size.Width(), mode.size.Height(), mode.GetRefreshInHz(), 0);
476 res.fPixelRatio = pixelRatio;
477
478 if (isCurrent)
479 {
480 CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP) = res;
481 }
482 else
483 {
484 CDisplaySettings::GetInstance().AddResolutionInfo(res);
485 }
486 }
487
488 CDisplaySettings::GetInstance().ApplyCalibrations();
489 }
490
491 std::shared_ptr<COutput> CWinSystemWayland::FindOutputByUserFriendlyName(const std::string& name)
492 {
493 std::unique_lock<CCriticalSection> lock(m_outputsMutex);
494 auto outputIt = std::find_if(m_outputs.begin(), m_outputs.end(),
495 [this, &name](decltype(m_outputs)::value_type const& entry)
496 {
497 return (name == UserFriendlyOutputName(entry.second));
498 });
499
500 return (outputIt == m_outputs.end() ? nullptr : outputIt->second);
501 }
502
503 std::shared_ptr<COutput> CWinSystemWayland::FindOutputByWaylandOutput(wayland::output_t const& output)
504 {
505 std::unique_lock<CCriticalSection> lock(m_outputsMutex);
506 auto outputIt = std::find_if(m_outputs.begin(), m_outputs.end(),
507 [&output](decltype(m_outputs)::value_type const& entry)
508 {
509 return (output == entry.second->GetWaylandOutput());
510 });
511
512 return (outputIt == m_outputs.end() ? nullptr : outputIt->second);
513 }
514
515 /**
516 * Change resolution and window state on Kodi request
517 *
518 * This function is used for updating resolution when Kodi initiates a resolution
519 * change, such as when changing between full screen and windowed mode or when
520 * selecting a different monitor or resolution in the settings.
521 *
522 * Size updates originating from compositor events (such as configure or buffer
523 * scale changes) should not use this function, but \ref SetResolutionInternal
524 * instead.
525 *
526 * \param fullScreen whether to go full screen or windowed
527 * \param res resolution to set
528 * \return whether the requested resolution was actually set - is false e.g.
529 * when already in full screen mode since the application cannot
530 * set the size then
531 */
532 bool CWinSystemWayland::SetResolutionExternal(bool fullScreen, RESOLUTION_INFO const& res)
533 {
534 // In fullscreen modes, we never change the surface size on Kodi's request,
535 // but only when the compositor tells us to. At least xdg_shell specifies
536 // that with state fullscreen the dimensions given in configure() must
537 // always be observed.
538 // This does mean that the compositor has no way of knowing which resolution
539 // we would (in theory) want. Since no compositor implements dynamic resolution
540 // switching at the moment, this is not a problem. If it is some day implemented
541 // in compositors, this code must be changed to match the behavior that is
542 // expected then anyway.
543
544 // We can honor the Kodi-requested size only if we are not bound by configure rules,
545 // which applies for maximized and fullscreen states.
546 // Also, setting an unconfigured size when just going fullscreen makes no sense.
547 // Give precedence to the size we have still pending, if any.
548 bool mustHonorSize{m_waitingForApply || m_shellSurfaceState.test(IShellSurface::STATE_MAXIMIZED) || m_shellSurfaceState.test(IShellSurface::STATE_FULLSCREEN) || fullScreen};
549
550 CLog::LogF(LOGINFO, "Kodi asked to switch mode to {}x{} @{:.3f} Hz on output \"{}\" {}",
551 res.iWidth, res.iHeight, res.fRefreshRate, res.strOutput,
552 fullScreen ? "full screen" : "windowed");
553
554 if (fullScreen)
555 {
556 // Try to match output
557 auto output = FindOutputByUserFriendlyName(res.strOutput);
558 auto wlOutput = output ? output->GetWaylandOutput() : wayland::output_t{};
559 if (!m_shellSurfaceState.test(IShellSurface::STATE_FULLSCREEN) || (m_lastSetOutput != wlOutput))
560 {
561 // Remember the output we set last so we don't set it again until we
562 // either go windowed or were on a different output
563 m_lastSetOutput = wlOutput;
564
565 if (output)
566 {
567 CLog::LogF(LOGDEBUG, "Resolved output \"{}\" to bound Wayland global {}", res.strOutput,
568 output->GetGlobalName());
569 }
570 else
571 {
572 CLog::LogF(LOGINFO,
573 "Could not match output \"{}\" to a currently available Wayland output, falling "
574 "back to default output",
575 res.strOutput);
576 }
577
578 CLog::LogF(LOGDEBUG, "Setting full-screen with refresh rate {:.3f}", res.fRefreshRate);
579 m_shellSurface->SetFullScreen(wlOutput, res.fRefreshRate);
580 }
581 else
582 {
583 CLog::LogF(LOGDEBUG, "Not setting full screen: already full screen on requested output");
584 }
585 }
586 else
587 {
588 if (m_shellSurfaceState.test(IShellSurface::STATE_FULLSCREEN))
589 {
590 CLog::LogF(LOGDEBUG, "Setting windowed");
591 m_shellSurface->SetWindowed();
592 }
593 else
594 {
595 CLog::LogF(LOGDEBUG, "Not setting windowed: already windowed");
596 }
597 }
598
599 // Set Kodi-provided size only if we are free to choose any size, otherwise
600 // wait for the compositor configure
601 if (!mustHonorSize)
602 {
603 CLog::LogF(LOGDEBUG, "Directly setting windowed size {}x{} on Kodi request", res.iWidth,
604 res.iHeight);
605 // Kodi is directly setting window size, apply
606 auto updateResult = UpdateSizeVariables({res.iWidth, res.iHeight}, m_scale, m_shellSurfaceState, false);
607 ApplySizeUpdate(updateResult);
608 }
609
610 bool wasInitialSetFullScreen{m_isInitialSetFullScreen};
611 m_isInitialSetFullScreen = false;
612
613 // Need to return true
614 // * when this SetFullScreen() call was free to change the context size (and possibly did so)
615 // * on first SetFullScreen so GraphicsContext gets resolution
616 // Otherwise, Kodi must keep the old resolution.
617 return !mustHonorSize || wasInitialSetFullScreen;
618 }
619
620 bool CWinSystemWayland::ResizeWindow(int, int, int, int)
621 {
622 // CGraphicContext is "smart" and calls ResizeWindow or SetFullScreen depending
623 // on some state like whether we were already fullscreen. But actually the processing
624 // here is always identical, so we are using a common function to handle both.
625 const auto& res = CDisplaySettings::GetInstance().GetResolutionInfo(RES_WINDOW);
626 // The newWidth/newHeight parameters are taken from RES_WINDOW anyway, so we can just
627 // ignore them
628 return SetResolutionExternal(false, res);
629 }
630
631 bool CWinSystemWayland::SetFullScreen(bool fullScreen, RESOLUTION_INFO& res, bool)
632 {
633 return SetResolutionExternal(fullScreen, res);
634 }
635
636 void CWinSystemWayland::ApplySizeUpdate(SizeUpdateInformation update)
637 {
638 if (update.bufferScaleChanged)
639 {
640 // Buffer scale must also match egl size configuration
641 ApplyBufferScale();
642 }
643 if (update.surfaceSizeChanged)
644 {
645 // Update opaque region here so size always matches the configured egl surface
646 ApplyOpaqueRegion();
647 }
648 if (update.configuredSizeChanged)
649 {
650 // Update window decoration state
651 m_windowDecorator->SetState(m_configuredSize, m_scale, m_shellSurfaceState);
652 ApplyWindowGeometry();
653 }
654 // Set always, because of initialization order GL context has to keep track of
655 // whether the size changed. If we skip based on update.bufferSizeChanged here,
656 // GL context will never get its initial size set.
657 SetContextSize(m_bufferSize);
658 }
659
660 void CWinSystemWayland::ApplyOpaqueRegion()
661 {
662 // Mark everything opaque so the compositor can render it faster
663 CLog::LogF(LOGDEBUG, "Setting opaque region size {}x{}", m_surfaceSize.Width(),
664 m_surfaceSize.Height());
665 wayland::region_t opaqueRegion{m_compositor.create_region()};
666 opaqueRegion.add(0, 0, m_surfaceSize.Width(), m_surfaceSize.Height());
667 m_surface.set_opaque_region(opaqueRegion);
668 }
669
670 void CWinSystemWayland::ApplyWindowGeometry()
671 {
672 m_shellSurface->SetWindowGeometry(m_windowDecorator->GetWindowGeometry());
673 }
674
675 void CWinSystemWayland::ProcessMessages()
676 {
677 if (m_waitingForApply)
678 {
679 // Do not put multiple size updates into the pipeline, this would only make
680 // it more complicated without any real benefit. Wait until the size was reconfigured,
681 // then process events again.
682 return;
683 }
684
685 Actor::Message* message{};
686 MessageHandle lastConfigureMessage;
687 int skippedConfigures{-1};
688 int newScale{m_scale};
689
690 while (m_protocol.ReceiveOutMessage(&message))
691 {
692 MessageHandle guard{message};
693 switch (message->signal)
694 {
695 case WinSystemWaylandProtocol::CONFIGURE:
696 // Do not directly process configures, get the last one queued:
697 // While resizing, the compositor will usually send a configure event
698 // each time the mouse moves without any throttling (i.e. multiple times
699 // per rendered frame).
700 // Going through all those and applying them would waste a lot of time when
701 // we already know that the size is not final and will change again anyway.
702 skippedConfigures++;
703 lastConfigureMessage = std::move(guard);
704 break;
705 case WinSystemWaylandProtocol::OUTPUT_HOTPLUG:
706 {
707 CLog::LogF(LOGDEBUG, "Output hotplug, re-reading resolutions");
708 UpdateResolutions();
709 std::unique_lock<CCriticalSection> lock(m_outputsMutex);
710 auto const& desktopRes = CDisplaySettings::GetInstance().GetResolutionInfo(RES_DESKTOP);
711 auto output = FindOutputByUserFriendlyName(desktopRes.strOutput);
712 auto const& wlOutput = output->GetWaylandOutput();
713 // Maybe the output that was added was the one we should be on?
714 if (m_bFullScreen && m_lastSetOutput != wlOutput)
715 {
716 CLog::LogF(LOGDEBUG, "Output hotplug resulted in monitor set in settings appearing, switching");
717 // Switch to this output
718 m_lastSetOutput = wlOutput;
719 m_shellSurface->SetFullScreen(wlOutput, desktopRes.fRefreshRate);
720 // SetOutput will result in a configure that updates the actual context size
721 }
722 }
723 break;
724 case WinSystemWaylandProtocol::BUFFER_SCALE:
725 // Never update buffer scale if not possible to set it
726 if (m_surface.can_set_buffer_scale())
727 {
728 newScale = (reinterpret_cast<WinSystemWaylandProtocol::MsgBufferScale*> (message->data))->scale;
729 }
730 break;
731 }
732 }
733
734 if (lastConfigureMessage)
735 {
736 if (skippedConfigures > 0)
737 {
738 CLog::LogF(LOGDEBUG, "Skipped {} configures", skippedConfigures);
739 }
740 // Wayland will tell us here the size of the surface that was actually created,
741 // which might be different from what we expected e.g. when fullscreening
742 // on an output we chose - the compositor might have decided to use a different
743 // output for example
744 // It is very important that the EGL native module and the rendering system use the
745 // Wayland-announced size for rendering or corrupted graphics output will result.
746 auto configure = reinterpret_cast<WinSystemWaylandProtocol::MsgConfigure*> (lastConfigureMessage.Get()->data);
747 CLog::LogF(LOGDEBUG, "Configure serial {}: size {}x{} state {}", configure->serial,
748 configure->surfaceSize.Width(), configure->surfaceSize.Height(),
749 IShellSurface::StateToString(configure->state));
750
751
752 CSizeInt size = configure->surfaceSize;
753 bool sizeIncludesDecoration = true;
754
755 if (size.IsZero())
756 {
757 if (configure->state.test(IShellSurface::STATE_FULLSCREEN))
758 {
759 // Do not change current size - UpdateWithConfiguredSize must be called regardless in case
760 // scale or something else changed
761 size = m_configuredSize;
762 }
763 else
764 {
765 // Compositor has no preference and we're windowed
766 // -> adopt windowed size that Kodi wants
767 auto const& windowed = CDisplaySettings::GetInstance().GetResolutionInfo(RES_WINDOW);
768 // Kodi resolution is buffer size, but SetResolutionInternal expects
769 // surface size, so divide by m_scale
770 size = CSizeInt{windowed.iWidth, windowed.iHeight} / newScale;
771 CLog::LogF(LOGDEBUG, "Adapting Kodi windowed size {}x{}", size.Width(), size.Height());
772 sizeIncludesDecoration = false;
773 }
774 }
775
776 SetResolutionInternal(size, newScale, configure->state, sizeIncludesDecoration, true, configure->serial);
777 }
778 // If we were also configured, scale is already taken care of. But it could
779 // also be a scale change without configure, so apply that.
780 else if (m_scale != newScale)
781 {
782 SetResolutionInternal(m_configuredSize, newScale, m_shellSurfaceState, true, false);
783 }
784 }
785
786 void CWinSystemWayland::ApplyShellSurfaceState(IShellSurface::StateBitset state)
787 {
788 m_windowDecorator->SetState(m_configuredSize, m_scale, state);
789 m_shellSurfaceState = state;
790 }
791
792 void CWinSystemWayland::OnConfigure(std::uint32_t serial, CSizeInt size, IShellSurface::StateBitset state)
793 {
794 if (m_shellSurfaceInitializing)
795 {
796 CLog::LogF(LOGDEBUG, "Initial configure serial {}: size {}x{} state {}", serial, size.Width(),
797 size.Height(), IShellSurface::StateToString(state));
798 m_shellSurfaceState = state;
799 if (!size.IsZero())
800 {
801 UpdateSizeVariables(size, m_scale, m_shellSurfaceState, true);
802 }
803 AckConfigure(serial);
804 }
805 else
806 {
807 WinSystemWaylandProtocol::MsgConfigure msg{serial, size, state};
808 m_protocol.SendOutMessage(WinSystemWaylandProtocol::CONFIGURE, &msg, sizeof(msg));
809 }
810 }
811
812 void CWinSystemWayland::AckConfigure(std::uint32_t serial)
813 {
814 // Send ack if we have a new serial number or this is the first time
815 // this function is called
816 if (serial != m_lastAckedSerial || !m_firstSerialAcked)
817 {
818 CLog::LogF(LOGDEBUG, "Acking serial {}", serial);
819 m_shellSurface->AckConfigure(serial);
820 m_lastAckedSerial = serial;
821 m_firstSerialAcked = true;
822 }
823 }
824
825 /**
826 * Recalculate sizes from given parameters, apply them and update Kodi CDisplaySettings
827 * resolution if necessary
828 *
829 * This function should be called when events internal to the windowing system
830 * such as a compositor configure lead to a size change.
831 *
832 * Call only from main thread.
833 *
834 * \param size configured size, can be zero if compositor does not have a preference
835 * \param scale new buffer scale
836 * \param sizeIncludesDecoration whether size includes the size of the window decorations if present
837 */
838 void CWinSystemWayland::SetResolutionInternal(CSizeInt size, std::int32_t scale, IShellSurface::StateBitset state, bool sizeIncludesDecoration, bool mustAck, std::uint32_t configureSerial)
839 {
840 // This should never be called while a size set is pending
841 assert(!m_waitingForApply);
842
843 bool fullScreen{state.test(IShellSurface::STATE_FULLSCREEN)};
844 auto sizes = CalculateSizes(size, scale, state, sizeIncludesDecoration);
845
846 CLog::LogF(LOGDEBUG, "Set size for serial {}: {}x{} {} decoration at scale {} state {}",
847 configureSerial, size.Width(), size.Height(),
848 sizeIncludesDecoration ? "including" : "excluding", scale,
849 IShellSurface::StateToString(state));
850
851 // Get actual frame rate from monitor, take highest frame rate if multiple
852 float refreshRate{m_fRefreshRate};
853 {
854 std::unique_lock<CCriticalSection> lock(m_surfaceOutputsMutex);
855 auto maxRefreshIt = std::max_element(m_surfaceOutputs.cbegin(), m_surfaceOutputs.cend(), OutputCurrentRefreshRateComparer());
856 if (maxRefreshIt != m_surfaceOutputs.cend())
857 {
858 refreshRate = (*maxRefreshIt)->GetCurrentMode().GetRefreshInHz();
859 CLog::LogF(LOGDEBUG, "Resolved actual (maximum) refresh rate to {:.3f} Hz on output \"{}\"",
860 refreshRate, UserFriendlyOutputName(*maxRefreshIt));
861 }
862 }
863
864 m_next.mustBeAcked = mustAck;
865 m_next.configureSerial = configureSerial;
866 m_next.configuredSize = sizes.configuredSize;
867 m_next.scale = scale;
868 m_next.shellSurfaceState = state;
869
870 // Check if any parameters of the Kodi resolution configuration changed
871 if (refreshRate != m_fRefreshRate || sizes.bufferSize != m_bufferSize || m_bFullScreen != fullScreen)
872 {
873 if (!fullScreen)
874 {
875 if (m_bFullScreen)
876 {
877 XBMC_Event msg{};
878 msg.type = XBMC_MODECHANGE;
879 msg.mode.res = RES_WINDOW;
880 SetWindowResolution(sizes.bufferSize.Width(), sizes.bufferSize.Height());
881 // FIXME
882 dynamic_cast<CWinEventsWayland&>(*m_winEvents).MessagePush(&msg);
883 m_waitingForApply = true;
884 CLog::LogF(LOGDEBUG, "Queued change to windowed mode size {}x{}", sizes.bufferSize.Width(),
885 sizes.bufferSize.Height());
886 }
887 else
888 {
889 XBMC_Event msg{};
890 msg.type = XBMC_VIDEORESIZE;
891 msg.resize = {sizes.surfaceSize.Width(), sizes.surfaceSize.Height(),
892 static_cast<double>(scale)};
893 // FIXME
894 dynamic_cast<CWinEventsWayland&>(*m_winEvents).MessagePush(&msg);
895 m_waitingForApply = true;
896 CLog::LogF(LOGDEBUG, "Queued change to windowed buffer size {}x{}",
897 sizes.bufferSize.Width(), sizes.bufferSize.Height());
898 }
899 }
900 else
901 {
902 // Find matching Kodi resolution member
903 RESOLUTION res{FindMatchingCustomResolution(sizes.bufferSize, refreshRate)};
904 if (res == RES_INVALID)
905 {
906 // Add new resolution if none found
907 RESOLUTION_INFO newResInfo;
908 // we just assume the compositor put us on the right output
909 UpdateDesktopResolution(newResInfo, CDisplaySettings::GetInstance().GetCurrentResolutionInfo().strOutput, sizes.bufferSize.Width(), sizes.bufferSize.Height(), refreshRate, 0);
910 CDisplaySettings::GetInstance().AddResolutionInfo(newResInfo);
911 CDisplaySettings::GetInstance().ApplyCalibrations();
912 res = static_cast<RESOLUTION> (CDisplaySettings::GetInstance().ResolutionInfoSize() - 1);
913 }
914
915 XBMC_Event msg{};
916 msg.type = XBMC_MODECHANGE;
917 msg.mode.res = res;
918 // FIXME
919 dynamic_cast<CWinEventsWayland&>(*m_winEvents).MessagePush(&msg);
920 m_waitingForApply = true;
921 CLog::LogF(LOGDEBUG, "Queued change to resolution {} surface size {}x{} scale {} state {}",
922 res, sizes.surfaceSize.Width(), sizes.surfaceSize.Height(), scale,
923 IShellSurface::StateToString(state));
924 }
925 }
926 else
927 {
928 // Apply directly, Kodi resolution does not change
929 ApplyNextState();
930 }
931 }
932
933 void CWinSystemWayland::FinishModeChange(RESOLUTION res)
934 {
935 const auto& resInfo = CDisplaySettings::GetInstance().GetResolutionInfo(res);
936
937 ApplyNextState();
938
939 m_fRefreshRate = resInfo.fRefreshRate;
940 m_bFullScreen = resInfo.bFullScreen;
941 m_waitingForApply = false;
942 }
943
944 void CWinSystemWayland::FinishWindowResize(int, int)
945 {
946 ApplyNextState();
947 m_waitingForApply = false;
948 }
949
950 void CWinSystemWayland::ApplyNextState()
951 {
952 CLog::LogF(LOGDEBUG, "Applying next state: serial {} configured size {}x{} scale {} state {}",
953 m_next.configureSerial, m_next.configuredSize.Width(), m_next.configuredSize.Height(),
954 m_next.scale, IShellSurface::StateToString(m_next.shellSurfaceState));
955
956 ApplyShellSurfaceState(m_next.shellSurfaceState);
957 auto updateResult = UpdateSizeVariables(m_next.configuredSize, m_next.scale, m_next.shellSurfaceState, true);
958 ApplySizeUpdate(updateResult);
959
960 if (m_next.mustBeAcked)
961 {
962 AckConfigure(m_next.configureSerial);
963 }
964 }
965
966 CWinSystemWayland::Sizes CWinSystemWayland::CalculateSizes(CSizeInt size, int scale, IShellSurface::StateBitset state, bool sizeIncludesDecoration)
967 {
968 Sizes result;
969
970 // Clamp to a sensible range
971 constexpr int MIN_WIDTH{300};
972 constexpr int MIN_HEIGHT{200};
973 if (size.Width() < MIN_WIDTH)
974 {
975 CLog::LogF(LOGWARNING, "Width {} is very small, clamping to {}", size.Width(), MIN_WIDTH);
976 size.SetWidth(MIN_WIDTH);
977 }
978 if (size.Height() < MIN_HEIGHT)
979 {
980 CLog::LogF(LOGWARNING, "Height {} is very small, clamping to {}", size.Height(), MIN_HEIGHT);
981 size.SetHeight(MIN_HEIGHT);
982 }
983
984 // Depending on whether the size has decorations included (i.e. comes from the
985 // compositor or from Kodi), we need to calculate differently
986 if (sizeIncludesDecoration)
987 {
988 result.configuredSize = size;
989 result.surfaceSize = m_windowDecorator->CalculateMainSurfaceSize(size, state);
990 }
991 else
992 {
993 result.surfaceSize = size;
994 result.configuredSize = m_windowDecorator->CalculateFullSurfaceSize(size, state);
995 }
996
997 result.bufferSize = result.surfaceSize * scale;
998
999 return result;
1000 }
1001
1002
1003 /**
1004 * Calculate internal resolution from surface size and set variables
1005 *
1006 * \param next surface size
1007 * \param scale new buffer scale
1008 * \param state window state to determine whether decorations are enabled at all
1009 * \param sizeIncludesDecoration if true, given size includes potential window decorations
1010 * \return whether main buffer (not surface) size changed
1011 */
1012 CWinSystemWayland::SizeUpdateInformation CWinSystemWayland::UpdateSizeVariables(CSizeInt size, int scale, IShellSurface::StateBitset state, bool sizeIncludesDecoration)
1013 {
1014 CLog::LogF(LOGDEBUG, "Set size {}x{} scale {} {} decorations with state {}", size.Width(),
1015 size.Height(), scale, sizeIncludesDecoration ? "including" : "excluding",
1016 IShellSurface::StateToString(state));
1017
1018 auto oldSurfaceSize = m_surfaceSize;
1019 auto oldBufferSize = m_bufferSize;
1020 auto oldConfiguredSize = m_configuredSize;
1021 auto oldBufferScale = m_scale;
1022
1023 m_scale = scale;
1024 auto sizes = CalculateSizes(size, scale, state, sizeIncludesDecoration);
1025 m_surfaceSize = sizes.surfaceSize;
1026 m_bufferSize = sizes.bufferSize;
1027 m_configuredSize = sizes.configuredSize;
1028
1029 SizeUpdateInformation changes{m_surfaceSize != oldSurfaceSize, m_bufferSize != oldBufferSize, m_configuredSize != oldConfiguredSize, m_scale != oldBufferScale};
1030
1031 if (changes.surfaceSizeChanged)
1032 {
1033 CLog::LogF(LOGINFO, "Surface size changed: {}x{} -> {}x{}", oldSurfaceSize.Width(),
1034 oldSurfaceSize.Height(), m_surfaceSize.Width(), m_surfaceSize.Height());
1035 }
1036 if (changes.bufferSizeChanged)
1037 {
1038 CLog::LogF(LOGINFO, "Buffer size changed: {}x{} -> {}x{}", oldBufferSize.Width(),
1039 oldBufferSize.Height(), m_bufferSize.Width(), m_bufferSize.Height());
1040 }
1041 if (changes.configuredSizeChanged)
1042 {
1043 CLog::LogF(LOGINFO, "Configured size changed: {}x{} -> {}x{}", oldConfiguredSize.Width(),
1044 oldConfiguredSize.Height(), m_configuredSize.Width(), m_configuredSize.Height());
1045 }
1046 if (changes.bufferScaleChanged)
1047 {
1048 CLog::LogF(LOGINFO, "Buffer scale changed: {} -> {}", oldBufferScale, m_scale);
1049 }
1050
1051 return changes;
1052 }
1053
1054 std::string CWinSystemWayland::UserFriendlyOutputName(std::shared_ptr<COutput> const& output)
1055 {
1056 std::vector<std::string> parts;
1057 if (!output->GetMake().empty())
1058 {
1059 parts.emplace_back(output->GetMake());
1060 }
1061 if (!output->GetModel().empty())
1062 {
1063 parts.emplace_back(output->GetModel());
1064 }
1065 if (parts.empty())
1066 {
1067 // Fallback to "unknown" if no name received from compositor
1068 parts.emplace_back(g_localizeStrings.Get(13205));
1069 }
1070
1071 // Add position
1072 auto pos = output->GetPosition();
1073 if (pos.x != 0 || pos.y != 0)
1074 {
1075 parts.emplace_back(StringUtils::Format("@{}x{}", pos.x, pos.y));
1076 }
1077
1078 return StringUtils::Join(parts, " ");
1079 }
1080
1081 bool CWinSystemWayland::Minimize()
1082 {
1083 m_shellSurface->SetMinimized();
1084 return true;
1085 }
1086
1087 bool CWinSystemWayland::HasCursor()
1088 {
1089 std::unique_lock<CCriticalSection> lock(m_seatsMutex);
1090 return std::any_of(m_seats.cbegin(), m_seats.cend(),
1091 [](decltype(m_seats)::value_type const& entry)
1092 {
1093 return entry.second.HasPointerCapability();
1094 });
1095 }
1096
1097 void CWinSystemWayland::ShowOSMouse(bool show)
1098 {
1099 m_osCursorVisible = show;
1100 }
1101
1102 void CWinSystemWayland::LoadDefaultCursor()
1103 {
1104 if (!m_cursorSurface)
1105 {
1106 // Load default cursor theme and default cursor
1107 // Size of 24px is what most themes seem to have
1108 m_cursorTheme = wayland::cursor_theme_t("", 24, m_shm);
1109 wayland::cursor_t cursor;
1110 try
1111 {
1112 cursor = CCursorUtil::LoadFromTheme(m_cursorTheme, "default");
1113 }
1114 catch (std::exception const& e)
1115 {
1116 CLog::Log(LOGWARNING, "Could not load default cursor from theme, continuing without OS cursor");
1117 }
1118 // Just use the first image, do not handle animation
1119 m_cursorImage = cursor.image(0);
1120 m_cursorBuffer = m_cursorImage.get_buffer();
1121 m_cursorSurface = m_compositor.create_surface();
1122 }
1123 // Attach buffer to a surface - it seems that the compositor may change
1124 // the cursor surface when the pointer leaves our surface, so we reattach the
1125 // buffer each time
1126 m_cursorSurface.attach(m_cursorBuffer, 0, 0);
1127 m_cursorSurface.damage(0, 0, m_cursorImage.width(), m_cursorImage.height());
1128 m_cursorSurface.commit();
1129 }
1130
1131 void CWinSystemWayland::Register(IDispResource* resource)
1132 {
1133 std::unique_lock<CCriticalSection> lock(m_dispResourcesMutex);
1134 m_dispResources.emplace(resource);
1135 }
1136
1137 void CWinSystemWayland::Unregister(IDispResource* resource)
1138 {
1139 std::unique_lock<CCriticalSection> lock(m_dispResourcesMutex);
1140 m_dispResources.erase(resource);
1141 }
1142
1143 void CWinSystemWayland::OnSeatAdded(std::uint32_t name, wayland::proxy_t&& proxy)
1144 {
1145 std::unique_lock<CCriticalSection> lock(m_seatsMutex);
1146
1147 wayland::seat_t seat(proxy);
1148 auto newSeatEmplace = m_seats.emplace(std::piecewise_construct,
1149 std::forward_as_tuple(name),
1150 std::forward_as_tuple(name, seat, *m_connection));
1151
1152 auto& seatInst = newSeatEmplace.first->second;
1153 m_seatInputProcessing->AddSeat(&seatInst);
1154 m_windowDecorator->AddSeat(&seatInst);
1155 }
1156
1157 void CWinSystemWayland::OnSeatRemoved(std::uint32_t name)
1158 {
1159 std::unique_lock<CCriticalSection> lock(m_seatsMutex);
1160
1161 auto seatI = m_seats.find(name);
1162 if (seatI != m_seats.end())
1163 {
1164 m_seatInputProcessing->RemoveSeat(&seatI->second);
1165 m_windowDecorator->RemoveSeat(&seatI->second);
1166 m_seats.erase(name);
1167 }
1168 }
1169
1170 void CWinSystemWayland::OnOutputAdded(std::uint32_t name, wayland::proxy_t&& proxy)
1171 {
1172 wayland::output_t output(proxy);
1173 // This is not accessed from multiple threads
1174 m_outputsInPreparation.emplace(name, std::make_shared<COutput>(name, output, std::bind(&CWinSystemWayland::OnOutputDone, this, name)));
1175 }
1176
1177 void CWinSystemWayland::OnOutputDone(std::uint32_t name)
1178 {
1179 auto it = m_outputsInPreparation.find(name);
1180 if (it != m_outputsInPreparation.end())
1181 {
1182 // This output was added for the first time - done is also sent when
1183 // output parameters change later
1184
1185 {
1186 std::unique_lock<CCriticalSection> lock(m_outputsMutex);
1187 // Move from m_outputsInPreparation to m_outputs
1188 m_outputs.emplace(std::move(*it));
1189 m_outputsInPreparation.erase(it);
1190 }
1191
1192 m_protocol.SendOutMessage(WinSystemWaylandProtocol::OUTPUT_HOTPLUG);
1193 }
1194
1195 UpdateBufferScale();
1196 }
1197
1198 void CWinSystemWayland::OnOutputRemoved(std::uint32_t name)
1199 {
1200 m_outputsInPreparation.erase(name);
1201
1202 std::unique_lock<CCriticalSection> lock(m_outputsMutex);
1203 if (m_outputs.erase(name) != 0)
1204 {
1205 // Theoretically, the compositor should automatically put us on another
1206 // (visible and connected) output if the output we were on is lost,
1207 // so there is nothing in particular to do here
1208 }
1209 }
1210
1211 void CWinSystemWayland::SendFocusChange(bool focus)
1212 {
1213 g_application.m_AppFocused = focus;
1214 std::unique_lock<CCriticalSection> lock(m_dispResourcesMutex);
1215 for (auto dispResource : m_dispResources)
1216 {
1217 dispResource->OnAppFocusChange(focus);
1218 }
1219 }
1220
1221 void CWinSystemWayland::OnEnter(InputType type)
1222 {
1223 // Couple to keyboard focus
1224 if (type == InputType::KEYBOARD)
1225 {
1226 SendFocusChange(true);
1227 }
1228 if (type == InputType::POINTER)
1229 {
1230 CServiceBroker::GetInputManager().SetMouseActive(true);
1231 }
1232 }
1233
1234 void CWinSystemWayland::OnLeave(InputType type)
1235 {
1236 // Couple to keyboard focus
1237 if (type == InputType::KEYBOARD)
1238 {
1239 SendFocusChange(false);
1240 }
1241 if (type == InputType::POINTER)
1242 {
1243 CServiceBroker::GetInputManager().SetMouseActive(false);
1244 }
1245 }
1246
1247 void CWinSystemWayland::OnEvent(InputType type, XBMC_Event& event)
1248 {
1249 // FIXME
1250 dynamic_cast<CWinEventsWayland&>(*m_winEvents).MessagePush(&event);
1251 }
1252
1253 void CWinSystemWayland::OnSetCursor(std::uint32_t seatGlobalName, std::uint32_t serial)
1254 {
1255 auto seatI = m_seats.find(seatGlobalName);
1256 if (seatI == m_seats.end())
1257 {
1258 return;
1259 }
1260
1261 if (m_osCursorVisible)
1262 {
1263 LoadDefaultCursor();
1264 if (m_cursorSurface) // Cursor loading could have failed
1265 {
1266 seatI->second.SetCursor(serial, m_cursorSurface, m_cursorImage.hotspot_x(), m_cursorImage.hotspot_y());
1267 }
1268 }
1269 else
1270 {
1271 seatI->second.SetCursor(serial, wayland::surface_t{}, 0, 0);
1272 }
1273 }
1274
1275 void CWinSystemWayland::UpdateBufferScale()
1276 {
1277 // Adjust our surface size to the output with the biggest scale in order
1278 // to get the best quality
1279 auto const maxBufferScaleIt = std::max_element(m_surfaceOutputs.cbegin(), m_surfaceOutputs.cend(), OutputScaleComparer());
1280 if (maxBufferScaleIt != m_surfaceOutputs.cend())
1281 {
1282 WinSystemWaylandProtocol::MsgBufferScale msg{(*maxBufferScaleIt)->GetScale()};
1283 m_protocol.SendOutMessage(WinSystemWaylandProtocol::BUFFER_SCALE, &msg, sizeof(msg));
1284 }
1285 }
1286
1287 void CWinSystemWayland::ApplyBufferScale()
1288 {
1289 CLog::LogF(LOGINFO, "Setting Wayland buffer scale to {}", m_scale);
1290 m_surface.set_buffer_scale(m_scale);
1291 m_windowDecorator->SetState(m_configuredSize, m_scale, m_shellSurfaceState);
1292 m_seatInputProcessing->SetCoordinateScale(m_scale);
1293 }
1294
1295 void CWinSystemWayland::UpdateTouchDpi()
1296 {
1297 // If we have multiple outputs with wildly different DPI, this is really just
1298 // guesswork to get a halfway reasonable value. min/max would probably also be OK.
1299 float dpiSum = std::accumulate(m_surfaceOutputs.cbegin(), m_surfaceOutputs.cend(), 0.0f,
1300 [](float acc, std::shared_ptr<COutput> const& output)
1301 {
1302 return acc + output->GetCurrentDpi();
1303 });
1304 float dpi = dpiSum / m_surfaceOutputs.size();
1305 CLog::LogF(LOGDEBUG, "Computed average dpi of {:.3f} for touch handler", dpi);
1306 CGenericTouchInputHandler::GetInstance().SetScreenDPI(dpi);
1307 }
1308
1309 CWinSystemWayland::SurfaceSubmission::SurfaceSubmission(timespec const& submissionTime, wayland::presentation_feedback_t const& feedback)
1310 : submissionTime{submissionTime}, feedback{feedback}
1311 {
1312 }
1313
1314 timespec CWinSystemWayland::GetPresentationClockTime()
1315 {
1316 timespec time;
1317 if (clock_gettime(m_presentationClock, &time) != 0)
1318 {
1319 throw std::system_error(errno, std::generic_category(), "Error getting time from Wayland presentation clock with clock_gettime");
1320 }
1321 return time;
1322 }
1323
1324 void CWinSystemWayland::PrepareFramePresentation()
1325 {
1326 // Continuously measure display latency (i.e. time between when the frame was rendered
1327 // and when it becomes visible to the user) to correct AV sync
1328 if (m_presentation)
1329 {
1330 auto tStart = GetPresentationClockTime();
1331 // wp_presentation_feedback creation is coupled to the surface's commit().
1332 // eglSwapBuffers() (which will be called after this) will call commit().
1333 // This creates a new Wayland protocol object in the main thread, but this
1334 // will not result in a race since the corresponding events are never sent
1335 // before commit() on the surface, which only occurs afterwards.
1336 auto feedback = m_presentation.feedback(m_surface);
1337 // Save feedback objects in list so they don't get destroyed upon exit of this function
1338 // Hand iterator to lambdas so they do not hold a (then circular) reference
1339 // to the actual object
1340 decltype(m_surfaceSubmissions)::iterator iter;
1341 {
1342 std::unique_lock<CCriticalSection> lock(m_surfaceSubmissionsMutex);
1343 iter = m_surfaceSubmissions.emplace(m_surfaceSubmissions.end(), tStart, feedback);
1344 }
1345
1346 feedback.on_sync_output() = [this](const wayland::output_t& wloutput) {
1347 m_syncOutputID = wloutput.get_id();
1348 auto output = FindOutputByWaylandOutput(wloutput);
1349 if (output)
1350 {
1351 m_syncOutputRefreshRate = output->GetCurrentMode().GetRefreshInHz();
1352 }
1353 else
1354 {
1355 CLog::Log(LOGWARNING, "Could not find Wayland output that is supposedly the sync output");
1356 }
1357 };
1358 feedback.on_presented() = [this, iter](std::uint32_t tvSecHi, std::uint32_t tvSecLo,
1359 std::uint32_t tvNsec, std::uint32_t refresh,
1360 std::uint32_t seqHi, std::uint32_t seqLo,
1361 const wayland::presentation_feedback_kind& flags) {
1362 timespec tv = { .tv_sec = static_cast<std::time_t> ((static_cast<std::uint64_t>(tvSecHi) << 32) + tvSecLo), .tv_nsec = static_cast<long>(tvNsec) };
1363 std::int64_t latency{KODI::LINUX::TimespecDifference(iter->submissionTime, tv)};
1364 std::uint64_t msc{(static_cast<std::uint64_t>(seqHi) << 32) + seqLo};
1365 m_presentationFeedbackHandlers.Invoke(tv, refresh, m_syncOutputID, m_syncOutputRefreshRate, msc);
1366
1367 iter->latency = latency / 1e9f; // nanoseconds to seconds
1368 float adjust{};
1369 {
1370 std::unique_lock<CCriticalSection> lock(m_surfaceSubmissionsMutex);
1371 if (m_surfaceSubmissions.size() > LATENCY_MOVING_AVERAGE_SIZE)
1372 {
1373 adjust = - m_surfaceSubmissions.front().latency / LATENCY_MOVING_AVERAGE_SIZE;
1374 m_surfaceSubmissions.pop_front();
1375 }
1376 }
1377 m_latencyMovingAverage = m_latencyMovingAverage + iter->latency / LATENCY_MOVING_AVERAGE_SIZE + adjust;
1378
1379 CLog::Log(LOGDEBUG, LOGAVTIMING, "Presentation feedback: {} ns -> moving average {:f} s",
1380 latency, static_cast<double>(m_latencyMovingAverage));
1381 };
1382 feedback.on_discarded() = [this,iter]()
1383 {
1384 CLog::Log(LOGDEBUG, "Presentation: Frame was discarded by compositor");
1385 std::unique_lock<CCriticalSection> lock(m_surfaceSubmissionsMutex);
1386 m_surfaceSubmissions.erase(iter);
1387 };
1388 }
1389
1390 // Now wait for the frame callback that tells us that it is a good time to start drawing
1391 //
1392 // To sum up, we:
1393 // 1. wait until a frame() drawing hint from the compositor arrives,
1394 // 2. request a new frame() hint for the next presentation
1395 // 2. then commit the backbuffer to the surface and immediately
1396 // return, i.e. drawing can start again
1397 // This means that rendering is optimized for maximum time available for
1398 // our repaint and reliable timing rather than latency. With weston, latency
1399 // will usually be on the order of two frames plus a few milliseconds.
1400 // The frame timings become irregular though when nothing is rendered because
1401 // kodi then sleeps for a fixed time without swapping buffers. This makes us
1402 // immediately attach the next buffer because the frame callback has already arrived when
1403 // this function is called and step 1. above is skipped. As we render with full
1404 // FPS during video playback anyway and the timing is otherwise not relevant,
1405 // this should not be a problem.
1406 if (m_frameCallback)
1407 {
1408 // If the window is e.g. minimized, chances are that we will *never* get frame
1409 // callbacks from the compositor for optimization reasons.
1410 // Still, the app should remain functional, which means that we can't
1411 // just block forever here - if the render thread is blocked, Kodi will not
1412 // function normally. It would also be impossible to close the application
1413 // while it is minimized (since the wait needs to be interrupted for that).
1414 // -> Use Wait with timeout here so we can maintain a reasonable frame rate
1415 // even when the window is not visible and we do not get any frame callbacks.
1416 if (m_frameCallbackEvent.Wait(50ms))
1417 {
1418 // Only reset frame callback object a callback was received so a
1419 // new one is not requested continuously
1420 m_frameCallback = {};
1421 m_frameCallbackEvent.Reset();
1422 }
1423 }
1424
1425 if (!m_frameCallback)
1426 {
1427 // Get frame callback event for checking in the next call to this function
1428 m_frameCallback = m_surface.frame();
1429 m_frameCallback.on_done() = [this](std::uint32_t)
1430 {
1431 m_frameCallbackEvent.Set();
1432 };
1433 }
1434 }
1435
1436 void CWinSystemWayland::FinishFramePresentation()
1437 {
1438 ProcessMessages();
1439
1440 m_frameStartTime = std::chrono::steady_clock::now();
1441 }
1442
1443 float CWinSystemWayland::GetFrameLatencyAdjustment()
1444 {
1445 const auto now = std::chrono::steady_clock::now();
1446 const std::chrono::duration<float, std::milli> duration = now - m_frameStartTime;
1447 return duration.count();
1448 }
1449
1450 float CWinSystemWayland::GetDisplayLatency()
1451 {
1452 if (m_presentation)
1453 {
1454 return m_latencyMovingAverage * 1000.0f;
1455 }
1456 else
1457 {
1458 return CWinSystemBase::GetDisplayLatency();
1459 }
1460 }
1461
1462 float CWinSystemWayland::GetSyncOutputRefreshRate()
1463 {
1464 return m_syncOutputRefreshRate;
1465 }
1466
1467 KODI::CSignalRegistration CWinSystemWayland::RegisterOnPresentationFeedback(
1468 const PresentationFeedbackHandler& handler)
1469 {
1470 return m_presentationFeedbackHandlers.Register(handler);
1471 }
1472
1473 std::unique_ptr<CVideoSync> CWinSystemWayland::GetVideoSync(CVideoReferenceClock* clock)
1474 {
1475 if (m_surface && m_presentation)
1476 {
1477 CLog::LogF(LOGINFO, "Using presentation protocol for video sync");
1478 return std::unique_ptr<CVideoSync>(new CVideoSyncWpPresentation(clock, *this));
1479 }
1480 else
1481 {
1482 CLog::LogF(LOGINFO, "No supported method for video sync found");
1483 return nullptr;
1484 }
1485 }
1486
1487 std::unique_ptr<IOSScreenSaver> CWinSystemWayland::GetOSScreenSaverImpl()
1488 {
1489 if (m_surface)
1490 {
1491 std::unique_ptr<IOSScreenSaver> ptr;
1492 ptr.reset(COSScreenSaverIdleInhibitUnstableV1::TryCreate(*m_connection, m_surface));
1493 if (ptr)
1494 {
1495 CLog::LogF(LOGINFO, "Using idle-inhibit-unstable-v1 protocol for screen saver inhibition");
1496 return ptr;
1497 }
1498 }
1499
1500 #if defined(HAS_DBUS)
1501 if (KODI::WINDOWING::LINUX::COSScreenSaverFreedesktop::IsAvailable())
1502 {
1503 CLog::LogF(LOGINFO, "Using freedesktop.org DBus interface for screen saver inhibition");
1504 return std::unique_ptr<IOSScreenSaver>(new KODI::WINDOWING::LINUX::COSScreenSaverFreedesktop);
1505 }
1506 #endif
1507
1508 CLog::LogF(LOGINFO, "No supported method for screen saver inhibition found");
1509 return std::unique_ptr<IOSScreenSaver>(new CDummyOSScreenSaver);
1510 }
1511
1512 std::string CWinSystemWayland::GetClipboardText()
1513 {
1514 std::unique_lock<CCriticalSection> lock(m_seatsMutex);
1515 // Get text of first seat with non-empty selection
1516 // Actually, the value of the seat that received the Ctrl+V keypress should be used,
1517 // but this would need a workaround or proper multi-seat support in Kodi - it's
1518 // probably just not that relevant in practice
1519 for (auto const& seat : m_seats)
1520 {
1521 auto text = seat.second.GetSelectionText();
1522 if (text != "")
1523 {
1524 return text;
1525 }
1526 }
1527 return "";
1528 }
1529
1530 void CWinSystemWayland::OnWindowMove(const wayland::seat_t& seat, std::uint32_t serial)
1531 {
1532 m_shellSurface->StartMove(seat, serial);
1533 }
1534
1535 void CWinSystemWayland::OnWindowResize(const wayland::seat_t& seat, std::uint32_t serial, wayland::shell_surface_resize edge)
1536 {
1537 m_shellSurface->StartResize(seat, serial, edge);
1538 }
1539
1540 void CWinSystemWayland::OnWindowShowContextMenu(const wayland::seat_t& seat, std::uint32_t serial, CPointInt position)
1541 {
1542 m_shellSurface->ShowShellContextMenu(seat, serial, position);
1543 }
1544
1545 void CWinSystemWayland::OnWindowClose()
1546 {
1547 CServiceBroker::GetAppMessenger()->PostMsg(TMSG_QUIT);
1548 }
1549
1550 void CWinSystemWayland::OnWindowMinimize()
1551 {
1552 m_shellSurface->SetMinimized();
1553 }
1554
1555 void CWinSystemWayland::OnWindowMaximize()
1556 {
1557 if (m_shellSurfaceState.test(IShellSurface::STATE_MAXIMIZED))
1558 {
1559 m_shellSurface->UnsetMaximized();
1560 }
1561 else
1562 {
1563 m_shellSurface->SetMaximized();
1564 }
1565 }
1566
1567 void CWinSystemWayland::OnClose()
1568 {
1569 CServiceBroker::GetAppMessenger()->PostMsg(TMSG_QUIT);
1570 }
1571
1572 bool CWinSystemWayland::MessagePump()
1573 {
1574 return m_winEvents->MessagePump();
1575 }