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