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"
27 #include "wx/stopwatch.h"
28 #include "wx/dcgraph.h"
30 // ============================================================================
31 // Constants used locally
32 // ============================================================================
34 #define DataViewPboardType @"OutlineViewItem"
36 // ============================================================================
37 // Classes used locally in dataview.mm
38 // ============================================================================
40 // ============================================================================
42 // ============================================================================
44 @implementation wxPointerObject
54 -(id) initWithPointer:(void*) initPointer
58 self->pointer = initPointer;
63 // inherited methods from NSObject
65 -(BOOL) isEqual:(id)object
67 return (object != nil) &&
68 ([object isKindOfClass:[wxPointerObject class]]) &&
69 (pointer == [((wxPointerObject*) object) pointer]);
74 return (NSUInteger) pointer;
82 -(void) setPointer:(void*) newPointer
92 inline wxDataViewItem wxDataViewItemFromItem(id item)
94 return wxDataViewItem([static_cast<wxPointerObject *>(item) pointer]);
97 inline wxDataViewItem wxDataViewItemFromMaybeNilItem(id item)
99 return item == nil ? wxDataViewItem() : wxDataViewItemFromItem(item);
102 } // anonymous namespace
104 // ----------------------------------------------------------------------------
105 // wxCustomRendererObject
106 // ----------------------------------------------------------------------------
108 @interface wxCustomRendererObject : NSObject <NSCopying>
111 wxDataViewCustomRenderer* customRenderer; // not owned by the class
115 -(id) initWithRenderer:(wxDataViewCustomRenderer*)renderer;
118 @implementation wxCustomRendererObject
125 customRenderer = NULL;
130 -(id) initWithRenderer:(wxDataViewCustomRenderer*)renderer
135 customRenderer = renderer;
140 -(id) copyWithZone:(NSZone*)zone
142 wxCustomRendererObject* copy;
144 copy = [[[self class] allocWithZone:zone] init];
145 copy->customRenderer = customRenderer;
151 // ----------------------------------------------------------------------------
152 // wxDVCNSTableColumn: exists only to override NSTableColumn:dataCellForRow:
153 // ----------------------------------------------------------------------------
155 @interface wxDVCNSTableColumn : NSTableColumn
159 -(id) dataCellForRow:(NSInteger)row;
162 @implementation wxDVCNSTableColumn
164 -(id) dataCellForRow:(NSInteger)row
166 // what we want to do here is to simply return nil for the cells which
167 // shouldn't show anything as otherwise we would show e.g. empty combo box
168 // or progress cells in the columns using the corresponding types even for
169 // the container rows which is wrong
171 // half of the problem is just finding the objects we need from the column
172 // pointer which is itself stashed inside wxPointerObject which we use as
174 const wxDataViewColumn * const
175 dvCol = static_cast<wxDataViewColumn *>(
176 [(wxPointerObject *)[self identifier] pointer]
179 const wxDataViewCtrl * const dvc = dvCol->GetOwner();
180 const wxCocoaDataViewControl * const
181 peer = static_cast<wxCocoaDataViewControl *>(dvc->GetPeer());
184 // once we do have everything, simply ask NSOutlineView for the item...
185 const id item = peer->GetItemAtRow(row);
188 // ... and if it succeeded, ask the model whether it has any value
189 wxDataViewItem dvItem(wxDataViewItemFromItem(item));
191 if ( !dvc->GetModel()->HasValue(dvItem, dvCol->GetModelColumn()) )
195 return [super dataCellForRow:row];
200 // ============================================================================
202 // ============================================================================
207 // convert from NSObject to different C++ types: all these functions check
208 // that the conversion really makes sense and assert if it doesn't
209 wxString ObjectToString(NSObject *object)
211 wxCHECK_MSG( [object isKindOfClass:[NSString class]], "",
214 "string expected but got %s",
215 wxCFStringRef::AsString([object className])
218 return wxCFStringRef([((NSString*) object) retain]).AsString();
221 bool ObjectToBool(NSObject *object)
223 // actually the value must be of NSCFBoolean class but it's private so we
224 // can't check for it directly
225 wxCHECK_MSG( [object isKindOfClass:[NSNumber class]], false,
228 "number expected but got %s",
229 wxCFStringRef::AsString([object className])
232 return [(NSNumber *)object boolValue];
235 long ObjectToLong(NSObject *object)
237 wxCHECK_MSG( [object isKindOfClass:[NSNumber class]], -1,
240 "number expected but got %s",
241 wxCFStringRef::AsString([object className])
244 return [(NSNumber *)object longValue];
247 wxDateTime ObjectToDate(NSObject *object)
249 wxCHECK_MSG( [object isKindOfClass:[NSDate class]], wxInvalidDateTime,
252 "date expected but got %s",
253 wxCFStringRef::AsString([object className])
256 // get the number of seconds since 1970-01-01 UTC and this is the only
257 // way to convert a double to a wxLongLong
258 const wxLongLong seconds = [((NSDate*) object) timeIntervalSince1970];
260 wxDateTime dt(1, wxDateTime::Jan, 1970);
261 dt.Add(wxTimeSpan(0,0,seconds));
263 // the user has entered a date in the local timezone but seconds
264 // contains the number of seconds from date in the local timezone
265 // since 1970-01-01 UTC; therefore, the timezone information has to be
266 // transferred to wxWidgets, too:
267 dt.MakeFromTimezone(wxDateTime::UTC);
272 NSInteger CompareItems(id item1, id item2, void* context)
274 NSArray* const sortDescriptors = (NSArray*) context;
276 NSUInteger const count = [sortDescriptors count];
278 NSInteger result = NSOrderedSame;
279 for ( NSUInteger i = 0; i < count && result == NSOrderedSame; ++i )
281 wxSortDescriptorObject* const
282 sortDescriptor = (wxSortDescriptorObject*)
283 [sortDescriptors objectAtIndex:i];
285 int rc = [sortDescriptor modelPtr]->Compare
287 wxDataViewItemFromItem(item1),
288 wxDataViewItemFromItem(item2),
289 [sortDescriptor columnPtr]->GetModelColumn(),
290 [sortDescriptor ascending] == YES
294 result = NSOrderedAscending;
296 result = NSOrderedDescending;
302 NSTextAlignment ConvertToNativeHorizontalTextAlignment(int alignment)
304 if (alignment & wxALIGN_CENTER_HORIZONTAL)
305 return NSCenterTextAlignment;
306 else if (alignment & wxALIGN_RIGHT)
307 return NSRightTextAlignment;
309 return NSLeftTextAlignment;
312 NSTableColumn* CreateNativeColumn(const wxDataViewColumn *column)
314 wxDataViewRenderer * const renderer = column->GetRenderer();
316 wxCHECK_MSG( renderer, NULL, "column should have a renderer" );
318 wxDVCNSTableColumn * const nativeColumn(
319 [[wxDVCNSTableColumn alloc] initWithIdentifier:
320 [[[wxPointerObject alloc] initWithPointer:
321 const_cast<wxDataViewColumn*>(column)]
325 // setting the size related parameters:
327 if (column->IsResizeable())
329 resizingMask = NSTableColumnUserResizingMask;
330 [nativeColumn setMinWidth:column->GetMinWidth()];
331 [nativeColumn setMaxWidth:column->GetMaxWidth()];
333 else // column is not resizable [by user]
335 // if the control doesn't show a header, make the columns resize
336 // automatically, this is particularly important for the single column
337 // controls (such as wxDataViewTreeCtrl) as their unique column should
338 // always take up all the available splace
339 resizingMask = column->GetOwner()->HasFlag(wxDV_NO_HEADER)
340 ? NSTableColumnAutoresizingMask
341 : NSTableColumnNoResizing;
343 [nativeColumn setResizingMask:resizingMask];
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 wxUnusedVar(outlineView);
501 NSArray* supportedTypes(
502 [NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]
505 NSPasteboard* pasteboard([info draggingPasteboard]);
507 NSString* bestType([pasteboard availableTypeFromArray:supportedTypes]);
509 if ( bestType == nil )
512 wxDataViewCtrl * const dvc(implementation->GetDataViewCtrl());
514 wxCHECK_MSG( dvc, false,
515 "Pointer to data view control not set correctly." );
516 wxCHECK_MSG( dvc->GetModel(), false,
517 "Pointer to model not set correctly." );
519 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_DROP, dvc->GetId());
520 event.SetEventObject(dvc);
521 event.SetItem(wxDataViewItemFromItem(item));
522 event.SetModel(dvc->GetModel());
524 BOOL dragSuccessful = false;
525 if ( [bestType compare:DataViewPboardType] == NSOrderedSame )
527 NSArray* dataArray((NSArray*)
528 [pasteboard propertyListForType:DataViewPboardType]);
529 NSUInteger indexDraggedItem, noOfDraggedItems([dataArray count]);
531 indexDraggedItem = 0;
532 while (indexDraggedItem < noOfDraggedItems)
534 wxDataObjectComposite* dataObjects(
535 implementation->GetDnDDataObjects((NSData*)
536 [dataArray objectAtIndex:indexDraggedItem]));
538 if (dataObjects && (dataObjects->GetFormatCount() > 0))
540 wxMemoryBuffer buffer;
542 // copy data into data object:
543 event.SetDataObject(dataObjects);
545 implementation->GetDnDDataFormat(dataObjects));
546 // copy data into buffer:
547 dataObjects->GetDataHere(
548 event.GetDataFormat().GetType(),
549 buffer.GetWriteBuf(event.GetDataSize()));
550 buffer.UngetWriteBuf(event.GetDataSize());
551 event.SetDataBuffer(buffer.GetData());
552 // finally, send event:
553 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
555 dragSuccessful = true;
560 dragSuccessful = true;
561 indexDraggedItem = noOfDraggedItems; // stop loop
566 dragSuccessful = false;
567 indexDraggedItem = noOfDraggedItems; // stop loop
575 // needed to convert internally used UTF-16 representation to a UTF-8
578 wxDataObjectComposite* dataObjects (new wxDataObjectComposite());
579 wxTextDataObject* textDataObject(new wxTextDataObject());
581 osxData = ::CFStringCreateExternalRepresentation
584 (CFStringRef)[pasteboard stringForType:NSStringPboardType],
585 kCFStringEncodingUTF8,
588 if (textDataObject->SetData(::CFDataGetLength(osxData),
589 ::CFDataGetBytePtr(osxData)))
590 dataObjects->Add(textDataObject);
592 delete textDataObject;
593 // send event if data could be copied:
594 if (dataObjects->GetFormatCount() > 0)
596 event.SetDataObject(dataObjects);
597 event.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
598 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
599 dragSuccessful = true;
601 dragSuccessful = false;
604 dragSuccessful = false;
606 ::CFRelease(osxData);
609 return dragSuccessful;
612 -(id) outlineView:(NSOutlineView*)outlineView
613 child:(NSInteger)index
616 wxUnusedVar(outlineView);
618 if ((item == currentParentItem) &&
619 (index < ((NSInteger) [self getChildCount])))
620 return [self getChild:index];
622 wxDataViewItemArray dataViewChildren;
624 wxCHECK_MSG( model, 0, "Valid model in data source does not exist." );
625 model->GetChildren(wxDataViewItemFromMaybeNilItem(item), dataViewChildren);
626 [self bufferItem:item withChildren:&dataViewChildren];
627 if ([sortDescriptors count] > 0)
628 [children sortUsingFunction:CompareItems context:sortDescriptors];
629 return [self getChild:index];
632 -(BOOL) outlineView:(NSOutlineView*)outlineView isItemExpandable:(id)item
634 wxUnusedVar(outlineView);
636 wxCHECK_MSG( model, 0, "Valid model in data source does not exist." );
637 return model->IsContainer(wxDataViewItemFromItem(item));
640 -(NSInteger) outlineView:(NSOutlineView*)outlineView numberOfChildrenOfItem:(id)item
642 wxUnusedVar(outlineView);
644 NSInteger noOfChildren;
646 wxDataViewItemArray dataViewChildren;
649 wxCHECK_MSG( model, 0, "Valid model in data source does not exist." );
650 noOfChildren = model->GetChildren(wxDataViewItemFromMaybeNilItem(item),
652 [self bufferItem:item withChildren:&dataViewChildren];
653 if ([sortDescriptors count] > 0)
654 [children sortUsingFunction:CompareItems context:sortDescriptors];
659 outlineView:(NSOutlineView*)outlineView
660 objectValueForTableColumn:(NSTableColumn*)tableColumn
663 wxUnusedVar(outlineView);
665 wxCHECK_MSG( model, nil, "Valid model in data source does not exist." );
667 wxDataViewColumn* col(static_cast<wxDataViewColumn*>([[tableColumn identifier] pointer]));
668 const unsigned colIdx = col->GetModelColumn();
670 wxDataViewItem dataViewItem(wxDataViewItemFromItem(item));
672 if ( model->HasValue(dataViewItem, colIdx) )
675 model->GetValue(value,dataViewItem, colIdx);
676 col->GetRenderer()->SetValue(value);
683 outlineView:(NSOutlineView*)outlineView
684 setObjectValue:(id)object
685 forTableColumn:(NSTableColumn*)tableColumn
688 wxUnusedVar(outlineView);
690 wxDataViewColumn* col(static_cast<wxDataViewColumn*>([[tableColumn identifier] pointer]));
693 OSXOnCellChanged(object, wxDataViewItemFromItem(item), col->GetModelColumn());
696 -(void) outlineView:(NSOutlineView*)outlineView sortDescriptorsDidChange:(NSArray*)oldDescriptors
698 wxUnusedVar(oldDescriptors);
700 // Warning: the new sort descriptors are guaranteed to be only of type
701 // NSSortDescriptor! Therefore, the sort descriptors for the data source
702 // have to be converted.
703 NSArray* newDescriptors;
705 NSMutableArray* wxSortDescriptors;
707 NSUInteger noOfDescriptors;
709 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
712 // convert NSSortDescriptors to wxSortDescriptorObjects:
713 newDescriptors = [outlineView sortDescriptors];
714 noOfDescriptors = [newDescriptors count];
715 wxSortDescriptors = [NSMutableArray arrayWithCapacity:noOfDescriptors];
716 for (NSUInteger i=0; i<noOfDescriptors; ++i)
718 NSSortDescriptor* const newDescriptor = [newDescriptors objectAtIndex:i];
720 [wxSortDescriptors addObject:[[[wxSortDescriptorObject alloc] initWithModelPtr:model
721 sortingColumnPtr:dvc->GetColumn([[newDescriptor key] intValue])
722 ascending:[newDescriptor ascending]] autorelease]];
724 [(wxCocoaOutlineDataSource*)[outlineView dataSource] setSortDescriptors:wxSortDescriptors];
726 // send first the event to wxWidgets that the sorting has changed so that
727 // the program can do special actions before the sorting actually starts:
728 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_COLUMN_SORTED,dvc->GetId()); // variable defintion
730 event.SetEventObject(dvc);
731 if (noOfDescriptors > 0)
733 wxDataViewColumn* const col = [[wxSortDescriptors objectAtIndex:0] columnPtr];
735 event.SetColumn(dvc->GetColumnPosition(col));
736 event.SetDataViewColumn(col);
738 dvc->GetEventHandler()->ProcessEvent(event);
740 // start re-ordering the data;
741 // children's buffer must be cleared first because it contains the old order:
742 [self clearChildren];
743 // sorting is done while reloading the data:
744 [outlineView reloadData];
747 -(NSDragOperation) outlineView:(NSOutlineView*)outlineView validateDrop:(id<NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
749 wxUnusedVar(outlineView);
752 NSArray* supportedTypes([NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]);
754 NSPasteboard* pasteboard([info draggingPasteboard]);
756 NSString* bestType([pasteboard availableTypeFromArray:supportedTypes]);
758 return NSDragOperationNone;
760 NSDragOperation dragOperation = NSDragOperationNone;
761 wxDataViewCtrl* const dvc(implementation->GetDataViewCtrl());
763 wxCHECK_MSG(dvc, false, "Pointer to data view control not set correctly.");
764 wxCHECK_MSG(dvc->GetModel(), false, "Pointer to model not set correctly.");
767 event(wxEVT_COMMAND_DATAVIEW_ITEM_DROP_POSSIBLE,dvc->GetId());
769 event.SetEventObject(dvc);
770 event.SetItem(wxDataViewItemFromItem(item));
771 event.SetModel(dvc->GetModel());
772 if ([bestType compare:DataViewPboardType] == NSOrderedSame)
774 NSArray* dataArray((NSArray*)[pasteboard propertyListForType:DataViewPboardType]);
775 NSUInteger indexDraggedItem, noOfDraggedItems([dataArray count]);
777 indexDraggedItem = 0;
778 while (indexDraggedItem < noOfDraggedItems)
780 wxDataObjectComposite* dataObjects(implementation->GetDnDDataObjects((NSData*)[dataArray objectAtIndex:indexDraggedItem]));
782 if (dataObjects && (dataObjects->GetFormatCount() > 0))
784 wxMemoryBuffer buffer;
786 // copy data into data object:
787 event.SetDataObject(dataObjects);
788 event.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
789 // copy data into buffer:
790 dataObjects->GetDataHere(event.GetDataFormat().GetType(),buffer.GetWriteBuf(event.GetDataSize()));
791 buffer.UngetWriteBuf(event.GetDataSize());
792 event.SetDataBuffer(buffer.GetData());
793 // finally, send event:
794 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
796 dragOperation = NSDragOperationEvery;
801 dragOperation = NSDragOperationNone;
802 indexDraggedItem = noOfDraggedItems; // stop loop
807 dragOperation = NSDragOperationNone;
808 indexDraggedItem = noOfDraggedItems; // stop loop
816 // needed to convert internally used UTF-16 representation to a UTF-8
819 wxDataObjectComposite* dataObjects (new wxDataObjectComposite());
820 wxTextDataObject* textDataObject(new wxTextDataObject());
822 osxData = ::CFStringCreateExternalRepresentation(kCFAllocatorDefault,(CFStringRef)[pasteboard stringForType:NSStringPboardType],kCFStringEncodingUTF8,32);
823 if (textDataObject->SetData(::CFDataGetLength(osxData),::CFDataGetBytePtr(osxData)))
824 dataObjects->Add(textDataObject);
826 delete textDataObject;
827 // send event if data could be copied:
828 if (dataObjects->GetFormatCount() > 0)
830 event.SetDataObject(dataObjects);
831 event.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
832 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
833 dragOperation = NSDragOperationEvery;
835 dragOperation = NSDragOperationNone;
838 dragOperation = NSDragOperationNone;
840 ::CFRelease(osxData);
844 return dragOperation;
847 -(BOOL) outlineView:(NSOutlineView*)outlineView writeItems:(NSArray*)writeItems toPasteboard:(NSPasteboard*)pasteboard
849 wxUnusedVar(outlineView);
851 // the pasteboard will be filled up with an array containing the data as
852 // returned by the events (including the data type) and a concatenation of
853 // text (string) data; the text data will only be put onto the pasteboard
854 // if for all items a string representation exists
855 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
857 wxDataViewItemArray dataViewItems;
860 wxCHECK_MSG(dvc, false,"Pointer to data view control not set correctly.");
861 wxCHECK_MSG(dvc->GetModel(),false,"Pointer to model not set correctly.");
863 if ([writeItems count] > 0)
865 bool dataStringAvailable(true); // a flag indicating if for all items a data string is available
866 NSMutableArray* dataArray = [NSMutableArray arrayWithCapacity:[writeItems count]]; // data of all items
867 wxString dataString; // contains the string data of all items
869 // send a begin drag event for all selected items and proceed with
870 // dragging unless the event is vetoed:
872 event(wxEVT_COMMAND_DATAVIEW_ITEM_BEGIN_DRAG,dvc->GetId());
874 event.SetEventObject(dvc);
875 event.SetModel(dvc->GetModel());
876 for (size_t itemCounter=0; itemCounter<[writeItems count]; ++itemCounter)
878 bool itemStringAvailable(false); // a flag indicating if for the current item a string is available
879 wxDataObjectComposite* itemObject(new wxDataObjectComposite()); // data object for current item
880 wxString itemString; // contains the TAB concatenated data of an item
883 wxDataViewItemFromItem([writeItems objectAtIndex:itemCounter]));
884 itemString = ::ConcatenateDataViewItemValues(dvc,event.GetItem());
885 itemObject->Add(new wxTextDataObject(itemString));
886 event.SetDataObject(itemObject);
887 // check if event has not been vetoed:
888 if (dvc->HandleWindowEvent(event) && event.IsAllowed() && (event.GetDataObject()->GetFormatCount() > 0))
890 size_t const noOfFormats = event.GetDataObject()->GetFormatCount();
891 wxDataFormat* dataFormats(new wxDataFormat[noOfFormats]);
893 event.GetDataObject()->GetAllFormats(dataFormats,wxDataObject::Get);
894 for (size_t formatCounter=0; formatCounter<noOfFormats; ++formatCounter)
896 // constant definitions for abbreviational purposes:
897 wxDataFormatId const idDataFormat = dataFormats[formatCounter].GetType();
898 size_t const dataSize = event.GetDataObject()->GetDataSize(idDataFormat);
899 size_t const dataBufferSize = sizeof(wxDataFormatId)+dataSize;
900 // variable definitions (used in all case statements):
901 wxMemoryBuffer dataBuffer(dataBufferSize);
903 dataBuffer.AppendData(&idDataFormat,sizeof(wxDataFormatId));
904 switch (idDataFormat)
907 // otherwise wxDF_UNICODETEXT already filled up
908 // the string; and the UNICODE representation has
910 if (!itemStringAvailable)
912 event.GetDataObject()->GetDataHere(wxDF_TEXT,dataBuffer.GetAppendBuf(dataSize));
913 dataBuffer.UngetAppendBuf(dataSize);
914 [dataArray addObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
915 itemString = wxString(static_cast<char const*>(dataBuffer.GetData())+sizeof(wxDataFormatId),wxConvLocal);
916 itemStringAvailable = true;
919 case wxDF_UNICODETEXT:
921 event.GetDataObject()->GetDataHere(wxDF_UNICODETEXT,dataBuffer.GetAppendBuf(dataSize));
922 dataBuffer.UngetAppendBuf(dataSize);
923 if (itemStringAvailable) // does an object already exist as an ASCII text (see wxDF_TEXT case statement)?
924 [dataArray replaceObjectAtIndex:itemCounter withObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
926 [dataArray addObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
927 itemString = wxString::FromUTF8(static_cast<char const*>(dataBuffer.GetData())+sizeof(wxDataFormatId),dataSize);
928 itemStringAvailable = true;
932 wxFAIL_MSG("Data object has invalid or unsupported data format");
937 delete[] dataFormats;
939 if (dataStringAvailable)
940 if (itemStringAvailable)
943 dataString << wxT('\n');
944 dataString << itemString;
947 dataStringAvailable = false;
953 return NO; // dragging was vetoed or no data available
956 if (dataStringAvailable)
958 wxCFStringRef osxString(dataString);
960 [pasteboard declareTypes:[NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil] owner:nil];
961 [pasteboard setPropertyList:dataArray forType:DataViewPboardType];
962 [pasteboard setString:osxString.AsNSString() forType:NSStringPboardType];
966 [pasteboard declareTypes:[NSArray arrayWithObject:DataViewPboardType] owner:nil];
967 [pasteboard setPropertyList:dataArray forType:DataViewPboardType];
972 return NO; // no items to drag (should never occur)
978 -(void) addToBuffer:(wxPointerObject*)item
980 [items addObject:item];
985 [items removeAllObjects];
988 -(wxPointerObject*) getDataViewItemFromBuffer:(const wxDataViewItem&)item
990 return [items member:[[[wxPointerObject alloc] initWithPointer:item.GetID()] autorelease]];
993 -(wxPointerObject*) getItemFromBuffer:(wxPointerObject*)item
995 return [items member:item];
998 -(BOOL) isInBuffer:(wxPointerObject*)item
1000 return [items containsObject:item];
1003 -(void) removeFromBuffer:(wxPointerObject*)item
1005 [items removeObject:item];
1009 // children handling
1011 -(void) appendChild:(wxPointerObject*)item
1013 [children addObject:item];
1016 -(void) clearChildren
1018 [children removeAllObjects];
1021 -(wxPointerObject*) getChild:(NSUInteger)index
1023 return [children objectAtIndex:index];
1026 -(NSUInteger) getChildCount
1028 return [children count];
1031 -(void) removeChild:(NSUInteger)index
1033 [children removeObjectAtIndex:index];
1039 -(void) clearBuffers
1042 [self clearChildren];
1043 [self setCurrentParentItem:nil];
1049 -(NSArray*) sortDescriptors
1051 return sortDescriptors;
1054 -(void) setSortDescriptors:(NSArray*)newSortDescriptors
1056 [newSortDescriptors retain];
1057 [sortDescriptors release];
1058 sortDescriptors = newSortDescriptors;
1062 // access to wxWidget's implementation
1064 -(wxPointerObject*) currentParentItem
1066 return currentParentItem;
1069 -(wxCocoaDataViewControl*) implementation
1071 return implementation;
1074 -(wxDataViewModel*) model
1079 -(void) setCurrentParentItem:(wxPointerObject*)newCurrentParentItem
1081 [newCurrentParentItem retain];
1082 [currentParentItem release];
1083 currentParentItem = newCurrentParentItem;
1086 -(void) setImplementation:(wxCocoaDataViewControl*) newImplementation
1088 implementation = newImplementation;
1091 -(void) setModel:(wxDataViewModel*) newModel
1099 -(void) bufferItem:(wxPointerObject*)parentItem withChildren:(wxDataViewItemArray*)dataViewChildrenPtr
1101 NSInteger const noOfChildren = (*dataViewChildrenPtr).GetCount();
1103 [self setCurrentParentItem:parentItem];
1104 [self clearChildren];
1105 for (NSInteger indexChild=0; indexChild<noOfChildren; ++indexChild)
1107 wxPointerObject* bufferedPointerObject;
1108 wxPointerObject* newPointerObject([[wxPointerObject alloc] initWithPointer:(*dataViewChildrenPtr)[indexChild].GetID()]);
1110 // The next statement and test looks strange but there is
1111 // unfortunately no workaround: due to the fact that two pointer
1112 // objects are identical if their pointers are identical - because the
1113 // method isEqual has been overloaded - the set operation will only
1114 // add a new pointer object if there is not already one in the set
1115 // having the same pointer. On the other side the children's array
1116 // would always add the new pointer object. This means that different
1117 // pointer objects are stored in the set and array. This will finally
1118 // lead to a crash as objects diverge. To solve this issue it is first
1119 // tested if the child already exists in the set and if it is the case
1120 // the sets object is going to be appended to the array, otheriwse the
1121 // new pointer object is added to the set and array:
1122 bufferedPointerObject = [self getItemFromBuffer:newPointerObject];
1123 if (bufferedPointerObject == nil)
1125 [items addObject:newPointerObject];
1126 [children addObject:newPointerObject];
1129 [children addObject:bufferedPointerObject];
1130 [newPointerObject release];
1136 // ============================================================================
1138 // ============================================================================
1140 @implementation wxCustomCell
1144 wxCustomRendererObject * const
1145 obj = static_cast<wxCustomRendererObject *>([self objectValue]);
1148 const wxSize size = obj->customRenderer->GetSize();
1149 return NSMakeSize(size.x, size.y);
1155 -(void) drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
1157 wxCustomRendererObject * const
1158 obj = static_cast<wxCustomRendererObject *>([self objectValue]);
1161 // this may happen for the custom cells in container rows: they don't
1166 wxDataViewCustomRenderer * const renderer = obj->customRenderer;
1168 // if this method is called everything is already setup correctly,
1169 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1170 CGContextSaveGState( context );
1172 if ( ![controlView isFlipped] )
1174 CGContextTranslateCTM( context, 0, [controlView bounds].size.height );
1175 CGContextScaleCTM( context, 1, -1 );
1179 wxGraphicsContext* gc = wxGraphicsContext::CreateFromNative(context);
1180 dc.SetGraphicsContext(gc);
1183 if ( [self isHighlighted] )
1184 state |= wxDATAVIEW_CELL_SELECTED;
1186 renderer->WXCallRender(wxFromNSRect(controlView, cellFrame), &dc, state);
1188 CGContextRestoreGState( context );
1191 -(NSRect) imageRectForBounds:(NSRect)cellFrame
1196 -(NSRect) titleRectForBounds:(NSRect)cellFrame
1203 // ============================================================================
1205 // ============================================================================
1206 @implementation wxImageTextCell
1212 self = [super init];
1215 // initializing the text part:
1216 [self setSelectable:YES];
1217 // initializing the image part:
1219 imageSize = NSMakeSize(16,16);
1220 spaceImageText = 5.0;
1226 -(id) copyWithZone:(NSZone*)zone
1228 wxImageTextCell* cell;
1231 cell = (wxImageTextCell*) [super copyWithZone:zone];
1232 cell->image = [image retain];
1233 cell->imageSize = imageSize;
1234 cell->spaceImageText = spaceImageText;
1235 cell->xImageShift = xImageShift;
1250 -(NSTextAlignment) alignment
1252 return cellAlignment;
1255 -(void) setAlignment:(NSTextAlignment)newAlignment
1257 cellAlignment = newAlignment;
1258 switch (newAlignment)
1260 case NSCenterTextAlignment:
1261 case NSLeftTextAlignment:
1262 case NSJustifiedTextAlignment:
1263 case NSNaturalTextAlignment:
1264 [super setAlignment:NSLeftTextAlignment];
1266 case NSRightTextAlignment:
1267 [super setAlignment:NSRightTextAlignment];
1270 wxFAIL_MSG("Unknown alignment type.");
1282 -(void) setImage:(NSImage*)newImage
1294 -(void) setImageSize:(NSSize) newImageSize
1296 imageSize = newImageSize;
1302 -(NSSize) cellImageSize
1304 return NSMakeSize(imageSize.width+xImageShift+spaceImageText,imageSize.height);
1309 NSSize cellSize([super cellSize]);
1312 if (imageSize.height > cellSize.height)
1313 cellSize.height = imageSize.height;
1314 cellSize.width += imageSize.width+xImageShift+spaceImageText;
1319 -(NSSize) cellTextSize
1321 return [super cellSize];
1327 -(void) determineCellParts:(NSRect)cellFrame imagePart:(NSRect*)imageFrame textPart:(NSRect*)textFrame
1329 switch (cellAlignment)
1331 case NSCenterTextAlignment:
1333 CGFloat const cellSpace = cellFrame.size.width-[self cellSize].width;
1335 // if the cell's frame is smaller than its contents (at least
1336 // in x-direction) make sure that the image is visible:
1338 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1339 else // otherwise center the image and text in the cell's frame
1340 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText+0.5*cellSpace,NSMinXEdge);
1343 case NSJustifiedTextAlignment:
1344 case NSLeftTextAlignment:
1345 case NSNaturalTextAlignment: // how to determine the natural writing direction? TODO
1346 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1348 case NSRightTextAlignment:
1350 CGFloat const cellSpace = cellFrame.size.width-[self cellSize].width;
1352 // if the cell's frame is smaller than its contents (at least
1353 // in x-direction) make sure that the image is visible:
1355 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1356 else // otherwise right align the image and text in the cell's frame
1357 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText+cellSpace,NSMinXEdge);
1361 *imageFrame = NSZeroRect;
1362 *textFrame = NSZeroRect;
1363 wxFAIL_MSG("Unhandled alignment type.");
1367 -(void) drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
1369 NSRect textFrame, imageFrame;
1372 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1373 // draw the image part by ourselves;
1374 // check if the cell has to draw its own background (checking is done by
1375 // the parameter of the textfield's cell):
1376 if ([self drawsBackground])
1378 [[self backgroundColor] set];
1379 NSRectFill(imageFrame);
1383 // the image is slightly shifted (xImageShift) and has a fixed size
1384 // but the image's frame might be larger and starts currently on the
1385 // left side of the cell's frame; therefore, the origin and the
1386 // image's frame size have to be adjusted:
1387 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1389 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1390 imageFrame.size.width = imageSize.width;
1394 imageFrame.origin.x += xImageShift;
1395 imageFrame.size.width -= xImageShift+spaceImageText;
1397 // ...and the image has to be centered in the y-direction:
1398 if (imageFrame.size.height > imageSize.height)
1399 imageFrame.size.height = imageSize.height;
1400 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1402 // according to the documentation the coordinate system should be
1403 // flipped for NSTableViews (y-coordinate goes from top to bottom); to
1404 // draw an image correctly the coordinate system has to be transformed
1405 // to a bottom-top coordinate system, otherwise the image's
1406 // content is flipped:
1407 NSAffineTransform* coordinateTransform([NSAffineTransform transform]);
1409 if ([controlView isFlipped])
1411 [coordinateTransform scaleXBy: 1.0 yBy:-1.0]; // first the coordinate system is brought back to bottom-top orientation
1412 [coordinateTransform translateXBy:0.0 yBy:(-2.0)*imageFrame.origin.y-imageFrame.size.height]; // the coordinate system has to be moved to compensate for the
1413 [coordinateTransform concat]; // other orientation and the position of the image's frame
1415 [image drawInRect:imageFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0]; // suggested method to draw the image
1416 // instead of compositeToPoint:operation:
1417 // take back previous transformation (if the view is not flipped the
1418 // coordinate transformation matrix contains the identity matrix and
1419 // the next two operations do not change the content's transformation
1421 [coordinateTransform invert];
1422 [coordinateTransform concat];
1424 // let the textfield cell draw the text part:
1425 if (textFrame.size.width > [self cellTextSize].width)
1427 // for unknown reasons the alignment of the text cell is ignored;
1428 // therefore change the size so that alignment does not influence the
1429 // visualization anymore
1430 textFrame.size.width = [self cellTextSize].width;
1432 [super drawWithFrame:textFrame inView:controlView];
1435 -(void) editWithFrame:(NSRect)aRect inView:(NSView*)controlView editor:(NSText*)textObj delegate:(id)anObject event:(NSEvent*)theEvent
1437 NSRect textFrame, imageFrame;
1440 [self determineCellParts:aRect imagePart:&imageFrame textPart:&textFrame];
1441 [super editWithFrame:textFrame inView:controlView editor:textObj delegate:anObject event:theEvent];
1444 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1445 -(NSUInteger) hitTestForEvent:(NSEvent*)event inRect:(NSRect)cellFrame ofView:(NSView*)controlView
1447 NSPoint point = [controlView convertPoint:[event locationInWindow] fromView:nil];
1449 NSRect imageFrame, textFrame;
1452 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1455 // the image is shifted...
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));
1470 // If the point is in the image rect, then it is a content hit (see
1471 // documentation for hitTestForEvent:inRect:ofView):
1472 if (NSMouseInRect(point, imageFrame, [controlView isFlipped]))
1473 return NSCellHitContentArea;
1475 // if the image was not hit let's try the text part:
1476 if (textFrame.size.width > [self cellTextSize].width)
1478 // for unknown reasons the alignment of the text cell is ignored;
1479 // therefore change the size so that alignment does not influence the
1480 // visualization anymore
1481 textFrame.size.width = [self cellTextSize].width;
1484 return [super hitTestForEvent:event inRect:textFrame ofView:controlView];
1488 -(NSRect) imageRectForBounds:(NSRect)cellFrame
1490 NSRect textFrame, imageFrame;
1493 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1494 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1496 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1497 imageFrame.size.width = imageSize.width;
1501 imageFrame.origin.x += xImageShift;
1502 imageFrame.size.width -= xImageShift+spaceImageText;
1505 if (imageFrame.size.height > imageSize.height)
1506 imageFrame.size.height = imageSize.height;
1507 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1512 -(void) selectWithFrame:(NSRect)aRect inView:(NSView*)controlView editor:(NSText*)textObj delegate:(id)anObject start:(NSInteger)selStart length:(NSInteger)selLength
1514 NSRect textFrame, imageFrame;
1517 [self determineCellParts:aRect imagePart:&imageFrame textPart:&textFrame];
1518 [super selectWithFrame:textFrame inView:controlView editor:textObj delegate:anObject start:selStart length:selLength];
1521 -(NSRect) titleRectForBounds:(NSRect)cellFrame
1523 NSRect textFrame, imageFrame;
1526 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1532 // ============================================================================
1533 // wxCocoaOutlineView
1534 // ============================================================================
1535 @implementation wxCocoaOutlineView
1538 // initializers / destructor
1542 self = [super init];
1545 currentlyEditedColumn =
1546 currentlyEditedRow = -1;
1548 [self registerForDraggedTypes:[NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]];
1549 [self setDelegate:self];
1550 [self setDoubleAction:@selector(actionDoubleClick:)];
1551 [self setDraggingSourceOperationMask:NSDragOperationEvery forLocal:NO];
1552 [self setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
1553 [self setTarget:self];
1559 // access to wxWidget's implementation
1561 -(wxCocoaDataViewControl*) implementation
1563 return implementation;
1566 -(void) setImplementation:(wxCocoaDataViewControl*) newImplementation
1568 implementation = newImplementation;
1574 -(void) actionDoubleClick:(id)sender
1576 wxUnusedVar(sender);
1578 // actually the documentation (NSTableView 2007-10-31) for doubleAction:
1579 // and setDoubleAction: seems to be wrong as this action message is always
1580 // sent whether the cell is editable or not
1581 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1583 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_ACTIVATED,dvc->GetId());
1586 event.SetEventObject(dvc);
1587 event.SetItem(wxDataViewItemFromItem([self itemAtRow:[self clickedRow]]));
1588 dvc->GetEventHandler()->ProcessEvent(event);
1595 -(NSMenu*) menuForEvent:(NSEvent*)theEvent
1597 wxUnusedVar(theEvent);
1599 // this method does not do any special menu event handling but only sends
1600 // an event message; therefore, the user has full control if a context
1601 // menu should be shown or not
1602 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1604 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_CONTEXT_MENU,dvc->GetId());
1606 wxDataViewItemArray selectedItems;
1609 event.SetEventObject(dvc);
1610 event.SetModel(dvc->GetModel());
1611 // get the item information;
1612 // theoretically more than one ID can be returned but the event can only
1613 // handle one item, therefore only the first item of the array is
1615 if (dvc->GetSelections(selectedItems) > 0)
1616 event.SetItem(selectedItems[0]);
1617 dvc->GetEventHandler()->ProcessEvent(event);
1625 -(void) outlineView:(NSOutlineView*)outlineView mouseDownInHeaderOfTableColumn:(NSTableColumn*)tableColumn
1627 wxDataViewColumn* const col(static_cast<wxDataViewColumn*>([[tableColumn identifier] pointer]));
1629 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1632 event(wxEVT_COMMAND_DATAVIEW_COLUMN_HEADER_CLICK,dvc->GetId());
1635 // first, send an event that the user clicked into a column's header:
1636 event.SetEventObject(dvc);
1637 event.SetColumn(dvc->GetColumnPosition(col));
1638 event.SetDataViewColumn(col);
1639 dvc->HandleWindowEvent(event);
1641 // now, check if the click may have had an influence on sorting, too;
1642 // the sorting setup has to be done only if the clicked table column is
1643 // sortable and has not been used for sorting before the click; if the
1644 // column is already responsible for sorting the native control changes
1645 // the sorting direction automatically and informs the data source via
1646 // outlineView:sortDescriptorsDidChange:
1647 if (col->IsSortable() && ([tableColumn sortDescriptorPrototype] == nil))
1649 // remove the sort order from the previously sorted column table (it
1650 // can also be that no sorted column table exists):
1651 UInt32 const noOfColumns = [outlineView numberOfColumns];
1653 for (UInt32 i=0; i<noOfColumns; ++i)
1654 [[[outlineView tableColumns] objectAtIndex:i] setSortDescriptorPrototype:nil];
1655 // make column table sortable:
1656 NSArray* sortDescriptors;
1657 NSSortDescriptor* sortDescriptor;
1659 sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[NSString stringWithFormat:@"%d",[outlineView columnWithIdentifier:[tableColumn identifier]]]
1661 sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
1662 [tableColumn setSortDescriptorPrototype:sortDescriptor];
1663 [outlineView setSortDescriptors:sortDescriptors];
1664 [sortDescriptor release];
1668 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldCollapseItem:(id)item
1670 wxUnusedVar(outlineView);
1672 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1674 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSING,dvc->GetId());
1677 event.SetEventObject(dvc);
1678 event.SetItem (wxDataViewItemFromItem(item));
1679 event.SetModel (dvc->GetModel());
1680 // finally send the equivalent wxWidget event:
1681 dvc->GetEventHandler()->ProcessEvent(event);
1682 // opening the container is allowed if not vetoed:
1683 return event.IsAllowed();
1686 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldExpandItem:(id)item
1688 wxUnusedVar(outlineView);
1690 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1692 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDING,dvc->GetId());
1695 event.SetEventObject(dvc);
1696 event.SetItem (wxDataViewItemFromItem(item));
1697 event.SetModel (dvc->GetModel());
1698 // finally send the equivalent wxWidget event:
1699 dvc->GetEventHandler()->ProcessEvent(event);
1700 // opening the container is allowed if not vetoed:
1701 return event.IsAllowed();
1704 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldSelectTableColumn:(NSTableColumn*)tableColumn
1706 wxUnusedVar(tableColumn);
1707 wxUnusedVar(outlineView);
1712 -(void) outlineView:(wxCocoaOutlineView*)outlineView
1713 willDisplayCell:(id)cell
1714 forTableColumn:(NSTableColumn*)tableColumn
1717 wxUnusedVar(outlineView);
1719 wxDataViewCtrl * const dvc = implementation->GetDataViewCtrl();
1720 wxDataViewModel * const model = dvc->GetModel();
1722 wxDataViewColumn * const
1723 dvCol(static_cast<wxDataViewColumn*>(
1724 [[tableColumn identifier] pointer]
1727 const unsigned colIdx = dvCol->GetModelColumn();
1729 wxDataViewItem dvItem(wxDataViewItemFromItem(item));
1731 if ( !model->HasValue(dvItem, colIdx) )
1734 wxDataViewRenderer * const renderer = dvCol->GetRenderer();
1735 wxDataViewRendererNativeData * const data = renderer->GetNativeData();
1737 // let the renderer know about what it's going to render next
1738 data->SetColumnPtr(tableColumn);
1739 data->SetItem(item);
1740 data->SetItemCell(cell);
1742 // use the attributes: notice that we need to do this whether we have them
1743 // or not as even if this cell doesn't have any attributes, the previous
1744 // one might have had some and then we need to reset them back to default
1745 wxDataViewItemAttr attr;
1746 model->GetAttr(dvItem, colIdx, attr);
1747 renderer->OSXApplyAttr(attr);
1749 // set the state (enabled/disabled) of the item
1750 renderer->OSXApplyEnabled(model->IsEnabled(dvItem, colIdx));
1752 // and finally do draw it
1753 renderer->MacRender();
1759 -(void) outlineViewColumnDidMove:(NSNotification*)notification
1761 int const newColumnPosition = [[[notification userInfo] objectForKey:@"NSNewColumn"] intValue];
1763 wxDataViewColumn* const col(static_cast<wxDataViewColumn*>([[[[self tableColumns] objectAtIndex:newColumnPosition] identifier] pointer]));
1765 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1767 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_COLUMN_REORDERED,dvc->GetId());
1770 event.SetEventObject(dvc);
1771 event.SetColumn(dvc->GetColumnPosition(col));
1772 event.SetDataViewColumn(col);
1773 dvc->GetEventHandler()->ProcessEvent(event);
1776 -(void) outlineViewItemDidCollapse:(NSNotification*)notification
1778 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1780 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSED,dvc->GetId());
1783 event.SetEventObject(dvc);
1784 event.SetItem(wxDataViewItemFromItem(
1785 [[notification userInfo] objectForKey:@"NSObject"]));
1786 dvc->GetEventHandler()->ProcessEvent(event);
1789 -(void) outlineViewItemDidExpand:(NSNotification*)notification
1791 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1793 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDED,dvc->GetId());
1796 event.SetEventObject(dvc);
1797 event.SetItem(wxDataViewItemFromItem(
1798 [[notification userInfo] objectForKey:@"NSObject"]));
1799 dvc->GetEventHandler()->ProcessEvent(event);
1802 -(void) outlineViewSelectionDidChange:(NSNotification*)notification
1804 wxUnusedVar(notification);
1806 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1808 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_SELECTION_CHANGED,dvc->GetId());
1810 event.SetEventObject(dvc);
1811 event.SetModel(dvc->GetModel());
1812 event.SetItem(dvc->GetSelection());
1813 dvc->GetEventHandler()->ProcessEvent(event);
1816 -(void) textDidBeginEditing:(NSNotification*)notification
1818 // this notification is only sent if the user started modifying the cell
1819 // (not when the user clicked into the cell and the cell's editor is
1822 // call method of superclass (otherwise editing does not work correctly -
1823 // the outline data source class is not informed about a change of data):
1824 [super textDidBeginEditing:notification];
1826 // remember the column being edited, it will be used in textDidEndEditing:
1827 currentlyEditedColumn = [self editedColumn];
1828 currentlyEditedRow = [self editedRow];
1830 wxDataViewColumn* const col =
1831 static_cast<wxDataViewColumn*>(
1832 [[[[self tableColumns] objectAtIndex:currentlyEditedColumn] identifier] pointer]);
1834 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1837 // stop editing of a custom item first (if necessary)
1838 dvc->FinishCustomItemEditing();
1840 // now, send the event:
1842 event(wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED,dvc->GetId());
1844 event.SetEventObject(dvc);
1846 wxDataViewItemFromItem([self itemAtRow:currentlyEditedRow]));
1847 event.SetColumn(dvc->GetColumnPosition(col));
1848 event.SetDataViewColumn(col);
1849 dvc->GetEventHandler()->ProcessEvent(event);
1852 -(void) textDidEndEditing:(NSNotification*)notification
1854 // call method of superclass (otherwise editing does not work correctly -
1855 // the outline data source class is not informed about a change of data):
1856 [super textDidEndEditing:notification];
1858 // under OSX an event indicating the end of an editing session can be sent
1859 // even if no event indicating a start of an editing session has been sent
1860 // (see Documentation for NSControl controlTextDidEndEditing:); this is
1861 // not expected by a user of the wxWidgets library and therefore an
1862 // wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_DONE event is only sent if a
1863 // corresponding wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED has been sent
1864 // before; to check if a wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED has
1865 // been sent the last edited column/row are valid:
1866 if ( currentlyEditedColumn != -1 && currentlyEditedRow != -1 )
1868 wxDataViewColumn* const col =
1869 static_cast<wxDataViewColumn*>(
1870 [[[[self tableColumns] objectAtIndex:currentlyEditedColumn] identifier] pointer]);
1872 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1874 // send event to wxWidgets:
1876 event(wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_DONE,dvc->GetId());
1878 event.SetEventObject(dvc);
1880 wxDataViewItemFromItem([self itemAtRow:currentlyEditedRow]));
1881 event.SetColumn(dvc->GetColumnPosition(col));
1882 event.SetDataViewColumn(col);
1883 dvc->GetEventHandler()->ProcessEvent(event);
1886 // we're not editing any more
1887 currentlyEditedColumn =
1888 currentlyEditedRow = -1;
1894 // ============================================================================
1895 // wxCocoaDataViewControl
1896 // ============================================================================
1898 wxCocoaDataViewControl::wxCocoaDataViewControl(wxWindow* peer,
1905 [[NSScrollView alloc] initWithFrame:wxOSXGetFrameForControl(peer,pos,size)]
1908 m_OutlineView([[wxCocoaOutlineView alloc] init])
1910 // initialize scrollview (the outline view is part of a scrollview):
1911 NSScrollView* scrollview = (NSScrollView*) GetWXWidget();
1913 [scrollview setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1914 [scrollview setBorderType:NSNoBorder];
1915 [scrollview setHasVerticalScroller:YES];
1916 [scrollview setHasHorizontalScroller:YES];
1917 [scrollview setAutohidesScrollers:YES];
1918 [scrollview setDocumentView:m_OutlineView];
1920 // initialize the native control itself too
1921 InitOutlineView(style);
1924 void wxCocoaDataViewControl::InitOutlineView(long style)
1926 [m_OutlineView setImplementation:this];
1927 [m_OutlineView setColumnAutoresizingStyle:NSTableViewSequentialColumnAutoresizingStyle];
1928 [m_OutlineView setIndentationPerLevel:GetDataViewCtrl()->GetIndent()];
1929 NSUInteger maskGridStyle(NSTableViewGridNone);
1930 if (style & wxDV_HORIZ_RULES)
1931 maskGridStyle |= NSTableViewSolidHorizontalGridLineMask;
1932 if (style & wxDV_VERT_RULES)
1933 maskGridStyle |= NSTableViewSolidVerticalGridLineMask;
1934 [m_OutlineView setGridStyleMask:maskGridStyle];
1935 [m_OutlineView setAllowsMultipleSelection: (style & wxDV_MULTIPLE) != 0];
1936 [m_OutlineView setUsesAlternatingRowBackgroundColors:(style & wxDV_ROW_LINES) != 0];
1938 if ( style & wxDV_NO_HEADER )
1939 [m_OutlineView setHeaderView:nil];
1942 wxCocoaDataViewControl::~wxCocoaDataViewControl()
1944 [m_DataSource release];
1945 [m_OutlineView release];
1949 // column related methods (inherited from wxDataViewWidgetImpl)
1951 bool wxCocoaDataViewControl::ClearColumns()
1953 // as there is a bug in NSOutlineView version (OSX 10.5.6 #6555162) the
1954 // columns cannot be deleted if there is an outline column in the view;
1955 // therefore, the whole view is deleted and newly constructed:
1956 [m_OutlineView release];
1957 m_OutlineView = [[wxCocoaOutlineView alloc] init];
1958 [((NSScrollView*) GetWXWidget()) setDocumentView:m_OutlineView];
1959 [m_OutlineView setDataSource:m_DataSource];
1961 InitOutlineView(GetDataViewCtrl()->GetWindowStyle());
1966 bool wxCocoaDataViewControl::DeleteColumn(wxDataViewColumn* columnPtr)
1968 if ([m_OutlineView outlineTableColumn] == columnPtr->GetNativeData()->GetNativeColumnPtr())
1969 [m_OutlineView setOutlineTableColumn:nil]; // due to a bug this does not work
1970 [m_OutlineView removeTableColumn:columnPtr->GetNativeData()->GetNativeColumnPtr()]; // due to a confirmed bug #6555162 the deletion does not work for
1971 // outline table columns (... and there is no workaround)
1972 return (([m_OutlineView columnWithIdentifier:[[[wxPointerObject alloc] initWithPointer:columnPtr] autorelease]]) == -1);
1975 void wxCocoaDataViewControl::DoSetExpanderColumn(const wxDataViewColumn *columnPtr)
1977 [m_OutlineView setOutlineTableColumn:columnPtr->GetNativeData()->GetNativeColumnPtr()];
1980 wxDataViewColumn* wxCocoaDataViewControl::GetColumn(unsigned int pos) const
1982 return static_cast<wxDataViewColumn*>([[[[m_OutlineView tableColumns] objectAtIndex:pos] identifier] pointer]);
1985 int wxCocoaDataViewControl::GetColumnPosition(const wxDataViewColumn *columnPtr) const
1987 return [m_OutlineView columnWithIdentifier:[[[wxPointerObject alloc] initWithPointer:const_cast<wxDataViewColumn*>(columnPtr)] autorelease]];
1990 bool wxCocoaDataViewControl::InsertColumn(unsigned int pos, wxDataViewColumn* columnPtr)
1992 // create column and set the native data of the dataview column:
1993 NSTableColumn *nativeColumn = ::CreateNativeColumn(columnPtr);
1994 columnPtr->GetNativeData()->SetNativeColumnPtr(nativeColumn);
1995 // as the native control does not allow the insertion of a column at a
1996 // specified position the column is first appended and - if necessary -
1997 // moved to its final position:
1998 [m_OutlineView addTableColumn:nativeColumn];
1999 if (pos != static_cast<unsigned int>([m_OutlineView numberOfColumns]-1))
2000 [m_OutlineView moveColumn:[m_OutlineView numberOfColumns]-1 toColumn:pos];
2002 // set columns width now that it can be computed even for autosized columns:
2003 columnPtr->SetWidth(columnPtr->GetWidthVariable());
2009 void wxCocoaDataViewControl::FitColumnWidthToContent(unsigned int pos)
2011 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
2012 const int count = GetCount();
2013 NSTableColumn *column = GetColumn(pos)->GetNativeData()->GetNativeColumnPtr();
2015 class MaxWidthCalculator
2018 MaxWidthCalculator(wxCocoaOutlineView *view,
2019 NSTableColumn *column, unsigned columnIndex)
2022 m_column(columnIndex),
2025 // account for indentation in the column with expander
2026 if ( column == [m_view outlineTableColumn] )
2027 m_indent = [m_view indentationPerLevel];
2030 void UpdateWithWidth(int width)
2032 m_width = wxMax(m_width, width);
2035 void UpdateWithRow(int row)
2037 NSCell *cell = [m_view preparedCellAtColumn:m_column row:row];
2038 unsigned cellWidth = [cell cellSize].width + 1/*round the float up*/;
2041 cellWidth += m_indent * ([m_view levelForRow:row] + 1);
2043 m_width = wxMax(m_width, cellWidth);
2046 int GetMaxWidth() const { return m_width; }
2050 wxCocoaOutlineView *m_view;
2055 MaxWidthCalculator calculator(m_OutlineView, column, pos);
2057 if ( [column headerCell] )
2059 calculator.UpdateWithWidth([[column headerCell] cellSize].width + 1/*round the float up*/);
2062 // The code below deserves some explanation. For very large controls, we
2063 // simply can't afford to calculate sizes for all items, it takes too
2064 // long. So the best we can do is to check the first and the last N/2
2065 // items in the control for some sufficiently large N and calculate best
2066 // sizes from that. That can result in the calculated best width being too
2067 // small for some outliers, but it's better to get slightly imperfect
2068 // result than to wait several seconds after every update. To avoid highly
2069 // visible miscalculations, we also include all currently visible items
2070 // no matter what. Finally, the value of N is determined dynamically by
2071 // measuring how much time we spent on the determining item widths so far.
2074 int top_part_end = count;
2075 static const long CALC_TIMEOUT = 20/*ms*/;
2076 // don't call wxStopWatch::Time() too often
2077 static const unsigned CALC_CHECK_FREQ = 100;
2080 // use some hard-coded limit, that's the best we can do without timer
2081 int top_part_end = wxMin(500, count);
2082 #endif // wxUSE_STOPWATCH/!wxUSE_STOPWATCH
2086 for ( row = 0; row < top_part_end; row++ )
2089 if ( row % CALC_CHECK_FREQ == CALC_CHECK_FREQ-1 &&
2090 timer.Time() > CALC_TIMEOUT )
2092 #endif // wxUSE_STOPWATCH
2093 calculator.UpdateWithRow(row);
2096 // row is the first unmeasured item now; that's our value of N/2
2102 // add bottom N/2 items now:
2103 const int bottom_part_start = wxMax(row, count - row);
2104 for ( row = bottom_part_start; row < count; row++ )
2105 calculator.UpdateWithRow(row);
2107 // finally, include currently visible items in the calculation:
2108 const NSRange visible = [m_OutlineView rowsInRect:[m_OutlineView visibleRect]];
2109 const int first_visible = wxMax(visible.location, top_part_end);
2110 const int last_visible = wxMin(first_visible + visible.length, bottom_part_start);
2112 for ( row = first_visible; row < last_visible; row++ )
2113 calculator.UpdateWithRow(row);
2115 wxLogTrace("dataview",
2116 "determined best size from %d top, %d bottom plus %d more visible items out of %d total",
2118 count - bottom_part_start,
2119 wxMax(0, last_visible - first_visible),
2123 [column setWidth:calculator.GetMaxWidth()];
2124 #endif // MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
2128 // item related methods (inherited from wxDataViewWidgetImpl)
2130 bool wxCocoaDataViewControl::Add(const wxDataViewItem& parent, const wxDataViewItem& WXUNUSED(item))
2133 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2135 [m_OutlineView reloadData];
2139 bool wxCocoaDataViewControl::Add(const wxDataViewItem& parent, const wxDataViewItemArray& WXUNUSED(items))
2142 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2144 [m_OutlineView reloadData];
2148 void wxCocoaDataViewControl::Collapse(const wxDataViewItem& item)
2150 [m_OutlineView collapseItem:[m_DataSource getDataViewItemFromBuffer:item]];
2153 void wxCocoaDataViewControl::EnsureVisible(const wxDataViewItem& item, const wxDataViewColumn *columnPtr)
2157 [m_OutlineView scrollRowToVisible:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2159 [m_OutlineView scrollColumnToVisible:GetColumnPosition(columnPtr)];
2163 void wxCocoaDataViewControl::Expand(const wxDataViewItem& item)
2165 [m_OutlineView expandItem:[m_DataSource getDataViewItemFromBuffer:item]];
2168 unsigned int wxCocoaDataViewControl::GetCount() const
2170 return [m_OutlineView numberOfRows];
2173 wxRect wxCocoaDataViewControl::GetRectangle(const wxDataViewItem& item, const wxDataViewColumn *columnPtr)
2175 return wxFromNSRect([m_osxView superview],[m_OutlineView frameOfCellAtColumn:GetColumnPosition(columnPtr)
2176 row:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]]);
2179 bool wxCocoaDataViewControl::IsExpanded(const wxDataViewItem& item) const
2181 return [m_OutlineView isItemExpanded:[m_DataSource getDataViewItemFromBuffer:item]];
2184 bool wxCocoaDataViewControl::Reload()
2186 [m_DataSource clearBuffers];
2187 [m_OutlineView reloadData];
2188 [m_OutlineView scrollColumnToVisible:0];
2189 [m_OutlineView scrollRowToVisible:0];
2193 bool wxCocoaDataViewControl::Remove(const wxDataViewItem& parent, const wxDataViewItem& WXUNUSED(item))
2196 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2198 [m_OutlineView reloadData];
2202 bool wxCocoaDataViewControl::Remove(const wxDataViewItem& parent, const wxDataViewItemArray& WXUNUSED(item))
2205 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2207 [m_OutlineView reloadData];
2211 bool wxCocoaDataViewControl::Update(const wxDataViewColumn *columnPtr)
2213 wxUnusedVar(columnPtr);
2218 bool wxCocoaDataViewControl::Update(const wxDataViewItem& WXUNUSED(parent), const wxDataViewItem& item)
2220 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:item]];
2224 bool wxCocoaDataViewControl::Update(const wxDataViewItem& WXUNUSED(parent), const wxDataViewItemArray& items)
2226 for (size_t i=0; i<items.GetCount(); ++i)
2227 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:items[i]]];
2232 // model related methods
2234 bool wxCocoaDataViewControl::AssociateModel(wxDataViewModel* model)
2236 [m_DataSource release];
2239 m_DataSource = [[wxCocoaOutlineDataSource alloc] init];
2240 [m_DataSource setImplementation:this];
2241 [m_DataSource setModel:model];
2244 m_DataSource = NULL;
2245 [m_OutlineView setDataSource:m_DataSource]; // if there is a data source the data is immediately going to be requested
2250 // selection related methods (inherited from wxDataViewWidgetImpl)
2253 wxDataViewItem wxCocoaDataViewControl::GetCurrentItem() const
2255 return wxDataViewItem([[m_OutlineView itemAtRow:[m_OutlineView selectedRow]] pointer]);
2258 void wxCocoaDataViewControl::SetCurrentItem(const wxDataViewItem& item)
2260 // We can't have unselected current item in a NSTableView, as the
2261 // documentation of its deselectRow method explains, the control will
2262 // automatically change the current item to the closest still selected item
2263 // if the current item is deselected. So we have no choice but to select
2264 // the item in the same time as making it current.
2268 int wxCocoaDataViewControl::GetSelections(wxDataViewItemArray& sel) const
2270 NSIndexSet* selectedRowIndexes([m_OutlineView selectedRowIndexes]);
2272 NSUInteger indexRow;
2276 sel.Alloc([selectedRowIndexes count]);
2277 indexRow = [selectedRowIndexes firstIndex];
2278 while (indexRow != NSNotFound)
2280 sel.Add(wxDataViewItem([[m_OutlineView itemAtRow:indexRow] pointer]));
2281 indexRow = [selectedRowIndexes indexGreaterThanIndex:indexRow];
2283 return sel.GetCount();
2286 bool wxCocoaDataViewControl::IsSelected(const wxDataViewItem& item) const
2288 return [m_OutlineView isRowSelected:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2291 void wxCocoaDataViewControl::Select(const wxDataViewItem& item)
2294 [m_OutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]]
2295 byExtendingSelection:GetDataViewCtrl()->HasFlag(wxDV_MULTIPLE) ? YES : NO];
2298 void wxCocoaDataViewControl::SelectAll()
2300 [m_OutlineView selectAll:m_OutlineView];
2303 void wxCocoaDataViewControl::Unselect(const wxDataViewItem& item)
2306 [m_OutlineView deselectRow:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2309 void wxCocoaDataViewControl::UnselectAll()
2311 [m_OutlineView deselectAll:m_OutlineView];
2315 // sorting related methods
2317 wxDataViewColumn* wxCocoaDataViewControl::GetSortingColumn() const
2319 NSArray* const columns = [m_OutlineView tableColumns];
2321 UInt32 const noOfColumns = [columns count];
2324 for (UInt32 i=0; i<noOfColumns; ++i)
2325 if ([[columns objectAtIndex:i] sortDescriptorPrototype] != nil)
2326 return static_cast<wxDataViewColumn*>([[[columns objectAtIndex:i] identifier] pointer]);
2330 void wxCocoaDataViewControl::Resort()
2332 [m_DataSource clearChildren];
2333 [m_OutlineView reloadData];
2336 void wxCocoaDataViewControl::StartEditor( const wxDataViewItem & item, unsigned int column )
2338 [m_OutlineView editColumn:column row:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]] withEvent:nil select:YES];
2342 // other methods (inherited from wxDataViewWidgetImpl)
2344 void wxCocoaDataViewControl::DoSetIndent(int indent)
2346 [m_OutlineView setIndentationPerLevel:static_cast<CGFloat>(indent)];
2349 void wxCocoaDataViewControl::HitTest(const wxPoint& point, wxDataViewItem& item, wxDataViewColumn*& columnPtr) const
2351 NSPoint const nativePoint = wxToNSPoint((NSScrollView*) GetWXWidget(),point);
2357 indexColumn = [m_OutlineView columnAtPoint:nativePoint];
2358 indexRow = [m_OutlineView rowAtPoint: nativePoint];
2359 if ((indexColumn >= 0) && (indexRow >= 0))
2361 columnPtr = static_cast<wxDataViewColumn*>([[[[m_OutlineView tableColumns] objectAtIndex:indexColumn] identifier] pointer]);
2362 item = wxDataViewItem([[m_OutlineView itemAtRow:indexRow] pointer]);
2367 item = wxDataViewItem();
2371 void wxCocoaDataViewControl::SetRowHeight(const wxDataViewItem& WXUNUSED(item), unsigned int WXUNUSED(height))
2372 // Not supported by the native control
2376 void wxCocoaDataViewControl::OnSize()
2378 if ([m_OutlineView numberOfColumns] == 1)
2379 [m_OutlineView sizeLastColumnToFit];
2383 // drag & drop helper methods
2385 wxDataFormat wxCocoaDataViewControl::GetDnDDataFormat(wxDataObjectComposite* dataObjects)
2387 wxDataFormat resultFormat;
2389 return resultFormat;
2391 bool compatible(true);
2393 size_t const noOfFormats = dataObjects->GetFormatCount();
2396 wxDataFormat* formats;
2398 // get all formats and check afterwards if the formats are compatible; if
2399 // they are compatible the preferred format is returned otherwise
2400 // wxDF_INVALID is returned;
2401 // currently compatible types (ordered by priority are):
2402 // - wxDF_UNICODETEXT - wxDF_TEXT
2403 formats = new wxDataFormat[noOfFormats];
2404 dataObjects->GetAllFormats(formats);
2406 while ((indexFormat < noOfFormats) && compatible)
2408 switch (resultFormat.GetType())
2411 resultFormat.SetType(formats[indexFormat].GetType()); // first format (should only be reached if indexFormat == 0)
2414 if (formats[indexFormat].GetType() == wxDF_UNICODETEXT)
2415 resultFormat.SetType(wxDF_UNICODETEXT);
2416 else // incompatible
2418 resultFormat.SetType(wxDF_INVALID);
2422 case wxDF_UNICODETEXT:
2423 if (formats[indexFormat].GetType() != wxDF_TEXT)
2425 resultFormat.SetType(wxDF_INVALID);
2430 resultFormat.SetType(wxDF_INVALID); // not (yet) supported format
2438 return resultFormat;
2441 wxDataObjectComposite* wxCocoaDataViewControl::GetDnDDataObjects(NSData* dataObject) const
2443 wxDataFormatId dataFormatID;
2446 [dataObject getBytes:&dataFormatID length:sizeof(wxDataFormatId)];
2447 switch (dataFormatID)
2450 case wxDF_UNICODETEXT:
2452 wxTextDataObject* textDataObject(new wxTextDataObject());
2454 if (textDataObject->SetData(wxDataFormat(dataFormatID),[dataObject length]-sizeof(wxDataFormatId),static_cast<char const*>([dataObject bytes])+sizeof(wxDataFormatId)))
2456 wxDataObjectComposite* dataObjectComposite(new wxDataObjectComposite());
2458 dataObjectComposite->Add(textDataObject);
2459 return dataObjectComposite;
2463 delete textDataObject;
2473 id wxCocoaDataViewControl::GetItemAtRow(int row) const
2475 return [m_OutlineView itemAtRow:row];
2478 // ----------------------------------------------------------------------------
2479 // wxDataViewRendererNativeData
2480 // ----------------------------------------------------------------------------
2482 void wxDataViewRendererNativeData::Init()
2485 m_origTextColour = NULL;
2486 m_ellipsizeMode = wxELLIPSIZE_MIDDLE;
2489 ApplyLineBreakMode(m_ColumnCell);
2492 void wxDataViewRendererNativeData::ApplyLineBreakMode(NSCell *cell)
2494 NSLineBreakMode nsMode = NSLineBreakByWordWrapping;
2495 switch ( m_ellipsizeMode )
2497 case wxELLIPSIZE_NONE:
2498 nsMode = NSLineBreakByClipping;
2501 case wxELLIPSIZE_START:
2502 nsMode = NSLineBreakByTruncatingHead;
2505 case wxELLIPSIZE_MIDDLE:
2506 nsMode = NSLineBreakByTruncatingMiddle;
2509 case wxELLIPSIZE_END:
2510 nsMode = NSLineBreakByTruncatingTail;
2514 wxASSERT_MSG( nsMode != NSLineBreakByWordWrapping, "unknown wxEllipsizeMode" );
2516 [cell setLineBreakMode: nsMode];
2519 // ---------------------------------------------------------
2520 // wxDataViewRenderer
2521 // ---------------------------------------------------------
2523 wxDataViewRenderer::wxDataViewRenderer(const wxString& varianttype,
2524 wxDataViewCellMode mode,
2526 : wxDataViewRendererBase(varianttype, mode, align),
2529 m_NativeDataPtr(NULL)
2533 wxDataViewRenderer::~wxDataViewRenderer()
2535 delete m_NativeDataPtr;
2538 void wxDataViewRenderer::SetAlignment(int align)
2540 m_alignment = align;
2541 [GetNativeData()->GetColumnCell() setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2544 void wxDataViewRenderer::SetMode(wxDataViewCellMode mode)
2548 [GetOwner()->GetNativeData()->GetNativeColumnPtr() setEditable:(mode == wxDATAVIEW_CELL_EDITABLE)];
2551 void wxDataViewRenderer::SetNativeData(wxDataViewRendererNativeData* newNativeDataPtr)
2553 delete m_NativeDataPtr;
2554 m_NativeDataPtr = newNativeDataPtr;
2557 void wxDataViewRenderer::EnableEllipsize(wxEllipsizeMode mode)
2559 // we need to store this value to apply it to the columns headerCell in
2560 // CreateNativeColumn()
2561 GetNativeData()->SetEllipsizeMode(mode);
2563 // but we may already apply it to the column cell which will be used for
2565 GetNativeData()->ApplyLineBreakMode(GetNativeData()->GetColumnCell());
2568 wxEllipsizeMode wxDataViewRenderer::GetEllipsizeMode() const
2570 return GetNativeData()->GetEllipsizeMode();
2574 wxDataViewRenderer::OSXOnCellChanged(NSObject *object,
2575 const wxDataViewItem& item,
2578 // TODO: we probably should get rid of this code entirely and make this
2579 // function pure virtual, but currently we still have some native
2580 // renderers (wxDataViewChoiceRenderer) which don't override it and
2581 // there is also wxDataViewCustomRenderer for which it's not obvious
2582 // how it should be implemented so keep this "auto-deduction" of
2583 // variant type from NSObject for now
2586 if ( [object isKindOfClass:[NSString class]] )
2587 value = ObjectToString(object);
2588 else if ( [object isKindOfClass:[NSNumber class]] )
2589 value = ObjectToLong(object);
2590 else if ( [object isKindOfClass:[NSDate class]] )
2591 value = ObjectToDate(object);
2594 wxFAIL_MSG( wxString::Format
2596 "unknown value type %s",
2597 wxCFStringRef::AsString([object className])
2602 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2603 model->ChangeValue(value, item, col);
2606 void wxDataViewRenderer::OSXApplyAttr(const wxDataViewItemAttr& attr)
2608 wxDataViewRendererNativeData * const data = GetNativeData();
2609 NSCell * const cell = data->GetItemCell();
2611 // set the font and text colour to use: we need to do it if we had ever
2612 // changed them before, even if this item itself doesn't have any special
2613 // attributes as otherwise it would reuse the attributes from the previous
2614 // cell rendered using the same renderer
2615 NSFont *font = NULL;
2616 NSColor *colText = NULL;
2618 if ( attr.HasFont() )
2620 font = data->GetOriginalFont();
2623 // this is the first time we're setting the font, remember the
2624 // original one before changing it
2626 data->SaveOriginalFont(font);
2631 // FIXME: using wxFont methods here doesn't work for some reason
2632 NSFontManager * const fm = [NSFontManager sharedFontManager];
2633 if ( attr.GetBold() )
2634 font = [fm convertFont:font toHaveTrait:NSBoldFontMask];
2635 if ( attr.GetItalic() )
2636 font = [fm convertFont:font toHaveTrait:NSItalicFontMask];
2638 //else: can't change font if the cell doesn't have any
2641 if ( attr.HasColour() )
2643 // we can set font for any cell but only NSTextFieldCell provides
2644 // a method for setting text colour so check that this method is
2645 // available before using it
2646 if ( [cell respondsToSelector:@selector(setTextColor:)] &&
2647 [cell respondsToSelector:@selector(textColor)] )
2649 if ( !data->GetOriginalTextColour() )
2651 // the cast to (untyped) id is safe because of the check above
2652 data->SaveOriginalTextColour([(id)cell textColor]);
2655 const wxColour& c = attr.GetColour();
2656 colText = [NSColor colorWithDeviceRed:c.Red() / 255.
2657 green:c.Green() / 255.
2658 blue:c.Blue() / 255.
2659 alpha:c.Alpha() / 255.];
2664 font = data->GetOriginalFont();
2666 colText = data->GetOriginalTextColour();
2669 [cell setFont:font];
2672 [(id)cell setTextColor:colText];
2675 void wxDataViewRenderer::OSXApplyEnabled(bool enabled)
2677 [GetNativeData()->GetItemCell() setEnabled:enabled];
2680 IMPLEMENT_ABSTRACT_CLASS(wxDataViewRenderer,wxDataViewRendererBase)
2682 // ---------------------------------------------------------
2683 // wxDataViewCustomRenderer
2684 // ---------------------------------------------------------
2685 wxDataViewCustomRenderer::wxDataViewCustomRenderer(const wxString& varianttype,
2686 wxDataViewCellMode mode,
2688 : wxDataViewCustomRendererBase(varianttype, mode, align),
2689 m_editorCtrlPtr(NULL),
2692 SetNativeData(new wxDataViewRendererNativeData([[wxCustomCell alloc] init]));
2695 bool wxDataViewCustomRenderer::MacRender()
2697 [GetNativeData()->GetItemCell() setObjectValue:[[[wxCustomRendererObject alloc] initWithRenderer:this] autorelease]];
2701 void wxDataViewCustomRenderer::OSXApplyAttr(const wxDataViewItemAttr& attr)
2703 // simply save the attribute so that it could be reused from our Render()
2706 // it's not necessary to call the base class version which sets the cell
2707 // properties to correspond to this attribute because we currently don't
2708 // use any NSCell methods in custom renderers anyhow but if we ever start
2709 // doing this (e.g. override RenderText() here to use NSTextFieldCell
2710 // methods), then we should pass it on to wxDataViewRenderer here
2713 IMPLEMENT_ABSTRACT_CLASS(wxDataViewCustomRenderer, wxDataViewRenderer)
2715 // ---------------------------------------------------------
2716 // wxDataViewTextRenderer
2717 // ---------------------------------------------------------
2718 wxDataViewTextRenderer::wxDataViewTextRenderer(const wxString& varianttype,
2719 wxDataViewCellMode mode,
2721 : wxDataViewRenderer(varianttype,mode,align)
2723 NSTextFieldCell* cell;
2726 cell = [[NSTextFieldCell alloc] init];
2727 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2728 SetNativeData(new wxDataViewRendererNativeData(cell));
2732 bool wxDataViewTextRenderer::MacRender()
2734 if (GetValue().GetType() == GetVariantType())
2736 [GetNativeData()->GetItemCell() setObjectValue:wxCFStringRef(GetValue().GetString()).AsNSString()];
2741 wxFAIL_MSG(wxString("Text renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2747 wxDataViewTextRenderer::OSXOnCellChanged(NSObject *value,
2748 const wxDataViewItem& item,
2751 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2752 model->ChangeValue(ObjectToString(value), item, col);
2755 IMPLEMENT_CLASS(wxDataViewTextRenderer,wxDataViewRenderer)
2757 // ---------------------------------------------------------
2758 // wxDataViewBitmapRenderer
2759 // ---------------------------------------------------------
2760 wxDataViewBitmapRenderer::wxDataViewBitmapRenderer(const wxString& varianttype,
2761 wxDataViewCellMode mode,
2763 : wxDataViewRenderer(varianttype,mode,align)
2768 cell = [[NSImageCell alloc] init];
2769 SetNativeData(new wxDataViewRendererNativeData(cell));
2773 // This method returns 'true' if
2774 // - the passed bitmap is valid and it could be assigned to the native data
2776 // - the passed bitmap is invalid (or is not initialized); this case
2777 // simulates a non-existing bitmap.
2778 // In all other cases the method returns 'false'.
2779 bool wxDataViewBitmapRenderer::MacRender()
2781 wxCHECK_MSG(GetValue().GetType() == GetVariantType(),false,wxString("Bitmap renderer cannot render value; value type: ") << GetValue().GetType());
2785 bitmap << GetValue();
2787 [GetNativeData()->GetItemCell() setObjectValue:[[bitmap.GetNSImage() retain] autorelease]];
2791 IMPLEMENT_CLASS(wxDataViewBitmapRenderer,wxDataViewRenderer)
2793 // -------------------------------------
2794 // wxDataViewChoiceRenderer
2795 // -------------------------------------
2796 wxDataViewChoiceRenderer::wxDataViewChoiceRenderer(const wxArrayString& choices,
2797 wxDataViewCellMode mode,
2799 : wxDataViewRenderer(wxT("string"), mode, alignment),
2802 NSPopUpButtonCell* cell;
2805 cell = [[NSPopUpButtonCell alloc] init];
2806 [cell setControlSize:NSMiniControlSize];
2807 [cell setFont:[NSFont fontWithName:[[cell font] fontName] size:[NSFont systemFontSizeForControlSize:NSMiniControlSize]]];
2808 for (size_t i=0; i<choices.GetCount(); ++i)
2809 [cell addItemWithTitle:wxCFStringRef(choices[i]).AsNSString()];
2810 SetNativeData(new wxDataViewRendererNativeData(cell));
2814 bool wxDataViewChoiceRenderer::MacRender()
2816 if (GetValue().GetType() == GetVariantType())
2818 [((NSPopUpButtonCell*) GetNativeData()->GetItemCell()) selectItemWithTitle:[[wxCFStringRef(GetValue().GetString()).AsNSString() retain] autorelease]];
2823 wxFAIL_MSG(wxString("Choice renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2828 IMPLEMENT_CLASS(wxDataViewChoiceRenderer,wxDataViewRenderer)
2830 // ---------------------------------------------------------
2831 // wxDataViewDateRenderer
2832 // ---------------------------------------------------------
2834 wxDataViewDateRenderer::wxDataViewDateRenderer(const wxString& varianttype,
2835 wxDataViewCellMode mode,
2837 : wxDataViewRenderer(varianttype,mode,align)
2839 NSTextFieldCell* cell;
2841 NSDateFormatter* dateFormatter;
2844 dateFormatter = [[NSDateFormatter alloc] init];
2845 [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
2846 [dateFormatter setDateStyle:NSDateFormatterShortStyle];
2847 cell = [[NSTextFieldCell alloc] init];
2848 [cell setFormatter:dateFormatter];
2849 SetNativeData(new wxDataViewRendererNativeData(cell,[NSDate dateWithString:@"2000-12-30 20:00:00 +0000"]));
2851 [dateFormatter release];
2854 bool wxDataViewDateRenderer::MacRender()
2856 if (GetValue().GetType() == GetVariantType())
2858 if (GetValue().GetDateTime().IsValid())
2860 // -- find best fitting style to show the date --
2861 // as the style should be identical for all cells a reference date
2862 // instead of the actual cell's date value is used for all cells;
2863 // this reference date is stored in the renderer's native data
2864 // section for speed purposes; otherwise, the reference date's
2865 // string has to be recalculated for each item that may become
2866 // timewise long if a lot of rows using dates exist; the algorithm
2867 // has the preference to display as much information as possible
2868 // in the first instance; but as this is often impossible due to
2869 // space restrictions the style is shortened per loop; finally, if
2870 // the shortest time and date format does not fit into the cell
2871 // the time part is dropped; remark: the time part itself is not
2872 // modified per iteration loop and only uses the short style,
2873 // means that only the hours and minutes are being shown
2875 // GetObject() returns a date for testing the size of a date object
2876 [GetNativeData()->GetItemCell() setObjectValue:GetNativeData()->GetObject()];
2877 [[GetNativeData()->GetItemCell() formatter] setTimeStyle:NSDateFormatterShortStyle];
2878 for (int dateFormatterStyle=4; dateFormatterStyle>0; --dateFormatterStyle)
2880 [[GetNativeData()->GetItemCell() formatter] setDateStyle:(NSDateFormatterStyle)dateFormatterStyle];
2881 if (dateFormatterStyle == 1)
2883 // if the shortest style for displaying the date and time
2884 // is too long to be fully visible remove the time part of
2886 if ([GetNativeData()->GetItemCell() cellSize].width > [GetNativeData()->GetColumnPtr() width])
2887 [[GetNativeData()->GetItemCell() formatter] setTimeStyle:NSDateFormatterNoStyle];
2889 // basically not necessary as the loop would end anyway
2890 // but let's save the last comparison
2894 else if ([GetNativeData()->GetItemCell() cellSize].width <= [GetNativeData()->GetColumnPtr() width])
2897 // set data (the style is set by the previous loop); on OSX the
2898 // date has to be specified with respect to UTC; in wxWidgets the
2899 // date is always entered in the local timezone; so, we have to do
2900 // a conversion from the local to UTC timezone when adding the
2901 // seconds to 1970-01-01 UTC:
2902 [GetNativeData()->GetItemCell() setObjectValue:[NSDate dateWithTimeIntervalSince1970:GetValue().GetDateTime().ToUTC().Subtract(wxDateTime(1,wxDateTime::Jan,1970)).GetSeconds().ToDouble()]];
2908 wxFAIL_MSG(wxString("Date renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2914 wxDataViewDateRenderer::OSXOnCellChanged(NSObject *value,
2915 const wxDataViewItem& item,
2918 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2919 model->ChangeValue(ObjectToDate(value), item, col);
2922 IMPLEMENT_ABSTRACT_CLASS(wxDataViewDateRenderer,wxDataViewRenderer)
2924 // ---------------------------------------------------------
2925 // wxDataViewIconTextRenderer
2926 // ---------------------------------------------------------
2927 wxDataViewIconTextRenderer::wxDataViewIconTextRenderer(const wxString& varianttype,
2928 wxDataViewCellMode mode,
2930 : wxDataViewRenderer(varianttype,mode)
2932 wxImageTextCell* cell;
2935 cell = [[wxImageTextCell alloc] init];
2936 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2937 SetNativeData(new wxDataViewRendererNativeData(cell));
2941 bool wxDataViewIconTextRenderer::MacRender()
2943 if (GetValue().GetType() == GetVariantType())
2945 wxDataViewIconText iconText;
2947 wxImageTextCell* cell;
2949 cell = (wxImageTextCell*) GetNativeData()->GetItemCell();
2950 iconText << GetValue();
2951 if (iconText.GetIcon().IsOk())
2952 [cell setImage:[[wxBitmap(iconText.GetIcon()).GetNSImage() retain] autorelease]];
2953 [cell setStringValue:[[wxCFStringRef(iconText.GetText()).AsNSString() retain] autorelease]];
2958 wxFAIL_MSG(wxString("Icon & text renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2964 wxDataViewIconTextRenderer::OSXOnCellChanged(NSObject *value,
2965 const wxDataViewItem& item,
2968 wxVariant valueIconText;
2969 valueIconText << wxDataViewIconText(ObjectToString(value));
2971 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2972 model->ChangeValue(valueIconText, item, col);
2975 IMPLEMENT_ABSTRACT_CLASS(wxDataViewIconTextRenderer,wxDataViewRenderer)
2977 // ---------------------------------------------------------
2978 // wxDataViewToggleRenderer
2979 // ---------------------------------------------------------
2980 wxDataViewToggleRenderer::wxDataViewToggleRenderer(const wxString& varianttype,
2981 wxDataViewCellMode mode,
2983 : wxDataViewRenderer(varianttype,mode)
2988 cell = [[NSButtonCell alloc] init];
2989 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2990 [cell setButtonType:NSSwitchButton];
2991 [cell setImagePosition:NSImageOnly];
2992 SetNativeData(new wxDataViewRendererNativeData(cell));
2996 bool wxDataViewToggleRenderer::MacRender()
2998 if (GetValue().GetType() == GetVariantType())
3000 [GetNativeData()->GetItemCell() setIntValue:GetValue().GetLong()];
3005 wxFAIL_MSG(wxString("Toggle renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
3011 wxDataViewToggleRenderer::OSXOnCellChanged(NSObject *value,
3012 const wxDataViewItem& item,
3015 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
3016 model->ChangeValue(ObjectToBool(value), item, col);
3019 IMPLEMENT_ABSTRACT_CLASS(wxDataViewToggleRenderer,wxDataViewRenderer)
3021 // ---------------------------------------------------------
3022 // wxDataViewProgressRenderer
3023 // ---------------------------------------------------------
3024 wxDataViewProgressRenderer::wxDataViewProgressRenderer(const wxString& label,
3025 const wxString& varianttype,
3026 wxDataViewCellMode mode,
3028 : wxDataViewRenderer(varianttype,mode,align)
3032 NSLevelIndicatorCell* cell;
3034 cell = [[NSLevelIndicatorCell alloc] initWithLevelIndicatorStyle:NSContinuousCapacityLevelIndicatorStyle];
3035 [cell setMinValue:0];
3036 [cell setMaxValue:100];
3037 SetNativeData(new wxDataViewRendererNativeData(cell));
3041 bool wxDataViewProgressRenderer::MacRender()
3043 if (GetValue().GetType() == GetVariantType())
3045 [GetNativeData()->GetItemCell() setIntValue:GetValue().GetLong()];
3050 wxFAIL_MSG(wxString("Progress renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
3056 wxDataViewProgressRenderer::OSXOnCellChanged(NSObject *value,
3057 const wxDataViewItem& item,
3060 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
3061 model->ChangeValue(ObjectToLong(value), item, col);
3064 IMPLEMENT_ABSTRACT_CLASS(wxDataViewProgressRenderer,wxDataViewRenderer)
3066 // ---------------------------------------------------------
3068 // ---------------------------------------------------------
3070 wxDataViewColumn::wxDataViewColumn(const wxString& title,
3071 wxDataViewRenderer* renderer,
3072 unsigned int model_column,
3076 : wxDataViewColumnBase(renderer, model_column),
3077 m_NativeDataPtr(new wxDataViewColumnNativeData()),
3080 InitCommon(width, align, flags);
3081 if (renderer && !renderer->IsCustomRenderer() &&
3082 (renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
3083 renderer->SetAlignment(align);
3086 wxDataViewColumn::wxDataViewColumn(const wxBitmap& bitmap,
3087 wxDataViewRenderer* renderer,
3088 unsigned int model_column,
3092 : wxDataViewColumnBase(bitmap, renderer, model_column),
3093 m_NativeDataPtr(new wxDataViewColumnNativeData())
3095 InitCommon(width, align, flags);
3096 if (renderer && !renderer->IsCustomRenderer() &&
3097 (renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
3098 renderer->SetAlignment(align);
3101 wxDataViewColumn::~wxDataViewColumn()
3103 delete m_NativeDataPtr;
3106 int wxDataViewColumn::GetWidth() const
3108 return [m_NativeDataPtr->GetNativeColumnPtr() width];
3111 bool wxDataViewColumn::IsSortKey() const
3113 NSTableColumn *nsCol = GetNativeData()->GetNativeColumnPtr();
3114 return nsCol && ([nsCol sortDescriptorPrototype] != nil);
3117 void wxDataViewColumn::SetAlignment(wxAlignment align)
3119 m_alignment = align;
3120 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
3121 if (m_renderer && !m_renderer->IsCustomRenderer() &&
3122 (m_renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
3123 m_renderer->SetAlignment(align);
3126 void wxDataViewColumn::SetBitmap(const wxBitmap& bitmap)
3128 // bitmaps and titles cannot exist at the same time - if the bitmap is set
3129 // the title is removed:
3130 m_title = wxEmptyString;
3131 wxDataViewColumnBase::SetBitmap(bitmap);
3132 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setImage:[[bitmap.GetNSImage() retain] autorelease]];
3135 void wxDataViewColumn::SetMaxWidth(int maxWidth)
3137 m_maxWidth = maxWidth;
3138 [m_NativeDataPtr->GetNativeColumnPtr() setMaxWidth:maxWidth];
3141 void wxDataViewColumn::SetMinWidth(int minWidth)
3143 m_minWidth = minWidth;
3144 [m_NativeDataPtr->GetNativeColumnPtr() setMinWidth:minWidth];
3147 void wxDataViewColumn::SetReorderable(bool reorderable)
3149 wxUnusedVar(reorderable);
3152 void wxDataViewColumn::SetHidden(bool hidden)
3154 // How to set flag here?
3156 [m_NativeDataPtr->GetNativeColumnPtr() setHidden:hidden];
3159 bool wxDataViewColumn::IsHidden() const
3161 return [m_NativeDataPtr->GetNativeColumnPtr() isHidden];
3164 void wxDataViewColumn::SetResizeable(bool resizable)
3166 wxDataViewColumnBase::SetResizeable(resizable);
3168 [m_NativeDataPtr->GetNativeColumnPtr() setResizingMask:NSTableColumnUserResizingMask];
3170 [m_NativeDataPtr->GetNativeColumnPtr() setResizingMask:NSTableColumnNoResizing];
3173 void wxDataViewColumn::SetSortable(bool sortable)
3175 // wxDataViewColumnBase::SetSortable(sortable);
3176 // Avoid endless recursion and just set the flag here
3178 m_flags |= wxDATAVIEW_COL_SORTABLE;
3180 m_flags &= ~wxDATAVIEW_COL_SORTABLE;
3183 void wxDataViewColumn::SetSortOrder(bool ascending)
3185 if (m_ascending != ascending)
3187 m_ascending = ascending;
3190 // change sorting order:
3191 NSArray* sortDescriptors;
3192 NSSortDescriptor* sortDescriptor;
3193 NSTableColumn* tableColumn;
3195 tableColumn = m_NativeDataPtr->GetNativeColumnPtr();
3196 sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[[tableColumn sortDescriptorPrototype] key] ascending:m_ascending];
3197 sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
3198 [tableColumn setSortDescriptorPrototype:sortDescriptor];
3199 [[tableColumn tableView] setSortDescriptors:sortDescriptors];
3200 [sortDescriptor release];
3205 void wxDataViewColumn::SetTitle(const wxString& title)
3207 // bitmaps and titles cannot exist at the same time - if the title is set
3208 // the bitmap is removed:
3209 wxDataViewColumnBase::SetBitmap(wxBitmap());
3211 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setStringValue:[[wxCFStringRef(title).AsNSString() retain] autorelease]];
3214 void wxDataViewColumn::SetWidth(int width)
3220 case wxCOL_WIDTH_AUTOSIZE:
3221 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
3224 wxCocoaDataViewControl *peer = static_cast<wxCocoaDataViewControl*>(GetOwner()->GetPeer());
3225 peer->FitColumnWidthToContent(GetOwner()->GetColumnPosition(this));
3229 // fall through if unsupported (OSX < 10.5) or not yet settable
3231 case wxCOL_WIDTH_DEFAULT:
3232 width = wxDVC_DEFAULT_WIDTH;
3236 [m_NativeDataPtr->GetNativeColumnPtr() setWidth:width];
3241 void wxDataViewColumn::SetAsSortKey(bool WXUNUSED(sort))
3243 // see wxGTK native wxDataViewColumn implementation
3244 wxFAIL_MSG("not implemented");
3247 void wxDataViewColumn::SetNativeData(wxDataViewColumnNativeData* newNativeDataPtr)
3249 delete m_NativeDataPtr;
3250 m_NativeDataPtr = newNativeDataPtr;
3253 #endif // (wxUSE_DATAVIEWCTRL == 1) && !defined(wxUSE_GENERICDATAVIEWCTRL)