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:
9 // The above copyright notice and this permission notice shall be
10 // included in all copies or substantial portions of the Software.
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.
20 // Copyright (c) 2004 Novell, Inc.
23 // Peter Bartok pbartok@novell.com
32 using System.ComponentModel;
33 using System.Runtime.InteropServices;
34 using System.Runtime.Serialization;
36 namespace System.Windows.Forms {
37 [Editor("System.Drawing.Design.CursorEditor, " + Consts.AssemblySystem_Drawing_Design, typeof(System.Drawing.Design.UITypeEditor))]
39 [TypeConverter(typeof(CursorConverter))]
40 public sealed class Cursor : IDisposable, ISerializable {
41 #region Internal Structs
42 [StructLayout(LayoutKind.Sequential)]
43 private struct CursorDir {
44 internal ushort idReserved; // Reserved
45 internal ushort idType; // resource type (2 for cursors)
46 internal ushort idCount; // how many cursors
47 internal CursorEntry[] idEntries; // the entries for each cursor
50 [StructLayout(LayoutKind.Sequential)]
51 private struct CursorEntry {
52 internal byte width; // Width of cursor
53 internal byte height; // Height of cursor
54 internal byte colorCount; // colors in cursor
55 internal byte reserved; // Reserved
56 internal ushort xHotspot; // Hotspot X
57 internal ushort yHotspot; // Hotspot Y
58 internal ushort bitCount; // Bits per pixel
59 internal uint sizeInBytes; // size of (CursorInfoHeader + ANDBitmap + ORBitmap)
60 internal uint fileOffset; // position in file
63 [StructLayout(LayoutKind.Sequential)]
64 private struct CursorInfoHeader {
67 internal int biHeight;
68 internal ushort biPlanes;
69 internal ushort biBitCount;
70 internal uint biCompression;
71 internal uint biSizeImage;
72 internal int biXPelsPerMeter;
73 internal int biYPelsPerMeter;
74 internal uint biClrUsed;
75 internal uint biClrImportant;
78 [StructLayout(LayoutKind.Sequential)]
79 private struct CursorImage {
80 internal CursorInfoHeader cursorHeader; // image header
81 internal uint[] cursorColors; // colors table
82 internal byte[] cursorXOR; // bits for XOR mask
83 internal byte[] cursorAND; // bits for AND mask
85 #endregion // Internal structs
87 #region Local Variables
88 private static Cursor current;
89 private CursorDir cursor_dir;
90 private CursorImage[] cursor_data;
93 internal IntPtr handle;
97 private Bitmap cursor;
99 #endregion // Local Variables
101 #region Public Constructors
102 private void CreateCursor(System.IO.Stream stream) {
103 InitFromStream(stream);
104 this.shape = ToBitmap(true, false);
105 this.mask = ToBitmap(false, false);
106 handle = XplatUI.DefineCursor(shape, mask, Color.FromArgb(255, 255, 255), Color.FromArgb(255, 255, 255), cursor_dir.idEntries[id].xHotspot, cursor_dir.idEntries[id].yHotspot);
107 this.shape.Dispose();
112 if (handle != IntPtr.Zero) {
113 this.cursor = ToBitmap(true, true);
124 // This is supposed to take a Win32 handle
125 public Cursor(IntPtr handle) {
126 this.handle = handle;
129 public Cursor(System.IO.Stream stream) {
130 CreateCursor(stream);
133 public Cursor(string fileName) : this (new FileStream (fileName, FileMode.Open)) {
136 public Cursor(Type type, string resource) {
137 using (Stream s = type.Assembly.GetManifestResourceStream (type, resource)) {
139 throw new FileNotFoundException ("Resource name was not found: `" + resource + "'");
144 #endregion // Public Constructors
146 #region Public Static Properties
147 public static Rectangle Clip {
154 XplatUI.GrabInfo(out handle, out confined, out rect);
155 if (handle != IntPtr.Zero) {
159 XplatUI.GetDisplaySize(out size);
162 rect.Width = size.Width;
163 rect.Height = size.Height;
167 [MonoTODO("First need to add ability to set cursor clip rectangle to XplatUI drivers to implement this property")]
173 public static Cursor Current {
179 if (current != value) {
181 XplatUI.OverrideCursor(current.handle);
186 public static Point Position {
191 XplatUI.GetCursorPos (IntPtr.Zero, out x, out y);
192 return new Point (x, y);
196 XplatUI.SetCursorPos(IntPtr.Zero, value.X, value.Y);
199 #endregion // Public Static Properties
201 #region Public Instance Properties
202 public IntPtr Handle {
213 #endregion // Public Instance Properties
215 #region Public Static Methods
216 public static void Hide() {
217 XplatUI.ShowCursor(false);
220 public static void Show() {
221 XplatUI.ShowCursor(false);
224 public static bool operator !=(Cursor left, Cursor right) {
225 if ((object)left == (object)right) {
229 if ((object)left == null || (object)right == null) {
233 if (left.handle == right.handle) {
240 public static bool operator ==(Cursor left, Cursor right) {
241 if ((object)left == (object)right) {
245 if ((object)left == null || (object)right == null) {
249 if (left.handle == right.handle) {
254 #endregion // Public Static Methods
256 #region Public Instance Methods
257 public IntPtr CopyHandle() {
261 public void Dispose() {
262 if (this.cursor != null) {
263 this.cursor.Dispose();
267 if (this.shape != null) {
268 this.shape.Dispose();
272 if (this.mask != null) {
278 public void Draw(Graphics g, Rectangle targetRect) {
279 if (this.cursor != null) {
280 g.DrawImage(this.cursor, targetRect);
284 public void DrawStretched(Graphics g, Rectangle targetRect) {
285 if (this.cursor != null) {
286 g.DrawImage(this.cursor, targetRect, new Rectangle(0, 0, this.cursor.Width, this.cursor.Height), GraphicsUnit.Pixel);
290 public override bool Equals(object obj) {
291 if ( !(obj is Cursor)) {
295 if (((Cursor)obj).handle == this.handle) {
302 public override int GetHashCode() {
303 return base.GetHashCode ();
306 public override string ToString() {
308 return "[Cursor:" + name + "]";
311 throw new FormatException("Cannot convert custom cursors to string.");
314 void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) {
319 ms = new MemoryStream();
320 wr = new BinaryWriter(ms);
321 ci = cursor_data[this.id];
323 // Build the headers, first the CursorDir
324 wr.Write((ushort)0); // Reserved
325 wr.Write((ushort)2); // Resource type
326 wr.Write((ushort)1); // Count
328 // Next the CursorEntry
329 wr.Write((byte)cursor_dir.idEntries[this.id].width);
330 wr.Write((byte)cursor_dir.idEntries[this.id].height);
331 wr.Write((byte)cursor_dir.idEntries[this.id].colorCount);
332 wr.Write((byte)cursor_dir.idEntries[this.id].reserved);
333 wr.Write((ushort)cursor_dir.idEntries[this.id].xHotspot);
334 wr.Write((ushort)cursor_dir.idEntries[this.id].yHotspot);
335 wr.Write((uint)(40 + (ci.cursorColors.Length * 4) + ci.cursorXOR.Length + ci.cursorAND.Length));
336 wr.Write((uint)(6 + 16)); // CursorDir + CursorEntry size
338 // Then the CursorInfoHeader
339 wr.Write(ci.cursorHeader.biSize);
340 wr.Write(ci.cursorHeader.biWidth);
341 wr.Write(ci.cursorHeader.biHeight);
342 wr.Write(ci.cursorHeader.biPlanes);
343 wr.Write(ci.cursorHeader.biBitCount);
344 wr.Write(ci.cursorHeader.biCompression);
345 wr.Write(ci.cursorHeader.biSizeImage);
346 wr.Write(ci.cursorHeader.biXPelsPerMeter);
347 wr.Write(ci.cursorHeader.biYPelsPerMeter);
348 wr.Write(ci.cursorHeader.biClrUsed);
349 wr.Write(ci.cursorHeader.biClrImportant);
350 for (int i = 0; i < ci.cursorColors.Length; i++) {
351 wr.Write(ci.cursorColors[i]);
353 wr.Write(ci.cursorXOR);
354 wr.Write(ci.cursorAND);
357 si.AddValue ("CursorData", ms.ToArray());
359 #endregion // Public Instance Methods
361 #region Private Methods w
362 private void InitFromStream(Stream stream) {
367 //read the cursor header
368 if (stream == null || stream.Length == 0) {
369 throw new System.ArgumentException ("The argument 'stream' must be a picture that can be used as a cursor", "stream");
372 BinaryReader reader = new BinaryReader (stream);
374 cursor_dir = new CursorDir ();
375 cursor_dir.idReserved = reader.ReadUInt16();
376 if (cursor_dir.idReserved != 0) {
377 throw new System.ArgumentException ("Invalid Argument", "stream");
380 cursor_dir.idType = reader.ReadUInt16();
381 if (cursor_dir.idType != 2) { //must be 2
382 throw new System.ArgumentException ("Invalid Argument", "stream");
385 entry_count = reader.ReadUInt16();
386 cursor_dir.idCount = entry_count;
387 cursor_dir.idEntries = new CursorEntry[entry_count];
388 cursor_data = new CursorImage[entry_count];
390 //now read in the CursorEntry structures
391 for (int i=0; i < entry_count; i++){
392 ce = new CursorEntry();
394 ce.width = reader.ReadByte();
395 ce.height = reader.ReadByte();
396 ce.colorCount = reader.ReadByte();
397 ce.reserved = reader.ReadByte();
398 ce.xHotspot = reader.ReadUInt16();
399 ce.yHotspot = reader.ReadUInt16();
400 ce.sizeInBytes = reader.ReadUInt32();
401 ce.fileOffset = reader.ReadUInt32();
403 cursor_dir.idEntries[i] = ce;
406 // If we have more than one pick the largest cursor
408 for (int j=0; j < entry_count; j++){
409 if (cursor_dir.idEntries[j].sizeInBytes >= largest) {
410 largest = cursor_dir.idEntries[j].sizeInBytes;
412 this.size.Height = cursor_dir.idEntries[j].height;
413 this.size.Width = cursor_dir.idEntries[j].width;
417 //now read in the cursor data
418 for (int j = 0; j < entry_count; j++) {
420 CursorInfoHeader cih;
422 BinaryReader cih_reader;
429 curdata = new CursorImage();
430 cih = new CursorInfoHeader();
432 stream.Seek (cursor_dir.idEntries[j].fileOffset, SeekOrigin.Begin);
433 buffer = new byte [cursor_dir.idEntries[j].sizeInBytes];
434 stream.Read (buffer, 0, buffer.Length);
436 cih_reader = new BinaryReader(new MemoryStream(buffer));
438 cih.biSize = cih_reader.ReadUInt32 ();
439 if (cih.biSize != 40) {
440 throw new System.ArgumentException ("Invalid cursor file", "stream");
442 cih.biWidth = cih_reader.ReadInt32 ();
443 cih.biHeight = cih_reader.ReadInt32 ();
444 cih.biPlanes = cih_reader.ReadUInt16 ();
445 cih.biBitCount = cih_reader.ReadUInt16 ();
446 cih.biCompression = cih_reader.ReadUInt32 ();
447 cih.biSizeImage = cih_reader.ReadUInt32 ();
448 cih.biXPelsPerMeter = cih_reader.ReadInt32 ();
449 cih.biYPelsPerMeter = cih_reader.ReadInt32 ();
450 cih.biClrUsed = cih_reader.ReadUInt32 ();
451 cih.biClrImportant = cih_reader.ReadUInt32 ();
453 curdata.cursorHeader = cih;
455 //Read the number of colors used and corresponding memory occupied by
456 //color table. Fill this memory chunk into rgbquad[]
457 switch (cih.biBitCount){
458 case 1: num_colors = 2; break;
459 case 4: num_colors = 16; break;
460 case 8: num_colors = 256; break;
461 default: num_colors = 0; break;
464 curdata.cursorColors = new uint[num_colors];
465 for (int i = 0; i < num_colors; i++) {
466 curdata.cursorColors[i] = cih_reader.ReadUInt32 ();
469 //XOR mask is immediately after ColorTable and its size is
470 //icon height* no. of bytes per line
472 //cursor height is half of BITMAPINFOHEADER.biHeight, since it contains
473 //both XOR as well as AND mask bytes
474 cursor_height = cih.biHeight/2;
476 //bytes per line should should be uint aligned
477 bytes_per_line = ((((cih.biWidth * cih.biPlanes * cih.biBitCount)+ 31)>>5)<<2);
479 //Determine the XOR array Size
480 xor_size = bytes_per_line * cursor_height;
481 curdata.cursorXOR = new byte[xor_size];
482 for (int i = 0; i < xor_size; i++) {
483 curdata.cursorXOR[i] = cih_reader.ReadByte();
486 //Determine the AND array size
487 and_size = (int)(cih_reader.BaseStream.Length - cih_reader.BaseStream.Position);
488 curdata.cursorAND = new byte[and_size];
489 for (int i = 0; i < and_size; i++) {
490 curdata.cursorAND[i] = cih_reader.ReadByte();
493 cursor_data[j] = curdata;
500 private Bitmap ToBitmap (bool xor, bool transparent) {
503 if (cursor_data != null) {
510 CursorInfoHeader cih;
513 stream = new MemoryStream();
514 writer = new BinaryWriter (stream);
516 ci = cursor_data[this.id];
519 // write bitmap file header
523 // write the file size
524 // file size = bitmapfileheader + bitmapinfo + colorpalette + image bits
525 // sizeof bitmapfileheader = 14 bytes
526 // sizeof bitmapinfo = 40 bytes
528 offset = (uint)(14 + 40 + ci.cursorColors.Length * 4);
529 filesize = (uint)(offset + ci.cursorXOR.Length);
531 offset = (uint)(14 + 40 + 8); // AND mask is always monochrome
532 filesize = (uint)(offset + ci.cursorAND.Length);
534 writer.Write(filesize);
536 // write reserved words
538 writer.Write(reserved12);
539 writer.Write(reserved12);
542 writer.Write (offset);
544 // write bitmapfile header
545 cih = ci.cursorHeader;
546 writer.Write(cih.biSize);
547 writer.Write(cih.biWidth);
548 writer.Write(cih.biHeight/2);
549 writer.Write(cih.biPlanes);
551 writer.Write(cih.biBitCount);
553 writer.Write((ushort)1);
555 writer.Write(cih.biCompression);
557 writer.Write(ci.cursorXOR.Length);
559 writer.Write(ci.cursorAND.Length);
561 writer.Write(cih.biXPelsPerMeter);
562 writer.Write(cih.biYPelsPerMeter);
563 writer.Write(cih.biClrUsed);
564 writer.Write(cih.biClrImportant);
568 color_count = ci.cursorColors.Length;
569 for (int j = 0; j < color_count; j++) {
570 writer.Write (ci.cursorColors[j]);
573 writer.Write((uint)0x00000000);
574 writer.Write((uint)0x00ffffff);
579 writer.Write(ci.cursorXOR);
581 writer.Write(ci.cursorAND);
585 // create bitmap from stream and return
586 bmp = new Bitmap(stream);
589 bmp = new Bitmap(bmp); // This makes a 32bpp image out of an indexed one
590 // Apply the mask to make properly transparent
591 for (int y = 0; y < cih.biHeight/2; y++) {
592 for (int x = 0; x < cih.biWidth / 8; x++) {
593 for (int bit = 7; bit >= 0; bit--) {
594 if (((ci.cursorAND[y * cih.biWidth / 8 +x] >> bit) & 1) != 0) {
595 bmp.SetPixel(x*8 + 7-bit, cih.biHeight/2 - y - 1, Color.Transparent);
601 } catch (Exception e) {
607 bmp = new Bitmap (32, 32);
613 #endregion // Private Methods