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