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