Files
palemoon27/widget/windows/nsWindowGfx.cpp
T
roytam1 10160cd03d import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1240749 - Fixes for DPI support in Gtk widget interface: remove incorrect Get[Avail]RectDisplayPix overrides, as desktop pixels == device pixels for the Gtk widget backend, and implement nsScreenGtk::GetDefaultCSSScaleFactor, required by nsGlobalWindow since per-monitor DPI patches in bug 890156. r=karlt (9975cac985)
- Bug 1033488 - Part 2. Make PuppetBidiKeyboard correctly on content process. r=masayuki (3a91ce60a8)
- Bug 1257067 - modified XF86XK_ keysyms to GDK_ ones r=masayuki (4b922f9365)
- Bug 1251984 - allow gfx.xrender.enabled pref to work for compositing even if content backend is not Cairo. r=jrmuizel (257a163074)
- Bug 1235941 - Detect DPI change for GTK3. r=karlt (f8ca209d4b)
- Bug 1256728: Add environment variable to disable force present from bug 1232042. r=BenWa (c3b12a085b)
- Bug 1257124: Add null check for IDWriteFactory in gfxDWriteFontFileLoader::CreateCustomFontFile. r=bas (d33af4b9e1)
- Bug 1266209 - log failure reason when PathBuilderD2D::Finish fails. r=bas.schouten (360d7c2ada)
- Bug 1256552 - Disable C4577 to unblock compilation on VS2015; r=jrmuizel (7375fbf42a)
- Bug 1265960 - Remove gfxReusable* r=Bas (ed0b3aca14)
- Bug 1246290 - Refactoring to get rid of SampleContentTransformForFrame from AsyncPanZoomController. r=botond (3be6b4c1f9)
- Bug 1246290 - Add the ability for APZCs to not expose async transforms. r=botond (48942ceddf)
- Bug 1259296 - Scroll snap in the compositor in response to wheel events. r=kats (5fc694c804)
- Bug 1249040 - Allow wheel scrolls to accumulate in the presence of scroll snapping. r=kats (7514e3f6d6)
- Bug 1237343 - Replace uses of mozilla::Vector with nsTArray. r=botond (b721de19cd)
- Bug 1236046 - Don't use a stupidly small time delta to compute a velocity. r=botond (6c8f298ab6)
- Bug 1257959 - Dynamic toolbar transition seems to slow down flings r=kats (47ec4d0d54)
- Bug 1265513 - Do a fuzzy match when checking to see if a scroll will result in overscroll. r=botond (03ee304916)
- Bug 1254252 - Have Axis::ClampOriginToScrollableRect just return the original value if it falls with in the page bounds. r=kats (f88c0b4d7d)
- Bug 1261373 - Record how long it takes for content response notifications to be delivered to APZ. r=botond f=bsmedberg (b4b24d7602)
- Bug 1265515 - Update nsAutoPtr.h includes in gfx/layers/apz to RefPtr.h. r=kats (48bbc2cda8)
- Bug 1259296 - Make sure APZ smooth scroll animations end at their exact destination scroll offset. r=kats (36cace259b)
- Bug 1251837, part 1 - Use pushPrefEnv in setDeltaMultiplierSettings in window_wheel_default_action.html. r=masayuki (d673d55f02)
- Bug 1251837, part 2 - Use pushPrefEnv in doTestActionOverride in window_wheel_default_action.html. r=masayuki (f0375a3820)
- Bug 1251837, part 3 - Use pushPrefEnv in doTestWholeScroll in window_wheel_default_action.html. r=masayuki (0a7af4e103)
- Bug 1251837, part 4 - Use pushPrefEnv in doTestActionOverride in window_wheel_default_action.html. r=masayuki (51bd9cd1e2)
- Bug 1251837, part 5 - Make prepare() in doTestScroll take a callback, and use pushPrefEnv. r=masayuki (856056a947)
- Bug 1251837, part 6 - Make cleanup() in doTestScroll take a callback, and use pushPrefEnv. r=masayuki (34aa62b7f3)
- Bug 1255173 - Fix onZoomReset() in test_wheel_default_action.html to work with e10s. r=masayuki, r=jmaher (0c248c7587)
- Bug 1255178 - Part 1: Remove a leftover use of clearUserPref. r=masayuki Also, remove some trailing whitespace. (c067affdba)
- Bug 1255178 - Part 2: Remove extraneous argument to sendWheelAndWait. r=masayuki (80ce47c89b)
- Bug 1255634 - APZ should scroll by more than a page with large values of mousewheel.default.delta_multiplier_{x,y}. r=masayuki,kats (d72f77daed)
- Bug 1251638 - Don't clamp the displayport to the scrollable rect on the compositor side. r=botond (5dae2ba82e)
- Bug 1251638 - Do a bit of cleanup on the displayport margin computation in APZC; no functional changes. r=botond (575453b538)
- Bug 1266154 - Don't start a scroll snap animation if we're already at the destination. r=kats (2926d33a07)
- Bug 1258851 - Update HitTestingTreeNode::IsScrollbarNode to include the scrollbar track layers. r=rbarker (1e68081a6a)
- Bug 1265806 - Update scrollbar finding code to deal with layer trees on both OS X and Windows properly. r=rbarker (e8df49352e)
- Bug 1255224 - Add pref to force glFinish in DXGL path. (default:false) - r=dvander (8d399f8a49)
- Bug 1224199 - Destroy SharedSurfaces before ~GLContext(). - r=jrmuizel (5ad8d11f8e)
- Bug 1232480. Use 'precision' instead of 'prevision' (c7310988fa)
- Bug 1232668. Allow using kTex2DBlit_FragShaderSource on non-ES targets. (1951af5c1c)
- Bug 1235299 - Fix WebGL assertions for copyTexImage2D. r=jgilbert (226b7c14a8)
- Bug 1249189 - Use GL_RED to replace GL_ALPHA in YCbCr convert. r=jgilbert (e1d8ae2513)
- Bug 1256552 - fix int-to-float conversions in RadialGradientEffectD2D1. r=jrmuizel (36bb7f7f0f)
- Bug 1249279 - Let subdocuments' presContexts inherit the DPI setting of their parent, instead of retrieving it from their widget, to avoid using stale values from a currently-hidden widget on a screen with a different DPI. r=bz (4b8f6e0960)
- Bug 1237479 -- nsScriptSecurityManager needs to use the correct user context id in the origin attributes in a few places. r=sicking (90504a4130)
- Bug 1105556 - Call Create(originAttributes) when loadinfo->loadingPrincipal is null, instead of CreatePrincipalWithInheritedAttributes(). r=sicking (fdb341ca53)
- Bug 1253788 - Don't reload inline chrome:// style sheets in nsXBLPrototypeResources. r=bzbarsky (862464ea6c)
- Bug 1261123 - don't needlessly construct nsAutoCString temporaries in nsDefaultURIFixup; r=smaug (08f13674a8)
- Bug 1253673, r=bz (03caab3cce)
- Bug 1259511 - Overwrite loadInfo within AboutProtocolHandler and log warning to console. r=sicking (e2fc868326)
- Bug 905460 - Convert http legacy refs to smart pointers r=dragana a=kwierso (d4bdd102fa)
- Bug 1248564 - "Default authentication credentials (NTLM, Kerb) used in private mode". r=mayhemer (37c5674a0d)
- Bug 345580 - Problem decoding quoted-printable question mark in subject r=biesi (00f66a34a7)
- Bug 906986 - Rework fix for Bug 1241690 to avoid reliance on NrIceCtx inside NrIceMediaStream. r=bwc, r=drno (3d6aabeab6)
- Bug 906986 - Disable TestSrflxCandPairingFilter until bug 1226838 is fixed. r=bwc, r=drno (687281bf8b)
- Bug 906986 - Use the streams from the ice_ctx, don't hold a separate set. r=bwc, r=drno (269cd38ed2)
- Bug 906986 - Genericize some of the test setup and improve logging. r=bwc, r=drno (ad735f2459)
- Bug 906986 - Wrap NrIceCtx in NrIceCtxHandler which will allow us to handle ice restart. r=bwc, r=drno (4f2c1e5866)
- Bug 911216 - Part 12: Windows build bustage fix on a CLOSED TREE. r=efaust (f81e40df57)
- Bug 1261329 - Fix OOM handling in shell dissrc function r=efaust (d61eb121de)
- Bug 1263868 - Properly recover from OOM in ShellAutoEntryMonitor. r=jonco (3830ce7aae)
- Bug 1257722 - Prevent stdout/stderr from getting closed, r=jorendorff (48629efc06)
- Bug 1258847 - Set PTHREAD_MUTEX_ERRORCHECK for js::Mutex in debug builds. r=sfink (48cb353190)
- Bug 1252464 - Remove FrameRange cray cray in favor of using GCVectors. (r=jimb) (60ad943599)
- Bug 1257194: Tracelogger - Check for oom in drainTracelogger, r=bbouvier (7d8299958f)
- Bug 1264961 - Fix OOM case in Debugger::replaceFrameGuts. (r=jimb) (203816a8b3)
- Bug 1257588 - Don't ignore self-hosted frames when getting a saved frame's async cause. r=fitzgen (15b467a950)
- Bug 1258535 - Part 0: Add more and stronger asserts that SavedStacks-related JSAPI methods are called correctly; r=jandem (187251c401)
- Bug 1258535 - Check for the existence of a global before checking if its standard classes are resolved; r=jandem (18f7bbcc69)
- Bug 1264975 - Fix assertion in DebugScope wrapping non-syntactic scopes. (r=jimb) (753e315ddb)
- Bug 1259403 - Tracelogger: Always make sure there are 3 free slots for events, r=bbouvier (67a13b7a14)
- Bug 1231926 - add assertions on BYTEOFFSET_SLOT. r=waldo (3508ea1943)
- Bug 1260725 - Handle and report OOM in census breakdown parsing; r=jorendorff a=kwierso (de669940d1)
- Bug 1263074 - Change the JavaScript syntax error message for the old octal literal notation to suggest the new notation. r=Waldo (4e2457b27a)
- Bug 1257096, don't try to report about unusual unhandled rejected Promises, r=bz,waldo (682e4720d9)
- Bug 1262402: Use the new int64 testing features; r=luke (d213bb4f2c)
- Bug 1263882: Set a default value in DescribeScriptedCaller if the filename is null; r=luke (f66ec211f5)
2024-05-09 21:38:16 +08:00

821 lines
28 KiB
C++

/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
/*
* nsWindowGfx - Painting and aceleration.
*/
/**************************************************************
**************************************************************
**
** BLOCK: Includes
**
** Include headers.
**
**************************************************************
**************************************************************/
#include "mozilla/dom/ContentParent.h"
#include "mozilla/plugins/PluginInstanceParent.h"
using mozilla::plugins::PluginInstanceParent;
#include "nsWindowGfx.h"
#include "nsAppRunner.h"
#include <windows.h>
#include "gfxEnv.h"
#include "gfxImageSurface.h"
#include "gfxUtils.h"
#include "gfxWindowsSurface.h"
#include "gfxWindowsPlatform.h"
#include "mozilla/gfx/2D.h"
#include "mozilla/gfx/DataSurfaceHelpers.h"
#include "mozilla/gfx/Tools.h"
#include "mozilla/RefPtr.h"
#include "mozilla/UniquePtrExtensions.h"
#include "nsGfxCIID.h"
#include "gfxContext.h"
#include "prmem.h"
#include "WinUtils.h"
#include "nsIWidgetListener.h"
#include "mozilla/unused.h"
#include "nsDebug.h"
#include "nsIXULRuntime.h"
#include "mozilla/layers/CompositorBridgeParent.h"
#include "mozilla/layers/CompositorBridgeChild.h"
#include "ClientLayerManager.h"
#include "nsUXThemeData.h"
#include "nsUXThemeConstants.h"
using namespace mozilla;
using namespace mozilla::gfx;
using namespace mozilla::layers;
using namespace mozilla::widget;
using namespace mozilla::plugins;
/**************************************************************
**************************************************************
**
** BLOCK: Variables
**
** nsWindow Class static initializations and global variables.
**
**************************************************************
**************************************************************/
/**************************************************************
*
* SECTION: nsWindow statics
*
**************************************************************/
static UniquePtr<uint8_t[]> sSharedSurfaceData;
static IntSize sSharedSurfaceSize;
struct IconMetrics {
int32_t xMetric;
int32_t yMetric;
int32_t defaultSize;
};
// Corresponds 1:1 to the IconSizeType enum
static IconMetrics sIconMetrics[] = {
{SM_CXSMICON, SM_CYSMICON, 16}, // small icon
{SM_CXICON, SM_CYICON, 32} // regular icon
};
/**************************************************************
**************************************************************
**
** BLOCK: nsWindowGfx impl.
**
** Misc. graphics related utilities.
**
**************************************************************
**************************************************************/
/* static */ bool
nsWindow::IsRenderMode(gfxWindowsPlatform::RenderMode rmode)
{
return gfxWindowsPlatform::GetPlatform()->GetRenderMode() == rmode;
}
/**************************************************************
**************************************************************
**
** BLOCK: nsWindow impl.
**
** Paint related nsWindow methods.
**
**************************************************************
**************************************************************/
// GetRegionToPaint returns the invalidated region that needs to be painted
nsIntRegion nsWindow::GetRegionToPaint(bool aForceFullRepaint,
PAINTSTRUCT ps, HDC aDC)
{
if (aForceFullRepaint) {
RECT paintRect;
::GetClientRect(mWnd, &paintRect);
return nsIntRegion(WinUtils::ToIntRect(paintRect));
}
HRGN paintRgn = ::CreateRectRgn(0, 0, 0, 0);
if (paintRgn != nullptr) {
int result = GetRandomRgn(aDC, paintRgn, SYSRGN);
if (result == 1) {
POINT pt = {0,0};
::MapWindowPoints(nullptr, mWnd, &pt, 1);
::OffsetRgn(paintRgn, pt.x, pt.y);
}
nsIntRegion rgn(WinUtils::ConvertHRGNToRegion(paintRgn));
::DeleteObject(paintRgn);
return rgn;
}
return nsIntRegion(WinUtils::ToIntRect(ps.rcPaint));
}
#define WORDSSIZE(x) ((x).width * (x).height)
static bool
EnsureSharedSurfaceSize(IntSize size)
{
IntSize screenSize;
screenSize.height = GetSystemMetrics(SM_CYSCREEN);
screenSize.width = GetSystemMetrics(SM_CXSCREEN);
if (WORDSSIZE(screenSize) > WORDSSIZE(size))
size = screenSize;
if (WORDSSIZE(screenSize) < WORDSSIZE(size))
NS_WARNING("Trying to create a shared surface larger than the screen");
if (!sSharedSurfaceData || (WORDSSIZE(size) > WORDSSIZE(sSharedSurfaceSize))) {
sSharedSurfaceSize = size;
sSharedSurfaceData =
MakeUniqueFallible<uint8_t[]>(WORDSSIZE(sSharedSurfaceSize) * 4);
}
return !sSharedSurfaceData;
}
nsIWidgetListener* nsWindow::GetPaintListener()
{
if (mDestroyCalled)
return nullptr;
return mAttachedWidgetListener ? mAttachedWidgetListener : mWidgetListener;
}
void nsWindow::ForcePresent()
{
if (CompositorBridgeChild* remoteRenderer = GetRemoteRenderer()) {
remoteRenderer->SendForcePresent();
}
}
bool nsWindow::OnPaint(HDC aDC, uint32_t aNestingLevel)
{
// We never have reentrant paint events, except when we're running our RPC
// windows event spin loop. If we don't trap for this, we'll try to paint,
// but view manager will refuse to paint the surface, resulting is black
// flashes on the plugin rendering surface.
if (mozilla::ipc::MessageChannel::IsSpinLoopActive() && mPainting)
return false;
if (gfxWindowsPlatform::GetPlatform()->DidRenderingDeviceReset()) {
gfxWindowsPlatform::GetPlatform()->UpdateRenderMode();
EnumAllWindows([] (nsWindow* aWindow) -> void {
aWindow->OnRenderingDeviceReset();
});
return false;
}
// After we CallUpdateWindow to the child, occasionally a WM_PAINT message
// is posted to the parent event loop with an empty update rect. Do a
// dummy paint so that Windows stops dispatching WM_PAINT in an inifinite
// loop. See bug 543788.
if (IsPlugin()) {
RECT updateRect;
if (!GetUpdateRect(mWnd, &updateRect, FALSE) ||
(updateRect.left == updateRect.right &&
updateRect.top == updateRect.bottom)) {
PAINTSTRUCT ps;
BeginPaint(mWnd, &ps);
EndPaint(mWnd, &ps);
return true;
}
if (mWindowType == eWindowType_plugin_ipc_chrome) {
// Fire off an async request to the plugin to paint its window
mozilla::dom::ContentParent::SendAsyncUpdate(this);
ValidateRect(mWnd, nullptr);
return true;
}
PluginInstanceParent* instance = reinterpret_cast<PluginInstanceParent*>(
::GetPropW(mWnd, L"PluginInstanceParentProperty"));
if (instance) {
Unused << instance->CallUpdateWindow();
} else {
// We should never get here since in-process plugins should have
// subclassed our HWND and handled WM_PAINT, but in some cases that
// could fail. Return without asserting since it's not our fault.
NS_WARNING("Plugin failed to subclass our window");
}
ValidateRect(mWnd, nullptr);
return true;
}
ClientLayerManager *clientLayerManager = GetLayerManager()->AsClientLayerManager();
if (clientLayerManager && mCompositorBridgeParent &&
!mBounds.IsEqualEdges(mLastPaintBounds))
{
// Do an early async composite so that we at least have something on the
// screen in the right place, even if the content is out of date.
mCompositorBridgeParent->ScheduleRenderOnCompositorThread();
}
mLastPaintBounds = mBounds;
PAINTSTRUCT ps;
#ifdef MOZ_XUL
if (!aDC && (eTransparencyTransparent == mTransparencyMode))
{
// For layered translucent windows all drawing should go to memory DC and no
// WM_PAINT messages are normally generated. To support asynchronous painting
// we force generation of WM_PAINT messages by invalidating window areas with
// RedrawWindow, InvalidateRect or InvalidateRgn function calls.
// BeginPaint/EndPaint must be called to make Windows think that invalid area
// is painted. Otherwise it will continue sending the same message endlessly.
::BeginPaint(mWnd, &ps);
::EndPaint(mWnd, &ps);
aDC = mMemoryDC;
}
#endif
mPainting = true;
#ifdef WIDGET_DEBUG_OUTPUT
HRGN debugPaintFlashRegion = nullptr;
HDC debugPaintFlashDC = nullptr;
if (debug_WantPaintFlashing())
{
debugPaintFlashRegion = ::CreateRectRgn(0, 0, 0, 0);
::GetUpdateRgn(mWnd, debugPaintFlashRegion, TRUE);
debugPaintFlashDC = ::GetDC(mWnd);
}
#endif // WIDGET_DEBUG_OUTPUT
HDC hDC = aDC ? aDC : (::BeginPaint(mWnd, &ps));
mPaintDC = hDC;
#ifdef MOZ_XUL
bool forceRepaint = aDC || (eTransparencyTransparent == mTransparencyMode);
#else
bool forceRepaint = nullptr != aDC;
#endif
nsIntRegion region = GetRegionToPaint(forceRepaint, ps, hDC);
if (clientLayerManager && mCompositorBridgeParent) {
// We need to paint to the screen even if nothing changed, since if we
// don't have a compositing window manager, our pixels could be stale.
clientLayerManager->SetNeedsComposite(true);
clientLayerManager->SendInvalidRegion(region);
}
nsIWidgetListener* listener = GetPaintListener();
if (listener) {
listener->WillPaintWindow(this);
}
// Re-get the listener since the will paint notification may have killed it.
listener = GetPaintListener();
if (!listener) {
return false;
}
if (clientLayerManager && mCompositorBridgeParent && clientLayerManager->NeedsComposite()) {
mCompositorBridgeParent->ScheduleRenderOnCompositorThread();
clientLayerManager->SetNeedsComposite(false);
}
bool result = true;
if (!region.IsEmpty() && listener)
{
// Should probably pass in a real region here, using GetRandomRgn
// http://msdn.microsoft.com/library/default.asp?url=/library/en-us/gdi/clipping_4q0e.asp
#ifdef WIDGET_DEBUG_OUTPUT
debug_DumpPaintEvent(stdout,
this,
region,
"noname",
(int32_t) mWnd);
#endif // WIDGET_DEBUG_OUTPUT
switch (GetLayerManager()->GetBackendType()) {
case LayersBackend::LAYERS_BASIC:
{
RefPtr<gfxASurface> targetSurface;
#if defined(MOZ_XUL)
// don't support transparency for non-GDI rendering, for now
if ((IsRenderMode(gfxWindowsPlatform::RENDER_GDI) ||
IsRenderMode(gfxWindowsPlatform::RENDER_DIRECT2D)) &&
eTransparencyTransparent == mTransparencyMode) {
if (mTransparentSurface == nullptr)
SetupTranslucentWindowMemoryBitmap(mTransparencyMode);
targetSurface = mTransparentSurface;
}
#endif
RefPtr<gfxWindowsSurface> targetSurfaceWin;
if (!targetSurface &&
(IsRenderMode(gfxWindowsPlatform::RENDER_GDI) ||
IsRenderMode(gfxWindowsPlatform::RENDER_DIRECT2D)))
{
uint32_t flags = (mTransparencyMode == eTransparencyOpaque) ? 0 :
gfxWindowsSurface::FLAG_IS_TRANSPARENT;
targetSurfaceWin = new gfxWindowsSurface(hDC, flags);
targetSurface = targetSurfaceWin;
}
RefPtr<gfxImageSurface> targetSurfaceImage;
if (!targetSurface &&
(IsRenderMode(gfxWindowsPlatform::RENDER_IMAGE_STRETCH32) ||
IsRenderMode(gfxWindowsPlatform::RENDER_IMAGE_STRETCH24)))
{
IntSize surfaceSize(ps.rcPaint.right - ps.rcPaint.left,
ps.rcPaint.bottom - ps.rcPaint.top);
if (!EnsureSharedSurfaceSize(surfaceSize)) {
NS_ERROR("Couldn't allocate a shared image surface!");
return false;
}
// don't use the shared surface directly; instead, create a new one
// that just reuses its buffer.
targetSurfaceImage = new gfxImageSurface(sSharedSurfaceData.get(),
surfaceSize,
surfaceSize.width * 4,
SurfaceFormat::X8R8G8B8_UINT32);
if (targetSurfaceImage && !targetSurfaceImage->CairoStatus()) {
targetSurfaceImage->SetDeviceOffset(gfxPoint(-ps.rcPaint.left, -ps.rcPaint.top));
targetSurface = targetSurfaceImage;
}
}
if (!targetSurface) {
NS_ERROR("Invalid RenderMode!");
return false;
}
RECT paintRect;
::GetClientRect(mWnd, &paintRect);
RefPtr<DrawTarget> dt =
gfxPlatform::GetPlatform()->CreateDrawTargetForSurface(targetSurface,
IntSize(paintRect.right - paintRect.left,
paintRect.bottom - paintRect.top));
if (!dt || !dt->IsValid()) {
gfxWarning() << "nsWindow::OnPaint failed in CreateDrawTargetForSurface";
return false;
}
// don't need to double buffer with anything but GDI
BufferMode doubleBuffering = mozilla::layers::BufferMode::BUFFER_NONE;
if (IsRenderMode(gfxWindowsPlatform::RENDER_GDI) ||
IsRenderMode(gfxWindowsPlatform::RENDER_DIRECT2D)) {
#ifdef MOZ_XUL
switch (mTransparencyMode) {
case eTransparencyGlass:
case eTransparencyBorderlessGlass:
default:
// If we're not doing translucency, then double buffer
doubleBuffering = mozilla::layers::BufferMode::BUFFERED;
break;
case eTransparencyTransparent:
// If we're rendering with translucency, we're going to be
// rendering the whole window; make sure we clear it first
dt->ClearRect(Rect(0.f, 0.f,
dt->GetSize().width, dt->GetSize().height));
break;
}
#else
doubleBuffering = mozilla::layers::BufferMode::BUFFERED;
#endif
}
RefPtr<gfxContext> thebesContext = gfxContext::ForDrawTarget(dt);
MOZ_ASSERT(thebesContext); // already checked draw target above
{
AutoLayerManagerSetup
setupLayerManager(this, thebesContext, doubleBuffering);
result = listener->PaintWindow(
this, LayoutDeviceIntRegion::FromUnknownRegion(region));
}
#ifdef MOZ_XUL
if ((IsRenderMode(gfxWindowsPlatform::RENDER_GDI) ||
IsRenderMode(gfxWindowsPlatform::RENDER_DIRECT2D))&&
eTransparencyTransparent == mTransparencyMode) {
// Data from offscreen drawing surface was copied to memory bitmap of transparent
// bitmap. Now it can be read from memory bitmap to apply alpha channel and after
// that displayed on the screen.
UpdateTranslucentWindow();
} else
#endif
if (result) {
if (IsRenderMode(gfxWindowsPlatform::RENDER_IMAGE_STRETCH24) ||
IsRenderMode(gfxWindowsPlatform::RENDER_IMAGE_STRETCH32))
{
IntSize surfaceSize = targetSurfaceImage->GetSize();
// Just blit this directly
BITMAPINFOHEADER bi;
memset(&bi, 0, sizeof(BITMAPINFOHEADER));
bi.biSize = sizeof(BITMAPINFOHEADER);
bi.biWidth = surfaceSize.width;
bi.biHeight = - surfaceSize.height;
bi.biPlanes = 1;
bi.biBitCount = 32;
bi.biCompression = BI_RGB;
if (IsRenderMode(gfxWindowsPlatform::RENDER_IMAGE_STRETCH24)) {
// On Windows CE/Windows Mobile, 24bpp packed-pixel sources
// seem to be far faster to blit than 32bpp (see bug 484864).
// So, convert the bits to 24bpp by stripping out the unused
// alpha byte. 24bpp DIBs also have scanlines that are 4-byte
// aligned though, so that must be taken into account.
int srcstride = surfaceSize.width*4;
int dststride = surfaceSize.width*3;
dststride = (dststride + 3) & ~3;
// Convert in place
for (int j = 0; j < surfaceSize.height; ++j) {
unsigned int *src = (unsigned int*) (targetSurfaceImage->Data() + j*srcstride);
unsigned int *dst = (unsigned int*) (targetSurfaceImage->Data() + j*dststride);
// go 4 pixels at a time, since each 4 pixels
// turns into 3 DWORDs when converted into BGR:
// BGRx BGRx BGRx BGRx -> BGRB GRBG RBGR
//
// However, since we're dealing with little-endian ints, this is actually:
// xRGB xrgb xRGB xrgb -> bRGB GBrg rgbR
int width_left = surfaceSize.width;
while (width_left >= 4) {
unsigned int a = *src++;
unsigned int b = *src++;
unsigned int c = *src++;
unsigned int d = *src++;
*dst++ = (a & 0x00ffffff) | (b << 24);
*dst++ = ((b & 0x00ffff00) >> 8) | (c << 16);
*dst++ = ((c & 0x00ff0000) >> 16) | (d << 8);
width_left -= 4;
}
// then finish up whatever number of pixels are left,
// using bytes.
unsigned char *bsrc = (unsigned char*) src;
unsigned char *bdst = (unsigned char*) dst;
switch (width_left) {
case 3:
*bdst++ = *bsrc++;
*bdst++ = *bsrc++;
*bdst++ = *bsrc++;
bsrc++;
case 2:
*bdst++ = *bsrc++;
*bdst++ = *bsrc++;
*bdst++ = *bsrc++;
bsrc++;
case 1:
*bdst++ = *bsrc++;
*bdst++ = *bsrc++;
*bdst++ = *bsrc++;
bsrc++;
case 0:
break;
}
}
bi.biBitCount = 24;
}
StretchDIBits(hDC,
ps.rcPaint.left, ps.rcPaint.top,
surfaceSize.width, surfaceSize.height,
0, 0,
surfaceSize.width, surfaceSize.height,
targetSurfaceImage->Data(),
(BITMAPINFO*) &bi,
DIB_RGB_COLORS,
SRCCOPY);
}
}
}
break;
case LayersBackend::LAYERS_CLIENT:
{
result = listener->PaintWindow(
this, LayoutDeviceIntRegion::FromUnknownRegion(region));
if (!gfxEnv::DisableForcePresent()) {
nsCOMPtr<nsIRunnable> event =
NS_NewRunnableMethod(this, &nsWindow::ForcePresent);
NS_DispatchToMainThread(event);
}
}
break;
default:
NS_ERROR("Unknown layers backend used!");
break;
}
}
if (!aDC) {
::EndPaint(mWnd, &ps);
}
mPaintDC = nullptr;
mLastPaintEndTime = TimeStamp::Now();
#if defined(WIDGET_DEBUG_OUTPUT)
if (debug_WantPaintFlashing())
{
// Only flash paint events which have not ignored the paint message.
// Those that ignore the paint message aren't painting anything so there
// is only the overhead of the dispatching the paint event.
if (result) {
::InvertRgn(debugPaintFlashDC, debugPaintFlashRegion);
PR_Sleep(PR_MillisecondsToInterval(30));
::InvertRgn(debugPaintFlashDC, debugPaintFlashRegion);
PR_Sleep(PR_MillisecondsToInterval(30));
}
::ReleaseDC(mWnd, debugPaintFlashDC);
::DeleteObject(debugPaintFlashRegion);
}
#endif // WIDGET_DEBUG_OUTPUT
mPainting = false;
// Re-get the listener since painting may have killed it.
listener = GetPaintListener();
if (listener)
listener->DidPaintWindow();
if (aNestingLevel == 0 && ::GetUpdateRect(mWnd, nullptr, false)) {
OnPaint(aDC, 1);
}
return result;
}
IntSize nsWindowGfx::GetIconMetrics(IconSizeType aSizeType) {
int32_t width = ::GetSystemMetrics(sIconMetrics[aSizeType].xMetric);
int32_t height = ::GetSystemMetrics(sIconMetrics[aSizeType].yMetric);
if (width == 0 || height == 0) {
width = height = sIconMetrics[aSizeType].defaultSize;
}
return IntSize(width, height);
}
nsresult nsWindowGfx::CreateIcon(imgIContainer *aContainer,
bool aIsCursor,
uint32_t aHotspotX,
uint32_t aHotspotY,
IntSize aScaledSize,
HICON *aIcon) {
MOZ_ASSERT((aScaledSize.width > 0 && aScaledSize.height > 0) ||
(aScaledSize.width == 0 && aScaledSize.height == 0));
// Get the image data
RefPtr<SourceSurface> surface =
aContainer->GetFrame(imgIContainer::FRAME_CURRENT,
imgIContainer::FLAG_SYNC_DECODE);
NS_ENSURE_TRUE(surface, NS_ERROR_NOT_AVAILABLE);
IntSize frameSize = surface->GetSize();
if (frameSize.IsEmpty()) {
return NS_ERROR_FAILURE;
}
IntSize iconSize(aScaledSize.width, aScaledSize.height);
if (iconSize == IntSize(0, 0)) { // use frame's intrinsic size
iconSize = frameSize;
}
RefPtr<DataSourceSurface> dataSurface;
bool mappedOK;
DataSourceSurface::MappedSurface map;
if (iconSize != frameSize) {
// Scale the surface
dataSurface = Factory::CreateDataSourceSurface(iconSize,
SurfaceFormat::B8G8R8A8);
NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
mappedOK = dataSurface->Map(DataSourceSurface::MapType::READ_WRITE, &map);
NS_ENSURE_TRUE(mappedOK, NS_ERROR_FAILURE);
RefPtr<DrawTarget> dt =
Factory::CreateDrawTargetForData(BackendType::CAIRO,
map.mData,
dataSurface->GetSize(),
map.mStride,
SurfaceFormat::B8G8R8A8);
if (!dt) {
gfxWarning() << "nsWindowGfx::CreatesIcon failed in CreateDrawTargetForData";
return NS_ERROR_OUT_OF_MEMORY;
}
dt->DrawSurface(surface,
Rect(0, 0, iconSize.width, iconSize.height),
Rect(0, 0, frameSize.width, frameSize.height),
DrawSurfaceOptions(),
DrawOptions(1.0f, CompositionOp::OP_SOURCE));
} else if (surface->GetFormat() != SurfaceFormat::B8G8R8A8) {
// Convert format to SurfaceFormat::B8G8R8A8
dataSurface = gfxUtils::
CopySurfaceToDataSourceSurfaceWithFormat(surface,
SurfaceFormat::B8G8R8A8);
NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
mappedOK = dataSurface->Map(DataSourceSurface::MapType::READ, &map);
} else {
dataSurface = surface->GetDataSurface();
NS_ENSURE_TRUE(dataSurface, NS_ERROR_FAILURE);
mappedOK = dataSurface->Map(DataSourceSurface::MapType::READ, &map);
}
NS_ENSURE_TRUE(dataSurface && mappedOK, NS_ERROR_FAILURE);
MOZ_ASSERT(dataSurface->GetFormat() == SurfaceFormat::B8G8R8A8);
uint8_t* data = nullptr;
UniquePtr<uint8_t[]> autoDeleteArray;
if (map.mStride == BytesPerPixel(dataSurface->GetFormat()) * iconSize.width) {
// Mapped data is already packed
data = map.mData;
} else {
// We can't use map.mData since the pixels are not packed (as required by
// CreateDIBitmap, which is called under the DataToBitmap call below).
//
// We must unmap before calling SurfaceToPackedBGRA because it needs access
// to the pixel data.
dataSurface->Unmap();
map.mData = nullptr;
autoDeleteArray = SurfaceToPackedBGRA(dataSurface);
data = autoDeleteArray.get();
NS_ENSURE_TRUE(data, NS_ERROR_FAILURE);
}
HBITMAP bmp = DataToBitmap(data, iconSize.width, -iconSize.height, 32);
uint8_t* a1data = Data32BitTo1Bit(data, iconSize.width, iconSize.height);
if (map.mData) {
dataSurface->Unmap();
}
if (!a1data) {
return NS_ERROR_FAILURE;
}
HBITMAP mbmp = DataToBitmap(a1data, iconSize.width, -iconSize.height, 1);
PR_Free(a1data);
ICONINFO info = {0};
info.fIcon = !aIsCursor;
info.xHotspot = aHotspotX;
info.yHotspot = aHotspotY;
info.hbmMask = mbmp;
info.hbmColor = bmp;
HCURSOR icon = ::CreateIconIndirect(&info);
::DeleteObject(mbmp);
::DeleteObject(bmp);
if (!icon)
return NS_ERROR_FAILURE;
*aIcon = icon;
return NS_OK;
}
// Adjust cursor image data
uint8_t* nsWindowGfx::Data32BitTo1Bit(uint8_t* aImageData,
uint32_t aWidth, uint32_t aHeight)
{
// We need (aWidth + 7) / 8 bytes plus zero-padding up to a multiple of
// 4 bytes for each row (HBITMAP requirement). Bug 353553.
uint32_t outBpr = ((aWidth + 31) / 8) & ~3;
// Allocate and clear mask buffer
uint8_t* outData = (uint8_t*)PR_Calloc(outBpr, aHeight);
if (!outData)
return nullptr;
int32_t *imageRow = (int32_t*)aImageData;
for (uint32_t curRow = 0; curRow < aHeight; curRow++) {
uint8_t *outRow = outData + curRow * outBpr;
uint8_t mask = 0x80;
for (uint32_t curCol = 0; curCol < aWidth; curCol++) {
// Use sign bit to test for transparency, as alpha byte is highest byte
if (*imageRow++ < 0)
*outRow |= mask;
mask >>= 1;
if (!mask) {
outRow ++;
mask = 0x80;
}
}
}
return outData;
}
/**
* Convert the given image data to a HBITMAP. If the requested depth is
* 32 bit, a bitmap with an alpha channel will be returned.
*
* @param aImageData The image data to convert. Must use the format accepted
* by CreateDIBitmap.
* @param aWidth With of the bitmap, in pixels.
* @param aHeight Height of the image, in pixels.
* @param aDepth Image depth, in bits. Should be one of 1, 24 and 32.
*
* @return The HBITMAP representing the image. Caller should call
* DeleteObject when done with the bitmap.
* On failure, nullptr will be returned.
*/
HBITMAP nsWindowGfx::DataToBitmap(uint8_t* aImageData,
uint32_t aWidth,
uint32_t aHeight,
uint32_t aDepth)
{
HDC dc = ::GetDC(nullptr);
if (aDepth == 32) {
// Alpha channel. We need the new header.
BITMAPV4HEADER head = { 0 };
head.bV4Size = sizeof(head);
head.bV4Width = aWidth;
head.bV4Height = aHeight;
head.bV4Planes = 1;
head.bV4BitCount = aDepth;
head.bV4V4Compression = BI_BITFIELDS;
head.bV4SizeImage = 0; // Uncompressed
head.bV4XPelsPerMeter = 0;
head.bV4YPelsPerMeter = 0;
head.bV4ClrUsed = 0;
head.bV4ClrImportant = 0;
head.bV4RedMask = 0x00FF0000;
head.bV4GreenMask = 0x0000FF00;
head.bV4BlueMask = 0x000000FF;
head.bV4AlphaMask = 0xFF000000;
HBITMAP bmp = ::CreateDIBitmap(dc,
reinterpret_cast<CONST BITMAPINFOHEADER*>(&head),
CBM_INIT,
aImageData,
reinterpret_cast<CONST BITMAPINFO*>(&head),
DIB_RGB_COLORS);
::ReleaseDC(nullptr, dc);
return bmp;
}
char reserved_space[sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * 2];
BITMAPINFOHEADER& head = *(BITMAPINFOHEADER*)reserved_space;
head.biSize = sizeof(BITMAPINFOHEADER);
head.biWidth = aWidth;
head.biHeight = aHeight;
head.biPlanes = 1;
head.biBitCount = (WORD)aDepth;
head.biCompression = BI_RGB;
head.biSizeImage = 0; // Uncompressed
head.biXPelsPerMeter = 0;
head.biYPelsPerMeter = 0;
head.biClrUsed = 0;
head.biClrImportant = 0;
BITMAPINFO& bi = *(BITMAPINFO*)reserved_space;
if (aDepth == 1) {
RGBQUAD black = { 0, 0, 0, 0 };
RGBQUAD white = { 255, 255, 255, 0 };
bi.bmiColors[0] = white;
bi.bmiColors[1] = black;
}
HBITMAP bmp = ::CreateDIBitmap(dc, &head, CBM_INIT, aImageData, &bi, DIB_RGB_COLORS);
::ReleaseDC(nullptr, dc);
return bmp;
}