nsXULPopupManager.cpp 95 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843
  1. /* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
  2. /* This Source Code Form is subject to the terms of the Mozilla Public
  3. * License, v. 2.0. If a copy of the MPL was not distributed with this
  4. * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
  5. #include "nsGkAtoms.h"
  6. #include "nsXULPopupManager.h"
  7. #include "nsMenuFrame.h"
  8. #include "nsMenuPopupFrame.h"
  9. #include "nsMenuBarFrame.h"
  10. #include "nsMenuBarListener.h"
  11. #include "nsContentUtils.h"
  12. #include "nsIDOMDocument.h"
  13. #include "nsIDOMEvent.h"
  14. #include "nsIDOMXULElement.h"
  15. #include "nsIDOMXULMenuListElement.h"
  16. #include "nsIXULDocument.h"
  17. #include "nsIXULTemplateBuilder.h"
  18. #include "nsCSSFrameConstructor.h"
  19. #include "nsGlobalWindow.h"
  20. #include "nsLayoutUtils.h"
  21. #include "nsViewManager.h"
  22. #include "nsIComponentManager.h"
  23. #include "nsITimer.h"
  24. #include "nsFocusManager.h"
  25. #include "nsIDocShell.h"
  26. #include "nsPIDOMWindow.h"
  27. #include "nsIInterfaceRequestorUtils.h"
  28. #include "nsIBaseWindow.h"
  29. #include "nsIDOMKeyEvent.h"
  30. #include "nsIDOMMouseEvent.h"
  31. #include "nsCaret.h"
  32. #include "nsIDocument.h"
  33. #include "nsPIWindowRoot.h"
  34. #include "nsFrameManager.h"
  35. #include "nsIObserverService.h"
  36. #include "mozilla/dom/Element.h"
  37. #include "mozilla/dom/Event.h" // for nsIDOMEvent::InternalDOMEvent()
  38. #include "mozilla/EventDispatcher.h"
  39. #include "mozilla/EventStateManager.h"
  40. #include "mozilla/LookAndFeel.h"
  41. #include "mozilla/MouseEvents.h"
  42. #include "mozilla/Services.h"
  43. using namespace mozilla;
  44. using namespace mozilla::dom;
  45. static_assert(nsIDOMKeyEvent::DOM_VK_HOME == nsIDOMKeyEvent::DOM_VK_END + 1 &&
  46. nsIDOMKeyEvent::DOM_VK_LEFT == nsIDOMKeyEvent::DOM_VK_END + 2 &&
  47. nsIDOMKeyEvent::DOM_VK_UP == nsIDOMKeyEvent::DOM_VK_END + 3 &&
  48. nsIDOMKeyEvent::DOM_VK_RIGHT == nsIDOMKeyEvent::DOM_VK_END + 4 &&
  49. nsIDOMKeyEvent::DOM_VK_DOWN == nsIDOMKeyEvent::DOM_VK_END + 5,
  50. "nsXULPopupManager assumes some keyCode values are consecutive");
  51. const nsNavigationDirection DirectionFromKeyCodeTable[2][6] = {
  52. {
  53. eNavigationDirection_Last, // nsIDOMKeyEvent::DOM_VK_END
  54. eNavigationDirection_First, // nsIDOMKeyEvent::DOM_VK_HOME
  55. eNavigationDirection_Start, // nsIDOMKeyEvent::DOM_VK_LEFT
  56. eNavigationDirection_Before, // nsIDOMKeyEvent::DOM_VK_UP
  57. eNavigationDirection_End, // nsIDOMKeyEvent::DOM_VK_RIGHT
  58. eNavigationDirection_After // nsIDOMKeyEvent::DOM_VK_DOWN
  59. },
  60. {
  61. eNavigationDirection_Last, // nsIDOMKeyEvent::DOM_VK_END
  62. eNavigationDirection_First, // nsIDOMKeyEvent::DOM_VK_HOME
  63. eNavigationDirection_End, // nsIDOMKeyEvent::DOM_VK_LEFT
  64. eNavigationDirection_Before, // nsIDOMKeyEvent::DOM_VK_UP
  65. eNavigationDirection_Start, // nsIDOMKeyEvent::DOM_VK_RIGHT
  66. eNavigationDirection_After // nsIDOMKeyEvent::DOM_VK_DOWN
  67. }
  68. };
  69. nsXULPopupManager* nsXULPopupManager::sInstance = nullptr;
  70. nsIContent* nsMenuChainItem::Content()
  71. {
  72. return mFrame->GetContent();
  73. }
  74. void nsMenuChainItem::SetParent(nsMenuChainItem* aParent)
  75. {
  76. if (mParent) {
  77. NS_ASSERTION(mParent->mChild == this, "Unexpected - parent's child not set to this");
  78. mParent->mChild = nullptr;
  79. }
  80. mParent = aParent;
  81. if (mParent) {
  82. if (mParent->mChild)
  83. mParent->mChild->mParent = nullptr;
  84. mParent->mChild = this;
  85. }
  86. }
  87. void nsMenuChainItem::Detach(nsMenuChainItem** aRoot)
  88. {
  89. // If the item has a child, set the child's parent to this item's parent,
  90. // effectively removing the item from the chain. If the item has no child,
  91. // just set the parent to null.
  92. if (mChild) {
  93. NS_ASSERTION(this != *aRoot, "Unexpected - popup with child at end of chain");
  94. mChild->SetParent(mParent);
  95. }
  96. else {
  97. // An item without a child should be the first item in the chain, so set
  98. // the first item pointer, pointed to by aRoot, to the parent.
  99. NS_ASSERTION(this == *aRoot, "Unexpected - popup with no child not at end of chain");
  100. *aRoot = mParent;
  101. SetParent(nullptr);
  102. }
  103. }
  104. bool nsXULPopupManager::sDevtoolsDisableAutoHide = false;
  105. const char* kPrefDevtoolsDisableAutoHide =
  106. "ui.popup.disable_autohide";
  107. NS_IMPL_ISUPPORTS(nsXULPopupManager,
  108. nsIDOMEventListener,
  109. nsITimerCallback,
  110. nsIObserver)
  111. nsXULPopupManager::nsXULPopupManager() :
  112. mRangeOffset(0),
  113. mCachedMousePoint(0, 0),
  114. mCachedModifiers(0),
  115. mActiveMenuBar(nullptr),
  116. mPopups(nullptr),
  117. mNoHidePanels(nullptr),
  118. mTimerMenu(nullptr)
  119. {
  120. nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
  121. if (obs) {
  122. obs->AddObserver(this, "xpcom-shutdown", false);
  123. }
  124. Preferences::AddBoolVarCache(&sDevtoolsDisableAutoHide,
  125. kPrefDevtoolsDisableAutoHide, false);
  126. }
  127. nsXULPopupManager::~nsXULPopupManager()
  128. {
  129. NS_ASSERTION(!mPopups && !mNoHidePanels, "XUL popups still open");
  130. }
  131. nsresult
  132. nsXULPopupManager::Init()
  133. {
  134. sInstance = new nsXULPopupManager();
  135. NS_ENSURE_TRUE(sInstance, NS_ERROR_OUT_OF_MEMORY);
  136. NS_ADDREF(sInstance);
  137. return NS_OK;
  138. }
  139. void
  140. nsXULPopupManager::Shutdown()
  141. {
  142. NS_IF_RELEASE(sInstance);
  143. }
  144. NS_IMETHODIMP
  145. nsXULPopupManager::Observe(nsISupports *aSubject,
  146. const char *aTopic,
  147. const char16_t *aData)
  148. {
  149. if (!nsCRT::strcmp(aTopic, "xpcom-shutdown")) {
  150. if (mKeyListener) {
  151. mKeyListener->RemoveEventListener(NS_LITERAL_STRING("keypress"), this, true);
  152. mKeyListener->RemoveEventListener(NS_LITERAL_STRING("keydown"), this, true);
  153. mKeyListener->RemoveEventListener(NS_LITERAL_STRING("keyup"), this, true);
  154. mKeyListener = nullptr;
  155. }
  156. mRangeParent = nullptr;
  157. // mOpeningPopup is cleared explicitly soon after using it.
  158. nsCOMPtr<nsIObserverService> obs = mozilla::services::GetObserverService();
  159. if (obs) {
  160. obs->RemoveObserver(this, "xpcom-shutdown");
  161. }
  162. }
  163. return NS_OK;
  164. }
  165. nsXULPopupManager*
  166. nsXULPopupManager::GetInstance()
  167. {
  168. MOZ_ASSERT(sInstance);
  169. return sInstance;
  170. }
  171. bool
  172. nsXULPopupManager::Rollup(uint32_t aCount, bool aFlush,
  173. const nsIntPoint* pos, nsIContent** aLastRolledUp)
  174. {
  175. // We can disable the autohide behavior via a pref to ease debugging.
  176. if (nsXULPopupManager::sDevtoolsDisableAutoHide) {
  177. // Required on linux to allow events to work on other targets.
  178. if (mWidget) {
  179. mWidget->CaptureRollupEvents(nullptr, false);
  180. }
  181. return false;
  182. }
  183. bool consume = false;
  184. nsMenuChainItem* item = GetTopVisibleMenu();
  185. if (item) {
  186. if (aLastRolledUp) {
  187. // We need to get the popup that will be closed last, so that widget can
  188. // keep track of it so it doesn't reopen if a mousedown event is going to
  189. // processed. Keep going up the menu chain to get the first level menu of
  190. // the same type. If a different type is encountered it means we have,
  191. // for example, a menulist or context menu inside a panel, and we want to
  192. // treat these as distinct. It's possible that this menu doesn't end up
  193. // closing because the popuphiding event was cancelled, but in that case
  194. // we don't need to deal with the menu reopening as it will already still
  195. // be open.
  196. nsMenuChainItem* first = item;
  197. while (first->GetParent()) {
  198. nsMenuChainItem* parent = first->GetParent();
  199. if (first->Frame()->PopupType() != parent->Frame()->PopupType() ||
  200. first->IsContextMenu() != parent->IsContextMenu()) {
  201. break;
  202. }
  203. first = parent;
  204. }
  205. *aLastRolledUp = first->Content();
  206. }
  207. ConsumeOutsideClicksResult consumeResult = item->Frame()->ConsumeOutsideClicks();
  208. consume = (consumeResult == ConsumeOutsideClicks_True);
  209. bool rollup = true;
  210. // If norolluponanchor is true, then don't rollup when clicking the anchor.
  211. // This would be used to allow adjusting the caret position in an
  212. // autocomplete field without hiding the popup for example.
  213. bool noRollupOnAnchor = (!consume && pos &&
  214. item->Frame()->GetContent()->AttrValueIs(kNameSpaceID_None,
  215. nsGkAtoms::norolluponanchor, nsGkAtoms::_true, eCaseMatters));
  216. // When ConsumeOutsideClicks_ParentOnly is used, always consume the click
  217. // when the click was over the anchor. This way, clicking on a menu doesn't
  218. // reopen the menu.
  219. if ((consumeResult == ConsumeOutsideClicks_ParentOnly || noRollupOnAnchor) && pos) {
  220. nsMenuPopupFrame* popupFrame = item->Frame();
  221. nsIntRect anchorRect;
  222. if (popupFrame->IsAnchored()) {
  223. // Check if the popup has a screen anchor rectangle. If not, get the rectangle
  224. // from the anchor element.
  225. anchorRect = popupFrame->GetScreenAnchorRect();
  226. if (anchorRect.x == -1 || anchorRect.y == -1) {
  227. nsCOMPtr<nsIContent> anchor = popupFrame->GetAnchor();
  228. // Check if the anchor has indicated another node to use for checking
  229. // for roll-up. That way, we can anchor a popup on anonymous content or
  230. // an individual icon, while clicking elsewhere within a button or other
  231. // container doesn't result in us re-opening the popup.
  232. if (anchor) {
  233. nsAutoString consumeAnchor;
  234. anchor->GetAttr(kNameSpaceID_None, nsGkAtoms::consumeanchor,
  235. consumeAnchor);
  236. if (!consumeAnchor.IsEmpty()) {
  237. nsIDocument* doc = anchor->GetOwnerDocument();
  238. nsIContent* newAnchor = doc->GetElementById(consumeAnchor);
  239. if (newAnchor) {
  240. anchor = newAnchor;
  241. }
  242. }
  243. }
  244. if (anchor && anchor->GetPrimaryFrame()) {
  245. anchorRect = anchor->GetPrimaryFrame()->GetScreenRect();
  246. }
  247. }
  248. }
  249. // It's possible that some other element is above the anchor at the same
  250. // position, but the only thing that would happen is that the mouse
  251. // event will get consumed, so here only a quick coordinates check is
  252. // done rather than a slower complete check of what is at that location.
  253. nsPresContext* presContext = item->Frame()->PresContext();
  254. nsIntPoint posCSSPixels(presContext->DevPixelsToIntCSSPixels(pos->x),
  255. presContext->DevPixelsToIntCSSPixels(pos->y));
  256. if (anchorRect.Contains(posCSSPixels)) {
  257. if (consumeResult == ConsumeOutsideClicks_ParentOnly) {
  258. consume = true;
  259. }
  260. if (noRollupOnAnchor) {
  261. rollup = false;
  262. }
  263. }
  264. }
  265. if (rollup) {
  266. // if a number of popups to close has been specified, determine the last
  267. // popup to close
  268. nsIContent* lastPopup = nullptr;
  269. if (aCount != UINT32_MAX) {
  270. nsMenuChainItem* last = item;
  271. while (--aCount && last->GetParent()) {
  272. last = last->GetParent();
  273. }
  274. if (last) {
  275. lastPopup = last->Content();
  276. }
  277. }
  278. nsPresContext* presContext = item->Frame()->PresContext();
  279. RefPtr<nsViewManager> viewManager = presContext->PresShell()->GetViewManager();
  280. HidePopup(item->Content(), true, true, false, true, lastPopup);
  281. if (aFlush) {
  282. // The popup's visibility doesn't update until the minimize animation has
  283. // finished, so call UpdateWidgetGeometry to update it right away.
  284. viewManager->UpdateWidgetGeometry();
  285. }
  286. }
  287. }
  288. return consume;
  289. }
  290. ////////////////////////////////////////////////////////////////////////
  291. bool nsXULPopupManager::ShouldRollupOnMouseWheelEvent()
  292. {
  293. // should rollup only for autocomplete widgets
  294. // XXXndeakin this should really be something the popup has more control over
  295. nsMenuChainItem* item = GetTopVisibleMenu();
  296. if (!item)
  297. return false;
  298. nsIContent* content = item->Frame()->GetContent();
  299. if (!content)
  300. return false;
  301. if (content->AttrValueIs(kNameSpaceID_None, nsGkAtoms::rolluponmousewheel,
  302. nsGkAtoms::_true, eCaseMatters))
  303. return true;
  304. if (content->AttrValueIs(kNameSpaceID_None, nsGkAtoms::rolluponmousewheel,
  305. nsGkAtoms::_false, eCaseMatters))
  306. return false;
  307. nsAutoString value;
  308. content->GetAttr(kNameSpaceID_None, nsGkAtoms::type, value);
  309. return StringBeginsWith(value, NS_LITERAL_STRING("autocomplete"));
  310. }
  311. bool nsXULPopupManager::ShouldConsumeOnMouseWheelEvent()
  312. {
  313. nsMenuChainItem* item = GetTopVisibleMenu();
  314. if (!item)
  315. return false;
  316. nsMenuPopupFrame* frame = item->Frame();
  317. if (frame->PopupType() != ePopupTypePanel)
  318. return true;
  319. nsIContent* content = frame->GetContent();
  320. return !(content && content->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
  321. nsGkAtoms::arrow, eCaseMatters));
  322. }
  323. // a menu should not roll up if activated by a mouse activate message (eg. X-mouse)
  324. bool nsXULPopupManager::ShouldRollupOnMouseActivate()
  325. {
  326. return false;
  327. }
  328. uint32_t
  329. nsXULPopupManager::GetSubmenuWidgetChain(nsTArray<nsIWidget*> *aWidgetChain)
  330. {
  331. // this method is used by the widget code to determine the list of popups
  332. // that are open. If a mouse click occurs outside one of these popups, the
  333. // panels will roll up. If the click is inside a popup, they will not roll up
  334. uint32_t count = 0, sameTypeCount = 0;
  335. NS_ASSERTION(aWidgetChain, "null parameter");
  336. nsMenuChainItem* item = GetTopVisibleMenu();
  337. while (item) {
  338. nsCOMPtr<nsIWidget> widget = item->Frame()->GetWidget();
  339. NS_ASSERTION(widget, "open popup has no widget");
  340. aWidgetChain->AppendElement(widget.get());
  341. // In the case when a menulist inside a panel is open, clicking in the
  342. // panel should still roll up the menu, so if a different type is found,
  343. // stop scanning.
  344. nsMenuChainItem* parent = item->GetParent();
  345. if (!sameTypeCount) {
  346. count++;
  347. if (!parent || item->Frame()->PopupType() != parent->Frame()->PopupType() ||
  348. item->IsContextMenu() != parent->IsContextMenu()) {
  349. sameTypeCount = count;
  350. }
  351. }
  352. item = parent;
  353. }
  354. return sameTypeCount;
  355. }
  356. nsIWidget*
  357. nsXULPopupManager::GetRollupWidget()
  358. {
  359. nsMenuChainItem* item = GetTopVisibleMenu();
  360. return item ? item->Frame()->GetWidget() : nullptr;
  361. }
  362. void
  363. nsXULPopupManager::AdjustPopupsOnWindowChange(nsPIDOMWindowOuter* aWindow)
  364. {
  365. // When the parent window is moved, adjust any child popups. Dismissable
  366. // menus and panels are expected to roll up when a window is moved, so there
  367. // is no need to check these popups, only the noautohide popups.
  368. // The items are added to a list so that they can be adjusted bottom to top.
  369. nsTArray<nsMenuPopupFrame *> list;
  370. nsMenuChainItem* item = mNoHidePanels;
  371. while (item) {
  372. // only move popups that are within the same window and where auto
  373. // positioning has not been disabled
  374. nsMenuPopupFrame* frame = item->Frame();
  375. if (frame->GetAutoPosition()) {
  376. nsIContent* popup = frame->GetContent();
  377. if (popup) {
  378. nsIDocument* document = popup->GetUncomposedDoc();
  379. if (document) {
  380. if (nsPIDOMWindowOuter* window = document->GetWindow()) {
  381. window = window->GetPrivateRoot();
  382. if (window == aWindow) {
  383. list.AppendElement(frame);
  384. }
  385. }
  386. }
  387. }
  388. }
  389. item = item->GetParent();
  390. }
  391. for (int32_t l = list.Length() - 1; l >= 0; l--) {
  392. list[l]->SetPopupPosition(nullptr, true, false, true);
  393. }
  394. }
  395. void nsXULPopupManager::AdjustPopupsOnWindowChange(nsIPresShell* aPresShell)
  396. {
  397. if (aPresShell->GetDocument()) {
  398. AdjustPopupsOnWindowChange(aPresShell->GetDocument()->GetWindow());
  399. }
  400. }
  401. static
  402. nsMenuPopupFrame* GetPopupToMoveOrResize(nsIFrame* aFrame)
  403. {
  404. nsMenuPopupFrame* menuPopupFrame = do_QueryFrame(aFrame);
  405. if (!menuPopupFrame)
  406. return nullptr;
  407. // no point moving or resizing hidden popups
  408. if (!menuPopupFrame->IsVisible())
  409. return nullptr;
  410. nsIWidget* widget = menuPopupFrame->GetWidget();
  411. if (widget && !widget->IsVisible())
  412. return nullptr;
  413. return menuPopupFrame;
  414. }
  415. void
  416. nsXULPopupManager::PopupMoved(nsIFrame* aFrame, nsIntPoint aPnt)
  417. {
  418. nsMenuPopupFrame* menuPopupFrame = GetPopupToMoveOrResize(aFrame);
  419. if (!menuPopupFrame)
  420. return;
  421. nsView* view = menuPopupFrame->GetView();
  422. if (!view)
  423. return;
  424. // Don't do anything if the popup is already at the specified location. This
  425. // prevents recursive calls when a popup is positioned.
  426. LayoutDeviceIntRect curDevSize = view->CalcWidgetBounds(eWindowType_popup);
  427. nsIWidget* widget = menuPopupFrame->GetWidget();
  428. if (curDevSize.x == aPnt.x && curDevSize.y == aPnt.y &&
  429. (!widget || widget->GetClientOffset() ==
  430. menuPopupFrame->GetLastClientOffset())) {
  431. return;
  432. }
  433. // Update the popup's position using SetPopupPosition if the popup is
  434. // anchored and at the parent level as these maintain their position
  435. // relative to the parent window. Otherwise, just update the popup to
  436. // the specified screen coordinates.
  437. if (menuPopupFrame->IsAnchored() &&
  438. menuPopupFrame->PopupLevel() == ePopupLevelParent) {
  439. menuPopupFrame->SetPopupPosition(nullptr, true, false, true);
  440. }
  441. else {
  442. CSSPoint cssPos = LayoutDeviceIntPoint::FromUnknownPoint(aPnt)
  443. / menuPopupFrame->PresContext()->CSSToDevPixelScale();
  444. menuPopupFrame->MoveTo(RoundedToInt(cssPos), false);
  445. }
  446. }
  447. void
  448. nsXULPopupManager::PopupResized(nsIFrame* aFrame, LayoutDeviceIntSize aSize)
  449. {
  450. nsMenuPopupFrame* menuPopupFrame = GetPopupToMoveOrResize(aFrame);
  451. if (!menuPopupFrame)
  452. return;
  453. nsView* view = menuPopupFrame->GetView();
  454. if (!view)
  455. return;
  456. LayoutDeviceIntRect curDevSize = view->CalcWidgetBounds(eWindowType_popup);
  457. // If the size is what we think it is, we have nothing to do.
  458. if (curDevSize.width == aSize.width && curDevSize.height == aSize.height)
  459. return;
  460. nsIContent* popup = menuPopupFrame->GetContent();
  461. // Only set the width and height if the popup already has these attributes.
  462. if (!popup->HasAttr(kNameSpaceID_None, nsGkAtoms::width) ||
  463. !popup->HasAttr(kNameSpaceID_None, nsGkAtoms::height)) {
  464. return;
  465. }
  466. // The size is different. Convert the actual size to css pixels and store it
  467. // as 'width' and 'height' attributes on the popup.
  468. nsPresContext* presContext = menuPopupFrame->PresContext();
  469. CSSIntSize newCSS(presContext->DevPixelsToIntCSSPixels(aSize.width),
  470. presContext->DevPixelsToIntCSSPixels(aSize.height));
  471. nsAutoString width, height;
  472. width.AppendInt(newCSS.width);
  473. height.AppendInt(newCSS.height);
  474. popup->SetAttr(kNameSpaceID_None, nsGkAtoms::width, width, false);
  475. popup->SetAttr(kNameSpaceID_None, nsGkAtoms::height, height, true);
  476. }
  477. nsMenuPopupFrame*
  478. nsXULPopupManager::GetPopupFrameForContent(nsIContent* aContent, bool aShouldFlush)
  479. {
  480. if (aShouldFlush) {
  481. nsIDocument *document = aContent->GetUncomposedDoc();
  482. if (document) {
  483. nsCOMPtr<nsIPresShell> presShell = document->GetShell();
  484. if (presShell)
  485. presShell->FlushPendingNotifications(Flush_Layout);
  486. }
  487. }
  488. return do_QueryFrame(aContent->GetPrimaryFrame());
  489. }
  490. nsMenuChainItem*
  491. nsXULPopupManager::GetTopVisibleMenu()
  492. {
  493. nsMenuChainItem* item = mPopups;
  494. while (item && item->Frame()->PopupState() == ePopupInvisible)
  495. item = item->GetParent();
  496. return item;
  497. }
  498. void
  499. nsXULPopupManager::GetMouseLocation(nsIDOMNode** aNode, int32_t* aOffset)
  500. {
  501. *aNode = mRangeParent;
  502. NS_IF_ADDREF(*aNode);
  503. *aOffset = mRangeOffset;
  504. }
  505. void
  506. nsXULPopupManager::InitTriggerEvent(nsIDOMEvent* aEvent, nsIContent* aPopup,
  507. nsIContent** aTriggerContent)
  508. {
  509. mCachedMousePoint = LayoutDeviceIntPoint(0, 0);
  510. if (aTriggerContent) {
  511. *aTriggerContent = nullptr;
  512. if (aEvent) {
  513. // get the trigger content from the event
  514. nsCOMPtr<nsIContent> target = do_QueryInterface(
  515. aEvent->InternalDOMEvent()->GetTarget());
  516. target.forget(aTriggerContent);
  517. }
  518. }
  519. mCachedModifiers = 0;
  520. nsCOMPtr<nsIDOMUIEvent> uiEvent = do_QueryInterface(aEvent);
  521. if (uiEvent) {
  522. uiEvent->GetRangeParent(getter_AddRefs(mRangeParent));
  523. uiEvent->GetRangeOffset(&mRangeOffset);
  524. // get the event coordinates relative to the root frame of the document
  525. // containing the popup.
  526. NS_ASSERTION(aPopup, "Expected a popup node");
  527. WidgetEvent* event = aEvent->WidgetEventPtr();
  528. if (event) {
  529. WidgetInputEvent* inputEvent = event->AsInputEvent();
  530. if (inputEvent) {
  531. mCachedModifiers = inputEvent->mModifiers;
  532. }
  533. nsIDocument* doc = aPopup->GetUncomposedDoc();
  534. if (doc) {
  535. nsIPresShell* presShell = doc->GetShell();
  536. nsPresContext* presContext;
  537. if (presShell && (presContext = presShell->GetPresContext())) {
  538. nsPresContext* rootDocPresContext =
  539. presContext->GetRootPresContext();
  540. if (!rootDocPresContext)
  541. return;
  542. nsIFrame* rootDocumentRootFrame = rootDocPresContext->
  543. PresShell()->FrameManager()->GetRootFrame();
  544. if ((event->mClass == eMouseEventClass ||
  545. event->mClass == eMouseScrollEventClass ||
  546. event->mClass == eWheelEventClass) &&
  547. !event->AsGUIEvent()->mWidget) {
  548. // no widget, so just use the client point if available
  549. nsCOMPtr<nsIDOMMouseEvent> mouseEvent = do_QueryInterface(aEvent);
  550. nsIntPoint clientPt;
  551. mouseEvent->GetClientX(&clientPt.x);
  552. mouseEvent->GetClientY(&clientPt.y);
  553. // XXX this doesn't handle IFRAMEs in transforms
  554. nsPoint thisDocToRootDocOffset = presShell->FrameManager()->
  555. GetRootFrame()->GetOffsetToCrossDoc(rootDocumentRootFrame);
  556. // convert to device pixels
  557. mCachedMousePoint.x = presContext->AppUnitsToDevPixels(
  558. nsPresContext::CSSPixelsToAppUnits(clientPt.x) + thisDocToRootDocOffset.x);
  559. mCachedMousePoint.y = presContext->AppUnitsToDevPixels(
  560. nsPresContext::CSSPixelsToAppUnits(clientPt.y) + thisDocToRootDocOffset.y);
  561. }
  562. else if (rootDocumentRootFrame) {
  563. nsPoint pnt =
  564. nsLayoutUtils::GetEventCoordinatesRelativeTo(event, rootDocumentRootFrame);
  565. mCachedMousePoint = LayoutDeviceIntPoint(rootDocPresContext->AppUnitsToDevPixels(pnt.x),
  566. rootDocPresContext->AppUnitsToDevPixels(pnt.y));
  567. }
  568. }
  569. }
  570. }
  571. }
  572. else {
  573. mRangeParent = nullptr;
  574. mRangeOffset = 0;
  575. }
  576. }
  577. void
  578. nsXULPopupManager::SetActiveMenuBar(nsMenuBarFrame* aMenuBar, bool aActivate)
  579. {
  580. if (aActivate)
  581. mActiveMenuBar = aMenuBar;
  582. else if (mActiveMenuBar == aMenuBar)
  583. mActiveMenuBar = nullptr;
  584. UpdateKeyboardListeners();
  585. }
  586. void
  587. nsXULPopupManager::ShowMenu(nsIContent *aMenu,
  588. bool aSelectFirstItem,
  589. bool aAsynchronous)
  590. {
  591. // generate any template content first. Otherwise, the menupopup may not
  592. // have been created yet.
  593. if (aMenu) {
  594. nsIContent* element = aMenu;
  595. do {
  596. nsCOMPtr<nsIDOMXULElement> xulelem = do_QueryInterface(element);
  597. if (xulelem) {
  598. nsCOMPtr<nsIXULTemplateBuilder> builder;
  599. xulelem->GetBuilder(getter_AddRefs(builder));
  600. if (builder) {
  601. builder->CreateContents(aMenu, true);
  602. break;
  603. }
  604. }
  605. element = element->GetParent();
  606. } while (element);
  607. }
  608. nsMenuFrame* menuFrame = do_QueryFrame(aMenu->GetPrimaryFrame());
  609. if (!menuFrame || !menuFrame->IsMenu())
  610. return;
  611. nsMenuPopupFrame* popupFrame = menuFrame->GetPopup();
  612. if (!popupFrame || !MayShowPopup(popupFrame))
  613. return;
  614. // inherit whether or not we're a context menu from the parent
  615. bool parentIsContextMenu = false;
  616. bool onMenuBar = false;
  617. bool onmenu = menuFrame->IsOnMenu();
  618. nsMenuParent* parent = menuFrame->GetMenuParent();
  619. if (parent && onmenu) {
  620. parentIsContextMenu = parent->IsContextMenu();
  621. onMenuBar = parent->IsMenuBar();
  622. }
  623. nsAutoString position;
  624. if (onMenuBar || !onmenu)
  625. position.AssignLiteral("after_start");
  626. else
  627. position.AssignLiteral("end_before");
  628. // there is no trigger event for menus
  629. InitTriggerEvent(nullptr, nullptr, nullptr);
  630. popupFrame->InitializePopup(menuFrame->GetAnchor(), nullptr, position, 0, 0,
  631. MenuPopupAnchorType_Node, true);
  632. if (aAsynchronous) {
  633. nsCOMPtr<nsIRunnable> event =
  634. new nsXULPopupShowingEvent(popupFrame->GetContent(),
  635. parentIsContextMenu, aSelectFirstItem);
  636. NS_DispatchToCurrentThread(event);
  637. }
  638. else {
  639. nsCOMPtr<nsIContent> popupContent = popupFrame->GetContent();
  640. FirePopupShowingEvent(popupContent, parentIsContextMenu, aSelectFirstItem);
  641. }
  642. }
  643. void
  644. nsXULPopupManager::ShowPopup(nsIContent* aPopup,
  645. nsIContent* aAnchorContent,
  646. const nsAString& aPosition,
  647. int32_t aXPos, int32_t aYPos,
  648. bool aIsContextMenu,
  649. bool aAttributesOverride,
  650. bool aSelectFirstItem,
  651. nsIDOMEvent* aTriggerEvent)
  652. {
  653. nsMenuPopupFrame* popupFrame = GetPopupFrameForContent(aPopup, true);
  654. if (!popupFrame || !MayShowPopup(popupFrame))
  655. return;
  656. nsCOMPtr<nsIContent> triggerContent;
  657. InitTriggerEvent(aTriggerEvent, aPopup, getter_AddRefs(triggerContent));
  658. popupFrame->InitializePopup(aAnchorContent, triggerContent, aPosition,
  659. aXPos, aYPos, MenuPopupAnchorType_Node, aAttributesOverride);
  660. FirePopupShowingEvent(aPopup, aIsContextMenu, aSelectFirstItem);
  661. }
  662. void
  663. nsXULPopupManager::ShowPopupAtScreen(nsIContent* aPopup,
  664. int32_t aXPos, int32_t aYPos,
  665. bool aIsContextMenu,
  666. nsIDOMEvent* aTriggerEvent)
  667. {
  668. nsMenuPopupFrame* popupFrame = GetPopupFrameForContent(aPopup, true);
  669. if (!popupFrame || !MayShowPopup(popupFrame))
  670. return;
  671. nsCOMPtr<nsIContent> triggerContent;
  672. InitTriggerEvent(aTriggerEvent, aPopup, getter_AddRefs(triggerContent));
  673. popupFrame->InitializePopupAtScreen(triggerContent, aXPos, aYPos, aIsContextMenu);
  674. FirePopupShowingEvent(aPopup, aIsContextMenu, false);
  675. }
  676. void
  677. nsXULPopupManager::ShowPopupAtScreenRect(nsIContent* aPopup,
  678. const nsAString& aPosition,
  679. const nsIntRect& aRect,
  680. bool aIsContextMenu,
  681. bool aAttributesOverride,
  682. nsIDOMEvent* aTriggerEvent)
  683. {
  684. nsMenuPopupFrame* popupFrame = GetPopupFrameForContent(aPopup, true);
  685. if (!popupFrame || !MayShowPopup(popupFrame))
  686. return;
  687. nsCOMPtr<nsIContent> triggerContent;
  688. InitTriggerEvent(aTriggerEvent, aPopup, getter_AddRefs(triggerContent));
  689. popupFrame->InitializePopupAtRect(triggerContent, aPosition,
  690. aRect, aAttributesOverride);
  691. FirePopupShowingEvent(aPopup, aIsContextMenu, false);
  692. }
  693. void
  694. nsXULPopupManager::ShowTooltipAtScreen(nsIContent* aPopup,
  695. nsIContent* aTriggerContent,
  696. int32_t aXPos, int32_t aYPos)
  697. {
  698. nsMenuPopupFrame* popupFrame = GetPopupFrameForContent(aPopup, true);
  699. if (!popupFrame || !MayShowPopup(popupFrame))
  700. return;
  701. InitTriggerEvent(nullptr, nullptr, nullptr);
  702. nsPresContext* pc = popupFrame->PresContext();
  703. mCachedMousePoint = LayoutDeviceIntPoint(pc->CSSPixelsToDevPixels(aXPos),
  704. pc->CSSPixelsToDevPixels(aYPos));
  705. // coordinates are relative to the root widget
  706. nsPresContext* rootPresContext = pc->GetRootPresContext();
  707. if (rootPresContext) {
  708. nsIWidget *rootWidget = rootPresContext->GetRootWidget();
  709. if (rootWidget) {
  710. mCachedMousePoint -= rootWidget->WidgetToScreenOffset();
  711. }
  712. }
  713. popupFrame->InitializePopupAtScreen(aTriggerContent, aXPos, aYPos, false);
  714. FirePopupShowingEvent(aPopup, false, false);
  715. }
  716. void
  717. nsXULPopupManager::ShowPopupWithAnchorAlign(nsIContent* aPopup,
  718. nsIContent* aAnchorContent,
  719. nsAString& aAnchor,
  720. nsAString& aAlign,
  721. int32_t aXPos, int32_t aYPos,
  722. bool aIsContextMenu)
  723. {
  724. nsMenuPopupFrame* popupFrame = GetPopupFrameForContent(aPopup, true);
  725. if (!popupFrame || !MayShowPopup(popupFrame))
  726. return;
  727. InitTriggerEvent(nullptr, nullptr, nullptr);
  728. popupFrame->InitializePopupWithAnchorAlign(aAnchorContent, aAnchor,
  729. aAlign, aXPos, aYPos);
  730. FirePopupShowingEvent(aPopup, aIsContextMenu, false);
  731. }
  732. static void
  733. CheckCaretDrawingState()
  734. {
  735. // There is 1 caret per document, we need to find the focused
  736. // document and erase its caret.
  737. nsIFocusManager* fm = nsFocusManager::GetFocusManager();
  738. if (fm) {
  739. nsCOMPtr<mozIDOMWindowProxy> window;
  740. fm->GetFocusedWindow(getter_AddRefs(window));
  741. if (!window)
  742. return;
  743. auto* piWindow = nsPIDOMWindowOuter::From(window);
  744. MOZ_ASSERT(piWindow);
  745. nsCOMPtr<nsIDocument> focusedDoc = piWindow->GetDoc();
  746. if (!focusedDoc)
  747. return;
  748. nsIPresShell* presShell = focusedDoc->GetShell();
  749. if (!presShell)
  750. return;
  751. RefPtr<nsCaret> caret = presShell->GetCaret();
  752. if (!caret)
  753. return;
  754. caret->SchedulePaint();
  755. }
  756. }
  757. void
  758. nsXULPopupManager::ShowPopupCallback(nsIContent* aPopup,
  759. nsMenuPopupFrame* aPopupFrame,
  760. bool aIsContextMenu,
  761. bool aSelectFirstItem)
  762. {
  763. nsPopupType popupType = aPopupFrame->PopupType();
  764. bool ismenu = (popupType == ePopupTypeMenu);
  765. nsMenuChainItem* item =
  766. new nsMenuChainItem(aPopupFrame, aIsContextMenu, popupType);
  767. if (!item)
  768. return;
  769. // install keyboard event listeners for navigating menus. For panels, the
  770. // escape key may be used to close the panel. However, the ignorekeys
  771. // attribute may be used to disable adding these event listeners for popups
  772. // that want to handle their own keyboard events.
  773. nsAutoString ignorekeys;
  774. aPopup->GetAttr(kNameSpaceID_None, nsGkAtoms::ignorekeys, ignorekeys);
  775. if (ignorekeys.EqualsLiteral("true")) {
  776. item->SetIgnoreKeys(eIgnoreKeys_True);
  777. } else if (ignorekeys.EqualsLiteral("shortcuts")) {
  778. item->SetIgnoreKeys(eIgnoreKeys_Shortcuts);
  779. }
  780. if (ismenu) {
  781. // if the menu is on a menubar, use the menubar's listener instead
  782. nsMenuFrame* menuFrame = do_QueryFrame(aPopupFrame->GetParent());
  783. if (menuFrame) {
  784. item->SetOnMenuBar(menuFrame->IsOnMenuBar());
  785. }
  786. }
  787. // use a weak frame as the popup will set an open attribute if it is a menu
  788. nsWeakFrame weakFrame(aPopupFrame);
  789. aPopupFrame->ShowPopup(aIsContextMenu);
  790. ENSURE_TRUE(weakFrame.IsAlive());
  791. // popups normally hide when an outside click occurs. Panels may use
  792. // the noautohide attribute to disable this behaviour. It is expected
  793. // that the application will hide these popups manually. The tooltip
  794. // listener will handle closing the tooltip also.
  795. if (aPopupFrame->IsNoAutoHide() || popupType == ePopupTypeTooltip) {
  796. item->SetParent(mNoHidePanels);
  797. mNoHidePanels = item;
  798. }
  799. else {
  800. nsIContent* oldmenu = nullptr;
  801. if (mPopups)
  802. oldmenu = mPopups->Content();
  803. item->SetParent(mPopups);
  804. mPopups = item;
  805. SetCaptureState(oldmenu);
  806. }
  807. if (aSelectFirstItem) {
  808. nsMenuFrame* next = GetNextMenuItem(aPopupFrame, nullptr, true);
  809. aPopupFrame->SetCurrentMenuItem(next);
  810. }
  811. if (ismenu)
  812. UpdateMenuItems(aPopup);
  813. // Caret visibility may have been affected, ensure that
  814. // the caret isn't now drawn when it shouldn't be.
  815. CheckCaretDrawingState();
  816. }
  817. void
  818. nsXULPopupManager::HidePopup(nsIContent* aPopup,
  819. bool aHideChain,
  820. bool aDeselectMenu,
  821. bool aAsynchronous,
  822. bool aIsCancel,
  823. nsIContent* aLastPopup)
  824. {
  825. // if the popup is on the nohide panels list, remove it but don't close any
  826. // other panels
  827. nsMenuPopupFrame* popupFrame = nullptr;
  828. bool foundPanel = false;
  829. nsMenuChainItem* item = mNoHidePanels;
  830. while (item) {
  831. if (item->Content() == aPopup) {
  832. foundPanel = true;
  833. popupFrame = item->Frame();
  834. break;
  835. }
  836. item = item->GetParent();
  837. }
  838. // when removing a menu, all of the child popups must be closed
  839. nsMenuChainItem* foundMenu = nullptr;
  840. item = mPopups;
  841. while (item) {
  842. if (item->Content() == aPopup) {
  843. foundMenu = item;
  844. break;
  845. }
  846. item = item->GetParent();
  847. }
  848. nsPopupType type = ePopupTypePanel;
  849. bool deselectMenu = false;
  850. nsCOMPtr<nsIContent> popupToHide, nextPopup, lastPopup;
  851. if (foundMenu) {
  852. // at this point, foundMenu will be set to the found item in the list. If
  853. // foundMenu is the topmost menu, the one to remove, then there are no other
  854. // popups to hide. If foundMenu is not the topmost menu, then there may be
  855. // open submenus below it. In this case, we need to make sure that those
  856. // submenus are closed up first. To do this, we scan up the menu list to
  857. // find the topmost popup with only menus between it and foundMenu and
  858. // close that menu first. In synchronous mode, the FirePopupHidingEvent
  859. // method will be called which in turn calls HidePopupCallback to close up
  860. // the next popup in the chain. These two methods will be called in
  861. // sequence recursively to close up all the necessary popups. In
  862. // asynchronous mode, a similar process occurs except that the
  863. // FirePopupHidingEvent method is called asynchronously. In either case,
  864. // nextPopup is set to the content node of the next popup to close, and
  865. // lastPopup is set to the last popup in the chain to close, which will be
  866. // aPopup, or null to close up all menus.
  867. nsMenuChainItem* topMenu = foundMenu;
  868. // Use IsMenu to ensure that foundMenu is a menu and scan down the child
  869. // list until a non-menu is found. If foundMenu isn't a menu at all, don't
  870. // scan and just close up this menu.
  871. if (foundMenu->IsMenu()) {
  872. item = topMenu->GetChild();
  873. while (item && item->IsMenu()) {
  874. topMenu = item;
  875. item = item->GetChild();
  876. }
  877. }
  878. deselectMenu = aDeselectMenu;
  879. popupToHide = topMenu->Content();
  880. popupFrame = topMenu->Frame();
  881. type = popupFrame->PopupType();
  882. nsMenuChainItem* parent = topMenu->GetParent();
  883. // close up another popup if there is one, and we are either hiding the
  884. // entire chain or the item to hide isn't the topmost popup.
  885. if (parent && (aHideChain || topMenu != foundMenu))
  886. nextPopup = parent->Content();
  887. lastPopup = aLastPopup ? aLastPopup : (aHideChain ? nullptr : aPopup);
  888. }
  889. else if (foundPanel) {
  890. popupToHide = aPopup;
  891. } else {
  892. // When the popup is in the popuppositioning state, it will not be in the
  893. // mPopups list. We need another way to find it and make sure it does not
  894. // continue the popup showing process.
  895. popupFrame = do_QueryFrame(aPopup->GetPrimaryFrame());
  896. if (popupFrame) {
  897. if (popupFrame->PopupState() == ePopupPositioning) {
  898. // Do basically the same thing we would have done if we had found the
  899. // popup in the mPopups list.
  900. deselectMenu = aDeselectMenu;
  901. popupToHide = aPopup;
  902. type = popupFrame->PopupType();
  903. } else {
  904. // The popup is not positioning. If we were supposed to have handled
  905. // closing it, it should have been in mPopups or mNoHidePanels
  906. popupFrame = nullptr;
  907. }
  908. }
  909. }
  910. if (popupFrame) {
  911. nsPopupState state = popupFrame->PopupState();
  912. // if the popup is already being hidden, don't attempt to hide it again
  913. if (state == ePopupHiding)
  914. return;
  915. // change the popup state to hiding. Don't set the hiding state if the
  916. // popup is invisible, otherwise nsMenuPopupFrame::HidePopup will
  917. // run again. In the invisible state, we just want the events to fire.
  918. if (state != ePopupInvisible)
  919. popupFrame->SetPopupState(ePopupHiding);
  920. // for menus, popupToHide is always the frontmost item in the list to hide.
  921. if (aAsynchronous) {
  922. nsCOMPtr<nsIRunnable> event =
  923. new nsXULPopupHidingEvent(popupToHide, nextPopup, lastPopup,
  924. type, deselectMenu, aIsCancel);
  925. NS_DispatchToCurrentThread(event);
  926. }
  927. else {
  928. FirePopupHidingEvent(popupToHide, nextPopup, lastPopup,
  929. popupFrame->PresContext(), type, deselectMenu, aIsCancel);
  930. }
  931. }
  932. }
  933. // This is used to hide the popup after a transition finishes.
  934. class TransitionEnder : public nsIDOMEventListener
  935. {
  936. protected:
  937. virtual ~TransitionEnder() { }
  938. public:
  939. nsCOMPtr<nsIContent> mContent;
  940. bool mDeselectMenu;
  941. NS_DECL_CYCLE_COLLECTING_ISUPPORTS
  942. NS_DECL_CYCLE_COLLECTION_CLASS(TransitionEnder)
  943. TransitionEnder(nsIContent* aContent, bool aDeselectMenu)
  944. : mContent(aContent), mDeselectMenu(aDeselectMenu)
  945. {
  946. }
  947. NS_IMETHOD HandleEvent(nsIDOMEvent* aEvent) override
  948. {
  949. mContent->RemoveSystemEventListener(NS_LITERAL_STRING("transitionend"), this, false);
  950. nsMenuPopupFrame* popupFrame = do_QueryFrame(mContent->GetPrimaryFrame());
  951. // Now hide the popup. There could be other properties transitioning, but
  952. // we'll assume they all end at the same time and just hide the popup upon
  953. // the first one ending.
  954. nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
  955. if (pm && popupFrame) {
  956. pm->HidePopupCallback(mContent, popupFrame, nullptr, nullptr,
  957. popupFrame->PopupType(), mDeselectMenu);
  958. }
  959. return NS_OK;
  960. }
  961. };
  962. NS_IMPL_CYCLE_COLLECTING_ADDREF(TransitionEnder)
  963. NS_IMPL_CYCLE_COLLECTING_RELEASE(TransitionEnder)
  964. NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(TransitionEnder)
  965. NS_INTERFACE_MAP_ENTRY(nsIDOMEventListener)
  966. NS_INTERFACE_MAP_ENTRY(nsISupports)
  967. NS_INTERFACE_MAP_END
  968. NS_IMPL_CYCLE_COLLECTION(TransitionEnder, mContent);
  969. void
  970. nsXULPopupManager::HidePopupCallback(nsIContent* aPopup,
  971. nsMenuPopupFrame* aPopupFrame,
  972. nsIContent* aNextPopup,
  973. nsIContent* aLastPopup,
  974. nsPopupType aPopupType,
  975. bool aDeselectMenu)
  976. {
  977. if (mCloseTimer && mTimerMenu == aPopupFrame) {
  978. mCloseTimer->Cancel();
  979. mCloseTimer = nullptr;
  980. mTimerMenu = nullptr;
  981. }
  982. // The popup to hide is aPopup. Search the list again to find the item that
  983. // corresponds to the popup to hide aPopup. This is done because it's
  984. // possible someone added another item (attempted to open another popup)
  985. // or removed a popup frame during the event processing so the item isn't at
  986. // the front anymore.
  987. nsMenuChainItem* item = mNoHidePanels;
  988. while (item) {
  989. if (item->Content() == aPopup) {
  990. item->Detach(&mNoHidePanels);
  991. break;
  992. }
  993. item = item->GetParent();
  994. }
  995. if (!item) {
  996. item = mPopups;
  997. while (item) {
  998. if (item->Content() == aPopup) {
  999. item->Detach(&mPopups);
  1000. SetCaptureState(aPopup);
  1001. break;
  1002. }
  1003. item = item->GetParent();
  1004. }
  1005. }
  1006. delete item;
  1007. nsWeakFrame weakFrame(aPopupFrame);
  1008. aPopupFrame->HidePopup(aDeselectMenu, ePopupClosed);
  1009. ENSURE_TRUE(weakFrame.IsAlive());
  1010. // send the popuphidden event synchronously. This event has no default
  1011. // behaviour.
  1012. nsEventStatus status = nsEventStatus_eIgnore;
  1013. WidgetMouseEvent event(true, eXULPopupHidden, nullptr,
  1014. WidgetMouseEvent::eReal);
  1015. EventDispatcher::Dispatch(aPopup, aPopupFrame->PresContext(),
  1016. &event, nullptr, &status);
  1017. ENSURE_TRUE(weakFrame.IsAlive());
  1018. // if there are more popups to close, look for the next one
  1019. if (aNextPopup && aPopup != aLastPopup) {
  1020. nsMenuChainItem* foundMenu = nullptr;
  1021. nsMenuChainItem* item = mPopups;
  1022. while (item) {
  1023. if (item->Content() == aNextPopup) {
  1024. foundMenu = item;
  1025. break;
  1026. }
  1027. item = item->GetParent();
  1028. }
  1029. // continue hiding the chain of popups until the last popup aLastPopup
  1030. // is reached, or until a popup of a different type is reached. This
  1031. // last check is needed so that a menulist inside a non-menu panel only
  1032. // closes the menu and not the panel as well.
  1033. if (foundMenu &&
  1034. (aLastPopup || aPopupType == foundMenu->PopupType())) {
  1035. nsCOMPtr<nsIContent> popupToHide = item->Content();
  1036. nsMenuChainItem* parent = item->GetParent();
  1037. nsCOMPtr<nsIContent> nextPopup;
  1038. if (parent && popupToHide != aLastPopup)
  1039. nextPopup = parent->Content();
  1040. nsMenuPopupFrame* popupFrame = item->Frame();
  1041. nsPopupState state = popupFrame->PopupState();
  1042. if (state == ePopupHiding)
  1043. return;
  1044. if (state != ePopupInvisible)
  1045. popupFrame->SetPopupState(ePopupHiding);
  1046. FirePopupHidingEvent(popupToHide, nextPopup, aLastPopup,
  1047. popupFrame->PresContext(),
  1048. foundMenu->PopupType(), aDeselectMenu, false);
  1049. }
  1050. }
  1051. }
  1052. void
  1053. nsXULPopupManager::HidePopup(nsIFrame* aFrame)
  1054. {
  1055. nsMenuPopupFrame* popup = do_QueryFrame(aFrame);
  1056. if (popup)
  1057. HidePopup(aFrame->GetContent(), false, true, false, false);
  1058. }
  1059. void
  1060. nsXULPopupManager::HidePopupAfterDelay(nsMenuPopupFrame* aPopup)
  1061. {
  1062. // Don't close up immediately.
  1063. // Kick off a close timer.
  1064. KillMenuTimer();
  1065. int32_t menuDelay =
  1066. LookAndFeel::GetInt(LookAndFeel::eIntID_SubmenuDelay, 300); // ms
  1067. // Kick off the timer.
  1068. mCloseTimer = do_CreateInstance("@mozilla.org/timer;1");
  1069. mCloseTimer->InitWithCallback(this, menuDelay, nsITimer::TYPE_ONE_SHOT);
  1070. // the popup will call PopupDestroyed if it is destroyed, which checks if it
  1071. // is set to mTimerMenu, so it should be safe to keep a reference to it
  1072. mTimerMenu = aPopup;
  1073. }
  1074. void
  1075. nsXULPopupManager::HidePopupsInList(const nsTArray<nsMenuPopupFrame *> &aFrames)
  1076. {
  1077. // Create a weak frame list. This is done in a separate array with the
  1078. // right capacity predetermined, otherwise the array would get resized and
  1079. // move the weak frame pointers around.
  1080. nsTArray<nsWeakFrame> weakPopups(aFrames.Length());
  1081. uint32_t f;
  1082. for (f = 0; f < aFrames.Length(); f++) {
  1083. nsWeakFrame* wframe = weakPopups.AppendElement();
  1084. if (wframe)
  1085. *wframe = aFrames[f];
  1086. }
  1087. for (f = 0; f < weakPopups.Length(); f++) {
  1088. // check to ensure that the frame is still alive before hiding it.
  1089. if (weakPopups[f].IsAlive()) {
  1090. nsMenuPopupFrame* frame =
  1091. static_cast<nsMenuPopupFrame *>(weakPopups[f].GetFrame());
  1092. frame->HidePopup(true, ePopupInvisible);
  1093. }
  1094. }
  1095. SetCaptureState(nullptr);
  1096. }
  1097. void
  1098. nsXULPopupManager::EnableRollup(nsIContent* aPopup, bool aShouldRollup)
  1099. {
  1100. #ifndef MOZ_GTK
  1101. if (aShouldRollup) {
  1102. nsMenuChainItem* item = mNoHidePanels;
  1103. while (item) {
  1104. if (item->Content() == aPopup) {
  1105. item->Detach(&mNoHidePanels);
  1106. nsIContent* oldmenu = nullptr;
  1107. if (mPopups)
  1108. oldmenu = mPopups->Content();
  1109. item->SetParent(mPopups);
  1110. mPopups = item;
  1111. SetCaptureState(oldmenu);
  1112. return;
  1113. }
  1114. item = item->GetParent();
  1115. }
  1116. } else {
  1117. nsMenuChainItem* item = mPopups;
  1118. while (item) {
  1119. if (item->Content() == aPopup) {
  1120. item->Detach(&mPopups);
  1121. item->SetParent(mNoHidePanels);
  1122. mNoHidePanels = item;
  1123. SetCaptureState(nullptr);
  1124. return;
  1125. }
  1126. item = item->GetParent();
  1127. }
  1128. }
  1129. #endif
  1130. }
  1131. bool
  1132. nsXULPopupManager::IsChildOfDocShell(nsIDocument* aDoc, nsIDocShellTreeItem* aExpected)
  1133. {
  1134. nsCOMPtr<nsIDocShellTreeItem> docShellItem(aDoc->GetDocShell());
  1135. while(docShellItem) {
  1136. if (docShellItem == aExpected)
  1137. return true;
  1138. nsCOMPtr<nsIDocShellTreeItem> parent;
  1139. docShellItem->GetParent(getter_AddRefs(parent));
  1140. docShellItem = parent;
  1141. }
  1142. return false;
  1143. }
  1144. void
  1145. nsXULPopupManager::HidePopupsInDocShell(nsIDocShellTreeItem* aDocShellToHide)
  1146. {
  1147. nsTArray<nsMenuPopupFrame *> popupsToHide;
  1148. // iterate to get the set of popup frames to hide
  1149. nsMenuChainItem* item = mPopups;
  1150. while (item) {
  1151. nsMenuChainItem* parent = item->GetParent();
  1152. if (item->Frame()->PopupState() != ePopupInvisible &&
  1153. IsChildOfDocShell(item->Content()->OwnerDoc(), aDocShellToHide)) {
  1154. nsMenuPopupFrame* frame = item->Frame();
  1155. item->Detach(&mPopups);
  1156. delete item;
  1157. popupsToHide.AppendElement(frame);
  1158. }
  1159. item = parent;
  1160. }
  1161. // now look for panels to hide
  1162. item = mNoHidePanels;
  1163. while (item) {
  1164. nsMenuChainItem* parent = item->GetParent();
  1165. if (item->Frame()->PopupState() != ePopupInvisible &&
  1166. IsChildOfDocShell(item->Content()->OwnerDoc(), aDocShellToHide)) {
  1167. nsMenuPopupFrame* frame = item->Frame();
  1168. item->Detach(&mNoHidePanels);
  1169. delete item;
  1170. popupsToHide.AppendElement(frame);
  1171. }
  1172. item = parent;
  1173. }
  1174. HidePopupsInList(popupsToHide);
  1175. }
  1176. void
  1177. nsXULPopupManager::ExecuteMenu(nsIContent* aMenu, nsXULMenuCommandEvent* aEvent)
  1178. {
  1179. CloseMenuMode cmm = CloseMenuMode_Auto;
  1180. static nsIContent::AttrValuesArray strings[] =
  1181. {&nsGkAtoms::none, &nsGkAtoms::single, nullptr};
  1182. switch (aMenu->FindAttrValueIn(kNameSpaceID_None, nsGkAtoms::closemenu,
  1183. strings, eCaseMatters)) {
  1184. case 0:
  1185. cmm = CloseMenuMode_None;
  1186. break;
  1187. case 1:
  1188. cmm = CloseMenuMode_Single;
  1189. break;
  1190. default:
  1191. break;
  1192. }
  1193. // When a menuitem is selected to be executed, first hide all the open
  1194. // popups, but don't remove them yet. This is needed when a menu command
  1195. // opens a modal dialog. The views associated with the popups needed to be
  1196. // hidden and the accesibility events fired before the command executes, but
  1197. // the popuphiding/popuphidden events are fired afterwards.
  1198. nsTArray<nsMenuPopupFrame *> popupsToHide;
  1199. nsMenuChainItem* item = GetTopVisibleMenu();
  1200. if (cmm != CloseMenuMode_None) {
  1201. while (item) {
  1202. // if it isn't a <menupopup>, don't close it automatically
  1203. if (!item->IsMenu())
  1204. break;
  1205. nsMenuChainItem* next = item->GetParent();
  1206. popupsToHide.AppendElement(item->Frame());
  1207. if (cmm == CloseMenuMode_Single) // only close one level of menu
  1208. break;
  1209. item = next;
  1210. }
  1211. // Now hide the popups. If the closemenu mode is auto, deselect the menu,
  1212. // otherwise only one popup is closing, so keep the parent menu selected.
  1213. HidePopupsInList(popupsToHide);
  1214. }
  1215. aEvent->SetCloseMenuMode(cmm);
  1216. nsCOMPtr<nsIRunnable> event = aEvent;
  1217. NS_DispatchToCurrentThread(event);
  1218. }
  1219. void
  1220. nsXULPopupManager::FirePopupShowingEvent(nsIContent* aPopup,
  1221. bool aIsContextMenu,
  1222. bool aSelectFirstItem)
  1223. {
  1224. nsCOMPtr<nsIContent> popup = aPopup; // keep a strong reference to the popup
  1225. nsMenuPopupFrame* popupFrame = do_QueryFrame(aPopup->GetPrimaryFrame());
  1226. if (!popupFrame)
  1227. return;
  1228. nsPresContext *presContext = popupFrame->PresContext();
  1229. nsCOMPtr<nsIPresShell> presShell = presContext->PresShell();
  1230. nsPopupType popupType = popupFrame->PopupType();
  1231. // generate the child frames if they have not already been generated
  1232. if (!popupFrame->HasGeneratedChildren()) {
  1233. popupFrame->SetGeneratedChildren();
  1234. presShell->FrameConstructor()->GenerateChildFrames(popupFrame);
  1235. }
  1236. // get the frame again
  1237. nsIFrame* frame = aPopup->GetPrimaryFrame();
  1238. if (!frame)
  1239. return;
  1240. presShell->FrameNeedsReflow(frame, nsIPresShell::eTreeChange,
  1241. NS_FRAME_HAS_DIRTY_CHILDREN);
  1242. // cache the popup so that document.popupNode can retrieve the trigger node
  1243. // during the popupshowing event. It will be cleared below after the event
  1244. // has fired.
  1245. mOpeningPopup = aPopup;
  1246. nsEventStatus status = nsEventStatus_eIgnore;
  1247. WidgetMouseEvent event(true, eXULPopupShowing, nullptr,
  1248. WidgetMouseEvent::eReal);
  1249. // coordinates are relative to the root widget
  1250. nsPresContext* rootPresContext =
  1251. presShell->GetPresContext()->GetRootPresContext();
  1252. if (rootPresContext) {
  1253. rootPresContext->PresShell()->GetViewManager()->
  1254. GetRootWidget(getter_AddRefs(event.mWidget));
  1255. }
  1256. else {
  1257. event.mWidget = nullptr;
  1258. }
  1259. event.mRefPoint = mCachedMousePoint;
  1260. event.mModifiers = mCachedModifiers;
  1261. EventDispatcher::Dispatch(popup, presContext, &event, nullptr, &status);
  1262. mCachedMousePoint = LayoutDeviceIntPoint(0, 0);
  1263. mOpeningPopup = nullptr;
  1264. mCachedModifiers = 0;
  1265. // if a panel, blur whatever has focus so that the panel can take the focus.
  1266. // This is done after the popupshowing event in case that event is cancelled.
  1267. // Using noautofocus="true" will disable this behaviour, which is needed for
  1268. // the autocomplete widget as it manages focus itself.
  1269. if (popupType == ePopupTypePanel &&
  1270. !popup->AttrValueIs(kNameSpaceID_None, nsGkAtoms::noautofocus,
  1271. nsGkAtoms::_true, eCaseMatters)) {
  1272. nsIFocusManager* fm = nsFocusManager::GetFocusManager();
  1273. if (fm) {
  1274. nsIDocument* doc = popup->GetUncomposedDoc();
  1275. // Only remove the focus if the currently focused item is ouside the
  1276. // popup. It isn't a big deal if the current focus is in a child popup
  1277. // inside the popup as that shouldn't be visible. This check ensures that
  1278. // a node inside the popup that is focused during a popupshowing event
  1279. // remains focused.
  1280. nsCOMPtr<nsIDOMElement> currentFocusElement;
  1281. fm->GetFocusedElement(getter_AddRefs(currentFocusElement));
  1282. nsCOMPtr<nsIContent> currentFocus = do_QueryInterface(currentFocusElement);
  1283. if (doc && currentFocus &&
  1284. !nsContentUtils::ContentIsCrossDocDescendantOf(currentFocus, popup)) {
  1285. fm->ClearFocus(doc->GetWindow());
  1286. }
  1287. }
  1288. }
  1289. // clear these as they are no longer valid
  1290. mRangeParent = nullptr;
  1291. mRangeOffset = 0;
  1292. // get the frame again in case it went away
  1293. popupFrame = do_QueryFrame(aPopup->GetPrimaryFrame());
  1294. if (popupFrame) {
  1295. // if the event was cancelled, don't open the popup, reset its state back
  1296. // to closed and clear its trigger content.
  1297. if (status == nsEventStatus_eConsumeNoDefault) {
  1298. popupFrame->SetPopupState(ePopupClosed);
  1299. popupFrame->ClearTriggerContent();
  1300. }
  1301. else {
  1302. // Now check if we need to fire the popuppositioned event. If not, call
  1303. // ShowPopupCallback directly.
  1304. // The popuppositioned event only fires on arrow panels for now.
  1305. if (popup->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
  1306. nsGkAtoms::arrow, eCaseMatters)) {
  1307. popupFrame->ShowWithPositionedEvent();
  1308. presShell->FrameNeedsReflow(popupFrame, nsIPresShell::eTreeChange,
  1309. NS_FRAME_HAS_DIRTY_CHILDREN);
  1310. }
  1311. else {
  1312. ShowPopupCallback(popup, popupFrame, aIsContextMenu, aSelectFirstItem);
  1313. }
  1314. }
  1315. }
  1316. }
  1317. void
  1318. nsXULPopupManager::FirePopupHidingEvent(nsIContent* aPopup,
  1319. nsIContent* aNextPopup,
  1320. nsIContent* aLastPopup,
  1321. nsPresContext *aPresContext,
  1322. nsPopupType aPopupType,
  1323. bool aDeselectMenu,
  1324. bool aIsCancel)
  1325. {
  1326. nsCOMPtr<nsIPresShell> presShell = aPresContext->PresShell();
  1327. mozilla::Unused << presShell; // This presShell may be keeping things alive on non GTK platforms
  1328. nsEventStatus status = nsEventStatus_eIgnore;
  1329. WidgetMouseEvent event(true, eXULPopupHiding, nullptr,
  1330. WidgetMouseEvent::eReal);
  1331. EventDispatcher::Dispatch(aPopup, aPresContext, &event, nullptr, &status);
  1332. // when a panel is closed, blur whatever has focus inside the popup
  1333. if (aPopupType == ePopupTypePanel &&
  1334. !aPopup->AttrValueIs(kNameSpaceID_None, nsGkAtoms::noautofocus,
  1335. nsGkAtoms::_true, eCaseMatters)) {
  1336. nsIFocusManager* fm = nsFocusManager::GetFocusManager();
  1337. if (fm) {
  1338. nsIDocument* doc = aPopup->GetUncomposedDoc();
  1339. // Remove the focus from the focused node only if it is inside the popup.
  1340. nsCOMPtr<nsIDOMElement> currentFocusElement;
  1341. fm->GetFocusedElement(getter_AddRefs(currentFocusElement));
  1342. nsCOMPtr<nsIContent> currentFocus = do_QueryInterface(currentFocusElement);
  1343. if (doc && currentFocus &&
  1344. nsContentUtils::ContentIsCrossDocDescendantOf(currentFocus, aPopup)) {
  1345. fm->ClearFocus(doc->GetWindow());
  1346. }
  1347. }
  1348. }
  1349. // get frame again in case it went away
  1350. nsMenuPopupFrame* popupFrame = do_QueryFrame(aPopup->GetPrimaryFrame());
  1351. if (popupFrame) {
  1352. // if the event was cancelled, don't hide the popup, and reset its
  1353. // state back to open. Only popups in chrome shells can prevent a popup
  1354. // from hiding.
  1355. if (status == nsEventStatus_eConsumeNoDefault &&
  1356. !popupFrame->IsInContentShell()) {
  1357. // XXXndeakin
  1358. // If an attempt was made to hide this popup before the popupshown event
  1359. // fired, then ePopupShown is set here even though it should be
  1360. // ePopupVisible. This probably isn't worth the hassle of handling.
  1361. popupFrame->SetPopupState(ePopupShown);
  1362. }
  1363. else {
  1364. // If the popup has an animate attribute and it is not set to false, check
  1365. // if it has a closing transition and wait for it to finish. The transition
  1366. // may still occur either way, but the view will be hidden and you won't be
  1367. // able to see it. If there is a next popup, indicating that mutliple popups
  1368. // are rolling up, don't wait and hide the popup right away since the effect
  1369. // would likely be undesirable. Transitions are currently disabled on Linux
  1370. // due to rendering issues on certain configurations.
  1371. #ifndef MOZ_WIDGET_GTK
  1372. if (!aNextPopup && aPopup->HasAttr(kNameSpaceID_None, nsGkAtoms::animate)) {
  1373. // If animate="false" then don't transition at all. If animate="cancel",
  1374. // only show the transition if cancelling the popup or rolling up.
  1375. // Otherwise, always show the transition.
  1376. nsAutoString animate;
  1377. aPopup->GetAttr(kNameSpaceID_None, nsGkAtoms::animate, animate);
  1378. if (!animate.EqualsLiteral("false") &&
  1379. (!animate.EqualsLiteral("cancel") || aIsCancel)) {
  1380. presShell->FlushPendingNotifications(Flush_Layout);
  1381. // Get the frame again in case the flush caused it to go away
  1382. popupFrame = do_QueryFrame(aPopup->GetPrimaryFrame());
  1383. if (!popupFrame)
  1384. return;
  1385. if (nsLayoutUtils::HasCurrentTransitions(popupFrame)) {
  1386. RefPtr<TransitionEnder> ender = new TransitionEnder(aPopup, aDeselectMenu);
  1387. aPopup->AddSystemEventListener(NS_LITERAL_STRING("transitionend"),
  1388. ender, false, false);
  1389. return;
  1390. }
  1391. }
  1392. }
  1393. #endif
  1394. HidePopupCallback(aPopup, popupFrame, aNextPopup, aLastPopup,
  1395. aPopupType, aDeselectMenu);
  1396. }
  1397. }
  1398. }
  1399. bool
  1400. nsXULPopupManager::IsPopupOpen(nsIContent* aPopup)
  1401. {
  1402. // a popup is open if it is in the open list. The assertions ensure that the
  1403. // frame is in the correct state. If the popup is in the hiding or invisible
  1404. // state, it will still be in the open popup list until it is closed.
  1405. nsMenuChainItem* item = mPopups;
  1406. while (item) {
  1407. if (item->Content() == aPopup) {
  1408. NS_ASSERTION(item->Frame()->IsOpen() ||
  1409. item->Frame()->PopupState() == ePopupHiding ||
  1410. item->Frame()->PopupState() == ePopupInvisible,
  1411. "popup in open list not actually open");
  1412. return true;
  1413. }
  1414. item = item->GetParent();
  1415. }
  1416. item = mNoHidePanels;
  1417. while (item) {
  1418. if (item->Content() == aPopup) {
  1419. NS_ASSERTION(item->Frame()->IsOpen() ||
  1420. item->Frame()->PopupState() == ePopupHiding ||
  1421. item->Frame()->PopupState() == ePopupInvisible,
  1422. "popup in open list not actually open");
  1423. return true;
  1424. }
  1425. item = item->GetParent();
  1426. }
  1427. return false;
  1428. }
  1429. bool
  1430. nsXULPopupManager::IsPopupOpenForMenuParent(nsMenuParent* aMenuParent)
  1431. {
  1432. nsMenuChainItem* item = GetTopVisibleMenu();
  1433. while (item) {
  1434. nsMenuPopupFrame* popup = item->Frame();
  1435. if (popup && popup->IsOpen()) {
  1436. nsMenuFrame* menuFrame = do_QueryFrame(popup->GetParent());
  1437. if (menuFrame && menuFrame->GetMenuParent() == aMenuParent) {
  1438. return true;
  1439. }
  1440. }
  1441. item = item->GetParent();
  1442. }
  1443. return false;
  1444. }
  1445. nsIFrame*
  1446. nsXULPopupManager::GetTopPopup(nsPopupType aType)
  1447. {
  1448. if ((aType == ePopupTypePanel || aType == ePopupTypeTooltip) && mNoHidePanels)
  1449. return mNoHidePanels->Frame();
  1450. nsMenuChainItem* item = GetTopVisibleMenu();
  1451. while (item) {
  1452. if (item->PopupType() == aType || aType == ePopupTypeAny)
  1453. return item->Frame();
  1454. item = item->GetParent();
  1455. }
  1456. return nullptr;
  1457. }
  1458. void
  1459. nsXULPopupManager::GetVisiblePopups(nsTArray<nsIFrame *>& aPopups)
  1460. {
  1461. aPopups.Clear();
  1462. // Iterate over both lists of popups
  1463. nsMenuChainItem* item = mPopups;
  1464. for (int32_t list = 0; list < 2; list++) {
  1465. while (item) {
  1466. // Skip panels which are not visible as well as popups that
  1467. // are transparent to mouse events.
  1468. if (item->Frame()->IsVisible() && !item->Frame()->IsMouseTransparent()) {
  1469. aPopups.AppendElement(item->Frame());
  1470. }
  1471. item = item->GetParent();
  1472. }
  1473. item = mNoHidePanels;
  1474. }
  1475. }
  1476. already_AddRefed<nsIDOMNode>
  1477. nsXULPopupManager::GetLastTriggerNode(nsIDocument* aDocument, bool aIsTooltip)
  1478. {
  1479. if (!aDocument)
  1480. return nullptr;
  1481. nsCOMPtr<nsIDOMNode> node;
  1482. // if mOpeningPopup is set, it means that a popupshowing event is being
  1483. // fired. In this case, just use the cached node, as the popup is not yet in
  1484. // the list of open popups.
  1485. if (mOpeningPopup && mOpeningPopup->GetUncomposedDoc() == aDocument &&
  1486. aIsTooltip == mOpeningPopup->IsXULElement(nsGkAtoms::tooltip)) {
  1487. node = do_QueryInterface(nsMenuPopupFrame::GetTriggerContent(GetPopupFrameForContent(mOpeningPopup, false)));
  1488. }
  1489. else {
  1490. nsMenuChainItem* item = aIsTooltip ? mNoHidePanels : mPopups;
  1491. while (item) {
  1492. // look for a popup of the same type and document.
  1493. if ((item->PopupType() == ePopupTypeTooltip) == aIsTooltip &&
  1494. item->Content()->GetUncomposedDoc() == aDocument) {
  1495. node = do_QueryInterface(nsMenuPopupFrame::GetTriggerContent(item->Frame()));
  1496. if (node)
  1497. break;
  1498. }
  1499. item = item->GetParent();
  1500. }
  1501. }
  1502. return node.forget();
  1503. }
  1504. bool
  1505. nsXULPopupManager::MayShowPopup(nsMenuPopupFrame* aPopup)
  1506. {
  1507. // if a popup's IsOpen method returns true, then the popup must always be in
  1508. // the popup chain scanned in IsPopupOpen.
  1509. NS_ASSERTION(!aPopup->IsOpen() || IsPopupOpen(aPopup->GetContent()),
  1510. "popup frame state doesn't match XULPopupManager open state");
  1511. nsPopupState state = aPopup->PopupState();
  1512. // if the popup is not in the open popup chain, then it must have a state that
  1513. // is either closed, in the process of being shown, or invisible.
  1514. NS_ASSERTION(IsPopupOpen(aPopup->GetContent()) || state == ePopupClosed ||
  1515. state == ePopupShowing || state == ePopupPositioning ||
  1516. state == ePopupInvisible,
  1517. "popup not in XULPopupManager open list is open");
  1518. // don't show popups unless they are closed or invisible
  1519. if (state != ePopupClosed && state != ePopupInvisible)
  1520. return false;
  1521. // Don't show popups that we already have in our popup chain
  1522. if (IsPopupOpen(aPopup->GetContent())) {
  1523. NS_WARNING("Refusing to show duplicate popup");
  1524. return false;
  1525. }
  1526. // if the popup was just rolled up, don't reopen it
  1527. nsCOMPtr<nsIWidget> widget = aPopup->GetWidget();
  1528. if (widget && widget->GetLastRollup() == aPopup->GetContent())
  1529. return false;
  1530. nsCOMPtr<nsIDocShellTreeItem> dsti = aPopup->PresContext()->GetDocShell();
  1531. nsCOMPtr<nsIBaseWindow> baseWin = do_QueryInterface(dsti);
  1532. if (!baseWin)
  1533. return false;
  1534. nsCOMPtr<nsIDocShellTreeItem> root;
  1535. dsti->GetRootTreeItem(getter_AddRefs(root));
  1536. if (!root) {
  1537. return false;
  1538. }
  1539. nsCOMPtr<nsPIDOMWindowOuter> rootWin = root->GetWindow();
  1540. // chrome shells can always open popups, but other types of shells can only
  1541. // open popups when they are focused and visible
  1542. if (dsti->ItemType() != nsIDocShellTreeItem::typeChrome) {
  1543. // only allow popups in active windows
  1544. nsIFocusManager* fm = nsFocusManager::GetFocusManager();
  1545. if (!fm || !rootWin)
  1546. return false;
  1547. nsCOMPtr<mozIDOMWindowProxy> activeWindow;
  1548. fm->GetActiveWindow(getter_AddRefs(activeWindow));
  1549. if (activeWindow != rootWin)
  1550. return false;
  1551. // only allow popups in visible frames
  1552. bool visible;
  1553. baseWin->GetVisibility(&visible);
  1554. if (!visible)
  1555. return false;
  1556. }
  1557. // platforms respond differently when an popup is opened in a minimized
  1558. // window, so this is always disabled.
  1559. nsCOMPtr<nsIWidget> mainWidget;
  1560. baseWin->GetMainWidget(getter_AddRefs(mainWidget));
  1561. if (mainWidget && mainWidget->SizeMode() == nsSizeMode_Minimized) {
  1562. return false;
  1563. }
  1564. // cannot open a popup that is a submenu of a menupopup that isn't open.
  1565. nsMenuFrame* menuFrame = do_QueryFrame(aPopup->GetParent());
  1566. if (menuFrame) {
  1567. nsMenuParent* parentPopup = menuFrame->GetMenuParent();
  1568. if (parentPopup && !parentPopup->IsOpen())
  1569. return false;
  1570. }
  1571. return true;
  1572. }
  1573. void
  1574. nsXULPopupManager::PopupDestroyed(nsMenuPopupFrame* aPopup)
  1575. {
  1576. // when a popup frame is destroyed, just unhook it from the list of popups
  1577. if (mTimerMenu == aPopup) {
  1578. if (mCloseTimer) {
  1579. mCloseTimer->Cancel();
  1580. mCloseTimer = nullptr;
  1581. }
  1582. mTimerMenu = nullptr;
  1583. }
  1584. nsMenuChainItem* item = mNoHidePanels;
  1585. while (item) {
  1586. if (item->Frame() == aPopup) {
  1587. item->Detach(&mNoHidePanels);
  1588. delete item;
  1589. break;
  1590. }
  1591. item = item->GetParent();
  1592. }
  1593. nsTArray<nsMenuPopupFrame *> popupsToHide;
  1594. item = mPopups;
  1595. while (item) {
  1596. nsMenuPopupFrame* frame = item->Frame();
  1597. if (frame == aPopup) {
  1598. if (frame->PopupState() != ePopupInvisible) {
  1599. // Iterate through any child menus and hide them as well, since the
  1600. // parent is going away. We won't remove them from the list yet, just
  1601. // hide them, as they will be removed from the list when this function
  1602. // gets called for that child frame.
  1603. nsMenuChainItem* child = item->GetChild();
  1604. while (child) {
  1605. // if the popup is a child frame of the menu that was destroyed, add
  1606. // it to the list of popups to hide. Don't bother with the events
  1607. // since the frames are going away. If the child menu is not a child
  1608. // frame, for example, a context menu, use HidePopup instead, but call
  1609. // it asynchronously since we are in the middle of frame destruction.
  1610. nsMenuPopupFrame* childframe = child->Frame();
  1611. if (nsLayoutUtils::IsProperAncestorFrame(frame, childframe)) {
  1612. popupsToHide.AppendElement(childframe);
  1613. }
  1614. else {
  1615. // HidePopup will take care of hiding any of its children, so
  1616. // break out afterwards
  1617. HidePopup(child->Content(), false, false, true, false);
  1618. break;
  1619. }
  1620. child = child->GetChild();
  1621. }
  1622. }
  1623. item->Detach(&mPopups);
  1624. delete item;
  1625. break;
  1626. }
  1627. item = item->GetParent();
  1628. }
  1629. HidePopupsInList(popupsToHide);
  1630. }
  1631. bool
  1632. nsXULPopupManager::HasContextMenu(nsMenuPopupFrame* aPopup)
  1633. {
  1634. nsMenuChainItem* item = GetTopVisibleMenu();
  1635. while (item && item->Frame() != aPopup) {
  1636. if (item->IsContextMenu())
  1637. return true;
  1638. item = item->GetParent();
  1639. }
  1640. return false;
  1641. }
  1642. void
  1643. nsXULPopupManager::SetCaptureState(nsIContent* aOldPopup)
  1644. {
  1645. nsMenuChainItem* item = GetTopVisibleMenu();
  1646. if (item && aOldPopup == item->Content())
  1647. return;
  1648. if (mWidget) {
  1649. mWidget->CaptureRollupEvents(nullptr, false);
  1650. mWidget = nullptr;
  1651. }
  1652. if (item) {
  1653. nsMenuPopupFrame* popup = item->Frame();
  1654. mWidget = popup->GetWidget();
  1655. if (mWidget) {
  1656. mWidget->CaptureRollupEvents(nullptr, true);
  1657. popup->AttachedDismissalListener();
  1658. }
  1659. }
  1660. UpdateKeyboardListeners();
  1661. }
  1662. void
  1663. nsXULPopupManager::UpdateKeyboardListeners()
  1664. {
  1665. nsCOMPtr<EventTarget> newTarget;
  1666. bool isForMenu = false;
  1667. nsMenuChainItem* item = GetTopVisibleMenu();
  1668. if (item) {
  1669. if (item->IgnoreKeys() != eIgnoreKeys_True) {
  1670. newTarget = item->Content()->GetComposedDoc();
  1671. }
  1672. isForMenu = item->PopupType() == ePopupTypeMenu;
  1673. }
  1674. else if (mActiveMenuBar) {
  1675. newTarget = mActiveMenuBar->GetContent()->GetComposedDoc();
  1676. isForMenu = true;
  1677. }
  1678. if (mKeyListener != newTarget) {
  1679. if (mKeyListener) {
  1680. mKeyListener->RemoveEventListener(NS_LITERAL_STRING("keypress"), this, true);
  1681. mKeyListener->RemoveEventListener(NS_LITERAL_STRING("keydown"), this, true);
  1682. mKeyListener->RemoveEventListener(NS_LITERAL_STRING("keyup"), this, true);
  1683. mKeyListener = nullptr;
  1684. nsContentUtils::NotifyInstalledMenuKeyboardListener(false);
  1685. }
  1686. if (newTarget) {
  1687. newTarget->AddEventListener(NS_LITERAL_STRING("keypress"), this, true);
  1688. newTarget->AddEventListener(NS_LITERAL_STRING("keydown"), this, true);
  1689. newTarget->AddEventListener(NS_LITERAL_STRING("keyup"), this, true);
  1690. nsContentUtils::NotifyInstalledMenuKeyboardListener(isForMenu);
  1691. mKeyListener = newTarget;
  1692. }
  1693. }
  1694. }
  1695. void
  1696. nsXULPopupManager::UpdateMenuItems(nsIContent* aPopup)
  1697. {
  1698. // Walk all of the menu's children, checking to see if any of them has a
  1699. // command attribute. If so, then several attributes must potentially be updated.
  1700. nsCOMPtr<nsIDocument> document = aPopup->GetUncomposedDoc();
  1701. if (!document) {
  1702. return;
  1703. }
  1704. for (nsCOMPtr<nsIContent> grandChild = aPopup->GetFirstChild();
  1705. grandChild;
  1706. grandChild = grandChild->GetNextSibling()) {
  1707. if (grandChild->IsXULElement(nsGkAtoms::menugroup)) {
  1708. if (grandChild->GetChildCount() == 0) {
  1709. continue;
  1710. }
  1711. grandChild = grandChild->GetFirstChild();
  1712. }
  1713. if (grandChild->IsXULElement(nsGkAtoms::menuitem)) {
  1714. // See if we have a command attribute.
  1715. nsAutoString command;
  1716. grandChild->GetAttr(kNameSpaceID_None, nsGkAtoms::command, command);
  1717. if (!command.IsEmpty()) {
  1718. // We do! Look it up in our document
  1719. RefPtr<dom::Element> commandElement =
  1720. document->GetElementById(command);
  1721. if (commandElement) {
  1722. nsAutoString commandValue;
  1723. // The menu's disabled state needs to be updated to match the command.
  1724. if (commandElement->GetAttr(kNameSpaceID_None, nsGkAtoms::disabled, commandValue))
  1725. grandChild->SetAttr(kNameSpaceID_None, nsGkAtoms::disabled, commandValue, true);
  1726. else
  1727. grandChild->UnsetAttr(kNameSpaceID_None, nsGkAtoms::disabled, true);
  1728. // The menu's label, accesskey checked and hidden states need to be updated
  1729. // to match the command. Note that unlike the disabled state if the
  1730. // command has *no* value, we assume the menu is supplying its own.
  1731. if (commandElement->GetAttr(kNameSpaceID_None, nsGkAtoms::label, commandValue))
  1732. grandChild->SetAttr(kNameSpaceID_None, nsGkAtoms::label, commandValue, true);
  1733. if (commandElement->GetAttr(kNameSpaceID_None, nsGkAtoms::accesskey, commandValue))
  1734. grandChild->SetAttr(kNameSpaceID_None, nsGkAtoms::accesskey, commandValue, true);
  1735. if (commandElement->GetAttr(kNameSpaceID_None, nsGkAtoms::checked, commandValue))
  1736. grandChild->SetAttr(kNameSpaceID_None, nsGkAtoms::checked, commandValue, true);
  1737. if (commandElement->GetAttr(kNameSpaceID_None, nsGkAtoms::hidden, commandValue))
  1738. grandChild->SetAttr(kNameSpaceID_None, nsGkAtoms::hidden, commandValue, true);
  1739. }
  1740. }
  1741. }
  1742. if (!grandChild->GetNextSibling() &&
  1743. grandChild->GetParent()->IsXULElement(nsGkAtoms::menugroup)) {
  1744. grandChild = grandChild->GetParent();
  1745. }
  1746. }
  1747. }
  1748. // Notify
  1749. //
  1750. // The item selection timer has fired, we might have to readjust the
  1751. // selected item. There are two cases here that we are trying to deal with:
  1752. // (1) diagonal movement from a parent menu to a submenu passing briefly over
  1753. // other items, and
  1754. // (2) moving out from a submenu to a parent or grandparent menu.
  1755. // In both cases, |mTimerMenu| is the menu item that might have an open submenu and
  1756. // the first item in |mPopups| is the item the mouse is currently over, which could be
  1757. // none of them.
  1758. //
  1759. // case (1):
  1760. // As the mouse moves from the parent item of a submenu (we'll call 'A') diagonally into the
  1761. // submenu, it probably passes through one or more sibilings (B). As the mouse passes
  1762. // through B, it becomes the current menu item and the timer is set and mTimerMenu is
  1763. // set to A. Before the timer fires, the mouse leaves the menu containing A and B and
  1764. // enters the submenus. Now when the timer fires, |mPopups| is null (!= |mTimerMenu|)
  1765. // so we have to see if anything in A's children is selected (recall that even disabled
  1766. // items are selected, the style just doesn't show it). If that is the case, we need to
  1767. // set the selected item back to A.
  1768. //
  1769. // case (2);
  1770. // Item A has an open submenu, and in it there is an item (B) which also has an open
  1771. // submenu (so there are 3 menus displayed right now). The mouse then leaves B's child
  1772. // submenu and selects an item that is a sibling of A, call it C. When the mouse enters C,
  1773. // the timer is set and |mTimerMenu| is A and |mPopups| is C. As the timer fires,
  1774. // the mouse is still within C. The correct behavior is to set the current item to C
  1775. // and close up the chain parented at A.
  1776. //
  1777. // This brings up the question of is the logic of case (1) enough? The answer is no,
  1778. // and is discussed in bugzilla bug 29400. Case (1) asks if A's submenu has a selected
  1779. // child, and if it does, set the selected item to A. Because B has a submenu open, it
  1780. // is selected and as a result, A is set to be the selected item even though the mouse
  1781. // rests in C -- very wrong.
  1782. //
  1783. // The solution is to use the same idea, but instead of only checking one level,
  1784. // drill all the way down to the deepest open submenu and check if it has something
  1785. // selected. Since the mouse is in a grandparent, it won't, and we know that we can
  1786. // safely close up A and all its children.
  1787. //
  1788. // The code below melds the two cases together.
  1789. //
  1790. nsresult
  1791. nsXULPopupManager::Notify(nsITimer* aTimer)
  1792. {
  1793. if (aTimer == mCloseTimer)
  1794. KillMenuTimer();
  1795. return NS_OK;
  1796. }
  1797. void
  1798. nsXULPopupManager::KillMenuTimer()
  1799. {
  1800. if (mCloseTimer && mTimerMenu) {
  1801. mCloseTimer->Cancel();
  1802. mCloseTimer = nullptr;
  1803. if (mTimerMenu->IsOpen())
  1804. HidePopup(mTimerMenu->GetContent(), false, false, true, false);
  1805. }
  1806. mTimerMenu = nullptr;
  1807. }
  1808. void
  1809. nsXULPopupManager::CancelMenuTimer(nsMenuParent* aMenuParent)
  1810. {
  1811. if (mCloseTimer && mTimerMenu == aMenuParent) {
  1812. mCloseTimer->Cancel();
  1813. mCloseTimer = nullptr;
  1814. mTimerMenu = nullptr;
  1815. }
  1816. }
  1817. bool
  1818. nsXULPopupManager::HandleShortcutNavigation(nsIDOMKeyEvent* aKeyEvent,
  1819. nsMenuPopupFrame* aFrame)
  1820. {
  1821. // On Windows, don't check shortcuts when the accelerator key is down.
  1822. #ifdef XP_WIN
  1823. WidgetInputEvent* evt = aKeyEvent->AsEvent()->WidgetEventPtr()->AsInputEvent();
  1824. if (evt && evt->IsAccel()) {
  1825. return false;
  1826. }
  1827. #endif
  1828. nsMenuChainItem* item = GetTopVisibleMenu();
  1829. if (!aFrame && item)
  1830. aFrame = item->Frame();
  1831. if (aFrame) {
  1832. bool action;
  1833. nsMenuFrame* result = aFrame->FindMenuWithShortcut(aKeyEvent, action);
  1834. if (result) {
  1835. aFrame->ChangeMenuItem(result, false, true);
  1836. if (action) {
  1837. WidgetGUIEvent* evt = aKeyEvent->AsEvent()->WidgetEventPtr()->AsGUIEvent();
  1838. nsMenuFrame* menuToOpen = result->Enter(evt);
  1839. if (menuToOpen) {
  1840. nsCOMPtr<nsIContent> content = menuToOpen->GetContent();
  1841. ShowMenu(content, true, false);
  1842. }
  1843. }
  1844. return true;
  1845. }
  1846. return false;
  1847. }
  1848. if (mActiveMenuBar) {
  1849. nsMenuFrame* result = mActiveMenuBar->FindMenuWithShortcut(aKeyEvent);
  1850. if (result) {
  1851. mActiveMenuBar->SetActive(true);
  1852. result->OpenMenu(true);
  1853. return true;
  1854. }
  1855. }
  1856. return false;
  1857. }
  1858. bool
  1859. nsXULPopupManager::HandleKeyboardNavigation(uint32_t aKeyCode)
  1860. {
  1861. // navigate up through the open menus, looking for the topmost one
  1862. // in the same hierarchy
  1863. nsMenuChainItem* item = nullptr;
  1864. nsMenuChainItem* nextitem = GetTopVisibleMenu();
  1865. while (nextitem) {
  1866. item = nextitem;
  1867. nextitem = item->GetParent();
  1868. if (nextitem) {
  1869. // stop if the parent isn't a menu
  1870. if (!nextitem->IsMenu())
  1871. break;
  1872. // check to make sure that the parent is actually the parent menu. It won't
  1873. // be if the parent is in a different frame hierarchy, for example, for a
  1874. // context menu opened on another menu.
  1875. nsMenuParent* expectedParent = static_cast<nsMenuParent *>(nextitem->Frame());
  1876. nsMenuFrame* menuFrame = do_QueryFrame(item->Frame()->GetParent());
  1877. if (!menuFrame || menuFrame->GetMenuParent() != expectedParent) {
  1878. break;
  1879. }
  1880. }
  1881. }
  1882. nsIFrame* itemFrame;
  1883. if (item)
  1884. itemFrame = item->Frame();
  1885. else if (mActiveMenuBar)
  1886. itemFrame = mActiveMenuBar;
  1887. else
  1888. return false;
  1889. nsNavigationDirection theDirection;
  1890. NS_ASSERTION(aKeyCode >= nsIDOMKeyEvent::DOM_VK_END &&
  1891. aKeyCode <= nsIDOMKeyEvent::DOM_VK_DOWN, "Illegal key code");
  1892. theDirection = NS_DIRECTION_FROM_KEY_CODE(itemFrame, aKeyCode);
  1893. // if a popup is open, first check for navigation within the popup
  1894. if (item && HandleKeyboardNavigationInPopup(item, theDirection))
  1895. return true;
  1896. // no popup handled the key, so check the active menubar, if any
  1897. if (mActiveMenuBar) {
  1898. nsMenuFrame* currentMenu = mActiveMenuBar->GetCurrentMenuItem();
  1899. if (NS_DIRECTION_IS_INLINE(theDirection)) {
  1900. nsMenuFrame* nextItem = (theDirection == eNavigationDirection_End) ?
  1901. GetNextMenuItem(mActiveMenuBar, currentMenu, false) :
  1902. GetPreviousMenuItem(mActiveMenuBar, currentMenu, false);
  1903. mActiveMenuBar->ChangeMenuItem(nextItem, true, true);
  1904. return true;
  1905. }
  1906. else if (NS_DIRECTION_IS_BLOCK(theDirection)) {
  1907. // Open the menu and select its first item.
  1908. if (currentMenu) {
  1909. nsCOMPtr<nsIContent> content = currentMenu->GetContent();
  1910. ShowMenu(content, true, false);
  1911. }
  1912. return true;
  1913. }
  1914. }
  1915. return false;
  1916. }
  1917. bool
  1918. nsXULPopupManager::HandleKeyboardNavigationInPopup(nsMenuChainItem* item,
  1919. nsMenuPopupFrame* aFrame,
  1920. nsNavigationDirection aDir)
  1921. {
  1922. NS_ASSERTION(aFrame, "aFrame is null");
  1923. NS_ASSERTION(!item || item->Frame() == aFrame,
  1924. "aFrame is expected to be equal to item->Frame()");
  1925. nsMenuFrame* currentMenu = aFrame->GetCurrentMenuItem();
  1926. aFrame->ClearIncrementalString();
  1927. // This method only gets called if we're open.
  1928. if (!currentMenu && NS_DIRECTION_IS_INLINE(aDir)) {
  1929. // We've been opened, but we haven't had anything selected.
  1930. // We can handle End, but our parent handles Start.
  1931. if (aDir == eNavigationDirection_End) {
  1932. nsMenuFrame* nextItem = GetNextMenuItem(aFrame, nullptr, true);
  1933. if (nextItem) {
  1934. aFrame->ChangeMenuItem(nextItem, false, true);
  1935. return true;
  1936. }
  1937. }
  1938. return false;
  1939. }
  1940. bool isContainer = false;
  1941. bool isOpen = false;
  1942. if (currentMenu) {
  1943. isOpen = currentMenu->IsOpen();
  1944. isContainer = currentMenu->IsMenu();
  1945. if (isOpen) {
  1946. // for an open popup, have the child process the event
  1947. nsMenuChainItem* child = item ? item->GetChild() : nullptr;
  1948. if (child && HandleKeyboardNavigationInPopup(child, aDir))
  1949. return true;
  1950. }
  1951. else if (aDir == eNavigationDirection_End &&
  1952. isContainer && !currentMenu->IsDisabled()) {
  1953. // The menu is not yet open. Open it and select the first item.
  1954. nsCOMPtr<nsIContent> content = currentMenu->GetContent();
  1955. ShowMenu(content, true, false);
  1956. return true;
  1957. }
  1958. }
  1959. // For block progression, we can move in either direction
  1960. if (NS_DIRECTION_IS_BLOCK(aDir) ||
  1961. NS_DIRECTION_IS_BLOCK_TO_EDGE(aDir)) {
  1962. nsMenuFrame* nextItem;
  1963. if (aDir == eNavigationDirection_Before)
  1964. nextItem = GetPreviousMenuItem(aFrame, currentMenu, true);
  1965. else if (aDir == eNavigationDirection_After)
  1966. nextItem = GetNextMenuItem(aFrame, currentMenu, true);
  1967. else if (aDir == eNavigationDirection_First)
  1968. nextItem = GetNextMenuItem(aFrame, nullptr, true);
  1969. else
  1970. nextItem = GetPreviousMenuItem(aFrame, nullptr, true);
  1971. if (nextItem) {
  1972. aFrame->ChangeMenuItem(nextItem, false, true);
  1973. return true;
  1974. }
  1975. }
  1976. else if (currentMenu && isContainer && isOpen) {
  1977. if (aDir == eNavigationDirection_Start) {
  1978. // close a submenu when Left is pressed
  1979. nsMenuPopupFrame* popupFrame = currentMenu->GetPopup();
  1980. if (popupFrame)
  1981. HidePopup(popupFrame->GetContent(), false, false, false, false);
  1982. return true;
  1983. }
  1984. }
  1985. return false;
  1986. }
  1987. bool
  1988. nsXULPopupManager::HandleKeyboardEventWithKeyCode(
  1989. nsIDOMKeyEvent* aKeyEvent,
  1990. nsMenuChainItem* aTopVisibleMenuItem)
  1991. {
  1992. uint32_t keyCode;
  1993. aKeyEvent->GetKeyCode(&keyCode);
  1994. // Escape should close panels, but the other keys should have no effect.
  1995. if (aTopVisibleMenuItem &&
  1996. aTopVisibleMenuItem->PopupType() != ePopupTypeMenu) {
  1997. if (keyCode == nsIDOMKeyEvent::DOM_VK_ESCAPE) {
  1998. HidePopup(aTopVisibleMenuItem->Content(), false, false, false, true);
  1999. aKeyEvent->AsEvent()->StopPropagation();
  2000. aKeyEvent->AsEvent()->StopCrossProcessForwarding();
  2001. aKeyEvent->AsEvent()->PreventDefault();
  2002. }
  2003. return true;
  2004. }
  2005. bool consume = (mPopups || mActiveMenuBar);
  2006. switch (keyCode) {
  2007. case nsIDOMKeyEvent::DOM_VK_UP:
  2008. case nsIDOMKeyEvent::DOM_VK_DOWN:
  2009. // roll up the popup when alt+up/down are pressed within a menulist.
  2010. bool alt;
  2011. aKeyEvent->GetAltKey(&alt);
  2012. if (alt && aTopVisibleMenuItem && aTopVisibleMenuItem->Frame()->IsMenuList()) {
  2013. Rollup(0, false, nullptr, nullptr);
  2014. break;
  2015. }
  2016. MOZ_FALLTHROUGH;
  2017. case nsIDOMKeyEvent::DOM_VK_LEFT:
  2018. case nsIDOMKeyEvent::DOM_VK_RIGHT:
  2019. case nsIDOMKeyEvent::DOM_VK_HOME:
  2020. case nsIDOMKeyEvent::DOM_VK_END:
  2021. HandleKeyboardNavigation(keyCode);
  2022. break;
  2023. case nsIDOMKeyEvent::DOM_VK_PAGE_DOWN:
  2024. case nsIDOMKeyEvent::DOM_VK_PAGE_UP:
  2025. if (aTopVisibleMenuItem) {
  2026. aTopVisibleMenuItem->Frame()->ChangeByPage(keyCode == nsIDOMKeyEvent::DOM_VK_PAGE_UP);
  2027. }
  2028. break;
  2029. case nsIDOMKeyEvent::DOM_VK_ESCAPE:
  2030. // Pressing Escape hides one level of menus only. If no menu is open,
  2031. // check if a menubar is active and inform it that a menu closed. Even
  2032. // though in this latter case, a menu didn't actually close, the effect
  2033. // ends up being the same. Similar for the tab key below.
  2034. if (aTopVisibleMenuItem) {
  2035. HidePopup(aTopVisibleMenuItem->Content(), false, false, false, true);
  2036. } else if (mActiveMenuBar) {
  2037. mActiveMenuBar->MenuClosed();
  2038. }
  2039. break;
  2040. case nsIDOMKeyEvent::DOM_VK_TAB:
  2041. case nsIDOMKeyEvent::DOM_VK_F10:
  2042. if (aTopVisibleMenuItem &&
  2043. !aTopVisibleMenuItem->Frame()->GetContent()->AttrValueIs(kNameSpaceID_None,
  2044. nsGkAtoms::activateontab, nsGkAtoms::_true, eCaseMatters)) {
  2045. // close popups or deactivate menubar when Tab or F10 are pressed
  2046. Rollup(0, false, nullptr, nullptr);
  2047. break;
  2048. } else if (mActiveMenuBar) {
  2049. mActiveMenuBar->MenuClosed();
  2050. break;
  2051. }
  2052. // Intentional fall-through to RETURN case
  2053. MOZ_FALLTHROUGH;
  2054. case nsIDOMKeyEvent::DOM_VK_RETURN: {
  2055. // If there is a popup open, check if the current item needs to be opened.
  2056. // Otherwise, tell the active menubar, if any, to activate the menu. The
  2057. // Enter method will return a menu if one needs to be opened as a result.
  2058. nsMenuFrame* menuToOpen = nullptr;
  2059. WidgetGUIEvent* GUIEvent = aKeyEvent->AsEvent()->
  2060. WidgetEventPtr()->AsGUIEvent();
  2061. if (aTopVisibleMenuItem) {
  2062. menuToOpen = aTopVisibleMenuItem->Frame()->Enter(GUIEvent);
  2063. } else if (mActiveMenuBar) {
  2064. menuToOpen = mActiveMenuBar->Enter(GUIEvent);
  2065. }
  2066. if (menuToOpen) {
  2067. nsCOMPtr<nsIContent> content = menuToOpen->GetContent();
  2068. ShowMenu(content, true, false);
  2069. }
  2070. break;
  2071. }
  2072. default:
  2073. return false;
  2074. }
  2075. if (consume) {
  2076. aKeyEvent->AsEvent()->StopPropagation();
  2077. aKeyEvent->AsEvent()->StopCrossProcessForwarding();
  2078. aKeyEvent->AsEvent()->PreventDefault();
  2079. }
  2080. return true;
  2081. }
  2082. nsMenuFrame*
  2083. nsXULPopupManager::GetNextMenuItem(nsContainerFrame* aParent,
  2084. nsMenuFrame* aStart,
  2085. bool aIsPopup)
  2086. {
  2087. nsPresContext* presContext = aParent->PresContext();
  2088. auto insertion = presContext->PresShell()->
  2089. FrameConstructor()->GetInsertionPoint(aParent->GetContent(), nullptr);
  2090. nsContainerFrame* immediateParent = insertion.mParentFrame;
  2091. if (!immediateParent)
  2092. immediateParent = aParent;
  2093. nsIFrame* currFrame = nullptr;
  2094. if (aStart) {
  2095. if (aStart->GetNextSibling())
  2096. currFrame = aStart->GetNextSibling();
  2097. else if (aStart->GetParent()->GetContent()->IsXULElement(nsGkAtoms::menugroup))
  2098. currFrame = aStart->GetParent()->GetNextSibling();
  2099. }
  2100. else
  2101. currFrame = immediateParent->PrincipalChildList().FirstChild();
  2102. while (currFrame) {
  2103. // See if it's a menu item.
  2104. nsIContent* currFrameContent = currFrame->GetContent();
  2105. if (IsValidMenuItem(currFrameContent, aIsPopup)) {
  2106. return do_QueryFrame(currFrame);
  2107. }
  2108. if (currFrameContent->IsXULElement(nsGkAtoms::menugroup) &&
  2109. currFrameContent->GetChildCount() > 0)
  2110. currFrame = currFrame->PrincipalChildList().FirstChild();
  2111. else if (!currFrame->GetNextSibling() &&
  2112. currFrame->GetParent()->GetContent()->IsXULElement(nsGkAtoms::menugroup))
  2113. currFrame = currFrame->GetParent()->GetNextSibling();
  2114. else
  2115. currFrame = currFrame->GetNextSibling();
  2116. }
  2117. currFrame = immediateParent->PrincipalChildList().FirstChild();
  2118. // Still don't have anything. Try cycling from the beginning.
  2119. while (currFrame && currFrame != aStart) {
  2120. // See if it's a menu item.
  2121. nsIContent* currFrameContent = currFrame->GetContent();
  2122. if (IsValidMenuItem(currFrameContent, aIsPopup)) {
  2123. return do_QueryFrame(currFrame);
  2124. }
  2125. if (currFrameContent->IsXULElement(nsGkAtoms::menugroup) &&
  2126. currFrameContent->GetChildCount() > 0)
  2127. currFrame = currFrame->PrincipalChildList().FirstChild();
  2128. else if (!currFrame->GetNextSibling() &&
  2129. currFrame->GetParent()->GetContent()->IsXULElement(nsGkAtoms::menugroup))
  2130. currFrame = currFrame->GetParent()->GetNextSibling();
  2131. else
  2132. currFrame = currFrame->GetNextSibling();
  2133. }
  2134. // No luck. Just return our start value.
  2135. return aStart;
  2136. }
  2137. nsMenuFrame*
  2138. nsXULPopupManager::GetPreviousMenuItem(nsContainerFrame* aParent,
  2139. nsMenuFrame* aStart,
  2140. bool aIsPopup)
  2141. {
  2142. nsPresContext* presContext = aParent->PresContext();
  2143. auto insertion = presContext->PresShell()->
  2144. FrameConstructor()->GetInsertionPoint(aParent->GetContent(), nullptr);
  2145. nsContainerFrame* immediateParent = insertion.mParentFrame;
  2146. if (!immediateParent)
  2147. immediateParent = aParent;
  2148. const nsFrameList& frames(immediateParent->PrincipalChildList());
  2149. nsIFrame* currFrame = nullptr;
  2150. if (aStart) {
  2151. if (aStart->GetPrevSibling())
  2152. currFrame = aStart->GetPrevSibling();
  2153. else if (aStart->GetParent()->GetContent()->IsXULElement(nsGkAtoms::menugroup))
  2154. currFrame = aStart->GetParent()->GetPrevSibling();
  2155. }
  2156. else
  2157. currFrame = frames.LastChild();
  2158. while (currFrame) {
  2159. // See if it's a menu item.
  2160. nsIContent* currFrameContent = currFrame->GetContent();
  2161. if (IsValidMenuItem(currFrameContent, aIsPopup)) {
  2162. return do_QueryFrame(currFrame);
  2163. }
  2164. if (currFrameContent->IsXULElement(nsGkAtoms::menugroup) &&
  2165. currFrameContent->GetChildCount() > 0) {
  2166. const nsFrameList& menugroupFrames(currFrame->PrincipalChildList());
  2167. currFrame = menugroupFrames.LastChild();
  2168. }
  2169. else if (!currFrame->GetPrevSibling() &&
  2170. currFrame->GetParent()->GetContent()->IsXULElement(nsGkAtoms::menugroup))
  2171. currFrame = currFrame->GetParent()->GetPrevSibling();
  2172. else
  2173. currFrame = currFrame->GetPrevSibling();
  2174. }
  2175. currFrame = frames.LastChild();
  2176. // Still don't have anything. Try cycling from the end.
  2177. while (currFrame && currFrame != aStart) {
  2178. // See if it's a menu item.
  2179. nsIContent* currFrameContent = currFrame->GetContent();
  2180. if (IsValidMenuItem(currFrameContent, aIsPopup)) {
  2181. return do_QueryFrame(currFrame);
  2182. }
  2183. if (currFrameContent->IsXULElement(nsGkAtoms::menugroup) &&
  2184. currFrameContent->GetChildCount() > 0) {
  2185. const nsFrameList& menugroupFrames(currFrame->PrincipalChildList());
  2186. currFrame = menugroupFrames.LastChild();
  2187. }
  2188. else if (!currFrame->GetPrevSibling() &&
  2189. currFrame->GetParent()->GetContent()->IsXULElement(nsGkAtoms::menugroup))
  2190. currFrame = currFrame->GetParent()->GetPrevSibling();
  2191. else
  2192. currFrame = currFrame->GetPrevSibling();
  2193. }
  2194. // No luck. Just return our start value.
  2195. return aStart;
  2196. }
  2197. bool
  2198. nsXULPopupManager::IsValidMenuItem(nsIContent* aContent, bool aOnPopup)
  2199. {
  2200. if (aContent->IsXULElement()) {
  2201. if (!aContent->IsAnyOfXULElements(nsGkAtoms::menu, nsGkAtoms::menuitem)) {
  2202. return false;
  2203. }
  2204. }
  2205. else if (!aOnPopup || !aContent->IsHTMLElement(nsGkAtoms::option)) {
  2206. return false;
  2207. }
  2208. nsMenuFrame* menuFrame = do_QueryFrame(aContent->GetPrimaryFrame());
  2209. bool skipNavigatingDisabledMenuItem = true;
  2210. if (aOnPopup && (!menuFrame || menuFrame->GetParentMenuListType() == eNotMenuList)) {
  2211. skipNavigatingDisabledMenuItem =
  2212. LookAndFeel::GetInt(LookAndFeel::eIntID_SkipNavigatingDisabledMenuItem,
  2213. 0) != 0;
  2214. }
  2215. return !(skipNavigatingDisabledMenuItem &&
  2216. aContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::disabled,
  2217. nsGkAtoms::_true, eCaseMatters));
  2218. }
  2219. nsresult
  2220. nsXULPopupManager::HandleEvent(nsIDOMEvent* aEvent)
  2221. {
  2222. nsCOMPtr<nsIDOMKeyEvent> keyEvent = do_QueryInterface(aEvent);
  2223. NS_ENSURE_TRUE(keyEvent, NS_ERROR_UNEXPECTED);
  2224. //handlers shouldn't be triggered by non-trusted events.
  2225. bool trustedEvent = false;
  2226. aEvent->GetIsTrusted(&trustedEvent);
  2227. if (!trustedEvent) {
  2228. return NS_OK;
  2229. }
  2230. nsAutoString eventType;
  2231. aEvent->GetType(eventType);
  2232. if (eventType.EqualsLiteral("keyup")) {
  2233. return KeyUp(keyEvent);
  2234. }
  2235. if (eventType.EqualsLiteral("keydown")) {
  2236. return KeyDown(keyEvent);
  2237. }
  2238. if (eventType.EqualsLiteral("keypress")) {
  2239. return KeyPress(keyEvent);
  2240. }
  2241. NS_ABORT();
  2242. return NS_OK;
  2243. }
  2244. nsresult
  2245. nsXULPopupManager::KeyUp(nsIDOMKeyEvent* aKeyEvent)
  2246. {
  2247. // don't do anything if a menu isn't open or a menubar isn't active
  2248. if (!mActiveMenuBar) {
  2249. nsMenuChainItem* item = GetTopVisibleMenu();
  2250. if (!item || item->PopupType() != ePopupTypeMenu)
  2251. return NS_OK;
  2252. if (item->IgnoreKeys() == eIgnoreKeys_Shortcuts) {
  2253. aKeyEvent->AsEvent()->StopCrossProcessForwarding();
  2254. return NS_OK;
  2255. }
  2256. }
  2257. aKeyEvent->AsEvent()->StopPropagation();
  2258. aKeyEvent->AsEvent()->StopCrossProcessForwarding();
  2259. aKeyEvent->AsEvent()->PreventDefault();
  2260. return NS_OK; // I am consuming event
  2261. }
  2262. nsresult
  2263. nsXULPopupManager::KeyDown(nsIDOMKeyEvent* aKeyEvent)
  2264. {
  2265. nsMenuChainItem* item = GetTopVisibleMenu();
  2266. if (item && item->Frame()->IsMenuLocked())
  2267. return NS_OK;
  2268. if (HandleKeyboardEventWithKeyCode(aKeyEvent, item)) {
  2269. return NS_OK;
  2270. }
  2271. // don't do anything if a menu isn't open or a menubar isn't active
  2272. if (!mActiveMenuBar && (!item || item->PopupType() != ePopupTypeMenu))
  2273. return NS_OK;
  2274. // Since a menu was open, stop propagation of the event to keep other event
  2275. // listeners from becoming confused.
  2276. if (!item || item->IgnoreKeys() != eIgnoreKeys_Shortcuts) {
  2277. aKeyEvent->AsEvent()->StopPropagation();
  2278. }
  2279. int32_t menuAccessKey = -1;
  2280. // If the key just pressed is the access key (usually Alt),
  2281. // dismiss and unfocus the menu.
  2282. nsMenuBarListener::GetMenuAccessKey(&menuAccessKey);
  2283. if (menuAccessKey) {
  2284. uint32_t theChar;
  2285. aKeyEvent->GetKeyCode(&theChar);
  2286. if (theChar == (uint32_t)menuAccessKey) {
  2287. bool ctrl = false;
  2288. if (menuAccessKey != nsIDOMKeyEvent::DOM_VK_CONTROL)
  2289. aKeyEvent->GetCtrlKey(&ctrl);
  2290. bool alt=false;
  2291. if (menuAccessKey != nsIDOMKeyEvent::DOM_VK_ALT)
  2292. aKeyEvent->GetAltKey(&alt);
  2293. bool shift=false;
  2294. if (menuAccessKey != nsIDOMKeyEvent::DOM_VK_SHIFT)
  2295. aKeyEvent->GetShiftKey(&shift);
  2296. bool meta=false;
  2297. if (menuAccessKey != nsIDOMKeyEvent::DOM_VK_META)
  2298. aKeyEvent->GetMetaKey(&meta);
  2299. if (!(ctrl || alt || shift || meta)) {
  2300. // The access key just went down and no other
  2301. // modifiers are already down.
  2302. nsMenuChainItem* item = GetTopVisibleMenu();
  2303. if (mPopups && item && !item->Frame()->IsMenuList()) {
  2304. Rollup(0, false, nullptr, nullptr);
  2305. } else if (mActiveMenuBar) {
  2306. mActiveMenuBar->MenuClosed();
  2307. }
  2308. // Clear the item to avoid bugs as it may have been deleted during rollup.
  2309. item = nullptr;
  2310. }
  2311. aKeyEvent->AsEvent()->StopPropagation();
  2312. aKeyEvent->AsEvent()->PreventDefault();
  2313. }
  2314. }
  2315. aKeyEvent->AsEvent()->StopCrossProcessForwarding();
  2316. return NS_OK;
  2317. }
  2318. nsresult
  2319. nsXULPopupManager::KeyPress(nsIDOMKeyEvent* aKeyEvent)
  2320. {
  2321. // Don't check prevent default flag -- menus always get first shot at key events.
  2322. nsMenuChainItem* item = GetTopVisibleMenu();
  2323. if (item &&
  2324. (item->Frame()->IsMenuLocked() || item->PopupType() != ePopupTypeMenu)) {
  2325. return NS_OK;
  2326. }
  2327. nsCOMPtr<nsIDOMKeyEvent> keyEvent = do_QueryInterface(aKeyEvent);
  2328. NS_ENSURE_TRUE(keyEvent, NS_ERROR_UNEXPECTED);
  2329. // if a menu is open or a menubar is active, it consumes the key event
  2330. bool consume = (mPopups || mActiveMenuBar);
  2331. WidgetInputEvent* evt = aKeyEvent->AsEvent()->WidgetEventPtr()->AsInputEvent();
  2332. bool isAccel = evt && evt->IsAccel();
  2333. // When ignorekeys="shortcuts" is used, we don't call preventDefault on the
  2334. // key event when the accelerator key is pressed. This allows another
  2335. // listener to handle keys. For instance, this allows global shortcuts to
  2336. // still apply while a menu is open.
  2337. if (item && item->IgnoreKeys() == eIgnoreKeys_Shortcuts && isAccel) {
  2338. consume = false;
  2339. }
  2340. HandleShortcutNavigation(keyEvent, nullptr);
  2341. aKeyEvent->AsEvent()->StopCrossProcessForwarding();
  2342. if (consume) {
  2343. aKeyEvent->AsEvent()->StopPropagation();
  2344. aKeyEvent->AsEvent()->PreventDefault();
  2345. }
  2346. return NS_OK; // I am consuming event
  2347. }
  2348. NS_IMETHODIMP
  2349. nsXULPopupShowingEvent::Run()
  2350. {
  2351. nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
  2352. if (pm) {
  2353. pm->FirePopupShowingEvent(mPopup, mIsContextMenu, mSelectFirstItem);
  2354. }
  2355. return NS_OK;
  2356. }
  2357. NS_IMETHODIMP
  2358. nsXULPopupHidingEvent::Run()
  2359. {
  2360. nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
  2361. nsIDocument *document = mPopup->GetUncomposedDoc();
  2362. if (pm && document) {
  2363. nsIPresShell* presShell = document->GetShell();
  2364. if (presShell) {
  2365. nsPresContext* context = presShell->GetPresContext();
  2366. if (context) {
  2367. pm->FirePopupHidingEvent(mPopup, mNextPopup, mLastPopup,
  2368. context, mPopupType, mDeselectMenu, mIsRollup);
  2369. }
  2370. }
  2371. }
  2372. return NS_OK;
  2373. }
  2374. bool
  2375. nsXULPopupPositionedEvent::DispatchIfNeeded(nsIContent *aPopup,
  2376. bool aIsContextMenu,
  2377. bool aSelectFirstItem)
  2378. {
  2379. // The popuppositioned event only fires on arrow panels for now.
  2380. if (aPopup->AttrValueIs(kNameSpaceID_None, nsGkAtoms::type,
  2381. nsGkAtoms::arrow, eCaseMatters)) {
  2382. nsCOMPtr<nsIRunnable> event =
  2383. new nsXULPopupPositionedEvent(aPopup, aIsContextMenu, aSelectFirstItem);
  2384. NS_DispatchToCurrentThread(event);
  2385. return true;
  2386. }
  2387. return false;
  2388. }
  2389. NS_IMETHODIMP
  2390. nsXULPopupPositionedEvent::Run()
  2391. {
  2392. nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
  2393. if (pm) {
  2394. nsMenuPopupFrame* popupFrame = do_QueryFrame(mPopup->GetPrimaryFrame());
  2395. if (popupFrame) {
  2396. // At this point, hidePopup may have been called but it currently has no
  2397. // way to stop this event. However, if hidePopup was called, the popup
  2398. // will now be in the hiding or closed state. If we are in the shown or
  2399. // positioning state instead, we can assume that we are still clear to
  2400. // open/move the popup
  2401. nsPopupState state = popupFrame->PopupState();
  2402. if (state != ePopupPositioning && state != ePopupShown) {
  2403. return NS_OK;
  2404. }
  2405. nsEventStatus status = nsEventStatus_eIgnore;
  2406. WidgetMouseEvent event(true, eXULPopupPositioned, nullptr,
  2407. WidgetMouseEvent::eReal);
  2408. EventDispatcher::Dispatch(mPopup, popupFrame->PresContext(),
  2409. &event, nullptr, &status);
  2410. // Get the popup frame and make sure it is still in the positioning
  2411. // state. If it isn't, someone may have tried to reshow or hide it
  2412. // during the popuppositioned event.
  2413. // Alternately, this event may have been fired in reponse to moving the
  2414. // popup rather than opening it. In that case, we are done.
  2415. nsMenuPopupFrame* popupFrame = do_QueryFrame(mPopup->GetPrimaryFrame());
  2416. if (popupFrame && popupFrame->PopupState() == ePopupPositioning) {
  2417. pm->ShowPopupCallback(mPopup, popupFrame, mIsContextMenu, mSelectFirstItem);
  2418. }
  2419. }
  2420. }
  2421. return NS_OK;
  2422. }
  2423. NS_IMETHODIMP
  2424. nsXULMenuCommandEvent::Run()
  2425. {
  2426. nsXULPopupManager* pm = nsXULPopupManager::GetInstance();
  2427. if (!pm)
  2428. return NS_OK;
  2429. // The order of the nsViewManager and nsIPresShell COM pointers is
  2430. // important below. We want the pres shell to get released before the
  2431. // associated view manager on exit from this function.
  2432. // See bug 54233.
  2433. // XXXndeakin is this still needed?
  2434. nsCOMPtr<nsIContent> popup;
  2435. nsMenuFrame* menuFrame = do_QueryFrame(mMenu->GetPrimaryFrame());
  2436. nsWeakFrame weakFrame(menuFrame);
  2437. if (menuFrame && mFlipChecked) {
  2438. if (menuFrame->IsChecked()) {
  2439. mMenu->UnsetAttr(kNameSpaceID_None, nsGkAtoms::checked, true);
  2440. } else {
  2441. mMenu->SetAttr(kNameSpaceID_None, nsGkAtoms::checked,
  2442. NS_LITERAL_STRING("true"), true);
  2443. }
  2444. }
  2445. if (menuFrame && weakFrame.IsAlive()) {
  2446. // Find the popup that the menu is inside. Below, this popup will
  2447. // need to be hidden.
  2448. nsIFrame* frame = menuFrame->GetParent();
  2449. while (frame) {
  2450. nsMenuPopupFrame* popupFrame = do_QueryFrame(frame);
  2451. if (popupFrame) {
  2452. popup = popupFrame->GetContent();
  2453. break;
  2454. }
  2455. frame = frame->GetParent();
  2456. }
  2457. nsPresContext* presContext = menuFrame->PresContext();
  2458. nsCOMPtr<nsIPresShell> shell = presContext->PresShell();
  2459. RefPtr<nsViewManager> kungFuDeathGrip = shell->GetViewManager();
  2460. mozilla::Unused << kungFuDeathGrip; // Not referred to directly within this function
  2461. // Deselect ourselves.
  2462. if (mCloseMenuMode != CloseMenuMode_None)
  2463. menuFrame->SelectMenu(false);
  2464. AutoHandlingUserInputStatePusher userInpStatePusher(mUserInput, nullptr,
  2465. shell->GetDocument());
  2466. nsContentUtils::DispatchXULCommand(mMenu, mIsTrusted, nullptr, shell,
  2467. mControl, mAlt, mShift, mMeta);
  2468. }
  2469. if (popup && mCloseMenuMode != CloseMenuMode_None)
  2470. pm->HidePopup(popup, mCloseMenuMode == CloseMenuMode_Auto, true, false, false);
  2471. return NS_OK;
  2472. }