]> git.saurik.com Git - wxWidgets.git/blob - src/mac/carbon/listbox.cpp
cleanup mac
[wxWidgets.git] / src / mac / carbon / listbox.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: src/mac/carbon/listbox.cpp
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
18 #ifndef WX_PRECOMP
19 #include "wx/log.h"
20 #include "wx/intl.h"
21 #include "wx/utils.h"
22 #include "wx/settings.h"
23 #include "wx/arrstr.h"
24 #include "wx/dcclient.h"
25 #endif
26
27 IMPLEMENT_DYNAMIC_CLASS(wxListBox, wxControlWithItems)
28
29 BEGIN_EVENT_TABLE(wxListBox, wxControl)
30 END_EVENT_TABLE()
31
32 #include "wx/mac/uma.h"
33
34 // ============================================================================
35 // list box control implementation
36 // ============================================================================
37
38 wxListBox::wxListBox()
39 {
40 }
41
42 bool wxListBox::Create(
43 wxWindow *parent,
44 wxWindowID id,
45 const wxPoint& pos,
46 const wxSize& size,
47 const wxArrayString& choices,
48 long style,
49 const wxValidator& validator,
50 const wxString& name )
51 {
52 wxCArrayString chs(choices);
53
54 return Create(
55 parent, id, pos, size, chs.GetCount(), chs.GetStrings(),
56 style, validator, name );
57 }
58
59 wxMacListControl* wxListBox::GetPeer() const
60 {
61 wxMacDataBrowserListControl *lb = wxDynamicCast(m_peer,wxMacDataBrowserListControl);
62 return lb ? wx_static_cast(wxMacListControl*,lb) : 0 ;
63 }
64
65 bool wxListBox::Create(
66 wxWindow *parent,
67 wxWindowID id,
68 const wxPoint& pos,
69 const wxSize& size,
70 int n,
71 const wxString choices[],
72 long style,
73 const wxValidator& validator,
74 const wxString& name )
75 {
76 m_macIsUserPane = false;
77
78 wxASSERT_MSG( !(style & wxLB_MULTIPLE) || !(style & wxLB_EXTENDED),
79 wxT("only a single listbox selection mode can be specified") );
80
81 if ( !wxListBoxBase::Create( parent, id, pos, size, style & ~(wxHSCROLL | wxVSCROLL), validator, name ) )
82 return false;
83
84 wxMacDataBrowserListControl* control = new wxMacDataBrowserListControl( this, pos, size, style );
85 // TODO CHECK control->SetClientDataType( m_clientDataItemsType );
86 m_peer = control;
87
88 MacPostControlCreate( pos, size );
89
90 Append(n, choices);
91
92 // Needed because it is a wxControlWithItems
93 SetInitialSize( size );
94
95 return true;
96 }
97
98 wxListBox::~wxListBox()
99 {
100 FreeData();
101 m_peer->SetReference( 0 );
102 }
103
104 void wxListBox::FreeData()
105 {
106 GetPeer()->MacClear();
107 }
108
109 void wxListBox::DoSetFirstItem(int n)
110 {
111 GetPeer()->MacScrollTo( n );
112 }
113
114 void wxListBox::EnsureVisible(int n)
115 {
116 GetPeer()->MacScrollTo( n );
117 }
118
119 void wxListBox::DoDeleteOneItem(unsigned int n)
120 {
121 wxCHECK_RET( IsValid(n), wxT("invalid index in wxListBox::Delete") );
122
123 GetPeer()->MacDelete( n );
124 }
125
126 int wxListBox::DoInsertItems(const wxArrayStringsAdapter& items,
127 unsigned int pos,
128 void **clientData,
129 wxClientDataType type)
130 {
131 InvalidateBestSize();
132
133 GetPeer()->MacInsert( pos, items );
134 const unsigned int count = items.GetCount();
135 if ( clientData )
136 {
137 for (unsigned int i = 0; i < count; ++i)
138 AssignNewItemClientData( pos + i, clientData, i, type );
139 }
140
141 return pos + count - 1;
142 }
143
144 int wxListBox::FindString(const wxString& s, bool bCase) const
145 {
146 for ( size_t i = 0; i < GetCount(); ++ i )
147 {
148 if (s.IsSameAs( GetString( i ), bCase) )
149 return (int)i;
150 }
151
152 return wxNOT_FOUND;
153 }
154
155 void wxListBox::DoClear()
156 {
157 FreeData();
158 }
159
160 void wxListBox::DoSetSelection(int n, bool select)
161 {
162 wxCHECK_RET( n == wxNOT_FOUND || IsValid(n),
163 wxT("invalid index in wxListBox::SetSelection") );
164
165 if ( n == wxNOT_FOUND )
166 GetPeer()->MacDeselectAll();
167 else
168 GetPeer()->MacSetSelection( n, select, HasMultipleSelection() );
169 }
170
171 bool wxListBox::IsSelected(int n) const
172 {
173 wxCHECK_MSG( IsValid(n), false, wxT("invalid index in wxListBox::Selected") );
174
175 return GetPeer()->MacIsSelected( n );
176 }
177
178 void *wxListBox::DoGetItemClientData(unsigned int n) const
179 {
180 wxCHECK_MSG( IsValid(n), NULL, wxT("invalid index in wxListBox::GetClientData"));
181 return GetPeer()->MacGetClientData( n );
182 }
183
184 void wxListBox::DoSetItemClientData(unsigned int n, void *clientData)
185 {
186 wxCHECK_RET( IsValid(n), wxT("invalid index in wxListBox::SetClientData") );
187 GetPeer()->MacSetClientData( n , clientData);
188 }
189
190 // Return number of selections and an array of selected integers
191 int wxListBox::GetSelections(wxArrayInt& aSelections) const
192 {
193 return GetPeer()->MacGetSelections( aSelections );
194 }
195
196 // Get single selection, for single choice list items
197 int wxListBox::GetSelection() const
198 {
199 return GetPeer()->MacGetSelection();
200 }
201
202 // Find string for position
203 wxString wxListBox::GetString(unsigned int n) const
204 {
205 wxCHECK_MSG( IsValid(n), wxEmptyString, wxT("invalid index in wxListBox::GetString") );
206 return GetPeer()->MacGetString(n);
207 }
208
209 void wxListBox::SetString(unsigned int n, const wxString& s)
210 {
211 GetPeer()->MacSetString( n, s );
212 }
213
214 wxSize wxListBox::DoGetBestSize() const
215 {
216 int lbWidth = 100; // some defaults
217 int lbHeight = 110;
218 int wLine;
219
220 {
221 #if wxMAC_USE_CORE_GRAPHICS
222 wxClientDC dc(const_cast<wxListBox*>(this));
223 dc.SetFont(GetFont());
224 #else
225 wxMacPortStateHelper st( UMAGetWindowPort( (WindowRef)MacGetTopLevelWindowRef() ) );
226
227 // TODO: clean this up
228 if ( m_font.Ok() )
229 {
230 ::TextFont( m_font.MacGetFontNum() );
231 ::TextSize( m_font.MacGetFontSize() );
232 ::TextFace( m_font.MacGetFontStyle() );
233 }
234 else
235 {
236 ::TextFont( kFontIDMonaco );
237 ::TextSize( 9 );
238 ::TextFace( 0 );
239 }
240 #endif
241 // Find the widest line
242 for (unsigned int i = 0; i < GetCount(); i++)
243 {
244 wxString str( GetString( i ) );
245 #if wxMAC_USE_CORE_GRAPHICS
246 wxCoord width, height ;
247 dc.GetTextExtent( str , &width, &height);
248 wLine = width ;
249 #else
250 #if wxUSE_UNICODE
251 Point bounds = {0, 0};
252 SInt16 baseline;
253
254 // NB: what if m_font.Ok() == false ???
255 ::GetThemeTextDimensions(
256 wxMacCFStringHolder( str, m_font.GetEncoding() ),
257 kThemeCurrentPortFont,
258 kThemeStateActive,
259 false,
260 &bounds,
261 &baseline );
262 wLine = bounds.h;
263 #else
264 wLine = ::TextWidth( str.c_str(), 0, str.length() );
265 #endif
266 #endif
267 lbWidth = wxMax( lbWidth, wLine );
268 }
269
270 // Add room for the scrollbar
271 lbWidth += wxSystemSettings::GetMetric( wxSYS_VSCROLL_X );
272
273 // And just a bit more
274 int cy = 12;
275 #if wxMAC_USE_CORE_GRAPHICS
276 wxCoord width, height ;
277 dc.GetTextExtent( wxT("XX") , &width, &height);
278 int cx = width ;
279 #else
280 int cx = ::TextWidth( "XX", 0, 1 );
281 #endif
282 lbWidth += cx;
283
284 // don't make the listbox too tall (limit height to around 10 items)
285 // but don't make it too small neither
286 lbHeight = wxMax( (cy + 4) * wxMin( wxMax( GetCount(), 3 ), 10 ), 70 );
287 }
288
289 return wxSize( lbWidth, lbHeight );
290 }
291
292 unsigned int wxListBox::GetCount() const
293 {
294 return GetPeer()->MacGetCount();
295 }
296
297 void wxListBox::Refresh(bool eraseBack, const wxRect *rect)
298 {
299 wxControl::Refresh( eraseBack, rect );
300 }
301
302 // Some custom controls depend on this
303 /* static */ wxVisualAttributes
304 wxListBox::GetClassDefaultAttributes(wxWindowVariant WXUNUSED(variant))
305 {
306 wxVisualAttributes attr;
307
308 attr.colFg = wxSystemSettings::GetColour( wxSYS_COLOUR_WINDOWTEXT );
309 attr.colBg = wxSystemSettings::GetColour( wxSYS_COLOUR_LISTBOX );
310 attr.font = wxSystemSettings::GetFont( wxSYS_DEFAULT_GUI_FONT );
311
312 return attr;
313 }
314
315 int wxListBox::DoListHitTest(const wxPoint& inpoint) const
316 {
317 OSStatus err;
318
319 // There are few reasons why this is complicated:
320 // 1) There is no native HitTest function for Mac
321 // 2) GetDataBrowserItemPartBounds only works on visible items
322 // 3) We can't do it through GetDataBrowserTableView[Item]RowHeight
323 // because what it returns is basically inaccurate in the context
324 // of the coordinates we want here, but we use this as a guess
325 // for where the first visible item lies
326
327 wxPoint point = inpoint;
328
329 // get column property ID (req. for call to itempartbounds)
330 DataBrowserTableViewColumnID colId = 0;
331 err = GetDataBrowserTableViewColumnProperty(m_peer->GetControlRef(), 0, &colId);
332 wxCHECK_MSG(err == noErr, wxNOT_FOUND, wxT("Unexpected error from GetDataBrowserTableViewColumnProperty"));
333
334 // OK, first we need to find the first visible item we have -
335 // this will be the "low" for our binary search. There is no real
336 // easy way around this, as we will need to do a SLOW linear search
337 // until we find a visible item, but we can do a cheap calculation
338 // via the row height to speed things up a bit
339 UInt32 scrollx, scrolly;
340 err = GetDataBrowserScrollPosition(m_peer->GetControlRef(), &scrollx, &scrolly);
341 wxCHECK_MSG(err == noErr, wxNOT_FOUND, wxT("Unexpected error from GetDataBrowserScrollPosition"));
342
343 UInt16 height;
344 err = GetDataBrowserTableViewRowHeight(m_peer->GetControlRef(), &height);
345 wxCHECK_MSG(err == noErr, wxNOT_FOUND, wxT("Unexpected error from GetDataBrowserTableViewRowHeight"));
346
347 // these indices are 0-based, as usual, so we need to add 1 to them when
348 // passing them to data browser functions which use 1-based indices
349 int low = scrolly / height,
350 high = GetCount() - 1;
351
352 // search for the first visible item (note that the scroll guess above
353 // is the low bounds of where the item might lie so we only use that as a
354 // starting point - we should reach it within 1 or 2 iterations of the loop)
355 while ( low <= high )
356 {
357 Rect bounds;
358 err = GetDataBrowserItemPartBounds(
359 m_peer->GetControlRef(), low + 1, colId,
360 kDataBrowserPropertyEnclosingPart,
361 &bounds); // note +1 to translate to Mac ID
362 if ( err == noErr )
363 break;
364
365 // errDataBrowserItemNotFound is expected as it simply means that the
366 // item is not currently visible -- but other errors are not
367 wxCHECK_MSG( err == errDataBrowserItemNotFound, wxNOT_FOUND,
368 wxT("Unexpected error from GetDataBrowserItemPartBounds") );
369
370 low++;
371 }
372
373 // NOW do a binary search for where the item lies, searching low again if
374 // we hit an item that isn't visible
375 while ( low <= high )
376 {
377 int mid = (low + high) / 2;
378
379 Rect bounds;
380 err = GetDataBrowserItemPartBounds(
381 m_peer->GetControlRef(), mid + 1, colId,
382 kDataBrowserPropertyEnclosingPart,
383 &bounds); //note +1 to trans to mac id
384 wxCHECK_MSG( err == noErr || err == errDataBrowserItemNotFound,
385 wxNOT_FOUND,
386 wxT("Unexpected error from GetDataBrowserItemPartBounds") );
387
388 if ( err == errDataBrowserItemNotFound )
389 {
390 // item not visible, attempt to find a visible one
391 // search lower
392 high = mid - 1;
393 }
394 else // visible item, do actual hitttest
395 {
396 // if point is within the bounds, return this item (since we assume
397 // all x coords of items are equal we only test the x coord in
398 // equality)
399 if ((point.x >= bounds.left && point.x <= bounds.right) &&
400 (point.y >= bounds.top && point.y <= bounds.bottom) )
401 {
402 // found!
403 return mid;
404 }
405
406 if ( point.y < bounds.top )
407 // index(bounds) greater then key(point)
408 high = mid - 1;
409 else
410 // index(bounds) less then key(point)
411 low = mid + 1;
412 }
413 }
414
415 return wxNOT_FOUND;
416 }
417
418 // ============================================================================
419 // data browser based implementation
420 // ============================================================================
421
422 wxMacListBoxItem::wxMacListBoxItem()
423 :wxMacDataItem()
424 {
425 }
426
427 wxMacListBoxItem::~wxMacListBoxItem()
428 {
429 }
430
431 void wxMacListBoxItem::Notification(wxMacDataItemBrowserControl *owner ,
432 DataBrowserItemNotification message,
433 DataBrowserItemDataRef WXUNUSED(itemData) ) const
434 {
435 wxMacDataBrowserListControl *lb = wxDynamicCast(owner,wxMacDataBrowserListControl);
436
437 // we want to depend on as little as possible to make sure tear-down of controls is safe
438
439 if ( message == kDataBrowserItemRemoved)
440 {
441 if ( lb != NULL && lb->GetClientDataType() == wxClientData_Object )
442 {
443 delete (wxClientData*) (m_data);
444 }
445
446 delete this;
447 return;
448 }
449
450 wxListBox *list = wxDynamicCast( owner->GetPeer() , wxListBox );
451 wxCHECK_RET( list != NULL , wxT("Listbox expected"));
452
453 bool trigger = false;
454 wxCommandEvent event( wxEVT_COMMAND_LISTBOX_SELECTED, list->GetId() );
455 switch (message)
456 {
457 case kDataBrowserItemDeselected:
458 if ( list->HasMultipleSelection() )
459 trigger = !lb->IsSelectionSuppressed();
460 break;
461
462 case kDataBrowserItemSelected:
463 trigger = !lb->IsSelectionSuppressed();
464 break;
465
466 case kDataBrowserItemDoubleClicked:
467 event.SetEventType( wxEVT_COMMAND_LISTBOX_DOUBLECLICKED );
468 trigger = true;
469 break;
470
471 default:
472 break;
473 }
474
475 if ( trigger )
476 {
477 event.SetEventObject( list );
478 if ( list->HasClientObjectData() )
479 event.SetClientObject( (wxClientData*) m_data );
480 else if ( list->HasClientUntypedData() )
481 event.SetClientData( m_data );
482 event.SetString( m_label );
483 event.SetInt( owner->GetLineFromItem( this ) );
484 event.SetExtraLong( list->HasMultipleSelection() ? message == kDataBrowserItemSelected : true );
485
486 // direct notification is not always having the listbox GetSelection()
487 // having in synch with event, so use wxPostEvent instead
488 // list->GetEventHandler()->ProcessEvent(event);
489
490 wxPostEvent( list->GetEventHandler(), event );
491 }
492 }
493
494 IMPLEMENT_DYNAMIC_CLASS( wxMacDataBrowserListControl , wxMacDataItemBrowserControl )
495
496 wxMacDataBrowserListControl::wxMacDataBrowserListControl( wxWindow *peer, const wxPoint& pos, const wxSize& size, long style)
497 : wxMacDataItemBrowserControl( peer, pos, size, style )
498 {
499 OSStatus err = noErr;
500 m_clientDataItemsType = wxClientData_None;
501 if ( style & wxLB_SORT )
502 m_sortOrder = SortOrder_Text_Ascending;
503
504 DataBrowserSelectionFlags options = kDataBrowserDragSelect;
505 if ( style & wxLB_MULTIPLE )
506 {
507 options |= kDataBrowserAlwaysExtendSelection | kDataBrowserCmdTogglesSelection;
508 }
509 else if ( style & wxLB_EXTENDED )
510 {
511 options |= kDataBrowserCmdTogglesSelection;
512 }
513 else
514 {
515 options |= kDataBrowserSelectOnlyOne;
516 }
517 err = SetSelectionFlags( options );
518 verify_noerr( err );
519
520 DataBrowserListViewColumnDesc columnDesc;
521 columnDesc.headerBtnDesc.titleOffset = 0;
522 columnDesc.headerBtnDesc.version = kDataBrowserListViewLatestHeaderDesc;
523
524 columnDesc.headerBtnDesc.btnFontStyle.flags =
525 kControlUseFontMask | kControlUseJustMask;
526
527 columnDesc.headerBtnDesc.btnContentInfo.contentType = kControlNoContent;
528 columnDesc.headerBtnDesc.btnFontStyle.just = teFlushDefault;
529 columnDesc.headerBtnDesc.btnFontStyle.font = kControlFontViewSystemFont;
530 columnDesc.headerBtnDesc.btnFontStyle.style = normal;
531 columnDesc.headerBtnDesc.titleString = NULL;
532
533 columnDesc.headerBtnDesc.minimumWidth = 0;
534 columnDesc.headerBtnDesc.maximumWidth = 10000;
535
536 columnDesc.propertyDesc.propertyID = kTextColumnId;
537 columnDesc.propertyDesc.propertyType = kDataBrowserTextType;
538 columnDesc.propertyDesc.propertyFlags = kDataBrowserTableViewSelectionColumn;
539 columnDesc.propertyDesc.propertyFlags |= kDataBrowserListViewTypeSelectColumn;
540
541 verify_noerr( AddColumn( &columnDesc, kDataBrowserListViewAppendColumn ) );
542
543 columnDesc.headerBtnDesc.minimumWidth = 0;
544 columnDesc.headerBtnDesc.maximumWidth = 0;
545 columnDesc.propertyDesc.propertyID = kNumericOrderColumnId;
546 columnDesc.propertyDesc.propertyType = kDataBrowserPropertyRelevanceRankPart;
547 columnDesc.propertyDesc.propertyFlags = kDataBrowserTableViewSelectionColumn;
548 columnDesc.propertyDesc.propertyFlags |= kDataBrowserListViewTypeSelectColumn;
549
550 verify_noerr( AddColumn( &columnDesc, kDataBrowserListViewAppendColumn ) );
551
552 SetDataBrowserSortProperty( m_controlRef , kTextColumnId);
553 if ( m_sortOrder == SortOrder_Text_Ascending )
554 {
555 SetDataBrowserSortProperty( m_controlRef , kTextColumnId);
556 SetDataBrowserSortOrder( m_controlRef , kDataBrowserOrderIncreasing);
557 }
558 else
559 {
560 SetDataBrowserSortProperty( m_controlRef , kNumericOrderColumnId);
561 SetDataBrowserSortOrder( m_controlRef , kDataBrowserOrderIncreasing);
562 }
563
564 verify_noerr( AutoSizeColumns() );
565 verify_noerr( SetHiliteStyle(kDataBrowserTableViewFillHilite ) );
566 verify_noerr( SetHeaderButtonHeight( 0 ) );
567 err = SetHasScrollBars( (style & wxHSCROLL) != 0 , true );
568 #if 0
569 // shouldn't be necessary anymore under 10.2
570 m_peer->SetData( kControlNoPart, kControlDataBrowserIncludesFrameAndFocusTag, (Boolean)false );
571 m_peer->SetNeedsFocusRect( true );
572 #endif
573 }
574
575 wxMacDataBrowserListControl::~wxMacDataBrowserListControl()
576 {
577 }
578
579 wxWindow * wxMacDataBrowserListControl::GetPeer() const
580 {
581 return wxDynamicCast( wxMacControl::GetPeer() , wxWindow );
582 }
583
584 wxMacDataItem* wxMacDataBrowserListControl::CreateItem()
585 {
586 return new wxMacListBoxItem();
587 }
588
589 #if 0
590
591 // in case we need that one day
592
593 // ============================================================================
594 // HIView owner-draw-based implementation
595 // ============================================================================
596
597 static pascal void ListBoxDrawProc(
598 ControlRef browser, DataBrowserItemID item, DataBrowserPropertyID property,
599 DataBrowserItemState itemState, const Rect *itemRect, SInt16 depth, Boolean isColorDevice )
600 {
601 CFStringRef cfString;
602 ThemeDrawingState themeState;
603 long systemVersion;
604
605 GetThemeDrawingState( &themeState );
606 cfString = CFStringCreateWithFormat( NULL, NULL, CFSTR("Row %d"), item );
607
608 // In this sample we handle the "selected" state; all others fall through to our "active" state
609 if ( itemState == kDataBrowserItemIsSelected )
610 {
611 ThemeBrush colorBrushID;
612
613 // TODO: switch over to wxSystemSettingsNative::GetColour() when kThemeBrushSecondaryHighlightColor
614 // is incorporated Panther DB starts using kThemeBrushSecondaryHighlightColor
615 // for inactive browser highlighting
616 Gestalt( gestaltSystemVersion, &systemVersion );
617 if ( (systemVersion >= 0x00001030) && !IsControlActive( browser ) )
618 colorBrushID = kThemeBrushSecondaryHighlightColor;
619 else
620 colorBrushID = kThemeBrushPrimaryHighlightColor;
621
622 // First paint the hilite rect, then the text on top
623 SetThemePen( colorBrushID, 32, true );
624 PaintRect( itemRect );
625 SetThemeDrawingState( themeState, false );
626 }
627
628 DrawThemeTextBox( cfString, kThemeApplicationFont, kThemeStateActive, true, itemRect, teFlushDefault, NULL );
629 SetThemeDrawingState( themeState, true );
630
631 if ( cfString != NULL )
632 CFRelease( cfString );
633 }
634
635 #endif
636
637
638 #endif // wxUSE_LISTBOX