1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/cocoa/dataview.mm
7 // RCS-ID: $Id: dataview.mm$
9 // Licence: wxWindows licence
10 ///////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
14 #if (wxUSE_DATAVIEWCTRL == 1) && !defined(wxUSE_GENERICDATAVIEWCTRL)
18 #include "wx/toplevel.h"
20 #include "wx/settings.h"
24 #include "wx/osx/cocoa/dataview.h"
25 #include "wx/osx/private.h"
26 #include "wx/renderer.h"
29 // ============================================================================
30 // Constants used locally
31 // ============================================================================
32 #define DataViewPboardType @"OutlineViewItem"
34 // ============================================================================
35 // Classes used locally in dataview.mm
36 // ============================================================================
37 @interface wxCustomRendererObject : NSObject <NSCopying>
40 NSTableColumn* tableColumn; // not owned by the class
42 wxDataViewCustomRenderer* customRenderer; // not owned by the class
44 wxPointerObject* item; // not owned by the class
51 -(id) initWithRenderer:(wxDataViewCustomRenderer*)initRenderer item:(wxPointerObject*)initItem column:(NSTableColumn*)initTableColumn;
55 @implementation wxCustomRendererObject
64 customRenderer = NULL;
71 -(id) initWithRenderer:(wxDataViewCustomRenderer*)initRenderer item:(wxPointerObject*)initItem column:(NSTableColumn*)initTableColumn
76 customRenderer = initRenderer;
78 tableColumn = initTableColumn;
83 -(id) copyWithZone:(NSZone*)zone
85 wxCustomRendererObject* copy;
88 copy = [[[self class] allocWithZone:zone] init];
89 copy->customRenderer = customRenderer;
91 copy->tableColumn = tableColumn;
98 // ============================================================================
99 // Functions used locally in dataview.mm
100 // ============================================================================
101 static NSInteger CompareItems(id item1, id item2, void* context)
103 NSArray* const sortDescriptors = (NSArray*) context;
105 NSUInteger const noOfDescriptors = [sortDescriptors count];
107 NSInteger result(NSOrderedAscending);
110 for (NSUInteger i=0; i<noOfDescriptors; ++i)
112 // constant definition for abbreviational purposes:
113 wxSortDescriptorObject* const sortDescriptor = (wxSortDescriptorObject*)[sortDescriptors objectAtIndex:i];
115 int wxComparisonResult;
117 wxComparisonResult = [sortDescriptor modelPtr]->Compare(wxDataViewItem([((wxPointerObject*) item1) pointer]),
118 wxDataViewItem([((wxPointerObject*) item2) pointer]),
119 [sortDescriptor columnPtr]->GetModelColumn(),
120 [sortDescriptor ascending] == YES);
121 if (wxComparisonResult < 0)
123 result = NSOrderedAscending;
126 else if (wxComparisonResult > 0)
128 result = NSOrderedDescending;
132 result = NSOrderedSame;
137 static NSTextAlignment ConvertToNativeHorizontalTextAlignment(int alignment)
139 if (alignment & wxALIGN_CENTER_HORIZONTAL) // center alignment is chosen also if alignment is equal to -1
140 return NSCenterTextAlignment;
141 else if (alignment & wxALIGN_RIGHT)
142 return NSRightTextAlignment;
144 return NSLeftTextAlignment;
147 static NSTableColumn* CreateNativeColumn(wxDataViewColumn const* columnPtr)
149 NSTableColumn* nativeColumn([[NSTableColumn alloc] initWithIdentifier:[[[wxPointerObject alloc] initWithPointer:const_cast<wxDataViewColumn*>(columnPtr)] autorelease]]);
152 // initialize the native column:
153 if ((nativeColumn != NULL) && (columnPtr->GetRenderer() != NULL))
155 // setting the size related parameters:
156 if (columnPtr->IsResizeable())
158 [nativeColumn setResizingMask:NSTableColumnUserResizingMask];
159 [nativeColumn setMinWidth:columnPtr->GetMinWidth()];
160 [nativeColumn setMaxWidth:columnPtr->GetMaxWidth()];
164 [nativeColumn setResizingMask:NSTableColumnNoResizing];
165 [nativeColumn setMinWidth:columnPtr->GetWidth()];
166 [nativeColumn setMaxWidth:columnPtr->GetWidth()];
168 [nativeColumn setWidth:columnPtr->GetWidth()];
169 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
170 // setting the visibility:
171 [nativeColumn setHidden:static_cast<BOOL>(columnPtr->IsHidden())];
173 // setting the header:
174 [[nativeColumn headerCell] setAlignment:ConvertToNativeHorizontalTextAlignment(columnPtr->GetAlignment())];
175 [[nativeColumn headerCell] setStringValue:[[wxCFStringRef(columnPtr->GetTitle()).AsNSString() retain] autorelease]];
176 // setting data cell's properties:
177 [[nativeColumn dataCell] setWraps:NO];
178 // setting the default data cell:
179 [nativeColumn setDataCell:columnPtr->GetRenderer()->GetNativeData()->GetColumnCell()];
180 // setting the editablility:
181 bool const dataCellIsEditable = (columnPtr->GetRenderer()->GetMode() == wxDATAVIEW_CELL_EDITABLE);
183 [nativeColumn setEditable:dataCellIsEditable];
184 [[nativeColumn dataCell] setEditable:dataCellIsEditable];
190 // ============================================================================
191 // Public helper functions for dataview implementation on OSX
192 // ============================================================================
193 wxWidgetImplType* CreateDataView(wxWindowMac* wxpeer, wxWindowMac* WXUNUSED(parent), wxWindowID WXUNUSED(id), wxPoint const& pos, wxSize const& size,
194 long style, long WXUNUSED(extraStyle))
196 return new wxCocoaDataViewControl(wxpeer,pos,size,style);
199 // ============================================================================
201 // ============================================================================
203 // This is a helper class to store a pointer in an object.
205 @implementation wxPointerObject
207 // object initialization
213 self->pointer = NULL;
217 -(id) initWithPointer:(void*) initPointer
221 self->pointer = initPointer;
226 // inherited methods from NSObject
228 -(BOOL) isEqual:(id)object
230 return (object != nil) && ([object isKindOfClass:[wxPointerObject class]]) && (pointer == [((wxPointerObject*) object) pointer]);
235 return (NSUInteger) pointer;
246 -(void) setPointer:(void*) newPointer
248 pointer = newPointer;
253 // ============================================================================
254 // wxSortDescriptorObject
255 // ============================================================================
256 @implementation wxSortDescriptorObject
271 -(id) initWithModelPtr:(wxDataViewModel*)initModelPtr sortingColumnPtr:(wxDataViewColumn*)initColumnPtr ascending:(BOOL)sortAscending
273 self = [super initWithKey:@"dummy" ascending:sortAscending];
276 columnPtr = initColumnPtr;
277 modelPtr = initModelPtr;
282 -(id) copyWithZone:(NSZone*)zone
284 wxSortDescriptorObject* copy;
287 copy = [super copyWithZone:zone];
288 copy->columnPtr = columnPtr;
289 copy->modelPtr = modelPtr;
295 // access to model column's index
297 -(wxDataViewColumn*) columnPtr
302 -(wxDataViewModel*) modelPtr
307 -(void) setColumnPtr:(wxDataViewColumn*)newColumnPtr
309 columnPtr = newColumnPtr;
312 -(void) setModelPtr:(wxDataViewModel*)newModelPtr
314 modelPtr = newModelPtr;
319 // ============================================================================
320 // wxCocoaOutlineDataSource
321 // ============================================================================
322 @implementation wxCocoaOutlineDataSource
325 // constructors / destructor
332 implementation = NULL;
335 currentParentItem = nil;
337 children = [[NSMutableArray alloc] init];
338 items = [[NSMutableSet alloc] init];
345 [currentParentItem release];
354 // methods of informal protocol:
356 -(BOOL) outlineView:(NSOutlineView*)outlineView acceptDrop:(id<NSDraggingInfo>)info item:(id)item childIndex:(NSInteger)index
360 NSArray* supportedTypes([NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]);
362 NSPasteboard* pasteboard([info draggingPasteboard]);
364 NSString* bestType([pasteboard availableTypeFromArray:supportedTypes]);
369 wxDataViewCtrl* const dataViewCtrlPtr(implementation->GetDataViewCtrl());
371 wxCHECK_MSG(dataViewCtrlPtr != NULL, false,_("Pointer to data view control not set correctly."));
372 wxCHECK_MSG(dataViewCtrlPtr->GetModel() != NULL,false,_("Pointer to model not set correctly."));
373 // create wxWidget's event:
374 wxDataViewEvent dataViewEvent(wxEVT_COMMAND_DATAVIEW_ITEM_DROP,dataViewCtrlPtr->GetId());
376 dataViewEvent.SetEventObject(dataViewCtrlPtr);
377 dataViewEvent.SetItem(wxDataViewItem([((wxPointerObject*) item) pointer]));
378 dataViewEvent.SetModel(dataViewCtrlPtr->GetModel());
379 if ([bestType compare:DataViewPboardType] == NSOrderedSame)
381 NSArray* dataArray((NSArray*)[pasteboard propertyListForType:DataViewPboardType]);
382 NSUInteger indexDraggedItem, noOfDraggedItems([dataArray count]);
384 indexDraggedItem = 0;
385 while (indexDraggedItem < noOfDraggedItems)
387 wxDataObjectComposite* dataObjects(implementation->GetDnDDataObjects((NSData*)[dataArray objectAtIndex:indexDraggedItem]));
389 if ((dataObjects != NULL) && (dataObjects->GetFormatCount() > 0))
391 wxMemoryBuffer buffer;
393 // copy data into data object:
394 dataViewEvent.SetDataObject(dataObjects);
395 dataViewEvent.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
396 // copy data into buffer:
397 dataObjects->GetDataHere(dataViewEvent.GetDataFormat().GetType(),buffer.GetWriteBuf(dataViewEvent.GetDataSize()));
398 buffer.UngetWriteBuf(dataViewEvent.GetDataSize());
399 dataViewEvent.SetDataBuffer(buffer.GetData());
400 // finally, send event:
401 if (dataViewCtrlPtr->HandleWindowEvent(dataViewEvent) && dataViewEvent.IsAllowed())
403 dragSuccessful = true;
408 dragSuccessful = true;
409 indexDraggedItem = noOfDraggedItems; // stop loop
414 dragSuccessful = false;
415 indexDraggedItem = noOfDraggedItems; // stop loop
423 CFDataRef osxData; // needed to convert internally used UTF-16 representation to a UTF-8 representation
424 wxDataObjectComposite* dataObjects (new wxDataObjectComposite());
425 wxTextDataObject* textDataObject(new wxTextDataObject());
427 osxData = ::CFStringCreateExternalRepresentation(kCFAllocatorDefault,(CFStringRef)[pasteboard stringForType:NSStringPboardType],kCFStringEncodingUTF8,32);
428 if (textDataObject->SetData(::CFDataGetLength(osxData),::CFDataGetBytePtr(osxData)))
429 dataObjects->Add(textDataObject);
431 delete textDataObject;
432 // send event if data could be copied:
433 if (dataObjects->GetFormatCount() > 0)
435 dataViewEvent.SetDataObject(dataObjects);
436 dataViewEvent.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
437 if (dataViewCtrlPtr->HandleWindowEvent(dataViewEvent) && dataViewEvent.IsAllowed())
438 dragSuccessful = true;
440 dragSuccessful = false;
443 dragSuccessful = false;
445 ::CFRelease(osxData);
450 dragSuccessful = false;
451 return dragSuccessful;
454 -(id) outlineView:(NSOutlineView*)outlineView child:(NSInteger)index ofItem:(id)item
456 if ((item == currentParentItem) && (index < ((NSInteger) [self getChildCount])))
457 return [self getChild:index];
460 wxDataViewItemArray dataViewChildren;
462 wxCHECK_MSG(model != NULL,0,_("Valid model in data source does not exist."));
463 (void) model->GetChildren((item == nil) ? wxDataViewItem() : wxDataViewItem([((wxPointerObject*) item) pointer]),dataViewChildren);
464 [self bufferItem:item withChildren:&dataViewChildren];
465 if ([sortDescriptors count] > 0)
466 [children sortUsingFunction:CompareItems context:sortDescriptors];
467 return [self getChild:index];
471 -(BOOL) outlineView:(NSOutlineView*)outlineView isItemExpandable:(id)item
473 wxCHECK_MSG(model != NULL,0,_("Valid model in data source does not exist."));
474 return model->IsContainer(wxDataViewItem([((wxPointerObject*) item) pointer]));
477 -(NSInteger) outlineView:(NSOutlineView*)outlineView numberOfChildrenOfItem:(id)item
479 NSInteger noOfChildren;
481 wxDataViewItemArray dataViewChildren;
484 wxCHECK_MSG(model != NULL,0,_("Valid model in data source does not exist."));
485 noOfChildren = model->GetChildren((item == nil) ? wxDataViewItem() : wxDataViewItem([((wxPointerObject*) item) pointer]),dataViewChildren);
486 [self bufferItem:item withChildren:&dataViewChildren];
487 if ([sortDescriptors count] > 0)
488 [children sortUsingFunction:CompareItems context:sortDescriptors];
492 -(id) outlineView:(NSOutlineView*)outlineView objectValueForTableColumn:(NSTableColumn*)tableColumn byItem:(id)item
494 wxDataViewColumn* dataViewColumnPtr(reinterpret_cast<wxDataViewColumn*>([[tableColumn identifier] pointer]));
496 wxDataViewItem dataViewItem([((wxPointerObject*) item) pointer]);
501 wxCHECK_MSG(model != NULL,0,_("Valid model in data source does not exist."));
502 model->GetValue(value,dataViewItem,dataViewColumnPtr->GetModelColumn());
503 dataViewColumnPtr->GetRenderer()->SetValue(value);
507 -(void) outlineView:(NSOutlineView*)outlineView setObjectValue:(id)object forTableColumn:(NSTableColumn*)tableColumn byItem:(id)item
509 wxDataViewColumn* dataViewColumnPtr(reinterpret_cast<wxDataViewColumn*>([[tableColumn identifier] pointer]));
511 wxDataViewItem dataViewItem([((wxPointerObject*) item) pointer]);
514 if (((dynamic_cast<wxDataViewTextRenderer*>(dataViewColumnPtr->GetRenderer()) != NULL) || (dynamic_cast<wxDataViewIconTextRenderer*>(dataViewColumnPtr->GetRenderer()) != NULL)) &&
515 ([object isKindOfClass:[NSString class]] == YES))
517 model->SetValue(wxVariant(wxCFStringRef([((NSString*) object) retain]).AsString()),dataViewItem,dataViewColumnPtr->GetModelColumn()); // the string has to be retained before being passed to wxCFStringRef
518 model->ValueChanged(dataViewItem,dataViewColumnPtr->GetModelColumn());
520 else if (dynamic_cast<wxDataViewChoiceRenderer*>(dataViewColumnPtr->GetRenderer()) != NULL)
522 if ([object isKindOfClass:[NSNumber class]] == YES)
524 model->SetValue(wxVariant(dynamic_cast<wxDataViewChoiceRenderer*>(dataViewColumnPtr->GetRenderer())->GetChoice([((NSNumber*) object) intValue])),
525 dataViewItem,dataViewColumnPtr->GetModelColumn());
526 model->ValueChanged(dataViewItem,dataViewColumnPtr->GetModelColumn());
528 else if ([object isKindOfClass:[NSString class]] == YES) // do not know if this case can occur but initializing using strings works
530 model->SetValue(wxVariant(wxCFStringRef((NSString*) object).AsString()),dataViewItem,dataViewColumnPtr->GetModelColumn());
531 model->ValueChanged(dataViewItem,dataViewColumnPtr->GetModelColumn());
534 else if ((dynamic_cast<wxDataViewDateRenderer*>(dataViewColumnPtr->GetRenderer()) != NULL) && ([object isKindOfClass:[NSDate class]] == YES))
536 wxDateTime wxDateTimeValue(1,wxDateTime::Jan,1970);
540 seconds.Assign([((NSDate*) object) timeIntervalSince1970]); // get the number of seconds since 1970-01-01 UTC and this is
541 // the only way to convert a double to a wxLongLong
542 // the user has entered a date in the local timezone but seconds contains the number of seconds from date in the local timezone since 1970-01-01 UTC;
543 // therefore, the timezone information has to be transferred to wxWidgets, too:
544 wxDateTimeValue.Add(wxTimeSpan(0,0,seconds));
545 wxDateTimeValue.MakeFromTimezone(wxDateTime::UTC);
546 model->SetValue(wxVariant(wxDateTimeValue),dataViewItem,dataViewColumnPtr->GetModelColumn());
547 model->ValueChanged(dataViewItem,dataViewColumnPtr->GetModelColumn());
549 else if ((dynamic_cast<wxDataViewToggleRenderer*>(dataViewColumnPtr->GetRenderer()) != NULL) && ([object isKindOfClass:[NSNumber class]] == YES))
551 model->SetValue(wxVariant((bool) [((NSNumber*) object) boolValue]),dataViewItem,dataViewColumnPtr->GetModelColumn());
552 model->ValueChanged(dataViewItem,dataViewColumnPtr->GetModelColumn());
556 -(void) outlineView:(NSOutlineView*)outlineView sortDescriptorsDidChange:(NSArray*)oldDescriptors
557 // Warning: the new sort descriptors are guaranteed to be only of type NSSortDescriptor! Therefore, the
558 // sort descriptors for the data source have to be converted.
560 NSArray* newDescriptors;
562 NSMutableArray* wxSortDescriptors;
564 NSUInteger noOfDescriptors;
566 wxDataViewCtrl* const dataViewCtrlPtr = implementation->GetDataViewCtrl();
569 // convert NSSortDescriptors to wxSortDescriptorObjects:
570 newDescriptors = [outlineView sortDescriptors];
571 noOfDescriptors = [newDescriptors count];
572 wxSortDescriptors = [NSMutableArray arrayWithCapacity:noOfDescriptors];
573 for (NSUInteger i=0; i<noOfDescriptors; ++i)
575 // constant definition for abbreviational purposes:
576 NSSortDescriptor* const newDescriptor = [newDescriptors objectAtIndex:i];
578 [wxSortDescriptors addObject:[[[wxSortDescriptorObject alloc] initWithModelPtr:model
579 sortingColumnPtr:dataViewCtrlPtr->GetColumn([[newDescriptor key] intValue])
580 ascending:[newDescriptor ascending]] autorelease]];
582 [[outlineView dataSource] setSortDescriptors:wxSortDescriptors];
584 // send first the event to wxWidgets that the sorting has changed so that the program can do special actions before
585 // the sorting actually starts:
586 wxDataViewEvent dataViewEvent(wxEVT_COMMAND_DATAVIEW_COLUMN_SORTED,dataViewCtrlPtr->GetId()); // variable defintion
588 dataViewEvent.SetEventObject(dataViewCtrlPtr);
589 if (noOfDescriptors > 0)
591 // constant definition for abbreviational purposes:
592 wxDataViewColumn* const dataViewColumnPtr = [[wxSortDescriptors objectAtIndex:0] columnPtr];
594 dataViewEvent.SetColumn(dataViewCtrlPtr->GetColumnPosition(dataViewColumnPtr));
595 dataViewEvent.SetDataViewColumn(dataViewColumnPtr);
597 dataViewCtrlPtr->GetEventHandler()->ProcessEvent(dataViewEvent);
599 // start re-ordering the data;
600 // children's buffer must be cleared first because it contains the old order:
601 [self clearChildren];
602 // sorting is done while reloading the data:
603 [outlineView reloadData];
606 -(NSDragOperation) outlineView:(NSOutlineView*)outlineView validateDrop:(id<NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
608 NSArray* supportedTypes([NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]);
610 NSDragOperation dragOperation;
612 NSPasteboard* pasteboard([info draggingPasteboard]);
614 NSString* bestType([pasteboard availableTypeFromArray:supportedTypes]);
619 wxDataViewCtrl* const dataViewCtrlPtr(implementation->GetDataViewCtrl());
621 wxCHECK_MSG(dataViewCtrlPtr != NULL, false,_("Pointer to data view control not set correctly."));
622 wxCHECK_MSG(dataViewCtrlPtr->GetModel() != NULL,false,_("Pointer to model not set correctly."));
623 // create wxWidget's event:
624 wxDataViewEvent dataViewEvent(wxEVT_COMMAND_DATAVIEW_ITEM_DROP_POSSIBLE,dataViewCtrlPtr->GetId());
626 dataViewEvent.SetEventObject(dataViewCtrlPtr);
627 dataViewEvent.SetItem(wxDataViewItem([((wxPointerObject*) item) pointer]));
628 dataViewEvent.SetModel(dataViewCtrlPtr->GetModel());
629 if ([bestType compare:DataViewPboardType] == NSOrderedSame)
631 NSArray* dataArray((NSArray*)[pasteboard propertyListForType:DataViewPboardType]);
632 NSUInteger indexDraggedItem, noOfDraggedItems([dataArray count]);
634 indexDraggedItem = 0;
635 while (indexDraggedItem < noOfDraggedItems)
637 wxDataObjectComposite* dataObjects(implementation->GetDnDDataObjects((NSData*)[dataArray objectAtIndex:indexDraggedItem]));
639 if ((dataObjects != NULL) && (dataObjects->GetFormatCount() > 0))
641 wxMemoryBuffer buffer;
643 // copy data into data object:
644 dataViewEvent.SetDataObject(dataObjects);
645 dataViewEvent.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
646 // copy data into buffer:
647 dataObjects->GetDataHere(dataViewEvent.GetDataFormat().GetType(),buffer.GetWriteBuf(dataViewEvent.GetDataSize()));
648 buffer.UngetWriteBuf(dataViewEvent.GetDataSize());
649 dataViewEvent.SetDataBuffer(buffer.GetData());
650 // finally, send event:
651 if (dataViewCtrlPtr->HandleWindowEvent(dataViewEvent) && dataViewEvent.IsAllowed())
653 dragOperation = NSDragOperationEvery;
658 dragOperation = NSDragOperationNone;
659 indexDraggedItem = noOfDraggedItems; // stop loop
664 dragOperation = NSDragOperationNone;
665 indexDraggedItem = noOfDraggedItems; // stop loop
673 CFDataRef osxData; // needed to convert internally used UTF-16 representation to a UTF-8 representation
674 wxDataObjectComposite* dataObjects (new wxDataObjectComposite());
675 wxTextDataObject* textDataObject(new wxTextDataObject());
677 osxData = ::CFStringCreateExternalRepresentation(kCFAllocatorDefault,(CFStringRef)[pasteboard stringForType:NSStringPboardType],kCFStringEncodingUTF8,32);
678 if (textDataObject->SetData(::CFDataGetLength(osxData),::CFDataGetBytePtr(osxData)))
679 dataObjects->Add(textDataObject);
681 delete textDataObject;
682 // send event if data could be copied:
683 if (dataObjects->GetFormatCount() > 0)
685 dataViewEvent.SetDataObject(dataObjects);
686 dataViewEvent.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
687 if (dataViewCtrlPtr->HandleWindowEvent(dataViewEvent) && dataViewEvent.IsAllowed())
688 dragOperation = NSDragOperationEvery;
690 dragOperation = NSDragOperationNone;
693 dragOperation = NSDragOperationNone;
695 ::CFRelease(osxData);
700 dragOperation = NSDragOperationNone;
701 return dragOperation;
704 -(BOOL) outlineView:(NSOutlineView*)outlineView writeItems:(NSArray*)writeItems toPasteboard:(NSPasteboard*)pasteboard
705 // the pasteboard will be filled up with an array containing the data as returned by the events (including the data type)
706 // and a concatenation of text (string) data; the text data will only be put onto the pasteboard if for all items a
707 // string representation exists
709 wxDataViewCtrl* const dataViewCtrlPtr = implementation->GetDataViewCtrl();
711 wxDataViewItemArray dataViewItems;
714 wxCHECK_MSG(dataViewCtrlPtr != NULL, false,_("Pointer to data view control not set correctly."));
715 wxCHECK_MSG(dataViewCtrlPtr->GetModel() != NULL,false,_("Pointer to model not set correctly."));
717 if ([writeItems count] > 0)
719 bool dataStringAvailable(true); // a flag indicating if for all items a data string is available
720 NSMutableArray* dataArray = [[NSMutableArray arrayWithCapacity:[writeItems count]] retain]; // data of all items
721 wxString dataString; // contains the string data of all items
723 // send a begin drag event for all selected items and proceed with dragging unless the event is vetoed:
724 wxDataViewEvent dataViewEvent(wxEVT_COMMAND_DATAVIEW_ITEM_BEGIN_DRAG,dataViewCtrlPtr->GetId());
726 dataViewEvent.SetEventObject(dataViewCtrlPtr);
727 dataViewEvent.SetModel(dataViewCtrlPtr->GetModel());
728 for (size_t itemCounter=0; itemCounter<[writeItems count]; ++itemCounter)
730 bool itemStringAvailable(false); // a flag indicating if for the current item a string is available
731 wxDataObjectComposite* itemObject(new wxDataObjectComposite()); // data object for current item
732 wxString itemString; // contains the TAB concatenated data of an item
734 dataViewEvent.SetItem(wxDataViewItem([((wxPointerObject*) [writeItems objectAtIndex:itemCounter]) pointer]));
735 itemString = ::ConcatenateDataViewItemValues(dataViewCtrlPtr,dataViewEvent.GetItem());
736 itemObject->Add(new wxTextDataObject(itemString));
737 dataViewEvent.SetDataObject(itemObject);
738 // check if event has not been vetoed:
739 if (dataViewCtrlPtr->HandleWindowEvent(dataViewEvent) && dataViewEvent.IsAllowed() && (dataViewEvent.GetDataObject()->GetFormatCount() > 0))
741 // constant definition for abbreviational purposes:
742 size_t const noOfFormats = dataViewEvent.GetDataObject()->GetFormatCount();
743 // variable definition and initialization:
744 wxDataFormat* dataFormats(new wxDataFormat[noOfFormats]);
746 dataViewEvent.GetDataObject()->GetAllFormats(dataFormats,wxDataObject::Get);
747 for (size_t formatCounter=0; formatCounter<noOfFormats; ++formatCounter)
749 // constant definitions for abbreviational purposes:
750 wxDataFormatId const idDataFormat = dataFormats[formatCounter].GetType();
751 size_t const dataSize = dataViewEvent.GetDataObject()->GetDataSize(idDataFormat);
752 size_t const dataBufferSize = sizeof(wxDataFormatId)+dataSize;
753 // variable definitions (used in all case statements):
754 wxMemoryBuffer dataBuffer(dataBufferSize);
756 dataBuffer.AppendData(&idDataFormat,sizeof(wxDataFormatId));
757 switch (idDataFormat)
760 if (!itemStringAvailable) // otherwise wxDF_UNICODETEXT already filled up the string; and the UNICODE representation has priority
762 dataViewEvent.GetDataObject()->GetDataHere(wxDF_TEXT,dataBuffer.GetAppendBuf(dataSize));
763 dataBuffer.UngetAppendBuf(dataSize);
764 [dataArray addObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
765 itemString = wxString(reinterpret_cast<char const*>(dataBuffer.GetData())+sizeof(wxDataFormatId),wxConvLocal);
766 itemStringAvailable = true;
769 case wxDF_UNICODETEXT:
771 dataViewEvent.GetDataObject()->GetDataHere(wxDF_UNICODETEXT,dataBuffer.GetAppendBuf(dataSize));
772 dataBuffer.UngetAppendBuf(dataSize);
773 if (itemStringAvailable) // does an object already exist as an ASCII text (see wxDF_TEXT case statement)?
774 [dataArray replaceObjectAtIndex:itemCounter withObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
776 [dataArray addObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
777 itemString = wxString::FromUTF8(reinterpret_cast<char const*>(dataBuffer.GetData())+sizeof(wxDataFormatId),dataSize);
778 itemStringAvailable = true;
782 wxFAIL_MSG(_("Data object has invalid or unsupported data format"));
787 delete[] dataFormats;
789 if (dataStringAvailable)
790 if (itemStringAvailable)
793 dataString << wxT('\n');
794 dataString << itemString;
797 dataStringAvailable = false;
803 return NO; // dragging was vetoed or no data available
806 if (dataStringAvailable)
808 wxCFStringRef osxString(dataString);
810 [pasteboard declareTypes:[NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil] owner:nil];
811 [pasteboard setPropertyList:dataArray forType:DataViewPboardType];
812 [pasteboard setString:osxString.AsNSString() forType:NSStringPboardType];
816 [pasteboard declareTypes:[NSArray arrayWithObject:DataViewPboardType] owner:nil];
817 [pasteboard setPropertyList:dataArray forType:DataViewPboardType];
822 return NO; // no items to drag (should never occur)
828 -(void) addToBuffer:(wxPointerObject*)item
830 [items addObject:item];
835 [items removeAllObjects];
838 -(wxPointerObject*) getDataViewItemFromBuffer:(wxDataViewItem const&)item
840 return [items member:[[[wxPointerObject alloc] initWithPointer:item.GetID()] autorelease]];
843 -(wxPointerObject*) getItemFromBuffer:(wxPointerObject*)item
845 return [items member:item];
848 -(BOOL) isInBuffer:(wxPointerObject*)item
850 return [items containsObject:item];
853 -(void) removeFromBuffer:(wxPointerObject*)item
855 [items removeObject:item];
861 -(void) appendChild:(wxPointerObject*)item
863 [children addObject:item];
866 -(void) clearChildren
868 [children removeAllObjects];
871 -(wxPointerObject*) getChild:(NSUInteger)index
873 return [children objectAtIndex:index];
876 -(NSUInteger) getChildCount
878 return [children count];
881 -(void) removeChild:(NSUInteger)index
883 [children removeObjectAtIndex:index];
892 [self clearChildren];
893 [self setCurrentParentItem:nil];
899 -(NSArray*) sortDescriptors
901 return sortDescriptors;
904 -(void) setSortDescriptors:(NSArray*)newSortDescriptors
906 [newSortDescriptors retain];
907 [sortDescriptors release];
908 sortDescriptors = newSortDescriptors;
912 // access to wxWidget's implementation
914 -(wxPointerObject*) currentParentItem
916 return currentParentItem;
919 -(wxCocoaDataViewControl*) implementation
921 return implementation;
924 -(wxDataViewModel*) model
929 -(void) setCurrentParentItem:(wxPointerObject*)newCurrentParentItem
931 [newCurrentParentItem retain];
932 [currentParentItem release];
933 currentParentItem = newCurrentParentItem;
936 -(void) setImplementation:(wxCocoaDataViewControl*) newImplementation
938 implementation = newImplementation;
941 -(void) setModel:(wxDataViewModel*) newModel
949 -(void) bufferItem:(wxPointerObject*)parentItem withChildren:(wxDataViewItemArray*)dataViewChildrenPtr
951 NSInteger const noOfChildren = (*dataViewChildrenPtr).GetCount();
953 [self setCurrentParentItem:parentItem];
954 [self clearChildren];
955 for (NSInteger indexChild=0; indexChild<noOfChildren; ++indexChild)
957 wxPointerObject* bufferedPointerObject;
958 wxPointerObject* newPointerObject([[wxPointerObject alloc] initWithPointer:(*dataViewChildrenPtr)[indexChild].GetID()]);
960 // The next statement and test looks strange but there is unfortunately no workaround:
961 // due to the fact that two pointer objects are identical if their pointers are identical - because the method isEqual
962 // has been overloaded - the set operation will only add a new pointer object if there is not already one in the set
963 // having the same pointer. On the other side the children's array would always add the new pointer object. This means
964 // that different pointer objects are stored in the set and array. This will finally lead to a crash as objects diverge.
965 // To solve this issue it is first tested if the child already exists in the set and if it is the case the sets object
966 // is going to be appended to the array, otheriwse the new pointer object is added to the set and array:
967 bufferedPointerObject = [self getItemFromBuffer:newPointerObject];
968 if (bufferedPointerObject == nil)
970 [items addObject:newPointerObject];
971 [children addObject:newPointerObject];
974 [children addObject:bufferedPointerObject];
975 [newPointerObject release];
981 // ============================================================================
983 // ============================================================================
984 @implementation wxCustomCell
990 wxCustomRendererObject* customRendererObject(((wxCustomRendererObject*)[self objectValue]));
993 return NSMakeSize(customRendererObject->customRenderer->GetSize().GetWidth(),customRendererObject->customRenderer->GetSize().GetHeight());
999 -(void) drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
1001 wxCustomRendererObject* customRendererObject(((wxCustomRendererObject*)[self objectValue]));
1004 // draw its own background:
1005 [[self backgroundColor] set];
1006 NSRectFill(cellFrame);
1008 (void) (customRendererObject->customRenderer->Render(wxFromNSRect(controlView,cellFrame),customRendererObject->customRenderer->GetDC(),0));
1009 customRendererObject->customRenderer->SetDC(NULL);
1012 #if 0 //TODO FIXME: MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1013 -(NSUInteger) hitTestForEvent:(NSEvent*)event inRect:(NSRect)cellFrame ofView:(NSView*)controlView
1015 NSPoint point = [controlView convertPoint:[event locationInWindow] fromView:nil];
1017 wxCustomRendererObject* customRendererObject((wxCustomRendererObject*)[self objectValue]);
1021 customRendererObject->customRenderer->LeftClick(wxFromNSPoint(controlView,point),wxFromNSRect(controlView,cellFrame),
1022 customRendererObject->GetOwner()->GetOwner(),wxDataViewItem([customRendererObject->item pointer]),
1023 [this->m_OutlineView columnWithIdentifier:[customRendererObject->GetColumnPtr() identifier]]);
1024 return NSCellHitContentArea;
1028 -(NSRect) imageRectForBounds:(NSRect)cellFrame
1033 -(NSRect) titleRectForBounds:(NSRect)cellFrame
1040 // ============================================================================
1042 // ============================================================================
1043 @implementation wxImageTextCell
1049 self = [super init];
1052 // initializing the text part:
1053 [self setLineBreakMode:NSLineBreakByTruncatingMiddle];
1054 [self setSelectable:YES];
1055 // initializing the image part:
1057 imageSize = NSMakeSize(16,16);
1058 spaceImageText = 5.0;
1064 -(id) copyWithZone:(NSZone*)zone
1066 wxImageTextCell* cell;
1069 cell = (wxImageTextCell*) [super copyWithZone:zone];
1070 cell->image = [image retain];
1071 cell->imageSize = imageSize;
1072 cell->spaceImageText = spaceImageText;
1073 cell->xImageShift = xImageShift;
1088 -(NSTextAlignment) alignment
1090 return cellAlignment;
1093 -(void) setAlignment:(NSTextAlignment)newAlignment
1095 cellAlignment = newAlignment;
1096 switch (newAlignment)
1098 case NSCenterTextAlignment:
1099 case NSLeftTextAlignment:
1100 case NSJustifiedTextAlignment:
1101 case NSNaturalTextAlignment:
1102 [super setAlignment:NSLeftTextAlignment];
1104 case NSRightTextAlignment:
1105 [super setAlignment:NSRightTextAlignment];
1108 wxFAIL_MSG(_("Unknown alignment type."));
1120 -(void) setImage:(NSImage*)newImage
1132 -(void) setImageSize:(NSSize) newImageSize
1134 imageSize = newImageSize;
1140 -(NSSize) cellImageSize
1142 return NSMakeSize(imageSize.width+xImageShift+spaceImageText,imageSize.height);
1147 NSSize cellSize([super cellSize]);
1150 if (imageSize.height > cellSize.height)
1151 cellSize.height = imageSize.height;
1152 cellSize.width += imageSize.width+xImageShift+spaceImageText;
1157 -(NSSize) cellTextSize
1159 return [super cellSize];
1165 -(void) determineCellParts:(NSRect)cellFrame imagePart:(NSRect*)imageFrame textPart:(NSRect*)textFrame
1167 switch (cellAlignment)
1169 case NSCenterTextAlignment:
1171 CGFloat const cellSpace = cellFrame.size.width-[self cellSize].width;
1173 if (cellSpace <= 0) // if the cell's frame is smaller than its contents (at least in x-direction) make sure that the image is visible:
1174 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1175 else // otherwise center the image and text in the cell's frame
1176 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText+0.5*cellSpace,NSMinXEdge);
1179 case NSJustifiedTextAlignment:
1180 case NSLeftTextAlignment:
1181 case NSNaturalTextAlignment: // how to determine the natural writing direction? TODO
1182 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1184 case NSRightTextAlignment:
1186 CGFloat const cellSpace = cellFrame.size.width-[self cellSize].width;
1188 if (cellSpace <= 0) // if the cell's frame is smaller than its contents (at least in x-direction) make sure that the image is visible:
1189 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1190 else // otherwise right align the image and text in the cell's frame
1191 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText+cellSpace,NSMinXEdge);
1195 *imageFrame = NSZeroRect;
1196 *textFrame = NSZeroRect;
1197 wxFAIL_MSG(_("Unhandled alignment type."));
1201 -(void) drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
1203 NSRect textFrame, imageFrame;
1206 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1207 // draw the image part by ourselves;
1208 // check if the cell has to draw its own background (checking is done by the parameter of the textfield's cell):
1209 if ([self drawsBackground])
1211 [[self backgroundColor] set];
1212 NSRectFill(imageFrame);
1216 // the image is slightly shifted (xImageShift) and has a fixed size but the image's frame might be larger and starts
1217 // currently on the left side of the cell's frame; therefore, the origin and the image's frame size have to be adjusted:
1218 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1220 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1221 imageFrame.size.width = imageSize.width;
1225 imageFrame.origin.x += xImageShift;
1226 imageFrame.size.width -= xImageShift+spaceImageText;
1228 // ...and the image has to be centered in the y-direction:
1229 if (imageFrame.size.height > imageSize.height)
1230 imageFrame.size.height = imageSize.height;
1231 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1233 // according to the documentation the coordinate system should be flipped for NSTableViews (y-coordinate goes from top to bottom);
1234 // to draw an image correctly the coordinate system has to be transformed to a bottom-top coordinate system, otherwise the image's
1235 // content is flipped:
1236 NSAffineTransform* coordinateTransform([NSAffineTransform transform]);
1238 if ([controlView isFlipped])
1240 [coordinateTransform scaleXBy: 1.0 yBy:-1.0]; // first the coordinate system is brought back to bottom-top orientation
1241 [coordinateTransform translateXBy:0.0 yBy:(-2.0)*imageFrame.origin.y-imageFrame.size.height]; // the coordinate system has to be moved to compensate for the
1242 [coordinateTransform concat]; // other orientation and the position of the image's frame
1244 [image drawInRect:imageFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0]; // suggested method to draw the image
1245 // instead of compositeToPoint:operation:
1246 // take back previous transformation (if the view is not flipped the coordinate transformation matrix contains the identity matrix
1247 // and the next two operations do not change the content's transformation matrix):
1248 [coordinateTransform invert];
1249 [coordinateTransform concat];
1251 // let the textfield cell draw the text part:
1252 if (textFrame.size.width > [self cellTextSize].width) // for unknown reasons the alignment of the text cell is ignored; therefore change the size so that
1253 textFrame.size.width = [self cellTextSize].width; // alignment does not influence the visualization anymore
1254 [super drawWithFrame:textFrame inView:controlView];
1257 -(void) editWithFrame:(NSRect)aRect inView:(NSView*)controlView editor:(NSText*)textObj delegate:(id)anObject event:(NSEvent*)theEvent
1259 NSRect textFrame, imageFrame;
1262 [self determineCellParts:aRect imagePart:&imageFrame textPart:&textFrame];
1263 [super editWithFrame:textFrame inView:controlView editor:textObj delegate:anObject event:theEvent];
1266 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1267 -(NSUInteger) hitTestForEvent:(NSEvent*)event inRect:(NSRect)cellFrame ofView:(NSView*)controlView
1269 NSPoint point = [controlView convertPoint:[event locationInWindow] fromView:nil];
1271 NSRect imageFrame, textFrame;
1274 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1277 // the image is shifted...
1278 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1280 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1281 imageFrame.size.width = imageSize.width;
1285 imageFrame.origin.x += xImageShift;
1286 imageFrame.size.width -= xImageShift+spaceImageText;
1289 if (imageFrame.size.height > imageSize.height)
1290 imageFrame.size.height = imageSize.height;
1291 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1292 // If the point is in the image rect, then it is a content hit (see documentation for hitTestForEvent:inRect:ofView):
1293 if (NSMouseInRect(point, imageFrame, [controlView isFlipped]))
1294 return NSCellHitContentArea;
1296 // if the image was not hit let's try the text part:
1297 if (textFrame.size.width > [self cellTextSize].width) // for unknown reasons the alignment of the text cell is ignored; therefore change the size so that
1298 textFrame.size.width = [self cellTextSize].width; // alignment does not influence the visualization anymore
1299 return [super hitTestForEvent:event inRect:textFrame ofView:controlView];
1303 -(NSRect) imageRectForBounds:(NSRect)cellFrame
1305 NSRect textFrame, imageFrame;
1308 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1309 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1311 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1312 imageFrame.size.width = imageSize.width;
1316 imageFrame.origin.x += xImageShift;
1317 imageFrame.size.width -= xImageShift+spaceImageText;
1320 if (imageFrame.size.height > imageSize.height)
1321 imageFrame.size.height = imageSize.height;
1322 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1327 -(void) selectWithFrame:(NSRect)aRect inView:(NSView*)controlView editor:(NSText*)textObj delegate:(id)anObject start:(NSInteger)selStart length:(NSInteger)selLength
1329 NSRect textFrame, imageFrame;
1332 [self determineCellParts:aRect imagePart:&imageFrame textPart:&textFrame];
1333 [super selectWithFrame:textFrame inView:controlView editor:textObj delegate:anObject start:selStart length:selLength];
1336 -(NSRect) titleRectForBounds:(NSRect)cellFrame
1338 NSRect textFrame, imageFrame;
1341 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1347 // ============================================================================
1348 // wxCocoaOutlineView
1349 // ============================================================================
1350 @implementation wxCocoaOutlineView
1353 // initializers / destructor
1357 self = [super init];
1361 [self registerForDraggedTypes:[NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]];
1362 [self setDelegate:self];
1363 [self setDoubleAction:@selector(actionDoubleClick:)];
1364 [self setDraggingSourceOperationMask:NSDragOperationEvery forLocal:NO];
1365 [self setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
1366 [self setTarget:self];
1372 // access to wxWidget's implementation
1374 -(wxCocoaDataViewControl*) implementation
1376 return implementation;
1379 -(void) setImplementation:(wxCocoaDataViewControl*) newImplementation
1381 implementation = newImplementation;
1387 -(void) actionDoubleClick:(id)sender
1388 // actually the documentation (NSTableView 2007-10-31) for doubleAction: and setDoubleAction: seems to be wrong as this action message is always sent
1389 // whether the cell is editable or not
1391 wxDataViewCtrl* const dataViewCtrlPtr = implementation->GetDataViewCtrl();
1393 wxDataViewEvent dataViewEvent(wxEVT_COMMAND_DATAVIEW_ITEM_ACTIVATED,dataViewCtrlPtr->GetId()); // variable definition
1396 dataViewEvent.SetEventObject(dataViewCtrlPtr);
1397 dataViewEvent.SetItem(wxDataViewItem([((wxPointerObject*) [self itemAtRow:[self clickedRow]]) pointer]));
1398 dataViewCtrlPtr->GetEventHandler()->ProcessEvent(dataViewEvent);
1405 -(NSMenu*) menuForEvent:(NSEvent*)theEvent
1406 // this method does not do any special menu event handling but only sends an event message; therefore, the user
1407 // has full control if a context menu should be shown or not
1409 wxDataViewCtrl* const dataViewCtrlPtr = implementation->GetDataViewCtrl();
1411 wxDataViewEvent dataViewEvent(wxEVT_COMMAND_DATAVIEW_ITEM_CONTEXT_MENU,dataViewCtrlPtr->GetId());
1413 wxDataViewItemArray selectedItems;
1416 dataViewEvent.SetEventObject(dataViewCtrlPtr);
1417 dataViewEvent.SetModel(dataViewCtrlPtr->GetModel());
1418 // get the item information;
1419 // theoretically more than one ID can be returned but the event can only handle one item, therefore only the first
1420 // item of the array is returned:
1421 if (dataViewCtrlPtr->GetSelections(selectedItems) > 0)
1422 dataViewEvent.SetItem(selectedItems[0]);
1423 dataViewCtrlPtr->GetEventHandler()->ProcessEvent(dataViewEvent);
1431 -(void) outlineView:(NSOutlineView*)outlineView mouseDownInHeaderOfTableColumn:(NSTableColumn*)tableColumn
1433 wxDataViewColumn* const dataViewColumnPtr(reinterpret_cast<wxDataViewColumn*>([[tableColumn identifier] pointer]));
1435 wxDataViewCtrl* const dataViewCtrlPtr = implementation->GetDataViewCtrl();
1437 wxDataViewEvent dataViewEvent(wxEVT_COMMAND_DATAVIEW_COLUMN_HEADER_CLICK,dataViewCtrlPtr->GetId());
1440 // first, send an event that the user clicked into a column's header:
1441 dataViewEvent.SetEventObject(dataViewCtrlPtr);
1442 dataViewEvent.SetColumn(dataViewCtrlPtr->GetColumnPosition(dataViewColumnPtr));
1443 dataViewEvent.SetDataViewColumn(dataViewColumnPtr);
1444 dataViewCtrlPtr->HandleWindowEvent(dataViewEvent);
1446 // now, check if the click may have had an influence on sorting, too;
1447 // the sorting setup has to be done only if the clicked table column is sortable and has not been used for
1448 // sorting before the click; if the column is already responsible for sorting the native control changes
1449 // the sorting direction automatically and informs the data source via outlineView:sortDescriptorsDidChange:
1450 if (dataViewColumnPtr->IsSortable() && ([tableColumn sortDescriptorPrototype] == nil))
1452 // remove the sort order from the previously sorted column table (it can also be that
1453 // no sorted column table exists):
1454 UInt32 const noOfColumns = [outlineView numberOfColumns];
1456 for (UInt32 i=0; i<noOfColumns; ++i)
1457 [[[outlineView tableColumns] objectAtIndex:i] setSortDescriptorPrototype:nil];
1458 // make column table sortable:
1459 NSArray* sortDescriptors;
1460 NSSortDescriptor* sortDescriptor;
1462 sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[NSString stringWithFormat:@"%d",[outlineView columnWithIdentifier:[tableColumn identifier]]]
1464 sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
1465 [tableColumn setSortDescriptorPrototype:sortDescriptor];
1466 [outlineView setSortDescriptors:sortDescriptors];
1467 [sortDescriptor release];
1471 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldCollapseItem:(id)item
1473 wxDataViewCtrl* const dataViewCtrlPtr = implementation->GetDataViewCtrl();
1475 wxDataViewEvent dataViewEvent(wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSING,dataViewCtrlPtr->GetId()); // variable definition
1478 dataViewEvent.SetEventObject(dataViewCtrlPtr);
1479 dataViewEvent.SetItem (wxDataViewItem([((wxPointerObject*) item) pointer]));
1480 dataViewEvent.SetModel (dataViewCtrlPtr->GetModel());
1481 // finally send the equivalent wxWidget event:
1482 dataViewCtrlPtr->GetEventHandler()->ProcessEvent(dataViewEvent);
1483 // opening the container is allowed if not vetoed:
1484 return dataViewEvent.IsAllowed();
1487 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldExpandItem:(id)item
1489 wxDataViewCtrl* const dataViewCtrlPtr = implementation->GetDataViewCtrl();
1491 wxDataViewEvent dataViewEvent(wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDING,dataViewCtrlPtr->GetId()); // variable definition
1494 dataViewEvent.SetEventObject(dataViewCtrlPtr);
1495 dataViewEvent.SetItem (wxDataViewItem([((wxPointerObject*) item) pointer]));
1496 dataViewEvent.SetModel (dataViewCtrlPtr->GetModel());
1497 // finally send the equivalent wxWidget event:
1498 dataViewCtrlPtr->GetEventHandler()->ProcessEvent(dataViewEvent);
1499 // opening the container is allowed if not vetoed:
1500 return dataViewEvent.IsAllowed();
1503 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldSelectTableColumn:(NSTableColumn*)tableColumn
1508 -(void) outlineView:(NSOutlineView*)outlineView willDisplayCell:(id)cell forTableColumn:(NSTableColumn*) tableColumn item:(id)item
1510 wxDataViewColumn* dataViewColumnPtr(reinterpret_cast<wxDataViewColumn*>([[tableColumn identifier] pointer]));
1513 dataViewColumnPtr->GetRenderer()->GetNativeData()->SetColumnPtr(tableColumn);
1514 dataViewColumnPtr->GetRenderer()->GetNativeData()->SetItem(item);
1515 dataViewColumnPtr->GetRenderer()->GetNativeData()->SetItemCell(cell);
1516 (void) dataViewColumnPtr->GetRenderer()->MacRender();
1522 -(void) outlineViewColumnDidMove:(NSNotification*)notification
1524 int const newColumnPosition = [[[notification userInfo] objectForKey:@"NSNewColumn"] intValue];
1526 wxDataViewColumn* const dataViewColumnPtr(reinterpret_cast<wxDataViewColumn*>([[[[self tableColumns] objectAtIndex:newColumnPosition] identifier] pointer]));
1528 wxDataViewCtrl* const dataViewCtrlPtr = implementation->GetDataViewCtrl();
1530 wxDataViewEvent dataViewEvent(wxEVT_COMMAND_DATAVIEW_COLUMN_REORDERED,dataViewCtrlPtr->GetId());
1533 dataViewEvent.SetEventObject(dataViewCtrlPtr);
1534 dataViewEvent.SetColumn(dataViewCtrlPtr->GetColumnPosition(dataViewColumnPtr));
1535 dataViewEvent.SetDataViewColumn(dataViewColumnPtr);
1536 dataViewCtrlPtr->GetEventHandler()->ProcessEvent(dataViewEvent);
1539 -(void) outlineViewItemDidCollapse:(NSNotification*)notification
1541 wxDataViewCtrl* const dataViewCtrlPtr = implementation->GetDataViewCtrl();
1543 wxDataViewEvent dataViewEvent(wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSED,dataViewCtrlPtr->GetId());
1546 dataViewEvent.SetEventObject(dataViewCtrlPtr);
1547 dataViewEvent.SetItem(wxDataViewItem([((wxPointerObject*) [[notification userInfo] objectForKey:@"NSObject"]) pointer]));
1548 dataViewCtrlPtr->GetEventHandler()->ProcessEvent(dataViewEvent);
1551 -(void) outlineViewItemDidExpand:(NSNotification*)notification
1553 wxDataViewCtrl* const dataViewCtrlPtr = implementation->GetDataViewCtrl();
1555 wxDataViewEvent dataViewEvent(wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDED,dataViewCtrlPtr->GetId());
1558 dataViewEvent.SetEventObject(dataViewCtrlPtr);
1559 dataViewEvent.SetItem(wxDataViewItem([((wxPointerObject*) [[notification userInfo] objectForKey:@"NSObject"]) pointer]));
1560 dataViewCtrlPtr->GetEventHandler()->ProcessEvent(dataViewEvent);
1563 -(void) outlineViewSelectionDidChange:(NSNotification*)notification
1565 wxDataViewCtrl* const dataViewCtrlPtr = implementation->GetDataViewCtrl();
1567 wxDataViewEvent dataViewEvent(wxEVT_COMMAND_DATAVIEW_SELECTION_CHANGED,dataViewCtrlPtr->GetId()); // variable definition
1570 dataViewEvent.SetEventObject(dataViewCtrlPtr);
1571 dataViewEvent.SetModel (dataViewCtrlPtr->GetModel());
1572 // finally send the equivalent wxWidget event:
1573 dataViewCtrlPtr->GetEventHandler()->ProcessEvent(dataViewEvent);
1576 -(void) textDidBeginEditing:(NSNotification*)notification
1577 // this notification is only sent if the user started modifying the cell (not when the user clicked into the cell
1578 // and the cell's editor is called!)
1580 // call method of superclass (otherwise editing does not work correctly - the outline data source class is not
1581 // informed about a change of data):
1582 [super textDidBeginEditing:notification];
1584 wxDataViewColumn* const dataViewColumnPtr = reinterpret_cast<wxDataViewColumn*>([[[[self tableColumns] objectAtIndex:[self editedColumn]] identifier] pointer]);
1586 wxDataViewCtrl* const dataViewCtrlPtr = implementation->GetDataViewCtrl();
1589 // stop editing of a custom item first (if necessary)
1590 dataViewCtrlPtr->FinishCustomItemEditing();
1591 // set the flag that currently a cell is being edited (see also textDidEndEditing:):
1592 isEditingCell = YES;
1594 // now, send the event:
1595 wxDataViewEvent dataViewEvent(wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED,dataViewCtrlPtr->GetId()); // variable definition
1597 dataViewEvent.SetEventObject(dataViewCtrlPtr);
1598 dataViewEvent.SetItem(wxDataViewItem([((wxPointerObject*) [self itemAtRow:[self editedRow]]) pointer]));
1599 dataViewEvent.SetColumn(dataViewCtrlPtr->GetColumnPosition(dataViewColumnPtr));
1600 dataViewEvent.SetDataViewColumn(dataViewColumnPtr);
1601 dataViewCtrlPtr->GetEventHandler()->ProcessEvent(dataViewEvent);
1604 -(void) textDidEndEditing:(NSNotification*)notification
1606 // call method of superclass (otherwise editing does not work correctly - the outline data source class is not
1607 // informed about a change of data):
1608 [super textDidEndEditing:notification];
1610 // under OSX an event indicating the end of an editing session can be sent even if no event indicating a start of an
1611 // editing session has been sent (see Documentation for NSControl controlTextDidEndEditing:); this is not expected by a user
1612 // of the wxWidgets library and therefore an wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_DONE event is only sent if a corresponding
1613 // wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED has been sent before; to check if a wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED
1614 // has been sent the flag isEditingCell is used:
1615 if (isEditingCell == YES)
1617 wxDataViewColumn* const dataViewColumnPtr = reinterpret_cast<wxDataViewColumn*>([[[[self tableColumns] objectAtIndex:[self editedColumn]] identifier] pointer]);
1619 wxDataViewCtrl* const dataViewCtrlPtr = implementation->GetDataViewCtrl();
1621 // send event to wxWidgets:
1622 wxDataViewEvent dataViewEvent(wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_DONE,dataViewCtrlPtr->GetId()); // variable definition
1624 dataViewEvent.SetEventObject(dataViewCtrlPtr);
1625 dataViewEvent.SetItem(wxDataViewItem([((wxPointerObject*) [self itemAtRow:[self editedRow]]) pointer]));
1626 dataViewEvent.SetColumn(dataViewCtrlPtr->GetColumnPosition(dataViewColumnPtr));
1627 dataViewEvent.SetDataViewColumn(dataViewColumnPtr);
1628 dataViewCtrlPtr->GetEventHandler()->ProcessEvent(dataViewEvent);
1629 // set flag to the inactive state:
1635 // ============================================================================
1636 // wxCocoaDataViewControl
1637 // ============================================================================
1639 // constructors / destructor
1641 wxCocoaDataViewControl::wxCocoaDataViewControl(wxWindow* peer, wxPoint const& pos, wxSize const& size, long style)
1642 :wxWidgetCocoaImpl(peer,[[NSScrollView alloc] initWithFrame:wxOSXGetFrameForControl(peer,pos,size)]),
1643 m_DataSource(NULL), m_OutlineView([[wxCocoaOutlineView alloc] init])
1645 // initialize scrollview (the outline view is part of a scrollview):
1646 NSScrollView* scrollview = (NSScrollView*) this->GetWXWidget(); // definition for abbreviational purposes
1649 [scrollview setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1650 [scrollview setBorderType:NSNoBorder];
1651 [scrollview setHasVerticalScroller:YES];
1652 [scrollview setHasHorizontalScroller:YES];
1653 [scrollview setAutohidesScrollers:YES];
1654 [scrollview setDocumentView:this->m_OutlineView];
1656 // setting up the native control itself
1657 NSUInteger maskGridStyle(NSTableViewGridNone);
1659 [this->m_OutlineView setImplementation:this];
1660 [this->m_OutlineView setColumnAutoresizingStyle:NSTableViewSequentialColumnAutoresizingStyle];
1661 [this->m_OutlineView setIndentationPerLevel:this->GetDataViewCtrl()->GetIndent()];
1662 if (style & wxDV_HORIZ_RULES)
1663 maskGridStyle |= NSTableViewSolidHorizontalGridLineMask;
1664 if (style & wxDV_VERT_RULES)
1665 maskGridStyle |= NSTableViewSolidVerticalGridLineMask;
1666 [this->m_OutlineView setGridStyleMask:maskGridStyle];
1667 [this->m_OutlineView setAllowsMultipleSelection: (style & wxDV_MULTIPLE) != 0];
1668 [this->m_OutlineView setUsesAlternatingRowBackgroundColors:(style & wxDV_ROW_LINES) != 0];
1671 wxCocoaDataViewControl::~wxCocoaDataViewControl(void)
1673 [this->m_DataSource release];
1674 [this->m_OutlineView release];
1678 // column related methods (inherited from wxDataViewWidgetImpl)
1680 bool wxCocoaDataViewControl::ClearColumns(void)
1682 bool const bufAllowsMultipleSelection = [this->m_OutlineView allowsMultipleSelection];
1685 // as there is a bug in NSOutlineView version (OSX 10.5.6 #6555162) the columns cannot be deleted if there is an outline column in the view;
1686 // therefore, the whole view is deleted and newly constructed:
1687 [this->m_OutlineView release];
1688 this->m_OutlineView = [[wxCocoaOutlineView alloc] init];
1689 [((NSScrollView*) this->GetWXWidget()) setDocumentView:this->m_OutlineView];
1691 // setting up the native control itself
1692 [this->m_OutlineView setImplementation:this];
1693 [this->m_OutlineView setColumnAutoresizingStyle:NSTableViewSequentialColumnAutoresizingStyle];
1694 [this->m_OutlineView setIndentationPerLevel:this->GetDataViewCtrl()->GetIndent()];
1695 if (bufAllowsMultipleSelection)
1696 [this->m_OutlineView setAllowsMultipleSelection:YES];
1697 [this->m_OutlineView setDataSource:this->m_DataSource];
1702 bool wxCocoaDataViewControl::DeleteColumn(wxDataViewColumn* columnPtr)
1704 if ([this->m_OutlineView outlineTableColumn] == columnPtr->GetNativeData()->GetNativeColumnPtr())
1705 [this->m_OutlineView setOutlineTableColumn:nil]; // due to a bug this does not work
1706 [this->m_OutlineView removeTableColumn:columnPtr->GetNativeData()->GetNativeColumnPtr()]; // due to a confirmed bug #6555162 the deletion does not work for
1707 // outline table columns (... and there is no workaround)
1708 return (([this->m_OutlineView columnWithIdentifier:[[[wxPointerObject alloc] initWithPointer:columnPtr] autorelease]]) == -1);
1711 void wxCocoaDataViewControl::DoSetExpanderColumn(wxDataViewColumn const* columnPtr)
1713 [this->m_OutlineView setOutlineTableColumn:columnPtr->GetNativeData()->GetNativeColumnPtr()];
1716 wxDataViewColumn* wxCocoaDataViewControl::GetColumn(unsigned int pos) const
1718 return reinterpret_cast<wxDataViewColumn*>([[[[this->m_OutlineView tableColumns] objectAtIndex:pos] identifier] pointer]);
1721 int wxCocoaDataViewControl::GetColumnPosition(wxDataViewColumn const* columnPtr) const
1723 return [this->m_OutlineView columnWithIdentifier:[[[wxPointerObject alloc] initWithPointer:const_cast<wxDataViewColumn*>(columnPtr)] autorelease]];
1726 bool wxCocoaDataViewControl::InsertColumn(unsigned int pos, wxDataViewColumn* columnPtr)
1728 NSTableColumn* nativeColumn;
1731 // create column and set the native data of the dataview column:
1732 nativeColumn = ::CreateNativeColumn(columnPtr);
1733 columnPtr->GetNativeData()->SetNativeColumnPtr(nativeColumn);
1734 // as the native control does not allow the insertion of a column at a specified position the column is first appended and
1735 // - if necessary - moved to its final position:
1736 [this->m_OutlineView addTableColumn:nativeColumn];
1737 if (pos != static_cast<unsigned int>([this->m_OutlineView numberOfColumns]-1))
1738 [this->m_OutlineView moveColumn:[this->m_OutlineView numberOfColumns]-1 toColumn:pos];
1744 // item related methods (inherited from wxDataViewWidgetImpl)
1746 bool wxCocoaDataViewControl::Add(wxDataViewItem const& parent, wxDataViewItem const& WXUNUSED(item))
1749 [this->m_OutlineView reloadItem:[this->m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
1751 [this->m_OutlineView reloadData];
1755 bool wxCocoaDataViewControl::Add(wxDataViewItem const& parent, wxDataViewItemArray const& WXUNUSED(items))
1758 [this->m_OutlineView reloadItem:[this->m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
1760 [this->m_OutlineView reloadData];
1764 void wxCocoaDataViewControl::Collapse(wxDataViewItem const& item)
1766 [this->m_OutlineView collapseItem:[this->m_DataSource getDataViewItemFromBuffer:item]];
1769 void wxCocoaDataViewControl::EnsureVisible(wxDataViewItem const& item, wxDataViewColumn const* columnPtr)
1773 [this->m_OutlineView scrollRowToVisible:[this->m_OutlineView rowForItem:[this->m_DataSource getDataViewItemFromBuffer:item]]];
1774 if (columnPtr != NULL)
1775 [this->m_OutlineView scrollColumnToVisible:this->GetColumnPosition(columnPtr)];
1779 void wxCocoaDataViewControl::Expand(wxDataViewItem const& item)
1781 [this->m_OutlineView expandItem:[this->m_DataSource getDataViewItemFromBuffer:item]];
1784 unsigned int wxCocoaDataViewControl::GetCount(void) const
1786 return [this->m_OutlineView numberOfRows];
1789 wxRect wxCocoaDataViewControl::GetRectangle(wxDataViewItem const& item, wxDataViewColumn const* columnPtr)
1791 return wxFromNSRect([m_osxView superview],[this->m_OutlineView frameOfCellAtColumn:this->GetColumnPosition(columnPtr)
1792 row:[this->m_OutlineView rowForItem:[this->m_DataSource getDataViewItemFromBuffer:item]]]);
1795 bool wxCocoaDataViewControl::IsExpanded(wxDataViewItem const& item) const
1797 return [this->m_OutlineView isItemExpanded:[this->m_DataSource getDataViewItemFromBuffer:item]];
1800 bool wxCocoaDataViewControl::Reload(void)
1802 [this->m_DataSource clearBuffers];
1803 [this->m_OutlineView scrollColumnToVisible:0];
1804 [this->m_OutlineView scrollRowToVisible:0];
1805 [this->m_OutlineView reloadData];
1809 bool wxCocoaDataViewControl::Remove(wxDataViewItem const& parent, wxDataViewItem const& WXUNUSED(item))
1812 [this->m_OutlineView reloadItem:[this->m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
1814 [this->m_OutlineView reloadData];
1818 bool wxCocoaDataViewControl::Remove(wxDataViewItem const& parent, wxDataViewItemArray const& WXUNUSED(item))
1821 [this->m_OutlineView reloadItem:[this->m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
1823 [this->m_OutlineView reloadData];
1827 bool wxCocoaDataViewControl::Update(wxDataViewColumn const* columnPtr)
1832 bool wxCocoaDataViewControl::Update(wxDataViewItem const& WXUNUSED(parent), wxDataViewItem const& item)
1834 [this->m_OutlineView reloadItem:[this->m_DataSource getDataViewItemFromBuffer:item]];
1838 bool wxCocoaDataViewControl::Update(wxDataViewItem const& WXUNUSED(parent), wxDataViewItemArray const& items)
1840 for (size_t i=0; i<items.GetCount(); ++i)
1841 [this->m_OutlineView reloadItem:[this->m_DataSource getDataViewItemFromBuffer:items[i]]];
1846 // model related methods
1848 bool wxCocoaDataViewControl::AssociateModel(wxDataViewModel* model)
1850 [this->m_DataSource release];
1853 this->m_DataSource = [[wxCocoaOutlineDataSource alloc] init];
1854 [this->m_DataSource setImplementation:this];
1855 [this->m_DataSource setModel:model];
1858 this->m_DataSource = NULL;
1859 [this->m_OutlineView setDataSource:this->m_DataSource]; // if there is a data source the data is immediately going to be requested
1864 // selection related methods (inherited from wxDataViewWidgetImpl)
1866 int wxCocoaDataViewControl::GetSelections(wxDataViewItemArray& sel) const
1868 NSIndexSet* selectedRowIndexes([this->m_OutlineView selectedRowIndexes]);
1870 NSUInteger indexRow;
1874 sel.Alloc([selectedRowIndexes count]);
1875 indexRow = [selectedRowIndexes firstIndex];
1876 while (indexRow != NSNotFound)
1878 sel.Add(wxDataViewItem([[this->m_OutlineView itemAtRow:indexRow] pointer]));
1879 indexRow = [selectedRowIndexes indexGreaterThanIndex:indexRow];
1881 return sel.GetCount();
1884 bool wxCocoaDataViewControl::IsSelected(wxDataViewItem const& item) const
1886 return [this->m_OutlineView isRowSelected:[this->m_OutlineView rowForItem:[this->m_DataSource getDataViewItemFromBuffer:item]]];
1889 void wxCocoaDataViewControl::Select(wxDataViewItem const& item)
1892 [this->m_OutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[this->m_OutlineView rowForItem:[this->m_DataSource getDataViewItemFromBuffer:item]]]
1893 byExtendingSelection:NO];
1896 void wxCocoaDataViewControl::SelectAll(void)
1898 [this->m_OutlineView selectAll:this->m_OutlineView];
1901 void wxCocoaDataViewControl::Unselect(wxDataViewItem const& item)
1904 [this->m_OutlineView deselectRow:[this->m_OutlineView rowForItem:[this->m_DataSource getDataViewItemFromBuffer:item]]];
1907 void wxCocoaDataViewControl::UnselectAll(void)
1909 [this->m_OutlineView deselectAll:this->m_OutlineView];
1913 // sorting related methods
1915 wxDataViewColumn* wxCocoaDataViewControl::GetSortingColumn(void) const
1917 NSArray* const columns = [this->m_OutlineView tableColumns];
1919 UInt32 const noOfColumns = [columns count];
1922 for (UInt32 i=0; i<noOfColumns; ++i)
1923 if ([[columns objectAtIndex:i] sortDescriptorPrototype] != nil)
1924 return reinterpret_cast<wxDataViewColumn*>([[[columns objectAtIndex:i] identifier] pointer]);
1928 void wxCocoaDataViewControl::Resort(void)
1930 [this->m_DataSource clearChildren];
1931 [this->m_OutlineView reloadData];
1935 // other methods (inherited from wxDataViewWidgetImpl)
1937 void wxCocoaDataViewControl::DoSetIndent(int indent)
1939 [this->m_OutlineView setIndentationPerLevel:static_cast<CGFloat>(indent)];
1942 void wxCocoaDataViewControl::HitTest(wxPoint const& point, wxDataViewItem& item, wxDataViewColumn*& columnPtr) const
1944 NSPoint const nativePoint = wxToNSPoint((NSScrollView*) this->GetWXWidget(),point);
1950 indexColumn = [this->m_OutlineView columnAtPoint:nativePoint];
1951 indexRow = [this->m_OutlineView rowAtPoint: nativePoint];
1952 if ((indexColumn >= 0) && (indexRow >= 0))
1954 columnPtr = reinterpret_cast<wxDataViewColumn*>([[[[this->m_OutlineView tableColumns] objectAtIndex:indexColumn] identifier] pointer]);
1955 item = wxDataViewItem([[this->m_OutlineView itemAtRow:indexRow] pointer]);
1960 item = wxDataViewItem();
1964 void wxCocoaDataViewControl::SetRowHeight(wxDataViewItem const& WXUNUSED(item), unsigned int WXUNUSED(height))
1965 // Not supported by the native control
1969 void wxCocoaDataViewControl::OnSize(void)
1971 if ([this->m_OutlineView numberOfColumns] == 1)
1972 [this->m_OutlineView sizeLastColumnToFit];
1976 // drag & drop helper methods
1978 wxDataFormat wxCocoaDataViewControl::GetDnDDataFormat(wxDataObjectComposite* dataObjects)
1980 wxDataFormat resultFormat;
1983 if (dataObjects != NULL)
1985 bool compatible(true);
1987 size_t const noOfFormats = dataObjects->GetFormatCount();
1990 wxDataFormat* formats;
1992 // get all formats and check afterwards if the formats are compatible; if they are compatible the preferred format is returned otherwise
1993 // wxDF_INVALID is returned;
1994 // currently compatible types (ordered by priority are):
1995 // - wxDF_UNICODETEXT - wxDF_TEXT
1996 formats = new wxDataFormat[noOfFormats];
1997 dataObjects->GetAllFormats(formats);
1999 while ((indexFormat < noOfFormats) && compatible)
2001 switch (resultFormat.GetType())
2004 resultFormat.SetType(formats[indexFormat].GetType()); // first format (should only be reached if indexFormat == 0)
2007 if (formats[indexFormat].GetType() == wxDF_UNICODETEXT)
2008 resultFormat.SetType(wxDF_UNICODETEXT);
2009 else // incompatible
2011 resultFormat.SetType(wxDF_INVALID);
2015 case wxDF_UNICODETEXT:
2016 if (formats[indexFormat].GetType() != wxDF_TEXT)
2018 resultFormat.SetType(wxDF_INVALID);
2023 resultFormat.SetType(wxDF_INVALID); // not (yet) supported format
2031 return resultFormat;
2034 wxDataObjectComposite* wxCocoaDataViewControl::GetDnDDataObjects(NSData* dataObject) const
2036 wxDataFormatId dataFormatID;
2039 [dataObject getBytes:&dataFormatID length:sizeof(wxDataFormatId)];
2040 switch (dataFormatID)
2043 case wxDF_UNICODETEXT:
2045 wxTextDataObject* textDataObject(new wxTextDataObject());
2047 if (textDataObject->SetData(wxDataFormat(dataFormatID),[dataObject length]-sizeof(wxDataFormatId),reinterpret_cast<char const*>([dataObject bytes])+sizeof(wxDataFormatId)))
2049 wxDataObjectComposite* dataObjectComposite(new wxDataObjectComposite());
2051 dataObjectComposite->Add(textDataObject);
2052 return dataObjectComposite;
2056 delete textDataObject;
2066 // ---------------------------------------------------------
2067 // wxDataViewRenderer
2068 // ---------------------------------------------------------
2069 wxDataViewRenderer::wxDataViewRenderer(wxString const& varianttype, wxDataViewCellMode mode, int align)
2070 :wxDataViewRendererBase(varianttype,mode,align), m_alignment(align), m_mode(mode), m_NativeDataPtr(NULL)
2074 wxDataViewRenderer::~wxDataViewRenderer(void)
2076 delete this->m_NativeDataPtr;
2079 void wxDataViewRenderer::SetAlignment(int align)
2081 this->m_alignment = align;
2082 [this->GetNativeData()->GetColumnCell() setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2085 void wxDataViewRenderer::SetMode(wxDataViewCellMode mode)
2087 this->m_mode = mode;
2088 if (this->GetOwner() != NULL)
2089 [this->GetOwner()->GetNativeData()->GetNativeColumnPtr() setEditable:(mode == wxDATAVIEW_CELL_EDITABLE)];
2092 void wxDataViewRenderer::SetNativeData(wxDataViewRendererNativeData* newNativeDataPtr)
2094 delete this->m_NativeDataPtr;
2095 this->m_NativeDataPtr = newNativeDataPtr;
2098 IMPLEMENT_ABSTRACT_CLASS(wxDataViewRenderer,wxDataViewRendererBase)
2100 // ---------------------------------------------------------
2101 // wxDataViewCustomRenderer
2102 // ---------------------------------------------------------
2103 wxDataViewCustomRenderer::wxDataViewCustomRenderer(wxString const& varianttype, wxDataViewCellMode mode, int align)
2104 :wxDataViewRenderer(varianttype,mode,align), m_editorCtrlPtr(NULL), m_DCPtr(NULL)
2106 this->SetNativeData(new wxDataViewRendererNativeData([[wxCustomCell alloc] init]));
2109 bool wxDataViewCustomRenderer::MacRender()
2111 [this->GetNativeData()->GetItemCell() setObjectValue:[[[wxCustomRendererObject alloc] initWithRenderer:this
2112 item:this->GetNativeData()->GetItem()
2113 column:this->GetNativeData()->GetColumnPtr()] autorelease]];
2117 IMPLEMENT_ABSTRACT_CLASS(wxDataViewCustomRenderer, wxDataViewRenderer)
2119 // ---------------------------------------------------------
2120 // wxDataViewTextRenderer
2121 // ---------------------------------------------------------
2122 wxDataViewTextRenderer::wxDataViewTextRenderer(wxString const& varianttype, wxDataViewCellMode mode, int align)
2123 :wxDataViewRenderer(varianttype,mode,align)
2125 NSTextFieldCell* cell;
2128 cell = [[NSTextFieldCell alloc] init];
2129 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2130 [cell setLineBreakMode:NSLineBreakByTruncatingMiddle];
2131 this->SetNativeData(new wxDataViewRendererNativeData(cell));
2135 bool wxDataViewTextRenderer::MacRender()
2137 if (this->GetValue().GetType() == this->GetVariantType())
2139 [this->GetNativeData()->GetItemCell() setObjectValue:wxCFStringRef(this->GetValue().GetString()).AsNSString()];
2144 wxFAIL_MSG(wxString(_("Text renderer cannot render value because of wrong value type; value type: ")) << this->GetValue().GetType());
2149 IMPLEMENT_CLASS(wxDataViewTextRenderer,wxDataViewRenderer)
2151 // ---------------------------------------------------------
2152 // wxDataViewBitmapRenderer
2153 // ---------------------------------------------------------
2154 wxDataViewBitmapRenderer::wxDataViewBitmapRenderer(wxString const& varianttype, wxDataViewCellMode mode, int align)
2155 :wxDataViewRenderer(varianttype,mode,align)
2160 cell = [[NSImageCell alloc] init];
2161 this->SetNativeData(new wxDataViewRendererNativeData(cell));
2165 bool wxDataViewBitmapRenderer::MacRender()
2166 // This method returns 'true' if
2167 // - the passed bitmap is valid and it could be assigned to the native data browser;
2168 // - the passed bitmap is invalid (or is not initialized); this case simulates a non-existing bitmap.
2169 // In all other cases the method returns 'false'.
2171 wxCHECK_MSG(this->GetValue().GetType() == this->GetVariantType(),false,wxString(_("Bitmap renderer cannot render value; value type: ")) << this->GetValue().GetType());
2175 bitmap << this->GetValue();
2177 [this->GetNativeData()->GetItemCell() setObjectValue:[[bitmap.GetNSImage() retain] autorelease]];
2181 IMPLEMENT_CLASS(wxDataViewBitmapRenderer,wxDataViewRenderer)
2183 // -------------------------------------
2184 // wxDataViewChoiceRenderer
2185 // -------------------------------------
2186 wxDataViewChoiceRenderer::wxDataViewChoiceRenderer(wxArrayString const& choices, wxDataViewCellMode mode, int alignment)
2187 :wxDataViewRenderer(wxT("string"),mode,alignment), m_Choices(choices)
2189 NSPopUpButtonCell* cell;
2192 cell = [[NSPopUpButtonCell alloc] init];
2193 [cell setControlSize:NSMiniControlSize];
2194 [cell setFont:[[NSFont fontWithName:[[cell font] fontName] size:[NSFont systemFontSizeForControlSize:NSMiniControlSize]] autorelease]];
2195 for (size_t i=0; i<choices.GetCount(); ++i)
2196 [cell addItemWithTitle:[[wxCFStringRef(choices[i]).AsNSString() retain] autorelease]];
2197 this->SetNativeData(new wxDataViewRendererNativeData(cell));
2201 bool wxDataViewChoiceRenderer::MacRender()
2203 if (this->GetValue().GetType() == this->GetVariantType())
2205 [((NSPopUpButtonCell*) this->GetNativeData()->GetItemCell()) selectItemWithTitle:[[wxCFStringRef(this->GetValue().GetString()).AsNSString() retain] autorelease]];
2210 wxFAIL_MSG(wxString(_("Choice renderer cannot render value because of wrong value type; value type: ")) << this->GetValue().GetType());
2215 IMPLEMENT_CLASS(wxDataViewChoiceRenderer,wxDataViewRenderer)
2217 // ---------------------------------------------------------
2218 // wxDataViewDateRenderer
2219 // ---------------------------------------------------------
2220 wxDataViewDateRenderer::wxDataViewDateRenderer(wxString const& varianttype, wxDataViewCellMode mode, int align)
2221 :wxDataViewRenderer(varianttype,mode,align)
2223 NSTextFieldCell* cell;
2225 NSDateFormatter* dateFormatter;
2228 dateFormatter = [[NSDateFormatter alloc] init];
2229 [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
2230 [dateFormatter setDateStyle:NSDateFormatterShortStyle];
2231 cell = [[NSTextFieldCell alloc] init];
2232 [cell setFormatter:dateFormatter];
2233 [cell setLineBreakMode:NSLineBreakByTruncatingMiddle];
2234 this->SetNativeData(new wxDataViewRendererNativeData(cell,[NSDate dateWithString:@"2000-12-30 20:00:00 +0000"]));
2236 [dateFormatter release];
2239 bool wxDataViewDateRenderer::MacRender()
2241 if (this->GetValue().GetType() == this->GetVariantType())
2243 if (this->GetValue().GetDateTime().IsValid())
2245 // -- find best fitting style to show the date --
2246 // as the style should be identical for all cells a reference date instead of the actual cell's date
2247 // value is used for all cells; this reference date is stored in the renderer's native data section
2248 // for speed purposes; otherwise, the reference date's string has to be recalculated for each item that
2249 // may become timewise long if a lot of rows using dates exist;
2250 // the algorithm has the preference to display as much information as possible in the first instance;
2251 // but as this is often impossible due to space restrictions the style is shortened per loop; finally,
2252 // if the shortest time and date format does not fit into the cell the time part is dropped;
2253 // remark: the time part itself is not modified per iteration loop and only uses the short style,
2254 // means that only the hours and minutes are being shown
2255 [this->GetNativeData()->GetItemCell() setObjectValue:this->GetNativeData()->GetObject()]; // GetObject() returns a date for testing the size of a date object
2256 [[this->GetNativeData()->GetItemCell() formatter] setTimeStyle:NSDateFormatterShortStyle];
2257 for (int dateFormatterStyle=4; dateFormatterStyle>0; --dateFormatterStyle)
2259 [[this->GetNativeData()->GetItemCell() formatter] setDateStyle:(NSDateFormatterStyle)dateFormatterStyle];
2260 if (dateFormatterStyle == 1)
2262 // if the shortest style for displaying the date and time is too long to be fully visible remove the time part of the date:
2263 if ([this->GetNativeData()->GetItemCell() cellSize].width > [this->GetNativeData()->GetColumnPtr() width])
2264 [[this->GetNativeData()->GetItemCell() formatter] setTimeStyle:NSDateFormatterNoStyle];
2265 break; // basically not necessary as the loop would end anyway but let's save the last comparison
2267 else if ([this->GetNativeData()->GetItemCell() cellSize].width <= [this->GetNativeData()->GetColumnPtr() width])
2270 // set data (the style is set by the previous loop);
2271 // on OSX the date has to be specified with respect to UTC; in wxWidgets the date is always entered in the local timezone; so, we have to do a conversion
2272 // from the local to UTC timezone when adding the seconds to 1970-01-01 UTC:
2273 [this->GetNativeData()->GetItemCell() setObjectValue:[NSDate dateWithTimeIntervalSince1970:this->GetValue().GetDateTime().ToUTC().Subtract(wxDateTime(1,wxDateTime::Jan,1970)).GetSeconds().ToDouble()]];
2279 wxFAIL_MSG(wxString(_("Date renderer cannot render value because of wrong value type; value type: ")) << this->GetValue().GetType());
2284 IMPLEMENT_ABSTRACT_CLASS(wxDataViewDateRenderer,wxDataViewRenderer)
2286 // ---------------------------------------------------------
2287 // wxDataViewIconTextRenderer
2288 // ---------------------------------------------------------
2289 wxDataViewIconTextRenderer::wxDataViewIconTextRenderer(wxString const& varianttype, wxDataViewCellMode mode, int align)
2290 :wxDataViewRenderer(varianttype,mode)
2292 wxImageTextCell* cell;
2295 cell = [[wxImageTextCell alloc] init];
2296 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2297 this->SetNativeData(new wxDataViewRendererNativeData(cell));
2301 bool wxDataViewIconTextRenderer::MacRender()
2303 if (this->GetValue().GetType() == this->GetVariantType())
2305 wxDataViewIconText iconText;
2307 wxImageTextCell* cell;
2309 cell = (wxImageTextCell*) this->GetNativeData()->GetItemCell();
2310 iconText << this->GetValue();
2311 if (iconText.GetIcon().IsOk())
2312 [cell setImage:[[wxBitmap(iconText.GetIcon()).GetNSImage() retain] autorelease]];
2313 [cell setStringValue:[[wxCFStringRef(iconText.GetText()).AsNSString() retain] autorelease]];
2318 wxFAIL_MSG(wxString(_("Icon & text renderer cannot render value because of wrong value type; value type: ")) << this->GetValue().GetType());
2323 IMPLEMENT_ABSTRACT_CLASS(wxDataViewIconTextRenderer,wxDataViewRenderer)
2325 // ---------------------------------------------------------
2326 // wxDataViewToggleRenderer
2327 // ---------------------------------------------------------
2328 wxDataViewToggleRenderer::wxDataViewToggleRenderer(wxString const& varianttype, wxDataViewCellMode mode, int align)
2329 :wxDataViewRenderer(varianttype,mode)
2334 cell = [[NSButtonCell alloc] init];
2335 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2336 [cell setButtonType:NSSwitchButton];
2337 [cell setImagePosition:NSImageOnly];
2338 this->SetNativeData(new wxDataViewRendererNativeData(cell));
2342 bool wxDataViewToggleRenderer::MacRender()
2344 if (this->GetValue().GetType() == this->GetVariantType())
2346 [this->GetNativeData()->GetItemCell() setIntValue:this->GetValue().GetLong()];
2351 wxFAIL_MSG(wxString(_("Toggle renderer cannot render value because of wrong value type; value type: ")) << this->GetValue().GetType());
2356 IMPLEMENT_ABSTRACT_CLASS(wxDataViewToggleRenderer,wxDataViewRenderer)
2358 // ---------------------------------------------------------
2359 // wxDataViewProgressRenderer
2360 // ---------------------------------------------------------
2361 wxDataViewProgressRenderer::wxDataViewProgressRenderer(wxString const& label, wxString const& varianttype, wxDataViewCellMode mode, int align)
2362 :wxDataViewRenderer(varianttype,mode,align)
2364 NSLevelIndicatorCell* cell;
2367 cell = [[NSLevelIndicatorCell alloc] initWithLevelIndicatorStyle:NSContinuousCapacityLevelIndicatorStyle];
2368 [cell setMinValue:0];
2369 [cell setMaxValue:100];
2370 this->SetNativeData(new wxDataViewRendererNativeData(cell));
2374 bool wxDataViewProgressRenderer::MacRender()
2376 if (this->GetValue().GetType() == this->GetVariantType())
2378 [this->GetNativeData()->GetItemCell() setIntValue:this->GetValue().GetLong()];
2383 wxFAIL_MSG(wxString(_("Progress renderer cannot render value because of wrong value type; value type: ")) << this->GetValue().GetType());
2388 IMPLEMENT_ABSTRACT_CLASS(wxDataViewProgressRenderer,wxDataViewRenderer)
2390 // ---------------------------------------------------------
2392 // ---------------------------------------------------------
2393 wxDataViewColumn::wxDataViewColumn(const wxString& title, wxDataViewRenderer* renderer, unsigned int model_column, int width, wxAlignment align, int flags)
2394 :wxDataViewColumnBase(renderer, model_column), m_NativeDataPtr(new wxDataViewColumnNativeData()), m_title(title)
2396 this->InitCommon(width, align, flags);
2397 if ((renderer != NULL) && (renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
2398 renderer->SetAlignment(align);
2401 wxDataViewColumn::wxDataViewColumn(const wxBitmap& bitmap, wxDataViewRenderer* renderer, unsigned int model_column, int width, wxAlignment align, int flags)
2402 :wxDataViewColumnBase(bitmap, renderer, model_column), m_NativeDataPtr(new wxDataViewColumnNativeData())
2404 this->InitCommon(width, align, flags);
2405 if ((renderer != NULL) && (renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
2406 renderer->SetAlignment(align);
2409 wxDataViewColumn::~wxDataViewColumn(void)
2411 delete this->m_NativeDataPtr;
2414 bool wxDataViewColumn::IsSortKey() const
2416 return ((this->GetNativeData()->GetNativeColumnPtr() != NULL) && ([this->GetNativeData()->GetNativeColumnPtr() sortDescriptorPrototype] != nil));
2419 void wxDataViewColumn::SetAlignment(wxAlignment align)
2421 this->m_alignment = align;
2422 [[this->m_NativeDataPtr->GetNativeColumnPtr() headerCell] setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2423 if ((this->m_renderer != NULL) && (this->m_renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
2424 this->m_renderer->SetAlignment(align);
2427 void wxDataViewColumn::SetBitmap(wxBitmap const& bitmap)
2429 // bitmaps and titles cannot exist at the same time - if the bitmap is set the title is removed:
2430 this->m_title = wxEmptyString;
2431 this->wxDataViewColumnBase::SetBitmap(bitmap);
2432 [[this->m_NativeDataPtr->GetNativeColumnPtr() headerCell] setImage:[[bitmap.GetNSImage() retain] autorelease]];
2435 void wxDataViewColumn::SetMaxWidth(int maxWidth)
2437 this->m_maxWidth = maxWidth;
2438 [this->m_NativeDataPtr->GetNativeColumnPtr() setMaxWidth:maxWidth];
2441 void wxDataViewColumn::SetMinWidth(int minWidth)
2443 this->m_minWidth = minWidth;
2444 [this->m_NativeDataPtr->GetNativeColumnPtr() setMinWidth:minWidth];
2447 void wxDataViewColumn::SetReorderable(bool reorderable)
2451 void wxDataViewColumn::SetResizeable(bool resizeable)
2453 this->wxDataViewColumnBase::SetResizeable(resizeable);
2455 [this->m_NativeDataPtr->GetNativeColumnPtr() setResizingMask:NSTableColumnUserResizingMask];
2457 [this->m_NativeDataPtr->GetNativeColumnPtr() setResizingMask:NSTableColumnNoResizing];
2460 void wxDataViewColumn::SetSortable(bool sortable)
2462 this->wxDataViewColumnBase::SetSortable(sortable);
2465 void wxDataViewColumn::SetSortOrder(bool ascending)
2467 if (m_ascending != ascending)
2469 m_ascending = ascending;
2470 if (this->IsSortKey())
2472 // change sorting order:
2473 NSArray* sortDescriptors;
2474 NSSortDescriptor* sortDescriptor;
2475 NSTableColumn* tableColumn;
2477 tableColumn = this->m_NativeDataPtr->GetNativeColumnPtr();
2478 sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[[tableColumn sortDescriptorPrototype] key] ascending:m_ascending];
2479 sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
2480 [tableColumn setSortDescriptorPrototype:sortDescriptor];
2481 [[tableColumn tableView] setSortDescriptors:sortDescriptors];
2482 [sortDescriptor release];
2487 void wxDataViewColumn::SetTitle(wxString const& title)
2489 // bitmaps and titles cannot exist at the same time - if the title is set the bitmap is removed:
2490 this->wxDataViewColumnBase::SetBitmap(wxBitmap());
2491 this->m_title = title;
2492 [[this->m_NativeDataPtr->GetNativeColumnPtr() headerCell] setStringValue:[[wxCFStringRef(title).AsNSString() retain] autorelease]];
2495 void wxDataViewColumn::SetWidth(int width)
2497 [this->m_NativeDataPtr->GetNativeColumnPtr() setWidth:width];
2498 this->m_width = width;
2501 void wxDataViewColumn::SetAsSortKey(bool WXUNUSED(sort))
2503 // see wxGTK native wxDataViewColumn implementation
2504 wxFAIL_MSG(_("not implemented"));
2507 void wxDataViewColumn::SetNativeData(wxDataViewColumnNativeData* newNativeDataPtr)
2509 delete this->m_NativeDataPtr;
2510 this->m_NativeDataPtr = newNativeDataPtr;
2512 #endif // (wxUSE_DATAVIEWCTRL == 1) && !defined(wxUSE_GENERICDATAVIEWCTRL)