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