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