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.

3065 lines
102KB

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