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"
28 // ============================================================================
29 // Constants used locally
30 // ============================================================================
32 #define DataViewPboardType @"OutlineViewItem"
34 // ============================================================================
35 // Classes used locally in dataview.mm
36 // ============================================================================
38 // ----------------------------------------------------------------------------
39 // wxCustomRendererObject
40 // ----------------------------------------------------------------------------
42 @interface wxCustomRendererObject : NSObject <NSCopying>
45 wxDataViewCustomRenderer* customRenderer; // not owned by the class
49 -(id) initWithRenderer:(wxDataViewCustomRenderer*)renderer;
52 @implementation wxCustomRendererObject
59 customRenderer = NULL;
64 -(id) initWithRenderer:(wxDataViewCustomRenderer*)renderer
69 customRenderer = renderer;
74 -(id) copyWithZone:(NSZone*)zone
76 wxCustomRendererObject* copy;
78 copy = [[[self class] allocWithZone:zone] init];
79 copy->customRenderer = customRenderer;
85 // ----------------------------------------------------------------------------
86 // wxDVCNSTableColumn: exists only to override NSTableColumn:dataCellForRow:
87 // ----------------------------------------------------------------------------
89 @interface wxDVCNSTableColumn : NSTableColumn
93 -(id) dataCellForRow:(NSInteger)row;
96 @implementation wxDVCNSTableColumn
98 -(id) dataCellForRow:(NSInteger)row
100 // what we want to do here is to simply return nil for the cells which
101 // shouldn't show anything as otherwise we would show e.g. empty combo box
102 // or progress cells in the columns using the corresponding types even for
103 // the container rows which is wrong
105 // half of the problem is just finding the objects we need from the column
106 // pointer which is itself stashed inside wxPointerObject which we use as
108 const wxDataViewColumn * const
109 dvCol = static_cast<wxDataViewColumn *>(
110 [(wxPointerObject *)[self identifier] pointer]
113 const wxDataViewCtrl * const dvc = dvCol->GetOwner();
114 const wxCocoaDataViewControl * const
115 peer = static_cast<wxCocoaDataViewControl *>(dvc->GetPeer());
118 // once we do have everything, simply ask NSOutlineView for the item...
119 const id item = peer->GetItemAtRow(row);
122 // ... and if it succeeded, ask the model whether it has any value
123 wxDataViewItem dvItem([((wxPointerObject*) item) pointer]);
125 if ( !dvc->GetModel()->HasValue(dvItem, dvCol->GetModelColumn()) )
129 return [super dataCellForRow:row];
134 // ============================================================================
136 // ============================================================================
141 // convert from NSObject to different C++ types: all these functions check
142 // that the conversion really makes sense and assert if it doesn't
143 wxString ObjectToString(NSObject *object)
145 wxCHECK_MSG( [object isKindOfClass:[NSString class]], "",
148 "string expected but got %s",
149 wxCFStringRef::AsString([object className])
152 return wxCFStringRef([((NSString*) object) retain]).AsString();
155 bool ObjectToBool(NSObject *object)
157 // actually the value must be of NSCFBoolean class but it's private so we
158 // can't check for it directly
159 wxCHECK_MSG( [object isKindOfClass:[NSNumber class]], false,
162 "number expected but got %s",
163 wxCFStringRef::AsString([object className])
166 return [(NSNumber *)object boolValue];
169 long ObjectToLong(NSObject *object)
171 wxCHECK_MSG( [object isKindOfClass:[NSNumber class]], -1,
174 "number expected but got %s",
175 wxCFStringRef::AsString([object className])
178 return [(NSNumber *)object longValue];
181 wxDateTime ObjectToDate(NSObject *object)
183 wxCHECK_MSG( [object isKindOfClass:[NSDate class]], wxInvalidDateTime,
186 "date expected but got %s",
187 wxCFStringRef::AsString([object className])
190 // get the number of seconds since 1970-01-01 UTC and this is the only
191 // way to convert a double to a wxLongLong
192 const wxLongLong seconds = [((NSDate*) object) timeIntervalSince1970];
194 wxDateTime dt(1, wxDateTime::Jan, 1970);
195 dt.Add(wxTimeSpan(0,0,seconds));
197 // the user has entered a date in the local timezone but seconds
198 // contains the number of seconds from date in the local timezone
199 // since 1970-01-01 UTC; therefore, the timezone information has to be
200 // transferred to wxWidgets, too:
201 dt.MakeFromTimezone(wxDateTime::UTC);
206 NSInteger CompareItems(id item1, id item2, void* context)
208 NSArray* const sortDescriptors = (NSArray*) context;
210 NSUInteger const count = [sortDescriptors count];
212 NSInteger result = NSOrderedSame;
213 for ( NSUInteger i = 0; i < count && result == NSOrderedSame; ++i )
215 // constant definition for abbreviational purposes:
216 wxSortDescriptorObject* const
217 sortDescriptor = (wxSortDescriptorObject*)
218 [sortDescriptors objectAtIndex:i];
220 int rc = [sortDescriptor modelPtr]->Compare
222 wxDataViewItem([((wxPointerObject*) item1) pointer]),
223 wxDataViewItem([((wxPointerObject*) item2) pointer]),
224 [sortDescriptor columnPtr]->GetModelColumn(),
225 [sortDescriptor ascending] == YES
229 result = NSOrderedAscending;
231 result = NSOrderedDescending;
237 NSTextAlignment ConvertToNativeHorizontalTextAlignment(int alignment)
239 if (alignment & wxALIGN_CENTER_HORIZONTAL)
240 return NSCenterTextAlignment;
241 else if (alignment & wxALIGN_RIGHT)
242 return NSRightTextAlignment;
244 return NSLeftTextAlignment;
247 NSTableColumn* CreateNativeColumn(const wxDataViewColumn *column)
249 wxDataViewRenderer * const renderer = column->GetRenderer();
251 wxCHECK_MSG( renderer, NULL, "column should have a renderer" );
253 wxDVCNSTableColumn * const nativeColumn(
254 [[wxDVCNSTableColumn alloc] initWithIdentifier:
255 [[[wxPointerObject alloc] initWithPointer:
256 const_cast<wxDataViewColumn*>(column)]
260 // setting the size related parameters:
261 if (column->IsResizeable())
263 [nativeColumn setResizingMask:NSTableColumnUserResizingMask];
264 [nativeColumn setMinWidth:column->GetMinWidth()];
265 [nativeColumn setMaxWidth:column->GetMaxWidth()];
269 [nativeColumn setResizingMask:NSTableColumnNoResizing];
270 [nativeColumn setMinWidth:column->GetWidth()];
271 [nativeColumn setMaxWidth:column->GetWidth()];
273 [nativeColumn setWidth:column->GetWidth()];
275 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
276 // setting the visibility:
277 [nativeColumn setHidden:static_cast<BOOL>(column->IsHidden())];
280 wxDataViewRendererNativeData * const renderData = renderer->GetNativeData();
282 // setting the header:
283 [[nativeColumn headerCell] setAlignment:
284 ConvertToNativeHorizontalTextAlignment(column->GetAlignment())];
285 [[nativeColumn headerCell] setStringValue:
286 [[wxCFStringRef(column->GetTitle()).AsNSString() retain] autorelease]];
287 renderData->ApplyLineBreakMode([nativeColumn headerCell]);
289 // setting data cell's properties:
290 [[nativeColumn dataCell] setWraps:NO];
291 // setting the default data cell:
292 [nativeColumn setDataCell:renderData->GetColumnCell()];
293 // setting the editablility:
294 const bool isEditable = renderer->GetMode() == wxDATAVIEW_CELL_EDITABLE;
296 [nativeColumn setEditable:isEditable];
297 [[nativeColumn dataCell] setEditable:isEditable];
302 } // anonymous namespace
304 // ============================================================================
305 // Public helper functions for dataview implementation on OSX
306 // ============================================================================
308 wxWidgetImplType* CreateDataView(wxWindowMac* wxpeer,
309 wxWindowMac* WXUNUSED(parent),
310 wxWindowID WXUNUSED(id),
314 long WXUNUSED(extraStyle))
316 return new wxCocoaDataViewControl(wxpeer,pos,size,style);
319 // ============================================================================
321 // ============================================================================
323 @implementation wxPointerObject
329 self->pointer = NULL;
333 -(id) initWithPointer:(void*) initPointer
337 self->pointer = initPointer;
342 // inherited methods from NSObject
344 -(BOOL) isEqual:(id)object
346 return (object != nil) &&
347 ([object isKindOfClass:[wxPointerObject class]]) &&
348 (pointer == [((wxPointerObject*) object) pointer]);
353 return (NSUInteger) pointer;
361 -(void) setPointer:(void*) newPointer
363 pointer = newPointer;
368 // ============================================================================
369 // wxSortDescriptorObject
370 // ============================================================================
372 @implementation wxSortDescriptorObject
385 initWithModelPtr:(wxDataViewModel*)initModelPtr
386 sortingColumnPtr:(wxDataViewColumn*)initColumnPtr
387 ascending:(BOOL)sortAscending
389 self = [super initWithKey:@"dummy" ascending:sortAscending];
392 columnPtr = initColumnPtr;
393 modelPtr = initModelPtr;
398 -(id) copyWithZone:(NSZone*)zone
400 wxSortDescriptorObject* copy;
403 copy = [super copyWithZone:zone];
404 copy->columnPtr = columnPtr;
405 copy->modelPtr = modelPtr;
411 // access to model column's index
413 -(wxDataViewColumn*) columnPtr
418 -(wxDataViewModel*) modelPtr
423 -(void) setColumnPtr:(wxDataViewColumn*)newColumnPtr
425 columnPtr = newColumnPtr;
428 -(void) setModelPtr:(wxDataViewModel*)newModelPtr
430 modelPtr = newModelPtr;
435 // ============================================================================
436 // wxCocoaOutlineDataSource
437 // ============================================================================
438 @implementation wxCocoaOutlineDataSource
441 // constructors / destructor
448 implementation = NULL;
451 currentParentItem = nil;
453 children = [[NSMutableArray alloc] init];
454 items = [[NSMutableSet alloc] init];
461 [currentParentItem release];
470 // methods of informal protocol:
473 outlineView:(NSOutlineView*)outlineView
474 acceptDrop:(id<NSDraggingInfo>)info
475 item:(id)item childIndex:(NSInteger)index
477 NSArray* supportedTypes(
478 [NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]
481 NSPasteboard* pasteboard([info draggingPasteboard]);
483 NSString* bestType([pasteboard availableTypeFromArray:supportedTypes]);
485 if ( bestType == nil )
488 wxDataViewCtrl * const dvc(implementation->GetDataViewCtrl());
490 wxCHECK_MSG( dvc, false,
491 "Pointer to data view control not set correctly." );
492 wxCHECK_MSG( dvc->GetModel(), false,
493 "Pointer to model not set correctly." );
495 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_DROP, dvc->GetId());
496 event.SetEventObject(dvc);
497 event.SetItem(wxDataViewItem([((wxPointerObject*) item) pointer]));
498 event.SetModel(dvc->GetModel());
501 if ( [bestType compare:DataViewPboardType] == NSOrderedSame )
503 NSArray* dataArray((NSArray*)[pasteboard propertyListForType:DataViewPboardType]);
504 NSUInteger indexDraggedItem, noOfDraggedItems([dataArray count]);
506 indexDraggedItem = 0;
507 while (indexDraggedItem < noOfDraggedItems)
509 wxDataObjectComposite* dataObjects(implementation->GetDnDDataObjects((NSData*)[dataArray objectAtIndex:indexDraggedItem]));
511 if (dataObjects && (dataObjects->GetFormatCount() > 0))
513 wxMemoryBuffer buffer;
515 // copy data into data object:
516 event.SetDataObject(dataObjects);
517 event.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
518 // copy data into buffer:
519 dataObjects->GetDataHere(event.GetDataFormat().GetType(),buffer.GetWriteBuf(event.GetDataSize()));
520 buffer.UngetWriteBuf(event.GetDataSize());
521 event.SetDataBuffer(buffer.GetData());
522 // finally, send event:
523 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
525 dragSuccessful = true;
530 dragSuccessful = true;
531 indexDraggedItem = noOfDraggedItems; // stop loop
536 dragSuccessful = false;
537 indexDraggedItem = noOfDraggedItems; // stop loop
545 CFDataRef osxData; // needed to convert internally used UTF-16 representation to a UTF-8 representation
546 wxDataObjectComposite* dataObjects (new wxDataObjectComposite());
547 wxTextDataObject* textDataObject(new wxTextDataObject());
549 osxData = ::CFStringCreateExternalRepresentation(kCFAllocatorDefault,(CFStringRef)[pasteboard stringForType:NSStringPboardType],kCFStringEncodingUTF8,32);
550 if (textDataObject->SetData(::CFDataGetLength(osxData),::CFDataGetBytePtr(osxData)))
551 dataObjects->Add(textDataObject);
553 delete textDataObject;
554 // send event if data could be copied:
555 if (dataObjects->GetFormatCount() > 0)
557 event.SetDataObject(dataObjects);
558 event.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
559 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
560 dragSuccessful = true;
562 dragSuccessful = false;
565 dragSuccessful = false;
567 ::CFRelease(osxData);
572 -(id) outlineView:(NSOutlineView*)outlineView child:(NSInteger)index ofItem:(id)item
574 if ((item == currentParentItem) && (index < ((NSInteger) [self getChildCount])))
575 return [self getChild:index];
578 wxDataViewItemArray dataViewChildren;
580 wxCHECK_MSG( model, 0, "Valid model in data source does not exist." );
581 (void) model->GetChildren((item == nil) ? wxDataViewItem() : wxDataViewItem([((wxPointerObject*) item) pointer]),dataViewChildren);
582 [self bufferItem:item withChildren:&dataViewChildren];
583 if ([sortDescriptors count] > 0)
584 [children sortUsingFunction:CompareItems context:sortDescriptors];
585 return [self getChild:index];
589 -(BOOL) outlineView:(NSOutlineView*)outlineView isItemExpandable:(id)item
591 wxCHECK_MSG( model, 0, "Valid model in data source does not exist." );
592 return model->IsContainer(wxDataViewItem([((wxPointerObject*) item) pointer]));
595 -(NSInteger) outlineView:(NSOutlineView*)outlineView numberOfChildrenOfItem:(id)item
597 NSInteger noOfChildren;
599 wxDataViewItemArray dataViewChildren;
602 wxCHECK_MSG( model, 0, "Valid model in data source does not exist." );
603 noOfChildren = model->GetChildren((item == nil) ? wxDataViewItem() : wxDataViewItem([((wxPointerObject*) item) pointer]),dataViewChildren);
604 [self bufferItem:item withChildren:&dataViewChildren];
605 if ([sortDescriptors count] > 0)
606 [children sortUsingFunction:CompareItems context:sortDescriptors];
611 outlineView:(NSOutlineView*)outlineView
612 objectValueForTableColumn:(NSTableColumn*)tableColumn
615 wxCHECK_MSG( model, nil, "Valid model in data source does not exist." );
617 wxDataViewColumn* col(static_cast<wxDataViewColumn*>([[tableColumn identifier] pointer]));
618 const unsigned colIdx = col->GetModelColumn();
620 wxDataViewItem dataViewItem([((wxPointerObject*) item) pointer]);
622 if ( model->HasValue(dataViewItem, colIdx) )
625 model->GetValue(value,dataViewItem, colIdx);
626 col->GetRenderer()->SetValue(value);
633 outlineView:(NSOutlineView*)outlineView
634 setObjectValue:(id)object
635 forTableColumn:(NSTableColumn*)tableColumn
638 wxDataViewColumn* col(static_cast<wxDataViewColumn*>([[tableColumn identifier] pointer]));
640 wxDataViewItem dataViewItem([((wxPointerObject*) item) pointer]);
643 OSXOnCellChanged(object, dataViewItem, col->GetModelColumn());
646 -(void) outlineView:(NSOutlineView*)outlineView sortDescriptorsDidChange:(NSArray*)oldDescriptors
647 // Warning: the new sort descriptors are guaranteed to be only of type NSSortDescriptor! Therefore, the
648 // sort descriptors for the data source have to be converted.
650 NSArray* newDescriptors;
652 NSMutableArray* wxSortDescriptors;
654 NSUInteger noOfDescriptors;
656 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
659 // convert NSSortDescriptors to wxSortDescriptorObjects:
660 newDescriptors = [outlineView sortDescriptors];
661 noOfDescriptors = [newDescriptors count];
662 wxSortDescriptors = [NSMutableArray arrayWithCapacity:noOfDescriptors];
663 for (NSUInteger i=0; i<noOfDescriptors; ++i)
665 // constant definition for abbreviational purposes:
666 NSSortDescriptor* const newDescriptor = [newDescriptors objectAtIndex:i];
668 [wxSortDescriptors addObject:[[[wxSortDescriptorObject alloc] initWithModelPtr:model
669 sortingColumnPtr:dvc->GetColumn([[newDescriptor key] intValue])
670 ascending:[newDescriptor ascending]] autorelease]];
672 [[outlineView dataSource] setSortDescriptors:wxSortDescriptors];
674 // send first the event to wxWidgets that the sorting has changed so that the program can do special actions before
675 // the sorting actually starts:
676 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_COLUMN_SORTED,dvc->GetId()); // variable defintion
678 event.SetEventObject(dvc);
679 if (noOfDescriptors > 0)
681 // constant definition for abbreviational purposes:
682 wxDataViewColumn* const col = [[wxSortDescriptors objectAtIndex:0] columnPtr];
684 event.SetColumn(dvc->GetColumnPosition(col));
685 event.SetDataViewColumn(col);
687 dvc->GetEventHandler()->ProcessEvent(event);
689 // start re-ordering the data;
690 // children's buffer must be cleared first because it contains the old order:
691 [self clearChildren];
692 // sorting is done while reloading the data:
693 [outlineView reloadData];
696 -(NSDragOperation) outlineView:(NSOutlineView*)outlineView validateDrop:(id<NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
698 NSArray* supportedTypes([NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]);
700 NSPasteboard* pasteboard([info draggingPasteboard]);
702 NSString* bestType([pasteboard availableTypeFromArray:supportedTypes]);
704 return NSDragOperationNone;
706 NSDragOperation dragOperation;
707 wxDataViewCtrl* const dvc(implementation->GetDataViewCtrl());
709 wxCHECK_MSG(dvc, false, "Pointer to data view control not set correctly.");
710 wxCHECK_MSG(dvc->GetModel(), false, "Pointer to model not set correctly.");
713 event(wxEVT_COMMAND_DATAVIEW_ITEM_DROP_POSSIBLE,dvc->GetId());
715 event.SetEventObject(dvc);
716 event.SetItem(wxDataViewItem([((wxPointerObject*) item) pointer]));
717 event.SetModel(dvc->GetModel());
718 if ([bestType compare:DataViewPboardType] == NSOrderedSame)
720 NSArray* dataArray((NSArray*)[pasteboard propertyListForType:DataViewPboardType]);
721 NSUInteger indexDraggedItem, noOfDraggedItems([dataArray count]);
723 indexDraggedItem = 0;
724 while (indexDraggedItem < noOfDraggedItems)
726 wxDataObjectComposite* dataObjects(implementation->GetDnDDataObjects((NSData*)[dataArray objectAtIndex:indexDraggedItem]));
728 if (dataObjects && (dataObjects->GetFormatCount() > 0))
730 wxMemoryBuffer buffer;
732 // copy data into data object:
733 event.SetDataObject(dataObjects);
734 event.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
735 // copy data into buffer:
736 dataObjects->GetDataHere(event.GetDataFormat().GetType(),buffer.GetWriteBuf(event.GetDataSize()));
737 buffer.UngetWriteBuf(event.GetDataSize());
738 event.SetDataBuffer(buffer.GetData());
739 // finally, send event:
740 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
742 dragOperation = NSDragOperationEvery;
747 dragOperation = NSDragOperationNone;
748 indexDraggedItem = noOfDraggedItems; // stop loop
753 dragOperation = NSDragOperationNone;
754 indexDraggedItem = noOfDraggedItems; // stop loop
762 CFDataRef osxData; // needed to convert internally used UTF-16 representation to a UTF-8 representation
763 wxDataObjectComposite* dataObjects (new wxDataObjectComposite());
764 wxTextDataObject* textDataObject(new wxTextDataObject());
766 osxData = ::CFStringCreateExternalRepresentation(kCFAllocatorDefault,(CFStringRef)[pasteboard stringForType:NSStringPboardType],kCFStringEncodingUTF8,32);
767 if (textDataObject->SetData(::CFDataGetLength(osxData),::CFDataGetBytePtr(osxData)))
768 dataObjects->Add(textDataObject);
770 delete textDataObject;
771 // send event if data could be copied:
772 if (dataObjects->GetFormatCount() > 0)
774 event.SetDataObject(dataObjects);
775 event.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
776 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
777 dragOperation = NSDragOperationEvery;
779 dragOperation = NSDragOperationNone;
782 dragOperation = NSDragOperationNone;
784 ::CFRelease(osxData);
788 return dragOperation;
791 -(BOOL) outlineView:(NSOutlineView*)outlineView writeItems:(NSArray*)writeItems toPasteboard:(NSPasteboard*)pasteboard
792 // the pasteboard will be filled up with an array containing the data as returned by the events (including the data type)
793 // and a concatenation of text (string) data; the text data will only be put onto the pasteboard if for all items a
794 // string representation exists
796 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
798 wxDataViewItemArray dataViewItems;
801 wxCHECK_MSG(dvc, false,"Pointer to data view control not set correctly.");
802 wxCHECK_MSG(dvc->GetModel(),false,"Pointer to model not set correctly.");
804 if ([writeItems count] > 0)
806 bool dataStringAvailable(true); // a flag indicating if for all items a data string is available
807 NSMutableArray* dataArray = [[NSMutableArray arrayWithCapacity:[writeItems count]] retain]; // data of all items
808 wxString dataString; // contains the string data of all items
810 // send a begin drag event for all selected items and proceed with dragging unless the event is vetoed:
812 event(wxEVT_COMMAND_DATAVIEW_ITEM_BEGIN_DRAG,dvc->GetId());
814 event.SetEventObject(dvc);
815 event.SetModel(dvc->GetModel());
816 for (size_t itemCounter=0; itemCounter<[writeItems count]; ++itemCounter)
818 bool itemStringAvailable(false); // a flag indicating if for the current item a string is available
819 wxDataObjectComposite* itemObject(new wxDataObjectComposite()); // data object for current item
820 wxString itemString; // contains the TAB concatenated data of an item
822 event.SetItem(wxDataViewItem([((wxPointerObject*) [writeItems objectAtIndex:itemCounter]) pointer]));
823 itemString = ::ConcatenateDataViewItemValues(dvc,event.GetItem());
824 itemObject->Add(new wxTextDataObject(itemString));
825 event.SetDataObject(itemObject);
826 // check if event has not been vetoed:
827 if (dvc->HandleWindowEvent(event) && event.IsAllowed() && (event.GetDataObject()->GetFormatCount() > 0))
829 // constant definition for abbreviational purposes:
830 size_t const noOfFormats = event.GetDataObject()->GetFormatCount();
831 // variable definition and initialization:
832 wxDataFormat* dataFormats(new wxDataFormat[noOfFormats]);
834 event.GetDataObject()->GetAllFormats(dataFormats,wxDataObject::Get);
835 for (size_t formatCounter=0; formatCounter<noOfFormats; ++formatCounter)
837 // constant definitions for abbreviational purposes:
838 wxDataFormatId const idDataFormat = dataFormats[formatCounter].GetType();
839 size_t const dataSize = event.GetDataObject()->GetDataSize(idDataFormat);
840 size_t const dataBufferSize = sizeof(wxDataFormatId)+dataSize;
841 // variable definitions (used in all case statements):
842 wxMemoryBuffer dataBuffer(dataBufferSize);
844 dataBuffer.AppendData(&idDataFormat,sizeof(wxDataFormatId));
845 switch (idDataFormat)
848 if (!itemStringAvailable) // otherwise wxDF_UNICODETEXT already filled up the string; and the UNICODE representation has priority
850 event.GetDataObject()->GetDataHere(wxDF_TEXT,dataBuffer.GetAppendBuf(dataSize));
851 dataBuffer.UngetAppendBuf(dataSize);
852 [dataArray addObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
853 itemString = wxString(static_cast<char const*>(dataBuffer.GetData())+sizeof(wxDataFormatId),wxConvLocal);
854 itemStringAvailable = true;
857 case wxDF_UNICODETEXT:
859 event.GetDataObject()->GetDataHere(wxDF_UNICODETEXT,dataBuffer.GetAppendBuf(dataSize));
860 dataBuffer.UngetAppendBuf(dataSize);
861 if (itemStringAvailable) // does an object already exist as an ASCII text (see wxDF_TEXT case statement)?
862 [dataArray replaceObjectAtIndex:itemCounter withObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
864 [dataArray addObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
865 itemString = wxString::FromUTF8(static_cast<char const*>(dataBuffer.GetData())+sizeof(wxDataFormatId),dataSize);
866 itemStringAvailable = true;
870 wxFAIL_MSG("Data object has invalid or unsupported data format");
875 delete[] dataFormats;
877 if (dataStringAvailable)
878 if (itemStringAvailable)
881 dataString << wxT('\n');
882 dataString << itemString;
885 dataStringAvailable = false;
891 return NO; // dragging was vetoed or no data available
894 if (dataStringAvailable)
896 wxCFStringRef osxString(dataString);
898 [pasteboard declareTypes:[NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil] owner:nil];
899 [pasteboard setPropertyList:dataArray forType:DataViewPboardType];
900 [pasteboard setString:osxString.AsNSString() forType:NSStringPboardType];
904 [pasteboard declareTypes:[NSArray arrayWithObject:DataViewPboardType] owner:nil];
905 [pasteboard setPropertyList:dataArray forType:DataViewPboardType];
910 return NO; // no items to drag (should never occur)
916 -(void) addToBuffer:(wxPointerObject*)item
918 [items addObject:item];
923 [items removeAllObjects];
926 -(wxPointerObject*) getDataViewItemFromBuffer:(const wxDataViewItem&)item
928 return [items member:[[[wxPointerObject alloc] initWithPointer:item.GetID()] autorelease]];
931 -(wxPointerObject*) getItemFromBuffer:(wxPointerObject*)item
933 return [items member:item];
936 -(BOOL) isInBuffer:(wxPointerObject*)item
938 return [items containsObject:item];
941 -(void) removeFromBuffer:(wxPointerObject*)item
943 [items removeObject:item];
949 -(void) appendChild:(wxPointerObject*)item
951 [children addObject:item];
954 -(void) clearChildren
956 [children removeAllObjects];
959 -(wxPointerObject*) getChild:(NSUInteger)index
961 return [children objectAtIndex:index];
964 -(NSUInteger) getChildCount
966 return [children count];
969 -(void) removeChild:(NSUInteger)index
971 [children removeObjectAtIndex:index];
980 [self clearChildren];
981 [self setCurrentParentItem:nil];
987 -(NSArray*) sortDescriptors
989 return sortDescriptors;
992 -(void) setSortDescriptors:(NSArray*)newSortDescriptors
994 [newSortDescriptors retain];
995 [sortDescriptors release];
996 sortDescriptors = newSortDescriptors;
1000 // access to wxWidget's implementation
1002 -(wxPointerObject*) currentParentItem
1004 return currentParentItem;
1007 -(wxCocoaDataViewControl*) implementation
1009 return implementation;
1012 -(wxDataViewModel*) model
1017 -(void) setCurrentParentItem:(wxPointerObject*)newCurrentParentItem
1019 [newCurrentParentItem retain];
1020 [currentParentItem release];
1021 currentParentItem = newCurrentParentItem;
1024 -(void) setImplementation:(wxCocoaDataViewControl*) newImplementation
1026 implementation = newImplementation;
1029 -(void) setModel:(wxDataViewModel*) newModel
1037 -(void) bufferItem:(wxPointerObject*)parentItem withChildren:(wxDataViewItemArray*)dataViewChildrenPtr
1039 NSInteger const noOfChildren = (*dataViewChildrenPtr).GetCount();
1041 [self setCurrentParentItem:parentItem];
1042 [self clearChildren];
1043 for (NSInteger indexChild=0; indexChild<noOfChildren; ++indexChild)
1045 wxPointerObject* bufferedPointerObject;
1046 wxPointerObject* newPointerObject([[wxPointerObject alloc] initWithPointer:(*dataViewChildrenPtr)[indexChild].GetID()]);
1048 // The next statement and test looks strange but there is
1049 // unfortunately no workaround: due to the fact that two pointer
1050 // objects are identical if their pointers are identical - because the
1051 // method isEqual has been overloaded - the set operation will only
1052 // add a new pointer object if there is not already one in the set
1053 // having the same pointer. On the other side the children's array
1054 // would always add the new pointer object. This means that different
1055 // pointer objects are stored in the set and array. This will finally
1056 // lead to a crash as objects diverge. To solve this issue it is first
1057 // tested if the child already exists in the set and if it is the case
1058 // the sets object is going to be appended to the array, otheriwse the
1059 // new pointer object is added to the set and array:
1060 bufferedPointerObject = [self getItemFromBuffer:newPointerObject];
1061 if (bufferedPointerObject == nil)
1063 [items addObject:newPointerObject];
1064 [children addObject:newPointerObject];
1067 [children addObject:bufferedPointerObject];
1068 [newPointerObject release];
1074 // ============================================================================
1076 // ============================================================================
1078 @implementation wxCustomCell
1082 wxCustomRendererObject * const
1083 obj = static_cast<wxCustomRendererObject *>([self objectValue]);
1086 const wxSize size = obj->customRenderer->GetSize();
1087 return NSMakeSize(size.x, size.y);
1093 -(void) drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
1095 wxCustomRendererObject * const
1096 obj = static_cast<wxCustomRendererObject *>([self objectValue]);
1099 // this may happen for the custom cells in container rows: they don't
1104 wxDataViewCustomRenderer * const renderer = obj->customRenderer;
1106 // draw its own background:
1107 [[self backgroundColor] set];
1108 NSRectFill(cellFrame);
1110 // TODO: attributes support
1111 renderer->Render(wxFromNSRect(controlView, cellFrame), renderer->GetDC(), 0);
1112 renderer->SetDC(NULL);
1115 -(NSRect) imageRectForBounds:(NSRect)cellFrame
1120 -(NSRect) titleRectForBounds:(NSRect)cellFrame
1127 // ============================================================================
1129 // ============================================================================
1130 @implementation wxImageTextCell
1136 self = [super init];
1139 // initializing the text part:
1140 [self setSelectable:YES];
1141 // initializing the image part:
1143 imageSize = NSMakeSize(16,16);
1144 spaceImageText = 5.0;
1150 -(id) copyWithZone:(NSZone*)zone
1152 wxImageTextCell* cell;
1155 cell = (wxImageTextCell*) [super copyWithZone:zone];
1156 cell->image = [image retain];
1157 cell->imageSize = imageSize;
1158 cell->spaceImageText = spaceImageText;
1159 cell->xImageShift = xImageShift;
1174 -(NSTextAlignment) alignment
1176 return cellAlignment;
1179 -(void) setAlignment:(NSTextAlignment)newAlignment
1181 cellAlignment = newAlignment;
1182 switch (newAlignment)
1184 case NSCenterTextAlignment:
1185 case NSLeftTextAlignment:
1186 case NSJustifiedTextAlignment:
1187 case NSNaturalTextAlignment:
1188 [super setAlignment:NSLeftTextAlignment];
1190 case NSRightTextAlignment:
1191 [super setAlignment:NSRightTextAlignment];
1194 wxFAIL_MSG("Unknown alignment type.");
1206 -(void) setImage:(NSImage*)newImage
1218 -(void) setImageSize:(NSSize) newImageSize
1220 imageSize = newImageSize;
1226 -(NSSize) cellImageSize
1228 return NSMakeSize(imageSize.width+xImageShift+spaceImageText,imageSize.height);
1233 NSSize cellSize([super cellSize]);
1236 if (imageSize.height > cellSize.height)
1237 cellSize.height = imageSize.height;
1238 cellSize.width += imageSize.width+xImageShift+spaceImageText;
1243 -(NSSize) cellTextSize
1245 return [super cellSize];
1251 -(void) determineCellParts:(NSRect)cellFrame imagePart:(NSRect*)imageFrame textPart:(NSRect*)textFrame
1253 switch (cellAlignment)
1255 case NSCenterTextAlignment:
1257 CGFloat const cellSpace = cellFrame.size.width-[self cellSize].width;
1259 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:
1260 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1261 else // otherwise center the image and text in the cell's frame
1262 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText+0.5*cellSpace,NSMinXEdge);
1265 case NSJustifiedTextAlignment:
1266 case NSLeftTextAlignment:
1267 case NSNaturalTextAlignment: // how to determine the natural writing direction? TODO
1268 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1270 case NSRightTextAlignment:
1272 CGFloat const cellSpace = cellFrame.size.width-[self cellSize].width;
1274 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:
1275 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1276 else // otherwise right align the image and text in the cell's frame
1277 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText+cellSpace,NSMinXEdge);
1281 *imageFrame = NSZeroRect;
1282 *textFrame = NSZeroRect;
1283 wxFAIL_MSG("Unhandled alignment type.");
1287 -(void) drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
1289 NSRect textFrame, imageFrame;
1292 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1293 // draw the image part by ourselves;
1294 // check if the cell has to draw its own background (checking is done by the parameter of the textfield's cell):
1295 if ([self drawsBackground])
1297 [[self backgroundColor] set];
1298 NSRectFill(imageFrame);
1302 // the image is slightly shifted (xImageShift) and has a fixed size but the image's frame might be larger and starts
1303 // currently on the left side of the cell's frame; therefore, the origin and the image's frame size have to be adjusted:
1304 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1306 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1307 imageFrame.size.width = imageSize.width;
1311 imageFrame.origin.x += xImageShift;
1312 imageFrame.size.width -= xImageShift+spaceImageText;
1314 // ...and the image has to be centered in the y-direction:
1315 if (imageFrame.size.height > imageSize.height)
1316 imageFrame.size.height = imageSize.height;
1317 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1319 // according to the documentation the coordinate system should be flipped for NSTableViews (y-coordinate goes from top to bottom);
1320 // to draw an image correctly the coordinate system has to be transformed to a bottom-top coordinate system, otherwise the image's
1321 // content is flipped:
1322 NSAffineTransform* coordinateTransform([NSAffineTransform transform]);
1324 if ([controlView isFlipped])
1326 [coordinateTransform scaleXBy: 1.0 yBy:-1.0]; // first the coordinate system is brought back to bottom-top orientation
1327 [coordinateTransform translateXBy:0.0 yBy:(-2.0)*imageFrame.origin.y-imageFrame.size.height]; // the coordinate system has to be moved to compensate for the
1328 [coordinateTransform concat]; // other orientation and the position of the image's frame
1330 [image drawInRect:imageFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0]; // suggested method to draw the image
1331 // instead of compositeToPoint:operation:
1332 // take back previous transformation (if the view is not flipped the coordinate transformation matrix contains the identity matrix
1333 // and the next two operations do not change the content's transformation matrix):
1334 [coordinateTransform invert];
1335 [coordinateTransform concat];
1337 // let the textfield cell draw the text part:
1338 if (textFrame.size.width > [self cellTextSize].width) // for unknown reasons the alignment of the text cell is ignored; therefore change the size so that
1339 textFrame.size.width = [self cellTextSize].width; // alignment does not influence the visualization anymore
1340 [super drawWithFrame:textFrame inView:controlView];
1343 -(void) editWithFrame:(NSRect)aRect inView:(NSView*)controlView editor:(NSText*)textObj delegate:(id)anObject event:(NSEvent*)theEvent
1345 NSRect textFrame, imageFrame;
1348 [self determineCellParts:aRect imagePart:&imageFrame textPart:&textFrame];
1349 [super editWithFrame:textFrame inView:controlView editor:textObj delegate:anObject event:theEvent];
1352 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1353 -(NSUInteger) hitTestForEvent:(NSEvent*)event inRect:(NSRect)cellFrame ofView:(NSView*)controlView
1355 NSPoint point = [controlView convertPoint:[event locationInWindow] fromView:nil];
1357 NSRect imageFrame, textFrame;
1360 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1363 // the image is shifted...
1364 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1366 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1367 imageFrame.size.width = imageSize.width;
1371 imageFrame.origin.x += xImageShift;
1372 imageFrame.size.width -= xImageShift+spaceImageText;
1375 if (imageFrame.size.height > imageSize.height)
1376 imageFrame.size.height = imageSize.height;
1377 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1378 // If the point is in the image rect, then it is a content hit (see documentation for hitTestForEvent:inRect:ofView):
1379 if (NSMouseInRect(point, imageFrame, [controlView isFlipped]))
1380 return NSCellHitContentArea;
1382 // if the image was not hit let's try the text part:
1383 if (textFrame.size.width > [self cellTextSize].width) // for unknown reasons the alignment of the text cell is ignored; therefore change the size so that
1384 textFrame.size.width = [self cellTextSize].width; // alignment does not influence the visualization anymore
1385 return [super hitTestForEvent:event inRect:textFrame ofView:controlView];
1389 -(NSRect) imageRectForBounds:(NSRect)cellFrame
1391 NSRect textFrame, imageFrame;
1394 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1395 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1397 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1398 imageFrame.size.width = imageSize.width;
1402 imageFrame.origin.x += xImageShift;
1403 imageFrame.size.width -= xImageShift+spaceImageText;
1406 if (imageFrame.size.height > imageSize.height)
1407 imageFrame.size.height = imageSize.height;
1408 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1413 -(void) selectWithFrame:(NSRect)aRect inView:(NSView*)controlView editor:(NSText*)textObj delegate:(id)anObject start:(NSInteger)selStart length:(NSInteger)selLength
1415 NSRect textFrame, imageFrame;
1418 [self determineCellParts:aRect imagePart:&imageFrame textPart:&textFrame];
1419 [super selectWithFrame:textFrame inView:controlView editor:textObj delegate:anObject start:selStart length:selLength];
1422 -(NSRect) titleRectForBounds:(NSRect)cellFrame
1424 NSRect textFrame, imageFrame;
1427 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1433 // ============================================================================
1434 // wxCocoaOutlineView
1435 // ============================================================================
1436 @implementation wxCocoaOutlineView
1439 // initializers / destructor
1443 self = [super init];
1446 currentlyEditedColumn =
1447 currentlyEditedRow = -1;
1449 [self registerForDraggedTypes:[NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]];
1450 [self setDelegate:self];
1451 [self setDoubleAction:@selector(actionDoubleClick:)];
1452 [self setDraggingSourceOperationMask:NSDragOperationEvery forLocal:NO];
1453 [self setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
1454 [self setTarget:self];
1460 // access to wxWidget's implementation
1462 -(wxCocoaDataViewControl*) implementation
1464 return implementation;
1467 -(void) setImplementation:(wxCocoaDataViewControl*) newImplementation
1469 implementation = newImplementation;
1475 -(void) actionDoubleClick:(id)sender
1476 // actually the documentation (NSTableView 2007-10-31) for doubleAction: and setDoubleAction: seems to be wrong as this action message is always sent
1477 // whether the cell is editable or not
1479 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1481 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_ACTIVATED,dvc->GetId()); // variable definition
1484 event.SetEventObject(dvc);
1485 event.SetItem(wxDataViewItem([((wxPointerObject*) [self itemAtRow:[self clickedRow]]) pointer]));
1486 dvc->GetEventHandler()->ProcessEvent(event);
1493 -(NSMenu*) menuForEvent:(NSEvent*)theEvent
1494 // this method does not do any special menu event handling but only sends an event message; therefore, the user
1495 // has full control if a context menu should be shown or not
1497 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1499 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_CONTEXT_MENU,dvc->GetId());
1501 wxDataViewItemArray selectedItems;
1504 event.SetEventObject(dvc);
1505 event.SetModel(dvc->GetModel());
1506 // get the item information;
1507 // theoretically more than one ID can be returned but the event can only handle one item, therefore only the first
1508 // item of the array is returned:
1509 if (dvc->GetSelections(selectedItems) > 0)
1510 event.SetItem(selectedItems[0]);
1511 dvc->GetEventHandler()->ProcessEvent(event);
1519 -(void) outlineView:(NSOutlineView*)outlineView mouseDownInHeaderOfTableColumn:(NSTableColumn*)tableColumn
1521 wxDataViewColumn* const col(static_cast<wxDataViewColumn*>([[tableColumn identifier] pointer]));
1523 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1526 event(wxEVT_COMMAND_DATAVIEW_COLUMN_HEADER_CLICK,dvc->GetId());
1529 // first, send an event that the user clicked into a column's header:
1530 event.SetEventObject(dvc);
1531 event.SetColumn(dvc->GetColumnPosition(col));
1532 event.SetDataViewColumn(col);
1533 dvc->HandleWindowEvent(event);
1535 // now, check if the click may have had an influence on sorting, too;
1536 // the sorting setup has to be done only if the clicked table column is sortable and has not been used for
1537 // sorting before the click; if the column is already responsible for sorting the native control changes
1538 // the sorting direction automatically and informs the data source via outlineView:sortDescriptorsDidChange:
1539 if (col->IsSortable() && ([tableColumn sortDescriptorPrototype] == nil))
1541 // remove the sort order from the previously sorted column table (it can also be that
1542 // no sorted column table exists):
1543 UInt32 const noOfColumns = [outlineView numberOfColumns];
1545 for (UInt32 i=0; i<noOfColumns; ++i)
1546 [[[outlineView tableColumns] objectAtIndex:i] setSortDescriptorPrototype:nil];
1547 // make column table sortable:
1548 NSArray* sortDescriptors;
1549 NSSortDescriptor* sortDescriptor;
1551 sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[NSString stringWithFormat:@"%d",[outlineView columnWithIdentifier:[tableColumn identifier]]]
1553 sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
1554 [tableColumn setSortDescriptorPrototype:sortDescriptor];
1555 [outlineView setSortDescriptors:sortDescriptors];
1556 [sortDescriptor release];
1560 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldCollapseItem:(id)item
1562 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1564 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSING,dvc->GetId()); // variable definition
1567 event.SetEventObject(dvc);
1568 event.SetItem (wxDataViewItem([((wxPointerObject*) item) pointer]));
1569 event.SetModel (dvc->GetModel());
1570 // finally send the equivalent wxWidget event:
1571 dvc->GetEventHandler()->ProcessEvent(event);
1572 // opening the container is allowed if not vetoed:
1573 return event.IsAllowed();
1576 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldExpandItem:(id)item
1578 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1580 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDING,dvc->GetId()); // variable definition
1583 event.SetEventObject(dvc);
1584 event.SetItem (wxDataViewItem([((wxPointerObject*) item) pointer]));
1585 event.SetModel (dvc->GetModel());
1586 // finally send the equivalent wxWidget event:
1587 dvc->GetEventHandler()->ProcessEvent(event);
1588 // opening the container is allowed if not vetoed:
1589 return event.IsAllowed();
1592 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldSelectTableColumn:(NSTableColumn*)tableColumn
1597 -(void) outlineView:(wxCocoaOutlineView*)outlineView
1598 willDisplayCell:(id)cell
1599 forTableColumn:(NSTableColumn*)tableColumn
1602 wxDataViewCtrl * const dvc = implementation->GetDataViewCtrl();
1603 wxDataViewModel * const model = dvc->GetModel();
1605 wxDataViewColumn * const
1606 dvCol(static_cast<wxDataViewColumn*>(
1607 [[tableColumn identifier] pointer]
1610 const unsigned colIdx = dvCol->GetModelColumn();
1612 wxDataViewItem dvItem([static_cast<wxPointerObject *>(item) pointer]);
1614 if ( !model->HasValue(dvItem, colIdx) )
1617 wxDataViewRenderer * const renderer = dvCol->GetRenderer();
1618 wxDataViewRendererNativeData * const data = renderer->GetNativeData();
1620 // set the font and text colour to use: we need to do it if we had ever
1621 // changed them before, even if this item itself doesn't have any special
1622 // attributes as otherwise it would reuse the attributes from the previous
1623 // cell rendered using the same renderer
1624 NSFont *font = NULL;
1625 NSColor *colText = NULL;
1627 wxDataViewItemAttr attr;
1628 if ( model && model->GetAttr(dvItem, colIdx, attr) )
1630 if ( attr.HasFont() )
1632 font = data->GetOriginalFont();
1635 // this is the first time we're setting the font, remember the
1636 // original one before changing it
1638 data->SaveOriginalFont(font);
1643 // FIXME: using wxFont methods here doesn't work for some reason
1644 NSFontManager * const fm = [NSFontManager sharedFontManager];
1645 if ( attr.GetBold() )
1646 font = [fm convertFont:font toHaveTrait:NSBoldFontMask];
1647 if ( attr.GetItalic() )
1648 font = [fm convertFont:font toHaveTrait:NSItalicFontMask];
1650 //else: can't change font if the cell doesn't have any
1653 if ( attr.HasColour() )
1655 // we can set font for any cell but only NSTextFieldCell provides
1656 // a method for setting text colour so check that this method is
1657 // available before using it
1658 if ( [cell respondsToSelector:@selector(setTextColor:)] &&
1659 [cell respondsToSelector:@selector(textColor)] )
1661 if ( !data->GetOriginalTextColour() )
1663 data->SaveOriginalTextColour([cell textColor]);
1666 const wxColour& c = attr.GetColour();
1667 colText = [NSColor colorWithDeviceRed:c.Red() / 255.
1668 green:c.Green() / 255.
1669 blue:c.Blue() / 255.
1670 alpha:c.Alpha() / 255.];
1676 font = data->GetOriginalFont();
1678 colText = data->GetOriginalTextColour();
1681 [cell setFont:font];
1684 [cell setTextColor:colText];
1687 data->SetColumnPtr(tableColumn);
1688 data->SetItem(item);
1689 data->SetItemCell(cell);
1691 renderer->MacRender();
1697 -(void) outlineViewColumnDidMove:(NSNotification*)notification
1699 int const newColumnPosition = [[[notification userInfo] objectForKey:@"NSNewColumn"] intValue];
1701 wxDataViewColumn* const col(static_cast<wxDataViewColumn*>([[[[self tableColumns] objectAtIndex:newColumnPosition] identifier] pointer]));
1703 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1705 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_COLUMN_REORDERED,dvc->GetId());
1708 event.SetEventObject(dvc);
1709 event.SetColumn(dvc->GetColumnPosition(col));
1710 event.SetDataViewColumn(col);
1711 dvc->GetEventHandler()->ProcessEvent(event);
1714 -(void) outlineViewItemDidCollapse:(NSNotification*)notification
1716 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1718 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSED,dvc->GetId());
1721 event.SetEventObject(dvc);
1722 event.SetItem(wxDataViewItem([((wxPointerObject*) [[notification userInfo] objectForKey:@"NSObject"]) pointer]));
1723 dvc->GetEventHandler()->ProcessEvent(event);
1726 -(void) outlineViewItemDidExpand:(NSNotification*)notification
1728 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1730 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDED,dvc->GetId());
1733 event.SetEventObject(dvc);
1734 event.SetItem(wxDataViewItem([((wxPointerObject*) [[notification userInfo] objectForKey:@"NSObject"]) pointer]));
1735 dvc->GetEventHandler()->ProcessEvent(event);
1738 -(void) outlineViewSelectionDidChange:(NSNotification*)notification
1740 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1742 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_SELECTION_CHANGED,dvc->GetId()); // variable definition
1745 event.SetEventObject(dvc);
1746 event.SetModel (dvc->GetModel());
1747 dvc->GetEventHandler()->ProcessEvent(event);
1750 -(void) textDidBeginEditing:(NSNotification*)notification
1751 // this notification is only sent if the user started modifying the cell (not when the user clicked into the cell
1752 // and the cell's editor is called!)
1754 // call method of superclass (otherwise editing does not work correctly - the outline data source class is not
1755 // informed about a change of data):
1756 [super textDidBeginEditing:notification];
1758 // remember the column being edited, it will be used in textDidEndEditing:
1759 currentlyEditedColumn = [self editedColumn];
1760 currentlyEditedRow = [self editedRow];
1762 wxDataViewColumn* const col =
1763 static_cast<wxDataViewColumn*>(
1764 [[[[self tableColumns] objectAtIndex:currentlyEditedColumn] identifier] pointer]);
1766 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1769 // stop editing of a custom item first (if necessary)
1770 dvc->FinishCustomItemEditing();
1772 // now, send the event:
1774 event(wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED,dvc->GetId()); // variable definition
1776 event.SetEventObject(dvc);
1778 wxDataViewItem([((wxPointerObject*) [self itemAtRow:currentlyEditedRow]) pointer]));
1779 event.SetColumn(dvc->GetColumnPosition(col));
1780 event.SetDataViewColumn(col);
1781 dvc->GetEventHandler()->ProcessEvent(event);
1784 -(void) textDidEndEditing:(NSNotification*)notification
1786 // call method of superclass (otherwise editing does not work correctly - the outline data source class is not
1787 // informed about a change of data):
1788 [super textDidEndEditing:notification];
1790 // under OSX an event indicating the end of an editing session can be sent even if no event indicating a start of an
1791 // editing session has been sent (see Documentation for NSControl controlTextDidEndEditing:); this is not expected by a user
1792 // of the wxWidgets library and therefore an wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_DONE event is only sent if a corresponding
1793 // wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED has been sent before; to check if a wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED
1794 // has been sent the last edited column/row are valid:
1795 if ( currentlyEditedColumn != -1 && currentlyEditedRow != -1 )
1797 wxDataViewColumn* const col =
1798 static_cast<wxDataViewColumn*>(
1799 [[[[self tableColumns] objectAtIndex:currentlyEditedColumn] identifier] pointer]);
1801 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1803 // send event to wxWidgets:
1805 event(wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_DONE,dvc->GetId()); // variable definition
1807 event.SetEventObject(dvc);
1809 wxDataViewItem([((wxPointerObject*) [self itemAtRow:currentlyEditedRow]) pointer]));
1810 event.SetColumn(dvc->GetColumnPosition(col));
1811 event.SetDataViewColumn(col);
1812 dvc->GetEventHandler()->ProcessEvent(event);
1815 // we're not editing any more
1816 currentlyEditedColumn =
1817 currentlyEditedRow = -1;
1822 // ============================================================================
1823 // wxCocoaDataViewControl
1824 // ============================================================================
1826 // constructors / destructor
1828 wxCocoaDataViewControl::wxCocoaDataViewControl(wxWindow* peer, const wxPoint& pos, const wxSize& size, long style)
1829 :wxWidgetCocoaImpl(peer,[[NSScrollView alloc] initWithFrame:wxOSXGetFrameForControl(peer,pos,size)]),
1830 m_DataSource(NULL), m_OutlineView([[wxCocoaOutlineView alloc] init])
1832 // initialize scrollview (the outline view is part of a scrollview):
1833 NSScrollView* scrollview = (NSScrollView*) GetWXWidget(); // definition for abbreviational purposes
1836 [scrollview setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1837 [scrollview setBorderType:NSNoBorder];
1838 [scrollview setHasVerticalScroller:YES];
1839 [scrollview setHasHorizontalScroller:YES];
1840 [scrollview setAutohidesScrollers:YES];
1841 [scrollview setDocumentView:m_OutlineView];
1843 // setting up the native control itself
1844 NSUInteger maskGridStyle(NSTableViewGridNone);
1846 [m_OutlineView setImplementation:this];
1847 [m_OutlineView setColumnAutoresizingStyle:NSTableViewSequentialColumnAutoresizingStyle];
1848 [m_OutlineView setIndentationPerLevel:GetDataViewCtrl()->GetIndent()];
1849 if (style & wxDV_HORIZ_RULES)
1850 maskGridStyle |= NSTableViewSolidHorizontalGridLineMask;
1851 if (style & wxDV_VERT_RULES)
1852 maskGridStyle |= NSTableViewSolidVerticalGridLineMask;
1853 [m_OutlineView setGridStyleMask:maskGridStyle];
1854 [m_OutlineView setAllowsMultipleSelection: (style & wxDV_MULTIPLE) != 0];
1855 [m_OutlineView setUsesAlternatingRowBackgroundColors:(style & wxDV_ROW_LINES) != 0];
1858 wxCocoaDataViewControl::~wxCocoaDataViewControl()
1860 [m_DataSource release];
1861 [m_OutlineView release];
1865 // column related methods (inherited from wxDataViewWidgetImpl)
1867 bool wxCocoaDataViewControl::ClearColumns()
1869 bool const bufAllowsMultipleSelection = [m_OutlineView allowsMultipleSelection];
1872 // 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;
1873 // therefore, the whole view is deleted and newly constructed:
1874 [m_OutlineView release];
1875 m_OutlineView = [[wxCocoaOutlineView alloc] init];
1876 [((NSScrollView*) GetWXWidget()) setDocumentView:m_OutlineView];
1878 // setting up the native control itself
1879 [m_OutlineView setImplementation:this];
1880 [m_OutlineView setColumnAutoresizingStyle:NSTableViewSequentialColumnAutoresizingStyle];
1881 [m_OutlineView setIndentationPerLevel:GetDataViewCtrl()->GetIndent()];
1882 if (bufAllowsMultipleSelection)
1883 [m_OutlineView setAllowsMultipleSelection:YES];
1884 [m_OutlineView setDataSource:m_DataSource];
1889 bool wxCocoaDataViewControl::DeleteColumn(wxDataViewColumn* columnPtr)
1891 if ([m_OutlineView outlineTableColumn] == columnPtr->GetNativeData()->GetNativeColumnPtr())
1892 [m_OutlineView setOutlineTableColumn:nil]; // due to a bug this does not work
1893 [m_OutlineView removeTableColumn:columnPtr->GetNativeData()->GetNativeColumnPtr()]; // due to a confirmed bug #6555162 the deletion does not work for
1894 // outline table columns (... and there is no workaround)
1895 return (([m_OutlineView columnWithIdentifier:[[[wxPointerObject alloc] initWithPointer:columnPtr] autorelease]]) == -1);
1898 void wxCocoaDataViewControl::DoSetExpanderColumn(const wxDataViewColumn *columnPtr)
1900 [m_OutlineView setOutlineTableColumn:columnPtr->GetNativeData()->GetNativeColumnPtr()];
1903 wxDataViewColumn* wxCocoaDataViewControl::GetColumn(unsigned int pos) const
1905 return static_cast<wxDataViewColumn*>([[[[m_OutlineView tableColumns] objectAtIndex:pos] identifier] pointer]);
1908 int wxCocoaDataViewControl::GetColumnPosition(const wxDataViewColumn *columnPtr) const
1910 return [m_OutlineView columnWithIdentifier:[[[wxPointerObject alloc] initWithPointer:const_cast<wxDataViewColumn*>(columnPtr)] autorelease]];
1913 bool wxCocoaDataViewControl::InsertColumn(unsigned int pos, wxDataViewColumn* columnPtr)
1915 // create column and set the native data of the dataview column:
1916 NSTableColumn *nativeColumn = ::CreateNativeColumn(columnPtr);
1917 columnPtr->GetNativeData()->SetNativeColumnPtr(nativeColumn);
1918 // as the native control does not allow the insertion of a column at a specified position the column is first appended and
1919 // - if necessary - moved to its final position:
1920 [m_OutlineView addTableColumn:nativeColumn];
1921 if (pos != static_cast<unsigned int>([m_OutlineView numberOfColumns]-1))
1922 [m_OutlineView moveColumn:[m_OutlineView numberOfColumns]-1 toColumn:pos];
1928 // item related methods (inherited from wxDataViewWidgetImpl)
1930 bool wxCocoaDataViewControl::Add(const wxDataViewItem& parent, const wxDataViewItem& WXUNUSED(item))
1933 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
1935 [m_OutlineView reloadData];
1939 bool wxCocoaDataViewControl::Add(const wxDataViewItem& parent, const wxDataViewItemArray& WXUNUSED(items))
1942 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
1944 [m_OutlineView reloadData];
1948 void wxCocoaDataViewControl::Collapse(const wxDataViewItem& item)
1950 [m_OutlineView collapseItem:[m_DataSource getDataViewItemFromBuffer:item]];
1953 void wxCocoaDataViewControl::EnsureVisible(const wxDataViewItem& item, const wxDataViewColumn *columnPtr)
1957 [m_OutlineView scrollRowToVisible:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
1959 [m_OutlineView scrollColumnToVisible:GetColumnPosition(columnPtr)];
1963 void wxCocoaDataViewControl::Expand(const wxDataViewItem& item)
1965 [m_OutlineView expandItem:[m_DataSource getDataViewItemFromBuffer:item]];
1968 unsigned int wxCocoaDataViewControl::GetCount() const
1970 return [m_OutlineView numberOfRows];
1973 wxRect wxCocoaDataViewControl::GetRectangle(const wxDataViewItem& item, const wxDataViewColumn *columnPtr)
1975 return wxFromNSRect([m_osxView superview],[m_OutlineView frameOfCellAtColumn:GetColumnPosition(columnPtr)
1976 row:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]]);
1979 bool wxCocoaDataViewControl::IsExpanded(const wxDataViewItem& item) const
1981 return [m_OutlineView isItemExpanded:[m_DataSource getDataViewItemFromBuffer:item]];
1984 bool wxCocoaDataViewControl::Reload()
1986 [m_DataSource clearBuffers];
1987 [m_OutlineView scrollColumnToVisible:0];
1988 [m_OutlineView scrollRowToVisible:0];
1989 [m_OutlineView reloadData];
1993 bool wxCocoaDataViewControl::Remove(const wxDataViewItem& parent, const wxDataViewItem& WXUNUSED(item))
1996 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
1998 [m_OutlineView reloadData];
2002 bool wxCocoaDataViewControl::Remove(const wxDataViewItem& parent, const wxDataViewItemArray& WXUNUSED(item))
2005 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2007 [m_OutlineView reloadData];
2011 bool wxCocoaDataViewControl::Update(const wxDataViewColumn *columnPtr)
2016 bool wxCocoaDataViewControl::Update(const wxDataViewItem& WXUNUSED(parent), const wxDataViewItem& item)
2018 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:item]];
2022 bool wxCocoaDataViewControl::Update(const wxDataViewItem& WXUNUSED(parent), const wxDataViewItemArray& items)
2024 for (size_t i=0; i<items.GetCount(); ++i)
2025 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:items[i]]];
2030 // model related methods
2032 bool wxCocoaDataViewControl::AssociateModel(wxDataViewModel* model)
2034 [m_DataSource release];
2037 m_DataSource = [[wxCocoaOutlineDataSource alloc] init];
2038 [m_DataSource setImplementation:this];
2039 [m_DataSource setModel:model];
2042 m_DataSource = NULL;
2043 [m_OutlineView setDataSource:m_DataSource]; // if there is a data source the data is immediately going to be requested
2048 // selection related methods (inherited from wxDataViewWidgetImpl)
2050 int wxCocoaDataViewControl::GetSelections(wxDataViewItemArray& sel) const
2052 NSIndexSet* selectedRowIndexes([m_OutlineView selectedRowIndexes]);
2054 NSUInteger indexRow;
2058 sel.Alloc([selectedRowIndexes count]);
2059 indexRow = [selectedRowIndexes firstIndex];
2060 while (indexRow != NSNotFound)
2062 sel.Add(wxDataViewItem([[m_OutlineView itemAtRow:indexRow] pointer]));
2063 indexRow = [selectedRowIndexes indexGreaterThanIndex:indexRow];
2065 return sel.GetCount();
2068 bool wxCocoaDataViewControl::IsSelected(const wxDataViewItem& item) const
2070 return [m_OutlineView isRowSelected:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2073 void wxCocoaDataViewControl::Select(const wxDataViewItem& item)
2076 [m_OutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]]
2077 byExtendingSelection:NO];
2080 void wxCocoaDataViewControl::SelectAll()
2082 [m_OutlineView selectAll:m_OutlineView];
2085 void wxCocoaDataViewControl::Unselect(const wxDataViewItem& item)
2088 [m_OutlineView deselectRow:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2091 void wxCocoaDataViewControl::UnselectAll()
2093 [m_OutlineView deselectAll:m_OutlineView];
2097 // sorting related methods
2099 wxDataViewColumn* wxCocoaDataViewControl::GetSortingColumn() const
2101 NSArray* const columns = [m_OutlineView tableColumns];
2103 UInt32 const noOfColumns = [columns count];
2106 for (UInt32 i=0; i<noOfColumns; ++i)
2107 if ([[columns objectAtIndex:i] sortDescriptorPrototype] != nil)
2108 return static_cast<wxDataViewColumn*>([[[columns objectAtIndex:i] identifier] pointer]);
2112 void wxCocoaDataViewControl::Resort()
2114 [m_DataSource clearChildren];
2115 [m_OutlineView reloadData];
2119 // other methods (inherited from wxDataViewWidgetImpl)
2121 void wxCocoaDataViewControl::DoSetIndent(int indent)
2123 [m_OutlineView setIndentationPerLevel:static_cast<CGFloat>(indent)];
2126 void wxCocoaDataViewControl::HitTest(const wxPoint& point, wxDataViewItem& item, wxDataViewColumn*& columnPtr) const
2128 NSPoint const nativePoint = wxToNSPoint((NSScrollView*) GetWXWidget(),point);
2134 indexColumn = [m_OutlineView columnAtPoint:nativePoint];
2135 indexRow = [m_OutlineView rowAtPoint: nativePoint];
2136 if ((indexColumn >= 0) && (indexRow >= 0))
2138 columnPtr = static_cast<wxDataViewColumn*>([[[[m_OutlineView tableColumns] objectAtIndex:indexColumn] identifier] pointer]);
2139 item = wxDataViewItem([[m_OutlineView itemAtRow:indexRow] pointer]);
2144 item = wxDataViewItem();
2148 void wxCocoaDataViewControl::SetRowHeight(const wxDataViewItem& WXUNUSED(item), unsigned int WXUNUSED(height))
2149 // Not supported by the native control
2153 void wxCocoaDataViewControl::OnSize()
2155 if ([m_OutlineView numberOfColumns] == 1)
2156 [m_OutlineView sizeLastColumnToFit];
2160 // drag & drop helper methods
2162 wxDataFormat wxCocoaDataViewControl::GetDnDDataFormat(wxDataObjectComposite* dataObjects)
2164 wxDataFormat resultFormat;
2166 return resultFormat;
2168 bool compatible(true);
2170 size_t const noOfFormats = dataObjects->GetFormatCount();
2173 wxDataFormat* formats;
2175 // get all formats and check afterwards if the formats are compatible; if
2176 // they are compatible the preferred format is returned otherwise
2177 // wxDF_INVALID is returned;
2178 // currently compatible types (ordered by priority are):
2179 // - wxDF_UNICODETEXT - wxDF_TEXT
2180 formats = new wxDataFormat[noOfFormats];
2181 dataObjects->GetAllFormats(formats);
2183 while ((indexFormat < noOfFormats) && compatible)
2185 switch (resultFormat.GetType())
2188 resultFormat.SetType(formats[indexFormat].GetType()); // first format (should only be reached if indexFormat == 0)
2191 if (formats[indexFormat].GetType() == wxDF_UNICODETEXT)
2192 resultFormat.SetType(wxDF_UNICODETEXT);
2193 else // incompatible
2195 resultFormat.SetType(wxDF_INVALID);
2199 case wxDF_UNICODETEXT:
2200 if (formats[indexFormat].GetType() != wxDF_TEXT)
2202 resultFormat.SetType(wxDF_INVALID);
2207 resultFormat.SetType(wxDF_INVALID); // not (yet) supported format
2215 return resultFormat;
2218 wxDataObjectComposite* wxCocoaDataViewControl::GetDnDDataObjects(NSData* dataObject) const
2220 wxDataFormatId dataFormatID;
2223 [dataObject getBytes:&dataFormatID length:sizeof(wxDataFormatId)];
2224 switch (dataFormatID)
2227 case wxDF_UNICODETEXT:
2229 wxTextDataObject* textDataObject(new wxTextDataObject());
2231 if (textDataObject->SetData(wxDataFormat(dataFormatID),[dataObject length]-sizeof(wxDataFormatId),static_cast<char const*>([dataObject bytes])+sizeof(wxDataFormatId)))
2233 wxDataObjectComposite* dataObjectComposite(new wxDataObjectComposite());
2235 dataObjectComposite->Add(textDataObject);
2236 return dataObjectComposite;
2240 delete textDataObject;
2250 id wxCocoaDataViewControl::GetItemAtRow(int row) const
2252 return [m_OutlineView itemAtRow:row];
2255 // ----------------------------------------------------------------------------
2256 // wxDataViewRendererNativeData
2257 // ----------------------------------------------------------------------------
2259 void wxDataViewRendererNativeData::Init()
2262 m_origTextColour = NULL;
2263 m_ellipsizeMode = wxELLIPSIZE_MIDDLE;
2266 ApplyLineBreakMode(m_ColumnCell);
2269 void wxDataViewRendererNativeData::ApplyLineBreakMode(NSCell *cell)
2271 NSLineBreakMode nsMode = NSLineBreakByWordWrapping;
2272 switch ( m_ellipsizeMode )
2274 case wxELLIPSIZE_NONE:
2275 nsMode = NSLineBreakByClipping;
2278 case wxELLIPSIZE_START:
2279 nsMode = NSLineBreakByTruncatingHead;
2282 case wxELLIPSIZE_MIDDLE:
2283 nsMode = NSLineBreakByTruncatingMiddle;
2286 case wxELLIPSIZE_END:
2287 nsMode = NSLineBreakByTruncatingTail;
2291 wxASSERT_MSG( nsMode != NSLineBreakByWordWrapping, "unknown wxEllipsizeMode" );
2293 [cell setLineBreakMode: nsMode];
2296 // ---------------------------------------------------------
2297 // wxDataViewRenderer
2298 // ---------------------------------------------------------
2300 wxDataViewRenderer::wxDataViewRenderer(const wxString& varianttype,
2301 wxDataViewCellMode mode,
2303 : wxDataViewRendererBase(varianttype, mode, align),
2306 m_NativeDataPtr(NULL)
2310 wxDataViewRenderer::~wxDataViewRenderer()
2312 delete m_NativeDataPtr;
2315 void wxDataViewRenderer::SetAlignment(int align)
2317 m_alignment = align;
2318 [GetNativeData()->GetColumnCell() setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2321 void wxDataViewRenderer::SetMode(wxDataViewCellMode mode)
2325 [GetOwner()->GetNativeData()->GetNativeColumnPtr() setEditable:(mode == wxDATAVIEW_CELL_EDITABLE)];
2328 void wxDataViewRenderer::SetNativeData(wxDataViewRendererNativeData* newNativeDataPtr)
2330 delete m_NativeDataPtr;
2331 m_NativeDataPtr = newNativeDataPtr;
2334 void wxDataViewRenderer::EnableEllipsize(wxEllipsizeMode mode)
2336 // we need to store this value to apply it to the columns headerCell in
2337 // CreateNativeColumn()
2338 GetNativeData()->SetEllipsizeMode(mode);
2340 // but we may already apply it to the column cell which will be used for
2342 GetNativeData()->ApplyLineBreakMode(GetNativeData()->GetColumnCell());
2345 wxEllipsizeMode wxDataViewRenderer::GetEllipsizeMode() const
2347 return GetNativeData()->GetEllipsizeMode();
2351 wxDataViewRenderer::OSXOnCellChanged(NSObject *object,
2352 const wxDataViewItem& item,
2355 // TODO: we probably should get rid of this code entirely and make this
2356 // function pure virtual, but currently we still have some native
2357 // renderers (wxDataViewChoiceRenderer) which don't override it and
2358 // there is also wxDataViewCustomRenderer for which it's not obvious
2359 // how it should be implemented so keep this "auto-deduction" of
2360 // variant type from NSObject for now
2363 if ( [object isKindOfClass:[NSString class]] )
2364 value = ObjectToString(object);
2365 else if ( [object isKindOfClass:[NSNumber class]] )
2366 value = ObjectToLong(object);
2367 else if ( [object isKindOfClass:[NSDate class]] )
2368 value = ObjectToDate(object);
2371 wxFAIL_MSG( wxString::Format
2373 "unknown value type %s",
2374 wxCFStringRef::AsString([object className])
2379 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2380 model->ChangeValue(value, item, col);
2383 IMPLEMENT_ABSTRACT_CLASS(wxDataViewRenderer,wxDataViewRendererBase)
2385 // ---------------------------------------------------------
2386 // wxDataViewCustomRenderer
2387 // ---------------------------------------------------------
2388 wxDataViewCustomRenderer::wxDataViewCustomRenderer(const wxString& varianttype,
2389 wxDataViewCellMode mode,
2391 : wxDataViewRenderer(varianttype, mode, align),
2392 m_editorCtrlPtr(NULL),
2395 SetNativeData(new wxDataViewRendererNativeData([[wxCustomCell alloc] init]));
2398 bool wxDataViewCustomRenderer::MacRender()
2400 [GetNativeData()->GetItemCell() setObjectValue:[[[wxCustomRendererObject alloc] initWithRenderer:this] autorelease]];
2404 IMPLEMENT_ABSTRACT_CLASS(wxDataViewCustomRenderer, wxDataViewRenderer)
2406 // ---------------------------------------------------------
2407 // wxDataViewTextRenderer
2408 // ---------------------------------------------------------
2409 wxDataViewTextRenderer::wxDataViewTextRenderer(const wxString& varianttype,
2410 wxDataViewCellMode mode,
2412 : wxDataViewRenderer(varianttype,mode,align)
2414 NSTextFieldCell* cell;
2417 cell = [[NSTextFieldCell alloc] init];
2418 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2419 SetNativeData(new wxDataViewRendererNativeData(cell));
2423 bool wxDataViewTextRenderer::MacRender()
2425 if (GetValue().GetType() == GetVariantType())
2427 [GetNativeData()->GetItemCell() setObjectValue:wxCFStringRef(GetValue().GetString()).AsNSString()];
2432 wxFAIL_MSG(wxString("Text renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2438 wxDataViewTextRenderer::OSXOnCellChanged(NSObject *value,
2439 const wxDataViewItem& item,
2442 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2443 model->ChangeValue(ObjectToString(value), item, col);
2446 IMPLEMENT_CLASS(wxDataViewTextRenderer,wxDataViewRenderer)
2448 // ---------------------------------------------------------
2449 // wxDataViewBitmapRenderer
2450 // ---------------------------------------------------------
2451 wxDataViewBitmapRenderer::wxDataViewBitmapRenderer(const wxString& varianttype,
2452 wxDataViewCellMode mode,
2454 : wxDataViewRenderer(varianttype,mode,align)
2459 cell = [[NSImageCell alloc] init];
2460 SetNativeData(new wxDataViewRendererNativeData(cell));
2464 bool wxDataViewBitmapRenderer::MacRender()
2465 // This method returns 'true' if
2466 // - the passed bitmap is valid and it could be assigned to the native data browser;
2467 // - the passed bitmap is invalid (or is not initialized); this case simulates a non-existing bitmap.
2468 // In all other cases the method returns 'false'.
2470 wxCHECK_MSG(GetValue().GetType() == GetVariantType(),false,wxString("Bitmap renderer cannot render value; value type: ") << GetValue().GetType());
2474 bitmap << GetValue();
2476 [GetNativeData()->GetItemCell() setObjectValue:[[bitmap.GetNSImage() retain] autorelease]];
2480 IMPLEMENT_CLASS(wxDataViewBitmapRenderer,wxDataViewRenderer)
2482 // -------------------------------------
2483 // wxDataViewChoiceRenderer
2484 // -------------------------------------
2485 wxDataViewChoiceRenderer::wxDataViewChoiceRenderer(const wxArrayString& choices,
2486 wxDataViewCellMode mode,
2488 : wxDataViewRenderer(wxT("string"),mode,alignment), m_Choices(choices)
2490 NSPopUpButtonCell* cell;
2493 cell = [[NSPopUpButtonCell alloc] init];
2494 [cell setControlSize:NSMiniControlSize];
2495 [cell setFont:[[NSFont fontWithName:[[cell font] fontName] size:[NSFont systemFontSizeForControlSize:NSMiniControlSize]] autorelease]];
2496 for (size_t i=0; i<choices.GetCount(); ++i)
2497 [cell addItemWithTitle:[[wxCFStringRef(choices[i]).AsNSString() retain] autorelease]];
2498 SetNativeData(new wxDataViewRendererNativeData(cell));
2502 bool wxDataViewChoiceRenderer::MacRender()
2504 if (GetValue().GetType() == GetVariantType())
2506 [((NSPopUpButtonCell*) GetNativeData()->GetItemCell()) selectItemWithTitle:[[wxCFStringRef(GetValue().GetString()).AsNSString() retain] autorelease]];
2511 wxFAIL_MSG(wxString("Choice renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2516 IMPLEMENT_CLASS(wxDataViewChoiceRenderer,wxDataViewRenderer)
2518 // ---------------------------------------------------------
2519 // wxDataViewDateRenderer
2520 // ---------------------------------------------------------
2522 wxDataViewDateRenderer::wxDataViewDateRenderer(const wxString& varianttype,
2523 wxDataViewCellMode mode,
2525 : wxDataViewRenderer(varianttype,mode,align)
2527 NSTextFieldCell* cell;
2529 NSDateFormatter* dateFormatter;
2532 dateFormatter = [[NSDateFormatter alloc] init];
2533 [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
2534 [dateFormatter setDateStyle:NSDateFormatterShortStyle];
2535 cell = [[NSTextFieldCell alloc] init];
2536 [cell setFormatter:dateFormatter];
2537 SetNativeData(new wxDataViewRendererNativeData(cell,[NSDate dateWithString:@"2000-12-30 20:00:00 +0000"]));
2539 [dateFormatter release];
2542 bool wxDataViewDateRenderer::MacRender()
2544 if (GetValue().GetType() == GetVariantType())
2546 if (GetValue().GetDateTime().IsValid())
2548 // -- find best fitting style to show the date --
2549 // as the style should be identical for all cells a reference date instead of the actual cell's date
2550 // value is used for all cells; this reference date is stored in the renderer's native data section
2551 // for speed purposes; otherwise, the reference date's string has to be recalculated for each item that
2552 // may become timewise long if a lot of rows using dates exist;
2553 // the algorithm has the preference to display as much information as possible in the first instance;
2554 // but as this is often impossible due to space restrictions the style is shortened per loop; finally,
2555 // if the shortest time and date format does not fit into the cell the time part is dropped;
2556 // remark: the time part itself is not modified per iteration loop and only uses the short style,
2557 // means that only the hours and minutes are being shown
2558 [GetNativeData()->GetItemCell() setObjectValue:GetNativeData()->GetObject()]; // GetObject() returns a date for testing the size of a date object
2559 [[GetNativeData()->GetItemCell() formatter] setTimeStyle:NSDateFormatterShortStyle];
2560 for (int dateFormatterStyle=4; dateFormatterStyle>0; --dateFormatterStyle)
2562 [[GetNativeData()->GetItemCell() formatter] setDateStyle:(NSDateFormatterStyle)dateFormatterStyle];
2563 if (dateFormatterStyle == 1)
2565 // if the shortest style for displaying the date and time is too long to be fully visible remove the time part of the date:
2566 if ([GetNativeData()->GetItemCell() cellSize].width > [GetNativeData()->GetColumnPtr() width])
2567 [[GetNativeData()->GetItemCell() formatter] setTimeStyle:NSDateFormatterNoStyle];
2568 break; // basically not necessary as the loop would end anyway but let's save the last comparison
2570 else if ([GetNativeData()->GetItemCell() cellSize].width <= [GetNativeData()->GetColumnPtr() width])
2573 // set data (the style is set by the previous loop);
2574 // 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
2575 // from the local to UTC timezone when adding the seconds to 1970-01-01 UTC:
2576 [GetNativeData()->GetItemCell() setObjectValue:[NSDate dateWithTimeIntervalSince1970:GetValue().GetDateTime().ToUTC().Subtract(wxDateTime(1,wxDateTime::Jan,1970)).GetSeconds().ToDouble()]];
2582 wxFAIL_MSG(wxString("Date renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2588 wxDataViewDateRenderer::OSXOnCellChanged(NSObject *value,
2589 const wxDataViewItem& item,
2592 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2593 model->ChangeValue(ObjectToDate(value), item, col);
2596 IMPLEMENT_ABSTRACT_CLASS(wxDataViewDateRenderer,wxDataViewRenderer)
2598 // ---------------------------------------------------------
2599 // wxDataViewIconTextRenderer
2600 // ---------------------------------------------------------
2601 wxDataViewIconTextRenderer::wxDataViewIconTextRenderer(const wxString& varianttype,
2602 wxDataViewCellMode mode,
2604 : wxDataViewRenderer(varianttype,mode)
2606 wxImageTextCell* cell;
2609 cell = [[wxImageTextCell alloc] init];
2610 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2611 SetNativeData(new wxDataViewRendererNativeData(cell));
2615 bool wxDataViewIconTextRenderer::MacRender()
2617 if (GetValue().GetType() == GetVariantType())
2619 wxDataViewIconText iconText;
2621 wxImageTextCell* cell;
2623 cell = (wxImageTextCell*) GetNativeData()->GetItemCell();
2624 iconText << GetValue();
2625 if (iconText.GetIcon().IsOk())
2626 [cell setImage:[[wxBitmap(iconText.GetIcon()).GetNSImage() retain] autorelease]];
2627 [cell setStringValue:[[wxCFStringRef(iconText.GetText()).AsNSString() retain] autorelease]];
2632 wxFAIL_MSG(wxString("Icon & text renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2638 wxDataViewIconTextRenderer::OSXOnCellChanged(NSObject *value,
2639 const wxDataViewItem& item,
2642 wxVariant valueIconText;
2643 valueIconText << wxDataViewIconText(ObjectToString(value));
2645 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2646 model->ChangeValue(valueIconText, item, col);
2649 IMPLEMENT_ABSTRACT_CLASS(wxDataViewIconTextRenderer,wxDataViewRenderer)
2651 // ---------------------------------------------------------
2652 // wxDataViewToggleRenderer
2653 // ---------------------------------------------------------
2654 wxDataViewToggleRenderer::wxDataViewToggleRenderer(const wxString& varianttype,
2655 wxDataViewCellMode mode,
2657 : wxDataViewRenderer(varianttype,mode)
2662 cell = [[NSButtonCell alloc] init];
2663 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2664 [cell setButtonType:NSSwitchButton];
2665 [cell setImagePosition:NSImageOnly];
2666 SetNativeData(new wxDataViewRendererNativeData(cell));
2670 bool wxDataViewToggleRenderer::MacRender()
2672 if (GetValue().GetType() == GetVariantType())
2674 [GetNativeData()->GetItemCell() setIntValue:GetValue().GetLong()];
2679 wxFAIL_MSG(wxString("Toggle renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2685 wxDataViewToggleRenderer::OSXOnCellChanged(NSObject *value,
2686 const wxDataViewItem& item,
2689 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2690 model->ChangeValue(ObjectToBool(value), item, col);
2693 IMPLEMENT_ABSTRACT_CLASS(wxDataViewToggleRenderer,wxDataViewRenderer)
2695 // ---------------------------------------------------------
2696 // wxDataViewProgressRenderer
2697 // ---------------------------------------------------------
2698 wxDataViewProgressRenderer::wxDataViewProgressRenderer(const wxString& label,
2699 const wxString& varianttype,
2700 wxDataViewCellMode mode,
2702 : wxDataViewRenderer(varianttype,mode,align)
2704 NSLevelIndicatorCell* cell;
2706 cell = [[NSLevelIndicatorCell alloc] initWithLevelIndicatorStyle:NSContinuousCapacityLevelIndicatorStyle];
2707 [cell setMinValue:0];
2708 [cell setMaxValue:100];
2709 SetNativeData(new wxDataViewRendererNativeData(cell));
2713 bool wxDataViewProgressRenderer::MacRender()
2715 if (GetValue().GetType() == GetVariantType())
2717 [GetNativeData()->GetItemCell() setIntValue:GetValue().GetLong()];
2722 wxFAIL_MSG(wxString("Progress renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2728 wxDataViewProgressRenderer::OSXOnCellChanged(NSObject *value,
2729 const wxDataViewItem& item,
2732 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2733 model->ChangeValue(ObjectToLong(value), item, col);
2736 IMPLEMENT_ABSTRACT_CLASS(wxDataViewProgressRenderer,wxDataViewRenderer)
2738 // ---------------------------------------------------------
2740 // ---------------------------------------------------------
2742 wxDataViewColumn::wxDataViewColumn(const wxString& title,
2743 wxDataViewRenderer* renderer,
2744 unsigned int model_column,
2748 : wxDataViewColumnBase(renderer, model_column),
2749 m_NativeDataPtr(new wxDataViewColumnNativeData()),
2752 InitCommon(width, align, flags);
2753 if (renderer && (renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
2754 renderer->SetAlignment(align);
2757 wxDataViewColumn::wxDataViewColumn(const wxBitmap& bitmap,
2758 wxDataViewRenderer* renderer,
2759 unsigned int model_column,
2763 : wxDataViewColumnBase(bitmap, renderer, model_column),
2764 m_NativeDataPtr(new wxDataViewColumnNativeData())
2766 InitCommon(width, align, flags);
2767 if (renderer && (renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
2768 renderer->SetAlignment(align);
2771 wxDataViewColumn::~wxDataViewColumn()
2773 delete m_NativeDataPtr;
2776 bool wxDataViewColumn::IsSortKey() const
2778 NSTableColumn *nsCol = GetNativeData()->GetNativeColumnPtr();
2779 return nsCol && ([nsCol sortDescriptorPrototype] != nil);
2782 void wxDataViewColumn::SetAlignment(wxAlignment align)
2784 m_alignment = align;
2785 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2786 if (m_renderer && (m_renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
2787 m_renderer->SetAlignment(align);
2790 void wxDataViewColumn::SetBitmap(const wxBitmap& bitmap)
2792 // bitmaps and titles cannot exist at the same time - if the bitmap is set the title is removed:
2793 m_title = wxEmptyString;
2794 wxDataViewColumnBase::SetBitmap(bitmap);
2795 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setImage:[[bitmap.GetNSImage() retain] autorelease]];
2798 void wxDataViewColumn::SetMaxWidth(int maxWidth)
2800 m_maxWidth = maxWidth;
2801 [m_NativeDataPtr->GetNativeColumnPtr() setMaxWidth:maxWidth];
2804 void wxDataViewColumn::SetMinWidth(int minWidth)
2806 m_minWidth = minWidth;
2807 [m_NativeDataPtr->GetNativeColumnPtr() setMinWidth:minWidth];
2810 void wxDataViewColumn::SetReorderable(bool reorderable)
2814 void wxDataViewColumn::SetResizeable(bool resizeable)
2816 wxDataViewColumnBase::SetResizeable(resizeable);
2818 [m_NativeDataPtr->GetNativeColumnPtr() setResizingMask:NSTableColumnUserResizingMask];
2820 [m_NativeDataPtr->GetNativeColumnPtr() setResizingMask:NSTableColumnNoResizing];
2823 void wxDataViewColumn::SetSortable(bool sortable)
2825 wxDataViewColumnBase::SetSortable(sortable);
2828 void wxDataViewColumn::SetSortOrder(bool ascending)
2830 if (m_ascending != ascending)
2832 m_ascending = ascending;
2835 // change sorting order:
2836 NSArray* sortDescriptors;
2837 NSSortDescriptor* sortDescriptor;
2838 NSTableColumn* tableColumn;
2840 tableColumn = m_NativeDataPtr->GetNativeColumnPtr();
2841 sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[[tableColumn sortDescriptorPrototype] key] ascending:m_ascending];
2842 sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
2843 [tableColumn setSortDescriptorPrototype:sortDescriptor];
2844 [[tableColumn tableView] setSortDescriptors:sortDescriptors];
2845 [sortDescriptor release];
2850 void wxDataViewColumn::SetTitle(const wxString& title)
2852 // bitmaps and titles cannot exist at the same time - if the title is set the bitmap is removed:
2853 wxDataViewColumnBase::SetBitmap(wxBitmap());
2855 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setStringValue:[[wxCFStringRef(title).AsNSString() retain] autorelease]];
2858 void wxDataViewColumn::SetWidth(int width)
2860 [m_NativeDataPtr->GetNativeColumnPtr() setWidth:width];
2864 void wxDataViewColumn::SetAsSortKey(bool WXUNUSED(sort))
2866 // see wxGTK native wxDataViewColumn implementation
2867 wxFAIL_MSG("not implemented");
2870 void wxDataViewColumn::SetNativeData(wxDataViewColumnNativeData* newNativeDataPtr)
2872 delete m_NativeDataPtr;
2873 m_NativeDataPtr = newNativeDataPtr;
2876 #endif // (wxUSE_DATAVIEWCTRL == 1) && !defined(wxUSE_GENERICDATAVIEWCTRL)