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
31 using System.Drawing.Imaging;
33 using System.ComponentModel;
34 using System.Runtime.InteropServices;
35 using System.Runtime.Serialization;
36 using System.Reflection;
38 namespace System.Windows.Forms {
39 [Editor("System.Drawing.Design.CursorEditor, " + Consts.AssemblySystem_Drawing_Design, typeof(System.Drawing.Design.UITypeEditor))]
41 [TypeConverter(typeof(CursorConverter))]
42 public sealed class Cursor : IDisposable, ISerializable {
43 #region Internal Structs
44 [StructLayout(LayoutKind.Sequential)]
45 private struct CursorDir {
46 internal ushort idReserved; // Reserved
47 internal ushort idType; // resource type (2 for cursors)
48 internal ushort idCount; // how many cursors
49 internal CursorEntry[] idEntries; // the entries for each cursor
52 [StructLayout(LayoutKind.Sequential)]
53 private struct CursorEntry {
54 internal byte width; // Width of cursor
55 internal byte height; // Height of cursor
56 internal byte colorCount; // colors in cursor
57 internal byte reserved; // Reserved
58 internal ushort xHotspot; // Hotspot X
59 internal ushort yHotspot; // Hotspot Y
60 internal ushort bitCount; // Bits per pixel
61 internal uint sizeInBytes; // size of (CursorInfoHeader + ANDBitmap + ORBitmap)
62 internal uint fileOffset; // position in file
65 [StructLayout(LayoutKind.Sequential)]
66 private struct CursorInfoHeader {
69 internal int biHeight;
70 internal ushort biPlanes;
71 internal ushort biBitCount;
72 internal uint biCompression;
73 internal uint biSizeImage;
74 internal int biXPelsPerMeter;
75 internal int biYPelsPerMeter;
76 internal uint biClrUsed;
77 internal uint biClrImportant;
80 [StructLayout(LayoutKind.Sequential)]
81 private struct CursorImage {
82 internal CursorInfoHeader cursorHeader; // image header
83 internal uint[] cursorColors; // colors table
84 internal byte[] cursorXOR; // bits for XOR mask
85 internal byte[] cursorAND; // bits for AND mask
87 #endregion // Internal structs
89 #region Local Variables
90 private static Cursor current;
91 private CursorDir cursor_dir;
92 private CursorImage[] cursor_data;
95 internal IntPtr handle;
99 private Bitmap cursor;
100 internal string name;
101 private StdCursor std_cursor = (StdCursor) (-1);
106 #endregion // Local Variables
108 #region Public Constructors
109 private void CreateCursor(System.IO.Stream stream) {
110 InitFromStream(stream);
111 this.shape = ToBitmap(true, false);
112 this.mask = ToBitmap(false, false);
113 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);
114 this.shape.Dispose();
119 if (handle != IntPtr.Zero) {
120 this.cursor = ToBitmap(true, true);
124 internal Cursor (StdCursor cursor) : this (XplatUI.DefineStdCursor (cursor)) {
128 private Cursor(SerializationInfo info, StreamingContext context) {
138 // This is supposed to take a Win32 handle
139 public Cursor(IntPtr handle) {
140 this.handle = handle;
143 public Cursor(System.IO.Stream stream) {
144 CreateCursor(stream);
147 public Cursor (string fileName)
149 using (FileStream fs = File.OpenRead (fileName)) {
154 public Cursor(Type type, string resource) {
155 using (Stream s = type.Assembly.GetManifestResourceStream (type, resource)) {
162 // Try a different way, previous failed
163 using (Stream s = Assembly.GetExecutingAssembly().GetManifestResourceStream(resource)) {
169 throw new FileNotFoundException ("Resource name was not found: `" + resource + "'");
171 #endregion // Public Constructors
173 #region Public Static Properties
174 public static Rectangle Clip {
181 XplatUI.GrabInfo(out handle, out confined, out rect);
182 if (handle != IntPtr.Zero) {
186 XplatUI.GetDisplaySize(out size);
189 rect.Width = size.Width;
190 rect.Height = size.Height;
194 [MonoTODO("First need to add ability to set cursor clip rectangle to XplatUI drivers to implement this property")]
200 [MonoTODO("Implement setting a null cursor, and add XplatUI method to get current cursor")]
201 public static Cursor Current {
203 if (current != null) {
206 return Cursors.Default;
210 if (current != value) {
212 if (current == null){
213 // FIXME - define and set empty cursor
214 XplatUI.OverrideCursor(IntPtr.Zero);
216 XplatUI.OverrideCursor(current.handle);
221 public static Point Position {
226 XplatUI.GetCursorPos (IntPtr.Zero, out x, out y);
227 return new Point (x, y);
231 XplatUI.SetCursorPos(IntPtr.Zero, value.X, value.Y);
234 #endregion // Public Static Properties
236 #region Public Instance Properties
237 public IntPtr Handle {
244 [MonoTODO ("Implemented for Win32, X11 always returns 0,0")]
245 public Point HotSpot {
247 int cursor_w, cursor_h, hot_x, hot_y;
248 XplatUI.GetCursorInfo (Handle, out cursor_w, out cursor_h, out hot_x, out hot_y);
250 return new Point (hot_x, hot_y);
261 [Localizable (false)]
263 [TypeConverter (typeof (StringConverter))]
264 [DefaultValue (null)]
265 [MWFCategory ("Data")]
267 get { return this.tag; }
268 set { this.tag = value; }
271 #endregion // Public Instance Properties
273 #region Public Static Methods
274 public static void Hide() {
275 XplatUI.ShowCursor(false);
278 public static void Show() {
279 XplatUI.ShowCursor(false);
282 public static bool operator !=(Cursor left, Cursor right) {
283 if ((object)left == (object)right) {
287 if ((object)left == null || (object)right == null) {
291 if (left.handle == right.handle) {
298 public static bool operator ==(Cursor left, Cursor right) {
299 if ((object)left == (object)right) {
303 if ((object)left == null || (object)right == null) {
307 if (left.handle == right.handle) {
312 #endregion // Public Static Methods
314 #region Public Instance Methods
315 public IntPtr CopyHandle() {
319 public void Dispose() {
320 if (this.cursor != null) {
321 this.cursor.Dispose();
325 if (this.shape != null) {
326 this.shape.Dispose();
330 if (this.mask != null) {
335 GC.SuppressFinalize (this);
338 public void Draw(Graphics g, Rectangle targetRect) {
339 if (this.cursor == null && std_cursor != (StdCursor) (-1)) {
340 this.cursor = XplatUI.DefineStdCursorBitmap (std_cursor);
342 if (this.cursor != null) {
343 // Size of the targetRect is not considered at all
344 g.DrawImage (this.cursor, targetRect.X, targetRect.Y);
348 public void DrawStretched (Graphics g, Rectangle targetRect)
350 if (this.cursor == null && std_cursor != (StdCursor)(-1)) {
351 this.cursor = XplatUI.DefineStdCursorBitmap (std_cursor);
353 if (this.cursor != null) {
354 g.DrawImage(this.cursor, targetRect, new Rectangle(0, 0, this.cursor.Width, this.cursor.Height), GraphicsUnit.Pixel);
358 public override bool Equals(object obj) {
359 if ( !(obj is Cursor)) {
363 if (((Cursor)obj).handle == this.handle) {
370 public override int GetHashCode() {
371 return base.GetHashCode ();
374 public override string ToString() {
376 return "[Cursor:" + name + "]";
379 throw new FormatException("Cannot convert custom cursors to string.");
382 void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) {
387 ms = new MemoryStream();
388 wr = new BinaryWriter(ms);
389 ci = cursor_data[this.id];
391 // Build the headers, first the CursorDir
392 wr.Write((ushort)0); // Reserved
393 wr.Write((ushort)2); // Resource type
394 wr.Write((ushort)1); // Count
396 // Next the CursorEntry
397 wr.Write((byte)cursor_dir.idEntries[this.id].width);
398 wr.Write((byte)cursor_dir.idEntries[this.id].height);
399 wr.Write((byte)cursor_dir.idEntries[this.id].colorCount);
400 wr.Write((byte)cursor_dir.idEntries[this.id].reserved);
401 wr.Write((ushort)cursor_dir.idEntries[this.id].xHotspot);
402 wr.Write((ushort)cursor_dir.idEntries[this.id].yHotspot);
403 wr.Write((uint)(40 + (ci.cursorColors.Length * 4) + ci.cursorXOR.Length + ci.cursorAND.Length));
404 wr.Write((uint)(6 + 16)); // CursorDir + CursorEntry size
406 // Then the CursorInfoHeader
407 wr.Write(ci.cursorHeader.biSize);
408 wr.Write(ci.cursorHeader.biWidth);
409 wr.Write(ci.cursorHeader.biHeight);
410 wr.Write(ci.cursorHeader.biPlanes);
411 wr.Write(ci.cursorHeader.biBitCount);
412 wr.Write(ci.cursorHeader.biCompression);
413 wr.Write(ci.cursorHeader.biSizeImage);
414 wr.Write(ci.cursorHeader.biXPelsPerMeter);
415 wr.Write(ci.cursorHeader.biYPelsPerMeter);
416 wr.Write(ci.cursorHeader.biClrUsed);
417 wr.Write(ci.cursorHeader.biClrImportant);
418 for (int i = 0; i < ci.cursorColors.Length; i++) {
419 wr.Write(ci.cursorColors[i]);
421 wr.Write(ci.cursorXOR);
422 wr.Write(ci.cursorAND);
425 si.AddValue ("CursorData", ms.ToArray());
427 #endregion // Public Instance Methods
429 #region Private Methods w
430 private void InitFromStream(Stream stream) {
435 //read the cursor header
436 if (stream == null || stream.Length == 0) {
437 throw new System.ArgumentException ("The argument 'stream' must be a picture that can be used as a cursor", "stream");
440 BinaryReader reader = new BinaryReader (stream);
442 cursor_dir = new CursorDir ();
443 cursor_dir.idReserved = reader.ReadUInt16();
444 cursor_dir.idType = reader.ReadUInt16();
445 if (cursor_dir.idReserved != 0 || !(cursor_dir.idType == 2 || cursor_dir.idType == 1))
446 throw new System.ArgumentException ("Invalid Argument, format error", "stream");
448 entry_count = reader.ReadUInt16();
449 cursor_dir.idCount = entry_count;
450 cursor_dir.idEntries = new CursorEntry[entry_count];
451 cursor_data = new CursorImage[entry_count];
453 //now read in the CursorEntry structures
454 for (int i=0; i < entry_count; i++){
455 ce = new CursorEntry();
457 ce.width = reader.ReadByte();
458 ce.height = reader.ReadByte();
459 ce.colorCount = reader.ReadByte();
460 ce.reserved = reader.ReadByte();
461 ce.xHotspot = reader.ReadUInt16();
462 ce.yHotspot = reader.ReadUInt16();
463 if (cursor_dir.idType == 1) {
464 ce.xHotspot = (ushort)(ce.width / 2);
465 ce.yHotspot = (ushort)(ce.height / 2);
467 ce.sizeInBytes = reader.ReadUInt32();
468 ce.fileOffset = reader.ReadUInt32();
470 cursor_dir.idEntries[i] = ce;
473 // If we have more than one pick the largest cursor
475 for (int j=0; j < entry_count; j++){
476 if (cursor_dir.idEntries[j].sizeInBytes >= largest) {
477 largest = cursor_dir.idEntries[j].sizeInBytes;
479 this.size.Height = cursor_dir.idEntries[j].height;
480 this.size.Width = cursor_dir.idEntries[j].width;
484 //now read in the cursor data
485 for (int j = 0; j < entry_count; j++) {
487 CursorInfoHeader cih;
489 BinaryReader cih_reader;
496 curdata = new CursorImage();
497 cih = new CursorInfoHeader();
499 stream.Seek (cursor_dir.idEntries[j].fileOffset, SeekOrigin.Begin);
500 buffer = new byte [cursor_dir.idEntries[j].sizeInBytes];
501 stream.Read (buffer, 0, buffer.Length);
503 cih_reader = new BinaryReader(new MemoryStream(buffer));
505 cih.biSize = cih_reader.ReadUInt32 ();
506 if (cih.biSize != 40) {
507 throw new System.ArgumentException ("Invalid cursor file", "stream");
509 cih.biWidth = cih_reader.ReadInt32 ();
510 cih.biHeight = cih_reader.ReadInt32 ();
511 cih.biPlanes = cih_reader.ReadUInt16 ();
512 cih.biBitCount = cih_reader.ReadUInt16 ();
513 cih.biCompression = cih_reader.ReadUInt32 ();
514 cih.biSizeImage = cih_reader.ReadUInt32 ();
515 cih.biXPelsPerMeter = cih_reader.ReadInt32 ();
516 cih.biYPelsPerMeter = cih_reader.ReadInt32 ();
517 cih.biClrUsed = cih_reader.ReadUInt32 ();
518 cih.biClrImportant = cih_reader.ReadUInt32 ();
520 curdata.cursorHeader = cih;
522 //Read the number of colors used and corresponding memory occupied by
523 //color table. Fill this memory chunk into rgbquad[]
524 switch (cih.biBitCount){
525 case 1: num_colors = 2; break;
526 case 4: num_colors = 16; break;
527 case 8: num_colors = 256; break;
528 default: num_colors = 0; break;
531 curdata.cursorColors = new uint[num_colors];
532 for (int i = 0; i < num_colors; i++) {
533 curdata.cursorColors[i] = cih_reader.ReadUInt32 ();
536 //XOR mask is immediately after ColorTable and its size is
537 //icon height* no. of bytes per line
539 //cursor height is half of BITMAPINFOHEADER.biHeight, since it contains
540 //both XOR as well as AND mask bytes
541 cursor_height = cih.biHeight/2;
543 //bytes per line should should be uint aligned
544 bytes_per_line = ((((cih.biWidth * cih.biPlanes * cih.biBitCount)+ 31)>>5)<<2);
546 //Determine the XOR array Size
547 xor_size = bytes_per_line * cursor_height;
548 curdata.cursorXOR = new byte[xor_size];
549 for (int i = 0; i < xor_size; i++) {
550 curdata.cursorXOR[i] = cih_reader.ReadByte();
553 //Determine the AND array size
554 and_size = (int)(cih_reader.BaseStream.Length - cih_reader.BaseStream.Position);
555 curdata.cursorAND = new byte[and_size];
556 for (int i = 0; i < and_size; i++) {
557 curdata.cursorAND[i] = cih_reader.ReadByte();
560 cursor_data[j] = curdata;
567 private Bitmap ToBitmap(bool xor, bool transparent) {
569 CursorInfoHeader cih;
577 if (cursor_data == null) {
578 return new Bitmap(32, 32);
581 ci = cursor_data[this.id];
582 cih = ci.cursorHeader;
583 biHeight = cih.biHeight / 2;
586 // The AND mask is 1bit - very straightforward
587 bmp = new Bitmap(cih.biWidth, biHeight, PixelFormat.Format1bppIndexed);
589 pal.Entries[0] = Color.FromArgb(0, 0, 0);
590 pal.Entries[1] = Color.FromArgb(unchecked((int)0xffffffffff));
591 bits = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat);
593 for (int y = 0; y < biHeight; y++) {
594 Marshal.Copy(ci.cursorAND, bits.Stride * y, (IntPtr)(bits.Scan0.ToInt64() + bits.Stride * (biHeight - 1 - y)), bits.Stride);
597 bmp.UnlockBits(bits);
599 ncolors = (int)cih.biClrUsed;
601 if (cih.biBitCount < 24) {
602 ncolors = (int)(1 << cih.biBitCount);
606 switch(cih.biBitCount) {
607 case 1: { // Monochrome
608 bmp = new Bitmap(cih.biWidth, biHeight, PixelFormat.Format1bppIndexed);
613 bmp = new Bitmap(cih.biWidth, biHeight, PixelFormat.Format4bppIndexed);
618 bmp = new Bitmap(cih.biWidth, biHeight, PixelFormat.Format8bppIndexed);
624 bmp = new Bitmap(cih.biWidth, biHeight, PixelFormat.Format32bppArgb);
629 throw new Exception("Unexpected number of bits:" + cih.biBitCount.ToString());
633 if (cih.biBitCount < 24) {
634 pal = bmp.Palette; // Managed palette
636 for (int i = 0; i < ci.cursorColors.Length; i++) {
637 pal.Entries[i] = Color.FromArgb((int)ci.cursorColors[i] | unchecked((int)0xff000000));
642 bytesPerLine = (int)((((cih.biWidth * cih.biBitCount) + 31) & ~31) >> 3);
643 bits = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat);
645 for (int y = 0; y < biHeight; y++) {
646 Marshal.Copy(ci.cursorXOR, bytesPerLine * y, (IntPtr)(bits.Scan0.ToInt64() + bits.Stride * (biHeight - 1 - y)), bytesPerLine);
649 bmp.UnlockBits(bits);
653 bmp = new Bitmap(bmp); // This makes a 32bpp image out of an indexed one
654 // Apply the mask to make properly transparent
655 for (int y = 0; y < biHeight; y++) {
656 for (int x = 0; x < cih.biWidth / 8; x++) {
657 for (int bit = 7; bit >= 0; bit--) {
658 if (((ci.cursorAND[y * cih.biWidth / 8 +x] >> bit) & 1) != 0) {
659 bmp.SetPixel(x*8 + 7-bit, biHeight - y - 1, Color.Transparent);
668 #endregion // Private Methods