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