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.

3571 lines
115KB

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