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.

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