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