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/private.h"
25 #include "wx/osx/cocoa/dataview.h"
26 #include "wx/renderer.h"
28 // ============================================================================
29 // Constants used locally
30 // ============================================================================
32 #define DataViewPboardType @"OutlineViewItem"
34 // ============================================================================
35 // Classes used locally in dataview.mm
36 // ============================================================================
38 // ============================================================================
40 // ============================================================================
42 @implementation wxPointerObject
52 -(id) initWithPointer:(void*) initPointer
56 self->pointer = initPointer;
61 // inherited methods from NSObject
63 -(BOOL) isEqual:(id)object
65 return (object != nil) &&
66 ([object isKindOfClass:[wxPointerObject class]]) &&
67 (pointer == [((wxPointerObject*) object) pointer]);
72 return (NSUInteger) pointer;
80 -(void) setPointer:(void*) newPointer
90 inline wxDataViewItem wxDataViewItemFromItem(id item)
92 return wxDataViewItem([static_cast<wxPointerObject *>(item) pointer]);
95 inline wxDataViewItem wxDataViewItemFromMaybeNilItem(id item)
97 return item == nil ? wxDataViewItem() : wxDataViewItemFromItem(item);
100 } // anonymous namespace
102 // ----------------------------------------------------------------------------
103 // wxCustomRendererObject
104 // ----------------------------------------------------------------------------
106 @interface wxCustomRendererObject : NSObject <NSCopying>
109 wxDataViewCustomRenderer* customRenderer; // not owned by the class
113 -(id) initWithRenderer:(wxDataViewCustomRenderer*)renderer;
116 @implementation wxCustomRendererObject
123 customRenderer = NULL;
128 -(id) initWithRenderer:(wxDataViewCustomRenderer*)renderer
133 customRenderer = renderer;
138 -(id) copyWithZone:(NSZone*)zone
140 wxCustomRendererObject* copy;
142 copy = [[[self class] allocWithZone:zone] init];
143 copy->customRenderer = customRenderer;
149 // ----------------------------------------------------------------------------
150 // wxDVCNSTableColumn: exists only to override NSTableColumn:dataCellForRow:
151 // ----------------------------------------------------------------------------
153 @interface wxDVCNSTableColumn : NSTableColumn
157 -(id) dataCellForRow:(NSInteger)row;
160 @implementation wxDVCNSTableColumn
162 -(id) dataCellForRow:(NSInteger)row
164 // what we want to do here is to simply return nil for the cells which
165 // shouldn't show anything as otherwise we would show e.g. empty combo box
166 // or progress cells in the columns using the corresponding types even for
167 // the container rows which is wrong
169 // half of the problem is just finding the objects we need from the column
170 // pointer which is itself stashed inside wxPointerObject which we use as
172 const wxDataViewColumn * const
173 dvCol = static_cast<wxDataViewColumn *>(
174 [(wxPointerObject *)[self identifier] pointer]
177 const wxDataViewCtrl * const dvc = dvCol->GetOwner();
178 const wxCocoaDataViewControl * const
179 peer = static_cast<wxCocoaDataViewControl *>(dvc->GetPeer());
182 // once we do have everything, simply ask NSOutlineView for the item...
183 const id item = peer->GetItemAtRow(row);
186 // ... and if it succeeded, ask the model whether it has any value
187 wxDataViewItem dvItem(wxDataViewItemFromItem(item));
189 if ( !dvc->GetModel()->HasValue(dvItem, dvCol->GetModelColumn()) )
193 return [super dataCellForRow:row];
198 // ============================================================================
200 // ============================================================================
205 // convert from NSObject to different C++ types: all these functions check
206 // that the conversion really makes sense and assert if it doesn't
207 wxString ObjectToString(NSObject *object)
209 wxCHECK_MSG( [object isKindOfClass:[NSString class]], "",
212 "string expected but got %s",
213 wxCFStringRef::AsString([object className])
216 return wxCFStringRef([((NSString*) object) retain]).AsString();
219 bool ObjectToBool(NSObject *object)
221 // actually the value must be of NSCFBoolean class but it's private so we
222 // can't check for it directly
223 wxCHECK_MSG( [object isKindOfClass:[NSNumber class]], false,
226 "number expected but got %s",
227 wxCFStringRef::AsString([object className])
230 return [(NSNumber *)object boolValue];
233 long ObjectToLong(NSObject *object)
235 wxCHECK_MSG( [object isKindOfClass:[NSNumber class]], -1,
238 "number expected but got %s",
239 wxCFStringRef::AsString([object className])
242 return [(NSNumber *)object longValue];
245 wxDateTime ObjectToDate(NSObject *object)
247 wxCHECK_MSG( [object isKindOfClass:[NSDate class]], wxInvalidDateTime,
250 "date expected but got %s",
251 wxCFStringRef::AsString([object className])
254 // get the number of seconds since 1970-01-01 UTC and this is the only
255 // way to convert a double to a wxLongLong
256 const wxLongLong seconds = [((NSDate*) object) timeIntervalSince1970];
258 wxDateTime dt(1, wxDateTime::Jan, 1970);
259 dt.Add(wxTimeSpan(0,0,seconds));
261 // the user has entered a date in the local timezone but seconds
262 // contains the number of seconds from date in the local timezone
263 // since 1970-01-01 UTC; therefore, the timezone information has to be
264 // transferred to wxWidgets, too:
265 dt.MakeFromTimezone(wxDateTime::UTC);
270 NSInteger CompareItems(id item1, id item2, void* context)
272 NSArray* const sortDescriptors = (NSArray*) context;
274 NSUInteger const count = [sortDescriptors count];
276 NSInteger result = NSOrderedSame;
277 for ( NSUInteger i = 0; i < count && result == NSOrderedSame; ++i )
279 wxSortDescriptorObject* const
280 sortDescriptor = (wxSortDescriptorObject*)
281 [sortDescriptors objectAtIndex:i];
283 int rc = [sortDescriptor modelPtr]->Compare
285 wxDataViewItemFromItem(item1),
286 wxDataViewItemFromItem(item2),
287 [sortDescriptor columnPtr]->GetModelColumn(),
288 [sortDescriptor ascending] == YES
292 result = NSOrderedAscending;
294 result = NSOrderedDescending;
300 NSTextAlignment ConvertToNativeHorizontalTextAlignment(int alignment)
302 if (alignment & wxALIGN_CENTER_HORIZONTAL)
303 return NSCenterTextAlignment;
304 else if (alignment & wxALIGN_RIGHT)
305 return NSRightTextAlignment;
307 return NSLeftTextAlignment;
310 NSTableColumn* CreateNativeColumn(const wxDataViewColumn *column)
312 wxDataViewRenderer * const renderer = column->GetRenderer();
314 wxCHECK_MSG( renderer, NULL, "column should have a renderer" );
316 wxDVCNSTableColumn * const nativeColumn(
317 [[wxDVCNSTableColumn alloc] initWithIdentifier:
318 [[[wxPointerObject alloc] initWithPointer:
319 const_cast<wxDataViewColumn*>(column)]
323 // setting the size related parameters:
324 const int width = column->GetWidthVariable();
326 if (column->IsResizeable())
328 resizingMask = NSTableColumnUserResizingMask;
329 [nativeColumn setMinWidth:column->GetMinWidth()];
330 [nativeColumn setMaxWidth:column->GetMaxWidth()];
332 else // column is not resizeable [by user]
334 // if the control doesn't show a header, make the columns resize
335 // automatically, this is particularly important for the single column
336 // controls (such as wxDataViewTreeCtrl) as their unique column should
337 // always take up all the available splace
338 resizingMask = column->GetOwner()->HasFlag(wxDV_NO_HEADER)
339 ? NSTableColumnAutoresizingMask
340 : NSTableColumnNoResizing;
342 [nativeColumn setResizingMask:resizingMask];
343 [nativeColumn setWidth:width];
345 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
346 // setting the visibility:
347 [nativeColumn setHidden:static_cast<BOOL>(column->IsHidden())];
350 wxDataViewRendererNativeData * const renderData = renderer->GetNativeData();
352 // setting the header:
353 [[nativeColumn headerCell] setAlignment:
354 ConvertToNativeHorizontalTextAlignment(column->GetAlignment())];
355 [[nativeColumn headerCell] setStringValue:
356 [[wxCFStringRef(column->GetTitle()).AsNSString() retain] autorelease]];
357 renderData->ApplyLineBreakMode([nativeColumn headerCell]);
359 // setting data cell's properties:
360 [[nativeColumn dataCell] setWraps:NO];
361 // setting the default data cell:
362 [nativeColumn setDataCell:renderData->GetColumnCell()];
363 // setting the editablility:
364 const bool isEditable = renderer->GetMode() == wxDATAVIEW_CELL_EDITABLE;
366 [nativeColumn setEditable:isEditable];
367 [[nativeColumn dataCell] setEditable:isEditable];
372 } // anonymous namespace
374 // ============================================================================
375 // Public helper functions for dataview implementation on OSX
376 // ============================================================================
378 wxWidgetImplType* CreateDataView(wxWindowMac* wxpeer,
379 wxWindowMac* WXUNUSED(parent),
380 wxWindowID WXUNUSED(id),
384 long WXUNUSED(extraStyle))
386 return new wxCocoaDataViewControl(wxpeer,pos,size,style);
389 // ============================================================================
390 // wxSortDescriptorObject
391 // ============================================================================
393 @implementation wxSortDescriptorObject
406 initWithModelPtr:(wxDataViewModel*)initModelPtr
407 sortingColumnPtr:(wxDataViewColumn*)initColumnPtr
408 ascending:(BOOL)sortAscending
410 self = [super initWithKey:@"dummy" ascending:sortAscending];
413 columnPtr = initColumnPtr;
414 modelPtr = initModelPtr;
419 -(id) copyWithZone:(NSZone*)zone
421 wxSortDescriptorObject* copy;
424 copy = [super copyWithZone:zone];
425 copy->columnPtr = columnPtr;
426 copy->modelPtr = modelPtr;
432 // access to model column's index
434 -(wxDataViewColumn*) columnPtr
439 -(wxDataViewModel*) modelPtr
444 -(void) setColumnPtr:(wxDataViewColumn*)newColumnPtr
446 columnPtr = newColumnPtr;
449 -(void) setModelPtr:(wxDataViewModel*)newModelPtr
451 modelPtr = newModelPtr;
456 // ============================================================================
457 // wxCocoaOutlineDataSource
458 // ============================================================================
459 @implementation wxCocoaOutlineDataSource
462 // constructors / destructor
469 implementation = NULL;
472 currentParentItem = nil;
474 children = [[NSMutableArray alloc] init];
475 items = [[NSMutableSet alloc] init];
482 [currentParentItem release];
491 // methods of informal protocol:
494 outlineView:(NSOutlineView*)outlineView
495 acceptDrop:(id<NSDraggingInfo>)info
496 item:(id)item childIndex:(NSInteger)index
498 NSArray* supportedTypes(
499 [NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]
502 NSPasteboard* pasteboard([info draggingPasteboard]);
504 NSString* bestType([pasteboard availableTypeFromArray:supportedTypes]);
506 if ( bestType == nil )
509 wxDataViewCtrl * const dvc(implementation->GetDataViewCtrl());
511 wxCHECK_MSG( dvc, false,
512 "Pointer to data view control not set correctly." );
513 wxCHECK_MSG( dvc->GetModel(), false,
514 "Pointer to model not set correctly." );
516 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_DROP, dvc->GetId());
517 event.SetEventObject(dvc);
518 event.SetItem(wxDataViewItemFromItem(item));
519 event.SetModel(dvc->GetModel());
522 if ( [bestType compare:DataViewPboardType] == NSOrderedSame )
524 NSArray* dataArray((NSArray*)
525 [pasteboard propertyListForType:DataViewPboardType]);
526 NSUInteger indexDraggedItem, noOfDraggedItems([dataArray count]);
528 indexDraggedItem = 0;
529 while (indexDraggedItem < noOfDraggedItems)
531 wxDataObjectComposite* dataObjects(
532 implementation->GetDnDDataObjects((NSData*)
533 [dataArray objectAtIndex:indexDraggedItem]));
535 if (dataObjects && (dataObjects->GetFormatCount() > 0))
537 wxMemoryBuffer buffer;
539 // copy data into data object:
540 event.SetDataObject(dataObjects);
542 implementation->GetDnDDataFormat(dataObjects));
543 // copy data into buffer:
544 dataObjects->GetDataHere(
545 event.GetDataFormat().GetType(),
546 buffer.GetWriteBuf(event.GetDataSize()));
547 buffer.UngetWriteBuf(event.GetDataSize());
548 event.SetDataBuffer(buffer.GetData());
549 // finally, send event:
550 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
552 dragSuccessful = true;
557 dragSuccessful = true;
558 indexDraggedItem = noOfDraggedItems; // stop loop
563 dragSuccessful = false;
564 indexDraggedItem = noOfDraggedItems; // stop loop
572 // needed to convert internally used UTF-16 representation to a UTF-8
575 wxDataObjectComposite* dataObjects (new wxDataObjectComposite());
576 wxTextDataObject* textDataObject(new wxTextDataObject());
578 osxData = ::CFStringCreateExternalRepresentation
581 (CFStringRef)[pasteboard stringForType:NSStringPboardType],
582 kCFStringEncodingUTF8,
585 if (textDataObject->SetData(::CFDataGetLength(osxData),
586 ::CFDataGetBytePtr(osxData)))
587 dataObjects->Add(textDataObject);
589 delete textDataObject;
590 // send event if data could be copied:
591 if (dataObjects->GetFormatCount() > 0)
593 event.SetDataObject(dataObjects);
594 event.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
595 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
596 dragSuccessful = true;
598 dragSuccessful = false;
601 dragSuccessful = false;
603 ::CFRelease(osxData);
606 return dragSuccessful;
609 -(id) outlineView:(NSOutlineView*)outlineView
610 child:(NSInteger)index
613 if ((item == currentParentItem) &&
614 (index < ((NSInteger) [self getChildCount])))
615 return [self getChild:index];
617 wxDataViewItemArray dataViewChildren;
619 wxCHECK_MSG( model, 0, "Valid model in data source does not exist." );
620 model->GetChildren(wxDataViewItemFromMaybeNilItem(item), dataViewChildren);
621 [self bufferItem:item withChildren:&dataViewChildren];
622 if ([sortDescriptors count] > 0)
623 [children sortUsingFunction:CompareItems context:sortDescriptors];
624 return [self getChild:index];
627 -(BOOL) outlineView:(NSOutlineView*)outlineView isItemExpandable:(id)item
629 wxCHECK_MSG( model, 0, "Valid model in data source does not exist." );
630 return model->IsContainer(wxDataViewItemFromItem(item));
633 -(NSInteger) outlineView:(NSOutlineView*)outlineView numberOfChildrenOfItem:(id)item
635 NSInteger noOfChildren;
637 wxDataViewItemArray dataViewChildren;
640 wxCHECK_MSG( model, 0, "Valid model in data source does not exist." );
641 noOfChildren = model->GetChildren(wxDataViewItemFromMaybeNilItem(item),
643 [self bufferItem:item withChildren:&dataViewChildren];
644 if ([sortDescriptors count] > 0)
645 [children sortUsingFunction:CompareItems context:sortDescriptors];
650 outlineView:(NSOutlineView*)outlineView
651 objectValueForTableColumn:(NSTableColumn*)tableColumn
654 wxCHECK_MSG( model, nil, "Valid model in data source does not exist." );
656 wxDataViewColumn* col(static_cast<wxDataViewColumn*>([[tableColumn identifier] pointer]));
657 const unsigned colIdx = col->GetModelColumn();
659 wxDataViewItem dataViewItem(wxDataViewItemFromItem(item));
661 if ( model->HasValue(dataViewItem, colIdx) )
664 model->GetValue(value,dataViewItem, colIdx);
665 col->GetRenderer()->SetValue(value);
672 outlineView:(NSOutlineView*)outlineView
673 setObjectValue:(id)object
674 forTableColumn:(NSTableColumn*)tableColumn
677 wxDataViewColumn* col(static_cast<wxDataViewColumn*>([[tableColumn identifier] pointer]));
680 OSXOnCellChanged(object, wxDataViewItemFromItem(item), col->GetModelColumn());
683 -(void) outlineView:(NSOutlineView*)outlineView sortDescriptorsDidChange:(NSArray*)oldDescriptors
685 // Warning: the new sort descriptors are guaranteed to be only of type
686 // NSSortDescriptor! Therefore, the sort descriptors for the data source
687 // have to be converted.
688 NSArray* newDescriptors;
690 NSMutableArray* wxSortDescriptors;
692 NSUInteger noOfDescriptors;
694 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
697 // convert NSSortDescriptors to wxSortDescriptorObjects:
698 newDescriptors = [outlineView sortDescriptors];
699 noOfDescriptors = [newDescriptors count];
700 wxSortDescriptors = [NSMutableArray arrayWithCapacity:noOfDescriptors];
701 for (NSUInteger i=0; i<noOfDescriptors; ++i)
703 NSSortDescriptor* const newDescriptor = [newDescriptors objectAtIndex:i];
705 [wxSortDescriptors addObject:[[[wxSortDescriptorObject alloc] initWithModelPtr:model
706 sortingColumnPtr:dvc->GetColumn([[newDescriptor key] intValue])
707 ascending:[newDescriptor ascending]] autorelease]];
709 [(wxCocoaOutlineDataSource*)[outlineView dataSource] setSortDescriptors:wxSortDescriptors];
711 // send first the event to wxWidgets that the sorting has changed so that
712 // the program can do special actions before the sorting actually starts:
713 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_COLUMN_SORTED,dvc->GetId()); // variable defintion
715 event.SetEventObject(dvc);
716 if (noOfDescriptors > 0)
718 wxDataViewColumn* const col = [[wxSortDescriptors objectAtIndex:0] columnPtr];
720 event.SetColumn(dvc->GetColumnPosition(col));
721 event.SetDataViewColumn(col);
723 dvc->GetEventHandler()->ProcessEvent(event);
725 // start re-ordering the data;
726 // children's buffer must be cleared first because it contains the old order:
727 [self clearChildren];
728 // sorting is done while reloading the data:
729 [outlineView reloadData];
732 -(NSDragOperation) outlineView:(NSOutlineView*)outlineView validateDrop:(id<NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
734 NSArray* supportedTypes([NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]);
736 NSPasteboard* pasteboard([info draggingPasteboard]);
738 NSString* bestType([pasteboard availableTypeFromArray:supportedTypes]);
740 return NSDragOperationNone;
742 NSDragOperation dragOperation;
743 wxDataViewCtrl* const dvc(implementation->GetDataViewCtrl());
745 wxCHECK_MSG(dvc, false, "Pointer to data view control not set correctly.");
746 wxCHECK_MSG(dvc->GetModel(), false, "Pointer to model not set correctly.");
749 event(wxEVT_COMMAND_DATAVIEW_ITEM_DROP_POSSIBLE,dvc->GetId());
751 event.SetEventObject(dvc);
752 event.SetItem(wxDataViewItemFromItem(item));
753 event.SetModel(dvc->GetModel());
754 if ([bestType compare:DataViewPboardType] == NSOrderedSame)
756 NSArray* dataArray((NSArray*)[pasteboard propertyListForType:DataViewPboardType]);
757 NSUInteger indexDraggedItem, noOfDraggedItems([dataArray count]);
759 indexDraggedItem = 0;
760 while (indexDraggedItem < noOfDraggedItems)
762 wxDataObjectComposite* dataObjects(implementation->GetDnDDataObjects((NSData*)[dataArray objectAtIndex:indexDraggedItem]));
764 if (dataObjects && (dataObjects->GetFormatCount() > 0))
766 wxMemoryBuffer buffer;
768 // copy data into data object:
769 event.SetDataObject(dataObjects);
770 event.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
771 // copy data into buffer:
772 dataObjects->GetDataHere(event.GetDataFormat().GetType(),buffer.GetWriteBuf(event.GetDataSize()));
773 buffer.UngetWriteBuf(event.GetDataSize());
774 event.SetDataBuffer(buffer.GetData());
775 // finally, send event:
776 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
778 dragOperation = NSDragOperationEvery;
783 dragOperation = NSDragOperationNone;
784 indexDraggedItem = noOfDraggedItems; // stop loop
789 dragOperation = NSDragOperationNone;
790 indexDraggedItem = noOfDraggedItems; // stop loop
798 // needed to convert internally used UTF-16 representation to a UTF-8
801 wxDataObjectComposite* dataObjects (new wxDataObjectComposite());
802 wxTextDataObject* textDataObject(new wxTextDataObject());
804 osxData = ::CFStringCreateExternalRepresentation(kCFAllocatorDefault,(CFStringRef)[pasteboard stringForType:NSStringPboardType],kCFStringEncodingUTF8,32);
805 if (textDataObject->SetData(::CFDataGetLength(osxData),::CFDataGetBytePtr(osxData)))
806 dataObjects->Add(textDataObject);
808 delete textDataObject;
809 // send event if data could be copied:
810 if (dataObjects->GetFormatCount() > 0)
812 event.SetDataObject(dataObjects);
813 event.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
814 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
815 dragOperation = NSDragOperationEvery;
817 dragOperation = NSDragOperationNone;
820 dragOperation = NSDragOperationNone;
822 ::CFRelease(osxData);
826 return dragOperation;
829 -(BOOL) outlineView:(NSOutlineView*)outlineView writeItems:(NSArray*)writeItems toPasteboard:(NSPasteboard*)pasteboard
831 // the pasteboard will be filled up with an array containing the data as
832 // returned by the events (including the data type) and a concatenation of
833 // text (string) data; the text data will only be put onto the pasteboard
834 // if for all items a string representation exists
835 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
837 wxDataViewItemArray dataViewItems;
840 wxCHECK_MSG(dvc, false,"Pointer to data view control not set correctly.");
841 wxCHECK_MSG(dvc->GetModel(),false,"Pointer to model not set correctly.");
843 if ([writeItems count] > 0)
845 bool dataStringAvailable(true); // a flag indicating if for all items a data string is available
846 NSMutableArray* dataArray = [[NSMutableArray arrayWithCapacity:[writeItems count]] retain]; // data of all items
847 wxString dataString; // contains the string data of all items
849 // send a begin drag event for all selected items and proceed with
850 // dragging unless the event is vetoed:
852 event(wxEVT_COMMAND_DATAVIEW_ITEM_BEGIN_DRAG,dvc->GetId());
854 event.SetEventObject(dvc);
855 event.SetModel(dvc->GetModel());
856 for (size_t itemCounter=0; itemCounter<[writeItems count]; ++itemCounter)
858 bool itemStringAvailable(false); // a flag indicating if for the current item a string is available
859 wxDataObjectComposite* itemObject(new wxDataObjectComposite()); // data object for current item
860 wxString itemString; // contains the TAB concatenated data of an item
863 wxDataViewItemFromItem([writeItems objectAtIndex:itemCounter]));
864 itemString = ::ConcatenateDataViewItemValues(dvc,event.GetItem());
865 itemObject->Add(new wxTextDataObject(itemString));
866 event.SetDataObject(itemObject);
867 // check if event has not been vetoed:
868 if (dvc->HandleWindowEvent(event) && event.IsAllowed() && (event.GetDataObject()->GetFormatCount() > 0))
870 size_t const noOfFormats = event.GetDataObject()->GetFormatCount();
871 wxDataFormat* dataFormats(new wxDataFormat[noOfFormats]);
873 event.GetDataObject()->GetAllFormats(dataFormats,wxDataObject::Get);
874 for (size_t formatCounter=0; formatCounter<noOfFormats; ++formatCounter)
876 // constant definitions for abbreviational purposes:
877 wxDataFormatId const idDataFormat = dataFormats[formatCounter].GetType();
878 size_t const dataSize = event.GetDataObject()->GetDataSize(idDataFormat);
879 size_t const dataBufferSize = sizeof(wxDataFormatId)+dataSize;
880 // variable definitions (used in all case statements):
881 wxMemoryBuffer dataBuffer(dataBufferSize);
883 dataBuffer.AppendData(&idDataFormat,sizeof(wxDataFormatId));
884 switch (idDataFormat)
887 // otherwise wxDF_UNICODETEXT already filled up
888 // the string; and the UNICODE representation has
890 if (!itemStringAvailable)
892 event.GetDataObject()->GetDataHere(wxDF_TEXT,dataBuffer.GetAppendBuf(dataSize));
893 dataBuffer.UngetAppendBuf(dataSize);
894 [dataArray addObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
895 itemString = wxString(static_cast<char const*>(dataBuffer.GetData())+sizeof(wxDataFormatId),wxConvLocal);
896 itemStringAvailable = true;
899 case wxDF_UNICODETEXT:
901 event.GetDataObject()->GetDataHere(wxDF_UNICODETEXT,dataBuffer.GetAppendBuf(dataSize));
902 dataBuffer.UngetAppendBuf(dataSize);
903 if (itemStringAvailable) // does an object already exist as an ASCII text (see wxDF_TEXT case statement)?
904 [dataArray replaceObjectAtIndex:itemCounter withObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
906 [dataArray addObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
907 itemString = wxString::FromUTF8(static_cast<char const*>(dataBuffer.GetData())+sizeof(wxDataFormatId),dataSize);
908 itemStringAvailable = true;
912 wxFAIL_MSG("Data object has invalid or unsupported data format");
917 delete[] dataFormats;
919 if (dataStringAvailable)
920 if (itemStringAvailable)
923 dataString << wxT('\n');
924 dataString << itemString;
927 dataStringAvailable = false;
933 return NO; // dragging was vetoed or no data available
936 if (dataStringAvailable)
938 wxCFStringRef osxString(dataString);
940 [pasteboard declareTypes:[NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil] owner:nil];
941 [pasteboard setPropertyList:dataArray forType:DataViewPboardType];
942 [pasteboard setString:osxString.AsNSString() forType:NSStringPboardType];
946 [pasteboard declareTypes:[NSArray arrayWithObject:DataViewPboardType] owner:nil];
947 [pasteboard setPropertyList:dataArray forType:DataViewPboardType];
952 return NO; // no items to drag (should never occur)
958 -(void) addToBuffer:(wxPointerObject*)item
960 [items addObject:item];
965 [items removeAllObjects];
968 -(wxPointerObject*) getDataViewItemFromBuffer:(const wxDataViewItem&)item
970 return [items member:[[[wxPointerObject alloc] initWithPointer:item.GetID()] autorelease]];
973 -(wxPointerObject*) getItemFromBuffer:(wxPointerObject*)item
975 return [items member:item];
978 -(BOOL) isInBuffer:(wxPointerObject*)item
980 return [items containsObject:item];
983 -(void) removeFromBuffer:(wxPointerObject*)item
985 [items removeObject:item];
991 -(void) appendChild:(wxPointerObject*)item
993 [children addObject:item];
996 -(void) clearChildren
998 [children removeAllObjects];
1001 -(wxPointerObject*) getChild:(NSUInteger)index
1003 return [children objectAtIndex:index];
1006 -(NSUInteger) getChildCount
1008 return [children count];
1011 -(void) removeChild:(NSUInteger)index
1013 [children removeObjectAtIndex:index];
1019 -(void) clearBuffers
1022 [self clearChildren];
1023 [self setCurrentParentItem:nil];
1029 -(NSArray*) sortDescriptors
1031 return sortDescriptors;
1034 -(void) setSortDescriptors:(NSArray*)newSortDescriptors
1036 [newSortDescriptors retain];
1037 [sortDescriptors release];
1038 sortDescriptors = newSortDescriptors;
1042 // access to wxWidget's implementation
1044 -(wxPointerObject*) currentParentItem
1046 return currentParentItem;
1049 -(wxCocoaDataViewControl*) implementation
1051 return implementation;
1054 -(wxDataViewModel*) model
1059 -(void) setCurrentParentItem:(wxPointerObject*)newCurrentParentItem
1061 [newCurrentParentItem retain];
1062 [currentParentItem release];
1063 currentParentItem = newCurrentParentItem;
1066 -(void) setImplementation:(wxCocoaDataViewControl*) newImplementation
1068 implementation = newImplementation;
1071 -(void) setModel:(wxDataViewModel*) newModel
1079 -(void) bufferItem:(wxPointerObject*)parentItem withChildren:(wxDataViewItemArray*)dataViewChildrenPtr
1081 NSInteger const noOfChildren = (*dataViewChildrenPtr).GetCount();
1083 [self setCurrentParentItem:parentItem];
1084 [self clearChildren];
1085 for (NSInteger indexChild=0; indexChild<noOfChildren; ++indexChild)
1087 wxPointerObject* bufferedPointerObject;
1088 wxPointerObject* newPointerObject([[wxPointerObject alloc] initWithPointer:(*dataViewChildrenPtr)[indexChild].GetID()]);
1090 // The next statement and test looks strange but there is
1091 // unfortunately no workaround: due to the fact that two pointer
1092 // objects are identical if their pointers are identical - because the
1093 // method isEqual has been overloaded - the set operation will only
1094 // add a new pointer object if there is not already one in the set
1095 // having the same pointer. On the other side the children's array
1096 // would always add the new pointer object. This means that different
1097 // pointer objects are stored in the set and array. This will finally
1098 // lead to a crash as objects diverge. To solve this issue it is first
1099 // tested if the child already exists in the set and if it is the case
1100 // the sets object is going to be appended to the array, otheriwse the
1101 // new pointer object is added to the set and array:
1102 bufferedPointerObject = [self getItemFromBuffer:newPointerObject];
1103 if (bufferedPointerObject == nil)
1105 [items addObject:newPointerObject];
1106 [children addObject:newPointerObject];
1109 [children addObject:bufferedPointerObject];
1110 [newPointerObject release];
1116 // ============================================================================
1118 // ============================================================================
1120 @implementation wxCustomCell
1124 wxCustomRendererObject * const
1125 obj = static_cast<wxCustomRendererObject *>([self objectValue]);
1128 const wxSize size = obj->customRenderer->GetSize();
1129 return NSMakeSize(size.x, size.y);
1135 -(void) drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
1137 wxCustomRendererObject * const
1138 obj = static_cast<wxCustomRendererObject *>([self objectValue]);
1141 // this may happen for the custom cells in container rows: they don't
1146 wxDataViewCustomRenderer * const renderer = obj->customRenderer;
1148 wxDC * const dc = renderer->GetDC();
1149 renderer->WXCallRender(wxFromNSRect(controlView, cellFrame), dc, 0);
1150 renderer->SetDC(NULL);
1153 -(NSRect) imageRectForBounds:(NSRect)cellFrame
1158 -(NSRect) titleRectForBounds:(NSRect)cellFrame
1165 // ============================================================================
1167 // ============================================================================
1168 @implementation wxImageTextCell
1174 self = [super init];
1177 // initializing the text part:
1178 [self setSelectable:YES];
1179 // initializing the image part:
1181 imageSize = NSMakeSize(16,16);
1182 spaceImageText = 5.0;
1188 -(id) copyWithZone:(NSZone*)zone
1190 wxImageTextCell* cell;
1193 cell = (wxImageTextCell*) [super copyWithZone:zone];
1194 cell->image = [image retain];
1195 cell->imageSize = imageSize;
1196 cell->spaceImageText = spaceImageText;
1197 cell->xImageShift = xImageShift;
1212 -(NSTextAlignment) alignment
1214 return cellAlignment;
1217 -(void) setAlignment:(NSTextAlignment)newAlignment
1219 cellAlignment = newAlignment;
1220 switch (newAlignment)
1222 case NSCenterTextAlignment:
1223 case NSLeftTextAlignment:
1224 case NSJustifiedTextAlignment:
1225 case NSNaturalTextAlignment:
1226 [super setAlignment:NSLeftTextAlignment];
1228 case NSRightTextAlignment:
1229 [super setAlignment:NSRightTextAlignment];
1232 wxFAIL_MSG("Unknown alignment type.");
1244 -(void) setImage:(NSImage*)newImage
1256 -(void) setImageSize:(NSSize) newImageSize
1258 imageSize = newImageSize;
1264 -(NSSize) cellImageSize
1266 return NSMakeSize(imageSize.width+xImageShift+spaceImageText,imageSize.height);
1271 NSSize cellSize([super cellSize]);
1274 if (imageSize.height > cellSize.height)
1275 cellSize.height = imageSize.height;
1276 cellSize.width += imageSize.width+xImageShift+spaceImageText;
1281 -(NSSize) cellTextSize
1283 return [super cellSize];
1289 -(void) determineCellParts:(NSRect)cellFrame imagePart:(NSRect*)imageFrame textPart:(NSRect*)textFrame
1291 switch (cellAlignment)
1293 case NSCenterTextAlignment:
1295 CGFloat const cellSpace = cellFrame.size.width-[self cellSize].width;
1297 // if the cell's frame is smaller than its contents (at least
1298 // in x-direction) make sure that the image is visible:
1300 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1301 else // otherwise center the image and text in the cell's frame
1302 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText+0.5*cellSpace,NSMinXEdge);
1305 case NSJustifiedTextAlignment:
1306 case NSLeftTextAlignment:
1307 case NSNaturalTextAlignment: // how to determine the natural writing direction? TODO
1308 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1310 case NSRightTextAlignment:
1312 CGFloat const cellSpace = cellFrame.size.width-[self cellSize].width;
1314 // if the cell's frame is smaller than its contents (at least
1315 // in x-direction) make sure that the image is visible:
1317 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1318 else // otherwise right align the image and text in the cell's frame
1319 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText+cellSpace,NSMinXEdge);
1323 *imageFrame = NSZeroRect;
1324 *textFrame = NSZeroRect;
1325 wxFAIL_MSG("Unhandled alignment type.");
1329 -(void) drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
1331 NSRect textFrame, imageFrame;
1334 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1335 // draw the image part by ourselves;
1336 // check if the cell has to draw its own background (checking is done by
1337 // the parameter of the textfield's cell):
1338 if ([self drawsBackground])
1340 [[self backgroundColor] set];
1341 NSRectFill(imageFrame);
1345 // the image is slightly shifted (xImageShift) and has a fixed size
1346 // but the image's frame might be larger and starts currently on the
1347 // left side of the cell's frame; therefore, the origin and the
1348 // image's frame size have to be adjusted:
1349 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1351 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1352 imageFrame.size.width = imageSize.width;
1356 imageFrame.origin.x += xImageShift;
1357 imageFrame.size.width -= xImageShift+spaceImageText;
1359 // ...and the image has to be centered in the y-direction:
1360 if (imageFrame.size.height > imageSize.height)
1361 imageFrame.size.height = imageSize.height;
1362 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1364 // according to the documentation the coordinate system should be
1365 // flipped for NSTableViews (y-coordinate goes from top to bottom); to
1366 // draw an image correctly the coordinate system has to be transformed
1367 // to a bottom-top coordinate system, otherwise the image's
1368 // content is flipped:
1369 NSAffineTransform* coordinateTransform([NSAffineTransform transform]);
1371 if ([controlView isFlipped])
1373 [coordinateTransform scaleXBy: 1.0 yBy:-1.0]; // first the coordinate system is brought back to bottom-top orientation
1374 [coordinateTransform translateXBy:0.0 yBy:(-2.0)*imageFrame.origin.y-imageFrame.size.height]; // the coordinate system has to be moved to compensate for the
1375 [coordinateTransform concat]; // other orientation and the position of the image's frame
1377 [image drawInRect:imageFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0]; // suggested method to draw the image
1378 // instead of compositeToPoint:operation:
1379 // take back previous transformation (if the view is not flipped the
1380 // coordinate transformation matrix contains the identity matrix and
1381 // the next two operations do not change the content's transformation
1383 [coordinateTransform invert];
1384 [coordinateTransform concat];
1386 // let the textfield cell draw the text part:
1387 if (textFrame.size.width > [self cellTextSize].width)
1389 // for unknown reasons the alignment of the text cell is ignored;
1390 // therefore change the size so that alignment does not influence the
1391 // visualization anymore
1392 textFrame.size.width = [self cellTextSize].width;
1394 [super drawWithFrame:textFrame inView:controlView];
1397 -(void) editWithFrame:(NSRect)aRect inView:(NSView*)controlView editor:(NSText*)textObj delegate:(id)anObject event:(NSEvent*)theEvent
1399 NSRect textFrame, imageFrame;
1402 [self determineCellParts:aRect imagePart:&imageFrame textPart:&textFrame];
1403 [super editWithFrame:textFrame inView:controlView editor:textObj delegate:anObject event:theEvent];
1406 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1407 -(NSUInteger) hitTestForEvent:(NSEvent*)event inRect:(NSRect)cellFrame ofView:(NSView*)controlView
1409 NSPoint point = [controlView convertPoint:[event locationInWindow] fromView:nil];
1411 NSRect imageFrame, textFrame;
1414 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1417 // the image is shifted...
1418 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1420 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1421 imageFrame.size.width = imageSize.width;
1425 imageFrame.origin.x += xImageShift;
1426 imageFrame.size.width -= xImageShift+spaceImageText;
1429 if (imageFrame.size.height > imageSize.height)
1430 imageFrame.size.height = imageSize.height;
1431 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1432 // If the point is in the image rect, then it is a content hit (see
1433 // documentation for hitTestForEvent:inRect:ofView):
1434 if (NSMouseInRect(point, imageFrame, [controlView isFlipped]))
1435 return NSCellHitContentArea;
1437 // if the image was not hit let's try the text part:
1438 if (textFrame.size.width > [self cellTextSize].width)
1440 // for unknown reasons the alignment of the text cell is ignored;
1441 // therefore change the size so that alignment does not influence the
1442 // visualization anymore
1443 textFrame.size.width = [self cellTextSize].width;
1446 return [super hitTestForEvent:event inRect:textFrame ofView:controlView];
1450 -(NSRect) imageRectForBounds:(NSRect)cellFrame
1452 NSRect textFrame, imageFrame;
1455 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1456 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1458 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1459 imageFrame.size.width = imageSize.width;
1463 imageFrame.origin.x += xImageShift;
1464 imageFrame.size.width -= xImageShift+spaceImageText;
1467 if (imageFrame.size.height > imageSize.height)
1468 imageFrame.size.height = imageSize.height;
1469 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1474 -(void) selectWithFrame:(NSRect)aRect inView:(NSView*)controlView editor:(NSText*)textObj delegate:(id)anObject start:(NSInteger)selStart length:(NSInteger)selLength
1476 NSRect textFrame, imageFrame;
1479 [self determineCellParts:aRect imagePart:&imageFrame textPart:&textFrame];
1480 [super selectWithFrame:textFrame inView:controlView editor:textObj delegate:anObject start:selStart length:selLength];
1483 -(NSRect) titleRectForBounds:(NSRect)cellFrame
1485 NSRect textFrame, imageFrame;
1488 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1494 // ============================================================================
1495 // wxCocoaOutlineView
1496 // ============================================================================
1497 @implementation wxCocoaOutlineView
1500 // initializers / destructor
1504 self = [super init];
1507 currentlyEditedColumn =
1508 currentlyEditedRow = -1;
1510 [self registerForDraggedTypes:[NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]];
1511 [self setDelegate:self];
1512 [self setDoubleAction:@selector(actionDoubleClick:)];
1513 [self setDraggingSourceOperationMask:NSDragOperationEvery forLocal:NO];
1514 [self setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
1515 [self setTarget:self];
1521 // access to wxWidget's implementation
1523 -(wxCocoaDataViewControl*) implementation
1525 return implementation;
1528 -(void) setImplementation:(wxCocoaDataViewControl*) newImplementation
1530 implementation = newImplementation;
1536 -(void) actionDoubleClick:(id)sender
1538 // actually the documentation (NSTableView 2007-10-31) for doubleAction:
1539 // and setDoubleAction: seems to be wrong as this action message is always
1540 // sent whether the cell is editable or not
1541 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1543 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_ACTIVATED,dvc->GetId());
1546 event.SetEventObject(dvc);
1547 event.SetItem(wxDataViewItemFromItem([self itemAtRow:[self clickedRow]]));
1548 dvc->GetEventHandler()->ProcessEvent(event);
1555 -(NSMenu*) menuForEvent:(NSEvent*)theEvent
1557 // this method does not do any special menu event handling but only sends
1558 // an event message; therefore, the user has full control if a context
1559 // menu should be shown or not
1560 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1562 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_CONTEXT_MENU,dvc->GetId());
1564 wxDataViewItemArray selectedItems;
1567 event.SetEventObject(dvc);
1568 event.SetModel(dvc->GetModel());
1569 // get the item information;
1570 // theoretically more than one ID can be returned but the event can only
1571 // handle one item, therefore only the first item of the array is
1573 if (dvc->GetSelections(selectedItems) > 0)
1574 event.SetItem(selectedItems[0]);
1575 dvc->GetEventHandler()->ProcessEvent(event);
1583 -(void) outlineView:(NSOutlineView*)outlineView mouseDownInHeaderOfTableColumn:(NSTableColumn*)tableColumn
1585 wxDataViewColumn* const col(static_cast<wxDataViewColumn*>([[tableColumn identifier] pointer]));
1587 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1590 event(wxEVT_COMMAND_DATAVIEW_COLUMN_HEADER_CLICK,dvc->GetId());
1593 // first, send an event that the user clicked into a column's header:
1594 event.SetEventObject(dvc);
1595 event.SetColumn(dvc->GetColumnPosition(col));
1596 event.SetDataViewColumn(col);
1597 dvc->HandleWindowEvent(event);
1599 // now, check if the click may have had an influence on sorting, too;
1600 // the sorting setup has to be done only if the clicked table column is
1601 // sortable and has not been used for sorting before the click; if the
1602 // column is already responsible for sorting the native control changes
1603 // the sorting direction automatically and informs the data source via
1604 // outlineView:sortDescriptorsDidChange:
1605 if (col->IsSortable() && ([tableColumn sortDescriptorPrototype] == nil))
1607 // remove the sort order from the previously sorted column table (it
1608 // can also be that no sorted column table exists):
1609 UInt32 const noOfColumns = [outlineView numberOfColumns];
1611 for (UInt32 i=0; i<noOfColumns; ++i)
1612 [[[outlineView tableColumns] objectAtIndex:i] setSortDescriptorPrototype:nil];
1613 // make column table sortable:
1614 NSArray* sortDescriptors;
1615 NSSortDescriptor* sortDescriptor;
1617 sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[NSString stringWithFormat:@"%d",[outlineView columnWithIdentifier:[tableColumn identifier]]]
1619 sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
1620 [tableColumn setSortDescriptorPrototype:sortDescriptor];
1621 [outlineView setSortDescriptors:sortDescriptors];
1622 [sortDescriptor release];
1626 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldCollapseItem:(id)item
1628 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1630 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSING,dvc->GetId());
1633 event.SetEventObject(dvc);
1634 event.SetItem (wxDataViewItemFromItem(item));
1635 event.SetModel (dvc->GetModel());
1636 // finally send the equivalent wxWidget event:
1637 dvc->GetEventHandler()->ProcessEvent(event);
1638 // opening the container is allowed if not vetoed:
1639 return event.IsAllowed();
1642 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldExpandItem:(id)item
1644 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1646 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDING,dvc->GetId());
1649 event.SetEventObject(dvc);
1650 event.SetItem (wxDataViewItemFromItem(item));
1651 event.SetModel (dvc->GetModel());
1652 // finally send the equivalent wxWidget event:
1653 dvc->GetEventHandler()->ProcessEvent(event);
1654 // opening the container is allowed if not vetoed:
1655 return event.IsAllowed();
1658 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldSelectTableColumn:(NSTableColumn*)tableColumn
1663 -(void) outlineView:(wxCocoaOutlineView*)outlineView
1664 willDisplayCell:(id)cell
1665 forTableColumn:(NSTableColumn*)tableColumn
1668 wxDataViewCtrl * const dvc = implementation->GetDataViewCtrl();
1669 wxDataViewModel * const model = dvc->GetModel();
1671 wxDataViewColumn * const
1672 dvCol(static_cast<wxDataViewColumn*>(
1673 [[tableColumn identifier] pointer]
1676 const unsigned colIdx = dvCol->GetModelColumn();
1678 wxDataViewItem dvItem(wxDataViewItemFromItem(item));
1680 if ( !model->HasValue(dvItem, colIdx) )
1683 wxDataViewRenderer * const renderer = dvCol->GetRenderer();
1684 wxDataViewRendererNativeData * const data = renderer->GetNativeData();
1686 // let the renderer know about what it's going to render next
1687 data->SetColumnPtr(tableColumn);
1688 data->SetItem(item);
1689 data->SetItemCell(cell);
1691 // use the attributes: notice that we need to do this whether we have them
1692 // or not as even if this cell doesn't have any attributes, the previous
1693 // one might have had some and then we need to reset them back to default
1694 wxDataViewItemAttr attr;
1695 model->GetAttr(dvItem, colIdx, attr);
1696 renderer->OSXApplyAttr(attr);
1698 // and finally do draw it
1699 renderer->MacRender();
1705 -(void) outlineViewColumnDidMove:(NSNotification*)notification
1707 int const newColumnPosition = [[[notification userInfo] objectForKey:@"NSNewColumn"] intValue];
1709 wxDataViewColumn* const col(static_cast<wxDataViewColumn*>([[[[self tableColumns] objectAtIndex:newColumnPosition] identifier] pointer]));
1711 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1713 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_COLUMN_REORDERED,dvc->GetId());
1716 event.SetEventObject(dvc);
1717 event.SetColumn(dvc->GetColumnPosition(col));
1718 event.SetDataViewColumn(col);
1719 dvc->GetEventHandler()->ProcessEvent(event);
1722 -(void) outlineViewItemDidCollapse:(NSNotification*)notification
1724 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1726 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSED,dvc->GetId());
1729 event.SetEventObject(dvc);
1730 event.SetItem(wxDataViewItemFromItem(
1731 [[notification userInfo] objectForKey:@"NSObject"]));
1732 dvc->GetEventHandler()->ProcessEvent(event);
1735 -(void) outlineViewItemDidExpand:(NSNotification*)notification
1737 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1739 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDED,dvc->GetId());
1742 event.SetEventObject(dvc);
1743 event.SetItem(wxDataViewItemFromItem(
1744 [[notification userInfo] objectForKey:@"NSObject"]));
1745 dvc->GetEventHandler()->ProcessEvent(event);
1748 -(void) outlineViewSelectionDidChange:(NSNotification*)notification
1750 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1752 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_SELECTION_CHANGED,dvc->GetId());
1754 event.SetEventObject(dvc);
1755 event.SetModel(dvc->GetModel());
1756 event.SetItem(dvc->GetSelection());
1757 dvc->GetEventHandler()->ProcessEvent(event);
1760 -(void) textDidBeginEditing:(NSNotification*)notification
1762 // this notification is only sent if the user started modifying the cell
1763 // (not when the user clicked into the cell and the cell's editor is
1766 // call method of superclass (otherwise editing does not work correctly -
1767 // the outline data source class is not informed about a change of data):
1768 [super textDidBeginEditing:notification];
1770 // remember the column being edited, it will be used in textDidEndEditing:
1771 currentlyEditedColumn = [self editedColumn];
1772 currentlyEditedRow = [self editedRow];
1774 wxDataViewColumn* const col =
1775 static_cast<wxDataViewColumn*>(
1776 [[[[self tableColumns] objectAtIndex:currentlyEditedColumn] identifier] pointer]);
1778 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1781 // stop editing of a custom item first (if necessary)
1782 dvc->FinishCustomItemEditing();
1784 // now, send the event:
1786 event(wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED,dvc->GetId());
1788 event.SetEventObject(dvc);
1790 wxDataViewItemFromItem([self itemAtRow:currentlyEditedRow]));
1791 event.SetColumn(dvc->GetColumnPosition(col));
1792 event.SetDataViewColumn(col);
1793 dvc->GetEventHandler()->ProcessEvent(event);
1796 -(void) textDidEndEditing:(NSNotification*)notification
1798 // call method of superclass (otherwise editing does not work correctly -
1799 // the outline data source class is not informed about a change of data):
1800 [super textDidEndEditing:notification];
1802 // under OSX an event indicating the end of an editing session can be sent
1803 // even if no event indicating a start of an editing session has been sent
1804 // (see Documentation for NSControl controlTextDidEndEditing:); this is
1805 // not expected by a user of the wxWidgets library and therefore an
1806 // wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_DONE event is only sent if a
1807 // corresponding wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED has been sent
1808 // before; to check if a wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED has
1809 // been sent the last edited column/row are valid:
1810 if ( currentlyEditedColumn != -1 && currentlyEditedRow != -1 )
1812 wxDataViewColumn* const col =
1813 static_cast<wxDataViewColumn*>(
1814 [[[[self tableColumns] objectAtIndex:currentlyEditedColumn] identifier] pointer]);
1816 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1818 // send event to wxWidgets:
1820 event(wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_DONE,dvc->GetId());
1822 event.SetEventObject(dvc);
1824 wxDataViewItemFromItem([self itemAtRow:currentlyEditedRow]));
1825 event.SetColumn(dvc->GetColumnPosition(col));
1826 event.SetDataViewColumn(col);
1827 dvc->GetEventHandler()->ProcessEvent(event);
1830 // we're not editing any more
1831 currentlyEditedColumn =
1832 currentlyEditedRow = -1;
1838 // ============================================================================
1839 // wxCocoaDataViewControl
1840 // ============================================================================
1842 wxCocoaDataViewControl::wxCocoaDataViewControl(wxWindow* peer,
1849 [[NSScrollView alloc] initWithFrame:wxOSXGetFrameForControl(peer,pos,size)]
1852 m_OutlineView([[wxCocoaOutlineView alloc] init])
1854 // initialize scrollview (the outline view is part of a scrollview):
1855 NSScrollView* scrollview = (NSScrollView*) GetWXWidget();
1857 [scrollview setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1858 [scrollview setBorderType:NSNoBorder];
1859 [scrollview setHasVerticalScroller:YES];
1860 [scrollview setHasHorizontalScroller:YES];
1861 [scrollview setAutohidesScrollers:YES];
1862 [scrollview setDocumentView:m_OutlineView];
1864 // initialize the native control itself too
1865 InitOutlineView(style);
1868 void wxCocoaDataViewControl::InitOutlineView(long style)
1870 [m_OutlineView setImplementation:this];
1871 [m_OutlineView setColumnAutoresizingStyle:NSTableViewSequentialColumnAutoresizingStyle];
1872 [m_OutlineView setIndentationPerLevel:GetDataViewCtrl()->GetIndent()];
1873 NSUInteger maskGridStyle(NSTableViewGridNone);
1874 if (style & wxDV_HORIZ_RULES)
1875 maskGridStyle |= NSTableViewSolidHorizontalGridLineMask;
1876 if (style & wxDV_VERT_RULES)
1877 maskGridStyle |= NSTableViewSolidVerticalGridLineMask;
1878 [m_OutlineView setGridStyleMask:maskGridStyle];
1879 [m_OutlineView setAllowsMultipleSelection: (style & wxDV_MULTIPLE) != 0];
1880 [m_OutlineView setUsesAlternatingRowBackgroundColors:(style & wxDV_ROW_LINES) != 0];
1882 if ( style & wxDV_NO_HEADER )
1883 [m_OutlineView setHeaderView:nil];
1886 wxCocoaDataViewControl::~wxCocoaDataViewControl()
1888 [m_DataSource release];
1889 [m_OutlineView release];
1893 // column related methods (inherited from wxDataViewWidgetImpl)
1895 bool wxCocoaDataViewControl::ClearColumns()
1897 // as there is a bug in NSOutlineView version (OSX 10.5.6 #6555162) the
1898 // columns cannot be deleted if there is an outline column in the view;
1899 // therefore, the whole view is deleted and newly constructed:
1900 [m_OutlineView release];
1901 m_OutlineView = [[wxCocoaOutlineView alloc] init];
1902 [((NSScrollView*) GetWXWidget()) setDocumentView:m_OutlineView];
1903 [m_OutlineView setDataSource:m_DataSource];
1905 InitOutlineView(GetDataViewCtrl()->GetWindowStyle());
1910 bool wxCocoaDataViewControl::DeleteColumn(wxDataViewColumn* columnPtr)
1912 if ([m_OutlineView outlineTableColumn] == columnPtr->GetNativeData()->GetNativeColumnPtr())
1913 [m_OutlineView setOutlineTableColumn:nil]; // due to a bug this does not work
1914 [m_OutlineView removeTableColumn:columnPtr->GetNativeData()->GetNativeColumnPtr()]; // due to a confirmed bug #6555162 the deletion does not work for
1915 // outline table columns (... and there is no workaround)
1916 return (([m_OutlineView columnWithIdentifier:[[[wxPointerObject alloc] initWithPointer:columnPtr] autorelease]]) == -1);
1919 void wxCocoaDataViewControl::DoSetExpanderColumn(const wxDataViewColumn *columnPtr)
1921 [m_OutlineView setOutlineTableColumn:columnPtr->GetNativeData()->GetNativeColumnPtr()];
1924 wxDataViewColumn* wxCocoaDataViewControl::GetColumn(unsigned int pos) const
1926 return static_cast<wxDataViewColumn*>([[[[m_OutlineView tableColumns] objectAtIndex:pos] identifier] pointer]);
1929 int wxCocoaDataViewControl::GetColumnPosition(const wxDataViewColumn *columnPtr) const
1931 return [m_OutlineView columnWithIdentifier:[[[wxPointerObject alloc] initWithPointer:const_cast<wxDataViewColumn*>(columnPtr)] autorelease]];
1934 bool wxCocoaDataViewControl::InsertColumn(unsigned int pos, wxDataViewColumn* columnPtr)
1936 // create column and set the native data of the dataview column:
1937 NSTableColumn *nativeColumn = ::CreateNativeColumn(columnPtr);
1938 columnPtr->GetNativeData()->SetNativeColumnPtr(nativeColumn);
1939 // as the native control does not allow the insertion of a column at a
1940 // specified position the column is first appended and - if necessary -
1941 // moved to its final position:
1942 [m_OutlineView addTableColumn:nativeColumn];
1943 if (pos != static_cast<unsigned int>([m_OutlineView numberOfColumns]-1))
1944 [m_OutlineView moveColumn:[m_OutlineView numberOfColumns]-1 toColumn:pos];
1950 // item related methods (inherited from wxDataViewWidgetImpl)
1952 bool wxCocoaDataViewControl::Add(const wxDataViewItem& parent, const wxDataViewItem& WXUNUSED(item))
1955 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
1957 [m_OutlineView reloadData];
1961 bool wxCocoaDataViewControl::Add(const wxDataViewItem& parent, const wxDataViewItemArray& WXUNUSED(items))
1964 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
1966 [m_OutlineView reloadData];
1970 void wxCocoaDataViewControl::Collapse(const wxDataViewItem& item)
1972 [m_OutlineView collapseItem:[m_DataSource getDataViewItemFromBuffer:item]];
1975 void wxCocoaDataViewControl::EnsureVisible(const wxDataViewItem& item, const wxDataViewColumn *columnPtr)
1979 [m_OutlineView scrollRowToVisible:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
1981 [m_OutlineView scrollColumnToVisible:GetColumnPosition(columnPtr)];
1985 void wxCocoaDataViewControl::Expand(const wxDataViewItem& item)
1987 [m_OutlineView expandItem:[m_DataSource getDataViewItemFromBuffer:item]];
1990 unsigned int wxCocoaDataViewControl::GetCount() const
1992 return [m_OutlineView numberOfRows];
1995 wxRect wxCocoaDataViewControl::GetRectangle(const wxDataViewItem& item, const wxDataViewColumn *columnPtr)
1997 return wxFromNSRect([m_osxView superview],[m_OutlineView frameOfCellAtColumn:GetColumnPosition(columnPtr)
1998 row:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]]);
2001 bool wxCocoaDataViewControl::IsExpanded(const wxDataViewItem& item) const
2003 return [m_OutlineView isItemExpanded:[m_DataSource getDataViewItemFromBuffer:item]];
2006 bool wxCocoaDataViewControl::Reload()
2008 [m_DataSource clearBuffers];
2009 [m_OutlineView scrollColumnToVisible:0];
2010 [m_OutlineView scrollRowToVisible:0];
2011 [m_OutlineView reloadData];
2015 bool wxCocoaDataViewControl::Remove(const wxDataViewItem& parent, const wxDataViewItem& WXUNUSED(item))
2018 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2020 [m_OutlineView reloadData];
2024 bool wxCocoaDataViewControl::Remove(const wxDataViewItem& parent, const wxDataViewItemArray& WXUNUSED(item))
2027 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2029 [m_OutlineView reloadData];
2033 bool wxCocoaDataViewControl::Update(const wxDataViewColumn *columnPtr)
2038 bool wxCocoaDataViewControl::Update(const wxDataViewItem& WXUNUSED(parent), const wxDataViewItem& item)
2040 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:item]];
2044 bool wxCocoaDataViewControl::Update(const wxDataViewItem& WXUNUSED(parent), const wxDataViewItemArray& items)
2046 for (size_t i=0; i<items.GetCount(); ++i)
2047 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:items[i]]];
2052 // model related methods
2054 bool wxCocoaDataViewControl::AssociateModel(wxDataViewModel* model)
2056 [m_DataSource release];
2059 m_DataSource = [[wxCocoaOutlineDataSource alloc] init];
2060 [m_DataSource setImplementation:this];
2061 [m_DataSource setModel:model];
2064 m_DataSource = NULL;
2065 [m_OutlineView setDataSource:m_DataSource]; // if there is a data source the data is immediately going to be requested
2070 // selection related methods (inherited from wxDataViewWidgetImpl)
2072 int wxCocoaDataViewControl::GetSelections(wxDataViewItemArray& sel) const
2074 NSIndexSet* selectedRowIndexes([m_OutlineView selectedRowIndexes]);
2076 NSUInteger indexRow;
2080 sel.Alloc([selectedRowIndexes count]);
2081 indexRow = [selectedRowIndexes firstIndex];
2082 while (indexRow != NSNotFound)
2084 sel.Add(wxDataViewItem([[m_OutlineView itemAtRow:indexRow] pointer]));
2085 indexRow = [selectedRowIndexes indexGreaterThanIndex:indexRow];
2087 return sel.GetCount();
2090 bool wxCocoaDataViewControl::IsSelected(const wxDataViewItem& item) const
2092 return [m_OutlineView isRowSelected:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2095 void wxCocoaDataViewControl::Select(const wxDataViewItem& item)
2098 [m_OutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]]
2099 byExtendingSelection:NO];
2102 void wxCocoaDataViewControl::SelectAll()
2104 [m_OutlineView selectAll:m_OutlineView];
2107 void wxCocoaDataViewControl::Unselect(const wxDataViewItem& item)
2110 [m_OutlineView deselectRow:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2113 void wxCocoaDataViewControl::UnselectAll()
2115 [m_OutlineView deselectAll:m_OutlineView];
2119 // sorting related methods
2121 wxDataViewColumn* wxCocoaDataViewControl::GetSortingColumn() const
2123 NSArray* const columns = [m_OutlineView tableColumns];
2125 UInt32 const noOfColumns = [columns count];
2128 for (UInt32 i=0; i<noOfColumns; ++i)
2129 if ([[columns objectAtIndex:i] sortDescriptorPrototype] != nil)
2130 return static_cast<wxDataViewColumn*>([[[columns objectAtIndex:i] identifier] pointer]);
2134 void wxCocoaDataViewControl::Resort()
2136 [m_DataSource clearChildren];
2137 [m_OutlineView reloadData];
2141 // other methods (inherited from wxDataViewWidgetImpl)
2143 void wxCocoaDataViewControl::DoSetIndent(int indent)
2145 [m_OutlineView setIndentationPerLevel:static_cast<CGFloat>(indent)];
2148 void wxCocoaDataViewControl::HitTest(const wxPoint& point, wxDataViewItem& item, wxDataViewColumn*& columnPtr) const
2150 NSPoint const nativePoint = wxToNSPoint((NSScrollView*) GetWXWidget(),point);
2156 indexColumn = [m_OutlineView columnAtPoint:nativePoint];
2157 indexRow = [m_OutlineView rowAtPoint: nativePoint];
2158 if ((indexColumn >= 0) && (indexRow >= 0))
2160 columnPtr = static_cast<wxDataViewColumn*>([[[[m_OutlineView tableColumns] objectAtIndex:indexColumn] identifier] pointer]);
2161 item = wxDataViewItem([[m_OutlineView itemAtRow:indexRow] pointer]);
2166 item = wxDataViewItem();
2170 void wxCocoaDataViewControl::SetRowHeight(const wxDataViewItem& WXUNUSED(item), unsigned int WXUNUSED(height))
2171 // Not supported by the native control
2175 void wxCocoaDataViewControl::OnSize()
2177 if ([m_OutlineView numberOfColumns] == 1)
2178 [m_OutlineView sizeLastColumnToFit];
2182 // drag & drop helper methods
2184 wxDataFormat wxCocoaDataViewControl::GetDnDDataFormat(wxDataObjectComposite* dataObjects)
2186 wxDataFormat resultFormat;
2188 return resultFormat;
2190 bool compatible(true);
2192 size_t const noOfFormats = dataObjects->GetFormatCount();
2195 wxDataFormat* formats;
2197 // get all formats and check afterwards if the formats are compatible; if
2198 // they are compatible the preferred format is returned otherwise
2199 // wxDF_INVALID is returned;
2200 // currently compatible types (ordered by priority are):
2201 // - wxDF_UNICODETEXT - wxDF_TEXT
2202 formats = new wxDataFormat[noOfFormats];
2203 dataObjects->GetAllFormats(formats);
2205 while ((indexFormat < noOfFormats) && compatible)
2207 switch (resultFormat.GetType())
2210 resultFormat.SetType(formats[indexFormat].GetType()); // first format (should only be reached if indexFormat == 0)
2213 if (formats[indexFormat].GetType() == wxDF_UNICODETEXT)
2214 resultFormat.SetType(wxDF_UNICODETEXT);
2215 else // incompatible
2217 resultFormat.SetType(wxDF_INVALID);
2221 case wxDF_UNICODETEXT:
2222 if (formats[indexFormat].GetType() != wxDF_TEXT)
2224 resultFormat.SetType(wxDF_INVALID);
2229 resultFormat.SetType(wxDF_INVALID); // not (yet) supported format
2237 return resultFormat;
2240 wxDataObjectComposite* wxCocoaDataViewControl::GetDnDDataObjects(NSData* dataObject) const
2242 wxDataFormatId dataFormatID;
2245 [dataObject getBytes:&dataFormatID length:sizeof(wxDataFormatId)];
2246 switch (dataFormatID)
2249 case wxDF_UNICODETEXT:
2251 wxTextDataObject* textDataObject(new wxTextDataObject());
2253 if (textDataObject->SetData(wxDataFormat(dataFormatID),[dataObject length]-sizeof(wxDataFormatId),static_cast<char const*>([dataObject bytes])+sizeof(wxDataFormatId)))
2255 wxDataObjectComposite* dataObjectComposite(new wxDataObjectComposite());
2257 dataObjectComposite->Add(textDataObject);
2258 return dataObjectComposite;
2262 delete textDataObject;
2272 id wxCocoaDataViewControl::GetItemAtRow(int row) const
2274 return [m_OutlineView itemAtRow:row];
2277 // ----------------------------------------------------------------------------
2278 // wxDataViewRendererNativeData
2279 // ----------------------------------------------------------------------------
2281 void wxDataViewRendererNativeData::Init()
2284 m_origTextColour = NULL;
2285 m_ellipsizeMode = wxELLIPSIZE_MIDDLE;
2288 ApplyLineBreakMode(m_ColumnCell);
2291 void wxDataViewRendererNativeData::ApplyLineBreakMode(NSCell *cell)
2293 NSLineBreakMode nsMode = NSLineBreakByWordWrapping;
2294 switch ( m_ellipsizeMode )
2296 case wxELLIPSIZE_NONE:
2297 nsMode = NSLineBreakByClipping;
2300 case wxELLIPSIZE_START:
2301 nsMode = NSLineBreakByTruncatingHead;
2304 case wxELLIPSIZE_MIDDLE:
2305 nsMode = NSLineBreakByTruncatingMiddle;
2308 case wxELLIPSIZE_END:
2309 nsMode = NSLineBreakByTruncatingTail;
2313 wxASSERT_MSG( nsMode != NSLineBreakByWordWrapping, "unknown wxEllipsizeMode" );
2315 [cell setLineBreakMode: nsMode];
2318 // ---------------------------------------------------------
2319 // wxDataViewRenderer
2320 // ---------------------------------------------------------
2322 wxDataViewRenderer::wxDataViewRenderer(const wxString& varianttype,
2323 wxDataViewCellMode mode,
2325 : wxDataViewRendererBase(varianttype, mode, align),
2328 m_NativeDataPtr(NULL)
2332 wxDataViewRenderer::~wxDataViewRenderer()
2334 delete m_NativeDataPtr;
2337 void wxDataViewRenderer::SetAlignment(int align)
2339 m_alignment = align;
2340 [GetNativeData()->GetColumnCell() setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2343 void wxDataViewRenderer::SetMode(wxDataViewCellMode mode)
2347 [GetOwner()->GetNativeData()->GetNativeColumnPtr() setEditable:(mode == wxDATAVIEW_CELL_EDITABLE)];
2350 void wxDataViewRenderer::SetNativeData(wxDataViewRendererNativeData* newNativeDataPtr)
2352 delete m_NativeDataPtr;
2353 m_NativeDataPtr = newNativeDataPtr;
2356 void wxDataViewRenderer::EnableEllipsize(wxEllipsizeMode mode)
2358 // we need to store this value to apply it to the columns headerCell in
2359 // CreateNativeColumn()
2360 GetNativeData()->SetEllipsizeMode(mode);
2362 // but we may already apply it to the column cell which will be used for
2364 GetNativeData()->ApplyLineBreakMode(GetNativeData()->GetColumnCell());
2367 wxEllipsizeMode wxDataViewRenderer::GetEllipsizeMode() const
2369 return GetNativeData()->GetEllipsizeMode();
2373 wxDataViewRenderer::OSXOnCellChanged(NSObject *object,
2374 const wxDataViewItem& item,
2377 // TODO: we probably should get rid of this code entirely and make this
2378 // function pure virtual, but currently we still have some native
2379 // renderers (wxDataViewChoiceRenderer) which don't override it and
2380 // there is also wxDataViewCustomRenderer for which it's not obvious
2381 // how it should be implemented so keep this "auto-deduction" of
2382 // variant type from NSObject for now
2385 if ( [object isKindOfClass:[NSString class]] )
2386 value = ObjectToString(object);
2387 else if ( [object isKindOfClass:[NSNumber class]] )
2388 value = ObjectToLong(object);
2389 else if ( [object isKindOfClass:[NSDate class]] )
2390 value = ObjectToDate(object);
2393 wxFAIL_MSG( wxString::Format
2395 "unknown value type %s",
2396 wxCFStringRef::AsString([object className])
2401 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2402 model->ChangeValue(value, item, col);
2405 void wxDataViewRenderer::OSXApplyAttr(const wxDataViewItemAttr& attr)
2407 wxDataViewRendererNativeData * const data = GetNativeData();
2408 NSCell * const cell = data->GetItemCell();
2410 // set the font and text colour to use: we need to do it if we had ever
2411 // changed them before, even if this item itself doesn't have any special
2412 // attributes as otherwise it would reuse the attributes from the previous
2413 // cell rendered using the same renderer
2414 NSFont *font = NULL;
2415 NSColor *colText = NULL;
2417 if ( attr.HasFont() )
2419 font = data->GetOriginalFont();
2422 // this is the first time we're setting the font, remember the
2423 // original one before changing it
2425 data->SaveOriginalFont(font);
2430 // FIXME: using wxFont methods here doesn't work for some reason
2431 NSFontManager * const fm = [NSFontManager sharedFontManager];
2432 if ( attr.GetBold() )
2433 font = [fm convertFont:font toHaveTrait:NSBoldFontMask];
2434 if ( attr.GetItalic() )
2435 font = [fm convertFont:font toHaveTrait:NSItalicFontMask];
2437 //else: can't change font if the cell doesn't have any
2440 if ( attr.HasColour() )
2442 // we can set font for any cell but only NSTextFieldCell provides
2443 // a method for setting text colour so check that this method is
2444 // available before using it
2445 if ( [cell respondsToSelector:@selector(setTextColor:)] &&
2446 [cell respondsToSelector:@selector(textColor)] )
2448 if ( !data->GetOriginalTextColour() )
2450 // the cast to (untyped) id is safe because of the check above
2451 data->SaveOriginalTextColour([(id)cell textColor]);
2454 const wxColour& c = attr.GetColour();
2455 colText = [NSColor colorWithDeviceRed:c.Red() / 255.
2456 green:c.Green() / 255.
2457 blue:c.Blue() / 255.
2458 alpha:c.Alpha() / 255.];
2463 font = data->GetOriginalFont();
2465 colText = data->GetOriginalTextColour();
2468 [cell setFont:font];
2471 [(id)cell setTextColor:colText];
2474 IMPLEMENT_ABSTRACT_CLASS(wxDataViewRenderer,wxDataViewRendererBase)
2476 // ---------------------------------------------------------
2477 // wxDataViewCustomRenderer
2478 // ---------------------------------------------------------
2479 wxDataViewCustomRenderer::wxDataViewCustomRenderer(const wxString& varianttype,
2480 wxDataViewCellMode mode,
2482 : wxDataViewCustomRendererBase(varianttype, mode, align),
2483 m_editorCtrlPtr(NULL),
2486 SetNativeData(new wxDataViewRendererNativeData([[wxCustomCell alloc] init]));
2489 bool wxDataViewCustomRenderer::MacRender()
2491 [GetNativeData()->GetItemCell() setObjectValue:[[[wxCustomRendererObject alloc] initWithRenderer:this] autorelease]];
2495 void wxDataViewCustomRenderer::OSXApplyAttr(const wxDataViewItemAttr& attr)
2497 // simply save the attribute so that it could be reused from our Render()
2500 // it's not necessary to call the base class version which sets the cell
2501 // properties to correspond to this attribute because we currently don't
2502 // use any NSCell methods in custom renderers anyhow but if we ever start
2503 // doing this (e.g. override RenderText() here to use NSTextFieldCell
2504 // methods), then we should pass it on to wxDataViewRenderer here
2507 IMPLEMENT_ABSTRACT_CLASS(wxDataViewCustomRenderer, wxDataViewRenderer)
2509 // ---------------------------------------------------------
2510 // wxDataViewTextRenderer
2511 // ---------------------------------------------------------
2512 wxDataViewTextRenderer::wxDataViewTextRenderer(const wxString& varianttype,
2513 wxDataViewCellMode mode,
2515 : wxDataViewRenderer(varianttype,mode,align)
2517 NSTextFieldCell* cell;
2520 cell = [[NSTextFieldCell alloc] init];
2521 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2522 SetNativeData(new wxDataViewRendererNativeData(cell));
2526 bool wxDataViewTextRenderer::MacRender()
2528 if (GetValue().GetType() == GetVariantType())
2530 [GetNativeData()->GetItemCell() setObjectValue:wxCFStringRef(GetValue().GetString()).AsNSString()];
2535 wxFAIL_MSG(wxString("Text renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2541 wxDataViewTextRenderer::OSXOnCellChanged(NSObject *value,
2542 const wxDataViewItem& item,
2545 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2546 model->ChangeValue(ObjectToString(value), item, col);
2549 IMPLEMENT_CLASS(wxDataViewTextRenderer,wxDataViewRenderer)
2551 // ---------------------------------------------------------
2552 // wxDataViewBitmapRenderer
2553 // ---------------------------------------------------------
2554 wxDataViewBitmapRenderer::wxDataViewBitmapRenderer(const wxString& varianttype,
2555 wxDataViewCellMode mode,
2557 : wxDataViewRenderer(varianttype,mode,align)
2562 cell = [[NSImageCell alloc] init];
2563 SetNativeData(new wxDataViewRendererNativeData(cell));
2567 // This method returns 'true' if
2568 // - the passed bitmap is valid and it could be assigned to the native data
2570 // - the passed bitmap is invalid (or is not initialized); this case
2571 // simulates a non-existing bitmap.
2572 // In all other cases the method returns 'false'.
2573 bool wxDataViewBitmapRenderer::MacRender()
2575 wxCHECK_MSG(GetValue().GetType() == GetVariantType(),false,wxString("Bitmap renderer cannot render value; value type: ") << GetValue().GetType());
2579 bitmap << GetValue();
2581 [GetNativeData()->GetItemCell() setObjectValue:[[bitmap.GetNSImage() retain] autorelease]];
2585 IMPLEMENT_CLASS(wxDataViewBitmapRenderer,wxDataViewRenderer)
2587 // -------------------------------------
2588 // wxDataViewChoiceRenderer
2589 // -------------------------------------
2590 wxDataViewChoiceRenderer::wxDataViewChoiceRenderer(const wxArrayString& choices,
2591 wxDataViewCellMode mode,
2593 : wxDataViewRenderer(wxT("string"), mode, alignment),
2596 NSPopUpButtonCell* cell;
2599 cell = [[NSPopUpButtonCell alloc] init];
2600 [cell setControlSize:NSMiniControlSize];
2601 [cell setFont:[[NSFont fontWithName:[[cell font] fontName] size:[NSFont systemFontSizeForControlSize:NSMiniControlSize]] autorelease]];
2602 for (size_t i=0; i<choices.GetCount(); ++i)
2603 [cell addItemWithTitle:[[wxCFStringRef(choices[i]).AsNSString() retain] autorelease]];
2604 SetNativeData(new wxDataViewRendererNativeData(cell));
2608 bool wxDataViewChoiceRenderer::MacRender()
2610 if (GetValue().GetType() == GetVariantType())
2612 [((NSPopUpButtonCell*) GetNativeData()->GetItemCell()) selectItemWithTitle:[[wxCFStringRef(GetValue().GetString()).AsNSString() retain] autorelease]];
2617 wxFAIL_MSG(wxString("Choice renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2622 IMPLEMENT_CLASS(wxDataViewChoiceRenderer,wxDataViewRenderer)
2624 // ---------------------------------------------------------
2625 // wxDataViewDateRenderer
2626 // ---------------------------------------------------------
2628 wxDataViewDateRenderer::wxDataViewDateRenderer(const wxString& varianttype,
2629 wxDataViewCellMode mode,
2631 : wxDataViewRenderer(varianttype,mode,align)
2633 NSTextFieldCell* cell;
2635 NSDateFormatter* dateFormatter;
2638 dateFormatter = [[NSDateFormatter alloc] init];
2639 [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
2640 [dateFormatter setDateStyle:NSDateFormatterShortStyle];
2641 cell = [[NSTextFieldCell alloc] init];
2642 [cell setFormatter:dateFormatter];
2643 SetNativeData(new wxDataViewRendererNativeData(cell,[NSDate dateWithString:@"2000-12-30 20:00:00 +0000"]));
2645 [dateFormatter release];
2648 bool wxDataViewDateRenderer::MacRender()
2650 if (GetValue().GetType() == GetVariantType())
2652 if (GetValue().GetDateTime().IsValid())
2654 // -- find best fitting style to show the date --
2655 // as the style should be identical for all cells a reference date
2656 // instead of the actual cell's date value is used for all cells;
2657 // this reference date is stored in the renderer's native data
2658 // section for speed purposes; otherwise, the reference date's
2659 // string has to be recalculated for each item that may become
2660 // timewise long if a lot of rows using dates exist; the algorithm
2661 // has the preference to display as much information as possible
2662 // in the first instance; but as this is often impossible due to
2663 // space restrictions the style is shortened per loop; finally, if
2664 // the shortest time and date format does not fit into the cell
2665 // the time part is dropped; remark: the time part itself is not
2666 // modified per iteration loop and only uses the short style,
2667 // means that only the hours and minutes are being shown
2669 // GetObject() returns a date for testing the size of a date object
2670 [GetNativeData()->GetItemCell() setObjectValue:GetNativeData()->GetObject()];
2671 [[GetNativeData()->GetItemCell() formatter] setTimeStyle:NSDateFormatterShortStyle];
2672 for (int dateFormatterStyle=4; dateFormatterStyle>0; --dateFormatterStyle)
2674 [[GetNativeData()->GetItemCell() formatter] setDateStyle:(NSDateFormatterStyle)dateFormatterStyle];
2675 if (dateFormatterStyle == 1)
2677 // if the shortest style for displaying the date and time
2678 // is too long to be fully visible remove the time part of
2680 if ([GetNativeData()->GetItemCell() cellSize].width > [GetNativeData()->GetColumnPtr() width])
2681 [[GetNativeData()->GetItemCell() formatter] setTimeStyle:NSDateFormatterNoStyle];
2683 // basically not necessary as the loop would end anyway
2684 // but let's save the last comparison
2688 else if ([GetNativeData()->GetItemCell() cellSize].width <= [GetNativeData()->GetColumnPtr() width])
2691 // set data (the style is set by the previous loop); on OSX the
2692 // date has to be specified with respect to UTC; in wxWidgets the
2693 // date is always entered in the local timezone; so, we have to do
2694 // a conversion from the local to UTC timezone when adding the
2695 // seconds to 1970-01-01 UTC:
2696 [GetNativeData()->GetItemCell() setObjectValue:[NSDate dateWithTimeIntervalSince1970:GetValue().GetDateTime().ToUTC().Subtract(wxDateTime(1,wxDateTime::Jan,1970)).GetSeconds().ToDouble()]];
2702 wxFAIL_MSG(wxString("Date renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2708 wxDataViewDateRenderer::OSXOnCellChanged(NSObject *value,
2709 const wxDataViewItem& item,
2712 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2713 model->ChangeValue(ObjectToDate(value), item, col);
2716 IMPLEMENT_ABSTRACT_CLASS(wxDataViewDateRenderer,wxDataViewRenderer)
2718 // ---------------------------------------------------------
2719 // wxDataViewIconTextRenderer
2720 // ---------------------------------------------------------
2721 wxDataViewIconTextRenderer::wxDataViewIconTextRenderer(const wxString& varianttype,
2722 wxDataViewCellMode mode,
2724 : wxDataViewRenderer(varianttype,mode)
2726 wxImageTextCell* cell;
2729 cell = [[wxImageTextCell alloc] init];
2730 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2731 SetNativeData(new wxDataViewRendererNativeData(cell));
2735 bool wxDataViewIconTextRenderer::MacRender()
2737 if (GetValue().GetType() == GetVariantType())
2739 wxDataViewIconText iconText;
2741 wxImageTextCell* cell;
2743 cell = (wxImageTextCell*) GetNativeData()->GetItemCell();
2744 iconText << GetValue();
2745 if (iconText.GetIcon().IsOk())
2746 [cell setImage:[[wxBitmap(iconText.GetIcon()).GetNSImage() retain] autorelease]];
2747 [cell setStringValue:[[wxCFStringRef(iconText.GetText()).AsNSString() retain] autorelease]];
2752 wxFAIL_MSG(wxString("Icon & text renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2758 wxDataViewIconTextRenderer::OSXOnCellChanged(NSObject *value,
2759 const wxDataViewItem& item,
2762 wxVariant valueIconText;
2763 valueIconText << wxDataViewIconText(ObjectToString(value));
2765 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2766 model->ChangeValue(valueIconText, item, col);
2769 IMPLEMENT_ABSTRACT_CLASS(wxDataViewIconTextRenderer,wxDataViewRenderer)
2771 // ---------------------------------------------------------
2772 // wxDataViewToggleRenderer
2773 // ---------------------------------------------------------
2774 wxDataViewToggleRenderer::wxDataViewToggleRenderer(const wxString& varianttype,
2775 wxDataViewCellMode mode,
2777 : wxDataViewRenderer(varianttype,mode)
2782 cell = [[NSButtonCell alloc] init];
2783 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2784 [cell setButtonType:NSSwitchButton];
2785 [cell setImagePosition:NSImageOnly];
2786 SetNativeData(new wxDataViewRendererNativeData(cell));
2790 bool wxDataViewToggleRenderer::MacRender()
2792 if (GetValue().GetType() == GetVariantType())
2794 [GetNativeData()->GetItemCell() setIntValue:GetValue().GetLong()];
2799 wxFAIL_MSG(wxString("Toggle renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2805 wxDataViewToggleRenderer::OSXOnCellChanged(NSObject *value,
2806 const wxDataViewItem& item,
2809 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2810 model->ChangeValue(ObjectToBool(value), item, col);
2813 IMPLEMENT_ABSTRACT_CLASS(wxDataViewToggleRenderer,wxDataViewRenderer)
2815 // ---------------------------------------------------------
2816 // wxDataViewProgressRenderer
2817 // ---------------------------------------------------------
2818 wxDataViewProgressRenderer::wxDataViewProgressRenderer(const wxString& label,
2819 const wxString& varianttype,
2820 wxDataViewCellMode mode,
2822 : wxDataViewRenderer(varianttype,mode,align)
2824 NSLevelIndicatorCell* cell;
2826 cell = [[NSLevelIndicatorCell alloc] initWithLevelIndicatorStyle:NSContinuousCapacityLevelIndicatorStyle];
2827 [cell setMinValue:0];
2828 [cell setMaxValue:100];
2829 SetNativeData(new wxDataViewRendererNativeData(cell));
2833 bool wxDataViewProgressRenderer::MacRender()
2835 if (GetValue().GetType() == GetVariantType())
2837 [GetNativeData()->GetItemCell() setIntValue:GetValue().GetLong()];
2842 wxFAIL_MSG(wxString("Progress renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2848 wxDataViewProgressRenderer::OSXOnCellChanged(NSObject *value,
2849 const wxDataViewItem& item,
2852 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2853 model->ChangeValue(ObjectToLong(value), item, col);
2856 IMPLEMENT_ABSTRACT_CLASS(wxDataViewProgressRenderer,wxDataViewRenderer)
2858 // ---------------------------------------------------------
2860 // ---------------------------------------------------------
2862 wxDataViewColumn::wxDataViewColumn(const wxString& title,
2863 wxDataViewRenderer* renderer,
2864 unsigned int model_column,
2868 : wxDataViewColumnBase(renderer, model_column),
2869 m_NativeDataPtr(new wxDataViewColumnNativeData()),
2872 InitCommon(width, align, flags);
2873 if (renderer && (renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
2874 renderer->SetAlignment(align);
2877 wxDataViewColumn::wxDataViewColumn(const wxBitmap& bitmap,
2878 wxDataViewRenderer* renderer,
2879 unsigned int model_column,
2883 : wxDataViewColumnBase(bitmap, renderer, model_column),
2884 m_NativeDataPtr(new wxDataViewColumnNativeData())
2886 InitCommon(width, align, flags);
2887 if (renderer && (renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
2888 renderer->SetAlignment(align);
2891 wxDataViewColumn::~wxDataViewColumn()
2893 delete m_NativeDataPtr;
2896 int wxDataViewColumn::GetWidth() const
2898 return [m_NativeDataPtr->GetNativeColumnPtr() width];
2901 bool wxDataViewColumn::IsSortKey() const
2903 NSTableColumn *nsCol = GetNativeData()->GetNativeColumnPtr();
2904 return nsCol && ([nsCol sortDescriptorPrototype] != nil);
2907 void wxDataViewColumn::SetAlignment(wxAlignment align)
2909 m_alignment = align;
2910 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2911 if (m_renderer && (m_renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
2912 m_renderer->SetAlignment(align);
2915 void wxDataViewColumn::SetBitmap(const wxBitmap& bitmap)
2917 // bitmaps and titles cannot exist at the same time - if the bitmap is set
2918 // the title is removed:
2919 m_title = wxEmptyString;
2920 wxDataViewColumnBase::SetBitmap(bitmap);
2921 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setImage:[[bitmap.GetNSImage() retain] autorelease]];
2924 void wxDataViewColumn::SetMaxWidth(int maxWidth)
2926 m_maxWidth = maxWidth;
2927 [m_NativeDataPtr->GetNativeColumnPtr() setMaxWidth:maxWidth];
2930 void wxDataViewColumn::SetMinWidth(int minWidth)
2932 m_minWidth = minWidth;
2933 [m_NativeDataPtr->GetNativeColumnPtr() setMinWidth:minWidth];
2936 void wxDataViewColumn::SetReorderable(bool reorderable)
2940 void wxDataViewColumn::SetHidden(bool hidden)
2942 // How to set flag here?
2944 [m_NativeDataPtr->GetNativeColumnPtr() setHidden:hidden];
2947 bool wxDataViewColumn::IsHidden() const
2949 return [m_NativeDataPtr->GetNativeColumnPtr() isHidden];
2952 void wxDataViewColumn::SetResizeable(bool resizeable)
2954 wxDataViewColumnBase::SetResizeable(resizeable);
2956 [m_NativeDataPtr->GetNativeColumnPtr() setResizingMask:NSTableColumnUserResizingMask];
2958 [m_NativeDataPtr->GetNativeColumnPtr() setResizingMask:NSTableColumnNoResizing];
2961 void wxDataViewColumn::SetSortable(bool sortable)
2963 wxDataViewColumnBase::SetSortable(sortable);
2966 void wxDataViewColumn::SetSortOrder(bool ascending)
2968 if (m_ascending != ascending)
2970 m_ascending = ascending;
2973 // change sorting order:
2974 NSArray* sortDescriptors;
2975 NSSortDescriptor* sortDescriptor;
2976 NSTableColumn* tableColumn;
2978 tableColumn = m_NativeDataPtr->GetNativeColumnPtr();
2979 sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[[tableColumn sortDescriptorPrototype] key] ascending:m_ascending];
2980 sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
2981 [tableColumn setSortDescriptorPrototype:sortDescriptor];
2982 [[tableColumn tableView] setSortDescriptors:sortDescriptors];
2983 [sortDescriptor release];
2988 void wxDataViewColumn::SetTitle(const wxString& title)
2990 // bitmaps and titles cannot exist at the same time - if the title is set
2991 // the bitmap is removed:
2992 wxDataViewColumnBase::SetBitmap(wxBitmap());
2994 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setStringValue:[[wxCFStringRef(title).AsNSString() retain] autorelease]];
2997 void wxDataViewColumn::SetWidth(int width)
2999 [m_NativeDataPtr->GetNativeColumnPtr() setWidth:width];
3003 void wxDataViewColumn::SetAsSortKey(bool WXUNUSED(sort))
3005 // see wxGTK native wxDataViewColumn implementation
3006 wxFAIL_MSG("not implemented");
3009 void wxDataViewColumn::SetNativeData(wxDataViewColumnNativeData* newNativeDataPtr)
3011 delete m_NativeDataPtr;
3012 m_NativeDataPtr = newNativeDataPtr;
3015 #endif // (wxUSE_DATAVIEWCTRL == 1) && !defined(wxUSE_GENERICDATAVIEWCTRL)