reworking event handling to redirect to c++ virtual functions
[wxWidgets.git] / src / osx / cocoa / listbox.mm
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name:        src/osx/cocoa/listbox.mm
3 // Purpose:     wxListBox
4 // Author:      Stefan Csomor
5 // Modified by:
6 // Created:     1998-01-01
7 // RCS-ID:      $Id: listbox.cpp 54820 2008-07-29 20:04:11Z SC $
8 // Copyright:   (c) Stefan Csomor
9 // Licence:     wxWindows licence
10 ///////////////////////////////////////////////////////////////////////////////
11
12 #include "wx/wxprec.h"
13
14 #if wxUSE_LISTBOX
15
16 #include "wx/listbox.h"
17 #include "wx/dnd.h"
18
19 #ifndef WX_PRECOMP
20     #include "wx/log.h"
21     #include "wx/intl.h"
22     #include "wx/utils.h"
23     #include "wx/settings.h"
24     #include "wx/arrstr.h"
25     #include "wx/dcclient.h"
26 #endif
27
28 #include "wx/osx/private.h"
29
30 #include <vector>
31
32 // forward decls
33
34 class wxListWidgetCocoaImpl;
35
36 @interface wxNSTableDataSource : NSObject
37 {
38     wxListWidgetCocoaImpl* impl;
39 }
40
41 - (id)tableView:(NSTableView *)aTableView 
42         objectValueForTableColumn:(NSTableColumn *)aTableColumn 
43         row:(NSInteger)rowIndex;
44
45 - (void)tableView:(NSTableView *)aTableView 
46         setObjectValue:(id)value forTableColumn:(NSTableColumn *)aTableColumn 
47         row:(NSInteger)rowIndex;
48         
49 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView;
50
51 - (void)setImplementation: (wxListWidgetCocoaImpl *) theImplementation;
52 - (wxListWidgetCocoaImpl*) implementation;
53
54 @end
55
56 @interface wxNSTableView : NSTableView
57 {
58 }
59
60 @end
61
62 //
63 // table column
64 //
65
66 class wxCocoaTableColumn;
67
68 @interface wxNSTableColumn : NSTableColumn
69 {
70     wxCocoaTableColumn* column;
71 }
72
73 - (void) setColumn: (wxCocoaTableColumn*) col;
74
75 - (wxCocoaTableColumn*) column;
76
77 @end
78
79 class WXDLLIMPEXP_CORE wxCocoaTableColumn : public wxListWidgetColumn
80 {
81 public :
82     wxCocoaTableColumn( wxNSTableColumn* column, bool editable ) 
83         : m_column( column ), m_editable(editable)
84     {
85     }
86     
87     ~wxCocoaTableColumn()
88     {
89     }
90     
91     wxNSTableColumn* GetNSTableColumn() const { return m_column ; }
92     
93     bool IsEditable() const { return m_editable; }
94     
95 protected :
96     wxNSTableColumn* m_column;
97     bool m_editable;
98 } ;
99
100 NSString* column1 = @"1";
101
102 class wxListWidgetCocoaImpl : public wxWidgetCocoaImpl, public wxListWidgetImpl
103 {
104 public :
105     wxListWidgetCocoaImpl( wxWindowMac* peer, NSScrollView* view, wxNSTableView* tableview, wxNSTableDataSource* data );
106     
107     ~wxListWidgetCocoaImpl();
108     
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)  ;
113     
114     // add and remove
115     
116     virtual void            ListDelete( unsigned int n ) ;    
117     virtual void            ListInsert( unsigned int n ) ;
118     virtual void            ListClear() ;
119
120     // selecting
121
122     virtual void            ListDeselectAll();
123     
124     virtual void            ListSetSelection( unsigned int n, bool select, bool multi ) ;
125     virtual int             ListGetSelection() const ;
126     
127     virtual int             ListGetSelections( wxArrayInt& aSelections ) const ;
128     
129     virtual bool            ListIsSelected( unsigned int n ) const ;
130     
131     // display
132
133     virtual void            ListScrollTo( unsigned int n ) ;
134
135     // accessing content
136
137     virtual unsigned int    ListGetCount() const ;
138     
139     int                     ListGetColumnType( int col )
140     {
141         return col;
142     }
143     virtual void            UpdateLine( unsigned int n, wxListWidgetColumn* col = NULL ) ;
144     virtual void            UpdateLineToEnd( unsigned int n);
145
146     virtual void            clickedAction(WXWidget slf, void* _cmd, void *sender);
147     virtual void            doubleClickedAction(void* _cmd);
148 protected :
149     wxNSTableView*          m_tableView ;
150     
151     wxNSTableDataSource*    m_dataSource;
152 } ;
153
154 //
155 // implementations
156 //
157
158 @implementation wxNSTableColumn
159
160 - (id) init
161 {
162     [super init];
163     column = nil;
164     return self;
165 }
166
167 - (void) setColumn: (wxCocoaTableColumn*) col
168 {
169     column = col;
170 }
171
172 - (wxCocoaTableColumn*) column
173 {
174     return column;
175 }
176
177 @end
178
179 class wxNSTableViewCellValue : public wxListWidgetCellValue
180 {
181 public :
182     wxNSTableViewCellValue( id &v ) : value(v)
183     {
184     }
185     
186     virtual ~wxNSTableViewCellValue() {}
187
188     virtual void Set( CFStringRef v )
189     {
190         value = [[(NSString*)v retain] autorelease];
191     }
192     virtual void Set( const wxString& value ) 
193     {
194         Set( (CFStringRef) wxCFStringRef( value ) );
195     }
196     virtual void Set( int v ) 
197     {
198         value = [NSNumber numberWithInt:v];
199     }
200     
201     virtual int GetIntValue() const 
202     {
203         if ( [value isKindOfClass:[NSNumber class]] )
204             return [ (NSNumber*) value intValue ];
205             
206         return 0;
207     }
208     
209     virtual wxString GetStringValue() const 
210     {
211         if ( [value isKindOfClass:[NSString class]] )
212             return wxCFStringRef( (CFStringRef) [value retain] ).AsString();
213             
214         return wxEmptyString;
215     }
216         
217 protected:
218     id& value;
219 } ;
220
221 @implementation wxNSTableDataSource
222
223 - (id) init
224 {
225     [super init];
226     impl = nil;
227     return self;
228 }
229
230 - (void)setImplementation: (wxListWidgetCocoaImpl *) theImplementation
231 {
232     impl = theImplementation;
233 }
234
235 - (wxListWidgetCocoaImpl*) implementation
236 {
237     return impl;
238 }
239
240 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
241 {
242     if ( impl )
243         return impl->ListGetCount();
244     return 0;
245 }
246
247 - (id)tableView:(NSTableView *)aTableView 
248         objectValueForTableColumn:(NSTableColumn *)aTableColumn 
249         row:(NSInteger)rowIndex
250 {
251     wxNSTableColumn* tablecol = (wxNSTableColumn *)aTableColumn;
252     wxListBox* lb = dynamic_cast<wxListBox*>(impl->GetWXPeer());
253     wxCocoaTableColumn* col = [tablecol column];
254     id value = nil;
255     wxNSTableViewCellValue cellvalue(value);
256     lb->GetValueCallback(rowIndex, col, cellvalue);
257     return value;
258 }
259
260 - (void)tableView:(NSTableView *)aTableView 
261         setObjectValue:(id)value forTableColumn:(NSTableColumn *)aTableColumn 
262         row:(NSInteger)rowIndex
263 {
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);
269 }
270
271 @end
272
273 @implementation wxNSTableView
274
275 + (void)initialize
276 {
277     static BOOL initialized = NO;
278     if (!initialized) 
279     {
280         initialized = YES;
281         wxOSXCocoaClassAddWXMethods( self );
282     }
283 }
284
285 @end
286
287 //
288 //
289 //
290
291 wxListWidgetCocoaImpl::wxListWidgetCocoaImpl( wxWindowMac* peer, NSScrollView* view, wxNSTableView* tableview, wxNSTableDataSource* data ) :
292     wxWidgetCocoaImpl( peer, view ), m_tableView(tableview), m_dataSource(data)
293 {
294     InstallEventHandler( tableview );
295 }
296
297 wxListWidgetCocoaImpl::~wxListWidgetCocoaImpl()
298 {
299     [m_dataSource release];
300 }
301
302 unsigned int wxListWidgetCocoaImpl::ListGetCount() const 
303 {
304     wxListBox* lb = dynamic_cast<wxListBox*> ( GetWXPeer() );
305     return lb->GetCount();
306 }
307
308 //
309 // columns
310 //
311
312 wxListWidgetColumn* wxListWidgetCocoaImpl::InsertTextColumn( unsigned pos, const wxString& title, bool editable, 
313                                 wxAlignment just, int defaultWidth) 
314 {
315     wxNSTableColumn* col1 = [[wxNSTableColumn alloc] init];
316     [col1 setEditable:editable];
317     
318     unsigned formerColCount = [m_tableView numberOfColumns];
319     
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];
324         
325     if ( defaultWidth >= 0 )
326     {
327         [col1 setMaxWidth:defaultWidth];
328         [col1 setMinWidth:defaultWidth];
329     }
330     
331     wxCocoaTableColumn* wxcol = new wxCocoaTableColumn( col1, editable );
332     [col1 setColumn:wxcol];
333
334     // owned by the tableview
335     [col1 release];
336     return wxcol;
337 }
338
339 wxListWidgetColumn* wxListWidgetCocoaImpl::InsertCheckColumn( unsigned pos , const wxString& title, bool editable, 
340                                 wxAlignment just, int defaultWidth ) 
341 {
342    wxNSTableColumn* col1 = [[wxNSTableColumn alloc] init];
343     [col1 setEditable:editable];
344  
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] ;
350     [checkbox release];
351              
352     unsigned formerColCount = [m_tableView numberOfColumns];
353     
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];
358         
359     if ( defaultWidth >= 0 )
360     {
361         [col1 setMaxWidth:defaultWidth];
362         [col1 setMinWidth:defaultWidth];
363     }
364     
365     wxCocoaTableColumn* wxcol = new wxCocoaTableColumn( col1, editable );
366     [col1 setColumn:wxcol];
367
368     // owned by the tableview
369     [col1 release];
370     return wxcol;
371 }
372
373
374 //
375 // inserting / removing lines
376 //
377
378 void wxListWidgetCocoaImpl::ListInsert( unsigned int n ) 
379 {
380 #if 0
381     {
382         wxListBoxCocoaLine* line = new wxListBoxCocoaLine();
383         line->SetLabel(items[i]);
384         if ( m_items.size() <= n+i )
385             m_items.push_back( line );
386         else
387             m_items.insert(m_items.begin()+n, line);
388 /*
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];
394         else
395             [array insertObject:line atIndex:n];
396 */
397     }
398 #endif
399     [m_tableView reloadData];
400 }
401
402 void wxListWidgetCocoaImpl::ListDelete( unsigned int n ) 
403 {
404     [m_tableView reloadData];
405 }
406
407 void wxListWidgetCocoaImpl::ListClear() 
408 {
409     [m_tableView reloadData];
410 }
411
412 // selecting
413
414 void wxListWidgetCocoaImpl::ListDeselectAll()
415 {
416     [m_tableView deselectAll:nil];
417 }
418
419 void wxListWidgetCocoaImpl::ListSetSelection( unsigned int n, bool select, bool multi ) 
420 {
421     // TODO
422     if ( select )
423         [m_tableView selectRow: n byExtendingSelection:multi];
424     else
425         [m_tableView deselectRow: n];
426
427 }
428
429 int wxListWidgetCocoaImpl::ListGetSelection() const 
430 {
431     return [m_tableView selectedRow];
432 }
433
434 int wxListWidgetCocoaImpl::ListGetSelections( wxArrayInt& aSelections ) const 
435 {
436     aSelections.Empty();
437
438     int count = ListGetCount();
439
440     for ( int i = 0; i < count; ++i)
441     {
442         if ([m_tableView isRowSelected:count])
443         aSelections.Add(i);
444     }
445
446     return aSelections.Count();
447 }
448
449 bool wxListWidgetCocoaImpl::ListIsSelected( unsigned int n ) const 
450 {
451     return [m_tableView isRowSelected:n];
452 }
453
454 // display
455
456 void wxListWidgetCocoaImpl::ListScrollTo( unsigned int n ) 
457 {
458     [m_tableView scrollRowToVisible:n];
459 }
460
461     
462 void wxListWidgetCocoaImpl::UpdateLine( unsigned int n, wxListWidgetColumn* col ) 
463 {
464     // TODO optimize
465     [m_tableView reloadData];
466 }
467
468 void wxListWidgetCocoaImpl::UpdateLineToEnd( unsigned int n) 
469 {
470     // TODO optimize
471     [m_tableView reloadData];
472 }
473
474 void wxListWidgetCocoaImpl::clickedAction(WXWidget slf,void* _cmd, void *sender)
475 {
476     wxListBox *list = static_cast<wxListBox*> ( GetWXPeer());
477     wxCHECK_RET( list != NULL , wxT("Listbox expected"));
478
479     wxCommandEvent event( wxEVT_COMMAND_LISTBOX_SELECTED, list->GetId() );
480
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?)
483        return;
484        
485     list->HandleLineEvent( sel, false );
486 }
487
488 void wxListWidgetCocoaImpl::doubleClickedAction(void* _cmd)
489 {
490     wxListBox *list = static_cast<wxListBox*> ( GetWXPeer());
491     wxCHECK_RET( list != NULL , wxT("Listbox expected"));
492
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?)
495        return;
496
497     list->HandleLineEvent( sel, true );
498 }
499
500 // accessing content
501
502
503 wxWidgetImplType* wxWidgetImpl::CreateListBox( wxWindowMac* wxpeer, 
504                                     wxWindowMac* parent, 
505                                     wxWindowID id, 
506                                     const wxPoint& pos, 
507                                     const wxSize& size,
508                                     long style, 
509                                     long extraStyle)
510 {
511     NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
512     NSScrollView* scrollview = [[NSScrollView alloc] initWithFrame:r];
513     
514     // use same scroll flags logic as msw
515     
516     [scrollview setHasVerticalScroller:YES];
517     
518     if ( style & wxLB_HSCROLL )
519         [scrollview setHasHorizontalScroller:YES];
520     
521     [scrollview setAutohidesScrollers: ((style & wxLB_ALWAYS_SB) ? NO : YES)];
522     
523     // setting up the true table
524     
525     wxNSTableView* tableview = [[wxNSTableView alloc] init];
526     [scrollview setDocumentView:tableview];
527     [tableview release];
528     
529     // only one multi-select mode available
530     if ( (style & wxLB_EXTENDED) || (style & wxLB_MULTIPLE) )
531         [tableview setAllowsMultipleSelection:YES];
532         
533     // simple listboxes have no header row
534     [tableview setHeaderView:nil];
535     
536     [tableview setColumnAutoresizingStyle:NSTableViewLastColumnOnlyAutoresizingStyle];
537     wxNSTableDataSource* ds = [[ wxNSTableDataSource alloc] init];
538     [tableview setDataSource:ds];
539     wxListWidgetCocoaImpl* c = new wxListWidgetCocoaImpl( wxpeer, scrollview, tableview, ds );
540
541     // temporary hook for dnd
542     [tableview registerForDraggedTypes:[NSArray arrayWithObjects:
543         NSStringPboardType, NSFilenamesPboardType, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
544
545     [ds setImplementation:c];
546     return c;
547 }
548
549 int wxListBox::DoListHitTest(const wxPoint& inpoint) const
550 {
551 #if wxOSX_USE_CARBON
552     OSStatus err;
553
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
561
562     wxPoint point = inpoint;
563
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"));
568
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"));
577
578     UInt16 height;
579     err = GetDataBrowserTableViewRowHeight(m_peer->GetControlRef(), &height);
580     wxCHECK_MSG(err == noErr, wxNOT_FOUND, wxT("Unexpected error from GetDataBrowserTableViewRowHeight"));
581
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;
586
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 )
591     {
592         Rect bounds;
593         err = GetDataBrowserItemPartBounds(
594             m_peer->GetControlRef(), low + 1, colId,
595             kDataBrowserPropertyEnclosingPart,
596             &bounds); // note +1 to translate to Mac ID
597         if ( err == noErr )
598             break;
599
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") );
604
605         low++;
606     }
607
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 )
611     {
612         int mid = (low + high) / 2;
613
614         Rect bounds;
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,
620                      wxNOT_FOUND,
621                      wxT("Unexpected error from GetDataBrowserItemPartBounds") );
622
623         if ( err == errDataBrowserItemNotFound )
624         {
625             // item not visible, attempt to find a visible one
626             // search lower
627             high = mid - 1;
628         }
629         else // visible item, do actual hitttest
630         {
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
633             // equality)
634             if ((point.x >= bounds.left && point.x <= bounds.right) &&
635                 (point.y >= bounds.top && point.y <= bounds.bottom) )
636             {
637                 // found!
638                 return mid;
639             }
640
641             if ( point.y < bounds.top )
642                 // index(bounds) greater then key(point)
643                 high = mid - 1;
644             else
645                 // index(bounds) less then key(point)
646                 low = mid + 1;
647         }
648     }
649 #endif
650     return wxNOT_FOUND;
651 }
652
653 #endif // wxUSE_LISTBOX