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