Audio plugin host https://kx.studio/carla
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.

500 lines
17KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2015 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of either:
  6. a) the GPL v2 (or any later version)
  7. b) the Affero GPL v3
  8. Details of these licenses can be found at: www.gnu.org/licenses
  9. JUCE is distributed in the hope that it will be useful, but WITHOUT ANY
  10. WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
  11. A PARTICULAR PURPOSE. See the GNU General Public License for more details.
  12. ------------------------------------------------------------------------------
  13. To release a closed-source product which uses JUCE, commercial licenses are
  14. available: visit www.juce.com for more information.
  15. ==============================================================================
  16. */
  17. void LookAndFeel::playAlertSound()
  18. {
  19. NSBeep();
  20. }
  21. //==============================================================================
  22. class OSXMessageBox : private AsyncUpdater
  23. {
  24. public:
  25. OSXMessageBox (AlertWindow::AlertIconType type, const String& t, const String& m,
  26. const char* b1, const char* b2, const char* b3,
  27. ModalComponentManager::Callback* c, const bool runAsync)
  28. : iconType (type), title (t), message (m), callback (c),
  29. button1 (b1), button2 (b2), button3 (b3)
  30. {
  31. if (runAsync)
  32. triggerAsyncUpdate();
  33. }
  34. int getResult() const
  35. {
  36. switch (getRawResult())
  37. {
  38. case NSAlertFirstButtonReturn: return 1;
  39. case NSAlertThirdButtonReturn: return 2;
  40. default: return 0;
  41. }
  42. }
  43. static int show (AlertWindow::AlertIconType iconType, const String& title, const String& message,
  44. ModalComponentManager::Callback* callback, const char* b1, const char* b2, const char* b3,
  45. bool runAsync)
  46. {
  47. ScopedPointer<OSXMessageBox> mb (new OSXMessageBox (iconType, title, message, b1, b2, b3,
  48. callback, runAsync));
  49. if (! runAsync)
  50. return mb->getResult();
  51. mb.release();
  52. return 0;
  53. }
  54. private:
  55. AlertWindow::AlertIconType iconType;
  56. String title, message;
  57. ScopedPointer<ModalComponentManager::Callback> callback;
  58. const char* button1;
  59. const char* button2;
  60. const char* button3;
  61. void handleAsyncUpdate() override
  62. {
  63. const int result = getResult();
  64. if (callback != nullptr)
  65. callback->modalStateFinished (result);
  66. delete this;
  67. }
  68. NSInteger getRawResult() const
  69. {
  70. NSAlert* alert = [[[NSAlert alloc] init] autorelease];
  71. [alert setMessageText: juceStringToNS (title)];
  72. [alert setInformativeText: juceStringToNS (message)];
  73. [alert setAlertStyle: iconType == AlertWindow::WarningIcon ? NSCriticalAlertStyle
  74. : NSInformationalAlertStyle];
  75. addButton (alert, button1);
  76. addButton (alert, button2);
  77. addButton (alert, button3);
  78. return [alert runModal];
  79. }
  80. static void addButton (NSAlert* alert, const char* button)
  81. {
  82. if (button != nullptr)
  83. [alert addButtonWithTitle: juceStringToNS (TRANS (button))];
  84. }
  85. };
  86. #if JUCE_MODAL_LOOPS_PERMITTED
  87. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (AlertWindow::AlertIconType iconType,
  88. const String& title, const String& message,
  89. Component* /*associatedComponent*/)
  90. {
  91. OSXMessageBox::show (iconType, title, message, nullptr, "OK", nullptr, nullptr, false);
  92. }
  93. #endif
  94. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (AlertWindow::AlertIconType iconType,
  95. const String& title, const String& message,
  96. Component* /*associatedComponent*/,
  97. ModalComponentManager::Callback* callback)
  98. {
  99. OSXMessageBox::show (iconType, title, message, callback, "OK", nullptr, nullptr, true);
  100. }
  101. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (AlertWindow::AlertIconType iconType,
  102. const String& title, const String& message,
  103. Component* /*associatedComponent*/,
  104. ModalComponentManager::Callback* callback)
  105. {
  106. return OSXMessageBox::show (iconType, title, message, callback,
  107. "OK", "Cancel", nullptr, callback != nullptr) == 1;
  108. }
  109. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (AlertWindow::AlertIconType iconType,
  110. const String& title, const String& message,
  111. Component* /*associatedComponent*/,
  112. ModalComponentManager::Callback* callback)
  113. {
  114. return OSXMessageBox::show (iconType, title, message, callback,
  115. "Yes", "Cancel", "No", callback != nullptr);
  116. }
  117. //==============================================================================
  118. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool /*canMoveFiles*/)
  119. {
  120. if (files.size() == 0)
  121. return false;
  122. MouseInputSource* draggingSource = Desktop::getInstance().getDraggingMouseSource(0);
  123. if (draggingSource == nullptr)
  124. {
  125. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  126. return false;
  127. }
  128. Component* sourceComp = draggingSource->getComponentUnderMouse();
  129. if (sourceComp == nullptr)
  130. {
  131. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  132. return false;
  133. }
  134. JUCE_AUTORELEASEPOOL
  135. {
  136. if (NSView* view = (NSView*) sourceComp->getWindowHandle())
  137. {
  138. if (NSEvent* event = [[view window] currentEvent])
  139. {
  140. NSPoint eventPos = [event locationInWindow];
  141. NSRect dragRect = [view convertRect: NSMakeRect (eventPos.x - 16.0f, eventPos.y - 16.0f, 32.0f, 32.0f)
  142. fromView: nil];
  143. for (int i = 0; i < files.size(); ++i)
  144. {
  145. if (! [view dragFile: juceStringToNS (files[i])
  146. fromRect: dragRect
  147. slideBack: YES
  148. event: event])
  149. return false;
  150. }
  151. return true;
  152. }
  153. }
  154. }
  155. return false;
  156. }
  157. bool DragAndDropContainer::performExternalDragDropOfText (const String& /*text*/)
  158. {
  159. jassertfalse; // not implemented!
  160. return false;
  161. }
  162. //==============================================================================
  163. bool Desktop::canUseSemiTransparentWindows() noexcept
  164. {
  165. return true;
  166. }
  167. Point<float> MouseInputSource::getCurrentRawMousePosition()
  168. {
  169. JUCE_AUTORELEASEPOOL
  170. {
  171. const NSPoint p ([NSEvent mouseLocation]);
  172. return Point<float> ((float) p.x, (float) (getMainScreenHeight() - p.y));
  173. }
  174. }
  175. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  176. {
  177. // this rubbish needs to be done around the warp call, to avoid causing a
  178. // bizarre glitch..
  179. CGAssociateMouseAndMouseCursorPosition (false);
  180. CGWarpMouseCursorPosition (convertToCGPoint (newPosition));
  181. CGAssociateMouseAndMouseCursorPosition (true);
  182. }
  183. double Desktop::getDefaultMasterScale()
  184. {
  185. return 1.0;
  186. }
  187. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  188. {
  189. return upright;
  190. }
  191. //==============================================================================
  192. #if defined (MAC_OS_X_VERSION_10_7) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7)
  193. #define JUCE_USE_IOPM_SCREENSAVER_DEFEAT 1
  194. #endif
  195. #if ! (defined (JUCE_USE_IOPM_SCREENSAVER_DEFEAT) || defined (__POWER__))
  196. extern "C" { extern OSErr UpdateSystemActivity (UInt8); } // Some versions of the SDK omit this function..
  197. #endif
  198. class ScreenSaverDefeater : public Timer
  199. {
  200. public:
  201. #if JUCE_USE_IOPM_SCREENSAVER_DEFEAT
  202. ScreenSaverDefeater()
  203. {
  204. startTimer (5000);
  205. timerCallback();
  206. }
  207. void timerCallback() override
  208. {
  209. if (Process::isForegroundProcess())
  210. {
  211. if (assertion == nullptr)
  212. assertion = new PMAssertion();
  213. }
  214. else
  215. {
  216. assertion = nullptr;
  217. }
  218. }
  219. struct PMAssertion
  220. {
  221. PMAssertion() : assertionID (kIOPMNullAssertionID)
  222. {
  223. IOReturn res = IOPMAssertionCreateWithName (kIOPMAssertionTypePreventUserIdleDisplaySleep,
  224. kIOPMAssertionLevelOn,
  225. CFSTR ("JUCE Playback"),
  226. &assertionID);
  227. jassert (res == kIOReturnSuccess); ignoreUnused (res);
  228. }
  229. ~PMAssertion()
  230. {
  231. if (assertionID != kIOPMNullAssertionID)
  232. IOPMAssertionRelease (assertionID);
  233. }
  234. IOPMAssertionID assertionID;
  235. };
  236. ScopedPointer<PMAssertion> assertion;
  237. #else
  238. ScreenSaverDefeater()
  239. {
  240. startTimer (10000);
  241. timerCallback();
  242. }
  243. void timerCallback() override
  244. {
  245. if (Process::isForegroundProcess())
  246. UpdateSystemActivity (1 /*UsrActivity*/);
  247. }
  248. #endif
  249. };
  250. static ScopedPointer<ScreenSaverDefeater> screenSaverDefeater;
  251. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  252. {
  253. if (isEnabled)
  254. screenSaverDefeater = nullptr;
  255. else if (screenSaverDefeater == nullptr)
  256. screenSaverDefeater = new ScreenSaverDefeater();
  257. }
  258. bool Desktop::isScreenSaverEnabled()
  259. {
  260. return screenSaverDefeater == nullptr;
  261. }
  262. //==============================================================================
  263. class DisplaySettingsChangeCallback : private DeletedAtShutdown
  264. {
  265. public:
  266. DisplaySettingsChangeCallback()
  267. {
  268. CGDisplayRegisterReconfigurationCallback (displayReconfigurationCallBack, 0);
  269. }
  270. ~DisplaySettingsChangeCallback()
  271. {
  272. CGDisplayRemoveReconfigurationCallback (displayReconfigurationCallBack, 0);
  273. clearSingletonInstance();
  274. }
  275. static void displayReconfigurationCallBack (CGDirectDisplayID, CGDisplayChangeSummaryFlags, void*)
  276. {
  277. const_cast<Desktop::Displays&> (Desktop::getInstance().getDisplays()).refresh();
  278. }
  279. juce_DeclareSingleton_SingleThreaded_Minimal (DisplaySettingsChangeCallback)
  280. private:
  281. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DisplaySettingsChangeCallback)
  282. };
  283. juce_ImplementSingleton_SingleThreaded (DisplaySettingsChangeCallback)
  284. static Rectangle<int> convertDisplayRect (NSRect r, CGFloat mainScreenBottom)
  285. {
  286. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  287. return convertToRectInt (r);
  288. }
  289. static Desktop::Displays::Display getDisplayFromScreen (NSScreen* s, CGFloat& mainScreenBottom, const float masterScale)
  290. {
  291. Desktop::Displays::Display d;
  292. d.isMain = (mainScreenBottom == 0);
  293. if (d.isMain)
  294. mainScreenBottom = [s frame].size.height;
  295. d.userArea = convertDisplayRect ([s visibleFrame], mainScreenBottom) / masterScale;
  296. d.totalArea = convertDisplayRect ([s frame], mainScreenBottom) / masterScale;
  297. d.scale = masterScale;
  298. #if defined (MAC_OS_X_VERSION_10_7) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)
  299. if ([s respondsToSelector: @selector (backingScaleFactor)])
  300. d.scale *= s.backingScaleFactor;
  301. #endif
  302. NSSize dpi = [[[s deviceDescription] objectForKey: NSDeviceResolution] sizeValue];
  303. d.dpi = (dpi.width + dpi.height) / 2.0;
  304. return d;
  305. }
  306. void Desktop::Displays::findDisplays (const float masterScale)
  307. {
  308. JUCE_AUTORELEASEPOOL
  309. {
  310. DisplaySettingsChangeCallback::getInstance();
  311. CGFloat mainScreenBottom = 0;
  312. for (NSScreen* s in [NSScreen screens])
  313. displays.add (getDisplayFromScreen (s, mainScreenBottom, masterScale));
  314. }
  315. }
  316. //==============================================================================
  317. bool juce_areThereAnyAlwaysOnTopWindows()
  318. {
  319. for (NSWindow* window in [NSApp windows])
  320. if ([window level] > NSNormalWindowLevel)
  321. return true;
  322. return false;
  323. }
  324. //==============================================================================
  325. static void selectImageForDrawing (const Image& image)
  326. {
  327. [NSGraphicsContext saveGraphicsState];
  328. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: juce_getImageContext (image)
  329. flipped: false]];
  330. }
  331. static void releaseImageAfterDrawing()
  332. {
  333. [[NSGraphicsContext currentContext] flushGraphics];
  334. [NSGraphicsContext restoreGraphicsState];
  335. }
  336. Image juce_createIconForFile (const File& file)
  337. {
  338. JUCE_AUTORELEASEPOOL
  339. {
  340. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  341. Image result (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  342. selectImageForDrawing (result);
  343. [image drawAtPoint: NSMakePoint (0, 0)
  344. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  345. operation: NSCompositeSourceOver fraction: 1.0f];
  346. releaseImageAfterDrawing();
  347. return result;
  348. }
  349. }
  350. static Image createNSWindowSnapshot (NSWindow* nsWindow)
  351. {
  352. JUCE_AUTORELEASEPOOL
  353. {
  354. CGImageRef screenShot = CGWindowListCreateImage (CGRectNull,
  355. kCGWindowListOptionIncludingWindow,
  356. (CGWindowID) [nsWindow windowNumber],
  357. kCGWindowImageBoundsIgnoreFraming);
  358. NSBitmapImageRep* bitmapRep = [[NSBitmapImageRep alloc] initWithCGImage: screenShot];
  359. Image result (Image::ARGB, (int) [bitmapRep size].width, (int) [bitmapRep size].height, true);
  360. selectImageForDrawing (result);
  361. [bitmapRep drawAtPoint: NSMakePoint (0, 0)];
  362. releaseImageAfterDrawing();
  363. [bitmapRep release];
  364. CGImageRelease (screenShot);
  365. return result;
  366. }
  367. }
  368. Image createSnapshotOfNativeWindow (void* nativeWindowHandle)
  369. {
  370. if (id windowOrView = (id) nativeWindowHandle)
  371. {
  372. if ([windowOrView isKindOfClass: [NSWindow class]])
  373. return createNSWindowSnapshot ((NSWindow*) windowOrView);
  374. if ([windowOrView isKindOfClass: [NSView class]])
  375. return createNSWindowSnapshot ([(NSView*) windowOrView window]);
  376. }
  377. return Image();
  378. }
  379. //==============================================================================
  380. void SystemClipboard::copyTextToClipboard (const String& text)
  381. {
  382. NSPasteboard* pb = [NSPasteboard generalPasteboard];
  383. [pb declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  384. owner: nil];
  385. [pb setString: juceStringToNS (text)
  386. forType: NSStringPboardType];
  387. }
  388. String SystemClipboard::getTextFromClipboard()
  389. {
  390. return nsStringToJuce ([[NSPasteboard generalPasteboard] stringForType: NSStringPboardType]);
  391. }
  392. void Process::setDockIconVisible (bool isVisible)
  393. {
  394. #if defined (MAC_OS_X_VERSION_10_6) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_6)
  395. [NSApp setActivationPolicy: isVisible ? NSApplicationActivationPolicyRegular
  396. : NSApplicationActivationPolicyProhibited];
  397. #else
  398. ignoreUnused (isVisible);
  399. jassertfalse; // sorry, not available in 10.5!
  400. #endif
  401. }
  402. bool Desktop::isOSXDarkModeActive()
  403. {
  404. return [[[NSUserDefaults standardUserDefaults] stringForKey: nsStringLiteral ("AppleInterfaceStyle")]
  405. isEqualToString: nsStringLiteral ("Dark")];
  406. }