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