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.

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