]> git.saurik.com Git - wxWidgets.git/blob - src/osx/cocoa/dataview.mm
Compilation fix to wxWebView under wxOSX/Carbon after r71620.
[wxWidgets.git] / src / osx / cocoa / dataview.mm
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/cocoa/dataview.mm
3 // Purpose: wxDataView
4 // Author:
5 // Modified by:
6 // Created: 2009-01-31
7 // RCS-ID: $Id: dataview.mm$
8 // Copyright:
9 // Licence: wxWindows licence
10 ///////////////////////////////////////////////////////////////////////////////
11
12 #include "wx/wxprec.h"
13
14 #if (wxUSE_DATAVIEWCTRL == 1) && !defined(wxUSE_GENERICDATAVIEWCTRL)
15
16 #ifndef WX_PRECOMP
17 #include "wx/app.h"
18 #include "wx/toplevel.h"
19 #include "wx/font.h"
20 #include "wx/settings.h"
21 #include "wx/utils.h"
22 #endif
23
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"
29
30 // ============================================================================
31 // Constants used locally
32 // ============================================================================
33
34 #define DataViewPboardType @"OutlineViewItem"
35
36 // ============================================================================
37 // Classes used locally in dataview.mm
38 // ============================================================================
39
40 // ============================================================================
41 // wxPointerObject
42 // ============================================================================
43
44 @implementation wxPointerObject
45
46 -(id) init
47 {
48 self = [super init];
49 if (self != nil)
50 self->pointer = NULL;
51 return self;
52 }
53
54 -(id) initWithPointer:(void*) initPointer
55 {
56 self = [super init];
57 if (self != nil)
58 self->pointer = initPointer;
59 return self;
60 }
61
62 //
63 // inherited methods from NSObject
64 //
65 -(BOOL) isEqual:(id)object
66 {
67 return (object != nil) &&
68 ([object isKindOfClass:[wxPointerObject class]]) &&
69 (pointer == [((wxPointerObject*) object) pointer]);
70 }
71
72 -(NSUInteger) hash
73 {
74 return (NSUInteger) pointer;
75 }
76
77 -(void*) pointer
78 {
79 return pointer;
80 }
81
82 -(void) setPointer:(void*) newPointer
83 {
84 pointer = newPointer;
85 }
86
87 @end
88
89 namespace
90 {
91
92 inline wxDataViewItem wxDataViewItemFromItem(id item)
93 {
94 return wxDataViewItem([static_cast<wxPointerObject *>(item) pointer]);
95 }
96
97 inline wxDataViewItem wxDataViewItemFromMaybeNilItem(id item)
98 {
99 return item == nil ? wxDataViewItem() : wxDataViewItemFromItem(item);
100 }
101
102 } // anonymous namespace
103
104 // ----------------------------------------------------------------------------
105 // wxCustomRendererObject
106 // ----------------------------------------------------------------------------
107
108 @interface wxCustomRendererObject : NSObject <NSCopying>
109 {
110 @public
111 wxDataViewCustomRenderer* customRenderer; // not owned by the class
112 }
113
114 -(id) init;
115 -(id) initWithRenderer:(wxDataViewCustomRenderer*)renderer;
116 @end
117
118 @implementation wxCustomRendererObject
119
120 -(id) init
121 {
122 self = [super init];
123 if (self != nil)
124 {
125 customRenderer = NULL;
126 }
127 return self;
128 }
129
130 -(id) initWithRenderer:(wxDataViewCustomRenderer*)renderer
131 {
132 self = [super init];
133 if (self != nil)
134 {
135 customRenderer = renderer;
136 }
137 return self;
138 }
139
140 -(id) copyWithZone:(NSZone*)zone
141 {
142 wxCustomRendererObject* copy;
143
144 copy = [[[self class] allocWithZone:zone] init];
145 copy->customRenderer = customRenderer;
146
147 return copy;
148 }
149 @end
150
151 // ----------------------------------------------------------------------------
152 // wxDVCNSTableColumn: exists only to override NSTableColumn:dataCellForRow:
153 // ----------------------------------------------------------------------------
154
155 @interface wxDVCNSTableColumn : NSTableColumn
156 {
157 }
158
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;
163
164 // Initialize the column with the given pointer to the associated
165 // wxDataViewColumn. This pointer can later be retrieved using
166 // getColumnPointer.
167 -(id) initWithColumnPointer:(const wxDataViewColumn*)column;
168
169 // Retrieve the associated column.
170 -(wxDataViewColumn*) getColumnPointer;
171
172 -(id) dataCellForRow:(NSInteger)row;
173 @end
174
175 @implementation wxDVCNSTableColumn
176
177 +(NSString*) identifierForColumnPointer:(const wxDataViewColumn*)column
178 {
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)];
184 }
185
186 -(id) initWithColumnPointer:(const wxDataViewColumn*)column
187 {
188 [self initWithIdentifier: [wxDVCNSTableColumn identifierForColumnPointer:column]];
189 return self;
190 }
191
192 -(wxDataViewColumn*) getColumnPointer
193 {
194 // The case to NSString is needed for OS X < 10.7.
195 return reinterpret_cast<wxDataViewColumn*>(
196 [static_cast<NSString*>([self identifier]) integerValue]);
197 }
198
199 -(id) dataCellForRow:(NSInteger)row
200 {
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
205
206 const wxDataViewColumn * const dvCol = [self getColumnPointer];
207
208 const wxDataViewCtrl * const dvc = dvCol->GetOwner();
209 const wxCocoaDataViewControl * const
210 peer = static_cast<wxCocoaDataViewControl *>(dvc->GetPeer());
211
212
213 // once we do have everything, simply ask NSOutlineView for the item...
214 const id item = peer->GetItemAtRow(row);
215 if ( item )
216 {
217 // ... and if it succeeded, ask the model whether it has any value
218 wxDataViewItem dvItem(wxDataViewItemFromItem(item));
219
220 if ( !dvc->GetModel()->HasValue(dvItem, dvCol->GetModelColumn()) )
221 return nil;
222 }
223
224 return [super dataCellForRow:row];
225 }
226
227 @end
228
229 // ============================================================================
230 // local helpers
231 // ============================================================================
232
233 namespace
234 {
235
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)
239 {
240 wxCHECK_MSG( [object isKindOfClass:[NSString class]], "",
241 wxString::Format
242 (
243 "string expected but got %s",
244 wxCFStringRef::AsString([object className])
245 ));
246
247 return wxCFStringRef([((NSString*) object) retain]).AsString();
248 }
249
250 bool ObjectToBool(NSObject *object)
251 {
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,
255 wxString::Format
256 (
257 "number expected but got %s",
258 wxCFStringRef::AsString([object className])
259 ));
260
261 return [(NSNumber *)object boolValue];
262 }
263
264 long ObjectToLong(NSObject *object)
265 {
266 wxCHECK_MSG( [object isKindOfClass:[NSNumber class]], -1,
267 wxString::Format
268 (
269 "number expected but got %s",
270 wxCFStringRef::AsString([object className])
271 ));
272
273 return [(NSNumber *)object longValue];
274 }
275
276 wxDateTime ObjectToDate(NSObject *object)
277 {
278 wxCHECK_MSG( [object isKindOfClass:[NSDate class]], wxInvalidDateTime,
279 wxString::Format
280 (
281 "date expected but got %s",
282 wxCFStringRef::AsString([object className])
283 ));
284
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];
288
289 wxDateTime dt(1, wxDateTime::Jan, 1970);
290 dt.Add(wxTimeSpan(0,0,seconds));
291
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);
297
298 return dt;
299 }
300
301 NSInteger CompareItems(id item1, id item2, void* context)
302 {
303 NSArray* const sortDescriptors = (NSArray*) context;
304
305 NSUInteger const count = [sortDescriptors count];
306
307 NSInteger result = NSOrderedSame;
308 for ( NSUInteger i = 0; i < count && result == NSOrderedSame; ++i )
309 {
310 wxSortDescriptorObject* const
311 sortDescriptor = (wxSortDescriptorObject*)
312 [sortDescriptors objectAtIndex:i];
313
314 int rc = [sortDescriptor modelPtr]->Compare
315 (
316 wxDataViewItemFromItem(item1),
317 wxDataViewItemFromItem(item2),
318 [sortDescriptor columnPtr]->GetModelColumn(),
319 [sortDescriptor ascending] == YES
320 );
321
322 if ( rc < 0 )
323 result = NSOrderedAscending;
324 else if ( rc > 0 )
325 result = NSOrderedDescending;
326 }
327
328 return result;
329 }
330
331 NSTextAlignment ConvertToNativeHorizontalTextAlignment(int alignment)
332 {
333 if (alignment & wxALIGN_CENTER_HORIZONTAL)
334 return NSCenterTextAlignment;
335 else if (alignment & wxALIGN_RIGHT)
336 return NSRightTextAlignment;
337 else
338 return NSLeftTextAlignment;
339 }
340
341 NSTableColumn* CreateNativeColumn(const wxDataViewColumn *column)
342 {
343 wxDataViewRenderer * const renderer = column->GetRenderer();
344
345 wxCHECK_MSG( renderer, NULL, "column should have a renderer" );
346
347 wxDVCNSTableColumn * const nativeColumn(
348 [[wxDVCNSTableColumn alloc] initWithColumnPointer: column]
349 );
350
351 // setting the size related parameters:
352 int resizingMask;
353 if (column->IsResizeable())
354 {
355 resizingMask = NSTableColumnUserResizingMask;
356 [nativeColumn setMinWidth:column->GetMinWidth()];
357 [nativeColumn setMaxWidth:column->GetMaxWidth()];
358 }
359 else // column is not resizable [by user]
360 {
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;
368 }
369 [nativeColumn setResizingMask:resizingMask];
370
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())];
374 #endif
375
376 wxDataViewRendererNativeData * const renderData = renderer->GetNativeData();
377
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]);
384
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;
391
392 [nativeColumn setEditable:isEditable];
393 [[nativeColumn dataCell] setEditable:isEditable];
394
395 return nativeColumn;
396 }
397
398 } // anonymous namespace
399
400 // ============================================================================
401 // Public helper functions for dataview implementation on OSX
402 // ============================================================================
403
404 wxWidgetImplType* CreateDataView(wxWindowMac* wxpeer,
405 wxWindowMac* WXUNUSED(parent),
406 wxWindowID WXUNUSED(id),
407 const wxPoint& pos,
408 const wxSize& size,
409 long style,
410 long WXUNUSED(extraStyle))
411 {
412 return new wxCocoaDataViewControl(wxpeer,pos,size,style);
413 }
414
415 // ============================================================================
416 // wxSortDescriptorObject
417 // ============================================================================
418
419 @implementation wxSortDescriptorObject
420 -(id) init
421 {
422 self = [super init];
423 if (self != nil)
424 {
425 columnPtr = NULL;
426 modelPtr = NULL;
427 }
428 return self;
429 }
430
431 -(id)
432 initWithModelPtr:(wxDataViewModel*)initModelPtr
433 sortingColumnPtr:(wxDataViewColumn*)initColumnPtr
434 ascending:(BOOL)sortAscending
435 {
436 self = [super initWithKey:@"dummy" ascending:sortAscending];
437 if (self != nil)
438 {
439 columnPtr = initColumnPtr;
440 modelPtr = initModelPtr;
441 }
442 return self;
443 }
444
445 -(id) copyWithZone:(NSZone*)zone
446 {
447 wxSortDescriptorObject* copy;
448
449
450 copy = [super copyWithZone:zone];
451 copy->columnPtr = columnPtr;
452 copy->modelPtr = modelPtr;
453
454 return copy;
455 }
456
457 //
458 // access to model column's index
459 //
460 -(wxDataViewColumn*) columnPtr
461 {
462 return columnPtr;
463 }
464
465 -(wxDataViewModel*) modelPtr
466 {
467 return modelPtr;
468 }
469
470 -(void) setColumnPtr:(wxDataViewColumn*)newColumnPtr
471 {
472 columnPtr = newColumnPtr;
473 }
474
475 -(void) setModelPtr:(wxDataViewModel*)newModelPtr
476 {
477 modelPtr = newModelPtr;
478 }
479
480 @end
481
482 // ============================================================================
483 // wxCocoaOutlineDataSource
484 // ============================================================================
485 @implementation wxCocoaOutlineDataSource
486
487 //
488 // constructors / destructor
489 //
490 -(id) init
491 {
492 self = [super init];
493 if (self != nil)
494 {
495 implementation = NULL;
496 model = NULL;
497
498 currentParentItem = nil;
499
500 children = [[NSMutableArray alloc] init];
501 items = [[NSMutableSet alloc] init];
502 }
503 return self;
504 }
505
506 -(void) dealloc
507 {
508 [currentParentItem release];
509
510 [children release];
511 [items release];
512
513 [super dealloc];
514 }
515
516 //
517 // methods of informal protocol:
518 //
519 -(BOOL)
520 outlineView:(NSOutlineView*)outlineView
521 acceptDrop:(id<NSDraggingInfo>)info
522 item:(id)item childIndex:(NSInteger)index
523 {
524 wxUnusedVar(outlineView);
525 wxUnusedVar(index);
526
527 NSArray* supportedTypes(
528 [NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]
529 );
530
531 NSPasteboard* pasteboard([info draggingPasteboard]);
532
533 NSString* bestType([pasteboard availableTypeFromArray:supportedTypes]);
534
535 if ( bestType == nil )
536 return FALSE;
537
538 wxDataViewCtrl * const dvc(implementation->GetDataViewCtrl());
539
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." );
544
545 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_DROP, dvc->GetId());
546 event.SetEventObject(dvc);
547 event.SetItem(wxDataViewItemFromItem(item));
548 event.SetModel(dvc->GetModel());
549
550 BOOL dragSuccessful = false;
551 if ( [bestType compare:DataViewPboardType] == NSOrderedSame )
552 {
553 NSArray* dataArray((NSArray*)
554 [pasteboard propertyListForType:DataViewPboardType]);
555 NSUInteger indexDraggedItem, noOfDraggedItems([dataArray count]);
556
557 indexDraggedItem = 0;
558 while (indexDraggedItem < noOfDraggedItems)
559 {
560 wxDataObjectComposite* dataObjects(
561 implementation->GetDnDDataObjects((NSData*)
562 [dataArray objectAtIndex:indexDraggedItem]));
563
564 if (dataObjects && (dataObjects->GetFormatCount() > 0))
565 {
566 wxMemoryBuffer buffer;
567
568 // copy data into data object:
569 event.SetDataObject(dataObjects);
570 event.SetDataFormat(
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())
580 {
581 dragSuccessful = true;
582 ++indexDraggedItem;
583 }
584 else
585 {
586 dragSuccessful = true;
587 indexDraggedItem = noOfDraggedItems; // stop loop
588 }
589 }
590 else
591 {
592 dragSuccessful = false;
593 indexDraggedItem = noOfDraggedItems; // stop loop
594 }
595 // clean-up:
596 delete dataObjects;
597 }
598 }
599 else
600 {
601 // needed to convert internally used UTF-16 representation to a UTF-8
602 // representation
603 CFDataRef osxData;
604 wxDataObjectComposite* dataObjects (new wxDataObjectComposite());
605 wxTextDataObject* textDataObject(new wxTextDataObject());
606
607 osxData = ::CFStringCreateExternalRepresentation
608 (
609 kCFAllocatorDefault,
610 (CFStringRef)[pasteboard stringForType:NSStringPboardType],
611 kCFStringEncodingUTF8,
612 32
613 );
614 if (textDataObject->SetData(::CFDataGetLength(osxData),
615 ::CFDataGetBytePtr(osxData)))
616 dataObjects->Add(textDataObject);
617 else
618 delete textDataObject;
619 // send event if data could be copied:
620 if (dataObjects->GetFormatCount() > 0)
621 {
622 event.SetDataObject(dataObjects);
623 event.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
624 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
625 dragSuccessful = true;
626 else
627 dragSuccessful = false;
628 }
629 else
630 dragSuccessful = false;
631 // clean up:
632 ::CFRelease(osxData);
633 delete dataObjects;
634 }
635 return dragSuccessful;
636 }
637
638 -(id) outlineView:(NSOutlineView*)outlineView
639 child:(NSInteger)index
640 ofItem:(id)item
641 {
642 wxUnusedVar(outlineView);
643
644 if ((item == currentParentItem) &&
645 (index < ((NSInteger) [self getChildCount])))
646 return [self getChild:index];
647
648 wxDataViewItemArray dataViewChildren;
649
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];
656 }
657
658 -(BOOL) outlineView:(NSOutlineView*)outlineView isItemExpandable:(id)item
659 {
660 wxUnusedVar(outlineView);
661
662 wxCHECK_MSG( model, 0, "Valid model in data source does not exist." );
663 return model->IsContainer(wxDataViewItemFromItem(item));
664 }
665
666 -(NSInteger) outlineView:(NSOutlineView*)outlineView numberOfChildrenOfItem:(id)item
667 {
668 wxUnusedVar(outlineView);
669
670 NSInteger noOfChildren;
671
672 wxDataViewItemArray dataViewChildren;
673
674
675 wxCHECK_MSG( model, 0, "Valid model in data source does not exist." );
676 noOfChildren = model->GetChildren(wxDataViewItemFromMaybeNilItem(item),
677 dataViewChildren);
678 [self bufferItem:item withChildren:&dataViewChildren];
679 if ([sortDescriptors count] > 0)
680 [children sortUsingFunction:CompareItems context:sortDescriptors];
681 return noOfChildren;
682 }
683
684 -(id)
685 outlineView:(NSOutlineView*)outlineView
686 objectValueForTableColumn:(NSTableColumn*)tableColumn
687 byItem:(id)item
688 {
689 wxUnusedVar(outlineView);
690
691 wxCHECK_MSG( model, nil, "Valid model in data source does not exist." );
692
693 wxDataViewColumn* const
694 col([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
695 const unsigned colIdx = col->GetModelColumn();
696
697 wxDataViewItem dataViewItem(wxDataViewItemFromItem(item));
698
699 if ( model->HasValue(dataViewItem, colIdx) )
700 {
701 wxVariant value;
702 model->GetValue(value,dataViewItem, colIdx);
703 col->GetRenderer()->SetValue(value);
704 }
705
706 return nil;
707 }
708
709 -(void)
710 outlineView:(NSOutlineView*)outlineView
711 setObjectValue:(id)object
712 forTableColumn:(NSTableColumn*)tableColumn
713 byItem:(id)item
714 {
715 wxUnusedVar(outlineView);
716
717 wxDataViewColumn* const
718 col([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
719
720 col->GetRenderer()->
721 OSXOnCellChanged(object, wxDataViewItemFromItem(item), col->GetModelColumn());
722 }
723
724 -(void) outlineView:(NSOutlineView*)outlineView sortDescriptorsDidChange:(NSArray*)oldDescriptors
725 {
726 wxUnusedVar(oldDescriptors);
727
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;
732
733 NSMutableArray* wxSortDescriptors;
734
735 NSUInteger noOfDescriptors;
736
737 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
738
739
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)
745 {
746 NSSortDescriptor* const newDescriptor = [newDescriptors objectAtIndex:i];
747
748 [wxSortDescriptors addObject:[[[wxSortDescriptorObject alloc] initWithModelPtr:model
749 sortingColumnPtr:dvc->GetColumn([[newDescriptor key] intValue])
750 ascending:[newDescriptor ascending]] autorelease]];
751 }
752 [(wxCocoaOutlineDataSource*)[outlineView dataSource] setSortDescriptors:wxSortDescriptors];
753
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 defintion
757
758 event.SetEventObject(dvc);
759 if (noOfDescriptors > 0)
760 {
761 wxDataViewColumn* const col = [[wxSortDescriptors objectAtIndex:0] columnPtr];
762
763 event.SetColumn(dvc->GetColumnPosition(col));
764 event.SetDataViewColumn(col);
765 }
766 dvc->GetEventHandler()->ProcessEvent(event);
767
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];
773 }
774
775 -(NSDragOperation) outlineView:(NSOutlineView*)outlineView validateDrop:(id<NSDraggingInfo>)info proposedItem:(id)item proposedChildIndex:(NSInteger)index
776 {
777 wxUnusedVar(outlineView);
778 wxUnusedVar(index);
779
780 NSArray* supportedTypes([NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]);
781
782 NSPasteboard* pasteboard([info draggingPasteboard]);
783
784 NSString* bestType([pasteboard availableTypeFromArray:supportedTypes]);
785 if (bestType == nil)
786 return NSDragOperationNone;
787
788 NSDragOperation dragOperation = NSDragOperationNone;
789 wxDataViewCtrl* const dvc(implementation->GetDataViewCtrl());
790
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.");
793
794 wxDataViewEvent
795 event(wxEVT_COMMAND_DATAVIEW_ITEM_DROP_POSSIBLE,dvc->GetId());
796
797 event.SetEventObject(dvc);
798 event.SetItem(wxDataViewItemFromItem(item));
799 event.SetModel(dvc->GetModel());
800 if ([bestType compare:DataViewPboardType] == NSOrderedSame)
801 {
802 NSArray* dataArray((NSArray*)[pasteboard propertyListForType:DataViewPboardType]);
803 NSUInteger indexDraggedItem, noOfDraggedItems([dataArray count]);
804
805 indexDraggedItem = 0;
806 while (indexDraggedItem < noOfDraggedItems)
807 {
808 wxDataObjectComposite* dataObjects(implementation->GetDnDDataObjects((NSData*)[dataArray objectAtIndex:indexDraggedItem]));
809
810 if (dataObjects && (dataObjects->GetFormatCount() > 0))
811 {
812 wxMemoryBuffer buffer;
813
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())
823 {
824 dragOperation = NSDragOperationEvery;
825 ++indexDraggedItem;
826 }
827 else
828 {
829 dragOperation = NSDragOperationNone;
830 indexDraggedItem = noOfDraggedItems; // stop loop
831 }
832 }
833 else
834 {
835 dragOperation = NSDragOperationNone;
836 indexDraggedItem = noOfDraggedItems; // stop loop
837 }
838 // clean-up:
839 delete dataObjects;
840 }
841 }
842 else
843 {
844 // needed to convert internally used UTF-16 representation to a UTF-8
845 // representation
846 CFDataRef osxData;
847 wxDataObjectComposite* dataObjects (new wxDataObjectComposite());
848 wxTextDataObject* textDataObject(new wxTextDataObject());
849
850 osxData = ::CFStringCreateExternalRepresentation(kCFAllocatorDefault,(CFStringRef)[pasteboard stringForType:NSStringPboardType],kCFStringEncodingUTF8,32);
851 if (textDataObject->SetData(::CFDataGetLength(osxData),::CFDataGetBytePtr(osxData)))
852 dataObjects->Add(textDataObject);
853 else
854 delete textDataObject;
855 // send event if data could be copied:
856 if (dataObjects->GetFormatCount() > 0)
857 {
858 event.SetDataObject(dataObjects);
859 event.SetDataFormat(implementation->GetDnDDataFormat(dataObjects));
860 if (dvc->HandleWindowEvent(event) && event.IsAllowed())
861 dragOperation = NSDragOperationEvery;
862 else
863 dragOperation = NSDragOperationNone;
864 }
865 else
866 dragOperation = NSDragOperationNone;
867 // clean up:
868 ::CFRelease(osxData);
869 delete dataObjects;
870 }
871
872 return dragOperation;
873 }
874
875 -(BOOL) outlineView:(NSOutlineView*)outlineView writeItems:(NSArray*)writeItems toPasteboard:(NSPasteboard*)pasteboard
876 {
877 wxUnusedVar(outlineView);
878
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();
884
885 wxDataViewItemArray dataViewItems;
886
887
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.");
890
891 if ([writeItems count] > 0)
892 {
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
896
897 // send a begin drag event for all selected items and proceed with
898 // dragging unless the event is vetoed:
899 wxDataViewEvent
900 event(wxEVT_COMMAND_DATAVIEW_ITEM_BEGIN_DRAG,dvc->GetId());
901
902 event.SetEventObject(dvc);
903 event.SetModel(dvc->GetModel());
904 for (size_t itemCounter=0; itemCounter<[writeItems count]; ++itemCounter)
905 {
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
909
910 event.SetItem(
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))
917 {
918 size_t const noOfFormats = event.GetDataObject()->GetFormatCount();
919 wxDataFormat* dataFormats(new wxDataFormat[noOfFormats]);
920
921 event.GetDataObject()->GetAllFormats(dataFormats,wxDataObject::Get);
922 for (size_t formatCounter=0; formatCounter<noOfFormats; ++formatCounter)
923 {
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);
930
931 dataBuffer.AppendData(&idDataFormat,sizeof(wxDataFormatId));
932 switch (idDataFormat)
933 {
934 case wxDF_TEXT:
935 // otherwise wxDF_UNICODETEXT already filled up
936 // the string; and the UNICODE representation has
937 // priority
938 if (!itemStringAvailable)
939 {
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;
945 }
946 break;
947 case wxDF_UNICODETEXT:
948 {
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]];
953 else
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;
957 } /* block */
958 break;
959 default:
960 wxFAIL_MSG("Data object has invalid or unsupported data format");
961 [dataArray release];
962 return NO;
963 }
964 }
965 delete[] dataFormats;
966 delete itemObject;
967 if (dataStringAvailable)
968 if (itemStringAvailable)
969 {
970 if (itemCounter > 0)
971 dataString << wxT('\n');
972 dataString << itemString;
973 }
974 else
975 dataStringAvailable = false;
976 }
977 else
978 {
979 [dataArray release];
980 delete itemObject;
981 return NO; // dragging was vetoed or no data available
982 }
983 }
984 if (dataStringAvailable)
985 {
986 wxCFStringRef osxString(dataString);
987
988 [pasteboard declareTypes:[NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil] owner:nil];
989 [pasteboard setPropertyList:dataArray forType:DataViewPboardType];
990 [pasteboard setString:osxString.AsNSString() forType:NSStringPboardType];
991 }
992 else
993 {
994 [pasteboard declareTypes:[NSArray arrayWithObject:DataViewPboardType] owner:nil];
995 [pasteboard setPropertyList:dataArray forType:DataViewPboardType];
996 }
997 return YES;
998 }
999 else
1000 return NO; // no items to drag (should never occur)
1001 }
1002
1003 //
1004 // buffer handling
1005 //
1006 -(void) addToBuffer:(wxPointerObject*)item
1007 {
1008 [items addObject:item];
1009 }
1010
1011 -(void) clearBuffer
1012 {
1013 [items removeAllObjects];
1014 }
1015
1016 -(wxPointerObject*) getDataViewItemFromBuffer:(const wxDataViewItem&)item
1017 {
1018 return [items member:[[[wxPointerObject alloc] initWithPointer:item.GetID()] autorelease]];
1019 }
1020
1021 -(wxPointerObject*) getItemFromBuffer:(wxPointerObject*)item
1022 {
1023 return [items member:item];
1024 }
1025
1026 -(BOOL) isInBuffer:(wxPointerObject*)item
1027 {
1028 return [items containsObject:item];
1029 }
1030
1031 -(void) removeFromBuffer:(wxPointerObject*)item
1032 {
1033 [items removeObject:item];
1034 }
1035
1036 //
1037 // children handling
1038 //
1039 -(void) appendChild:(wxPointerObject*)item
1040 {
1041 [children addObject:item];
1042 }
1043
1044 -(void) clearChildren
1045 {
1046 [children removeAllObjects];
1047 }
1048
1049 -(wxPointerObject*) getChild:(NSUInteger)index
1050 {
1051 return [children objectAtIndex:index];
1052 }
1053
1054 -(NSUInteger) getChildCount
1055 {
1056 return [children count];
1057 }
1058
1059 -(void) removeChild:(NSUInteger)index
1060 {
1061 [children removeObjectAtIndex:index];
1062 }
1063
1064 //
1065 // buffer handling
1066 //
1067 -(void) clearBuffers
1068 {
1069 [self clearBuffer];
1070 [self clearChildren];
1071 [self setCurrentParentItem:nil];
1072 }
1073
1074 //
1075 // sorting
1076 //
1077 -(NSArray*) sortDescriptors
1078 {
1079 return sortDescriptors;
1080 }
1081
1082 -(void) setSortDescriptors:(NSArray*)newSortDescriptors
1083 {
1084 [newSortDescriptors retain];
1085 [sortDescriptors release];
1086 sortDescriptors = newSortDescriptors;
1087 }
1088
1089 //
1090 // access to wxWidget's implementation
1091 //
1092 -(wxPointerObject*) currentParentItem
1093 {
1094 return currentParentItem;
1095 }
1096
1097 -(wxCocoaDataViewControl*) implementation
1098 {
1099 return implementation;
1100 }
1101
1102 -(wxDataViewModel*) model
1103 {
1104 return model;
1105 }
1106
1107 -(void) setCurrentParentItem:(wxPointerObject*)newCurrentParentItem
1108 {
1109 [newCurrentParentItem retain];
1110 [currentParentItem release];
1111 currentParentItem = newCurrentParentItem;
1112 }
1113
1114 -(void) setImplementation:(wxCocoaDataViewControl*) newImplementation
1115 {
1116 implementation = newImplementation;
1117 }
1118
1119 -(void) setModel:(wxDataViewModel*) newModel
1120 {
1121 model = newModel;
1122 }
1123
1124 //
1125 // other methods
1126 //
1127 -(void) bufferItem:(wxPointerObject*)parentItem withChildren:(wxDataViewItemArray*)dataViewChildrenPtr
1128 {
1129 NSInteger const noOfChildren = (*dataViewChildrenPtr).GetCount();
1130
1131 [self setCurrentParentItem:parentItem];
1132 [self clearChildren];
1133 for (NSInteger indexChild=0; indexChild<noOfChildren; ++indexChild)
1134 {
1135 wxPointerObject* bufferedPointerObject;
1136 wxPointerObject* newPointerObject([[wxPointerObject alloc] initWithPointer:(*dataViewChildrenPtr)[indexChild].GetID()]);
1137
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)
1152 {
1153 [items addObject:newPointerObject];
1154 [children addObject:newPointerObject];
1155 }
1156 else
1157 [children addObject:bufferedPointerObject];
1158 [newPointerObject release];
1159 }
1160 }
1161
1162 @end
1163
1164 // ============================================================================
1165 // wxCustomCell
1166 // ============================================================================
1167
1168 @implementation wxCustomCell
1169
1170 -(NSSize) cellSize
1171 {
1172 wxCustomRendererObject * const
1173 obj = static_cast<wxCustomRendererObject *>([self objectValue]);
1174
1175
1176 const wxSize size = obj->customRenderer->GetSize();
1177 return NSMakeSize(size.x, size.y);
1178 }
1179
1180 //
1181 // implementations
1182 //
1183 -(void) drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
1184 {
1185 wxCustomRendererObject * const
1186 obj = static_cast<wxCustomRendererObject *>([self objectValue]);
1187 if ( !obj )
1188 {
1189 // this may happen for the custom cells in container rows: they don't
1190 // have any values
1191 return;
1192 }
1193
1194 wxDataViewCustomRenderer * const renderer = obj->customRenderer;
1195
1196 // if this method is called everything is already setup correctly,
1197 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1198 CGContextSaveGState( context );
1199
1200 if ( ![controlView isFlipped] )
1201 {
1202 CGContextTranslateCTM( context, 0, [controlView bounds].size.height );
1203 CGContextScaleCTM( context, 1, -1 );
1204 }
1205
1206 wxGCDC dc;
1207 wxGraphicsContext* gc = wxGraphicsContext::CreateFromNative(context);
1208 dc.SetGraphicsContext(gc);
1209
1210 int state = 0;
1211 if ( [self isHighlighted] )
1212 state |= wxDATAVIEW_CELL_SELECTED;
1213
1214 renderer->WXCallRender(wxFromNSRect(controlView, cellFrame), &dc, state);
1215
1216 CGContextRestoreGState( context );
1217 }
1218
1219 -(NSRect) imageRectForBounds:(NSRect)cellFrame
1220 {
1221 return cellFrame;
1222 }
1223
1224 -(NSRect) titleRectForBounds:(NSRect)cellFrame
1225 {
1226 return cellFrame;
1227 }
1228
1229 @end
1230
1231 // ============================================================================
1232 // wxImageTextCell
1233 // ============================================================================
1234 @implementation wxImageTextCell
1235 //
1236 // initialization
1237 //
1238 -(id) init
1239 {
1240 self = [super init];
1241 if (self != nil)
1242 {
1243 // initializing the text part:
1244 [self setSelectable:YES];
1245 // initializing the image part:
1246 image = nil;
1247 imageSize = NSMakeSize(16,16);
1248 spaceImageText = 5.0;
1249 xImageShift = 5.0;
1250 }
1251 return self;
1252 }
1253
1254 -(id) copyWithZone:(NSZone*)zone
1255 {
1256 wxImageTextCell* cell;
1257
1258
1259 cell = (wxImageTextCell*) [super copyWithZone:zone];
1260 cell->image = [image retain];
1261 cell->imageSize = imageSize;
1262 cell->spaceImageText = spaceImageText;
1263 cell->xImageShift = xImageShift;
1264
1265 return cell;
1266 }
1267
1268 -(void) dealloc
1269 {
1270 [image release];
1271
1272 [super dealloc];
1273 }
1274
1275 //
1276 // alignment
1277 //
1278 -(NSTextAlignment) alignment
1279 {
1280 return cellAlignment;
1281 }
1282
1283 -(void) setAlignment:(NSTextAlignment)newAlignment
1284 {
1285 cellAlignment = newAlignment;
1286 switch (newAlignment)
1287 {
1288 case NSCenterTextAlignment:
1289 case NSLeftTextAlignment:
1290 case NSJustifiedTextAlignment:
1291 case NSNaturalTextAlignment:
1292 [super setAlignment:NSLeftTextAlignment];
1293 break;
1294 case NSRightTextAlignment:
1295 [super setAlignment:NSRightTextAlignment];
1296 break;
1297 default:
1298 wxFAIL_MSG("Unknown alignment type.");
1299 }
1300 }
1301
1302 //
1303 // image access
1304 //
1305 -(NSImage*) image
1306 {
1307 return image;
1308 }
1309
1310 -(void) setImage:(NSImage*)newImage
1311 {
1312 [newImage retain];
1313 [image release];
1314 image = newImage;
1315 }
1316
1317 -(NSSize) imageSize
1318 {
1319 return imageSize;
1320 }
1321
1322 -(void) setImageSize:(NSSize) newImageSize
1323 {
1324 imageSize = newImageSize;
1325 }
1326
1327 //
1328 // other methods
1329 //
1330 -(NSSize) cellImageSize
1331 {
1332 return NSMakeSize(imageSize.width+xImageShift+spaceImageText,imageSize.height);
1333 }
1334
1335 -(NSSize) cellSize
1336 {
1337 NSSize cellSize([super cellSize]);
1338
1339
1340 if (imageSize.height > cellSize.height)
1341 cellSize.height = imageSize.height;
1342 cellSize.width += imageSize.width+xImageShift+spaceImageText;
1343
1344 return cellSize;
1345 }
1346
1347 -(NSSize) cellTextSize
1348 {
1349 return [super cellSize];
1350 }
1351
1352 //
1353 // implementations
1354 //
1355 -(void) determineCellParts:(NSRect)cellFrame imagePart:(NSRect*)imageFrame textPart:(NSRect*)textFrame
1356 {
1357 switch (cellAlignment)
1358 {
1359 case NSCenterTextAlignment:
1360 {
1361 CGFloat const cellSpace = cellFrame.size.width-[self cellSize].width;
1362
1363 // if the cell's frame is smaller than its contents (at least
1364 // in x-direction) make sure that the image is visible:
1365 if (cellSpace <= 0)
1366 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1367 else // otherwise center the image and text in the cell's frame
1368 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText+0.5*cellSpace,NSMinXEdge);
1369 }
1370 break;
1371 case NSJustifiedTextAlignment:
1372 case NSLeftTextAlignment:
1373 case NSNaturalTextAlignment: // how to determine the natural writing direction? TODO
1374 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1375 break;
1376 case NSRightTextAlignment:
1377 {
1378 CGFloat const cellSpace = cellFrame.size.width-[self cellSize].width;
1379
1380 // if the cell's frame is smaller than its contents (at least
1381 // in x-direction) make sure that the image is visible:
1382 if (cellSpace <= 0)
1383 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1384 else // otherwise right align the image and text in the cell's frame
1385 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText+cellSpace,NSMinXEdge);
1386 }
1387 break;
1388 default:
1389 *imageFrame = NSZeroRect;
1390 *textFrame = NSZeroRect;
1391 wxFAIL_MSG("Unhandled alignment type.");
1392 }
1393 }
1394
1395 -(void) drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
1396 {
1397 NSRect textFrame, imageFrame;
1398
1399
1400 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1401 // draw the image part by ourselves;
1402 // check if the cell has to draw its own background (checking is done by
1403 // the parameter of the textfield's cell):
1404 if ([self drawsBackground])
1405 {
1406 [[self backgroundColor] set];
1407 NSRectFill(imageFrame);
1408 }
1409 if (image != nil)
1410 {
1411 // the image is slightly shifted (xImageShift) and has a fixed size
1412 // but the image's frame might be larger and starts currently on the
1413 // left side of the cell's frame; therefore, the origin and the
1414 // image's frame size have to be adjusted:
1415 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1416 {
1417 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1418 imageFrame.size.width = imageSize.width;
1419 }
1420 else
1421 {
1422 imageFrame.origin.x += xImageShift;
1423 imageFrame.size.width -= xImageShift+spaceImageText;
1424 }
1425 // ...and the image has to be centered in the y-direction:
1426 if (imageFrame.size.height > imageSize.height)
1427 imageFrame.size.height = imageSize.height;
1428 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1429
1430 // according to the documentation the coordinate system should be
1431 // flipped for NSTableViews (y-coordinate goes from top to bottom); to
1432 // draw an image correctly the coordinate system has to be transformed
1433 // to a bottom-top coordinate system, otherwise the image's
1434 // content is flipped:
1435 NSAffineTransform* coordinateTransform([NSAffineTransform transform]);
1436
1437 if ([controlView isFlipped])
1438 {
1439 [coordinateTransform scaleXBy: 1.0 yBy:-1.0]; // first the coordinate system is brought back to bottom-top orientation
1440 [coordinateTransform translateXBy:0.0 yBy:(-2.0)*imageFrame.origin.y-imageFrame.size.height]; // the coordinate system has to be moved to compensate for the
1441 [coordinateTransform concat]; // other orientation and the position of the image's frame
1442 }
1443 [image drawInRect:imageFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0]; // suggested method to draw the image
1444 // instead of compositeToPoint:operation:
1445 // take back previous transformation (if the view is not flipped the
1446 // coordinate transformation matrix contains the identity matrix and
1447 // the next two operations do not change the content's transformation
1448 // matrix):
1449 [coordinateTransform invert];
1450 [coordinateTransform concat];
1451 }
1452 // let the textfield cell draw the text part:
1453 if (textFrame.size.width > [self cellTextSize].width)
1454 {
1455 // for unknown reasons the alignment of the text cell is ignored;
1456 // therefore change the size so that alignment does not influence the
1457 // visualization anymore
1458 textFrame.size.width = [self cellTextSize].width;
1459 }
1460 [super drawWithFrame:textFrame inView:controlView];
1461 }
1462
1463 -(void) editWithFrame:(NSRect)aRect inView:(NSView*)controlView editor:(NSText*)textObj delegate:(id)anObject event:(NSEvent*)theEvent
1464 {
1465 NSRect textFrame, imageFrame;
1466
1467
1468 [self determineCellParts:aRect imagePart:&imageFrame textPart:&textFrame];
1469 [super editWithFrame:textFrame inView:controlView editor:textObj delegate:anObject event:theEvent];
1470 }
1471
1472 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1473 -(NSUInteger) hitTestForEvent:(NSEvent*)event inRect:(NSRect)cellFrame ofView:(NSView*)controlView
1474 {
1475 NSPoint point = [controlView convertPoint:[event locationInWindow] fromView:nil];
1476
1477 NSRect imageFrame, textFrame;
1478
1479
1480 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1481 if (image != nil)
1482 {
1483 // the image is shifted...
1484 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1485 {
1486 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1487 imageFrame.size.width = imageSize.width;
1488 }
1489 else
1490 {
1491 imageFrame.origin.x += xImageShift;
1492 imageFrame.size.width -= xImageShift+spaceImageText;
1493 }
1494 // ...and centered:
1495 if (imageFrame.size.height > imageSize.height)
1496 imageFrame.size.height = imageSize.height;
1497 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1498 // If the point is in the image rect, then it is a content hit (see
1499 // documentation for hitTestForEvent:inRect:ofView):
1500 if (NSMouseInRect(point, imageFrame, [controlView isFlipped]))
1501 return NSCellHitContentArea;
1502 }
1503 // if the image was not hit let's try the text part:
1504 if (textFrame.size.width > [self cellTextSize].width)
1505 {
1506 // for unknown reasons the alignment of the text cell is ignored;
1507 // therefore change the size so that alignment does not influence the
1508 // visualization anymore
1509 textFrame.size.width = [self cellTextSize].width;
1510 }
1511
1512 return [super hitTestForEvent:event inRect:textFrame ofView:controlView];
1513 }
1514 #endif
1515
1516 -(NSRect) imageRectForBounds:(NSRect)cellFrame
1517 {
1518 NSRect textFrame, imageFrame;
1519
1520
1521 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1522 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1523 {
1524 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1525 imageFrame.size.width = imageSize.width;
1526 }
1527 else
1528 {
1529 imageFrame.origin.x += xImageShift;
1530 imageFrame.size.width -= xImageShift+spaceImageText;
1531 }
1532 // ...and centered:
1533 if (imageFrame.size.height > imageSize.height)
1534 imageFrame.size.height = imageSize.height;
1535 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1536
1537 return imageFrame;
1538 }
1539
1540 -(void) selectWithFrame:(NSRect)aRect inView:(NSView*)controlView editor:(NSText*)textObj delegate:(id)anObject start:(NSInteger)selStart length:(NSInteger)selLength
1541 {
1542 NSRect textFrame, imageFrame;
1543
1544
1545 [self determineCellParts:aRect imagePart:&imageFrame textPart:&textFrame];
1546 [super selectWithFrame:textFrame inView:controlView editor:textObj delegate:anObject start:selStart length:selLength];
1547 }
1548
1549 -(NSRect) titleRectForBounds:(NSRect)cellFrame
1550 {
1551 NSRect textFrame, imageFrame;
1552
1553
1554 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1555 return textFrame;
1556 }
1557
1558 @end
1559
1560 // ============================================================================
1561 // wxCocoaOutlineView
1562 // ============================================================================
1563 @implementation wxCocoaOutlineView
1564
1565 //
1566 // initializers / destructor
1567 //
1568 -(id) init
1569 {
1570 self = [super init];
1571 if (self != nil)
1572 {
1573 currentlyEditedColumn =
1574 currentlyEditedRow = -1;
1575
1576 [self registerForDraggedTypes:[NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]];
1577 [self setDelegate:self];
1578 [self setDoubleAction:@selector(actionDoubleClick:)];
1579 [self setDraggingSourceOperationMask:NSDragOperationEvery forLocal:NO];
1580 [self setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
1581 [self setTarget:self];
1582 }
1583 return self;
1584 }
1585
1586 //
1587 // access to wxWidget's implementation
1588 //
1589 -(wxCocoaDataViewControl*) implementation
1590 {
1591 return implementation;
1592 }
1593
1594 -(void) setImplementation:(wxCocoaDataViewControl*) newImplementation
1595 {
1596 implementation = newImplementation;
1597 }
1598
1599 //
1600 // actions
1601 //
1602 -(void) actionDoubleClick:(id)sender
1603 {
1604 wxUnusedVar(sender);
1605
1606 // actually the documentation (NSTableView 2007-10-31) for doubleAction:
1607 // and setDoubleAction: seems to be wrong as this action message is always
1608 // sent whether the cell is editable or not
1609 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1610
1611 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_ACTIVATED,dvc->GetId());
1612
1613
1614 event.SetEventObject(dvc);
1615 event.SetItem(wxDataViewItemFromItem([self itemAtRow:[self clickedRow]]));
1616 dvc->GetEventHandler()->ProcessEvent(event);
1617 }
1618
1619
1620 //
1621 // contextual menus
1622 //
1623 -(NSMenu*) menuForEvent:(NSEvent*)theEvent
1624 {
1625 wxUnusedVar(theEvent);
1626
1627 // this method does not do any special menu event handling but only sends
1628 // an event message; therefore, the user has full control if a context
1629 // menu should be shown or not
1630 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1631
1632 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_CONTEXT_MENU,dvc->GetId());
1633
1634 wxDataViewItemArray selectedItems;
1635
1636
1637 event.SetEventObject(dvc);
1638 event.SetModel(dvc->GetModel());
1639 // get the item information;
1640 // theoretically more than one ID can be returned but the event can only
1641 // handle one item, therefore only the first item of the array is
1642 // returned:
1643 if (dvc->GetSelections(selectedItems) > 0)
1644 event.SetItem(selectedItems[0]);
1645 dvc->GetEventHandler()->ProcessEvent(event);
1646 // nothing is done:
1647 return nil;
1648 }
1649
1650 //
1651 // delegate methods
1652 //
1653 -(void) outlineView:(NSOutlineView*)outlineView mouseDownInHeaderOfTableColumn:(NSTableColumn*)tableColumn
1654 {
1655 wxDataViewColumn* const
1656 col([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
1657
1658 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1659
1660 wxDataViewEvent
1661 event(wxEVT_COMMAND_DATAVIEW_COLUMN_HEADER_CLICK,dvc->GetId());
1662
1663
1664 // first, send an event that the user clicked into a column's header:
1665 event.SetEventObject(dvc);
1666 event.SetColumn(dvc->GetColumnPosition(col));
1667 event.SetDataViewColumn(col);
1668 dvc->HandleWindowEvent(event);
1669
1670 // now, check if the click may have had an influence on sorting, too;
1671 // the sorting setup has to be done only if the clicked table column is
1672 // sortable and has not been used for sorting before the click; if the
1673 // column is already responsible for sorting the native control changes
1674 // the sorting direction automatically and informs the data source via
1675 // outlineView:sortDescriptorsDidChange:
1676 if (col->IsSortable() && ([tableColumn sortDescriptorPrototype] == nil))
1677 {
1678 // remove the sort order from the previously sorted column table (it
1679 // can also be that no sorted column table exists):
1680 UInt32 const noOfColumns = [outlineView numberOfColumns];
1681
1682 for (UInt32 i=0; i<noOfColumns; ++i)
1683 [[[outlineView tableColumns] objectAtIndex:i] setSortDescriptorPrototype:nil];
1684 // make column table sortable:
1685 NSArray* sortDescriptors;
1686 NSSortDescriptor* sortDescriptor;
1687
1688 sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[NSString stringWithFormat:@"%d",[outlineView columnWithIdentifier:[tableColumn identifier]]]
1689 ascending:YES];
1690 sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
1691 [tableColumn setSortDescriptorPrototype:sortDescriptor];
1692 [outlineView setSortDescriptors:sortDescriptors];
1693 [sortDescriptor release];
1694 }
1695 }
1696
1697 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldCollapseItem:(id)item
1698 {
1699 wxUnusedVar(outlineView);
1700
1701 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1702
1703 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSING,dvc->GetId());
1704
1705
1706 event.SetEventObject(dvc);
1707 event.SetItem (wxDataViewItemFromItem(item));
1708 event.SetModel (dvc->GetModel());
1709 // finally send the equivalent wxWidget event:
1710 dvc->GetEventHandler()->ProcessEvent(event);
1711 // opening the container is allowed if not vetoed:
1712 return event.IsAllowed();
1713 }
1714
1715 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldExpandItem:(id)item
1716 {
1717 wxUnusedVar(outlineView);
1718
1719 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1720
1721 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDING,dvc->GetId());
1722
1723
1724 event.SetEventObject(dvc);
1725 event.SetItem (wxDataViewItemFromItem(item));
1726 event.SetModel (dvc->GetModel());
1727 // finally send the equivalent wxWidget event:
1728 dvc->GetEventHandler()->ProcessEvent(event);
1729 // opening the container is allowed if not vetoed:
1730 return event.IsAllowed();
1731 }
1732
1733 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldSelectTableColumn:(NSTableColumn*)tableColumn
1734 {
1735 wxUnusedVar(tableColumn);
1736 wxUnusedVar(outlineView);
1737
1738 return NO;
1739 }
1740
1741 -(void) outlineView:(wxCocoaOutlineView*)outlineView
1742 willDisplayCell:(id)cell
1743 forTableColumn:(NSTableColumn*)tableColumn
1744 item:(id)item
1745 {
1746 wxUnusedVar(outlineView);
1747
1748 wxDataViewCtrl * const dvc = implementation->GetDataViewCtrl();
1749 wxDataViewModel * const model = dvc->GetModel();
1750
1751 wxDataViewColumn* const
1752 dvCol([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
1753 const unsigned colIdx = dvCol->GetModelColumn();
1754
1755 wxDataViewItem dvItem(wxDataViewItemFromItem(item));
1756
1757 if ( !model->HasValue(dvItem, colIdx) )
1758 return;
1759
1760 wxDataViewRenderer * const renderer = dvCol->GetRenderer();
1761 wxDataViewRendererNativeData * const data = renderer->GetNativeData();
1762
1763 // let the renderer know about what it's going to render next
1764 data->SetColumnPtr(tableColumn);
1765 data->SetItem(item);
1766 data->SetItemCell(cell);
1767
1768 // use the attributes: notice that we need to do this whether we have them
1769 // or not as even if this cell doesn't have any attributes, the previous
1770 // one might have had some and then we need to reset them back to default
1771 wxDataViewItemAttr attr;
1772 model->GetAttr(dvItem, colIdx, attr);
1773 renderer->OSXApplyAttr(attr);
1774
1775 // set the state (enabled/disabled) of the item
1776 renderer->OSXApplyEnabled(model->IsEnabled(dvItem, colIdx));
1777
1778 // and finally do draw it
1779 renderer->MacRender();
1780 }
1781
1782 //
1783 // notifications
1784 //
1785 -(void) outlineViewColumnDidMove:(NSNotification*)notification
1786 {
1787 int const newColumnPosition = [[[notification userInfo] objectForKey:@"NSNewColumn"] intValue];
1788
1789 NSTableColumn*
1790 tableColumn = [[self tableColumns] objectAtIndex:newColumnPosition];
1791 wxDataViewColumn* const
1792 col([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
1793
1794 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1795
1796 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_COLUMN_REORDERED,dvc->GetId());
1797
1798
1799 event.SetEventObject(dvc);
1800 event.SetColumn(dvc->GetColumnPosition(col));
1801 event.SetDataViewColumn(col);
1802 dvc->GetEventHandler()->ProcessEvent(event);
1803 }
1804
1805 -(void) outlineViewItemDidCollapse:(NSNotification*)notification
1806 {
1807 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1808
1809 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_COLLAPSED,dvc->GetId());
1810
1811
1812 event.SetEventObject(dvc);
1813 event.SetItem(wxDataViewItemFromItem(
1814 [[notification userInfo] objectForKey:@"NSObject"]));
1815 dvc->GetEventHandler()->ProcessEvent(event);
1816 }
1817
1818 -(void) outlineViewItemDidExpand:(NSNotification*)notification
1819 {
1820 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1821
1822 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_ITEM_EXPANDED,dvc->GetId());
1823
1824
1825 event.SetEventObject(dvc);
1826 event.SetItem(wxDataViewItemFromItem(
1827 [[notification userInfo] objectForKey:@"NSObject"]));
1828 dvc->GetEventHandler()->ProcessEvent(event);
1829 }
1830
1831 -(void) outlineViewSelectionDidChange:(NSNotification*)notification
1832 {
1833 wxUnusedVar(notification);
1834
1835 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1836
1837 wxDataViewEvent event(wxEVT_COMMAND_DATAVIEW_SELECTION_CHANGED,dvc->GetId());
1838
1839 event.SetEventObject(dvc);
1840 event.SetModel(dvc->GetModel());
1841 event.SetItem(dvc->GetSelection());
1842 dvc->GetEventHandler()->ProcessEvent(event);
1843 }
1844
1845 -(void) textDidBeginEditing:(NSNotification*)notification
1846 {
1847 // this notification is only sent if the user started modifying the cell
1848 // (not when the user clicked into the cell and the cell's editor is
1849 // called!)
1850
1851 // call method of superclass (otherwise editing does not work correctly -
1852 // the outline data source class is not informed about a change of data):
1853 [super textDidBeginEditing:notification];
1854
1855 // remember the column being edited, it will be used in textDidEndEditing:
1856 currentlyEditedColumn = [self editedColumn];
1857 currentlyEditedRow = [self editedRow];
1858
1859 NSTableColumn*
1860 tableColumn = [[self tableColumns] objectAtIndex:currentlyEditedColumn];
1861 wxDataViewColumn* const
1862 col([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
1863
1864 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1865
1866
1867 // stop editing of a custom item first (if necessary)
1868 dvc->FinishCustomItemEditing();
1869
1870 // now, send the event:
1871 wxDataViewEvent
1872 event(wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED,dvc->GetId());
1873
1874 event.SetEventObject(dvc);
1875 event.SetItem(
1876 wxDataViewItemFromItem([self itemAtRow:currentlyEditedRow]));
1877 event.SetColumn(dvc->GetColumnPosition(col));
1878 event.SetDataViewColumn(col);
1879 dvc->GetEventHandler()->ProcessEvent(event);
1880 }
1881
1882 -(void) textDidEndEditing:(NSNotification*)notification
1883 {
1884 // call method of superclass (otherwise editing does not work correctly -
1885 // the outline data source class is not informed about a change of data):
1886 [super textDidEndEditing:notification];
1887
1888 // under OSX an event indicating the end of an editing session can be sent
1889 // even if no event indicating a start of an editing session has been sent
1890 // (see Documentation for NSControl controlTextDidEndEditing:); this is
1891 // not expected by a user of the wxWidgets library and therefore an
1892 // wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_DONE event is only sent if a
1893 // corresponding wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED has been sent
1894 // before; to check if a wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_STARTED has
1895 // been sent the last edited column/row are valid:
1896 if ( currentlyEditedColumn != -1 && currentlyEditedRow != -1 )
1897 {
1898 NSTableColumn*
1899 tableColumn = [[self tableColumns] objectAtIndex:currentlyEditedColumn];
1900 wxDataViewColumn* const
1901 col([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
1902
1903 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1904
1905 // send event to wxWidgets:
1906 wxDataViewEvent
1907 event(wxEVT_COMMAND_DATAVIEW_ITEM_EDITING_DONE,dvc->GetId());
1908
1909 event.SetEventObject(dvc);
1910 event.SetItem(
1911 wxDataViewItemFromItem([self itemAtRow:currentlyEditedRow]));
1912 event.SetColumn(dvc->GetColumnPosition(col));
1913 event.SetDataViewColumn(col);
1914 dvc->GetEventHandler()->ProcessEvent(event);
1915
1916
1917 // we're not editing any more
1918 currentlyEditedColumn =
1919 currentlyEditedRow = -1;
1920 }
1921 }
1922
1923 @end
1924
1925 // ============================================================================
1926 // wxCocoaDataViewControl
1927 // ============================================================================
1928
1929 wxCocoaDataViewControl::wxCocoaDataViewControl(wxWindow* peer,
1930 const wxPoint& pos,
1931 const wxSize& size,
1932 long style)
1933 : wxWidgetCocoaImpl
1934 (
1935 peer,
1936 [[NSScrollView alloc] initWithFrame:wxOSXGetFrameForControl(peer,pos,size)]
1937 ),
1938 m_DataSource(NULL),
1939 m_OutlineView([[wxCocoaOutlineView alloc] init])
1940 {
1941 // initialize scrollview (the outline view is part of a scrollview):
1942 NSScrollView* scrollview = (NSScrollView*) GetWXWidget();
1943
1944 [scrollview setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1945 [scrollview setBorderType:NSNoBorder];
1946 [scrollview setHasVerticalScroller:YES];
1947 [scrollview setHasHorizontalScroller:YES];
1948 [scrollview setAutohidesScrollers:YES];
1949 [scrollview setDocumentView:m_OutlineView];
1950
1951 // initialize the native control itself too
1952 InitOutlineView(style);
1953 }
1954
1955 void wxCocoaDataViewControl::InitOutlineView(long style)
1956 {
1957 [m_OutlineView setImplementation:this];
1958 [m_OutlineView setColumnAutoresizingStyle:NSTableViewSequentialColumnAutoresizingStyle];
1959 [m_OutlineView setIndentationPerLevel:GetDataViewCtrl()->GetIndent()];
1960 NSUInteger maskGridStyle(NSTableViewGridNone);
1961 if (style & wxDV_HORIZ_RULES)
1962 maskGridStyle |= NSTableViewSolidHorizontalGridLineMask;
1963 if (style & wxDV_VERT_RULES)
1964 maskGridStyle |= NSTableViewSolidVerticalGridLineMask;
1965 [m_OutlineView setGridStyleMask:maskGridStyle];
1966 [m_OutlineView setAllowsMultipleSelection: (style & wxDV_MULTIPLE) != 0];
1967 [m_OutlineView setUsesAlternatingRowBackgroundColors:(style & wxDV_ROW_LINES) != 0];
1968
1969 if ( style & wxDV_NO_HEADER )
1970 [m_OutlineView setHeaderView:nil];
1971 }
1972
1973 wxCocoaDataViewControl::~wxCocoaDataViewControl()
1974 {
1975 [m_DataSource release];
1976 [m_OutlineView release];
1977 }
1978
1979 //
1980 // column related methods (inherited from wxDataViewWidgetImpl)
1981 //
1982 bool wxCocoaDataViewControl::ClearColumns()
1983 {
1984 // as there is a bug in NSOutlineView version (OSX 10.5.6 #6555162) the
1985 // columns cannot be deleted if there is an outline column in the view;
1986 // therefore, the whole view is deleted and newly constructed:
1987 [m_OutlineView release];
1988 m_OutlineView = [[wxCocoaOutlineView alloc] init];
1989 [((NSScrollView*) GetWXWidget()) setDocumentView:m_OutlineView];
1990 [m_OutlineView setDataSource:m_DataSource];
1991
1992 InitOutlineView(GetDataViewCtrl()->GetWindowStyle());
1993
1994 return true;
1995 }
1996
1997 bool wxCocoaDataViewControl::DeleteColumn(wxDataViewColumn* columnPtr)
1998 {
1999 if ([m_OutlineView outlineTableColumn] == columnPtr->GetNativeData()->GetNativeColumnPtr())
2000 [m_OutlineView setOutlineTableColumn:nil]; // due to a bug this does not work
2001 [m_OutlineView removeTableColumn:columnPtr->GetNativeData()->GetNativeColumnPtr()]; // due to a confirmed bug #6555162 the deletion does not work for
2002 // outline table columns (... and there is no workaround)
2003 return (([m_OutlineView columnWithIdentifier:[wxDVCNSTableColumn identifierForColumnPointer:columnPtr]]) == -1);
2004 }
2005
2006 void wxCocoaDataViewControl::DoSetExpanderColumn(const wxDataViewColumn *columnPtr)
2007 {
2008 [m_OutlineView setOutlineTableColumn:columnPtr->GetNativeData()->GetNativeColumnPtr()];
2009 }
2010
2011 wxDataViewColumn* wxCocoaDataViewControl::GetColumn(unsigned int pos) const
2012 {
2013 NSTableColumn* tableColumn = [[m_OutlineView tableColumns] objectAtIndex:pos];
2014 return [static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer];
2015 }
2016
2017 int wxCocoaDataViewControl::GetColumnPosition(const wxDataViewColumn *columnPtr) const
2018 {
2019 return [m_OutlineView columnWithIdentifier:[wxDVCNSTableColumn identifierForColumnPointer:columnPtr]];
2020 }
2021
2022 bool wxCocoaDataViewControl::InsertColumn(unsigned int pos, wxDataViewColumn* columnPtr)
2023 {
2024 // create column and set the native data of the dataview column:
2025 NSTableColumn *nativeColumn = ::CreateNativeColumn(columnPtr);
2026 columnPtr->GetNativeData()->SetNativeColumnPtr(nativeColumn);
2027 // as the native control does not allow the insertion of a column at a
2028 // specified position the column is first appended and - if necessary -
2029 // moved to its final position:
2030 [m_OutlineView addTableColumn:nativeColumn];
2031 if (pos != static_cast<unsigned int>([m_OutlineView numberOfColumns]-1))
2032 [m_OutlineView moveColumn:[m_OutlineView numberOfColumns]-1 toColumn:pos];
2033
2034 // set columns width now that it can be computed even for autosized columns:
2035 columnPtr->SetWidth(columnPtr->GetWidthVariable());
2036
2037 // done:
2038 return true;
2039 }
2040
2041 void wxCocoaDataViewControl::FitColumnWidthToContent(unsigned int pos)
2042 {
2043 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
2044 const int count = GetCount();
2045 NSTableColumn *column = GetColumn(pos)->GetNativeData()->GetNativeColumnPtr();
2046
2047 class MaxWidthCalculator
2048 {
2049 public:
2050 MaxWidthCalculator(wxCocoaOutlineView *view,
2051 NSTableColumn *column, unsigned columnIndex)
2052 : m_width(0),
2053 m_view(view),
2054 m_column(columnIndex),
2055 m_indent(0)
2056 {
2057 // account for indentation in the column with expander
2058 if ( column == [m_view outlineTableColumn] )
2059 m_indent = [m_view indentationPerLevel];
2060 }
2061
2062 void UpdateWithWidth(int width)
2063 {
2064 m_width = wxMax(m_width, width);
2065 }
2066
2067 void UpdateWithRow(int row)
2068 {
2069 NSCell *cell = [m_view preparedCellAtColumn:m_column row:row];
2070 unsigned cellWidth = [cell cellSize].width + 1/*round the float up*/;
2071
2072 if ( m_indent )
2073 cellWidth += m_indent * ([m_view levelForRow:row] + 1);
2074
2075 m_width = wxMax(m_width, cellWidth);
2076 }
2077
2078 int GetMaxWidth() const { return m_width; }
2079
2080 private:
2081 int m_width;
2082 wxCocoaOutlineView *m_view;
2083 unsigned m_column;
2084 int m_indent;
2085 };
2086
2087 MaxWidthCalculator calculator(m_OutlineView, column, pos);
2088
2089 if ( [column headerCell] )
2090 {
2091 calculator.UpdateWithWidth([[column headerCell] cellSize].width + 1/*round the float up*/);
2092 }
2093
2094 // The code below deserves some explanation. For very large controls, we
2095 // simply can't afford to calculate sizes for all items, it takes too
2096 // long. So the best we can do is to check the first and the last N/2
2097 // items in the control for some sufficiently large N and calculate best
2098 // sizes from that. That can result in the calculated best width being too
2099 // small for some outliers, but it's better to get slightly imperfect
2100 // result than to wait several seconds after every update. To avoid highly
2101 // visible miscalculations, we also include all currently visible items
2102 // no matter what. Finally, the value of N is determined dynamically by
2103 // measuring how much time we spent on the determining item widths so far.
2104
2105 #if wxUSE_STOPWATCH
2106 int top_part_end = count;
2107 static const long CALC_TIMEOUT = 20/*ms*/;
2108 // don't call wxStopWatch::Time() too often
2109 static const unsigned CALC_CHECK_FREQ = 100;
2110 wxStopWatch timer;
2111 #else
2112 // use some hard-coded limit, that's the best we can do without timer
2113 int top_part_end = wxMin(500, count);
2114 #endif // wxUSE_STOPWATCH/!wxUSE_STOPWATCH
2115
2116 int row = 0;
2117
2118 for ( row = 0; row < top_part_end; row++ )
2119 {
2120 #if wxUSE_STOPWATCH
2121 if ( row % CALC_CHECK_FREQ == CALC_CHECK_FREQ-1 &&
2122 timer.Time() > CALC_TIMEOUT )
2123 break;
2124 #endif // wxUSE_STOPWATCH
2125 calculator.UpdateWithRow(row);
2126 }
2127
2128 // row is the first unmeasured item now; that's our value of N/2
2129
2130 if ( row < count )
2131 {
2132 top_part_end = row;
2133
2134 // add bottom N/2 items now:
2135 const int bottom_part_start = wxMax(row, count - row);
2136 for ( row = bottom_part_start; row < count; row++ )
2137 calculator.UpdateWithRow(row);
2138
2139 // finally, include currently visible items in the calculation:
2140 const NSRange visible = [m_OutlineView rowsInRect:[m_OutlineView visibleRect]];
2141 const int first_visible = wxMax(visible.location, top_part_end);
2142 const int last_visible = wxMin(first_visible + visible.length, bottom_part_start);
2143
2144 for ( row = first_visible; row < last_visible; row++ )
2145 calculator.UpdateWithRow(row);
2146
2147 wxLogTrace("dataview",
2148 "determined best size from %d top, %d bottom plus %d more visible items out of %d total",
2149 top_part_end,
2150 count - bottom_part_start,
2151 wxMax(0, last_visible - first_visible),
2152 count);
2153 }
2154
2155 [column setWidth:calculator.GetMaxWidth()];
2156 #endif // MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
2157 }
2158
2159 //
2160 // item related methods (inherited from wxDataViewWidgetImpl)
2161 //
2162 bool wxCocoaDataViewControl::Add(const wxDataViewItem& parent, const wxDataViewItem& WXUNUSED(item))
2163 {
2164 if (parent.IsOk())
2165 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2166 else
2167 [m_OutlineView reloadData];
2168 return true;
2169 }
2170
2171 bool wxCocoaDataViewControl::Add(const wxDataViewItem& parent, const wxDataViewItemArray& WXUNUSED(items))
2172 {
2173 if (parent.IsOk())
2174 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2175 else
2176 [m_OutlineView reloadData];
2177 return true;
2178 }
2179
2180 void wxCocoaDataViewControl::Collapse(const wxDataViewItem& item)
2181 {
2182 [m_OutlineView collapseItem:[m_DataSource getDataViewItemFromBuffer:item]];
2183 }
2184
2185 void wxCocoaDataViewControl::EnsureVisible(const wxDataViewItem& item, const wxDataViewColumn *columnPtr)
2186 {
2187 if (item.IsOk())
2188 {
2189 [m_OutlineView scrollRowToVisible:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2190 if (columnPtr)
2191 [m_OutlineView scrollColumnToVisible:GetColumnPosition(columnPtr)];
2192 }
2193 }
2194
2195 void wxCocoaDataViewControl::Expand(const wxDataViewItem& item)
2196 {
2197 [m_OutlineView expandItem:[m_DataSource getDataViewItemFromBuffer:item]];
2198 }
2199
2200 unsigned int wxCocoaDataViewControl::GetCount() const
2201 {
2202 return [m_OutlineView numberOfRows];
2203 }
2204
2205 wxRect wxCocoaDataViewControl::GetRectangle(const wxDataViewItem& item, const wxDataViewColumn *columnPtr)
2206 {
2207 return wxFromNSRect([m_osxView superview],[m_OutlineView frameOfCellAtColumn:GetColumnPosition(columnPtr)
2208 row:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]]);
2209 }
2210
2211 bool wxCocoaDataViewControl::IsExpanded(const wxDataViewItem& item) const
2212 {
2213 return [m_OutlineView isItemExpanded:[m_DataSource getDataViewItemFromBuffer:item]];
2214 }
2215
2216 bool wxCocoaDataViewControl::Reload()
2217 {
2218 [m_DataSource clearBuffers];
2219 [m_OutlineView reloadData];
2220 [m_OutlineView scrollColumnToVisible:0];
2221 [m_OutlineView scrollRowToVisible:0];
2222 return true;
2223 }
2224
2225 bool wxCocoaDataViewControl::Remove(const wxDataViewItem& parent, const wxDataViewItem& WXUNUSED(item))
2226 {
2227 if (parent.IsOk())
2228 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2229 else
2230 [m_OutlineView reloadData];
2231 return true;
2232 }
2233
2234 bool wxCocoaDataViewControl::Remove(const wxDataViewItem& parent, const wxDataViewItemArray& WXUNUSED(item))
2235 {
2236 if (parent.IsOk())
2237 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2238 else
2239 [m_OutlineView reloadData];
2240 return true;
2241 }
2242
2243 bool wxCocoaDataViewControl::Update(const wxDataViewColumn *columnPtr)
2244 {
2245 wxUnusedVar(columnPtr);
2246
2247 return false;
2248 }
2249
2250 bool wxCocoaDataViewControl::Update(const wxDataViewItem& WXUNUSED(parent), const wxDataViewItem& item)
2251 {
2252 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:item]];
2253 return true;
2254 }
2255
2256 bool wxCocoaDataViewControl::Update(const wxDataViewItem& WXUNUSED(parent), const wxDataViewItemArray& items)
2257 {
2258 for (size_t i=0; i<items.GetCount(); ++i)
2259 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:items[i]]];
2260 return true;
2261 }
2262
2263 //
2264 // model related methods
2265 //
2266 bool wxCocoaDataViewControl::AssociateModel(wxDataViewModel* model)
2267 {
2268 [m_DataSource release];
2269 if (model)
2270 {
2271 m_DataSource = [[wxCocoaOutlineDataSource alloc] init];
2272 [m_DataSource setImplementation:this];
2273 [m_DataSource setModel:model];
2274 }
2275 else
2276 m_DataSource = NULL;
2277 [m_OutlineView setDataSource:m_DataSource]; // if there is a data source the data is immediately going to be requested
2278 return true;
2279 }
2280
2281 //
2282 // selection related methods (inherited from wxDataViewWidgetImpl)
2283 //
2284
2285 wxDataViewItem wxCocoaDataViewControl::GetCurrentItem() const
2286 {
2287 return wxDataViewItem([[m_OutlineView itemAtRow:[m_OutlineView selectedRow]] pointer]);
2288 }
2289
2290 wxDataViewColumn *wxCocoaDataViewControl::GetCurrentColumn() const
2291 {
2292 int col = [m_OutlineView selectedColumn];
2293 if ( col == -1 )
2294 return NULL;
2295 return GetColumn(col);
2296 }
2297
2298 void wxCocoaDataViewControl::SetCurrentItem(const wxDataViewItem& item)
2299 {
2300 // We can't have unselected current item in a NSTableView, as the
2301 // documentation of its deselectRow method explains, the control will
2302 // automatically change the current item to the closest still selected item
2303 // if the current item is deselected. So we have no choice but to select
2304 // the item in the same time as making it current.
2305 Select(item);
2306 }
2307
2308 int wxCocoaDataViewControl::GetSelectedItemsCount() const
2309 {
2310 return [m_OutlineView numberOfSelectedRows];
2311 }
2312
2313 int wxCocoaDataViewControl::GetSelections(wxDataViewItemArray& sel) const
2314 {
2315 NSIndexSet* selectedRowIndexes([m_OutlineView selectedRowIndexes]);
2316
2317 NSUInteger indexRow;
2318
2319
2320 sel.Empty();
2321 sel.Alloc([selectedRowIndexes count]);
2322 indexRow = [selectedRowIndexes firstIndex];
2323 while (indexRow != NSNotFound)
2324 {
2325 sel.Add(wxDataViewItem([[m_OutlineView itemAtRow:indexRow] pointer]));
2326 indexRow = [selectedRowIndexes indexGreaterThanIndex:indexRow];
2327 }
2328 return sel.GetCount();
2329 }
2330
2331 bool wxCocoaDataViewControl::IsSelected(const wxDataViewItem& item) const
2332 {
2333 return [m_OutlineView isRowSelected:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2334 }
2335
2336 void wxCocoaDataViewControl::Select(const wxDataViewItem& item)
2337 {
2338 if (item.IsOk())
2339 [m_OutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]]
2340 byExtendingSelection:GetDataViewCtrl()->HasFlag(wxDV_MULTIPLE) ? YES : NO];
2341 }
2342
2343 void wxCocoaDataViewControl::SelectAll()
2344 {
2345 [m_OutlineView selectAll:m_OutlineView];
2346 }
2347
2348 void wxCocoaDataViewControl::Unselect(const wxDataViewItem& item)
2349 {
2350 if (item.IsOk())
2351 [m_OutlineView deselectRow:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2352 }
2353
2354 void wxCocoaDataViewControl::UnselectAll()
2355 {
2356 [m_OutlineView deselectAll:m_OutlineView];
2357 }
2358
2359 //
2360 // sorting related methods
2361 //
2362 wxDataViewColumn* wxCocoaDataViewControl::GetSortingColumn() const
2363 {
2364 NSArray* const columns = [m_OutlineView tableColumns];
2365
2366 UInt32 const noOfColumns = [columns count];
2367
2368
2369 for (UInt32 i=0; i<noOfColumns; ++i)
2370 if ([[columns objectAtIndex:i] sortDescriptorPrototype] != nil)
2371 return GetColumn(i);
2372 return NULL;
2373 }
2374
2375 void wxCocoaDataViewControl::Resort()
2376 {
2377 [m_DataSource clearChildren];
2378 [m_OutlineView reloadData];
2379 }
2380
2381 void wxCocoaDataViewControl::StartEditor( const wxDataViewItem & item, unsigned int column )
2382 {
2383 [m_OutlineView editColumn:column row:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]] withEvent:nil select:YES];
2384 }
2385
2386 //
2387 // other methods (inherited from wxDataViewWidgetImpl)
2388 //
2389 void wxCocoaDataViewControl::DoSetIndent(int indent)
2390 {
2391 [m_OutlineView setIndentationPerLevel:static_cast<CGFloat>(indent)];
2392 }
2393
2394 void wxCocoaDataViewControl::HitTest(const wxPoint& point, wxDataViewItem& item, wxDataViewColumn*& columnPtr) const
2395 {
2396 NSPoint const nativePoint = wxToNSPoint((NSScrollView*) GetWXWidget(),point);
2397
2398 int indexColumn;
2399 int indexRow;
2400
2401
2402 indexColumn = [m_OutlineView columnAtPoint:nativePoint];
2403 indexRow = [m_OutlineView rowAtPoint: nativePoint];
2404 if ((indexColumn >= 0) && (indexRow >= 0))
2405 {
2406 columnPtr = GetColumn(indexColumn);
2407 item = wxDataViewItem([[m_OutlineView itemAtRow:indexRow] pointer]);
2408 }
2409 else
2410 {
2411 columnPtr = NULL;
2412 item = wxDataViewItem();
2413 }
2414 }
2415
2416 void wxCocoaDataViewControl::SetRowHeight(const wxDataViewItem& WXUNUSED(item), unsigned int WXUNUSED(height))
2417 // Not supported by the native control
2418 {
2419 }
2420
2421 void wxCocoaDataViewControl::OnSize()
2422 {
2423 if ([m_OutlineView numberOfColumns] == 1)
2424 [m_OutlineView sizeLastColumnToFit];
2425 }
2426
2427 //
2428 // drag & drop helper methods
2429 //
2430 wxDataFormat wxCocoaDataViewControl::GetDnDDataFormat(wxDataObjectComposite* dataObjects)
2431 {
2432 wxDataFormat resultFormat;
2433 if ( !dataObjects )
2434 return resultFormat;
2435
2436 bool compatible(true);
2437
2438 size_t const noOfFormats = dataObjects->GetFormatCount();
2439 size_t indexFormat;
2440
2441 wxDataFormat* formats;
2442
2443 // get all formats and check afterwards if the formats are compatible; if
2444 // they are compatible the preferred format is returned otherwise
2445 // wxDF_INVALID is returned;
2446 // currently compatible types (ordered by priority are):
2447 // - wxDF_UNICODETEXT - wxDF_TEXT
2448 formats = new wxDataFormat[noOfFormats];
2449 dataObjects->GetAllFormats(formats);
2450 indexFormat = 0;
2451 while ((indexFormat < noOfFormats) && compatible)
2452 {
2453 switch (resultFormat.GetType())
2454 {
2455 case wxDF_INVALID:
2456 resultFormat.SetType(formats[indexFormat].GetType()); // first format (should only be reached if indexFormat == 0)
2457 break;
2458 case wxDF_TEXT:
2459 if (formats[indexFormat].GetType() == wxDF_UNICODETEXT)
2460 resultFormat.SetType(wxDF_UNICODETEXT);
2461 else // incompatible
2462 {
2463 resultFormat.SetType(wxDF_INVALID);
2464 compatible = false;
2465 }
2466 break;
2467 case wxDF_UNICODETEXT:
2468 if (formats[indexFormat].GetType() != wxDF_TEXT)
2469 {
2470 resultFormat.SetType(wxDF_INVALID);
2471 compatible = false;
2472 }
2473 break;
2474 default:
2475 resultFormat.SetType(wxDF_INVALID); // not (yet) supported format
2476 compatible = false;
2477 }
2478 ++indexFormat;
2479 }
2480
2481 delete[] formats;
2482
2483 return resultFormat;
2484 }
2485
2486 wxDataObjectComposite* wxCocoaDataViewControl::GetDnDDataObjects(NSData* dataObject) const
2487 {
2488 wxDataFormatId dataFormatID;
2489
2490
2491 [dataObject getBytes:&dataFormatID length:sizeof(wxDataFormatId)];
2492 switch (dataFormatID)
2493 {
2494 case wxDF_TEXT:
2495 case wxDF_UNICODETEXT:
2496 {
2497 wxTextDataObject* textDataObject(new wxTextDataObject());
2498
2499 if (textDataObject->SetData(wxDataFormat(dataFormatID),[dataObject length]-sizeof(wxDataFormatId),static_cast<char const*>([dataObject bytes])+sizeof(wxDataFormatId)))
2500 {
2501 wxDataObjectComposite* dataObjectComposite(new wxDataObjectComposite());
2502
2503 dataObjectComposite->Add(textDataObject);
2504 return dataObjectComposite;
2505 }
2506 else
2507 {
2508 delete textDataObject;
2509 return NULL;
2510 }
2511 }
2512 break;
2513 default:
2514 return NULL;
2515 }
2516 }
2517
2518 id wxCocoaDataViewControl::GetItemAtRow(int row) const
2519 {
2520 return [m_OutlineView itemAtRow:row];
2521 }
2522
2523 // ----------------------------------------------------------------------------
2524 // wxDataViewRendererNativeData
2525 // ----------------------------------------------------------------------------
2526
2527 void wxDataViewRendererNativeData::Init()
2528 {
2529 m_origFont = NULL;
2530 m_origTextColour = NULL;
2531 m_ellipsizeMode = wxELLIPSIZE_MIDDLE;
2532
2533 if ( m_ColumnCell )
2534 ApplyLineBreakMode(m_ColumnCell);
2535 }
2536
2537 void wxDataViewRendererNativeData::ApplyLineBreakMode(NSCell *cell)
2538 {
2539 NSLineBreakMode nsMode = NSLineBreakByWordWrapping;
2540 switch ( m_ellipsizeMode )
2541 {
2542 case wxELLIPSIZE_NONE:
2543 nsMode = NSLineBreakByClipping;
2544 break;
2545
2546 case wxELLIPSIZE_START:
2547 nsMode = NSLineBreakByTruncatingHead;
2548 break;
2549
2550 case wxELLIPSIZE_MIDDLE:
2551 nsMode = NSLineBreakByTruncatingMiddle;
2552 break;
2553
2554 case wxELLIPSIZE_END:
2555 nsMode = NSLineBreakByTruncatingTail;
2556 break;
2557 }
2558
2559 wxASSERT_MSG( nsMode != NSLineBreakByWordWrapping, "unknown wxEllipsizeMode" );
2560
2561 [cell setLineBreakMode: nsMode];
2562 }
2563
2564 // ---------------------------------------------------------
2565 // wxDataViewRenderer
2566 // ---------------------------------------------------------
2567
2568 wxDataViewRenderer::wxDataViewRenderer(const wxString& varianttype,
2569 wxDataViewCellMode mode,
2570 int align)
2571 : wxDataViewRendererBase(varianttype, mode, align),
2572 m_alignment(align),
2573 m_mode(mode),
2574 m_NativeDataPtr(NULL)
2575 {
2576 }
2577
2578 wxDataViewRenderer::~wxDataViewRenderer()
2579 {
2580 delete m_NativeDataPtr;
2581 }
2582
2583 void wxDataViewRenderer::SetAlignment(int align)
2584 {
2585 m_alignment = align;
2586 [GetNativeData()->GetColumnCell() setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2587 }
2588
2589 void wxDataViewRenderer::SetMode(wxDataViewCellMode mode)
2590 {
2591 m_mode = mode;
2592 if ( GetOwner() )
2593 [GetOwner()->GetNativeData()->GetNativeColumnPtr() setEditable:(mode == wxDATAVIEW_CELL_EDITABLE)];
2594 }
2595
2596 void wxDataViewRenderer::SetNativeData(wxDataViewRendererNativeData* newNativeDataPtr)
2597 {
2598 delete m_NativeDataPtr;
2599 m_NativeDataPtr = newNativeDataPtr;
2600 }
2601
2602 void wxDataViewRenderer::EnableEllipsize(wxEllipsizeMode mode)
2603 {
2604 // we need to store this value to apply it to the columns headerCell in
2605 // CreateNativeColumn()
2606 GetNativeData()->SetEllipsizeMode(mode);
2607
2608 // but we may already apply it to the column cell which will be used for
2609 // this column
2610 GetNativeData()->ApplyLineBreakMode(GetNativeData()->GetColumnCell());
2611 }
2612
2613 wxEllipsizeMode wxDataViewRenderer::GetEllipsizeMode() const
2614 {
2615 return GetNativeData()->GetEllipsizeMode();
2616 }
2617
2618 void
2619 wxDataViewRenderer::OSXOnCellChanged(NSObject *object,
2620 const wxDataViewItem& item,
2621 unsigned col)
2622 {
2623 // TODO: we probably should get rid of this code entirely and make this
2624 // function pure virtual, but currently we still have some native
2625 // renderers (wxDataViewChoiceRenderer) which don't override it and
2626 // there is also wxDataViewCustomRenderer for which it's not obvious
2627 // how it should be implemented so keep this "auto-deduction" of
2628 // variant type from NSObject for now
2629
2630 wxVariant value;
2631 if ( [object isKindOfClass:[NSString class]] )
2632 value = ObjectToString(object);
2633 else if ( [object isKindOfClass:[NSNumber class]] )
2634 value = ObjectToLong(object);
2635 else if ( [object isKindOfClass:[NSDate class]] )
2636 value = ObjectToDate(object);
2637 else
2638 {
2639 wxFAIL_MSG( wxString::Format
2640 (
2641 "unknown value type %s",
2642 wxCFStringRef::AsString([object className])
2643 ));
2644 return;
2645 }
2646
2647 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2648 model->ChangeValue(value, item, col);
2649 }
2650
2651 void wxDataViewRenderer::OSXApplyAttr(const wxDataViewItemAttr& attr)
2652 {
2653 wxDataViewRendererNativeData * const data = GetNativeData();
2654 NSCell * const cell = data->GetItemCell();
2655
2656 // set the font and text colour to use: we need to do it if we had ever
2657 // changed them before, even if this item itself doesn't have any special
2658 // attributes as otherwise it would reuse the attributes from the previous
2659 // cell rendered using the same renderer
2660 NSFont *font = NULL;
2661 NSColor *colText = NULL;
2662
2663 if ( attr.HasFont() )
2664 {
2665 font = data->GetOriginalFont();
2666 if ( !font )
2667 {
2668 // this is the first time we're setting the font, remember the
2669 // original one before changing it
2670 font = [cell font];
2671 data->SaveOriginalFont(font);
2672 }
2673
2674 if ( font )
2675 {
2676 // FIXME: using wxFont methods here doesn't work for some reason
2677 NSFontManager * const fm = [NSFontManager sharedFontManager];
2678 if ( attr.GetBold() )
2679 font = [fm convertFont:font toHaveTrait:NSBoldFontMask];
2680 if ( attr.GetItalic() )
2681 font = [fm convertFont:font toHaveTrait:NSItalicFontMask];
2682 }
2683 //else: can't change font if the cell doesn't have any
2684 }
2685
2686 if ( attr.HasColour() )
2687 {
2688 // we can set font for any cell but only NSTextFieldCell provides
2689 // a method for setting text colour so check that this method is
2690 // available before using it
2691 if ( [cell respondsToSelector:@selector(setTextColor:)] &&
2692 [cell respondsToSelector:@selector(textColor)] )
2693 {
2694 if ( !data->GetOriginalTextColour() )
2695 {
2696 // the cast to (untyped) id is safe because of the check above
2697 data->SaveOriginalTextColour([(id)cell textColor]);
2698 }
2699
2700 const wxColour& c = attr.GetColour();
2701 colText = [NSColor colorWithDeviceRed:c.Red() / 255.
2702 green:c.Green() / 255.
2703 blue:c.Blue() / 255.
2704 alpha:c.Alpha() / 255.];
2705 }
2706 }
2707
2708 if ( !font )
2709 font = data->GetOriginalFont();
2710 if ( !colText )
2711 colText = data->GetOriginalTextColour();
2712
2713 if ( font )
2714 [cell setFont:font];
2715
2716 if ( colText )
2717 [(id)cell setTextColor:colText];
2718 }
2719
2720 void wxDataViewRenderer::OSXApplyEnabled(bool enabled)
2721 {
2722 [GetNativeData()->GetItemCell() setEnabled:enabled];
2723 }
2724
2725 IMPLEMENT_ABSTRACT_CLASS(wxDataViewRenderer,wxDataViewRendererBase)
2726
2727 // ---------------------------------------------------------
2728 // wxDataViewCustomRenderer
2729 // ---------------------------------------------------------
2730 wxDataViewCustomRenderer::wxDataViewCustomRenderer(const wxString& varianttype,
2731 wxDataViewCellMode mode,
2732 int align)
2733 : wxDataViewCustomRendererBase(varianttype, mode, align),
2734 m_editorCtrlPtr(NULL),
2735 m_DCPtr(NULL)
2736 {
2737 SetNativeData(new wxDataViewRendererNativeData([[wxCustomCell alloc] init]));
2738 }
2739
2740 bool wxDataViewCustomRenderer::MacRender()
2741 {
2742 [GetNativeData()->GetItemCell() setObjectValue:[[[wxCustomRendererObject alloc] initWithRenderer:this] autorelease]];
2743 return true;
2744 }
2745
2746 void wxDataViewCustomRenderer::OSXApplyAttr(const wxDataViewItemAttr& attr)
2747 {
2748 // simply save the attribute so that it could be reused from our Render()
2749 SetAttr(attr);
2750
2751 // it's not necessary to call the base class version which sets the cell
2752 // properties to correspond to this attribute because we currently don't
2753 // use any NSCell methods in custom renderers anyhow but if we ever start
2754 // doing this (e.g. override RenderText() here to use NSTextFieldCell
2755 // methods), then we should pass it on to wxDataViewRenderer here
2756 }
2757
2758 IMPLEMENT_ABSTRACT_CLASS(wxDataViewCustomRenderer, wxDataViewRenderer)
2759
2760 // ---------------------------------------------------------
2761 // wxDataViewTextRenderer
2762 // ---------------------------------------------------------
2763 wxDataViewTextRenderer::wxDataViewTextRenderer(const wxString& varianttype,
2764 wxDataViewCellMode mode,
2765 int align)
2766 : wxDataViewRenderer(varianttype,mode,align)
2767 {
2768 NSTextFieldCell* cell;
2769
2770
2771 cell = [[NSTextFieldCell alloc] init];
2772 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2773 SetNativeData(new wxDataViewRendererNativeData(cell));
2774 [cell release];
2775 }
2776
2777 bool wxDataViewTextRenderer::MacRender()
2778 {
2779 if (GetValue().GetType() == GetVariantType())
2780 {
2781 [GetNativeData()->GetItemCell() setObjectValue:wxCFStringRef(GetValue().GetString()).AsNSString()];
2782 return true;
2783 }
2784 else
2785 {
2786 wxFAIL_MSG(wxString("Text renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2787 return false;
2788 }
2789 }
2790
2791 void
2792 wxDataViewTextRenderer::OSXOnCellChanged(NSObject *value,
2793 const wxDataViewItem& item,
2794 unsigned col)
2795 {
2796 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2797 model->ChangeValue(ObjectToString(value), item, col);
2798 }
2799
2800 IMPLEMENT_CLASS(wxDataViewTextRenderer,wxDataViewRenderer)
2801
2802 // ---------------------------------------------------------
2803 // wxDataViewBitmapRenderer
2804 // ---------------------------------------------------------
2805 wxDataViewBitmapRenderer::wxDataViewBitmapRenderer(const wxString& varianttype,
2806 wxDataViewCellMode mode,
2807 int align)
2808 : wxDataViewRenderer(varianttype,mode,align)
2809 {
2810 NSImageCell* cell;
2811
2812
2813 cell = [[NSImageCell alloc] init];
2814 SetNativeData(new wxDataViewRendererNativeData(cell));
2815 [cell release];
2816 }
2817
2818 // This method returns 'true' if
2819 // - the passed bitmap is valid and it could be assigned to the native data
2820 // browser;
2821 // - the passed bitmap is invalid (or is not initialized); this case
2822 // simulates a non-existing bitmap.
2823 // In all other cases the method returns 'false'.
2824 bool wxDataViewBitmapRenderer::MacRender()
2825 {
2826 wxCHECK_MSG(GetValue().GetType() == GetVariantType(),false,wxString("Bitmap renderer cannot render value; value type: ") << GetValue().GetType());
2827
2828 wxBitmap bitmap;
2829
2830 bitmap << GetValue();
2831 if (bitmap.IsOk())
2832 [GetNativeData()->GetItemCell() setObjectValue:[[bitmap.GetNSImage() retain] autorelease]];
2833 return true;
2834 }
2835
2836 IMPLEMENT_CLASS(wxDataViewBitmapRenderer,wxDataViewRenderer)
2837
2838 // -------------------------------------
2839 // wxDataViewChoiceRenderer
2840 // -------------------------------------
2841 wxDataViewChoiceRenderer::wxDataViewChoiceRenderer(const wxArrayString& choices,
2842 wxDataViewCellMode mode,
2843 int alignment)
2844 : wxDataViewRenderer(wxT("string"), mode, alignment),
2845 m_choices(choices)
2846 {
2847 NSPopUpButtonCell* cell;
2848
2849
2850 cell = [[NSPopUpButtonCell alloc] init];
2851 [cell setControlSize:NSMiniControlSize];
2852 [cell setFont:[NSFont fontWithName:[[cell font] fontName] size:[NSFont systemFontSizeForControlSize:NSMiniControlSize]]];
2853 for (size_t i=0; i<choices.GetCount(); ++i)
2854 [cell addItemWithTitle:wxCFStringRef(choices[i]).AsNSString()];
2855 SetNativeData(new wxDataViewRendererNativeData(cell));
2856 [cell release];
2857 }
2858
2859 bool wxDataViewChoiceRenderer::MacRender()
2860 {
2861 if (GetValue().GetType() == GetVariantType())
2862 {
2863 [((NSPopUpButtonCell*) GetNativeData()->GetItemCell()) selectItemWithTitle:[[wxCFStringRef(GetValue().GetString()).AsNSString() retain] autorelease]];
2864 return true;
2865 }
2866 else
2867 {
2868 wxFAIL_MSG(wxString("Choice renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2869 return false;
2870 }
2871 }
2872
2873 IMPLEMENT_CLASS(wxDataViewChoiceRenderer,wxDataViewRenderer)
2874
2875 // ---------------------------------------------------------
2876 // wxDataViewDateRenderer
2877 // ---------------------------------------------------------
2878
2879 wxDataViewDateRenderer::wxDataViewDateRenderer(const wxString& varianttype,
2880 wxDataViewCellMode mode,
2881 int align)
2882 : wxDataViewRenderer(varianttype,mode,align)
2883 {
2884 NSTextFieldCell* cell;
2885
2886 NSDateFormatter* dateFormatter;
2887
2888
2889 dateFormatter = [[NSDateFormatter alloc] init];
2890 [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
2891 [dateFormatter setDateStyle:NSDateFormatterShortStyle];
2892 cell = [[NSTextFieldCell alloc] init];
2893 [cell setFormatter:dateFormatter];
2894 SetNativeData(new wxDataViewRendererNativeData(cell,[NSDate dateWithString:@"2000-12-30 20:00:00 +0000"]));
2895 [cell release];
2896 [dateFormatter release];
2897 }
2898
2899 bool wxDataViewDateRenderer::MacRender()
2900 {
2901 if (GetValue().GetType() == GetVariantType())
2902 {
2903 if (GetValue().GetDateTime().IsValid())
2904 {
2905 // -- find best fitting style to show the date --
2906 // as the style should be identical for all cells a reference date
2907 // instead of the actual cell's date value is used for all cells;
2908 // this reference date is stored in the renderer's native data
2909 // section for speed purposes; otherwise, the reference date's
2910 // string has to be recalculated for each item that may become
2911 // timewise long if a lot of rows using dates exist; the algorithm
2912 // has the preference to display as much information as possible
2913 // in the first instance; but as this is often impossible due to
2914 // space restrictions the style is shortened per loop; finally, if
2915 // the shortest time and date format does not fit into the cell
2916 // the time part is dropped; remark: the time part itself is not
2917 // modified per iteration loop and only uses the short style,
2918 // means that only the hours and minutes are being shown
2919
2920 // GetObject() returns a date for testing the size of a date object
2921 [GetNativeData()->GetItemCell() setObjectValue:GetNativeData()->GetObject()];
2922 [[GetNativeData()->GetItemCell() formatter] setTimeStyle:NSDateFormatterShortStyle];
2923 for (int dateFormatterStyle=4; dateFormatterStyle>0; --dateFormatterStyle)
2924 {
2925 [[GetNativeData()->GetItemCell() formatter] setDateStyle:(NSDateFormatterStyle)dateFormatterStyle];
2926 if (dateFormatterStyle == 1)
2927 {
2928 // if the shortest style for displaying the date and time
2929 // is too long to be fully visible remove the time part of
2930 // the date:
2931 if ([GetNativeData()->GetItemCell() cellSize].width > [GetNativeData()->GetColumnPtr() width])
2932 [[GetNativeData()->GetItemCell() formatter] setTimeStyle:NSDateFormatterNoStyle];
2933 {
2934 // basically not necessary as the loop would end anyway
2935 // but let's save the last comparison
2936 break;
2937 }
2938 }
2939 else if ([GetNativeData()->GetItemCell() cellSize].width <= [GetNativeData()->GetColumnPtr() width])
2940 break;
2941 }
2942 // set data (the style is set by the previous loop); on OSX the
2943 // date has to be specified with respect to UTC; in wxWidgets the
2944 // date is always entered in the local timezone; so, we have to do
2945 // a conversion from the local to UTC timezone when adding the
2946 // seconds to 1970-01-01 UTC:
2947 [GetNativeData()->GetItemCell() setObjectValue:[NSDate dateWithTimeIntervalSince1970:GetValue().GetDateTime().ToUTC().Subtract(wxDateTime(1,wxDateTime::Jan,1970)).GetSeconds().ToDouble()]];
2948 }
2949 return true;
2950 }
2951 else
2952 {
2953 wxFAIL_MSG(wxString("Date renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2954 return false;
2955 }
2956 }
2957
2958 void
2959 wxDataViewDateRenderer::OSXOnCellChanged(NSObject *value,
2960 const wxDataViewItem& item,
2961 unsigned col)
2962 {
2963 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2964 model->ChangeValue(ObjectToDate(value), item, col);
2965 }
2966
2967 IMPLEMENT_ABSTRACT_CLASS(wxDataViewDateRenderer,wxDataViewRenderer)
2968
2969 // ---------------------------------------------------------
2970 // wxDataViewIconTextRenderer
2971 // ---------------------------------------------------------
2972 wxDataViewIconTextRenderer::wxDataViewIconTextRenderer(const wxString& varianttype,
2973 wxDataViewCellMode mode,
2974 int align)
2975 : wxDataViewRenderer(varianttype,mode)
2976 {
2977 wxImageTextCell* cell;
2978
2979
2980 cell = [[wxImageTextCell alloc] init];
2981 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2982 SetNativeData(new wxDataViewRendererNativeData(cell));
2983 [cell release];
2984 }
2985
2986 bool wxDataViewIconTextRenderer::MacRender()
2987 {
2988 if (GetValue().GetType() == GetVariantType())
2989 {
2990 wxDataViewIconText iconText;
2991
2992 wxImageTextCell* cell;
2993
2994 cell = (wxImageTextCell*) GetNativeData()->GetItemCell();
2995 iconText << GetValue();
2996 if (iconText.GetIcon().IsOk())
2997 [cell setImage:[[wxBitmap(iconText.GetIcon()).GetNSImage() retain] autorelease]];
2998 else
2999 [cell setImage:nil];
3000 [cell setStringValue:[[wxCFStringRef(iconText.GetText()).AsNSString() retain] autorelease]];
3001 return true;
3002 }
3003 else
3004 {
3005 wxFAIL_MSG(wxString("Icon & text renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
3006 return false;
3007 }
3008 }
3009
3010 void
3011 wxDataViewIconTextRenderer::OSXOnCellChanged(NSObject *value,
3012 const wxDataViewItem& item,
3013 unsigned col)
3014 {
3015 wxVariant valueIconText;
3016 valueIconText << wxDataViewIconText(ObjectToString(value));
3017
3018 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
3019 model->ChangeValue(valueIconText, item, col);
3020 }
3021
3022 IMPLEMENT_ABSTRACT_CLASS(wxDataViewIconTextRenderer,wxDataViewRenderer)
3023
3024 // ---------------------------------------------------------
3025 // wxDataViewToggleRenderer
3026 // ---------------------------------------------------------
3027 wxDataViewToggleRenderer::wxDataViewToggleRenderer(const wxString& varianttype,
3028 wxDataViewCellMode mode,
3029 int align)
3030 : wxDataViewRenderer(varianttype,mode)
3031 {
3032 NSButtonCell* cell;
3033
3034
3035 cell = [[NSButtonCell alloc] init];
3036 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
3037 [cell setButtonType:NSSwitchButton];
3038 [cell setImagePosition:NSImageOnly];
3039 SetNativeData(new wxDataViewRendererNativeData(cell));
3040 [cell release];
3041 }
3042
3043 bool wxDataViewToggleRenderer::MacRender()
3044 {
3045 if (GetValue().GetType() == GetVariantType())
3046 {
3047 [GetNativeData()->GetItemCell() setIntValue:GetValue().GetLong()];
3048 return true;
3049 }
3050 else
3051 {
3052 wxFAIL_MSG(wxString("Toggle renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
3053 return false;
3054 }
3055 }
3056
3057 void
3058 wxDataViewToggleRenderer::OSXOnCellChanged(NSObject *value,
3059 const wxDataViewItem& item,
3060 unsigned col)
3061 {
3062 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
3063 model->ChangeValue(ObjectToBool(value), item, col);
3064 }
3065
3066 IMPLEMENT_ABSTRACT_CLASS(wxDataViewToggleRenderer,wxDataViewRenderer)
3067
3068 // ---------------------------------------------------------
3069 // wxDataViewProgressRenderer
3070 // ---------------------------------------------------------
3071 wxDataViewProgressRenderer::wxDataViewProgressRenderer(const wxString& label,
3072 const wxString& varianttype,
3073 wxDataViewCellMode mode,
3074 int align)
3075 : wxDataViewRenderer(varianttype,mode,align)
3076 {
3077 wxUnusedVar(label);
3078
3079 NSLevelIndicatorCell* cell;
3080
3081 cell = [[NSLevelIndicatorCell alloc] initWithLevelIndicatorStyle:NSContinuousCapacityLevelIndicatorStyle];
3082 [cell setMinValue:0];
3083 [cell setMaxValue:100];
3084 SetNativeData(new wxDataViewRendererNativeData(cell));
3085 [cell release];
3086 }
3087
3088 bool wxDataViewProgressRenderer::MacRender()
3089 {
3090 if (GetValue().GetType() == GetVariantType())
3091 {
3092 [GetNativeData()->GetItemCell() setIntValue:GetValue().GetLong()];
3093 return true;
3094 }
3095 else
3096 {
3097 wxFAIL_MSG(wxString("Progress renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
3098 return false;
3099 }
3100 }
3101
3102 void
3103 wxDataViewProgressRenderer::OSXOnCellChanged(NSObject *value,
3104 const wxDataViewItem& item,
3105 unsigned col)
3106 {
3107 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
3108 model->ChangeValue(ObjectToLong(value), item, col);
3109 }
3110
3111 IMPLEMENT_ABSTRACT_CLASS(wxDataViewProgressRenderer,wxDataViewRenderer)
3112
3113 // ---------------------------------------------------------
3114 // wxDataViewColumn
3115 // ---------------------------------------------------------
3116
3117 wxDataViewColumn::wxDataViewColumn(const wxString& title,
3118 wxDataViewRenderer* renderer,
3119 unsigned int model_column,
3120 int width,
3121 wxAlignment align,
3122 int flags)
3123 : wxDataViewColumnBase(renderer, model_column),
3124 m_NativeDataPtr(new wxDataViewColumnNativeData()),
3125 m_title(title)
3126 {
3127 InitCommon(width, align, flags);
3128 if (renderer && !renderer->IsCustomRenderer() &&
3129 (renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
3130 renderer->SetAlignment(align);
3131 }
3132
3133 wxDataViewColumn::wxDataViewColumn(const wxBitmap& bitmap,
3134 wxDataViewRenderer* renderer,
3135 unsigned int model_column,
3136 int width,
3137 wxAlignment align,
3138 int flags)
3139 : wxDataViewColumnBase(bitmap, renderer, model_column),
3140 m_NativeDataPtr(new wxDataViewColumnNativeData())
3141 {
3142 InitCommon(width, align, flags);
3143 if (renderer && !renderer->IsCustomRenderer() &&
3144 (renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
3145 renderer->SetAlignment(align);
3146 }
3147
3148 wxDataViewColumn::~wxDataViewColumn()
3149 {
3150 delete m_NativeDataPtr;
3151 }
3152
3153 int wxDataViewColumn::GetWidth() const
3154 {
3155 return [m_NativeDataPtr->GetNativeColumnPtr() width];
3156 }
3157
3158 bool wxDataViewColumn::IsSortKey() const
3159 {
3160 NSTableColumn *nsCol = GetNativeData()->GetNativeColumnPtr();
3161 return nsCol && ([nsCol sortDescriptorPrototype] != nil);
3162 }
3163
3164 void wxDataViewColumn::SetAlignment(wxAlignment align)
3165 {
3166 m_alignment = align;
3167 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
3168 if (m_renderer && !m_renderer->IsCustomRenderer() &&
3169 (m_renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
3170 m_renderer->SetAlignment(align);
3171 }
3172
3173 void wxDataViewColumn::SetBitmap(const wxBitmap& bitmap)
3174 {
3175 // bitmaps and titles cannot exist at the same time - if the bitmap is set
3176 // the title is removed:
3177 m_title = wxEmptyString;
3178 wxDataViewColumnBase::SetBitmap(bitmap);
3179 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setImage:[[bitmap.GetNSImage() retain] autorelease]];
3180 }
3181
3182 void wxDataViewColumn::SetMaxWidth(int maxWidth)
3183 {
3184 m_maxWidth = maxWidth;
3185 [m_NativeDataPtr->GetNativeColumnPtr() setMaxWidth:maxWidth];
3186 }
3187
3188 void wxDataViewColumn::SetMinWidth(int minWidth)
3189 {
3190 m_minWidth = minWidth;
3191 [m_NativeDataPtr->GetNativeColumnPtr() setMinWidth:minWidth];
3192 }
3193
3194 void wxDataViewColumn::SetReorderable(bool reorderable)
3195 {
3196 wxUnusedVar(reorderable);
3197 }
3198
3199 void wxDataViewColumn::SetHidden(bool hidden)
3200 {
3201 // How to set flag here?
3202
3203 [m_NativeDataPtr->GetNativeColumnPtr() setHidden:hidden];
3204 }
3205
3206 bool wxDataViewColumn::IsHidden() const
3207 {
3208 return [m_NativeDataPtr->GetNativeColumnPtr() isHidden];
3209 }
3210
3211 void wxDataViewColumn::SetResizeable(bool resizable)
3212 {
3213 wxDataViewColumnBase::SetResizeable(resizable);
3214 if (resizable)
3215 [m_NativeDataPtr->GetNativeColumnPtr() setResizingMask:NSTableColumnUserResizingMask];
3216 else
3217 [m_NativeDataPtr->GetNativeColumnPtr() setResizingMask:NSTableColumnNoResizing];
3218 }
3219
3220 void wxDataViewColumn::SetSortable(bool sortable)
3221 {
3222 // wxDataViewColumnBase::SetSortable(sortable);
3223 // Avoid endless recursion and just set the flag here
3224 if (sortable)
3225 m_flags |= wxDATAVIEW_COL_SORTABLE;
3226 else
3227 m_flags &= ~wxDATAVIEW_COL_SORTABLE;
3228 }
3229
3230 void wxDataViewColumn::SetSortOrder(bool ascending)
3231 {
3232 if (m_ascending != ascending)
3233 {
3234 m_ascending = ascending;
3235 if (IsSortKey())
3236 {
3237 // change sorting order:
3238 NSArray* sortDescriptors;
3239 NSSortDescriptor* sortDescriptor;
3240 NSTableColumn* tableColumn;
3241
3242 tableColumn = m_NativeDataPtr->GetNativeColumnPtr();
3243 sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[[tableColumn sortDescriptorPrototype] key] ascending:m_ascending];
3244 sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
3245 [tableColumn setSortDescriptorPrototype:sortDescriptor];
3246 [[tableColumn tableView] setSortDescriptors:sortDescriptors];
3247 [sortDescriptor release];
3248 }
3249 }
3250 }
3251
3252 void wxDataViewColumn::SetTitle(const wxString& title)
3253 {
3254 // bitmaps and titles cannot exist at the same time - if the title is set
3255 // the bitmap is removed:
3256 wxDataViewColumnBase::SetBitmap(wxBitmap());
3257 m_title = title;
3258 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setStringValue:[[wxCFStringRef(title).AsNSString() retain] autorelease]];
3259 }
3260
3261 void wxDataViewColumn::SetWidth(int width)
3262 {
3263 m_width = width;
3264
3265 switch ( width )
3266 {
3267 case wxCOL_WIDTH_AUTOSIZE:
3268 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
3269 if ( GetOwner() )
3270 {
3271 wxCocoaDataViewControl *peer = static_cast<wxCocoaDataViewControl*>(GetOwner()->GetPeer());
3272 peer->FitColumnWidthToContent(GetOwner()->GetColumnPosition(this));
3273 break;
3274 }
3275 #endif
3276 // fall through if unsupported (OSX < 10.5) or not yet settable
3277
3278 case wxCOL_WIDTH_DEFAULT:
3279 width = wxDVC_DEFAULT_WIDTH;
3280 // fall through
3281
3282 default:
3283 [m_NativeDataPtr->GetNativeColumnPtr() setWidth:width];
3284 break;
3285 }
3286 }
3287
3288 void wxDataViewColumn::SetNativeData(wxDataViewColumnNativeData* newNativeDataPtr)
3289 {
3290 delete m_NativeDataPtr;
3291 m_NativeDataPtr = newNativeDataPtr;
3292 }
3293
3294 #endif // (wxUSE_DATAVIEWCTRL == 1) && !defined(wxUSE_GENERICDATAVIEWCTRL)