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.

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