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 clickedAction(WXWidget slf, void* _cmd, void *sender);
147 virtual void doubleClickedAction(void* _cmd);
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];
331 wxCocoaTableColumn* wxcol = new wxCocoaTableColumn( col1, editable );
332 [col1 setColumn:wxcol];
334 // owned by the tableview
339 wxListWidgetColumn* wxListWidgetCocoaImpl::InsertCheckColumn( unsigned pos , const wxString& title, bool editable,
340 wxAlignment just, int defaultWidth )
342 wxNSTableColumn* col1 = [[wxNSTableColumn alloc] init];
343 [col1 setEditable:editable];
345 // set your custom cell & set it up
346 NSButtonCell* checkbox = [[NSButtonCell alloc] init];
347 [checkbox setTitle:@""];
348 [checkbox setButtonType:NSSwitchButton];
349 [col1 setDataCell:checkbox] ;
352 unsigned formerColCount = [m_tableView numberOfColumns];
354 // there's apparently no way to insert at a specific position
355 [m_tableView addTableColumn:col1 ];
356 if ( pos < formerColCount )
357 [m_tableView moveColumn:formerColCount toColumn:pos];
359 if ( defaultWidth >= 0 )
361 [col1 setMaxWidth:defaultWidth];
362 [col1 setMinWidth:defaultWidth];
365 wxCocoaTableColumn* wxcol = new wxCocoaTableColumn( col1, editable );
366 [col1 setColumn:wxcol];
368 // owned by the tableview
375 // inserting / removing lines
378 void wxListWidgetCocoaImpl::ListInsert( unsigned int n )
382 wxListBoxCocoaLine* line = new wxListBoxCocoaLine();
383 line->SetLabel(items[i]);
384 if ( m_items.size() <= n+i )
385 m_items.push_back( line );
387 m_items.insert(m_items.begin()+n, line);
389 NSMutableDictionary* line = [[NSMutableDictionary alloc] init];
390 [line setObject:wxCFStringRef(items[i]).AsNSString() forKey:column1];
391 NSMutableArray* array = [m_dataSource items];
392 if ( [array count] <= n+i )
393 [array addObject:line];
395 [array insertObject:line atIndex:n];
399 [m_tableView reloadData];
402 void wxListWidgetCocoaImpl::ListDelete( unsigned int n )
404 [m_tableView reloadData];
407 void wxListWidgetCocoaImpl::ListClear()
409 [m_tableView reloadData];
414 void wxListWidgetCocoaImpl::ListDeselectAll()
416 [m_tableView deselectAll:nil];
419 void wxListWidgetCocoaImpl::ListSetSelection( unsigned int n, bool select, bool multi )
423 [m_tableView selectRow: n byExtendingSelection:multi];
425 [m_tableView deselectRow: n];
429 int wxListWidgetCocoaImpl::ListGetSelection() const
431 return [m_tableView selectedRow];
434 int wxListWidgetCocoaImpl::ListGetSelections( wxArrayInt& aSelections ) const
438 int count = ListGetCount();
440 for ( int i = 0; i < count; ++i)
442 if ([m_tableView isRowSelected:count])
446 return aSelections.Count();
449 bool wxListWidgetCocoaImpl::ListIsSelected( unsigned int n ) const
451 return [m_tableView isRowSelected:n];
456 void wxListWidgetCocoaImpl::ListScrollTo( unsigned int n )
458 [m_tableView scrollRowToVisible:n];
462 void wxListWidgetCocoaImpl::UpdateLine( unsigned int n, wxListWidgetColumn* col )
465 [m_tableView reloadData];
468 void wxListWidgetCocoaImpl::UpdateLineToEnd( unsigned int n)
471 [m_tableView reloadData];
474 void wxListWidgetCocoaImpl::clickedAction(WXWidget slf,void* _cmd, void *sender)
476 wxListBox *list = static_cast<wxListBox*> ( GetWXPeer());
477 wxCHECK_RET( list != NULL , wxT("Listbox expected"));
479 wxCommandEvent event( wxEVT_COMMAND_LISTBOX_SELECTED, list->GetId() );
481 int sel = [m_tableView clickedRow];
482 if ((sel < 0) || (sel > (int) list->GetCount())) // OS X can select an item below the last item (why?)
485 list->HandleLineEvent( sel, false );
488 void wxListWidgetCocoaImpl::doubleClickedAction(void* _cmd)
490 wxListBox *list = static_cast<wxListBox*> ( GetWXPeer());
491 wxCHECK_RET( list != NULL , wxT("Listbox expected"));
493 int sel = [m_tableView clickedRow];
494 if ((sel < 0) || (sel > (int) list->GetCount())) // OS X can select an item below the last item (why?)
497 list->HandleLineEvent( sel, true );
503 wxWidgetImplType* wxWidgetImpl::CreateListBox( wxWindowMac* wxpeer,
511 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
512 NSScrollView* scrollview = [[NSScrollView alloc] initWithFrame:r];
514 // use same scroll flags logic as msw
516 [scrollview setHasVerticalScroller:YES];
518 if ( style & wxLB_HSCROLL )
519 [scrollview setHasHorizontalScroller:YES];
521 [scrollview setAutohidesScrollers: ((style & wxLB_ALWAYS_SB) ? NO : YES)];
523 // setting up the true table
525 wxNSTableView* tableview = [[wxNSTableView alloc] init];
526 [scrollview setDocumentView:tableview];
529 // only one multi-select mode available
530 if ( (style & wxLB_EXTENDED) || (style & wxLB_MULTIPLE) )
531 [tableview setAllowsMultipleSelection:YES];
533 // simple listboxes have no header row
534 [tableview setHeaderView:nil];
536 [tableview setColumnAutoresizingStyle:NSTableViewLastColumnOnlyAutoresizingStyle];
537 wxNSTableDataSource* ds = [[ wxNSTableDataSource alloc] init];
538 [tableview setDataSource:ds];
539 wxListWidgetCocoaImpl* c = new wxListWidgetCocoaImpl( wxpeer, scrollview, tableview, ds );
541 // temporary hook for dnd
542 [tableview registerForDraggedTypes:[NSArray arrayWithObjects:
543 NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
545 [ds setImplementation:c];
549 int wxListBox::DoListHitTest(const wxPoint& inpoint) const
554 // There are few reasons why this is complicated:
555 // 1) There is no native HitTest function for Mac
556 // 2) GetDataBrowserItemPartBounds only works on visible items
557 // 3) We can't do it through GetDataBrowserTableView[Item]RowHeight
558 // because what it returns is basically inaccurate in the context
559 // of the coordinates we want here, but we use this as a guess
560 // for where the first visible item lies
562 wxPoint point = inpoint;
564 // get column property ID (req. for call to itempartbounds)
565 DataBrowserTableViewColumnID colId = 0;
566 err = GetDataBrowserTableViewColumnProperty(m_peer->GetControlRef(), 0, &colId);
567 wxCHECK_MSG(err == noErr, wxNOT_FOUND, wxT("Unexpected error from GetDataBrowserTableViewColumnProperty"));
569 // OK, first we need to find the first visible item we have -
570 // this will be the "low" for our binary search. There is no real
571 // easy way around this, as we will need to do a SLOW linear search
572 // until we find a visible item, but we can do a cheap calculation
573 // via the row height to speed things up a bit
574 UInt32 scrollx, scrolly;
575 err = GetDataBrowserScrollPosition(m_peer->GetControlRef(), &scrollx, &scrolly);
576 wxCHECK_MSG(err == noErr, wxNOT_FOUND, wxT("Unexpected error from GetDataBrowserScrollPosition"));
579 err = GetDataBrowserTableViewRowHeight(m_peer->GetControlRef(), &height);
580 wxCHECK_MSG(err == noErr, wxNOT_FOUND, wxT("Unexpected error from GetDataBrowserTableViewRowHeight"));
582 // these indices are 0-based, as usual, so we need to add 1 to them when
583 // passing them to data browser functions which use 1-based indices
584 int low = scrolly / height,
585 high = GetCount() - 1;
587 // search for the first visible item (note that the scroll guess above
588 // is the low bounds of where the item might lie so we only use that as a
589 // starting point - we should reach it within 1 or 2 iterations of the loop)
590 while ( low <= high )
593 err = GetDataBrowserItemPartBounds(
594 m_peer->GetControlRef(), low + 1, colId,
595 kDataBrowserPropertyEnclosingPart,
596 &bounds); // note +1 to translate to Mac ID
600 // errDataBrowserItemNotFound is expected as it simply means that the
601 // item is not currently visible -- but other errors are not
602 wxCHECK_MSG( err == errDataBrowserItemNotFound, wxNOT_FOUND,
603 wxT("Unexpected error from GetDataBrowserItemPartBounds") );
608 // NOW do a binary search for where the item lies, searching low again if
609 // we hit an item that isn't visible
610 while ( low <= high )
612 int mid = (low + high) / 2;
615 err = GetDataBrowserItemPartBounds(
616 m_peer->GetControlRef(), mid + 1, colId,
617 kDataBrowserPropertyEnclosingPart,
618 &bounds); //note +1 to trans to mac id
619 wxCHECK_MSG( err == noErr || err == errDataBrowserItemNotFound,
621 wxT("Unexpected error from GetDataBrowserItemPartBounds") );
623 if ( err == errDataBrowserItemNotFound )
625 // item not visible, attempt to find a visible one
629 else // visible item, do actual hitttest
631 // if point is within the bounds, return this item (since we assume
632 // all x coords of items are equal we only test the x coord in
634 if ((point.x >= bounds.left && point.x <= bounds.right) &&
635 (point.y >= bounds.top && point.y <= bounds.bottom) )
641 if ( point.y < bounds.top )
642 // index(bounds) greater then key(point)
645 // index(bounds) less then key(point)
653 #endif // wxUSE_LISTBOX