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.

3607 lines
120KB

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