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