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.

3546 lines
117KB

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