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.

3368 lines
111KB

  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() throw()
  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. Rectangle r (lastNonFullscreenBounds);
  460. setMinimised (false);
  461. if (fullScreen != shouldBeFullScreen)
  462. {
  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) && keyTranslations [rawKey] != 0)
  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. // (avoid doing this in plugins because of some strange redraw bugs..)
  1167. if (rgn != 0 && JUCEApplication::getInstance() != 0)
  1168. {
  1169. Rect bounds;
  1170. GetRegionBounds (rgn, &bounds);
  1171. clip.origin.x = bounds.left;
  1172. clip.origin.y = bounds.top;
  1173. clip.size.width = bounds.right - bounds.left;
  1174. clip.size.height = bounds.bottom - bounds.top;
  1175. }
  1176. else
  1177. {
  1178. HIViewGetBounds (viewRef, &clip);
  1179. clip.origin.x = 0;
  1180. clip.origin.y = 0;
  1181. }
  1182. #else
  1183. CGRect clip (CGContextGetClipBoundingBox (context));
  1184. #endif
  1185. clip = CGRectIntegral (clip);
  1186. if (clip.origin.x < 0)
  1187. {
  1188. clip.size.width += clip.origin.x;
  1189. clip.origin.x = 0;
  1190. }
  1191. if (clip.origin.y < 0)
  1192. {
  1193. clip.size.height += clip.origin.y;
  1194. clip.origin.y = 0;
  1195. }
  1196. if (! component->isOpaque())
  1197. CGContextClearRect (context, clip);
  1198. repainter->paint (context,
  1199. (int) clip.origin.x, (int) clip.origin.y,
  1200. (int) clip.size.width, (int) clip.size.height);
  1201. if (port != 0)
  1202. {
  1203. CGContextFlush (context);
  1204. QDEndCGContext (port, &context);
  1205. SetPort (oldPort);
  1206. }
  1207. repainter->repaintAnyRemainingRegions();
  1208. return noErr;
  1209. }
  1210. static pascal OSStatus handleWindowEvent (EventHandlerCallRef callRef, EventRef theEvent, void* userData)
  1211. {
  1212. MessageManager::delayWaitCursor();
  1213. HIViewComponentPeer* const peer = (HIViewComponentPeer*) userData;
  1214. const MessageManagerLock messLock;
  1215. if (ComponentPeer::isValidPeer (peer))
  1216. return peer->handleWindowEventForPeer (callRef, theEvent);
  1217. return eventNotHandledErr;
  1218. }
  1219. OSStatus handleWindowEventForPeer (EventHandlerCallRef callRef, EventRef theEvent)
  1220. {
  1221. switch (GetEventClass (theEvent))
  1222. {
  1223. case kEventClassMouse:
  1224. {
  1225. static HIViewComponentPeer* lastMouseDownPeer = 0;
  1226. const UInt32 eventKind = GetEventKind (theEvent);
  1227. HIViewRef view = 0;
  1228. if (eventKind == kEventMouseDragged)
  1229. {
  1230. view = viewRef;
  1231. }
  1232. else
  1233. {
  1234. HIViewGetViewForMouseEvent (HIViewGetRoot (windowRef), theEvent, &view);
  1235. if (view != viewRef)
  1236. {
  1237. if ((eventKind == kEventMouseUp
  1238. || eventKind == kEventMouseExited)
  1239. && ComponentPeer::isValidPeer (lastMouseDownPeer))
  1240. {
  1241. return lastMouseDownPeer->handleMouseEvent (callRef, theEvent);
  1242. }
  1243. return eventNotHandledErr;
  1244. }
  1245. }
  1246. if (eventKind == kEventMouseDown
  1247. || eventKind == kEventMouseDragged
  1248. || eventKind == kEventMouseEntered)
  1249. {
  1250. lastMouseDownPeer = this;
  1251. }
  1252. return handleMouseEvent (callRef, theEvent);
  1253. }
  1254. break;
  1255. case kEventClassWindow:
  1256. return handleWindowClassEvent (theEvent);
  1257. case kEventClassKeyboard:
  1258. if (isFocused())
  1259. return handleKeyEvent (theEvent, 0);
  1260. break;
  1261. case kEventClassTextInput:
  1262. if (isFocused())
  1263. return handleTextInputEvent (theEvent);
  1264. break;
  1265. default:
  1266. break;
  1267. }
  1268. return eventNotHandledErr;
  1269. }
  1270. static pascal OSStatus hiViewEventHandler (EventHandlerCallRef myHandler, EventRef theEvent, void* userData)
  1271. {
  1272. MessageManager::delayWaitCursor();
  1273. const UInt32 eventKind = GetEventKind (theEvent);
  1274. const UInt32 eventClass = GetEventClass (theEvent);
  1275. if (eventClass == kEventClassHIObject)
  1276. {
  1277. switch (eventKind)
  1278. {
  1279. case kEventHIObjectConstruct:
  1280. {
  1281. void* data = juce_calloc (sizeof (void*));
  1282. SetEventParameter (theEvent, kEventParamHIObjectInstance,
  1283. typeVoidPtr, sizeof (void*), &data);
  1284. return noErr;
  1285. }
  1286. case kEventHIObjectInitialize:
  1287. GetEventParameter (theEvent, 'peer', typeVoidPtr, 0, sizeof (void*), 0, (void**) userData);
  1288. return noErr;
  1289. case kEventHIObjectDestruct:
  1290. juce_free (userData);
  1291. return noErr;
  1292. default:
  1293. break;
  1294. }
  1295. }
  1296. else if (eventClass == kEventClassControl)
  1297. {
  1298. HIViewComponentPeer* const peer = *(HIViewComponentPeer**) userData;
  1299. const MessageManagerLock messLock;
  1300. if (! ComponentPeer::isValidPeer (peer))
  1301. return eventNotHandledErr;
  1302. switch (eventKind)
  1303. {
  1304. case kEventControlDraw:
  1305. return peer->hiViewDraw (theEvent);
  1306. case kEventControlBoundsChanged:
  1307. {
  1308. HIRect bounds;
  1309. HIViewGetBounds (peer->viewRef, &bounds);
  1310. peer->repaint (0, 0, roundFloatToInt (bounds.size.width), roundFloatToInt (bounds.size.height));
  1311. peer->handleMovedOrResized();
  1312. return noErr;
  1313. }
  1314. case kEventControlHitTest:
  1315. {
  1316. HIPoint where;
  1317. GetEventParameter (theEvent, kEventParamMouseLocation, typeHIPoint, 0, sizeof (HIPoint), 0, &where);
  1318. HIRect bounds;
  1319. HIViewGetBounds (peer->viewRef, &bounds);
  1320. ControlPartCode part = kControlNoPart;
  1321. if (CGRectContainsPoint (bounds, where))
  1322. part = 1;
  1323. SetEventParameter (theEvent, kEventParamControlPart, typeControlPartCode, sizeof (ControlPartCode), &part);
  1324. return noErr;
  1325. }
  1326. break;
  1327. case kEventControlSetFocusPart:
  1328. {
  1329. ControlPartCode desiredFocus;
  1330. if (GetEventParameter (theEvent, kEventParamControlPart, typeControlPartCode, 0, sizeof (ControlPartCode), 0, &desiredFocus) != noErr)
  1331. break;
  1332. if (desiredFocus == kControlNoPart)
  1333. peer->viewFocusLoss();
  1334. else
  1335. peer->viewFocusGain();
  1336. return noErr;
  1337. }
  1338. break;
  1339. case kEventControlDragEnter:
  1340. {
  1341. #if MACOS_10_2_OR_EARLIER
  1342. enum { kEventParamControlWouldAcceptDrop = 'cldg' };
  1343. #endif
  1344. Boolean accept = true;
  1345. SetEventParameter (theEvent, kEventParamControlWouldAcceptDrop, typeBoolean, sizeof (accept), &accept);
  1346. return noErr;
  1347. }
  1348. case kEventControlDragWithin:
  1349. return noErr;
  1350. case kEventControlDragReceive:
  1351. return peer->handleDragAndDrop (theEvent);
  1352. case kEventControlOwningWindowChanged:
  1353. return peer->ownerWindowChanged (theEvent);
  1354. #if ! MACOS_10_2_OR_EARLIER
  1355. case kEventControlGetFrameMetrics:
  1356. {
  1357. CallNextEventHandler (myHandler, theEvent);
  1358. HIViewFrameMetrics metrics;
  1359. GetEventParameter (theEvent, kEventParamControlFrameMetrics, typeControlFrameMetrics, 0, sizeof (metrics), 0, &metrics);
  1360. metrics.top = metrics.bottom = 0;
  1361. SetEventParameter (theEvent, kEventParamControlFrameMetrics, typeControlFrameMetrics, sizeof (metrics), &metrics);
  1362. return noErr;
  1363. }
  1364. #endif
  1365. case kEventControlInitialize:
  1366. {
  1367. UInt32 features = kControlSupportsDragAndDrop
  1368. | kControlSupportsFocus
  1369. | kControlHandlesTracking
  1370. | kControlSupportsEmbedding
  1371. | (1 << 8) /*kHIViewFeatureGetsFocusOnClick*/;
  1372. SetEventParameter (theEvent, kEventParamControlFeatures, typeUInt32, sizeof (UInt32), &features);
  1373. return noErr;
  1374. }
  1375. default:
  1376. break;
  1377. }
  1378. }
  1379. return eventNotHandledErr;
  1380. }
  1381. WindowRef createNewWindow (const int windowStyleFlags)
  1382. {
  1383. jassert (windowRef == 0);
  1384. static ToolboxObjectClassRef customWindowClass = 0;
  1385. if (customWindowClass == 0)
  1386. {
  1387. // Register our window class
  1388. const EventTypeSpec customTypes[] = { { kEventClassWindow, kEventWindowDrawFrame } };
  1389. UnsignedWide t;
  1390. Microseconds (&t);
  1391. const String randomString ((int) (t.lo & 0x7ffffff));
  1392. const String juceWindowClassName (T("JUCEWindowClass_") + randomString);
  1393. CFStringRef juceWindowClassNameCFString = PlatformUtilities::juceStringToCFString (juceWindowClassName);
  1394. RegisterToolboxObjectClass (juceWindowClassNameCFString,
  1395. 0, 1, customTypes,
  1396. NewEventHandlerUPP (handleFrameRepaintEvent),
  1397. 0, &customWindowClass);
  1398. CFRelease (juceWindowClassNameCFString);
  1399. }
  1400. Rect pos;
  1401. pos.left = getComponent()->getX();
  1402. pos.top = getComponent()->getY();
  1403. pos.right = getComponent()->getRight();
  1404. pos.bottom = getComponent()->getBottom();
  1405. int attributes = kWindowStandardHandlerAttribute | kWindowCompositingAttribute;
  1406. if ((windowStyleFlags & windowHasDropShadow) == 0)
  1407. attributes |= kWindowNoShadowAttribute;
  1408. if ((windowStyleFlags & windowIgnoresMouseClicks) != 0)
  1409. attributes |= kWindowIgnoreClicksAttribute;
  1410. #if ! MACOS_10_3_OR_EARLIER
  1411. if ((windowStyleFlags & windowIsTemporary) != 0)
  1412. attributes |= kWindowDoesNotCycleAttribute;
  1413. #endif
  1414. WindowRef newWindow = 0;
  1415. if ((windowStyleFlags & windowHasTitleBar) == 0)
  1416. {
  1417. attributes |= kWindowCollapseBoxAttribute;
  1418. WindowDefSpec customWindowSpec;
  1419. customWindowSpec.defType = kWindowDefObjectClass;
  1420. customWindowSpec.u.classRef = customWindowClass;
  1421. CreateCustomWindow (&customWindowSpec,
  1422. ((windowStyleFlags & windowIsTemporary) != 0) ? kUtilityWindowClass :
  1423. (getComponent()->isAlwaysOnTop() ? kUtilityWindowClass
  1424. : kDocumentWindowClass),
  1425. attributes,
  1426. &pos,
  1427. &newWindow);
  1428. }
  1429. else
  1430. {
  1431. if ((windowStyleFlags & windowHasCloseButton) != 0)
  1432. attributes |= kWindowCloseBoxAttribute;
  1433. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  1434. attributes |= kWindowCollapseBoxAttribute;
  1435. if ((windowStyleFlags & windowHasMaximiseButton) != 0)
  1436. attributes |= kWindowFullZoomAttribute;
  1437. if ((windowStyleFlags & windowIsResizable) != 0)
  1438. attributes |= kWindowResizableAttribute | kWindowLiveResizeAttribute;
  1439. CreateNewWindow (kDocumentWindowClass, attributes, &pos, &newWindow);
  1440. }
  1441. jassert (newWindow != 0);
  1442. if (newWindow != 0)
  1443. {
  1444. HideWindow (newWindow);
  1445. SetAutomaticControlDragTrackingEnabledForWindow (newWindow, true);
  1446. if (! getComponent()->isOpaque())
  1447. SetWindowAlpha (newWindow, 0.9999999f); // to fool it into giving the window an alpha-channel
  1448. }
  1449. return newWindow;
  1450. }
  1451. OSStatus ownerWindowChanged (EventRef theEvent)
  1452. {
  1453. WindowRef newWindow = 0;
  1454. GetEventParameter (theEvent, kEventParamControlCurrentOwningWindow, typeWindowRef, 0, sizeof (newWindow), 0, &newWindow);
  1455. if (windowRef != newWindow)
  1456. {
  1457. if (eventHandlerRef != 0)
  1458. {
  1459. RemoveEventHandler (eventHandlerRef);
  1460. eventHandlerRef = 0;
  1461. }
  1462. windowRef = newWindow;
  1463. if (windowRef != 0)
  1464. {
  1465. const EventTypeSpec eventTypes[] =
  1466. {
  1467. { kEventClassWindow, kEventWindowBoundsChanged },
  1468. { kEventClassWindow, kEventWindowBoundsChanging },
  1469. { kEventClassWindow, kEventWindowFocusAcquired },
  1470. { kEventClassWindow, kEventWindowFocusRelinquish },
  1471. { kEventClassWindow, kEventWindowCollapsed },
  1472. { kEventClassWindow, kEventWindowExpanded },
  1473. { kEventClassWindow, kEventWindowShown },
  1474. { kEventClassWindow, kEventWindowClose },
  1475. { kEventClassMouse, kEventMouseDown },
  1476. { kEventClassMouse, kEventMouseUp },
  1477. { kEventClassMouse, kEventMouseMoved },
  1478. { kEventClassMouse, kEventMouseDragged },
  1479. { kEventClassMouse, kEventMouseEntered },
  1480. { kEventClassMouse, kEventMouseExited },
  1481. { kEventClassMouse, kEventMouseWheelMoved },
  1482. { kEventClassKeyboard, kEventRawKeyUp },
  1483. { kEventClassKeyboard, kEventRawKeyRepeat },
  1484. { kEventClassKeyboard, kEventRawKeyModifiersChanged },
  1485. { kEventClassTextInput, kEventTextInputUnicodeForKeyEvent }
  1486. };
  1487. static EventHandlerUPP handleWindowEventUPP = 0;
  1488. if (handleWindowEventUPP == 0)
  1489. handleWindowEventUPP = NewEventHandlerUPP (handleWindowEvent);
  1490. InstallWindowEventHandler (windowRef, handleWindowEventUPP,
  1491. GetEventTypeCount (eventTypes), eventTypes,
  1492. (void*) this, (EventHandlerRef*) &eventHandlerRef);
  1493. WindowAttributes attributes;
  1494. GetWindowAttributes (windowRef, &attributes);
  1495. #if MACOS_10_3_OR_EARLIER
  1496. isCompositingWindow = ((attributes & kWindowCompositingAttribute) != 0);
  1497. #else
  1498. isCompositingWindow = HIViewIsCompositingEnabled (viewRef);
  1499. #endif
  1500. MouseCheckTimer::getInstance()->resetMouseMoveChecker();
  1501. }
  1502. }
  1503. resizeViewToFitWindow();
  1504. return noErr;
  1505. }
  1506. void createNewHIView()
  1507. {
  1508. jassert (viewRef == 0);
  1509. if (viewClassRef == 0)
  1510. {
  1511. // Register our HIView class
  1512. EventTypeSpec viewEvents[] =
  1513. {
  1514. { kEventClassHIObject, kEventHIObjectConstruct },
  1515. { kEventClassHIObject, kEventHIObjectInitialize },
  1516. { kEventClassHIObject, kEventHIObjectDestruct },
  1517. { kEventClassControl, kEventControlInitialize },
  1518. { kEventClassControl, kEventControlDraw },
  1519. { kEventClassControl, kEventControlBoundsChanged },
  1520. { kEventClassControl, kEventControlSetFocusPart },
  1521. { kEventClassControl, kEventControlHitTest },
  1522. { kEventClassControl, kEventControlDragEnter },
  1523. { kEventClassControl, kEventControlDragWithin },
  1524. { kEventClassControl, kEventControlDragReceive },
  1525. { kEventClassControl, kEventControlOwningWindowChanged }
  1526. };
  1527. UnsignedWide t;
  1528. Microseconds (&t);
  1529. const String randomString ((int) (t.lo & 0x7ffffff));
  1530. const String juceHiViewClassName (T("JUCEHIViewClass_") + randomString);
  1531. juceHiViewClassNameCFString = PlatformUtilities::juceStringToCFString (juceHiViewClassName);
  1532. HIObjectRegisterSubclass (juceHiViewClassNameCFString,
  1533. kHIViewClassID, 0,
  1534. NewEventHandlerUPP (hiViewEventHandler),
  1535. GetEventTypeCount (viewEvents),
  1536. viewEvents, 0,
  1537. &viewClassRef);
  1538. }
  1539. EventRef event;
  1540. CreateEvent (0, kEventClassHIObject, kEventHIObjectInitialize, GetCurrentEventTime(), kEventAttributeNone, &event);
  1541. void* thisPointer = this;
  1542. SetEventParameter (event, 'peer', typeVoidPtr, sizeof (void*), &thisPointer);
  1543. HIObjectCreate (juceHiViewClassNameCFString, event, (HIObjectRef*) &viewRef);
  1544. SetControlDragTrackingEnabled (viewRef, true);
  1545. if (isSharedWindow)
  1546. {
  1547. setBounds (component->getX(), component->getY(),
  1548. component->getWidth(), component->getHeight(), false);
  1549. }
  1550. }
  1551. };
  1552. bool juce_isHIViewCreatedByJuce (HIViewRef view)
  1553. {
  1554. return juceHiViewClassNameCFString != 0
  1555. && HIObjectIsOfClass ((HIObjectRef) view, juceHiViewClassNameCFString);
  1556. }
  1557. static void trackNextMouseEvent()
  1558. {
  1559. UInt32 mods;
  1560. MouseTrackingResult result;
  1561. ::Point where;
  1562. if (TrackMouseLocationWithOptions ((GrafPtr) -1, 0, 0.01, //kEventDurationForever,
  1563. &where, &mods, &result) != noErr
  1564. || ! ComponentPeer::isValidPeer (juce_currentMouseTrackingPeer))
  1565. {
  1566. juce_currentMouseTrackingPeer = 0;
  1567. return;
  1568. }
  1569. if (result == kMouseTrackingTimedOut)
  1570. return;
  1571. #if MACOS_10_3_OR_EARLIER
  1572. const int x = where.h - juce_currentMouseTrackingPeer->getScreenX();
  1573. const int y = where.v - juce_currentMouseTrackingPeer->getScreenY();
  1574. #else
  1575. HIPoint p;
  1576. p.x = where.h;
  1577. p.y = where.v;
  1578. HIPointConvert (&p, kHICoordSpaceScreenPixel, 0,
  1579. kHICoordSpaceView, ((HIViewComponentPeer*) juce_currentMouseTrackingPeer)->viewRef);
  1580. const int x = p.x;
  1581. const int y = p.y;
  1582. #endif
  1583. if (result == kMouseTrackingMouseDragged)
  1584. {
  1585. updateModifiers (0);
  1586. juce_currentMouseTrackingPeer->handleMouseDrag (x, y, getEventTime (0));
  1587. if (! ComponentPeer::isValidPeer (juce_currentMouseTrackingPeer))
  1588. {
  1589. juce_currentMouseTrackingPeer = 0;
  1590. return;
  1591. }
  1592. }
  1593. else if (result == kMouseTrackingMouseUp
  1594. || result == kMouseTrackingUserCancelled
  1595. || result == kMouseTrackingMouseMoved)
  1596. {
  1597. ComponentPeer* const oldPeer = juce_currentMouseTrackingPeer;
  1598. juce_currentMouseTrackingPeer = 0;
  1599. if (ComponentPeer::isValidPeer (oldPeer))
  1600. {
  1601. const int oldModifiers = currentModifiers;
  1602. currentModifiers &= ~(ModifierKeys::leftButtonModifier | ModifierKeys::rightButtonModifier | ModifierKeys::middleButtonModifier);
  1603. updateModifiers (0);
  1604. oldPeer->handleMouseUp (oldModifiers, x, y, getEventTime (0));
  1605. }
  1606. }
  1607. }
  1608. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  1609. {
  1610. if (juce_currentMouseTrackingPeer != 0)
  1611. trackNextMouseEvent();
  1612. EventRef theEvent;
  1613. if (ReceiveNextEvent (0, 0, (returnIfNoPendingMessages) ? kEventDurationNoWait
  1614. : kEventDurationForever,
  1615. true, &theEvent) == noErr)
  1616. {
  1617. if (GetEventClass (theEvent) == kEventClassAppleEvent)
  1618. {
  1619. EventRecord eventRec;
  1620. if (ConvertEventRefToEventRecord (theEvent, &eventRec))
  1621. AEProcessAppleEvent (&eventRec);
  1622. }
  1623. else
  1624. {
  1625. EventTargetRef theTarget = GetEventDispatcherTarget();
  1626. SendEventToEventTarget (theEvent, theTarget);
  1627. }
  1628. ReleaseEvent (theEvent);
  1629. return true;
  1630. }
  1631. return false;
  1632. }
  1633. //==============================================================================
  1634. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  1635. {
  1636. return new HIViewComponentPeer (this, styleFlags, (HIViewRef) windowToAttachTo);
  1637. }
  1638. //==============================================================================
  1639. void MouseCheckTimer::timerCallback()
  1640. {
  1641. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  1642. return;
  1643. if (Process::isForegroundProcess())
  1644. {
  1645. bool stillOver = false;
  1646. int x = 0, y = 0, w = 0, h = 0;
  1647. int mx = 0, my = 0;
  1648. const bool validWindow = ComponentPeer::isValidPeer (lastPeerUnderMouse);
  1649. if (validWindow)
  1650. {
  1651. lastPeerUnderMouse->getBounds (x, y, w, h, true);
  1652. Desktop::getMousePosition (mx, my);
  1653. stillOver = (mx >= x && my >= y && mx < x + w && my < y + h);
  1654. if (stillOver)
  1655. {
  1656. // check if it's over an embedded HIView
  1657. int rx = mx, ry = my;
  1658. lastPeerUnderMouse->globalPositionToRelative (rx, ry);
  1659. HIPoint hipoint;
  1660. hipoint.x = rx;
  1661. hipoint.y = ry;
  1662. HIViewRef root;
  1663. GetRootControl ((WindowRef) lastPeerUnderMouse->getNativeHandle(), &root);
  1664. HIViewRef hitview;
  1665. if (HIViewGetSubviewHit (root, &hipoint, true, &hitview) == noErr && hitview != 0)
  1666. {
  1667. stillOver = HIObjectIsOfClass ((HIObjectRef) hitview, juceHiViewClassNameCFString);
  1668. }
  1669. }
  1670. }
  1671. if (! stillOver)
  1672. {
  1673. // mouse is outside our windows so set a normal cursor (only
  1674. // if we're running as an app, not a plugin)
  1675. if (JUCEApplication::getInstance() != 0)
  1676. SetThemeCursor (kThemeArrowCursor);
  1677. if (validWindow)
  1678. lastPeerUnderMouse->handleMouseExit (mx - x, my - y, Time::currentTimeMillis());
  1679. if (hasEverHadAMouseMove)
  1680. stopTimer();
  1681. }
  1682. if ((! hasEverHadAMouseMove) && validWindow
  1683. && (mx != lastX || my != lastY))
  1684. {
  1685. lastX = mx;
  1686. lastY = my;
  1687. if (stillOver)
  1688. lastPeerUnderMouse->handleMouseMove (mx - x, my - y, Time::currentTimeMillis());
  1689. }
  1690. }
  1691. }
  1692. //==============================================================================
  1693. // called from juce_Messaging.cpp
  1694. void juce_HandleProcessFocusChange()
  1695. {
  1696. keysCurrentlyDown.clear();
  1697. if (HIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  1698. {
  1699. if (Process::isForegroundProcess())
  1700. currentlyFocusedPeer->handleFocusGain();
  1701. else
  1702. currentlyFocusedPeer->handleFocusLoss();
  1703. }
  1704. }
  1705. static bool performDrag (DragRef drag)
  1706. {
  1707. EventRecord event;
  1708. event.what = mouseDown;
  1709. event.message = 0;
  1710. event.when = TickCount();
  1711. int x, y;
  1712. Desktop::getMousePosition (x, y);
  1713. event.where.h = x;
  1714. event.where.v = y;
  1715. event.modifiers = GetCurrentKeyModifiers();
  1716. RgnHandle rgn = NewRgn();
  1717. RgnHandle rgn2 = NewRgn();
  1718. SetRectRgn (rgn,
  1719. event.where.h - 8, event.where.v - 8,
  1720. event.where.h + 8, event.where.v + 8);
  1721. CopyRgn (rgn, rgn2);
  1722. InsetRgn (rgn2, 1, 1);
  1723. DiffRgn (rgn, rgn2, rgn);
  1724. DisposeRgn (rgn2);
  1725. bool result = TrackDrag (drag, &event, rgn) == noErr;
  1726. DisposeRgn (rgn);
  1727. return result;
  1728. }
  1729. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  1730. {
  1731. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  1732. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  1733. DragRef drag;
  1734. bool result = false;
  1735. if (NewDrag (&drag) == noErr)
  1736. {
  1737. for (int i = 0; i < files.size(); ++i)
  1738. {
  1739. HFSFlavor hfsData;
  1740. if (PlatformUtilities::makeFSSpecFromPath (&hfsData.fileSpec, files[i]))
  1741. {
  1742. FInfo info;
  1743. if (FSpGetFInfo (&hfsData.fileSpec, &info) == noErr)
  1744. {
  1745. hfsData.fileType = info.fdType;
  1746. hfsData.fileCreator = info.fdCreator;
  1747. hfsData.fdFlags = info.fdFlags;
  1748. AddDragItemFlavor (drag, i + 1, kDragFlavorTypeHFS, &hfsData, sizeof (hfsData), 0);
  1749. result = true;
  1750. }
  1751. }
  1752. }
  1753. SetDragAllowableActions (drag, canMoveFiles ? kDragActionAll
  1754. : kDragActionCopy, false);
  1755. if (result)
  1756. result = performDrag (drag);
  1757. DisposeDrag (drag);
  1758. }
  1759. return result;
  1760. }
  1761. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  1762. {
  1763. jassertfalse // not implemented!
  1764. return false;
  1765. }
  1766. //==============================================================================
  1767. bool Process::isForegroundProcess() throw()
  1768. {
  1769. ProcessSerialNumber psn, front;
  1770. GetCurrentProcess (&psn);
  1771. GetFrontProcess (&front);
  1772. Boolean b;
  1773. return (SameProcess (&psn, &front, &b) == noErr) && b;
  1774. }
  1775. //==============================================================================
  1776. bool Desktop::canUseSemiTransparentWindows() throw()
  1777. {
  1778. return true;
  1779. }
  1780. //==============================================================================
  1781. void Desktop::getMousePosition (int& x, int& y) throw()
  1782. {
  1783. CGrafPtr currentPort;
  1784. GetPort (&currentPort);
  1785. if (! IsValidPort (currentPort))
  1786. {
  1787. WindowRef front = FrontWindow();
  1788. if (front != 0)
  1789. {
  1790. SetPortWindowPort (front);
  1791. }
  1792. else
  1793. {
  1794. x = y = 0;
  1795. return;
  1796. }
  1797. }
  1798. ::Point p;
  1799. GetMouse (&p);
  1800. LocalToGlobal (&p);
  1801. x = p.h;
  1802. y = p.v;
  1803. SetPort (currentPort);
  1804. }
  1805. void Desktop::setMousePosition (int x, int y) throw()
  1806. {
  1807. // this rubbish needs to be done around the warp call, to avoid causing a
  1808. // bizarre glitch..
  1809. CGAssociateMouseAndMouseCursorPosition (false);
  1810. CGSetLocalEventsSuppressionInterval (0);
  1811. CGPoint pos = { x, y };
  1812. CGWarpMouseCursorPosition (pos);
  1813. CGAssociateMouseAndMouseCursorPosition (true);
  1814. }
  1815. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  1816. {
  1817. return ModifierKeys (currentModifiers);
  1818. }
  1819. //==============================================================================
  1820. class ScreenSaverDefeater : public Timer,
  1821. public DeletedAtShutdown
  1822. {
  1823. public:
  1824. ScreenSaverDefeater() throw()
  1825. {
  1826. startTimer (10000);
  1827. timerCallback();
  1828. }
  1829. ~ScreenSaverDefeater()
  1830. {
  1831. }
  1832. void timerCallback()
  1833. {
  1834. if (Process::isForegroundProcess())
  1835. UpdateSystemActivity (UsrActivity);
  1836. }
  1837. };
  1838. static ScreenSaverDefeater* screenSaverDefeater = 0;
  1839. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  1840. {
  1841. if (screenSaverDefeater == 0)
  1842. screenSaverDefeater = new ScreenSaverDefeater();
  1843. }
  1844. bool Desktop::isScreenSaverEnabled() throw()
  1845. {
  1846. return screenSaverDefeater == 0;
  1847. }
  1848. //==============================================================================
  1849. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  1850. {
  1851. int mainMonitorIndex = 0;
  1852. CGDirectDisplayID mainDisplayID = CGMainDisplayID();
  1853. CGDisplayCount count = 0;
  1854. CGDirectDisplayID disps [8];
  1855. if (CGGetOnlineDisplayList (numElementsInArray (disps), disps, &count) == noErr)
  1856. {
  1857. for (int i = 0; i < count; ++i)
  1858. {
  1859. if (mainDisplayID == disps[i])
  1860. mainMonitorIndex = monitorCoords.size();
  1861. GDHandle hGDevice;
  1862. if (clipToWorkArea
  1863. && DMGetGDeviceByDisplayID ((DisplayIDType) disps[i], &hGDevice, false) == noErr)
  1864. {
  1865. Rect rect;
  1866. GetAvailableWindowPositioningBounds (hGDevice, &rect);
  1867. monitorCoords.add (Rectangle (rect.left,
  1868. rect.top,
  1869. rect.right - rect.left,
  1870. rect.bottom - rect.top));
  1871. }
  1872. else
  1873. {
  1874. const CGRect r (CGDisplayBounds (disps[i]));
  1875. monitorCoords.add (Rectangle ((int) r.origin.x,
  1876. (int) r.origin.y,
  1877. (int) r.size.width,
  1878. (int) r.size.height));
  1879. }
  1880. }
  1881. }
  1882. // make sure the first in the list is the main monitor
  1883. if (mainMonitorIndex > 0)
  1884. monitorCoords.swap (mainMonitorIndex, 0);
  1885. jassert (monitorCoords.size() > 0);
  1886. if (monitorCoords.size() == 0)
  1887. monitorCoords.add (Rectangle (0, 0, 1024, 768));
  1888. //xxx need to register for display change callbacks
  1889. }
  1890. //==============================================================================
  1891. struct CursorWrapper
  1892. {
  1893. Cursor* cursor;
  1894. ThemeCursor themeCursor;
  1895. };
  1896. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  1897. {
  1898. const int maxW = 16;
  1899. const int maxH = 16;
  1900. const Image* im = &image;
  1901. Image* newIm = 0;
  1902. if (image.getWidth() > maxW || image.getHeight() > maxH)
  1903. {
  1904. im = newIm = image.createCopy (maxW, maxH);
  1905. hotspotX = (hotspotX * maxW) / image.getWidth();
  1906. hotspotY = (hotspotY * maxH) / image.getHeight();
  1907. }
  1908. Cursor* const c = new Cursor();
  1909. c->hotSpot.h = hotspotX;
  1910. c->hotSpot.v = hotspotY;
  1911. for (int y = 0; y < maxH; ++y)
  1912. {
  1913. c->data[y] = 0;
  1914. c->mask[y] = 0;
  1915. for (int x = 0; x < maxW; ++x)
  1916. {
  1917. const Colour pixelColour (im->getPixelAt (15 - x, y));
  1918. if (pixelColour.getAlpha() > 0.5f)
  1919. {
  1920. c->mask[y] |= (1 << x);
  1921. if (pixelColour.getBrightness() < 0.5f)
  1922. c->data[y] |= (1 << x);
  1923. }
  1924. }
  1925. c->data[y] = CFSwapInt16BigToHost (c->data[y]);
  1926. c->mask[y] = CFSwapInt16BigToHost (c->mask[y]);
  1927. }
  1928. if (newIm != 0)
  1929. delete newIm;
  1930. CursorWrapper* const cw = new CursorWrapper();
  1931. cw->cursor = c;
  1932. cw->themeCursor = kThemeArrowCursor;
  1933. return (void*) cw;
  1934. }
  1935. static void* cursorFromData (const unsigned char* data, const int size, int hx, int hy) throw()
  1936. {
  1937. Image* const im = ImageFileFormat::loadFrom ((const char*) data, size);
  1938. jassert (im != 0);
  1939. void* curs = juce_createMouseCursorFromImage (*im, hx, hy);
  1940. delete im;
  1941. return curs;
  1942. }
  1943. const unsigned int kSpecialNoCursor = 'nocr';
  1944. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  1945. {
  1946. ThemeCursor id = kThemeArrowCursor;
  1947. switch (type)
  1948. {
  1949. case MouseCursor::NormalCursor:
  1950. id = kThemeArrowCursor;
  1951. break;
  1952. case MouseCursor::NoCursor:
  1953. id = kSpecialNoCursor;
  1954. break;
  1955. case MouseCursor::DraggingHandCursor:
  1956. {
  1957. 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,
  1958. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  1959. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  1960. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  1961. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  1962. const int cursDataSize = 99;
  1963. return cursorFromData (cursData, cursDataSize, 8, 8);
  1964. }
  1965. break;
  1966. case MouseCursor::CopyingCursor:
  1967. id = kThemeCopyArrowCursor;
  1968. break;
  1969. case MouseCursor::WaitCursor:
  1970. id = kThemeWatchCursor;
  1971. break;
  1972. case MouseCursor::IBeamCursor:
  1973. id = kThemeIBeamCursor;
  1974. break;
  1975. case MouseCursor::PointingHandCursor:
  1976. id = kThemePointingHandCursor;
  1977. break;
  1978. case MouseCursor::LeftRightResizeCursor:
  1979. case MouseCursor::LeftEdgeResizeCursor:
  1980. case MouseCursor::RightEdgeResizeCursor:
  1981. {
  1982. 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,
  1983. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  1984. 16,0,0,2,38,148,143,169,203,237,15,19,0,106,202,64,111,22,32,224,
  1985. 9,78,30,213,121,230,121,146,99,8,142,71,183,189,152,20,27,86,132,231,
  1986. 58,83,0,0,59 };
  1987. const int cursDataSize = 85;
  1988. return cursorFromData (cursData, cursDataSize, 8, 8);
  1989. }
  1990. case MouseCursor::UpDownResizeCursor:
  1991. case MouseCursor::TopEdgeResizeCursor:
  1992. case MouseCursor::BottomEdgeResizeCursor:
  1993. {
  1994. 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,
  1995. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  1996. 16,0,0,2,38,148,111,128,187,16,202,90,152,48,10,55,169,189,192,245,
  1997. 106,121,27,34,142,201,99,158,224,86,154,109,216,61,29,155,105,180,61,190,
  1998. 121,84,0,0,59 };
  1999. const int cursDataSize = 85;
  2000. return cursorFromData (cursData, cursDataSize, 8, 8);
  2001. }
  2002. case MouseCursor::TopLeftCornerResizeCursor:
  2003. case MouseCursor::BottomRightCornerResizeCursor:
  2004. {
  2005. 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,
  2006. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  2007. 16,0,0,2,43,132,15,162,187,16,255,18,99,14,202,217,44,158,213,221,
  2008. 237,9,225,38,94,35,73,5,31,42,170,108,106,174,112,43,195,209,91,185,
  2009. 104,174,131,208,77,66,28,10,0,59 };
  2010. const int cursDataSize = 90;
  2011. return cursorFromData (cursData, cursDataSize, 8, 8);
  2012. }
  2013. case MouseCursor::TopRightCornerResizeCursor:
  2014. case MouseCursor::BottomLeftCornerResizeCursor:
  2015. {
  2016. 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,
  2017. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  2018. 16,0,0,2,45,148,127,160,11,232,16,98,108,14,65,73,107,194,122,223,
  2019. 92,65,141,216,145,134,162,153,221,25,128,73,166,62,173,16,203,237,188,94,
  2020. 120,46,237,105,239,123,48,80,157,2,0,59 };
  2021. const int cursDataSize = 92;
  2022. return cursorFromData (cursData, cursDataSize, 8, 8);
  2023. }
  2024. case MouseCursor::UpDownLeftRightResizeCursor:
  2025. {
  2026. 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,
  2027. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,15,0,
  2028. 15,0,0,2,46,156,63,129,139,1,202,26,152,48,186,73,109,114,65,85,
  2029. 195,37,143,88,93,29,215,101,23,198,178,30,149,158,25,56,134,97,179,61,
  2030. 158,213,126,203,234,99,220,34,56,70,1,0,59,0,0 };
  2031. const int cursDataSize = 93;
  2032. return cursorFromData (cursData, cursDataSize, 7, 7);
  2033. }
  2034. case MouseCursor::CrosshairCursor:
  2035. id = kThemeCrossCursor;
  2036. break;
  2037. }
  2038. CursorWrapper* cw = new CursorWrapper();
  2039. cw->cursor = 0;
  2040. cw->themeCursor = id;
  2041. return (void*) cw;
  2042. }
  2043. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  2044. {
  2045. CursorWrapper* const cw = (CursorWrapper*) cursorHandle;
  2046. if (cw != 0)
  2047. {
  2048. delete cw->cursor;
  2049. delete cw;
  2050. }
  2051. }
  2052. void MouseCursor::showInAllWindows() const throw()
  2053. {
  2054. showInWindow (0);
  2055. }
  2056. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  2057. {
  2058. const CursorWrapper* const cw = (CursorWrapper*) getHandle();
  2059. if (cw != 0)
  2060. {
  2061. static bool isCursorHidden = false;
  2062. static bool showingWaitCursor = false;
  2063. const bool shouldShowWaitCursor = (cw->themeCursor == kThemeWatchCursor);
  2064. const bool shouldHideCursor = (cw->themeCursor == kSpecialNoCursor);
  2065. if (shouldShowWaitCursor != showingWaitCursor
  2066. && Process::isForegroundProcess())
  2067. {
  2068. showingWaitCursor = shouldShowWaitCursor;
  2069. QDDisplayWaitCursor (shouldShowWaitCursor);
  2070. }
  2071. if (shouldHideCursor != isCursorHidden)
  2072. {
  2073. isCursorHidden = shouldHideCursor;
  2074. if (shouldHideCursor)
  2075. HideCursor();
  2076. else
  2077. ShowCursor();
  2078. }
  2079. if (cw->cursor != 0)
  2080. SetCursor (cw->cursor);
  2081. else if (! (shouldShowWaitCursor || shouldHideCursor))
  2082. SetThemeCursor (cw->themeCursor);
  2083. }
  2084. }
  2085. //==============================================================================
  2086. Image* juce_createIconForFile (const File& file)
  2087. {
  2088. return 0;
  2089. }
  2090. //==============================================================================
  2091. class MainMenuHandler;
  2092. static MainMenuHandler* mainMenu = 0;
  2093. class MainMenuHandler : private MenuBarModelListener,
  2094. private DeletedAtShutdown
  2095. {
  2096. public:
  2097. MainMenuHandler() throw()
  2098. : currentModel (0)
  2099. {
  2100. }
  2101. ~MainMenuHandler() throw()
  2102. {
  2103. setMenu (0);
  2104. jassert (mainMenu == this);
  2105. mainMenu = 0;
  2106. }
  2107. void setMenu (MenuBarModel* const newMenuBarModel) throw()
  2108. {
  2109. if (currentModel != newMenuBarModel)
  2110. {
  2111. if (currentModel != 0)
  2112. currentModel->removeListener (this);
  2113. currentModel = newMenuBarModel;
  2114. if (currentModel != 0)
  2115. currentModel->addListener (this);
  2116. menuBarItemsChanged (0);
  2117. }
  2118. }
  2119. void menuBarItemsChanged (MenuBarModel*)
  2120. {
  2121. ClearMenuBar();
  2122. if (currentModel != 0)
  2123. {
  2124. int id = 1000;
  2125. const StringArray menuNames (currentModel->getMenuBarNames());
  2126. for (int i = 0; i < menuNames.size(); ++i)
  2127. {
  2128. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  2129. MenuRef m = createMenu (menu, menuNames [i], id, i);
  2130. InsertMenu (m, 0);
  2131. CFRelease (m);
  2132. }
  2133. }
  2134. }
  2135. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  2136. {
  2137. MenuRef menu = 0;
  2138. MenuItemIndex index = 0;
  2139. GetIndMenuItemWithCommandID (0, info.commandID, 1, &menu, &index);
  2140. FlashMenuBar (GetMenuID (menu));
  2141. FlashMenuBar (GetMenuID (menu));
  2142. }
  2143. void invoke (const int id, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  2144. {
  2145. if (currentModel != 0)
  2146. {
  2147. if (commandManager != 0)
  2148. {
  2149. ApplicationCommandTarget::InvocationInfo info (id);
  2150. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  2151. commandManager->invoke (info, true);
  2152. }
  2153. currentModel->menuItemSelected (id, topLevelIndex);
  2154. }
  2155. }
  2156. MenuBarModel* currentModel;
  2157. private:
  2158. static MenuRef createMenu (const PopupMenu menu,
  2159. const String& menuName,
  2160. int& id,
  2161. const int topLevelIndex)
  2162. {
  2163. MenuRef m = 0;
  2164. if (CreateNewMenu (id++, kMenuAttrAutoDisable, &m) == noErr)
  2165. {
  2166. CFStringRef name = PlatformUtilities::juceStringToCFString (menuName);
  2167. SetMenuTitleWithCFString (m, name);
  2168. CFRelease (name);
  2169. PopupMenu::MenuItemIterator iter (menu);
  2170. while (iter.next())
  2171. {
  2172. MenuItemIndex index = 0;
  2173. int flags = kMenuAttrAutoDisable | kMenuItemAttrIgnoreMeta | kMenuItemAttrNotPreviousAlternate;
  2174. if (! iter.isEnabled)
  2175. flags |= kMenuItemAttrDisabled;
  2176. CFStringRef text = PlatformUtilities::juceStringToCFString (iter.itemName.upToFirstOccurrenceOf (T("<end>"), false, true));
  2177. if (iter.isSeparator)
  2178. {
  2179. AppendMenuItemTextWithCFString (m, text, kMenuItemAttrSeparator, 0, &index);
  2180. }
  2181. else if (iter.isSectionHeader)
  2182. {
  2183. AppendMenuItemTextWithCFString (m, text, kMenuItemAttrSectionHeader, 0, &index);
  2184. }
  2185. else if (iter.subMenu != 0)
  2186. {
  2187. AppendMenuItemTextWithCFString (m, text, flags, id++, &index);
  2188. MenuRef sub = createMenu (*iter.subMenu, iter.itemName, id, topLevelIndex);
  2189. SetMenuItemHierarchicalMenu (m, index, sub);
  2190. CFRelease (sub);
  2191. }
  2192. else
  2193. {
  2194. AppendMenuItemTextWithCFString (m, text, flags, iter.itemId, &index);
  2195. if (iter.isTicked)
  2196. CheckMenuItem (m, index, true);
  2197. SetMenuItemProperty (m, index, 'juce', 'apcm', sizeof (void*), &iter.commandManager);
  2198. SetMenuItemProperty (m, index, 'juce', 'topi', sizeof (int), &topLevelIndex);
  2199. if (iter.commandManager != 0)
  2200. {
  2201. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  2202. ->getKeyPressesAssignedToCommand (iter.itemId));
  2203. if (keyPresses.size() > 0)
  2204. {
  2205. const KeyPress& kp = keyPresses.getUnchecked(0);
  2206. int mods = 0;
  2207. if (kp.getModifiers().isShiftDown())
  2208. mods |= kMenuShiftModifier;
  2209. if (kp.getModifiers().isCtrlDown())
  2210. mods |= kMenuControlModifier;
  2211. if (kp.getModifiers().isAltDown())
  2212. mods |= kMenuOptionModifier;
  2213. if (! kp.getModifiers().isCommandDown())
  2214. mods |= kMenuNoCommandModifier;
  2215. tchar keyCode = (tchar) kp.getKeyCode();
  2216. if (kp.getKeyCode() >= KeyPress::numberPad0
  2217. && kp.getKeyCode() <= KeyPress::numberPad9)
  2218. {
  2219. keyCode = (tchar) ((T('0') - KeyPress::numberPad0) + kp.getKeyCode());
  2220. }
  2221. SetMenuItemCommandKey (m, index, true, 255);
  2222. if (CharacterFunctions::isLetterOrDigit (keyCode)
  2223. || CharacterFunctions::indexOfChar (T(",.;/\\'[]=-+_<>?{}\":"), keyCode, false) >= 0)
  2224. {
  2225. SetMenuItemModifiers (m, index, mods);
  2226. SetMenuItemCommandKey (m, index, false, CharacterFunctions::toUpperCase (keyCode));
  2227. }
  2228. else
  2229. {
  2230. const SInt16 glyph = getGlyphForKeyCode (kp.getKeyCode());
  2231. if (glyph != 0)
  2232. {
  2233. SetMenuItemModifiers (m, index, mods);
  2234. SetMenuItemKeyGlyph (m, index, glyph);
  2235. }
  2236. }
  2237. // if we set the key glyph to be a text char, and enable virtual
  2238. // key triggering, it stops the menu automatically triggering the callback
  2239. ChangeMenuItemAttributes (m, index, kMenuItemAttrUseVirtualKey, 0);
  2240. }
  2241. }
  2242. }
  2243. CFRelease (text);
  2244. }
  2245. }
  2246. return m;
  2247. }
  2248. static SInt16 getGlyphForKeyCode (const int keyCode) throw()
  2249. {
  2250. if (keyCode == KeyPress::spaceKey)
  2251. return kMenuSpaceGlyph;
  2252. else if (keyCode == KeyPress::returnKey)
  2253. return kMenuReturnGlyph;
  2254. else if (keyCode == KeyPress::escapeKey)
  2255. return kMenuEscapeGlyph;
  2256. else if (keyCode == KeyPress::backspaceKey)
  2257. return kMenuDeleteLeftGlyph;
  2258. else if (keyCode == KeyPress::leftKey)
  2259. return kMenuLeftArrowGlyph;
  2260. else if (keyCode == KeyPress::rightKey)
  2261. return kMenuRightArrowGlyph;
  2262. else if (keyCode == KeyPress::upKey)
  2263. return kMenuUpArrowGlyph;
  2264. else if (keyCode == KeyPress::downKey)
  2265. return kMenuDownArrowGlyph;
  2266. else if (keyCode == KeyPress::pageUpKey)
  2267. return kMenuPageUpGlyph;
  2268. else if (keyCode == KeyPress::pageDownKey)
  2269. return kMenuPageDownGlyph;
  2270. else if (keyCode == KeyPress::endKey)
  2271. return kMenuSoutheastArrowGlyph;
  2272. else if (keyCode == KeyPress::homeKey)
  2273. return kMenuNorthwestArrowGlyph;
  2274. else if (keyCode == KeyPress::deleteKey)
  2275. return kMenuDeleteRightGlyph;
  2276. else if (keyCode == KeyPress::tabKey)
  2277. return kMenuTabRightGlyph;
  2278. else if (keyCode == KeyPress::F1Key)
  2279. return kMenuF1Glyph;
  2280. else if (keyCode == KeyPress::F2Key)
  2281. return kMenuF2Glyph;
  2282. else if (keyCode == KeyPress::F3Key)
  2283. return kMenuF3Glyph;
  2284. else if (keyCode == KeyPress::F4Key)
  2285. return kMenuF4Glyph;
  2286. else if (keyCode == KeyPress::F5Key)
  2287. return kMenuF5Glyph;
  2288. else if (keyCode == KeyPress::F6Key)
  2289. return kMenuF6Glyph;
  2290. else if (keyCode == KeyPress::F7Key)
  2291. return kMenuF7Glyph;
  2292. else if (keyCode == KeyPress::F8Key)
  2293. return kMenuF8Glyph;
  2294. else if (keyCode == KeyPress::F9Key)
  2295. return kMenuF9Glyph;
  2296. else if (keyCode == KeyPress::F10Key)
  2297. return kMenuF10Glyph;
  2298. else if (keyCode == KeyPress::F11Key)
  2299. return kMenuF11Glyph;
  2300. else if (keyCode == KeyPress::F12Key)
  2301. return kMenuF12Glyph;
  2302. else if (keyCode == KeyPress::F13Key)
  2303. return kMenuF13Glyph;
  2304. else if (keyCode == KeyPress::F14Key)
  2305. return kMenuF14Glyph;
  2306. else if (keyCode == KeyPress::F15Key)
  2307. return kMenuF15Glyph;
  2308. return 0;
  2309. }
  2310. };
  2311. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel) throw()
  2312. {
  2313. if (getMacMainMenu() != newMenuBarModel)
  2314. {
  2315. if (newMenuBarModel == 0)
  2316. {
  2317. delete mainMenu;
  2318. jassert (mainMenu == 0); // should be zeroed in the destructor
  2319. }
  2320. else
  2321. {
  2322. if (mainMenu == 0)
  2323. mainMenu = new MainMenuHandler();
  2324. mainMenu->setMenu (newMenuBarModel);
  2325. }
  2326. }
  2327. }
  2328. MenuBarModel* MenuBarModel::getMacMainMenu() throw()
  2329. {
  2330. return mainMenu != 0 ? mainMenu->currentModel : 0;
  2331. }
  2332. // these functions are called externally from the message handling code
  2333. void juce_MainMenuAboutToBeUsed()
  2334. {
  2335. // force an update of the items just before the menu appears..
  2336. if (mainMenu != 0)
  2337. mainMenu->menuBarItemsChanged (0);
  2338. }
  2339. void juce_InvokeMainMenuCommand (const HICommand& command)
  2340. {
  2341. if (mainMenu != 0)
  2342. {
  2343. ApplicationCommandManager* commandManager = 0;
  2344. int topLevelIndex = 0;
  2345. if (GetMenuItemProperty (command.menu.menuRef, command.menu.menuItemIndex,
  2346. 'juce', 'apcm', sizeof (commandManager), 0, &commandManager) == noErr
  2347. && GetMenuItemProperty (command.menu.menuRef, command.menu.menuItemIndex,
  2348. 'juce', 'topi', sizeof (topLevelIndex), 0, &topLevelIndex) == noErr)
  2349. {
  2350. mainMenu->invoke (command.commandID, commandManager, topLevelIndex);
  2351. }
  2352. }
  2353. }
  2354. //==============================================================================
  2355. void PlatformUtilities::beep()
  2356. {
  2357. SysBeep (30);
  2358. }
  2359. //==============================================================================
  2360. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  2361. {
  2362. ClearCurrentScrap();
  2363. ScrapRef ref;
  2364. GetCurrentScrap (&ref);
  2365. const int len = text.length();
  2366. const int numBytes = sizeof (UniChar) * len;
  2367. UniChar* const temp = (UniChar*) juce_calloc (numBytes);
  2368. for (int i = 0; i < len; ++i)
  2369. temp[i] = (UniChar) text[i];
  2370. PutScrapFlavor (ref,
  2371. kScrapFlavorTypeUnicode,
  2372. kScrapFlavorMaskNone,
  2373. numBytes,
  2374. temp);
  2375. juce_free (temp);
  2376. }
  2377. const String SystemClipboard::getTextFromClipboard() throw()
  2378. {
  2379. String result;
  2380. ScrapRef ref;
  2381. GetCurrentScrap (&ref);
  2382. Size size = 0;
  2383. if (GetScrapFlavorSize (ref, kScrapFlavorTypeUnicode, &size) == noErr
  2384. && size > 0)
  2385. {
  2386. void* const data = juce_calloc (size + 8);
  2387. if (GetScrapFlavorData (ref, kScrapFlavorTypeUnicode, &size, data) == noErr)
  2388. {
  2389. result = PlatformUtilities::convertUTF16ToString ((UniChar*) data);
  2390. }
  2391. juce_free (data);
  2392. }
  2393. return result;
  2394. }
  2395. //==============================================================================
  2396. bool AlertWindow::showNativeDialogBox (const String& title,
  2397. const String& bodyText,
  2398. bool isOkCancel)
  2399. {
  2400. Str255 tit, txt;
  2401. PlatformUtilities::copyToStr255 (tit, title);
  2402. PlatformUtilities::copyToStr255 (txt, bodyText);
  2403. AlertStdAlertParamRec ar;
  2404. ar.movable = true;
  2405. ar.helpButton = false;
  2406. ar.filterProc = 0;
  2407. ar.defaultText = (const unsigned char*)-1;
  2408. ar.cancelText = (const unsigned char*)((isOkCancel) ? -1 : 0);
  2409. ar.otherText = 0;
  2410. ar.defaultButton = kAlertStdAlertOKButton;
  2411. ar.cancelButton = 0;
  2412. ar.position = kWindowDefaultPosition;
  2413. SInt16 result;
  2414. StandardAlert (kAlertNoteAlert, tit, txt, &ar, &result);
  2415. return result == kAlertStdAlertOKButton;
  2416. }
  2417. //==============================================================================
  2418. const int KeyPress::spaceKey = ' ';
  2419. const int KeyPress::returnKey = kReturnCharCode;
  2420. const int KeyPress::escapeKey = kEscapeCharCode;
  2421. const int KeyPress::backspaceKey = kBackspaceCharCode;
  2422. const int KeyPress::leftKey = kLeftArrowCharCode;
  2423. const int KeyPress::rightKey = kRightArrowCharCode;
  2424. const int KeyPress::upKey = kUpArrowCharCode;
  2425. const int KeyPress::downKey = kDownArrowCharCode;
  2426. const int KeyPress::pageUpKey = kPageUpCharCode;
  2427. const int KeyPress::pageDownKey = kPageDownCharCode;
  2428. const int KeyPress::endKey = kEndCharCode;
  2429. const int KeyPress::homeKey = kHomeCharCode;
  2430. const int KeyPress::deleteKey = kDeleteCharCode;
  2431. const int KeyPress::insertKey = -1;
  2432. const int KeyPress::tabKey = kTabCharCode;
  2433. const int KeyPress::F1Key = 0x10110;
  2434. const int KeyPress::F2Key = 0x10111;
  2435. const int KeyPress::F3Key = 0x10112;
  2436. const int KeyPress::F4Key = 0x10113;
  2437. const int KeyPress::F5Key = 0x10114;
  2438. const int KeyPress::F6Key = 0x10115;
  2439. const int KeyPress::F7Key = 0x10116;
  2440. const int KeyPress::F8Key = 0x10117;
  2441. const int KeyPress::F9Key = 0x10118;
  2442. const int KeyPress::F10Key = 0x10119;
  2443. const int KeyPress::F11Key = 0x1011a;
  2444. const int KeyPress::F12Key = 0x1011b;
  2445. const int KeyPress::F13Key = 0x1011c;
  2446. const int KeyPress::F14Key = 0x1011d;
  2447. const int KeyPress::F15Key = 0x1011e;
  2448. const int KeyPress::F16Key = 0x1011f;
  2449. const int KeyPress::numberPad0 = 0x30020;
  2450. const int KeyPress::numberPad1 = 0x30021;
  2451. const int KeyPress::numberPad2 = 0x30022;
  2452. const int KeyPress::numberPad3 = 0x30023;
  2453. const int KeyPress::numberPad4 = 0x30024;
  2454. const int KeyPress::numberPad5 = 0x30025;
  2455. const int KeyPress::numberPad6 = 0x30026;
  2456. const int KeyPress::numberPad7 = 0x30027;
  2457. const int KeyPress::numberPad8 = 0x30028;
  2458. const int KeyPress::numberPad9 = 0x30029;
  2459. const int KeyPress::numberPadAdd = 0x3002a;
  2460. const int KeyPress::numberPadSubtract = 0x3002b;
  2461. const int KeyPress::numberPadMultiply = 0x3002c;
  2462. const int KeyPress::numberPadDivide = 0x3002d;
  2463. const int KeyPress::numberPadSeparator = 0x3002e;
  2464. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  2465. const int KeyPress::numberPadEquals = 0x30030;
  2466. const int KeyPress::numberPadDelete = 0x30031;
  2467. const int KeyPress::playKey = 0x30000;
  2468. const int KeyPress::stopKey = 0x30001;
  2469. const int KeyPress::fastForwardKey = 0x30002;
  2470. const int KeyPress::rewindKey = 0x30003;
  2471. //==============================================================================
  2472. AppleRemoteDevice::AppleRemoteDevice()
  2473. : device (0),
  2474. queue (0),
  2475. remoteId (0)
  2476. {
  2477. }
  2478. AppleRemoteDevice::~AppleRemoteDevice()
  2479. {
  2480. stop();
  2481. }
  2482. static io_object_t getAppleRemoteDevice() throw()
  2483. {
  2484. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  2485. io_iterator_t iter = 0;
  2486. io_object_t iod = 0;
  2487. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  2488. && iter != 0)
  2489. {
  2490. iod = IOIteratorNext (iter);
  2491. }
  2492. IOObjectRelease (iter);
  2493. return iod;
  2494. }
  2495. static bool createAppleRemoteInterface (io_object_t iod, void** device) throw()
  2496. {
  2497. jassert (*device == 0);
  2498. io_name_t classname;
  2499. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  2500. {
  2501. IOCFPlugInInterface** cfPlugInInterface = 0;
  2502. SInt32 score = 0;
  2503. if (IOCreatePlugInInterfaceForService (iod,
  2504. kIOHIDDeviceUserClientTypeID,
  2505. kIOCFPlugInInterfaceID,
  2506. &cfPlugInInterface,
  2507. &score) == kIOReturnSuccess)
  2508. {
  2509. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  2510. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  2511. device);
  2512. (void) hr;
  2513. (*cfPlugInInterface)->Release (cfPlugInInterface);
  2514. }
  2515. }
  2516. return *device != 0;
  2517. }
  2518. bool AppleRemoteDevice::start (const bool inExclusiveMode) throw()
  2519. {
  2520. if (queue != 0)
  2521. return true;
  2522. stop();
  2523. bool result = false;
  2524. io_object_t iod = getAppleRemoteDevice();
  2525. if (iod != 0)
  2526. {
  2527. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  2528. result = true;
  2529. else
  2530. stop();
  2531. IOObjectRelease (iod);
  2532. }
  2533. return result;
  2534. }
  2535. void AppleRemoteDevice::stop() throw()
  2536. {
  2537. if (queue != 0)
  2538. {
  2539. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  2540. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  2541. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  2542. queue = 0;
  2543. }
  2544. if (device != 0)
  2545. {
  2546. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  2547. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  2548. device = 0;
  2549. }
  2550. }
  2551. bool AppleRemoteDevice::isActive() const throw()
  2552. {
  2553. return queue != 0;
  2554. }
  2555. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  2556. {
  2557. if (result == kIOReturnSuccess)
  2558. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  2559. }
  2560. bool AppleRemoteDevice::open (const bool openInExclusiveMode) throw()
  2561. {
  2562. #if ! MACOS_10_2_OR_EARLIER
  2563. Array <int> cookies;
  2564. CFArrayRef elements;
  2565. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  2566. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  2567. return false;
  2568. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  2569. {
  2570. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  2571. // get the cookie
  2572. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  2573. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  2574. continue;
  2575. long number;
  2576. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  2577. continue;
  2578. cookies.add ((int) number);
  2579. }
  2580. CFRelease (elements);
  2581. if ((*(IOHIDDeviceInterface**) device)
  2582. ->open ((IOHIDDeviceInterface**) device,
  2583. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  2584. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  2585. {
  2586. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  2587. if (queue != 0)
  2588. {
  2589. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  2590. for (int i = 0; i < cookies.size(); ++i)
  2591. {
  2592. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  2593. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  2594. }
  2595. CFRunLoopSourceRef eventSource;
  2596. if ((*(IOHIDQueueInterface**) queue)
  2597. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  2598. {
  2599. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  2600. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  2601. {
  2602. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  2603. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  2604. return true;
  2605. }
  2606. }
  2607. }
  2608. }
  2609. #endif
  2610. return false;
  2611. }
  2612. void AppleRemoteDevice::handleCallbackInternal()
  2613. {
  2614. int totalValues = 0;
  2615. AbsoluteTime nullTime = { 0, 0 };
  2616. char cookies [12];
  2617. int numCookies = 0;
  2618. while (numCookies < numElementsInArray (cookies))
  2619. {
  2620. IOHIDEventStruct e;
  2621. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  2622. break;
  2623. if ((int) e.elementCookie == 19)
  2624. {
  2625. remoteId = e.value;
  2626. buttonPressed (switched, false);
  2627. }
  2628. else
  2629. {
  2630. totalValues += e.value;
  2631. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  2632. }
  2633. }
  2634. cookies [numCookies++] = 0;
  2635. static const char buttonPatterns[] =
  2636. {
  2637. 14, 7, 6, 5, 14, 7, 6, 5, 0,
  2638. 14, 8, 6, 5, 14, 8, 6, 5, 0,
  2639. 14, 12, 11, 6, 5, 0,
  2640. 14, 13, 11, 6, 5, 0,
  2641. 14, 9, 6, 5, 14, 9, 6, 5, 0,
  2642. 14, 10, 6, 5, 14, 10, 6, 5, 0,
  2643. 14, 6, 5, 4, 2, 0,
  2644. 14, 6, 5, 3, 2, 0,
  2645. 14, 6, 5, 14, 6, 5, 0,
  2646. 18, 14, 6, 5, 18, 14, 6, 5, 0,
  2647. 19, 0
  2648. };
  2649. int buttonNum = (int) menuButton;
  2650. int i = 0;
  2651. while (i < numElementsInArray (buttonPatterns))
  2652. {
  2653. if (strcmp (cookies, buttonPatterns + i) == 0)
  2654. {
  2655. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  2656. break;
  2657. }
  2658. i += strlen (buttonPatterns + i) + 1;
  2659. ++buttonNum;
  2660. }
  2661. }
  2662. //==============================================================================
  2663. #if JUCE_OPENGL
  2664. struct OpenGLContextInfo
  2665. {
  2666. AGLContext renderContext;
  2667. };
  2668. void* juce_createOpenGLContext (OpenGLComponent* component, void* sharedContext)
  2669. {
  2670. jassert (component != 0);
  2671. HIViewComponentPeer* const peer = dynamic_cast <HIViewComponentPeer*> (component->getTopLevelComponent()->getPeer());
  2672. if (peer == 0)
  2673. return 0;
  2674. OpenGLContextInfo* const oc = new OpenGLContextInfo();
  2675. GLint attrib[] = { AGL_RGBA, AGL_DOUBLEBUFFER,
  2676. AGL_RED_SIZE, 8,
  2677. AGL_ALPHA_SIZE, 8,
  2678. AGL_DEPTH_SIZE, 24,
  2679. AGL_CLOSEST_POLICY, AGL_NO_RECOVERY,
  2680. AGL_SAMPLE_BUFFERS_ARB, 1,
  2681. AGL_SAMPLES_ARB, 4,
  2682. AGL_NONE };
  2683. oc->renderContext = aglCreateContext (aglChoosePixelFormat (0, 0, attrib),
  2684. (sharedContext != 0) ? ((OpenGLContextInfo*) sharedContext)->renderContext
  2685. : 0);
  2686. aglSetDrawable (oc->renderContext,
  2687. GetWindowPort (peer->windowRef));
  2688. return oc;
  2689. }
  2690. void juce_updateOpenGLWindowPos (void* context, Component* owner, Component* topComp)
  2691. {
  2692. jassert (context != 0);
  2693. OpenGLContextInfo* const oc = (OpenGLContextInfo*) context;
  2694. GLint bufferRect[4];
  2695. bufferRect[0] = owner->getScreenX() - topComp->getScreenX();
  2696. bufferRect[1] = topComp->getHeight() - (owner->getHeight() + owner->getScreenY() - topComp->getScreenY());
  2697. bufferRect[2] = owner->getWidth();
  2698. bufferRect[3] = owner->getHeight();
  2699. aglSetInteger (oc->renderContext, AGL_BUFFER_RECT, bufferRect);
  2700. aglEnable (oc->renderContext, AGL_BUFFER_RECT);
  2701. }
  2702. void juce_deleteOpenGLContext (void* context)
  2703. {
  2704. OpenGLContextInfo* const oc = (OpenGLContextInfo*) context;
  2705. aglDestroyContext (oc->renderContext);
  2706. delete oc;
  2707. }
  2708. bool juce_makeOpenGLContextCurrent (void* context)
  2709. {
  2710. OpenGLContextInfo* const oc = (OpenGLContextInfo*) context;
  2711. return aglSetCurrentContext ((oc != 0) ? oc->renderContext : 0);
  2712. }
  2713. void juce_swapOpenGLBuffers (void* context)
  2714. {
  2715. OpenGLContextInfo* const oc = (OpenGLContextInfo*) context;
  2716. if (oc != 0)
  2717. aglSwapBuffers (oc->renderContext);
  2718. }
  2719. void juce_repaintOpenGLWindow (void* context)
  2720. {
  2721. }
  2722. #endif
  2723. END_JUCE_NAMESPACE