skia_utils_win.cc 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. // Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "skia/ext/skia_utils_win.h"
  5. #include <stddef.h>
  6. #include <windows.h>
  7. #include "base/check_op.h"
  8. #include "base/debug/gdi_debug_util_win.h"
  9. #include "base/numerics/checked_math.h"
  10. #include "base/win/scoped_hdc.h"
  11. #include "base/win/scoped_hglobal.h"
  12. #include "skia/ext/legacy_display_globals.h"
  13. #include "skia/ext/skia_utils_base.h"
  14. #include "third_party/skia/include/core/SkColorSpace.h"
  15. #include "third_party/skia/include/core/SkRect.h"
  16. #include "third_party/skia/include/core/SkSurface.h"
  17. #include "third_party/skia/include/core/SkTypes.h"
  18. namespace {
  19. static_assert(offsetof(RECT, left) == offsetof(SkIRect, fLeft), "o1");
  20. static_assert(offsetof(RECT, top) == offsetof(SkIRect, fTop), "o2");
  21. static_assert(offsetof(RECT, right) == offsetof(SkIRect, fRight), "o3");
  22. static_assert(offsetof(RECT, bottom) == offsetof(SkIRect, fBottom), "o4");
  23. static_assert(sizeof(RECT().left) == sizeof(SkIRect().fLeft), "o5");
  24. static_assert(sizeof(RECT().top) == sizeof(SkIRect().fTop), "o6");
  25. static_assert(sizeof(RECT().right) == sizeof(SkIRect().fRight), "o7");
  26. static_assert(sizeof(RECT().bottom) == sizeof(SkIRect().fBottom), "o8");
  27. static_assert(sizeof(RECT) == sizeof(SkIRect), "o9");
  28. void CreateBitmapHeaderWithColorDepth(LONG width,
  29. LONG height,
  30. WORD color_depth,
  31. BITMAPINFOHEADER* hdr) {
  32. // These values are shared with gfx::PlatformDevice.
  33. hdr->biSize = sizeof(BITMAPINFOHEADER);
  34. hdr->biWidth = width;
  35. hdr->biHeight = -height; // Minus means top-down bitmap.
  36. hdr->biPlanes = 1;
  37. hdr->biBitCount = color_depth;
  38. hdr->biCompression = BI_RGB; // No compression.
  39. hdr->biSizeImage = 0;
  40. hdr->biXPelsPerMeter = 1;
  41. hdr->biYPelsPerMeter = 1;
  42. hdr->biClrUsed = 0;
  43. hdr->biClrImportant = 0;
  44. }
  45. // Fills in a BITMAPV5HEADER structure. This is to be used for images that have
  46. // an alpha channel and are in the ARGB8888 format. This is because DIBV5 has an
  47. // explicit mask for each component which default to XRGB and we manually set
  48. // flag so the alpha channel is the first byte. This is not supported by the
  49. // older-style BITMAPINFOHEADER.
  50. void CreateBitmapV5HeaderForARGB8888(LONG width,
  51. LONG height,
  52. LONG image_size,
  53. BITMAPV5HEADER* hdr) {
  54. memset(hdr, 0, sizeof(BITMAPV5HEADER));
  55. hdr->bV5Size = sizeof(BITMAPV5HEADER);
  56. hdr->bV5Width = width;
  57. // If height is positive this means that the image will be bottom-up.
  58. hdr->bV5Height = height;
  59. hdr->bV5Planes = 1;
  60. hdr->bV5BitCount = 32;
  61. hdr->bV5Compression = BI_RGB;
  62. hdr->bV5AlphaMask = 0xff000000;
  63. hdr->bV5CSType = LCS_WINDOWS_COLOR_SPACE;
  64. hdr->bV5Intent = LCS_GM_IMAGES;
  65. hdr->bV5ClrUsed = 0;
  66. hdr->bV5ClrImportant = 0;
  67. hdr->bV5ProfileData = 0;
  68. }
  69. } // namespace
  70. namespace skia {
  71. POINT SkPointToPOINT(const SkPoint& point) {
  72. POINT win_point = {
  73. SkScalarRoundToInt(point.fX), SkScalarRoundToInt(point.fY)
  74. };
  75. return win_point;
  76. }
  77. SkRect RECTToSkRect(const RECT& rect) {
  78. SkRect sk_rect = { SkIntToScalar(rect.left), SkIntToScalar(rect.top),
  79. SkIntToScalar(rect.right), SkIntToScalar(rect.bottom) };
  80. return sk_rect;
  81. }
  82. SkColor COLORREFToSkColor(COLORREF color) {
  83. #ifndef _MSC_VER
  84. return SkColorSetRGB(GetRValue(color), GetGValue(color), GetBValue(color));
  85. #else
  86. // ARGB = 0xFF000000 | ((0BGR -> RGB0) >> 8)
  87. return 0xFF000000u | (_byteswap_ulong(color) >> 8);
  88. #endif
  89. }
  90. COLORREF SkColorToCOLORREF(SkColor color) {
  91. #ifndef _MSC_VER
  92. return RGB(SkColorGetR(color), SkColorGetG(color), SkColorGetB(color));
  93. #else
  94. // 0BGR = ((ARGB -> BGRA) >> 8)
  95. return (_byteswap_ulong(color) >> 8);
  96. #endif
  97. }
  98. void InitializeDC(HDC context) {
  99. // Enables world transformation.
  100. // If the GM_ADVANCED graphics mode is set, GDI always draws arcs in the
  101. // counterclockwise direction in logical space. This is equivalent to the
  102. // statement that, in the GM_ADVANCED graphics mode, both arc control points
  103. // and arcs themselves fully respect the device context's world-to-device
  104. // transformation.
  105. BOOL res = SetGraphicsMode(context, GM_ADVANCED);
  106. SkASSERT(res != 0);
  107. // Enables dithering.
  108. res = SetStretchBltMode(context, HALFTONE);
  109. SkASSERT(res != 0);
  110. // As per SetStretchBltMode() documentation, SetBrushOrgEx() must be called
  111. // right after.
  112. res = SetBrushOrgEx(context, 0, 0, NULL);
  113. SkASSERT(res != 0);
  114. // Sets up default orientation.
  115. res = SetArcDirection(context, AD_CLOCKWISE);
  116. SkASSERT(res != 0);
  117. // Sets up default colors.
  118. res = SetBkColor(context, RGB(255, 255, 255));
  119. SkASSERT(res != CLR_INVALID);
  120. res = SetTextColor(context, RGB(0, 0, 0));
  121. SkASSERT(res != CLR_INVALID);
  122. res = SetDCBrushColor(context, RGB(255, 255, 255));
  123. SkASSERT(res != CLR_INVALID);
  124. res = SetDCPenColor(context, RGB(0, 0, 0));
  125. SkASSERT(res != CLR_INVALID);
  126. // Sets up default transparency.
  127. res = SetBkMode(context, OPAQUE);
  128. SkASSERT(res != 0);
  129. res = SetROP2(context, R2_COPYPEN);
  130. SkASSERT(res != 0);
  131. }
  132. void LoadTransformToDC(HDC dc, const SkMatrix& matrix) {
  133. XFORM xf;
  134. xf.eM11 = matrix[SkMatrix::kMScaleX];
  135. xf.eM21 = matrix[SkMatrix::kMSkewX];
  136. xf.eDx = matrix[SkMatrix::kMTransX];
  137. xf.eM12 = matrix[SkMatrix::kMSkewY];
  138. xf.eM22 = matrix[SkMatrix::kMScaleY];
  139. xf.eDy = matrix[SkMatrix::kMTransY];
  140. SetWorldTransform(dc, &xf);
  141. }
  142. void CopyHDC(HDC source, HDC destination, int x, int y, bool is_opaque,
  143. const RECT& src_rect, const SkMatrix& transform) {
  144. int copy_width = src_rect.right - src_rect.left;
  145. int copy_height = src_rect.bottom - src_rect.top;
  146. // We need to reset the translation for our bitmap or (0,0) won't be in the
  147. // upper left anymore
  148. SkMatrix identity;
  149. identity.reset();
  150. LoadTransformToDC(source, identity);
  151. if (is_opaque) {
  152. BitBlt(destination,
  153. x,
  154. y,
  155. copy_width,
  156. copy_height,
  157. source,
  158. src_rect.left,
  159. src_rect.top,
  160. SRCCOPY);
  161. } else {
  162. SkASSERT(copy_width != 0 && copy_height != 0);
  163. BLENDFUNCTION blend_function = {AC_SRC_OVER, 0, 255, AC_SRC_ALPHA};
  164. GdiAlphaBlend(destination,
  165. x,
  166. y,
  167. copy_width,
  168. copy_height,
  169. source,
  170. src_rect.left,
  171. src_rect.top,
  172. copy_width,
  173. copy_height,
  174. blend_function);
  175. }
  176. LoadTransformToDC(source, transform);
  177. }
  178. SkImageInfo PrepareAllocation(HDC context, BITMAP* backing) {
  179. HBITMAP backing_handle =
  180. static_cast<HBITMAP>(GetCurrentObject(context, OBJ_BITMAP));
  181. const size_t backing_size = sizeof *backing;
  182. return (GetObject(backing_handle, backing_size, backing) == backing_size)
  183. ? SkImageInfo::MakeN32Premul(backing->bmWidth, backing->bmHeight)
  184. : SkImageInfo();
  185. }
  186. sk_sp<SkSurface> MapPlatformSurface(HDC context) {
  187. BITMAP backing;
  188. const SkImageInfo size(PrepareAllocation(context, &backing));
  189. SkSurfaceProps props = skia::LegacyDisplayGlobals::GetSkSurfaceProps();
  190. return size.isEmpty()
  191. ? nullptr
  192. : SkSurface::MakeRasterDirect(size, backing.bmBits,
  193. backing.bmWidthBytes, &props);
  194. }
  195. SkBitmap MapPlatformBitmap(HDC context) {
  196. BITMAP backing;
  197. const SkImageInfo size(PrepareAllocation(context, &backing));
  198. SkBitmap bitmap;
  199. if (!size.isEmpty())
  200. bitmap.installPixels(size, backing.bmBits, size.minRowBytes());
  201. return bitmap;
  202. }
  203. void CreateBitmapHeaderForN32SkBitmap(const SkBitmap& bitmap,
  204. BITMAPINFOHEADER* hdr) {
  205. // Native HBITMAPs are XRGB-backed, and we expect SkBitmaps that we will use
  206. // with them to also be of the same format.
  207. CHECK_EQ(bitmap.colorType(), kN32_SkColorType);
  208. // The header will be for an RGB bitmap with 32 bits-per-pixel. The SkBitmap
  209. // data to go into the bitmap should be of the same size. If the SkBitmap
  210. // SkColorType is for a larger number of bits-per-pixel, copying the SkBitmap
  211. // into the HBITMAP for this header would cause a write out-of-bounds.
  212. CHECK_EQ(4, bitmap.info().bytesPerPixel());
  213. // The HBITMAP's bytes will always be tightly packed so we expect the SkBitmap
  214. // to be also. Row padding would mean the number of bytes in the SkBitmap and
  215. // in the HBITMAP for this header would be different, which can cause out-of-
  216. // bound reads or writes.
  217. CHECK_EQ(bitmap.rowBytes(), bitmap.width() * static_cast<size_t>(4));
  218. CreateBitmapHeaderWithColorDepth(bitmap.width(), bitmap.height(), 32, hdr);
  219. }
  220. HGLOBAL CreateHGlobalForByteArray(
  221. const std::vector<unsigned char>& byte_array) {
  222. HGLOBAL hglobal = ::GlobalAlloc(GHND, byte_array.size());
  223. if (!hglobal) {
  224. return nullptr;
  225. }
  226. base::win::ScopedHGlobal<uint8_t*> global_mem(hglobal);
  227. if (!global_mem.get()) {
  228. ::GlobalFree(hglobal);
  229. return nullptr;
  230. }
  231. memcpy(global_mem.get(), byte_array.data(), byte_array.size());
  232. return hglobal;
  233. }
  234. HGLOBAL CreateDIBV5ImageDataFromN32SkBitmap(const SkBitmap& bitmap) {
  235. // While DIBV5 support bit flags which would allow us to put channels in a any
  236. // order, we require an ARGB format because it is more convenient to use.
  237. CHECK_EQ(bitmap.colorType(), kN32_SkColorType);
  238. // The header will be for an ARGB bitmap with 32 bits-per-pixel. The SkBitmap
  239. // data to go into the bitmap should be of the same size. If the SkBitmap
  240. // SkColorType is for a larger number of bits-per-pixel, copying the SkBitmap
  241. // into the DIBV5ImageData for this header would cause a write out-of-bounds.
  242. CHECK_EQ(4, bitmap.info().bytesPerPixel());
  243. // The DIBV5ImageData bytes will always be tightly packed so we expect the
  244. // SkBitmap to be also. Row padding would mean the number of bytes in the
  245. // SkBitmap and in the DIBV5ImageData for this header would be different,
  246. // which can cause out-of- bound reads or writes.
  247. CHECK_EQ(bitmap.rowBytes(), bitmap.width() * static_cast<size_t>(4));
  248. int width = bitmap.width();
  249. int height = bitmap.height();
  250. size_t bytes;
  251. // Native DIBV5 bitmaps store 32-bit ARGB data, and the SkBitmap used with it
  252. // must also, as verified at the start of this function. A size_t type causes
  253. // a type change from int when multiplying.
  254. constexpr size_t bpp = 4;
  255. if (!base::CheckMul(height, base::CheckMul(width, bpp)).AssignIfValid(&bytes))
  256. return nullptr;
  257. HGLOBAL hglobal = ::GlobalAlloc(GHND, sizeof(BITMAPV5HEADER) + bytes);
  258. if (hglobal == nullptr)
  259. return nullptr;
  260. base::win::ScopedHGlobal<BITMAPV5HEADER*> header(hglobal);
  261. if (!header.get()) {
  262. ::GlobalFree(hglobal);
  263. return nullptr;
  264. }
  265. CreateBitmapV5HeaderForARGB8888(width, height, bytes, header.get());
  266. auto* dst_pixels =
  267. reinterpret_cast<uint8_t*>(header.get()) + sizeof(BITMAPV5HEADER);
  268. // CreateBitmapV5HeaderForARGB8888 creates a bitmap with a positive height as
  269. // stated in the image's header. Having a positive value implies that the
  270. // image is stored bottom-up. As skia uses the opposite, we have to flip
  271. // vertically so the image's content while copying in the DIBV5 data structure
  272. // to account for that. In theory, we could use a negative value to avoid the
  273. // flip, but not all programs treat a negative value properly.
  274. SkImageInfo infoSRGB = bitmap.info()
  275. .makeColorSpace(SkColorSpace::MakeSRGB())
  276. .makeWH(bitmap.width(), 1);
  277. const size_t row_bytes = bitmap.rowBytes();
  278. for (size_t line = 0; line < height; line++) {
  279. size_t flipped_line_index = height - 1 - line;
  280. auto* current_dst = dst_pixels + (row_bytes * flipped_line_index);
  281. bool success = bitmap.readPixels(infoSRGB, current_dst, row_bytes, 0, line);
  282. DCHECK(success);
  283. }
  284. return hglobal;
  285. }
  286. base::win::ScopedBitmap CreateHBitmapFromN32SkBitmap(const SkBitmap& bitmap) {
  287. BITMAPINFOHEADER header;
  288. CreateBitmapHeaderForN32SkBitmap(bitmap, &header);
  289. int width = bitmap.width();
  290. int height = bitmap.height();
  291. size_t bytes;
  292. // Native HBITMAPs store 32-bit RGB data, and the SkBitmap used with it must
  293. // also, as verified by CreateBitmapHeaderForN32SkBitmap(). A size_t type
  294. // causes a type change from int when multiplying.
  295. const size_t bpp = 4;
  296. if (!base::CheckMul(height, base::CheckMul(width, bpp)).AssignIfValid(&bytes))
  297. return {};
  298. void* bits;
  299. HBITMAP hbitmap;
  300. {
  301. base::win::ScopedGetDC screen_dc(nullptr);
  302. // By giving a null hSection, the |bits| will be destroyed when the
  303. // |hbitmap| is destroyed.
  304. hbitmap =
  305. CreateDIBSection(screen_dc, reinterpret_cast<BITMAPINFO*>(&header),
  306. DIB_RGB_COLORS, &bits, nullptr, 0);
  307. }
  308. if (hbitmap) {
  309. memcpy(bits, bitmap.getPixels(), bytes);
  310. } else {
  311. // If CreateDIBSection() failed, try to get some useful information out
  312. // before we crash for post-mortem analysis.
  313. base::debug::CollectGDIUsageAndDie(&header, nullptr);
  314. }
  315. return base::win::ScopedBitmap(hbitmap);
  316. }
  317. void CreateBitmapHeaderForXRGB888(int width,
  318. int height,
  319. BITMAPINFOHEADER* hdr) {
  320. CreateBitmapHeaderWithColorDepth(width, height, 32, hdr);
  321. }
  322. base::win::ScopedBitmap CreateHBitmapXRGB8888(int width,
  323. int height,
  324. HANDLE shared_section,
  325. void** data) {
  326. // CreateDIBSection fails to allocate anything if we try to create an empty
  327. // bitmap, so just create a minimal bitmap.
  328. if ((width == 0) || (height == 0)) {
  329. width = 1;
  330. height = 1;
  331. }
  332. BITMAPINFOHEADER hdr = {0};
  333. CreateBitmapHeaderWithColorDepth(width, height, 32, &hdr);
  334. HBITMAP hbitmap = CreateDIBSection(NULL, reinterpret_cast<BITMAPINFO*>(&hdr),
  335. 0, data, shared_section, 0);
  336. // If CreateDIBSection() failed, try to get some useful information out
  337. // before we crash for post-mortem analysis.
  338. if (!hbitmap)
  339. base::debug::CollectGDIUsageAndDie(&hdr, shared_section);
  340. return base::win::ScopedBitmap(hbitmap);
  341. }
  342. } // namespace skia