* ssapre-cee-ops.h: Renamed as "simple-cee-ops.h"
[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;
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                                 return;
781                         }
782
783                         // making a scroll bar visible might make
784                         // other scroll bar visible                     
785                         if (layout_wd > client_area.Right) {
786                                 h_scroll.Visible = true;
787                                 if ((layout_ht + h_scroll.Height) > client_area.Bottom)
788                                         v_scroll.Visible = true;                                        
789                                 else
790                                         v_scroll.Visible = false;
791                         } else if (layout_ht > client_area.Bottom) {                            
792                                 v_scroll.Visible = true;
793                                 if ((layout_wd + v_scroll.Width) > client_area.Right)
794                                         h_scroll.Visible = true;
795                                 else
796                                         h_scroll.Visible = false;
797                         } else {
798                                 h_scroll.Visible = false;
799                                 v_scroll.Visible = false;
800                         }                       
801
802                         item_control.Height = ClientRectangle.Height - header_control.Height;
803
804                         if (h_scroll.Visible) {
805                                 h_scroll.Location = new Point (client_area.X, client_area.Bottom - h_scroll.Height);
806                                 h_scroll.Minimum = 0;
807
808                                 // if v_scroll is visible, adjust the maximum of the
809                                 // h_scroll to account for the width of v_scroll
810                                 if (v_scroll.Visible) {
811                                         h_scroll.Maximum = layout_wd + v_scroll.Width;
812                                         h_scroll.Width = client_area.Width - v_scroll.Width;
813                                 }
814                                 else {
815                                         h_scroll.Maximum = layout_wd;
816                                         h_scroll.Width = client_area.Width;
817                                 }
818    
819                                 h_scroll.LargeChange = client_area.Width;
820                                 h_scroll.SmallChange = Font.Height;
821                                 item_control.Height -= h_scroll.Height;
822                         }
823
824                         if (header_control.Visible)
825                                 header_control.Width = ClientRectangle.Width;
826                         item_control.Width = ClientRectangle.Width;
827
828                         if (v_scroll.Visible) {
829                                 v_scroll.Location = new Point (client_area.Right - v_scroll.Width, client_area.Y);
830                                 v_scroll.Minimum = 0;
831
832                                 // if h_scroll is visible, adjust the maximum of the
833                                 // v_scroll to account for the height of h_scroll
834                                 if (h_scroll.Visible) {
835                                         v_scroll.Maximum = layout_ht + h_scroll.Height;
836                                         v_scroll.Height = client_area.Height; // - h_scroll.Height already done 
837                                 } else {
838                                         v_scroll.Maximum = layout_ht;
839                                         v_scroll.Height = client_area.Height;
840                                 }
841
842                                 v_scroll.LargeChange = client_area.Height;
843                                 v_scroll.SmallChange = Font.Height;
844                                 if (header_control.Visible)
845                                         header_control.Width -= v_scroll.Width;
846                                 item_control.Width -= v_scroll.Width;
847                         }
848                 }
849                 
850                 ColumnHeader GetReorderedColumn (int index)
851                 {
852                         if (reordered_column_indices == null)
853                                 return Columns [index];
854                         else
855                                 return Columns [reordered_column_indices [index]];
856                 }
857
858                 void ReorderColumn (ColumnHeader col, int index)
859                 {
860                         if (reordered_column_indices == null) {
861                                 reordered_column_indices = new int [Columns.Count];
862                                 for (int i = 0; i < Columns.Count; i++)
863                                         reordered_column_indices [i] = i;
864                         }
865
866                         if (reordered_column_indices [index] == col.Index)
867                                 return;
868
869                         int[] curr = reordered_column_indices;
870                         int[] result = new int [Columns.Count];
871                         int curr_idx = 0;
872                         for (int i = 0; i < Columns.Count; i++) {
873                                 if (curr_idx < Columns.Count && curr [curr_idx] == col.Index)
874                                         curr_idx++;
875
876                                 if (i == index)
877                                         result [i] = col.Index;
878                                 else
879                                         result [i] = curr [curr_idx++];
880                         }
881
882                         reordered_column_indices = result;
883                         LayoutDetails ();
884                         header_control.Invalidate ();
885                         item_control.Invalidate ();
886                 }
887
888                 Size LargeIconItemSize {
889                         get {
890                                 int image_w = LargeImageList == null ? 12 : LargeImageList.ImageSize.Width;
891                                 int image_h = LargeImageList == null ? 2 : LargeImageList.ImageSize.Height;
892                                 int w = CheckBoxSize.Width + 2 + Math.Max (text_size.Width, image_w);
893                                 int h = text_size.Height + 2 + Math.Max (CheckBoxSize.Height, image_h);
894                                 return new Size (w, h);
895                         }
896                 }
897
898                 Size SmallIconItemSize {
899                         get {
900                                 int image_w = SmallImageList == null ? 0 : SmallImageList.ImageSize.Width;
901                                 int image_h = SmallImageList == null ? 0 : SmallImageList.ImageSize.Height;
902                                 int w = text_size.Width + 2 + CheckBoxSize.Width + image_w;
903                                 int h = Math.Max (text_size.Height, Math.Max (CheckBoxSize.Height, image_h));
904                                 return new Size (w, h);
905                         }
906                 }
907
908                 int rows;
909                 int cols;
910                 ListViewItem[,] item_matrix;
911
912                 void LayoutIcons (bool large_icons, bool left_aligned, int x_spacing, int y_spacing)
913                 {
914                         header_control.Visible = false;
915                         header_control.Size = Size.Empty;
916                         item_control.Visible = true;
917                         item_control.Location = Point.Empty;
918
919                         if (items.Count == 0)
920                                 return;
921
922                         Size sz = large_icons ? LargeIconItemSize : SmallIconItemSize;
923
924                         Rectangle area = ClientRectangle;
925
926                         if (left_aligned) {
927                                 rows = (int) Math.Floor ((double)(area.Height - h_scroll.Height + y_spacing) / (double)(sz.Height + y_spacing));
928                                 if (rows <= 0)
929                                         rows = 1;
930                                 cols = (int) Math.Ceiling ((double)items.Count / (double)rows);
931                         } else {
932                                 cols = (int) Math.Floor ((double)(area.Width - v_scroll.Width + x_spacing) / (double)(sz.Width + x_spacing));
933                                 if (cols <= 0)
934                                         cols = 1;
935                                 rows = (int) Math.Ceiling ((double)items.Count / (double)cols);
936                         }
937
938                         layout_ht = rows * (sz.Height + y_spacing) - y_spacing;
939                         layout_wd = cols * (sz.Width + x_spacing) - x_spacing;
940                         item_matrix = new ListViewItem [rows, cols];
941                         int row = 0;
942                         int col = 0;
943                         foreach (ListViewItem item in items) {
944                                 int x = col * (sz.Width + x_spacing);
945                                 int y = row * (sz.Height + y_spacing);
946                                 item.Location = new Point (x, y);
947                                 item.Layout ();
948                                 item.row = row;
949                                 item.col = col;
950                                 item_matrix [row, col] = item;
951                                 if (left_aligned) {
952                                         if (++row == rows) {
953                                                 row = 0;
954                                                 col++;
955                                         }
956                                 } else {
957                                         if (++col == cols) {
958                                                 col = 0;
959                                                 row++;
960                                         }
961                                 }
962                         }
963
964                         item_control.Size = new Size (layout_wd, layout_ht);
965                 }
966
967                 void LayoutHeader ()
968                 {
969                         if (header_style == ColumnHeaderStyle.None) {
970                                 header_control.Visible = false;
971                                 header_control.Size = Size.Empty;
972                                 return;
973                         }
974
975                         int x = 0;
976                         for (int i = 0; i < Columns.Count; i++) {
977                                 ColumnHeader col = GetReorderedColumn (i);
978                                 col.X = x;
979                                 col.Y = 0;
980                                 col.CalcColumnHeader ();
981                                 x += col.Wd;
982                         }
983
984                         if (x < ClientRectangle.Width)
985                                 x = ClientRectangle.Width;
986
987                         header_control.Width = x;
988                         header_control.Height = columns [0].Ht;
989                         header_control.Visible = true;
990                 }
991
992                 void LayoutDetails ()
993                 {
994                         if (columns.Count == 0) {
995                                 header_control.Visible = false;
996                                 item_control.Visible = false;
997                                 return;
998                         }
999
1000                         LayoutHeader ();
1001
1002                         item_control.Visible = true;
1003                         item_control.Location = new Point (0, header_control.Height);
1004
1005                         int y = 0; 
1006                         if (items.Count > 0) {
1007                                 foreach (ListViewItem item in items) {
1008                                         item.Layout ();
1009                                         item.Location = new Point (0, y);
1010                                         y += item.Bounds.Height + 2;
1011                                 }
1012
1013                                 // some space for bottom gridline
1014                                 if (grid_lines)
1015                                         y += 2;
1016                         }
1017
1018                         layout_wd = Math.Max (header_control.Width, item_control.Width);
1019                         layout_ht = y + header_control.Height;
1020                 }
1021
1022                 private void CalculateListView (ListViewAlignment align)
1023                 {
1024                         CalcTextSize ();
1025
1026                         switch (view) {
1027                         case View.Details:
1028                                 LayoutDetails ();
1029                                 break;
1030
1031                         case View.SmallIcon:
1032                                 LayoutIcons (false, alignment == ListViewAlignment.Left, 4, 2);
1033                                 break;
1034
1035                         case View.LargeIcon:
1036                                 LayoutIcons (true, alignment == ListViewAlignment.Left,
1037                                              ThemeEngine.Current.ListViewHorizontalSpacing,
1038                                              ThemeEngine.Current.ListViewVerticalSpacing);
1039                                 break;
1040
1041                         case View.List:
1042                                 LayoutIcons (false, true, 4, 2);
1043                                 break;
1044                         }
1045
1046                         CalculateScrollBars ();
1047                 }
1048
1049                 internal void UpdateSelection (ListViewItem item)
1050                 {
1051                         if (item.Selected) {
1052
1053                                 if (!CanMultiselect && SelectedItems.Count > 0) {
1054                                         SelectedItems.Clear ();
1055                                         SelectedIndices.list.Clear ();
1056                                 }
1057
1058                                 if (!SelectedItems.Contains (item)) {
1059                                         SelectedItems.list.Add (item);
1060                                         SelectedIndices.list.Add (item.Index);
1061                                 }
1062                         } else {
1063                                 SelectedItems.list.Remove (item);
1064                                 SelectedIndices.list.Remove (item.Index);
1065                         }
1066                 }
1067
1068                 private bool KeySearchString (KeyEventArgs ke)
1069                 {
1070                         int current_tickcnt = Environment.TickCount;
1071                         if (keysearch_tickcnt > 0 && current_tickcnt - keysearch_tickcnt > keysearch_keydelay) {
1072                                 keysearch_text = string.Empty;
1073                         }
1074                         
1075                         keysearch_text += (char) ke.KeyData;
1076                         keysearch_tickcnt = current_tickcnt;
1077
1078                         int start = FocusedItem == null ? 0 : FocusedItem.Index;
1079                         int i = start;
1080                         while (true) {
1081                                 if (CultureInfo.CurrentCulture.CompareInfo.IsPrefix (Items[i].Text, keysearch_text,
1082                                         CompareOptions.IgnoreCase)) {
1083                                         SetFocusedItem (Items [i]);
1084                                         items [i].Selected = true;
1085                                         EnsureVisible (i);
1086                                         break;
1087                                 }
1088                                 i = (i + 1  < Items.Count) ? i+1 : 0;
1089
1090                                 if (i == start)
1091                                         break;
1092                         }
1093                         return true;
1094                 }
1095
1096                 int GetAdjustedIndex (Keys key)
1097                 {
1098                         int result = -1;
1099
1100                         if (View == View.Details) {
1101                                 if (key == Keys.Up)
1102                                         result = FocusedItem.Index - 1;
1103                                 else if (key == Keys.Down) {
1104                                         result = FocusedItem.Index + 1;
1105                                         if (result == items.Count)
1106                                                 result = -1;
1107                                 }
1108                                 return result;
1109                         }
1110
1111                         int row = FocusedItem.row;
1112                         int col = FocusedItem.col;
1113
1114                         switch (key) {
1115                         case Keys.Left:
1116                                 if (col == 0)
1117                                         return -1;
1118                                 return item_matrix [row, col - 1].Index;
1119
1120                         case Keys.Right:
1121                                 if (col == (cols - 1))
1122                                         return -1;
1123                                 while (item_matrix [row, col + 1] == null)
1124                                        row--;   
1125                                 return item_matrix [row, col + 1].Index;
1126
1127                         case Keys.Up:
1128                                 if (row == 0)
1129                                         return -1;
1130                                 return item_matrix [row - 1, col].Index;
1131
1132                         case Keys.Down:
1133                                 if (row == (rows - 1) || row == Items.Count - 1)
1134                                         return -1;
1135                                 while (item_matrix [row + 1, col] == null)
1136                                        col--;   
1137                                 return item_matrix [row + 1, col].Index;
1138
1139                         default:
1140                                 return -1;
1141                         }
1142                 }
1143
1144                 ListViewItem selection_start;
1145
1146                 private bool SelectItems (ArrayList sel_items)
1147                 {
1148                         bool changed = false;
1149                         multiselecting = true;
1150                         ArrayList curr_items = (ArrayList) SelectedItems.list.Clone ();
1151                         foreach (ListViewItem item in curr_items)
1152                                 if (!sel_items.Contains (item)) {
1153                                         item.Selected = false;
1154                                         changed = true;
1155                                 }
1156                         foreach (ListViewItem item in sel_items)
1157                                 if (!item.Selected) {
1158                                         item.Selected = true;
1159                                         changed = true;
1160                                 }
1161                         multiselecting = false;
1162                         return changed;
1163                 }
1164
1165                 private void UpdateMultiSelection (int index)
1166                 {
1167                         bool shift_pressed = (XplatUI.State.ModifierKeys & Keys.Shift) != 0;
1168                         bool ctrl_pressed = (XplatUI.State.ModifierKeys & Keys.Control) != 0;
1169                         ListViewItem item = items [index];
1170
1171                         if (shift_pressed && selection_start != null) {
1172                                 ArrayList list = new ArrayList ();
1173                                 int start = Math.Min (selection_start.Index, index);
1174                                 int end = Math.Max (selection_start.Index, index);
1175                                 if (View == View.Details) {
1176                                         for (int i = start; i <= end; i++)
1177                                                 list.Add (items [i]);
1178                                 } else {
1179                                         int left = Math.Min (items [start].col, items [end].col);
1180                                         int right = Math.Max (items [start].col, items [end].col);
1181                                         int top = Math.Min (items [start].row, items [end].row);
1182                                         int bottom = Math.Max (items [start].row, items [end].row);
1183                                         foreach (ListViewItem curr in items)
1184                                                 if (curr.row >= top && curr.row <= bottom && 
1185                                                     curr.col >= left && curr.col <= right)
1186                                                         list.Add (curr);
1187                                 }
1188                                 if (SelectItems (list))
1189                                         OnSelectedIndexChanged (EventArgs.Empty);
1190                         } else if (!ctrl_pressed) {
1191                                 SelectedItems.Clear ();
1192                                 SelectedIndices.list.Clear ();
1193                                 item.Selected = true;
1194                                 selection_start = item;
1195                                 OnSelectedIndexChanged (EventArgs.Empty);
1196                         }
1197                 }
1198
1199                 private void ListView_KeyDown (object sender, KeyEventArgs ke)
1200                 {                       
1201                         if (ke.Handled || Items.Count == 0 || !item_control.Visible)
1202                                 return;
1203
1204                         int index = -1;
1205                         ke.Handled = true;
1206
1207                         if (FocusedItem == null)
1208                                 SetFocusedItem (Items [0]);
1209
1210                         switch (ke.KeyCode) {
1211
1212                         case Keys.End:
1213                                 index = Items.Count - 1;
1214                                 break;
1215
1216                         case Keys.Home:                 
1217                                 index = 0;
1218                                 break;
1219
1220                         case Keys.Left:
1221                         case Keys.Right:
1222                         case Keys.Up:                           
1223                         case Keys.Down:
1224                                 index = GetAdjustedIndex (ke.KeyCode);
1225                                 break;
1226
1227                         default:
1228                                 ke.Handled = KeySearchString (ke);
1229                                 return;
1230                         }
1231                         
1232                         if (index == -1)
1233                                 return;
1234
1235                         if (MultiSelect)
1236                                 UpdateMultiSelection (index);
1237                         else if (!items [index].Selected) {
1238                                 items [index].Selected = true;
1239                                 OnSelectedIndexChanged (EventArgs.Empty);
1240                         }
1241
1242                         SetFocusedItem (items [index]);                         
1243                         EnsureVisible (index);
1244                 }
1245
1246                                 
1247                 internal class ItemControl : Control {
1248
1249                         ListView owner;
1250                         ListViewItem clicked_item;
1251                         ListViewItem last_clicked_item;
1252                         bool hover_processed = false;
1253                         bool checking = false;
1254
1255                         public ItemControl (ListView owner)
1256                         {
1257                                 this.owner = owner;
1258                                 DoubleClick += new EventHandler(ItemsDoubleClick);
1259                                 MouseDown += new MouseEventHandler(ItemsMouseDown);
1260                                 MouseMove += new MouseEventHandler(ItemsMouseMove);
1261                                 MouseHover += new EventHandler(ItemsMouseHover);
1262                                 MouseUp += new MouseEventHandler(ItemsMouseUp);
1263                                 MouseWheel += new MouseEventHandler(ItemsMouseWheel);
1264                         }
1265
1266                         void ItemsDoubleClick (object sender, EventArgs e)
1267                         {
1268                                 if (owner.activation == ItemActivation.Standard && owner.ItemActivate != null)
1269                                         owner.ItemActivate (this, e);
1270                         }
1271
1272                         enum BoxSelect {
1273                                 None,
1274                                 Normal,
1275                                 Shift,
1276                                 Control
1277                         }
1278
1279                         BoxSelect box_select_mode = BoxSelect.None;
1280                         ArrayList prev_selection;
1281                         Point box_select_start;
1282
1283                         Rectangle box_select_rect;
1284                         internal Rectangle BoxSelectRectangle {
1285                                 get { return box_select_rect; }
1286                                 set {
1287                                         if (box_select_rect == value)
1288                                                 return;
1289
1290                                         InvalidateBoxSelectRect ();
1291                                         box_select_rect = value;
1292                                         InvalidateBoxSelectRect ();
1293                                 }
1294                         }
1295
1296                         void InvalidateBoxSelectRect ()
1297                         {
1298                                 if (BoxSelectRectangle.Size.IsEmpty)
1299                                         return;
1300
1301                                 Rectangle edge = BoxSelectRectangle;
1302                                 edge.X -= 1;
1303                                 edge.Y -= 1;
1304                                 edge.Width += 2;
1305                                 edge.Height = 2;
1306                                 Invalidate (edge);
1307                                 edge.Y = BoxSelectRectangle.Bottom - 1;
1308                                 Invalidate (edge);
1309                                 edge.Y = BoxSelectRectangle.Y - 1;
1310                                 edge.Width = 2;
1311                                 edge.Height = BoxSelectRectangle.Height + 2;
1312                                 Invalidate (edge);
1313                                 edge.X = BoxSelectRectangle.Right - 1;
1314                                 Invalidate (edge);
1315                         }
1316
1317                         private Rectangle CalculateBoxSelectRectangle (Point pt)
1318                         {
1319                                 int left = Math.Min (box_select_start.X, pt.X);
1320                                 int right = Math.Max (box_select_start.X, pt.X);
1321                                 int top = Math.Min (box_select_start.Y, pt.Y);
1322                                 int bottom = Math.Max (box_select_start.Y, pt.Y);
1323                                 return Rectangle.FromLTRB (left, top, right, bottom);
1324                         }
1325
1326                         ArrayList BoxSelectedItems {
1327                                 get {
1328                                         ArrayList result = new ArrayList ();
1329                                         foreach (ListViewItem item in owner.Items) {
1330                                                 Rectangle r = item.Bounds;
1331                                                 r.X += r.Width / 4;
1332                                                 r.Y += r.Height / 4;
1333                                                 r.Width /= 2;
1334                                                 r.Height /= 2;
1335                                                 if (BoxSelectRectangle.IntersectsWith (r))
1336                                                         result.Add (item);
1337                                         }
1338                                         return result;
1339                                 }
1340                         }
1341
1342                         private bool PerformBoxSelection (Point pt)
1343                         {
1344                                 if (box_select_mode == BoxSelect.None)
1345                                         return false;
1346
1347                                 BoxSelectRectangle = CalculateBoxSelectRectangle (pt);
1348                                 
1349                                 ArrayList box_items = BoxSelectedItems;
1350
1351                                 ArrayList items;
1352
1353                                 switch (box_select_mode) {
1354
1355                                 case BoxSelect.Normal:
1356                                         items = box_items;
1357                                         break;
1358
1359                                 case BoxSelect.Control:
1360                                         items = new ArrayList ();
1361                                         foreach (ListViewItem item in prev_selection)
1362                                                 if (!box_items.Contains (item))
1363                                                         items.Add (item);
1364                                         foreach (ListViewItem item in box_items)
1365                                                 if (!prev_selection.Contains (item))
1366                                                         items.Add (item);
1367                                         break;
1368
1369                                 case BoxSelect.Shift:
1370                                         items = box_items;
1371                                         foreach (ListViewItem item in box_items)
1372                                                 prev_selection.Remove (item);
1373                                         foreach (ListViewItem item in prev_selection)
1374                                                 items.Add (item);
1375                                         break;
1376
1377                                 default:
1378                                         throw new Exception ("Unexpected Selection mode: " + box_select_mode);
1379                                 }
1380
1381                                 SuspendLayout ();
1382                                 owner.SelectItems (items);
1383                                 ResumeLayout ();
1384
1385                                 return true;
1386                         }
1387
1388                         private void ToggleCheckState (ListViewItem item)
1389                         {
1390                                 CheckState curr_state = item.Checked ?  CheckState.Checked : CheckState.Unchecked;
1391                                 item.Checked = !item.Checked;
1392                                 CheckState new_state = item.Checked ?  CheckState.Checked : CheckState.Unchecked;
1393
1394                                 ItemCheckEventArgs ice = new ItemCheckEventArgs (item.Index, curr_state, new_state);
1395                                 owner.OnItemCheck (ice);
1396                         }
1397
1398                         private void ItemsMouseDown (object sender, MouseEventArgs me)
1399                         {
1400                                 if (owner.items.Count == 0)
1401                                         return;
1402
1403                                 Point pt = new Point (me.X, me.Y);
1404                                 foreach (ListViewItem item in owner.items) {
1405                                         if (me.Clicks == 1 && item.CheckRectReal.Contains (pt)) {
1406                                                 checking = true;
1407                                                 if (me.Clicks > 1)
1408                                                         return;
1409                                                 ToggleCheckState (item);
1410                                                 return;
1411                                         }
1412
1413                                         if (owner.View == View.Details && !owner.FullRowSelect) {
1414                                                 if (item.GetBounds (ItemBoundsPortion.Label).Contains (pt)) {
1415                                                         clicked_item = item;
1416                                                         break;
1417                                                 }
1418                                         } else {
1419                                                 if (item.Bounds.Contains (pt)) {
1420                                                         clicked_item = item;
1421                                                         break;
1422                                                 }
1423                                         }
1424                                 }
1425
1426
1427                                 if (clicked_item != null) {
1428                                         owner.SetFocusedItem (clicked_item);
1429                                         bool changed = !clicked_item.Selected;
1430                                         if (owner.MultiSelect && (XplatUI.State.ModifierKeys & Keys.Control) == 0)
1431                                                 owner.UpdateMultiSelection (clicked_item.Index);
1432                                         else
1433                                                 clicked_item.Selected = true;
1434                                 
1435                                         if (changed)
1436                                                 owner.OnSelectedIndexChanged (EventArgs.Empty);
1437
1438                                         // Raise double click if the item was clicked. On MS the
1439                                         // double click is only raised if you double click an item
1440                                         if (me.Clicks > 1) {
1441                                                 owner.OnDoubleClick (EventArgs.Empty);
1442                                                 if (owner.CheckBoxes)
1443                                                         ToggleCheckState (clicked_item);
1444                                         } else if (me.Clicks == 1)
1445                                                 owner.OnClick (EventArgs.Empty);
1446                                 } else {
1447                                         if (owner.MultiSelect) {
1448                                                 Keys mods = XplatUI.State.ModifierKeys;
1449                                                 if ((mods & Keys.Shift) != 0)
1450                                                         box_select_mode = BoxSelect.Shift;
1451                                                 else if ((mods & Keys.Control) != 0)
1452                                                         box_select_mode = BoxSelect.Control;
1453                                                 else
1454                                                         box_select_mode = BoxSelect.Normal;
1455                                                 box_select_start = pt; 
1456                                                 prev_selection = (ArrayList) owner.SelectedItems.list.Clone ();
1457                                         } else if (owner.selected_indices.Count > 0) {
1458                                                 owner.SelectedItems.Clear ();
1459                                                 owner.SelectedIndices.list.Clear ();
1460                                                 owner.OnSelectedIndexChanged (EventArgs.Empty);
1461                                         }
1462                                 }
1463                         }
1464
1465                         private void ItemsMouseMove (object sender, MouseEventArgs me)
1466                         {
1467                                 if (PerformBoxSelection (new Point (me.X, me.Y)))
1468                                         return;
1469
1470                                 if (owner.HoverSelection && hover_processed) {
1471
1472                                         Point pt = PointToClient (Control.MousePosition);
1473                                         ListViewItem item = owner.GetItemAt (pt.X, pt.Y);
1474                                         if (item == null || item.Selected)
1475                                                 return;
1476
1477                                         hover_processed = false;
1478                                         XplatUI.ResetMouseHover (Handle);
1479                                 }
1480                         }
1481
1482
1483                         private void ItemsMouseHover (object sender, EventArgs e)
1484                         {
1485                                 if (Capture || !owner.HoverSelection)
1486                                         return;
1487
1488                                 hover_processed = true;
1489                                 Point pt = PointToClient (Control.MousePosition);
1490                                 ListViewItem item = owner.GetItemAt (pt.X, pt.Y);
1491
1492                                 if (item == null)
1493                                         return;
1494
1495                                 item.Selected = true;
1496                                 owner.OnSelectedIndexChanged (new EventArgs ());
1497                         }
1498
1499                         private void ItemsMouseUp (object sender, MouseEventArgs me)
1500                         {
1501                                 Capture = false;
1502                                 if (owner.Items.Count == 0)
1503                                         return;
1504
1505                                 Point pt = new Point (me.X, me.Y);
1506
1507                                 Rectangle rect = Rectangle.Empty;
1508                                 if (clicked_item != null) {
1509                                         if (owner.view == View.Details && !owner.full_row_select)
1510                                                 rect = clicked_item.GetBounds (ItemBoundsPortion.Label);
1511                                         else
1512                                                 rect = clicked_item.Bounds;
1513
1514                                         if (rect.Contains (pt)) {
1515                                                 switch (owner.activation) {
1516                                                 case ItemActivation.OneClick:
1517                                                         owner.OnItemActivate (EventArgs.Empty);
1518                                                         break;
1519
1520                                                 case ItemActivation.TwoClick:
1521                                                         if (last_clicked_item == clicked_item) {
1522                                                                 owner.OnItemActivate (EventArgs.Empty);
1523                                                                 last_clicked_item = null;
1524                                                         } else
1525                                                                 last_clicked_item = clicked_item;
1526                                                         break;
1527                                                 default:
1528                                                         // DoubleClick activation is handled in another handler
1529                                                         break;
1530                                                 }
1531                                         }
1532                                 } else if (!checking && owner.SelectedItems.Count > 0 && BoxSelectRectangle.Size.IsEmpty) {
1533                                         // Need this to clean up background clicks
1534                                         owner.SelectedItems.Clear ();
1535                                         owner.SelectedIndices.list.Clear ();
1536                                         owner.OnSelectedIndexChanged (EventArgs.Empty);
1537                                 }
1538
1539                                 clicked_item = null;
1540                                 box_select_start = Point.Empty;
1541                                 BoxSelectRectangle = Rectangle.Empty;
1542                                 prev_selection = null;
1543                                 box_select_mode = BoxSelect.None;
1544                                 checking = false;
1545                         }
1546
1547                         private void ItemsMouseWheel (object sender, MouseEventArgs me)
1548                         {
1549                                 if (owner.Items.Count == 0)
1550                                         return;
1551
1552                                 int lines = me.Delta / 120;
1553
1554                                 if (lines == 0)
1555                                         return;
1556
1557                                 switch (owner.View) {
1558                                 case View.Details:
1559                                 case View.SmallIcon:
1560                                         owner.Scroll (owner.v_scroll, -owner.Items [0].Bounds.Height * SystemInformation.MouseWheelScrollLines * lines);
1561                                         break;
1562                                 case View.LargeIcon:
1563                                         owner.Scroll (owner.v_scroll, -(owner.Items [0].Bounds.Height + ThemeEngine.Current.ListViewVerticalSpacing)  * lines);
1564                                         break;
1565                                 case View.List:
1566                                         owner.Scroll (owner.h_scroll, -owner.Items [0].Bounds.Width * lines);
1567                                         break;
1568                                 }
1569                         }
1570
1571                         internal override void OnPaintInternal (PaintEventArgs pe)
1572                         {
1573                                 ThemeEngine.Current.DrawListViewItems (pe.Graphics, pe.ClipRectangle, owner);
1574                         }
1575
1576                         protected override void WndProc (ref Message m)
1577                         {
1578                                 switch ((Msg)m.Msg) {
1579                                 case Msg.WM_SETFOCUS:
1580                                         owner.Focus ();
1581                                         break;
1582                                 default:
1583                                         base.WndProc (ref m);
1584                                         break;
1585                                 }
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                 public class CheckedIndexCollection : IList, ICollection, IEnumerable
2077                 {
2078                         internal ArrayList list;
2079                         private ListView owner;
2080
2081                         #region Public Constructor
2082                         public CheckedIndexCollection (ListView owner)
2083                         {
2084                                 list = new ArrayList ();
2085                                 this.owner = owner;
2086                         }
2087                         #endregion      // Public Constructor
2088
2089                         #region Public Properties
2090                         [Browsable (false)]
2091                         public int Count {
2092                                 get { return list.Count; }
2093                         }
2094
2095                         public bool IsReadOnly {
2096                                 get { return true; }
2097                         }
2098
2099                         public int this [int index] {
2100                                 get {
2101                                         if (index < 0 || index >= list.Count)
2102                                                 throw new ArgumentOutOfRangeException ("index");
2103                                         return (int) list [index];
2104                                 }
2105                         }
2106
2107                         bool ICollection.IsSynchronized {
2108                                 get { return false; }
2109                         }
2110
2111                         object ICollection.SyncRoot {
2112                                 get { return this; }
2113                         }
2114
2115                         bool IList.IsFixedSize {
2116                                 get { return true; }
2117                         }
2118
2119                         object IList.this [int index] {
2120                                 get { return this [index]; }
2121                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
2122                         }
2123                         #endregion      // Public Properties
2124
2125                         #region Public Methods
2126                         public bool Contains (int checkedIndex)
2127                         {
2128                                 return list.Contains (checkedIndex);
2129                         }
2130
2131                         public IEnumerator GetEnumerator ()
2132                         {
2133                                 return list.GetEnumerator ();
2134                         }
2135
2136                         void ICollection.CopyTo (Array dest, int index)
2137                         {
2138                                 list.CopyTo (dest, index);
2139                         }
2140
2141                         int IList.Add (object value)
2142                         {
2143                                 throw new NotSupportedException ("Add operation is not supported.");
2144                         }
2145
2146                         void IList.Clear ()
2147                         {
2148                                 throw new NotSupportedException ("Clear operation is not supported.");
2149                         }
2150
2151                         bool IList.Contains (object checkedIndex)
2152                         {
2153                                 return list.Contains (checkedIndex);
2154                         }
2155
2156                         int IList.IndexOf (object checkedIndex)
2157                         {
2158                                 return list.IndexOf (checkedIndex);
2159                         }
2160
2161                         void IList.Insert (int index, object value)
2162                         {
2163                                 throw new NotSupportedException ("Insert operation is not supported.");
2164                         }
2165
2166                         void IList.Remove (object value)
2167                         {
2168                                 throw new NotSupportedException ("Remove operation is not supported.");
2169                         }
2170
2171                         void IList.RemoveAt (int index)
2172                         {
2173                                 throw new NotSupportedException ("RemoveAt operation is not supported.");
2174                         }
2175
2176                         public int IndexOf (int checkedIndex)
2177                         {
2178                                 return list.IndexOf (checkedIndex);
2179                         }
2180                         #endregion      // Public Methods
2181
2182                 }       // CheckedIndexCollection
2183
2184                 public class CheckedListViewItemCollection : IList, ICollection, IEnumerable
2185                 {
2186                         internal ArrayList list;
2187                         private ListView owner;
2188
2189                         #region Public Constructor
2190                         public CheckedListViewItemCollection (ListView owner)
2191                         {
2192                                 list = new ArrayList ();
2193                                 this.owner = owner;
2194                         }
2195                         #endregion      // Public Constructor
2196
2197                         #region Public Properties
2198                         [Browsable (false)]
2199                         public int Count {
2200                                 get { return list.Count; }
2201                         }
2202
2203                         public bool IsReadOnly {
2204                                 get { return true; }
2205                         }
2206
2207                         public ListViewItem this [int index] {
2208                                 get {
2209                                         if (index < 0 || index >= list.Count)
2210                                                 throw new ArgumentOutOfRangeException ("index");
2211                                         return (ListViewItem) list [index];
2212                                 }
2213                         }
2214
2215                         bool ICollection.IsSynchronized {
2216                                 get { return list.IsSynchronized; }
2217                         }
2218
2219                         object ICollection.SyncRoot {
2220                                 get { return this; }
2221                         }
2222
2223                         bool IList.IsFixedSize {
2224                                 get { return true; }
2225                         }
2226
2227                         object IList.this [int index] {
2228                                 get { return this [index]; }
2229                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
2230                         }
2231                         #endregion      // Public Properties
2232
2233                         #region Public Methods
2234                         public bool Contains (ListViewItem item)
2235                         {
2236                                 return list.Contains (item);
2237                         }
2238
2239                         public void CopyTo (Array dest, int index)
2240                         {
2241                                 list.CopyTo (dest, index);
2242                         }
2243
2244                         public IEnumerator GetEnumerator ()
2245                         {
2246                                 return list.GetEnumerator ();
2247                         }
2248
2249                         int IList.Add (object value)
2250                         {
2251                                 throw new NotSupportedException ("Add operation is not supported.");
2252                         }
2253
2254                         void IList.Clear ()
2255                         {
2256                                 throw new NotSupportedException ("Clear operation is not supported.");
2257                         }
2258
2259                         bool IList.Contains (object item)
2260                         {
2261                                 return list.Contains (item);
2262                         }
2263
2264                         int IList.IndexOf (object item)
2265                         {
2266                                 return list.IndexOf (item);
2267                         }
2268
2269                         void IList.Insert (int index, object value)
2270                         {
2271                                 throw new NotSupportedException ("Insert operation is not supported.");
2272                         }
2273
2274                         void IList.Remove (object value)
2275                         {
2276                                 throw new NotSupportedException ("Remove operation is not supported.");
2277                         }
2278
2279                         void IList.RemoveAt (int index)
2280                         {
2281                                 throw new NotSupportedException ("RemoveAt operation is not supported.");
2282                         }
2283
2284                         public int IndexOf (ListViewItem item)
2285                         {
2286                                 return list.IndexOf (item);
2287                         }
2288                         #endregion      // Public Methods
2289
2290                 }       // CheckedListViewItemCollection
2291
2292                 public class ColumnHeaderCollection : IList, ICollection, IEnumerable
2293                 {
2294                         internal ArrayList list;
2295                         private ListView owner;
2296
2297                         #region Public Constructor
2298                         public ColumnHeaderCollection (ListView owner)
2299                         {
2300                                 list = new ArrayList ();
2301                                 this.owner = owner;
2302                         }
2303                         #endregion      // Public Constructor
2304
2305                         #region Public Properties
2306                         [Browsable (false)]
2307                         public int Count {
2308                                 get { return list.Count; }
2309                         }
2310
2311                         public bool IsReadOnly {
2312                                 get { return false; }
2313                         }
2314
2315                         public virtual ColumnHeader this [int index] {
2316                                 get {
2317                                         if (index < 0 || index >= list.Count)
2318                                                 throw new ArgumentOutOfRangeException ("index");
2319                                         return (ColumnHeader) list [index];
2320                                 }
2321                         }
2322
2323                         bool ICollection.IsSynchronized {
2324                                 get { return true; }
2325                         }
2326
2327                         object ICollection.SyncRoot {
2328                                 get { return this; }
2329                         }
2330
2331                         bool IList.IsFixedSize {
2332                                 get { return list.IsFixedSize; }
2333                         }
2334
2335                         object IList.this [int index] {
2336                                 get { return this [index]; }
2337                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
2338                         }
2339                         #endregion      // Public Properties
2340
2341                         #region Public Methods
2342                         public virtual int Add (ColumnHeader value)
2343                         {
2344                                 int idx;
2345                                 value.owner = this.owner;
2346                                 idx = list.Add (value);
2347                                 if (owner.IsHandleCreated) {
2348                                         owner.Redraw (true); 
2349                                 }
2350                                 return idx;
2351                         }
2352
2353                         public virtual ColumnHeader Add (string str, int width, HorizontalAlignment textAlign)
2354                         {
2355                                 ColumnHeader colHeader = new ColumnHeader (this.owner, str, textAlign, width);
2356                                 this.Add (colHeader);                                                                   
2357                                 return colHeader;
2358                         }
2359
2360                         public virtual void AddRange (ColumnHeader [] values)
2361                         {
2362                                 foreach (ColumnHeader colHeader in values) {
2363                                         colHeader.owner = this.owner;
2364                                         Add (colHeader);
2365                                 }
2366                                 
2367                                 owner.Redraw (true); 
2368                         }
2369
2370                         public virtual void Clear ()
2371                         {
2372                                 list.Clear ();
2373                                 owner.Redraw (true);
2374                         }
2375
2376                         public bool Contains (ColumnHeader value)
2377                         {
2378                                 return list.Contains (value);
2379                         }
2380
2381                         public IEnumerator GetEnumerator ()
2382                         {
2383                                 return list.GetEnumerator ();
2384                         }
2385
2386                         void ICollection.CopyTo (Array dest, int index)
2387                         {
2388                                 list.CopyTo (dest, index);
2389                         }
2390
2391                         int IList.Add (object value)
2392                         {
2393                                 if (! (value is ColumnHeader)) {
2394                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
2395                                 }
2396
2397                                 return this.Add ((ColumnHeader) value);
2398                         }
2399
2400                         bool IList.Contains (object value)
2401                         {
2402                                 if (! (value is ColumnHeader)) {
2403                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
2404                                 }
2405
2406                                 return this.Contains ((ColumnHeader) value);
2407                         }
2408
2409                         int IList.IndexOf (object value)
2410                         {
2411                                 if (! (value is ColumnHeader)) {
2412                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
2413                                 }
2414
2415                                 return this.IndexOf ((ColumnHeader) value);
2416                         }
2417
2418                         void IList.Insert (int index, object value)
2419                         {
2420                                 if (! (value is ColumnHeader)) {
2421                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
2422                                 }
2423
2424                                 this.Insert (index, (ColumnHeader) value);
2425                         }
2426
2427                         void IList.Remove (object value)
2428                         {
2429                                 if (! (value is ColumnHeader)) {
2430                                         throw new ArgumentException ("Not of type ColumnHeader", "value");
2431                                 }
2432
2433                                 this.Remove ((ColumnHeader) value);
2434                         }
2435
2436                         public int IndexOf (ColumnHeader value)
2437                         {
2438                                 return list.IndexOf (value);
2439                         }
2440
2441                         public void Insert (int index, ColumnHeader value)
2442                         {
2443                                 // LAMESPEC: MSDOCS say greater than or equal to the value of the Count property
2444                                 // but it's really only greater.
2445                                 if (index < 0 || index > list.Count)
2446                                         throw new ArgumentOutOfRangeException ("index");
2447
2448                                 value.owner = this.owner;
2449                                 list.Insert (index, value);
2450                                 owner.Redraw (true);
2451                         }
2452
2453                         public void Insert (int index, string str, int width, HorizontalAlignment textAlign)
2454                         {
2455                                 ColumnHeader colHeader = new ColumnHeader (this.owner, str, textAlign, width);
2456                                 this.Insert (index, colHeader);
2457                         }
2458
2459                         public virtual void Remove (ColumnHeader column)
2460                         {
2461                                 // TODO: Update Column internal index ?
2462                                 list.Remove (column);
2463                                 owner.Redraw (true);
2464                         }
2465
2466                         public virtual void RemoveAt (int index)
2467                         {
2468                                 if (index < 0 || index >= list.Count)
2469                                         throw new ArgumentOutOfRangeException ("index");
2470
2471                                 // TODO: Update Column internal index ?
2472                                 list.RemoveAt (index);
2473                                 owner.Redraw (true);
2474                         }
2475                         #endregion      // Public Methods
2476                         
2477
2478                 }       // ColumnHeaderCollection
2479
2480                 public class ListViewItemCollection : IList, ICollection, IEnumerable
2481                 {
2482                         internal ArrayList list;
2483                         private ListView owner;
2484
2485                         #region Public Constructor
2486                         public ListViewItemCollection (ListView owner)
2487                         {
2488                                 list = new ArrayList ();
2489                                 this.owner = owner;
2490                         }
2491                         #endregion      // Public Constructor
2492
2493                         #region Public Properties
2494                         [Browsable (false)]
2495                         public int Count {
2496                                 get { return list.Count; }
2497                         }
2498
2499                         public bool IsReadOnly {
2500                                 get { return false; }
2501                         }
2502
2503                         public virtual ListViewItem this [int displayIndex] {
2504                                 get {
2505                                         if (displayIndex < 0 || displayIndex >= list.Count)
2506                                                 throw new ArgumentOutOfRangeException ("displayIndex");
2507                                         return (ListViewItem) list [displayIndex];
2508                                 }
2509
2510                                 set {
2511                                         if (displayIndex < 0 || displayIndex >= list.Count)
2512                                                 throw new ArgumentOutOfRangeException ("displayIndex");
2513
2514                                         if (list.Contains (value))
2515                                                 throw new ArgumentException ("An item cannot be added more than once. To add an item again, you need to clone it.", "value");
2516
2517                                         value.Owner = owner;
2518                                         list [displayIndex] = value;
2519
2520                                         owner.Redraw (true);
2521                                 }
2522                         }
2523
2524                         bool ICollection.IsSynchronized {
2525                                 get { return true; }
2526                         }
2527
2528                         object ICollection.SyncRoot {
2529                                 get { return this; }
2530                         }
2531
2532                         bool IList.IsFixedSize {
2533                                 get { return list.IsFixedSize; }
2534                         }
2535
2536                         object IList.this [int index] {
2537                                 get { return this [index]; }
2538                                 set {
2539                                         if (value is ListViewItem)
2540                                                 this [index] = (ListViewItem) value;
2541                                         else
2542                                                 this [index] = new ListViewItem (value.ToString ());
2543                                 }
2544                         }
2545                         #endregion      // Public Properties
2546
2547                         #region Public Methods
2548                         public virtual ListViewItem Add (ListViewItem value)
2549                         {
2550                                 if (list.Contains (value))
2551                                         throw new ArgumentException ("An item cannot be added more than once. To add an item again, you need to clone it.", "value");
2552
2553                                 value.Owner = owner;
2554                                 list.Add (value);
2555
2556                                 if (owner.Sorting != SortOrder.None)
2557                                         owner.Sort ();
2558
2559                                 owner.Redraw (true);
2560
2561                                 return value;
2562                         }
2563
2564                         public virtual ListViewItem Add (string text)
2565                         {
2566                                 ListViewItem item = new ListViewItem (text);
2567                                 return this.Add (item);
2568                         }
2569
2570                         public virtual ListViewItem Add (string text, int imageIndex)
2571                         {
2572                                 ListViewItem item = new ListViewItem (text, imageIndex);
2573                                 return this.Add (item);
2574                         }
2575
2576                         public void AddRange (ListViewItem [] values)
2577                         {
2578                                 list.Clear ();
2579                                 owner.SelectedItems.list.Clear ();
2580                                 owner.SelectedIndices.list.Clear ();
2581                                 owner.CheckedItems.list.Clear ();
2582                                 owner.CheckedIndices.list.Clear ();
2583
2584                                 foreach (ListViewItem item in values) {
2585                                         item.Owner = owner;
2586                                         list.Add (item);
2587                                 }
2588
2589                                 if (owner.Sorting != SortOrder.None)
2590                                         owner.Sort ();
2591
2592                                 owner.Redraw (true);
2593                         }
2594
2595                         public virtual void Clear ()
2596                         {
2597                                 owner.SetFocusedItem (null);
2598                                 owner.h_scroll.Value = owner.v_scroll.Value = 0;
2599                                 list.Clear ();
2600                                 owner.SelectedItems.list.Clear ();
2601                                 owner.SelectedIndices.list.Clear ();
2602                                 owner.CheckedItems.list.Clear ();
2603                                 owner.CheckedIndices.list.Clear ();
2604                                 owner.Redraw (true);
2605                         }
2606
2607                         public bool Contains (ListViewItem item)
2608                         {
2609                                 return list.Contains (item);
2610                         }
2611
2612                         public void CopyTo (Array dest, int index)
2613                         {
2614                                 list.CopyTo (dest, index);
2615                         }
2616
2617                         public IEnumerator GetEnumerator ()
2618                         {
2619                                 return list.GetEnumerator ();
2620                         }
2621
2622                         int IList.Add (object item)
2623                         {
2624                                 int result;
2625                                 ListViewItem li;
2626
2627                                 if (item is ListViewItem) {
2628                                         li = (ListViewItem) item;
2629                                         if (list.Contains (li))
2630                                                 throw new ArgumentException ("An item cannot be added more than once. To add an item again, you need to clone it.", "item");
2631                                 }
2632                                 else
2633                                         li = new ListViewItem (item.ToString ());
2634
2635                                 li.Owner = owner;
2636                                 result = list.Add (li);
2637                                 owner.Redraw (true);
2638
2639                                 return result;
2640                         }
2641
2642                         bool IList.Contains (object item)
2643                         {
2644                                 return list.Contains (item);
2645                         }
2646
2647                         int IList.IndexOf (object item)
2648                         {
2649                                 return list.IndexOf (item);
2650                         }
2651
2652                         void IList.Insert (int index, object item)
2653                         {
2654                                 if (item is ListViewItem)
2655                                         this.Insert (index, (ListViewItem) item);
2656                                 else
2657                                         this.Insert (index, item.ToString ());
2658                         }
2659
2660                         void IList.Remove (object item)
2661                         {
2662                                 Remove ((ListViewItem) item);
2663                         }
2664
2665                         public int IndexOf (ListViewItem item)
2666                         {
2667                                 return list.IndexOf (item);
2668                         }
2669
2670                         public ListViewItem Insert (int index, ListViewItem item)
2671                         {
2672                                 // LAMESPEC: MSDOCS say greater than or equal to the value of the Count property
2673                                 // but it's really only greater.
2674                                 if (index < 0 || index > list.Count)
2675                                         throw new ArgumentOutOfRangeException ("index");
2676
2677                                 if (list.Contains (item))
2678                                         throw new ArgumentException ("An item cannot be added more than once. To add an item again, you need to clone it.", "item");
2679
2680                                 item.Owner = owner;
2681                                 list.Insert (index, item);
2682                                 owner.Redraw (true);
2683                                 return item;
2684                         }
2685
2686                         public ListViewItem Insert (int index, string text)
2687                         {
2688                                 return this.Insert (index, new ListViewItem (text));
2689                         }
2690
2691                         public ListViewItem Insert (int index, string text, int imageIndex)
2692                         {
2693                                 return this.Insert (index, new ListViewItem (text, imageIndex));
2694                         }
2695
2696                         public virtual void Remove (ListViewItem item)
2697                         {
2698                                 if (!list.Contains (item))
2699                                         return;
2700                                         
2701                                 owner.SelectedItems.list.Remove (item);
2702                                 owner.SelectedIndices.list.Remove (item.Index);
2703                                 owner.CheckedItems.list.Remove (item);
2704                                 owner.CheckedIndices.list.Remove (item.Index);
2705                                 list.Remove (item);
2706                                 owner.Redraw (true);                            
2707                         }
2708
2709                         public virtual void RemoveAt (int index)
2710                         {
2711                                 if (index < 0 || index >= list.Count)
2712                                         throw new ArgumentOutOfRangeException ("index");
2713
2714                                 list.RemoveAt (index);
2715                                 owner.SelectedItems.list.RemoveAt (index);
2716                                 owner.SelectedIndices.list.RemoveAt (index);
2717                                 owner.CheckedItems.list.RemoveAt (index);
2718                                 owner.CheckedIndices.list.RemoveAt (index);
2719                                 owner.Redraw (false);
2720                         }
2721                         #endregion      // Public Methods
2722
2723                 }       // ListViewItemCollection
2724
2725                 public class SelectedIndexCollection : IList, ICollection, IEnumerable
2726                 {
2727                         internal ArrayList list;
2728                         private ListView owner;
2729
2730                         #region Public Constructor
2731                         public SelectedIndexCollection (ListView owner)
2732                         {
2733                                 list = new ArrayList ();
2734                                 this.owner = owner;
2735                         }
2736                         #endregion      // Public Constructor
2737
2738                         #region Public Properties
2739                         [Browsable (false)]
2740                         public int Count {
2741                                 get { return list.Count; }
2742                         }
2743
2744                         public bool IsReadOnly {
2745                                 get { return true; }
2746                         }
2747
2748                         public int this [int index] {
2749                                 get {
2750                                         if (index < 0 || index >= list.Count)
2751                                                 throw new ArgumentOutOfRangeException ("index");
2752                                         return (int) list [index];
2753                                 }
2754                         }
2755
2756                         bool ICollection.IsSynchronized {
2757                                 get { return list.IsSynchronized; }
2758                         }
2759
2760                         object ICollection.SyncRoot {
2761                                 get { return this; }
2762                         }
2763
2764                         bool IList.IsFixedSize {
2765                                 get { return true; }
2766                         }
2767
2768                         object IList.this [int index] {
2769                                 get { return this [index]; }
2770                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
2771                         }
2772                         #endregion      // Public Properties
2773
2774                         #region Public Methods
2775                         public bool Contains (int selectedIndex)
2776                         {
2777                                 return list.Contains (selectedIndex);
2778                         }
2779
2780                         public void CopyTo (Array dest, int index)
2781                         {
2782                                 list.CopyTo (dest, index);
2783                         }
2784
2785                         public IEnumerator GetEnumerator ()
2786                         {
2787                                 return list.GetEnumerator ();
2788                         }
2789
2790                         int IList.Add (object value)
2791                         {
2792                                 throw new NotSupportedException ("Add operation is not supported.");
2793                         }
2794
2795                         void IList.Clear ()
2796                         {
2797                                 throw new NotSupportedException ("Clear operation is not supported.");
2798                         }
2799
2800                         bool IList.Contains (object selectedIndex)
2801                         {
2802                                 return list.Contains (selectedIndex);
2803                         }
2804
2805                         int IList.IndexOf (object selectedIndex)
2806                         {
2807                                 return list.IndexOf (selectedIndex);
2808                         }
2809
2810                         void IList.Insert (int index, object value)
2811                         {
2812                                 throw new NotSupportedException ("Insert operation is not supported.");
2813                         }
2814
2815                         void IList.Remove (object value)
2816                         {
2817                                 throw new NotSupportedException ("Remove operation is not supported.");
2818                         }
2819
2820                         void IList.RemoveAt (int index)
2821                         {
2822                                 throw new NotSupportedException ("RemoveAt operation is not supported.");
2823                         }
2824
2825                         public int IndexOf (int selectedIndex)
2826                         {
2827                                 return list.IndexOf (selectedIndex);
2828                         }
2829                         #endregion      // Public Methods
2830
2831                 }       // SelectedIndexCollection
2832
2833                 public class SelectedListViewItemCollection : IList, ICollection, IEnumerable
2834                 {
2835                         internal ArrayList list;
2836                         private ListView owner;
2837
2838                         #region Public Constructor
2839                         public SelectedListViewItemCollection (ListView owner)
2840                         {
2841                                 list = new ArrayList ();
2842                                 this.owner = owner;
2843                         }
2844                         #endregion      // Public Constructor
2845
2846                         #region Public Properties
2847                         [Browsable (false)]
2848                         public int Count {
2849                                 get { return list.Count; }
2850                         }
2851
2852                         public bool IsReadOnly {
2853                                 get { return true; }
2854                         }
2855
2856                         public ListViewItem this [int index] {
2857                                 get {
2858                                         if (index < 0 || index >= list.Count)
2859                                                 throw new ArgumentOutOfRangeException ("index");
2860                                         return (ListViewItem) list [index];
2861                                 }
2862                         }
2863
2864                         bool ICollection.IsSynchronized {
2865                                 get { return list.IsSynchronized; }
2866                         }
2867
2868                         object ICollection.SyncRoot {
2869                                 get { return this; }
2870                         }
2871
2872                         bool IList.IsFixedSize {
2873                                 get { return true; }
2874                         }
2875
2876                         object IList.this [int index] {
2877                                 get { return this [index]; }
2878                                 set { throw new NotSupportedException ("SetItem operation is not supported."); }
2879                         }
2880                         #endregion      // Public Properties
2881
2882                         #region Public Methods
2883                         public void Clear ()
2884                         {
2885                                 ArrayList copy = (ArrayList) list.Clone ();
2886                                 for (int i = 0; i < copy.Count; i++)
2887                                         ((ListViewItem) copy [i]).Selected = false;
2888
2889                                 list.Clear ();
2890                         }
2891
2892                         public bool Contains (ListViewItem item)
2893                         {
2894                                 return list.Contains (item);
2895                         }
2896
2897                         public void CopyTo (Array dest, int index)
2898                         {
2899                                 list.CopyTo (dest, index);
2900                         }
2901
2902                         public IEnumerator GetEnumerator ()
2903                         {
2904                                 return list.GetEnumerator ();
2905                         }
2906
2907                         int IList.Add (object value)
2908                         {
2909                                 throw new NotSupportedException ("Add operation is not supported.");
2910                         }
2911
2912                         bool IList.Contains (object item)
2913                         {
2914                                 return list.Contains (item);
2915                         }
2916
2917                         int IList.IndexOf (object item)
2918                         {
2919                                 return list.IndexOf (item);
2920                         }
2921
2922                         void IList.Insert (int index, object value)
2923                         {
2924                                 throw new NotSupportedException ("Insert operation is not supported.");
2925                         }
2926
2927                         void IList.Remove (object value)
2928                         {
2929                                 throw new NotSupportedException ("Remove operation is not supported.");
2930                         }
2931
2932                         void IList.RemoveAt (int index)
2933                         {
2934                                 throw new NotSupportedException ("RemoveAt operation is not supported.");
2935                         }
2936
2937                         public int IndexOf (ListViewItem item)
2938                         {
2939                                 return list.IndexOf (item);
2940                         }
2941                         #endregion      // Public Methods
2942
2943                 }       // SelectedListViewItemCollection
2944
2945                 #endregion // Subclasses
2946         }
2947 }