2005-09-08 Peter Dennis Bartok <pbartok@novell.com>
[mono.git] / mcs / class / Managed.Windows.Forms / System.Windows.Forms / Cursor.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 Novell, Inc.
21 //
22 // Authors:
23 //      Peter Bartok    pbartok@novell.com
24 //
25
26
27 // NOT COMPLETE
28
29 using System;
30 using System.Drawing;
31 using System.IO;
32 using System.ComponentModel;
33 using System.Runtime.InteropServices;
34 using System.Runtime.Serialization;
35
36 namespace System.Windows.Forms {
37         [Editor("System.Drawing.Design.CursorEditor, " + Consts.AssemblySystem_Drawing_Design, typeof(System.Drawing.Design.UITypeEditor))]
38         [Serializable]
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
48                 };
49                 
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 
61                 }; 
62
63                 [StructLayout(LayoutKind.Sequential)]
64                 private  struct CursorInfoHeader {
65                         internal uint           biSize; 
66                         internal int            biWidth; 
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; 
76                 };
77
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
84                 };
85                 #endregion      // Internal structs
86
87                 #region Local Variables
88                 private static Cursor   current;
89                 private CursorDir       cursor_dir;
90                 private CursorImage[]   cursor_data;
91                 private int             id;
92
93                 internal IntPtr         handle;
94                 private Size            size;
95                 private Bitmap          shape;
96                 private Bitmap          mask;
97                 private Bitmap          cursor;
98                 internal string         name;
99                 #endregion      // Local Variables
100
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();
108                         this.shape = null;
109                         this.mask.Dispose();
110                         this.mask = null;
111
112                         if (handle != IntPtr.Zero) {
113                                 this.cursor = ToBitmap(true, true);
114                         }
115                 }
116
117                 private Cursor() {
118                 }
119
120                 ~Cursor() {
121                         Dispose();
122                 }
123
124                 // This is supposed to take a Win32 handle
125                 public Cursor(IntPtr handle) {
126                         this.handle = handle;
127                 }
128
129                 public Cursor(System.IO.Stream stream) {
130                         CreateCursor(stream);
131                 }
132
133                 public Cursor(string fileName) : this (new FileStream (fileName, FileMode.Open)) {
134                 }
135
136                 public Cursor(Type type, string resource) {
137                         using (Stream s = type.Assembly.GetManifestResourceStream (type, resource)) {
138                                 if (s == null) {
139                                         throw new FileNotFoundException ("Resource name was not found: `" + resource + "'");
140                                 }
141                                 CreateCursor(s);
142                         }
143                 }
144                 #endregion      // Public Constructors
145
146                 #region Public Static Properties
147                 public static Rectangle Clip {
148                         get {
149                                 IntPtr          handle;
150                                 bool            confined;
151                                 Rectangle       rect;
152                                 Size            size;
153
154                                 XplatUI.GrabInfo(out handle, out confined, out rect);
155                                 if (handle != IntPtr.Zero) {
156                                         return rect;
157                                 }
158
159                                 XplatUI.GetDisplaySize(out size);
160                                 rect.X = 0;
161                                 rect.Y = 0;
162                                 rect.Width = size.Width;
163                                 rect.Height = size.Height;
164                                 return rect;
165                         }
166
167                         [MonoTODO("First need to add ability to set cursor clip rectangle to XplatUI drivers to implement this property")]
168                         set {
169                                 ;
170                         }
171                 }
172
173                 public static Cursor Current {
174                         get {
175                                 return current;
176                         }
177
178                         set {
179                                 if (current != value) {
180                                         current = value;
181                                         XplatUI.OverrideCursor(current.handle);
182                                 }
183                         }
184                 }
185
186                 public static Point Position {
187                         get {
188                                 int x;
189                                 int y;
190
191                                 XplatUI.GetCursorPos (IntPtr.Zero, out x, out y);
192                                 return new Point (x, y);
193                         }
194
195                         set {
196                                 XplatUI.SetCursorPos(IntPtr.Zero, value.X, value.Y);
197                         }
198                 }
199                 #endregion      // Public Static Properties
200
201                 #region Public Instance Properties
202                 public IntPtr Handle {
203                         get {
204                                 return handle;
205                         }
206                 }
207
208                 public Size Size {
209                         get {
210                                 return size;
211                         }
212                 }
213                 #endregion      // Public Instance Properties
214
215                 #region Public Static Methods
216                 public static void Hide() {
217                         XplatUI.ShowCursor(false);
218                 }
219
220                 public static void Show() {
221                         XplatUI.ShowCursor(false);
222                 }
223
224                 public static bool operator !=(Cursor left, Cursor right) {
225                         if ((object)left == (object)right) {
226                                 return false;
227                         }
228
229                         if ((object)left == null || (object)right == null) {
230                                 return true;
231                         }
232
233                         if (left.handle == right.handle) {
234                                 return false;
235                         }
236                         return true;
237                 }
238
239
240                 public static bool operator ==(Cursor left, Cursor right) {
241                         if ((object)left == (object)right) {
242                                 return true;
243                         }
244
245                         if ((object)left == null || (object)right == null) {
246                                 return false;
247                         }
248
249                         if (left.handle == right.handle) {
250                                 return true;
251                         }
252                         return false;
253                 }
254                 #endregion      // Public Static Methods
255
256                 #region Public Instance Methods
257                 public IntPtr CopyHandle() {
258                         return handle;
259                 }
260
261                 public void Dispose() {
262                         if (this.cursor != null) {
263                                 this.cursor.Dispose();
264                                 this.cursor = null;
265                         }
266
267                         if (this.shape != null) {
268                                 this.shape.Dispose();
269                                 this.shape = null;
270                         }
271
272                         if (this.mask != null) {
273                                 this.mask.Dispose();
274                                 this.mask = null;
275                         }
276                 }
277
278                 public void Draw(Graphics g, Rectangle targetRect) {
279                         if (this.cursor != null) {
280                                 g.DrawImage(this.cursor, targetRect);
281                         }
282                 }
283
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);
287                         }
288                 }
289
290                 public override bool Equals(object obj) {
291                         if ( !(obj is Cursor)) {
292                                 return false;
293                         }
294
295                         if (((Cursor)obj).handle == this.handle) {
296                                 return true;
297                         }
298
299                         return false;
300                 }
301
302                 public override int GetHashCode() {
303                         return base.GetHashCode ();
304                 }
305
306                 public override string ToString() {
307                         if (name != null) {
308                                 return "[Cursor:" + name + "]";
309                         }
310
311                         throw new FormatException("Cannot convert custom cursors to string.");
312                 }
313
314                 void ISerializable.GetObjectData(SerializationInfo si, StreamingContext context) {
315                         MemoryStream    ms;
316                         BinaryWriter    wr;
317                         CursorImage     ci;
318
319                         ms = new MemoryStream();
320                         wr = new BinaryWriter(ms);
321                         ci = cursor_data[this.id];
322
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
327
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
337
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]);
352                         }
353                         wr.Write(ci.cursorXOR);
354                         wr.Write(ci.cursorAND);
355                         wr.Flush();
356
357                         si.AddValue ("CursorData", ms.ToArray());
358                 }
359                 #endregion      // Public Instance Methods
360
361                 #region Private Methods           w
362                 private void InitFromStream(Stream stream) {
363                         ushort          entry_count;
364                         CursorEntry     ce;
365                         uint            largest;
366
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");
370                         }
371                         
372                         BinaryReader reader = new BinaryReader (stream);
373             
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");
378                         }
379                         
380                         cursor_dir.idType = reader.ReadUInt16();
381                         if (cursor_dir.idType != 2) { //must be 2
382                                 throw new System.ArgumentException ("Invalid Argument", "stream");
383                         }
384
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];
389
390                         //now read in the CursorEntry structures
391                         for (int i=0; i < entry_count; i++){
392                                 ce = new CursorEntry();
393
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();
402
403                                 cursor_dir.idEntries[i] = ce;
404                         }
405
406                         // If we have more than one pick the largest cursor
407                         largest = 0;
408                         for (int j=0; j < entry_count; j++){
409                                 if (cursor_dir.idEntries[j].sizeInBytes >= largest)     {
410                                         largest = cursor_dir.idEntries[j].sizeInBytes;
411                                         this.id = (ushort)j;
412                                         this.size.Height = cursor_dir.idEntries[j].height;
413                                         this.size.Width = cursor_dir.idEntries[j].width;
414                                 }
415                         }
416
417                         //now read in the cursor data
418                         for (int j = 0; j < entry_count; j++) {
419                                 CursorImage             curdata;
420                                 CursorInfoHeader        cih;
421                                 byte[]                  buffer;
422                                 BinaryReader            cih_reader;
423                                 int                     num_colors;
424                                 int                     cursor_height;
425                                 int                     bytes_per_line;
426                                 int                     xor_size;
427                                 int                     and_size;
428
429                                 curdata = new CursorImage();
430                                 cih = new CursorInfoHeader();
431                                 
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);
435
436                                 cih_reader = new BinaryReader(new MemoryStream(buffer));
437
438                                 cih.biSize = cih_reader.ReadUInt32 ();
439                                 if (cih.biSize != 40) {
440                                         throw new System.ArgumentException ("Invalid cursor file", "stream");
441                                 }
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 ();
452
453                                 curdata.cursorHeader = cih;
454
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;
462                                 }
463                                 
464                                 curdata.cursorColors = new uint[num_colors];
465                                 for (int i = 0; i < num_colors; i++) {
466                                         curdata.cursorColors[i] = cih_reader.ReadUInt32 ();
467                                 }
468
469                                 //XOR mask is immediately after ColorTable and its size is 
470                                 //icon height* no. of bytes per line
471                                 
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;
475                                 
476                                 //bytes per line should should be uint aligned
477                                 bytes_per_line = ((((cih.biWidth * cih.biPlanes * cih.biBitCount)+ 31)>>5)<<2);
478                                 
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();
484                                 }
485                                 
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();
491                                 }
492                                 
493                                 cursor_data[j] = curdata;
494                                 cih_reader.Close();
495                         }                       
496
497                         reader.Close();
498                 }
499
500                 private Bitmap ToBitmap (bool xor, bool transparent) {
501                         Bitmap bmp;
502
503                         if (cursor_data != null) {
504                                 MemoryStream            stream;
505                                 BinaryWriter            writer;
506                                 CursorImage             ci;
507                                 uint                    offset;
508                                 uint                    filesize;
509                                 ushort                  reserved12;
510                                 CursorInfoHeader        cih;
511                                 int                     color_count;
512
513                                 stream = new MemoryStream();
514                                 writer = new BinaryWriter (stream);
515
516                                 ci = cursor_data[this.id];
517
518                                 try {
519                                         // write bitmap file header
520                                         writer.Write ('B');
521                                         writer.Write ('M');
522
523                                         // write the file size
524                                         // file size = bitmapfileheader + bitmapinfo + colorpalette + image bits
525                                         // sizeof bitmapfileheader = 14 bytes
526                                         // sizeof bitmapinfo = 40 bytes
527                                         if (xor) {
528                                                 offset = (uint)(14 + 40 + ci.cursorColors.Length * 4);
529                                                 filesize = (uint)(offset + ci.cursorXOR.Length);
530                                         } else {
531                                                 offset = (uint)(14 + 40 + 8);   // AND mask is always monochrome
532                                                 filesize = (uint)(offset + ci.cursorAND.Length);
533                                         }
534                                         writer.Write(filesize);
535                                         
536                                         // write reserved words
537                                         reserved12 = 0;
538                                         writer.Write(reserved12);
539                                         writer.Write(reserved12);
540
541                                         // write offset
542                                         writer.Write (offset);
543
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);
550                                         if (xor) {
551                                                 writer.Write(cih.biBitCount);
552                                         } else {
553                                                 writer.Write((ushort)1);
554                                         }
555                                         writer.Write(cih.biCompression);
556                                         if (xor) {
557                                                 writer.Write(ci.cursorXOR.Length);
558                                         } else {
559                                                 writer.Write(ci.cursorAND.Length);
560                                         }
561                                         writer.Write(cih.biXPelsPerMeter);
562                                         writer.Write(cih.biYPelsPerMeter);
563                                         writer.Write(cih.biClrUsed);
564                                         writer.Write(cih.biClrImportant);
565
566                                         // write color table
567                                         if (xor) {
568                                                 color_count = ci.cursorColors.Length;
569                                                 for (int j = 0; j < color_count; j++) {
570                                                         writer.Write (ci.cursorColors[j]);
571                                                 }
572                                         } else {
573                                                 writer.Write((uint)0x00000000);
574                                                 writer.Write((uint)0x00ffffff);
575                                         }
576
577                                         // write image bits
578                                         if (xor) {
579                                                 writer.Write(ci.cursorXOR);
580                                         } else {
581                                                 writer.Write(ci.cursorAND);
582                                         }
583                                         writer.Flush();
584
585                                         // create bitmap from stream and return
586                                         bmp = new Bitmap(stream);
587
588                                         if (transparent) {
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);
596                                                                         }
597                                                                 }
598                                                         }
599                                                 }
600                                         }
601                                 } catch (Exception e) {
602                                         throw e;
603                                 } finally {
604                                         writer.Close();
605                                 }
606                         } else {
607                                 bmp = new Bitmap (32, 32);
608                         }
609
610                         return bmp;
611                 }
612
613                 #endregion      // Private Methods
614         }
615 }