1 /////////////////////////////////////////////////////////////////////////////
2 // Name:        src/gtk/listbox.cpp
3 // Purpose:
4 // Author:      Robert Roebling
5 // Modified By: Ryan Norton (GtkTreeView implementation)
6 // Copyright:   (c) 1998 Robert Roebling
7 // Licence:     wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
9 
10 // For compilers that support precompilation, includes "wx.h".
11 #include "wx/wxprec.h"
12 
13 #if wxUSE_LISTBOX
14 
15 #include "wx/listbox.h"
16 
17 #ifndef WX_PRECOMP
18     #include "wx/dynarray.h"
19     #include "wx/intl.h"
20     #include "wx/log.h"
21     #include "wx/utils.h"
22     #include "wx/settings.h"
23     #include "wx/checklst.h"
24     #include "wx/arrstr.h"
25 #endif
26 
27 #if wxUSE_TOOLTIPS
28     #include "wx/tooltip.h"
29 #endif
30 
31 #include "wx/gtk/private.h"
32 #include "wx/gtk/private/eventsdisabler.h"
33 #include "wx/gtk/private/object.h"
34 #include "wx/gtk/private/treeentry_gtk.h"
35 #include "wx/gtk/private/treeview.h"
36 
37 //-----------------------------------------------------------------------------
38 // data
39 //-----------------------------------------------------------------------------
40 
41 extern bool           g_blockEventsOnDrag;
42 extern bool           g_blockEventsOnScroll;
43 
44 
45 
46 //-----------------------------------------------------------------------------
47 // Macro to tell which row the strings are in (1 if native checklist, 0 if not)
48 //-----------------------------------------------------------------------------
49 
50 #if wxUSE_CHECKLISTBOX
51 #   define WXLISTBOX_DATACOLUMN_ARG(x)  (x->m_hasCheckBoxes ? 1 : 0)
52 #else
53 #   define WXLISTBOX_DATACOLUMN_ARG(x)  (0)
54 #endif // wxUSE_CHECKLISTBOX
55 
56 #define WXLISTBOX_DATACOLUMN    WXLISTBOX_DATACOLUMN_ARG(this)
57 
58 // ----------------------------------------------------------------------------
59 // helper functions
60 // ----------------------------------------------------------------------------
61 
62 namespace
63 {
64 
65 // Return the entry for the given listbox item.
66 wxTreeEntry *
GetEntry(GtkListStore * store,GtkTreeIter * iter,const wxListBox * listbox)67 GetEntry(GtkListStore *store, GtkTreeIter *iter, const wxListBox *listbox)
68 {
69     wxTreeEntry* entry;
70     gtk_tree_model_get(GTK_TREE_MODEL(store),
71                        iter,
72                        WXLISTBOX_DATACOLUMN_ARG(listbox),
73                        &entry,
74                        -1);
75     g_object_unref(entry);
76     return entry;
77 }
78 
79 } // anonymous namespace
80 
81 //-----------------------------------------------------------------------------
82 // "row-activated"
83 //-----------------------------------------------------------------------------
84 
85 extern "C" {
86 static void
gtk_listbox_row_activated_callback(GtkTreeView * WXUNUSED (treeview),GtkTreePath * path,GtkTreeViewColumn * WXUNUSED (col),wxListBox * listbox)87 gtk_listbox_row_activated_callback(GtkTreeView        * WXUNUSED(treeview),
88                                    GtkTreePath        *path,
89                                    GtkTreeViewColumn  * WXUNUSED(col),
90                                    wxListBox          *listbox)
91 {
92     if (g_blockEventsOnDrag) return;
93     if (g_blockEventsOnScroll) return;
94 
95     // This is triggered by either a double-click or a space press
96 
97     int sel = gtk_tree_path_get_indices(path)[0];
98 
99     listbox->GTKOnActivated(sel);
100 }
101 }
102 
103 //-----------------------------------------------------------------------------
104 // "changed"
105 //-----------------------------------------------------------------------------
106 
107 extern "C" {
108 static void
gtk_listitem_changed_callback(GtkTreeSelection * WXUNUSED (selection),wxListBox * listbox)109 gtk_listitem_changed_callback(GtkTreeSelection * WXUNUSED(selection),
110                               wxListBox *listbox )
111 {
112     if (g_blockEventsOnDrag) return;
113 
114     listbox->GTKOnSelectionChanged();
115 }
116 
117 }
118 
119 //-----------------------------------------------------------------------------
120 // "key_press_event"
121 //-----------------------------------------------------------------------------
122 
123 extern "C" {
124 static gboolean
gtk_listbox_key_press_callback(GtkWidget * WXUNUSED (widget),GdkEventKey * gdk_event,wxListBox * listbox)125 gtk_listbox_key_press_callback( GtkWidget *WXUNUSED(widget),
126                                 GdkEventKey *gdk_event,
127                                 wxListBox *listbox )
128 {
129     if ((gdk_event->keyval == GDK_KEY_Return) ||
130         (gdk_event->keyval == GDK_KEY_ISO_Enter) ||
131         (gdk_event->keyval == GDK_KEY_KP_Enter))
132     {
133         int index = -1;
134         if (!listbox->HasMultipleSelection())
135             index = listbox->GetSelection();
136         else
137         {
138             wxArrayInt sels;
139             if (listbox->GetSelections( sels ) < 1)
140                 return FALSE;
141             index = sels[0];
142         }
143 
144         if (index != wxNOT_FOUND)
145         {
146             listbox->GTKOnActivated(index);
147 
148 //          wxMac and wxMSW always invoke default action
149 //          if (!ret)
150             {
151                 // DClick not handled -> invoke default action
152                 wxWindow *tlw = wxGetTopLevelParent( listbox );
153                 if (tlw)
154                 {
155                     GtkWindow *gtk_window = GTK_WINDOW( tlw->GetHandle() );
156                     if (gtk_window)
157                         gtk_window_activate_default( gtk_window );
158                 }
159             }
160 
161             // Always intercept, otherwise we'd get another dclick
162             // event from row_activated
163             return TRUE;
164         }
165     }
166 
167     return FALSE;
168 }
169 }
170 
171 //-----------------------------------------------------------------------------
172 // GtkTreeEntry destruction (to destroy client data)
173 //-----------------------------------------------------------------------------
174 
175 extern "C" {
tree_entry_destroy_cb(wxTreeEntry * entry,wxListBox * listbox)176 static void tree_entry_destroy_cb(wxTreeEntry* entry,
177                                       wxListBox* listbox)
178 {
179     if (listbox->HasClientObjectData())
180     {
181         void* userdata = wx_tree_entry_get_userdata(entry);
182         if (userdata)
183             delete (wxClientData *)userdata;
184     }
185 }
186 }
187 
188 //-----------------------------------------------------------------------------
189 // Sorting callback (standard CmpNoCase return value)
190 //-----------------------------------------------------------------------------
191 
192 extern "C" {
193 static int
sort_callback(GtkTreeModel *,GtkTreeIter * a,GtkTreeIter * b,void * data)194 sort_callback(GtkTreeModel*, GtkTreeIter* a, GtkTreeIter* b, void* data)
195 {
196     wxListBox* listbox = static_cast<wxListBox*>(data);
197     wxTreeEntry* entry1 = GetEntry(listbox->m_liststore, a, listbox);
198     wxCHECK_MSG(entry1, 0, wxT("Could not get first entry"));
199 
200     wxTreeEntry* entry2 = GetEntry(listbox->m_liststore, b, listbox);
201     wxCHECK_MSG(entry2, 0, wxT("Could not get second entry"));
202 
203     //We compare collate keys here instead of calling g_utf8_collate
204     //as it is rather slow (and even the docs recommend this)
205     return strcmp(wx_tree_entry_get_collate_key(entry1),
206                   wx_tree_entry_get_collate_key(entry2)) >= 0;
207 }
208 }
209 
210 //-----------------------------------------------------------------------------
211 // Searching callback (TRUE == not equal, FALSE == equal)
212 //-----------------------------------------------------------------------------
213 
214 extern "C" {
215 static gboolean
search_callback(GtkTreeModel *,int,const char * key,GtkTreeIter * iter,void * data)216 search_callback(GtkTreeModel*, int, const char* key, GtkTreeIter* iter, void* data)
217 {
218     wxListBox* listbox = static_cast<wxListBox*>(data);
219     wxTreeEntry* entry = GetEntry(listbox->m_liststore, iter, listbox);
220     wxCHECK_MSG(entry, true, "could not get entry");
221 
222     wxGtkString keyc(g_utf8_collate_key(key, -1));
223 
224     return strncmp(keyc, wx_tree_entry_get_collate_key(entry), strlen(keyc));
225 }
226 }
227 
228 //-----------------------------------------------------------------------------
229 // wxListBox
230 //-----------------------------------------------------------------------------
231 
232 // ----------------------------------------------------------------------------
233 // construction
234 // ----------------------------------------------------------------------------
235 
Init()236 void wxListBox::Init()
237 {
238     m_treeview = NULL;
239 #if wxUSE_CHECKLISTBOX
240     m_hasCheckBoxes = false;
241 #endif // wxUSE_CHECKLISTBOX
242 }
243 
Create(wxWindow * parent,wxWindowID id,const wxPoint & pos,const wxSize & size,const wxArrayString & choices,long style,const wxValidator & validator,const wxString & name)244 bool wxListBox::Create( wxWindow *parent, wxWindowID id,
245                         const wxPoint &pos, const wxSize &size,
246                         const wxArrayString& choices,
247                         long style, const wxValidator& validator,
248                         const wxString &name )
249 {
250     wxCArrayString chs(choices);
251 
252     return Create( parent, id, pos, size, chs.GetCount(), chs.GetStrings(),
253                    style, validator, name );
254 }
255 
Create(wxWindow * parent,wxWindowID id,const wxPoint & pos,const wxSize & size,int n,const wxString choices[],long style,const wxValidator & validator,const wxString & name)256 bool wxListBox::Create( wxWindow *parent, wxWindowID id,
257                         const wxPoint &pos, const wxSize &size,
258                         int n, const wxString choices[],
259                         long style, const wxValidator& validator,
260                         const wxString &name )
261 {
262     if (!PreCreation( parent, pos, size ) ||
263         !CreateBase( parent, id, pos, size, style, validator, name ))
264     {
265         wxFAIL_MSG( wxT("wxListBox creation failed") );
266         return false;
267     }
268 
269     m_widget = gtk_scrolled_window_new( NULL, NULL );
270     g_object_ref(m_widget);
271 
272     GtkPolicyType vPolicy = GTK_POLICY_AUTOMATIC;
273     if (style & wxLB_ALWAYS_SB)
274         vPolicy = GTK_POLICY_ALWAYS;
275     else if (style & wxLB_NO_SB)
276         vPolicy = GTK_POLICY_NEVER;
277 
278     gtk_scrolled_window_set_policy(GTK_SCROLLED_WINDOW(m_widget),
279         GTK_POLICY_AUTOMATIC, vPolicy);
280 
281 
282     GTKScrolledWindowSetBorder(m_widget, style);
283 
284     m_treeview = GTK_TREE_VIEW( gtk_tree_view_new( ) );
285 
286     //wxListBox doesn't have a header :)
287     //NB: If enabled SetFirstItem doesn't work correctly
288     gtk_tree_view_set_headers_visible(m_treeview, FALSE);
289 
290 #if wxUSE_CHECKLISTBOX
291     if(m_hasCheckBoxes)
292         ((wxCheckListBox*)this)->DoCreateCheckList();
293 #endif // wxUSE_CHECKLISTBOX
294 
295     // Create the data column
296     gtk_tree_view_insert_column_with_attributes(m_treeview, -1, "",
297                                                 gtk_cell_renderer_text_new(),
298                                                 "text",
299                                                 WXLISTBOX_DATACOLUMN, NULL);
300 
301     // Now create+set the model (GtkListStore) - first argument # of columns
302 #if wxUSE_CHECKLISTBOX
303     if(m_hasCheckBoxes)
304         m_liststore = gtk_list_store_new(2, G_TYPE_BOOLEAN,
305                                             WX_TYPE_TREE_ENTRY);
306     else
307 #endif
308         m_liststore = gtk_list_store_new(1, WX_TYPE_TREE_ENTRY);
309 
310     gtk_tree_view_set_model(m_treeview, GTK_TREE_MODEL(m_liststore));
311 
312     g_object_unref (m_liststore); //free on treeview destruction
313 
314     // Disable the pop-up textctrl that enables searching - note that
315     // the docs specify that even if this disabled (which we are doing)
316     // the user can still have it through the start-interactive-search
317     // key binding...either way we want to provide a searchequal callback
318     // NB: If this is enabled a doubleclick event (activate) gets sent
319     //     on a successful search
320     gtk_tree_view_set_search_column(m_treeview, WXLISTBOX_DATACOLUMN);
321     gtk_tree_view_set_search_equal_func(m_treeview, search_callback, this, NULL);
322 
323     gtk_tree_view_set_enable_search(m_treeview, FALSE);
324 
325     GtkSelectionMode mode;
326     // GTK_SELECTION_EXTENDED is a deprecated synonym for GTK_SELECTION_MULTIPLE
327     if ( style & (wxLB_MULTIPLE | wxLB_EXTENDED) )
328     {
329         mode = GTK_SELECTION_MULTIPLE;
330     }
331     else // no multi-selection flags specified
332     {
333         m_windowStyle |= wxLB_SINGLE;
334 
335         // Notice that we must use BROWSE and not GTK_SELECTION_SINGLE because
336         // the latter allows to not select any items at all while a single
337         // selection listbox is supposed to always have a selection (at least
338         // once the user selected something, it might not have any initially).
339         mode = GTK_SELECTION_BROWSE;
340     }
341 
342     GtkTreeSelection* selection = gtk_tree_view_get_selection( m_treeview );
343     gtk_tree_selection_set_mode( selection, mode );
344 
345     // Handle sortable stuff
346     if(HasFlag(wxLB_SORT))
347     {
348         // Setup sorting in ascending (wx) order
349         gtk_tree_sortable_set_sort_column_id(GTK_TREE_SORTABLE(m_liststore),
350                                              WXLISTBOX_DATACOLUMN,
351                                              GTK_SORT_ASCENDING);
352 
353         // Set the sort callback
354         gtk_tree_sortable_set_sort_func(GTK_TREE_SORTABLE(m_liststore),
355                                         WXLISTBOX_DATACOLUMN,
356                                         sort_callback,
357                                         this, //userdata
358                                         NULL //"destroy notifier"
359                                        );
360     }
361 
362 
363     gtk_container_add (GTK_CONTAINER (m_widget), GTK_WIDGET(m_treeview) );
364 
365     gtk_widget_show( GTK_WIDGET(m_treeview) );
366     m_focusWidget = GTK_WIDGET(m_treeview);
367 
368     Append(n, choices); // insert initial items
369 
370     // generate dclick events
371     g_signal_connect_after(m_treeview, "row-activated",
372                      G_CALLBACK(gtk_listbox_row_activated_callback), this);
373 
374     // for intercepting dclick generation by <ENTER>
375     g_signal_connect (m_treeview, "key_press_event",
376                       G_CALLBACK (gtk_listbox_key_press_callback),
377                            this);
378     m_parent->DoAddChild( this );
379 
380     PostCreation(size);
381     SetInitialSize(size); // need this too because this is a wxControlWithItems
382 
383     g_signal_connect_after (selection, "changed",
384                             G_CALLBACK (gtk_listitem_changed_callback), this);
385 
386     return true;
387 }
388 
~wxListBox()389 wxListBox::~wxListBox()
390 {
391     if (m_treeview)
392     {
393         GTKDisconnect(m_treeview);
394         GtkTreeSelection* selection = gtk_tree_view_get_selection(m_treeview);
395         if (selection)
396             GTKDisconnect(selection);
397     }
398 
399     Clear();
400 }
401 
GTKDisableEvents()402 void wxListBox::GTKDisableEvents()
403 {
404     GtkTreeSelection* selection = gtk_tree_view_get_selection( m_treeview );
405 
406     g_signal_handlers_block_by_func(selection,
407                                 (gpointer) gtk_listitem_changed_callback, this);
408 }
409 
GTKEnableEvents()410 void wxListBox::GTKEnableEvents()
411 {
412     GtkTreeSelection* selection = gtk_tree_view_get_selection( m_treeview );
413 
414     g_signal_handlers_unblock_by_func(selection,
415                                 (gpointer) gtk_listitem_changed_callback, this);
416 
417     UpdateOldSelections();
418 }
419 
420 
Update()421 void wxListBox::Update()
422 {
423     wxWindow::Update();
424 
425     if (m_treeview)
426         gdk_window_process_updates(gtk_widget_get_window(GTK_WIDGET(m_treeview)), true);
427 }
428 
429 // ----------------------------------------------------------------------------
430 // adding items
431 // ----------------------------------------------------------------------------
432 
DoInsertItems(const wxArrayStringsAdapter & items,unsigned int pos,void ** clientData,wxClientDataType type)433 int wxListBox::DoInsertItems(const wxArrayStringsAdapter& items,
434                              unsigned int pos,
435                              void **clientData,
436                              wxClientDataType type)
437 {
438     wxCHECK_MSG( m_treeview != NULL, wxNOT_FOUND, wxT("invalid listbox") );
439 
440     InvalidateBestSize();
441     int n = DoInsertItemsInLoop(items, pos, clientData, type);
442     UpdateOldSelections();
443     return n;
444 }
445 
DoInsertOneItem(const wxString & item,unsigned int pos)446 int wxListBox::DoInsertOneItem(const wxString& item, unsigned int pos)
447 {
448     wxTreeEntry* entry = wx_tree_entry_new();
449     wx_tree_entry_set_label(entry, wxGTK_CONV(item));
450     wx_tree_entry_set_destroy_func(entry, (wxTreeEntryDestroy)tree_entry_destroy_cb, this);
451 
452 #if wxUSE_CHECKLISTBOX
453     int entryCol = int(m_hasCheckBoxes);
454 #else
455     int entryCol = 0;
456 #endif
457     GtkTreeIter iter;
458     gtk_list_store_insert_with_values(m_liststore, &iter, pos, entryCol, entry, -1);
459     g_object_unref(entry);
460 
461     if (HasFlag(wxLB_SORT))
462         pos = GTKGetIndexFor(iter);
463 
464     return pos;
465 }
466 
467 // ----------------------------------------------------------------------------
468 // deleting items
469 // ----------------------------------------------------------------------------
470 
DoClear()471 void wxListBox::DoClear()
472 {
473     wxCHECK_RET( m_treeview != NULL, wxT("invalid listbox") );
474 
475     {
476         wxGtkEventsDisabler<wxListBox> noEvents(this);
477 
478         InvalidateBestSize();
479 
480         gtk_list_store_clear( m_liststore ); /* well, THAT was easy :) */
481     }
482 
483     UpdateOldSelections();
484 }
485 
DoDeleteOneItem(unsigned int n)486 void wxListBox::DoDeleteOneItem(unsigned int n)
487 {
488     wxCHECK_RET( m_treeview != NULL, wxT("invalid listbox") );
489 
490     InvalidateBestSize();
491 
492     wxGtkEventsDisabler<wxListBox> noEvents(this);
493 
494     GtkTreeIter iter;
495     wxCHECK_RET( GTKGetIteratorFor(n, &iter), wxT("wrong listbox index") );
496 
497     // this returns false if iter is invalid (e.g. deleting item at end) but
498     // since we don't use iter, we ignore the return value
499     gtk_list_store_remove(m_liststore, &iter);
500 
501 #ifdef __WXGTK3__
502     // Invalidate selection in a single-selection control for consistency with
503     // MSW and GTK+ 2 where this happens automatically when deleting the
504     // selected item or any item before it.
505     if ( !HasMultipleSelection() )
506     {
507         const int sel = GetSelection();
508         if ( sel != wxNOT_FOUND && static_cast<unsigned>(sel) >= n )
509         {
510             // Don't call SetSelection() from here, it's not totally clear if
511             // it is safe to do, so just do this at GTK+ level.
512             gtk_tree_selection_unselect_all
513             (
514                 gtk_tree_view_get_selection(m_treeview)
515             );
516         }
517     }
518 #endif // __WXGTK3__
519 }
520 
521 // ----------------------------------------------------------------------------
522 // helper functions for working with iterators
523 // ----------------------------------------------------------------------------
524 
GTKGetIteratorFor(unsigned pos,GtkTreeIter * iter) const525 bool wxListBox::GTKGetIteratorFor(unsigned pos, GtkTreeIter *iter) const
526 {
527     if ( !gtk_tree_model_iter_nth_child(GTK_TREE_MODEL(m_liststore),
528                                         iter, NULL, pos) )
529     {
530         wxLogDebug(wxT("gtk_tree_model_iter_nth_child(%u) failed"), pos);
531         return false;
532     }
533 
534     return true;
535 }
536 
GTKGetIndexFor(GtkTreeIter & iter) const537 int wxListBox::GTKGetIndexFor(GtkTreeIter& iter) const
538 {
539     wxGtkTreePath path(
540         gtk_tree_model_get_path(GTK_TREE_MODEL(m_liststore), &iter));
541 
542     gint* pIntPath = gtk_tree_path_get_indices(path);
543 
544     wxCHECK_MSG( pIntPath, wxNOT_FOUND, wxT("failed to get iterator path") );
545 
546     return pIntPath[0];
547 }
548 
549 // get GtkTreeEntry from position (note: you need to g_unref it if valid)
GTKGetEntry(unsigned n) const550 wxTreeEntry* wxListBox::GTKGetEntry(unsigned n) const
551 {
552     GtkTreeIter iter;
553     if ( !GTKGetIteratorFor(n, &iter) )
554         return NULL;
555 
556     return GetEntry(m_liststore, &iter, this);
557 }
558 
559 // ----------------------------------------------------------------------------
560 // client data
561 // ----------------------------------------------------------------------------
562 
DoGetItemClientData(unsigned int n) const563 void* wxListBox::DoGetItemClientData(unsigned int n) const
564 {
565     wxTreeEntry* entry = GTKGetEntry(n);
566     wxCHECK_MSG(entry, NULL, wxT("could not get entry"));
567 
568     return wx_tree_entry_get_userdata(entry);
569 }
570 
DoSetItemClientData(unsigned int n,void * clientData)571 void wxListBox::DoSetItemClientData(unsigned int n, void* clientData)
572 {
573     wxTreeEntry* entry = GTKGetEntry(n);
574     wxCHECK_RET(entry, wxT("could not get entry"));
575 
576     wx_tree_entry_set_userdata(entry, clientData);
577 }
578 
579 // ----------------------------------------------------------------------------
580 // string list access
581 // ----------------------------------------------------------------------------
582 
SetString(unsigned int n,const wxString & label)583 void wxListBox::SetString(unsigned int n, const wxString& label)
584 {
585     wxCHECK_RET( m_treeview != NULL, wxT("invalid listbox") );
586 
587     GtkTreeIter iter;
588     wxCHECK_RET(GTKGetIteratorFor(n, &iter), "invalid index");
589     wxTreeEntry* entry = GetEntry(m_liststore, &iter, this);
590 
591     // update the item itself
592     wx_tree_entry_set_label(entry, wxGTK_CONV(label));
593 
594     // signal row changed
595     GtkTreeModel* tree_model = GTK_TREE_MODEL(m_liststore);
596     wxGtkTreePath path(gtk_tree_model_get_path(tree_model, &iter));
597     gtk_tree_model_row_changed(tree_model, path, &iter);
598 }
599 
GetString(unsigned int n) const600 wxString wxListBox::GetString(unsigned int n) const
601 {
602     wxCHECK_MSG( m_treeview != NULL, wxEmptyString, wxT("invalid listbox") );
603 
604     wxTreeEntry* entry = GTKGetEntry(n);
605     wxCHECK_MSG( entry, wxEmptyString, wxT("wrong listbox index") );
606 
607     return wxGTK_CONV_BACK(wx_tree_entry_get_label(entry));
608 }
609 
GetCount() const610 unsigned int wxListBox::GetCount() const
611 {
612     wxCHECK_MSG( m_treeview != NULL, 0, wxT("invalid listbox") );
613 
614     return (unsigned int)gtk_tree_model_iter_n_children(GTK_TREE_MODEL(m_liststore), NULL);
615 }
616 
FindString(const wxString & item,bool bCase) const617 int wxListBox::FindString( const wxString &item, bool bCase ) const
618 {
619     wxCHECK_MSG( m_treeview != NULL, wxNOT_FOUND, wxT("invalid listbox") );
620 
621     //Sort of hackish - maybe there is a faster way
622     unsigned int nCount = wxListBox::GetCount();
623 
624     for(unsigned int i = 0; i < nCount; ++i)
625     {
626         if( item.IsSameAs( wxListBox::GetString(i), bCase ) )
627             return (int)i;
628     }
629 
630 
631     // it's not an error if the string is not found -> no wxCHECK
632     return wxNOT_FOUND;
633 }
634 
635 // ----------------------------------------------------------------------------
636 // selection
637 // ----------------------------------------------------------------------------
638 
GTKOnActivated(int item)639 void wxListBox::GTKOnActivated(int item)
640 {
641     SendEvent(wxEVT_LISTBOX_DCLICK, item, IsSelected(item));
642 }
643 
GTKOnSelectionChanged()644 void wxListBox::GTKOnSelectionChanged()
645 {
646     if ( HasFlag(wxLB_MULTIPLE | wxLB_EXTENDED) )
647     {
648         CalcAndSendEvent();
649     }
650     else // single selection
651     {
652         const int item = GetSelection();
653         if (item >= 0 && DoChangeSingleSelection(item))
654             SendEvent(wxEVT_LISTBOX, item, true);
655     }
656 }
657 
GetSelection() const658 int wxListBox::GetSelection() const
659 {
660     wxCHECK_MSG( m_treeview != NULL, wxNOT_FOUND, wxT("invalid listbox"));
661     wxCHECK_MSG( HasFlag(wxLB_SINGLE), wxNOT_FOUND,
662                     wxT("must be single selection listbox"));
663 
664     GtkTreeIter iter;
665     GtkTreeSelection* selection = gtk_tree_view_get_selection(m_treeview);
666 
667     // only works on single-sel
668     if (!gtk_tree_selection_get_selected(selection, NULL, &iter))
669         return wxNOT_FOUND;
670 
671     return GTKGetIndexFor(iter);
672 }
673 
GetSelections(wxArrayInt & aSelections) const674 int wxListBox::GetSelections( wxArrayInt& aSelections ) const
675 {
676     wxCHECK_MSG( m_treeview != NULL, wxNOT_FOUND, wxT("invalid listbox") );
677 
678     aSelections.Empty();
679 
680     GtkTreeIter iter;
681     GtkTreeSelection* selection = gtk_tree_view_get_selection(m_treeview);
682 
683     if (gtk_tree_model_get_iter_first(GTK_TREE_MODEL(m_liststore), &iter))
684     { //gtk_tree_selection_get_selected_rows is GTK 2.2+ so iter instead
685         int i = 0;
686         do
687         {
688             if (gtk_tree_selection_iter_is_selected(selection, &iter))
689                 aSelections.Add(i);
690 
691             i++;
692         } while(gtk_tree_model_iter_next(GTK_TREE_MODEL(m_liststore), &iter));
693     }
694 
695     return aSelections.GetCount();
696 }
697 
IsSelected(int n) const698 bool wxListBox::IsSelected( int n ) const
699 {
700     wxCHECK_MSG( m_treeview != NULL, false, wxT("invalid listbox") );
701 
702     GtkTreeSelection* selection = gtk_tree_view_get_selection(m_treeview);
703 
704     GtkTreeIter iter;
705     wxCHECK_MSG( GTKGetIteratorFor(n, &iter), false, wxT("Invalid index") );
706 
707     return gtk_tree_selection_iter_is_selected(selection, &iter) != 0;
708 }
709 
DoSetSelection(int n,bool select)710 void wxListBox::DoSetSelection( int n, bool select )
711 {
712     wxCHECK_RET( m_treeview != NULL, wxT("invalid listbox") );
713 
714     wxGtkEventsDisabler<wxListBox> noEvents(this);
715 
716     GtkTreeSelection* selection = gtk_tree_view_get_selection(m_treeview);
717 
718     // passing -1 to SetSelection() is documented to deselect all items
719     if ( n == wxNOT_FOUND )
720     {
721         gtk_tree_selection_unselect_all(selection);
722         return;
723     }
724 
725     wxCHECK_RET( IsValid(n), wxT("invalid index in wxListBox::SetSelection") );
726 
727 
728     GtkTreeIter iter;
729     wxCHECK_RET( GTKGetIteratorFor(n, &iter), wxT("Invalid index") );
730 
731     if (select)
732         gtk_tree_selection_select_iter(selection, &iter);
733     else
734         gtk_tree_selection_unselect_iter(selection, &iter);
735 
736     wxGtkTreePath path(
737             gtk_tree_model_get_path(GTK_TREE_MODEL(m_liststore), &iter));
738 
739     gtk_tree_view_scroll_to_cell(m_treeview, path, NULL, FALSE, 0.0f, 0.0f);
740 }
741 
DoScrollToCell(int n,float alignY,float alignX)742 void wxListBox::DoScrollToCell(int n, float alignY, float alignX)
743 {
744     wxCHECK_RET( m_treeview, wxT("invalid listbox") );
745     wxCHECK_RET( IsValid(n), wxT("invalid index"));
746 
747     //RN: I have no idea why this line is needed...
748     if (gtk_widget_has_grab(GTK_WIDGET(m_treeview)))
749         return;
750 
751     GtkTreeIter iter;
752     if ( !GTKGetIteratorFor(n, &iter) )
753         return;
754 
755     wxGtkTreePath path(
756             gtk_tree_model_get_path(GTK_TREE_MODEL(m_liststore), &iter));
757 
758     // Scroll to the desired cell (0.0 == topleft alignment)
759     gtk_tree_view_scroll_to_cell(m_treeview, path, NULL,
760                                  TRUE, alignY, alignX);
761 }
762 
DoSetFirstItem(int n)763 void wxListBox::DoSetFirstItem(int n)
764 {
765     DoScrollToCell(n, 0, 0);
766 }
767 
EnsureVisible(int n)768 void wxListBox::EnsureVisible(int n)
769 {
770     DoScrollToCell(n, 0.5, 0);
771 }
772 
GetTopItem() const773 int wxListBox::GetTopItem() const
774 {
775     int idx = wxNOT_FOUND;
776 
777 #if GTK_CHECK_VERSION(2,8,0)
778     wxGtkTreePath start;
779     if (
780         wx_is_at_least_gtk2(8) &&
781         gtk_tree_view_get_visible_range(m_treeview, start.ByRef(), NULL))
782     {
783         gint *ptr = gtk_tree_path_get_indices(start);
784 
785         if ( ptr )
786             idx = *ptr;
787     }
788 #endif
789 
790     return idx;
791 }
792 
GetCountPerPage() const793 int wxListBox::GetCountPerPage() const
794 {
795     wxGtkTreePath path;
796     GtkTreeViewColumn *column;
797 
798     if ( !gtk_tree_view_get_path_at_pos
799           (
800             m_treeview,
801             0,
802             0,
803             path.ByRef(),
804             &column,
805             NULL,
806             NULL
807           ) )
808     {
809         return -1;
810     }
811 
812     GdkRectangle rect;
813     gtk_tree_view_get_cell_area(m_treeview, path, column, &rect);
814 
815     if ( !rect.height )
816         return -1;
817 
818     GdkRectangle vis;
819     gtk_tree_view_get_visible_rect(m_treeview, &vis);
820 
821     return vis.height / rect.height;
822 }
823 
824 // ----------------------------------------------------------------------------
825 // hittest
826 // ----------------------------------------------------------------------------
827 
DoListHitTest(const wxPoint & point) const828 int wxListBox::DoListHitTest(const wxPoint& point) const
829 {
830     // gtk_tree_view_get_path_at_pos() also gets items that are not visible and
831     // we only want visible items we need to check for it manually here
832     if ( !GetClientRect().Contains(point) )
833         return wxNOT_FOUND;
834 
835     // need to translate from master window since it is in client coords
836     gint binx, biny;
837     gdk_window_get_geometry(gtk_tree_view_get_bin_window(m_treeview),
838                             &binx, &biny, NULL, NULL);
839 
840     wxGtkTreePath path;
841     if ( !gtk_tree_view_get_path_at_pos
842           (
843             m_treeview,
844             point.x - binx,
845             point.y - biny,
846             path.ByRef(),
847             NULL,   // [out] column (always 0 here)
848             NULL,   // [out] x-coord relative to the cell (not interested)
849             NULL    // [out] y-coord relative to the cell
850           ) )
851     {
852         return wxNOT_FOUND;
853     }
854 
855     return gtk_tree_path_get_indices(path)[0];
856 }
857 
858 // ----------------------------------------------------------------------------
859 // helpers
860 // ----------------------------------------------------------------------------
861 
GetConnectWidget()862 GtkWidget *wxListBox::GetConnectWidget()
863 {
864     // the correct widget for listbox events (such as mouse clicks for example)
865     // is m_treeview, not the parent scrolled window
866     return GTK_WIDGET(m_treeview);
867 }
868 
GTKGetWindow(wxArrayGdkWindows & WXUNUSED (windows)) const869 GdkWindow *wxListBox::GTKGetWindow(wxArrayGdkWindows& WXUNUSED(windows)) const
870 {
871     return gtk_tree_view_get_bin_window(m_treeview);
872 }
873 
DoApplyWidgetStyle(GtkRcStyle * style)874 void wxListBox::DoApplyWidgetStyle(GtkRcStyle *style)
875 {
876 #ifdef __WXGTK3__
877     // don't know if this is even necessary, or how to do it
878 #else
879     if (m_hasBgCol && m_backgroundColour.IsOk())
880     {
881         GdkWindow *window = gtk_tree_view_get_bin_window(m_treeview);
882         if (window)
883         {
884             m_backgroundColour.CalcPixel( gdk_drawable_get_colormap( window ) );
885             gdk_window_set_background( window, m_backgroundColour.GetColor() );
886             gdk_window_clear( window );
887         }
888     }
889 #endif
890 
891     GTKApplyStyle(GTK_WIDGET(m_treeview), style);
892 }
893 
DoGetBestSize() const894 wxSize wxListBox::DoGetBestSize() const
895 {
896     wxCHECK_MSG(m_treeview, wxDefaultSize, wxT("invalid tree view"));
897 
898     // Start with a minimum size that's not too small
899     int cx, cy;
900     GetTextExtent( wxT("X"), &cx, &cy);
901     int lbWidth = 0;
902     int lbHeight = 10;
903 
904     // Find the widest string.
905     const unsigned int count = GetCount();
906     if ( count )
907     {
908         int wLine;
909         for ( unsigned int i = 0; i < count; i++ )
910         {
911             GetTextExtent(GetString(i), &wLine, NULL);
912             if ( wLine > lbWidth )
913                 lbWidth = wLine;
914         }
915     }
916 
917     lbWidth += 3 * cx;
918 
919     // And just a bit more for the checkbox if present and then some
920     // (these are rough guesses)
921 #if wxUSE_CHECKLISTBOX
922     if ( m_hasCheckBoxes )
923     {
924         lbWidth += 35;
925         cy = cy > 25 ? cy : 25; // rough height of checkbox
926     }
927 #endif
928 
929     // Add room for the scrollbar
930     lbWidth += wxSystemSettings::GetMetric(wxSYS_VSCROLL_X);
931 
932     // Don't make the listbox too tall but don't make it too small neither
933     lbHeight = (cy+4) * wxMin(wxMax(count, 3), 10);
934 
935     return wxSize(lbWidth, lbHeight);
936 }
937 
938 // static
939 wxVisualAttributes
GetClassDefaultAttributes(wxWindowVariant WXUNUSED (variant))940 wxListBox::GetClassDefaultAttributes(wxWindowVariant WXUNUSED(variant))
941 {
942     return GetDefaultAttributesFromGTKWidget(gtk_tree_view_new(), true);
943 }
944 
945 #endif // wxUSE_LISTBOX
946