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.

3066 lines
103KB

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