Files
palemoon27/view/nsView.cpp
T
roytam1 b6f6aa65fb import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1165518 - Part 2: Replace prlog.h with Logging.h. rs=froydnj (342dfd711)
- Bug 1085567 - Fixup synth events within pointer lock implementation for e10s. r=billm (45c50a0e6)
- Bug 1128238 - Ajust NPP_SetWindow and synth native event coords to account for the chrome offset of remote tabs. Prior to this the content process always assumed the tab was the window origin. r=aklotz (202ffc006)
- Bug 1128934 - Avoid calling GetClientBounds from BasicComposior. r=roc, karlt (5e98232bd)
- Bug 1149041 - Make nsIWidget::SizeConstraints use LayoutDeviceIntSize instead of unit-less nsIntSize. r=roc (d0b345926)
- shuffle around (fcdc51510)
- Bug 1142852 P1 Fix NS_NewNonOwningRunnableMethodWithArgs() so that it compiles. r=froydnj (394d2b200)
- Bug 1142852 P2 Make Cache Action use non-threadsafe ref-counting. r=ehsan (0b2b91d86)
- Bug 1146349 - Allow NS_NewRunnableMethodWithArgs to take up to 8 arguments. r=froydnj (7207e74d0)
- Bug 1146349 - Make the native event synthesization functions in DOMWindowUtils async. r=smaug (e43579a1d)
- Bug 949614 - Use === for SimpleTest.is; r=Waldo (9f54faca4)
- Bug 1146349 - Update some widget tests to deal with async native key event synthesization. r=smaug,masayuki (f1e82df79)
- Bug 920013 - Rewrite test_cocoa_focus.html to use SpecialPowers. r=smichaud (8708d6a71)
- Bug 1146349 - Update DOM mochitests to deal with async native event synthesization. r=smaug (a4eceb9f6)
- Bug 1146349 - Update browser-chrome mochitests to deal with async native event synthesization. r=Gijs (c864ad939)
- Bug 1146349 - Wire up native event synthesization in child processes.  r=smaug (e8574457e)
- Bug 1146349 - Mark SynthesizedEventObserver::Observe() as override (9063f04b5)
- Bug 1149613 - Remove unneded field. r=botond (9aa7155e2)
- Bug 1153613 - [e10s], ensure the buffer for the drag image is large enough for SourceSurfaceRawData::GuaranteePersistance() to succeed, r=mattwoodrow (aa885dae7)
- remove spurious file (ff199d3ae)
- Bug 1043013 - Generalize nsIntRegion into a BaseIntRegion template. r=jrmuizel (9d3e02820)
- Bug 1043013 - Introduce IntRegionTyped. r=jrmuizel (f73902921)
- Bug 1043013 - Use strongly-typed regions in HitTestingTreeNode. r=kats (7b8c8ae44)
- Bug 913443 - Remove mention of the word ThebesLayer in a comment. r=roc (e9706e025)
- Bug 913443 - Remove some #ifdefs. r=roc (da76f831b)
- Bug 913443 - Break up CreateOrRecyclePaintedLayer into more parts. r=roc (dd94560fe)
- Bug 913443 - Extract layer hint calculation. r=roc (5c7806a95)
- Bug 913443 - Break CreateOrRecyclePaintedLayer up even more. r=roc (9e5edab17)
- Bug 913443 - Remove unused aItemVisibleRect argument. r=roc (f3d1a5195)
- Bug 913443 - Move IsWidgetLayerManager() check out of UpdateCommonClipCount. r=roc (3be7b19a6)
- Bug 913443 - Change the order of these calls. r=roc (c7bc59fee)
- Bug 913443 - Add a display item buffer for PaintedLayerData so that we can assign items without needing to know the actual Layer. r=roc (674df6aa8)
- Bug 913443 - Delay PaintedLayer recycling until PopPaintedLayerData() r=roc (9d6de961a)
- Bug 913443 - When determining the layer to recycle, only consider layers that have display items in common with the layer we need. r=roc (3327c31c5)
- Bug 913443 - Recycle PaintedLayers as soon as possible. r=roc (37ef6d530)
- Bug 913443 - Remove duplicated argument variables. r=roc (19c5af270)
- Bug 1141408 - Don't include the display item's memory address in the profile label. r=BenWa (5bb1d73c1)
- Bug 1141281 - Don't put empty Info: lines into the layers dump. r=BenWa (85f4b28be)
- Bug 1035611 - Part 1: Updated Matrix4x4::ProjectRectBounds to properly handle infinite values when untransformed rects cross the w=0 plane. r=mattwoodrow (f47ed4383)
- Bug 1035611 - Part 2: Test to ensure that transformed rects crossing the w=0 plane are clipped correctly. r=mattwoodrow (5701b435f)
- Bug 1141089 - Add some release assertions to gather more data. r=roc (805c2994d)
- Bug 1141595 - Make scroll info display item hoisting work after bug 913443. r=tn (1efcaf164)
- Bug 1144307 - Destroy scroll info layer items when we're done with them. r=tn (3ffd3b1f2)
- Bug 1148855 - Mark some ContainerState methods as const. r=roc (791585baf)
- Bug 1144820 - Use rvalue reference in AddProfileTimelineMarker. r=smaug (12316b65f)
- Bug 1148855 - Set overflow:hidden on scrollbar tracks so that layerization knows that the scrollbar thumb won't leave the scrollbar. r=roc (082ec87bf)
- Bug 1148855 - Intermediate state that unifies APZ and non-APZ layerization behavior somewhat. (3da45ab96)
- Bug 1148855 - Rework how display items are assigned to PaintedLayers and make it work the same way with and without APZ. r=roc (7258f9c90)
- Bug 913443 - Add some tests. r=roc (9977682da)
- Bug 1039926 - Add a test for not invalidating stuff inside mask layers. (1f8aef65e)
- Bug 1148855 - Add some tests. r=roc (2ba1f7f18)
- Bug 1148855 - Tweak reftest fuzziness. (a600be7d5)
- Bug 1151306 - Add a missing check during background color pulling. r=roc (b3a6c886b)
- Bug 1150774 (Part 1) - Add helpers to simplify using typed units in ConfigureLayer. r=botond (baecb2c2e)
- Bug 1150774 (Part 2) - Use the correct units in nsDisplayImageContainer::ConfigureLayer and related code. r=botond (a79beb1fb)
- Bug 1141089 - Initialize DisplayItemData with a non-null mLayer, so that mLayer is non-null throughout the object's whole lifetime. r=roc (7c2f9eb09)
- Bug 1141089 - Remove unused DisplayItemData copy constructor. r=roc (ba5c46c45)
- Bug 1141089 - Add a few more MOZ_RELEASE_ASSERT(mLayer) checks, just for fun. r=roc (50a8f2db7)
- Bug 1141089 - Use const nsTArray* in all the places where we don't change the array's contents. r=roc (cd07a5bbd)
- Bug 1141089 - Turn these two assertions into release assertions. r=roc (71daf5ef3)
- Bug 1141089 - Check that we're unsetting sDestroyedFrame correctly. r=roc (6c7da67e7)
- Bug 1143522 - Convert Layer::mClipRect to ParentLayerIntRect. r=botond (ddab1c0ff)
- Bug 1144951. Warn if the result of ConvertAppUnits is unused. r=mats (e1d79c6ca)
- Bug 1144951. Rename ConvertAppUnits to ScaleToOtherAppUnits. r=mats (675c918c3)
- Bug 1149035 - Make nsXULPopupManager::PopupResized take a LayoutDeviceIntSize param instead of a unit-less nsIntSize. r=roc (eb9529af7)
- missing bit of Bug 1156110 - Make nsView::mWindow an nsCOMPtr; r=roc (972255b4f)
- Bug 1147706 - Warn if we don't use the result of const methods on BaseRect and its subclasses. r=tn (9e91deada)
- Bug 1152838 - Fix BaseRect::InflateToMultiple and move it to nsIntRect. r=mattwoodrow, r=jrmuizel (5a942df29)
- Bug 1125055 - Sync decode layerized images if necessary. r=roc,tn (1379db5c7)
- Bug 1145167 - make imgIContainer::type getter infallible; r=seth (7b7091b89)
- Bug 1148213 - Implement image locking for VectorImage. r=dholbert (240e14cb3)
- Bug 1143653 - Crash in CompositorD3D9 rather than TextureD3D9 if device reset fails, after a few attemps. r=jrmuizel (76607ddc3)
- Bug 1147894 - Only use non-null compositors with TextureHost::SetCompositor. r=sotaro (605bf34f6)
- Bug 1146912 - Finish replacing TextureHost::GetTextureSource by BindTextureSource. r=sotaro (cf3763879)
- Bug 1132854 - Remove useless ThebesIntSize conversion helper. r=Bas (78cdfee14)
- Bug 1068881 - Inflate the dest rect to at least one device pixel when computing the optimal image size for drawing. r=roc (3d5644913)
2020-05-30 12:49:08 +08:00

1091 lines
31 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/. */
#include "nsView.h"
#include "mozilla/Attributes.h"
#include "mozilla/BasicEvents.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/IntegerPrintfMacros.h"
#include "mozilla/Likely.h"
#include "mozilla/Poison.h"
#include "nsIWidget.h"
#include "nsViewManager.h"
#include "nsIFrame.h"
#include "nsPresArena.h"
#include "nsXULPopupManager.h"
#include "nsIWidgetListener.h"
#include "nsContentUtils.h" // for nsAutoScriptBlocker
using namespace mozilla;
nsView::nsView(nsViewManager* aViewManager, nsViewVisibility aVisibility)
{
MOZ_COUNT_CTOR(nsView);
mVis = aVisibility;
// Views should be transparent by default. Not being transparent is
// a promise that the view will paint all its pixels opaquely. Views
// should make this promise explicitly by calling
// SetViewContentTransparency.
mVFlags = 0;
mViewManager = aViewManager;
mDirtyRegion = nullptr;
mWidgetIsTopLevel = false;
}
void nsView::DropMouseGrabbing()
{
nsIPresShell* presShell = mViewManager->GetPresShell();
if (presShell)
presShell->ClearMouseCaptureOnView(this);
}
nsView::~nsView()
{
MOZ_COUNT_DTOR(nsView);
while (GetFirstChild())
{
nsView* child = GetFirstChild();
if (child->GetViewManager() == mViewManager) {
child->Destroy();
} else {
// just unhook it. Someone else will want to destroy this.
RemoveChild(child);
}
}
if (mViewManager)
{
DropMouseGrabbing();
nsView *rootView = mViewManager->GetRootView();
if (rootView)
{
// Root views can have parents!
if (mParent)
{
mViewManager->RemoveChild(this);
}
if (rootView == this)
{
// Inform the view manager that the root view has gone away...
mViewManager->SetRootView(nullptr);
}
}
else if (mParent)
{
mParent->RemoveChild(this);
}
mViewManager = nullptr;
}
else if (mParent)
{
mParent->RemoveChild(this);
}
// Destroy and release the widget
DestroyWidget();
delete mDirtyRegion;
}
class DestroyWidgetRunnable : public nsRunnable {
public:
NS_DECL_NSIRUNNABLE
explicit DestroyWidgetRunnable(nsIWidget* aWidget) : mWidget(aWidget) {}
private:
nsCOMPtr<nsIWidget> mWidget;
};
NS_IMETHODIMP DestroyWidgetRunnable::Run()
{
mWidget->Destroy();
mWidget = nullptr;
return NS_OK;
}
void nsView::DestroyWidget()
{
if (mWindow)
{
// If we are not attached to a base window, we're going to tear down our
// widget here. However, if we're attached to somebody elses widget, we
// want to leave the widget alone: don't reset the client data or call
// Destroy. Just clear our event view ptr and free our reference to it.
if (mWidgetIsTopLevel) {
mWindow->SetAttachedWidgetListener(nullptr);
}
else {
mWindow->SetWidgetListener(nullptr);
nsCOMPtr<nsIRunnable> widgetDestroyer =
new DestroyWidgetRunnable(mWindow);
NS_DispatchToMainThread(widgetDestroyer);
}
NS_RELEASE(mWindow);
}
}
nsView* nsView::GetViewFor(nsIWidget* aWidget)
{
NS_PRECONDITION(nullptr != aWidget, "null widget ptr");
nsIWidgetListener* listener = aWidget->GetWidgetListener();
if (listener) {
nsView* view = listener->GetView();
if (view)
return view;
}
listener = aWidget->GetAttachedWidgetListener();
return listener ? listener->GetView() : nullptr;
}
void nsView::Destroy()
{
this->~nsView();
mozWritePoison(this, sizeof(*this));
nsView::operator delete(this);
}
void nsView::SetPosition(nscoord aX, nscoord aY)
{
mDimBounds.x += aX - mPosX;
mDimBounds.y += aY - mPosY;
mPosX = aX;
mPosY = aY;
NS_ASSERTION(GetParent() || (aX == 0 && aY == 0),
"Don't try to move the root widget to something non-zero");
ResetWidgetBounds(true, false);
}
void nsView::ResetWidgetBounds(bool aRecurse, bool aForceSync)
{
if (mWindow) {
if (!aForceSync) {
// Don't change widget geometry synchronously, since that can
// cause synchronous painting.
mViewManager->PostPendingUpdate();
} else {
DoResetWidgetBounds(false, true);
}
return;
}
if (aRecurse) {
// reposition any widgets under this view
for (nsView* v = GetFirstChild(); v; v = v->GetNextSibling()) {
v->ResetWidgetBounds(true, aForceSync);
}
}
}
bool nsView::IsEffectivelyVisible()
{
for (nsView* v = this; v; v = v->mParent) {
if (v->GetVisibility() == nsViewVisibility_kHide)
return false;
}
return true;
}
nsIntRect nsView::CalcWidgetBounds(nsWindowType aType)
{
int32_t p2a = mViewManager->AppUnitsPerDevPixel();
nsRect viewBounds(mDimBounds);
nsView* parent = GetParent();
nsIWidget* parentWidget = nullptr;
if (parent) {
nsPoint offset;
parentWidget = parent->GetNearestWidget(&offset, p2a);
// make viewBounds be relative to the parent widget, in appunits
viewBounds += offset;
if (parentWidget && aType == eWindowType_popup &&
IsEffectivelyVisible()) {
// put offset into screen coordinates. (based on client area origin)
LayoutDeviceIntPoint screenPoint = parentWidget->WidgetToScreenOffset();
viewBounds += nsPoint(NSIntPixelsToAppUnits(screenPoint.x, p2a),
NSIntPixelsToAppUnits(screenPoint.y, p2a));
}
}
// Compute widget bounds in device pixels
nsIntRect newBounds = viewBounds.ToNearestPixels(p2a);
#ifdef XP_MACOSX
// cocoa rounds widget coordinates to the nearest global "display pixel"
// integer value. So we avoid fractional display pixel values by rounding
// to the nearest value that won't yield a fractional display pixel.
nsIWidget* widget = parentWidget ? parentWidget : mWindow;
uint32_t round;
if (aType == eWindowType_popup && widget &&
((round = widget->RoundsWidgetCoordinatesTo()) > 1)) {
nsIntSize pixelRoundedSize = newBounds.Size();
// round the top left and bottom right to the nearest round pixel
newBounds.x = NSToIntRoundUp(NSAppUnitsToDoublePixels(viewBounds.x, p2a) / round) * round;
newBounds.y = NSToIntRoundUp(NSAppUnitsToDoublePixels(viewBounds.y, p2a) / round) * round;
newBounds.width =
NSToIntRoundUp(NSAppUnitsToDoublePixels(viewBounds.XMost(), p2a) / round) * round - newBounds.x;
newBounds.height =
NSToIntRoundUp(NSAppUnitsToDoublePixels(viewBounds.YMost(), p2a) / round) * round - newBounds.y;
// but if that makes the widget larger then our frame may not paint the
// extra pixels, so reduce the size to the nearest round value
if (newBounds.width > pixelRoundedSize.width) {
newBounds.width -= round;
}
if (newBounds.height > pixelRoundedSize.height) {
newBounds.height -= round;
}
}
#endif
// Compute where the top-left of our widget ended up relative to the parent
// widget, in appunits.
nsPoint roundedOffset(NSIntPixelsToAppUnits(newBounds.x, p2a),
NSIntPixelsToAppUnits(newBounds.y, p2a));
// mViewToWidgetOffset is added to coordinates relative to the view origin
// to get coordinates relative to the widget.
// The view origin, relative to the parent widget, is at
// (mPosX,mPosY) - mDimBounds.TopLeft() + viewBounds.TopLeft().
// Our widget, relative to the parent widget, is roundedOffset.
mViewToWidgetOffset = nsPoint(mPosX, mPosY)
- mDimBounds.TopLeft() + viewBounds.TopLeft() - roundedOffset;
return newBounds;
}
void nsView::DoResetWidgetBounds(bool aMoveOnly,
bool aInvalidateChangedSize) {
// The geometry of a root view's widget is controlled externally,
// NOT by sizing or positioning the view
if (mViewManager->GetRootView() == this) {
return;
}
NS_PRECONDITION(mWindow, "Why was this called??");
// Hold this ref to make sure it stays alive.
nsCOMPtr<nsIWidget> widget = mWindow;
// Stash a copy of these and use them so we can handle this being deleted (say
// from sync painting/flushing from Show/Move/Resize on the widget).
nsIntRect newBounds;
nsRefPtr<nsDeviceContext> dx = mViewManager->GetDeviceContext();
nsWindowType type = widget->WindowType();
nsIntRect curBounds;
widget->GetClientBounds(curBounds);
bool invisiblePopup = type == eWindowType_popup &&
((curBounds.IsEmpty() && mDimBounds.IsEmpty()) ||
mVis == nsViewVisibility_kHide);
if (invisiblePopup) {
// We're going to hit the early exit below, avoid calling CalcWidgetBounds.
} else {
newBounds = CalcWidgetBounds(type);
}
bool curVisibility = widget->IsVisible();
bool newVisibility = IsEffectivelyVisible();
if (curVisibility && !newVisibility) {
widget->Show(false);
}
if (invisiblePopup) {
// Don't manipulate empty or hidden popup widgets. For example there's no
// point moving hidden comboboxes around, or doing X server roundtrips
// to compute their true screen position. This could mean that WidgetToScreen
// operations on these widgets don't return up-to-date values, but popup
// positions aren't reliable anyway because of correction to be on or off-screen.
return;
}
bool changedPos = curBounds.TopLeft() != newBounds.TopLeft();
bool changedSize = curBounds.Size() != newBounds.Size();
// Child views are never attached to top level widgets, this is safe.
// Coordinates are converted to display pixels for window Move/Resize APIs,
// because of the potential for device-pixel coordinate spaces for mixed
// hidpi/lodpi screens to overlap each other and result in bad placement
// (bug 814434).
double invScale;
// Bug 861270: for correct widget manipulation at arbitrary scale factors,
// prefer to base scaling on widget->GetDefaultScale(). But only do this if
// it matches the view manager's device context scale after allowing for the
// quantization to app units, because of OS X multiscreen issues (where the
// only two scales are 1.0 or 2.0, and so the quantization doesn't actually
// cause problems anyhow).
// In the case of a mismatch, fall back to scaling based on the dev context's
// AppUnitsPerDevPixelAtUnitFullZoom value. On platforms where the device-pixel
// scale is uniform across all displays (currently all except OS X), we'll
// always use the precise value from mWindow->GetDefaultScale here.
CSSToLayoutDeviceScale scale = widget->GetDefaultScale();
if (NSToIntRound(60.0 / scale.scale) == dx->AppUnitsPerDevPixelAtUnitFullZoom()) {
invScale = 1.0 / scale.scale;
} else {
invScale = dx->AppUnitsPerDevPixelAtUnitFullZoom() / 60.0;
}
if (changedPos) {
if (changedSize && !aMoveOnly) {
widget->ResizeClient(newBounds.x * invScale,
newBounds.y * invScale,
newBounds.width * invScale,
newBounds.height * invScale,
aInvalidateChangedSize);
} else {
widget->MoveClient(newBounds.x * invScale,
newBounds.y * invScale);
}
} else {
if (changedSize && !aMoveOnly) {
widget->ResizeClient(newBounds.width * invScale,
newBounds.height * invScale,
aInvalidateChangedSize);
} // else do nothing!
}
if (!curVisibility && newVisibility) {
widget->Show(true);
}
}
void nsView::SetDimensions(const nsRect& aRect, bool aPaint, bool aResizeWidget)
{
nsRect dims = aRect;
dims.MoveBy(mPosX, mPosY);
// Don't use nsRect's operator== here, since it returns true when
// both rects are empty even if they have different widths and we
// have cases where that sort of thing matters to us.
if (mDimBounds.TopLeft() == dims.TopLeft() &&
mDimBounds.Size() == dims.Size()) {
return;
}
mDimBounds = dims;
if (aResizeWidget) {
ResetWidgetBounds(false, false);
}
}
void nsView::NotifyEffectiveVisibilityChanged(bool aEffectivelyVisible)
{
if (!aEffectivelyVisible)
{
DropMouseGrabbing();
}
SetForcedRepaint(true);
if (nullptr != mWindow)
{
ResetWidgetBounds(false, false);
}
for (nsView* child = mFirstChild; child; child = child->mNextSibling) {
if (child->mVis == nsViewVisibility_kHide) {
// It was effectively hidden and still is
continue;
}
// Our child is visible if we are
child->NotifyEffectiveVisibilityChanged(aEffectivelyVisible);
}
}
void nsView::SetVisibility(nsViewVisibility aVisibility)
{
mVis = aVisibility;
NotifyEffectiveVisibilityChanged(IsEffectivelyVisible());
}
void nsView::SetFloating(bool aFloatingView)
{
if (aFloatingView)
mVFlags |= NS_VIEW_FLAG_FLOATING;
else
mVFlags &= ~NS_VIEW_FLAG_FLOATING;
}
void nsView::InvalidateHierarchy(nsViewManager *aViewManagerParent)
{
if (mViewManager->GetRootView() == this)
mViewManager->InvalidateHierarchy();
for (nsView *child = mFirstChild; child; child = child->GetNextSibling())
child->InvalidateHierarchy(aViewManagerParent);
}
void nsView::InsertChild(nsView *aChild, nsView *aSibling)
{
NS_PRECONDITION(nullptr != aChild, "null ptr");
if (nullptr != aChild)
{
if (nullptr != aSibling)
{
#ifdef DEBUG
NS_ASSERTION(aSibling->GetParent() == this, "tried to insert view with invalid sibling");
#endif
//insert after sibling
aChild->SetNextSibling(aSibling->GetNextSibling());
aSibling->SetNextSibling(aChild);
}
else
{
aChild->SetNextSibling(mFirstChild);
mFirstChild = aChild;
}
aChild->SetParent(this);
// If we just inserted a root view, then update the RootViewManager
// on all view managers in the new subtree.
nsViewManager *vm = aChild->GetViewManager();
if (vm->GetRootView() == aChild)
{
aChild->InvalidateHierarchy(nullptr); // don't care about releasing grabs
}
}
}
void nsView::RemoveChild(nsView *child)
{
NS_PRECONDITION(nullptr != child, "null ptr");
if (nullptr != child)
{
nsView* prevKid = nullptr;
nsView* kid = mFirstChild;
DebugOnly<bool> found = false;
while (nullptr != kid) {
if (kid == child) {
if (nullptr != prevKid) {
prevKid->SetNextSibling(kid->GetNextSibling());
} else {
mFirstChild = kid->GetNextSibling();
}
child->SetParent(nullptr);
found = true;
break;
}
prevKid = kid;
kid = kid->GetNextSibling();
}
NS_ASSERTION(found, "tried to remove non child");
// If we just removed a root view, then update the RootViewManager
// on all view managers in the removed subtree.
nsViewManager *vm = child->GetViewManager();
if (vm->GetRootView() == child)
{
child->InvalidateHierarchy(GetViewManager());
}
}
}
// Native widgets ultimately just can't deal with the awesome power of
// CSS2 z-index. However, we set the z-index on the widget anyway
// because in many simple common cases the widgets do end up in the
// right order. We set each widget's z-index to the z-index of the
// nearest ancestor that has non-auto z-index.
static void UpdateNativeWidgetZIndexes(nsView* aView, int32_t aZIndex)
{
if (aView->HasWidget()) {
nsIWidget* widget = aView->GetWidget();
if (widget->GetZIndex() != aZIndex) {
widget->SetZIndex(aZIndex);
}
} else {
for (nsView* v = aView->GetFirstChild(); v; v = v->GetNextSibling()) {
if (v->GetZIndexIsAuto()) {
UpdateNativeWidgetZIndexes(v, aZIndex);
}
}
}
}
static int32_t FindNonAutoZIndex(nsView* aView)
{
while (aView) {
if (!aView->GetZIndexIsAuto()) {
return aView->GetZIndex();
}
aView = aView->GetParent();
}
return 0;
}
struct DefaultWidgetInitData : public nsWidgetInitData {
DefaultWidgetInitData() : nsWidgetInitData()
{
mWindowType = eWindowType_child;
clipChildren = true;
clipSiblings = true;
}
};
nsresult nsView::CreateWidget(nsWidgetInitData *aWidgetInitData,
bool aEnableDragDrop,
bool aResetVisibility)
{
AssertNoWindow();
MOZ_ASSERT(!aWidgetInitData ||
aWidgetInitData->mWindowType != eWindowType_popup,
"Use CreateWidgetForPopup");
DefaultWidgetInitData defaultInitData;
bool initDataPassedIn = !!aWidgetInitData;
aWidgetInitData = aWidgetInitData ? aWidgetInitData : &defaultInitData;
defaultInitData.mListenForResizes =
(!initDataPassedIn && GetParent() &&
GetParent()->GetViewManager() != mViewManager);
nsIntRect trect = CalcWidgetBounds(aWidgetInitData->mWindowType);
nsIWidget* parentWidget =
GetParent() ? GetParent()->GetNearestWidget(nullptr) : nullptr;
if (!parentWidget) {
NS_ERROR("nsView::CreateWidget without suitable parent widget??");
return NS_ERROR_FAILURE;
}
// XXX: using aForceUseIWidgetParent=true to preserve previous
// semantics. It's not clear that it's actually needed.
mWindow = parentWidget->CreateChild(trect, aWidgetInitData, true).take();
if (!mWindow) {
return NS_ERROR_FAILURE;
}
InitializeWindow(aEnableDragDrop, aResetVisibility);
return NS_OK;
}
nsresult nsView::CreateWidgetForParent(nsIWidget* aParentWidget,
nsWidgetInitData *aWidgetInitData,
bool aEnableDragDrop,
bool aResetVisibility)
{
AssertNoWindow();
MOZ_ASSERT(!aWidgetInitData ||
aWidgetInitData->mWindowType != eWindowType_popup,
"Use CreateWidgetForPopup");
MOZ_ASSERT(aParentWidget, "Parent widget required");
DefaultWidgetInitData defaultInitData;
aWidgetInitData = aWidgetInitData ? aWidgetInitData : &defaultInitData;
nsIntRect trect = CalcWidgetBounds(aWidgetInitData->mWindowType);
mWindow =
aParentWidget->CreateChild(trect, aWidgetInitData).take();
if (!mWindow) {
return NS_ERROR_FAILURE;
}
InitializeWindow(aEnableDragDrop, aResetVisibility);
return NS_OK;
}
nsresult nsView::CreateWidgetForPopup(nsWidgetInitData *aWidgetInitData,
nsIWidget* aParentWidget,
bool aEnableDragDrop,
bool aResetVisibility)
{
AssertNoWindow();
MOZ_ASSERT(aWidgetInitData, "Widget init data required");
MOZ_ASSERT(aWidgetInitData->mWindowType == eWindowType_popup,
"Use one of the other CreateWidget methods");
nsIntRect trect = CalcWidgetBounds(aWidgetInitData->mWindowType);
// XXX/cjones: having these two separate creation cases seems ... um
// ... unnecessary, but it's the way the old code did it. Please
// unify them by first finding a suitable parent nsIWidget, then
// getting rid of aForceUseIWidgetParent.
if (aParentWidget) {
// XXX: using aForceUseIWidgetParent=true to preserve previous
// semantics. It's not clear that it's actually needed.
mWindow = aParentWidget->CreateChild(trect, aWidgetInitData, true).take();
}
else {
nsIWidget* nearestParent = GetParent() ? GetParent()->GetNearestWidget(nullptr)
: nullptr;
if (!nearestParent) {
// Without a parent, we can't make a popup. This can happen
// when printing
return NS_ERROR_FAILURE;
}
mWindow = nearestParent->CreateChild(trect, aWidgetInitData).take();
}
if (!mWindow) {
return NS_ERROR_FAILURE;
}
InitializeWindow(aEnableDragDrop, aResetVisibility);
return NS_OK;
}
void
nsView::InitializeWindow(bool aEnableDragDrop, bool aResetVisibility)
{
MOZ_ASSERT(mWindow, "Must have a window to initialize");
mWindow->SetWidgetListener(this);
if (aEnableDragDrop) {
mWindow->EnableDragDrop(true);
}
// propagate the z-index to the widget.
UpdateNativeWidgetZIndexes(this, FindNonAutoZIndex(this));
//make sure visibility state is accurate
if (aResetVisibility) {
SetVisibility(GetVisibility());
}
}
// Attach to a top level widget and start receiving mirrored events.
nsresult nsView::AttachToTopLevelWidget(nsIWidget* aWidget)
{
NS_PRECONDITION(nullptr != aWidget, "null widget ptr");
/// XXXjimm This is a temporary workaround to an issue w/document
// viewer (bug 513162).
nsIWidgetListener* listener = aWidget->GetAttachedWidgetListener();
if (listener) {
nsView *oldView = listener->GetView();
if (oldView) {
oldView->DetachFromTopLevelWidget();
}
}
// Note, the previous device context will be released. Detaching
// will not restore the old one.
nsresult rv = aWidget->AttachViewToTopLevel(!nsIWidget::UsePuppetWidgets());
if (NS_FAILED(rv))
return rv;
mWindow = aWidget;
NS_ADDREF(mWindow);
mWindow->SetAttachedWidgetListener(this);
mWindow->EnableDragDrop(true);
mWidgetIsTopLevel = true;
// Refresh the view bounds
CalcWidgetBounds(mWindow->WindowType());
return NS_OK;
}
// Detach this view from an attached widget.
nsresult nsView::DetachFromTopLevelWidget()
{
NS_PRECONDITION(mWidgetIsTopLevel, "Not attached currently!");
NS_PRECONDITION(mWindow, "null mWindow for DetachFromTopLevelWidget!");
mWindow->SetAttachedWidgetListener(nullptr);
NS_RELEASE(mWindow);
mWidgetIsTopLevel = false;
return NS_OK;
}
void nsView::SetZIndex(bool aAuto, int32_t aZIndex)
{
bool oldIsAuto = GetZIndexIsAuto();
mVFlags = (mVFlags & ~NS_VIEW_FLAG_AUTO_ZINDEX) | (aAuto ? NS_VIEW_FLAG_AUTO_ZINDEX : 0);
mZIndex = aZIndex;
if (HasWidget() || !oldIsAuto || !aAuto) {
UpdateNativeWidgetZIndexes(this, FindNonAutoZIndex(this));
}
}
void nsView::AssertNoWindow()
{
// XXX: it would be nice to make this a strong assert
if (MOZ_UNLIKELY(mWindow)) {
NS_ERROR("We already have a window for this view? BAD");
mWindow->SetWidgetListener(nullptr);
mWindow->Destroy();
NS_RELEASE(mWindow);
}
}
//
// internal window creation functions
//
void nsView::AttachWidgetEventHandler(nsIWidget* aWidget)
{
#ifdef DEBUG
NS_ASSERTION(!aWidget->GetWidgetListener(), "Already have a widget listener");
#endif
aWidget->SetWidgetListener(this);
}
void nsView::DetachWidgetEventHandler(nsIWidget* aWidget)
{
NS_ASSERTION(!aWidget->GetWidgetListener() ||
aWidget->GetWidgetListener()->GetView() == this, "Wrong view");
aWidget->SetWidgetListener(nullptr);
}
#ifdef DEBUG
void nsView::List(FILE* out, int32_t aIndent) const
{
int32_t i;
for (i = aIndent; --i >= 0; ) fputs(" ", out);
fprintf(out, "%p ", (void*)this);
if (nullptr != mWindow) {
nscoord p2a = mViewManager->AppUnitsPerDevPixel();
nsIntRect rect;
mWindow->GetClientBounds(rect);
nsRect windowBounds = rect.ToAppUnits(p2a);
mWindow->GetBounds(rect);
nsRect nonclientBounds = rect.ToAppUnits(p2a);
nsrefcnt widgetRefCnt = mWindow.get()->AddRef() - 1;
mWindow.get()->Release();
int32_t Z = mWindow->GetZIndex();
fprintf(out, "(widget=%p[%" PRIuPTR "] z=%d pos={%d,%d,%d,%d}) ",
(void*)mWindow, widgetRefCnt, Z,
nonclientBounds.x, nonclientBounds.y,
windowBounds.width, windowBounds.height);
}
nsRect brect = GetBounds();
fprintf(out, "{%d,%d,%d,%d}",
brect.x, brect.y, brect.width, brect.height);
fprintf(out, " z=%d vis=%d frame=%p <\n",
mZIndex, mVis, static_cast<void*>(mFrame));
for (nsView* kid = mFirstChild; kid; kid = kid->GetNextSibling()) {
NS_ASSERTION(kid->GetParent() == this, "incorrect parent");
kid->List(out, aIndent + 1);
}
for (i = aIndent; --i >= 0; ) fputs(" ", out);
fputs(">\n", out);
}
#endif // DEBUG
nsPoint nsView::GetOffsetTo(const nsView* aOther) const
{
return GetOffsetTo(aOther, GetViewManager()->AppUnitsPerDevPixel());
}
nsPoint nsView::GetOffsetTo(const nsView* aOther, const int32_t aAPD) const
{
MOZ_ASSERT(GetParent() || !aOther || aOther->GetParent() || this == aOther,
"caller of (outer) GetOffsetTo must not pass unrelated views");
// We accumulate the final result in offset
nsPoint offset(0, 0);
// The offset currently accumulated at the current APD
nsPoint docOffset(0, 0);
const nsView* v = this;
nsViewManager* currVM = v->GetViewManager();
int32_t currAPD = currVM->AppUnitsPerDevPixel();
const nsView* root = nullptr;
for ( ; v != aOther && v; root = v, v = v->GetParent()) {
nsViewManager* newVM = v->GetViewManager();
if (newVM != currVM) {
int32_t newAPD = newVM->AppUnitsPerDevPixel();
if (newAPD != currAPD) {
offset += docOffset.ScaleToOtherAppUnits(currAPD, aAPD);
docOffset.x = docOffset.y = 0;
currAPD = newAPD;
}
currVM = newVM;
}
docOffset += v->GetPosition();
}
offset += docOffset.ScaleToOtherAppUnits(currAPD, aAPD);
if (v != aOther) {
// Looks like aOther wasn't an ancestor of |this|. So now we have
// the root-VM-relative position of |this| in |offset|. Get the
// root-VM-relative position of aOther and subtract it.
nsPoint negOffset = aOther->GetOffsetTo(root, aAPD);
offset -= negOffset;
}
return offset;
}
nsPoint nsView::GetOffsetToWidget(nsIWidget* aWidget) const
{
nsPoint pt;
// Get the view for widget
nsView* widgetView = GetViewFor(aWidget);
if (!widgetView) {
return pt;
}
// Get the offset to the widget view in the widget view's APD
// We get the offset in the widget view's APD first and then convert to our
// APD afterwards so that we can include the widget view's ViewToWidgetOffset
// in the sum in its native APD, and then convert the whole thing to our APD
// so that we don't have to convert the APD of the relatively small
// ViewToWidgetOffset by itself with a potentially large relative rounding
// error.
pt = -widgetView->GetOffsetTo(this);
// Add in the offset to the widget.
pt += widgetView->ViewToWidgetOffset();
// Convert to our appunits.
int32_t widgetAPD = widgetView->GetViewManager()->AppUnitsPerDevPixel();
int32_t ourAPD = GetViewManager()->AppUnitsPerDevPixel();
pt = pt.ScaleToOtherAppUnits(widgetAPD, ourAPD);
return pt;
}
nsIWidget* nsView::GetNearestWidget(nsPoint* aOffset) const
{
return GetNearestWidget(aOffset, GetViewManager()->AppUnitsPerDevPixel());
}
nsIWidget* nsView::GetNearestWidget(nsPoint* aOffset, const int32_t aAPD) const
{
// aOffset is based on the view's position, which ignores any chrome on
// attached parent widgets.
// We accumulate the final result in pt
nsPoint pt(0, 0);
// The offset currently accumulated at the current APD
nsPoint docPt(0,0);
const nsView* v = this;
nsViewManager* currVM = v->GetViewManager();
int32_t currAPD = currVM->AppUnitsPerDevPixel();
for ( ; v && !v->HasWidget(); v = v->GetParent()) {
nsViewManager* newVM = v->GetViewManager();
if (newVM != currVM) {
int32_t newAPD = newVM->AppUnitsPerDevPixel();
if (newAPD != currAPD) {
pt += docPt.ScaleToOtherAppUnits(currAPD, aAPD);
docPt.x = docPt.y = 0;
currAPD = newAPD;
}
currVM = newVM;
}
docPt += v->GetPosition();
}
if (!v) {
if (aOffset) {
pt += docPt.ScaleToOtherAppUnits(currAPD, aAPD);
*aOffset = pt;
}
return nullptr;
}
// pt is now the offset from v's origin to this view's origin.
// We add the ViewToWidgetOffset to get the offset to the widget.
if (aOffset) {
docPt += v->ViewToWidgetOffset();
pt += docPt.ScaleToOtherAppUnits(currAPD, aAPD);
*aOffset = pt;
}
return v->GetWidget();
}
bool nsView::IsRoot() const
{
NS_ASSERTION(mViewManager != nullptr," View manager is null in nsView::IsRoot()");
return mViewManager->GetRootView() == this;
}
nsRect
nsView::GetBoundsInParentUnits() const
{
nsView* parent = GetParent();
nsViewManager* VM = GetViewManager();
if (this != VM->GetRootView() || !parent) {
return mDimBounds;
}
int32_t ourAPD = VM->AppUnitsPerDevPixel();
int32_t parentAPD = parent->GetViewManager()->AppUnitsPerDevPixel();
return mDimBounds.ScaleToOtherAppUnitsRoundOut(ourAPD, parentAPD);
}
nsPoint
nsView::ConvertFromParentCoords(nsPoint aPt) const
{
const nsView* parent = GetParent();
if (parent) {
aPt = aPt.ScaleToOtherAppUnits(
parent->GetViewManager()->AppUnitsPerDevPixel(),
GetViewManager()->AppUnitsPerDevPixel());
}
aPt -= GetPosition();
return aPt;
}
static bool
IsPopupWidget(nsIWidget* aWidget)
{
return (aWidget->WindowType() == eWindowType_popup);
}
nsIPresShell*
nsView::GetPresShell()
{
return GetViewManager()->GetPresShell();
}
bool
nsView::WindowMoved(nsIWidget* aWidget, int32_t x, int32_t y)
{
nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
if (pm && IsPopupWidget(aWidget)) {
pm->PopupMoved(mFrame, nsIntPoint(x, y));
return true;
}
return false;
}
bool
nsView::WindowResized(nsIWidget* aWidget, int32_t aWidth, int32_t aHeight)
{
// The root view may not be set if this is the resize associated with
// window creation
SetForcedRepaint(true);
if (this == mViewManager->GetRootView()) {
nsRefPtr<nsDeviceContext> devContext = mViewManager->GetDeviceContext();
// ensure DPI is up-to-date, in case of window being opened and sized
// on a non-default-dpi display (bug 829963)
devContext->CheckDPIChange();
int32_t p2a = devContext->AppUnitsPerDevPixel();
mViewManager->SetWindowDimensions(NSIntPixelsToAppUnits(aWidth, p2a),
NSIntPixelsToAppUnits(aHeight, p2a));
nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
if (pm) {
nsIPresShell* presShell = mViewManager->GetPresShell();
if (presShell && presShell->GetDocument()) {
pm->AdjustPopupsOnWindowChange(presShell);
}
}
return true;
}
else if (IsPopupWidget(aWidget)) {
nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
if (pm) {
pm->PopupResized(mFrame, LayoutDeviceIntSize(aWidth, aHeight));
return true;
}
}
return false;
}
bool
nsView::RequestWindowClose(nsIWidget* aWidget)
{
if (mFrame && IsPopupWidget(aWidget) &&
mFrame->GetType() == nsGkAtoms::menuPopupFrame) {
nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
if (pm) {
pm->HidePopup(mFrame->GetContent(), false, true, false, false);
return true;
}
}
return false;
}
void
nsView::WillPaintWindow(nsIWidget* aWidget)
{
nsRefPtr<nsViewManager> vm = mViewManager;
vm->WillPaintWindow(aWidget);
}
bool
nsView::PaintWindow(nsIWidget* aWidget, nsIntRegion aRegion)
{
NS_ASSERTION(this == nsView::GetViewFor(aWidget), "wrong view for widget?");
nsRefPtr<nsViewManager> vm = mViewManager;
bool result = vm->PaintWindow(aWidget, aRegion);
return result;
}
void
nsView::DidPaintWindow()
{
nsRefPtr<nsViewManager> vm = mViewManager;
vm->DidPaintWindow();
}
void
nsView::DidCompositeWindow()
{
nsIPresShell* presShell = mViewManager->GetPresShell();
if (presShell) {
nsAutoScriptBlocker scriptBlocker;
presShell->GetPresContext()->GetRootPresContext()->NotifyDidPaintForSubtree(nsIPresShell::PAINT_COMPOSITE);
}
}
void
nsView::RequestRepaint()
{
nsIPresShell* presShell = mViewManager->GetPresShell();
if (presShell) {
presShell->ScheduleViewManagerFlush();
}
}
nsEventStatus
nsView::HandleEvent(WidgetGUIEvent* aEvent,
bool aUseAttachedEvents)
{
NS_PRECONDITION(nullptr != aEvent->widget, "null widget ptr");
nsEventStatus result = nsEventStatus_eIgnore;
nsView* view;
if (aUseAttachedEvents) {
nsIWidgetListener* listener = aEvent->widget->GetAttachedWidgetListener();
view = listener ? listener->GetView() : nullptr;
}
else {
view = GetViewFor(aEvent->widget);
}
if (view) {
nsRefPtr<nsViewManager> vm = view->GetViewManager();
vm->DispatchEvent(aEvent, view, &result);
}
return result;
}