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.

785 lines
28KB

  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. void LookAndFeel::playAlertSound()
  21. {
  22. NSBeep();
  23. }
  24. //==============================================================================
  25. class OSXMessageBox : private AsyncUpdater
  26. {
  27. public:
  28. OSXMessageBox (const MessageBoxOptions& opts,
  29. std::unique_ptr<ModalComponentManager::Callback>&& c)
  30. : options (opts), callback (std::move (c))
  31. {
  32. }
  33. int getResult() const
  34. {
  35. return convertResult ([getAlert() runModal]);
  36. }
  37. using AsyncUpdater::triggerAsyncUpdate;
  38. private:
  39. static int convertResult (NSModalResponse response)
  40. {
  41. switch (response)
  42. {
  43. case NSAlertFirstButtonReturn: return 0;
  44. case NSAlertSecondButtonReturn: return 1;
  45. case NSAlertThirdButtonReturn: return 2;
  46. default: break;
  47. }
  48. jassertfalse;
  49. return 0;
  50. }
  51. void handleAsyncUpdate() override
  52. {
  53. if (auto* comp = options.getAssociatedComponent())
  54. {
  55. if (auto* peer = comp->getPeer())
  56. {
  57. if (auto* view = static_cast<NSView*> (peer->getNativeHandle()))
  58. {
  59. if (auto* window = [view window])
  60. {
  61. if (@available (macOS 10.9, *))
  62. {
  63. [getAlert() beginSheetModalForWindow: window completionHandler: ^(NSModalResponse result)
  64. {
  65. handleModalFinished (result);
  66. }];
  67. return;
  68. }
  69. }
  70. }
  71. }
  72. }
  73. handleModalFinished ([getAlert() runModal]);
  74. }
  75. void handleModalFinished (NSModalResponse result)
  76. {
  77. if (callback != nullptr)
  78. callback->modalStateFinished (convertResult (result));
  79. delete this;
  80. }
  81. static void addButton (NSAlert* alert, const String& button)
  82. {
  83. if (! button.isEmpty())
  84. [alert addButtonWithTitle: juceStringToNS (button)];
  85. }
  86. NSAlert* getAlert() const
  87. {
  88. NSAlert* alert = [[[NSAlert alloc] init] autorelease];
  89. [alert setMessageText: juceStringToNS (options.getTitle())];
  90. [alert setInformativeText: juceStringToNS (options.getMessage())];
  91. [alert setAlertStyle: options.getIconType() == MessageBoxIconType::WarningIcon ? NSAlertStyleCritical
  92. : NSAlertStyleInformational];
  93. const auto button1Text = options.getButtonText (0);
  94. addButton (alert, button1Text.isEmpty() ? "OK" : button1Text);
  95. addButton (alert, options.getButtonText (1));
  96. addButton (alert, options.getButtonText (2));
  97. return alert;
  98. }
  99. MessageBoxOptions options;
  100. std::unique_ptr<ModalComponentManager::Callback> callback;
  101. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OSXMessageBox)
  102. };
  103. static int showDialog (const MessageBoxOptions& options,
  104. ModalComponentManager::Callback* callbackIn,
  105. AlertWindowMappings::MapFn mapFn)
  106. {
  107. #if JUCE_MODAL_LOOPS_PERMITTED
  108. if (callbackIn == nullptr)
  109. {
  110. jassert (mapFn != nullptr);
  111. OSXMessageBox messageBox (options, nullptr);
  112. return mapFn (messageBox.getResult());
  113. }
  114. #endif
  115. auto messageBox = std::make_unique<OSXMessageBox> (options,
  116. AlertWindowMappings::getWrappedCallback (callbackIn, mapFn));
  117. messageBox->triggerAsyncUpdate();
  118. messageBox.release();
  119. return 0;
  120. }
  121. #if JUCE_MODAL_LOOPS_PERMITTED
  122. void JUCE_CALLTYPE NativeMessageBox::showMessageBox (MessageBoxIconType iconType,
  123. const String& title, const String& message,
  124. Component* associatedComponent)
  125. {
  126. showDialog (MessageBoxOptions()
  127. .withIconType (iconType)
  128. .withTitle (title)
  129. .withMessage (message)
  130. .withButton (TRANS("OK"))
  131. .withAssociatedComponent (associatedComponent),
  132. nullptr, AlertWindowMappings::messageBox);
  133. }
  134. int JUCE_CALLTYPE NativeMessageBox::show (const MessageBoxOptions& options)
  135. {
  136. return showDialog (options, nullptr, AlertWindowMappings::noMapping);
  137. }
  138. #endif
  139. void JUCE_CALLTYPE NativeMessageBox::showMessageBoxAsync (MessageBoxIconType iconType,
  140. const String& title, const String& message,
  141. Component* associatedComponent,
  142. ModalComponentManager::Callback* callback)
  143. {
  144. showDialog (MessageBoxOptions()
  145. .withIconType (iconType)
  146. .withTitle (title)
  147. .withMessage (message)
  148. .withButton (TRANS("OK"))
  149. .withAssociatedComponent (associatedComponent),
  150. callback, AlertWindowMappings::messageBox);
  151. }
  152. bool JUCE_CALLTYPE NativeMessageBox::showOkCancelBox (MessageBoxIconType iconType,
  153. const String& title, const String& message,
  154. Component* associatedComponent,
  155. ModalComponentManager::Callback* callback)
  156. {
  157. return showDialog (MessageBoxOptions()
  158. .withIconType (iconType)
  159. .withTitle (title)
  160. .withMessage (message)
  161. .withButton (TRANS("OK"))
  162. .withButton (TRANS("Cancel"))
  163. .withAssociatedComponent (associatedComponent),
  164. callback, AlertWindowMappings::okCancel) != 0;
  165. }
  166. int JUCE_CALLTYPE NativeMessageBox::showYesNoCancelBox (MessageBoxIconType iconType,
  167. const String& title, const String& message,
  168. Component* associatedComponent,
  169. ModalComponentManager::Callback* callback)
  170. {
  171. return showDialog (MessageBoxOptions()
  172. .withIconType (iconType)
  173. .withTitle (title)
  174. .withMessage (message)
  175. .withButton (TRANS("Yes"))
  176. .withButton (TRANS("No"))
  177. .withButton (TRANS("Cancel"))
  178. .withAssociatedComponent (associatedComponent),
  179. callback, AlertWindowMappings::yesNoCancel);
  180. }
  181. int JUCE_CALLTYPE NativeMessageBox::showYesNoBox (MessageBoxIconType iconType,
  182. const String& title, const String& message,
  183. Component* associatedComponent,
  184. ModalComponentManager::Callback* callback)
  185. {
  186. return showDialog (MessageBoxOptions()
  187. .withIconType (iconType)
  188. .withTitle (title)
  189. .withMessage (message)
  190. .withButton (TRANS("Yes"))
  191. .withButton (TRANS("No"))
  192. .withAssociatedComponent (associatedComponent),
  193. callback, AlertWindowMappings::okCancel);
  194. }
  195. void JUCE_CALLTYPE NativeMessageBox::showAsync (const MessageBoxOptions& options,
  196. ModalComponentManager::Callback* callback)
  197. {
  198. showDialog (options, callback, AlertWindowMappings::noMapping);
  199. }
  200. void JUCE_CALLTYPE NativeMessageBox::showAsync (const MessageBoxOptions& options,
  201. std::function<void (int)> callback)
  202. {
  203. showAsync (options, ModalCallbackFunction::create (callback));
  204. }
  205. //==============================================================================
  206. static NSRect getDragRect (NSView* view, NSEvent* event)
  207. {
  208. auto eventPos = [event locationInWindow];
  209. return [view convertRect: NSMakeRect (eventPos.x - 16.0f, eventPos.y - 16.0f, 32.0f, 32.0f)
  210. fromView: nil];
  211. }
  212. static NSView* getNSViewForDragEvent (Component* sourceComp)
  213. {
  214. if (sourceComp == nullptr)
  215. if (auto* draggingSource = Desktop::getInstance().getDraggingMouseSource (0))
  216. sourceComp = draggingSource->getComponentUnderMouse();
  217. if (sourceComp != nullptr)
  218. return (NSView*) sourceComp->getWindowHandle();
  219. jassertfalse; // This method must be called in response to a component's mouseDown or mouseDrag event!
  220. return nil;
  221. }
  222. struct NSDraggingSourceHelper : public ObjCClass<NSObject<NSDraggingSource>>
  223. {
  224. NSDraggingSourceHelper() : ObjCClass<NSObject<NSDraggingSource>> ("JUCENSDraggingSourceHelper_")
  225. {
  226. addIvar<std::function<void()>*> ("callback");
  227. addIvar<String*> ("text");
  228. addIvar<NSDragOperation*> ("operation");
  229. addMethod (@selector (dealloc), dealloc);
  230. addMethod (@selector (pasteboard:item:provideDataForType:), provideDataForType);
  231. addMethod (@selector (draggingSession:sourceOperationMaskForDraggingContext:), sourceOperationMaskForDraggingContext);
  232. addMethod (@selector (draggingSession:endedAtPoint:operation:), draggingSessionEnded);
  233. addProtocol (@protocol (NSPasteboardItemDataProvider));
  234. registerClass();
  235. }
  236. static void setText (id self, const String& text)
  237. {
  238. object_setInstanceVariable (self, "text", new String (text));
  239. }
  240. static void setCompletionCallback (id self, std::function<void()> cb)
  241. {
  242. object_setInstanceVariable (self, "callback", new std::function<void()> (cb));
  243. }
  244. static void setDragOperation (id self, NSDragOperation op)
  245. {
  246. object_setInstanceVariable (self, "operation", new NSDragOperation (op));
  247. }
  248. private:
  249. static void dealloc (id self, SEL)
  250. {
  251. delete getIvar<String*> (self, "text");
  252. delete getIvar<std::function<void()>*> (self, "callback");
  253. delete getIvar<NSDragOperation*> (self, "operation");
  254. sendSuperclassMessage<void> (self, @selector (dealloc));
  255. }
  256. static void provideDataForType (id self, SEL, NSPasteboard* sender, NSPasteboardItem*, NSString* type)
  257. {
  258. if ([type compare: NSPasteboardTypeString] == NSOrderedSame)
  259. if (auto* text = getIvar<String*> (self, "text"))
  260. [sender setData: [juceStringToNS (*text) dataUsingEncoding: NSUTF8StringEncoding]
  261. forType: NSPasteboardTypeString];
  262. }
  263. static NSDragOperation sourceOperationMaskForDraggingContext (id self, SEL, NSDraggingSession*, NSDraggingContext)
  264. {
  265. return *getIvar<NSDragOperation*> (self, "operation");
  266. }
  267. static void draggingSessionEnded (id self, SEL, NSDraggingSession*, NSPoint p, NSDragOperation)
  268. {
  269. // Our view doesn't receive a mouse up when the drag ends so we need to generate one here and send it...
  270. if (auto* view = getNSViewForDragEvent (nullptr))
  271. if (auto* cgEvent = CGEventCreateMouseEvent (nullptr, kCGEventLeftMouseUp, CGPointMake (p.x, p.y), kCGMouseButtonLeft))
  272. if (id e = [NSEvent eventWithCGEvent: cgEvent])
  273. [view mouseUp: e];
  274. if (auto* cb = getIvar<std::function<void()>*> (self, "callback"))
  275. cb->operator()();
  276. }
  277. };
  278. static NSDraggingSourceHelper draggingSourceHelper;
  279. bool DragAndDropContainer::performExternalDragDropOfText (const String& text, Component* sourceComponent,
  280. std::function<void()> callback)
  281. {
  282. if (text.isEmpty())
  283. return false;
  284. if (auto* view = getNSViewForDragEvent (sourceComponent))
  285. {
  286. JUCE_AUTORELEASEPOOL
  287. {
  288. if (auto event = [[view window] currentEvent])
  289. {
  290. id helper = [draggingSourceHelper.createInstance() init];
  291. NSDraggingSourceHelper::setText (helper, text);
  292. NSDraggingSourceHelper::setDragOperation (helper, NSDragOperationCopy);
  293. if (callback != nullptr)
  294. NSDraggingSourceHelper::setCompletionCallback (helper, callback);
  295. auto pasteboardItem = [[NSPasteboardItem new] autorelease];
  296. [pasteboardItem setDataProvider: helper
  297. forTypes: [NSArray arrayWithObjects: NSPasteboardTypeString, nil]];
  298. auto dragItem = [[[NSDraggingItem alloc] initWithPasteboardWriter: pasteboardItem] autorelease];
  299. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: nsEmptyString()];
  300. [dragItem setDraggingFrame: getDragRect (view, event) contents: image];
  301. if (auto session = [view beginDraggingSessionWithItems: [NSArray arrayWithObject: dragItem]
  302. event: event
  303. source: helper])
  304. {
  305. session.animatesToStartingPositionsOnCancelOrFail = YES;
  306. session.draggingFormation = NSDraggingFormationNone;
  307. return true;
  308. }
  309. }
  310. }
  311. }
  312. return false;
  313. }
  314. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, bool canMoveFiles,
  315. Component* sourceComponent, std::function<void()> callback)
  316. {
  317. if (files.isEmpty())
  318. return false;
  319. if (auto* view = getNSViewForDragEvent (sourceComponent))
  320. {
  321. JUCE_AUTORELEASEPOOL
  322. {
  323. if (auto event = [[view window] currentEvent])
  324. {
  325. auto dragItems = [[[NSMutableArray alloc] init] autorelease];
  326. for (auto& filename : files)
  327. {
  328. auto* nsFilename = juceStringToNS (filename);
  329. auto fileURL = [NSURL fileURLWithPath: nsFilename];
  330. auto dragItem = [[NSDraggingItem alloc] initWithPasteboardWriter: fileURL];
  331. auto eventPos = [event locationInWindow];
  332. auto dragRect = [view convertRect: NSMakeRect (eventPos.x - 16.0f, eventPos.y - 16.0f, 32.0f, 32.0f)
  333. fromView: nil];
  334. auto dragImage = [[NSWorkspace sharedWorkspace] iconForFile: nsFilename];
  335. [dragItem setDraggingFrame: dragRect
  336. contents: dragImage];
  337. [dragItems addObject: dragItem];
  338. [dragItem release];
  339. }
  340. auto helper = [draggingSourceHelper.createInstance() autorelease];
  341. if (callback != nullptr)
  342. NSDraggingSourceHelper::setCompletionCallback (helper, callback);
  343. NSDraggingSourceHelper::setDragOperation (helper, canMoveFiles ? NSDragOperationMove
  344. : NSDragOperationCopy);
  345. return [view beginDraggingSessionWithItems: dragItems
  346. event: event
  347. source: helper] != nullptr;
  348. }
  349. }
  350. }
  351. return false;
  352. }
  353. //==============================================================================
  354. bool Desktop::canUseSemiTransparentWindows() noexcept
  355. {
  356. return true;
  357. }
  358. Point<float> MouseInputSource::getCurrentRawMousePosition()
  359. {
  360. JUCE_AUTORELEASEPOOL
  361. {
  362. auto p = [NSEvent mouseLocation];
  363. return { (float) p.x, (float) (getMainScreenHeight() - p.y) };
  364. }
  365. }
  366. void MouseInputSource::setRawMousePosition (Point<float> newPosition)
  367. {
  368. // this rubbish needs to be done around the warp call, to avoid causing a
  369. // bizarre glitch..
  370. CGAssociateMouseAndMouseCursorPosition (false);
  371. CGWarpMouseCursorPosition (convertToCGPoint (newPosition));
  372. CGAssociateMouseAndMouseCursorPosition (true);
  373. }
  374. double Desktop::getDefaultMasterScale()
  375. {
  376. return 1.0;
  377. }
  378. Desktop::DisplayOrientation Desktop::getCurrentOrientation() const
  379. {
  380. return upright;
  381. }
  382. bool Desktop::isDarkModeActive() const
  383. {
  384. return [[[NSUserDefaults standardUserDefaults] stringForKey: nsStringLiteral ("AppleInterfaceStyle")]
  385. isEqualToString: nsStringLiteral ("Dark")];
  386. }
  387. class Desktop::NativeDarkModeChangeDetectorImpl
  388. {
  389. public:
  390. NativeDarkModeChangeDetectorImpl()
  391. {
  392. static DelegateClass delegateClass;
  393. delegate = [delegateClass.createInstance() init];
  394. object_setInstanceVariable (delegate, "owner", this);
  395. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  396. [[NSDistributedNotificationCenter defaultCenter] addObserver: delegate
  397. selector: @selector (darkModeChanged:)
  398. name: @"AppleInterfaceThemeChangedNotification"
  399. object: nil];
  400. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  401. }
  402. ~NativeDarkModeChangeDetectorImpl()
  403. {
  404. object_setInstanceVariable (delegate, "owner", nullptr);
  405. [[NSDistributedNotificationCenter defaultCenter] removeObserver: delegate];
  406. [delegate release];
  407. }
  408. void darkModeChanged()
  409. {
  410. Desktop::getInstance().darkModeChanged();
  411. }
  412. private:
  413. struct DelegateClass : public ObjCClass<NSObject>
  414. {
  415. DelegateClass() : ObjCClass<NSObject> ("JUCEDelegate_")
  416. {
  417. addIvar<NativeDarkModeChangeDetectorImpl*> ("owner");
  418. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
  419. addMethod (@selector (darkModeChanged:), darkModeChanged);
  420. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  421. registerClass();
  422. }
  423. static void darkModeChanged (id self, SEL, NSNotification*)
  424. {
  425. if (auto* owner = getIvar<NativeDarkModeChangeDetectorImpl*> (self, "owner"))
  426. owner->darkModeChanged();
  427. }
  428. };
  429. id delegate = nil;
  430. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (NativeDarkModeChangeDetectorImpl)
  431. };
  432. std::unique_ptr<Desktop::NativeDarkModeChangeDetectorImpl> Desktop::createNativeDarkModeChangeDetectorImpl()
  433. {
  434. return std::make_unique<NativeDarkModeChangeDetectorImpl>();
  435. }
  436. //==============================================================================
  437. class ScreenSaverDefeater : public Timer
  438. {
  439. public:
  440. ScreenSaverDefeater()
  441. {
  442. startTimer (5000);
  443. timerCallback();
  444. }
  445. void timerCallback() override
  446. {
  447. if (Process::isForegroundProcess())
  448. {
  449. if (assertion == nullptr)
  450. assertion.reset (new PMAssertion());
  451. }
  452. else
  453. {
  454. assertion.reset();
  455. }
  456. }
  457. struct PMAssertion
  458. {
  459. PMAssertion() : assertionID (kIOPMNullAssertionID)
  460. {
  461. IOReturn res = IOPMAssertionCreateWithName (kIOPMAssertionTypePreventUserIdleDisplaySleep,
  462. kIOPMAssertionLevelOn,
  463. CFSTR ("JUCE Playback"),
  464. &assertionID);
  465. jassert (res == kIOReturnSuccess); ignoreUnused (res);
  466. }
  467. ~PMAssertion()
  468. {
  469. if (assertionID != kIOPMNullAssertionID)
  470. IOPMAssertionRelease (assertionID);
  471. }
  472. IOPMAssertionID assertionID;
  473. };
  474. std::unique_ptr<PMAssertion> assertion;
  475. };
  476. static std::unique_ptr<ScreenSaverDefeater> screenSaverDefeater;
  477. void Desktop::setScreenSaverEnabled (const bool isEnabled)
  478. {
  479. if (isEnabled)
  480. screenSaverDefeater.reset();
  481. else if (screenSaverDefeater == nullptr)
  482. screenSaverDefeater.reset (new ScreenSaverDefeater());
  483. }
  484. bool Desktop::isScreenSaverEnabled()
  485. {
  486. return screenSaverDefeater == nullptr;
  487. }
  488. //==============================================================================
  489. struct DisplaySettingsChangeCallback : private DeletedAtShutdown
  490. {
  491. DisplaySettingsChangeCallback()
  492. {
  493. CGDisplayRegisterReconfigurationCallback (displayReconfigurationCallback, this);
  494. }
  495. ~DisplaySettingsChangeCallback()
  496. {
  497. CGDisplayRemoveReconfigurationCallback (displayReconfigurationCallback, this);
  498. clearSingletonInstance();
  499. }
  500. static void displayReconfigurationCallback (CGDirectDisplayID, CGDisplayChangeSummaryFlags, void* userInfo)
  501. {
  502. if (auto* thisPtr = static_cast<DisplaySettingsChangeCallback*> (userInfo))
  503. if (thisPtr->forceDisplayUpdate != nullptr)
  504. thisPtr->forceDisplayUpdate();
  505. }
  506. std::function<void()> forceDisplayUpdate;
  507. JUCE_DECLARE_SINGLETON (DisplaySettingsChangeCallback, false)
  508. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DisplaySettingsChangeCallback)
  509. };
  510. JUCE_IMPLEMENT_SINGLETON (DisplaySettingsChangeCallback)
  511. static Rectangle<int> convertDisplayRect (NSRect r, CGFloat mainScreenBottom)
  512. {
  513. r.origin.y = mainScreenBottom - (r.origin.y + r.size.height);
  514. return convertToRectInt (r);
  515. }
  516. static Displays::Display getDisplayFromScreen (NSScreen* s, CGFloat& mainScreenBottom, const float masterScale)
  517. {
  518. Displays::Display d;
  519. d.isMain = (mainScreenBottom == 0);
  520. if (d.isMain)
  521. mainScreenBottom = [s frame].size.height;
  522. d.userArea = convertDisplayRect ([s visibleFrame], mainScreenBottom) / masterScale;
  523. d.totalArea = convertDisplayRect ([s frame], mainScreenBottom) / masterScale;
  524. d.scale = masterScale;
  525. if ([s respondsToSelector: @selector (backingScaleFactor)])
  526. d.scale *= s.backingScaleFactor;
  527. NSSize dpi = [[[s deviceDescription] objectForKey: NSDeviceResolution] sizeValue];
  528. d.dpi = (dpi.width + dpi.height) / 2.0;
  529. return d;
  530. }
  531. void Displays::findDisplays (const float masterScale)
  532. {
  533. JUCE_AUTORELEASEPOOL
  534. {
  535. if (DisplaySettingsChangeCallback::getInstanceWithoutCreating() == nullptr)
  536. DisplaySettingsChangeCallback::getInstance()->forceDisplayUpdate = [this] { refresh(); };
  537. CGFloat mainScreenBottom = 0;
  538. for (NSScreen* s in [NSScreen screens])
  539. displays.add (getDisplayFromScreen (s, mainScreenBottom, masterScale));
  540. }
  541. }
  542. //==============================================================================
  543. bool juce_areThereAnyAlwaysOnTopWindows()
  544. {
  545. for (NSWindow* window in [NSApp windows])
  546. if ([window level] > NSNormalWindowLevel)
  547. return true;
  548. return false;
  549. }
  550. //==============================================================================
  551. static void selectImageForDrawing (const Image& image)
  552. {
  553. [NSGraphicsContext saveGraphicsState];
  554. if (@available (macOS 10.10, *))
  555. {
  556. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithCGContext: juce_getImageContext (image)
  557. flipped: false]];
  558. return;
  559. }
  560. JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wdeprecated-declarations")
  561. [NSGraphicsContext setCurrentContext: [NSGraphicsContext graphicsContextWithGraphicsPort: juce_getImageContext (image)
  562. flipped: false]];
  563. JUCE_END_IGNORE_WARNINGS_GCC_LIKE
  564. }
  565. static void releaseImageAfterDrawing()
  566. {
  567. [[NSGraphicsContext currentContext] flushGraphics];
  568. [NSGraphicsContext restoreGraphicsState];
  569. }
  570. Image juce_createIconForFile (const File& file)
  571. {
  572. JUCE_AUTORELEASEPOOL
  573. {
  574. NSImage* image = [[NSWorkspace sharedWorkspace] iconForFile: juceStringToNS (file.getFullPathName())];
  575. Image result (Image::ARGB, (int) [image size].width, (int) [image size].height, true);
  576. selectImageForDrawing (result);
  577. [image drawAtPoint: NSMakePoint (0, 0)
  578. fromRect: NSMakeRect (0, 0, [image size].width, [image size].height)
  579. operation: NSCompositingOperationSourceOver fraction: 1.0f];
  580. releaseImageAfterDrawing();
  581. return result;
  582. }
  583. }
  584. static Image createNSWindowSnapshot (NSWindow* nsWindow)
  585. {
  586. JUCE_AUTORELEASEPOOL
  587. {
  588. CGImageRef screenShot = CGWindowListCreateImage (CGRectNull,
  589. kCGWindowListOptionIncludingWindow,
  590. (CGWindowID) [nsWindow windowNumber],
  591. kCGWindowImageBoundsIgnoreFraming);
  592. NSBitmapImageRep* bitmapRep = [[NSBitmapImageRep alloc] initWithCGImage: screenShot];
  593. Image result (Image::ARGB, (int) [bitmapRep size].width, (int) [bitmapRep size].height, true);
  594. selectImageForDrawing (result);
  595. [bitmapRep drawAtPoint: NSMakePoint (0, 0)];
  596. releaseImageAfterDrawing();
  597. [bitmapRep release];
  598. CGImageRelease (screenShot);
  599. return result;
  600. }
  601. }
  602. Image createSnapshotOfNativeWindow (void* nativeWindowHandle)
  603. {
  604. if (id windowOrView = (id) nativeWindowHandle)
  605. {
  606. if ([windowOrView isKindOfClass: [NSWindow class]])
  607. return createNSWindowSnapshot ((NSWindow*) windowOrView);
  608. if ([windowOrView isKindOfClass: [NSView class]])
  609. return createNSWindowSnapshot ([(NSView*) windowOrView window]);
  610. }
  611. return {};
  612. }
  613. //==============================================================================
  614. void SystemClipboard::copyTextToClipboard (const String& text)
  615. {
  616. NSPasteboard* pb = [NSPasteboard generalPasteboard];
  617. [pb declareTypes: [NSArray arrayWithObject: NSPasteboardTypeString]
  618. owner: nil];
  619. [pb setString: juceStringToNS (text)
  620. forType: NSPasteboardTypeString];
  621. }
  622. String SystemClipboard::getTextFromClipboard()
  623. {
  624. return nsStringToJuce ([[NSPasteboard generalPasteboard] stringForType: NSPasteboardTypeString]);
  625. }
  626. void Process::setDockIconVisible (bool isVisible)
  627. {
  628. ProcessSerialNumber psn { 0, kCurrentProcess };
  629. OSStatus err = TransformProcessType (&psn, isVisible ? kProcessTransformToForegroundApplication
  630. : kProcessTransformToUIElementApplication);
  631. jassert (err == 0);
  632. ignoreUnused (err);
  633. }
  634. } // namespace juce