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.

3325 lines
107KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library - "Jules' Utility Class Extensions"
  4. Copyright 2004-7 by Raw Material Software ltd.
  5. ------------------------------------------------------------------------------
  6. JUCE can be redistributed and/or modified under the terms of the
  7. GNU General Public License, as published by the Free Software Foundation;
  8. either version 2 of the License, or (at your option) any later version.
  9. JUCE is distributed in the hope that it will be useful,
  10. but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. GNU General Public License for more details.
  13. You should have received a copy of the GNU General Public License
  14. along with JUCE; if not, visit www.gnu.org/licenses or write to the
  15. Free Software Foundation, Inc., 59 Temple Place, Suite 330,
  16. Boston, MA 02111-1307 USA
  17. ------------------------------------------------------------------------------
  18. If you'd like to release a closed-source product which uses JUCE, commercial
  19. licenses are also available: visit www.rawmaterialsoftware.com/juce for
  20. more information.
  21. ==============================================================================
  22. */
  23. #include "../../../src/juce_core/basics/juce_StandardHeader.h"
  24. #include <Carbon/Carbon.h>
  25. #include <IOKit/IOKitLib.h>
  26. #include <IOKit/IOCFPlugIn.h>
  27. #include <IOKit/hid/IOHIDLib.h>
  28. #include <IOKit/hid/IOHIDKeys.h>
  29. #include <fnmatch.h>
  30. #if JUCE_OPENGL
  31. #include <agl/agl.h>
  32. #endif
  33. BEGIN_JUCE_NAMESPACE
  34. #include "../../../src/juce_appframework/events/juce_Timer.h"
  35. #include "../../../src/juce_appframework/application/juce_DeletedAtShutdown.h"
  36. #include "../../../src/juce_appframework/events/juce_AsyncUpdater.h"
  37. #include "../../../src/juce_appframework/events/juce_MessageManager.h"
  38. #include "../../../src/juce_core/basics/juce_Singleton.h"
  39. #include "../../../src/juce_core/basics/juce_Random.h"
  40. #include "../../../src/juce_core/threads/juce_Process.h"
  41. #include "../../../src/juce_appframework/application/juce_SystemClipboard.h"
  42. #include "../../../src/juce_appframework/gui/components/keyboard/juce_KeyPress.h"
  43. #include "../../../src/juce_appframework/gui/components/windows/juce_AlertWindow.h"
  44. #include "../../../src/juce_appframework/gui/graphics/geometry/juce_RectangleList.h"
  45. #include "../../../src/juce_appframework/gui/graphics/contexts/juce_LowLevelGraphicsSoftwareRenderer.h"
  46. #include "../../../src/juce_appframework/gui/components/juce_Desktop.h"
  47. #include "../../../src/juce_appframework/gui/components/menus/juce_MenuBarModel.h"
  48. #include "../../../src/juce_core/misc/juce_PlatformUtilities.h"
  49. #include "../../../src/juce_appframework/application/juce_Application.h"
  50. #include "../../../src/juce_appframework/gui/components/special/juce_OpenGLComponent.h"
  51. #include "../../../src/juce_appframework/gui/components/mouse/juce_DragAndDropContainer.h"
  52. #include "../../../src/juce_appframework/gui/components/keyboard/juce_KeyPressMappingSet.h"
  53. #include "../../../src/juce_appframework/gui/graphics/imaging/juce_ImageFileFormat.h"
  54. #undef Point
  55. const WindowRegionCode windowRegionToUse = kWindowContentRgn;
  56. static HIObjectClassRef viewClassRef = 0;
  57. static CFStringRef juceHiViewClassNameCFString = 0;
  58. static ComponentPeer* juce_currentMouseTrackingPeer = 0;
  59. //==============================================================================
  60. static VoidArray keysCurrentlyDown;
  61. bool KeyPress::isKeyCurrentlyDown (const int keyCode) throw()
  62. {
  63. if (keysCurrentlyDown.contains ((void*) keyCode))
  64. return true;
  65. if (keyCode >= 'A' && keyCode <= 'Z'
  66. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toLowerCase ((tchar) keyCode)))
  67. return true;
  68. if (keyCode >= 'a' && keyCode <= 'z'
  69. && keysCurrentlyDown.contains ((void*) (int) CharacterFunctions::toUpperCase ((tchar) keyCode)))
  70. return true;
  71. return false;
  72. }
  73. //==============================================================================
  74. static VoidArray minimisedWindows;
  75. static void setWindowMinimised (WindowRef ref, const bool isMinimised)
  76. {
  77. if (isMinimised != minimisedWindows.contains (ref))
  78. CollapseWindow (ref, isMinimised);
  79. }
  80. void juce_maximiseAllMinimisedWindows()
  81. {
  82. const VoidArray minWin (minimisedWindows);
  83. for (int i = minWin.size(); --i >= 0;)
  84. setWindowMinimised ((WindowRef) (minWin[i]), false);
  85. }
  86. //==============================================================================
  87. class HIViewComponentPeer;
  88. static HIViewComponentPeer* currentlyFocusedPeer = 0;
  89. //==============================================================================
  90. static int currentModifiers = 0;
  91. static void updateModifiers (EventRef theEvent)
  92. {
  93. currentModifiers &= ~ (ModifierKeys::shiftModifier | ModifierKeys::ctrlModifier
  94. | ModifierKeys::altModifier | ModifierKeys::commandModifier);
  95. UInt32 m;
  96. if (theEvent != 0)
  97. GetEventParameter (theEvent, kEventParamKeyModifiers, typeUInt32, 0, sizeof(m), 0, &m);
  98. else
  99. m = GetCurrentEventKeyModifiers();
  100. if ((m & (shiftKey | rightShiftKey)) != 0)
  101. currentModifiers |= ModifierKeys::shiftModifier;
  102. if ((m & (controlKey | rightControlKey)) != 0)
  103. currentModifiers |= ModifierKeys::ctrlModifier;
  104. if ((m & (optionKey | rightOptionKey)) != 0)
  105. currentModifiers |= ModifierKeys::altModifier;
  106. if ((m & cmdKey) != 0)
  107. currentModifiers |= ModifierKeys::commandModifier;
  108. }
  109. void ModifierKeys::updateCurrentModifiers()
  110. {
  111. currentModifierFlags = currentModifiers;
  112. }
  113. static int64 getEventTime (EventRef event)
  114. {
  115. const int64 millis = (int64) (1000.0 * (event != 0 ? GetEventTime (event)
  116. : GetCurrentEventTime()));
  117. static int64 offset = 0;
  118. if (offset == 0)
  119. offset = Time::currentTimeMillis() - millis;
  120. return offset + millis;
  121. }
  122. //==============================================================================
  123. class MacBitmapImage : public Image
  124. {
  125. public:
  126. //==============================================================================
  127. CGColorSpaceRef colourspace;
  128. CGDataProviderRef provider;
  129. //==============================================================================
  130. MacBitmapImage (const PixelFormat format_,
  131. const int w, const int h, const bool clearImage)
  132. : Image (format_, w, h)
  133. {
  134. jassert (format_ == RGB || format_ == ARGB);
  135. pixelStride = (format_ == RGB) ? 3 : 4;
  136. lineStride = (w * pixelStride + 3) & ~3;
  137. const int imageSize = lineStride * h;
  138. if (clearImage)
  139. imageData = (uint8*) juce_calloc (imageSize);
  140. else
  141. imageData = (uint8*) juce_malloc (imageSize);
  142. //colourspace = CGColorSpaceCreateWithName (kCGColorSpaceUserRGB);
  143. CMProfileRef prof;
  144. CMGetSystemProfile (&prof);
  145. colourspace = CGColorSpaceCreateWithPlatformColorSpace (prof);
  146. provider = CGDataProviderCreateWithData (0, imageData, h * lineStride, 0);
  147. }
  148. MacBitmapImage::~MacBitmapImage()
  149. {
  150. CGDataProviderRelease (provider);
  151. CGColorSpaceRelease (colourspace);
  152. juce_free (imageData);
  153. imageData = 0; // to stop the base class freeing this
  154. }
  155. void blitToContext (CGContextRef context, const float dx, const float dy)
  156. {
  157. CGImageRef tempImage = CGImageCreate (getWidth(), getHeight(),
  158. 8, pixelStride << 3, lineStride, colourspace,
  159. #if MACOS_10_3_OR_EARLIER || JUCE_BIG_ENDIAN
  160. hasAlphaChannel() ? kCGImageAlphaPremultipliedFirst
  161. : kCGImageAlphaNone,
  162. #else
  163. hasAlphaChannel() ? kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst
  164. : kCGImageAlphaNone,
  165. #endif
  166. provider, 0, false,
  167. kCGRenderingIntentDefault);
  168. HIRect r;
  169. r.origin.x = dx;
  170. r.origin.y = dy;
  171. r.size.width = (float) getWidth();
  172. r.size.height = (float) getHeight();
  173. HIViewDrawCGImage (context, &r, tempImage);
  174. CGImageRelease (tempImage);
  175. }
  176. juce_UseDebuggingNewOperator
  177. };
  178. //==============================================================================
  179. class MouseCheckTimer : private Timer,
  180. private DeletedAtShutdown
  181. {
  182. HIViewComponentPeer* lastPeerUnderMouse;
  183. int lastX, lastY;
  184. public:
  185. MouseCheckTimer()
  186. : lastX (0),
  187. lastY (0)
  188. {
  189. lastPeerUnderMouse = 0;
  190. resetMouseMoveChecker();
  191. }
  192. ~MouseCheckTimer()
  193. {
  194. clearSingletonInstance();
  195. }
  196. juce_DeclareSingleton_SingleThreaded_Minimal (MouseCheckTimer)
  197. bool hasEverHadAMouseMove;
  198. void moved (HIViewComponentPeer* const peer)
  199. {
  200. if (hasEverHadAMouseMove)
  201. startTimer (200);
  202. lastPeerUnderMouse = peer;
  203. }
  204. void resetMouseMoveChecker()
  205. {
  206. hasEverHadAMouseMove = false;
  207. startTimer (1000 / 16);
  208. }
  209. void timerCallback();
  210. };
  211. juce_ImplementSingleton_SingleThreaded (MouseCheckTimer)
  212. //==============================================================================
  213. #if JUCE_QUICKTIME
  214. extern void OfferMouseClickToQuickTime (WindowRef window, ::Point where, long when, long modifiers,
  215. Component* topLevelComp);
  216. #endif
  217. //==============================================================================
  218. class HIViewComponentPeer : public ComponentPeer,
  219. private Timer
  220. {
  221. public:
  222. //==============================================================================
  223. HIViewComponentPeer (Component* const component,
  224. const int windowStyleFlags,
  225. HIViewRef viewToAttachTo)
  226. : ComponentPeer (component, windowStyleFlags),
  227. fullScreen (false),
  228. isCompositingWindow (false),
  229. windowRef (0),
  230. viewRef (0)
  231. {
  232. repainter = new RepaintManager (this);
  233. eventHandlerRef = 0;
  234. if (viewToAttachTo != 0)
  235. {
  236. isSharedWindow = true;
  237. }
  238. else
  239. {
  240. isSharedWindow = false;
  241. WindowRef newWindow = createNewWindow (windowStyleFlags);
  242. GetRootControl (newWindow, (ControlRef*) &viewToAttachTo);
  243. jassert (viewToAttachTo != 0);
  244. HIViewRef growBox = 0;
  245. HIViewFindByID (HIViewGetRoot (newWindow), kHIViewWindowGrowBoxID, &growBox);
  246. if (growBox != 0)
  247. HIGrowBoxViewSetTransparent (growBox, true);
  248. }
  249. createNewHIView();
  250. HIViewAddSubview (viewToAttachTo, viewRef);
  251. HIViewSetVisible (viewRef, component->isVisible());
  252. setTitle (component->getName());
  253. if (component->isVisible() && ! isSharedWindow)
  254. {
  255. ShowWindow (windowRef);
  256. ActivateWindow (windowRef, component->getWantsKeyboardFocus());
  257. }
  258. }
  259. ~HIViewComponentPeer()
  260. {
  261. minimisedWindows.removeValue (windowRef);
  262. if (IsValidWindowPtr (windowRef))
  263. {
  264. if (! isSharedWindow)
  265. {
  266. CFRelease (viewRef);
  267. viewRef = 0;
  268. DisposeWindow (windowRef);
  269. }
  270. else
  271. {
  272. if (eventHandlerRef != 0)
  273. RemoveEventHandler (eventHandlerRef);
  274. CFRelease (viewRef);
  275. viewRef = 0;
  276. }
  277. windowRef = 0;
  278. }
  279. if (currentlyFocusedPeer == this)
  280. currentlyFocusedPeer = 0;
  281. delete repainter;
  282. }
  283. //==============================================================================
  284. void* getNativeHandle() const
  285. {
  286. return windowRef;
  287. }
  288. void setVisible (bool shouldBeVisible)
  289. {
  290. HIViewSetVisible (viewRef, shouldBeVisible);
  291. if ((! isSharedWindow) && IsValidWindowPtr (windowRef))
  292. {
  293. if (shouldBeVisible)
  294. ShowWindow (windowRef);
  295. else
  296. HideWindow (windowRef);
  297. resizeViewToFitWindow();
  298. // If nothing else is focused, then grab the focus too
  299. if (shouldBeVisible
  300. && Component::getCurrentlyFocusedComponent() == 0
  301. && Process::isForegroundProcess())
  302. {
  303. component->toFront (true);
  304. }
  305. }
  306. }
  307. void setTitle (const String& title)
  308. {
  309. if ((! isSharedWindow) && IsValidWindowPtr (windowRef))
  310. {
  311. CFStringRef t = PlatformUtilities::juceStringToCFString (title);
  312. SetWindowTitleWithCFString (windowRef, t);
  313. CFRelease (t);
  314. }
  315. }
  316. void setPosition (int x, int y)
  317. {
  318. if (isSharedWindow)
  319. {
  320. HIViewPlaceInSuperviewAt (viewRef, x, y);
  321. }
  322. else if (IsValidWindowPtr (windowRef))
  323. {
  324. Rect r;
  325. GetWindowBounds (windowRef, windowRegionToUse, &r);
  326. r.right += x - r.left;
  327. r.bottom += y - r.top;
  328. r.left = x;
  329. r.top = y;
  330. SetWindowBounds (windowRef, windowRegionToUse, &r);
  331. }
  332. }
  333. void setSize (int w, int h)
  334. {
  335. w = jmax (0, w);
  336. h = jmax (0, h);
  337. if (w != getComponent()->getWidth()
  338. || h != getComponent()->getHeight())
  339. {
  340. repainter->repaint (0, 0, w, h);
  341. }
  342. if (isSharedWindow)
  343. {
  344. HIRect r;
  345. HIViewGetFrame (viewRef, &r);
  346. r.size.width = (float) w;
  347. r.size.height = (float) h;
  348. HIViewSetFrame (viewRef, &r);
  349. }
  350. else if (IsValidWindowPtr (windowRef))
  351. {
  352. Rect r;
  353. GetWindowBounds (windowRef, windowRegionToUse, &r);
  354. r.right = r.left + w;
  355. r.bottom = r.top + h;
  356. SetWindowBounds (windowRef, windowRegionToUse, &r);
  357. }
  358. }
  359. void setBounds (int x, int y, int w, int h, const bool isNowFullScreen)
  360. {
  361. fullScreen = isNowFullScreen;
  362. w = jmax (0, w);
  363. h = jmax (0, h);
  364. if (w != getComponent()->getWidth()
  365. || h != getComponent()->getHeight())
  366. {
  367. repainter->repaint (0, 0, w, h);
  368. }
  369. if (isSharedWindow)
  370. {
  371. HIRect r;
  372. r.origin.x = (float) x;
  373. r.origin.y = (float) y;
  374. r.size.width = (float) w;
  375. r.size.height = (float) h;
  376. HIViewSetFrame (viewRef, &r);
  377. }
  378. else if (IsValidWindowPtr (windowRef))
  379. {
  380. Rect r;
  381. r.left = x;
  382. r.top = y;
  383. r.right = x + w;
  384. r.bottom = y + h;
  385. SetWindowBounds (windowRef, windowRegionToUse, &r);
  386. }
  387. }
  388. void getBounds (int& x, int& y, int& w, int& h, const bool global) const
  389. {
  390. HIRect hiViewPos;
  391. HIViewGetFrame (viewRef, &hiViewPos);
  392. if (global)
  393. {
  394. HIViewRef content = 0;
  395. HIViewFindByID (HIViewGetRoot (windowRef), kHIViewWindowContentID, &content);
  396. HIPoint p = { 0.0f, 0.0f };
  397. HIViewConvertPoint (&p, viewRef, content);
  398. x = (int) p.x;
  399. y = (int) p.y;
  400. if (IsValidWindowPtr (windowRef))
  401. {
  402. Rect windowPos;
  403. GetWindowBounds (windowRef, kWindowContentRgn, &windowPos);
  404. x += windowPos.left;
  405. y += windowPos.top;
  406. }
  407. }
  408. else
  409. {
  410. x = (int) hiViewPos.origin.x;
  411. y = (int) hiViewPos.origin.y;
  412. }
  413. w = (int) hiViewPos.size.width;
  414. h = (int) hiViewPos.size.height;
  415. }
  416. void getBounds (int& x, int& y, int& w, int& h) const
  417. {
  418. getBounds (x, y, w, h, ! isSharedWindow);
  419. }
  420. int getScreenX() const
  421. {
  422. int x, y, w, h;
  423. getBounds (x, y, w, h, true);
  424. return x;
  425. }
  426. int getScreenY() const
  427. {
  428. int x, y, w, h;
  429. getBounds (x, y, w, h, true);
  430. return y;
  431. }
  432. void relativePositionToGlobal (int& x, int& y)
  433. {
  434. int wx, wy, ww, wh;
  435. getBounds (wx, wy, ww, wh, true);
  436. x += wx;
  437. y += wy;
  438. }
  439. void globalPositionToRelative (int& x, int& y)
  440. {
  441. int wx, wy, ww, wh;
  442. getBounds (wx, wy, ww, wh, true);
  443. x -= wx;
  444. y -= wy;
  445. }
  446. void setMinimised (bool shouldBeMinimised)
  447. {
  448. if (! isSharedWindow)
  449. setWindowMinimised (windowRef, shouldBeMinimised);
  450. }
  451. bool isMinimised() const
  452. {
  453. return minimisedWindows.contains (windowRef);
  454. }
  455. void setFullScreen (bool shouldBeFullScreen)
  456. {
  457. if (! isSharedWindow)
  458. {
  459. setMinimised (false);
  460. if (fullScreen != shouldBeFullScreen)
  461. {
  462. Rectangle r (lastNonFullscreenBounds);
  463. if (shouldBeFullScreen)
  464. r = Desktop::getInstance().getMainMonitorArea();
  465. // (can't call the component's setBounds method because that'll reset our fullscreen flag)
  466. if (r != getComponent()->getBounds() && ! r.isEmpty())
  467. setBounds (r.getX(), r.getY(), r.getWidth(), r.getHeight(), shouldBeFullScreen);
  468. }
  469. }
  470. }
  471. bool isFullScreen() const
  472. {
  473. return fullScreen;
  474. }
  475. bool contains (int x, int y, bool trueIfInAChildWindow) const
  476. {
  477. if (x < 0 || y < 0
  478. || x >= component->getWidth() || y >= component->getHeight()
  479. || ! IsValidWindowPtr (windowRef))
  480. return false;
  481. Rect r;
  482. GetWindowBounds (windowRef, windowRegionToUse, &r);
  483. ::Point p;
  484. p.h = r.left + x;
  485. p.v = r.top + y;
  486. WindowRef ref2 = 0;
  487. FindWindow (p, &ref2);
  488. if (windowRef != ref2)
  489. return false;
  490. if (trueIfInAChildWindow)
  491. return true;
  492. HIPoint p2;
  493. p2.x = (float) x;
  494. p2.y = (float) y;
  495. HIViewRef hit;
  496. HIViewGetSubviewHit (viewRef, &p2, true, &hit);
  497. return hit == 0 || hit == viewRef;
  498. }
  499. const BorderSize getFrameSize() const
  500. {
  501. return BorderSize();
  502. }
  503. bool setAlwaysOnTop (bool alwaysOnTop)
  504. {
  505. // can't do this so return false and let the component create a new window
  506. return false;
  507. }
  508. void toFront (bool makeActiveWindow)
  509. {
  510. makeActiveWindow = makeActiveWindow
  511. && component->isValidComponent()
  512. && (component->getWantsKeyboardFocus()
  513. || component->isCurrentlyModal());
  514. if (windowRef != FrontWindow()
  515. || (makeActiveWindow && ! IsWindowActive (windowRef))
  516. || ! Process::isForegroundProcess())
  517. {
  518. if (! Process::isForegroundProcess())
  519. {
  520. ProcessSerialNumber psn;
  521. GetCurrentProcess (&psn);
  522. SetFrontProcess (&psn);
  523. }
  524. if (IsValidWindowPtr (windowRef))
  525. {
  526. if (makeActiveWindow)
  527. {
  528. SelectWindow (windowRef);
  529. SetUserFocusWindow (windowRef);
  530. HIViewAdvanceFocus (viewRef, 0);
  531. }
  532. else
  533. {
  534. BringToFront (windowRef);
  535. }
  536. handleBroughtToFront();
  537. }
  538. }
  539. }
  540. void toBehind (ComponentPeer* other)
  541. {
  542. HIViewComponentPeer* const otherWindow = dynamic_cast <HIViewComponentPeer*> (other);
  543. if (other != 0 && windowRef != 0 && otherWindow->windowRef != 0)
  544. {
  545. if (windowRef == otherWindow->windowRef)
  546. {
  547. HIViewSetZOrder (viewRef, kHIViewZOrderBelow, otherWindow->viewRef);
  548. }
  549. else
  550. {
  551. SendBehind (windowRef, otherWindow->windowRef);
  552. }
  553. }
  554. }
  555. void setIcon (const Image& /*newIcon*/)
  556. {
  557. // to do..
  558. }
  559. //==============================================================================
  560. void viewFocusGain()
  561. {
  562. const MessageManagerLock messLock;
  563. if (currentlyFocusedPeer != this)
  564. {
  565. if (ComponentPeer::isValidPeer (currentlyFocusedPeer))
  566. currentlyFocusedPeer->handleFocusLoss();
  567. currentlyFocusedPeer = this;
  568. handleFocusGain();
  569. }
  570. }
  571. void viewFocusLoss()
  572. {
  573. if (currentlyFocusedPeer == this)
  574. {
  575. currentlyFocusedPeer = 0;
  576. handleFocusLoss();
  577. }
  578. }
  579. bool isFocused() const
  580. {
  581. return windowRef == GetUserFocusWindow()
  582. && HIViewSubtreeContainsFocus (viewRef);
  583. }
  584. void grabFocus()
  585. {
  586. if ((! isFocused()) && IsValidWindowPtr (windowRef))
  587. {
  588. SetUserFocusWindow (windowRef);
  589. HIViewAdvanceFocus (viewRef, 0);
  590. }
  591. }
  592. //==============================================================================
  593. void repaint (int x, int y, int w, int h)
  594. {
  595. if (Rectangle::intersectRectangles (x, y, w, h,
  596. 0, 0,
  597. getComponent()->getWidth(),
  598. getComponent()->getHeight()))
  599. {
  600. if ((getStyleFlags() & windowRepaintedExplictly) == 0)
  601. {
  602. if (isCompositingWindow)
  603. {
  604. #if MACOS_10_3_OR_EARLIER
  605. RgnHandle rgn = NewRgn();
  606. SetRectRgn (rgn, x, y, x + w, y + h);
  607. HIViewSetNeedsDisplayInRegion (viewRef, rgn, true);
  608. DisposeRgn (rgn);
  609. #else
  610. HIRect r;
  611. r.origin.x = x;
  612. r.origin.y = y;
  613. r.size.width = w;
  614. r.size.height = h;
  615. HIViewSetNeedsDisplayInRect (viewRef, &r, true);
  616. #endif
  617. }
  618. else
  619. {
  620. if (! isTimerRunning())
  621. startTimer (20);
  622. }
  623. }
  624. repainter->repaint (x, y, w, h);
  625. }
  626. }
  627. void timerCallback()
  628. {
  629. performAnyPendingRepaintsNow();
  630. }
  631. void performAnyPendingRepaintsNow()
  632. {
  633. stopTimer();
  634. if (component->isVisible())
  635. {
  636. #if MACOS_10_2_OR_EARLIER
  637. if (! isCompositingWindow)
  638. {
  639. Rect w;
  640. GetWindowBounds (windowRef, windowRegionToUse, &w);
  641. RgnHandle rgn = NewRgn();
  642. SetRectRgn (rgn, 0, 0, w.right - w.left, w.bottom - w.top);
  643. UpdateControls (windowRef, rgn);
  644. DisposeRgn (rgn);
  645. }
  646. else
  647. {
  648. EventRef theEvent;
  649. EventTypeSpec eventTypes[1];
  650. eventTypes[0].eventClass = kEventClassControl;
  651. eventTypes[0].eventKind = kEventControlDraw;
  652. int n = 3;
  653. while (--n >= 0
  654. && ReceiveNextEvent (1, eventTypes, kEventDurationNoWait, true, &theEvent) == noErr)
  655. {
  656. if (GetEventClass (theEvent) == kEventClassAppleEvent)
  657. {
  658. EventRecord eventRec;
  659. if (ConvertEventRefToEventRecord (theEvent, &eventRec))
  660. AEProcessAppleEvent (&eventRec);
  661. }
  662. else
  663. {
  664. EventTargetRef theTarget = GetEventDispatcherTarget();
  665. SendEventToEventTarget (theEvent, theTarget);
  666. }
  667. ReleaseEvent (theEvent);
  668. }
  669. }
  670. #else
  671. HIViewRender (viewRef);
  672. #endif
  673. }
  674. }
  675. //==============================================================================
  676. juce_UseDebuggingNewOperator
  677. WindowRef windowRef;
  678. HIViewRef viewRef;
  679. private:
  680. EventHandlerRef eventHandlerRef;
  681. bool fullScreen, isSharedWindow, isCompositingWindow;
  682. //==============================================================================
  683. class RepaintManager : public Timer
  684. {
  685. public:
  686. RepaintManager (HIViewComponentPeer* const peer_)
  687. : peer (peer_),
  688. image (0)
  689. {
  690. }
  691. ~RepaintManager()
  692. {
  693. delete image;
  694. }
  695. void timerCallback()
  696. {
  697. stopTimer();
  698. deleteAndZero (image);
  699. }
  700. void repaint (int x, int y, int w, int h)
  701. {
  702. regionsNeedingRepaint.add (x, y, w, h);
  703. }
  704. void repaintAnyRemainingRegions()
  705. {
  706. // if any regions have been invaldated during the paint callback,
  707. // we need to repaint them explicitly because the mac throws this
  708. // stuff away
  709. for (RectangleList::Iterator i (regionsNeedingRepaint); i.next();)
  710. {
  711. const Rectangle& r = *i.getRectangle();
  712. peer->repaint (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  713. }
  714. }
  715. void paint (CGContextRef cgContext, int x, int y, int w, int h)
  716. {
  717. if (w > 0 && h > 0)
  718. {
  719. bool refresh = false;
  720. int imW = image != 0 ? image->getWidth() : 0;
  721. int imH = image != 0 ? image->getHeight() : 0;
  722. if (imW < w || imH < h)
  723. {
  724. imW = jmin (peer->getComponent()->getWidth(), (w + 31) & ~31);
  725. imH = jmin (peer->getComponent()->getHeight(), (h + 31) & ~31);
  726. delete image;
  727. image = new MacBitmapImage (peer->getComponent()->isOpaque() ? Image::RGB
  728. : Image::ARGB,
  729. imW, imH, false);
  730. refresh = true;
  731. }
  732. else if (imageX > x || imageY > y
  733. || imageX + imW < x + w
  734. || imageY + imH < y + h)
  735. {
  736. refresh = true;
  737. }
  738. if (refresh)
  739. {
  740. regionsNeedingRepaint.clear();
  741. regionsNeedingRepaint.addWithoutMerging (Rectangle (x, y, imW, imH));
  742. imageX = x;
  743. imageY = y;
  744. }
  745. LowLevelGraphicsSoftwareRenderer context (*image);
  746. context.setOrigin (-imageX, -imageY);
  747. if (context.reduceClipRegion (regionsNeedingRepaint))
  748. {
  749. regionsNeedingRepaint.clear();
  750. if (! peer->getComponent()->isOpaque())
  751. {
  752. for (RectangleList::Iterator i (*context.getRawClipRegion()); i.next();)
  753. {
  754. const Rectangle& r = *i.getRectangle();
  755. image->clear (r.getX(), r.getY(), r.getWidth(), r.getHeight());
  756. }
  757. }
  758. regionsNeedingRepaint.clear();
  759. peer->clearMaskedRegion();
  760. peer->handlePaint (context);
  761. }
  762. else
  763. {
  764. regionsNeedingRepaint.clear();
  765. }
  766. if (! peer->maskedRegion.isEmpty())
  767. {
  768. RectangleList total (Rectangle (x, y, w, h));
  769. total.subtract (peer->maskedRegion);
  770. CGRect* rects = (CGRect*) juce_malloc (sizeof (CGRect) * total.getNumRectangles());
  771. int n = 0;
  772. for (RectangleList::Iterator i (total); i.next();)
  773. {
  774. const Rectangle& r = *i.getRectangle();
  775. rects[n].origin.x = (int) r.getX();
  776. rects[n].origin.y = (int) r.getY();
  777. rects[n].size.width = roundFloatToInt (r.getWidth());
  778. rects[n++].size.height = roundFloatToInt (r.getHeight());
  779. }
  780. CGContextClipToRects (cgContext, rects, n);
  781. juce_free (rects);
  782. }
  783. if (peer->isSharedWindow)
  784. {
  785. CGRect clip;
  786. clip.origin.x = x;
  787. clip.origin.y = y;
  788. clip.size.width = jmin (w, peer->getComponent()->getWidth() - x);
  789. clip.size.height = jmin (h, peer->getComponent()->getHeight() - y);
  790. CGContextClipToRect (cgContext, clip);
  791. }
  792. image->blitToContext (cgContext, imageX, imageY);
  793. }
  794. startTimer (3000);
  795. }
  796. private:
  797. HIViewComponentPeer* const peer;
  798. MacBitmapImage* image;
  799. int imageX, imageY;
  800. RectangleList regionsNeedingRepaint;
  801. RepaintManager (const RepaintManager&);
  802. const RepaintManager& operator= (const RepaintManager&);
  803. };
  804. RepaintManager* repainter;
  805. friend class RepaintManager;
  806. //==============================================================================
  807. static OSStatus handleFrameRepaintEvent (EventHandlerCallRef myHandler,
  808. EventRef theEvent,
  809. void* userData)
  810. {
  811. // don't draw the frame..
  812. return noErr;
  813. }
  814. //==============================================================================
  815. OSStatus handleWindowClassEvent (EventRef theEvent)
  816. {
  817. switch (GetEventKind (theEvent))
  818. {
  819. case kEventWindowBoundsChanged:
  820. resizeViewToFitWindow();
  821. break; // allow other handlers in the event chain to also get a look at the events
  822. case kEventWindowBoundsChanging:
  823. if ((styleFlags & (windowIsResizable | windowHasTitleBar)) == (windowIsResizable | windowHasTitleBar))
  824. {
  825. UInt32 atts = 0;
  826. GetEventParameter (theEvent, kEventParamAttributes, typeUInt32,
  827. 0, sizeof (UInt32), 0, &atts);
  828. if ((atts & (kWindowBoundsChangeUserDrag | kWindowBoundsChangeUserResize)) != 0)
  829. {
  830. if (component->isCurrentlyBlockedByAnotherModalComponent())
  831. {
  832. Component* const modal = Component::getCurrentlyModalComponent();
  833. if (modal != 0)
  834. modal->inputAttemptWhenModal();
  835. }
  836. if ((atts & kWindowBoundsChangeUserResize) != 0
  837. && constrainer != 0 && ! isSharedWindow)
  838. {
  839. Rect current;
  840. GetEventParameter (theEvent, kEventParamCurrentBounds, typeQDRectangle,
  841. 0, sizeof (Rect), 0, &current);
  842. int x = current.left;
  843. int y = current.top;
  844. int w = current.right - current.left;
  845. int h = current.bottom - current.top;
  846. const Rectangle currentRect (getComponent()->getBounds());
  847. constrainer->checkBounds (x, y, w, h, currentRect,
  848. Desktop::getInstance().getAllMonitorDisplayAreas().getBounds(),
  849. y != currentRect.getY() && y + h == currentRect.getBottom(),
  850. x != currentRect.getX() && x + w == currentRect.getRight(),
  851. y == currentRect.getY() && y + h != currentRect.getBottom(),
  852. x == currentRect.getX() && x + w != currentRect.getRight());
  853. current.left = x;
  854. current.top = y;
  855. current.right = x + w;
  856. current.bottom = y + h;
  857. SetEventParameter (theEvent, kEventParamCurrentBounds, typeQDRectangle,
  858. sizeof (Rect), &current);
  859. return noErr;
  860. }
  861. }
  862. }
  863. break;
  864. case kEventWindowFocusAcquired:
  865. keysCurrentlyDown.clear();
  866. if ((! isSharedWindow) || HIViewSubtreeContainsFocus (viewRef))
  867. viewFocusGain();
  868. break; // allow other handlers in the event chain to also get a look at the events
  869. case kEventWindowFocusRelinquish:
  870. keysCurrentlyDown.clear();
  871. viewFocusLoss();
  872. break; // allow other handlers in the event chain to also get a look at the events
  873. case kEventWindowCollapsed:
  874. minimisedWindows.addIfNotAlreadyThere (windowRef);
  875. handleMovedOrResized();
  876. break; // allow other handlers in the event chain to also get a look at the events
  877. case kEventWindowExpanded:
  878. minimisedWindows.removeValue (windowRef);
  879. handleMovedOrResized();
  880. break; // allow other handlers in the event chain to also get a look at the events
  881. case kEventWindowShown:
  882. break; // allow other handlers in the event chain to also get a look at the events
  883. case kEventWindowClose:
  884. if (isSharedWindow)
  885. break; // break to let the OS delete the window
  886. handleUserClosingWindow();
  887. return noErr; // avoids letting the OS to delete the window, we'll do that ourselves.
  888. default:
  889. break;
  890. }
  891. return eventNotHandledErr;
  892. }
  893. OSStatus handleKeyEvent (EventRef theEvent, juce_wchar textCharacter)
  894. {
  895. updateModifiers (theEvent);
  896. UniChar unicodeChars [4];
  897. zeromem (unicodeChars, sizeof (unicodeChars));
  898. GetEventParameter (theEvent, kEventParamKeyUnicodes, typeUnicodeText, 0, sizeof (unicodeChars), 0, unicodeChars);
  899. int keyCode = (int) (unsigned int) unicodeChars[0];
  900. UInt32 rawKey = 0;
  901. GetEventParameter (theEvent, kEventParamKeyCode, typeUInt32, 0, sizeof (UInt32), 0, &rawKey);
  902. if ((currentModifiers & ModifierKeys::ctrlModifier) != 0)
  903. {
  904. if (keyCode >= 1 && keyCode <= 26)
  905. keyCode += ('A' - 1);
  906. }
  907. static const int keyTranslations[] =
  908. {
  909. 0, 's', 'd', 'f', 'h', 'g', 'z', 'x', 'c', 'v', 0xa7, 'b',
  910. 'q', 'w', 'e', 'r', 'y', 't', '1', '2', '3', '4', '6', '5',
  911. '=', '9', '7', '-', '8', '0', ']', 'o', 'u', '[', 'i', 'p',
  912. KeyPress::returnKey, 'l', 'j', '\'', 'k', ';', '\\', ',', '/',
  913. 'n', 'm', '.', 0, KeyPress::spaceKey, '`', KeyPress::backspaceKey, 0, 0, 0, 0,
  914. 0, 0, 0, 0, 0, 0, 0, 0, 0, KeyPress::numberPadDecimalPoint,
  915. 0, KeyPress::numberPadMultiply, 0, KeyPress::numberPadAdd,
  916. 0, KeyPress::numberPadDelete, 0, 0, 0, KeyPress::numberPadDivide, KeyPress::returnKey,
  917. 0, KeyPress::numberPadSubtract, 0, 0, KeyPress::numberPadEquals, KeyPress::numberPad0,
  918. KeyPress::numberPad1, KeyPress::numberPad2, KeyPress::numberPad3,
  919. KeyPress::numberPad4, KeyPress::numberPad5, KeyPress::numberPad6,
  920. KeyPress::numberPad7, 0, KeyPress::numberPad8, KeyPress::numberPad9,
  921. 0, 0, 0, KeyPress::F5Key, KeyPress::F6Key, KeyPress::F7Key, KeyPress::F3Key,
  922. KeyPress::F8Key, KeyPress::F9Key, 0, KeyPress::F11Key, 0, KeyPress::F13Key,
  923. KeyPress::F16Key, KeyPress::F14Key, 0, KeyPress::F10Key, 0, KeyPress::F12Key,
  924. 0, KeyPress::F15Key, 0, KeyPress::homeKey, KeyPress::pageUpKey, 0, KeyPress::F4Key,
  925. KeyPress::endKey, KeyPress::F2Key, KeyPress::pageDownKey, KeyPress::F1Key,
  926. KeyPress::leftKey, KeyPress::rightKey, KeyPress::downKey, KeyPress::upKey, 0
  927. };
  928. if (rawKey > 0 && rawKey < numElementsInArray (keyTranslations))
  929. keyCode = keyTranslations [rawKey];
  930. else if (rawKey == 0 && textCharacter != 0)
  931. keyCode = 'a';
  932. if ((currentModifiers & (ModifierKeys::commandModifier | ModifierKeys::ctrlModifier)) != 0)
  933. textCharacter = 0;
  934. static juce_wchar lastTextCharacter = 0;
  935. switch (GetEventKind (theEvent))
  936. {
  937. case kEventRawKeyDown:
  938. {
  939. keysCurrentlyDown.addIfNotAlreadyThere ((void*) keyCode);
  940. lastTextCharacter = textCharacter;
  941. const bool used1 = handleKeyUpOrDown();
  942. const bool used2 = handleKeyPress (keyCode, textCharacter);
  943. if (used1 || used2)
  944. return noErr;
  945. break;
  946. }
  947. case kEventRawKeyUp:
  948. keysCurrentlyDown.removeValue ((void*) keyCode);
  949. lastTextCharacter = 0;
  950. if (handleKeyUpOrDown())
  951. return noErr;
  952. break;
  953. case kEventRawKeyRepeat:
  954. if (handleKeyPress (keyCode, lastTextCharacter))
  955. return noErr;
  956. break;
  957. case kEventRawKeyModifiersChanged:
  958. handleModifierKeysChange();
  959. break;
  960. default:
  961. jassertfalse
  962. break;
  963. }
  964. return eventNotHandledErr;
  965. }
  966. OSStatus handleTextInputEvent (EventRef theEvent)
  967. {
  968. UniChar uc;
  969. GetEventParameter (theEvent, kEventParamTextInputSendText, typeUnicodeText, 0, sizeof (uc), 0, &uc);
  970. EventRef originalEvent;
  971. GetEventParameter (theEvent, kEventParamTextInputSendKeyboardEvent, typeEventRef, 0, sizeof (originalEvent), 0, &originalEvent);
  972. return handleKeyEvent (originalEvent, (juce_wchar) uc);
  973. }
  974. OSStatus handleMouseEvent (EventHandlerCallRef callRef, EventRef theEvent)
  975. {
  976. MouseCheckTimer::getInstance()->moved (this);
  977. ::Point where;
  978. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof (::Point), 0, &where);
  979. int x = where.h;
  980. int y = where.v;
  981. globalPositionToRelative (x, y);
  982. int64 time = getEventTime (theEvent);
  983. switch (GetEventKind (theEvent))
  984. {
  985. case kEventMouseMoved:
  986. MouseCheckTimer::getInstance()->hasEverHadAMouseMove = true;
  987. updateModifiers (theEvent);
  988. handleMouseMove (x, y, time);
  989. break;
  990. case kEventMouseDragged:
  991. updateModifiers (theEvent);
  992. handleMouseDrag (x, y, time);
  993. break;
  994. case kEventMouseDown:
  995. {
  996. if (! Process::isForegroundProcess())
  997. {
  998. ProcessSerialNumber psn;
  999. GetCurrentProcess (&psn);
  1000. SetFrontProcess (&psn);
  1001. toFront (true);
  1002. }
  1003. #if JUCE_QUICKTIME
  1004. {
  1005. long mods;
  1006. GetEventParameter (theEvent, kEventParamKeyModifiers, typeUInt32, 0, sizeof (mods), 0, &mods);
  1007. ::Point where;
  1008. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof (::Point), 0, &where);
  1009. OfferMouseClickToQuickTime (windowRef, where, EventTimeToTicks (GetEventTime (theEvent)), mods, component);
  1010. }
  1011. #endif
  1012. if (component->isBroughtToFrontOnMouseClick()
  1013. && ! component->isCurrentlyBlockedByAnotherModalComponent())
  1014. {
  1015. //ActivateWindow (windowRef, true);
  1016. SelectWindow (windowRef);
  1017. }
  1018. EventMouseButton button;
  1019. GetEventParameter (theEvent, kEventParamMouseButton, typeMouseButton, 0, sizeof (EventMouseButton), 0, &button);
  1020. // need to clear all these flags because sometimes the mac can swallow (right) mouse-up events and
  1021. // this makes a button get stuck down. Since there's no other way to tell what buttons are down,
  1022. // this is all I can think of doing about it..
  1023. currentModifiers &= ~(ModifierKeys::leftButtonModifier | ModifierKeys::rightButtonModifier | ModifierKeys::middleButtonModifier);
  1024. if (button == kEventMouseButtonPrimary)
  1025. currentModifiers |= ModifierKeys::leftButtonModifier;
  1026. else if (button == kEventMouseButtonSecondary)
  1027. currentModifiers |= ModifierKeys::rightButtonModifier;
  1028. else if (button == kEventMouseButtonTertiary)
  1029. currentModifiers |= ModifierKeys::middleButtonModifier;
  1030. updateModifiers (theEvent);
  1031. juce_currentMouseTrackingPeer = this; // puts the message dispatcher into mouse-tracking mode..
  1032. handleMouseDown (x, y, time);
  1033. break;
  1034. }
  1035. case kEventMouseUp:
  1036. {
  1037. const int oldModifiers = currentModifiers;
  1038. EventMouseButton button;
  1039. GetEventParameter (theEvent, kEventParamMouseButton, typeMouseButton, 0, sizeof (EventMouseButton), 0, &button);
  1040. if (button == kEventMouseButtonPrimary)
  1041. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  1042. else if (button == kEventMouseButtonSecondary)
  1043. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  1044. updateModifiers (theEvent);
  1045. juce_currentMouseTrackingPeer = 0;
  1046. handleMouseUp (oldModifiers, x, y, time);
  1047. break;
  1048. }
  1049. case kEventMouseWheelMoved:
  1050. {
  1051. EventMouseWheelAxis axis;
  1052. GetEventParameter (theEvent, kEventParamMouseWheelAxis, typeMouseWheelAxis, 0, sizeof (axis), 0, &axis);
  1053. SInt32 delta;
  1054. GetEventParameter (theEvent, kEventParamMouseWheelDelta,
  1055. typeLongInteger, 0, sizeof (delta), 0, &delta);
  1056. updateModifiers (theEvent);
  1057. handleMouseWheel (axis == kEventMouseWheelAxisX ? delta * 10 : 0,
  1058. axis == kEventMouseWheelAxisX ? 0 : delta * 10,
  1059. time);
  1060. break;
  1061. }
  1062. }
  1063. return noErr;
  1064. }
  1065. OSStatus handleDragAndDrop (EventRef theEvent)
  1066. {
  1067. DragRef dragRef;
  1068. if (GetEventParameter (theEvent, kEventParamDragRef, typeDragRef, 0, sizeof (dragRef), 0, &dragRef) == noErr)
  1069. {
  1070. int mx, my;
  1071. component->getMouseXYRelative (mx, my);
  1072. UInt16 numItems = 0;
  1073. if (CountDragItems (dragRef, &numItems) == noErr)
  1074. {
  1075. StringArray filenames;
  1076. for (int i = 0; i < (int) numItems; ++i)
  1077. {
  1078. DragItemRef ref;
  1079. if (GetDragItemReferenceNumber (dragRef, i + 1, &ref) == noErr)
  1080. {
  1081. const FlavorType flavorType = kDragFlavorTypeHFS;
  1082. Size size = 0;
  1083. if (GetFlavorDataSize (dragRef, ref, flavorType, &size) == noErr)
  1084. {
  1085. void* data = juce_calloc (size);
  1086. if (GetFlavorData (dragRef, ref, flavorType, data, &size, 0) == noErr)
  1087. {
  1088. HFSFlavor* f = (HFSFlavor*) data;
  1089. FSRef fsref;
  1090. if (FSpMakeFSRef (&f->fileSpec, &fsref) == noErr)
  1091. {
  1092. const String path (PlatformUtilities::makePathFromFSRef (&fsref));
  1093. if (path.isNotEmpty())
  1094. filenames.add (path);
  1095. }
  1096. }
  1097. juce_free (data);
  1098. }
  1099. }
  1100. }
  1101. filenames.trim();
  1102. filenames.removeEmptyStrings();
  1103. if (filenames.size() > 0)
  1104. handleFilesDropped (mx, my, filenames);
  1105. }
  1106. }
  1107. return noErr;
  1108. }
  1109. void resizeViewToFitWindow()
  1110. {
  1111. HIRect r;
  1112. if (isSharedWindow)
  1113. {
  1114. HIViewGetFrame (viewRef, &r);
  1115. r.size.width = (float) component->getWidth();
  1116. r.size.height = (float) component->getHeight();
  1117. }
  1118. else
  1119. {
  1120. r.origin.x = 0;
  1121. r.origin.y = 0;
  1122. Rect w;
  1123. GetWindowBounds (windowRef, windowRegionToUse, &w);
  1124. r.size.width = (float) (w.right - w.left);
  1125. r.size.height = (float) (w.bottom - w.top);
  1126. }
  1127. HIViewSetFrame (viewRef, &r);
  1128. #if MACOS_10_3_OR_EARLIER
  1129. component->repaint();
  1130. #endif
  1131. }
  1132. OSStatus hiViewDraw (EventRef theEvent)
  1133. {
  1134. CGContextRef context = 0;
  1135. GetEventParameter (theEvent, kEventParamCGContextRef, typeCGContextRef, 0, sizeof (CGContextRef), 0, &context);
  1136. CGrafPtr oldPort;
  1137. CGrafPtr port = 0;
  1138. if (context == 0)
  1139. {
  1140. GetEventParameter (theEvent, kEventParamGrafPort, typeGrafPtr, 0, sizeof (CGrafPtr), 0, &port);
  1141. GetPort (&oldPort);
  1142. SetPort (port);
  1143. if (port != 0)
  1144. QDBeginCGContext (port, &context);
  1145. if (! isCompositingWindow)
  1146. {
  1147. Rect bounds;
  1148. GetWindowBounds (windowRef, windowRegionToUse, &bounds);
  1149. CGContextTranslateCTM (context, 0, bounds.bottom - bounds.top);
  1150. CGContextScaleCTM (context, 1.0, -1.0);
  1151. }
  1152. if (isSharedWindow)
  1153. {
  1154. // NB - Had terrible problems trying to correctly get the position
  1155. // of this view relative to the window, and this seems wrong, but
  1156. // works better than any other method I've tried..
  1157. HIRect hiViewPos;
  1158. HIViewGetFrame (viewRef, &hiViewPos);
  1159. CGContextTranslateCTM (context, hiViewPos.origin.x, hiViewPos.origin.y);
  1160. }
  1161. }
  1162. #if MACOS_10_2_OR_EARLIER
  1163. RgnHandle rgn = 0;
  1164. GetEventParameter (theEvent, kEventParamRgnHandle, typeQDRgnHandle, 0, sizeof (RgnHandle), 0, &rgn);
  1165. CGRect clip;
  1166. if (rgn != 0)
  1167. {
  1168. Rect bounds;
  1169. GetRegionBounds (rgn, &bounds);
  1170. clip.origin.x = bounds.left;
  1171. clip.origin.y = bounds.top;
  1172. clip.size.width = bounds.right - bounds.left;
  1173. clip.size.height = bounds.bottom - bounds.top;
  1174. }
  1175. else
  1176. {
  1177. HIViewGetBounds (viewRef, &clip);
  1178. }
  1179. #else
  1180. CGRect clip (CGContextGetClipBoundingBox (context));
  1181. #endif
  1182. clip = CGRectIntegral (clip);
  1183. if (clip.origin.x < 0)
  1184. {
  1185. clip.size.width += clip.origin.x;
  1186. clip.origin.x = 0;
  1187. }
  1188. if (clip.origin.y < 0)
  1189. {
  1190. clip.size.height += clip.origin.y;
  1191. clip.origin.y = 0;
  1192. }
  1193. if (! component->isOpaque())
  1194. CGContextClearRect (context, clip);
  1195. repainter->paint (context,
  1196. (int) clip.origin.x, (int) clip.origin.y,
  1197. (int) clip.size.width, (int) clip.size.height);
  1198. if (port != 0)
  1199. {
  1200. CGContextFlush (context);
  1201. QDEndCGContext (port, &context);
  1202. SetPort (oldPort);
  1203. }
  1204. repainter->repaintAnyRemainingRegions();
  1205. return noErr;
  1206. }
  1207. static pascal OSStatus handleWindowEvent (EventHandlerCallRef callRef, EventRef theEvent, void* userData)
  1208. {
  1209. MessageManager::delayWaitCursor();
  1210. HIViewComponentPeer* const peer = (HIViewComponentPeer*) userData;
  1211. const MessageManagerLock messLock;
  1212. if (ComponentPeer::isValidPeer (peer))
  1213. return peer->handleWindowEventForPeer (callRef, theEvent);
  1214. return eventNotHandledErr;
  1215. }
  1216. OSStatus handleWindowEventForPeer (EventHandlerCallRef callRef, EventRef theEvent)
  1217. {
  1218. switch (GetEventClass (theEvent))
  1219. {
  1220. case kEventClassMouse:
  1221. {
  1222. static HIViewComponentPeer* lastMouseDownPeer = 0;
  1223. const UInt32 eventKind = GetEventKind (theEvent);
  1224. HIViewRef view = 0;
  1225. if (eventKind == kEventMouseDragged)
  1226. {
  1227. view = viewRef;
  1228. }
  1229. else
  1230. {
  1231. HIViewGetViewForMouseEvent (HIViewGetRoot (windowRef), theEvent, &view);
  1232. if (view != viewRef)
  1233. {
  1234. if ((eventKind == kEventMouseUp
  1235. || eventKind == kEventMouseExited)
  1236. && ComponentPeer::isValidPeer (lastMouseDownPeer))
  1237. {
  1238. return lastMouseDownPeer->handleMouseEvent (callRef, theEvent);
  1239. }
  1240. return eventNotHandledErr;
  1241. }
  1242. }
  1243. if (eventKind == kEventMouseDown
  1244. || eventKind == kEventMouseDragged
  1245. || eventKind == kEventMouseEntered)
  1246. {
  1247. lastMouseDownPeer = this;
  1248. }
  1249. return handleMouseEvent (callRef, theEvent);
  1250. }
  1251. break;
  1252. case kEventClassWindow:
  1253. return handleWindowClassEvent (theEvent);
  1254. case kEventClassKeyboard:
  1255. if (isFocused())
  1256. return handleKeyEvent (theEvent, 0);
  1257. break;
  1258. case kEventClassTextInput:
  1259. if (isFocused())
  1260. return handleTextInputEvent (theEvent);
  1261. break;
  1262. default:
  1263. break;
  1264. }
  1265. return eventNotHandledErr;
  1266. }
  1267. static pascal OSStatus hiViewEventHandler (EventHandlerCallRef myHandler, EventRef theEvent, void* userData)
  1268. {
  1269. MessageManager::delayWaitCursor();
  1270. const UInt32 eventKind = GetEventKind (theEvent);
  1271. const UInt32 eventClass = GetEventClass (theEvent);
  1272. if (eventClass == kEventClassHIObject)
  1273. {
  1274. switch (eventKind)
  1275. {
  1276. case kEventHIObjectConstruct:
  1277. {
  1278. void* data = juce_calloc (sizeof (void*));
  1279. SetEventParameter (theEvent, kEventParamHIObjectInstance,
  1280. typeVoidPtr, sizeof (void*), &data);
  1281. return noErr;
  1282. }
  1283. case kEventHIObjectInitialize:
  1284. GetEventParameter (theEvent, 'peer', typeVoidPtr, 0, sizeof (void*), 0, (void**) userData);
  1285. return noErr;
  1286. case kEventHIObjectDestruct:
  1287. juce_free (userData);
  1288. return noErr;
  1289. default:
  1290. break;
  1291. }
  1292. }
  1293. else if (eventClass == kEventClassControl)
  1294. {
  1295. HIViewComponentPeer* const peer = *(HIViewComponentPeer**) userData;
  1296. const MessageManagerLock messLock;
  1297. if (! ComponentPeer::isValidPeer (peer))
  1298. return eventNotHandledErr;
  1299. switch (eventKind)
  1300. {
  1301. case kEventControlDraw:
  1302. return peer->hiViewDraw (theEvent);
  1303. case kEventControlBoundsChanged:
  1304. {
  1305. HIRect bounds;
  1306. HIViewGetBounds (peer->viewRef, &bounds);
  1307. peer->repaint (0, 0, roundFloatToInt (bounds.size.width), roundFloatToInt (bounds.size.height));
  1308. peer->handleMovedOrResized();
  1309. return noErr;
  1310. }
  1311. case kEventControlHitTest:
  1312. {
  1313. HIPoint where;
  1314. GetEventParameter (theEvent, kEventParamMouseLocation, typeHIPoint, 0, sizeof (HIPoint), 0, &where);
  1315. HIRect bounds;
  1316. HIViewGetBounds (peer->viewRef, &bounds);
  1317. ControlPartCode part = kControlNoPart;
  1318. if (CGRectContainsPoint (bounds, where))
  1319. part = 1;
  1320. SetEventParameter (theEvent, kEventParamControlPart, typeControlPartCode, sizeof (ControlPartCode), &part);
  1321. return noErr;
  1322. }
  1323. break;
  1324. case kEventControlSetFocusPart:
  1325. {
  1326. ControlPartCode desiredFocus;
  1327. if (GetEventParameter (theEvent, kEventParamControlPart, typeControlPartCode, 0, sizeof (ControlPartCode), 0, &desiredFocus) != noErr)
  1328. break;
  1329. if (desiredFocus == kControlNoPart)
  1330. peer->viewFocusLoss();
  1331. else
  1332. peer->viewFocusGain();
  1333. return noErr;
  1334. }
  1335. break;
  1336. case kEventControlDragEnter:
  1337. {
  1338. #if MACOS_10_2_OR_EARLIER
  1339. enum { kEventParamControlWouldAcceptDrop = 'cldg' };
  1340. #endif
  1341. Boolean accept = true;
  1342. SetEventParameter (theEvent, kEventParamControlWouldAcceptDrop, typeBoolean, sizeof (accept), &accept);
  1343. return noErr;
  1344. }
  1345. case kEventControlDragWithin:
  1346. return noErr;
  1347. case kEventControlDragReceive:
  1348. return peer->handleDragAndDrop (theEvent);
  1349. case kEventControlOwningWindowChanged:
  1350. return peer->ownerWindowChanged (theEvent);
  1351. #if ! MACOS_10_2_OR_EARLIER
  1352. case kEventControlGetFrameMetrics:
  1353. {
  1354. CallNextEventHandler (myHandler, theEvent);
  1355. HIViewFrameMetrics metrics;
  1356. GetEventParameter (theEvent, kEventParamControlFrameMetrics, typeControlFrameMetrics, 0, sizeof (metrics), 0, &metrics);
  1357. metrics.top = metrics.bottom = 0;
  1358. SetEventParameter (theEvent, kEventParamControlFrameMetrics, typeControlFrameMetrics, sizeof (metrics), &metrics);
  1359. return noErr;
  1360. }
  1361. #endif
  1362. case kEventControlInitialize:
  1363. {
  1364. UInt32 features = kControlSupportsDragAndDrop
  1365. | kControlSupportsFocus
  1366. | kControlHandlesTracking
  1367. | kControlSupportsEmbedding
  1368. | (1 << 8) /*kHIViewFeatureGetsFocusOnClick*/;
  1369. SetEventParameter (theEvent, kEventParamControlFeatures, typeUInt32, sizeof (UInt32), &features);
  1370. return noErr;
  1371. }
  1372. default:
  1373. break;
  1374. }
  1375. }
  1376. return eventNotHandledErr;
  1377. }
  1378. WindowRef createNewWindow (const int windowStyleFlags)
  1379. {
  1380. jassert (windowRef == 0);
  1381. static ToolboxObjectClassRef customWindowClass = 0;
  1382. if (customWindowClass == 0)
  1383. {
  1384. // Register our window class
  1385. const EventTypeSpec customTypes[] = { { kEventClassWindow, kEventWindowDrawFrame } };
  1386. UnsignedWide t;
  1387. Microseconds (&t);
  1388. const String randomString ((int) (t.lo & 0x7ffffff));
  1389. const String juceWindowClassName (T("JUCEWindowClass_") + randomString);
  1390. CFStringRef juceWindowClassNameCFString = PlatformUtilities::juceStringToCFString (juceWindowClassName);
  1391. RegisterToolboxObjectClass (juceWindowClassNameCFString,
  1392. 0, 1, customTypes,
  1393. NewEventHandlerUPP (handleFrameRepaintEvent),
  1394. 0, &customWindowClass);
  1395. CFRelease (juceWindowClassNameCFString);
  1396. }
  1397. Rect pos;
  1398. pos.left = getComponent()->getX();
  1399. pos.top = getComponent()->getY();
  1400. pos.right = getComponent()->getRight();
  1401. pos.bottom = getComponent()->getBottom();
  1402. int attributes = kWindowStandardHandlerAttribute | kWindowCompositingAttribute;
  1403. if ((windowStyleFlags & windowHasDropShadow) == 0)
  1404. attributes |= kWindowNoShadowAttribute;
  1405. if ((windowStyleFlags & windowIgnoresMouseClicks) != 0)
  1406. attributes |= kWindowIgnoreClicksAttribute;
  1407. #if ! MACOS_10_3_OR_EARLIER
  1408. if ((windowStyleFlags & windowIsTemporary) != 0)
  1409. attributes |= kWindowDoesNotCycleAttribute;
  1410. #endif
  1411. WindowRef newWindow = 0;
  1412. if ((windowStyleFlags & windowHasTitleBar) == 0)
  1413. {
  1414. attributes |= kWindowCollapseBoxAttribute;
  1415. WindowDefSpec customWindowSpec;
  1416. customWindowSpec.defType = kWindowDefObjectClass;
  1417. customWindowSpec.u.classRef = customWindowClass;
  1418. CreateCustomWindow (&customWindowSpec,
  1419. ((windowStyleFlags & windowIsTemporary) != 0) ? kUtilityWindowClass :
  1420. (getComponent()->isAlwaysOnTop() ? kUtilityWindowClass
  1421. : kDocumentWindowClass),
  1422. attributes,
  1423. &pos,
  1424. &newWindow);
  1425. }
  1426. else
  1427. {
  1428. if ((windowStyleFlags & windowHasCloseButton) != 0)
  1429. attributes |= kWindowCloseBoxAttribute;
  1430. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  1431. attributes |= kWindowCollapseBoxAttribute;
  1432. if ((windowStyleFlags & windowHasMaximiseButton) != 0)
  1433. attributes |= kWindowFullZoomAttribute;
  1434. if ((windowStyleFlags & windowIsResizable) != 0)
  1435. attributes |= kWindowResizableAttribute | kWindowLiveResizeAttribute;
  1436. CreateNewWindow (kDocumentWindowClass, attributes, &pos, &newWindow);
  1437. }
  1438. jassert (newWindow != 0);
  1439. if (newWindow != 0)
  1440. {
  1441. HideWindow (newWindow);
  1442. SetAutomaticControlDragTrackingEnabledForWindow (newWindow, true);
  1443. if (! getComponent()->isOpaque())
  1444. SetWindowAlpha (newWindow, 0.9999999f); // to fool it into giving the window an alpha-channel
  1445. }
  1446. return newWindow;
  1447. }
  1448. OSStatus ownerWindowChanged (EventRef theEvent)
  1449. {
  1450. WindowRef newWindow = 0;
  1451. GetEventParameter (theEvent, kEventParamControlCurrentOwningWindow, typeWindowRef, 0, sizeof (newWindow), 0, &newWindow);
  1452. if (windowRef != newWindow)
  1453. {
  1454. if (eventHandlerRef != 0)
  1455. {
  1456. RemoveEventHandler (eventHandlerRef);
  1457. eventHandlerRef = 0;
  1458. }
  1459. windowRef = newWindow;
  1460. if (windowRef != 0)
  1461. {
  1462. const EventTypeSpec eventTypes[] =
  1463. {
  1464. { kEventClassWindow, kEventWindowBoundsChanged },
  1465. { kEventClassWindow, kEventWindowBoundsChanging },
  1466. { kEventClassWindow, kEventWindowFocusAcquired },
  1467. { kEventClassWindow, kEventWindowFocusRelinquish },
  1468. { kEventClassWindow, kEventWindowCollapsed },
  1469. { kEventClassWindow, kEventWindowExpanded },
  1470. { kEventClassWindow, kEventWindowShown },
  1471. { kEventClassWindow, kEventWindowClose },
  1472. { kEventClassMouse, kEventMouseDown },
  1473. { kEventClassMouse, kEventMouseUp },
  1474. { kEventClassMouse, kEventMouseMoved },
  1475. { kEventClassMouse, kEventMouseDragged },
  1476. { kEventClassMouse, kEventMouseEntered },
  1477. { kEventClassMouse, kEventMouseExited },
  1478. { kEventClassMouse, kEventMouseWheelMoved },
  1479. { kEventClassKeyboard, kEventRawKeyUp },
  1480. { kEventClassKeyboard, kEventRawKeyRepeat },
  1481. { kEventClassKeyboard, kEventRawKeyModifiersChanged },
  1482. { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent }
  1483. };
  1484. static EventHandlerUPP handleWindowEventUPP = 0;
  1485. if (handleWindowEventUPP == 0)
  1486. handleWindowEventUPP = NewEventHandlerUPP (handleWindowEvent);
  1487. InstallWindowEventHandler (windowRef, handleWindowEventUPP,
  1488. GetEventTypeCount (eventTypes), eventTypes,
  1489. (void*) this, (EventHandlerRef*) &eventHandlerRef);
  1490. WindowAttributes attributes;
  1491. GetWindowAttributes (windowRef, &attributes);
  1492. #if MACOS_10_3_OR_EARLIER
  1493. isCompositingWindow = ((attributes & kWindowCompositingAttribute) != 0);
  1494. #else
  1495. isCompositingWindow = HIViewIsCompositingEnabled (viewRef);
  1496. #endif
  1497. MouseCheckTimer::getInstance()->resetMouseMoveChecker();
  1498. }
  1499. }
  1500. resizeViewToFitWindow();
  1501. return noErr;
  1502. }
  1503. void createNewHIView()
  1504. {
  1505. jassert (viewRef == 0);
  1506. if (viewClassRef == 0)
  1507. {
  1508. // Register our HIView class
  1509. EventTypeSpec viewEvents[] =
  1510. {
  1511. { kEventClassHIObject, kEventHIObjectConstruct },
  1512. { kEventClassHIObject, kEventHIObjectInitialize },
  1513. { kEventClassHIObject, kEventHIObjectDestruct },
  1514. { kEventClassControl, kEventControlInitialize },
  1515. { kEventClassControl, kEventControlDraw },
  1516. { kEventClassControl, kEventControlBoundsChanged },
  1517. { kEventClassControl, kEventControlSetFocusPart },
  1518. { kEventClassControl, kEventControlHitTest },
  1519. { kEventClassControl, kEventControlDragEnter },
  1520. { kEventClassControl, kEventControlDragWithin },
  1521. { kEventClassControl, kEventControlDragReceive },
  1522. { kEventClassControl, kEventControlOwningWindowChanged }
  1523. };
  1524. UnsignedWide t;
  1525. Microseconds (&t);
  1526. const String randomString ((int) (t.lo & 0x7ffffff));
  1527. const String juceHiViewClassName (T("JUCEHIViewClass_") + randomString);
  1528. juceHiViewClassNameCFString = PlatformUtilities::juceStringToCFString (juceHiViewClassName);
  1529. HIObjectRegisterSubclass (juceHiViewClassNameCFString,
  1530. kHIViewClassID, 0,
  1531. NewEventHandlerUPP (hiViewEventHandler),
  1532. GetEventTypeCount (viewEvents),
  1533. viewEvents, 0,
  1534. &viewClassRef);
  1535. }
  1536. EventRef event;
  1537. CreateEvent (0, kEventClassHIObject, kEventHIObjectInitialize, GetCurrentEventTime(), kEventAttributeNone, &event);
  1538. void* thisPointer = this;
  1539. SetEventParameter (event, 'peer', typeVoidPtr, sizeof (void*), &thisPointer);
  1540. HIObjectCreate (juceHiViewClassNameCFString, event, (HIObjectRef*) &viewRef);
  1541. SetControlDragTrackingEnabled (viewRef, true);
  1542. if (isSharedWindow)
  1543. {
  1544. setBounds (component->getX(), component->getY(),
  1545. component->getWidth(), component->getHeight(), false);
  1546. }
  1547. }
  1548. };
  1549. bool juce_isHIViewCreatedByJuce (HIViewRef view)
  1550. {
  1551. return juceHiViewClassNameCFString != 0
  1552. && HIObjectIsOfClass ((HIObjectRef) view, juceHiViewClassNameCFString);
  1553. }
  1554. static void trackNextMouseEvent()
  1555. {
  1556. UInt32 mods;
  1557. MouseTrackingResult result;
  1558. ::Point where;
  1559. if (TrackMouseLocationWithOptions ((GrafPtr) -1, 0, 0.01, //kEventDurationForever,
  1560. &where, &mods, &result) != noErr
  1561. || ! ComponentPeer::isValidPeer (juce_currentMouseTrackingPeer))
  1562. {
  1563. juce_currentMouseTrackingPeer = 0;
  1564. return;
  1565. }
  1566. if (result == kMouseTrackingTimedOut)
  1567. return;
  1568. #if MACOS_10_3_OR_EARLIER
  1569. const int x = where.h - juce_currentMouseTrackingPeer->getScreenX();
  1570. const int y = where.v - juce_currentMouseTrackingPeer->getScreenY();
  1571. #else
  1572. HIPoint p;
  1573. p.x = where.h;
  1574. p.y = where.v;
  1575. HIPointConvert (&p, kHICoordSpaceScreenPixel, 0,
  1576. kHICoordSpaceView, ((HIViewComponentPeer*) juce_currentMouseTrackingPeer)->viewRef);
  1577. const int x = p.x;
  1578. const int y = p.y;
  1579. #endif
  1580. if (result == kMouseTrackingMouseDragged)
  1581. {
  1582. updateModifiers (0);
  1583. juce_currentMouseTrackingPeer->handleMouseDrag (x, y, getEventTime (0));
  1584. if (! ComponentPeer::isValidPeer (juce_currentMouseTrackingPeer))
  1585. {
  1586. juce_currentMouseTrackingPeer = 0;
  1587. return;
  1588. }
  1589. }
  1590. else if (result == kMouseTrackingMouseUp
  1591. || result == kMouseTrackingUserCancelled
  1592. || result == kMouseTrackingMouseMoved)
  1593. {
  1594. ComponentPeer* const oldPeer = juce_currentMouseTrackingPeer;
  1595. juce_currentMouseTrackingPeer = 0;
  1596. if (ComponentPeer::isValidPeer (oldPeer))
  1597. {
  1598. const int oldModifiers = currentModifiers;
  1599. currentModifiers &= ~(ModifierKeys::leftButtonModifier | ModifierKeys::rightButtonModifier | ModifierKeys::middleButtonModifier);
  1600. updateModifiers (0);
  1601. oldPeer->handleMouseUp (oldModifiers, x, y, getEventTime (0));
  1602. }
  1603. }
  1604. }
  1605. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  1606. {
  1607. if (juce_currentMouseTrackingPeer != 0)
  1608. trackNextMouseEvent();
  1609. EventRef theEvent;
  1610. if (ReceiveNextEvent (0, 0, (returnIfNoPendingMessages) ? kEventDurationNoWait
  1611. : kEventDurationForever,
  1612. true, &theEvent) == noErr)
  1613. {
  1614. if (GetEventClass (theEvent) == kEventClassAppleEvent)
  1615. {
  1616. EventRecord eventRec;
  1617. if (ConvertEventRefToEventRecord (theEvent, &eventRec))
  1618. AEProcessAppleEvent (&eventRec);
  1619. }
  1620. else
  1621. {
  1622. EventTargetRef theTarget = GetEventDispatcherTarget();
  1623. SendEventToEventTarget (theEvent, theTarget);
  1624. }
  1625. ReleaseEvent (theEvent);
  1626. return true;
  1627. }
  1628. return false;
  1629. }
  1630. //==============================================================================
  1631. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  1632. {
  1633. return new HIViewComponentPeer (this, styleFlags, (HIViewRef) windowToAttachTo);
  1634. }
  1635. //==============================================================================
  1636. void MouseCheckTimer::timerCallback()
  1637. {
  1638. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  1639. return;
  1640. if (Process::isForegroundProcess())
  1641. {
  1642. bool stillOver = false;
  1643. int x = 0, y = 0, w = 0, h = 0;
  1644. int mx = 0, my = 0;
  1645. const bool validWindow = ComponentPeer::isValidPeer (lastPeerUnderMouse);
  1646. if (validWindow)
  1647. {
  1648. lastPeerUnderMouse->getBounds (x, y, w, h, true);
  1649. Desktop::getMousePosition (mx, my);
  1650. stillOver = (mx >= x && my >= y && mx < x + w && my < y + h);
  1651. if (stillOver)
  1652. {
  1653. // check if it's over an embedded HIView
  1654. int rx = mx, ry = my;
  1655. lastPeerUnderMouse->globalPositionToRelative (rx, ry);
  1656. HIPoint hipoint;
  1657. hipoint.x = rx;
  1658. hipoint.y = ry;
  1659. HIViewRef root;
  1660. GetRootControl ((WindowRef) lastPeerUnderMouse->getNativeHandle(), &root);
  1661. HIViewRef hitview;
  1662. if (HIViewGetSubviewHit (root, &hipoint, true, &hitview) == noErr && hitview != 0)
  1663. {
  1664. stillOver = HIObjectIsOfClass ((HIObjectRef) hitview, juceHiViewClassNameCFString);
  1665. }
  1666. }
  1667. }
  1668. if (! stillOver)
  1669. {
  1670. // mouse is outside our windows so set a normal cursor (only
  1671. // if we're running as an app, not a plugin)
  1672. if (JUCEApplication::getInstance() != 0)
  1673. SetThemeCursor (kThemeArrowCursor);
  1674. if (validWindow)
  1675. lastPeerUnderMouse->handleMouseExit (mx - x, my - y, Time::currentTimeMillis());
  1676. if (hasEverHadAMouseMove)
  1677. stopTimer();
  1678. }
  1679. if ((! hasEverHadAMouseMove) && validWindow
  1680. && (mx != lastX || my != lastY))
  1681. {
  1682. lastX = mx;
  1683. lastY = my;
  1684. if (stillOver)
  1685. lastPeerUnderMouse->handleMouseMove (mx - x, my - y, Time::currentTimeMillis());
  1686. }
  1687. }
  1688. }
  1689. //==============================================================================
  1690. // called from juce_Messaging.cpp
  1691. void juce_HandleProcessFocusChange()
  1692. {
  1693. keysCurrentlyDown.clear();
  1694. if (HIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  1695. {
  1696. if (Process::isForegroundProcess())
  1697. currentlyFocusedPeer->handleFocusGain();
  1698. else
  1699. currentlyFocusedPeer->handleFocusLoss();
  1700. }
  1701. }
  1702. static bool performDrag (DragRef drag)
  1703. {
  1704. EventRecord event;
  1705. event.what = mouseDown;
  1706. event.message = 0;
  1707. event.when = TickCount();
  1708. int x, y;
  1709. Desktop::getMousePosition (x, y);
  1710. event.where.h = x;
  1711. event.where.v = y;
  1712. event.modifiers = GetCurrentKeyModifiers();
  1713. RgnHandle rgn = NewRgn();
  1714. RgnHandle rgn2 = NewRgn();
  1715. SetRectRgn (rgn,
  1716. event.where.h - 8, event.where.v - 8,
  1717. event.where.h + 8, event.where.v + 8);
  1718. CopyRgn (rgn, rgn2);
  1719. InsetRgn (rgn2, 1, 1);
  1720. DiffRgn (rgn, rgn2, rgn);
  1721. DisposeRgn (rgn2);
  1722. bool result = TrackDrag (drag, &event, rgn) == noErr;
  1723. DisposeRgn (rgn);
  1724. return result;
  1725. }
  1726. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  1727. {
  1728. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  1729. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  1730. DragRef drag;
  1731. bool result = false;
  1732. if (NewDrag (&drag) == noErr)
  1733. {
  1734. for (int i = 0; i < files.size(); ++i)
  1735. {
  1736. HFSFlavor hfsData;
  1737. if (PlatformUtilities::makeFSSpecFromPath (&hfsData.fileSpec, files[i]))
  1738. {
  1739. FInfo info;
  1740. if (FSpGetFInfo (&hfsData.fileSpec, &info) == noErr)
  1741. {
  1742. hfsData.fileType = info.fdType;
  1743. hfsData.fileCreator = info.fdCreator;
  1744. hfsData.fdFlags = info.fdFlags;
  1745. AddDragItemFlavor (drag, i + 1, kDragFlavorTypeHFS, &hfsData, sizeof (hfsData), 0);
  1746. result = true;
  1747. }
  1748. }
  1749. }
  1750. SetDragAllowableActions (drag, canMoveFiles ? kDragActionAll
  1751. : kDragActionCopy, false);
  1752. if (result)
  1753. result = performDrag (drag);
  1754. DisposeDrag (drag);
  1755. }
  1756. return result;
  1757. }
  1758. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  1759. {
  1760. jassertfalse // not implemented!
  1761. return false;
  1762. }
  1763. //==============================================================================
  1764. bool Process::isForegroundProcess() throw()
  1765. {
  1766. ProcessSerialNumber psn, front;
  1767. GetCurrentProcess (&psn);
  1768. GetFrontProcess (&front);
  1769. Boolean b;
  1770. return (SameProcess (&psn, &front, &b) == noErr) && b;
  1771. }
  1772. //==============================================================================
  1773. bool Desktop::canUseSemiTransparentWindows() throw()
  1774. {
  1775. return true;
  1776. }
  1777. //==============================================================================
  1778. void Desktop::getMousePosition (int& x, int& y) throw()
  1779. {
  1780. CGrafPtr currentPort;
  1781. GetPort (&currentPort);
  1782. if (! IsValidPort (currentPort))
  1783. {
  1784. WindowRef front = FrontWindow();
  1785. if (front != 0)
  1786. {
  1787. SetPortWindowPort (front);
  1788. }
  1789. else
  1790. {
  1791. x = y = 0;
  1792. return;
  1793. }
  1794. }
  1795. ::Point p;
  1796. GetMouse (&p);
  1797. LocalToGlobal (&p);
  1798. x = p.h;
  1799. y = p.v;
  1800. SetPort (currentPort);
  1801. }
  1802. void Desktop::setMousePosition (int x, int y) throw()
  1803. {
  1804. // this rubbish needs to be done around the warp call, to avoid causing a
  1805. // bizarre glitch..
  1806. CGAssociateMouseAndMouseCursorPosition (false);
  1807. CGSetLocalEventsSuppressionInterval (0);
  1808. CGPoint pos = { x, y };
  1809. CGWarpMouseCursorPosition (pos);
  1810. CGAssociateMouseAndMouseCursorPosition (true);
  1811. }
  1812. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  1813. {
  1814. return ModifierKeys (currentModifiers);
  1815. }
  1816. //==============================================================================
  1817. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  1818. {
  1819. int mainMonitorIndex = 0;
  1820. CGDirectDisplayID mainDisplayID = CGMainDisplayID();
  1821. CGDisplayCount count = 0;
  1822. CGDirectDisplayID disps [8];
  1823. if (CGGetActiveDisplayList (numElementsInArray (disps), disps, &count) == noErr)
  1824. {
  1825. for (int i = 0; i < count; ++i)
  1826. {
  1827. if (mainDisplayID == disps[i])
  1828. mainMonitorIndex = monitorCoords.size();
  1829. GDHandle hGDevice;
  1830. if (clipToWorkArea
  1831. && DMGetGDeviceByDisplayID ((DisplayIDType) disps[i], &hGDevice, false) == noErr)
  1832. {
  1833. Rect rect;
  1834. GetAvailableWindowPositioningBounds (hGDevice, &rect);
  1835. monitorCoords.add (Rectangle (rect.left,
  1836. rect.top,
  1837. rect.right - rect.left,
  1838. rect.bottom - rect.top));
  1839. }
  1840. else
  1841. {
  1842. const CGRect r (CGDisplayBounds (disps[i]));
  1843. monitorCoords.add (Rectangle ((int) r.origin.x,
  1844. (int) r.origin.y,
  1845. (int) r.size.width,
  1846. (int) r.size.height));
  1847. }
  1848. }
  1849. }
  1850. // make sure the first in the list is the main monitor
  1851. if (mainMonitorIndex > 0)
  1852. monitorCoords.swap (mainMonitorIndex, 0);
  1853. jassert (monitorCoords.size() > 0); // xxx seems like this can happen when the screen's in power-saving mode..
  1854. if (monitorCoords.size() == 0)
  1855. monitorCoords.add (Rectangle (0, 0, 1024, 768));
  1856. //xxx need to register for display change callbacks
  1857. }
  1858. //==============================================================================
  1859. struct CursorWrapper
  1860. {
  1861. Cursor* cursor;
  1862. ThemeCursor themeCursor;
  1863. };
  1864. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  1865. {
  1866. const int maxW = 16;
  1867. const int maxH = 16;
  1868. const Image* im = &image;
  1869. Image* newIm = 0;
  1870. if (image.getWidth() > maxW || image.getHeight() > maxH)
  1871. {
  1872. im = newIm = image.createCopy (maxW, maxH);
  1873. hotspotX = (hotspotX * maxW) / image.getWidth();
  1874. hotspotY = (hotspotY * maxH) / image.getHeight();
  1875. }
  1876. Cursor* const c = new Cursor();
  1877. c->hotSpot.h = hotspotX;
  1878. c->hotSpot.v = hotspotY;
  1879. for (int y = 0; y < maxH; ++y)
  1880. {
  1881. c->data[y] = 0;
  1882. c->mask[y] = 0;
  1883. for (int x = 0; x < maxW; ++x)
  1884. {
  1885. const Colour pixelColour (im->getPixelAt (15 - x, y));
  1886. if (pixelColour.getAlpha() > 0.5f)
  1887. {
  1888. c->mask[y] |= (1 << x);
  1889. if (pixelColour.getBrightness() < 0.5f)
  1890. c->data[y] |= (1 << x);
  1891. }
  1892. }
  1893. c->data[y] = CFSwapInt16BigToHost (c->data[y]);
  1894. c->mask[y] = CFSwapInt16BigToHost (c->mask[y]);
  1895. }
  1896. if (newIm != 0)
  1897. delete newIm;
  1898. CursorWrapper* const cw = new CursorWrapper();
  1899. cw->cursor = c;
  1900. cw->themeCursor = kThemeArrowCursor;
  1901. return (void*) cw;
  1902. }
  1903. static void* cursorFromData (const unsigned char* data, const int size, int hx, int hy) throw()
  1904. {
  1905. Image* const im = ImageFileFormat::loadFrom ((const char*) data, size);
  1906. jassert (im != 0);
  1907. void* curs = juce_createMouseCursorFromImage (*im, hx, hy);
  1908. delete im;
  1909. return curs;
  1910. }
  1911. const unsigned int kSpecialNoCursor = 'nocr';
  1912. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  1913. {
  1914. ThemeCursor id = kThemeArrowCursor;
  1915. switch (type)
  1916. {
  1917. case MouseCursor::NormalCursor:
  1918. id = kThemeArrowCursor;
  1919. break;
  1920. case MouseCursor::NoCursor:
  1921. id = kSpecialNoCursor;
  1922. break;
  1923. case MouseCursor::DraggingHandCursor:
  1924. {
  1925. static const unsigned char cursData[] = {71,73,70,56,57,97,16,0,16,0,145,2,0,0,0,0,255,255,255,0,
  1926. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  1927. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  1928. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  1929. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  1930. const int cursDataSize = 99;
  1931. return cursorFromData (cursData, cursDataSize, 8, 8);
  1932. }
  1933. break;
  1934. case MouseCursor::CopyingCursor:
  1935. id = kThemeCopyArrowCursor;
  1936. break;
  1937. case MouseCursor::WaitCursor:
  1938. id = kThemeWatchCursor;
  1939. break;
  1940. case MouseCursor::IBeamCursor:
  1941. id = kThemeIBeamCursor;
  1942. break;
  1943. case MouseCursor::PointingHandCursor:
  1944. id = kThemePointingHandCursor;
  1945. break;
  1946. case MouseCursor::LeftRightResizeCursor:
  1947. case MouseCursor::LeftEdgeResizeCursor:
  1948. case MouseCursor::RightEdgeResizeCursor:
  1949. {
  1950. static const unsigned char cursData[] = {71,73,70,56,57,97,16,0,16,0,145,0,0,255,255,255,0,0,0,255,
  1951. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  1952. 16,0,0,2,38,148,143,169,203,237,15,19,0,106,202,64,111,22,32,224,
  1953. 9,78,30,213,121,230,121,146,99,8,142,71,183,189,152,20,27,86,132,231,
  1954. 58,83,0,0,59 };
  1955. const int cursDataSize = 85;
  1956. return cursorFromData (cursData, cursDataSize, 8, 8);
  1957. }
  1958. case MouseCursor::UpDownResizeCursor:
  1959. case MouseCursor::TopEdgeResizeCursor:
  1960. case MouseCursor::BottomEdgeResizeCursor:
  1961. {
  1962. static const unsigned char cursData[] = {71,73,70,56,57,97,16,0,16,0,145,0,0,255,255,255,0,0,0,255,
  1963. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  1964. 16,0,0,2,38,148,111,128,187,16,202,90,152,48,10,55,169,189,192,245,
  1965. 106,121,27,34,142,201,99,158,224,86,154,109,216,61,29,155,105,180,61,190,
  1966. 121,84,0,0,59 };
  1967. const int cursDataSize = 85;
  1968. return cursorFromData (cursData, cursDataSize, 8, 8);
  1969. }
  1970. case MouseCursor::TopLeftCornerResizeCursor:
  1971. case MouseCursor::BottomRightCornerResizeCursor:
  1972. {
  1973. static const unsigned char cursData[] = {71,73,70,56,57,97,16,0,16,0,145,0,0,255,255,255,0,0,0,255,
  1974. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  1975. 16,0,0,2,43,132,15,162,187,16,255,18,99,14,202,217,44,158,213,221,
  1976. 237,9,225,38,94,35,73,5,31,42,170,108,106,174,112,43,195,209,91,185,
  1977. 104,174,131,208,77,66,28,10,0,59 };
  1978. const int cursDataSize = 90;
  1979. return cursorFromData (cursData, cursDataSize, 8, 8);
  1980. }
  1981. case MouseCursor::TopRightCornerResizeCursor:
  1982. case MouseCursor::BottomLeftCornerResizeCursor:
  1983. {
  1984. static const unsigned char cursData[] = {71,73,70,56,57,97,16,0,16,0,145,0,0,255,255,255,0,0,0,255,
  1985. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  1986. 16,0,0,2,45,148,127,160,11,232,16,98,108,14,65,73,107,194,122,223,
  1987. 92,65,141,216,145,134,162,153,221,25,128,73,166,62,173,16,203,237,188,94,
  1988. 120,46,237,105,239,123,48,80,157,2,0,59 };
  1989. const int cursDataSize = 92;
  1990. return cursorFromData (cursData, cursDataSize, 8, 8);
  1991. }
  1992. case MouseCursor::UpDownLeftRightResizeCursor:
  1993. {
  1994. static const unsigned char cursData[] = {71,73,70,56,57,97,15,0,15,0,145,0,0,0,0,0,255,255,255,0,
  1995. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,15,0,
  1996. 15,0,0,2,46,156,63,129,139,1,202,26,152,48,186,73,109,114,65,85,
  1997. 195,37,143,88,93,29,215,101,23,198,178,30,149,158,25,56,134,97,179,61,
  1998. 158,213,126,203,234,99,220,34,56,70,1,0,59,0,0 };
  1999. const int cursDataSize = 93;
  2000. return cursorFromData (cursData, cursDataSize, 7, 7);
  2001. }
  2002. case MouseCursor::CrosshairCursor:
  2003. id = kThemeCrossCursor;
  2004. break;
  2005. }
  2006. CursorWrapper* cw = new CursorWrapper();
  2007. cw->cursor = 0;
  2008. cw->themeCursor = id;
  2009. return (void*) cw;
  2010. }
  2011. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  2012. {
  2013. CursorWrapper* const cw = (CursorWrapper*) cursorHandle;
  2014. if (cw != 0)
  2015. {
  2016. delete cw->cursor;
  2017. delete cw;
  2018. }
  2019. }
  2020. void MouseCursor::showInAllWindows() const throw()
  2021. {
  2022. showInWindow (0);
  2023. }
  2024. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  2025. {
  2026. const CursorWrapper* const cw = (CursorWrapper*) getHandle();
  2027. if (cw != 0)
  2028. {
  2029. static bool isCursorHidden = false;
  2030. static bool showingWaitCursor = false;
  2031. const bool shouldShowWaitCursor = (cw->themeCursor == kThemeWatchCursor);
  2032. const bool shouldHideCursor = (cw->themeCursor == kSpecialNoCursor);
  2033. if (shouldShowWaitCursor != showingWaitCursor
  2034. && Process::isForegroundProcess())
  2035. {
  2036. showingWaitCursor = shouldShowWaitCursor;
  2037. QDDisplayWaitCursor (shouldShowWaitCursor);
  2038. }
  2039. if (shouldHideCursor != isCursorHidden)
  2040. {
  2041. isCursorHidden = shouldHideCursor;
  2042. if (shouldHideCursor)
  2043. HideCursor();
  2044. else
  2045. ShowCursor();
  2046. }
  2047. if (cw->cursor != 0)
  2048. SetCursor (cw->cursor);
  2049. else if (! (shouldShowWaitCursor || shouldHideCursor))
  2050. SetThemeCursor (cw->themeCursor);
  2051. }
  2052. }
  2053. //==============================================================================
  2054. Image* juce_createIconForFile (const File& file)
  2055. {
  2056. return 0;
  2057. }
  2058. //==============================================================================
  2059. class MainMenuHandler;
  2060. static MainMenuHandler* mainMenu = 0;
  2061. class MainMenuHandler : private MenuBarModelListener,
  2062. private DeletedAtShutdown
  2063. {
  2064. public:
  2065. MainMenuHandler() throw()
  2066. : currentModel (0)
  2067. {
  2068. }
  2069. ~MainMenuHandler() throw()
  2070. {
  2071. setMenu (0);
  2072. jassert (mainMenu == this);
  2073. mainMenu = 0;
  2074. }
  2075. void setMenu (MenuBarModel* const newMenuBarModel) throw()
  2076. {
  2077. if (currentModel != newMenuBarModel)
  2078. {
  2079. if (currentModel != 0)
  2080. currentModel->removeListener (this);
  2081. currentModel = newMenuBarModel;
  2082. if (currentModel != 0)
  2083. currentModel->addListener (this);
  2084. menuBarItemsChanged (0);
  2085. }
  2086. }
  2087. void menuBarItemsChanged (MenuBarModel*)
  2088. {
  2089. ClearMenuBar();
  2090. if (currentModel != 0)
  2091. {
  2092. int id = 1000;
  2093. const StringArray menuNames (currentModel->getMenuBarNames());
  2094. for (int i = 0; i < menuNames.size(); ++i)
  2095. {
  2096. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  2097. MenuRef m = createMenu (menu, menuNames [i], id, i);
  2098. InsertMenu (m, 0);
  2099. CFRelease (m);
  2100. }
  2101. }
  2102. }
  2103. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  2104. {
  2105. MenuRef menu = 0;
  2106. MenuItemIndex index = 0;
  2107. GetIndMenuItemWithCommandID (0, info.commandID, 1, &menu, &index);
  2108. FlashMenuBar (GetMenuID (menu));
  2109. FlashMenuBar (GetMenuID (menu));
  2110. }
  2111. void invoke (const int id, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  2112. {
  2113. if (currentModel != 0)
  2114. {
  2115. if (commandManager != 0)
  2116. {
  2117. ApplicationCommandTarget::InvocationInfo info (id);
  2118. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  2119. commandManager->invoke (info, true);
  2120. }
  2121. currentModel->menuItemSelected (id, topLevelIndex);
  2122. }
  2123. }
  2124. MenuBarModel* currentModel;
  2125. private:
  2126. static MenuRef createMenu (const PopupMenu menu,
  2127. const String& menuName,
  2128. int& id,
  2129. const int topLevelIndex)
  2130. {
  2131. MenuRef m = 0;
  2132. if (CreateNewMenu (id++, kMenuAttrAutoDisable, &m) == noErr)
  2133. {
  2134. CFStringRef name = PlatformUtilities::juceStringToCFString (menuName);
  2135. SetMenuTitleWithCFString (m, name);
  2136. CFRelease (name);
  2137. PopupMenu::MenuItemIterator iter (menu);
  2138. while (iter.next())
  2139. {
  2140. MenuItemIndex index = 0;
  2141. int flags = kMenuAttrAutoDisable | kMenuItemAttrIgnoreMeta | kMenuItemAttrNotPreviousAlternate;
  2142. if (! iter.isEnabled)
  2143. flags |= kMenuItemAttrDisabled;
  2144. CFStringRef text = PlatformUtilities::juceStringToCFString (iter.itemName.upToFirstOccurrenceOf (T("<end>"), false, true));
  2145. if (iter.isSeparator)
  2146. {
  2147. AppendMenuItemTextWithCFString (m, text, kMenuItemAttrSeparator, 0, &index);
  2148. }
  2149. else if (iter.isSectionHeader)
  2150. {
  2151. AppendMenuItemTextWithCFString (m, text, kMenuItemAttrSectionHeader, 0, &index);
  2152. }
  2153. else if (iter.subMenu != 0)
  2154. {
  2155. AppendMenuItemTextWithCFString (m, text, flags, id++, &index);
  2156. MenuRef sub = createMenu (*iter.subMenu, iter.itemName, id, topLevelIndex);
  2157. SetMenuItemHierarchicalMenu (m, index, sub);
  2158. CFRelease (sub);
  2159. }
  2160. else
  2161. {
  2162. AppendMenuItemTextWithCFString (m, text, flags, iter.itemId, &index);
  2163. if (iter.isTicked)
  2164. CheckMenuItem (m, index, true);
  2165. SetMenuItemProperty (m, index, 'juce', 'apcm', sizeof (void*), &iter.commandManager);
  2166. SetMenuItemProperty (m, index, 'juce', 'topi', sizeof (int), &topLevelIndex);
  2167. if (iter.commandManager != 0)
  2168. {
  2169. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  2170. ->getKeyPressesAssignedToCommand (iter.itemId));
  2171. if (keyPresses.size() > 0)
  2172. {
  2173. const KeyPress& kp = keyPresses.getUnchecked(0);
  2174. int mods = 0;
  2175. if (kp.getModifiers().isShiftDown())
  2176. mods |= kMenuShiftModifier;
  2177. if (kp.getModifiers().isCtrlDown())
  2178. mods |= kMenuControlModifier;
  2179. if (kp.getModifiers().isAltDown())
  2180. mods |= kMenuOptionModifier;
  2181. if (! kp.getModifiers().isCommandDown())
  2182. mods |= kMenuNoCommandModifier;
  2183. tchar keyCode = (tchar) kp.getKeyCode();
  2184. if (kp.getKeyCode() >= KeyPress::numberPad0
  2185. && kp.getKeyCode() <= KeyPress::numberPad9)
  2186. {
  2187. keyCode = (tchar) ((T('0') - KeyPress::numberPad0) + kp.getKeyCode());
  2188. }
  2189. SetMenuItemCommandKey (m, index, true, 255);
  2190. if (CharacterFunctions::isLetterOrDigit (keyCode)
  2191. || CharacterFunctions::indexOfChar (T(",.;/\\'[]=-+_<>?{}\":"), keyCode, false) >= 0)
  2192. {
  2193. SetMenuItemModifiers (m, index, mods);
  2194. SetMenuItemCommandKey (m, index, false, CharacterFunctions::toUpperCase (keyCode));
  2195. }
  2196. else
  2197. {
  2198. const SInt16 glyph = getGlyphForKeyCode (kp.getKeyCode());
  2199. if (glyph != 0)
  2200. {
  2201. SetMenuItemModifiers (m, index, mods);
  2202. SetMenuItemKeyGlyph (m, index, glyph);
  2203. }
  2204. }
  2205. // if we set the key glyph to be a text char, and enable virtual
  2206. // key triggering, it stops the menu automatically triggering the callback
  2207. ChangeMenuItemAttributes (m, index, kMenuItemAttrUseVirtualKey, 0);
  2208. }
  2209. }
  2210. }
  2211. CFRelease (text);
  2212. }
  2213. }
  2214. return m;
  2215. }
  2216. static SInt16 getGlyphForKeyCode (const int keyCode) throw()
  2217. {
  2218. if (keyCode == KeyPress::spaceKey)
  2219. return kMenuSpaceGlyph;
  2220. else if (keyCode == KeyPress::returnKey)
  2221. return kMenuReturnGlyph;
  2222. else if (keyCode == KeyPress::escapeKey)
  2223. return kMenuEscapeGlyph;
  2224. else if (keyCode == KeyPress::backspaceKey)
  2225. return kMenuDeleteLeftGlyph;
  2226. else if (keyCode == KeyPress::leftKey)
  2227. return kMenuLeftArrowGlyph;
  2228. else if (keyCode == KeyPress::rightKey)
  2229. return kMenuRightArrowGlyph;
  2230. else if (keyCode == KeyPress::upKey)
  2231. return kMenuUpArrowGlyph;
  2232. else if (keyCode == KeyPress::downKey)
  2233. return kMenuDownArrowGlyph;
  2234. else if (keyCode == KeyPress::pageUpKey)
  2235. return kMenuPageUpGlyph;
  2236. else if (keyCode == KeyPress::pageDownKey)
  2237. return kMenuPageDownGlyph;
  2238. else if (keyCode == KeyPress::endKey)
  2239. return kMenuSoutheastArrowGlyph;
  2240. else if (keyCode == KeyPress::homeKey)
  2241. return kMenuNorthwestArrowGlyph;
  2242. else if (keyCode == KeyPress::deleteKey)
  2243. return kMenuDeleteRightGlyph;
  2244. else if (keyCode == KeyPress::tabKey)
  2245. return kMenuTabRightGlyph;
  2246. else if (keyCode == KeyPress::F1Key)
  2247. return kMenuF1Glyph;
  2248. else if (keyCode == KeyPress::F2Key)
  2249. return kMenuF2Glyph;
  2250. else if (keyCode == KeyPress::F3Key)
  2251. return kMenuF3Glyph;
  2252. else if (keyCode == KeyPress::F4Key)
  2253. return kMenuF4Glyph;
  2254. else if (keyCode == KeyPress::F5Key)
  2255. return kMenuF5Glyph;
  2256. else if (keyCode == KeyPress::F6Key)
  2257. return kMenuF6Glyph;
  2258. else if (keyCode == KeyPress::F7Key)
  2259. return kMenuF7Glyph;
  2260. else if (keyCode == KeyPress::F8Key)
  2261. return kMenuF8Glyph;
  2262. else if (keyCode == KeyPress::F9Key)
  2263. return kMenuF9Glyph;
  2264. else if (keyCode == KeyPress::F10Key)
  2265. return kMenuF10Glyph;
  2266. else if (keyCode == KeyPress::F11Key)
  2267. return kMenuF11Glyph;
  2268. else if (keyCode == KeyPress::F12Key)
  2269. return kMenuF12Glyph;
  2270. else if (keyCode == KeyPress::F13Key)
  2271. return kMenuF13Glyph;
  2272. else if (keyCode == KeyPress::F14Key)
  2273. return kMenuF14Glyph;
  2274. else if (keyCode == KeyPress::F15Key)
  2275. return kMenuF15Glyph;
  2276. return 0;
  2277. }
  2278. };
  2279. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel) throw()
  2280. {
  2281. if (getMacMainMenu() != newMenuBarModel)
  2282. {
  2283. if (newMenuBarModel == 0)
  2284. {
  2285. delete mainMenu;
  2286. jassert (mainMenu == 0); // should be zeroed in the destructor
  2287. }
  2288. else
  2289. {
  2290. if (mainMenu == 0)
  2291. mainMenu = new MainMenuHandler();
  2292. mainMenu->setMenu (newMenuBarModel);
  2293. }
  2294. }
  2295. }
  2296. MenuBarModel* MenuBarModel::getMacMainMenu() throw()
  2297. {
  2298. return mainMenu != 0 ? mainMenu->currentModel : 0;
  2299. }
  2300. // these functions are called externally from the message handling code
  2301. void juce_MainMenuAboutToBeUsed()
  2302. {
  2303. // force an update of the items just before the menu appears..
  2304. if (mainMenu != 0)
  2305. mainMenu->menuBarItemsChanged (0);
  2306. }
  2307. void juce_InvokeMainMenuCommand (const HICommand& command)
  2308. {
  2309. if (mainMenu != 0)
  2310. {
  2311. ApplicationCommandManager* commandManager = 0;
  2312. int topLevelIndex = 0;
  2313. if (GetMenuItemProperty (command.menu.menuRef, command.menu.menuItemIndex,
  2314. 'juce', 'apcm', sizeof (commandManager), 0, &commandManager) == noErr
  2315. && GetMenuItemProperty (command.menu.menuRef, command.menu.menuItemIndex,
  2316. 'juce', 'topi', sizeof (topLevelIndex), 0, &topLevelIndex) == noErr)
  2317. {
  2318. mainMenu->invoke (command.commandID, commandManager, topLevelIndex);
  2319. }
  2320. }
  2321. }
  2322. //==============================================================================
  2323. void PlatformUtilities::beep()
  2324. {
  2325. SysBeep (30);
  2326. }
  2327. //==============================================================================
  2328. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  2329. {
  2330. ClearCurrentScrap();
  2331. ScrapRef ref;
  2332. GetCurrentScrap (&ref);
  2333. const int len = text.length();
  2334. const int numBytes = sizeof (UniChar) * len;
  2335. UniChar* const temp = (UniChar*) juce_calloc (numBytes);
  2336. for (int i = 0; i < len; ++i)
  2337. temp[i] = (UniChar) text[i];
  2338. PutScrapFlavor (ref,
  2339. kScrapFlavorTypeUnicode,
  2340. kScrapFlavorMaskNone,
  2341. numBytes,
  2342. temp);
  2343. juce_free (temp);
  2344. }
  2345. const String SystemClipboard::getTextFromClipboard() throw()
  2346. {
  2347. String result;
  2348. ScrapRef ref;
  2349. GetCurrentScrap (&ref);
  2350. Size size = 0;
  2351. if (GetScrapFlavorSize (ref, kScrapFlavorTypeUnicode, &size) == noErr
  2352. && size > 0)
  2353. {
  2354. void* const data = juce_calloc (size + 8);
  2355. if (GetScrapFlavorData (ref, kScrapFlavorTypeUnicode, &size, data) == noErr)
  2356. {
  2357. result = PlatformUtilities::convertUTF16ToString ((UniChar*) data);
  2358. }
  2359. juce_free (data);
  2360. }
  2361. return result;
  2362. }
  2363. //==============================================================================
  2364. bool AlertWindow::showNativeDialogBox (const String& title,
  2365. const String& bodyText,
  2366. bool isOkCancel)
  2367. {
  2368. Str255 tit, txt;
  2369. PlatformUtilities::copyToStr255 (tit, title);
  2370. PlatformUtilities::copyToStr255 (txt, bodyText);
  2371. AlertStdAlertParamRec ar;
  2372. ar.movable = true;
  2373. ar.helpButton = false;
  2374. ar.filterProc = 0;
  2375. ar.defaultText = (const unsigned char*)-1;
  2376. ar.cancelText = (const unsigned char*)((isOkCancel) ? -1 : 0);
  2377. ar.otherText = 0;
  2378. ar.defaultButton = kAlertStdAlertOKButton;
  2379. ar.cancelButton = 0;
  2380. ar.position = kWindowDefaultPosition;
  2381. SInt16 result;
  2382. StandardAlert (kAlertNoteAlert, tit, txt, &ar, &result);
  2383. return result == kAlertStdAlertOKButton;
  2384. }
  2385. //==============================================================================
  2386. const int KeyPress::spaceKey = ' ';
  2387. const int KeyPress::returnKey = kReturnCharCode;
  2388. const int KeyPress::escapeKey = kEscapeCharCode;
  2389. const int KeyPress::backspaceKey = kBackspaceCharCode;
  2390. const int KeyPress::leftKey = kLeftArrowCharCode;
  2391. const int KeyPress::rightKey = kRightArrowCharCode;
  2392. const int KeyPress::upKey = kUpArrowCharCode;
  2393. const int KeyPress::downKey = kDownArrowCharCode;
  2394. const int KeyPress::pageUpKey = kPageUpCharCode;
  2395. const int KeyPress::pageDownKey = kPageDownCharCode;
  2396. const int KeyPress::endKey = kEndCharCode;
  2397. const int KeyPress::homeKey = kHomeCharCode;
  2398. const int KeyPress::deleteKey = kDeleteCharCode;
  2399. const int KeyPress::insertKey = -1;
  2400. const int KeyPress::tabKey = kTabCharCode;
  2401. const int KeyPress::F1Key = 0x10110;
  2402. const int KeyPress::F2Key = 0x10111;
  2403. const int KeyPress::F3Key = 0x10112;
  2404. const int KeyPress::F4Key = 0x10113;
  2405. const int KeyPress::F5Key = 0x10114;
  2406. const int KeyPress::F6Key = 0x10115;
  2407. const int KeyPress::F7Key = 0x10116;
  2408. const int KeyPress::F8Key = 0x10117;
  2409. const int KeyPress::F9Key = 0x10118;
  2410. const int KeyPress::F10Key = 0x10119;
  2411. const int KeyPress::F11Key = 0x1011a;
  2412. const int KeyPress::F12Key = 0x1011b;
  2413. const int KeyPress::F13Key = 0x1011c;
  2414. const int KeyPress::F14Key = 0x1011d;
  2415. const int KeyPress::F15Key = 0x1011e;
  2416. const int KeyPress::F16Key = 0x1011f;
  2417. const int KeyPress::numberPad0 = 0x30020;
  2418. const int KeyPress::numberPad1 = 0x30021;
  2419. const int KeyPress::numberPad2 = 0x30022;
  2420. const int KeyPress::numberPad3 = 0x30023;
  2421. const int KeyPress::numberPad4 = 0x30024;
  2422. const int KeyPress::numberPad5 = 0x30025;
  2423. const int KeyPress::numberPad6 = 0x30026;
  2424. const int KeyPress::numberPad7 = 0x30027;
  2425. const int KeyPress::numberPad8 = 0x30028;
  2426. const int KeyPress::numberPad9 = 0x30029;
  2427. const int KeyPress::numberPadAdd = 0x3002a;
  2428. const int KeyPress::numberPadSubtract = 0x3002b;
  2429. const int KeyPress::numberPadMultiply = 0x3002c;
  2430. const int KeyPress::numberPadDivide = 0x3002d;
  2431. const int KeyPress::numberPadSeparator = 0x3002e;
  2432. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  2433. const int KeyPress::numberPadEquals = 0x30030;
  2434. const int KeyPress::numberPadDelete = 0x30031;
  2435. const int KeyPress::playKey = 0x30000;
  2436. const int KeyPress::stopKey = 0x30001;
  2437. const int KeyPress::fastForwardKey = 0x30002;
  2438. const int KeyPress::rewindKey = 0x30003;
  2439. //==============================================================================
  2440. AppleRemoteDevice::AppleRemoteDevice()
  2441. : device (0),
  2442. queue (0),
  2443. remoteId (0)
  2444. {
  2445. }
  2446. AppleRemoteDevice::~AppleRemoteDevice()
  2447. {
  2448. stop();
  2449. }
  2450. static io_object_t getAppleRemoteDevice() throw()
  2451. {
  2452. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  2453. io_iterator_t iter = 0;
  2454. io_object_t iod = 0;
  2455. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  2456. && iter != 0)
  2457. {
  2458. iod = IOIteratorNext (iter);
  2459. }
  2460. IOObjectRelease (iter);
  2461. return iod;
  2462. }
  2463. static bool createAppleRemoteInterface (io_object_t iod, void** device) throw()
  2464. {
  2465. jassert (*device == 0);
  2466. io_name_t classname;
  2467. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  2468. {
  2469. IOCFPlugInInterface** cfPlugInInterface = 0;
  2470. SInt32 score = 0;
  2471. if (IOCreatePlugInInterfaceForService (iod,
  2472. kIOHIDDeviceUserClientTypeID,
  2473. kIOCFPlugInInterfaceID,
  2474. &cfPlugInInterface,
  2475. &score) == kIOReturnSuccess)
  2476. {
  2477. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  2478. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  2479. device);
  2480. (void) hr;
  2481. (*cfPlugInInterface)->Release (cfPlugInInterface);
  2482. }
  2483. }
  2484. return *device != 0;
  2485. }
  2486. bool AppleRemoteDevice::start (const bool inExclusiveMode) throw()
  2487. {
  2488. if (queue != 0)
  2489. return true;
  2490. stop();
  2491. bool result = false;
  2492. io_object_t iod = getAppleRemoteDevice();
  2493. if (iod != 0)
  2494. {
  2495. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  2496. result = true;
  2497. else
  2498. stop();
  2499. IOObjectRelease (iod);
  2500. }
  2501. return result;
  2502. }
  2503. void AppleRemoteDevice::stop() throw()
  2504. {
  2505. if (queue != 0)
  2506. {
  2507. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  2508. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  2509. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  2510. queue = 0;
  2511. }
  2512. if (device != 0)
  2513. {
  2514. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  2515. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  2516. device = 0;
  2517. }
  2518. }
  2519. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  2520. {
  2521. if (result == kIOReturnSuccess)
  2522. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  2523. }
  2524. bool AppleRemoteDevice::open (const bool openInExclusiveMode) throw()
  2525. {
  2526. #if ! MACOS_10_2_OR_EARLIER
  2527. Array <int> cookies;
  2528. CFArrayRef elements;
  2529. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  2530. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  2531. return false;
  2532. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  2533. {
  2534. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  2535. // get the cookie
  2536. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  2537. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  2538. continue;
  2539. long number;
  2540. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  2541. continue;
  2542. cookies.add ((int) number);
  2543. }
  2544. CFRelease (elements);
  2545. if ((*(IOHIDDeviceInterface**) device)
  2546. ->open ((IOHIDDeviceInterface**) device,
  2547. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  2548. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  2549. {
  2550. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  2551. if (queue != 0)
  2552. {
  2553. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  2554. for (int i = 0; i < cookies.size(); ++i)
  2555. {
  2556. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  2557. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  2558. }
  2559. CFRunLoopSourceRef eventSource;
  2560. if ((*(IOHIDQueueInterface**) queue)
  2561. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  2562. {
  2563. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  2564. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  2565. {
  2566. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  2567. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  2568. return true;
  2569. }
  2570. }
  2571. }
  2572. }
  2573. #endif
  2574. return false;
  2575. }
  2576. void AppleRemoteDevice::handleCallbackInternal()
  2577. {
  2578. int totalValues = 0;
  2579. AbsoluteTime nullTime = { 0, 0 };
  2580. char cookies [12];
  2581. int numCookies = 0;
  2582. while (numCookies < numElementsInArray (cookies))
  2583. {
  2584. IOHIDEventStruct e;
  2585. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  2586. break;
  2587. if ((int) e.elementCookie == 19)
  2588. {
  2589. remoteId = e.value;
  2590. buttonPressed (switched, false);
  2591. }
  2592. else
  2593. {
  2594. totalValues += e.value;
  2595. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  2596. }
  2597. }
  2598. cookies [numCookies++] = 0;
  2599. static const char buttonPatterns[] =
  2600. {
  2601. 14, 7, 6, 5, 14, 7, 6, 5, 0,
  2602. 14, 8, 6, 5, 14, 8, 6, 5, 0,
  2603. 14, 12, 11, 6, 5, 0,
  2604. 14, 13, 11, 6, 5, 0,
  2605. 14, 9, 6, 5, 14, 9, 6, 5, 0,
  2606. 14, 10, 6, 5, 14, 10, 6, 5, 0,
  2607. 14, 6, 5, 4, 2, 0,
  2608. 14, 6, 5, 3, 2, 0,
  2609. 14, 6, 5, 14, 6, 5, 0,
  2610. 18, 14, 6, 5, 18, 14, 6, 5, 0,
  2611. 19, 0
  2612. };
  2613. int buttonNum = (int) menuButton;
  2614. int i = 0;
  2615. while (i < numElementsInArray (buttonPatterns))
  2616. {
  2617. if (strcmp (cookies, buttonPatterns + i) == 0)
  2618. {
  2619. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  2620. break;
  2621. }
  2622. i += strlen (buttonPatterns + i) + 1;
  2623. ++buttonNum;
  2624. }
  2625. }
  2626. //==============================================================================
  2627. #if JUCE_OPENGL
  2628. struct OpenGLContextInfo
  2629. {
  2630. AGLContext renderContext;
  2631. };
  2632. void* juce_createOpenGLContext (OpenGLComponent* component, void* sharedContext)
  2633. {
  2634. jassert (component != 0);
  2635. HIViewComponentPeer* const peer = dynamic_cast <HIViewComponentPeer*> (component->getTopLevelComponent()->getPeer());
  2636. if (peer == 0)
  2637. return 0;
  2638. OpenGLContextInfo* const oc = new OpenGLContextInfo();
  2639. GLint attrib[] = { AGL_RGBA, AGL_DOUBLEBUFFER,
  2640. AGL_RED_SIZE, 8,
  2641. AGL_ALPHA_SIZE, 8,
  2642. AGL_DEPTH_SIZE, 24,
  2643. AGL_CLOSEST_POLICY, AGL_NO_RECOVERY,
  2644. AGL_SAMPLE_BUFFERS_ARB, 1,
  2645. AGL_SAMPLES_ARB, 4,
  2646. AGL_NONE };
  2647. oc->renderContext = aglCreateContext (aglChoosePixelFormat (0, 0, attrib),
  2648. (sharedContext != 0) ? ((OpenGLContextInfo*) sharedContext)->renderContext
  2649. : 0);
  2650. aglSetDrawable (oc->renderContext,
  2651. GetWindowPort (peer->windowRef));
  2652. return oc;
  2653. }
  2654. void juce_updateOpenGLWindowPos (void* context, Component* owner, Component* topComp)
  2655. {
  2656. jassert (context != 0);
  2657. OpenGLContextInfo* const oc = (OpenGLContextInfo*) context;
  2658. GLint bufferRect[4];
  2659. bufferRect[0] = owner->getScreenX() - topComp->getScreenX();
  2660. bufferRect[1] = topComp->getHeight() - (owner->getHeight() + owner->getScreenY() - topComp->getScreenY());
  2661. bufferRect[2] = owner->getWidth();
  2662. bufferRect[3] = owner->getHeight();
  2663. aglSetInteger (oc->renderContext, AGL_BUFFER_RECT, bufferRect);
  2664. aglEnable (oc->renderContext, AGL_BUFFER_RECT);
  2665. }
  2666. void juce_deleteOpenGLContext (void* context)
  2667. {
  2668. OpenGLContextInfo* const oc = (OpenGLContextInfo*) context;
  2669. aglDestroyContext (oc->renderContext);
  2670. delete oc;
  2671. }
  2672. bool juce_makeOpenGLContextCurrent (void* context)
  2673. {
  2674. OpenGLContextInfo* const oc = (OpenGLContextInfo*) context;
  2675. return aglSetCurrentContext ((oc != 0) ? oc->renderContext : 0);
  2676. }
  2677. void juce_swapOpenGLBuffers (void* context)
  2678. {
  2679. OpenGLContextInfo* const oc = (OpenGLContextInfo*) context;
  2680. if (oc != 0)
  2681. aglSwapBuffers (oc->renderContext);
  2682. }
  2683. void juce_repaintOpenGLWindow (void* context)
  2684. {
  2685. }
  2686. #endif
  2687. END_JUCE_NAMESPACE