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