propagating font to the individual columns, changing row heights according to font...
[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$
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 wxOSX_10_6_AND_LATER(<NSTableViewDataSource>)
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 wxOSX_10_6_AND_LATER(<NSTableViewDelegate>)
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     virtual int             DoListHitTest( const wxPoint& inpoint ) const;
139
140     int                     ListGetColumnType( int col )
141     {
142         return col;
143     }
144     virtual void            UpdateLine( unsigned int n, wxListWidgetColumn* col = NULL ) ;
145     virtual void            UpdateLineToEnd( unsigned int n);
146
147     virtual void            controlDoubleAction(WXWidget slf, void* _cmd, void *sender);
148
149     
150 protected :
151     wxNSTableView*          m_tableView ;
152
153     wxNSTableDataSource*    m_dataSource;
154 } ;
155
156 //
157 // implementations
158 //
159
160 @implementation wxNSTableColumn
161
162 - (id) init
163 {
164     self = [super init];
165     column = nil;
166     return self;
167 }
168
169 - (void) setColumn: (wxCocoaTableColumn*) col
170 {
171     column = col;
172 }
173
174 - (wxCocoaTableColumn*) column
175 {
176     return column;
177 }
178
179 @end
180
181 class wxNSTableViewCellValue : public wxListWidgetCellValue
182 {
183 public :
184     wxNSTableViewCellValue( id &v ) : value(v)
185     {
186     }
187
188     virtual ~wxNSTableViewCellValue() {}
189
190     virtual void Set( CFStringRef v )
191     {
192         value = [[(NSString*)v retain] autorelease];
193     }
194     virtual void Set( const wxString& value )
195     {
196         Set( (CFStringRef) wxCFStringRef( value ) );
197     }
198     virtual void Set( int v )
199     {
200         value = [NSNumber numberWithInt:v];
201     }
202
203     virtual int GetIntValue() const
204     {
205         if ( [value isKindOfClass:[NSNumber class]] )
206             return [ (NSNumber*) value intValue ];
207
208         return 0;
209     }
210
211     virtual wxString GetStringValue() const
212     {
213         if ( [value isKindOfClass:[NSString class]] )
214             return wxCFStringRef::AsString( (NSString*) value );
215
216         return wxEmptyString;
217     }
218
219 protected:
220     id& value;
221 } ;
222
223 @implementation wxNSTableDataSource
224
225 - (id) init
226 {
227     self = [super init];
228     impl = nil;
229     return self;
230 }
231
232 - (void)setImplementation: (wxListWidgetCocoaImpl *) theImplementation
233 {
234     impl = theImplementation;
235 }
236
237 - (wxListWidgetCocoaImpl*) implementation
238 {
239     return impl;
240 }
241
242 - (NSInteger)numberOfRowsInTableView:(NSTableView *)aTableView
243 {
244     wxUnusedVar(aTableView);
245     if ( impl )
246         return impl->ListGetCount();
247     return 0;
248 }
249
250 - (id)tableView:(NSTableView *)aTableView
251         objectValueForTableColumn:(NSTableColumn *)aTableColumn
252         row:(NSInteger)rowIndex
253 {
254     wxUnusedVar(aTableView);
255     wxNSTableColumn* tablecol = (wxNSTableColumn *)aTableColumn;
256     wxListBox* lb = dynamic_cast<wxListBox*>(impl->GetWXPeer());
257     wxCocoaTableColumn* col = [tablecol column];
258     id value = nil;
259     wxNSTableViewCellValue cellvalue(value);
260     lb->GetValueCallback(rowIndex, col, cellvalue);
261     return value;
262 }
263
264 - (void)tableView:(NSTableView *)aTableView
265         setObjectValue:(id)value forTableColumn:(NSTableColumn *)aTableColumn
266         row:(NSInteger)rowIndex
267 {
268     wxUnusedVar(aTableView);
269     wxNSTableColumn* tablecol = (wxNSTableColumn *)aTableColumn;
270     wxListBox* lb = dynamic_cast<wxListBox*>(impl->GetWXPeer());
271     wxCocoaTableColumn* col = [tablecol column];
272     wxNSTableViewCellValue cellvalue(value);
273     lb->SetValueCallback(rowIndex, col, cellvalue);
274 }
275
276 @end
277
278 @implementation wxNSTableView
279
280 + (void)initialize
281 {
282     static BOOL initialized = NO;
283     if (!initialized)
284     {
285         initialized = YES;
286         wxOSXCocoaClassAddWXMethods( self );
287     }
288 }
289
290 - (void) tableViewSelectionDidChange: (NSNotification *) notification
291 {
292     wxUnusedVar(notification);
293     
294     int row = [self selectedRow];
295     
296     if (row == -1) 
297     {
298         // no row selected
299     } 
300     else 
301     {
302         wxWidgetCocoaImpl* impl = (wxWidgetCocoaImpl* ) wxWidgetImpl::FindFromWXWidget( self );
303         wxListBox *list = static_cast<wxListBox*> ( impl->GetWXPeer());
304         wxCHECK_RET( list != NULL , wxT("Listbox expected"));
305         
306         wxCommandEvent event( wxEVT_COMMAND_LISTBOX_SELECTED, list->GetId() );
307         
308         if ((row < 0) || (row > (int) list->GetCount()))  // OS X can select an item below the last item
309             return;
310         
311         if ( !list->MacGetBlockEvents() )
312             list->HandleLineEvent( row, false );
313     }
314     
315
316
317 - (void)setFont:(NSFont *)aFont
318 {
319     NSArray *tableColumns = [self tableColumns];
320     unsigned int columnIndex = [tableColumns count];
321     while (columnIndex--)
322         [[(NSTableColumn *)[tableColumns objectAtIndex:columnIndex] dataCell] setFont:aFont];
323
324     // todo introduce a common NSLayoutManager instance for all and use new method
325     [self setRowHeight:[aFont defaultLineHeightForFont]+2];
326 }
327
328 - (void) setControlSize:(NSControlSize) size
329 {
330     NSArray *tableColumns = [self tableColumns];
331     unsigned int columnIndex = [tableColumns count];
332     while (columnIndex--)
333         [[(NSTableColumn *)[tableColumns objectAtIndex:columnIndex] dataCell] setControlSize:size];
334 }
335
336 @end
337
338 //
339 //
340 //
341
342 wxListWidgetCocoaImpl::wxListWidgetCocoaImpl( wxWindowMac* peer, NSScrollView* view, wxNSTableView* tableview, wxNSTableDataSource* data ) :
343     wxWidgetCocoaImpl( peer, view ), m_tableView(tableview), m_dataSource(data)
344 {
345     InstallEventHandler( tableview );
346 }
347
348 wxListWidgetCocoaImpl::~wxListWidgetCocoaImpl()
349 {
350     [m_dataSource release];
351 }
352
353 unsigned int wxListWidgetCocoaImpl::ListGetCount() const
354 {
355     wxListBox* lb = dynamic_cast<wxListBox*> ( GetWXPeer() );
356     return lb->GetCount();
357 }
358
359 //
360 // columns
361 //
362
363 wxListWidgetColumn* wxListWidgetCocoaImpl::InsertTextColumn( unsigned pos, const wxString& WXUNUSED(title), bool editable,
364                                 wxAlignment WXUNUSED(just), int defaultWidth)
365 {
366     wxNSTableColumn* col1 = [[wxNSTableColumn alloc] init];
367     [col1 setEditable:editable];
368
369     unsigned formerColCount = [m_tableView numberOfColumns];
370
371     // there's apparently no way to insert at a specific position
372     [m_tableView addTableColumn:col1 ];
373     if ( pos < formerColCount )
374         [m_tableView moveColumn:formerColCount toColumn:pos];
375
376     if ( defaultWidth >= 0 )
377     {
378         [col1 setMaxWidth:defaultWidth];
379         [col1 setMinWidth:defaultWidth];
380         [col1 setWidth:defaultWidth];
381     }
382     else
383     {
384         [col1 setMaxWidth:1000];
385         [col1 setMinWidth:10];
386         // temporary hack, because I cannot get the automatic column resizing
387         // to work properly
388         [col1 setWidth:1000];
389     }
390     [col1 setResizingMask: NSTableColumnAutoresizingMask];
391     
392     wxListBox *list = static_cast<wxListBox*> ( GetWXPeer());
393     if ( list != NULL )
394         [[col1 dataCell] setFont:list->GetFont().OSXGetNSFont()];
395     
396     wxCocoaTableColumn* wxcol = new wxCocoaTableColumn( col1, editable );
397     [col1 setColumn:wxcol];
398
399     // owned by the tableview
400     [col1 release];
401     return wxcol;
402 }
403
404 wxListWidgetColumn* wxListWidgetCocoaImpl::InsertCheckColumn( unsigned pos , const wxString& WXUNUSED(title), bool editable,
405                                 wxAlignment WXUNUSED(just), int defaultWidth )
406 {
407    wxNSTableColumn* col1 = [[wxNSTableColumn alloc] init];
408     [col1 setEditable:editable];
409
410     // set your custom cell & set it up
411     NSButtonCell* checkbox = [[NSButtonCell alloc] init];
412     [checkbox setTitle:@""];
413     [checkbox setButtonType:NSSwitchButton];
414     [col1 setDataCell:checkbox] ;
415     
416     wxListBox *list = static_cast<wxListBox*> ( GetWXPeer());
417     if ( list != NULL )
418     {
419         NSControlSize size = NSRegularControlSize;
420         
421         switch ( list->GetWindowVariant() )
422         {
423             case wxWINDOW_VARIANT_NORMAL :
424                 size = NSRegularControlSize;
425                 break ;
426                 
427             case wxWINDOW_VARIANT_SMALL :
428                 size = NSSmallControlSize;
429                 break ;
430                 
431             case wxWINDOW_VARIANT_MINI :
432                 size = NSMiniControlSize;
433                 break ;
434                 
435             case wxWINDOW_VARIANT_LARGE :
436                 size = NSRegularControlSize;
437                 break ;
438                 
439             default:
440                 break ;
441         }
442
443         [[col1 dataCell] setControlSize:size];
444         // although there is no text, it may help to get the correct vertical layout
445         [[col1 dataCell] setFont:list->GetFont().OSXGetNSFont()];        
446     }
447
448     [checkbox release];
449
450     unsigned formerColCount = [m_tableView numberOfColumns];
451
452     // there's apparently no way to insert at a specific position
453     [m_tableView addTableColumn:col1 ];
454     if ( pos < formerColCount )
455         [m_tableView moveColumn:formerColCount toColumn:pos];
456
457     if ( defaultWidth >= 0 )
458     {
459         [col1 setMaxWidth:defaultWidth];
460         [col1 setMinWidth:defaultWidth];
461         [col1 setWidth:defaultWidth];
462     }
463
464     [col1 setResizingMask: NSTableColumnNoResizing];
465     wxCocoaTableColumn* wxcol = new wxCocoaTableColumn( col1, editable );
466     [col1 setColumn:wxcol];
467
468     // owned by the tableview
469     [col1 release];
470     return wxcol;
471 }
472
473
474 //
475 // inserting / removing lines
476 //
477
478 void wxListWidgetCocoaImpl::ListInsert( unsigned int WXUNUSED(n) )
479 {
480     [m_tableView reloadData];
481 }
482
483 void wxListWidgetCocoaImpl::ListDelete( unsigned int WXUNUSED(n) )
484 {
485     [m_tableView reloadData];
486 }
487
488 void wxListWidgetCocoaImpl::ListClear()
489 {
490     [m_tableView reloadData];
491 }
492
493 // selecting
494
495 void wxListWidgetCocoaImpl::ListDeselectAll()
496 {
497     [m_tableView deselectAll:nil];
498 }
499
500 void wxListWidgetCocoaImpl::ListSetSelection( unsigned int n, bool select, bool multi )
501 {
502     // TODO
503     if ( select )
504         [m_tableView selectRowIndexes:[NSIndexSet indexSetWithIndex:n]
505                      byExtendingSelection:multi];
506     else
507         [m_tableView deselectRow: n];
508
509 }
510
511 int wxListWidgetCocoaImpl::ListGetSelection() const
512 {
513     return [m_tableView selectedRow];
514 }
515
516 int wxListWidgetCocoaImpl::ListGetSelections( wxArrayInt& aSelections ) const
517 {
518     aSelections.Empty();
519
520     int count = ListGetCount();
521
522     for ( int i = 0; i < count; ++i)
523     {
524         if ([m_tableView isRowSelected:i])
525         aSelections.Add(i);
526     }
527
528     return aSelections.Count();
529 }
530
531 bool wxListWidgetCocoaImpl::ListIsSelected( unsigned int n ) const
532 {
533     return [m_tableView isRowSelected:n];
534 }
535
536 // display
537
538 void wxListWidgetCocoaImpl::ListScrollTo( unsigned int n )
539 {
540     [m_tableView scrollRowToVisible:n];
541 }
542
543
544 void wxListWidgetCocoaImpl::UpdateLine( unsigned int WXUNUSED(n), wxListWidgetColumn* WXUNUSED(col) )
545 {
546     // TODO optimize
547     [m_tableView reloadData];
548 }
549
550 void wxListWidgetCocoaImpl::UpdateLineToEnd( unsigned int WXUNUSED(n))
551 {
552     // TODO optimize
553     [m_tableView reloadData];
554 }
555
556 void wxListWidgetCocoaImpl::controlDoubleAction(WXWidget WXUNUSED(slf),void* WXUNUSED(_cmd), void *WXUNUSED(sender))
557 {
558     wxListBox *list = static_cast<wxListBox*> ( GetWXPeer());
559     wxCHECK_RET( list != NULL , wxT("Listbox expected"));
560
561     int sel = [m_tableView clickedRow];
562     if ((sel < 0) || (sel > (int) list->GetCount()))  // OS X can select an item below the last item (why?)
563        return;
564
565     list->HandleLineEvent( sel, true );
566 }
567
568 // accessing content
569
570
571 wxWidgetImplType* wxWidgetImpl::CreateListBox( wxWindowMac* wxpeer,
572                                     wxWindowMac* WXUNUSED(parent),
573                                     wxWindowID WXUNUSED(id),
574                                     const wxPoint& pos,
575                                     const wxSize& size,
576                                     long style,
577                                     long WXUNUSED(extraStyle))
578 {
579     NSRect r = wxOSXGetFrameForControl( wxpeer, pos , size ) ;
580     NSScrollView* scrollview = [[NSScrollView alloc] initWithFrame:r];
581
582     // use same scroll flags logic as msw
583
584     [scrollview setHasVerticalScroller:YES];
585
586     if ( style & wxLB_HSCROLL )
587         [scrollview setHasHorizontalScroller:YES];
588
589     [scrollview setAutohidesScrollers: ((style & wxLB_ALWAYS_SB) ? NO : YES)];
590
591     // setting up the true table
592
593     wxNSTableView* tableview = [[wxNSTableView alloc] init];
594     [tableview setDelegate:tableview];
595     // only one multi-select mode available
596     if ( (style & wxLB_EXTENDED) || (style & wxLB_MULTIPLE) )
597         [tableview setAllowsMultipleSelection:YES];
598
599     // simple listboxes have no header row
600     [tableview setHeaderView:nil];
601
602     if ( style & wxLB_HSCROLL )
603         [tableview setColumnAutoresizingStyle:NSTableViewNoColumnAutoresizing];
604     else
605         [tableview setColumnAutoresizingStyle:NSTableViewLastColumnOnlyAutoresizingStyle];
606
607     wxNSTableDataSource* ds = [[ wxNSTableDataSource alloc] init];
608     [tableview setDataSource:ds];
609     [scrollview setDocumentView:tableview];
610     [tableview release];
611
612     wxListWidgetCocoaImpl* c = new wxListWidgetCocoaImpl( wxpeer, scrollview, tableview, ds );
613
614     // temporary hook for dnd
615  //   [tableview registerForDraggedTypes:[NSArray arrayWithObjects:
616  //       NSStringPboardType, NSFilenamesPboardType, (NSString*) kPasteboardTypeFileURLPromise, NSTIFFPboardType, NSPICTPboardType, NSPDFPboardType, nil]];
617
618     [ds setImplementation:c];
619     return c;
620 }
621
622 int wxListWidgetCocoaImpl::DoListHitTest(const wxPoint& inpoint) const
623 {
624     // translate inpoint to listpoint via scrollview
625     NSPoint p = wxToNSPoint( m_osxView, inpoint );
626     p = [m_osxView convertPoint:p toView:m_tableView];
627     // hittest using new point
628     NSInteger i = [m_tableView rowAtPoint:p];
629     return i;
630 }
631
632 #endif // wxUSE_LISTBOX