Merge mozilla-central to autoland on a CLOSED TREE
[gecko.git] / widget / windows / nsWindowGfx.cpp
blobc2a91dcf6bfba21e587d40cc300241e9e16e480e
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(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 if (mClearNCEdge) {
179 // We need to clear this edge of the non-client region to black (once).
180 HDC hdc;
181 RECT rect;
182 hdc = ::GetWindowDC(mWnd);
183 ::GetWindowRect(mWnd, &rect);
184 ::MapWindowPoints(nullptr, mWnd, (LPPOINT)&rect, 2);
185 switch (mClearNCEdge.value()) {
186 case ABE_TOP:
187 rect.bottom = rect.top + kHiddenTaskbarSize;
188 break;
189 case ABE_LEFT:
190 rect.right = rect.left + kHiddenTaskbarSize;
191 break;
192 case ABE_BOTTOM:
193 rect.top = rect.bottom - kHiddenTaskbarSize;
194 break;
195 case ABE_RIGHT:
196 rect.left = rect.right - kHiddenTaskbarSize;
197 break;
198 default:
199 MOZ_ASSERT_UNREACHABLE("Invalid edge value");
200 break;
202 ::FillRect(hdc, &rect,
203 reinterpret_cast<HBRUSH>(::GetStockObject(BLACK_BRUSH)));
204 ::ReleaseDC(mWnd, hdc);
206 mClearNCEdge.reset();
209 if (knowsCompositor && layerManager &&
210 !mBounds.IsEqualEdges(mLastPaintBounds)) {
211 // Do an early async composite so that we at least have something on the
212 // screen in the right place, even if the content is out of date.
213 layerManager->ScheduleComposite(wr::RenderReasons::WIDGET);
215 mLastPaintBounds = mBounds;
217 // For layered translucent windows all drawing should go to memory DC and no
218 // WM_PAINT messages are normally generated. To support asynchronous painting
219 // we force generation of WM_PAINT messages by invalidating window areas with
220 // RedrawWindow, InvalidateRect or InvalidateRgn function calls.
221 const bool usingMemoryDC =
222 renderer->GetBackendType() == LayersBackend::LAYERS_NONE &&
223 mTransparencyMode == TransparencyMode::Transparent;
225 HDC hDC = nullptr;
226 if (usingMemoryDC) {
227 // BeginPaint/EndPaint must be called to make Windows think that invalid
228 // area is painted. Otherwise it will continue sending the same message
229 // endlessly.
230 ::BeginPaint(mWnd, &ps);
231 ::EndPaint(mWnd, &ps);
233 // We're guaranteed to have a widget proxy since we called
234 // GetLayerManager().
235 hDC = mBasicLayersSurface->GetTransparentDC();
236 } else {
237 hDC = ::BeginPaint(mWnd, &ps);
240 const bool forceRepaint = mTransparencyMode == TransparencyMode::Transparent;
241 const LayoutDeviceIntRegion region = GetRegionToPaint(forceRepaint, ps, hDC);
243 if (knowsCompositor && layerManager) {
244 // We need to paint to the screen even if nothing changed, since if we
245 // don't have a compositing window manager, our pixels could be stale.
246 layerManager->SetNeedsComposite(true);
247 layerManager->SendInvalidRegion(region.ToUnknownRegion());
250 RefPtr<nsWindow> strongThis(this);
252 nsIWidgetListener* listener = GetPaintListener();
253 if (listener) {
254 listener->WillPaintWindow(this);
256 // Re-get the listener since the will paint notification may have killed it.
257 listener = GetPaintListener();
258 if (!listener) {
259 return false;
262 if (knowsCompositor && layerManager && layerManager->NeedsComposite()) {
263 layerManager->ScheduleComposite(wr::RenderReasons::WIDGET);
264 layerManager->SetNeedsComposite(false);
267 bool result = true;
268 if (!region.IsEmpty() && listener) {
269 // Should probably pass in a real region here, using GetRandomRgn
270 // http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/clipping_4q0e.asp
272 #ifdef WIDGET_DEBUG_OUTPUT
273 debug_DumpPaintEvent(stdout, this, region.ToUnknownRegion(), "noname",
274 (int32_t)mWnd);
275 #endif // WIDGET_DEBUG_OUTPUT
277 switch (renderer->GetBackendType()) {
278 case LayersBackend::LAYERS_NONE: {
279 RefPtr<gfxASurface> targetSurface;
281 // don't support transparency for non-GDI rendering, for now
282 if (TransparencyMode::Transparent == mTransparencyMode) {
283 // This mutex needs to be held when EnsureTransparentSurface is
284 // called.
285 MutexAutoLock lock(mBasicLayersSurface->GetTransparentSurfaceLock());
286 targetSurface = mBasicLayersSurface->EnsureTransparentSurface();
289 RefPtr<gfxWindowsSurface> targetSurfaceWin;
290 if (!targetSurface) {
291 uint32_t flags = (mTransparencyMode == TransparencyMode::Opaque)
293 : gfxWindowsSurface::FLAG_IS_TRANSPARENT;
294 targetSurfaceWin = new gfxWindowsSurface(hDC, flags);
295 targetSurface = targetSurfaceWin;
298 if (!targetSurface) {
299 NS_ERROR("Invalid RenderMode!");
300 return false;
303 RECT paintRect;
304 ::GetClientRect(mWnd, &paintRect);
305 RefPtr<DrawTarget> dt = gfxPlatform::CreateDrawTargetForSurface(
306 targetSurface, IntSize(paintRect.right - paintRect.left,
307 paintRect.bottom - paintRect.top));
308 if (!dt || !dt->IsValid()) {
309 gfxWarning()
310 << "nsWindow::OnPaint failed in CreateDrawTargetForSurface";
311 return false;
314 // don't need to double buffer with anything but GDI
315 BufferMode doubleBuffering = mozilla::layers::BufferMode::BUFFER_NONE;
316 switch (mTransparencyMode) {
317 case TransparencyMode::Transparent:
318 // If we're rendering with translucency, we're going to be
319 // rendering the whole window; make sure we clear it first
320 dt->ClearRect(
321 Rect(0.f, 0.f, dt->GetSize().width, dt->GetSize().height));
322 break;
323 default:
324 // If we're not doing translucency, then double buffer
325 doubleBuffering = mozilla::layers::BufferMode::BUFFERED;
326 break;
329 gfxContext thebesContext(dt);
332 AutoLayerManagerSetup setupLayerManager(this, &thebesContext,
333 doubleBuffering);
334 result = listener->PaintWindow(this, region);
337 if (TransparencyMode::Transparent == mTransparencyMode) {
338 // Data from offscreen drawing surface was copied to memory bitmap of
339 // transparent bitmap. Now it can be read from memory bitmap to apply
340 // alpha channel and after that displayed on the screen.
341 mBasicLayersSurface->RedrawTransparentWindow();
343 } break;
344 case LayersBackend::LAYERS_WR: {
345 result = listener->PaintWindow(this, region);
346 if (!gfxEnv::MOZ_DISABLE_FORCE_PRESENT()) {
347 nsCOMPtr<nsIRunnable> event = NewRunnableMethod(
348 "nsWindow::ForcePresent", this, &nsWindow::ForcePresent);
349 NS_DispatchToMainThread(event);
351 } break;
352 default:
353 NS_ERROR("Unknown layers backend used!");
354 break;
358 if (!usingMemoryDC) {
359 ::EndPaint(mWnd, &ps);
362 mLastPaintEndTime = TimeStamp::Now();
364 // Re-get the listener since painting may have killed it.
365 listener = GetPaintListener();
366 if (listener) listener->DidPaintWindow();
368 if (aNestingLevel == 0 && ::GetUpdateRect(mWnd, nullptr, false)) {
369 OnPaint(1);
372 return result;
375 bool nsWindow::NeedsToTrackWindowOcclusionState() {
376 if (!WinWindowOcclusionTracker::Get()) {
377 return false;
380 if (mCompositorSession && mWindowType == WindowType::TopLevel) {
381 return true;
384 return false;
387 void nsWindow::NotifyOcclusionState(mozilla::widget::OcclusionState aState) {
388 MOZ_ASSERT(NeedsToTrackWindowOcclusionState());
390 bool isFullyOccluded = aState == mozilla::widget::OcclusionState::OCCLUDED;
391 // When window is minimized, it is not set as fully occluded.
392 if (mFrameState->GetSizeMode() == nsSizeMode_Minimized) {
393 isFullyOccluded = false;
396 // Don't dispatch if the new occlustion state is the same as the current
397 // state.
398 if (mIsFullyOccluded == isFullyOccluded) {
399 return;
402 mIsFullyOccluded = isFullyOccluded;
404 MOZ_LOG(gWindowsLog, LogLevel::Info,
405 ("nsWindow::NotifyOcclusionState() mIsFullyOccluded %d "
406 "mFrameState->GetSizeMode() %d",
407 mIsFullyOccluded, mFrameState->GetSizeMode()));
409 wr::DebugFlags flags{0};
410 flags._0 = gfx::gfxVars::WebRenderDebugFlags();
411 bool debugEnabled = bool(flags & wr::DebugFlags::WINDOW_VISIBILITY_DBG);
412 if (debugEnabled && mCompositorWidgetDelegate) {
413 mCompositorWidgetDelegate->NotifyVisibilityUpdated(
414 mFrameState->GetSizeMode(), mIsFullyOccluded);
417 if (mWidgetListener) {
418 mWidgetListener->OcclusionStateChanged(mIsFullyOccluded);
422 void nsWindow::MaybeEnableWindowOcclusion(bool aEnable) {
423 // WindowOcclusion is enabled/disabled only when compositor session exists.
424 // See nsWindow::NeedsToTrackWindowOcclusionState().
425 if (!mCompositorSession) {
426 return;
429 bool enabled = gfxConfig::IsEnabled(gfx::Feature::WINDOW_OCCLUSION);
431 if (aEnable) {
432 // Enable window occlusion.
433 if (enabled && NeedsToTrackWindowOcclusionState()) {
434 WinWindowOcclusionTracker::Get()->Enable(this, mWnd);
436 wr::DebugFlags flags{0};
437 flags._0 = gfx::gfxVars::WebRenderDebugFlags();
438 bool debugEnabled = bool(flags & wr::DebugFlags::WINDOW_VISIBILITY_DBG);
439 if (debugEnabled && mCompositorWidgetDelegate) {
440 mCompositorWidgetDelegate->NotifyVisibilityUpdated(
441 mFrameState->GetSizeMode(), mIsFullyOccluded);
444 return;
447 // Disable window occlusion.
448 MOZ_ASSERT(!aEnable);
450 if (!NeedsToTrackWindowOcclusionState()) {
451 return;
454 WinWindowOcclusionTracker::Get()->Disable(this, mWnd);
455 NotifyOcclusionState(OcclusionState::VISIBLE);
457 wr::DebugFlags flags{0};
458 flags._0 = gfx::gfxVars::WebRenderDebugFlags();
459 bool debugEnabled = bool(flags & wr::DebugFlags::WINDOW_VISIBILITY_DBG);
460 if (debugEnabled && mCompositorWidgetDelegate) {
461 mCompositorWidgetDelegate->NotifyVisibilityUpdated(
462 mFrameState->GetSizeMode(), mIsFullyOccluded);
466 // This override of CreateCompositor is to add support for sending the IPC
467 // call for RequesetFxrOutput as soon as the compositor for this widget is
468 // available.
469 void nsWindow::CreateCompositor() {
470 nsBaseWidget::CreateCompositor();
472 MaybeEnableWindowOcclusion(/* aEnable */ true);
474 if (mRequestFxrOutputPending) {
475 GetRemoteRenderer()->SendRequestFxrOutput();
479 void nsWindow::DestroyCompositor() {
480 MaybeEnableWindowOcclusion(/* aEnable */ false);
482 nsBaseWidget::DestroyCompositor();
485 void nsWindow::RequestFxrOutput() {
486 if (GetRemoteRenderer() != nullptr) {
487 MOZ_CRASH("RequestFxrOutput should happen before Compositor is created.");
488 } else {
489 // The compositor isn't ready, so indicate to make the IPC call when
490 // it is available.
491 mRequestFxrOutputPending = true;
495 LayoutDeviceIntSize nsWindowGfx::GetIconMetrics(IconSizeType aSizeType) {
496 int32_t width = ::GetSystemMetrics(sIconMetrics[aSizeType].xMetric);
497 int32_t height = ::GetSystemMetrics(sIconMetrics[aSizeType].yMetric);
499 if (width == 0 || height == 0) {
500 width = height = sIconMetrics[aSizeType].defaultSize;
503 return LayoutDeviceIntSize(width, height);
506 nsresult nsWindowGfx::CreateIcon(imgIContainer* aContainer, bool aIsCursor,
507 LayoutDeviceIntPoint aHotspot,
508 LayoutDeviceIntSize aScaledSize,
509 HICON* aIcon) {
510 MOZ_ASSERT(aHotspot.x >= 0 && aHotspot.y >= 0);
511 MOZ_ASSERT((aScaledSize.width > 0 && aScaledSize.height > 0) ||
512 (aScaledSize.width == 0 && aScaledSize.height == 0));
514 // Get the image data
515 RefPtr<SourceSurface> surface = aContainer->GetFrame(
516 imgIContainer::FRAME_CURRENT,
517 imgIContainer::FLAG_SYNC_DECODE | imgIContainer::FLAG_ASYNC_NOTIFY);
518 NS_ENSURE_TRUE(surface, NS_ERROR_NOT_AVAILABLE);
520 IntSize frameSize = surface->GetSize();
521 if (frameSize.IsEmpty()) {
522 return NS_ERROR_FAILURE;
525 IntSize iconSize(aScaledSize.width, aScaledSize.height);
526 if (iconSize == IntSize(0, 0)) { // use frame's intrinsic size
527 iconSize = frameSize;
530 RefPtr<DataSourceSurface> dataSurface;
531 bool mappedOK;
532 DataSourceSurface::MappedSurface map;
534 if (iconSize != frameSize) {
535 // Scale the surface
536 dataSurface =
537 Factory::CreateDataSourceSurface(iconSize, SurfaceFormat::B8G8R8A8);
538 NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
539 mappedOK = dataSurface->Map(DataSourceSurface::MapType::READ_WRITE, &map);
540 NS_ENSURE_TRUE(mappedOK, NS_ERROR_FAILURE);
542 RefPtr<DrawTarget> dt = Factory::CreateDrawTargetForData(
543 BackendType::CAIRO, map.mData, dataSurface->GetSize(), map.mStride,
544 SurfaceFormat::B8G8R8A8);
545 if (!dt) {
546 gfxWarning()
547 << "nsWindowGfx::CreatesIcon failed in CreateDrawTargetForData";
548 return NS_ERROR_OUT_OF_MEMORY;
550 dt->DrawSurface(surface, Rect(0, 0, iconSize.width, iconSize.height),
551 Rect(0, 0, frameSize.width, frameSize.height),
552 DrawSurfaceOptions(),
553 DrawOptions(1.0f, CompositionOp::OP_SOURCE));
554 } else if (surface->GetFormat() != SurfaceFormat::B8G8R8A8) {
555 // Convert format to SurfaceFormat::B8G8R8A8
556 dataSurface = gfxUtils::CopySurfaceToDataSourceSurfaceWithFormat(
557 surface, SurfaceFormat::B8G8R8A8);
558 NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
559 mappedOK = dataSurface->Map(DataSourceSurface::MapType::READ, &map);
560 } else {
561 dataSurface = surface->GetDataSurface();
562 NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
563 mappedOK = dataSurface->Map(DataSourceSurface::MapType::READ, &map);
565 NS_ENSURE_TRUE(dataSurface && mappedOK, NS_ERROR_FAILURE);
566 MOZ_ASSERT(dataSurface->GetFormat() == SurfaceFormat::B8G8R8A8);
568 uint8_t* data = nullptr;
569 UniquePtr<uint8_t[]> autoDeleteArray;
570 if (map.mStride == BytesPerPixel(dataSurface->GetFormat()) * iconSize.width) {
571 // Mapped data is already packed
572 data = map.mData;
573 } else {
574 // We can't use map.mData since the pixels are not packed (as required by
575 // CreateDIBitmap, which is called under the DataToBitmap call below).
577 // We must unmap before calling SurfaceToPackedBGRA because it needs access
578 // to the pixel data.
579 dataSurface->Unmap();
580 map.mData = nullptr;
582 autoDeleteArray = SurfaceToPackedBGRA(dataSurface);
583 data = autoDeleteArray.get();
584 NS_ENSURE_TRUE(data, NS_ERROR_FAILURE);
587 HBITMAP bmp = DataToBitmap(data, iconSize.width, -iconSize.height, 32);
588 uint8_t* a1data = Data32BitTo1Bit(data, iconSize.width, iconSize.height);
589 if (map.mData) {
590 dataSurface->Unmap();
592 if (!a1data) {
593 return NS_ERROR_FAILURE;
596 HBITMAP mbmp = DataToBitmap(a1data, iconSize.width, -iconSize.height, 1);
597 free(a1data);
599 ICONINFO info = {0};
600 info.fIcon = !aIsCursor;
601 info.xHotspot = aHotspot.x;
602 info.yHotspot = aHotspot.y;
603 info.hbmMask = mbmp;
604 info.hbmColor = bmp;
606 HCURSOR icon = ::CreateIconIndirect(&info);
607 ::DeleteObject(mbmp);
608 ::DeleteObject(bmp);
609 if (!icon) return NS_ERROR_FAILURE;
610 *aIcon = icon;
611 return NS_OK;
614 // Adjust cursor image data
615 uint8_t* nsWindowGfx::Data32BitTo1Bit(uint8_t* aImageData, uint32_t aWidth,
616 uint32_t aHeight) {
617 // We need (aWidth + 7) / 8 bytes plus zero-padding up to a multiple of
618 // 4 bytes for each row (HBITMAP requirement). Bug 353553.
619 uint32_t outBpr = ((aWidth + 31) / 8) & ~3;
621 // Allocate and clear mask buffer
622 uint8_t* outData = (uint8_t*)calloc(outBpr, aHeight);
623 if (!outData) return nullptr;
625 int32_t* imageRow = (int32_t*)aImageData;
626 for (uint32_t curRow = 0; curRow < aHeight; curRow++) {
627 uint8_t* outRow = outData + curRow * outBpr;
628 uint8_t mask = 0x80;
629 for (uint32_t curCol = 0; curCol < aWidth; curCol++) {
630 // Use sign bit to test for transparency, as alpha byte is highest byte
631 if (*imageRow++ < 0) *outRow |= mask;
633 mask >>= 1;
634 if (!mask) {
635 outRow++;
636 mask = 0x80;
641 return outData;
645 * Convert the given image data to a HBITMAP. If the requested depth is
646 * 32 bit, a bitmap with an alpha channel will be returned.
648 * @param aImageData The image data to convert. Must use the format accepted
649 * by CreateDIBitmap.
650 * @param aWidth With of the bitmap, in pixels.
651 * @param aHeight Height of the image, in pixels.
652 * @param aDepth Image depth, in bits. Should be one of 1, 24 and 32.
654 * @return The HBITMAP representing the image. Caller should call
655 * DeleteObject when done with the bitmap.
656 * On failure, nullptr will be returned.
658 HBITMAP nsWindowGfx::DataToBitmap(uint8_t* aImageData, uint32_t aWidth,
659 uint32_t aHeight, uint32_t aDepth) {
660 HDC dc = ::GetDC(nullptr);
662 if (aDepth == 32) {
663 // Alpha channel. We need the new header.
664 BITMAPV4HEADER head = {0};
665 head.bV4Size = sizeof(head);
666 head.bV4Width = aWidth;
667 head.bV4Height = aHeight;
668 head.bV4Planes = 1;
669 head.bV4BitCount = aDepth;
670 head.bV4V4Compression = BI_BITFIELDS;
671 head.bV4SizeImage = 0; // Uncompressed
672 head.bV4XPelsPerMeter = 0;
673 head.bV4YPelsPerMeter = 0;
674 head.bV4ClrUsed = 0;
675 head.bV4ClrImportant = 0;
677 head.bV4RedMask = 0x00FF0000;
678 head.bV4GreenMask = 0x0000FF00;
679 head.bV4BlueMask = 0x000000FF;
680 head.bV4AlphaMask = 0xFF000000;
682 HBITMAP bmp = ::CreateDIBitmap(
683 dc, reinterpret_cast<CONST BITMAPINFOHEADER*>(&head), CBM_INIT,
684 aImageData, reinterpret_cast<CONST BITMAPINFO*>(&head), DIB_RGB_COLORS);
685 ::ReleaseDC(nullptr, dc);
686 return bmp;
689 char reserved_space[sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 2];
690 BITMAPINFOHEADER& head = *(BITMAPINFOHEADER*)reserved_space;
692 head.biSize = sizeof(BITMAPINFOHEADER);
693 head.biWidth = aWidth;
694 head.biHeight = aHeight;
695 head.biPlanes = 1;
696 head.biBitCount = (WORD)aDepth;
697 head.biCompression = BI_RGB;
698 head.biSizeImage = 0; // Uncompressed
699 head.biXPelsPerMeter = 0;
700 head.biYPelsPerMeter = 0;
701 head.biClrUsed = 0;
702 head.biClrImportant = 0;
704 BITMAPINFO& bi = *(BITMAPINFO*)reserved_space;
706 if (aDepth == 1) {
707 RGBQUAD black = {0, 0, 0, 0};
708 RGBQUAD white = {255, 255, 255, 0};
710 bi.bmiColors[0] = white;
711 bi.bmiColors[1] = black;
714 HBITMAP bmp =
715 ::CreateDIBitmap(dc, &head, CBM_INIT, aImageData, &bi, DIB_RGB_COLORS);
716 ::ReleaseDC(nullptr, dc);
717 return bmp;