Files
roytam1 69d1f32ff7 import changes from `dev' branch of rmottola/Arctic-Fox:
- Bug 1268085 - Remove unused post barrier callbacks r=terrence (0ab13411c9)
- Bug 1267699 - Move some public types to the right namespace; r=sfink (3d5008e610)
- Bug 1267550 (part 1) - Rename MOZ_MUST_USE as MOZ_MUST_USE_TYPE. r=ehsan. (6f47375796)
- Bug 1259021 - Rename Vector::extractRawBuffer to extractOrCopyRawBuffer r=Waldo (97ca94495b)
- Bug 1259021 - Add Vector::extractRawBuffer method that doesn't copy the buffer r=Waldo (e58deec48f)
- Bug 1265892 - Change Vector to use Impl::new_ consistently. r=Waldo (7a52d21b29)
- Bug 1267912 - Rename nsNetUtil.inl as nsNetUtilInlines.h. r=valentin. (548a41b293)
- Bug 1265690 part 1 - Mark StringBuffer methods WARN_UNUSED_RESULT, fix OOM issues. r=jonco (0d7e6837e3)
- Bug 1265690 part 2 - Fix some more OOM issues in TypedObject code. r=jonco (b60902453e)
- Bug 1263490 - Part 2: Add GetFirstDollarIndex intrinsic and use it inRegExpReplace. r=till (4ba19db8c4)
- Bug 1263490 - Part 3: Inline GetFirstDollarIndex intrinsic. r=h4writer (e7d9b5d1cc)
- Bug 1263490 - Part 4: Fold GetFirstDollarIndex into a integer constant. r=h4writer (3479c7d1af)
- Bug 1267269 - Make MIRType an enum class. r=bbouvier (d580ef372a)
- Bug 1259295 - BaldrMonkey: Postorder (r=luke) (6ef7a77663)
- Bug 1254142: BaldrMonkey: make br_table yield (r=luke) (80e7635e58)
- Bug 1263202 - BaldrMonkey: switch to arities on branches, calls and return (r=bbouvier) (f5a0358634)
- Bug 1236358 - Improper reading of string16 in Pickle::ReadString16. r=jld (8370ba6a0b)
- Bug 1263205 - BaldrMonkey: Update section headers for proposed spec changes (r=luke) (0def2e6bc2)
- Bug 1263205 - BaldrMonkey: Update for proposed new section names (r=luke) (e57f0e3367)
- Bug 1263205 - BaldrMonkey: Add 'form' field to types section (r=bbouvier) (794edc890f)
- Bug 1259021 - Use in-place storage in AutoStableStringChars to avoid allocation for short strings r=jandem r=Waldo (ffb53cbcf4)
- Bug 1267550 (part 2) - Rename MOZ_WARN_UNUSED_RESULT as MOZ_MUST_USE. r=froydnj. (47bc674b86)
- Bug 1268518: Baldr: implement int32/int64 rotations; r=luke (0d5eedccce)
- Bug 1255008: IonMonkey - Add a by default disabled flow sensitive alias analysis pass, r=jandem (521c585d75)
- Bug 1266781: Baldr: implement proper checked truncations to integer types; r=sunfish (46078fb3d3)
- Bug 1266781: Rename MTruncateToInt64 into MWasmTruncateInt64; r=sunfish (c7d7d1ac11)
- Bug 1266781: Add new traps; r=luke (b7ed3d44e6)
- Bug 1268024: Pass the atomic attribute down to EmitHeapAccess; r=luke (6195f7d7a3)
- Bug 1268024: A few cleanups related to loads/stores; r=luke (88141e3a01)
- Bug 1258312 - Make Pickle::Resize infallible r=jld (241ee9b60d)
- Bug 1162772, part 1 - Allow CompartmentCreationOptions to store Secure Context state. r=jorendorff (ff666384cf)
- Bug 1162772, part 2 - Expose whether SEC_FORCE_INHERIT_PRINCIPAL was dropped from an nsILoadInfo. r=bz (ada46f86bf)
- Bug 1162772, part 3 - Add a getChannelResultPrincipalIfNotSandboxed method to nsIScriptSecurityManager. r=bz (5b1d9f6807)
- Bug 1162772, part 4 - Implement nsGlobalWindow::IsSecureContext. r=bz (f392f439c9)
- Bug 1162772, part 5 - Expose Window.isSecureContext to content. r=bz (e7296e2cf1)
- Bug 1267509 - Make nsContentSecurityManager::IsURIPotentiallyTrustworthy act on an nsIPrincipal. r=bz (83de80350a)
- Bug 1219098 - Use UniquePtr in UncompressedSourceCache, for it is good (r=jandem) (b68769c729)
- Bug 1244279 - Part 1: Take a bit in ObjectElements::Flags to indicate whether the object is in the whole cell store buffer. r=terrence (968cf373f9)
- Bug 1244279 - Part 0: Add a GC ubench for large arrays with both elements and properties. r=terrence (ec76b48323)
- Bug 1255925 - Give a name to getters/setters and integer-named methods. r=efaust (f978cc6916)
- Bug 888969 - Make the getPrototypeOf/setPrototypeOf traps scriptable. r=efaust, r=bholley (eb2325a9ea)
- Bug 1267557 part 0 - Move JS poison constants to jsutil.h. r=jonco (65afc690d2)
- Bug 1267557 part 1 - Also poison bytes allocated before the actual jitcode. r=nbp (70f0b327d3)
- Bug 1267557 part 2 - Use different jitcode poison values. r=nbp (08008ab9dc)
- Bug 1267557 part 3 - Define JS_SWEPT_CODE_PATTERN for mips. r=nbp (17e894d59d)
- Bug 1267449 - Do not infinite loop in js_fputs; r=jimb (67f961b6cd)
- Bug 1219098 - Reenable compression on large sources, but revert to uncompressed if decompression happens (r=jandem) (b44ee8d77d)
- Bug 1267551 (part 1) - Use MOZ_MUST_USE more in jsnum.h. r=jonco. (d2476bf8f4)
- Bug 1267551 (part 2) - Use MOZ_MUST_USE more in js/src/ds/. r=jonco. (4ff5d9aa88)
- Bug 1267412 - Use MutableHandleValue instead of pointer-to-AutoValueVector; r=sfink (3f6dd284bb)
- Bug 1266406 - Use EnumSet<AllocKind> to simplify GC sweeping phase information r=terrence (64811500e7)
- Bug 1266457 - Update pointers in GC things in two phases when compacting r=terrence (f6f5bc4e4d)
- Bug 1266457 - Simplify typed object trace hook r=terence (3b06c8d1e5)
- Bug 1268541 - Compact arenas containing base shapes r=terrence (b458b92eea)
- Bug 1268805 - Implement PrivateGCThingValue. (r=terrence) (deec9a83ae)
- Bug 1268415: Initialize members in UpdatePointerTasks; r=jonco (6cb219005a)
- Bug 1268501 - Release the GC lock periodically when releasing arenas on the backgound thread r=terrence (37f0997682)
- Bug 1263572 - Wait for background sweeping to finish before checking base shapes r=terrence (354801a411)
- Bug 1266887 - Store Rooted heads on the Zone; r=sfink (91c0101ee3)
- Bug 1266402 - Add iteration to EnumSet<T> so that it can be used in range-based for loops r=Waldo (e9507a2524)
- Bug 1266404 - Allow construction of an EnumSet<T> using an initializer list r=Waldo (1b6d340e99)
- Bug 1254020 - Always compute theme scaling factor when per-monitor dpi aware, even if only a single display is currently present. r=emk (a00cda21f4)
- Bug 1263525 - Add dedicated function for std_Array self-hosted intrinsic. r=efaust (449d8bb7eb)
- Bug 1255925 - Change JSFunction::name to return a JSAtom. r=efaust (5ab396ce83)
- Bug 888969 - Make our tree's sole implementation of nsIRemoteTagService.getRemoteObjectTag not depend upon the infallibility of [[GetPrototypeOf]] on the object provided to it. r=bz (f388f4bf1f)
- Bug 1264896 - Kill off nsIRemoteTagService and do what it does, in its sole caller, in far-faster C++. r=billm (5ed3fb103d)
- Bug 1268246 - Add a simple Poison class lifetime checker. r=froydnj (7b237bc70e)
- Bug 1249496 - Don't apply dpi-based scaling for window titlebar dimensions when on a secondary display, because windows doesn't scale it. r=emk (64dd706dbc)
- Bug 1164518 - Avoid unnecessary DB updates when caching Safe Browsing results. r=gcp (3cafd9a4df)
- Bug 1264472 - Use nsRunnables in FIDO U2F. r=keeler (3aa9570132)
- Bug 1236060 - Dispatch error should advance queue. r=smaug (74155b75dd)
- Bug 1251697 part 1. Thread an ErrorResult reference through the worker XHR WorkerThreadProxySyncRunnable implementations. r=khuey (77804cbb7c)
- Bug 1251697 part 2. Have WorkerThreadProxySyncRunnable hand the ErrorResult reference it holds to its ResponseRunnable so it can report exceptions on there instead of on a JSContext. r=khuey (355c9ee313)
- Bug 1251697 part 3. Remove the JSContext argument of StopSyncLoopRunnable::MaybeSetException. r=khuey (010f5b1058)
- Bug 1155328. r=smaug (e1f8dac304)
- Bug 1265927: Move nsRunnable to mozilla::Runnable, CancelableRunnable to mozilla::CancelableRunnable. r=froydnj (f83bfcae02)
- Bug 1239946 - Change test to return error on Speak. r=eeejay (1d402beb02)
- Bug 1254378 - Update synth tests and introduce no voiceschanged test. r=smaug (f5823bb70e)
- Bug 1251627. Fix XMLHttpRequest.send() to follow the spec better in terms of the exceptions it throws. r=khuey (cd0e321948)
- Bug 1268868: [MSE] P1. Re-enable gap detection within a media segment. r=gerald (b8b8df4bc2)
- Bug 1268868: [MSE] P2. Reset longest duration after keyframe is seen. r=gerald (2b1401465c)
- Bug 1268868: [MSE] P3. Prevent crash should gap be detected in content. r=gerald (063d9376fc)
- Bug 1254378 - Implement nsISynthVoiceRegistry.notifyVoicesChanged. r=smaug (4b63b1c360)
- Bug 1266804 - Un-inline js::Unbox(); r=jorendorff (0f288b6173)
- Bug 1268863 - Report ScriptSources that are only reachable via AsmJSModule (r=njn) (5ba40acb64)
- bump version to 45.1b1 (1414db0ca8)
- Bug 1262062 - remove old futex names. r=bbouvier (62662bdd2e)
- memory: build fix after renaming MOZ_WARN_UNUSED_RESULT (7254dc8d53)
- import from mozilla:
 - Bug 1268725 - BaldrMonkey: Refactor away the internal storage from ExprIter. r=luke (1931bd636f17)
 - Bug 1268725 - BaldrMonkey: Convert default arguments into explicit arguments. r=luke (c8a11b8b6bbd) (867ec715d6)
2024-08-21 10:45:07 +08:00

1151 lines
34 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
#include "mozilla/TimelineConsumers.h"
#include "mozilla/CompositeTimelineMarker.h"
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);
}
if (mPreviousWindow) {
mPreviousWindow->SetPreviouslyAttachedWidgetListener(nullptr);
}
// Destroy and release the widget
DestroyWidget();
delete mDirtyRegion;
}
class DestroyWidgetRunnable : public Runnable {
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);
// Don't leak if we happen to arrive here after the main thread
// has disappeared.
nsCOMPtr<nsIThread> mainThread = do_GetMainThread();
if (mainThread) {
mainThread->Dispatch(widgetDestroyer.forget(), NS_DISPATCH_NORMAL);
}
}
mWindow = nullptr;
}
}
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;
}
LayoutDeviceIntRect 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
LayoutDeviceIntRect newBounds =
LayoutDeviceIntRect::FromUnknownRect(viewBounds.ToNearestPixels(p2a));
#if defined(XP_MACOSX) || (MOZ_WIDGET_GTK == 3)
// cocoa and GTK round 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.get();
uint32_t round;
if (aType == eWindowType_popup && widget &&
((round = widget->RoundsWidgetCoordinatesTo()) > 1)) {
LayoutDeviceIntSize 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).
LayoutDeviceIntRect newBounds;
RefPtr<nsDeviceContext> dx = mViewManager->GetDeviceContext();
nsWindowType type = widget->WindowType();
LayoutDeviceIntRect 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 desktop 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).
DesktopToLayoutDeviceScale scale = widget->GetDesktopToDeviceScale();
#ifdef XP_MACOSX
// On OS X, this can be called before Cocoa has updated the backing scale
// factor of our widget, in which case |scale| is wrong here. To work
// around this, we check the device context and override |scale| if it
// doesn't match. (This happens when a popup window that has previously
// been created and hidden is being moved between hi- and lo-dpi screens,
// but is not currently visible; Cocoa doesn't notify it of the scale
// factor change until it gets shown on the new screen, which is too late
// for us because we'll have already done the computations involving scale
// here to move/size it.)
// It might be better to avoid this by keeping calculations such as
// CalcWidgetBounds entirely in appUnits, rather than using device pixels,
// but that seems like a more extensive and potentially risky change.
int32_t appPerDev = dx->AppUnitsPerDevPixelAtUnitFullZoom();
if (NSToIntRound(60.0 / scale.scale) != appPerDev) {
scale = DesktopToLayoutDeviceScale(60.0 / appPerDev);
}
#endif
DesktopRect deskRect = newBounds / scale;
if (changedPos) {
if (changedSize && !aMoveOnly) {
widget->ResizeClient(deskRect.x, deskRect.y,
deskRect.width, deskRect.height,
aInvalidateChangedSize);
} else {
widget->MoveClient(deskRect.x, deskRect.y);
}
} else {
if (changedSize && !aMoveOnly) {
widget->ResizeClient(deskRect.width, deskRect.height,
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()
{
if (mViewManager->GetRootView() == this)
mViewManager->InvalidateHierarchy();
for (nsView *child = mFirstChild; child; child = child->GetNextSibling())
child->InvalidateHierarchy();
}
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();
}
}
}
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();
}
}
}
// 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);
LayoutDeviceIntRect 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);
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;
LayoutDeviceIntRect trect = CalcWidgetBounds(aWidgetInitData->mWindowType);
mWindow = aParentWidget->CreateChild(trect, aWidgetInitData);
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");
LayoutDeviceIntRect 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);
}
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);
}
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());
}
}
void
nsView::SetNeedsWindowPropertiesSync()
{
mNeedsWindowPropertiesSync = true;
if (mViewManager) {
mViewManager->PostPendingUpdate();
}
}
// 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;
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);
nsIWidgetListener* listener = mWindow->GetPreviouslyAttachedWidgetListener();
if (listener && listener->GetView()) {
// Ensure the listener doesn't think it's being used anymore
listener->GetView()->SetPreviousWidget(nullptr);
}
// If the new view's frame is paint suppressed then the window
// will want to use us instead until that's done
mWindow->SetPreviouslyAttachedWidgetListener(this);
mPreviousWindow = mWindow;
mWindow = nullptr;
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();
mWindow = nullptr;
}
}
//
// 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();
LayoutDeviceIntRect rect;
mWindow->GetClientBounds(rect);
nsRect windowBounds = LayoutDeviceIntRect::ToAppUnits(rect, p2a);
mWindow->GetBounds(rect);
nsRect nonclientBounds = LayoutDeviceIntRect::ToAppUnits(rect, 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()) {
RefPtr<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)
{
RefPtr<nsViewManager> vm = mViewManager;
vm->WillPaintWindow(aWidget);
}
bool
nsView::PaintWindow(nsIWidget* aWidget, LayoutDeviceIntRegion aRegion)
{
NS_ASSERTION(this == nsView::GetViewFor(aWidget), "wrong view for widget?");
RefPtr<nsViewManager> vm = mViewManager;
bool result = vm->PaintWindow(aWidget, aRegion);
return result;
}
void
nsView::DidPaintWindow()
{
RefPtr<nsViewManager> vm = mViewManager;
vm->DidPaintWindow();
}
void
nsView::DidCompositeWindow(uint64_t aTransactionId,
const TimeStamp& aCompositeStart,
const TimeStamp& aCompositeEnd)
{
nsIPresShell* presShell = mViewManager->GetPresShell();
if (presShell) {
nsAutoScriptBlocker scriptBlocker;
nsPresContext* context = presShell->GetPresContext();
nsRootPresContext* rootContext = context->GetRootPresContext();
MOZ_ASSERT(rootContext, "rootContext must be valid.");
rootContext->NotifyDidPaintForSubtree(nsIPresShell::PAINT_COMPOSITE, aTransactionId,
aCompositeEnd);
// If the two timestamps are identical, this was likely a fake composite
// event which wouldn't be terribly useful to display.
if (aCompositeStart == aCompositeEnd) {
return;
}
nsIDocShell* docShell = context->GetDocShell();
RefPtr<TimelineConsumers> timelines = TimelineConsumers::Get();
if (timelines && timelines->HasConsumer(docShell)) {
timelines->AddMarkerForDocShell(docShell,
MakeUnique<CompositeTimelineMarker>(aCompositeStart, MarkerTracingType::START));
timelines->AddMarkerForDocShell(docShell,
MakeUnique<CompositeTimelineMarker>(aCompositeEnd, MarkerTracingType::END));
}
}
}
void
nsView::RequestRepaint()
{
nsIPresShell* presShell = mViewManager->GetPresShell();
if (presShell) {
presShell->ScheduleViewManagerFlush();
}
}
nsEventStatus
nsView::HandleEvent(WidgetGUIEvent* aEvent,
bool aUseAttachedEvents)
{
NS_PRECONDITION(nullptr != aEvent->mWidget, "null widget ptr");
nsEventStatus result = nsEventStatus_eIgnore;
nsView* view;
if (aUseAttachedEvents) {
nsIWidgetListener* listener = aEvent->mWidget->GetAttachedWidgetListener();
view = listener ? listener->GetView() : nullptr;
}
else {
view = GetViewFor(aEvent->mWidget);
}
if (view) {
RefPtr<nsViewManager> vm = view->GetViewManager();
vm->DispatchEvent(aEvent, view, &result);
}
return result;
}
bool
nsView::IsPrimaryFramePaintSuppressed()
{
return mFrame ? mFrame->PresContext()->PresShell()->IsPaintingSuppressed() : false;
}