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