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