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.

3069 lines
99KB

  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, 0, '`', 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, 0, 0, 0, 0, KeyPress::numberPadDivide, KeyPress::returnKey,
  913. 0, KeyPress::numberPadSubtract, 0, 0, 0, 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. {
  926. keyCode = keyTranslations [rawKey];
  927. }
  928. else if (rawKey == 0 && textCharacter != 0)
  929. {
  930. keyCode = 'a';
  931. }
  932. if ((currentModifiers & (ModifierKeys::commandModifier | ModifierKeys::ctrlModifier)) != 0)
  933. textCharacter = 0;
  934. static juce_wchar lastTextCharacter = 0;
  935. switch (GetEventKind (theEvent))
  936. {
  937. case kEventRawKeyDown:
  938. keysCurrentlyDown.addIfNotAlreadyThere ((void*) keyCode);
  939. handleKeyUpOrDown();
  940. lastTextCharacter = textCharacter;
  941. handleKeyPress (keyCode, textCharacter);
  942. break;
  943. case kEventRawKeyUp:
  944. keysCurrentlyDown.removeValue ((void*) keyCode);
  945. handleKeyUpOrDown();
  946. lastTextCharacter = 0;
  947. break;
  948. case kEventRawKeyRepeat:
  949. handleKeyPress (keyCode, lastTextCharacter);
  950. break;
  951. case kEventRawKeyModifiersChanged:
  952. handleModifierKeysChange();
  953. break;
  954. default:
  955. jassertfalse
  956. break;
  957. }
  958. return noErr;
  959. }
  960. OSStatus handleTextInputEvent (EventRef theEvent)
  961. {
  962. UniChar uc;
  963. GetEventParameter (theEvent, kEventParamTextInputSendText, typeUnicodeText, 0, sizeof (uc), 0, &uc);
  964. EventRef originalEvent;
  965. GetEventParameter (theEvent, kEventParamTextInputSendKeyboardEvent, typeEventRef, 0, sizeof (originalEvent), 0, &originalEvent);
  966. handleKeyEvent (originalEvent, (juce_wchar) uc);
  967. return noErr;
  968. }
  969. OSStatus handleMouseEvent (EventHandlerCallRef callRef, EventRef theEvent)
  970. {
  971. MouseCheckTimer::getInstance()->moved (this);
  972. ::Point where;
  973. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof (::Point), 0, &where);
  974. int x = where.h;
  975. int y = where.v;
  976. globalPositionToRelative (x, y);
  977. int64 time = getEventTime (theEvent);
  978. switch (GetEventKind (theEvent))
  979. {
  980. case kEventMouseMoved:
  981. MouseCheckTimer::getInstance()->hasEverHadAMouseMove = true;
  982. updateModifiers (theEvent);
  983. handleMouseMove (x, y, time);
  984. break;
  985. case kEventMouseDragged:
  986. updateModifiers (theEvent);
  987. handleMouseDrag (x, y, time);
  988. break;
  989. case kEventMouseDown:
  990. {
  991. if (! Process::isForegroundProcess())
  992. {
  993. ProcessSerialNumber psn;
  994. GetCurrentProcess (&psn);
  995. SetFrontProcess (&psn);
  996. toFront (true);
  997. }
  998. #if JUCE_QUICKTIME
  999. {
  1000. long mods;
  1001. GetEventParameter (theEvent, kEventParamKeyModifiers, typeUInt32, 0, sizeof (mods), 0, &mods);
  1002. ::Point where;
  1003. GetEventParameter (theEvent, kEventParamMouseLocation, typeQDPoint, 0, sizeof (::Point), 0, &where);
  1004. OfferMouseClickToQuickTime (windowRef, where, EventTimeToTicks (GetEventTime (theEvent)), mods, component);
  1005. }
  1006. #endif
  1007. if (component->isBroughtToFrontOnMouseClick()
  1008. && ! component->isCurrentlyBlockedByAnotherModalComponent())
  1009. {
  1010. //ActivateWindow (windowRef, true);
  1011. SelectWindow (windowRef);
  1012. }
  1013. EventMouseButton button;
  1014. GetEventParameter (theEvent, kEventParamMouseButton, typeMouseButton, 0, sizeof (EventMouseButton), 0, &button);
  1015. // need to clear all these flags because sometimes the mac can swallow (right) mouse-up events and
  1016. // this makes a button get stuck down. Since there's no other way to tell what buttons are down,
  1017. // this is all I can think of doing about it..
  1018. currentModifiers &= ~(ModifierKeys::leftButtonModifier | ModifierKeys::rightButtonModifier | ModifierKeys::middleButtonModifier);
  1019. if (button == kEventMouseButtonPrimary)
  1020. currentModifiers |= ModifierKeys::leftButtonModifier;
  1021. else if (button == kEventMouseButtonSecondary)
  1022. currentModifiers |= ModifierKeys::rightButtonModifier;
  1023. else if (button == kEventMouseButtonTertiary)
  1024. currentModifiers |= ModifierKeys::middleButtonModifier;
  1025. updateModifiers (theEvent);
  1026. juce_currentMouseTrackingPeer = this; // puts the message dispatcher into mouse-tracking mode..
  1027. handleMouseDown (x, y, time);
  1028. break;
  1029. }
  1030. case kEventMouseUp:
  1031. {
  1032. const int oldModifiers = currentModifiers;
  1033. EventMouseButton button;
  1034. GetEventParameter (theEvent, kEventParamMouseButton, typeMouseButton, 0, sizeof (EventMouseButton), 0, &button);
  1035. if (button == kEventMouseButtonPrimary)
  1036. currentModifiers &= ~ModifierKeys::leftButtonModifier;
  1037. else if (button == kEventMouseButtonSecondary)
  1038. currentModifiers &= ~ModifierKeys::rightButtonModifier;
  1039. updateModifiers (theEvent);
  1040. handleMouseUp (oldModifiers, x, y, time);
  1041. juce_currentMouseTrackingPeer = 0;
  1042. break;
  1043. }
  1044. case kEventMouseWheelMoved:
  1045. {
  1046. EventMouseWheelAxis axis;
  1047. GetEventParameter (theEvent, kEventParamMouseWheelAxis, typeMouseWheelAxis, 0, sizeof (axis), 0, &axis);
  1048. SInt32 delta;
  1049. GetEventParameter (theEvent, kEventParamMouseWheelDelta,
  1050. typeLongInteger, 0, sizeof (delta), 0, &delta);
  1051. updateModifiers (theEvent);
  1052. handleMouseWheel (axis == kEventMouseWheelAxisX ? delta * 10 : 0,
  1053. axis == kEventMouseWheelAxisX ? 0 : delta * 10,
  1054. time);
  1055. break;
  1056. }
  1057. }
  1058. return noErr;
  1059. }
  1060. OSStatus handleDragAndDrop (EventRef theEvent)
  1061. {
  1062. DragRef dragRef;
  1063. if (GetEventParameter (theEvent, kEventParamDragRef, typeDragRef, 0, sizeof (dragRef), 0, &dragRef) == noErr)
  1064. {
  1065. int mx, my;
  1066. component->getMouseXYRelative (mx, my);
  1067. UInt16 numItems = 0;
  1068. if (CountDragItems (dragRef, &numItems) == noErr)
  1069. {
  1070. StringArray filenames;
  1071. for (int i = 0; i < (int) numItems; ++i)
  1072. {
  1073. DragItemRef ref;
  1074. if (GetDragItemReferenceNumber (dragRef, i + 1, &ref) == noErr)
  1075. {
  1076. const FlavorType flavorType = kDragFlavorTypeHFS;
  1077. Size size = 0;
  1078. if (GetFlavorDataSize (dragRef, ref, flavorType, &size) == noErr)
  1079. {
  1080. void* data = juce_calloc (size);
  1081. if (GetFlavorData (dragRef, ref, flavorType, data, &size, 0) == noErr)
  1082. {
  1083. HFSFlavor* f = (HFSFlavor*) data;
  1084. FSRef fsref;
  1085. if (FSpMakeFSRef (&f->fileSpec, &fsref) == noErr)
  1086. {
  1087. const String path (PlatformUtilities::makePathFromFSRef (&fsref));
  1088. if (path.isNotEmpty())
  1089. filenames.add (path);
  1090. }
  1091. }
  1092. juce_free (data);
  1093. }
  1094. }
  1095. }
  1096. filenames.trim();
  1097. filenames.removeEmptyStrings();
  1098. if (filenames.size() > 0)
  1099. handleFilesDropped (mx, my, filenames);
  1100. }
  1101. }
  1102. return noErr;
  1103. }
  1104. void resizeViewToFitWindow()
  1105. {
  1106. HIRect r;
  1107. if (isSharedWindow)
  1108. {
  1109. HIViewGetFrame (viewRef, &r);
  1110. r.size.width = (float) component->getWidth();
  1111. r.size.height = (float) component->getHeight();
  1112. }
  1113. else
  1114. {
  1115. r.origin.x = 0;
  1116. r.origin.y = 0;
  1117. Rect w;
  1118. GetWindowBounds (windowRef, windowRegionToUse, &w);
  1119. r.size.width = (float) (w.right - w.left);
  1120. r.size.height = (float) (w.bottom - w.top);
  1121. }
  1122. HIViewSetFrame (viewRef, &r);
  1123. #if MACOS_10_3_OR_EARLIER
  1124. component->repaint();
  1125. #endif
  1126. }
  1127. OSStatus hiViewDraw (EventRef theEvent)
  1128. {
  1129. CGContextRef context = 0;
  1130. GetEventParameter (theEvent, kEventParamCGContextRef, typeCGContextRef, 0, sizeof (CGContextRef), 0, &context);
  1131. CGrafPtr oldPort;
  1132. CGrafPtr port = 0;
  1133. if (context == 0)
  1134. {
  1135. GetEventParameter (theEvent, kEventParamGrafPort, typeGrafPtr, 0, sizeof (CGrafPtr), 0, &port);
  1136. GetPort (&oldPort);
  1137. SetPort (port);
  1138. if (port != 0)
  1139. QDBeginCGContext (port, &context);
  1140. if (! isCompositingWindow)
  1141. {
  1142. Rect bounds;
  1143. GetWindowBounds (windowRef, windowRegionToUse, &bounds);
  1144. CGContextTranslateCTM (context, 0, bounds.bottom - bounds.top);
  1145. CGContextScaleCTM (context, 1.0, -1.0);
  1146. }
  1147. if (isSharedWindow)
  1148. {
  1149. // NB - Had terrible problems trying to correctly get the position
  1150. // of this view relative to the window, and this seems wrong, but
  1151. // works better than any other method I've tried..
  1152. HIRect hiViewPos;
  1153. HIViewGetFrame (viewRef, &hiViewPos);
  1154. CGContextTranslateCTM (context, hiViewPos.origin.x, hiViewPos.origin.y);
  1155. }
  1156. }
  1157. #if MACOS_10_2_OR_EARLIER
  1158. RgnHandle rgn = 0;
  1159. GetEventParameter (theEvent, kEventParamRgnHandle, typeQDRgnHandle, 0, sizeof (RgnHandle), 0, &rgn);
  1160. CGRect clip;
  1161. if (rgn != 0)
  1162. {
  1163. Rect bounds;
  1164. GetRegionBounds (rgn, &bounds);
  1165. clip.origin.x = bounds.left;
  1166. clip.origin.y = bounds.top;
  1167. clip.size.width = bounds.right - bounds.left;
  1168. clip.size.height = bounds.bottom - bounds.top;
  1169. }
  1170. else
  1171. {
  1172. HIViewGetBounds (viewRef, &clip);
  1173. }
  1174. #else
  1175. CGRect clip (CGContextGetClipBoundingBox (context));
  1176. #endif
  1177. clip = CGRectIntegral (clip);
  1178. if (clip.origin.x < 0)
  1179. {
  1180. clip.size.width += clip.origin.x;
  1181. clip.origin.x = 0;
  1182. }
  1183. if (clip.origin.y < 0)
  1184. {
  1185. clip.size.height += clip.origin.y;
  1186. clip.origin.y = 0;
  1187. }
  1188. if (! component->isOpaque())
  1189. CGContextClearRect (context, clip);
  1190. repainter->paint (context,
  1191. (int) clip.origin.x, (int) clip.origin.y,
  1192. (int) clip.size.width, (int) clip.size.height);
  1193. if (port != 0)
  1194. {
  1195. CGContextFlush (context);
  1196. QDEndCGContext (port, &context);
  1197. SetPort (oldPort);
  1198. }
  1199. repainter->repaintAnyRemainingRegions();
  1200. return noErr;
  1201. }
  1202. static pascal OSStatus handleWindowEvent (EventHandlerCallRef callRef, EventRef theEvent, void* userData)
  1203. {
  1204. MessageManager::delayWaitCursor();
  1205. HIViewComponentPeer* const peer = (HIViewComponentPeer*) userData;
  1206. const MessageManagerLock messLock;
  1207. if (ComponentPeer::isValidPeer (peer))
  1208. return peer->handleWindowEventForPeer (callRef, theEvent);
  1209. return eventNotHandledErr;
  1210. }
  1211. OSStatus handleWindowEventForPeer (EventHandlerCallRef callRef, EventRef theEvent)
  1212. {
  1213. switch (GetEventClass (theEvent))
  1214. {
  1215. case kEventClassMouse:
  1216. {
  1217. static HIViewComponentPeer* lastMouseDownPeer = 0;
  1218. const UInt32 eventKind = GetEventKind (theEvent);
  1219. HIViewRef view = 0;
  1220. if (eventKind == kEventMouseDragged)
  1221. {
  1222. view = viewRef;
  1223. }
  1224. else
  1225. {
  1226. HIViewGetViewForMouseEvent (HIViewGetRoot (windowRef), theEvent, &view);
  1227. if (view != viewRef)
  1228. {
  1229. if ((eventKind == kEventMouseUp
  1230. || eventKind == kEventMouseExited)
  1231. && ComponentPeer::isValidPeer (lastMouseDownPeer))
  1232. {
  1233. return lastMouseDownPeer->handleMouseEvent (callRef, theEvent);
  1234. }
  1235. return eventNotHandledErr;
  1236. }
  1237. }
  1238. if (eventKind == kEventMouseDown
  1239. || eventKind == kEventMouseDragged
  1240. || eventKind == kEventMouseEntered)
  1241. {
  1242. lastMouseDownPeer = this;
  1243. }
  1244. return handleMouseEvent (callRef, theEvent);
  1245. }
  1246. break;
  1247. case kEventClassWindow:
  1248. return handleWindowClassEvent (theEvent);
  1249. case kEventClassKeyboard:
  1250. if (isFocused())
  1251. return handleKeyEvent (theEvent, 0);
  1252. break;
  1253. case kEventClassTextInput:
  1254. if (isFocused())
  1255. return handleTextInputEvent (theEvent);
  1256. break;
  1257. default:
  1258. break;
  1259. }
  1260. return eventNotHandledErr;
  1261. }
  1262. static pascal OSStatus hiViewEventHandler (EventHandlerCallRef myHandler, EventRef theEvent, void* userData)
  1263. {
  1264. MessageManager::delayWaitCursor();
  1265. const UInt32 eventKind = GetEventKind (theEvent);
  1266. const UInt32 eventClass = GetEventClass (theEvent);
  1267. if (eventClass == kEventClassHIObject)
  1268. {
  1269. switch (eventKind)
  1270. {
  1271. case kEventHIObjectConstruct:
  1272. {
  1273. void* data = juce_calloc (sizeof (void*));
  1274. SetEventParameter (theEvent, kEventParamHIObjectInstance,
  1275. typeVoidPtr, sizeof (void*), &data);
  1276. return noErr;
  1277. }
  1278. case kEventHIObjectInitialize:
  1279. GetEventParameter (theEvent, 'peer', typeVoidPtr, 0, sizeof (void*), 0, (void**) userData);
  1280. return noErr;
  1281. case kEventHIObjectDestruct:
  1282. juce_free (userData);
  1283. return noErr;
  1284. default:
  1285. break;
  1286. }
  1287. }
  1288. else if (eventClass == kEventClassControl)
  1289. {
  1290. HIViewComponentPeer* const peer = *(HIViewComponentPeer**) userData;
  1291. const MessageManagerLock messLock;
  1292. if (! ComponentPeer::isValidPeer (peer))
  1293. return eventNotHandledErr;
  1294. switch (eventKind)
  1295. {
  1296. case kEventControlDraw:
  1297. return peer->hiViewDraw (theEvent);
  1298. case kEventControlBoundsChanged:
  1299. {
  1300. HIRect bounds;
  1301. HIViewGetBounds (peer->viewRef, &bounds);
  1302. peer->repaint (0, 0, roundFloatToInt (bounds.size.width), roundFloatToInt (bounds.size.height));
  1303. peer->handleMovedOrResized();
  1304. return noErr;
  1305. }
  1306. case kEventControlHitTest:
  1307. {
  1308. HIPoint where;
  1309. GetEventParameter (theEvent, kEventParamMouseLocation, typeHIPoint, 0, sizeof (HIPoint), 0, &where);
  1310. HIRect bounds;
  1311. HIViewGetBounds (peer->viewRef, &bounds);
  1312. ControlPartCode part = kControlNoPart;
  1313. if (CGRectContainsPoint (bounds, where))
  1314. part = 1;
  1315. SetEventParameter (theEvent, kEventParamControlPart, typeControlPartCode, sizeof (ControlPartCode), &part);
  1316. return noErr;
  1317. }
  1318. break;
  1319. case kEventControlSetFocusPart:
  1320. {
  1321. ControlPartCode desiredFocus;
  1322. if (GetEventParameter (theEvent, kEventParamControlPart, typeControlPartCode, 0, sizeof (ControlPartCode), 0, &desiredFocus) != noErr)
  1323. break;
  1324. if (desiredFocus == kControlNoPart)
  1325. peer->viewFocusLoss();
  1326. else
  1327. peer->viewFocusGain();
  1328. return noErr;
  1329. }
  1330. break;
  1331. case kEventControlDragEnter:
  1332. {
  1333. #if MACOS_10_2_OR_EARLIER
  1334. enum { kEventParamControlWouldAcceptDrop = 'cldg' };
  1335. #endif
  1336. Boolean accept = true;
  1337. SetEventParameter (theEvent, kEventParamControlWouldAcceptDrop, typeBoolean, sizeof (accept), &accept);
  1338. return noErr;
  1339. }
  1340. case kEventControlDragWithin:
  1341. return noErr;
  1342. case kEventControlDragReceive:
  1343. return peer->handleDragAndDrop (theEvent);
  1344. case kEventControlOwningWindowChanged:
  1345. return peer->ownerWindowChanged (theEvent);
  1346. #if ! MACOS_10_2_OR_EARLIER
  1347. case kEventControlGetFrameMetrics:
  1348. {
  1349. CallNextEventHandler (myHandler, theEvent);
  1350. HIViewFrameMetrics metrics;
  1351. GetEventParameter (theEvent, kEventParamControlFrameMetrics, typeControlFrameMetrics, 0, sizeof (metrics), 0, &metrics);
  1352. metrics.top = metrics.bottom = 0;
  1353. SetEventParameter (theEvent, kEventParamControlFrameMetrics, typeControlFrameMetrics, sizeof (metrics), &metrics);
  1354. return noErr;
  1355. }
  1356. #endif
  1357. case kEventControlInitialize:
  1358. {
  1359. UInt32 features = kControlSupportsDragAndDrop
  1360. | kControlSupportsFocus
  1361. | kControlHandlesTracking
  1362. | kControlSupportsEmbedding
  1363. | (1 << 8) /*kHIViewFeatureGetsFocusOnClick*/;
  1364. SetEventParameter (theEvent, kEventParamControlFeatures, typeUInt32, sizeof (UInt32), &features);
  1365. return noErr;
  1366. }
  1367. default:
  1368. break;
  1369. }
  1370. }
  1371. return eventNotHandledErr;
  1372. }
  1373. WindowRef createNewWindow (const int windowStyleFlags)
  1374. {
  1375. jassert (windowRef == 0);
  1376. static ToolboxObjectClassRef customWindowClass = 0;
  1377. if (customWindowClass == 0)
  1378. {
  1379. // Register our window class
  1380. const EventTypeSpec customTypes[] = { { kEventClassWindow, kEventWindowDrawFrame } };
  1381. UnsignedWide t;
  1382. Microseconds (&t);
  1383. const String randomString ((int) (t.lo & 0x7ffffff));
  1384. const String juceWindowClassName (T("JUCEWindowClass_") + randomString);
  1385. CFStringRef juceWindowClassNameCFString = PlatformUtilities::juceStringToCFString (juceWindowClassName);
  1386. RegisterToolboxObjectClass (juceWindowClassNameCFString,
  1387. 0, 1, customTypes,
  1388. NewEventHandlerUPP (handleFrameRepaintEvent),
  1389. 0, &customWindowClass);
  1390. CFRelease (juceWindowClassNameCFString);
  1391. }
  1392. Rect pos;
  1393. pos.left = getComponent()->getX();
  1394. pos.top = getComponent()->getY();
  1395. pos.right = getComponent()->getRight();
  1396. pos.bottom = getComponent()->getBottom();
  1397. int attributes = kWindowStandardHandlerAttribute | kWindowCompositingAttribute;
  1398. if ((windowStyleFlags & windowHasDropShadow) == 0)
  1399. attributes |= kWindowNoShadowAttribute;
  1400. if ((windowStyleFlags & windowIgnoresMouseClicks) != 0)
  1401. attributes |= kWindowIgnoreClicksAttribute;
  1402. #if ! MACOS_10_3_OR_EARLIER
  1403. if ((windowStyleFlags & windowIsTemporary) != 0)
  1404. attributes |= kWindowDoesNotCycleAttribute;
  1405. #endif
  1406. WindowRef newWindow = 0;
  1407. if ((windowStyleFlags & windowHasTitleBar) == 0)
  1408. {
  1409. attributes |= kWindowCollapseBoxAttribute;
  1410. WindowDefSpec customWindowSpec;
  1411. customWindowSpec.defType = kWindowDefObjectClass;
  1412. customWindowSpec.u.classRef = customWindowClass;
  1413. CreateCustomWindow (&customWindowSpec,
  1414. ((windowStyleFlags & windowIsTemporary) != 0) ? kUtilityWindowClass :
  1415. (getComponent()->isAlwaysOnTop() ? kUtilityWindowClass
  1416. : kDocumentWindowClass),
  1417. attributes,
  1418. &pos,
  1419. &newWindow);
  1420. }
  1421. else
  1422. {
  1423. if ((windowStyleFlags & windowHasCloseButton) != 0)
  1424. attributes |= kWindowCloseBoxAttribute;
  1425. if ((windowStyleFlags & windowHasMinimiseButton) != 0)
  1426. attributes |= kWindowCollapseBoxAttribute;
  1427. if ((windowStyleFlags & windowHasMaximiseButton) != 0)
  1428. attributes |= kWindowFullZoomAttribute;
  1429. if ((windowStyleFlags & windowIsResizable) != 0)
  1430. attributes |= kWindowResizableAttribute | kWindowLiveResizeAttribute;
  1431. CreateNewWindow (kDocumentWindowClass, attributes, &pos, &newWindow);
  1432. }
  1433. jassert (newWindow != 0);
  1434. if (newWindow != 0)
  1435. {
  1436. HideWindow (newWindow);
  1437. SetAutomaticControlDragTrackingEnabledForWindow (newWindow, true);
  1438. if (! getComponent()->isOpaque())
  1439. SetWindowAlpha (newWindow, 0.9999999f); // to fool it into giving the window an alpha-channel
  1440. }
  1441. return newWindow;
  1442. }
  1443. OSStatus ownerWindowChanged (EventRef theEvent)
  1444. {
  1445. WindowRef newWindow = 0;
  1446. GetEventParameter (theEvent, kEventParamControlCurrentOwningWindow, typeWindowRef, 0, sizeof (newWindow), 0, &newWindow);
  1447. if (windowRef != newWindow)
  1448. {
  1449. if (eventHandlerRef != 0)
  1450. {
  1451. RemoveEventHandler (eventHandlerRef);
  1452. eventHandlerRef = 0;
  1453. }
  1454. windowRef = newWindow;
  1455. if (windowRef != 0)
  1456. {
  1457. const EventTypeSpec eventTypes[] =
  1458. {
  1459. { kEventClassWindow, kEventWindowBoundsChanged },
  1460. { kEventClassWindow, kEventWindowBoundsChanging },
  1461. { kEventClassWindow, kEventWindowFocusAcquired },
  1462. { kEventClassWindow, kEventWindowFocusRelinquish },
  1463. { kEventClassWindow, kEventWindowCollapsed },
  1464. { kEventClassWindow, kEventWindowExpanded },
  1465. { kEventClassWindow, kEventWindowShown },
  1466. { kEventClassWindow, kEventWindowClose },
  1467. { kEventClassMouse, kEventMouseDown },
  1468. { kEventClassMouse, kEventMouseUp },
  1469. { kEventClassMouse, kEventMouseMoved },
  1470. { kEventClassMouse, kEventMouseDragged },
  1471. { kEventClassMouse, kEventMouseEntered },
  1472. { kEventClassMouse, kEventMouseExited },
  1473. { kEventClassMouse, kEventMouseWheelMoved },
  1474. //{ kEventClassKeyboard, kEventRawKeyDown },
  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. if (ComponentPeer::isValidPeer (juce_currentMouseTrackingPeer))
  1591. {
  1592. const int oldModifiers = currentModifiers;
  1593. currentModifiers &= ~(ModifierKeys::leftButtonModifier | ModifierKeys::rightButtonModifier | ModifierKeys::middleButtonModifier);
  1594. updateModifiers (0);
  1595. juce_currentMouseTrackingPeer->handleMouseUp (oldModifiers, x, y, getEventTime (0));
  1596. }
  1597. juce_currentMouseTrackingPeer = 0;
  1598. }
  1599. }
  1600. bool juce_dispatchNextMessageOnSystemQueue (bool returnIfNoPendingMessages)
  1601. {
  1602. if (juce_currentMouseTrackingPeer != 0)
  1603. trackNextMouseEvent();
  1604. EventRef theEvent;
  1605. if (ReceiveNextEvent (0, 0, (returnIfNoPendingMessages) ? kEventDurationNoWait
  1606. : kEventDurationForever,
  1607. true, &theEvent) == noErr)
  1608. {
  1609. if (GetEventClass (theEvent) == kEventClassAppleEvent)
  1610. {
  1611. EventRecord eventRec;
  1612. if (ConvertEventRefToEventRecord (theEvent, &eventRec))
  1613. AEProcessAppleEvent (&eventRec);
  1614. }
  1615. else
  1616. {
  1617. EventTargetRef theTarget = GetEventDispatcherTarget();
  1618. SendEventToEventTarget (theEvent, theTarget);
  1619. }
  1620. ReleaseEvent (theEvent);
  1621. return true;
  1622. }
  1623. return false;
  1624. }
  1625. //==============================================================================
  1626. ComponentPeer* Component::createNewPeer (int styleFlags, void* windowToAttachTo)
  1627. {
  1628. return new HIViewComponentPeer (this, styleFlags, (HIViewRef) windowToAttachTo);
  1629. }
  1630. //==============================================================================
  1631. void MouseCheckTimer::timerCallback()
  1632. {
  1633. if (ModifierKeys::getCurrentModifiersRealtime().isAnyMouseButtonDown())
  1634. return;
  1635. if (Process::isForegroundProcess())
  1636. {
  1637. bool stillOver = false;
  1638. int x = 0, y = 0, w = 0, h = 0;
  1639. int mx = 0, my = 0;
  1640. const bool validWindow = ComponentPeer::isValidPeer (lastPeerUnderMouse);
  1641. if (validWindow)
  1642. {
  1643. lastPeerUnderMouse->getBounds (x, y, w, h, true);
  1644. Desktop::getMousePosition (mx, my);
  1645. stillOver = (mx >= x && my >= y && mx < x + w && my < y + h);
  1646. if (stillOver)
  1647. {
  1648. // check if it's over an embedded HIView
  1649. int rx = mx, ry = my;
  1650. lastPeerUnderMouse->globalPositionToRelative (rx, ry);
  1651. HIPoint hipoint;
  1652. hipoint.x = rx;
  1653. hipoint.y = ry;
  1654. HIViewRef root;
  1655. GetRootControl ((WindowRef) lastPeerUnderMouse->getNativeHandle(), &root);
  1656. HIViewRef hitview;
  1657. if (HIViewGetSubviewHit (root, &hipoint, true, &hitview) == noErr && hitview != 0)
  1658. {
  1659. stillOver = HIObjectIsOfClass ((HIObjectRef) hitview, juceHiViewClassNameCFString);
  1660. }
  1661. }
  1662. }
  1663. if (! stillOver)
  1664. {
  1665. // mouse is outside our windows so set a normal cursor (only
  1666. // if we're running as an app, not a plugin)
  1667. if (JUCEApplication::getInstance() != 0)
  1668. SetThemeCursor (kThemeArrowCursor);
  1669. if (validWindow)
  1670. lastPeerUnderMouse->handleMouseExit (mx - x, my - y, Time::currentTimeMillis());
  1671. if (hasEverHadAMouseMove)
  1672. stopTimer();
  1673. }
  1674. if ((! hasEverHadAMouseMove) && validWindow
  1675. && (mx != lastX || my != lastY))
  1676. {
  1677. lastX = mx;
  1678. lastY = my;
  1679. if (stillOver)
  1680. lastPeerUnderMouse->handleMouseMove (mx - x, my - y, Time::currentTimeMillis());
  1681. }
  1682. }
  1683. }
  1684. //==============================================================================
  1685. // called from juce_Messaging.cpp
  1686. void juce_HandleProcessFocusChange()
  1687. {
  1688. keysCurrentlyDown.clear();
  1689. if (HIViewComponentPeer::isValidPeer (currentlyFocusedPeer))
  1690. {
  1691. if (Process::isForegroundProcess())
  1692. currentlyFocusedPeer->handleFocusGain();
  1693. else
  1694. currentlyFocusedPeer->handleFocusLoss();
  1695. }
  1696. }
  1697. static bool performDrag (DragRef drag)
  1698. {
  1699. EventRecord event;
  1700. event.what = mouseDown;
  1701. event.message = 0;
  1702. event.when = TickCount();
  1703. int x, y;
  1704. Desktop::getMousePosition (x, y);
  1705. event.where.h = x;
  1706. event.where.v = y;
  1707. event.modifiers = GetCurrentKeyModifiers();
  1708. RgnHandle rgn = NewRgn();
  1709. RgnHandle rgn2 = NewRgn();
  1710. SetRectRgn (rgn,
  1711. event.where.h - 8, event.where.v - 8,
  1712. event.where.h + 8, event.where.v + 8);
  1713. CopyRgn (rgn, rgn2);
  1714. InsetRgn (rgn2, 1, 1);
  1715. DiffRgn (rgn, rgn2, rgn);
  1716. DisposeRgn (rgn2);
  1717. bool result = TrackDrag (drag, &event, rgn) == noErr;
  1718. DisposeRgn (rgn);
  1719. return result;
  1720. }
  1721. bool DragAndDropContainer::performExternalDragDropOfFiles (const StringArray& files, const bool canMoveFiles)
  1722. {
  1723. for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
  1724. ComponentPeer::getPeer (i)->performAnyPendingRepaintsNow();
  1725. DragRef drag;
  1726. bool result = false;
  1727. if (NewDrag (&drag) == noErr)
  1728. {
  1729. for (int i = 0; i < files.size(); ++i)
  1730. {
  1731. HFSFlavor hfsData;
  1732. if (PlatformUtilities::makeFSSpecFromPath (&hfsData.fileSpec, files[i]))
  1733. {
  1734. FInfo info;
  1735. if (FSpGetFInfo (&hfsData.fileSpec, &info) == noErr)
  1736. {
  1737. hfsData.fileType = info.fdType;
  1738. hfsData.fileCreator = info.fdCreator;
  1739. hfsData.fdFlags = info.fdFlags;
  1740. AddDragItemFlavor (drag, i + 1, kDragFlavorTypeHFS, &hfsData, sizeof (hfsData), 0);
  1741. result = true;
  1742. }
  1743. }
  1744. }
  1745. SetDragAllowableActions (drag, canMoveFiles ? kDragActionAll
  1746. : kDragActionCopy, false);
  1747. if (result)
  1748. result = performDrag (drag);
  1749. DisposeDrag (drag);
  1750. }
  1751. return result;
  1752. }
  1753. bool DragAndDropContainer::performExternalDragDropOfText (const String& text)
  1754. {
  1755. jassertfalse // not implemented!
  1756. return false;
  1757. }
  1758. //==============================================================================
  1759. bool Process::isForegroundProcess() throw()
  1760. {
  1761. ProcessSerialNumber psn, front;
  1762. GetCurrentProcess (&psn);
  1763. GetFrontProcess (&front);
  1764. Boolean b;
  1765. return (SameProcess (&psn, &front, &b) == noErr) && b;
  1766. }
  1767. //==============================================================================
  1768. bool Desktop::canUseSemiTransparentWindows()
  1769. {
  1770. return true;
  1771. }
  1772. //==============================================================================
  1773. void Desktop::getMousePosition (int& x, int& y)
  1774. {
  1775. CGrafPtr currentPort;
  1776. GetPort (&currentPort);
  1777. if (! IsValidPort (currentPort))
  1778. {
  1779. WindowRef front = FrontWindow();
  1780. if (front != 0)
  1781. {
  1782. SetPortWindowPort (front);
  1783. }
  1784. else
  1785. {
  1786. x = y = 0;
  1787. return;
  1788. }
  1789. }
  1790. ::Point p;
  1791. GetMouse (&p);
  1792. LocalToGlobal (&p);
  1793. x = p.h;
  1794. y = p.v;
  1795. SetPort (currentPort);
  1796. }
  1797. void Desktop::setMousePosition (int x, int y)
  1798. {
  1799. CGPoint pos = { x, y };
  1800. CGWarpMouseCursorPosition (pos);
  1801. }
  1802. const ModifierKeys ModifierKeys::getCurrentModifiersRealtime()
  1803. {
  1804. return ModifierKeys (currentModifiers);
  1805. }
  1806. //==============================================================================
  1807. void juce_updateMultiMonitorInfo (Array <Rectangle>& monitorCoords, const bool clipToWorkArea) throw()
  1808. {
  1809. int mainMonitorIndex = 0;
  1810. CGDirectDisplayID mainDisplayID = CGMainDisplayID();
  1811. CGDisplayCount count = 0;
  1812. CGDirectDisplayID disps [8];
  1813. if (CGGetActiveDisplayList (numElementsInArray (disps), disps, &count) == noErr)
  1814. {
  1815. for (int i = 0; i < count; ++i)
  1816. {
  1817. if (mainDisplayID == disps[i])
  1818. mainMonitorIndex = monitorCoords.size();
  1819. GDHandle hGDevice;
  1820. if (clipToWorkArea
  1821. && DMGetGDeviceByDisplayID ((DisplayIDType) disps[i], &hGDevice, false) == noErr)
  1822. {
  1823. Rect rect;
  1824. GetAvailableWindowPositioningBounds (hGDevice, &rect);
  1825. monitorCoords.add (Rectangle (rect.left,
  1826. rect.top,
  1827. rect.right - rect.left,
  1828. rect.bottom - rect.top));
  1829. }
  1830. else
  1831. {
  1832. const CGRect r (CGDisplayBounds (disps[i]));
  1833. monitorCoords.add (Rectangle (r.origin.x,
  1834. r.origin.y,
  1835. r.size.width,
  1836. r.size.height));
  1837. }
  1838. }
  1839. }
  1840. // make sure the first in the list is the main monitor
  1841. if (mainMonitorIndex > 0)
  1842. monitorCoords.swap (mainMonitorIndex, 0);
  1843. jassert (monitorCoords.size() > 0);
  1844. //xxx need to register for display change callbacks
  1845. }
  1846. //==============================================================================
  1847. struct CursorWrapper
  1848. {
  1849. Cursor* cursor;
  1850. ThemeCursor themeCursor;
  1851. };
  1852. void* juce_createMouseCursorFromImage (const Image& image, int hotspotX, int hotspotY) throw()
  1853. {
  1854. const int maxW = 16;
  1855. const int maxH = 16;
  1856. const Image* im = &image;
  1857. Image* newIm = 0;
  1858. if (image.getWidth() > maxW || image.getHeight() > maxH)
  1859. {
  1860. im = newIm = image.createCopy (maxW, maxH);
  1861. hotspotX = (hotspotX * maxW) / image.getWidth();
  1862. hotspotY = (hotspotY * maxH) / image.getHeight();
  1863. }
  1864. Cursor* const c = new Cursor();
  1865. c->hotSpot.h = hotspotX;
  1866. c->hotSpot.v = hotspotY;
  1867. for (int y = 0; y < maxH; ++y)
  1868. {
  1869. c->data[y] = 0;
  1870. c->mask[y] = 0;
  1871. for (int x = 0; x < maxW; ++x)
  1872. {
  1873. const Colour pixelColour (im->getPixelAt (15 - x, y));
  1874. if (pixelColour.getAlpha() > 0.5f)
  1875. {
  1876. c->mask[y] |= (1 << x);
  1877. if (pixelColour.getBrightness() < 0.5f)
  1878. c->data[y] |= (1 << x);
  1879. }
  1880. }
  1881. c->data[y] = CFSwapInt16BigToHost (c->data[y]);
  1882. c->mask[y] = CFSwapInt16BigToHost (c->mask[y]);
  1883. }
  1884. if (newIm != 0)
  1885. delete newIm;
  1886. CursorWrapper* const cw = new CursorWrapper();
  1887. cw->cursor = c;
  1888. cw->themeCursor = kThemeArrowCursor;
  1889. return (void*) cw;
  1890. }
  1891. static void* cursorFromData (const unsigned char* data, const int size, int hx, int hy) throw()
  1892. {
  1893. Image* const im = ImageFileFormat::loadFrom ((const char*) data, size);
  1894. jassert (im != 0);
  1895. void* curs = juce_createMouseCursorFromImage (*im, hx, hy);
  1896. delete im;
  1897. return curs;
  1898. }
  1899. const unsigned int kSpecialNoCursor = 'nocr';
  1900. void* juce_createStandardMouseCursor (MouseCursor::StandardCursorType type) throw()
  1901. {
  1902. ThemeCursor id = kThemeArrowCursor;
  1903. switch (type)
  1904. {
  1905. case MouseCursor::NormalCursor:
  1906. id = kThemeArrowCursor;
  1907. break;
  1908. case MouseCursor::NoCursor:
  1909. id = kSpecialNoCursor;
  1910. break;
  1911. case MouseCursor::DraggingHandCursor:
  1912. {
  1913. 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,
  1914. 0,0,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  1915. 16,0,0,2,52,148,47,0,200,185,16,130,90,12,74,139,107,84,123,39,
  1916. 132,117,151,116,132,146,248,60,209,138,98,22,203,114,34,236,37,52,77,217,
  1917. 247,154,191,119,110,240,193,128,193,95,163,56,60,234,98,135,2,0,59 };
  1918. const int cursDataSize = 99;
  1919. return cursorFromData (cursData, cursDataSize, 8, 8);
  1920. }
  1921. break;
  1922. case MouseCursor::CopyingCursor:
  1923. id = kThemeCopyArrowCursor;
  1924. break;
  1925. case MouseCursor::WaitCursor:
  1926. id = kThemeWatchCursor;
  1927. break;
  1928. case MouseCursor::IBeamCursor:
  1929. id = kThemeIBeamCursor;
  1930. break;
  1931. case MouseCursor::PointingHandCursor:
  1932. id = kThemePointingHandCursor;
  1933. break;
  1934. case MouseCursor::LeftRightResizeCursor:
  1935. case MouseCursor::LeftEdgeResizeCursor:
  1936. case MouseCursor::RightEdgeResizeCursor:
  1937. {
  1938. 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,
  1939. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  1940. 16,0,0,2,38,148,143,169,203,237,15,19,0,106,202,64,111,22,32,224,
  1941. 9,78,30,213,121,230,121,146,99,8,142,71,183,189,152,20,27,86,132,231,
  1942. 58,83,0,0,59 };
  1943. const int cursDataSize = 85;
  1944. return cursorFromData (cursData, cursDataSize, 8, 8);
  1945. }
  1946. case MouseCursor::UpDownResizeCursor:
  1947. case MouseCursor::TopEdgeResizeCursor:
  1948. case MouseCursor::BottomEdgeResizeCursor:
  1949. {
  1950. 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,
  1951. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  1952. 16,0,0,2,38,148,111,128,187,16,202,90,152,48,10,55,169,189,192,245,
  1953. 106,121,27,34,142,201,99,158,224,86,154,109,216,61,29,155,105,180,61,190,
  1954. 121,84,0,0,59 };
  1955. const int cursDataSize = 85;
  1956. return cursorFromData (cursData, cursDataSize, 8, 8);
  1957. }
  1958. case MouseCursor::TopLeftCornerResizeCursor:
  1959. case MouseCursor::BottomRightCornerResizeCursor:
  1960. {
  1961. 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,
  1962. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  1963. 16,0,0,2,43,132,15,162,187,16,255,18,99,14,202,217,44,158,213,221,
  1964. 237,9,225,38,94,35,73,5,31,42,170,108,106,174,112,43,195,209,91,185,
  1965. 104,174,131,208,77,66,28,10,0,59 };
  1966. const int cursDataSize = 90;
  1967. return cursorFromData (cursData, cursDataSize, 8, 8);
  1968. }
  1969. case MouseCursor::TopRightCornerResizeCursor:
  1970. case MouseCursor::BottomLeftCornerResizeCursor:
  1971. {
  1972. 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,
  1973. 255,255,0,0,0,33,249,4,1,0,0,2,0,44,0,0,0,0,16,0,
  1974. 16,0,0,2,45,148,127,160,11,232,16,98,108,14,65,73,107,194,122,223,
  1975. 92,65,141,216,145,134,162,153,221,25,128,73,166,62,173,16,203,237,188,94,
  1976. 120,46,237,105,239,123,48,80,157,2,0,59 };
  1977. const int cursDataSize = 92;
  1978. return cursorFromData (cursData, cursDataSize, 8, 8);
  1979. }
  1980. case MouseCursor::UpDownLeftRightResizeCursor:
  1981. {
  1982. 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,
  1983. 128,128,255,255,255,33,249,4,1,0,0,3,0,44,0,0,0,0,15,0,
  1984. 15,0,0,2,46,156,63,129,139,1,202,26,152,48,186,73,109,114,65,85,
  1985. 195,37,143,88,93,29,215,101,23,198,178,30,149,158,25,56,134,97,179,61,
  1986. 158,213,126,203,234,99,220,34,56,70,1,0,59,0,0 };
  1987. const int cursDataSize = 93;
  1988. return cursorFromData (cursData, cursDataSize, 7, 7);
  1989. }
  1990. case MouseCursor::CrosshairCursor:
  1991. id = kThemeCrossCursor;
  1992. break;
  1993. }
  1994. CursorWrapper* cw = new CursorWrapper();
  1995. cw->cursor = 0;
  1996. cw->themeCursor = id;
  1997. return (void*) cw;
  1998. }
  1999. void juce_deleteMouseCursor (void* const cursorHandle, const bool isStandard) throw()
  2000. {
  2001. CursorWrapper* const cw = (CursorWrapper*) cursorHandle;
  2002. if (cw != 0)
  2003. {
  2004. delete cw->cursor;
  2005. delete cw;
  2006. }
  2007. }
  2008. void MouseCursor::showInAllWindows() const throw()
  2009. {
  2010. showInWindow (0);
  2011. }
  2012. void MouseCursor::showInWindow (ComponentPeer*) const throw()
  2013. {
  2014. const CursorWrapper* const cw = (CursorWrapper*) getHandle();
  2015. if (cw != 0)
  2016. {
  2017. static bool isCursorHidden = false;
  2018. static bool showingWaitCursor = false;
  2019. const bool shouldShowWaitCursor = (cw->themeCursor == kThemeWatchCursor);
  2020. const bool shouldHideCursor = (cw->themeCursor == kSpecialNoCursor);
  2021. if (shouldShowWaitCursor != showingWaitCursor
  2022. && Process::isForegroundProcess())
  2023. {
  2024. showingWaitCursor = shouldShowWaitCursor;
  2025. QDDisplayWaitCursor (shouldShowWaitCursor);
  2026. }
  2027. if (shouldHideCursor != isCursorHidden)
  2028. {
  2029. isCursorHidden = shouldHideCursor;
  2030. if (shouldHideCursor)
  2031. HideCursor();
  2032. else
  2033. ShowCursor();
  2034. }
  2035. if (cw->cursor != 0)
  2036. SetCursor (cw->cursor);
  2037. else if (! (shouldShowWaitCursor || shouldHideCursor))
  2038. SetThemeCursor (cw->themeCursor);
  2039. }
  2040. }
  2041. //==============================================================================
  2042. Image* juce_createIconForFile (const File& file)
  2043. {
  2044. return 0;
  2045. }
  2046. //==============================================================================
  2047. class MainMenuHandler;
  2048. static MainMenuHandler* mainMenu = 0;
  2049. class MainMenuHandler : private MenuBarModelListener,
  2050. private DeletedAtShutdown
  2051. {
  2052. public:
  2053. MainMenuHandler() throw()
  2054. : currentModel (0)
  2055. {
  2056. }
  2057. ~MainMenuHandler() throw()
  2058. {
  2059. setMenu (0);
  2060. jassert (mainMenu == this);
  2061. mainMenu = 0;
  2062. }
  2063. void setMenu (MenuBarModel* const newMenuBarModel) throw()
  2064. {
  2065. if (currentModel != newMenuBarModel)
  2066. {
  2067. if (currentModel != 0)
  2068. currentModel->removeListener (this);
  2069. currentModel = newMenuBarModel;
  2070. if (currentModel != 0)
  2071. currentModel->addListener (this);
  2072. menuBarItemsChanged (0);
  2073. }
  2074. }
  2075. void menuBarItemsChanged (MenuBarModel*)
  2076. {
  2077. ClearMenuBar();
  2078. if (currentModel != 0)
  2079. {
  2080. int id = 1000;
  2081. const StringArray menuNames (currentModel->getMenuBarNames());
  2082. for (int i = 0; i < menuNames.size(); ++i)
  2083. {
  2084. const PopupMenu menu (currentModel->getMenuForIndex (i, menuNames [i]));
  2085. MenuRef m = createMenu (menu, menuNames [i], id);
  2086. InsertMenu (m, 0);
  2087. CFRelease (m);
  2088. }
  2089. }
  2090. }
  2091. void menuCommandInvoked (MenuBarModel*, const ApplicationCommandTarget::InvocationInfo& info)
  2092. {
  2093. MenuRef menu = 0;
  2094. MenuItemIndex index = 0;
  2095. GetIndMenuItemWithCommandID (0, info.commandID, 1, &menu, &index);
  2096. FlashMenuBar (GetMenuID (menu));
  2097. FlashMenuBar (GetMenuID (menu));
  2098. }
  2099. void invoke (const int id, ApplicationCommandManager* commandManager, const int topLevelIndex) const
  2100. {
  2101. if (currentModel != 0)
  2102. {
  2103. if (commandManager != 0)
  2104. {
  2105. ApplicationCommandTarget::InvocationInfo info (id);
  2106. info.invocationMethod = ApplicationCommandTarget::InvocationInfo::fromMenu;
  2107. commandManager->invoke (info, true);
  2108. }
  2109. currentModel->menuItemSelected (id, topLevelIndex);
  2110. }
  2111. }
  2112. MenuBarModel* currentModel;
  2113. private:
  2114. static MenuRef createMenu (const PopupMenu menu,
  2115. const String& menuName,
  2116. int& id)
  2117. {
  2118. MenuRef m = 0;
  2119. if (CreateNewMenu (id++, kMenuAttrAutoDisable, &m) == noErr)
  2120. {
  2121. CFStringRef name = PlatformUtilities::juceStringToCFString (menuName);
  2122. SetMenuTitleWithCFString (m, name);
  2123. CFRelease (name);
  2124. PopupMenu::MenuItemIterator iter (menu);
  2125. int topLevelIndex = 0;
  2126. while (iter.next())
  2127. {
  2128. MenuItemIndex index = 0;
  2129. int flags = kMenuAttrAutoDisable | kMenuItemAttrIgnoreMeta | kMenuItemAttrNotPreviousAlternate;
  2130. if (! iter.isEnabled)
  2131. flags |= kMenuItemAttrDisabled;
  2132. CFStringRef text = PlatformUtilities::juceStringToCFString (iter.itemName.upToFirstOccurrenceOf (T("<end>"), false, true));
  2133. if (iter.isSeparator)
  2134. {
  2135. AppendMenuItemTextWithCFString (m, text, kMenuItemAttrSeparator, 0, &index);
  2136. }
  2137. else if (iter.isSectionHeader)
  2138. {
  2139. AppendMenuItemTextWithCFString (m, text, kMenuItemAttrSectionHeader, 0, &index);
  2140. }
  2141. else if (iter.subMenu != 0)
  2142. {
  2143. AppendMenuItemTextWithCFString (m, text, flags, id++, &index);
  2144. MenuRef sub = createMenu (*iter.subMenu, iter.itemName, id);
  2145. SetMenuItemHierarchicalMenu (m, index, sub);
  2146. CFRelease (sub);
  2147. }
  2148. else
  2149. {
  2150. AppendMenuItemTextWithCFString (m, text, flags, iter.itemId, &index);
  2151. if (iter.isTicked)
  2152. CheckMenuItem (m, index, true);
  2153. SetMenuItemProperty (m, index, 'juce', 'apcm', sizeof (void*), &iter.commandManager);
  2154. SetMenuItemProperty (m, index, 'juce', 'topi', sizeof (int), &topLevelIndex);
  2155. if (iter.commandManager != 0)
  2156. {
  2157. const Array <KeyPress> keyPresses (iter.commandManager->getKeyMappings()
  2158. ->getKeyPressesAssignedToCommand (iter.itemId));
  2159. if (keyPresses.size() > 0)
  2160. {
  2161. const KeyPress& kp = keyPresses.getUnchecked(0);
  2162. int mods = 0;
  2163. if (kp.getModifiers().isShiftDown())
  2164. mods |= kMenuShiftModifier;
  2165. if (kp.getModifiers().isCtrlDown())
  2166. mods |= kMenuControlModifier;
  2167. if (kp.getModifiers().isAltDown())
  2168. mods |= kMenuOptionModifier;
  2169. if (! kp.getModifiers().isCommandDown())
  2170. mods |= kMenuNoCommandModifier;
  2171. tchar keyCode = (tchar) kp.getKeyCode();
  2172. if (kp.getKeyCode() >= KeyPress::numberPad0
  2173. && kp.getKeyCode() <= KeyPress::numberPad9)
  2174. {
  2175. keyCode = (tchar) ((T('0') - KeyPress::numberPad0) + kp.getKeyCode());
  2176. }
  2177. SetMenuItemCommandKey (m, index, true, 255);
  2178. if (CharacterFunctions::isLetterOrDigit (keyCode)
  2179. || CharacterFunctions::indexOfChar (T(",.;/\\'[]=-+_<>?{}\":"), keyCode, false) >= 0)
  2180. {
  2181. SetMenuItemModifiers (m, index, mods);
  2182. SetMenuItemCommandKey (m, index, false, CharacterFunctions::toUpperCase (keyCode));
  2183. }
  2184. else
  2185. {
  2186. const SInt16 glyph = getGlyphForKeyCode (kp.getKeyCode());
  2187. if (glyph != 0)
  2188. {
  2189. SetMenuItemModifiers (m, index, mods);
  2190. SetMenuItemKeyGlyph (m, index, glyph);
  2191. }
  2192. }
  2193. // if we set the key glyph to be a text char, and enable virtual
  2194. // key triggering, it stops the menu automatically triggering the callback
  2195. ChangeMenuItemAttributes (m, index, kMenuItemAttrUseVirtualKey, 0);
  2196. }
  2197. }
  2198. }
  2199. CFRelease (text);
  2200. ++topLevelIndex;
  2201. }
  2202. }
  2203. return m;
  2204. }
  2205. static SInt16 getGlyphForKeyCode (const int keyCode) throw()
  2206. {
  2207. if (keyCode == KeyPress::spaceKey)
  2208. return kMenuSpaceGlyph;
  2209. else if (keyCode == KeyPress::returnKey)
  2210. return kMenuReturnGlyph;
  2211. else if (keyCode == KeyPress::escapeKey)
  2212. return kMenuEscapeGlyph;
  2213. else if (keyCode == KeyPress::backspaceKey)
  2214. return kMenuDeleteLeftGlyph;
  2215. else if (keyCode == KeyPress::leftKey)
  2216. return kMenuLeftArrowGlyph;
  2217. else if (keyCode == KeyPress::rightKey)
  2218. return kMenuRightArrowGlyph;
  2219. else if (keyCode == KeyPress::upKey)
  2220. return kMenuUpArrowGlyph;
  2221. else if (keyCode == KeyPress::downKey)
  2222. return kMenuDownArrowGlyph;
  2223. else if (keyCode == KeyPress::pageUpKey)
  2224. return kMenuPageUpGlyph;
  2225. else if (keyCode == KeyPress::pageDownKey)
  2226. return kMenuPageDownGlyph;
  2227. else if (keyCode == KeyPress::endKey)
  2228. return kMenuSoutheastArrowGlyph;
  2229. else if (keyCode == KeyPress::homeKey)
  2230. return kMenuNorthwestArrowGlyph;
  2231. else if (keyCode == KeyPress::deleteKey)
  2232. return kMenuDeleteRightGlyph;
  2233. else if (keyCode == KeyPress::tabKey)
  2234. return kMenuTabRightGlyph;
  2235. else if (keyCode == KeyPress::F1Key)
  2236. return kMenuF1Glyph;
  2237. else if (keyCode == KeyPress::F2Key)
  2238. return kMenuF2Glyph;
  2239. else if (keyCode == KeyPress::F3Key)
  2240. return kMenuF3Glyph;
  2241. else if (keyCode == KeyPress::F4Key)
  2242. return kMenuF4Glyph;
  2243. else if (keyCode == KeyPress::F5Key)
  2244. return kMenuF5Glyph;
  2245. else if (keyCode == KeyPress::F6Key)
  2246. return kMenuF6Glyph;
  2247. else if (keyCode == KeyPress::F7Key)
  2248. return kMenuF7Glyph;
  2249. else if (keyCode == KeyPress::F8Key)
  2250. return kMenuF8Glyph;
  2251. else if (keyCode == KeyPress::F9Key)
  2252. return kMenuF9Glyph;
  2253. else if (keyCode == KeyPress::F10Key)
  2254. return kMenuF10Glyph;
  2255. else if (keyCode == KeyPress::F11Key)
  2256. return kMenuF11Glyph;
  2257. else if (keyCode == KeyPress::F12Key)
  2258. return kMenuF12Glyph;
  2259. else if (keyCode == KeyPress::F13Key)
  2260. return kMenuF13Glyph;
  2261. else if (keyCode == KeyPress::F14Key)
  2262. return kMenuF14Glyph;
  2263. else if (keyCode == KeyPress::F15Key)
  2264. return kMenuF15Glyph;
  2265. return 0;
  2266. }
  2267. };
  2268. void MenuBarModel::setMacMainMenu (MenuBarModel* newMenuBarModel) throw()
  2269. {
  2270. if (getMacMainMenu() != newMenuBarModel)
  2271. {
  2272. if (newMenuBarModel == 0)
  2273. {
  2274. delete mainMenu;
  2275. jassert (mainMenu == 0); // should be zeroed in the destructor
  2276. }
  2277. else
  2278. {
  2279. if (mainMenu == 0)
  2280. mainMenu = new MainMenuHandler();
  2281. mainMenu->setMenu (newMenuBarModel);
  2282. }
  2283. }
  2284. }
  2285. MenuBarModel* MenuBarModel::getMacMainMenu() throw()
  2286. {
  2287. return mainMenu != 0 ? mainMenu->currentModel : 0;
  2288. }
  2289. // these functions are called externally from the message handling code
  2290. void juce_MainMenuAboutToBeUsed()
  2291. {
  2292. // force an update of the items just before the menu appears..
  2293. if (mainMenu != 0)
  2294. mainMenu->menuBarItemsChanged (0);
  2295. }
  2296. void juce_InvokeMainMenuCommand (const HICommand& command)
  2297. {
  2298. if (mainMenu != 0)
  2299. {
  2300. ApplicationCommandManager* commandManager = 0;
  2301. int topLevelIndex = 0;
  2302. if (GetMenuItemProperty (command.menu.menuRef, command.menu.menuItemIndex,
  2303. 'juce', 'apcm', sizeof (commandManager), 0, &commandManager) == noErr
  2304. && GetMenuItemProperty (command.menu.menuRef, command.menu.menuItemIndex,
  2305. 'juce', 'topi', sizeof (topLevelIndex), 0, &topLevelIndex) == noErr)
  2306. {
  2307. mainMenu->invoke (command.commandID, commandManager, topLevelIndex);
  2308. }
  2309. }
  2310. }
  2311. //==============================================================================
  2312. void PlatformUtilities::beep()
  2313. {
  2314. SysBeep (30);
  2315. }
  2316. //==============================================================================
  2317. void SystemClipboard::copyTextToClipboard (const String& text)
  2318. {
  2319. ClearCurrentScrap();
  2320. ScrapRef ref;
  2321. GetCurrentScrap (&ref);
  2322. const int len = text.length();
  2323. const int numBytes = sizeof (UniChar) * len;
  2324. UniChar* const temp = (UniChar*) juce_calloc (numBytes);
  2325. for (int i = 0; i < len; ++i)
  2326. temp[i] = (UniChar) text[i];
  2327. PutScrapFlavor (ref,
  2328. kScrapFlavorTypeUnicode,
  2329. kScrapFlavorMaskNone,
  2330. numBytes,
  2331. temp);
  2332. juce_free (temp);
  2333. }
  2334. const String SystemClipboard::getTextFromClipboard()
  2335. {
  2336. String result;
  2337. ScrapRef ref;
  2338. GetCurrentScrap (&ref);
  2339. Size size = 0;
  2340. if (GetScrapFlavorSize (ref, kScrapFlavorTypeUnicode, &size) == noErr
  2341. && size > 0)
  2342. {
  2343. void* const data = juce_calloc (size + 8);
  2344. if (GetScrapFlavorData (ref, kScrapFlavorTypeUnicode, &size, data) == noErr)
  2345. {
  2346. result = PlatformUtilities::convertUTF16ToString ((UniChar*) data);
  2347. }
  2348. juce_free (data);
  2349. }
  2350. return result;
  2351. }
  2352. //==============================================================================
  2353. bool AlertWindow::showNativeDialogBox (const String& title,
  2354. const String& bodyText,
  2355. bool isOkCancel)
  2356. {
  2357. Str255 tit, txt;
  2358. PlatformUtilities::copyToStr255 (tit, title);
  2359. PlatformUtilities::copyToStr255 (txt, bodyText);
  2360. AlertStdAlertParamRec ar;
  2361. ar.movable = true;
  2362. ar.helpButton = false;
  2363. ar.filterProc = 0;
  2364. ar.defaultText = (const unsigned char*)-1;
  2365. ar.cancelText = (const unsigned char*)((isOkCancel) ? -1 : 0);
  2366. ar.otherText = 0;
  2367. ar.defaultButton = kAlertStdAlertOKButton;
  2368. ar.cancelButton = 0;
  2369. ar.position = kWindowDefaultPosition;
  2370. SInt16 result;
  2371. StandardAlert (kAlertNoteAlert, tit, txt, &ar, &result);
  2372. return result == kAlertStdAlertOKButton;
  2373. }
  2374. //==============================================================================
  2375. const int KeyPress::spaceKey = ' ';
  2376. const int KeyPress::returnKey = kReturnCharCode;
  2377. const int KeyPress::escapeKey = kEscapeCharCode;
  2378. const int KeyPress::backspaceKey = kBackspaceCharCode;
  2379. const int KeyPress::leftKey = kLeftArrowCharCode;
  2380. const int KeyPress::rightKey = kRightArrowCharCode;
  2381. const int KeyPress::upKey = kUpArrowCharCode;
  2382. const int KeyPress::downKey = kDownArrowCharCode;
  2383. const int KeyPress::pageUpKey = kPageUpCharCode;
  2384. const int KeyPress::pageDownKey = kPageDownCharCode;
  2385. const int KeyPress::endKey = kEndCharCode;
  2386. const int KeyPress::homeKey = kHomeCharCode;
  2387. const int KeyPress::deleteKey = kDeleteCharCode;
  2388. const int KeyPress::insertKey = -1;
  2389. const int KeyPress::tabKey = kTabCharCode;
  2390. const int KeyPress::F1Key = 0x10110;
  2391. const int KeyPress::F2Key = 0x10111;
  2392. const int KeyPress::F3Key = 0x10112;
  2393. const int KeyPress::F4Key = 0x10113;
  2394. const int KeyPress::F5Key = 0x10114;
  2395. const int KeyPress::F6Key = 0x10115;
  2396. const int KeyPress::F7Key = 0x10116;
  2397. const int KeyPress::F8Key = 0x10117;
  2398. const int KeyPress::F9Key = 0x10118;
  2399. const int KeyPress::F10Key = 0x10119;
  2400. const int KeyPress::F11Key = 0x1011a;
  2401. const int KeyPress::F12Key = 0x1011b;
  2402. const int KeyPress::F13Key = 0x1011c;
  2403. const int KeyPress::F14Key = 0x1011d;
  2404. const int KeyPress::F15Key = 0x1011e;
  2405. const int KeyPress::F16Key = 0x1011f;
  2406. const int KeyPress::numberPad0 = 0x30020;
  2407. const int KeyPress::numberPad1 = 0x30021;
  2408. const int KeyPress::numberPad2 = 0x30022;
  2409. const int KeyPress::numberPad3 = 0x30023;
  2410. const int KeyPress::numberPad4 = 0x30024;
  2411. const int KeyPress::numberPad5 = 0x30025;
  2412. const int KeyPress::numberPad6 = 0x30026;
  2413. const int KeyPress::numberPad7 = 0x30027;
  2414. const int KeyPress::numberPad8 = 0x30028;
  2415. const int KeyPress::numberPad9 = 0x30029;
  2416. const int KeyPress::numberPadAdd = 0x3002a;
  2417. const int KeyPress::numberPadSubtract = 0x3002b;
  2418. const int KeyPress::numberPadMultiply = 0x3002c;
  2419. const int KeyPress::numberPadDivide = 0x3002d;
  2420. const int KeyPress::numberPadSeparator = 0x3002e;
  2421. const int KeyPress::numberPadDecimalPoint = 0x3002f;
  2422. const int KeyPress::playKey = 0x30000;
  2423. const int KeyPress::stopKey = 0x30001;
  2424. const int KeyPress::fastForwardKey = 0x30002;
  2425. const int KeyPress::rewindKey = 0x30003;
  2426. //==============================================================================
  2427. #if JUCE_OPENGL
  2428. struct OpenGLContextInfo
  2429. {
  2430. AGLContext renderContext;
  2431. };
  2432. void* juce_createOpenGLContext (OpenGLComponent* component, void* sharedContext)
  2433. {
  2434. jassert (component != 0);
  2435. HIViewComponentPeer* const peer = dynamic_cast <HIViewComponentPeer*> (component->getTopLevelComponent()->getPeer());
  2436. if (peer == 0)
  2437. return 0;
  2438. OpenGLContextInfo* const oc = new OpenGLContextInfo();
  2439. GLint attrib[] = { AGL_RGBA, AGL_DOUBLEBUFFER,
  2440. AGL_RED_SIZE, 8,
  2441. AGL_ALPHA_SIZE, 8,
  2442. AGL_DEPTH_SIZE, 24,
  2443. AGL_CLOSEST_POLICY, AGL_NO_RECOVERY,
  2444. AGL_SAMPLE_BUFFERS_ARB, 1,
  2445. AGL_SAMPLES_ARB, 4,
  2446. AGL_NONE };
  2447. oc->renderContext = aglCreateContext (aglChoosePixelFormat (0, 0, attrib),
  2448. (sharedContext != 0) ? ((OpenGLContextInfo*) sharedContext)->renderContext
  2449. : 0);
  2450. aglSetDrawable (oc->renderContext,
  2451. GetWindowPort (peer->windowRef));
  2452. return oc;
  2453. }
  2454. void juce_updateOpenGLWindowPos (void* context, Component* owner, Component* topComp)
  2455. {
  2456. jassert (context != 0);
  2457. OpenGLContextInfo* const oc = (OpenGLContextInfo*) context;
  2458. GLint bufferRect[4];
  2459. bufferRect[0] = owner->getScreenX() - topComp->getScreenX();
  2460. bufferRect[1] = topComp->getHeight() - (owner->getHeight() + owner->getScreenY() - topComp->getScreenY());
  2461. bufferRect[2] = owner->getWidth();
  2462. bufferRect[3] = owner->getHeight();
  2463. aglSetInteger (oc->renderContext, AGL_BUFFER_RECT, bufferRect);
  2464. aglEnable (oc->renderContext, AGL_BUFFER_RECT);
  2465. }
  2466. void juce_deleteOpenGLContext (void* context)
  2467. {
  2468. OpenGLContextInfo* const oc = (OpenGLContextInfo*) context;
  2469. aglDestroyContext (oc->renderContext);
  2470. delete oc;
  2471. }
  2472. bool juce_makeOpenGLContextCurrent (void* context)
  2473. {
  2474. OpenGLContextInfo* const oc = (OpenGLContextInfo*) context;
  2475. return aglSetCurrentContext ((oc != 0) ? oc->renderContext : 0);
  2476. }
  2477. void juce_swapOpenGLBuffers (void* context)
  2478. {
  2479. OpenGLContextInfo* const oc = (OpenGLContextInfo*) context;
  2480. if (oc != 0)
  2481. aglSwapBuffers (oc->renderContext);
  2482. }
  2483. void juce_repaintOpenGLWindow (void* context)
  2484. {
  2485. }
  2486. #endif
  2487. END_JUCE_NAMESPACE