source: trunk/src/gui/kernel/qcocoaview_mac.mm@ 624

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

trunk: Merged in qt 4.6.1 sources.

File size: 54.1 KB
Line 
1/****************************************************************************
2**
3** Copyright (C) 2009 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#import <private/qcocoaview_mac_p.h>
43#ifdef QT_MAC_USE_COCOA
44
45#include <private/qwidget_p.h>
46#include <private/qt_mac_p.h>
47#include <private/qapplication_p.h>
48#include <private/qabstractscrollarea_p.h>
49#include <private/qt_cocoa_helpers_mac_p.h>
50#include <private/qdnd_p.h>
51#include <private/qmacinputcontext_p.h>
52#include <private/qmultitouch_mac_p.h>
53#include <private/qevent_p.h>
54#include <private/qbackingstore_p.h>
55
56#include <qscrollarea.h>
57#include <qhash.h>
58#include <qtextformat.h>
59#include <qpaintengine.h>
60#include <QUrl>
61#include <QAccessible>
62#include <QFileInfo>
63#include <QFile>
64
65#include <qdebug.h>
66
67@interface NSEvent (Qt_Compile_Leopard_DeviceDelta)
68 - (CGFloat)deviceDeltaX;
69 - (CGFloat)deviceDeltaY;
70 - (CGFloat)deviceDeltaZ;
71@end
72
73@interface NSEvent (Qt_Compile_Leopard_Gestures)
74 - (CGFloat)magnification;
75@end
76
77QT_BEGIN_NAMESPACE
78
79Q_GLOBAL_STATIC(DnDParams, qMacDnDParams);
80
81extern void qt_mac_update_cursor_at_global_pos(const QPoint &globalPos); // qcursor_mac.mm
82extern bool qt_sendSpontaneousEvent(QObject *, QEvent *); // qapplication.cpp
83extern OSViewRef qt_mac_nativeview_for(const QWidget *w); // qwidget_mac.mm
84extern const QStringList& qEnabledDraggedTypes(); // qmime_mac.cpp
85extern QPointer<QWidget> qt_mouseover; //qapplication_mac.mm
86extern QPointer<QWidget> qt_button_down; //qapplication_mac.cpp
87
88Qt::MouseButton cocoaButton2QtButton(NSInteger buttonNum)
89{
90 if (buttonNum == 0)
91 return Qt::LeftButton;
92 if (buttonNum == 1)
93 return Qt::RightButton;
94 if (buttonNum == 2)
95 return Qt::MidButton;
96 if (buttonNum == 3)
97 return Qt::XButton1;
98 if (buttonNum == 4)
99 return Qt::XButton2;
100 return Qt::NoButton;
101}
102
103struct dndenum_mapper
104{
105 NSDragOperation mac_code;
106 Qt::DropAction qt_code;
107 bool Qt2Mac;
108};
109
110static dndenum_mapper dnd_enums[] = {
111 { NSDragOperationLink, Qt::LinkAction, true },
112 { NSDragOperationMove, Qt::MoveAction, true },
113 { NSDragOperationCopy, Qt::CopyAction, true },
114 { NSDragOperationGeneric, Qt::CopyAction, false },
115 { NSDragOperationEvery, Qt::ActionMask, false },
116 { NSDragOperationNone, Qt::IgnoreAction, false }
117};
118
119static NSDragOperation qt_mac_mapDropAction(Qt::DropAction action)
120{
121 for (int i=0; dnd_enums[i].qt_code; i++) {
122 if (dnd_enums[i].Qt2Mac && (action & dnd_enums[i].qt_code)) {
123 return dnd_enums[i].mac_code;
124 }
125 }
126 return NSDragOperationNone;
127}
128
129static NSDragOperation qt_mac_mapDropActions(Qt::DropActions actions)
130{
131 NSDragOperation nsActions = NSDragOperationNone;
132 for (int i=0; dnd_enums[i].qt_code; i++) {
133 if (dnd_enums[i].Qt2Mac && (actions & dnd_enums[i].qt_code))
134 nsActions |= dnd_enums[i].mac_code;
135 }
136 return nsActions;
137}
138
139static Qt::DropAction qt_mac_mapNSDragOperation(NSDragOperation nsActions)
140{
141 Qt::DropAction action = Qt::IgnoreAction;
142 for (int i=0; dnd_enums[i].mac_code; i++) {
143 if (nsActions & dnd_enums[i].mac_code)
144 return dnd_enums[i].qt_code;
145 }
146 return action;
147}
148
149static Qt::DropActions qt_mac_mapNSDragOperations(NSDragOperation nsActions)
150{
151 Qt::DropActions actions = Qt::IgnoreAction;
152 for (int i=0; dnd_enums[i].mac_code; i++) {
153 if (nsActions & dnd_enums[i].mac_code)
154 actions |= dnd_enums[i].qt_code;
155 }
156 return actions;
157}
158
159static QColor colorFrom(NSColor *color)
160{
161 QColor qtColor;
162 NSString *colorSpace = [color colorSpaceName];
163 if (colorSpace == NSDeviceCMYKColorSpace) {
164 CGFloat cyan, magenta, yellow, black, alpha;
165 [color getCyan:&cyan magenta:&magenta yellow:&yellow black:&black alpha:&alpha];
166 qtColor.setCmykF(cyan, magenta, yellow, black, alpha);
167 } else {
168 NSColor *tmpColor;
169 tmpColor = [color colorUsingColorSpaceName:NSDeviceRGBColorSpace];
170 CGFloat red, green, blue, alpha;
171 [tmpColor getRed:&red green:&green blue:&blue alpha:&alpha];
172 qtColor.setRgbF(red, green, blue, alpha);
173 }
174 return qtColor;
175}
176
177QT_END_NAMESPACE
178
179QT_FORWARD_DECLARE_CLASS(QMacCocoaAutoReleasePool)
180QT_FORWARD_DECLARE_CLASS(QCFString)
181QT_FORWARD_DECLARE_CLASS(QDragManager)
182QT_FORWARD_DECLARE_CLASS(QMimeData)
183QT_FORWARD_DECLARE_CLASS(QPoint)
184QT_FORWARD_DECLARE_CLASS(QApplication)
185QT_FORWARD_DECLARE_CLASS(QApplicationPrivate)
186QT_FORWARD_DECLARE_CLASS(QDragEnterEvent)
187QT_FORWARD_DECLARE_CLASS(QDragMoveEvent)
188QT_FORWARD_DECLARE_CLASS(QStringList)
189QT_FORWARD_DECLARE_CLASS(QString)
190QT_FORWARD_DECLARE_CLASS(QRect)
191QT_FORWARD_DECLARE_CLASS(QRegion)
192QT_FORWARD_DECLARE_CLASS(QAbstractScrollArea)
193QT_FORWARD_DECLARE_CLASS(QAbstractScrollAreaPrivate)
194QT_FORWARD_DECLARE_CLASS(QPaintEvent)
195QT_FORWARD_DECLARE_CLASS(QPainter)
196QT_FORWARD_DECLARE_CLASS(QHoverEvent)
197QT_FORWARD_DECLARE_CLASS(QCursor)
198QT_USE_NAMESPACE
199extern "C" {
200 extern NSString *NSTextInputReplacementRangeAttributeName;
201}
202
203
204@implementation QT_MANGLE_NAMESPACE(QCocoaView)
205
206- (id)initWithQWidget:(QWidget *)widget widgetPrivate:(QWidgetPrivate *)widgetprivate
207{
208 self = [super init];
209 if (self) {
210 [self finishInitWithQWidget:widget widgetPrivate:widgetprivate];
211 }
212 composingText = new QString();
213 composing = false;
214 sendKeyEvents = true;
215 currentCustomTypes = 0;
216 [self setHidden:YES];
217 return self;
218}
219
220- (void) finishInitWithQWidget:(QWidget *)widget widgetPrivate:(QWidgetPrivate *)widgetprivate
221{
222 qwidget = widget;
223 qwidgetprivate = widgetprivate;
224 [[NSNotificationCenter defaultCenter] addObserver:self
225 selector:@selector(frameDidChange:)
226 name:@"NSViewFrameDidChangeNotification"
227 object:self];
228}
229
230-(void)registerDragTypes
231{
232 QMacCocoaAutoReleasePool pool;
233 // Calling registerForDraggedTypes is slow, so only do it once for each widget
234 // or when the custom types change.
235 const QStringList& customTypes = qEnabledDraggedTypes();
236 if (currentCustomTypes == 0 || *currentCustomTypes != customTypes) {
237 if (currentCustomTypes == 0)
238 currentCustomTypes = new QStringList();
239 *currentCustomTypes = customTypes;
240 const NSString* mimeTypeGeneric = @"com.trolltech.qt.MimeTypeName";
241 NSMutableArray *supportedTypes = [NSMutableArray arrayWithObjects:NSColorPboardType,
242 NSFilenamesPboardType, NSStringPboardType,
243 NSFilenamesPboardType, NSPostScriptPboardType, NSTIFFPboardType,
244 NSRTFPboardType, NSTabularTextPboardType, NSFontPboardType,
245 NSRulerPboardType, NSFileContentsPboardType, NSColorPboardType,
246 NSRTFDPboardType, NSHTMLPboardType, NSPICTPboardType,
247 NSURLPboardType, NSPDFPboardType, NSVCardPboardType,
248 NSFilesPromisePboardType, NSInkTextPboardType,
249 NSMultipleTextSelectionPboardType, mimeTypeGeneric, nil];
250 // Add custom types supported by the application.
251 for (int i = 0; i < customTypes.size(); i++) {
252 [supportedTypes addObject:reinterpret_cast<const NSString *>(QCFString::toCFStringRef(customTypes[i]))];
253 }
254 [self registerForDraggedTypes:supportedTypes];
255 }
256}
257
258- (void)resetCursorRects
259{
260 QWidget *cursorWidget = qwidget;
261
262 if (cursorWidget->testAttribute(Qt::WA_TransparentForMouseEvents))
263 cursorWidget = QApplication::widgetAt(qwidget->mapToGlobal(qwidget->rect().center()));
264
265 if (cursorWidget == 0)
266 return;
267
268 if (!cursorWidget->testAttribute(Qt::WA_SetCursor)) {
269 [super resetCursorRects];
270 return;
271 }
272
273 QRegion mask = qt_widget_private(cursorWidget)->extra->mask;
274 NSCursor *nscursor = static_cast<NSCursor *>(qt_mac_nsCursorForQCursor(cursorWidget->cursor()));
275 if (mask.isEmpty()) {
276 [self addCursorRect:[qt_mac_nativeview_for(cursorWidget) visibleRect] cursor:nscursor];
277 } else {
278 const QVector<QRect> &rects = mask.rects();
279 for (int i = 0; i < rects.size(); ++i) {
280 const QRect &rect = rects.at(i);
281 [self addCursorRect:NSMakeRect(rect.x(), rect.y(), rect.width(), rect.height()) cursor:nscursor];
282 }
283 }
284}
285
286- (void)removeDropData
287{
288 if (dropData) {
289 delete dropData;
290 dropData = 0;
291 }
292}
293
294- (void)addDropData:(id <NSDraggingInfo>)sender
295{
296 [self removeDropData];
297 CFStringRef dropPasteboard = (CFStringRef) [[sender draggingPasteboard] name];
298 dropData = new QCocoaDropData(dropPasteboard);
299}
300
301- (NSDragOperation)draggingEntered:(id <NSDraggingInfo>)sender
302{
303 if (qwidget->testAttribute(Qt::WA_DropSiteRegistered) == false)
304 return NSDragOperationNone;
305 NSPoint windowPoint = [sender draggingLocation];
306 if (qwidget->testAttribute(Qt::WA_TransparentForMouseEvents)) {
307 // pass the drag enter event to the view underneath.
308 NSView *candidateView = [[[self window] contentView] hitTest:windowPoint];
309 if (candidateView && candidateView != self)
310 return [candidateView draggingEntered:sender];
311 }
312 dragEnterSequence = [sender draggingSequenceNumber];
313 [self addDropData:sender];
314 QMimeData *mimeData = dropData;
315 if (QDragManager::self()->source())
316 mimeData = QDragManager::self()->dragPrivate()->data;
317 NSPoint globalPoint = [[sender draggingDestinationWindow] convertBaseToScreen:windowPoint];
318 NSPoint localPoint = [self convertPoint:windowPoint fromView:nil];
319 QPoint posDrag(localPoint.x, localPoint.y);
320 NSDragOperation nsActions = [sender draggingSourceOperationMask];
321 Qt::DropActions qtAllowed = qt_mac_mapNSDragOperations(nsActions);
322 QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec.lastOperation) = nsActions;
323 Qt::KeyboardModifiers modifiers = Qt::NoModifier;
324 if ([sender draggingSource] != nil) {
325 // modifier flags might have changed, update it here since we don't send any input events.
326 QApplicationPrivate::modifier_buttons = qt_cocoaModifiers2QtModifiers([[NSApp currentEvent] modifierFlags]);
327 modifiers = QApplication::keyboardModifiers();
328 } else {
329 // when the source is from another application the above technique will not work.
330 modifiers = qt_cocoaDragOperation2QtModifiers(nsActions);
331 }
332 // send the drag enter event to the widget.
333 QDragEnterEvent qDEEvent(posDrag, qtAllowed, mimeData, QApplication::mouseButtons(), modifiers);
334 QApplication::sendEvent(qwidget, &qDEEvent);
335 if (!qDEEvent.isAccepted()) {
336 // widget is not interested in this drag, so ignore this drop data.
337 [self removeDropData];
338 return NSDragOperationNone;
339 } else {
340 // save the mouse position, used by draggingExited handler.
341 DnDParams *dndParams = [QT_MANGLE_NAMESPACE(QCocoaView) currentMouseEvent];
342 dndParams->activeDragEnterPos = windowPoint;
343 // send a drag move event immediately after a drag enter event (as per documentation).
344 QDragMoveEvent qDMEvent(posDrag, qtAllowed, mimeData, QApplication::mouseButtons(), modifiers);
345 qDMEvent.setDropAction(qDEEvent.dropAction());
346 qDMEvent.accept(); // accept by default, since enter event was accepted.
347 QApplication::sendEvent(qwidget, &qDMEvent);
348 if (!qDMEvent.isAccepted() || qDMEvent.dropAction() == Qt::IgnoreAction) {
349 // since we accepted the drag enter event, the widget expects
350 // future drage move events.
351 // ### check if we need to treat this like the drag enter event.
352 nsActions = NSDragOperationNone;
353 // Save as ignored in the answer rect.
354 qDMEvent.setDropAction(Qt::IgnoreAction);
355 } else {
356 nsActions = QT_PREPEND_NAMESPACE(qt_mac_mapDropAction)(qDMEvent.dropAction());
357 }
358 QT_PREPEND_NAMESPACE(qt_mac_copy_answer_rect)(qDMEvent);
359 return nsActions;
360 }
361 }
362- (NSDragOperation)draggingUpdated:(id < NSDraggingInfo >)sender
363{
364 NSPoint windowPoint = [sender draggingLocation];
365 if (qwidget->testAttribute(Qt::WA_TransparentForMouseEvents)) {
366 // pass the drag move event to the view underneath.
367 NSView *candidateView = [[[self window] contentView] hitTest:windowPoint];
368 if (candidateView && candidateView != self)
369 return [candidateView draggingUpdated:sender];
370 }
371 // in cases like QFocusFrame, the view under the mouse might
372 // not have received the drag enter. Generate a synthetic
373 // drag enter event for that view.
374 if (dragEnterSequence != [sender draggingSequenceNumber])
375 [self draggingEntered:sender];
376 // drag enter event was rejected, so ignore the move event.
377 if (dropData == 0)
378 return NSDragOperationNone;
379 // return last value, if we are still in the answerRect.
380 NSPoint globalPoint = [[sender draggingDestinationWindow] convertBaseToScreen:windowPoint];
381 NSPoint localPoint = [self convertPoint:windowPoint fromView:nil];
382 NSDragOperation nsActions = [sender draggingSourceOperationMask];
383 QPoint posDrag(localPoint.x, localPoint.y);
384 if (qt_mac_mouse_inside_answer_rect(posDrag)
385 && QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec.lastOperation) == nsActions)
386 return QT_PREPEND_NAMESPACE(qt_mac_mapDropActions)(QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec.lastAction));
387 // send drag move event to the widget
388 QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec.lastOperation) = nsActions;
389 Qt::DropActions qtAllowed = QT_PREPEND_NAMESPACE(qt_mac_mapNSDragOperations)(nsActions);
390 Qt::KeyboardModifiers modifiers = Qt::NoModifier;
391 if ([sender draggingSource] != nil) {
392 // modifier flags might have changed, update it here since we don't send any input events.
393 QApplicationPrivate::modifier_buttons = qt_cocoaModifiers2QtModifiers([[NSApp currentEvent] modifierFlags]);
394 modifiers = QApplication::keyboardModifiers();
395 } else {
396 // when the source is from another application the above technique will not work.
397 modifiers = qt_cocoaDragOperation2QtModifiers(nsActions);
398 }
399 QMimeData *mimeData = dropData;
400 if (QDragManager::self()->source())
401 mimeData = QDragManager::self()->dragPrivate()->data;
402 QDragMoveEvent qDMEvent(posDrag, qtAllowed, mimeData, QApplication::mouseButtons(), modifiers);
403 qDMEvent.setDropAction(QT_PREPEND_NAMESPACE(qt_mac_dnd_answer_rec).lastAction);
404 qDMEvent.accept();
405 QApplication::sendEvent(qwidget, &qDMEvent);
406
407 NSDragOperation operation = qt_mac_mapDropAction(qDMEvent.dropAction());
408 if (!qDMEvent.isAccepted() || qDMEvent.dropAction() == Qt::IgnoreAction) {
409 // ignore this event (we will still receive further notifications)
410 operation = NSDragOperationNone;
411 // Save as ignored in the answer rect.
412 qDMEvent.setDropAction(Qt::IgnoreAction);
413 }
414 qt_mac_copy_answer_rect(qDMEvent);
415 return operation;
416}
417
418- (void)draggingExited:(id < NSDraggingInfo >)sender
419{
420 dragEnterSequence = -1;
421 if (qwidget->testAttribute(Qt::WA_TransparentForMouseEvents)) {
422 // try sending the leave event to the last view which accepted drag enter.
423 DnDParams *dndParams = [QT_MANGLE_NAMESPACE(QCocoaView) currentMouseEvent];
424 NSView *candidateView = [[[self window] contentView] hitTest:dndParams->activeDragEnterPos];
425 if (candidateView && candidateView != self)
426 return [candidateView draggingExited:sender];
427 }
428 // drag enter event was rejected, so ignore the move event.
429 if (dropData) {
430 QDragLeaveEvent de;
431 QApplication::sendEvent(qwidget, &de);
432 [self removeDropData];
433 }
434}
435
436- (BOOL)performDragOperation:(id <NSDraggingInfo>)sender
437{
438 NSPoint windowPoint = [sender draggingLocation];
439 dragEnterSequence = -1;
440 if (qwidget->testAttribute(Qt::WA_TransparentForMouseEvents)) {
441 // pass the drop event to the view underneath.
442 NSView *candidateView = [[[self window] contentView] hitTest:windowPoint];
443 if (candidateView && candidateView != self)
444 return [candidateView performDragOperation:sender];
445 }
446 [self addDropData:sender];
447
448 NSPoint globalPoint = [[sender draggingDestinationWindow] convertBaseToScreen:windowPoint];
449 NSPoint localPoint = [self convertPoint:windowPoint fromView:nil];
450 QPoint posDrop(localPoint.x, localPoint.y);
451
452 NSDragOperation nsActions = [sender draggingSourceOperationMask];
453 Qt::DropActions qtAllowed = qt_mac_mapNSDragOperations(nsActions);
454 QMimeData *mimeData = dropData;
455 if (QDragManager::self()->source())
456 mimeData = QDragManager::self()->dragPrivate()->data;
457 // send the drop event to the widget.
458 QDropEvent de(posDrop, qtAllowed, mimeData,
459 QApplication::mouseButtons(), QApplication::keyboardModifiers());
460 if (QDragManager::self()->object)
461 QDragManager::self()->dragPrivate()->target = qwidget;
462 QApplication::sendEvent(qwidget, &de);
463 if (QDragManager::self()->object)
464 QDragManager::self()->dragPrivate()->executed_action = de.dropAction();
465 if (!de.isAccepted())
466 return NO;
467 else
468 return YES;
469}
470
471- (void)dealloc
472{
473 delete composingText;
474 [[NSNotificationCenter defaultCenter] removeObserver:self];
475 delete currentCustomTypes;
476 [self unregisterDraggedTypes];
477 [super dealloc];
478}
479
480- (BOOL)isOpaque;
481{
482 return qwidgetprivate->isOpaque;
483}
484
485- (BOOL)isFlipped;
486{
487 return YES;
488}
489
490- (BOOL) preservesContentDuringLiveResize;
491{
492 return qwidget->testAttribute(Qt::WA_StaticContents);
493}
494
495- (void) setFrameSize:(NSSize)newSize
496{
497 [super setFrameSize:newSize];
498
499 // A change in size has required the view to be invalidated.
500 if ([self inLiveResize]) {
501 NSRect rects[4];
502 NSInteger count;
503 [self getRectsExposedDuringLiveResize:rects count:&count];
504 while (count-- > 0)
505 {
506 [self setNeedsDisplayInRect:rects[count]];
507 }
508 } else {
509 [self setNeedsDisplay:YES];
510 }
511}
512
513- (void)drawRect:(NSRect)aRect
514{
515 if (QApplicationPrivate::graphicsSystem() != 0) {
516 if (QWidgetBackingStore *bs = qwidgetprivate->maybeBackingStore())
517 bs->markDirty(qwidget->rect(), qwidget);
518 qwidgetprivate->syncBackingStore(qwidget->rect());
519 return;
520 }
521 CGContextRef cg = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
522 qwidgetprivate->hd = cg;
523 CGContextSaveGState(cg);
524
525 if (qwidget->isVisible() && qwidget->updatesEnabled()) { //process the actual paint event.
526 if (qwidget->testAttribute(Qt::WA_WState_InPaintEvent))
527 qWarning("QWidget::repaint: Recursive repaint detected");
528
529 const QRect qrect = QRect(aRect.origin.x, aRect.origin.y, aRect.size.width, aRect.size.height);
530 QRegion qrgn(qrect);
531
532 if (!qwidget->isWindow() && !qobject_cast<QAbstractScrollArea *>(qwidget->parent())) {
533 const QRegion &parentMask = qwidget->window()->mask();
534 if (!parentMask.isEmpty()) {
535 const QPoint mappedPoint = qwidget->mapTo(qwidget->window(), qrect.topLeft());
536 qrgn.translate(mappedPoint);
537 qrgn &= parentMask;
538 qrgn.translate(-mappedPoint.x(), -mappedPoint.y());
539 }
540 }
541
542 QPoint redirectionOffset(0, 0);
543 //setup the context
544 qwidget->setAttribute(Qt::WA_WState_InPaintEvent);
545 QPaintEngine *engine = qwidget->paintEngine();
546 if (engine)
547 engine->setSystemClip(qrgn);
548 if (qwidgetprivate->extra && qwidgetprivate->extra->hasMask) {
549 CGRect widgetRect = CGRectMake(0, 0, qwidget->width(), qwidget->height());
550 CGContextTranslateCTM (cg, 0, widgetRect.size.height);
551 CGContextScaleCTM(cg, 1, -1);
552 if (qwidget->isWindow())
553 CGContextClearRect(cg, widgetRect);
554 CGContextClipToMask(cg, widgetRect, qwidgetprivate->extra->imageMask);
555 CGContextScaleCTM(cg, 1, -1);
556 CGContextTranslateCTM (cg, 0, -widgetRect.size.height);
557 }
558
559 if (qwidget->isWindow() && !qwidgetprivate->isOpaque
560 && !qwidget->testAttribute(Qt::WA_MacBrushedMetal)) {
561 CGContextClearRect(cg, NSRectToCGRect(aRect));
562 }
563
564 if (engine && !qwidget->testAttribute(Qt::WA_NoSystemBackground)
565 && (qwidget->isWindow() || qwidget->autoFillBackground())
566 || qwidget->testAttribute(Qt::WA_TintedBackground)
567 || qwidget->testAttribute(Qt::WA_StyledBackground)) {
568#ifdef DEBUG_WIDGET_PAINT
569 if(doDebug)
570 qDebug(" Handling erase for [%s::%s]", qwidget->metaObject()->className(),
571 qwidget->objectName().local8Bit().data());
572#endif
573 QPainter p(qwidget);
574 qwidgetprivate->paintBackground(&p, qrgn,
575 qwidget->isWindow() ? QWidgetPrivate::DrawAsRoot : 0);
576 p.end();
577 }
578 QPaintEvent e(qrgn);
579#ifdef QT3_SUPPORT
580 e.setErased(true);
581#endif
582 qt_sendSpontaneousEvent(qwidget, &e);
583 if (!redirectionOffset.isNull())
584 QPainter::restoreRedirected(qwidget);
585 if (engine)
586 engine->setSystemClip(QRegion());
587 qwidget->setAttribute(Qt::WA_WState_InPaintEvent, false);
588 if(!qwidget->testAttribute(Qt::WA_PaintOutsidePaintEvent) && qwidget->paintingActive())
589 qWarning("QWidget: It is dangerous to leave painters active on a"
590 " widget outside of the PaintEvent");
591 }
592 qwidgetprivate->hd = 0;
593 CGContextRestoreGState(cg);
594}
595
596- (BOOL)acceptsFirstMouse:(NSEvent *)theEvent
597{
598 Q_UNUSED(theEvent);
599 return !qwidget->testAttribute(Qt::WA_MacNoClickThrough);
600}
601
602- (NSView *)hitTest:(NSPoint)aPoint
603{
604 if (qwidget->testAttribute(Qt::WA_TransparentForMouseEvents))
605 return nil; // You cannot hit a transparent for mouse event widget.
606 return [super hitTest:aPoint];
607}
608
609- (void)updateTrackingAreas
610{
611 QMacCocoaAutoReleasePool pool;
612 if (NSArray *trackingArray = [self trackingAreas]) {
613 NSUInteger size = [trackingArray count];
614 for (NSUInteger i = 0; i < size; ++i) {
615 NSTrackingArea *t = [trackingArray objectAtIndex:i];
616 [self removeTrackingArea:t];
617 }
618 }
619
620 // Ideally, we shouldn't have NSTrackingMouseMoved events included below, it should
621 // only be turned on if mouseTracking, hover is on or a tool tip is set.
622 // Unfortunately, Qt will send "tooltip" events on mouse moves, so we need to
623 // turn it on in ALL case. That means EVERY QCocoaView gets to pay the cost of
624 // mouse moves delivered to it (Apple recommends keeping it OFF because there
625 // is a performance hit). So it goes.
626 NSUInteger trackingOptions = NSTrackingMouseEnteredAndExited | NSTrackingActiveInActiveApp
627 | NSTrackingInVisibleRect | NSTrackingMouseMoved;
628 NSTrackingArea *ta = [[NSTrackingArea alloc] initWithRect:NSMakeRect(0, 0,
629 qwidget->width(),
630 qwidget->height())
631 options:trackingOptions
632 owner:self
633 userInfo:nil];
634 [self addTrackingArea:ta];
635 [ta release];
636}
637
638- (void)mouseEntered:(NSEvent *)event
639{
640 QEvent enterEvent(QEvent::Enter);
641 NSPoint windowPoint = [event locationInWindow];
642 NSPoint globalPoint = [[event window] convertBaseToScreen:windowPoint];
643 NSPoint viewPoint = [self convertPoint:windowPoint fromView:nil];
644 if (!qAppInstance()->activeModalWidget() || QApplicationPrivate::tryModalHelper(qwidget, 0)) {
645 QApplication::sendEvent(qwidget, &enterEvent);
646 qt_mouseover = qwidget;
647
648 // Update cursor and dispatch hover events.
649 qt_mac_update_cursor_at_global_pos(flipPoint(globalPoint).toPoint());
650 if (qwidget->testAttribute(Qt::WA_Hover) &&
651 (!qAppInstance()->activePopupWidget() || qAppInstance()->activePopupWidget() == qwidget->window())) {
652 QHoverEvent he(QEvent::HoverEnter, QPoint(viewPoint.x, viewPoint.y), QPoint(-1, -1));
653 QApplicationPrivate::instance()->notify_helper(qwidget, &he);
654 }
655 }
656}
657
658- (void)mouseExited:(NSEvent *)event
659{
660 QEvent leaveEvent(QEvent::Leave);
661 NSPoint globalPoint = [[event window] convertBaseToScreen:[event locationInWindow]];
662 if (!qAppInstance()->activeModalWidget() || QApplicationPrivate::tryModalHelper(qwidget, 0)) {
663 QApplication::sendEvent(qwidget, &leaveEvent);
664
665 // ### Think about if it is necessary to update the cursor, should only be for a few cases.
666 qt_mac_update_cursor_at_global_pos(flipPoint(globalPoint).toPoint());
667 if (qwidget->testAttribute(Qt::WA_Hover)
668 && (!qAppInstance()->activePopupWidget() || qAppInstance()->activePopupWidget() == qwidget->window())) {
669 QHoverEvent he(QEvent::HoverLeave, QPoint(-1, -1),
670 qwidget->mapFromGlobal(QApplicationPrivate::instance()->hoverGlobalPos));
671 QApplicationPrivate::instance()->notify_helper(qwidget, &he);
672 }
673 }
674}
675
676- (void)flagsChanged:(NSEvent *)theEvent
677{
678 QWidget *widgetToGetKey = qwidget;
679
680 QWidget *popup = qAppInstance()->activePopupWidget();
681 if (popup && popup != qwidget->window())
682 widgetToGetKey = popup->focusWidget() ? popup->focusWidget() : popup;
683 qt_dispatchModifiersChanged(theEvent, widgetToGetKey);
684 [super flagsChanged:theEvent];
685}
686
687- (void)mouseMoved:(NSEvent *)theEvent
688{
689 // We always enable mouse tracking for all QCocoaView-s. In cases where we have
690 // child views, we will receive mouseMoved for both parent & the child (if
691 // mouse is over the child). We need to ignore the parent mouseMoved in such
692 // cases.
693 NSPoint windowPoint = [theEvent locationInWindow];
694 NSView *candidateView = [[[self window] contentView] hitTest:windowPoint];
695 if (candidateView && candidateView == self) {
696 qt_mac_handleMouseEvent(self, theEvent, QEvent::MouseMove, Qt::NoButton);
697 }
698}
699
700- (void)mouseDown:(NSEvent *)theEvent
701{
702 if (!qt_button_down)
703 qt_button_down = qwidget;
704
705 qt_mac_handleMouseEvent(self, theEvent, QEvent::MouseButtonPress, Qt::LeftButton);
706 // Don't call super here. This prevents us from getting the mouseUp event,
707 // which we need to send even if the mouseDown event was not accepted.
708 // (this is standard Qt behavior.)
709}
710
711
712- (void)mouseUp:(NSEvent *)theEvent
713{
714 qt_mac_handleMouseEvent(self, theEvent, QEvent::MouseButtonRelease, Qt::LeftButton);
715
716 qt_button_down = 0;
717}
718
719- (void)rightMouseDown:(NSEvent *)theEvent
720{
721 if (!qt_button_down)
722 qt_button_down = qwidget;
723
724 qt_mac_handleMouseEvent(self, theEvent, QEvent::MouseButtonPress, Qt::RightButton);
725}
726
727- (void)rightMouseUp:(NSEvent *)theEvent
728{
729 qt_mac_handleMouseEvent(self, theEvent, QEvent::MouseButtonRelease, Qt::RightButton);
730
731 qt_button_down = 0;
732}
733
734- (void)otherMouseDown:(NSEvent *)theEvent
735{
736 if (!qt_button_down)
737 qt_button_down = qwidget;
738
739 Qt::MouseButton mouseButton = cocoaButton2QtButton([theEvent buttonNumber]);
740 qt_mac_handleMouseEvent(self, theEvent, QEvent::MouseButtonPress, mouseButton);
741}
742
743- (void)otherMouseUp:(NSEvent *)theEvent
744{
745 Qt::MouseButton mouseButton = cocoaButton2QtButton([theEvent buttonNumber]);
746 qt_mac_handleMouseEvent(self, theEvent, QEvent::MouseButtonRelease, mouseButton);
747
748 qt_button_down = 0;
749}
750
751- (void)mouseDragged:(NSEvent *)theEvent
752{
753 qMacDnDParams()->view = self;
754 qMacDnDParams()->theEvent = theEvent;
755 qt_mac_handleMouseEvent(self, theEvent, QEvent::MouseMove, Qt::NoButton);
756}
757
758- (void)rightMouseDragged:(NSEvent *)theEvent
759{
760 qMacDnDParams()->view = self;
761 qMacDnDParams()->theEvent = theEvent;
762 qt_mac_handleMouseEvent(self, theEvent, QEvent::MouseMove, Qt::NoButton);
763}
764
765- (void)otherMouseDragged:(NSEvent *)theEvent
766{
767 qMacDnDParams()->view = self;
768 qMacDnDParams()->theEvent = theEvent;
769 qt_mac_handleMouseEvent(self, theEvent, QEvent::MouseMove, Qt::NoButton);
770}
771
772- (void)scrollWheel:(NSEvent *)theEvent
773{
774 // Give the Input Manager a chance to process the wheel event.
775 NSInputManager *currentIManager = [NSInputManager currentInputManager];
776 if (currentIManager && [currentIManager wantsToHandleMouseEvents]) {
777 [currentIManager handleMouseEvent:theEvent];
778 }
779
780 NSPoint windowPoint = [theEvent locationInWindow];
781 NSPoint globalPoint = [[theEvent window] convertBaseToScreen:windowPoint];
782 NSPoint localPoint = [self convertPoint:windowPoint fromView:nil];
783 QPoint qlocal = QPoint(localPoint.x, localPoint.y);
784 QPoint qglobal = QPoint(globalPoint.x, flipYCoordinate(globalPoint.y));
785 Qt::MouseButtons buttons = QApplication::mouseButtons();
786 bool wheelOK = false;
787 Qt::KeyboardModifiers keyMods = qt_cocoaModifiers2QtModifiers([theEvent modifierFlags]);
788 QWidget *widgetToGetMouse = qwidget;
789 // if popup is open it should get wheel events if the cursor is over the popup,
790 // otherwise the event should be ignored.
791 if (QWidget *popup = qAppInstance()->activePopupWidget()) {
792 if (!popup->geometry().contains(qglobal))
793 return;
794 }
795
796 int deltaX = 0;
797 int deltaY = 0;
798 int deltaZ = 0;
799
800 const EventRef carbonEvent = (EventRef)[theEvent eventRef];
801 const UInt32 carbonEventKind = carbonEvent ? ::GetEventKind(carbonEvent) : 0;
802 const bool scrollEvent = carbonEventKind == kEventMouseScroll;
803
804 if (scrollEvent) {
805 // The mouse device containts pixel scroll wheel support (Mighty Mouse, Trackpad).
806 // Since deviceDelta is delivered as pixels rather than degrees, we need to
807 // convert from pixels to degrees in a sensible manner.
808 // It looks like four degrees per pixel behaves most native.
809 // Qt expects the unit for delta to be 1/8 of a degree:
810 deltaX = [theEvent deviceDeltaX];
811 deltaY = [theEvent deviceDeltaY];
812 deltaZ = [theEvent deviceDeltaZ];
813 } else {
814 // carbonEventKind == kEventMouseWheelMoved
815 // Remove acceleration, and use either -120 or 120 as delta:
816 deltaX = qBound(-120, int([theEvent deltaX] * 10000), 120);
817 deltaY = qBound(-120, int([theEvent deltaY] * 10000), 120);
818 deltaZ = qBound(-120, int([theEvent deltaZ] * 10000), 120);
819 }
820
821 if (deltaX != 0) {
822 QWheelEvent qwe(qlocal, qglobal, deltaX, buttons, keyMods, Qt::Horizontal);
823 qt_sendSpontaneousEvent(widgetToGetMouse, &qwe);
824 wheelOK = qwe.isAccepted();
825 if (!wheelOK && QApplicationPrivate::focus_widget
826 && QApplicationPrivate::focus_widget != widgetToGetMouse) {
827 QWheelEvent qwe2(QApplicationPrivate::focus_widget->mapFromGlobal(qglobal), qglobal,
828 deltaX, buttons, keyMods, Qt::Horizontal);
829 qt_sendSpontaneousEvent(QApplicationPrivate::focus_widget, &qwe2);
830 wheelOK = qwe2.isAccepted();
831 }
832 }
833
834 if (deltaY) {
835 QWheelEvent qwe(qlocal, qglobal, deltaY, buttons, keyMods, Qt::Vertical);
836 qt_sendSpontaneousEvent(widgetToGetMouse, &qwe);
837 wheelOK = qwe.isAccepted();
838 if (!wheelOK && QApplicationPrivate::focus_widget
839 && QApplicationPrivate::focus_widget != widgetToGetMouse) {
840 QWheelEvent qwe2(QApplicationPrivate::focus_widget->mapFromGlobal(qglobal), qglobal,
841 deltaY, buttons, keyMods, Qt::Vertical);
842 qt_sendSpontaneousEvent(QApplicationPrivate::focus_widget, &qwe2);
843 wheelOK = qwe2.isAccepted();
844 }
845 }
846
847 if (deltaZ) {
848 // Qt doesn't explicitly support wheels with a Z component. In a misguided attempt to
849 // try to be ahead of the pack, I'm adding this extra value.
850 QWheelEvent qwe(qlocal, qglobal, deltaZ, buttons, keyMods, (Qt::Orientation)3);
851 qt_sendSpontaneousEvent(widgetToGetMouse, &qwe);
852 wheelOK = qwe.isAccepted();
853 if (!wheelOK && QApplicationPrivate::focus_widget
854 && QApplicationPrivate::focus_widget != widgetToGetMouse) {
855 QWheelEvent qwe2(QApplicationPrivate::focus_widget->mapFromGlobal(qglobal), qglobal,
856 deltaZ, buttons, keyMods, (Qt::Orientation)3);
857 qt_sendSpontaneousEvent(QApplicationPrivate::focus_widget, &qwe2);
858 wheelOK = qwe2.isAccepted();
859 }
860 }
861 if (!wheelOK) {
862 return [super scrollWheel:theEvent];
863 }
864}
865
866- (void)tabletProximity:(NSEvent *)tabletEvent
867{
868 qt_dispatchTabletProximityEvent(tabletEvent);
869}
870
871- (void)tabletPoint:(NSEvent *)tabletEvent
872{
873 if (!qt_mac_handleTabletEvent(self, tabletEvent))
874 [super tabletPoint:tabletEvent];
875}
876
877#if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
878- (void)touchesBeganWithEvent:(NSEvent *)event;
879{
880 bool all = qwidget->testAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents);
881 qt_translateRawTouchEvent(qwidget, QTouchEvent::TouchPad, QCocoaTouch::getCurrentTouchPointList(event, all));
882}
883
884- (void)touchesMovedWithEvent:(NSEvent *)event;
885{
886 bool all = qwidget->testAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents);
887 qt_translateRawTouchEvent(qwidget, QTouchEvent::TouchPad, QCocoaTouch::getCurrentTouchPointList(event, all));
888}
889
890- (void)touchesEndedWithEvent:(NSEvent *)event;
891{
892 bool all = qwidget->testAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents);
893 qt_translateRawTouchEvent(qwidget, QTouchEvent::TouchPad, QCocoaTouch::getCurrentTouchPointList(event, all));
894}
895
896- (void)touchesCancelledWithEvent:(NSEvent *)event;
897{
898 bool all = qwidget->testAttribute(Qt::WA_TouchPadAcceptSingleTouchEvents);
899 qt_translateRawTouchEvent(qwidget, QTouchEvent::TouchPad, QCocoaTouch::getCurrentTouchPointList(event, all));
900}
901#endif // MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
902
903- (void)magnifyWithEvent:(NSEvent *)event;
904{
905 if (!QApplicationPrivate::tryModalHelper(qwidget, 0))
906 return;
907
908 QNativeGestureEvent qNGEvent;
909 qNGEvent.gestureType = QNativeGestureEvent::Zoom;
910 NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]];
911 qNGEvent.position = flipPoint(p).toPoint();
912 qNGEvent.percentage = [event magnification];
913 qt_sendSpontaneousEvent(qwidget, &qNGEvent);
914}
915
916- (void)rotateWithEvent:(NSEvent *)event;
917{
918 if (!QApplicationPrivate::tryModalHelper(qwidget, 0))
919 return;
920
921 QNativeGestureEvent qNGEvent;
922 qNGEvent.gestureType = QNativeGestureEvent::Rotate;
923 NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]];
924 qNGEvent.position = flipPoint(p).toPoint();
925 qNGEvent.percentage = -[event rotation];
926 qt_sendSpontaneousEvent(qwidget, &qNGEvent);
927}
928
929- (void)swipeWithEvent:(NSEvent *)event;
930{
931 if (!QApplicationPrivate::tryModalHelper(qwidget, 0))
932 return;
933
934 QNativeGestureEvent qNGEvent;
935 qNGEvent.gestureType = QNativeGestureEvent::Swipe;
936 NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]];
937 qNGEvent.position = flipPoint(p).toPoint();
938 if ([event deltaX] == 1)
939 qNGEvent.angle = 180.0f;
940 else if ([event deltaX] == -1)
941 qNGEvent.angle = 0.0f;
942 else if ([event deltaY] == 1)
943 qNGEvent.angle = 90.0f;
944 else if ([event deltaY] == -1)
945 qNGEvent.angle = 270.0f;
946 qt_sendSpontaneousEvent(qwidget, &qNGEvent);
947}
948
949- (void)beginGestureWithEvent:(NSEvent *)event;
950{
951 if (!QApplicationPrivate::tryModalHelper(qwidget, 0))
952 return;
953
954 QNativeGestureEvent qNGEvent;
955 qNGEvent.gestureType = QNativeGestureEvent::GestureBegin;
956 NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]];
957 qNGEvent.position = flipPoint(p).toPoint();
958 qt_sendSpontaneousEvent(qwidget, &qNGEvent);
959}
960
961- (void)endGestureWithEvent:(NSEvent *)event;
962{
963 if (!QApplicationPrivate::tryModalHelper(qwidget, 0))
964 return;
965
966 QNativeGestureEvent qNGEvent;
967 qNGEvent.gestureType = QNativeGestureEvent::GestureEnd;
968 NSPoint p = [[event window] convertBaseToScreen:[event locationInWindow]];
969 qNGEvent.position = flipPoint(p).toPoint();
970 qt_sendSpontaneousEvent(qwidget, &qNGEvent);
971}
972
973- (void)frameDidChange:(NSNotification *)note
974{
975 Q_UNUSED(note);
976 if (qwidget->isWindow())
977 return;
978 NSRect newFrame = [self frame];
979 QRect newGeo(newFrame.origin.x, newFrame.origin.y, newFrame.size.width, newFrame.size.height);
980 bool moved = qwidget->testAttribute(Qt::WA_Moved);
981 bool resized = qwidget->testAttribute(Qt::WA_Resized);
982 qwidget->setGeometry(newGeo);
983 qwidget->setAttribute(Qt::WA_Moved, moved);
984 qwidget->setAttribute(Qt::WA_Resized, resized);
985 qwidgetprivate->syncCocoaMask();
986}
987
988- (BOOL)isEnabled
989{
990 if (!qwidget)
991 return [super isEnabled];
992 return [super isEnabled] && qwidget->isEnabled();
993}
994
995- (void)setEnabled:(BOOL)flag
996{
997 QMacCocoaAutoReleasePool pool;
998 [super setEnabled:flag];
999 if (qwidget->isEnabled() != flag)
1000 qwidget->setEnabled(flag);
1001}
1002
1003+ (Class)cellClass
1004{
1005 return [NSActionCell class];
1006}
1007
1008- (BOOL)acceptsFirstResponder
1009{
1010 if (qwidget->isWindow())
1011 return YES; // Always do it, so that windows can accept key press events.
1012 return qwidget->focusPolicy() != Qt::NoFocus;
1013}
1014
1015- (BOOL)resignFirstResponder
1016{
1017 // Seems like the following test only triggers if this
1018 // view is inside a QMacNativeWidget:
1019 if (qwidget == QApplication::focusWidget())
1020 QApplicationPrivate::setFocusWidget(0, Qt::OtherFocusReason);
1021 return YES;
1022}
1023
1024- (NSDragOperation)draggingSourceOperationMaskForLocal:(BOOL)isLocal
1025{
1026 Q_UNUSED(isLocal);
1027 return supportedActions;
1028}
1029
1030- (void)setSupportedActions:(NSDragOperation)actions
1031{
1032 supportedActions = actions;
1033}
1034
1035- (void)draggedImage:(NSImage *)anImage endedAt:(NSPoint)aPoint operation:(NSDragOperation)operation
1036{
1037 Q_UNUSED(anImage);
1038 Q_UNUSED(aPoint);
1039 qMacDnDParams()->performedAction = operation;
1040 if (QDragManager::self()->object
1041 && QDragManager::self()->dragPrivate()->executed_action != Qt::ActionMask) {
1042 qMacDnDParams()->performedAction =
1043 qt_mac_mapDropAction(QDragManager::self()->dragPrivate()->executed_action);
1044 }
1045}
1046
1047- (QWidget *)qt_qwidget
1048{
1049 return qwidget;
1050}
1051
1052- (BOOL)qt_leftButtonIsRightButton
1053{
1054 return leftButtonIsRightButton;
1055}
1056
1057- (void)qt_setLeftButtonIsRightButton:(BOOL)isSwapped
1058{
1059 leftButtonIsRightButton = isSwapped;
1060}
1061
1062+ (DnDParams*)currentMouseEvent
1063{
1064 return qMacDnDParams();
1065}
1066
1067- (void)keyDown:(NSEvent *)theEvent
1068{
1069 sendKeyEvents = true;
1070
1071 QWidget *widgetToGetKey = qwidget;
1072
1073 QWidget *popup = qAppInstance()->activePopupWidget();
1074 bool sendToPopup = false;
1075 if (popup && popup != qwidget->window()) {
1076 widgetToGetKey = popup->focusWidget() ? popup->focusWidget() : popup;
1077 sendToPopup = true;
1078 }
1079
1080 if (widgetToGetKey->testAttribute(Qt::WA_InputMethodEnabled)
1081 && !(widgetToGetKey->inputMethodHints() & Qt::ImhDigitsOnly
1082 || widgetToGetKey->inputMethodHints() & Qt::ImhFormattedNumbersOnly
1083 || widgetToGetKey->inputMethodHints() & Qt::ImhHiddenText)) {
1084 [qt_mac_nativeview_for(widgetToGetKey) interpretKeyEvents:[NSArray arrayWithObject: theEvent]];
1085 }
1086 if (sendKeyEvents && !composing) {
1087 bool keyOK = qt_dispatchKeyEvent(theEvent, widgetToGetKey);
1088 if (!keyOK && !sendToPopup)
1089 [super keyDown:theEvent];
1090 }
1091}
1092
1093
1094- (void)keyUp:(NSEvent *)theEvent
1095{
1096 if (sendKeyEvents) {
1097 bool keyOK = qt_dispatchKeyEvent(theEvent, qwidget);
1098 if (!keyOK)
1099 [super keyUp:theEvent];
1100 }
1101}
1102
1103- (void)viewWillMoveToWindow:(NSWindow *)window
1104{
1105 if (qwidget->windowFlags() & Qt::MSWindowsOwnDC
1106 && (window != [self window])) { // OpenGL Widget
1107 // Create a stupid ClearDrawable Event
1108 QEvent event(QEvent::MacGLClearDrawable);
1109 qApp->sendEvent(qwidget, &event);
1110 }
1111}
1112
1113- (void)viewDidMoveToWindow
1114{
1115 if (qwidget->windowFlags() & Qt::MSWindowsOwnDC && [self window]) {
1116 // call update paint event
1117 qwidgetprivate->needWindowChange = true;
1118 QEvent event(QEvent::MacGLWindowChange);
1119 qApp->sendEvent(qwidget, &event);
1120 }
1121}
1122
1123
1124// NSTextInput Protocol implementation
1125
1126- (void) insertText:(id)aString
1127{
1128 QString commitText;
1129 if ([aString length]) {
1130 if ([aString isKindOfClass:[NSAttributedString class]]) {
1131 commitText = QCFString::toQString(reinterpret_cast<CFStringRef>([aString string]));
1132 } else {
1133 commitText = QCFString::toQString(reinterpret_cast<CFStringRef>(aString));
1134 };
1135 }
1136
1137 if ([aString length] && composing) {
1138 // Send the commit string to the widget.
1139 composing = false;
1140 sendKeyEvents = false;
1141 QInputMethodEvent e;
1142 e.setCommitString(commitText);
1143 qt_sendSpontaneousEvent(qwidget, &e);
1144 } else {
1145 // The key sequence "`q" on a French Keyboard will generate two calls to insertText before
1146 // it returns from interpretKeyEvents. The first call will turn off 'composing' and accept
1147 // the "`" key. The last keyDown event needs to be processed by the widget to get the
1148 // character "q". The string parameter is ignored for the second call.
1149 sendKeyEvents = true;
1150 }
1151
1152 composingText->clear();
1153}
1154
1155- (void) setMarkedText:(id)aString selectedRange:(NSRange)selRange
1156{
1157 // Generate the QInputMethodEvent with preedit string and the attributes
1158 // for rendering it. The attributes handled here are 'underline',
1159 // 'underline color' and 'cursor position'.
1160 sendKeyEvents = false;
1161 composing = true;
1162 QString qtText;
1163 // Cursor position is retrived from the range.
1164 QList<QInputMethodEvent::Attribute> attrs;
1165 attrs<<QInputMethodEvent::Attribute(QInputMethodEvent::Cursor, selRange.location, 1, QVariant());
1166 if ([aString isKindOfClass:[NSAttributedString class]]) {
1167 qtText = QCFString::toQString(reinterpret_cast<CFStringRef>([aString string]));
1168 composingLength = qtText.length();
1169 int index = 0;
1170 // Create attributes for individual sections of preedit text
1171 while (index < composingLength) {
1172 NSRange effectiveRange;
1173 NSRange range = NSMakeRange(index, composingLength-index);
1174 NSDictionary *attributes = [aString attributesAtIndex:index
1175 longestEffectiveRange:&effectiveRange
1176 inRange:range];
1177 NSNumber *underlineStyle = [attributes objectForKey:NSUnderlineStyleAttributeName];
1178 if (underlineStyle) {
1179 QColor clr (Qt::black);
1180 NSColor *color = [attributes objectForKey:NSUnderlineColorAttributeName];
1181 if (color) {
1182 clr = colorFrom(color);
1183 }
1184 QTextCharFormat format;
1185 format.setFontUnderline(true);
1186 format.setUnderlineColor(clr);
1187 attrs<<QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat,
1188 effectiveRange.location,
1189 effectiveRange.length,
1190 format);
1191 }
1192 index = effectiveRange.location + effectiveRange.length;
1193 }
1194 } else {
1195 // No attributes specified, take only the preedit text.
1196 qtText = QCFString::toQString(reinterpret_cast<CFStringRef>(aString));
1197 composingLength = qtText.length();
1198 }
1199 // Make sure that we have at least one text format.
1200 if (attrs.size() <= 1) {
1201 QTextCharFormat format;
1202 format.setFontUnderline(true);
1203 attrs<<QInputMethodEvent::Attribute(QInputMethodEvent::TextFormat,
1204 0, composingLength, format);
1205 }
1206 *composingText = qtText;
1207 QInputMethodEvent e(qtText, attrs);
1208 qt_sendSpontaneousEvent(qwidget, &e);
1209 if (!composingLength)
1210 composing = false;
1211}
1212
1213- (void) unmarkText
1214{
1215 if (composing) {
1216 QInputMethodEvent e;
1217 e.setCommitString(*composingText);
1218 qt_sendSpontaneousEvent(qwidget, &e);
1219 }
1220 composingText->clear();
1221 composing = false;
1222}
1223
1224- (BOOL) hasMarkedText
1225{
1226 return (composing ? YES: NO);
1227}
1228
1229- (void) doCommandBySelector:(SEL)aSelector
1230{
1231 Q_UNUSED(aSelector);
1232}
1233
1234- (BOOL)isComposing
1235{
1236 return composing;
1237}
1238
1239- (NSInteger) conversationIdentifier
1240{
1241 // Return a unique identifier fot this ime conversation
1242 return (NSInteger)self;
1243}
1244
1245- (NSAttributedString *) attributedSubstringFromRange:(NSRange)theRange
1246{
1247 QString selectedText(qwidget->inputMethodQuery(Qt::ImCurrentSelection).toString());
1248 if (!selectedText.isEmpty()) {
1249 QCFString string(selectedText.mid(theRange.location, theRange.length));
1250 const NSString *tmpString = reinterpret_cast<const NSString *>((CFStringRef)string);
1251 return [[[NSAttributedString alloc] initWithString:tmpString] autorelease];
1252 } else {
1253 return nil;
1254 }
1255}
1256
1257- (NSRange) markedRange
1258{
1259 NSRange range;
1260 if (composing) {
1261 range.location = 0;
1262 range.length = composingLength;
1263 } else {
1264 range.location = NSNotFound;
1265 range.length = 0;
1266 }
1267 return range;
1268}
1269
1270- (NSRange) selectedRange
1271{
1272 NSRange selRange;
1273 QString selectedText(qwidget->inputMethodQuery(Qt::ImCurrentSelection).toString());
1274 if (!selectedText.isEmpty()) {
1275 // Consider only the selected text.
1276 selRange.location = 0;
1277 selRange.length = selectedText.length();
1278 } else {
1279 // No selected text.
1280 selRange.location = NSNotFound;
1281 selRange.length = 0;
1282 }
1283 return selRange;
1284
1285}
1286
1287- (NSRect) firstRectForCharacterRange:(NSRange)theRange
1288{
1289 Q_UNUSED(theRange);
1290 // The returned rect is always based on the internal cursor.
1291 QRect mr(qwidget->inputMethodQuery(Qt::ImMicroFocus).toRect());
1292 QPoint mp(qwidget->mapToGlobal(QPoint(mr.bottomLeft())));
1293 NSRect rect ;
1294 rect.origin.x = mp.x();
1295 rect.origin.y = flipYCoordinate(mp.y());
1296 rect.size.width = mr.width();
1297 rect.size.height = mr.height();
1298 return rect;
1299}
1300
1301- (NSUInteger)characterIndexForPoint:(NSPoint)thePoint
1302{
1303 // We dont support cursor movements using mouse while composing.
1304 Q_UNUSED(thePoint);
1305 return NSNotFound;
1306}
1307
1308- (NSArray*) validAttributesForMarkedText
1309{
1310 if (!qwidget->testAttribute(Qt::WA_InputMethodEnabled))
1311 return nil; // Not sure if that's correct, but it's saves a malloc.
1312
1313 // Support only underline color/style.
1314 return [NSArray arrayWithObjects:NSUnderlineColorAttributeName,
1315 NSUnderlineStyleAttributeName, nil];
1316}
1317@end
1318
1319QT_BEGIN_NAMESPACE
1320void QMacInputContext::reset()
1321{
1322 QWidget *w = QInputContext::focusWidget();
1323 if (w) {
1324 NSView *view = qt_mac_nativeview_for(w);
1325 if ([view isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaView) class]]) {
1326 QMacCocoaAutoReleasePool pool;
1327 QT_MANGLE_NAMESPACE(QCocoaView) *qc = static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(view);
1328 NSInputManager *currentIManager = [NSInputManager currentInputManager];
1329 if (currentIManager) {
1330 [currentIManager markedTextAbandoned:view];
1331 [qc unmarkText];
1332 }
1333 }
1334 }
1335}
1336
1337bool QMacInputContext::isComposing() const
1338{
1339 QWidget *w = QInputContext::focusWidget();
1340 if (w) {
1341 NSView *view = qt_mac_nativeview_for(w);
1342 if ([view isKindOfClass:[QT_MANGLE_NAMESPACE(QCocoaView) class]]) {
1343 return [static_cast<QT_MANGLE_NAMESPACE(QCocoaView) *>(view) isComposing];
1344 }
1345 }
1346 return false;
1347}
1348
1349extern bool qt_mac_in_drag;
1350void * /*NSImage */qt_mac_create_nsimage(const QPixmap &pm);
1351static const int default_pm_hotx = -2;
1352static const int default_pm_hoty = -16;
1353static const char* default_pm[] = {
1354 "13 9 3 1",
1355 ". c None",
1356 " c #000000",
1357 "X c #FFFFFF",
1358 "X X X X X X X",
1359 " X X X X X X ",
1360 "X ......... X",
1361 " X.........X ",
1362 "X ......... X",
1363 " X.........X ",
1364 "X ......... X",
1365 " X X X X X X ",
1366 "X X X X X X X",
1367};
1368
1369Qt::DropAction QDragManager::drag(QDrag *o)
1370{
1371 if(qt_mac_in_drag) { //just make sure..
1372 qWarning("Qt: Internal error: WH0A, unexpected condition reached");
1373 return Qt::IgnoreAction;
1374 }
1375 if(object == o)
1376 return Qt::IgnoreAction;
1377 /* At the moment it seems clear that Mac OS X does not want to drag with a non-left button
1378 so we just bail early to prevent it */
1379 if(!(GetCurrentEventButtonState() & kEventMouseButtonPrimary))
1380 return Qt::IgnoreAction;
1381
1382 if(object) {
1383 dragPrivate()->source->removeEventFilter(this);
1384 cancel();
1385 beingCancelled = false;
1386 }
1387
1388 object = o;
1389 dragPrivate()->target = 0;
1390
1391#ifndef QT_NO_ACCESSIBILITY
1392 QAccessible::updateAccessibility(this, 0, QAccessible::DragDropStart);
1393#endif
1394
1395 // setup the data
1396 QMacPasteboard dragBoard((CFStringRef) NSDragPboard, QMacPasteboardMime::MIME_DND);
1397 dragPrivate()->data->setData(QLatin1String("application/x-qt-mime-type-name"), QByteArray());
1398 dragBoard.setMimeData(dragPrivate()->data);
1399
1400 // create the image
1401 QPoint hotspot;
1402 QPixmap pix = dragPrivate()->pixmap;
1403 if(pix.isNull()) {
1404 if(dragPrivate()->data->hasText() || dragPrivate()->data->hasUrls()) {
1405 // get the string
1406 QString s = dragPrivate()->data->hasText() ? dragPrivate()->data->text()
1407 : dragPrivate()->data->urls().first().toString();
1408 if(s.length() > 26)
1409 s = s.left(23) + QChar(0x2026);
1410 if(!s.isEmpty()) {
1411 // draw it
1412 QFont f(qApp->font());
1413 f.setPointSize(12);
1414 QFontMetrics fm(f);
1415 QPixmap tmp(fm.width(s), fm.height());
1416 if(!tmp.isNull()) {
1417 QPainter p(&tmp);
1418 p.fillRect(0, 0, tmp.width(), tmp.height(), Qt::color0);
1419 p.setPen(Qt::color1);
1420 p.setFont(f);
1421 p.drawText(0, fm.ascent(), s);
1422 // save it
1423 pix = tmp;
1424 hotspot = QPoint(tmp.width() / 2, tmp.height() / 2);
1425 }
1426 }
1427 } else {
1428 pix = QPixmap(default_pm);
1429 hotspot = QPoint(default_pm_hotx, default_pm_hoty);
1430 }
1431 } else {
1432 hotspot = dragPrivate()->hotspot;
1433 }
1434 // convert the image to NSImage.
1435 NSImage *image = (NSImage *)qt_mac_create_nsimage(pix);
1436 [image retain];
1437 DnDParams dndParams = *[QT_MANGLE_NAMESPACE(QCocoaView) currentMouseEvent];
1438 // save supported actions
1439 [dndParams.view setSupportedActions: qt_mac_mapDropActions(dragPrivate()->possible_actions)];
1440 NSPoint imageLoc = {dndParams.localPoint.x - hotspot.x(),
1441 dndParams.localPoint.y + pix.height() - hotspot.y()};
1442 NSSize mouseOffset = {0.0, 0.0};
1443 NSPasteboard *pboard = [NSPasteboard pasteboardWithName:NSDragPboard];
1444 NSPoint windowPoint = [dndParams.theEvent locationInWindow];
1445 dragPrivate()->executed_action = Qt::ActionMask;
1446 // do the drag
1447 [dndParams.view retain];
1448 [dndParams.view dragImage:image
1449 at:imageLoc
1450 offset:mouseOffset
1451 event:dndParams.theEvent
1452 pasteboard:pboard
1453 source:dndParams.view
1454 slideBack:YES];
1455 // reset the implicit grab widget when drag ends because we will not
1456 // receive the mouse release event when DND is active.
1457 qt_button_down = 0;
1458 [dndParams.view release];
1459 [image release];
1460 dragPrivate()->executed_action = Qt::IgnoreAction;
1461 object = 0;
1462 Qt::DropAction performedAction(qt_mac_mapNSDragOperation(qMacDnDParams()->performedAction));
1463 // do post drag processing, if required.
1464 if(performedAction != Qt::IgnoreAction) {
1465 // check if the receiver points us to a file location.
1466 // if so, we need to do the file copy/move ourselves.
1467 QCFType<CFURLRef> pasteLocation = 0;
1468 PasteboardCopyPasteLocation(dragBoard.pasteBoard(), &pasteLocation);
1469 if (pasteLocation) {
1470 QList<QUrl> urls = o->mimeData()->urls();
1471 for (int i = 0; i < urls.size(); ++i) {
1472 QUrl fromUrl = urls.at(i);
1473 QString filename = QFileInfo(fromUrl.path()).fileName();
1474 QUrl toUrl(QCFString::toQString(CFURLGetString(pasteLocation)) + filename);
1475 if (performedAction == Qt::MoveAction)
1476 QFile::rename(fromUrl.path(), toUrl.path());
1477 else if (performedAction == Qt::CopyAction)
1478 QFile::copy(fromUrl.path(), toUrl.path());
1479 }
1480 }
1481 }
1482 return performedAction;
1483}
1484
1485QT_END_NAMESPACE
1486
1487#endif // QT_MAC_USE_COCOA
Note: See TracBrowser for help on using the repository browser.