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