Qt 4.8
qt_cocoa_helpers_mac.mm
Go to the documentation of this file.
1 /****************************************************************************
2 **
3 ** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
4 ** Contact: http://www.qt-project.org/legal
5 **
6 ** This file is part of the QtGui module of the Qt Toolkit.
7 **
8 ** $QT_BEGIN_LICENSE:LGPL$
9 ** Commercial License Usage
10 ** Licensees holding valid commercial Qt licenses may use this file in
11 ** accordance with the commercial license agreement provided with the
12 ** Software or, alternatively, in accordance with the terms contained in
13 ** a written agreement between you and Digia. For licensing terms and
14 ** conditions see http://qt.digia.com/licensing. For further information
15 ** use the contact form at http://qt.digia.com/contact-us.
16 **
17 ** GNU Lesser General Public License Usage
18 ** Alternatively, this file may be used under the terms of the GNU Lesser
19 ** General Public License version 2.1 as published by the Free Software
20 ** Foundation and appearing in the file LICENSE.LGPL included in the
21 ** packaging of this file. Please review the following information to
22 ** ensure the GNU Lesser General Public License version 2.1 requirements
23 ** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24 **
25 ** In addition, as a special exception, Digia gives you certain additional
26 ** rights. These rights are described in the Digia Qt LGPL Exception
27 ** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
28 **
29 ** GNU General Public License Usage
30 ** Alternatively, this file may be used under the terms of the GNU
31 ** General Public License version 3.0 as published by the Free Software
32 ** Foundation and appearing in the file LICENSE.GPL included in the
33 ** packaging of this file. Please review the following information to
34 ** ensure the GNU General Public License version 3.0 requirements will be
35 ** met: http://www.gnu.org/copyleft/gpl.html.
36 **
37 **
38 ** $QT_END_LICENSE$
39 **
40 ****************************************************************************/
41 
42 /****************************************************************************
43 **
44 ** Copyright (c) 2007-2008, Apple, Inc.
45 **
46 ** All rights reserved.
47 **
48 ** Redistribution and use in source and binary forms, with or without
49 ** modification, are permitted provided that the following conditions are met:
50 **
51 ** * Redistributions of source code must retain the above copyright notice,
52 ** this list of conditions and the following disclaimer.
53 **
54 ** * Redistributions in binary form must reproduce the above copyright notice,
55 ** this list of conditions and the following disclaimer in the documentation
56 ** and/or other materials provided with the distribution.
57 **
58 ** * Neither the name of Apple, Inc. nor the names of its contributors
59 ** may be used to endorse or promote products derived from this software
60 ** without specific prior written permission.
61 **
62 ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
63 ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
64 ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
65 ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
66 ** CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
67 ** EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
68 ** PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
69 ** PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
70 ** LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
71 ** NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
72 ** SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
73 **
74 ****************************************************************************/
75 
76 #include <private/qcore_mac_p.h>
77 #include <qaction.h>
78 #include <qwidget.h>
79 #include <qdesktopwidget.h>
80 #include <qevent.h>
81 #include <qpixmapcache.h>
82 #include <qvarlengtharray.h>
83 #include <private/qevent_p.h>
84 #include <private/qt_cocoa_helpers_mac_p.h>
85 #include <private/qt_mac_p.h>
86 #include <private/qapplication_p.h>
87 #include <private/qcocoaapplication_mac_p.h>
88 #include <private/qcocoawindow_mac_p.h>
89 #include <private/qcocoaview_mac_p.h>
90 #include <private/qkeymapper_p.h>
91 #include <private/qwidget_p.h>
92 #include <private/qcocoawindow_mac_p.h>
93 
95 
96 #ifdef QT_MAC_USE_COCOA
97 // Cmd + left mousebutton should produce a right button
98 // press (mainly for mac users with one-button mice):
99 static bool qt_leftButtonIsRightButton = false;
100 #endif
101 
102 Q_GLOBAL_STATIC(QMacWindowFader, macwindowFader);
103 
105  : m_duration(0.250)
106 {
107 }
108 
110 {
111  return macwindowFader();
112 }
113 
115 {
116  m_windowsToFade.append(window);
117 }
118 
120 {
121  const QWidgetList myWidgetsToFade = m_windowsToFade;
122  const int widgetCount = myWidgetsToFade.count();
123 #if QT_MAC_USE_COCOA
125  [NSAnimationContext beginGrouping];
126  [[NSAnimationContext currentContext] setDuration:NSTimeInterval(m_duration)];
127 #endif
128 
129  for (int i = 0; i < widgetCount; ++i) {
132 #if QT_MAC_USE_COCOA
133  [[window animator] setAlphaValue:0.0];
134  QTimer::singleShot(qRound(m_duration * 1000), widget, SLOT(hide()));
135 #else
136  TransitionWindowOptions options = {0, m_duration, 0, 0};
137  TransitionWindowWithOptions(window, kWindowFadeTransitionEffect, kWindowHideTransitionAction,
138  0, 1, &options);
139 #endif
140  }
141 #if QT_MAC_USE_COCOA
142  [NSAnimationContext endGrouping];
143 #endif
144  m_duration = 0.250;
146 }
147 
148 extern bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event); // qapplication.cpp;
149 extern QWidget * mac_mouse_grabber;
150 extern QWidget *qt_button_down; //qapplication_mac.cpp
153 extern void qt_mac_updateCursorWithWidgetUnderMouse(QWidget *widgetUnderMouse); // qcursor_mac.mm
154 
155 void macWindowFade(void * /*OSWindowRef*/ window, float durationSeconds)
156 {
157 #ifdef QT_MAC_USE_COCOA
159 #endif
160  OSWindowRef wnd = static_cast<OSWindowRef>(window);
161  if (wnd) {
162  QWidget *widget;
163 #if QT_MAC_USE_COCOA
164  widget = [wnd QT_MANGLE_NAMESPACE(qt_qwidget)];
165 #else
166  const UInt32 kWidgetCreatorQt = kEventClassQt;
167  enum {
168  kWidgetPropertyQWidget = 'QWId' //QWidget *
169  };
170  if (GetWindowProperty(static_cast<WindowRef>(window), kWidgetCreatorQt, kWidgetPropertyQWidget, sizeof(widget), 0, &widget) != noErr)
171  widget = 0;
172 #endif
173  if (widget) {
177  }
178  }
179 }
181 {
182  NSDragOperation mac_code;
184  bool Qt2Mac;
185 };
186 
187 #if defined(QT_MAC_USE_COCOA) && defined(__OBJC__)
188 
189 static dndenum_mapper dnd_enums[] = {
190  { NSDragOperationLink, Qt::LinkAction, true },
191  { NSDragOperationMove, Qt::MoveAction, true },
192  { NSDragOperationCopy, Qt::CopyAction, true },
193  { NSDragOperationGeneric, Qt::CopyAction, false },
194  { NSDragOperationEvery, Qt::ActionMask, false },
195  { NSDragOperationNone, Qt::IgnoreAction, false }
196 };
197 
198 NSDragOperation qt_mac_mapDropAction(Qt::DropAction action)
199 {
200  for (int i=0; dnd_enums[i].qt_code; i++) {
201  if (dnd_enums[i].Qt2Mac && (action & dnd_enums[i].qt_code)) {
202  return dnd_enums[i].mac_code;
203  }
204  }
205  return NSDragOperationNone;
206 }
207 
208 NSDragOperation qt_mac_mapDropActions(Qt::DropActions actions)
209 {
210  NSDragOperation nsActions = NSDragOperationNone;
211  for (int i=0; dnd_enums[i].qt_code; i++) {
212  if (dnd_enums[i].Qt2Mac && (actions & dnd_enums[i].qt_code))
213  nsActions |= dnd_enums[i].mac_code;
214  }
215  return nsActions;
216 }
217 
218 Qt::DropAction qt_mac_mapNSDragOperation(NSDragOperation nsActions)
219 {
221  for (int i=0; dnd_enums[i].mac_code; i++) {
222  if (nsActions & dnd_enums[i].mac_code)
223  return dnd_enums[i].qt_code;
224  }
225  return action;
226 }
227 
228 Qt::DropActions qt_mac_mapNSDragOperations(NSDragOperation nsActions)
229 {
230  Qt::DropActions actions = Qt::IgnoreAction;
231  for (int i=0; dnd_enums[i].mac_code; i++) {
232  if (nsActions & dnd_enums[i].mac_code)
233  actions |= dnd_enums[i].qt_code;
234  }
235  return actions;
236 }
237 
238 Q_GLOBAL_STATIC(DnDParams, currentDnDParameters);
239 DnDParams *macCurrentDnDParameters()
240 {
241  return currentDnDParameters();
242 }
243 #endif
244 
245 bool macWindowIsTextured( void * /*OSWindowRef*/ window )
246 {
247  OSWindowRef wnd = static_cast<OSWindowRef>(window);
248 #if QT_MAC_USE_COCOA
249  return ( [wnd styleMask] & NSTexturedBackgroundWindowMask ) ? true : false;
250 #else
251  WindowAttributes currentAttributes;
252  GetWindowAttributes(wnd, &currentAttributes);
253  return (currentAttributes & kWindowMetalAttribute) ? true : false;
254 #endif
255 }
256 
257 void macWindowToolbarShow(const QWidget *widget, bool show )
258 {
259  OSWindowRef wnd = qt_mac_window_for(widget);
260 #if QT_MAC_USE_COCOA
261  if (NSToolbar *toolbar = [wnd toolbar]) {
263  if (show != [toolbar isVisible]) {
264  [toolbar setVisible:show];
265  } else {
266  // The toolbar may be in sync, but we are not, update our framestrut.
267  qt_widget_private(const_cast<QWidget *>(widget))->updateFrameStrut();
268  }
269  }
270 #else
271  qt_widget_private(const_cast<QWidget *>(widget))->updateFrameStrut();
272  ShowHideWindowToolbar(wnd, show, false);
273 #endif
274 }
275 
276 
277 void macWindowToolbarSet( void * /*OSWindowRef*/ window, void *toolbarRef )
278 {
279  OSWindowRef wnd = static_cast<OSWindowRef>(window);
280 #if QT_MAC_USE_COCOA
281  [wnd setToolbar:static_cast<NSToolbar *>(toolbarRef)];
282 #else
283  SetWindowToolbar(wnd, static_cast<HIToolbarRef>(toolbarRef));
284 #endif
285 }
286 
287 bool macWindowToolbarIsVisible( void * /*OSWindowRef*/ window )
288 {
289  OSWindowRef wnd = static_cast<OSWindowRef>(window);
290 #if QT_MAC_USE_COCOA
291  if (NSToolbar *toolbar = [wnd toolbar])
292  return [toolbar isVisible];
293  return false;
294 #else
295  return IsWindowToolbarVisible(wnd);
296 #endif
297 }
298 
299 void macWindowSetHasShadow( void * /*OSWindowRef*/ window, bool hasShadow )
300 {
301  OSWindowRef wnd = static_cast<OSWindowRef>(window);
302 #if QT_MAC_USE_COCOA
303  [wnd setHasShadow:BOOL(hasShadow)];
304 #else
305  if (hasShadow)
306  ChangeWindowAttributes(wnd, 0, kWindowNoShadowAttribute);
307  else
308  ChangeWindowAttributes(wnd, kWindowNoShadowAttribute, 0);
309 #endif
310 }
311 
312 void macWindowFlush(void * /*OSWindowRef*/ window)
313 {
314  OSWindowRef wnd = static_cast<OSWindowRef>(window);
315 #if QT_MAC_USE_COCOA
316  [wnd flushWindowIfNeeded];
317 #else
318  HIWindowFlush(wnd);
319 #endif
320 }
321 
322 void * /*NSImage */qt_mac_create_nsimage(const QPixmap &pm)
323 {
325  if(QCFType<CGImageRef> image = pm.toMacCGImageRef()) {
326  NSImage *newImage = 0;
327  NSRect imageRect = NSMakeRect(0.0, 0.0, CGImageGetWidth(image), CGImageGetHeight(image));
328  newImage = [[NSImage alloc] initWithSize:imageRect.size];
329  [newImage lockFocus];
330  {
331  CGContextRef imageContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
332  CGContextDrawImage(imageContext, *(CGRect*)&imageRect, image);
333  }
334  [newImage unlockFocus];
335  return newImage;
336  }
337  return 0;
338 }
339 
341 {
342 #ifdef QT_MAC_USE_COCOA
343  [qt_mac_nativeview_for(widget) updateTrackingAreas];
344 #else
345  Q_UNUSED(widget);
346 #endif
347 }
348 
349 OSStatus qt_mac_drawCGImage(CGContextRef inContext, const CGRect *inBounds, CGImageRef inImage)
350 {
351  // Verbatim copy if HIViewDrawCGImage (as shown on Carbon-Dev)
352  OSStatus err = noErr;
353 
354  require_action(inContext != NULL, InvalidContext, err = paramErr);
355  require_action(inBounds != NULL, InvalidBounds, err = paramErr);
356  require_action(inImage != NULL, InvalidImage, err = paramErr);
357 
358  CGContextSaveGState( inContext );
359  CGContextTranslateCTM (inContext, 0, inBounds->origin.y + CGRectGetMaxY(*inBounds));
360  CGContextScaleCTM(inContext, 1, -1);
361 
362  CGContextDrawImage(inContext, *inBounds, inImage);
363 
364  CGContextRestoreGState(inContext);
365 InvalidImage:
366 InvalidBounds:
367 InvalidContext:
368  return err;
369 }
370 
372 {
373 #ifndef QT_MAC_USE_COCOA
374  OSViewRef nativeSizeGrip = 0;
375  HIViewFindByID(HIViewGetRoot(HIViewGetWindow(HIViewRef(widget->winId()))), kHIViewWindowGrowBoxID, &nativeSizeGrip);
376  return (nativeSizeGrip != 0);
377 #else
378  return [[reinterpret_cast<NSView *>(widget->effectiveWinId()) window] showsResizeIndicator];
379 #endif
380 }
381 struct qt_mac_enum_mapper
382 {
383  int mac_code;
384  int qt_code;
385 #if defined(DEBUG_MOUSE_MAPS)
386 # define QT_MAC_MAP_ENUM(x) x, #x
387  const char *desc;
388 #else
389 # define QT_MAC_MAP_ENUM(x) x
390 #endif
391 };
392 
393 //mouse buttons
395 { kEventMouseButtonPrimary, QT_MAC_MAP_ENUM(Qt::LeftButton) },
396 { kEventMouseButtonSecondary, QT_MAC_MAP_ENUM(Qt::RightButton) },
397 { kEventMouseButtonTertiary, QT_MAC_MAP_ENUM(Qt::MidButton) },
400 { 0, QT_MAC_MAP_ENUM(0) }
401 };
402 Qt::MouseButtons qt_mac_get_buttons(int buttons)
403 {
404 #ifdef DEBUG_MOUSE_MAPS
405  qDebug("Qt: internal: **Mapping buttons: %d (0x%04x)", buttons, buttons);
406 #endif
407  Qt::MouseButtons ret = Qt::NoButton;
408  for(int i = 0; qt_mac_mouse_symbols[i].qt_code; i++) {
409  if (buttons & (0x01<<(qt_mac_mouse_symbols[i].mac_code-1))) {
410 #ifdef DEBUG_MOUSE_MAPS
411  qDebug("Qt: internal: got button: %s", qt_mac_mouse_symbols[i].desc);
412 #endif
413  ret |= Qt::MouseButtons(qt_mac_mouse_symbols[i].qt_code);
414  }
415  }
416  return ret;
417 }
418 Qt::MouseButton qt_mac_get_button(EventMouseButton button)
419 {
420 #ifdef DEBUG_MOUSE_MAPS
421  qDebug("Qt: internal: **Mapping button: %d (0x%04x)", button, button);
422 #endif
423  Qt::MouseButtons ret = 0;
424  for(int i = 0; qt_mac_mouse_symbols[i].qt_code; i++) {
425  if (button == qt_mac_mouse_symbols[i].mac_code) {
426 #ifdef DEBUG_MOUSE_MAPS
427  qDebug("Qt: internal: got button: %s", qt_mac_mouse_symbols[i].desc);
428 #endif
429  return Qt::MouseButton(qt_mac_mouse_symbols[i].qt_code);
430  }
431  }
432  return Qt::NoButton;
433 }
434 
436 {
437  QToolBarChangeEvent ev(!(GetCurrentKeyModifiers() & cmdKey));
438  qt_sendSpontaneousEvent(widget, &ev);
439 }
440 
441 Q_GLOBAL_STATIC(QMacTabletHash, tablet_hash)
443 {
444  return tablet_hash();
445 }
446 
447 #ifdef QT_MAC_USE_COCOA
448 
449 // Clears the QWidget pointer that each QCocoaView holds.
450 void qt_mac_clearCocoaViewQWidgetPointers(QWidget *widget)
451 {
452  QT_MANGLE_NAMESPACE(QCocoaView) *cocoaView = reinterpret_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(qt_mac_nativeview_for(widget));
453  if (cocoaView && [cocoaView respondsToSelector:@selector(qt_qwidget)]) {
454  [cocoaView qt_clearQWidget];
455  }
456 }
457 
458 void qt_dispatchTabletProximityEvent(void * /*NSEvent * */ tabletEvent)
459 {
460  NSEvent *proximityEvent = static_cast<NSEvent *>(tabletEvent);
461  // simply construct a Carbon proximity record and handle it all in one spot.
462  TabletProximityRec carbonProximityRec = { [proximityEvent vendorID],
463  [proximityEvent tabletID],
464  [proximityEvent pointingDeviceID],
465  [proximityEvent deviceID],
466  [proximityEvent systemTabletID],
467  [proximityEvent vendorPointingDeviceType],
468  [proximityEvent pointingDeviceSerialNumber],
469  [proximityEvent uniqueID],
470  [proximityEvent capabilityMask],
471  [proximityEvent pointingDeviceType],
472  [proximityEvent isEnteringProximity] };
473  qt_dispatchTabletProximityEvent(carbonProximityRec);
474 }
475 #endif // QT_MAC_USE_COCOA
476 
477 void qt_dispatchTabletProximityEvent(const ::TabletProximityRec &proxRec)
478 {
479  QTabletDeviceData proximityDevice;
480  proximityDevice.tabletUniqueID = proxRec.uniqueID;
481  proximityDevice.capabilityMask = proxRec.capabilityMask;
482 
483  switch (proxRec.pointerType) {
484  case NSUnknownPointingDevice:
485  default:
486  proximityDevice.tabletPointerType = QTabletEvent::UnknownPointer;
487  break;
488  case NSPenPointingDevice:
489  proximityDevice.tabletPointerType = QTabletEvent::Pen;
490  break;
491  case NSCursorPointingDevice:
492  proximityDevice.tabletPointerType = QTabletEvent::Cursor;
493  break;
494  case NSEraserPointingDevice:
495  proximityDevice.tabletPointerType = QTabletEvent::Eraser;
496  break;
497  }
498  uint bits = proxRec.vendorPointerType;
499  if (bits == 0 && proximityDevice.tabletUniqueID != 0) {
500  // Fallback. It seems that the driver doesn't always include all the information.
501  // High-End Wacom devices store their "type" in the uper bits of the Unique ID.
502  // I'm not sure how to handle it for consumer devices, but I'll test that in a bit.
503  bits = proximityDevice.tabletUniqueID >> 32;
504  }
505  // Defined in the "EN0056-NxtGenImpGuideX"
506  // on Wacom's Developer Website (www.wacomeng.com)
507  if (((bits & 0x0006) == 0x0002) && ((bits & 0x0F06) != 0x0902)) {
508  proximityDevice.tabletDeviceType = QTabletEvent::Stylus;
509  } else {
510  switch (bits & 0x0F06) {
511  case 0x0802:
512  proximityDevice.tabletDeviceType = QTabletEvent::Stylus;
513  break;
514  case 0x0902:
515  proximityDevice.tabletDeviceType = QTabletEvent::Airbrush;
516  break;
517  case 0x0004:
518  proximityDevice.tabletDeviceType = QTabletEvent::FourDMouse;
519  break;
520  case 0x0006:
521  proximityDevice.tabletDeviceType = QTabletEvent::Puck;
522  break;
523  case 0x0804:
524  proximityDevice.tabletDeviceType = QTabletEvent::RotationStylus;
525  break;
526  default:
527  proximityDevice.tabletDeviceType = QTabletEvent::NoDevice;
528  }
529  }
530  // The deviceID is "unique" while in the proximity, it's a key that we can use for
531  // linking up TabletDeviceData to an event (especially if there are two devices in action).
532  bool entering = proxRec.enterProximity;
533  if (entering) {
534  qt_mac_tablet_hash()->insert(proxRec.deviceID, proximityDevice);
535  } else {
536  qt_mac_tablet_hash()->remove(proxRec.deviceID);
537  }
538 
539  QTabletEvent qtabletProximity(entering ? QEvent::TabletEnterProximity
541  QPoint(), QPoint(), QPointF(), proximityDevice.tabletDeviceType,
542  proximityDevice.tabletPointerType, 0., 0, 0, 0., 0., 0, 0,
543  proximityDevice.tabletUniqueID);
544 
545  qt_sendSpontaneousEvent(qApp, &qtabletProximity);
546 }
547 
548 // Use this method to keep all the information in the TextSegment. As long as it is ordered
549 // we are in OK shape, and we can influence that ourselves.
550 struct KeyPair
551 {
554 };
555 
556 bool operator==(const KeyPair &entry, QChar qchar)
557 {
558  return entry.cocoaKey == qchar;
559 }
560 
561 bool operator<(const KeyPair &entry, QChar qchar)
562 {
563  return entry.cocoaKey < qchar;
564 }
565 
566 bool operator<(QChar qchar, const KeyPair &entry)
567 {
568  return qchar < entry.cocoaKey;
569 }
570 
571 bool operator<(const Qt::Key &key, const KeyPair &entry)
572 {
573  return key < entry.qtKey;
574 }
575 
576 bool operator<(const KeyPair &entry, const Qt::Key &key)
577 {
578  return entry.qtKey < key;
579 }
580 
581 static bool qtKey2CocoaKeySortLessThan(const KeyPair &entry1, const KeyPair &entry2)
582 {
583  return entry1.qtKey < entry2.qtKey;
584 }
585 
586 static const int NumEntries = 59;
587 static const KeyPair entries[NumEntries] = {
588  { NSEnterCharacter, Qt::Key_Enter },
589  { NSBackspaceCharacter, Qt::Key_Backspace },
590  { NSTabCharacter, Qt::Key_Tab },
591  { NSNewlineCharacter, Qt::Key_Return },
592  { NSCarriageReturnCharacter, Qt::Key_Return },
593  { NSBackTabCharacter, Qt::Key_Backtab },
594  { kEscapeCharCode, Qt::Key_Escape },
595  // Cocoa sends us delete when pressing backspace!
596  // (NB when we reverse this list in qtKey2CocoaKey, there
597  // will be two indices of Qt::Key_Backspace. But is seems to work
598  // ok for menu shortcuts (which uses that function):
599  { NSDeleteCharacter, Qt::Key_Backspace },
600  { NSUpArrowFunctionKey, Qt::Key_Up },
601  { NSDownArrowFunctionKey, Qt::Key_Down },
602  { NSLeftArrowFunctionKey, Qt::Key_Left },
603  { NSRightArrowFunctionKey, Qt::Key_Right },
604  { NSF1FunctionKey, Qt::Key_F1 },
605  { NSF2FunctionKey, Qt::Key_F2 },
606  { NSF3FunctionKey, Qt::Key_F3 },
607  { NSF4FunctionKey, Qt::Key_F4 },
608  { NSF5FunctionKey, Qt::Key_F5 },
609  { NSF6FunctionKey, Qt::Key_F6 },
610  { NSF7FunctionKey, Qt::Key_F7 },
611  { NSF8FunctionKey, Qt::Key_F8 },
612  { NSF9FunctionKey, Qt::Key_F9 },
613  { NSF10FunctionKey, Qt::Key_F10 },
614  { NSF11FunctionKey, Qt::Key_F11 },
615  { NSF12FunctionKey, Qt::Key_F12 },
616  { NSF13FunctionKey, Qt::Key_F13 },
617  { NSF14FunctionKey, Qt::Key_F14 },
618  { NSF15FunctionKey, Qt::Key_F15 },
619  { NSF16FunctionKey, Qt::Key_F16 },
620  { NSF17FunctionKey, Qt::Key_F17 },
621  { NSF18FunctionKey, Qt::Key_F18 },
622  { NSF19FunctionKey, Qt::Key_F19 },
623  { NSF20FunctionKey, Qt::Key_F20 },
624  { NSF21FunctionKey, Qt::Key_F21 },
625  { NSF22FunctionKey, Qt::Key_F22 },
626  { NSF23FunctionKey, Qt::Key_F23 },
627  { NSF24FunctionKey, Qt::Key_F24 },
628  { NSF25FunctionKey, Qt::Key_F25 },
629  { NSF26FunctionKey, Qt::Key_F26 },
630  { NSF27FunctionKey, Qt::Key_F27 },
631  { NSF28FunctionKey, Qt::Key_F28 },
632  { NSF29FunctionKey, Qt::Key_F29 },
633  { NSF30FunctionKey, Qt::Key_F30 },
634  { NSF31FunctionKey, Qt::Key_F31 },
635  { NSF32FunctionKey, Qt::Key_F32 },
636  { NSF33FunctionKey, Qt::Key_F33 },
637  { NSF34FunctionKey, Qt::Key_F34 },
638  { NSF35FunctionKey, Qt::Key_F35 },
639  { NSInsertFunctionKey, Qt::Key_Insert },
640  { NSDeleteFunctionKey, Qt::Key_Delete },
641  { NSHomeFunctionKey, Qt::Key_Home },
642  { NSEndFunctionKey, Qt::Key_End },
643  { NSPageUpFunctionKey, Qt::Key_PageUp },
644  { NSPageDownFunctionKey, Qt::Key_PageDown },
645  { NSPrintScreenFunctionKey, Qt::Key_Print },
646  { NSScrollLockFunctionKey, Qt::Key_ScrollLock },
647  { NSPauseFunctionKey, Qt::Key_Pause },
648  { NSSysReqFunctionKey, Qt::Key_SysReq },
649  { NSMenuFunctionKey, Qt::Key_Menu },
650  { NSHelpFunctionKey, Qt::Key_Help },
651 };
652 static const KeyPair * const end = entries + NumEntries;
653 
655 {
656  // The first time this function is called, create a reverse
657  // looup table sorted on Qt Key rather than Cocoa key:
658  static QVector<KeyPair> rev_entries(NumEntries);
659  static bool mustInit = true;
660  if (mustInit){
661  mustInit = false;
662  for (int i=0; i<NumEntries; ++i)
663  rev_entries[i] = entries[i];
664  qSort(rev_entries.begin(), rev_entries.end(), qtKey2CocoaKeySortLessThan);
665  }
667  = qBinaryFind(rev_entries.begin(), rev_entries.end(), key);
668  if (i == rev_entries.end())
669  return QChar();
670  return i->cocoaKey;
671 }
672 
673 #ifdef QT_MAC_USE_COCOA
674 static Qt::Key cocoaKey2QtKey(QChar keyCode)
675 {
676  const KeyPair *i = qBinaryFind(entries, end, keyCode);
677  if (i == end)
678  return Qt::Key(keyCode.unicode());
679  return i->qtKey;
680 }
681 
682 Qt::KeyboardModifiers qt_cocoaModifiers2QtModifiers(ulong modifierFlags)
683 {
684  Qt::KeyboardModifiers qtMods =Qt::NoModifier;
685  if (modifierFlags & NSShiftKeyMask)
686  qtMods |= Qt::ShiftModifier;
687  if (modifierFlags & NSControlKeyMask)
688  qtMods |= Qt::MetaModifier;
689  if (modifierFlags & NSAlternateKeyMask)
690  qtMods |= Qt::AltModifier;
691  if (modifierFlags & NSCommandKeyMask)
692  qtMods |= Qt::ControlModifier;
693  if (modifierFlags & NSNumericPadKeyMask)
694  qtMods |= Qt::KeypadModifier;
695  return qtMods;
696 }
697 
698 NSString *qt_mac_removePrivateUnicode(NSString* string)
699 {
700  int len = [string length];
701  if (len) {
702  QVarLengthArray <unichar, 10> characters(len);
703  bool changed = false;
704  for (int i = 0; i<len; i++) {
705  characters[i] = [string characterAtIndex:i];
706  // check if they belong to key codes in private unicode range
707  // currently we need to handle only the NSDeleteFunctionKey
708  if (characters[i] == NSDeleteFunctionKey) {
709  characters[i] = NSDeleteCharacter;
710  changed = true;
711  }
712  }
713  if (changed)
714  return [NSString stringWithCharacters:characters.data() length:len];
715  }
716  return string;
717 }
718 
719 Qt::KeyboardModifiers qt_cocoaDragOperation2QtModifiers(uint dragOperations)
720 {
721  Qt::KeyboardModifiers qtMods =Qt::NoModifier;
722  if (dragOperations & NSDragOperationLink)
723  qtMods |= Qt::MetaModifier;
724  if (dragOperations & NSDragOperationGeneric)
725  qtMods |= Qt::ControlModifier;
726  if (dragOperations & NSDragOperationCopy)
727  qtMods |= Qt::AltModifier;
728  return qtMods;
729 }
730 
731 static inline QEvent::Type cocoaEvent2QtEvent(NSUInteger eventType)
732 {
733  // Handle the trivial cases that can be determined from the type.
734  switch (eventType) {
735  case NSKeyDown:
736  return QEvent::KeyPress;
737  case NSKeyUp:
738  return QEvent::KeyRelease;
739  case NSLeftMouseDown:
740  case NSRightMouseDown:
741  case NSOtherMouseDown:
743  case NSLeftMouseUp:
744  case NSRightMouseUp:
745  case NSOtherMouseUp:
747  case NSMouseMoved:
748  case NSLeftMouseDragged:
749  case NSRightMouseDragged:
750  case NSOtherMouseDragged:
751  return QEvent::MouseMove;
752  case NSScrollWheel:
753  return QEvent::Wheel;
754  }
755  return QEvent::None;
756 }
757 
758 static bool mustUseCocoaKeyEvent()
759 {
760  QCFType<TISInputSourceRef> source = TISCopyCurrentKeyboardInputSource();
761  return TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData) == 0;
762 }
763 
764 bool qt_dispatchKeyEventWithCocoa(void * /*NSEvent * */ keyEvent, QWidget *widgetToGetEvent)
765 {
766  NSEvent *event = static_cast<NSEvent *>(keyEvent);
767  NSString *keyChars = [event charactersIgnoringModifiers];
768  int keyLength = [keyChars length];
769  if (keyLength == 0)
770  return false; // Dead Key, nothing to do!
771  bool ignoreText = false;
773  if (keyLength == 1) {
774  QChar ch([keyChars characterAtIndex:0]);
775  if (ch.isLower())
776  ch = ch.toUpper();
777  qtKey = cocoaKey2QtKey(ch);
778  // Do not set the text for Function-Key Unicodes characters (0xF700–0xF8FF).
779  ignoreText = (ch.unicode() >= 0xF700 && ch.unicode() <= 0xF8FF);
780  }
781  Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([event modifierFlags]);
782  QString text;
783 
784  // To quote from the Carbon port: This is actually wrong--but it is the best that
785  // can be done for now because of the Control/Meta mapping issues
786  // (we always get text on the Mac)
787  if (!ignoreText && !(keyMods & (Qt::ControlModifier | Qt::MetaModifier)))
788  text = QCFString::toQString(reinterpret_cast<CFStringRef>(keyChars));
789 
790  UInt32 macScanCode = 1;
791  QKeyEventEx ke(cocoaEvent2QtEvent([event type]), qtKey, keyMods, text, [event isARepeat], qMax(1, keyLength),
792  macScanCode, [event keyCode], [event modifierFlags]);
793  return qt_sendSpontaneousEvent(widgetToGetEvent, &ke) && ke.isAccepted();
794 }
795 #endif
796 
798 {
799  if (buttonNum == 0)
800  return Qt::LeftButton;
801  if (buttonNum == 1)
802  return Qt::RightButton;
803  if (buttonNum == 2)
804  return Qt::MidButton;
805  if (buttonNum == 3)
806  return Qt::XButton1;
807  if (buttonNum == 4)
808  return Qt::XButton2;
809  return Qt::NoButton;
810 }
811 
812 bool qt_dispatchKeyEvent(void * /*NSEvent * */ keyEvent, QWidget *widgetToGetEvent)
813 {
814 #ifndef QT_MAC_USE_COCOA
815  Q_UNUSED(keyEvent);
816  Q_UNUSED(widgetToGetEvent);
817  return false;
818 #else
819  NSEvent *event = static_cast<NSEvent *>(keyEvent);
820  EventRef key_event = static_cast<EventRef>(const_cast<void *>([event eventRef]));
821  Q_ASSERT(key_event);
822  unsigned int info = 0;
823 
824  if ([event type] == NSKeyDown) {
825  NSString *characters = [event characters];
826  if ([characters length]) {
827  unichar value = [characters characterAtIndex:0];
828  qt_keymapper_private()->updateKeyMap(0, key_event, (void *)&value);
829  info = value;
830  }
831  }
832 
833  if (qt_mac_sendMacEventToWidget(widgetToGetEvent, key_event))
834  return true;
835 
836  if (mustUseCocoaKeyEvent())
837  return qt_dispatchKeyEventWithCocoa(keyEvent, widgetToGetEvent);
838 
839  bool consumed = qt_keymapper_private()->translateKeyEvent(widgetToGetEvent, 0, key_event, &info, true);
840  return consumed && (info != 0);
841 #endif
842 }
843 
844 void qt_dispatchModifiersChanged(void * /*NSEvent * */flagsChangedEvent, QWidget *widgetToGetEvent)
845 {
846 #ifndef QT_MAC_USE_COCOA
847  Q_UNUSED(flagsChangedEvent);
848  Q_UNUSED(widgetToGetEvent);
849 #else
850  UInt32 modifiers = 0;
851  // Sync modifiers with Qt
852  NSEvent *event = static_cast<NSEvent *>(flagsChangedEvent);
853  EventRef key_event = static_cast<EventRef>(const_cast<void *>([event eventRef]));
854  Q_ASSERT(key_event);
855  GetEventParameter(key_event, kEventParamKeyModifiers, typeUInt32, 0,
856  sizeof(modifiers), 0, &modifiers);
857  extern void qt_mac_send_modifiers_changed(quint32 modifiers, QObject *object);
858  qt_mac_send_modifiers_changed(modifiers, widgetToGetEvent);
859 #endif
860 }
861 
863 {
864  return QPointF(p.x, flipYCoordinate(p.y));
865 }
866 
868 {
869  return NSMakePoint(p.x(), flipYCoordinate(p.y()));
870 }
871 
873 {
874  return NSMakePoint(p.x(), flipYCoordinate(p.y()));
875 }
876 
877 #if QT_MAC_USE_COCOA && __OBJC__
878 
879 void qt_mac_handleNonClientAreaMouseEvent(NSWindow *window, NSEvent *event)
880 {
881  QWidget *widgetToGetEvent = [window QT_MANGLE_NAMESPACE(qt_qwidget)];
882  if (widgetToGetEvent == 0)
883  return;
884 
885  NSEventType evtType = [event type];
886  QPoint qlocalPoint;
887  QPoint qglobalPoint;
888  bool processThisEvent = false;
889  bool fakeNCEvents = false;
890  bool fakeMouseEvents = false;
891 
892  // Check if this is a mouse event.
893  if (evtType == NSLeftMouseDown || evtType == NSLeftMouseUp
894  || evtType == NSRightMouseDown || evtType == NSRightMouseUp
895  || evtType == NSOtherMouseDown || evtType == NSOtherMouseUp
896  || evtType == NSMouseMoved || evtType == NSLeftMouseDragged
897  || evtType == NSRightMouseDragged || evtType == NSOtherMouseDragged) {
898  // Check if we want to pass this message to another window
899  if (mac_mouse_grabber && mac_mouse_grabber != widgetToGetEvent) {
900  NSWindow *grabWindow = static_cast<NSWindow *>(qt_mac_window_for(mac_mouse_grabber));
901  if (window != grabWindow) {
902  window = grabWindow;
903  widgetToGetEvent = mac_mouse_grabber;
904  fakeNCEvents = true;
905  }
906  }
907  // Dont generate normal NC mouse events for Left Button dragged
908  if(evtType != NSLeftMouseDragged || fakeNCEvents) {
909  NSPoint windowPoint = [event locationInWindow];
910  NSPoint globalPoint = [[event window] convertBaseToScreen:windowPoint];
911  NSRect frameRect = [window frame];
912  if (fakeNCEvents || NSMouseInRect(globalPoint, frameRect, NO)) {
913  NSRect contentRect = [window contentRectForFrameRect:frameRect];
914  qglobalPoint = QPoint(flipPoint(globalPoint).toPoint());
915  QWidget *w = widgetToGetEvent->childAt(widgetToGetEvent->mapFromGlobal(qglobalPoint));
916  // check that the mouse pointer is on the non-client area and
917  // there are not widgets in it.
918  if (fakeNCEvents || (!NSMouseInRect(globalPoint, contentRect, NO) && !w)) {
919  qglobalPoint = QPoint(flipPoint(globalPoint).toPoint());
920  qlocalPoint = widgetToGetEvent->mapFromGlobal(qglobalPoint);
921  processThisEvent = true;
922  }
923  }
924  }
925  }
926  // This is not an NC area mouse message.
927  if (!processThisEvent)
928  return;
929 
930  // If the window is frame less, generate fake mouse events instead. (floating QToolBar)
931  // or if someone already got an explicit or implicit grab
932  if (mac_mouse_grabber || qt_button_down ||
933  (fakeNCEvents && (widgetToGetEvent->window()->windowFlags() & Qt::FramelessWindowHint)))
934  fakeMouseEvents = true;
935 
936  Qt::MouseButton button;
937  QEvent::Type eventType;
938  // Convert to Qt::Event type
939  switch (evtType) {
940  case NSLeftMouseDown:
941  button = Qt::LeftButton;
942  eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonPress
944  break;
945  case NSLeftMouseUp:
946  button = Qt::LeftButton;
947  eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonRelease
949  break;
950  case NSRightMouseDown:
951  button = Qt::RightButton;
952  eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonPress
954  break;
955  case NSRightMouseUp:
956  button = Qt::RightButton;
957  eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonRelease
959  break;
960  case NSOtherMouseDown:
961  button = cocoaButton2QtButton([event buttonNumber]);
962  eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonPress
964  break;
965  case NSOtherMouseUp:
966  button = cocoaButton2QtButton([event buttonNumber]);
967  eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonRelease
969  break;
970  case NSMouseMoved:
971  button = Qt::NoButton;
972  eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
974  break;
975  case NSLeftMouseDragged:
976  button = Qt::LeftButton;
977  eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
979  break;
980  case NSRightMouseDragged:
981  button = Qt::RightButton;
982  eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
984  break;
985  case NSOtherMouseDragged:
986  button = cocoaButton2QtButton([event buttonNumber]);
987  eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
989  break;
990  default:
991  qWarning("not handled! Non client area mouse message");
992  return;
993  }
994 
995  Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([event modifierFlags]);
996  if (eventType == QEvent::NonClientAreaMouseButtonPress || eventType == QEvent::MouseButtonPress) {
997  NSInteger clickCount = [event clickCount];
998  if (clickCount % 2 == 0)
999  eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonDblClick
1001  if (button == Qt::LeftButton && (keyMods & Qt::MetaModifier)) {
1002  button = Qt::RightButton;
1003  qt_leftButtonIsRightButton = true;
1004  }
1005  } else if (eventType == QEvent::NonClientAreaMouseButtonRelease || eventType == QEvent::MouseButtonRelease) {
1006  if (button == Qt::LeftButton && qt_leftButtonIsRightButton) {
1007  button = Qt::RightButton;
1008  qt_leftButtonIsRightButton = false;
1009  }
1010  }
1011 
1012  Qt::MouseButtons buttons = 0;
1013  {
1014  UInt32 mac_buttons;
1015  if (GetEventParameter((EventRef)[event eventRef], kEventParamMouseChord, typeUInt32, 0,
1016  sizeof(mac_buttons), 0, &mac_buttons) == noErr)
1017  buttons = qt_mac_get_buttons(mac_buttons);
1018  }
1019 
1020  QMouseEvent qme(eventType, qlocalPoint, qglobalPoint, button, buttons, keyMods);
1021  qt_sendSpontaneousEvent(widgetToGetEvent, &qme);
1022 
1023  // We don't need to set the implicit grab widget here because we won't
1024  // reach this point if then event type is Press over a Qt widget.
1025  // However we might need to unset it if the event is Release.
1026  if (eventType == QEvent::MouseButtonRelease)
1027  qt_button_down = 0;
1028 }
1029 
1030 QWidget *qt_mac_getTargetForKeyEvent(QWidget *widgetThatReceivedEvent)
1031 {
1032  if (QWidget *popup = QApplication::activePopupWidget()) {
1033  QWidget *focusInPopup = popup->focusWidget();
1034  return focusInPopup ? focusInPopup : popup;
1035  }
1036 
1037  QWidget *widgetToGetKey = qApp->focusWidget();
1038  if (!widgetToGetKey)
1039  widgetToGetKey = widgetThatReceivedEvent;
1040 
1041  return widgetToGetKey;
1042 }
1043 
1044 // This function will find the widget that should receive the
1045 // mouse event. Because of explicit/implicit mouse grabs, popups,
1046 // etc, this might not end up being the same as the widget under
1047 // the mouse (which is more interresting when handling enter/leave
1048 // events
1050  // You can call this function without providing an event.
1051  NSEvent *event,
1052  QEvent::Type eventType,
1053  QPoint &returnLocalPoint,
1054  QPoint &returnGlobalPoint,
1055  QWidget *nativeWidget,
1056  QWidget **returnWidgetUnderMouse)
1057 {
1058  Q_UNUSED(event);
1059  NSPoint nsglobalpoint = event ? [[event window] convertBaseToScreen:[event locationInWindow]] : [NSEvent mouseLocation];
1060  QPointF globalPointF = flipPoint(nsglobalpoint);
1061  // Always truncate to convert to integer, same as Cocoa does for clicks
1062  returnGlobalPoint = QPoint(globalPointF.x(), globalPointF.y());
1063  QWidget *mouseGrabber = QWidget::mouseGrabber();
1064  bool buttonDownNotBlockedByModal = qt_button_down && !QApplicationPrivate::isBlockedByModal(qt_button_down);
1066 
1067  // Resolve the widget under the mouse:
1068  QWidget *widgetUnderMouse = 0;
1069  if (popup || qt_button_down || !nativeWidget || !nativeWidget->isVisible()) {
1070  // Using QApplication::widgetAt for finding the widget under the mouse
1071  // is most safe, since it ignores cocoas own mouse down redirections (which
1072  // we need to be prepared for when using nativeWidget as starting point).
1073  // (the only exception is for QMacNativeWidget, where QApplication::widgetAt fails).
1074  // But it is also slower (I guess), so we try to avoid it and use nativeWidget if we can:
1075  widgetUnderMouse = QApplication::widgetAt(returnGlobalPoint);
1076  }
1077 
1078  if (!widgetUnderMouse && nativeWidget) {
1079  // Entering here should be the common case. We
1080  // also handle the QMacNativeWidget fallback case.
1081  QPoint p = nativeWidget->mapFromGlobal(returnGlobalPoint);
1082  widgetUnderMouse = nativeWidget->childAt(p);
1083  if (!widgetUnderMouse && nativeWidget->rect().contains(p))
1084  widgetUnderMouse = nativeWidget;
1085  }
1086 
1087  if (widgetUnderMouse) {
1088  // Check if widgetUnderMouse is blocked by a modal
1089  // window, or the mouse if over the frame strut:
1090  if (widgetUnderMouse == qt_button_down) {
1091  // Small optimization to avoid an extra call to isBlockedByModal:
1092  if (buttonDownNotBlockedByModal == false)
1093  widgetUnderMouse = 0;
1094  } else if (QApplicationPrivate::isBlockedByModal(widgetUnderMouse)) {
1095  widgetUnderMouse = 0;
1096  }
1097 
1098  if (widgetUnderMouse && widgetUnderMouse->isWindow()) {
1099  // Exclude the titlebar (and frame strut) when finding widget under mouse:
1100  QPoint p = widgetUnderMouse->mapFromGlobal(returnGlobalPoint);
1101  if (!widgetUnderMouse->rect().contains(p))
1102  widgetUnderMouse = 0;
1103  }
1104  }
1105  if (returnWidgetUnderMouse)
1106  *returnWidgetUnderMouse = widgetUnderMouse;
1107 
1108  // Resolve the target for the mouse event. Default will be
1109  // widgetUnderMouse, except if there is a grab (popup/mouse/button-down):
1110  if (popup && !mouseGrabber) {
1111  // We special case handling of popups, since they have an implicitt mouse grab.
1112  QWidget *candidate = buttonDownNotBlockedByModal ? qt_button_down : widgetUnderMouse;
1113  if (!popup->isAncestorOf(candidate)) {
1114  // INVARIANT: we have a popup, but the candidate is not
1115  // in it. But the popup will grab the mouse anyway,
1116  // except if the user scrolls:
1117  if (eventType == QEvent::Wheel)
1118  return 0;
1119  returnLocalPoint = popup->mapFromGlobal(returnGlobalPoint);
1120  return popup;
1121  } else if (popup == candidate) {
1122  // INVARIANT: The candidate is the popup itself, and not a child:
1123  returnLocalPoint = popup->mapFromGlobal(returnGlobalPoint);
1124  return popup;
1125  } else {
1126  // INVARIANT: The candidate is a child inside the popup:
1127  returnLocalPoint = candidate->mapFromGlobal(returnGlobalPoint);
1128  return candidate;
1129  }
1130  }
1131 
1132  QWidget *target = mouseGrabber;
1133  if (!target && buttonDownNotBlockedByModal)
1134  target = qt_button_down;
1135  if (!target)
1136  target = widgetUnderMouse;
1137  if (!target)
1138  return 0;
1139 
1140  returnLocalPoint = target->mapFromGlobal(returnGlobalPoint);
1141  return target;
1142 }
1143 
1145 
1146 static inline void qt_mac_checkEnterLeaveForNativeWidgets(QWidget *maybeEnterWidget)
1147 {
1148  // Dispatch enter/leave for the cases where QApplicationPrivate::sendMouseEvent do
1149  // not. This will in general be the cases when alien widgets are not involved:
1150  // 1. from a native widget to another native widget or
1151  // 2. from a native widget to no widget
1152  // 3. from no widget to a native or alien widget
1153 
1154  if (qt_button_down || QWidget::mouseGrabber())
1155  return;
1156 
1157  if ((maybeEnterWidget == qt_last_native_mouse_receiver) && qt_last_native_mouse_receiver)
1158  return;
1159  if (maybeEnterWidget) {
1160  if (!qt_last_native_mouse_receiver) {
1161  // case 3
1162  QApplicationPrivate::dispatchEnterLeave(maybeEnterWidget, 0);
1163  qt_last_native_mouse_receiver = maybeEnterWidget->internalWinId() ? maybeEnterWidget : maybeEnterWidget->nativeParentWidget();
1164  } else if (maybeEnterWidget->internalWinId()) {
1165  // case 1
1166  QApplicationPrivate::dispatchEnterLeave(maybeEnterWidget, qt_last_native_mouse_receiver);
1167  qt_last_native_mouse_receiver = maybeEnterWidget->internalWinId() ? maybeEnterWidget : maybeEnterWidget->nativeParentWidget();
1168  } // else at lest one of the widgets are alien, so enter/leave will be handled in QApplicationPrivate
1169  } else {
1170  if (qt_last_native_mouse_receiver) {
1171  // case 2
1172  QApplicationPrivate::dispatchEnterLeave(0, qt_last_native_mouse_receiver);
1173  qt_last_mouse_receiver = 0;
1174  qt_last_native_mouse_receiver = 0;
1175  }
1176  }
1177 }
1178 
1179 bool qt_mac_handleMouseEvent(NSEvent *event, QEvent::Type eventType, Qt::MouseButton button, QWidget *nativeWidget, bool fakeEvent)
1180 {
1181  // Give the Input Manager a chance to process the mouse events.
1182  NSInputManager *currentIManager = [NSInputManager currentInputManager];
1183  if (currentIManager && [currentIManager wantsToHandleMouseEvents]) {
1184  [currentIManager handleMouseEvent:event];
1185  }
1186 
1187  // Find the widget that should receive the event, and the widget under the mouse. Those
1188  // can differ if an implicit or explicit mouse grab is active:
1189  QWidget *widgetUnderMouse = 0;
1190  QPoint localPoint, globalPoint;
1191  QWidget *widgetToGetMouse = qt_mac_getTargetForMouseEvent(event, eventType, localPoint, globalPoint, nativeWidget, &widgetUnderMouse);
1192  if (!widgetToGetMouse)
1193  return false;
1194 
1195  // From here on, we let nativeWidget actually be the native widget under widgetUnderMouse. The reason
1196  // for this, is that qt_mac_getTargetForMouseEvent will set cocoa's mouse event redirection aside when
1197  // determining which widget is under the mouse (in other words, it will usually ignore nativeWidget).
1198  // nativeWidget will be used in QApplicationPrivate::sendMouseEvent to correctly dispatch enter/leave events.
1199  if (widgetUnderMouse)
1200  nativeWidget = widgetUnderMouse->internalWinId() ? widgetUnderMouse : widgetUnderMouse->nativeParentWidget();
1201  if (!nativeWidget)
1202  return false;
1203  NSView *view = qt_mac_effectiveview_for(nativeWidget);
1204 
1205  // Handle tablet events (if any) first.
1206  if (qt_mac_handleTabletEvent(view, event)) {
1207  // Tablet event was handled. In Qt we aren't supposed to send the mouse event.
1208  return true;
1209  }
1210 
1211  EventRef carbonEvent = static_cast<EventRef>(const_cast<void *>([event eventRef]));
1212  if (qt_mac_sendMacEventToWidget(widgetToGetMouse, carbonEvent))
1213  return true;
1214 
1215  // Keep previousButton to make sure we don't send double click
1216  // events when the user double clicks using two different buttons:
1217  static Qt::MouseButton previousButton = Qt::NoButton;
1218 
1219  Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([event modifierFlags]);
1220  NSInteger clickCount = [event clickCount];
1221  Qt::MouseButtons buttons = 0;
1222  {
1223  UInt32 mac_buttons;
1224  if (GetEventParameter(carbonEvent, kEventParamMouseChord, typeUInt32, 0,
1225  sizeof(mac_buttons), 0, &mac_buttons) == noErr)
1226  buttons = qt_mac_get_buttons(mac_buttons);
1227  if (fakeEvent && buttons == 0)
1229  }
1230 
1231  // Send enter/leave events for the cases when QApplicationPrivate::sendMouseEvent do not:
1232  qt_mac_checkEnterLeaveForNativeWidgets(widgetUnderMouse);
1233 
1234  switch (eventType) {
1235  default:
1236  qWarning("not handled! %d", eventType);
1237  break;
1238  case QEvent::MouseMove:
1239  if (button == Qt::LeftButton && qt_leftButtonIsRightButton)
1240  button = Qt::RightButton;
1241  break;
1243  qt_button_down = widgetUnderMouse;
1244  if (clickCount % 2 == 0 && (previousButton == Qt::NoButton || previousButton == button))
1245  eventType = QEvent::MouseButtonDblClick;
1246  if (button == Qt::LeftButton && (keyMods & Qt::MetaModifier)) {
1247  button = Qt::RightButton;
1248  qt_leftButtonIsRightButton = true;
1249  }
1250  break;
1252  if (button == Qt::LeftButton && qt_leftButtonIsRightButton) {
1253  button = Qt::RightButton;
1254  qt_leftButtonIsRightButton = false;
1255  }
1256  qt_button_down = 0;
1257  break;
1258  }
1259 
1260  qt_mac_updateCursorWithWidgetUnderMouse(widgetUnderMouse);
1261 
1262  DnDParams *dndParams = currentDnDParameters();
1263  dndParams->view = view;
1264  dndParams->theEvent = event;
1265  dndParams->globalPoint = globalPoint;
1266 
1267  // Send the mouse event:
1268  QMouseEvent qme(eventType, localPoint, globalPoint, button, buttons, keyMods);
1270  widgetToGetMouse, &qme, widgetUnderMouse, nativeWidget,
1271  &qt_button_down, qt_last_mouse_receiver, true);
1272 
1273  if (eventType == QEvent::MouseButtonPress && button == Qt::RightButton) {
1274  QContextMenuEvent qcme(QContextMenuEvent::Mouse, localPoint, globalPoint, keyMods);
1275  qt_sendSpontaneousEvent(widgetToGetMouse, &qcme);
1276  }
1277 
1278  if (eventType == QEvent::MouseButtonRelease) {
1279  // A mouse button was released, which means that the implicit grab was
1280  // released. We therefore need to re-check if should send (delayed) enter leave events:
1281  // qt_button_down has now become NULL since the call at the top of the function. Also, since
1282  // the relase might have closed a window, we dont give the nativeWidget hint
1283  qt_mac_getTargetForMouseEvent(0, QEvent::None, localPoint, globalPoint, nativeWidget, &widgetUnderMouse);
1284  qt_mac_checkEnterLeaveForNativeWidgets(widgetUnderMouse);
1285  }
1286 
1287  previousButton = button;
1288  return true;
1289 }
1290 #endif
1291 
1292 bool qt_mac_handleTabletEvent(void * /*QCocoaView * */view, void * /*NSEvent * */tabletEvent)
1293 {
1294 #ifndef QT_MAC_USE_COCOA
1295  Q_UNUSED(view);
1296  Q_UNUSED(tabletEvent);
1297  return false;
1298 #else
1299  QT_MANGLE_NAMESPACE(QCocoaView) *theView = static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(view);
1300  NSView *theNSView = static_cast<NSView *>(view);
1301  NSEvent *theTabletEvent = static_cast<NSEvent *>(tabletEvent);
1302 
1303  NSEventType eventType = [theTabletEvent type];
1304  if (eventType != NSTabletPoint && [theTabletEvent subtype] != NSTabletPointEventSubtype)
1305  return false; // Not a tablet event.
1306 
1307  NSPoint windowPoint = [theTabletEvent locationInWindow];
1308  NSPoint globalPoint = [[theTabletEvent window] convertBaseToScreen:windowPoint];
1309 
1310  QWidget *qwidget = [theView qt_qwidget];
1311  QWidget *widgetToGetMouse = qwidget;
1312  QWidget *popup = qAppInstance()->activePopupWidget();
1313  if (popup && popup != qwidget->window())
1314  widgetToGetMouse = popup;
1315 
1316  if (qt_mac_sendMacEventToWidget(widgetToGetMouse,
1317  static_cast<EventRef>(const_cast<void *>([theTabletEvent eventRef]))))
1318  return true;
1319  if (widgetToGetMouse != qwidget) {
1320  theNSView = qt_mac_nativeview_for(widgetToGetMouse);
1321  windowPoint = [[theNSView window] convertScreenToBase:globalPoint];
1322  }
1323  NSPoint localPoint = [theNSView convertPoint:windowPoint fromView:nil];
1324  // Tablet events do not handle WA_TransparentForMouseEvents ATM
1325  // In theory, people who set the WA_TransparentForMouseEvents attribute won't handle
1326  // tablet events either in which case they will fall into the mouse event case and get
1327  // them passed on. This will NOT handle the raw events, but that might not be a big problem.
1328 
1329  const QMacTabletHash *tabletHash = qt_mac_tablet_hash();
1330  if (!tabletHash->contains([theTabletEvent deviceID])) {
1331  qWarning("QCocoaView handleTabletEvent: This tablet device is unknown"
1332  " (received no proximity event for it). Discarding event.");
1333  return false;
1334  }
1335  const QTabletDeviceData &deviceData = tabletHash->value([theTabletEvent deviceID]);
1336 
1337 
1338  QEvent::Type qType;
1339  switch (eventType) {
1340  case NSLeftMouseDown:
1341  case NSRightMouseDown:
1342  qType = QEvent::TabletPress;
1343  break;
1344  case NSLeftMouseUp:
1345  case NSRightMouseUp:
1346  qType = QEvent::TabletRelease;
1347  break;
1348  case NSMouseMoved:
1349  case NSTabletPoint:
1350  case NSLeftMouseDragged:
1351  case NSRightMouseDragged:
1352  default:
1353  qType = QEvent::TabletMove;
1354  break;
1355  }
1356 
1357  qreal pressure;
1358  if (eventType != NSMouseMoved) {
1359  pressure = [theTabletEvent pressure];
1360  } else {
1361  pressure = 0.0;
1362  }
1363 
1364  NSPoint tilt = [theTabletEvent tilt];
1365  int xTilt = qRound(tilt.x * 60.0);
1366  int yTilt = qRound(tilt.y * -60.0);
1367  qreal tangentialPressure = 0;
1368  qreal rotation = 0;
1369  int z = 0;
1370  if (deviceData.capabilityMask & 0x0200)
1371  z = [theTabletEvent absoluteZ];
1372 
1373  if (deviceData.capabilityMask & 0x0800)
1374  tangentialPressure = [theTabletEvent tangentialPressure];
1375 
1376  rotation = [theTabletEvent rotation];
1377  QPointF hiRes = flipPoint(globalPoint);
1378  QTabletEvent qtabletEvent(qType, QPoint(localPoint.x, localPoint.y),
1379  hiRes.toPoint(), hiRes,
1380  deviceData.tabletDeviceType, deviceData.tabletPointerType,
1381  pressure, xTilt, yTilt, tangentialPressure, rotation, z,
1382  qt_cocoaModifiers2QtModifiers([theTabletEvent modifierFlags]),
1383  deviceData.tabletUniqueID);
1384 
1385  qt_sendSpontaneousEvent(widgetToGetMouse, &qtabletEvent);
1386  return qtabletEvent.isAccepted();
1387 #endif
1388 }
1389 
1390 void qt_mac_updateContentBorderMetricts(void * /*OSWindowRef */window, const ::HIContentBorderMetrics &metrics)
1391 {
1392  OSWindowRef theWindow = static_cast<OSWindowRef>(window);
1393 #if !defined(QT_MAC_USE_COCOA)
1394 # if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1396  ::HIWindowSetContentBorderThickness(theWindow, &metrics);
1397  }
1398 # else
1399  Q_UNUSED(window);
1400  Q_UNUSED(metrics);
1401 # endif
1402 #else
1403  if ([theWindow styleMask] & NSTexturedBackgroundWindowMask)
1404  [theWindow setContentBorderThickness:metrics.top forEdge:NSMaxYEdge];
1405  [theWindow setContentBorderThickness:metrics.bottom forEdge:NSMinYEdge];
1406 #endif
1407 }
1408 
1409 #if QT_MAC_USE_COCOA
1410 void qt_mac_replaceDrawRect(void * /*OSWindowRef */window, QWidgetPrivate *widget)
1411 {
1413  OSWindowRef theWindow = static_cast<OSWindowRef>(window);
1414  if(!theWindow)
1415  return;
1416  id theClass = [[[theWindow contentView] superview] class];
1417  // What we do here is basically to add a new selector to NSThemeFrame called
1418  // "drawRectOriginal:" which will contain the original implementation of
1419  // "drawRect:". After that we get the new implementation from QCocoaWindow
1420  // and exchange them. The new implementation is called drawRectSpecial.
1421  // We cannot just add the method because it might have been added before and since
1422  // we cannot remove a method once it has been added we need to ask QCocoaWindow if
1423  // we did the swap or not.
1424  if(!widget->drawRectOriginalAdded) {
1425  Method m2 = class_getInstanceMethod(theClass, @selector(drawRect:));
1426  if(!m2) {
1427  // This case is pretty extreme, no drawRect means no drawing!
1428  return;
1429  }
1430  class_addMethod(theClass, @selector(drawRectOriginal:), method_getImplementation(m2), method_getTypeEncoding(m2));
1431  widget->drawRectOriginalAdded = true;
1432  }
1433  if(widget->originalDrawMethod) {
1434  Method m0 = class_getInstanceMethod([theWindow class], @selector(drawRectSpecial:));
1435  if(!m0) {
1436  // Ok, this means the methods were never swapped. Just ignore
1437  return;
1438  }
1439  Method m1 = class_getInstanceMethod(theClass, @selector(drawRect:));
1440  if(!m1) {
1441  // Ok, this means the methods were never swapped. Just ignore
1442  return;
1443  }
1444  // We have the original method here. Proceed and swap the methods.
1445  method_exchangeImplementations(m1, m0);
1446  widget->originalDrawMethod = false;
1447  [theWindow display];
1448  }
1449 }
1450 
1451 void qt_mac_replaceDrawRectOriginal(void * /*OSWindowRef */window, QWidgetPrivate *widget)
1452 {
1454  OSWindowRef theWindow = static_cast<OSWindowRef>(window);
1455  id theClass = [[[theWindow contentView] superview] class];
1456  // Now we need to revert the methods to their original state.
1457  // We cannot remove the method, so we just keep track of it in QCocoaWindow.
1458  Method m0 = class_getInstanceMethod([theWindow class], @selector(drawRectSpecial:));
1459  if(!m0) {
1460  // Ok, this means the methods were never swapped. Just ignore
1461  return;
1462  }
1463  Method m1 = class_getInstanceMethod(theClass, @selector(drawRect:));
1464  if(!m1) {
1465  // Ok, this means the methods were never swapped. Just ignore
1466  return;
1467  }
1468  method_exchangeImplementations(m1, m0);
1469  widget->originalDrawMethod = true;
1470  [theWindow display];
1471 }
1472 #endif // QT_MAC_USE_COCOA
1473 
1474 #if QT_MAC_USE_COCOA
1475 void qt_mac_showBaseLineSeparator(void * /*OSWindowRef */window, bool show)
1476 {
1477  if(!window)
1478  return;
1480  OSWindowRef theWindow = static_cast<OSWindowRef>(window);
1481  NSToolbar *macToolbar = [theWindow toolbar];
1482  [macToolbar setShowsBaselineSeparator:show];
1483 }
1484 #endif // QT_MAC_USE_COCOA
1485 
1487 {
1488  QStringList result;
1489  NSArray *array = static_cast<NSArray *>(nsarray);
1490  for (NSUInteger i=0; i<[array count]; ++i)
1491  result << qt_mac_NSStringToQString([array objectAtIndex:i]);
1492  return result;
1493 }
1494 
1496 {
1497  NSMutableArray *result = [NSMutableArray arrayWithCapacity:list.size()];
1498  for (int i=0; i<list.size(); ++i){
1499  [result addObject:reinterpret_cast<const NSString *>(QCFString::toCFStringRef(list[i]))];
1500  }
1501  return result;
1502 }
1503 
1504 #if QT_MAC_USE_COCOA
1505 void qt_syncCocoaTitleBarButtons(OSWindowRef window, QWidget *widgetForWindow)
1506 {
1507  if (!widgetForWindow)
1508  return;
1509 
1510  Qt::WindowFlags flags = widgetForWindow->windowFlags();
1511  bool customize = flags & Qt::CustomizeWindowHint;
1512 
1513  NSButton *btn = [window standardWindowButton:NSWindowZoomButton];
1514  // BOOL is not an int, so the bitwise AND doesn't work.
1515  bool go = uint(customize && !(flags & Qt::WindowMaximizeButtonHint)) == 0;
1516  [btn setEnabled:go];
1517 
1518  btn = [window standardWindowButton:NSWindowMiniaturizeButton];
1519  go = uint(customize && !(flags & Qt::WindowMinimizeButtonHint)) == 0;
1520  [btn setEnabled:go];
1521 
1522  btn = [window standardWindowButton:NSWindowCloseButton];
1523  go = uint(customize && !(flags & Qt::WindowSystemMenuHint
1524  || flags & Qt::WindowCloseButtonHint)) == 0;
1525  [btn setEnabled:go];
1526 
1527  [window setShowsToolbarButton:uint(flags & Qt::MacWindowToolBarButtonHint) != 0];
1528 }
1529 #endif // QT_MAC_USE_COCOA
1530 
1531 // Carbon: Make sure you call QDEndContext on the context when done with it.
1533 {
1534  if (!widget)
1535  return 0;
1536 
1537 #ifndef QT_MAC_USE_COCOA
1538  CGContextRef context;
1539  CGrafPtr port = GetWindowPort(qt_mac_window_for(widget));
1540  QDBeginCGContext(port, &context);
1541 #else
1542  CGContextRef context = (CGContextRef)[[NSGraphicsContext graphicsContextWithWindow:qt_mac_window_for(widget)] graphicsPort];
1543 #endif
1544  return context;
1545 }
1546 
1548 {
1549  if (!widget)
1550  return;
1551 #ifndef QT_MAC_USE_COCOA
1552  HIViewRender(qt_mac_nativeview_for(widget));
1553 #else
1554  [qt_mac_nativeview_for(widget) displayIfNeeded];
1555 #endif
1556 }
1557 
1559 {
1560 #ifndef QT_MAC_USE_COCOA
1561  return HIGetScaleFactor();
1562 #endif
1563 
1564 #if (MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_7)
1565  NSScreen *mainScreen = [NSScreen mainScreen];
1566  if ([mainScreen respondsToSelector:@selector(backingScaleFactor)])
1567  return [mainScreen backingScaleFactor];
1568 #endif
1569  return 1.0;
1570 }
1571 
1573 {
1575  NSPasteboard *pb = nil;
1576  CFStringRef pbname;
1577  if (PasteboardCopyName(paste, &pbname) == noErr) {
1578  pb = [NSPasteboard pasteboardWithName:const_cast<NSString *>(reinterpret_cast<const NSString *>(pbname))];
1579  CFRelease(pbname);
1580  } else {
1581  pb = [NSPasteboard generalPasteboard];
1582  }
1583  if (pb) {
1584  NSString *text = [pb stringForType:NSStringPboardType];
1585  if (text)
1586  return qt_mac_NSStringToQString(text);
1587  }
1588  return QString();
1589 }
1590 
1591 QPixmap qt_mac_convert_iconref(const IconRef icon, int width, int height)
1592 {
1593  QPixmap ret(width, height);
1594  ret.fill(QColor(0, 0, 0, 0));
1595 
1596  CGRect rect = CGRectMake(0, 0, width, height);
1597 
1599  CGAffineTransform old_xform = CGContextGetCTM(ctx);
1600  CGContextConcatCTM(ctx, CGAffineTransformInvert(old_xform));
1601  CGContextConcatCTM(ctx, CGAffineTransformIdentity);
1602 
1603  ::RGBColor b;
1604  b.blue = b.green = b.red = 255*255;
1605  PlotIconRefInContext(ctx, &rect, kAlignNone, kTransformNone, &b, kPlotIconRefNormalFlags, icon);
1606  CGContextRelease(ctx);
1607  return ret;
1608 }
1609 
1610 void qt_mac_constructQIconFromIconRef(const IconRef icon, const IconRef overlayIcon, QIcon *retIcon, QStyle::StandardPixmap standardIcon)
1611 {
1612  int size = 16;
1613  while (size <= 128) {
1614 
1615  const QString cacheKey = QLatin1String("qt_mac_constructQIconFromIconRef") + QString::number(standardIcon) + QString::number(size);
1616  QPixmap mainIcon;
1617  if (standardIcon >= QStyle::SP_CustomBase) {
1618  mainIcon = qt_mac_convert_iconref(icon, size, size);
1619  } else if (QPixmapCache::find(cacheKey, mainIcon) == false) {
1620  mainIcon = qt_mac_convert_iconref(icon, size, size);
1621  QPixmapCache::insert(cacheKey, mainIcon);
1622  }
1623 
1624  if (overlayIcon) {
1625  int littleSize = size / 2;
1626  QPixmap overlayPix = qt_mac_convert_iconref(overlayIcon, littleSize, littleSize);
1627  QPainter painter(&mainIcon);
1628  painter.drawPixmap(size - littleSize, size - littleSize, overlayPix);
1629  }
1630 
1631  retIcon->addPixmap(mainIcon);
1632  size += size; // 16 -> 32 -> 64 -> 128
1633  }
1634 }
1635 
1636 #ifdef QT_MAC_USE_COCOA
1637 void qt_mac_menu_collapseSeparators(void */*NSMenu **/ theMenu, bool collapse)
1638 {
1640  OSMenuRef menu = static_cast<OSMenuRef>(theMenu);
1641  if (collapse) {
1642  bool previousIsSeparator = true; // setting to true kills all the separators placed at the top.
1643  NSMenuItem *previousItem = nil;
1644 
1645  NSArray *itemArray = [menu itemArray];
1646  for (unsigned int i = 0; i < [itemArray count]; ++i) {
1647  NSMenuItem *item = reinterpret_cast<NSMenuItem *>([itemArray objectAtIndex:i]);
1648  if ([item isSeparatorItem]) {
1649  [item setHidden:previousIsSeparator];
1650  }
1651 
1652  if (![item isHidden]) {
1653  previousItem = item;
1654  previousIsSeparator = ([previousItem isSeparatorItem]);
1655  }
1656  }
1657 
1658  // We now need to check the final item since we don't want any separators at the end of the list.
1659  if (previousItem && previousIsSeparator)
1660  [previousItem setHidden:YES];
1661  } else {
1662  NSArray *itemArray = [menu itemArray];
1663  for (unsigned int i = 0; i < [itemArray count]; ++i) {
1664  NSMenuItem *item = reinterpret_cast<NSMenuItem *>([itemArray objectAtIndex:i]);
1665  if (QAction *action = reinterpret_cast<QAction *>([item tag]))
1666  [item setHidden:!action->isVisible()];
1667  }
1668  }
1669 }
1670 
1671 class CocoaPostMessageAfterEventLoopExitHelp : public QObject
1672 {
1673  id target;
1674  SEL selector;
1675  int argCount;
1676  id arg1;
1677  id arg2;
1678 public:
1679  CocoaPostMessageAfterEventLoopExitHelp(id target, SEL selector, int argCount, id arg1, id arg2)
1680  : target(target), selector(selector), argCount(argCount), arg1(arg1), arg2(arg2){
1681  deleteLater();
1682  }
1683 
1684  ~CocoaPostMessageAfterEventLoopExitHelp()
1685  {
1686  qt_cocoaPostMessage(target, selector, argCount, arg1, arg2);
1687  }
1688 };
1689 
1690 void qt_cocoaPostMessage(id target, SEL selector, int argCount, id arg1, id arg2)
1691 {
1692  // WARNING: data1 and data2 is truncated to from 64-bit to 32-bit on OS 10.5!
1693  // That is why we need to split the address in two parts:
1694  QCocoaPostMessageArgs *args = new QCocoaPostMessageArgs(target, selector, argCount, arg1, arg2);
1695  quint32 lower = quintptr(args);
1696  quint32 upper = quintptr(args) >> 32;
1697  NSEvent *e = [NSEvent otherEventWithType:NSApplicationDefined
1698  location:NSZeroPoint modifierFlags:0 timestamp:0 windowNumber:0
1699  context:nil subtype:QtCocoaEventSubTypePostMessage data1:lower data2:upper];
1700  [NSApp postEvent:e atStart:NO];
1701 }
1702 
1703 void qt_cocoaPostMessageAfterEventLoopExit(id target, SEL selector, int argCount, id arg1, id arg2)
1704 {
1705  if (QApplicationPrivate::instance()->threadData->eventLoops.size() <= 1)
1706  qt_cocoaPostMessage(target, selector, argCount, arg1, arg2);
1707  else
1708  new CocoaPostMessageAfterEventLoopExitHelp(target, selector, argCount, arg1, arg2);
1709 }
1710 
1711 #endif
1712 
1714 {
1715 #ifndef QT_MAC_USE_COCOA
1716  NSApplicationLoad();
1717 #endif
1718  pool = (void*)[[NSAutoreleasePool alloc] init];
1719 }
1720 
1722 {
1723  [(NSAutoreleasePool*)pool release];
1724 }
1725 
1727 {
1728 #ifdef QT_MAC_USE_COCOA
1730  qt_cocoaPostMessage([NSApp QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)], @selector(qtTranslateApplicationMenu));
1731 #endif
1732 }
1733 
1739 
1740 #ifdef QT_MAC_USE_COCOA
1741 // This method implements the magic for the drawRectSpecial method.
1742 // We draw a line at the upper edge of the content view in order to
1743 // override the title baseline.
1744 void macDrawRectOnTop(void * /*OSWindowRef */window)
1745 {
1746  OSWindowRef theWindow = static_cast<OSWindowRef>(window);
1747  NSView *contentView = [theWindow contentView];
1748  if(!contentView)
1749  return;
1750  // Get coordinates of the content view
1751  NSRect contentRect = [contentView frame];
1752  // Draw a line on top of the already drawn line.
1753  // We need to check if we are active or not to use the proper color.
1754  if([theWindow isKeyWindow] || [theWindow isMainWindow]) {
1755  [[NSColor colorWithCalibratedRed:1.0 green:1.0 blue:1.0 alpha:1.0] set];
1756  } else {
1757  [[NSColor colorWithCalibratedRed:1.0 green:1.0 blue:1.0 alpha:1.0] set];
1758  }
1759  NSPoint origin = NSMakePoint(0, contentRect.size.height);
1760  NSPoint end = NSMakePoint(contentRect.size.width, contentRect.size.height);
1761  [NSBezierPath strokeLineFromPoint:origin toPoint:end];
1762 }
1763 
1764 // This method will (or at least should) get called only once.
1765 // Its mission is to find out if we are active or not. If we are active
1766 // we assume that we were launched via finder, otherwise we assume
1767 // we were called from the command line. The distinction is important,
1768 // since in the first case we don't need to trigger a paintEvent, while
1769 // in the second case we do.
1770 void macSyncDrawingOnFirstInvocation(void * /*OSWindowRef */window)
1771 {
1772  OSWindowRef theWindow = static_cast<OSWindowRef>(window);
1773  NSApplication *application = [NSApplication sharedApplication];
1774  NSToolbar *toolbar = [theWindow toolbar];
1775  if([application isActive]) {
1776  // Launched from finder
1777  [toolbar setShowsBaselineSeparator:NO];
1778  } else {
1779  // Launched from commandline
1780  [toolbar setVisible:false];
1781  [toolbar setShowsBaselineSeparator:NO];
1782  [toolbar setVisible:true];
1783  [theWindow display];
1784  }
1785 }
1786 
1787 void qt_cocoaStackChildWindowOnTopOfOtherChildren(QWidget *childWidget)
1788 {
1789  if (!childWidget)
1790  return;
1791 
1792  QWidget *parent = childWidget->parentWidget();
1793  if (childWidget->isWindow() && parent) {
1794  if ([[qt_mac_window_for(parent) childWindows] containsObject:qt_mac_window_for(childWidget)]) {
1795  QWidgetPrivate *d = qt_widget_private(childWidget);
1796  d->setSubWindowStacking(false);
1797  d->setSubWindowStacking(true);
1798  }
1799  }
1800 }
1801 
1802 void qt_mac_display(QWidget *widget)
1803 {
1804  NSView *theNSView = qt_mac_nativeview_for(widget);
1805  [theNSView display];
1806 }
1807 
1808 void qt_mac_setNeedsDisplay(QWidget *widget)
1809 {
1810  NSView *theNSView = qt_mac_nativeview_for(widget);
1811  [theNSView setNeedsDisplay:YES];
1812 }
1813 
1814 void qt_mac_setNeedsDisplayInRect(QWidget *widget, QRegion region)
1815 {
1816  NSView *theNSView = qt_mac_nativeview_for(widget);
1817  if (region.isEmpty()) {
1818  [theNSView setNeedsDisplay:YES];
1819  return;
1820  }
1821 
1822  QVector<QRect> rects = region.rects();
1823  for (int i = 0; i < rects.count(); ++i) {
1824  const QRect &rect = rects.at(i);
1825  NSRect nsrect = NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height());
1826  [theNSView setNeedsDisplayInRect:nsrect];
1827  }
1828 
1829 }
1830 
1831 #endif // QT_MAC_USE_COCOA
1832 
static QString number(int, int base=10)
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition: qstring.cpp:6448
The QPainter class performs low-level painting on widgets and other paint devices.
Definition: qpainter.h:86
The QColor class provides colors based on RGB, HSV or CMYK values.
Definition: qcolor.h:67
double d
Definition: qnumeric_p.h:62
const struct __CFString * CFStringRef
QWidget * parentWidget() const
Returns the parent of this widget, or 0 if it does not have any parent widget.
Definition: qwidget.h:1035
void qt_mac_post_retranslateAppMenu()
QWidget * focusWidget() const
Returns the last child of this widget that setFocus had been called on.
Definition: qwidget.cpp:6863
float m_duration
Definition: qt_mac_p.h:130
int type
Definition: qmetatype.cpp:239
double qreal
Definition: qglobal.h:1193
QIntegerForSizeof< void * >::Unsigned quintptr
Definition: qglobal.h:986
static mach_timebase_info_data_t info
void addPixmap(const QPixmap &pixmap, Mode mode=Normal, State state=Off)
Adds pixmap to the icon, as a specialization for mode and state.
Definition: qicon.cpp:814
#define QT_END_NAMESPACE
This macro expands to.
Definition: qglobal.h:90
EventRef event
QPointer< QWidget > widget
int remove(const Key &key)
Removes all the items that have the key from the hash.
Definition: qhash.h:784
static void keyEvent(KeyAction action, QWidget *widget, char ascii, Qt::KeyboardModifiers modifier=Qt::NoModifier, int delay=-1)
Qt::MouseButton qt_mac_get_button(EventMouseButton button)
ushort unicode() const
This is an overloaded member function, provided for convenience. It differs from the above function o...
Definition: qchar.h:251
int flipYCoordinate(int y)
bool isWindow() const
Returns true if the widget is an independent window, otherwise returns false.
Definition: qwidget.h:945
int count(const T &t) const
Returns the number of occurrences of value in the vector.
Definition: qvector.h:742
NSDragOperation mac_code
void qt_dispatchTabletProximityEvent(const ::TabletProximityRec &proxRec)
The QContextMenuEvent class contains parameters that describe a context menu event.
Definition: qevent.h:396
WId effectiveWinId() const
Returns the effective window system identifier of the widget, i.
Definition: qwidget.cpp:2654
bool isVisible() const
Definition: qwidget.h:1005
PasteboardRef OSPasteboardRef
bool operator<(const KeyPair &entry, QChar qchar)
QPixmap qt_mac_convert_iconref(const IconRef icon, int width, int height)
const UInt32 kWidgetCreatorQt
Definition: qwidget_mac.mm:148
CGFloat qt_mac_get_scalefactor()
#define SLOT(a)
Definition: qobjectdefs.h:226
The QPointF class defines a point in the plane using floating point precision.
Definition: qpoint.h:214
static Qt::MouseButtons buttons
void macWindowFlush(void *window)
The QWidget class is the base class of all user interface objects.
Definition: qwidget.h:150
static CFStringRef toCFStringRef(const QString &str)
Definition: qcore_mac.cpp:69
static QString toQString(CFStringRef cfstr)
Definition: qcore_mac.cpp:47
QString qt_mac_get_pasteboardString(OSPasteboardRef paste)
int width() const
Returns the width of the rectangle.
Definition: qrect.h:303
OSViewRef qt_mac_effectiveview_for(const QWidget *w)
Definition: qwidget_mac.mm:424
struct CGImage * CGImageRef
QLatin1String(DBUS_INTERFACE_DBUS))) Q_GLOBAL_STATIC_WITH_ARGS(QString
bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event)
static QApplicationPrivate * instance()
void * qt_mac_create_nsimage(const QPixmap &pm)
void qt_mac_update_mouseTracking(QWidget *widget)
void qt_mac_dispatchPendingUpdateRequests(QWidget *widget)
Q_OUTOFLINE_TEMPLATE RandomAccessIterator qBinaryFind(RandomAccessIterator begin, RandomAccessIterator end, const T &value)
Definition: qalgorithms.h:295
int count(const T &t) const
Returns the number of occurrences of value in the list.
Definition: qlist.h:891
static qt_mac_enum_mapper qt_mac_mouse_symbols[]
int height() const
Returns the height of the rectangle.
Definition: qrect.h:306
QPointF flipPoint(const NSPoint &p)
The QString class provides a Unicode character string.
Definition: qstring.h:83
QPointer< QWidget > qt_last_mouse_receiver
Q_GLOBAL_STATIC(QMacWindowFader, macwindowFader)
The QHash class is a template class that provides a hash-table-based dictionary.
Definition: qdatastream.h:66
void updateKeyMap(const MSG &msg)
Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum)
void macWindowToolbarSet(void *window, void *toolbarRef)
#define Q_ASSERT(cond)
Definition: qglobal.h:1823
The QVector class is a template class that provides a dynamic array.
Definition: qdatastream.h:64
The QObject class is the base class of all Qt objects.
Definition: qobject.h:111
CGContextRef qt_mac_graphicsContextFor(QWidget *widget)
bool contains(const Key &key) const
Returns true if the hash contains an item with the key; otherwise returns false.
Definition: qhash.h:872
The QChar class provides a 16-bit Unicode character.
Definition: qchar.h:72
bool macWindowToolbarIsVisible(void *window)
NSToolbar * toolbar
const T value(const Key &key) const
Returns the value associated with the key.
Definition: qhash.h:606
QMacTabletHash * qt_mac_tablet_hash()
Q_DECL_CONSTEXPR const T & qMax(const T &a, const T &b)
Definition: qglobal.h:1217
StandardPixmap
This enum describes the available standard pixmaps.
Definition: qstyle.h:755
Qt::KeyboardModifiers qt_cocoaModifiers2QtModifiers(ulong modifierFlags)
static QPixmap * find(const QString &key)
bool isLower() const
Returns true if the character is a lowercase letter, i.
Definition: qchar.h:272
qreal x() const
Returns the x-coordinate of this point.
Definition: qpoint.h:282
iterator insert(const Key &key, const T &value)
Inserts a new item with the key and a value of value.
Definition: qhash.h:753
iterator end()
Returns an STL-style iterator pointing to the imaginary item after the last item in the vector...
Definition: qvector.h:250
OSWindowRef qt_mac_window_for(const QWidget *)
Definition: qwidget_mac.mm:484
void macSendToolbarChangeEvent(QWidget *widget)
static QWidgetPrivate * _target
void NSMenuItem
Definition: qmenu_p.h:80
static const KeyPair entries[NumEntries]
static bool qtKey2CocoaKeySortLessThan(const KeyPair &entry1, const KeyPair &entry2)
Q_CORE_EXPORT void qDebug(const char *,...)
static QWidget * widgetAt(const QPoint &p)
Returns the widget at global screen position point, or 0 if there is no Qt widget there...
Qt::DropAction qt_code
NSWindow * window
void qt_dispatchModifiersChanged(void *flagsChangedEvent, QWidget *widgetToGetEvent)
void append(const T &t)
Inserts value at the end of the list.
Definition: qlist.h:507
#define QT_BEGIN_NAMESPACE
This macro expands to.
Definition: qglobal.h:89
static QMacWindowFader * currentFader()
QWidget * nativeParentWidget() const
Returns the native parent for this widget, i.
Definition: qwidget.cpp:4514
void macWindowSetHasShadow(void *window, bool hasShadow)
Q_GUI_EXPORT EGLDisplay display()
Definition: qegl.cpp:589
bool isAccepted() const
Definition: qcoreevent.h:307
void qt_mac_replaceDrawRectOriginal(void *window, QWidgetPrivate *widget)
WindowRef OSWindowRef
void * qt_mac_QStringListToNSMutableArrayVoid(const QStringList &list)
static QWidget * mouseGrabber()
Returns the widget that is currently grabbing the mouse input.
bool isEmpty() const
Returns true if the region is empty; otherwise returns false.
Definition: qregion.cpp:4098
#define qApp
static bool init
CGContextRef qt_mac_cg_context(const QPaintDevice *pdev)
Returns the CoreGraphics CGContextRef of the paint device.
QWidget * childAt(int x, int y) const
Returns the visible child widget at the position ({x}, {y}) in the widget&#39;s coordinate system...
Definition: qwidget.h:934
#define QT_MAC_MAP_ENUM(x)
void setFadeDuration(float durationInSecs)
Definition: qt_mac_p.h:136
const T & at(int i) const
Returns the item at index position i in the list.
Definition: qlist.h:468
struct OpaqueControlRef * HIViewRef
The QStringList class provides a list of strings.
Definition: qstringlist.h:66
QWidget * mac_mouse_grabber
Definition: qwidget_mac.mm:156
void updateFrameStrut()
Computes the frame rectangle when needed.
Q_CORE_EXPORT void qWarning(const char *,...)
unsigned int uint
Definition: qglobal.h:996
bool macWindowIsTextured(void *window)
bool qt_mac_handleTabletEvent(void *view, void *tabletEvent)
bool translateKeyEvent(QWidget *receiver, const MSG &msg, bool grab)
bool qt_mac_sendMacEventToWidget(QWidget *widget, EventRef ref)
Definition: qwidget_mac.mm:448
QChar toUpper() const
Returns the uppercase equivalent if the character is lowercase or titlecase; otherwise returns the ch...
Definition: qchar.cpp:1287
The QRegion class specifies a clip region for a painter.
Definition: qregion.h:68
DropAction
Definition: qnamespace.h:1597
bool operator==(const KeyPair &entry, QChar qchar)
void clear()
Removes all items from the list.
Definition: qlist.h:764
bool qt_dispatchKeyEvent(void *keyEvent, QWidget *widgetToGetEvent)
QWidgetList m_windowsToFade
Definition: qt_mac_p.h:129
unsigned long ulong
Definition: qglobal.h:997
signed long OSStatus
void registerWindowToFade(QWidget *window)
void qSort(RandomAccessIterator start, RandomAccessIterator end)
Definition: qalgorithms.h:177
bool contains(const QPoint &p, bool proper=false) const
Returns true if the given point is inside or on the edge of the rectangle, otherwise returns false...
Definition: qrect.cpp:1101
struct OpaqueEventRef * EventRef
MenuRef OSMenuRef
The QTabletEvent class contains parameters that describe a Tablet event.
Definition: qevent.h:179
const T & at(int i) const
Returns the item at index position i in the vector.
Definition: qvector.h:350
QApplication * qAppInstance()
Qt::KeyboardModifiers qt_cocoaDragOperation2QtModifiers(uint dragOperations)
The QMouseEvent class contains parameters that describe a mouse event.
Definition: qevent.h:85
void qt_mac_replaceDrawRect(void *window, QWidgetPrivate *widget)
void fill(const QColor &fillColor=Qt::white)
Fills the pixmap with the given color.
Definition: qpixmap.cpp:1080
struct CGRect CGRect
static QWidget * activePopupWidget()
Returns the active popup widget.
static const int NumEntries
Type
This enum type defines the valid event types in Qt.
Definition: qcoreevent.h:62
static bool isBlockedByModal(QWidget *widget)
Returns true if widget is blocked by a modal window.
iterator begin()
Returns an STL-style iterator pointing to the first item in the vector.
Definition: qvector.h:247
QRect rect
the internal geometry of the widget excluding any window frame
Definition: qwidget.h:168
int y() const
Returns the y-coordinate of the rectangle&#39;s top edge.
Definition: qrect.h:255
void qt_mac_updateCursorWithWidgetUnderMouse(QWidget *widgetUnderMouse)
Definition: qcursor_mac.mm:144
QPoint toPoint() const
Rounds the coordinates of this point to the nearest integer, and returns a QPoint object with the rou...
Definition: qpoint.h:376
#define QT_MANGLE_NAMESPACE(name)
Definition: qglobal.h:106
int x() const
Returns the x-coordinate of the rectangle&#39;s left edge.
Definition: qrect.h:252
QPointer< QWidget > qt_last_native_mouse_receiver
#define ctx
Definition: qgl.cpp:6094
struct CGPoint NSPoint
static bool insert(const QString &key, const QPixmap &pixmap)
Inserts a copy of the pixmap pixmap associated with the key into the cache.
static QTestResult::TestLocation location
Definition: qtestresult.cpp:63
int key
The QPoint class defines a point in the plane using integer precision.
Definition: qpoint.h:53
bool singleShot
This static function calls a slot after a given time interval.
Definition: qtimer.h:59
QVector< QRect > rects() const
Returns an array of non-overlapping rectangles that make up the region.
Definition: qregion.cpp:4412
Qt::MouseButtons qt_mac_get_buttons(int buttons)
const UInt32 kEventClassQt
Definition: qt_mac_p.h:92
unsigned int quint32
Definition: qglobal.h:938
int size() const
Returns the number of items in the list.
Definition: qlist.h:137
OSStatus qt_mac_drawCGImage(CGContextRef inContext, const CGRect *inBounds, CGImageRef inImage)
void macWindowToolbarShow(const QWidget *widget, bool show)
bool isAncestorOf(const QWidget *child) const
Returns true if this widget is a parent, (or grandparent and so on to any level), of the given child...
Definition: qwidget.cpp:8573
The QRect class defines a rectangle in the plane using integer precision.
Definition: qrect.h:58
void qt_mac_constructQIconFromIconRef(const IconRef icon, const IconRef overlayIcon, QIcon *retIcon, QStyle::StandardPixmap standardIcon)
OSViewRef qt_mac_nativeview_for(const QWidget *)
Definition: qwidget_mac.mm:419
QChar qtKey2CocoaKey(Qt::Key key)
WId internalWinId() const
Returns the window system identifier of the widget, or 0 if the widget is not created yet...
Definition: qwidget.h:244
static void dispatchEnterLeave(QWidget *enter, QWidget *leave)
int y() const
Returns the y coordinate of this point.
Definition: qpoint.h:131
The QToolBarChangeEvent class provides an event that is sent whenever a the toolbar button is clicked...
Definition: qevent.h:662
qreal y() const
Returns the y-coordinate of this point.
Definition: qpoint.h:287
QPoint mapFromGlobal(const QPoint &) const
Translates the global screen coordinate pos to widget coordinates.
QWidget * window() const
Returns the window for this widget, i.e.
Definition: qwidget.cpp:4492
The QPixmap class is an off-screen image representation that can be used as a paint device...
Definition: qpixmap.h:71
void qt_mac_showBaseLineSeparator(void *window, bool show)
void qt_syncCocoaTitleBarButtons(OSWindowRef window, QWidget *widgetForWindow)
void drawPixmap(const QRectF &targetRect, const QPixmap &pixmap, const QRectF &sourceRect)
Draws the rectangular portion source of the given pixmap into the given target in the paint device...
Definition: qpainter.cpp:5619
QKeyMapperPrivate * qt_keymapper_private()
Definition: qkeymapper.cpp:113
static const MacVersion MacintoshVersion
the version of the Macintosh operating system on which the application is run (Mac only)...
Definition: qglobal.h:1646
static Qt::MouseButtons mouseButtons()
Returns the current state of the buttons on the mouse.
WId winId() const
Returns the window system identifier of the widget.
Definition: qwidget.cpp:2557
void qt_mac_send_modifiers_changed(quint32, QObject *)
int x() const
Returns the x coordinate of this point.
Definition: qpoint.h:128
struct CGContext * CGContextRef
Qt::WindowFlags windowFlags() const
Window flags are a combination of a type (e.
Definition: qwidget.h:939
Q_GUI_EXPORT QWidgetPrivate * qt_widget_private(QWidget *widget)
Definition: qwidget.cpp:12920
QWidget * qt_button_down
static QString qtKey(CFStringRef cfkey)
HIViewRef OSViewRef
CGImageRef toMacCGImageRef() const
Creates a CGImageRef equivalent to the QPixmap.
static const KeyPair *const end
bool qt_mac_checkForNativeSizeGrip(const QWidget *widget)
The QTableWidgetItem class provides an item for use with the QTableWidget class.
Definition: qtablewidget.h:82
static bool sendMouseEvent(QWidget *receiver, QMouseEvent *event, QWidget *alienWidget, QWidget *native, QWidget **buttonDown, QPointer< QWidget > &lastMouseReceiver, bool spontaneous=true)
The QEvent class is the base class of all event classes.
Definition: qcoreevent.h:56
#define Q_UNUSED(x)
Indicates to the compiler that the parameter with the specified name is not used in the body of a fun...
Definition: qglobal.h:1729
QStringList qt_mac_NSArrayToQStringList(void *nsarray)
Q_DECL_CONSTEXPR int qRound(qreal d)
Definition: qglobal.h:1203
The QAction class provides an abstract user interface action that can be inserted into widgets...
Definition: qaction.h:64
#define text
Definition: qobjectdefs.h:80
qt_mac_getTargetForMouseEvent(event, QEvent::Gesture, qlocal, qglobal, 0, &widgetToGetTouch)
void qt_mac_updateContentBorderMetricts(void *window, const ::HIContentBorderMetrics &metrics)
struct OpaqueIconRef * IconRef
The QList class is a template class that provides lists.
Definition: qdatastream.h:62
float CGFloat
void macWindowFade(void *window, float durationSeconds)
MouseButton
Definition: qnamespace.h:150
The QIcon class provides scalable icons in different modes and states.
Definition: qicon.h:60