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