/src/gui/kernel/qt_cocoa_helpers_mac.mm

https://bitbucket.org/ultra_iter/qt-vtl
Objective C++ | 1824 lines | 1446 code | 174 blank | 204 comment | 309 complexity | 4c3725c0300d127271ff0d64d4fe84aa MD5 | raw file

Large files are truncated, but you can click here to view the full file

  1. /****************************************************************************
  2. **
  3. ** Copyright (C) 2012 Nokia Corporation and/or its subsidiary(-ies).
  4. ** All rights reserved.
  5. ** Contact: Nokia Corporation (qt-info@nokia.com)
  6. **
  7. ** This file is part of the QtGui module of the Qt Toolkit.
  8. **
  9. ** $QT_BEGIN_LICENSE:LGPL$
  10. ** GNU Lesser General Public License Usage
  11. ** This file may be used under the terms of the GNU Lesser General Public
  12. ** License version 2.1 as published by the Free Software Foundation and
  13. ** appearing in the file LICENSE.LGPL included in the packaging of this
  14. ** file. Please review the following information to ensure the GNU Lesser
  15. ** General Public License version 2.1 requirements will be met:
  16. ** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
  17. **
  18. ** In addition, as a special exception, Nokia gives you certain additional
  19. ** rights. These rights are described in the Nokia Qt LGPL Exception
  20. ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
  21. **
  22. ** GNU General Public License Usage
  23. ** Alternatively, this file may be used under the terms of the GNU General
  24. ** Public License version 3.0 as published by the Free Software Foundation
  25. ** and appearing in the file LICENSE.GPL included in the packaging of this
  26. ** file. Please review the following information to ensure the GNU General
  27. ** Public License version 3.0 requirements will be met:
  28. ** http://www.gnu.org/copyleft/gpl.html.
  29. **
  30. ** Other Usage
  31. ** Alternatively, this file may be used in accordance with the terms and
  32. ** conditions contained in a signed written agreement between you and Nokia.
  33. **
  34. **
  35. **
  36. **
  37. **
  38. ** $QT_END_LICENSE$
  39. **
  40. ****************************************************************************/
  41. /****************************************************************************
  42. **
  43. ** Copyright (c) 2007-2008, Apple, Inc.
  44. **
  45. ** All rights reserved.
  46. **
  47. ** Redistribution and use in source and binary forms, with or without
  48. ** modification, are permitted provided that the following conditions are met:
  49. **
  50. ** * Redistributions of source code must retain the above copyright notice,
  51. ** this list of conditions and the following disclaimer.
  52. **
  53. ** * Redistributions in binary form must reproduce the above copyright notice,
  54. ** this list of conditions and the following disclaimer in the documentation
  55. ** and/or other materials provided with the distribution.
  56. **
  57. ** * Neither the name of Apple, Inc. nor the names of its contributors
  58. ** may be used to endorse or promote products derived from this software
  59. ** without specific prior written permission.
  60. **
  61. ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  62. ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  63. ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  64. ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
  65. ** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  66. ** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
  67. ** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
  68. ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
  69. ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  70. ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  71. ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  72. **
  73. ****************************************************************************/
  74. #include <private/qcore_mac_p.h>
  75. #include <qaction.h>
  76. #include <qwidget.h>
  77. #include <qdesktopwidget.h>
  78. #include <qevent.h>
  79. #include <qpixmapcache.h>
  80. #include <qvarlengtharray.h>
  81. #include <private/qevent_p.h>
  82. #include <private/qt_cocoa_helpers_mac_p.h>
  83. #include <private/qt_mac_p.h>
  84. #include <private/qapplication_p.h>
  85. #include <private/qcocoaapplication_mac_p.h>
  86. #include <private/qcocoawindow_mac_p.h>
  87. #include <private/qcocoaview_mac_p.h>
  88. #include <private/qkeymapper_p.h>
  89. #include <private/qwidget_p.h>
  90. #include <private/qcocoawindow_mac_p.h>
  91. QT_BEGIN_NAMESPACE
  92. #ifdef QT_MAC_USE_COCOA
  93. // Cmd + left mousebutton should produce a right button
  94. // press (mainly for mac users with one-button mice):
  95. static bool qt_leftButtonIsRightButton = false;
  96. #endif
  97. Q_GLOBAL_STATIC(QMacWindowFader, macwindowFader);
  98. QMacWindowFader::QMacWindowFader()
  99. : m_duration(0.250)
  100. {
  101. }
  102. QMacWindowFader *QMacWindowFader::currentFader()
  103. {
  104. return macwindowFader();
  105. }
  106. void QMacWindowFader::registerWindowToFade(QWidget *window)
  107. {
  108. m_windowsToFade.append(window);
  109. }
  110. void QMacWindowFader::performFade()
  111. {
  112. const QWidgetList myWidgetsToFade = m_windowsToFade;
  113. const int widgetCount = myWidgetsToFade.count();
  114. #if QT_MAC_USE_COCOA
  115. QMacCocoaAutoReleasePool pool;
  116. [NSAnimationContext beginGrouping];
  117. [[NSAnimationContext currentContext] setDuration:NSTimeInterval(m_duration)];
  118. #endif
  119. for (int i = 0; i < widgetCount; ++i) {
  120. QWidget *widget = m_windowsToFade.at(i);
  121. OSWindowRef window = qt_mac_window_for(widget);
  122. #if QT_MAC_USE_COCOA
  123. [[window animator] setAlphaValue:0.0];
  124. QTimer::singleShot(qRound(m_duration * 1000), widget, SLOT(hide()));
  125. #else
  126. TransitionWindowOptions options = {0, m_duration, 0, 0};
  127. TransitionWindowWithOptions(window, kWindowFadeTransitionEffect, kWindowHideTransitionAction,
  128. 0, 1, &options);
  129. #endif
  130. }
  131. #if QT_MAC_USE_COCOA
  132. [NSAnimationContext endGrouping];
  133. #endif
  134. m_duration = 0.250;
  135. m_windowsToFade.clear();
  136. }
  137. extern bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event); // qapplication.cpp;
  138. extern QWidget * mac_mouse_grabber;
  139. extern QWidget *qt_button_down; //qapplication_mac.cpp
  140. extern QPointer<QWidget> qt_last_mouse_receiver;
  141. extern OSViewRef qt_mac_effectiveview_for(const QWidget *w);
  142. extern void qt_mac_updateCursorWithWidgetUnderMouse(QWidget *widgetUnderMouse); // qcursor_mac.mm
  143. void macWindowFade(void * /*OSWindowRef*/ window, float durationSeconds)
  144. {
  145. #ifdef QT_MAC_USE_COCOA
  146. QMacCocoaAutoReleasePool pool;
  147. #endif
  148. OSWindowRef wnd = static_cast<OSWindowRef>(window);
  149. if (wnd) {
  150. QWidget *widget;
  151. #if QT_MAC_USE_COCOA
  152. widget = [wnd QT_MANGLE_NAMESPACE(qt_qwidget)];
  153. #else
  154. const UInt32 kWidgetCreatorQt = kEventClassQt;
  155. enum {
  156. kWidgetPropertyQWidget = 'QWId' //QWidget *
  157. };
  158. if (GetWindowProperty(static_cast<WindowRef>(window), kWidgetCreatorQt, kWidgetPropertyQWidget, sizeof(widget), 0, &widget) != noErr)
  159. widget = 0;
  160. #endif
  161. if (widget) {
  162. QMacWindowFader::currentFader()->setFadeDuration(durationSeconds);
  163. QMacWindowFader::currentFader()->registerWindowToFade(widget);
  164. QMacWindowFader::currentFader()->performFade();
  165. }
  166. }
  167. }
  168. struct dndenum_mapper
  169. {
  170. NSDragOperation mac_code;
  171. Qt::DropAction qt_code;
  172. bool Qt2Mac;
  173. };
  174. #if defined(QT_MAC_USE_COCOA) && defined(__OBJC__)
  175. static dndenum_mapper dnd_enums[] = {
  176. { NSDragOperationLink, Qt::LinkAction, true },
  177. { NSDragOperationMove, Qt::MoveAction, true },
  178. { NSDragOperationCopy, Qt::CopyAction, true },
  179. { NSDragOperationGeneric, Qt::CopyAction, false },
  180. { NSDragOperationEvery, Qt::ActionMask, false },
  181. { NSDragOperationNone, Qt::IgnoreAction, false }
  182. };
  183. NSDragOperation qt_mac_mapDropAction(Qt::DropAction action)
  184. {
  185. for (int i=0; dnd_enums[i].qt_code; i++) {
  186. if (dnd_enums[i].Qt2Mac && (action & dnd_enums[i].qt_code)) {
  187. return dnd_enums[i].mac_code;
  188. }
  189. }
  190. return NSDragOperationNone;
  191. }
  192. NSDragOperation qt_mac_mapDropActions(Qt::DropActions actions)
  193. {
  194. NSDragOperation nsActions = NSDragOperationNone;
  195. for (int i=0; dnd_enums[i].qt_code; i++) {
  196. if (dnd_enums[i].Qt2Mac && (actions & dnd_enums[i].qt_code))
  197. nsActions |= dnd_enums[i].mac_code;
  198. }
  199. return nsActions;
  200. }
  201. Qt::DropAction qt_mac_mapNSDragOperation(NSDragOperation nsActions)
  202. {
  203. Qt::DropAction action = Qt::IgnoreAction;
  204. for (int i=0; dnd_enums[i].mac_code; i++) {
  205. if (nsActions & dnd_enums[i].mac_code)
  206. return dnd_enums[i].qt_code;
  207. }
  208. return action;
  209. }
  210. Qt::DropActions qt_mac_mapNSDragOperations(NSDragOperation nsActions)
  211. {
  212. Qt::DropActions actions = Qt::IgnoreAction;
  213. for (int i=0; dnd_enums[i].mac_code; i++) {
  214. if (nsActions & dnd_enums[i].mac_code)
  215. actions |= dnd_enums[i].qt_code;
  216. }
  217. return actions;
  218. }
  219. Q_GLOBAL_STATIC(DnDParams, currentDnDParameters);
  220. DnDParams *macCurrentDnDParameters()
  221. {
  222. return currentDnDParameters();
  223. }
  224. #endif
  225. bool macWindowIsTextured( void * /*OSWindowRef*/ window )
  226. {
  227. OSWindowRef wnd = static_cast<OSWindowRef>(window);
  228. #if QT_MAC_USE_COCOA
  229. return ( [wnd styleMask] & NSTexturedBackgroundWindowMask ) ? true : false;
  230. #else
  231. WindowAttributes currentAttributes;
  232. GetWindowAttributes(wnd, &currentAttributes);
  233. return (currentAttributes & kWindowMetalAttribute) ? true : false;
  234. #endif
  235. }
  236. void macWindowToolbarShow(const QWidget *widget, bool show )
  237. {
  238. OSWindowRef wnd = qt_mac_window_for(widget);
  239. #if QT_MAC_USE_COCOA
  240. if (NSToolbar *toolbar = [wnd toolbar]) {
  241. QMacCocoaAutoReleasePool pool;
  242. if (show != [toolbar isVisible]) {
  243. [toolbar setVisible:show];
  244. } else {
  245. // The toolbar may be in sync, but we are not, update our framestrut.
  246. qt_widget_private(const_cast<QWidget *>(widget))->updateFrameStrut();
  247. }
  248. }
  249. #else
  250. qt_widget_private(const_cast<QWidget *>(widget))->updateFrameStrut();
  251. ShowHideWindowToolbar(wnd, show, false);
  252. #endif
  253. }
  254. void macWindowToolbarSet( void * /*OSWindowRef*/ window, void *toolbarRef )
  255. {
  256. OSWindowRef wnd = static_cast<OSWindowRef>(window);
  257. #if QT_MAC_USE_COCOA
  258. [wnd setToolbar:static_cast<NSToolbar *>(toolbarRef)];
  259. #else
  260. SetWindowToolbar(wnd, static_cast<HIToolbarRef>(toolbarRef));
  261. #endif
  262. }
  263. bool macWindowToolbarIsVisible( void * /*OSWindowRef*/ window )
  264. {
  265. OSWindowRef wnd = static_cast<OSWindowRef>(window);
  266. #if QT_MAC_USE_COCOA
  267. if (NSToolbar *toolbar = [wnd toolbar])
  268. return [toolbar isVisible];
  269. return false;
  270. #else
  271. return IsWindowToolbarVisible(wnd);
  272. #endif
  273. }
  274. void macWindowSetHasShadow( void * /*OSWindowRef*/ window, bool hasShadow )
  275. {
  276. OSWindowRef wnd = static_cast<OSWindowRef>(window);
  277. #if QT_MAC_USE_COCOA
  278. [wnd setHasShadow:BOOL(hasShadow)];
  279. #else
  280. if (hasShadow)
  281. ChangeWindowAttributes(wnd, 0, kWindowNoShadowAttribute);
  282. else
  283. ChangeWindowAttributes(wnd, kWindowNoShadowAttribute, 0);
  284. #endif
  285. }
  286. void macWindowFlush(void * /*OSWindowRef*/ window)
  287. {
  288. OSWindowRef wnd = static_cast<OSWindowRef>(window);
  289. #if QT_MAC_USE_COCOA
  290. [wnd flushWindowIfNeeded];
  291. #else
  292. HIWindowFlush(wnd);
  293. #endif
  294. }
  295. void * /*NSImage */qt_mac_create_nsimage(const QPixmap &pm)
  296. {
  297. QMacCocoaAutoReleasePool pool;
  298. if(QCFType<CGImageRef> image = pm.toMacCGImageRef()) {
  299. NSImage *newImage = 0;
  300. NSRect imageRect = NSMakeRect(0.0, 0.0, CGImageGetWidth(image), CGImageGetHeight(image));
  301. newImage = [[NSImage alloc] initWithSize:imageRect.size];
  302. [newImage lockFocus];
  303. {
  304. CGContextRef imageContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
  305. CGContextDrawImage(imageContext, *(CGRect*)&imageRect, image);
  306. }
  307. [newImage unlockFocus];
  308. return newImage;
  309. }
  310. return 0;
  311. }
  312. void qt_mac_update_mouseTracking(QWidget *widget)
  313. {
  314. #ifdef QT_MAC_USE_COCOA
  315. [qt_mac_nativeview_for(widget) updateTrackingAreas];
  316. #else
  317. Q_UNUSED(widget);
  318. #endif
  319. }
  320. OSStatus qt_mac_drawCGImage(CGContextRef inContext, const CGRect *inBounds, CGImageRef inImage)
  321. {
  322. // Verbatim copy if HIViewDrawCGImage (as shown on Carbon-Dev)
  323. OSStatus err = noErr;
  324. require_action(inContext != NULL, InvalidContext, err = paramErr);
  325. require_action(inBounds != NULL, InvalidBounds, err = paramErr);
  326. require_action(inImage != NULL, InvalidImage, err = paramErr);
  327. CGContextSaveGState( inContext );
  328. CGContextTranslateCTM (inContext, 0, inBounds->origin.y + CGRectGetMaxY(*inBounds));
  329. CGContextScaleCTM(inContext, 1, -1);
  330. CGContextDrawImage(inContext, *inBounds, inImage);
  331. CGContextRestoreGState(inContext);
  332. InvalidImage:
  333. InvalidBounds:
  334. InvalidContext:
  335. return err;
  336. }
  337. bool qt_mac_checkForNativeSizeGrip(const QWidget *widget)
  338. {
  339. #ifndef QT_MAC_USE_COCOA
  340. OSViewRef nativeSizeGrip = 0;
  341. HIViewFindByID(HIViewGetRoot(HIViewGetWindow(HIViewRef(widget->winId()))), kHIViewWindowGrowBoxID, &nativeSizeGrip);
  342. return (nativeSizeGrip != 0);
  343. #else
  344. return [[reinterpret_cast<NSView *>(widget->effectiveWinId()) window] showsResizeIndicator];
  345. #endif
  346. }
  347. struct qt_mac_enum_mapper
  348. {
  349. int mac_code;
  350. int qt_code;
  351. #if defined(DEBUG_MOUSE_MAPS)
  352. # define QT_MAC_MAP_ENUM(x) x, #x
  353. const char *desc;
  354. #else
  355. # define QT_MAC_MAP_ENUM(x) x
  356. #endif
  357. };
  358. //mouse buttons
  359. static qt_mac_enum_mapper qt_mac_mouse_symbols[] = {
  360. { kEventMouseButtonPrimary, QT_MAC_MAP_ENUM(Qt::LeftButton) },
  361. { kEventMouseButtonSecondary, QT_MAC_MAP_ENUM(Qt::RightButton) },
  362. { kEventMouseButtonTertiary, QT_MAC_MAP_ENUM(Qt::MidButton) },
  363. { 4, QT_MAC_MAP_ENUM(Qt::XButton1) },
  364. { 5, QT_MAC_MAP_ENUM(Qt::XButton2) },
  365. { 0, QT_MAC_MAP_ENUM(0) }
  366. };
  367. Qt::MouseButtons qt_mac_get_buttons(int buttons)
  368. {
  369. #ifdef DEBUG_MOUSE_MAPS
  370. qDebug("Qt: internal: **Mapping buttons: %d (0x%04x)", buttons, buttons);
  371. #endif
  372. Qt::MouseButtons ret = Qt::NoButton;
  373. for(int i = 0; qt_mac_mouse_symbols[i].qt_code; i++) {
  374. if (buttons & (0x01<<(qt_mac_mouse_symbols[i].mac_code-1))) {
  375. #ifdef DEBUG_MOUSE_MAPS
  376. qDebug("Qt: internal: got button: %s", qt_mac_mouse_symbols[i].desc);
  377. #endif
  378. ret |= Qt::MouseButtons(qt_mac_mouse_symbols[i].qt_code);
  379. }
  380. }
  381. return ret;
  382. }
  383. Qt::MouseButton qt_mac_get_button(EventMouseButton button)
  384. {
  385. #ifdef DEBUG_MOUSE_MAPS
  386. qDebug("Qt: internal: **Mapping button: %d (0x%04x)", button, button);
  387. #endif
  388. Qt::MouseButtons ret = 0;
  389. for(int i = 0; qt_mac_mouse_symbols[i].qt_code; i++) {
  390. if (button == qt_mac_mouse_symbols[i].mac_code) {
  391. #ifdef DEBUG_MOUSE_MAPS
  392. qDebug("Qt: internal: got button: %s", qt_mac_mouse_symbols[i].desc);
  393. #endif
  394. return Qt::MouseButton(qt_mac_mouse_symbols[i].qt_code);
  395. }
  396. }
  397. return Qt::NoButton;
  398. }
  399. void macSendToolbarChangeEvent(QWidget *widget)
  400. {
  401. QToolBarChangeEvent ev(!(GetCurrentKeyModifiers() & cmdKey));
  402. qt_sendSpontaneousEvent(widget, &ev);
  403. }
  404. Q_GLOBAL_STATIC(QMacTabletHash, tablet_hash)
  405. QMacTabletHash *qt_mac_tablet_hash()
  406. {
  407. return tablet_hash();
  408. }
  409. #ifdef QT_MAC_USE_COCOA
  410. // Clears the QWidget pointer that each QCocoaView holds.
  411. void qt_mac_clearCocoaViewQWidgetPointers(QWidget *widget)
  412. {
  413. QT_MANGLE_NAMESPACE(QCocoaView) *cocoaView = reinterpret_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(qt_mac_nativeview_for(widget));
  414. if (cocoaView && [cocoaView respondsToSelector:@selector(qt_qwidget)]) {
  415. [cocoaView qt_clearQWidget];
  416. }
  417. }
  418. void qt_dispatchTabletProximityEvent(void * /*NSEvent * */ tabletEvent)
  419. {
  420. NSEvent *proximityEvent = static_cast<NSEvent *>(tabletEvent);
  421. // simply construct a Carbon proximity record and handle it all in one spot.
  422. TabletProximityRec carbonProximityRec = { [proximityEvent vendorID],
  423. [proximityEvent tabletID],
  424. [proximityEvent pointingDeviceID],
  425. [proximityEvent deviceID],
  426. [proximityEvent systemTabletID],
  427. [proximityEvent vendorPointingDeviceType],
  428. [proximityEvent pointingDeviceSerialNumber],
  429. [proximityEvent uniqueID],
  430. [proximityEvent capabilityMask],
  431. [proximityEvent pointingDeviceType],
  432. [proximityEvent isEnteringProximity] };
  433. qt_dispatchTabletProximityEvent(carbonProximityRec);
  434. }
  435. #endif // QT_MAC_USE_COCOA
  436. void qt_dispatchTabletProximityEvent(const ::TabletProximityRec &proxRec)
  437. {
  438. QTabletDeviceData proximityDevice;
  439. proximityDevice.tabletUniqueID = proxRec.uniqueID;
  440. proximityDevice.capabilityMask = proxRec.capabilityMask;
  441. switch (proxRec.pointerType) {
  442. case NSUnknownPointingDevice:
  443. default:
  444. proximityDevice.tabletPointerType = QTabletEvent::UnknownPointer;
  445. break;
  446. case NSPenPointingDevice:
  447. proximityDevice.tabletPointerType = QTabletEvent::Pen;
  448. break;
  449. case NSCursorPointingDevice:
  450. proximityDevice.tabletPointerType = QTabletEvent::Cursor;
  451. break;
  452. case NSEraserPointingDevice:
  453. proximityDevice.tabletPointerType = QTabletEvent::Eraser;
  454. break;
  455. }
  456. uint bits = proxRec.vendorPointerType;
  457. if (bits == 0 && proximityDevice.tabletUniqueID != 0) {
  458. // Fallback. It seems that the driver doesn't always include all the information.
  459. // High-End Wacom devices store their "type" in the uper bits of the Unique ID.
  460. // I'm not sure how to handle it for consumer devices, but I'll test that in a bit.
  461. bits = proximityDevice.tabletUniqueID >> 32;
  462. }
  463. // Defined in the "EN0056-NxtGenImpGuideX"
  464. // on Wacom's Developer Website (www.wacomeng.com)
  465. if (((bits & 0x0006) == 0x0002) && ((bits & 0x0F06) != 0x0902)) {
  466. proximityDevice.tabletDeviceType = QTabletEvent::Stylus;
  467. } else {
  468. switch (bits & 0x0F06) {
  469. case 0x0802:
  470. proximityDevice.tabletDeviceType = QTabletEvent::Stylus;
  471. break;
  472. case 0x0902:
  473. proximityDevice.tabletDeviceType = QTabletEvent::Airbrush;
  474. break;
  475. case 0x0004:
  476. proximityDevice.tabletDeviceType = QTabletEvent::FourDMouse;
  477. break;
  478. case 0x0006:
  479. proximityDevice.tabletDeviceType = QTabletEvent::Puck;
  480. break;
  481. case 0x0804:
  482. proximityDevice.tabletDeviceType = QTabletEvent::RotationStylus;
  483. break;
  484. default:
  485. proximityDevice.tabletDeviceType = QTabletEvent::NoDevice;
  486. }
  487. }
  488. // The deviceID is "unique" while in the proximity, it's a key that we can use for
  489. // linking up TabletDeviceData to an event (especially if there are two devices in action).
  490. bool entering = proxRec.enterProximity;
  491. if (entering) {
  492. qt_mac_tablet_hash()->insert(proxRec.deviceID, proximityDevice);
  493. } else {
  494. qt_mac_tablet_hash()->remove(proxRec.deviceID);
  495. }
  496. QTabletEvent qtabletProximity(entering ? QEvent::TabletEnterProximity
  497. : QEvent::TabletLeaveProximity,
  498. QPoint(), QPoint(), QPointF(), proximityDevice.tabletDeviceType,
  499. proximityDevice.tabletPointerType, 0., 0, 0, 0., 0., 0, 0,
  500. proximityDevice.tabletUniqueID);
  501. qt_sendSpontaneousEvent(qApp, &qtabletProximity);
  502. }
  503. // Use this method to keep all the information in the TextSegment. As long as it is ordered
  504. // we are in OK shape, and we can influence that ourselves.
  505. struct KeyPair
  506. {
  507. QChar cocoaKey;
  508. Qt::Key qtKey;
  509. };
  510. bool operator==(const KeyPair &entry, QChar qchar)
  511. {
  512. return entry.cocoaKey == qchar;
  513. }
  514. bool operator<(const KeyPair &entry, QChar qchar)
  515. {
  516. return entry.cocoaKey < qchar;
  517. }
  518. bool operator<(QChar qchar, const KeyPair &entry)
  519. {
  520. return qchar < entry.cocoaKey;
  521. }
  522. bool operator<(const Qt::Key &key, const KeyPair &entry)
  523. {
  524. return key < entry.qtKey;
  525. }
  526. bool operator<(const KeyPair &entry, const Qt::Key &key)
  527. {
  528. return entry.qtKey < key;
  529. }
  530. static bool qtKey2CocoaKeySortLessThan(const KeyPair &entry1, const KeyPair &entry2)
  531. {
  532. return entry1.qtKey < entry2.qtKey;
  533. }
  534. static const int NumEntries = 59;
  535. static const KeyPair entries[NumEntries] = {
  536. { NSEnterCharacter, Qt::Key_Enter },
  537. { NSBackspaceCharacter, Qt::Key_Backspace },
  538. { NSTabCharacter, Qt::Key_Tab },
  539. { NSNewlineCharacter, Qt::Key_Return },
  540. { NSCarriageReturnCharacter, Qt::Key_Return },
  541. { NSBackTabCharacter, Qt::Key_Backtab },
  542. { kEscapeCharCode, Qt::Key_Escape },
  543. // Cocoa sends us delete when pressing backspace!
  544. // (NB when we reverse this list in qtKey2CocoaKey, there
  545. // will be two indices of Qt::Key_Backspace. But is seems to work
  546. // ok for menu shortcuts (which uses that function):
  547. { NSDeleteCharacter, Qt::Key_Backspace },
  548. { NSUpArrowFunctionKey, Qt::Key_Up },
  549. { NSDownArrowFunctionKey, Qt::Key_Down },
  550. { NSLeftArrowFunctionKey, Qt::Key_Left },
  551. { NSRightArrowFunctionKey, Qt::Key_Right },
  552. { NSF1FunctionKey, Qt::Key_F1 },
  553. { NSF2FunctionKey, Qt::Key_F2 },
  554. { NSF3FunctionKey, Qt::Key_F3 },
  555. { NSF4FunctionKey, Qt::Key_F4 },
  556. { NSF5FunctionKey, Qt::Key_F5 },
  557. { NSF6FunctionKey, Qt::Key_F6 },
  558. { NSF7FunctionKey, Qt::Key_F7 },
  559. { NSF8FunctionKey, Qt::Key_F8 },
  560. { NSF9FunctionKey, Qt::Key_F8 },
  561. { NSF10FunctionKey, Qt::Key_F10 },
  562. { NSF11FunctionKey, Qt::Key_F11 },
  563. { NSF12FunctionKey, Qt::Key_F12 },
  564. { NSF13FunctionKey, Qt::Key_F13 },
  565. { NSF14FunctionKey, Qt::Key_F14 },
  566. { NSF15FunctionKey, Qt::Key_F15 },
  567. { NSF16FunctionKey, Qt::Key_F16 },
  568. { NSF17FunctionKey, Qt::Key_F17 },
  569. { NSF18FunctionKey, Qt::Key_F18 },
  570. { NSF19FunctionKey, Qt::Key_F19 },
  571. { NSF20FunctionKey, Qt::Key_F20 },
  572. { NSF21FunctionKey, Qt::Key_F21 },
  573. { NSF22FunctionKey, Qt::Key_F22 },
  574. { NSF23FunctionKey, Qt::Key_F23 },
  575. { NSF24FunctionKey, Qt::Key_F24 },
  576. { NSF25FunctionKey, Qt::Key_F25 },
  577. { NSF26FunctionKey, Qt::Key_F26 },
  578. { NSF27FunctionKey, Qt::Key_F27 },
  579. { NSF28FunctionKey, Qt::Key_F28 },
  580. { NSF29FunctionKey, Qt::Key_F29 },
  581. { NSF30FunctionKey, Qt::Key_F30 },
  582. { NSF31FunctionKey, Qt::Key_F31 },
  583. { NSF32FunctionKey, Qt::Key_F32 },
  584. { NSF33FunctionKey, Qt::Key_F33 },
  585. { NSF34FunctionKey, Qt::Key_F34 },
  586. { NSF35FunctionKey, Qt::Key_F35 },
  587. { NSInsertFunctionKey, Qt::Key_Insert },
  588. { NSDeleteFunctionKey, Qt::Key_Delete },
  589. { NSHomeFunctionKey, Qt::Key_Home },
  590. { NSEndFunctionKey, Qt::Key_End },
  591. { NSPageUpFunctionKey, Qt::Key_PageUp },
  592. { NSPageDownFunctionKey, Qt::Key_PageDown },
  593. { NSPrintScreenFunctionKey, Qt::Key_Print },
  594. { NSScrollLockFunctionKey, Qt::Key_ScrollLock },
  595. { NSPauseFunctionKey, Qt::Key_Pause },
  596. { NSSysReqFunctionKey, Qt::Key_SysReq },
  597. { NSMenuFunctionKey, Qt::Key_Menu },
  598. { NSHelpFunctionKey, Qt::Key_Help },
  599. };
  600. static const KeyPair * const end = entries + NumEntries;
  601. QChar qtKey2CocoaKey(Qt::Key key)
  602. {
  603. // The first time this function is called, create a reverse
  604. // looup table sorted on Qt Key rather than Cocoa key:
  605. static QVector<KeyPair> rev_entries(NumEntries);
  606. static bool mustInit = true;
  607. if (mustInit){
  608. mustInit = false;
  609. for (int i=0; i<NumEntries; ++i)
  610. rev_entries[i] = entries[i];
  611. qSort(rev_entries.begin(), rev_entries.end(), qtKey2CocoaKeySortLessThan);
  612. }
  613. const QVector<KeyPair>::iterator i
  614. = qBinaryFind(rev_entries.begin(), rev_entries.end(), key);
  615. if (i == rev_entries.end())
  616. return QChar();
  617. return i->cocoaKey;
  618. }
  619. #ifdef QT_MAC_USE_COCOA
  620. static Qt::Key cocoaKey2QtKey(QChar keyCode)
  621. {
  622. const KeyPair *i = qBinaryFind(entries, end, keyCode);
  623. if (i == end)
  624. return Qt::Key(keyCode.unicode());
  625. return i->qtKey;
  626. }
  627. Qt::KeyboardModifiers qt_cocoaModifiers2QtModifiers(ulong modifierFlags)
  628. {
  629. Qt::KeyboardModifiers qtMods =Qt::NoModifier;
  630. if (modifierFlags & NSShiftKeyMask)
  631. qtMods |= Qt::ShiftModifier;
  632. if (modifierFlags & NSControlKeyMask)
  633. qtMods |= Qt::MetaModifier;
  634. if (modifierFlags & NSAlternateKeyMask)
  635. qtMods |= Qt::AltModifier;
  636. if (modifierFlags & NSCommandKeyMask)
  637. qtMods |= Qt::ControlModifier;
  638. if (modifierFlags & NSNumericPadKeyMask)
  639. qtMods |= Qt::KeypadModifier;
  640. return qtMods;
  641. }
  642. NSString *qt_mac_removePrivateUnicode(NSString* string)
  643. {
  644. int len = [string length];
  645. if (len) {
  646. QVarLengthArray <unichar, 10> characters(len);
  647. bool changed = false;
  648. for (int i = 0; i<len; i++) {
  649. characters[i] = [string characterAtIndex:i];
  650. // check if they belong to key codes in private unicode range
  651. // currently we need to handle only the NSDeleteFunctionKey
  652. if (characters[i] == NSDeleteFunctionKey) {
  653. characters[i] = NSDeleteCharacter;
  654. changed = true;
  655. }
  656. }
  657. if (changed)
  658. return [NSString stringWithCharacters:characters.data() length:len];
  659. }
  660. return string;
  661. }
  662. Qt::KeyboardModifiers qt_cocoaDragOperation2QtModifiers(uint dragOperations)
  663. {
  664. Qt::KeyboardModifiers qtMods =Qt::NoModifier;
  665. if (dragOperations & NSDragOperationLink)
  666. qtMods |= Qt::MetaModifier;
  667. if (dragOperations & NSDragOperationGeneric)
  668. qtMods |= Qt::ControlModifier;
  669. if (dragOperations & NSDragOperationCopy)
  670. qtMods |= Qt::AltModifier;
  671. return qtMods;
  672. }
  673. static inline QEvent::Type cocoaEvent2QtEvent(NSUInteger eventType)
  674. {
  675. // Handle the trivial cases that can be determined from the type.
  676. switch (eventType) {
  677. case NSKeyDown:
  678. return QEvent::KeyPress;
  679. case NSKeyUp:
  680. return QEvent::KeyRelease;
  681. case NSLeftMouseDown:
  682. case NSRightMouseDown:
  683. case NSOtherMouseDown:
  684. return QEvent::MouseButtonPress;
  685. case NSLeftMouseUp:
  686. case NSRightMouseUp:
  687. case NSOtherMouseUp:
  688. return QEvent::MouseButtonRelease;
  689. case NSMouseMoved:
  690. case NSLeftMouseDragged:
  691. case NSRightMouseDragged:
  692. case NSOtherMouseDragged:
  693. return QEvent::MouseMove;
  694. case NSScrollWheel:
  695. return QEvent::Wheel;
  696. }
  697. return QEvent::None;
  698. }
  699. static bool mustUseCocoaKeyEvent()
  700. {
  701. QCFType<TISInputSourceRef> source = TISCopyCurrentKeyboardInputSource();
  702. return TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData) == 0;
  703. }
  704. bool qt_dispatchKeyEventWithCocoa(void * /*NSEvent * */ keyEvent, QWidget *widgetToGetEvent)
  705. {
  706. NSEvent *event = static_cast<NSEvent *>(keyEvent);
  707. NSString *keyChars = [event charactersIgnoringModifiers];
  708. int keyLength = [keyChars length];
  709. if (keyLength == 0)
  710. return false; // Dead Key, nothing to do!
  711. bool ignoreText = false;
  712. Qt::Key qtKey = Qt::Key_unknown;
  713. if (keyLength == 1) {
  714. QChar ch([keyChars characterAtIndex:0]);
  715. if (ch.isLower())
  716. ch = ch.toUpper();
  717. qtKey = cocoaKey2QtKey(ch);
  718. // Do not set the text for Function-Key Unicodes characters (0xF700–0xF8FF).
  719. ignoreText = (ch.unicode() >= 0xF700 && ch.unicode() <= 0xF8FF);
  720. }
  721. Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([event modifierFlags]);
  722. QString text;
  723. // To quote from the Carbon port: This is actually wrong--but it is the best that
  724. // can be done for now because of the Control/Meta mapping issues
  725. // (we always get text on the Mac)
  726. if (!ignoreText && !(keyMods & (Qt::ControlModifier | Qt::MetaModifier)))
  727. text = QCFString::toQString(reinterpret_cast<CFStringRef>(keyChars));
  728. UInt32 macScanCode = 1;
  729. QKeyEventEx ke(cocoaEvent2QtEvent([event type]), qtKey, keyMods, text, [event isARepeat], qMax(1, keyLength),
  730. macScanCode, [event keyCode], [event modifierFlags]);
  731. return qt_sendSpontaneousEvent(widgetToGetEvent, &ke) && ke.isAccepted();
  732. }
  733. #endif
  734. Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum)
  735. {
  736. if (buttonNum == 0)
  737. return Qt::LeftButton;
  738. if (buttonNum == 1)
  739. return Qt::RightButton;
  740. if (buttonNum == 2)
  741. return Qt::MidButton;
  742. if (buttonNum == 3)
  743. return Qt::XButton1;
  744. if (buttonNum == 4)
  745. return Qt::XButton2;
  746. return Qt::NoButton;
  747. }
  748. bool qt_dispatchKeyEvent(void * /*NSEvent * */ keyEvent, QWidget *widgetToGetEvent)
  749. {
  750. #ifndef QT_MAC_USE_COCOA
  751. Q_UNUSED(keyEvent);
  752. Q_UNUSED(widgetToGetEvent);
  753. return false;
  754. #else
  755. NSEvent *event = static_cast<NSEvent *>(keyEvent);
  756. EventRef key_event = static_cast<EventRef>(const_cast<void *>([event eventRef]));
  757. Q_ASSERT(key_event);
  758. unsigned int info = 0;
  759. if ([event type] == NSKeyDown) {
  760. NSString *characters = [event characters];
  761. if ([characters length]) {
  762. unichar value = [characters characterAtIndex:0];
  763. qt_keymapper_private()->updateKeyMap(0, key_event, (void *)&value);
  764. info = value;
  765. }
  766. }
  767. if (qt_mac_sendMacEventToWidget(widgetToGetEvent, key_event))
  768. return true;
  769. if (mustUseCocoaKeyEvent())
  770. return qt_dispatchKeyEventWithCocoa(keyEvent, widgetToGetEvent);
  771. bool consumed = qt_keymapper_private()->translateKeyEvent(widgetToGetEvent, 0, key_event, &info, true);
  772. return consumed && (info != 0);
  773. #endif
  774. }
  775. void qt_dispatchModifiersChanged(void * /*NSEvent * */flagsChangedEvent, QWidget *widgetToGetEvent)
  776. {
  777. #ifndef QT_MAC_USE_COCOA
  778. Q_UNUSED(flagsChangedEvent);
  779. Q_UNUSED(widgetToGetEvent);
  780. #else
  781. UInt32 modifiers = 0;
  782. // Sync modifiers with Qt
  783. NSEvent *event = static_cast<NSEvent *>(flagsChangedEvent);
  784. EventRef key_event = static_cast<EventRef>(const_cast<void *>([event eventRef]));
  785. Q_ASSERT(key_event);
  786. GetEventParameter(key_event, kEventParamKeyModifiers, typeUInt32, 0,
  787. sizeof(modifiers), 0, &modifiers);
  788. extern void qt_mac_send_modifiers_changed(quint32 modifiers, QObject *object);
  789. qt_mac_send_modifiers_changed(modifiers, widgetToGetEvent);
  790. #endif
  791. }
  792. QPointF flipPoint(const NSPoint &p)
  793. {
  794. return QPointF(p.x, flipYCoordinate(p.y));
  795. }
  796. NSPoint flipPoint(const QPoint &p)
  797. {
  798. return NSMakePoint(p.x(), flipYCoordinate(p.y()));
  799. }
  800. NSPoint flipPoint(const QPointF &p)
  801. {
  802. return NSMakePoint(p.x(), flipYCoordinate(p.y()));
  803. }
  804. #if QT_MAC_USE_COCOA && __OBJC__
  805. void qt_mac_handleNonClientAreaMouseEvent(NSWindow *window, NSEvent *event)
  806. {
  807. QWidget *widgetToGetEvent = [window QT_MANGLE_NAMESPACE(qt_qwidget)];
  808. if (widgetToGetEvent == 0)
  809. return;
  810. NSEventType evtType = [event type];
  811. QPoint qlocalPoint;
  812. QPoint qglobalPoint;
  813. bool processThisEvent = false;
  814. bool fakeNCEvents = false;
  815. bool fakeMouseEvents = false;
  816. // Check if this is a mouse event.
  817. if (evtType == NSLeftMouseDown || evtType == NSLeftMouseUp
  818. || evtType == NSRightMouseDown || evtType == NSRightMouseUp
  819. || evtType == NSOtherMouseDown || evtType == NSOtherMouseUp
  820. || evtType == NSMouseMoved || evtType == NSLeftMouseDragged
  821. || evtType == NSRightMouseDragged || evtType == NSOtherMouseDragged) {
  822. // Check if we want to pass this message to another window
  823. if (mac_mouse_grabber && mac_mouse_grabber != widgetToGetEvent) {
  824. NSWindow *grabWindow = static_cast<NSWindow *>(qt_mac_window_for(mac_mouse_grabber));
  825. if (window != grabWindow) {
  826. window = grabWindow;
  827. widgetToGetEvent = mac_mouse_grabber;
  828. fakeNCEvents = true;
  829. }
  830. }
  831. // Dont generate normal NC mouse events for Left Button dragged
  832. if(evtType != NSLeftMouseDragged || fakeNCEvents) {
  833. NSPoint windowPoint = [event locationInWindow];
  834. NSPoint globalPoint = [[event window] convertBaseToScreen:windowPoint];
  835. NSRect frameRect = [window frame];
  836. if (fakeNCEvents || NSMouseInRect(globalPoint, frameRect, NO)) {
  837. NSRect contentRect = [window contentRectForFrameRect:frameRect];
  838. qglobalPoint = QPoint(flipPoint(globalPoint).toPoint());
  839. QWidget *w = widgetToGetEvent->childAt(widgetToGetEvent->mapFromGlobal(qglobalPoint));
  840. // check that the mouse pointer is on the non-client area and
  841. // there are not widgets in it.
  842. if (fakeNCEvents || (!NSMouseInRect(globalPoint, contentRect, NO) && !w)) {
  843. qglobalPoint = QPoint(flipPoint(globalPoint).toPoint());
  844. qlocalPoint = widgetToGetEvent->mapFromGlobal(qglobalPoint);
  845. processThisEvent = true;
  846. }
  847. }
  848. }
  849. }
  850. // This is not an NC area mouse message.
  851. if (!processThisEvent)
  852. return;
  853. // If the window is frame less, generate fake mouse events instead. (floating QToolBar)
  854. // or if someone already got an explicit or implicit grab
  855. if (mac_mouse_grabber || qt_button_down ||
  856. (fakeNCEvents && (widgetToGetEvent->window()->windowFlags() & Qt::FramelessWindowHint)))
  857. fakeMouseEvents = true;
  858. Qt::MouseButton button;
  859. QEvent::Type eventType;
  860. // Convert to Qt::Event type
  861. switch (evtType) {
  862. case NSLeftMouseDown:
  863. button = Qt::LeftButton;
  864. eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonPress
  865. : QEvent::MouseButtonPress;
  866. break;
  867. case NSLeftMouseUp:
  868. button = Qt::LeftButton;
  869. eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonRelease
  870. : QEvent::MouseButtonRelease;
  871. break;
  872. case NSRightMouseDown:
  873. button = Qt::RightButton;
  874. eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonPress
  875. : QEvent::MouseButtonPress;
  876. break;
  877. case NSRightMouseUp:
  878. button = Qt::RightButton;
  879. eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonRelease
  880. : QEvent::MouseButtonRelease;
  881. break;
  882. case NSOtherMouseDown:
  883. button = cocoaButton2QtButton([event buttonNumber]);
  884. eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonPress
  885. : QEvent::MouseButtonPress;
  886. break;
  887. case NSOtherMouseUp:
  888. button = cocoaButton2QtButton([event buttonNumber]);
  889. eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonRelease
  890. : QEvent::MouseButtonRelease;
  891. break;
  892. case NSMouseMoved:
  893. button = Qt::NoButton;
  894. eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
  895. : QEvent::MouseMove;
  896. break;
  897. case NSLeftMouseDragged:
  898. button = Qt::LeftButton;
  899. eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
  900. : QEvent::MouseMove;
  901. break;
  902. case NSRightMouseDragged:
  903. button = Qt::RightButton;
  904. eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
  905. : QEvent::MouseMove;
  906. break;
  907. case NSOtherMouseDragged:
  908. button = cocoaButton2QtButton([event buttonNumber]);
  909. eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
  910. : QEvent::MouseMove;
  911. break;
  912. default:
  913. qWarning("not handled! Non client area mouse message");
  914. return;
  915. }
  916. Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([event modifierFlags]);
  917. if (eventType == QEvent::NonClientAreaMouseButtonPress || eventType == QEvent::MouseButtonPress) {
  918. NSInteger clickCount = [event clickCount];
  919. if (clickCount % 2 == 0)
  920. eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonDblClick
  921. : QEvent::MouseButtonDblClick;
  922. if (button == Qt::LeftButton && (keyMods & Qt::MetaModifier)) {
  923. button = Qt::RightButton;
  924. qt_leftButtonIsRightButton = true;
  925. }
  926. } else if (eventType == QEvent::NonClientAreaMouseButtonRelease || eventType == QEvent::MouseButtonRelease) {
  927. if (button == Qt::LeftButton && qt_leftButtonIsRightButton) {
  928. button = Qt::RightButton;
  929. qt_leftButtonIsRightButton = false;
  930. }
  931. }
  932. Qt::MouseButtons buttons = 0;
  933. {
  934. UInt32 mac_buttons;
  935. if (GetEventParameter((EventRef)[event eventRef], kEventParamMouseChord, typeUInt32, 0,
  936. sizeof(mac_buttons), 0, &mac_buttons) == noErr)
  937. buttons = qt_mac_get_buttons(mac_buttons);
  938. }
  939. QMouseEvent qme(eventType, qlocalPoint, qglobalPoint, button, buttons, keyMods);
  940. qt_sendSpontaneousEvent(widgetToGetEvent, &qme);
  941. // We don't need to set the implicit grab widget here because we won't
  942. // reach this point if then event type is Press over a Qt widget.
  943. // However we might need to unset it if the event is Release.
  944. if (eventType == QEvent::MouseButtonRelease)
  945. qt_button_down = 0;
  946. }
  947. QWidget *qt_mac_getTargetForKeyEvent(QWidget *widgetThatReceivedEvent)
  948. {
  949. if (QWidget *popup = QApplication::activePopupWidget()) {
  950. QWidget *focusInPopup = popup->focusWidget();
  951. return focusInPopup ? focusInPopup : popup;
  952. }
  953. QWidget *widgetToGetKey = qApp->focusWidget();
  954. if (!widgetToGetKey)
  955. widgetToGetKey = widgetThatReceivedEvent;
  956. return widgetToGetKey;
  957. }
  958. // This function will find the widget that should receive the
  959. // mouse event. Because of explicit/implicit mouse grabs, popups,
  960. // etc, this might not end up being the same as the widget under
  961. // the mouse (which is more interresting when handling enter/leave
  962. // events
  963. QWidget *qt_mac_getTargetForMouseEvent(
  964. // You can call this function without providing an event.
  965. NSEvent *event,
  966. QEvent::Type eventType,
  967. QPoint &returnLocalPoint,
  968. QPoint &returnGlobalPoint,
  969. QWidget *nativeWidget,
  970. QWidget **returnWidgetUnderMouse)
  971. {
  972. Q_UNUSED(event);
  973. NSPoint nsglobalpoint = event ? [[event window] convertBaseToScreen:[event locationInWindow]] : [NSEvent mouseLocation];
  974. returnGlobalPoint = flipPoint(nsglobalpoint).toPoint();
  975. QWidget *mouseGrabber = QWidget::mouseGrabber();
  976. bool buttonDownNotBlockedByModal = qt_button_down && !QApplicationPrivate::isBlockedByModal(qt_button_down);
  977. QWidget *popup = QApplication::activePopupWidget();
  978. // Resolve the widget under the mouse:
  979. QWidget *widgetUnderMouse = 0;
  980. if (popup || qt_button_down || !nativeWidget || !nativeWidget->isVisible()) {
  981. // Using QApplication::widgetAt for finding the widget under the mouse
  982. // is most safe, since it ignores cocoas own mouse down redirections (which
  983. // we need to be prepared for when using nativeWidget as starting point).
  984. // (the only exception is for QMacNativeWidget, where QApplication::widgetAt fails).
  985. // But it is also slower (I guess), so we try to avoid it and use nativeWidget if we can:
  986. widgetUnderMouse = QApplication::widgetAt(returnGlobalPoint);
  987. }
  988. if (!widgetUnderMouse && nativeWidget) {
  989. // Entering here should be the common case. We
  990. // also handle the QMacNativeWidget fallback case.
  991. QPoint p = nativeWidget->mapFromGlobal(returnGlobalPoint);
  992. widgetUnderMouse = nativeWidget->childAt(p);
  993. if (!widgetUnderMouse && nativeWidget->rect().contains(p))
  994. widgetUnderMouse = nativeWidget;
  995. }
  996. if (widgetUnderMouse) {
  997. // Check if widgetUnderMouse is blocked by a modal
  998. // window, or the mouse if over the frame strut:
  999. if (widgetUnderMouse == qt_button_down) {
  1000. // Small optimization to avoid an extra call to isBlockedByModal:
  1001. if (buttonDownNotBlockedByModal == false)
  1002. widgetUnderMouse = 0;
  1003. } else if (QApplicationPrivate::isBlockedByModal(widgetUnderMouse)) {
  1004. widgetUnderMouse = 0;
  1005. }
  1006. if (widgetUnderMouse && widgetUnderMouse->isWindow()) {
  1007. // Exclude the titlebar (and frame strut) when finding widget under mouse:
  1008. QPoint p = widgetUnderMouse->mapFromGlobal(returnGlobalPoint);
  1009. if (!widgetUnderMouse->rect().contains(p))
  1010. widgetUnderMouse = 0;
  1011. }
  1012. }
  1013. if (returnWidgetUnderMouse)
  1014. *returnWidgetUnderMouse = widgetUnderMouse;
  1015. // Resolve the target for the mouse event. Default will be
  1016. // widgetUnderMouse, except if there is a grab (popup/mouse/button-down):
  1017. if (popup && !mouseGrabber) {
  1018. // We special case handling of popups, since they have an implicitt mouse grab.
  1019. QWidget *candidate = buttonDownNotBlockedByModal ? qt_button_down : widgetUnderMouse;
  1020. if (!popup->isAncestorOf(candidate)) {
  1021. // INVARIANT: we have a popup, but the candidate is not
  1022. // in it. But the popup will grab the mouse anyway,
  1023. // except if the user scrolls:
  1024. if (eventType == QEvent::Wheel)
  1025. return 0;
  1026. returnLocalPoint = popup->mapFromGlobal(returnGlobalPoint);
  1027. return popup;
  1028. } else if (popup == candidate) {
  1029. // INVARIANT: The candidate is the popup itself, and not a child:
  1030. returnLocalPoint = popup->mapFromGlobal(returnGlobalPoint);
  1031. return popup;
  1032. } else {
  1033. // INVARIANT: The candidate is a child inside the popup:
  1034. returnLocalPoint = candidate->mapFromGlobal(returnGlobalPoint);
  1035. return candidate;
  1036. }
  1037. }
  1038. QWidget *target = mouseGrabber;
  1039. if (!target && buttonDownNotBlockedByModal)
  1040. target = qt_button_down;
  1041. if (!target)
  1042. target = widgetUnderMouse;
  1043. if (!target)
  1044. return 0;
  1045. returnLocalPoint = target->mapFromGlobal(returnGlobalPoint);
  1046. return target;
  1047. }
  1048. QPointer<QWidget> qt_last_native_mouse_receiver = 0;
  1049. static inline void qt_mac_checkEnterLeaveForNativeWidgets(QWidget *maybeEnterWidget)
  1050. {
  1051. // Dispatch enter/leave for the cases where QApplicationPrivate::sendMouseEvent do
  1052. // not. This will in general be the cases when alien widgets are not involved:
  1053. // 1. from a native widget to another native widget or
  1054. // 2. from a native widget to no widget
  1055. // 3. from no widget to a native or alien widget
  1056. if (qt_button_down || QWidget::mouseGrabber())
  1057. return;
  1058. if ((maybeEnterWidget == qt_last_native_mouse_receiver) && qt_last_native_mouse_receiver)
  1059. return;
  1060. if (maybeEnterWidget) {
  1061. if (!qt_last_native_mouse_receiver) {
  1062. // case 3
  1063. QApplicationPrivate::dispatchEnterLeave(maybeEnterWidget, 0);
  1064. qt_last_native_mouse_receiver = maybeEnterWidget->internalWinId() ? maybeEnterWidget : maybeEnterWidget->nativeParentWidget();
  1065. } else if (maybeEnterWidget->internalWinId()) {
  1066. // case 1
  1067. QApplicationPrivate::dispatchEnterLeave(maybeEnterWidget, qt_last_native_mouse_receiver);
  1068. qt_last_native_mouse_receiver = maybeEnterWidget->internalWinId() ? maybeEnterWidget : maybeEnterWidget->nativeParentWidget();
  1069. } // else at lest one of the widgets are alien, so enter/leave will be handled in QApplicationPrivate
  1070. } else {
  1071. if (qt_last_native_mouse_receiver) {
  1072. // case 2
  1073. QApplicationPrivate::dispatchEnterLeave(0, qt_last_native_mouse_receiver);
  1074. qt_last_mouse_receiver = 0;
  1075. qt_last_native_mouse_receiver = 0;
  1076. }
  1077. }
  1078. }
  1079. bool qt_mac_handleMouseEvent(NSEvent *event, QEvent::Type eventType, Qt::MouseButton button, QWidget *nativeWidget)
  1080. {
  1081. // Give the Input Manager a chance to process the mouse events.
  1082. NSInputManager *currentIManager = [NSInputManager currentInputManager];
  1083. if (currentIManager && [currentIManager wantsToHandleMouseEvents]) {
  1084. [currentIManager handleMouseEvent:event];
  1085. }
  1086. // Find the widget that should receive the event, and the widget under the mouse. Those
  1087. // can differ if an implicit or explicit mouse grab is active:
  1088. QWidget *widgetUnderMouse = 0;
  1089. QPoint localPoint, globalPoint;
  1090. QWidget *widgetToGetMouse = qt_mac_getTargetForMouseEvent(event, eventType, localPoint, globalPoint, nativeWidget, &widgetUnderMouse);
  1091. if (!widgetToGetMouse)
  1092. return false;
  1093. // From here on, we let nativeWidget actually be the native widget under widgetUnderMouse. The reason
  1094. // for this, is that qt_mac_getTargetForMouseEvent will set cocoa's mouse event redirection aside when
  1095. // determining which widget is under the mouse (in other words, it will usually ignore nativeWidget).
  1096. // nativeWidget will be used in QApplicationPrivate::sendMouseEvent to correctly dispatch enter/leave events.
  1097. if (widgetUnderMouse)
  1098. nativeWidget = widgetUnderMouse->internalWinId() ? widgetUnderMouse : widgetUnderMouse->nativeParentWidget();
  1099. if (!nativeWidget)
  1100. return false;
  1101. NSView *view = qt_mac_effectiveview_for(nativeWidget);
  1102. // Handle tablet events (if any) first.
  1103. if (qt_mac_handleTabletEvent(view, event)) {
  1104. // Tablet event was handled. In Qt we aren't supposed to send the mouse event.
  1105. return true;
  1106. }
  1107. EventRef carbonEvent = static_cast<EventRef>(const_cast<void *>([event eventRef]));
  1108. if (qt_mac_sendMacEventToWidget(widgetToGetMouse, carbonEvent))
  1109. return true;
  1110. // Keep previousButton to make sure we don't send double click
  1111. // events when the user double clicks using two different buttons:
  1112. static Qt::MouseButton previousButton = Qt::NoButton;
  1113. Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([event modifierFlags]);
  1114. NSInteger clickCount = [event clickCount];
  1115. Qt::MouseButtons buttons = 0;
  1116. {
  1117. UInt32 mac_buttons;
  1118. if (GetEventParameter(carbonEvent, kEventParamMouseChord, typeUInt32, 0,
  1119. sizeof(mac_buttons), 0, &mac_buttons) == noErr)
  1120. buttons = qt_mac_get_buttons(mac_buttons);
  1121. }
  1122. // Send enter/leave events for the cases when QApplicationPrivate::sendMouseEvent do not:
  1123. qt_mac_checkEnterLeaveForNativeWidgets(widgetUnderMouse);
  1124. switch (eventType) {
  1125. default:
  1126. qWarning("not handled! %d", eventType);
  1127. break;
  1128. case QEvent::MouseMove:
  1129. if (button == Qt::LeftButton && qt_leftButtonIsRightButton)
  1130. button = Qt::RightButton;
  1131. break;
  1132. case QEvent::MouseButtonPress:
  1133. qt_button_down = widgetUnderMouse;
  1134. if (clickCount % 2 == 0 && (previousButton == Qt::NoButton || previousButton == button))
  1135. eventType = QEvent::MouseButtonDblClick;
  1136. if (button == Qt::LeftButton && (keyMods & Qt::MetaModifier)) {
  1137. button = Qt::RightButton;
  1138. qt_leftButtonIsRightButton = true;
  1139. }
  1140. break;
  1141. case QEvent::MouseButtonRelease:
  1142. if (button == Qt::LeftButton && qt_leftButtonIsRightButton) {
  1143. button = Qt::RightButton;
  1144. qt_leftButtonIsRightButton = false;
  1145. }
  1146. qt_button_down = 0;
  1147. break;
  1148. }
  1149. qt_mac_updateCursorWithWidgetUnderMouse(widgetUnderMouse);
  1150. DnDParams *dndParams = currentDnDParameters();
  1151. dndParams->view = view;
  1152. dndParams->theEvent = event;
  1153. dndParams->globalPoint = globalPoint;
  1154. // Send the mouse event:
  1155. QMouseEvent qme(eventType, localPoint, globalPoint, button, buttons, keyMods);
  1156. QApplicationPrivate::sendMouseEvent(
  1157. widgetToGetMouse, &qme, widgetUnderMouse, nativeWidget,
  1158. &qt_button_down, qt_last_mouse_receiver, true);
  1159. if (eventType == QEvent::MouseButtonPress && button == Qt::RightButton) {
  1160. QContextMenuEvent qcme(QContextMenuEvent::Mouse, localPoint, globalPoint, keyMods);
  1161. qt_sendSpontaneousEvent(widgetToGetMouse, &qcme);
  1162. }
  1163. if (eventType == QEvent::MouseButtonRelease) {
  1164. // A mouse button was released, which means that the implicit grab was
  1165. // released. We therefore need to re-check if should send (delayed) enter leave events:
  1166. // qt_button_down has now become NULL since the call at the top of the function. Also, since
  1167. // the relase might have closed a window, we dont give the nativeWidget hint
  1168. qt_mac_getTargetForMouseEvent(0, QEvent::None, localPoint, globalPoint, nativeWidget, &widgetUnderMouse);
  1169. qt_mac_checkEnterLeaveForNativeWidgets(widgetUnderMouse);
  1170. }
  1171. previousButton = button;
  1172. return true;
  1173. }
  1174. #endif
  1175. bool qt_mac_handleTabletEvent(void * /*QCocoaView * */view, void * /*NSEvent * */tabletEvent)
  1176. {
  1177. #ifndef QT_MAC_USE_COCOA
  1178. Q_UNUSED(view);
  1179. Q_UNUSED(tabletEvent);
  1180. return false;
  1181. #else
  1182. QT_MANGLE_NAMESPACE(QCocoaView) *theView = static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(view);
  1183. NSView *theNSView = static_cast<NSView *>(view);
  1184. NSEvent *theTabletEvent = static_cast<NSEvent *>(tabletEvent);
  1185. NSEventType eventType = [theTabletEvent type];
  1186. if (eventType != NSTabletPoint && [theTabletEvent subtype] != NSTabletPointEventSubtype)
  1187. return false; // Not a tablet event.
  1188. NSPoint windowPoint = [theTabletEvent locationInWindow];
  1189. NSPoint globalPoint = [[theTabletEvent window] convertBaseToScreen:windowPoint];
  1190. QWidget *qwidget = [theView qt_qwidget];
  1191. QWidget *widgetToGetMouse = qwidget;
  1192. QWidget *popup = qAppInstance()->activePopupWidget();
  1193. if (popup && popup != qwidget->window())
  1194. widgetToGetMouse = popup;
  1195. if (qt_mac_sendMacEventToWidget(widgetToGetMouse,
  1196. static_cast<EventRef>(const_cast<void *>([theTabletEvent eventRef]))))
  1197. return true;
  1198. if (widgetToGetMouse != qwidg

Large files are truncated, but you can click here to view the full file