Bug 1826326 [wpt PR 39360] - Get rid of ResourceWarnings produced by the tests, a...
[gecko.git] / widget / windows / nsWindowGfx.cpp
blob8df90a63c9a24fda0fd2861fb46173d2b7391786
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 <shellapi.h>
26 #include "gfxEnv.h"
27 #include "gfxImageSurface.h"
28 #include "gfxUtils.h"
29 #include "gfxConfig.h"
30 #include "gfxWindowsSurface.h"
31 #include "gfxWindowsPlatform.h"
32 #include "gfxDWriteFonts.h"
33 #include "mozilla/gfx/2D.h"
34 #include "mozilla/gfx/DataSurfaceHelpers.h"
35 #include "mozilla/gfx/Tools.h"
36 #include "mozilla/RefPtr.h"
37 #include "mozilla/UniquePtrExtensions.h"
38 #include "nsGfxCIID.h"
39 #include "gfxContext.h"
40 #include "WinUtils.h"
41 #include "WinWindowOcclusionTracker.h"
42 #include "nsIWidgetListener.h"
43 #include "mozilla/Unused.h"
44 #include "nsDebug.h"
45 #include "WindowRenderer.h"
46 #include "mozilla/layers/WebRenderLayerManager.h"
48 #include "mozilla/gfx/GPUProcessManager.h"
49 #include "mozilla/layers/CompositorBridgeParent.h"
50 #include "mozilla/layers/CompositorBridgeChild.h"
51 #include "InProcessWinCompositorWidget.h"
53 #include "nsUXThemeData.h"
54 #include "nsUXThemeConstants.h"
56 using namespace mozilla;
57 using namespace mozilla::gfx;
58 using namespace mozilla::layers;
59 using namespace mozilla::widget;
60 using namespace mozilla::plugins;
61 extern mozilla::LazyLogModule gWindowsLog;
63 /**************************************************************
64 **************************************************************
66 ** BLOCK: Variables
68 ** nsWindow Class static initializations and global variables.
70 **************************************************************
71 **************************************************************/
73 /**************************************************************
75 * SECTION: nsWindow statics
77 **************************************************************/
79 struct IconMetrics {
80 int32_t xMetric;
81 int32_t yMetric;
82 int32_t defaultSize;
85 // Corresponds 1:1 to the IconSizeType enum
86 static IconMetrics sIconMetrics[] = {
87 {SM_CXSMICON, SM_CYSMICON, 16}, // small icon
88 {SM_CXICON, SM_CYICON, 32} // regular icon
91 /**************************************************************
92 **************************************************************
94 ** BLOCK: nsWindow impl.
96 ** Paint related nsWindow methods.
98 **************************************************************
99 **************************************************************/
101 // GetRegionToPaint returns the invalidated region that needs to be painted
102 LayoutDeviceIntRegion nsWindow::GetRegionToPaint(bool aForceFullRepaint,
103 PAINTSTRUCT ps, HDC aDC) {
104 if (aForceFullRepaint) {
105 RECT paintRect;
106 ::GetClientRect(mWnd, &paintRect);
107 return LayoutDeviceIntRegion(WinUtils::ToIntRect(paintRect));
110 HRGN paintRgn = ::CreateRectRgn(0, 0, 0, 0);
111 if (paintRgn != nullptr) {
112 int result = GetRandomRgn(aDC, paintRgn, SYSRGN);
113 if (result == 1) {
114 POINT pt = {0, 0};
115 ::MapWindowPoints(nullptr, mWnd, &pt, 1);
116 ::OffsetRgn(paintRgn, pt.x, pt.y);
118 LayoutDeviceIntRegion rgn(WinUtils::ConvertHRGNToRegion(paintRgn));
119 ::DeleteObject(paintRgn);
120 return rgn;
122 return LayoutDeviceIntRegion(WinUtils::ToIntRect(ps.rcPaint));
125 nsIWidgetListener* nsWindow::GetPaintListener() {
126 if (mDestroyCalled) return nullptr;
127 return mAttachedWidgetListener ? mAttachedWidgetListener : mWidgetListener;
130 void nsWindow::ForcePresent() {
131 if (mResizeState != RESIZING) {
132 if (CompositorBridgeChild* remoteRenderer = GetRemoteRenderer()) {
133 remoteRenderer->SendForcePresent(wr::RenderReasons::WIDGET);
138 bool nsWindow::OnPaint(HDC aDC, uint32_t aNestingLevel) {
139 DeviceResetReason resetReason = DeviceResetReason::OK;
140 if (gfxWindowsPlatform::GetPlatform()->DidRenderingDeviceReset(
141 &resetReason)) {
142 gfxCriticalNote << "(nsWindow) Detected device reset: " << (int)resetReason;
144 gfxWindowsPlatform::GetPlatform()->UpdateRenderMode();
146 bool guilty;
147 switch (resetReason) {
148 case DeviceResetReason::HUNG:
149 case DeviceResetReason::RESET:
150 case DeviceResetReason::INVALID_CALL:
151 guilty = true;
152 break;
153 default:
154 guilty = false;
155 break;
158 GPUProcessManager::Get()->OnInProcessDeviceReset(guilty);
160 gfxCriticalNote << "(nsWindow) Finished device reset.";
161 return false;
164 PAINTSTRUCT ps;
166 // Avoid starting the GPU process for the initial navigator:blank window.
167 if (mIsEarlyBlankWindow) {
168 // Call BeginPaint/EndPaint or Windows will keep sending us messages.
169 ::BeginPaint(mWnd, &ps);
170 ::EndPaint(mWnd, &ps);
171 return true;
174 WindowRenderer* renderer = GetWindowRenderer();
175 KnowsCompositor* knowsCompositor = renderer->AsKnowsCompositor();
176 WebRenderLayerManager* layerManager = renderer->AsWebRender();
178 // Clear window by transparent black when compositor window is used in GPU
179 // process and non-client area rendering by DWM is enabled.
180 // It is for showing non-client area rendering. See nsWindow::UpdateGlass().
181 if (HasGlass() && knowsCompositor && knowsCompositor->GetUseCompositorWnd()) {
182 HDC hdc;
183 RECT rect;
184 hdc = ::GetWindowDC(mWnd);
185 ::GetWindowRect(mWnd, &rect);
186 ::MapWindowPoints(nullptr, mWnd, (LPPOINT)&rect, 2);
187 ::FillRect(hdc, &rect,
188 reinterpret_cast<HBRUSH>(GetStockObject(BLACK_BRUSH)));
189 ReleaseDC(mWnd, hdc);
192 if (mClearNCEdge) {
193 // We need to clear this edge of the non-client region to black (once).
194 HDC hdc;
195 RECT rect;
196 hdc = ::GetWindowDC(mWnd);
197 ::GetWindowRect(mWnd, &rect);
198 ::MapWindowPoints(nullptr, mWnd, (LPPOINT)&rect, 2);
199 switch (mClearNCEdge.value()) {
200 case ABE_TOP:
201 rect.bottom = rect.top + kHiddenTaskbarSize;
202 break;
203 case ABE_LEFT:
204 rect.right = rect.left + kHiddenTaskbarSize;
205 break;
206 case ABE_BOTTOM:
207 rect.top = rect.bottom - kHiddenTaskbarSize;
208 break;
209 case ABE_RIGHT:
210 rect.left = rect.right - kHiddenTaskbarSize;
211 break;
212 default:
213 MOZ_ASSERT_UNREACHABLE("Invalid edge value");
214 break;
216 ::FillRect(hdc, &rect,
217 reinterpret_cast<HBRUSH>(::GetStockObject(BLACK_BRUSH)));
218 ::ReleaseDC(mWnd, hdc);
220 mClearNCEdge.reset();
223 if (knowsCompositor && layerManager &&
224 !mBounds.IsEqualEdges(mLastPaintBounds)) {
225 // Do an early async composite so that we at least have something on the
226 // screen in the right place, even if the content is out of date.
227 layerManager->ScheduleComposite(wr::RenderReasons::WIDGET);
229 mLastPaintBounds = mBounds;
231 if (!aDC && (renderer->GetBackendType() == LayersBackend::LAYERS_NONE) &&
232 (TransparencyMode::Transparent == mTransparencyMode)) {
233 // For layered translucent windows all drawing should go to memory DC and no
234 // WM_PAINT messages are normally generated. To support asynchronous
235 // painting we force generation of WM_PAINT messages by invalidating window
236 // areas with RedrawWindow, InvalidateRect or InvalidateRgn function calls.
237 // BeginPaint/EndPaint must be called to make Windows think that invalid
238 // area is painted. Otherwise it will continue sending the same message
239 // endlessly.
240 ::BeginPaint(mWnd, &ps);
241 ::EndPaint(mWnd, &ps);
243 // We're guaranteed to have a widget proxy since we called
244 // GetLayerManager().
245 aDC = mBasicLayersSurface->GetTransparentDC();
248 HDC hDC = aDC ? aDC : (::BeginPaint(mWnd, &ps));
249 mPaintDC = hDC;
251 bool forceRepaint =
252 aDC || (TransparencyMode::Transparent == mTransparencyMode);
253 LayoutDeviceIntRegion region = GetRegionToPaint(forceRepaint, ps, hDC);
255 if (knowsCompositor && layerManager) {
256 // We need to paint to the screen even if nothing changed, since if we
257 // don't have a compositing window manager, our pixels could be stale.
258 layerManager->SetNeedsComposite(true);
259 layerManager->SendInvalidRegion(region.ToUnknownRegion());
262 RefPtr<nsWindow> strongThis(this);
264 nsIWidgetListener* listener = GetPaintListener();
265 if (listener) {
266 listener->WillPaintWindow(this);
268 // Re-get the listener since the will paint notification may have killed it.
269 listener = GetPaintListener();
270 if (!listener) {
271 return false;
274 if (knowsCompositor && layerManager && layerManager->NeedsComposite()) {
275 layerManager->ScheduleComposite(wr::RenderReasons::WIDGET);
276 layerManager->SetNeedsComposite(false);
279 bool result = true;
280 if (!region.IsEmpty() && listener) {
281 // Should probably pass in a real region here, using GetRandomRgn
282 // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/clipping_4q0e.asp
284 #ifdef WIDGET_DEBUG_OUTPUT
285 debug_DumpPaintEvent(stdout, this, region.ToUnknownRegion(), "noname",
286 (int32_t)mWnd);
287 #endif // WIDGET_DEBUG_OUTPUT
289 switch (renderer->GetBackendType()) {
290 case LayersBackend::LAYERS_NONE: {
291 RefPtr<gfxASurface> targetSurface;
293 // don't support transparency for non-GDI rendering, for now
294 if (TransparencyMode::Transparent == mTransparencyMode) {
295 // This mutex needs to be held when EnsureTransparentSurface is
296 // called.
297 MutexAutoLock lock(mBasicLayersSurface->GetTransparentSurfaceLock());
298 targetSurface = mBasicLayersSurface->EnsureTransparentSurface();
301 RefPtr<gfxWindowsSurface> targetSurfaceWin;
302 if (!targetSurface) {
303 uint32_t flags = (mTransparencyMode == TransparencyMode::Opaque)
305 : gfxWindowsSurface::FLAG_IS_TRANSPARENT;
306 targetSurfaceWin = new gfxWindowsSurface(hDC, flags);
307 targetSurface = targetSurfaceWin;
310 if (!targetSurface) {
311 NS_ERROR("Invalid RenderMode!");
312 return false;
315 RECT paintRect;
316 ::GetClientRect(mWnd, &paintRect);
317 RefPtr<DrawTarget> dt = gfxPlatform::CreateDrawTargetForSurface(
318 targetSurface, IntSize(paintRect.right - paintRect.left,
319 paintRect.bottom - paintRect.top));
320 if (!dt || !dt->IsValid()) {
321 gfxWarning()
322 << "nsWindow::OnPaint failed in CreateDrawTargetForSurface";
323 return false;
326 // don't need to double buffer with anything but GDI
327 BufferMode doubleBuffering = mozilla::layers::BufferMode::BUFFER_NONE;
328 switch (mTransparencyMode) {
329 case TransparencyMode::BorderlessGlass:
330 default:
331 // If we're not doing translucency, then double buffer
332 doubleBuffering = mozilla::layers::BufferMode::BUFFERED;
333 break;
334 case TransparencyMode::Transparent:
335 // If we're rendering with translucency, we're going to be
336 // rendering the whole window; make sure we clear it first
337 dt->ClearRect(
338 Rect(0.f, 0.f, dt->GetSize().width, dt->GetSize().height));
339 break;
342 gfxContext thebesContext(dt);
345 AutoLayerManagerSetup setupLayerManager(this, &thebesContext,
346 doubleBuffering);
347 result = listener->PaintWindow(this, region);
350 if (TransparencyMode::Transparent == mTransparencyMode) {
351 // Data from offscreen drawing surface was copied to memory bitmap of
352 // transparent bitmap. Now it can be read from memory bitmap to apply
353 // alpha channel and after that displayed on the screen.
354 mBasicLayersSurface->RedrawTransparentWindow();
356 } break;
357 case LayersBackend::LAYERS_WR: {
358 result = listener->PaintWindow(this, region);
359 if (!gfxEnv::MOZ_DISABLE_FORCE_PRESENT() &&
360 gfxWindowsPlatform::GetPlatform()->DwmCompositionEnabled()) {
361 nsCOMPtr<nsIRunnable> event = NewRunnableMethod(
362 "nsWindow::ForcePresent", this, &nsWindow::ForcePresent);
363 NS_DispatchToMainThread(event);
365 } break;
366 default:
367 NS_ERROR("Unknown layers backend used!");
368 break;
372 if (!aDC) {
373 ::EndPaint(mWnd, &ps);
376 mPaintDC = nullptr;
377 mLastPaintEndTime = TimeStamp::Now();
379 // Re-get the listener since painting may have killed it.
380 listener = GetPaintListener();
381 if (listener) listener->DidPaintWindow();
383 if (aNestingLevel == 0 && ::GetUpdateRect(mWnd, nullptr, false)) {
384 OnPaint(aDC, 1);
387 return result;
390 bool nsWindow::NeedsToTrackWindowOcclusionState() {
391 if (!WinWindowOcclusionTracker::Get()) {
392 return false;
395 if (mCompositorSession && mWindowType == WindowType::TopLevel) {
396 return true;
399 return false;
402 void nsWindow::NotifyOcclusionState(mozilla::widget::OcclusionState aState) {
403 MOZ_ASSERT(NeedsToTrackWindowOcclusionState());
405 bool isFullyOccluded = aState == mozilla::widget::OcclusionState::OCCLUDED;
406 // When window is minimized, it is not set as fully occluded.
407 if (mFrameState->GetSizeMode() == nsSizeMode_Minimized) {
408 isFullyOccluded = false;
411 // Don't dispatch if the new occlustion state is the same as the current
412 // state.
413 if (mIsFullyOccluded == isFullyOccluded) {
414 return;
417 mIsFullyOccluded = isFullyOccluded;
419 MOZ_LOG(gWindowsLog, LogLevel::Info,
420 ("nsWindow::NotifyOcclusionState() mIsFullyOccluded %d "
421 "mFrameState->GetSizeMode() %d",
422 mIsFullyOccluded, mFrameState->GetSizeMode()));
424 wr::DebugFlags flags{0};
425 flags.bits = gfx::gfxVars::WebRenderDebugFlags();
426 bool debugEnabled = bool(flags & wr::DebugFlags::WINDOW_VISIBILITY_DBG);
427 if (debugEnabled && mCompositorWidgetDelegate) {
428 mCompositorWidgetDelegate->NotifyVisibilityUpdated(
429 mFrameState->GetSizeMode(), mIsFullyOccluded);
432 if (mWidgetListener) {
433 mWidgetListener->OcclusionStateChanged(mIsFullyOccluded);
437 void nsWindow::MaybeEnableWindowOcclusion(bool aEnable) {
438 // WindowOcclusion is enabled/disabled only when compositor session exists.
439 // See nsWindow::NeedsToTrackWindowOcclusionState().
440 if (!mCompositorSession) {
441 return;
444 bool enabled = gfxConfig::IsEnabled(gfx::Feature::WINDOW_OCCLUSION);
446 if (aEnable) {
447 // Enable window occlusion.
448 if (enabled && NeedsToTrackWindowOcclusionState()) {
449 WinWindowOcclusionTracker::Get()->Enable(this, mWnd);
451 wr::DebugFlags flags{0};
452 flags.bits = gfx::gfxVars::WebRenderDebugFlags();
453 bool debugEnabled = bool(flags & wr::DebugFlags::WINDOW_VISIBILITY_DBG);
454 if (debugEnabled && mCompositorWidgetDelegate) {
455 mCompositorWidgetDelegate->NotifyVisibilityUpdated(
456 mFrameState->GetSizeMode(), mIsFullyOccluded);
459 return;
462 // Disable window occlusion.
463 MOZ_ASSERT(!aEnable);
465 if (!NeedsToTrackWindowOcclusionState()) {
466 return;
469 WinWindowOcclusionTracker::Get()->Disable(this, mWnd);
470 NotifyOcclusionState(OcclusionState::VISIBLE);
472 wr::DebugFlags flags{0};
473 flags.bits = gfx::gfxVars::WebRenderDebugFlags();
474 bool debugEnabled = bool(flags & wr::DebugFlags::WINDOW_VISIBILITY_DBG);
475 if (debugEnabled && mCompositorWidgetDelegate) {
476 mCompositorWidgetDelegate->NotifyVisibilityUpdated(
477 mFrameState->GetSizeMode(), mIsFullyOccluded);
481 // This override of CreateCompositor is to add support for sending the IPC
482 // call for RequesetFxrOutput as soon as the compositor for this widget is
483 // available.
484 void nsWindow::CreateCompositor() {
485 nsBaseWidget::CreateCompositor();
487 MaybeEnableWindowOcclusion(/* aEnable */ true);
489 if (mRequestFxrOutputPending) {
490 GetRemoteRenderer()->SendRequestFxrOutput();
494 void nsWindow::DestroyCompositor() {
495 MaybeEnableWindowOcclusion(/* aEnable */ false);
497 nsBaseWidget::DestroyCompositor();
500 void nsWindow::RequestFxrOutput() {
501 if (GetRemoteRenderer() != nullptr) {
502 MOZ_CRASH("RequestFxrOutput should happen before Compositor is created.");
503 } else {
504 // The compositor isn't ready, so indicate to make the IPC call when
505 // it is available.
506 mRequestFxrOutputPending = true;
510 LayoutDeviceIntSize nsWindowGfx::GetIconMetrics(IconSizeType aSizeType) {
511 int32_t width = ::GetSystemMetrics(sIconMetrics[aSizeType].xMetric);
512 int32_t height = ::GetSystemMetrics(sIconMetrics[aSizeType].yMetric);
514 if (width == 0 || height == 0) {
515 width = height = sIconMetrics[aSizeType].defaultSize;
518 return LayoutDeviceIntSize(width, height);
521 nsresult nsWindowGfx::CreateIcon(imgIContainer* aContainer, bool aIsCursor,
522 LayoutDeviceIntPoint aHotspot,
523 LayoutDeviceIntSize aScaledSize,
524 HICON* aIcon) {
525 MOZ_ASSERT(aHotspot.x >= 0 && aHotspot.y >= 0);
526 MOZ_ASSERT((aScaledSize.width > 0 && aScaledSize.height > 0) ||
527 (aScaledSize.width == 0 && aScaledSize.height == 0));
529 // Get the image data
530 RefPtr<SourceSurface> surface = aContainer->GetFrame(
531 imgIContainer::FRAME_CURRENT,
532 imgIContainer::FLAG_SYNC_DECODE | imgIContainer::FLAG_ASYNC_NOTIFY);
533 NS_ENSURE_TRUE(surface, NS_ERROR_NOT_AVAILABLE);
535 IntSize frameSize = surface->GetSize();
536 if (frameSize.IsEmpty()) {
537 return NS_ERROR_FAILURE;
540 IntSize iconSize(aScaledSize.width, aScaledSize.height);
541 if (iconSize == IntSize(0, 0)) { // use frame's intrinsic size
542 iconSize = frameSize;
545 RefPtr<DataSourceSurface> dataSurface;
546 bool mappedOK;
547 DataSourceSurface::MappedSurface map;
549 if (iconSize != frameSize) {
550 // Scale the surface
551 dataSurface =
552 Factory::CreateDataSourceSurface(iconSize, SurfaceFormat::B8G8R8A8);
553 NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
554 mappedOK = dataSurface->Map(DataSourceSurface::MapType::READ_WRITE, &map);
555 NS_ENSURE_TRUE(mappedOK, NS_ERROR_FAILURE);
557 RefPtr<DrawTarget> dt = Factory::CreateDrawTargetForData(
558 BackendType::CAIRO, map.mData, dataSurface->GetSize(), map.mStride,
559 SurfaceFormat::B8G8R8A8);
560 if (!dt) {
561 gfxWarning()
562 << "nsWindowGfx::CreatesIcon failed in CreateDrawTargetForData";
563 return NS_ERROR_OUT_OF_MEMORY;
565 dt->DrawSurface(surface, Rect(0, 0, iconSize.width, iconSize.height),
566 Rect(0, 0, frameSize.width, frameSize.height),
567 DrawSurfaceOptions(),
568 DrawOptions(1.0f, CompositionOp::OP_SOURCE));
569 } else if (surface->GetFormat() != SurfaceFormat::B8G8R8A8) {
570 // Convert format to SurfaceFormat::B8G8R8A8
571 dataSurface = gfxUtils::CopySurfaceToDataSourceSurfaceWithFormat(
572 surface, SurfaceFormat::B8G8R8A8);
573 NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
574 mappedOK = dataSurface->Map(DataSourceSurface::MapType::READ, &map);
575 } else {
576 dataSurface = surface->GetDataSurface();
577 NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
578 mappedOK = dataSurface->Map(DataSourceSurface::MapType::READ, &map);
580 NS_ENSURE_TRUE(dataSurface && mappedOK, NS_ERROR_FAILURE);
581 MOZ_ASSERT(dataSurface->GetFormat() == SurfaceFormat::B8G8R8A8);
583 uint8_t* data = nullptr;
584 UniquePtr<uint8_t[]> autoDeleteArray;
585 if (map.mStride == BytesPerPixel(dataSurface->GetFormat()) * iconSize.width) {
586 // Mapped data is already packed
587 data = map.mData;
588 } else {
589 // We can't use map.mData since the pixels are not packed (as required by
590 // CreateDIBitmap, which is called under the DataToBitmap call below).
592 // We must unmap before calling SurfaceToPackedBGRA because it needs access
593 // to the pixel data.
594 dataSurface->Unmap();
595 map.mData = nullptr;
597 autoDeleteArray = SurfaceToPackedBGRA(dataSurface);
598 data = autoDeleteArray.get();
599 NS_ENSURE_TRUE(data, NS_ERROR_FAILURE);
602 HBITMAP bmp = DataToBitmap(data, iconSize.width, -iconSize.height, 32);
603 uint8_t* a1data = Data32BitTo1Bit(data, iconSize.width, iconSize.height);
604 if (map.mData) {
605 dataSurface->Unmap();
607 if (!a1data) {
608 return NS_ERROR_FAILURE;
611 HBITMAP mbmp = DataToBitmap(a1data, iconSize.width, -iconSize.height, 1);
612 free(a1data);
614 ICONINFO info = {0};
615 info.fIcon = !aIsCursor;
616 info.xHotspot = aHotspot.x;
617 info.yHotspot = aHotspot.y;
618 info.hbmMask = mbmp;
619 info.hbmColor = bmp;
621 HCURSOR icon = ::CreateIconIndirect(&info);
622 ::DeleteObject(mbmp);
623 ::DeleteObject(bmp);
624 if (!icon) return NS_ERROR_FAILURE;
625 *aIcon = icon;
626 return NS_OK;
629 // Adjust cursor image data
630 uint8_t* nsWindowGfx::Data32BitTo1Bit(uint8_t* aImageData, uint32_t aWidth,
631 uint32_t aHeight) {
632 // We need (aWidth + 7) / 8 bytes plus zero-padding up to a multiple of
633 // 4 bytes for each row (HBITMAP requirement). Bug 353553.
634 uint32_t outBpr = ((aWidth + 31) / 8) & ~3;
636 // Allocate and clear mask buffer
637 uint8_t* outData = (uint8_t*)calloc(outBpr, aHeight);
638 if (!outData) return nullptr;
640 int32_t* imageRow = (int32_t*)aImageData;
641 for (uint32_t curRow = 0; curRow < aHeight; curRow++) {
642 uint8_t* outRow = outData + curRow * outBpr;
643 uint8_t mask = 0x80;
644 for (uint32_t curCol = 0; curCol < aWidth; curCol++) {
645 // Use sign bit to test for transparency, as alpha byte is highest byte
646 if (*imageRow++ < 0) *outRow |= mask;
648 mask >>= 1;
649 if (!mask) {
650 outRow++;
651 mask = 0x80;
656 return outData;
660 * Convert the given image data to a HBITMAP. If the requested depth is
661 * 32 bit, a bitmap with an alpha channel will be returned.
663 * @param aImageData The image data to convert. Must use the format accepted
664 * by CreateDIBitmap.
665 * @param aWidth With of the bitmap, in pixels.
666 * @param aHeight Height of the image, in pixels.
667 * @param aDepth Image depth, in bits. Should be one of 1, 24 and 32.
669 * @return The HBITMAP representing the image. Caller should call
670 * DeleteObject when done with the bitmap.
671 * On failure, nullptr will be returned.
673 HBITMAP nsWindowGfx::DataToBitmap(uint8_t* aImageData, uint32_t aWidth,
674 uint32_t aHeight, uint32_t aDepth) {
675 HDC dc = ::GetDC(nullptr);
677 if (aDepth == 32) {
678 // Alpha channel. We need the new header.
679 BITMAPV4HEADER head = {0};
680 head.bV4Size = sizeof(head);
681 head.bV4Width = aWidth;
682 head.bV4Height = aHeight;
683 head.bV4Planes = 1;
684 head.bV4BitCount = aDepth;
685 head.bV4V4Compression = BI_BITFIELDS;
686 head.bV4SizeImage = 0; // Uncompressed
687 head.bV4XPelsPerMeter = 0;
688 head.bV4YPelsPerMeter = 0;
689 head.bV4ClrUsed = 0;
690 head.bV4ClrImportant = 0;
692 head.bV4RedMask = 0x00FF0000;
693 head.bV4GreenMask = 0x0000FF00;
694 head.bV4BlueMask = 0x000000FF;
695 head.bV4AlphaMask = 0xFF000000;
697 HBITMAP bmp = ::CreateDIBitmap(
698 dc, reinterpret_cast<CONST BITMAPINFOHEADER*>(&head), CBM_INIT,
699 aImageData, reinterpret_cast<CONST BITMAPINFO*>(&head), DIB_RGB_COLORS);
700 ::ReleaseDC(nullptr, dc);
701 return bmp;
704 char reserved_space[sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 2];
705 BITMAPINFOHEADER& head = *(BITMAPINFOHEADER*)reserved_space;
707 head.biSize = sizeof(BITMAPINFOHEADER);
708 head.biWidth = aWidth;
709 head.biHeight = aHeight;
710 head.biPlanes = 1;
711 head.biBitCount = (WORD)aDepth;
712 head.biCompression = BI_RGB;
713 head.biSizeImage = 0; // Uncompressed
714 head.biXPelsPerMeter = 0;
715 head.biYPelsPerMeter = 0;
716 head.biClrUsed = 0;
717 head.biClrImportant = 0;
719 BITMAPINFO& bi = *(BITMAPINFO*)reserved_space;
721 if (aDepth == 1) {
722 RGBQUAD black = {0, 0, 0, 0};
723 RGBQUAD white = {255, 255, 255, 0};
725 bi.bmiColors[0] = white;
726 bi.bmiColors[1] = black;
729 HBITMAP bmp =
730 ::CreateDIBitmap(dc, &head, CBM_INIT, aImageData, &bi, DIB_RGB_COLORS);
731 ::ReleaseDC(nullptr, dc);
732 return bmp;