The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

300 lines
9.8KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. //==============================================================================
  21. /*
  22. Forwards NSNotificationCenter callbacks to a std::function<void()>.
  23. */
  24. class FunctionNotificationCenterObserver
  25. {
  26. public:
  27. FunctionNotificationCenterObserver (NSNotificationName notificationName,
  28. id objectToObserve,
  29. std::function<void()> callback)
  30. : onNotification (std::move (callback)),
  31. observer (observerObject.get(), getSelector(), notificationName, objectToObserve)
  32. {}
  33. private:
  34. struct ObserverClass
  35. {
  36. ObserverClass()
  37. {
  38. klass.addIvar<FunctionNotificationCenterObserver*> ("owner");
  39. klass.addMethod (getSelector(), [] (id self, SEL, NSNotification*)
  40. {
  41. getIvar<FunctionNotificationCenterObserver*> (self, "owner")->onNotification();
  42. });
  43. klass.registerClass();
  44. }
  45. NSObject* createInstance() const { return klass.createInstance(); }
  46. private:
  47. ObjCClass<NSObject> klass { "JUCEObserverClass_" };
  48. };
  49. static SEL getSelector()
  50. {
  51. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  52. return @selector (notificationFired:);
  53. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  54. }
  55. std::function<void()> onNotification;
  56. NSUniquePtr<NSObject> observerObject
  57. {
  58. [this]
  59. {
  60. static ObserverClass observerClass;
  61. auto* result = observerClass.createInstance();
  62. object_setInstanceVariable (result, "owner", this);
  63. return result;
  64. }()
  65. };
  66. ScopedNotificationCenterObserver observer;
  67. // Instances can't be copied or moved, because 'this' is stored as a member of the ObserverClass
  68. // object.
  69. JUCE_DECLARE_NON_COPYABLE (FunctionNotificationCenterObserver)
  70. JUCE_DECLARE_NON_MOVEABLE (FunctionNotificationCenterObserver)
  71. };
  72. //==============================================================================
  73. /*
  74. Manages the lifetime of a CVDisplayLinkRef for a single display, and automatically starts and
  75. stops it.
  76. */
  77. class ScopedDisplayLink
  78. {
  79. public:
  80. ScopedDisplayLink (NSScreen* screenIn, std::function<void()> onCallbackIn)
  81. : screen (screenIn),
  82. link ([display = (CGDirectDisplayID) [[screen.deviceDescription objectForKey: @"NSScreenNumber"] unsignedIntegerValue]]
  83. {
  84. CVDisplayLinkRef ptr = nullptr;
  85. const auto result = CVDisplayLinkCreateWithCGDisplay (display, &ptr);
  86. jassertquiet (result == kCVReturnSuccess);
  87. jassertquiet (ptr != nullptr);
  88. return ptr;
  89. }()),
  90. onCallback (std::move (onCallbackIn))
  91. {
  92. const auto callback = [] (CVDisplayLinkRef,
  93. const CVTimeStamp*,
  94. const CVTimeStamp*,
  95. CVOptionFlags,
  96. CVOptionFlags*,
  97. void* context) -> int
  98. {
  99. static_cast<const ScopedDisplayLink*> (context)->onCallback();
  100. return kCVReturnSuccess;
  101. };
  102. const auto callbackResult = CVDisplayLinkSetOutputCallback (link.get(), callback, this);
  103. jassertquiet (callbackResult == kCVReturnSuccess);
  104. const auto startResult = CVDisplayLinkStart (link.get());
  105. jassertquiet (startResult == kCVReturnSuccess);
  106. }
  107. ~ScopedDisplayLink() noexcept
  108. {
  109. if (link != nullptr)
  110. CVDisplayLinkStop (link.get());
  111. }
  112. NSScreen* getScreen() const { return screen; }
  113. double getNominalVideoRefreshPeriodS() const
  114. {
  115. const auto nominalVideoRefreshPeriod = CVDisplayLinkGetNominalOutputVideoRefreshPeriod (link.get());
  116. if ((nominalVideoRefreshPeriod.flags & kCVTimeIsIndefinite) == 0)
  117. return (double) nominalVideoRefreshPeriod.timeValue / (double) nominalVideoRefreshPeriod.timeScale;
  118. return 0.0;
  119. }
  120. private:
  121. struct DisplayLinkDestructor
  122. {
  123. void operator() (CVDisplayLinkRef ptr) const
  124. {
  125. if (ptr != nullptr)
  126. CVDisplayLinkRelease (ptr);
  127. }
  128. };
  129. NSScreen* screen = nullptr;
  130. std::unique_ptr<std::remove_pointer_t<CVDisplayLinkRef>, DisplayLinkDestructor> link;
  131. std::function<void()> onCallback;
  132. // Instances can't be copied or moved, because 'this' is passed as context to
  133. // CVDisplayLinkSetOutputCallback
  134. JUCE_DECLARE_NON_COPYABLE (ScopedDisplayLink)
  135. JUCE_DECLARE_NON_MOVEABLE (ScopedDisplayLink)
  136. };
  137. //==============================================================================
  138. /*
  139. Holds a ScopedDisplayLink for each screen. When the screen configuration changes, the
  140. ScopedDisplayLinks will be recreated automatically to match the new configuration.
  141. */
  142. class PerScreenDisplayLinks
  143. {
  144. public:
  145. PerScreenDisplayLinks()
  146. {
  147. refreshScreens();
  148. }
  149. using RefreshCallback = std::function<void()>;
  150. using Factory = std::function<RefreshCallback (NSScreen*)>;
  151. /*
  152. Automatically unregisters a CVDisplayLink callback factory when ~Connection() is called.
  153. */
  154. class Connection
  155. {
  156. public:
  157. Connection() = default;
  158. Connection (PerScreenDisplayLinks& linksIn, std::list<Factory>::const_iterator it)
  159. : links (&linksIn), iter (it) {}
  160. ~Connection() noexcept
  161. {
  162. if (links != nullptr)
  163. links->unregisterFactory (iter);
  164. }
  165. Connection (const Connection&) = delete;
  166. Connection& operator= (const Connection&) = delete;
  167. Connection (Connection&& other) noexcept
  168. : links (std::exchange (other.links, nullptr)), iter (other.iter) {}
  169. Connection& operator= (Connection&& other) noexcept
  170. {
  171. Connection { std::move (other) }.swap (*this);
  172. return *this;
  173. }
  174. private:
  175. void swap (Connection& other) noexcept
  176. {
  177. std::swap (other.links, links);
  178. std::swap (other.iter, iter);
  179. }
  180. PerScreenDisplayLinks* links = nullptr;
  181. std::list<Factory>::const_iterator iter;
  182. };
  183. /* Stores the provided factory for as long as the returned Connection remains alive.
  184. Whenever the screen configuration changes, the factory function will be called for each
  185. screen. The RefreshCallback returned by the factory will be called every time that screen's
  186. display link callback fires.
  187. */
  188. [[nodiscard]] Connection registerFactory (Factory factory)
  189. {
  190. const ScopedLock lock (mutex);
  191. factories.push_front (std::move (factory));
  192. refreshScreens();
  193. return { *this, factories.begin() };
  194. }
  195. double getNominalVideoRefreshPeriodSForScreen (NSScreen* screen) const
  196. {
  197. const ScopedLock lock (mutex);
  198. for (const auto& link : links)
  199. if (link.getScreen() == screen)
  200. return link.getNominalVideoRefreshPeriodS();
  201. return 0.0;
  202. }
  203. private:
  204. void unregisterFactory (std::list<Factory>::const_iterator iter)
  205. {
  206. const ScopedLock lock (mutex);
  207. factories.erase (iter);
  208. refreshScreens();
  209. }
  210. void refreshScreens()
  211. {
  212. auto newLinks = [&]
  213. {
  214. std::list<ScopedDisplayLink> result;
  215. for (NSScreen* screen in [NSScreen screens])
  216. {
  217. std::vector<RefreshCallback> callbacks;
  218. for (auto& factory : factories)
  219. callbacks.push_back (factory (screen));
  220. // This is the callback that will actually fire in response to this screen's display
  221. // link callback.
  222. result.emplace_back (screen, [callbacks = std::move (callbacks)]
  223. {
  224. for (const auto& callback : callbacks)
  225. callback();
  226. });
  227. }
  228. return result;
  229. }();
  230. const ScopedLock lock (mutex);
  231. links = std::move (newLinks);
  232. }
  233. CriticalSection mutex;
  234. // This is a list rather than a vector so that the iterators are stable, even when items are
  235. // added/removed from the list. This is important because Connection objects store an iterator
  236. // internally, and may be created/destroyed arbitrarily.
  237. std::list<Factory> factories;
  238. // This is a list rather than a vector because ScopedDisplayLink is non-moveable.
  239. std::list<ScopedDisplayLink> links;
  240. FunctionNotificationCenterObserver observer { NSApplicationDidChangeScreenParametersNotification,
  241. nullptr,
  242. [this] { refreshScreens(); } };
  243. };
  244. } // namespace juce