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.

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