PdnGraphics.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472
  1. using System;
  2. using System.ComponentModel;
  3. using System.Drawing;
  4. using System.Drawing.Drawing2D;
  5. using System.Drawing.Imaging;
  6. using System.Runtime.InteropServices;
  7. namespace PaintDotNet.SystemLayer
  8. {
  9. /// <summary>
  10. /// These methods are used because we found some bugs in GDI+ / WinForms. Some
  11. /// were the cause of major flickering with the transparent toolforms.
  12. /// Other implementations of this class, or more generic implementations, may safely
  13. /// thunk straight to equivelants in System.Drawing.Graphics.
  14. /// </summary>
  15. public static class PdnGraphics
  16. {
  17. public static GraphicsPath ClipPath(GraphicsPath subjectPath, CombineMode combineMode, GraphicsPath clipPath)
  18. {
  19. GpcWrapper.Polygon.Validate(combineMode);
  20. GpcWrapper.Polygon basePoly = new GpcWrapper.Polygon(subjectPath);
  21. GraphicsPath clipClone = (GraphicsPath)clipPath.Clone();
  22. clipClone.CloseAllFigures();
  23. GpcWrapper.Polygon clipPoly = new GpcWrapper.Polygon(clipClone);
  24. clipClone.Dispose();
  25. GpcWrapper.Polygon clippedPoly = GpcWrapper.Polygon.Clip(combineMode, basePoly, clipPoly);
  26. GraphicsPath returnPath = clippedPoly.ToGraphicsPath();
  27. returnPath.CloseAllFigures();
  28. return returnPath;
  29. }
  30. public static void SetPropertyItems(Image image, PropertyItem[] items)
  31. {
  32. PropertyItem[] pis = image.PropertyItems;
  33. foreach (PropertyItem pi in pis)
  34. {
  35. image.RemovePropertyItem(pi.Id);
  36. }
  37. foreach (PropertyItem pi in items)
  38. {
  39. image.SetPropertyItem(pi);
  40. }
  41. }
  42. /// <summary>
  43. /// Creates a new, zero-filled PropertyItem.
  44. /// </summary>
  45. /// <returns>A PropertyItem that is zero-filled.</returns>
  46. public static PropertyItem CreatePropertyItem()
  47. {
  48. PropertyItem2 pi2 = new PropertyItem2(0, 0, 0, new byte[0]);
  49. return pi2.ToPropertyItem();
  50. }
  51. /// <summary>
  52. /// Copies the given PropertyItem.
  53. /// </summary>
  54. /// <param name="pi">The PropertyItem to clone.</param>
  55. /// <returns>A copy of the given PropertyItem.</returns>
  56. public static PropertyItem ClonePropertyItem(PropertyItem pi)
  57. {
  58. byte[] valueClone;
  59. if (pi.Value == null)
  60. {
  61. valueClone = new byte[0];
  62. }
  63. else
  64. {
  65. valueClone = (byte[])pi.Value.Clone();
  66. }
  67. PropertyItem2 pi2 = new PropertyItem2(pi.Id, pi.Len, pi.Type, valueClone);
  68. return pi2.ToPropertyItem();
  69. }
  70. /// <summary>
  71. /// Serializes a PropertyItem into a string blob.
  72. /// </summary>
  73. /// <param name="pi">The PropertyItem to serialize.</param>
  74. /// <returns>A string that may be later deserialized using DeserializePropertyItem.</returns>
  75. /// <remarks>
  76. /// Note to implementors: The format for the serialized data is intentionally opaque for programmatic users
  77. /// of this class. However, since this data goes into .PDN files, it must be carefully maintained. See
  78. /// the PropertyItem2 class for details.
  79. /// </remarks>
  80. public static string SerializePropertyItem(PropertyItem pi)
  81. {
  82. PropertyItem2 pi2 = PropertyItem2.FromPropertyItem(pi);
  83. return pi2.ToBlob();
  84. }
  85. /// <summary>
  86. /// Deserializes a PropertyItem from a string previously returned from SerializePropertyItem.
  87. /// </summary>
  88. /// <param name="piBlob">The string data to deserialize.</param>
  89. /// <returns>A PropertyItem instance.</returns>
  90. /// <remarks>
  91. /// Note to implementors: The format for the serialized data is intentionally opaque for programmatic users
  92. /// of this class. However, since this data goes into .PDN files, it must be carefully maintained. See
  93. /// the PropertyItem2 class for details.
  94. /// </remarks>
  95. public static PropertyItem DeserializePropertyItem(string piBlob)
  96. {
  97. PropertyItem2 pi2 = PropertyItem2.FromBlob(piBlob);
  98. return pi2.ToPropertyItem();
  99. }
  100. /// <summary>
  101. /// Draws a bitmap to a Graphics context.
  102. /// </summary>
  103. /// <param name="dst">The Graphics context to draw the bitmap on to.</param>
  104. /// <param name="dstRect">The clipping rectangle in destination coordinates.</param>
  105. /// <param name="dstMatrix">The transformation matrix to apply. This is only used to transform the upper-left corner of dstRect.</param>
  106. /// <param name="srcBitmapHandle">The handle to the bitmap obtained from Memory.AllocateBitmap().</param>
  107. /// <param name="srcWidth">The full width of the bitmap.</param>
  108. /// <param name="srcHeight">The full height of the bitmap.</param>
  109. /// <param name="srcOffsetX">The left edge of the source bitmap to draw from.</param>
  110. /// <param name="srcOffsetY">The top edge of the source bitmap to draw from.</param>
  111. public unsafe static void DrawBitmap(
  112. Graphics dst,
  113. Rectangle dstRect,
  114. Matrix dstMatrix,
  115. IntPtr srcBitmapHandle,
  116. int srcOffsetX,
  117. int srcOffsetY)
  118. {
  119. if (srcBitmapHandle == IntPtr.Zero)
  120. {
  121. throw new ArgumentNullException("srcBitmapHandle");
  122. }
  123. Point[] points = new Point[] { dstRect.Location };
  124. dstMatrix.TransformPoints(points);
  125. dstRect.Location = points[0];
  126. IntPtr hdc = IntPtr.Zero;
  127. IntPtr hbitmap = IntPtr.Zero;
  128. IntPtr chdc = IntPtr.Zero;
  129. IntPtr old = IntPtr.Zero;
  130. try
  131. {
  132. hdc = dst.GetHdc();
  133. chdc = SafeNativeMethods.CreateCompatibleDC(hdc);
  134. old = SafeNativeMethods.SelectObject(chdc, srcBitmapHandle);
  135. SafeNativeMethods.BitBlt(hdc, dstRect.Left, dstRect.Top, dstRect.Width,
  136. dstRect.Height, chdc, srcOffsetX, srcOffsetY, NativeConstants.SRCCOPY);
  137. }
  138. finally
  139. {
  140. if (old != IntPtr.Zero)
  141. {
  142. SafeNativeMethods.SelectObject(chdc, old);
  143. old = IntPtr.Zero;
  144. }
  145. if (chdc != IntPtr.Zero)
  146. {
  147. SafeNativeMethods.DeleteDC(chdc);
  148. chdc = IntPtr.Zero;
  149. }
  150. if (hdc != IntPtr.Zero)
  151. {
  152. dst.ReleaseHdc(hdc);
  153. hdc = IntPtr.Zero;
  154. }
  155. }
  156. GC.KeepAlive(dst);
  157. }
  158. internal unsafe static void GetRegionScans(IntPtr hRgn, out Rectangle[] scans, out int area)
  159. {
  160. uint bytes = 0;
  161. int countdown = screwUpMax;
  162. int error = 0;
  163. while (countdown > 0)
  164. {
  165. bytes = SafeNativeMethods.GetRegionData(hRgn, 0, (NativeStructs.RGNDATA*)IntPtr.Zero);
  166. error = Marshal.GetLastWin32Error();
  167. if (bytes == 0)
  168. {
  169. --countdown;
  170. System.Threading.Thread.Sleep(5);
  171. }
  172. else
  173. {
  174. break;
  175. }
  176. }
  177. // But if we retry several times and it still messes up then we will finally give up.
  178. if (bytes == 0)
  179. {
  180. throw new Win32Exception(error, "GetRegionData returned " + bytes.ToString() + ", GetLastError() = " + error.ToString());
  181. }
  182. byte* data;
  183. // Up to 512 bytes, allocate on the stack. Otherwise allocate from the heap.
  184. if (bytes <= 512)
  185. {
  186. byte* data1 = stackalloc byte[(int)bytes];
  187. data = data1;
  188. }
  189. else
  190. {
  191. data = (byte*)Memory.Allocate(bytes).ToPointer();
  192. }
  193. try
  194. {
  195. NativeStructs.RGNDATA* pRgnData = (NativeStructs.RGNDATA*)data;
  196. uint result = SafeNativeMethods.GetRegionData(hRgn, bytes, pRgnData);
  197. if (result != bytes)
  198. {
  199. throw new OutOfMemoryException("SafeNativeMethods.GetRegionData returned 0");
  200. }
  201. NativeStructs.RECT* pRects = NativeStructs.RGNDATA.GetRectsPointer(pRgnData);
  202. scans = new Rectangle[pRgnData->rdh.nCount];
  203. area = 0;
  204. for (int i = 0; i < scans.Length; ++i)
  205. {
  206. scans[i] = Rectangle.FromLTRB(pRects[i].left, pRects[i].top, pRects[i].right, pRects[i].bottom);
  207. area += scans[i].Width * scans[i].Height;
  208. }
  209. pRects = null;
  210. pRgnData = null;
  211. }
  212. finally
  213. {
  214. if (bytes > 512)
  215. {
  216. Memory.Free(new IntPtr(data));
  217. }
  218. }
  219. }
  220. private const int screwUpMax = 100;
  221. /// <summary>
  222. /// Retrieves an array of rectangles that approximates a region, and computes the
  223. /// pixel area of it. This method is necessary to work around some bugs in .NET
  224. /// and to increase performance for the way in which we typically use this data.
  225. /// </summary>
  226. /// <param name="region">The Region to retrieve data from.</param>
  227. /// <param name="scans">An array of Rectangle to put the scans into.</param>
  228. /// <param name="area">An integer to write the computed area of the region into.</param>
  229. /// <remarks>
  230. /// Note to implementors: Simple implementations may simple call region.GetRegionScans()
  231. /// and process the data for the 'out' variables.</remarks>
  232. public static void GetRegionScans(Region region, out Rectangle[] scans, out int area)
  233. {
  234. using (NullGraphics nullGraphics = new NullGraphics())
  235. {
  236. IntPtr hRgn = IntPtr.Zero;
  237. try
  238. {
  239. hRgn = region.GetHrgn(nullGraphics.Graphics);
  240. GetRegionScans(hRgn, out scans, out area);
  241. }
  242. finally
  243. {
  244. if (hRgn != IntPtr.Zero)
  245. {
  246. SafeNativeMethods.DeleteObject(hRgn);
  247. hRgn = IntPtr.Zero;
  248. }
  249. }
  250. }
  251. GC.KeepAlive(region);
  252. }
  253. /// <summary>
  254. /// Draws a polygon. The last point is not joined to the beginning point. If there is an error while
  255. /// trying to draw, it is discarded and ignored.
  256. /// </summary>
  257. /// <param name="g">The Graphics context to draw to.</param>
  258. /// <param name="points">The points to draw. Lines are drawn between every point N to point N+1.</param>
  259. /// <param name="color">The color to draw with.</param>
  260. /// <remarks>
  261. /// Note to implementors: This method is used to avoid drawing with GDI+, which avoids flickering
  262. /// with our transparent toolforms. Implementations may thunk straight to g.DrawLines().
  263. /// </remarks>
  264. public static void DrawPolyLine(Graphics g, Color color, Point[] points)
  265. {
  266. try
  267. {
  268. DrawPolyLineImpl(g, color, points);
  269. }
  270. catch (Exception ex)
  271. {
  272. Tracing.Ping("Exception while executing PdnGraphics.DrawPolyLine: " + ex.ToString());
  273. }
  274. }
  275. private static void DrawPolyLineImpl(Graphics g, Color color, Point[] points)
  276. {
  277. if (points.Length < 1)
  278. {
  279. return;
  280. }
  281. uint nativeColor = (uint)(color.R + (color.G << 8) + (color.B << 16));
  282. IntPtr hdc = IntPtr.Zero;
  283. IntPtr pen = IntPtr.Zero;
  284. IntPtr oldObject = IntPtr.Zero;
  285. try
  286. {
  287. hdc = g.GetHdc();
  288. pen = SafeNativeMethods.CreatePen(NativeConstants.PS_SOLID, 1, nativeColor);
  289. if (pen == IntPtr.Zero)
  290. {
  291. NativeMethods.ThrowOnWin32Error("CreatePen returned NULL");
  292. }
  293. oldObject = SafeNativeMethods.SelectObject(hdc, pen);
  294. NativeStructs.POINT pt;
  295. bool bResult = SafeNativeMethods.MoveToEx(hdc, points[0].X, points[0].Y, out pt);
  296. if (!bResult)
  297. {
  298. NativeMethods.ThrowOnWin32Error("MoveToEx returned false");
  299. }
  300. for (int i = 1; i < points.Length; ++i)
  301. {
  302. bResult = SafeNativeMethods.LineTo(hdc, points[i].X, points[i].Y);
  303. if (!bResult)
  304. {
  305. NativeMethods.ThrowOnWin32Error("LineTo returned false");
  306. }
  307. }
  308. }
  309. finally
  310. {
  311. if (oldObject != IntPtr.Zero)
  312. {
  313. SafeNativeMethods.SelectObject(hdc, oldObject);
  314. oldObject = IntPtr.Zero;
  315. }
  316. if (pen != IntPtr.Zero)
  317. {
  318. SafeNativeMethods.DeleteObject(pen);
  319. pen = IntPtr.Zero;
  320. }
  321. if (hdc != IntPtr.Zero)
  322. {
  323. g.ReleaseHdc(hdc);
  324. hdc = IntPtr.Zero;
  325. }
  326. }
  327. GC.KeepAlive(g);
  328. }
  329. /// <summary>
  330. /// Draws several filled rectangles using the same color. If there is an error while trying to draw,
  331. /// it is discarded and ignored.
  332. /// </summary>
  333. /// <param name="g">The Graphics context to draw to.</param>
  334. /// <param name="rects">A list of rectangles to draw.</param>
  335. /// <param name="color">The color to fill the rectangles with.</param>
  336. /// <remarks>
  337. /// Note to implementors: This method is used to avoid drawing with GDI+, which avoids flickering
  338. /// with our transparent toolforms. Implementations may thunk straight to g.FillRectangle().
  339. /// </remarks>
  340. public static void FillRectangles(Graphics g, Color color, Rectangle[] rects)
  341. {
  342. try
  343. {
  344. FillRectanglesImpl(g, color, rects);
  345. }
  346. catch (Exception ex)
  347. {
  348. Tracing.Ping("Exception while executing PdnGraphics.FillRectangles: " + ex.ToString());
  349. }
  350. }
  351. private static void FillRectanglesImpl(Graphics g, Color color, Rectangle[] rects)
  352. {
  353. uint nativeColor = (uint)(color.R + (color.G << 8) + (color.B << 16));
  354. IntPtr hdc = IntPtr.Zero;
  355. IntPtr brush = IntPtr.Zero;
  356. IntPtr oldObject = IntPtr.Zero;
  357. try
  358. {
  359. hdc = g.GetHdc();
  360. brush = SafeNativeMethods.CreateSolidBrush(nativeColor);
  361. if (brush == IntPtr.Zero)
  362. {
  363. NativeMethods.ThrowOnWin32Error("CreateSolidBrush returned NULL");
  364. }
  365. oldObject = SafeNativeMethods.SelectObject(hdc, brush);
  366. foreach (Rectangle rect in rects)
  367. {
  368. NativeStructs.RECT nativeRect;
  369. nativeRect.left = rect.Left;
  370. nativeRect.top = rect.Top;
  371. nativeRect.right = rect.Right;
  372. nativeRect.bottom = rect.Bottom;
  373. int result = SafeNativeMethods.FillRect(hdc, ref nativeRect, brush);
  374. if (result == 0)
  375. {
  376. NativeMethods.ThrowOnWin32Error("FillRect returned zero");
  377. }
  378. }
  379. }
  380. finally
  381. {
  382. if (oldObject != IntPtr.Zero)
  383. {
  384. SafeNativeMethods.SelectObject(hdc, oldObject);
  385. oldObject = IntPtr.Zero;
  386. }
  387. if (brush != IntPtr.Zero)
  388. {
  389. SafeNativeMethods.DeleteObject(brush);
  390. brush = IntPtr.Zero;
  391. }
  392. if (hdc != IntPtr.Zero)
  393. {
  394. g.ReleaseHdc(hdc);
  395. hdc = IntPtr.Zero;
  396. }
  397. }
  398. GC.KeepAlive(g);
  399. }
  400. }
  401. }