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.

3561 lines
118KB

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