2006-09-29 Mike Kestner <mkestner@novell.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 //
27 // TODO:
28 //   - Feedback for item activation, change in cursor types as mouse moves.
29 //   - LabelEdit
30 //   - Drag and drop
31
32
33 // NOT COMPLETE
34
35
36 using System.Collections;
37 using System.ComponentModel;
38 using System.ComponentModel.Design;
39 using System.Drawing;
40 using System.Runtime.InteropServices;
41 using System.Globalization;
42
43 namespace System.Windows.Forms
44 {
45         [DefaultEvent ("SelectedIndexChanged")]
46         [DefaultProperty ("Items")]
47         [Designer ("System.Windows.Forms.Design.ListViewDesigner, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.IDesigner")]
48         public class ListView : Control
49         {
50                 private ItemActivation activation = ItemActivation.Standard;
51                 private ListViewAlignment alignment = ListViewAlignment.Top;
52                 private bool allow_column_reorder = false;
53                 private bool auto_arrange = true;
54                 private bool check_boxes = false;
55                 private CheckedIndexCollection checked_indices;
56                 private CheckedListViewItemCollection checked_items;
57                 private ColumnHeaderCollection columns;
58                 internal ListViewItem focused_item;
59                 private bool full_row_select = false;
60                 private bool grid_lines = false;
61                 private ColumnHeaderStyle header_style = ColumnHeaderStyle.Clickable;
62                 private bool hide_selection = true;
63                 private bool hover_selection = false;
64                 private IComparer item_sorter;
65                 private ListViewItemCollection items;
66                 private bool label_edit = false;
67                 private bool label_wrap = true;
68                 private bool multiselect = true;
69                 private bool scrollable = true;
70                 private SelectedIndexCollection selected_indices;
71                 private SelectedListViewItemCollection selected_items;
72                 private SortOrder sort_order = SortOrder.None;
73                 private ImageList state_image_list;
74                 private bool updating = false;
75                 private View view = View.LargeIcon;
76                 private int layout_wd;    // We might draw more than our client area
77                 private int layout_ht;    // therefore we need to have these two.
78                 //private TextBox editor;   // Used for editing an item text
79                 HeaderControl header_control;
80                 internal ItemControl item_control;
81                 internal ScrollBar h_scroll; // used for scrolling horizontally
82                 internal ScrollBar v_scroll; // used for scrolling vertically
83                 internal int h_marker;          // Position markers for scrolling
84                 internal int v_marker;
85                 private int keysearch_tickcnt;
86                 private string keysearch_text;
87                 static private readonly int keysearch_keydelay = 1000;
88                 private int[] reordered_column_indices;
89
90                 // internal variables
91                 internal ImageList large_image_list;
92                 internal ImageList small_image_list;
93                 internal Size text_size = Size.Empty;
94
95                 #region Events
96                 public event LabelEditEventHandler AfterLabelEdit;
97
98                 [Browsable (false)]
99                 [EditorBrowsable (EditorBrowsableState.Never)]
100                 public new event EventHandler BackgroundImageChanged {
101                         add { base.BackgroundImageChanged += value; }
102                         remove { base.BackgroundImageChanged -= value; }
103                 }
104
105                 public event LabelEditEventHandler BeforeLabelEdit;
106                 public event ColumnClickEventHandler ColumnClick;
107                 public event EventHandler ItemActivate;
108                 public event ItemCheckEventHandler ItemCheck;
109                 public event ItemDragEventHandler ItemDrag;
110
111                 [Browsable (false)]
112                 [EditorBrowsable (EditorBrowsableState.Never)]
113                 public new event PaintEventHandler Paint {
114                         add { base.Paint += value; }
115                         remove { base.Paint -= value; }
116                 }
117
118                 public event EventHandler SelectedIndexChanged;
119
120                 [Browsable (false)]
121                 [EditorBrowsable (EditorBrowsableState.Never)]
122                 public new event EventHandler TextChanged {
123                         add { base.TextChanged += value; }
124                         remove { base.TextChanged -= value; }
125                 }
126
127                 #endregion // Events
128
129                 #region Public Constructors
130                 public ListView ()
131                 {
132                         background_color = ThemeEngine.Current.ColorWindow;
133                         checked_indices = new CheckedIndexCollection (this);
134                         checked_items = new CheckedListViewItemCollection (this);
135                         columns = new ColumnHeaderCollection (this);
136                         foreground_color = SystemColors.WindowText;
137                         items = new ListViewItemCollection (this);
138                         selected_indices = new SelectedIndexCollection (this);
139                         selected_items = new SelectedListViewItemCollection (this);
140
141                         border_style = BorderStyle.Fixed3D;
142
143                         header_control = new HeaderControl (this);
144                         header_control.Visible = false;
145                         Controls.AddImplicit (header_control);
146
147                         item_control = new ItemControl (this);
148                         Controls.AddImplicit (item_control);
149
150                         h_scroll = new HScrollBar ();
151                         Controls.AddImplicit (this.h_scroll);
152
153                         v_scroll = new VScrollBar ();
154                         Controls.AddImplicit (this.v_scroll);
155
156                         h_marker = v_marker = 0;
157                         keysearch_tickcnt = 0;
158
159                         // scroll bars are disabled initially
160                         h_scroll.Visible = false;
161                         h_scroll.ValueChanged += new EventHandler(HorizontalScroller);
162                         v_scroll.Visible = false;
163                         v_scroll.ValueChanged += new EventHandler(VerticalScroller);
164
165                         // event handlers
166                         base.KeyDown += new KeyEventHandler(ListView_KeyDown);
167                         SizeChanged += new EventHandler (ListView_SizeChanged);
168                         GotFocus += new EventHandler (FocusChanged);
169                         LostFocus += new EventHandler (FocusChanged);
170                         MouseWheel += new MouseEventHandler(ListView_MouseWheel);
171
172                         this.SetStyle (ControlStyles.UserPaint | ControlStyles.StandardClick, false);
173                 }
174                 #endregion      // Public Constructors
175
176                 #region Private Internal Properties
177                 internal Size CheckBoxSize {
178                         get {
179                                 if (this.check_boxes) {
180                                         if (this.state_image_list != null)
181                                                 return this.state_image_list.ImageSize;
182                                         else
183                                                 return ThemeEngine.Current.ListViewCheckBoxSize;
184                                 }
185                                 return Size.Empty;
186                         }
187                 }
188
189                 #endregion      // Private Internal Properties
190
191                 #region  Protected Properties
192                 protected override CreateParams CreateParams {
193                         get { return base.CreateParams; }
194                 }
195
196                 protected override Size DefaultSize {
197                         get { return ThemeEngine.Current.ListViewDefaultSize; }
198                 }
199                 #endregion      // Protected Properties
200
201                 #region Public Instance Properties
202                 [DefaultValue (ItemActivation.Standard)]
203                 public ItemActivation Activation {
204                         get { return activation; }
205                         set { 
206                                 if (value != ItemActivation.Standard && value != ItemActivation.OneClick && 
207                                         value != ItemActivation.TwoClick) {
208                                         throw new InvalidEnumArgumentException (string.Format
209                                                 ("Enum argument value '{0}' is not valid for Activation", value));
210                                 }
211                                   
212                                 activation = value;
213                         }
214                 }
215
216                 [DefaultValue (ListViewAlignment.Top)]
217                 [Localizable (true)]
218                 public ListViewAlignment Alignment {
219                         get { return alignment; }
220                         set {
221                                 if (value != ListViewAlignment.Default && value != ListViewAlignment.Left && 
222                                         value != ListViewAlignment.SnapToGrid && value != ListViewAlignment.Top) {
223                                         throw new InvalidEnumArgumentException (string.Format 
224                                                 ("Enum argument value '{0}' is not valid for Alignment", value));
225                                 }
226                                 
227                                 if (this.alignment != value) {
228                                         alignment = value;
229                                         // alignment does not matter in Details/List views
230                                         if (this.view == View.LargeIcon ||
231                                             this.View == View.SmallIcon)
232                                                 this.Redraw (true);
233                                 }
234                         }
235                 }
236
237                 [DefaultValue (false)]
238                 public bool AllowColumnReorder {
239                         get { return allow_column_reorder; }
240                         set { allow_column_reorder = value; }
241                 }
242
243                 [DefaultValue (true)]
244                 public bool AutoArrange {
245                         get { return auto_arrange; }
246                         set {
247                                 if (auto_arrange != value) {
248                                         auto_arrange = value;
249                                         // autoarrange does not matter in Details/List views
250                                         if (this.view == View.LargeIcon || this.View == View.SmallIcon)
251                                                 this.Redraw (true);
252                                 }
253                         }
254                 }
255
256                 public override Color BackColor {
257                         get {
258                                 if (background_color.IsEmpty)
259                                         return ThemeEngine.Current.ColorWindow;
260                                 else
261                                         return background_color;
262                         }
263                         set { background_color = value; }
264                 }
265
266                 [Browsable (false)]
267                 [EditorBrowsable (EditorBrowsableState.Never)]
268                 public override Image BackgroundImage {
269                         get { return background_image; }
270                         set {
271                                 if (value == background_image)
272                                         return;
273
274                                 background_image = value;
275                                 OnBackgroundImageChanged (EventArgs.Empty);
276                         }
277                 }
278
279                 [DefaultValue (BorderStyle.Fixed3D)]
280                 [DispId (-504)]
281                 public BorderStyle BorderStyle {
282                         get { return InternalBorderStyle; }
283                         set { InternalBorderStyle = value; }
284                 }
285
286                 [DefaultValue (false)]
287                 public bool CheckBoxes {
288                         get { return check_boxes; }
289                         set {
290                                 if (check_boxes != value) {
291 #if NET_2_0
292                                         if (value && View == View.Tile)
293                                                 throw new NotSupportedException ("CheckBoxes are not"
294                                                         + " supported in Tile view. Choose a different"
295                                                         + " view or set CheckBoxes to false.");
296 #endif
297
298                                         check_boxes = value;
299                                         this.Redraw (true);
300                                 }
301                         }
302                 }
303
304                 [Browsable (false)]
305                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
306                 public CheckedIndexCollection CheckedIndices {
307                         get { return checked_indices; }
308                 }
309
310                 [Browsable (false)]
311                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
312                 public CheckedListViewItemCollection CheckedItems {
313                         get { return checked_items; }
314                 }
315
316                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
317                 [Localizable (true)]
318                 [MergableProperty (false)]
319                 public ColumnHeaderCollection Columns {
320                         get { return columns; }
321                 }
322
323                 [Browsable (false)]
324                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
325                 public ListViewItem FocusedItem {
326                         get {
327                                 return focused_item;
328                         }
329                 }
330
331                 public override Color ForeColor {
332                         get {
333                                 if (foreground_color.IsEmpty)
334                                         return ThemeEngine.Current.ColorWindowText;
335                                 else
336                                         return foreground_color;
337                         }
338                         set { foreground_color = value; }
339                 }
340
341                 [DefaultValue (false)]
342                 public bool FullRowSelect {
343                         get { return full_row_select; }
344                         set { full_row_select = value; }
345                 }
346
347                 [DefaultValue (false)]
348                 public bool GridLines {
349                         get { return grid_lines; }
350                         set {
351                                 if (grid_lines != value) {
352                                         grid_lines = value;
353                                         this.Redraw (false);
354                                 }
355                         }
356                 }
357
358                 [DefaultValue (ColumnHeaderStyle.Clickable)]
359                 public ColumnHeaderStyle HeaderStyle {
360                         get { return header_style; }
361                         set {
362                                 if (header_style == value)
363                                         return;
364
365                                 switch (value) {
366                                 case ColumnHeaderStyle.Clickable:
367                                 case ColumnHeaderStyle.Nonclickable:
368                                 case ColumnHeaderStyle.None:
369                                         break;
370                                 default:
371                                         throw new InvalidEnumArgumentException (string.Format 
372                                                 ("Enum argument value '{0}' is not valid for ColumnHeaderStyle", value));
373                                 }
374                                 
375                                 header_style = value;
376                                 if (view == View.Details)
377                                         Redraw (true);
378                         }
379                 }
380
381                 [DefaultValue (true)]
382                 public bool HideSelection {
383                         get { return hide_selection; }
384                         set {
385                                 if (hide_selection != value) {
386                                         hide_selection = value;
387                                         this.Redraw (false);
388                                 }
389                         }
390                 }
391
392                 [DefaultValue (false)]
393                 public bool HoverSelection {
394                         get { return hover_selection; }
395                         set { hover_selection = value; }
396                 }
397
398                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Content)]
399                 [Localizable (true)]
400                 [MergableProperty (false)]              
401                 public ListViewItemCollection Items {
402                         get { return items; }
403                 }
404
405                 [DefaultValue (false)]
406                 public bool LabelEdit {
407                         get { return label_edit; }
408                         set { label_edit = value; }
409                 }
410
411                 [DefaultValue (true)]
412                 [Localizable (true)]
413                 public bool LabelWrap {
414                         get { return label_wrap; }
415                         set {
416                                 if (label_wrap != value) {
417                                         label_wrap = value;
418                                         this.Redraw (true);
419                                 }
420                         }
421                 }
422
423                 [DefaultValue (null)]
424                 public ImageList LargeImageList {
425                         get { return large_image_list; }
426                         set {
427                                 large_image_list = value;
428                                 this.Redraw (true);
429                         }
430                 }
431
432                 [Browsable (false)]
433                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
434                 public IComparer ListViewItemSorter {
435                         get {
436                                 if (View != View.SmallIcon && View != View.LargeIcon && item_sorter is ItemComparer)
437                                         return null;
438                                 return item_sorter;
439                         }
440                         set {
441                                 if (item_sorter != value) {
442                                         item_sorter = value;
443                                         Sort ();
444                                 }
445                         }
446                 }
447
448                 [DefaultValue (true)]
449                 public bool MultiSelect {
450                         get { return multiselect; }
451                         set { multiselect = value; }
452                 }
453
454                 [DefaultValue (true)]
455                 public bool Scrollable {
456                         get { return scrollable; }
457                         set {
458                                 if (scrollable != value) {
459                                         scrollable = value;
460                                         this.Redraw (true);
461                                 }
462                         }
463                 }
464
465                 [Browsable (false)]
466                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
467                 public SelectedIndexCollection SelectedIndices {
468                         get { return selected_indices; }
469                 }
470
471                 [Browsable (false)]
472                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
473                 public SelectedListViewItemCollection SelectedItems {
474                         get { return selected_items; }
475                 }
476
477 #if NET_2_0
478                 [MonoTODO("Implement")]
479                 public bool ShowGroups {
480                         get {
481                                 return false;
482                         }
483
484                         set {
485                         }
486                 }
487 #endif
488
489                 [DefaultValue (null)]
490                 public ImageList SmallImageList {
491                         get { return small_image_list; }
492                         set {
493                                 small_image_list = value;
494                                 this.Redraw (true);
495                         }
496                 }
497
498                 [DefaultValue (SortOrder.None)]
499                 public SortOrder Sorting {
500                         get { return sort_order; }
501                         set { 
502                                 if (!Enum.IsDefined (typeof (SortOrder), value)) {
503                                         throw new InvalidEnumArgumentException ("value", (int) value,
504                                                 typeof (SortOrder));
505                                 }
506                                 
507                                 if (sort_order == value)
508                                         return;
509
510                                 sort_order = value;
511
512                                 if (value == SortOrder.None) {
513                                         if (item_sorter != null) {
514                                                 // ListViewItemSorter should never be reset for SmallIcon
515                                                 // and LargeIcon view
516                                                 if (View != View.SmallIcon && View != View.LargeIcon)
517 #if NET_2_0
518                                                         item_sorter = null;
519 #else
520                                                         // in .NET 1.1, only internal IComparer would be
521                                                         // set to null
522                                                         if (item_sorter is ItemComparer)
523                                                                 item_sorter = null;
524 #endif
525                                         }
526                                         this.Redraw (false);
527                                 } else {
528                                         if (item_sorter == null)
529                                                 item_sorter = new ItemComparer (value);
530                                         if (item_sorter is ItemComparer) {
531 #if NET_2_0
532                                                 item_sorter = new ItemComparer (value);
533 #else
534                                                 // in .NET 1.1, the sort order is not updated for
535                                                 // SmallIcon and LargeIcon views if no custom IComparer
536                                                 // is set
537                                                 if (View != View.SmallIcon && View != View.LargeIcon)
538                                                         item_sorter = new ItemComparer (value);
539 #endif
540                                         }
541                                         Sort ();
542                                 }
543                         }
544                 }
545
546                 [DefaultValue (null)]
547                 public ImageList StateImageList {
548                         get { return state_image_list; }
549                         set {
550                                 state_image_list = value;
551                                 this.Redraw (true);
552                         }
553                 }
554
555                 [Bindable (false)]
556                 [Browsable (false)]
557                 [EditorBrowsable (EditorBrowsableState.Never)]
558                 public override string Text {
559                         get { return text; } 
560                         set {
561                                 if (value == text)
562                                         return;
563
564                                 text = value;
565                                 this.Redraw (true);
566
567                                 OnTextChanged (EventArgs.Empty);
568                         }
569                 }
570
571                 [Browsable (false)]
572                 [DesignerSerializationVisibility (DesignerSerializationVisibility.Hidden)]
573                 public ListViewItem TopItem {
574                         get {
575                                 // there is no item
576                                 if (this.items.Count == 0)
577                                         return null;
578                                 // if contents are not scrolled
579                                 // it is the first item
580                                 else if (h_marker == 0 && v_marker == 0)
581                                         return this.items [0];
582                                 // do a hit test for the scrolled position
583                                 else {
584                                         foreach (ListViewItem item in this.items) {
585                                                 if (item.Bounds.X >= 0 && item.Bounds.Y >= 0)
586                                                         return item;
587                                         }
588                                         return null;
589                                 }
590                         }
591                 }
592
593 #if NET_2_0
594                 [MonoTODO("Implement")]
595                 public bool UseCompatibleStateImageBehavior {
596                         get {
597                                 return false;
598                         }
599
600                         set {
601                         }
602                 }
603 #endif
604
605                 [DefaultValue (View.LargeIcon)]
606                 public View View {
607                         get { return view; }
608                         set { 
609                                 if (!Enum.IsDefined (typeof (View), value))
610                                         throw new InvalidEnumArgumentException ("value", (int) value,
611                                                 typeof (View));
612
613                                 if (view != value) {
614 #if NET_2_0
615                                         if (CheckBoxes && value == View.Tile)
616                                                 throw new NotSupportedException ("CheckBoxes are not"
617                                                         + " supported in Tile view. Choose a different"
618                                                         + " view or set CheckBoxes to false.");
619 #endif
620
621                                         h_scroll.Value = v_scroll.Value = 0;
622                                         view = value; 
623                                         Redraw (true);
624                                 }
625                         }
626                 }
627                 #endregion      // Public Instance Properties
628
629                 #region Internal Methods Properties
630                 
631                 internal int FirstVisibleIndex {
632                         get {
633                                 // there is no item
634                                 if (this.items.Count == 0)
635                                         return 0;
636                                                                         
637                                 if (h_marker == 0 && v_marker == 0)
638                                         return 0;                                       
639                                 
640                                 foreach (ListViewItem item in this.items) {
641                                         if (item.Bounds.Right >= 0 && item.Bounds.Bottom >= 0)
642                                                 return item.Index;
643                                 }
644                                 return 0;
645
646                         }
647                 }
648
649                 
650                 internal int LastVisibleIndex {                 
651                         get {                                                   
652                                 for (int i = FirstVisibleIndex; i < Items.Count; i++) {
653                                         if (View == View.List || Alignment == ListViewAlignment.Left) {
654                                                 if (Items[i].Bounds.X > ClientRectangle.Right)
655                                                         return i - 1;                                   
656                                         } else {
657                                                 if (Items[i].Bounds.Y > ClientRectangle.Bottom)
658                                                         return i - 1;                                   
659                                         }
660                                 }
661                                 
662                                 return Items.Count - 1;
663                         }
664                 }
665                 
666                 internal int TotalWidth {
667                         get { return Math.Max (this.Width, this.layout_wd); }
668                 }
669
670                 internal int TotalHeight {
671                         get { return Math.Max (this.Height, this.layout_ht); }
672                 }
673
674                 internal void Redraw (bool recalculate)
675                 {
676                         // Avoid calculations when control is being updated
677                         if (this.updating)
678                                 return;
679
680                         if (recalculate)
681                                 CalculateListView (this.alignment);
682
683                         Refresh ();
684                 }
685
686                 internal Size GetChildColumnSize (int index)
687                 {
688                         Size ret_size = Size.Empty;
689                         ColumnHeader col = this.columns [index];
690
691                         if (col.Width == -2) { // autosize = max(items, columnheader)
692                                 Size size = Size.Ceiling (this.DeviceContext.MeasureString
693                                                           (col.Text, this.Font));
694                                 ret_size = BiggestItem (index);
695                                 if (size.Width > ret_size.Width)
696                                         ret_size = size;
697                         }
698                         else { // -1 and all the values < -2 are put under one category
699                                 ret_size = BiggestItem (index);
700                                 // fall back to empty columns' width if no subitem is available for a column
701                                 if (ret_size.IsEmpty) {
702                                         ret_size.Width = ThemeEngine.Current.ListViewEmptyColumnWidth;
703                                         if (col.Text.Length > 0)
704                                                 ret_size.Height = Size.Ceiling (this.DeviceContext.MeasureString
705                                                                                 (col.Text, this.Font)).Height;
706                                         else
707                                                 ret_size.Height = this.Font.Height;
708                                 }
709                         }
710
711                         // adjust the size for icon and checkbox for 0th column
712                         if (index == 0) {
713                                 ret_size.Width += (this.CheckBoxSize.Width + 4);
714                                 if (this.small_image_list != null)
715                                         ret_size.Width += this.small_image_list.ImageSize.Width;
716                         }
717                         return ret_size;
718                 }
719
720                 // Returns the size of biggest item text in a column.
721                 private Size BiggestItem (int col)
722                 {
723                         Size temp = Size.Empty;
724                         Size ret_size = Size.Empty;
725
726                         // 0th column holds the item text, we check the size of
727                         // the various subitems falling in that column and get
728                         // the biggest one's size.
729                         foreach (ListViewItem item in items) {
730                                 if (col >= item.SubItems.Count)
731                                         continue;
732
733                                 temp = Size.Ceiling (this.DeviceContext.MeasureString
734                                                      (item.SubItems [col].Text, this.Font));
735                                 if (temp.Width > ret_size.Width)
736                                         ret_size = temp;
737                         }
738
739                         // adjustment for space
740                         if (!ret_size.IsEmpty)
741                                 ret_size.Width += 4;
742
743                         return ret_size;
744                 }
745
746                 // Sets the size of the biggest item text as per the view
747                 private void CalcTextSize ()
748                 {                       
749                         // clear the old value
750                         text_size = Size.Empty;
751
752                         if (items.Count == 0)
753                                 return;
754
755                         text_size = BiggestItem (0);
756
757                         if (view == View.LargeIcon && this.label_wrap) {
758                                 Size temp = Size.Empty;
759                                 if (this.check_boxes)
760                                         temp.Width += 2 * this.CheckBoxSize.Width;
761                                 if (large_image_list != null)
762                                         temp.Width += large_image_list.ImageSize.Width;
763                                 if (temp.Width == 0)
764                                         temp.Width = 43;
765                                 // wrapping is done for two lines only
766                                 if (text_size.Width > temp.Width) {
767                                         text_size.Width = temp.Width;
768                                         text_size.Height *= 2;
769                                 }
770                         }
771                         else if (view == View.List) {
772                                 // in list view max text shown in determined by the
773                                 // control width, even if scolling is enabled.
774                                 int max_wd = this.Width - (this.CheckBoxSize.Width - 2);
775                                 if (this.small_image_list != null)
776                                         max_wd -= this.small_image_list.ImageSize.Width;
777
778                                 if (text_size.Width > max_wd)
779                                         text_size.Width = max_wd;
780                         }
781
782                         // we do the default settings, if we have got 0's
783                         if (text_size.Height <= 0)
784                                 text_size.Height = this.Font.Height;
785                         if (text_size.Width <= 0)
786                                 text_size.Width = this.Width;
787
788                         // little adjustment
789                         text_size.Width += 4;
790                         text_size.Height += 2;
791                 }
792
793                 private void Scroll (ScrollBar scrollbar, int delta)
794                 {
795                         if (delta == 0 || !scrollbar.Visible)
796                                 return;
797
798                         int max;
799                         if (scrollbar == h_scroll)
800                                 max = h_scroll.Maximum - item_control.Width;
801                         else
802                                 max = v_scroll.Maximum - item_control.Height;
803
804                         int val = scrollbar.Value + delta;
805                         if (val > max)
806                                 val = max;
807                         else if (val < scrollbar.Minimum)
808                                 val = scrollbar.Minimum;
809                         scrollbar.Value = val;
810                 }
811
812                 private void CalculateScrollBars ()
813                 {
814                         Rectangle client_area = ClientRectangle;
815                         
816                         if (!this.scrollable || this.items.Count <= 0) {
817                                 h_scroll.Visible = false;
818                                 v_scroll.Visible = false;
819                                 item_control.Location = new Point (0, header_control.Height);
820                                 item_control.Height = ClientRectangle.Width - header_control.Height;
821                                 item_control.Width = ClientRectangle.Width;
822                                 header_control.Width = ClientRectangle.Width;
823                                 return;
824                         }
825
826                         // Don't calculate if the view is not displayable
827                         if (client_area.Height < 0 || client_area.Width < 0)
828                                 return;
829
830                         // making a scroll bar visible might make
831                         // other scroll bar visible                     
832                         if (layout_wd > client_area.Right) {
833                                 h_scroll.Visible = true;
834                                 if ((layout_ht + h_scroll.Height) > client_area.Bottom)
835                                         v_scroll.Visible = true;                                        
836                                 else
837                                         v_scroll.Visible = false;
838                         } else if (layout_ht > client_area.Bottom) {                            
839                                 v_scroll.Visible = true;
840                                 if ((layout_wd + v_scroll.Width) > client_area.Right)
841                                         h_scroll.Visible = true;
842                                 else
843                                         h_scroll.Visible = false;
844                         } else {
845                                 h_scroll.Visible = false;
846                                 v_scroll.Visible = false;
847                         }                       
848
849                         item_control.Height = ClientRectangle.Height - header_control.Height;
850
851                         if (h_scroll.Visible) {
852                                 h_scroll.Location = new Point (client_area.X, client_area.Bottom - h_scroll.Height);
853                                 h_scroll.Minimum = 0;
854
855                                 // if v_scroll is visible, adjust the maximum of the
856                                 // h_scroll to account for the width of v_scroll
857                                 if (v_scroll.Visible) {
858                                         h_scroll.Maximum = layout_wd + v_scroll.Width;
859                                         h_scroll.Width = client_area.Width - v_scroll.Width;
860                                 }
861                                 else {
862                                         h_scroll.Maximum = layout_wd;
863                                         h_scroll.Width = client_area.Width;
864                                 }
865    
866                                 h_scroll.LargeChange = client_area.Width;
867                                 h_scroll.SmallChange = Font.Height;
868                                 item_control.Height -= h_scroll.Height;
869                         }
870
871                         if (header_control.Visible)
872                                 header_control.Width = ClientRectangle.Width;
873                         item_control.Width = ClientRectangle.Width;
874
875                         if (v_scroll.Visible) {
876                                 v_scroll.Location = new Point (client_area.Right - v_scroll.Width, client_area.Y);
877                                 v_scroll.Minimum = 0;
878
879                                 // if h_scroll is visible, adjust the maximum of the
880                                 // v_scroll to account for the height of h_scroll
881                                 if (h_scroll.Visible) {
882                                         v_scroll.Maximum = layout_ht + h_scroll.Height;
883                                         v_scroll.Height = client_area.Height; // - h_scroll.Height already done 
884                                 } else {
885                                         v_scroll.Maximum = layout_ht;
886                                         v_scroll.Height = client_area.Height;
887                                 }
888
889                                 v_scroll.LargeChange = client_area.Height;
890                                 v_scroll.SmallChange = Font.Height;
891                                 if (header_control.Visible)
892                                         header_control.Width -= v_scroll.Width;
893                                 item_control.Width -= v_scroll.Width;
894                         }
895                 }
896                 
897                 ColumnHeader GetReorderedColumn (int index)
898                 {
899                         if (reordered_column_indices == null)
900                                 return Columns [index];
901                         else
902                                 return Columns [reordered_column_indices [index]];
903                 }
904
905                 void ReorderColumn (ColumnHeader col, int index)
906                 {
907                         if (reordered_column_indices == null) {
908                                 reordered_column_indices = new int [Columns.Count];
909                                 for (int i = 0; i < Columns.Count; i++)
910                                         reordered_column_indices [i] = i;
911                         }
912
913                         if (reordered_column_indices [index] == col.Index)
914                                 return;
915
916                         int[] curr = reordered_column_indices;
917                         int[] result = new int [Columns.Count];
918                         int curr_idx = 0;
919                         for (int i = 0; i < Columns.Count; i++) {
920                                 if (curr_idx < Columns.Count && curr [curr_idx] == col.Index)
921                                         curr_idx++;
922
923                                 if (i == index)
924                                         result [i] = col.Index;
925                                 else
926                                         result [i] = curr [curr_idx++];
927                         }
928
929                         reordered_column_indices = result;
930                         LayoutDetails ();
931                         header_control.Invalidate ();
932                         item_control.Invalidate ();
933                 }
934
935                 Size LargeIconItemSize {
936                         get {
937                                 int image_w = LargeImageList == null ? 12 : LargeImageList.ImageSize.Width;
938                                 int image_h = LargeImageList == null ? 2 : LargeImageList.ImageSize.Height;
939                                 int w = CheckBoxSize.Width + 2 + Math.Max (text_size.Width, image_w);
940                                 int h = text_size.Height + 2 + Math.Max (CheckBoxSize.Height, image_h);
941                                 return new Size (w, h);
942                         }
943                 }
944
945                 Size SmallIconItemSize {
946                         get {
947                                 int image_w = SmallImageList == null ? 0 : SmallImageList.ImageSize.Width;
948                                 int image_h = SmallImageList == null ? 0 : SmallImageList.ImageSize.Height;
949                                 int w = text_size.Width + 2 + CheckBoxSize.Width + image_w;
950                                 int h = Math.Max (text_size.Height, Math.Max (CheckBoxSize.Height, image_h));
951                                 return new Size (w, h);
952                         }
953                 }
954
955                 int rows;
956                 int cols;
957                 ListViewItem[,] item_matrix;
958
959                 void LayoutIcons (bool large_icons, bool left_aligned, int x_spacing, int y_spacing)
960                 {
961                         header_control.Visible = false;
962                         header_control.Size = Size.Empty;
963                         item_control.Visible = true;
964                         item_control.Location = Point.Empty;
965
966                         if (items.Count == 0)
967                                 return;
968
969                         Size sz = large_icons ? LargeIconItemSize : SmallIconItemSize;
970
971                         Rectangle area = ClientRectangle;
972
973                         if (left_aligned) {
974                                 rows = (int) Math.Floor ((double)(area.Height - h_scroll.Height + y_spacing) / (double)(sz.Height + y_spacing));
975                                 if (rows <= 0)
976                                         rows = 1;
977                                 cols = (int) Math.Ceiling ((double)items.Count / (double)rows);
978                         } else {
979                                 cols = (int) Math.Floor ((double)(area.Width - v_scroll.Width + x_spacing) / (double)(sz.Width + x_spacing));
980                                 if (cols <= 0)
981                                         cols = 1;
982                                 rows = (int) Math.Ceiling ((double)items.Count / (double)cols);
983                         }
984
985                         layout_ht = rows * (sz.Height + y_spacing) - y_spacing;
986                         layout_wd = cols * (sz.Width + x_spacing) - x_spacing;
987                         item_matrix = new ListViewItem [rows, cols];
988                         int row = 0;
989                         int col = 0;
990                         foreach (ListViewItem item in items) {
991                                 int x = col * (sz.Width + x_spacing);
992                                 int y = row * (sz.Height + y_spacing);
993                                 item.Location = new Point (x, y);
994                                 item.Layout ();
995                                 item.row = row;
996                                 item.col = col;
997                                 item_matrix [row, col] = item;
998                                 if (left_aligned) {
999                                         if (++row == rows) {
1000                                                 row = 0;
1001                                                 col++;
1002                                         }
1003                                 } else {
1004                                         if (++col == cols) {
1005                                                 col = 0;
1006                                                 row++;
1007                                         }
1008                                 }
1009                         }
1010
1011                         item_control.Size = new Size (layout_wd, layout_ht);
1012                 }
1013
1014                 void LayoutHeader ()
1015                 {
1016                         int x = 0;
1017                         for (int i = 0; i < Columns.Count; i++) {
1018                                 ColumnHeader col = GetReorderedColumn (i);
1019                                 col.X = x;
1020                                 col.Y = 0;
1021                                 col.CalcColumnHeader ();
1022                                 x += col.Wd;
1023                         }
1024
1025                         if (x < ClientRectangle.Width)
1026                                 x = ClientRectangle.Width;
1027
1028                         if (header_style == ColumnHeaderStyle.None) {
1029                                 header_control.Visible = false;
1030                                 header_control.Size = Size.Empty;
1031                         } else {
1032                                 header_control.Width = x;
1033                                 header_control.Height = columns [0].Ht;
1034                                 header_control.Visible = true;
1035                         }
1036                 }
1037
1038                 void LayoutDetails ()
1039                 {
1040                         if (columns.Count == 0) {
1041                                 header_control.Visible = false;
1042                                 item_control.Visible = false;
1043                                 return;
1044                         }
1045
1046                         LayoutHeader ();
1047
1048                         item_control.Visible = true;
1049                         item_control.Location = new Point (0, header_control.Height);
1050
1051                         int y = 0; 
1052                         if (items.Count > 0) {
1053                                 foreach (ListViewItem item in items) {
1054                                         item.Layout ();
1055                                         item.Location = new Point (0, y);
1056                                         y += item.Bounds.Height + 2;
1057                                 }
1058
1059                                 // some space for bottom gridline
1060                                 if (grid_lines)
1061                                         y += 2;
1062                         }
1063
1064                         layout_wd = Math.Max (header_control.Width, item_control.Width);
1065                         layout_ht = y + header_control.Height;
1066                 }
1067
1068                 private void CalculateListView (ListViewAlignment align)
1069                 {
1070                         CalcTextSize ();
1071
1072                         switch (view) {
1073                         case View.Details:
1074                                 LayoutDetails ();
1075                                 break;
1076
1077                         case View.SmallIcon:
1078                                 LayoutIcons (false, alignment == ListViewAlignment.Left, 4, 2);
1079                                 break;
1080
1081                         case View.LargeIcon:
1082                                 LayoutIcons (true, alignment == ListViewAlignment.Left,
1083                                              ThemeEngine.Current.ListViewHorizontalSpacing,
1084                                              ThemeEngine.Current.ListViewVerticalSpacing);
1085                                 break;
1086
1087                         case View.List:
1088                                 LayoutIcons (false, true, 4, 2);
1089                                 break;
1090                         }
1091
1092                         CalculateScrollBars ();
1093                 }
1094
1095                 bool HaveModKeys {
1096                         get {
1097                                 return (XplatUI.State.ModifierKeys & (Keys.Control | Keys.Shift)) != 0;
1098                         }
1099                 }
1100
1101                 internal void UpdateSelection (ListViewItem item)
1102                 {
1103                         if (item.Selected) {
1104                                 if (!MultiSelect && SelectedItems.Count > 0)
1105                                         SelectedItems.Clear ();
1106
1107                                 if (!SelectedItems.list.Contains (item))
1108                                         SelectedItems.list.Add (item);
1109                         } else {
1110                                 SelectedItems.list.Remove (item);
1111                         }
1112                 }
1113
1114                 private bool KeySearchString (KeyEventArgs ke)
1115                 {
1116                         int current_tickcnt = Environment.TickCount;
1117                         if (keysearch_tickcnt > 0 && current_tickcnt - keysearch_tickcnt > keysearch_keydelay) {
1118                                 keysearch_text = string.Empty;
1119                         }
1120                         
1121                         keysearch_text += (char) ke.KeyData;
1122                         keysearch_tickcnt = current_tickcnt;
1123
1124                         int start = FocusedItem == null ? 0 : FocusedItem.Index;
1125                         int i = start;
1126                         while (true) {
1127                                 if (CultureInfo.CurrentCulture.CompareInfo.IsPrefix (Items[i].Text, keysearch_text,
1128                                         CompareOptions.IgnoreCase)) {
1129                                         SetFocusedItem (Items [i]);
1130                                         items [i].Selected = true;
1131                                         EnsureVisible (i);
1132                                         break;
1133                                 }
1134                                 i = (i + 1  < Items.Count) ? i+1 : 0;
1135
1136                                 if (i == start)
1137                                         break;
1138                         }
1139                         return true;
1140                 }
1141
1142                 int GetAdjustedIndex (Keys key)
1143                 {
1144                         int result = -1;
1145
1146                         if (View == View.Details) {
1147                                 if (key == Keys.Up)
1148                                         result = FocusedItem.Index - 1;
1149                                 else if (key == Keys.Down) {
1150                                         result = FocusedItem.Index + 1;
1151                                         if (result == items.Count)
1152                                                 result = -1;
1153                                 }
1154                                 return result;
1155                         }
1156
1157                         int row = FocusedItem.row;
1158                         int col = FocusedItem.col;
1159
1160                         switch (key) {
1161                         case Keys.Left:
1162                                 if (col == 0)
1163                                         return -1;
1164                                 return item_matrix [row, col - 1].Index;
1165
1166                         case Keys.Right:
1167                                 if (col == (cols - 1))
1168                                         return -1;
1169                                 while (item_matrix [row, col + 1] == null)
1170                                        row--;   
1171                                 return item_matrix [row, col + 1].Index;
1172
1173                         case Keys.Up:
1174                                 if (row == 0)
1175                                         return -1;
1176                                 return item_matrix [row - 1, col].Index;
1177
1178                         case Keys.Down:
1179                                 if (row == (rows - 1) || row == Items.Count - 1)
1180                                         return -1;
1181                                 while (item_matrix [row + 1, col] == null)
1182                                        col--;   
1183                                 return item_matrix [row + 1, col].Index;
1184
1185                         default:
1186                                 return -1;
1187                         }
1188                 }
1189
1190                 ListViewItem selection_start;
1191
1192                 private bool SelectItems (ArrayList sel_items)
1193                 {
1194                         bool changed = false;
1195                         ArrayList curr_items = (ArrayList) SelectedItems.list.Clone ();
1196                         foreach (ListViewItem item in curr_items)
1197                                 if (!sel_items.Contains (item)) {
1198                                         item.Selected = false;
1199                                         changed = true;
1200                                 }
1201                         foreach (ListViewItem item in sel_items)
1202                                 if (!item.Selected) {
1203                                         item.Selected = true;
1204                                         changed = true;
1205                                 }
1206                         return changed;
1207                 }
1208
1209                 private void UpdateMultiSelection (int index)
1210                 {
1211                         bool shift_pressed = (XplatUI.State.ModifierKeys & Keys.Shift) != 0;
1212                         bool ctrl_pressed = (XplatUI.State.ModifierKeys & Keys.Control) != 0;
1213                         ListViewItem item = items [index];
1214
1215                         if (shift_pressed && selection_start != null) {
1216                                 ArrayList list = new ArrayList ();
1217                                 int start = Math.Min (selection_start.Index, index);
1218                                 int end = Math.Max (selection_start.Index, index);
1219                                 if (View == View.Details) {
1220                                         for (int i = start; i <= end; i++)
1221                                                 list.Add (items [i]);
1222                                 } else {
1223                                         int left = Math.Min (items [start].col, items [end].col);
1224                                         int right = Math.Max (items [start].col, items [end].col);
1225                                         int top = Math.Min (items [start].row, items [end].row);
1226                                         int bottom = Math.Max (items [start].row, items [end].row);
1227                                         foreach (ListViewItem curr in items)
1228                                                 if (curr.row >= top && curr.row <= bottom && 
1229                                                     curr.col >= left && curr.col <= right)
1230                                                         list.Add (curr);
1231                                 }
1232                                 if (SelectItems (list))
1233                                         OnSelectedIndexChanged (EventArgs.Empty);
1234                         } else {
1235                                 if (!ctrl_pressed)
1236                                         SelectedItems.Clear ();
1237                                 item.Selected = true;
1238                                 selection_start = item;
1239                                 OnSelectedIndexChanged (EventArgs.Empty);
1240                         }
1241                 }
1242
1243                 internal override bool InternalPreProcessMessage (ref Message msg)
1244                 {
1245                         if (msg.Msg == (int)Msg.WM_KEYDOWN) {
1246                                 Keys key_data = (Keys)msg.WParam.ToInt32();
1247                                 if (HandleNavKeys (key_data))
1248                                         return true;
1249                         } 
1250                         return base.InternalPreProcessMessage (ref msg);
1251                 }
1252
1253                 bool HandleNavKeys (Keys key_data)
1254                 {
1255                         if (Items.Count == 0 || !item_control.Visible)
1256                                 return false;
1257
1258                         if (FocusedItem == null)
1259                                 SetFocusedItem (Items [0]);
1260
1261                         switch (key_data) {
1262                         case Keys.End:
1263                                 SelectIndex (Items.Count - 1);
1264                                 break;
1265
1266                         case Keys.Home:                 
1267                                 SelectIndex (0);
1268                                 break;
1269
1270                         case Keys.Left:
1271                         case Keys.Right:
1272                         case Keys.Up:                           
1273                         case Keys.Down:
1274                                 SelectIndex (GetAdjustedIndex (key_data));
1275                                 break;
1276
1277                         default:
1278                                 return false;
1279                         }
1280
1281                         return true;
1282                 }
1283
1284                 void SelectIndex (int index)
1285                 {
1286                         if (index == -1)
1287                                 return;
1288
1289                         if (MultiSelect)
1290                                 UpdateMultiSelection (index);
1291                         else if (!items [index].Selected) {
1292                                 items [index].Selected = true;
1293                                 OnSelectedIndexChanged (EventArgs.Empty);
1294                         }
1295
1296                         SetFocusedItem (items [index]);                         
1297                         EnsureVisible (index);
1298                 }
1299
1300                 private void ListView_KeyDown (object sender, KeyEventArgs ke)
1301                 {                       
1302                         if (ke.Handled || Items.Count == 0 || !item_control.Visible)
1303                                 return;
1304
1305                         ke.Handled = KeySearchString (ke);
1306                 }
1307
1308                 internal class ItemControl : Control {
1309
1310                         ListView owner;
1311                         ListViewItem clicked_item;
1312                         ListViewItem last_clicked_item;
1313                         bool hover_processed = false;
1314                         bool checking = false;
1315
1316                         public ItemControl (ListView owner)
1317                         {
1318                                 this.owner = owner;
1319                                 DoubleClick += new EventHandler(ItemsDoubleClick);
1320                                 MouseDown += new MouseEventHandler(ItemsMouseDown);
1321                                 MouseMove += new MouseEventHandler(ItemsMouseMove);
1322                                 MouseHover += new EventHandler(ItemsMouseHover);
1323                                 MouseUp += new MouseEventHandler(ItemsMouseUp);
1324                         }
1325
1326                         void ItemsDoubleClick (object sender, EventArgs e)
1327                         {
1328                                 if (owner.activation == ItemActivation.Standard && owner.ItemActivate != null)
1329                                         owner.ItemActivate (this, e);
1330                         }
1331
1332                         enum BoxSelect {
1333                                 None,
1334                                 Normal,
1335                                 Shift,
1336                                 Control
1337                         }
1338
1339                         BoxSelect box_select_mode = BoxSelect.None;
1340                         ArrayList prev_selection;
1341                         Point box_select_start;
1342
1343                         Rectangle box_select_rect;
1344                         internal Rectangle BoxSelectRectangle {
1345                                 get { return box_select_rect; }
1346                                 set {
1347                                         if (box_select_rect == value)
1348                                                 return;
1349
1350                                         InvalidateBoxSelectRect ();
1351                                         box_select_rect = value;
1352                                         InvalidateBoxSelectRect ();
1353                                 }
1354                         }
1355
1356                         void InvalidateBoxSelectRect ()
1357                         {
1358                                 if (BoxSelectRectangle.Size.IsEmpty)
1359                                         return;
1360
1361                                 Rectangle edge = BoxSelectRectangle;
1362                                 edge.X -= 1;
1363                                 edge.Y -= 1;
1364                                 edge.Width += 2;
1365                                 edge.Height = 2;
1366                                 Invalidate (edge);
1367                                 edge.Y = BoxSelectRectangle.Bottom - 1;
1368                                 Invalidate (edge);
1369                                 edge.Y = BoxSelectRectangle.Y - 1;
1370                                 edge.Width = 2;
1371                                 edge.Height = BoxSelectRectangle.Height + 2;
1372                                 Invalidate (edge);
1373                                 edge.X = BoxSelectRectangle.Right - 1;
1374                                 Invalidate (edge);
1375                         }
1376
1377                         private Rectangle CalculateBoxSelectRectangle (Point pt)
1378                         {
1379                                 int left = Math.Min (box_select_start.X, pt.X);
1380                                 int right = Math.Max (box_select_start.X, pt.X);
1381                                 int top = Math.Min (box_select_start.Y, pt.Y);
1382                                 int bottom = Math.Max (box_select_start.Y, pt.Y);
1383                                 return Rectangle.FromLTRB (left, top, right, bottom);
1384                         }
1385
1386                         ArrayList BoxSelectedItems {
1387                                 get {
1388                                         ArrayList result = new ArrayList ();
1389                                         foreach (ListViewItem item in owner.Items) {
1390                                                 Rectangle r = item.Bounds;
1391                                                 r.X += r.Width / 4;
1392                                                 r.Y += r.Height / 4;
1393                                                 r.Width /= 2;
1394                                                 r.Height /= 2;
1395                                                 if (BoxSelectRectangle.IntersectsWith (r))
1396                                                         result.Add (item);
1397                                         }
1398                                         return result;
1399                                 }
1400                         }
1401
1402                         private bool PerformBoxSelection (Point pt)
1403                         {
1404                                 if (box_select_mode == BoxSelect.None)
1405                                         return false;
1406
1407                                 BoxSelectRectangle = CalculateBoxSelectRectangle (pt);
1408                                 
1409                                 ArrayList box_items = BoxSelectedItems;
1410
1411                                 ArrayList items;
1412
1413                                 switch (box_select_mode) {
1414
1415                                 case BoxSelect.Normal:
1416                                         items = box_items;
1417                                         break;
1418
1419                                 case BoxSelect.Control:
1420                                         items = new ArrayList ();
1421                                         foreach (ListViewItem item in prev_selection)
1422                                                 if (!box_items.Contains (item))
1423                                                         items.Add (item);
1424                                         foreach (ListViewItem item in box_items)
1425                                                 if (!prev_selection.Contains (item))
1426                                                         items.Add (item);
1427                                         break;
1428
1429                                 case BoxSelect.Shift:
1430                                         items = box_items;
1431                                         foreach (ListViewItem item in box_items)
1432                                                 prev_selection.Remove (item);
1433                                         foreach (ListViewItem item in prev_selection)
1434                                                 items.Add (item);
1435                                         break;
1436
1437                                 default:
1438                                         throw new Exception ("Unexpected Selection mode: " + box_select_mode);
1439                                 }
1440
1441                                 SuspendLayout ();
1442                                 owner.SelectItems (items);
1443                                 ResumeLayout ();
1444
1445                                 return true;
1446                         }
1447
1448                         private void ToggleCheckState (ListViewItem item)
1449                         {
1450                                 CheckState curr_state = item.Checked ?  CheckState.Checked : CheckState.Unchecked;
1451                                 item.Checked = !item.Checked;
1452                                 CheckState new_state = item.Checked ?  CheckState.Checked : CheckState.Unchecked;
1453
1454                                 ItemCheckEventArgs ice = new ItemCheckEventArgs (item.Index, curr_state, new_state);
1455                                 owner.OnItemCheck (ice);
1456                         }
1457
1458                         private void ItemsMouseDown (object sender, MouseEventArgs me)
1459                         {
1460                                 if (owner.items.Count == 0)
1461                                         return;
1462
1463                                 Point pt = new Point (me.X, me.Y);
1464                                 foreach (ListViewItem item in owner.items) {
1465                                         if (me.Clicks == 1 && item.CheckRectReal.Contains (pt)) {
1466                                                 checking = true;
1467                                                 if (me.Clicks > 1)
1468                                                         return;
1469                                                 ToggleCheckState (item);
1470                                                 return;
1471                                         }
1472
1473                                         if (owner.View == View.Details && !owner.FullRowSelect) {
1474                                                 if (item.GetBounds (ItemBoundsPortion.Label).Contains (pt)) {
1475                                                         clicked_item = item;
1476                                                         break;
1477                                                 }
1478                                         } else {
1479                                                 if (item.Bounds.Contains (pt)) {
1480                                                         clicked_item = item;
1481                                                         break;
1482                                                 }
1483                                         }
1484                                 }
1485
1486
1487                                 if (clicked_item != null) {
1488                                         owner.SetFocusedItem (clicked_item);
1489                                         bool changed = !clicked_item.Selected;
1490                                         if (owner.MultiSelect)
1491                                                 owner.UpdateMultiSelection (clicked_item.Index);
1492                                         else
1493                                                 clicked_item.Selected = true;
1494                                 
1495                                         if (changed)
1496                                                 owner.OnSelectedIndexChanged (EventArgs.Empty);
1497
1498                                         // Raise double click if the item was clicked. On MS the
1499                                         // double click is only raised if you double click an item
1500                                         if (me.Clicks > 1) {
1501                                                 owner.OnDoubleClick (EventArgs.Empty);
1502                                                 if (owner.CheckBoxes)
1503                                                         ToggleCheckState (clicked_item);
1504                                         } else if (me.Clicks == 1)
1505                                                 owner.OnClick (EventArgs.Empty);
1506                                 } else {
1507                                         if (owner.MultiSelect) {
1508                                                 Keys mods = XplatUI.State.ModifierKeys;
1509                                                 if ((mods & Keys.Shift) != 0)
1510                                                         box_select_mode = BoxSelect.Shift;
1511                                                 else if ((mods & Keys.Control) != 0)
1512                                                         box_select_mode = BoxSelect.Control;
1513                                                 else
1514                                                         box_select_mode = BoxSelect.Normal;
1515                                                 box_select_start = pt; 
1516                                                 prev_selection = (ArrayList) owner.SelectedItems.list.Clone ();
1517                                         } else if (owner.selected_indices.Count > 0) {
1518                                                 owner.SelectedItems.Clear ();
1519                                                 owner.OnSelectedIndexChanged (EventArgs.Empty);
1520                                         }
1521                                 }
1522                         }
1523
1524                         private void ItemsMouseMove (object sender, MouseEventArgs me)
1525                         {
1526                                 if (PerformBoxSelection (new Point (me.X, me.Y)))
1527                                         return;
1528
1529                                 if (owner.HoverSelection && hover_processed) {
1530
1531                                         Point pt = PointToClient (Control.MousePosition);
1532                                         ListViewItem item = owner.GetItemAt (pt.X, pt.Y);
1533                                         if (item == null || item.Selected)
1534                                                 return;
1535
1536                                         hover_processed = false;
1537                                         XplatUI.ResetMouseHover (Handle);
1538                                 }
1539                         }
1540
1541
1542                         private void ItemsMouseHover (object sender, EventArgs e)
1543                         {
1544                                 if (Capture || !owner.HoverSelection)
1545                                         return;
1546
1547                                 hover_processed = true;
1548                                 Point pt = PointToClient (Control.MousePosition);
1549                                 ListViewItem item = owner.GetItemAt (pt.X, pt.Y);
1550
1551                                 if (item == null)
1552                                         return;
1553
1554                                 item.Selected = true;
1555                                 owner.OnSelectedIndexChanged (new EventArgs ());
1556                         }
1557
1558                         private void ItemsMouseUp (object sender, MouseEventArgs me)
1559                         {
1560                                 Capture = false;
1561                                 if (owner.Items.Count == 0)
1562                                         return;
1563
1564                                 Point pt = new Point (me.X, me.Y);
1565
1566                                 Rectangle rect = Rectangle.Empty;
1567                                 if (clicked_item != null) {
1568                                         if (owner.view == View.Details && !owner.full_row_select)
1569                                                 rect = clicked_item.GetBounds (ItemBoundsPortion.Label);
1570                                         else
1571                                                 rect = clicked_item.Bounds;
1572
1573                                         if (rect.Contains (pt)) {
1574                                                 switch (owner.activation) {
1575                                                 case ItemActivation.OneClick:
1576                                                         owner.OnItemActivate (EventArgs.Empty);
1577                                                         break;
1578
1579                                                 case ItemActivation.TwoClick:
1580                                                         if (last_clicked_item == clicked_item) {
1581                                                                 owner.OnItemActivate (EventArgs.Empty);
1582                                                                 last_clicked_item = null;
1583                                                         } else
1584                                                                 last_clicked_item = clicked_item;
1585                                                         break;
1586                                                 default:
1587                                                         // DoubleClick activation is handled in another handler
1588                                                         break;
1589                                                 }
1590                                         }
1591                                 } else if (!checking && owner.SelectedItems.Count > 0 && BoxSelectRectangle.Size.IsEmpty) {
1592                                         // Need this to clean up background clicks
1593                                         owner.SelectedItems.Clear ();
1594                                         owner.OnSelectedIndexChanged (EventArgs.Empty);
1595                                 }
1596
1597                                 clicked_item = null;
1598                                 box_select_start = Point.Empty;
1599                                 BoxSelectRectangle = Rectangle.Empty;
1600                                 prev_selection = null;
1601                                 box_select_mode = BoxSelect.None;
1602                                 checking = false;
1603                         }
1604
1605                         internal override void OnPaintInternal (PaintEventArgs pe)
1606                         {
1607                                 ThemeEngine.Current.DrawListViewItems (pe.Graphics, pe.ClipRectangle, owner);
1608                         }
1609
1610                         internal override void OnGotFocusInternal (EventArgs e)
1611                         {
1612                                 owner.Focus ();
1613                         }
1614                 }
1615
1616                 internal override void OnPaintInternal (PaintEventArgs pe)
1617                 {
1618                         if (updating)
1619                                 return; 
1620                                 
1621                         CalculateScrollBars ();
1622                 }
1623
1624                 void FocusChanged (object o, EventArgs args)
1625                 {
1626                         if (Items.Count == 0)
1627                                 return;
1628
1629                         if (FocusedItem == null)
1630                                 SetFocusedItem (Items [0]);
1631
1632                         item_control.Invalidate (FocusedItem.Bounds);
1633                 }
1634
1635                 private void ListView_MouseWheel (object sender, MouseEventArgs me)
1636                 {
1637                         if (Items.Count == 0)
1638                                 return;
1639
1640                         int lines = me.Delta / 120;
1641
1642                         if (lines == 0)
1643                                 return;
1644
1645                         switch (View) {
1646                         case View.Details:
1647                         case View.SmallIcon:
1648                                 Scroll (v_scroll, -Items [0].Bounds.Height * SystemInformation.MouseWheelScrollLines * lines);
1649                                 break;
1650                         case View.LargeIcon:
1651                                 Scroll (v_scroll, -(Items [0].Bounds.Height + ThemeEngine.Current.ListViewVerticalSpacing)  * lines);
1652                                 break;
1653                         case View.List:
1654                                 Scroll (h_scroll, -Items [0].Bounds.Width * lines);
1655                                 break;
1656                         }
1657                 }
1658
1659                 private void ListView_SizeChanged (object sender, EventArgs e)
1660                 {
1661                         CalculateListView (alignment);
1662                 }
1663                 
1664                 private void SetFocusedItem (ListViewItem item)
1665                 {
1666                         if (focused_item != null)
1667                                 focused_item.Focused = false;
1668                         
1669                         if (item != null)
1670                                 item.Focused = true;
1671                                 
1672                         focused_item = item;
1673                 }
1674
1675                 private void HorizontalScroller (object sender, EventArgs e)
1676                 {
1677                         // Avoid unnecessary flickering, when button is
1678                         // kept pressed at the end
1679                         if (h_marker != h_scroll.Value) {
1680                                 
1681                                 int pixels =  h_marker - h_scroll.Value;
1682                                 
1683                                 h_marker = h_scroll.Value;
1684                                 if (header_control.Visible)
1685                                         XplatUI.ScrollWindow (header_control.Handle, pixels, 0, false);
1686
1687                                 XplatUI.ScrollWindow (item_control.Handle, pixels, 0, false);
1688                         }
1689                 }
1690
1691                 private void VerticalScroller (object sender, EventArgs e)
1692                 {
1693                         // Avoid unnecessary flickering, when button is
1694                         // kept pressed at the end
1695                         if (v_marker != v_scroll.Value) {
1696                                 int pixels =  v_marker - v_scroll.Value;
1697                                 Rectangle area = item_control.ClientRectangle;
1698                                 v_marker = v_scroll.Value;
1699                                 XplatUI.ScrollWindow (item_control.Handle, area, 0, pixels, false);
1700                         }
1701                 }
1702                 #endregion      // Internal Methods Properties
1703
1704                 #region Protected Methods
1705                 protected override void CreateHandle ()
1706                 {
1707                         base.CreateHandle ();
1708                 }
1709
1710                 protected override void Dispose (bool disposing)
1711                 {                       
1712                         if (disposing) {                        
1713                                 h_scroll.Dispose ();
1714                                 v_scroll.Dispose ();
1715                                 
1716                                 large_image_list = null;
1717                                 small_image_list = null;
1718                                 state_image_list = null;
1719                         }
1720                         
1721                         base.Dispose (disposing);
1722                 }
1723
1724                 protected override bool IsInputKey (Keys keyData)
1725                 {
1726                         switch (keyData) {
1727                         case Keys.Up:
1728                         case Keys.Down:
1729                         case Keys.PageUp:
1730                         case Keys.PageDown:
1731                         case Keys.Right:
1732                         case Keys.Left:
1733                         case Keys.End:
1734                         case Keys.Home:                         
1735                                 return true;
1736
1737                         default:
1738                                 break;
1739                         }
1740                         
1741                         return base.IsInputKey (keyData);
1742                 }
1743
1744                 protected virtual void OnAfterLabelEdit (LabelEditEventArgs e)
1745                 {
1746                         if (AfterLabelEdit != null)
1747                                 AfterLabelEdit (this, e);
1748                 }
1749
1750                 protected virtual void OnBeforeLabelEdit (LabelEditEventArgs e)
1751                 {
1752                         if (BeforeLabelEdit != null)
1753                                 BeforeLabelEdit (this, e);
1754                 }
1755
1756                 protected virtual void OnColumnClick (ColumnClickEventArgs e)
1757                 {
1758                         if (ColumnClick != null)
1759                                 ColumnClick (this, e);
1760                 }
1761
1762                 protected override void OnEnabledChanged (EventArgs e)
1763                 {
1764                         base.OnEnabledChanged (e);
1765                 }
1766
1767                 protected override void OnFontChanged (EventArgs e)
1768                 {
1769                         base.OnFontChanged (e);
1770                         Redraw (true);
1771                 }
1772
1773                 protected override void OnHandleCreated (EventArgs e)
1774                 {
1775                         base.OnHandleCreated (e);
1776                         Sort ();
1777                 }
1778
1779                 protected override void OnHandleDestroyed (EventArgs e)
1780                 {
1781                         base.OnHandleDestroyed (e);
1782                 }
1783
1784                 protected virtual void OnItemActivate (EventArgs e)
1785                 {
1786                         if (ItemActivate != null)
1787                                 ItemActivate (this, e);
1788                 }
1789
1790                 protected virtual void OnItemCheck (ItemCheckEventArgs ice)
1791                 {
1792                         if (ItemCheck != null)
1793                                 ItemCheck (this, ice);
1794                 }
1795
1796                 protected virtual void OnItemDrag (ItemDragEventArgs e)
1797                 {
1798                         if (ItemDrag != null)
1799                                 ItemDrag (this, e);
1800                 }
1801
1802                 protected virtual void OnSelectedIndexChanged (EventArgs e)
1803                 {
1804                         if (SelectedIndexChanged != null)
1805                                 SelectedIndexChanged (this, e);
1806                 }
1807
1808                 protected override void OnSystemColorsChanged (EventArgs e)
1809                 {
1810                         base.OnSystemColorsChanged (e);
1811                 }
1812
1813                 protected void RealizeProperties ()
1814                 {
1815                         // FIXME: TODO
1816                 }
1817
1818                 protected void UpdateExtendedStyles ()
1819                 {
1820                         // FIXME: TODO
1821                 }
1822
1823                 protected override void WndProc (ref Message m)
1824                 {
1825                         base.WndProc (ref m);
1826                 }
1827                 #endregion // Protected Methods
1828
1829                 #region Public Instance Methods
1830                 public void ArrangeIcons ()
1831                 {
1832                         ArrangeIcons (this.alignment);
1833                 }
1834
1835                 public void ArrangeIcons (ListViewAlignment alignment)
1836                 {
1837                         // Icons are arranged only if view is set to LargeIcon or SmallIcon
1838                         if (view == View.LargeIcon || view == View.SmallIcon) {
1839                                 this.CalculateListView (alignment);
1840                                 // we have done the calculations already
1841                                 this.Redraw (false);
1842                         }
1843                 }
1844
1845                 public void BeginUpdate ()
1846                 {
1847                         // flag to avoid painting
1848                         updating = true;
1849                 }
1850
1851                 public void Clear ()
1852                 {
1853                         columns.Clear ();
1854                         items.Clear (); // Redraw (true) called here                    
1855                 }
1856
1857                 public void EndUpdate ()
1858                 {
1859                         // flag to avoid painting
1860                         updating = false;
1861
1862                         // probably, now we need a redraw with recalculations
1863                         this.Redraw (true);
1864                 }
1865
1866                 public void EnsureVisible (int index)
1867                 {
1868                         if (index < 0 || index >= items.Count || scrollable == false)
1869                                 return;
1870
1871                         Rectangle view_rect = item_control.ClientRectangle;
1872                         Rectangle bounds = items [index].Bounds;
1873
1874                         if (view_rect.Contains (bounds))
1875                                 return;
1876
1877                         if (bounds.Left < 0)
1878                                 h_scroll.Value += bounds.Left;
1879                         else if (bounds.Right > view_rect.Right)
1880                                 h_scroll.Value += (bounds.Right - view_rect.Right);
1881
1882                         if (bounds.Top < 0)
1883                                 v_scroll.Value += bounds.Top;
1884                         else if (bounds.Bottom > view_rect.Bottom)
1885                                 v_scroll.Value += (bounds.Bottom - view_rect.Bottom);
1886                 }
1887                 
1888                 public ListViewItem GetItemAt (int x, int y)
1889                 {
1890                         foreach (ListViewItem item in items) {
1891                                 if (item.Bounds.Contains (x, y))
1892                                         return item;
1893                         }
1894                         return null;
1895                 }
1896
1897                 public Rectangle GetItemRect (int index)
1898                 {
1899                         return GetItemRect (index, ItemBoundsPortion.Entire);
1900                 }
1901
1902                 public Rectangle GetItemRect (int index, ItemBoundsPortion portion)
1903                 {
1904                         if (index < 0 || index >= items.Count)
1905                                 throw new IndexOutOfRangeException ("index");
1906
1907                         return items [index].GetBounds (portion);
1908                 }
1909
1910                 public void Sort ()
1911                 {
1912                         Sort (true);
1913                 }
1914
1915                 // we need this overload to reuse the logic for sorting, while allowing
1916                 // redrawing to be done by caller or have it done by this method when
1917                 // sorting is really performed
1918                 //
1919                 // ListViewItemCollection's Add and AddRange methods call this overload
1920                 // with redraw set to false, as they take care of redrawing themselves
1921                 // (they even want to redraw the listview if no sort is performed, as 
1922                 // an item was added), while ListView.Sort () only wants to redraw if 
1923                 // sorting was actually performed
1924                 private void Sort (bool redraw)
1925                 {
1926                         if (!IsHandleCreated || item_sorter == null) {
1927                                 return;
1928                         }
1929                         
1930                         items.list.Sort (item_sorter);
1931                         if (redraw)
1932                                 this.Redraw (true);
1933                 }
1934
1935                 public override string ToString ()
1936                 {
1937                         int count = this.Items.Count;
1938
1939                         if (count == 0)
1940                                 return string.Format ("System.Windows.Forms.ListView, Items.Count: 0");
1941                         else
1942                                 return string.Format ("System.Windows.Forms.ListView, Items.Count: {0}, Items[0]: {1}", count, this.Items [0].ToString ());
1943                 }
1944                 #endregion      // Public Instance Methods
1945
1946
1947                 #region Subclasses
1948
1949                 class HeaderControl : Control {
1950
1951                         ListView owner;
1952                         bool column_resize_active = false;
1953                         ColumnHeader resize_column;
1954                         ColumnHeader clicked_column;
1955                         ColumnHeader drag_column;
1956                         int drag_x;
1957                         int drag_to_index = -1;
1958
1959                         public HeaderControl (ListView owner)
1960                         {
1961                                 this.owner = owner;
1962                                 MouseDown += new MouseEventHandler (HeaderMouseDown);
1963                                 MouseMove += new MouseEventHandler (HeaderMouseMove);
1964                                 MouseUp += new MouseEventHandler (HeaderMouseUp);
1965                         }
1966
1967                         private ColumnHeader ColumnAtX (int x)
1968                         {
1969                                 Point pt = new Point (x, 0);
1970                                 ColumnHeader result = null;
1971                                 foreach (ColumnHeader col in owner.Columns) {
1972                                         if (col.Rect.Contains (pt)) {
1973                                                 result = col;
1974                                                 break;
1975                                         }
1976                                 }
1977                                 return result;
1978                         }
1979
1980                         private int GetReorderedIndex (ColumnHeader col)
1981                         {
1982                                 if (owner.reordered_column_indices == null)
1983                                         return col.Index;
1984                                 else
1985                                         for (int i = 0; i < owner.Columns.Count; i++)
1986                                                 if (owner.reordered_column_indices [i] == col.Index)
1987                                                         return i;
1988                                 throw new Exception ("Column index missing from reordered array");
1989                         }
1990
1991                         private void HeaderMouseDown (object sender, MouseEventArgs me)
1992                         {
1993                                 if (resize_column != null) {
1994                                         column_resize_active = true;
1995                                         Capture = true;
1996                                         return;
1997                                 }
1998
1999                                 clicked_column = ColumnAtX (me.X + owner.h_marker);
2000
2001                                 if (clicked_column != null) {
2002                                         Capture = true;
2003                                         if (owner.AllowColumnReorder) {
2004                                                 drag_x = me.X;
2005                                                 drag_column = (ColumnHeader) (clicked_column as ICloneable).Clone ();
2006                                                 drag_column.column_rect = clicked_column.Rect;
2007                                                 drag_to_index = GetReorderedIndex (clicked_column);
2008                                         }
2009                                         clicked_column.pressed = true;
2010                                         Rectangle bounds = clicked_column.Rect;
2011                                         bounds.X -= owner.h_marker;
2012                                         Invalidate (bounds);
2013                                         return;
2014                                 }
2015                         }
2016
2017                         private void HeaderMouseMove (object sender, MouseEventArgs me)
2018                         {
2019                                 Point pt = new Point (me.X + owner.h_marker, me.Y);
2020
2021                                 if (column_resize_active)  {
2022                                         resize_column.Width = pt.X - resize_column.X;
2023                                         if (resize_column.Width < 0)
2024                                                 resize_column.Width = 0;
2025                                         return;
2026                                 }
2027
2028                                 resize_column = null;
2029
2030                                 if (clicked_column != null) {
2031                                         if (owner.AllowColumnReorder) {
2032                                                 Rectangle r;
2033
2034                                                 r = drag_column.column_rect;
2035                                                 r.X = clicked_column.Rect.X + me.X - drag_x;
2036                                                 drag_column.column_rect = r;
2037
2038                                                 int x = me.X + owner.h_marker;
2039                                                 ColumnHeader over = ColumnAtX (x);
2040                                                 if (over == null)
2041                                                         drag_to_index = owner.Columns.Count;
2042                                                 else if (x < over.X + over.Width / 2)
2043                                                         drag_to_index = GetReorderedIndex (over);
2044                                                 else
2045                                                         drag_to_index = GetReorderedIndex (over) + 1;
2046                                                 Invalidate ();
2047                                         } else {
2048                                                 ColumnHeader over = ColumnAtX (me.X + owner.h_marker);
2049                                                 bool pressed = clicked_column.pressed;
2050                                                 clicked_column.pressed = over == clicked_column;
2051                                                 if (clicked_column.pressed ^ pressed) {
2052                                                         Rectangle bounds = clicked_column.Rect;
2053                                                         bounds.X -= owner.h_marker;
2054                                                         Invalidate (bounds);
2055                                                 }
2056                                         }
2057                                         return;
2058                                 }
2059
2060                                 for (int i = 0; i < owner.Columns.Count; i++) {
2061                                         Rectangle zone = owner.Columns [i].Rect;
2062                                         zone.X = zone.Right - 5;
2063                                         zone.Width = 10;
2064                                         if (zone.Contains (pt)) {
2065                                                 if (i < owner.Columns.Count - 1 && owner.Columns [i + 1].Width == 0)
2066                                                         i++;
2067                                                 resize_column = owner.Columns [i];
2068                                                 break;
2069                                         }
2070                                 }
2071
2072                                 if (resize_column == null)
2073                                         Cursor = Cursors.Default;
2074                                 else
2075                                         Cursor = Cursors.VSplit;
2076                         }
2077
2078                         void HeaderMouseUp (object sender, MouseEventArgs me)
2079                         {
2080                                 Capture = false;
2081
2082                                 if (column_resize_active) {
2083                                         column_resize_active = false;
2084                                         resize_column = null;
2085                                         Cursor = Cursors.Default;
2086                                         return;
2087                                 }
2088
2089                                 if (clicked_column != null && clicked_column.pressed) {
2090                                         clicked_column.pressed = false;
2091                                         Rectangle bounds = clicked_column.Rect;
2092                                         bounds.X -= owner.h_marker;
2093                                         Invalidate (bounds);
2094                                         owner.OnColumnClick (new ColumnClickEventArgs (clicked_column.Index));
2095                                 }
2096
2097                                 if (drag_column != null && owner.AllowColumnReorder) {
2098                                         drag_column = null;
2099                                         if (drag_to_index > GetReorderedIndex (clicked_column))
2100                                                 drag_to_index--;
2101                                         if (owner.GetReorderedColumn (drag_to_index) != clicked_column)
2102                                                 owner.ReorderColumn (clicked_column, drag_to_index);
2103                                         drag_to_index = -1;
2104                                         Invalidate ();
2105                                 }
2106
2107                                 clicked_column = null;
2108                         }
2109
2110                         internal override void OnPaintInternal (PaintEventArgs pe)
2111                         {
2112                                 if (owner.updating)
2113                                         return; 
2114                                 
2115                                 Theme theme = ThemeEngine.Current;
2116                                 theme.DrawListViewHeader (pe.Graphics, pe.ClipRectangle, this.owner);
2117
2118                                 if (drag_column == null)
2119                                         return;
2120
2121                                 int target_x;
2122                                 if (drag_to_index == owner.Columns.Count)
2123                                         target_x = owner.GetReorderedColumn (drag_to_index - 1).Rect.Right - owner.h_marker;
2124                                 else
2125                                         target_x = owner.GetReorderedColumn (drag_to_index).Rect.X - owner.h_marker;
2126                                 theme.DrawListViewHeaderDragDetails (pe.Graphics, owner, drag_column, target_x);
2127                         }
2128
2129                         protected override void WndProc (ref Message m)
2130                         {
2131                                 switch ((Msg)m.Msg) {
2132                                 case Msg.WM_SETFOCUS:
2133                                         owner.Focus ();
2134                                         break;
2135                                 default:
2136                                         base.WndProc (ref m);
2137                                         break;
2138                                 }
2139                         }
2140                 }
2141
2142                 private class ItemComparer : IComparer {
2143                         readonly SortOrder sort_order;
2144
2145                         public ItemComparer (SortOrder sortOrder)
2146                         {
2147                                 sort_order = sortOrder;
2148                         }
2149
2150                         public int Compare (object x, object y)
2151                         {
2152                                 ListViewItem item_x = x as ListViewItem;
2153                                 ListViewItem item_y = y as ListViewItem;
2154                                 if (sort_order == SortOrder.Ascending)
2155                                         return String.Compare (item_x.Text, item_y.Text);
2156                                 else
2157                                         return String.Compare (item_y.Text, item_x.Text);
2158                         }
2159                 }
2160
2161                 public class CheckedIndexCollection : IList, ICollection, IEnumerable
2162                 {
2163                         private readonly ListView owner;
2164
2165                         #region Public Constructor
2166                         public CheckedIndexCollection (ListView owner)
2167                         {
2168                                 this.owner = owner;
2169                         }
2170                         #endregion      // Public Constructor
2171
2172                         #region Public Properties
2173                         [Browsable (false)]
2174                         public int Count {
2175                                 get { return owner.CheckedItems.Count; }
2176                         }
2177
2178                         public bool IsReadOnly {
2179                                 get { return true; }
2180                         }
2181
2182                         public int this [int index] {
2183                                 get {
2184                                         int [] indices = GetIndices ();
2185                                         if (index < 0 || index >= indices.Length)
2186                                                 throw new ArgumentOutOfRangeException ("index");
2187                                         return indices [index];
2188                                 }
2189                         }
2190
2191                         bool ICollection.IsSynchronized {
2192                                 get { return false; }
2193                         }
2194
2195                         object ICollection.SyncRoot {
2196                                 get { return this; }
2197                         }
2198
2199                         bool IList.IsFixedSize {
2200                                 get { return true; }
2201                         }
2202
2203                         object IList.this [int index] {
2204                                 get { return this [index]; }
2205                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
2206                         }
2207                         #endregion      // Public Properties
2208
2209                         #region Public Methods
2210                         public bool Contains (int checkedIndex)
2211                         {
2212                                 int [] indices = GetIndices ();
2213                                 for (int i = 0; i < indices.Length; i++) {
2214                                         if (indices [i] == checkedIndex)
2215                                                 return true;
2216                                 }
2217                                 return false;
2218                         }
2219
2220                         public IEnumerator GetEnumerator ()
2221                         {
2222                                 int [] indices = GetIndices ();
2223                                 return indices.GetEnumerator ();
2224                         }
2225
2226                         void ICollection.CopyTo (Array dest, int index)
2227                         {
2228                                 int [] indices = GetIndices ();
2229                                 Array.Copy (indices, 0, dest, index, indices.Length);
2230                         }
2231
2232                         int IList.Add (object value)
2233                         {
2234                                 throw new NotSupportedException ("Add operation is not supported.");
2235                         }
2236
2237                         void IList.Clear ()
2238                         {
2239                                 throw new NotSupportedException ("Clear operation is not supported.");
2240                         }
2241
2242                         bool IList.Contains (object checkedIndex)
2243                         {
2244                                 if (!(checkedIndex is int))
2245                                         return false;
2246                                 return Contains ((int) checkedIndex);
2247                         }
2248
2249                         int IList.IndexOf (object checkedIndex)
2250                         {
2251                                 if (!(checkedIndex is int))
2252                                         return -1;
2253                                 return IndexOf ((int) checkedIndex);
2254                         }
2255
2256                         void IList.Insert (int index, object value)
2257                         {
2258                                 throw new NotSupportedException ("Insert operation is not supported.");
2259                         }
2260
2261                         void IList.Remove (object value)
2262                         {
2263                                 throw new NotSupportedException ("Remove operation is not supported.");
2264                         }
2265
2266                         void IList.RemoveAt (int index)
2267                         {
2268                                 throw new NotSupportedException ("RemoveAt operation is not supported.");
2269                         }
2270
2271                         public int IndexOf (int checkedIndex)
2272                         {
2273                                 int [] indices = GetIndices ();
2274                                 for (int i = 0; i < indices.Length; i++) {
2275                                         if (indices [i] == checkedIndex)
2276                                                 return i;
2277                                 }
2278                                 return -1;
2279                         }
2280                         #endregion      // Public Methods
2281
2282                         private int [] GetIndices ()
2283                         {
2284                                 int [] indices = new int [Count];
2285                                 for (int i = 0; i < owner.CheckedItems.Count; i++) {
2286                                         ListViewItem item = owner.CheckedItems [i];
2287                                         indices [i] = item.Index;
2288                                 }
2289                                 return indices;
2290                         }
2291                 }       // CheckedIndexCollection
2292
2293                 public class CheckedListViewItemCollection : IList, ICollection, IEnumerable
2294                 {
2295                         internal readonly ArrayList list;
2296                         private readonly ListView owner;
2297
2298                         #region Public Constructor
2299                         public CheckedListViewItemCollection (ListView owner)
2300                         {
2301                                 list = new ArrayList ();
2302                                 this.owner = owner;
2303                         }
2304                         #endregion      // Public Constructor
2305
2306                         #region Public Properties
2307                         [Browsable (false)]
2308                         public int Count {
2309                                 get {
2310                                         if (!owner.CheckBoxes)
2311                                                 return 0;
2312                                         return list.Count;
2313                                 }
2314                         }
2315
2316                         public bool IsReadOnly {
2317                                 get { return true; }
2318                         }
2319
2320                         public ListViewItem this [int index] {
2321                                 get {
2322                                         if (index < 0 || index >= Count)
2323                                                 throw new ArgumentOutOfRangeException ("index");
2324                                         return (ListViewItem) list [index];
2325                                 }
2326                         }
2327
2328                         bool ICollection.IsSynchronized {
2329                                 get { return list.IsSynchronized; }
2330                         }
2331
2332                         object ICollection.SyncRoot {
2333                                 get { return this; }
2334                         }
2335
2336                         bool IList.IsFixedSize {
2337                                 get { return true; }
2338                         }
2339
2340                         object IList.this [int index] {
2341                                 get { return this [index]; }
2342                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
2343                         }
2344                         #endregion      // Public Properties
2345
2346                         #region Public Methods
2347                         public bool Contains (ListViewItem item)
2348                         {
2349                                 if (!owner.CheckBoxes)
2350                                         return false;
2351                                 return list.Contains (item);
2352                         }
2353
2354                         public void CopyTo (Array dest, int index)
2355                         {
2356                                 if (!owner.CheckBoxes)
2357                                         return;
2358                                 list.CopyTo (dest, index);
2359                         }
2360
2361                         public IEnumerator GetEnumerator ()
2362                         {
2363                                 if (!owner.CheckBoxes)
2364                                         return (new ListViewItem [0]).GetEnumerator ();
2365                                 return list.GetEnumerator ();
2366                         }
2367
2368                         int IList.Add (object value)
2369                         {
2370                                 throw new NotSupportedException ("Add operation is not supported.");
2371                         }
2372
2373                         void IList.Clear ()
2374                         {
2375                                 throw new NotSupportedException ("Clear operation is not supported.");
2376                         }
2377
2378                         bool IList.Contains (object item)
2379                         {
2380                                 if (!(item is ListViewItem))
2381                                         return false;
2382                                 return Contains ((ListViewItem) item);
2383                         }
2384
2385                         int IList.IndexOf (object item)
2386                         {
2387                                 if (!(item is ListViewItem))
2388                                         return -1;
2389                                 return IndexOf ((ListViewItem) item);
2390                         }
2391
2392                         void IList.Insert (int index, object value)
2393                         {
2394                                 throw new NotSupportedException ("Insert operation is not supported.");
2395                         }
2396
2397                         void IList.Remove (object value)
2398                         {
2399                                 throw new NotSupportedException ("Remove operation is not supported.");
2400                         }
2401
2402                         void IList.RemoveAt (int index)
2403                         {
2404                                 throw new NotSupportedException ("RemoveAt operation is not supported.");
2405                         }
2406
2407                         public int IndexOf (ListViewItem item)
2408                         {
2409                                 if (!owner.CheckBoxes)
2410                                         return -1;
2411                                 return list.IndexOf (item);
2412                         }
2413                         #endregion      // Public Methods
2414                 }       // CheckedListViewItemCollection
2415
2416                 public class ColumnHeaderCollection : IList, ICollection, IEnumerable
2417                 {
2418                         internal ArrayList list;
2419                         private ListView owner;
2420
2421                         #region Public Constructor
2422                         public ColumnHeaderCollection (ListView owner)
2423                         {
2424                                 list = new ArrayList ();
2425                                 this.owner = owner;
2426                         }
2427                         #endregion      // Public Constructor
2428
2429                         #region Public Properties
2430                         [Browsable (false)]
2431                         public int Count {
2432                                 get { return list.Count; }
2433                         }
2434
2435                         public bool IsReadOnly {
2436                                 get { return false; }
2437                         }
2438
2439                         public virtual ColumnHeader this [int index] {
2440                                 get {
2441                                         if (index < 0 || index >= list.Count)
2442                                                 throw new ArgumentOutOfRangeException ("index");
2443                                         return (ColumnHeader) list [index];
2444                                 }
2445                         }
2446
2447                         bool ICollection.IsSynchronized {
2448                                 get { return true; }
2449                         }
2450
2451                         object ICollection.SyncRoot {
2452                                 get { return this; }
2453                         }
2454
2455                         bool IList.IsFixedSize {
2456                                 get { return list.IsFixedSize; }
2457                         }
2458
2459                         object IList.this [int index] {
2460                                 get { return this [index]; }
2461                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
2462                         }
2463                         #endregion      // Public Properties
2464
2465                         #region Public Methods
2466                         public virtual int Add (ColumnHeader value)
2467                         {
2468                                 int idx;
2469                                 value.owner = this.owner;
2470                                 idx = list.Add (value);
2471                                 if (owner.IsHandleCreated) {
2472                                         owner.Redraw (true); 
2473                                 }
2474                                 return idx;
2475                         }
2476
2477                         public virtual ColumnHeader Add (string str, int width, HorizontalAlignment textAlign)
2478                         {
2479                                 ColumnHeader colHeader = new ColumnHeader (this.owner, str, textAlign, width);
2480                                 this.Add (colHeader);                                                                   
2481                                 return colHeader;
2482                         }
2483
2484                         public virtual void AddRange (ColumnHeader [] values)
2485                         {
2486                                 foreach (ColumnHeader colHeader in values) {
2487                                         colHeader.owner = this.owner;
2488                                         Add (colHeader);
2489                                 }
2490                                 
2491                                 owner.Redraw (true); 
2492                         }
2493
2494                         public virtual void Clear ()
2495                         {
2496                                 list.Clear ();
2497                                 owner.Redraw (true);
2498                         }
2499
2500                         public bool Contains (ColumnHeader value)
2501                         {
2502                                 return list.Contains (value);
2503                         }
2504
2505                         public IEnumerator GetEnumerator ()
2506                         {
2507                                 return list.GetEnumerator ();
2508                         }
2509
2510                         void ICollection.CopyTo (Array dest, int index)
2511                         {
2512                                 list.CopyTo (dest, index);
2513                         }
2514
2515                         int IList.Add (object value)
2516                         {
2517                                 if (! (value is ColumnHeader)) {
2518                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
2519                                 }
2520
2521                                 return this.Add ((ColumnHeader) value);
2522                         }
2523
2524                         bool IList.Contains (object value)
2525                         {
2526                                 if (! (value is ColumnHeader)) {
2527                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
2528                                 }
2529
2530                                 return this.Contains ((ColumnHeader) value);
2531                         }
2532
2533                         int IList.IndexOf (object value)
2534                         {
2535                                 if (! (value is ColumnHeader)) {
2536                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
2537                                 }
2538
2539                                 return this.IndexOf ((ColumnHeader) value);
2540                         }
2541
2542                         void IList.Insert (int index, object value)
2543                         {
2544                                 if (! (value is ColumnHeader)) {
2545                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
2546                                 }
2547
2548                                 this.Insert (index, (ColumnHeader) value);
2549                         }
2550
2551                         void IList.Remove (object value)
2552                         {
2553                                 if (! (value is ColumnHeader)) {
2554                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
2555                                 }
2556
2557                                 this.Remove ((ColumnHeader) value);
2558                         }
2559
2560                         public int IndexOf (ColumnHeader value)
2561                         {
2562                                 return list.IndexOf (value);
2563                         }
2564
2565                         public void Insert (int index, ColumnHeader value)
2566                         {
2567                                 // LAMESPEC: MSDOCS say greater than or equal to the value of the Count property
2568                                 // but it's really only greater.
2569                                 if (index < 0 || index > list.Count)
2570                                         throw new ArgumentOutOfRangeException ("index");
2571
2572                                 value.owner = this.owner;
2573                                 list.Insert (index, value);
2574                                 owner.Redraw (true);
2575                         }
2576
2577                         public void Insert (int index, string str, int width, HorizontalAlignment textAlign)
2578                         {
2579                                 ColumnHeader colHeader = new ColumnHeader (this.owner, str, textAlign, width);
2580                                 this.Insert (index, colHeader);
2581                         }
2582
2583                         public virtual void Remove (ColumnHeader column)
2584                         {
2585                                 // TODO: Update Column internal index ?
2586                                 list.Remove (column);
2587                                 owner.Redraw (true);
2588                         }
2589
2590                         public virtual void RemoveAt (int index)
2591                         {
2592                                 if (index < 0 || index >= list.Count)
2593                                         throw new ArgumentOutOfRangeException ("index");
2594
2595                                 // TODO: Update Column internal index ?
2596                                 list.RemoveAt (index);
2597                                 owner.Redraw (true);
2598                         }
2599                         #endregion      // Public Methods
2600                         
2601
2602                 }       // ColumnHeaderCollection
2603
2604                 public class ListViewItemCollection : IList, ICollection, IEnumerable
2605                 {
2606                         internal ArrayList list;
2607                         private readonly ListView owner;
2608
2609                         #region Public Constructor
2610                         public ListViewItemCollection (ListView owner)
2611                         {
2612                                 list = new ArrayList ();
2613                                 this.owner = owner;
2614                         }
2615                         #endregion      // Public Constructor
2616
2617                         #region Public Properties
2618                         [Browsable (false)]
2619                         public int Count {
2620                                 get { return list.Count; }
2621                         }
2622
2623                         public bool IsReadOnly {
2624                                 get { return false; }
2625                         }
2626
2627                         public virtual ListViewItem this [int displayIndex] {
2628                                 get {
2629                                         if (displayIndex < 0 || displayIndex >= list.Count)
2630                                                 throw new ArgumentOutOfRangeException ("displayIndex");
2631                                         return (ListViewItem) list [displayIndex];
2632                                 }
2633
2634                                 set {
2635                                         if (displayIndex < 0 || displayIndex >= list.Count)
2636                                                 throw new ArgumentOutOfRangeException ("displayIndex");
2637
2638                                         if (list.Contains (value))
2639                                                 throw new ArgumentException ("An item cannot be added more than once. To add an item again, you need to clone it.", "value");
2640
2641                                         value.Owner = owner;
2642                                         list [displayIndex] = value;
2643
2644                                         owner.Redraw (true);
2645                                 }
2646                         }
2647
2648                         bool ICollection.IsSynchronized {
2649                                 get { return true; }
2650                         }
2651
2652                         object ICollection.SyncRoot {
2653                                 get { return this; }
2654                         }
2655
2656                         bool IList.IsFixedSize {
2657                                 get { return list.IsFixedSize; }
2658                         }
2659
2660                         object IList.this [int index] {
2661                                 get { return this [index]; }
2662                                 set {
2663                                         if (value is ListViewItem)
2664                                                 this [index] = (ListViewItem) value;
2665                                         else
2666                                                 this [index] = new ListViewItem (value.ToString ());
2667                                 }
2668                         }
2669                         #endregion      // Public Properties
2670
2671                         #region Public Methods
2672                         public virtual ListViewItem Add (ListViewItem value)
2673                         {
2674                                 if (list.Contains (value))
2675                                         throw new ArgumentException ("An item cannot be added more than once. To add an item again, you need to clone it.", "value");
2676
2677                                 value.Owner = owner;
2678                                 list.Add (value);
2679
2680                                 owner.Sort (false);
2681                                 owner.Redraw (true);
2682                                 return value;
2683                         }
2684
2685                         public virtual ListViewItem Add (string text)
2686                         {
2687                                 ListViewItem item = new ListViewItem (text);
2688                                 return this.Add (item);
2689                         }
2690
2691                         public virtual ListViewItem Add (string text, int imageIndex)
2692                         {
2693                                 ListViewItem item = new ListViewItem (text, imageIndex);
2694                                 return this.Add (item);
2695                         }
2696
2697                         public void AddRange (ListViewItem [] values)
2698                         {
2699                                 list.Clear ();
2700                                 owner.SelectedItems.list.Clear ();
2701                                 owner.CheckedItems.list.Clear ();
2702
2703                                 foreach (ListViewItem item in values) {
2704                                         item.Owner = owner;
2705                                         list.Add (item);
2706                                 }
2707
2708                                 owner.Sort (false);
2709                                 owner.Redraw (true);
2710                         }
2711
2712                         public virtual void Clear ()
2713                         {
2714                                 owner.SetFocusedItem (null);
2715                                 owner.h_scroll.Value = owner.v_scroll.Value = 0;
2716                                 list.Clear ();
2717                                 owner.SelectedItems.list.Clear ();
2718                                 owner.CheckedItems.list.Clear ();
2719                                 owner.Redraw (true);
2720                         }
2721
2722                         public bool Contains (ListViewItem item)
2723                         {
2724                                 return list.Contains (item);
2725                         }
2726
2727                         public void CopyTo (Array dest, int index)
2728                         {
2729                                 list.CopyTo (dest, index);
2730                         }
2731
2732                         public IEnumerator GetEnumerator ()
2733                         {
2734                                 return list.GetEnumerator ();
2735                         }
2736
2737                         int IList.Add (object item)
2738                         {
2739                                 int result;
2740                                 ListViewItem li;
2741
2742                                 if (item is ListViewItem) {
2743                                         li = (ListViewItem) item;
2744                                         if (list.Contains (li))
2745                                                 throw new ArgumentException ("An item cannot be added more than once. To add an item again, you need to clone it.", "item");
2746                                 }
2747                                 else
2748                                         li = new ListViewItem (item.ToString ());
2749
2750                                 li.Owner = owner;
2751                                 result = list.Add (li);
2752                                 owner.Redraw (true);
2753
2754                                 return result;
2755                         }
2756
2757                         bool IList.Contains (object item)
2758                         {
2759                                 return list.Contains (item);
2760                         }
2761
2762                         int IList.IndexOf (object item)
2763                         {
2764                                 return list.IndexOf (item);
2765                         }
2766
2767                         void IList.Insert (int index, object item)
2768                         {
2769                                 if (item is ListViewItem)
2770                                         this.Insert (index, (ListViewItem) item);
2771                                 else
2772                                         this.Insert (index, item.ToString ());
2773                         }
2774
2775                         void IList.Remove (object item)
2776                         {
2777                                 Remove ((ListViewItem) item);
2778                         }
2779
2780                         public int IndexOf (ListViewItem item)
2781                         {
2782                                 return list.IndexOf (item);
2783                         }
2784
2785                         public ListViewItem Insert (int index, ListViewItem item)
2786                         {
2787                                 if (index < 0 || index > list.Count)
2788                                         throw new ArgumentOutOfRangeException ("index");
2789
2790                                 if (list.Contains (item))
2791                                         throw new ArgumentException ("An item cannot be added more than once. To add an item again, you need to clone it.", "item");
2792
2793                                 item.Owner = owner;
2794                                 list.Insert (index, item);
2795                                 owner.Redraw (true);
2796                                 return item;
2797                         }
2798
2799                         public ListViewItem Insert (int index, string text)
2800                         {
2801                                 return this.Insert (index, new ListViewItem (text));
2802                         }
2803
2804                         public ListViewItem Insert (int index, string text, int imageIndex)
2805                         {
2806                                 return this.Insert (index, new ListViewItem (text, imageIndex));
2807                         }
2808
2809                         public virtual void Remove (ListViewItem item)
2810                         {
2811                                 if (!list.Contains (item))
2812                                         return;
2813                                         
2814                                 owner.SelectedItems.list.Remove (item);
2815                                 owner.CheckedItems.list.Remove (item);
2816                                 list.Remove (item);
2817                                 owner.Redraw (true);                            
2818                         }
2819
2820                         public virtual void RemoveAt (int index)
2821                         {
2822                                 ListViewItem item = this [index];
2823                                 list.RemoveAt (index);
2824                                 owner.SelectedItems.list.Remove (item);
2825                                 owner.CheckedItems.list.Remove (item);
2826                                 owner.Redraw (false);
2827                         }
2828                         #endregion      // Public Methods
2829
2830                 }       // ListViewItemCollection
2831
2832                 public class SelectedIndexCollection : IList, ICollection, IEnumerable
2833                 {
2834                         private readonly ListView owner;
2835
2836                         #region Public Constructor
2837                         public SelectedIndexCollection (ListView owner)
2838                         {
2839                                 this.owner = owner;
2840                         }
2841                         #endregion      // Public Constructor
2842
2843                         #region Public Properties
2844                         [Browsable (false)]
2845                         public int Count {
2846                                 get {
2847                                         return owner.SelectedItems.Count;
2848                                 }
2849                         }
2850
2851                         public bool IsReadOnly {
2852                                 get { return true; }
2853                         }
2854
2855                         public int this [int index] {
2856                                 get {
2857                                         int [] indices = GetIndices ();
2858                                         if (index < 0 || index >= indices.Length)
2859                                                 throw new ArgumentOutOfRangeException ("index");
2860                                         return indices [index];
2861                                 }
2862                         }
2863
2864                         bool ICollection.IsSynchronized {
2865                                 get { return false; }
2866                         }
2867
2868                         object ICollection.SyncRoot {
2869                                 get { return this; }
2870                         }
2871
2872                         bool IList.IsFixedSize {
2873                                 get { return true; }
2874                         }
2875
2876                         object IList.this [int index] {
2877                                 get { return this [index]; }
2878                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
2879                         }
2880                         #endregion      // Public Properties
2881
2882                         #region Public Methods
2883                         public bool Contains (int selectedIndex)
2884                         {
2885                                 int [] indices = GetIndices ();
2886                                 for (int i = 0; i < indices.Length; i++) {
2887                                         if (indices [i] == selectedIndex)
2888                                                 return true;
2889                                 }
2890                                 return false;
2891                         }
2892
2893                         public void CopyTo (Array dest, int index)
2894                         {
2895                                 int [] indices = GetIndices ();
2896                                 Array.Copy (indices, 0, dest, index, indices.Length);
2897                         }
2898
2899                         public IEnumerator GetEnumerator ()
2900                         {
2901                                 int [] indices = GetIndices ();
2902                                 return indices.GetEnumerator ();
2903                         }
2904
2905                         int IList.Add (object value)
2906                         {
2907                                 throw new NotSupportedException ("Add operation is not supported.");
2908                         }
2909
2910                         void IList.Clear ()
2911                         {
2912                                 throw new NotSupportedException ("Clear operation is not supported.");
2913                         }
2914
2915                         bool IList.Contains (object selectedIndex)
2916                         {
2917                                 if (!(selectedIndex is int))
2918                                         return false;
2919                                 return Contains ((int) selectedIndex);
2920                         }
2921
2922                         int IList.IndexOf (object selectedIndex)
2923                         {
2924                                 if (!(selectedIndex is int))
2925                                         return -1;
2926                                 return IndexOf ((int) selectedIndex);
2927                         }
2928
2929                         void IList.Insert (int index, object value)
2930                         {
2931                                 throw new NotSupportedException ("Insert operation is not supported.");
2932                         }
2933
2934                         void IList.Remove (object value)
2935                         {
2936                                 throw new NotSupportedException ("Remove operation is not supported.");
2937                         }
2938
2939                         void IList.RemoveAt (int index)
2940                         {
2941                                 throw new NotSupportedException ("RemoveAt operation is not supported.");
2942                         }
2943
2944                         public int IndexOf (int selectedIndex)
2945                         {
2946                                 int [] indices = GetIndices ();
2947                                 for (int i = 0; i < indices.Length; i++) {
2948                                         if (indices [i] == selectedIndex)
2949                                                 return i;
2950                                 }
2951                                 return -1;
2952                         }
2953                         #endregion      // Public Methods
2954
2955                         private int [] GetIndices ()
2956                         {
2957                                 int [] indices = new int [Count];
2958                                 for (int i = 0; i < owner.SelectedItems.Count; i++) {
2959                                         ListViewItem item = owner.SelectedItems [i];
2960                                         indices [i] = item.Index;
2961                                 }
2962                                 return indices;
2963                         }
2964
2965                 }       // SelectedIndexCollection
2966
2967                 public class SelectedListViewItemCollection : IList, ICollection, IEnumerable
2968                 {
2969                         internal ArrayList list;
2970                         private readonly ListView owner;
2971
2972                         #region Public Constructor
2973                         public SelectedListViewItemCollection (ListView owner)
2974                         {
2975                                 list = new ArrayList ();
2976                                 this.owner = owner;
2977                         }
2978                         #endregion      // Public Constructor
2979
2980                         #region Public Properties
2981                         [Browsable (false)]
2982                         public int Count {
2983                                 get {
2984                                         if (!owner.IsHandleCreated)
2985                                                 return 0;
2986                                         return list.Count;
2987                                 }
2988                         }
2989
2990                         public bool IsReadOnly {
2991                                 get { return true; }
2992                         }
2993
2994                         public ListViewItem this [int index] {
2995                                 get {
2996                                         if (index < 0 || index >= Count)
2997                                                 throw new ArgumentOutOfRangeException ("index");
2998                                         return (ListViewItem) list [index];
2999                                 }
3000                         }
3001
3002                         bool ICollection.IsSynchronized {
3003                                 get { return list.IsSynchronized; }
3004                         }
3005
3006                         object ICollection.SyncRoot {
3007                                 get { return this; }
3008                         }
3009
3010                         bool IList.IsFixedSize {
3011                                 get { return true; }
3012                         }
3013
3014                         object IList.this [int index] {
3015                                 get { return this [index]; }
3016                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
3017                         }
3018                         #endregion      // Public Properties
3019
3020                         #region Public Methods
3021                         public void Clear ()
3022                         {
3023                                 if (!owner.IsHandleCreated)
3024                                         return;
3025
3026                                 ArrayList copy = (ArrayList) list.Clone ();
3027                                 for (int i = 0; i < copy.Count; i++)
3028                                         ((ListViewItem) copy [i]).Selected = false;
3029
3030                                 list.Clear ();
3031                         }
3032
3033                         public bool Contains (ListViewItem item)
3034                         {
3035                                 if (!owner.IsHandleCreated)
3036                                         return false;
3037                                 return list.Contains (item);
3038                         }
3039
3040                         public void CopyTo (Array dest, int index)
3041                         {
3042                                 if (!owner.IsHandleCreated)
3043                                         return;
3044                                 list.CopyTo (dest, index);
3045                         }
3046
3047                         public IEnumerator GetEnumerator ()
3048                         {
3049                                 if (!owner.IsHandleCreated)
3050                                         return (new ListViewItem [0]).GetEnumerator ();
3051                                 return list.GetEnumerator ();
3052                         }
3053
3054                         int IList.Add (object value)
3055                         {
3056                                 throw new NotSupportedException ("Add operation is not supported.");
3057                         }
3058
3059                         bool IList.Contains (object item)
3060                         {
3061                                 if (!(item is ListViewItem))
3062                                         return false;
3063                                 return Contains ((ListViewItem) item);
3064                         }
3065
3066                         int IList.IndexOf (object item)
3067                         {
3068                                 if (!(item is ListViewItem))
3069                                         return -1;
3070                                 return IndexOf ((ListViewItem) item);
3071                         }
3072
3073                         void IList.Insert (int index, object value)
3074                         {
3075                                 throw new NotSupportedException ("Insert operation is not supported.");
3076                         }
3077
3078                         void IList.Remove (object value)
3079                         {
3080                                 throw new NotSupportedException ("Remove operation is not supported.");
3081                         }
3082
3083                         void IList.RemoveAt (int index)
3084                         {
3085                                 throw new NotSupportedException ("RemoveAt operation is not supported.");
3086                         }
3087
3088                         public int IndexOf (ListViewItem item)
3089                         {
3090                                 if (!owner.IsHandleCreated)
3091                                         return -1;
3092                                 return list.IndexOf (item);
3093                         }
3094                         #endregion      // Public Methods
3095
3096                 }       // SelectedListViewItemCollection
3097
3098                 #endregion // Subclasses
3099         }
3100 }