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