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