File: nsView.cpp

package info (click to toggle)
firefox 146.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 4,653,260 kB
  • sloc: cpp: 7,587,892; javascript: 6,509,455; ansic: 3,755,295; python: 1,410,813; xml: 629,201; asm: 438,677; java: 186,096; sh: 62,697; makefile: 18,086; objc: 13,087; perl: 12,811; yacc: 4,583; cs: 3,846; pascal: 3,448; lex: 1,720; ruby: 1,003; php: 436; lisp: 258; awk: 247; sql: 66; sed: 54; csh: 10; exp: 6
file content (852 lines) | stat: -rw-r--r-- 27,540 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
/* -*- 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/BasicEvents.h"
#include "mozilla/DebugOnly.h"
#include "mozilla/IntegerPrintfMacros.h"
#include "mozilla/Likely.h"
#include "mozilla/Poison.h"
#include "mozilla/PresShell.h"
#include "mozilla/StaticPrefs_layout.h"
#include "mozilla/dom/Document.h"
#include "mozilla/dom/BrowserParent.h"
#include "mozilla/widget/Screen.h"
#include "nsIWidget.h"
#include "nsViewManager.h"
#include "nsIFrame.h"
#include "nsXULPopupManager.h"
#include "nsIWidgetListener.h"
#include "nsContentUtils.h"  // for nsAutoScriptBlocker
#include "nsDocShell.h"
#include "nsLayoutUtils.h"
#include "mozilla/StartupTimeline.h"

using namespace mozilla;
using namespace mozilla::widget;

nsView::nsView(nsViewManager* aViewManager, ViewVisibility aVisibility)
    : mViewManager(aViewManager),
      mParent(nullptr),
      mNextSibling(nullptr),
      mFirstChild(nullptr),
      mFrame(nullptr),
      mVis(aVisibility),
      mPosX(0),
      mPosY(0),
      mWidgetIsTopLevel(false),
      mForcedRepaint(false),
      mNeedsWindowPropertiesSync(false) {
  MOZ_COUNT_CTOR(nsView);

  // 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.
}

void nsView::DropMouseGrabbing() {
  if (mViewManager->GetPresShell()) {
    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();

  MOZ_RELEASE_ASSERT(!mFrame);
}

class DestroyWidgetRunnable : public Runnable {
 public:
  NS_DECL_NSIRUNNABLE

  explicit DestroyWidgetRunnable(nsIWidget* aWidget)
      : mozilla::Runnable("DestroyWidgetRunnable"), 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(const nsIWidget* aWidget) {
  MOZ_ASSERT(aWidget, "null widget ptr");

  nsIWidgetListener* listener = aWidget->GetWidgetListener();
  if (listener) {
    if (nsView* view = listener->GetView()) {
      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.MoveBy(aX - mPosX, 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");
}

bool nsView::IsEffectivelyVisible() {
  for (nsView* v = this; v; v = v->mParent) {
    if (v->GetVisibility() == ViewVisibility::Hide) {
      return false;
    }
  }
  return true;
}

struct WidgetViewBounds {
  nsRect mBounds;
  int32_t mRoundTo = 1;
};

static WidgetViewBounds CalcWidgetViewBounds(
    const nsRect& aBounds, int32_t aAppUnitsPerDevPixel, nsView* aParentView,
    nsIWidget* aThisWidget, WindowType aType, TransparencyMode aTransparency) {
  nsRect viewBounds(aBounds);
  nsIWidget* parentWidget = nullptr;
  if (aParentView) {
    nsPoint offset;
    parentWidget = aParentView->GetNearestWidget(&offset, aAppUnitsPerDevPixel);
    // make viewBounds be relative to the parent widget, in appunits
    viewBounds += offset;

    if (parentWidget && aType == WindowType::Popup) {
      // put offset into screen coordinates. (based on client area origin)
      LayoutDeviceIntPoint screenPoint = parentWidget->WidgetToScreenOffset();
      viewBounds +=
          nsPoint(NSIntPixelsToAppUnits(screenPoint.x, aAppUnitsPerDevPixel),
                  NSIntPixelsToAppUnits(screenPoint.y, aAppUnitsPerDevPixel));
    }
  }

  nsIWidget* widget = parentWidget ? parentWidget : aThisWidget;
  int32_t roundTo = widget ? widget->RoundsWidgetCoordinatesTo() : 1;
  return {viewBounds, roundTo};
}

static LayoutDeviceIntRect WidgetViewBoundsToDevicePixels(
    const WidgetViewBounds& aViewBounds, int32_t aAppUnitsPerDevPixel,
    WindowType aType, TransparencyMode aTransparency) {
  // Compute widget bounds in device pixels
  // TODO(emilio): We should probably use outside pixels for transparent
  // windows (not just popups) as well.
  if (aType != WindowType::Popup) {
    return LayoutDeviceIntRect::FromUnknownRect(
        aViewBounds.mBounds.ToNearestPixels(aAppUnitsPerDevPixel));
  }
  // We use outside pixels for transparent windows if possible, so that we
  // don't truncate the contents. For opaque popups, we use nearest pixels
  // which prevents having pixels not drawn by the frame.
  const bool opaque = aTransparency == TransparencyMode::Opaque;
  const auto idealBounds = LayoutDeviceIntRect::FromUnknownRect(
      opaque ? aViewBounds.mBounds.ToNearestPixels(aAppUnitsPerDevPixel)
             : aViewBounds.mBounds.ToOutsidePixels(aAppUnitsPerDevPixel));

  return nsIWidget::MaybeRoundToDisplayPixels(idealBounds, aTransparency,
                                              aViewBounds.mRoundTo);
}

LayoutDeviceIntRect nsView::CalcWidgetBounds(WindowType aType,
                                             TransparencyMode aTransparency) {
  int32_t p2a = mViewManager->AppUnitsPerDevPixel();
  auto viewBounds = CalcWidgetViewBounds(mDimBounds, p2a, GetParent(),
                                         mWindow.get(), aType, aTransparency);
  auto newBounds =
      WidgetViewBoundsToDevicePixels(viewBounds, p2a, aType, aTransparency);

  // 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.mBounds.TopLeft() - roundedOffset;
  return newBounds;
}

LayoutDeviceIntRect nsView::CalcWidgetBounds(
    const nsRect& aBounds, int32_t aAppUnitsPerDevPixel, nsView* aParentView,
    nsIWidget* aThisWidget, WindowType aType, TransparencyMode aTransparency) {
  auto viewBounds =
      CalcWidgetViewBounds(aBounds, aAppUnitsPerDevPixel, aParentView,
                           aThisWidget, aType, aTransparency);
  return WidgetViewBoundsToDevicePixels(viewBounds, aAppUnitsPerDevPixel, aType,
                                        aTransparency);
}

LayoutDeviceIntRect nsView::RecalcWidgetBounds() {
  MOZ_ASSERT(mWindow);
  return CalcWidgetBounds(mWindow->GetWindowType(),
                          mWindow->GetTransparencyMode());
}

void nsView::SetDimensions(const nsRect& aRect) {
  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;
}

void nsView::NotifyEffectiveVisibilityChanged(bool aEffectivelyVisible) {
  if (!aEffectivelyVisible) {
    DropMouseGrabbing();
  }

  SetForcedRepaint(true);

  for (nsView* child = mFirstChild; child; child = child->mNextSibling) {
    if (child->mVis == ViewVisibility::Hide) {
      // It was effectively hidden and still is
      continue;
    }
    // Our child is visible if we are
    child->NotifyEffectiveVisibilityChanged(aEffectivelyVisible);
  }
}

void nsView::SetVisibility(ViewVisibility aVisibility) {
  mVis = aVisibility;
  NotifyEffectiveVisibilityChanged(IsEffectivelyVisible());
}

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) {
  MOZ_ASSERT(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) {
  MOZ_ASSERT(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();
    }
  }
}

void nsView::SetNeedsWindowPropertiesSync() {
  mNeedsWindowPropertiesSync = true;
  if (mViewManager) {
    mViewManager->PostPendingUpdate();
  }
}

// Attach to a top level widget and start receiving mirrored events.
void nsView::AttachToTopLevelWidget(nsIWidget* aWidget) {
  MOZ_ASSERT(aWidget, "null widget ptr");
#ifdef DEBUG
  nsIWidgetListener* parentListener = aWidget->GetWidgetListener();
  MOZ_ASSERT(!parentListener || !parentListener->GetView(),
             "Expect a top level widget");
  MOZ_ASSERT(!parentListener || !parentListener->GetAsMenuPopupFrame(),
             "Expect a top level widget");
#endif

  /// XXXjimm This is a temporary workaround to an issue w/document
  // viewer (bug 513162).
  if (nsIWidgetListener* listener = aWidget->GetAttachedWidgetListener()) {
    if (nsView* oldView = listener->GetView()) {
      oldView->DetachFromTopLevelWidget();
    }
  }

  // Note, the previous device context will be released. Detaching
  // will not restore the old one.
  aWidget->AttachViewToTopLevel(!nsIWidget::UsePuppetWidgets());

  mWindow = aWidget;

  mWindow->SetAttachedWidgetListener(this);
  if (mWindow->GetWindowType() != WindowType::Invisible) {
    mWindow->AsyncEnableDragDrop(true);
  }
  mWidgetIsTopLevel = true;

  // Refresh the view bounds
  RecalcWidgetBounds();
}

// Detach this view from an attached widget.
void nsView::DetachFromTopLevelWidget() {
  MOZ_ASSERT(mWidgetIsTopLevel, "Not attached currently!");
  MOZ_ASSERT(mWindow, "null mWindow for DetachFromTopLevelWidget!");

  mWindow->SetAttachedWidgetListener(nullptr);
  if (nsIWidgetListener* listener =
          mWindow->GetPreviouslyAttachedWidgetListener()) {
    if (nsView* view = listener->GetView()) {
      // Ensure the listener doesn't think it's being used anymore
      view->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;
}

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();
    nsRect windowBounds = LayoutDeviceIntRect::ToAppUnits(rect, p2a);
    rect = mWindow->GetBounds();
    nsRect nonclientBounds = LayoutDeviceIntRect::ToAppUnits(rect, p2a);
    nsrefcnt widgetRefCnt = mWindow.get()->AddRef() - 1;
    mWindow.get()->Release();
    fprintf(out, "(widget=%p[%" PRIuPTR "] pos={%d,%d,%d,%d}) ", (void*)mWindow,
            widgetRefCnt, nonclientBounds.X(), nonclientBounds.Y(),
            windowBounds.Width(), windowBounds.Height());
  }
  nsRect brect = GetBounds();
  fprintf(out, "{%d,%d,%d,%d} @ %d,%d", brect.X(), brect.Y(), brect.Width(),
          brect.Height(), mPosX, mPosY);
  fprintf(out, " vis=%d frame=%p <\n", int(mVis), 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;
}

PresShell* nsView::GetPresShell() { return GetViewManager()->GetPresShell(); }

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()) {
    return false;
  }

  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();
  if (auto* frame = GetFrame()) {
    // Usually the resize would deal with this, but there are some cases (like
    // web-extension popups) where frames might already be correctly sized etc
    // due to a call to e.g. nsDocumentViewer::GetContentSize or so.
    frame->InvalidateFrame();
  }

  mViewManager->SetWindowDimensions(NSIntPixelsToAppUnits(aWidth, p2a),
                                    NSIntPixelsToAppUnits(aHeight, p2a));

  if (nsXULPopupManager* pm = nsXULPopupManager::GetInstance()) {
    PresShell* presShell = mViewManager->GetPresShell();
    if (presShell && presShell->GetDocument()) {
      pm->AdjustPopupsOnWindowChange(presShell);
    }
  }

  return true;
}

#ifdef MOZ_WIDGET_ANDROID
void nsView::DynamicToolbarMaxHeightChanged(ScreenIntCoord aHeight) {
  MOZ_ASSERT(XRE_IsParentProcess(),
             "Should be only called for the browser parent process");
  MOZ_ASSERT(this == mViewManager->GetRootView(),
             "Should be called for the root view");

  CallOnAllRemoteChildren(
      [aHeight](dom::BrowserParent* aBrowserParent) -> CallState {
        aBrowserParent->DynamicToolbarMaxHeightChanged(aHeight);
        return CallState::Continue;
      });
}

void nsView::DynamicToolbarOffsetChanged(ScreenIntCoord aOffset) {
  MOZ_ASSERT(XRE_IsParentProcess(),
             "Should be only called for the browser parent process");
  MOZ_ASSERT(this == mViewManager->GetRootView(),
             "Should be called for the root view");
  CallOnAllRemoteChildren(
      [aOffset](dom::BrowserParent* aBrowserParent) -> CallState {
        // Skip background tabs.
        if (!aBrowserParent->GetDocShellIsActive()) {
          return CallState::Continue;
        }

        aBrowserParent->DynamicToolbarOffsetChanged(aOffset);
        return CallState::Stop;
      });
}

void nsView::KeyboardHeightChanged(ScreenIntCoord aHeight) {
  MOZ_ASSERT(XRE_IsParentProcess(),
             "Should be only called for the browser parent process");
  MOZ_ASSERT(this == mViewManager->GetRootView(),
             "Should be called for the root view");
  CallOnAllRemoteChildren(
      [aHeight](dom::BrowserParent* aBrowserParent) -> CallState {
        // Skip background tabs.
        if (!aBrowserParent->GetDocShellIsActive()) {
          return CallState::Continue;
        }

        aBrowserParent->KeyboardHeightChanged(aHeight);
        return CallState::Stop;
      });
}

void nsView::AndroidPipModeChanged(bool aPipMode) {
  MOZ_ASSERT(XRE_IsParentProcess(),
             "Should be only called for the browser parent process");
  MOZ_ASSERT(this == mViewManager->GetRootView(),
             "Should be called for the root view");
  CallOnAllRemoteChildren(
      [aPipMode](dom::BrowserParent* aBrowserParent) -> CallState {
        aBrowserParent->AndroidPipModeChanged(aPipMode);
        return CallState::Continue;
      });
}
#endif

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(mozilla::layers::TransactionId aTransactionId,
                                const TimeStamp& aCompositeStart,
                                const TimeStamp& aCompositeEnd) {
  PresShell* presShell = mViewManager->GetPresShell();
  if (!presShell) {
    return;
  }

  nsAutoScriptBlocker scriptBlocker;

  nsPresContext* context = presShell->GetPresContext();
  nsRootPresContext* rootContext = context->GetRootPresContext();
  if (rootContext) {
    rootContext->NotifyDidPaintForSubtree(aTransactionId, aCompositeEnd);
  }

  mozilla::StartupTimeline::RecordOnce(mozilla::StartupTimeline::FIRST_PAINT2,
                                       aCompositeEnd);
}

void nsView::RequestRepaint() {
  if (PresShell* presShell = mViewManager->GetPresShell()) {
    presShell->SchedulePaint();
  }
}

bool nsView::ShouldNotBeVisible() {
  if (mFrame && mFrame->IsMenuPopupFrame()) {
    nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
    return !pm || !pm->IsPopupOpen(mFrame->GetContent()->AsElement());
  }

  return false;
}

nsEventStatus nsView::HandleEvent(WidgetGUIEvent* aEvent,
                                  bool aUseAttachedEvents) {
  MOZ_ASSERT(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;
}

void nsView::SafeAreaInsetsChanged(
    const LayoutDeviceIntMargin& aSafeAreaInsets) {
  if (!IsRoot()) {
    return;
  }

  PresShell* presShell = mViewManager->GetPresShell();
  if (!presShell) {
    return;
  }

  LayoutDeviceIntMargin windowSafeAreaInsets;
  const LayoutDeviceIntRect windowRect = mWindow->GetScreenBounds();
  if (nsCOMPtr<nsIScreen> screen = mWindow->GetWidgetScreen()) {
    windowSafeAreaInsets = nsContentUtils::GetWindowSafeAreaInsets(
        screen, aSafeAreaInsets, windowRect);
  }

  presShell->GetPresContext()->SetSafeAreaInsets(windowSafeAreaInsets);

  // https://github.com/w3c/csswg-drafts/issues/4670
  // Actually we don't set this value on sub document. This behaviour is
  // same as Blink.
  CallOnAllRemoteChildren(
      [windowSafeAreaInsets](dom::BrowserParent* aBrowserParent) -> CallState {
        (void)aBrowserParent->SendSafeAreaInsetsChanged(windowSafeAreaInsets);
        return CallState::Continue;
      });
}

bool nsView::IsPrimaryFramePaintSuppressed() {
  return StaticPrefs::layout_show_previous_page() && mFrame &&
         mFrame->PresShell()->IsPaintingSuppressed();
}

void nsView::CallOnAllRemoteChildren(
    const std::function<CallState(dom::BrowserParent*)>& aCallback) {
  PresShell* presShell = mViewManager->GetPresShell();
  if (!presShell) {
    return;
  }

  dom::Document* document = presShell->GetDocument();
  if (!document) {
    return;
  }

  nsPIDOMWindowOuter* window = document->GetWindow();
  if (!window) {
    return;
  }

  nsContentUtils::CallOnAllRemoteChildren(window, aCallback);
}