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.

3625 lines
121KB

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