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.

3613 lines
117KB

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