source: trunk/src/gui/kernel/qt_cocoa_helpers_mac.mm@ 890

Last change on this file since 890 was 846, checked in by Dmitry A. Kuminov, 15 years ago

trunk: Merged in qt 4.7.2 sources from branches/vendor/nokia/qt.

File size: 57.4 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
4** All rights reserved.
5** Contact: Nokia Corporation ([email protected])
6**
7** This file is part of the QtGui module of the Qt Toolkit.
8**
9** $QT_BEGIN_LICENSE:LGPL$
10** Commercial Usage
11** Licensees holding valid Qt Commercial licenses may use this file in
12** accordance with the Qt Commercial License Agreement provided with the
13** Software or, alternatively, in accordance with the terms contained in
14** a written agreement between you and Nokia.
15**
16** GNU Lesser General Public License Usage
17** Alternatively, this file may be used under the terms of the GNU Lesser
18** General Public License version 2.1 as published by the Free Software
19** Foundation and appearing in the file LICENSE.LGPL included in the
20** packaging of this file. Please review the following information to
21** ensure the GNU Lesser General Public License version 2.1 requirements
22** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
23**
24** In addition, as a special exception, Nokia gives you certain additional
25** rights. These rights are described in the Nokia Qt LGPL Exception
26** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
27**
28** GNU General Public License Usage
29** Alternatively, this file may be used under the terms of the GNU
30** General Public License version 3.0 as published by the Free Software
31** Foundation and appearing in the file LICENSE.GPL included in the
32** packaging of this file. Please review the following information to
33** ensure the GNU General Public License version 3.0 requirements will be
34** met: http://www.gnu.org/copyleft/gpl.html.
35**
36** If you have questions regarding the use of this file, please contact
37** Nokia at [email protected].
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 <private/qevent_p.h>
83#include <private/qt_cocoa_helpers_mac_p.h>
84#include <private/qt_mac_p.h>
85#include <private/qapplication_p.h>
86#include <private/qcocoaapplication_mac_p.h>
87#include <private/qcocoawindow_mac_p.h>
88#include <private/qcocoaview_mac_p.h>
89#include <private/qkeymapper_p.h>
90#include <private/qwidget_p.h>
91
92QT_BEGIN_NAMESPACE
93
94Q_GLOBAL_STATIC(QMacWindowFader, macwindowFader);
95
96QMacWindowFader::QMacWindowFader()
97 : m_duration(0.250)
98{
99}
100
101QMacWindowFader *QMacWindowFader::currentFader()
102{
103 return macwindowFader();
104}
105
106void QMacWindowFader::registerWindowToFade(QWidget *window)
107{
108 m_windowsToFade.append(window);
109}
110
111void QMacWindowFader::performFade()
112{
113 const QWidgetList myWidgetsToFade = m_windowsToFade;
114 const int widgetCount = myWidgetsToFade.count();
115#if QT_MAC_USE_COCOA
116 QMacCocoaAutoReleasePool pool;
117 [NSAnimationContext beginGrouping];
118 [[NSAnimationContext currentContext] setDuration:NSTimeInterval(m_duration)];
119#endif
120
121 for (int i = 0; i < widgetCount; ++i) {
122 QWidget *widget = m_windowsToFade.at(i);
123 OSWindowRef window = qt_mac_window_for(widget);
124#if QT_MAC_USE_COCOA
125 [[window animator] setAlphaValue:0.0];
126 QTimer::singleShot(qRound(m_duration * 1000), widget, SLOT(hide()));
127#else
128 TransitionWindowOptions options = {0, m_duration, 0, 0};
129 TransitionWindowWithOptions(window, kWindowFadeTransitionEffect, kWindowHideTransitionAction,
130 0, 1, &options);
131#endif
132 }
133#if QT_MAC_USE_COCOA
134 [NSAnimationContext endGrouping];
135#endif
136 m_duration = 0.250;
137 m_windowsToFade.clear();
138}
139
140extern bool qt_sendSpontaneousEvent(QObject *receiver, QEvent *event); // qapplication.cpp;
141extern QWidget * mac_mouse_grabber;
142extern QWidget *qt_button_down; //qapplication_mac.cpp
143
144void macWindowFade(void * /*OSWindowRef*/ window, float durationSeconds)
145{
146#ifdef QT_MAC_USE_COCOA
147 QMacCocoaAutoReleasePool pool;
148#endif
149 OSWindowRef wnd = static_cast<OSWindowRef>(window);
150 if (wnd) {
151 QWidget *widget;
152#if QT_MAC_USE_COCOA
153 widget = [wnd QT_MANGLE_NAMESPACE(qt_qwidget)];
154#else
155 const UInt32 kWidgetCreatorQt = kEventClassQt;
156 enum {
157 kWidgetPropertyQWidget = 'QWId' //QWidget *
158 };
159 if (GetWindowProperty(static_cast<WindowRef>(window), kWidgetCreatorQt, kWidgetPropertyQWidget, sizeof(widget), 0, &widget) != noErr)
160 widget = 0;
161#endif
162 if (widget) {
163 QMacWindowFader::currentFader()->setFadeDuration(durationSeconds);
164 QMacWindowFader::currentFader()->registerWindowToFade(widget);
165 QMacWindowFader::currentFader()->performFade();
166 }
167 }
168}
169
170bool macWindowIsTextured( void * /*OSWindowRef*/ window )
171{
172 OSWindowRef wnd = static_cast<OSWindowRef>(window);
173#if QT_MAC_USE_COCOA
174 return ( [wnd styleMask] & NSTexturedBackgroundWindowMask ) ? true : false;
175#else
176 WindowAttributes currentAttributes;
177 GetWindowAttributes(wnd, &currentAttributes);
178 return (currentAttributes & kWindowMetalAttribute) ? true : false;
179#endif
180}
181
182void macWindowToolbarShow(const QWidget *widget, bool show )
183{
184 OSWindowRef wnd = qt_mac_window_for(widget);
185#if QT_MAC_USE_COCOA
186 if (NSToolbar *toolbar = [wnd toolbar]) {
187 QMacCocoaAutoReleasePool pool;
188 if (show != [toolbar isVisible]) {
189 [toolbar setVisible:show];
190 } else {
191 // The toolbar may be in sync, but we are not, update our framestrut.
192 qt_widget_private(const_cast<QWidget *>(widget))->updateFrameStrut();
193 }
194 }
195#else
196 qt_widget_private(const_cast<QWidget *>(widget))->updateFrameStrut();
197 ShowHideWindowToolbar(wnd, show, false);
198#endif
199}
200
201
202void macWindowToolbarSet( void * /*OSWindowRef*/ window, void *toolbarRef )
203{
204 OSWindowRef wnd = static_cast<OSWindowRef>(window);
205#if QT_MAC_USE_COCOA
206 [wnd setToolbar:static_cast<NSToolbar *>(toolbarRef)];
207#else
208 SetWindowToolbar(wnd, static_cast<HIToolbarRef>(toolbarRef));
209#endif
210}
211
212bool macWindowToolbarIsVisible( void * /*OSWindowRef*/ window )
213{
214 OSWindowRef wnd = static_cast<OSWindowRef>(window);
215#if QT_MAC_USE_COCOA
216 if (NSToolbar *toolbar = [wnd toolbar])
217 return [toolbar isVisible];
218 return false;
219#else
220 return IsWindowToolbarVisible(wnd);
221#endif
222}
223
224void macWindowSetHasShadow( void * /*OSWindowRef*/ window, bool hasShadow )
225{
226 OSWindowRef wnd = static_cast<OSWindowRef>(window);
227#if QT_MAC_USE_COCOA
228 [wnd setHasShadow:BOOL(hasShadow)];
229#else
230 if (hasShadow)
231 ChangeWindowAttributes(wnd, 0, kWindowNoShadowAttribute);
232 else
233 ChangeWindowAttributes(wnd, kWindowNoShadowAttribute, 0);
234#endif
235}
236
237void macWindowFlush(void * /*OSWindowRef*/ window)
238{
239 OSWindowRef wnd = static_cast<OSWindowRef>(window);
240#if QT_MAC_USE_COCOA
241 [wnd flushWindowIfNeeded];
242#else
243 HIWindowFlush(wnd);
244#endif
245}
246
247void * /*NSImage */qt_mac_create_nsimage(const QPixmap &pm)
248{
249 QMacCocoaAutoReleasePool pool;
250 if(QCFType<CGImageRef> image = pm.toMacCGImageRef()) {
251 NSImage *newImage = 0;
252 NSRect imageRect = NSMakeRect(0.0, 0.0, CGImageGetWidth(image), CGImageGetHeight(image));
253 newImage = [[NSImage alloc] initWithSize:imageRect.size];
254 [newImage lockFocus];
255 {
256 CGContextRef imageContext = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
257 CGContextDrawImage(imageContext, *(CGRect*)&imageRect, image);
258 }
259 [newImage unlockFocus];
260 return newImage;
261 }
262 return 0;
263}
264
265void qt_mac_update_mouseTracking(QWidget *widget)
266{
267#ifdef QT_MAC_USE_COCOA
268 [qt_mac_nativeview_for(widget) updateTrackingAreas];
269#else
270 Q_UNUSED(widget);
271#endif
272}
273
274OSStatus qt_mac_drawCGImage(CGContextRef inContext, const CGRect *inBounds, CGImageRef inImage)
275{
276 // Verbatim copy if HIViewDrawCGImage (as shown on Carbon-Dev)
277 OSStatus err = noErr;
278
279 require_action(inContext != NULL, InvalidContext, err = paramErr);
280 require_action(inBounds != NULL, InvalidBounds, err = paramErr);
281 require_action(inImage != NULL, InvalidImage, err = paramErr);
282
283 CGContextSaveGState( inContext );
284 CGContextTranslateCTM (inContext, 0, inBounds->origin.y + CGRectGetMaxY(*inBounds));
285 CGContextScaleCTM(inContext, 1, -1);
286
287 CGContextDrawImage(inContext, *inBounds, inImage);
288
289 CGContextRestoreGState(inContext);
290InvalidImage:
291InvalidBounds:
292InvalidContext:
293 return err;
294}
295
296bool qt_mac_checkForNativeSizeGrip(const QWidget *widget)
297{
298#ifndef QT_MAC_USE_COCOA
299 OSViewRef nativeSizeGrip = 0;
300 HIViewFindByID(HIViewGetRoot(HIViewGetWindow(HIViewRef(widget->winId()))), kHIViewWindowGrowBoxID, &nativeSizeGrip);
301 return (nativeSizeGrip != 0);
302#else
303 return [[reinterpret_cast<NSView *>(widget->winId()) window] showsResizeIndicator];
304#endif
305}
306struct qt_mac_enum_mapper
307{
308 int mac_code;
309 int qt_code;
310#if defined(DEBUG_MOUSE_MAPS)
311# define QT_MAC_MAP_ENUM(x) x, #x
312 const char *desc;
313#else
314# define QT_MAC_MAP_ENUM(x) x
315#endif
316};
317
318//mouse buttons
319static qt_mac_enum_mapper qt_mac_mouse_symbols[] = {
320{ kEventMouseButtonPrimary, QT_MAC_MAP_ENUM(Qt::LeftButton) },
321{ kEventMouseButtonSecondary, QT_MAC_MAP_ENUM(Qt::RightButton) },
322{ kEventMouseButtonTertiary, QT_MAC_MAP_ENUM(Qt::MidButton) },
323{ 4, QT_MAC_MAP_ENUM(Qt::XButton1) },
324{ 5, QT_MAC_MAP_ENUM(Qt::XButton2) },
325{ 0, QT_MAC_MAP_ENUM(0) }
326};
327Qt::MouseButtons qt_mac_get_buttons(int buttons)
328{
329#ifdef DEBUG_MOUSE_MAPS
330 qDebug("Qt: internal: **Mapping buttons: %d (0x%04x)", buttons, buttons);
331#endif
332 Qt::MouseButtons ret = Qt::NoButton;
333 for(int i = 0; qt_mac_mouse_symbols[i].qt_code; i++) {
334 if (buttons & (0x01<<(qt_mac_mouse_symbols[i].mac_code-1))) {
335#ifdef DEBUG_MOUSE_MAPS
336 qDebug("Qt: internal: got button: %s", qt_mac_mouse_symbols[i].desc);
337#endif
338 ret |= Qt::MouseButtons(qt_mac_mouse_symbols[i].qt_code);
339 }
340 }
341 return ret;
342}
343Qt::MouseButton qt_mac_get_button(EventMouseButton button)
344{
345#ifdef DEBUG_MOUSE_MAPS
346 qDebug("Qt: internal: **Mapping button: %d (0x%04x)", button, button);
347#endif
348 Qt::MouseButtons ret = 0;
349 for(int i = 0; qt_mac_mouse_symbols[i].qt_code; i++) {
350 if (button == qt_mac_mouse_symbols[i].mac_code) {
351#ifdef DEBUG_MOUSE_MAPS
352 qDebug("Qt: internal: got button: %s", qt_mac_mouse_symbols[i].desc);
353#endif
354 return Qt::MouseButton(qt_mac_mouse_symbols[i].qt_code);
355 }
356 }
357 return Qt::NoButton;
358}
359
360void macSendToolbarChangeEvent(QWidget *widget)
361{
362 QToolBarChangeEvent ev(!(GetCurrentKeyModifiers() & cmdKey));
363 qt_sendSpontaneousEvent(widget, &ev);
364}
365
366Q_GLOBAL_STATIC(QMacTabletHash, tablet_hash)
367QMacTabletHash *qt_mac_tablet_hash()
368{
369 return tablet_hash();
370}
371
372#ifdef QT_MAC_USE_COCOA
373
374// Clears the QWidget pointer that each QCocoaView holds.
375void qt_mac_clearCocoaViewQWidgetPointers(QWidget *widget)
376{
377 QT_MANGLE_NAMESPACE(QCocoaView) *cocoaView = reinterpret_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(qt_mac_nativeview_for(widget));
378 if (cocoaView && [cocoaView respondsToSelector:@selector(qt_qwidget)]) {
379 [cocoaView qt_clearQWidget];
380 }
381}
382
383void qt_dispatchTabletProximityEvent(void * /*NSEvent * */ tabletEvent)
384{
385 NSEvent *proximityEvent = static_cast<NSEvent *>(tabletEvent);
386 // simply construct a Carbon proximity record and handle it all in one spot.
387 TabletProximityRec carbonProximityRec = { [proximityEvent vendorID],
388 [proximityEvent tabletID],
389 [proximityEvent pointingDeviceID],
390 [proximityEvent deviceID],
391 [proximityEvent systemTabletID],
392 [proximityEvent vendorPointingDeviceType],
393 [proximityEvent pointingDeviceSerialNumber],
394 [proximityEvent uniqueID],
395 [proximityEvent capabilityMask],
396 [proximityEvent pointingDeviceType],
397 [proximityEvent isEnteringProximity] };
398 qt_dispatchTabletProximityEvent(carbonProximityRec);
399}
400#endif // QT_MAC_USE_COCOA
401
402void qt_dispatchTabletProximityEvent(const ::TabletProximityRec &proxRec)
403{
404 QTabletDeviceData proximityDevice;
405 proximityDevice.tabletUniqueID = proxRec.uniqueID;
406 proximityDevice.capabilityMask = proxRec.capabilityMask;
407
408 switch (proxRec.pointerType) {
409 case NSUnknownPointingDevice:
410 default:
411 proximityDevice.tabletPointerType = QTabletEvent::UnknownPointer;
412 break;
413 case NSPenPointingDevice:
414 proximityDevice.tabletPointerType = QTabletEvent::Pen;
415 break;
416 case NSCursorPointingDevice:
417 proximityDevice.tabletPointerType = QTabletEvent::Cursor;
418 break;
419 case NSEraserPointingDevice:
420 proximityDevice.tabletPointerType = QTabletEvent::Eraser;
421 break;
422 }
423 uint bits = proxRec.vendorPointerType;
424 if (bits == 0 && proximityDevice.tabletUniqueID != 0) {
425 // Fallback. It seems that the driver doesn't always include all the information.
426 // High-End Wacom devices store their "type" in the uper bits of the Unique ID.
427 // I'm not sure how to handle it for consumer devices, but I'll test that in a bit.
428 bits = proximityDevice.tabletUniqueID >> 32;
429 }
430 // Defined in the "EN0056-NxtGenImpGuideX"
431 // on Wacom's Developer Website (www.wacomeng.com)
432 if (((bits & 0x0006) == 0x0002) && ((bits & 0x0F06) != 0x0902)) {
433 proximityDevice.tabletDeviceType = QTabletEvent::Stylus;
434 } else {
435 switch (bits & 0x0F06) {
436 case 0x0802:
437 proximityDevice.tabletDeviceType = QTabletEvent::Stylus;
438 break;
439 case 0x0902:
440 proximityDevice.tabletDeviceType = QTabletEvent::Airbrush;
441 break;
442 case 0x0004:
443 proximityDevice.tabletDeviceType = QTabletEvent::FourDMouse;
444 break;
445 case 0x0006:
446 proximityDevice.tabletDeviceType = QTabletEvent::Puck;
447 break;
448 case 0x0804:
449 proximityDevice.tabletDeviceType = QTabletEvent::RotationStylus;
450 break;
451 default:
452 proximityDevice.tabletDeviceType = QTabletEvent::NoDevice;
453 }
454 }
455 // The deviceID is "unique" while in the proximity, it's a key that we can use for
456 // linking up TabletDeviceData to an event (especially if there are two devices in action).
457 bool entering = proxRec.enterProximity;
458 if (entering) {
459 qt_mac_tablet_hash()->insert(proxRec.deviceID, proximityDevice);
460 } else {
461 qt_mac_tablet_hash()->remove(proxRec.deviceID);
462 }
463
464 QTabletEvent qtabletProximity(entering ? QEvent::TabletEnterProximity
465 : QEvent::TabletLeaveProximity,
466 QPoint(), QPoint(), QPointF(), proximityDevice.tabletDeviceType,
467 proximityDevice.tabletPointerType, 0., 0, 0, 0., 0., 0, 0,
468 proximityDevice.tabletUniqueID);
469
470 qt_sendSpontaneousEvent(qApp, &qtabletProximity);
471}
472
473#ifdef QT_MAC_USE_COCOA
474// Use this method to keep all the information in the TextSegment. As long as it is ordered
475// we are in OK shape, and we can influence that ourselves.
476struct KeyPair
477{
478 QChar cocoaKey;
479 Qt::Key qtKey;
480};
481
482bool operator==(const KeyPair &entry, QChar qchar)
483{
484 return entry.cocoaKey == qchar;
485}
486
487bool operator<(const KeyPair &entry, QChar qchar)
488{
489 return entry.cocoaKey < qchar;
490}
491
492bool operator<(QChar qchar, const KeyPair &entry)
493{
494 return qchar < entry.cocoaKey;
495}
496
497static Qt::Key cocoaKey2QtKey(QChar keyCode)
498{
499 static const int NumEntries = 57;
500 static const KeyPair entries[NumEntries] = {
501 { NSEnterCharacter, Qt::Key_Enter },
502 { NSTabCharacter, Qt::Key_Tab },
503 { NSCarriageReturnCharacter, Qt::Key_Return },
504 { NSBackTabCharacter, Qt::Key_Backtab },
505 { kEscapeCharCode, Qt::Key_Escape },
506 { NSDeleteCharacter, Qt::Key_Backspace },
507 { NSUpArrowFunctionKey, Qt::Key_Up },
508 { NSDownArrowFunctionKey, Qt::Key_Down },
509 { NSLeftArrowFunctionKey, Qt::Key_Left },
510 { NSRightArrowFunctionKey, Qt::Key_Right },
511 { NSF1FunctionKey, Qt::Key_F1 },
512 { NSF2FunctionKey, Qt::Key_F2 },
513 { NSF3FunctionKey, Qt::Key_F3 },
514 { NSF4FunctionKey, Qt::Key_F4 },
515 { NSF5FunctionKey, Qt::Key_F5 },
516 { NSF6FunctionKey, Qt::Key_F6 },
517 { NSF7FunctionKey, Qt::Key_F7 },
518 { NSF8FunctionKey, Qt::Key_F8 },
519 { NSF9FunctionKey, Qt::Key_F8 },
520 { NSF10FunctionKey, Qt::Key_F10 },
521 { NSF11FunctionKey, Qt::Key_F11 },
522 { NSF12FunctionKey, Qt::Key_F12 },
523 { NSF13FunctionKey, Qt::Key_F13 },
524 { NSF14FunctionKey, Qt::Key_F14 },
525 { NSF15FunctionKey, Qt::Key_F15 },
526 { NSF16FunctionKey, Qt::Key_F16 },
527 { NSF17FunctionKey, Qt::Key_F17 },
528 { NSF18FunctionKey, Qt::Key_F18 },
529 { NSF19FunctionKey, Qt::Key_F19 },
530 { NSF20FunctionKey, Qt::Key_F20 },
531 { NSF21FunctionKey, Qt::Key_F21 },
532 { NSF22FunctionKey, Qt::Key_F22 },
533 { NSF23FunctionKey, Qt::Key_F23 },
534 { NSF24FunctionKey, Qt::Key_F24 },
535 { NSF25FunctionKey, Qt::Key_F25 },
536 { NSF26FunctionKey, Qt::Key_F26 },
537 { NSF27FunctionKey, Qt::Key_F27 },
538 { NSF28FunctionKey, Qt::Key_F28 },
539 { NSF29FunctionKey, Qt::Key_F29 },
540 { NSF30FunctionKey, Qt::Key_F30 },
541 { NSF31FunctionKey, Qt::Key_F31 },
542 { NSF32FunctionKey, Qt::Key_F32 },
543 { NSF33FunctionKey, Qt::Key_F33 },
544 { NSF34FunctionKey, Qt::Key_F34 },
545 { NSF35FunctionKey, Qt::Key_F35 },
546 { NSInsertFunctionKey, Qt::Key_Insert },
547 { NSDeleteFunctionKey, Qt::Key_Delete },
548 { NSHomeFunctionKey, Qt::Key_Home },
549 { NSEndFunctionKey, Qt::Key_End },
550 { NSPageUpFunctionKey, Qt::Key_PageUp },
551 { NSPageDownFunctionKey, Qt::Key_PageDown },
552 { NSPrintScreenFunctionKey, Qt::Key_Print },
553 { NSScrollLockFunctionKey, Qt::Key_ScrollLock },
554 { NSPauseFunctionKey, Qt::Key_Pause },
555 { NSSysReqFunctionKey, Qt::Key_SysReq },
556 { NSMenuFunctionKey, Qt::Key_Menu },
557 { NSHelpFunctionKey, Qt::Key_Help },
558 };
559 static const KeyPair * const end = entries + NumEntries;
560 const KeyPair *i = qBinaryFind(entries, end, keyCode);
561 if (i == end)
562 return Qt::Key(keyCode.unicode());
563 return i->qtKey;
564}
565
566Qt::KeyboardModifiers qt_cocoaModifiers2QtModifiers(ulong modifierFlags)
567{
568 Qt::KeyboardModifiers qtMods =Qt::NoModifier;
569 if (modifierFlags & NSShiftKeyMask)
570 qtMods |= Qt::ShiftModifier;
571 if (modifierFlags & NSControlKeyMask)
572 qtMods |= Qt::MetaModifier;
573 if (modifierFlags & NSAlternateKeyMask)
574 qtMods |= Qt::AltModifier;
575 if (modifierFlags & NSCommandKeyMask)
576 qtMods |= Qt::ControlModifier;
577 if (modifierFlags & NSNumericPadKeyMask)
578 qtMods |= Qt::KeypadModifier;
579 return qtMods;
580}
581
582Qt::KeyboardModifiers qt_cocoaDragOperation2QtModifiers(uint dragOperations)
583{
584 Qt::KeyboardModifiers qtMods =Qt::NoModifier;
585 if (dragOperations & NSDragOperationLink)
586 qtMods |= Qt::MetaModifier;
587 if (dragOperations & NSDragOperationGeneric)
588 qtMods |= Qt::ControlModifier;
589 if (dragOperations & NSDragOperationCopy)
590 qtMods |= Qt::AltModifier;
591 return qtMods;
592}
593
594static inline QEvent::Type cocoaEvent2QtEvent(NSUInteger eventType)
595{
596 // Handle the trivial cases that can be determined from the type.
597 switch (eventType) {
598 case NSKeyDown:
599 return QEvent::KeyPress;
600 case NSKeyUp:
601 return QEvent::KeyRelease;
602 case NSLeftMouseDown:
603 case NSRightMouseDown:
604 case NSOtherMouseDown:
605 return QEvent::MouseButtonPress;
606 case NSLeftMouseUp:
607 case NSRightMouseUp:
608 case NSOtherMouseUp:
609 return QEvent::MouseButtonRelease;
610 case NSMouseMoved:
611 case NSLeftMouseDragged:
612 case NSRightMouseDragged:
613 case NSOtherMouseDragged:
614 return QEvent::MouseMove;
615 case NSScrollWheel:
616 return QEvent::Wheel;
617 }
618 return QEvent::None;
619}
620
621static bool mustUseCocoaKeyEvent()
622{
623 QCFType<TISInputSourceRef> source = TISCopyCurrentKeyboardInputSource();
624 return TISGetInputSourceProperty(source, kTISPropertyUnicodeKeyLayoutData) == 0;
625}
626
627bool qt_dispatchKeyEventWithCocoa(void * /*NSEvent * */ keyEvent, QWidget *widgetToGetEvent)
628{
629 NSEvent *event = static_cast<NSEvent *>(keyEvent);
630 NSString *keyChars = [event charactersIgnoringModifiers];
631 int keyLength = [keyChars length];
632 if (keyLength == 0)
633 return false; // Dead Key, nothing to do!
634 bool ignoreText = false;
635 Qt::Key qtKey = Qt::Key_unknown;
636 if (keyLength == 1) {
637 QChar ch([keyChars characterAtIndex:0]);
638 if (ch.isLower())
639 ch = ch.toUpper();
640 qtKey = cocoaKey2QtKey(ch);
641 // Do not set the text for Function-Key Unicodes characters (0xF700–0xF8FF).
642 ignoreText = (ch.unicode() >= 0xF700 && ch.unicode() <= 0xF8FF);
643 }
644 Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([event modifierFlags]);
645 QString text;
646
647 // To quote from the Carbon port: This is actually wrong--but it is the best that
648 // can be done for now because of the Control/Meta mapping issues
649 // (we always get text on the Mac)
650 if (!ignoreText && !(keyMods & (Qt::ControlModifier | Qt::MetaModifier)))
651 text = QCFString::toQString(reinterpret_cast<CFStringRef>(keyChars));
652
653 UInt32 macScanCode = 1;
654 QKeyEventEx ke(cocoaEvent2QtEvent([event type]), qtKey, keyMods, text, [event isARepeat], qMax(1, keyLength),
655 macScanCode, [event keyCode], [event modifierFlags]);
656 return qt_sendSpontaneousEvent(widgetToGetEvent, &ke) && ke.isAccepted();
657}
658#endif
659
660Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum)
661{
662 if (buttonNum == 0)
663 return Qt::LeftButton;
664 if (buttonNum == 1)
665 return Qt::RightButton;
666 if (buttonNum == 2)
667 return Qt::MidButton;
668 if (buttonNum == 3)
669 return Qt::XButton1;
670 if (buttonNum == 4)
671 return Qt::XButton2;
672 return Qt::NoButton;
673}
674
675// Helper to share code between QCocoaWindow and QCocoaView
676bool qt_dispatchKeyEvent(void * /*NSEvent * */ keyEvent, QWidget *widgetToGetEvent)
677{
678#ifndef QT_MAC_USE_COCOA
679 Q_UNUSED(keyEvent);
680 Q_UNUSED(widgetToGetEvent);
681 return false;
682#else
683 NSEvent *event = static_cast<NSEvent *>(keyEvent);
684 EventRef key_event = static_cast<EventRef>(const_cast<void *>([event eventRef]));
685 Q_ASSERT(key_event);
686 unsigned int info = 0;
687 if ([event type] == NSKeyDown) {
688 NSString *characters = [event characters];
689 if ([characters length]) {
690 unichar value = [characters characterAtIndex:0];
691 qt_keymapper_private()->updateKeyMap(0, key_event, (void *)&value);
692 info = value;
693 }
694 }
695
696 // Redirect keys to alien widgets.
697 if (widgetToGetEvent->testAttribute(Qt::WA_NativeWindow) == false) {
698 widgetToGetEvent = qApp->focusWidget();
699 }
700
701 if (widgetToGetEvent == 0)
702 return false;
703
704 if (qt_mac_sendMacEventToWidget(widgetToGetEvent, key_event))
705 return true;
706
707 if (mustUseCocoaKeyEvent())
708 return qt_dispatchKeyEventWithCocoa(keyEvent, widgetToGetEvent);
709 bool consumed = qt_keymapper_private()->translateKeyEvent(widgetToGetEvent, 0, key_event, &info, true);
710 return consumed && (info != 0);
711#endif
712}
713
714void qt_dispatchModifiersChanged(void * /*NSEvent * */flagsChangedEvent, QWidget *widgetToGetEvent)
715{
716#ifndef QT_MAC_USE_COCOA
717 Q_UNUSED(flagsChangedEvent);
718 Q_UNUSED(widgetToGetEvent);
719#else
720 UInt32 modifiers = 0;
721 // Sync modifiers with Qt
722 NSEvent *event = static_cast<NSEvent *>(flagsChangedEvent);
723 EventRef key_event = static_cast<EventRef>(const_cast<void *>([event eventRef]));
724 Q_ASSERT(key_event);
725 GetEventParameter(key_event, kEventParamKeyModifiers, typeUInt32, 0,
726 sizeof(modifiers), 0, &modifiers);
727 extern void qt_mac_send_modifiers_changed(quint32 modifiers, QObject *object);
728 qt_mac_send_modifiers_changed(modifiers, widgetToGetEvent);
729#endif
730}
731
732
733QPointF flipPoint(const NSPoint &p)
734{
735 return QPointF(p.x, flipYCoordinate(p.y));
736}
737
738NSPoint flipPoint(const QPoint &p)
739{
740 return NSMakePoint(p.x(), flipYCoordinate(p.y()));
741}
742
743NSPoint flipPoint(const QPointF &p)
744{
745 return NSMakePoint(p.x(), flipYCoordinate(p.y()));
746}
747
748void qt_mac_dispatchNCMouseMessage(void * /* NSWindow* */eventWindow, void * /* NSEvent* */mouseEvent,
749 QWidget *widgetToGetEvent, bool &leftButtonIsRightButton)
750{
751#ifndef QT_MAC_USE_COCOA
752 Q_UNUSED(eventWindow);
753 Q_UNUSED(mouseEvent);
754 Q_UNUSED(widgetToGetEvent);
755 Q_UNUSED(leftButtonIsRightButton);
756#else
757 if (widgetToGetEvent == 0)
758 return;
759 NSWindow *window = static_cast<NSWindow *>(eventWindow);
760 NSEvent *event = static_cast<NSEvent *>(mouseEvent);
761 NSEventType evtType = [event type];
762
763 QPoint qlocalPoint;
764 QPoint qglobalPoint;
765 bool processThisEvent = false;
766 bool fakeNCEvents = false;
767 bool fakeMouseEvents = false;
768
769 // Check if this is a mouse event.
770 if (evtType == NSLeftMouseDown || evtType == NSLeftMouseUp
771 || evtType == NSRightMouseDown || evtType == NSRightMouseUp
772 || evtType == NSOtherMouseDown || evtType == NSOtherMouseUp
773 || evtType == NSMouseMoved || evtType == NSLeftMouseDragged
774 || evtType == NSRightMouseDragged || evtType == NSOtherMouseDragged) {
775 // Check if we want to pass this message to another window
776 if (mac_mouse_grabber && mac_mouse_grabber != widgetToGetEvent) {
777 NSWindow *grabWindow = static_cast<NSWindow *>(qt_mac_window_for(mac_mouse_grabber));
778 if (window != grabWindow) {
779 window = grabWindow;
780 widgetToGetEvent = mac_mouse_grabber;
781 fakeNCEvents = true;
782 }
783 }
784 // Dont generate normal NC mouse events for Left Button dragged
785 if(evtType != NSLeftMouseDragged || fakeNCEvents) {
786 NSPoint windowPoint = [event locationInWindow];
787 NSPoint globalPoint = [[event window] convertBaseToScreen:windowPoint];
788 NSRect frameRect = [window frame];
789 if (fakeNCEvents || NSMouseInRect(globalPoint, frameRect, NO)) {
790 NSRect contentRect = [window contentRectForFrameRect:frameRect];
791 qglobalPoint = QPoint(flipPoint(globalPoint).toPoint());
792 QWidget *w = widgetToGetEvent->childAt(widgetToGetEvent->mapFromGlobal(qglobalPoint));
793 // check that the mouse pointer is on the non-client area and
794 // there are not widgets in it.
795 if (fakeNCEvents || (!NSMouseInRect(globalPoint, contentRect, NO) && !w)) {
796 qglobalPoint = QPoint(flipPoint(globalPoint).toPoint());
797 qlocalPoint = widgetToGetEvent->mapFromGlobal(qglobalPoint);
798 processThisEvent = true;
799 }
800 }
801 }
802 }
803 // This is not an NC area mouse message.
804 if (!processThisEvent)
805 return;
806
807 // If the window is frame less, generate fake mouse events instead. (floating QToolBar)
808 // or if someone already got an explicit or implicit grab
809 if (mac_mouse_grabber || qt_button_down ||
810 (fakeNCEvents && (widgetToGetEvent->window()->windowFlags() & Qt::FramelessWindowHint)))
811 fakeMouseEvents = true;
812
813 Qt::MouseButton button;
814 QEvent::Type eventType;
815 // Convert to Qt::Event type
816 switch (evtType) {
817 case NSLeftMouseDown:
818 button = Qt::LeftButton;
819 eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonPress
820 : QEvent::MouseButtonPress;
821 break;
822 case NSLeftMouseUp:
823 button = Qt::LeftButton;
824 eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonRelease
825 : QEvent::MouseButtonRelease;
826 break;
827 case NSRightMouseDown:
828 button = Qt::RightButton;
829 eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonPress
830 : QEvent::MouseButtonPress;
831 break;
832 case NSRightMouseUp:
833 button = Qt::RightButton;
834 eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonRelease
835 : QEvent::MouseButtonRelease;
836 break;
837 case NSOtherMouseDown:
838 button = cocoaButton2QtButton([event buttonNumber]);
839 eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonPress
840 : QEvent::MouseButtonPress;
841 break;
842 case NSOtherMouseUp:
843 button = cocoaButton2QtButton([event buttonNumber]);
844 eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonRelease
845 : QEvent::MouseButtonRelease;
846 break;
847 case NSMouseMoved:
848 button = Qt::NoButton;
849 eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
850 : QEvent::MouseMove;
851 break;
852 case NSLeftMouseDragged:
853 button = Qt::LeftButton;
854 eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
855 : QEvent::MouseMove;
856 break;
857 case NSRightMouseDragged:
858 button = Qt::RightButton;
859 eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
860 : QEvent::MouseMove;
861 break;
862 case NSOtherMouseDragged:
863 button = cocoaButton2QtButton([event buttonNumber]);
864 eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseMove
865 : QEvent::MouseMove;
866 break;
867 default:
868 qWarning("not handled! Non client area mouse message");
869 return;
870 }
871
872 Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([event modifierFlags]);
873 if (eventType == QEvent::NonClientAreaMouseButtonPress || eventType == QEvent::MouseButtonPress) {
874 NSInteger clickCount = [event clickCount];
875 if (clickCount % 2 == 0)
876 eventType = (!fakeMouseEvents) ? QEvent::NonClientAreaMouseButtonDblClick
877 : QEvent::MouseButtonDblClick;
878 if (button == Qt::LeftButton && (keyMods & Qt::MetaModifier)) {
879 button = Qt::RightButton;
880 leftButtonIsRightButton = true;
881 }
882 } else if (eventType == QEvent::NonClientAreaMouseButtonRelease || eventType == QEvent::MouseButtonRelease) {
883 if (button == Qt::LeftButton && leftButtonIsRightButton) {
884 button = Qt::RightButton;
885 leftButtonIsRightButton = false;
886 }
887 }
888
889 Qt::MouseButtons buttons = 0;
890 {
891 UInt32 mac_buttons;
892 if (GetEventParameter((EventRef)[event eventRef], kEventParamMouseChord, typeUInt32, 0,
893 sizeof(mac_buttons), 0, &mac_buttons) == noErr)
894 buttons = qt_mac_get_buttons(mac_buttons);
895 }
896
897 QMouseEvent qme(eventType, qlocalPoint, qglobalPoint, button, buttons, keyMods);
898 qt_sendSpontaneousEvent(widgetToGetEvent, &qme);
899
900 // We don't need to set the implicit grab widget here because we won't
901 // reach this point if then event type is Press over a Qt widget.
902 // However we might need to unset it if the event is Release.
903 if (eventType == QEvent::MouseButtonRelease)
904 qt_button_down = 0;
905#endif
906}
907
908bool qt_mac_handleMouseEvent(void * /* NSView * */view, void * /* NSEvent * */event, QEvent::Type eventType, Qt::MouseButton button)
909{
910#ifndef QT_MAC_USE_COCOA
911 Q_UNUSED(view);
912 Q_UNUSED(event);
913 Q_UNUSED(eventType);
914 Q_UNUSED(button);
915 return false;
916#else
917 QT_MANGLE_NAMESPACE(QCocoaView) *theView = static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(view);
918 NSEvent *theEvent = static_cast<NSEvent *>(event);
919
920 // Give the Input Manager a chance to process the mouse events.
921 NSInputManager *currentIManager = [NSInputManager currentInputManager];
922 if (currentIManager && [currentIManager wantsToHandleMouseEvents]) {
923 [currentIManager handleMouseEvent:theEvent];
924 }
925
926 // Handle tablet events (if any) first.
927 if (qt_mac_handleTabletEvent(theView, theEvent)) {
928 // Tablet event was handled. In Qt we aren't supposed to send the mouse event.
929 return true;
930 }
931
932 NSPoint windowPoint = [theEvent locationInWindow];
933 NSPoint globalPoint = [[theEvent window] convertBaseToScreen:windowPoint];
934
935 // Find the widget that *should* get the event (e.g., maybe it was a pop-up,
936 // they always get the mouse event).
937 QWidget *qwidget = [theView qt_qwidget];
938 QWidget *widgetToGetMouse = 0;
939 NSView *tmpView = 0;
940 QWidget *popup = qAppInstance()->activePopupWidget();
941 QPoint qglobalPoint(flipPoint(globalPoint).toPoint());
942
943 if (popup) {
944 widgetToGetMouse = popup;
945 tmpView = qt_mac_nativeview_for(popup);
946 windowPoint = [[tmpView window] convertScreenToBase:globalPoint];
947
948 QPoint qWindowPoint(windowPoint.x, windowPoint.y);
949 if (widgetToGetMouse->rect().contains(qWindowPoint)) {
950 // Keeping the mouse pressed on a combobox button will make
951 // the popup pop in front of the mouse. But all mouse events
952 // will be sendt to the button. Since we want mouse events
953 // to be sendt to widgets inside the popup, we search for the
954 // widget in front of the mouse:
955 tmpView = [tmpView hitTest:windowPoint];
956 if (!tmpView)
957 return false;
958 widgetToGetMouse =
959 [static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(tmpView) qt_qwidget];
960 }
961 } else {
962 extern QWidget * qt_button_down; //qapplication_mac.cpp
963 QPoint pos;
964 widgetToGetMouse = QApplicationPrivate::pickMouseReceiver(qwidget, qglobalPoint,
965 pos, eventType,
966 button, qt_button_down, 0);
967 if (widgetToGetMouse)
968 tmpView = qt_mac_nativeview_for(widgetToGetMouse);
969 }
970 if (!widgetToGetMouse)
971 return false;
972
973 NSPoint localPoint = [tmpView convertPoint:windowPoint fromView:nil];
974 QPoint qlocalPoint = QPoint(localPoint.x, localPoint.y);
975
976 // Search for alien child widgets (either on this qwidget or on the popup)
977 if (widgetToGetMouse->testAttribute(Qt::WA_NativeWindow) == false || qt_widget_private(widgetToGetMouse)->hasAlienChildren) {
978 QPoint qScreenPoint = flipPoint(globalPoint).toPoint();
979#ifdef ALIEN_DEBUG
980 qDebug() << "alien mouse event" << qScreenPoint << possibleAlien;
981#endif
982 QWidget *possibleAlien = widgetToGetMouse->childAt(qlocalPoint);
983 if (possibleAlien) {
984 qlocalPoint = possibleAlien->mapFromGlobal(widgetToGetMouse->mapToGlobal(qlocalPoint));
985 widgetToGetMouse = possibleAlien;
986 }
987 }
988
989 EventRef carbonEvent = static_cast<EventRef>(const_cast<void *>([theEvent eventRef]));
990 if (qt_mac_sendMacEventToWidget(widgetToGetMouse, carbonEvent))
991 return true;
992
993 // Yay! All the special cases are handled, it really is just a normal mouse event.
994 Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([theEvent modifierFlags]);
995 NSInteger clickCount = [theEvent clickCount];
996 Qt::MouseButtons buttons = 0;
997 static Qt::MouseButton previousButton = Qt::NoButton;
998 {
999 UInt32 mac_buttons;
1000 if (GetEventParameter(carbonEvent, kEventParamMouseChord, typeUInt32, 0,
1001 sizeof(mac_buttons), 0, &mac_buttons) == noErr)
1002 buttons = qt_mac_get_buttons(mac_buttons);
1003 }
1004 switch (eventType) {
1005 default:
1006 qWarning("not handled! %d", eventType);
1007 break;
1008 case QEvent::MouseMove:
1009 break;
1010 case QEvent::MouseButtonPress:
1011 [QT_MANGLE_NAMESPACE(QCocoaView) currentMouseEvent]->view = theView;
1012 [QT_MANGLE_NAMESPACE(QCocoaView) currentMouseEvent]->theEvent = theEvent;
1013#ifndef QT_NAMESPACE
1014 Q_ASSERT(clickCount > 0);
1015#endif
1016 if (clickCount % 2 == 0 && (previousButton == Qt::NoButton || previousButton == button))
1017 eventType = QEvent::MouseButtonDblClick;
1018 if (button == Qt::LeftButton && (keyMods & Qt::MetaModifier)) {
1019 button = Qt::RightButton;
1020 [theView qt_setLeftButtonIsRightButton: true];
1021 }
1022 break;
1023 case QEvent::MouseButtonRelease:
1024 if (button == Qt::LeftButton && [theView qt_leftButtonIsRightButton]) {
1025 button = Qt::RightButton;
1026 [theView qt_setLeftButtonIsRightButton: false];
1027 }
1028 qt_button_down = 0;
1029 break;
1030 }
1031 [QT_MANGLE_NAMESPACE(QCocoaView) currentMouseEvent]->localPoint = localPoint;
1032 QMouseEvent qme(eventType, qlocalPoint, qglobalPoint, button, buttons, keyMods);
1033
1034#ifdef ALIEN_DEBUG
1035 qDebug() << "sending mouse event to" << widgetToGetMouse;
1036#endif
1037 extern QWidget *qt_button_down;
1038 extern QPointer<QWidget> qt_last_mouse_receiver;
1039
1040 if (qwidget->testAttribute(Qt::WA_NativeWindow) && qt_widget_private(qwidget)->hasAlienChildren == false)
1041 qt_sendSpontaneousEvent(widgetToGetMouse, &qme);
1042 else
1043 QApplicationPrivate::sendMouseEvent(widgetToGetMouse, &qme, widgetToGetMouse, qwidget, &qt_button_down,
1044 qt_last_mouse_receiver);
1045
1046 if (eventType == QEvent::MouseButtonPress && button == Qt::RightButton) {
1047 QContextMenuEvent qcme(QContextMenuEvent::Mouse, qlocalPoint, qglobalPoint, keyMods);
1048 qt_sendSpontaneousEvent(widgetToGetMouse, &qcme);
1049 }
1050 previousButton = button;
1051 return true;
1052#endif
1053}
1054
1055bool qt_mac_handleTabletEvent(void * /*QCocoaView * */view, void * /*NSEvent * */tabletEvent)
1056{
1057#ifndef QT_MAC_USE_COCOA
1058 Q_UNUSED(view);
1059 Q_UNUSED(tabletEvent);
1060 return false;
1061#else
1062 QT_MANGLE_NAMESPACE(QCocoaView) *theView = static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(view);
1063 NSView *theNSView = static_cast<NSView *>(view);
1064 NSEvent *theTabletEvent = static_cast<NSEvent *>(tabletEvent);
1065
1066 NSEventType eventType = [theTabletEvent type];
1067 if (eventType != NSTabletPoint && [theTabletEvent subtype] != NSTabletPointEventSubtype)
1068 return false; // Not a tablet event.
1069
1070 NSPoint windowPoint = [theTabletEvent locationInWindow];
1071 NSPoint globalPoint = [[theTabletEvent window] convertBaseToScreen:windowPoint];
1072
1073 QWidget *qwidget = [theView qt_qwidget];
1074 QWidget *widgetToGetMouse = qwidget;
1075 QWidget *popup = qAppInstance()->activePopupWidget();
1076 if (popup && popup != qwidget->window())
1077 widgetToGetMouse = popup;
1078
1079 if (qt_mac_sendMacEventToWidget(widgetToGetMouse,
1080 static_cast<EventRef>(const_cast<void *>([theTabletEvent eventRef]))))
1081 return true;
1082 if (widgetToGetMouse != qwidget) {
1083 theNSView = qt_mac_nativeview_for(widgetToGetMouse);
1084 windowPoint = [[theNSView window] convertScreenToBase:globalPoint];
1085 }
1086 NSPoint localPoint = [theNSView convertPoint:windowPoint fromView:nil];
1087 // Tablet events do not handle WA_TransparentForMouseEvents ATM
1088 // In theory, people who set the WA_TransparentForMouseEvents attribute won't handle
1089 // tablet events either in which case they will fall into the mouse event case and get
1090 // them passed on. This will NOT handle the raw events, but that might not be a big problem.
1091
1092 const QMacTabletHash *tabletHash = qt_mac_tablet_hash();
1093 if (!tabletHash->contains([theTabletEvent deviceID])) {
1094 qWarning("QCocoaView handleTabletEvent: This tablet device is unknown"
1095 " (received no proximity event for it). Discarding event.");
1096 return false;
1097 }
1098 const QTabletDeviceData &deviceData = tabletHash->value([theTabletEvent deviceID]);
1099
1100
1101 QEvent::Type qType;
1102 switch (eventType) {
1103 case NSLeftMouseDown:
1104 case NSRightMouseDown:
1105 qType = QEvent::TabletPress;
1106 break;
1107 case NSLeftMouseUp:
1108 case NSRightMouseUp:
1109 qType = QEvent::TabletRelease;
1110 break;
1111 case NSMouseMoved:
1112 case NSTabletPoint:
1113 case NSLeftMouseDragged:
1114 case NSRightMouseDragged:
1115 default:
1116 qType = QEvent::TabletMove;
1117 break;
1118 }
1119
1120 qreal pressure;
1121 if (eventType != NSMouseMoved) {
1122 pressure = [theTabletEvent pressure];
1123 } else {
1124 pressure = 0.0;
1125 }
1126
1127 NSPoint tilt = [theTabletEvent tilt];
1128 int xTilt = qRound(tilt.x * 60.0);
1129 int yTilt = qRound(tilt.y * -60.0);
1130 qreal tangentialPressure = 0;
1131 qreal rotation = 0;
1132 int z = 0;
1133 if (deviceData.capabilityMask & 0x0200)
1134 z = [theTabletEvent absoluteZ];
1135
1136 if (deviceData.capabilityMask & 0x0800)
1137 tangentialPressure = [theTabletEvent tangentialPressure];
1138
1139 rotation = [theTabletEvent rotation];
1140 QPointF hiRes = flipPoint(globalPoint);
1141 QTabletEvent qtabletEvent(qType, QPoint(localPoint.x, localPoint.y),
1142 hiRes.toPoint(), hiRes,
1143 deviceData.tabletDeviceType, deviceData.tabletPointerType,
1144 pressure, xTilt, yTilt, tangentialPressure, rotation, z,
1145 qt_cocoaModifiers2QtModifiers([theTabletEvent modifierFlags]),
1146 deviceData.tabletUniqueID);
1147
1148 qt_sendSpontaneousEvent(widgetToGetMouse, &qtabletEvent);
1149 return qtabletEvent.isAccepted();
1150#endif
1151}
1152
1153void qt_mac_updateContentBorderMetricts(void * /*OSWindowRef */window, const ::HIContentBorderMetrics &metrics)
1154{
1155 OSWindowRef theWindow = static_cast<OSWindowRef>(window);
1156#if !defined(QT_MAC_USE_COCOA)
1157# if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1158 if (QSysInfo::MacintoshVersion >= QSysInfo::MV_10_5) {
1159 ::HIWindowSetContentBorderThickness(theWindow, &metrics);
1160 }
1161# else
1162 Q_UNUSED(window);
1163 Q_UNUSED(metrics);
1164# endif
1165#else
1166 if ([theWindow styleMask] & NSTexturedBackgroundWindowMask)
1167 [theWindow setContentBorderThickness:metrics.top forEdge:NSMaxYEdge];
1168 [theWindow setContentBorderThickness:metrics.bottom forEdge:NSMinYEdge];
1169#endif
1170}
1171
1172#if QT_MAC_USE_COCOA
1173void qt_mac_replaceDrawRect(void * /*OSWindowRef */window, QWidgetPrivate *widget)
1174{
1175 QMacCocoaAutoReleasePool pool;
1176 OSWindowRef theWindow = static_cast<OSWindowRef>(window);
1177 if(!theWindow)
1178 return;
1179 id theClass = [[[theWindow contentView] superview] class];
1180 // What we do here is basically to add a new selector to NSThemeFrame called
1181 // "drawRectOriginal:" which will contain the original implementation of
1182 // "drawRect:". After that we get the new implementation from QCocoaWindow
1183 // and exchange them. The new implementation is called drawRectSpecial.
1184 // We cannot just add the method because it might have been added before and since
1185 // we cannot remove a method once it has been added we need to ask QCocoaWindow if
1186 // we did the swap or not.
1187 if(!widget->drawRectOriginalAdded) {
1188 Method m2 = class_getInstanceMethod(theClass, @selector(drawRect:));
1189 if(!m2) {
1190 // This case is pretty extreme, no drawRect means no drawing!
1191 return;
1192 }
1193 class_addMethod(theClass, @selector(drawRectOriginal:), method_getImplementation(m2), method_getTypeEncoding(m2));
1194 widget->drawRectOriginalAdded = true;
1195 }
1196 if(widget->originalDrawMethod) {
1197 Method m0 = class_getInstanceMethod([theWindow class], @selector(drawRectSpecial:));
1198 if(!m0) {
1199 // Ok, this means the methods were never swapped. Just ignore
1200 return;
1201 }
1202 Method m1 = class_getInstanceMethod(theClass, @selector(drawRect:));
1203 if(!m1) {
1204 // Ok, this means the methods were never swapped. Just ignore
1205 return;
1206 }
1207 // We have the original method here. Proceed and swap the methods.
1208 method_exchangeImplementations(m1, m0);
1209 widget->originalDrawMethod = false;
1210 [window display];
1211 }
1212}
1213
1214void qt_mac_replaceDrawRectOriginal(void * /*OSWindowRef */window, QWidgetPrivate *widget)
1215{
1216 QMacCocoaAutoReleasePool pool;
1217 OSWindowRef theWindow = static_cast<OSWindowRef>(window);
1218 id theClass = [[[theWindow contentView] superview] class];
1219 // Now we need to revert the methods to their original state.
1220 // We cannot remove the method, so we just keep track of it in QCocoaWindow.
1221 Method m0 = class_getInstanceMethod([theWindow class], @selector(drawRectSpecial:));
1222 if(!m0) {
1223 // Ok, this means the methods were never swapped. Just ignore
1224 return;
1225 }
1226 Method m1 = class_getInstanceMethod(theClass, @selector(drawRect:));
1227 if(!m1) {
1228 // Ok, this means the methods were never swapped. Just ignore
1229 return;
1230 }
1231 method_exchangeImplementations(m1, m0);
1232 widget->originalDrawMethod = true;
1233 [window display];
1234}
1235#endif // QT_MAC_USE_COCOA
1236
1237void qt_mac_showBaseLineSeparator(void * /*OSWindowRef */window, bool show)
1238{
1239 if(!window)
1240 return;
1241#if QT_MAC_USE_COCOA
1242 QMacCocoaAutoReleasePool pool;
1243 OSWindowRef theWindow = static_cast<OSWindowRef>(window);
1244 NSToolbar *macToolbar = [theWindow toolbar];
1245 [macToolbar setShowsBaselineSeparator:show];
1246#endif // QT_MAC_USE_COCOA
1247}
1248
1249QStringList qt_mac_NSArrayToQStringList(void *nsarray)
1250{
1251 QStringList result;
1252 NSArray *array = static_cast<NSArray *>(nsarray);
1253 for (NSUInteger i=0; i<[array count]; ++i)
1254 result << qt_mac_NSStringToQString([array objectAtIndex:i]);
1255 return result;
1256}
1257
1258void *qt_mac_QStringListToNSMutableArrayVoid(const QStringList &list)
1259{
1260 NSMutableArray *result = [NSMutableArray arrayWithCapacity:list.size()];
1261 for (int i=0; i<list.size(); ++i){
1262 [result addObject:reinterpret_cast<const NSString *>(QCFString::toCFStringRef(list[i]))];
1263 }
1264 return result;
1265}
1266
1267void qt_syncCocoaTitleBarButtons(OSWindowRef window, QWidget *widgetForWindow)
1268{
1269 if (!widgetForWindow)
1270 return;
1271
1272 Qt::WindowFlags flags = widgetForWindow->windowFlags();
1273 bool customize = flags & Qt::CustomizeWindowHint;
1274
1275 NSButton *btn = [window standardWindowButton:NSWindowZoomButton];
1276 // BOOL is not an int, so the bitwise AND doesn't work.
1277 bool go = uint(customize && !(flags & Qt::WindowMaximizeButtonHint)) == 0;
1278 [btn setEnabled:go];
1279
1280 btn = [window standardWindowButton:NSWindowMiniaturizeButton];
1281 go = uint(customize && !(flags & Qt::WindowMinimizeButtonHint)) == 0;
1282 [btn setEnabled:go];
1283
1284 btn = [window standardWindowButton:NSWindowCloseButton];
1285 go = uint(customize && !(flags & Qt::WindowSystemMenuHint
1286 || flags & Qt::WindowCloseButtonHint)) == 0;
1287 [btn setEnabled:go];
1288
1289 [window setShowsToolbarButton:uint(flags & Qt::MacWindowToolBarButtonHint) != 0];
1290}
1291
1292// Carbon: Make sure you call QDEndContext on the context when done with it.
1293CGContextRef qt_mac_graphicsContextFor(QWidget *widget)
1294{
1295 if (!widget)
1296 return 0;
1297
1298#ifndef QT_MAC_USE_COCOA
1299 CGContextRef context;
1300 CGrafPtr port = GetWindowPort(qt_mac_window_for(widget));
1301 QDBeginCGContext(port, &context);
1302#else
1303 CGContextRef context = reinterpret_cast<CGContextRef>([[qt_mac_window_for(widget) graphicsContext] graphicsPort]);
1304#endif
1305 return context;
1306}
1307
1308void qt_mac_dispatchPendingUpdateRequests(QWidget *widget)
1309{
1310 if (!widget)
1311 return;
1312#ifndef QT_MAC_USE_COCOA
1313 HIViewRender(qt_mac_nativeview_for(widget));
1314#else
1315 [qt_mac_nativeview_for(widget) displayIfNeeded];
1316#endif
1317}
1318
1319CGFloat qt_mac_get_scalefactor()
1320{
1321#ifndef QT_MAC_USE_COCOA
1322 return HIGetScaleFactor();
1323#else
1324 return [[NSScreen mainScreen] userSpaceScaleFactor];
1325#endif
1326}
1327
1328QString qt_mac_get_pasteboardString(OSPasteboardRef paste)
1329{
1330 QMacCocoaAutoReleasePool pool;
1331 NSPasteboard *pb = nil;
1332 CFStringRef pbname;
1333 if (PasteboardCopyName (paste, &pbname)) {
1334 pb = [NSPasteboard generalPasteboard];
1335 } else {
1336 pb = [NSPasteboard pasteboardWithName:reinterpret_cast<const NSString *>(pbname)];
1337 CFRelease (pbname);
1338 }
1339 if (pb) {
1340 NSString *text = [pb stringForType:NSStringPboardType];
1341 if (text)
1342 return qt_mac_NSStringToQString(text);
1343 }
1344 return QString();
1345}
1346
1347QPixmap qt_mac_convert_iconref(const IconRef icon, int width, int height)
1348{
1349 QPixmap ret(width, height);
1350 ret.fill(QColor(0, 0, 0, 0));
1351
1352 CGRect rect = CGRectMake(0, 0, width, height);
1353
1354 CGContextRef ctx = qt_mac_cg_context(&ret);
1355 CGAffineTransform old_xform = CGContextGetCTM(ctx);
1356 CGContextConcatCTM(ctx, CGAffineTransformInvert(old_xform));
1357 CGContextConcatCTM(ctx, CGAffineTransformIdentity);
1358
1359 ::RGBColor b;
1360 b.blue = b.green = b.red = 255*255;
1361 PlotIconRefInContext(ctx, &rect, kAlignNone, kTransformNone, &b, kPlotIconRefNormalFlags, icon);
1362 CGContextRelease(ctx);
1363 return ret;
1364}
1365
1366void qt_mac_constructQIconFromIconRef(const IconRef icon, const IconRef overlayIcon, QIcon *retIcon, QStyle::StandardPixmap standardIcon)
1367{
1368 int size = 16;
1369 while (size <= 128) {
1370
1371 const QString cacheKey = QLatin1String("qt_mac_constructQIconFromIconRef") + QString::number(standardIcon) + QString::number(size);
1372 QPixmap mainIcon;
1373 if (standardIcon >= QStyle::SP_CustomBase) {
1374 mainIcon = qt_mac_convert_iconref(icon, size, size);
1375 } else if (QPixmapCache::find(cacheKey, mainIcon) == false) {
1376 mainIcon = qt_mac_convert_iconref(icon, size, size);
1377 QPixmapCache::insert(cacheKey, mainIcon);
1378 }
1379
1380 if (overlayIcon) {
1381 int littleSize = size / 2;
1382 QPixmap overlayPix = qt_mac_convert_iconref(overlayIcon, littleSize, littleSize);
1383 QPainter painter(&mainIcon);
1384 painter.drawPixmap(size - littleSize, size - littleSize, overlayPix);
1385 }
1386
1387 retIcon->addPixmap(mainIcon);
1388 size += size; // 16 -> 32 -> 64 -> 128
1389 }
1390}
1391
1392void qt_mac_menu_collapseSeparators(void */*NSMenu **/ theMenu, bool collapse)
1393{
1394 OSMenuRef menu = static_cast<OSMenuRef>(theMenu);
1395 if (collapse) {
1396 bool previousIsSeparator = true; // setting to true kills all the separators placed at the top.
1397 NSMenuItem *previousItem = nil;
1398
1399 NSArray *itemArray = [menu itemArray];
1400 for (unsigned int i = 0; i < [itemArray count]; ++i) {
1401 NSMenuItem *item = reinterpret_cast<NSMenuItem *>([itemArray objectAtIndex:i]);
1402 if ([item isSeparatorItem]) {
1403 [item setHidden:previousIsSeparator];
1404 }
1405
1406 if (![item isHidden]) {
1407 previousItem = item;
1408 previousIsSeparator = ([previousItem isSeparatorItem]);
1409 }
1410 }
1411
1412 // We now need to check the final item since we don't want any separators at the end of the list.
1413 if (previousItem && previousIsSeparator)
1414 [previousItem setHidden:YES];
1415 } else {
1416 NSArray *itemArray = [menu itemArray];
1417 for (unsigned int i = 0; i < [itemArray count]; ++i) {
1418 NSMenuItem *item = reinterpret_cast<NSMenuItem *>([itemArray objectAtIndex:i]);
1419 if (QAction *action = reinterpret_cast<QAction *>([item tag]))
1420 [item setHidden:!action->isVisible()];
1421 }
1422 }
1423}
1424
1425#ifdef QT_MAC_USE_COCOA
1426void qt_cocoaChangeOverrideCursor(const QCursor &cursor)
1427{
1428 QMacCocoaAutoReleasePool pool;
1429 [static_cast<NSCursor *>(qt_mac_nsCursorForQCursor(cursor)) set];
1430}
1431
1432// WARNING: If Qt did not create NSApplication (e.g. in case it is
1433// used as a plugin), and at the same time, there is no window on
1434// screen (or the window that the event is sendt to becomes hidden etc
1435// before the event gets delivered), the message will not be performed.
1436bool qt_cocoaPostMessage(id target, SEL selector)
1437{
1438 if (!target)
1439 return false;
1440
1441 NSInteger windowNumber = 0;
1442 if (![NSApp isMemberOfClass:[QNSApplication class]]) {
1443 // INVARIANT: Cocoa is not using our NSApplication subclass. That means
1444 // we don't control the main event handler either. So target the event
1445 // for one of the windows on screen:
1446 NSWindow *nswin = [NSApp mainWindow];
1447 if (!nswin) {
1448 nswin = [NSApp keyWindow];
1449 if (!nswin)
1450 return false;
1451 }
1452 windowNumber = [nswin windowNumber];
1453 }
1454
1455 // WARNING: data1 and data2 is truncated to from 64-bit to 32-bit on OS 10.5!
1456 // That is why we need to split the address in two parts:
1457 QCocoaPostMessageArgs *args = new QCocoaPostMessageArgs(target, selector);
1458 quint32 lower = quintptr(args);
1459 quint32 upper = quintptr(args) >> 32;
1460 NSEvent *e = [NSEvent otherEventWithType:NSApplicationDefined
1461 location:NSZeroPoint modifierFlags:0 timestamp:0 windowNumber:windowNumber
1462 context:nil subtype:QtCocoaEventSubTypePostMessage data1:lower data2:upper];
1463 [NSApp postEvent:e atStart:NO];
1464 return true;
1465}
1466#endif
1467
1468QMacCocoaAutoReleasePool::QMacCocoaAutoReleasePool()
1469{
1470#ifndef QT_MAC_USE_COCOA
1471 NSApplicationLoad();
1472#endif
1473 pool = (void*)[[NSAutoreleasePool alloc] init];
1474}
1475
1476QMacCocoaAutoReleasePool::~QMacCocoaAutoReleasePool()
1477{
1478 [(NSAutoreleasePool*)pool release];
1479}
1480
1481void qt_mac_post_retranslateAppMenu()
1482{
1483#ifdef QT_MAC_USE_COCOA
1484 QMacCocoaAutoReleasePool pool;
1485 qt_cocoaPostMessage([NSApp QT_MANGLE_NAMESPACE(qt_qcocoamenuLoader)], @selector(qtTranslateApplicationMenu));
1486#endif
1487}
1488
1489#ifdef QT_MAC_USE_COCOA
1490// This method implements the magic for the drawRectSpecial method.
1491// We draw a line at the upper edge of the content view in order to
1492// override the title baseline.
1493void macDrawRectOnTop(void * /*OSWindowRef */window)
1494{
1495 OSWindowRef theWindow = static_cast<OSWindowRef>(window);
1496 NSView *contentView = [theWindow contentView];
1497 if(!contentView)
1498 return;
1499 // Get coordinates of the content view
1500 NSRect contentRect = [contentView frame];
1501 // Draw a line on top of the already drawn line.
1502 // We need to check if we are active or not to use the proper color.
1503 if([window isKeyWindow] || [window isMainWindow]) {
1504 [[NSColor colorWithCalibratedRed:1.0 green:1.0 blue:1.0 alpha:1.0] set];
1505 } else {
1506 [[NSColor colorWithCalibratedRed:1.0 green:1.0 blue:1.0 alpha:1.0] set];
1507 }
1508 NSPoint origin = NSMakePoint(0, contentRect.size.height);
1509 NSPoint end = NSMakePoint(contentRect.size.width, contentRect.size.height);
1510 [NSBezierPath strokeLineFromPoint:origin toPoint:end];
1511}
1512
1513// This method will (or at least should) get called only once.
1514// Its mission is to find out if we are active or not. If we are active
1515// we assume that we were launched via finder, otherwise we assume
1516// we were called from the command line. The distinction is important,
1517// since in the first case we don't need to trigger a paintEvent, while
1518// in the second case we do.
1519void macSyncDrawingOnFirstInvocation(void * /*OSWindowRef */window)
1520{
1521 OSWindowRef theWindow = static_cast<OSWindowRef>(window);
1522 NSApplication *application = [NSApplication sharedApplication];
1523 NSToolbar *toolbar = [window toolbar];
1524 if([application isActive]) {
1525 // Launched from finder
1526 [toolbar setShowsBaselineSeparator:NO];
1527 } else {
1528 // Launched from commandline
1529 [toolbar setVisible:false];
1530 [toolbar setShowsBaselineSeparator:NO];
1531 [toolbar setVisible:true];
1532 [theWindow display];
1533 }
1534}
1535
1536void qt_cocoaStackChildWindowOnTopOfOtherChildren(QWidget *childWidget)
1537{
1538 if (!childWidget)
1539 return;
1540
1541 QWidget *parent = childWidget->parentWidget();
1542 if (childWidget->isWindow() && parent) {
1543 if ([[qt_mac_window_for(parent) childWindows] containsObject:qt_mac_window_for(childWidget)]) {
1544 QWidgetPrivate *d = qt_widget_private(childWidget);
1545 d->setSubWindowStacking(false);
1546 d->setSubWindowStacking(true);
1547 }
1548 }
1549}
1550
1551#endif // QT_MAC_USE_COCOA
1552
1553QT_END_NAMESPACE
Note: See TracBrowser for help on using the repository browser.