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
37 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
38 <NSTableViewDataSource>
41 wxListWidgetCocoaImpl* impl;
44 - (id)tableView:(NSTableView *)aTableView
45 objectValueForTableColumn:(NSTableColumn *)aTableColumn
46 row:(NSInteger)rowIndex;
48 - (void)tableView:(NSTableView *)aTableView
49 setObjectValue:(id)value forTableColumn:(NSTableColumn *)aTableColumn
50 row:(NSInteger)rowIndex;
52 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView;
54 - (void)setImplementation: (wxListWidgetCocoaImpl *) theImplementation;
55 - (wxListWidgetCocoaImpl*) implementation;
59 @interface wxNSTableView : NSTableView
60 #if MAC_OS_X_VERSION_MAX_ALLOWED >= MAC_OS_X_VERSION_10_6
72 class wxCocoaTableColumn;
74 @interface wxNSTableColumn : NSTableColumn
76 wxCocoaTableColumn* column;
79 - (void) setColumn: (wxCocoaTableColumn*) col;
81 - (wxCocoaTableColumn*) column;
85 class WXDLLIMPEXP_CORE wxCocoaTableColumn : public wxListWidgetColumn
88 wxCocoaTableColumn( wxNSTableColumn* column, bool editable )
89 : m_column( column ), m_editable(editable)
97 wxNSTableColumn* GetNSTableColumn() const { return m_column ; }
99 bool IsEditable() const { return m_editable; }
102 wxNSTableColumn* m_column;
106 NSString* column1 = @"1";
108 class wxListWidgetCocoaImpl : public wxWidgetCocoaImpl, public wxListWidgetImpl
111 wxListWidgetCocoaImpl( wxWindowMac* peer, NSScrollView* view, wxNSTableView* tableview, wxNSTableDataSource* data );
113 ~wxListWidgetCocoaImpl();
115 virtual wxListWidgetColumn* InsertTextColumn( unsigned pos, const wxString& title, bool editable = false,
116 wxAlignment just = wxALIGN_LEFT , int defaultWidth = -1) ;
117 virtual wxListWidgetColumn* InsertCheckColumn( unsigned pos , const wxString& title, bool editable = false,
118 wxAlignment just = wxALIGN_LEFT , int defaultWidth = -1) ;
122 virtual void ListDelete( unsigned int n ) ;
123 virtual void ListInsert( unsigned int n ) ;
124 virtual void ListClear() ;
128 virtual void ListDeselectAll();
130 virtual void ListSetSelection( unsigned int n, bool select, bool multi ) ;
131 virtual int ListGetSelection() const ;
133 virtual int ListGetSelections( wxArrayInt& aSelections ) const ;
135 virtual bool ListIsSelected( unsigned int n ) const ;
139 virtual void ListScrollTo( unsigned int n ) ;
143 virtual unsigned int ListGetCount() const ;
145 int ListGetColumnType( int col )
149 virtual void UpdateLine( unsigned int n, wxListWidgetColumn* col = NULL ) ;
150 virtual void UpdateLineToEnd( unsigned int n);
152 virtual void controlDoubleAction(WXWidget slf, void* _cmd, void *sender);
153 virtual bool DoHandleKeyEvent(NSEvent *event);
156 wxNSTableView* m_tableView ;
158 wxNSTableDataSource* m_dataSource;
165 @implementation wxNSTableColumn
174 - (void) setColumn: (wxCocoaTableColumn*) col
179 - (wxCocoaTableColumn*) column
186 class wxNSTableViewCellValue : public wxListWidgetCellValue
189 wxNSTableViewCellValue( id &v ) : value(v)
193 virtual ~wxNSTableViewCellValue() {}
195 virtual void Set( CFStringRef v )
197 value = [[(NSString*)v retain] autorelease];
199 virtual void Set( const wxString& value )
201 Set( (CFStringRef) wxCFStringRef( value ) );
203 virtual void Set( int v )
205 value = [NSNumber numberWithInt:v];
208 virtual int GetIntValue() const
210 if ( [value isKindOfClass:[NSNumber class]] )
211 return [ (NSNumber*) value intValue ];
216 virtual wxString GetStringValue() const
218 if ( [value isKindOfClass:[NSString class]] )
219 return wxCFStringRef::AsString( (NSString*) value );
221 return wxEmptyString;
228 @implementation wxNSTableDataSource
237 - (void)setImplementation: (wxListWidgetCocoaImpl *) theImplementation
239 impl = theImplementation;
242 - (wxListWidgetCocoaImpl*) implementation
247 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
249 wxUnusedVar(aTableView);
251 return impl->ListGetCount();
255 - (id)tableView:(NSTableView *)aTableView
256 objectValueForTableColumn:(NSTableColumn *)aTableColumn
257 row:(NSInteger)rowIndex
259 wxUnusedVar(aTableView);
260 wxNSTableColumn* tablecol = (wxNSTableColumn *)aTableColumn;
261 wxListBox* lb = dynamic_cast<wxListBox*>(impl->GetWXPeer());
262 wxCocoaTableColumn* col = [tablecol column];
264 wxNSTableViewCellValue cellvalue(value);
265 lb->GetValueCallback(rowIndex, col, cellvalue);
269 - (void)tableView:(NSTableView *)aTableView
270 setObjectValue:(id)value forTableColumn:(NSTableColumn *)aTableColumn
271 row:(NSInteger)rowIndex
273 wxUnusedVar(aTableView);
274 wxNSTableColumn* tablecol = (wxNSTableColumn *)aTableColumn;
275 wxListBox* lb = dynamic_cast<wxListBox*>(impl->GetWXPeer());
276 wxCocoaTableColumn* col = [tablecol column];
277 wxNSTableViewCellValue cellvalue(value);
278 lb->SetValueCallback(rowIndex, col, cellvalue);
283 @implementation wxNSTableView
287 static BOOL initialized = NO;
291 wxOSXCocoaClassAddWXMethods( self );
295 - (void) tableViewSelectionDidChange: (NSNotification *) notification
297 wxUnusedVar(notification);
299 int row = [self selectedRow];
307 wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
308 wxListBox *list = static_cast<wxListBox*> ( impl->GetWXPeer());
309 wxCHECK_RET( list != NULL , wxT("Listbox expected"));
311 wxCommandEvent event( wxEVT_COMMAND_LISTBOX_SELECTED, list->GetId() );
313 if ((row < 0) || (row > (int) list->GetCount())) // OS X can select an item below the last item
316 if ( !list->MacGetBlockEvents() )
317 list->HandleLineEvent( row, false );
328 wxListWidgetCocoaImpl::wxListWidgetCocoaImpl( wxWindowMac* peer, NSScrollView* view, wxNSTableView* tableview, wxNSTableDataSource* data ) :
329 wxWidgetCocoaImpl( peer, view ), m_tableView(tableview), m_dataSource(data)
331 InstallEventHandler( tableview );
334 wxListWidgetCocoaImpl::~wxListWidgetCocoaImpl()
336 [m_dataSource release];
339 unsigned int wxListWidgetCocoaImpl::ListGetCount() const
341 wxListBox* lb = dynamic_cast<wxListBox*> ( GetWXPeer() );
342 return lb->GetCount();
349 wxListWidgetColumn* wxListWidgetCocoaImpl::InsertTextColumn( unsigned pos, const wxString& WXUNUSED(title), bool editable,
350 wxAlignment WXUNUSED(just), int defaultWidth)
352 wxNSTableColumn* col1 = [[wxNSTableColumn alloc] init];
353 [col1 setEditable:editable];
355 unsigned formerColCount = [m_tableView numberOfColumns];
357 // there's apparently no way to insert at a specific position
358 [m_tableView addTableColumn:col1 ];
359 if ( pos < formerColCount )
360 [m_tableView moveColumn:formerColCount toColumn:pos];
362 if ( defaultWidth >= 0 )
364 [col1 setMaxWidth:defaultWidth];
365 [col1 setMinWidth:defaultWidth];
366 [col1 setWidth:defaultWidth];
370 [col1 setMaxWidth:1000];
371 [col1 setMinWidth:10];
372 // temporary hack, because I cannot get the automatic column resizing
374 [col1 setWidth:1000];
376 [col1 setResizingMask: NSTableColumnAutoresizingMask];
377 wxCocoaTableColumn* wxcol = new wxCocoaTableColumn( col1, editable );
378 [col1 setColumn:wxcol];
380 // owned by the tableview
385 wxListWidgetColumn* wxListWidgetCocoaImpl::InsertCheckColumn( unsigned pos , const wxString& WXUNUSED(title), bool editable,
386 wxAlignment WXUNUSED(just), int defaultWidth )
388 wxNSTableColumn* col1 = [[wxNSTableColumn alloc] init];
389 [col1 setEditable:editable];
391 // set your custom cell & set it up
392 NSButtonCell* checkbox = [[NSButtonCell alloc] init];
393 [checkbox setTitle:@""];
394 [checkbox setButtonType:NSSwitchButton];
395 [col1 setDataCell:checkbox] ;
398 unsigned formerColCount = [m_tableView numberOfColumns];
400 // there's apparently no way to insert at a specific position
401 [m_tableView addTableColumn:col1 ];
402 if ( pos < formerColCount )
403 [m_tableView moveColumn:formerColCount toColumn:pos];
405 if ( defaultWidth >= 0 )
407 [col1 setMaxWidth:defaultWidth];
408 [col1 setMinWidth:defaultWidth];
409 [col1 setWidth:defaultWidth];
412 [col1 setResizingMask: NSTableColumnNoResizing];
413 wxCocoaTableColumn* wxcol = new wxCocoaTableColumn( col1, editable );
414 [col1 setColumn:wxcol];
416 // owned by the tableview
423 // inserting / removing lines
426 void wxListWidgetCocoaImpl::ListInsert( unsigned int WXUNUSED(n) )
428 [m_tableView reloadData];
431 void wxListWidgetCocoaImpl::ListDelete( unsigned int WXUNUSED(n) )
433 [m_tableView reloadData];
436 void wxListWidgetCocoaImpl::ListClear()
438 [m_tableView reloadData];
443 void wxListWidgetCocoaImpl::ListDeselectAll()
445 [m_tableView deselectAll:nil];
448 void wxListWidgetCocoaImpl::ListSetSelection( unsigned int n, bool select, bool multi )
452 [m_tableView selectRow: n byExtendingSelection:multi];
454 [m_tableView deselectRow: n];
458 int wxListWidgetCocoaImpl::ListGetSelection() const
460 return [m_tableView selectedRow];
463 int wxListWidgetCocoaImpl::ListGetSelections( wxArrayInt& aSelections ) const
467 int count = ListGetCount();
469 for ( int i = 0; i < count; ++i)
471 if ([m_tableView isRowSelected:count])
475 return aSelections.Count();
478 bool wxListWidgetCocoaImpl::ListIsSelected( unsigned int n ) const
480 return [m_tableView isRowSelected:n];
485 void wxListWidgetCocoaImpl::ListScrollTo( unsigned int n )
487 [m_tableView scrollRowToVisible:n];
491 void wxListWidgetCocoaImpl::UpdateLine( unsigned int WXUNUSED(n), wxListWidgetColumn* WXUNUSED(col) )
494 [m_tableView reloadData];
497 void wxListWidgetCocoaImpl::UpdateLineToEnd( unsigned int WXUNUSED(n))
500 [m_tableView reloadData];
503 void wxListWidgetCocoaImpl::controlDoubleAction(WXWidget WXUNUSED(slf),void* WXUNUSED(_cmd), void *WXUNUSED(sender))
505 wxListBox *list = static_cast<wxListBox*> ( GetWXPeer());
506 wxCHECK_RET( list != NULL , wxT("Listbox expected"));
508 int sel = [m_tableView clickedRow];
509 if ((sel < 0) || (sel > (int) list->GetCount())) // OS X can select an item below the last item (why?)
512 list->HandleLineEvent( sel, true );
515 bool wxListWidgetCocoaImpl::DoHandleKeyEvent(NSEvent *event)
517 wxKeyEvent wxevent(wxEVT_KEY_DOWN);
518 SetupKeyEvent( wxevent, event );
519 wxevent.SetEventObject(GetWXPeer());
520 bool result = GetWXPeer()->OSXHandleKeyEvent(wxevent);
522 // no interpretKeyEvents here, but rerouting to native keyhandling
530 wxWidgetImplType* wxWidgetImpl::CreateListBox( wxWindowMac* wxpeer,
531 wxWindowMac* WXUNUSED(parent),
532 wxWindowID WXUNUSED(id),
536 long WXUNUSED(extraStyle))
538 NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
539 NSScrollView* scrollview = [[NSScrollView alloc] initWithFrame:r];
541 // use same scroll flags logic as msw
543 [scrollview setHasVerticalScroller:YES];
545 if ( style & wxLB_HSCROLL )
546 [scrollview setHasHorizontalScroller:YES];
548 [scrollview setAutohidesScrollers: ((style & wxLB_ALWAYS_SB) ? NO : YES)];
550 // setting up the true table
552 wxNSTableView* tableview = [[wxNSTableView alloc] init];
553 [tableview setDelegate:tableview];
554 // only one multi-select mode available
555 if ( (style & wxLB_EXTENDED) || (style & wxLB_MULTIPLE) )
556 [tableview setAllowsMultipleSelection:YES];
558 // simple listboxes have no header row
559 [tableview setHeaderView:nil];
561 if ( style & wxLB_HSCROLL )
562 [tableview setColumnAutoresizingStyle:NSTableViewNoColumnAutoresizing];
564 [tableview setColumnAutoresizingStyle:NSTableViewLastColumnOnlyAutoresizingStyle];
566 wxNSTableDataSource* ds = [[ wxNSTableDataSource alloc] init];
567 [tableview setDataSource:ds];
568 [scrollview setDocumentView:tableview];
571 wxListWidgetCocoaImpl* c = new wxListWidgetCocoaImpl( wxpeer, scrollview, tableview, ds );
573 // temporary hook for dnd
574 [tableview registerForDraggedTypes:[NSArray arrayWithObjects:
575 NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
577 [ds setImplementation:c];
581 int wxListBox::DoListHitTest(const wxPoint& WXUNUSED(inpoint)) const
586 // There are few reasons why this is complicated:
587 // 1) There is no native HitTest function for Mac
588 // 2) GetDataBrowserItemPartBounds only works on visible items
589 // 3) We can't do it through GetDataBrowserTableView[Item]RowHeight
590 // because what it returns is basically inaccurate in the context
591 // of the coordinates we want here, but we use this as a guess
592 // for where the first visible item lies
594 wxPoint point = inpoint;
596 // get column property ID (req. for call to itempartbounds)
597 DataBrowserTableViewColumnID colId = 0;
598 err = GetDataBrowserTableViewColumnProperty(m_peer->GetControlRef(), 0, &colId);
599 wxCHECK_MSG(err == noErr, wxNOT_FOUND, wxT("Unexpected error from GetDataBrowserTableViewColumnProperty"));
601 // OK, first we need to find the first visible item we have -
602 // this will be the "low" for our binary search. There is no real
603 // easy way around this, as we will need to do a SLOW linear search
604 // until we find a visible item, but we can do a cheap calculation
605 // via the row height to speed things up a bit
606 UInt32 scrollx, scrolly;
607 err = GetDataBrowserScrollPosition(m_peer->GetControlRef(), &scrollx, &scrolly);
608 wxCHECK_MSG(err == noErr, wxNOT_FOUND, wxT("Unexpected error from GetDataBrowserScrollPosition"));
611 err = GetDataBrowserTableViewRowHeight(m_peer->GetControlRef(), &height);
612 wxCHECK_MSG(err == noErr, wxNOT_FOUND, wxT("Unexpected error from GetDataBrowserTableViewRowHeight"));
614 // these indices are 0-based, as usual, so we need to add 1 to them when
615 // passing them to data browser functions which use 1-based indices
616 int low = scrolly / height,
617 high = GetCount() - 1;
619 // search for the first visible item (note that the scroll guess above
620 // is the low bounds of where the item might lie so we only use that as a
621 // starting point - we should reach it within 1 or 2 iterations of the loop)
622 while ( low <= high )
625 err = GetDataBrowserItemPartBounds(
626 m_peer->GetControlRef(), low + 1, colId,
627 kDataBrowserPropertyEnclosingPart,
628 &bounds); // note +1 to translate to Mac ID
632 // errDataBrowserItemNotFound is expected as it simply means that the
633 // item is not currently visible -- but other errors are not
634 wxCHECK_MSG( err == errDataBrowserItemNotFound, wxNOT_FOUND,
635 wxT("Unexpected error from GetDataBrowserItemPartBounds") );
640 // NOW do a binary search for where the item lies, searching low again if
641 // we hit an item that isn't visible
642 while ( low <= high )
644 int mid = (low + high) / 2;
647 err = GetDataBrowserItemPartBounds(
648 m_peer->GetControlRef(), mid + 1, colId,
649 kDataBrowserPropertyEnclosingPart,
650 &bounds); //note +1 to trans to mac id
651 wxCHECK_MSG( err == noErr || err == errDataBrowserItemNotFound,
653 wxT("Unexpected error from GetDataBrowserItemPartBounds") );
655 if ( err == errDataBrowserItemNotFound )
657 // item not visible, attempt to find a visible one
661 else // visible item, do actual hitttest
663 // if point is within the bounds, return this item (since we assume
664 // all x coords of items are equal we only test the x coord in
666 if ((point.x >= bounds.left && point.x <= bounds.right) &&
667 (point.y >= bounds.top && point.y <= bounds.bottom) )
673 if ( point.y < bounds.top )
674 // index(bounds) greater then key(point)
677 // index(bounds) less then key(point)
685 #endif // wxUSE_LISTBOX