1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/osx/cocoa/listbox.mm
4 // Author: Stefan Csomor
7 // RCS-ID: $Id: listbox.cpp 54820 2008-07-29 20:04:11Z SC $
8 // Copyright: (c) Stefan Csomor
9 // Licence: wxWindows licence
10 ///////////////////////////////////////////////////////////////////////////////
12 #include "wx/wxprec.h"
16 #include "wx/listbox.h"
23 #include "wx/settings.h"
24 #include "wx/arrstr.h"
25 #include "wx/dcclient.h"
28 #include "wx/osx/private.h"
34 class wxListWidgetCocoaImpl;
36 @interface wxNSTableDataSource : NSObject
38 wxListWidgetCocoaImpl* impl;
41 - (id)tableView:(NSTableView *)aTableView
42 objectValueForTableColumn:(NSTableColumn *)aTableColumn
43 row:(NSInteger)rowIndex;
45 - (void)tableView:(NSTableView *)aTableView
46 setObjectValue:(id)value forTableColumn:(NSTableColumn *)aTableColumn
47 row:(NSInteger)rowIndex;
49 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView;
51 - (void)setImplementation: (wxListWidgetCocoaImpl *) theImplementation;
52 - (wxListWidgetCocoaImpl*) implementation;
56 @interface wxNSTableView : NSTableView
66 class wxCocoaTableColumn;
68 @interface wxNSTableColumn : NSTableColumn
70 wxCocoaTableColumn* column;
73 - (void) setColumn: (wxCocoaTableColumn*) col;
75 - (wxCocoaTableColumn*) column;
79 class WXDLLIMPEXP_CORE wxCocoaTableColumn : public wxListWidgetColumn
82 wxCocoaTableColumn( wxNSTableColumn* column, bool editable )
83 : m_column( column ), m_editable(editable)
91 wxNSTableColumn* GetNSTableColumn() const { return m_column ; }
93 bool IsEditable() const { return m_editable; }
96 wxNSTableColumn* m_column;
100 NSString* column1 = @"1";
102 class wxListWidgetCocoaImpl : public wxWidgetCocoaImpl, public wxListWidgetImpl
105 wxListWidgetCocoaImpl( wxWindowMac* peer, NSScrollView* view, wxNSTableView* tableview, wxNSTableDataSource* data );
107 ~wxListWidgetCocoaImpl();
109 virtual wxListWidgetColumn* InsertTextColumn( unsigned pos, const wxString& title, bool editable = false,
110 wxAlignment just = wxALIGN_LEFT , int defaultWidth = -1) ;
111 virtual wxListWidgetColumn* InsertCheckColumn( unsigned pos , const wxString& title, bool editable = false,
112 wxAlignment just = wxALIGN_LEFT , int defaultWidth = -1) ;
116 virtual void ListDelete( unsigned int n ) ;
117 virtual void ListInsert( unsigned int n ) ;
118 virtual void ListClear() ;
122 virtual void ListDeselectAll();
124 virtual void ListSetSelection( unsigned int n, bool select, bool multi ) ;
125 virtual int ListGetSelection() const ;
127 virtual int ListGetSelections( wxArrayInt& aSelections ) const ;
129 virtual bool ListIsSelected( unsigned int n ) const ;
133 virtual void ListScrollTo( unsigned int n ) ;
137 virtual unsigned int ListGetCount() const ;
139 int ListGetColumnType( int col )
143 virtual void UpdateLine( unsigned int n, wxListWidgetColumn* col = NULL ) ;
144 virtual void UpdateLineToEnd( unsigned int n);
146 virtual void controlAction(WXWidget slf, void* _cmd, void *sender);
147 virtual void controlDoubleAction(WXWidget slf, void* _cmd, void *sender);
149 wxNSTableView* m_tableView ;
151 wxNSTableDataSource* m_dataSource;
158 @implementation wxNSTableColumn
167 - (void) setColumn: (wxCocoaTableColumn*) col
172 - (wxCocoaTableColumn*) column
179 class wxNSTableViewCellValue : public wxListWidgetCellValue
182 wxNSTableViewCellValue( id &v ) : value(v)
186 virtual ~wxNSTableViewCellValue() {}
188 virtual void Set( CFStringRef v )
190 value = [[(NSString*)v retain] autorelease];
192 virtual void Set( const wxString& value )
194 Set( (CFStringRef) wxCFStringRef( value ) );
196 virtual void Set( int v )
198 value = [NSNumber numberWithInt:v];
201 virtual int GetIntValue() const
203 if ( [value isKindOfClass:[NSNumber class]] )
204 return [ (NSNumber*) value intValue ];
209 virtual wxString GetStringValue() const
211 if ( [value isKindOfClass:[NSString class]] )
212 return wxCFStringRef( (CFStringRef) [value retain] ).AsString();
214 return wxEmptyString;
221 @implementation wxNSTableDataSource
230 - (void)setImplementation: (wxListWidgetCocoaImpl *) theImplementation
232 impl = theImplementation;
235 - (wxListWidgetCocoaImpl*) implementation
240 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
243 return impl->ListGetCount();
247 - (id)tableView:(NSTableView *)aTableView
248 objectValueForTableColumn:(NSTableColumn *)aTableColumn
249 row:(NSInteger)rowIndex
251 wxNSTableColumn* tablecol = (wxNSTableColumn *)aTableColumn;
252 wxListBox* lb = dynamic_cast<wxListBox*>(impl->GetWXPeer());
253 wxCocoaTableColumn* col = [tablecol column];
255 wxNSTableViewCellValue cellvalue(value);
256 lb->GetValueCallback(rowIndex, col, cellvalue);
260 - (void)tableView:(NSTableView *)aTableView
261 setObjectValue:(id)value forTableColumn:(NSTableColumn *)aTableColumn
262 row:(NSInteger)rowIndex
264 wxNSTableColumn* tablecol = (wxNSTableColumn *)aTableColumn;
265 wxListBox* lb = dynamic_cast<wxListBox*>(impl->GetWXPeer());
266 wxCocoaTableColumn* col = [tablecol column];
267 wxNSTableViewCellValue cellvalue(value);
268 lb->SetValueCallback(rowIndex, col, cellvalue);
273 @implementation wxNSTableView
277 static BOOL initialized = NO;
281 wxOSXCocoaClassAddWXMethods( self );
291 wxListWidgetCocoaImpl::wxListWidgetCocoaImpl( wxWindowMac* peer, NSScrollView* view, wxNSTableView* tableview, wxNSTableDataSource* data ) :
292 wxWidgetCocoaImpl( peer, view ), m_tableView(tableview), m_dataSource(data)
294 InstallEventHandler( tableview );
297 wxListWidgetCocoaImpl::~wxListWidgetCocoaImpl()
299 [m_dataSource release];
302 unsigned int wxListWidgetCocoaImpl::ListGetCount() const
304 wxListBox* lb = dynamic_cast<wxListBox*> ( GetWXPeer() );
305 return lb->GetCount();
312 wxListWidgetColumn* wxListWidgetCocoaImpl::InsertTextColumn( unsigned pos, const wxString& title, bool editable,
313 wxAlignment just, int defaultWidth)
315 wxNSTableColumn* col1 = [[wxNSTableColumn alloc] init];
316 [col1 setEditable:editable];
318 unsigned formerColCount = [m_tableView numberOfColumns];
320 // there's apparently no way to insert at a specific position
321 [m_tableView addTableColumn:col1 ];
322 if ( pos < formerColCount )
323 [m_tableView moveColumn:formerColCount toColumn:pos];
325 if ( defaultWidth >= 0 )
327 [col1 setMaxWidth:defaultWidth];
328 [col1 setMinWidth:defaultWidth];
329 [col1 setWidth:defaultWidth];
333 [col1 setMaxWidth:1000];
334 [col1 setMinWidth:10];
335 // temporary hack, because I cannot get the automatic column resizing
337 [col1 setWidth:1000];
339 [col1 setResizingMask: NSTableColumnAutoresizingMask];
340 wxCocoaTableColumn* wxcol = new wxCocoaTableColumn( col1, editable );
341 [col1 setColumn:wxcol];
343 // owned by the tableview
348 wxListWidgetColumn* wxListWidgetCocoaImpl::InsertCheckColumn( unsigned pos , const wxString& title, bool editable,
349 wxAlignment just, int defaultWidth )
351 wxNSTableColumn* col1 = [[wxNSTableColumn alloc] init];
352 [col1 setEditable:editable];
354 // set your custom cell & set it up
355 NSButtonCell* checkbox = [[NSButtonCell alloc] init];
356 [checkbox setTitle:@""];
357 [checkbox setButtonType:NSSwitchButton];
358 [col1 setDataCell:checkbox] ;
361 unsigned formerColCount = [m_tableView numberOfColumns];
363 // there's apparently no way to insert at a specific position
364 [m_tableView addTableColumn:col1 ];
365 if ( pos < formerColCount )
366 [m_tableView moveColumn:formerColCount toColumn:pos];
368 if ( defaultWidth >= 0 )
370 [col1 setMaxWidth:defaultWidth];
371 [col1 setMinWidth:defaultWidth];
372 [col1 setWidth:defaultWidth];
375 [col1 setResizingMask: NSTableColumnNoResizing];
376 wxCocoaTableColumn* wxcol = new wxCocoaTableColumn( col1, editable );
377 [col1 setColumn:wxcol];
379 // owned by the tableview
386 // inserting / removing lines
389 void wxListWidgetCocoaImpl::ListInsert( unsigned int n )
393 wxListBoxCocoaLine* line = new wxListBoxCocoaLine();
394 line->SetLabel(items[i]);
395 if ( m_items.size() <= n+i )
396 m_items.push_back( line );
398 m_items.insert(m_items.begin()+n, line);
400 NSMutableDictionary* line = [[NSMutableDictionary alloc] init];
401 [line setObject:wxCFStringRef(items[i]).AsNSString() forKey:column1];
402 NSMutableArray* array = [m_dataSource items];
403 if ( [array count] <= n+i )
404 [array addObject:line];
406 [array insertObject:line atIndex:n];
410 [m_tableView reloadData];
413 void wxListWidgetCocoaImpl::ListDelete( unsigned int n )
415 [m_tableView reloadData];
418 void wxListWidgetCocoaImpl::ListClear()
420 [m_tableView reloadData];
425 void wxListWidgetCocoaImpl::ListDeselectAll()
427 [m_tableView deselectAll:nil];
430 void wxListWidgetCocoaImpl::ListSetSelection( unsigned int n, bool select, bool multi )
434 [m_tableView selectRow: n byExtendingSelection:multi];
436 [m_tableView deselectRow: n];
440 int wxListWidgetCocoaImpl::ListGetSelection() const
442 return [m_tableView selectedRow];
445 int wxListWidgetCocoaImpl::ListGetSelections( wxArrayInt& aSelections ) const
449 int count = ListGetCount();
451 for ( int i = 0; i < count; ++i)
453 if ([m_tableView isRowSelected:count])
457 return aSelections.Count();
460 bool wxListWidgetCocoaImpl::ListIsSelected( unsigned int n ) const
462 return [m_tableView isRowSelected:n];
467 void wxListWidgetCocoaImpl::ListScrollTo( unsigned int n )
469 [m_tableView scrollRowToVisible:n];
473 void wxListWidgetCocoaImpl::UpdateLine( unsigned int n, wxListWidgetColumn* col )
476 [m_tableView reloadData];
479 void wxListWidgetCocoaImpl::UpdateLineToEnd( unsigned int n)
482 [m_tableView reloadData];
485 void wxListWidgetCocoaImpl::controlAction(WXWidget slf,void* _cmd, void *sender)
487 wxListBox *list = static_cast<wxListBox*> ( GetWXPeer());
488 wxCHECK_RET( list != NULL , wxT("Listbox expected"));
490 wxCommandEvent event( wxEVT_COMMAND_LISTBOX_SELECTED, list->GetId() );
492 int sel = [m_tableView clickedRow];
493 if ((sel < 0) || (sel > (int) list->GetCount())) // OS X can select an item below the last item (why?)
496 list->HandleLineEvent( sel, false );
499 void wxListWidgetCocoaImpl::controlDoubleAction(WXWidget slf,void* _cmd, void *sender)
501 wxListBox *list = static_cast<wxListBox*> ( GetWXPeer());
502 wxCHECK_RET( list != NULL , wxT("Listbox expected"));
504 int sel = [m_tableView clickedRow];
505 if ((sel < 0) || (sel > (int) list->GetCount())) // OS X can select an item below the last item (why?)
508 list->HandleLineEvent( sel, true );
514 wxWidgetImplType* wxWidgetImpl::CreateListBox( wxWindowMac* wxpeer,
522 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
523 NSScrollView* scrollview = [[NSScrollView alloc] initWithFrame:r];
525 // use same scroll flags logic as msw
527 [scrollview setHasVerticalScroller:YES];
529 if ( style & wxLB_HSCROLL )
530 [scrollview setHasHorizontalScroller:YES];
532 [scrollview setAutohidesScrollers: ((style & wxLB_ALWAYS_SB) ? NO : YES)];
534 // setting up the true table
536 wxNSTableView* tableview = [[wxNSTableView alloc] init];
537 // only one multi-select mode available
538 if ( (style & wxLB_EXTENDED) || (style & wxLB_MULTIPLE) )
539 [tableview setAllowsMultipleSelection:YES];
541 // simple listboxes have no header row
542 [tableview setHeaderView:nil];
544 if ( style & wxLB_HSCROLL )
545 [tableview setColumnAutoresizingStyle:NSTableViewNoColumnAutoresizing];
547 [tableview setColumnAutoresizingStyle:NSTableViewLastColumnOnlyAutoresizingStyle];
549 wxNSTableDataSource* ds = [[ wxNSTableDataSource alloc] init];
550 [tableview setDataSource:ds];
551 [scrollview setDocumentView:tableview];
554 wxListWidgetCocoaImpl* c = new wxListWidgetCocoaImpl( wxpeer, scrollview, tableview, ds );
556 // temporary hook for dnd
557 [tableview registerForDraggedTypes:[NSArray arrayWithObjects:
558 NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
560 [ds setImplementation:c];
564 int wxListBox::DoListHitTest(const wxPoint& inpoint) const
569 // There are few reasons why this is complicated:
570 // 1) There is no native HitTest function for Mac
571 // 2) GetDataBrowserItemPartBounds only works on visible items
572 // 3) We can't do it through GetDataBrowserTableView[Item]RowHeight
573 // because what it returns is basically inaccurate in the context
574 // of the coordinates we want here, but we use this as a guess
575 // for where the first visible item lies
577 wxPoint point = inpoint;
579 // get column property ID (req. for call to itempartbounds)
580 DataBrowserTableViewColumnID colId = 0;
581 err = GetDataBrowserTableViewColumnProperty(m_peer->GetControlRef(), 0, &colId);
582 wxCHECK_MSG(err == noErr, wxNOT_FOUND, wxT("Unexpected error from GetDataBrowserTableViewColumnProperty"));
584 // OK, first we need to find the first visible item we have -
585 // this will be the "low" for our binary search. There is no real
586 // easy way around this, as we will need to do a SLOW linear search
587 // until we find a visible item, but we can do a cheap calculation
588 // via the row height to speed things up a bit
589 UInt32 scrollx, scrolly;
590 err = GetDataBrowserScrollPosition(m_peer->GetControlRef(), &scrollx, &scrolly);
591 wxCHECK_MSG(err == noErr, wxNOT_FOUND, wxT("Unexpected error from GetDataBrowserScrollPosition"));
594 err = GetDataBrowserTableViewRowHeight(m_peer->GetControlRef(), &height);
595 wxCHECK_MSG(err == noErr, wxNOT_FOUND, wxT("Unexpected error from GetDataBrowserTableViewRowHeight"));
597 // these indices are 0-based, as usual, so we need to add 1 to them when
598 // passing them to data browser functions which use 1-based indices
599 int low = scrolly / height,
600 high = GetCount() - 1;
602 // search for the first visible item (note that the scroll guess above
603 // is the low bounds of where the item might lie so we only use that as a
604 // starting point - we should reach it within 1 or 2 iterations of the loop)
605 while ( low <= high )
608 err = GetDataBrowserItemPartBounds(
609 m_peer->GetControlRef(), low + 1, colId,
610 kDataBrowserPropertyEnclosingPart,
611 &bounds); // note +1 to translate to Mac ID
615 // errDataBrowserItemNotFound is expected as it simply means that the
616 // item is not currently visible -- but other errors are not
617 wxCHECK_MSG( err == errDataBrowserItemNotFound, wxNOT_FOUND,
618 wxT("Unexpected error from GetDataBrowserItemPartBounds") );
623 // NOW do a binary search for where the item lies, searching low again if
624 // we hit an item that isn't visible
625 while ( low <= high )
627 int mid = (low + high) / 2;
630 err = GetDataBrowserItemPartBounds(
631 m_peer->GetControlRef(), mid + 1, colId,
632 kDataBrowserPropertyEnclosingPart,
633 &bounds); //note +1 to trans to mac id
634 wxCHECK_MSG( err == noErr || err == errDataBrowserItemNotFound,
636 wxT("Unexpected error from GetDataBrowserItemPartBounds") );
638 if ( err == errDataBrowserItemNotFound )
640 // item not visible, attempt to find a visible one
644 else // visible item, do actual hitttest
646 // if point is within the bounds, return this item (since we assume
647 // all x coords of items are equal we only test the x coord in
649 if ((point.x >= bounds.left && point.x <= bounds.right) &&
650 (point.y >= bounds.top && point.y <= bounds.bottom) )
656 if ( point.y < bounds.top )
657 // index(bounds) greater then key(point)
660 // index(bounds) less then key(point)
668 #endif // wxUSE_LISTBOX