OSDN Git Service

A couple of bugfix in the Document. The version number is set to 1.0b1.
[molby/Molby.git] / wxSources / listctrl.cpp
1 /////////////////////////////////////////////////////////////////////////////
2 // Name:        src/generic/listctrl.cpp
3 // Purpose:     generic implementation of wxListCtrl
4 // Author:      Robert Roebling
5 //              Vadim Zeitlin (virtual list control support)
6 // Copyright:   (c) 1998 Robert Roebling
7 // Licence:     wxWindows licence
8 /////////////////////////////////////////////////////////////////////////////
9
10 // TODO
11 //
12 //   1. we need to implement searching/sorting for virtual controls somehow
13 //   2. when changing selection the lines are refreshed twice
14
15
16 // For compilers that support precompilation, includes "wx.h".
17 #include "wx/wxprec.h"
18
19 #ifdef __BORLANDC__
20     #pragma hdrstop
21 #endif
22
23 #if wxUSE_LISTCTRL
24
25 #include "wx/listctrl.h"
26 #include "wx/generic/listctrl.h"
27
28 //  Define an event class to implement delayed syncing of the header window
29 wxDECLARE_EVENT(ListCtrlEvent, wxCommandEvent);
30 wxDEFINE_EVENT(ListCtrlEvent, wxCommandEvent);
31 //  End Toshi Nagata
32
33 #ifndef WX_PRECOMP
34     #include "wx/scrolwin.h"
35     #include "wx/timer.h"
36     #include "wx/settings.h"
37     #include "wx/dynarray.h"
38     #include "wx/dcclient.h"
39     #include "wx/dcscreen.h"
40     #include "wx/math.h"
41     #include "wx/settings.h"
42     #include "wx/sizer.h"
43 #endif
44
45 #include "wx/imaglist.h"
46 #include "wx/renderer.h"
47 //  2013.12.10. Toshi Nagata; include my own version of private/listctrl.h
48 //#include "wx/generic/private/listctrl.h"
49 #include "listctrl_private.h"
50 //  End Toshi Nagata
51
52 #ifdef __WXMAC__
53     #include "wx/osx/private.h"
54 #endif
55
56 #if defined(__WXMSW__) && !defined(__WXWINCE__) && !defined(__WXUNIVERSAL__)
57     #include "wx/msw/wrapwin.h"   // 2013.11.27. define -> include Toshi Nagata
58 #endif
59
60 // NOTE: If using the wxListBox visual attributes works everywhere then this can
61 // be removed, as well as the #else case below.
62 #define _USE_VISATTR 0
63
64
65 // ----------------------------------------------------------------------------
66 // constants
67 // ----------------------------------------------------------------------------
68
69 // // the height of the header window (FIXME: should depend on its font!)
70 // static const int HEADER_HEIGHT = 23;
71
72 static const int SCROLL_UNIT_X = 15;
73
74 // the spacing between the lines (in report mode)
75 static const int LINE_SPACING = 0;
76
77 // extra margins around the text label
78 #ifdef __WXGTK__
79 static const int EXTRA_WIDTH = 6;
80 #else
81 static const int EXTRA_WIDTH = 4;
82 #endif
83
84 #ifdef __WXGTK__
85 static const int EXTRA_HEIGHT = 6;
86 //  2013.12.30. Toshi Nagata
87 #elif defined(__WXMSW__)
88 static const int EXTRA_HEIGHT = 1;
89 //  End Toshi Nagata
90 #else
91 static const int EXTRA_HEIGHT = 4;
92 #endif
93
94 // margin between the window and the items
95 static const int EXTRA_BORDER_X = 2;
96 static const int EXTRA_BORDER_Y = 2;
97
98 // offset for the header window
99 static const int HEADER_OFFSET_X = 0;
100 static const int HEADER_OFFSET_Y = 0;
101
102 // margin between rows of icons in [small] icon view
103 static const int MARGIN_BETWEEN_ROWS = 6;
104
105 // when autosizing the columns, add some slack
106 static const int AUTOSIZE_COL_MARGIN = 10;
107
108 // default width for the header columns
109 static const int WIDTH_COL_DEFAULT = 80;
110
111 // the space between the image and the text in the report mode
112 static const int IMAGE_MARGIN_IN_REPORT_MODE = 5;
113
114 // the space between the image and the text in the report mode in header
115 static const int HEADER_IMAGE_MARGIN_IN_REPORT_MODE = 2;
116
117
118
119 // ----------------------------------------------------------------------------
120 // arrays/list implementations
121 // ----------------------------------------------------------------------------
122
123 #include "wx/listimpl.cpp"
124 WX_DEFINE_LIST(wxListItemDataList)
125
126 #include "wx/arrimpl.cpp"
127 WX_DEFINE_OBJARRAY(wxListLineDataArray)
128
129 #include "wx/listimpl.cpp"
130 WX_DEFINE_LIST(wxListHeaderDataList)
131
132
133 // ----------------------------------------------------------------------------
134 // wxListItemData
135 // ----------------------------------------------------------------------------
136
137 wxListItemData::~wxListItemData()
138 {
139     // in the virtual list control the attributes are managed by the main
140     // program, so don't delete them
141     if ( !m_owner->IsVirtual() )
142         delete m_attr;
143
144     delete m_rect;
145 }
146
147 void wxListItemData::Init()
148 {
149     m_image = -1;
150     m_data = 0;
151
152     m_attr = NULL;
153 }
154
155 wxListItemData::wxListItemData(wxListMainWindow *owner)
156 {
157     Init();
158
159     m_owner = owner;
160
161     if ( owner->InReportView() )
162         m_rect = NULL;
163     else
164         m_rect = new wxRect;
165 }
166
167 void wxListItemData::SetItem( const wxListItem &info )
168 {
169     if ( info.m_mask & wxLIST_MASK_TEXT )
170         SetText(info.m_text);
171     if ( info.m_mask & wxLIST_MASK_IMAGE )
172         m_image = info.m_image;
173     if ( info.m_mask & wxLIST_MASK_DATA )
174         m_data = info.m_data;
175
176     if ( info.HasAttributes() )
177     {
178         if ( m_attr )
179             m_attr->AssignFrom(*info.GetAttributes());
180         else
181             m_attr = new wxListItemAttr(*info.GetAttributes());
182     }
183
184     if ( m_rect )
185     {
186         m_rect->x =
187         m_rect->y =
188         m_rect->height = 0;
189         m_rect->width = info.m_width;
190     }
191 }
192
193 void wxListItemData::SetPosition( int x, int y )
194 {
195     wxCHECK_RET( m_rect, wxT("unexpected SetPosition() call") );
196
197     m_rect->x = x;
198     m_rect->y = y;
199 }
200
201 void wxListItemData::SetSize( int width, int height )
202 {
203     wxCHECK_RET( m_rect, wxT("unexpected SetSize() call") );
204
205     if ( width != -1 )
206         m_rect->width = width;
207     if ( height != -1 )
208         m_rect->height = height;
209 }
210
211 bool wxListItemData::IsHit( int x, int y ) const
212 {
213     wxCHECK_MSG( m_rect, false, wxT("can't be called in this mode") );
214
215     return wxRect(GetX(), GetY(), GetWidth(), GetHeight()).Contains(x, y);
216 }
217
218 int wxListItemData::GetX() const
219 {
220     wxCHECK_MSG( m_rect, 0, wxT("can't be called in this mode") );
221
222     return m_rect->x;
223 }
224
225 int wxListItemData::GetY() const
226 {
227     wxCHECK_MSG( m_rect, 0, wxT("can't be called in this mode") );
228
229     return m_rect->y;
230 }
231
232 int wxListItemData::GetWidth() const
233 {
234     wxCHECK_MSG( m_rect, 0, wxT("can't be called in this mode") );
235
236     return m_rect->width;
237 }
238
239 int wxListItemData::GetHeight() const
240 {
241     wxCHECK_MSG( m_rect, 0, wxT("can't be called in this mode") );
242
243     return m_rect->height;
244 }
245
246 void wxListItemData::GetItem( wxListItem &info ) const
247 {
248     long mask = info.m_mask;
249     if ( !mask )
250         // by default, get everything for backwards compatibility
251         mask = -1;
252
253     if ( mask & wxLIST_MASK_TEXT )
254         info.m_text = m_text;
255     if ( mask & wxLIST_MASK_IMAGE )
256         info.m_image = m_image;
257     if ( mask & wxLIST_MASK_DATA )
258         info.m_data = m_data;
259
260     if ( m_attr )
261     {
262         if ( m_attr->HasTextColour() )
263             info.SetTextColour(m_attr->GetTextColour());
264         if ( m_attr->HasBackgroundColour() )
265             info.SetBackgroundColour(m_attr->GetBackgroundColour());
266         if ( m_attr->HasFont() )
267             info.SetFont(m_attr->GetFont());
268     }
269 }
270
271 //-----------------------------------------------------------------------------
272 //  wxListHeaderData
273 //-----------------------------------------------------------------------------
274
275 void wxListHeaderData::Init()
276 {
277     m_mask = 0;
278     m_image = -1;
279     m_format = 0;
280     m_width = 0;
281     m_xpos = 0;
282     m_ypos = 0;
283     m_height = 0;
284     m_state = 0;
285 }
286
287 wxListHeaderData::wxListHeaderData()
288 {
289     Init();
290 }
291
292 wxListHeaderData::wxListHeaderData( const wxListItem &item )
293 {
294     Init();
295
296     SetItem( item );
297 }
298
299 void wxListHeaderData::SetItem( const wxListItem &item )
300 {
301     m_mask = item.m_mask;
302
303     if ( m_mask & wxLIST_MASK_TEXT )
304         m_text = item.m_text;
305
306     if ( m_mask & wxLIST_MASK_IMAGE )
307         m_image = item.m_image;
308
309     if ( m_mask & wxLIST_MASK_FORMAT )
310         m_format = item.m_format;
311
312     if ( m_mask & wxLIST_MASK_WIDTH )
313         SetWidth(item.m_width);
314
315     if ( m_mask & wxLIST_MASK_STATE )
316         SetState(item.m_state);
317 }
318
319 void wxListHeaderData::SetPosition( int x, int y )
320 {
321     m_xpos = x;
322     m_ypos = y;
323 }
324
325 void wxListHeaderData::SetHeight( int h )
326 {
327     m_height = h;
328 }
329
330 void wxListHeaderData::SetWidth( int w )
331 {
332     m_width = w < 0 ? WIDTH_COL_DEFAULT : w;
333 }
334
335 void wxListHeaderData::SetState( int flag )
336 {
337     m_state = flag;
338 }
339
340 void wxListHeaderData::SetFormat( int format )
341 {
342     m_format = format;
343 }
344
345 bool wxListHeaderData::HasImage() const
346 {
347     return m_image != -1;
348 }
349
350 bool wxListHeaderData::IsHit( int x, int y ) const
351 {
352     return ((x >= m_xpos) && (x <= m_xpos+m_width) && (y >= m_ypos) && (y <= m_ypos+m_height));
353 }
354
355 void wxListHeaderData::GetItem( wxListItem& item )
356 {
357     long mask = item.m_mask;
358     if ( !mask )
359     {
360         // by default, get everything for backwards compatibility
361         mask = -1;
362     }
363
364     if ( mask & wxLIST_MASK_STATE )
365         item.m_state = m_state;
366     if ( mask & wxLIST_MASK_TEXT )
367         item.m_text = m_text;
368     if ( mask & wxLIST_MASK_IMAGE )
369         item.m_image = m_image;
370     if ( mask & wxLIST_MASK_WIDTH )
371         item.m_width = m_width;
372     if ( mask & wxLIST_MASK_FORMAT )
373         item.m_format = m_format;
374 }
375
376 int wxListHeaderData::GetImage() const
377 {
378     return m_image;
379 }
380
381 int wxListHeaderData::GetWidth() const
382 {
383     return m_width;
384 }
385
386 int wxListHeaderData::GetFormat() const
387 {
388     return m_format;
389 }
390
391 int wxListHeaderData::GetState() const
392 {
393     return m_state;
394 }
395
396 //-----------------------------------------------------------------------------
397 //  wxListLineData
398 //-----------------------------------------------------------------------------
399
400 inline int wxListLineData::GetMode() const
401 {
402     return m_owner->GetListCtrl()->GetWindowStyleFlag() & wxLC_MASK_TYPE;
403 }
404
405 inline bool wxListLineData::InReportView() const
406 {
407     return m_owner->HasFlag(wxLC_REPORT);
408 }
409
410 inline bool wxListLineData::IsVirtual() const
411 {
412     return m_owner->IsVirtual();
413 }
414
415 wxListLineData::wxListLineData( wxListMainWindow *owner )
416 {
417     m_owner = owner;
418
419     if ( InReportView() )
420         m_gi = NULL;
421     else // !report
422         m_gi = new GeometryInfo;
423
424     m_highlighted = false;
425
426     InitItems( GetMode() == wxLC_REPORT ? m_owner->GetColumnCount() : 1 );
427 }
428
429 void wxListLineData::CalculateSize( wxDC *dc, int spacing )
430 {
431     wxListItemDataList::compatibility_iterator node = m_items.GetFirst();
432     wxCHECK_RET( node, wxT("no subitems at all??") );
433
434     wxListItemData *item = node->GetData();
435
436     wxString s;
437     wxCoord lw, lh;
438
439     switch ( GetMode() )
440     {
441         case wxLC_ICON:
442         case wxLC_SMALL_ICON:
443             m_gi->m_rectAll.width = spacing;
444
445             s = item->GetText();
446
447             if ( s.empty() )
448             {
449                 lh =
450                 m_gi->m_rectLabel.width =
451                 m_gi->m_rectLabel.height = 0;
452             }
453             else // has label
454             {
455                 dc->GetTextExtent( s, &lw, &lh );
456                 lw += EXTRA_WIDTH;
457                 lh += EXTRA_HEIGHT;
458
459                 m_gi->m_rectAll.height = spacing + lh;
460                 if (lw > spacing)
461                     m_gi->m_rectAll.width = lw;
462
463                 m_gi->m_rectLabel.width = lw;
464                 m_gi->m_rectLabel.height = lh;
465             }
466
467             if (item->HasImage())
468             {
469                 int w, h;
470                 m_owner->GetImageSize( item->GetImage(), w, h );
471                 m_gi->m_rectIcon.width = w + 8;
472                 m_gi->m_rectIcon.height = h + 8;
473
474                 if ( m_gi->m_rectIcon.width > m_gi->m_rectAll.width )
475                     m_gi->m_rectAll.width = m_gi->m_rectIcon.width;
476                 if ( m_gi->m_rectIcon.height + lh > m_gi->m_rectAll.height - 4 )
477                     m_gi->m_rectAll.height = m_gi->m_rectIcon.height + lh + 4;
478             }
479
480             if ( item->HasText() )
481             {
482                 m_gi->m_rectHighlight.width = m_gi->m_rectLabel.width;
483                 m_gi->m_rectHighlight.height = m_gi->m_rectLabel.height;
484             }
485             else // no text, highlight the icon
486             {
487                 m_gi->m_rectHighlight.width = m_gi->m_rectIcon.width;
488                 m_gi->m_rectHighlight.height = m_gi->m_rectIcon.height;
489             }
490             break;
491
492         case wxLC_LIST:
493             s = item->GetTextForMeasuring();
494
495             dc->GetTextExtent( s, &lw, &lh );
496             lw += EXTRA_WIDTH;
497             lh += EXTRA_HEIGHT;
498
499             m_gi->m_rectLabel.width = lw;
500             m_gi->m_rectLabel.height = lh;
501
502             m_gi->m_rectAll.width = lw;
503             m_gi->m_rectAll.height = lh;
504
505             if (item->HasImage())
506             {
507                 int w, h;
508                 m_owner->GetImageSize( item->GetImage(), w, h );
509                 m_gi->m_rectIcon.width = w;
510                 m_gi->m_rectIcon.height = h;
511
512                 m_gi->m_rectAll.width += 4 + w;
513                 if (h > m_gi->m_rectAll.height)
514                     m_gi->m_rectAll.height = h;
515             }
516
517             m_gi->m_rectHighlight.width = m_gi->m_rectAll.width;
518             m_gi->m_rectHighlight.height = m_gi->m_rectAll.height;
519             break;
520
521         case wxLC_REPORT:
522             wxFAIL_MSG( wxT("unexpected call to SetSize") );
523             break;
524
525         default:
526             wxFAIL_MSG( wxT("unknown mode") );
527             break;
528     }
529 }
530
531 void wxListLineData::SetPosition( int x, int y, int spacing )
532 {
533     wxListItemDataList::compatibility_iterator node = m_items.GetFirst();
534     wxCHECK_RET( node, wxT("no subitems at all??") );
535
536     wxListItemData *item = node->GetData();
537
538     switch ( GetMode() )
539     {
540         case wxLC_ICON:
541         case wxLC_SMALL_ICON:
542             m_gi->m_rectAll.x = x;
543             m_gi->m_rectAll.y = y;
544
545             if ( item->HasImage() )
546             {
547                 m_gi->m_rectIcon.x = m_gi->m_rectAll.x + 4 +
548                     (m_gi->m_rectAll.width - m_gi->m_rectIcon.width) / 2;
549                 m_gi->m_rectIcon.y = m_gi->m_rectAll.y + 4;
550             }
551
552             if ( item->HasText() )
553             {
554                 if (m_gi->m_rectAll.width > spacing)
555                     m_gi->m_rectLabel.x = m_gi->m_rectAll.x + (EXTRA_WIDTH/2);
556                 else
557                     m_gi->m_rectLabel.x = m_gi->m_rectAll.x + (EXTRA_WIDTH/2) + (spacing / 2) - (m_gi->m_rectLabel.width / 2);
558                 m_gi->m_rectLabel.y = m_gi->m_rectAll.y + m_gi->m_rectAll.height + 2 - m_gi->m_rectLabel.height;
559                 m_gi->m_rectHighlight.x = m_gi->m_rectLabel.x - 2;
560                 m_gi->m_rectHighlight.y = m_gi->m_rectLabel.y - 2;
561             }
562             else // no text, highlight the icon
563             {
564                 m_gi->m_rectHighlight.x = m_gi->m_rectIcon.x - 4;
565                 m_gi->m_rectHighlight.y = m_gi->m_rectIcon.y - 4;
566             }
567             break;
568
569         case wxLC_LIST:
570             m_gi->m_rectAll.x = x;
571             m_gi->m_rectAll.y = y;
572
573             m_gi->m_rectHighlight.x = m_gi->m_rectAll.x;
574             m_gi->m_rectHighlight.y = m_gi->m_rectAll.y;
575             m_gi->m_rectLabel.y = m_gi->m_rectAll.y + 2;
576
577             if (item->HasImage())
578             {
579                 m_gi->m_rectIcon.x = m_gi->m_rectAll.x + 2;
580                 m_gi->m_rectIcon.y = m_gi->m_rectAll.y + 2;
581                 m_gi->m_rectLabel.x = m_gi->m_rectAll.x + 4 + (EXTRA_WIDTH/2) + m_gi->m_rectIcon.width;
582             }
583             else
584             {
585                 m_gi->m_rectLabel.x = m_gi->m_rectAll.x + (EXTRA_WIDTH/2);
586             }
587             break;
588
589         case wxLC_REPORT:
590             wxFAIL_MSG( wxT("unexpected call to SetPosition") );
591             break;
592
593         default:
594             wxFAIL_MSG( wxT("unknown mode") );
595             break;
596     }
597 }
598
599 void wxListLineData::InitItems( int num )
600 {
601     for (int i = 0; i < num; i++)
602         m_items.Append( new wxListItemData(m_owner) );
603 }
604
605 void wxListLineData::SetItem( int index, const wxListItem &info )
606 {
607     wxListItemDataList::compatibility_iterator node = m_items.Item( index );
608     wxCHECK_RET( node, wxT("invalid column index in SetItem") );
609
610     wxListItemData *item = node->GetData();
611     item->SetItem( info );
612 }
613
614 void wxListLineData::GetItem( int index, wxListItem &info )
615 {
616     wxListItemDataList::compatibility_iterator node = m_items.Item( index );
617     if (node)
618     {
619         wxListItemData *item = node->GetData();
620         item->GetItem( info );
621     }
622 }
623
624 wxString wxListLineData::GetText(int index) const
625 {
626     wxString s;
627
628     wxListItemDataList::compatibility_iterator node = m_items.Item( index );
629     if (node)
630     {
631         wxListItemData *item = node->GetData();
632         s = item->GetText();
633     }
634
635     return s;
636 }
637
638 void wxListLineData::SetText( int index, const wxString& s )
639 {
640     wxListItemDataList::compatibility_iterator node = m_items.Item( index );
641     if (node)
642     {
643         wxListItemData *item = node->GetData();
644         item->SetText( s );
645     }
646 }
647
648 void wxListLineData::SetImage( int index, int image )
649 {
650     wxListItemDataList::compatibility_iterator node = m_items.Item( index );
651     wxCHECK_RET( node, wxT("invalid column index in SetImage()") );
652
653     wxListItemData *item = node->GetData();
654     item->SetImage(image);
655 }
656
657 int wxListLineData::GetImage( int index ) const
658 {
659     wxListItemDataList::compatibility_iterator node = m_items.Item( index );
660     wxCHECK_MSG( node, -1, wxT("invalid column index in GetImage()") );
661
662     wxListItemData *item = node->GetData();
663     return item->GetImage();
664 }
665
666 wxListItemAttr *wxListLineData::GetAttr() const
667 {
668     wxListItemDataList::compatibility_iterator node = m_items.GetFirst();
669     wxCHECK_MSG( node, NULL, wxT("invalid column index in GetAttr()") );
670
671     wxListItemData *item = node->GetData();
672     return item->GetAttr();
673 }
674
675 void wxListLineData::SetAttr(wxListItemAttr *attr)
676 {
677     wxListItemDataList::compatibility_iterator node = m_items.GetFirst();
678     wxCHECK_RET( node, wxT("invalid column index in SetAttr()") );
679
680     wxListItemData *item = node->GetData();
681     item->SetAttr(attr);
682 }
683
684 void wxListLineData::ApplyAttributes(wxDC *dc,
685                                      const wxRect& rectHL,
686                                      bool highlighted,
687                                      bool current, wxListItemAttr *override) // 2013.12.10. Toshi Nagata; add "override" argument
688 {
689         //  2013.12.10. Toshi Nagata
690 //    const wxListItemAttr * const attr = GetAttr();
691         const wxListItemAttr * const attr = (override ? override : GetAttr());
692         //  End Toshi Nagata
693
694     wxWindow * const listctrl = m_owner->GetParent();
695
696     const bool hasFocus = listctrl->HasFocus()
697 #if defined(__WXMAC__) && !defined(__WXUNIVERSAL__) && wxOSX_USE_CARBON
698                 && IsControlActive( (ControlRef)listctrl->GetHandle() )
699 #endif
700                 ;
701
702     // fg colour
703
704     // don't use foreground colour for drawing highlighted items - this might
705     // make them completely invisible (and there is no way to do bit
706     // arithmetics on wxColour, unfortunately)
707     wxColour colText;
708     if ( highlighted )
709     {
710 #ifdef __WXMAC__
711         if ( hasFocus )
712             colText = *wxWHITE;
713         else
714             colText = *wxBLACK;
715 #else
716         if ( hasFocus )
717             colText = wxSystemSettings::GetColour(wxSYS_COLOUR_HIGHLIGHTTEXT);
718         else {
719                 //  Modified Toshi Nagata 2013.12.30.
720         //    colText = wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOXHIGHLIGHTTEXT);
721                         colText = *wxBLACK;
722                 }
723                 //  End Toshi Nagata
724 #endif
725     }
726     else if ( attr && attr->HasTextColour() )
727         colText = attr->GetTextColour();
728     else
729         colText = listctrl->GetForegroundColour();
730
731     dc->SetTextForeground(colText);
732
733     // font
734     wxFont font;
735     if ( attr && attr->HasFont() )
736         font = attr->GetFont();
737     else
738         font = listctrl->GetFont();
739
740     dc->SetFont(font);
741
742     // background
743     if ( highlighted )
744     {
745         // Use the renderer method to ensure that the selected items use the
746         // native look.
747         int flags = wxCONTROL_SELECTED;
748         if ( hasFocus )
749             flags |= wxCONTROL_FOCUSED;
750         if (current)
751            flags |= wxCONTROL_CURRENT;
752         wxRendererNative::Get().
753             DrawItemSelectionRect( m_owner, *dc, rectHL, flags );
754     }
755     else if ( attr && attr->HasBackgroundColour() )
756     {
757         // Draw the background using the items custom background colour.
758         dc->SetBrush(attr->GetBackgroundColour());
759         dc->SetPen(*wxTRANSPARENT_PEN);
760         dc->DrawRectangle(rectHL);
761     }
762
763     // just for debugging to better see where the items are
764 #if 0
765     dc->SetPen(*wxRED_PEN);
766     dc->SetBrush(*wxTRANSPARENT_BRUSH);
767     dc->DrawRectangle( m_gi->m_rectAll );
768     dc->SetPen(*wxGREEN_PEN);
769     dc->DrawRectangle( m_gi->m_rectIcon );
770 #endif
771 }
772
773 void wxListLineData::Draw(wxDC *dc, bool current)
774 {
775     wxListItemDataList::compatibility_iterator node = m_items.GetFirst();
776     wxCHECK_RET( node, wxT("no subitems at all??") );
777
778     ApplyAttributes(dc, m_gi->m_rectHighlight, IsHighlighted(), current);
779
780     wxListItemData *item = node->GetData();
781     if (item->HasImage())
782     {
783         // centre the image inside our rectangle, this looks nicer when items
784         // ae aligned in a row
785         const wxRect& rectIcon = m_gi->m_rectIcon;
786
787         m_owner->DrawImage(item->GetImage(), dc, rectIcon.x, rectIcon.y);
788     }
789
790     if (item->HasText())
791     {
792         const wxRect& rectLabel = m_gi->m_rectLabel;
793
794         wxDCClipper clipper(*dc, rectLabel);
795         dc->DrawText(item->GetText(), rectLabel.x, rectLabel.y);
796     }
797 }
798
799 void wxListLineData::DrawInReportMode( wxDC *dc,
800                                        const wxRect& rect,
801                                        const wxRect& rectHL,
802                                        bool highlighted,
803                                        bool current, long line ) // 2013.12.10. Toshi Nagata; add "line" argument
804 {
805     // TODO: later we should support setting different attributes for
806     //       different columns - to do it, just add "col" argument to
807     //       GetAttr() and move these lines into the loop below
808
809 //    ApplyAttributes(dc, rectHL, highlighted, current);  //  2013.12.10. Toshi Nagata; move to the inside the loop
810
811     wxCoord x = rect.x + HEADER_OFFSET_X,
812             yMid = rect.y + rect.height/2;
813 #ifdef __WXGTK__
814     // This probably needs to be done
815     // on all platforms as the icons
816     // otherwise nearly touch the border
817     x += 2;
818 #endif
819
820     size_t col = 0;
821     for ( wxListItemDataList::compatibility_iterator node = m_items.GetFirst();
822           node;
823           node = node->GetNext(), col++ )
824     {
825         wxListItemData *item = node->GetData();
826
827         int width = m_owner->GetColumnWidth(col);
828         int xOld = x;
829         x += width;
830
831                 //  2013.12.10. Toshi Nagata
832                 //  Implement attribute for each column
833                 {
834                         wxListItemAttr *cattr = m_owner->GetListCtrl()->OnGetItemAttr(line + 1000000 * (col + 1));
835                         wxRect itemRect(xOld, rect.y, width, rect.height);
836                         ApplyAttributes(dc, itemRect, highlighted, current, cattr);
837                 }
838                 //  End Toshi Nagata
839
840         width -= 8;
841         const int wText = width;
842         wxDCClipper clipper(*dc, xOld, rect.y, wText, rect.height);
843
844         if ( item->HasImage() )
845         {
846             int ix, iy;
847             m_owner->GetImageSize( item->GetImage(), ix, iy );
848             m_owner->DrawImage( item->GetImage(), dc, xOld, yMid - iy/2 );
849
850             ix += IMAGE_MARGIN_IN_REPORT_MODE;
851
852             xOld += ix;
853             width -= ix;
854         }
855
856         if ( item->HasText() )
857             DrawTextFormatted(dc, item->GetText(), col, xOld, yMid, width);
858     }
859 }
860
861 void wxListLineData::DrawTextFormatted(wxDC *dc,
862                                        const wxString& textOrig,
863                                        int col,
864                                        int x,
865                                        int yMid,
866                                        int width)
867 {
868     // we don't support displaying multiple lines currently (and neither does
869     // wxMSW FWIW) so just merge all the lines
870     wxString text(textOrig);
871     text.Replace(wxT("\n"), wxT(" "));
872
873     wxCoord w, h;
874     dc->GetTextExtent(text, &w, &h);
875
876     const wxCoord y = yMid - (h + 1)/2;
877
878     wxDCClipper clipper(*dc, x, y, width, h);
879
880     // determine if the string can fit inside the current width
881     if (w <= width)
882     {
883         // it can, draw it using the items alignment
884         wxListItem item;
885         m_owner->GetColumn(col, item);
886         switch ( item.GetAlign() )
887         {
888             case wxLIST_FORMAT_LEFT:
889                 // nothing to do
890                 break;
891
892             case wxLIST_FORMAT_RIGHT:
893                 x += width - w;
894                 break;
895
896             case wxLIST_FORMAT_CENTER:
897                 x += (width - w) / 2;
898                 break;
899
900             default:
901                 wxFAIL_MSG( wxT("unknown list item format") );
902                 break;
903         }
904
905         dc->DrawText(text, x, y);
906     }
907     else // otherwise, truncate and add an ellipsis if possible
908     {
909         // determine the base width
910         wxString ellipsis(wxT("..."));
911         wxCoord base_w;
912         dc->GetTextExtent(ellipsis, &base_w, &h);
913
914         // continue until we have enough space or only one character left
915         wxCoord w_c, h_c;
916         size_t len = text.length();
917         wxString drawntext = text.Left(len);
918         while (len > 1)
919         {
920             dc->GetTextExtent(drawntext.Last(), &w_c, &h_c);
921             drawntext.RemoveLast();
922             len--;
923             w -= w_c;
924             if (w + base_w <= width)
925                 break;
926         }
927
928         // if still not enough space, remove ellipsis characters
929         while (ellipsis.length() > 0 && w + base_w > width)
930         {
931             ellipsis = ellipsis.Left(ellipsis.length() - 1);
932             dc->GetTextExtent(ellipsis, &base_w, &h);
933         }
934
935         // now draw the text
936         dc->DrawText(drawntext, x, y);
937         dc->DrawText(ellipsis, x + w, y);
938     }
939 }
940
941 bool wxListLineData::Highlight( bool on )
942 {
943     wxCHECK_MSG( !IsVirtual(), false, wxT("unexpected call to Highlight") );
944
945     if ( on == m_highlighted )
946         return false;
947
948     m_highlighted = on;
949
950     return true;
951 }
952
953 void wxListLineData::ReverseHighlight( void )
954 {
955     Highlight(!IsHighlighted());
956 }
957
958 //-----------------------------------------------------------------------------
959 //  wxListHeaderWindow
960 //-----------------------------------------------------------------------------
961
962 BEGIN_EVENT_TABLE(wxListHeaderWindow,wxWindow)
963     EVT_PAINT         (wxListHeaderWindow::OnPaint)
964     EVT_MOUSE_EVENTS  (wxListHeaderWindow::OnMouse)
965     EVT_COMMAND(-1, ListCtrlEvent, wxListHeaderWindow::OnListCtrlEvent)  //  Toshi Nagata 2014.01.13.
966 END_EVENT_TABLE()
967
968 void wxListHeaderWindow::Init()
969 {
970     m_currentCursor = NULL;
971     m_isDragging = false;
972     m_dirty = false;
973     m_sendSetColumnWidth = false;
974 }
975
976 wxListHeaderWindow::wxListHeaderWindow()
977 {
978     Init();
979
980     m_owner = NULL;
981     m_resizeCursor = NULL;
982 }
983
984 bool wxListHeaderWindow::Create( wxWindow *win,
985                                  wxWindowID id,
986                                  wxListMainWindow *owner,
987                                  const wxPoint& pos,
988                                  const wxSize& size,
989                                  long style,
990                                  const wxString &name )
991 {
992     if ( !wxWindow::Create(win, id, pos, size, style, name) )
993         return false;
994
995     Init();
996
997     m_owner = owner;
998     m_resizeCursor = new wxCursor( wxCURSOR_SIZEWE );
999
1000 #if _USE_VISATTR
1001     wxVisualAttributes attr = wxPanel::GetClassDefaultAttributes();
1002     SetOwnForegroundColour( attr.colFg );
1003     SetOwnBackgroundColour( attr.colBg );
1004     if (!m_hasFont)
1005         SetOwnFont( attr.font );
1006 #else
1007     SetOwnForegroundColour( wxSystemSettings::GetColour(wxSYS_COLOUR_WINDOWTEXT));
1008     SetOwnBackgroundColour( wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE));
1009     if (!m_hasFont)
1010         SetOwnFont( wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT ));
1011 #endif
1012
1013     return true;
1014 }
1015
1016 wxListHeaderWindow::~wxListHeaderWindow()
1017 {
1018     delete m_resizeCursor;
1019 }
1020
1021 #ifdef __WXUNIVERSAL__
1022 #include "wx/univ/renderer.h"
1023 #include "wx/univ/theme.h"
1024 #endif
1025
1026 // shift the DC origin to match the position of the main window horz
1027 // scrollbar: this allows us to always use logical coords
1028 void wxListHeaderWindow::AdjustDC(wxDC& dc)
1029 {
1030     wxGenericListCtrl *parent = m_owner->GetListCtrl();
1031
1032     int xpix;
1033     parent->GetScrollPixelsPerUnit( &xpix, NULL );
1034
1035     int view_start;
1036     parent->GetViewStart( &view_start, NULL );
1037         
1038     int org_x = 0;
1039     int org_y = 0;
1040     dc.GetDeviceOrigin( &org_x, &org_y );
1041
1042     // account for the horz scrollbar offset
1043 #ifdef __WXGTK__
1044     if (GetLayoutDirection() == wxLayout_RightToLeft)
1045     {
1046         // Maybe we just have to check for m_signX
1047         // in the DC, but I leave the #ifdef __WXGTK__
1048         // for now
1049         dc.SetDeviceOrigin( org_x + (view_start * xpix), org_y );
1050     }
1051     else
1052 #endif
1053         dc.SetDeviceOrigin( org_x - (view_start * xpix), org_y );
1054 }
1055
1056 void wxListHeaderWindow::OnPaint( wxPaintEvent &WXUNUSED(event) )
1057 {
1058     wxGenericListCtrl *parent = m_owner->GetListCtrl();
1059
1060     wxPaintDC dc( this );
1061
1062     AdjustDC( dc );
1063
1064     dc.SetFont( GetFont() );
1065
1066     // width and height of the entire header window
1067     int w, h;
1068     GetClientSize( &w, &h );
1069     parent->CalcUnscrolledPosition(w, 0, &w, NULL);
1070
1071     dc.SetBackgroundMode(wxBRUSHSTYLE_TRANSPARENT);
1072     dc.SetTextForeground(GetForegroundColour());
1073
1074     int x = HEADER_OFFSET_X;
1075     int numColumns = m_owner->GetColumnCount();
1076     wxListItem item;
1077     for ( int i = 0; i < numColumns && x < w; i++ )
1078     {
1079         m_owner->GetColumn( i, item );
1080         int wCol = item.m_width;
1081
1082         int cw = wCol;
1083         int ch = h;
1084
1085         int flags = 0;
1086         if (!m_parent->IsEnabled())
1087             flags |= wxCONTROL_DISABLED;
1088
1089 // NB: The code below is not really Mac-specific, but since we are close
1090 // to 2.8 release and I don't have time to test on other platforms, I
1091 // defined this only for wxMac. If this behaviour is desired on
1092 // other platforms, please go ahead and revise or remove the #ifdef.
1093 #ifdef __WXMAC__
1094         if ( !m_owner->IsVirtual() && (item.m_mask & wxLIST_MASK_STATE) &&
1095                 (item.m_state & wxLIST_STATE_SELECTED) )
1096             flags |= wxCONTROL_SELECTED;
1097 #endif
1098
1099         if (i == 0)
1100            flags |= wxCONTROL_SPECIAL; // mark as first column
1101
1102         wxRendererNative::Get().DrawHeaderButton
1103                                 (
1104                                     this,
1105                                     dc,
1106                                     wxRect(x, HEADER_OFFSET_Y, cw, ch),
1107                                     flags
1108                                 );
1109
1110         // see if we have enough space for the column label
1111
1112         // for this we need the width of the text
1113         wxCoord wLabel;
1114         wxCoord hLabel;
1115         dc.GetTextExtent(item.GetText(), &wLabel, &hLabel);
1116         wLabel += 2 * EXTRA_WIDTH;
1117
1118         // and the width of the icon, if any
1119         int ix = 0, iy = 0;    // init them just to suppress the compiler warnings
1120         const int image = item.m_image;
1121         wxImageList *imageList;
1122         if ( image != -1 )
1123         {
1124             imageList = m_owner->GetSmallImageList();
1125             if ( imageList )
1126             {
1127                 imageList->GetSize(image, ix, iy);
1128                 wLabel += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE;
1129             }
1130         }
1131         else
1132         {
1133             imageList = NULL;
1134         }
1135
1136         // ignore alignment if there is not enough space anyhow
1137         int xAligned;
1138         switch ( wLabel < cw ? item.GetAlign() : wxLIST_FORMAT_LEFT )
1139         {
1140             default:
1141                 wxFAIL_MSG( wxT("unknown list item format") );
1142                 // fall through
1143
1144             case wxLIST_FORMAT_LEFT:
1145                 xAligned = x;
1146                 break;
1147
1148             case wxLIST_FORMAT_RIGHT:
1149                 xAligned = x + cw - wLabel;
1150                 break;
1151
1152             case wxLIST_FORMAT_CENTER:
1153                 xAligned = x + (cw - wLabel) / 2;
1154                 break;
1155         }
1156
1157         // draw the text and image clipping them so that they
1158         // don't overwrite the column boundary
1159         wxDCClipper clipper(dc, x, HEADER_OFFSET_Y, cw, h);
1160
1161         // if we have an image, draw it on the right of the label
1162         if ( imageList )
1163         {
1164             imageList->Draw
1165                        (
1166                         image,
1167                         dc,
1168                         xAligned + wLabel - ix - HEADER_IMAGE_MARGIN_IN_REPORT_MODE,
1169                         HEADER_OFFSET_Y + (h - iy)/2,
1170                         wxIMAGELIST_DRAW_TRANSPARENT
1171                        );
1172         }
1173
1174         dc.DrawText( item.GetText(),
1175                      xAligned + EXTRA_WIDTH, (h - hLabel) / 2 );
1176
1177         x += wCol;
1178     }
1179
1180     // Fill in what's missing to the right of the columns, otherwise we will
1181     // leave an unpainted area when columns are removed (and it looks better)
1182     if ( x < w )
1183     {
1184         wxRendererNative::Get().DrawHeaderButton
1185                                 (
1186                                     this,
1187                                     dc,
1188                                     wxRect(x, HEADER_OFFSET_Y, w - x, h),
1189                                     wxCONTROL_DIRTY // mark as last column
1190                                 );
1191     }
1192 }
1193
1194 void wxListHeaderWindow::OnInternalIdle()
1195 {
1196     wxWindow::OnInternalIdle();
1197
1198     if (m_sendSetColumnWidth)
1199     {
1200         m_owner->SetColumnWidth( m_colToSend, m_widthToSend );
1201         m_sendSetColumnWidth = false;
1202     }
1203 }
1204
1205 void wxListHeaderWindow::DrawCurrent()
1206 {
1207     m_sendSetColumnWidth = true;
1208     m_colToSend = m_column;
1209     m_widthToSend = m_currentX - m_minX;
1210 }
1211
1212 void wxListHeaderWindow::OnMouse( wxMouseEvent &event )
1213 {
1214     wxGenericListCtrl *parent = m_owner->GetListCtrl();
1215
1216     // we want to work with logical coords
1217     int x;
1218     parent->CalcUnscrolledPosition(event.GetX(), 0, &x, NULL);
1219     int y = event.GetY();
1220
1221     if (m_isDragging)
1222     {
1223         SendListEvent(wxEVT_LIST_COL_DRAGGING, event.GetPosition());
1224
1225         // we don't draw the line beyond our window, but we allow dragging it
1226         // there
1227         int w = 0;
1228         GetClientSize( &w, NULL );
1229         parent->CalcUnscrolledPosition(w, 0, &w, NULL);
1230         w -= 6;
1231
1232         // erase the line if it was drawn
1233         if ( m_currentX < w )
1234             DrawCurrent();
1235
1236         if (event.ButtonUp())
1237         {
1238             ReleaseMouse();
1239             m_isDragging = false;
1240             m_dirty = true;
1241             m_owner->SetColumnWidth( m_column, m_currentX - m_minX );
1242             SendListEvent(wxEVT_LIST_COL_END_DRAG, event.GetPosition());
1243         }
1244         else
1245         {
1246             if (x > m_minX + 7)
1247                 m_currentX = x;
1248             else
1249                 m_currentX = m_minX + 7;
1250
1251             // draw in the new location
1252             if ( m_currentX < w )
1253                 DrawCurrent();
1254         }
1255     }
1256     else // not dragging
1257     {
1258         m_minX = 0;
1259         bool hit_border = false;
1260
1261         // end of the current column
1262         int xpos = 0;
1263
1264         // find the column where this event occurred
1265         int col,
1266             countCol = m_owner->GetColumnCount();
1267         for (col = 0; col < countCol; col++)
1268         {
1269             xpos += m_owner->GetColumnWidth( col );
1270             m_column = col;
1271
1272             if ( (abs(x-xpos) < 3) && (y < 22) )
1273             {
1274                 // near the column border
1275                 hit_border = true;
1276                 break;
1277             }
1278
1279             if ( x < xpos )
1280             {
1281                 // inside the column
1282                 break;
1283             }
1284
1285             m_minX = xpos;
1286         }
1287
1288         if ( col == countCol )
1289             m_column = -1;
1290
1291         if (event.LeftDown() || event.RightUp())
1292         {
1293             if (hit_border && event.LeftDown())
1294             {
1295                 if ( SendListEvent(wxEVT_LIST_COL_BEGIN_DRAG,
1296                                    event.GetPosition()) )
1297                 {
1298                     m_isDragging = true;
1299                     m_currentX = x;
1300                     CaptureMouse();
1301                     DrawCurrent();
1302                 }
1303                 //else: column resizing was vetoed by the user code
1304             }
1305             else // click on a column
1306             {
1307                 // record the selected state of the columns
1308                 if (event.LeftDown())
1309                 {
1310                     for (int i=0; i < m_owner->GetColumnCount(); i++)
1311                     {
1312                         wxListItem colItem;
1313                         m_owner->GetColumn(i, colItem);
1314                         long state = colItem.GetState();
1315                         if (i == m_column)
1316                             colItem.SetState(state | wxLIST_STATE_SELECTED);
1317                         else
1318                             colItem.SetState(state & ~wxLIST_STATE_SELECTED);
1319                         m_owner->SetColumn(i, colItem);
1320                     }
1321                 }
1322
1323                 SendListEvent( event.LeftDown()
1324                                     ? wxEVT_LIST_COL_CLICK
1325                                     : wxEVT_LIST_COL_RIGHT_CLICK,
1326                                 event.GetPosition());
1327             }
1328         }
1329         else if (event.Moving())
1330         {
1331             bool setCursor;
1332             if (hit_border)
1333             {
1334                 setCursor = m_currentCursor == wxSTANDARD_CURSOR;
1335                 m_currentCursor = m_resizeCursor;
1336             }
1337             else
1338             {
1339                 setCursor = m_currentCursor != wxSTANDARD_CURSOR;
1340                 m_currentCursor = wxSTANDARD_CURSOR;
1341             }
1342
1343             if ( setCursor )
1344                 SetCursor(*m_currentCursor);
1345         }
1346     }
1347 }
1348
1349 bool wxListHeaderWindow::SendListEvent(wxEventType type, const wxPoint& pos)
1350 {
1351     wxWindow *parent = GetParent();
1352     wxListEvent le( type, parent->GetId() );
1353     le.SetEventObject( parent );
1354     le.m_pointDrag = pos;
1355
1356     // the position should be relative to the parent window, not
1357     // this one for compatibility with MSW and common sense: the
1358     // user code doesn't know anything at all about this header
1359     // window, so why should it get positions relative to it?
1360     le.m_pointDrag.y -= GetSize().y;
1361
1362     le.m_col = m_column;
1363     return !parent->GetEventHandler()->ProcessEvent( le ) || le.IsAllowed();
1364 }
1365
1366 //  Toshi Nagata 2014.01.13.
1367 void wxListHeaderWindow::QueueListCtrlEvent(wxCommandEvent &event)
1368 {
1369         AddPendingEvent(event);
1370 }
1371
1372 void wxListHeaderWindow::OnListCtrlEvent(wxCommandEvent &event)
1373 {
1374         Refresh();
1375         Update();       
1376 }
1377 //  End Toshi Nagata
1378
1379 //-----------------------------------------------------------------------------
1380 // wxListRenameTimer (internal)
1381 //-----------------------------------------------------------------------------
1382
1383 wxListRenameTimer::wxListRenameTimer( wxListMainWindow *owner )
1384 {
1385     m_owner = owner;
1386 }
1387
1388 void wxListRenameTimer::Notify()
1389 {
1390     m_owner->OnRenameTimer();
1391 }
1392
1393 //-----------------------------------------------------------------------------
1394 // wxListFindTimer (internal)
1395 //-----------------------------------------------------------------------------
1396
1397 void wxListFindTimer::Notify()
1398 {
1399     m_owner->OnFindTimer();
1400 }
1401
1402 //-----------------------------------------------------------------------------
1403 // wxListTextCtrlWrapper (internal)
1404 //-----------------------------------------------------------------------------
1405
1406 BEGIN_EVENT_TABLE(wxListTextCtrlWrapper, wxEvtHandler)
1407     EVT_CHAR           (wxListTextCtrlWrapper::OnChar)
1408     EVT_KEY_UP         (wxListTextCtrlWrapper::OnKeyUp)
1409     EVT_KILL_FOCUS     (wxListTextCtrlWrapper::OnKillFocus)
1410 END_EVENT_TABLE()
1411
1412 wxListTextCtrlWrapper::wxListTextCtrlWrapper(wxListMainWindow *owner,
1413                                              wxTextCtrl *text,
1414                                              size_t itemEdit)
1415               : m_startValue(owner->GetItemText(itemEdit)),
1416                 m_itemEdited(itemEdit)
1417 {
1418     m_owner = owner;
1419     m_text = text;
1420     m_aboutToFinish = false;
1421
1422     wxGenericListCtrl *parent = m_owner->GetListCtrl();
1423
1424     wxRect rectLabel = owner->GetLineLabelRect(itemEdit);
1425
1426     parent->CalcScrolledPosition(rectLabel.x, rectLabel.y,
1427                                   &rectLabel.x, &rectLabel.y);
1428
1429     m_text->Create(owner, wxID_ANY, m_startValue,
1430                    wxPoint(rectLabel.x-4,rectLabel.y-4),
1431                    wxSize(rectLabel.width+11,rectLabel.height+8));
1432     m_text->SetFocus();
1433
1434     m_text->PushEventHandler(this);
1435 }
1436
1437 void wxListTextCtrlWrapper::EndEdit(EndReason reason)
1438 {
1439     m_aboutToFinish = true;
1440
1441     switch ( reason )
1442     {
1443         case End_Accept:
1444             // Notify the owner about the changes
1445             AcceptChanges();
1446
1447             // Even if vetoed, close the control (consistent with MSW)
1448             Finish( true );
1449             break;
1450
1451         case End_Discard:
1452             m_owner->OnRenameCancelled(m_itemEdited);
1453
1454             Finish( true );
1455             break;
1456
1457         case End_Destroy:
1458             // Don't generate any notifications for the control being destroyed
1459             // and don't set focus to it neither.
1460             Finish(false);
1461             break;
1462     }
1463 }
1464
1465 void wxListTextCtrlWrapper::Finish( bool setfocus )
1466 {
1467     m_text->RemoveEventHandler(this);
1468     m_owner->ResetTextControl( m_text );
1469
1470     wxPendingDelete.Append( this );
1471
1472     if (setfocus)
1473         m_owner->SetFocus();
1474 }
1475
1476 bool wxListTextCtrlWrapper::AcceptChanges()
1477 {
1478     const wxString value = m_text->GetValue();
1479
1480     // notice that we should always call OnRenameAccept() to generate the "end
1481     // label editing" event, even if the user hasn't really changed anything
1482     if ( !m_owner->OnRenameAccept(m_itemEdited, value) )
1483     {
1484         // vetoed by the user
1485         return false;
1486     }
1487
1488     // accepted, do rename the item (unless nothing changed)
1489     if ( value != m_startValue )
1490         m_owner->SetItemText(m_itemEdited, value);
1491
1492     return true;
1493 }
1494
1495 void wxListTextCtrlWrapper::OnChar( wxKeyEvent &event )
1496 {
1497     if ( !CheckForEndEditKey(event) )
1498         event.Skip();
1499 }
1500
1501 bool wxListTextCtrlWrapper::CheckForEndEditKey(const wxKeyEvent& event)
1502 {
1503     switch ( event.m_keyCode )
1504     {
1505         case WXK_RETURN:
1506             EndEdit( End_Accept );
1507             break;
1508
1509         case WXK_ESCAPE:
1510             EndEdit( End_Discard );
1511             break;
1512
1513         default:
1514             return false;
1515     }
1516
1517     return true;
1518 }
1519
1520 void wxListTextCtrlWrapper::OnKeyUp( wxKeyEvent &event )
1521 {
1522     if (m_aboutToFinish)
1523     {
1524         // auto-grow the textctrl:
1525         wxSize parentSize = m_owner->GetSize();
1526         wxPoint myPos = m_text->GetPosition();
1527         wxSize mySize = m_text->GetSize();
1528         int sx, sy;
1529         m_text->GetTextExtent(m_text->GetValue() + wxT("MM"), &sx, &sy);
1530         if (myPos.x + sx > parentSize.x)
1531             sx = parentSize.x - myPos.x;
1532        if (mySize.x > sx)
1533             sx = mySize.x;
1534        m_text->SetSize(sx, wxDefaultCoord);
1535     }
1536
1537     event.Skip();
1538 }
1539
1540 void wxListTextCtrlWrapper::OnKillFocus( wxFocusEvent &event )
1541 {
1542     if ( !m_aboutToFinish )
1543     {
1544         if ( !AcceptChanges() )
1545             m_owner->OnRenameCancelled( m_itemEdited );
1546
1547         Finish( false );
1548     }
1549
1550     // We must let the native text control handle focus
1551     event.Skip();
1552 }
1553
1554 //-----------------------------------------------------------------------------
1555 //  wxListMainWindow
1556 //-----------------------------------------------------------------------------
1557
1558 BEGIN_EVENT_TABLE(wxListMainWindow, wxWindow)
1559   EVT_PAINT          (wxListMainWindow::OnPaint)
1560   EVT_MOUSE_EVENTS   (wxListMainWindow::OnMouse)
1561   EVT_CHAR_HOOK      (wxListMainWindow::OnCharHook)
1562   EVT_CHAR           (wxListMainWindow::OnChar)
1563   EVT_KEY_DOWN       (wxListMainWindow::OnKeyDown)
1564   EVT_KEY_UP         (wxListMainWindow::OnKeyUp)
1565   EVT_SET_FOCUS      (wxListMainWindow::OnSetFocus)
1566   EVT_KILL_FOCUS     (wxListMainWindow::OnKillFocus)
1567   EVT_SCROLLWIN      (wxListMainWindow::OnScroll)
1568   EVT_CHILD_FOCUS    (wxListMainWindow::OnChildFocus)
1569 END_EVENT_TABLE()
1570
1571 void wxListMainWindow::Init()
1572 {
1573     m_dirty = true;
1574     m_countVirt = 0;
1575     m_lineFrom =
1576     m_lineTo = (size_t)-1;
1577     m_linesPerPage = 0;
1578
1579     m_headerWidth =
1580     m_lineHeight = 0;
1581
1582     m_small_image_list = NULL;
1583     m_normal_image_list = NULL;
1584
1585     m_small_spacing = 30;
1586     m_normal_spacing = 40;
1587
1588     m_hasFocus = false;
1589     m_dragCount = 0;
1590     m_isCreated = false;
1591
1592     m_lastOnSame = false;
1593     m_renameTimer = new wxListRenameTimer( this );
1594     m_findTimer = NULL;
1595     m_findBell = 0;  // default is to not ring bell at all
1596     m_textctrlWrapper = NULL;
1597
1598     m_current =
1599     m_lineLastClicked =
1600     m_lineSelectSingleOnUp =
1601     m_lineBeforeLastClicked = (size_t)-1;
1602 }
1603
1604 wxListMainWindow::wxListMainWindow()
1605 {
1606     Init();
1607
1608     m_highlightBrush =
1609     m_highlightUnfocusedBrush = NULL;
1610 }
1611
1612 wxListMainWindow::wxListMainWindow( wxWindow *parent,
1613                                     wxWindowID id,
1614                                     const wxPoint& pos,
1615                                     const wxSize& size )
1616                 : wxWindow( parent, id, pos, size,
1617                             wxWANTS_CHARS | wxBORDER_NONE )
1618 {
1619     Init();
1620
1621     m_highlightBrush = new wxBrush
1622                          (
1623                             wxSystemSettings::GetColour
1624                             (
1625                                 wxSYS_COLOUR_HIGHLIGHT
1626                             ),
1627                             wxBRUSHSTYLE_SOLID
1628                          );
1629
1630     m_highlightUnfocusedBrush = new wxBrush
1631                               (
1632                                  wxSystemSettings::GetColour
1633                                  (
1634                                      wxSYS_COLOUR_BTNSHADOW
1635                                  ),
1636                                  wxBRUSHSTYLE_SOLID
1637                               );
1638
1639     wxVisualAttributes attr = wxGenericListCtrl::GetClassDefaultAttributes();
1640     SetOwnForegroundColour( attr.colFg );
1641     SetOwnBackgroundColour( attr.colBg );
1642     if (!m_hasFont)
1643         SetOwnFont( attr.font );
1644 }
1645
1646 wxListMainWindow::~wxListMainWindow()
1647 {
1648     if ( m_textctrlWrapper )
1649         m_textctrlWrapper->EndEdit(wxListTextCtrlWrapper::End_Destroy);
1650
1651     DoDeleteAllItems();
1652     WX_CLEAR_LIST(wxListHeaderDataList, m_columns);
1653     WX_CLEAR_ARRAY(m_aColWidths);
1654
1655     delete m_highlightBrush;
1656     delete m_highlightUnfocusedBrush;
1657     delete m_renameTimer;
1658     delete m_findTimer;
1659 }
1660
1661 void wxListMainWindow::SetReportView(bool inReportView)
1662 {
1663     const size_t count = m_lines.size();
1664     for ( size_t n = 0; n < count; n++ )
1665     {
1666         m_lines[n].SetReportView(inReportView);
1667     }
1668 }
1669
1670 void wxListMainWindow::CacheLineData(size_t line)
1671 {
1672     wxGenericListCtrl *listctrl = GetListCtrl();
1673
1674     wxListLineData *ld = GetDummyLine();
1675
1676     size_t countCol = GetColumnCount();
1677     for ( size_t col = 0; col < countCol; col++ )
1678     {
1679         ld->SetText(col, listctrl->OnGetItemText(line, col));
1680         ld->SetImage(col, listctrl->OnGetItemColumnImage(line, col));
1681     }
1682
1683     ld->SetAttr(listctrl->OnGetItemAttr(line));
1684 }
1685
1686 wxListLineData *wxListMainWindow::GetDummyLine() const
1687 {
1688     wxASSERT_MSG( !IsEmpty(), wxT("invalid line index") );
1689     wxASSERT_MSG( IsVirtual(), wxT("GetDummyLine() shouldn't be called") );
1690
1691     wxListMainWindow *self = wxConstCast(this, wxListMainWindow);
1692
1693     // we need to recreate the dummy line if the number of columns in the
1694     // control changed as it would have the incorrect number of fields
1695     // otherwise
1696     if ( !m_lines.IsEmpty() &&
1697             m_lines[0].m_items.GetCount() != (size_t)GetColumnCount() )
1698     {
1699         self->m_lines.Clear();
1700     }
1701
1702     if ( m_lines.IsEmpty() )
1703     {
1704         wxListLineData *line = new wxListLineData(self);
1705         self->m_lines.Add(line);
1706
1707         // don't waste extra memory -- there never going to be anything
1708         // else/more in this array
1709         self->m_lines.Shrink();
1710     }
1711
1712     return &m_lines[0];
1713 }
1714
1715 // ----------------------------------------------------------------------------
1716 // line geometry (report mode only)
1717 // ----------------------------------------------------------------------------
1718
1719 wxCoord wxListMainWindow::GetLineHeight() const
1720 {
1721     // we cache the line height as calling GetTextExtent() is slow
1722     if ( !m_lineHeight )
1723     {
1724         wxListMainWindow *self = wxConstCast(this, wxListMainWindow);
1725
1726         wxClientDC dc( self );
1727         dc.SetFont( GetFont() );
1728
1729         wxCoord y;
1730         dc.GetTextExtent(wxT("H"), NULL, &y);
1731
1732         if ( m_small_image_list && m_small_image_list->GetImageCount() )
1733         {
1734             int iw = 0, ih = 0;
1735             m_small_image_list->GetSize(0, iw, ih);
1736             y = wxMax(y, ih);
1737         }
1738
1739         y += EXTRA_HEIGHT;
1740         self->m_lineHeight = y + LINE_SPACING;
1741     }
1742
1743     return m_lineHeight;
1744 }
1745
1746 wxCoord wxListMainWindow::GetLineY(size_t line) const
1747 {
1748     wxASSERT_MSG( InReportView(), wxT("only works in report mode") );
1749
1750     return LINE_SPACING + line * GetLineHeight();
1751 }
1752
1753 wxRect wxListMainWindow::GetLineRect(size_t line) const
1754 {
1755     if ( !InReportView() )
1756         return GetLine(line)->m_gi->m_rectAll;
1757
1758     wxRect rect;
1759     rect.x = HEADER_OFFSET_X;
1760     rect.y = GetLineY(line);
1761     rect.width = GetHeaderWidth();
1762     rect.height = GetLineHeight();
1763
1764     return rect;
1765 }
1766
1767 wxRect wxListMainWindow::GetLineLabelRect(size_t line) const
1768 {
1769     if ( !InReportView() )
1770         return GetLine(line)->m_gi->m_rectLabel;
1771
1772     int image_x = 0;
1773     wxListLineData *data = GetLine(line);
1774     wxListItemDataList::compatibility_iterator node = data->m_items.GetFirst();
1775     if (node)
1776     {
1777         wxListItemData *item = node->GetData();
1778         if ( item->HasImage() )
1779         {
1780             int ix, iy;
1781             GetImageSize( item->GetImage(), ix, iy );
1782             image_x = 3 + ix + IMAGE_MARGIN_IN_REPORT_MODE;
1783         }
1784     }
1785
1786     wxRect rect;
1787     rect.x = image_x + HEADER_OFFSET_X;
1788     rect.y = GetLineY(line);
1789     rect.width = GetColumnWidth(0) - image_x;
1790     rect.height = GetLineHeight();
1791
1792     return rect;
1793 }
1794
1795 wxRect wxListMainWindow::GetLineIconRect(size_t line) const
1796 {
1797     if ( !InReportView() )
1798         return GetLine(line)->m_gi->m_rectIcon;
1799
1800     wxListLineData *ld = GetLine(line);
1801     wxASSERT_MSG( ld->HasImage(), wxT("should have an image") );
1802
1803     wxRect rect;
1804     rect.x = HEADER_OFFSET_X;
1805     rect.y = GetLineY(line);
1806     GetImageSize(ld->GetImage(), rect.width, rect.height);
1807
1808     return rect;
1809 }
1810
1811 wxRect wxListMainWindow::GetLineHighlightRect(size_t line) const
1812 {
1813     return InReportView() ? GetLineRect(line)
1814                           : GetLine(line)->m_gi->m_rectHighlight;
1815 }
1816
1817 long wxListMainWindow::HitTestLine(size_t line, int x, int y) const
1818 {
1819     wxASSERT_MSG( line < GetItemCount(), wxT("invalid line in HitTestLine") );
1820
1821     wxListLineData *ld = GetLine(line);
1822
1823     if ( ld->HasImage() && GetLineIconRect(line).Contains(x, y) )
1824         return wxLIST_HITTEST_ONITEMICON;
1825
1826     // VS: Testing for "ld->HasText() || InReportView()" instead of
1827     //     "ld->HasText()" is needed to make empty lines in report view
1828     //     possible
1829     if ( ld->HasText() || InReportView() )
1830     {
1831         wxRect rect = InReportView() ? GetLineRect(line)
1832                                      : GetLineLabelRect(line);
1833
1834         if ( rect.Contains(x, y) )
1835             return wxLIST_HITTEST_ONITEMLABEL;
1836     }
1837
1838     return 0;
1839 }
1840
1841 // ----------------------------------------------------------------------------
1842 // highlight (selection) handling
1843 // ----------------------------------------------------------------------------
1844
1845 bool wxListMainWindow::IsHighlighted(size_t line) const
1846 {
1847     if ( IsVirtual() )
1848     {
1849         return m_selStore.IsSelected(line);
1850     }
1851     else // !virtual
1852     {
1853         wxListLineData *ld = GetLine(line);
1854         wxCHECK_MSG( ld, false, wxT("invalid index in IsHighlighted") );
1855
1856         return ld->IsHighlighted();
1857     }
1858 }
1859
1860 void wxListMainWindow::HighlightLines( size_t lineFrom,
1861                                        size_t lineTo,
1862                                        bool highlight )
1863 {
1864     if ( IsVirtual() )
1865     {
1866         wxArrayInt linesChanged;
1867         if ( !m_selStore.SelectRange(lineFrom, lineTo, highlight,
1868                                      &linesChanged) )
1869         {
1870             // meny items changed state, refresh everything
1871             RefreshLines(lineFrom, lineTo);
1872         }
1873         else // only a few items changed state, refresh only them
1874         {
1875             size_t count = linesChanged.GetCount();
1876             for ( size_t n = 0; n < count; n++ )
1877             {
1878                 RefreshLine(linesChanged[n]);
1879             }
1880         }
1881     }
1882     else // iterate over all items in non report view
1883     {
1884         for ( size_t line = lineFrom; line <= lineTo; line++ )
1885         {
1886             if ( HighlightLine(line, highlight) )
1887                 RefreshLine(line);
1888         }
1889     }
1890 }
1891
1892 bool wxListMainWindow::HighlightLine( size_t line, bool highlight )
1893 {
1894     bool changed;
1895
1896     if ( IsVirtual() )
1897     {
1898         changed = m_selStore.SelectItem(line, highlight);
1899     }
1900     else // !virtual
1901     {
1902         wxListLineData *ld = GetLine(line);
1903         wxCHECK_MSG( ld, false, wxT("invalid index in HighlightLine") );
1904
1905         changed = ld->Highlight(highlight);
1906     }
1907
1908     if ( changed )
1909     {
1910         SendNotify( line, highlight ? wxEVT_LIST_ITEM_SELECTED
1911                                     : wxEVT_LIST_ITEM_DESELECTED );
1912     }
1913
1914     return changed;
1915 }
1916
1917 void wxListMainWindow::RefreshLine( size_t line )
1918 {
1919     if ( InReportView() )
1920     {
1921         size_t visibleFrom, visibleTo;
1922         GetVisibleLinesRange(&visibleFrom, &visibleTo);
1923
1924         if ( line < visibleFrom || line > visibleTo )
1925             return;
1926     }
1927
1928     wxRect rect = GetLineRect(line);
1929
1930     GetListCtrl()->CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
1931     RefreshRect( rect );
1932 }
1933
1934 void wxListMainWindow::RefreshLines( size_t lineFrom, size_t lineTo )
1935 {
1936     // we suppose that they are ordered by caller
1937     wxASSERT_MSG( lineFrom <= lineTo, wxT("indices in disorder") );
1938
1939     wxASSERT_MSG( lineTo < GetItemCount(), wxT("invalid line range") );
1940
1941     if ( InReportView() )
1942     {
1943         size_t visibleFrom, visibleTo;
1944         GetVisibleLinesRange(&visibleFrom, &visibleTo);
1945
1946         if ( lineFrom < visibleFrom )
1947             lineFrom = visibleFrom;
1948         if ( lineTo > visibleTo )
1949             lineTo = visibleTo;
1950
1951         wxRect rect;
1952         rect.x = 0;
1953         rect.y = GetLineY(lineFrom);
1954         rect.width = GetClientSize().x;
1955         rect.height = GetLineY(lineTo) - rect.y + GetLineHeight();
1956
1957         GetListCtrl()->CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
1958         RefreshRect( rect );
1959     }
1960     else // !report
1961     {
1962         // TODO: this should be optimized...
1963         for ( size_t line = lineFrom; line <= lineTo; line++ )
1964         {
1965             RefreshLine(line);
1966         }
1967     }
1968 }
1969
1970 void wxListMainWindow::RefreshAfter( size_t lineFrom )
1971 {
1972     if ( InReportView() )
1973     {
1974         size_t visibleFrom, visibleTo;
1975         GetVisibleLinesRange(&visibleFrom, &visibleTo);
1976
1977         if ( lineFrom < visibleFrom )
1978             lineFrom = visibleFrom;
1979         else if ( lineFrom > visibleTo )
1980             return;
1981
1982         wxRect rect;
1983         rect.x = 0;
1984         rect.y = GetLineY(lineFrom);
1985         GetListCtrl()->CalcScrolledPosition( rect.x, rect.y, &rect.x, &rect.y );
1986
1987         wxSize size = GetClientSize();
1988         rect.width = size.x;
1989
1990         // refresh till the bottom of the window
1991         rect.height = size.y - rect.y;
1992
1993         RefreshRect( rect );
1994     }
1995     else // !report
1996     {
1997         // TODO: how to do it more efficiently?
1998         m_dirty = true;
1999     }
2000 }
2001
2002 void wxListMainWindow::RefreshSelected()
2003 {
2004     if ( IsEmpty() )
2005         return;
2006
2007     size_t from, to;
2008     if ( InReportView() )
2009     {
2010         GetVisibleLinesRange(&from, &to);
2011     }
2012     else // !virtual
2013     {
2014         from = 0;
2015         to = GetItemCount() - 1;
2016     }
2017
2018     if ( HasCurrent() && m_current >= from && m_current <= to )
2019         RefreshLine(m_current);
2020
2021     for ( size_t line = from; line <= to; line++ )
2022     {
2023         // NB: the test works as expected even if m_current == -1
2024         if ( line != m_current && IsHighlighted(line) )
2025             RefreshLine(line);
2026     }
2027 }
2028
2029 extern void wxListCtrl_onPaintCallback(wxGenericListCtrl *listctrl, wxDC *dc); //  2013.12.10. Toshi Nagata
2030
2031 void wxListMainWindow::OnPaint( wxPaintEvent &WXUNUSED(event) )
2032 {
2033     // Note: a wxPaintDC must be constructed even if no drawing is
2034     // done (a Windows requirement).
2035     wxPaintDC dc( this );
2036
2037     if ( IsEmpty() )
2038     {
2039         // nothing to draw or not the moment to draw it
2040         return;
2041     }
2042
2043     if ( m_dirty )
2044         RecalculatePositions( false );
2045
2046     GetListCtrl()->PrepareDC( dc );
2047
2048     int dev_x, dev_y;
2049     GetListCtrl()->CalcScrolledPosition( 0, 0, &dev_x, &dev_y );
2050
2051     dc.SetFont( GetFont() );
2052
2053     if ( InReportView() )
2054     {
2055         int lineHeight = GetLineHeight();
2056
2057         size_t visibleFrom, visibleTo;
2058         GetVisibleLinesRange(&visibleFrom, &visibleTo);
2059
2060         wxRect rectLine;
2061         int xOrig = dc.LogicalToDeviceX( 0 );
2062         int yOrig = dc.LogicalToDeviceY( 0 );
2063
2064         // tell the caller cache to cache the data
2065         if ( IsVirtual() )
2066         {
2067             wxListEvent evCache(wxEVT_LIST_CACHE_HINT,
2068                                 GetParent()->GetId());
2069             evCache.SetEventObject( GetParent() );
2070             evCache.m_oldItemIndex = visibleFrom;
2071             evCache.m_item.m_itemId =
2072             evCache.m_itemIndex = visibleTo;
2073             GetParent()->GetEventHandler()->ProcessEvent( evCache );
2074         }
2075
2076         for ( size_t line = visibleFrom; line <= visibleTo; line++ )
2077         {
2078             rectLine = GetLineRect(line);
2079
2080
2081             if ( !IsExposed(rectLine.x + xOrig, rectLine.y + yOrig,
2082                             rectLine.width, rectLine.height) )
2083             {
2084                 // don't redraw unaffected lines to avoid flicker
2085                 continue;
2086             }
2087
2088             GetLine(line)->DrawInReportMode( &dc,
2089                                              rectLine,
2090                                              GetLineHighlightRect(line),
2091                                              IsHighlighted(line),
2092                                              line == m_current, line ); // 2013.12.10. Toshi Nagata; add "line" argument
2093         }
2094
2095         if ( HasFlag(wxLC_HRULES) )
2096         {
2097             wxPen pen(GetRuleColour(), 1, wxPENSTYLE_SOLID);
2098             wxSize clientSize = GetClientSize();
2099
2100             size_t i = visibleFrom;
2101             if (i == 0) i = 1; // Don't draw the first one
2102             for ( ; i <= visibleTo; i++ )
2103             {
2104                 dc.SetPen(pen);
2105                 dc.SetBrush( *wxTRANSPARENT_BRUSH );
2106                 dc.DrawLine(0 - dev_x, i * lineHeight,
2107                             clientSize.x - dev_x, i * lineHeight);
2108             }
2109
2110             // Draw last horizontal rule
2111             if ( visibleTo == GetItemCount() - 1 )
2112             {
2113                 dc.SetPen( pen );
2114                 dc.SetBrush( *wxTRANSPARENT_BRUSH );
2115                 dc.DrawLine(0 - dev_x, (m_lineTo + 1) * lineHeight,
2116                             clientSize.x - dev_x , (m_lineTo + 1) * lineHeight );
2117             }
2118         }
2119
2120         // Draw vertical rules if required
2121         if ( HasFlag(wxLC_VRULES) && !IsEmpty() )
2122         {
2123             wxPen pen(GetRuleColour(), 1, wxPENSTYLE_SOLID);
2124             wxRect firstItemRect, lastItemRect;
2125
2126             GetItemRect(visibleFrom, firstItemRect);
2127             GetItemRect(visibleTo, lastItemRect);
2128             int x = firstItemRect.GetX();
2129             dc.SetPen(pen);
2130             dc.SetBrush(* wxTRANSPARENT_BRUSH);
2131
2132             for (int col = 0; col < GetColumnCount(); col++)
2133             {
2134                 int colWidth = GetColumnWidth(col);
2135                 x += colWidth;
2136                 int x_pos = x - dev_x;
2137                 if (col < GetColumnCount()-1) x_pos -= 2;
2138                 dc.DrawLine(x_pos, firstItemRect.GetY() - 1 - dev_y,
2139                             x_pos, lastItemRect.GetBottom() + 1 - dev_y);
2140             }
2141         }
2142     }
2143     else // !report
2144     {
2145         size_t count = GetItemCount();
2146         for ( size_t i = 0; i < count; i++ )
2147         {
2148             GetLine(i)->Draw( &dc, i == m_current );
2149         }
2150     }
2151
2152         ::wxListCtrl_onPaintCallback(GetListCtrl(), &dc);  // 2013.12.10. Toshi Nagata
2153
2154     // DrawFocusRect() is unusable under Mac, it draws outside of the highlight
2155     // rectangle somehow and so leaves traces when the item is not selected any
2156     // more, see #12229.
2157 #ifndef __WXMAC__
2158     if ( HasCurrent() )
2159     {
2160         int flags = 0;
2161         if ( IsHighlighted(m_current) )
2162             flags |= wxCONTROL_SELECTED;
2163
2164         wxRendererNative::Get().
2165             DrawFocusRect(this, dc, GetLineHighlightRect(m_current), flags);
2166     }
2167 #endif // !__WXMAC__
2168 }
2169
2170 void wxListMainWindow::HighlightAll( bool on )
2171 {
2172     if ( IsSingleSel() )
2173     {
2174         wxASSERT_MSG( !on, wxT("can't do this in a single selection control") );
2175
2176         // we just have one item to turn off
2177         if ( HasCurrent() && IsHighlighted(m_current) )
2178         {
2179             HighlightLine(m_current, false);
2180             RefreshLine(m_current);
2181         }
2182     }
2183     else // multi selection
2184     {
2185         if ( !IsEmpty() )
2186             HighlightLines(0, GetItemCount() - 1, on);
2187     }
2188 }
2189
2190 void wxListMainWindow::OnChildFocus(wxChildFocusEvent& WXUNUSED(event))
2191 {
2192     // Do nothing here.  This prevents the default handler in wxScrolledWindow
2193     // from needlessly scrolling the window when the edit control is
2194     // dismissed.  See ticket #9563.
2195 }
2196
2197 void wxListMainWindow::SendNotify( size_t line,
2198                                    wxEventType command,
2199                                    const wxPoint& point )
2200 {
2201     wxListEvent le( command, GetParent()->GetId() );
2202     le.SetEventObject( GetParent() );
2203
2204     le.m_item.m_itemId =
2205     le.m_itemIndex = line;
2206
2207     // set only for events which have position
2208     if ( point != wxDefaultPosition )
2209         le.m_pointDrag = point;
2210
2211     // don't try to get the line info for virtual list controls: the main
2212     // program has it anyhow and if we did it would result in accessing all
2213     // the lines, even those which are not visible now and this is precisely
2214     // what we're trying to avoid
2215     if ( !IsVirtual() )
2216     {
2217         if ( line != (size_t)-1 )
2218         {
2219             GetLine(line)->GetItem( 0, le.m_item );
2220         }
2221         //else: this happens for wxEVT_LIST_ITEM_FOCUSED event
2222     }
2223     //else: there may be no more such item
2224
2225     GetParent()->GetEventHandler()->ProcessEvent( le );
2226 }
2227
2228 void wxListMainWindow::ChangeCurrent(size_t current)
2229 {
2230     m_current = current;
2231
2232     // as the current item changed, we shouldn't start editing it when the
2233     // "slow click" timer expires as the click happened on another item
2234     if ( m_renameTimer->IsRunning() )
2235         m_renameTimer->Stop();
2236
2237     SendNotify(current, wxEVT_LIST_ITEM_FOCUSED);
2238 }
2239
2240 wxTextCtrl *wxListMainWindow::EditLabel(long item, wxClassInfo* textControlClass)
2241 {
2242     wxCHECK_MSG( (item >= 0) && ((size_t)item < GetItemCount()), NULL,
2243                  wxT("wrong index in wxGenericListCtrl::EditLabel()") );
2244
2245     wxASSERT_MSG( textControlClass->IsKindOf(wxCLASSINFO(wxTextCtrl)),
2246                  wxT("EditLabel() needs a text control") );
2247
2248     size_t itemEdit = (size_t)item;
2249
2250     wxListEvent le( wxEVT_LIST_BEGIN_LABEL_EDIT, GetParent()->GetId() );
2251     le.SetEventObject( GetParent() );
2252     le.m_item.m_itemId =
2253     le.m_itemIndex = item;
2254     wxListLineData *data = GetLine(itemEdit);
2255     wxCHECK_MSG( data, NULL, wxT("invalid index in EditLabel()") );
2256     data->GetItem( 0, le.m_item );
2257
2258     if ( GetParent()->GetEventHandler()->ProcessEvent( le ) && !le.IsAllowed() )
2259     {
2260         // vetoed by user code
2261         return NULL;
2262     }
2263
2264     if ( m_dirty )
2265     {
2266         // Ensure the display is updated before we start editing.
2267         Update();
2268     }
2269
2270     wxTextCtrl * const text = (wxTextCtrl *)textControlClass->CreateObject();
2271     m_textctrlWrapper = new wxListTextCtrlWrapper(this, text, item);
2272     return m_textctrlWrapper->GetText();
2273 }
2274
2275 void wxListMainWindow::OnRenameTimer()
2276 {
2277     wxCHECK_RET( HasCurrent(), wxT("unexpected rename timer") );
2278
2279     EditLabel( m_current );
2280 }
2281
2282 bool wxListMainWindow::OnRenameAccept(size_t itemEdit, const wxString& value)
2283 {
2284     wxListEvent le( wxEVT_LIST_END_LABEL_EDIT, GetParent()->GetId() );
2285     le.SetEventObject( GetParent() );
2286     le.m_item.m_itemId =
2287     le.m_itemIndex = itemEdit;
2288
2289     wxListLineData *data = GetLine(itemEdit);
2290
2291     wxCHECK_MSG( data, false, wxT("invalid index in OnRenameAccept()") );
2292
2293     data->GetItem( 0, le.m_item );
2294     le.m_item.m_text = value;
2295     return !GetParent()->GetEventHandler()->ProcessEvent( le ) ||
2296                 le.IsAllowed();
2297 }
2298
2299 void wxListMainWindow::OnRenameCancelled(size_t itemEdit)
2300 {
2301     // let owner know that the edit was cancelled
2302     wxListEvent le( wxEVT_LIST_END_LABEL_EDIT, GetParent()->GetId() );
2303
2304     le.SetEditCanceled(true);
2305
2306     le.SetEventObject( GetParent() );
2307     le.m_item.m_itemId =
2308     le.m_itemIndex = itemEdit;
2309
2310     wxListLineData *data = GetLine(itemEdit);
2311     wxCHECK_RET( data, wxT("invalid index in OnRenameCancelled()") );
2312
2313     data->GetItem( 0, le.m_item );
2314     GetEventHandler()->ProcessEvent( le );
2315 }
2316
2317 void wxListMainWindow::OnFindTimer()
2318 {
2319     m_findPrefix.clear();
2320     if ( m_findBell )
2321         m_findBell = 1;
2322 }
2323
2324 void wxListMainWindow::EnableBellOnNoMatch( bool on )
2325 {
2326     m_findBell = on;
2327 }
2328
2329 void wxListMainWindow::OnMouse( wxMouseEvent &event )
2330 {
2331 #ifdef __WXMAC__
2332     // On wxMac we can't depend on the EVT_KILL_FOCUS event to properly
2333     // shutdown the edit control when the mouse is clicked elsewhere on the
2334     // listctrl because the order of events is different (or something like
2335     // that), so explicitly end the edit if it is active.
2336     if ( event.LeftDown() && m_textctrlWrapper )
2337         m_textctrlWrapper->EndEdit(wxListTextCtrlWrapper::End_Accept);
2338 #endif // __WXMAC__
2339
2340     if ( event.LeftDown() )
2341     {
2342         // Ensure we skip the event to let the system set focus to this window.
2343         event.Skip();
2344     }
2345
2346     // Pretend that the event happened in wxListCtrl itself.
2347     wxMouseEvent me(event);
2348     me.SetEventObject( GetParent() );
2349     me.SetId(GetParent()->GetId());
2350     if ( GetParent()->GetEventHandler()->ProcessEvent( me ))
2351         return;
2352
2353     if (event.GetEventType() == wxEVT_MOUSEWHEEL)
2354     {
2355         // let the base class handle mouse wheel events.
2356         event.Skip();
2357         return;
2358     }
2359
2360     if ( !HasCurrent() || IsEmpty() )
2361     {
2362         if (event.RightDown())
2363         {
2364             SendNotify( (size_t)-1, wxEVT_LIST_ITEM_RIGHT_CLICK, event.GetPosition() );
2365
2366             wxContextMenuEvent evtCtx(wxEVT_CONTEXT_MENU,
2367                                       GetParent()->GetId(),
2368                                       ClientToScreen(event.GetPosition()));
2369             evtCtx.SetEventObject(GetParent());
2370             GetParent()->GetEventHandler()->ProcessEvent(evtCtx);
2371         }
2372         return;
2373     }
2374
2375     if (m_dirty)
2376         return;
2377
2378     if ( !(event.Dragging() || event.ButtonDown() || event.LeftUp() ||
2379         event.ButtonDClick()) )
2380         return;
2381
2382     int x = event.GetX();
2383     int y = event.GetY();
2384     GetListCtrl()->CalcUnscrolledPosition( x, y, &x, &y );
2385
2386     // where did we hit it (if we did)?
2387     long hitResult = 0;
2388
2389     size_t count = GetItemCount(),
2390            current;
2391
2392     if ( InReportView() )
2393     {
2394         current = y / GetLineHeight();
2395         if ( current < count )
2396             hitResult = HitTestLine(current, x, y);
2397     }
2398     else // !report
2399     {
2400         // TODO: optimize it too! this is less simple than for report view but
2401         //       enumerating all items is still not a way to do it!!
2402         for ( current = 0; current < count; current++ )
2403         {
2404             hitResult = HitTestLine(current, x, y);
2405             if ( hitResult )
2406                 break;
2407         }
2408     }
2409
2410     // Update drag events counter first as we must do it even if the mouse is
2411     // not on any item right now as we must keep count in case we started
2412     // dragging from the empty control area but continued to do it over a valid
2413     // item -- in this situation we must not start dragging this item.
2414     if (event.Dragging())
2415         m_dragCount++;
2416     else
2417         m_dragCount = 0;
2418
2419     // The only mouse event that can be generated without any valid item is
2420     // wxEVT_LIST_ITEM_RIGHT_CLICK as it can be useful to have a global
2421     // popup menu for the list control itself which should be shown even when
2422     // the user clicks outside of any item.
2423     if ( !hitResult )
2424     {
2425         // outside of any item
2426         if (event.RightDown())
2427         {
2428             SendNotify( (size_t) -1, wxEVT_LIST_ITEM_RIGHT_CLICK, event.GetPosition() );
2429
2430             wxContextMenuEvent evtCtx(
2431                 wxEVT_CONTEXT_MENU,
2432                 GetParent()->GetId(),
2433                 ClientToScreen(event.GetPosition()));
2434             evtCtx.SetEventObject(GetParent());
2435             GetParent()->GetEventHandler()->ProcessEvent(evtCtx);
2436         }
2437         else
2438         {
2439             // reset the selection and bail out
2440             HighlightAll(false);
2441         }
2442
2443         return;
2444     }
2445
2446     if ( event.Dragging() )
2447     {
2448         if (m_dragCount == 1)
2449         {
2450             // we have to report the raw, physical coords as we want to be
2451             // able to call HitTest(event.m_pointDrag) from the user code to
2452             // get the item being dragged
2453             m_dragStart = event.GetPosition();
2454         }
2455
2456         if (m_dragCount != 3)
2457             return;
2458
2459         int command = event.RightIsDown() ? wxEVT_LIST_BEGIN_RDRAG
2460                                           : wxEVT_LIST_BEGIN_DRAG;
2461
2462         SendNotify( m_lineLastClicked, command, m_dragStart );
2463
2464         return;
2465     }
2466
2467     bool forceClick = false;
2468     if (event.ButtonDClick())
2469     {
2470         if ( m_renameTimer->IsRunning() )
2471             m_renameTimer->Stop();
2472
2473         m_lastOnSame = false;
2474
2475         if ( current == m_lineLastClicked )
2476         {
2477             SendNotify( current, wxEVT_LIST_ITEM_ACTIVATED );
2478
2479             return;
2480         }
2481         else
2482         {
2483             // The first click was on another item, so don't interpret this as
2484             // a double click, but as a simple click instead
2485             forceClick = true;
2486         }
2487     }
2488
2489     if (event.LeftUp())
2490     {
2491         if (m_lineSelectSingleOnUp != (size_t)-1)
2492         {
2493             // select single line
2494             HighlightAll( false );
2495             ReverseHighlight(m_lineSelectSingleOnUp);
2496         }
2497
2498         if (m_lastOnSame)
2499         {
2500             if ((current == m_current) &&
2501                 (hitResult == wxLIST_HITTEST_ONITEMLABEL) &&
2502                 HasFlag(wxLC_EDIT_LABELS) )
2503             {
2504                 if ( !InReportView() ||
2505                         GetLineLabelRect(current).Contains(x, y) )
2506                 {
2507                     int dclick = wxSystemSettings::GetMetric(wxSYS_DCLICK_MSEC);
2508                     m_renameTimer->Start(dclick > 0 ? dclick : 250, true);
2509                 }
2510             }
2511
2512             m_lastOnSame = false;
2513         }
2514
2515         m_lineSelectSingleOnUp = (size_t)-1;
2516     }
2517     else
2518     {
2519         // This is necessary, because after a DnD operation in
2520         // from and to ourself, the up event is swallowed by the
2521         // DnD code. So on next non-up event (which means here and
2522         // now) m_lineSelectSingleOnUp should be reset.
2523         m_lineSelectSingleOnUp = (size_t)-1;
2524     }
2525     if (event.RightDown())
2526     {
2527         m_lineBeforeLastClicked = m_lineLastClicked;
2528         m_lineLastClicked = current;
2529
2530         // If the item is already selected, do not update the selection.
2531         // Multi-selections should not be cleared if a selected item is clicked.
2532         if (!IsHighlighted(current))
2533         {
2534             HighlightAll(false);
2535             ChangeCurrent(current);
2536             ReverseHighlight(m_current);
2537         }
2538
2539         SendNotify( current, wxEVT_LIST_ITEM_RIGHT_CLICK, event.GetPosition() );
2540
2541         // Allow generation of context menu event
2542         event.Skip();
2543     }
2544     else if (event.MiddleDown())
2545     {
2546         SendNotify( current, wxEVT_LIST_ITEM_MIDDLE_CLICK );
2547     }
2548     else if ( event.LeftDown() || forceClick )
2549     {
2550         m_lineBeforeLastClicked = m_lineLastClicked;
2551         m_lineLastClicked = current;
2552
2553         size_t oldCurrent = m_current;
2554         bool oldWasSelected = IsHighlighted(m_current);
2555
2556         bool cmdModifierDown = event.CmdDown();
2557         if ( IsSingleSel() || !(cmdModifierDown || event.ShiftDown()) )
2558         {
2559             if ( IsSingleSel() || !IsHighlighted(current) )
2560             {
2561                 HighlightAll( false );
2562
2563                 ChangeCurrent(current);
2564
2565                 ReverseHighlight(m_current);
2566             }
2567             else // multi sel & current is highlighted & no mod keys
2568             {
2569                 m_lineSelectSingleOnUp = current;
2570                 ChangeCurrent(current); // change focus
2571             }
2572         }
2573         else // multi sel & either ctrl or shift is down
2574         {
2575             if (cmdModifierDown)
2576             {
2577                 ChangeCurrent(current);
2578
2579                 ReverseHighlight(m_current);
2580             }
2581             else if (event.ShiftDown())
2582             {
2583                 ChangeCurrent(current);
2584
2585                 size_t lineFrom = oldCurrent,
2586                        lineTo = current;
2587
2588                 if ( lineTo < lineFrom )
2589                 {
2590                     lineTo = lineFrom;
2591                     lineFrom = m_current;
2592                 }
2593
2594                 HighlightLines(lineFrom, lineTo);
2595             }
2596             else // !ctrl, !shift
2597             {
2598                 // test in the enclosing if should make it impossible
2599                 wxFAIL_MSG( wxT("how did we get here?") );
2600             }
2601         }
2602
2603         if (m_current != oldCurrent)
2604             RefreshLine( oldCurrent );
2605
2606         // Set the flag telling us whether the next click on this item should
2607         // start editing its label. This should happen if we clicked on the
2608         // current item and it was already selected, i.e. if this click was not
2609         // done to select it.
2610         //
2611         // It should not happen if this was a double click (forceClick is true)
2612         // nor if we hadn't had the focus before as then this click was used to
2613         // give focus to the control.
2614         m_lastOnSame = (m_current == oldCurrent) && oldWasSelected &&
2615                             !forceClick && HasFocus();
2616     }
2617 }
2618
2619 void wxListMainWindow::MoveToItem(size_t item)
2620 {
2621     if ( item == (size_t)-1 )
2622         return;
2623
2624     wxRect rect = GetLineRect(item);
2625
2626     int client_w, client_h;
2627     GetClientSize( &client_w, &client_h );
2628
2629     const int hLine = GetLineHeight();
2630
2631     int view_x = SCROLL_UNIT_X * GetListCtrl()->GetScrollPos( wxHORIZONTAL );
2632     int view_y = hLine * GetListCtrl()->GetScrollPos( wxVERTICAL );
2633
2634     if ( InReportView() )
2635     {
2636         // the next we need the range of lines shown it might be different,
2637         // so recalculate it
2638         ResetVisibleLinesRange();
2639
2640         if (rect.y < view_y)
2641             GetListCtrl()->Scroll( -1, rect.y / hLine );
2642         if (rect.y + rect.height + 5 > view_y + client_h)
2643             GetListCtrl()->Scroll( -1, (rect.y + rect.height - client_h + hLine) / hLine );
2644
2645 #ifdef __WXMAC__
2646         // At least on Mac the visible lines value will get reset inside of
2647         // Scroll *before* it actually scrolls the window because of the
2648         // Update() that happens there, so it will still have the wrong value.
2649         // So let's reset it again and wait for it to be recalculated in the
2650         // next paint event.  I would expect this problem to show up in wxGTK
2651         // too but couldn't duplicate it there.  Perhaps the order of events
2652         // is different...  --Robin
2653         ResetVisibleLinesRange();
2654 #endif
2655     }
2656     else // !report
2657     {
2658         int sx = -1,
2659             sy = -1;
2660
2661         if (rect.x-view_x < 5)
2662             sx = (rect.x - 5) / SCROLL_UNIT_X;
2663         if (rect.x + rect.width - 5 > view_x + client_w)
2664             sx = (rect.x + rect.width - client_w + SCROLL_UNIT_X) / SCROLL_UNIT_X;
2665
2666         if (rect.y-view_y < 5)
2667             sy = (rect.y - 5) / hLine;
2668         if (rect.y + rect.height - 5 > view_y + client_h)
2669             sy = (rect.y + rect.height - client_h + hLine) / hLine;
2670
2671         GetListCtrl()->Scroll(sx, sy);
2672     }
2673 }
2674
2675 bool wxListMainWindow::ScrollList(int WXUNUSED(dx), int dy)
2676 {
2677     if ( !InReportView() )
2678     {
2679         // TODO: this should work in all views but is not implemented now
2680         return false;
2681     }
2682
2683     size_t top, bottom;
2684     GetVisibleLinesRange(&top, &bottom);
2685
2686     if ( bottom == (size_t)-1 )
2687         return 0;
2688
2689     ResetVisibleLinesRange();
2690
2691     int hLine = GetLineHeight();
2692
2693     GetListCtrl()->Scroll(-1, top + dy / hLine);
2694
2695 #ifdef __WXMAC__
2696     // see comment in MoveToItem() for why we do this
2697     ResetVisibleLinesRange();
2698 #endif
2699
2700     return true;
2701 }
2702
2703 // ----------------------------------------------------------------------------
2704 // keyboard handling
2705 // ----------------------------------------------------------------------------
2706
2707 void wxListMainWindow::OnArrowChar(size_t newCurrent, const wxKeyEvent& event)
2708 {
2709     wxCHECK_RET( newCurrent < (size_t)GetItemCount(),
2710                  wxT("invalid item index in OnArrowChar()") );
2711
2712     size_t oldCurrent = m_current;
2713
2714     // in single selection we just ignore Shift as we can't select several
2715     // items anyhow
2716     if ( event.ShiftDown() && !IsSingleSel() )
2717     {
2718         ChangeCurrent(newCurrent);
2719
2720         // refresh the old focus to remove it
2721         RefreshLine( oldCurrent );
2722
2723         // select all the items between the old and the new one
2724         if ( oldCurrent > newCurrent )
2725         {
2726             newCurrent = oldCurrent;
2727             oldCurrent = m_current;
2728         }
2729
2730         HighlightLines(oldCurrent, newCurrent);
2731     }
2732     else // !shift
2733     {
2734         // all previously selected items are unselected unless ctrl is held
2735         // in a multiselection control
2736         if ( !event.ControlDown() || IsSingleSel() )
2737             HighlightAll(false);
2738
2739         ChangeCurrent(newCurrent);
2740
2741         // refresh the old focus to remove it
2742         RefreshLine( oldCurrent );
2743
2744         // in single selection mode we must always have a selected item
2745         if ( !event.ControlDown() || IsSingleSel() )
2746             HighlightLine( m_current, true );
2747     }
2748
2749     RefreshLine( m_current );
2750
2751     MoveToFocus();
2752 }
2753
2754 void wxListMainWindow::OnKeyDown( wxKeyEvent &event )
2755 {
2756     wxWindow *parent = GetParent();
2757
2758     // propagate the key event upwards
2759     wxKeyEvent ke(event);
2760     ke.SetEventObject( parent );
2761     ke.SetId(GetParent()->GetId());
2762     if (parent->GetEventHandler()->ProcessEvent( ke ))
2763         return;
2764
2765     // send a list event
2766     wxListEvent le( wxEVT_LIST_KEY_DOWN, parent->GetId() );
2767     le.m_item.m_itemId =
2768     le.m_itemIndex = m_current;
2769     if (HasCurrent())
2770         GetLine(m_current)->GetItem( 0, le.m_item );
2771     le.m_code = event.GetKeyCode();
2772     le.SetEventObject( parent );
2773     if (parent->GetEventHandler()->ProcessEvent( le ))
2774         return;
2775
2776     event.Skip();
2777 }
2778
2779 void wxListMainWindow::OnKeyUp( wxKeyEvent &event )
2780 {
2781     wxWindow *parent = GetParent();
2782
2783     // propagate the key event upwards
2784     wxKeyEvent ke(event);
2785     ke.SetEventObject( parent );
2786     ke.SetId(GetParent()->GetId());
2787     if (parent->GetEventHandler()->ProcessEvent( ke ))
2788         return;
2789
2790     event.Skip();
2791 }
2792
2793 void wxListMainWindow::OnCharHook( wxKeyEvent &event )
2794 {
2795     if ( m_textctrlWrapper )
2796     {
2797         // When an in-place editor is active we should ensure that it always
2798         // gets the key events that are special to it.
2799         if ( m_textctrlWrapper->CheckForEndEditKey(event) )
2800         {
2801             // Skip the call to wxEvent::Skip() below.
2802             return;
2803         }
2804     }
2805
2806     event.Skip();
2807 }
2808
2809 void wxListMainWindow::OnChar( wxKeyEvent &event )
2810 {
2811     wxWindow *parent = GetParent();
2812
2813     // propagate the char event upwards
2814     wxKeyEvent ke(event);
2815     ke.SetEventObject( parent );
2816     ke.SetId(GetParent()->GetId());
2817     if (parent->GetEventHandler()->ProcessEvent( ke ))
2818         return;
2819
2820     if ( HandleAsNavigationKey(event) )
2821         return;
2822
2823     // no item -> nothing to do
2824     if (!HasCurrent())
2825     {
2826         event.Skip();
2827         return;
2828     }
2829
2830     // don't use m_linesPerPage directly as it might not be computed yet
2831     const int pageSize = GetCountPerPage();
2832     wxCHECK_RET( pageSize, wxT("should have non zero page size") );
2833
2834     if (GetLayoutDirection() == wxLayout_RightToLeft)
2835     {
2836         if (event.GetKeyCode() == WXK_RIGHT)
2837             event.m_keyCode = WXK_LEFT;
2838         else if (event.GetKeyCode() == WXK_LEFT)
2839             event.m_keyCode = WXK_RIGHT;
2840     }
2841
2842     int keyCode = event.GetKeyCode();
2843     switch ( keyCode )
2844     {
2845         case WXK_UP:
2846             if ( m_current > 0 )
2847                 OnArrowChar( m_current - 1, event );
2848             break;
2849
2850         case WXK_DOWN:
2851             if ( m_current < (size_t)GetItemCount() - 1 )
2852                 OnArrowChar( m_current + 1, event );
2853             break;
2854
2855         case WXK_END:
2856             if (!IsEmpty())
2857                 OnArrowChar( GetItemCount() - 1, event );
2858             break;
2859
2860         case WXK_HOME:
2861             if (!IsEmpty())
2862                 OnArrowChar( 0, event );
2863             break;
2864
2865         case WXK_PAGEUP:
2866             {
2867                 int steps = InReportView() ? pageSize - 1
2868                                            : m_current % pageSize;
2869
2870                 int index = m_current - steps;
2871                 if (index < 0)
2872                     index = 0;
2873
2874                 OnArrowChar( index, event );
2875             }
2876             break;
2877
2878         case WXK_PAGEDOWN:
2879             {
2880                 int steps = InReportView()
2881                                 ? pageSize - 1
2882                                 : pageSize - (m_current % pageSize) - 1;
2883
2884                 size_t index = m_current + steps;
2885                 size_t count = GetItemCount();
2886                 if ( index >= count )
2887                     index = count - 1;
2888
2889                 OnArrowChar( index, event );
2890             }
2891             break;
2892
2893         case WXK_LEFT:
2894             if ( !InReportView() )
2895             {
2896                 int index = m_current - pageSize;
2897                 if (index < 0)
2898                     index = 0;
2899
2900                 OnArrowChar( index, event );
2901             }
2902             break;
2903
2904         case WXK_RIGHT:
2905             if ( !InReportView() )
2906             {
2907                 size_t index = m_current + pageSize;
2908
2909                 size_t count = GetItemCount();
2910                 if ( index >= count )
2911                     index = count - 1;
2912
2913                 OnArrowChar( index, event );
2914             }
2915             break;
2916
2917         case WXK_SPACE:
2918             if ( IsSingleSel() )
2919             {
2920                 if ( event.ControlDown() )
2921                 {
2922                     ReverseHighlight(m_current);
2923                 }
2924                 else // normal space press
2925                 {
2926                     SendNotify( m_current, wxEVT_LIST_ITEM_ACTIVATED );
2927                 }
2928             }
2929             else // multiple selection
2930             {
2931                 ReverseHighlight(m_current);
2932             }
2933             break;
2934
2935         case WXK_RETURN:
2936         case WXK_EXECUTE:
2937             SendNotify( m_current, wxEVT_LIST_ITEM_ACTIVATED );
2938             break;
2939
2940         default:
2941             if ( !event.HasModifiers() &&
2942                  ((keyCode >= '0' && keyCode <= '9') ||
2943                   (keyCode >= 'a' && keyCode <= 'z') ||
2944                   (keyCode >= 'A' && keyCode <= 'Z') ||
2945                   (keyCode == '_') ||
2946                   (keyCode == '+') ||
2947                   (keyCode == '*') ||
2948                   (keyCode == '-')))
2949             {
2950                 // find the next item starting with the given prefix
2951                 wxChar ch = (wxChar)keyCode;
2952                 size_t item;
2953
2954                 // if the same character is typed multiple times then go to the
2955                 // next entry starting with that character instead of searching
2956                 // for an item starting with multiple copies of this character,
2957                 // this is more useful and is how it works under Windows.
2958                 if ( m_findPrefix.length() == 1 && m_findPrefix[0] == ch )
2959                 {
2960                     item = PrefixFindItem(m_current, ch);
2961                 }
2962                 else
2963                 {
2964                     const wxString newPrefix(m_findPrefix + ch);
2965                     item = PrefixFindItem(m_current, newPrefix);
2966                     if ( item != (size_t)-1 )
2967                         m_findPrefix = newPrefix;
2968                 }
2969
2970                 // also start the timer to reset the current prefix if the user
2971                 // doesn't press any more alnum keys soon -- we wouldn't want
2972                 // to use this prefix for a new item search
2973                 if ( !m_findTimer )
2974                 {
2975                     m_findTimer = new wxListFindTimer( this );
2976                 }
2977
2978                 // Notice that we should start the timer even if we didn't find
2979                 // anything to make sure we reset the search state later.
2980                 m_findTimer->Start(wxListFindTimer::DELAY, wxTIMER_ONE_SHOT);
2981
2982                 // restart timer even when there's no match so bell get's reset
2983                 if ( item != (size_t)-1 )
2984                 {
2985                     // Select the found item and go to it.
2986                     HighlightAll(false);
2987                     SetItemState(item,
2988                                  wxLIST_STATE_FOCUSED | wxLIST_STATE_SELECTED,
2989                                  wxLIST_STATE_FOCUSED | wxLIST_STATE_SELECTED);
2990
2991                     // Reset the bell flag if it had been temporarily disabled
2992                     // before.
2993                     if ( m_findBell )
2994                         m_findBell = 1;
2995                 }
2996                 else // No such item
2997                 {
2998                     // Signal it with a bell if enabled.
2999                     if ( m_findBell == 1 )
3000                     {
3001                         ::wxBell();
3002
3003                         // Disable it for the next unsuccessful match, we only
3004                         // beep once, this is usually enough and continuing to
3005                         // do it would be annoying.
3006                         m_findBell = -1;
3007                     }
3008                 }
3009             }
3010             else
3011             {
3012                 event.Skip();
3013             }
3014     }
3015 }
3016
3017 // ----------------------------------------------------------------------------
3018 // focus handling
3019 // ----------------------------------------------------------------------------
3020
3021 void wxListMainWindow::OnSetFocus( wxFocusEvent &WXUNUSED(event) )
3022 {
3023     if ( GetParent() )
3024     {
3025         wxFocusEvent event( wxEVT_SET_FOCUS, GetParent()->GetId() );
3026         event.SetEventObject( GetParent() );
3027         if ( GetParent()->GetEventHandler()->ProcessEvent( event) )
3028             return;
3029     }
3030
3031     // wxGTK sends us EVT_SET_FOCUS events even if we had never got
3032     // EVT_KILL_FOCUS before which means that we finish by redrawing the items
3033     // which are already drawn correctly resulting in horrible flicker - avoid
3034     // it
3035     if ( !m_hasFocus )
3036     {
3037         m_hasFocus = true;
3038
3039         RefreshSelected();
3040     }
3041 }
3042
3043 void wxListMainWindow::OnKillFocus( wxFocusEvent &WXUNUSED(event) )
3044 {
3045     if ( GetParent() )
3046     {
3047         wxFocusEvent event( wxEVT_KILL_FOCUS, GetParent()->GetId() );
3048         event.SetEventObject( GetParent() );
3049         if ( GetParent()->GetEventHandler()->ProcessEvent( event) )
3050             return;
3051     }
3052
3053     m_hasFocus = false;
3054     RefreshSelected();
3055 }
3056
3057 void wxListMainWindow::DrawImage( int index, wxDC *dc, int x, int y )
3058 {
3059     if ( HasFlag(wxLC_ICON) && (m_normal_image_list))
3060     {
3061         m_normal_image_list->Draw( index, *dc, x, y, wxIMAGELIST_DRAW_TRANSPARENT );
3062     }
3063     else if ( HasFlag(wxLC_SMALL_ICON) && (m_small_image_list))
3064     {
3065         m_small_image_list->Draw( index, *dc, x, y, wxIMAGELIST_DRAW_TRANSPARENT );
3066     }
3067     else if ( HasFlag(wxLC_LIST) && (m_small_image_list))
3068     {
3069         m_small_image_list->Draw( index, *dc, x, y, wxIMAGELIST_DRAW_TRANSPARENT );
3070     }
3071     else if ( InReportView() && (m_small_image_list))
3072     {
3073         m_small_image_list->Draw( index, *dc, x, y, wxIMAGELIST_DRAW_TRANSPARENT );
3074     }
3075 }
3076
3077 void wxListMainWindow::GetImageSize( int index, int &width, int &height ) const
3078 {
3079     if ( HasFlag(wxLC_ICON) && m_normal_image_list )
3080     {
3081         m_normal_image_list->GetSize( index, width, height );
3082     }
3083     else if ( HasFlag(wxLC_SMALL_ICON) && m_small_image_list )
3084     {
3085         m_small_image_list->GetSize( index, width, height );
3086     }
3087     else if ( HasFlag(wxLC_LIST) && m_small_image_list )
3088     {
3089         m_small_image_list->GetSize( index, width, height );
3090     }
3091     else if ( InReportView() && m_small_image_list )
3092     {
3093         m_small_image_list->GetSize( index, width, height );
3094     }
3095     else
3096     {
3097         width =
3098         height = 0;
3099     }
3100 }
3101
3102 void wxListMainWindow::SetImageList( wxImageList *imageList, int which )
3103 {
3104     m_dirty = true;
3105
3106     // calc the spacing from the icon size
3107     int width = 0, height = 0;
3108
3109     if ((imageList) && (imageList->GetImageCount()) )
3110         imageList->GetSize(0, width, height);
3111
3112     if (which == wxIMAGE_LIST_NORMAL)
3113     {
3114         m_normal_image_list = imageList;
3115         m_normal_spacing = width + 8;
3116     }
3117
3118     if (which == wxIMAGE_LIST_SMALL)
3119     {
3120         m_small_image_list = imageList;
3121         m_small_spacing = width + 14;
3122         m_lineHeight = 0;  // ensure that the line height will be recalc'd
3123     }
3124 }
3125
3126 void wxListMainWindow::SetItemSpacing( int spacing, bool isSmall )
3127 {
3128     m_dirty = true;
3129     if (isSmall)
3130         m_small_spacing = spacing;
3131     else
3132         m_normal_spacing = spacing;
3133 }
3134
3135 int wxListMainWindow::GetItemSpacing( bool isSmall )
3136 {
3137     return isSmall ? m_small_spacing : m_normal_spacing;
3138 }
3139
3140 // ----------------------------------------------------------------------------
3141 // columns
3142 // ----------------------------------------------------------------------------
3143
3144 int
3145 wxListMainWindow::ComputeMinHeaderWidth(const wxListHeaderData* column) const
3146 {
3147     wxClientDC dc(const_cast<wxListMainWindow*>(this));
3148
3149     int width = dc.GetTextExtent(column->GetText()).x + AUTOSIZE_COL_MARGIN;
3150
3151     width += 2*EXTRA_WIDTH;
3152
3153     // check for column header's image availability
3154     const int image = column->GetImage();
3155     if ( image != -1 )
3156     {
3157         if ( m_small_image_list )
3158         {
3159             int ix = 0, iy = 0;
3160             m_small_image_list->GetSize(image, ix, iy);
3161             width += ix + HEADER_IMAGE_MARGIN_IN_REPORT_MODE;
3162         }
3163     }
3164
3165     return width;
3166 }
3167
3168 void wxListMainWindow::SetColumn( int col, const wxListItem &item )
3169 {
3170     wxListHeaderDataList::compatibility_iterator node = m_columns.Item( col );
3171
3172     wxCHECK_RET( node, wxT("invalid column index in SetColumn") );
3173
3174     wxListHeaderData *column = node->GetData();
3175     column->SetItem( item );
3176
3177     if ( item.m_width == wxLIST_AUTOSIZE_USEHEADER )
3178         column->SetWidth(ComputeMinHeaderWidth(column));
3179
3180     wxListHeaderWindow *headerWin = GetListCtrl()->m_headerWin;
3181     if ( headerWin )
3182         headerWin->m_dirty = true;
3183
3184     m_dirty = true;
3185
3186     // invalidate it as it has to be recalculated
3187     m_headerWidth = 0;
3188 }
3189
3190 void wxListMainWindow::SetColumnWidth( int col, int width )
3191 {
3192     wxCHECK_RET( col >= 0 && col < GetColumnCount(),
3193                  wxT("invalid column index") );
3194
3195     wxCHECK_RET( InReportView(),
3196                  wxT("SetColumnWidth() can only be called in report mode.") );
3197
3198     m_dirty = true;
3199
3200     wxListHeaderWindow *headerWin = GetListCtrl()->m_headerWin;
3201     if ( headerWin )
3202         headerWin->m_dirty = true;
3203
3204     wxListHeaderDataList::compatibility_iterator node = m_columns.Item( col );
3205     wxCHECK_RET( node, wxT("no column?") );
3206
3207     wxListHeaderData *column = node->GetData();
3208
3209     size_t count = GetItemCount();
3210
3211     if (width == wxLIST_AUTOSIZE_USEHEADER)
3212     {
3213         width = ComputeMinHeaderWidth(column);
3214     }
3215     else if ( width == wxLIST_AUTOSIZE )
3216     {
3217         width = ComputeMinHeaderWidth(column);
3218
3219         if ( !IsVirtual() )
3220         {
3221             wxClientDC dc(this);
3222             dc.SetFont( GetFont() );
3223
3224             int max = AUTOSIZE_COL_MARGIN;
3225
3226             //  if the cached column width isn't valid then recalculate it
3227             if (m_aColWidths.Item(col)->bNeedsUpdate)
3228             {
3229                 for (size_t i = 0; i < count; i++)
3230                 {
3231                     wxListLineData *line = GetLine( i );
3232                     wxListItemDataList::compatibility_iterator n = line->m_items.Item( col );
3233
3234                     wxCHECK_RET( n, wxT("no subitem?") );
3235
3236                     wxListItemData *itemData = n->GetData();
3237                     wxListItem      item;
3238
3239                     itemData->GetItem(item);
3240                     int itemWidth = GetItemWidthWithImage(&item);
3241                     if (itemWidth > max)
3242                         max = itemWidth;
3243                 }
3244
3245                 m_aColWidths.Item(col)->bNeedsUpdate = false;
3246                 m_aColWidths.Item(col)->nMaxWidth = max;
3247             }
3248
3249             max = m_aColWidths.Item(col)->nMaxWidth + AUTOSIZE_COL_MARGIN;
3250             if ( width < max )
3251                 width = max;
3252         }
3253     }
3254
3255     column->SetWidth( width );
3256
3257     // invalidate it as it has to be recalculated
3258     m_headerWidth = 0;
3259 }
3260
3261 int wxListMainWindow::GetHeaderWidth() const
3262 {
3263     if ( !m_headerWidth )
3264     {
3265         wxListMainWindow *self = wxConstCast(this, wxListMainWindow);
3266
3267         size_t count = GetColumnCount();
3268         for ( size_t col = 0; col < count; col++ )
3269         {
3270             self->m_headerWidth += GetColumnWidth(col);
3271         }
3272     }
3273
3274     return m_headerWidth;
3275 }
3276
3277 void wxListMainWindow::GetColumn( int col, wxListItem &item ) const
3278 {
3279     wxListHeaderDataList::compatibility_iterator node = m_columns.Item( col );
3280     wxCHECK_RET( node, wxT("invalid column index in GetColumn") );
3281
3282     wxListHeaderData *column = node->GetData();
3283     column->GetItem( item );
3284 }
3285
3286 int wxListMainWindow::GetColumnWidth( int col ) const
3287 {
3288     wxListHeaderDataList::compatibility_iterator node = m_columns.Item( col );
3289     wxCHECK_MSG( node, 0, wxT("invalid column index") );
3290
3291     wxListHeaderData *column = node->GetData();
3292     return column->GetWidth();
3293 }
3294
3295 // ----------------------------------------------------------------------------
3296 // item state
3297 // ----------------------------------------------------------------------------
3298
3299 void wxListMainWindow::SetItem( wxListItem &item )
3300 {
3301     long id = item.m_itemId;
3302     wxCHECK_RET( id >= 0 && (size_t)id < GetItemCount(),
3303                  wxT("invalid item index in SetItem") );
3304
3305     if ( !IsVirtual() )
3306     {
3307         wxListLineData *line = GetLine((size_t)id);
3308         line->SetItem( item.m_col, item );
3309
3310         // Set item state if user wants
3311         if ( item.m_mask & wxLIST_MASK_STATE )
3312             SetItemState( item.m_itemId, item.m_state, item.m_state );
3313
3314         if (InReportView())
3315         {
3316             //  update the Max Width Cache if needed
3317             int width = GetItemWidthWithImage(&item);
3318
3319             if (width > m_aColWidths.Item(item.m_col)->nMaxWidth)
3320                 m_aColWidths.Item(item.m_col)->nMaxWidth = width;
3321         }
3322     }
3323
3324     // update the item on screen unless we're going to update everything soon
3325     // anyhow
3326     if ( !m_dirty )
3327     {
3328         wxRect rectItem;
3329         GetItemRect(id, rectItem);
3330         RefreshRect(rectItem);
3331     }
3332 }
3333
3334 void wxListMainWindow::SetItemStateAll(long state, long stateMask)
3335 {
3336     if ( IsEmpty() )
3337         return;
3338
3339     // first deal with selection
3340     if ( stateMask & wxLIST_STATE_SELECTED )
3341     {
3342         // set/clear select state
3343         if ( IsVirtual() )
3344         {
3345             // optimized version for virtual listctrl.
3346             m_selStore.SelectRange(0, GetItemCount() - 1, state == wxLIST_STATE_SELECTED);
3347             Refresh();
3348         }
3349         else if ( state & wxLIST_STATE_SELECTED )
3350         {
3351             const long count = GetItemCount();
3352             for( long i = 0; i <  count; i++ )
3353             {
3354                 SetItemState( i, wxLIST_STATE_SELECTED, wxLIST_STATE_SELECTED );
3355             }
3356
3357         }
3358         else
3359         {
3360             // clear for non virtual (somewhat optimized by using GetNextItem())
3361             long i = -1;
3362             while ( (i = GetNextItem(i, wxLIST_NEXT_ALL, wxLIST_STATE_SELECTED)) != -1 )
3363             {
3364                 SetItemState( i, 0, wxLIST_STATE_SELECTED );
3365             }
3366         }
3367     }
3368
3369     if ( HasCurrent() && (state == 0) && (stateMask & wxLIST_STATE_FOCUSED) )
3370     {
3371         // unfocus all: only one item can be focussed, so clearing focus for
3372         // all items is simply clearing focus of the focussed item.
3373         SetItemState(m_current, state, stateMask);
3374     }
3375     //(setting focus to all items makes no sense, so it is not handled here.)
3376 }
3377
3378 void wxListMainWindow::SetItemState( long litem, long state, long stateMask )
3379 {
3380     if ( litem == -1 )
3381     {
3382         SetItemStateAll(state, stateMask);
3383         return;
3384     }
3385
3386     wxCHECK_RET( litem >= 0 && (size_t)litem < GetItemCount(),
3387                  wxT("invalid list ctrl item index in SetItem") );
3388
3389     size_t oldCurrent = m_current;
3390     size_t item = (size_t)litem;    // safe because of the check above
3391
3392     // do we need to change the focus?
3393     if ( stateMask & wxLIST_STATE_FOCUSED )
3394     {
3395         if ( state & wxLIST_STATE_FOCUSED )
3396         {
3397             // don't do anything if this item is already focused
3398             if ( item != m_current )
3399             {
3400                 ChangeCurrent(item);
3401
3402                 if ( oldCurrent != (size_t)-1 )
3403                 {
3404                     if ( IsSingleSel() )
3405                     {
3406                         HighlightLine(oldCurrent, false);
3407                     }
3408
3409                     RefreshLine(oldCurrent);
3410                 }
3411
3412                 RefreshLine( m_current );
3413             }
3414         }
3415         else // unfocus
3416         {
3417             // don't do anything if this item is not focused
3418             if ( item == m_current )
3419             {
3420                 ResetCurrent();
3421
3422                 if ( IsSingleSel() )
3423                 {
3424                     // we must unselect the old current item as well or we
3425                     // might end up with more than one selected item in a
3426                     // single selection control
3427                     HighlightLine(oldCurrent, false);
3428                 }
3429
3430                 RefreshLine( oldCurrent );
3431             }
3432         }
3433     }
3434
3435     // do we need to change the selection state?
3436     if ( stateMask & wxLIST_STATE_SELECTED )
3437     {
3438         bool on = (state & wxLIST_STATE_SELECTED) != 0;
3439
3440         if ( IsSingleSel() )
3441         {
3442             if ( on )
3443             {
3444                 // selecting the item also makes it the focused one in the
3445                 // single sel mode
3446                 if ( m_current != item )
3447                 {
3448                     ChangeCurrent(item);
3449
3450                     if ( oldCurrent != (size_t)-1 )
3451                     {
3452                         HighlightLine( oldCurrent, false );
3453                         RefreshLine( oldCurrent );
3454                     }
3455                 }
3456             }
3457             else // off
3458             {
3459                 // only the current item may be selected anyhow
3460                 if ( item != m_current )
3461                     return;
3462             }
3463         }
3464
3465         if ( HighlightLine(item, on) )
3466         {
3467             RefreshLine(item);
3468         }
3469     }
3470 }
3471
3472 int wxListMainWindow::GetItemState( long item, long stateMask ) const
3473 {
3474     wxCHECK_MSG( item >= 0 && (size_t)item < GetItemCount(), 0,
3475                  wxT("invalid list ctrl item index in GetItemState()") );
3476
3477     int ret = wxLIST_STATE_DONTCARE;
3478
3479     if ( stateMask & wxLIST_STATE_FOCUSED )
3480     {
3481         if ( (size_t)item == m_current )
3482             ret |= wxLIST_STATE_FOCUSED;
3483     }
3484
3485     if ( stateMask & wxLIST_STATE_SELECTED )
3486     {
3487         if ( IsHighlighted(item) )
3488             ret |= wxLIST_STATE_SELECTED;
3489     }
3490
3491     return ret;
3492 }
3493
3494 void wxListMainWindow::GetItem( wxListItem &item ) const
3495 {
3496     wxCHECK_RET( item.m_itemId >= 0 && (size_t)item.m_itemId < GetItemCount(),
3497                  wxT("invalid item index in GetItem") );
3498
3499     wxListLineData *line = GetLine((size_t)item.m_itemId);
3500     line->GetItem( item.m_col, item );
3501
3502     // Get item state if user wants it
3503     if ( item.m_mask & wxLIST_MASK_STATE )
3504         item.m_state = GetItemState( item.m_itemId, wxLIST_STATE_SELECTED |
3505                                                  wxLIST_STATE_FOCUSED );
3506 }
3507
3508 // ----------------------------------------------------------------------------
3509 // item count
3510 // ----------------------------------------------------------------------------
3511
3512 size_t wxListMainWindow::GetItemCount() const
3513 {
3514     return IsVirtual() ? m_countVirt : m_lines.GetCount();
3515 }
3516
3517 void wxListMainWindow::SetItemCount(long count)
3518 {
3519     // Update the current item if it's not valid any longer (notice that this
3520     // invalidates it completely if the control is becoming empty, which is the
3521     // right thing to do).
3522     if ( HasCurrent() && m_current >= (size_t)count )
3523         ChangeCurrent(count - 1);
3524
3525     m_selStore.SetItemCount(count);
3526     m_countVirt = count;
3527
3528     ResetVisibleLinesRange();
3529
3530     // scrollbars must be reset
3531     m_dirty = true;
3532 }
3533
3534 int wxListMainWindow::GetSelectedItemCount() const
3535 {
3536     // deal with the quick case first
3537     if ( IsSingleSel() )
3538         return HasCurrent() ? IsHighlighted(m_current) : false;
3539
3540     // virtual controls remmebers all its selections itself
3541     if ( IsVirtual() )
3542         return m_selStore.GetSelectedCount();
3543
3544     // TODO: we probably should maintain the number of items selected even for
3545     //       non virtual controls as enumerating all lines is really slow...
3546     size_t countSel = 0;
3547     size_t count = GetItemCount();
3548     for ( size_t line = 0; line < count; line++ )
3549     {
3550         if ( GetLine(line)->IsHighlighted() )
3551             countSel++;
3552     }
3553
3554     return countSel;
3555 }
3556
3557 // ----------------------------------------------------------------------------
3558 // item position/size
3559 // ----------------------------------------------------------------------------
3560
3561 wxRect wxListMainWindow::GetViewRect() const
3562 {
3563     wxASSERT_MSG( !HasFlag(wxLC_LIST), "not implemented for list view" );
3564
3565     // we need to find the longest/tallest label
3566     wxCoord xMax = 0, yMax = 0;
3567     const int count = GetItemCount();
3568     if ( count )
3569     {
3570         for ( int i = 0; i < count; i++ )
3571         {
3572             // we need logical, not physical, coordinates here, so use
3573             // GetLineRect() instead of GetItemRect()
3574             wxRect r = GetLineRect(i);
3575
3576             wxCoord x = r.GetRight(),
3577                     y = r.GetBottom();
3578
3579             if ( x > xMax )
3580                 xMax = x;
3581             if ( y > yMax )
3582                 yMax = y;
3583         }
3584     }
3585
3586     // some fudge needed to make it look prettier
3587     xMax += 2 * EXTRA_BORDER_X;
3588     yMax += 2 * EXTRA_BORDER_Y;
3589
3590     // account for the scrollbars if necessary
3591     const wxSize sizeAll = GetClientSize();
3592     if ( xMax > sizeAll.x )
3593         yMax += wxSystemSettings::GetMetric(wxSYS_HSCROLL_Y);
3594     if ( yMax > sizeAll.y )
3595         xMax += wxSystemSettings::GetMetric(wxSYS_VSCROLL_X);
3596
3597     return wxRect(0, 0, xMax, yMax);
3598 }
3599
3600 bool
3601 wxListMainWindow::GetSubItemRect(long item, long subItem, wxRect& rect) const
3602 {
3603     wxCHECK_MSG( subItem == wxLIST_GETSUBITEMRECT_WHOLEITEM || InReportView(),
3604                  false,
3605                  wxT("GetSubItemRect only meaningful in report view") );
3606     wxCHECK_MSG( item >= 0 && (size_t)item < GetItemCount(), false,
3607                  wxT("invalid item in GetSubItemRect") );
3608
3609     // ensure that we're laid out, otherwise we could return nonsense
3610     if ( m_dirty )
3611     {
3612         wxConstCast(this, wxListMainWindow)->
3613             RecalculatePositions(true /* no refresh */);
3614     }
3615
3616     rect = GetLineRect((size_t)item);
3617
3618     // Adjust rect to specified column
3619     if ( subItem != wxLIST_GETSUBITEMRECT_WHOLEITEM )
3620     {
3621         wxCHECK_MSG( subItem >= 0 && subItem < GetColumnCount(), false,
3622                      wxT("invalid subItem in GetSubItemRect") );
3623
3624         for (int i = 0; i < subItem; i++)
3625         {
3626             rect.x += GetColumnWidth(i);
3627         }
3628         rect.width = GetColumnWidth(subItem);
3629     }
3630
3631     GetListCtrl()->CalcScrolledPosition(rect.x, rect.y, &rect.x, &rect.y);
3632
3633     return true;
3634 }
3635
3636 bool wxListMainWindow::GetItemPosition(long item, wxPoint& pos) const
3637 {
3638     wxRect rect;
3639     GetItemRect(item, rect);
3640
3641     pos.x = rect.x;
3642     pos.y = rect.y;
3643
3644     return true;
3645 }
3646
3647 // ----------------------------------------------------------------------------
3648 // geometry calculation
3649 // ----------------------------------------------------------------------------
3650
3651 void wxListMainWindow::RecalculatePositions(bool noRefresh)
3652 {
3653     const int lineHeight = GetLineHeight();
3654
3655     wxClientDC dc( this );
3656     dc.SetFont( GetFont() );
3657
3658     const size_t count = GetItemCount();
3659
3660     int iconSpacing;
3661     if ( HasFlag(wxLC_ICON) && m_normal_image_list )
3662         iconSpacing = m_normal_spacing;
3663     else if ( HasFlag(wxLC_SMALL_ICON) && m_small_image_list )
3664         iconSpacing = m_small_spacing;
3665     else
3666         iconSpacing = 0;
3667
3668     // Note that we do not call GetClientSize() here but
3669     // GetSize() and subtract the border size for sunken
3670     // borders manually. This is technically incorrect,
3671     // but we need to know the client area's size WITHOUT
3672     // scrollbars here. Since we don't know if there are
3673     // any scrollbars, we use GetSize() instead. Another
3674     // solution would be to call SetScrollbars() here to
3675     // remove the scrollbars and call GetClientSize() then,
3676     // but this might result in flicker and - worse - will
3677     // reset the scrollbars to 0 which is not good at all
3678     // if you resize a dialog/window, but don't want to
3679     // reset the window scrolling. RR.
3680     // Furthermore, we actually do NOT subtract the border
3681     // width as 2 pixels is just the extra space which we
3682     // need around the actual content in the window. Other-
3683     // wise the text would e.g. touch the upper border. RR.
3684     int clientWidth,
3685         clientHeight;
3686     GetSize( &clientWidth, &clientHeight );
3687
3688     if ( InReportView() )
3689     {
3690         // all lines have the same height and we scroll one line per step
3691         int entireHeight = count * lineHeight + LINE_SPACING;
3692
3693         m_linesPerPage = clientHeight / lineHeight;
3694
3695         ResetVisibleLinesRange();
3696
3697         GetListCtrl()->SetScrollbars( SCROLL_UNIT_X, lineHeight,
3698                        GetHeaderWidth() / SCROLL_UNIT_X,
3699                        (entireHeight + lineHeight - 1) / lineHeight,
3700                        GetListCtrl()->GetScrollPos(wxHORIZONTAL),
3701                        GetListCtrl()->GetScrollPos(wxVERTICAL),
3702                        true );
3703     }
3704     else // !report
3705     {
3706         // we have 3 different layout strategies: either layout all items
3707         // horizontally/vertically (wxLC_ALIGN_XXX styles explicitly given) or
3708         // to arrange them in top to bottom, left to right (don't ask me why
3709         // not the other way round...) order
3710         if ( HasFlag(wxLC_ALIGN_LEFT | wxLC_ALIGN_TOP) )
3711         {
3712             int x = EXTRA_BORDER_X;
3713             int y = EXTRA_BORDER_Y;
3714
3715             wxCoord widthMax = 0;
3716
3717             size_t i;
3718             for ( i = 0; i < count; i++ )
3719             {
3720                 wxListLineData *line = GetLine(i);
3721                 line->CalculateSize( &dc, iconSpacing );
3722                 line->SetPosition( x, y, iconSpacing );
3723
3724                 wxSize sizeLine = GetLineSize(i);
3725
3726                 if ( HasFlag(wxLC_ALIGN_TOP) )
3727                 {
3728                     if ( sizeLine.x > widthMax )
3729                         widthMax = sizeLine.x;
3730
3731                     y += sizeLine.y;
3732                 }
3733                 else // wxLC_ALIGN_LEFT
3734                 {
3735                     x += sizeLine.x + MARGIN_BETWEEN_ROWS;
3736                 }
3737             }
3738
3739             if ( HasFlag(wxLC_ALIGN_TOP) )
3740             {
3741                 // traverse the items again and tweak their sizes so that they are
3742                 // all the same in a row
3743                 for ( i = 0; i < count; i++ )
3744                 {
3745                     wxListLineData *line = GetLine(i);
3746                     line->m_gi->ExtendWidth(widthMax);
3747                 }
3748             }
3749
3750             GetListCtrl()->SetScrollbars
3751             (
3752                 SCROLL_UNIT_X,
3753                 lineHeight,
3754                 (x + SCROLL_UNIT_X) / SCROLL_UNIT_X,
3755                 (y + lineHeight) / lineHeight,
3756                 GetListCtrl()->GetScrollPos( wxHORIZONTAL ),
3757                 GetListCtrl()->GetScrollPos( wxVERTICAL ),
3758                 true
3759             );
3760         }
3761         else // "flowed" arrangement, the most complicated case
3762         {
3763             // at first we try without any scrollbars, if the items don't fit into
3764             // the window, we recalculate after subtracting the space taken by the
3765             // scrollbar
3766
3767             int entireWidth = 0;
3768
3769             for (int tries = 0; tries < 2; tries++)
3770             {
3771                 entireWidth = 2 * EXTRA_BORDER_X;
3772
3773                 if (tries == 1)
3774                 {
3775                     // Now we have decided that the items do not fit into the
3776                     // client area, so we need a scrollbar
3777                     entireWidth += SCROLL_UNIT_X;
3778                 }
3779
3780                 int x = EXTRA_BORDER_X;
3781                 int y = EXTRA_BORDER_Y;
3782
3783                 // Note that "row" here is vertical, i.e. what is called
3784                 // "column" in many other places in wxWidgets.
3785                 int maxWidthInThisRow = 0;
3786
3787                 m_linesPerPage = 0;
3788                 int currentlyVisibleLines = 0;
3789
3790                 for (size_t i = 0; i < count; i++)
3791                 {
3792                     currentlyVisibleLines++;
3793                     wxListLineData *line = GetLine( i );
3794                     line->CalculateSize( &dc, iconSpacing );
3795                     line->SetPosition( x, y, iconSpacing );
3796
3797                     wxSize sizeLine = GetLineSize( i );
3798
3799                     if ( maxWidthInThisRow < sizeLine.x )
3800                         maxWidthInThisRow = sizeLine.x;
3801
3802                     y += sizeLine.y;
3803                     if (currentlyVisibleLines > m_linesPerPage)
3804                         m_linesPerPage = currentlyVisibleLines;
3805
3806                     // Have we reached the end of the row either because no
3807                     // more items would fit or because there are simply no more
3808                     // items?
3809                     if ( y + sizeLine.y >= clientHeight
3810                             || i == count - 1)
3811                     {
3812                         // Adjust all items in this row to have the same
3813                         // width to ensure that they all align horizontally in
3814                         // icon view.
3815                         if ( HasFlag(wxLC_ICON) || HasFlag(wxLC_SMALL_ICON) )
3816                         {
3817                             size_t firstRowLine = i - currentlyVisibleLines + 1;
3818                             for (size_t j = firstRowLine; j <= i; j++)
3819                             {
3820                                 GetLine(j)->m_gi->ExtendWidth(maxWidthInThisRow);
3821                             }
3822                         }
3823
3824                         currentlyVisibleLines = 0;
3825                         y = EXTRA_BORDER_Y;
3826                         maxWidthInThisRow += MARGIN_BETWEEN_ROWS;
3827                         x += maxWidthInThisRow;
3828                         entireWidth += maxWidthInThisRow;
3829                         maxWidthInThisRow = 0;
3830                     }
3831
3832                     if ( (tries == 0) &&
3833                             (entireWidth + SCROLL_UNIT_X > clientWidth) )
3834                     {
3835                         clientHeight -= wxSystemSettings::
3836                                             GetMetric(wxSYS_HSCROLL_Y);
3837                         m_linesPerPage = 0;
3838                         break;
3839                     }
3840
3841                     if ( i == count - 1 )
3842                         tries = 1;  // Everything fits, no second try required.
3843                 }
3844             }
3845
3846             GetListCtrl()->SetScrollbars
3847             (
3848                 SCROLL_UNIT_X,
3849                 lineHeight,
3850                 (entireWidth + SCROLL_UNIT_X) / SCROLL_UNIT_X,
3851                 0,
3852                 GetListCtrl()->GetScrollPos( wxHORIZONTAL ),
3853                 0,
3854                 true
3855             );
3856         }
3857     }
3858
3859     if ( !noRefresh )
3860     {
3861         // FIXME: why should we call it from here?
3862         UpdateCurrent();
3863
3864         RefreshAll();
3865     }
3866 }
3867
3868 void wxListMainWindow::RefreshAll()
3869 {
3870     m_dirty = false;
3871     Refresh();
3872
3873     wxListHeaderWindow *headerWin = GetListCtrl()->m_headerWin;
3874     if ( headerWin && headerWin->m_dirty )
3875     {
3876         headerWin->m_dirty = false;
3877         headerWin->Refresh();
3878     }
3879 }
3880
3881 void wxListMainWindow::UpdateCurrent()
3882 {
3883     if ( !HasCurrent() && !IsEmpty() )
3884         ChangeCurrent(0);
3885 }
3886
3887 long wxListMainWindow::GetNextItem( long item,
3888                                     int WXUNUSED(geometry),
3889                                     int state ) const
3890 {
3891     long ret = item,
3892          max = GetItemCount();
3893     wxCHECK_MSG( (ret == -1) || (ret < max), -1,
3894                  wxT("invalid listctrl index in GetNextItem()") );
3895
3896     // notice that we start with the next item (or the first one if item == -1)
3897     // and this is intentional to allow writing a simple loop to iterate over
3898     // all selected items
3899     ret++;
3900     if ( ret == max )
3901         // this is not an error because the index was OK initially,
3902         // just no such item
3903         return -1;
3904
3905     if ( !state )
3906         // any will do
3907         return (size_t)ret;
3908
3909     size_t count = GetItemCount();
3910     for ( size_t line = (size_t)ret; line < count; line++ )
3911     {
3912         if ( (state & wxLIST_STATE_FOCUSED) && (line == m_current) )
3913             return line;
3914
3915         if ( (state & wxLIST_STATE_SELECTED) && IsHighlighted(line) )
3916             return line;
3917     }
3918
3919     return -1;
3920 }
3921
3922 // ----------------------------------------------------------------------------
3923 // deleting stuff
3924 // ----------------------------------------------------------------------------
3925
3926 void wxListMainWindow::DeleteItem( long lindex )
3927 {
3928     size_t count = GetItemCount();
3929
3930     wxCHECK_RET( (lindex >= 0) && ((size_t)lindex < count),
3931                  wxT("invalid item index in DeleteItem") );
3932
3933     size_t index = (size_t)lindex;
3934
3935     // we don't need to adjust the index for the previous items
3936     if ( HasCurrent() && m_current >= index )
3937     {
3938         // if the current item is being deleted, we want the next one to
3939         // become selected - unless there is no next one - so don't adjust
3940         // m_current in this case
3941         if ( m_current != index || m_current == count - 1 )
3942             m_current--;
3943     }
3944
3945     if ( InReportView() )
3946     {
3947         //  mark the Column Max Width cache as dirty if the items in the line
3948         //  we're deleting contain the Max Column Width
3949         wxListLineData * const line = GetLine(index);
3950         wxListItemDataList::compatibility_iterator n;
3951         wxListItemData *itemData;
3952         wxListItem      item;
3953         int             itemWidth;
3954
3955         for (size_t i = 0; i < m_columns.GetCount(); i++)
3956         {
3957             n = line->m_items.Item( i );
3958             itemData = n->GetData();
3959             itemData->GetItem(item);
3960
3961             itemWidth = GetItemWidthWithImage(&item);
3962
3963             if (itemWidth >= m_aColWidths.Item(i)->nMaxWidth)
3964                 m_aColWidths.Item(i)->bNeedsUpdate = true;
3965         }
3966
3967         ResetVisibleLinesRange();
3968     }
3969
3970     SendNotify( index, wxEVT_LIST_DELETE_ITEM, wxDefaultPosition );
3971
3972     if ( IsVirtual() )
3973     {
3974         m_countVirt--;
3975         m_selStore.OnItemDelete(index);
3976     }
3977     else
3978     {
3979         m_lines.RemoveAt( index );
3980     }
3981
3982     // we need to refresh the (vert) scrollbar as the number of items changed
3983     m_dirty = true;
3984
3985     RefreshAfter(index);
3986 }
3987
3988 void wxListMainWindow::DeleteColumn( int col )
3989 {
3990     wxListHeaderDataList::compatibility_iterator node = m_columns.Item( col );
3991
3992     wxCHECK_RET( node, wxT("invalid column index in DeleteColumn()") );
3993
3994     m_dirty = true;
3995     delete node->GetData();
3996     m_columns.Erase( node );
3997
3998     if ( !IsVirtual() )
3999     {
4000         // update all the items
4001         for ( size_t i = 0; i < m_lines.GetCount(); i++ )
4002         {
4003             wxListLineData * const line = GetLine(i);
4004
4005             // In the following atypical but possible scenario it can be
4006             // legal to call DeleteColumn() but the items may not have any
4007             // values for it:
4008             //  1. In report view, insert a second column.
4009             //  2. Still in report view, add an item with 2 values.
4010             //  3. Switch to an icon (or list) view.
4011             //  4. Add an item -- necessarily with 1 value only.
4012             //  5. Switch back to report view.
4013             //  6. Call DeleteColumn().
4014             // So we need to check for this as otherwise we would simply crash
4015             // if this happens.
4016             if ( line->m_items.GetCount() <= static_cast<unsigned>(col) )
4017                 continue;
4018
4019             wxListItemDataList::compatibility_iterator n = line->m_items.Item( col );
4020             delete n->GetData();
4021             line->m_items.Erase(n);
4022         }
4023     }
4024
4025     if ( InReportView() )   //  we only cache max widths when in Report View
4026     {
4027         delete m_aColWidths.Item(col);
4028         m_aColWidths.RemoveAt(col);
4029     }
4030
4031     // invalidate it as it has to be recalculated
4032     m_headerWidth = 0;
4033 }
4034
4035 void wxListMainWindow::DoDeleteAllItems()
4036 {
4037     if ( IsEmpty() )
4038         // nothing to do - in particular, don't send the event
4039         return;
4040
4041     ResetCurrent();
4042
4043     // to make the deletion of all items faster, we don't send the
4044     // notifications for each item deletion in this case but only one event
4045     // for all of them: this is compatible with wxMSW and documented in
4046     // DeleteAllItems() description
4047
4048     wxListEvent event( wxEVT_LIST_DELETE_ALL_ITEMS, GetParent()->GetId() );
4049     event.SetEventObject( GetParent() );
4050     GetParent()->GetEventHandler()->ProcessEvent( event );
4051
4052     if ( IsVirtual() )
4053     {
4054         m_countVirt = 0;
4055         m_selStore.Clear();
4056     }
4057
4058     if ( InReportView() )
4059     {
4060         ResetVisibleLinesRange();
4061         for (size_t i = 0; i < m_aColWidths.GetCount(); i++)
4062         {
4063             m_aColWidths.Item(i)->bNeedsUpdate = true;
4064         }
4065     }
4066
4067     m_lines.Clear();
4068 }
4069
4070 void wxListMainWindow::DeleteAllItems()
4071 {
4072     DoDeleteAllItems();
4073
4074     RecalculatePositions();
4075 }
4076
4077 void wxListMainWindow::DeleteEverything()
4078 {
4079     WX_CLEAR_LIST(wxListHeaderDataList, m_columns);
4080     WX_CLEAR_ARRAY(m_aColWidths);
4081
4082     DeleteAllItems();
4083 }
4084
4085 // ----------------------------------------------------------------------------
4086 // scanning for an item
4087 // ----------------------------------------------------------------------------
4088
4089 void wxListMainWindow::EnsureVisible( long index )
4090 {
4091     wxCHECK_RET( index >= 0 && (size_t)index < GetItemCount(),
4092                  wxT("invalid index in EnsureVisible") );
4093
4094     // We have to call this here because the label in question might just have
4095     // been added and its position is not known yet
4096     if ( m_dirty )
4097         RecalculatePositions(true /* no refresh */);
4098
4099     MoveToItem((size_t)index);
4100 }
4101
4102 long wxListMainWindow::FindItem(long start, const wxString& str, bool partial )
4103 {
4104     if (str.empty())
4105         return wxNOT_FOUND;
4106
4107     long pos = start;
4108     wxString str_upper = str.Upper();
4109     if (pos < 0)
4110         pos = 0;
4111
4112     size_t count = GetItemCount();
4113     for ( size_t i = (size_t)pos; i < count; i++ )
4114     {
4115         wxListLineData *line = GetLine(i);
4116         wxString line_upper = line->GetText(0).Upper();
4117         if (!partial)
4118         {
4119             if (line_upper == str_upper )
4120                 return i;
4121         }
4122         else
4123         {
4124             if (line_upper.find(str_upper) == 0)
4125                 return i;
4126         }
4127     }
4128
4129     return wxNOT_FOUND;
4130 }
4131
4132 long wxListMainWindow::FindItem(long start, wxUIntPtr data)
4133 {
4134     long pos = start;
4135     if (pos < 0)
4136         pos = 0;
4137
4138     size_t count = GetItemCount();
4139     for (size_t i = (size_t)pos; i < count; i++)
4140     {
4141         wxListLineData *line = GetLine(i);
4142         wxListItem item;
4143         line->GetItem( 0, item );
4144         if (item.m_data == data)
4145             return i;
4146     }
4147
4148     return wxNOT_FOUND;
4149 }
4150
4151 long wxListMainWindow::FindItem( const wxPoint& pt )
4152 {
4153     size_t topItem;
4154     GetVisibleLinesRange( &topItem, NULL );
4155
4156     wxPoint p;
4157     GetItemPosition( GetItemCount() - 1, p );
4158     if ( p.y == 0 )
4159         return topItem;
4160
4161     long id = (long)floor( pt.y * double(GetItemCount() - topItem - 1) / p.y + topItem );
4162     if ( id >= 0 && id < (long)GetItemCount() )
4163         return id;
4164
4165     return wxNOT_FOUND;
4166 }
4167
4168 long wxListMainWindow::HitTest( int x, int y, int &flags ) const
4169 {
4170     GetListCtrl()->CalcUnscrolledPosition( x, y, &x, &y );
4171
4172     size_t count = GetItemCount();
4173
4174     if ( InReportView() )
4175     {
4176         size_t current = y / GetLineHeight();
4177         if ( current < count )
4178         {
4179             flags = HitTestLine(current, x, y);
4180             if ( flags )
4181                 return current;
4182         }
4183     }
4184     else // !report
4185     {
4186         // TODO: optimize it too! this is less simple than for report view but
4187         //       enumerating all items is still not a way to do it!!
4188         for ( size_t current = 0; current < count; current++ )
4189         {
4190             flags = HitTestLine(current, x, y);
4191             if ( flags )
4192                 return current;
4193         }
4194     }
4195
4196     return wxNOT_FOUND;
4197 }
4198
4199 // ----------------------------------------------------------------------------
4200 // adding stuff
4201 // ----------------------------------------------------------------------------
4202
4203 void wxListMainWindow::InsertItem( wxListItem &item )
4204 {
4205     wxASSERT_MSG( !IsVirtual(), wxT("can't be used with virtual control") );
4206
4207     int count = GetItemCount();
4208     wxCHECK_RET( item.m_itemId >= 0, wxT("invalid item index") );
4209
4210     if (item.m_itemId > count)
4211         item.m_itemId = count;
4212
4213     size_t id = item.m_itemId;
4214
4215     m_dirty = true;
4216
4217     if ( InReportView() )
4218     {
4219         ResetVisibleLinesRange();
4220
4221         const unsigned col = item.GetColumn();
4222         wxCHECK_RET( col < m_aColWidths.size(), "invalid item column" );
4223
4224         // calculate the width of the item and adjust the max column width
4225         wxColWidthInfo *pWidthInfo = m_aColWidths.Item(col);
4226         int width = GetItemWidthWithImage(&item);
4227         item.SetWidth(width);
4228         if (width > pWidthInfo->nMaxWidth)
4229             pWidthInfo->nMaxWidth = width;
4230     }
4231
4232     wxListLineData *line = new wxListLineData(this);
4233
4234     line->SetItem( item.m_col, item );
4235     if ( item.m_mask & wxLIST_MASK_IMAGE )
4236     {
4237         // Reset the buffered height if it's not big enough for the new image.
4238         int image = item.GetImage();
4239         if ( m_small_image_list && image != -1 && InReportView() )
4240         {
4241             int imageWidth, imageHeight;
4242             m_small_image_list->GetSize(image, imageWidth, imageHeight);
4243
4244             if ( imageHeight > m_lineHeight )
4245                 m_lineHeight = 0;
4246         }
4247     }
4248
4249     m_lines.Insert( line, id );
4250
4251     m_dirty = true;
4252
4253     // If an item is selected at or below the point of insertion, we need to
4254     // increment the member variables because the current row's index has gone
4255     // up by one
4256     if ( HasCurrent() && m_current >= id )
4257         m_current++;
4258
4259     SendNotify(id, wxEVT_LIST_INSERT_ITEM);
4260
4261     RefreshLines(id, GetItemCount() - 1);
4262 }
4263
4264 long wxListMainWindow::InsertColumn( long col, const wxListItem &item )
4265 {
4266     long idx = -1;
4267
4268     m_dirty = true;
4269     if ( InReportView() )
4270     {
4271         wxListHeaderData *column = new wxListHeaderData( item );
4272         if (item.m_width == wxLIST_AUTOSIZE_USEHEADER)
4273             column->SetWidth(ComputeMinHeaderWidth(column));
4274
4275         wxColWidthInfo *colWidthInfo = new wxColWidthInfo();
4276
4277         bool insert = (col >= 0) && ((size_t)col < m_columns.GetCount());
4278         if ( insert )
4279         {
4280             wxListHeaderDataList::compatibility_iterator
4281                 node = m_columns.Item( col );
4282             m_columns.Insert( node, column );
4283             m_aColWidths.Insert( colWidthInfo, col );
4284             idx = col;
4285         }
4286         else
4287         {
4288             idx = m_aColWidths.GetCount();
4289             m_columns.Append( column );
4290             m_aColWidths.Add( colWidthInfo );
4291         }
4292
4293         if ( !IsVirtual() )
4294         {
4295             // update all the items
4296             for ( size_t i = 0; i < m_lines.GetCount(); i++ )
4297             {
4298                 wxListLineData * const line = GetLine(i);
4299                 wxListItemData * const data = new wxListItemData(this);
4300                 if ( insert )
4301                     line->m_items.Insert(col, data);
4302                 else
4303                     line->m_items.Append(data);
4304             }
4305         }
4306
4307         // invalidate it as it has to be recalculated
4308         m_headerWidth = 0;
4309     }
4310     return idx;
4311 }
4312
4313 int wxListMainWindow::GetItemWidthWithImage(wxListItem * item)
4314 {
4315     int width = 0;
4316     wxClientDC dc(this);
4317
4318     dc.SetFont( GetFont() );
4319
4320     if (item->GetImage() != -1)
4321     {
4322         int ix, iy;
4323         GetImageSize( item->GetImage(), ix, iy );
4324         width += ix + 5;
4325     }
4326
4327     if (!item->GetText().empty())
4328     {
4329         wxCoord w;
4330         dc.GetTextExtent( item->GetText(), &w, NULL );
4331         width += w;
4332     }
4333
4334     return width;
4335 }
4336
4337 // ----------------------------------------------------------------------------
4338 // sorting
4339 // ----------------------------------------------------------------------------
4340
4341 static wxListCtrlCompare list_ctrl_compare_func_2;
4342 static wxIntPtr          list_ctrl_compare_data;
4343
4344 int LINKAGEMODE list_ctrl_compare_func_1( wxListLineData **arg1, wxListLineData **arg2 )
4345 {
4346     wxListLineData *line1 = *arg1;
4347     wxListLineData *line2 = *arg2;
4348     wxListItem item;
4349     line1->GetItem( 0, item );
4350     wxUIntPtr data1 = item.m_data;
4351     line2->GetItem( 0, item );
4352     wxUIntPtr data2 = item.m_data;
4353     return list_ctrl_compare_func_2( data1, data2, list_ctrl_compare_data );
4354 }
4355
4356 void wxListMainWindow::SortItems( wxListCtrlCompare fn, wxIntPtr data )
4357 {
4358     // selections won't make sense any more after sorting the items so reset
4359     // them
4360     HighlightAll(false);
4361     ResetCurrent();
4362
4363     list_ctrl_compare_func_2 = fn;
4364     list_ctrl_compare_data = data;
4365     m_lines.Sort( list_ctrl_compare_func_1 );
4366     m_dirty = true;
4367 }
4368
4369 // ----------------------------------------------------------------------------
4370 // scrolling
4371 // ----------------------------------------------------------------------------
4372
4373 void wxListMainWindow::OnScroll(wxScrollWinEvent& event)
4374 {
4375     // update our idea of which lines are shown when we redraw the window the
4376     // next time
4377     ResetVisibleLinesRange();
4378
4379     if ( event.GetOrientation() == wxHORIZONTAL && HasHeader() )
4380     {
4381         wxGenericListCtrl* lc = GetListCtrl();
4382         wxCHECK_RET( lc, wxT("no listctrl window?") );
4383
4384         if (lc->m_headerWin) // when we use wxLC_NO_HEADER, m_headerWin==NULL
4385         {
4386             lc->m_headerWin->Refresh();
4387             lc->m_headerWin->Update();
4388         }
4389     }
4390 }
4391
4392 int wxListMainWindow::GetCountPerPage() const
4393 {
4394     if ( !m_linesPerPage )
4395     {
4396         wxConstCast(this, wxListMainWindow)->
4397             m_linesPerPage = GetClientSize().y / GetLineHeight();
4398     }
4399
4400     return m_linesPerPage;
4401 }
4402
4403 void wxListMainWindow::GetVisibleLinesRange(size_t *from, size_t *to)
4404 {
4405     wxASSERT_MSG( InReportView(), wxT("this is for report mode only") );
4406
4407     if ( m_lineFrom == (size_t)-1 )
4408     {
4409         size_t count = GetItemCount();
4410         if ( count )
4411         {
4412             m_lineFrom = GetListCtrl()->GetScrollPos(wxVERTICAL);
4413
4414             // this may happen if SetScrollbars() hadn't been called yet
4415             if ( m_lineFrom >= count )
4416                 m_lineFrom = count - 1;
4417
4418             // we redraw one extra line but this is needed to make the redrawing
4419             // logic work when there is a fractional number of lines on screen
4420             m_lineTo = m_lineFrom + m_linesPerPage;
4421             if ( m_lineTo >= count )
4422                 m_lineTo = count - 1;
4423         }
4424         else // empty control
4425         {
4426             m_lineFrom = 0;
4427             m_lineTo = (size_t)-1;
4428         }
4429     }
4430
4431     wxASSERT_MSG( IsEmpty() ||
4432                   (m_lineFrom <= m_lineTo && m_lineTo < GetItemCount()),
4433                   wxT("GetVisibleLinesRange() returns incorrect result") );
4434
4435     if ( from )
4436         *from = m_lineFrom;
4437     if ( to )
4438         *to = m_lineTo;
4439 }
4440
4441 size_t
4442 wxListMainWindow::PrefixFindItem(size_t idParent,
4443                                  const wxString& prefixOrig) const
4444 {
4445     // if no items then just return
4446     if ( idParent == (size_t)-1 )
4447         return idParent;
4448
4449     // match is case insensitive as this is more convenient to the user: having
4450     // to press Shift-letter to go to the item starting with a capital letter
4451     // would be too bothersome
4452     wxString prefix = prefixOrig.Lower();
4453
4454     // determine the starting point: we shouldn't take the current item (this
4455     // allows to switch between two items starting with the same letter just by
4456     // pressing it) but we shouldn't jump to the next one if the user is
4457     // continuing to type as otherwise he might easily skip the item he wanted
4458     size_t itemid = idParent;
4459     if ( prefix.length() == 1 )
4460     {
4461         itemid += 1;
4462     }
4463
4464     // look for the item starting with the given prefix after it
4465     while ( ( itemid < (size_t)GetItemCount() ) &&
4466             !GetLine(itemid)->GetText(0).Lower().StartsWith(prefix) )
4467     {
4468         itemid += 1;
4469     }
4470
4471     // if we haven't found anything...
4472     if ( !( itemid < (size_t)GetItemCount() ) )
4473     {
4474         // ... wrap to the beginning
4475         itemid = 0;
4476
4477         // and try all the items (stop when we get to the one we started from)
4478         while ( ( itemid < (size_t)GetItemCount() ) && itemid != idParent &&
4479                     !GetLine(itemid)->GetText(0).Lower().StartsWith(prefix) )
4480         {
4481             itemid += 1;
4482         }
4483         // If we haven't found the item, id will be (size_t)-1, as per
4484         // documentation
4485         if ( !( itemid < (size_t)GetItemCount() ) ||
4486              ( ( itemid == idParent ) &&
4487                !GetLine(itemid)->GetText(0).Lower().StartsWith(prefix) ) )
4488         {
4489             itemid = (size_t)-1;
4490         }
4491     }
4492
4493     return itemid;
4494 }
4495
4496 // -------------------------------------------------------------------------------------
4497 // wxGenericListCtrl
4498 // -------------------------------------------------------------------------------------
4499
4500 IMPLEMENT_DYNAMIC_CLASS(wxGenericListCtrl, wxControl)
4501
4502 BEGIN_EVENT_TABLE(wxGenericListCtrl,wxListCtrlBase)
4503   EVT_SIZE(wxGenericListCtrl::OnSize)
4504   EVT_SCROLLWIN(wxGenericListCtrl::OnScroll)
4505 END_EVENT_TABLE()
4506
4507 void wxGenericListCtrl::Init()
4508 {
4509     m_imageListNormal = NULL;
4510     m_imageListSmall = NULL;
4511     m_imageListState = NULL;
4512
4513     m_ownsImageListNormal =
4514     m_ownsImageListSmall =
4515     m_ownsImageListState = false;
4516
4517     m_mainWin = NULL;
4518     m_headerWin = NULL;
4519 }
4520
4521 wxGenericListCtrl::~wxGenericListCtrl()
4522 {
4523     if (m_ownsImageListNormal)
4524         delete m_imageListNormal;
4525     if (m_ownsImageListSmall)
4526         delete m_imageListSmall;
4527     if (m_ownsImageListState)
4528         delete m_imageListState;
4529 }
4530
4531 void wxGenericListCtrl::CreateOrDestroyHeaderWindowAsNeeded()
4532 {
4533     bool needs_header = HasHeader();
4534     bool has_header = (m_headerWin != NULL);
4535
4536     if (needs_header == has_header)
4537         return;
4538
4539     if (needs_header)
4540     {
4541         // Notice that we must initialize m_headerWin first, and create the
4542         // real window only later, so that the test in the beginning of the
4543         // function blocks repeated creation of the header as it could happen
4544         // before via wxNavigationEnabled::AddChild() -> ToggleWindowStyle() ->
4545         // SetWindowStyleFlag().
4546         m_headerWin = new wxListHeaderWindow();
4547         m_headerWin->Create
4548                       (
4549                         this, wxID_ANY, m_mainWin,
4550                         wxPoint(0,0),
4551                         wxSize
4552                         (
4553                           GetClientSize().x,
4554                           wxRendererNative::Get().GetHeaderButtonHeight(this)
4555                         ),
4556                         wxTAB_TRAVERSAL
4557                       );
4558         
4559 #if defined( __WXMAC__ )
4560         static wxFont font( wxOSX_SYSTEM_FONT_SMALL );
4561         m_headerWin->SetFont( font );
4562 #endif
4563
4564         GetSizer()->Prepend( m_headerWin, 0, wxGROW );
4565     }
4566     else
4567     {
4568         GetSizer()->Detach( m_headerWin );
4569
4570         wxDELETE(m_headerWin);
4571     }
4572 }
4573
4574 bool wxGenericListCtrl::Create(wxWindow *parent,
4575                         wxWindowID id,
4576                         const wxPoint &pos,
4577                         const wxSize &size,
4578                         long style,
4579                         const wxValidator &validator,
4580                         const wxString &name)
4581 {
4582     Init();
4583
4584     // just like in other ports, an assert will fail if the user doesn't give any type style:
4585     wxASSERT_MSG( (style & wxLC_MASK_TYPE),
4586                   wxT("wxListCtrl style should have exactly one mode bit set") );
4587
4588     if ( !wxListCtrlBase::Create( parent, id, pos, size,
4589                                   style | wxVSCROLL | wxHSCROLL,
4590                                   validator, name ) )
4591         return false;
4592
4593     m_mainWin = new wxListMainWindow(this, wxID_ANY, wxPoint(0, 0), size);
4594
4595     SetTargetWindow( m_mainWin );
4596
4597     // We use the cursor keys for moving the selection, not scrolling, so call
4598     // this method to ensure wxScrollHelperEvtHandler doesn't catch all
4599     // keyboard events forwarded to us from wxListMainWindow.
4600     DisableKeyboardScrolling();
4601
4602     wxBoxSizer *sizer = new wxBoxSizer( wxVERTICAL );
4603     sizer->Add( m_mainWin, 1, wxGROW );
4604     SetSizer( sizer );
4605
4606     CreateOrDestroyHeaderWindowAsNeeded();
4607
4608     SetInitialSize(size);
4609
4610     return true;
4611 }
4612
4613 wxBorder wxGenericListCtrl::GetDefaultBorder() const
4614 {
4615     return wxBORDER_THEME;
4616 }
4617
4618 #if defined(__WXMSW__) && !defined(__WXWINCE__) && !defined(__WXUNIVERSAL__)
4619 WXLRESULT wxGenericListCtrl::MSWWindowProc(WXUINT nMsg,
4620                                        WXWPARAM wParam,
4621                                        WXLPARAM lParam)
4622 {
4623     WXLRESULT rc = wxListCtrlBase::MSWWindowProc(nMsg, wParam, lParam);
4624
4625     // we need to process arrows ourselves for scrolling
4626     if ( nMsg == WM_GETDLGCODE )
4627     {
4628         rc |= DLGC_WANTARROWS;
4629     }
4630
4631     return rc;
4632 }
4633 #endif // __WXMSW__
4634
4635 wxSize wxGenericListCtrl::GetSizeAvailableForScrollTarget(const wxSize& size)
4636 {
4637     wxSize newsize = size;
4638     if (m_headerWin)
4639        newsize.y -= m_headerWin->GetSize().y;
4640
4641     return newsize;
4642 }
4643
4644 void wxGenericListCtrl::OnScroll(wxScrollWinEvent& event)
4645 {
4646     // update our idea of which lines are shown when we redraw
4647     // the window the next time
4648     m_mainWin->ResetVisibleLinesRange();
4649
4650     if ( event.GetOrientation() == wxHORIZONTAL && HasHeader() )
4651     {
4652                 //  Toshi Nagata 2014.01.13.
4653                 //  Defer the scrolling of the header window after all scrolling of the
4654                 //  List window is complete
4655     //    m_headerWin->Refresh();
4656     //    m_headerWin->Update();
4657                 wxCommandEvent event(ListCtrlEvent);
4658                 m_headerWin->QueueListCtrlEvent(event);
4659                 //  End Toshi Nagata
4660     }
4661
4662         // Let the window be scrolled as usual by the default handler.
4663     event.Skip();       
4664 }
4665
4666 void wxGenericListCtrl::SetSingleStyle( long style, bool add )
4667 {
4668     wxASSERT_MSG( !(style & wxLC_VIRTUAL),
4669                   wxT("wxLC_VIRTUAL can't be [un]set") );
4670
4671     long flag = GetWindowStyle();
4672
4673     if (add)
4674     {
4675         if (style & wxLC_MASK_TYPE)
4676             flag &= ~(wxLC_MASK_TYPE | wxLC_VIRTUAL);
4677         if (style & wxLC_MASK_ALIGN)
4678             flag &= ~wxLC_MASK_ALIGN;
4679         if (style & wxLC_MASK_SORT)
4680             flag &= ~wxLC_MASK_SORT;
4681     }
4682
4683     if (add)
4684         flag |= style;
4685     else
4686         flag &= ~style;
4687
4688     // some styles can be set without recreating everything (as happens in
4689     // SetWindowStyleFlag() which calls wxListMainWindow::DeleteEverything())
4690     if ( !(style & ~(wxLC_HRULES | wxLC_VRULES)) )
4691     {
4692         Refresh();
4693         wxWindow::SetWindowStyleFlag(flag);
4694     }
4695     else
4696     {
4697         SetWindowStyleFlag( flag );
4698     }
4699 }
4700
4701 void wxGenericListCtrl::SetWindowStyleFlag( long flag )
4702 {
4703     // we add wxHSCROLL and wxVSCROLL in ctor unconditionally and it never
4704     // makes sense to remove them as we'll always add scrollbars anyhow when
4705     // needed
4706     flag |= wxHSCROLL | wxVSCROLL;
4707
4708     const bool wasInReportView = HasFlag(wxLC_REPORT);
4709
4710     // update the window style first so that the header is created or destroyed
4711     // corresponding to the new style
4712     wxWindow::SetWindowStyleFlag( flag );
4713
4714     if (m_mainWin)
4715     {
4716         const bool inReportView = (flag & wxLC_REPORT) != 0;
4717         if ( inReportView != wasInReportView )
4718         {
4719             // we need to notify the main window about this change as it must
4720             // update its data structures
4721             m_mainWin->SetReportView(inReportView);
4722         }
4723
4724         // m_mainWin->DeleteEverything();  wxMSW doesn't do that
4725
4726         CreateOrDestroyHeaderWindowAsNeeded();
4727
4728         GetSizer()->Layout();
4729     }
4730 }
4731
4732 bool wxGenericListCtrl::GetColumn(int col, wxListItem &item) const
4733 {
4734     m_mainWin->GetColumn( col, item );
4735     return true;
4736 }
4737
4738 bool wxGenericListCtrl::SetColumn( int col, const wxListItem& item )
4739 {
4740     m_mainWin->SetColumn( col, item );
4741     return true;
4742 }
4743
4744 int wxGenericListCtrl::GetColumnWidth( int col ) const
4745 {
4746     return m_mainWin->GetColumnWidth( col );
4747 }
4748
4749 bool wxGenericListCtrl::SetColumnWidth( int col, int width )
4750 {
4751     m_mainWin->SetColumnWidth( col, width );
4752     return true;
4753 }
4754
4755 int wxGenericListCtrl::GetCountPerPage() const
4756 {
4757   return m_mainWin->GetCountPerPage();  // different from Windows ?
4758 }
4759
4760 bool wxGenericListCtrl::GetItem( wxListItem &info ) const
4761 {
4762     m_mainWin->GetItem( info );
4763     return true;
4764 }
4765
4766 bool wxGenericListCtrl::SetItem( wxListItem &info )
4767 {
4768     m_mainWin->SetItem( info );
4769     return true;
4770 }
4771
4772 long wxGenericListCtrl::SetItem( long index, int col, const wxString& label, int imageId )
4773 {
4774     wxListItem info;
4775     info.m_text = label;
4776     info.m_mask = wxLIST_MASK_TEXT;
4777     info.m_itemId = index;
4778     info.m_col = col;
4779     if ( imageId > -1 )
4780     {
4781         info.m_image = imageId;
4782         info.m_mask |= wxLIST_MASK_IMAGE;
4783     }
4784
4785     m_mainWin->SetItem(info);
4786     return true;
4787 }
4788
4789 int wxGenericListCtrl::GetItemState( long item, long stateMask ) const
4790 {
4791     return m_mainWin->GetItemState( item, stateMask );
4792 }
4793
4794 bool wxGenericListCtrl::SetItemState( long item, long state, long stateMask )
4795 {
4796     m_mainWin->SetItemState( item, state, stateMask );
4797     return true;
4798 }
4799
4800 bool
4801 wxGenericListCtrl::SetItemImage( long item, int image, int WXUNUSED(selImage) )
4802 {
4803     return SetItemColumnImage(item, 0, image);
4804 }
4805
4806 bool
4807 wxGenericListCtrl::SetItemColumnImage( long item, long column, int image )
4808 {
4809     wxListItem info;
4810     info.m_image = image;
4811     info.m_mask = wxLIST_MASK_IMAGE;
4812     info.m_itemId = item;
4813     info.m_col = column;
4814     m_mainWin->SetItem( info );
4815     return true;
4816 }
4817
4818 wxString wxGenericListCtrl::GetItemText( long item, int col ) const
4819 {
4820     return m_mainWin->GetItemText(item, col);
4821 }
4822
4823 void wxGenericListCtrl::SetItemText( long item, const wxString& str )
4824 {
4825     m_mainWin->SetItemText(item, str);
4826 }
4827
4828 wxUIntPtr wxGenericListCtrl::GetItemData( long item ) const
4829 {
4830     wxListItem info;
4831     info.m_mask = wxLIST_MASK_DATA;
4832     info.m_itemId = item;
4833     m_mainWin->GetItem( info );
4834     return info.m_data;
4835 }
4836
4837 bool wxGenericListCtrl::SetItemPtrData( long item, wxUIntPtr data )
4838 {
4839     wxListItem info;
4840     info.m_mask = wxLIST_MASK_DATA;
4841     info.m_itemId = item;
4842     info.m_data = data;
4843     m_mainWin->SetItem( info );
4844     return true;
4845 }
4846
4847 wxRect wxGenericListCtrl::GetViewRect() const
4848 {
4849     return m_mainWin->GetViewRect();
4850 }
4851
4852 bool wxGenericListCtrl::GetItemRect(long item, wxRect& rect, int code) const
4853 {
4854     return GetSubItemRect(item, wxLIST_GETSUBITEMRECT_WHOLEITEM, rect, code);
4855 }
4856
4857 bool wxGenericListCtrl::GetSubItemRect(long item,
4858                                        long subItem,
4859                                        wxRect& rect,
4860                                        int WXUNUSED(code)) const
4861 {
4862     if ( !m_mainWin->GetSubItemRect( item, subItem, rect ) )
4863         return false;
4864
4865     if ( m_mainWin->HasHeader() )
4866         rect.y += m_headerWin->GetSize().y + 1;
4867
4868     return true;
4869 }
4870
4871 bool wxGenericListCtrl::GetItemPosition( long item, wxPoint& pos ) const
4872 {
4873     m_mainWin->GetItemPosition( item, pos );
4874     return true;
4875 }
4876
4877 bool wxGenericListCtrl::SetItemPosition( long WXUNUSED(item), const wxPoint& WXUNUSED(pos) )
4878 {
4879     return false;
4880 }
4881
4882 int wxGenericListCtrl::GetItemCount() const
4883 {
4884     return m_mainWin->GetItemCount();
4885 }
4886
4887 int wxGenericListCtrl::GetColumnCount() const
4888 {
4889     return m_mainWin->GetColumnCount();
4890 }
4891
4892 void wxGenericListCtrl::SetItemSpacing( int spacing, bool isSmall )
4893 {
4894     m_mainWin->SetItemSpacing( spacing, isSmall );
4895 }
4896
4897 wxSize wxGenericListCtrl::GetItemSpacing() const
4898 {
4899     const int spacing = m_mainWin->GetItemSpacing(HasFlag(wxLC_SMALL_ICON));
4900
4901     return wxSize(spacing, spacing);
4902 }
4903
4904 #if WXWIN_COMPATIBILITY_2_6
4905 int wxGenericListCtrl::GetItemSpacing( bool isSmall ) const
4906 {
4907     return m_mainWin->GetItemSpacing( isSmall );
4908 }
4909 #endif // WXWIN_COMPATIBILITY_2_6
4910
4911 void wxGenericListCtrl::SetItemTextColour( long item, const wxColour &col )
4912 {
4913     wxListItem info;
4914     info.m_itemId = item;
4915     info.SetTextColour( col );
4916     m_mainWin->SetItem( info );
4917 }
4918
4919 wxColour wxGenericListCtrl::GetItemTextColour( long item ) const
4920 {
4921     wxListItem info;
4922     info.m_itemId = item;
4923     m_mainWin->GetItem( info );
4924     return info.GetTextColour();
4925 }
4926
4927 void wxGenericListCtrl::SetItemBackgroundColour( long item, const wxColour &col )
4928 {
4929     wxListItem info;
4930     info.m_itemId = item;
4931     info.SetBackgroundColour( col );
4932     m_mainWin->SetItem( info );
4933 }
4934
4935 wxColour wxGenericListCtrl::GetItemBackgroundColour( long item ) const
4936 {
4937     wxListItem info;
4938     info.m_itemId = item;
4939     m_mainWin->GetItem( info );
4940     return info.GetBackgroundColour();
4941 }
4942
4943 void wxGenericListCtrl::SetItemFont( long item, const wxFont &f )
4944 {
4945     wxListItem info;
4946     info.m_itemId = item;
4947     info.SetFont( f );
4948     m_mainWin->SetItem( info );
4949 }
4950
4951 wxFont wxGenericListCtrl::GetItemFont( long item ) const
4952 {
4953     wxListItem info;
4954     info.m_itemId = item;
4955     m_mainWin->GetItem( info );
4956     return info.GetFont();
4957 }
4958
4959 int wxGenericListCtrl::GetSelectedItemCount() const
4960 {
4961     return m_mainWin->GetSelectedItemCount();
4962 }
4963
4964 wxColour wxGenericListCtrl::GetTextColour() const
4965 {
4966     return GetForegroundColour();
4967 }
4968
4969 void wxGenericListCtrl::SetTextColour(const wxColour& col)
4970 {
4971     SetForegroundColour(col);
4972 }
4973
4974 long wxGenericListCtrl::GetTopItem() const
4975 {
4976     size_t top;
4977     m_mainWin->GetVisibleLinesRange(&top, NULL);
4978     return (long)top;
4979 }
4980
4981 long wxGenericListCtrl::GetNextItem( long item, int geom, int state ) const
4982 {
4983     return m_mainWin->GetNextItem( item, geom, state );
4984 }
4985
4986 wxImageList *wxGenericListCtrl::GetImageList(int which) const
4987 {
4988     if (which == wxIMAGE_LIST_NORMAL)
4989         return m_imageListNormal;
4990     else if (which == wxIMAGE_LIST_SMALL)
4991         return m_imageListSmall;
4992     else if (which == wxIMAGE_LIST_STATE)
4993         return m_imageListState;
4994
4995     return NULL;
4996 }
4997
4998 void wxGenericListCtrl::SetImageList( wxImageList *imageList, int which )
4999 {
5000     if ( which == wxIMAGE_LIST_NORMAL )
5001     {
5002         if (m_ownsImageListNormal)
5003             delete m_imageListNormal;
5004         m_imageListNormal = imageList;
5005         m_ownsImageListNormal = false;
5006     }
5007     else if ( which == wxIMAGE_LIST_SMALL )
5008     {
5009         if (m_ownsImageListSmall)
5010             delete m_imageListSmall;
5011         m_imageListSmall = imageList;
5012         m_ownsImageListSmall = false;
5013     }
5014     else if ( which == wxIMAGE_LIST_STATE )
5015     {
5016         if (m_ownsImageListState)
5017             delete m_imageListState;
5018         m_imageListState = imageList;
5019         m_ownsImageListState = false;
5020     }
5021
5022     m_mainWin->SetImageList( imageList, which );
5023 }
5024
5025 void wxGenericListCtrl::AssignImageList(wxImageList *imageList, int which)
5026 {
5027     SetImageList(imageList, which);
5028     if ( which == wxIMAGE_LIST_NORMAL )
5029         m_ownsImageListNormal = true;
5030     else if ( which == wxIMAGE_LIST_SMALL )
5031         m_ownsImageListSmall = true;
5032     else if ( which == wxIMAGE_LIST_STATE )
5033         m_ownsImageListState = true;
5034 }
5035
5036 bool wxGenericListCtrl::Arrange( int WXUNUSED(flag) )
5037 {
5038     return 0;
5039 }
5040
5041 bool wxGenericListCtrl::DeleteItem( long item )
5042 {
5043     m_mainWin->DeleteItem( item );
5044     return true;
5045 }
5046
5047 bool wxGenericListCtrl::DeleteAllItems()
5048 {
5049     m_mainWin->DeleteAllItems();
5050     return true;
5051 }
5052
5053 bool wxGenericListCtrl::DeleteAllColumns()
5054 {
5055     size_t count = m_mainWin->m_columns.GetCount();
5056     for ( size_t n = 0; n < count; n++ )
5057         DeleteColumn( 0 );
5058     return true;
5059 }
5060
5061 void wxGenericListCtrl::ClearAll()
5062 {
5063     m_mainWin->DeleteEverything();
5064 }
5065
5066 bool wxGenericListCtrl::DeleteColumn( int col )
5067 {
5068     m_mainWin->DeleteColumn( col );
5069
5070     // if we don't have the header any longer, we need to relayout the window
5071     // if ( !GetColumnCount() )
5072
5073
5074     // Ensure that the non-existent columns are really removed from display.
5075     Refresh();
5076
5077     return true;
5078 }
5079
5080 wxTextCtrl *wxGenericListCtrl::EditLabel(long item,
5081                                          wxClassInfo* textControlClass)
5082 {
5083     return m_mainWin->EditLabel( item, textControlClass );
5084 }
5085
5086 wxTextCtrl *wxGenericListCtrl::GetEditControl() const
5087 {
5088     return m_mainWin->GetEditControl();
5089 }
5090
5091 bool wxGenericListCtrl::EnsureVisible( long item )
5092 {
5093     m_mainWin->EnsureVisible( item );
5094     return true;
5095 }
5096
5097 long wxGenericListCtrl::FindItem( long start, const wxString& str, bool partial )
5098 {
5099     return m_mainWin->FindItem( start, str, partial );
5100 }
5101
5102 long wxGenericListCtrl::FindItem( long start, wxUIntPtr data )
5103 {
5104     return m_mainWin->FindItem( start, data );
5105 }
5106
5107 long wxGenericListCtrl::FindItem( long WXUNUSED(start), const wxPoint& pt,
5108                            int WXUNUSED(direction))
5109 {
5110     return m_mainWin->FindItem( pt );
5111 }
5112
5113 // TODO: sub item hit testing
5114 long wxGenericListCtrl::HitTest(const wxPoint& point, int& flags, long *) const
5115 {
5116     return m_mainWin->HitTest( (int)point.x, (int)point.y, flags );
5117 }
5118
5119 long wxGenericListCtrl::InsertItem( wxListItem& info )
5120 {
5121     m_mainWin->InsertItem( info );
5122     return info.m_itemId;
5123 }
5124
5125 long wxGenericListCtrl::InsertItem( long index, const wxString &label )
5126 {
5127     wxListItem info;
5128     info.m_text = label;
5129     info.m_mask = wxLIST_MASK_TEXT;
5130     info.m_itemId = index;
5131     return InsertItem( info );
5132 }
5133
5134 long wxGenericListCtrl::InsertItem( long index, int imageIndex )
5135 {
5136     wxListItem info;
5137     info.m_mask = wxLIST_MASK_IMAGE;
5138     info.m_image = imageIndex;
5139     info.m_itemId = index;
5140     return InsertItem( info );
5141 }
5142
5143 long wxGenericListCtrl::InsertItem( long index, const wxString &label, int imageIndex )
5144 {
5145     wxListItem info;
5146     info.m_text = label;
5147     info.m_image = imageIndex;
5148     info.m_mask = wxLIST_MASK_TEXT;
5149     if (imageIndex > -1)
5150         info.m_mask |= wxLIST_MASK_IMAGE;
5151     info.m_itemId = index;
5152     return InsertItem( info );
5153 }
5154
5155 long wxGenericListCtrl::DoInsertColumn( long col, const wxListItem &item )
5156 {
5157     wxCHECK_MSG( InReportView(), -1, wxT("can't add column in non report mode") );
5158
5159     long idx = m_mainWin->InsertColumn( col, item );
5160
5161     // NOTE: if wxLC_NO_HEADER was given, then we are in report view mode but
5162     //       still have m_headerWin==NULL
5163     if (m_headerWin)
5164         m_headerWin->Refresh();
5165
5166     return idx;
5167 }
5168
5169 bool wxGenericListCtrl::ScrollList( int dx, int dy )
5170 {
5171     return m_mainWin->ScrollList(dx, dy);
5172 }
5173
5174 // Sort items.
5175 // fn is a function which takes 3 long arguments: item1, item2, data.
5176 // item1 is the long data associated with a first item (NOT the index).
5177 // item2 is the long data associated with a second item (NOT the index).
5178 // data is the same value as passed to SortItems.
5179 // The return value is a negative number if the first item should precede the second
5180 // item, a positive number of the second item should precede the first,
5181 // or zero if the two items are equivalent.
5182 // data is arbitrary data to be passed to the sort function.
5183
5184 bool wxGenericListCtrl::SortItems( wxListCtrlCompare fn, wxIntPtr data )
5185 {
5186     m_mainWin->SortItems( fn, data );
5187     return true;
5188 }
5189
5190 // ----------------------------------------------------------------------------
5191 // event handlers
5192 // ----------------------------------------------------------------------------
5193
5194 void wxGenericListCtrl::OnSize(wxSizeEvent& WXUNUSED(event))
5195 {
5196     if (!m_mainWin) return;
5197
5198     // We need to override OnSize so that our scrolled
5199     // window a) does call Layout() to use sizers for
5200     // positioning the controls but b) does not query
5201     // the sizer for their size and use that for setting
5202     // the scrollable area as set that ourselves by
5203     // calling SetScrollbar() further down.
5204
5205     Layout();
5206
5207     m_mainWin->RecalculatePositions();
5208
5209     AdjustScrollbars();
5210 }
5211
5212 void wxGenericListCtrl::OnInternalIdle()
5213 {
5214     wxWindow::OnInternalIdle();
5215
5216     if (m_mainWin->m_dirty)
5217         m_mainWin->RecalculatePositions();
5218 }
5219
5220 // ----------------------------------------------------------------------------
5221 // font/colours
5222 // ----------------------------------------------------------------------------
5223
5224 bool wxGenericListCtrl::SetBackgroundColour( const wxColour &colour )
5225 {
5226     if (m_mainWin)
5227     {
5228         m_mainWin->SetBackgroundColour( colour );
5229         m_mainWin->m_dirty = true;
5230     }
5231
5232     return true;
5233 }
5234
5235 bool wxGenericListCtrl::SetForegroundColour( const wxColour &colour )
5236 {
5237     if ( !wxWindow::SetForegroundColour( colour ) )
5238         return false;
5239
5240     if (m_mainWin)
5241     {
5242         m_mainWin->SetForegroundColour( colour );
5243         m_mainWin->m_dirty = true;
5244     }
5245
5246     if (m_headerWin)
5247         m_headerWin->SetForegroundColour( colour );
5248
5249     return true;
5250 }
5251
5252 bool wxGenericListCtrl::SetFont( const wxFont &font )
5253 {
5254     if ( !wxWindow::SetFont( font ) )
5255         return false;
5256
5257     if (m_mainWin)
5258     {
5259         m_mainWin->SetFont( font );
5260         m_mainWin->m_dirty = true;
5261     }
5262
5263     if (m_headerWin)
5264     {
5265         m_headerWin->SetFont( font );
5266         // CalculateAndSetHeaderHeight();
5267     }
5268
5269     Refresh();
5270
5271     return true;
5272 }
5273
5274 // static
5275 wxVisualAttributes
5276 wxGenericListCtrl::GetClassDefaultAttributes(wxWindowVariant variant)
5277 {
5278 #if _USE_VISATTR
5279     // Use the same color scheme as wxListBox
5280     return wxListBox::GetClassDefaultAttributes(variant);
5281 #else
5282     wxUnusedVar(variant);
5283     wxVisualAttributes attr;
5284     attr.colFg = wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOXTEXT);
5285     attr.colBg = wxSystemSettings::GetColour(wxSYS_COLOUR_LISTBOX);
5286     attr.font  = wxSystemSettings::GetFont(wxSYS_DEFAULT_GUI_FONT);
5287     return attr;
5288 #endif
5289 }
5290
5291 // ----------------------------------------------------------------------------
5292 // methods forwarded to m_mainWin
5293 // ----------------------------------------------------------------------------
5294
5295 #if wxUSE_DRAG_AND_DROP
5296
5297 void wxGenericListCtrl::SetDropTarget( wxDropTarget *dropTarget )
5298 {
5299     m_mainWin->SetDropTarget( dropTarget );
5300 }
5301
5302 wxDropTarget *wxGenericListCtrl::GetDropTarget() const
5303 {
5304     return m_mainWin->GetDropTarget();
5305 }
5306
5307 #endif
5308
5309 bool wxGenericListCtrl::SetCursor( const wxCursor &cursor )
5310 {
5311     return m_mainWin ? m_mainWin->wxWindow::SetCursor(cursor) : false;
5312 }
5313
5314 wxColour wxGenericListCtrl::GetBackgroundColour() const
5315 {
5316     return m_mainWin ? m_mainWin->GetBackgroundColour() : wxColour();
5317 }
5318
5319 wxColour wxGenericListCtrl::GetForegroundColour() const
5320 {
5321     return m_mainWin ? m_mainWin->GetForegroundColour() : wxColour();
5322 }
5323
5324 bool wxGenericListCtrl::DoPopupMenu( wxMenu *menu, int x, int y )
5325 {
5326 #if wxUSE_MENUS
5327     return m_mainWin->PopupMenu( menu, x, y );
5328 #else
5329     return false;
5330 #endif
5331 }
5332
5333 wxSize wxGenericListCtrl::DoGetBestClientSize() const
5334 {
5335     // The base class version can compute the best size in report view only.
5336     wxSize sizeBest = wxListCtrlBase::DoGetBestClientSize();
5337
5338     if ( !InReportView() )
5339     {
5340         // Ensure that our minimal width is at least big enough to show all our
5341         // items. This is important for wxListbook to size itself correctly.
5342
5343         // Remember the offset of the first item: this corresponds to the
5344         // margins around the item so we will add it to the minimal size below
5345         // to ensure that we have equal margins on all sides.
5346         wxPoint ofs;
5347
5348         // We can iterate over all items as there shouldn't be too many of them
5349         // in non-report view. If it ever becomes a problem, we could examine
5350         // just the first few items probably, the determination of the best
5351         // size is less important if we will need scrollbars anyhow.
5352         for ( int n = 0; n < GetItemCount(); n++ )
5353         {
5354             const wxRect itemRect = m_mainWin->GetLineRect(n);
5355             if ( !n )
5356             {
5357                 // Remember the position of the first item as all the rest are
5358                 // offset by at least this number of pixels too.
5359                 ofs = itemRect.GetPosition();
5360             }
5361
5362             sizeBest.IncTo(itemRect.GetSize());
5363         }
5364
5365         sizeBest.IncBy(2*ofs);
5366
5367
5368         // If we have the scrollbars we need to account for them too. And to
5369         // make sure the scrollbars status is up to date we need to call this
5370         // function to set them.
5371         m_mainWin->RecalculatePositions(true /* no refresh */);
5372
5373         // Unfortunately we can't use wxWindow::HasScrollbar() here as we need
5374         // to use m_mainWin client/virtual size for determination of whether we
5375         // use scrollbars and not the size of this window itself. Maybe that
5376         // function should be extended to work correctly in the case when our
5377         // scrollbars manage a different window from this one but currently it
5378         // doesn't work.
5379         const wxSize sizeClient = m_mainWin->GetClientSize();
5380         const wxSize sizeVirt = m_mainWin->GetVirtualSize();
5381
5382         if ( sizeVirt.x > sizeClient.x /* HasScrollbar(wxHORIZONTAL) */ )
5383             sizeBest.y += wxSystemSettings::GetMetric(wxSYS_HSCROLL_Y);
5384
5385         if ( sizeVirt.y > sizeClient.y /* HasScrollbar(wxVERTICAL) */ )
5386             sizeBest.x += wxSystemSettings::GetMetric(wxSYS_VSCROLL_X);
5387     }
5388
5389     return sizeBest;
5390 }
5391
5392 // ----------------------------------------------------------------------------
5393 // virtual list control support
5394 // ----------------------------------------------------------------------------
5395
5396 wxString wxGenericListCtrl::OnGetItemText(long WXUNUSED(item), long WXUNUSED(col)) const
5397 {
5398     // this is a pure virtual function, in fact - which is not really pure
5399     // because the controls which are not virtual don't need to implement it
5400     wxFAIL_MSG( wxT("wxGenericListCtrl::OnGetItemText not supposed to be called") );
5401
5402     return wxEmptyString;
5403 }
5404
5405 int wxGenericListCtrl::OnGetItemImage(long WXUNUSED(item)) const
5406 {
5407     wxCHECK_MSG(!GetImageList(wxIMAGE_LIST_SMALL),
5408                 -1,
5409                 wxT("List control has an image list, OnGetItemImage or OnGetItemColumnImage should be overridden."));
5410     return -1;
5411 }
5412
5413 int wxGenericListCtrl::OnGetItemColumnImage(long item, long column) const
5414 {
5415     if (!column)
5416         return OnGetItemImage(item);
5417
5418    return -1;
5419 }
5420
5421 void wxGenericListCtrl::SetItemCount(long count)
5422 {
5423     wxASSERT_MSG( IsVirtual(), wxT("this is for virtual controls only") );
5424
5425     m_mainWin->SetItemCount(count);
5426 }
5427
5428 void wxGenericListCtrl::RefreshItem(long item)
5429 {
5430     m_mainWin->RefreshLine(item);
5431 }
5432
5433 void wxGenericListCtrl::RefreshItems(long itemFrom, long itemTo)
5434 {
5435     m_mainWin->RefreshLines(itemFrom, itemTo);
5436 }
5437
5438 void wxGenericListCtrl::EnableBellOnNoMatch( bool on )
5439 {
5440     m_mainWin->EnableBellOnNoMatch(on);
5441 }
5442
5443 // Generic wxListCtrl is more or less a container for two other
5444 // windows which drawings are done upon. These are namely
5445 // 'm_headerWin' and 'm_mainWin'.
5446 // Here we override 'virtual wxWindow::Refresh()' to mimic the
5447 // behaviour wxListCtrl has under wxMSW.
5448 //
5449 void wxGenericListCtrl::Refresh(bool eraseBackground, const wxRect *rect)
5450 {
5451     if (!rect)
5452     {
5453         // The easy case, no rectangle specified.
5454         if (m_headerWin)
5455             m_headerWin->Refresh(eraseBackground);
5456
5457         if (m_mainWin)
5458             m_mainWin->Refresh(eraseBackground);
5459     }
5460     else
5461     {
5462         // Refresh the header window
5463         if (m_headerWin)
5464         {
5465             wxRect rectHeader = m_headerWin->GetRect();
5466             rectHeader.Intersect(*rect);
5467             if (rectHeader.GetWidth() && rectHeader.GetHeight())
5468             {
5469                 int x, y;
5470                 m_headerWin->GetPosition(&x, &y);
5471                 rectHeader.Offset(-x, -y);
5472                 m_headerWin->Refresh(eraseBackground, &rectHeader);
5473             }
5474         }
5475
5476         // Refresh the main window
5477         if (m_mainWin)
5478         {
5479             wxRect rectMain = m_mainWin->GetRect();
5480             rectMain.Intersect(*rect);
5481             if (rectMain.GetWidth() && rectMain.GetHeight())
5482             {
5483                 int x, y;
5484                 m_mainWin->GetPosition(&x, &y);
5485                 rectMain.Offset(-x, -y);
5486                 m_mainWin->Refresh(eraseBackground, &rectMain);
5487             }
5488         }
5489     }
5490 }
5491
5492 void wxGenericListCtrl::Update()
5493 {
5494     if ( m_mainWin )
5495     {
5496         if ( m_mainWin->m_dirty )
5497             m_mainWin->RecalculatePositions();
5498
5499         m_mainWin->Update();
5500     }
5501
5502     if ( m_headerWin )
5503         m_headerWin->Update();
5504 }
5505
5506 #endif // wxUSE_LISTCTRL