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