2008-02-04 Carlos Alberto Cortez <calberto.cortez@gmail.com>
[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 //      Carlos Alberto Cortez <calberto.cortez@gmail.com>
28 //
29
30
31 // NOT COMPLETE
32
33
34 using System.Collections;
35 using System.ComponentModel;
36 using System.ComponentModel.Design;
37 using System.Drawing;
38 using System.Runtime.InteropServices;
39 using System.Globalization;
40 #if NET_2_0
41 using System.Collections.Generic;
42 #endif
43
44 namespace System.Windows.Forms
45 {
46         [DefaultEvent ("SelectedIndexChanged")]
47         [DefaultProperty ("Items")]
48         [Designer ("System.Windows.Forms.Design.ListViewDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
49 #if NET_2_0
50         [ClassInterface (ClassInterfaceType.AutoDispatch)]
51         [ComVisible (true)]
52         [Docking (DockingBehavior.Ask)]
53 #endif
54         public class ListView : Control
55         {
56                 private ItemActivation activation = ItemActivation.Standard;
57                 private ListViewAlignment alignment = ListViewAlignment.Top;
58                 private bool allow_column_reorder;
59                 private bool auto_arrange = true;
60                 private bool check_boxes;
61                 private readonly CheckedIndexCollection checked_indices;
62                 private readonly CheckedListViewItemCollection checked_items;
63                 private readonly ColumnHeaderCollection columns;
64                 internal int focused_item_index = -1;
65                 private bool full_row_select;
66                 private bool grid_lines;
67                 private ColumnHeaderStyle header_style = ColumnHeaderStyle.Clickable;
68                 private bool hide_selection = true;
69                 private bool hover_selection;
70                 private IComparer item_sorter;
71                 private readonly ListViewItemCollection items;
72 #if NET_2_0
73                 private readonly ListViewGroupCollection groups;
74                 private bool owner_draw;
75                 private bool show_groups = true;
76 #endif
77                 private bool label_edit;
78                 private bool label_wrap = true;
79                 private bool multiselect = true;
80                 private bool scrollable = true;
81                 private bool hover_pending;
82                 private readonly SelectedIndexCollection selected_indices;
83                 private readonly SelectedListViewItemCollection selected_items;
84                 private SortOrder sort_order = SortOrder.None;
85                 private ImageList state_image_list;
86                 internal bool updating;
87                 private View view = View.LargeIcon;
88                 private int layout_wd;    // We might draw more than our client area
89                 private int layout_ht;    // therefore we need to have these two.
90                 HeaderControl header_control;
91                 internal ItemControl item_control;
92                 internal ScrollBar h_scroll; // used for scrolling horizontally
93                 internal ScrollBar v_scroll; // used for scrolling vertically
94                 internal int h_marker;          // Position markers for scrolling
95                 internal int v_marker;
96                 private int keysearch_tickcnt;
97                 private string keysearch_text;
98                 static private readonly int keysearch_keydelay = 1000;
99                 private int[] reordered_column_indices;
100                 private int[] reordered_items_indices;
101                 private Point [] items_location;
102                 private ItemMatrixLocation [] items_matrix_location;
103                 private Size item_size; // used for caching item size
104                 private int hot_item_index = -1;
105 #if NET_2_0
106                 private bool hot_tracking;
107                 private ListViewInsertionMark insertion_mark;
108                 private bool show_item_tooltips;
109                 private ToolTip item_tooltip;
110                 private Size tile_size;
111                 private bool virtual_mode;
112                 private int virtual_list_size;
113                 private bool right_to_left_layout;
114 #endif
115
116                 // internal variables
117                 internal ImageList large_image_list;
118                 internal ImageList small_image_list;
119                 internal Size text_size = Size.Empty;
120
121                 #region Events
122                 static object AfterLabelEditEvent = new object ();
123                 static object BeforeLabelEditEvent = new object ();
124                 static object ColumnClickEvent = new object ();
125                 static object ItemActivateEvent = new object ();
126                 static object ItemCheckEvent = new object ();
127                 static object ItemDragEvent = new object ();
128                 static object SelectedIndexChangedEvent = new object ();
129 #if NET_2_0
130                 static object DrawColumnHeaderEvent = new object();
131                 static object DrawItemEvent = new object();
132                 static object DrawSubItemEvent = new object();
133                 static object ItemCheckedEvent = new object ();
134                 static object ItemMouseHoverEvent = new object ();
135                 static object ItemSelectionChangedEvent = new object ();
136                 static object CacheVirtualItemsEvent = new object ();
137                 static object RetrieveVirtualItemEvent = new object ();
138                 static object RightToLeftLayoutChangedEvent = new object ();
139                 static object SearchForVirtualItemEvent = new object ();
140                 static object VirtualItemsSelectionRangeChangedEvent = new object ();
141 #endif
142
143                 public event LabelEditEventHandler AfterLabelEdit {
144                         add { Events.AddHandler (AfterLabelEditEvent, value); }
145                         remove { Events.RemoveHandler (AfterLabelEditEvent, value); }
146                 }
147
148 #if !NET_2_0
149                 [Browsable (false)]
150                 [EditorBrowsable (EditorBrowsableState.Never)]
151                 public new event EventHandler BackgroundImageChanged {
152                         add { base.BackgroundImageChanged += value; }
153                         remove { base.BackgroundImageChanged -= value; }
154                 }
155 #endif
156
157 #if NET_2_0
158                 [Browsable (false)]
159                 [EditorBrowsable (EditorBrowsableState.Never)]
160                 public new event EventHandler BackgroundImageLayoutChanged {
161                         add { base.BackgroundImageLayoutChanged += value; }
162                         remove { base.BackgroundImageLayoutChanged -= value; }
163                 }
164 #endif
165
166                 public event LabelEditEventHandler BeforeLabelEdit {
167                         add { Events.AddHandler (BeforeLabelEditEvent, value); }
168                         remove { Events.RemoveHandler (BeforeLabelEditEvent, value); }
169                 }
170
171                 public event ColumnClickEventHandler ColumnClick {
172                         add { Events.AddHandler (ColumnClickEvent, value); }
173                         remove { Events.RemoveHandler (ColumnClickEvent, value); }
174                 }
175
176 #if NET_2_0
177                 public event DrawListViewColumnHeaderEventHandler DrawColumnHeader {
178                         add { Events.AddHandler(DrawColumnHeaderEvent, value); }
179                         remove { Events.RemoveHandler(DrawColumnHeaderEvent, value); }
180                 }
181
182                 public event DrawListViewItemEventHandler DrawItem {
183                         add { Events.AddHandler(DrawItemEvent, value); }
184                         remove { Events.RemoveHandler(DrawItemEvent, value); }
185                 }
186
187                 public event DrawListViewSubItemEventHandler DrawSubItem {
188                         add { Events.AddHandler(DrawSubItemEvent, value); }
189                         remove { Events.RemoveHandler(DrawSubItemEvent, value); }
190                 }
191 #endif
192
193                 public event EventHandler ItemActivate {
194                         add { Events.AddHandler (ItemActivateEvent, value); }
195                         remove { Events.RemoveHandler (ItemActivateEvent, value); }
196                 }
197
198                 public event ItemCheckEventHandler ItemCheck {
199                         add { Events.AddHandler (ItemCheckEvent, value); }
200                         remove { Events.RemoveHandler (ItemCheckEvent, value); }
201                 }
202
203 #if NET_2_0
204                 public event ItemCheckedEventHandler ItemChecked {
205                         add { Events.AddHandler (ItemCheckedEvent, value); }
206                         remove { Events.RemoveHandler (ItemCheckedEvent, value); }
207                 }
208 #endif
209
210                 public event ItemDragEventHandler ItemDrag {
211                         add { Events.AddHandler (ItemDragEvent, value); }
212                         remove { Events.RemoveHandler (ItemDragEvent, value); }
213                 }
214
215 #if NET_2_0
216                 public event ListViewItemMouseHoverEventHandler ItemMouseHover {
217                         add { Events.AddHandler (ItemMouseHoverEvent, value); }
218                         remove { Events.RemoveHandler (ItemMouseHoverEvent, value); }
219                 }
220
221                 public event ListViewItemSelectionChangedEventHandler ItemSelectionChanged {
222                         add { Events.AddHandler (ItemSelectionChangedEvent, value); }
223                         remove { Events.RemoveHandler (ItemSelectionChangedEvent, value); }
224                 }
225
226                 [Browsable (false)]
227                 [EditorBrowsable (EditorBrowsableState.Never)]
228                 public new event EventHandler PaddingChanged {
229                         add { base.PaddingChanged += value; }
230                         remove { base.PaddingChanged -= value; }
231                 }
232 #endif
233
234                 [Browsable (false)]
235                 [EditorBrowsable (EditorBrowsableState.Never)]
236                 public new event PaintEventHandler Paint {
237                         add { base.Paint += value; }
238                         remove { base.Paint -= value; }
239                 }
240
241                 public event EventHandler SelectedIndexChanged {
242                         add { Events.AddHandler (SelectedIndexChangedEvent, value); }
243                         remove { Events.RemoveHandler (SelectedIndexChangedEvent, value); }
244                 }
245
246                 [Browsable (false)]
247                 [EditorBrowsable (EditorBrowsableState.Never)]
248                 public new event EventHandler TextChanged {
249                         add { base.TextChanged += value; }
250                         remove { base.TextChanged -= value; }
251                 }
252
253 #if NET_2_0
254                 public event CacheVirtualItemsEventHandler CacheVirtualItems {
255                         add { Events.AddHandler (CacheVirtualItemsEvent, value); }
256                         remove { Events.RemoveHandler (CacheVirtualItemsEvent, value); }
257                 }
258
259                 public event RetrieveVirtualItemEventHandler RetrieveVirtualItem {
260                         add { Events.AddHandler (RetrieveVirtualItemEvent, value); }
261                         remove { Events.RemoveHandler (RetrieveVirtualItemEvent, value); }
262                 }
263
264                 public event EventHandler RightToLeftLayoutChanged {
265                         add { Events.AddHandler (RightToLeftLayoutChangedEvent, value); }
266                         remove { Events.RemoveHandler (RightToLeftLayoutChangedEvent, value); }
267                 }
268
269                 public event SearchForVirtualItemEventHandler SearchForVirtualItem {
270                         add { Events.AddHandler (SearchForVirtualItemEvent, value); }
271                         remove { Events.AddHandler (SearchForVirtualItemEvent, value); }
272                 }
273                 
274                 public event ListViewVirtualItemsSelectionRangeChangedEventHandler VirtualItemsSelectionRangeChanged {
275                         add { Events.AddHandler (VirtualItemsSelectionRangeChangedEvent, value); }
276                         remove { Events.RemoveHandler (VirtualItemsSelectionRangeChangedEvent, value); }
277                 }
278 #endif
279
280                 #endregion // Events
281
282                 #region Public Constructors
283                 public ListView ()
284                 {
285                         background_color = ThemeEngine.Current.ColorWindow;
286 #if NET_2_0
287                         groups = new ListViewGroupCollection (this);
288 #endif
289                         items = new ListViewItemCollection (this);
290                         checked_indices = new CheckedIndexCollection (this);
291                         checked_items = new CheckedListViewItemCollection (this);
292                         columns = new ColumnHeaderCollection (this);
293                         foreground_color = SystemColors.WindowText;
294                         selected_indices = new SelectedIndexCollection (this);
295                         selected_items = new SelectedListViewItemCollection (this);
296                         items_location = new Point [16];
297                         items_matrix_location = new ItemMatrixLocation [16];
298                         reordered_items_indices = new int [16];
299 #if NET_2_0
300                         item_tooltip = new ToolTip ();
301                         item_tooltip.Active = false;
302                         insertion_mark = new ListViewInsertionMark (this);
303 #endif
304
305                         InternalBorderStyle = BorderStyle.Fixed3D;
306
307                         header_control = new HeaderControl (this);
308                         header_control.Visible = false;
309                         Controls.AddImplicit (header_control);
310
311                         item_control = new ItemControl (this);
312                         Controls.AddImplicit (item_control);
313
314                         h_scroll = new ImplicitHScrollBar ();
315                         Controls.AddImplicit (this.h_scroll);
316
317                         v_scroll = new ImplicitVScrollBar ();
318                         Controls.AddImplicit (this.v_scroll);
319
320                         h_marker = v_marker = 0;
321                         keysearch_tickcnt = 0;
322
323                         // scroll bars are disabled initially
324                         h_scroll.Visible = false;
325                         h_scroll.ValueChanged += new EventHandler(HorizontalScroller);
326                         v_scroll.Visible = false;
327                         v_scroll.ValueChanged += new EventHandler(VerticalScroller);
328
329                         // event handlers
330                         base.KeyDown += new KeyEventHandler(ListView_KeyDown);
331                         SizeChanged += new EventHandler (ListView_SizeChanged);
332                         GotFocus += new EventHandler (FocusChanged);
333                         LostFocus += new EventHandler (FocusChanged);
334                         MouseWheel += new MouseEventHandler(ListView_MouseWheel);
335                         MouseEnter += new EventHandler (ListView_MouseEnter);
336
337 #if NET_2_0
338                         BackgroundImageTiled = false;
339 #endif
340
341                         this.SetStyle (ControlStyles.UserPaint | ControlStyles.StandardClick
342 #if NET_2_0
343                                 | ControlStyles.UseTextForAccessibility
344 #endif
345                                 , false);
346                 }
347                 #endregion      // Public Constructors
348
349                 #region Private Internal Properties
350                 internal Size CheckBoxSize {
351                         get {
352                                 if (this.check_boxes) {
353                                         if (this.state_image_list != null)
354                                                 return this.state_image_list.ImageSize;
355                                         else
356                                                 return ThemeEngine.Current.ListViewCheckBoxSize;
357                                 }
358                                 return Size.Empty;
359                         }
360                 }
361
362                 internal Size ItemSize {
363                         get {
364                                 if (view != View.Details)
365                                         return item_size;
366
367                                 Size size = new Size ();
368                                 size.Height = item_size.Height;
369                                 for (int i = 0; i < columns.Count; i++)
370                                         size.Width += columns [i].Wd;
371
372                                 return size;
373                         }
374                         set {
375                                 item_size = value;
376                         }
377                 }
378
379                 internal int HotItemIndex {
380                         get {
381                                 return hot_item_index;
382                         }
383                         set {
384                                 hot_item_index = value;
385                         }
386                 }
387
388                 #endregion      // Private Internal Properties
389
390                 #region  Protected Properties
391                 protected override CreateParams CreateParams {
392                         get { return base.CreateParams; }
393                 }
394
395                 protected override Size DefaultSize {
396                         get { return ThemeEngine.Current.ListViewDefaultSize; }
397                 }
398 #if NET_2_0
399                 protected override bool DoubleBuffered {
400                         get {
401                                 return base.DoubleBuffered;
402                         }
403                         set {
404                                 base.DoubleBuffered = value;
405                         }
406                 }
407 #endif
408                 #endregion      // Protected Properties
409
410                 #region Public Instance Properties
411                 [DefaultValue (ItemActivation.Standard)]
412                 public ItemActivation Activation {
413                         get { return activation; }
414                         set { 
415                                 if (value != ItemActivation.Standard && value != ItemActivation.OneClick && 
416                                         value != ItemActivation.TwoClick) {
417                                         throw new InvalidEnumArgumentException (string.Format
418                                                 ("Enum argument value '{0}' is not valid for Activation", value));
419                                 }
420 #if NET_2_0
421                                 if (hot_tracking && value != ItemActivation.OneClick)
422                                         throw new ArgumentException ("When HotTracking is on, activation must be ItemActivation.OneClick");
423 #endif
424                                 
425                                 activation = value;
426                         }
427                 }
428
429                 [DefaultValue (ListViewAlignment.Top)]
430                 [Localizable (true)]
431                 public ListViewAlignment Alignment {
432                         get { return alignment; }
433                         set {
434                                 if (value != ListViewAlignment.Default && value != ListViewAlignment.Left && 
435                                         value != ListViewAlignment.SnapToGrid && value != ListViewAlignment.Top) {
436                                         throw new InvalidEnumArgumentException (string.Format 
437                                                 ("Enum argument value '{0}' is not valid for Alignment", value));
438                                 }
439                                 
440                                 if (this.alignment != value) {
441                                         alignment = value;
442                                         // alignment does not matter in Details/List views
443                                         if (this.view == View.LargeIcon || this.View == View.SmallIcon)
444                                                 this.Redraw (true);
445                                 }
446                         }
447                 }
448
449                 [DefaultValue (false)]
450                 public bool AllowColumnReorder {
451                         get { return allow_column_reorder; }
452                         set { allow_column_reorder = value; }
453                 }
454
455                 [DefaultValue (true)]
456                 public bool AutoArrange {
457                         get { return auto_arrange; }
458                         set {
459                                 if (auto_arrange != value) {
460                                         auto_arrange = value;
461                                         // autoarrange does not matter in Details/List views
462                                         if (this.view == View.LargeIcon || this.View == View.SmallIcon)
463                                                 this.Redraw (true);
464                                 }
465                         }
466                 }
467
468                 public override Color BackColor {
469                         get {
470                                 if (background_color.IsEmpty)
471                                         return ThemeEngine.Current.ColorWindow;
472                                 else
473                                         return background_color;
474                         }
475                         set { 
476                                 background_color = value;
477                                 item_control.BackColor = value;
478                         }
479                 }
480
481 #if !NET_2_0
482                 [Browsable (false)]
483                 [EditorBrowsable (EditorBrowsableState.Never)]
484                 public override Image BackgroundImage {
485                         get { return base.BackgroundImage; }
486                         set { base.BackgroundImage = value; }
487                 }
488 #endif
489
490 #if NET_2_0
491                 [Browsable (false)]
492                 [EditorBrowsable (EditorBrowsableState.Never)]
493                 public override ImageLayout BackgroundImageLayout {
494                         get {
495                                 return base.BackgroundImageLayout;
496                         }
497                         set {
498                                 base.BackgroundImageLayout = value;
499                         }
500                 }
501
502                 [DefaultValue (false)]
503                 public bool BackgroundImageTiled {
504                         get {
505                                 return item_control.BackgroundImageLayout == ImageLayout.Tile;
506                         }
507                         set {
508                                 ImageLayout new_image_layout = value ? ImageLayout.Tile : ImageLayout.None;
509                                 if (new_image_layout == item_control.BackgroundImageLayout)
510                                         return;
511
512                                 item_control.BackgroundImageLayout = new_image_layout;
513                         }
514                 }
515 #endif
516
517                 [DefaultValue (BorderStyle.Fixed3D)]
518                 [DispId (-504)]
519                 public BorderStyle BorderStyle {
520                         get { return InternalBorderStyle; }
521                         set { InternalBorderStyle = value; }
522                 }
523
524                 [DefaultValue (false)]
525                 public bool CheckBoxes {
526                         get { return check_boxes; }
527                         set {
528                                 if (check_boxes != value) {
529 #if NET_2_0
530                                         if (value && View == View.Tile)
531                                                 throw new NotSupportedException ("CheckBoxes are not"
532                                                         + " supported in Tile view. Choose a different"
533                                                         + " view or set CheckBoxes to false.");
534 #endif
535
536                                         check_boxes = value;
537                                         this.Redraw (true);
538                                 }
539                         }
540                 }
541
542                 [Browsable (false)]
543                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
544                 public CheckedIndexCollection CheckedIndices {
545                         get { return checked_indices; }
546                 }
547
548                 [Browsable (false)]
549                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
550                 public CheckedListViewItemCollection CheckedItems {
551                         get { return checked_items; }
552                 }
553
554 #if NET_2_0
555                 [Editor ("System.Windows.Forms.Design.ColumnHeaderCollectionEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))]
556 #endif
557                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
558                 [Localizable (true)]
559                 [MergableProperty (false)]
560                 public ColumnHeaderCollection Columns {
561                         get { return columns; }
562                 }
563
564                 [Browsable (false)]
565                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
566                 public ListViewItem FocusedItem {
567                         get {
568                                 if (focused_item_index == -1)
569                                         return null;
570
571                                 return items [focused_item_index];
572                         }
573 #if NET_2_0
574                         set {
575                                 if (value == null || value.ListView != this || 
576                                                 !IsHandleCreated)
577                                         return;
578
579                                 SetFocusedItem (value.Index);
580                         }
581 #endif
582                 }
583
584                 public override Color ForeColor {
585                         get {
586                                 if (foreground_color.IsEmpty)
587                                         return ThemeEngine.Current.ColorWindowText;
588                                 else
589                                         return foreground_color;
590                         }
591                         set { foreground_color = value; }
592                 }
593
594                 [DefaultValue (false)]
595                 public bool FullRowSelect {
596                         get { return full_row_select; }
597                         set { 
598                                 if (full_row_select != value) {
599                                         full_row_select = value;
600                                         InvalidateSelection ();
601                                 }
602                         }
603                 }
604
605                 [DefaultValue (false)]
606                 public bool GridLines {
607                         get { return grid_lines; }
608                         set {
609                                 if (grid_lines != value) {
610                                         grid_lines = value;
611                                         this.Redraw (false);
612                                 }
613                         }
614                 }
615
616                 [DefaultValue (ColumnHeaderStyle.Clickable)]
617                 public ColumnHeaderStyle HeaderStyle {
618                         get { return header_style; }
619                         set {
620                                 if (header_style == value)
621                                         return;
622
623                                 switch (value) {
624                                 case ColumnHeaderStyle.Clickable:
625                                 case ColumnHeaderStyle.Nonclickable:
626                                 case ColumnHeaderStyle.None:
627                                         break;
628                                 default:
629                                         throw new InvalidEnumArgumentException (string.Format 
630                                                 ("Enum argument value '{0}' is not valid for ColumnHeaderStyle", value));
631                                 }
632                                 
633                                 header_style = value;
634                                 if (view == View.Details)
635                                         Redraw (true);
636                         }
637                 }
638
639                 [DefaultValue (true)]
640                 public bool HideSelection {
641                         get { return hide_selection; }
642                         set {
643                                 if (hide_selection != value) {
644                                         hide_selection = value;
645                                         InvalidateSelection ();
646                                 }
647                         }
648                 }
649
650 #if NET_2_0
651                 [DefaultValue (false)]
652                 public bool HotTracking {
653                         get {
654                                 return hot_tracking;
655                         }
656                         set {
657                                 if (hot_tracking == value)
658                                         return;
659                                 
660                                 hot_tracking = value;
661                                 if (hot_tracking) {
662                                         hover_selection = true;
663                                         activation = ItemActivation.OneClick;
664                                 }
665                         }
666                 }
667 #endif
668
669                 [DefaultValue (false)]
670                 public bool HoverSelection {
671                         get { return hover_selection; }
672                         set { 
673 #if NET_2_0
674                                 if (hot_tracking && value == false)
675                                         throw new ArgumentException ("When HotTracking is on, hover selection must be true");
676 #endif
677                                 hover_selection = value; 
678                         }
679                 }
680
681 #if NET_2_0
682                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
683                 [Browsable (false)]
684                 public ListViewInsertionMark InsertionMark {
685                         get {
686                                 return insertion_mark;
687                         }
688                 }
689 #endif
690
691 #if NET_2_0
692                 [Editor ("System.Windows.Forms.Design.ListViewItemCollectionEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))]
693 #endif
694                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
695                 [Localizable (true)]
696                 [MergableProperty (false)]
697                 public ListViewItemCollection Items {
698                         get { return items; }
699                 }
700
701                 [DefaultValue (false)]
702                 public bool LabelEdit {
703                         get { return label_edit; }
704                         set { label_edit = value; }
705                 }
706
707                 [DefaultValue (true)]
708                 [Localizable (true)]
709                 public bool LabelWrap {
710                         get { return label_wrap; }
711                         set {
712                                 if (label_wrap != value) {
713                                         label_wrap = value;
714                                         this.Redraw (true);
715                                 }
716                         }
717                 }
718
719                 [DefaultValue (null)]
720                 public ImageList LargeImageList {
721                         get { return large_image_list; }
722                         set {
723                                 large_image_list = value;
724                                 this.Redraw (true);
725                         }
726                 }
727
728                 [Browsable (false)]
729                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
730                 public IComparer ListViewItemSorter {
731                         get {
732                                 if (View != View.SmallIcon && View != View.LargeIcon && item_sorter is ItemComparer)
733                                         return null;
734                                 return item_sorter;
735                         }
736                         set {
737                                 if (item_sorter != value) {
738                                         item_sorter = value;
739                                         Sort ();
740                                 }
741                         }
742                 }
743
744                 [DefaultValue (true)]
745                 public bool MultiSelect {
746                         get { return multiselect; }
747                         set { multiselect = value; }
748                 }
749
750
751 #if NET_2_0
752                 [DefaultValue(false)]
753                 public bool OwnerDraw {
754                         get { return owner_draw; }
755                         set { 
756                                 owner_draw = value;
757                                 Redraw (true);
758                         }
759                 }
760
761                 [Browsable (false)]
762                 [EditorBrowsable (EditorBrowsableState.Never)]
763                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
764                 public new Padding Padding {
765                         get {
766                                 return base.Padding;
767                         }
768                         set {
769                                 base.Padding = value;
770                         }
771                 }
772                 
773                 [MonoTODO ("RTL not supported")]
774                 [Localizable (true)]
775                 [DefaultValue (false)]
776                 public virtual bool RightToLeftLayout {
777                         get { return right_to_left_layout; }
778                         set { 
779                                 if (right_to_left_layout != value) {
780                                         right_to_left_layout = value;
781                                         OnRightToLeftLayoutChanged (EventArgs.Empty);
782                                 }
783                         }
784                 }
785 #endif
786
787                 [DefaultValue (true)]
788                 public bool Scrollable {
789                         get { return scrollable; }
790                         set {
791                                 if (scrollable != value) {
792                                         scrollable = value;
793                                         this.Redraw (true);
794                                 }
795                         }
796                 }
797
798                 [Browsable (false)]
799                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
800                 public SelectedIndexCollection SelectedIndices {
801                         get { return selected_indices; }
802                 }
803
804                 [Browsable (false)]
805                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
806                 public SelectedListViewItemCollection SelectedItems {
807                         get { return selected_items; }
808                 }
809
810 #if NET_2_0
811                 [DefaultValue(true)]
812                 public bool ShowGroups {
813                         get { return show_groups; }
814                         set {
815                                 if (show_groups != value) {
816                                         show_groups = value;
817                                         Redraw(true);
818                                 }
819                         }
820                 }
821
822                 [LocalizableAttribute (true)]
823                 [MergableProperty (false)]
824                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
825                 [Editor ("System.Windows.Forms.Design.ListViewGroupCollectionEditor, " + Consts.AssemblySystem_Design, typeof (System.Drawing.Design.UITypeEditor))]
826                 public ListViewGroupCollection Groups {
827                         get { return groups; }
828                 }
829
830                 [DefaultValue (false)]
831                 public bool ShowItemToolTips {
832                         get {
833                                 return show_item_tooltips;
834                         }
835                         set {
836                                 show_item_tooltips = value;
837                                 item_tooltip.Active = false;
838                         }
839                 }
840 #endif
841
842                 [DefaultValue (null)]
843                 public ImageList SmallImageList {
844                         get { return small_image_list; }
845                         set {
846                                 small_image_list = value;
847                                 this.Redraw (true);
848                         }
849                 }
850
851                 [DefaultValue (SortOrder.None)]
852                 public SortOrder Sorting {
853                         get { return sort_order; }
854                         set { 
855                                 if (!Enum.IsDefined (typeof (SortOrder), value)) {
856                                         throw new InvalidEnumArgumentException ("value", (int) value,
857                                                 typeof (SortOrder));
858                                 }
859                                 
860                                 if (sort_order == value)
861                                         return;
862
863                                 sort_order = value;
864
865 #if NET_2_0
866                                 if (virtual_mode) // Sorting is not allowed in virtual mode
867                                         return;
868 #endif
869
870                                 if (value == SortOrder.None) {
871                                         if (item_sorter != null) {
872                                                 // ListViewItemSorter should never be reset for SmallIcon
873                                                 // and LargeIcon view
874                                                 if (View != View.SmallIcon && View != View.LargeIcon)
875 #if NET_2_0
876                                                         item_sorter = null;
877 #else
878                                                         // in .NET 1.1, only internal IComparer would be
879                                                         // set to null
880                                                         if (item_sorter is ItemComparer)
881                                                                 item_sorter = null;
882 #endif
883                                         }
884                                         this.Redraw (false);
885                                 } else {
886                                         if (item_sorter == null)
887                                                 item_sorter = new ItemComparer (value);
888                                         if (item_sorter is ItemComparer) {
889 #if NET_2_0
890                                                 item_sorter = new ItemComparer (value);
891 #else
892                                                 // in .NET 1.1, the sort order is not updated for
893                                                 // SmallIcon and LargeIcon views if no custom IComparer
894                                                 // is set
895                                                 if (View != View.SmallIcon && View != View.LargeIcon)
896                                                         item_sorter = new ItemComparer (value);
897 #endif
898                                         }
899                                         Sort ();
900                                 }
901                         }
902                 }
903
904                 private void OnImageListChanged (object sender, EventArgs args)
905                 {
906                         item_control.Invalidate ();
907                 }
908
909                 [DefaultValue (null)]
910                 public ImageList StateImageList {
911                         get { return state_image_list; }
912                         set {
913                                 if (state_image_list == value)
914                                         return;
915
916                                 if (state_image_list != null)
917                                         state_image_list.Images.Changed -= new EventHandler (OnImageListChanged);
918
919                                 state_image_list = value;
920
921                                 if (state_image_list != null)
922                                         state_image_list.Images.Changed += new EventHandler (OnImageListChanged);
923
924                                 this.Redraw (true);
925                         }
926                 }
927
928                 [Bindable (false)]
929                 [Browsable (false)]
930                 [EditorBrowsable (EditorBrowsableState.Never)]
931                 public override string Text {
932                         get { return base.Text; } 
933                         set {
934                                 if (value == base.Text)
935                                         return;
936
937                                 base.Text = value;
938                                 this.Redraw (true);
939                         }
940                 }
941
942 #if NET_2_0
943                 [Browsable (true)]
944                 public Size TileSize {
945                         get {
946                                 return tile_size;
947                         }
948                         set {
949                                 if (value.Width <= 0 || value.Height <= 0)
950                                         throw new ArgumentOutOfRangeException ("value");
951
952                                 tile_size = value;
953                                 Redraw (true);
954                         }
955                 }
956 #endif
957
958                 [Browsable (false)]
959                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
960                 public ListViewItem TopItem {
961                         get {
962 #if NET_2_0
963                                 if (view == View.LargeIcon || view == View.SmallIcon || view == View.Tile)
964                                         throw new InvalidOperationException ("Cannot get the top item in LargeIcon, SmallIcon or Tile view.");
965 #endif
966                                 // there is no item
967                                 if (this.items.Count == 0)
968                                         return null;
969                                 // if contents are not scrolled
970                                 // it is the first item
971                                 else if (h_marker == 0 && v_marker == 0)
972                                         return this.items [0];
973                                 // do a hit test for the scrolled position
974                                 else {
975                                         for (int i = 0; i < items.Count; i++) {
976                                                 Point item_loc = GetItemLocation (i);
977                                                 if (item_loc.X >= 0 && item_loc.Y >= 0)
978                                                         return items [i];
979                                         }
980                                         return null;
981                                 }
982                         }
983 #if NET_2_0
984                         set {
985                                 if (view == View.LargeIcon || view == View.SmallIcon || view == View.Tile)
986                                         throw new InvalidOperationException ("Cannot set the top item in LargeIcon, SmallIcon or Tile view.");
987
988                                 // .Net doesn't throw any exception in the cases below
989                                 if (value == null || value.ListView != this)
990                                         return;
991
992                                 EnsureVisible (value.Index);
993                         }
994 #endif
995                 }
996
997 #if NET_2_0
998                 [EditorBrowsable (EditorBrowsableState.Advanced)]
999                 [DefaultValue (true)]
1000                 [Browsable (false)]
1001                 [MonoInternalNote ("Stub, not implemented")]
1002                 public bool UseCompatibleStateImageBehavior {
1003                         get {
1004                                 return false;
1005                         }
1006                         set {
1007                         }
1008                 }
1009 #endif
1010
1011                 [DefaultValue (View.LargeIcon)]
1012                 public View View {
1013                         get { return view; }
1014                         set { 
1015                                 if (!Enum.IsDefined (typeof (View), value))
1016                                         throw new InvalidEnumArgumentException ("value", (int) value,
1017                                                 typeof (View));
1018
1019                                 if (view != value) {
1020 #if NET_2_0
1021                                         if (CheckBoxes && value == View.Tile)
1022                                                 throw new NotSupportedException ("CheckBoxes are not"
1023                                                         + " supported in Tile view. Choose a different"
1024                                                         + " view or set CheckBoxes to false.");
1025 #endif
1026
1027                                         h_scroll.Value = v_scroll.Value = 0;
1028                                         view = value; 
1029                                         Redraw (true);
1030                                 }
1031                         }
1032                 }
1033
1034 #if NET_2_0
1035                 [DefaultValue (false)]
1036                 [RefreshProperties (RefreshProperties.Repaint)]
1037                 public bool VirtualMode {
1038                         get {
1039                                 return virtual_mode;
1040                         }
1041                         set {
1042                                 if (virtual_mode == value)
1043                                         return;
1044
1045                                 if (!virtual_mode && items.Count > 0)
1046                                         throw new InvalidOperationException ();
1047
1048                                 virtual_mode = value;
1049                                 Redraw (true);
1050                         }
1051                 }
1052
1053                 [DefaultValue (0)]
1054                 [RefreshProperties (RefreshProperties.Repaint)]
1055                 public int VirtualListSize {
1056                         get {
1057                                 return virtual_list_size;
1058                         }
1059                         set {
1060                                 if (value < 0)
1061                                         throw new ArgumentException ("value");
1062
1063                                 if (virtual_list_size == value)
1064                                         return;
1065
1066                                 virtual_list_size = value;
1067                                 if (virtual_mode)
1068                                         Redraw (true);
1069                         }
1070                 }
1071 #endif
1072                 #endregion      // Public Instance Properties
1073
1074                 #region Internal Methods Properties
1075                 
1076                 internal int FirstVisibleIndex {
1077                         get {
1078                                 // there is no item
1079                                 if (this.items.Count == 0)
1080                                         return 0;
1081                                 
1082                                 if (h_marker == 0 && v_marker == 0)
1083                                         return 0;
1084                                 
1085                                 Size item_size = ItemSize;
1086                                 for (int i = 0; i < items.Count; i++) {
1087                                         Rectangle item_rect = new Rectangle (GetItemLocation (i), item_size);
1088                                         if (item_rect.Right >= 0 && item_rect.Bottom >= 0)
1089                                                 return i;
1090                                 }
1091
1092                                 return 0;
1093                         }
1094                 }
1095
1096                 
1097                 internal int LastVisibleIndex {
1098                         get {
1099                                 for (int i = FirstVisibleIndex; i < Items.Count; i++) {
1100                                         if (View == View.List || Alignment == ListViewAlignment.Left) {
1101                                                 if (GetItemLocation (i).X > item_control.ClientRectangle.Right)
1102                                                         return i - 1;
1103                                         } else {
1104                                                 if (GetItemLocation (i).Y > item_control.ClientRectangle.Bottom)
1105                                                         return i - 1;
1106                                         }
1107                                 }
1108                                 
1109                                 return Items.Count - 1;
1110                         }
1111                 }
1112
1113                 internal void OnSelectedIndexChanged ()
1114                 {
1115                         if (IsHandleCreated)
1116                                 OnSelectedIndexChanged (EventArgs.Empty);
1117                 }
1118
1119                 internal int TotalWidth {
1120                         get { return Math.Max (this.Width, this.layout_wd); }
1121                 }
1122
1123                 internal int TotalHeight {
1124                         get { return Math.Max (this.Height, this.layout_ht); }
1125                 }
1126
1127                 internal void Redraw (bool recalculate)
1128                 {
1129                         // Avoid calculations when control is being updated
1130                         if (updating)
1131                                 return;
1132 #if NET_2_0
1133                         // VirtualMode doesn't do any calculations until handle is created
1134                         if (virtual_mode && !IsHandleCreated)
1135                                 return;
1136 #endif
1137
1138
1139                         if (recalculate)
1140                                 CalculateListView (this.alignment);
1141
1142                         Refresh ();
1143                 }
1144
1145                 void InvalidateSelection ()
1146                 {
1147                         foreach (int selected_index in SelectedIndices)
1148                                 items [selected_index].Invalidate ();
1149                 }
1150
1151                 const int text_padding = 15;
1152
1153                 internal Size GetChildColumnSize (int index)
1154                 {
1155                         Size ret_size = Size.Empty;
1156                         ColumnHeader col = this.columns [index];
1157
1158                         if (col.Width == -2) { // autosize = max(items, columnheader)
1159                                 Size size = Size.Ceiling (TextRenderer.MeasureString
1160                                         (col.Text, this.Font));
1161                                 size.Width += text_padding;
1162                                 ret_size = BiggestItem (index);
1163                                 if (size.Width > ret_size.Width)
1164                                         ret_size = size;
1165                         }
1166                         else { // -1 and all the values < -2 are put under one category
1167                                 ret_size = BiggestItem (index);
1168                                 // fall back to empty columns' width if no subitem is available for a column
1169                                 if (ret_size.IsEmpty) {
1170                                         ret_size.Width = ThemeEngine.Current.ListViewEmptyColumnWidth;
1171                                         if (col.Text.Length > 0)
1172                                                 ret_size.Height = Size.Ceiling (TextRenderer.MeasureString
1173                                                                                 (col.Text, this.Font)).Height;
1174                                         else
1175                                                 ret_size.Height = this.Font.Height;
1176                                 }
1177                         }
1178
1179                         ret_size.Height += text_padding;
1180
1181                         // adjust the size for icon and checkbox for 0th column
1182                         if (index == 0) {
1183                                 ret_size.Width += (this.CheckBoxSize.Width + 4);
1184                                 if (this.small_image_list != null)
1185                                         ret_size.Width += this.small_image_list.ImageSize.Width;
1186                         }
1187                         return ret_size;
1188                 }
1189
1190                 // Returns the size of biggest item text in a column
1191                 // or the sum of the text and indent count if we are on 2.0
1192                 private Size BiggestItem (int col)
1193                 {
1194                         Size temp = Size.Empty;
1195                         Size ret_size = Size.Empty;
1196 #if NET_2_0
1197                         bool use_indent_count = small_image_list != null;
1198
1199                         // VirtualMode uses the first item text size
1200                         if (virtual_mode && items.Count > 0) {
1201                                 ListViewItem item = items [0];
1202                                 ret_size = Size.Ceiling (TextRenderer.MeasureString (item.SubItems[col].Text,
1203                                                         Font));
1204
1205                                 if (use_indent_count)
1206                                         ret_size.Width += item.IndentCount * small_image_list.ImageSize.Width;
1207                         } else {
1208 #endif
1209                                 // 0th column holds the item text, we check the size of
1210                                 // the various subitems falling in that column and get
1211                                 // the biggest one's size.
1212                                 foreach (ListViewItem item in items) {
1213                                         if (col >= item.SubItems.Count)
1214                                                 continue;
1215
1216                                         temp = Size.Ceiling (TextRenderer.MeasureString
1217                                                                 (item.SubItems [col].Text, Font));
1218
1219 #if NET_2_0
1220                                         if (use_indent_count)
1221                                                 temp.Width += item.IndentCount * small_image_list.ImageSize.Width;
1222 #endif
1223     
1224                                         if (temp.Width > ret_size.Width)
1225                                                 ret_size = temp;
1226                                 }
1227 #if NET_2_0
1228                         }
1229 #endif
1230
1231                         // adjustment for space in Details view
1232                         if (!ret_size.IsEmpty && view == View.Details)
1233                                 ret_size.Width += ThemeEngine.Current.ListViewItemPaddingWidth;
1234
1235                         return ret_size;
1236                 }
1237
1238                 const int max_wrap_padding = 30;
1239
1240                 // Sets the size of the biggest item text as per the view
1241                 private void CalcTextSize ()
1242                 {
1243                         // clear the old value
1244                         text_size = Size.Empty;
1245
1246                         if (items.Count == 0)
1247                                 return;
1248
1249                         text_size = BiggestItem (0);
1250
1251                         if (view == View.LargeIcon && this.label_wrap) {
1252                                 Size temp = Size.Empty;
1253                                 if (this.check_boxes)
1254                                         temp.Width += 2 * this.CheckBoxSize.Width;
1255                                 int icon_w = LargeImageList == null ? 12 : LargeImageList.ImageSize.Width;
1256                                 temp.Width += icon_w + max_wrap_padding;
1257                                 // wrapping is done for two lines only
1258                                 if (text_size.Width > temp.Width) {
1259                                         text_size.Width = temp.Width;
1260                                         text_size.Height *= 2;
1261                                 }
1262                         }
1263                         else if (view == View.List) {
1264                                 // in list view max text shown in determined by the
1265                                 // control width, even if scolling is enabled.
1266                                 int max_wd = this.Width - (this.CheckBoxSize.Width - 2);
1267                                 if (this.small_image_list != null)
1268                                         max_wd -= this.small_image_list.ImageSize.Width;
1269
1270                                 if (text_size.Width > max_wd)
1271                                         text_size.Width = max_wd;
1272                         }
1273
1274                         // we do the default settings, if we have got 0's
1275                         if (text_size.Height <= 0)
1276                                 text_size.Height = this.Font.Height;
1277                         if (text_size.Width <= 0)
1278                                 text_size.Width = this.Width;
1279
1280                         // little adjustment
1281                         text_size.Width += 2;
1282                         text_size.Height += 2;
1283                 }
1284
1285                 private void Scroll (ScrollBar scrollbar, int delta)
1286                 {
1287                         if (delta == 0 || !scrollbar.Visible)
1288                                 return;
1289
1290                         int max;
1291                         if (scrollbar == h_scroll)
1292                                 max = h_scroll.Maximum - item_control.Width;
1293                         else
1294                                 max = v_scroll.Maximum - item_control.Height;
1295
1296                         int val = scrollbar.Value + delta;
1297                         if (val > max)
1298                                 val = max;
1299                         else if (val < scrollbar.Minimum)
1300                                 val = scrollbar.Minimum;
1301                         scrollbar.Value = val;
1302                 }
1303
1304                 private void CalculateScrollBars ()
1305                 {
1306                         if (!IsHandleCreated)
1307                                 return;
1308
1309                         Rectangle client_area = ClientRectangle;
1310                         
1311                         if (!scrollable) {
1312                                 h_scroll.Visible = false;
1313                                 v_scroll.Visible = false;
1314                                 item_control.Height = client_area.Height;
1315                                 item_control.Width = client_area.Width;
1316                                 header_control.Width = client_area.Width;
1317                                 return;
1318                         }
1319
1320                         // Don't calculate if the view is not displayable
1321                         if (client_area.Height < 0 || client_area.Width < 0)
1322                                 return;
1323
1324                         // making a scroll bar visible might make
1325                         // other scroll bar visible
1326                         if (layout_wd > client_area.Right) {
1327                                 h_scroll.Visible = true;
1328                                 if ((layout_ht + h_scroll.Height) > client_area.Bottom)
1329                                         v_scroll.Visible = true;
1330                                 else
1331                                         v_scroll.Visible = false;
1332                         } else if (layout_ht > client_area.Bottom) {
1333                                 v_scroll.Visible = true;
1334                                 if ((layout_wd + v_scroll.Width) > client_area.Right)
1335                                         h_scroll.Visible = true;
1336                                 else
1337                                         h_scroll.Visible = false;
1338                         } else {
1339                                 h_scroll.Visible = false;
1340                                 v_scroll.Visible = false;
1341                         }
1342
1343                         item_control.Height = client_area.Height;
1344
1345                         if (h_scroll.is_visible) {
1346                                 h_scroll.Location = new Point (client_area.X, client_area.Bottom - h_scroll.Height);
1347                                 h_scroll.Minimum = 0;
1348
1349                                 // if v_scroll is visible, adjust the maximum of the
1350                                 // h_scroll to account for the width of v_scroll
1351                                 if (v_scroll.Visible) {
1352                                         h_scroll.Maximum = layout_wd + v_scroll.Width;
1353                                         h_scroll.Width = client_area.Width - v_scroll.Width;
1354                                 }
1355                                 else {
1356                                         h_scroll.Maximum = layout_wd;
1357                                         h_scroll.Width = client_area.Width;
1358                                 }
1359
1360                                 h_scroll.LargeChange = client_area.Width;
1361                                 h_scroll.SmallChange = Font.Height;
1362                                 item_control.Height -= h_scroll.Height;
1363                         }
1364
1365                         if (header_control.is_visible)
1366                                 header_control.Width = client_area.Width;
1367                         item_control.Width = client_area.Width;
1368
1369                         if (v_scroll.is_visible) {
1370                                 v_scroll.Location = new Point (client_area.Right - v_scroll.Width, client_area.Y);
1371                                 v_scroll.Minimum = 0;
1372
1373                                 // if h_scroll is visible, adjust the maximum of the
1374                                 // v_scroll to account for the height of h_scroll
1375                                 if (h_scroll.Visible) {
1376                                         v_scroll.Maximum = layout_ht + h_scroll.Height;
1377                                         v_scroll.Height = client_area.Height; // - h_scroll.Height already done 
1378                                 } else {
1379                                         v_scroll.Maximum = layout_ht;
1380                                         v_scroll.Height = client_area.Height;
1381                                 }
1382
1383                                 v_scroll.LargeChange = client_area.Height;
1384                                 v_scroll.SmallChange = Font.Height;
1385                                 if (header_control.Visible)
1386                                         header_control.Width -= v_scroll.Width;
1387                                 item_control.Width -= v_scroll.Width;
1388                         }
1389                 }
1390
1391 #if NET_2_0
1392                 internal int GetReorderedColumnIndex (ColumnHeader column)
1393                 {
1394                         if (reordered_column_indices == null)
1395                                 return column.Index;
1396
1397                         for (int i = 0; i < Columns.Count; i++)
1398                                 if (reordered_column_indices [i] == column.Index)
1399                                         return i;
1400
1401                         return -1;
1402                 }
1403 #endif
1404
1405                 internal ColumnHeader GetReorderedColumn (int index)
1406                 {
1407                         if (reordered_column_indices == null)
1408                                 return Columns [index];
1409                         else
1410                                 return Columns [reordered_column_indices [index]];
1411                 }
1412
1413                 internal void ReorderColumn (ColumnHeader col, int index, bool fireEvent)
1414                 {
1415 #if NET_2_0
1416                         if (fireEvent) {
1417                                 ColumnReorderedEventHandler eh = (ColumnReorderedEventHandler) (Events [ColumnReorderedEvent]);
1418                                 if (eh != null){
1419                                         ColumnReorderedEventArgs args = new ColumnReorderedEventArgs (col.Index, index, col);
1420
1421                                         eh (this, args);
1422                                         if (args.Cancel) {
1423                                                 header_control.Invalidate ();
1424                                                 item_control.Invalidate ();
1425                                                 return;
1426                                         }
1427                                 }
1428                         }
1429 #endif
1430                         int column_count = Columns.Count;
1431
1432                         if (reordered_column_indices == null) {
1433                                 reordered_column_indices = new int [column_count];
1434                                 for (int i = 0; i < column_count; i++)
1435                                         reordered_column_indices [i] = i;
1436                         }
1437
1438                         if (reordered_column_indices [index] == col.Index)
1439                                 return;
1440
1441                         int[] curr = reordered_column_indices;
1442                         int [] result = new int [column_count];
1443                         int curr_idx = 0;
1444                         for (int i = 0; i < column_count; i++) {
1445                                 if (curr_idx < column_count && curr [curr_idx] == col.Index)
1446                                         curr_idx++;
1447
1448                                 if (i == index)
1449                                         result [i] = col.Index;
1450                                 else
1451                                         result [i] = curr [curr_idx++];
1452                         }
1453
1454                         ReorderColumns (result, true);
1455                 }
1456
1457                 internal void ReorderColumns (int [] display_indices, bool redraw)
1458                 {
1459                         reordered_column_indices = display_indices;
1460                         for (int i = 0; i < Columns.Count; i++) {
1461                                 ColumnHeader col = Columns [i];
1462                                 col.InternalDisplayIndex = reordered_column_indices [i];
1463                         }
1464                         if (redraw && view == View.Details && IsHandleCreated) {
1465                                 LayoutDetails ();
1466                                 header_control.Invalidate ();
1467                                 item_control.Invalidate ();
1468                         }
1469                 }
1470
1471                 internal void AddColumn (ColumnHeader newCol, int index, bool redraw)
1472                 {
1473                         int column_count = Columns.Count;
1474                         newCol.SetListView (this);
1475
1476                         int [] display_indices = new int [column_count];
1477                         for (int i = 0; i < column_count; i++) {
1478                                 ColumnHeader col = Columns [i];
1479                                 if (i == index) {
1480                                         display_indices [i] = index;
1481                                 } else {
1482                                         int display_index = col.InternalDisplayIndex;
1483                                         if (display_index < index) {
1484                                                 display_indices [i] = display_index;
1485                                         } else {
1486                                                 display_indices [i] = (display_index + 1);
1487                                         }
1488                                 }
1489                         }
1490
1491                         ReorderColumns (display_indices, redraw);
1492                         Invalidate ();
1493                 }
1494
1495                 Size LargeIconItemSize
1496                 {
1497                         get {
1498                                 int image_w = LargeImageList == null ? 12 : LargeImageList.ImageSize.Width;
1499                                 int image_h = LargeImageList == null ? 2 : LargeImageList.ImageSize.Height;
1500                                 int h = text_size.Height + 2 + Math.Max (CheckBoxSize.Height, image_h);
1501                                 int w = Math.Max (text_size.Width, image_w);
1502
1503                                 if (check_boxes)
1504                                         w += 2 + CheckBoxSize.Width;
1505
1506                                 return new Size (w, h);
1507                         }
1508                 }
1509
1510                 Size SmallIconItemSize {
1511                         get {
1512                                 int image_w = SmallImageList == null ? 0 : SmallImageList.ImageSize.Width;
1513                                 int image_h = SmallImageList == null ? 0 : SmallImageList.ImageSize.Height;
1514                                 int h = Math.Max (text_size.Height, Math.Max (CheckBoxSize.Height, image_h));
1515                                 int w = text_size.Width + image_w;
1516
1517                                 if (check_boxes)
1518                                         w += 2 + CheckBoxSize.Width;
1519
1520                                 return new Size (w, h);
1521                         }
1522                 }
1523
1524 #if NET_2_0
1525                 Size TileItemSize {
1526                         get {
1527                                 // Calculate tile size if needed
1528                                 // It appears that using Font.Size instead of a SizeF value can give us
1529                                 // a slightly better approach to the proportions defined in .Net
1530                                 if (tile_size == Size.Empty) {
1531                                         int image_w = LargeImageList == null ? 0 : LargeImageList.ImageSize.Width;
1532                                         int image_h = LargeImageList == null ? 0 : LargeImageList.ImageSize.Height;
1533                                         int w = (int)Font.Size * ThemeEngine.Current.ListViewTileWidthFactor + image_w + 4;
1534                                         int h = Math.Max ((int)Font.Size * ThemeEngine.Current.ListViewTileHeightFactor, image_h);
1535                                 
1536                                         tile_size = new Size (w, h);
1537                                 }
1538                         
1539                                 return tile_size;
1540                         }
1541                 }
1542 #endif
1543
1544                 int GetDetailsItemHeight ()
1545                 {
1546                         int item_height;
1547                         int checkbox_height = CheckBoxes ? CheckBoxSize.Height : 0;
1548                         int small_image_height = SmallImageList == null ? 0 : SmallImageList.ImageSize.Height;
1549                         item_height = Math.Max (checkbox_height, text_size.Height);
1550                         item_height = Math.Max (item_height, small_image_height);
1551                         return item_height;
1552                 }
1553
1554                 void SetItemLocation (int index, int x, int y, int row, int col)
1555                 {
1556                         Point old_location = items_location [index];
1557                         if (old_location.X == x && old_location.Y == y)
1558                                 return;
1559
1560                         Size item_size = ItemSize;
1561                         Rectangle old_rect = new Rectangle (GetItemLocation (index), item_size);
1562
1563                         items_location [index] = new Point (x, y);
1564                         items_matrix_location [index] = new ItemMatrixLocation (row, col);
1565
1566                         //
1567                         // Initial position matches item's position in ListViewItemCollection
1568                         //
1569                         reordered_items_indices [index] = index;
1570
1571                         // Invalidate both previous and new bounds
1572                         item_control.Invalidate (old_rect);
1573                         item_control.Invalidate (new Rectangle (GetItemLocation (index), item_size));
1574                 }
1575
1576 #if NET_2_0
1577                 void ShiftItemsPositions (int from, int to, bool forward)
1578                 {
1579                         if (forward) {
1580                                 for (int i = to + 1; i > from; i--) {
1581                                         reordered_items_indices [i] = reordered_items_indices [i - 1];
1582
1583                                         ListViewItem item = items [reordered_items_indices [i]];
1584                                         item_control.Invalidate (item.Bounds);
1585                                         item.DisplayIndex = i;
1586                                         item_control.Invalidate (item.Bounds);
1587                                 }
1588                         } else {
1589                                 for (int i = from - 1; i < to; i++) {
1590                                         reordered_items_indices [i] = reordered_items_indices [i + 1];
1591
1592                                         ListViewItem item = items [reordered_items_indices [i]];
1593                                         item_control.Invalidate (item.Bounds);
1594                                         item.DisplayIndex = i;
1595                                         item_control.Invalidate (item.Bounds);
1596                                 }
1597                         }
1598                 }
1599
1600                 internal void ChangeItemLocation (int display_index, Point new_pos)
1601                 {
1602                         int new_display_index = GetDisplayIndexFromLocation (new_pos);
1603                         if (new_display_index == display_index)
1604                                 return;
1605
1606                         int item_index = reordered_items_indices [display_index];
1607                         ListViewItem item = items [item_index];
1608
1609                         bool forward = new_display_index < display_index;
1610                         int index_from, index_to;
1611                         if (forward) {
1612                                 index_from = new_display_index;
1613                                 index_to = display_index - 1;
1614                         } else {
1615                                 index_from = display_index + 1;
1616                                 index_to = new_display_index;
1617                         }
1618
1619                         ShiftItemsPositions (index_from, index_to, forward);
1620
1621                         reordered_items_indices [new_display_index] = item_index;
1622
1623                         item_control.Invalidate (item.Bounds);
1624                         item.DisplayIndex = new_display_index;
1625                         item_control.Invalidate (item.Bounds);
1626                 }
1627
1628                 int GetDisplayIndexFromLocation (Point loc)
1629                 {
1630                         int display_index = -1;
1631                         Rectangle item_area;
1632
1633                         // First item
1634                         if (loc.X < 0 || loc.Y < 0)
1635                                 return 0;
1636
1637                         // Adjustment to put in the next position refered by 'loc'
1638                         loc.X -= item_size.Width / 2;
1639                         if (loc.X < 0)
1640                                 loc.X = 0;
1641
1642                         for (int i = 0; i < items.Count; i++) {
1643                                 item_area = new Rectangle (GetItemLocation (i), item_size);
1644                                 item_area.Inflate (ThemeEngine.Current.ListViewHorizontalSpacing,
1645                                                 ThemeEngine.Current.ListViewVerticalSpacing);
1646
1647                                 if (item_area.Contains (loc)) {
1648                                         display_index = i;
1649                                         break;
1650                                 }
1651                         }
1652
1653                         // Put in in last position
1654                         if (display_index == -1)
1655                                 display_index = items.Count - 1;
1656
1657                         return display_index;
1658                 }
1659
1660                 // When using groups, the items with no group assigned
1661                 // belong to the DefaultGroup
1662                 int GetDefaultGroupItems ()
1663                 {
1664                         int count = 0;
1665                         foreach (ListViewItem item in items)
1666                                 if (item.Group == null)
1667                                         count++;
1668
1669                         return count;
1670                 }
1671 #endif
1672
1673                 int rows;
1674                 int cols;
1675                 int[,] item_index_matrix;
1676
1677                 void CalculateRowsAndCols (Size item_size, bool left_aligned, int x_spacing, int y_spacing)
1678                 {
1679                         Rectangle area = ClientRectangle;
1680 #if NET_2_0
1681                         if (show_groups && groups.Count > 0 && view != View.List) {
1682                                 // When groups are used the alignment is always top-aligned
1683                                 rows = 0;
1684                                 cols = 0;
1685
1686                                 groups.DefaultGroup.ItemCount = GetDefaultGroupItems ();
1687                                 for (int i = 0; i < groups.InternalCount; i++) {
1688                                         ListViewGroup group = groups.GetInternalGroup (i);
1689                                         int items_in_group = group.ItemCount;
1690
1691                                         if (items_in_group == 0)
1692                                                 continue;
1693
1694                                         int group_cols = (int) Math.Floor ((double)(area.Width - v_scroll.Width + x_spacing) / (double)(item_size.Width + x_spacing));
1695                                         if (group_cols <= 0)
1696                                                 group_cols = 1;
1697                                         int group_rows = (int) Math.Ceiling ((double)items_in_group / (double)group_cols);
1698
1699                                         group.starting_row = rows;
1700                                         group.rows = group_rows;
1701
1702                                         cols = Math.Max (group_cols, cols);
1703                                         rows += group_rows;
1704                                 }
1705                         } else
1706 #endif
1707                         {
1708                                 // Simple matrix if no groups are used
1709                                 if (left_aligned) {
1710                                         rows = (int) Math.Floor ((double)(area.Height - h_scroll.Height + y_spacing) / (double)(item_size.Height + y_spacing));
1711                                         if (rows <= 0)
1712                                                 rows = 1;
1713                                         cols = (int) Math.Ceiling ((double)items.Count / (double)rows);
1714                                 } else {
1715                                         cols = (int) Math.Floor ((double)(area.Width - v_scroll.Width + x_spacing) / (double)(item_size.Width + x_spacing));
1716                                         if (cols <= 0)
1717                                                 cols = 1;
1718                                         rows = (int) Math.Ceiling ((double)items.Count / (double)cols);
1719                                 }
1720                         }
1721
1722                         item_index_matrix = new int [rows, cols];
1723                 }
1724
1725                 void LayoutIcons (Size item_size, bool left_aligned, int x_spacing, int y_spacing)
1726                 {
1727                         header_control.Visible = false;
1728                         header_control.Size = Size.Empty;
1729                         item_control.Visible = true;
1730                         item_control.Location = Point.Empty;
1731                         ItemSize = item_size; // Cache item size
1732
1733                         if (items.Count == 0)
1734                                 return;
1735
1736                         Size sz = item_size;
1737 #if NET_2_0
1738                         bool using_groups = show_groups && groups.Count > 0 && view != View.List;
1739 #endif
1740
1741                         CalculateRowsAndCols (sz, left_aligned, x_spacing, y_spacing);
1742
1743                         layout_ht = rows * (sz.Height + y_spacing) - y_spacing;
1744                         layout_wd = cols * (sz.Width + x_spacing) - x_spacing;
1745
1746 #if NET_2_0
1747                         if (using_groups)
1748                                 CalculateGroupsLayout (sz, y_spacing, 0);
1749 #endif
1750
1751                         int row = 0, col = 0;
1752                         int x = 0, y = 0;
1753
1754                         for (int i = 0; i < items.Count; i++) {
1755                                 ListViewItem item = items [i];
1756 #if NET_2_0
1757                                 if (using_groups) {
1758                                         ListViewGroup group = item.Group;
1759                                         if (group == null)
1760                                                 group = groups.DefaultGroup;
1761
1762                                         Point group_items_loc = group.items_area_location;
1763                                         int current_item = group.current_item++;
1764                                         int starting_row = group.starting_row;
1765
1766                                         row = (current_item / cols);
1767                                         col = current_item % cols;
1768
1769                                         x = col * (item_size.Width + x_spacing);
1770                                         y = row * (item_size.Height + y_spacing) + group_items_loc.Y;
1771
1772                                         SetItemLocation (i, x, y, row + starting_row, col);
1773                                         item_index_matrix [row + starting_row, col] = i;
1774                                 } else
1775 #endif
1776                                 {
1777                                         x = col * (item_size.Width + x_spacing);
1778                                         y = row * (item_size.Height + y_spacing);
1779
1780                                         SetItemLocation (i, x, y, row, col);
1781                                         item_index_matrix [row, col] = i;
1782
1783                                         if (left_aligned) {
1784                                                 row++;
1785                                                 if (row == rows) {
1786                                                         row = 0;
1787                                                         col++;
1788                                                 }
1789                                         } else {
1790                                                 if (++col == cols) {
1791                                                         col = 0;
1792                                                         row++;
1793                                                 }
1794                                         }
1795                                 }
1796 #if NET_2_0
1797                                 if (!virtual_mode) 
1798 #endif
1799                                 {
1800                                         item.Layout ();
1801                                         item.DisplayIndex = i;
1802                                         item.SetPosition (new Point (x, y));
1803                                 }
1804
1805
1806                         }
1807
1808                         item_control.Size = new Size (layout_wd, layout_ht);
1809                 }
1810
1811 #if NET_2_0
1812                 void CalculateGroupsLayout (Size item_size, int y_spacing, int y_origin)
1813                 {
1814                         int y = y_origin;
1815                         bool details = view == View.Details;
1816
1817                         for (int i = 0; i < groups.InternalCount; i++) {
1818                                 ListViewGroup group = groups.GetInternalGroup (i);
1819                                 if (group.ItemCount == 0)
1820                                         continue;
1821
1822                                 group.current_item = 0; // Reset layout
1823                                 y += LayoutGroupHeader (group, y, item_size.Height, y_spacing, details ? group.ItemCount : group.rows);
1824                         }
1825
1826                         layout_ht = y; // Update height taking into account Groups' headers heights
1827                 }
1828
1829                 int LayoutGroupHeader (ListViewGroup group, int y_origin, int item_height, int y_spacing, int rows)
1830                 {
1831                         Rectangle client_area = ClientRectangle;
1832                         int header_height = text_size.Height + 10;
1833
1834                         group.HeaderBounds = new Rectangle (0, y_origin, client_area.Width - v_scroll.Width, header_height);
1835                         group.items_area_location = new Point (0, y_origin + header_height);
1836
1837                         int items_area_height = ((item_height + y_spacing) * rows);
1838                         return header_height + items_area_height + 10; // Add a small bottom margin
1839                 }
1840 #endif
1841
1842                 void LayoutHeader ()
1843                 {
1844                         int x = 0;
1845                         for (int i = 0; i < Columns.Count; i++) {
1846                                 ColumnHeader col = GetReorderedColumn (i);
1847                                 col.X = x;
1848                                 col.Y = 0;
1849                                 col.CalcColumnHeader ();
1850                                 x += col.Wd;
1851                         }
1852
1853                         layout_wd = x;
1854
1855                         if (x < ClientRectangle.Width)
1856                                 x = ClientRectangle.Width;
1857
1858                         if (header_style == ColumnHeaderStyle.None) {
1859                                 header_control.Visible = false;
1860                                 header_control.Size = Size.Empty;
1861                                 layout_wd = ClientRectangle.Width;
1862                         } else {
1863                                 header_control.Width = x;
1864                                 header_control.Height = columns.Count > 0 ? columns [0].Ht : Font.Height + 5;
1865                                 header_control.Visible = true;
1866                         }
1867                 }
1868
1869                 void LayoutDetails ()
1870                 {
1871                         LayoutHeader ();
1872
1873                         if (columns.Count == 0) {
1874                                 item_control.Visible = false;
1875                                 layout_wd = ClientRectangle.Width;
1876                                 layout_ht = ClientRectangle.Height;
1877                                 return;
1878                         }
1879
1880                         item_control.Visible = true;
1881                         item_control.Location = Point.Empty;
1882                         item_control.Width = ClientRectangle.Width;
1883
1884                         int item_height = GetDetailsItemHeight ();
1885                         ItemSize = new Size (0, item_height); // We only cache Height for details view
1886                         int y = header_control.Height;
1887 #if NET_2_0
1888                         bool using_groups = show_groups && groups.Count > 0 && view != View.List;
1889                         if (using_groups) 
1890                                 CalculateGroupsLayout (ItemSize, 2, y);
1891 #endif
1892
1893                         for (int i = 0; i < items.Count; i++) {
1894                                 ListViewItem item = items [i];
1895 #if NET_2_0
1896                                 if (!virtual_mode) // Virtual mode sets Layout until draw time
1897 #endif
1898                                 {
1899                                         item.Layout ();
1900                                         item.DisplayIndex = i;
1901                                 }
1902
1903 #if NET_2_0
1904                                 if (using_groups) {
1905                                         ListViewGroup group = item.Group;
1906                                         if (group == null)
1907                                                 group = groups.DefaultGroup;
1908
1909                                         int current_item = group.current_item++;
1910                                         Point group_items_loc = group.items_area_location;
1911
1912                                         y = current_item * (item_height + 2) + group_items_loc.Y;
1913                                         SetItemLocation (i, 0, y, 0, 0);
1914                                         item.SetPosition (new Point (0, y));
1915                                 } else
1916 #endif
1917                                 {
1918                                         SetItemLocation (i, 0, y, 0, 0);
1919                                         item.SetPosition (new Point (0, y));
1920                                         y += item_height;
1921                                 }
1922                         }
1923
1924                         // some space for bottom gridline
1925                         if (items.Count > 0 && grid_lines)
1926                                 y += 2;
1927
1928 #if NET_2_0
1929                         if (!using_groups) // With groups it has been previously computed
1930 #endif
1931                                 layout_ht = y;
1932                 }
1933
1934                 private void AdjustItemsPositionArray (int count)
1935                 {
1936                         if (items_location.Length >= count)
1937                                 return;
1938
1939                         // items_location, items_matrix_location and reordered_items_indices must keep the same length
1940                         count = Math.Max (count, items_location.Length * 2);
1941                         items_location = new Point [count];
1942                         items_matrix_location = new ItemMatrixLocation [count];
1943                         reordered_items_indices = new int [count];
1944                 }
1945
1946                 private void CalculateListView (ListViewAlignment align)
1947                 {
1948                         CalcTextSize ();
1949
1950                         AdjustItemsPositionArray (items.Count);
1951
1952                         switch (view) {
1953                         case View.Details:
1954                                 LayoutDetails ();
1955                                 break;
1956
1957                         case View.SmallIcon:
1958                                 LayoutIcons (SmallIconItemSize, alignment == ListViewAlignment.Left, 
1959                                                 ThemeEngine.Current.ListViewHorizontalSpacing, 2);
1960                                 break;
1961
1962                         case View.LargeIcon:
1963                                 LayoutIcons (LargeIconItemSize, alignment == ListViewAlignment.Left,
1964                                         ThemeEngine.Current.ListViewHorizontalSpacing,
1965                                         ThemeEngine.Current.ListViewVerticalSpacing);
1966                                 break;
1967
1968                         case View.List:
1969                                 LayoutIcons (SmallIconItemSize, true, 
1970                                                 ThemeEngine.Current.ListViewHorizontalSpacing, 2);
1971                                 break;
1972 #if NET_2_0
1973                         case View.Tile:
1974                                 LayoutIcons (TileItemSize, alignment == ListViewAlignment.Left, 
1975                                                 ThemeEngine.Current.ListViewHorizontalSpacing,
1976                                                 ThemeEngine.Current.ListViewVerticalSpacing);
1977                                 break;
1978 #endif
1979                         }
1980
1981                         CalculateScrollBars ();
1982                 }
1983
1984                 internal Point GetItemLocation (int index)
1985                 {
1986                         Point loc = items_location [index];
1987                         loc.X -= h_marker; // Adjust to scroll
1988                         loc.Y -= v_marker;
1989
1990                         return loc;
1991                 }
1992
1993                 internal int GetItemIndex (int display_index)
1994                 {
1995                         return reordered_items_indices [display_index];
1996                 }
1997
1998                 private bool KeySearchString (KeyEventArgs ke)
1999                 {
2000                         int current_tickcnt = Environment.TickCount;
2001                         if (keysearch_tickcnt > 0 && current_tickcnt - keysearch_tickcnt > keysearch_keydelay) {
2002                                 keysearch_text = string.Empty;
2003                         }
2004                         
2005                         if (!Char.IsLetterOrDigit ((char)ke.KeyCode))
2006                                 return false;
2007
2008                         keysearch_text += (char)ke.KeyCode;
2009                         keysearch_tickcnt = current_tickcnt;
2010
2011                         int start = FocusedItem == null ? 0 : FocusedItem.Index;
2012                         int i = start;
2013                         while (true) {
2014                                 if (CultureInfo.CurrentCulture.CompareInfo.IsPrefix (Items[i].Text, keysearch_text,
2015                                         CompareOptions.IgnoreCase)) {
2016                                         SetFocusedItem (i);
2017                                         items [i].Selected = true;
2018                                         EnsureVisible (i);
2019                                         break;
2020                                 }
2021                                 i = (i + 1 < Items.Count) ? i+1 : 0;
2022
2023                                 if (i == start)
2024                                         break;
2025                         }
2026                         return true;
2027                 }
2028
2029                 int GetAdjustedIndex (Keys key)
2030                 {
2031                         int result = -1;
2032
2033                         if (View == View.Details) {
2034                                 switch (key) {
2035                                 case Keys.Up:
2036                                         result = FocusedItem.Index - 1;
2037                                         break;
2038                                 case Keys.Down:
2039                                         result = FocusedItem.Index + 1;
2040                                         if (result == items.Count)
2041                                                 result = -1;
2042                                         break;
2043                                 case Keys.PageDown:
2044                                         int last_index = LastVisibleIndex;
2045                                         Rectangle item_rect = new Rectangle (GetItemLocation (last_index), ItemSize);
2046                                         if (item_rect.Bottom > item_control.ClientRectangle.Bottom)
2047                                                 last_index--;
2048                                         if (FocusedItem.Index == last_index) {
2049                                                 if (FocusedItem.Index < Items.Count - 1) {
2050                                                         int page_size = item_control.Height / ItemSize.Height - 1;
2051                                                         result = FocusedItem.Index + page_size - 1;
2052                                                         if (result >= Items.Count)
2053                                                                 result = Items.Count - 1;
2054                                                 }
2055                                         } else
2056                                                 result = last_index;
2057                                         break;
2058                                 case Keys.PageUp:
2059                                         int first_index = FirstVisibleIndex;
2060                                         if (GetItemLocation (first_index).Y < 0)
2061                                                 first_index++;
2062                                         if (FocusedItem.Index == first_index) {
2063                                                 if (first_index > 0) {
2064                                                         int page_size = item_control.Height / ItemSize.Height - 1;
2065                                                         result = first_index - page_size + 1;
2066                                                         if (result < 0)
2067                                                                 result = 0;
2068                                                 }
2069                                         } else
2070                                                 result = first_index;
2071                                         break;
2072                                 }
2073                                 return result;
2074                         }
2075
2076                         ItemMatrixLocation item_matrix_location = items_matrix_location [FocusedItem.Index];
2077                         int row = item_matrix_location.Row;
2078                         int col = item_matrix_location.Col;
2079
2080                         switch (key) {
2081                         case Keys.Left:
2082                                 if (col == 0)
2083                                         return -1;
2084                                 return item_index_matrix [row, col - 1];
2085
2086                         case Keys.Right:
2087                                 if (col == (cols - 1))
2088                                         return -1;
2089                                 while (item_index_matrix [row, col + 1] == 0) {
2090                                         row--;
2091                                         if (row < 0)
2092                                                 return -1;
2093                                 }
2094                                 return item_index_matrix [row, col + 1];
2095
2096                         case Keys.Up:
2097                                 if (row == 0)
2098                                         return -1;
2099                                 while (item_index_matrix [row - 1, col] == 0 && row != 1) {
2100                                         col--;
2101                                         if (col < 0)
2102                                                 return -1;
2103                                 }
2104                                 return item_index_matrix [row - 1, col];
2105
2106                         case Keys.Down:
2107                                 if (row == (rows - 1) || row == Items.Count - 1)
2108                                         return -1;
2109                                 while (item_index_matrix [row + 1, col] == 0) {
2110                                         col--;
2111                                         if (col < 0)
2112                                                 return -1;
2113                                 }
2114                                 return item_index_matrix [row + 1, col];
2115
2116                         default:
2117                                 return -1;
2118                         }
2119                 }
2120
2121                 ListViewItem selection_start;
2122
2123                 private bool SelectItems (ArrayList sel_items)
2124                 {
2125                         bool changed = false;
2126                         foreach (ListViewItem item in SelectedItems)
2127                                 if (!sel_items.Contains (item)) {
2128                                         item.Selected = false;
2129                                         changed = true;
2130                                 }
2131                         foreach (ListViewItem item in sel_items)
2132                                 if (!item.Selected) {
2133                                         item.Selected = true;
2134                                         changed = true;
2135                                 }
2136                         return changed;
2137                 }
2138
2139                 private void UpdateMultiSelection (int index, bool reselect)
2140                 {
2141                         bool shift_pressed = (XplatUI.State.ModifierKeys & Keys.Shift) != 0;
2142                         bool ctrl_pressed = (XplatUI.State.ModifierKeys & Keys.Control) != 0;
2143                         ListViewItem item = items [index];
2144
2145                         if (shift_pressed && selection_start != null) {
2146                                 ArrayList list = new ArrayList ();
2147                                 int start_index = selection_start.Index;
2148                                 int start = Math.Min (start_index, index);
2149                                 int end = Math.Max (start_index, index);
2150                                 if (View == View.Details) {
2151                                         for (int i = start; i <= end; i++)
2152                                                 list.Add (items [i]);
2153                                 } else {
2154                                         ItemMatrixLocation start_item_matrix_location = items_matrix_location [start];
2155                                         ItemMatrixLocation end_item_matrix_location = items_matrix_location [end];
2156                                         int left = Math.Min (start_item_matrix_location.Col, end_item_matrix_location.Col);
2157                                         int right = Math.Max (start_item_matrix_location.Col, end_item_matrix_location.Col);
2158                                         int top = Math.Min (start_item_matrix_location.Row, end_item_matrix_location.Row);
2159                                         int bottom = Math.Max (start_item_matrix_location.Row, end_item_matrix_location.Row);
2160
2161                                         for (int i = 0; i < items.Count; i++) {
2162                                                 ItemMatrixLocation item_matrix_loc = items_matrix_location [i];
2163
2164                                                 if (item_matrix_loc.Row >= top && item_matrix_loc.Row <= bottom &&
2165                                                                 item_matrix_loc.Col >= left && item_matrix_loc.Col <= right)
2166                                                         list.Add (items [i]);
2167                                         }
2168                                 }
2169                                 SelectItems (list);
2170                         } else if (ctrl_pressed) {
2171                                 item.Selected = !item.Selected;
2172                                 selection_start = item;
2173                         } else {
2174                                 if (!reselect) {
2175                                         // do not unselect, and reselect the item
2176                                         foreach (int itemIndex in SelectedIndices) {
2177                                                 if (index == itemIndex)
2178                                                         continue;
2179                                                 items [itemIndex].Selected = false;
2180                                         }
2181                                 } else {
2182                                         SelectedItems.Clear ();
2183                                         item.Selected = true;
2184                                 }
2185                                 selection_start = item;
2186                         }
2187                 }
2188
2189                 internal override bool InternalPreProcessMessage (ref Message msg)
2190                 {
2191                         if (msg.Msg == (int)Msg.WM_KEYDOWN) {
2192                                 Keys key_data = (Keys)msg.WParam.ToInt32();
2193                                 
2194                                 HandleNavKeys (key_data);
2195                         } 
2196                         
2197                         return base.InternalPreProcessMessage (ref msg);
2198                 }
2199
2200                 bool HandleNavKeys (Keys key_data)
2201                 {
2202                         if (Items.Count == 0 || !item_control.Visible)
2203                                 return false;
2204
2205                         if (FocusedItem == null)
2206                                 SetFocusedItem (0);
2207
2208                         switch (key_data) {
2209                         case Keys.End:
2210                                 SelectIndex (Items.Count - 1);
2211                                 break;
2212
2213                         case Keys.Home:
2214                                 SelectIndex (0);
2215                                 break;
2216
2217                         case Keys.Left:
2218                         case Keys.Right:
2219                         case Keys.Up:
2220                         case Keys.Down:
2221                         case Keys.PageUp:
2222                         case Keys.PageDown:
2223                                 SelectIndex (GetAdjustedIndex (key_data));
2224                                 break;
2225
2226                         case Keys.Space:
2227                                 ToggleItemsCheckState ();
2228                                 break;
2229                         case Keys.Enter:
2230                                 if (selected_indices.Count > 0)
2231                                         OnItemActivate (EventArgs.Empty);
2232                                 break;
2233
2234                         default:
2235                                 return false;
2236                         }
2237
2238                         return true;
2239                 }
2240
2241                 void ToggleItemsCheckState ()
2242                 {
2243                         if (!CheckBoxes)
2244                                 return;
2245
2246                         // Don't modify check state if StateImageList has less than 2 elements
2247                         if (StateImageList != null && StateImageList.Images.Count < 2)
2248                                 return;
2249
2250                         if (SelectedIndices.Count > 0) {
2251                                 for (int i = 0; i < SelectedIndices.Count; i++) {
2252                                         ListViewItem item = Items [SelectedIndices [i]];
2253                                         item.Checked = !item.Checked;
2254                                 }
2255                                 return;
2256                         } 
2257                         
2258                         if (FocusedItem != null) {
2259                                 FocusedItem.Checked = !FocusedItem.Checked;
2260                                 SelectIndex (FocusedItem.Index);
2261                         }
2262                 }
2263
2264                 void SelectIndex (int index)
2265                 {
2266                         if (index == -1)
2267                                 return;
2268
2269                         if (MultiSelect)
2270                                 UpdateMultiSelection (index, true);
2271                         else if (!items [index].Selected)
2272                                 items [index].Selected = true;
2273
2274                         SetFocusedItem (index);
2275                         EnsureVisible (index);
2276                 }
2277
2278                 private void ListView_KeyDown (object sender, KeyEventArgs ke)
2279                 {
2280                         if (ke.Handled || Items.Count == 0 || !item_control.Visible)
2281                                 return;
2282
2283                         if (ke.Alt || ke.Control)
2284                                 return;
2285                                 
2286                         ke.Handled = KeySearchString (ke);
2287                 }
2288
2289                 private MouseEventArgs TranslateMouseEventArgs (MouseEventArgs args)
2290                 {
2291                         Point loc = PointToClient (Control.MousePosition);
2292                         return new MouseEventArgs (args.Button, args.Clicks, loc.X, loc.Y, args.Delta);
2293                 }
2294
2295                 internal class ItemControl : Control {
2296
2297                         ListView owner;
2298                         ListViewItem clicked_item;
2299                         ListViewItem last_clicked_item;
2300                         bool hover_processed = false;
2301                         bool checking = false;
2302                         ListViewItem prev_hovered_item;
2303 #if NET_2_0
2304                         ListViewItem prev_tooltip_item;
2305 #endif
2306                         int clicks;
2307                         Point drag_begin = new Point (-1, -1);
2308                         internal int dragged_item_index = -1;
2309                         
2310                         ListViewLabelEditTextBox edit_text_box;
2311                         internal ListViewItem edit_item;
2312                         LabelEditEventArgs edit_args;
2313
2314                         public ItemControl (ListView owner)
2315                         {
2316                                 this.owner = owner;
2317                                 DoubleClick += new EventHandler(ItemsDoubleClick);
2318                                 MouseDown += new MouseEventHandler(ItemsMouseDown);
2319                                 MouseMove += new MouseEventHandler(ItemsMouseMove);
2320                                 MouseHover += new EventHandler(ItemsMouseHover);
2321                                 MouseUp += new MouseEventHandler(ItemsMouseUp);
2322                         }
2323
2324                         void ItemsDoubleClick (object sender, EventArgs e)
2325                         {
2326                                 if (owner.activation == ItemActivation.Standard)
2327                                         owner.OnItemActivate (EventArgs.Empty);
2328                         }
2329
2330                         enum BoxSelect {
2331                                 None,
2332                                 Normal,
2333                                 Shift,
2334                                 Control
2335                         }
2336
2337                         BoxSelect box_select_mode = BoxSelect.None;
2338                         IList prev_selection;
2339                         Point box_select_start;
2340
2341                         Rectangle box_select_rect;
2342                         internal Rectangle BoxSelectRectangle {
2343                                 get { return box_select_rect; }
2344                                 set {
2345                                         if (box_select_rect == value)
2346                                                 return;
2347
2348                                         InvalidateBoxSelectRect ();
2349                                         box_select_rect = value;
2350                                         InvalidateBoxSelectRect ();
2351                                 }
2352                         }
2353
2354                         void InvalidateBoxSelectRect ()
2355                         {
2356                                 if (BoxSelectRectangle.Size.IsEmpty)
2357                                         return;
2358
2359                                 Rectangle edge = BoxSelectRectangle;
2360                                 edge.X -= 1;
2361                                 edge.Y -= 1;
2362                                 edge.Width += 2;
2363                                 edge.Height = 2;
2364                                 Invalidate (edge);
2365                                 edge.Y = BoxSelectRectangle.Bottom - 1;
2366                                 Invalidate (edge);
2367                                 edge.Y = BoxSelectRectangle.Y - 1;
2368                                 edge.Width = 2;
2369                                 edge.Height = BoxSelectRectangle.Height + 2;
2370                                 Invalidate (edge);
2371                                 edge.X = BoxSelectRectangle.Right - 1;
2372                                 Invalidate (edge);
2373                         }
2374
2375                         private Rectangle CalculateBoxSelectRectangle (Point pt)
2376                         {
2377                                 int left = Math.Min (box_select_start.X, pt.X);
2378                                 int right = Math.Max (box_select_start.X, pt.X);
2379                                 int top = Math.Min (box_select_start.Y, pt.Y);
2380                                 int bottom = Math.Max (box_select_start.Y, pt.Y);
2381                                 return Rectangle.FromLTRB (left, top, right, bottom);
2382                         }
2383
2384                         bool BoxIntersectsItem (int index)
2385                         {
2386                                 Rectangle r = new Rectangle (owner.GetItemLocation (index), owner.ItemSize);
2387                                 if (owner.View != View.Details) {
2388                                         r.X += r.Width / 4;
2389                                         r.Y += r.Height / 4;
2390                                         r.Width /= 2;
2391                                         r.Height /= 2;
2392                                 }
2393                                 return BoxSelectRectangle.IntersectsWith (r);
2394                         }
2395
2396                         bool BoxIntersectsText (int index)
2397                         {
2398                                 Rectangle r = owner.Items [index].TextBounds;
2399                                 return BoxSelectRectangle.IntersectsWith (r);
2400                         }
2401
2402                         ArrayList BoxSelectedItems {
2403                                 get {
2404                                         ArrayList result = new ArrayList ();
2405                                         for (int i = 0; i < owner.Items.Count; i++) {
2406                                                 bool intersects;
2407                                                 if (owner.View == View.Details && !owner.FullRowSelect)
2408                                                         intersects = BoxIntersectsText (i);
2409                                                 else
2410                                                         intersects = BoxIntersectsItem (i);
2411
2412                                                 if (intersects)
2413                                                         result.Add (owner.Items [i]);
2414                                         }
2415                                         return result;
2416                                 }
2417                         }
2418
2419                         private bool PerformBoxSelection (Point pt)
2420                         {
2421                                 if (box_select_mode == BoxSelect.None)
2422                                         return false;
2423
2424                                 BoxSelectRectangle = CalculateBoxSelectRectangle (pt);
2425                                 
2426                                 ArrayList box_items = BoxSelectedItems;
2427
2428                                 ArrayList items;
2429
2430                                 switch (box_select_mode) {
2431
2432                                 case BoxSelect.Normal:
2433                                         items = box_items;
2434                                         break;
2435
2436                                 case BoxSelect.Control:
2437                                         items = new ArrayList ();
2438                                         foreach (int index in prev_selection)
2439                                                 if (!box_items.Contains (owner.Items [index]))
2440                                                         items.Add (owner.Items [index]);
2441                                         foreach (ListViewItem item in box_items)
2442                                                 if (!prev_selection.Contains (item.Index))
2443                                                         items.Add (item);
2444                                         break;
2445
2446                                 case BoxSelect.Shift:
2447                                         items = box_items;
2448                                         foreach (ListViewItem item in box_items)
2449                                                 prev_selection.Remove (item.Index);
2450                                         foreach (int index in prev_selection)
2451                                                 items.Add (owner.Items [index]);
2452                                         break;
2453
2454                                 default:
2455                                         throw new Exception ("Unexpected Selection mode: " + box_select_mode);
2456                                 }
2457
2458                                 SuspendLayout ();
2459                                 owner.SelectItems (items);
2460                                 ResumeLayout ();
2461
2462                                 return true;
2463                         }
2464
2465                         private void ItemsMouseDown (object sender, MouseEventArgs me)
2466                         {
2467                                 owner.OnMouseDown (owner.TranslateMouseEventArgs (me));
2468                                 if (owner.items.Count == 0)
2469                                         return;
2470
2471                                 bool box_selecting = false;
2472                                 Size item_size = owner.ItemSize;
2473                                 Point pt = new Point (me.X, me.Y);
2474                                 for (int i = 0; i < owner.items.Count; i++) {
2475                                         Rectangle item_rect = new Rectangle (owner.GetItemLocation (i), item_size);
2476                                         if (!item_rect.Contains (pt))
2477                                                 continue;
2478
2479                                         // Actual item in 'i' position
2480                                         ListViewItem item = owner.items [owner.reordered_items_indices [i]];
2481
2482                                         if (item.CheckRectReal.Contains (pt)) {
2483                                                 // Don't modify check state if we have only one image
2484                                                 // and if we are in 1.1 profile only take into account
2485                                                 // double clicks
2486                                                 if (owner.StateImageList != null && owner.StateImageList.Images.Count < 2 
2487 #if !NET_2_0
2488                                                                 && me.Clicks == 1
2489 #endif
2490                                                                 )
2491                                                         return;
2492
2493                                                 // Generate an extra ItemCheck event when we got two clicks
2494                                                 // (Match weird .Net behaviour)
2495                                                 if (me.Clicks == 2)
2496                                                         item.Checked = !item.Checked;
2497
2498                                                 item.Checked = !item.Checked;
2499                                                 checking = true;
2500                                                 return;
2501                                         }
2502                                         
2503                                         if (owner.View == View.Details) {
2504                                                 bool over_text = item.TextBounds.Contains (pt);
2505                                                 if (owner.FullRowSelect) {
2506                                                         clicked_item = owner.items [i];
2507                                                         bool over_item_column = (me.X > owner.Columns[0].X && me.X < owner.Columns[0].X + owner.Columns[0].Width);
2508                                                         if (!over_text && over_item_column && owner.MultiSelect)
2509                                                                 box_selecting = true;
2510                                                 } else if (over_text)
2511                                                         clicked_item = item;
2512                                                 else
2513                                                         owner.SetFocusedItem (i);
2514                                         } else
2515                                                 clicked_item = item;
2516
2517                                         break;
2518                                 }
2519
2520
2521                                 if (clicked_item != null) {
2522                                         bool changed = !clicked_item.Selected;
2523                                         if (me.Button == MouseButtons.Left || (XplatUI.State.ModifierKeys == Keys.None && changed))
2524                                                 owner.SetFocusedItem (clicked_item.Index);
2525
2526                                         if (owner.MultiSelect) {
2527                                                 bool reselect = (!owner.LabelEdit || changed);
2528                                                 if (me.Button == MouseButtons.Left || (XplatUI.State.ModifierKeys == Keys.None && changed))
2529                                                         owner.UpdateMultiSelection (clicked_item.Index, reselect);
2530                                         } else {
2531                                                 clicked_item.Selected = true;
2532                                         }
2533
2534 #if NET_2_0
2535                                         if (owner.VirtualMode && changed) {
2536                                                 // Broken event - It's not fired from Item.Selected also
2537                                                 ListViewVirtualItemsSelectionRangeChangedEventArgs args = 
2538                                                         new ListViewVirtualItemsSelectionRangeChangedEventArgs (0, owner.items.Count - 1, false);
2539
2540                                                 owner.OnVirtualItemsSelectionRangeChanged (args);
2541                                         }
2542 #endif
2543                                         // Report clicks only if the item was clicked. On MS the
2544                                         // clicks are only raised if you click an item
2545                                         clicks = me.Clicks;
2546                                         if (me.Clicks > 1) {
2547                                                 if (owner.CheckBoxes)
2548                                                         clicked_item.Checked = !clicked_item.Checked;
2549                                         } else if (me.Clicks == 1) {
2550                                                 if (owner.LabelEdit && !changed)
2551                                                         BeginEdit (clicked_item); // this is probably not the correct place to execute BeginEdit
2552                                         }
2553                                 } else {
2554                                         if (owner.MultiSelect)
2555                                                 box_selecting = true;
2556                                         else if (owner.SelectedItems.Count > 0)
2557                                                 owner.SelectedItems.Clear ();
2558                                 }
2559
2560                                 if (box_selecting) {
2561                                         Keys mods = XplatUI.State.ModifierKeys;
2562                                         if ((mods & Keys.Shift) != 0)
2563                                                 box_select_mode = BoxSelect.Shift;
2564                                         else if ((mods & Keys.Control) != 0)
2565                                                 box_select_mode = BoxSelect.Control;
2566                                         else
2567                                                 box_select_mode = BoxSelect.Normal;
2568                                         box_select_start = pt; 
2569                                         prev_selection = owner.SelectedIndices.List.Clone () as IList;
2570                                 }
2571                         }
2572
2573                         private void ItemsMouseMove (object sender, MouseEventArgs me)
2574                         {
2575                                 bool done = PerformBoxSelection (new Point (me.X, me.Y));
2576
2577                                 owner.OnMouseMove (owner.TranslateMouseEventArgs (me));
2578
2579                                 if (done)
2580                                         return;
2581                                 if ((me.Button != MouseButtons.Left && me.Button != MouseButtons.Right) &&
2582                                         !hover_processed && owner.Activation != ItemActivation.OneClick
2583 #if NET_2_0
2584                                         && !owner.ShowItemToolTips
2585 #endif
2586                                                 )
2587                                         return;
2588
2589                                 Point pt = PointToClient (Control.MousePosition);
2590                                 ListViewItem item = owner.GetItemAt (pt.X, pt.Y);
2591
2592                                 if (hover_processed && item != null && item != prev_hovered_item) {
2593                                         hover_processed = false;
2594                                         XplatUI.ResetMouseHover (Handle);
2595                                 }
2596
2597                                 // Need to invalidate the item in HotTracking to show/hide the underline style
2598                                 if (owner.Activation == ItemActivation.OneClick) {
2599                                         if (item == null && owner.HotItemIndex != -1) {
2600 #if NET_2_0
2601                                                 if (owner.HotTracking)
2602                                                         Invalidate (owner.Items [owner.HotItemIndex].Bounds); // Previous one
2603 #endif
2604
2605                                                 Cursor = Cursors.Default;
2606                                                 owner.HotItemIndex = -1;
2607                                         } else if (item != null && owner.HotItemIndex == -1) {
2608 #if NET_2_0
2609                                                 if (owner.HotTracking)
2610                                                         Invalidate (item.Bounds);
2611 #endif
2612
2613                                                 Cursor = Cursors.Hand;
2614                                                 owner.HotItemIndex = item.Index;
2615                                         }
2616                                 }
2617
2618                                 if (me.Button == MouseButtons.Left || me.Button == MouseButtons.Right) {
2619                                         if (drag_begin.X == -1 && drag_begin.Y == -1) {
2620                                                 if (item != null) {
2621                                                         drag_begin = new Point (me.X, me.Y);
2622                                                         dragged_item_index = item.Index;
2623                                                 }
2624
2625                                         } else {
2626                                                 Rectangle r = new Rectangle (drag_begin, SystemInformation.DragSize);
2627                                                 if (!r.Contains (me.X, me.Y)) {
2628                                                         ListViewItem dragged_item  = owner.items [dragged_item_index];
2629                                                         owner.OnItemDrag (new ItemDragEventArgs (me.Button, dragged_item));
2630
2631                                                         drag_begin = new Point (-1, -1);
2632                                                         dragged_item_index = -1;
2633                                                 }
2634                                         }
2635                                 }
2636
2637 #if NET_2_0
2638                                 if (owner.ShowItemToolTips) {
2639                                         if (item == null) {
2640                                                 owner.item_tooltip.Active = false;
2641                                                 prev_tooltip_item = null;
2642                                         } else if (item != prev_tooltip_item && item.ToolTipText.Length > 0) {
2643                                                 owner.item_tooltip.Active = true;
2644                                                 owner.item_tooltip.SetToolTip (owner, item.ToolTipText);
2645                                                 prev_tooltip_item = item;
2646                                         }
2647                                 }
2648 #endif
2649
2650                         }
2651
2652                         private void ItemsMouseHover (object sender, EventArgs e)
2653                         {
2654                                 if (owner.hover_pending) {
2655                                         owner.OnMouseHover (e);
2656                                         owner.hover_pending = false;
2657                                 }
2658
2659                                 if (Capture)
2660                                         return;
2661
2662                                 hover_processed = true;
2663                                 Point pt = PointToClient (Control.MousePosition);
2664                                 ListViewItem item = owner.GetItemAt (pt.X, pt.Y);
2665                                 if (item == null)
2666                                         return;
2667
2668                                 prev_hovered_item = item;
2669
2670                                 if (owner.HoverSelection) {
2671                                         if (owner.MultiSelect)
2672                                                 owner.UpdateMultiSelection (item.Index, true);
2673                                         else
2674                                                 item.Selected = true;
2675                                         
2676                                         owner.SetFocusedItem (item.Index);
2677                                         Select (); // Make sure we have the focus, since MouseHover doesn't give it to us
2678                                 }
2679
2680 #if NET_2_0
2681                                 owner.OnItemMouseHover (new ListViewItemMouseHoverEventArgs (item));
2682 #endif
2683                         }
2684
2685                         void HandleClicks (MouseEventArgs me)
2686                         {
2687                                 // if the click is not on an item,
2688                                 // clicks remains as 0
2689                                 if (clicks > 1) {
2690 #if !NET_2_0
2691                                         owner.OnDoubleClick (EventArgs.Empty);
2692                                 } else if (clicks == 1) {
2693                                         owner.OnClick (EventArgs.Empty);
2694 #else
2695                                         owner.OnDoubleClick (EventArgs.Empty);
2696                                         owner.OnMouseDoubleClick (me);
2697                                 } else if (clicks == 1) {
2698                                         owner.OnClick (EventArgs.Empty);
2699                                         owner.OnMouseClick (me);
2700 #endif
2701                                 }
2702
2703                                 clicks = 0;
2704                         }
2705
2706                         private void ItemsMouseUp (object sender, MouseEventArgs me)
2707                         {
2708                                 MouseEventArgs owner_me = owner.TranslateMouseEventArgs (me);
2709                                 HandleClicks (owner_me);
2710
2711                                 Capture = false;
2712                                 if (owner.Items.Count == 0) {
2713                                         ResetMouseState ();
2714                                         owner.OnMouseUp (owner_me);
2715                                         return;
2716                                 }
2717
2718                                 Point pt = new Point (me.X, me.Y);
2719
2720                                 Rectangle rect = Rectangle.Empty;
2721                                 if (clicked_item != null) {
2722                                         if (owner.view == View.Details && !owner.full_row_select)
2723                                                 rect = clicked_item.GetBounds (ItemBoundsPortion.Label);
2724                                         else
2725                                                 rect = clicked_item.Bounds;
2726
2727                                         if (rect.Contains (pt)) {
2728                                                 switch (owner.activation) {
2729                                                 case ItemActivation.OneClick:
2730                                                         owner.OnItemActivate (EventArgs.Empty);
2731                                                         break;
2732
2733                                                 case ItemActivation.TwoClick:
2734                                                         if (last_clicked_item == clicked_item) {
2735                                                                 owner.OnItemActivate (EventArgs.Empty);
2736                                                                 last_clicked_item = null;
2737                                                         } else
2738                                                                 last_clicked_item = clicked_item;
2739                                                         break;
2740                                                 default:
2741                                                         // DoubleClick activation is handled in another handler
2742                                                         break;
2743                                                 }
2744                                         }
2745                                 } else if (!checking && owner.SelectedItems.Count > 0 && BoxSelectRectangle.Size.IsEmpty) {
2746                                         // Need this to clean up background clicks
2747                                         owner.SelectedItems.Clear ();
2748                                 }
2749
2750                                 ResetMouseState ();
2751                                 owner.OnMouseUp (owner_me);
2752                         }
2753
2754                         private void ResetMouseState ()
2755                         {                               
2756                                 clicked_item = null;
2757                                 box_select_start = Point.Empty;
2758                                 BoxSelectRectangle = Rectangle.Empty;
2759                                 prev_selection = null;
2760                                 box_select_mode = BoxSelect.None;
2761                                 checking = false;
2762
2763                                 // Clean these bits in case the mouse buttons were
2764                                 // released before firing ItemDrag
2765                                 dragged_item_index = -1;
2766                                 drag_begin = new Point (-1, -1);
2767                         }
2768                         
2769                         private void LabelEditFinished (object sender, EventArgs e)
2770                         {
2771                                 EndEdit (edit_item);
2772                         }
2773
2774                         private void LabelEditCancelled (object sender, EventArgs e)
2775                         {
2776                                 edit_args.SetLabel (null);
2777                                 EndEdit (edit_item);
2778                         }
2779
2780                         private void LabelTextChanged (object sender, EventArgs e)
2781                         {
2782                                 if (edit_args != null)
2783                                         edit_args.SetLabel (edit_text_box.Text);
2784                         }
2785
2786                         internal void BeginEdit (ListViewItem item)
2787                         {
2788                                 if (edit_item != null)
2789                                         EndEdit (edit_item);
2790                                 
2791                                 if (edit_text_box == null) {
2792                                         edit_text_box = new ListViewLabelEditTextBox ();
2793                                         edit_text_box.BorderStyle = BorderStyle.FixedSingle;
2794                                         edit_text_box.EditingCancelled += new EventHandler (LabelEditCancelled);
2795                                         edit_text_box.EditingFinished += new EventHandler (LabelEditFinished);
2796                                         edit_text_box.TextChanged += new EventHandler (LabelTextChanged);
2797                                         edit_text_box.Visible = false;
2798                                         Controls.Add (edit_text_box);
2799                                 }
2800                                 
2801                                 item.EnsureVisible();
2802                                 
2803                                 edit_text_box.Reset ();
2804                                 
2805                                 switch (owner.view) {
2806                                         case View.List:
2807                                         case View.SmallIcon:
2808                                         case View.Details:
2809                                                 edit_text_box.TextAlign = HorizontalAlignment.Left;
2810                                                 edit_text_box.Bounds = item.GetBounds (ItemBoundsPortion.Label);
2811                                                 SizeF sizef = TextRenderer.MeasureString (item.Text, item.Font);
2812                                                 edit_text_box.Width = (int)sizef.Width + 4;
2813                                                 edit_text_box.MaxWidth = owner.ClientRectangle.Width - edit_text_box.Bounds.X;
2814                                                 edit_text_box.WordWrap = false;
2815                                                 edit_text_box.Multiline = false;
2816                                                 break;
2817                                         case View.LargeIcon:
2818                                                 edit_text_box.TextAlign = HorizontalAlignment.Center;
2819                                                 edit_text_box.Bounds = item.GetBounds (ItemBoundsPortion.Label);
2820                                                 sizef = TextRenderer.MeasureString (item.Text, item.Font);
2821                                                 edit_text_box.Width = (int)sizef.Width + 4;
2822                                                 edit_text_box.MaxWidth = item.GetBounds(ItemBoundsPortion.Entire).Width;
2823                                                 edit_text_box.MaxHeight = owner.ClientRectangle.Height - edit_text_box.Bounds.Y;
2824                                                 edit_text_box.WordWrap = true;
2825                                                 edit_text_box.Multiline = true;
2826                                                 break;
2827                                 }
2828
2829                                 edit_item = item;
2830
2831                                 edit_text_box.Text = item.Text;
2832                                 edit_text_box.Font = item.Font;
2833                                 edit_text_box.Visible = true;
2834                                 edit_text_box.Focus ();
2835                                 edit_text_box.SelectAll ();
2836
2837                                 edit_args = new LabelEditEventArgs (owner.Items.IndexOf (edit_item));
2838                                 owner.OnBeforeLabelEdit (edit_args);
2839
2840                                 if (edit_args.CancelEdit)
2841                                         EndEdit (item);
2842                         }
2843
2844                         internal void CancelEdit (ListViewItem item)
2845                         {
2846                                 // do nothing if there's no item being edited, or if the
2847                                 // item being edited is not the one passed in
2848                                 if (edit_item == null || edit_item != item)
2849                                         return;
2850
2851                                 edit_args.SetLabel (null);
2852                                 EndEdit (item);
2853                         }
2854
2855                         internal void EndEdit (ListViewItem item)
2856                         {
2857                                 // do nothing if there's no item being edited, or if the
2858                                 // item being edited is not the one passed in
2859                                 if (edit_item == null || edit_item != item)
2860                                         return;
2861
2862                                 if (edit_text_box != null) {
2863                                         if (edit_text_box.Visible)
2864                                                 edit_text_box.Visible = false;
2865                                         // ensure listview gets focus
2866                                         owner.Focus ();
2867                                 }
2868
2869                                 // Same as TreeView.EndEdit: need to have focus in synch
2870                                 Application.DoEvents ();
2871
2872                                 // 
2873                                 // Create a new instance, since we could get a call to BeginEdit
2874                                 // from the handler and have fields out of synch
2875                                 //
2876                                 LabelEditEventArgs args = new LabelEditEventArgs (item.Index, edit_args.Label);
2877                                 edit_item = null;
2878
2879                                 owner.OnAfterLabelEdit (args);
2880                                 if (!args.CancelEdit && args.Label != null)
2881                                         item.Text = args.Label;
2882                         }
2883
2884                         internal override void OnPaintInternal (PaintEventArgs pe)
2885                         {
2886                                 ThemeEngine.Current.DrawListViewItems (pe.Graphics, pe.ClipRectangle, owner);
2887                         }
2888
2889                         protected override void WndProc (ref Message m)
2890                         {
2891                                 switch ((Msg)m.Msg) {
2892                                 case Msg.WM_KILLFOCUS:
2893                                         owner.Select (false, true);
2894                                         break;
2895                                 case Msg.WM_SETFOCUS:
2896                                         owner.Select (false, true);
2897                                         break;
2898                                 case Msg.WM_LBUTTONDOWN:
2899                                         if (!Focused)
2900                                                 owner.Select (false, true);
2901                                         break;
2902                                 case Msg.WM_RBUTTONDOWN:
2903                                         if (!Focused)
2904                                                 owner.Select (false, true);
2905                                         break;
2906                                 default:
2907                                         break;
2908                                 }
2909                                 base.WndProc (ref m);
2910                         }
2911                 }
2912                 
2913                 internal class ListViewLabelEditTextBox : TextBox
2914                 {
2915                         int max_width = -1;
2916                         int min_width = -1;
2917                         
2918                         int max_height = -1;
2919                         int min_height = -1;
2920                         
2921                         int old_number_lines = 1;
2922                         
2923                         SizeF text_size_one_char;
2924                         
2925                         public ListViewLabelEditTextBox ()
2926                         {
2927                                 min_height = DefaultSize.Height;
2928                                 text_size_one_char = TextRenderer.MeasureString ("B", Font);
2929                         }
2930                         
2931                         public int MaxWidth {
2932                                 set {
2933                                         if (value < min_width)
2934                                                 max_width = min_width;
2935                                         else
2936                                                 max_width = value;
2937                                 }
2938                         }
2939                         
2940                         public int MaxHeight {
2941                                 set {
2942                                         if (value < min_height)
2943                                                 max_height = min_height;
2944                                         else
2945                                                 max_height = value;
2946                                 }
2947                         }
2948                         
2949                         public new int Width {
2950                                 get {
2951                                         return base.Width;
2952                                 }
2953                                 set {
2954                                         min_width = value;
2955                                         base.Width = value;
2956                                 }
2957                         }
2958                         
2959                         public override Font Font {
2960                                 get {
2961                                         return base.Font;
2962                                 }
2963                                 set {
2964                                         base.Font = value;
2965                                         text_size_one_char = TextRenderer.MeasureString ("B", Font);
2966                                 }
2967                         }
2968                         
2969                         protected override void OnTextChanged (EventArgs e)
2970                         {
2971                                 SizeF text_size = TextRenderer.MeasureString (Text, Font);
2972                                 
2973                                 int new_width = (int)text_size.Width + 8;
2974                                 
2975                                 if (!Multiline)
2976                                         ResizeTextBoxWidth (new_width);
2977                                 else {
2978                                         if (Width != max_width)
2979                                                 ResizeTextBoxWidth (new_width);
2980                                         
2981                                         int number_lines = Lines.Length;
2982                                         
2983                                         if (number_lines != old_number_lines) {
2984                                                 int new_height = number_lines * (int)text_size_one_char.Height + 4;
2985                                                 old_number_lines = number_lines;
2986                                                 
2987                                                 ResizeTextBoxHeight (new_height);
2988                                         }
2989                                 }
2990                                 
2991                                 base.OnTextChanged (e);
2992                         }
2993                         
2994                         protected override bool IsInputKey (Keys key_data)
2995                         {
2996                                 if ((key_data & Keys.Alt) == 0) {
2997                                         switch (key_data & Keys.KeyCode) {
2998                                                 case Keys.Enter:
2999                                                         return true;
3000                                                 case Keys.Escape:
3001                                                         return true;
3002                                         }
3003                                 }
3004                                 return base.IsInputKey (key_data);
3005                         }
3006                         
3007                         protected override void OnKeyDown (KeyEventArgs e)
3008                         {
3009                                 if (!Visible)
3010                                         return;
3011
3012                                 switch (e.KeyCode) {
3013                                 case Keys.Return:
3014                                         Visible = false;
3015                                         e.Handled = true;
3016                                         OnEditingFinished (e);
3017                                         break;
3018                                 case Keys.Escape:
3019                                         Visible = false;
3020                                         e.Handled = true;
3021                                         OnEditingCancelled (e);
3022                                         break;
3023                                 }
3024                         }
3025                         
3026                         protected override void OnLostFocus (EventArgs e)
3027                         {
3028                                 if (Visible) {
3029                                         OnEditingFinished (e);
3030                                 }
3031                         }
3032
3033                         protected void OnEditingCancelled (EventArgs e)
3034                         {
3035                                 EventHandler eh = (EventHandler)(Events [EditingCancelledEvent]);
3036                                 if (eh != null)
3037                                         eh (this, e);
3038                         }
3039                         
3040                         protected void OnEditingFinished (EventArgs e)
3041                         {
3042                                 EventHandler eh = (EventHandler)(Events [EditingFinishedEvent]);
3043                                 if (eh != null)
3044                                         eh (this, e);
3045                         }
3046                         
3047                         private void ResizeTextBoxWidth (int new_width)
3048                         {
3049                                 if (new_width > max_width)
3050                                         base.Width = max_width;
3051                                 else 
3052                                 if (new_width >= min_width)
3053                                         base.Width = new_width;
3054                                 else
3055                                         base.Width = min_width;
3056                         }
3057                         
3058                         private void ResizeTextBoxHeight (int new_height)
3059                         {
3060                                 if (new_height > max_height)
3061                                         base.Height = max_height;
3062                                 else 
3063                                 if (new_height >= min_height)
3064                                         base.Height = new_height;
3065                                 else
3066                                         base.Height = min_height;
3067                         }
3068                         
3069                         public void Reset ()
3070                         {
3071                                 max_width = -1;
3072                                 min_width = -1;
3073                                 
3074                                 max_height = -1;
3075                                 
3076                                 old_number_lines = 1;
3077                                 
3078                                 Text = String.Empty;
3079                                 
3080                                 Size = DefaultSize;
3081                         }
3082
3083                         static object EditingCancelledEvent = new object ();
3084                         public event EventHandler EditingCancelled {
3085                                 add { Events.AddHandler (EditingCancelledEvent, value); }
3086                                 remove { Events.RemoveHandler (EditingCancelledEvent, value); }
3087                         }
3088
3089                         static object EditingFinishedEvent = new object ();
3090                         public event EventHandler EditingFinished {
3091                                 add { Events.AddHandler (EditingFinishedEvent, value); }
3092                                 remove { Events.RemoveHandler (EditingFinishedEvent, value); }
3093                         }
3094                 }
3095
3096                 internal override void OnPaintInternal (PaintEventArgs pe)
3097                 {
3098                         if (updating)
3099                                 return;
3100                                 
3101                         CalculateScrollBars ();
3102                 }
3103
3104                 void FocusChanged (object o, EventArgs args)
3105                 {
3106                         if (Items.Count == 0)
3107                                 return;
3108
3109                         if (FocusedItem == null)
3110                                 SetFocusedItem (0);
3111
3112                         ListViewItem focused_item = FocusedItem;
3113
3114                         if (focused_item.ListView != null) {
3115                                 item_control.Invalidate (focused_item.Bounds);
3116                                 focused_item.Layout ();
3117                                 item_control.Invalidate (focused_item.Bounds);
3118                         }
3119                 }
3120
3121                 private void ListView_MouseEnter (object sender, EventArgs args)
3122                 {
3123                         hover_pending = true; // Need a hover event for every Enter/Leave cycle
3124                 }
3125
3126                 private void ListView_MouseWheel (object sender, MouseEventArgs me)
3127                 {
3128                         if (Items.Count == 0)
3129                                 return;
3130
3131                         int lines = me.Delta / 120;
3132
3133                         if (lines == 0)
3134                                 return;
3135
3136                         switch (View) {
3137                         case View.Details:
3138                         case View.SmallIcon:
3139                                 Scroll (v_scroll, -ItemSize.Height * SystemInformation.MouseWheelScrollLines * lines);
3140                                 break;
3141                         case View.LargeIcon:
3142                                 Scroll (v_scroll, -(ItemSize.Height + ThemeEngine.Current.ListViewVerticalSpacing)  * lines);
3143                                 break;
3144                         case View.List:
3145                                 Scroll (h_scroll, -ItemSize.Width * lines);
3146                                 break;
3147 #if NET_2_0
3148                         case View.Tile:
3149                                 Scroll (v_scroll, -(ItemSize.Height + ThemeEngine.Current.ListViewVerticalSpacing) * 2 * lines);
3150                                 break;
3151 #endif
3152                         }
3153                 }
3154
3155                 private void ListView_SizeChanged (object sender, EventArgs e)
3156                 {
3157                         CalculateListView (alignment);
3158                 }
3159                 
3160                 private void SetFocusedItem (int index)
3161                 {
3162                         if (index != -1)
3163                                 items [index].Focused = true;
3164                         else if (focused_item_index != -1 && focused_item_index < items.Count) // Previous focused item
3165                                 items [focused_item_index].Focused = false;
3166
3167                         focused_item_index = index;
3168                 }
3169
3170                 private void HorizontalScroller (object sender, EventArgs e)
3171                 {
3172                         item_control.EndEdit (item_control.edit_item);
3173                         
3174                         // Avoid unnecessary flickering, when button is
3175                         // kept pressed at the end
3176                         if (h_marker != h_scroll.Value) {
3177                                 
3178                                 int pixels = h_marker - h_scroll.Value;
3179                                 
3180                                 h_marker = h_scroll.Value;
3181                                 if (header_control.Visible)
3182                                         XplatUI.ScrollWindow (header_control.Handle, pixels, 0, false);
3183
3184                                 XplatUI.ScrollWindow (item_control.Handle, pixels, 0, false);
3185                         }
3186                 }
3187
3188                 private void VerticalScroller (object sender, EventArgs e)
3189                 {
3190                         item_control.EndEdit (item_control.edit_item);
3191                         
3192                         // Avoid unnecessary flickering, when button is
3193                         // kept pressed at the end
3194                         if (v_marker != v_scroll.Value) {
3195                                 int pixels = v_marker - v_scroll.Value;
3196                                 Rectangle area = item_control.ClientRectangle;
3197                                 if (header_control.Visible) {
3198                                         area.Y += header_control.Height;
3199                                         area.Height -= header_control.Height;
3200                                 }
3201
3202                                 v_marker = v_scroll.Value;
3203                                 XplatUI.ScrollWindow (item_control.Handle, area, 0, pixels, false);
3204                         }
3205                 }
3206
3207                 internal override bool IsInputCharInternal (char charCode)
3208                 {
3209                         return true;
3210                 }
3211                 #endregion      // Internal Methods Properties
3212
3213                 #region Protected Methods
3214                 protected override void CreateHandle ()
3215                 {
3216                         base.CreateHandle ();
3217                         for (int i = 0; i < SelectedItems.Count; i++)
3218                                 OnSelectedIndexChanged (EventArgs.Empty);
3219                 }
3220
3221                 protected override void Dispose (bool disposing)
3222                 {
3223                         if (disposing) {
3224                                 h_scroll.Dispose ();
3225                                 v_scroll.Dispose ();
3226                                 
3227                                 large_image_list = null;
3228                                 small_image_list = null;
3229                                 state_image_list = null;
3230
3231                                 foreach (ColumnHeader col in columns)
3232                                         col.SetListView (null);
3233
3234 #if NET_2_0
3235                                 if (!virtual_mode) // In virtual mode we don't save the items
3236 #endif
3237                                         foreach (ListViewItem item in items)
3238                                                 item.Owner = null;
3239                         }
3240                         
3241                         base.Dispose (disposing);
3242                 }
3243
3244                 protected override bool IsInputKey (Keys keyData)
3245                 {
3246                         switch (keyData) {
3247                         case Keys.Up:
3248                         case Keys.Down:
3249                         case Keys.PageUp:
3250                         case Keys.PageDown:
3251                         case Keys.Right:
3252                         case Keys.Left:
3253                         case Keys.End:
3254                         case Keys.Home:
3255                                 return true;
3256
3257                         default:
3258                                 break;
3259                         }
3260                         
3261                         return base.IsInputKey (keyData);
3262                 }
3263
3264                 protected virtual void OnAfterLabelEdit (LabelEditEventArgs e)
3265                 {
3266                         LabelEditEventHandler eh = (LabelEditEventHandler)(Events [AfterLabelEditEvent]);
3267                         if (eh != null)
3268                                 eh (this, e);
3269                 }
3270
3271 #if NET_2_0
3272                 protected override void OnBackgroundImageChanged (EventArgs args)
3273                 {
3274                         item_control.BackgroundImage = BackgroundImage;
3275                         base.OnBackgroundImageChanged (args);
3276                 }
3277 #endif
3278
3279                 protected virtual void OnBeforeLabelEdit (LabelEditEventArgs e)
3280                 {
3281                         LabelEditEventHandler eh = (LabelEditEventHandler)(Events [BeforeLabelEditEvent]);
3282                         if (eh != null)
3283                                 eh (this, e);
3284                 }
3285
3286                 protected virtual void OnColumnClick (ColumnClickEventArgs e)
3287                 {
3288                         ColumnClickEventHandler eh = (ColumnClickEventHandler)(Events [ColumnClickEvent]);
3289                         if (eh != null)
3290                                 eh (this, e);
3291                 }
3292
3293 #if NET_2_0
3294                 protected internal virtual void OnDrawColumnHeader(DrawListViewColumnHeaderEventArgs e)
3295                 {
3296                         DrawListViewColumnHeaderEventHandler eh = (DrawListViewColumnHeaderEventHandler)(Events[DrawColumnHeaderEvent]);
3297                         if (eh != null)
3298                                 eh(this, e);
3299                 }
3300
3301                 protected internal virtual void OnDrawItem(DrawListViewItemEventArgs e)
3302                 {
3303                         DrawListViewItemEventHandler eh = (DrawListViewItemEventHandler)(Events[DrawItemEvent]);
3304                         if (eh != null)
3305                                 eh(this, e);
3306                 }
3307
3308                 protected internal virtual void OnDrawSubItem(DrawListViewSubItemEventArgs e)
3309                 {
3310                         DrawListViewSubItemEventHandler eh = (DrawListViewSubItemEventHandler)(Events[DrawSubItemEvent]);
3311                         if (eh != null)
3312                                 eh(this, e);
3313                 }
3314
3315 #else
3316                 protected override void OnEnabledChanged (EventArgs e)
3317                 {
3318                         base.OnEnabledChanged (e);
3319                 }
3320 #endif
3321
3322                 protected override void OnFontChanged (EventArgs e)
3323                 {
3324                         base.OnFontChanged (e);
3325                         Redraw (true);
3326                 }
3327
3328                 protected override void OnHandleCreated (EventArgs e)
3329                 {
3330                         base.OnHandleCreated (e);
3331                         CalculateListView (alignment);
3332 #if NET_2_0
3333                         if (!virtual_mode) // Sorting is not allowed in virtual mode
3334 #endif
3335                                 Sort ();
3336                 }
3337
3338                 protected override void OnHandleDestroyed (EventArgs e)
3339                 {
3340                         base.OnHandleDestroyed (e);
3341                 }
3342
3343                 protected virtual void OnItemActivate (EventArgs e)
3344                 {
3345                         EventHandler eh = (EventHandler)(Events [ItemActivateEvent]);
3346                         if (eh != null)
3347                                 eh (this, e);
3348                 }
3349
3350                 protected internal virtual void OnItemCheck (ItemCheckEventArgs ice)
3351                 {
3352                         ItemCheckEventHandler eh = (ItemCheckEventHandler)(Events [ItemCheckEvent]);
3353                         if (eh != null)
3354                                 eh (this, ice);
3355                 }
3356
3357 #if NET_2_0
3358                 protected internal virtual void OnItemChecked (ItemCheckedEventArgs icea)
3359                 {
3360                         ItemCheckedEventHandler eh = (ItemCheckedEventHandler)(Events [ItemCheckedEvent]);
3361                         if (eh != null)
3362                                 eh (this, icea);
3363                 }
3364 #endif
3365
3366                 protected virtual void OnItemDrag (ItemDragEventArgs e)
3367                 {
3368                         ItemDragEventHandler eh = (ItemDragEventHandler)(Events [ItemDragEvent]);
3369                         if (eh != null)
3370                                 eh (this, e);
3371                 }
3372
3373 #if NET_2_0
3374                 protected virtual void OnItemMouseHover (ListViewItemMouseHoverEventArgs args)
3375                 {
3376                         ListViewItemMouseHoverEventHandler eh = (ListViewItemMouseHoverEventHandler)(Events [ItemMouseHoverEvent]);
3377                         if (eh != null)
3378                                 eh (this, args);
3379                 }
3380
3381                 protected internal virtual void OnItemSelectionChanged (ListViewItemSelectionChangedEventArgs args)
3382                 {
3383                         ListViewItemSelectionChangedEventHandler eh = 
3384                                 (ListViewItemSelectionChangedEventHandler) Events [ItemSelectionChangedEvent];
3385                         if (eh != null)
3386                                 eh (this, args);
3387                 }
3388
3389                 protected override void OnMouseHover (EventArgs args)
3390                 {
3391                         base.OnMouseHover (args);
3392                 }
3393
3394                 protected override void OnParentChanged (EventArgs args)
3395                 {
3396                         base.OnParentChanged (args);
3397                 }
3398 #endif
3399
3400                 protected virtual void OnSelectedIndexChanged (EventArgs e)
3401                 {
3402                         EventHandler eh = (EventHandler)(Events [SelectedIndexChangedEvent]);
3403                         if (eh != null)
3404                                 eh (this, e);
3405                 }
3406
3407                 protected override void OnSystemColorsChanged (EventArgs e)
3408                 {
3409                         base.OnSystemColorsChanged (e);
3410                 }
3411
3412 #if NET_2_0
3413                 protected virtual void OnCacheVirtualItems (CacheVirtualItemsEventArgs args)
3414                 {
3415                         EventHandler eh = (EventHandler)Events [CacheVirtualItemsEvent];
3416                         if (eh != null)
3417                                 eh (this, args);
3418                 }
3419
3420                 protected virtual void OnRetrieveVirtualItem (RetrieveVirtualItemEventArgs args)
3421                 {
3422                         RetrieveVirtualItemEventHandler eh = (RetrieveVirtualItemEventHandler)Events [RetrieveVirtualItemEvent];
3423                         if (eh != null)
3424                                 eh (this, args);
3425                 }
3426
3427                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3428                 protected virtual void OnRightToLeftLayoutChanged (EventArgs e)
3429                 {
3430                         EventHandler eh = (EventHandler)Events[RightToLeftLayoutChangedEvent];
3431                         if (eh != null)
3432                                 eh (this, e);
3433                 }
3434
3435                 protected virtual void OnSearchForVirtualItem (SearchForVirtualItemEventArgs args)
3436                 {
3437                         SearchForVirtualItemEventHandler eh = (SearchForVirtualItemEventHandler) Events [SearchForVirtualItemEvent];
3438                         if (eh != null)
3439                                 eh (this, args);
3440                 }
3441                 
3442                 protected virtual void OnVirtualItemsSelectionRangeChanged (ListViewVirtualItemsSelectionRangeChangedEventArgs args)
3443                 {
3444                         ListViewVirtualItemsSelectionRangeChangedEventHandler eh = 
3445                                 (ListViewVirtualItemsSelectionRangeChangedEventHandler) Events [VirtualItemsSelectionRangeChangedEvent];
3446                         if (eh != null)
3447                                 eh (this, args);
3448                 }
3449 #endif
3450
3451                 protected void RealizeProperties ()
3452                 {
3453                         // FIXME: TODO
3454                 }
3455
3456                 protected void UpdateExtendedStyles ()
3457                 {
3458                         // FIXME: TODO
3459                 }
3460
3461                 bool refocusing = false;
3462
3463                 protected override void WndProc (ref Message m)
3464                 {
3465                         switch ((Msg)m.Msg) {
3466                         case Msg.WM_KILLFOCUS:
3467                                 Control receiver = Control.FromHandle (m.WParam);
3468                                 if (receiver == item_control) {
3469                                         has_focus = false;
3470                                         refocusing = true;
3471                                         return;
3472                                 }
3473                                 break;
3474                         case Msg.WM_SETFOCUS:
3475                                 if (refocusing) {
3476                                         has_focus = true;
3477                                         refocusing = false;
3478                                         return;
3479                                 }
3480                                 break;
3481                         default:
3482                                 break;
3483                         }
3484                         base.WndProc (ref m);
3485                 }
3486                 #endregion // Protected Methods
3487
3488                 #region Public Instance Methods
3489                 public void ArrangeIcons ()
3490                 {
3491                         ArrangeIcons (this.alignment);
3492                 }
3493
3494                 public void ArrangeIcons (ListViewAlignment alignment)
3495                 {
3496                         // Icons are arranged only if view is set to LargeIcon or SmallIcon
3497                         if (view == View.LargeIcon || view == View.SmallIcon) {
3498                                 this.CalculateListView (alignment);
3499                                 // we have done the calculations already
3500                                 this.Redraw (false);
3501                         }
3502                 }
3503
3504 #if NET_2_0
3505                 public void AutoResizeColumn (int columnIndex, ColumnHeaderAutoResizeStyle headerAutoResize)
3506                 {
3507                         if (columnIndex < 0 || columnIndex >= columns.Count)
3508                                 throw new ArgumentOutOfRangeException ("columnIndex");
3509
3510                         columns [columnIndex].AutoResize (headerAutoResize);
3511                 }
3512
3513                 public void AutoResizeColumns (ColumnHeaderAutoResizeStyle headerAutoResize)
3514                 {
3515                         BeginUpdate ();
3516                         foreach (ColumnHeader col in columns) 
3517                                 col.AutoResize (headerAutoResize);
3518                         EndUpdate ();
3519                 }
3520 #endif
3521
3522                 public void BeginUpdate ()
3523                 {
3524                         // flag to avoid painting
3525                         updating = true;
3526                 }
3527
3528                 public void Clear ()
3529                 {
3530                         columns.Clear ();
3531                         items.Clear (); // Redraw (true) called here
3532                 }
3533
3534                 public void EndUpdate ()
3535                 {
3536                         // flag to avoid painting
3537                         updating = false;
3538
3539                         // probably, now we need a redraw with recalculations
3540                         this.Redraw (true);
3541                 }
3542
3543                 public void EnsureVisible (int index)
3544                 {
3545                         if (index < 0 || index >= items.Count || scrollable == false)
3546                                 return;
3547
3548                         Rectangle view_rect = item_control.ClientRectangle;
3549                         Rectangle bounds = new Rectangle (GetItemLocation (index), ItemSize);
3550
3551                         if (view_rect.Contains (bounds))
3552                                 return;
3553
3554                         if (View != View.Details) {
3555                                 if (bounds.Left < 0)
3556                                         h_scroll.Value += bounds.Left;
3557                                 else if (bounds.Right > view_rect.Right)
3558                                         h_scroll.Value += (bounds.Right - view_rect.Right);
3559                         }
3560
3561                         if (bounds.Top < 0)
3562                                 v_scroll.Value += bounds.Top;
3563                         else if (bounds.Bottom > view_rect.Bottom)
3564                                 v_scroll.Value += (bounds.Bottom - view_rect.Bottom);
3565                 }
3566
3567 #if NET_2_0
3568                 public ListViewItem FindItemWithText (string text)
3569                 {
3570                         if (items.Count == 0)
3571                                 return null;
3572
3573                         return FindItemWithText (text, true, 0, true);
3574                 }
3575
3576                 public ListViewItem FindItemWithText (string text, bool includeSubItems, int startIndex)
3577                 {
3578                         return FindItemWithText (text, includeSubItems, startIndex, true);
3579                 }
3580
3581                 public ListViewItem FindItemWithText (string text, bool includeSubItems, int startIndex, bool prefixSearch)
3582                 {
3583                         if (startIndex < 0 || startIndex >= items.Count)
3584                                 throw new ArgumentOutOfRangeException ("startIndex");
3585
3586                         if (text == null)
3587                                 throw new ArgumentNullException ("text");
3588
3589                         if (virtual_mode) {
3590                                 SearchForVirtualItemEventArgs args = new SearchForVirtualItemEventArgs (true,
3591                                                 prefixSearch, includeSubItems, text, Point.Empty, 
3592                                                 SearchDirectionHint.Down, startIndex);
3593
3594                                 OnSearchForVirtualItem (args);
3595                                 int idx = args.Index;
3596                                 if (idx >= 0 && idx < virtual_list_size)
3597                                         return items [idx];
3598
3599                                 return null;
3600                         }
3601
3602                         for (int i = startIndex; i < items.Count; i++) {
3603                                 ListViewItem lvi = items [i];
3604
3605                                 if ((prefixSearch && lvi.Text.StartsWith (text, true, CultureInfo.CurrentCulture)) // prefix search
3606                                                 || String.Compare (lvi.Text, text, true) == 0) // match
3607                                         return lvi;
3608                         }
3609
3610                         if (includeSubItems) {
3611                                 for (int i = startIndex; i < items.Count; i++) {
3612                                         ListViewItem lvi = items [i];
3613                                         foreach (ListViewItem.ListViewSubItem sub_item in lvi.SubItems)
3614                                                 if ((prefixSearch && sub_item.Text.StartsWith (text, true, CultureInfo.CurrentCulture))
3615                                                                 || String.Compare (sub_item.Text, text, true) == 0)
3616                                                         return lvi;
3617                                 }
3618                         }
3619
3620                         return null;
3621                 }
3622
3623                 public ListViewItem FindNearestItem (SearchDirectionHint direction, int x, int y)
3624                 {
3625                         return FindNearestItem (direction, new Point (x, y));
3626                 }
3627
3628                 public ListViewItem FindNearestItem (SearchDirectionHint direction, Point location)
3629                 {
3630                         if (direction < SearchDirectionHint.Left || direction > SearchDirectionHint.Down)
3631                                 throw new ArgumentOutOfRangeException ("searchDirection");
3632
3633                         if (view != View.LargeIcon && view != View.SmallIcon)
3634                                 throw new InvalidOperationException ();
3635
3636                         if (virtual_mode) {
3637                                 SearchForVirtualItemEventArgs args = new SearchForVirtualItemEventArgs (false,
3638                                                 false, false, String.Empty, location, 
3639                                                 direction, 0);
3640
3641                                 OnSearchForVirtualItem (args);
3642                                 int idx = args.Index;
3643                                 if (idx >= 0 && idx < virtual_list_size)
3644                                         return items [idx];
3645
3646                                 return null;
3647                         }
3648
3649                         ListViewItem item = null;
3650                         int min_dist = Int32.MaxValue;
3651
3652                         //
3653                         // It looks like .Net does a previous adjustment
3654                         //
3655                         switch (direction) {
3656                                 case SearchDirectionHint.Up:
3657                                         location.Y -= item_size.Height;
3658                                         break;
3659                                 case SearchDirectionHint.Down:
3660                                         location.Y += item_size.Height;
3661                                         break;
3662                                 case SearchDirectionHint.Left:
3663                                         location.X -= item_size.Width;
3664                                         break;
3665                                 case SearchDirectionHint.Right:
3666                                         location.X += item_size.Width;
3667                                         break;
3668                         }
3669
3670                         for (int i = 0; i < items.Count; i++) {
3671                                 Point item_loc = GetItemLocation (i);
3672
3673                                 if (direction == SearchDirectionHint.Up) {
3674                                         if (location.Y < item_loc.Y)
3675                                                 continue;
3676                                 } else if (direction == SearchDirectionHint.Down) {
3677                                         if (location.Y > item_loc.Y)
3678                                                 continue;
3679                                 } else if (direction == SearchDirectionHint.Left) {
3680                                         if (location.X < item_loc.X)
3681                                                 continue;
3682                                 } else if (direction == SearchDirectionHint.Right) {
3683                                         if (location.X > item_loc.X)
3684                                                 continue;
3685                                 }
3686
3687                                 int x_dist = location.X - item_loc.X;
3688                                 int y_dist = location.Y - item_loc.Y;
3689
3690                                 int dist = x_dist * x_dist  + y_dist * y_dist;
3691                                 if (dist < min_dist) {
3692                                         item = items [i];
3693                                         min_dist = dist;
3694                                 }
3695                         }
3696
3697                         return item;
3698                 }
3699 #endif
3700                 
3701                 public ListViewItem GetItemAt (int x, int y)
3702                 {
3703                         Size item_size = ItemSize;
3704                         for (int i = 0; i < items.Count; i++) {
3705                                 Point item_location = GetItemLocation (i);
3706                                 Rectangle item_rect = new Rectangle (item_location, item_size);
3707                                 if (item_rect.Contains (x, y))
3708                                         return items [i];
3709                         }
3710
3711                         return null;
3712                 }
3713
3714                 public Rectangle GetItemRect (int index)
3715                 {
3716                         return GetItemRect (index, ItemBoundsPortion.Entire);
3717                 }
3718
3719                 public Rectangle GetItemRect (int index, ItemBoundsPortion portion)
3720                 {
3721                         if (index < 0 || index >= items.Count)
3722                                 throw new IndexOutOfRangeException ("index");
3723
3724                         return items [index].GetBounds (portion);
3725                 }
3726
3727 #if NET_2_0
3728                 public ListViewHitTestInfo HitTest (Point pt)
3729                 {
3730                         return HitTest (pt.X, pt.Y);
3731                 }
3732
3733                 public ListViewHitTestInfo HitTest (int x, int y)
3734                 {
3735                         if (x < 0)
3736                                 throw new ArgumentOutOfRangeException ("x");
3737                         if (y < 0)
3738                                 throw new ArgumentOutOfRangeException ("y");
3739
3740                         ListViewItem item = GetItemAt (x, y);
3741                         if (item == null)
3742                                 return new ListViewHitTestInfo (null, null, ListViewHitTestLocations.None);
3743
3744                         ListViewHitTestLocations locations = 0;
3745                         if (item.GetBounds (ItemBoundsPortion.Label).Contains (x, y))
3746                                 locations |= ListViewHitTestLocations.Label;
3747                         else if (item.GetBounds (ItemBoundsPortion.Icon).Contains (x, y))
3748                                 locations |= ListViewHitTestLocations.Image;
3749                         else if (item.CheckRectReal.Contains (x, y))
3750                                 locations |= ListViewHitTestLocations.StateImage;
3751
3752                         ListViewItem.ListViewSubItem subitem = null;
3753                         if (view == View.Details)
3754                                 foreach (ListViewItem.ListViewSubItem si in item.SubItems)
3755                                         if (si.Bounds.Contains (x, y)) {
3756                                                 subitem = si;
3757                                                 break;
3758                                         }
3759
3760                         return new ListViewHitTestInfo (item, subitem, locations);
3761                 }
3762
3763                 [EditorBrowsable (EditorBrowsableState.Advanced)]
3764                 public void RedrawItems (int startIndex, int endIndex, bool invalidateOnly)
3765                 {
3766                         if (startIndex < 0 || startIndex >= items.Count)
3767                                 throw new ArgumentOutOfRangeException ("startIndex");
3768                         if (endIndex < 0 || endIndex >= items.Count)
3769                                 throw new ArgumentOutOfRangeException ("endIndex");
3770                         if (startIndex > endIndex)
3771                                 throw new ArgumentException ("startIndex");
3772
3773                         if (updating)
3774                                 return;
3775
3776                         for (int i = startIndex; i <= endIndex; i++)
3777                                 item_control.Invalidate (items [i].Bounds);
3778
3779                         if (!invalidateOnly)
3780                                 Update ();
3781                 }
3782 #endif
3783
3784                 public void Sort ()
3785                 {
3786 #if NET_2_0
3787                         if (virtual_mode)
3788                                 throw new InvalidOperationException ();
3789 #endif
3790
3791                         Sort (true);
3792                 }
3793
3794                 // we need this overload to reuse the logic for sorting, while allowing
3795                 // redrawing to be done by caller or have it done by this method when
3796                 // sorting is really performed
3797                 //
3798                 // ListViewItemCollection's Add and AddRange methods call this overload
3799                 // with redraw set to false, as they take care of redrawing themselves
3800                 // (they even want to redraw the listview if no sort is performed, as 
3801                 // an item was added), while ListView.Sort () only wants to redraw if 
3802                 // sorting was actually performed
3803                 private void Sort (bool redraw)
3804                 {
3805                         if (!IsHandleCreated || item_sorter == null) {
3806                                 return;
3807                         }
3808                         
3809                         items.Sort (item_sorter);
3810                         if (redraw)
3811                                 this.Redraw (true);
3812                 }
3813
3814                 public override string ToString ()
3815                 {
3816                         int count = this.Items.Count;
3817
3818                         if (count == 0)
3819                                 return string.Format ("System.Windows.Forms.ListView, Items.Count: 0");
3820                         else
3821                                 return string.Format ("System.Windows.Forms.ListView, Items.Count: {0}, Items[0]: {1}", count, this.Items [0].ToString ());
3822                 }
3823                 #endregion      // Public Instance Methods
3824
3825
3826                 #region Subclasses
3827
3828                 class HeaderControl : Control {
3829
3830                         ListView owner;
3831                         bool column_resize_active = false;
3832                         ColumnHeader resize_column;
3833                         ColumnHeader clicked_column;
3834                         ColumnHeader drag_column;
3835                         int drag_x;
3836                         int drag_to_index = -1;
3837
3838                         public HeaderControl (ListView owner)
3839                         {
3840                                 this.owner = owner;
3841                                 MouseDown += new MouseEventHandler (HeaderMouseDown);
3842                                 MouseMove += new MouseEventHandler (HeaderMouseMove);
3843                                 MouseUp += new MouseEventHandler (HeaderMouseUp);
3844                         }
3845
3846                         private ColumnHeader ColumnAtX (int x)
3847                         {
3848                                 Point pt = new Point (x, 0);
3849                                 ColumnHeader result = null;
3850                                 foreach (ColumnHeader col in owner.Columns) {
3851                                         if (col.Rect.Contains (pt)) {
3852                                                 result = col;
3853                                                 break;
3854                                         }
3855                                 }
3856                                 return result;
3857                         }
3858
3859                         private int GetReorderedIndex (ColumnHeader col)
3860                         {
3861                                 if (owner.reordered_column_indices == null)
3862                                         return col.Index;
3863                                 else
3864                                         for (int i = 0; i < owner.Columns.Count; i++)
3865                                                 if (owner.reordered_column_indices [i] == col.Index)
3866                                                         return i;
3867                                 throw new Exception ("Column index missing from reordered array");
3868                         }
3869
3870                         private void HeaderMouseDown (object sender, MouseEventArgs me)
3871                         {
3872                                 if (resize_column != null) {
3873                                         column_resize_active = true;
3874                                         Capture = true;
3875                                         return;
3876                                 }
3877
3878                                 clicked_column = ColumnAtX (me.X + owner.h_marker);
3879
3880                                 if (clicked_column != null) {
3881                                         Capture = true;
3882                                         if (owner.AllowColumnReorder) {
3883                                                 drag_x = me.X;
3884                                                 drag_column = (ColumnHeader) (clicked_column as ICloneable).Clone ();
3885                                                 drag_column.Rect = clicked_column.Rect;
3886                                                 drag_to_index = GetReorderedIndex (clicked_column);
3887                                         }
3888                                         clicked_column.Pressed = true;
3889                                         Rectangle bounds = clicked_column.Rect;
3890                                         bounds.X -= owner.h_marker;
3891                                         Invalidate (bounds);
3892                                         return;
3893                                 }
3894                         }
3895
3896                         void StopResize ()
3897                         {
3898                                 column_resize_active = false;
3899                                 resize_column = null;
3900                                 Capture = false;
3901                                 Cursor = Cursors.Default;
3902                         }
3903                         
3904                         private void HeaderMouseMove (object sender, MouseEventArgs me)
3905                         {
3906                                 Point pt = new Point (me.X + owner.h_marker, me.Y);
3907
3908                                 if (column_resize_active) {
3909                                         int width = pt.X - resize_column.X;
3910                                         if (width < 0)
3911                                                 width = 0;
3912
3913                                         if (!owner.CanProceedWithResize (resize_column, width)){
3914                                                 StopResize ();
3915                                                 return;
3916                                         }
3917                                         resize_column.Width = width;
3918                                         return;
3919                                 }
3920
3921                                 resize_column = null;
3922
3923                                 if (clicked_column != null) {
3924                                         if (owner.AllowColumnReorder) {
3925                                                 Rectangle r;
3926
3927                                                 r = drag_column.Rect;
3928                                                 r.X = clicked_column.Rect.X + me.X - drag_x;
3929                                                 drag_column.Rect = r;
3930
3931                                                 int x = me.X + owner.h_marker;
3932                                                 ColumnHeader over = ColumnAtX (x);
3933                                                 if (over == null)
3934                                                         drag_to_index = owner.Columns.Count;
3935                                                 else if (x < over.X + over.Width / 2)
3936                                                         drag_to_index = GetReorderedIndex (over);
3937                                                 else
3938                                                         drag_to_index = GetReorderedIndex (over) + 1;
3939                                                 Invalidate ();
3940                                         } else {
3941                                                 ColumnHeader over = ColumnAtX (me.X + owner.h_marker);
3942                                                 bool pressed = clicked_column.Pressed;
3943                                                 clicked_column.Pressed = over == clicked_column;
3944                                                 if (clicked_column.Pressed ^ pressed) {
3945                                                         Rectangle bounds = clicked_column.Rect;
3946                                                         bounds.X -= owner.h_marker;
3947                                                         Invalidate (bounds);
3948                                                 }
3949                                         }
3950                                         return;
3951                                 }
3952
3953                                 for (int i = 0; i < owner.Columns.Count; i++) {
3954                                         Rectangle zone = owner.Columns [i].Rect;
3955                                         zone.X = zone.Right - 5;
3956                                         zone.Width = 10;
3957                                         if (zone.Contains (pt)) {
3958                                                 if (i < owner.Columns.Count - 1 && owner.Columns [i + 1].Width == 0)
3959                                                         i++;
3960                                                 resize_column = owner.Columns [i];
3961                                                 break;
3962                                         }
3963                                 }
3964
3965                                 if (resize_column == null)
3966                                         Cursor = Cursors.Default;
3967                                 else
3968                                         Cursor = Cursors.VSplit;
3969                         }
3970
3971                         void HeaderMouseUp (object sender, MouseEventArgs me)
3972                         {
3973                                 Capture = false;
3974
3975                                 if (column_resize_active) {
3976                                         int column_idx = resize_column.Index;
3977                                         StopResize ();
3978                                         owner.RaiseColumnWidthChanged (column_idx);
3979                                         return;
3980                                 }
3981
3982                                 if (clicked_column != null && clicked_column.Pressed) {
3983                                         clicked_column.Pressed = false;
3984                                         Rectangle bounds = clicked_column.Rect;
3985                                         bounds.X -= owner.h_marker;
3986                                         Invalidate (bounds);
3987                                         owner.OnColumnClick (new ColumnClickEventArgs (clicked_column.Index));
3988                                 }
3989
3990                                 if (drag_column != null && owner.AllowColumnReorder) {
3991                                         drag_column = null;
3992                                         if (drag_to_index > GetReorderedIndex (clicked_column))
3993                                                 drag_to_index--;
3994                                         if (owner.GetReorderedColumn (drag_to_index) != clicked_column)
3995                                                 owner.ReorderColumn (clicked_column, drag_to_index, true);
3996                                         drag_to_index = -1;
3997                                         Invalidate ();
3998                                 }
3999
4000                                 clicked_column = null;
4001                         }
4002
4003                         internal override void OnPaintInternal (PaintEventArgs pe)
4004                         {
4005                                 if (owner.updating)
4006                                         return;
4007                                 
4008                                 Theme theme = ThemeEngine.Current;
4009                                 theme.DrawListViewHeader (pe.Graphics, pe.ClipRectangle, this.owner);
4010
4011                                 if (drag_column == null)
4012                                         return;
4013
4014                                 int target_x;
4015                                 if (drag_to_index == owner.Columns.Count)
4016                                         target_x = owner.GetReorderedColumn (drag_to_index - 1).Rect.Right - owner.h_marker;
4017                                 else
4018                                         target_x = owner.GetReorderedColumn (drag_to_index).Rect.X - owner.h_marker;
4019                                 theme.DrawListViewHeaderDragDetails (pe.Graphics, owner, drag_column, target_x);
4020                         }
4021
4022                         protected override void WndProc (ref Message m)
4023                         {
4024                                 switch ((Msg)m.Msg) {
4025                                 case Msg.WM_SETFOCUS:
4026                                         owner.Focus ();
4027                                         break;
4028                                 default:
4029                                         base.WndProc (ref m);
4030                                         break;
4031                                 }
4032                         }
4033                 }
4034
4035                 private class ItemComparer : IComparer {
4036                         readonly SortOrder sort_order;
4037
4038                         public ItemComparer (SortOrder sortOrder)
4039                         {
4040                                 sort_order = sortOrder;
4041                         }
4042
4043                         public int Compare (object x, object y)
4044                         {
4045                                 ListViewItem item_x = x as ListViewItem;
4046                                 ListViewItem item_y = y as ListViewItem;
4047                                 if (sort_order == SortOrder.Ascending)
4048                                         return String.Compare (item_x.Text, item_y.Text);
4049                                 else
4050                                         return String.Compare (item_y.Text, item_x.Text);
4051                         }
4052                 }
4053
4054 #if NET_2_0
4055                 [ListBindable (false)]
4056 #endif
4057                 public class CheckedIndexCollection : IList, ICollection, IEnumerable
4058                 {
4059                         private readonly ListView owner;
4060
4061                         #region Public Constructor
4062                         public CheckedIndexCollection (ListView owner)
4063                         {
4064                                 this.owner = owner;
4065                         }
4066                         #endregion      // Public Constructor
4067
4068                         #region Public Properties
4069                         [Browsable (false)]
4070                         public int Count {
4071                                 get { return owner.CheckedItems.Count; }
4072                         }
4073
4074                         public bool IsReadOnly {
4075                                 get { return true; }
4076                         }
4077
4078                         public int this [int index] {
4079                                 get {
4080                                         int [] indices = GetIndices ();
4081                                         if (index < 0 || index >= indices.Length)
4082                                                 throw new ArgumentOutOfRangeException ("index");
4083                                         return indices [index];
4084                                 }
4085                         }
4086
4087                         bool ICollection.IsSynchronized {
4088                                 get { return false; }
4089                         }
4090
4091                         object ICollection.SyncRoot {
4092                                 get { return this; }
4093                         }
4094
4095                         bool IList.IsFixedSize {
4096                                 get { return true; }
4097                         }
4098
4099                         object IList.this [int index] {
4100                                 get { return this [index]; }
4101                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
4102                         }
4103                         #endregion      // Public Properties
4104
4105                         #region Public Methods
4106                         public bool Contains (int checkedIndex)
4107                         {
4108                                 int [] indices = GetIndices ();
4109                                 for (int i = 0; i < indices.Length; i++) {
4110                                         if (indices [i] == checkedIndex)
4111                                                 return true;
4112                                 }
4113                                 return false;
4114                         }
4115
4116                         public IEnumerator GetEnumerator ()
4117                         {
4118                                 int [] indices = GetIndices ();
4119                                 return indices.GetEnumerator ();
4120                         }
4121
4122                         void ICollection.CopyTo (Array dest, int index)
4123                         {
4124                                 int [] indices = GetIndices ();
4125                                 Array.Copy (indices, 0, dest, index, indices.Length);
4126                         }
4127
4128                         int IList.Add (object value)
4129                         {
4130                                 throw new NotSupportedException ("Add operation is not supported.");
4131                         }
4132
4133                         void IList.Clear ()
4134                         {
4135                                 throw new NotSupportedException ("Clear operation is not supported.");
4136                         }
4137
4138                         bool IList.Contains (object checkedIndex)
4139                         {
4140                                 if (!(checkedIndex is int))
4141                                         return false;
4142                                 return Contains ((int) checkedIndex);
4143                         }
4144
4145                         int IList.IndexOf (object checkedIndex)
4146                         {
4147                                 if (!(checkedIndex is int))
4148                                         return -1;
4149                                 return IndexOf ((int) checkedIndex);
4150                         }
4151
4152                         void IList.Insert (int index, object value)
4153                         {
4154                                 throw new NotSupportedException ("Insert operation is not supported.");
4155                         }
4156
4157                         void IList.Remove (object value)
4158                         {
4159                                 throw new NotSupportedException ("Remove operation is not supported.");
4160                         }
4161
4162                         void IList.RemoveAt (int index)
4163                         {
4164                                 throw new NotSupportedException ("RemoveAt operation is not supported.");
4165                         }
4166
4167                         public int IndexOf (int checkedIndex)
4168                         {
4169                                 int [] indices = GetIndices ();
4170                                 for (int i = 0; i < indices.Length; i++) {
4171                                         if (indices [i] == checkedIndex)
4172                                                 return i;
4173                                 }
4174                                 return -1;
4175                         }
4176                         #endregion      // Public Methods
4177
4178                         private int [] GetIndices ()
4179                         {
4180                                 ArrayList checked_items = owner.CheckedItems.List;
4181                                 int [] indices = new int [checked_items.Count];
4182                                 for (int i = 0; i < checked_items.Count; i++) {
4183                                         ListViewItem item = (ListViewItem) checked_items [i];
4184                                         indices [i] = item.Index;
4185                                 }
4186                                 return indices;
4187                         }
4188                 }       // CheckedIndexCollection
4189
4190 #if NET_2_0
4191                 [ListBindable (false)]
4192 #endif
4193                 public class CheckedListViewItemCollection : IList, ICollection, IEnumerable
4194                 {
4195                         private readonly ListView owner;
4196                         private ArrayList list;
4197
4198                         #region Public Constructor
4199                         public CheckedListViewItemCollection (ListView owner)
4200                         {
4201                                 this.owner = owner;
4202                                 this.owner.Items.Changed += new CollectionChangedHandler (
4203                                         ItemsCollection_Changed);
4204                         }
4205                         #endregion      // Public Constructor
4206
4207                         #region Public Properties
4208                         [Browsable (false)]
4209                         public int Count {
4210                                 get {
4211                                         if (!owner.CheckBoxes)
4212                                                 return 0;
4213                                         return List.Count;
4214                                 }
4215                         }
4216
4217                         public bool IsReadOnly {
4218                                 get { return true; }
4219                         }
4220
4221                         public ListViewItem this [int index] {
4222                                 get {
4223 #if NET_2_0
4224                                         if (owner.VirtualMode)
4225                                                 throw new InvalidOperationException ();
4226 #endif
4227                                         ArrayList checked_items = List;
4228                                         if (index < 0 || index >= checked_items.Count)
4229                                                 throw new ArgumentOutOfRangeException ("index");
4230                                         return (ListViewItem) checked_items [index];
4231                                 }
4232                         }
4233
4234 #if NET_2_0
4235                         public virtual ListViewItem this [string key] {
4236                                 get {
4237                                         int idx = IndexOfKey (key);
4238                                         return idx == -1 ? null : (ListViewItem) List [idx];
4239                                 }
4240                         }
4241 #endif
4242
4243                         bool ICollection.IsSynchronized {
4244                                 get { return false; }
4245                         }
4246
4247                         object ICollection.SyncRoot {
4248                                 get { return this; }
4249                         }
4250
4251                         bool IList.IsFixedSize {
4252                                 get { return true; }
4253                         }
4254
4255                         object IList.this [int index] {
4256                                 get { return this [index]; }
4257                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
4258                         }
4259                         #endregion      // Public Properties
4260
4261                         #region Public Methods
4262                         public bool Contains (ListViewItem item)
4263                         {
4264                                 if (!owner.CheckBoxes)
4265                                         return false;
4266                                 return List.Contains (item);
4267                         }
4268
4269 #if NET_2_0
4270                         public virtual bool ContainsKey (string key)
4271                         {
4272                                 return IndexOfKey (key) != -1;
4273                         }
4274 #endif
4275
4276                         public void CopyTo (Array dest, int index)
4277                         {
4278 #if NET_2_0
4279                                 if (owner.VirtualMode)
4280                                         throw new InvalidOperationException ();
4281 #endif
4282                                 if (!owner.CheckBoxes)
4283                                         return;
4284                                 List.CopyTo (dest, index);
4285                         }
4286
4287                         public IEnumerator GetEnumerator ()
4288                         {
4289 #if NET_2_0
4290                                 if (owner.VirtualMode)
4291                                         throw new InvalidOperationException ();
4292 #endif
4293                                 if (!owner.CheckBoxes)
4294                                         return (new ListViewItem [0]).GetEnumerator ();
4295                                 return List.GetEnumerator ();
4296                         }
4297
4298                         int IList.Add (object value)
4299                         {
4300                                 throw new NotSupportedException ("Add operation is not supported.");
4301                         }
4302
4303                         void IList.Clear ()
4304                         {
4305                                 throw new NotSupportedException ("Clear operation is not supported.");
4306                         }
4307
4308                         bool IList.Contains (object item)
4309                         {
4310                                 if (!(item is ListViewItem))
4311                                         return false;
4312                                 return Contains ((ListViewItem) item);
4313                         }
4314
4315                         int IList.IndexOf (object item)
4316                         {
4317                                 if (!(item is ListViewItem))
4318                                         return -1;
4319                                 return IndexOf ((ListViewItem) item);
4320                         }
4321
4322                         void IList.Insert (int index, object value)
4323                         {
4324                                 throw new NotSupportedException ("Insert operation is not supported.");
4325                         }
4326
4327                         void IList.Remove (object value)
4328                         {
4329                                 throw new NotSupportedException ("Remove operation is not supported.");
4330                         }
4331
4332                         void IList.RemoveAt (int index)
4333                         {
4334                                 throw new NotSupportedException ("RemoveAt operation is not supported.");
4335                         }
4336
4337                         public int IndexOf (ListViewItem item)
4338                         {
4339 #if NET_2_0
4340                                 if (owner.VirtualMode)
4341                                         throw new InvalidOperationException ();
4342 #endif
4343                                 if (!owner.CheckBoxes)
4344                                         return -1;
4345                                 return List.IndexOf (item);
4346                         }
4347
4348 #if NET_2_0
4349                         public virtual int IndexOfKey (string key)
4350                         {
4351 #if NET_2_0
4352                                 if (owner.VirtualMode)
4353                                         throw new InvalidOperationException ();
4354 #endif
4355                                 if (key == null || key.Length == 0)
4356                                         return -1;
4357
4358                                 ArrayList checked_items = List;
4359                                 for (int i = 0; i < checked_items.Count; i++) {
4360                                         ListViewItem item = (ListViewItem) checked_items [i];
4361                                         if (String.Compare (key, item.Name, true) == 0)
4362                                                 return i;
4363                                 }
4364
4365                                 return -1;
4366                         }
4367 #endif
4368                         #endregion      // Public Methods
4369
4370                         internal ArrayList List {
4371                                 get {
4372                                         if (list == null) {
4373                                                 list = new ArrayList ();
4374                                                 foreach (ListViewItem item in owner.Items) {
4375                                                         if (item.Checked)
4376                                                                 list.Add (item);
4377                                                 }
4378                                         }
4379                                         return list;
4380                                 }
4381                         }
4382
4383                         internal void Reset ()
4384                         {
4385                                 // force re-population of list
4386                                 list = null;
4387                         }
4388
4389                         private void ItemsCollection_Changed ()
4390                         {
4391                                 Reset ();
4392                         }
4393                 }       // CheckedListViewItemCollection
4394
4395 #if NET_2_0
4396                 [ListBindable (false)]
4397 #endif
4398                 public class ColumnHeaderCollection : IList, ICollection, IEnumerable
4399                 {
4400                         internal ArrayList list;
4401                         private ListView owner;
4402
4403                         #region Public Constructor
4404                         public ColumnHeaderCollection (ListView owner)
4405                         {
4406                                 list = new ArrayList ();
4407                                 this.owner = owner;
4408                         }
4409                         #endregion      // Public Constructor
4410
4411                         #region Public Properties
4412                         [Browsable (false)]
4413                         public int Count {
4414                                 get { return list.Count; }
4415                         }
4416
4417                         public bool IsReadOnly {
4418                                 get { return false; }
4419                         }
4420
4421                         public virtual ColumnHeader this [int index] {
4422                                 get {
4423                                         if (index < 0 || index >= list.Count)
4424                                                 throw new ArgumentOutOfRangeException ("index");
4425                                         return (ColumnHeader) list [index];
4426                                 }
4427                         }
4428
4429 #if NET_2_0
4430                         public virtual ColumnHeader this [string key] {
4431                                 get {
4432                                         int idx = IndexOfKey (key);
4433                                         if (idx == -1)
4434                                                 return null;
4435
4436                                         return (ColumnHeader) list [idx];
4437                                 }
4438                         }
4439 #endif
4440
4441                         bool ICollection.IsSynchronized {
4442                                 get { return true; }
4443                         }
4444
4445                         object ICollection.SyncRoot {
4446                                 get { return this; }
4447                         }
4448
4449                         bool IList.IsFixedSize {
4450                                 get { return list.IsFixedSize; }
4451                         }
4452
4453                         object IList.this [int index] {
4454                                 get { return this [index]; }
4455                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
4456                         }
4457                         #endregion      // Public Properties
4458
4459                         #region Public Methods
4460                         public virtual int Add (ColumnHeader value)
4461                         {
4462                                 int idx = list.Add (value);
4463                                 owner.AddColumn (value, idx, true);
4464                                 return idx;
4465                         }
4466
4467                         public virtual ColumnHeader Add (string str, int width, HorizontalAlignment textAlign)
4468                         {
4469                                 ColumnHeader colHeader = new ColumnHeader (this.owner, str, textAlign, width);
4470                                 this.Add (colHeader);
4471                                 return colHeader;
4472                         }
4473
4474 #if NET_2_0
4475                         public virtual ColumnHeader Add (string text)
4476                         {
4477                                 return Add (String.Empty, text);
4478                         }
4479
4480                         public virtual ColumnHeader Add (string text, int iwidth)
4481                         {
4482                                 return Add (String.Empty, text, iwidth);
4483                         }
4484
4485                         public virtual ColumnHeader Add (string key, string text)
4486                         {
4487                                 ColumnHeader colHeader = new ColumnHeader ();
4488                                 colHeader.Name = key;
4489                                 colHeader.Text = text;
4490                                 Add (colHeader);
4491                                 return colHeader;
4492                         }
4493
4494                         public virtual ColumnHeader Add (string key, string text, int iwidth)
4495                         {
4496                                 return Add (key, text, iwidth, HorizontalAlignment.Left, -1);
4497                         }
4498
4499                         public virtual ColumnHeader Add (string key, string text, int iwidth, HorizontalAlignment textAlign, int imageIndex)
4500                         {
4501                                 ColumnHeader colHeader = new ColumnHeader (key, text, iwidth, textAlign);
4502                                 colHeader.ImageIndex = imageIndex;
4503                                 Add (colHeader);
4504                                 return colHeader;
4505                         }
4506
4507                         public virtual ColumnHeader Add (string key, string text, int iwidth, HorizontalAlignment textAlign, string imageKey)
4508                         {
4509                                 ColumnHeader colHeader = new ColumnHeader (key, text, iwidth, textAlign);
4510                                 colHeader.ImageKey = imageKey;
4511                                 Add (colHeader);
4512                                 return colHeader;
4513                         }
4514 #endif
4515
4516                         public virtual void AddRange (ColumnHeader [] values)
4517                         {
4518                                 foreach (ColumnHeader colHeader in values) {
4519                                         int idx = list.Add (colHeader);
4520                                         owner.AddColumn (colHeader, idx, false);
4521                                 }
4522                                 
4523                                 owner.Redraw (true);
4524                         }
4525
4526                         public virtual void Clear ()
4527                         {
4528                                 foreach (ColumnHeader col in list)
4529                                         col.SetListView (null);
4530                                 list.Clear ();
4531                                 owner.ReorderColumns (new int [0], true);
4532                         }
4533
4534                         public bool Contains (ColumnHeader value)
4535                         {
4536                                 return list.Contains (value);
4537                         }
4538
4539 #if NET_2_0
4540                         public virtual bool ContainsKey (string key)
4541                         {
4542                                 return IndexOfKey (key) != -1;
4543                         }
4544 #endif
4545
4546                         public IEnumerator GetEnumerator ()
4547                         {
4548                                 return list.GetEnumerator ();
4549                         }
4550
4551                         void ICollection.CopyTo (Array dest, int index)
4552                         {
4553                                 list.CopyTo (dest, index);
4554                         }
4555
4556                         int IList.Add (object value)
4557                         {
4558                                 if (! (value is ColumnHeader)) {
4559                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
4560                                 }
4561
4562                                 return this.Add ((ColumnHeader) value);
4563                         }
4564
4565                         bool IList.Contains (object value)
4566                         {
4567                                 if (! (value is ColumnHeader)) {
4568                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
4569                                 }
4570
4571                                 return this.Contains ((ColumnHeader) value);
4572                         }
4573
4574                         int IList.IndexOf (object value)
4575                         {
4576                                 if (! (value is ColumnHeader)) {
4577                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
4578                                 }
4579
4580                                 return this.IndexOf ((ColumnHeader) value);
4581                         }
4582
4583                         void IList.Insert (int index, object value)
4584                         {
4585                                 if (! (value is ColumnHeader)) {
4586                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
4587                                 }
4588
4589                                 this.Insert (index, (ColumnHeader) value);
4590                         }
4591
4592                         void IList.Remove (object value)
4593                         {
4594                                 if (! (value is ColumnHeader)) {
4595                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
4596                                 }
4597
4598                                 this.Remove ((ColumnHeader) value);
4599                         }
4600
4601                         public int IndexOf (ColumnHeader value)
4602                         {
4603                                 return list.IndexOf (value);
4604                         }
4605
4606 #if NET_2_0
4607                         public virtual int IndexOfKey (string key)
4608                         {
4609                                 if (key == null || key.Length == 0)
4610                                         return -1;
4611
4612                                 for (int i = 0; i < list.Count; i++) {
4613                                         ColumnHeader col = (ColumnHeader) list [i];
4614                                         if (String.Compare (key, col.Name, true) == 0)
4615                                                 return i;
4616                                 }
4617
4618                                 return -1;
4619                         }
4620 #endif
4621
4622                         public void Insert (int index, ColumnHeader value)
4623                         {
4624                                 // LAMESPEC: MSDOCS say greater than or equal to the value of the Count property
4625                                 // but it's really only greater.
4626                                 if (index < 0 || index > list.Count)
4627                                         throw new ArgumentOutOfRangeException ("index");
4628
4629                                 list.Insert (index, value);
4630                                 owner.AddColumn (value, index, true);
4631                         }
4632
4633 #if NET_2_0
4634                         public void Insert (int index, string text)
4635                         {
4636                                 Insert (index, String.Empty, text);
4637                         }
4638
4639                         public void Insert (int index, string text, int width)
4640                         {
4641                                 Insert (index, String.Empty, text, width);
4642                         }
4643
4644                         public void Insert (int index, string key, string text)
4645                         {
4646                                 ColumnHeader colHeader = new ColumnHeader ();
4647                                 colHeader.Name = key;
4648                                 colHeader.Text = text;
4649                                 Insert (index, colHeader);
4650                         }
4651
4652                         public void Insert (int index, string key, string text, int width)
4653                         {
4654                                 ColumnHeader colHeader = new ColumnHeader (key, text, width, HorizontalAlignment.Left);
4655                                 Insert (index, colHeader);
4656                         }
4657
4658                         public void Insert (int index, string key, string text, int width, HorizontalAlignment textAlign, int imageIndex)
4659                         {
4660                                 ColumnHeader colHeader = new ColumnHeader (key, text, width, textAlign);
4661                                 colHeader.ImageIndex = imageIndex;
4662                                 Insert (index, colHeader);
4663                         }
4664
4665                         public void Insert (int index, string key, string text, int width, HorizontalAlignment textAlign, string imageKey)
4666                         {
4667                                 ColumnHeader colHeader = new ColumnHeader (key, text, width, textAlign);
4668                                 colHeader.ImageKey = imageKey;
4669                                 Insert (index, colHeader);
4670                         }
4671 #endif
4672
4673                         public void Insert (int index, string str, int width, HorizontalAlignment textAlign)
4674                         {
4675                                 ColumnHeader colHeader = new ColumnHeader (this.owner, str, textAlign, width);
4676                                 this.Insert (index, colHeader);
4677                         }
4678
4679                         public virtual void Remove (ColumnHeader column)
4680                         {
4681                                 if (!Contains (column))
4682                                         return;
4683
4684                                 list.Remove (column);
4685                                 column.SetListView (null);
4686
4687                                 int rem_display_index = column.InternalDisplayIndex;
4688                                 int [] display_indices = new int [list.Count];
4689                                 for (int i = 0; i < display_indices.Length; i++) {
4690                                         ColumnHeader col = (ColumnHeader) list [i];
4691                                         int display_index = col.InternalDisplayIndex;
4692                                         if (display_index < rem_display_index) {
4693                                                 display_indices [i] = display_index;
4694                                         } else {
4695                                                 display_indices [i] = (display_index - 1);
4696                                         }
4697                                 }
4698
4699                                 column.InternalDisplayIndex = -1;
4700                                 owner.ReorderColumns (display_indices, true);
4701                         }
4702
4703 #if NET_2_0
4704                         public virtual void RemoveByKey (string key)
4705                         {
4706                                 int idx = IndexOfKey (key);
4707                                 if (idx != -1)
4708                                         RemoveAt (idx);
4709                         }
4710 #endif
4711
4712                         public virtual void RemoveAt (int index)
4713                         {
4714                                 if (index < 0 || index >= list.Count)
4715                                         throw new ArgumentOutOfRangeException ("index");
4716
4717                                 ColumnHeader col = (ColumnHeader) list [index];
4718                                 Remove (col);
4719                         }
4720                         #endregion      // Public Methods
4721                         
4722
4723                 }       // ColumnHeaderCollection
4724
4725 #if NET_2_0
4726                 [ListBindable (false)]
4727 #endif
4728                 public class ListViewItemCollection : IList, ICollection, IEnumerable
4729                 {
4730                         private readonly ArrayList list;
4731                         private ListView owner;
4732 #if NET_2_0
4733                         private ListViewGroup group;
4734 #endif
4735
4736                         // The collection can belong to a ListView (main) or to a ListViewGroup (sub-collection)
4737                         // In the later case ListViewItem.ListView never gets modified
4738                         private bool is_main_collection = true;
4739
4740                         #region Public Constructor
4741                         public ListViewItemCollection (ListView owner)
4742                         {
4743                                 list = new ArrayList (0);
4744                                 this.owner = owner;
4745                         }
4746                         #endregion      // Public Constructor
4747
4748 #if NET_2_0
4749                         internal ListViewItemCollection (ListView owner, ListViewGroup group) : this (owner)
4750                         {
4751                                 this.group = group;
4752                                 is_main_collection = false;
4753                         }
4754 #endif
4755
4756                         #region Public Properties
4757                         [Browsable (false)]
4758                         public int Count {
4759                                 get {
4760 #if NET_2_0
4761                                         if (owner != null && owner.VirtualMode)
4762                                                 return owner.VirtualListSize;
4763 #endif
4764
4765                                         return list.Count; 
4766                                 }
4767                         }
4768
4769                         public bool IsReadOnly {
4770                                 get { return false; }
4771                         }
4772
4773                         public virtual ListViewItem this [int displayIndex] {
4774                                 get {
4775                                         if (displayIndex < 0 || displayIndex >= Count)
4776                                                 throw new ArgumentOutOfRangeException ("displayIndex");
4777
4778 #if NET_2_0
4779                                         if (owner != null && owner.VirtualMode)
4780                                                 return RetrieveVirtualItemFromOwner (displayIndex);
4781 #endif
4782                                         return (ListViewItem) list [displayIndex];
4783                                 }
4784
4785                                 set {
4786                                         if (displayIndex < 0 || displayIndex >= Count)
4787                                                 throw new ArgumentOutOfRangeException ("displayIndex");
4788
4789 #if NET_2_0
4790                                         if (owner != null && owner.VirtualMode)
4791                                                 throw new InvalidOperationException ();
4792 #endif
4793
4794                                         if (list.Contains (value))
4795                                                 throw new ArgumentException ("An item cannot be added more than once. To add an item again, you need to clone it.", "value");
4796
4797                                         if (value.ListView != null && value.ListView != owner)
4798                                                 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");
4799
4800                                         if (is_main_collection)
4801                                                 value.Owner = owner;
4802 #if NET_2_0
4803                                         else {
4804                                                 if (value.Group != null)
4805                                                         value.Group.Items.Remove (value);
4806
4807                                                 value.SetGroup (group);
4808                                         }
4809 #endif
4810
4811                                         list [displayIndex] = value;
4812                                         CollectionChanged (true);
4813                                 }
4814                         }
4815
4816 #if NET_2_0
4817                         public virtual ListViewItem this [string key] {
4818                                 get {
4819                                         int idx = IndexOfKey (key);
4820                                         if (idx == -1)
4821                                                 return null;
4822
4823                                         return this [idx];
4824                                 }
4825                         }
4826 #endif
4827
4828                         bool ICollection.IsSynchronized {
4829                                 get { return true; }
4830                         }
4831
4832                         object ICollection.SyncRoot {
4833                                 get { return this; }
4834                         }
4835
4836                         bool IList.IsFixedSize {
4837                                 get { return list.IsFixedSize; }
4838                         }
4839
4840                         object IList.this [int index] {
4841                                 get { return this [index]; }
4842                                 set {
4843                                         if (value is ListViewItem)
4844                                                 this [index] = (ListViewItem) value;
4845                                         else
4846                                                 this [index] = new ListViewItem (value.ToString ());
4847                                         OnChange ();
4848                                 }
4849                         }
4850                         #endregion      // Public Properties
4851
4852                         #region Public Methods
4853                         public virtual ListViewItem Add (ListViewItem value)
4854                         {
4855 #if NET_2_0
4856                                 if (owner != null && owner.VirtualMode)
4857                                         throw new InvalidOperationException ();
4858 #endif
4859
4860                                 AddItem (value);
4861                                 CollectionChanged (true);
4862
4863                                 return value;
4864                         }
4865
4866                         public virtual ListViewItem Add (string text)
4867                         {
4868                                 ListViewItem item = new ListViewItem (text);
4869                                 return this.Add (item);
4870                         }
4871
4872                         public virtual ListViewItem Add (string text, int imageIndex)
4873                         {
4874                                 ListViewItem item = new ListViewItem (text, imageIndex);
4875                                 return this.Add (item);
4876                         }
4877
4878 #if NET_2_0
4879                         public virtual ListViewItem Add (string text, string imageKey)
4880                         {
4881                                 ListViewItem item = new ListViewItem (text, imageKey);
4882                                 return this.Add (item);
4883                         }
4884
4885                         public virtual ListViewItem Add (string key, string text, int imageIndex)
4886                         {
4887                                 ListViewItem item = new ListViewItem (text, imageIndex);
4888                                 item.Name = key;
4889                                 return this.Add (item);
4890                         }
4891
4892                         public virtual ListViewItem Add (string key, string text, string imageKey)
4893                         {
4894                                 ListViewItem item = new ListViewItem (text, imageKey);
4895                                 item.Name = key;
4896                                 return this.Add (item);
4897                         }
4898 #endif
4899
4900                         public void AddRange (ListViewItem [] values)
4901                         {
4902                                 if (values == null)
4903                                         throw new ArgumentNullException ("Argument cannot be null!", "values");
4904 #if NET_2_0
4905                                 if (owner != null && owner.VirtualMode)
4906                                         throw new InvalidOperationException ();
4907 #endif
4908
4909                                 foreach (ListViewItem item in values)
4910                                         AddItem (item);
4911
4912                                 CollectionChanged (true);
4913                         }
4914
4915 #if NET_2_0
4916                         public void AddRange (ListViewItemCollection items)
4917                         {
4918                                 if (items == null)
4919                                         throw new ArgumentNullException ("Argument cannot be null!", "items");
4920
4921                                 ListViewItem[] itemArray = new ListViewItem[items.Count];
4922                                 items.CopyTo (itemArray,0);
4923                                 this.AddRange (itemArray);
4924                         }
4925 #endif
4926
4927                         public virtual void Clear ()
4928                         {
4929 #if NET_2_0
4930                                 if (owner != null && owner.VirtualMode)
4931                                         throw new InvalidOperationException ();
4932 #endif
4933                                 if (is_main_collection && owner != null) {
4934                                         owner.SetFocusedItem (-1);
4935                                         owner.h_scroll.Value = owner.v_scroll.Value = 0;
4936                                                 
4937                                         foreach (ListViewItem item in list) {
4938                                                 owner.item_control.CancelEdit (item);
4939                                                 item.Owner = null;
4940                                         }
4941                                         
4942                                 }
4943 #if NET_2_0
4944                                 else
4945                                         foreach (ListViewItem item in list)
4946                                                 item.SetGroup (null);
4947 #endif
4948
4949                                 list.Clear ();
4950                                 CollectionChanged (false);
4951                         }
4952
4953                         public bool Contains (ListViewItem item)
4954                         {
4955                                 return IndexOf (item) != -1;
4956                         }
4957
4958 #if NET_2_0
4959                         public virtual bool ContainsKey (string key)
4960                         {
4961                                 return IndexOfKey (key) != -1;
4962                         }
4963 #endif
4964
4965                         public void CopyTo (Array dest, int index)
4966                         {
4967                                 list.CopyTo (dest, index);
4968                         }
4969
4970 #if NET_2_0
4971                         public ListViewItem [] Find (string key, bool searchAllSubitems)
4972                         {
4973                                 if (key == null)
4974                                         return new ListViewItem [0];
4975
4976                                 List<ListViewItem> temp_list = new List<ListViewItem> ();
4977                                 
4978                                 for (int i = 0; i < list.Count; i++) {
4979                                         ListViewItem lvi = (ListViewItem) list [i];
4980                                         if (String.Compare (key, lvi.Name, true) == 0)
4981                                                 temp_list.Add (lvi);
4982                                 }
4983
4984                                 ListViewItem [] retval = new ListViewItem [temp_list.Count];
4985                                 temp_list.CopyTo (retval);
4986
4987                                 return retval;
4988                         }
4989 #endif
4990
4991                         public IEnumerator GetEnumerator ()
4992                         {
4993 #if NET_2_0
4994                                 if (owner != null && owner.VirtualMode)
4995                                         throw new InvalidOperationException ();
4996 #endif
4997                                 
4998                                 return list.GetEnumerator ();
4999                         }
5000
5001                         int IList.Add (object item)
5002                         {
5003                                 int result;
5004                                 ListViewItem li;
5005
5006 #if NET_2_0
5007                                 if (owner != null && owner.VirtualMode)
5008                                         throw new InvalidOperationException ();
5009 #endif
5010
5011                                 if (item is ListViewItem) {
5012                                         li = (ListViewItem) item;
5013                                         if (list.Contains (li))
5014                                                 throw new ArgumentException ("An item cannot be added more than once. To add an item again, you need to clone it.", "item");
5015
5016                                         if (li.ListView != null && li.ListView != owner)
5017                                                 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");
5018                                 }
5019                                 else
5020                                         li = new ListViewItem (item.ToString ());
5021
5022                                 li.Owner = owner;
5023                                 result = list.Add (li);
5024                                 CollectionChanged (true);
5025
5026                                 return result;
5027                         }
5028
5029                         bool IList.Contains (object item)
5030                         {
5031                                 return Contains ((ListViewItem) item);
5032                         }
5033
5034                         int IList.IndexOf (object item)
5035                         {
5036                                 return IndexOf ((ListViewItem) item);
5037                         }
5038
5039                         void IList.Insert (int index, object item)
5040                         {
5041                                 if (item is ListViewItem)
5042                                         this.Insert (index, (ListViewItem) item);
5043                                 else
5044                                         this.Insert (index, item.ToString ());
5045                         }
5046
5047                         void IList.Remove (object item)
5048                         {
5049                                 Remove ((ListViewItem) item);
5050                         }
5051
5052                         public int IndexOf (ListViewItem item)
5053                         {
5054 #if NET_2_0
5055                                 if (owner != null && owner.VirtualMode) {
5056                                         for (int i = 0; i < Count; i++)
5057                                                 if (RetrieveVirtualItemFromOwner (i) == item)
5058                                                         return i;
5059
5060                                         return -1;
5061                                 }
5062 #endif
5063                                 
5064                                 return list.IndexOf (item);
5065                         }
5066
5067 #if NET_2_0
5068                         public virtual int IndexOfKey (string key)
5069                         {
5070                                 if (key == null || key.Length == 0)
5071                                         return -1;
5072
5073                                 for (int i = 0; i < Count; i++) {
5074                                         ListViewItem lvi = this [i];
5075                                         if (String.Compare (key, lvi.Name, true) == 0)
5076                                                 return i;
5077                                 }
5078
5079                                 return -1;
5080                         }
5081 #endif
5082
5083                         public ListViewItem Insert (int index, ListViewItem item)
5084                         {
5085                                 if (index < 0 || index > list.Count)
5086                                         throw new ArgumentOutOfRangeException ("index");
5087
5088 #if NET_2_0
5089                                 if (owner != null && owner.VirtualMode)
5090                                         throw new InvalidOperationException ();
5091 #endif
5092
5093                                 if (list.Contains (item))
5094                                         throw new ArgumentException ("An item cannot be added more than once. To add an item again, you need to clone it.", "item");
5095
5096                                 if (item.ListView != null && item.ListView != owner)
5097                                         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");
5098
5099                                 if (is_main_collection)
5100                                         item.Owner = owner;
5101 #if NET_2_0
5102                                 else {
5103                                         if (item.Group != null)
5104                                                 item.Group.Items.Remove (item);
5105
5106                                         item.SetGroup (group);
5107                                 }
5108 #endif
5109
5110                                 list.Insert (index, item);
5111                                 CollectionChanged (true);
5112                                 return item;
5113                         }
5114
5115                         public ListViewItem Insert (int index, string text)
5116                         {
5117                                 return this.Insert (index, new ListViewItem (text));
5118                         }
5119
5120                         public ListViewItem Insert (int index, string text, int imageIndex)
5121                         {
5122                                 return this.Insert (index, new ListViewItem (text, imageIndex));
5123                         }
5124
5125 #if NET_2_0
5126                         public ListViewItem Insert (int index, string text, string imageKey)
5127                         {
5128                                 ListViewItem lvi = new ListViewItem (text, imageKey);
5129                                 return Insert (index, lvi);
5130                         }
5131
5132                         public virtual ListViewItem Insert (int index, string key, string text, int imageIndex)
5133                         {
5134                                 ListViewItem lvi = new ListViewItem (text, imageIndex);
5135                                 lvi.Name = key;
5136                                 return Insert (index, lvi);
5137                         }
5138
5139                         public virtual ListViewItem Insert (int index, string key, string text, string imageKey)
5140                         {
5141                                 ListViewItem lvi = new ListViewItem (text, imageKey);
5142                                 lvi.Name = key;
5143                                 return Insert (index, lvi);
5144                         }
5145 #endif
5146
5147                         public virtual void Remove (ListViewItem item)
5148                         {
5149 #if NET_2_0
5150                                 if (owner != null && owner.VirtualMode)
5151                                         throw new InvalidOperationException ();
5152 #endif
5153
5154                                 int idx = list.IndexOf (item);
5155                                 if (idx != -1)
5156                                         RemoveAt (idx);
5157                         }
5158
5159                         public virtual void RemoveAt (int index)
5160                         {
5161                                 if (index < 0 || index >= Count)
5162                                         throw new ArgumentOutOfRangeException ("index");
5163
5164 #if NET_2_0
5165                                 if (owner != null && owner.VirtualMode)
5166                                         throw new InvalidOperationException ();
5167 #endif
5168
5169                                 ListViewItem item = (ListViewItem) list [index];
5170
5171                                 bool selection_changed = false;
5172                                 if (is_main_collection && owner != null) {
5173
5174                                         if (item.Focused && index + 1 == Count) // Last item
5175                                                 owner.SetFocusedItem (index == 0 ? -1 : index - 1);
5176
5177                                         selection_changed = owner.SelectedIndices.Contains (index);
5178                                         owner.item_control.CancelEdit (item);
5179                                 }
5180
5181                                 list.RemoveAt (index);
5182
5183                                 if (is_main_collection)
5184                                         item.Owner = null;
5185 #if NET_2_0
5186                                 else
5187                                         item.SetGroup (null);
5188 #endif
5189
5190                                 CollectionChanged (false);
5191                                 if (selection_changed && owner != null)
5192                                         owner.OnSelectedIndexChanged (EventArgs.Empty);
5193                         }
5194
5195 #if NET_2_0
5196                         public virtual void RemoveByKey (string key)
5197                         {
5198                                 int idx = IndexOfKey (key);
5199                                 if (idx != -1)
5200                                         RemoveAt (idx);
5201                         }
5202 #endif
5203
5204                         #endregion      // Public Methods
5205
5206                         internal ListView Owner {
5207                                 get {
5208                                         return owner;
5209                                 }
5210                                 set {
5211                                         owner = value;
5212                                 }
5213                         }
5214
5215 #if NET_2_0
5216                         internal ListViewGroup Group {
5217                                 get {
5218                                         return group;
5219                                 }
5220                                 set {
5221                                         group = value;
5222                                 }
5223                         }
5224 #endif
5225
5226                         void AddItem (ListViewItem value)
5227                         {
5228                                 if (list.Contains (value))
5229                                         throw new ArgumentException ("An item cannot be added more than once. To add an item again, you need to clone it.", "value");
5230
5231                                 if (value.ListView != null && value.ListView != owner)
5232                                         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");
5233                                 if (is_main_collection)
5234                                         value.Owner = owner;
5235 #if NET_2_0
5236                                 else {
5237                                         if (value.Group != null)
5238                                                 value.Group.Items.Remove (value);
5239
5240                                         value.SetGroup (group);
5241                                 }
5242 #endif
5243
5244                                 list.Add (value);
5245                         }
5246
5247                         void CollectionChanged (bool sort)
5248                         {
5249                                 if (owner != null) {
5250                                         if (sort)
5251                                                 owner.Sort (false);
5252
5253                                         OnChange ();
5254                                         owner.Redraw (true);
5255                                 }
5256                         }
5257
5258 #if NET_2_0
5259                         ListViewItem RetrieveVirtualItemFromOwner (int displayIndex)
5260                         {
5261                                 RetrieveVirtualItemEventArgs args = new RetrieveVirtualItemEventArgs (displayIndex);
5262
5263                                 owner.OnRetrieveVirtualItem (args);
5264                                 ListViewItem retval = args.Item;
5265                                 retval.Owner = owner;
5266                                 retval.DisplayIndex = displayIndex;
5267
5268                                 return retval;
5269                         }
5270 #endif
5271
5272                         internal event CollectionChangedHandler Changed;
5273
5274                         internal void Sort (IComparer comparer)
5275                         {
5276                                 list.Sort (comparer);
5277                                 OnChange ();
5278                         }
5279
5280                         internal void OnChange ()
5281                         {
5282                                 if (Changed != null)
5283                                         Changed ();
5284                         }
5285                 }       // ListViewItemCollection
5286
5287                         
5288                 // In normal mode, the selection information resides in the Items,
5289                 // making SelectedIndexCollection.List read-only
5290                 //
5291                 // In virtual mode, SelectedIndexCollection directly saves the selection
5292                 // information, instead of getting it from Items, making List read-and-write
5293 #if NET_2_0
5294                 [ListBindable (false)]
5295 #endif
5296                 public class SelectedIndexCollection : IList, ICollection, IEnumerable
5297                 {
5298                         private readonly ListView owner;
5299                         private ArrayList list;
5300
5301                         #region Public Constructor
5302                         public SelectedIndexCollection (ListView owner)
5303                         {
5304                                 this.owner = owner;
5305                                 owner.Items.Changed += new CollectionChangedHandler (ItemsCollection_Changed);
5306                         }
5307                         #endregion      // Public Constructor
5308
5309                         #region Public Properties
5310                         [Browsable (false)]
5311                         public int Count {
5312                                 get {
5313                                         if (!owner.IsHandleCreated)
5314                                                 return 0;
5315
5316                                         return List.Count;
5317                                 }
5318                         }
5319
5320                         public bool IsReadOnly {
5321                                 get { 
5322 #if NET_2_0
5323                                         return false;
5324 #else
5325                                         return true; 
5326 #endif
5327                                 }
5328                         }
5329
5330                         public int this [int index] {
5331                                 get {
5332                                         if (!owner.IsHandleCreated || index < 0 || index >= List.Count)
5333                                                 throw new ArgumentOutOfRangeException ("index");
5334
5335                                         return (int) List [index];
5336                                 }
5337                         }
5338
5339                         bool ICollection.IsSynchronized {
5340                                 get { return false; }
5341                         }
5342
5343                         object ICollection.SyncRoot {
5344                                 get { return this; }
5345                         }
5346
5347                         bool IList.IsFixedSize {
5348                                 get { 
5349 #if NET_2_0
5350                                         return false;
5351 #else
5352                                         return true;
5353 #endif
5354                                 }
5355                         }
5356
5357                         object IList.this [int index] {
5358                                 get { return this [index]; }
5359                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
5360                         }
5361                         #endregion      // Public Properties
5362
5363                         #region Public Methods
5364 #if NET_2_0
5365                         public int Add (int itemIndex)
5366                         {
5367                                 if (itemIndex < 0 || itemIndex >= owner.Items.Count)
5368                                         throw new ArgumentOutOfRangeException ("index");
5369
5370                                 if (owner.virtual_mode && !owner.IsHandleCreated)
5371                                         return -1;
5372
5373                                 owner.Items [itemIndex].Selected = true;
5374
5375                                 if (!owner.IsHandleCreated)
5376                                         return 0;
5377
5378                                 return List.Count;
5379                         }
5380 #endif
5381
5382 #if NET_2_0
5383                         public 
5384 #else
5385                         internal
5386 #endif  
5387                         void Clear ()
5388                         {
5389                                 if (!owner.IsHandleCreated)
5390                                         return;
5391
5392                                 int [] indexes = (int []) List.ToArray (typeof (int));
5393                                 foreach (int index in indexes)
5394                                         owner.Items [index].Selected = false;
5395                         }
5396
5397                         public bool Contains (int selectedIndex)
5398                         {
5399                                 return IndexOf (selectedIndex) != -1;
5400                         }
5401
5402                         public void CopyTo (Array dest, int index)
5403                         {
5404                                 List.CopyTo (dest, index);
5405                         }
5406
5407                         public IEnumerator GetEnumerator ()
5408                         {
5409                                 return List.GetEnumerator ();
5410                         }
5411
5412                         int IList.Add (object value)
5413                         {
5414                                 throw new NotSupportedException ("Add operation is not supported.");
5415                         }
5416
5417                         void IList.Clear ()
5418                         {
5419                                 Clear ();
5420                         }
5421
5422                         bool IList.Contains (object selectedIndex)
5423                         {
5424                                 if (!(selectedIndex is int))
5425                                         return false;
5426                                 return Contains ((int) selectedIndex);
5427                         }
5428
5429                         int IList.IndexOf (object selectedIndex)
5430                         {
5431                                 if (!(selectedIndex is int))
5432                                         return -1;
5433                                 return IndexOf ((int) selectedIndex);
5434                         }
5435
5436                         void IList.Insert (int index, object value)
5437                         {
5438                                 throw new NotSupportedException ("Insert operation is not supported.");
5439                         }
5440
5441                         void IList.Remove (object value)
5442                         {
5443                                 throw new NotSupportedException ("Remove operation is not supported.");
5444                         }
5445
5446                         void IList.RemoveAt (int index)
5447                         {
5448                                 throw new NotSupportedException ("RemoveAt operation is not supported.");
5449                         }
5450
5451                         public int IndexOf (int selectedIndex)
5452                         {
5453                                 if (!owner.IsHandleCreated)
5454                                         return -1;
5455
5456                                 return List.IndexOf (selectedIndex);
5457                         }
5458
5459 #if NET_2_0
5460                         public void Remove (int itemIndex)
5461                         {
5462                                 if (itemIndex < 0 || itemIndex >= owner.Items.Count)
5463                                         throw new ArgumentOutOfRangeException ("itemIndex");
5464
5465                                 owner.Items [itemIndex].Selected = false;
5466                         }
5467 #endif
5468                         #endregion      // Public Methods
5469
5470                         internal ArrayList List {
5471                                 get {
5472                                         if (list == null) {
5473                                                 list = new ArrayList ();
5474 #if NET_2_0
5475                                                 if (!owner.VirtualMode)
5476 #endif
5477                                                 for (int i = 0; i < owner.Items.Count; i++) {
5478                                                         if (owner.Items [i].Selected)
5479                                                                 list.Add (i);
5480                                                 }
5481                                         }
5482                                         return list;
5483                                 }
5484                         }
5485
5486                         internal void Reset ()
5487                         {
5488                                 // force re-population of list
5489 #if NET_2_0
5490                                 if (!owner.VirtualMode)
5491 #endif
5492                                 list = null;
5493                         }
5494
5495                         private void ItemsCollection_Changed ()
5496                         {
5497                                 Reset ();
5498                         }
5499
5500 #if NET_2_0
5501                         internal void RemoveIndex (int index)
5502                         {
5503                                 int idx = List.BinarySearch (index);
5504                                 if (idx != -1)
5505                                         List.RemoveAt (idx);
5506                         }
5507
5508                         // actually store index in the collection
5509                         // also, keep the collection sorted, as .Net does
5510                         internal void InsertIndex (int index)
5511                         {
5512                                 int iMin = 0;
5513                                 int iMax = List.Count - 1;
5514                                 while (iMin <= iMax) {
5515                                         int iMid = (iMin + iMax) / 2;
5516                                         int current_index = (int) List [iMid];
5517
5518                                         if (current_index == index)
5519                                                 return; // Already added
5520                                         if (current_index > index)
5521                                                 iMax = iMid - 1;
5522                                         else
5523                                                 iMin = iMid + 1;
5524                                 }
5525
5526                                 List.Insert (iMin, index);
5527                         }
5528 #endif
5529
5530                 }       // SelectedIndexCollection
5531
5532 #if NET_2_0
5533                 [ListBindable (false)]
5534 #endif
5535                 public class SelectedListViewItemCollection : IList, ICollection, IEnumerable
5536                 {
5537                         private readonly ListView owner;
5538
5539                         #region Public Constructor
5540                         public SelectedListViewItemCollection (ListView owner)
5541                         {
5542                                 this.owner = owner;
5543                         }
5544                         #endregion      // Public Constructor
5545
5546                         #region Public Properties
5547                         [Browsable (false)]
5548                         public int Count {
5549                                 get {
5550                                         return owner.SelectedIndices.Count;
5551                                 }
5552                         }
5553
5554                         public bool IsReadOnly {
5555                                 get { return true; }
5556                         }
5557
5558                         public ListViewItem this [int index] {
5559                                 get {
5560                                         if (!owner.IsHandleCreated || index < 0 || index >= Count)
5561                                                 throw new ArgumentOutOfRangeException ("index");
5562
5563                                         int item_index = owner.SelectedIndices [index];
5564                                         return owner.Items [item_index];
5565                                 }
5566                         }
5567
5568 #if NET_2_0
5569                         public virtual ListViewItem this [string key] {
5570                                 get {
5571                                         int idx = IndexOfKey (key);
5572                                         if (idx == -1)
5573                                                 return null;
5574
5575                                         return this [idx];
5576                                 }
5577                         }
5578 #endif
5579
5580                         bool ICollection.IsSynchronized {
5581                                 get { return false; }
5582                         }
5583
5584                         object ICollection.SyncRoot {
5585                                 get { return this; }
5586                         }
5587
5588                         bool IList.IsFixedSize {
5589                                 get { return true; }
5590                         }
5591
5592                         object IList.this [int index] {
5593                                 get { return this [index]; }
5594                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
5595                         }
5596                         #endregion      // Public Properties
5597
5598                         #region Public Methods
5599                         public void Clear ()
5600                         {
5601                                 owner.SelectedIndices.Clear ();
5602                         }
5603
5604                         public bool Contains (ListViewItem item)
5605                         {
5606                                 return IndexOf (item) != -1;
5607                         }
5608
5609 #if NET_2_0
5610                         public virtual bool ContainsKey (string key)
5611                         {
5612                                 return IndexOfKey (key) != -1;
5613                         }
5614 #endif
5615
5616                         public void CopyTo (Array dest, int index)
5617                         {
5618                                 if (!owner.IsHandleCreated)
5619                                         return;
5620                                 if (index > Count) // Throws ArgumentException instead of IOOR exception
5621                                         throw new ArgumentException ("index");
5622
5623                                 for (int i = 0; i < Count; i++)
5624                                         dest.SetValue (this [i], index++);
5625                         }
5626
5627                         public IEnumerator GetEnumerator ()
5628                         {
5629                                 if (!owner.IsHandleCreated)
5630                                         return (new ListViewItem [0]).GetEnumerator ();
5631
5632                                 ListViewItem [] items = new ListViewItem [Count];
5633                                 for (int i = 0; i < Count; i++)
5634                                         items [i] = this [i];
5635
5636                                 return items.GetEnumerator ();
5637                         }
5638
5639                         int IList.Add (object value)
5640                         {
5641                                 throw new NotSupportedException ("Add operation is not supported.");
5642                         }
5643
5644                         bool IList.Contains (object item)
5645                         {
5646                                 if (!(item is ListViewItem))
5647                                         return false;
5648                                 return Contains ((ListViewItem) item);
5649                         }
5650
5651                         int IList.IndexOf (object item)
5652                         {
5653                                 if (!(item is ListViewItem))
5654                                         return -1;
5655                                 return IndexOf ((ListViewItem) item);
5656                         }
5657
5658                         void IList.Insert (int index, object value)
5659                         {
5660                                 throw new NotSupportedException ("Insert operation is not supported.");
5661                         }
5662
5663                         void IList.Remove (object value)
5664                         {
5665                                 throw new NotSupportedException ("Remove operation is not supported.");
5666                         }
5667
5668                         void IList.RemoveAt (int index)
5669                         {
5670                                 throw new NotSupportedException ("RemoveAt operation is not supported.");
5671                         }
5672
5673                         public int IndexOf (ListViewItem item)
5674                         {
5675                                 if (!owner.IsHandleCreated)
5676                                         return -1;
5677
5678                                 for (int i = 0; i < Count; i++)
5679                                         if (this [i] == item)
5680                                                 return i;
5681
5682                                 return -1;
5683                         }
5684
5685 #if NET_2_0
5686                         public virtual int IndexOfKey (string key)
5687                         {
5688                                 if (!owner.IsHandleCreated || key == null || key.Length == 0)
5689                                         return -1;
5690
5691                                 for (int i = 0; i < Count; i++) {
5692                                         ListViewItem item = this [i];
5693                                         if (String.Compare (item.Name, key, true) == 0)
5694                                                 return i;
5695                                 }
5696
5697                                 return -1;
5698                         }
5699 #endif
5700                         #endregion      // Public Methods
5701
5702                 }       // SelectedListViewItemCollection
5703
5704                 internal delegate void CollectionChangedHandler ();
5705
5706                 struct ItemMatrixLocation
5707                 {
5708                         int row;
5709                         int col;
5710
5711                         public ItemMatrixLocation (int row, int col)
5712                         {
5713                                 this.row = row;
5714                                 this.col = col;
5715                 
5716                         }
5717                 
5718                         public int Col {
5719                                 get {
5720                                         return col;
5721                                 }
5722                                 set {
5723                                         col = value;
5724                                 }
5725                         }
5726
5727                         public int Row {
5728                                 get {
5729                                         return row;
5730                                 }
5731                                 set {
5732                                         row = value;
5733                                 }
5734                         }
5735         
5736                 }
5737
5738                 #endregion // Subclasses
5739 #if NET_2_0
5740                 protected override void OnResize (EventArgs e)
5741                 {
5742                         base.OnResize (e);
5743                 }
5744
5745                 protected override void OnMouseLeave (EventArgs e)
5746                 {
5747                         base.OnMouseLeave (e);
5748                 }
5749
5750                 //
5751                 // ColumnReorder event
5752                 //
5753                 static object ColumnReorderedEvent = new object ();
5754                 public event ColumnReorderedEventHandler ColumnReordered {
5755                         add { Events.AddHandler (ColumnReorderedEvent, value); }
5756                         remove { Events.RemoveHandler (ColumnReorderedEvent, value); }
5757                 }
5758
5759                 protected virtual void OnColumnReordered (ColumnReorderedEventArgs e)
5760                 {
5761                         ColumnReorderedEventHandler creh = (ColumnReorderedEventHandler) (Events [ColumnReorderedEvent]);
5762
5763                         if (creh != null)
5764                                 creh (this, e);
5765                 }
5766
5767                 //
5768                 // ColumnWidthChanged
5769                 //
5770                 static object ColumnWidthChangedEvent = new object ();
5771                 public event ColumnWidthChangedEventHandler ColumnWidthChanged {
5772                         add { Events.AddHandler (ColumnWidthChangedEvent, value); }
5773                         remove { Events.RemoveHandler (ColumnWidthChangedEvent, value); }
5774                 }
5775
5776                 protected virtual void OnColumnWidthChanged (ColumnWidthChangedEventArgs e)
5777                 {
5778                         ColumnWidthChangedEventHandler eh = (ColumnWidthChangedEventHandler) (Events[ColumnWidthChangedEvent]);
5779                         if (eh != null)
5780                                 eh (this, e);
5781                 }
5782                 
5783                 void RaiseColumnWidthChanged (int resize_column)
5784                 {
5785                         ColumnWidthChangedEventArgs n = new ColumnWidthChangedEventArgs (resize_column);
5786
5787                         OnColumnWidthChanged (n);
5788                 }
5789                 
5790                 //
5791                 // ColumnWidthChanging
5792                 //
5793                 static object ColumnWidthChangingEvent = new object ();
5794                 public event ColumnWidthChangingEventHandler ColumnWidthChanging {
5795                         add { Events.AddHandler (ColumnWidthChangingEvent, value); }
5796                         remove { Events.RemoveHandler (ColumnWidthChangingEvent, value); }
5797                 }
5798
5799                 protected virtual void OnColumnWidthChanging (ColumnWidthChangingEventArgs e)
5800                 {
5801                         ColumnWidthChangingEventHandler cwceh = (ColumnWidthChangingEventHandler) (Events[ColumnWidthChangingEvent]);
5802                         if (cwceh != null)
5803                                 cwceh (this, e);
5804                 }
5805                 
5806                 //
5807                 // 2.0 profile based implementation
5808                 //
5809                 bool CanProceedWithResize (ColumnHeader col, int width)
5810                 {
5811                         ColumnWidthChangingEventHandler cwceh = (ColumnWidthChangingEventHandler) (Events[ColumnWidthChangingEvent]);
5812                         if (cwceh == null)
5813                                 return true;
5814                         
5815                         ColumnWidthChangingEventArgs changing = new ColumnWidthChangingEventArgs (col.Index, width);
5816                         cwceh (this, changing);
5817                         return !changing.Cancel;
5818                 }
5819 #else
5820                 //
5821                 // 1.0 profile based implementation
5822                 //
5823                 bool CanProceedWithResize (ColumnHeader col, int width)
5824                 {
5825                         return true;
5826                 }
5827
5828                 void RaiseColumnWidthChanged (int resize_column)
5829                 {
5830                 }
5831 #endif
5832         }
5833 }