]> git.saurik.com Git - wxWidgets.git/blob - src/osx/cocoa/dataview.mm
Fit modeless preferences dialog to its contents too.
[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_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_DATAVIEW_COLUMN_SORTED,dvc->GetId()); // variable definition
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_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_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 // give additional headroom for trailing NULL
930 wxMemoryBuffer dataBuffer(dataBufferSize+4);
931
932 dataBuffer.AppendData(&idDataFormat,sizeof(wxDataFormatId));
933 switch (idDataFormat)
934 {
935 case wxDF_TEXT:
936 // otherwise wxDF_UNICODETEXT already filled up
937 // the string; and the UNICODE representation has
938 // priority
939 if (!itemStringAvailable)
940 {
941 event.GetDataObject()->GetDataHere(wxDF_TEXT,dataBuffer.GetAppendBuf(dataSize));
942 dataBuffer.UngetAppendBuf(dataSize);
943 [dataArray addObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
944 itemString = wxString(static_cast<char const*>(dataBuffer.GetData())+sizeof(wxDataFormatId),wxConvLocal);
945 itemStringAvailable = true;
946 }
947 break;
948 case wxDF_UNICODETEXT:
949 {
950 event.GetDataObject()->GetDataHere(wxDF_UNICODETEXT,dataBuffer.GetAppendBuf(dataSize));
951 dataBuffer.UngetAppendBuf(dataSize);
952 if (itemStringAvailable) // does an object already exist as an ASCII text (see wxDF_TEXT case statement)?
953 [dataArray replaceObjectAtIndex:itemCounter withObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
954 else
955 [dataArray addObject:[NSData dataWithBytes:dataBuffer.GetData() length:dataBufferSize]];
956 itemString = wxString::FromUTF8(static_cast<char const*>(dataBuffer.GetData())+sizeof(wxDataFormatId),dataSize);
957 itemStringAvailable = true;
958 } /* block */
959 break;
960 default:
961 wxFAIL_MSG("Data object has invalid or unsupported data format");
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 delete itemObject;
980 return NO; // dragging was vetoed or no data available
981 }
982 }
983 if (dataStringAvailable)
984 {
985 wxCFStringRef osxString(dataString);
986
987 [pasteboard declareTypes:[NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil] owner:nil];
988 [pasteboard setPropertyList:dataArray forType:DataViewPboardType];
989 [pasteboard setString:osxString.AsNSString() forType:NSStringPboardType];
990 }
991 else
992 {
993 [pasteboard declareTypes:[NSArray arrayWithObject:DataViewPboardType] owner:nil];
994 [pasteboard setPropertyList:dataArray forType:DataViewPboardType];
995 }
996 return YES;
997 }
998 else
999 return NO; // no items to drag (should never occur)
1000 }
1001
1002 //
1003 // buffer handling
1004 //
1005 -(void) addToBuffer:(wxPointerObject*)item
1006 {
1007 [items addObject:item];
1008 }
1009
1010 -(void) clearBuffer
1011 {
1012 [items removeAllObjects];
1013 }
1014
1015 -(wxPointerObject*) getDataViewItemFromBuffer:(const wxDataViewItem&)item
1016 {
1017 return [items member:[[[wxPointerObject alloc] initWithPointer:item.GetID()] autorelease]];
1018 }
1019
1020 -(wxPointerObject*) getItemFromBuffer:(wxPointerObject*)item
1021 {
1022 return [items member:item];
1023 }
1024
1025 -(BOOL) isInBuffer:(wxPointerObject*)item
1026 {
1027 return [items containsObject:item];
1028 }
1029
1030 -(void) removeFromBuffer:(wxPointerObject*)item
1031 {
1032 [items removeObject:item];
1033 }
1034
1035 //
1036 // children handling
1037 //
1038 -(void) appendChild:(wxPointerObject*)item
1039 {
1040 [children addObject:item];
1041 }
1042
1043 -(void) clearChildren
1044 {
1045 [children removeAllObjects];
1046 }
1047
1048 -(wxPointerObject*) getChild:(NSUInteger)index
1049 {
1050 return [children objectAtIndex:index];
1051 }
1052
1053 -(NSUInteger) getChildCount
1054 {
1055 return [children count];
1056 }
1057
1058 -(void) removeChild:(NSUInteger)index
1059 {
1060 [children removeObjectAtIndex:index];
1061 }
1062
1063 //
1064 // buffer handling
1065 //
1066 -(void) clearBuffers
1067 {
1068 [self clearBuffer];
1069 [self clearChildren];
1070 [self setCurrentParentItem:nil];
1071 }
1072
1073 //
1074 // sorting
1075 //
1076 -(NSArray*) sortDescriptors
1077 {
1078 return sortDescriptors;
1079 }
1080
1081 -(void) setSortDescriptors:(NSArray*)newSortDescriptors
1082 {
1083 [newSortDescriptors retain];
1084 [sortDescriptors release];
1085 sortDescriptors = newSortDescriptors;
1086 }
1087
1088 //
1089 // access to wxWidget's implementation
1090 //
1091 -(wxPointerObject*) currentParentItem
1092 {
1093 return currentParentItem;
1094 }
1095
1096 -(wxCocoaDataViewControl*) implementation
1097 {
1098 return implementation;
1099 }
1100
1101 -(wxDataViewModel*) model
1102 {
1103 return model;
1104 }
1105
1106 -(void) setCurrentParentItem:(wxPointerObject*)newCurrentParentItem
1107 {
1108 [newCurrentParentItem retain];
1109 [currentParentItem release];
1110 currentParentItem = newCurrentParentItem;
1111 }
1112
1113 -(void) setImplementation:(wxCocoaDataViewControl*) newImplementation
1114 {
1115 implementation = newImplementation;
1116 }
1117
1118 -(void) setModel:(wxDataViewModel*) newModel
1119 {
1120 model = newModel;
1121 }
1122
1123 //
1124 // other methods
1125 //
1126 -(void) bufferItem:(wxPointerObject*)parentItem withChildren:(wxDataViewItemArray*)dataViewChildrenPtr
1127 {
1128 NSInteger const noOfChildren = (*dataViewChildrenPtr).GetCount();
1129
1130 [self setCurrentParentItem:parentItem];
1131 [self clearChildren];
1132 for (NSInteger indexChild=0; indexChild<noOfChildren; ++indexChild)
1133 {
1134 wxPointerObject* bufferedPointerObject;
1135 wxPointerObject* newPointerObject([[wxPointerObject alloc] initWithPointer:(*dataViewChildrenPtr)[indexChild].GetID()]);
1136
1137 // The next statement and test looks strange but there is
1138 // unfortunately no workaround: due to the fact that two pointer
1139 // objects are identical if their pointers are identical - because the
1140 // method isEqual has been overloaded - the set operation will only
1141 // add a new pointer object if there is not already one in the set
1142 // having the same pointer. On the other side the children's array
1143 // would always add the new pointer object. This means that different
1144 // pointer objects are stored in the set and array. This will finally
1145 // lead to a crash as objects diverge. To solve this issue it is first
1146 // tested if the child already exists in the set and if it is the case
1147 // the sets object is going to be appended to the array, otheriwse the
1148 // new pointer object is added to the set and array:
1149 bufferedPointerObject = [self getItemFromBuffer:newPointerObject];
1150 if (bufferedPointerObject == nil)
1151 {
1152 [items addObject:newPointerObject];
1153 [children addObject:newPointerObject];
1154 }
1155 else
1156 [children addObject:bufferedPointerObject];
1157 [newPointerObject release];
1158 }
1159 }
1160
1161 @end
1162
1163 // ============================================================================
1164 // wxCustomCell
1165 // ============================================================================
1166
1167 @implementation wxCustomCell
1168
1169 #if 0 // starting implementation for custom cell clicks
1170
1171 - (id)init
1172 {
1173 self = [super init];
1174 [self setAction:@selector(clickedAction)];
1175 [self setTarget:self];
1176 return self;
1177 }
1178
1179 - (void) clickedAction: (id) sender
1180 {
1181 wxUnusedVar(sender);
1182 }
1183
1184 #endif
1185
1186 -(NSSize) cellSize
1187 {
1188 wxCustomRendererObject * const
1189 obj = static_cast<wxCustomRendererObject *>([self objectValue]);
1190
1191
1192 const wxSize size = obj->customRenderer->GetSize();
1193 return NSMakeSize(size.x, size.y);
1194 }
1195
1196 //
1197 // implementations
1198 //
1199 -(void) drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
1200 {
1201 wxCustomRendererObject * const
1202 obj = static_cast<wxCustomRendererObject *>([self objectValue]);
1203 if ( !obj )
1204 {
1205 // this may happen for the custom cells in container rows: they don't
1206 // have any values
1207 return;
1208 }
1209
1210 wxDataViewCustomRenderer * const renderer = obj->customRenderer;
1211
1212 // if this method is called everything is already setup correctly,
1213 CGContextRef context = (CGContextRef) [[NSGraphicsContext currentContext] graphicsPort];
1214 CGContextSaveGState( context );
1215
1216 if ( ![controlView isFlipped] )
1217 {
1218 CGContextTranslateCTM( context, 0, [controlView bounds].size.height );
1219 CGContextScaleCTM( context, 1, -1 );
1220 }
1221
1222 wxGCDC dc;
1223 wxGraphicsContext* gc = wxGraphicsContext::CreateFromNative(context);
1224 dc.SetGraphicsContext(gc);
1225
1226 int state = 0;
1227 if ( [self isHighlighted] )
1228 state |= wxDATAVIEW_CELL_SELECTED;
1229
1230 renderer->WXCallRender(wxFromNSRect(controlView, cellFrame), &dc, state);
1231
1232 CGContextRestoreGState( context );
1233 }
1234
1235 -(NSRect) imageRectForBounds:(NSRect)cellFrame
1236 {
1237 return cellFrame;
1238 }
1239
1240 -(NSRect) titleRectForBounds:(NSRect)cellFrame
1241 {
1242 return cellFrame;
1243 }
1244
1245 @end
1246
1247 // ============================================================================
1248 // wxImageTextCell
1249 // ============================================================================
1250 @implementation wxImageTextCell
1251 //
1252 // initialization
1253 //
1254 -(id) init
1255 {
1256 self = [super init];
1257 if (self != nil)
1258 {
1259 // initializing the text part:
1260 [self setSelectable:YES];
1261 // initializing the image part:
1262 image = nil;
1263 imageSize = NSMakeSize(16,16);
1264 spaceImageText = 5.0;
1265 xImageShift = 5.0;
1266 }
1267 return self;
1268 }
1269
1270 -(id) copyWithZone:(NSZone*)zone
1271 {
1272 wxImageTextCell* cell;
1273
1274
1275 cell = (wxImageTextCell*) [super copyWithZone:zone];
1276 cell->image = [image retain];
1277 cell->imageSize = imageSize;
1278 cell->spaceImageText = spaceImageText;
1279 cell->xImageShift = xImageShift;
1280
1281 return cell;
1282 }
1283
1284 -(void) dealloc
1285 {
1286 [image release];
1287
1288 [super dealloc];
1289 }
1290
1291 //
1292 // alignment
1293 //
1294 -(NSTextAlignment) alignment
1295 {
1296 return cellAlignment;
1297 }
1298
1299 -(void) setAlignment:(NSTextAlignment)newAlignment
1300 {
1301 cellAlignment = newAlignment;
1302 switch (newAlignment)
1303 {
1304 case NSCenterTextAlignment:
1305 case NSLeftTextAlignment:
1306 case NSJustifiedTextAlignment:
1307 case NSNaturalTextAlignment:
1308 [super setAlignment:NSLeftTextAlignment];
1309 break;
1310 case NSRightTextAlignment:
1311 [super setAlignment:NSRightTextAlignment];
1312 break;
1313 default:
1314 wxFAIL_MSG("Unknown alignment type.");
1315 }
1316 }
1317
1318 //
1319 // image access
1320 //
1321 -(NSImage*) image
1322 {
1323 return image;
1324 }
1325
1326 -(void) setImage:(NSImage*)newImage
1327 {
1328 [newImage retain];
1329 [image release];
1330 image = newImage;
1331 }
1332
1333 -(NSSize) imageSize
1334 {
1335 return imageSize;
1336 }
1337
1338 -(void) setImageSize:(NSSize) newImageSize
1339 {
1340 imageSize = newImageSize;
1341 }
1342
1343 //
1344 // other methods
1345 //
1346 -(NSSize) cellImageSize
1347 {
1348 return NSMakeSize(imageSize.width+xImageShift+spaceImageText,imageSize.height);
1349 }
1350
1351 -(NSSize) cellSize
1352 {
1353 NSSize cellSize([super cellSize]);
1354
1355
1356 if (imageSize.height > cellSize.height)
1357 cellSize.height = imageSize.height;
1358 cellSize.width += imageSize.width+xImageShift+spaceImageText;
1359
1360 return cellSize;
1361 }
1362
1363 -(NSSize) cellTextSize
1364 {
1365 return [super cellSize];
1366 }
1367
1368 //
1369 // implementations
1370 //
1371 -(void) determineCellParts:(NSRect)cellFrame imagePart:(NSRect*)imageFrame textPart:(NSRect*)textFrame
1372 {
1373 switch (cellAlignment)
1374 {
1375 case NSCenterTextAlignment:
1376 {
1377 CGFloat const cellSpace = cellFrame.size.width-[self cellSize].width;
1378
1379 // if the cell's frame is smaller than its contents (at least
1380 // in x-direction) make sure that the image is visible:
1381 if (cellSpace <= 0)
1382 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1383 else // otherwise center the image and text in the cell's frame
1384 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText+0.5*cellSpace,NSMinXEdge);
1385 }
1386 break;
1387 case NSJustifiedTextAlignment:
1388 case NSLeftTextAlignment:
1389 case NSNaturalTextAlignment: // how to determine the natural writing direction? TODO
1390 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1391 break;
1392 case NSRightTextAlignment:
1393 {
1394 CGFloat const cellSpace = cellFrame.size.width-[self cellSize].width;
1395
1396 // if the cell's frame is smaller than its contents (at least
1397 // in x-direction) make sure that the image is visible:
1398 if (cellSpace <= 0)
1399 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText,NSMinXEdge);
1400 else // otherwise right align the image and text in the cell's frame
1401 NSDivideRect(cellFrame,imageFrame,textFrame,xImageShift+imageSize.width+spaceImageText+cellSpace,NSMinXEdge);
1402 }
1403 break;
1404 default:
1405 *imageFrame = NSZeroRect;
1406 *textFrame = NSZeroRect;
1407 wxFAIL_MSG("Unhandled alignment type.");
1408 }
1409 }
1410
1411 -(void) drawWithFrame:(NSRect)cellFrame inView:(NSView*)controlView
1412 {
1413 NSRect textFrame, imageFrame;
1414
1415
1416 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1417 // draw the image part by ourselves;
1418 // check if the cell has to draw its own background (checking is done by
1419 // the parameter of the textfield's cell):
1420 if ([self drawsBackground])
1421 {
1422 [[self backgroundColor] set];
1423 NSRectFill(imageFrame);
1424 }
1425 if (image != nil)
1426 {
1427 // the image is slightly shifted (xImageShift) and has a fixed size
1428 // but the image's frame might be larger and starts currently on the
1429 // left side of the cell's frame; therefore, the origin and the
1430 // image's frame size have to be adjusted:
1431 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1432 {
1433 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1434 imageFrame.size.width = imageSize.width;
1435 }
1436 else
1437 {
1438 imageFrame.origin.x += xImageShift;
1439 imageFrame.size.width -= xImageShift+spaceImageText;
1440 }
1441 // ...and the image has to be centered in the y-direction:
1442 if (imageFrame.size.height > imageSize.height)
1443 imageFrame.size.height = imageSize.height;
1444 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1445
1446 // according to the documentation the coordinate system should be
1447 // flipped for NSTableViews (y-coordinate goes from top to bottom); to
1448 // draw an image correctly the coordinate system has to be transformed
1449 // to a bottom-top coordinate system, otherwise the image's
1450 // content is flipped:
1451 NSAffineTransform* coordinateTransform([NSAffineTransform transform]);
1452
1453 if ([controlView isFlipped])
1454 {
1455 [coordinateTransform scaleXBy: 1.0 yBy:-1.0]; // first the coordinate system is brought back to bottom-top orientation
1456 [coordinateTransform translateXBy:0.0 yBy:(-2.0)*imageFrame.origin.y-imageFrame.size.height]; // the coordinate system has to be moved to compensate for the
1457 [coordinateTransform concat]; // other orientation and the position of the image's frame
1458 }
1459 [image drawInRect:imageFrame fromRect:NSZeroRect operation:NSCompositeSourceOver fraction:1.0]; // suggested method to draw the image
1460 // instead of compositeToPoint:operation:
1461 // take back previous transformation (if the view is not flipped the
1462 // coordinate transformation matrix contains the identity matrix and
1463 // the next two operations do not change the content's transformation
1464 // matrix):
1465 [coordinateTransform invert];
1466 [coordinateTransform concat];
1467 }
1468 // let the textfield cell draw the text part:
1469 if (textFrame.size.width > [self cellTextSize].width)
1470 {
1471 // for unknown reasons the alignment of the text cell is ignored;
1472 // therefore change the size so that alignment does not influence the
1473 // visualization anymore
1474 textFrame.size.width = [self cellTextSize].width;
1475 }
1476 [super drawWithFrame:textFrame inView:controlView];
1477 }
1478
1479 -(void) editWithFrame:(NSRect)aRect inView:(NSView*)controlView editor:(NSText*)textObj delegate:(id)anObject event:(NSEvent*)theEvent
1480 {
1481 NSRect textFrame, imageFrame;
1482
1483
1484 [self determineCellParts:aRect imagePart:&imageFrame textPart:&textFrame];
1485 [super editWithFrame:textFrame inView:controlView editor:textObj delegate:anObject event:theEvent];
1486 }
1487
1488 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_5
1489 -(NSUInteger) hitTestForEvent:(NSEvent*)event inRect:(NSRect)cellFrame ofView:(NSView*)controlView
1490 {
1491 NSPoint point = [controlView convertPoint:[event locationInWindow] fromView:nil];
1492
1493 NSRect imageFrame, textFrame;
1494
1495
1496 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1497 if (image != nil)
1498 {
1499 // the image is shifted...
1500 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1501 {
1502 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1503 imageFrame.size.width = imageSize.width;
1504 }
1505 else
1506 {
1507 imageFrame.origin.x += xImageShift;
1508 imageFrame.size.width -= xImageShift+spaceImageText;
1509 }
1510 // ...and centered:
1511 if (imageFrame.size.height > imageSize.height)
1512 imageFrame.size.height = imageSize.height;
1513 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1514 // If the point is in the image rect, then it is a content hit (see
1515 // documentation for hitTestForEvent:inRect:ofView):
1516 if (NSMouseInRect(point, imageFrame, [controlView isFlipped]))
1517 return NSCellHitContentArea;
1518 }
1519 // if the image was not hit let's try the text part:
1520 if (textFrame.size.width > [self cellTextSize].width)
1521 {
1522 // for unknown reasons the alignment of the text cell is ignored;
1523 // therefore change the size so that alignment does not influence the
1524 // visualization anymore
1525 textFrame.size.width = [self cellTextSize].width;
1526 }
1527
1528 return [super hitTestForEvent:event inRect:textFrame ofView:controlView];
1529 }
1530 #endif
1531
1532 -(NSRect) imageRectForBounds:(NSRect)cellFrame
1533 {
1534 NSRect textFrame, imageFrame;
1535
1536
1537 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1538 if (imageFrame.size.width >= xImageShift+imageSize.width+spaceImageText)
1539 {
1540 imageFrame.origin.x += imageFrame.size.width-imageSize.width-spaceImageText;
1541 imageFrame.size.width = imageSize.width;
1542 }
1543 else
1544 {
1545 imageFrame.origin.x += xImageShift;
1546 imageFrame.size.width -= xImageShift+spaceImageText;
1547 }
1548 // ...and centered:
1549 if (imageFrame.size.height > imageSize.height)
1550 imageFrame.size.height = imageSize.height;
1551 imageFrame.origin.y += ceil(0.5*(cellFrame.size.height-imageFrame.size.height));
1552
1553 return imageFrame;
1554 }
1555
1556 -(void) selectWithFrame:(NSRect)aRect inView:(NSView*)controlView editor:(NSText*)textObj delegate:(id)anObject start:(NSInteger)selStart length:(NSInteger)selLength
1557 {
1558 NSRect textFrame, imageFrame;
1559
1560
1561 [self determineCellParts:aRect imagePart:&imageFrame textPart:&textFrame];
1562 [super selectWithFrame:textFrame inView:controlView editor:textObj delegate:anObject start:selStart length:selLength];
1563 }
1564
1565 -(NSRect) titleRectForBounds:(NSRect)cellFrame
1566 {
1567 NSRect textFrame, imageFrame;
1568
1569
1570 [self determineCellParts:cellFrame imagePart:&imageFrame textPart:&textFrame];
1571 return textFrame;
1572 }
1573
1574 @end
1575
1576 // ============================================================================
1577 // wxCocoaOutlineView
1578 // ============================================================================
1579 @implementation wxCocoaOutlineView
1580
1581 //
1582 // initializers / destructor
1583 //
1584 -(id) init
1585 {
1586 self = [super init];
1587 if (self != nil)
1588 {
1589 currentlyEditedColumn =
1590 currentlyEditedRow = -1;
1591
1592 [self registerForDraggedTypes:[NSArray arrayWithObjects:DataViewPboardType,NSStringPboardType,nil]];
1593 [self setDelegate:self];
1594 [self setDoubleAction:@selector(actionDoubleClick:)];
1595 [self setDraggingSourceOperationMask:NSDragOperationEvery forLocal:NO];
1596 [self setDraggingSourceOperationMask:NSDragOperationEvery forLocal:YES];
1597 [self setTarget:self];
1598 }
1599 return self;
1600 }
1601
1602 //
1603 // access to wxWidget's implementation
1604 //
1605 -(wxCocoaDataViewControl*) implementation
1606 {
1607 return implementation;
1608 }
1609
1610 -(void) setImplementation:(wxCocoaDataViewControl*) newImplementation
1611 {
1612 implementation = newImplementation;
1613 }
1614
1615 //
1616 // actions
1617 //
1618 -(void) actionDoubleClick:(id)sender
1619 {
1620 wxUnusedVar(sender);
1621
1622 // actually the documentation (NSTableView 2007-10-31) for doubleAction:
1623 // and setDoubleAction: seems to be wrong as this action message is always
1624 // sent whether the cell is editable or not
1625 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1626
1627 wxDataViewEvent event(wxEVT_DATAVIEW_ITEM_ACTIVATED,dvc->GetId());
1628
1629
1630 event.SetEventObject(dvc);
1631 event.SetItem(wxDataViewItemFromItem([self itemAtRow:[self clickedRow]]));
1632 dvc->GetEventHandler()->ProcessEvent(event);
1633 }
1634
1635
1636 //
1637 // contextual menus
1638 //
1639 -(NSMenu*) menuForEvent:(NSEvent*)theEvent
1640 {
1641 wxUnusedVar(theEvent);
1642
1643 // this method does not do any special menu event handling but only sends
1644 // an event message; therefore, the user has full control if a context
1645 // menu should be shown or not
1646 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1647
1648 wxDataViewEvent event(wxEVT_DATAVIEW_ITEM_CONTEXT_MENU,dvc->GetId());
1649
1650 wxDataViewItemArray selectedItems;
1651
1652
1653 event.SetEventObject(dvc);
1654 event.SetModel(dvc->GetModel());
1655 // get the item information;
1656 // theoretically more than one ID can be returned but the event can only
1657 // handle one item, therefore only the first item of the array is
1658 // returned:
1659 if (dvc->GetSelections(selectedItems) > 0)
1660 event.SetItem(selectedItems[0]);
1661 dvc->GetEventHandler()->ProcessEvent(event);
1662 // nothing is done:
1663 return nil;
1664 }
1665
1666 //
1667 // delegate methods
1668 //
1669 -(void) outlineView:(NSOutlineView*)outlineView mouseDownInHeaderOfTableColumn:(NSTableColumn*)tableColumn
1670 {
1671 wxDataViewColumn* const
1672 col([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
1673
1674 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1675
1676 wxDataViewEvent
1677 event(wxEVT_DATAVIEW_COLUMN_HEADER_CLICK,dvc->GetId());
1678
1679
1680 // first, send an event that the user clicked into a column's header:
1681 event.SetEventObject(dvc);
1682 event.SetColumn(dvc->GetColumnPosition(col));
1683 event.SetDataViewColumn(col);
1684 dvc->HandleWindowEvent(event);
1685
1686 // now, check if the click may have had an influence on sorting, too;
1687 // the sorting setup has to be done only if the clicked table column is
1688 // sortable and has not been used for sorting before the click; if the
1689 // column is already responsible for sorting the native control changes
1690 // the sorting direction automatically and informs the data source via
1691 // outlineView:sortDescriptorsDidChange:
1692 if (col->IsSortable() && ([tableColumn sortDescriptorPrototype] == nil))
1693 {
1694 // remove the sort order from the previously sorted column table (it
1695 // can also be that no sorted column table exists):
1696 UInt32 const noOfColumns = [outlineView numberOfColumns];
1697
1698 for (UInt32 i=0; i<noOfColumns; ++i)
1699 [[[outlineView tableColumns] objectAtIndex:i] setSortDescriptorPrototype:nil];
1700 // make column table sortable:
1701 NSArray* sortDescriptors;
1702 NSSortDescriptor* sortDescriptor;
1703
1704 sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[NSString stringWithFormat:@"%d",[outlineView columnWithIdentifier:[tableColumn identifier]]]
1705 ascending:YES];
1706 sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
1707 [tableColumn setSortDescriptorPrototype:sortDescriptor];
1708 [outlineView setSortDescriptors:sortDescriptors];
1709 [sortDescriptor release];
1710 }
1711 }
1712
1713 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldCollapseItem:(id)item
1714 {
1715 wxUnusedVar(outlineView);
1716
1717 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1718
1719 wxDataViewEvent event(wxEVT_DATAVIEW_ITEM_COLLAPSING,dvc->GetId());
1720
1721
1722 event.SetEventObject(dvc);
1723 event.SetItem (wxDataViewItemFromItem(item));
1724 event.SetModel (dvc->GetModel());
1725 // finally send the equivalent wxWidget event:
1726 dvc->GetEventHandler()->ProcessEvent(event);
1727 // opening the container is allowed if not vetoed:
1728 return event.IsAllowed();
1729 }
1730
1731 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldExpandItem:(id)item
1732 {
1733 wxUnusedVar(outlineView);
1734
1735 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1736
1737 wxDataViewEvent event(wxEVT_DATAVIEW_ITEM_EXPANDING,dvc->GetId());
1738
1739
1740 event.SetEventObject(dvc);
1741 event.SetItem (wxDataViewItemFromItem(item));
1742 event.SetModel (dvc->GetModel());
1743 // finally send the equivalent wxWidget event:
1744 dvc->GetEventHandler()->ProcessEvent(event);
1745 // opening the container is allowed if not vetoed:
1746 return event.IsAllowed();
1747 }
1748
1749 -(BOOL) outlineView:(NSOutlineView*)outlineView shouldSelectTableColumn:(NSTableColumn*)tableColumn
1750 {
1751 wxUnusedVar(tableColumn);
1752 wxUnusedVar(outlineView);
1753
1754 return NO;
1755 }
1756
1757 -(void) outlineView:(wxCocoaOutlineView*)outlineView
1758 willDisplayCell:(id)cell
1759 forTableColumn:(NSTableColumn*)tableColumn
1760 item:(id)item
1761 {
1762 wxUnusedVar(outlineView);
1763
1764 wxDataViewCtrl * const dvc = implementation->GetDataViewCtrl();
1765 wxDataViewModel * const model = dvc->GetModel();
1766
1767 wxDataViewColumn* const
1768 dvCol([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
1769 const unsigned colIdx = dvCol->GetModelColumn();
1770
1771 wxDataViewItem dvItem(wxDataViewItemFromItem(item));
1772
1773 if ( !model->HasValue(dvItem, colIdx) )
1774 return;
1775
1776 wxDataViewRenderer * const renderer = dvCol->GetRenderer();
1777 wxDataViewRendererNativeData * const data = renderer->GetNativeData();
1778
1779 // let the renderer know about what it's going to render next
1780 data->SetColumnPtr(tableColumn);
1781 data->SetItem(item);
1782 data->SetItemCell(cell);
1783
1784 // use the attributes: notice that we need to do this whether we have them
1785 // or not as even if this cell doesn't have any attributes, the previous
1786 // one might have had some and then we need to reset them back to default
1787 wxDataViewItemAttr attr;
1788 model->GetAttr(dvItem, colIdx, attr);
1789 renderer->OSXApplyAttr(attr);
1790
1791 // set the state (enabled/disabled) of the item
1792 renderer->OSXApplyEnabled(model->IsEnabled(dvItem, colIdx));
1793
1794 // and finally do draw it
1795 renderer->MacRender();
1796 }
1797
1798 //
1799 // notifications
1800 //
1801 -(void) outlineViewColumnDidMove:(NSNotification*)notification
1802 {
1803 int const newColumnPosition = [[[notification userInfo] objectForKey:@"NSNewColumn"] intValue];
1804
1805 NSTableColumn*
1806 tableColumn = [[self tableColumns] objectAtIndex:newColumnPosition];
1807 wxDataViewColumn* const
1808 col([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
1809
1810 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1811
1812 wxDataViewEvent event(wxEVT_DATAVIEW_COLUMN_REORDERED,dvc->GetId());
1813
1814
1815 event.SetEventObject(dvc);
1816 event.SetColumn(dvc->GetColumnPosition(col));
1817 event.SetDataViewColumn(col);
1818 dvc->GetEventHandler()->ProcessEvent(event);
1819 }
1820
1821 -(void) outlineViewItemDidCollapse:(NSNotification*)notification
1822 {
1823 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1824
1825 wxDataViewEvent event(wxEVT_DATAVIEW_ITEM_COLLAPSED,dvc->GetId());
1826
1827
1828 event.SetEventObject(dvc);
1829 event.SetItem(wxDataViewItemFromItem(
1830 [[notification userInfo] objectForKey:@"NSObject"]));
1831 dvc->GetEventHandler()->ProcessEvent(event);
1832 }
1833
1834 -(void) outlineViewItemDidExpand:(NSNotification*)notification
1835 {
1836 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1837
1838 wxDataViewEvent event(wxEVT_DATAVIEW_ITEM_EXPANDED,dvc->GetId());
1839
1840
1841 event.SetEventObject(dvc);
1842 event.SetItem(wxDataViewItemFromItem(
1843 [[notification userInfo] objectForKey:@"NSObject"]));
1844 dvc->GetEventHandler()->ProcessEvent(event);
1845 }
1846
1847 -(void) outlineViewSelectionDidChange:(NSNotification*)notification
1848 {
1849 wxUnusedVar(notification);
1850
1851 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1852
1853 wxDataViewEvent event(wxEVT_DATAVIEW_SELECTION_CHANGED,dvc->GetId());
1854
1855 event.SetEventObject(dvc);
1856 event.SetModel(dvc->GetModel());
1857 event.SetItem(dvc->GetSelection());
1858 dvc->GetEventHandler()->ProcessEvent(event);
1859 }
1860
1861 -(void) textDidBeginEditing:(NSNotification*)notification
1862 {
1863 // this notification is only sent if the user started modifying the cell
1864 // (not when the user clicked into the cell and the cell's editor is
1865 // called!)
1866
1867 // call method of superclass (otherwise editing does not work correctly -
1868 // the outline data source class is not informed about a change of data):
1869 [super textDidBeginEditing:notification];
1870
1871 // remember the column being edited, it will be used in textDidEndEditing:
1872 currentlyEditedColumn = [self editedColumn];
1873 currentlyEditedRow = [self editedRow];
1874
1875 NSTableColumn*
1876 tableColumn = [[self tableColumns] objectAtIndex:currentlyEditedColumn];
1877 wxDataViewColumn* const
1878 col([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
1879
1880 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1881
1882
1883 // stop editing of a custom item first (if necessary)
1884 dvc->FinishCustomItemEditing();
1885
1886 // now, send the event:
1887 wxDataViewEvent
1888 event(wxEVT_DATAVIEW_ITEM_EDITING_STARTED,dvc->GetId());
1889
1890 event.SetEventObject(dvc);
1891 event.SetItem(
1892 wxDataViewItemFromItem([self itemAtRow:currentlyEditedRow]));
1893 event.SetColumn(dvc->GetColumnPosition(col));
1894 event.SetDataViewColumn(col);
1895 dvc->GetEventHandler()->ProcessEvent(event);
1896 }
1897
1898 -(void) textDidEndEditing:(NSNotification*)notification
1899 {
1900 // call method of superclass (otherwise editing does not work correctly -
1901 // the outline data source class is not informed about a change of data):
1902 [super textDidEndEditing:notification];
1903
1904 // under OSX an event indicating the end of an editing session can be sent
1905 // even if no event indicating a start of an editing session has been sent
1906 // (see Documentation for NSControl controlTextDidEndEditing:); this is
1907 // not expected by a user of the wxWidgets library and therefore an
1908 // wxEVT_DATAVIEW_ITEM_EDITING_DONE event is only sent if a
1909 // corresponding wxEVT_DATAVIEW_ITEM_EDITING_STARTED has been sent
1910 // before; to check if a wxEVT_DATAVIEW_ITEM_EDITING_STARTED has
1911 // been sent the last edited column/row are valid:
1912 if ( currentlyEditedColumn != -1 && currentlyEditedRow != -1 )
1913 {
1914 NSTableColumn*
1915 tableColumn = [[self tableColumns] objectAtIndex:currentlyEditedColumn];
1916 wxDataViewColumn* const
1917 col([static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer]);
1918
1919 wxDataViewCtrl* const dvc = implementation->GetDataViewCtrl();
1920
1921 // send event to wxWidgets:
1922 wxDataViewEvent
1923 event(wxEVT_DATAVIEW_ITEM_EDITING_DONE,dvc->GetId());
1924
1925 event.SetEventObject(dvc);
1926 event.SetItem(
1927 wxDataViewItemFromItem([self itemAtRow:currentlyEditedRow]));
1928 event.SetColumn(dvc->GetColumnPosition(col));
1929 event.SetDataViewColumn(col);
1930 dvc->GetEventHandler()->ProcessEvent(event);
1931
1932
1933 // we're not editing any more
1934 currentlyEditedColumn =
1935 currentlyEditedRow = -1;
1936 }
1937 }
1938
1939 @end
1940
1941 // ============================================================================
1942 // wxCocoaDataViewControl
1943 // ============================================================================
1944
1945 wxCocoaDataViewControl::wxCocoaDataViewControl(wxWindow* peer,
1946 const wxPoint& pos,
1947 const wxSize& size,
1948 long style)
1949 : wxWidgetCocoaImpl
1950 (
1951 peer,
1952 [[NSScrollView alloc] initWithFrame:wxOSXGetFrameForControl(peer,pos,size)]
1953 ),
1954 m_DataSource(NULL),
1955 m_OutlineView([[wxCocoaOutlineView alloc] init])
1956 {
1957 // initialize scrollview (the outline view is part of a scrollview):
1958 NSScrollView* scrollview = (NSScrollView*) GetWXWidget();
1959
1960 [scrollview setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable];
1961 [scrollview setBorderType:NSNoBorder];
1962 [scrollview setHasVerticalScroller:YES];
1963 [scrollview setHasHorizontalScroller:YES];
1964 [scrollview setAutohidesScrollers:YES];
1965 [scrollview setDocumentView:m_OutlineView];
1966
1967 // initialize the native control itself too
1968 InitOutlineView(style);
1969 }
1970
1971 void wxCocoaDataViewControl::InitOutlineView(long style)
1972 {
1973 [m_OutlineView setImplementation:this];
1974 [m_OutlineView setColumnAutoresizingStyle:NSTableViewSequentialColumnAutoresizingStyle];
1975 [m_OutlineView setIndentationPerLevel:GetDataViewCtrl()->GetIndent()];
1976 NSUInteger maskGridStyle(NSTableViewGridNone);
1977 if (style & wxDV_HORIZ_RULES)
1978 maskGridStyle |= NSTableViewSolidHorizontalGridLineMask;
1979 if (style & wxDV_VERT_RULES)
1980 maskGridStyle |= NSTableViewSolidVerticalGridLineMask;
1981 [m_OutlineView setGridStyleMask:maskGridStyle];
1982 [m_OutlineView setAllowsMultipleSelection: (style & wxDV_MULTIPLE) != 0];
1983 [m_OutlineView setUsesAlternatingRowBackgroundColors:(style & wxDV_ROW_LINES) != 0];
1984
1985 if ( style & wxDV_NO_HEADER )
1986 [m_OutlineView setHeaderView:nil];
1987 }
1988
1989 wxCocoaDataViewControl::~wxCocoaDataViewControl()
1990 {
1991 [m_DataSource release];
1992 [m_OutlineView release];
1993 }
1994
1995 //
1996 // column related methods (inherited from wxDataViewWidgetImpl)
1997 //
1998 bool wxCocoaDataViewControl::ClearColumns()
1999 {
2000 // as there is a bug in NSOutlineView version (OSX 10.5.6 #6555162) the
2001 // columns cannot be deleted if there is an outline column in the view;
2002 // therefore, the whole view is deleted and newly constructed:
2003 [m_OutlineView release];
2004 m_OutlineView = [[wxCocoaOutlineView alloc] init];
2005 [((NSScrollView*) GetWXWidget()) setDocumentView:m_OutlineView];
2006 [m_OutlineView setDataSource:m_DataSource];
2007
2008 InitOutlineView(GetDataViewCtrl()->GetWindowStyle());
2009
2010 return true;
2011 }
2012
2013 bool wxCocoaDataViewControl::DeleteColumn(wxDataViewColumn* columnPtr)
2014 {
2015 if ([m_OutlineView outlineTableColumn] == columnPtr->GetNativeData()->GetNativeColumnPtr())
2016 [m_OutlineView setOutlineTableColumn:nil]; // due to a bug this does not work
2017 [m_OutlineView removeTableColumn:columnPtr->GetNativeData()->GetNativeColumnPtr()]; // due to a confirmed bug #6555162 the deletion does not work for
2018 // outline table columns (... and there is no workaround)
2019 return (([m_OutlineView columnWithIdentifier:[wxDVCNSTableColumn identifierForColumnPointer:columnPtr]]) == -1);
2020 }
2021
2022 void wxCocoaDataViewControl::DoSetExpanderColumn(const wxDataViewColumn *columnPtr)
2023 {
2024 [m_OutlineView setOutlineTableColumn:columnPtr->GetNativeData()->GetNativeColumnPtr()];
2025 }
2026
2027 wxDataViewColumn* wxCocoaDataViewControl::GetColumn(unsigned int pos) const
2028 {
2029 NSTableColumn* tableColumn = [[m_OutlineView tableColumns] objectAtIndex:pos];
2030 return [static_cast<wxDVCNSTableColumn*>(tableColumn) getColumnPointer];
2031 }
2032
2033 int wxCocoaDataViewControl::GetColumnPosition(const wxDataViewColumn *columnPtr) const
2034 {
2035 return [m_OutlineView columnWithIdentifier:[wxDVCNSTableColumn identifierForColumnPointer:columnPtr]];
2036 }
2037
2038 bool wxCocoaDataViewControl::InsertColumn(unsigned int pos, wxDataViewColumn* columnPtr)
2039 {
2040 // create column and set the native data of the dataview column:
2041 NSTableColumn *nativeColumn = ::CreateNativeColumn(columnPtr);
2042 columnPtr->GetNativeData()->SetNativeColumnPtr(nativeColumn);
2043 // as the native control does not allow the insertion of a column at a
2044 // specified position the column is first appended and - if necessary -
2045 // moved to its final position:
2046 [m_OutlineView addTableColumn:nativeColumn];
2047 if (pos != static_cast<unsigned int>([m_OutlineView numberOfColumns]-1))
2048 [m_OutlineView moveColumn:[m_OutlineView numberOfColumns]-1 toColumn:pos];
2049
2050 // set columns width now that it can be computed even for autosized columns:
2051 columnPtr->SetWidth(columnPtr->GetWidthVariable());
2052
2053 // done:
2054 return true;
2055 }
2056
2057 void wxCocoaDataViewControl::FitColumnWidthToContent(unsigned int pos)
2058 {
2059 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
2060 const int count = GetCount();
2061 NSTableColumn *column = GetColumn(pos)->GetNativeData()->GetNativeColumnPtr();
2062
2063 class MaxWidthCalculator
2064 {
2065 public:
2066 MaxWidthCalculator(wxCocoaOutlineView *view,
2067 NSTableColumn *column, unsigned columnIndex)
2068 : m_width(0),
2069 m_view(view),
2070 m_column(columnIndex),
2071 m_indent(0)
2072 {
2073 // account for indentation in the column with expander
2074 if ( column == [m_view outlineTableColumn] )
2075 m_indent = [m_view indentationPerLevel];
2076 }
2077
2078 void UpdateWithWidth(int width)
2079 {
2080 m_width = wxMax(m_width, width);
2081 }
2082
2083 void UpdateWithRow(int row)
2084 {
2085 NSCell *cell = [m_view preparedCellAtColumn:m_column row:row];
2086 unsigned cellWidth = [cell cellSize].width + 1/*round the float up*/;
2087
2088 if ( m_indent )
2089 cellWidth += m_indent * ([m_view levelForRow:row] + 1);
2090
2091 m_width = wxMax(m_width, cellWidth);
2092 }
2093
2094 int GetMaxWidth() const { return m_width; }
2095
2096 private:
2097 int m_width;
2098 wxCocoaOutlineView *m_view;
2099 unsigned m_column;
2100 int m_indent;
2101 };
2102
2103 MaxWidthCalculator calculator(m_OutlineView, column, pos);
2104
2105 if ( [column headerCell] )
2106 {
2107 calculator.UpdateWithWidth([[column headerCell] cellSize].width + 1/*round the float up*/);
2108 }
2109
2110 // The code below deserves some explanation. For very large controls, we
2111 // simply can't afford to calculate sizes for all items, it takes too
2112 // long. So the best we can do is to check the first and the last N/2
2113 // items in the control for some sufficiently large N and calculate best
2114 // sizes from that. That can result in the calculated best width being too
2115 // small for some outliers, but it's better to get slightly imperfect
2116 // result than to wait several seconds after every update. To avoid highly
2117 // visible miscalculations, we also include all currently visible items
2118 // no matter what. Finally, the value of N is determined dynamically by
2119 // measuring how much time we spent on the determining item widths so far.
2120
2121 #if wxUSE_STOPWATCH
2122 int top_part_end = count;
2123 static const long CALC_TIMEOUT = 20/*ms*/;
2124 // don't call wxStopWatch::Time() too often
2125 static const unsigned CALC_CHECK_FREQ = 100;
2126 wxStopWatch timer;
2127 #else
2128 // use some hard-coded limit, that's the best we can do without timer
2129 int top_part_end = wxMin(500, count);
2130 #endif // wxUSE_STOPWATCH/!wxUSE_STOPWATCH
2131
2132 int row = 0;
2133
2134 for ( row = 0; row < top_part_end; row++ )
2135 {
2136 #if wxUSE_STOPWATCH
2137 if ( row % CALC_CHECK_FREQ == CALC_CHECK_FREQ-1 &&
2138 timer.Time() > CALC_TIMEOUT )
2139 break;
2140 #endif // wxUSE_STOPWATCH
2141 calculator.UpdateWithRow(row);
2142 }
2143
2144 // row is the first unmeasured item now; that's our value of N/2
2145
2146 if ( row < count )
2147 {
2148 top_part_end = row;
2149
2150 // add bottom N/2 items now:
2151 const int bottom_part_start = wxMax(row, count - row);
2152 for ( row = bottom_part_start; row < count; row++ )
2153 calculator.UpdateWithRow(row);
2154
2155 // finally, include currently visible items in the calculation:
2156 const NSRange visible = [m_OutlineView rowsInRect:[m_OutlineView visibleRect]];
2157 const int first_visible = wxMax(visible.location, top_part_end);
2158 const int last_visible = wxMin(first_visible + visible.length, bottom_part_start);
2159
2160 for ( row = first_visible; row < last_visible; row++ )
2161 calculator.UpdateWithRow(row);
2162
2163 wxLogTrace("dataview",
2164 "determined best size from %d top, %d bottom plus %d more visible items out of %d total",
2165 top_part_end,
2166 count - bottom_part_start,
2167 wxMax(0, last_visible - first_visible),
2168 count);
2169 }
2170
2171 [column setWidth:calculator.GetMaxWidth()];
2172 #endif // MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
2173 }
2174
2175 //
2176 // item related methods (inherited from wxDataViewWidgetImpl)
2177 //
2178 bool wxCocoaDataViewControl::Add(const wxDataViewItem& parent, const wxDataViewItem& WXUNUSED(item))
2179 {
2180 if (parent.IsOk())
2181 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2182 else
2183 [m_OutlineView reloadData];
2184 return true;
2185 }
2186
2187 bool wxCocoaDataViewControl::Add(const wxDataViewItem& parent, const wxDataViewItemArray& WXUNUSED(items))
2188 {
2189 if (parent.IsOk())
2190 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2191 else
2192 [m_OutlineView reloadData];
2193 return true;
2194 }
2195
2196 void wxCocoaDataViewControl::Collapse(const wxDataViewItem& item)
2197 {
2198 [m_OutlineView collapseItem:[m_DataSource getDataViewItemFromBuffer:item]];
2199 }
2200
2201 void wxCocoaDataViewControl::EnsureVisible(const wxDataViewItem& item, const wxDataViewColumn *columnPtr)
2202 {
2203 if (item.IsOk())
2204 {
2205 [m_OutlineView scrollRowToVisible:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2206 if (columnPtr)
2207 [m_OutlineView scrollColumnToVisible:GetColumnPosition(columnPtr)];
2208 }
2209 }
2210
2211 void wxCocoaDataViewControl::Expand(const wxDataViewItem& item)
2212 {
2213 [m_OutlineView expandItem:[m_DataSource getDataViewItemFromBuffer:item]];
2214 }
2215
2216 unsigned int wxCocoaDataViewControl::GetCount() const
2217 {
2218 return [m_OutlineView numberOfRows];
2219 }
2220
2221 wxRect wxCocoaDataViewControl::GetRectangle(const wxDataViewItem& item, const wxDataViewColumn *columnPtr)
2222 {
2223 return wxFromNSRect([m_osxView superview],[m_OutlineView frameOfCellAtColumn:GetColumnPosition(columnPtr)
2224 row:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]]);
2225 }
2226
2227 bool wxCocoaDataViewControl::IsExpanded(const wxDataViewItem& item) const
2228 {
2229 return [m_OutlineView isItemExpanded:[m_DataSource getDataViewItemFromBuffer:item]];
2230 }
2231
2232 bool wxCocoaDataViewControl::Reload()
2233 {
2234 [m_DataSource clearBuffers];
2235 [m_OutlineView reloadData];
2236 [m_OutlineView scrollColumnToVisible:0];
2237 [m_OutlineView scrollRowToVisible:0];
2238 return true;
2239 }
2240
2241 bool wxCocoaDataViewControl::Remove(const wxDataViewItem& parent, const wxDataViewItem& WXUNUSED(item))
2242 {
2243 if (parent.IsOk())
2244 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2245 else
2246 [m_OutlineView reloadData];
2247 return true;
2248 }
2249
2250 bool wxCocoaDataViewControl::Remove(const wxDataViewItem& parent, const wxDataViewItemArray& WXUNUSED(item))
2251 {
2252 if (parent.IsOk())
2253 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:parent] reloadChildren:YES];
2254 else
2255 [m_OutlineView reloadData];
2256 return true;
2257 }
2258
2259 bool wxCocoaDataViewControl::Update(const wxDataViewColumn *columnPtr)
2260 {
2261 wxUnusedVar(columnPtr);
2262
2263 return false;
2264 }
2265
2266 bool wxCocoaDataViewControl::Update(const wxDataViewItem& WXUNUSED(parent), const wxDataViewItem& item)
2267 {
2268 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:item]];
2269 return true;
2270 }
2271
2272 bool wxCocoaDataViewControl::Update(const wxDataViewItem& WXUNUSED(parent), const wxDataViewItemArray& items)
2273 {
2274 for (size_t i=0; i<items.GetCount(); ++i)
2275 [m_OutlineView reloadItem:[m_DataSource getDataViewItemFromBuffer:items[i]]];
2276 return true;
2277 }
2278
2279 //
2280 // model related methods
2281 //
2282 bool wxCocoaDataViewControl::AssociateModel(wxDataViewModel* model)
2283 {
2284 [m_DataSource release];
2285 if (model)
2286 {
2287 m_DataSource = [[wxCocoaOutlineDataSource alloc] init];
2288 [m_DataSource setImplementation:this];
2289 [m_DataSource setModel:model];
2290 }
2291 else
2292 m_DataSource = NULL;
2293 [m_OutlineView setDataSource:m_DataSource]; // if there is a data source the data is immediately going to be requested
2294 return true;
2295 }
2296
2297 //
2298 // selection related methods (inherited from wxDataViewWidgetImpl)
2299 //
2300
2301 wxDataViewItem wxCocoaDataViewControl::GetCurrentItem() const
2302 {
2303 return wxDataViewItem([[m_OutlineView itemAtRow:[m_OutlineView selectedRow]] pointer]);
2304 }
2305
2306 wxDataViewColumn *wxCocoaDataViewControl::GetCurrentColumn() const
2307 {
2308 int col = [m_OutlineView selectedColumn];
2309 if ( col == -1 )
2310 return NULL;
2311 return GetColumn(col);
2312 }
2313
2314 void wxCocoaDataViewControl::SetCurrentItem(const wxDataViewItem& item)
2315 {
2316 // We can't have unselected current item in a NSTableView, as the
2317 // documentation of its deselectRow method explains, the control will
2318 // automatically change the current item to the closest still selected item
2319 // if the current item is deselected. So we have no choice but to select
2320 // the item in the same time as making it current.
2321 Select(item);
2322 }
2323
2324 int wxCocoaDataViewControl::GetSelectedItemsCount() const
2325 {
2326 return [m_OutlineView numberOfSelectedRows];
2327 }
2328
2329 int wxCocoaDataViewControl::GetSelections(wxDataViewItemArray& sel) const
2330 {
2331 NSIndexSet* selectedRowIndexes([m_OutlineView selectedRowIndexes]);
2332
2333 NSUInteger indexRow;
2334
2335
2336 sel.Empty();
2337 sel.Alloc([selectedRowIndexes count]);
2338 indexRow = [selectedRowIndexes firstIndex];
2339 while (indexRow != NSNotFound)
2340 {
2341 sel.Add(wxDataViewItem([[m_OutlineView itemAtRow:indexRow] pointer]));
2342 indexRow = [selectedRowIndexes indexGreaterThanIndex:indexRow];
2343 }
2344 return sel.GetCount();
2345 }
2346
2347 bool wxCocoaDataViewControl::IsSelected(const wxDataViewItem& item) const
2348 {
2349 return [m_OutlineView isRowSelected:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2350 }
2351
2352 void wxCocoaDataViewControl::Select(const wxDataViewItem& item)
2353 {
2354 if (item.IsOk())
2355 [m_OutlineView selectRowIndexes:[NSIndexSet indexSetWithIndex:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]]
2356 byExtendingSelection:GetDataViewCtrl()->HasFlag(wxDV_MULTIPLE) ? YES : NO];
2357 }
2358
2359 void wxCocoaDataViewControl::SelectAll()
2360 {
2361 [m_OutlineView selectAll:m_OutlineView];
2362 }
2363
2364 void wxCocoaDataViewControl::Unselect(const wxDataViewItem& item)
2365 {
2366 if (item.IsOk())
2367 [m_OutlineView deselectRow:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]]];
2368 }
2369
2370 void wxCocoaDataViewControl::UnselectAll()
2371 {
2372 [m_OutlineView deselectAll:m_OutlineView];
2373 }
2374
2375 //
2376 // sorting related methods
2377 //
2378 wxDataViewColumn* wxCocoaDataViewControl::GetSortingColumn() const
2379 {
2380 NSArray* const columns = [m_OutlineView tableColumns];
2381
2382 UInt32 const noOfColumns = [columns count];
2383
2384
2385 for (UInt32 i=0; i<noOfColumns; ++i)
2386 if ([[columns objectAtIndex:i] sortDescriptorPrototype] != nil)
2387 return GetColumn(i);
2388 return NULL;
2389 }
2390
2391 void wxCocoaDataViewControl::Resort()
2392 {
2393 [m_DataSource clearChildren];
2394 [m_OutlineView reloadData];
2395 }
2396
2397 void wxCocoaDataViewControl::StartEditor( const wxDataViewItem & item, unsigned int column )
2398 {
2399 [m_OutlineView editColumn:column row:[m_OutlineView rowForItem:[m_DataSource getDataViewItemFromBuffer:item]] withEvent:nil select:YES];
2400 }
2401
2402 //
2403 // other methods (inherited from wxDataViewWidgetImpl)
2404 //
2405 void wxCocoaDataViewControl::DoSetIndent(int indent)
2406 {
2407 [m_OutlineView setIndentationPerLevel:static_cast<CGFloat>(indent)];
2408 }
2409
2410 void wxCocoaDataViewControl::HitTest(const wxPoint& point, wxDataViewItem& item, wxDataViewColumn*& columnPtr) const
2411 {
2412 NSPoint const nativePoint = wxToNSPoint((NSScrollView*) GetWXWidget(),point);
2413
2414 int indexColumn;
2415 int indexRow;
2416
2417
2418 indexColumn = [m_OutlineView columnAtPoint:nativePoint];
2419 indexRow = [m_OutlineView rowAtPoint: nativePoint];
2420 if ((indexColumn >= 0) && (indexRow >= 0))
2421 {
2422 columnPtr = GetColumn(indexColumn);
2423 item = wxDataViewItem([[m_OutlineView itemAtRow:indexRow] pointer]);
2424 }
2425 else
2426 {
2427 columnPtr = NULL;
2428 item = wxDataViewItem();
2429 }
2430 }
2431
2432 void wxCocoaDataViewControl::SetRowHeight(const wxDataViewItem& WXUNUSED(item), unsigned int WXUNUSED(height))
2433 // Not supported by the native control
2434 {
2435 }
2436
2437 void wxCocoaDataViewControl::OnSize()
2438 {
2439 if ([m_OutlineView numberOfColumns] == 1)
2440 [m_OutlineView sizeLastColumnToFit];
2441 }
2442
2443 //
2444 // drag & drop helper methods
2445 //
2446 wxDataFormat wxCocoaDataViewControl::GetDnDDataFormat(wxDataObjectComposite* dataObjects)
2447 {
2448 wxDataFormat resultFormat;
2449 if ( !dataObjects )
2450 return resultFormat;
2451
2452 bool compatible(true);
2453
2454 size_t const noOfFormats = dataObjects->GetFormatCount();
2455 size_t indexFormat;
2456
2457 wxDataFormat* formats;
2458
2459 // get all formats and check afterwards if the formats are compatible; if
2460 // they are compatible the preferred format is returned otherwise
2461 // wxDF_INVALID is returned;
2462 // currently compatible types (ordered by priority are):
2463 // - wxDF_UNICODETEXT - wxDF_TEXT
2464 formats = new wxDataFormat[noOfFormats];
2465 dataObjects->GetAllFormats(formats);
2466 indexFormat = 0;
2467 while ((indexFormat < noOfFormats) && compatible)
2468 {
2469 switch (resultFormat.GetType())
2470 {
2471 case wxDF_INVALID:
2472 resultFormat.SetType(formats[indexFormat].GetType()); // first format (should only be reached if indexFormat == 0)
2473 break;
2474 case wxDF_TEXT:
2475 if (formats[indexFormat].GetType() == wxDF_UNICODETEXT)
2476 resultFormat.SetType(wxDF_UNICODETEXT);
2477 else // incompatible
2478 {
2479 resultFormat.SetType(wxDF_INVALID);
2480 compatible = false;
2481 }
2482 break;
2483 case wxDF_UNICODETEXT:
2484 if (formats[indexFormat].GetType() != wxDF_TEXT)
2485 {
2486 resultFormat.SetType(wxDF_INVALID);
2487 compatible = false;
2488 }
2489 break;
2490 default:
2491 resultFormat.SetType(wxDF_INVALID); // not (yet) supported format
2492 compatible = false;
2493 }
2494 ++indexFormat;
2495 }
2496
2497 delete[] formats;
2498
2499 return resultFormat;
2500 }
2501
2502 wxDataObjectComposite* wxCocoaDataViewControl::GetDnDDataObjects(NSData* dataObject) const
2503 {
2504 wxDataFormatId dataFormatID;
2505
2506
2507 [dataObject getBytes:&dataFormatID length:sizeof(wxDataFormatId)];
2508 switch (dataFormatID)
2509 {
2510 case wxDF_TEXT:
2511 case wxDF_UNICODETEXT:
2512 {
2513 wxTextDataObject* textDataObject(new wxTextDataObject());
2514
2515 if (textDataObject->SetData(wxDataFormat(dataFormatID),[dataObject length]-sizeof(wxDataFormatId),static_cast<char const*>([dataObject bytes])+sizeof(wxDataFormatId)))
2516 {
2517 wxDataObjectComposite* dataObjectComposite(new wxDataObjectComposite());
2518
2519 dataObjectComposite->Add(textDataObject);
2520 return dataObjectComposite;
2521 }
2522 else
2523 {
2524 delete textDataObject;
2525 return NULL;
2526 }
2527 }
2528 break;
2529 default:
2530 return NULL;
2531 }
2532 }
2533
2534 id wxCocoaDataViewControl::GetItemAtRow(int row) const
2535 {
2536 return [m_OutlineView itemAtRow:row];
2537 }
2538
2539 // ----------------------------------------------------------------------------
2540 // wxDataViewRendererNativeData
2541 // ----------------------------------------------------------------------------
2542
2543 void wxDataViewRendererNativeData::Init()
2544 {
2545 m_origFont = NULL;
2546 m_origTextColour = NULL;
2547 m_ellipsizeMode = wxELLIPSIZE_MIDDLE;
2548
2549 if ( m_ColumnCell )
2550 ApplyLineBreakMode(m_ColumnCell);
2551 }
2552
2553 void wxDataViewRendererNativeData::ApplyLineBreakMode(NSCell *cell)
2554 {
2555 NSLineBreakMode nsMode = NSLineBreakByWordWrapping;
2556 switch ( m_ellipsizeMode )
2557 {
2558 case wxELLIPSIZE_NONE:
2559 nsMode = NSLineBreakByClipping;
2560 break;
2561
2562 case wxELLIPSIZE_START:
2563 nsMode = NSLineBreakByTruncatingHead;
2564 break;
2565
2566 case wxELLIPSIZE_MIDDLE:
2567 nsMode = NSLineBreakByTruncatingMiddle;
2568 break;
2569
2570 case wxELLIPSIZE_END:
2571 nsMode = NSLineBreakByTruncatingTail;
2572 break;
2573 }
2574
2575 wxASSERT_MSG( nsMode != NSLineBreakByWordWrapping, "unknown wxEllipsizeMode" );
2576
2577 [cell setLineBreakMode: nsMode];
2578 }
2579
2580 // ---------------------------------------------------------
2581 // wxDataViewRenderer
2582 // ---------------------------------------------------------
2583
2584 wxDataViewRenderer::wxDataViewRenderer(const wxString& varianttype,
2585 wxDataViewCellMode mode,
2586 int align)
2587 : wxDataViewRendererBase(varianttype, mode, align),
2588 m_alignment(align),
2589 m_mode(mode),
2590 m_NativeDataPtr(NULL)
2591 {
2592 }
2593
2594 wxDataViewRenderer::~wxDataViewRenderer()
2595 {
2596 delete m_NativeDataPtr;
2597 }
2598
2599 void wxDataViewRenderer::SetAlignment(int align)
2600 {
2601 m_alignment = align;
2602 [GetNativeData()->GetColumnCell() setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2603 }
2604
2605 void wxDataViewRenderer::SetMode(wxDataViewCellMode mode)
2606 {
2607 m_mode = mode;
2608 if ( GetOwner() )
2609 [GetOwner()->GetNativeData()->GetNativeColumnPtr() setEditable:(mode == wxDATAVIEW_CELL_EDITABLE)];
2610 }
2611
2612 void wxDataViewRenderer::SetNativeData(wxDataViewRendererNativeData* newNativeDataPtr)
2613 {
2614 delete m_NativeDataPtr;
2615 m_NativeDataPtr = newNativeDataPtr;
2616 }
2617
2618 void wxDataViewRenderer::EnableEllipsize(wxEllipsizeMode mode)
2619 {
2620 // we need to store this value to apply it to the columns headerCell in
2621 // CreateNativeColumn()
2622 GetNativeData()->SetEllipsizeMode(mode);
2623
2624 // but we may already apply it to the column cell which will be used for
2625 // this column
2626 GetNativeData()->ApplyLineBreakMode(GetNativeData()->GetColumnCell());
2627 }
2628
2629 wxEllipsizeMode wxDataViewRenderer::GetEllipsizeMode() const
2630 {
2631 return GetNativeData()->GetEllipsizeMode();
2632 }
2633
2634 void
2635 wxDataViewRenderer::OSXOnCellChanged(NSObject *object,
2636 const wxDataViewItem& item,
2637 unsigned col)
2638 {
2639 // TODO: This code should really be removed and this function be made pure
2640 // virtual. We just need to decide what to do with custom renderers
2641 // (i.e. wxDataViewCustomRenderer), currently OS X "in place" editing
2642 // which doesn't really create an editor control is not compatible
2643 // with the in place editing under other platforms.
2644
2645 wxVariant value;
2646 if ( [object isKindOfClass:[NSString class]] )
2647 value = ObjectToString(object);
2648 else if ( [object isKindOfClass:[NSNumber class]] )
2649 value = ObjectToLong(object);
2650 else if ( [object isKindOfClass:[NSDate class]] )
2651 value = ObjectToDate(object);
2652 else
2653 {
2654 wxFAIL_MSG( wxString::Format
2655 (
2656 "unknown value type %s",
2657 wxCFStringRef::AsString([object className])
2658 ));
2659 return;
2660 }
2661
2662 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2663 model->ChangeValue(value, item, col);
2664 }
2665
2666 void wxDataViewRenderer::OSXApplyAttr(const wxDataViewItemAttr& attr)
2667 {
2668 wxDataViewRendererNativeData * const data = GetNativeData();
2669 NSCell * const cell = data->GetItemCell();
2670
2671 // set the font and text colour to use: we need to do it if we had ever
2672 // changed them before, even if this item itself doesn't have any special
2673 // attributes as otherwise it would reuse the attributes from the previous
2674 // cell rendered using the same renderer
2675 NSFont *font = NULL;
2676 NSColor *colText = NULL;
2677
2678 if ( attr.HasFont() )
2679 {
2680 font = data->GetOriginalFont();
2681 if ( !font )
2682 {
2683 // this is the first time we're setting the font, remember the
2684 // original one before changing it
2685 font = [cell font];
2686 data->SaveOriginalFont(font);
2687 }
2688
2689 if ( font )
2690 {
2691 // FIXME: using wxFont methods here doesn't work for some reason
2692 NSFontManager * const fm = [NSFontManager sharedFontManager];
2693 if ( attr.GetBold() )
2694 font = [fm convertFont:font toHaveTrait:NSBoldFontMask];
2695 if ( attr.GetItalic() )
2696 font = [fm convertFont:font toHaveTrait:NSItalicFontMask];
2697 }
2698 //else: can't change font if the cell doesn't have any
2699 }
2700
2701 if ( attr.HasColour() )
2702 {
2703 // we can set font for any cell but only NSTextFieldCell provides
2704 // a method for setting text colour so check that this method is
2705 // available before using it
2706 if ( [cell respondsToSelector:@selector(setTextColor:)] &&
2707 [cell respondsToSelector:@selector(textColor)] )
2708 {
2709 if ( !data->GetOriginalTextColour() )
2710 {
2711 // the cast to (untyped) id is safe because of the check above
2712 data->SaveOriginalTextColour([(id)cell textColor]);
2713 }
2714
2715 const wxColour& c = attr.GetColour();
2716 colText = [NSColor colorWithCalibratedRed:c.Red() / 255.
2717 green:c.Green() / 255.
2718 blue:c.Blue() / 255.
2719 alpha:c.Alpha() / 255.];
2720 }
2721 }
2722
2723 if ( !font )
2724 font = data->GetOriginalFont();
2725 if ( !colText )
2726 colText = data->GetOriginalTextColour();
2727
2728 if ( font )
2729 [cell setFont:font];
2730
2731 if ( colText )
2732 [(id)cell setTextColor:colText];
2733 }
2734
2735 void wxDataViewRenderer::OSXApplyEnabled(bool enabled)
2736 {
2737 [GetNativeData()->GetItemCell() setEnabled:enabled];
2738 }
2739
2740 IMPLEMENT_ABSTRACT_CLASS(wxDataViewRenderer,wxDataViewRendererBase)
2741
2742 // ---------------------------------------------------------
2743 // wxDataViewCustomRenderer
2744 // ---------------------------------------------------------
2745 wxDataViewCustomRenderer::wxDataViewCustomRenderer(const wxString& varianttype,
2746 wxDataViewCellMode mode,
2747 int align)
2748 : wxDataViewCustomRendererBase(varianttype, mode, align),
2749 m_editorCtrlPtr(NULL),
2750 m_DCPtr(NULL)
2751 {
2752 SetNativeData(new wxDataViewRendererNativeData([[wxCustomCell alloc] init]));
2753 }
2754
2755 bool wxDataViewCustomRenderer::MacRender()
2756 {
2757 [GetNativeData()->GetItemCell() setObjectValue:[[[wxCustomRendererObject alloc] initWithRenderer:this] autorelease]];
2758 return true;
2759 }
2760
2761 void wxDataViewCustomRenderer::OSXApplyAttr(const wxDataViewItemAttr& attr)
2762 {
2763 // simply save the attribute so that it could be reused from our Render()
2764 SetAttr(attr);
2765
2766 // it's not necessary to call the base class version which sets the cell
2767 // properties to correspond to this attribute because we currently don't
2768 // use any NSCell methods in custom renderers anyhow but if we ever start
2769 // doing this (e.g. override RenderText() here to use NSTextFieldCell
2770 // methods), then we should pass it on to wxDataViewRenderer here
2771 }
2772
2773 IMPLEMENT_ABSTRACT_CLASS(wxDataViewCustomRenderer, wxDataViewRenderer)
2774
2775 // ---------------------------------------------------------
2776 // wxDataViewTextRenderer
2777 // ---------------------------------------------------------
2778 wxDataViewTextRenderer::wxDataViewTextRenderer(const wxString& varianttype,
2779 wxDataViewCellMode mode,
2780 int align)
2781 : wxDataViewRenderer(varianttype,mode,align)
2782 {
2783 NSTextFieldCell* cell;
2784
2785
2786 cell = [[NSTextFieldCell alloc] init];
2787 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
2788 SetNativeData(new wxDataViewRendererNativeData(cell));
2789 [cell release];
2790 }
2791
2792 bool wxDataViewTextRenderer::MacRender()
2793 {
2794 if (GetValue().GetType() == GetVariantType())
2795 {
2796 [GetNativeData()->GetItemCell() setObjectValue:wxCFStringRef(GetValue().GetString()).AsNSString()];
2797 return true;
2798 }
2799 else
2800 {
2801 wxFAIL_MSG(wxString("Text renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2802 return false;
2803 }
2804 }
2805
2806 void
2807 wxDataViewTextRenderer::OSXOnCellChanged(NSObject *value,
2808 const wxDataViewItem& item,
2809 unsigned col)
2810 {
2811 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2812 model->ChangeValue(ObjectToString(value), item, col);
2813 }
2814
2815 IMPLEMENT_CLASS(wxDataViewTextRenderer,wxDataViewRenderer)
2816
2817 // ---------------------------------------------------------
2818 // wxDataViewBitmapRenderer
2819 // ---------------------------------------------------------
2820 wxDataViewBitmapRenderer::wxDataViewBitmapRenderer(const wxString& varianttype,
2821 wxDataViewCellMode mode,
2822 int align)
2823 : wxDataViewRenderer(varianttype,mode,align)
2824 {
2825 NSImageCell* cell;
2826
2827
2828 cell = [[NSImageCell alloc] init];
2829 SetNativeData(new wxDataViewRendererNativeData(cell));
2830 [cell release];
2831 }
2832
2833 // This method returns 'true' if
2834 // - the passed bitmap is valid and it could be assigned to the native data
2835 // browser;
2836 // - the passed bitmap is invalid (or is not initialized); this case
2837 // simulates a non-existing bitmap.
2838 // In all other cases the method returns 'false'.
2839 bool wxDataViewBitmapRenderer::MacRender()
2840 {
2841 wxCHECK_MSG(GetValue().GetType() == GetVariantType(),false,wxString("Bitmap renderer cannot render value; value type: ") << GetValue().GetType());
2842
2843 wxBitmap bitmap;
2844
2845 bitmap << GetValue();
2846 if (bitmap.IsOk())
2847 [GetNativeData()->GetItemCell() setObjectValue:[[bitmap.GetNSImage() retain] autorelease]];
2848 return true;
2849 }
2850
2851 IMPLEMENT_CLASS(wxDataViewBitmapRenderer,wxDataViewRenderer)
2852
2853 // -------------------------------------
2854 // wxDataViewChoiceRenderer
2855 // -------------------------------------
2856 wxDataViewChoiceRenderer::wxDataViewChoiceRenderer(const wxArrayString& choices,
2857 wxDataViewCellMode mode,
2858 int alignment)
2859 : wxDataViewRenderer(wxT("string"), mode, alignment),
2860 m_choices(choices)
2861 {
2862 NSPopUpButtonCell* cell;
2863
2864
2865 cell = [[NSPopUpButtonCell alloc] init];
2866 [cell setControlSize:NSMiniControlSize];
2867 [cell setFont:[NSFont fontWithName:[[cell font] fontName] size:[NSFont systemFontSizeForControlSize:NSMiniControlSize]]];
2868 for (size_t i=0; i<choices.GetCount(); ++i)
2869 [cell addItemWithTitle:wxCFStringRef(choices[i]).AsNSString()];
2870 SetNativeData(new wxDataViewRendererNativeData(cell));
2871 [cell release];
2872 }
2873
2874 void
2875 wxDataViewChoiceRenderer::OSXOnCellChanged(NSObject *value,
2876 const wxDataViewItem& item,
2877 unsigned col)
2878 {
2879 // At least under OS X 10.7 we get the index of the item selected and not
2880 // its string.
2881 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2882 model->ChangeValue(GetChoice(ObjectToLong(value)), item, col);
2883 }
2884
2885 bool wxDataViewChoiceRenderer::MacRender()
2886 {
2887 if (GetValue().GetType() == GetVariantType())
2888 {
2889 [((NSPopUpButtonCell*) GetNativeData()->GetItemCell()) selectItemWithTitle:[[wxCFStringRef(GetValue().GetString()).AsNSString() retain] autorelease]];
2890 return true;
2891 }
2892 else
2893 {
2894 wxFAIL_MSG(wxString("Choice renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2895 return false;
2896 }
2897 }
2898
2899 IMPLEMENT_CLASS(wxDataViewChoiceRenderer,wxDataViewRenderer)
2900
2901 // ---------------------------------------------------------
2902 // wxDataViewDateRenderer
2903 // ---------------------------------------------------------
2904
2905 wxDataViewDateRenderer::wxDataViewDateRenderer(const wxString& varianttype,
2906 wxDataViewCellMode mode,
2907 int align)
2908 : wxDataViewRenderer(varianttype,mode,align)
2909 {
2910 NSTextFieldCell* cell;
2911
2912 NSDateFormatter* dateFormatter;
2913
2914
2915 dateFormatter = [[NSDateFormatter alloc] init];
2916 [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
2917 [dateFormatter setDateStyle:NSDateFormatterShortStyle];
2918 cell = [[NSTextFieldCell alloc] init];
2919 [cell setFormatter:dateFormatter];
2920 SetNativeData(new wxDataViewRendererNativeData(cell,[NSDate dateWithString:@"2000-12-30 20:00:00 +0000"]));
2921 [cell release];
2922 [dateFormatter release];
2923 }
2924
2925 bool wxDataViewDateRenderer::MacRender()
2926 {
2927 if (GetValue().GetType() == GetVariantType())
2928 {
2929 if (GetValue().GetDateTime().IsValid())
2930 {
2931 // -- find best fitting style to show the date --
2932 // as the style should be identical for all cells a reference date
2933 // instead of the actual cell's date value is used for all cells;
2934 // this reference date is stored in the renderer's native data
2935 // section for speed purposes; otherwise, the reference date's
2936 // string has to be recalculated for each item that may become
2937 // timewise long if a lot of rows using dates exist; the algorithm
2938 // has the preference to display as much information as possible
2939 // in the first instance; but as this is often impossible due to
2940 // space restrictions the style is shortened per loop; finally, if
2941 // the shortest time and date format does not fit into the cell
2942 // the time part is dropped; remark: the time part itself is not
2943 // modified per iteration loop and only uses the short style,
2944 // means that only the hours and minutes are being shown
2945
2946 // GetObject() returns a date for testing the size of a date object
2947 [GetNativeData()->GetItemCell() setObjectValue:GetNativeData()->GetObject()];
2948 [[GetNativeData()->GetItemCell() formatter] setTimeStyle:NSDateFormatterShortStyle];
2949 for (int dateFormatterStyle=4; dateFormatterStyle>0; --dateFormatterStyle)
2950 {
2951 [[GetNativeData()->GetItemCell() formatter] setDateStyle:(NSDateFormatterStyle)dateFormatterStyle];
2952 if (dateFormatterStyle == 1)
2953 {
2954 // if the shortest style for displaying the date and time
2955 // is too long to be fully visible remove the time part of
2956 // the date:
2957 if ([GetNativeData()->GetItemCell() cellSize].width > [GetNativeData()->GetColumnPtr() width])
2958 [[GetNativeData()->GetItemCell() formatter] setTimeStyle:NSDateFormatterNoStyle];
2959 {
2960 // basically not necessary as the loop would end anyway
2961 // but let's save the last comparison
2962 break;
2963 }
2964 }
2965 else if ([GetNativeData()->GetItemCell() cellSize].width <= [GetNativeData()->GetColumnPtr() width])
2966 break;
2967 }
2968 // set data (the style is set by the previous loop); on OSX the
2969 // date has to be specified with respect to UTC; in wxWidgets the
2970 // date is always entered in the local timezone; so, we have to do
2971 // a conversion from the local to UTC timezone when adding the
2972 // seconds to 1970-01-01 UTC:
2973 [GetNativeData()->GetItemCell() setObjectValue:[NSDate dateWithTimeIntervalSince1970:GetValue().GetDateTime().ToUTC().Subtract(wxDateTime(1,wxDateTime::Jan,1970)).GetSeconds().ToDouble()]];
2974 }
2975 return true;
2976 }
2977 else
2978 {
2979 wxFAIL_MSG(wxString("Date renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
2980 return false;
2981 }
2982 }
2983
2984 void
2985 wxDataViewDateRenderer::OSXOnCellChanged(NSObject *value,
2986 const wxDataViewItem& item,
2987 unsigned col)
2988 {
2989 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
2990 model->ChangeValue(ObjectToDate(value), item, col);
2991 }
2992
2993 IMPLEMENT_ABSTRACT_CLASS(wxDataViewDateRenderer,wxDataViewRenderer)
2994
2995 // ---------------------------------------------------------
2996 // wxDataViewIconTextRenderer
2997 // ---------------------------------------------------------
2998 wxDataViewIconTextRenderer::wxDataViewIconTextRenderer(const wxString& varianttype,
2999 wxDataViewCellMode mode,
3000 int align)
3001 : wxDataViewRenderer(varianttype,mode)
3002 {
3003 wxImageTextCell* cell;
3004
3005
3006 cell = [[wxImageTextCell alloc] init];
3007 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
3008 SetNativeData(new wxDataViewRendererNativeData(cell));
3009 [cell release];
3010 }
3011
3012 bool wxDataViewIconTextRenderer::MacRender()
3013 {
3014 if (GetValue().GetType() == GetVariantType())
3015 {
3016 wxDataViewIconText iconText;
3017
3018 wxImageTextCell* cell;
3019
3020 cell = (wxImageTextCell*) GetNativeData()->GetItemCell();
3021 iconText << GetValue();
3022 if (iconText.GetIcon().IsOk())
3023 [cell setImage:[[wxBitmap(iconText.GetIcon()).GetNSImage() retain] autorelease]];
3024 else
3025 [cell setImage:nil];
3026 [cell setStringValue:[[wxCFStringRef(iconText.GetText()).AsNSString() retain] autorelease]];
3027 return true;
3028 }
3029 else
3030 {
3031 wxFAIL_MSG(wxString("Icon & text renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
3032 return false;
3033 }
3034 }
3035
3036 void
3037 wxDataViewIconTextRenderer::OSXOnCellChanged(NSObject *value,
3038 const wxDataViewItem& item,
3039 unsigned col)
3040 {
3041 wxVariant valueIconText;
3042 valueIconText << wxDataViewIconText(ObjectToString(value));
3043
3044 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
3045 model->ChangeValue(valueIconText, item, col);
3046 }
3047
3048 IMPLEMENT_ABSTRACT_CLASS(wxDataViewIconTextRenderer,wxDataViewRenderer)
3049
3050 // ---------------------------------------------------------
3051 // wxDataViewToggleRenderer
3052 // ---------------------------------------------------------
3053 wxDataViewToggleRenderer::wxDataViewToggleRenderer(const wxString& varianttype,
3054 wxDataViewCellMode mode,
3055 int align)
3056 : wxDataViewRenderer(varianttype,mode)
3057 {
3058 NSButtonCell* cell;
3059
3060
3061 cell = [[NSButtonCell alloc] init];
3062 [cell setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
3063 [cell setButtonType:NSSwitchButton];
3064 [cell setImagePosition:NSImageOnly];
3065 SetNativeData(new wxDataViewRendererNativeData(cell));
3066 [cell release];
3067 }
3068
3069 bool wxDataViewToggleRenderer::MacRender()
3070 {
3071 if (GetValue().GetType() == GetVariantType())
3072 {
3073 [GetNativeData()->GetItemCell() setIntValue:GetValue().GetLong()];
3074 return true;
3075 }
3076 else
3077 {
3078 wxFAIL_MSG(wxString("Toggle renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
3079 return false;
3080 }
3081 }
3082
3083 void
3084 wxDataViewToggleRenderer::OSXOnCellChanged(NSObject *value,
3085 const wxDataViewItem& item,
3086 unsigned col)
3087 {
3088 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
3089 model->ChangeValue(ObjectToBool(value), item, col);
3090 }
3091
3092 IMPLEMENT_ABSTRACT_CLASS(wxDataViewToggleRenderer,wxDataViewRenderer)
3093
3094 // ---------------------------------------------------------
3095 // wxDataViewProgressRenderer
3096 // ---------------------------------------------------------
3097 wxDataViewProgressRenderer::wxDataViewProgressRenderer(const wxString& label,
3098 const wxString& varianttype,
3099 wxDataViewCellMode mode,
3100 int align)
3101 : wxDataViewRenderer(varianttype,mode,align)
3102 {
3103 wxUnusedVar(label);
3104
3105 NSLevelIndicatorCell* cell;
3106
3107 cell = [[NSLevelIndicatorCell alloc] initWithLevelIndicatorStyle:NSContinuousCapacityLevelIndicatorStyle];
3108 [cell setMinValue:0];
3109 [cell setMaxValue:100];
3110 SetNativeData(new wxDataViewRendererNativeData(cell));
3111 [cell release];
3112 }
3113
3114 bool wxDataViewProgressRenderer::MacRender()
3115 {
3116 if (GetValue().GetType() == GetVariantType())
3117 {
3118 [GetNativeData()->GetItemCell() setIntValue:GetValue().GetLong()];
3119 return true;
3120 }
3121 else
3122 {
3123 wxFAIL_MSG(wxString("Progress renderer cannot render value because of wrong value type; value type: ") << GetValue().GetType());
3124 return false;
3125 }
3126 }
3127
3128 void
3129 wxDataViewProgressRenderer::OSXOnCellChanged(NSObject *value,
3130 const wxDataViewItem& item,
3131 unsigned col)
3132 {
3133 wxDataViewModel *model = GetOwner()->GetOwner()->GetModel();
3134 model->ChangeValue(ObjectToLong(value), item, col);
3135 }
3136
3137 IMPLEMENT_ABSTRACT_CLASS(wxDataViewProgressRenderer,wxDataViewRenderer)
3138
3139 // ---------------------------------------------------------
3140 // wxDataViewColumn
3141 // ---------------------------------------------------------
3142
3143 wxDataViewColumn::wxDataViewColumn(const wxString& title,
3144 wxDataViewRenderer* renderer,
3145 unsigned int model_column,
3146 int width,
3147 wxAlignment align,
3148 int flags)
3149 : wxDataViewColumnBase(renderer, model_column),
3150 m_NativeDataPtr(new wxDataViewColumnNativeData()),
3151 m_title(title)
3152 {
3153 InitCommon(width, align, flags);
3154 if (renderer && !renderer->IsCustomRenderer() &&
3155 (renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
3156 renderer->SetAlignment(align);
3157 }
3158
3159 wxDataViewColumn::wxDataViewColumn(const wxBitmap& bitmap,
3160 wxDataViewRenderer* renderer,
3161 unsigned int model_column,
3162 int width,
3163 wxAlignment align,
3164 int flags)
3165 : wxDataViewColumnBase(bitmap, renderer, model_column),
3166 m_NativeDataPtr(new wxDataViewColumnNativeData())
3167 {
3168 InitCommon(width, align, flags);
3169 if (renderer && !renderer->IsCustomRenderer() &&
3170 (renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
3171 renderer->SetAlignment(align);
3172 }
3173
3174 wxDataViewColumn::~wxDataViewColumn()
3175 {
3176 delete m_NativeDataPtr;
3177 }
3178
3179 int wxDataViewColumn::GetWidth() const
3180 {
3181 return [m_NativeDataPtr->GetNativeColumnPtr() width];
3182 }
3183
3184 bool wxDataViewColumn::IsSortKey() const
3185 {
3186 NSTableColumn *nsCol = GetNativeData()->GetNativeColumnPtr();
3187 return nsCol && ([nsCol sortDescriptorPrototype] != nil);
3188 }
3189
3190 void wxDataViewColumn::SetAlignment(wxAlignment align)
3191 {
3192 m_alignment = align;
3193 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setAlignment:ConvertToNativeHorizontalTextAlignment(align)];
3194 if (m_renderer && !m_renderer->IsCustomRenderer() &&
3195 (m_renderer->GetAlignment() == wxDVR_DEFAULT_ALIGNMENT))
3196 m_renderer->SetAlignment(align);
3197 }
3198
3199 void wxDataViewColumn::SetBitmap(const wxBitmap& bitmap)
3200 {
3201 // bitmaps and titles cannot exist at the same time - if the bitmap is set
3202 // the title is removed:
3203 m_title = wxEmptyString;
3204 wxDataViewColumnBase::SetBitmap(bitmap);
3205 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setImage:[[bitmap.GetNSImage() retain] autorelease]];
3206 }
3207
3208 void wxDataViewColumn::SetMaxWidth(int maxWidth)
3209 {
3210 m_maxWidth = maxWidth;
3211 [m_NativeDataPtr->GetNativeColumnPtr() setMaxWidth:maxWidth];
3212 }
3213
3214 void wxDataViewColumn::SetMinWidth(int minWidth)
3215 {
3216 m_minWidth = minWidth;
3217 [m_NativeDataPtr->GetNativeColumnPtr() setMinWidth:minWidth];
3218 }
3219
3220 void wxDataViewColumn::SetReorderable(bool reorderable)
3221 {
3222 wxUnusedVar(reorderable);
3223 }
3224
3225 void wxDataViewColumn::SetHidden(bool hidden)
3226 {
3227 // How to set flag here?
3228
3229 [m_NativeDataPtr->GetNativeColumnPtr() setHidden:hidden];
3230 }
3231
3232 bool wxDataViewColumn::IsHidden() const
3233 {
3234 return [m_NativeDataPtr->GetNativeColumnPtr() isHidden];
3235 }
3236
3237 void wxDataViewColumn::SetResizeable(bool resizable)
3238 {
3239 wxDataViewColumnBase::SetResizeable(resizable);
3240 if (resizable)
3241 [m_NativeDataPtr->GetNativeColumnPtr() setResizingMask:NSTableColumnUserResizingMask];
3242 else
3243 [m_NativeDataPtr->GetNativeColumnPtr() setResizingMask:NSTableColumnNoResizing];
3244 }
3245
3246 void wxDataViewColumn::SetSortable(bool sortable)
3247 {
3248 // wxDataViewColumnBase::SetSortable(sortable);
3249 // Avoid endless recursion and just set the flag here
3250 if (sortable)
3251 m_flags |= wxDATAVIEW_COL_SORTABLE;
3252 else
3253 m_flags &= ~wxDATAVIEW_COL_SORTABLE;
3254 }
3255
3256 void wxDataViewColumn::SetSortOrder(bool ascending)
3257 {
3258 if (m_ascending != ascending)
3259 {
3260 m_ascending = ascending;
3261 if (IsSortKey())
3262 {
3263 // change sorting order:
3264 NSArray* sortDescriptors;
3265 NSSortDescriptor* sortDescriptor;
3266 NSTableColumn* tableColumn;
3267
3268 tableColumn = m_NativeDataPtr->GetNativeColumnPtr();
3269 sortDescriptor = [[NSSortDescriptor alloc] initWithKey:[[tableColumn sortDescriptorPrototype] key] ascending:m_ascending];
3270 sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
3271 [tableColumn setSortDescriptorPrototype:sortDescriptor];
3272 [[tableColumn tableView] setSortDescriptors:sortDescriptors];
3273 [sortDescriptor release];
3274 }
3275 }
3276 }
3277
3278 void wxDataViewColumn::SetTitle(const wxString& title)
3279 {
3280 // bitmaps and titles cannot exist at the same time - if the title is set
3281 // the bitmap is removed:
3282 wxDataViewColumnBase::SetBitmap(wxBitmap());
3283 m_title = title;
3284 [[m_NativeDataPtr->GetNativeColumnPtr() headerCell] setStringValue:[[wxCFStringRef(title).AsNSString() retain] autorelease]];
3285 }
3286
3287 void wxDataViewColumn::SetWidth(int width)
3288 {
3289 m_width = width;
3290
3291 switch ( width )
3292 {
3293 case wxCOL_WIDTH_AUTOSIZE:
3294 #if MAC_OS_X_VERSION_MIN_REQUIRED >= MAC_OS_X_VERSION_10_5
3295 if ( GetOwner() )
3296 {
3297 wxCocoaDataViewControl *peer = static_cast<wxCocoaDataViewControl*>(GetOwner()->GetPeer());
3298 peer->FitColumnWidthToContent(GetOwner()->GetColumnPosition(this));
3299 break;
3300 }
3301 #endif
3302 // fall through if unsupported (OSX < 10.5) or not yet settable
3303
3304 case wxCOL_WIDTH_DEFAULT:
3305 width = wxDVC_DEFAULT_WIDTH;
3306 // fall through
3307
3308 default:
3309 [m_NativeDataPtr->GetNativeColumnPtr() setWidth:width];
3310 break;
3311 }
3312 }
3313
3314 void wxDataViewColumn::SetNativeData(wxDataViewColumnNativeData* newNativeDataPtr)
3315 {
3316 delete m_NativeDataPtr;
3317 m_NativeDataPtr = newNativeDataPtr;
3318 }
3319
3320 #endif // (wxUSE_DATAVIEWCTRL == 1) && !defined(wxUSE_GENERICDATAVIEWCTRL)