mono /mcs/class/Managed.Windows.Forms/System.Windows.Forms/ImageList.cs

Language C# Lines 1073
MD5 Hash e49a5889817b2fa55ebbc091cf80a698 Estimated Cost $21,009 (why?)
Repository https://bitbucket.org/danipen/mono.git View Raw File View Project SPDX
   1
   2
   3
   4
   5
   6
   7
   8
   9
  10
  11
  12
  13
  14
  15
  16
  17
  18
  19
  20
  21
  22
  23
  24
  25
  26
  27
  28
  29
  30
  31
  32
  33
  34
  35
  36
  37
  38
  39
  40
  41
  42
  43
  44
  45
  46
  47
  48
  49
  50
  51
  52
  53
  54
  55
  56
  57
  58
  59
  60
  61
  62
  63
  64
  65
  66
  67
  68
  69
  70
  71
  72
  73
  74
  75
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
//
// System.Windows.Forms.ImageList.cs
//
// Authors:
//   Peter Bartok <pbartok@novell.com>
//   Kornél Pál <http://www.kornelpal.hu/>
//
// Copyright (C) 2004-2005 Novell, Inc.
// Copyright (C) 2005 Kornél Pál
//

//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//

// COMPLETE

//
// Differences between MS.NET ImageList and this implementation:
//
// This is a fully managed image list implementation.
//
// Images are stored as Format32bppArgb internally but ColorDepth is applied
// to the colors of images. Images[index] returns a Format32bppArgb copy of
// the image so this difference is only internal.
//
// MS.NET has no alpha channel support (except for icons in 32-bit mode with
// comctl32.dll version 6.0) but this implementation has full alpha channel
// support in 32-bit mode.
//
// Handle should be an HIMAGELIST returned by ImageList_Create. This
// implementation uses (IntPtr)(-1) that is a non-zero but invalid handle.
//
// MS.NET destroys handles using the garbage collector this implementation
// does the same with Image objects stored in an ArrayList.
//
// MS.NET 1.x shares the same HIMAGELIST between ImageLists that were
// initialized from the same ImageListStreamer and doesn't update ImageSize
// and ColorDepth that are treated as bugs and MS.NET 2.0 behavior is
// implemented.
//
// MS.NET 2.0 does not clear keys when handle is destroyed that is treated as
// a bug.
//

using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Drawing;
using System.Drawing.Design;
using System.Drawing.Imaging;
using System.Globalization;
using System.Runtime.InteropServices;

namespace System.Windows.Forms
{
	[DefaultProperty("Images")]
	[Designer("System.Windows.Forms.Design.ImageListDesigner, " + Consts.AssemblySystem_Design)]
	[DesignerSerializer("System.Windows.Forms.Design.ImageListCodeDomSerializer, " + Consts.AssemblySystem_Design, "System.ComponentModel.Design.Serialization.CodeDomSerializer, " + Consts.AssemblySystem_Design)]
	[ToolboxItemFilter("System.Windows.Forms")]
	[TypeConverter(typeof(ImageListConverter))]
	public sealed class ImageList : System.ComponentModel.Component
	{
		#region Private Fields
		private const ColorDepth DefaultColorDepth = ColorDepth.Depth8Bit;
		private static readonly Size DefaultImageSize = new Size(16, 16);
		private static readonly Color DefaultTransparentColor = Color.Transparent;
		private object tag;
		private readonly ImageCollection images;
		#endregion // Private Fields

		#region Sub-classes
		[Editor("System.Windows.Forms.Design.ImageCollectionEditor, " + Consts.AssemblySystem_Design, typeof(UITypeEditor))]
		public sealed class ImageCollection : IList, ICollection, IEnumerable
		{
			private const int AlphaMask = unchecked((int)0xFF000000);

			private static class IndexedColorDepths
			{
				internal static readonly ColorPalette Palette4Bit;
				internal static readonly ColorPalette Palette8Bit;
				private static readonly int[] squares;

				static IndexedColorDepths()
				{
					Bitmap bitmap;
					int index;

					bitmap = new Bitmap(1, 1, PixelFormat.Format4bppIndexed);
					Palette4Bit = bitmap.Palette;
					bitmap.Dispose();

					bitmap = new Bitmap(1, 1, PixelFormat.Format8bppIndexed);
					Palette8Bit = bitmap.Palette;
					bitmap.Dispose();

					squares = new int[511];
					for (index = 0; index < 256; index++)
						squares[255 + index] = squares[255 - index] = index * index;
				}

				internal static int GetNearestColor(Color[] palette, int color)
				{
					int index;
					int count;
					int red;
					int green;
					int blue;
					int nearestColor;
					int minDistance;
					int distance;

					count = palette.Length;
					for (index = 0; index < count; index++)
						if (palette[index].ToArgb() == color)
							return color;

					red = unchecked((int)(unchecked((uint)color) >> 16) & 0xFF);
					green = unchecked((int)(unchecked((uint)color) >> 8) & 0xFF);
					blue = color & 0xFF;
					nearestColor = AlphaMask;
					minDistance = int.MaxValue;

					for (index = 0; index < count; index++)
						if ((distance = squares[255 + palette[index].R - red] + squares[255 + palette[index].G - green] + squares[255 + palette[index].B - blue]) < minDistance) {
							nearestColor = palette[index].ToArgb();
							minDistance = distance;
						}

					return nearestColor;
				}
			}

			[Flags()]
			private enum ItemFlags
			{
				None = 0,
				UseTransparentColor = 1,
				ImageStrip = 2
			}

			private sealed class ImageListItem
			{
				internal readonly object Image;
				internal readonly ItemFlags Flags;
				internal readonly Color TransparentColor;
				internal readonly int ImageCount = 1;

				internal ImageListItem(Icon value)
				{
					if (value == null)
						throw new ArgumentNullException("value");

					// Icons are cloned.
					this.Image = (Icon)value.Clone();
				}

				internal ImageListItem(Image value)
				{
					if (value == null)
						throw new ArgumentNullException("value");

					if (!(value is Bitmap))
						throw new ArgumentException("Image must be a Bitmap.");

					// Images are not cloned.
					this.Image = value;
				}

				internal ImageListItem(Image value, Color transparentColor) : this(value)
				{
					this.Flags = ItemFlags.UseTransparentColor;
					this.TransparentColor = transparentColor;
				}

				internal ImageListItem(Image value, int imageCount) : this(value)
				{
					this.Flags = ItemFlags.ImageStrip;
					this.ImageCount = imageCount;
				}
			}

			#region ImageCollection Private Fields
			private ColorDepth colorDepth = DefaultColorDepth;
			private Size imageSize = DefaultImageSize;
			private Color transparentColor = DefaultTransparentColor;
			private ArrayList list = new ArrayList();
			private ArrayList keys = new ArrayList();
			private int count;
			private bool handleCreated;
			private int lastKeyIndex = -1;
			private readonly ImageList owner;
			#endregion // ImageCollection Private Fields

			#region ImageCollection Internal Constructors
			// For use in ImageList
			internal ImageCollection(ImageList owner)
			{
				this.owner = owner;
			}
			#endregion // ImageCollection Internal Constructor

			#region ImageCollection Internal Instance Properties
			// For use in ImageList
			internal ColorDepth ColorDepth {
				get {
					return this.colorDepth;
				}

				set {
					if (!Enum.IsDefined(typeof(ColorDepth), value))
						throw new InvalidEnumArgumentException("value", (int)value, typeof(ColorDepth));

					if (this.colorDepth != value) {
						this.colorDepth = value;
						RecreateHandle();
					}
				}
			}

			// For use in ImageList
			internal IntPtr Handle {
				get {
					CreateHandle();
					return (IntPtr)(-1);
				}
			}

			// For use in ImageList
			internal bool HandleCreated {
				get {
					return this.handleCreated;
				}
			}

			// For use in ImageList
			internal Size ImageSize {
				get {
					return this.imageSize;
				}

				set {
					if (value.Width < 1 || value.Width > 256 || value.Height < 1 || value.Height > 256)
						throw new ArgumentException("ImageSize.Width and Height must be between 1 and 256", "value");

					if (this.imageSize != value) {
						this.imageSize = value;
						RecreateHandle();
					}
				}
			}

			// For use in ImageList
			internal ImageListStreamer ImageStream {
				get {
					return this.Empty ? null : new ImageListStreamer(this);
				}

				set {
					int index;
					Image[] streamImages;

					if (value == null) {
						if (this.handleCreated)
							DestroyHandle();
						else
							this.Clear();
					}
					// Only deserialized ImageListStreamers are used.
					else if ((streamImages = value.Images) != null) {
						this.list = new ArrayList(streamImages.Length);
						this.count = 0;
						this.handleCreated = true;
						this.keys = new ArrayList(streamImages.Length);

						for (index = 0; index < streamImages.Length; index++) {
							list.Add((Image)streamImages[index].Clone());
							keys.Add(null);
						}

						// Invalid ColorDepth values are ignored.
						if (Enum.IsDefined(typeof(ColorDepth), value.ColorDepth))
							this.colorDepth = (ColorDepth)value.ColorDepth;
						this.imageSize = value.ImageSize;

						// Event is raised even when handle was not created yet.
						owner.OnRecreateHandle();
					}
				}
			}

			// For use in ImageList
			internal Color TransparentColor {
				get {
					return this.transparentColor;
				}

				set {
					this.transparentColor = value;
				}
			}
			#endregion // ImageCollection Internal Instance Properties

			#region ImageCollection Public Instance Properties
			[Browsable(false)]
			public int Count {
				get {
					return this.handleCreated ? list.Count : this.count;
				}
			}

			public bool Empty {
				get {
					return this.Count == 0;
				}
			}

			public bool IsReadOnly {
				get {
					return false;
				}
			}

			[Browsable(false)]
			[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
			public Image this[int index] {
				get {
					return (Image)GetImage(index).Clone();
				}

				set {
					Image image;

					if (index < 0 || index >= this.Count)
						throw new ArgumentOutOfRangeException("index");

					if (value == null)
						throw new ArgumentNullException("value");

					if (!(value is Bitmap))
						throw new ArgumentException("Image must be a Bitmap.");

					image = CreateImage(value, this.transparentColor);
					CreateHandle();
					list[index] = image;
				}
			}

			public Image this[string key] {
				get {
					int index;

					return (index = IndexOfKey(key)) == -1 ? null : this[index];
				}
			}

			public StringCollection Keys {
				get {
					int index;
					string key;
					StringCollection keyCollection;

					// Returns all keys even when there are more keys than
					// images. Null keys are returned as empty strings.

					keyCollection = new StringCollection();
					for (index = 0; index < keys.Count; index++)
						keyCollection.Add(((key = (string)keys[index]) == null || key.Length == 0) ? string.Empty : key);

					return keyCollection;
				}
			}
			#endregion // ImageCollection Public Instance Properties

			#region ImageCollection Private Static Methods
			private static bool CompareKeys(string key1, string key2)
			{
				// Keys are case-insensitive and keys with different length
				// are not equal even when string.Compare treats them equal.

				if (key1 == null || key2 == null || key1.Length != key2.Length)
					return false;

				return string.Compare(key1, key2, true, CultureInfo.InvariantCulture) == 0;
			}
			#endregion // ImageCollection Private Static Methods

			#region ImageCollection Private Instance Methods
			private int AddItem(string key, ImageListItem item)
			{
				int itemIndex;
				int index;

				if (this.handleCreated)
					itemIndex = AddItemInternal(item);
				else {
					// Image strips are counted as a single item in the return
					// value of Add and AddStrip until handle is created.

					itemIndex = list.Add(item);
					this.count += item.ImageCount;
				}

				if ((item.Flags & ItemFlags.ImageStrip) == 0)
					keys.Add(key);
				else
					for (index = 0; index < item.ImageCount; index++)
						keys.Add(null);

				return itemIndex;
			}

			internal event EventHandler Changed;

			private int AddItemInternal(ImageListItem item)
			{
				if (Changed != null)
					Changed (this, EventArgs.Empty);

				if (item.Image is Icon) {
					int imageWidth;
					int imageHeight;
					Bitmap bitmap;
					Graphics graphics;

					bitmap = new Bitmap(imageWidth = this.imageSize.Width, imageHeight = this.imageSize.Height, PixelFormat.Format32bppArgb);
					graphics = Graphics.FromImage(bitmap);
					graphics.DrawIcon((Icon)item.Image, new Rectangle(0, 0, imageWidth, imageHeight));
					graphics.Dispose();

					ReduceColorDepth(bitmap);
					return list.Add(bitmap);
				}
				else if ((item.Flags & ItemFlags.ImageStrip) == 0)
					return list.Add(CreateImage((Image)item.Image, (item.Flags & ItemFlags.UseTransparentColor) == 0 ? this.transparentColor : item.TransparentColor));
				else {
					int imageX;
					int width;
					int imageWidth;
					int imageHeight;
					int index;
					Image image;
					Bitmap bitmap;
					Graphics graphics;
					Rectangle imageRect;
					ImageAttributes imageAttributes;

					// When ImageSize was changed after adding image strips
					// Count will return invalid values based on old ImageSize
					// but when creating handle either ArgumentException will
					// be thrown or image strip will be added according to the
					// new ImageSize. This can result in image count
					// difference that can result in exceptions in methods
					// that use Count before creating handle. In addition this
					// can result in the loss of sync with keys. When doing
					// the same after handle was created there are no problems
					// as handle will be recreated after changing ImageSize
					// that results in the loss of images added previously.

					if ((width = (image = (Image)item.Image).Width) == 0 || (width % (imageWidth = this.imageSize.Width)) != 0)
						throw new ArgumentException("Width of image strip must be a positive multiple of ImageSize.Width.", "value");

					if (image.Height != (imageHeight = this.imageSize.Height))
						throw new ArgumentException("Height of image strip must be equal to ImageSize.Height.", "value");

					imageRect = new Rectangle(0, 0, imageWidth, imageHeight);
					if (this.transparentColor.A == 0)
						imageAttributes = null;
					else {
						imageAttributes = new ImageAttributes();
						imageAttributes.SetColorKey(this.transparentColor, this.transparentColor);
					}

					index = list.Count;
					for (imageX = 0; imageX < width; imageX += imageWidth) {
						bitmap = new Bitmap(imageWidth, imageHeight, PixelFormat.Format32bppArgb);
						graphics = Graphics.FromImage(bitmap);
						graphics.DrawImage(image, imageRect, imageX, 0, imageWidth, imageHeight, GraphicsUnit.Pixel, imageAttributes);
						graphics.Dispose();

						ReduceColorDepth(bitmap);
						list.Add(bitmap);
					}

					if (imageAttributes != null)
						imageAttributes.Dispose();

					return index;
				}
			}

			private void CreateHandle()
			{
				int index;
				ArrayList items;

				if (!this.handleCreated) {
					items = this.list;
					this.list = new ArrayList(this.count);
					this.count = 0;
					this.handleCreated = true;

					for (index = 0; index < items.Count; index++)
						AddItemInternal((ImageListItem)items[index]);
				}
			}

			private Image CreateImage(Image value, Color transparentColor)
			{
				int imageWidth;
				int imageHeight;
				ImageAttributes imageAttributes;

				if (transparentColor.A == 0)
					imageAttributes = null;
				else {
					imageAttributes = new ImageAttributes();
					imageAttributes.SetColorKey (transparentColor, transparentColor);
				}

				var bitmap = new Bitmap (imageWidth = this.imageSize.Width, imageHeight = this.imageSize.Height, PixelFormat.Format32bppArgb);
				using (var graphics = Graphics.FromImage (bitmap))
					graphics.DrawImage (value, new Rectangle(0, 0, imageWidth, imageHeight), 0, 0, value.Width, value.Height, GraphicsUnit.Pixel, imageAttributes);

				if (imageAttributes != null)
					imageAttributes.Dispose ();

				ReduceColorDepth (bitmap);
				return bitmap;
			}

			private void RecreateHandle()
			{
				if (this.handleCreated) {
					DestroyHandle();
					this.handleCreated = true;
					owner.OnRecreateHandle();
				}
			}

			private unsafe void ReduceColorDepth(Bitmap bitmap)
			{
				byte* pixelPtr;
				byte* lineEndPtr;
				byte* linePtr;
				int line;
				int pixel;
				int height;
				int widthBytes;
				int stride;
				BitmapData bitmapData;
				Color[] palette;

				if (this.colorDepth < ColorDepth.Depth32Bit) {
					bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
					try {
						linePtr = (byte*)bitmapData.Scan0;
						height = bitmapData.Height;
						widthBytes = bitmapData.Width << 2;
						stride = bitmapData.Stride;

						if (this.colorDepth < ColorDepth.Depth16Bit) {
							palette = (this.colorDepth < ColorDepth.Depth8Bit ? IndexedColorDepths.Palette4Bit : IndexedColorDepths.Palette8Bit).Entries;

							for (line = 0; line < height; line++) {
								lineEndPtr = linePtr + widthBytes;
								for (pixelPtr = linePtr; pixelPtr < lineEndPtr; pixelPtr += 4)
									*(int*)pixelPtr = ((pixel = *(int*)pixelPtr) & AlphaMask) == 0 ? 0x00000000 : IndexedColorDepths.GetNearestColor(palette, pixel | AlphaMask);
								linePtr += stride;
							}
						}
						else if (this.colorDepth < ColorDepth.Depth24Bit) {
							for (line = 0; line < height; line++) {
								lineEndPtr = linePtr + widthBytes;
								for (pixelPtr = linePtr; pixelPtr < lineEndPtr; pixelPtr += 4)
									*(int*)pixelPtr = ((pixel = *(int*)pixelPtr) & AlphaMask) == 0 ? 0x00000000 : (pixel & 0x00F8F8F8) | AlphaMask;
								linePtr += stride;
							}
						}
						else {
							for (line = 0; line < height; line++) {
								lineEndPtr = linePtr + widthBytes;
								for (pixelPtr = linePtr; pixelPtr < lineEndPtr; pixelPtr += 4)
									*(int*)pixelPtr = ((pixel = *(int*)pixelPtr) & AlphaMask) == 0 ? 0x00000000 : pixel | AlphaMask;
								linePtr += stride;
							}
						}
					}
					finally {
						bitmap.UnlockBits(bitmapData);
					}
				}
			}
			#endregion // ImageCollection Private Instance Methods

			#region ImageCollection Internal Instance Methods
			// For use in ImageList
			internal void DestroyHandle()
			{
				if (this.handleCreated) {
					this.list = new ArrayList();
					this.count = 0;
					this.handleCreated = false;
					keys = new ArrayList();
				}
			}

			// For use in ImageList
			internal Image GetImage(int index)
			{
				if (index < 0 || index >= this.Count)
					throw new ArgumentOutOfRangeException("index");

				CreateHandle();
				return (Image)list[index];
			}

			// For use in ImageListStreamer
			internal Image[] ToArray()
			{
				Image[] images;

				// Handle is created even when the list is empty.
				CreateHandle();
				images = new Image[list.Count];
				list.CopyTo(images);
				return images;
			}
			#endregion // ImageCollection Internal Instance Methods

			#region ImageCollection Public Instance Methods
			public void Add(Icon value)
			{
				Add(null, value);
			}

			public void Add(Image value)
			{
				Add(null, value);
			}

			public int Add(Image value, Color transparentColor)
			{
				return AddItem(null, new ImageListItem(value, transparentColor));
			}

			public void Add(string key, Icon icon)
			{
				// Argument has name icon but exceptions use name value.
				AddItem(key, new ImageListItem(icon));
			}

			public void Add(string key, Image image)
			{
				// Argument has name image but exceptions use name value.
				AddItem(key, new ImageListItem(image));
			}

			public void AddRange(Image[] images)
			{
				int index;

				if (images == null)
					throw new ArgumentNullException("images");

				for (index = 0; index < images.Length; index++)
					Add(images[index]);
			}

			public int AddStrip(Image value)
			{
				int width;
				int imageWidth;

				if (value == null)
					throw new ArgumentNullException("value");

				if ((width = value.Width) == 0 || (width % (imageWidth = this.imageSize.Width)) != 0)
					throw new ArgumentException("Width of image strip must be a positive multiple of ImageSize.Width.", "value");

				if (value.Height != this.imageSize.Height)
					throw new ArgumentException("Height of image strip must be equal to ImageSize.Height.", "value");

				return AddItem(null, new ImageListItem(value, width / imageWidth));
			}

			public void Clear()
			{
				list.Clear();
				if (!this.handleCreated)
					this.count = 0;
				keys.Clear();
			}

			[EditorBrowsable(EditorBrowsableState.Never)]
			public bool Contains(Image image)
			{
				throw new NotSupportedException();
			}

			public bool ContainsKey(string key)
			{
				return IndexOfKey(key) != -1;
			}

			public IEnumerator GetEnumerator()
			{
				Image[] images = new Image[this.Count];
				int index;

				if (images.Length != 0) {
					// Handle is created only when there are images.
					CreateHandle();

					for (index = 0; index < images.Length; index++)
						images[index] = (Image)((Image)list[index]).Clone();
				}

				return images.GetEnumerator();
			}

			[EditorBrowsable(EditorBrowsableState.Never)]
			public int IndexOf(Image image)
			{
				throw new NotSupportedException();
			}

			public int IndexOfKey(string key)
			{
				int index;

				if (key != null && key.Length != 0) {
					// When last IndexOfKey was successful and the same key was
					// assigned to an image with a lower index than the last
					// result and the key of the last result equals to key
					// argument the last result is returned.

					if (this.lastKeyIndex >= 0 && this.lastKeyIndex < this.Count && CompareKeys((string)keys[this.lastKeyIndex], key))
						return this.lastKeyIndex;

					// Duplicate keys are allowed and first match is returned.
					for (index = 0; index < this.Count; index++)
						if (CompareKeys((string)keys[index], key))
							return this.lastKeyIndex = index;
				}

				return this.lastKeyIndex = -1;
			}

			[EditorBrowsable(EditorBrowsableState.Never)]
			public void Remove(Image image)
			{
				throw new NotSupportedException();
			}

			public void RemoveAt(int index)
			{
				if (index < 0 || index >= this.Count)
					throw new ArgumentOutOfRangeException("index");

				CreateHandle();
				list.RemoveAt(index);
				keys.RemoveAt(index);
				if (Changed != null)
					Changed (this, EventArgs.Empty);
			}

			public void RemoveByKey(string key)
			{
				int index;

				if ((index = IndexOfKey(key)) != -1)
					RemoveAt(index);
			}

			public void SetKeyName(int index, string name)
			{
				// Only SetKeyName throws IndexOutOfRangeException.
				if (index < 0 || index >= this.Count)
					throw new IndexOutOfRangeException();

				keys[index] = name;
			}
			#endregion // ImageCollection Public Instance Methods

			#region ImageCollection Interface Properties
			object IList.this[int index] {
				get {
					return this[index];
				}

				set {
					if (!(value is Image))
						throw new ArgumentException("value");

					this[index] = (Image)value;
				}
			}

			bool IList.IsFixedSize {
				get {
					return false;
				}
			}

			bool ICollection.IsSynchronized {
				get {
					return false;
				}
			}

			object ICollection.SyncRoot {
				get {
					return this;
				}
			}
			#endregion // ImageCollection Interface Properties

			#region ImageCollection Interface Methods
			int IList.Add(object value)
			{
				int index;

				if (!(value is Image))
					throw new ArgumentException("value");

				index = this.Count;
				this.Add((Image)value);
				return index;
			}

			bool IList.Contains(object image)
			{
				return image is Image ? this.Contains ((Image) image) : false;
			}

			int IList.IndexOf (object image)
			{
				return image is Image ? this.IndexOf ((Image) image) : -1;
			}

			void IList.Insert(int index, object value)
			{
				throw new NotSupportedException();
			}

			void IList.Remove (object image)
			{
				if (image is Image)
					this.Remove ((Image) image);
			}

			void ICollection.CopyTo(Array dest, int index)
			{
				for (int imageIndex = 0; imageIndex < this.Count; imageIndex++)
					dest.SetValue (this[imageIndex], index++);
			}
			#endregion // ImageCollection Interface Methods
		}
		#endregion // Sub-classes

		#region Public Constructors
		public ImageList()
		{
			images = new ImageCollection(this);
		}

		public ImageList(System.ComponentModel.IContainer container) : this()
		{
			container.Add(this);
		}
		#endregion // Public Constructors

		#region Private Instance Methods
		private void OnRecreateHandle()
		{
			EventHandler eh = (EventHandler)(Events [RecreateHandleEvent]);
			if (eh != null)
				eh (this, EventArgs.Empty);
		}

		// MS's TypeDescriptor stuff apparently uses
		// non-public ShouldSerialize* methods, because it
		// picks up this behavior even though the methods
		// aren't public.  we can't make them private, though,
		// without adding compiler warnings.  so, make then
		// internal instead.

		internal bool ShouldSerializeTransparentColor ()
		{
			return this.TransparentColor != Color.LightGray;
		}

		internal bool ShouldSerializeColorDepth()
		{
			// ColorDepth is serialized in ImageStream when non-empty.
			// It is serialized even if it has its default value when empty.
			return images.Empty;
		}               

		internal bool ShouldSerializeImageSize()
		{
			// ImageSize is serialized in ImageStream when non-empty.
			// It is serialized even if it has its default value when empty.
			return images.Empty;
		}

		internal void ResetColorDepth ()
		{
			this.ColorDepth = DefaultColorDepth;
		}

		internal void ResetImageSize ()
		{
			this.ImageSize = DefaultImageSize;
		}

		internal void ResetTransparentColor ()
		{
			this.TransparentColor = Color.LightGray;
		}
		#endregion // Private Instance Methods

		#region Public Instance Properties
		public ColorDepth ColorDepth {
			get {
				return images.ColorDepth;
			}

			set {
				images.ColorDepth = value;
			}
		}

		[Browsable(false)]
		[EditorBrowsable(EditorBrowsableState.Advanced)]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public IntPtr Handle {
			get {
				return images.Handle;
			}
		}

		[Browsable(false)]
		[EditorBrowsable(EditorBrowsableState.Advanced)]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public bool HandleCreated {
			get {
				return images.HandleCreated;
			}
		}

		[DefaultValue(null)]
		[MergableProperty(false)]
		[DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
		public ImageCollection Images {
			get {
				return this.images;
			}
		}

		[Localizable(true)]
		public Size ImageSize {
			get {
				return images.ImageSize;
			}

			set {
				images.ImageSize = value;
			}
		}

		[Browsable(false)]
		[DefaultValue(null)]
		[EditorBrowsable(EditorBrowsableState.Advanced)]
		public ImageListStreamer ImageStream {
			get {
				return images.ImageStream;
			}

			set {
				images.ImageStream = value;
			}
		}

		[Bindable(true)]
		[DefaultValue(null)]
		[Localizable(false)]
		[TypeConverter(typeof(StringConverter))]
		public object Tag {
			get {
				return this.tag;
			}

			set {
				this.tag = value;
			}
		}

		public Color TransparentColor {
			get {
				return images.TransparentColor;
			}

			set {
				images.TransparentColor = value;
			}
		}
		#endregion // Public Instance Properties

		#region Public Instance Methods
		public void Draw(Graphics g, Point pt, int index)
		{
			this.Draw(g, pt.X, pt.Y, index);
		}

		public void Draw(Graphics g, int x, int y, int index)
		{
			g.DrawImage(images.GetImage(index), x, y);
		}

		public void Draw(Graphics g, int x, int y, int width, int height, int index)
		{
			g.DrawImage(images.GetImage(index), x, y, width, height);
		}

		public override string ToString()
		{
			return base.ToString() + " Images.Count: " + images.Count.ToString() + ", ImageSize: " + this.ImageSize.ToString();
		}
		#endregion // Public Instance Methods

		#region Protected Instance Methods
		protected override void Dispose(bool disposing)
		{
			if (disposing)
				images.DestroyHandle();

			base.Dispose(disposing);
		}
		#endregion // Protected Instance Methods

		#region Events
		static object RecreateHandleEvent = new object ();

		[Browsable(false)]
		[EditorBrowsable(EditorBrowsableState.Advanced)]
		public event EventHandler RecreateHandle {
			add { Events.AddHandler (RecreateHandleEvent, value); }
			remove { Events.RemoveHandler (RecreateHandleEvent, value); }
		}
		#endregion // Events
	}
}
Back to Top