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"
29 // ============================================================================
30 // Constants used locally
31 // ============================================================================
33 #define DataViewPboardType @"OutlineViewItem"
35 // ============================================================================
36 // Classes used locally in dataview.mm
37 // ============================================================================
39 // ============================================================================
41 // ============================================================================
43 @implementation wxPointerObject
53 -(id) initWithPointer:(void*) initPointer
57 self->pointer = initPointer;
62 // inherited methods from NSObject
64 -(BOOL) isEqual:(id)object
66 return (object != nil) &&
67 ([object isKindOfClass:[wxPointerObject class]]) &&
68 (pointer == [((wxPointerObject*) object) pointer]);
73 return (NSUInteger) pointer;
81 -(void) setPointer:(void*) newPointer
91 inline wxDataViewItem wxDataViewItemFromItem(id item)
93 return wxDataViewItem([static_cast<wxPointerObject *>(item) pointer]);
96 inline wxDataViewItem wxDataViewItemFromMaybeNilItem(id item)
98 return item == nil ? wxDataViewItem() : wxDataViewItemFromItem(item);
101 } // anonymous namespace
103 // ----------------------------------------------------------------------------
104 // wxCustomRendererObject
105 // ----------------------------------------------------------------------------
107 @interface wxCustomRendererObject : NSObject <NSCopying>
110 wxDataViewCustomRenderer* customRenderer; // not owned by the class
114 -(id) initWithRenderer:(wxDataViewCustomRenderer*)renderer;
117 @implementation wxCustomRendererObject
124 customRenderer = NULL;
129 -(id) initWithRenderer:(wxDataViewCustomRenderer*)renderer
134 customRenderer = renderer;
139 -(id) copyWithZone:(NSZone*)zone
141 wxCustomRendererObject* copy;
143 copy = [[[self class] allocWithZone:zone] init];
144 copy->customRenderer = customRenderer;
150 // ----------------------------------------------------------------------------
151 // wxDVCNSTableColumn: exists only to override NSTableColumn:dataCellForRow:
152 // ----------------------------------------------------------------------------
154 @interface wxDVCNSTableColumn : NSTableColumn
158 -(id) dataCellForRow:(NSInteger)row;
161 @implementation wxDVCNSTableColumn
163 -(id) dataCellForRow:(NSInteger)row
165 // what we want to do here is to simply return nil for the cells which
166 // shouldn't show anything as otherwise we would show e.g. empty combo box
167 // or progress cells in the columns using the corresponding types even for
168 // the container rows which is wrong
170 // half of the problem is just finding the objects we need from the column
171 // pointer which is itself stashed inside wxPointerObject which we use as
173 const wxDataViewColumn * const
174 dvCol = static_cast<wxDataViewColumn *>(
175 [(wxPointerObject *)[self identifier] pointer]
178 const wxDataViewCtrl * const dvc = dvCol->GetOwner();
179 const wxCocoaDataViewControl * const
180 peer = static_cast<wxCocoaDataViewControl *>(dvc->GetPeer());
183 // once we do have everything, simply ask NSOutlineView for the item...
184 const id item = peer->GetItemAtRow(row);
187 // ... and if it succeeded, ask the model whether it has any value
188 wxDataViewItem dvItem(wxDataViewItemFromItem(item));
190 if ( !dvc->GetModel()->HasValue(dvItem, dvCol->GetModelColumn()) )
194 return [super dataCellForRow:row];
199 // ============================================================================
201 // ============================================================================
206 // convert from NSObject to different C++ types: all these functions check
207 // that the conversion really makes sense and assert if it doesn't
208 wxString ObjectToString(NSObject *object)
210 wxCHECK_MSG( [object isKindOfClass:[NSString class]], "",
213 "string expected but got %s",
214 wxCFStringRef::AsString([object className])
217 return wxCFStringRef([((NSString*) object) retain]).AsString();
220 bool ObjectToBool(NSObject *object)
222 // actually the value must be of NSCFBoolean class but it's private so we
223 // can't check for it directly
224 wxCHECK_MSG( [object isKindOfClass:[NSNumber class]], false,
227 "number expected but got %s",
228 wxCFStringRef::AsString([object className])
231 return [(NSNumber *)object boolValue];
234 long ObjectToLong(NSObject *object)
236 wxCHECK_MSG( [object isKindOfClass:[NSNumber class]], -1,
239 "number expected but got %s",
240 wxCFStringRef::AsString([object className])
243 return [(NSNumber *)object longValue];
246 wxDateTime ObjectToDate(NSObject *object)
248 wxCHECK_MSG( [object isKindOfClass:[NSDate class]], wxInvalidDateTime,
251 "date expected but got %s",
252 wxCFStringRef::AsString([object className])
255 // get the number of seconds since 1970-01-01 UTC and this is the only
256 // way to convert a double to a wxLongLong
257 const wxLongLong seconds = [((NSDate*) object) timeIntervalSince1970];
259 wxDateTime dt(1, wxDateTime::Jan, 1970);
260 dt.Add(wxTimeSpan(0,0,seconds));
262 // the user has entered a date in the local timezone but seconds
263 // contains the number of seconds from date in the local timezone
264 // since 1970-01-01 UTC; therefore, the timezone information has to be
265 // transferred to wxWidgets, too:
266 dt.MakeFromTimezone(wxDateTime::UTC);
271 NSInteger CompareItems(id item1, id item2, void* context)
273 NSArray* const sortDescriptors = (NSArray*) context;
275 NSUInteger const count = [sortDescriptors count];
277 NSInteger result = NSOrderedSame;
278 for ( NSUInteger i = 0; i < count && result == NSOrderedSame; ++i )
280 wxSortDescriptorObject* const
281 sortDescriptor = (wxSortDescriptorObject*)
282 [sortDescriptors objectAtIndex:i];
284 int rc = [sortDescriptor modelPtr]->Compare
286 wxDataViewItemFromItem(item1),
287 wxDataViewItemFromItem(item2),
288 [sortDescriptor columnPtr]->GetModelColumn(),
289 [sortDescriptor ascending] == YES
293 result = NSOrderedAscending;
295 result = NSOrderedDescending;
301 NSTextAlignment ConvertToNativeHorizontalTextAlignment(int alignment)
303 if (alignment & wxALIGN_CENTER_HORIZONTAL)
304 return NSCenterTextAlignment;
305 else if (alignment & wxALIGN_RIGHT)
306 return NSRightTextAlignment;
308 return NSLeftTextAlignment;
311 NSTableColumn* CreateNativeColumn(const wxDataViewColumn *column)
313 wxDataViewRenderer * const renderer = column->GetRenderer();
315 wxCHECK_MSG( renderer, NULL, "column should have a renderer" );
317 wxDVCNSTableColumn * const nativeColumn(
318 [[wxDVCNSTableColumn alloc] initWithIdentifier:
319 [[[wxPointerObject alloc] initWithPointer:
320 const_cast<wxDataViewColumn*>(column)]
324 // setting the size related parameters:
326 if (column->IsResizeable())
328 resizingMask = NSTableColumnUserResizingMask;
329 [nativeColumn setMinWidth:column->GetMinWidth()];
330 [nativeColumn setMaxWidth:column->GetMaxWidth()];
332 else // column is not resizeable [by user]
334 // if the control doesn't show a header, make the columns resize
335 // automatically, this is particularly important for the single column
336 // controls (such as wxDataViewTreeCtrl) as their unique column should
337 // always take up all the available splace
338 resizingMask = column->GetOwner()->HasFlag(wxDV_NO_HEADER)
339 ? NSTableColumnAutoresizingMask
340 : NSTableColumnNoResizing;
342 [nativeColumn setResizingMask:resizingMask];
344 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
345 // setting the visibility:
346 [nativeColumn setHidden:static_cast<BOOL>(column->IsHidden())];
349 wxDataViewRendererNativeData * const renderData = renderer->GetNativeData();
351 // setting the header:
352 [[nativeColumn headerCell] setAlignment:
353 ConvertToNativeHorizontalTextAlignment(column->GetAlignment())];
354 [[nativeColumn headerCell] setStringValue:
355 [[wxCFStringRef(column->GetTitle()).AsNSString() retain] autorelease]];
356 renderData->ApplyLineBreakMode([nativeColumn headerCell]);
358 // setting data cell's properties:
359 [[nativeColumn dataCell] setWraps:NO];
360 // setting the default data cell:
361 [nativeColumn setDataCell:renderData->GetColumnCell()];
362 // setting the editablility:
363 const bool isEditable = renderer->GetMode() == wxDATAVIEW_CELL_EDITABLE;
365 [nativeColumn setEditable:isEditable];
366 [[nativeColumn dataCell] setEditable:isEditable];
371 } // anonymous namespace
373 // ============================================================================
374 // Public helper functions for dataview implementation on OSX
375 // ============================================================================
377 wxWidgetImplType* CreateDataView(wxWindowMac* wxpeer,
378 wxWindowMac* WXUNUSED(parent),
379 wxWindowID WXUNUSED(id),
383 long WXUNUSED(extraStyle))
385 return new wxCocoaDataViewControl(wxpeer,pos,size,style);
388 // ============================================================================
389 // wxSortDescriptorObject
390 // ============================================================================
392 @implementation wxSortDescriptorObject
405 initWithModelPtr:(wxDataViewModel*)initModelPtr
406 sortingColumnPtr:(wxDataViewColumn*)initColumnPtr
407 ascending:(BOOL)sortAscending
409 self = [super initWithKey:@"dummy" ascending:sortAscending];
412 columnPtr = initColumnPtr;
413 modelPtr = initModelPtr;
418 -(id) copyWithZone:(NSZone*)zone
420 wxSortDescriptorObject* copy;
423 copy = [super copyWithZone:zone];
424 copy->columnPtr = columnPtr;
425 copy->modelPtr = modelPtr;
431 // access to model column's index
433 -(wxDataViewColumn*) columnPtr
438 -(wxDataViewModel*) modelPtr
443 -(void) setColumnPtr:(wxDataViewColumn*)newColumnPtr
445 columnPtr = newColumnPtr;
448 -(void) setModelPtr:(wxDataViewModel*)newModelPtr
450 modelPtr = newModelPtr;
455 // ============================================================================
456 // wxCocoaOutlineDataSource
457 // ============================================================================
458 @implementation wxCocoaOutlineDataSource
461 // constructors / destructor
468 implementation = NULL;
471 currentParentItem = nil;
473 children = [[NSMutableArray alloc] init];
474 items = [[NSMutableSet alloc] init];
481 [currentParentItem release];
490 // methods of informal protocol:
493 outlineView:(NSOutlineView*)outlineView
494 acceptDrop:(id<NSDraggingInfo>)info
495 item:(id)item childIndex:(NSInteger)index
497 wxUnusedVar(outlineView);
500 NSArray* supportedTypes(
501 [NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]
504 NSPasteboard* pasteboard([info draggingPasteboard]);
506 NSString* bestType([pasteboard availableTypeFromArray:supportedTypes]);
508 if ( bestType == nil )
511 wxDataViewCtrl * const dvc(implementation->GetDataViewCtrl());
513 wxCHECK_MSG( dvc, false,
514 "Pointer to data view control not set correctly." );
515 wxCHECK_MSG( dvc->GetModel(), false,
516 "Pointer to model not set correctly." );
518 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_DROP, dvc->GetId());
519 event.SetEventObject(dvc);
520 event.SetItem(wxDataViewItemFromItem(item));
521 event.SetModel(dvc->GetModel());
524 if ( [bestType compare:DataViewPboardType] == NSOrderedSame )
526 NSArray* dataArray((NSArray*)
527 [pasteboard propertyListForType:DataViewPboardType]);
528 NSUInteger indexDraggedItem, noOfDraggedItems([dataArray count]);
530 indexDraggedItem = 0;
531 while (indexDraggedItem < noOfDraggedItems)
533 wxDataObjectComposite* dataObjects(
534 implementation->GetDnDDataObjects((NSData*)
535 [dataArray objectAtIndex:indexDraggedItem]));
537 if (dataObjects && (dataObjects->GetFormatCount() > 0))
539 wxMemoryBuffer buffer;
541 // copy data into data object:
542 event.SetDataObject(dataObjects);
544 implementation->GetDnDDataFormat(dataObjects));
545 // copy data into buffer:
546 dataObjects->GetDataHere(
547 event.GetDataFormat().GetType(),
548 buffer.GetWriteBuf(event.GetDataSize()));
549 buffer.UngetWriteBuf(event.GetDataSize());
550 event.SetDataBuffer(buffer.GetData());
551 // finally, send event:
552 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
554 dragSuccessful = true;
559 dragSuccessful = true;
560 indexDraggedItem = noOfDraggedItems; // stop loop
565 dragSuccessful = false;
566 indexDraggedItem = noOfDraggedItems; // stop loop
574 // needed to convert internally used UTF-16 representation to a UTF-8
577 wxDataObjectComposite* dataObjects (new wxDataObjectComposite());
578 wxTextDataObject* textDataObject(new wxTextDataObject());
580 osxData = ::CFStringCreateExternalRepresentation
583 (CFStringRef)[pasteboard stringForType:NSStringPboardType],
584 kCFStringEncodingUTF8,
587 if (textDataObject->SetData(::CFDataGetLength(osxData),
588 ::CFDataGetBytePtr(osxData)))
589 dataObjects->Add(textDataObject);
591 delete textDataObject;
592 // send event if data could be copied:
593 if (dataObjects->GetFormatCount() > 0)
595 event.SetDataObject(dataObjects);
596 event.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
597 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
598 dragSuccessful = true;
600 dragSuccessful = false;
603 dragSuccessful = false;
605 ::CFRelease(osxData);
608 return dragSuccessful;
611 -(id) outlineView:(NSOutlineView*)outlineView
612 child:(NSInteger)index
615 wxUnusedVar(outlineView);
617 if ((item == currentParentItem) &&
618 (index < ((NSInteger) [self getChildCount])))
619 return [self getChild:index];
621 wxDataViewItemArray dataViewChildren;
623 wxCHECK_MSG( model, 0, "Valid model in data source does not exist." );
624 model->GetChildren(wxDataViewItemFromMaybeNilItem(item), dataViewChildren);
625 [self bufferItem:item withChildren:&dataViewChildren];
626 if ([sortDescriptors count] > 0)
627 [children sortUsingFunction:CompareItems context:sortDescriptors];
628 return [self getChild:index];
631 -(BOOL) outlineView:(NSOutlineView*)outlineView isItemExpandable:(id)item
633 wxUnusedVar(outlineView);
635 wxCHECK_MSG( model, 0, "Valid model in data source does not exist." );
636 return model->IsContainer(wxDataViewItemFromItem(item));
639 -(NSInteger) outlineView:(NSOutlineView*)outlineView numberOfChildrenOfItem:(id)item
641 wxUnusedVar(outlineView);
643 NSInteger noOfChildren;
645 wxDataViewItemArray dataViewChildren;
648 wxCHECK_MSG( model, 0, "Valid model in data source does not exist." );
649 noOfChildren = model->GetChildren(wxDataViewItemFromMaybeNilItem(item),
651 [self bufferItem:item withChildren:&dataViewChildren];
652 if ([sortDescriptors count] > 0)
653 [children sortUsingFunction:CompareItems context:sortDescriptors];
658 outlineView:(NSOutlineView*)outlineView
659 objectValueForTableColumn:(NSTableColumn*)tableColumn
662 wxUnusedVar(outlineView);
664 wxCHECK_MSG( model, nil, "Valid model in data source does not exist." );
666 wxDataViewColumn* col(static_cast<wxDataViewColumn*>([[tableColumn identifier] pointer]));
667 const unsigned colIdx = col->GetModelColumn();
669 wxDataViewItem dataViewItem(wxDataViewItemFromItem(item));
671 if ( model->HasValue(dataViewItem, colIdx) )
674 model->GetValue(value,dataViewItem, colIdx);
675 col->GetRenderer()->SetValue(value);
682 outlineView:(NSOutlineView*)outlineView
683 setObjectValue:(id)object
684 forTableColumn:(NSTableColumn*)tableColumn
687 wxUnusedVar(outlineView);
689 wxDataViewColumn* col(static_cast<wxDataViewColumn*>([[tableColumn identifier] pointer]));
692 OSXOnCellChanged(object, wxDataViewItemFromItem(item), col->GetModelColumn());
695 -(void) outlineView:(NSOutlineView*)outlineView sortDescriptorsDidChange:(NSArray*)oldDescriptors
697 wxUnusedVar(oldDescriptors);
699 // Warning: the new sort descriptors are guaranteed to be only of type
700 // NSSortDescriptor! Therefore, the sort descriptors for the data source
701 // have to be converted.
702 NSArray* newDescriptors;
704 NSMutableArray* wxSortDescriptors;
706 NSUInteger noOfDescriptors;
708 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
711 // convert NSSortDescriptors to wxSortDescriptorObjects:
712 newDescriptors = [outlineView sortDescriptors];
713 noOfDescriptors = [newDescriptors count];
714 wxSortDescriptors = [NSMutableArray arrayWithCapacity:noOfDescriptors];
715 for (NSUInteger i=0; i<noOfDescriptors; ++i)
717 NSSortDescriptor* const newDescriptor = [newDescriptors objectAtIndex:i];
719 [wxSortDescriptors addObject:[[[wxSortDescriptorObject alloc] initWithModelPtr:model
720 sortingColumnPtr:dvc->GetColumn([[newDescriptor key] intValue])
721 ascending:[newDescriptor ascending]] autorelease]];
723 [(wxCocoaOutlineDataSource*)[outlineView dataSource] setSortDescriptors:wxSortDescriptors];
725 // send first the event to wxWidgets that the sorting has changed so that
726 // the program can do special actions before the sorting actually starts:
727 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_COLUMN_SORTED,dvc->GetId()); // variable defintion
729 event.SetEventObject(dvc);
730 if (noOfDescriptors > 0)
732 wxDataViewColumn* const col = [[wxSortDescriptors objectAtIndex:0] columnPtr];
734 event.SetColumn(dvc->GetColumnPosition(col));
735 event.SetDataViewColumn(col);
737 dvc->GetEventHandler()->ProcessEvent(event);
739 // start re-ordering the data;
740 // children's buffer must be cleared first because it contains the old order:
741 [self clearChildren];
742 // sorting is done while reloading the data:
743 [outlineView reloadData];
746 -(NSDragOperation) outlineView:(NSOutlineView*)outlineView validateDrop:(id<NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
748 wxUnusedVar(outlineView);
751 NSArray* supportedTypes([NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]);
753 NSPasteboard* pasteboard([info draggingPasteboard]);
755 NSString* bestType([pasteboard availableTypeFromArray:supportedTypes]);
757 return NSDragOperationNone;
759 NSDragOperation dragOperation;
760 wxDataViewCtrl* const dvc(implementation->GetDataViewCtrl());
762 wxCHECK_MSG(dvc, false, "Pointer to data view control not set correctly.");
763 wxCHECK_MSG(dvc->GetModel(), false, "Pointer to model not set correctly.");
766 event(wxEVT_COMMAND_DATAVIEW_ITEM_DROP_POSSIBLE,dvc->GetId());
768 event.SetEventObject(dvc);
769 event.SetItem(wxDataViewItemFromItem(item));
770 event.SetModel(dvc->GetModel());
771 if ([bestType compare:DataViewPboardType] == NSOrderedSame)
773 NSArray* dataArray((NSArray*)[pasteboard propertyListForType:DataViewPboardType]);
774 NSUInteger indexDraggedItem, noOfDraggedItems([dataArray count]);
776 indexDraggedItem = 0;
777 while (indexDraggedItem < noOfDraggedItems)
779 wxDataObjectComposite* dataObjects(implementation->GetDnDDataObjects((NSData*)[dataArray objectAtIndex:indexDraggedItem]));
781 if (dataObjects && (dataObjects->GetFormatCount() > 0))
783 wxMemoryBuffer buffer;
785 // copy data into data object:
786 event.SetDataObject(dataObjects);
787 event.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
788 // copy data into buffer:
789 dataObjects->GetDataHere(event.GetDataFormat().GetType(),buffer.GetWriteBuf(event.GetDataSize()));
790 buffer.UngetWriteBuf(event.GetDataSize());
791 event.SetDataBuffer(buffer.GetData());
792 // finally, send event:
793 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
795 dragOperation = NSDragOperationEvery;
800 dragOperation = NSDragOperationNone;
801 indexDraggedItem = noOfDraggedItems; // stop loop
806 dragOperation = NSDragOperationNone;
807 indexDraggedItem = noOfDraggedItems; // stop loop
815 // needed to convert internally used UTF-16 representation to a UTF-8
818 wxDataObjectComposite* dataObjects (new wxDataObjectComposite());
819 wxTextDataObject* textDataObject(new wxTextDataObject());
821 osxData = ::CFStringCreateExternalRepresentation(kCFAllocatorDefault,(CFStringRef)[pasteboard stringForType:NSStringPboardType],kCFStringEncodingUTF8,32);
822 if (textDataObject->SetData(::CFDataGetLength(osxData),::CFDataGetBytePtr(osxData)))
823 dataObjects->Add(textDataObject);
825 delete textDataObject;
826 // send event if data could be copied:
827 if (dataObjects->GetFormatCount() > 0)
829 event.SetDataObject(dataObjects);
830 event.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
831 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
832 dragOperation = NSDragOperationEvery;
834 dragOperation = NSDragOperationNone;
837 dragOperation = NSDragOperationNone;
839 ::CFRelease(osxData);
843 return dragOperation;
846 -(BOOL) outlineView:(NSOutlineView*)outlineView writeItems:(NSArray*)writeItems toPasteboard:(NSPasteboard*)pasteboard
848 wxUnusedVar(outlineView);
850 // the pasteboard will be filled up with an array containing the data as
851 // returned by the events (including the data type) and a concatenation of
852 // text (string) data; the text data will only be put onto the pasteboard
853 // if for all items a string representation exists
854 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
856 wxDataViewItemArray dataViewItems;
859 wxCHECK_MSG(dvc, false,"Pointer to data view control not set correctly.");
860 wxCHECK_MSG(dvc->GetModel(),false,"Pointer to model not set correctly.");
862 if ([writeItems count] > 0)
864 bool dataStringAvailable(true); // a flag indicating if for all items a data string is available
865 NSMutableArray* dataArray = [[NSMutableArray arrayWithCapacity:[writeItems count]] retain]; // data of all items
866 wxString dataString; // contains the string data of all items
868 // send a begin drag event for all selected items and proceed with
869 // dragging unless the event is vetoed:
871 event(wxEVT_COMMAND_DATAVIEW_ITEM_BEGIN_DRAG,dvc->GetId());
873 event.SetEventObject(dvc);
874 event.SetModel(dvc->GetModel());
875 for (size_t itemCounter=0; itemCounter<[writeItems count]; ++itemCounter)
877 bool itemStringAvailable(false); // a flag indicating if for the current item a string is available
878 wxDataObjectComposite* itemObject(new wxDataObjectComposite()); // data object for current item
879 wxString itemString; // contains the TAB concatenated data of an item
882 wxDataViewItemFromItem([writeItems objectAtIndex:itemCounter]));
883 itemString = ::ConcatenateDataViewItemValues(dvc,event.GetItem());
884 itemObject->Add(new wxTextDataObject(itemString));
885 event.SetDataObject(itemObject);
886 // check if event has not been vetoed:
887 if (dvc->HandleWindowEvent(event) && event.IsAllowed() && (event.GetDataObject()->GetFormatCount() > 0))
889 size_t const noOfFormats = event.GetDataObject()->GetFormatCount();
890 wxDataFormat* dataFormats(new wxDataFormat[noOfFormats]);
892 event.GetDataObject()->GetAllFormats(dataFormats,wxDataObject::Get);
893 for (size_t formatCounter=0; formatCounter<noOfFormats; ++formatCounter)
895 // constant definitions for abbreviational purposes:
896 wxDataFormatId const idDataFormat = dataFormats[formatCounter].GetType();
897 size_t const dataSize = event.GetDataObject()->GetDataSize(idDataFormat);
898 size_t const dataBufferSize = sizeof(wxDataFormatId)+dataSize;
899 // variable definitions (used in all case statements):
900 wxMemoryBuffer dataBuffer(dataBufferSize);
902 dataBuffer.AppendData(&idDataFormat,sizeof(wxDataFormatId));
903 switch (idDataFormat)
906 // otherwise wxDF_UNICODETEXT already filled up
907 // the string; and the UNICODE representation has
909 if (!itemStringAvailable)
911 event.GetDataObject()->GetDataHere(wxDF_TEXT,dataBuffer.GetAppendBuf(dataSize));
912 dataBuffer.UngetAppendBuf(dataSize);
913 [dataArray addObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
914 itemString = wxString(static_cast<char const*>(dataBuffer.GetData())+sizeof(wxDataFormatId),wxConvLocal);
915 itemStringAvailable = true;
918 case wxDF_UNICODETEXT:
920 event.GetDataObject()->GetDataHere(wxDF_UNICODETEXT,dataBuffer.GetAppendBuf(dataSize));
921 dataBuffer.UngetAppendBuf(dataSize);
922 if (itemStringAvailable) // does an object already exist as an ASCII text (see wxDF_TEXT case statement)?
923 [dataArray replaceObjectAtIndex:itemCounter withObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
925 [dataArray addObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
926 itemString = wxString::FromUTF8(static_cast<char const*>(dataBuffer.GetData())+sizeof(wxDataFormatId),dataSize);
927 itemStringAvailable = true;
931 wxFAIL_MSG("Data object has invalid or unsupported data format");
936 delete[] dataFormats;
938 if (dataStringAvailable)
939 if (itemStringAvailable)
942 dataString << wxT('\n');
943 dataString << itemString;
946 dataStringAvailable = false;
952 return NO; // dragging was vetoed or no data available
955 if (dataStringAvailable)
957 wxCFStringRef osxString(dataString);
959 [pasteboard declareTypes:[NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil] owner:nil];
960 [pasteboard setPropertyList:dataArray forType:DataViewPboardType];
961 [pasteboard setString:osxString.AsNSString() forType:NSStringPboardType];
965 [pasteboard declareTypes:[NSArray arrayWithObject:DataViewPboardType] owner:nil];
966 [pasteboard setPropertyList:dataArray forType:DataViewPboardType];
971 return NO; // no items to drag (should never occur)
977 -(void) addToBuffer:(wxPointerObject*)item
979 [items addObject:item];
984 [items removeAllObjects];
987 -(wxPointerObject*) getDataViewItemFromBuffer:(const wxDataViewItem&)item
989 return [items member:[[[wxPointerObject alloc] initWithPointer:item.GetID()] autorelease]];
992 -(wxPointerObject*) getItemFromBuffer:(wxPointerObject*)item
994 return [items member:item];
997 -(BOOL) isInBuffer:(wxPointerObject*)item
999 return [items containsObject:item];
1002 -(void) removeFromBuffer:(wxPointerObject*)item
1004 [items removeObject:item];
1008 // children handling
1010 -(void) appendChild:(wxPointerObject*)item
1012 [children addObject:item];
1015 -(void) clearChildren
1017 [children removeAllObjects];
1020 -(wxPointerObject*) getChild:(NSUInteger)index
1022 return [children objectAtIndex:index];
1025 -(NSUInteger) getChildCount
1027 return [children count];
1030 -(void) removeChild:(NSUInteger)index
1032 [children removeObjectAtIndex:index];
1038 -(void) clearBuffers
1041 [self clearChildren];
1042 [self setCurrentParentItem:nil];
1048 -(NSArray*) sortDescriptors
1050 return sortDescriptors;
1053 -(void) setSortDescriptors:(NSArray*)newSortDescriptors
1055 [newSortDescriptors retain];
1056 [sortDescriptors release];
1057 sortDescriptors = newSortDescriptors;
1061 // access to wxWidget's implementation
1063 -(wxPointerObject*) currentParentItem
1065 return currentParentItem;
1068 -(wxCocoaDataViewControl*) implementation
1070 return implementation;
1073 -(wxDataViewModel*) model
1078 -(void) setCurrentParentItem:(wxPointerObject*)newCurrentParentItem
1080 [newCurrentParentItem retain];
1081 [currentParentItem release];
1082 currentParentItem = newCurrentParentItem;
1085 -(void) setImplementation:(wxCocoaDataViewControl*) newImplementation
1087 implementation = newImplementation;
1090 -(void) setModel:(wxDataViewModel*) newModel
1098 -(void) bufferItem:(wxPointerObject*)parentItem withChildren:(wxDataViewItemArray*)dataViewChildrenPtr
1100 NSInteger const noOfChildren = (*dataViewChildrenPtr).GetCount();
1102 [self setCurrentParentItem:parentItem];
1103 [self clearChildren];
1104 for (NSInteger indexChild=0; indexChild<noOfChildren; ++indexChild)
1106 wxPointerObject* bufferedPointerObject;
1107 wxPointerObject* newPointerObject([[wxPointerObject alloc] initWithPointer:(*dataViewChildrenPtr)[indexChild].GetID()]);
1109 // The next statement and test looks strange but there is
1110 // unfortunately no workaround: due to the fact that two pointer
1111 // objects are identical if their pointers are identical - because the
1112 // method isEqual has been overloaded - the set operation will only
1113 // add a new pointer object if there is not already one in the set
1114 // having the same pointer. On the other side the children's array
1115 // would always add the new pointer object. This means that different
1116 // pointer objects are stored in the set and array. This will finally
1117 // lead to a crash as objects diverge. To solve this issue it is first
1118 // tested if the child already exists in the set and if it is the case
1119 // the sets object is going to be appended to the array, otheriwse the
1120 // new pointer object is added to the set and array:
1121 bufferedPointerObject = [self getItemFromBuffer:newPointerObject];
1122 if (bufferedPointerObject == nil)
1124 [items addObject:newPointerObject];
1125 [children addObject:newPointerObject];
1128 [children addObject:bufferedPointerObject];
1129 [newPointerObject release];
1135 // ============================================================================
1137 // ============================================================================
1139 @implementation wxCustomCell
1143 wxCustomRendererObject * const
1144 obj = static_cast<wxCustomRendererObject *>([self objectValue]);
1147 const wxSize size = obj->customRenderer->GetSize();
1148 return NSMakeSize(size.x, size.y);
1154 -(void) drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
1156 wxCustomRendererObject * const
1157 obj = static_cast<wxCustomRendererObject *>([self objectValue]);
1160 // this may happen for the custom cells in container rows: they don't
1165 wxDataViewCustomRenderer * const renderer = obj->customRenderer;
1167 wxDC * const dc = renderer->GetDC();
1168 renderer->WXCallRender(wxFromNSRect(controlView, cellFrame), dc, 0);
1169 renderer->SetDC(NULL);
1172 -(NSRect) imageRectForBounds:(NSRect)cellFrame
1177 -(NSRect) titleRectForBounds:(NSRect)cellFrame
1184 // ============================================================================
1186 // ============================================================================
1187 @implementation wxImageTextCell
1193 self = [super init];
1196 // initializing the text part:
1197 [self setSelectable:YES];
1198 // initializing the image part:
1200 imageSize = NSMakeSize(16,16);
1201 spaceImageText = 5.0;
1207 -(id) copyWithZone:(NSZone*)zone
1209 wxImageTextCell* cell;
1212 cell = (wxImageTextCell*) [super copyWithZone:zone];
1213 cell->image = [image retain];
1214 cell->imageSize = imageSize;
1215 cell->spaceImageText = spaceImageText;
1216 cell->xImageShift = xImageShift;
1231 -(NSTextAlignment) alignment
1233 return cellAlignment;
1236 -(void) setAlignment:(NSTextAlignment)newAlignment
1238 cellAlignment = newAlignment;
1239 switch (newAlignment)
1241 case NSCenterTextAlignment:
1242 case NSLeftTextAlignment:
1243 case NSJustifiedTextAlignment:
1244 case NSNaturalTextAlignment:
1245 [super setAlignment:NSLeftTextAlignment];
1247 case NSRightTextAlignment:
1248 [super setAlignment:NSRightTextAlignment];
1251 wxFAIL_MSG("Unknown alignment type.");
1263 -(void) setImage:(NSImage*)newImage
1275 -(void) setImageSize:(NSSize) newImageSize
1277 imageSize = newImageSize;
1283 -(NSSize) cellImageSize
1285 return NSMakeSize(imageSize.width+xImageShift+spaceImageText,imageSize.height);
1290 NSSize cellSize([super cellSize]);
1293 if (imageSize.height > cellSize.height)
1294 cellSize.height = imageSize.height;
1295 cellSize.width += imageSize.width+xImageShift+spaceImageText;
1300 -(NSSize) cellTextSize
1302 return [super cellSize];
1308 -(void) determineCellParts:(NSRect)cellFrame imagePart:(NSRect*)imageFrame textPart:(NSRect*)textFrame
1310 switch (cellAlignment)
1312 case NSCenterTextAlignment:
1314 CGFloat const cellSpace = cellFrame.size.width-[self cellSize].width;
1316 // if the cell's frame is smaller than its contents (at least
1317 // in x-direction) make sure that the image is visible:
1319 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1320 else // otherwise center the image and text in the cell's frame
1321 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText+0.5*cellSpace,NSMinXEdge);
1324 case NSJustifiedTextAlignment:
1325 case NSLeftTextAlignment:
1326 case NSNaturalTextAlignment: // how to determine the natural writing direction? TODO
1327 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1329 case NSRightTextAlignment:
1331 CGFloat const cellSpace = cellFrame.size.width-[self cellSize].width;
1333 // if the cell's frame is smaller than its contents (at least
1334 // in x-direction) make sure that the image is visible:
1336 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1337 else // otherwise right align the image and text in the cell's frame
1338 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText+cellSpace,NSMinXEdge);
1342 *imageFrame = NSZeroRect;
1343 *textFrame = NSZeroRect;
1344 wxFAIL_MSG("Unhandled alignment type.");
1348 -(void) drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
1350 NSRect textFrame, imageFrame;
1353 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1354 // draw the image part by ourselves;
1355 // check if the cell has to draw its own background (checking is done by
1356 // the parameter of the textfield's cell):
1357 if ([self drawsBackground])
1359 [[self backgroundColor] set];
1360 NSRectFill(imageFrame);
1364 // the image is slightly shifted (xImageShift) and has a fixed size
1365 // but the image's frame might be larger and starts currently on the
1366 // left side of the cell's frame; therefore, the origin and the
1367 // image's frame size have to be adjusted:
1368 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1370 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1371 imageFrame.size.width = imageSize.width;
1375 imageFrame.origin.x += xImageShift;
1376 imageFrame.size.width -= xImageShift+spaceImageText;
1378 // ...and the image has to be centered in the y-direction:
1379 if (imageFrame.size.height > imageSize.height)
1380 imageFrame.size.height = imageSize.height;
1381 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1383 // according to the documentation the coordinate system should be
1384 // flipped for NSTableViews (y-coordinate goes from top to bottom); to
1385 // draw an image correctly the coordinate system has to be transformed
1386 // to a bottom-top coordinate system, otherwise the image's
1387 // content is flipped:
1388 NSAffineTransform* coordinateTransform([NSAffineTransform transform]);
1390 if ([controlView isFlipped])
1392 [coordinateTransform scaleXBy: 1.0 yBy:-1.0]; // first the coordinate system is brought back to bottom-top orientation
1393 [coordinateTransform translateXBy:0.0 yBy:(-2.0)*imageFrame.origin.y-imageFrame.size.height]; // the coordinate system has to be moved to compensate for the
1394 [coordinateTransform concat]; // other orientation and the position of the image's frame
1396 [image drawInRect:imageFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0]; // suggested method to draw the image
1397 // instead of compositeToPoint:operation:
1398 // take back previous transformation (if the view is not flipped the
1399 // coordinate transformation matrix contains the identity matrix and
1400 // the next two operations do not change the content's transformation
1402 [coordinateTransform invert];
1403 [coordinateTransform concat];
1405 // let the textfield cell draw the text part:
1406 if (textFrame.size.width > [self cellTextSize].width)
1408 // for unknown reasons the alignment of the text cell is ignored;
1409 // therefore change the size so that alignment does not influence the
1410 // visualization anymore
1411 textFrame.size.width = [self cellTextSize].width;
1413 [super drawWithFrame:textFrame inView:controlView];
1416 -(void) editWithFrame:(NSRect)aRect inView:(NSView*)controlView editor:(NSText*)textObj delegate:(id)anObject event:(NSEvent*)theEvent
1418 NSRect textFrame, imageFrame;
1421 [self determineCellParts:aRect imagePart:&imageFrame textPart:&textFrame];
1422 [super editWithFrame:textFrame inView:controlView editor:textObj delegate:anObject event:theEvent];
1425 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1426 -(NSUInteger) hitTestForEvent:(NSEvent*)event inRect:(NSRect)cellFrame ofView:(NSView*)controlView
1428 NSPoint point = [controlView convertPoint:[event locationInWindow] fromView:nil];
1430 NSRect imageFrame, textFrame;
1433 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1436 // the image is shifted...
1437 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1439 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1440 imageFrame.size.width = imageSize.width;
1444 imageFrame.origin.x += xImageShift;
1445 imageFrame.size.width -= xImageShift+spaceImageText;
1448 if (imageFrame.size.height > imageSize.height)
1449 imageFrame.size.height = imageSize.height;
1450 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1451 // If the point is in the image rect, then it is a content hit (see
1452 // documentation for hitTestForEvent:inRect:ofView):
1453 if (NSMouseInRect(point, imageFrame, [controlView isFlipped]))
1454 return NSCellHitContentArea;
1456 // if the image was not hit let's try the text part:
1457 if (textFrame.size.width > [self cellTextSize].width)
1459 // for unknown reasons the alignment of the text cell is ignored;
1460 // therefore change the size so that alignment does not influence the
1461 // visualization anymore
1462 textFrame.size.width = [self cellTextSize].width;
1465 return [super hitTestForEvent:event inRect:textFrame ofView:controlView];
1469 -(NSRect) imageRectForBounds:(NSRect)cellFrame
1471 NSRect textFrame, imageFrame;
1474 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1475 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1477 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1478 imageFrame.size.width = imageSize.width;
1482 imageFrame.origin.x += xImageShift;
1483 imageFrame.size.width -= xImageShift+spaceImageText;
1486 if (imageFrame.size.height > imageSize.height)
1487 imageFrame.size.height = imageSize.height;
1488 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1493 -(void) selectWithFrame:(NSRect)aRect inView:(NSView*)controlView editor:(NSText*)textObj delegate:(id)anObject start:(NSInteger)selStart length:(NSInteger)selLength
1495 NSRect textFrame, imageFrame;
1498 [self determineCellParts:aRect imagePart:&imageFrame textPart:&textFrame];
1499 [super selectWithFrame:textFrame inView:controlView editor:textObj delegate:anObject start:selStart length:selLength];
1502 -(NSRect) titleRectForBounds:(NSRect)cellFrame
1504 NSRect textFrame, imageFrame;
1507 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1513 // ============================================================================
1514 // wxCocoaOutlineView
1515 // ============================================================================
1516 @implementation wxCocoaOutlineView
1519 // initializers / destructor
1523 self = [super init];
1526 currentlyEditedColumn =
1527 currentlyEditedRow = -1;
1529 [self registerForDraggedTypes:[NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]];
1530 [self setDelegate:self];
1531 [self setDoubleAction:@selector(actionDoubleClick:)];
1532 [self setDraggingSourceOperationMask:NSDragOperationEvery forLocal:NO];
1533 [self setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
1534 [self setTarget:self];
1540 // access to wxWidget's implementation
1542 -(wxCocoaDataViewControl*) implementation
1544 return implementation;
1547 -(void) setImplementation:(wxCocoaDataViewControl*) newImplementation
1549 implementation = newImplementation;
1555 -(void) actionDoubleClick:(id)sender
1557 wxUnusedVar(sender);
1559 // actually the documentation (NSTableView 2007-10-31) for doubleAction:
1560 // and setDoubleAction: seems to be wrong as this action message is always
1561 // sent whether the cell is editable or not
1562 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1564 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_ACTIVATED,dvc->GetId());
1567 event.SetEventObject(dvc);
1568 event.SetItem(wxDataViewItemFromItem([self itemAtRow:[self clickedRow]]));
1569 dvc->GetEventHandler()->ProcessEvent(event);
1576 -(NSMenu*) menuForEvent:(NSEvent*)theEvent
1578 wxUnusedVar(theEvent);
1580 // this method does not do any special menu event handling but only sends
1581 // an event message; therefore, the user has full control if a context
1582 // menu should be shown or not
1583 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1585 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_CONTEXT_MENU,dvc->GetId());
1587 wxDataViewItemArray selectedItems;
1590 event.SetEventObject(dvc);
1591 event.SetModel(dvc->GetModel());
1592 // get the item information;
1593 // theoretically more than one ID can be returned but the event can only
1594 // handle one item, therefore only the first item of the array is
1596 if (dvc->GetSelections(selectedItems) > 0)
1597 event.SetItem(selectedItems[0]);
1598 dvc->GetEventHandler()->ProcessEvent(event);
1606 -(void) outlineView:(NSOutlineView*)outlineView mouseDownInHeaderOfTableColumn:(NSTableColumn*)tableColumn
1608 wxDataViewColumn* const col(static_cast<wxDataViewColumn*>([[tableColumn identifier] pointer]));
1610 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1613 event(wxEVT_COMMAND_DATAVIEW_COLUMN_HEADER_CLICK,dvc->GetId());
1616 // first, send an event that the user clicked into a column's header:
1617 event.SetEventObject(dvc);
1618 event.SetColumn(dvc->GetColumnPosition(col));
1619 event.SetDataViewColumn(col);
1620 dvc->HandleWindowEvent(event);
1622 // now, check if the click may have had an influence on sorting, too;
1623 // the sorting setup has to be done only if the clicked table column is
1624 // sortable and has not been used for sorting before the click; if the
1625 // column is already responsible for sorting the native control changes
1626 // the sorting direction automatically and informs the data source via
1627 // outlineView:sortDescriptorsDidChange:
1628 if (col->IsSortable() && ([tableColumn sortDescriptorPrototype] == nil))
1630 // remove the sort order from the previously sorted column table (it
1631 // can also be that no sorted column table exists):
1632 UInt32 const noOfColumns = [outlineView numberOfColumns];
1634 for (UInt32 i=0; i<noOfColumns; ++i)
1635 [[[outlineView tableColumns] objectAtIndex:i] setSortDescriptorPrototype:nil];
1636 // make column table sortable:
1637 NSArray* sortDescriptors;
1638 NSSortDescriptor* sortDescriptor;
1640 sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[NSString stringWithFormat:@"%d",[outlineView columnWithIdentifier:[tableColumn identifier]]]
1642 sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
1643 [tableColumn setSortDescriptorPrototype:sortDescriptor];
1644 [outlineView setSortDescriptors:sortDescriptors];
1645 [sortDescriptor release];
1649 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldCollapseItem:(id)item
1651 wxUnusedVar(outlineView);
1653 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1655 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSING,dvc->GetId());
1658 event.SetEventObject(dvc);
1659 event.SetItem (wxDataViewItemFromItem(item));
1660 event.SetModel (dvc->GetModel());
1661 // finally send the equivalent wxWidget event:
1662 dvc->GetEventHandler()->ProcessEvent(event);
1663 // opening the container is allowed if not vetoed:
1664 return event.IsAllowed();
1667 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldExpandItem:(id)item
1669 wxUnusedVar(outlineView);
1671 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1673 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDING,dvc->GetId());
1676 event.SetEventObject(dvc);
1677 event.SetItem (wxDataViewItemFromItem(item));
1678 event.SetModel (dvc->GetModel());
1679 // finally send the equivalent wxWidget event:
1680 dvc->GetEventHandler()->ProcessEvent(event);
1681 // opening the container is allowed if not vetoed:
1682 return event.IsAllowed();
1685 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldSelectTableColumn:(NSTableColumn*)tableColumn
1687 wxUnusedVar(tableColumn);
1688 wxUnusedVar(outlineView);
1693 -(void) outlineView:(wxCocoaOutlineView*)outlineView
1694 willDisplayCell:(id)cell
1695 forTableColumn:(NSTableColumn*)tableColumn
1698 wxUnusedVar(outlineView);
1700 wxDataViewCtrl * const dvc = implementation->GetDataViewCtrl();
1701 wxDataViewModel * const model = dvc->GetModel();
1703 wxDataViewColumn * const
1704 dvCol(static_cast<wxDataViewColumn*>(
1705 [[tableColumn identifier] pointer]
1708 const unsigned colIdx = dvCol->GetModelColumn();
1710 wxDataViewItem dvItem(wxDataViewItemFromItem(item));
1712 if ( !model->HasValue(dvItem, colIdx) )
1715 wxDataViewRenderer * const renderer = dvCol->GetRenderer();
1716 wxDataViewRendererNativeData * const data = renderer->GetNativeData();
1718 // let the renderer know about what it's going to render next
1719 data->SetColumnPtr(tableColumn);
1720 data->SetItem(item);
1721 data->SetItemCell(cell);
1723 // use the attributes: notice that we need to do this whether we have them
1724 // or not as even if this cell doesn't have any attributes, the previous
1725 // one might have had some and then we need to reset them back to default
1726 wxDataViewItemAttr attr;
1727 model->GetAttr(dvItem, colIdx, attr);
1728 renderer->OSXApplyAttr(attr);
1730 // set the state (enabled/disabled) of the item
1731 renderer->OSXApplyEnabled(model->IsEnabled(dvItem, colIdx));
1733 // and finally do draw it
1734 renderer->MacRender();
1740 -(void) outlineViewColumnDidMove:(NSNotification*)notification
1742 int const newColumnPosition = [[[notification userInfo] objectForKey:@"NSNewColumn"] intValue];
1744 wxDataViewColumn* const col(static_cast<wxDataViewColumn*>([[[[self tableColumns] objectAtIndex:newColumnPosition] identifier] pointer]));
1746 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1748 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_COLUMN_REORDERED,dvc->GetId());
1751 event.SetEventObject(dvc);
1752 event.SetColumn(dvc->GetColumnPosition(col));
1753 event.SetDataViewColumn(col);
1754 dvc->GetEventHandler()->ProcessEvent(event);
1757 -(void) outlineViewItemDidCollapse:(NSNotification*)notification
1759 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1761 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSED,dvc->GetId());
1764 event.SetEventObject(dvc);
1765 event.SetItem(wxDataViewItemFromItem(
1766 [[notification userInfo] objectForKey:@"NSObject"]));
1767 dvc->GetEventHandler()->ProcessEvent(event);
1770 -(void) outlineViewItemDidExpand:(NSNotification*)notification
1772 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1774 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDED,dvc->GetId());
1777 event.SetEventObject(dvc);
1778 event.SetItem(wxDataViewItemFromItem(
1779 [[notification userInfo] objectForKey:@"NSObject"]));
1780 dvc->GetEventHandler()->ProcessEvent(event);
1783 -(void) outlineViewSelectionDidChange:(NSNotification*)notification
1785 wxUnusedVar(notification);
1787 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1789 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_SELECTION_CHANGED,dvc->GetId());
1791 event.SetEventObject(dvc);
1792 event.SetModel(dvc->GetModel());
1793 event.SetItem(dvc->GetSelection());
1794 dvc->GetEventHandler()->ProcessEvent(event);
1797 -(void) textDidBeginEditing:(NSNotification*)notification
1799 // this notification is only sent if the user started modifying the cell
1800 // (not when the user clicked into the cell and the cell's editor is
1803 // call method of superclass (otherwise editing does not work correctly -
1804 // the outline data source class is not informed about a change of data):
1805 [super textDidBeginEditing:notification];
1807 // remember the column being edited, it will be used in textDidEndEditing:
1808 currentlyEditedColumn = [self editedColumn];
1809 currentlyEditedRow = [self editedRow];
1811 wxDataViewColumn* const col =
1812 static_cast<wxDataViewColumn*>(
1813 [[[[self tableColumns] objectAtIndex:currentlyEditedColumn] identifier] pointer]);
1815 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1818 // stop editing of a custom item first (if necessary)
1819 dvc->FinishCustomItemEditing();
1821 // now, send the event:
1823 event(wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED,dvc->GetId());
1825 event.SetEventObject(dvc);
1827 wxDataViewItemFromItem([self itemAtRow:currentlyEditedRow]));
1828 event.SetColumn(dvc->GetColumnPosition(col));
1829 event.SetDataViewColumn(col);
1830 dvc->GetEventHandler()->ProcessEvent(event);
1833 -(void) textDidEndEditing:(NSNotification*)notification
1835 // call method of superclass (otherwise editing does not work correctly -
1836 // the outline data source class is not informed about a change of data):
1837 [super textDidEndEditing:notification];
1839 // under OSX an event indicating the end of an editing session can be sent
1840 // even if no event indicating a start of an editing session has been sent
1841 // (see Documentation for NSControl controlTextDidEndEditing:); this is
1842 // not expected by a user of the wxWidgets library and therefore an
1843 // wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_DONE event is only sent if a
1844 // corresponding wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED has been sent
1845 // before; to check if a wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED has
1846 // been sent the last edited column/row are valid:
1847 if ( currentlyEditedColumn != -1 && currentlyEditedRow != -1 )
1849 wxDataViewColumn* const col =
1850 static_cast<wxDataViewColumn*>(
1851 [[[[self tableColumns] objectAtIndex:currentlyEditedColumn] identifier] pointer]);
1853 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1855 // send event to wxWidgets:
1857 event(wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_DONE,dvc->GetId());
1859 event.SetEventObject(dvc);
1861 wxDataViewItemFromItem([self itemAtRow:currentlyEditedRow]));
1862 event.SetColumn(dvc->GetColumnPosition(col));
1863 event.SetDataViewColumn(col);
1864 dvc->GetEventHandler()->ProcessEvent(event);
1867 // we're not editing any more
1868 currentlyEditedColumn =
1869 currentlyEditedRow = -1;
1875 // ============================================================================
1876 // wxCocoaDataViewControl
1877 // ============================================================================
1879 wxCocoaDataViewControl::wxCocoaDataViewControl(wxWindow* peer,
1886 [[NSScrollView alloc] initWithFrame:wxOSXGetFrameForControl(peer,pos,size)]
1889 m_OutlineView([[wxCocoaOutlineView alloc] init])
1891 // initialize scrollview (the outline view is part of a scrollview):
1892 NSScrollView* scrollview = (NSScrollView*) GetWXWidget();
1894 [scrollview setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1895 [scrollview setBorderType:NSNoBorder];
1896 [scrollview setHasVerticalScroller:YES];
1897 [scrollview setHasHorizontalScroller:YES];
1898 [scrollview setAutohidesScrollers:YES];
1899 [scrollview setDocumentView:m_OutlineView];
1901 // initialize the native control itself too
1902 InitOutlineView(style);
1905 void wxCocoaDataViewControl::InitOutlineView(long style)
1907 [m_OutlineView setImplementation:this];
1908 [m_OutlineView setColumnAutoresizingStyle:NSTableViewSequentialColumnAutoresizingStyle];
1909 [m_OutlineView setIndentationPerLevel:GetDataViewCtrl()->GetIndent()];
1910 NSUInteger maskGridStyle(NSTableViewGridNone);
1911 if (style & wxDV_HORIZ_RULES)
1912 maskGridStyle |= NSTableViewSolidHorizontalGridLineMask;
1913 if (style & wxDV_VERT_RULES)
1914 maskGridStyle |= NSTableViewSolidVerticalGridLineMask;
1915 [m_OutlineView setGridStyleMask:maskGridStyle];
1916 [m_OutlineView setAllowsMultipleSelection: (style & wxDV_MULTIPLE) != 0];
1917 [m_OutlineView setUsesAlternatingRowBackgroundColors:(style & wxDV_ROW_LINES) != 0];
1919 if ( style & wxDV_NO_HEADER )
1920 [m_OutlineView setHeaderView:nil];
1923 wxCocoaDataViewControl::~wxCocoaDataViewControl()
1925 [m_DataSource release];
1926 [m_OutlineView release];
1930 // column related methods (inherited from wxDataViewWidgetImpl)
1932 bool wxCocoaDataViewControl::ClearColumns()
1934 // as there is a bug in NSOutlineView version (OSX 10.5.6 #6555162) the
1935 // columns cannot be deleted if there is an outline column in the view;
1936 // therefore, the whole view is deleted and newly constructed:
1937 [m_OutlineView release];
1938 m_OutlineView = [[wxCocoaOutlineView alloc] init];
1939 [((NSScrollView*) GetWXWidget()) setDocumentView:m_OutlineView];
1940 [m_OutlineView setDataSource:m_DataSource];
1942 InitOutlineView(GetDataViewCtrl()->GetWindowStyle());
1947 bool wxCocoaDataViewControl::DeleteColumn(wxDataViewColumn* columnPtr)
1949 if ([m_OutlineView outlineTableColumn] == columnPtr->GetNativeData()->GetNativeColumnPtr())
1950 [m_OutlineView setOutlineTableColumn:nil]; // due to a bug this does not work
1951 [m_OutlineView removeTableColumn:columnPtr->GetNativeData()->GetNativeColumnPtr()]; // due to a confirmed bug #6555162 the deletion does not work for
1952 // outline table columns (... and there is no workaround)
1953 return (([m_OutlineView columnWithIdentifier:[[[wxPointerObject alloc] initWithPointer:columnPtr] autorelease]]) == -1);
1956 void wxCocoaDataViewControl::DoSetExpanderColumn(const wxDataViewColumn *columnPtr)
1958 [m_OutlineView setOutlineTableColumn:columnPtr->GetNativeData()->GetNativeColumnPtr()];
1961 wxDataViewColumn* wxCocoaDataViewControl::GetColumn(unsigned int pos) const
1963 return static_cast<wxDataViewColumn*>([[[[m_OutlineView tableColumns] objectAtIndex:pos] identifier] pointer]);
1966 int wxCocoaDataViewControl::GetColumnPosition(const wxDataViewColumn *columnPtr) const
1968 return [m_OutlineView columnWithIdentifier:[[[wxPointerObject alloc] initWithPointer:const_cast<wxDataViewColumn*>(columnPtr)] autorelease]];
1971 bool wxCocoaDataViewControl::InsertColumn(unsigned int pos, wxDataViewColumn* columnPtr)
1973 // create column and set the native data of the dataview column:
1974 NSTableColumn *nativeColumn = ::CreateNativeColumn(columnPtr);
1975 columnPtr->GetNativeData()->SetNativeColumnPtr(nativeColumn);
1976 // as the native control does not allow the insertion of a column at a
1977 // specified position the column is first appended and - if necessary -
1978 // moved to its final position:
1979 [m_OutlineView addTableColumn:nativeColumn];
1980 if (pos != static_cast<unsigned int>([m_OutlineView numberOfColumns]-1))
1981 [m_OutlineView moveColumn:[m_OutlineView numberOfColumns]-1 toColumn:pos];
1983 // set columns width now that it can be computed even for autosized columns:
1984 columnPtr->SetWidth(columnPtr->GetWidthVariable());
1990 void wxCocoaDataViewControl::FitColumnWidthToContent(unsigned int pos)
1992 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
1993 const int count = GetCount();
1994 NSTableColumn *column = GetColumn(pos)->GetNativeData()->GetNativeColumnPtr();
1996 class MaxWidthCalculator
1999 MaxWidthCalculator(wxCocoaOutlineView *view,
2000 NSTableColumn *column, unsigned columnIndex)
2003 m_column(columnIndex),
2006 // account for indentation in the column with expander
2007 if ( column == [m_view outlineTableColumn] )
2008 m_indent = [m_view indentationPerLevel];
2011 void UpdateWithWidth(int width)
2013 m_width = wxMax(m_width, width);
2016 void UpdateWithRow(int row)
2018 NSCell *cell = [m_view preparedCellAtColumn:m_column row:row];
2019 unsigned cellWidth = [cell cellSize].width + 1/*round the float up*/;
2022 cellWidth += m_indent * ([m_view levelForRow:row] + 1);
2024 m_width = wxMax(m_width, cellWidth);
2027 int GetMaxWidth() const { return m_width; }
2031 wxCocoaOutlineView *m_view;
2036 MaxWidthCalculator calculator(m_OutlineView, column, pos);
2038 if ( [column headerCell] )
2040 calculator.UpdateWithWidth([[column headerCell] cellSize].width + 1/*round the float up*/);
2043 // The code below deserves some explanation. For very large controls, we
2044 // simply can't afford to calculate sizes for all items, it takes too
2045 // long. So the best we can do is to check the first and the last N/2
2046 // items in the control for some sufficiently large N and calculate best
2047 // sizes from that. That can result in the calculated best width being too
2048 // small for some outliers, but it's better to get slightly imperfect
2049 // result than to wait several seconds after every update. To avoid highly
2050 // visible miscalculations, we also include all currently visible items
2051 // no matter what. Finally, the value of N is determined dynamically by
2052 // measuring how much time we spent on the determining item widths so far.
2055 int top_part_end = count;
2056 static const long CALC_TIMEOUT = 20/*ms*/;
2057 // don't call wxStopWatch::Time() too often
2058 static const unsigned CALC_CHECK_FREQ = 100;
2061 // use some hard-coded limit, that's the best we can do without timer
2062 int top_part_end = wxMin(500, count);
2063 #endif // wxUSE_STOPWATCH/!wxUSE_STOPWATCH
2067 for ( row = 0; row < top_part_end; row++ )
2070 if ( row % CALC_CHECK_FREQ == CALC_CHECK_FREQ-1 &&
2071 timer.Time() > CALC_TIMEOUT )
2073 #endif // wxUSE_STOPWATCH
2074 calculator.UpdateWithRow(row);
2077 // row is the first unmeasured item now; that's our value of N/2
2083 // add bottom N/2 items now:
2084 const int bottom_part_start = wxMax(row, count - row);
2085 for ( row = bottom_part_start; row < count; row++ )
2086 calculator.UpdateWithRow(row);
2088 // finally, include currently visible items in the calculation:
2089 const NSRange visible = [m_OutlineView rowsInRect:[m_OutlineView visibleRect]];
2090 const int first_visible = wxMax(visible.location, top_part_end);
2091 const int last_visible = wxMin(first_visible + visible.length, bottom_part_start);
2093 for ( row = first_visible; row < last_visible; row++ )
2094 calculator.UpdateWithRow(row);
2096 wxLogTrace("dataview",
2097 "determined best size from %d top, %d bottom plus %d more visible items out of %d total",
2099 count - bottom_part_start,
2100 wxMax(0, last_visible - first_visible),
2104 [column setWidth:calculator.GetMaxWidth()];
2105 #endif // MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
2109 // item related methods (inherited from wxDataViewWidgetImpl)
2111 bool wxCocoaDataViewControl::Add(const wxDataViewItem& parent, const wxDataViewItem& WXUNUSED(item))
2114 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2116 [m_OutlineView reloadData];
2120 bool wxCocoaDataViewControl::Add(const wxDataViewItem& parent, const wxDataViewItemArray& WXUNUSED(items))
2123 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2125 [m_OutlineView reloadData];
2129 void wxCocoaDataViewControl::Collapse(const wxDataViewItem& item)
2131 [m_OutlineView collapseItem:[m_DataSource getDataViewItemFromBuffer:item]];
2134 void wxCocoaDataViewControl::EnsureVisible(const wxDataViewItem& item, const wxDataViewColumn *columnPtr)
2138 [m_OutlineView scrollRowToVisible:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2140 [m_OutlineView scrollColumnToVisible:GetColumnPosition(columnPtr)];
2144 void wxCocoaDataViewControl::Expand(const wxDataViewItem& item)
2146 [m_OutlineView expandItem:[m_DataSource getDataViewItemFromBuffer:item]];
2149 unsigned int wxCocoaDataViewControl::GetCount() const
2151 return [m_OutlineView numberOfRows];
2154 wxRect wxCocoaDataViewControl::GetRectangle(const wxDataViewItem& item, const wxDataViewColumn *columnPtr)
2156 return wxFromNSRect([m_osxView superview],[m_OutlineView frameOfCellAtColumn:GetColumnPosition(columnPtr)
2157 row:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]]);
2160 bool wxCocoaDataViewControl::IsExpanded(const wxDataViewItem& item) const
2162 return [m_OutlineView isItemExpanded:[m_DataSource getDataViewItemFromBuffer:item]];
2165 bool wxCocoaDataViewControl::Reload()
2167 [m_DataSource clearBuffers];
2168 [m_OutlineView scrollColumnToVisible:0];
2169 [m_OutlineView scrollRowToVisible:0];
2170 [m_OutlineView reloadData];
2174 bool wxCocoaDataViewControl::Remove(const wxDataViewItem& parent, const wxDataViewItem& WXUNUSED(item))
2177 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2179 [m_OutlineView reloadData];
2183 bool wxCocoaDataViewControl::Remove(const wxDataViewItem& parent, const wxDataViewItemArray& WXUNUSED(item))
2186 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2188 [m_OutlineView reloadData];
2192 bool wxCocoaDataViewControl::Update(const wxDataViewColumn *columnPtr)
2194 wxUnusedVar(columnPtr);
2199 bool wxCocoaDataViewControl::Update(const wxDataViewItem& WXUNUSED(parent), const wxDataViewItem& item)
2201 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:item]];
2205 bool wxCocoaDataViewControl::Update(const wxDataViewItem& WXUNUSED(parent), const wxDataViewItemArray& items)
2207 for (size_t i=0; i<items.GetCount(); ++i)
2208 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:items[i]]];
2213 // model related methods
2215 bool wxCocoaDataViewControl::AssociateModel(wxDataViewModel* model)
2217 [m_DataSource release];
2220 m_DataSource = [[wxCocoaOutlineDataSource alloc] init];
2221 [m_DataSource setImplementation:this];
2222 [m_DataSource setModel:model];
2225 m_DataSource = NULL;
2226 [m_OutlineView setDataSource:m_DataSource]; // if there is a data source the data is immediately going to be requested
2231 // selection related methods (inherited from wxDataViewWidgetImpl)
2234 wxDataViewItem wxCocoaDataViewControl::GetCurrentItem() const
2236 return wxDataViewItem([[m_OutlineView itemAtRow:[m_OutlineView selectedRow]] pointer]);
2239 void wxCocoaDataViewControl::SetCurrentItem(const wxDataViewItem& item)
2241 // We can't have unselected current item in a NSTableView, as the
2242 // documentation of its deselectRow method explains, the control will
2243 // automatically change the current item to the closest still selected item
2244 // if the current item is deselected. So we have no choice but to select
2245 // the item in the same time as making it current.
2249 int wxCocoaDataViewControl::GetSelections(wxDataViewItemArray& sel) const
2251 NSIndexSet* selectedRowIndexes([m_OutlineView selectedRowIndexes]);
2253 NSUInteger indexRow;
2257 sel.Alloc([selectedRowIndexes count]);
2258 indexRow = [selectedRowIndexes firstIndex];
2259 while (indexRow != NSNotFound)
2261 sel.Add(wxDataViewItem([[m_OutlineView itemAtRow:indexRow] pointer]));
2262 indexRow = [selectedRowIndexes indexGreaterThanIndex:indexRow];
2264 return sel.GetCount();
2267 bool wxCocoaDataViewControl::IsSelected(const wxDataViewItem& item) const
2269 return [m_OutlineView isRowSelected:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2272 void wxCocoaDataViewControl::Select(const wxDataViewItem& item)
2275 [m_OutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]]
2276 byExtendingSelection:GetDataViewCtrl()->HasFlag(wxDV_MULTIPLE) ? YES : NO];
2279 void wxCocoaDataViewControl::SelectAll()
2281 [m_OutlineView selectAll:m_OutlineView];
2284 void wxCocoaDataViewControl::Unselect(const wxDataViewItem& item)
2287 [m_OutlineView deselectRow:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2290 void wxCocoaDataViewControl::UnselectAll()
2292 [m_OutlineView deselectAll:m_OutlineView];
2296 // sorting related methods
2298 wxDataViewColumn* wxCocoaDataViewControl::GetSortingColumn() const
2300 NSArray* const columns = [m_OutlineView tableColumns];
2302 UInt32 const noOfColumns = [columns count];
2305 for (UInt32 i=0; i<noOfColumns; ++i)
2306 if ([[columns objectAtIndex:i] sortDescriptorPrototype] != nil)
2307 return static_cast<wxDataViewColumn*>([[[columns objectAtIndex:i] identifier] pointer]);
2311 void wxCocoaDataViewControl::Resort()
2313 [m_DataSource clearChildren];
2314 [m_OutlineView reloadData];
2318 // other methods (inherited from wxDataViewWidgetImpl)
2320 void wxCocoaDataViewControl::DoSetIndent(int indent)
2322 [m_OutlineView setIndentationPerLevel:static_cast<CGFloat>(indent)];
2325 void wxCocoaDataViewControl::HitTest(const wxPoint& point, wxDataViewItem& item, wxDataViewColumn*& columnPtr) const
2327 NSPoint const nativePoint = wxToNSPoint((NSScrollView*) GetWXWidget(),point);
2333 indexColumn = [m_OutlineView columnAtPoint:nativePoint];
2334 indexRow = [m_OutlineView rowAtPoint: nativePoint];
2335 if ((indexColumn >= 0) && (indexRow >= 0))
2337 columnPtr = static_cast<wxDataViewColumn*>([[[[m_OutlineView tableColumns] objectAtIndex:indexColumn] identifier] pointer]);
2338 item = wxDataViewItem([[m_OutlineView itemAtRow:indexRow] pointer]);
2343 item = wxDataViewItem();
2347 void wxCocoaDataViewControl::SetRowHeight(const wxDataViewItem& WXUNUSED(item), unsigned int WXUNUSED(height))
2348 // Not supported by the native control
2352 void wxCocoaDataViewControl::OnSize()
2354 if ([m_OutlineView numberOfColumns] == 1)
2355 [m_OutlineView sizeLastColumnToFit];
2359 // drag & drop helper methods
2361 wxDataFormat wxCocoaDataViewControl::GetDnDDataFormat(wxDataObjectComposite* dataObjects)
2363 wxDataFormat resultFormat;
2365 return resultFormat;
2367 bool compatible(true);
2369 size_t const noOfFormats = dataObjects->GetFormatCount();
2372 wxDataFormat* formats;
2374 // get all formats and check afterwards if the formats are compatible; if
2375 // they are compatible the preferred format is returned otherwise
2376 // wxDF_INVALID is returned;
2377 // currently compatible types (ordered by priority are):
2378 // - wxDF_UNICODETEXT - wxDF_TEXT
2379 formats = new wxDataFormat[noOfFormats];
2380 dataObjects->GetAllFormats(formats);
2382 while ((indexFormat < noOfFormats) && compatible)
2384 switch (resultFormat.GetType())
2387 resultFormat.SetType(formats[indexFormat].GetType()); // first format (should only be reached if indexFormat == 0)
2390 if (formats[indexFormat].GetType() == wxDF_UNICODETEXT)
2391 resultFormat.SetType(wxDF_UNICODETEXT);
2392 else // incompatible
2394 resultFormat.SetType(wxDF_INVALID);
2398 case wxDF_UNICODETEXT:
2399 if (formats[indexFormat].GetType() != wxDF_TEXT)
2401 resultFormat.SetType(wxDF_INVALID);
2406 resultFormat.SetType(wxDF_INVALID); // not (yet) supported format
2414 return resultFormat;
2417 wxDataObjectComposite* wxCocoaDataViewControl::GetDnDDataObjects(NSData* dataObject) const
2419 wxDataFormatId dataFormatID;
2422 [dataObject getBytes:&dataFormatID length:sizeof(wxDataFormatId)];
2423 switch (dataFormatID)
2426 case wxDF_UNICODETEXT:
2428 wxTextDataObject* textDataObject(new wxTextDataObject());
2430 if (textDataObject->SetData(wxDataFormat(dataFormatID),[dataObject length]-sizeof(wxDataFormatId),static_cast<char const*>([dataObject bytes])+sizeof(wxDataFormatId)))
2432 wxDataObjectComposite* dataObjectComposite(new wxDataObjectComposite());
2434 dataObjectComposite->Add(textDataObject);
2435 return dataObjectComposite;
2439 delete textDataObject;
2449 id wxCocoaDataViewControl::GetItemAtRow(int row) const
2451 return [m_OutlineView itemAtRow:row];
2454 // ----------------------------------------------------------------------------
2455 // wxDataViewRendererNativeData
2456 // ----------------------------------------------------------------------------
2458 void wxDataViewRendererNativeData::Init()
2461 m_origTextColour = NULL;
2462 m_ellipsizeMode = wxELLIPSIZE_MIDDLE;
2465 ApplyLineBreakMode(m_ColumnCell);
2468 void wxDataViewRendererNativeData::ApplyLineBreakMode(NSCell *cell)
2470 NSLineBreakMode nsMode = NSLineBreakByWordWrapping;
2471 switch ( m_ellipsizeMode )
2473 case wxELLIPSIZE_NONE:
2474 nsMode = NSLineBreakByClipping;
2477 case wxELLIPSIZE_START:
2478 nsMode = NSLineBreakByTruncatingHead;
2481 case wxELLIPSIZE_MIDDLE:
2482 nsMode = NSLineBreakByTruncatingMiddle;
2485 case wxELLIPSIZE_END:
2486 nsMode = NSLineBreakByTruncatingTail;
2490 wxASSERT_MSG( nsMode != NSLineBreakByWordWrapping, "unknown wxEllipsizeMode" );
2492 [cell setLineBreakMode: nsMode];
2495 // ---------------------------------------------------------
2496 // wxDataViewRenderer
2497 // ---------------------------------------------------------
2499 wxDataViewRenderer::wxDataViewRenderer(const wxString& varianttype,
2500 wxDataViewCellMode mode,
2502 : wxDataViewRendererBase(varianttype, mode, align),
2505 m_NativeDataPtr(NULL)
2509 wxDataViewRenderer::~wxDataViewRenderer()
2511 delete m_NativeDataPtr;
2514 void wxDataViewRenderer::SetAlignment(int align)
2516 m_alignment = align;
2517 [GetNativeData()->GetColumnCell() setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2520 void wxDataViewRenderer::SetMode(wxDataViewCellMode mode)
2524 [GetOwner()->GetNativeData()->GetNativeColumnPtr() setEditable:(mode == wxDATAVIEW_CELL_EDITABLE)];
2527 void wxDataViewRenderer::SetNativeData(wxDataViewRendererNativeData* newNativeDataPtr)
2529 delete m_NativeDataPtr;
2530 m_NativeDataPtr = newNativeDataPtr;
2533 void wxDataViewRenderer::EnableEllipsize(wxEllipsizeMode mode)
2535 // we need to store this value to apply it to the columns headerCell in
2536 // CreateNativeColumn()
2537 GetNativeData()->SetEllipsizeMode(mode);
2539 // but we may already apply it to the column cell which will be used for
2541 GetNativeData()->ApplyLineBreakMode(GetNativeData()->GetColumnCell());
2544 wxEllipsizeMode wxDataViewRenderer::GetEllipsizeMode() const
2546 return GetNativeData()->GetEllipsizeMode();
2550 wxDataViewRenderer::OSXOnCellChanged(NSObject *object,
2551 const wxDataViewItem& item,
2554 // TODO: we probably should get rid of this code entirely and make this
2555 // function pure virtual, but currently we still have some native
2556 // renderers (wxDataViewChoiceRenderer) which don't override it and
2557 // there is also wxDataViewCustomRenderer for which it's not obvious
2558 // how it should be implemented so keep this "auto-deduction" of
2559 // variant type from NSObject for now
2562 if ( [object isKindOfClass:[NSString class]] )
2563 value = ObjectToString(object);
2564 else if ( [object isKindOfClass:[NSNumber class]] )
2565 value = ObjectToLong(object);
2566 else if ( [object isKindOfClass:[NSDate class]] )
2567 value = ObjectToDate(object);
2570 wxFAIL_MSG( wxString::Format
2572 "unknown value type %s",
2573 wxCFStringRef::AsString([object className])
2578 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2579 model->ChangeValue(value, item, col);
2582 void wxDataViewRenderer::OSXApplyAttr(const wxDataViewItemAttr& attr)
2584 wxDataViewRendererNativeData * const data = GetNativeData();
2585 NSCell * const cell = data->GetItemCell();
2587 // set the font and text colour to use: we need to do it if we had ever
2588 // changed them before, even if this item itself doesn't have any special
2589 // attributes as otherwise it would reuse the attributes from the previous
2590 // cell rendered using the same renderer
2591 NSFont *font = NULL;
2592 NSColor *colText = NULL;
2594 if ( attr.HasFont() )
2596 font = data->GetOriginalFont();
2599 // this is the first time we're setting the font, remember the
2600 // original one before changing it
2602 data->SaveOriginalFont(font);
2607 // FIXME: using wxFont methods here doesn't work for some reason
2608 NSFontManager * const fm = [NSFontManager sharedFontManager];
2609 if ( attr.GetBold() )
2610 font = [fm convertFont:font toHaveTrait:NSBoldFontMask];
2611 if ( attr.GetItalic() )
2612 font = [fm convertFont:font toHaveTrait:NSItalicFontMask];
2614 //else: can't change font if the cell doesn't have any
2617 if ( attr.HasColour() )
2619 // we can set font for any cell but only NSTextFieldCell provides
2620 // a method for setting text colour so check that this method is
2621 // available before using it
2622 if ( [cell respondsToSelector:@selector(setTextColor:)] &&
2623 [cell respondsToSelector:@selector(textColor)] )
2625 if ( !data->GetOriginalTextColour() )
2627 // the cast to (untyped) id is safe because of the check above
2628 data->SaveOriginalTextColour([(id)cell textColor]);
2631 const wxColour& c = attr.GetColour();
2632 colText = [NSColor colorWithDeviceRed:c.Red() / 255.
2633 green:c.Green() / 255.
2634 blue:c.Blue() / 255.
2635 alpha:c.Alpha() / 255.];
2640 font = data->GetOriginalFont();
2642 colText = data->GetOriginalTextColour();
2645 [cell setFont:font];
2648 [(id)cell setTextColor:colText];
2651 void wxDataViewRenderer::OSXApplyEnabled(bool enabled)
2653 [GetNativeData()->GetItemCell() setEnabled:enabled];
2656 IMPLEMENT_ABSTRACT_CLASS(wxDataViewRenderer,wxDataViewRendererBase)
2658 // ---------------------------------------------------------
2659 // wxDataViewCustomRenderer
2660 // ---------------------------------------------------------
2661 wxDataViewCustomRenderer::wxDataViewCustomRenderer(const wxString& varianttype,
2662 wxDataViewCellMode mode,
2664 : wxDataViewCustomRendererBase(varianttype, mode, align),
2665 m_editorCtrlPtr(NULL),
2668 SetNativeData(new wxDataViewRendererNativeData([[wxCustomCell alloc] init]));
2671 bool wxDataViewCustomRenderer::MacRender()
2673 [GetNativeData()->GetItemCell() setObjectValue:[[[wxCustomRendererObject alloc] initWithRenderer:this] autorelease]];
2677 void wxDataViewCustomRenderer::OSXApplyAttr(const wxDataViewItemAttr& attr)
2679 // simply save the attribute so that it could be reused from our Render()
2682 // it's not necessary to call the base class version which sets the cell
2683 // properties to correspond to this attribute because we currently don't
2684 // use any NSCell methods in custom renderers anyhow but if we ever start
2685 // doing this (e.g. override RenderText() here to use NSTextFieldCell
2686 // methods), then we should pass it on to wxDataViewRenderer here
2689 IMPLEMENT_ABSTRACT_CLASS(wxDataViewCustomRenderer, wxDataViewRenderer)
2691 // ---------------------------------------------------------
2692 // wxDataViewTextRenderer
2693 // ---------------------------------------------------------
2694 wxDataViewTextRenderer::wxDataViewTextRenderer(const wxString& varianttype,
2695 wxDataViewCellMode mode,
2697 : wxDataViewRenderer(varianttype,mode,align)
2699 NSTextFieldCell* cell;
2702 cell = [[NSTextFieldCell alloc] init];
2703 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2704 SetNativeData(new wxDataViewRendererNativeData(cell));
2708 bool wxDataViewTextRenderer::MacRender()
2710 if (GetValue().GetType() == GetVariantType())
2712 [GetNativeData()->GetItemCell() setObjectValue:wxCFStringRef(GetValue().GetString()).AsNSString()];
2717 wxFAIL_MSG(wxString("Text renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2723 wxDataViewTextRenderer::OSXOnCellChanged(NSObject *value,
2724 const wxDataViewItem& item,
2727 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2728 model->ChangeValue(ObjectToString(value), item, col);
2731 IMPLEMENT_CLASS(wxDataViewTextRenderer,wxDataViewRenderer)
2733 // ---------------------------------------------------------
2734 // wxDataViewBitmapRenderer
2735 // ---------------------------------------------------------
2736 wxDataViewBitmapRenderer::wxDataViewBitmapRenderer(const wxString& varianttype,
2737 wxDataViewCellMode mode,
2739 : wxDataViewRenderer(varianttype,mode,align)
2744 cell = [[NSImageCell alloc] init];
2745 SetNativeData(new wxDataViewRendererNativeData(cell));
2749 // This method returns 'true' if
2750 // - the passed bitmap is valid and it could be assigned to the native data
2752 // - the passed bitmap is invalid (or is not initialized); this case
2753 // simulates a non-existing bitmap.
2754 // In all other cases the method returns 'false'.
2755 bool wxDataViewBitmapRenderer::MacRender()
2757 wxCHECK_MSG(GetValue().GetType() == GetVariantType(),false,wxString("Bitmap renderer cannot render value; value type: ") << GetValue().GetType());
2761 bitmap << GetValue();
2763 [GetNativeData()->GetItemCell() setObjectValue:[[bitmap.GetNSImage() retain] autorelease]];
2767 IMPLEMENT_CLASS(wxDataViewBitmapRenderer,wxDataViewRenderer)
2769 // -------------------------------------
2770 // wxDataViewChoiceRenderer
2771 // -------------------------------------
2772 wxDataViewChoiceRenderer::wxDataViewChoiceRenderer(const wxArrayString& choices,
2773 wxDataViewCellMode mode,
2775 : wxDataViewRenderer(wxT("string"), mode, alignment),
2778 NSPopUpButtonCell* cell;
2781 cell = [[NSPopUpButtonCell alloc] init];
2782 [cell setControlSize:NSMiniControlSize];
2783 [cell setFont:[[NSFont fontWithName:[[cell font] fontName] size:[NSFont systemFontSizeForControlSize:NSMiniControlSize]] autorelease]];
2784 for (size_t i=0; i<choices.GetCount(); ++i)
2785 [cell addItemWithTitle:[[wxCFStringRef(choices[i]).AsNSString() retain] autorelease]];
2786 SetNativeData(new wxDataViewRendererNativeData(cell));
2790 bool wxDataViewChoiceRenderer::MacRender()
2792 if (GetValue().GetType() == GetVariantType())
2794 [((NSPopUpButtonCell*) GetNativeData()->GetItemCell()) selectItemWithTitle:[[wxCFStringRef(GetValue().GetString()).AsNSString() retain] autorelease]];
2799 wxFAIL_MSG(wxString("Choice renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2804 IMPLEMENT_CLASS(wxDataViewChoiceRenderer,wxDataViewRenderer)
2806 // ---------------------------------------------------------
2807 // wxDataViewDateRenderer
2808 // ---------------------------------------------------------
2810 wxDataViewDateRenderer::wxDataViewDateRenderer(const wxString& varianttype,
2811 wxDataViewCellMode mode,
2813 : wxDataViewRenderer(varianttype,mode,align)
2815 NSTextFieldCell* cell;
2817 NSDateFormatter* dateFormatter;
2820 dateFormatter = [[NSDateFormatter alloc] init];
2821 [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
2822 [dateFormatter setDateStyle:NSDateFormatterShortStyle];
2823 cell = [[NSTextFieldCell alloc] init];
2824 [cell setFormatter:dateFormatter];
2825 SetNativeData(new wxDataViewRendererNativeData(cell,[NSDate dateWithString:@"2000-12-30 20:00:00 +0000"]));
2827 [dateFormatter release];
2830 bool wxDataViewDateRenderer::MacRender()
2832 if (GetValue().GetType() == GetVariantType())
2834 if (GetValue().GetDateTime().IsValid())
2836 // -- find best fitting style to show the date --
2837 // as the style should be identical for all cells a reference date
2838 // instead of the actual cell's date value is used for all cells;
2839 // this reference date is stored in the renderer's native data
2840 // section for speed purposes; otherwise, the reference date's
2841 // string has to be recalculated for each item that may become
2842 // timewise long if a lot of rows using dates exist; the algorithm
2843 // has the preference to display as much information as possible
2844 // in the first instance; but as this is often impossible due to
2845 // space restrictions the style is shortened per loop; finally, if
2846 // the shortest time and date format does not fit into the cell
2847 // the time part is dropped; remark: the time part itself is not
2848 // modified per iteration loop and only uses the short style,
2849 // means that only the hours and minutes are being shown
2851 // GetObject() returns a date for testing the size of a date object
2852 [GetNativeData()->GetItemCell() setObjectValue:GetNativeData()->GetObject()];
2853 [[GetNativeData()->GetItemCell() formatter] setTimeStyle:NSDateFormatterShortStyle];
2854 for (int dateFormatterStyle=4; dateFormatterStyle>0; --dateFormatterStyle)
2856 [[GetNativeData()->GetItemCell() formatter] setDateStyle:(NSDateFormatterStyle)dateFormatterStyle];
2857 if (dateFormatterStyle == 1)
2859 // if the shortest style for displaying the date and time
2860 // is too long to be fully visible remove the time part of
2862 if ([GetNativeData()->GetItemCell() cellSize].width > [GetNativeData()->GetColumnPtr() width])
2863 [[GetNativeData()->GetItemCell() formatter] setTimeStyle:NSDateFormatterNoStyle];
2865 // basically not necessary as the loop would end anyway
2866 // but let's save the last comparison
2870 else if ([GetNativeData()->GetItemCell() cellSize].width <= [GetNativeData()->GetColumnPtr() width])
2873 // set data (the style is set by the previous loop); on OSX the
2874 // date has to be specified with respect to UTC; in wxWidgets the
2875 // date is always entered in the local timezone; so, we have to do
2876 // a conversion from the local to UTC timezone when adding the
2877 // seconds to 1970-01-01 UTC:
2878 [GetNativeData()->GetItemCell() setObjectValue:[NSDate dateWithTimeIntervalSince1970:GetValue().GetDateTime().ToUTC().Subtract(wxDateTime(1,wxDateTime::Jan,1970)).GetSeconds().ToDouble()]];
2884 wxFAIL_MSG(wxString("Date renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2890 wxDataViewDateRenderer::OSXOnCellChanged(NSObject *value,
2891 const wxDataViewItem& item,
2894 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2895 model->ChangeValue(ObjectToDate(value), item, col);
2898 IMPLEMENT_ABSTRACT_CLASS(wxDataViewDateRenderer,wxDataViewRenderer)
2900 // ---------------------------------------------------------
2901 // wxDataViewIconTextRenderer
2902 // ---------------------------------------------------------
2903 wxDataViewIconTextRenderer::wxDataViewIconTextRenderer(const wxString& varianttype,
2904 wxDataViewCellMode mode,
2906 : wxDataViewRenderer(varianttype,mode)
2908 wxImageTextCell* cell;
2911 cell = [[wxImageTextCell alloc] init];
2912 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2913 SetNativeData(new wxDataViewRendererNativeData(cell));
2917 bool wxDataViewIconTextRenderer::MacRender()
2919 if (GetValue().GetType() == GetVariantType())
2921 wxDataViewIconText iconText;
2923 wxImageTextCell* cell;
2925 cell = (wxImageTextCell*) GetNativeData()->GetItemCell();
2926 iconText << GetValue();
2927 if (iconText.GetIcon().IsOk())
2928 [cell setImage:[[wxBitmap(iconText.GetIcon()).GetNSImage() retain] autorelease]];
2929 [cell setStringValue:[[wxCFStringRef(iconText.GetText()).AsNSString() retain] autorelease]];
2934 wxFAIL_MSG(wxString("Icon & text renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2940 wxDataViewIconTextRenderer::OSXOnCellChanged(NSObject *value,
2941 const wxDataViewItem& item,
2944 wxVariant valueIconText;
2945 valueIconText << wxDataViewIconText(ObjectToString(value));
2947 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2948 model->ChangeValue(valueIconText, item, col);
2951 IMPLEMENT_ABSTRACT_CLASS(wxDataViewIconTextRenderer,wxDataViewRenderer)
2953 // ---------------------------------------------------------
2954 // wxDataViewToggleRenderer
2955 // ---------------------------------------------------------
2956 wxDataViewToggleRenderer::wxDataViewToggleRenderer(const wxString& varianttype,
2957 wxDataViewCellMode mode,
2959 : wxDataViewRenderer(varianttype,mode)
2964 cell = [[NSButtonCell alloc] init];
2965 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2966 [cell setButtonType:NSSwitchButton];
2967 [cell setImagePosition:NSImageOnly];
2968 SetNativeData(new wxDataViewRendererNativeData(cell));
2972 bool wxDataViewToggleRenderer::MacRender()
2974 if (GetValue().GetType() == GetVariantType())
2976 [GetNativeData()->GetItemCell() setIntValue:GetValue().GetLong()];
2981 wxFAIL_MSG(wxString("Toggle renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2987 wxDataViewToggleRenderer::OSXOnCellChanged(NSObject *value,
2988 const wxDataViewItem& item,
2991 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2992 model->ChangeValue(ObjectToBool(value), item, col);
2995 IMPLEMENT_ABSTRACT_CLASS(wxDataViewToggleRenderer,wxDataViewRenderer)
2997 // ---------------------------------------------------------
2998 // wxDataViewProgressRenderer
2999 // ---------------------------------------------------------
3000 wxDataViewProgressRenderer::wxDataViewProgressRenderer(const wxString& label,
3001 const wxString& varianttype,
3002 wxDataViewCellMode mode,
3004 : wxDataViewRenderer(varianttype,mode,align)
3008 NSLevelIndicatorCell* cell;
3010 cell = [[NSLevelIndicatorCell alloc] initWithLevelIndicatorStyle:NSContinuousCapacityLevelIndicatorStyle];
3011 [cell setMinValue:0];
3012 [cell setMaxValue:100];
3013 SetNativeData(new wxDataViewRendererNativeData(cell));
3017 bool wxDataViewProgressRenderer::MacRender()
3019 if (GetValue().GetType() == GetVariantType())
3021 [GetNativeData()->GetItemCell() setIntValue:GetValue().GetLong()];
3026 wxFAIL_MSG(wxString("Progress renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
3032 wxDataViewProgressRenderer::OSXOnCellChanged(NSObject *value,
3033 const wxDataViewItem& item,
3036 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
3037 model->ChangeValue(ObjectToLong(value), item, col);
3040 IMPLEMENT_ABSTRACT_CLASS(wxDataViewProgressRenderer,wxDataViewRenderer)
3042 // ---------------------------------------------------------
3044 // ---------------------------------------------------------
3046 wxDataViewColumn::wxDataViewColumn(const wxString& title,
3047 wxDataViewRenderer* renderer,
3048 unsigned int model_column,
3052 : wxDataViewColumnBase(renderer, model_column),
3053 m_NativeDataPtr(new wxDataViewColumnNativeData()),
3056 InitCommon(width, align, flags);
3057 if (renderer && !renderer->IsCustomRenderer() &&
3058 (renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
3059 renderer->SetAlignment(align);
3062 wxDataViewColumn::wxDataViewColumn(const wxBitmap& bitmap,
3063 wxDataViewRenderer* renderer,
3064 unsigned int model_column,
3068 : wxDataViewColumnBase(bitmap, renderer, model_column),
3069 m_NativeDataPtr(new wxDataViewColumnNativeData())
3071 InitCommon(width, align, flags);
3072 if (renderer && !renderer->IsCustomRenderer() &&
3073 (renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
3074 renderer->SetAlignment(align);
3077 wxDataViewColumn::~wxDataViewColumn()
3079 delete m_NativeDataPtr;
3082 int wxDataViewColumn::GetWidth() const
3084 return [m_NativeDataPtr->GetNativeColumnPtr() width];
3087 bool wxDataViewColumn::IsSortKey() const
3089 NSTableColumn *nsCol = GetNativeData()->GetNativeColumnPtr();
3090 return nsCol && ([nsCol sortDescriptorPrototype] != nil);
3093 void wxDataViewColumn::SetAlignment(wxAlignment align)
3095 m_alignment = align;
3096 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
3097 if (m_renderer && !m_renderer->IsCustomRenderer() &&
3098 (m_renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
3099 m_renderer->SetAlignment(align);
3102 void wxDataViewColumn::SetBitmap(const wxBitmap& bitmap)
3104 // bitmaps and titles cannot exist at the same time - if the bitmap is set
3105 // the title is removed:
3106 m_title = wxEmptyString;
3107 wxDataViewColumnBase::SetBitmap(bitmap);
3108 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setImage:[[bitmap.GetNSImage() retain] autorelease]];
3111 void wxDataViewColumn::SetMaxWidth(int maxWidth)
3113 m_maxWidth = maxWidth;
3114 [m_NativeDataPtr->GetNativeColumnPtr() setMaxWidth:maxWidth];
3117 void wxDataViewColumn::SetMinWidth(int minWidth)
3119 m_minWidth = minWidth;
3120 [m_NativeDataPtr->GetNativeColumnPtr() setMinWidth:minWidth];
3123 void wxDataViewColumn::SetReorderable(bool reorderable)
3125 wxUnusedVar(reorderable);
3128 void wxDataViewColumn::SetHidden(bool hidden)
3130 // How to set flag here?
3132 [m_NativeDataPtr->GetNativeColumnPtr() setHidden:hidden];
3135 bool wxDataViewColumn::IsHidden() const
3137 return [m_NativeDataPtr->GetNativeColumnPtr() isHidden];
3140 void wxDataViewColumn::SetResizeable(bool resizeable)
3142 wxDataViewColumnBase::SetResizeable(resizeable);
3144 [m_NativeDataPtr->GetNativeColumnPtr() setResizingMask:NSTableColumnUserResizingMask];
3146 [m_NativeDataPtr->GetNativeColumnPtr() setResizingMask:NSTableColumnNoResizing];
3149 void wxDataViewColumn::SetSortable(bool sortable)
3151 // wxDataViewColumnBase::SetSortable(sortable);
3152 // Avoid endless recursion and just set the flag here
3154 m_flags |= wxDATAVIEW_COL_SORTABLE;
3156 m_flags &= ~wxDATAVIEW_COL_SORTABLE;
3159 void wxDataViewColumn::SetSortOrder(bool ascending)
3161 if (m_ascending != ascending)
3163 m_ascending = ascending;
3166 // change sorting order:
3167 NSArray* sortDescriptors;
3168 NSSortDescriptor* sortDescriptor;
3169 NSTableColumn* tableColumn;
3171 tableColumn = m_NativeDataPtr->GetNativeColumnPtr();
3172 sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[[tableColumn sortDescriptorPrototype] key] ascending:m_ascending];
3173 sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
3174 [tableColumn setSortDescriptorPrototype:sortDescriptor];
3175 [[tableColumn tableView] setSortDescriptors:sortDescriptors];
3176 [sortDescriptor release];
3181 void wxDataViewColumn::SetTitle(const wxString& title)
3183 // bitmaps and titles cannot exist at the same time - if the title is set
3184 // the bitmap is removed:
3185 wxDataViewColumnBase::SetBitmap(wxBitmap());
3187 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setStringValue:[[wxCFStringRef(title).AsNSString() retain] autorelease]];
3190 void wxDataViewColumn::SetWidth(int width)
3196 case wxCOL_WIDTH_AUTOSIZE:
3197 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
3200 wxCocoaDataViewControl *peer = static_cast<wxCocoaDataViewControl*>(GetOwner()->GetPeer());
3201 peer->FitColumnWidthToContent(GetOwner()->GetColumnPosition(this));
3205 // fall through if unsupported (OSX < 10.5) or not yet settable
3207 case wxCOL_WIDTH_DEFAULT:
3208 width = wxDVC_DEFAULT_WIDTH;
3212 [m_NativeDataPtr->GetNativeColumnPtr() setWidth:width];
3217 void wxDataViewColumn::SetAsSortKey(bool WXUNUSED(sort))
3219 // see wxGTK native wxDataViewColumn implementation
3220 wxFAIL_MSG("not implemented");
3223 void wxDataViewColumn::SetNativeData(wxDataViewColumnNativeData* newNativeDataPtr)
3225 delete m_NativeDataPtr;
3226 m_NativeDataPtr = newNativeDataPtr;
3229 #endif // (wxUSE_DATAVIEWCTRL == 1) && !defined(wxUSE_GENERICDATAVIEWCTRL)