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