layout/xul/nsMenuPopupFrame.cpp

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/layout/xul/nsMenuPopupFrame.cpp	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,2046 @@
     1.4 +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
     1.5 +/* vim: set ts=2 sw=2 et tw=78: */
     1.6 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.7 + * License, v. 2.0. If a copy of the MPL was not distributed with this
     1.8 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.9 +
    1.10 +#include "nsMenuPopupFrame.h"
    1.11 +#include "nsGkAtoms.h"
    1.12 +#include "nsIContent.h"
    1.13 +#include "nsIAtom.h"
    1.14 +#include "nsPresContext.h"
    1.15 +#include "nsStyleContext.h"
    1.16 +#include "nsCSSRendering.h"
    1.17 +#include "nsNameSpaceManager.h"
    1.18 +#include "nsViewManager.h"
    1.19 +#include "nsWidgetsCID.h"
    1.20 +#include "nsMenuFrame.h"
    1.21 +#include "nsMenuBarFrame.h"
    1.22 +#include "nsPopupSetFrame.h"
    1.23 +#include "nsPIDOMWindow.h"
    1.24 +#include "nsIDOMKeyEvent.h"
    1.25 +#include "nsIDOMScreen.h"
    1.26 +#include "nsIPresShell.h"
    1.27 +#include "nsFrameManager.h"
    1.28 +#include "nsIDocument.h"
    1.29 +#include "nsRect.h"
    1.30 +#include "nsIComponentManager.h"
    1.31 +#include "nsBoxLayoutState.h"
    1.32 +#include "nsIScrollableFrame.h"
    1.33 +#include "nsIRootBox.h"
    1.34 +#include "nsIDocShell.h"
    1.35 +#include "nsReadableUtils.h"
    1.36 +#include "nsUnicharUtils.h"
    1.37 +#include "nsLayoutUtils.h"
    1.38 +#include "nsContentUtils.h"
    1.39 +#include "nsCSSFrameConstructor.h"
    1.40 +#include "nsIPopupBoxObject.h"
    1.41 +#include "nsPIWindowRoot.h"
    1.42 +#include "nsIReflowCallback.h"
    1.43 +#include "nsBindingManager.h"
    1.44 +#include "nsIDocShellTreeOwner.h"
    1.45 +#include "nsIBaseWindow.h"
    1.46 +#include "nsISound.h"
    1.47 +#include "nsIScreenManager.h"
    1.48 +#include "nsIServiceManager.h"
    1.49 +#include "nsThemeConstants.h"
    1.50 +#include "nsDisplayList.h"
    1.51 +#include "mozilla/EventDispatcher.h"
    1.52 +#include "mozilla/EventStateManager.h"
    1.53 +#include "mozilla/EventStates.h"
    1.54 +#include "mozilla/Preferences.h"
    1.55 +#include "mozilla/LookAndFeel.h"
    1.56 +#include "mozilla/MouseEvents.h"
    1.57 +#include "mozilla/dom/Element.h"
    1.58 +#include <algorithm>
    1.59 +
    1.60 +using namespace mozilla;
    1.61 +
    1.62 +int8_t nsMenuPopupFrame::sDefaultLevelIsTop = -1;
    1.63 +
    1.64 +// NS_NewMenuPopupFrame
    1.65 +//
    1.66 +// Wrapper for creating a new menu popup container
    1.67 +//
    1.68 +nsIFrame*
    1.69 +NS_NewMenuPopupFrame(nsIPresShell* aPresShell, nsStyleContext* aContext)
    1.70 +{
    1.71 +  return new (aPresShell) nsMenuPopupFrame (aPresShell, aContext);
    1.72 +}
    1.73 +
    1.74 +NS_IMPL_FRAMEARENA_HELPERS(nsMenuPopupFrame)
    1.75 +
    1.76 +NS_QUERYFRAME_HEAD(nsMenuPopupFrame)
    1.77 +  NS_QUERYFRAME_ENTRY(nsMenuPopupFrame)
    1.78 +NS_QUERYFRAME_TAIL_INHERITING(nsBoxFrame)
    1.79 +
    1.80 +//
    1.81 +// nsMenuPopupFrame ctor
    1.82 +//
    1.83 +nsMenuPopupFrame::nsMenuPopupFrame(nsIPresShell* aShell, nsStyleContext* aContext)
    1.84 +  :nsBoxFrame(aShell, aContext),
    1.85 +  mCurrentMenu(nullptr),
    1.86 +  mPrefSize(-1, -1),
    1.87 +  mLastClientOffset(0, 0),
    1.88 +  mPopupType(ePopupTypePanel),
    1.89 +  mPopupState(ePopupClosed),
    1.90 +  mPopupAlignment(POPUPALIGNMENT_NONE),
    1.91 +  mPopupAnchor(POPUPALIGNMENT_NONE),
    1.92 +  mPosition(POPUPPOSITION_UNKNOWN),
    1.93 +  mConsumeRollupEvent(nsIPopupBoxObject::ROLLUP_DEFAULT),
    1.94 +  mFlip(FlipType_Default),
    1.95 +  mIsOpenChanged(false),
    1.96 +  mIsContextMenu(false),
    1.97 +  mAdjustOffsetForContextMenu(false),
    1.98 +  mGeneratedChildren(false),
    1.99 +  mMenuCanOverlapOSBar(false),
   1.100 +  mShouldAutoPosition(true),
   1.101 +  mInContentShell(true),
   1.102 +  mIsMenuLocked(false),
   1.103 +  mMouseTransparent(false),
   1.104 +  mHFlip(false),
   1.105 +  mVFlip(false)
   1.106 +{
   1.107 +  // the preference name is backwards here. True means that the 'top' level is
   1.108 +  // the default, and false means that the 'parent' level is the default.
   1.109 +  if (sDefaultLevelIsTop >= 0)
   1.110 +    return;
   1.111 +  sDefaultLevelIsTop =
   1.112 +    Preferences::GetBool("ui.panel.default_level_parent", false);
   1.113 +} // ctor
   1.114 +
   1.115 +
   1.116 +void
   1.117 +nsMenuPopupFrame::Init(nsIContent*      aContent,
   1.118 +                       nsIFrame*        aParent,
   1.119 +                       nsIFrame*        aPrevInFlow)
   1.120 +{
   1.121 +  nsBoxFrame::Init(aContent, aParent, aPrevInFlow);
   1.122 +
   1.123 +  // lookup if we're allowed to overlap the OS bar (menubar/taskbar) from the
   1.124 +  // look&feel object
   1.125 +  mMenuCanOverlapOSBar =
   1.126 +    LookAndFeel::GetInt(LookAndFeel::eIntID_MenusCanOverlapOSBar) != 0;
   1.127 +
   1.128 +  CreatePopupView();
   1.129 +
   1.130 +  // XXX Hack. The popup's view should float above all other views,
   1.131 +  // so we use the nsView::SetFloating() to tell the view manager
   1.132 +  // about that constraint.
   1.133 +  nsView* ourView = GetView();
   1.134 +  nsViewManager* viewManager = ourView->GetViewManager();
   1.135 +  viewManager->SetViewFloating(ourView, true);
   1.136 +
   1.137 +  mPopupType = ePopupTypePanel;
   1.138 +  nsIDocument* doc = aContent->OwnerDoc();
   1.139 +  int32_t namespaceID;
   1.140 +  nsCOMPtr<nsIAtom> tag = doc->BindingManager()->ResolveTag(aContent, &namespaceID);
   1.141 +  if (namespaceID == kNameSpaceID_XUL) {
   1.142 +    if (tag == nsGkAtoms::menupopup || tag == nsGkAtoms::popup)
   1.143 +      mPopupType = ePopupTypeMenu;
   1.144 +    else if (tag == nsGkAtoms::tooltip)
   1.145 +      mPopupType = ePopupTypeTooltip;
   1.146 +  }
   1.147 +
   1.148 +  nsCOMPtr<nsIDocShellTreeItem> dsti = PresContext()->GetDocShell();
   1.149 +  if (dsti && dsti->ItemType() == nsIDocShellTreeItem::typeChrome) {
   1.150 +    mInContentShell = false;
   1.151 +  }
   1.152 +
   1.153 +  // To improve performance, create the widget for the popup only if it is not
   1.154 +  // a leaf. Leaf popups such as menus will create their widgets later when
   1.155 +  // the popup opens.
   1.156 +  if (!IsLeaf() && !ourView->HasWidget()) {
   1.157 +    CreateWidgetForView(ourView);
   1.158 +  }
   1.159 +
   1.160 +  if (aContent->NodeInfo()->Equals(nsGkAtoms::tooltip, kNameSpaceID_XUL) &&
   1.161 +      aContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::_default,
   1.162 +                            nsGkAtoms::_true, eIgnoreCase)) {
   1.163 +    nsIRootBox* rootBox =
   1.164 +      nsIRootBox::GetRootBox(PresContext()->GetPresShell());
   1.165 +    if (rootBox) {
   1.166 +      rootBox->SetDefaultTooltip(aContent);
   1.167 +    }
   1.168 +  }
   1.169 +
   1.170 +  AddStateBits(NS_FRAME_IN_POPUP);
   1.171 +}
   1.172 +
   1.173 +bool
   1.174 +nsMenuPopupFrame::IsNoAutoHide() const
   1.175 +{
   1.176 +  // Panels with noautohide="true" don't hide when the mouse is clicked
   1.177 +  // outside of them, or when another application is made active. Non-autohide
   1.178 +  // panels cannot be used in content windows.
   1.179 +  return (!mInContentShell && mPopupType == ePopupTypePanel &&
   1.180 +           mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::noautohide,
   1.181 +                                 nsGkAtoms::_true, eIgnoreCase));
   1.182 +}
   1.183 +
   1.184 +nsPopupLevel
   1.185 +nsMenuPopupFrame::PopupLevel(bool aIsNoAutoHide) const
   1.186 +{
   1.187 +  // The popup level is determined as follows, in this order:
   1.188 +  //   1. non-panels (menus and tooltips) are always topmost
   1.189 +  //   2. any specified level attribute
   1.190 +  //   3. if a titlebar attribute is set, use the 'floating' level
   1.191 +  //   4. if this is a noautohide panel, use the 'parent' level
   1.192 +  //   5. use the platform-specific default level
   1.193 +
   1.194 +  // If this is not a panel, this is always a top-most popup.
   1.195 +  if (mPopupType != ePopupTypePanel)
   1.196 +    return ePopupLevelTop;
   1.197 +
   1.198 +  // If the level attribute has been set, use that.
   1.199 +  static nsIContent::AttrValuesArray strings[] =
   1.200 +    {&nsGkAtoms::top, &nsGkAtoms::parent, &nsGkAtoms::floating, nullptr};
   1.201 +  switch (mContent->FindAttrValueIn(kNameSpaceID_None, nsGkAtoms::level,
   1.202 +                                    strings, eCaseMatters)) {
   1.203 +    case 0:
   1.204 +      return ePopupLevelTop;
   1.205 +    case 1:
   1.206 +      return ePopupLevelParent;
   1.207 +    case 2:
   1.208 +      return ePopupLevelFloating;
   1.209 +  }
   1.210 +
   1.211 +  // Panels with titlebars most likely want to be floating popups.
   1.212 +  if (mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::titlebar))
   1.213 +    return ePopupLevelFloating;
   1.214 +
   1.215 +  // If this panel is a noautohide panel, the default is the parent level.
   1.216 +  if (aIsNoAutoHide)
   1.217 +    return ePopupLevelParent;
   1.218 +
   1.219 +  // Otherwise, the result depends on the platform.
   1.220 +  return sDefaultLevelIsTop ? ePopupLevelTop : ePopupLevelParent;
   1.221 +}
   1.222 +
   1.223 +void
   1.224 +nsMenuPopupFrame::EnsureWidget()
   1.225 +{
   1.226 +  nsView* ourView = GetView();
   1.227 +  if (!ourView->HasWidget()) {
   1.228 +    NS_ASSERTION(!mGeneratedChildren && !GetFirstPrincipalChild(),
   1.229 +                 "Creating widget for MenuPopupFrame with children");
   1.230 +    CreateWidgetForView(ourView);
   1.231 +  }
   1.232 +}
   1.233 +
   1.234 +nsresult
   1.235 +nsMenuPopupFrame::CreateWidgetForView(nsView* aView)
   1.236 +{
   1.237 +  // Create a widget for ourselves.
   1.238 +  nsWidgetInitData widgetData;
   1.239 +  widgetData.mWindowType = eWindowType_popup;
   1.240 +  widgetData.mBorderStyle = eBorderStyle_default;
   1.241 +  widgetData.clipSiblings = true;
   1.242 +  widgetData.mPopupHint = mPopupType;
   1.243 +  widgetData.mNoAutoHide = IsNoAutoHide();
   1.244 +
   1.245 +  if (!mInContentShell) {
   1.246 +    // A drag popup may be used for non-static translucent drag feedback
   1.247 +    if (mPopupType == ePopupTypePanel &&
   1.248 +        mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
   1.249 +                              nsGkAtoms::drag, eIgnoreCase)) {
   1.250 +      widgetData.mIsDragPopup = true;
   1.251 +    }
   1.252 +
   1.253 +    // If mousethrough="always" is set directly on the popup, then the widget
   1.254 +    // should ignore mouse events, passing them through to the content behind.
   1.255 +    mMouseTransparent = GetStateBits() & NS_FRAME_MOUSE_THROUGH_ALWAYS;
   1.256 +    widgetData.mMouseTransparent = mMouseTransparent;
   1.257 +  }
   1.258 +
   1.259 +  nsAutoString title;
   1.260 +  if (mContent && widgetData.mNoAutoHide) {
   1.261 +    if (mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::titlebar,
   1.262 +                              nsGkAtoms::normal, eCaseMatters)) {
   1.263 +      widgetData.mBorderStyle = eBorderStyle_title;
   1.264 +
   1.265 +      mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::label, title);
   1.266 +
   1.267 +      if (mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::close,
   1.268 +                                nsGkAtoms::_true, eCaseMatters)) {
   1.269 +        widgetData.mBorderStyle =
   1.270 +          static_cast<enum nsBorderStyle>(widgetData.mBorderStyle | eBorderStyle_close);
   1.271 +      }
   1.272 +    }
   1.273 +  }
   1.274 +
   1.275 +  nsTransparencyMode mode = nsLayoutUtils::GetFrameTransparency(this, this);
   1.276 +  nsIContent* parentContent = GetContent()->GetParent();
   1.277 +  nsIAtom *tag = nullptr;
   1.278 +  if (parentContent)
   1.279 +    tag = parentContent->Tag();
   1.280 +  widgetData.mSupportTranslucency = mode == eTransparencyTransparent;
   1.281 +  widgetData.mDropShadow = !(mode == eTransparencyTransparent || tag == nsGkAtoms::menulist);
   1.282 +  widgetData.mPopupLevel = PopupLevel(widgetData.mNoAutoHide);
   1.283 +
   1.284 +  // panels which have a parent level need a parent widget. This allows them to
   1.285 +  // always appear in front of the parent window but behind other windows that
   1.286 +  // should be in front of it.
   1.287 +  nsCOMPtr<nsIWidget> parentWidget;
   1.288 +  if (widgetData.mPopupLevel != ePopupLevelTop) {
   1.289 +    nsCOMPtr<nsIDocShellTreeItem> dsti = PresContext()->GetDocShell();
   1.290 +    if (!dsti)
   1.291 +      return NS_ERROR_FAILURE;
   1.292 +
   1.293 +    nsCOMPtr<nsIDocShellTreeOwner> treeOwner;
   1.294 +    dsti->GetTreeOwner(getter_AddRefs(treeOwner));
   1.295 +    if (!treeOwner) return NS_ERROR_FAILURE;
   1.296 +
   1.297 +    nsCOMPtr<nsIBaseWindow> baseWindow(do_QueryInterface(treeOwner));
   1.298 +    if (baseWindow)
   1.299 +      baseWindow->GetMainWidget(getter_AddRefs(parentWidget));
   1.300 +  }
   1.301 +
   1.302 +  nsresult rv = aView->CreateWidgetForPopup(&widgetData, parentWidget,
   1.303 +                                            true, true);
   1.304 +  if (NS_FAILED(rv)) {
   1.305 +    return rv;
   1.306 +  }
   1.307 +
   1.308 +  nsIWidget* widget = aView->GetWidget();
   1.309 +  widget->SetTransparencyMode(mode);
   1.310 +  widget->SetWindowShadowStyle(GetShadowStyle());
   1.311 +
   1.312 +  // most popups don't have a title so avoid setting the title if there isn't one
   1.313 +  if (!title.IsEmpty()) {
   1.314 +    widget->SetTitle(title);
   1.315 +  }
   1.316 +
   1.317 +  return NS_OK;
   1.318 +}
   1.319 +
   1.320 +uint8_t
   1.321 +nsMenuPopupFrame::GetShadowStyle()
   1.322 +{
   1.323 +  uint8_t shadow = StyleUIReset()->mWindowShadow;
   1.324 +  if (shadow != NS_STYLE_WINDOW_SHADOW_DEFAULT)
   1.325 +    return shadow;
   1.326 +
   1.327 +  switch (StyleDisplay()->mAppearance) {
   1.328 +    case NS_THEME_TOOLTIP:
   1.329 +      return NS_STYLE_WINDOW_SHADOW_TOOLTIP;
   1.330 +    case NS_THEME_MENUPOPUP:
   1.331 +      return NS_STYLE_WINDOW_SHADOW_MENU;
   1.332 +  }
   1.333 +  return NS_STYLE_WINDOW_SHADOW_DEFAULT;
   1.334 +}
   1.335 +
   1.336 +// this class is used for dispatching popupshown events asynchronously.
   1.337 +class nsXULPopupShownEvent : public nsRunnable
   1.338 +{
   1.339 +public:
   1.340 +  nsXULPopupShownEvent(nsIContent *aPopup, nsPresContext* aPresContext)
   1.341 +    : mPopup(aPopup), mPresContext(aPresContext)
   1.342 +  {
   1.343 +  }
   1.344 +
   1.345 +  NS_IMETHOD Run() MOZ_OVERRIDE
   1.346 +  {
   1.347 +    WidgetMouseEvent event(true, NS_XUL_POPUP_SHOWN, nullptr,
   1.348 +                           WidgetMouseEvent::eReal);
   1.349 +    return EventDispatcher::Dispatch(mPopup, mPresContext, &event);                 
   1.350 +  }
   1.351 +
   1.352 +private:
   1.353 +  nsCOMPtr<nsIContent> mPopup;
   1.354 +  nsRefPtr<nsPresContext> mPresContext;
   1.355 +};
   1.356 +
   1.357 +nsresult
   1.358 +nsMenuPopupFrame::SetInitialChildList(ChildListID  aListID,
   1.359 +                                      nsFrameList& aChildList)
   1.360 +{
   1.361 +  // unless the list is empty, indicate that children have been generated.
   1.362 +  if (aChildList.NotEmpty())
   1.363 +    mGeneratedChildren = true;
   1.364 +  return nsBoxFrame::SetInitialChildList(aListID, aChildList);
   1.365 +}
   1.366 +
   1.367 +bool
   1.368 +nsMenuPopupFrame::IsLeaf() const
   1.369 +{
   1.370 +  if (mGeneratedChildren)
   1.371 +    return false;
   1.372 +
   1.373 +  if (mPopupType != ePopupTypeMenu) {
   1.374 +    // any panel with a type attribute, such as the autocomplete popup,
   1.375 +    // is always generated right away.
   1.376 +    return !mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::type);
   1.377 +  }
   1.378 +
   1.379 +  // menu popups generate their child frames lazily only when opened, so
   1.380 +  // behave like a leaf frame. However, generate child frames normally if
   1.381 +  // the parent menu has a sizetopopup attribute. In this case the size of
   1.382 +  // the parent menu is dependent on the size of the popup, so the frames
   1.383 +  // need to exist in order to calculate this size.
   1.384 +  nsIContent* parentContent = mContent->GetParent();
   1.385 +  return (parentContent &&
   1.386 +          !parentContent->HasAttr(kNameSpaceID_None, nsGkAtoms::sizetopopup));
   1.387 +}
   1.388 +
   1.389 +void
   1.390 +nsMenuPopupFrame::LayoutPopup(nsBoxLayoutState& aState, nsIFrame* aParentMenu,
   1.391 +                              nsIFrame* aAnchor, bool aSizedToPopup)
   1.392 +{
   1.393 +  if (!mGeneratedChildren)
   1.394 +    return;
   1.395 +
   1.396 +  SchedulePaint();
   1.397 +
   1.398 +  bool shouldPosition = true;
   1.399 +  bool isOpen = IsOpen();
   1.400 +  if (!isOpen) {
   1.401 +    // if the popup is not open, only do layout while showing or if the menu
   1.402 +    // is sized to the popup
   1.403 +    shouldPosition = (mPopupState == ePopupShowing);
   1.404 +    if (!shouldPosition && !aSizedToPopup) {
   1.405 +      RemoveStateBits(NS_FRAME_FIRST_REFLOW);
   1.406 +      return;
   1.407 +    }
   1.408 +  }
   1.409 +
   1.410 +  // if the popup has just been opened, make sure the scrolled window is at 0,0
   1.411 +  if (mIsOpenChanged) {
   1.412 +    nsIScrollableFrame *scrollframe = do_QueryFrame(GetChildBox());
   1.413 +    if (scrollframe) {
   1.414 +      nsWeakFrame weakFrame(this);
   1.415 +      scrollframe->ScrollTo(nsPoint(0,0), nsIScrollableFrame::INSTANT);
   1.416 +      if (!weakFrame.IsAlive()) {
   1.417 +        return;
   1.418 +      }
   1.419 +    }
   1.420 +  }
   1.421 +
   1.422 +  // get the preferred, minimum and maximum size. If the menu is sized to the
   1.423 +  // popup, then the popup's width is the menu's width.
   1.424 +  nsSize prefSize = GetPrefSize(aState);
   1.425 +  nsSize minSize = GetMinSize(aState); 
   1.426 +  nsSize maxSize = GetMaxSize(aState);
   1.427 +
   1.428 +  if (aSizedToPopup) {
   1.429 +    prefSize.width = aParentMenu->GetRect().width;
   1.430 +  }
   1.431 +  prefSize = BoundsCheck(minSize, prefSize, maxSize);
   1.432 +
   1.433 +  // if the size changed then set the bounds to be the preferred size
   1.434 +  bool sizeChanged = (mPrefSize != prefSize);
   1.435 +  if (sizeChanged) {
   1.436 +    SetBounds(aState, nsRect(0, 0, prefSize.width, prefSize.height), false);
   1.437 +    mPrefSize = prefSize;
   1.438 +  }
   1.439 +
   1.440 +  if (shouldPosition) {
   1.441 +    SetPopupPosition(aAnchor, false, aSizedToPopup);
   1.442 +  }
   1.443 +
   1.444 +  nsRect bounds(GetRect());
   1.445 +  Layout(aState);
   1.446 +
   1.447 +  // if the width or height changed, readjust the popup position. This is a
   1.448 +  // special case for tooltips where the preferred height doesn't include the
   1.449 +  // real height for its inline element, but does once it is laid out.
   1.450 +  // This is bug 228673 which doesn't have a simple fix.
   1.451 +  if (!aParentMenu) {
   1.452 +    nsSize newsize = GetSize();
   1.453 +    if (newsize.width > bounds.width || newsize.height > bounds.height) {
   1.454 +      // the size after layout was larger than the preferred size,
   1.455 +      // so set the preferred size accordingly
   1.456 +      mPrefSize = newsize;
   1.457 +      if (isOpen) {
   1.458 +        SetPopupPosition(nullptr, false, aSizedToPopup);
   1.459 +      }
   1.460 +    }
   1.461 +  }
   1.462 +
   1.463 +  nsPresContext* pc = PresContext();
   1.464 +  nsView* view = GetView();
   1.465 +
   1.466 +  if (sizeChanged) {
   1.467 +    // If the size of the popup changed, apply any size constraints.
   1.468 +    nsIWidget* widget = view->GetWidget();
   1.469 +    if (widget) {
   1.470 +      SetSizeConstraints(pc, widget, minSize, maxSize);
   1.471 +    }
   1.472 +  }
   1.473 +
   1.474 +  if (isOpen) {
   1.475 +    nsViewManager* viewManager = view->GetViewManager();
   1.476 +    nsRect rect = GetRect();
   1.477 +    rect.x = rect.y = 0;
   1.478 +    viewManager->ResizeView(view, rect);
   1.479 +
   1.480 +    viewManager->SetViewVisibility(view, nsViewVisibility_kShow);
   1.481 +    mPopupState = ePopupOpenAndVisible;
   1.482 +    nsContainerFrame::SyncFrameViewProperties(pc, this, nullptr, view, 0);
   1.483 +  }
   1.484 +
   1.485 +  // finally, if the popup just opened, send a popupshown event
   1.486 +  if (mIsOpenChanged) {
   1.487 +    mIsOpenChanged = false;
   1.488 +    nsCOMPtr<nsIRunnable> event = new nsXULPopupShownEvent(GetContent(), pc);
   1.489 +    NS_DispatchToCurrentThread(event);
   1.490 +  }
   1.491 +}
   1.492 +
   1.493 +nsIContent*
   1.494 +nsMenuPopupFrame::GetTriggerContent(nsMenuPopupFrame* aMenuPopupFrame)
   1.495 +{
   1.496 +  while (aMenuPopupFrame) {
   1.497 +    if (aMenuPopupFrame->mTriggerContent)
   1.498 +      return aMenuPopupFrame->mTriggerContent;
   1.499 +
   1.500 +    // check up the menu hierarchy until a popup with a trigger node is found
   1.501 +    nsMenuFrame* menuFrame = do_QueryFrame(aMenuPopupFrame->GetParent());
   1.502 +    if (!menuFrame)
   1.503 +      break;
   1.504 +
   1.505 +    nsMenuParent* parentPopup = menuFrame->GetMenuParent();
   1.506 +    if (!parentPopup || !parentPopup->IsMenu())
   1.507 +      break;
   1.508 +
   1.509 +    aMenuPopupFrame = static_cast<nsMenuPopupFrame *>(parentPopup);
   1.510 +  }
   1.511 +
   1.512 +  return nullptr;
   1.513 +}
   1.514 +
   1.515 +void
   1.516 +nsMenuPopupFrame::InitPositionFromAnchorAlign(const nsAString& aAnchor,
   1.517 +                                              const nsAString& aAlign)
   1.518 +{
   1.519 +  mTriggerContent = nullptr;
   1.520 +
   1.521 +  if (aAnchor.EqualsLiteral("topleft"))
   1.522 +    mPopupAnchor = POPUPALIGNMENT_TOPLEFT;
   1.523 +  else if (aAnchor.EqualsLiteral("topright"))
   1.524 +    mPopupAnchor = POPUPALIGNMENT_TOPRIGHT;
   1.525 +  else if (aAnchor.EqualsLiteral("bottomleft"))
   1.526 +    mPopupAnchor = POPUPALIGNMENT_BOTTOMLEFT;
   1.527 +  else if (aAnchor.EqualsLiteral("bottomright"))
   1.528 +    mPopupAnchor = POPUPALIGNMENT_BOTTOMRIGHT;
   1.529 +  else if (aAnchor.EqualsLiteral("leftcenter"))
   1.530 +    mPopupAnchor = POPUPALIGNMENT_LEFTCENTER;
   1.531 +  else if (aAnchor.EqualsLiteral("rightcenter"))
   1.532 +    mPopupAnchor = POPUPALIGNMENT_RIGHTCENTER;
   1.533 +  else if (aAnchor.EqualsLiteral("topcenter"))
   1.534 +    mPopupAnchor = POPUPALIGNMENT_TOPCENTER;
   1.535 +  else if (aAnchor.EqualsLiteral("bottomcenter"))
   1.536 +    mPopupAnchor = POPUPALIGNMENT_BOTTOMCENTER;
   1.537 +  else
   1.538 +    mPopupAnchor = POPUPALIGNMENT_NONE;
   1.539 +
   1.540 +  if (aAlign.EqualsLiteral("topleft"))
   1.541 +    mPopupAlignment = POPUPALIGNMENT_TOPLEFT;
   1.542 +  else if (aAlign.EqualsLiteral("topright"))
   1.543 +    mPopupAlignment = POPUPALIGNMENT_TOPRIGHT;
   1.544 +  else if (aAlign.EqualsLiteral("bottomleft"))
   1.545 +    mPopupAlignment = POPUPALIGNMENT_BOTTOMLEFT;
   1.546 +  else if (aAlign.EqualsLiteral("bottomright"))
   1.547 +    mPopupAlignment = POPUPALIGNMENT_BOTTOMRIGHT;
   1.548 +  else
   1.549 +    mPopupAlignment = POPUPALIGNMENT_NONE;
   1.550 +
   1.551 +  mPosition = POPUPPOSITION_UNKNOWN;
   1.552 +}
   1.553 +
   1.554 +void
   1.555 +nsMenuPopupFrame::InitializePopup(nsIContent* aAnchorContent,
   1.556 +                                  nsIContent* aTriggerContent,
   1.557 +                                  const nsAString& aPosition,
   1.558 +                                  int32_t aXPos, int32_t aYPos,
   1.559 +                                  bool aAttributesOverride)
   1.560 +{
   1.561 +  EnsureWidget();
   1.562 +
   1.563 +  mPopupState = ePopupShowing;
   1.564 +  mAnchorContent = aAnchorContent;
   1.565 +  mTriggerContent = aTriggerContent;
   1.566 +  mXPos = aXPos;
   1.567 +  mYPos = aYPos;
   1.568 +  mAdjustOffsetForContextMenu = false;
   1.569 +  mVFlip = false;
   1.570 +  mHFlip = false;
   1.571 +  mAlignmentOffset = 0;
   1.572 +
   1.573 +  // if aAttributesOverride is true, then the popupanchor, popupalign and
   1.574 +  // position attributes on the <popup> override those values passed in.
   1.575 +  // If false, those attributes are only used if the values passed in are empty
   1.576 +  if (aAnchorContent) {
   1.577 +    nsAutoString anchor, align, position, flip;
   1.578 +    mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::popupanchor, anchor);
   1.579 +    mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::popupalign, align);
   1.580 +    mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::position, position);
   1.581 +    mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::flip, flip);
   1.582 +
   1.583 +    if (aAttributesOverride) {
   1.584 +      // if the attributes are set, clear the offset position. Otherwise,
   1.585 +      // the offset is used to adjust the position from the anchor point
   1.586 +      if (anchor.IsEmpty() && align.IsEmpty() && position.IsEmpty())
   1.587 +        position.Assign(aPosition);
   1.588 +      else
   1.589 +        mXPos = mYPos = 0;
   1.590 +    }
   1.591 +    else if (!aPosition.IsEmpty()) {
   1.592 +      position.Assign(aPosition);
   1.593 +    }
   1.594 +
   1.595 +    if (flip.EqualsLiteral("none")) {
   1.596 +      mFlip = FlipType_None;
   1.597 +    } else if (flip.EqualsLiteral("both")) {
   1.598 +      mFlip = FlipType_Both;
   1.599 +    } else if (flip.EqualsLiteral("slide")) {
   1.600 +      mFlip = FlipType_Slide;
   1.601 +    }
   1.602 +
   1.603 +    position.CompressWhitespace();
   1.604 +    int32_t spaceIdx = position.FindChar(' ');
   1.605 +    // if there is a space in the position, assume it is the anchor and
   1.606 +    // alignment as two separate tokens.
   1.607 +    if (spaceIdx >= 0) {
   1.608 +      InitPositionFromAnchorAlign(Substring(position, 0, spaceIdx), Substring(position, spaceIdx + 1));
   1.609 +    }
   1.610 +    else if (position.EqualsLiteral("before_start")) {
   1.611 +      mPopupAnchor = POPUPALIGNMENT_TOPLEFT;
   1.612 +      mPopupAlignment = POPUPALIGNMENT_BOTTOMLEFT;
   1.613 +      mPosition = POPUPPOSITION_BEFORESTART;
   1.614 +    }
   1.615 +    else if (position.EqualsLiteral("before_end")) {
   1.616 +      mPopupAnchor = POPUPALIGNMENT_TOPRIGHT;
   1.617 +      mPopupAlignment = POPUPALIGNMENT_BOTTOMRIGHT;
   1.618 +      mPosition = POPUPPOSITION_BEFOREEND;
   1.619 +    }
   1.620 +    else if (position.EqualsLiteral("after_start")) {
   1.621 +      mPopupAnchor = POPUPALIGNMENT_BOTTOMLEFT;
   1.622 +      mPopupAlignment = POPUPALIGNMENT_TOPLEFT;
   1.623 +      mPosition = POPUPPOSITION_AFTERSTART;
   1.624 +    }
   1.625 +    else if (position.EqualsLiteral("after_end")) {
   1.626 +      mPopupAnchor = POPUPALIGNMENT_BOTTOMRIGHT;
   1.627 +      mPopupAlignment = POPUPALIGNMENT_TOPRIGHT;
   1.628 +      mPosition = POPUPPOSITION_AFTEREND;
   1.629 +    }
   1.630 +    else if (position.EqualsLiteral("start_before")) {
   1.631 +      mPopupAnchor = POPUPALIGNMENT_TOPLEFT;
   1.632 +      mPopupAlignment = POPUPALIGNMENT_TOPRIGHT;
   1.633 +      mPosition = POPUPPOSITION_STARTBEFORE;
   1.634 +    }
   1.635 +    else if (position.EqualsLiteral("start_after")) {
   1.636 +      mPopupAnchor = POPUPALIGNMENT_BOTTOMLEFT;
   1.637 +      mPopupAlignment = POPUPALIGNMENT_BOTTOMRIGHT;
   1.638 +      mPosition = POPUPPOSITION_STARTAFTER;
   1.639 +    }
   1.640 +    else if (position.EqualsLiteral("end_before")) {
   1.641 +      mPopupAnchor = POPUPALIGNMENT_TOPRIGHT;
   1.642 +      mPopupAlignment = POPUPALIGNMENT_TOPLEFT;
   1.643 +      mPosition = POPUPPOSITION_ENDBEFORE;
   1.644 +    }
   1.645 +    else if (position.EqualsLiteral("end_after")) {
   1.646 +      mPopupAnchor = POPUPALIGNMENT_BOTTOMRIGHT;
   1.647 +      mPopupAlignment = POPUPALIGNMENT_BOTTOMLEFT;
   1.648 +      mPosition = POPUPPOSITION_ENDAFTER;
   1.649 +    }
   1.650 +    else if (position.EqualsLiteral("overlap")) {
   1.651 +      mPopupAnchor = POPUPALIGNMENT_TOPLEFT;
   1.652 +      mPopupAlignment = POPUPALIGNMENT_TOPLEFT;
   1.653 +      mPosition = POPUPPOSITION_OVERLAP;
   1.654 +    }
   1.655 +    else if (position.EqualsLiteral("after_pointer")) {
   1.656 +      mPopupAnchor = POPUPALIGNMENT_TOPLEFT;
   1.657 +      mPopupAlignment = POPUPALIGNMENT_TOPLEFT;
   1.658 +      mPosition = POPUPPOSITION_AFTERPOINTER;
   1.659 +      // XXXndeakin this is supposed to anchor vertically after, but with the
   1.660 +      // horizontal position as the mouse pointer.
   1.661 +      mYPos += 21;
   1.662 +    }
   1.663 +    else {
   1.664 +      InitPositionFromAnchorAlign(anchor, align);
   1.665 +    }
   1.666 +  }
   1.667 +
   1.668 +  mScreenXPos = -1;
   1.669 +  mScreenYPos = -1;
   1.670 +
   1.671 +  if (aAttributesOverride) {
   1.672 +    // Use |left| and |top| dimension attributes to position the popup if
   1.673 +    // present, as they may have been persisted. 
   1.674 +    nsAutoString left, top;
   1.675 +    mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::left, left);
   1.676 +    mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::top, top);
   1.677 +
   1.678 +    nsresult err;
   1.679 +    if (!left.IsEmpty()) {
   1.680 +      int32_t x = left.ToInteger(&err);
   1.681 +      if (NS_SUCCEEDED(err))
   1.682 +        mScreenXPos = x;
   1.683 +    }
   1.684 +    if (!top.IsEmpty()) {
   1.685 +      int32_t y = top.ToInteger(&err);
   1.686 +      if (NS_SUCCEEDED(err))
   1.687 +        mScreenYPos = y;
   1.688 +    }
   1.689 +  }
   1.690 +}
   1.691 +
   1.692 +void
   1.693 +nsMenuPopupFrame::InitializePopupAtScreen(nsIContent* aTriggerContent,
   1.694 +                                          int32_t aXPos, int32_t aYPos,
   1.695 +                                          bool aIsContextMenu)
   1.696 +{
   1.697 +  EnsureWidget();
   1.698 +
   1.699 +  mPopupState = ePopupShowing;
   1.700 +  mAnchorContent = nullptr;
   1.701 +  mTriggerContent = aTriggerContent;
   1.702 +  mScreenXPos = aXPos;
   1.703 +  mScreenYPos = aYPos;
   1.704 +  mFlip = FlipType_Default;
   1.705 +  mPopupAnchor = POPUPALIGNMENT_NONE;
   1.706 +  mPopupAlignment = POPUPALIGNMENT_NONE;
   1.707 +  mIsContextMenu = aIsContextMenu;
   1.708 +  mAdjustOffsetForContextMenu = aIsContextMenu;
   1.709 +}
   1.710 +
   1.711 +void
   1.712 +nsMenuPopupFrame::InitializePopupWithAnchorAlign(nsIContent* aAnchorContent,
   1.713 +                                                 nsAString& aAnchor,
   1.714 +                                                 nsAString& aAlign,
   1.715 +                                                 int32_t aXPos, int32_t aYPos)
   1.716 +{
   1.717 +  EnsureWidget();
   1.718 +
   1.719 +  mPopupState = ePopupShowing;
   1.720 +  mAdjustOffsetForContextMenu = false;
   1.721 +  mFlip = FlipType_Default;
   1.722 +
   1.723 +  // this popup opening function is provided for backwards compatibility
   1.724 +  // only. It accepts either coordinates or an anchor and alignment value
   1.725 +  // but doesn't use both together.
   1.726 +  if (aXPos == -1 && aYPos == -1) {
   1.727 +    mAnchorContent = aAnchorContent;
   1.728 +    mScreenXPos = -1;
   1.729 +    mScreenYPos = -1;
   1.730 +    mXPos = 0;
   1.731 +    mYPos = 0;
   1.732 +    InitPositionFromAnchorAlign(aAnchor, aAlign);
   1.733 +  }
   1.734 +  else {
   1.735 +    mAnchorContent = nullptr;
   1.736 +    mPopupAnchor = POPUPALIGNMENT_NONE;
   1.737 +    mPopupAlignment = POPUPALIGNMENT_NONE;
   1.738 +    mScreenXPos = aXPos;
   1.739 +    mScreenYPos = aYPos;
   1.740 +    mXPos = aXPos;
   1.741 +    mYPos = aYPos;
   1.742 +  }
   1.743 +}
   1.744 +
   1.745 +void
   1.746 +nsMenuPopupFrame::ShowPopup(bool aIsContextMenu, bool aSelectFirstItem)
   1.747 +{
   1.748 +  mIsContextMenu = aIsContextMenu;
   1.749 +
   1.750 +  InvalidateFrameSubtree();
   1.751 +
   1.752 +  if (mPopupState == ePopupShowing) {
   1.753 +    mPopupState = ePopupOpen;
   1.754 +    mIsOpenChanged = true;
   1.755 +
   1.756 +    nsMenuFrame* menuFrame = do_QueryFrame(GetParent());
   1.757 +    if (menuFrame) {
   1.758 +      nsWeakFrame weakFrame(this);
   1.759 +      menuFrame->PopupOpened();
   1.760 +      if (!weakFrame.IsAlive())
   1.761 +        return;
   1.762 +    }
   1.763 +
   1.764 +    // do we need an actual reflow here?
   1.765 +    // is SetPopupPosition all that is needed?
   1.766 +    PresContext()->PresShell()->FrameNeedsReflow(this, nsIPresShell::eTreeChange,
   1.767 +                                                 NS_FRAME_HAS_DIRTY_CHILDREN);
   1.768 +
   1.769 +    if (mPopupType == ePopupTypeMenu) {
   1.770 +      nsCOMPtr<nsISound> sound(do_CreateInstance("@mozilla.org/sound;1"));
   1.771 +      if (sound)
   1.772 +        sound->PlayEventSound(nsISound::EVENT_MENU_POPUP);
   1.773 +    }
   1.774 +  }
   1.775 +
   1.776 +  mShouldAutoPosition = true;
   1.777 +}
   1.778 +
   1.779 +void
   1.780 +nsMenuPopupFrame::HidePopup(bool aDeselectMenu, nsPopupState aNewState)
   1.781 +{
   1.782 +  NS_ASSERTION(aNewState == ePopupClosed || aNewState == ePopupInvisible,
   1.783 +               "popup being set to unexpected state");
   1.784 +
   1.785 +  // don't hide the popup when it isn't open
   1.786 +  if (mPopupState == ePopupClosed || mPopupState == ePopupShowing)
   1.787 +    return;
   1.788 +
   1.789 +  // clear the trigger content if the popup is being closed. But don't clear
   1.790 +  // it if the popup is just being made invisible as a popuphiding or command
   1.791 +  // event may want to retrieve it.
   1.792 +  if (aNewState == ePopupClosed) {
   1.793 +    // if the popup had a trigger node set, clear the global window popup node
   1.794 +    // as well
   1.795 +    if (mTriggerContent) {
   1.796 +      nsIDocument* doc = mContent->GetCurrentDoc();
   1.797 +      if (doc) {
   1.798 +        nsPIDOMWindow* win = doc->GetWindow();
   1.799 +        if (win) {
   1.800 +          nsCOMPtr<nsPIWindowRoot> root = win->GetTopWindowRoot();
   1.801 +          if (root) {
   1.802 +            root->SetPopupNode(nullptr);
   1.803 +          }
   1.804 +        }
   1.805 +      }
   1.806 +    }
   1.807 +    mTriggerContent = nullptr;
   1.808 +    mAnchorContent = nullptr;
   1.809 +  }
   1.810 +
   1.811 +  // when invisible and about to be closed, HidePopup has already been called,
   1.812 +  // so just set the new state to closed and return
   1.813 +  if (mPopupState == ePopupInvisible) {
   1.814 +    if (aNewState == ePopupClosed)
   1.815 +      mPopupState = ePopupClosed;
   1.816 +    return;
   1.817 +  }
   1.818 +
   1.819 +  mPopupState = aNewState;
   1.820 +
   1.821 +  if (IsMenu())
   1.822 +    SetCurrentMenuItem(nullptr);
   1.823 +
   1.824 +  mIncrementalString.Truncate();
   1.825 +
   1.826 +  LockMenuUntilClosed(false);
   1.827 +
   1.828 +  mIsOpenChanged = false;
   1.829 +  mCurrentMenu = nullptr; // make sure no current menu is set
   1.830 +  mHFlip = mVFlip = false;
   1.831 +
   1.832 +  nsView* view = GetView();
   1.833 +  nsViewManager* viewManager = view->GetViewManager();
   1.834 +  viewManager->SetViewVisibility(view, nsViewVisibility_kHide);
   1.835 +
   1.836 +  FireDOMEvent(NS_LITERAL_STRING("DOMMenuInactive"), mContent);
   1.837 +
   1.838 +  // XXX, bug 137033, In Windows, if mouse is outside the window when the menupopup closes, no
   1.839 +  // mouse_enter/mouse_exit event will be fired to clear current hover state, we should clear it manually.
   1.840 +  // This code may not the best solution, but we can leave it here until we find the better approach.
   1.841 +  NS_ASSERTION(mContent->IsElement(), "How do we have a non-element?");
   1.842 +  EventStates state = mContent->AsElement()->State();
   1.843 +
   1.844 +  if (state.HasState(NS_EVENT_STATE_HOVER)) {
   1.845 +    EventStateManager* esm = PresContext()->EventStateManager();
   1.846 +    esm->SetContentState(nullptr, NS_EVENT_STATE_HOVER);
   1.847 +  }
   1.848 +
   1.849 +  nsMenuFrame* menuFrame = do_QueryFrame(GetParent());
   1.850 +  if (menuFrame) {
   1.851 +    menuFrame->PopupClosed(aDeselectMenu);
   1.852 +  }
   1.853 +}
   1.854 +
   1.855 +void
   1.856 +nsMenuPopupFrame::GetLayoutFlags(uint32_t& aFlags)
   1.857 +{
   1.858 +  aFlags = NS_FRAME_NO_SIZE_VIEW | NS_FRAME_NO_MOVE_VIEW | NS_FRAME_NO_VISIBILITY;
   1.859 +}
   1.860 +
   1.861 +///////////////////////////////////////////////////////////////////////////////
   1.862 +// GetRootViewForPopup
   1.863 +//   Retrieves the view for the popup widget that contains the given frame. 
   1.864 +//   If the given frame is not contained by a popup widget, return the
   1.865 +//   root view of the root viewmanager.
   1.866 +nsView*
   1.867 +nsMenuPopupFrame::GetRootViewForPopup(nsIFrame* aStartFrame)
   1.868 +{
   1.869 +  nsView* view = aStartFrame->GetClosestView();
   1.870 +  NS_ASSERTION(view, "frame must have a closest view!");
   1.871 +  while (view) {
   1.872 +    // Walk up the view hierarchy looking for a view whose widget has a 
   1.873 +    // window type of eWindowType_popup - in other words a popup window
   1.874 +    // widget. If we find one, this is the view we want. 
   1.875 +    nsIWidget* widget = view->GetWidget();
   1.876 +    if (widget && widget->WindowType() == eWindowType_popup) {
   1.877 +      return view;
   1.878 +    }
   1.879 +
   1.880 +    nsView* temp = view->GetParent();
   1.881 +    if (!temp) {
   1.882 +      // Otherwise, we've walked all the way up to the root view and not
   1.883 +      // found a view for a popup window widget. Just return the root view.
   1.884 +      return view;
   1.885 +    }
   1.886 +    view = temp;
   1.887 +  }
   1.888 +
   1.889 +  return nullptr;
   1.890 +}
   1.891 +
   1.892 +nsPoint
   1.893 +nsMenuPopupFrame::AdjustPositionForAnchorAlign(nsRect& anchorRect,
   1.894 +                                               FlipStyle& aHFlip, FlipStyle& aVFlip)
   1.895 +{
   1.896 +  // flip the anchor and alignment for right-to-left
   1.897 +  int8_t popupAnchor(mPopupAnchor);
   1.898 +  int8_t popupAlign(mPopupAlignment);
   1.899 +  if (IsDirectionRTL()) {
   1.900 +    // no need to flip the centered anchor types vertically
   1.901 +    if (popupAnchor <= POPUPALIGNMENT_LEFTCENTER) {
   1.902 +      popupAnchor = -popupAnchor;
   1.903 +    }
   1.904 +    popupAlign = -popupAlign;
   1.905 +  }
   1.906 +
   1.907 +  // first, determine at which corner of the anchor the popup should appear
   1.908 +  nsPoint pnt;
   1.909 +  switch (popupAnchor) {
   1.910 +    case POPUPALIGNMENT_LEFTCENTER:
   1.911 +      pnt = nsPoint(anchorRect.x, anchorRect.y + anchorRect.height / 2);
   1.912 +      anchorRect.y = pnt.y;
   1.913 +      anchorRect.height = 0;
   1.914 +      break;
   1.915 +    case POPUPALIGNMENT_RIGHTCENTER:
   1.916 +      pnt = nsPoint(anchorRect.XMost(), anchorRect.y + anchorRect.height / 2);
   1.917 +      anchorRect.y = pnt.y;
   1.918 +      anchorRect.height = 0;
   1.919 +      break;
   1.920 +    case POPUPALIGNMENT_TOPCENTER:
   1.921 +      pnt = nsPoint(anchorRect.x + anchorRect.width / 2, anchorRect.y);
   1.922 +      anchorRect.x = pnt.x;
   1.923 +      anchorRect.width = 0;
   1.924 +      break;
   1.925 +    case POPUPALIGNMENT_BOTTOMCENTER:
   1.926 +      pnt = nsPoint(anchorRect.x + anchorRect.width / 2, anchorRect.YMost());
   1.927 +      anchorRect.x = pnt.x;
   1.928 +      anchorRect.width = 0;
   1.929 +      break;
   1.930 +    case POPUPALIGNMENT_TOPRIGHT:
   1.931 +      pnt = anchorRect.TopRight();
   1.932 +      break;
   1.933 +    case POPUPALIGNMENT_BOTTOMLEFT:
   1.934 +      pnt = anchorRect.BottomLeft();
   1.935 +      break;
   1.936 +    case POPUPALIGNMENT_BOTTOMRIGHT:
   1.937 +      pnt = anchorRect.BottomRight();
   1.938 +      break;
   1.939 +    case POPUPALIGNMENT_TOPLEFT:
   1.940 +    default:
   1.941 +      pnt = anchorRect.TopLeft();
   1.942 +      break;
   1.943 +  }
   1.944 +
   1.945 +  // If the alignment is on the right edge of the popup, move the popup left
   1.946 +  // by the width. Similarly, if the alignment is on the bottom edge of the
   1.947 +  // popup, move the popup up by the height. In addition, account for the
   1.948 +  // margins of the popup on the edge on which it is aligned.
   1.949 +  nsMargin margin(0, 0, 0, 0);
   1.950 +  StyleMargin()->GetMargin(margin);
   1.951 +  switch (popupAlign) {
   1.952 +    case POPUPALIGNMENT_TOPRIGHT:
   1.953 +      pnt.MoveBy(-mRect.width - margin.right, margin.top);
   1.954 +      break;
   1.955 +    case POPUPALIGNMENT_BOTTOMLEFT:
   1.956 +      pnt.MoveBy(margin.left, -mRect.height - margin.bottom);
   1.957 +      break;
   1.958 +    case POPUPALIGNMENT_BOTTOMRIGHT:
   1.959 +      pnt.MoveBy(-mRect.width - margin.right, -mRect.height - margin.bottom);
   1.960 +      break;
   1.961 +    case POPUPALIGNMENT_TOPLEFT:
   1.962 +    default:
   1.963 +      pnt.MoveBy(margin.left, margin.top);
   1.964 +      break;
   1.965 +  }
   1.966 +
   1.967 +  // Flipping horizontally is allowed as long as the popup is above or below
   1.968 +  // the anchor. This will happen if both the anchor and alignment are top or
   1.969 +  // both are bottom, but different values. Similarly, flipping vertically is
   1.970 +  // allowed if the popup is to the left or right of the anchor. In this case,
   1.971 +  // the values of the constants are such that both must be positive or both
   1.972 +  // must be negative. A special case, used for overlap, allows flipping
   1.973 +  // vertically as well.
   1.974 +  // If we are flipping in both directions, we want to set a flip style both
   1.975 +  // horizontally and vertically. However, we want to flip on the inside edge
   1.976 +  // of the anchor. Consider the example of a typical dropdown menu.
   1.977 +  // Vertically, we flip the popup on the outside edges of the anchor menu,
   1.978 +  // however horizontally, we want to to use the inside edges so the popup
   1.979 +  // still appears underneath the anchor menu instead of floating off the
   1.980 +  // side of the menu.
   1.981 +  switch (popupAnchor) {
   1.982 +    case POPUPALIGNMENT_LEFTCENTER:
   1.983 +    case POPUPALIGNMENT_RIGHTCENTER:
   1.984 +      aHFlip = FlipStyle_Outside;
   1.985 +      aVFlip = FlipStyle_Inside;
   1.986 +      break;
   1.987 +    case POPUPALIGNMENT_TOPCENTER:
   1.988 +    case POPUPALIGNMENT_BOTTOMCENTER:
   1.989 +      aHFlip = FlipStyle_Inside;
   1.990 +      aVFlip = FlipStyle_Outside;
   1.991 +      break;
   1.992 +    default:
   1.993 +    {
   1.994 +      FlipStyle anchorEdge = mFlip == FlipType_Both ? FlipStyle_Inside : FlipStyle_None;
   1.995 +      aHFlip = (popupAnchor == -popupAlign) ? FlipStyle_Outside : anchorEdge;
   1.996 +      if (((popupAnchor > 0) == (popupAlign > 0)) ||
   1.997 +          (popupAnchor == POPUPALIGNMENT_TOPLEFT && popupAlign == POPUPALIGNMENT_TOPLEFT))
   1.998 +        aVFlip = FlipStyle_Outside;
   1.999 +      else
  1.1000 +        aVFlip = anchorEdge;
  1.1001 +      break;
  1.1002 +    }
  1.1003 +  }
  1.1004 +
  1.1005 +  return pnt;
  1.1006 +}
  1.1007 +
  1.1008 +nscoord
  1.1009 +nsMenuPopupFrame::SlideOrResize(nscoord& aScreenPoint, nscoord aSize,
  1.1010 +                               nscoord aScreenBegin, nscoord aScreenEnd,
  1.1011 +                               nscoord *aOffset)
  1.1012 +{
  1.1013 +  // The popup may be positioned such that either the left/top or bottom/right
  1.1014 +  // is outside the screen - but never both.
  1.1015 +  nscoord newPos =
  1.1016 +    std::max(aScreenBegin, std::min(aScreenEnd - aSize, aScreenPoint));
  1.1017 +  *aOffset = newPos - aScreenPoint;
  1.1018 +  aScreenPoint = newPos;
  1.1019 +  return std::min(aSize, aScreenEnd - aScreenPoint);
  1.1020 +}
  1.1021 +
  1.1022 +nscoord
  1.1023 +nsMenuPopupFrame::FlipOrResize(nscoord& aScreenPoint, nscoord aSize, 
  1.1024 +                               nscoord aScreenBegin, nscoord aScreenEnd,
  1.1025 +                               nscoord aAnchorBegin, nscoord aAnchorEnd,
  1.1026 +                               nscoord aMarginBegin, nscoord aMarginEnd,
  1.1027 +                               nscoord aOffsetForContextMenu, FlipStyle aFlip,
  1.1028 +                               bool* aFlipSide)
  1.1029 +{
  1.1030 +  // all of the coordinates used here are in app units relative to the screen
  1.1031 +  nscoord popupSize = aSize;
  1.1032 +  if (aScreenPoint < aScreenBegin) {
  1.1033 +    // at its current position, the popup would extend past the left or top
  1.1034 +    // edge of the screen, so it will have to be moved or resized.
  1.1035 +    if (aFlip) {
  1.1036 +      // for inside flips, we flip on the opposite side of the anchor
  1.1037 +      nscoord startpos = aFlip == FlipStyle_Outside ? aAnchorBegin : aAnchorEnd;
  1.1038 +      nscoord endpos = aFlip == FlipStyle_Outside ? aAnchorEnd : aAnchorBegin;
  1.1039 +
  1.1040 +      // check whether there is more room to the left and right (or top and
  1.1041 +      // bottom) of the anchor and put the popup on the side with more room.
  1.1042 +      if (startpos - aScreenBegin >= aScreenEnd - endpos) {
  1.1043 +        aScreenPoint = aScreenBegin;
  1.1044 +        popupSize = startpos - aScreenPoint - aMarginEnd;
  1.1045 +      }
  1.1046 +      else {
  1.1047 +        // If the newly calculated position is different than the existing
  1.1048 +        // position, flip such that the popup is to the right or bottom of the
  1.1049 +        // anchor point instead . However, when flipping use the same margin
  1.1050 +        // size.
  1.1051 +        nscoord newScreenPoint = endpos + aMarginEnd;
  1.1052 +        if (newScreenPoint != aScreenPoint) {
  1.1053 +          *aFlipSide = true;
  1.1054 +          aScreenPoint = newScreenPoint;
  1.1055 +          // check if the new position is still off the right or bottom edge of
  1.1056 +          // the screen. If so, resize the popup.
  1.1057 +          if (aScreenPoint + aSize > aScreenEnd) {
  1.1058 +            popupSize = aScreenEnd - aScreenPoint;
  1.1059 +          }
  1.1060 +        }
  1.1061 +      }
  1.1062 +    }
  1.1063 +    else {
  1.1064 +      aScreenPoint = aScreenBegin;
  1.1065 +    }
  1.1066 +  }
  1.1067 +  else if (aScreenPoint + aSize > aScreenEnd) {
  1.1068 +    // at its current position, the popup would extend past the right or
  1.1069 +    // bottom edge of the screen, so it will have to be moved or resized.
  1.1070 +    if (aFlip) {
  1.1071 +      // for inside flips, we flip on the opposite side of the anchor
  1.1072 +      nscoord startpos = aFlip == FlipStyle_Outside ? aAnchorBegin : aAnchorEnd;
  1.1073 +      nscoord endpos = aFlip == FlipStyle_Outside ? aAnchorEnd : aAnchorBegin;
  1.1074 +
  1.1075 +      // check whether there is more room to the left and right (or top and
  1.1076 +      // bottom) of the anchor and put the popup on the side with more room.
  1.1077 +      if (aScreenEnd - endpos >= startpos - aScreenBegin) {
  1.1078 +        if (mIsContextMenu) {
  1.1079 +          aScreenPoint = aScreenEnd - aSize;
  1.1080 +        }
  1.1081 +        else {
  1.1082 +          aScreenPoint = endpos + aMarginBegin;
  1.1083 +          popupSize = aScreenEnd - aScreenPoint;
  1.1084 +        }
  1.1085 +      }
  1.1086 +      else {
  1.1087 +        // if the newly calculated position is different than the existing
  1.1088 +        // position, we flip such that the popup is to the left or top of the
  1.1089 +        // anchor point instead.
  1.1090 +        nscoord newScreenPoint = startpos - aSize - aMarginBegin - aOffsetForContextMenu;
  1.1091 +        if (newScreenPoint != aScreenPoint) {
  1.1092 +          *aFlipSide = true;
  1.1093 +          aScreenPoint = newScreenPoint;
  1.1094 +
  1.1095 +          // check if the new position is still off the left or top edge of the
  1.1096 +          // screen. If so, resize the popup.
  1.1097 +          if (aScreenPoint < aScreenBegin) {
  1.1098 +            aScreenPoint = aScreenBegin;
  1.1099 +            if (!mIsContextMenu) {
  1.1100 +              popupSize = startpos - aScreenPoint - aMarginBegin;
  1.1101 +            }
  1.1102 +          }
  1.1103 +        }
  1.1104 +      }
  1.1105 +    }
  1.1106 +    else {
  1.1107 +      aScreenPoint = aScreenEnd - aSize;
  1.1108 +    }
  1.1109 +  }
  1.1110 +
  1.1111 +  // Make sure that the point is within the screen boundaries and that the
  1.1112 +  // size isn't off the edge of the screen. This can happen when a large
  1.1113 +  // positive or negative margin is used.
  1.1114 +  if (aScreenPoint < aScreenBegin) {
  1.1115 +    aScreenPoint = aScreenBegin;
  1.1116 +  }
  1.1117 +  if (aScreenPoint > aScreenEnd) {
  1.1118 +    aScreenPoint = aScreenEnd - aSize;
  1.1119 +  }
  1.1120 +
  1.1121 +  // If popupSize ended up being negative, or the original size was actually
  1.1122 +  // smaller than the calculated popup size, just use the original size instead.
  1.1123 +  if (popupSize <= 0 || aSize < popupSize) {
  1.1124 +    popupSize = aSize;
  1.1125 +  }
  1.1126 +  return std::min(popupSize, aScreenEnd - aScreenPoint);
  1.1127 +}
  1.1128 +
  1.1129 +nsresult
  1.1130 +nsMenuPopupFrame::SetPopupPosition(nsIFrame* aAnchorFrame, bool aIsMove, bool aSizedToPopup)
  1.1131 +{
  1.1132 +  if (!mShouldAutoPosition)
  1.1133 +    return NS_OK;
  1.1134 +
  1.1135 +  // If this is due to a move, return early if the popup hasn't been laid out
  1.1136 +  // yet. On Windows, this can happen when using a drag popup before it opens.
  1.1137 +  if (aIsMove && (mPrefSize.width == -1 || mPrefSize.height == -1)) {
  1.1138 +    return NS_OK;
  1.1139 +  }
  1.1140 +
  1.1141 +  nsPresContext* presContext = PresContext();
  1.1142 +  nsIFrame* rootFrame = presContext->PresShell()->FrameManager()->GetRootFrame();
  1.1143 +  NS_ASSERTION(rootFrame->GetView() && GetView() &&
  1.1144 +               rootFrame->GetView() == GetView()->GetParent(),
  1.1145 +               "rootFrame's view is not our view's parent???");
  1.1146 +
  1.1147 +  // if the frame is not specified, use the anchor node passed to OpenPopup. If
  1.1148 +  // that wasn't specified either, use the root frame. Note that mAnchorContent
  1.1149 +  // might be a different document so its presshell must be used.
  1.1150 +  if (!aAnchorFrame) {
  1.1151 +    if (mAnchorContent) {
  1.1152 +      aAnchorFrame = mAnchorContent->GetPrimaryFrame();
  1.1153 +    }
  1.1154 +
  1.1155 +    if (!aAnchorFrame) {
  1.1156 +      aAnchorFrame = rootFrame;
  1.1157 +      if (!aAnchorFrame)
  1.1158 +        return NS_OK;
  1.1159 +    }
  1.1160 +  }
  1.1161 +
  1.1162 +  // the dimensions of the anchor in its app units
  1.1163 +  nsRect parentRect = aAnchorFrame->GetScreenRectInAppUnits();
  1.1164 +
  1.1165 +  // the anchor may be in a different document with a different scale,
  1.1166 +  // so adjust the size so that it is in the app units of the popup instead
  1.1167 +  // of the anchor.
  1.1168 +  parentRect = parentRect.ConvertAppUnitsRoundOut(
  1.1169 +    aAnchorFrame->PresContext()->AppUnitsPerDevPixel(),
  1.1170 +    presContext->AppUnitsPerDevPixel());
  1.1171 +
  1.1172 +  // Set the popup's size to the preferred size. Below, this size will be
  1.1173 +  // adjusted to fit on the screen or within the content area. If the anchor
  1.1174 +  // is sized to the popup, use the anchor's width instead of the preferred
  1.1175 +  // width. The preferred size should already be set by the parent frame.
  1.1176 +  NS_ASSERTION(mPrefSize.width >= 0 || mPrefSize.height >= 0,
  1.1177 +               "preferred size of popup not set");
  1.1178 +  mRect.width = aSizedToPopup ? parentRect.width : mPrefSize.width;
  1.1179 +  mRect.height = mPrefSize.height;
  1.1180 +
  1.1181 +  // the screen position in app units where the popup should appear
  1.1182 +  nsPoint screenPoint;
  1.1183 +
  1.1184 +  // For anchored popups, the anchor rectangle. For non-anchored popups, the
  1.1185 +  // size will be 0.
  1.1186 +  nsRect anchorRect = parentRect;
  1.1187 +
  1.1188 +  // indicators of whether the popup should be flipped or resized.
  1.1189 +  FlipStyle hFlip = FlipStyle_None, vFlip = FlipStyle_None;
  1.1190 +
  1.1191 +  nsMargin margin(0, 0, 0, 0);
  1.1192 +  StyleMargin()->GetMargin(margin);
  1.1193 +
  1.1194 +  // the screen rectangle of the root frame, in dev pixels.
  1.1195 +  nsRect rootScreenRect = rootFrame->GetScreenRectInAppUnits();
  1.1196 +
  1.1197 +  nsDeviceContext* devContext = presContext->DeviceContext();
  1.1198 +  nscoord offsetForContextMenu = 0;
  1.1199 +
  1.1200 +  bool isNoAutoHide = IsNoAutoHide();
  1.1201 +  nsPopupLevel popupLevel = PopupLevel(isNoAutoHide);
  1.1202 +
  1.1203 +  if (IsAnchored()) {
  1.1204 +    // if we are anchored, there are certain things we don't want to do when
  1.1205 +    // repositioning the popup to fit on the screen, such as end up positioned
  1.1206 +    // over the anchor, for instance a popup appearing over the menu label.
  1.1207 +    // When doing this reposition, we want to move the popup to the side with
  1.1208 +    // the most room. The combination of anchor and alignment dictate if we 
  1.1209 +    // readjust above/below or to the left/right.
  1.1210 +    if (mAnchorContent) {
  1.1211 +      // move the popup according to the anchor and alignment. This will also
  1.1212 +      // tell us which axis the popup is flush against in case we have to move
  1.1213 +      // it around later. The AdjustPositionForAnchorAlign method accounts for
  1.1214 +      // the popup's margin.
  1.1215 +      screenPoint = AdjustPositionForAnchorAlign(anchorRect, hFlip, vFlip);
  1.1216 +    }
  1.1217 +    else {
  1.1218 +      // with no anchor, the popup is positioned relative to the root frame
  1.1219 +      anchorRect = rootScreenRect;
  1.1220 +      screenPoint = anchorRect.TopLeft() + nsPoint(margin.left, margin.top);
  1.1221 +    }
  1.1222 +
  1.1223 +    // mXPos and mYPos specify an additonal offset passed to OpenPopup that
  1.1224 +    // should be added to the position.  We also add the offset to the anchor
  1.1225 +    // pos so a later flip/resize takes the offset into account.
  1.1226 +    nscoord anchorXOffset = presContext->CSSPixelsToAppUnits(mXPos);
  1.1227 +    if (IsDirectionRTL()) {
  1.1228 +      screenPoint.x -= anchorXOffset;
  1.1229 +      anchorRect.x -= anchorXOffset;
  1.1230 +    } else {
  1.1231 +      screenPoint.x += anchorXOffset;
  1.1232 +      anchorRect.x += anchorXOffset;
  1.1233 +    }
  1.1234 +    nscoord anchorYOffset = presContext->CSSPixelsToAppUnits(mYPos);
  1.1235 +    screenPoint.y += anchorYOffset;
  1.1236 +    anchorRect.y += anchorYOffset;
  1.1237 +
  1.1238 +    // If this is a noautohide popup, set the screen coordinates of the popup.
  1.1239 +    // This way, the popup stays at the location where it was opened even when
  1.1240 +    // the window is moved. Popups at the parent level follow the parent
  1.1241 +    // window as it is moved and remained anchored, so we want to maintain the
  1.1242 +    // anchoring instead.
  1.1243 +    if (isNoAutoHide && popupLevel != ePopupLevelParent) {
  1.1244 +      // Account for the margin that will end up being added to the screen coordinate
  1.1245 +      // the next time SetPopupPosition is called.
  1.1246 +      mScreenXPos = presContext->AppUnitsToIntCSSPixels(screenPoint.x - margin.left);
  1.1247 +      mScreenYPos = presContext->AppUnitsToIntCSSPixels(screenPoint.y - margin.top);
  1.1248 +    }
  1.1249 +  }
  1.1250 +  else {
  1.1251 +    // the popup is positioned at a screen coordinate.
  1.1252 +    // first convert the screen position in mScreenXPos and mScreenYPos from
  1.1253 +    // CSS pixels into device pixels, ignoring any scaling as mScreenXPos and
  1.1254 +    // mScreenYPos are unscaled screen coordinates.
  1.1255 +    int32_t factor = devContext->UnscaledAppUnitsPerDevPixel();
  1.1256 +
  1.1257 +    // context menus should be offset by two pixels so that they don't appear
  1.1258 +    // directly where the cursor is. Otherwise, it is too easy to have the
  1.1259 +    // context menu close up again.
  1.1260 +    if (mAdjustOffsetForContextMenu) {
  1.1261 +      int32_t offsetForContextMenuDev =
  1.1262 +        nsPresContext::CSSPixelsToAppUnits(CONTEXT_MENU_OFFSET_PIXELS) / factor;
  1.1263 +      offsetForContextMenu = presContext->DevPixelsToAppUnits(offsetForContextMenuDev);
  1.1264 +    }
  1.1265 +
  1.1266 +    // next, convert into app units accounting for the scaling
  1.1267 +    screenPoint.x = presContext->DevPixelsToAppUnits(
  1.1268 +                      nsPresContext::CSSPixelsToAppUnits(mScreenXPos) / factor);
  1.1269 +    screenPoint.y = presContext->DevPixelsToAppUnits(
  1.1270 +                      nsPresContext::CSSPixelsToAppUnits(mScreenYPos) / factor);
  1.1271 +    anchorRect = nsRect(screenPoint, nsSize(0, 0));
  1.1272 +
  1.1273 +    // add the margins on the popup
  1.1274 +    screenPoint.MoveBy(margin.left + offsetForContextMenu,
  1.1275 +                       margin.top + offsetForContextMenu);
  1.1276 +
  1.1277 +    // screen positioned popups can be flipped vertically but never horizontally
  1.1278 +    vFlip = FlipStyle_Outside;
  1.1279 +  }
  1.1280 +
  1.1281 +  // If a panel is being moved or has flip="none", don't constrain or flip it. But always do this for
  1.1282 +  // content shells, so that the popup doesn't extend outside the containing frame.
  1.1283 +  if (mInContentShell || (mFlip != FlipType_None && (!aIsMove || mPopupType != ePopupTypePanel))) {
  1.1284 +    nsRect screenRect = GetConstraintRect(anchorRect, rootScreenRect, popupLevel);
  1.1285 +
  1.1286 +    // Ensure that anchorRect is on screen.
  1.1287 +    anchorRect = anchorRect.Intersect(screenRect);
  1.1288 +
  1.1289 +    // shrink the the popup down if it is larger than the screen size
  1.1290 +    if (mRect.width > screenRect.width)
  1.1291 +      mRect.width = screenRect.width;
  1.1292 +    if (mRect.height > screenRect.height)
  1.1293 +      mRect.height = screenRect.height;
  1.1294 +
  1.1295 +    // at this point the anchor (anchorRect) is within the available screen
  1.1296 +    // area (screenRect) and the popup is known to be no larger than the screen.
  1.1297 +
  1.1298 +    // We might want to "slide" an arrow if the panel is of the correct type -
  1.1299 +    // but we can only slide on one axis - the other axis must be "flipped or
  1.1300 +    // resized" as normal.
  1.1301 +    bool slideHorizontal = false, slideVertical = false;
  1.1302 +    if (mFlip == FlipType_Slide) {
  1.1303 +      int8_t position = GetAlignmentPosition();
  1.1304 +      slideHorizontal = position >= POPUPPOSITION_BEFORESTART &&
  1.1305 +                        position <= POPUPPOSITION_AFTEREND;
  1.1306 +      slideVertical = position >= POPUPPOSITION_STARTBEFORE &&
  1.1307 +                      position <= POPUPPOSITION_ENDAFTER;
  1.1308 +    }
  1.1309 +
  1.1310 +    // Next, check if there is enough space to show the popup at full size when
  1.1311 +    // positioned at screenPoint. If not, flip the popups to the opposite side
  1.1312 +    // of their anchor point, or resize them as necessary.
  1.1313 +    if (slideHorizontal) {
  1.1314 +      mRect.width = SlideOrResize(screenPoint.x, mRect.width, screenRect.x,
  1.1315 +                                  screenRect.XMost(), &mAlignmentOffset);
  1.1316 +    } else {
  1.1317 +      mRect.width = FlipOrResize(screenPoint.x, mRect.width, screenRect.x,
  1.1318 +                                 screenRect.XMost(), anchorRect.x, anchorRect.XMost(),
  1.1319 +                                 margin.left, margin.right, offsetForContextMenu, hFlip,
  1.1320 +                                 &mHFlip);
  1.1321 +    }
  1.1322 +    if (slideVertical) {
  1.1323 +      mRect.height = SlideOrResize(screenPoint.y, mRect.height, screenRect.y,
  1.1324 +                                  screenRect.YMost(), &mAlignmentOffset);
  1.1325 +    } else {
  1.1326 +      mRect.height = FlipOrResize(screenPoint.y, mRect.height, screenRect.y,
  1.1327 +                                  screenRect.YMost(), anchorRect.y, anchorRect.YMost(),
  1.1328 +                                  margin.top, margin.bottom, offsetForContextMenu, vFlip,
  1.1329 +                                  &mVFlip);
  1.1330 +    }
  1.1331 +
  1.1332 +    NS_ASSERTION(screenPoint.x >= screenRect.x && screenPoint.y >= screenRect.y &&
  1.1333 +                 screenPoint.x + mRect.width <= screenRect.XMost() &&
  1.1334 +                 screenPoint.y + mRect.height <= screenRect.YMost(),
  1.1335 +                 "Popup is offscreen");
  1.1336 +  }
  1.1337 +
  1.1338 +  // snap the popup's position in screen coordinates to device pixels,
  1.1339 +  // see bug 622507, bug 961431
  1.1340 +  screenPoint.x = presContext->RoundAppUnitsToNearestDevPixels(screenPoint.x);
  1.1341 +  screenPoint.y = presContext->RoundAppUnitsToNearestDevPixels(screenPoint.y);
  1.1342 +
  1.1343 +  // determine the x and y position of the view by subtracting the desired
  1.1344 +  // screen position from the screen position of the root frame.
  1.1345 +  nsPoint viewPoint = screenPoint - rootScreenRect.TopLeft();
  1.1346 +
  1.1347 +  nsView* view = GetView();
  1.1348 +  NS_ASSERTION(view, "popup with no view");
  1.1349 +
  1.1350 +  // Offset the position by the width and height of the borders and titlebar.
  1.1351 +  // Even though GetClientOffset should return (0, 0) when there is no
  1.1352 +  // titlebar or borders, we skip these calculations anyway for non-panels
  1.1353 +  // to save time since they will never have a titlebar.
  1.1354 +  nsIWidget* widget = view->GetWidget();
  1.1355 +  if (mPopupType == ePopupTypePanel && widget) {
  1.1356 +    mLastClientOffset = widget->GetClientOffset();
  1.1357 +    viewPoint.x += presContext->DevPixelsToAppUnits(mLastClientOffset.x);
  1.1358 +    viewPoint.y += presContext->DevPixelsToAppUnits(mLastClientOffset.y);
  1.1359 +  }
  1.1360 +
  1.1361 +  presContext->GetPresShell()->GetViewManager()->
  1.1362 +    MoveViewTo(view, viewPoint.x, viewPoint.y);
  1.1363 +
  1.1364 +  // Now that we've positioned the view, sync up the frame's origin.
  1.1365 +  nsBoxFrame::SetPosition(viewPoint - GetParent()->GetOffsetTo(rootFrame));
  1.1366 +
  1.1367 +  if (aSizedToPopup) {
  1.1368 +    nsBoxLayoutState state(PresContext());
  1.1369 +    // XXXndeakin can parentSize.width still extend outside?
  1.1370 +    SetBounds(state, nsRect(mRect.x, mRect.y, parentRect.width, mRect.height));
  1.1371 +  }
  1.1372 +
  1.1373 +  return NS_OK;
  1.1374 +}
  1.1375 +
  1.1376 +/* virtual */ nsMenuFrame*
  1.1377 +nsMenuPopupFrame::GetCurrentMenuItem()
  1.1378 +{
  1.1379 +  return mCurrentMenu;
  1.1380 +}
  1.1381 +
  1.1382 +nsRect
  1.1383 +nsMenuPopupFrame::GetConstraintRect(const nsRect& aAnchorRect,
  1.1384 +                                    const nsRect& aRootScreenRect,
  1.1385 +                                    nsPopupLevel aPopupLevel)
  1.1386 +{
  1.1387 +  nsIntRect screenRectPixels;
  1.1388 +  nsPresContext* presContext = PresContext();
  1.1389 +
  1.1390 +  // determine the available screen space. It will be reduced by the OS chrome
  1.1391 +  // such as menubars. It addition, for content shells, it will be the area of
  1.1392 +  // the content rather than the screen.
  1.1393 +  nsCOMPtr<nsIScreen> screen;
  1.1394 +  nsCOMPtr<nsIScreenManager> sm(do_GetService("@mozilla.org/gfx/screenmanager;1"));
  1.1395 +  if (sm) {
  1.1396 +    // for content shells, get the screen where the root frame is located.
  1.1397 +    // This is because we need to constrain the content to this content area,
  1.1398 +    // so we should use the same screen. Otherwise, use the screen where the
  1.1399 +    // anchor is located.
  1.1400 +    nsRect rect = mInContentShell ? aRootScreenRect : aAnchorRect;
  1.1401 +    // nsIScreenManager::ScreenForRect wants the coordinates in CSS pixels
  1.1402 +    int32_t width = std::max(1, nsPresContext::AppUnitsToIntCSSPixels(rect.width));
  1.1403 +    int32_t height = std::max(1, nsPresContext::AppUnitsToIntCSSPixels(rect.height));
  1.1404 +    sm->ScreenForRect(nsPresContext::AppUnitsToIntCSSPixels(rect.x),
  1.1405 +                      nsPresContext::AppUnitsToIntCSSPixels(rect.y),
  1.1406 +                      width, height, getter_AddRefs(screen));
  1.1407 +    if (screen) {
  1.1408 +      // Non-top-level popups (which will always be panels)
  1.1409 +      // should never overlap the OS bar:
  1.1410 +      bool dontOverlapOSBar = aPopupLevel != ePopupLevelTop;
  1.1411 +      // get the total screen area if the popup is allowed to overlap it.
  1.1412 +      if (!dontOverlapOSBar && mMenuCanOverlapOSBar && !mInContentShell)
  1.1413 +        screen->GetRect(&screenRectPixels.x, &screenRectPixels.y,
  1.1414 +                        &screenRectPixels.width, &screenRectPixels.height);
  1.1415 +      else
  1.1416 +        screen->GetAvailRect(&screenRectPixels.x, &screenRectPixels.y,
  1.1417 +                             &screenRectPixels.width, &screenRectPixels.height);
  1.1418 +    }
  1.1419 +  }
  1.1420 +
  1.1421 +  nsRect screenRect = screenRectPixels.ToAppUnits(presContext->AppUnitsPerDevPixel());
  1.1422 +  if (mInContentShell) {
  1.1423 +    // for content shells, clip to the client area rather than the screen area
  1.1424 +    screenRect.IntersectRect(screenRect, aRootScreenRect);
  1.1425 +  }
  1.1426 +
  1.1427 +  return screenRect;
  1.1428 +}
  1.1429 +
  1.1430 +void nsMenuPopupFrame::CanAdjustEdges(int8_t aHorizontalSide, int8_t aVerticalSide, nsIntPoint& aChange)
  1.1431 +{
  1.1432 +  int8_t popupAlign(mPopupAlignment);
  1.1433 +  if (IsDirectionRTL()) {
  1.1434 +    popupAlign = -popupAlign;
  1.1435 +  }
  1.1436 +
  1.1437 +  if (aHorizontalSide == (mHFlip ? NS_SIDE_RIGHT : NS_SIDE_LEFT)) {
  1.1438 +    if (popupAlign == POPUPALIGNMENT_TOPLEFT || popupAlign == POPUPALIGNMENT_BOTTOMLEFT) {
  1.1439 +      aChange.x = 0;
  1.1440 +    }
  1.1441 +  }
  1.1442 +  else if (aHorizontalSide == (mHFlip ? NS_SIDE_LEFT : NS_SIDE_RIGHT)) {
  1.1443 +    if (popupAlign == POPUPALIGNMENT_TOPRIGHT || popupAlign == POPUPALIGNMENT_BOTTOMRIGHT) {
  1.1444 +      aChange.x = 0;
  1.1445 +    }
  1.1446 +  }
  1.1447 +
  1.1448 +  if (aVerticalSide == (mVFlip ? NS_SIDE_BOTTOM : NS_SIDE_TOP)) {
  1.1449 +    if (popupAlign == POPUPALIGNMENT_TOPLEFT || popupAlign == POPUPALIGNMENT_TOPRIGHT) {
  1.1450 +      aChange.y = 0;
  1.1451 +    }
  1.1452 +  }
  1.1453 +  else if (aVerticalSide == (mVFlip ? NS_SIDE_TOP : NS_SIDE_BOTTOM)) {
  1.1454 +    if (popupAlign == POPUPALIGNMENT_BOTTOMLEFT || popupAlign == POPUPALIGNMENT_BOTTOMRIGHT) {
  1.1455 +      aChange.y = 0;
  1.1456 +    }
  1.1457 +  }
  1.1458 +}
  1.1459 +
  1.1460 +bool nsMenuPopupFrame::ConsumeOutsideClicks()
  1.1461 +{
  1.1462 +  // If the popup has explicitly set a consume mode, honor that.
  1.1463 +  if (mConsumeRollupEvent != nsIPopupBoxObject::ROLLUP_DEFAULT)
  1.1464 +    return (mConsumeRollupEvent == nsIPopupBoxObject::ROLLUP_CONSUME);
  1.1465 +
  1.1466 +  if (mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::consumeoutsideclicks,
  1.1467 +                            nsGkAtoms::_true, eCaseMatters))
  1.1468 +    return true;
  1.1469 +  if (mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::consumeoutsideclicks,
  1.1470 +                            nsGkAtoms::_false, eCaseMatters))
  1.1471 +    return false;
  1.1472 +
  1.1473 +  nsCOMPtr<nsIContent> parentContent = mContent->GetParent();
  1.1474 +  if (parentContent) {
  1.1475 +    nsINodeInfo *ni = parentContent->NodeInfo();
  1.1476 +    if (ni->Equals(nsGkAtoms::menulist, kNameSpaceID_XUL))
  1.1477 +      return true;  // Consume outside clicks for combo boxes on all platforms
  1.1478 +#if defined(XP_WIN)
  1.1479 +    // Don't consume outside clicks for menus in Windows
  1.1480 +    if (ni->Equals(nsGkAtoms::menu, kNameSpaceID_XUL) ||
  1.1481 +        ni->Equals(nsGkAtoms::splitmenu, kNameSpaceID_XUL) ||
  1.1482 +        ni->Equals(nsGkAtoms::popupset, kNameSpaceID_XUL) ||
  1.1483 +        ((ni->Equals(nsGkAtoms::button, kNameSpaceID_XUL) ||
  1.1484 +          ni->Equals(nsGkAtoms::toolbarbutton, kNameSpaceID_XUL)) &&
  1.1485 +         (parentContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
  1.1486 +                                     nsGkAtoms::menu, eCaseMatters) ||
  1.1487 +          parentContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
  1.1488 +                                     nsGkAtoms::menuButton, eCaseMatters)))) {
  1.1489 +      return false;
  1.1490 +    }
  1.1491 +#endif
  1.1492 +    if (ni->Equals(nsGkAtoms::textbox, kNameSpaceID_XUL)) {
  1.1493 +      // Don't consume outside clicks for autocomplete widget
  1.1494 +      if (parentContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
  1.1495 +                                     nsGkAtoms::autocomplete, eCaseMatters))
  1.1496 +        return false;
  1.1497 +    }
  1.1498 +  }
  1.1499 +
  1.1500 +  return true;
  1.1501 +}
  1.1502 +
  1.1503 +// XXXroc this is megalame. Fossicking around for a frame of the right
  1.1504 +// type is a recipe for disaster in the long term.
  1.1505 +nsIScrollableFrame* nsMenuPopupFrame::GetScrollFrame(nsIFrame* aStart)
  1.1506 +{
  1.1507 +  if (!aStart)
  1.1508 +    return nullptr;  
  1.1509 +
  1.1510 +  // try start frame and siblings
  1.1511 +  nsIFrame* currFrame = aStart;
  1.1512 +  do {
  1.1513 +    nsIScrollableFrame* sf = do_QueryFrame(currFrame);
  1.1514 +    if (sf)
  1.1515 +      return sf;
  1.1516 +    currFrame = currFrame->GetNextSibling();
  1.1517 +  } while (currFrame);
  1.1518 +
  1.1519 +  // try children
  1.1520 +  currFrame = aStart;
  1.1521 +  do {
  1.1522 +    nsIFrame* childFrame = currFrame->GetFirstPrincipalChild();
  1.1523 +    nsIScrollableFrame* sf = GetScrollFrame(childFrame);
  1.1524 +    if (sf)
  1.1525 +      return sf;
  1.1526 +    currFrame = currFrame->GetNextSibling();
  1.1527 +  } while (currFrame);
  1.1528 +
  1.1529 +  return nullptr;
  1.1530 +}
  1.1531 +
  1.1532 +void nsMenuPopupFrame::EnsureMenuItemIsVisible(nsMenuFrame* aMenuItem)
  1.1533 +{
  1.1534 +  if (aMenuItem) {
  1.1535 +    aMenuItem->PresContext()->PresShell()->ScrollFrameRectIntoView(
  1.1536 +      aMenuItem,
  1.1537 +      nsRect(nsPoint(0,0), aMenuItem->GetRect().Size()),
  1.1538 +      nsIPresShell::ScrollAxis(),
  1.1539 +      nsIPresShell::ScrollAxis(),
  1.1540 +      nsIPresShell::SCROLL_OVERFLOW_HIDDEN |
  1.1541 +      nsIPresShell::SCROLL_FIRST_ANCESTOR_ONLY);
  1.1542 +  }
  1.1543 +}
  1.1544 +
  1.1545 +NS_IMETHODIMP nsMenuPopupFrame::SetCurrentMenuItem(nsMenuFrame* aMenuItem)
  1.1546 +{
  1.1547 +  if (mCurrentMenu == aMenuItem)
  1.1548 +    return NS_OK;
  1.1549 +
  1.1550 +  if (mCurrentMenu) {
  1.1551 +    mCurrentMenu->SelectMenu(false);
  1.1552 +  }
  1.1553 +
  1.1554 +  if (aMenuItem) {
  1.1555 +    EnsureMenuItemIsVisible(aMenuItem);
  1.1556 +    aMenuItem->SelectMenu(true);
  1.1557 +  }
  1.1558 +
  1.1559 +  mCurrentMenu = aMenuItem;
  1.1560 +
  1.1561 +  return NS_OK;
  1.1562 +}
  1.1563 +
  1.1564 +void
  1.1565 +nsMenuPopupFrame::CurrentMenuIsBeingDestroyed()
  1.1566 +{
  1.1567 +  mCurrentMenu = nullptr;
  1.1568 +}
  1.1569 +
  1.1570 +NS_IMETHODIMP
  1.1571 +nsMenuPopupFrame::ChangeMenuItem(nsMenuFrame* aMenuItem,
  1.1572 +                                 bool aSelectFirstItem)
  1.1573 +{
  1.1574 +  if (mCurrentMenu == aMenuItem)
  1.1575 +    return NS_OK;
  1.1576 +
  1.1577 +  // When a context menu is open, the current menu is locked, and no change
  1.1578 +  // to the menu is allowed.
  1.1579 +  nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
  1.1580 +  if (!mIsContextMenu && pm && pm->HasContextMenu(this))
  1.1581 +    return NS_OK;
  1.1582 +
  1.1583 +  // Unset the current child.
  1.1584 +  if (mCurrentMenu) {
  1.1585 +    mCurrentMenu->SelectMenu(false);
  1.1586 +    nsMenuPopupFrame* popup = mCurrentMenu->GetPopup();
  1.1587 +    if (popup) {
  1.1588 +      if (mCurrentMenu->IsOpen()) {
  1.1589 +        if (pm)
  1.1590 +          pm->HidePopupAfterDelay(popup);
  1.1591 +      }
  1.1592 +    }
  1.1593 +  }
  1.1594 +
  1.1595 +  // Set the new child.
  1.1596 +  if (aMenuItem) {
  1.1597 +    EnsureMenuItemIsVisible(aMenuItem);
  1.1598 +    aMenuItem->SelectMenu(true);
  1.1599 +  }
  1.1600 +
  1.1601 +  mCurrentMenu = aMenuItem;
  1.1602 +
  1.1603 +  return NS_OK;
  1.1604 +}
  1.1605 +
  1.1606 +nsMenuFrame*
  1.1607 +nsMenuPopupFrame::Enter(WidgetGUIEvent* aEvent)
  1.1608 +{
  1.1609 +  mIncrementalString.Truncate();
  1.1610 +
  1.1611 +  // Give it to the child.
  1.1612 +  if (mCurrentMenu)
  1.1613 +    return mCurrentMenu->Enter(aEvent);
  1.1614 +
  1.1615 +  return nullptr;
  1.1616 +}
  1.1617 +
  1.1618 +nsMenuFrame*
  1.1619 +nsMenuPopupFrame::FindMenuWithShortcut(nsIDOMKeyEvent* aKeyEvent, bool& doAction)
  1.1620 +{
  1.1621 +  uint32_t charCode, keyCode;
  1.1622 +  aKeyEvent->GetCharCode(&charCode);
  1.1623 +  aKeyEvent->GetKeyCode(&keyCode);
  1.1624 +
  1.1625 +  doAction = false;
  1.1626 +
  1.1627 +  // Enumerate over our list of frames.
  1.1628 +  nsIFrame* immediateParent = PresContext()->PresShell()->
  1.1629 +    FrameConstructor()->GetInsertionPoint(GetContent(), nullptr);
  1.1630 +  if (!immediateParent)
  1.1631 +    immediateParent = this;
  1.1632 +
  1.1633 +  uint32_t matchCount = 0, matchShortcutCount = 0;
  1.1634 +  bool foundActive = false;
  1.1635 +  bool isShortcut;
  1.1636 +  nsMenuFrame* frameBefore = nullptr;
  1.1637 +  nsMenuFrame* frameAfter = nullptr;
  1.1638 +  nsMenuFrame* frameShortcut = nullptr;
  1.1639 +
  1.1640 +  nsIContent* parentContent = mContent->GetParent();
  1.1641 +
  1.1642 +  bool isMenu = parentContent &&
  1.1643 +                  !parentContent->NodeInfo()->Equals(nsGkAtoms::menulist, kNameSpaceID_XUL);
  1.1644 +
  1.1645 +  static DOMTimeStamp lastKeyTime = 0;
  1.1646 +  DOMTimeStamp keyTime;
  1.1647 +  aKeyEvent->GetTimeStamp(&keyTime);
  1.1648 +
  1.1649 +  if (charCode == 0) {
  1.1650 +    if (keyCode == nsIDOMKeyEvent::DOM_VK_BACK_SPACE) {
  1.1651 +      if (!isMenu && !mIncrementalString.IsEmpty()) {
  1.1652 +        mIncrementalString.SetLength(mIncrementalString.Length() - 1);
  1.1653 +        return nullptr;
  1.1654 +      }
  1.1655 +      else {
  1.1656 +#ifdef XP_WIN
  1.1657 +        nsCOMPtr<nsISound> soundInterface = do_CreateInstance("@mozilla.org/sound;1");
  1.1658 +        if (soundInterface)
  1.1659 +          soundInterface->Beep();
  1.1660 +#endif  // #ifdef XP_WIN
  1.1661 +      }
  1.1662 +    }
  1.1663 +    return nullptr;
  1.1664 +  }
  1.1665 +  else {
  1.1666 +    char16_t uniChar = ToLowerCase(static_cast<char16_t>(charCode));
  1.1667 +    if (isMenu || // Menu supports only first-letter navigation
  1.1668 +        keyTime - lastKeyTime > INC_TYP_INTERVAL) // Interval too long, treat as new typing
  1.1669 +      mIncrementalString = uniChar;
  1.1670 +    else {
  1.1671 +      mIncrementalString.Append(uniChar);
  1.1672 +    }
  1.1673 +  }
  1.1674 +
  1.1675 +  // See bug 188199 & 192346, if all letters in incremental string are same, just try to match the first one
  1.1676 +  nsAutoString incrementalString(mIncrementalString);
  1.1677 +  uint32_t charIndex = 1, stringLength = incrementalString.Length();
  1.1678 +  while (charIndex < stringLength && incrementalString[charIndex] == incrementalString[charIndex - 1]) {
  1.1679 +    charIndex++;
  1.1680 +  }
  1.1681 +  if (charIndex == stringLength) {
  1.1682 +    incrementalString.Truncate(1);
  1.1683 +    stringLength = 1;
  1.1684 +  }
  1.1685 +
  1.1686 +  lastKeyTime = keyTime;
  1.1687 +
  1.1688 +  nsIFrame* currFrame;
  1.1689 +  // NOTE: If you crashed here due to a bogus |immediateParent| it is 
  1.1690 +  //       possible that the menu whose shortcut is being looked up has 
  1.1691 +  //       been destroyed already.  One strategy would be to 
  1.1692 +  //       setTimeout(<func>,0) as detailed in:
  1.1693 +  //       <http://bugzilla.mozilla.org/show_bug.cgi?id=126675#c32>
  1.1694 +  currFrame = immediateParent->GetFirstPrincipalChild();
  1.1695 +
  1.1696 +  int32_t menuAccessKey = -1;
  1.1697 +  nsMenuBarListener::GetMenuAccessKey(&menuAccessKey);
  1.1698 +
  1.1699 +  // We start searching from first child. This process is divided into two parts
  1.1700 +  //   -- before current and after current -- by the current item
  1.1701 +  while (currFrame) {
  1.1702 +    nsIContent* current = currFrame->GetContent();
  1.1703 +    
  1.1704 +    // See if it's a menu item.
  1.1705 +    if (nsXULPopupManager::IsValidMenuItem(PresContext(), current, true)) {
  1.1706 +      nsAutoString textKey;
  1.1707 +      if (menuAccessKey >= 0) {
  1.1708 +        // Get the shortcut attribute.
  1.1709 +        current->GetAttr(kNameSpaceID_None, nsGkAtoms::accesskey, textKey);
  1.1710 +      }
  1.1711 +      if (textKey.IsEmpty()) { // No shortcut, try first letter
  1.1712 +        isShortcut = false;
  1.1713 +        current->GetAttr(kNameSpaceID_None, nsGkAtoms::label, textKey);
  1.1714 +        if (textKey.IsEmpty()) // No label, try another attribute (value)
  1.1715 +          current->GetAttr(kNameSpaceID_None, nsGkAtoms::value, textKey);
  1.1716 +      }
  1.1717 +      else
  1.1718 +        isShortcut = true;
  1.1719 +
  1.1720 +      if (StringBeginsWith(textKey, incrementalString,
  1.1721 +                           nsCaseInsensitiveStringComparator())) {
  1.1722 +        // mIncrementalString is a prefix of textKey
  1.1723 +        nsMenuFrame* menu = do_QueryFrame(currFrame);
  1.1724 +        if (menu) {
  1.1725 +          // There is one match
  1.1726 +          matchCount++;
  1.1727 +          if (isShortcut) {
  1.1728 +            // There is one shortcut-key match
  1.1729 +            matchShortcutCount++;
  1.1730 +            // Record the matched item. If there is only one matched shortcut item, do it
  1.1731 +            frameShortcut = menu;
  1.1732 +          }
  1.1733 +          if (!foundActive) {
  1.1734 +            // It's a first candidate item located before/on the current item
  1.1735 +            if (!frameBefore)
  1.1736 +              frameBefore = menu;
  1.1737 +          }
  1.1738 +          else {
  1.1739 +            // It's a first candidate item located after the current item
  1.1740 +            if (!frameAfter)
  1.1741 +              frameAfter = menu;
  1.1742 +          }
  1.1743 +        }
  1.1744 +        else
  1.1745 +          return nullptr;
  1.1746 +      }
  1.1747 +
  1.1748 +      // Get the active status
  1.1749 +      if (current->AttrValueIs(kNameSpaceID_None, nsGkAtoms::menuactive,
  1.1750 +                               nsGkAtoms::_true, eCaseMatters)) {
  1.1751 +        foundActive = true;
  1.1752 +        if (stringLength > 1) {
  1.1753 +          // If there is more than one char typed, the current item has highest priority,
  1.1754 +          //   otherwise the item next to current has highest priority
  1.1755 +          if (currFrame == frameBefore)
  1.1756 +            return frameBefore;
  1.1757 +        }
  1.1758 +      }
  1.1759 +    }
  1.1760 +    currFrame = currFrame->GetNextSibling();
  1.1761 +  }
  1.1762 +
  1.1763 +  doAction = (isMenu && (matchCount == 1 || matchShortcutCount == 1));
  1.1764 +
  1.1765 +  if (matchShortcutCount == 1) // We have one matched shortcut item
  1.1766 +    return frameShortcut;
  1.1767 +  if (frameAfter) // If we have matched item after the current, use it
  1.1768 +    return frameAfter;
  1.1769 +  else if (frameBefore) // If we haven't, use the item before the current
  1.1770 +    return frameBefore;
  1.1771 +
  1.1772 +  // If we don't match anything, rollback the last typing
  1.1773 +  mIncrementalString.SetLength(mIncrementalString.Length() - 1);
  1.1774 +
  1.1775 +  // didn't find a matching menu item
  1.1776 +#ifdef XP_WIN
  1.1777 +  // behavior on Windows - this item is in a menu popup off of the
  1.1778 +  // menu bar, so beep and do nothing else
  1.1779 +  if (isMenu) {
  1.1780 +    nsCOMPtr<nsISound> soundInterface = do_CreateInstance("@mozilla.org/sound;1");
  1.1781 +    if (soundInterface)
  1.1782 +      soundInterface->Beep();
  1.1783 +  }
  1.1784 +#endif  // #ifdef XP_WIN
  1.1785 +
  1.1786 +  return nullptr;
  1.1787 +}
  1.1788 +
  1.1789 +void
  1.1790 +nsMenuPopupFrame::LockMenuUntilClosed(bool aLock)
  1.1791 +{
  1.1792 +  mIsMenuLocked = aLock;
  1.1793 +
  1.1794 +  // Lock / unlock the parent, too.
  1.1795 +  nsMenuFrame* menu = do_QueryFrame(GetParent());
  1.1796 +  if (menu) {
  1.1797 +    nsMenuParent* parentParent = menu->GetMenuParent();
  1.1798 +    if (parentParent) {
  1.1799 +      parentParent->LockMenuUntilClosed(aLock);
  1.1800 +    }
  1.1801 +  }
  1.1802 +}
  1.1803 +
  1.1804 +nsIWidget*
  1.1805 +nsMenuPopupFrame::GetWidget()
  1.1806 +{
  1.1807 +  nsView * view = GetRootViewForPopup(this);
  1.1808 +  if (!view)
  1.1809 +    return nullptr;
  1.1810 +
  1.1811 +  return view->GetWidget();
  1.1812 +}
  1.1813 +
  1.1814 +void
  1.1815 +nsMenuPopupFrame::AttachedDismissalListener()
  1.1816 +{
  1.1817 +  mConsumeRollupEvent = nsIPopupBoxObject::ROLLUP_DEFAULT;
  1.1818 +}
  1.1819 +
  1.1820 +// helpers /////////////////////////////////////////////////////////////
  1.1821 +
  1.1822 +nsresult 
  1.1823 +nsMenuPopupFrame::AttributeChanged(int32_t aNameSpaceID,
  1.1824 +                                   nsIAtom* aAttribute,
  1.1825 +                                   int32_t aModType)
  1.1826 +
  1.1827 +{
  1.1828 +  nsresult rv = nsBoxFrame::AttributeChanged(aNameSpaceID, aAttribute,
  1.1829 +                                             aModType);
  1.1830 +  
  1.1831 +  if (aAttribute == nsGkAtoms::left || aAttribute == nsGkAtoms::top)
  1.1832 +    MoveToAttributePosition();
  1.1833 +
  1.1834 +  if (aAttribute == nsGkAtoms::label) {
  1.1835 +    // set the label for the titlebar
  1.1836 +    nsView* view = GetView();
  1.1837 +    if (view) {
  1.1838 +      nsIWidget* widget = view->GetWidget();
  1.1839 +      if (widget) {
  1.1840 +        nsAutoString title;
  1.1841 +        mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::label, title);
  1.1842 +        if (!title.IsEmpty()) {
  1.1843 +          widget->SetTitle(title);
  1.1844 +        }
  1.1845 +      }
  1.1846 +    }
  1.1847 +  }
  1.1848 +
  1.1849 +  return rv;
  1.1850 +}
  1.1851 +
  1.1852 +void
  1.1853 +nsMenuPopupFrame::MoveToAttributePosition()
  1.1854 +{
  1.1855 +  // Move the widget around when the user sets the |left| and |top| attributes. 
  1.1856 +  // Note that this is not the best way to move the widget, as it results in lots
  1.1857 +  // of FE notifications and is likely to be slow as molasses. Use |moveTo| on
  1.1858 +  // nsIPopupBoxObject if possible. 
  1.1859 +  nsAutoString left, top;
  1.1860 +  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::left, left);
  1.1861 +  mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::top, top);
  1.1862 +  nsresult err1, err2;
  1.1863 +  int32_t xpos = left.ToInteger(&err1);
  1.1864 +  int32_t ypos = top.ToInteger(&err2);
  1.1865 +
  1.1866 +  if (NS_SUCCEEDED(err1) && NS_SUCCEEDED(err2))
  1.1867 +    MoveTo(xpos, ypos, false);
  1.1868 +}
  1.1869 +
  1.1870 +void
  1.1871 +nsMenuPopupFrame::DestroyFrom(nsIFrame* aDestructRoot)
  1.1872 +{
  1.1873 +  nsMenuFrame* menu = do_QueryFrame(GetParent());
  1.1874 +  if (menu) {
  1.1875 +    // clear the open attribute on the parent menu
  1.1876 +    nsContentUtils::AddScriptRunner(
  1.1877 +      new nsUnsetAttrRunnable(menu->GetContent(), nsGkAtoms::open));
  1.1878 +  }
  1.1879 +
  1.1880 +  nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
  1.1881 +  if (pm)
  1.1882 +    pm->PopupDestroyed(this);
  1.1883 +
  1.1884 +  nsIRootBox* rootBox =
  1.1885 +    nsIRootBox::GetRootBox(PresContext()->GetPresShell());
  1.1886 +  if (rootBox && rootBox->GetDefaultTooltip() == mContent) {
  1.1887 +    rootBox->SetDefaultTooltip(nullptr);
  1.1888 +  }
  1.1889 +
  1.1890 +  nsBoxFrame::DestroyFrom(aDestructRoot);
  1.1891 +}
  1.1892 +
  1.1893 +
  1.1894 +void
  1.1895 +nsMenuPopupFrame::MoveTo(int32_t aLeft, int32_t aTop, bool aUpdateAttrs)
  1.1896 +{
  1.1897 +  nsIWidget* widget = GetWidget();
  1.1898 +  if ((mScreenXPos == aLeft && mScreenYPos == aTop) &&
  1.1899 +      (!widget || widget->GetClientOffset() == mLastClientOffset)) {
  1.1900 +    return;
  1.1901 +  }
  1.1902 +
  1.1903 +  // reposition the popup at the specified coordinates. Don't clear the anchor
  1.1904 +  // and position, because the popup can be reset to its anchor position by
  1.1905 +  // using (-1, -1) as coordinates. Subtract off the margin as it will be
  1.1906 +  // added to the position when SetPopupPosition is called.
  1.1907 +  nsMargin margin(0, 0, 0, 0);
  1.1908 +  StyleMargin()->GetMargin(margin);
  1.1909 +
  1.1910 +  // Workaround for bug 788189.  See also bug 708278 comment #25 and following.
  1.1911 +  if (mAdjustOffsetForContextMenu) {
  1.1912 +    nscoord offsetForContextMenu =
  1.1913 +      nsPresContext::CSSPixelsToAppUnits(CONTEXT_MENU_OFFSET_PIXELS);
  1.1914 +    margin.left += offsetForContextMenu;
  1.1915 +    margin.top += offsetForContextMenu;
  1.1916 +  }
  1.1917 +
  1.1918 +  nsPresContext* presContext = PresContext();
  1.1919 +  mScreenXPos = aLeft - presContext->AppUnitsToIntCSSPixels(margin.left);
  1.1920 +  mScreenYPos = aTop - presContext->AppUnitsToIntCSSPixels(margin.top);
  1.1921 +
  1.1922 +  SetPopupPosition(nullptr, true, false);
  1.1923 +
  1.1924 +  nsCOMPtr<nsIContent> popup = mContent;
  1.1925 +  if (aUpdateAttrs && (popup->HasAttr(kNameSpaceID_None, nsGkAtoms::left) ||
  1.1926 +                       popup->HasAttr(kNameSpaceID_None, nsGkAtoms::top)))
  1.1927 +  {
  1.1928 +    nsAutoString left, top;
  1.1929 +    left.AppendInt(aLeft);
  1.1930 +    top.AppendInt(aTop);
  1.1931 +    popup->SetAttr(kNameSpaceID_None, nsGkAtoms::left, left, false);
  1.1932 +    popup->SetAttr(kNameSpaceID_None, nsGkAtoms::top, top, false);
  1.1933 +  }
  1.1934 +}
  1.1935 +
  1.1936 +void
  1.1937 +nsMenuPopupFrame::MoveToAnchor(nsIContent* aAnchorContent,
  1.1938 +                               const nsAString& aPosition,
  1.1939 +                               int32_t aXPos, int32_t aYPos,
  1.1940 +                               bool aAttributesOverride)
  1.1941 +{
  1.1942 +  NS_ASSERTION(mPopupState == ePopupOpenAndVisible, "popup must be open to move it");
  1.1943 +
  1.1944 +  InitializePopup(aAnchorContent, mTriggerContent, aPosition,
  1.1945 +                  aXPos, aYPos, aAttributesOverride);
  1.1946 +  // InitializePopup changed the state so reset it.
  1.1947 +  mPopupState = ePopupOpenAndVisible;
  1.1948 +
  1.1949 +  // Pass false here so that flipping and adjusting to fit on the screen happen.
  1.1950 +  SetPopupPosition(nullptr, false, false);
  1.1951 +}
  1.1952 +
  1.1953 +bool
  1.1954 +nsMenuPopupFrame::GetAutoPosition()
  1.1955 +{
  1.1956 +  return mShouldAutoPosition;
  1.1957 +}
  1.1958 +
  1.1959 +void
  1.1960 +nsMenuPopupFrame::SetAutoPosition(bool aShouldAutoPosition)
  1.1961 +{
  1.1962 +  mShouldAutoPosition = aShouldAutoPosition;
  1.1963 +}
  1.1964 +
  1.1965 +void
  1.1966 +nsMenuPopupFrame::SetConsumeRollupEvent(uint32_t aConsumeMode)
  1.1967 +{
  1.1968 +  mConsumeRollupEvent = aConsumeMode;
  1.1969 +}
  1.1970 +
  1.1971 +int8_t
  1.1972 +nsMenuPopupFrame::GetAlignmentPosition() const
  1.1973 +{
  1.1974 +  // The code below handles most cases of alignment, anchor and position values. Those that are
  1.1975 +  // not handled just return POPUPPOSITION_UNKNOWN.
  1.1976 +
  1.1977 +  if (mPosition == POPUPPOSITION_OVERLAP || mPosition == POPUPPOSITION_AFTERPOINTER)
  1.1978 +    return mPosition;
  1.1979 +
  1.1980 +  int8_t position = mPosition;
  1.1981 +
  1.1982 +  if (position == POPUPPOSITION_UNKNOWN) {
  1.1983 +    switch (mPopupAnchor) {
  1.1984 +      case POPUPALIGNMENT_BOTTOMCENTER:
  1.1985 +        position = mPopupAlignment == POPUPALIGNMENT_TOPRIGHT ?
  1.1986 +                     POPUPPOSITION_AFTEREND : POPUPPOSITION_AFTERSTART;
  1.1987 +        break;
  1.1988 +      case POPUPALIGNMENT_TOPCENTER:
  1.1989 +        position = mPopupAlignment == POPUPALIGNMENT_BOTTOMRIGHT ?
  1.1990 +                     POPUPPOSITION_BEFOREEND : POPUPPOSITION_BEFORESTART;
  1.1991 +        break;
  1.1992 +      case POPUPALIGNMENT_LEFTCENTER:
  1.1993 +        position = mPopupAlignment == POPUPALIGNMENT_BOTTOMRIGHT ?
  1.1994 +                     POPUPPOSITION_STARTAFTER : POPUPPOSITION_STARTBEFORE;
  1.1995 +        break;
  1.1996 +      case POPUPALIGNMENT_RIGHTCENTER:
  1.1997 +        position = mPopupAlignment == POPUPALIGNMENT_BOTTOMLEFT ?
  1.1998 +                     POPUPPOSITION_ENDAFTER : POPUPPOSITION_ENDBEFORE;
  1.1999 +        break;
  1.2000 +      default:
  1.2001 +        break;
  1.2002 +    }
  1.2003 +  }
  1.2004 +
  1.2005 +  if (mHFlip) {
  1.2006 +    position = POPUPPOSITION_HFLIP(position);
  1.2007 +  }
  1.2008 +
  1.2009 +  if (mVFlip) {
  1.2010 +    position = POPUPPOSITION_VFLIP(position);
  1.2011 +  }
  1.2012 +
  1.2013 +  return position;
  1.2014 +}
  1.2015 +
  1.2016 +/**
  1.2017 + * KEEP THIS IN SYNC WITH nsContainerFrame::CreateViewForFrame
  1.2018 + * as much as possible. Until we get rid of views finally...
  1.2019 + */
  1.2020 +void
  1.2021 +nsMenuPopupFrame::CreatePopupView()
  1.2022 +{
  1.2023 +  if (HasView()) {
  1.2024 +    return;
  1.2025 +  }
  1.2026 +
  1.2027 +  nsViewManager* viewManager = PresContext()->GetPresShell()->GetViewManager();
  1.2028 +  NS_ASSERTION(nullptr != viewManager, "null view manager");
  1.2029 +
  1.2030 +  // Create a view
  1.2031 +  nsView* parentView = viewManager->GetRootView();
  1.2032 +  nsViewVisibility visibility = nsViewVisibility_kHide;
  1.2033 +  int32_t zIndex = INT32_MAX;
  1.2034 +  bool    autoZIndex = false;
  1.2035 +
  1.2036 +  NS_ASSERTION(parentView, "no parent view");
  1.2037 +
  1.2038 +  // Create a view
  1.2039 +  nsView *view = viewManager->CreateView(GetRect(), parentView, visibility);
  1.2040 +  viewManager->SetViewZIndex(view, autoZIndex, zIndex);
  1.2041 +  // XXX put view last in document order until we can do better
  1.2042 +  viewManager->InsertChild(parentView, view, nullptr, true);
  1.2043 +
  1.2044 +  // Remember our view
  1.2045 +  SetView(view);
  1.2046 +
  1.2047 +  NS_FRAME_LOG(NS_FRAME_TRACE_CALLS,
  1.2048 +    ("nsMenuPopupFrame::CreatePopupView: frame=%p view=%p", this, view));
  1.2049 +}

mercurial