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