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.

564 lines
19KB

  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 ? NSAlertStyleCritical
  74. : NSAlertStyleInformational];
  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. static NSRect getDragRect (NSView* view, NSEvent* event)
  119. {
  120. auto eventPos = [event locationInWindow];
  121. return [view convertRect: NSMakeRect (eventPos.x - 16.0f, eventPos.y - 16.0f, 32.0f, 32.0f)
  122. fromView: nil];
  123. }
  124. NSView* getNSViewForDragEvent()
  125. {
  126. if (auto* draggingSource = Desktop::getInstance().getDraggingMouseSource(0))
  127. if (auto* sourceComp = draggingSource->getComponentUnderMouse())
  128. return (NSView*) sourceComp->getWindowHandle();
  129. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  130. return nil;
  131. }
  132. struct TextDragDataProviderClass : public ObjCClass<NSObject>
  133. {
  134. TextDragDataProviderClass() : ObjCClass<NSObject> ("JUCE_NSTextDragDataProvider_")
  135. {
  136. addIvar<String*> ("text");
  137. addMethod (@selector (dealloc), dealloc, "v@:");
  138. addMethod (@selector (pasteboard:item:provideDataForType:), provideDataForType, "v@:@@@");
  139. addProtocol (@protocol (NSPasteboardItemDataProvider));
  140. registerClass();
  141. }
  142. static void setText (id self, const String& text)
  143. {
  144. object_setInstanceVariable (self, "text", new String (text));
  145. }
  146. private:
  147. static void dealloc (id self, SEL)
  148. {
  149. delete getIvar<String*> (self, "text");
  150. sendSuperclassMessage (self, @selector (dealloc));
  151. }
  152. static void provideDataForType (id self, SEL, NSPasteboard* sender, NSPasteboardItem*, NSString* type)
  153. {
  154. if ([type compare: NSPasteboardTypeString] == NSOrderedSame)
  155. if (auto* text = getIvar<String*> (self, "text"))
  156. [sender setData: [juceStringToNS (*text) dataUsingEncoding: NSUTF8StringEncoding]
  157. forType: NSPasteboardTypeString];
  158. }
  159. };
  160. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  161. {
  162. if (text.isEmpty())
  163. return false;
  164. if (auto* view = getNSViewForDragEvent())
  165. {
  166. JUCE_AUTORELEASEPOOL
  167. {
  168. if (auto* event = [[view window] currentEvent])
  169. {
  170. static TextDragDataProviderClass dataProviderClass;
  171. id delegate = [dataProviderClass.createInstance() init];
  172. TextDragDataProviderClass::setText (delegate, text);
  173. auto* pasteboardItem = [[NSPasteboardItem new] autorelease];
  174. [pasteboardItem setDataProvider: delegate
  175. forTypes: [NSArray arrayWithObjects: NSPasteboardTypeString, nil]];
  176. auto* dragItem = [[[NSDraggingItem alloc] initWithPasteboardWriter: pasteboardItem] autorelease];
  177. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: nsEmptyString()];
  178. [dragItem setDraggingFrame: getDragRect (view, event) contents: image];
  179. auto* draggingSession = [view beginDraggingSessionWithItems: [NSArray arrayWithObject: dragItem]
  180. event: event
  181. source: delegate];
  182. draggingSession.animatesToStartingPositionsOnCancelOrFail = YES;
  183. draggingSession.draggingFormation = NSDraggingFormationNone;
  184. return true;
  185. }
  186. }
  187. }
  188. return false;
  189. }
  190. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, bool /*canMoveFiles*/)
  191. {
  192. if (files.isEmpty())
  193. return false;
  194. if (auto* view = getNSViewForDragEvent())
  195. {
  196. JUCE_AUTORELEASEPOOL
  197. {
  198. if (auto* event = [[view window] currentEvent])
  199. {
  200. auto dragRect = getDragRect (view, event);
  201. for (int i = 0; i < files.size(); ++i)
  202. if (! [view dragFile: juceStringToNS (files[i])
  203. fromRect: dragRect
  204. slideBack: YES
  205. event: event])
  206. return false;
  207. return true;
  208. }
  209. }
  210. }
  211. return false;
  212. }
  213. //==============================================================================
  214. bool Desktop::canUseSemiTransparentWindows() noexcept
  215. {
  216. return true;
  217. }
  218. Point<float> MouseInputSource::getCurrentRawMousePosition()
  219. {
  220. JUCE_AUTORELEASEPOOL
  221. {
  222. auto p = [NSEvent mouseLocation];
  223. return { (float) p.x, (float) (getMainScreenHeight() - p.y) };
  224. }
  225. }
  226. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  227. {
  228. // this rubbish needs to be done around the warp call, to avoid causing a
  229. // bizarre glitch..
  230. CGAssociateMouseAndMouseCursorPosition (false);
  231. CGWarpMouseCursorPosition (convertToCGPoint (newPosition));
  232. CGAssociateMouseAndMouseCursorPosition (true);
  233. }
  234. double Desktop::getDefaultMasterScale()
  235. {
  236. return 1.0;
  237. }
  238. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  239. {
  240. return upright;
  241. }
  242. //==============================================================================
  243. #if defined (MAC_OS_X_VERSION_10_7) && (MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_7)
  244. #define JUCE_USE_IOPM_SCREENSAVER_DEFEAT 1
  245. #endif
  246. #if ! (defined (JUCE_USE_IOPM_SCREENSAVER_DEFEAT) || defined (__POWER__))
  247. extern "C" { extern OSErr UpdateSystemActivity (UInt8); } // Some versions of the SDK omit this function..
  248. #endif
  249. class ScreenSaverDefeater : public Timer
  250. {
  251. public:
  252. #if JUCE_USE_IOPM_SCREENSAVER_DEFEAT
  253. ScreenSaverDefeater()
  254. {
  255. startTimer (5000);
  256. timerCallback();
  257. }
  258. void timerCallback() override
  259. {
  260. if (Process::isForegroundProcess())
  261. {
  262. if (assertion == nullptr)
  263. assertion = new PMAssertion();
  264. }
  265. else
  266. {
  267. assertion = nullptr;
  268. }
  269. }
  270. struct PMAssertion
  271. {
  272. PMAssertion() : assertionID (kIOPMNullAssertionID)
  273. {
  274. IOReturn res = IOPMAssertionCreateWithName (kIOPMAssertionTypePreventUserIdleDisplaySleep,
  275. kIOPMAssertionLevelOn,
  276. CFSTR ("JUCE Playback"),
  277. &assertionID);
  278. jassert (res == kIOReturnSuccess); ignoreUnused (res);
  279. }
  280. ~PMAssertion()
  281. {
  282. if (assertionID != kIOPMNullAssertionID)
  283. IOPMAssertionRelease (assertionID);
  284. }
  285. IOPMAssertionID assertionID;
  286. };
  287. ScopedPointer<PMAssertion> assertion;
  288. #else
  289. ScreenSaverDefeater()
  290. {
  291. startTimer (10000);
  292. timerCallback();
  293. }
  294. void timerCallback() override
  295. {
  296. if (Process::isForegroundProcess())
  297. UpdateSystemActivity (1 /*UsrActivity*/);
  298. }
  299. #endif
  300. };
  301. static ScopedPointer<ScreenSaverDefeater> screenSaverDefeater;
  302. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  303. {
  304. if (isEnabled)
  305. screenSaverDefeater = nullptr;
  306. else if (screenSaverDefeater == nullptr)
  307. screenSaverDefeater = new ScreenSaverDefeater();
  308. }
  309. bool Desktop::isScreenSaverEnabled()
  310. {
  311. return screenSaverDefeater == nullptr;
  312. }
  313. //==============================================================================
  314. class DisplaySettingsChangeCallback : private DeletedAtShutdown
  315. {
  316. public:
  317. DisplaySettingsChangeCallback()
  318. {
  319. CGDisplayRegisterReconfigurationCallback (displayReconfigurationCallBack, 0);
  320. }
  321. ~DisplaySettingsChangeCallback()
  322. {
  323. CGDisplayRemoveReconfigurationCallback (displayReconfigurationCallBack, 0);
  324. clearSingletonInstance();
  325. }
  326. static void displayReconfigurationCallBack (CGDirectDisplayID, CGDisplayChangeSummaryFlags, void*)
  327. {
  328. const_cast<Desktop::Displays&> (Desktop::getInstance().getDisplays()).refresh();
  329. }
  330. juce_DeclareSingleton_SingleThreaded_Minimal (DisplaySettingsChangeCallback)
  331. private:
  332. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DisplaySettingsChangeCallback)
  333. };
  334. juce_ImplementSingleton_SingleThreaded (DisplaySettingsChangeCallback)
  335. static Rectangle<int> convertDisplayRect (NSRect r, CGFloat mainScreenBottom)
  336. {
  337. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  338. return convertToRectInt (r);
  339. }
  340. static Desktop::Displays::Display getDisplayFromScreen (NSScreen* s, CGFloat& mainScreenBottom, const float masterScale)
  341. {
  342. Desktop::Displays::Display d;
  343. d.isMain = (mainScreenBottom == 0);
  344. if (d.isMain)
  345. mainScreenBottom = [s frame].size.height;
  346. d.userArea = convertDisplayRect ([s visibleFrame], mainScreenBottom) / masterScale;
  347. d.totalArea = convertDisplayRect ([s frame], mainScreenBottom) / masterScale;
  348. d.scale = masterScale;
  349. #if defined (MAC_OS_X_VERSION_10_7) && (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)
  350. if ([s respondsToSelector: @selector (backingScaleFactor)])
  351. d.scale *= s.backingScaleFactor;
  352. #endif
  353. NSSize dpi = [[[s deviceDescription] objectForKey: NSDeviceResolution] sizeValue];
  354. d.dpi = (dpi.width + dpi.height) / 2.0;
  355. return d;
  356. }
  357. void Desktop::Displays::findDisplays (const float masterScale)
  358. {
  359. JUCE_AUTORELEASEPOOL
  360. {
  361. DisplaySettingsChangeCallback::getInstance();
  362. CGFloat mainScreenBottom = 0;
  363. for (NSScreen* s in [NSScreen screens])
  364. displays.add (getDisplayFromScreen (s, mainScreenBottom, masterScale));
  365. }
  366. }
  367. //==============================================================================
  368. bool juce_areThereAnyAlwaysOnTopWindows()
  369. {
  370. for (NSWindow* window in [NSApp windows])
  371. if ([window level] > NSNormalWindowLevel)
  372. return true;
  373. return false;
  374. }
  375. //==============================================================================
  376. static void selectImageForDrawing (const Image& image)
  377. {
  378. [NSGraphicsContext saveGraphicsState];
  379. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: juce_getImageContext (image)
  380. flipped: false]];
  381. }
  382. static void releaseImageAfterDrawing()
  383. {
  384. [[NSGraphicsContext currentContext] flushGraphics];
  385. [NSGraphicsContext restoreGraphicsState];
  386. }
  387. Image juce_createIconForFile (const File& file)
  388. {
  389. JUCE_AUTORELEASEPOOL
  390. {
  391. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  392. Image result (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  393. selectImageForDrawing (result);
  394. [image drawAtPoint: NSMakePoint (0, 0)
  395. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  396. operation: NSCompositingOperationSourceOver fraction: 1.0f];
  397. releaseImageAfterDrawing();
  398. return result;
  399. }
  400. }
  401. static Image createNSWindowSnapshot (NSWindow* nsWindow)
  402. {
  403. JUCE_AUTORELEASEPOOL
  404. {
  405. CGImageRef screenShot = CGWindowListCreateImage (CGRectNull,
  406. kCGWindowListOptionIncludingWindow,
  407. (CGWindowID) [nsWindow windowNumber],
  408. kCGWindowImageBoundsIgnoreFraming);
  409. NSBitmapImageRep* bitmapRep = [[NSBitmapImageRep alloc] initWithCGImage: screenShot];
  410. Image result (Image::ARGB, (int) [bitmapRep size].width, (int) [bitmapRep size].height, true);
  411. selectImageForDrawing (result);
  412. [bitmapRep drawAtPoint: NSMakePoint (0, 0)];
  413. releaseImageAfterDrawing();
  414. [bitmapRep release];
  415. CGImageRelease (screenShot);
  416. return result;
  417. }
  418. }
  419. Image createSnapshotOfNativeWindow (void* nativeWindowHandle)
  420. {
  421. if (id windowOrView = (id) nativeWindowHandle)
  422. {
  423. if ([windowOrView isKindOfClass: [NSWindow class]])
  424. return createNSWindowSnapshot ((NSWindow*) windowOrView);
  425. if ([windowOrView isKindOfClass: [NSView class]])
  426. return createNSWindowSnapshot ([(NSView*) windowOrView window]);
  427. }
  428. return Image();
  429. }
  430. //==============================================================================
  431. void SystemClipboard::copyTextToClipboard (const String& text)
  432. {
  433. NSPasteboard* pb = [NSPasteboard generalPasteboard];
  434. [pb declareTypes: [NSArray arrayWithObject: NSStringPboardType]
  435. owner: nil];
  436. [pb setString: juceStringToNS (text)
  437. forType: NSStringPboardType];
  438. }
  439. String SystemClipboard::getTextFromClipboard()
  440. {
  441. return nsStringToJuce ([[NSPasteboard generalPasteboard] stringForType: NSStringPboardType]);
  442. }
  443. void Process::setDockIconVisible (bool isVisible)
  444. {
  445. ProcessSerialNumber psn { 0, kCurrentProcess };
  446. ProcessApplicationTransformState state = isVisible
  447. ? kProcessTransformToForegroundApplication
  448. : kProcessTransformToUIElementApplication;
  449. OSStatus err = TransformProcessType (&psn, state);
  450. jassert (err == 0);
  451. ignoreUnused (err);
  452. }
  453. bool Desktop::isOSXDarkModeActive()
  454. {
  455. return [[[NSUserDefaults standardUserDefaults] stringForKey: nsStringLiteral ("AppleInterfaceStyle")]
  456. isEqualToString: nsStringLiteral ("Dark")];
  457. }