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.

3085 lines
100KB

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