caf4df3c886d602445f9bd01cceffdc31df8a5e5
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / ListView.cs
1 // Permission is hereby granted, free of charge, to any person obtaining
2 // a copy of this software and associated documentation files (the
3 // "Software"), to deal in the Software without restriction, including
4 // without limitation the rights to use, copy, modify, merge, publish,
5 // distribute, sublicense, and/or sell copies of the Software, and to
6 // permit persons to whom the Software is furnished to do so, subject to
7 // the following conditions:
8 // 
9 // The above copyright notice and this permission notice shall be
10 // included in all copies or substantial portions of the Software.
11 // 
12 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
13 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
15 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
16 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
17 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
18 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
19 //
20 // Copyright (c) 2004-2005 Novell, Inc. (http://www.novell.com)
21 //
22 // Authors:
23 //      Ravindra Kumar (rkumar@novell.com)
24 //      Jordi Mas i Hernandez, jordi@ximian.com
25 //      Mike Kestner (mkestner@novell.com)
26 //      Daniel Nauck (dna(at)mono-project(dot)de)
27 //
28 // TODO:
29 //   - Feedback for item activation, change in cursor types as mouse moves.
30 //   - LabelEdit
31 //   - Drag and drop
32
33
34 // NOT COMPLETE
35
36
37 using System.Collections;
38 using System.ComponentModel;
39 using System.ComponentModel.Design;
40 using System.Drawing;
41 using System.Runtime.InteropServices;
42 using System.Globalization;
43 #if NET_2_0
44 using System.Collections.Generic;
45 #endif
46
47 namespace System.Windows.Forms
48 {
49         [DefaultEvent ("SelectedIndexChanged")]
50         [DefaultProperty ("Items")]
51         [Designer ("System.Windows.Forms.Design.ListViewDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
52         public class ListView : Control
53         {
54                 private ItemActivation activation = ItemActivation.Standard;
55                 private ListViewAlignment alignment = ListViewAlignment.Top;
56                 private bool allow_column_reorder = false;
57                 private bool auto_arrange = true;
58                 private bool check_boxes = false;
59                 private readonly CheckedIndexCollection checked_indices;
60                 private readonly CheckedListViewItemCollection checked_items;
61                 private readonly ColumnHeaderCollection columns;
62                 internal ListViewItem focused_item;
63                 private bool full_row_select = false;
64                 private bool grid_lines = false;
65                 private ColumnHeaderStyle header_style = ColumnHeaderStyle.Clickable;
66                 private bool hide_selection = true;
67                 private bool hover_selection = false;
68                 private IComparer item_sorter;
69                 private readonly ListViewItemCollection items;
70 #if NET_2_0
71                 private readonly ListViewGroupCollection groups;
72                 private bool show_groups = true;
73 #endif
74                 private bool label_edit = false;
75                 private bool label_wrap = true;
76                 private bool multiselect = true;
77                 private bool scrollable = true;
78                 private readonly SelectedIndexCollection selected_indices;
79                 private readonly SelectedListViewItemCollection selected_items;
80                 private SortOrder sort_order = SortOrder.None;
81                 private ImageList state_image_list;
82                 private bool updating = false;
83                 private View view = View.LargeIcon;
84                 private int layout_wd;    // We might draw more than our client area
85                 private int layout_ht;    // therefore we need to have these two.
86                 //private TextBox editor;   // Used for editing an item text
87                 HeaderControl header_control;
88                 internal ItemControl item_control;
89                 internal ScrollBar h_scroll; // used for scrolling horizontally
90                 internal ScrollBar v_scroll; // used for scrolling vertically
91                 internal int h_marker;          // Position markers for scrolling
92                 internal int v_marker;
93                 private int keysearch_tickcnt;
94                 private string keysearch_text;
95                 static private readonly int keysearch_keydelay = 1000;
96                 private int[] reordered_column_indices;
97
98                 // internal variables
99                 internal ImageList large_image_list;
100                 internal ImageList small_image_list;
101                 internal Size text_size = Size.Empty;
102
103                 #region Events
104                 static object AfterLabelEditEvent = new object ();
105                 static object BeforeLabelEditEvent = new object ();
106                 static object ColumnClickEvent = new object ();
107                 static object ItemActivateEvent = new object ();
108                 static object ItemCheckEvent = new object ();
109                 static object ItemDragEvent = new object ();
110                 static object SelectedIndexChangedEvent = new object ();
111
112                 public event LabelEditEventHandler AfterLabelEdit {
113                         add { Events.AddHandler (AfterLabelEditEvent, value); }
114                         remove { Events.RemoveHandler (AfterLabelEditEvent, value); }
115                 }
116
117                 [Browsable (false)]
118                 [EditorBrowsable (EditorBrowsableState.Never)]
119                 public new event EventHandler BackgroundImageChanged {
120                         add { base.BackgroundImageChanged += value; }
121                         remove { base.BackgroundImageChanged -= value; }
122                 }
123
124                 public event LabelEditEventHandler BeforeLabelEdit {
125                         add { Events.AddHandler (BeforeLabelEditEvent, value); }
126                         remove { Events.RemoveHandler (BeforeLabelEditEvent, value); }
127                 }
128
129                 public event ColumnClickEventHandler ColumnClick {
130                         add { Events.AddHandler (ColumnClickEvent, value); }
131                         remove { Events.RemoveHandler (ColumnClickEvent, value); }
132                 }
133
134                 public event EventHandler ItemActivate {
135                         add { Events.AddHandler (ItemActivateEvent, value); }
136                         remove { Events.RemoveHandler (ItemActivateEvent, value); }
137                 }
138
139                 public event ItemCheckEventHandler ItemCheck {
140                         add { Events.AddHandler (ItemCheckEvent, value); }
141                         remove { Events.RemoveHandler (ItemCheckEvent, value); }
142                 }
143
144                 public event ItemDragEventHandler ItemDrag {
145                         add { Events.AddHandler (ItemDragEvent, value); }
146                         remove { Events.RemoveHandler (ItemDragEvent, value); }
147                 }
148
149                 [Browsable (false)]
150                 [EditorBrowsable (EditorBrowsableState.Never)]
151                 public new event PaintEventHandler Paint {
152                         add { base.Paint += value; }
153                         remove { base.Paint -= value; }
154                 }
155
156                 public event EventHandler SelectedIndexChanged {
157                         add { Events.AddHandler (SelectedIndexChangedEvent, value); }
158                         remove { Events.RemoveHandler (SelectedIndexChangedEvent, value); }
159                 }
160
161                 [Browsable (false)]
162                 [EditorBrowsable (EditorBrowsableState.Never)]
163                 public new event EventHandler TextChanged {
164                         add { base.TextChanged += value; }
165                         remove { base.TextChanged -= value; }
166                 }
167
168                 #endregion // Events
169
170                 #region Public Constructors
171                 public ListView ()
172                 {
173                         background_color = ThemeEngine.Current.ColorWindow;
174                         items = new ListViewItemCollection (this);
175 #if NET_2_0
176                         groups = new ListViewGroupCollection (this);
177 #endif
178                         checked_indices = new CheckedIndexCollection (this);
179                         checked_items = new CheckedListViewItemCollection (this);
180                         columns = new ColumnHeaderCollection (this);
181                         foreground_color = SystemColors.WindowText;
182                         selected_indices = new SelectedIndexCollection (this);
183                         selected_items = new SelectedListViewItemCollection (this);
184
185                         border_style = BorderStyle.Fixed3D;
186
187                         header_control = new HeaderControl (this);
188                         header_control.Visible = false;
189                         Controls.AddImplicit (header_control);
190
191                         item_control = new ItemControl (this);
192                         Controls.AddImplicit (item_control);
193
194                         h_scroll = new ImplicitHScrollBar ();
195                         Controls.AddImplicit (this.h_scroll);
196
197                         v_scroll = new ImplicitVScrollBar ();
198                         Controls.AddImplicit (this.v_scroll);
199
200                         h_marker = v_marker = 0;
201                         keysearch_tickcnt = 0;
202
203                         // scroll bars are disabled initially
204                         h_scroll.Visible = false;
205                         h_scroll.ValueChanged += new EventHandler(HorizontalScroller);
206                         v_scroll.Visible = false;
207                         v_scroll.ValueChanged += new EventHandler(VerticalScroller);
208
209                         // event handlers
210                         base.KeyDown += new KeyEventHandler(ListView_KeyDown);
211                         SizeChanged += new EventHandler (ListView_SizeChanged);
212                         GotFocus += new EventHandler (FocusChanged);
213                         LostFocus += new EventHandler (FocusChanged);
214                         MouseWheel += new MouseEventHandler(ListView_MouseWheel);
215
216                         this.SetStyle (ControlStyles.UserPaint | ControlStyles.StandardClick
217 #if NET_2_0
218                                 | ControlStyles.UseTextForAccessibility
219 #endif
220                                 , false);
221                 }
222                 #endregion      // Public Constructors
223
224                 #region Private Internal Properties
225                 internal Size CheckBoxSize {
226                         get {
227                                 if (this.check_boxes) {
228                                         if (this.state_image_list != null)
229                                                 return this.state_image_list.ImageSize;
230                                         else
231                                                 return ThemeEngine.Current.ListViewCheckBoxSize;
232                                 }
233                                 return Size.Empty;
234                         }
235                 }
236
237                 #endregion      // Private Internal Properties
238
239                 #region  Protected Properties
240                 protected override CreateParams CreateParams {
241                         get { return base.CreateParams; }
242                 }
243
244                 protected override Size DefaultSize {
245                         get { return ThemeEngine.Current.ListViewDefaultSize; }
246                 }
247                 #endregion      // Protected Properties
248
249                 #region Public Instance Properties
250                 [DefaultValue (ItemActivation.Standard)]
251                 public ItemActivation Activation {
252                         get { return activation; }
253                         set { 
254                                 if (value != ItemActivation.Standard && value != ItemActivation.OneClick && 
255                                         value != ItemActivation.TwoClick) {
256                                         throw new InvalidEnumArgumentException (string.Format
257                                                 ("Enum argument value '{0}' is not valid for Activation", value));
258                                 }
259                                   
260                                 activation = value;
261                         }
262                 }
263
264                 [DefaultValue (ListViewAlignment.Top)]
265                 [Localizable (true)]
266                 public ListViewAlignment Alignment {
267                         get { return alignment; }
268                         set {
269                                 if (value != ListViewAlignment.Default && value != ListViewAlignment.Left && 
270                                         value != ListViewAlignment.SnapToGrid && value != ListViewAlignment.Top) {
271                                         throw new InvalidEnumArgumentException (string.Format 
272                                                 ("Enum argument value '{0}' is not valid for Alignment", value));
273                                 }
274                                 
275                                 if (this.alignment != value) {
276                                         alignment = value;
277                                         // alignment does not matter in Details/List views
278                                         if (this.view == View.LargeIcon ||
279                                             this.View == View.SmallIcon)
280                                                 this.Redraw (true);
281                                 }
282                         }
283                 }
284
285                 [DefaultValue (false)]
286                 public bool AllowColumnReorder {
287                         get { return allow_column_reorder; }
288                         set { allow_column_reorder = value; }
289                 }
290
291                 [DefaultValue (true)]
292                 public bool AutoArrange {
293                         get { return auto_arrange; }
294                         set {
295                                 if (auto_arrange != value) {
296                                         auto_arrange = value;
297                                         // autoarrange does not matter in Details/List views
298                                         if (this.view == View.LargeIcon || this.View == View.SmallIcon)
299                                                 this.Redraw (true);
300                                 }
301                         }
302                 }
303
304                 public override Color BackColor {
305                         get {
306                                 if (background_color.IsEmpty)
307                                         return ThemeEngine.Current.ColorWindow;
308                                 else
309                                         return background_color;
310                         }
311                         set { background_color = value; }
312                 }
313
314                 [Browsable (false)]
315                 [EditorBrowsable (EditorBrowsableState.Never)]
316                 public override Image BackgroundImage {
317                         get { return base.BackgroundImage; }
318                         set { base.BackgroundImage = value; }
319                 }
320
321                 [DefaultValue (BorderStyle.Fixed3D)]
322                 [DispId (-504)]
323                 public BorderStyle BorderStyle {
324                         get { return InternalBorderStyle; }
325                         set { InternalBorderStyle = value; }
326                 }
327
328                 [DefaultValue (false)]
329                 public bool CheckBoxes {
330                         get { return check_boxes; }
331                         set {
332                                 if (check_boxes != value) {
333 #if NET_2_0
334                                         if (value && View == View.Tile)
335                                                 throw new NotSupportedException ("CheckBoxes are not"
336                                                         + " supported in Tile view. Choose a different"
337                                                         + " view or set CheckBoxes to false.");
338 #endif
339
340                                         check_boxes = value;
341                                         this.Redraw (true);
342                                 }
343                         }
344                 }
345
346                 [Browsable (false)]
347                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
348                 public CheckedIndexCollection CheckedIndices {
349                         get { return checked_indices; }
350                 }
351
352                 [Browsable (false)]
353                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
354                 public CheckedListViewItemCollection CheckedItems {
355                         get { return checked_items; }
356                 }
357
358                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
359                 [Localizable (true)]
360                 [MergableProperty (false)]
361                 public ColumnHeaderCollection Columns {
362                         get { return columns; }
363                 }
364
365                 [Browsable (false)]
366                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
367                 public ListViewItem FocusedItem {
368                         get {
369                                 return focused_item;
370                         }
371                 }
372
373                 public override Color ForeColor {
374                         get {
375                                 if (foreground_color.IsEmpty)
376                                         return ThemeEngine.Current.ColorWindowText;
377                                 else
378                                         return foreground_color;
379                         }
380                         set { foreground_color = value; }
381                 }
382
383                 [DefaultValue (false)]
384                 public bool FullRowSelect {
385                         get { return full_row_select; }
386                         set { full_row_select = value; }
387                 }
388
389                 [DefaultValue (false)]
390                 public bool GridLines {
391                         get { return grid_lines; }
392                         set {
393                                 if (grid_lines != value) {
394                                         grid_lines = value;
395                                         this.Redraw (false);
396                                 }
397                         }
398                 }
399
400                 [DefaultValue (ColumnHeaderStyle.Clickable)]
401                 public ColumnHeaderStyle HeaderStyle {
402                         get { return header_style; }
403                         set {
404                                 if (header_style == value)
405                                         return;
406
407                                 switch (value) {
408                                 case ColumnHeaderStyle.Clickable:
409                                 case ColumnHeaderStyle.Nonclickable:
410                                 case ColumnHeaderStyle.None:
411                                         break;
412                                 default:
413                                         throw new InvalidEnumArgumentException (string.Format 
414                                                 ("Enum argument value '{0}' is not valid for ColumnHeaderStyle", value));
415                                 }
416                                 
417                                 header_style = value;
418                                 if (view == View.Details)
419                                         Redraw (true);
420                         }
421                 }
422
423                 [DefaultValue (true)]
424                 public bool HideSelection {
425                         get { return hide_selection; }
426                         set {
427                                 if (hide_selection != value) {
428                                         hide_selection = value;
429                                         this.Redraw (false);
430                                 }
431                         }
432                 }
433
434                 [DefaultValue (false)]
435                 public bool HoverSelection {
436                         get { return hover_selection; }
437                         set { hover_selection = value; }
438                 }
439
440                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
441                 [Localizable (true)]
442                 [MergableProperty (false)]              
443                 public ListViewItemCollection Items {
444                         get { return items; }
445                 }
446
447                 [DefaultValue (false)]
448                 public bool LabelEdit {
449                         get { return label_edit; }
450                         set { label_edit = value; }
451                 }
452
453                 [DefaultValue (true)]
454                 [Localizable (true)]
455                 public bool LabelWrap {
456                         get { return label_wrap; }
457                         set {
458                                 if (label_wrap != value) {
459                                         label_wrap = value;
460                                         this.Redraw (true);
461                                 }
462                         }
463                 }
464
465                 [DefaultValue (null)]
466                 public ImageList LargeImageList {
467                         get { return large_image_list; }
468                         set {
469                                 large_image_list = value;
470                                 this.Redraw (true);
471                         }
472                 }
473
474                 [Browsable (false)]
475                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
476                 public IComparer ListViewItemSorter {
477                         get {
478                                 if (View != View.SmallIcon && View != View.LargeIcon && item_sorter is ItemComparer)
479                                         return null;
480                                 return item_sorter;
481                         }
482                         set {
483                                 if (item_sorter != value) {
484                                         item_sorter = value;
485                                         Sort ();
486                                 }
487                         }
488                 }
489
490                 [DefaultValue (true)]
491                 public bool MultiSelect {
492                         get { return multiselect; }
493                         set { multiselect = value; }
494                 }
495
496                 [DefaultValue (true)]
497                 public bool Scrollable {
498                         get { return scrollable; }
499                         set {
500                                 if (scrollable != value) {
501                                         scrollable = value;
502                                         this.Redraw (true);
503                                 }
504                         }
505                 }
506
507                 [Browsable (false)]
508                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
509                 public SelectedIndexCollection SelectedIndices {
510                         get { return selected_indices; }
511                 }
512
513                 [Browsable (false)]
514                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
515                 public SelectedListViewItemCollection SelectedItems {
516                         get { return selected_items; }
517                 }
518
519 #if NET_2_0
520                 [DefaultValue(true)]
521                 public bool ShowGroups {
522                         get { return show_groups; }
523                         set 
524                         {
525                                 if (show_groups != value)
526                                 {
527                                         show_groups = value;
528                                         Redraw(true);
529                                 }
530                         }
531                 }
532
533                 [LocalizableAttribute(true)]
534                 public ListViewGroupCollection Groups {
535                         get { return groups;    }
536                 }
537 #endif
538
539                 [DefaultValue (null)]
540                 public ImageList SmallImageList {
541                         get { return small_image_list; }
542                         set {
543                                 small_image_list = value;
544                                 this.Redraw (true);
545                         }
546                 }
547
548                 [DefaultValue (SortOrder.None)]
549                 public SortOrder Sorting {
550                         get { return sort_order; }
551                         set { 
552                                 if (!Enum.IsDefined (typeof (SortOrder), value)) {
553                                         throw new InvalidEnumArgumentException ("value", (int) value,
554                                                 typeof (SortOrder));
555                                 }
556                                 
557                                 if (sort_order == value)
558                                         return;
559
560                                 sort_order = value;
561
562                                 if (value == SortOrder.None) {
563                                         if (item_sorter != null) {
564                                                 // ListViewItemSorter should never be reset for SmallIcon
565                                                 // and LargeIcon view
566                                                 if (View != View.SmallIcon && View != View.LargeIcon)
567 #if NET_2_0
568                                                         item_sorter = null;
569 #else
570                                                         // in .NET 1.1, only internal IComparer would be
571                                                         // set to null
572                                                         if (item_sorter is ItemComparer)
573                                                                 item_sorter = null;
574 #endif
575                                         }
576                                         this.Redraw (false);
577                                 } else {
578                                         if (item_sorter == null)
579                                                 item_sorter = new ItemComparer (value);
580                                         if (item_sorter is ItemComparer) {
581 #if NET_2_0
582                                                 item_sorter = new ItemComparer (value);
583 #else
584                                                 // in .NET 1.1, the sort order is not updated for
585                                                 // SmallIcon and LargeIcon views if no custom IComparer
586                                                 // is set
587                                                 if (View != View.SmallIcon && View != View.LargeIcon)
588                                                         item_sorter = new ItemComparer (value);
589 #endif
590                                         }
591                                         Sort ();
592                                 }
593                         }
594                 }
595
596                 [DefaultValue (null)]
597                 public ImageList StateImageList {
598                         get { return state_image_list; }
599                         set {
600                                 state_image_list = value;
601                                 this.Redraw (true);
602                         }
603                 }
604
605                 [Bindable (false)]
606                 [Browsable (false)]
607                 [EditorBrowsable (EditorBrowsableState.Never)]
608                 public override string Text {
609                         get { return base.Text; } 
610                         set {
611                                 if (value == base.Text)
612                                         return;
613
614                                 base.Text = value;
615                                 this.Redraw (true);
616                         }
617                 }
618
619                 [Browsable (false)]
620                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
621                 public ListViewItem TopItem {
622                         get {
623                                 // there is no item
624                                 if (this.items.Count == 0)
625                                         return null;
626                                 // if contents are not scrolled
627                                 // it is the first item
628                                 else if (h_marker == 0 && v_marker == 0)
629                                         return this.items [0];
630                                 // do a hit test for the scrolled position
631                                 else {
632                                         foreach (ListViewItem item in this.items) {
633                                                 if (item.Bounds.X >= 0 && item.Bounds.Y >= 0)
634                                                         return item;
635                                         }
636                                         return null;
637                                 }
638                         }
639                 }
640
641 #if NET_2_0
642                 [MonoTODO("Implement")]
643                 public bool UseCompatibleStateImageBehavior {
644                         get {
645                                 return false;
646                         }
647
648                         set {
649                         }
650                 }
651 #endif
652
653                 [DefaultValue (View.LargeIcon)]
654                 public View View {
655                         get { return view; }
656                         set { 
657                                 if (!Enum.IsDefined (typeof (View), value))
658                                         throw new InvalidEnumArgumentException ("value", (int) value,
659                                                 typeof (View));
660
661                                 if (view != value) {
662 #if NET_2_0
663                                         if (CheckBoxes && value == View.Tile)
664                                                 throw new NotSupportedException ("CheckBoxes are not"
665                                                         + " supported in Tile view. Choose a different"
666                                                         + " view or set CheckBoxes to false.");
667 #endif
668
669                                         h_scroll.Value = v_scroll.Value = 0;
670                                         view = value; 
671                                         Redraw (true);
672                                 }
673                         }
674                 }
675                 #endregion      // Public Instance Properties
676
677                 #region Internal Methods Properties
678                 
679                 internal int FirstVisibleIndex {
680                         get {
681                                 // there is no item
682                                 if (this.items.Count == 0)
683                                         return 0;
684                                                                         
685                                 if (h_marker == 0 && v_marker == 0)
686                                         return 0;                                       
687                                 
688                                 foreach (ListViewItem item in this.items) {
689                                         if (item.Bounds.Right >= 0 && item.Bounds.Bottom >= 0)
690                                                 return item.Index;
691                                 }
692                                 return 0;
693
694                         }
695                 }
696
697                 
698                 internal int LastVisibleIndex {                 
699                         get {                                                   
700                                 for (int i = FirstVisibleIndex; i < Items.Count; i++) {
701                                         if (View == View.List || Alignment == ListViewAlignment.Left) {
702                                                 if (Items[i].Bounds.X > ClientRectangle.Right)
703                                                         return i - 1;                                   
704                                         } else {
705                                                 if (Items[i].Bounds.Y > ClientRectangle.Bottom)
706                                                         return i - 1;                                   
707                                         }
708                                 }
709                                 
710                                 return Items.Count - 1;
711                         }
712                 }
713                 
714                 internal void OnSelectedIndexChanged ()
715                 {
716                         if (IsHandleCreated)
717                                 OnSelectedIndexChanged (EventArgs.Empty);
718                 }
719
720                 internal int TotalWidth {
721                         get { return Math.Max (this.Width, this.layout_wd); }
722                 }
723
724                 internal int TotalHeight {
725                         get { return Math.Max (this.Height, this.layout_ht); }
726                 }
727
728                 internal void Redraw (bool recalculate)
729                 {
730                         // Avoid calculations when control is being updated
731                         if (this.updating)
732                                 return;
733
734                         if (recalculate)
735                                 CalculateListView (this.alignment);
736
737                         Refresh ();
738                 }
739
740                 const int text_padding = 5;
741
742                 internal Size GetChildColumnSize (int index)
743                 {
744                         Size ret_size = Size.Empty;
745                         ColumnHeader col = this.columns [index];
746
747                         if (col.Width == -2) { // autosize = max(items, columnheader)
748                                 Size size = Size.Ceiling (this.DeviceContext.MeasureString
749                                                           (col.Text, this.Font));
750                                 size.Height += text_padding;
751                                 size.Width += text_padding;
752                                 ret_size = BiggestItem (index);
753                                 if (size.Width > ret_size.Width)
754                                         ret_size = size;
755                         }
756                         else { // -1 and all the values < -2 are put under one category
757                                 ret_size = BiggestItem (index);
758                                 // fall back to empty columns' width if no subitem is available for a column
759                                 if (ret_size.IsEmpty) {
760                                         ret_size.Width = ThemeEngine.Current.ListViewEmptyColumnWidth;
761                                         if (col.Text.Length > 0)
762                                                 ret_size.Height = Size.Ceiling (this.DeviceContext.MeasureString
763                                                                                 (col.Text, this.Font)).Height;
764                                         else
765                                                 ret_size.Height = this.Font.Height;
766                                 }
767                         }
768
769                         // adjust the size for icon and checkbox for 0th column
770                         if (index == 0) {
771                                 ret_size.Width += (this.CheckBoxSize.Width + 4);
772                                 if (this.small_image_list != null)
773                                         ret_size.Width += this.small_image_list.ImageSize.Width;
774                         }
775                         return ret_size;
776                 }
777
778                 // Returns the size of biggest item text in a column.
779                 private Size BiggestItem (int col)
780                 {
781                         Size temp = Size.Empty;
782                         Size ret_size = Size.Empty;
783
784                         // 0th column holds the item text, we check the size of
785                         // the various subitems falling in that column and get
786                         // the biggest one's size.
787                         foreach (ListViewItem item in items) {
788                                 if (col >= item.SubItems.Count)
789                                         continue;
790
791                                 temp = Size.Ceiling (this.DeviceContext.MeasureString
792                                                      (item.SubItems [col].Text, this.Font));
793                                 if (temp.Width > ret_size.Width)
794                                         ret_size = temp;
795                         }
796
797                         // adjustment for space
798                         if (!ret_size.IsEmpty)
799                                 ret_size.Width += 4;
800
801                         return ret_size;
802                 }
803
804                 const int max_wrap_padding = 38;
805
806                 // Sets the size of the biggest item text as per the view
807                 private void CalcTextSize ()
808                 {                       
809                         // clear the old value
810                         text_size = Size.Empty;
811
812                         if (items.Count == 0)
813                                 return;
814
815                         text_size = BiggestItem (0);
816
817                         if (view == View.LargeIcon && this.label_wrap) {
818                                 Size temp = Size.Empty;
819                                 if (this.check_boxes)
820                                         temp.Width += 2 * this.CheckBoxSize.Width;
821                                 int icon_w = LargeImageList == null ? 12 : LargeImageList.ImageSize.Width;
822                                 temp.Width += icon_w + max_wrap_padding;
823                                 // wrapping is done for two lines only
824                                 if (text_size.Width > temp.Width) {
825                                         text_size.Width = temp.Width;
826                                         text_size.Height *= 2;
827                                 }
828                         }
829                         else if (view == View.List) {
830                                 // in list view max text shown in determined by the
831                                 // control width, even if scolling is enabled.
832                                 int max_wd = this.Width - (this.CheckBoxSize.Width - 2);
833                                 if (this.small_image_list != null)
834                                         max_wd -= this.small_image_list.ImageSize.Width;
835
836                                 if (text_size.Width > max_wd)
837                                         text_size.Width = max_wd;
838                         }
839
840                         // we do the default settings, if we have got 0's
841                         if (text_size.Height <= 0)
842                                 text_size.Height = this.Font.Height;
843                         if (text_size.Width <= 0)
844                                 text_size.Width = this.Width;
845
846                         // little adjustment
847                         text_size.Width += 4;
848                         text_size.Height += 2;
849                 }
850
851                 private void Scroll (ScrollBar scrollbar, int delta)
852                 {
853                         if (delta == 0 || !scrollbar.Visible)
854                                 return;
855
856                         int max;
857                         if (scrollbar == h_scroll)
858                                 max = h_scroll.Maximum - item_control.Width;
859                         else
860                                 max = v_scroll.Maximum - item_control.Height;
861
862                         int val = scrollbar.Value + delta;
863                         if (val > max)
864                                 val = max;
865                         else if (val < scrollbar.Minimum)
866                                 val = scrollbar.Minimum;
867                         scrollbar.Value = val;
868                 }
869
870                 private void CalculateScrollBars ()
871                 {
872                         Rectangle client_area = ClientRectangle;
873                         
874                         if (!this.scrollable || this.items.Count <= 0) {
875                                 h_scroll.Visible = false;
876                                 v_scroll.Visible = false;
877                                 item_control.Location = new Point (0, header_control.Height);
878                                 item_control.Height = ClientRectangle.Width - header_control.Height;
879                                 item_control.Width = ClientRectangle.Width;
880                                 header_control.Width = ClientRectangle.Width;
881                                 return;
882                         }
883
884                         // Don't calculate if the view is not displayable
885                         if (client_area.Height < 0 || client_area.Width < 0)
886                                 return;
887
888                         // making a scroll bar visible might make
889                         // other scroll bar visible                     
890                         if (layout_wd > client_area.Right) {
891                                 h_scroll.Visible = true;
892                                 if ((layout_ht + h_scroll.Height) > client_area.Bottom)
893                                         v_scroll.Visible = true;                                        
894                                 else
895                                         v_scroll.Visible = false;
896                         } else if (layout_ht > client_area.Bottom) {                            
897                                 v_scroll.Visible = true;
898                                 if ((layout_wd + v_scroll.Width) > client_area.Right)
899                                         h_scroll.Visible = true;
900                                 else
901                                         h_scroll.Visible = false;
902                         } else {
903                                 h_scroll.Visible = false;
904                                 v_scroll.Visible = false;
905                         }                       
906
907                         item_control.Height = ClientRectangle.Height - header_control.Height;
908
909                         if (h_scroll.is_visible) {
910                                 h_scroll.Location = new Point (client_area.X, client_area.Bottom - h_scroll.Height);
911                                 h_scroll.Minimum = 0;
912
913                                 // if v_scroll is visible, adjust the maximum of the
914                                 // h_scroll to account for the width of v_scroll
915                                 if (v_scroll.Visible) {
916                                         h_scroll.Maximum = layout_wd + v_scroll.Width;
917                                         h_scroll.Width = client_area.Width - v_scroll.Width;
918                                 }
919                                 else {
920                                         h_scroll.Maximum = layout_wd;
921                                         h_scroll.Width = client_area.Width;
922                                 }
923    
924                                 h_scroll.LargeChange = client_area.Width;
925                                 h_scroll.SmallChange = Font.Height;
926                                 item_control.Height -= h_scroll.Height;
927                         }
928
929                         if (header_control.is_visible)
930                                 header_control.Width = ClientRectangle.Width;
931                         item_control.Width = ClientRectangle.Width;
932
933                         if (v_scroll.is_visible) {
934                                 v_scroll.Location = new Point (client_area.Right - v_scroll.Width, client_area.Y);
935                                 v_scroll.Minimum = 0;
936
937                                 // if h_scroll is visible, adjust the maximum of the
938                                 // v_scroll to account for the height of h_scroll
939                                 if (h_scroll.Visible) {
940                                         v_scroll.Maximum = layout_ht + h_scroll.Height;
941                                         v_scroll.Height = client_area.Height; // - h_scroll.Height already done 
942                                 } else {
943                                         v_scroll.Maximum = layout_ht;
944                                         v_scroll.Height = client_area.Height;
945                                 }
946
947                                 v_scroll.LargeChange = client_area.Height;
948                                 v_scroll.SmallChange = Font.Height;
949                                 if (header_control.Visible)
950                                         header_control.Width -= v_scroll.Width;
951                                 item_control.Width -= v_scroll.Width;
952                         }
953                 }
954                 
955                 ColumnHeader GetReorderedColumn (int index)
956                 {
957                         if (reordered_column_indices == null)
958                                 return Columns [index];
959                         else
960                                 return Columns [reordered_column_indices [index]];
961                 }
962
963                 void ReorderColumn (ColumnHeader col, int index)
964                 {
965 #if NET_2_0
966                         ColumnReorderedEventHandler eh = (ColumnReorderedEventHandler) (Events [ColumnReorderedEvent]);
967                         if (eh != null){
968                                 ColumnReorderedEventArgs args = new ColumnReorderedEventArgs (col.Index, index, col);
969
970                                 eh (this, args);
971                                 if (args.Cancel){
972                                         header_control.Invalidate ();
973                                         item_control.Invalidate ();
974                                         return;
975                                 }
976                         }
977 #endif
978                         if (reordered_column_indices == null) {
979                                 reordered_column_indices = new int [Columns.Count];
980                                 for (int i = 0; i < Columns.Count; i++)
981                                         reordered_column_indices [i] = i;
982                         }
983
984                         if (reordered_column_indices [index] == col.Index)
985                                 return;
986
987                         int[] curr = reordered_column_indices;
988                         int[] result = new int [Columns.Count];
989                         int curr_idx = 0;
990                         for (int i = 0; i < Columns.Count; i++) {
991                                 if (curr_idx < Columns.Count && curr [curr_idx] == col.Index)
992                                         curr_idx++;
993
994                                 if (i == index)
995                                         result [i] = col.Index;
996                                 else
997                                         result [i] = curr [curr_idx++];
998                         }
999
1000                         reordered_column_indices = result;
1001                         LayoutDetails ();
1002                         header_control.Invalidate ();
1003                         item_control.Invalidate ();
1004                 }
1005
1006                 Size LargeIconItemSize {
1007                         get {
1008                                 int image_w = LargeImageList == null ? 12 : LargeImageList.ImageSize.Width;
1009                                 int image_h = LargeImageList == null ? 2 : LargeImageList.ImageSize.Height;
1010                                 int w = CheckBoxSize.Width + 2 + Math.Max (text_size.Width, image_w);
1011                                 int h = text_size.Height + 2 + Math.Max (CheckBoxSize.Height, image_h);
1012                                 return new Size (w, h);
1013                         }
1014                 }
1015
1016                 Size SmallIconItemSize {
1017                         get {
1018                                 int image_w = SmallImageList == null ? 0 : SmallImageList.ImageSize.Width;
1019                                 int image_h = SmallImageList == null ? 0 : SmallImageList.ImageSize.Height;
1020                                 int w = text_size.Width + 2 + CheckBoxSize.Width + image_w;
1021                                 int h = Math.Max (text_size.Height, Math.Max (CheckBoxSize.Height, image_h));
1022                                 return new Size (w, h);
1023                         }
1024                 }
1025
1026                 int rows;
1027                 int cols;
1028                 ListViewItem[,] item_matrix;
1029
1030                 void LayoutIcons (bool large_icons, bool left_aligned, int x_spacing, int y_spacing)
1031                 {
1032                         header_control.Visible = false;
1033                         header_control.Size = Size.Empty;
1034                         item_control.Visible = true;
1035                         item_control.Location = Point.Empty;
1036
1037                         if (items.Count == 0)
1038                                 return;
1039
1040                         Size sz = large_icons ? LargeIconItemSize : SmallIconItemSize;
1041
1042                         Rectangle area = ClientRectangle;
1043
1044                         if (left_aligned) {
1045                                 rows = (int) Math.Floor ((double)(area.Height - h_scroll.Height + y_spacing) / (double)(sz.Height + y_spacing));
1046                                 if (rows <= 0)
1047                                         rows = 1;
1048                                 cols = (int) Math.Ceiling ((double)items.Count / (double)rows);
1049                         } else {
1050                                 cols = (int) Math.Floor ((double)(area.Width - v_scroll.Width + x_spacing) / (double)(sz.Width + x_spacing));
1051                                 if (cols <= 0)
1052                                         cols = 1;
1053                                 rows = (int) Math.Ceiling ((double)items.Count / (double)cols);
1054                         }
1055
1056                         layout_ht = rows * (sz.Height + y_spacing) - y_spacing;
1057                         layout_wd = cols * (sz.Width + x_spacing) - x_spacing;
1058                         item_matrix = new ListViewItem [rows, cols];
1059                         int row = 0;
1060                         int col = 0;
1061                         foreach (ListViewItem item in items) {
1062                                 int x = col * (sz.Width + x_spacing);
1063                                 int y = row * (sz.Height + y_spacing);
1064                                 item.Location = new Point (x, y);
1065                                 item.Layout ();
1066                                 item.row = row;
1067                                 item.col = col;
1068                                 item_matrix [row, col] = item;
1069                                 if (left_aligned) {
1070                                         if (++row == rows) {
1071                                                 row = 0;
1072                                                 col++;
1073                                         }
1074                                 } else {
1075                                         if (++col == cols) {
1076                                                 col = 0;
1077                                                 row++;
1078                                         }
1079                                 }
1080                         }
1081
1082                         item_control.Size = new Size (layout_wd, layout_ht);
1083                 }
1084
1085                 void LayoutHeader ()
1086                 {
1087                         int x = 0;
1088                         for (int i = 0; i < Columns.Count; i++) {
1089                                 ColumnHeader col = GetReorderedColumn (i);
1090                                 col.X = x;
1091                                 col.Y = 0;
1092                                 col.CalcColumnHeader ();
1093                                 x += col.Wd;
1094                         }
1095
1096                         if (x < ClientRectangle.Width)
1097                                 x = ClientRectangle.Width;
1098
1099                         if (header_style == ColumnHeaderStyle.None) {
1100                                 header_control.Visible = false;
1101                                 header_control.Size = Size.Empty;
1102                         } else {
1103                                 header_control.Width = x;
1104                                 header_control.Height = columns [0].Ht;
1105                                 header_control.Visible = true;
1106                         }
1107                 }
1108
1109                 void LayoutDetails ()
1110                 {
1111                         if (columns.Count == 0) {
1112                                 header_control.Visible = false;
1113                                 item_control.Visible = false;
1114                                 return;
1115                         }
1116
1117                         LayoutHeader ();
1118
1119                         item_control.Visible = true;
1120                         item_control.Location = new Point (0, header_control.Height);
1121
1122                         int y = 0; 
1123                         if (items.Count > 0) {
1124                                 foreach (ListViewItem item in items) {
1125                                         item.Layout ();
1126                                         item.Location = new Point (0, y);
1127                                         y += item.Bounds.Height + 2;
1128                                 }
1129
1130                                 // some space for bottom gridline
1131                                 if (grid_lines)
1132                                         y += 2;
1133                         }
1134
1135                         layout_wd = Math.Max (header_control.Width, item_control.Width);
1136                         layout_ht = y + header_control.Height;
1137                 }
1138
1139                 private void CalculateListView (ListViewAlignment align)
1140                 {
1141                         CalcTextSize ();
1142
1143                         switch (view) {
1144                         case View.Details:
1145                                 LayoutDetails ();
1146                                 break;
1147
1148                         case View.SmallIcon:
1149                                 LayoutIcons (false, alignment == ListViewAlignment.Left, 4, 2);
1150                                 break;
1151
1152                         case View.LargeIcon:
1153                                 LayoutIcons (true, alignment == ListViewAlignment.Left,
1154                                              ThemeEngine.Current.ListViewHorizontalSpacing,
1155                                              ThemeEngine.Current.ListViewVerticalSpacing);
1156                                 break;
1157
1158                         case View.List:
1159                                 LayoutIcons (false, true, 4, 2);
1160                                 break;
1161                         }
1162
1163                         CalculateScrollBars ();
1164                 }
1165
1166                 private bool KeySearchString (KeyEventArgs ke)
1167                 {
1168                         int current_tickcnt = Environment.TickCount;
1169                         if (keysearch_tickcnt > 0 && current_tickcnt - keysearch_tickcnt > keysearch_keydelay) {
1170                                 keysearch_text = string.Empty;
1171                         }
1172                         
1173                         keysearch_text += (char) ke.KeyData;
1174                         keysearch_tickcnt = current_tickcnt;
1175
1176                         int start = FocusedItem == null ? 0 : FocusedItem.Index;
1177                         int i = start;
1178                         while (true) {
1179                                 if (CultureInfo.CurrentCulture.CompareInfo.IsPrefix (Items[i].Text, keysearch_text,
1180                                         CompareOptions.IgnoreCase)) {
1181                                         SetFocusedItem (Items [i]);
1182                                         items [i].Selected = true;
1183                                         EnsureVisible (i);
1184                                         break;
1185                                 }
1186                                 i = (i + 1  < Items.Count) ? i+1 : 0;
1187
1188                                 if (i == start)
1189                                         break;
1190                         }
1191                         return true;
1192                 }
1193
1194                 int GetAdjustedIndex (Keys key)
1195                 {
1196                         int result = -1;
1197
1198                         if (View == View.Details) {
1199                                 if (key == Keys.Up)
1200                                         result = FocusedItem.Index - 1;
1201                                 else if (key == Keys.Down) {
1202                                         result = FocusedItem.Index + 1;
1203                                         if (result == items.Count)
1204                                                 result = -1;
1205                                 }
1206                                 return result;
1207                         }
1208
1209                         int row = FocusedItem.row;
1210                         int col = FocusedItem.col;
1211
1212                         switch (key) {
1213                         case Keys.Left:
1214                                 if (col == 0)
1215                                         return -1;
1216                                 return item_matrix [row, col - 1].Index;
1217
1218                         case Keys.Right:
1219                                 if (col == (cols - 1))
1220                                         return -1;
1221                                 while (item_matrix [row, col + 1] == null) {
1222                                         row--;  
1223                                         if (row < 0)
1224                                                 return -1;
1225                                 }
1226                                 return item_matrix [row, col + 1].Index;
1227
1228                         case Keys.Up:
1229                                 if (row == 0)
1230                                         return -1;
1231                                 return item_matrix [row - 1, col].Index;
1232
1233                         case Keys.Down:
1234                                 if (row == (rows - 1) || row == Items.Count - 1)
1235                                         return -1;
1236                                 while (item_matrix [row + 1, col] == null) {
1237                                         col--;  
1238                                         if (col < 0)
1239                                                 return -1;
1240                                 }
1241                                 return item_matrix [row + 1, col].Index;
1242
1243                         default:
1244                                 return -1;
1245                         }
1246                 }
1247
1248                 ListViewItem selection_start;
1249
1250                 private bool SelectItems (ArrayList sel_items)
1251                 {
1252                         bool changed = false;
1253                         ArrayList curr_items = SelectedItems.List;
1254                         foreach (ListViewItem item in curr_items)
1255                                 if (!sel_items.Contains (item)) {
1256                                         item.Selected = false;
1257                                         changed = true;
1258                                 }
1259                         foreach (ListViewItem item in sel_items)
1260                                 if (!item.Selected) {
1261                                         item.Selected = true;
1262                                         changed = true;
1263                                 }
1264                         return changed;
1265                 }
1266
1267                 private void UpdateMultiSelection (int index)
1268                 {
1269                         bool shift_pressed = (XplatUI.State.ModifierKeys & Keys.Shift) != 0;
1270                         bool ctrl_pressed = (XplatUI.State.ModifierKeys & Keys.Control) != 0;
1271                         ListViewItem item = items [index];
1272
1273                         if (shift_pressed && selection_start != null) {
1274                                 ArrayList list = new ArrayList ();
1275                                 int start = Math.Min (selection_start.Index, index);
1276                                 int end = Math.Max (selection_start.Index, index);
1277                                 if (View == View.Details) {
1278                                         for (int i = start; i <= end; i++)
1279                                                 list.Add (items [i]);
1280                                 } else {
1281                                         int left = Math.Min (items [start].col, items [end].col);
1282                                         int right = Math.Max (items [start].col, items [end].col);
1283                                         int top = Math.Min (items [start].row, items [end].row);
1284                                         int bottom = Math.Max (items [start].row, items [end].row);
1285                                         foreach (ListViewItem curr in items)
1286                                                 if (curr.row >= top && curr.row <= bottom && 
1287                                                     curr.col >= left && curr.col <= right)
1288                                                         list.Add (curr);
1289                                 }
1290                                 if (SelectItems (list))
1291                                         OnSelectedIndexChanged (EventArgs.Empty);
1292                         } else  if (ctrl_pressed) {
1293                                 item.Selected = !item.Selected;
1294                                 selection_start = item;
1295                                 OnSelectedIndexChanged (EventArgs.Empty);
1296                         } else {
1297                                 SelectedItems.Clear ();
1298                                 item.Selected = true;
1299                                 selection_start = item;
1300                                 OnSelectedIndexChanged (EventArgs.Empty);
1301                         }
1302                 }
1303
1304                 internal override bool InternalPreProcessMessage (ref Message msg)
1305                 {
1306                         if (msg.Msg == (int)Msg.WM_KEYDOWN) {
1307                                 Keys key_data = (Keys)msg.WParam.ToInt32();
1308                                 if (HandleNavKeys (key_data))
1309                                         return true;
1310                         } 
1311                         return base.InternalPreProcessMessage (ref msg);
1312                 }
1313
1314                 bool HandleNavKeys (Keys key_data)
1315                 {
1316                         if (Items.Count == 0 || !item_control.Visible)
1317                                 return false;
1318
1319                         if (FocusedItem == null)
1320                                 SetFocusedItem (Items [0]);
1321
1322                         switch (key_data) {
1323                         case Keys.End:
1324                                 SelectIndex (Items.Count - 1);
1325                                 break;
1326
1327                         case Keys.Home:                 
1328                                 SelectIndex (0);
1329                                 break;
1330
1331                         case Keys.Left:
1332                         case Keys.Right:
1333                         case Keys.Up:                           
1334                         case Keys.Down:
1335                                 SelectIndex (GetAdjustedIndex (key_data));
1336                                 break;
1337
1338                         default:
1339                                 return false;
1340                         }
1341
1342                         return true;
1343                 }
1344
1345                 void SelectIndex (int index)
1346                 {
1347                         if (index == -1)
1348                                 return;
1349
1350                         if (MultiSelect)
1351                                 UpdateMultiSelection (index);
1352                         else if (!items [index].Selected) {
1353                                 items [index].Selected = true;
1354                                 OnSelectedIndexChanged (EventArgs.Empty);
1355                         }
1356
1357                         SetFocusedItem (items [index]);                         
1358                         EnsureVisible (index);
1359                 }
1360
1361                 private void ListView_KeyDown (object sender, KeyEventArgs ke)
1362                 {                       
1363                         if (ke.Handled || Items.Count == 0 || !item_control.Visible)
1364                                 return;
1365
1366                         ke.Handled = KeySearchString (ke);
1367                 }
1368
1369                 internal class ItemControl : Control {
1370
1371                         ListView owner;
1372                         ListViewItem clicked_item;
1373                         ListViewItem last_clicked_item;
1374                         bool hover_processed = false;
1375                         bool checking = false;
1376                         
1377                         ListViewLabelEditTextBox edit_text_box;
1378                         internal ListViewItem edit_item;
1379                         LabelEditEventArgs edit_args;
1380
1381                         public ItemControl (ListView owner)
1382                         {
1383                                 this.owner = owner;
1384                                 DoubleClick += new EventHandler(ItemsDoubleClick);
1385                                 MouseDown += new MouseEventHandler(ItemsMouseDown);
1386                                 MouseMove += new MouseEventHandler(ItemsMouseMove);
1387                                 MouseHover += new EventHandler(ItemsMouseHover);
1388                                 MouseUp += new MouseEventHandler(ItemsMouseUp);
1389                         }
1390
1391                         void ItemsDoubleClick (object sender, EventArgs e)
1392                         {
1393                                 if (owner.activation == ItemActivation.Standard)
1394                                         owner.OnItemActivate (EventArgs.Empty);
1395                         }
1396
1397                         enum BoxSelect {
1398                                 None,
1399                                 Normal,
1400                                 Shift,
1401                                 Control
1402                         }
1403
1404                         BoxSelect box_select_mode = BoxSelect.None;
1405                         ArrayList prev_selection;
1406                         Point box_select_start;
1407
1408                         Rectangle box_select_rect;
1409                         internal Rectangle BoxSelectRectangle {
1410                                 get { return box_select_rect; }
1411                                 set {
1412                                         if (box_select_rect == value)
1413                                                 return;
1414
1415                                         InvalidateBoxSelectRect ();
1416                                         box_select_rect = value;
1417                                         InvalidateBoxSelectRect ();
1418                                 }
1419                         }
1420
1421                         void InvalidateBoxSelectRect ()
1422                         {
1423                                 if (BoxSelectRectangle.Size.IsEmpty)
1424                                         return;
1425
1426                                 Rectangle edge = BoxSelectRectangle;
1427                                 edge.X -= 1;
1428                                 edge.Y -= 1;
1429                                 edge.Width += 2;
1430                                 edge.Height = 2;
1431                                 Invalidate (edge);
1432                                 edge.Y = BoxSelectRectangle.Bottom - 1;
1433                                 Invalidate (edge);
1434                                 edge.Y = BoxSelectRectangle.Y - 1;
1435                                 edge.Width = 2;
1436                                 edge.Height = BoxSelectRectangle.Height + 2;
1437                                 Invalidate (edge);
1438                                 edge.X = BoxSelectRectangle.Right - 1;
1439                                 Invalidate (edge);
1440                         }
1441
1442                         private Rectangle CalculateBoxSelectRectangle (Point pt)
1443                         {
1444                                 int left = Math.Min (box_select_start.X, pt.X);
1445                                 int right = Math.Max (box_select_start.X, pt.X);
1446                                 int top = Math.Min (box_select_start.Y, pt.Y);
1447                                 int bottom = Math.Max (box_select_start.Y, pt.Y);
1448                                 return Rectangle.FromLTRB (left, top, right, bottom);
1449                         }
1450
1451                         ArrayList BoxSelectedItems {
1452                                 get {
1453                                         ArrayList result = new ArrayList ();
1454                                         foreach (ListViewItem item in owner.Items) {
1455                                                 Rectangle r = item.Bounds;
1456                                                 r.X += r.Width / 4;
1457                                                 r.Y += r.Height / 4;
1458                                                 r.Width /= 2;
1459                                                 r.Height /= 2;
1460                                                 if (BoxSelectRectangle.IntersectsWith (r))
1461                                                         result.Add (item);
1462                                         }
1463                                         return result;
1464                                 }
1465                         }
1466
1467                         private bool PerformBoxSelection (Point pt)
1468                         {
1469                                 if (box_select_mode == BoxSelect.None)
1470                                         return false;
1471
1472                                 BoxSelectRectangle = CalculateBoxSelectRectangle (pt);
1473                                 
1474                                 ArrayList box_items = BoxSelectedItems;
1475
1476                                 ArrayList items;
1477
1478                                 switch (box_select_mode) {
1479
1480                                 case BoxSelect.Normal:
1481                                         items = box_items;
1482                                         break;
1483
1484                                 case BoxSelect.Control:
1485                                         items = new ArrayList ();
1486                                         foreach (ListViewItem item in prev_selection)
1487                                                 if (!box_items.Contains (item))
1488                                                         items.Add (item);
1489                                         foreach (ListViewItem item in box_items)
1490                                                 if (!prev_selection.Contains (item))
1491                                                         items.Add (item);
1492                                         break;
1493
1494                                 case BoxSelect.Shift:
1495                                         items = box_items;
1496                                         foreach (ListViewItem item in box_items)
1497                                                 prev_selection.Remove (item);
1498                                         foreach (ListViewItem item in prev_selection)
1499                                                 items.Add (item);
1500                                         break;
1501
1502                                 default:
1503                                         throw new Exception ("Unexpected Selection mode: " + box_select_mode);
1504                                 }
1505
1506                                 SuspendLayout ();
1507                                 owner.SelectItems (items);
1508                                 ResumeLayout ();
1509
1510                                 return true;
1511                         }
1512
1513                         private void ToggleCheckState (ListViewItem item)
1514                         {
1515                                 CheckState curr_state = item.Checked ?  CheckState.Checked : CheckState.Unchecked;
1516                                 item.Checked = !item.Checked;
1517                                 CheckState new_state = item.Checked ?  CheckState.Checked : CheckState.Unchecked;
1518
1519                                 ItemCheckEventArgs ice = new ItemCheckEventArgs (item.Index, curr_state, new_state);
1520                                 owner.OnItemCheck (ice);
1521                         }
1522
1523                         private void ItemsMouseDown (object sender, MouseEventArgs me)
1524                         {
1525                                 if (owner.items.Count == 0)
1526                                         return;
1527
1528                                 Point pt = new Point (me.X, me.Y);
1529                                 foreach (ListViewItem item in owner.items) {
1530                                         if (me.Clicks == 1 && item.CheckRectReal.Contains (pt)) {
1531                                                 checking = true;
1532                                                 if (me.Clicks > 1)
1533                                                         return;
1534                                                 ToggleCheckState (item);
1535                                                 return;
1536                                         }
1537
1538                                         if (owner.View == View.Details && !owner.FullRowSelect) {
1539                                                 if (item.GetBounds (ItemBoundsPortion.Label).Contains (pt)) {
1540                                                         clicked_item = item;
1541                                                         break;
1542                                                 }
1543                                         } else {
1544                                                 if (item.Bounds.Contains (pt)) {
1545                                                         clicked_item = item;
1546                                                         break;
1547                                                 }
1548                                         }
1549                                 }
1550
1551
1552                                 if (clicked_item != null) {
1553                                         owner.SetFocusedItem (clicked_item);
1554                                         bool changed = !clicked_item.Selected;
1555                                         if (owner.MultiSelect)
1556                                                 owner.UpdateMultiSelection (clicked_item.Index);
1557                                         else
1558                                                 clicked_item.Selected = true;
1559                                 
1560                                         if (changed)
1561                                                 owner.OnSelectedIndexChanged (EventArgs.Empty);
1562
1563                                         // Raise double click if the item was clicked. On MS the
1564                                         // double click is only raised if you double click an item
1565                                         if (me.Clicks > 1) {
1566                                                 owner.OnDoubleClick (EventArgs.Empty);
1567                                                 if (owner.CheckBoxes)
1568                                                         ToggleCheckState (clicked_item);
1569                                         } else if (me.Clicks == 1) {
1570                                                 owner.OnClick (EventArgs.Empty);
1571                                                 if (owner.LabelEdit && !changed)
1572                                                         BeginEdit (clicked_item); // this is probably not the correct place to execute BeginEdit
1573                                         }
1574                                 } else {
1575                                         if (owner.MultiSelect) {
1576                                                 Keys mods = XplatUI.State.ModifierKeys;
1577                                                 if ((mods & Keys.Shift) != 0)
1578                                                         box_select_mode = BoxSelect.Shift;
1579                                                 else if ((mods & Keys.Control) != 0)
1580                                                         box_select_mode = BoxSelect.Control;
1581                                                 else
1582                                                         box_select_mode = BoxSelect.Normal;
1583                                                 box_select_start = pt; 
1584                                                 prev_selection = owner.SelectedItems.List;
1585                                         } else if (owner.SelectedItems.Count > 0) {
1586                                                 owner.SelectedItems.Clear ();
1587                                                 owner.OnSelectedIndexChanged (EventArgs.Empty);
1588                                         }
1589                                 }
1590                         }
1591
1592                         private void ItemsMouseMove (object sender, MouseEventArgs me)
1593                         {
1594                                 if (PerformBoxSelection (new Point (me.X, me.Y)))
1595                                         return;
1596
1597                                 if (owner.HoverSelection && hover_processed) {
1598
1599                                         Point pt = PointToClient (Control.MousePosition);
1600                                         ListViewItem item = owner.GetItemAt (pt.X, pt.Y);
1601                                         if (item == null || item.Selected)
1602                                                 return;
1603
1604                                         hover_processed = false;
1605                                         XplatUI.ResetMouseHover (Handle);
1606                                 }
1607                         }
1608
1609
1610                         private void ItemsMouseHover (object sender, EventArgs e)
1611                         {
1612                                 if (Capture || !owner.HoverSelection)
1613                                         return;
1614
1615                                 hover_processed = true;
1616                                 Point pt = PointToClient (Control.MousePosition);
1617                                 ListViewItem item = owner.GetItemAt (pt.X, pt.Y);
1618
1619                                 if (item == null)
1620                                         return;
1621
1622                                 item.Selected = true;
1623                                 owner.OnSelectedIndexChanged (new EventArgs ());
1624                         }
1625
1626                         private void ItemsMouseUp (object sender, MouseEventArgs me)
1627                         {
1628                                 Capture = false;
1629                                 if (owner.Items.Count == 0)
1630                                         return;
1631
1632                                 Point pt = new Point (me.X, me.Y);
1633
1634                                 Rectangle rect = Rectangle.Empty;
1635                                 if (clicked_item != null) {
1636                                         if (owner.view == View.Details && !owner.full_row_select)
1637                                                 rect = clicked_item.GetBounds (ItemBoundsPortion.Label);
1638                                         else
1639                                                 rect = clicked_item.Bounds;
1640
1641                                         if (rect.Contains (pt)) {
1642                                                 switch (owner.activation) {
1643                                                 case ItemActivation.OneClick:
1644                                                         owner.OnItemActivate (EventArgs.Empty);
1645                                                         break;
1646
1647                                                 case ItemActivation.TwoClick:
1648                                                         if (last_clicked_item == clicked_item) {
1649                                                                 owner.OnItemActivate (EventArgs.Empty);
1650                                                                 last_clicked_item = null;
1651                                                         } else
1652                                                                 last_clicked_item = clicked_item;
1653                                                         break;
1654                                                 default:
1655                                                         // DoubleClick activation is handled in another handler
1656                                                         break;
1657                                                 }
1658                                         }
1659                                 } else if (!checking && owner.SelectedItems.Count > 0 && BoxSelectRectangle.Size.IsEmpty) {
1660                                         // Need this to clean up background clicks
1661                                         owner.SelectedItems.Clear ();
1662                                         owner.OnSelectedIndexChanged (EventArgs.Empty);
1663                                 }
1664
1665                                 clicked_item = null;
1666                                 box_select_start = Point.Empty;
1667                                 BoxSelectRectangle = Rectangle.Empty;
1668                                 prev_selection = null;
1669                                 box_select_mode = BoxSelect.None;
1670                                 checking = false;
1671                         }
1672                         
1673                         internal void LabelEditFinished (object sender, EventArgs e)
1674                         {
1675                                 EndEdit (edit_item);
1676                         }
1677                         
1678                         internal void BeginEdit (ListViewItem item)
1679                         {
1680                                 if (edit_item != null)
1681                                         EndEdit (edit_item);
1682                                 
1683                                 if (edit_text_box == null) {
1684                                         edit_text_box = new ListViewLabelEditTextBox ();
1685                                         edit_text_box.BorderStyle = BorderStyle.FixedSingle;
1686                                         edit_text_box.EditingFinished += new EventHandler (LabelEditFinished);
1687                                         edit_text_box.Visible = false;
1688                                         Controls.Add (edit_text_box);
1689                                 }
1690                                 
1691                                 item.EnsureVisible();
1692                                 
1693                                 edit_text_box.Reset ();
1694                                 
1695                                 switch (owner.view) {
1696                                         case View.List:
1697                                         case View.SmallIcon:
1698                                         case View.Details:
1699                                                 edit_text_box.TextAlign = HorizontalAlignment.Left;
1700                                                 edit_text_box.Bounds = item.GetBounds (ItemBoundsPortion.Label);
1701                                                 SizeF sizef = DeviceContext.MeasureString (item.Text, item.Font);
1702                                                 edit_text_box.Width = (int)sizef.Width + 4;
1703                                                 edit_text_box.MaxWidth = owner.ClientRectangle.Width - edit_text_box.Bounds.X;
1704                                                 edit_text_box.WordWrap = false;
1705                                                 edit_text_box.Multiline = false;
1706                                                 break;
1707                                         case View.LargeIcon:
1708                                                 edit_text_box.TextAlign = HorizontalAlignment.Center;
1709                                                 edit_text_box.Bounds = item.GetBounds (ItemBoundsPortion.Label);
1710                                                 sizef = DeviceContext.MeasureString (item.Text, item.Font);
1711                                                 edit_text_box.Width = (int)sizef.Width + 4;
1712                                                 edit_text_box.MaxWidth = item.GetBounds(ItemBoundsPortion.Entire).Width;
1713                                                 edit_text_box.MaxHeight = owner.ClientRectangle.Height - edit_text_box.Bounds.Y;
1714                                                 edit_text_box.WordWrap = true;
1715                                                 edit_text_box.Multiline = true;
1716                                                 break;
1717                                 }
1718                                 
1719                                 edit_text_box.Text = item.Text;
1720                                 edit_text_box.Font = item.Font;
1721                                 edit_text_box.Visible = true;
1722                                 edit_text_box.Focus ();
1723                                 edit_text_box.SelectAll ();
1724                                 
1725                                 edit_args = new LabelEditEventArgs (owner.Items.IndexOf(edit_item));
1726                                 owner.OnBeforeLabelEdit (edit_args);
1727                                 
1728                                 if (edit_args.CancelEdit)
1729                                         EndEdit (item);
1730                                 
1731                                 edit_item = item;
1732                         }
1733                         
1734                         internal void EndEdit (ListViewItem item)
1735                         {
1736                                 if (edit_text_box != null && edit_text_box.Visible) {
1737                                         edit_text_box.Visible = false;
1738                                 }
1739                                 
1740                                 if (edit_item != null && edit_item == item) {
1741                                         owner.OnAfterLabelEdit (edit_args);
1742                                         
1743                                         if (!edit_args.CancelEdit) {
1744                                                 if (edit_args.Label != null)
1745                                                         edit_item.Text = edit_args.Label;
1746                                                 else
1747                                                         edit_item.Text = edit_text_box.Text;
1748                                         }
1749                                         
1750                                 }
1751                                 
1752                                 
1753                                 edit_item = null;
1754                         }
1755
1756                         internal override void OnPaintInternal (PaintEventArgs pe)
1757                         {
1758                                 ThemeEngine.Current.DrawListViewItems (pe.Graphics, pe.ClipRectangle, owner);
1759                         }
1760
1761                         internal override void OnGotFocusInternal (EventArgs e)
1762                         {
1763                                 owner.Focus ();
1764                         }
1765                 }
1766                 
1767                 internal class ListViewLabelEditTextBox : TextBox
1768                 {
1769                         int max_width = -1;
1770                         int min_width = -1;
1771                         
1772                         int max_height = -1;
1773                         int min_height = -1;
1774                         
1775                         int old_number_lines = 1;
1776                         
1777                         SizeF text_size_one_char;
1778                         
1779                         public ListViewLabelEditTextBox ()
1780                         {
1781                                 min_height = DefaultSize.Height;
1782                                 text_size_one_char = DeviceContext.MeasureString ("B", Font);
1783                         }
1784                         
1785                         public int MaxWidth {
1786                                 set {
1787                                         if (value < min_width)
1788                                                 max_width = min_width;
1789                                         else
1790                                                 max_width = value;
1791                                 }
1792                         }
1793                         
1794                         public int MaxHeight {
1795                                 set {
1796                                         if (value < min_height)
1797                                                 max_height = min_height;
1798                                         else
1799                                                 max_height = value;
1800                                 }
1801                         }
1802                         
1803                         public new int Width {
1804                                 get {
1805                                         return base.Width;
1806                                 }
1807                                 set {
1808                                         min_width = value;
1809                                         base.Width = value;
1810                                 }
1811                         }
1812                         
1813                         public override Font Font {
1814                                 get {
1815                                         return base.Font;
1816                                 }
1817                                 set {
1818                                         base.Font = value;
1819                                         text_size_one_char = DeviceContext.MeasureString ("B", Font);
1820                                 }
1821                         }
1822                         
1823                         protected override void OnTextChanged (EventArgs e)
1824                         {
1825                                 SizeF text_size = DeviceContext.MeasureString (Text, Font);
1826                                 
1827                                 int new_width = (int)text_size.Width + 8;
1828                                 
1829                                 if (!Multiline)
1830                                         ResizeTextBoxWidth (new_width);
1831                                 else {
1832                                         if (Width != max_width)
1833                                                 ResizeTextBoxWidth (new_width);
1834                                         
1835                                         int number_lines = Lines.Length;
1836                                         
1837                                         if (number_lines != old_number_lines) {
1838                                                 int new_height = number_lines * (int)text_size_one_char.Height + 4;
1839                                                 old_number_lines = number_lines;
1840                                                 
1841                                                 ResizeTextBoxHeight (new_height);
1842                                         }
1843                                 }
1844                                 
1845                                 base.OnTextChanged (e);
1846                         }
1847                         
1848                         protected override bool IsInputKey (Keys key_data)
1849                         {
1850                                 if ((key_data & Keys.Alt) == 0) {
1851                                         switch (key_data & Keys.KeyCode) {
1852                                                 case Keys.Enter:
1853                                                         return true;
1854                                         }
1855                                 }
1856                                 return base.IsInputKey (key_data);
1857                         }
1858                         
1859                         protected override void OnKeyDown (KeyEventArgs e)
1860                         {
1861                                 if (e.KeyCode == Keys.Return && Visible) {
1862                                         this.Visible = false;
1863                                         OnEditingFinished (e);
1864                                 }
1865                         }
1866                         
1867                         protected override void OnLostFocus (EventArgs e)
1868                         {
1869                                 if (Visible) {
1870                                         OnEditingFinished (e);
1871                                 }
1872                         }
1873                         
1874                         protected void OnEditingFinished (EventArgs e)
1875                         {
1876                                 EventHandler eh = (EventHandler)(Events [EditingFinishedEvent]);
1877                                 if (eh != null)
1878                                         eh (this, e);
1879                         }
1880                         
1881                         private void ResizeTextBoxWidth (int new_width)
1882                         {
1883                                 if (new_width > max_width)
1884                                         base.Width = max_width;
1885                                 else 
1886                                 if (new_width >= min_width)
1887                                         base.Width = new_width;
1888                                 else
1889                                         base.Width = min_width;
1890                         }
1891                         
1892                         private void ResizeTextBoxHeight (int new_height)
1893                         {
1894                                 if (new_height > max_height)
1895                                         base.Height = max_height;
1896                                 else 
1897                                 if (new_height >= min_height)
1898                                         base.Height = new_height;
1899                                 else
1900                                         base.Height = min_height;
1901                         }
1902                         
1903                         public void Reset ()
1904                         {
1905                                 max_width = -1;
1906                                 min_width = -1;
1907                                 
1908                                 max_height = -1;
1909                                 
1910                                 old_number_lines = 1;
1911                                 
1912                                 Text = String.Empty;
1913                                 
1914                                 Size = DefaultSize;
1915                         }
1916                         
1917                         static object EditingFinishedEvent = new object ();
1918                         public event EventHandler EditingFinished {
1919                                 add { Events.AddHandler (EditingFinishedEvent, value); }
1920                                 remove { Events.RemoveHandler (EditingFinishedEvent, value); }
1921                         }
1922                 }
1923
1924                 internal override void OnPaintInternal (PaintEventArgs pe)
1925                 {
1926                         if (updating)
1927                                 return; 
1928                                 
1929                         CalculateScrollBars ();
1930                 }
1931
1932                 void FocusChanged (object o, EventArgs args)
1933                 {
1934                         if (Items.Count == 0)
1935                                 return;
1936
1937                         if (FocusedItem == null)
1938                                 SetFocusedItem (Items [0]);
1939
1940                         item_control.Invalidate (FocusedItem.Bounds);
1941                 }
1942
1943                 private void ListView_MouseWheel (object sender, MouseEventArgs me)
1944                 {
1945                         if (Items.Count == 0)
1946                                 return;
1947
1948                         int lines = me.Delta / 120;
1949
1950                         if (lines == 0)
1951                                 return;
1952
1953                         switch (View) {
1954                         case View.Details:
1955                         case View.SmallIcon:
1956                                 Scroll (v_scroll, -Items [0].Bounds.Height * SystemInformation.MouseWheelScrollLines * lines);
1957                                 break;
1958                         case View.LargeIcon:
1959                                 Scroll (v_scroll, -(Items [0].Bounds.Height + ThemeEngine.Current.ListViewVerticalSpacing)  * lines);
1960                                 break;
1961                         case View.List:
1962                                 Scroll (h_scroll, -Items [0].Bounds.Width * lines);
1963                                 break;
1964                         }
1965                 }
1966
1967                 private void ListView_SizeChanged (object sender, EventArgs e)
1968                 {
1969                         CalculateListView (alignment);
1970                 }
1971                 
1972                 private void SetFocusedItem (ListViewItem item)
1973                 {
1974                         if (focused_item != null)
1975                                 focused_item.Focused = false;
1976                         
1977                         if (item != null)
1978                                 item.Focused = true;
1979                                 
1980                         focused_item = item;
1981                 }
1982
1983                 private void HorizontalScroller (object sender, EventArgs e)
1984                 {
1985                         item_control.EndEdit (item_control.edit_item);
1986                         
1987                         // Avoid unnecessary flickering, when button is
1988                         // kept pressed at the end
1989                         if (h_marker != h_scroll.Value) {
1990                                 
1991                                 int pixels =  h_marker - h_scroll.Value;
1992                                 
1993                                 h_marker = h_scroll.Value;
1994                                 if (header_control.Visible)
1995                                         XplatUI.ScrollWindow (header_control.Handle, pixels, 0, false);
1996
1997                                 XplatUI.ScrollWindow (item_control.Handle, pixels, 0, false);
1998                         }
1999                 }
2000
2001                 private void VerticalScroller (object sender, EventArgs e)
2002                 {
2003                         item_control.EndEdit (item_control.edit_item);
2004                         
2005                         // Avoid unnecessary flickering, when button is
2006                         // kept pressed at the end
2007                         if (v_marker != v_scroll.Value) {
2008                                 int pixels =  v_marker - v_scroll.Value;
2009                                 Rectangle area = item_control.ClientRectangle;
2010                                 v_marker = v_scroll.Value;
2011                                 XplatUI.ScrollWindow (item_control.Handle, area, 0, pixels, false);
2012                         }
2013                 }
2014                 #endregion      // Internal Methods Properties
2015
2016                 #region Protected Methods
2017                 protected override void CreateHandle ()
2018                 {
2019                         base.CreateHandle ();
2020                         for (int i = 0; i < SelectedItems.Count; i++)
2021                                 OnSelectedIndexChanged (EventArgs.Empty);
2022                 }
2023
2024                 protected override void Dispose (bool disposing)
2025                 {                       
2026                         if (disposing) {                        
2027                                 h_scroll.Dispose ();
2028                                 v_scroll.Dispose ();
2029                                 
2030                                 large_image_list = null;
2031                                 small_image_list = null;
2032                                 state_image_list = null;
2033                         }
2034                         
2035                         base.Dispose (disposing);
2036                 }
2037
2038                 protected override bool IsInputKey (Keys keyData)
2039                 {
2040                         switch (keyData) {
2041                         case Keys.Up:
2042                         case Keys.Down:
2043                         case Keys.PageUp:
2044                         case Keys.PageDown:
2045                         case Keys.Right:
2046                         case Keys.Left:
2047                         case Keys.End:
2048                         case Keys.Home:                         
2049                                 return true;
2050
2051                         default:
2052                                 break;
2053                         }
2054                         
2055                         return base.IsInputKey (keyData);
2056                 }
2057
2058                 protected virtual void OnAfterLabelEdit (LabelEditEventArgs e)
2059                 {
2060                         LabelEditEventHandler eh = (LabelEditEventHandler)(Events [AfterLabelEditEvent]);
2061                         if (eh != null)
2062                                 eh (this, e);
2063                 }
2064
2065                 protected virtual void OnBeforeLabelEdit (LabelEditEventArgs e)
2066                 {
2067                         LabelEditEventHandler eh = (LabelEditEventHandler)(Events [BeforeLabelEditEvent]);
2068                         if (eh != null)
2069                                 eh (this, e);
2070                 }
2071
2072                 protected virtual void OnColumnClick (ColumnClickEventArgs e)
2073                 {
2074                         ColumnClickEventHandler eh = (ColumnClickEventHandler)(Events [ColumnClickEvent]);
2075                         if (eh != null)
2076                                 eh (this, e);
2077                 }
2078
2079                 protected override void OnEnabledChanged (EventArgs e)
2080                 {
2081                         base.OnEnabledChanged (e);
2082                 }
2083
2084                 protected override void OnFontChanged (EventArgs e)
2085                 {
2086                         base.OnFontChanged (e);
2087                         Redraw (true);
2088                 }
2089
2090                 protected override void OnHandleCreated (EventArgs e)
2091                 {
2092                         base.OnHandleCreated (e);
2093                         Sort ();
2094                 }
2095
2096                 protected override void OnHandleDestroyed (EventArgs e)
2097                 {
2098                         base.OnHandleDestroyed (e);
2099                 }
2100
2101                 protected virtual void OnItemActivate (EventArgs e)
2102                 {
2103                         EventHandler eh = (EventHandler)(Events [ItemActivateEvent]);
2104                         if (eh != null)
2105                                 eh (this, e);
2106                 }
2107
2108                 protected virtual void OnItemCheck (ItemCheckEventArgs ice)
2109                 {
2110                         EventHandler eh = (EventHandler)(Events [ItemCheckEvent]);
2111                         if (eh != null)
2112                                 eh (this, ice);
2113                 }
2114
2115                 protected virtual void OnItemDrag (ItemDragEventArgs e)
2116                 {
2117                         EventHandler eh = (EventHandler)(Events [ItemDragEvent]);
2118                         if (eh != null)
2119                                 eh (this, e);
2120                 }
2121
2122                 protected virtual void OnSelectedIndexChanged (EventArgs e)
2123                 {
2124                         EventHandler eh = (EventHandler)(Events [SelectedIndexChangedEvent]);
2125                         if (eh != null)
2126                                 eh (this, e);
2127                 }
2128
2129                 protected override void OnSystemColorsChanged (EventArgs e)
2130                 {
2131                         base.OnSystemColorsChanged (e);
2132                 }
2133
2134                 protected void RealizeProperties ()
2135                 {
2136                         // FIXME: TODO
2137                 }
2138
2139                 protected void UpdateExtendedStyles ()
2140                 {
2141                         // FIXME: TODO
2142                 }
2143
2144                 protected override void WndProc (ref Message m)
2145                 {
2146                         base.WndProc (ref m);
2147                 }
2148                 #endregion // Protected Methods
2149
2150                 #region Public Instance Methods
2151                 public void ArrangeIcons ()
2152                 {
2153                         ArrangeIcons (this.alignment);
2154                 }
2155
2156                 public void ArrangeIcons (ListViewAlignment alignment)
2157                 {
2158                         // Icons are arranged only if view is set to LargeIcon or SmallIcon
2159                         if (view == View.LargeIcon || view == View.SmallIcon) {
2160                                 this.CalculateListView (alignment);
2161                                 // we have done the calculations already
2162                                 this.Redraw (false);
2163                         }
2164                 }
2165
2166                 public void BeginUpdate ()
2167                 {
2168                         // flag to avoid painting
2169                         updating = true;
2170                 }
2171
2172                 public void Clear ()
2173                 {
2174                         columns.Clear ();
2175                         items.Clear (); // Redraw (true) called here                    
2176                 }
2177
2178                 public void EndUpdate ()
2179                 {
2180                         // flag to avoid painting
2181                         updating = false;
2182
2183                         // probably, now we need a redraw with recalculations
2184                         this.Redraw (true);
2185                 }
2186
2187                 public void EnsureVisible (int index)
2188                 {
2189                         if (index < 0 || index >= items.Count || scrollable == false)
2190                                 return;
2191
2192                         Rectangle view_rect = item_control.ClientRectangle;
2193                         Rectangle bounds = items [index].Bounds;
2194
2195                         if (view_rect.Contains (bounds))
2196                                 return;
2197
2198                         if (bounds.Left < 0)
2199                                 h_scroll.Value += bounds.Left;
2200                         else if (bounds.Right > view_rect.Right)
2201                                 h_scroll.Value += (bounds.Right - view_rect.Right);
2202
2203                         if (bounds.Top < 0)
2204                                 v_scroll.Value += bounds.Top;
2205                         else if (bounds.Bottom > view_rect.Bottom)
2206                                 v_scroll.Value += (bounds.Bottom - view_rect.Bottom);
2207                 }
2208                 
2209                 public ListViewItem GetItemAt (int x, int y)
2210                 {
2211                         foreach (ListViewItem item in items) {
2212                                 if (item.Bounds.Contains (x, y))
2213                                         return item;
2214                         }
2215                         return null;
2216                 }
2217
2218                 public Rectangle GetItemRect (int index)
2219                 {
2220                         return GetItemRect (index, ItemBoundsPortion.Entire);
2221                 }
2222
2223                 public Rectangle GetItemRect (int index, ItemBoundsPortion portion)
2224                 {
2225                         if (index < 0 || index >= items.Count)
2226                                 throw new IndexOutOfRangeException ("index");
2227
2228                         return items [index].GetBounds (portion);
2229                 }
2230
2231                 public void Sort ()
2232                 {
2233                         Sort (true);
2234                 }
2235
2236                 // we need this overload to reuse the logic for sorting, while allowing
2237                 // redrawing to be done by caller or have it done by this method when
2238                 // sorting is really performed
2239                 //
2240                 // ListViewItemCollection's Add and AddRange methods call this overload
2241                 // with redraw set to false, as they take care of redrawing themselves
2242                 // (they even want to redraw the listview if no sort is performed, as 
2243                 // an item was added), while ListView.Sort () only wants to redraw if 
2244                 // sorting was actually performed
2245                 private void Sort (bool redraw)
2246                 {
2247                         if (!IsHandleCreated || item_sorter == null) {
2248                                 return;
2249                         }
2250                         
2251                         items.Sort (item_sorter);
2252                         if (redraw)
2253                                 this.Redraw (true);
2254                 }
2255
2256                 public override string ToString ()
2257                 {
2258                         int count = this.Items.Count;
2259
2260                         if (count == 0)
2261                                 return string.Format ("System.Windows.Forms.ListView, Items.Count: 0");
2262                         else
2263                                 return string.Format ("System.Windows.Forms.ListView, Items.Count: {0}, Items[0]: {1}", count, this.Items [0].ToString ());
2264                 }
2265                 #endregion      // Public Instance Methods
2266
2267
2268                 #region Subclasses
2269
2270                 class HeaderControl : Control {
2271
2272                         ListView owner;
2273                         bool column_resize_active = false;
2274                         ColumnHeader resize_column;
2275                         ColumnHeader clicked_column;
2276                         ColumnHeader drag_column;
2277                         int drag_x;
2278                         int drag_to_index = -1;
2279
2280                         public HeaderControl (ListView owner)
2281                         {
2282                                 this.owner = owner;
2283                                 MouseDown += new MouseEventHandler (HeaderMouseDown);
2284                                 MouseMove += new MouseEventHandler (HeaderMouseMove);
2285                                 MouseUp += new MouseEventHandler (HeaderMouseUp);
2286                         }
2287
2288                         private ColumnHeader ColumnAtX (int x)
2289                         {
2290                                 Point pt = new Point (x, 0);
2291                                 ColumnHeader result = null;
2292                                 foreach (ColumnHeader col in owner.Columns) {
2293                                         if (col.Rect.Contains (pt)) {
2294                                                 result = col;
2295                                                 break;
2296                                         }
2297                                 }
2298                                 return result;
2299                         }
2300
2301                         private int GetReorderedIndex (ColumnHeader col)
2302                         {
2303                                 if (owner.reordered_column_indices == null)
2304                                         return col.Index;
2305                                 else
2306                                         for (int i = 0; i < owner.Columns.Count; i++)
2307                                                 if (owner.reordered_column_indices [i] == col.Index)
2308                                                         return i;
2309                                 throw new Exception ("Column index missing from reordered array");
2310                         }
2311
2312                         private void HeaderMouseDown (object sender, MouseEventArgs me)
2313                         {
2314                                 if (resize_column != null) {
2315                                         column_resize_active = true;
2316                                         Capture = true;
2317                                         return;
2318                                 }
2319
2320                                 clicked_column = ColumnAtX (me.X + owner.h_marker);
2321
2322                                 if (clicked_column != null) {
2323                                         Capture = true;
2324                                         if (owner.AllowColumnReorder) {
2325                                                 drag_x = me.X;
2326                                                 drag_column = (ColumnHeader) (clicked_column as ICloneable).Clone ();
2327                                                 drag_column.column_rect = clicked_column.Rect;
2328                                                 drag_to_index = GetReorderedIndex (clicked_column);
2329                                         }
2330                                         clicked_column.pressed = true;
2331                                         Rectangle bounds = clicked_column.Rect;
2332                                         bounds.X -= owner.h_marker;
2333                                         Invalidate (bounds);
2334                                         return;
2335                                 }
2336                         }
2337
2338                         private void HeaderMouseMove (object sender, MouseEventArgs me)
2339                         {
2340                                 Point pt = new Point (me.X + owner.h_marker, me.Y);
2341
2342                                 if (column_resize_active)  {
2343                                         resize_column.Width = pt.X - resize_column.X;
2344                                         if (resize_column.Width < 0)
2345                                                 resize_column.Width = 0;
2346                                         return;
2347                                 }
2348
2349                                 resize_column = null;
2350
2351                                 if (clicked_column != null) {
2352                                         if (owner.AllowColumnReorder) {
2353                                                 Rectangle r;
2354
2355                                                 r = drag_column.column_rect;
2356                                                 r.X = clicked_column.Rect.X + me.X - drag_x;
2357                                                 drag_column.column_rect = r;
2358
2359                                                 int x = me.X + owner.h_marker;
2360                                                 ColumnHeader over = ColumnAtX (x);
2361                                                 if (over == null)
2362                                                         drag_to_index = owner.Columns.Count;
2363                                                 else if (x < over.X + over.Width / 2)
2364                                                         drag_to_index = GetReorderedIndex (over);
2365                                                 else
2366                                                         drag_to_index = GetReorderedIndex (over) + 1;
2367                                                 Invalidate ();
2368                                         } else {
2369                                                 ColumnHeader over = ColumnAtX (me.X + owner.h_marker);
2370                                                 bool pressed = clicked_column.pressed;
2371                                                 clicked_column.pressed = over == clicked_column;
2372                                                 if (clicked_column.pressed ^ pressed) {
2373                                                         Rectangle bounds = clicked_column.Rect;
2374                                                         bounds.X -= owner.h_marker;
2375                                                         Invalidate (bounds);
2376                                                 }
2377                                         }
2378                                         return;
2379                                 }
2380
2381                                 for (int i = 0; i < owner.Columns.Count; i++) {
2382                                         Rectangle zone = owner.Columns [i].Rect;
2383                                         zone.X = zone.Right - 5;
2384                                         zone.Width = 10;
2385                                         if (zone.Contains (pt)) {
2386                                                 if (i < owner.Columns.Count - 1 && owner.Columns [i + 1].Width == 0)
2387                                                         i++;
2388                                                 resize_column = owner.Columns [i];
2389                                                 break;
2390                                         }
2391                                 }
2392
2393                                 if (resize_column == null)
2394                                         Cursor = Cursors.Default;
2395                                 else
2396                                         Cursor = Cursors.VSplit;
2397                         }
2398
2399                         void HeaderMouseUp (object sender, MouseEventArgs me)
2400                         {
2401                                 Capture = false;
2402
2403                                 if (column_resize_active) {
2404                                         column_resize_active = false;
2405                                         resize_column = null;
2406                                         Cursor = Cursors.Default;
2407                                         return;
2408                                 }
2409
2410                                 if (clicked_column != null && clicked_column.pressed) {
2411                                         clicked_column.pressed = false;
2412                                         Rectangle bounds = clicked_column.Rect;
2413                                         bounds.X -= owner.h_marker;
2414                                         Invalidate (bounds);
2415                                         owner.OnColumnClick (new ColumnClickEventArgs (clicked_column.Index));
2416                                 }
2417
2418                                 if (drag_column != null && owner.AllowColumnReorder) {
2419                                         drag_column = null;
2420                                         if (drag_to_index > GetReorderedIndex (clicked_column))
2421                                                 drag_to_index--;
2422                                         if (owner.GetReorderedColumn (drag_to_index) != clicked_column)
2423                                                 owner.ReorderColumn (clicked_column, drag_to_index);
2424                                         drag_to_index = -1;
2425                                         Invalidate ();
2426                                 }
2427
2428                                 clicked_column = null;
2429                         }
2430
2431                         internal override void OnPaintInternal (PaintEventArgs pe)
2432                         {
2433                                 if (owner.updating)
2434                                         return; 
2435                                 
2436                                 Theme theme = ThemeEngine.Current;
2437                                 theme.DrawListViewHeader (pe.Graphics, pe.ClipRectangle, this.owner);
2438
2439                                 if (drag_column == null)
2440                                         return;
2441
2442                                 int target_x;
2443                                 if (drag_to_index == owner.Columns.Count)
2444                                         target_x = owner.GetReorderedColumn (drag_to_index - 1).Rect.Right - owner.h_marker;
2445                                 else
2446                                         target_x = owner.GetReorderedColumn (drag_to_index).Rect.X - owner.h_marker;
2447                                 theme.DrawListViewHeaderDragDetails (pe.Graphics, owner, drag_column, target_x);
2448                         }
2449
2450                         protected override void WndProc (ref Message m)
2451                         {
2452                                 switch ((Msg)m.Msg) {
2453                                 case Msg.WM_SETFOCUS:
2454                                         owner.Focus ();
2455                                         break;
2456                                 default:
2457                                         base.WndProc (ref m);
2458                                         break;
2459                                 }
2460                         }
2461                 }
2462
2463                 private class ItemComparer : IComparer {
2464                         readonly SortOrder sort_order;
2465
2466                         public ItemComparer (SortOrder sortOrder)
2467                         {
2468                                 sort_order = sortOrder;
2469                         }
2470
2471                         public int Compare (object x, object y)
2472                         {
2473                                 ListViewItem item_x = x as ListViewItem;
2474                                 ListViewItem item_y = y as ListViewItem;
2475                                 if (sort_order == SortOrder.Ascending)
2476                                         return String.Compare (item_x.Text, item_y.Text);
2477                                 else
2478                                         return String.Compare (item_y.Text, item_x.Text);
2479                         }
2480                 }
2481
2482                 public class CheckedIndexCollection : IList, ICollection, IEnumerable
2483                 {
2484                         private readonly ListView owner;
2485
2486                         #region Public Constructor
2487                         public CheckedIndexCollection (ListView owner)
2488                         {
2489                                 this.owner = owner;
2490                         }
2491                         #endregion      // Public Constructor
2492
2493                         #region Public Properties
2494                         [Browsable (false)]
2495                         public int Count {
2496                                 get { return owner.CheckedItems.Count; }
2497                         }
2498
2499                         public bool IsReadOnly {
2500                                 get { return true; }
2501                         }
2502
2503                         public int this [int index] {
2504                                 get {
2505                                         int [] indices = GetIndices ();
2506                                         if (index < 0 || index >= indices.Length)
2507                                                 throw new ArgumentOutOfRangeException ("index");
2508                                         return indices [index];
2509                                 }
2510                         }
2511
2512                         bool ICollection.IsSynchronized {
2513                                 get { return false; }
2514                         }
2515
2516                         object ICollection.SyncRoot {
2517                                 get { return this; }
2518                         }
2519
2520                         bool IList.IsFixedSize {
2521                                 get { return true; }
2522                         }
2523
2524                         object IList.this [int index] {
2525                                 get { return this [index]; }
2526                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
2527                         }
2528                         #endregion      // Public Properties
2529
2530                         #region Public Methods
2531                         public bool Contains (int checkedIndex)
2532                         {
2533                                 int [] indices = GetIndices ();
2534                                 for (int i = 0; i < indices.Length; i++) {
2535                                         if (indices [i] == checkedIndex)
2536                                                 return true;
2537                                 }
2538                                 return false;
2539                         }
2540
2541                         public IEnumerator GetEnumerator ()
2542                         {
2543                                 int [] indices = GetIndices ();
2544                                 return indices.GetEnumerator ();
2545                         }
2546
2547                         void ICollection.CopyTo (Array dest, int index)
2548                         {
2549                                 int [] indices = GetIndices ();
2550                                 Array.Copy (indices, 0, dest, index, indices.Length);
2551                         }
2552
2553                         int IList.Add (object value)
2554                         {
2555                                 throw new NotSupportedException ("Add operation is not supported.");
2556                         }
2557
2558                         void IList.Clear ()
2559                         {
2560                                 throw new NotSupportedException ("Clear operation is not supported.");
2561                         }
2562
2563                         bool IList.Contains (object checkedIndex)
2564                         {
2565                                 if (!(checkedIndex is int))
2566                                         return false;
2567                                 return Contains ((int) checkedIndex);
2568                         }
2569
2570                         int IList.IndexOf (object checkedIndex)
2571                         {
2572                                 if (!(checkedIndex is int))
2573                                         return -1;
2574                                 return IndexOf ((int) checkedIndex);
2575                         }
2576
2577                         void IList.Insert (int index, object value)
2578                         {
2579                                 throw new NotSupportedException ("Insert operation is not supported.");
2580                         }
2581
2582                         void IList.Remove (object value)
2583                         {
2584                                 throw new NotSupportedException ("Remove operation is not supported.");
2585                         }
2586
2587                         void IList.RemoveAt (int index)
2588                         {
2589                                 throw new NotSupportedException ("RemoveAt operation is not supported.");
2590                         }
2591
2592                         public int IndexOf (int checkedIndex)
2593                         {
2594                                 int [] indices = GetIndices ();
2595                                 for (int i = 0; i < indices.Length; i++) {
2596                                         if (indices [i] == checkedIndex)
2597                                                 return i;
2598                                 }
2599                                 return -1;
2600                         }
2601                         #endregion      // Public Methods
2602
2603                         private int [] GetIndices ()
2604                         {
2605                                 ArrayList checked_items = owner.CheckedItems.List;
2606                                 int [] indices = new int [checked_items.Count];
2607                                 for (int i = 0; i < checked_items.Count; i++) {
2608                                         ListViewItem item = (ListViewItem) checked_items [i];
2609                                         indices [i] = item.Index;
2610                                 }
2611                                 return indices;
2612                         }
2613                 }       // CheckedIndexCollection
2614
2615                 public class CheckedListViewItemCollection : IList, ICollection, IEnumerable
2616                 {
2617                         private readonly ListView owner;
2618                         private ArrayList list;
2619
2620                         #region Public Constructor
2621                         public CheckedListViewItemCollection (ListView owner)
2622                         {
2623                                 this.owner = owner;
2624                                 this.owner.Items.Changed += new CollectionChangedHandler (
2625                                         ItemsCollection_Changed);
2626                         }
2627                         #endregion      // Public Constructor
2628
2629                         #region Public Properties
2630                         [Browsable (false)]
2631                         public int Count {
2632                                 get {
2633                                         if (!owner.CheckBoxes)
2634                                                 return 0;
2635                                         return List.Count;
2636                                 }
2637                         }
2638
2639                         public bool IsReadOnly {
2640                                 get { return true; }
2641                         }
2642
2643                         public ListViewItem this [int index] {
2644                                 get {
2645                                         ArrayList checked_items = List;
2646                                         if (index < 0 || index >= checked_items.Count)
2647                                                 throw new ArgumentOutOfRangeException ("index");
2648                                         return (ListViewItem) checked_items [index];
2649                                 }
2650                         }
2651
2652                         bool ICollection.IsSynchronized {
2653                                 get { return false; }
2654                         }
2655
2656                         object ICollection.SyncRoot {
2657                                 get { return this; }
2658                         }
2659
2660                         bool IList.IsFixedSize {
2661                                 get { return true; }
2662                         }
2663
2664                         object IList.this [int index] {
2665                                 get { return this [index]; }
2666                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
2667                         }
2668                         #endregion      // Public Properties
2669
2670                         #region Public Methods
2671                         public bool Contains (ListViewItem item)
2672                         {
2673                                 if (!owner.CheckBoxes)
2674                                         return false;
2675                                 return List.Contains (item);
2676                         }
2677
2678                         public void CopyTo (Array dest, int index)
2679                         {
2680                                 if (!owner.CheckBoxes)
2681                                         return;
2682                                 List.CopyTo (dest, index);
2683                         }
2684
2685                         public IEnumerator GetEnumerator ()
2686                         {
2687                                 if (!owner.CheckBoxes)
2688                                         return (new ListViewItem [0]).GetEnumerator ();
2689                                 return List.GetEnumerator ();
2690                         }
2691
2692                         int IList.Add (object value)
2693                         {
2694                                 throw new NotSupportedException ("Add operation is not supported.");
2695                         }
2696
2697                         void IList.Clear ()
2698                         {
2699                                 throw new NotSupportedException ("Clear operation is not supported.");
2700                         }
2701
2702                         bool IList.Contains (object item)
2703                         {
2704                                 if (!(item is ListViewItem))
2705                                         return false;
2706                                 return Contains ((ListViewItem) item);
2707                         }
2708
2709                         int IList.IndexOf (object item)
2710                         {
2711                                 if (!(item is ListViewItem))
2712                                         return -1;
2713                                 return IndexOf ((ListViewItem) item);
2714                         }
2715
2716                         void IList.Insert (int index, object value)
2717                         {
2718                                 throw new NotSupportedException ("Insert operation is not supported.");
2719                         }
2720
2721                         void IList.Remove (object value)
2722                         {
2723                                 throw new NotSupportedException ("Remove operation is not supported.");
2724                         }
2725
2726                         void IList.RemoveAt (int index)
2727                         {
2728                                 throw new NotSupportedException ("RemoveAt operation is not supported.");
2729                         }
2730
2731                         public int IndexOf (ListViewItem item)
2732                         {
2733                                 if (!owner.CheckBoxes)
2734                                         return -1;
2735                                 return List.IndexOf (item);
2736                         }
2737                         #endregion      // Public Methods
2738
2739                         internal ArrayList List {
2740                                 get {
2741                                         if (list == null) {
2742                                                 list = new ArrayList ();
2743                                                 foreach (ListViewItem item in owner.Items) {
2744                                                         if (item.Checked)
2745                                                                 list.Add (item);
2746                                                 }
2747                                         }
2748                                         return list;
2749                                 }
2750                         }
2751
2752                         internal void Reset ()
2753                         {
2754                                 // force re-population of list
2755                                 list = null;
2756                         }
2757
2758                         private void ItemsCollection_Changed ()
2759                         {
2760                                 Reset ();
2761                         }
2762                 }       // CheckedListViewItemCollection
2763
2764                 public class ColumnHeaderCollection : IList, ICollection, IEnumerable
2765                 {
2766                         internal ArrayList list;
2767                         private ListView owner;
2768
2769                         #region Public Constructor
2770                         public ColumnHeaderCollection (ListView owner)
2771                         {
2772                                 list = new ArrayList ();
2773                                 this.owner = owner;
2774                         }
2775                         #endregion      // Public Constructor
2776
2777                         #region Public Properties
2778                         [Browsable (false)]
2779                         public int Count {
2780                                 get { return list.Count; }
2781                         }
2782
2783                         public bool IsReadOnly {
2784                                 get { return false; }
2785                         }
2786
2787                         public virtual ColumnHeader this [int index] {
2788                                 get {
2789                                         if (index < 0 || index >= list.Count)
2790                                                 throw new ArgumentOutOfRangeException ("index");
2791                                         return (ColumnHeader) list [index];
2792                                 }
2793                         }
2794
2795 #if NET_2_0
2796                         public virtual ColumnHeader this [string key] {
2797                                 get {
2798                                         int idx = IndexOfKey (key);
2799                                         if (idx == -1)
2800                                                 return null;
2801
2802                                         return (ColumnHeader) list [idx];
2803                                 }
2804                         }
2805 #endif
2806
2807                         bool ICollection.IsSynchronized {
2808                                 get { return true; }
2809                         }
2810
2811                         object ICollection.SyncRoot {
2812                                 get { return this; }
2813                         }
2814
2815                         bool IList.IsFixedSize {
2816                                 get { return list.IsFixedSize; }
2817                         }
2818
2819                         object IList.this [int index] {
2820                                 get { return this [index]; }
2821                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
2822                         }
2823                         #endregion      // Public Properties
2824
2825                         #region Public Methods
2826                         public virtual int Add (ColumnHeader value)
2827                         {
2828                                 int idx;
2829                                 value.owner = this.owner;
2830                                 idx = list.Add (value);
2831                                 if (owner.IsHandleCreated) {
2832                                         owner.Redraw (true); 
2833                                 }
2834                                 return idx;
2835                         }
2836
2837                         public virtual ColumnHeader Add (string str, int width, HorizontalAlignment textAlign)
2838                         {
2839                                 ColumnHeader colHeader = new ColumnHeader (this.owner, str, textAlign, width);
2840                                 this.Add (colHeader);                                                                   
2841                                 return colHeader;
2842                         }
2843
2844 #if NET_2_0
2845                         public virtual ColumnHeader Add (string text)
2846                         {
2847                                 return Add (String.Empty, text);
2848                         }
2849
2850                         public virtual ColumnHeader Add (string text, int iwidth)
2851                         {
2852                                 return Add (String.Empty, text, iwidth);
2853                         }
2854
2855                         public virtual ColumnHeader Add (string key, string text)
2856                         {
2857                                 ColumnHeader colHeader = new ColumnHeader ();
2858                                 colHeader.Name = key;
2859                                 colHeader.Text = text;
2860                                 Add (colHeader);
2861                                 return colHeader;
2862                         }
2863
2864                         public virtual ColumnHeader Add (string key, string text, int iwidth)
2865                         {
2866                                 return Add (key, text, iwidth, HorizontalAlignment.Left, -1);
2867                         }
2868
2869                         public virtual ColumnHeader Add (string key, string text, int iwidth, HorizontalAlignment textAlign, int imageIndex)
2870                         {
2871                                 ColumnHeader colHeader = new ColumnHeader (key, text, iwidth, textAlign);
2872                                 colHeader.ImageIndex = imageIndex;
2873                                 Add (colHeader);
2874                                 return colHeader;
2875                         }
2876
2877                         public virtual ColumnHeader Add (string key, string text, int iwidth, HorizontalAlignment textAlign, string imageKey)
2878                         {
2879                                 ColumnHeader colHeader = new ColumnHeader (key, text, iwidth, textAlign);
2880                                 colHeader.ImageKey = imageKey;
2881                                 Add (colHeader);
2882                                 return colHeader;
2883                         }
2884 #endif
2885
2886                         public virtual void AddRange (ColumnHeader [] values)
2887                         {
2888                                 foreach (ColumnHeader colHeader in values) {
2889                                         colHeader.owner = this.owner;
2890                                         Add (colHeader);
2891                                 }
2892                                 
2893                                 owner.Redraw (true); 
2894                         }
2895
2896                         public virtual void Clear ()
2897                         {
2898                                 list.Clear ();
2899                                 owner.Redraw (true);
2900                         }
2901
2902                         public bool Contains (ColumnHeader value)
2903                         {
2904                                 return list.Contains (value);
2905                         }
2906
2907 #if NET_2_0
2908                         public virtual bool ContainsKey (string key)
2909                         {
2910                                 return IndexOfKey (key) != -1;
2911                         }
2912 #endif
2913
2914                         public IEnumerator GetEnumerator ()
2915                         {
2916                                 return list.GetEnumerator ();
2917                         }
2918
2919                         void ICollection.CopyTo (Array dest, int index)
2920                         {
2921                                 list.CopyTo (dest, index);
2922                         }
2923
2924                         int IList.Add (object value)
2925                         {
2926                                 if (! (value is ColumnHeader)) {
2927                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
2928                                 }
2929
2930                                 return this.Add ((ColumnHeader) value);
2931                         }
2932
2933                         bool IList.Contains (object value)
2934                         {
2935                                 if (! (value is ColumnHeader)) {
2936                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
2937                                 }
2938
2939                                 return this.Contains ((ColumnHeader) value);
2940                         }
2941
2942                         int IList.IndexOf (object value)
2943                         {
2944                                 if (! (value is ColumnHeader)) {
2945                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
2946                                 }
2947
2948                                 return this.IndexOf ((ColumnHeader) value);
2949                         }
2950
2951                         void IList.Insert (int index, object value)
2952                         {
2953                                 if (! (value is ColumnHeader)) {
2954                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
2955                                 }
2956
2957                                 this.Insert (index, (ColumnHeader) value);
2958                         }
2959
2960                         void IList.Remove (object value)
2961                         {
2962                                 if (! (value is ColumnHeader)) {
2963                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
2964                                 }
2965
2966                                 this.Remove ((ColumnHeader) value);
2967                         }
2968
2969                         public int IndexOf (ColumnHeader value)
2970                         {
2971                                 return list.IndexOf (value);
2972                         }
2973
2974 #if NET_2_0
2975                         public virtual int IndexOfKey (string key)
2976                         {
2977                                 if (key == null || key.Length == 0)
2978                                         return -1;
2979
2980                                 for (int i = 0; i < list.Count; i++) {
2981                                         ColumnHeader col = (ColumnHeader) list [i];
2982                                         if (String.Compare (key, col.Name, true) == 0)
2983                                                 return i;
2984                                 }
2985
2986                                 return -1;
2987                         }
2988 #endif
2989
2990                         public void Insert (int index, ColumnHeader value)
2991                         {
2992                                 // LAMESPEC: MSDOCS say greater than or equal to the value of the Count property
2993                                 // but it's really only greater.
2994                                 if (index < 0 || index > list.Count)
2995                                         throw new ArgumentOutOfRangeException ("index");
2996
2997                                 value.owner = this.owner;
2998                                 list.Insert (index, value);
2999                                 owner.Redraw (true);
3000                         }
3001
3002 #if NET_2_0
3003                         public void Insert (int index, string text)
3004                         {
3005                                 Insert (index, String.Empty, text);
3006                         }
3007
3008                         public void Insert (int index, string text, int width)
3009                         {
3010                                 Insert (index, String.Empty, text, width);
3011                         }
3012
3013                         public void Insert (int index, string key, string text)
3014                         {
3015                                 ColumnHeader colHeader = new ColumnHeader ();
3016                                 colHeader.Name = key;
3017                                 colHeader.Text = text;
3018                                 Insert (index, colHeader);
3019                         }
3020
3021                         public void Insert (int index, string key, string text, int width)
3022                         {
3023                                 ColumnHeader colHeader = new ColumnHeader (key, text, width, HorizontalAlignment.Left);
3024                                 Insert (index, colHeader);
3025                         }
3026
3027                         public void Insert (int index, string key, string text, int width, HorizontalAlignment textAlign, int imageIndex)
3028                         {
3029                                 ColumnHeader colHeader = new ColumnHeader (key, text, width, textAlign);
3030                                 colHeader.ImageIndex = imageIndex;
3031                                 Insert (index, colHeader);
3032                         }
3033
3034                         public void Insert (int index, string key, string text, int width, HorizontalAlignment textAlign, string imageKey)
3035                         {
3036                                 ColumnHeader colHeader = new ColumnHeader (key, text, width, textAlign);
3037                                 colHeader.ImageKey = imageKey;
3038                                 Insert (index, colHeader);
3039                         }
3040 #endif
3041
3042                         public void Insert (int index, string str, int width, HorizontalAlignment textAlign)
3043                         {
3044                                 ColumnHeader colHeader = new ColumnHeader (this.owner, str, textAlign, width);
3045                                 this.Insert (index, colHeader);
3046                         }
3047
3048                         public virtual void Remove (ColumnHeader column)
3049                         {
3050                                 // TODO: Update Column internal index ?
3051                                 list.Remove (column);
3052                                 owner.Redraw (true);
3053                         }
3054
3055 #if NET_2_0
3056                         public virtual void RemoveByKey (string key)
3057                         {
3058                                 int idx = IndexOfKey (key);
3059                                 if (idx != -1)
3060                                         RemoveAt (idx);
3061                         }
3062 #endif
3063
3064                         public virtual void RemoveAt (int index)
3065                         {
3066                                 if (index < 0 || index >= list.Count)
3067                                         throw new ArgumentOutOfRangeException ("index");
3068
3069                                 // TODO: Update Column internal index ?
3070                                 list.RemoveAt (index);
3071                                 owner.Redraw (true);
3072                         }
3073                         #endregion      // Public Methods
3074                         
3075
3076                 }       // ColumnHeaderCollection
3077
3078                 public class ListViewItemCollection : IList, ICollection, IEnumerable
3079                 {
3080                         private readonly ArrayList list;
3081                         private readonly ListView owner;
3082
3083                         #region Public Constructor
3084                         public ListViewItemCollection (ListView owner)
3085                         {
3086                                 list = new ArrayList ();
3087                                 this.owner = owner;
3088                         }
3089                         #endregion      // Public Constructor
3090
3091                         #region Public Properties
3092                         [Browsable (false)]
3093                         public int Count {
3094                                 get { return list.Count; }
3095                         }
3096
3097                         public bool IsReadOnly {
3098                                 get { return false; }
3099                         }
3100
3101                         public virtual ListViewItem this [int displayIndex] {
3102                                 get {
3103                                         if (displayIndex < 0 || displayIndex >= list.Count)
3104                                                 throw new ArgumentOutOfRangeException ("displayIndex");
3105                                         return (ListViewItem) list [displayIndex];
3106                                 }
3107
3108                                 set {
3109                                         if (displayIndex < 0 || displayIndex >= list.Count)
3110                                                 throw new ArgumentOutOfRangeException ("displayIndex");
3111
3112                                         if (list.Contains (value))
3113                                                 throw new ArgumentException ("An item cannot be added more than once. To add an item again, you need to clone it.", "value");
3114
3115                                         if (value.ListView != null && value.ListView != owner)
3116                                                 throw new ArgumentException ("Cannot add or insert the item '" + value.Text + "' in more than one place. You must first remove it from its current location or clone it.", "value");
3117
3118                                         value.Owner = owner;
3119                                         list [displayIndex] = value;
3120                                         OnChange ();
3121
3122                                         owner.Redraw (true);
3123                                 }
3124                         }
3125
3126 #if NET_2_0
3127                         public virtual ListViewItem this [string key] {
3128                                 get {
3129                                         int idx = IndexOfKey (key);
3130                                         if (idx == -1)
3131                                                 return null;
3132
3133                                         return (ListViewItem) list [idx];
3134                                 }
3135                         }
3136 #endif
3137
3138                         bool ICollection.IsSynchronized {
3139                                 get { return true; }
3140                         }
3141
3142                         object ICollection.SyncRoot {
3143                                 get { return this; }
3144                         }
3145
3146                         bool IList.IsFixedSize {
3147                                 get { return list.IsFixedSize; }
3148                         }
3149
3150                         object IList.this [int index] {
3151                                 get { return this [index]; }
3152                                 set {
3153                                         if (value is ListViewItem)
3154                                                 this [index] = (ListViewItem) value;
3155                                         else
3156                                                 this [index] = new ListViewItem (value.ToString ());
3157                                         OnChange ();
3158                                 }
3159                         }
3160                         #endregion      // Public Properties
3161
3162                         #region Public Methods
3163                         public virtual ListViewItem Add (ListViewItem value)
3164                         {
3165                                 if (list.Contains (value))
3166                                         throw new ArgumentException ("An item cannot be added more than once. To add an item again, you need to clone it.", "value");
3167
3168                                 if (value.ListView != null && value.ListView != owner)
3169                                         throw new ArgumentException ("Cannot add or insert the item '" + value.Text + "' in more than one place. You must first remove it from its current location or clone it.", "value");
3170
3171                                 value.Owner = owner;
3172                                 list.Add (value);
3173
3174                                 if (this.owner != null)
3175                                 {
3176                                         owner.Sort (false);
3177                                         OnChange ();
3178                                         owner.Redraw (true);
3179                                 }
3180
3181                                 return value;
3182                         }
3183
3184                         public virtual ListViewItem Add (string text)
3185                         {
3186                                 ListViewItem item = new ListViewItem (text);
3187                                 return this.Add (item);
3188                         }
3189
3190                         public virtual ListViewItem Add (string text, int imageIndex)
3191                         {
3192                                 ListViewItem item = new ListViewItem (text, imageIndex);
3193                                 return this.Add (item);
3194                         }
3195
3196 #if NET_2_0
3197                         public virtual ListViewItem Add (string text, string imageKey)
3198                         {
3199                                 ListViewItem item = new ListViewItem (text, imageKey);
3200                                 return this.Add (item);
3201                         }
3202
3203                         public virtual ListViewItem Add (string key, string text, int imageIndex)
3204                         {
3205                                 ListViewItem item = new ListViewItem (text, imageIndex);
3206                                 item.Name = key;
3207                                 return this.Add (item);
3208                         }
3209
3210                         public virtual ListViewItem Add (string key, string text, string imageKey)
3211                         {
3212                                 ListViewItem item = new ListViewItem (text, imageKey);
3213                                 item.Name = key;
3214                                 return this.Add (item);
3215                         }
3216 #endif
3217
3218                         public void AddRange (ListViewItem [] values)
3219                         {
3220                                 if (values == null)
3221                                         throw new ArgumentNullException ("Argument cannot be null!", "values");
3222
3223                                 foreach (ListViewItem item in values) {
3224                                         this.Add (item);
3225                                 }
3226                         }
3227
3228 #if NET_2_0
3229                         public void AddRange (ListViewItemCollection items)
3230                         {
3231                                 if (items == null)
3232                                         throw new ArgumentNullException ("Argument cannot be null!", "items");
3233
3234                                 ListViewItem[] itemArray = new ListViewItem[items.Count];
3235                                 items.CopyTo (itemArray,0);
3236                                 this.AddRange (itemArray);
3237                         }
3238 #endif
3239
3240                         public virtual void Clear ()
3241                         {
3242                                 owner.SetFocusedItem (null);
3243                                 owner.h_scroll.Value = owner.v_scroll.Value = 0;
3244                                 list.Clear ();
3245                                 OnChange ();
3246                                 owner.Redraw (true);
3247                         }
3248
3249                         public bool Contains (ListViewItem item)
3250                         {
3251                                 return list.Contains (item);
3252                         }
3253
3254 #if NET_2_0
3255                         public virtual bool ContainsKey (string key)
3256                         {
3257                                 return IndexOfKey (key) != -1;
3258                         }
3259 #endif
3260
3261                         public void CopyTo (Array dest, int index)
3262                         {
3263                                 list.CopyTo (dest, index);
3264                         }
3265
3266 #if NET_2_0
3267                         public ListViewItem [] Find (string key, bool searchAllSubitems)
3268                         {
3269                                 if (key == null)
3270                                         return new ListViewItem [0];
3271
3272                                 List<ListViewItem> temp_list = new List<ListViewItem> ();
3273                                 
3274                                 for (int i = 0; i < list.Count; i++) {
3275                                         ListViewItem lvi = (ListViewItem) list [i];
3276                                         if (String.Compare (key, lvi.Name, true) == 0)
3277                                                 temp_list.Add (lvi);
3278                                 }
3279
3280                                 ListViewItem [] retval = new ListViewItem [temp_list.Count];
3281                                 temp_list.CopyTo (retval);
3282
3283                                 return retval;
3284                         }
3285 #endif
3286
3287                         public IEnumerator GetEnumerator ()
3288                         {
3289                                 return list.GetEnumerator ();
3290                         }
3291
3292                         int IList.Add (object item)
3293                         {
3294                                 int result;
3295                                 ListViewItem li;
3296
3297                                 if (item is ListViewItem) {
3298                                         li = (ListViewItem) item;
3299                                         if (list.Contains (li))
3300                                                 throw new ArgumentException ("An item cannot be added more than once. To add an item again, you need to clone it.", "item");
3301
3302                                         if (li.ListView != null && li.ListView != owner)
3303                                                 throw new ArgumentException ("Cannot add or insert the item '" + li.Text + "' in more than one place. You must first remove it from its current location or clone it.", "item");
3304                                 }
3305                                 else
3306                                         li = new ListViewItem (item.ToString ());
3307
3308                                 li.Owner = owner;
3309                                 result = list.Add (li);
3310                                 OnChange ();
3311                                 owner.Redraw (true);
3312
3313                                 return result;
3314                         }
3315
3316                         bool IList.Contains (object item)
3317                         {
3318                                 return list.Contains (item);
3319                         }
3320
3321                         int IList.IndexOf (object item)
3322                         {
3323                                 return list.IndexOf (item);
3324                         }
3325
3326                         void IList.Insert (int index, object item)
3327                         {
3328                                 if (item is ListViewItem)
3329                                         this.Insert (index, (ListViewItem) item);
3330                                 else
3331                                         this.Insert (index, item.ToString ());
3332                         }
3333
3334                         void IList.Remove (object item)
3335                         {
3336                                 Remove ((ListViewItem) item);
3337                         }
3338
3339                         public int IndexOf (ListViewItem item)
3340                         {
3341                                 return list.IndexOf (item);
3342                         }
3343
3344 #if NET_2_0
3345                         public int IndexOfKey (string key)
3346                         {
3347                                 if (key == null || key.Length == 0)
3348                                         return -1;
3349
3350                                 for (int i = 0; i < list.Count; i++) {
3351                                         ListViewItem lvi = (ListViewItem) list [i];
3352                                         if (String.Compare (key, lvi.Name, true) == 0)
3353                                                 return i;
3354                                 }
3355
3356                                 return -1;
3357                         }
3358 #endif
3359
3360                         public ListViewItem Insert (int index, ListViewItem item)
3361                         {
3362                                 if (index < 0 || index > list.Count)
3363                                         throw new ArgumentOutOfRangeException ("index");
3364
3365                                 if (list.Contains (item))
3366                                         throw new ArgumentException ("An item cannot be added more than once. To add an item again, you need to clone it.", "item");
3367
3368                                 if (item.ListView != null && item.ListView != owner)
3369                                         throw new ArgumentException ("Cannot add or insert the item '" + item.Text + "' in more than one place. You must first remove it from its current location or clone it.", "item");
3370
3371                                 item.Owner = owner;
3372                                 list.Insert (index, item);
3373                                 OnChange ();
3374                                 owner.Redraw (true);
3375                                 return item;
3376                         }
3377
3378                         public ListViewItem Insert (int index, string text)
3379                         {
3380                                 return this.Insert (index, new ListViewItem (text));
3381                         }
3382
3383                         public ListViewItem Insert (int index, string text, int imageIndex)
3384                         {
3385                                 return this.Insert (index, new ListViewItem (text, imageIndex));
3386                         }
3387
3388 #if NET_2_0
3389                         public ListViewItem Insert (int index, string key, string text, int imageIndex)
3390                         {
3391                                 ListViewItem lvi = new ListViewItem (text, imageIndex);
3392                                 lvi.Name = key;
3393                                 return Insert (index, lvi);
3394                         }
3395 #endif
3396
3397                         public virtual void Remove (ListViewItem item)
3398                         {
3399                                 if (!list.Contains (item))
3400                                         return;
3401                                         
3402                                 bool selection_changed = owner.SelectedItems.Contains (item);
3403                                 list.Remove (item);
3404                                 OnChange ();
3405                                 owner.Redraw (true);                            
3406                                 if (selection_changed)
3407                                         owner.OnSelectedIndexChanged (EventArgs.Empty);
3408                         }
3409
3410                         public virtual void RemoveAt (int index)
3411                         {
3412                                 if (index < 0 || index >= Count)
3413                                         throw new ArgumentOutOfRangeException ("index");
3414                                 bool selection_changed = owner.SelectedIndices.Contains (index);
3415                                 list.RemoveAt (index);
3416                                 OnChange ();
3417                                 owner.Redraw (false);
3418                                 if (selection_changed)
3419                                         owner.OnSelectedIndexChanged (EventArgs.Empty);
3420                         }
3421
3422 #if NET_2_0
3423                         public void RemoveByKey (string key)
3424                         {
3425                                 int idx = IndexOfKey (key);
3426                                 if (idx != -1)
3427                                         RemoveAt (idx);
3428                         }
3429 #endif
3430
3431                         #endregion      // Public Methods
3432
3433                         internal event CollectionChangedHandler Changed;
3434
3435                         internal void Sort (IComparer comparer)
3436                         {
3437                                 list.Sort (comparer);
3438                                 OnChange ();
3439                         }
3440
3441                         internal void OnChange ()
3442                         {
3443                                 if (Changed != null)
3444                                         Changed ();
3445                         }
3446                 }       // ListViewItemCollection
3447
3448                 public class SelectedIndexCollection : IList, ICollection, IEnumerable
3449                 {
3450                         private readonly ListView owner;
3451
3452                         #region Public Constructor
3453                         public SelectedIndexCollection (ListView owner)
3454                         {
3455                                 this.owner = owner;
3456                         }
3457                         #endregion      // Public Constructor
3458
3459                         #region Public Properties
3460                         [Browsable (false)]
3461                         public int Count {
3462                                 get {
3463                                         return owner.SelectedItems.Count;
3464                                 }
3465                         }
3466
3467                         public bool IsReadOnly {
3468                                 get { 
3469 #if NET_2_0
3470                                         return false;
3471 #else
3472                                         return true; 
3473 #endif
3474                                 }
3475                         }
3476
3477                         public int this [int index] {
3478                                 get {
3479                                         int [] indices = GetIndices ();
3480                                         if (index < 0 || index >= indices.Length)
3481                                                 throw new ArgumentOutOfRangeException ("index");
3482                                         return indices [index];
3483                                 }
3484                         }
3485
3486                         bool ICollection.IsSynchronized {
3487                                 get { return false; }
3488                         }
3489
3490                         object ICollection.SyncRoot {
3491                                 get { return this; }
3492                         }
3493
3494                         bool IList.IsFixedSize {
3495                                 get { 
3496 #if NET_2_0
3497                                         return false;
3498 #else
3499                                         return true;
3500 #endif
3501                                 }
3502                         }
3503
3504                         object IList.this [int index] {
3505                                 get { return this [index]; }
3506                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
3507                         }
3508                         #endregion      // Public Properties
3509
3510                         #region Public Methods
3511 #if NET_2_0
3512                         public int Add (int itemIndex)
3513                         {
3514                                 if (itemIndex < 0 || itemIndex >= owner.Items.Count)
3515                                         throw new ArgumentOutOfRangeException ("index");
3516
3517                                 owner.Items [itemIndex].Selected = true;
3518                                 if (!owner.IsHandleCreated)
3519                                         return 0;
3520
3521                                 return owner.SelectedItems.Count;
3522                         }
3523
3524                         public void Clear ()
3525                         {
3526                                 owner.SelectedItems.Clear ();
3527                         }
3528 #endif
3529                         public bool Contains (int selectedIndex)
3530                         {
3531                                 int [] indices = GetIndices ();
3532                                 for (int i = 0; i < indices.Length; i++) {
3533                                         if (indices [i] == selectedIndex)
3534                                                 return true;
3535                                 }
3536                                 return false;
3537                         }
3538
3539                         public void CopyTo (Array dest, int index)
3540                         {
3541                                 int [] indices = GetIndices ();
3542                                 Array.Copy (indices, 0, dest, index, indices.Length);
3543                         }
3544
3545                         public IEnumerator GetEnumerator ()
3546                         {
3547                                 int [] indices = GetIndices ();
3548                                 return indices.GetEnumerator ();
3549                         }
3550
3551                         int IList.Add (object value)
3552                         {
3553                                 throw new NotSupportedException ("Add operation is not supported.");
3554                         }
3555
3556                         void IList.Clear ()
3557                         {
3558                                 throw new NotSupportedException ("Clear operation is not supported.");
3559                         }
3560
3561                         bool IList.Contains (object selectedIndex)
3562                         {
3563                                 if (!(selectedIndex is int))
3564                                         return false;
3565                                 return Contains ((int) selectedIndex);
3566                         }
3567
3568                         int IList.IndexOf (object selectedIndex)
3569                         {
3570                                 if (!(selectedIndex is int))
3571                                         return -1;
3572                                 return IndexOf ((int) selectedIndex);
3573                         }
3574
3575                         void IList.Insert (int index, object value)
3576                         {
3577                                 throw new NotSupportedException ("Insert operation is not supported.");
3578                         }
3579
3580                         void IList.Remove (object value)
3581                         {
3582                                 throw new NotSupportedException ("Remove operation is not supported.");
3583                         }
3584
3585                         void IList.RemoveAt (int index)
3586                         {
3587                                 throw new NotSupportedException ("RemoveAt operation is not supported.");
3588                         }
3589
3590                         public int IndexOf (int selectedIndex)
3591                         {
3592                                 int [] indices = GetIndices ();
3593                                 for (int i = 0; i < indices.Length; i++) {
3594                                         if (indices [i] == selectedIndex)
3595                                                 return i;
3596                                 }
3597                                 return -1;
3598                         }
3599
3600 #if NET_2_0
3601                         public void Remove (int itemIndex)
3602                         {
3603                                 if (itemIndex < 0 || itemIndex >= owner.Items.Count)
3604                                         throw new ArgumentOutOfRangeException ("itemIndex");
3605
3606                                 owner.Items [itemIndex].Selected = false;
3607                         }
3608 #endif
3609                         #endregion      // Public Methods
3610
3611                         private int [] GetIndices ()
3612                         {
3613                                 ArrayList selected_items = owner.SelectedItems.List;
3614                                 int [] indices = new int [selected_items.Count];
3615                                 for (int i = 0; i < selected_items.Count; i++) {
3616                                         ListViewItem item = (ListViewItem) selected_items [i];
3617                                         indices [i] = item.Index;
3618                                 }
3619                                 return indices;
3620                         }
3621                 }       // SelectedIndexCollection
3622
3623                 public class SelectedListViewItemCollection : IList, ICollection, IEnumerable
3624                 {
3625                         private readonly ListView owner;
3626                         private ArrayList list;
3627
3628                         #region Public Constructor
3629                         public SelectedListViewItemCollection (ListView owner)
3630                         {
3631                                 this.owner = owner;
3632                                 this.owner.Items.Changed += new CollectionChangedHandler (
3633                                         ItemsCollection_Changed);
3634                         }
3635                         #endregion      // Public Constructor
3636
3637                         #region Public Properties
3638                         [Browsable (false)]
3639                         public int Count {
3640                                 get {
3641                                         if (!owner.IsHandleCreated)
3642                                                 return 0;
3643                                         return List.Count;
3644                                 }
3645                         }
3646
3647                         public bool IsReadOnly {
3648                                 get { return true; }
3649                         }
3650
3651                         public ListViewItem this [int index] {
3652                                 get {
3653                                         ArrayList selected_items = List;
3654                                         if (!owner.IsHandleCreated || index < 0 || index >= selected_items.Count)
3655                                                 throw new ArgumentOutOfRangeException ("index");
3656                                         return (ListViewItem) selected_items [index];
3657                                 }
3658                         }
3659
3660 #if NET_2_0
3661                         public ListViewItem this [string key] {
3662                                 get {
3663                                         int idx = IndexOfKey (key);
3664                                         if (idx == -1)
3665                                                 return null;
3666
3667                                         return (ListViewItem) List [idx];
3668                                 }
3669                         }
3670 #endif
3671
3672                         bool ICollection.IsSynchronized {
3673                                 get { return false; }
3674                         }
3675
3676                         object ICollection.SyncRoot {
3677                                 get { return this; }
3678                         }
3679
3680                         bool IList.IsFixedSize {
3681                                 get { return true; }
3682                         }
3683
3684                         object IList.this [int index] {
3685                                 get { return this [index]; }
3686                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
3687                         }
3688                         #endregion      // Public Properties
3689
3690                         #region Public Methods
3691                         public void Clear ()
3692                         {
3693                                 if (!owner.IsHandleCreated)
3694                                         return;
3695
3696                                 foreach (ListViewItem item in List)
3697                                         item.Selected = false;
3698                         }
3699
3700                         public bool Contains (ListViewItem item)
3701                         {
3702                                 if (!owner.IsHandleCreated)
3703                                         return false;
3704                                 return List.Contains (item);
3705                         }
3706
3707 #if NET_2_0
3708                         public bool ContainsKey (string key)
3709                         {
3710                                 return IndexOfKey (key) != -1;
3711                         }
3712 #endif
3713
3714                         public void CopyTo (Array dest, int index)
3715                         {
3716                                 if (!owner.IsHandleCreated)
3717                                         return;
3718                                 List.CopyTo (dest, index);
3719                         }
3720
3721                         public IEnumerator GetEnumerator ()
3722                         {
3723                                 if (!owner.IsHandleCreated)
3724                                         return (new ListViewItem [0]).GetEnumerator ();
3725                                 return List.GetEnumerator ();
3726                         }
3727
3728                         int IList.Add (object value)
3729                         {
3730                                 throw new NotSupportedException ("Add operation is not supported.");
3731                         }
3732
3733                         bool IList.Contains (object item)
3734                         {
3735                                 if (!(item is ListViewItem))
3736                                         return false;
3737                                 return Contains ((ListViewItem) item);
3738                         }
3739
3740                         int IList.IndexOf (object item)
3741                         {
3742                                 if (!(item is ListViewItem))
3743                                         return -1;
3744                                 return IndexOf ((ListViewItem) item);
3745                         }
3746
3747                         void IList.Insert (int index, object value)
3748                         {
3749                                 throw new NotSupportedException ("Insert operation is not supported.");
3750                         }
3751
3752                         void IList.Remove (object value)
3753                         {
3754                                 throw new NotSupportedException ("Remove operation is not supported.");
3755                         }
3756
3757                         void IList.RemoveAt (int index)
3758                         {
3759                                 throw new NotSupportedException ("RemoveAt operation is not supported.");
3760                         }
3761
3762                         public int IndexOf (ListViewItem item)
3763                         {
3764                                 if (!owner.IsHandleCreated)
3765                                         return -1;
3766                                 return List.IndexOf (item);
3767                         }
3768
3769 #if NET_2_0
3770                         public virtual int IndexOfKey (string key)
3771                         {
3772                                 if (!owner.IsHandleCreated || key == null || key.Length == 0)
3773                                         return -1;
3774
3775                                 ArrayList selected_items = List;
3776                                 for (int i = 0; i < selected_items.Count; i++) {
3777                                         ListViewItem item = (ListViewItem) selected_items [i];
3778                                         if (String.Compare (item.Name, key, true) == 0)
3779                                                 return i;
3780                                 }
3781
3782                                 return -1;
3783                         }
3784 #endif
3785                         #endregion      // Public Methods
3786
3787                         internal ArrayList List {
3788                                 get {
3789                                         if (list == null) {
3790                                                 list = new ArrayList ();
3791                                                 foreach (ListViewItem item in owner.Items) {
3792                                                         if (item.Selected)
3793                                                                 list.Add (item);
3794                                                 }
3795                                         }
3796                                         return list;
3797                                 }
3798                         }
3799
3800                         internal void Reset ()
3801                         {
3802                                 // force re-population of list
3803                                 list = null;
3804                         }
3805
3806                         private void ItemsCollection_Changed ()
3807                         {
3808                                 Reset ();
3809                         }
3810                 }       // SelectedListViewItemCollection
3811
3812                 internal delegate void CollectionChangedHandler ();
3813
3814                 #endregion // Subclasses
3815 #if NET_2_0
3816                 protected override void OnResize (EventArgs e)
3817                 {
3818                         base.OnResize (e);
3819                 }
3820
3821                 protected override void OnMouseLeave (EventArgs e)
3822                 {
3823                         base.OnMouseLeave (e);
3824                 }
3825
3826                 //
3827                 // ColumnReorder event
3828                 //
3829                 static object ColumnReorderedEvent = new object ();
3830                 public event ColumnReorderedEventHandler ColumnReordered {
3831                         add { Events.AddHandler (ColumnReorderedEvent, value); }
3832                         remove { Events.RemoveHandler (ColumnReorderedEvent, value); }
3833                 }
3834
3835                 protected virtual void OnColumnReordered (ColumnReorderedEventArgs e)
3836                 {
3837                         ColumnReorderedEventHandler creh = (ColumnReorderedEventHandler) (Events [ColumnReorderedEvent]);
3838
3839                         if (creh != null)
3840                                 creh (this, e);
3841                 }
3842 #endif
3843         }
3844 }