Bug 1777519 [wpt PR 34660] - Avoid OSError from --kill-safari stat'ing random paths...
[gecko.git] / widget / windows / nsWindowGfx.cpp
blob395095f365d4e0ea72bd6660f2f36769660ab45c
1 /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
6 /*
7 * nsWindowGfx - Painting and aceleration.
8 */
10 /**************************************************************
11 **************************************************************
13 ** BLOCK: Includes
15 ** Include headers.
17 **************************************************************
18 **************************************************************/
20 #include "mozilla/dom/ContentParent.h"
22 #include "nsWindowGfx.h"
23 #include "nsAppRunner.h"
24 #include <windows.h>
25 #include "gfxEnv.h"
26 #include "gfxImageSurface.h"
27 #include "gfxUtils.h"
28 #include "gfxWindowsSurface.h"
29 #include "gfxWindowsPlatform.h"
30 #include "gfxDWriteFonts.h"
31 #include "mozilla/gfx/2D.h"
32 #include "mozilla/gfx/DataSurfaceHelpers.h"
33 #include "mozilla/gfx/Tools.h"
34 #include "mozilla/RefPtr.h"
35 #include "mozilla/UniquePtrExtensions.h"
36 #include "nsGfxCIID.h"
37 #include "gfxContext.h"
38 #include "WinUtils.h"
39 #include "WinWindowOcclusionTracker.h"
40 #include "nsIWidgetListener.h"
41 #include "mozilla/Unused.h"
42 #include "nsDebug.h"
44 #include "mozilla/gfx/GPUProcessManager.h"
45 #include "mozilla/layers/CompositorBridgeParent.h"
46 #include "mozilla/layers/CompositorBridgeChild.h"
47 #include "InProcessWinCompositorWidget.h"
49 #include "nsUXThemeData.h"
50 #include "nsUXThemeConstants.h"
52 using namespace mozilla;
53 using namespace mozilla::gfx;
54 using namespace mozilla::layers;
55 using namespace mozilla::widget;
56 using namespace mozilla::plugins;
57 extern mozilla::LazyLogModule gWindowsLog;
59 /**************************************************************
60 **************************************************************
62 ** BLOCK: Variables
64 ** nsWindow Class static initializations and global variables.
66 **************************************************************
67 **************************************************************/
69 /**************************************************************
71 * SECTION: nsWindow statics
73 **************************************************************/
75 static UniquePtr<uint8_t[]> sSharedSurfaceData;
76 static IntSize sSharedSurfaceSize;
78 struct IconMetrics {
79 int32_t xMetric;
80 int32_t yMetric;
81 int32_t defaultSize;
84 // Corresponds 1:1 to the IconSizeType enum
85 static IconMetrics sIconMetrics[] = {
86 {SM_CXSMICON, SM_CYSMICON, 16}, // small icon
87 {SM_CXICON, SM_CYICON, 32} // regular icon
90 /**************************************************************
91 **************************************************************
93 ** BLOCK: nsWindow impl.
95 ** Paint related nsWindow methods.
97 **************************************************************
98 **************************************************************/
100 // GetRegionToPaint returns the invalidated region that needs to be painted
101 LayoutDeviceIntRegion nsWindow::GetRegionToPaint(bool aForceFullRepaint,
102 PAINTSTRUCT ps, HDC aDC) {
103 if (aForceFullRepaint) {
104 RECT paintRect;
105 ::GetClientRect(mWnd, &paintRect);
106 return LayoutDeviceIntRegion(WinUtils::ToIntRect(paintRect));
109 HRGN paintRgn = ::CreateRectRgn(0, 0, 0, 0);
110 if (paintRgn != nullptr) {
111 int result = GetRandomRgn(aDC, paintRgn, SYSRGN);
112 if (result == 1) {
113 POINT pt = {0, 0};
114 ::MapWindowPoints(nullptr, mWnd, &pt, 1);
115 ::OffsetRgn(paintRgn, pt.x, pt.y);
117 LayoutDeviceIntRegion rgn(WinUtils::ConvertHRGNToRegion(paintRgn));
118 ::DeleteObject(paintRgn);
119 return rgn;
121 return LayoutDeviceIntRegion(WinUtils::ToIntRect(ps.rcPaint));
124 nsIWidgetListener* nsWindow::GetPaintListener() {
125 if (mDestroyCalled) return nullptr;
126 return mAttachedWidgetListener ? mAttachedWidgetListener : mWidgetListener;
129 void nsWindow::ForcePresent() {
130 if (mResizeState != RESIZING) {
131 if (CompositorBridgeChild* remoteRenderer = GetRemoteRenderer()) {
132 remoteRenderer->SendForcePresent(wr::RenderReasons::WIDGET);
137 bool nsWindow::OnPaint(HDC aDC, uint32_t aNestingLevel) {
138 DeviceResetReason resetReason = DeviceResetReason::OK;
139 if (gfxWindowsPlatform::GetPlatform()->DidRenderingDeviceReset(
140 &resetReason)) {
141 gfxCriticalNote << "(nsWindow) Detected device reset: " << (int)resetReason;
143 gfxWindowsPlatform::GetPlatform()->UpdateRenderMode();
145 bool guilty;
146 switch (resetReason) {
147 case DeviceResetReason::HUNG:
148 case DeviceResetReason::RESET:
149 case DeviceResetReason::INVALID_CALL:
150 guilty = true;
151 break;
152 default:
153 guilty = false;
154 break;
157 GPUProcessManager::Get()->OnInProcessDeviceReset(guilty);
159 gfxCriticalNote << "(nsWindow) Finished device reset.";
160 return false;
163 PAINTSTRUCT ps;
165 // Avoid starting the GPU process for the initial navigator:blank window.
166 if (mIsEarlyBlankWindow) {
167 // Call BeginPaint/EndPaint or Windows will keep sending us messages.
168 ::BeginPaint(mWnd, &ps);
169 ::EndPaint(mWnd, &ps);
170 return true;
173 WindowRenderer* renderer = GetWindowRenderer();
174 KnowsCompositor* knowsCompositor = renderer->AsKnowsCompositor();
175 WebRenderLayerManager* layerManager = renderer->AsWebRender();
177 // Clear window by transparent black when compositor window is used in GPU
178 // process and non-client area rendering by DWM is enabled.
179 // It is for showing non-client area rendering. See nsWindow::UpdateGlass().
180 if (HasGlass() && knowsCompositor && knowsCompositor->GetUseCompositorWnd()) {
181 HDC hdc;
182 RECT rect;
183 hdc = ::GetWindowDC(mWnd);
184 ::GetWindowRect(mWnd, &rect);
185 ::MapWindowPoints(nullptr, mWnd, (LPPOINT)&rect, 2);
186 ::FillRect(hdc, &rect,
187 reinterpret_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)));
188 ReleaseDC(mWnd, hdc);
191 if (knowsCompositor && layerManager &&
192 !mBounds.IsEqualEdges(mLastPaintBounds)) {
193 // Do an early async composite so that we at least have something on the
194 // screen in the right place, even if the content is out of date.
195 layerManager->ScheduleComposite(wr::RenderReasons::WIDGET);
197 mLastPaintBounds = mBounds;
199 if (!aDC && (renderer->GetBackendType() == LayersBackend::LAYERS_NONE) &&
200 (TransparencyMode::Transparent == mTransparencyMode)) {
201 // For layered translucent windows all drawing should go to memory DC and no
202 // WM_PAINT messages are normally generated. To support asynchronous
203 // painting we force generation of WM_PAINT messages by invalidating window
204 // areas with RedrawWindow, InvalidateRect or InvalidateRgn function calls.
205 // BeginPaint/EndPaint must be called to make Windows think that invalid
206 // area is painted. Otherwise it will continue sending the same message
207 // endlessly.
208 ::BeginPaint(mWnd, &ps);
209 ::EndPaint(mWnd, &ps);
211 // We're guaranteed to have a widget proxy since we called
212 // GetLayerManager().
213 aDC = mBasicLayersSurface->GetTransparentDC();
216 HDC hDC = aDC ? aDC : (::BeginPaint(mWnd, &ps));
217 mPaintDC = hDC;
219 bool forceRepaint =
220 aDC || (TransparencyMode::Transparent == mTransparencyMode);
221 LayoutDeviceIntRegion region = GetRegionToPaint(forceRepaint, ps, hDC);
223 if (knowsCompositor && layerManager) {
224 // We need to paint to the screen even if nothing changed, since if we
225 // don't have a compositing window manager, our pixels could be stale.
226 layerManager->SetNeedsComposite(true);
227 layerManager->SendInvalidRegion(region.ToUnknownRegion());
230 RefPtr<nsWindow> strongThis(this);
232 nsIWidgetListener* listener = GetPaintListener();
233 if (listener) {
234 listener->WillPaintWindow(this);
236 // Re-get the listener since the will paint notification may have killed it.
237 listener = GetPaintListener();
238 if (!listener) {
239 return false;
242 if (knowsCompositor && layerManager && layerManager->NeedsComposite()) {
243 layerManager->ScheduleComposite(wr::RenderReasons::WIDGET);
244 layerManager->SetNeedsComposite(false);
247 bool result = true;
248 if (!region.IsEmpty() && listener) {
249 // Should probably pass in a real region here, using GetRandomRgn
250 // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/clipping_4q0e.asp
252 #ifdef WIDGET_DEBUG_OUTPUT
253 debug_DumpPaintEvent(stdout, this, region.ToUnknownRegion(), "noname",
254 (int32_t)mWnd);
255 #endif // WIDGET_DEBUG_OUTPUT
257 switch (renderer->GetBackendType()) {
258 case LayersBackend::LAYERS_NONE: {
259 RefPtr<gfxASurface> targetSurface;
261 // don't support transparency for non-GDI rendering, for now
262 if (TransparencyMode::Transparent == mTransparencyMode) {
263 // This mutex needs to be held when EnsureTransparentSurface is
264 // called.
265 MutexAutoLock lock(mBasicLayersSurface->GetTransparentSurfaceLock());
266 targetSurface = mBasicLayersSurface->EnsureTransparentSurface();
269 RefPtr<gfxWindowsSurface> targetSurfaceWin;
270 if (!targetSurface) {
271 uint32_t flags = (mTransparencyMode == TransparencyMode::Opaque)
273 : gfxWindowsSurface::FLAG_IS_TRANSPARENT;
274 targetSurfaceWin = new gfxWindowsSurface(hDC, flags);
275 targetSurface = targetSurfaceWin;
278 if (!targetSurface) {
279 NS_ERROR("Invalid RenderMode!");
280 return false;
283 RECT paintRect;
284 ::GetClientRect(mWnd, &paintRect);
285 RefPtr<DrawTarget> dt = gfxPlatform::CreateDrawTargetForSurface(
286 targetSurface, IntSize(paintRect.right - paintRect.left,
287 paintRect.bottom - paintRect.top));
288 if (!dt || !dt->IsValid()) {
289 gfxWarning()
290 << "nsWindow::OnPaint failed in CreateDrawTargetForSurface";
291 return false;
294 // don't need to double buffer with anything but GDI
295 BufferMode doubleBuffering = mozilla::layers::BufferMode::BUFFER_NONE;
296 switch (mTransparencyMode) {
297 case TransparencyMode::BorderlessGlass:
298 default:
299 // If we're not doing translucency, then double buffer
300 doubleBuffering = mozilla::layers::BufferMode::BUFFERED;
301 break;
302 case TransparencyMode::Transparent:
303 // If we're rendering with translucency, we're going to be
304 // rendering the whole window; make sure we clear it first
305 dt->ClearRect(
306 Rect(0.f, 0.f, dt->GetSize().width, dt->GetSize().height));
307 break;
310 RefPtr<gfxContext> thebesContext = gfxContext::CreateOrNull(dt);
311 MOZ_ASSERT(thebesContext); // already checked draw target above
314 AutoLayerManagerSetup setupLayerManager(this, thebesContext,
315 doubleBuffering);
316 result = listener->PaintWindow(this, region);
319 if (TransparencyMode::Transparent == mTransparencyMode) {
320 // Data from offscreen drawing surface was copied to memory bitmap of
321 // transparent bitmap. Now it can be read from memory bitmap to apply
322 // alpha channel and after that displayed on the screen.
323 mBasicLayersSurface->RedrawTransparentWindow();
325 } break;
326 case LayersBackend::LAYERS_WR: {
327 result = listener->PaintWindow(this, region);
328 if (!gfxEnv::MOZ_DISABLE_FORCE_PRESENT() &&
329 gfxWindowsPlatform::GetPlatform()->DwmCompositionEnabled()) {
330 nsCOMPtr<nsIRunnable> event = NewRunnableMethod(
331 "nsWindow::ForcePresent", this, &nsWindow::ForcePresent);
332 NS_DispatchToMainThread(event);
334 } break;
335 default:
336 NS_ERROR("Unknown layers backend used!");
337 break;
341 if (!aDC) {
342 ::EndPaint(mWnd, &ps);
345 mPaintDC = nullptr;
346 mLastPaintEndTime = TimeStamp::Now();
348 // Re-get the listener since painting may have killed it.
349 listener = GetPaintListener();
350 if (listener) listener->DidPaintWindow();
352 if (aNestingLevel == 0 && ::GetUpdateRect(mWnd, nullptr, false)) {
353 OnPaint(aDC, 1);
356 return result;
359 bool nsWindow::NeedsToTrackWindowOcclusionState() {
360 if (!WinWindowOcclusionTracker::Get()) {
361 return false;
364 if (mCompositorSession && mWindowType == WindowType::TopLevel) {
365 return true;
368 return false;
371 void nsWindow::NotifyOcclusionState(mozilla::widget::OcclusionState aState) {
372 MOZ_ASSERT(NeedsToTrackWindowOcclusionState());
374 bool isFullyOccluded = aState == mozilla::widget::OcclusionState::OCCLUDED;
375 // When window is minimized, it is not set as fully occluded.
376 if (mFrameState->GetSizeMode() == nsSizeMode_Minimized) {
377 isFullyOccluded = false;
380 // Don't dispatch if the new occlustion state is the same as the current
381 // state.
382 if (mIsFullyOccluded == isFullyOccluded) {
383 return;
386 mIsFullyOccluded = isFullyOccluded;
388 MOZ_LOG(gWindowsLog, LogLevel::Info,
389 ("nsWindow::NotifyOcclusionState() mIsFullyOccluded %d "
390 "mFrameState->GetSizeMode() %d",
391 mIsFullyOccluded, mFrameState->GetSizeMode()));
393 wr::DebugFlags flags{0};
394 flags.bits = gfx::gfxVars::WebRenderDebugFlags();
395 bool debugEnabled = bool(flags & wr::DebugFlags::WINDOW_VISIBILITY_DBG);
396 if (debugEnabled && mCompositorWidgetDelegate) {
397 mCompositorWidgetDelegate->NotifyVisibilityUpdated(
398 mFrameState->GetSizeMode(), mIsFullyOccluded);
401 if (mWidgetListener) {
402 mWidgetListener->OcclusionStateChanged(mIsFullyOccluded);
406 void nsWindow::MaybeEnableWindowOcclusion(bool aEnable) {
407 // WindowOcclusion is enabled/disabled only when compositor session exists.
408 // See nsWindow::NeedsToTrackWindowOcclusionState().
409 if (!mCompositorSession) {
410 return;
413 bool enabled = gfxConfig::IsEnabled(gfx::Feature::WINDOW_OCCLUSION);
415 if (aEnable) {
416 // Enable window occlusion.
417 if (enabled && NeedsToTrackWindowOcclusionState()) {
418 WinWindowOcclusionTracker::Get()->Enable(this, mWnd);
420 wr::DebugFlags flags{0};
421 flags.bits = gfx::gfxVars::WebRenderDebugFlags();
422 bool debugEnabled = bool(flags & wr::DebugFlags::WINDOW_VISIBILITY_DBG);
423 if (debugEnabled && mCompositorWidgetDelegate) {
424 mCompositorWidgetDelegate->NotifyVisibilityUpdated(
425 mFrameState->GetSizeMode(), mIsFullyOccluded);
428 return;
431 // Disable window occlusion.
432 MOZ_ASSERT(!aEnable);
434 if (!NeedsToTrackWindowOcclusionState()) {
435 return;
438 WinWindowOcclusionTracker::Get()->Disable(this, mWnd);
439 NotifyOcclusionState(OcclusionState::VISIBLE);
441 wr::DebugFlags flags{0};
442 flags.bits = gfx::gfxVars::WebRenderDebugFlags();
443 bool debugEnabled = bool(flags & wr::DebugFlags::WINDOW_VISIBILITY_DBG);
444 if (debugEnabled && mCompositorWidgetDelegate) {
445 mCompositorWidgetDelegate->NotifyVisibilityUpdated(
446 mFrameState->GetSizeMode(), mIsFullyOccluded);
450 // This override of CreateCompositor is to add support for sending the IPC
451 // call for RequesetFxrOutput as soon as the compositor for this widget is
452 // available.
453 void nsWindow::CreateCompositor() {
454 nsBaseWidget::CreateCompositor();
456 MaybeEnableWindowOcclusion(/* aEnable */ true);
458 if (mRequestFxrOutputPending) {
459 GetRemoteRenderer()->SendRequestFxrOutput();
463 void nsWindow::DestroyCompositor() {
464 MaybeEnableWindowOcclusion(/* aEnable */ false);
466 nsBaseWidget::DestroyCompositor();
469 void nsWindow::RequestFxrOutput() {
470 if (GetRemoteRenderer() != nullptr) {
471 MOZ_CRASH("RequestFxrOutput should happen before Compositor is created.");
472 } else {
473 // The compositor isn't ready, so indicate to make the IPC call when
474 // it is available.
475 mRequestFxrOutputPending = true;
479 LayoutDeviceIntSize nsWindowGfx::GetIconMetrics(IconSizeType aSizeType) {
480 int32_t width = ::GetSystemMetrics(sIconMetrics[aSizeType].xMetric);
481 int32_t height = ::GetSystemMetrics(sIconMetrics[aSizeType].yMetric);
483 if (width == 0 || height == 0) {
484 width = height = sIconMetrics[aSizeType].defaultSize;
487 return LayoutDeviceIntSize(width, height);
490 nsresult nsWindowGfx::CreateIcon(imgIContainer* aContainer, bool aIsCursor,
491 LayoutDeviceIntPoint aHotspot,
492 LayoutDeviceIntSize aScaledSize,
493 HICON* aIcon) {
494 MOZ_ASSERT(aHotspot.x >= 0 && aHotspot.y >= 0);
495 MOZ_ASSERT((aScaledSize.width > 0 && aScaledSize.height > 0) ||
496 (aScaledSize.width == 0 && aScaledSize.height == 0));
498 // Get the image data
499 RefPtr<SourceSurface> surface = aContainer->GetFrame(
500 imgIContainer::FRAME_CURRENT,
501 imgIContainer::FLAG_SYNC_DECODE | imgIContainer::FLAG_ASYNC_NOTIFY);
502 NS_ENSURE_TRUE(surface, NS_ERROR_NOT_AVAILABLE);
504 IntSize frameSize = surface->GetSize();
505 if (frameSize.IsEmpty()) {
506 return NS_ERROR_FAILURE;
509 IntSize iconSize(aScaledSize.width, aScaledSize.height);
510 if (iconSize == IntSize(0, 0)) { // use frame's intrinsic size
511 iconSize = frameSize;
514 RefPtr<DataSourceSurface> dataSurface;
515 bool mappedOK;
516 DataSourceSurface::MappedSurface map;
518 if (iconSize != frameSize) {
519 // Scale the surface
520 dataSurface =
521 Factory::CreateDataSourceSurface(iconSize, SurfaceFormat::B8G8R8A8);
522 NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
523 mappedOK = dataSurface->Map(DataSourceSurface::MapType::READ_WRITE, &map);
524 NS_ENSURE_TRUE(mappedOK, NS_ERROR_FAILURE);
526 RefPtr<DrawTarget> dt = Factory::CreateDrawTargetForData(
527 BackendType::CAIRO, map.mData, dataSurface->GetSize(), map.mStride,
528 SurfaceFormat::B8G8R8A8);
529 if (!dt) {
530 gfxWarning()
531 << "nsWindowGfx::CreatesIcon failed in CreateDrawTargetForData";
532 return NS_ERROR_OUT_OF_MEMORY;
534 dt->DrawSurface(surface, Rect(0, 0, iconSize.width, iconSize.height),
535 Rect(0, 0, frameSize.width, frameSize.height),
536 DrawSurfaceOptions(),
537 DrawOptions(1.0f, CompositionOp::OP_SOURCE));
538 } else if (surface->GetFormat() != SurfaceFormat::B8G8R8A8) {
539 // Convert format to SurfaceFormat::B8G8R8A8
540 dataSurface = gfxUtils::CopySurfaceToDataSourceSurfaceWithFormat(
541 surface, SurfaceFormat::B8G8R8A8);
542 NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
543 mappedOK = dataSurface->Map(DataSourceSurface::MapType::READ, &map);
544 } else {
545 dataSurface = surface->GetDataSurface();
546 NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
547 mappedOK = dataSurface->Map(DataSourceSurface::MapType::READ, &map);
549 NS_ENSURE_TRUE(dataSurface && mappedOK, NS_ERROR_FAILURE);
550 MOZ_ASSERT(dataSurface->GetFormat() == SurfaceFormat::B8G8R8A8);
552 uint8_t* data = nullptr;
553 UniquePtr<uint8_t[]> autoDeleteArray;
554 if (map.mStride == BytesPerPixel(dataSurface->GetFormat()) * iconSize.width) {
555 // Mapped data is already packed
556 data = map.mData;
557 } else {
558 // We can't use map.mData since the pixels are not packed (as required by
559 // CreateDIBitmap, which is called under the DataToBitmap call below).
561 // We must unmap before calling SurfaceToPackedBGRA because it needs access
562 // to the pixel data.
563 dataSurface->Unmap();
564 map.mData = nullptr;
566 autoDeleteArray = SurfaceToPackedBGRA(dataSurface);
567 data = autoDeleteArray.get();
568 NS_ENSURE_TRUE(data, NS_ERROR_FAILURE);
571 HBITMAP bmp = DataToBitmap(data, iconSize.width, -iconSize.height, 32);
572 uint8_t* a1data = Data32BitTo1Bit(data, iconSize.width, iconSize.height);
573 if (map.mData) {
574 dataSurface->Unmap();
576 if (!a1data) {
577 return NS_ERROR_FAILURE;
580 HBITMAP mbmp = DataToBitmap(a1data, iconSize.width, -iconSize.height, 1);
581 free(a1data);
583 ICONINFO info = {0};
584 info.fIcon = !aIsCursor;
585 info.xHotspot = aHotspot.x;
586 info.yHotspot = aHotspot.y;
587 info.hbmMask = mbmp;
588 info.hbmColor = bmp;
590 HCURSOR icon = ::CreateIconIndirect(&info);
591 ::DeleteObject(mbmp);
592 ::DeleteObject(bmp);
593 if (!icon) return NS_ERROR_FAILURE;
594 *aIcon = icon;
595 return NS_OK;
598 // Adjust cursor image data
599 uint8_t* nsWindowGfx::Data32BitTo1Bit(uint8_t* aImageData, uint32_t aWidth,
600 uint32_t aHeight) {
601 // We need (aWidth + 7) / 8 bytes plus zero-padding up to a multiple of
602 // 4 bytes for each row (HBITMAP requirement). Bug 353553.
603 uint32_t outBpr = ((aWidth + 31) / 8) & ~3;
605 // Allocate and clear mask buffer
606 uint8_t* outData = (uint8_t*)calloc(outBpr, aHeight);
607 if (!outData) return nullptr;
609 int32_t* imageRow = (int32_t*)aImageData;
610 for (uint32_t curRow = 0; curRow < aHeight; curRow++) {
611 uint8_t* outRow = outData + curRow * outBpr;
612 uint8_t mask = 0x80;
613 for (uint32_t curCol = 0; curCol < aWidth; curCol++) {
614 // Use sign bit to test for transparency, as alpha byte is highest byte
615 if (*imageRow++ < 0) *outRow |= mask;
617 mask >>= 1;
618 if (!mask) {
619 outRow++;
620 mask = 0x80;
625 return outData;
629 * Convert the given image data to a HBITMAP. If the requested depth is
630 * 32 bit, a bitmap with an alpha channel will be returned.
632 * @param aImageData The image data to convert. Must use the format accepted
633 * by CreateDIBitmap.
634 * @param aWidth With of the bitmap, in pixels.
635 * @param aHeight Height of the image, in pixels.
636 * @param aDepth Image depth, in bits. Should be one of 1, 24 and 32.
638 * @return The HBITMAP representing the image. Caller should call
639 * DeleteObject when done with the bitmap.
640 * On failure, nullptr will be returned.
642 HBITMAP nsWindowGfx::DataToBitmap(uint8_t* aImageData, uint32_t aWidth,
643 uint32_t aHeight, uint32_t aDepth) {
644 HDC dc = ::GetDC(nullptr);
646 if (aDepth == 32) {
647 // Alpha channel. We need the new header.
648 BITMAPV4HEADER head = {0};
649 head.bV4Size = sizeof(head);
650 head.bV4Width = aWidth;
651 head.bV4Height = aHeight;
652 head.bV4Planes = 1;
653 head.bV4BitCount = aDepth;
654 head.bV4V4Compression = BI_BITFIELDS;
655 head.bV4SizeImage = 0; // Uncompressed
656 head.bV4XPelsPerMeter = 0;
657 head.bV4YPelsPerMeter = 0;
658 head.bV4ClrUsed = 0;
659 head.bV4ClrImportant = 0;
661 head.bV4RedMask = 0x00FF0000;
662 head.bV4GreenMask = 0x0000FF00;
663 head.bV4BlueMask = 0x000000FF;
664 head.bV4AlphaMask = 0xFF000000;
666 HBITMAP bmp = ::CreateDIBitmap(
667 dc, reinterpret_cast<CONST BITMAPINFOHEADER*>(&head), CBM_INIT,
668 aImageData, reinterpret_cast<CONST BITMAPINFO*>(&head), DIB_RGB_COLORS);
669 ::ReleaseDC(nullptr, dc);
670 return bmp;
673 char reserved_space[sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 2];
674 BITMAPINFOHEADER& head = *(BITMAPINFOHEADER*)reserved_space;
676 head.biSize = sizeof(BITMAPINFOHEADER);
677 head.biWidth = aWidth;
678 head.biHeight = aHeight;
679 head.biPlanes = 1;
680 head.biBitCount = (WORD)aDepth;
681 head.biCompression = BI_RGB;
682 head.biSizeImage = 0; // Uncompressed
683 head.biXPelsPerMeter = 0;
684 head.biYPelsPerMeter = 0;
685 head.biClrUsed = 0;
686 head.biClrImportant = 0;
688 BITMAPINFO& bi = *(BITMAPINFO*)reserved_space;
690 if (aDepth == 1) {
691 RGBQUAD black = {0, 0, 0, 0};
692 RGBQUAD white = {255, 255, 255, 0};
694 bi.bmiColors[0] = white;
695 bi.bmiColors[1] = black;
698 HBITMAP bmp =
699 ::CreateDIBitmap(dc, &head, CBM_INIT, aImageData, &bi, DIB_RGB_COLORS);
700 ::ReleaseDC(nullptr, dc);
701 return bmp;