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 // Get the identifier we use for the specified column. This should be used
160 // for finding columns from identifier only, to initialize the identifier
161 // of a new column use initWithColumnPointer below instead.
162 +(NSString*) identifierForColumnPointer:(const wxDataViewColumn*)column;
164 // Initialize the column with the given pointer to the associated
165 // wxDataViewColumn. This pointer can later be retrieved using
167 -(id) initWithColumnPointer:(const wxDataViewColumn*)column;
169 // Retrieve the associated column.
170 -(wxDataViewColumn*) getColumnPointer;
172 -(id) dataCellForRow:(NSInteger)row;
175 @implementation wxDVCNSTableColumn
177 +(NSString*) identifierForColumnPointer:(const wxDataViewColumn*)column
179 // Starting from OS X 10.7 the column identifier must be an NSString and
180 // not just some arbitrary object, so we serialize the pointer into the
181 // string. Notice the use of NSInteger which is big enough to store a
182 // pointer in both 32 and 64 bit builds.
183 return [NSString stringWithFormat:@"%lu", reinterpret_cast<NSUInteger>(column)];
186 -(id) initWithColumnPointer:(const wxDataViewColumn*)column
188 [self initWithIdentifier: [wxDVCNSTableColumn identifierForColumnPointer:column]];
192 -(wxDataViewColumn*) getColumnPointer
194 // The case to NSString is needed for OS X < 10.7.
195 return reinterpret_cast<wxDataViewColumn*>(
196 [static_cast<NSString*>([self identifier]) integerValue]);
199 -(id) dataCellForRow:(NSInteger)row
201 // what we want to do here is to simply return nil for the cells which
202 // shouldn't show anything as otherwise we would show e.g. empty combo box
203 // or progress cells in the columns using the corresponding types even for
204 // the container rows which is wrong
206 const wxDataViewColumn * const dvCol = [self getColumnPointer];
208 const wxDataViewCtrl * const dvc = dvCol->GetOwner();
209 const wxCocoaDataViewControl * const
210 peer = static_cast<wxCocoaDataViewControl *>(dvc->GetPeer());
213 // once we do have everything, simply ask NSOutlineView for the item...
214 const id item = peer->GetItemAtRow(row);
217 // ... and if it succeeded, ask the model whether it has any value
218 wxDataViewItem dvItem(wxDataViewItemFromItem(item));
220 if ( !dvc->GetModel()->HasValue(dvItem, dvCol->GetModelColumn()) )
224 return [super dataCellForRow:row];
229 // ============================================================================
231 // ============================================================================
236 // convert from NSObject to different C++ types: all these functions check
237 // that the conversion really makes sense and assert if it doesn't
238 wxString ObjectToString(NSObject *object)
240 wxCHECK_MSG( [object isKindOfClass:[NSString class]], "",
243 "string expected but got %s",
244 wxCFStringRef::AsString([object className])
247 return wxCFStringRef([((NSString*) object) retain]).AsString();
250 bool ObjectToBool(NSObject *object)
252 // actually the value must be of NSCFBoolean class but it's private so we
253 // can't check for it directly
254 wxCHECK_MSG( [object isKindOfClass:[NSNumber class]], false,
257 "number expected but got %s",
258 wxCFStringRef::AsString([object className])
261 return [(NSNumber *)object boolValue];
264 long ObjectToLong(NSObject *object)
266 wxCHECK_MSG( [object isKindOfClass:[NSNumber class]], -1,
269 "number expected but got %s",
270 wxCFStringRef::AsString([object className])
273 return [(NSNumber *)object longValue];
276 wxDateTime ObjectToDate(NSObject *object)
278 wxCHECK_MSG( [object isKindOfClass:[NSDate class]], wxInvalidDateTime,
281 "date expected but got %s",
282 wxCFStringRef::AsString([object className])
285 // get the number of seconds since 1970-01-01 UTC and this is the only
286 // way to convert a double to a wxLongLong
287 const wxLongLong seconds = [((NSDate*) object) timeIntervalSince1970];
289 wxDateTime dt(1, wxDateTime::Jan, 1970);
290 dt.Add(wxTimeSpan(0,0,seconds));
292 // the user has entered a date in the local timezone but seconds
293 // contains the number of seconds from date in the local timezone
294 // since 1970-01-01 UTC; therefore, the timezone information has to be
295 // transferred to wxWidgets, too:
296 dt.MakeFromTimezone(wxDateTime::UTC);
301 NSInteger CompareItems(id item1, id item2, void* context)
303 NSArray* const sortDescriptors = (NSArray*) context;
305 NSUInteger const count = [sortDescriptors count];
307 NSInteger result = NSOrderedSame;
308 for ( NSUInteger i = 0; i < count && result == NSOrderedSame; ++i )
310 wxSortDescriptorObject* const
311 sortDescriptor = (wxSortDescriptorObject*)
312 [sortDescriptors objectAtIndex:i];
314 int rc = [sortDescriptor modelPtr]->Compare
316 wxDataViewItemFromItem(item1),
317 wxDataViewItemFromItem(item2),
318 [sortDescriptor columnPtr]->GetModelColumn(),
319 [sortDescriptor ascending] == YES
323 result = NSOrderedAscending;
325 result = NSOrderedDescending;
331 NSTextAlignment ConvertToNativeHorizontalTextAlignment(int alignment)
333 if (alignment & wxALIGN_CENTER_HORIZONTAL)
334 return NSCenterTextAlignment;
335 else if (alignment & wxALIGN_RIGHT)
336 return NSRightTextAlignment;
338 return NSLeftTextAlignment;
341 NSTableColumn* CreateNativeColumn(const wxDataViewColumn *column)
343 wxDataViewRenderer * const renderer = column->GetRenderer();
345 wxCHECK_MSG( renderer, NULL, "column should have a renderer" );
347 wxDVCNSTableColumn * const nativeColumn(
348 [[wxDVCNSTableColumn alloc] initWithColumnPointer: column]
351 // setting the size related parameters:
353 if (column->IsResizeable())
355 resizingMask = NSTableColumnUserResizingMask;
356 [nativeColumn setMinWidth:column->GetMinWidth()];
357 [nativeColumn setMaxWidth:column->GetMaxWidth()];
359 else // column is not resizable [by user]
361 // if the control doesn't show a header, make the columns resize
362 // automatically, this is particularly important for the single column
363 // controls (such as wxDataViewTreeCtrl) as their unique column should
364 // always take up all the available splace
365 resizingMask = column->GetOwner()->HasFlag(wxDV_NO_HEADER)
366 ? NSTableColumnAutoresizingMask
367 : NSTableColumnNoResizing;
369 [nativeColumn setResizingMask:resizingMask];
371 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
372 // setting the visibility:
373 [nativeColumn setHidden:static_cast<BOOL>(column->IsHidden())];
376 wxDataViewRendererNativeData * const renderData = renderer->GetNativeData();
378 // setting the header:
379 [[nativeColumn headerCell] setAlignment:
380 ConvertToNativeHorizontalTextAlignment(column->GetAlignment())];
381 [[nativeColumn headerCell] setStringValue:
382 [[wxCFStringRef(column->GetTitle()).AsNSString() retain] autorelease]];
383 renderData->ApplyLineBreakMode([nativeColumn headerCell]);
385 // setting data cell's properties:
386 [[nativeColumn dataCell] setWraps:NO];
387 // setting the default data cell:
388 [nativeColumn setDataCell:renderData->GetColumnCell()];
389 // setting the editablility:
390 const bool isEditable = renderer->GetMode() == wxDATAVIEW_CELL_EDITABLE;
392 [nativeColumn setEditable:isEditable];
393 [[nativeColumn dataCell] setEditable:isEditable];
398 } // anonymous namespace
400 // ============================================================================
401 // Public helper functions for dataview implementation on OSX
402 // ============================================================================
404 wxWidgetImplType* CreateDataView(wxWindowMac* wxpeer,
405 wxWindowMac* WXUNUSED(parent),
406 wxWindowID WXUNUSED(id),
410 long WXUNUSED(extraStyle))
412 return new wxCocoaDataViewControl(wxpeer,pos,size,style);
415 // ============================================================================
416 // wxSortDescriptorObject
417 // ============================================================================
419 @implementation wxSortDescriptorObject
432 initWithModelPtr:(wxDataViewModel*)initModelPtr
433 sortingColumnPtr:(wxDataViewColumn*)initColumnPtr
434 ascending:(BOOL)sortAscending
436 self = [super initWithKey:@"dummy" ascending:sortAscending];
439 columnPtr = initColumnPtr;
440 modelPtr = initModelPtr;
445 -(id) copyWithZone:(NSZone*)zone
447 wxSortDescriptorObject* copy;
450 copy = [super copyWithZone:zone];
451 copy->columnPtr = columnPtr;
452 copy->modelPtr = modelPtr;
458 // access to model column's index
460 -(wxDataViewColumn*) columnPtr
465 -(wxDataViewModel*) modelPtr
470 -(void) setColumnPtr:(wxDataViewColumn*)newColumnPtr
472 columnPtr = newColumnPtr;
475 -(void) setModelPtr:(wxDataViewModel*)newModelPtr
477 modelPtr = newModelPtr;
482 // ============================================================================
483 // wxCocoaOutlineDataSource
484 // ============================================================================
485 @implementation wxCocoaOutlineDataSource
488 // constructors / destructor
495 implementation = NULL;
498 currentParentItem = nil;
500 children = [[NSMutableArray alloc] init];
501 items = [[NSMutableSet alloc] init];
508 [currentParentItem release];
517 // methods of informal protocol:
520 outlineView:(NSOutlineView*)outlineView
521 acceptDrop:(id<NSDraggingInfo>)info
522 item:(id)item childIndex:(NSInteger)index
524 wxUnusedVar(outlineView);
527 NSArray* supportedTypes(
528 [NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]
531 NSPasteboard* pasteboard([info draggingPasteboard]);
533 NSString* bestType([pasteboard availableTypeFromArray:supportedTypes]);
535 if ( bestType == nil )
538 wxDataViewCtrl * const dvc(implementation->GetDataViewCtrl());
540 wxCHECK_MSG( dvc, false,
541 "Pointer to data view control not set correctly." );
542 wxCHECK_MSG( dvc->GetModel(), false,
543 "Pointer to model not set correctly." );
545 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_DROP, dvc->GetId());
546 event.SetEventObject(dvc);
547 event.SetItem(wxDataViewItemFromItem(item));
548 event.SetModel(dvc->GetModel());
550 BOOL dragSuccessful = false;
551 if ( [bestType compare:DataViewPboardType] == NSOrderedSame )
553 NSArray* dataArray((NSArray*)
554 [pasteboard propertyListForType:DataViewPboardType]);
555 NSUInteger indexDraggedItem, noOfDraggedItems([dataArray count]);
557 indexDraggedItem = 0;
558 while (indexDraggedItem < noOfDraggedItems)
560 wxDataObjectComposite* dataObjects(
561 implementation->GetDnDDataObjects((NSData*)
562 [dataArray objectAtIndex:indexDraggedItem]));
564 if (dataObjects && (dataObjects->GetFormatCount() > 0))
566 wxMemoryBuffer buffer;
568 // copy data into data object:
569 event.SetDataObject(dataObjects);
571 implementation->GetDnDDataFormat(dataObjects));
572 // copy data into buffer:
573 dataObjects->GetDataHere(
574 event.GetDataFormat().GetType(),
575 buffer.GetWriteBuf(event.GetDataSize()));
576 buffer.UngetWriteBuf(event.GetDataSize());
577 event.SetDataBuffer(buffer.GetData());
578 // finally, send event:
579 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
581 dragSuccessful = true;
586 dragSuccessful = true;
587 indexDraggedItem = noOfDraggedItems; // stop loop
592 dragSuccessful = false;
593 indexDraggedItem = noOfDraggedItems; // stop loop
601 // needed to convert internally used UTF-16 representation to a UTF-8
604 wxDataObjectComposite* dataObjects (new wxDataObjectComposite());
605 wxTextDataObject* textDataObject(new wxTextDataObject());
607 osxData = ::CFStringCreateExternalRepresentation
610 (CFStringRef)[pasteboard stringForType:NSStringPboardType],
611 kCFStringEncodingUTF8,
614 if (textDataObject->SetData(::CFDataGetLength(osxData),
615 ::CFDataGetBytePtr(osxData)))
616 dataObjects->Add(textDataObject);
618 delete textDataObject;
619 // send event if data could be copied:
620 if (dataObjects->GetFormatCount() > 0)
622 event.SetDataObject(dataObjects);
623 event.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
624 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
625 dragSuccessful = true;
627 dragSuccessful = false;
630 dragSuccessful = false;
632 ::CFRelease(osxData);
635 return dragSuccessful;
638 -(id) outlineView:(NSOutlineView*)outlineView
639 child:(NSInteger)index
642 wxUnusedVar(outlineView);
644 if ((item == currentParentItem) &&
645 (index < ((NSInteger) [self getChildCount])))
646 return [self getChild:index];
648 wxDataViewItemArray dataViewChildren;
650 wxCHECK_MSG( model, 0, "Valid model in data source does not exist." );
651 model->GetChildren(wxDataViewItemFromMaybeNilItem(item), dataViewChildren);
652 [self bufferItem:item withChildren:&dataViewChildren];
653 if ([sortDescriptors count] > 0)
654 [children sortUsingFunction:CompareItems context:sortDescriptors];
655 return [self getChild:index];
658 -(BOOL) outlineView:(NSOutlineView*)outlineView isItemExpandable:(id)item
660 wxUnusedVar(outlineView);
662 wxCHECK_MSG( model, 0, "Valid model in data source does not exist." );
663 return model->IsContainer(wxDataViewItemFromItem(item));
666 -(NSInteger) outlineView:(NSOutlineView*)outlineView numberOfChildrenOfItem:(id)item
668 wxUnusedVar(outlineView);
670 NSInteger noOfChildren;
672 wxDataViewItemArray dataViewChildren;
675 wxCHECK_MSG( model, 0, "Valid model in data source does not exist." );
676 noOfChildren = model->GetChildren(wxDataViewItemFromMaybeNilItem(item),
678 [self bufferItem:item withChildren:&dataViewChildren];
679 if ([sortDescriptors count] > 0)
680 [children sortUsingFunction:CompareItems context:sortDescriptors];
685 outlineView:(NSOutlineView*)outlineView
686 objectValueForTableColumn:(NSTableColumn*)tableColumn
689 wxUnusedVar(outlineView);
691 wxCHECK_MSG( model, nil, "Valid model in data source does not exist." );
693 wxDataViewColumn* const
694 col([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
695 const unsigned colIdx = col->GetModelColumn();
697 wxDataViewItem dataViewItem(wxDataViewItemFromItem(item));
699 if ( model->HasValue(dataViewItem, colIdx) )
702 model->GetValue(value,dataViewItem, colIdx);
703 col->GetRenderer()->SetValue(value);
710 outlineView:(NSOutlineView*)outlineView
711 setObjectValue:(id)object
712 forTableColumn:(NSTableColumn*)tableColumn
715 wxUnusedVar(outlineView);
717 wxDataViewColumn* const
718 col([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
721 OSXOnCellChanged(object, wxDataViewItemFromItem(item), col->GetModelColumn());
724 -(void) outlineView:(NSOutlineView*)outlineView sortDescriptorsDidChange:(NSArray*)oldDescriptors
726 wxUnusedVar(oldDescriptors);
728 // Warning: the new sort descriptors are guaranteed to be only of type
729 // NSSortDescriptor! Therefore, the sort descriptors for the data source
730 // have to be converted.
731 NSArray* newDescriptors;
733 NSMutableArray* wxSortDescriptors;
735 NSUInteger noOfDescriptors;
737 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
740 // convert NSSortDescriptors to wxSortDescriptorObjects:
741 newDescriptors = [outlineView sortDescriptors];
742 noOfDescriptors = [newDescriptors count];
743 wxSortDescriptors = [NSMutableArray arrayWithCapacity:noOfDescriptors];
744 for (NSUInteger i=0; i<noOfDescriptors; ++i)
746 NSSortDescriptor* const newDescriptor = [newDescriptors objectAtIndex:i];
748 [wxSortDescriptors addObject:[[[wxSortDescriptorObject alloc] initWithModelPtr:model
749 sortingColumnPtr:dvc->GetColumn([[newDescriptor key] intValue])
750 ascending:[newDescriptor ascending]] autorelease]];
752 [(wxCocoaOutlineDataSource*)[outlineView dataSource] setSortDescriptors:wxSortDescriptors];
754 // send first the event to wxWidgets that the sorting has changed so that
755 // the program can do special actions before the sorting actually starts:
756 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_COLUMN_SORTED,dvc->GetId()); // variable definition
758 event.SetEventObject(dvc);
759 if (noOfDescriptors > 0)
761 wxDataViewColumn* const col = [[wxSortDescriptors objectAtIndex:0] columnPtr];
763 event.SetColumn(dvc->GetColumnPosition(col));
764 event.SetDataViewColumn(col);
766 dvc->GetEventHandler()->ProcessEvent(event);
768 // start re-ordering the data;
769 // children's buffer must be cleared first because it contains the old order:
770 [self clearChildren];
771 // sorting is done while reloading the data:
772 [outlineView reloadData];
775 -(NSDragOperation) outlineView:(NSOutlineView*)outlineView validateDrop:(id<NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
777 wxUnusedVar(outlineView);
780 NSArray* supportedTypes([NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]);
782 NSPasteboard* pasteboard([info draggingPasteboard]);
784 NSString* bestType([pasteboard availableTypeFromArray:supportedTypes]);
786 return NSDragOperationNone;
788 NSDragOperation dragOperation = NSDragOperationNone;
789 wxDataViewCtrl* const dvc(implementation->GetDataViewCtrl());
791 wxCHECK_MSG(dvc, false, "Pointer to data view control not set correctly.");
792 wxCHECK_MSG(dvc->GetModel(), false, "Pointer to model not set correctly.");
795 event(wxEVT_COMMAND_DATAVIEW_ITEM_DROP_POSSIBLE,dvc->GetId());
797 event.SetEventObject(dvc);
798 event.SetItem(wxDataViewItemFromItem(item));
799 event.SetModel(dvc->GetModel());
800 if ([bestType compare:DataViewPboardType] == NSOrderedSame)
802 NSArray* dataArray((NSArray*)[pasteboard propertyListForType:DataViewPboardType]);
803 NSUInteger indexDraggedItem, noOfDraggedItems([dataArray count]);
805 indexDraggedItem = 0;
806 while (indexDraggedItem < noOfDraggedItems)
808 wxDataObjectComposite* dataObjects(implementation->GetDnDDataObjects((NSData*)[dataArray objectAtIndex:indexDraggedItem]));
810 if (dataObjects && (dataObjects->GetFormatCount() > 0))
812 wxMemoryBuffer buffer;
814 // copy data into data object:
815 event.SetDataObject(dataObjects);
816 event.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
817 // copy data into buffer:
818 dataObjects->GetDataHere(event.GetDataFormat().GetType(),buffer.GetWriteBuf(event.GetDataSize()));
819 buffer.UngetWriteBuf(event.GetDataSize());
820 event.SetDataBuffer(buffer.GetData());
821 // finally, send event:
822 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
824 dragOperation = NSDragOperationEvery;
829 dragOperation = NSDragOperationNone;
830 indexDraggedItem = noOfDraggedItems; // stop loop
835 dragOperation = NSDragOperationNone;
836 indexDraggedItem = noOfDraggedItems; // stop loop
844 // needed to convert internally used UTF-16 representation to a UTF-8
847 wxDataObjectComposite* dataObjects (new wxDataObjectComposite());
848 wxTextDataObject* textDataObject(new wxTextDataObject());
850 osxData = ::CFStringCreateExternalRepresentation(kCFAllocatorDefault,(CFStringRef)[pasteboard stringForType:NSStringPboardType],kCFStringEncodingUTF8,32);
851 if (textDataObject->SetData(::CFDataGetLength(osxData),::CFDataGetBytePtr(osxData)))
852 dataObjects->Add(textDataObject);
854 delete textDataObject;
855 // send event if data could be copied:
856 if (dataObjects->GetFormatCount() > 0)
858 event.SetDataObject(dataObjects);
859 event.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
860 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
861 dragOperation = NSDragOperationEvery;
863 dragOperation = NSDragOperationNone;
866 dragOperation = NSDragOperationNone;
868 ::CFRelease(osxData);
872 return dragOperation;
875 -(BOOL) outlineView:(NSOutlineView*)outlineView writeItems:(NSArray*)writeItems toPasteboard:(NSPasteboard*)pasteboard
877 wxUnusedVar(outlineView);
879 // the pasteboard will be filled up with an array containing the data as
880 // returned by the events (including the data type) and a concatenation of
881 // text (string) data; the text data will only be put onto the pasteboard
882 // if for all items a string representation exists
883 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
885 wxDataViewItemArray dataViewItems;
888 wxCHECK_MSG(dvc, false,"Pointer to data view control not set correctly.");
889 wxCHECK_MSG(dvc->GetModel(),false,"Pointer to model not set correctly.");
891 if ([writeItems count] > 0)
893 bool dataStringAvailable(true); // a flag indicating if for all items a data string is available
894 NSMutableArray* dataArray = [NSMutableArray arrayWithCapacity:[writeItems count]]; // data of all items
895 wxString dataString; // contains the string data of all items
897 // send a begin drag event for all selected items and proceed with
898 // dragging unless the event is vetoed:
900 event(wxEVT_COMMAND_DATAVIEW_ITEM_BEGIN_DRAG,dvc->GetId());
902 event.SetEventObject(dvc);
903 event.SetModel(dvc->GetModel());
904 for (size_t itemCounter=0; itemCounter<[writeItems count]; ++itemCounter)
906 bool itemStringAvailable(false); // a flag indicating if for the current item a string is available
907 wxDataObjectComposite* itemObject(new wxDataObjectComposite()); // data object for current item
908 wxString itemString; // contains the TAB concatenated data of an item
911 wxDataViewItemFromItem([writeItems objectAtIndex:itemCounter]));
912 itemString = ::ConcatenateDataViewItemValues(dvc,event.GetItem());
913 itemObject->Add(new wxTextDataObject(itemString));
914 event.SetDataObject(itemObject);
915 // check if event has not been vetoed:
916 if (dvc->HandleWindowEvent(event) && event.IsAllowed() && (event.GetDataObject()->GetFormatCount() > 0))
918 size_t const noOfFormats = event.GetDataObject()->GetFormatCount();
919 wxDataFormat* dataFormats(new wxDataFormat[noOfFormats]);
921 event.GetDataObject()->GetAllFormats(dataFormats,wxDataObject::Get);
922 for (size_t formatCounter=0; formatCounter<noOfFormats; ++formatCounter)
924 // constant definitions for abbreviational purposes:
925 wxDataFormatId const idDataFormat = dataFormats[formatCounter].GetType();
926 size_t const dataSize = event.GetDataObject()->GetDataSize(idDataFormat);
927 size_t const dataBufferSize = sizeof(wxDataFormatId)+dataSize;
928 // variable definitions (used in all case statements):
929 wxMemoryBuffer dataBuffer(dataBufferSize);
931 dataBuffer.AppendData(&idDataFormat,sizeof(wxDataFormatId));
932 switch (idDataFormat)
935 // otherwise wxDF_UNICODETEXT already filled up
936 // the string; and the UNICODE representation has
938 if (!itemStringAvailable)
940 event.GetDataObject()->GetDataHere(wxDF_TEXT,dataBuffer.GetAppendBuf(dataSize));
941 dataBuffer.UngetAppendBuf(dataSize);
942 [dataArray addObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
943 itemString = wxString(static_cast<char const*>(dataBuffer.GetData())+sizeof(wxDataFormatId),wxConvLocal);
944 itemStringAvailable = true;
947 case wxDF_UNICODETEXT:
949 event.GetDataObject()->GetDataHere(wxDF_UNICODETEXT,dataBuffer.GetAppendBuf(dataSize));
950 dataBuffer.UngetAppendBuf(dataSize);
951 if (itemStringAvailable) // does an object already exist as an ASCII text (see wxDF_TEXT case statement)?
952 [dataArray replaceObjectAtIndex:itemCounter withObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
954 [dataArray addObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
955 itemString = wxString::FromUTF8(static_cast<char const*>(dataBuffer.GetData())+sizeof(wxDataFormatId),dataSize);
956 itemStringAvailable = true;
960 wxFAIL_MSG("Data object has invalid or unsupported data format");
965 delete[] dataFormats;
967 if (dataStringAvailable)
968 if (itemStringAvailable)
971 dataString << wxT('\n');
972 dataString << itemString;
975 dataStringAvailable = false;
981 return NO; // dragging was vetoed or no data available
984 if (dataStringAvailable)
986 wxCFStringRef osxString(dataString);
988 [pasteboard declareTypes:[NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil] owner:nil];
989 [pasteboard setPropertyList:dataArray forType:DataViewPboardType];
990 [pasteboard setString:osxString.AsNSString() forType:NSStringPboardType];
994 [pasteboard declareTypes:[NSArray arrayWithObject:DataViewPboardType] owner:nil];
995 [pasteboard setPropertyList:dataArray forType:DataViewPboardType];
1000 return NO; // no items to drag (should never occur)
1006 -(void) addToBuffer:(wxPointerObject*)item
1008 [items addObject:item];
1013 [items removeAllObjects];
1016 -(wxPointerObject*) getDataViewItemFromBuffer:(const wxDataViewItem&)item
1018 return [items member:[[[wxPointerObject alloc] initWithPointer:item.GetID()] autorelease]];
1021 -(wxPointerObject*) getItemFromBuffer:(wxPointerObject*)item
1023 return [items member:item];
1026 -(BOOL) isInBuffer:(wxPointerObject*)item
1028 return [items containsObject:item];
1031 -(void) removeFromBuffer:(wxPointerObject*)item
1033 [items removeObject:item];
1037 // children handling
1039 -(void) appendChild:(wxPointerObject*)item
1041 [children addObject:item];
1044 -(void) clearChildren
1046 [children removeAllObjects];
1049 -(wxPointerObject*) getChild:(NSUInteger)index
1051 return [children objectAtIndex:index];
1054 -(NSUInteger) getChildCount
1056 return [children count];
1059 -(void) removeChild:(NSUInteger)index
1061 [children removeObjectAtIndex:index];
1067 -(void) clearBuffers
1070 [self clearChildren];
1071 [self setCurrentParentItem:nil];
1077 -(NSArray*) sortDescriptors
1079 return sortDescriptors;
1082 -(void) setSortDescriptors:(NSArray*)newSortDescriptors
1084 [newSortDescriptors retain];
1085 [sortDescriptors release];
1086 sortDescriptors = newSortDescriptors;
1090 // access to wxWidget's implementation
1092 -(wxPointerObject*) currentParentItem
1094 return currentParentItem;
1097 -(wxCocoaDataViewControl*) implementation
1099 return implementation;
1102 -(wxDataViewModel*) model
1107 -(void) setCurrentParentItem:(wxPointerObject*)newCurrentParentItem
1109 [newCurrentParentItem retain];
1110 [currentParentItem release];
1111 currentParentItem = newCurrentParentItem;
1114 -(void) setImplementation:(wxCocoaDataViewControl*) newImplementation
1116 implementation = newImplementation;
1119 -(void) setModel:(wxDataViewModel*) newModel
1127 -(void) bufferItem:(wxPointerObject*)parentItem withChildren:(wxDataViewItemArray*)dataViewChildrenPtr
1129 NSInteger const noOfChildren = (*dataViewChildrenPtr).GetCount();
1131 [self setCurrentParentItem:parentItem];
1132 [self clearChildren];
1133 for (NSInteger indexChild=0; indexChild<noOfChildren; ++indexChild)
1135 wxPointerObject* bufferedPointerObject;
1136 wxPointerObject* newPointerObject([[wxPointerObject alloc] initWithPointer:(*dataViewChildrenPtr)[indexChild].GetID()]);
1138 // The next statement and test looks strange but there is
1139 // unfortunately no workaround: due to the fact that two pointer
1140 // objects are identical if their pointers are identical - because the
1141 // method isEqual has been overloaded - the set operation will only
1142 // add a new pointer object if there is not already one in the set
1143 // having the same pointer. On the other side the children's array
1144 // would always add the new pointer object. This means that different
1145 // pointer objects are stored in the set and array. This will finally
1146 // lead to a crash as objects diverge. To solve this issue it is first
1147 // tested if the child already exists in the set and if it is the case
1148 // the sets object is going to be appended to the array, otheriwse the
1149 // new pointer object is added to the set and array:
1150 bufferedPointerObject = [self getItemFromBuffer:newPointerObject];
1151 if (bufferedPointerObject == nil)
1153 [items addObject:newPointerObject];
1154 [children addObject:newPointerObject];
1157 [children addObject:bufferedPointerObject];
1158 [newPointerObject release];
1164 // ============================================================================
1166 // ============================================================================
1168 @implementation wxCustomCell
1170 #if 0 // starting implementation for custom cell clicks
1174 self = [super init];
1175 [self setAction:@selector(clickedAction)];
1176 [self setTarget:self];
1180 - (void) clickedAction: (id) sender
1182 wxUnusedVar(sender);
1189 wxCustomRendererObject * const
1190 obj = static_cast<wxCustomRendererObject *>([self objectValue]);
1193 const wxSize size = obj->customRenderer->GetSize();
1194 return NSMakeSize(size.x, size.y);
1200 -(void) drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
1202 wxCustomRendererObject * const
1203 obj = static_cast<wxCustomRendererObject *>([self objectValue]);
1206 // this may happen for the custom cells in container rows: they don't
1211 wxDataViewCustomRenderer * const renderer = obj->customRenderer;
1213 // if this method is called everything is already setup correctly,
1214 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1215 CGContextSaveGState( context );
1217 if ( ![controlView isFlipped] )
1219 CGContextTranslateCTM( context, 0, [controlView bounds].size.height );
1220 CGContextScaleCTM( context, 1, -1 );
1224 wxGraphicsContext* gc = wxGraphicsContext::CreateFromNative(context);
1225 dc.SetGraphicsContext(gc);
1228 if ( [self isHighlighted] )
1229 state |= wxDATAVIEW_CELL_SELECTED;
1231 renderer->WXCallRender(wxFromNSRect(controlView, cellFrame), &dc, state);
1233 CGContextRestoreGState( context );
1236 -(NSRect) imageRectForBounds:(NSRect)cellFrame
1241 -(NSRect) titleRectForBounds:(NSRect)cellFrame
1248 // ============================================================================
1250 // ============================================================================
1251 @implementation wxImageTextCell
1257 self = [super init];
1260 // initializing the text part:
1261 [self setSelectable:YES];
1262 // initializing the image part:
1264 imageSize = NSMakeSize(16,16);
1265 spaceImageText = 5.0;
1271 -(id) copyWithZone:(NSZone*)zone
1273 wxImageTextCell* cell;
1276 cell = (wxImageTextCell*) [super copyWithZone:zone];
1277 cell->image = [image retain];
1278 cell->imageSize = imageSize;
1279 cell->spaceImageText = spaceImageText;
1280 cell->xImageShift = xImageShift;
1295 -(NSTextAlignment) alignment
1297 return cellAlignment;
1300 -(void) setAlignment:(NSTextAlignment)newAlignment
1302 cellAlignment = newAlignment;
1303 switch (newAlignment)
1305 case NSCenterTextAlignment:
1306 case NSLeftTextAlignment:
1307 case NSJustifiedTextAlignment:
1308 case NSNaturalTextAlignment:
1309 [super setAlignment:NSLeftTextAlignment];
1311 case NSRightTextAlignment:
1312 [super setAlignment:NSRightTextAlignment];
1315 wxFAIL_MSG("Unknown alignment type.");
1327 -(void) setImage:(NSImage*)newImage
1339 -(void) setImageSize:(NSSize) newImageSize
1341 imageSize = newImageSize;
1347 -(NSSize) cellImageSize
1349 return NSMakeSize(imageSize.width+xImageShift+spaceImageText,imageSize.height);
1354 NSSize cellSize([super cellSize]);
1357 if (imageSize.height > cellSize.height)
1358 cellSize.height = imageSize.height;
1359 cellSize.width += imageSize.width+xImageShift+spaceImageText;
1364 -(NSSize) cellTextSize
1366 return [super cellSize];
1372 -(void) determineCellParts:(NSRect)cellFrame imagePart:(NSRect*)imageFrame textPart:(NSRect*)textFrame
1374 switch (cellAlignment)
1376 case NSCenterTextAlignment:
1378 CGFloat const cellSpace = cellFrame.size.width-[self cellSize].width;
1380 // if the cell's frame is smaller than its contents (at least
1381 // in x-direction) make sure that the image is visible:
1383 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1384 else // otherwise center the image and text in the cell's frame
1385 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText+0.5*cellSpace,NSMinXEdge);
1388 case NSJustifiedTextAlignment:
1389 case NSLeftTextAlignment:
1390 case NSNaturalTextAlignment: // how to determine the natural writing direction? TODO
1391 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1393 case NSRightTextAlignment:
1395 CGFloat const cellSpace = cellFrame.size.width-[self cellSize].width;
1397 // if the cell's frame is smaller than its contents (at least
1398 // in x-direction) make sure that the image is visible:
1400 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1401 else // otherwise right align the image and text in the cell's frame
1402 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText+cellSpace,NSMinXEdge);
1406 *imageFrame = NSZeroRect;
1407 *textFrame = NSZeroRect;
1408 wxFAIL_MSG("Unhandled alignment type.");
1412 -(void) drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
1414 NSRect textFrame, imageFrame;
1417 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1418 // draw the image part by ourselves;
1419 // check if the cell has to draw its own background (checking is done by
1420 // the parameter of the textfield's cell):
1421 if ([self drawsBackground])
1423 [[self backgroundColor] set];
1424 NSRectFill(imageFrame);
1428 // the image is slightly shifted (xImageShift) and has a fixed size
1429 // but the image's frame might be larger and starts currently on the
1430 // left side of the cell's frame; therefore, the origin and the
1431 // image's frame size have to be adjusted:
1432 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1434 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1435 imageFrame.size.width = imageSize.width;
1439 imageFrame.origin.x += xImageShift;
1440 imageFrame.size.width -= xImageShift+spaceImageText;
1442 // ...and the image has to be centered in the y-direction:
1443 if (imageFrame.size.height > imageSize.height)
1444 imageFrame.size.height = imageSize.height;
1445 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1447 // according to the documentation the coordinate system should be
1448 // flipped for NSTableViews (y-coordinate goes from top to bottom); to
1449 // draw an image correctly the coordinate system has to be transformed
1450 // to a bottom-top coordinate system, otherwise the image's
1451 // content is flipped:
1452 NSAffineTransform* coordinateTransform([NSAffineTransform transform]);
1454 if ([controlView isFlipped])
1456 [coordinateTransform scaleXBy: 1.0 yBy:-1.0]; // first the coordinate system is brought back to bottom-top orientation
1457 [coordinateTransform translateXBy:0.0 yBy:(-2.0)*imageFrame.origin.y-imageFrame.size.height]; // the coordinate system has to be moved to compensate for the
1458 [coordinateTransform concat]; // other orientation and the position of the image's frame
1460 [image drawInRect:imageFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0]; // suggested method to draw the image
1461 // instead of compositeToPoint:operation:
1462 // take back previous transformation (if the view is not flipped the
1463 // coordinate transformation matrix contains the identity matrix and
1464 // the next two operations do not change the content's transformation
1466 [coordinateTransform invert];
1467 [coordinateTransform concat];
1469 // let the textfield cell draw the text part:
1470 if (textFrame.size.width > [self cellTextSize].width)
1472 // for unknown reasons the alignment of the text cell is ignored;
1473 // therefore change the size so that alignment does not influence the
1474 // visualization anymore
1475 textFrame.size.width = [self cellTextSize].width;
1477 [super drawWithFrame:textFrame inView:controlView];
1480 -(void) editWithFrame:(NSRect)aRect inView:(NSView*)controlView editor:(NSText*)textObj delegate:(id)anObject event:(NSEvent*)theEvent
1482 NSRect textFrame, imageFrame;
1485 [self determineCellParts:aRect imagePart:&imageFrame textPart:&textFrame];
1486 [super editWithFrame:textFrame inView:controlView editor:textObj delegate:anObject event:theEvent];
1489 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1490 -(NSUInteger) hitTestForEvent:(NSEvent*)event inRect:(NSRect)cellFrame ofView:(NSView*)controlView
1492 NSPoint point = [controlView convertPoint:[event locationInWindow] fromView:nil];
1494 NSRect imageFrame, textFrame;
1497 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1500 // the image is shifted...
1501 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1503 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1504 imageFrame.size.width = imageSize.width;
1508 imageFrame.origin.x += xImageShift;
1509 imageFrame.size.width -= xImageShift+spaceImageText;
1512 if (imageFrame.size.height > imageSize.height)
1513 imageFrame.size.height = imageSize.height;
1514 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1515 // If the point is in the image rect, then it is a content hit (see
1516 // documentation for hitTestForEvent:inRect:ofView):
1517 if (NSMouseInRect(point, imageFrame, [controlView isFlipped]))
1518 return NSCellHitContentArea;
1520 // if the image was not hit let's try the text part:
1521 if (textFrame.size.width > [self cellTextSize].width)
1523 // for unknown reasons the alignment of the text cell is ignored;
1524 // therefore change the size so that alignment does not influence the
1525 // visualization anymore
1526 textFrame.size.width = [self cellTextSize].width;
1529 return [super hitTestForEvent:event inRect:textFrame ofView:controlView];
1533 -(NSRect) imageRectForBounds:(NSRect)cellFrame
1535 NSRect textFrame, imageFrame;
1538 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1539 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1541 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1542 imageFrame.size.width = imageSize.width;
1546 imageFrame.origin.x += xImageShift;
1547 imageFrame.size.width -= xImageShift+spaceImageText;
1550 if (imageFrame.size.height > imageSize.height)
1551 imageFrame.size.height = imageSize.height;
1552 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1557 -(void) selectWithFrame:(NSRect)aRect inView:(NSView*)controlView editor:(NSText*)textObj delegate:(id)anObject start:(NSInteger)selStart length:(NSInteger)selLength
1559 NSRect textFrame, imageFrame;
1562 [self determineCellParts:aRect imagePart:&imageFrame textPart:&textFrame];
1563 [super selectWithFrame:textFrame inView:controlView editor:textObj delegate:anObject start:selStart length:selLength];
1566 -(NSRect) titleRectForBounds:(NSRect)cellFrame
1568 NSRect textFrame, imageFrame;
1571 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1577 // ============================================================================
1578 // wxCocoaOutlineView
1579 // ============================================================================
1580 @implementation wxCocoaOutlineView
1583 // initializers / destructor
1587 self = [super init];
1590 currentlyEditedColumn =
1591 currentlyEditedRow = -1;
1593 [self registerForDraggedTypes:[NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]];
1594 [self setDelegate:self];
1595 [self setDoubleAction:@selector(actionDoubleClick:)];
1596 [self setDraggingSourceOperationMask:NSDragOperationEvery forLocal:NO];
1597 [self setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
1598 [self setTarget:self];
1604 // access to wxWidget's implementation
1606 -(wxCocoaDataViewControl*) implementation
1608 return implementation;
1611 -(void) setImplementation:(wxCocoaDataViewControl*) newImplementation
1613 implementation = newImplementation;
1619 -(void) actionDoubleClick:(id)sender
1621 wxUnusedVar(sender);
1623 // actually the documentation (NSTableView 2007-10-31) for doubleAction:
1624 // and setDoubleAction: seems to be wrong as this action message is always
1625 // sent whether the cell is editable or not
1626 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1628 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_ACTIVATED,dvc->GetId());
1631 event.SetEventObject(dvc);
1632 event.SetItem(wxDataViewItemFromItem([self itemAtRow:[self clickedRow]]));
1633 dvc->GetEventHandler()->ProcessEvent(event);
1640 -(NSMenu*) menuForEvent:(NSEvent*)theEvent
1642 wxUnusedVar(theEvent);
1644 // this method does not do any special menu event handling but only sends
1645 // an event message; therefore, the user has full control if a context
1646 // menu should be shown or not
1647 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1649 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_CONTEXT_MENU,dvc->GetId());
1651 wxDataViewItemArray selectedItems;
1654 event.SetEventObject(dvc);
1655 event.SetModel(dvc->GetModel());
1656 // get the item information;
1657 // theoretically more than one ID can be returned but the event can only
1658 // handle one item, therefore only the first item of the array is
1660 if (dvc->GetSelections(selectedItems) > 0)
1661 event.SetItem(selectedItems[0]);
1662 dvc->GetEventHandler()->ProcessEvent(event);
1670 -(void) outlineView:(NSOutlineView*)outlineView mouseDownInHeaderOfTableColumn:(NSTableColumn*)tableColumn
1672 wxDataViewColumn* const
1673 col([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
1675 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1678 event(wxEVT_COMMAND_DATAVIEW_COLUMN_HEADER_CLICK,dvc->GetId());
1681 // first, send an event that the user clicked into a column's header:
1682 event.SetEventObject(dvc);
1683 event.SetColumn(dvc->GetColumnPosition(col));
1684 event.SetDataViewColumn(col);
1685 dvc->HandleWindowEvent(event);
1687 // now, check if the click may have had an influence on sorting, too;
1688 // the sorting setup has to be done only if the clicked table column is
1689 // sortable and has not been used for sorting before the click; if the
1690 // column is already responsible for sorting the native control changes
1691 // the sorting direction automatically and informs the data source via
1692 // outlineView:sortDescriptorsDidChange:
1693 if (col->IsSortable() && ([tableColumn sortDescriptorPrototype] == nil))
1695 // remove the sort order from the previously sorted column table (it
1696 // can also be that no sorted column table exists):
1697 UInt32 const noOfColumns = [outlineView numberOfColumns];
1699 for (UInt32 i=0; i<noOfColumns; ++i)
1700 [[[outlineView tableColumns] objectAtIndex:i] setSortDescriptorPrototype:nil];
1701 // make column table sortable:
1702 NSArray* sortDescriptors;
1703 NSSortDescriptor* sortDescriptor;
1705 sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[NSString stringWithFormat:@"%d",[outlineView columnWithIdentifier:[tableColumn identifier]]]
1707 sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
1708 [tableColumn setSortDescriptorPrototype:sortDescriptor];
1709 [outlineView setSortDescriptors:sortDescriptors];
1710 [sortDescriptor release];
1714 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldCollapseItem:(id)item
1716 wxUnusedVar(outlineView);
1718 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1720 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSING,dvc->GetId());
1723 event.SetEventObject(dvc);
1724 event.SetItem (wxDataViewItemFromItem(item));
1725 event.SetModel (dvc->GetModel());
1726 // finally send the equivalent wxWidget event:
1727 dvc->GetEventHandler()->ProcessEvent(event);
1728 // opening the container is allowed if not vetoed:
1729 return event.IsAllowed();
1732 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldExpandItem:(id)item
1734 wxUnusedVar(outlineView);
1736 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1738 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDING,dvc->GetId());
1741 event.SetEventObject(dvc);
1742 event.SetItem (wxDataViewItemFromItem(item));
1743 event.SetModel (dvc->GetModel());
1744 // finally send the equivalent wxWidget event:
1745 dvc->GetEventHandler()->ProcessEvent(event);
1746 // opening the container is allowed if not vetoed:
1747 return event.IsAllowed();
1750 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldSelectTableColumn:(NSTableColumn*)tableColumn
1752 wxUnusedVar(tableColumn);
1753 wxUnusedVar(outlineView);
1758 -(void) outlineView:(wxCocoaOutlineView*)outlineView
1759 willDisplayCell:(id)cell
1760 forTableColumn:(NSTableColumn*)tableColumn
1763 wxUnusedVar(outlineView);
1765 wxDataViewCtrl * const dvc = implementation->GetDataViewCtrl();
1766 wxDataViewModel * const model = dvc->GetModel();
1768 wxDataViewColumn* const
1769 dvCol([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
1770 const unsigned colIdx = dvCol->GetModelColumn();
1772 wxDataViewItem dvItem(wxDataViewItemFromItem(item));
1774 if ( !model->HasValue(dvItem, colIdx) )
1777 wxDataViewRenderer * const renderer = dvCol->GetRenderer();
1778 wxDataViewRendererNativeData * const data = renderer->GetNativeData();
1780 // let the renderer know about what it's going to render next
1781 data->SetColumnPtr(tableColumn);
1782 data->SetItem(item);
1783 data->SetItemCell(cell);
1785 // use the attributes: notice that we need to do this whether we have them
1786 // or not as even if this cell doesn't have any attributes, the previous
1787 // one might have had some and then we need to reset them back to default
1788 wxDataViewItemAttr attr;
1789 model->GetAttr(dvItem, colIdx, attr);
1790 renderer->OSXApplyAttr(attr);
1792 // set the state (enabled/disabled) of the item
1793 renderer->OSXApplyEnabled(model->IsEnabled(dvItem, colIdx));
1795 // and finally do draw it
1796 renderer->MacRender();
1802 -(void) outlineViewColumnDidMove:(NSNotification*)notification
1804 int const newColumnPosition = [[[notification userInfo] objectForKey:@"NSNewColumn"] intValue];
1807 tableColumn = [[self tableColumns] objectAtIndex:newColumnPosition];
1808 wxDataViewColumn* const
1809 col([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
1811 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1813 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_COLUMN_REORDERED,dvc->GetId());
1816 event.SetEventObject(dvc);
1817 event.SetColumn(dvc->GetColumnPosition(col));
1818 event.SetDataViewColumn(col);
1819 dvc->GetEventHandler()->ProcessEvent(event);
1822 -(void) outlineViewItemDidCollapse:(NSNotification*)notification
1824 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1826 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSED,dvc->GetId());
1829 event.SetEventObject(dvc);
1830 event.SetItem(wxDataViewItemFromItem(
1831 [[notification userInfo] objectForKey:@"NSObject"]));
1832 dvc->GetEventHandler()->ProcessEvent(event);
1835 -(void) outlineViewItemDidExpand:(NSNotification*)notification
1837 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1839 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDED,dvc->GetId());
1842 event.SetEventObject(dvc);
1843 event.SetItem(wxDataViewItemFromItem(
1844 [[notification userInfo] objectForKey:@"NSObject"]));
1845 dvc->GetEventHandler()->ProcessEvent(event);
1848 -(void) outlineViewSelectionDidChange:(NSNotification*)notification
1850 wxUnusedVar(notification);
1852 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1854 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_SELECTION_CHANGED,dvc->GetId());
1856 event.SetEventObject(dvc);
1857 event.SetModel(dvc->GetModel());
1858 event.SetItem(dvc->GetSelection());
1859 dvc->GetEventHandler()->ProcessEvent(event);
1862 -(void) textDidBeginEditing:(NSNotification*)notification
1864 // this notification is only sent if the user started modifying the cell
1865 // (not when the user clicked into the cell and the cell's editor is
1868 // call method of superclass (otherwise editing does not work correctly -
1869 // the outline data source class is not informed about a change of data):
1870 [super textDidBeginEditing:notification];
1872 // remember the column being edited, it will be used in textDidEndEditing:
1873 currentlyEditedColumn = [self editedColumn];
1874 currentlyEditedRow = [self editedRow];
1877 tableColumn = [[self tableColumns] objectAtIndex:currentlyEditedColumn];
1878 wxDataViewColumn* const
1879 col([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
1881 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1884 // stop editing of a custom item first (if necessary)
1885 dvc->FinishCustomItemEditing();
1887 // now, send the event:
1889 event(wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED,dvc->GetId());
1891 event.SetEventObject(dvc);
1893 wxDataViewItemFromItem([self itemAtRow:currentlyEditedRow]));
1894 event.SetColumn(dvc->GetColumnPosition(col));
1895 event.SetDataViewColumn(col);
1896 dvc->GetEventHandler()->ProcessEvent(event);
1899 -(void) textDidEndEditing:(NSNotification*)notification
1901 // call method of superclass (otherwise editing does not work correctly -
1902 // the outline data source class is not informed about a change of data):
1903 [super textDidEndEditing:notification];
1905 // under OSX an event indicating the end of an editing session can be sent
1906 // even if no event indicating a start of an editing session has been sent
1907 // (see Documentation for NSControl controlTextDidEndEditing:); this is
1908 // not expected by a user of the wxWidgets library and therefore an
1909 // wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_DONE event is only sent if a
1910 // corresponding wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED has been sent
1911 // before; to check if a wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED has
1912 // been sent the last edited column/row are valid:
1913 if ( currentlyEditedColumn != -1 && currentlyEditedRow != -1 )
1916 tableColumn = [[self tableColumns] objectAtIndex:currentlyEditedColumn];
1917 wxDataViewColumn* const
1918 col([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
1920 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1922 // send event to wxWidgets:
1924 event(wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_DONE,dvc->GetId());
1926 event.SetEventObject(dvc);
1928 wxDataViewItemFromItem([self itemAtRow:currentlyEditedRow]));
1929 event.SetColumn(dvc->GetColumnPosition(col));
1930 event.SetDataViewColumn(col);
1931 dvc->GetEventHandler()->ProcessEvent(event);
1934 // we're not editing any more
1935 currentlyEditedColumn =
1936 currentlyEditedRow = -1;
1942 // ============================================================================
1943 // wxCocoaDataViewControl
1944 // ============================================================================
1946 wxCocoaDataViewControl::wxCocoaDataViewControl(wxWindow* peer,
1953 [[NSScrollView alloc] initWithFrame:wxOSXGetFrameForControl(peer,pos,size)]
1956 m_OutlineView([[wxCocoaOutlineView alloc] init])
1958 // initialize scrollview (the outline view is part of a scrollview):
1959 NSScrollView* scrollview = (NSScrollView*) GetWXWidget();
1961 [scrollview setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1962 [scrollview setBorderType:NSNoBorder];
1963 [scrollview setHasVerticalScroller:YES];
1964 [scrollview setHasHorizontalScroller:YES];
1965 [scrollview setAutohidesScrollers:YES];
1966 [scrollview setDocumentView:m_OutlineView];
1968 // initialize the native control itself too
1969 InitOutlineView(style);
1972 void wxCocoaDataViewControl::InitOutlineView(long style)
1974 [m_OutlineView setImplementation:this];
1975 [m_OutlineView setColumnAutoresizingStyle:NSTableViewSequentialColumnAutoresizingStyle];
1976 [m_OutlineView setIndentationPerLevel:GetDataViewCtrl()->GetIndent()];
1977 NSUInteger maskGridStyle(NSTableViewGridNone);
1978 if (style & wxDV_HORIZ_RULES)
1979 maskGridStyle |= NSTableViewSolidHorizontalGridLineMask;
1980 if (style & wxDV_VERT_RULES)
1981 maskGridStyle |= NSTableViewSolidVerticalGridLineMask;
1982 [m_OutlineView setGridStyleMask:maskGridStyle];
1983 [m_OutlineView setAllowsMultipleSelection: (style & wxDV_MULTIPLE) != 0];
1984 [m_OutlineView setUsesAlternatingRowBackgroundColors:(style & wxDV_ROW_LINES) != 0];
1986 if ( style & wxDV_NO_HEADER )
1987 [m_OutlineView setHeaderView:nil];
1990 wxCocoaDataViewControl::~wxCocoaDataViewControl()
1992 [m_DataSource release];
1993 [m_OutlineView release];
1997 // column related methods (inherited from wxDataViewWidgetImpl)
1999 bool wxCocoaDataViewControl::ClearColumns()
2001 // as there is a bug in NSOutlineView version (OSX 10.5.6 #6555162) the
2002 // columns cannot be deleted if there is an outline column in the view;
2003 // therefore, the whole view is deleted and newly constructed:
2004 [m_OutlineView release];
2005 m_OutlineView = [[wxCocoaOutlineView alloc] init];
2006 [((NSScrollView*) GetWXWidget()) setDocumentView:m_OutlineView];
2007 [m_OutlineView setDataSource:m_DataSource];
2009 InitOutlineView(GetDataViewCtrl()->GetWindowStyle());
2014 bool wxCocoaDataViewControl::DeleteColumn(wxDataViewColumn* columnPtr)
2016 if ([m_OutlineView outlineTableColumn] == columnPtr->GetNativeData()->GetNativeColumnPtr())
2017 [m_OutlineView setOutlineTableColumn:nil]; // due to a bug this does not work
2018 [m_OutlineView removeTableColumn:columnPtr->GetNativeData()->GetNativeColumnPtr()]; // due to a confirmed bug #6555162 the deletion does not work for
2019 // outline table columns (... and there is no workaround)
2020 return (([m_OutlineView columnWithIdentifier:[wxDVCNSTableColumn identifierForColumnPointer:columnPtr]]) == -1);
2023 void wxCocoaDataViewControl::DoSetExpanderColumn(const wxDataViewColumn *columnPtr)
2025 [m_OutlineView setOutlineTableColumn:columnPtr->GetNativeData()->GetNativeColumnPtr()];
2028 wxDataViewColumn* wxCocoaDataViewControl::GetColumn(unsigned int pos) const
2030 NSTableColumn* tableColumn = [[m_OutlineView tableColumns] objectAtIndex:pos];
2031 return [static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer];
2034 int wxCocoaDataViewControl::GetColumnPosition(const wxDataViewColumn *columnPtr) const
2036 return [m_OutlineView columnWithIdentifier:[wxDVCNSTableColumn identifierForColumnPointer:columnPtr]];
2039 bool wxCocoaDataViewControl::InsertColumn(unsigned int pos, wxDataViewColumn* columnPtr)
2041 // create column and set the native data of the dataview column:
2042 NSTableColumn *nativeColumn = ::CreateNativeColumn(columnPtr);
2043 columnPtr->GetNativeData()->SetNativeColumnPtr(nativeColumn);
2044 // as the native control does not allow the insertion of a column at a
2045 // specified position the column is first appended and - if necessary -
2046 // moved to its final position:
2047 [m_OutlineView addTableColumn:nativeColumn];
2048 if (pos != static_cast<unsigned int>([m_OutlineView numberOfColumns]-1))
2049 [m_OutlineView moveColumn:[m_OutlineView numberOfColumns]-1 toColumn:pos];
2051 // set columns width now that it can be computed even for autosized columns:
2052 columnPtr->SetWidth(columnPtr->GetWidthVariable());
2058 void wxCocoaDataViewControl::FitColumnWidthToContent(unsigned int pos)
2060 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
2061 const int count = GetCount();
2062 NSTableColumn *column = GetColumn(pos)->GetNativeData()->GetNativeColumnPtr();
2064 class MaxWidthCalculator
2067 MaxWidthCalculator(wxCocoaOutlineView *view,
2068 NSTableColumn *column, unsigned columnIndex)
2071 m_column(columnIndex),
2074 // account for indentation in the column with expander
2075 if ( column == [m_view outlineTableColumn] )
2076 m_indent = [m_view indentationPerLevel];
2079 void UpdateWithWidth(int width)
2081 m_width = wxMax(m_width, width);
2084 void UpdateWithRow(int row)
2086 NSCell *cell = [m_view preparedCellAtColumn:m_column row:row];
2087 unsigned cellWidth = [cell cellSize].width + 1/*round the float up*/;
2090 cellWidth += m_indent * ([m_view levelForRow:row] + 1);
2092 m_width = wxMax(m_width, cellWidth);
2095 int GetMaxWidth() const { return m_width; }
2099 wxCocoaOutlineView *m_view;
2104 MaxWidthCalculator calculator(m_OutlineView, column, pos);
2106 if ( [column headerCell] )
2108 calculator.UpdateWithWidth([[column headerCell] cellSize].width + 1/*round the float up*/);
2111 // The code below deserves some explanation. For very large controls, we
2112 // simply can't afford to calculate sizes for all items, it takes too
2113 // long. So the best we can do is to check the first and the last N/2
2114 // items in the control for some sufficiently large N and calculate best
2115 // sizes from that. That can result in the calculated best width being too
2116 // small for some outliers, but it's better to get slightly imperfect
2117 // result than to wait several seconds after every update. To avoid highly
2118 // visible miscalculations, we also include all currently visible items
2119 // no matter what. Finally, the value of N is determined dynamically by
2120 // measuring how much time we spent on the determining item widths so far.
2123 int top_part_end = count;
2124 static const long CALC_TIMEOUT = 20/*ms*/;
2125 // don't call wxStopWatch::Time() too often
2126 static const unsigned CALC_CHECK_FREQ = 100;
2129 // use some hard-coded limit, that's the best we can do without timer
2130 int top_part_end = wxMin(500, count);
2131 #endif // wxUSE_STOPWATCH/!wxUSE_STOPWATCH
2135 for ( row = 0; row < top_part_end; row++ )
2138 if ( row % CALC_CHECK_FREQ == CALC_CHECK_FREQ-1 &&
2139 timer.Time() > CALC_TIMEOUT )
2141 #endif // wxUSE_STOPWATCH
2142 calculator.UpdateWithRow(row);
2145 // row is the first unmeasured item now; that's our value of N/2
2151 // add bottom N/2 items now:
2152 const int bottom_part_start = wxMax(row, count - row);
2153 for ( row = bottom_part_start; row < count; row++ )
2154 calculator.UpdateWithRow(row);
2156 // finally, include currently visible items in the calculation:
2157 const NSRange visible = [m_OutlineView rowsInRect:[m_OutlineView visibleRect]];
2158 const int first_visible = wxMax(visible.location, top_part_end);
2159 const int last_visible = wxMin(first_visible + visible.length, bottom_part_start);
2161 for ( row = first_visible; row < last_visible; row++ )
2162 calculator.UpdateWithRow(row);
2164 wxLogTrace("dataview",
2165 "determined best size from %d top, %d bottom plus %d more visible items out of %d total",
2167 count - bottom_part_start,
2168 wxMax(0, last_visible - first_visible),
2172 [column setWidth:calculator.GetMaxWidth()];
2173 #endif // MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
2177 // item related methods (inherited from wxDataViewWidgetImpl)
2179 bool wxCocoaDataViewControl::Add(const wxDataViewItem& parent, const wxDataViewItem& WXUNUSED(item))
2182 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2184 [m_OutlineView reloadData];
2188 bool wxCocoaDataViewControl::Add(const wxDataViewItem& parent, const wxDataViewItemArray& WXUNUSED(items))
2191 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2193 [m_OutlineView reloadData];
2197 void wxCocoaDataViewControl::Collapse(const wxDataViewItem& item)
2199 [m_OutlineView collapseItem:[m_DataSource getDataViewItemFromBuffer:item]];
2202 void wxCocoaDataViewControl::EnsureVisible(const wxDataViewItem& item, const wxDataViewColumn *columnPtr)
2206 [m_OutlineView scrollRowToVisible:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2208 [m_OutlineView scrollColumnToVisible:GetColumnPosition(columnPtr)];
2212 void wxCocoaDataViewControl::Expand(const wxDataViewItem& item)
2214 [m_OutlineView expandItem:[m_DataSource getDataViewItemFromBuffer:item]];
2217 unsigned int wxCocoaDataViewControl::GetCount() const
2219 return [m_OutlineView numberOfRows];
2222 wxRect wxCocoaDataViewControl::GetRectangle(const wxDataViewItem& item, const wxDataViewColumn *columnPtr)
2224 return wxFromNSRect([m_osxView superview],[m_OutlineView frameOfCellAtColumn:GetColumnPosition(columnPtr)
2225 row:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]]);
2228 bool wxCocoaDataViewControl::IsExpanded(const wxDataViewItem& item) const
2230 return [m_OutlineView isItemExpanded:[m_DataSource getDataViewItemFromBuffer:item]];
2233 bool wxCocoaDataViewControl::Reload()
2235 [m_DataSource clearBuffers];
2236 [m_OutlineView reloadData];
2237 [m_OutlineView scrollColumnToVisible:0];
2238 [m_OutlineView scrollRowToVisible:0];
2242 bool wxCocoaDataViewControl::Remove(const wxDataViewItem& parent, const wxDataViewItem& WXUNUSED(item))
2245 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2247 [m_OutlineView reloadData];
2251 bool wxCocoaDataViewControl::Remove(const wxDataViewItem& parent, const wxDataViewItemArray& WXUNUSED(item))
2254 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2256 [m_OutlineView reloadData];
2260 bool wxCocoaDataViewControl::Update(const wxDataViewColumn *columnPtr)
2262 wxUnusedVar(columnPtr);
2267 bool wxCocoaDataViewControl::Update(const wxDataViewItem& WXUNUSED(parent), const wxDataViewItem& item)
2269 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:item]];
2273 bool wxCocoaDataViewControl::Update(const wxDataViewItem& WXUNUSED(parent), const wxDataViewItemArray& items)
2275 for (size_t i=0; i<items.GetCount(); ++i)
2276 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:items[i]]];
2281 // model related methods
2283 bool wxCocoaDataViewControl::AssociateModel(wxDataViewModel* model)
2285 [m_DataSource release];
2288 m_DataSource = [[wxCocoaOutlineDataSource alloc] init];
2289 [m_DataSource setImplementation:this];
2290 [m_DataSource setModel:model];
2293 m_DataSource = NULL;
2294 [m_OutlineView setDataSource:m_DataSource]; // if there is a data source the data is immediately going to be requested
2299 // selection related methods (inherited from wxDataViewWidgetImpl)
2302 wxDataViewItem wxCocoaDataViewControl::GetCurrentItem() const
2304 return wxDataViewItem([[m_OutlineView itemAtRow:[m_OutlineView selectedRow]] pointer]);
2307 wxDataViewColumn *wxCocoaDataViewControl::GetCurrentColumn() const
2309 int col = [m_OutlineView selectedColumn];
2312 return GetColumn(col);
2315 void wxCocoaDataViewControl::SetCurrentItem(const wxDataViewItem& item)
2317 // We can't have unselected current item in a NSTableView, as the
2318 // documentation of its deselectRow method explains, the control will
2319 // automatically change the current item to the closest still selected item
2320 // if the current item is deselected. So we have no choice but to select
2321 // the item in the same time as making it current.
2325 int wxCocoaDataViewControl::GetSelectedItemsCount() const
2327 return [m_OutlineView numberOfSelectedRows];
2330 int wxCocoaDataViewControl::GetSelections(wxDataViewItemArray& sel) const
2332 NSIndexSet* selectedRowIndexes([m_OutlineView selectedRowIndexes]);
2334 NSUInteger indexRow;
2338 sel.Alloc([selectedRowIndexes count]);
2339 indexRow = [selectedRowIndexes firstIndex];
2340 while (indexRow != NSNotFound)
2342 sel.Add(wxDataViewItem([[m_OutlineView itemAtRow:indexRow] pointer]));
2343 indexRow = [selectedRowIndexes indexGreaterThanIndex:indexRow];
2345 return sel.GetCount();
2348 bool wxCocoaDataViewControl::IsSelected(const wxDataViewItem& item) const
2350 return [m_OutlineView isRowSelected:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2353 void wxCocoaDataViewControl::Select(const wxDataViewItem& item)
2356 [m_OutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]]
2357 byExtendingSelection:GetDataViewCtrl()->HasFlag(wxDV_MULTIPLE) ? YES : NO];
2360 void wxCocoaDataViewControl::SelectAll()
2362 [m_OutlineView selectAll:m_OutlineView];
2365 void wxCocoaDataViewControl::Unselect(const wxDataViewItem& item)
2368 [m_OutlineView deselectRow:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2371 void wxCocoaDataViewControl::UnselectAll()
2373 [m_OutlineView deselectAll:m_OutlineView];
2377 // sorting related methods
2379 wxDataViewColumn* wxCocoaDataViewControl::GetSortingColumn() const
2381 NSArray* const columns = [m_OutlineView tableColumns];
2383 UInt32 const noOfColumns = [columns count];
2386 for (UInt32 i=0; i<noOfColumns; ++i)
2387 if ([[columns objectAtIndex:i] sortDescriptorPrototype] != nil)
2388 return GetColumn(i);
2392 void wxCocoaDataViewControl::Resort()
2394 [m_DataSource clearChildren];
2395 [m_OutlineView reloadData];
2398 void wxCocoaDataViewControl::StartEditor( const wxDataViewItem & item, unsigned int column )
2400 [m_OutlineView editColumn:column row:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]] withEvent:nil select:YES];
2404 // other methods (inherited from wxDataViewWidgetImpl)
2406 void wxCocoaDataViewControl::DoSetIndent(int indent)
2408 [m_OutlineView setIndentationPerLevel:static_cast<CGFloat>(indent)];
2411 void wxCocoaDataViewControl::HitTest(const wxPoint& point, wxDataViewItem& item, wxDataViewColumn*& columnPtr) const
2413 NSPoint const nativePoint = wxToNSPoint((NSScrollView*) GetWXWidget(),point);
2419 indexColumn = [m_OutlineView columnAtPoint:nativePoint];
2420 indexRow = [m_OutlineView rowAtPoint: nativePoint];
2421 if ((indexColumn >= 0) && (indexRow >= 0))
2423 columnPtr = GetColumn(indexColumn);
2424 item = wxDataViewItem([[m_OutlineView itemAtRow:indexRow] pointer]);
2429 item = wxDataViewItem();
2433 void wxCocoaDataViewControl::SetRowHeight(const wxDataViewItem& WXUNUSED(item), unsigned int WXUNUSED(height))
2434 // Not supported by the native control
2438 void wxCocoaDataViewControl::OnSize()
2440 if ([m_OutlineView numberOfColumns] == 1)
2441 [m_OutlineView sizeLastColumnToFit];
2445 // drag & drop helper methods
2447 wxDataFormat wxCocoaDataViewControl::GetDnDDataFormat(wxDataObjectComposite* dataObjects)
2449 wxDataFormat resultFormat;
2451 return resultFormat;
2453 bool compatible(true);
2455 size_t const noOfFormats = dataObjects->GetFormatCount();
2458 wxDataFormat* formats;
2460 // get all formats and check afterwards if the formats are compatible; if
2461 // they are compatible the preferred format is returned otherwise
2462 // wxDF_INVALID is returned;
2463 // currently compatible types (ordered by priority are):
2464 // - wxDF_UNICODETEXT - wxDF_TEXT
2465 formats = new wxDataFormat[noOfFormats];
2466 dataObjects->GetAllFormats(formats);
2468 while ((indexFormat < noOfFormats) && compatible)
2470 switch (resultFormat.GetType())
2473 resultFormat.SetType(formats[indexFormat].GetType()); // first format (should only be reached if indexFormat == 0)
2476 if (formats[indexFormat].GetType() == wxDF_UNICODETEXT)
2477 resultFormat.SetType(wxDF_UNICODETEXT);
2478 else // incompatible
2480 resultFormat.SetType(wxDF_INVALID);
2484 case wxDF_UNICODETEXT:
2485 if (formats[indexFormat].GetType() != wxDF_TEXT)
2487 resultFormat.SetType(wxDF_INVALID);
2492 resultFormat.SetType(wxDF_INVALID); // not (yet) supported format
2500 return resultFormat;
2503 wxDataObjectComposite* wxCocoaDataViewControl::GetDnDDataObjects(NSData* dataObject) const
2505 wxDataFormatId dataFormatID;
2508 [dataObject getBytes:&dataFormatID length:sizeof(wxDataFormatId)];
2509 switch (dataFormatID)
2512 case wxDF_UNICODETEXT:
2514 wxTextDataObject* textDataObject(new wxTextDataObject());
2516 if (textDataObject->SetData(wxDataFormat(dataFormatID),[dataObject length]-sizeof(wxDataFormatId),static_cast<char const*>([dataObject bytes])+sizeof(wxDataFormatId)))
2518 wxDataObjectComposite* dataObjectComposite(new wxDataObjectComposite());
2520 dataObjectComposite->Add(textDataObject);
2521 return dataObjectComposite;
2525 delete textDataObject;
2535 id wxCocoaDataViewControl::GetItemAtRow(int row) const
2537 return [m_OutlineView itemAtRow:row];
2540 // ----------------------------------------------------------------------------
2541 // wxDataViewRendererNativeData
2542 // ----------------------------------------------------------------------------
2544 void wxDataViewRendererNativeData::Init()
2547 m_origTextColour = NULL;
2548 m_ellipsizeMode = wxELLIPSIZE_MIDDLE;
2551 ApplyLineBreakMode(m_ColumnCell);
2554 void wxDataViewRendererNativeData::ApplyLineBreakMode(NSCell *cell)
2556 NSLineBreakMode nsMode = NSLineBreakByWordWrapping;
2557 switch ( m_ellipsizeMode )
2559 case wxELLIPSIZE_NONE:
2560 nsMode = NSLineBreakByClipping;
2563 case wxELLIPSIZE_START:
2564 nsMode = NSLineBreakByTruncatingHead;
2567 case wxELLIPSIZE_MIDDLE:
2568 nsMode = NSLineBreakByTruncatingMiddle;
2571 case wxELLIPSIZE_END:
2572 nsMode = NSLineBreakByTruncatingTail;
2576 wxASSERT_MSG( nsMode != NSLineBreakByWordWrapping, "unknown wxEllipsizeMode" );
2578 [cell setLineBreakMode: nsMode];
2581 // ---------------------------------------------------------
2582 // wxDataViewRenderer
2583 // ---------------------------------------------------------
2585 wxDataViewRenderer::wxDataViewRenderer(const wxString& varianttype,
2586 wxDataViewCellMode mode,
2588 : wxDataViewRendererBase(varianttype, mode, align),
2591 m_NativeDataPtr(NULL)
2595 wxDataViewRenderer::~wxDataViewRenderer()
2597 delete m_NativeDataPtr;
2600 void wxDataViewRenderer::SetAlignment(int align)
2602 m_alignment = align;
2603 [GetNativeData()->GetColumnCell() setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2606 void wxDataViewRenderer::SetMode(wxDataViewCellMode mode)
2610 [GetOwner()->GetNativeData()->GetNativeColumnPtr() setEditable:(mode == wxDATAVIEW_CELL_EDITABLE)];
2613 void wxDataViewRenderer::SetNativeData(wxDataViewRendererNativeData* newNativeDataPtr)
2615 delete m_NativeDataPtr;
2616 m_NativeDataPtr = newNativeDataPtr;
2619 void wxDataViewRenderer::EnableEllipsize(wxEllipsizeMode mode)
2621 // we need to store this value to apply it to the columns headerCell in
2622 // CreateNativeColumn()
2623 GetNativeData()->SetEllipsizeMode(mode);
2625 // but we may already apply it to the column cell which will be used for
2627 GetNativeData()->ApplyLineBreakMode(GetNativeData()->GetColumnCell());
2630 wxEllipsizeMode wxDataViewRenderer::GetEllipsizeMode() const
2632 return GetNativeData()->GetEllipsizeMode();
2636 wxDataViewRenderer::OSXOnCellChanged(NSObject *object,
2637 const wxDataViewItem& item,
2640 // TODO: This code should really be removed and this function be made pure
2641 // virtual. We just need to decide what to do with custom renderers
2642 // (i.e. wxDataViewCustomRenderer), currently OS X "in place" editing
2643 // which doesn't really create an editor control is not compatible
2644 // with the in place editing under other platforms.
2647 if ( [object isKindOfClass:[NSString class]] )
2648 value = ObjectToString(object);
2649 else if ( [object isKindOfClass:[NSNumber class]] )
2650 value = ObjectToLong(object);
2651 else if ( [object isKindOfClass:[NSDate class]] )
2652 value = ObjectToDate(object);
2655 wxFAIL_MSG( wxString::Format
2657 "unknown value type %s",
2658 wxCFStringRef::AsString([object className])
2663 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2664 model->ChangeValue(value, item, col);
2667 void wxDataViewRenderer::OSXApplyAttr(const wxDataViewItemAttr& attr)
2669 wxDataViewRendererNativeData * const data = GetNativeData();
2670 NSCell * const cell = data->GetItemCell();
2672 // set the font and text colour to use: we need to do it if we had ever
2673 // changed them before, even if this item itself doesn't have any special
2674 // attributes as otherwise it would reuse the attributes from the previous
2675 // cell rendered using the same renderer
2676 NSFont *font = NULL;
2677 NSColor *colText = NULL;
2679 if ( attr.HasFont() )
2681 font = data->GetOriginalFont();
2684 // this is the first time we're setting the font, remember the
2685 // original one before changing it
2687 data->SaveOriginalFont(font);
2692 // FIXME: using wxFont methods here doesn't work for some reason
2693 NSFontManager * const fm = [NSFontManager sharedFontManager];
2694 if ( attr.GetBold() )
2695 font = [fm convertFont:font toHaveTrait:NSBoldFontMask];
2696 if ( attr.GetItalic() )
2697 font = [fm convertFont:font toHaveTrait:NSItalicFontMask];
2699 //else: can't change font if the cell doesn't have any
2702 if ( attr.HasColour() )
2704 // we can set font for any cell but only NSTextFieldCell provides
2705 // a method for setting text colour so check that this method is
2706 // available before using it
2707 if ( [cell respondsToSelector:@selector(setTextColor:)] &&
2708 [cell respondsToSelector:@selector(textColor)] )
2710 if ( !data->GetOriginalTextColour() )
2712 // the cast to (untyped) id is safe because of the check above
2713 data->SaveOriginalTextColour([(id)cell textColor]);
2716 const wxColour& c = attr.GetColour();
2717 colText = [NSColor colorWithCalibratedRed:c.Red() / 255.
2718 green:c.Green() / 255.
2719 blue:c.Blue() / 255.
2720 alpha:c.Alpha() / 255.];
2725 font = data->GetOriginalFont();
2727 colText = data->GetOriginalTextColour();
2730 [cell setFont:font];
2733 [(id)cell setTextColor:colText];
2736 void wxDataViewRenderer::OSXApplyEnabled(bool enabled)
2738 [GetNativeData()->GetItemCell() setEnabled:enabled];
2741 IMPLEMENT_ABSTRACT_CLASS(wxDataViewRenderer,wxDataViewRendererBase)
2743 // ---------------------------------------------------------
2744 // wxDataViewCustomRenderer
2745 // ---------------------------------------------------------
2746 wxDataViewCustomRenderer::wxDataViewCustomRenderer(const wxString& varianttype,
2747 wxDataViewCellMode mode,
2749 : wxDataViewCustomRendererBase(varianttype, mode, align),
2750 m_editorCtrlPtr(NULL),
2753 SetNativeData(new wxDataViewRendererNativeData([[wxCustomCell alloc] init]));
2756 bool wxDataViewCustomRenderer::MacRender()
2758 [GetNativeData()->GetItemCell() setObjectValue:[[[wxCustomRendererObject alloc] initWithRenderer:this] autorelease]];
2762 void wxDataViewCustomRenderer::OSXApplyAttr(const wxDataViewItemAttr& attr)
2764 // simply save the attribute so that it could be reused from our Render()
2767 // it's not necessary to call the base class version which sets the cell
2768 // properties to correspond to this attribute because we currently don't
2769 // use any NSCell methods in custom renderers anyhow but if we ever start
2770 // doing this (e.g. override RenderText() here to use NSTextFieldCell
2771 // methods), then we should pass it on to wxDataViewRenderer here
2774 IMPLEMENT_ABSTRACT_CLASS(wxDataViewCustomRenderer, wxDataViewRenderer)
2776 // ---------------------------------------------------------
2777 // wxDataViewTextRenderer
2778 // ---------------------------------------------------------
2779 wxDataViewTextRenderer::wxDataViewTextRenderer(const wxString& varianttype,
2780 wxDataViewCellMode mode,
2782 : wxDataViewRenderer(varianttype,mode,align)
2784 NSTextFieldCell* cell;
2787 cell = [[NSTextFieldCell alloc] init];
2788 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2789 SetNativeData(new wxDataViewRendererNativeData(cell));
2793 bool wxDataViewTextRenderer::MacRender()
2795 if (GetValue().GetType() == GetVariantType())
2797 [GetNativeData()->GetItemCell() setObjectValue:wxCFStringRef(GetValue().GetString()).AsNSString()];
2802 wxFAIL_MSG(wxString("Text renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2808 wxDataViewTextRenderer::OSXOnCellChanged(NSObject *value,
2809 const wxDataViewItem& item,
2812 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2813 model->ChangeValue(ObjectToString(value), item, col);
2816 IMPLEMENT_CLASS(wxDataViewTextRenderer,wxDataViewRenderer)
2818 // ---------------------------------------------------------
2819 // wxDataViewBitmapRenderer
2820 // ---------------------------------------------------------
2821 wxDataViewBitmapRenderer::wxDataViewBitmapRenderer(const wxString& varianttype,
2822 wxDataViewCellMode mode,
2824 : wxDataViewRenderer(varianttype,mode,align)
2829 cell = [[NSImageCell alloc] init];
2830 SetNativeData(new wxDataViewRendererNativeData(cell));
2834 // This method returns 'true' if
2835 // - the passed bitmap is valid and it could be assigned to the native data
2837 // - the passed bitmap is invalid (or is not initialized); this case
2838 // simulates a non-existing bitmap.
2839 // In all other cases the method returns 'false'.
2840 bool wxDataViewBitmapRenderer::MacRender()
2842 wxCHECK_MSG(GetValue().GetType() == GetVariantType(),false,wxString("Bitmap renderer cannot render value; value type: ") << GetValue().GetType());
2846 bitmap << GetValue();
2848 [GetNativeData()->GetItemCell() setObjectValue:[[bitmap.GetNSImage() retain] autorelease]];
2852 IMPLEMENT_CLASS(wxDataViewBitmapRenderer,wxDataViewRenderer)
2854 // -------------------------------------
2855 // wxDataViewChoiceRenderer
2856 // -------------------------------------
2857 wxDataViewChoiceRenderer::wxDataViewChoiceRenderer(const wxArrayString& choices,
2858 wxDataViewCellMode mode,
2860 : wxDataViewRenderer(wxT("string"), mode, alignment),
2863 NSPopUpButtonCell* cell;
2866 cell = [[NSPopUpButtonCell alloc] init];
2867 [cell setControlSize:NSMiniControlSize];
2868 [cell setFont:[NSFont fontWithName:[[cell font] fontName] size:[NSFont systemFontSizeForControlSize:NSMiniControlSize]]];
2869 for (size_t i=0; i<choices.GetCount(); ++i)
2870 [cell addItemWithTitle:wxCFStringRef(choices[i]).AsNSString()];
2871 SetNativeData(new wxDataViewRendererNativeData(cell));
2876 wxDataViewChoiceRenderer::OSXOnCellChanged(NSObject *value,
2877 const wxDataViewItem& item,
2880 // At least under OS X 10.7 we get the index of the item selected and not
2882 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2883 model->ChangeValue(GetChoice(ObjectToLong(value)), item, col);
2886 bool wxDataViewChoiceRenderer::MacRender()
2888 if (GetValue().GetType() == GetVariantType())
2890 [((NSPopUpButtonCell*) GetNativeData()->GetItemCell()) selectItemWithTitle:[[wxCFStringRef(GetValue().GetString()).AsNSString() retain] autorelease]];
2895 wxFAIL_MSG(wxString("Choice renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2900 IMPLEMENT_CLASS(wxDataViewChoiceRenderer,wxDataViewRenderer)
2902 // ---------------------------------------------------------
2903 // wxDataViewDateRenderer
2904 // ---------------------------------------------------------
2906 wxDataViewDateRenderer::wxDataViewDateRenderer(const wxString& varianttype,
2907 wxDataViewCellMode mode,
2909 : wxDataViewRenderer(varianttype,mode,align)
2911 NSTextFieldCell* cell;
2913 NSDateFormatter* dateFormatter;
2916 dateFormatter = [[NSDateFormatter alloc] init];
2917 [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
2918 [dateFormatter setDateStyle:NSDateFormatterShortStyle];
2919 cell = [[NSTextFieldCell alloc] init];
2920 [cell setFormatter:dateFormatter];
2921 SetNativeData(new wxDataViewRendererNativeData(cell,[NSDate dateWithString:@"2000-12-30 20:00:00 +0000"]));
2923 [dateFormatter release];
2926 bool wxDataViewDateRenderer::MacRender()
2928 if (GetValue().GetType() == GetVariantType())
2930 if (GetValue().GetDateTime().IsValid())
2932 // -- find best fitting style to show the date --
2933 // as the style should be identical for all cells a reference date
2934 // instead of the actual cell's date value is used for all cells;
2935 // this reference date is stored in the renderer's native data
2936 // section for speed purposes; otherwise, the reference date's
2937 // string has to be recalculated for each item that may become
2938 // timewise long if a lot of rows using dates exist; the algorithm
2939 // has the preference to display as much information as possible
2940 // in the first instance; but as this is often impossible due to
2941 // space restrictions the style is shortened per loop; finally, if
2942 // the shortest time and date format does not fit into the cell
2943 // the time part is dropped; remark: the time part itself is not
2944 // modified per iteration loop and only uses the short style,
2945 // means that only the hours and minutes are being shown
2947 // GetObject() returns a date for testing the size of a date object
2948 [GetNativeData()->GetItemCell() setObjectValue:GetNativeData()->GetObject()];
2949 [[GetNativeData()->GetItemCell() formatter] setTimeStyle:NSDateFormatterShortStyle];
2950 for (int dateFormatterStyle=4; dateFormatterStyle>0; --dateFormatterStyle)
2952 [[GetNativeData()->GetItemCell() formatter] setDateStyle:(NSDateFormatterStyle)dateFormatterStyle];
2953 if (dateFormatterStyle == 1)
2955 // if the shortest style for displaying the date and time
2956 // is too long to be fully visible remove the time part of
2958 if ([GetNativeData()->GetItemCell() cellSize].width > [GetNativeData()->GetColumnPtr() width])
2959 [[GetNativeData()->GetItemCell() formatter] setTimeStyle:NSDateFormatterNoStyle];
2961 // basically not necessary as the loop would end anyway
2962 // but let's save the last comparison
2966 else if ([GetNativeData()->GetItemCell() cellSize].width <= [GetNativeData()->GetColumnPtr() width])
2969 // set data (the style is set by the previous loop); on OSX the
2970 // date has to be specified with respect to UTC; in wxWidgets the
2971 // date is always entered in the local timezone; so, we have to do
2972 // a conversion from the local to UTC timezone when adding the
2973 // seconds to 1970-01-01 UTC:
2974 [GetNativeData()->GetItemCell() setObjectValue:[NSDate dateWithTimeIntervalSince1970:GetValue().GetDateTime().ToUTC().Subtract(wxDateTime(1,wxDateTime::Jan,1970)).GetSeconds().ToDouble()]];
2980 wxFAIL_MSG(wxString("Date renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2986 wxDataViewDateRenderer::OSXOnCellChanged(NSObject *value,
2987 const wxDataViewItem& item,
2990 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2991 model->ChangeValue(ObjectToDate(value), item, col);
2994 IMPLEMENT_ABSTRACT_CLASS(wxDataViewDateRenderer,wxDataViewRenderer)
2996 // ---------------------------------------------------------
2997 // wxDataViewIconTextRenderer
2998 // ---------------------------------------------------------
2999 wxDataViewIconTextRenderer::wxDataViewIconTextRenderer(const wxString& varianttype,
3000 wxDataViewCellMode mode,
3002 : wxDataViewRenderer(varianttype,mode)
3004 wxImageTextCell* cell;
3007 cell = [[wxImageTextCell alloc] init];
3008 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
3009 SetNativeData(new wxDataViewRendererNativeData(cell));
3013 bool wxDataViewIconTextRenderer::MacRender()
3015 if (GetValue().GetType() == GetVariantType())
3017 wxDataViewIconText iconText;
3019 wxImageTextCell* cell;
3021 cell = (wxImageTextCell*) GetNativeData()->GetItemCell();
3022 iconText << GetValue();
3023 if (iconText.GetIcon().IsOk())
3024 [cell setImage:[[wxBitmap(iconText.GetIcon()).GetNSImage() retain] autorelease]];
3026 [cell setImage:nil];
3027 [cell setStringValue:[[wxCFStringRef(iconText.GetText()).AsNSString() retain] autorelease]];
3032 wxFAIL_MSG(wxString("Icon & text renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
3038 wxDataViewIconTextRenderer::OSXOnCellChanged(NSObject *value,
3039 const wxDataViewItem& item,
3042 wxVariant valueIconText;
3043 valueIconText << wxDataViewIconText(ObjectToString(value));
3045 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
3046 model->ChangeValue(valueIconText, item, col);
3049 IMPLEMENT_ABSTRACT_CLASS(wxDataViewIconTextRenderer,wxDataViewRenderer)
3051 // ---------------------------------------------------------
3052 // wxDataViewToggleRenderer
3053 // ---------------------------------------------------------
3054 wxDataViewToggleRenderer::wxDataViewToggleRenderer(const wxString& varianttype,
3055 wxDataViewCellMode mode,
3057 : wxDataViewRenderer(varianttype,mode)
3062 cell = [[NSButtonCell alloc] init];
3063 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
3064 [cell setButtonType:NSSwitchButton];
3065 [cell setImagePosition:NSImageOnly];
3066 SetNativeData(new wxDataViewRendererNativeData(cell));
3070 bool wxDataViewToggleRenderer::MacRender()
3072 if (GetValue().GetType() == GetVariantType())
3074 [GetNativeData()->GetItemCell() setIntValue:GetValue().GetLong()];
3079 wxFAIL_MSG(wxString("Toggle renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
3085 wxDataViewToggleRenderer::OSXOnCellChanged(NSObject *value,
3086 const wxDataViewItem& item,
3089 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
3090 model->ChangeValue(ObjectToBool(value), item, col);
3093 IMPLEMENT_ABSTRACT_CLASS(wxDataViewToggleRenderer,wxDataViewRenderer)
3095 // ---------------------------------------------------------
3096 // wxDataViewProgressRenderer
3097 // ---------------------------------------------------------
3098 wxDataViewProgressRenderer::wxDataViewProgressRenderer(const wxString& label,
3099 const wxString& varianttype,
3100 wxDataViewCellMode mode,
3102 : wxDataViewRenderer(varianttype,mode,align)
3106 NSLevelIndicatorCell* cell;
3108 cell = [[NSLevelIndicatorCell alloc] initWithLevelIndicatorStyle:NSContinuousCapacityLevelIndicatorStyle];
3109 [cell setMinValue:0];
3110 [cell setMaxValue:100];
3111 SetNativeData(new wxDataViewRendererNativeData(cell));
3115 bool wxDataViewProgressRenderer::MacRender()
3117 if (GetValue().GetType() == GetVariantType())
3119 [GetNativeData()->GetItemCell() setIntValue:GetValue().GetLong()];
3124 wxFAIL_MSG(wxString("Progress renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
3130 wxDataViewProgressRenderer::OSXOnCellChanged(NSObject *value,
3131 const wxDataViewItem& item,
3134 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
3135 model->ChangeValue(ObjectToLong(value), item, col);
3138 IMPLEMENT_ABSTRACT_CLASS(wxDataViewProgressRenderer,wxDataViewRenderer)
3140 // ---------------------------------------------------------
3142 // ---------------------------------------------------------
3144 wxDataViewColumn::wxDataViewColumn(const wxString& title,
3145 wxDataViewRenderer* renderer,
3146 unsigned int model_column,
3150 : wxDataViewColumnBase(renderer, model_column),
3151 m_NativeDataPtr(new wxDataViewColumnNativeData()),
3154 InitCommon(width, align, flags);
3155 if (renderer && !renderer->IsCustomRenderer() &&
3156 (renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
3157 renderer->SetAlignment(align);
3160 wxDataViewColumn::wxDataViewColumn(const wxBitmap& bitmap,
3161 wxDataViewRenderer* renderer,
3162 unsigned int model_column,
3166 : wxDataViewColumnBase(bitmap, renderer, model_column),
3167 m_NativeDataPtr(new wxDataViewColumnNativeData())
3169 InitCommon(width, align, flags);
3170 if (renderer && !renderer->IsCustomRenderer() &&
3171 (renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
3172 renderer->SetAlignment(align);
3175 wxDataViewColumn::~wxDataViewColumn()
3177 delete m_NativeDataPtr;
3180 int wxDataViewColumn::GetWidth() const
3182 return [m_NativeDataPtr->GetNativeColumnPtr() width];
3185 bool wxDataViewColumn::IsSortKey() const
3187 NSTableColumn *nsCol = GetNativeData()->GetNativeColumnPtr();
3188 return nsCol && ([nsCol sortDescriptorPrototype] != nil);
3191 void wxDataViewColumn::SetAlignment(wxAlignment align)
3193 m_alignment = align;
3194 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
3195 if (m_renderer && !m_renderer->IsCustomRenderer() &&
3196 (m_renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
3197 m_renderer->SetAlignment(align);
3200 void wxDataViewColumn::SetBitmap(const wxBitmap& bitmap)
3202 // bitmaps and titles cannot exist at the same time - if the bitmap is set
3203 // the title is removed:
3204 m_title = wxEmptyString;
3205 wxDataViewColumnBase::SetBitmap(bitmap);
3206 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setImage:[[bitmap.GetNSImage() retain] autorelease]];
3209 void wxDataViewColumn::SetMaxWidth(int maxWidth)
3211 m_maxWidth = maxWidth;
3212 [m_NativeDataPtr->GetNativeColumnPtr() setMaxWidth:maxWidth];
3215 void wxDataViewColumn::SetMinWidth(int minWidth)
3217 m_minWidth = minWidth;
3218 [m_NativeDataPtr->GetNativeColumnPtr() setMinWidth:minWidth];
3221 void wxDataViewColumn::SetReorderable(bool reorderable)
3223 wxUnusedVar(reorderable);
3226 void wxDataViewColumn::SetHidden(bool hidden)
3228 // How to set flag here?
3230 [m_NativeDataPtr->GetNativeColumnPtr() setHidden:hidden];
3233 bool wxDataViewColumn::IsHidden() const
3235 return [m_NativeDataPtr->GetNativeColumnPtr() isHidden];
3238 void wxDataViewColumn::SetResizeable(bool resizable)
3240 wxDataViewColumnBase::SetResizeable(resizable);
3242 [m_NativeDataPtr->GetNativeColumnPtr() setResizingMask:NSTableColumnUserResizingMask];
3244 [m_NativeDataPtr->GetNativeColumnPtr() setResizingMask:NSTableColumnNoResizing];
3247 void wxDataViewColumn::SetSortable(bool sortable)
3249 // wxDataViewColumnBase::SetSortable(sortable);
3250 // Avoid endless recursion and just set the flag here
3252 m_flags |= wxDATAVIEW_COL_SORTABLE;
3254 m_flags &= ~wxDATAVIEW_COL_SORTABLE;
3257 void wxDataViewColumn::SetSortOrder(bool ascending)
3259 if (m_ascending != ascending)
3261 m_ascending = ascending;
3264 // change sorting order:
3265 NSArray* sortDescriptors;
3266 NSSortDescriptor* sortDescriptor;
3267 NSTableColumn* tableColumn;
3269 tableColumn = m_NativeDataPtr->GetNativeColumnPtr();
3270 sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[[tableColumn sortDescriptorPrototype] key] ascending:m_ascending];
3271 sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
3272 [tableColumn setSortDescriptorPrototype:sortDescriptor];
3273 [[tableColumn tableView] setSortDescriptors:sortDescriptors];
3274 [sortDescriptor release];
3279 void wxDataViewColumn::SetTitle(const wxString& title)
3281 // bitmaps and titles cannot exist at the same time - if the title is set
3282 // the bitmap is removed:
3283 wxDataViewColumnBase::SetBitmap(wxBitmap());
3285 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setStringValue:[[wxCFStringRef(title).AsNSString() retain] autorelease]];
3288 void wxDataViewColumn::SetWidth(int width)
3294 case wxCOL_WIDTH_AUTOSIZE:
3295 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
3298 wxCocoaDataViewControl *peer = static_cast<wxCocoaDataViewControl*>(GetOwner()->GetPeer());
3299 peer->FitColumnWidthToContent(GetOwner()->GetColumnPosition(this));
3303 // fall through if unsupported (OSX < 10.5) or not yet settable
3305 case wxCOL_WIDTH_DEFAULT:
3306 width = wxDVC_DEFAULT_WIDTH;
3310 [m_NativeDataPtr->GetNativeColumnPtr() setWidth:width];
3315 void wxDataViewColumn::SetNativeData(wxDataViewColumnNativeData* newNativeDataPtr)
3317 delete m_NativeDataPtr;
3318 m_NativeDataPtr = newNativeDataPtr;
3321 #endif // (wxUSE_DATAVIEWCTRL == 1) && !defined(wxUSE_GENERICDATAVIEWCTRL)