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