Bug 1841966 - Fix verifyOpenLinkInNewPrivateTabContextMenuOptionTest UI test r=aaronmt
[gecko.git] / widget / cocoa / ViewRegion.mm
blob5b275a18a3a3630cfbb8d7c82d0c6b1a70128cb5
1 /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
2 /* vim: set ts=8 sts=2 et sw=2 tw=80: */
3 /* This Source Code Form is subject to the terms of the Mozilla Public
4  * License, v. 2.0. If a copy of the MPL was not distributed with this file,
5  * You can obtain one at http://mozilla.org/MPL/2.0/. */
7 #include "ViewRegion.h"
8 #import <Cocoa/Cocoa.h>
10 #include "nsChildView.h"
12 using namespace mozilla;
14 ViewRegion::~ViewRegion() {
15   for (NSView* view : mViews) {
16     [view removeFromSuperview];
17   }
20 bool ViewRegion::UpdateRegion(const LayoutDeviceIntRegion& aRegion,
21                               const nsChildView& aCoordinateConverter,
22                               NSView* aContainerView,
23                               NSView* (^aViewCreationCallback)()) {
24   if (mRegion == aRegion) {
25     return false;
26   }
28   // We need to construct the required region using as many EffectViews
29   // as necessary. We try to update the geometry of existing views if
30   // possible, or create new ones or remove old ones if the number of
31   // rects in the region has changed.
33   nsTArray<NSView*> viewsToRecycle = std::move(mViews);
34   // The mViews array is now empty.
36   size_t viewsRecycled = 0;
37   for (auto iter = aRegion.RectIter(); !iter.Done(); iter.Next()) {
38     NSRect rect = aCoordinateConverter.DevPixelsToCocoaPoints(iter.Get());
39     NSView* view = nil;
40     if (viewsRecycled < viewsToRecycle.Length()) {
41       view = viewsToRecycle[viewsRecycled++];
42     } else {
43       view = aViewCreationCallback();
44       [aContainerView addSubview:view];
46       // Now that the view is in the view hierarchy, it'll be kept alive by
47       // its superview, so we can drop our reference.
48       [view release];
49     }
50     if (!NSEqualRects(rect, view.frame)) {
51       view.frame = rect;
52     }
53     view.needsDisplay = YES;
54     mViews.AppendElement(view);
55   }
56   for (NSView* view : Span(viewsToRecycle).From(viewsRecycled)) {
57     // Our new region is made of fewer rects than the old region, so we can
58     // remove this view. We only have a weak reference to it, so removing it
59     // from the view hierarchy will release it.
60     [view removeFromSuperview];
61   }
63   mRegion = aRegion;
64   return true;