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.

3385 lines
112KB

  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. bool juce_isWindowCreatedByJuce (WindowRef window)
  1558. {
  1559. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  1560. if (ComponentPeer::getPeer(i)->getNativeHandle() == window)
  1561. return true;
  1562. return false;
  1563. }
  1564. static void trackNextMouseEvent()
  1565. {
  1566. UInt32 mods;
  1567. MouseTrackingResult result;
  1568. ::Point where;
  1569. if (TrackMouseLocationWithOptions ((GrafPtr) -1, 0, 0.01, //kEventDurationForever,
  1570. &where, &mods, &result) != noErr
  1571. || ! ComponentPeer::isValidPeer (juce_currentMouseTrackingPeer))
  1572. {
  1573. juce_currentMouseTrackingPeer = 0;
  1574. return;
  1575. }
  1576. if (result == kMouseTrackingTimedOut)
  1577. return;
  1578. #if MACOS_10_3_OR_EARLIER
  1579. const int x = where.h - juce_currentMouseTrackingPeer->getScreenX();
  1580. const int y = where.v - juce_currentMouseTrackingPeer->getScreenY();
  1581. #else
  1582. HIPoint p;
  1583. p.x = where.h;
  1584. p.y = where.v;
  1585. HIPointConvert (&p, kHICoordSpaceScreenPixel, 0,
  1586. kHICoordSpaceView, ((HIViewComponentPeer*) juce_currentMouseTrackingPeer)->viewRef);
  1587. const int x = p.x;
  1588. const int y = p.y;
  1589. #endif
  1590. if (result == kMouseTrackingMouseDragged)
  1591. {
  1592. updateModifiers (0);
  1593. juce_currentMouseTrackingPeer->handleMouseDrag (x, y, getEventTime (0));
  1594. if (! ComponentPeer::isValidPeer (juce_currentMouseTrackingPeer))
  1595. {
  1596. juce_currentMouseTrackingPeer = 0;
  1597. return;
  1598. }
  1599. }
  1600. else if (result == kMouseTrackingMouseUp
  1601. || result == kMouseTrackingUserCancelled
  1602. || result == kMouseTrackingMouseMoved)
  1603. {
  1604. ComponentPeer* const oldPeer = juce_currentMouseTrackingPeer;
  1605. juce_currentMouseTrackingPeer = 0;
  1606. if (ComponentPeer::isValidPeer (oldPeer))
  1607. {
  1608. const int oldModifiers = currentModifiers;
  1609. currentModifiers &= ~(ModifierKeys::leftButtonModifier | ModifierKeys::rightButtonModifier | ModifierKeys::middleButtonModifier);
  1610. updateModifiers (0);
  1611. oldPeer->handleMouseUp (oldModifiers, x, y, getEventTime (0));
  1612. }
  1613. }
  1614. }
  1615. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  1616. {
  1617. if (juce_currentMouseTrackingPeer != 0)
  1618. trackNextMouseEvent();
  1619. EventRef theEvent;
  1620. if (ReceiveNextEvent (0, 0, (returnIfNoPendingMessages) ? kEventDurationNoWait
  1621. : kEventDurationForever,
  1622. true, &theEvent) == noErr)
  1623. {
  1624. if (GetEventClass (theEvent) == kEventClassAppleEvent)
  1625. {
  1626. EventRecord eventRec;
  1627. if (ConvertEventRefToEventRecord (theEvent, &eventRec))
  1628. AEProcessAppleEvent (&eventRec);
  1629. }
  1630. else
  1631. {
  1632. EventTargetRef theTarget = GetEventDispatcherTarget();
  1633. SendEventToEventTarget (theEvent, theTarget);
  1634. }
  1635. ReleaseEvent (theEvent);
  1636. return true;
  1637. }
  1638. return false;
  1639. }
  1640. //==============================================================================
  1641. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  1642. {
  1643. return new HIViewComponentPeer (this, styleFlags, (HIViewRef) windowToAttachTo);
  1644. }
  1645. //==============================================================================
  1646. void MouseCheckTimer::timerCallback()
  1647. {
  1648. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  1649. return;
  1650. if (Process::isForegroundProcess())
  1651. {
  1652. bool stillOver = false;
  1653. int x = 0, y = 0, w = 0, h = 0;
  1654. int mx = 0, my = 0;
  1655. const bool validWindow = ComponentPeer::isValidPeer (lastPeerUnderMouse);
  1656. if (validWindow)
  1657. {
  1658. lastPeerUnderMouse->getBounds (x, y, w, h, true);
  1659. Desktop::getMousePosition (mx, my);
  1660. stillOver = (mx >= x && my >= y && mx < x + w && my < y + h);
  1661. if (stillOver)
  1662. {
  1663. // check if it's over an embedded HIView
  1664. int rx = mx, ry = my;
  1665. lastPeerUnderMouse->globalPositionToRelative (rx, ry);
  1666. HIPoint hipoint;
  1667. hipoint.x = rx;
  1668. hipoint.y = ry;
  1669. HIViewRef root;
  1670. GetRootControl ((WindowRef) lastPeerUnderMouse->getNativeHandle(), &root);
  1671. HIViewRef hitview;
  1672. if (HIViewGetSubviewHit (root, &hipoint, true, &hitview) == noErr && hitview != 0)
  1673. {
  1674. stillOver = HIObjectIsOfClass ((HIObjectRef) hitview, juceHiViewClassNameCFString);
  1675. }
  1676. }
  1677. }
  1678. if (! stillOver)
  1679. {
  1680. // mouse is outside our windows so set a normal cursor (only
  1681. // if we're running as an app, not a plugin)
  1682. if (JUCEApplication::getInstance() != 0)
  1683. SetThemeCursor (kThemeArrowCursor);
  1684. if (validWindow)
  1685. lastPeerUnderMouse->handleMouseExit (mx - x, my - y, Time::currentTimeMillis());
  1686. if (hasEverHadAMouseMove)
  1687. stopTimer();
  1688. }
  1689. if ((! hasEverHadAMouseMove) && validWindow
  1690. && (mx != lastX || my != lastY))
  1691. {
  1692. lastX = mx;
  1693. lastY = my;
  1694. if (stillOver)
  1695. lastPeerUnderMouse->handleMouseMove (mx - x, my - y, Time::currentTimeMillis());
  1696. }
  1697. }
  1698. }
  1699. //==============================================================================
  1700. // called from juce_Messaging.cpp
  1701. void juce_HandleProcessFocusChange()
  1702. {
  1703. keysCurrentlyDown.clear();
  1704. if (HIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  1705. {
  1706. if (Process::isForegroundProcess())
  1707. currentlyFocusedPeer->handleFocusGain();
  1708. else
  1709. currentlyFocusedPeer->handleFocusLoss();
  1710. }
  1711. }
  1712. static bool performDrag (DragRef drag)
  1713. {
  1714. EventRecord event;
  1715. event.what = mouseDown;
  1716. event.message = 0;
  1717. event.when = TickCount();
  1718. int x, y;
  1719. Desktop::getMousePosition (x, y);
  1720. event.where.h = x;
  1721. event.where.v = y;
  1722. event.modifiers = GetCurrentKeyModifiers();
  1723. RgnHandle rgn = NewRgn();
  1724. RgnHandle rgn2 = NewRgn();
  1725. SetRectRgn (rgn,
  1726. event.where.h - 8, event.where.v - 8,
  1727. event.where.h + 8, event.where.v + 8);
  1728. CopyRgn (rgn, rgn2);
  1729. InsetRgn (rgn2, 1, 1);
  1730. DiffRgn (rgn, rgn2, rgn);
  1731. DisposeRgn (rgn2);
  1732. bool result = TrackDrag (drag, &event, rgn) == noErr;
  1733. DisposeRgn (rgn);
  1734. return result;
  1735. }
  1736. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  1737. {
  1738. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  1739. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  1740. DragRef drag;
  1741. bool result = false;
  1742. if (NewDrag (&drag) == noErr)
  1743. {
  1744. for (int i = 0; i < files.size(); ++i)
  1745. {
  1746. HFSFlavor hfsData;
  1747. if (PlatformUtilities::makeFSSpecFromPath (&hfsData.fileSpec, files[i]))
  1748. {
  1749. FInfo info;
  1750. if (FSpGetFInfo (&hfsData.fileSpec, &info) == noErr)
  1751. {
  1752. hfsData.fileType = info.fdType;
  1753. hfsData.fileCreator = info.fdCreator;
  1754. hfsData.fdFlags = info.fdFlags;
  1755. AddDragItemFlavor (drag, i + 1, kDragFlavorTypeHFS, &hfsData, sizeof (hfsData), 0);
  1756. result = true;
  1757. }
  1758. }
  1759. }
  1760. SetDragAllowableActions (drag, canMoveFiles ? kDragActionAll
  1761. : kDragActionCopy, false);
  1762. if (result)
  1763. result = performDrag (drag);
  1764. DisposeDrag (drag);
  1765. }
  1766. return result;
  1767. }
  1768. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  1769. {
  1770. jassertfalse // not implemented!
  1771. return false;
  1772. }
  1773. //==============================================================================
  1774. bool Process::isForegroundProcess() throw()
  1775. {
  1776. ProcessSerialNumber psn, front;
  1777. GetCurrentProcess (&psn);
  1778. GetFrontProcess (&front);
  1779. Boolean b;
  1780. return (SameProcess (&psn, &front, &b) == noErr) && b;
  1781. }
  1782. //==============================================================================
  1783. bool Desktop::canUseSemiTransparentWindows() throw()
  1784. {
  1785. return true;
  1786. }
  1787. //==============================================================================
  1788. void Desktop::getMousePosition (int& x, int& y) throw()
  1789. {
  1790. CGrafPtr currentPort;
  1791. GetPort (&currentPort);
  1792. if (! IsValidPort (currentPort))
  1793. {
  1794. WindowRef front = FrontWindow();
  1795. if (front != 0)
  1796. {
  1797. SetPortWindowPort (front);
  1798. }
  1799. else
  1800. {
  1801. x = y = 0;
  1802. return;
  1803. }
  1804. }
  1805. ::Point p;
  1806. GetMouse (&p);
  1807. LocalToGlobal (&p);
  1808. x = p.h;
  1809. y = p.v;
  1810. SetPort (currentPort);
  1811. }
  1812. void Desktop::setMousePosition (int x, int y) throw()
  1813. {
  1814. // this rubbish needs to be done around the warp call, to avoid causing a
  1815. // bizarre glitch..
  1816. CGAssociateMouseAndMouseCursorPosition (false);
  1817. CGSetLocalEventsSuppressionInterval (0);
  1818. CGPoint pos = { x, y };
  1819. CGWarpMouseCursorPosition (pos);
  1820. CGAssociateMouseAndMouseCursorPosition (true);
  1821. }
  1822. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime() throw()
  1823. {
  1824. return ModifierKeys (currentModifiers);
  1825. }
  1826. //==============================================================================
  1827. class ScreenSaverDefeater : public Timer,
  1828. public DeletedAtShutdown
  1829. {
  1830. public:
  1831. ScreenSaverDefeater() throw()
  1832. {
  1833. startTimer (10000);
  1834. timerCallback();
  1835. }
  1836. ~ScreenSaverDefeater()
  1837. {
  1838. }
  1839. void timerCallback()
  1840. {
  1841. if (Process::isForegroundProcess())
  1842. UpdateSystemActivity (UsrActivity);
  1843. }
  1844. };
  1845. static ScreenSaverDefeater* screenSaverDefeater = 0;
  1846. void Desktop::setScreenSaverEnabled (const bool isEnabled) throw()
  1847. {
  1848. if (screenSaverDefeater == 0)
  1849. screenSaverDefeater = new ScreenSaverDefeater();
  1850. }
  1851. bool Desktop::isScreenSaverEnabled() throw()
  1852. {
  1853. return screenSaverDefeater == 0;
  1854. }
  1855. //==============================================================================
  1856. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  1857. {
  1858. int mainMonitorIndex = 0;
  1859. CGDirectDisplayID mainDisplayID = CGMainDisplayID();
  1860. CGDisplayCount count = 0;
  1861. CGDirectDisplayID disps [8];
  1862. if (CGGetOnlineDisplayList (numElementsInArray (disps), disps, &count) == noErr)
  1863. {
  1864. for (int i = 0; i < count; ++i)
  1865. {
  1866. if (mainDisplayID == disps[i])
  1867. mainMonitorIndex = monitorCoords.size();
  1868. GDHandle hGDevice;
  1869. if (clipToWorkArea
  1870. && DMGetGDeviceByDisplayID ((DisplayIDType) disps[i], &hGDevice, false) == noErr)
  1871. {
  1872. Rect rect;
  1873. GetAvailableWindowPositioningBounds (hGDevice, &rect);
  1874. monitorCoords.add (Rectangle (rect.left,
  1875. rect.top,
  1876. rect.right - rect.left,
  1877. rect.bottom - rect.top));
  1878. }
  1879. else
  1880. {
  1881. const CGRect r (CGDisplayBounds (disps[i]));
  1882. monitorCoords.add (Rectangle ((int) r.origin.x,
  1883. (int) r.origin.y,
  1884. (int) r.size.width,
  1885. (int) r.size.height));
  1886. }
  1887. }
  1888. }
  1889. // make sure the first in the list is the main monitor
  1890. if (mainMonitorIndex > 0)
  1891. monitorCoords.swap (mainMonitorIndex, 0);
  1892. jassert (monitorCoords.size() > 0);
  1893. if (monitorCoords.size() == 0)
  1894. monitorCoords.add (Rectangle (0, 0, 1024, 768));
  1895. //xxx need to register for display change callbacks
  1896. }
  1897. //==============================================================================
  1898. struct CursorWrapper
  1899. {
  1900. Cursor* cursor;
  1901. ThemeCursor themeCursor;
  1902. };
  1903. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  1904. {
  1905. const int maxW = 16;
  1906. const int maxH = 16;
  1907. const Image* im = &image;
  1908. Image* newIm = 0;
  1909. if (image.getWidth() > maxW || image.getHeight() > maxH)
  1910. {
  1911. im = newIm = image.createCopy (maxW, maxH);
  1912. hotspotX = (hotspotX * maxW) / image.getWidth();
  1913. hotspotY = (hotspotY * maxH) / image.getHeight();
  1914. }
  1915. Cursor* const c = new Cursor();
  1916. c->hotSpot.h = hotspotX;
  1917. c->hotSpot.v = hotspotY;
  1918. for (int y = 0; y < maxH; ++y)
  1919. {
  1920. c->data[y] = 0;
  1921. c->mask[y] = 0;
  1922. for (int x = 0; x < maxW; ++x)
  1923. {
  1924. const Colour pixelColour (im->getPixelAt (15 - x, y));
  1925. if (pixelColour.getAlpha() > 0.5f)
  1926. {
  1927. c->mask[y] |= (1 << x);
  1928. if (pixelColour.getBrightness() < 0.5f)
  1929. c->data[y] |= (1 << x);
  1930. }
  1931. }
  1932. c->data[y] = CFSwapInt16BigToHost (c->data[y]);
  1933. c->mask[y] = CFSwapInt16BigToHost (c->mask[y]);
  1934. }
  1935. if (newIm != 0)
  1936. delete newIm;
  1937. CursorWrapper* const cw = new CursorWrapper();
  1938. cw->cursor = c;
  1939. cw->themeCursor = kThemeArrowCursor;
  1940. return (void*) cw;
  1941. }
  1942. static void* cursorFromData (const unsigned char* data, const int size, int hx, int hy) throw()
  1943. {
  1944. Image* const im = ImageFileFormat::loadFrom ((const char*) data, size);
  1945. jassert (im != 0);
  1946. void* curs = juce_createMouseCursorFromImage (*im, hx, hy);
  1947. delete im;
  1948. return curs;
  1949. }
  1950. const unsigned int kSpecialNoCursor = 'nocr';
  1951. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  1952. {
  1953. ThemeCursor id = kThemeArrowCursor;
  1954. switch (type)
  1955. {
  1956. case MouseCursor::NormalCursor:
  1957. id = kThemeArrowCursor;
  1958. break;
  1959. case MouseCursor::NoCursor:
  1960. id = kSpecialNoCursor;
  1961. break;
  1962. case MouseCursor::DraggingHandCursor:
  1963. {
  1964. 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,
  1965. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  1966. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  1967. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  1968. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  1969. const int cursDataSize = 99;
  1970. return cursorFromData (cursData, cursDataSize, 8, 8);
  1971. }
  1972. break;
  1973. case MouseCursor::CopyingCursor:
  1974. id = kThemeCopyArrowCursor;
  1975. break;
  1976. case MouseCursor::WaitCursor:
  1977. id = kThemeWatchCursor;
  1978. break;
  1979. case MouseCursor::IBeamCursor:
  1980. id = kThemeIBeamCursor;
  1981. break;
  1982. case MouseCursor::PointingHandCursor:
  1983. id = kThemePointingHandCursor;
  1984. break;
  1985. case MouseCursor::LeftRightResizeCursor:
  1986. case MouseCursor::LeftEdgeResizeCursor:
  1987. case MouseCursor::RightEdgeResizeCursor:
  1988. {
  1989. 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,
  1990. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  1991. 16,0,0,2,38,148,143,169,203,237,15,19,0,106,202,64,111,22,32,224,
  1992. 9,78,30,213,121,230,121,146,99,8,142,71,183,189,152,20,27,86,132,231,
  1993. 58,83,0,0,59 };
  1994. const int cursDataSize = 85;
  1995. return cursorFromData (cursData, cursDataSize, 8, 8);
  1996. }
  1997. case MouseCursor::UpDownResizeCursor:
  1998. case MouseCursor::TopEdgeResizeCursor:
  1999. case MouseCursor::BottomEdgeResizeCursor:
  2000. {
  2001. 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,
  2002. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  2003. 16,0,0,2,38,148,111,128,187,16,202,90,152,48,10,55,169,189,192,245,
  2004. 106,121,27,34,142,201,99,158,224,86,154,109,216,61,29,155,105,180,61,190,
  2005. 121,84,0,0,59 };
  2006. const int cursDataSize = 85;
  2007. return cursorFromData (cursData, cursDataSize, 8, 8);
  2008. }
  2009. case MouseCursor::TopLeftCornerResizeCursor:
  2010. case MouseCursor::BottomRightCornerResizeCursor:
  2011. {
  2012. 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,
  2013. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  2014. 16,0,0,2,43,132,15,162,187,16,255,18,99,14,202,217,44,158,213,221,
  2015. 237,9,225,38,94,35,73,5,31,42,170,108,106,174,112,43,195,209,91,185,
  2016. 104,174,131,208,77,66,28,10,0,59 };
  2017. const int cursDataSize = 90;
  2018. return cursorFromData (cursData, cursDataSize, 8, 8);
  2019. }
  2020. case MouseCursor::TopRightCornerResizeCursor:
  2021. case MouseCursor::BottomLeftCornerResizeCursor:
  2022. {
  2023. 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,
  2024. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  2025. 16,0,0,2,45,148,127,160,11,232,16,98,108,14,65,73,107,194,122,223,
  2026. 92,65,141,216,145,134,162,153,221,25,128,73,166,62,173,16,203,237,188,94,
  2027. 120,46,237,105,239,123,48,80,157,2,0,59 };
  2028. const int cursDataSize = 92;
  2029. return cursorFromData (cursData, cursDataSize, 8, 8);
  2030. }
  2031. case MouseCursor::UpDownLeftRightResizeCursor:
  2032. {
  2033. 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,
  2034. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,15,0,
  2035. 15,0,0,2,46,156,63,129,139,1,202,26,152,48,186,73,109,114,65,85,
  2036. 195,37,143,88,93,29,215,101,23,198,178,30,149,158,25,56,134,97,179,61,
  2037. 158,213,126,203,234,99,220,34,56,70,1,0,59,0,0 };
  2038. const int cursDataSize = 93;
  2039. return cursorFromData (cursData, cursDataSize, 7, 7);
  2040. }
  2041. case MouseCursor::CrosshairCursor:
  2042. id = kThemeCrossCursor;
  2043. break;
  2044. }
  2045. CursorWrapper* cw = new CursorWrapper();
  2046. cw->cursor = 0;
  2047. cw->themeCursor = id;
  2048. return (void*) cw;
  2049. }
  2050. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  2051. {
  2052. CursorWrapper* const cw = (CursorWrapper*) cursorHandle;
  2053. if (cw != 0)
  2054. {
  2055. delete cw->cursor;
  2056. delete cw;
  2057. }
  2058. }
  2059. void MouseCursor::showInAllWindows() const throw()
  2060. {
  2061. showInWindow (0);
  2062. }
  2063. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  2064. {
  2065. const CursorWrapper* const cw = (CursorWrapper*) getHandle();
  2066. if (cw != 0)
  2067. {
  2068. static bool isCursorHidden = false;
  2069. static bool showingWaitCursor = false;
  2070. const bool shouldShowWaitCursor = (cw->themeCursor == kThemeWatchCursor);
  2071. const bool shouldHideCursor = (cw->themeCursor == kSpecialNoCursor);
  2072. if (shouldShowWaitCursor != showingWaitCursor
  2073. && Process::isForegroundProcess())
  2074. {
  2075. showingWaitCursor = shouldShowWaitCursor;
  2076. QDDisplayWaitCursor (shouldShowWaitCursor);
  2077. }
  2078. if (shouldHideCursor != isCursorHidden)
  2079. {
  2080. isCursorHidden = shouldHideCursor;
  2081. if (shouldHideCursor)
  2082. HideCursor();
  2083. else
  2084. ShowCursor();
  2085. }
  2086. if (cw->cursor != 0)
  2087. SetCursor (cw->cursor);
  2088. else if (! (shouldShowWaitCursor || shouldHideCursor))
  2089. SetThemeCursor (cw->themeCursor);
  2090. }
  2091. }
  2092. //==============================================================================
  2093. Image* juce_createIconForFile (const File& file)
  2094. {
  2095. return 0;
  2096. }
  2097. //==============================================================================
  2098. class MainMenuHandler;
  2099. static MainMenuHandler* mainMenu = 0;
  2100. class MainMenuHandler : private MenuBarModelListener,
  2101. private DeletedAtShutdown
  2102. {
  2103. public:
  2104. MainMenuHandler() throw()
  2105. : currentModel (0)
  2106. {
  2107. }
  2108. ~MainMenuHandler() throw()
  2109. {
  2110. setMenu (0);
  2111. jassert (mainMenu == this);
  2112. mainMenu = 0;
  2113. }
  2114. void setMenu (MenuBarModel* const newMenuBarModel) throw()
  2115. {
  2116. if (currentModel != newMenuBarModel)
  2117. {
  2118. if (currentModel != 0)
  2119. currentModel->removeListener (this);
  2120. currentModel = newMenuBarModel;
  2121. if (currentModel != 0)
  2122. currentModel->addListener (this);
  2123. menuBarItemsChanged (0);
  2124. }
  2125. }
  2126. void menuBarItemsChanged (MenuBarModel*)
  2127. {
  2128. ClearMenuBar();
  2129. if (currentModel != 0)
  2130. {
  2131. int id = 1000;
  2132. const StringArray menuNames (currentModel->getMenuBarNames());
  2133. for (int i = 0; i < menuNames.size(); ++i)
  2134. {
  2135. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  2136. MenuRef m = createMenu (menu, menuNames [i], id, i);
  2137. InsertMenu (m, 0);
  2138. CFRelease (m);
  2139. }
  2140. }
  2141. }
  2142. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  2143. {
  2144. MenuRef menu = 0;
  2145. MenuItemIndex index = 0;
  2146. GetIndMenuItemWithCommandID (0, info.commandID, 1, &menu, &index);
  2147. FlashMenuBar (GetMenuID (menu));
  2148. FlashMenuBar (GetMenuID (menu));
  2149. }
  2150. void invoke (const int id, ApplicationCommandManager* const commandManager, const int topLevelIndex) const
  2151. {
  2152. if (currentModel != 0)
  2153. {
  2154. if (commandManager != 0)
  2155. {
  2156. ApplicationCommandTarget::InvocationInfo info (id);
  2157. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  2158. commandManager->invoke (info, true);
  2159. }
  2160. currentModel->menuItemSelected (id, topLevelIndex);
  2161. }
  2162. }
  2163. MenuBarModel* currentModel;
  2164. private:
  2165. static MenuRef createMenu (const PopupMenu menu,
  2166. const String& menuName,
  2167. int& id,
  2168. const int topLevelIndex)
  2169. {
  2170. MenuRef m = 0;
  2171. if (CreateNewMenu (id++, kMenuAttrAutoDisable, &m) == noErr)
  2172. {
  2173. CFStringRef name = PlatformUtilities::juceStringToCFString (menuName);
  2174. SetMenuTitleWithCFString (m, name);
  2175. CFRelease (name);
  2176. PopupMenu::MenuItemIterator iter (menu);
  2177. while (iter.next())
  2178. {
  2179. MenuItemIndex index = 0;
  2180. int flags = kMenuAttrAutoDisable | kMenuItemAttrIgnoreMeta | kMenuItemAttrNotPreviousAlternate;
  2181. if (! iter.isEnabled)
  2182. flags |= kMenuItemAttrDisabled;
  2183. CFStringRef text = PlatformUtilities::juceStringToCFString (iter.itemName.upToFirstOccurrenceOf (T("<end>"), false, true));
  2184. if (iter.isSeparator)
  2185. {
  2186. AppendMenuItemTextWithCFString (m, text, kMenuItemAttrSeparator, 0, &index);
  2187. }
  2188. else if (iter.isSectionHeader)
  2189. {
  2190. AppendMenuItemTextWithCFString (m, text, kMenuItemAttrSectionHeader, 0, &index);
  2191. }
  2192. else if (iter.subMenu != 0)
  2193. {
  2194. AppendMenuItemTextWithCFString (m, text, flags, id++, &index);
  2195. MenuRef sub = createMenu (*iter.subMenu, iter.itemName, id, topLevelIndex);
  2196. SetMenuItemHierarchicalMenu (m, index, sub);
  2197. CFRelease (sub);
  2198. }
  2199. else
  2200. {
  2201. AppendMenuItemTextWithCFString (m, text, flags, iter.itemId, &index);
  2202. if (iter.isTicked)
  2203. CheckMenuItem (m, index, true);
  2204. SetMenuItemProperty (m, index, 'juce', 'apcm', sizeof (void*), &iter.commandManager);
  2205. SetMenuItemProperty (m, index, 'juce', 'topi', sizeof (int), &topLevelIndex);
  2206. if (iter.commandManager != 0)
  2207. {
  2208. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  2209. ->getKeyPressesAssignedToCommand (iter.itemId));
  2210. if (keyPresses.size() > 0)
  2211. {
  2212. const KeyPress& kp = keyPresses.getUnchecked(0);
  2213. int mods = 0;
  2214. if (kp.getModifiers().isShiftDown())
  2215. mods |= kMenuShiftModifier;
  2216. if (kp.getModifiers().isCtrlDown())
  2217. mods |= kMenuControlModifier;
  2218. if (kp.getModifiers().isAltDown())
  2219. mods |= kMenuOptionModifier;
  2220. if (! kp.getModifiers().isCommandDown())
  2221. mods |= kMenuNoCommandModifier;
  2222. tchar keyCode = (tchar) kp.getKeyCode();
  2223. if (kp.getKeyCode() >= KeyPress::numberPad0
  2224. && kp.getKeyCode() <= KeyPress::numberPad9)
  2225. {
  2226. keyCode = (tchar) ((T('0') - KeyPress::numberPad0) + kp.getKeyCode());
  2227. }
  2228. SetMenuItemCommandKey (m, index, true, 255);
  2229. if (CharacterFunctions::isLetterOrDigit (keyCode)
  2230. || CharacterFunctions::indexOfChar (T(",.;/\\'[]=-+_<>?{}\":"), keyCode, false) >= 0)
  2231. {
  2232. SetMenuItemModifiers (m, index, mods);
  2233. SetMenuItemCommandKey (m, index, false, CharacterFunctions::toUpperCase (keyCode));
  2234. }
  2235. else
  2236. {
  2237. const SInt16 glyph = getGlyphForKeyCode (kp.getKeyCode());
  2238. if (glyph != 0)
  2239. {
  2240. SetMenuItemModifiers (m, index, mods);
  2241. SetMenuItemKeyGlyph (m, index, glyph);
  2242. }
  2243. }
  2244. // if we set the key glyph to be a text char, and enable virtual
  2245. // key triggering, it stops the menu automatically triggering the callback
  2246. ChangeMenuItemAttributes (m, index, kMenuItemAttrUseVirtualKey, 0);
  2247. }
  2248. }
  2249. }
  2250. CFRelease (text);
  2251. }
  2252. }
  2253. return m;
  2254. }
  2255. static SInt16 getGlyphForKeyCode (const int keyCode) throw()
  2256. {
  2257. if (keyCode == KeyPress::spaceKey)
  2258. return kMenuSpaceGlyph;
  2259. else if (keyCode == KeyPress::returnKey)
  2260. return kMenuReturnGlyph;
  2261. else if (keyCode == KeyPress::escapeKey)
  2262. return kMenuEscapeGlyph;
  2263. else if (keyCode == KeyPress::backspaceKey)
  2264. return kMenuDeleteLeftGlyph;
  2265. else if (keyCode == KeyPress::leftKey)
  2266. return kMenuLeftArrowGlyph;
  2267. else if (keyCode == KeyPress::rightKey)
  2268. return kMenuRightArrowGlyph;
  2269. else if (keyCode == KeyPress::upKey)
  2270. return kMenuUpArrowGlyph;
  2271. else if (keyCode == KeyPress::downKey)
  2272. return kMenuDownArrowGlyph;
  2273. else if (keyCode == KeyPress::pageUpKey)
  2274. return kMenuPageUpGlyph;
  2275. else if (keyCode == KeyPress::pageDownKey)
  2276. return kMenuPageDownGlyph;
  2277. else if (keyCode == KeyPress::endKey)
  2278. return kMenuSoutheastArrowGlyph;
  2279. else if (keyCode == KeyPress::homeKey)
  2280. return kMenuNorthwestArrowGlyph;
  2281. else if (keyCode == KeyPress::deleteKey)
  2282. return kMenuDeleteRightGlyph;
  2283. else if (keyCode == KeyPress::tabKey)
  2284. return kMenuTabRightGlyph;
  2285. else if (keyCode == KeyPress::F1Key)
  2286. return kMenuF1Glyph;
  2287. else if (keyCode == KeyPress::F2Key)
  2288. return kMenuF2Glyph;
  2289. else if (keyCode == KeyPress::F3Key)
  2290. return kMenuF3Glyph;
  2291. else if (keyCode == KeyPress::F4Key)
  2292. return kMenuF4Glyph;
  2293. else if (keyCode == KeyPress::F5Key)
  2294. return kMenuF5Glyph;
  2295. else if (keyCode == KeyPress::F6Key)
  2296. return kMenuF6Glyph;
  2297. else if (keyCode == KeyPress::F7Key)
  2298. return kMenuF7Glyph;
  2299. else if (keyCode == KeyPress::F8Key)
  2300. return kMenuF8Glyph;
  2301. else if (keyCode == KeyPress::F9Key)
  2302. return kMenuF9Glyph;
  2303. else if (keyCode == KeyPress::F10Key)
  2304. return kMenuF10Glyph;
  2305. else if (keyCode == KeyPress::F11Key)
  2306. return kMenuF11Glyph;
  2307. else if (keyCode == KeyPress::F12Key)
  2308. return kMenuF12Glyph;
  2309. else if (keyCode == KeyPress::F13Key)
  2310. return kMenuF13Glyph;
  2311. else if (keyCode == KeyPress::F14Key)
  2312. return kMenuF14Glyph;
  2313. else if (keyCode == KeyPress::F15Key)
  2314. return kMenuF15Glyph;
  2315. return 0;
  2316. }
  2317. };
  2318. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel) throw()
  2319. {
  2320. if (getMacMainMenu() != newMenuBarModel)
  2321. {
  2322. if (newMenuBarModel == 0)
  2323. {
  2324. delete mainMenu;
  2325. jassert (mainMenu == 0); // should be zeroed in the destructor
  2326. }
  2327. else
  2328. {
  2329. if (mainMenu == 0)
  2330. mainMenu = new MainMenuHandler();
  2331. mainMenu->setMenu (newMenuBarModel);
  2332. }
  2333. }
  2334. }
  2335. MenuBarModel* MenuBarModel::getMacMainMenu() throw()
  2336. {
  2337. return mainMenu != 0 ? mainMenu->currentModel : 0;
  2338. }
  2339. // these functions are called externally from the message handling code
  2340. void juce_MainMenuAboutToBeUsed()
  2341. {
  2342. // force an update of the items just before the menu appears..
  2343. if (mainMenu != 0)
  2344. mainMenu->menuBarItemsChanged (0);
  2345. }
  2346. void juce_InvokeMainMenuCommand (const HICommand& command)
  2347. {
  2348. if (mainMenu != 0)
  2349. {
  2350. ApplicationCommandManager* commandManager = 0;
  2351. int topLevelIndex = 0;
  2352. if (GetMenuItemProperty (command.menu.menuRef, command.menu.menuItemIndex,
  2353. 'juce', 'apcm', sizeof (commandManager), 0, &commandManager) == noErr
  2354. && GetMenuItemProperty (command.menu.menuRef, command.menu.menuItemIndex,
  2355. 'juce', 'topi', sizeof (topLevelIndex), 0, &topLevelIndex) == noErr)
  2356. {
  2357. mainMenu->invoke (command.commandID, commandManager, topLevelIndex);
  2358. }
  2359. }
  2360. }
  2361. //==============================================================================
  2362. void PlatformUtilities::beep()
  2363. {
  2364. SysBeep (30);
  2365. }
  2366. //==============================================================================
  2367. void SystemClipboard::copyTextToClipboard (const String& text) throw()
  2368. {
  2369. ClearCurrentScrap();
  2370. ScrapRef ref;
  2371. GetCurrentScrap (&ref);
  2372. const int len = text.length();
  2373. const int numBytes = sizeof (UniChar) * len;
  2374. UniChar* const temp = (UniChar*) juce_calloc (numBytes);
  2375. for (int i = 0; i < len; ++i)
  2376. temp[i] = (UniChar) text[i];
  2377. PutScrapFlavor (ref,
  2378. kScrapFlavorTypeUnicode,
  2379. kScrapFlavorMaskNone,
  2380. numBytes,
  2381. temp);
  2382. juce_free (temp);
  2383. }
  2384. const String SystemClipboard::getTextFromClipboard() throw()
  2385. {
  2386. String result;
  2387. ScrapRef ref;
  2388. GetCurrentScrap (&ref);
  2389. Size size = 0;
  2390. if (GetScrapFlavorSize (ref, kScrapFlavorTypeUnicode, &size) == noErr
  2391. && size > 0)
  2392. {
  2393. void* const data = juce_calloc (size + 8);
  2394. if (GetScrapFlavorData (ref, kScrapFlavorTypeUnicode, &size, data) == noErr)
  2395. {
  2396. result = PlatformUtilities::convertUTF16ToString ((UniChar*) data);
  2397. }
  2398. juce_free (data);
  2399. }
  2400. return result;
  2401. }
  2402. //==============================================================================
  2403. bool AlertWindow::showNativeDialogBox (const String& title,
  2404. const String& bodyText,
  2405. bool isOkCancel)
  2406. {
  2407. Str255 tit, txt;
  2408. PlatformUtilities::copyToStr255 (tit, title);
  2409. PlatformUtilities::copyToStr255 (txt, bodyText);
  2410. AlertStdAlertParamRec ar;
  2411. ar.movable = true;
  2412. ar.helpButton = false;
  2413. ar.filterProc = 0;
  2414. ar.defaultText = (const unsigned char*)-1;
  2415. ar.cancelText = (const unsigned char*)((isOkCancel) ? -1 : 0);
  2416. ar.otherText = 0;
  2417. ar.defaultButton = kAlertStdAlertOKButton;
  2418. ar.cancelButton = 0;
  2419. ar.position = kWindowDefaultPosition;
  2420. SInt16 result;
  2421. StandardAlert (kAlertNoteAlert, tit, txt, &ar, &result);
  2422. return result == kAlertStdAlertOKButton;
  2423. }
  2424. //==============================================================================
  2425. const int KeyPress::spaceKey = ' ';
  2426. const int KeyPress::returnKey = kReturnCharCode;
  2427. const int KeyPress::escapeKey = kEscapeCharCode;
  2428. const int KeyPress::backspaceKey = kBackspaceCharCode;
  2429. const int KeyPress::leftKey = kLeftArrowCharCode;
  2430. const int KeyPress::rightKey = kRightArrowCharCode;
  2431. const int KeyPress::upKey = kUpArrowCharCode;
  2432. const int KeyPress::downKey = kDownArrowCharCode;
  2433. const int KeyPress::pageUpKey = kPageUpCharCode;
  2434. const int KeyPress::pageDownKey = kPageDownCharCode;
  2435. const int KeyPress::endKey = kEndCharCode;
  2436. const int KeyPress::homeKey = kHomeCharCode;
  2437. const int KeyPress::deleteKey = kDeleteCharCode;
  2438. const int KeyPress::insertKey = -1;
  2439. const int KeyPress::tabKey = kTabCharCode;
  2440. const int KeyPress::F1Key = 0x10110;
  2441. const int KeyPress::F2Key = 0x10111;
  2442. const int KeyPress::F3Key = 0x10112;
  2443. const int KeyPress::F4Key = 0x10113;
  2444. const int KeyPress::F5Key = 0x10114;
  2445. const int KeyPress::F6Key = 0x10115;
  2446. const int KeyPress::F7Key = 0x10116;
  2447. const int KeyPress::F8Key = 0x10117;
  2448. const int KeyPress::F9Key = 0x10118;
  2449. const int KeyPress::F10Key = 0x10119;
  2450. const int KeyPress::F11Key = 0x1011a;
  2451. const int KeyPress::F12Key = 0x1011b;
  2452. const int KeyPress::F13Key = 0x1011c;
  2453. const int KeyPress::F14Key = 0x1011d;
  2454. const int KeyPress::F15Key = 0x1011e;
  2455. const int KeyPress::F16Key = 0x1011f;
  2456. const int KeyPress::numberPad0 = 0x30020;
  2457. const int KeyPress::numberPad1 = 0x30021;
  2458. const int KeyPress::numberPad2 = 0x30022;
  2459. const int KeyPress::numberPad3 = 0x30023;
  2460. const int KeyPress::numberPad4 = 0x30024;
  2461. const int KeyPress::numberPad5 = 0x30025;
  2462. const int KeyPress::numberPad6 = 0x30026;
  2463. const int KeyPress::numberPad7 = 0x30027;
  2464. const int KeyPress::numberPad8 = 0x30028;
  2465. const int KeyPress::numberPad9 = 0x30029;
  2466. const int KeyPress::numberPadAdd = 0x3002a;
  2467. const int KeyPress::numberPadSubtract = 0x3002b;
  2468. const int KeyPress::numberPadMultiply = 0x3002c;
  2469. const int KeyPress::numberPadDivide = 0x3002d;
  2470. const int KeyPress::numberPadSeparator = 0x3002e;
  2471. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  2472. const int KeyPress::numberPadEquals = 0x30030;
  2473. const int KeyPress::numberPadDelete = 0x30031;
  2474. const int KeyPress::playKey = 0x30000;
  2475. const int KeyPress::stopKey = 0x30001;
  2476. const int KeyPress::fastForwardKey = 0x30002;
  2477. const int KeyPress::rewindKey = 0x30003;
  2478. //==============================================================================
  2479. AppleRemoteDevice::AppleRemoteDevice()
  2480. : device (0),
  2481. queue (0),
  2482. remoteId (0)
  2483. {
  2484. }
  2485. AppleRemoteDevice::~AppleRemoteDevice()
  2486. {
  2487. stop();
  2488. }
  2489. static io_object_t getAppleRemoteDevice() throw()
  2490. {
  2491. CFMutableDictionaryRef dict = IOServiceMatching ("AppleIRController");
  2492. io_iterator_t iter = 0;
  2493. io_object_t iod = 0;
  2494. if (IOServiceGetMatchingServices (kIOMasterPortDefault, dict, &iter) == kIOReturnSuccess
  2495. && iter != 0)
  2496. {
  2497. iod = IOIteratorNext (iter);
  2498. }
  2499. IOObjectRelease (iter);
  2500. return iod;
  2501. }
  2502. static bool createAppleRemoteInterface (io_object_t iod, void** device) throw()
  2503. {
  2504. jassert (*device == 0);
  2505. io_name_t classname;
  2506. if (IOObjectGetClass (iod, classname) == kIOReturnSuccess)
  2507. {
  2508. IOCFPlugInInterface** cfPlugInInterface = 0;
  2509. SInt32 score = 0;
  2510. if (IOCreatePlugInInterfaceForService (iod,
  2511. kIOHIDDeviceUserClientTypeID,
  2512. kIOCFPlugInInterfaceID,
  2513. &cfPlugInInterface,
  2514. &score) == kIOReturnSuccess)
  2515. {
  2516. HRESULT hr = (*cfPlugInInterface)->QueryInterface (cfPlugInInterface,
  2517. CFUUIDGetUUIDBytes (kIOHIDDeviceInterfaceID),
  2518. device);
  2519. (void) hr;
  2520. (*cfPlugInInterface)->Release (cfPlugInInterface);
  2521. }
  2522. }
  2523. return *device != 0;
  2524. }
  2525. bool AppleRemoteDevice::start (const bool inExclusiveMode) throw()
  2526. {
  2527. if (queue != 0)
  2528. return true;
  2529. stop();
  2530. bool result = false;
  2531. io_object_t iod = getAppleRemoteDevice();
  2532. if (iod != 0)
  2533. {
  2534. if (createAppleRemoteInterface (iod, &device) && open (inExclusiveMode))
  2535. result = true;
  2536. else
  2537. stop();
  2538. IOObjectRelease (iod);
  2539. }
  2540. return result;
  2541. }
  2542. void AppleRemoteDevice::stop() throw()
  2543. {
  2544. if (queue != 0)
  2545. {
  2546. (*(IOHIDQueueInterface**) queue)->stop ((IOHIDQueueInterface**) queue);
  2547. (*(IOHIDQueueInterface**) queue)->dispose ((IOHIDQueueInterface**) queue);
  2548. (*(IOHIDQueueInterface**) queue)->Release ((IOHIDQueueInterface**) queue);
  2549. queue = 0;
  2550. }
  2551. if (device != 0)
  2552. {
  2553. (*(IOHIDDeviceInterface**) device)->close ((IOHIDDeviceInterface**) device);
  2554. (*(IOHIDDeviceInterface**) device)->Release ((IOHIDDeviceInterface**) device);
  2555. device = 0;
  2556. }
  2557. }
  2558. bool AppleRemoteDevice::isActive() const throw()
  2559. {
  2560. return queue != 0;
  2561. }
  2562. static void appleRemoteQueueCallback (void* const target, const IOReturn result, void*, void*)
  2563. {
  2564. if (result == kIOReturnSuccess)
  2565. ((AppleRemoteDevice*) target)->handleCallbackInternal();
  2566. }
  2567. bool AppleRemoteDevice::open (const bool openInExclusiveMode) throw()
  2568. {
  2569. #if ! MACOS_10_2_OR_EARLIER
  2570. Array <int> cookies;
  2571. CFArrayRef elements;
  2572. IOHIDDeviceInterface122** const device122 = (IOHIDDeviceInterface122**) device;
  2573. if ((*device122)->copyMatchingElements (device122, 0, &elements) != kIOReturnSuccess)
  2574. return false;
  2575. for (int i = 0; i < CFArrayGetCount (elements); ++i)
  2576. {
  2577. CFDictionaryRef element = (CFDictionaryRef) CFArrayGetValueAtIndex (elements, i);
  2578. // get the cookie
  2579. CFTypeRef object = CFDictionaryGetValue (element, CFSTR (kIOHIDElementCookieKey));
  2580. if (object == 0 || CFGetTypeID (object) != CFNumberGetTypeID())
  2581. continue;
  2582. long number;
  2583. if (! CFNumberGetValue ((CFNumberRef) object, kCFNumberLongType, &number))
  2584. continue;
  2585. cookies.add ((int) number);
  2586. }
  2587. CFRelease (elements);
  2588. if ((*(IOHIDDeviceInterface**) device)
  2589. ->open ((IOHIDDeviceInterface**) device,
  2590. openInExclusiveMode ? kIOHIDOptionsTypeSeizeDevice
  2591. : kIOHIDOptionsTypeNone) == KERN_SUCCESS)
  2592. {
  2593. queue = (*(IOHIDDeviceInterface**) device)->allocQueue ((IOHIDDeviceInterface**) device);
  2594. if (queue != 0)
  2595. {
  2596. (*(IOHIDQueueInterface**) queue)->create ((IOHIDQueueInterface**) queue, 0, 12);
  2597. for (int i = 0; i < cookies.size(); ++i)
  2598. {
  2599. IOHIDElementCookie cookie = (IOHIDElementCookie) cookies.getUnchecked(i);
  2600. (*(IOHIDQueueInterface**) queue)->addElement ((IOHIDQueueInterface**) queue, cookie, 0);
  2601. }
  2602. CFRunLoopSourceRef eventSource;
  2603. if ((*(IOHIDQueueInterface**) queue)
  2604. ->createAsyncEventSource ((IOHIDQueueInterface**) queue, &eventSource) == KERN_SUCCESS)
  2605. {
  2606. if ((*(IOHIDQueueInterface**) queue)->setEventCallout ((IOHIDQueueInterface**) queue,
  2607. appleRemoteQueueCallback, this, 0) == KERN_SUCCESS)
  2608. {
  2609. CFRunLoopAddSource (CFRunLoopGetCurrent(), eventSource, kCFRunLoopDefaultMode);
  2610. (*(IOHIDQueueInterface**) queue)->start ((IOHIDQueueInterface**) queue);
  2611. return true;
  2612. }
  2613. }
  2614. }
  2615. }
  2616. #endif
  2617. return false;
  2618. }
  2619. void AppleRemoteDevice::handleCallbackInternal()
  2620. {
  2621. int totalValues = 0;
  2622. AbsoluteTime nullTime = { 0, 0 };
  2623. char cookies [12];
  2624. int numCookies = 0;
  2625. while (numCookies < numElementsInArray (cookies))
  2626. {
  2627. IOHIDEventStruct e;
  2628. if ((*(IOHIDQueueInterface**) queue)->getNextEvent ((IOHIDQueueInterface**) queue, &e, nullTime, 0) != kIOReturnSuccess)
  2629. break;
  2630. if ((int) e.elementCookie == 19)
  2631. {
  2632. remoteId = e.value;
  2633. buttonPressed (switched, false);
  2634. }
  2635. else
  2636. {
  2637. totalValues += e.value;
  2638. cookies [numCookies++] = (char) (pointer_sized_int) e.elementCookie;
  2639. }
  2640. }
  2641. cookies [numCookies++] = 0;
  2642. static const char buttonPatterns[] =
  2643. {
  2644. 14, 7, 6, 5, 14, 7, 6, 5, 0,
  2645. 14, 8, 6, 5, 14, 8, 6, 5, 0,
  2646. 14, 12, 11, 6, 5, 0,
  2647. 14, 13, 11, 6, 5, 0,
  2648. 14, 9, 6, 5, 14, 9, 6, 5, 0,
  2649. 14, 10, 6, 5, 14, 10, 6, 5, 0,
  2650. 14, 6, 5, 4, 2, 0,
  2651. 14, 6, 5, 3, 2, 0,
  2652. 14, 6, 5, 14, 6, 5, 0,
  2653. 18, 14, 6, 5, 18, 14, 6, 5, 0,
  2654. 19, 0
  2655. };
  2656. int buttonNum = (int) menuButton;
  2657. int i = 0;
  2658. while (i < numElementsInArray (buttonPatterns))
  2659. {
  2660. if (strcmp (cookies, buttonPatterns + i) == 0)
  2661. {
  2662. buttonPressed ((ButtonType) buttonNum, totalValues > 0);
  2663. break;
  2664. }
  2665. i += strlen (buttonPatterns + i) + 1;
  2666. ++buttonNum;
  2667. }
  2668. }
  2669. //==============================================================================
  2670. #if JUCE_OPENGL
  2671. struct OpenGLContextInfo
  2672. {
  2673. AGLContext renderContext;
  2674. };
  2675. void* juce_createOpenGLContext (OpenGLComponent* component, void* sharedContext)
  2676. {
  2677. jassert (component != 0);
  2678. HIViewComponentPeer* const peer = dynamic_cast <HIViewComponentPeer*> (component->getTopLevelComponent()->getPeer());
  2679. if (peer == 0)
  2680. return 0;
  2681. OpenGLContextInfo* const oc = new OpenGLContextInfo();
  2682. GLint attrib[] = { AGL_RGBA, AGL_DOUBLEBUFFER,
  2683. AGL_RED_SIZE, 8,
  2684. AGL_ALPHA_SIZE, 8,
  2685. AGL_DEPTH_SIZE, 24,
  2686. AGL_CLOSEST_POLICY, AGL_NO_RECOVERY,
  2687. AGL_SAMPLE_BUFFERS_ARB, 1,
  2688. AGL_SAMPLES_ARB, 4,
  2689. AGL_NONE };
  2690. oc->renderContext = aglCreateContext (aglChoosePixelFormat (0, 0, attrib),
  2691. (sharedContext != 0) ? ((OpenGLContextInfo*) sharedContext)->renderContext
  2692. : 0);
  2693. aglSetDrawable (oc->renderContext,
  2694. GetWindowPort (peer->windowRef));
  2695. return oc;
  2696. }
  2697. void juce_updateOpenGLWindowPos (void* context, Component* owner, Component* topComp)
  2698. {
  2699. jassert (context != 0);
  2700. OpenGLContextInfo* const oc = (OpenGLContextInfo*) context;
  2701. GLint bufferRect[4];
  2702. bufferRect[0] = owner->getScreenX() - topComp->getScreenX();
  2703. bufferRect[1] = topComp->getHeight() - (owner->getHeight() + owner->getScreenY() - topComp->getScreenY());
  2704. bufferRect[2] = owner->getWidth();
  2705. bufferRect[3] = owner->getHeight();
  2706. aglSetInteger (oc->renderContext, AGL_BUFFER_RECT, bufferRect);
  2707. aglEnable (oc->renderContext, AGL_BUFFER_RECT);
  2708. }
  2709. void juce_deleteOpenGLContext (void* context)
  2710. {
  2711. OpenGLContextInfo* const oc = (OpenGLContextInfo*) context;
  2712. aglDestroyContext (oc->renderContext);
  2713. delete oc;
  2714. }
  2715. bool juce_makeOpenGLContextCurrent (void* context)
  2716. {
  2717. OpenGLContextInfo* const oc = (OpenGLContextInfo*) context;
  2718. return aglSetCurrentContext ((oc != 0) ? oc->renderContext : 0);
  2719. }
  2720. bool juce_isActiveOpenGLContext (void* context) throw()
  2721. {
  2722. OpenGLContextInfo* const oc = (OpenGLContextInfo*) context;
  2723. jassert (oc != 0);
  2724. return aglGetCurrentContext() == oc->renderContext;
  2725. }
  2726. void juce_swapOpenGLBuffers (void* context)
  2727. {
  2728. OpenGLContextInfo* const oc = (OpenGLContextInfo*) context;
  2729. if (oc != 0)
  2730. aglSwapBuffers (oc->renderContext);
  2731. }
  2732. void juce_repaintOpenGLWindow (void* context)
  2733. {
  2734. }
  2735. #endif
  2736. END_JUCE_NAMESPACE