Bug 1793629 - Implement attention indicator for the unified extensions button, r...
[gecko.git] / widget / windows / nsWindowGfx.cpp
blob1c321c00ed543872a2eb54523579828e0aa7f13d
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 (eTransparencyTransparent == 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 = aDC || (eTransparencyTransparent == mTransparencyMode);
220 LayoutDeviceIntRegion region = GetRegionToPaint(forceRepaint, ps, hDC);
222 if (knowsCompositor && layerManager) {
223 // We need to paint to the screen even if nothing changed, since if we
224 // don't have a compositing window manager, our pixels could be stale.
225 layerManager->SetNeedsComposite(true);
226 layerManager->SendInvalidRegion(region.ToUnknownRegion());
229 RefPtr<nsWindow> strongThis(this);
231 nsIWidgetListener* listener = GetPaintListener();
232 if (listener) {
233 listener->WillPaintWindow(this);
235 // Re-get the listener since the will paint notification may have killed it.
236 listener = GetPaintListener();
237 if (!listener) {
238 return false;
241 if (knowsCompositor && layerManager && layerManager->NeedsComposite()) {
242 layerManager->ScheduleComposite(wr::RenderReasons::WIDGET);
243 layerManager->SetNeedsComposite(false);
246 bool result = true;
247 if (!region.IsEmpty() && listener) {
248 // Should probably pass in a real region here, using GetRandomRgn
249 // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/clipping_4q0e.asp
251 #ifdef WIDGET_DEBUG_OUTPUT
252 debug_DumpPaintEvent(stdout, this, region.ToUnknownRegion(), "noname",
253 (int32_t)mWnd);
254 #endif // WIDGET_DEBUG_OUTPUT
256 switch (renderer->GetBackendType()) {
257 case LayersBackend::LAYERS_NONE: {
258 RefPtr<gfxASurface> targetSurface;
260 // don't support transparency for non-GDI rendering, for now
261 if (eTransparencyTransparent == mTransparencyMode) {
262 // This mutex needs to be held when EnsureTransparentSurface is
263 // called.
264 MutexAutoLock lock(mBasicLayersSurface->GetTransparentSurfaceLock());
265 targetSurface = mBasicLayersSurface->EnsureTransparentSurface();
268 RefPtr<gfxWindowsSurface> targetSurfaceWin;
269 if (!targetSurface) {
270 uint32_t flags = (mTransparencyMode == eTransparencyOpaque)
272 : gfxWindowsSurface::FLAG_IS_TRANSPARENT;
273 targetSurfaceWin = new gfxWindowsSurface(hDC, flags);
274 targetSurface = targetSurfaceWin;
277 if (!targetSurface) {
278 NS_ERROR("Invalid RenderMode!");
279 return false;
282 RECT paintRect;
283 ::GetClientRect(mWnd, &paintRect);
284 RefPtr<DrawTarget> dt = gfxPlatform::CreateDrawTargetForSurface(
285 targetSurface, IntSize(paintRect.right - paintRect.left,
286 paintRect.bottom - paintRect.top));
287 if (!dt || !dt->IsValid()) {
288 gfxWarning()
289 << "nsWindow::OnPaint failed in CreateDrawTargetForSurface";
290 return false;
293 // don't need to double buffer with anything but GDI
294 BufferMode doubleBuffering = mozilla::layers::BufferMode::BUFFER_NONE;
295 switch (mTransparencyMode) {
296 case eTransparencyGlass:
297 case eTransparencyBorderlessGlass:
298 default:
299 // If we're not doing translucency, then double buffer
300 doubleBuffering = mozilla::layers::BufferMode::BUFFERED;
301 break;
302 case eTransparencyTransparent:
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 (eTransparencyTransparent == 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 == eWindowType_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 bool enabled = gfxConfig::IsEnabled(gfx::Feature::WINDOW_OCCLUSION);
409 if (aEnable) {
410 // Enable window occlusion.
411 if (enabled && NeedsToTrackWindowOcclusionState()) {
412 WinWindowOcclusionTracker::Get()->Enable(this, mWnd);
414 wr::DebugFlags flags{0};
415 flags.bits = gfx::gfxVars::WebRenderDebugFlags();
416 bool debugEnabled = bool(flags & wr::DebugFlags::WINDOW_VISIBILITY_DBG);
417 if (debugEnabled && mCompositorWidgetDelegate) {
418 mCompositorWidgetDelegate->NotifyVisibilityUpdated(
419 mFrameState->GetSizeMode(), mIsFullyOccluded);
422 return;
425 // Disable window occlusion.
426 MOZ_ASSERT(!aEnable);
428 if (!NeedsToTrackWindowOcclusionState()) {
429 return;
432 WinWindowOcclusionTracker::Get()->Disable(this, mWnd);
433 NotifyOcclusionState(OcclusionState::VISIBLE);
435 wr::DebugFlags flags{0};
436 flags.bits = gfx::gfxVars::WebRenderDebugFlags();
437 bool debugEnabled = bool(flags & wr::DebugFlags::WINDOW_VISIBILITY_DBG);
438 if (debugEnabled && mCompositorWidgetDelegate) {
439 mCompositorWidgetDelegate->NotifyVisibilityUpdated(
440 mFrameState->GetSizeMode(), mIsFullyOccluded);
444 // This override of CreateCompositor is to add support for sending the IPC
445 // call for RequesetFxrOutput as soon as the compositor for this widget is
446 // available.
447 void nsWindow::CreateCompositor() {
448 nsBaseWidget::CreateCompositor();
450 MaybeEnableWindowOcclusion(/* aEnable */ true);
452 if (mRequestFxrOutputPending) {
453 GetRemoteRenderer()->SendRequestFxrOutput();
457 void nsWindow::DestroyCompositor() {
458 MaybeEnableWindowOcclusion(/* aEnable */ false);
460 nsBaseWidget::DestroyCompositor();
463 void nsWindow::RequestFxrOutput() {
464 if (GetRemoteRenderer() != nullptr) {
465 MOZ_CRASH("RequestFxrOutput should happen before Compositor is created.");
466 } else {
467 // The compositor isn't ready, so indicate to make the IPC call when
468 // it is available.
469 mRequestFxrOutputPending = true;
473 LayoutDeviceIntSize nsWindowGfx::GetIconMetrics(IconSizeType aSizeType) {
474 int32_t width = ::GetSystemMetrics(sIconMetrics[aSizeType].xMetric);
475 int32_t height = ::GetSystemMetrics(sIconMetrics[aSizeType].yMetric);
477 if (width == 0 || height == 0) {
478 width = height = sIconMetrics[aSizeType].defaultSize;
481 return LayoutDeviceIntSize(width, height);
484 nsresult nsWindowGfx::CreateIcon(imgIContainer* aContainer, bool aIsCursor,
485 LayoutDeviceIntPoint aHotspot,
486 LayoutDeviceIntSize aScaledSize,
487 HICON* aIcon) {
488 MOZ_ASSERT(aHotspot.x >= 0 && aHotspot.y >= 0);
489 MOZ_ASSERT((aScaledSize.width > 0 && aScaledSize.height > 0) ||
490 (aScaledSize.width == 0 && aScaledSize.height == 0));
492 // Get the image data
493 RefPtr<SourceSurface> surface = aContainer->GetFrame(
494 imgIContainer::FRAME_CURRENT,
495 imgIContainer::FLAG_SYNC_DECODE | imgIContainer::FLAG_ASYNC_NOTIFY);
496 NS_ENSURE_TRUE(surface, NS_ERROR_NOT_AVAILABLE);
498 IntSize frameSize = surface->GetSize();
499 if (frameSize.IsEmpty()) {
500 return NS_ERROR_FAILURE;
503 IntSize iconSize(aScaledSize.width, aScaledSize.height);
504 if (iconSize == IntSize(0, 0)) { // use frame's intrinsic size
505 iconSize = frameSize;
508 RefPtr<DataSourceSurface> dataSurface;
509 bool mappedOK;
510 DataSourceSurface::MappedSurface map;
512 if (iconSize != frameSize) {
513 // Scale the surface
514 dataSurface =
515 Factory::CreateDataSourceSurface(iconSize, SurfaceFormat::B8G8R8A8);
516 NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
517 mappedOK = dataSurface->Map(DataSourceSurface::MapType::READ_WRITE, &map);
518 NS_ENSURE_TRUE(mappedOK, NS_ERROR_FAILURE);
520 RefPtr<DrawTarget> dt = Factory::CreateDrawTargetForData(
521 BackendType::CAIRO, map.mData, dataSurface->GetSize(), map.mStride,
522 SurfaceFormat::B8G8R8A8);
523 if (!dt) {
524 gfxWarning()
525 << "nsWindowGfx::CreatesIcon failed in CreateDrawTargetForData";
526 return NS_ERROR_OUT_OF_MEMORY;
528 dt->DrawSurface(surface, Rect(0, 0, iconSize.width, iconSize.height),
529 Rect(0, 0, frameSize.width, frameSize.height),
530 DrawSurfaceOptions(),
531 DrawOptions(1.0f, CompositionOp::OP_SOURCE));
532 } else if (surface->GetFormat() != SurfaceFormat::B8G8R8A8) {
533 // Convert format to SurfaceFormat::B8G8R8A8
534 dataSurface = gfxUtils::CopySurfaceToDataSourceSurfaceWithFormat(
535 surface, SurfaceFormat::B8G8R8A8);
536 NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
537 mappedOK = dataSurface->Map(DataSourceSurface::MapType::READ, &map);
538 } else {
539 dataSurface = surface->GetDataSurface();
540 NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
541 mappedOK = dataSurface->Map(DataSourceSurface::MapType::READ, &map);
543 NS_ENSURE_TRUE(dataSurface && mappedOK, NS_ERROR_FAILURE);
544 MOZ_ASSERT(dataSurface->GetFormat() == SurfaceFormat::B8G8R8A8);
546 uint8_t* data = nullptr;
547 UniquePtr<uint8_t[]> autoDeleteArray;
548 if (map.mStride == BytesPerPixel(dataSurface->GetFormat()) * iconSize.width) {
549 // Mapped data is already packed
550 data = map.mData;
551 } else {
552 // We can't use map.mData since the pixels are not packed (as required by
553 // CreateDIBitmap, which is called under the DataToBitmap call below).
555 // We must unmap before calling SurfaceToPackedBGRA because it needs access
556 // to the pixel data.
557 dataSurface->Unmap();
558 map.mData = nullptr;
560 autoDeleteArray = SurfaceToPackedBGRA(dataSurface);
561 data = autoDeleteArray.get();
562 NS_ENSURE_TRUE(data, NS_ERROR_FAILURE);
565 HBITMAP bmp = DataToBitmap(data, iconSize.width, -iconSize.height, 32);
566 uint8_t* a1data = Data32BitTo1Bit(data, iconSize.width, iconSize.height);
567 if (map.mData) {
568 dataSurface->Unmap();
570 if (!a1data) {
571 return NS_ERROR_FAILURE;
574 HBITMAP mbmp = DataToBitmap(a1data, iconSize.width, -iconSize.height, 1);
575 free(a1data);
577 ICONINFO info = {0};
578 info.fIcon = !aIsCursor;
579 info.xHotspot = aHotspot.x;
580 info.yHotspot = aHotspot.y;
581 info.hbmMask = mbmp;
582 info.hbmColor = bmp;
584 HCURSOR icon = ::CreateIconIndirect(&info);
585 ::DeleteObject(mbmp);
586 ::DeleteObject(bmp);
587 if (!icon) return NS_ERROR_FAILURE;
588 *aIcon = icon;
589 return NS_OK;
592 // Adjust cursor image data
593 uint8_t* nsWindowGfx::Data32BitTo1Bit(uint8_t* aImageData, uint32_t aWidth,
594 uint32_t aHeight) {
595 // We need (aWidth + 7) / 8 bytes plus zero-padding up to a multiple of
596 // 4 bytes for each row (HBITMAP requirement). Bug 353553.
597 uint32_t outBpr = ((aWidth + 31) / 8) & ~3;
599 // Allocate and clear mask buffer
600 uint8_t* outData = (uint8_t*)calloc(outBpr, aHeight);
601 if (!outData) return nullptr;
603 int32_t* imageRow = (int32_t*)aImageData;
604 for (uint32_t curRow = 0; curRow < aHeight; curRow++) {
605 uint8_t* outRow = outData + curRow * outBpr;
606 uint8_t mask = 0x80;
607 for (uint32_t curCol = 0; curCol < aWidth; curCol++) {
608 // Use sign bit to test for transparency, as alpha byte is highest byte
609 if (*imageRow++ < 0) *outRow |= mask;
611 mask >>= 1;
612 if (!mask) {
613 outRow++;
614 mask = 0x80;
619 return outData;
623 * Convert the given image data to a HBITMAP. If the requested depth is
624 * 32 bit, a bitmap with an alpha channel will be returned.
626 * @param aImageData The image data to convert. Must use the format accepted
627 * by CreateDIBitmap.
628 * @param aWidth With of the bitmap, in pixels.
629 * @param aHeight Height of the image, in pixels.
630 * @param aDepth Image depth, in bits. Should be one of 1, 24 and 32.
632 * @return The HBITMAP representing the image. Caller should call
633 * DeleteObject when done with the bitmap.
634 * On failure, nullptr will be returned.
636 HBITMAP nsWindowGfx::DataToBitmap(uint8_t* aImageData, uint32_t aWidth,
637 uint32_t aHeight, uint32_t aDepth) {
638 HDC dc = ::GetDC(nullptr);
640 if (aDepth == 32) {
641 // Alpha channel. We need the new header.
642 BITMAPV4HEADER head = {0};
643 head.bV4Size = sizeof(head);
644 head.bV4Width = aWidth;
645 head.bV4Height = aHeight;
646 head.bV4Planes = 1;
647 head.bV4BitCount = aDepth;
648 head.bV4V4Compression = BI_BITFIELDS;
649 head.bV4SizeImage = 0; // Uncompressed
650 head.bV4XPelsPerMeter = 0;
651 head.bV4YPelsPerMeter = 0;
652 head.bV4ClrUsed = 0;
653 head.bV4ClrImportant = 0;
655 head.bV4RedMask = 0x00FF0000;
656 head.bV4GreenMask = 0x0000FF00;
657 head.bV4BlueMask = 0x000000FF;
658 head.bV4AlphaMask = 0xFF000000;
660 HBITMAP bmp = ::CreateDIBitmap(
661 dc, reinterpret_cast<CONST BITMAPINFOHEADER*>(&head), CBM_INIT,
662 aImageData, reinterpret_cast<CONST BITMAPINFO*>(&head), DIB_RGB_COLORS);
663 ::ReleaseDC(nullptr, dc);
664 return bmp;
667 char reserved_space[sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 2];
668 BITMAPINFOHEADER& head = *(BITMAPINFOHEADER*)reserved_space;
670 head.biSize = sizeof(BITMAPINFOHEADER);
671 head.biWidth = aWidth;
672 head.biHeight = aHeight;
673 head.biPlanes = 1;
674 head.biBitCount = (WORD)aDepth;
675 head.biCompression = BI_RGB;
676 head.biSizeImage = 0; // Uncompressed
677 head.biXPelsPerMeter = 0;
678 head.biYPelsPerMeter = 0;
679 head.biClrUsed = 0;
680 head.biClrImportant = 0;
682 BITMAPINFO& bi = *(BITMAPINFO*)reserved_space;
684 if (aDepth == 1) {
685 RGBQUAD black = {0, 0, 0, 0};
686 RGBQUAD white = {255, 255, 255, 0};
688 bi.bmiColors[0] = white;
689 bi.bmiColors[1] = black;
692 HBITMAP bmp =
693 ::CreateDIBitmap(dc, &head, CBM_INIT, aImageData, &bi, DIB_RGB_COLORS);
694 ::ReleaseDC(nullptr, dc);
695 return bmp;