Accessible.cpp 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858
  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 "Accessible-inl.h"
  6. #include "nsIXBLAccessible.h"
  7. #include "EmbeddedObjCollector.h"
  8. #include "AccGroupInfo.h"
  9. #include "AccIterator.h"
  10. #include "nsAccUtils.h"
  11. #include "nsAccessibilityService.h"
  12. #include "ApplicationAccessible.h"
  13. #include "NotificationController.h"
  14. #include "nsEventShell.h"
  15. #include "nsTextEquivUtils.h"
  16. #include "DocAccessibleChild.h"
  17. #include "EventTree.h"
  18. #include "Relation.h"
  19. #include "Role.h"
  20. #include "RootAccessible.h"
  21. #include "States.h"
  22. #include "StyleInfo.h"
  23. #include "TableAccessible.h"
  24. #include "TableCellAccessible.h"
  25. #include "TreeWalker.h"
  26. #include "nsIDOMElement.h"
  27. #include "nsIDOMNodeFilter.h"
  28. #include "nsIDOMHTMLElement.h"
  29. #include "nsIDOMKeyEvent.h"
  30. #include "nsIDOMTreeWalker.h"
  31. #include "nsIDOMXULButtonElement.h"
  32. #include "nsIDOMXULDocument.h"
  33. #include "nsIDOMXULElement.h"
  34. #include "nsIDOMXULLabelElement.h"
  35. #include "nsIDOMXULSelectCntrlEl.h"
  36. #include "nsIDOMXULSelectCntrlItemEl.h"
  37. #include "nsPIDOMWindow.h"
  38. #include "nsIDocument.h"
  39. #include "nsIContent.h"
  40. #include "nsIForm.h"
  41. #include "nsIFormControl.h"
  42. #include "nsDeckFrame.h"
  43. #include "nsLayoutUtils.h"
  44. #include "nsIPersistentProperties2.h"
  45. #include "nsIPresShell.h"
  46. #include "nsIStringBundle.h"
  47. #include "nsPresContext.h"
  48. #include "nsIFrame.h"
  49. #include "nsView.h"
  50. #include "nsIDocShellTreeItem.h"
  51. #include "nsIScrollableFrame.h"
  52. #include "nsFocusManager.h"
  53. #include "nsXPIDLString.h"
  54. #include "nsUnicharUtils.h"
  55. #include "nsReadableUtils.h"
  56. #include "prdtoa.h"
  57. #include "nsIAtom.h"
  58. #include "nsIURI.h"
  59. #include "nsArrayUtils.h"
  60. #include "nsIMutableArray.h"
  61. #include "nsIObserverService.h"
  62. #include "nsIServiceManager.h"
  63. #include "nsWhitespaceTokenizer.h"
  64. #include "nsAttrName.h"
  65. #ifdef DEBUG
  66. #include "nsIDOMCharacterData.h"
  67. #endif
  68. #include "mozilla/Assertions.h"
  69. #include "mozilla/BasicEvents.h"
  70. #include "mozilla/EventStates.h"
  71. #include "mozilla/FloatingPoint.h"
  72. #include "mozilla/MouseEvents.h"
  73. #include "mozilla/Unused.h"
  74. #include "mozilla/Preferences.h"
  75. #include "mozilla/dom/CanvasRenderingContext2D.h"
  76. #include "mozilla/dom/Element.h"
  77. #include "mozilla/dom/HTMLCanvasElement.h"
  78. #include "mozilla/dom/HTMLBodyElement.h"
  79. #include "mozilla/dom/TreeWalker.h"
  80. using namespace mozilla;
  81. using namespace mozilla::a11y;
  82. ////////////////////////////////////////////////////////////////////////////////
  83. // Accessible: nsISupports and cycle collection
  84. NS_IMPL_CYCLE_COLLECTION_CLASS(Accessible)
  85. NS_IMPL_CYCLE_COLLECTION_UNLINK_BEGIN(Accessible)
  86. tmp->Shutdown();
  87. NS_IMPL_CYCLE_COLLECTION_UNLINK_END
  88. NS_IMPL_CYCLE_COLLECTION_TRAVERSE_BEGIN(Accessible)
  89. NS_IMPL_CYCLE_COLLECTION_TRAVERSE(mContent, mDoc)
  90. NS_IMPL_CYCLE_COLLECTION_TRAVERSE_END
  91. NS_INTERFACE_MAP_BEGIN_CYCLE_COLLECTION(Accessible)
  92. if (aIID.Equals(NS_GET_IID(Accessible)))
  93. foundInterface = this;
  94. else
  95. NS_INTERFACE_MAP_ENTRY_AMBIGUOUS(nsISupports, Accessible)
  96. NS_INTERFACE_MAP_END
  97. NS_IMPL_CYCLE_COLLECTING_ADDREF(Accessible)
  98. NS_IMPL_CYCLE_COLLECTING_RELEASE_WITH_DESTROY(Accessible, LastRelease())
  99. Accessible::Accessible(nsIContent* aContent, DocAccessible* aDoc) :
  100. mContent(aContent), mDoc(aDoc),
  101. mParent(nullptr), mIndexInParent(-1),
  102. mRoleMapEntryIndex(aria::NO_ROLE_MAP_ENTRY_INDEX),
  103. mStateFlags(0), mContextFlags(0), mType(0), mGenericTypes(0),
  104. mReorderEventTarget(false), mShowEventTarget(false), mHideEventTarget(false)
  105. {
  106. mBits.groupInfo = nullptr;
  107. mInt.mIndexOfEmbeddedChild = -1;
  108. }
  109. Accessible::~Accessible()
  110. {
  111. NS_ASSERTION(!mDoc, "LastRelease was never called!?!");
  112. }
  113. ENameValueFlag
  114. Accessible::Name(nsString& aName)
  115. {
  116. aName.Truncate();
  117. if (!HasOwnContent())
  118. return eNameOK;
  119. ARIAName(aName);
  120. if (!aName.IsEmpty())
  121. return eNameOK;
  122. nsCOMPtr<nsIXBLAccessible> xblAccessible(do_QueryInterface(mContent));
  123. if (xblAccessible) {
  124. xblAccessible->GetAccessibleName(aName);
  125. if (!aName.IsEmpty())
  126. return eNameOK;
  127. }
  128. ENameValueFlag nameFlag = NativeName(aName);
  129. if (!aName.IsEmpty())
  130. return nameFlag;
  131. // In the end get the name from tooltip.
  132. if (mContent->IsHTMLElement()) {
  133. if (mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::title, aName)) {
  134. aName.CompressWhitespace();
  135. return eNameFromTooltip;
  136. }
  137. } else if (mContent->IsXULElement()) {
  138. if (mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::tooltiptext, aName)) {
  139. aName.CompressWhitespace();
  140. return eNameFromTooltip;
  141. }
  142. } else if (mContent->IsSVGElement()) {
  143. // If user agents need to choose among multiple ‘desc’ or ‘title’ elements
  144. // for processing, the user agent shall choose the first one.
  145. for (nsIContent* childElm = mContent->GetFirstChild(); childElm;
  146. childElm = childElm->GetNextSibling()) {
  147. if (childElm->IsSVGElement(nsGkAtoms::desc)) {
  148. nsTextEquivUtils::AppendTextEquivFromContent(this, childElm, &aName);
  149. return eNameFromTooltip;
  150. }
  151. }
  152. }
  153. if (nameFlag != eNoNameOnPurpose)
  154. aName.SetIsVoid(true);
  155. return nameFlag;
  156. }
  157. void
  158. Accessible::Description(nsString& aDescription)
  159. {
  160. // There are 4 conditions that make an accessible have no accDescription:
  161. // 1. it's a text node; or
  162. // 2. It has no DHTML describedby property
  163. // 3. it doesn't have an accName; or
  164. // 4. its title attribute already equals to its accName nsAutoString name;
  165. if (!HasOwnContent() || mContent->IsNodeOfType(nsINode::eTEXT))
  166. return;
  167. nsTextEquivUtils::
  168. GetTextEquivFromIDRefs(this, nsGkAtoms::aria_describedby,
  169. aDescription);
  170. if (aDescription.IsEmpty()) {
  171. NativeDescription(aDescription);
  172. if (aDescription.IsEmpty()) {
  173. // Keep the Name() method logic.
  174. if (mContent->IsHTMLElement()) {
  175. mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::title, aDescription);
  176. } else if (mContent->IsXULElement()) {
  177. mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::tooltiptext, aDescription);
  178. } else if (mContent->IsSVGElement()) {
  179. for (nsIContent* childElm = mContent->GetFirstChild(); childElm;
  180. childElm = childElm->GetNextSibling()) {
  181. if (childElm->IsSVGElement(nsGkAtoms::desc)) {
  182. nsTextEquivUtils::AppendTextEquivFromContent(this, childElm,
  183. &aDescription);
  184. break;
  185. }
  186. }
  187. }
  188. }
  189. }
  190. if (!aDescription.IsEmpty()) {
  191. aDescription.CompressWhitespace();
  192. nsAutoString name;
  193. Name(name);
  194. // Don't expose a description if it is the same as the name.
  195. if (aDescription.Equals(name))
  196. aDescription.Truncate();
  197. }
  198. }
  199. KeyBinding
  200. Accessible::AccessKey() const
  201. {
  202. if (!HasOwnContent())
  203. return KeyBinding();
  204. uint32_t key = nsCoreUtils::GetAccessKeyFor(mContent);
  205. if (!key && mContent->IsElement()) {
  206. Accessible* label = nullptr;
  207. // Copy access key from label node.
  208. if (mContent->IsHTMLElement()) {
  209. // Unless it is labeled via an ancestor <label>, in which case that would
  210. // be redundant.
  211. HTMLLabelIterator iter(Document(), this,
  212. HTMLLabelIterator::eSkipAncestorLabel);
  213. label = iter.Next();
  214. } else if (mContent->IsXULElement()) {
  215. XULLabelIterator iter(Document(), mContent);
  216. label = iter.Next();
  217. }
  218. if (label)
  219. key = nsCoreUtils::GetAccessKeyFor(label->GetContent());
  220. }
  221. if (!key)
  222. return KeyBinding();
  223. // Get modifier mask. Use ui.key.generalAccessKey (unless it is -1).
  224. switch (Preferences::GetInt("ui.key.generalAccessKey", -1)) {
  225. case -1:
  226. break;
  227. case nsIDOMKeyEvent::DOM_VK_SHIFT:
  228. return KeyBinding(key, KeyBinding::kShift);
  229. case nsIDOMKeyEvent::DOM_VK_CONTROL:
  230. return KeyBinding(key, KeyBinding::kControl);
  231. case nsIDOMKeyEvent::DOM_VK_ALT:
  232. return KeyBinding(key, KeyBinding::kAlt);
  233. case nsIDOMKeyEvent::DOM_VK_META:
  234. return KeyBinding(key, KeyBinding::kMeta);
  235. default:
  236. return KeyBinding();
  237. }
  238. // Determine the access modifier used in this context.
  239. nsIDocument* document = mContent->GetUncomposedDoc();
  240. if (!document)
  241. return KeyBinding();
  242. nsCOMPtr<nsIDocShellTreeItem> treeItem(document->GetDocShell());
  243. if (!treeItem)
  244. return KeyBinding();
  245. nsresult rv = NS_ERROR_FAILURE;
  246. int32_t modifierMask = 0;
  247. switch (treeItem->ItemType()) {
  248. case nsIDocShellTreeItem::typeChrome:
  249. rv = Preferences::GetInt("ui.key.chromeAccess", &modifierMask);
  250. break;
  251. case nsIDocShellTreeItem::typeContent:
  252. rv = Preferences::GetInt("ui.key.contentAccess", &modifierMask);
  253. break;
  254. }
  255. return NS_SUCCEEDED(rv) ? KeyBinding(key, modifierMask) : KeyBinding();
  256. }
  257. KeyBinding
  258. Accessible::KeyboardShortcut() const
  259. {
  260. return KeyBinding();
  261. }
  262. void
  263. Accessible::TranslateString(const nsString& aKey, nsAString& aStringOut)
  264. {
  265. nsCOMPtr<nsIStringBundleService> stringBundleService =
  266. services::GetStringBundleService();
  267. if (!stringBundleService)
  268. return;
  269. nsCOMPtr<nsIStringBundle> stringBundle;
  270. stringBundleService->CreateBundle(
  271. "chrome://global-platform/locale/accessible.properties",
  272. getter_AddRefs(stringBundle));
  273. if (!stringBundle)
  274. return;
  275. nsXPIDLString xsValue;
  276. nsresult rv = stringBundle->GetStringFromName(aKey.get(), getter_Copies(xsValue));
  277. if (NS_SUCCEEDED(rv))
  278. aStringOut.Assign(xsValue);
  279. }
  280. uint64_t
  281. Accessible::VisibilityState()
  282. {
  283. nsIFrame* frame = GetFrame();
  284. if (!frame)
  285. return states::INVISIBLE;
  286. // Walk the parent frame chain to see if there's invisible parent or the frame
  287. // is in background tab.
  288. if (!frame->StyleVisibility()->IsVisible())
  289. return states::INVISIBLE;
  290. nsIFrame* curFrame = frame;
  291. do {
  292. nsView* view = curFrame->GetView();
  293. if (view && view->GetVisibility() == nsViewVisibility_kHide)
  294. return states::INVISIBLE;
  295. if (nsLayoutUtils::IsPopup(curFrame))
  296. return 0;
  297. // Offscreen state for background tab content and invisible for not selected
  298. // deck panel.
  299. nsIFrame* parentFrame = curFrame->GetParent();
  300. nsDeckFrame* deckFrame = do_QueryFrame(parentFrame);
  301. if (deckFrame && deckFrame->GetSelectedBox() != curFrame) {
  302. if (deckFrame->GetContent()->IsXULElement(nsGkAtoms::tabpanels))
  303. return states::OFFSCREEN;
  304. NS_NOTREACHED("Children of not selected deck panel are not accessible.");
  305. return states::INVISIBLE;
  306. }
  307. // If contained by scrollable frame then check that at least 12 pixels
  308. // around the object is visible, otherwise the object is offscreen.
  309. nsIScrollableFrame* scrollableFrame = do_QueryFrame(parentFrame);
  310. if (scrollableFrame) {
  311. nsRect scrollPortRect = scrollableFrame->GetScrollPortRect();
  312. nsRect frameRect = nsLayoutUtils::TransformFrameRectToAncestor(
  313. frame, frame->GetRectRelativeToSelf(), parentFrame);
  314. if (!scrollPortRect.Contains(frameRect)) {
  315. const nscoord kMinPixels = nsPresContext::CSSPixelsToAppUnits(12);
  316. scrollPortRect.Deflate(kMinPixels, kMinPixels);
  317. if (!scrollPortRect.Intersects(frameRect))
  318. return states::OFFSCREEN;
  319. }
  320. }
  321. if (!parentFrame) {
  322. parentFrame = nsLayoutUtils::GetCrossDocParentFrame(curFrame);
  323. if (parentFrame && !parentFrame->StyleVisibility()->IsVisible())
  324. return states::INVISIBLE;
  325. }
  326. curFrame = parentFrame;
  327. } while (curFrame);
  328. // Zero area rects can occur in the first frame of a multi-frame text flow,
  329. // in which case the rendered text is not empty and the frame should not be
  330. // marked invisible.
  331. // XXX Can we just remove this check? Why do we need to mark empty
  332. // text invisible?
  333. if (frame->GetType() == nsGkAtoms::textFrame &&
  334. !(frame->GetStateBits() & NS_FRAME_OUT_OF_FLOW) &&
  335. frame->GetRect().IsEmpty()) {
  336. nsIFrame::RenderedText text = frame->GetRenderedText(0,
  337. UINT32_MAX, nsIFrame::TextOffsetType::OFFSETS_IN_CONTENT_TEXT,
  338. nsIFrame::TrailingWhitespace::DONT_TRIM_TRAILING_WHITESPACE);
  339. if (text.mString.IsEmpty()) {
  340. return states::INVISIBLE;
  341. }
  342. }
  343. return 0;
  344. }
  345. uint64_t
  346. Accessible::NativeState()
  347. {
  348. uint64_t state = 0;
  349. if (!IsInDocument())
  350. state |= states::STALE;
  351. if (HasOwnContent() && mContent->IsElement()) {
  352. EventStates elementState = mContent->AsElement()->State();
  353. if (elementState.HasState(NS_EVENT_STATE_INVALID))
  354. state |= states::INVALID;
  355. if (elementState.HasState(NS_EVENT_STATE_REQUIRED))
  356. state |= states::REQUIRED;
  357. state |= NativeInteractiveState();
  358. if (FocusMgr()->IsFocused(this))
  359. state |= states::FOCUSED;
  360. }
  361. // Gather states::INVISIBLE and states::OFFSCREEN flags for this object.
  362. state |= VisibilityState();
  363. nsIFrame *frame = GetFrame();
  364. if (frame) {
  365. if (frame->GetStateBits() & NS_FRAME_OUT_OF_FLOW)
  366. state |= states::FLOATING;
  367. // XXX we should look at layout for non XUL box frames, but need to decide
  368. // how that interacts with ARIA.
  369. if (HasOwnContent() && mContent->IsXULElement() && frame->IsXULBoxFrame()) {
  370. const nsStyleXUL* xulStyle = frame->StyleXUL();
  371. if (xulStyle && frame->IsXULBoxFrame()) {
  372. // In XUL all boxes are either vertical or horizontal
  373. if (xulStyle->mBoxOrient == StyleBoxOrient::Vertical)
  374. state |= states::VERTICAL;
  375. else
  376. state |= states::HORIZONTAL;
  377. }
  378. }
  379. }
  380. // Check if a XUL element has the popup attribute (an attached popup menu).
  381. if (HasOwnContent() && mContent->IsXULElement() &&
  382. mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::popup))
  383. state |= states::HASPOPUP;
  384. // Bypass the link states specialization for non links.
  385. const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
  386. if (!roleMapEntry || roleMapEntry->roleRule == kUseNativeRole ||
  387. roleMapEntry->role == roles::LINK)
  388. state |= NativeLinkState();
  389. return state;
  390. }
  391. uint64_t
  392. Accessible::NativeInteractiveState() const
  393. {
  394. if (!mContent->IsElement())
  395. return 0;
  396. if (NativelyUnavailable())
  397. return states::UNAVAILABLE;
  398. nsIFrame* frame = GetFrame();
  399. if (frame && frame->IsFocusable())
  400. return states::FOCUSABLE;
  401. return 0;
  402. }
  403. uint64_t
  404. Accessible::NativeLinkState() const
  405. {
  406. return 0;
  407. }
  408. bool
  409. Accessible::NativelyUnavailable() const
  410. {
  411. if (mContent->IsHTMLElement())
  412. return mContent->AsElement()->State().HasState(NS_EVENT_STATE_DISABLED);
  413. return mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::disabled,
  414. nsGkAtoms::_true, eCaseMatters);
  415. }
  416. Accessible*
  417. Accessible::FocusedChild()
  418. {
  419. Accessible* focus = FocusMgr()->FocusedAccessible();
  420. if (focus && (focus == this || focus->Parent() == this))
  421. return focus;
  422. return nullptr;
  423. }
  424. Accessible*
  425. Accessible::ChildAtPoint(int32_t aX, int32_t aY,
  426. EWhichChildAtPoint aWhichChild)
  427. {
  428. // If we can't find the point in a child, we will return the fallback answer:
  429. // we return |this| if the point is within it, otherwise nullptr.
  430. Accessible* fallbackAnswer = nullptr;
  431. nsIntRect rect = Bounds();
  432. if (aX >= rect.x && aX < rect.x + rect.width &&
  433. aY >= rect.y && aY < rect.y + rect.height)
  434. fallbackAnswer = this;
  435. if (nsAccUtils::MustPrune(this)) // Do not dig any further
  436. return fallbackAnswer;
  437. // Search an accessible at the given point starting from accessible document
  438. // because containing block (see CSS2) for out of flow element (for example,
  439. // absolutely positioned element) may be different from its DOM parent and
  440. // therefore accessible for containing block may be different from accessible
  441. // for DOM parent but GetFrameForPoint() should be called for containing block
  442. // to get an out of flow element.
  443. DocAccessible* accDocument = Document();
  444. NS_ENSURE_TRUE(accDocument, nullptr);
  445. nsIFrame* rootFrame = accDocument->GetFrame();
  446. NS_ENSURE_TRUE(rootFrame, nullptr);
  447. nsIFrame* startFrame = rootFrame;
  448. // Check whether the point is at popup content.
  449. nsIWidget* rootWidget = rootFrame->GetView()->GetNearestWidget(nullptr);
  450. NS_ENSURE_TRUE(rootWidget, nullptr);
  451. LayoutDeviceIntRect rootRect = rootWidget->GetScreenBounds();
  452. WidgetMouseEvent dummyEvent(true, eMouseMove, rootWidget,
  453. WidgetMouseEvent::eSynthesized);
  454. dummyEvent.mRefPoint = LayoutDeviceIntPoint(aX - rootRect.x, aY - rootRect.y);
  455. nsIFrame* popupFrame = nsLayoutUtils::
  456. GetPopupFrameForEventCoordinates(accDocument->PresContext()->GetRootPresContext(),
  457. &dummyEvent);
  458. if (popupFrame) {
  459. // If 'this' accessible is not inside the popup then ignore the popup when
  460. // searching an accessible at point.
  461. DocAccessible* popupDoc =
  462. GetAccService()->GetDocAccessible(popupFrame->GetContent()->OwnerDoc());
  463. Accessible* popupAcc =
  464. popupDoc->GetAccessibleOrContainer(popupFrame->GetContent());
  465. Accessible* popupChild = this;
  466. while (popupChild && !popupChild->IsDoc() && popupChild != popupAcc)
  467. popupChild = popupChild->Parent();
  468. if (popupChild == popupAcc)
  469. startFrame = popupFrame;
  470. }
  471. nsPresContext* presContext = startFrame->PresContext();
  472. nsRect screenRect = startFrame->GetScreenRectInAppUnits();
  473. nsPoint offset(presContext->DevPixelsToAppUnits(aX) - screenRect.x,
  474. presContext->DevPixelsToAppUnits(aY) - screenRect.y);
  475. nsIFrame* foundFrame = nsLayoutUtils::GetFrameForPoint(startFrame, offset);
  476. nsIContent* content = nullptr;
  477. if (!foundFrame || !(content = foundFrame->GetContent()))
  478. return fallbackAnswer;
  479. // Get accessible for the node with the point or the first accessible in
  480. // the DOM parent chain.
  481. DocAccessible* contentDocAcc = GetAccService()->
  482. GetDocAccessible(content->OwnerDoc());
  483. // contentDocAcc in some circumstances can be nullptr. See bug 729861
  484. NS_ASSERTION(contentDocAcc, "could not get the document accessible");
  485. if (!contentDocAcc)
  486. return fallbackAnswer;
  487. Accessible* accessible = contentDocAcc->GetAccessibleOrContainer(content);
  488. if (!accessible)
  489. return fallbackAnswer;
  490. // Hurray! We have an accessible for the frame that layout gave us.
  491. // Since DOM node of obtained accessible may be out of flow then we should
  492. // ensure obtained accessible is a child of this accessible.
  493. Accessible* child = accessible;
  494. while (child != this) {
  495. Accessible* parent = child->Parent();
  496. if (!parent) {
  497. // Reached the top of the hierarchy. These bounds were inside an
  498. // accessible that is not a descendant of this one.
  499. return fallbackAnswer;
  500. }
  501. // If we landed on a legitimate child of |this|, and we want the direct
  502. // child, return it here.
  503. if (parent == this && aWhichChild == eDirectChild)
  504. return child;
  505. child = parent;
  506. }
  507. // Manually walk through accessible children and see if the are within this
  508. // point. Skip offscreen or invisible accessibles. This takes care of cases
  509. // where layout won't walk into things for us, such as image map areas and
  510. // sub documents (XXX: subdocuments should be handled by methods of
  511. // OuterDocAccessibles).
  512. uint32_t childCount = accessible->ChildCount();
  513. for (uint32_t childIdx = 0; childIdx < childCount; childIdx++) {
  514. Accessible* child = accessible->GetChildAt(childIdx);
  515. nsIntRect childRect = child->Bounds();
  516. if (aX >= childRect.x && aX < childRect.x + childRect.width &&
  517. aY >= childRect.y && aY < childRect.y + childRect.height &&
  518. (child->State() & states::INVISIBLE) == 0) {
  519. if (aWhichChild == eDeepestChild)
  520. return child->ChildAtPoint(aX, aY, eDeepestChild);
  521. return child;
  522. }
  523. }
  524. return accessible;
  525. }
  526. nsRect
  527. Accessible::RelativeBounds(nsIFrame** aBoundingFrame) const
  528. {
  529. nsIFrame* frame = GetFrame();
  530. if (frame && mContent) {
  531. bool* hasHitRegionRect = static_cast<bool*>(mContent->GetProperty(nsGkAtoms::hitregion));
  532. if (hasHitRegionRect && mContent->IsElement()) {
  533. // This is for canvas fallback content
  534. // Find a canvas frame the found hit region is relative to.
  535. nsIFrame* canvasFrame = frame->GetParent();
  536. if (canvasFrame) {
  537. canvasFrame = nsLayoutUtils::GetClosestFrameOfType(canvasFrame, nsGkAtoms::HTMLCanvasFrame);
  538. }
  539. // make the canvas the bounding frame
  540. if (canvasFrame) {
  541. *aBoundingFrame = canvasFrame;
  542. dom::HTMLCanvasElement *canvas =
  543. dom::HTMLCanvasElement::FromContent(canvasFrame->GetContent());
  544. // get the bounding rect of the hit region
  545. nsRect bounds;
  546. if (canvas && canvas->CountContexts() &&
  547. canvas->GetContextAtIndex(0)->GetHitRegionRect(mContent->AsElement(), bounds)) {
  548. return bounds;
  549. }
  550. }
  551. }
  552. *aBoundingFrame = nsLayoutUtils::GetContainingBlockForClientRect(frame);
  553. return nsLayoutUtils::
  554. GetAllInFlowRectsUnion(frame, *aBoundingFrame,
  555. nsLayoutUtils::RECTS_ACCOUNT_FOR_TRANSFORMS);
  556. }
  557. return nsRect();
  558. }
  559. nsIntRect
  560. Accessible::Bounds() const
  561. {
  562. nsIFrame* boundingFrame = nullptr;
  563. nsRect unionRectTwips = RelativeBounds(&boundingFrame);
  564. if (!boundingFrame)
  565. return nsIntRect();
  566. nsIntRect screenRect;
  567. nsPresContext* presContext = mDoc->PresContext();
  568. screenRect.x = presContext->AppUnitsToDevPixels(unionRectTwips.x);
  569. screenRect.y = presContext->AppUnitsToDevPixels(unionRectTwips.y);
  570. screenRect.width = presContext->AppUnitsToDevPixels(unionRectTwips.width);
  571. screenRect.height = presContext->AppUnitsToDevPixels(unionRectTwips.height);
  572. // We have the union of the rectangle, now we need to put it in absolute
  573. // screen coords.
  574. nsIntRect orgRectPixels = boundingFrame->GetScreenRectInAppUnits().
  575. ToNearestPixels(presContext->AppUnitsPerDevPixel());
  576. screenRect.x += orgRectPixels.x;
  577. screenRect.y += orgRectPixels.y;
  578. return screenRect;
  579. }
  580. void
  581. Accessible::SetSelected(bool aSelect)
  582. {
  583. if (!HasOwnContent())
  584. return;
  585. Accessible* select = nsAccUtils::GetSelectableContainer(this, State());
  586. if (select) {
  587. if (select->State() & states::MULTISELECTABLE) {
  588. if (ARIARoleMap()) {
  589. if (aSelect) {
  590. mContent->SetAttr(kNameSpaceID_None, nsGkAtoms::aria_selected,
  591. NS_LITERAL_STRING("true"), true);
  592. } else {
  593. mContent->UnsetAttr(kNameSpaceID_None, nsGkAtoms::aria_selected, true);
  594. }
  595. }
  596. return;
  597. }
  598. if (aSelect)
  599. TakeFocus();
  600. }
  601. }
  602. void
  603. Accessible::TakeSelection()
  604. {
  605. Accessible* select = nsAccUtils::GetSelectableContainer(this, State());
  606. if (select) {
  607. if (select->State() & states::MULTISELECTABLE)
  608. select->UnselectAll();
  609. SetSelected(true);
  610. }
  611. }
  612. void
  613. Accessible::TakeFocus()
  614. {
  615. nsIFrame* frame = GetFrame();
  616. if (!frame)
  617. return;
  618. nsIContent* focusContent = mContent;
  619. // If the accessible focus is managed by container widget then focus the
  620. // widget and set the accessible as its current item.
  621. if (!frame->IsFocusable()) {
  622. Accessible* widget = ContainerWidget();
  623. if (widget && widget->AreItemsOperable()) {
  624. nsIContent* widgetElm = widget->GetContent();
  625. nsIFrame* widgetFrame = widgetElm->GetPrimaryFrame();
  626. if (widgetFrame && widgetFrame->IsFocusable()) {
  627. focusContent = widgetElm;
  628. widget->SetCurrentItem(this);
  629. }
  630. }
  631. }
  632. nsCOMPtr<nsIDOMElement> element(do_QueryInterface(focusContent));
  633. nsFocusManager* fm = nsFocusManager::GetFocusManager();
  634. if (fm)
  635. fm->SetFocus(element, 0);
  636. }
  637. void
  638. Accessible::XULElmName(DocAccessible* aDocument,
  639. nsIContent* aElm, nsString& aName)
  640. {
  641. /**
  642. * 3 main cases for XUL Controls to be labeled
  643. * 1 - control contains label="foo"
  644. * 2 - control has, as a child, a label element
  645. * - label has either value="foo" or children
  646. * 3 - non-child label contains control="controlID"
  647. * - label has either value="foo" or children
  648. * Once a label is found, the search is discontinued, so a control
  649. * that has a label child as well as having a label external to
  650. * the control that uses the control="controlID" syntax will use
  651. * the child label for its Name.
  652. */
  653. // CASE #1 (via label attribute) -- great majority of the cases
  654. nsCOMPtr<nsIDOMXULLabeledControlElement> labeledEl = do_QueryInterface(aElm);
  655. if (labeledEl) {
  656. labeledEl->GetLabel(aName);
  657. } else {
  658. nsCOMPtr<nsIDOMXULSelectControlItemElement> itemEl = do_QueryInterface(aElm);
  659. if (itemEl) {
  660. itemEl->GetLabel(aName);
  661. } else {
  662. nsCOMPtr<nsIDOMXULSelectControlElement> select = do_QueryInterface(aElm);
  663. // Use label if this is not a select control element which
  664. // uses label attribute to indicate which option is selected
  665. if (!select) {
  666. nsCOMPtr<nsIDOMXULElement> xulEl(do_QueryInterface(aElm));
  667. if (xulEl)
  668. xulEl->GetAttribute(NS_LITERAL_STRING("label"), aName);
  669. }
  670. }
  671. }
  672. // CASES #2 and #3 ------ label as a child or <label control="id" ... > </label>
  673. if (aName.IsEmpty()) {
  674. Accessible* labelAcc = nullptr;
  675. XULLabelIterator iter(aDocument, aElm);
  676. while ((labelAcc = iter.Next())) {
  677. nsCOMPtr<nsIDOMXULLabelElement> xulLabel =
  678. do_QueryInterface(labelAcc->GetContent());
  679. // Check if label's value attribute is used
  680. if (xulLabel && NS_SUCCEEDED(xulLabel->GetValue(aName)) && aName.IsEmpty()) {
  681. // If no value attribute, a non-empty label must contain
  682. // children that define its text -- possibly using HTML
  683. nsTextEquivUtils::
  684. AppendTextEquivFromContent(labelAcc, labelAcc->GetContent(), &aName);
  685. }
  686. }
  687. }
  688. aName.CompressWhitespace();
  689. if (!aName.IsEmpty())
  690. return;
  691. // Can get text from title of <toolbaritem> if we're a child of a <toolbaritem>
  692. nsIContent *bindingParent = aElm->GetBindingParent();
  693. nsIContent* parent =
  694. bindingParent? bindingParent->GetParent() : aElm->GetParent();
  695. nsAutoString ancestorTitle;
  696. while (parent) {
  697. if (parent->IsXULElement(nsGkAtoms::toolbaritem) &&
  698. parent->GetAttr(kNameSpaceID_None, nsGkAtoms::title, ancestorTitle)) {
  699. // Before returning this, check if the element itself has a tooltip:
  700. if (aElm->GetAttr(kNameSpaceID_None, nsGkAtoms::tooltiptext, aName)) {
  701. aName.CompressWhitespace();
  702. return;
  703. }
  704. aName.Assign(ancestorTitle);
  705. aName.CompressWhitespace();
  706. return;
  707. }
  708. parent = parent->GetParent();
  709. }
  710. }
  711. nsresult
  712. Accessible::HandleAccEvent(AccEvent* aEvent)
  713. {
  714. NS_ENSURE_ARG_POINTER(aEvent);
  715. if (IPCAccessibilityActive() && Document()) {
  716. DocAccessibleChild* ipcDoc = mDoc->IPCDoc();
  717. MOZ_ASSERT(ipcDoc);
  718. if (ipcDoc) {
  719. uint64_t id = aEvent->GetAccessible()->IsDoc() ? 0 :
  720. reinterpret_cast<uintptr_t>(aEvent->GetAccessible());
  721. switch(aEvent->GetEventType()) {
  722. case nsIAccessibleEvent::EVENT_SHOW:
  723. ipcDoc->ShowEvent(downcast_accEvent(aEvent));
  724. break;
  725. case nsIAccessibleEvent::EVENT_HIDE:
  726. ipcDoc->SendHideEvent(id, aEvent->IsFromUserInput());
  727. break;
  728. case nsIAccessibleEvent::EVENT_REORDER:
  729. // reorder events on the application acc aren't necessary to tell the parent
  730. // about new top level documents.
  731. if (!aEvent->GetAccessible()->IsApplication())
  732. ipcDoc->SendEvent(id, aEvent->GetEventType());
  733. break;
  734. case nsIAccessibleEvent::EVENT_STATE_CHANGE: {
  735. AccStateChangeEvent* event = downcast_accEvent(aEvent);
  736. ipcDoc->SendStateChangeEvent(id, event->GetState(),
  737. event->IsStateEnabled());
  738. break;
  739. }
  740. case nsIAccessibleEvent::EVENT_TEXT_CARET_MOVED: {
  741. AccCaretMoveEvent* event = downcast_accEvent(aEvent);
  742. ipcDoc->SendCaretMoveEvent(id, event->GetCaretOffset());
  743. break;
  744. }
  745. case nsIAccessibleEvent::EVENT_TEXT_INSERTED:
  746. case nsIAccessibleEvent::EVENT_TEXT_REMOVED: {
  747. AccTextChangeEvent* event = downcast_accEvent(aEvent);
  748. ipcDoc->SendTextChangeEvent(id, event->ModifiedText(),
  749. event->GetStartOffset(),
  750. event->GetLength(),
  751. event->IsTextInserted(),
  752. event->IsFromUserInput());
  753. break;
  754. }
  755. case nsIAccessibleEvent::EVENT_SELECTION:
  756. case nsIAccessibleEvent::EVENT_SELECTION_ADD:
  757. case nsIAccessibleEvent::EVENT_SELECTION_REMOVE: {
  758. AccSelChangeEvent* selEvent = downcast_accEvent(aEvent);
  759. uint64_t widgetID = selEvent->Widget()->IsDoc() ? 0 :
  760. reinterpret_cast<uintptr_t>(selEvent->Widget());
  761. ipcDoc->SendSelectionEvent(id, widgetID, aEvent->GetEventType());
  762. break;
  763. }
  764. default:
  765. ipcDoc->SendEvent(id, aEvent->GetEventType());
  766. }
  767. }
  768. }
  769. if (nsCoreUtils::AccEventObserversExist()) {
  770. nsCoreUtils::DispatchAccEvent(MakeXPCEvent(aEvent));
  771. }
  772. return NS_OK;
  773. }
  774. already_AddRefed<nsIPersistentProperties>
  775. Accessible::Attributes()
  776. {
  777. nsCOMPtr<nsIPersistentProperties> attributes = NativeAttributes();
  778. if (!HasOwnContent() || !mContent->IsElement())
  779. return attributes.forget();
  780. // 'xml-roles' attribute for landmark.
  781. nsIAtom* landmark = LandmarkRole();
  782. if (landmark) {
  783. nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles, landmark);
  784. } else {
  785. // 'xml-roles' attribute coming from ARIA.
  786. nsAutoString xmlRoles;
  787. if (mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::role, xmlRoles))
  788. nsAccUtils::SetAccAttr(attributes, nsGkAtoms::xmlroles, xmlRoles);
  789. }
  790. // Expose object attributes from ARIA attributes.
  791. nsAutoString unused;
  792. aria::AttrIterator attribIter(mContent);
  793. nsAutoString name, value;
  794. while(attribIter.Next(name, value))
  795. attributes->SetStringProperty(NS_ConvertUTF16toUTF8(name), value, unused);
  796. if (IsARIAHidden()) {
  797. nsAccUtils::SetAccAttr(attributes, nsGkAtoms::hidden,
  798. NS_LITERAL_STRING("true"));
  799. }
  800. // If there is no aria-live attribute then expose default value of 'live'
  801. // object attribute used for ARIA role of this accessible.
  802. const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
  803. if (roleMapEntry) {
  804. if (roleMapEntry->Is(nsGkAtoms::searchbox)) {
  805. nsAccUtils::SetAccAttr(attributes, nsGkAtoms::textInputType,
  806. NS_LITERAL_STRING("search"));
  807. }
  808. nsAutoString live;
  809. nsAccUtils::GetAccAttr(attributes, nsGkAtoms::live, live);
  810. if (live.IsEmpty()) {
  811. if (nsAccUtils::GetLiveAttrValue(roleMapEntry->liveAttRule, live))
  812. nsAccUtils::SetAccAttr(attributes, nsGkAtoms::live, live);
  813. }
  814. }
  815. return attributes.forget();
  816. }
  817. already_AddRefed<nsIPersistentProperties>
  818. Accessible::NativeAttributes()
  819. {
  820. nsCOMPtr<nsIPersistentProperties> attributes =
  821. do_CreateInstance(NS_PERSISTENTPROPERTIES_CONTRACTID);
  822. nsAutoString unused;
  823. // We support values, so expose the string value as well, via the valuetext
  824. // object attribute. We test for the value interface because we don't want
  825. // to expose traditional Value() information such as URL's on links and
  826. // documents, or text in an input.
  827. if (HasNumericValue()) {
  828. nsAutoString valuetext;
  829. Value(valuetext);
  830. attributes->SetStringProperty(NS_LITERAL_CSTRING("valuetext"), valuetext,
  831. unused);
  832. }
  833. // Expose checkable object attribute if the accessible has checkable state
  834. if (State() & states::CHECKABLE) {
  835. nsAccUtils::SetAccAttr(attributes, nsGkAtoms::checkable,
  836. NS_LITERAL_STRING("true"));
  837. }
  838. // Expose 'explicit-name' attribute.
  839. nsAutoString name;
  840. if (Name(name) != eNameFromSubtree && !name.IsVoid()) {
  841. attributes->SetStringProperty(NS_LITERAL_CSTRING("explicit-name"),
  842. NS_LITERAL_STRING("true"), unused);
  843. }
  844. // Group attributes (level/setsize/posinset)
  845. GroupPos groupPos = GroupPosition();
  846. nsAccUtils::SetAccGroupAttrs(attributes, groupPos.level,
  847. groupPos.setSize, groupPos.posInSet);
  848. // If the accessible doesn't have own content (such as list item bullet or
  849. // xul tree item) then don't calculate content based attributes.
  850. if (!HasOwnContent())
  851. return attributes.forget();
  852. nsEventShell::GetEventAttributes(GetNode(), attributes);
  853. // Get container-foo computed live region properties based on the closest
  854. // container with the live region attribute. Inner nodes override outer nodes
  855. // within the same document. The inner nodes can be used to override live
  856. // region behavior on more general outer nodes. However, nodes in outer
  857. // documents override nodes in inner documents: outer doc author may want to
  858. // override properties on a widget they used in an iframe.
  859. nsIContent* startContent = mContent;
  860. while (startContent) {
  861. nsIDocument* doc = startContent->GetComposedDoc();
  862. if (!doc)
  863. break;
  864. nsAccUtils::SetLiveContainerAttributes(attributes, startContent,
  865. doc->GetRootElement());
  866. // Allow ARIA live region markup from outer documents to override
  867. nsCOMPtr<nsIDocShellTreeItem> docShellTreeItem = doc->GetDocShell();
  868. if (!docShellTreeItem)
  869. break;
  870. nsCOMPtr<nsIDocShellTreeItem> sameTypeParent;
  871. docShellTreeItem->GetSameTypeParent(getter_AddRefs(sameTypeParent));
  872. if (!sameTypeParent || sameTypeParent == docShellTreeItem)
  873. break;
  874. nsIDocument* parentDoc = doc->GetParentDocument();
  875. if (!parentDoc)
  876. break;
  877. startContent = parentDoc->FindContentForSubDocument(doc);
  878. }
  879. if (!mContent->IsElement())
  880. return attributes.forget();
  881. nsAutoString id;
  882. if (nsCoreUtils::GetID(mContent, id))
  883. attributes->SetStringProperty(NS_LITERAL_CSTRING("id"), id, unused);
  884. // Expose class because it may have useful microformat information.
  885. nsAutoString _class;
  886. if (mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::_class, _class))
  887. nsAccUtils::SetAccAttr(attributes, nsGkAtoms::_class, _class);
  888. // Expose tag.
  889. nsAutoString tagName;
  890. mContent->NodeInfo()->GetName(tagName);
  891. nsAccUtils::SetAccAttr(attributes, nsGkAtoms::tag, tagName);
  892. // Expose draggable object attribute.
  893. nsCOMPtr<nsIDOMHTMLElement> htmlElement = do_QueryInterface(mContent);
  894. if (htmlElement) {
  895. bool draggable = false;
  896. htmlElement->GetDraggable(&draggable);
  897. if (draggable) {
  898. nsAccUtils::SetAccAttr(attributes, nsGkAtoms::draggable,
  899. NS_LITERAL_STRING("true"));
  900. }
  901. }
  902. // Don't calculate CSS-based object attributes when no frame (i.e.
  903. // the accessible is unattached from the tree).
  904. if (!mContent->GetPrimaryFrame())
  905. return attributes.forget();
  906. // CSS style based object attributes.
  907. nsAutoString value;
  908. StyleInfo styleInfo(mContent->AsElement(), mDoc->PresShell());
  909. // Expose 'display' attribute.
  910. styleInfo.Display(value);
  911. nsAccUtils::SetAccAttr(attributes, nsGkAtoms::display, value);
  912. // Expose 'text-align' attribute.
  913. styleInfo.TextAlign(value);
  914. nsAccUtils::SetAccAttr(attributes, nsGkAtoms::textAlign, value);
  915. // Expose 'text-indent' attribute.
  916. styleInfo.TextIndent(value);
  917. nsAccUtils::SetAccAttr(attributes, nsGkAtoms::textIndent, value);
  918. // Expose 'margin-left' attribute.
  919. styleInfo.MarginLeft(value);
  920. nsAccUtils::SetAccAttr(attributes, nsGkAtoms::marginLeft, value);
  921. // Expose 'margin-right' attribute.
  922. styleInfo.MarginRight(value);
  923. nsAccUtils::SetAccAttr(attributes, nsGkAtoms::marginRight, value);
  924. // Expose 'margin-top' attribute.
  925. styleInfo.MarginTop(value);
  926. nsAccUtils::SetAccAttr(attributes, nsGkAtoms::marginTop, value);
  927. // Expose 'margin-bottom' attribute.
  928. styleInfo.MarginBottom(value);
  929. nsAccUtils::SetAccAttr(attributes, nsGkAtoms::marginBottom, value);
  930. return attributes.forget();
  931. }
  932. GroupPos
  933. Accessible::GroupPosition()
  934. {
  935. GroupPos groupPos;
  936. if (!HasOwnContent())
  937. return groupPos;
  938. // Get group position from ARIA attributes.
  939. nsCoreUtils::GetUIntAttr(mContent, nsGkAtoms::aria_level, &groupPos.level);
  940. nsCoreUtils::GetUIntAttr(mContent, nsGkAtoms::aria_setsize, &groupPos.setSize);
  941. nsCoreUtils::GetUIntAttr(mContent, nsGkAtoms::aria_posinset, &groupPos.posInSet);
  942. // If ARIA is missed and the accessible is visible then calculate group
  943. // position from hierarchy.
  944. if (State() & states::INVISIBLE)
  945. return groupPos;
  946. // Calculate group level if ARIA is missed.
  947. if (groupPos.level == 0) {
  948. int32_t level = GetLevelInternal();
  949. if (level != 0)
  950. groupPos.level = level;
  951. }
  952. // Calculate position in group and group size if ARIA is missed.
  953. if (groupPos.posInSet == 0 || groupPos.setSize == 0) {
  954. int32_t posInSet = 0, setSize = 0;
  955. GetPositionAndSizeInternal(&posInSet, &setSize);
  956. if (posInSet != 0 && setSize != 0) {
  957. if (groupPos.posInSet == 0)
  958. groupPos.posInSet = posInSet;
  959. if (groupPos.setSize == 0)
  960. groupPos.setSize = setSize;
  961. }
  962. }
  963. return groupPos;
  964. }
  965. uint64_t
  966. Accessible::State()
  967. {
  968. if (IsDefunct())
  969. return states::DEFUNCT;
  970. uint64_t state = NativeState();
  971. // Apply ARIA states to be sure accessible states will be overridden.
  972. ApplyARIAState(&state);
  973. // If this is an ARIA item of the selectable widget and if it's focused and
  974. // not marked unselected explicitly (i.e. aria-selected="false") then expose
  975. // it as selected to make ARIA widget authors life easier.
  976. const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
  977. if (roleMapEntry && !(state & states::SELECTED) &&
  978. !mContent->AttrValueIs(kNameSpaceID_None,
  979. nsGkAtoms::aria_selected,
  980. nsGkAtoms::_false, eCaseMatters)) {
  981. // Special case for tabs: focused tab or focus inside related tab panel
  982. // implies selected state.
  983. if (roleMapEntry->role == roles::PAGETAB) {
  984. if (state & states::FOCUSED) {
  985. state |= states::SELECTED;
  986. } else {
  987. // If focus is in a child of the tab panel surely the tab is selected!
  988. Relation rel = RelationByType(RelationType::LABEL_FOR);
  989. Accessible* relTarget = nullptr;
  990. while ((relTarget = rel.Next())) {
  991. if (relTarget->Role() == roles::PROPERTYPAGE &&
  992. FocusMgr()->IsFocusWithin(relTarget))
  993. state |= states::SELECTED;
  994. }
  995. }
  996. } else if (state & states::FOCUSED) {
  997. Accessible* container = nsAccUtils::GetSelectableContainer(this, state);
  998. if (container &&
  999. !nsAccUtils::HasDefinedARIAToken(container->GetContent(),
  1000. nsGkAtoms::aria_multiselectable)) {
  1001. state |= states::SELECTED;
  1002. }
  1003. }
  1004. }
  1005. const uint32_t kExpandCollapseStates = states::COLLAPSED | states::EXPANDED;
  1006. if ((state & kExpandCollapseStates) == kExpandCollapseStates) {
  1007. // Cannot be both expanded and collapsed -- this happens in ARIA expanded
  1008. // combobox because of limitation of ARIAMap.
  1009. // XXX: Perhaps we will be able to make this less hacky if we support
  1010. // extended states in ARIAMap, e.g. derive COLLAPSED from
  1011. // EXPANDABLE && !EXPANDED.
  1012. state &= ~states::COLLAPSED;
  1013. }
  1014. if (!(state & states::UNAVAILABLE)) {
  1015. state |= states::ENABLED | states::SENSITIVE;
  1016. // If the object is a current item of container widget then mark it as
  1017. // ACTIVE. This allows screen reader virtual buffer modes to know which
  1018. // descendant is the current one that would get focus if the user navigates
  1019. // to the container widget.
  1020. Accessible* widget = ContainerWidget();
  1021. if (widget && widget->CurrentItem() == this)
  1022. state |= states::ACTIVE;
  1023. }
  1024. if ((state & states::COLLAPSED) || (state & states::EXPANDED))
  1025. state |= states::EXPANDABLE;
  1026. // For some reasons DOM node may have not a frame. We tract such accessibles
  1027. // as invisible.
  1028. nsIFrame *frame = GetFrame();
  1029. if (!frame)
  1030. return state;
  1031. if (frame->StyleEffects()->mOpacity == 1.0f &&
  1032. !(state & states::INVISIBLE)) {
  1033. state |= states::OPAQUE1;
  1034. }
  1035. return state;
  1036. }
  1037. void
  1038. Accessible::ApplyARIAState(uint64_t* aState) const
  1039. {
  1040. if (!mContent->IsElement())
  1041. return;
  1042. dom::Element* element = mContent->AsElement();
  1043. // Test for universal states first
  1044. *aState |= aria::UniversalStatesFor(element);
  1045. const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
  1046. if (roleMapEntry) {
  1047. // We only force the readonly bit off if we have a real mapping for the aria
  1048. // role. This preserves the ability for screen readers to use readonly
  1049. // (primarily on the document) as the hint for creating a virtual buffer.
  1050. if (roleMapEntry->role != roles::NOTHING)
  1051. *aState &= ~states::READONLY;
  1052. if (mContent->HasID()) {
  1053. // If has a role & ID and aria-activedescendant on the container, assume
  1054. // focusable.
  1055. const Accessible* ancestor = this;
  1056. while ((ancestor = ancestor->Parent()) && !ancestor->IsDoc()) {
  1057. dom::Element* el = ancestor->Elm();
  1058. if (el &&
  1059. el->HasAttr(kNameSpaceID_None, nsGkAtoms::aria_activedescendant)) {
  1060. *aState |= states::FOCUSABLE;
  1061. break;
  1062. }
  1063. }
  1064. }
  1065. }
  1066. if (*aState & states::FOCUSABLE) {
  1067. // Propogate aria-disabled from ancestors down to any focusable descendant.
  1068. const Accessible* ancestor = this;
  1069. while ((ancestor = ancestor->Parent()) && !ancestor->IsDoc()) {
  1070. dom::Element* el = ancestor->Elm();
  1071. if (el && el->AttrValueIs(kNameSpaceID_None, nsGkAtoms::aria_disabled,
  1072. nsGkAtoms::_true, eCaseMatters)) {
  1073. *aState |= states::UNAVAILABLE;
  1074. break;
  1075. }
  1076. }
  1077. }
  1078. // special case: A native button element whose role got transformed by ARIA to a toggle button
  1079. // Also applies to togglable button menus, like in the Dev Tools Web Console.
  1080. if (IsButton() || IsMenuButton())
  1081. aria::MapToState(aria::eARIAPressed, element, aState);
  1082. if (!roleMapEntry)
  1083. return;
  1084. *aState |= roleMapEntry->state;
  1085. if (aria::MapToState(roleMapEntry->attributeMap1, element, aState) &&
  1086. aria::MapToState(roleMapEntry->attributeMap2, element, aState) &&
  1087. aria::MapToState(roleMapEntry->attributeMap3, element, aState))
  1088. aria::MapToState(roleMapEntry->attributeMap4, element, aState);
  1089. // ARIA gridcell inherits editable/readonly states from the grid until it's
  1090. // overridden.
  1091. if ((roleMapEntry->Is(nsGkAtoms::gridcell) ||
  1092. roleMapEntry->Is(nsGkAtoms::columnheader) ||
  1093. roleMapEntry->Is(nsGkAtoms::rowheader)) &&
  1094. !(*aState & (states::READONLY | states::EDITABLE))) {
  1095. const TableCellAccessible* cell = AsTableCell();
  1096. if (cell) {
  1097. TableAccessible* table = cell->Table();
  1098. if (table) {
  1099. Accessible* grid = table->AsAccessible();
  1100. uint64_t gridState = 0;
  1101. grid->ApplyARIAState(&gridState);
  1102. *aState |= (gridState & (states::READONLY | states::EDITABLE));
  1103. }
  1104. }
  1105. }
  1106. }
  1107. void
  1108. Accessible::Value(nsString& aValue)
  1109. {
  1110. const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
  1111. if (!roleMapEntry)
  1112. return;
  1113. if (roleMapEntry->valueRule != eNoValue) {
  1114. // aria-valuenow is a number, and aria-valuetext is the optional text
  1115. // equivalent. For the string value, we will try the optional text
  1116. // equivalent first.
  1117. if (!mContent->GetAttr(kNameSpaceID_None,
  1118. nsGkAtoms::aria_valuetext, aValue)) {
  1119. mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::aria_valuenow,
  1120. aValue);
  1121. }
  1122. return;
  1123. }
  1124. // Value of textbox is a textified subtree.
  1125. if (roleMapEntry->Is(nsGkAtoms::textbox)) {
  1126. nsTextEquivUtils::GetTextEquivFromSubtree(this, aValue);
  1127. return;
  1128. }
  1129. // Value of combobox is a text of current or selected item.
  1130. if (roleMapEntry->Is(nsGkAtoms::combobox)) {
  1131. Accessible* option = CurrentItem();
  1132. if (!option) {
  1133. uint32_t childCount = ChildCount();
  1134. for (uint32_t idx = 0; idx < childCount; idx++) {
  1135. Accessible* child = mChildren.ElementAt(idx);
  1136. if (child->IsListControl()) {
  1137. option = child->GetSelectedItem(0);
  1138. break;
  1139. }
  1140. }
  1141. }
  1142. if (option)
  1143. nsTextEquivUtils::GetTextEquivFromSubtree(option, aValue);
  1144. }
  1145. }
  1146. double
  1147. Accessible::MaxValue() const
  1148. {
  1149. return AttrNumericValue(nsGkAtoms::aria_valuemax);
  1150. }
  1151. double
  1152. Accessible::MinValue() const
  1153. {
  1154. return AttrNumericValue(nsGkAtoms::aria_valuemin);
  1155. }
  1156. double
  1157. Accessible::Step() const
  1158. {
  1159. return UnspecifiedNaN<double>(); // no mimimum increment (step) in ARIA.
  1160. }
  1161. double
  1162. Accessible::CurValue() const
  1163. {
  1164. return AttrNumericValue(nsGkAtoms::aria_valuenow);
  1165. }
  1166. bool
  1167. Accessible::SetCurValue(double aValue)
  1168. {
  1169. const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
  1170. if (!roleMapEntry || roleMapEntry->valueRule == eNoValue)
  1171. return false;
  1172. const uint32_t kValueCannotChange = states::READONLY | states::UNAVAILABLE;
  1173. if (State() & kValueCannotChange)
  1174. return false;
  1175. double checkValue = MinValue();
  1176. if (!IsNaN(checkValue) && aValue < checkValue)
  1177. return false;
  1178. checkValue = MaxValue();
  1179. if (!IsNaN(checkValue) && aValue > checkValue)
  1180. return false;
  1181. nsAutoString strValue;
  1182. strValue.AppendFloat(aValue);
  1183. return NS_SUCCEEDED(
  1184. mContent->SetAttr(kNameSpaceID_None, nsGkAtoms::aria_valuenow, strValue, true));
  1185. }
  1186. role
  1187. Accessible::ARIATransformRole(role aRole)
  1188. {
  1189. // XXX: these unfortunate exceptions don't fit into the ARIA table. This is
  1190. // where the accessible role depends on both the role and ARIA state.
  1191. if (aRole == roles::PUSHBUTTON) {
  1192. if (nsAccUtils::HasDefinedARIAToken(mContent, nsGkAtoms::aria_pressed)) {
  1193. // For simplicity, any existing pressed attribute except "" or "undefined"
  1194. // indicates a toggle.
  1195. return roles::TOGGLE_BUTTON;
  1196. }
  1197. if (mContent->AttrValueIs(kNameSpaceID_None,
  1198. nsGkAtoms::aria_haspopup,
  1199. nsGkAtoms::_true,
  1200. eCaseMatters)) {
  1201. // For button with aria-haspopup="true".
  1202. return roles::BUTTONMENU;
  1203. }
  1204. } else if (aRole == roles::LISTBOX) {
  1205. // A listbox inside of a combobox needs a special role because of ATK
  1206. // mapping to menu.
  1207. if (mParent && mParent->Role() == roles::COMBOBOX) {
  1208. return roles::COMBOBOX_LIST;
  1209. } else {
  1210. // Listbox is owned by a combobox
  1211. Relation rel = RelationByType(RelationType::NODE_CHILD_OF);
  1212. Accessible* targetAcc = nullptr;
  1213. while ((targetAcc = rel.Next()))
  1214. if (targetAcc->Role() == roles::COMBOBOX)
  1215. return roles::COMBOBOX_LIST;
  1216. }
  1217. } else if (aRole == roles::OPTION) {
  1218. if (mParent && mParent->Role() == roles::COMBOBOX_LIST)
  1219. return roles::COMBOBOX_OPTION;
  1220. } else if (aRole == roles::MENUITEM) {
  1221. // Menuitem has a submenu.
  1222. if (mContent->AttrValueIs(kNameSpaceID_None, nsGkAtoms::aria_haspopup,
  1223. nsGkAtoms::_true, eCaseMatters)) {
  1224. return roles::PARENT_MENUITEM;
  1225. }
  1226. }
  1227. return aRole;
  1228. }
  1229. nsIAtom*
  1230. Accessible::LandmarkRole() const
  1231. {
  1232. const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
  1233. return roleMapEntry && roleMapEntry->IsOfType(eLandmark) ?
  1234. *(roleMapEntry->roleAtom) : nullptr;
  1235. }
  1236. role
  1237. Accessible::NativeRole()
  1238. {
  1239. return roles::NOTHING;
  1240. }
  1241. uint8_t
  1242. Accessible::ActionCount()
  1243. {
  1244. return GetActionRule() == eNoAction ? 0 : 1;
  1245. }
  1246. void
  1247. Accessible::ActionNameAt(uint8_t aIndex, nsAString& aName)
  1248. {
  1249. aName.Truncate();
  1250. if (aIndex != 0)
  1251. return;
  1252. uint32_t actionRule = GetActionRule();
  1253. switch (actionRule) {
  1254. case eActivateAction:
  1255. aName.AssignLiteral("activate");
  1256. return;
  1257. case eClickAction:
  1258. aName.AssignLiteral("click");
  1259. return;
  1260. case ePressAction:
  1261. aName.AssignLiteral("press");
  1262. return;
  1263. case eCheckUncheckAction:
  1264. {
  1265. uint64_t state = State();
  1266. if (state & states::CHECKED)
  1267. aName.AssignLiteral("uncheck");
  1268. else if (state & states::MIXED)
  1269. aName.AssignLiteral("cycle");
  1270. else
  1271. aName.AssignLiteral("check");
  1272. return;
  1273. }
  1274. case eJumpAction:
  1275. aName.AssignLiteral("jump");
  1276. return;
  1277. case eOpenCloseAction:
  1278. if (State() & states::COLLAPSED)
  1279. aName.AssignLiteral("open");
  1280. else
  1281. aName.AssignLiteral("close");
  1282. return;
  1283. case eSelectAction:
  1284. aName.AssignLiteral("select");
  1285. return;
  1286. case eSwitchAction:
  1287. aName.AssignLiteral("switch");
  1288. return;
  1289. case eSortAction:
  1290. aName.AssignLiteral("sort");
  1291. return;
  1292. case eExpandAction:
  1293. if (State() & states::COLLAPSED)
  1294. aName.AssignLiteral("expand");
  1295. else
  1296. aName.AssignLiteral("collapse");
  1297. return;
  1298. }
  1299. }
  1300. bool
  1301. Accessible::DoAction(uint8_t aIndex)
  1302. {
  1303. if (aIndex != 0)
  1304. return false;
  1305. if (GetActionRule() != eNoAction) {
  1306. DoCommand();
  1307. return true;
  1308. }
  1309. return false;
  1310. }
  1311. nsIContent*
  1312. Accessible::GetAtomicRegion() const
  1313. {
  1314. nsIContent *loopContent = mContent;
  1315. nsAutoString atomic;
  1316. while (loopContent && !loopContent->GetAttr(kNameSpaceID_None, nsGkAtoms::aria_atomic, atomic))
  1317. loopContent = loopContent->GetParent();
  1318. return atomic.EqualsLiteral("true") ? loopContent : nullptr;
  1319. }
  1320. Relation
  1321. Accessible::RelationByType(RelationType aType)
  1322. {
  1323. if (!HasOwnContent())
  1324. return Relation();
  1325. const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
  1326. // Relationships are defined on the same content node that the role would be
  1327. // defined on.
  1328. switch (aType) {
  1329. case RelationType::LABELLED_BY: {
  1330. Relation rel(new IDRefsIterator(mDoc, mContent,
  1331. nsGkAtoms::aria_labelledby));
  1332. if (mContent->IsHTMLElement()) {
  1333. rel.AppendIter(new HTMLLabelIterator(Document(), this));
  1334. } else if (mContent->IsXULElement()) {
  1335. rel.AppendIter(new XULLabelIterator(Document(), mContent));
  1336. }
  1337. return rel;
  1338. }
  1339. case RelationType::LABEL_FOR: {
  1340. Relation rel(new RelatedAccIterator(Document(), mContent,
  1341. nsGkAtoms::aria_labelledby));
  1342. if (mContent->IsXULElement(nsGkAtoms::label))
  1343. rel.AppendIter(new IDRefsIterator(mDoc, mContent, nsGkAtoms::control));
  1344. return rel;
  1345. }
  1346. case RelationType::DESCRIBED_BY: {
  1347. Relation rel(new IDRefsIterator(mDoc, mContent,
  1348. nsGkAtoms::aria_describedby));
  1349. if (mContent->IsXULElement())
  1350. rel.AppendIter(new XULDescriptionIterator(Document(), mContent));
  1351. return rel;
  1352. }
  1353. case RelationType::DESCRIPTION_FOR: {
  1354. Relation rel(new RelatedAccIterator(Document(), mContent,
  1355. nsGkAtoms::aria_describedby));
  1356. // This affectively adds an optional control attribute to xul:description,
  1357. // which only affects accessibility, by allowing the description to be
  1358. // tied to a control.
  1359. if (mContent->IsXULElement(nsGkAtoms::description))
  1360. rel.AppendIter(new IDRefsIterator(mDoc, mContent,
  1361. nsGkAtoms::control));
  1362. return rel;
  1363. }
  1364. case RelationType::NODE_CHILD_OF: {
  1365. Relation rel;
  1366. // This is an ARIA tree or treegrid that doesn't use owns, so we need to
  1367. // get the parent the hard way.
  1368. if (roleMapEntry && (roleMapEntry->role == roles::OUTLINEITEM ||
  1369. roleMapEntry->role == roles::LISTITEM ||
  1370. roleMapEntry->role == roles::ROW)) {
  1371. rel.AppendTarget(GetGroupInfo()->ConceptualParent());
  1372. }
  1373. // If accessible is in its own Window, or is the root of a document,
  1374. // then we should provide NODE_CHILD_OF relation so that MSAA clients
  1375. // can easily get to true parent instead of getting to oleacc's
  1376. // ROLE_WINDOW accessible which will prevent us from going up further
  1377. // (because it is system generated and has no idea about the hierarchy
  1378. // above it).
  1379. nsIFrame *frame = GetFrame();
  1380. if (frame) {
  1381. nsView *view = frame->GetView();
  1382. if (view) {
  1383. nsIScrollableFrame *scrollFrame = do_QueryFrame(frame);
  1384. if (scrollFrame || view->GetWidget() || !frame->GetParent())
  1385. rel.AppendTarget(Parent());
  1386. }
  1387. }
  1388. return rel;
  1389. }
  1390. case RelationType::NODE_PARENT_OF: {
  1391. // ARIA tree or treegrid can do the hierarchy by @aria-level, ARIA trees
  1392. // also can be organized by groups.
  1393. if (roleMapEntry &&
  1394. (roleMapEntry->role == roles::OUTLINEITEM ||
  1395. roleMapEntry->role == roles::LISTITEM ||
  1396. roleMapEntry->role == roles::ROW ||
  1397. roleMapEntry->role == roles::OUTLINE ||
  1398. roleMapEntry->role == roles::LIST ||
  1399. roleMapEntry->role == roles::TREE_TABLE)) {
  1400. return Relation(new ItemIterator(this));
  1401. }
  1402. return Relation();
  1403. }
  1404. case RelationType::CONTROLLED_BY:
  1405. return Relation(new RelatedAccIterator(Document(), mContent,
  1406. nsGkAtoms::aria_controls));
  1407. case RelationType::CONTROLLER_FOR: {
  1408. Relation rel(new IDRefsIterator(mDoc, mContent,
  1409. nsGkAtoms::aria_controls));
  1410. rel.AppendIter(new HTMLOutputIterator(Document(), mContent));
  1411. return rel;
  1412. }
  1413. case RelationType::FLOWS_TO:
  1414. return Relation(new IDRefsIterator(mDoc, mContent,
  1415. nsGkAtoms::aria_flowto));
  1416. case RelationType::FLOWS_FROM:
  1417. return Relation(new RelatedAccIterator(Document(), mContent,
  1418. nsGkAtoms::aria_flowto));
  1419. case RelationType::MEMBER_OF:
  1420. return Relation(mDoc, GetAtomicRegion());
  1421. case RelationType::SUBWINDOW_OF:
  1422. case RelationType::EMBEDS:
  1423. case RelationType::EMBEDDED_BY:
  1424. case RelationType::POPUP_FOR:
  1425. case RelationType::PARENT_WINDOW_OF:
  1426. return Relation();
  1427. case RelationType::DEFAULT_BUTTON: {
  1428. if (mContent->IsHTMLElement()) {
  1429. // HTML form controls implements nsIFormControl interface.
  1430. nsCOMPtr<nsIFormControl> control(do_QueryInterface(mContent));
  1431. if (control) {
  1432. nsCOMPtr<nsIForm> form(do_QueryInterface(control->GetFormElement()));
  1433. if (form) {
  1434. nsCOMPtr<nsIContent> formContent =
  1435. do_QueryInterface(form->GetDefaultSubmitElement());
  1436. return Relation(mDoc, formContent);
  1437. }
  1438. }
  1439. } else {
  1440. // In XUL, use first <button default="true" .../> in the document
  1441. nsCOMPtr<nsIDOMXULDocument> xulDoc =
  1442. do_QueryInterface(mContent->OwnerDoc());
  1443. nsCOMPtr<nsIDOMXULButtonElement> buttonEl;
  1444. if (xulDoc) {
  1445. nsCOMPtr<nsIDOMNodeList> possibleDefaultButtons;
  1446. xulDoc->GetElementsByAttribute(NS_LITERAL_STRING("default"),
  1447. NS_LITERAL_STRING("true"),
  1448. getter_AddRefs(possibleDefaultButtons));
  1449. if (possibleDefaultButtons) {
  1450. uint32_t length;
  1451. possibleDefaultButtons->GetLength(&length);
  1452. nsCOMPtr<nsIDOMNode> possibleButton;
  1453. // Check for button in list of default="true" elements
  1454. for (uint32_t count = 0; count < length && !buttonEl; count ++) {
  1455. possibleDefaultButtons->Item(count, getter_AddRefs(possibleButton));
  1456. buttonEl = do_QueryInterface(possibleButton);
  1457. }
  1458. }
  1459. if (!buttonEl) { // Check for anonymous accept button in <dialog>
  1460. dom::Element* rootElm = mContent->OwnerDoc()->GetRootElement();
  1461. if (rootElm) {
  1462. nsIContent* possibleButtonEl = rootElm->OwnerDoc()->
  1463. GetAnonymousElementByAttribute(rootElm, nsGkAtoms::_default,
  1464. NS_LITERAL_STRING("true"));
  1465. buttonEl = do_QueryInterface(possibleButtonEl);
  1466. }
  1467. }
  1468. nsCOMPtr<nsIContent> relatedContent(do_QueryInterface(buttonEl));
  1469. return Relation(mDoc, relatedContent);
  1470. }
  1471. }
  1472. return Relation();
  1473. }
  1474. case RelationType::CONTAINING_DOCUMENT:
  1475. return Relation(mDoc);
  1476. case RelationType::CONTAINING_TAB_PANE: {
  1477. nsCOMPtr<nsIDocShell> docShell =
  1478. nsCoreUtils::GetDocShellFor(GetNode());
  1479. if (docShell) {
  1480. // Walk up the parent chain without crossing the boundary at which item
  1481. // types change, preventing us from walking up out of tab content.
  1482. nsCOMPtr<nsIDocShellTreeItem> root;
  1483. docShell->GetSameTypeRootTreeItem(getter_AddRefs(root));
  1484. if (root) {
  1485. // If the item type is typeContent, we assume we are in browser tab
  1486. // content. Note, this includes content such as about:addons,
  1487. // for consistency.
  1488. if (root->ItemType() == nsIDocShellTreeItem::typeContent) {
  1489. return Relation(nsAccUtils::GetDocAccessibleFor(root));
  1490. }
  1491. }
  1492. }
  1493. return Relation();
  1494. }
  1495. case RelationType::CONTAINING_APPLICATION:
  1496. return Relation(ApplicationAcc());
  1497. case RelationType::DETAILS:
  1498. return Relation(new IDRefsIterator(mDoc, mContent, nsGkAtoms::aria_details));
  1499. case RelationType::DETAILS_FOR:
  1500. return Relation(new RelatedAccIterator(mDoc, mContent, nsGkAtoms::aria_details));
  1501. case RelationType::ERRORMSG:
  1502. return Relation(new IDRefsIterator(mDoc, mContent, nsGkAtoms::aria_errormessage));
  1503. case RelationType::ERRORMSG_FOR:
  1504. return Relation(new RelatedAccIterator(mDoc, mContent, nsGkAtoms::aria_errormessage));
  1505. default:
  1506. return Relation();
  1507. }
  1508. }
  1509. void
  1510. Accessible::GetNativeInterface(void** aNativeAccessible)
  1511. {
  1512. }
  1513. void
  1514. Accessible::DoCommand(nsIContent *aContent, uint32_t aActionIndex)
  1515. {
  1516. class Runnable final : public mozilla::Runnable
  1517. {
  1518. public:
  1519. Runnable(Accessible* aAcc, nsIContent* aContent, uint32_t aIdx) :
  1520. mAcc(aAcc), mContent(aContent), mIdx(aIdx) { }
  1521. NS_IMETHOD Run() override
  1522. {
  1523. if (mAcc)
  1524. mAcc->DispatchClickEvent(mContent, mIdx);
  1525. return NS_OK;
  1526. }
  1527. void Revoke()
  1528. {
  1529. mAcc = nullptr;
  1530. mContent = nullptr;
  1531. }
  1532. private:
  1533. RefPtr<Accessible> mAcc;
  1534. nsCOMPtr<nsIContent> mContent;
  1535. uint32_t mIdx;
  1536. };
  1537. nsIContent* content = aContent ? aContent : mContent.get();
  1538. nsCOMPtr<nsIRunnable> runnable = new Runnable(this, content, aActionIndex);
  1539. NS_DispatchToMainThread(runnable);
  1540. }
  1541. void
  1542. Accessible::DispatchClickEvent(nsIContent *aContent, uint32_t aActionIndex)
  1543. {
  1544. if (IsDefunct())
  1545. return;
  1546. nsCOMPtr<nsIPresShell> presShell = mDoc->PresShell();
  1547. // Scroll into view.
  1548. presShell->ScrollContentIntoView(aContent,
  1549. nsIPresShell::ScrollAxis(),
  1550. nsIPresShell::ScrollAxis(),
  1551. nsIPresShell::SCROLL_OVERFLOW_HIDDEN);
  1552. nsWeakFrame frame = aContent->GetPrimaryFrame();
  1553. if (!frame)
  1554. return;
  1555. // Compute x and y coordinates.
  1556. nsPoint point;
  1557. nsCOMPtr<nsIWidget> widget = frame->GetNearestWidget(point);
  1558. if (!widget)
  1559. return;
  1560. nsSize size = frame->GetSize();
  1561. RefPtr<nsPresContext> presContext = presShell->GetPresContext();
  1562. int32_t x = presContext->AppUnitsToDevPixels(point.x + size.width / 2);
  1563. int32_t y = presContext->AppUnitsToDevPixels(point.y + size.height / 2);
  1564. // Simulate a touch interaction by dispatching touch events with mouse events.
  1565. nsCoreUtils::DispatchTouchEvent(eTouchStart, x, y, aContent, frame,
  1566. presShell, widget);
  1567. nsCoreUtils::DispatchMouseEvent(eMouseDown, x, y, aContent, frame,
  1568. presShell, widget);
  1569. nsCoreUtils::DispatchTouchEvent(eTouchEnd, x, y, aContent, frame,
  1570. presShell, widget);
  1571. nsCoreUtils::DispatchMouseEvent(eMouseUp, x, y, aContent, frame,
  1572. presShell, widget);
  1573. }
  1574. void
  1575. Accessible::ScrollToPoint(uint32_t aCoordinateType, int32_t aX, int32_t aY)
  1576. {
  1577. nsIFrame* frame = GetFrame();
  1578. if (!frame)
  1579. return;
  1580. nsIntPoint coords =
  1581. nsAccUtils::ConvertToScreenCoords(aX, aY, aCoordinateType, this);
  1582. nsIFrame* parentFrame = frame;
  1583. while ((parentFrame = parentFrame->GetParent()))
  1584. nsCoreUtils::ScrollFrameToPoint(parentFrame, frame, coords);
  1585. }
  1586. void
  1587. Accessible::AppendTextTo(nsAString& aText, uint32_t aStartOffset,
  1588. uint32_t aLength)
  1589. {
  1590. // Return text representation of non-text accessible within hypertext
  1591. // accessible. Text accessible overrides this method to return enclosed text.
  1592. if (aStartOffset != 0 || aLength == 0)
  1593. return;
  1594. nsIFrame *frame = GetFrame();
  1595. if (!frame)
  1596. return;
  1597. NS_ASSERTION(mParent,
  1598. "Called on accessible unbound from tree. Result can be wrong.");
  1599. if (frame->GetType() == nsGkAtoms::brFrame) {
  1600. aText += kForcedNewLineChar;
  1601. } else if (mParent && nsAccUtils::MustPrune(mParent)) {
  1602. // Expose the embedded object accessible as imaginary embedded object
  1603. // character if its parent hypertext accessible doesn't expose children to
  1604. // AT.
  1605. aText += kImaginaryEmbeddedObjectChar;
  1606. } else {
  1607. aText += kEmbeddedObjectChar;
  1608. }
  1609. }
  1610. void
  1611. Accessible::Shutdown()
  1612. {
  1613. // Mark the accessible as defunct, invalidate the child count and pointers to
  1614. // other accessibles, also make sure none of its children point to this parent
  1615. mStateFlags |= eIsDefunct;
  1616. int32_t childCount = mChildren.Length();
  1617. for (int32_t childIdx = 0; childIdx < childCount; childIdx++) {
  1618. mChildren.ElementAt(childIdx)->UnbindFromParent();
  1619. }
  1620. mChildren.Clear();
  1621. mEmbeddedObjCollector = nullptr;
  1622. if (mParent)
  1623. mParent->RemoveChild(this);
  1624. mContent = nullptr;
  1625. mDoc = nullptr;
  1626. if (SelectionMgr() && SelectionMgr()->AccessibleWithCaret(nullptr) == this)
  1627. SelectionMgr()->ResetCaretOffset();
  1628. }
  1629. // Accessible protected
  1630. void
  1631. Accessible::ARIAName(nsString& aName)
  1632. {
  1633. // aria-labelledby now takes precedence over aria-label
  1634. nsresult rv = nsTextEquivUtils::
  1635. GetTextEquivFromIDRefs(this, nsGkAtoms::aria_labelledby, aName);
  1636. if (NS_SUCCEEDED(rv)) {
  1637. aName.CompressWhitespace();
  1638. }
  1639. if (aName.IsEmpty() &&
  1640. mContent->GetAttr(kNameSpaceID_None, nsGkAtoms::aria_label, aName)) {
  1641. aName.CompressWhitespace();
  1642. }
  1643. }
  1644. // Accessible protected
  1645. ENameValueFlag
  1646. Accessible::NativeName(nsString& aName)
  1647. {
  1648. if (mContent->IsHTMLElement()) {
  1649. Accessible* label = nullptr;
  1650. HTMLLabelIterator iter(Document(), this);
  1651. while ((label = iter.Next())) {
  1652. nsTextEquivUtils::AppendTextEquivFromContent(this, label->GetContent(),
  1653. &aName);
  1654. aName.CompressWhitespace();
  1655. }
  1656. if (!aName.IsEmpty())
  1657. return eNameOK;
  1658. nsTextEquivUtils::GetNameFromSubtree(this, aName);
  1659. return aName.IsEmpty() ? eNameOK : eNameFromSubtree;
  1660. }
  1661. if (mContent->IsXULElement()) {
  1662. XULElmName(mDoc, mContent, aName);
  1663. if (!aName.IsEmpty())
  1664. return eNameOK;
  1665. nsTextEquivUtils::GetNameFromSubtree(this, aName);
  1666. return aName.IsEmpty() ? eNameOK : eNameFromSubtree;
  1667. }
  1668. if (mContent->IsSVGElement()) {
  1669. // If user agents need to choose among multiple ‘desc’ or ‘title’ elements
  1670. // for processing, the user agent shall choose the first one.
  1671. for (nsIContent* childElm = mContent->GetFirstChild(); childElm;
  1672. childElm = childElm->GetNextSibling()) {
  1673. if (childElm->IsSVGElement(nsGkAtoms::title)) {
  1674. nsTextEquivUtils::AppendTextEquivFromContent(this, childElm, &aName);
  1675. return eNameOK;
  1676. }
  1677. }
  1678. }
  1679. return eNameOK;
  1680. }
  1681. // Accessible protected
  1682. void
  1683. Accessible::NativeDescription(nsString& aDescription)
  1684. {
  1685. bool isXUL = mContent->IsXULElement();
  1686. if (isXUL) {
  1687. // Try XUL <description control="[id]">description text</description>
  1688. XULDescriptionIterator iter(Document(), mContent);
  1689. Accessible* descr = nullptr;
  1690. while ((descr = iter.Next())) {
  1691. nsTextEquivUtils::AppendTextEquivFromContent(this, descr->GetContent(),
  1692. &aDescription);
  1693. }
  1694. }
  1695. }
  1696. // Accessible protected
  1697. void
  1698. Accessible::BindToParent(Accessible* aParent, uint32_t aIndexInParent)
  1699. {
  1700. MOZ_ASSERT(aParent, "This method isn't used to set null parent");
  1701. MOZ_ASSERT(!mParent, "The child was expected to be moved");
  1702. #ifdef A11Y_LOG
  1703. if (mParent) {
  1704. logging::TreeInfo("BindToParent: stealing accessible", 0,
  1705. "old parent", mParent,
  1706. "new parent", aParent,
  1707. "child", this, nullptr);
  1708. }
  1709. #endif
  1710. mParent = aParent;
  1711. mIndexInParent = aIndexInParent;
  1712. // Note: this is currently only used for richlistitems and their children.
  1713. if (mParent->HasNameDependentParent() || mParent->IsXULListItem())
  1714. mContextFlags |= eHasNameDependentParent;
  1715. else
  1716. mContextFlags &= ~eHasNameDependentParent;
  1717. if (mParent->IsARIAHidden() || aria::HasDefinedARIAHidden(mContent))
  1718. SetARIAHidden(true);
  1719. mContextFlags |=
  1720. static_cast<uint32_t>((mParent->IsAlert() ||
  1721. mParent->IsInsideAlert())) & eInsideAlert;
  1722. }
  1723. // Accessible protected
  1724. void
  1725. Accessible::UnbindFromParent()
  1726. {
  1727. mParent = nullptr;
  1728. mIndexInParent = -1;
  1729. mInt.mIndexOfEmbeddedChild = -1;
  1730. if (IsProxy())
  1731. MOZ_CRASH("this should never be called on proxy wrappers");
  1732. delete mBits.groupInfo;
  1733. mBits.groupInfo = nullptr;
  1734. mContextFlags &= ~eHasNameDependentParent & ~eInsideAlert;
  1735. }
  1736. ////////////////////////////////////////////////////////////////////////////////
  1737. // Accessible public methods
  1738. RootAccessible*
  1739. Accessible::RootAccessible() const
  1740. {
  1741. nsCOMPtr<nsIDocShell> docShell = nsCoreUtils::GetDocShellFor(GetNode());
  1742. NS_ASSERTION(docShell, "No docshell for mContent");
  1743. if (!docShell) {
  1744. return nullptr;
  1745. }
  1746. nsCOMPtr<nsIDocShellTreeItem> root;
  1747. docShell->GetRootTreeItem(getter_AddRefs(root));
  1748. NS_ASSERTION(root, "No root content tree item");
  1749. if (!root) {
  1750. return nullptr;
  1751. }
  1752. DocAccessible* docAcc = nsAccUtils::GetDocAccessibleFor(root);
  1753. return docAcc ? docAcc->AsRoot() : nullptr;
  1754. }
  1755. nsIFrame*
  1756. Accessible::GetFrame() const
  1757. {
  1758. return mContent ? mContent->GetPrimaryFrame() : nullptr;
  1759. }
  1760. nsINode*
  1761. Accessible::GetNode() const
  1762. {
  1763. return mContent;
  1764. }
  1765. void
  1766. Accessible::Language(nsAString& aLanguage)
  1767. {
  1768. aLanguage.Truncate();
  1769. if (!mDoc)
  1770. return;
  1771. nsCoreUtils::GetLanguageFor(mContent, nullptr, aLanguage);
  1772. if (aLanguage.IsEmpty()) { // Nothing found, so use document's language
  1773. mDoc->DocumentNode()->GetHeaderData(nsGkAtoms::headerContentLanguage,
  1774. aLanguage);
  1775. }
  1776. }
  1777. bool
  1778. Accessible::InsertChildAt(uint32_t aIndex, Accessible* aChild)
  1779. {
  1780. if (!aChild)
  1781. return false;
  1782. if (aIndex == mChildren.Length()) {
  1783. if (!mChildren.AppendElement(aChild))
  1784. return false;
  1785. } else {
  1786. if (!mChildren.InsertElementAt(aIndex, aChild))
  1787. return false;
  1788. MOZ_ASSERT(mStateFlags & eKidsMutating, "Illicit children change");
  1789. for (uint32_t idx = aIndex + 1; idx < mChildren.Length(); idx++) {
  1790. mChildren[idx]->mIndexInParent = idx;
  1791. }
  1792. }
  1793. if (aChild->IsText()) {
  1794. mStateFlags |= eHasTextKids;
  1795. }
  1796. aChild->BindToParent(this, aIndex);
  1797. return true;
  1798. }
  1799. bool
  1800. Accessible::RemoveChild(Accessible* aChild)
  1801. {
  1802. if (!aChild)
  1803. return false;
  1804. if (aChild->mParent != this || aChild->mIndexInParent == -1)
  1805. return false;
  1806. MOZ_ASSERT((mStateFlags & eKidsMutating) || aChild->IsDefunct() || aChild->IsDoc(),
  1807. "Illicit children change");
  1808. int32_t index = static_cast<uint32_t>(aChild->mIndexInParent);
  1809. if (mChildren.SafeElementAt(index) != aChild) {
  1810. MOZ_ASSERT_UNREACHABLE("A wrong child index");
  1811. index = mChildren.IndexOf(aChild);
  1812. if (index == -1) {
  1813. MOZ_ASSERT_UNREACHABLE("No child was found");
  1814. return false;
  1815. }
  1816. }
  1817. aChild->UnbindFromParent();
  1818. mChildren.RemoveElementAt(index);
  1819. for (uint32_t idx = index; idx < mChildren.Length(); idx++) {
  1820. mChildren[idx]->mIndexInParent = idx;
  1821. }
  1822. return true;
  1823. }
  1824. void
  1825. Accessible::MoveChild(uint32_t aNewIndex, Accessible* aChild)
  1826. {
  1827. MOZ_ASSERT(aChild, "No child was given");
  1828. MOZ_ASSERT(aChild->mParent == this, "A child from different subtree was given");
  1829. MOZ_ASSERT(aChild->mIndexInParent != -1, "Unbound child was given");
  1830. MOZ_ASSERT(static_cast<uint32_t>(aChild->mIndexInParent) != aNewIndex,
  1831. "No move, same index");
  1832. MOZ_ASSERT(aNewIndex <= mChildren.Length(), "Wrong new index was given");
  1833. RefPtr<AccHideEvent> hideEvent = new AccHideEvent(aChild, false);
  1834. if (mDoc->Controller()->QueueMutationEvent(hideEvent)) {
  1835. aChild->SetHideEventTarget(true);
  1836. }
  1837. mEmbeddedObjCollector = nullptr;
  1838. mChildren.RemoveElementAt(aChild->mIndexInParent);
  1839. uint32_t startIdx = aNewIndex, endIdx = aChild->mIndexInParent;
  1840. // If the child is moved after its current position.
  1841. if (static_cast<uint32_t>(aChild->mIndexInParent) < aNewIndex) {
  1842. startIdx = aChild->mIndexInParent;
  1843. if (aNewIndex == mChildren.Length() + 1) {
  1844. // The child is moved to the end.
  1845. mChildren.AppendElement(aChild);
  1846. endIdx = mChildren.Length() - 1;
  1847. }
  1848. else {
  1849. mChildren.InsertElementAt(aNewIndex - 1, aChild);
  1850. endIdx = aNewIndex;
  1851. }
  1852. }
  1853. else {
  1854. // The child is moved prior its current position.
  1855. mChildren.InsertElementAt(aNewIndex, aChild);
  1856. }
  1857. for (uint32_t idx = startIdx; idx <= endIdx; idx++) {
  1858. mChildren[idx]->mIndexInParent = idx;
  1859. mChildren[idx]->mStateFlags |= eGroupInfoDirty;
  1860. mChildren[idx]->mInt.mIndexOfEmbeddedChild = -1;
  1861. }
  1862. RefPtr<AccShowEvent> showEvent = new AccShowEvent(aChild);
  1863. DebugOnly<bool> added = mDoc->Controller()->QueueMutationEvent(showEvent);
  1864. MOZ_ASSERT(added);
  1865. aChild->SetShowEventTarget(true);
  1866. }
  1867. Accessible*
  1868. Accessible::GetChildAt(uint32_t aIndex) const
  1869. {
  1870. Accessible* child = mChildren.SafeElementAt(aIndex, nullptr);
  1871. if (!child)
  1872. return nullptr;
  1873. #ifdef DEBUG
  1874. Accessible* realParent = child->mParent;
  1875. NS_ASSERTION(!realParent || realParent == this,
  1876. "Two accessibles have the same first child accessible!");
  1877. #endif
  1878. return child;
  1879. }
  1880. uint32_t
  1881. Accessible::ChildCount() const
  1882. {
  1883. return mChildren.Length();
  1884. }
  1885. int32_t
  1886. Accessible::IndexInParent() const
  1887. {
  1888. return mIndexInParent;
  1889. }
  1890. uint32_t
  1891. Accessible::EmbeddedChildCount()
  1892. {
  1893. if (mStateFlags & eHasTextKids) {
  1894. if (!mEmbeddedObjCollector)
  1895. mEmbeddedObjCollector.reset(new EmbeddedObjCollector(this));
  1896. return mEmbeddedObjCollector->Count();
  1897. }
  1898. return ChildCount();
  1899. }
  1900. Accessible*
  1901. Accessible::GetEmbeddedChildAt(uint32_t aIndex)
  1902. {
  1903. if (mStateFlags & eHasTextKids) {
  1904. if (!mEmbeddedObjCollector)
  1905. mEmbeddedObjCollector.reset(new EmbeddedObjCollector(this));
  1906. return mEmbeddedObjCollector.get() ?
  1907. mEmbeddedObjCollector->GetAccessibleAt(aIndex) : nullptr;
  1908. }
  1909. return GetChildAt(aIndex);
  1910. }
  1911. int32_t
  1912. Accessible::GetIndexOfEmbeddedChild(Accessible* aChild)
  1913. {
  1914. if (mStateFlags & eHasTextKids) {
  1915. if (!mEmbeddedObjCollector)
  1916. mEmbeddedObjCollector.reset(new EmbeddedObjCollector(this));
  1917. return mEmbeddedObjCollector.get() ?
  1918. mEmbeddedObjCollector->GetIndexAt(aChild) : -1;
  1919. }
  1920. return GetIndexOf(aChild);
  1921. }
  1922. ////////////////////////////////////////////////////////////////////////////////
  1923. // HyperLinkAccessible methods
  1924. bool
  1925. Accessible::IsLink()
  1926. {
  1927. // Every embedded accessible within hypertext accessible implements
  1928. // hyperlink interface.
  1929. return mParent && mParent->IsHyperText() && !IsText();
  1930. }
  1931. uint32_t
  1932. Accessible::StartOffset()
  1933. {
  1934. NS_PRECONDITION(IsLink(), "StartOffset is called not on hyper link!");
  1935. HyperTextAccessible* hyperText = mParent ? mParent->AsHyperText() : nullptr;
  1936. return hyperText ? hyperText->GetChildOffset(this) : 0;
  1937. }
  1938. uint32_t
  1939. Accessible::EndOffset()
  1940. {
  1941. NS_PRECONDITION(IsLink(), "EndOffset is called on not hyper link!");
  1942. HyperTextAccessible* hyperText = mParent ? mParent->AsHyperText() : nullptr;
  1943. return hyperText ? (hyperText->GetChildOffset(this) + 1) : 0;
  1944. }
  1945. uint32_t
  1946. Accessible::AnchorCount()
  1947. {
  1948. NS_PRECONDITION(IsLink(), "AnchorCount is called on not hyper link!");
  1949. return 1;
  1950. }
  1951. Accessible*
  1952. Accessible::AnchorAt(uint32_t aAnchorIndex)
  1953. {
  1954. NS_PRECONDITION(IsLink(), "GetAnchor is called on not hyper link!");
  1955. return aAnchorIndex == 0 ? this : nullptr;
  1956. }
  1957. already_AddRefed<nsIURI>
  1958. Accessible::AnchorURIAt(uint32_t aAnchorIndex)
  1959. {
  1960. NS_PRECONDITION(IsLink(), "AnchorURIAt is called on not hyper link!");
  1961. return nullptr;
  1962. }
  1963. void
  1964. Accessible::ToTextPoint(HyperTextAccessible** aContainer, int32_t* aOffset,
  1965. bool aIsBefore) const
  1966. {
  1967. if (IsHyperText()) {
  1968. *aContainer = const_cast<Accessible*>(this)->AsHyperText();
  1969. *aOffset = aIsBefore ? 0 : (*aContainer)->CharacterCount();
  1970. return;
  1971. }
  1972. const Accessible* child = nullptr;
  1973. const Accessible* parent = this;
  1974. do {
  1975. child = parent;
  1976. parent = parent->Parent();
  1977. } while (parent && !parent->IsHyperText());
  1978. if (parent) {
  1979. *aContainer = const_cast<Accessible*>(parent)->AsHyperText();
  1980. *aOffset = (*aContainer)->GetChildOffset(
  1981. child->IndexInParent() + static_cast<int32_t>(!aIsBefore));
  1982. }
  1983. }
  1984. ////////////////////////////////////////////////////////////////////////////////
  1985. // SelectAccessible
  1986. void
  1987. Accessible::SelectedItems(nsTArray<Accessible*>* aItems)
  1988. {
  1989. AccIterator iter(this, filters::GetSelected);
  1990. Accessible* selected = nullptr;
  1991. while ((selected = iter.Next()))
  1992. aItems->AppendElement(selected);
  1993. }
  1994. uint32_t
  1995. Accessible::SelectedItemCount()
  1996. {
  1997. uint32_t count = 0;
  1998. AccIterator iter(this, filters::GetSelected);
  1999. Accessible* selected = nullptr;
  2000. while ((selected = iter.Next()))
  2001. ++count;
  2002. return count;
  2003. }
  2004. Accessible*
  2005. Accessible::GetSelectedItem(uint32_t aIndex)
  2006. {
  2007. AccIterator iter(this, filters::GetSelected);
  2008. Accessible* selected = nullptr;
  2009. uint32_t index = 0;
  2010. while ((selected = iter.Next()) && index < aIndex)
  2011. index++;
  2012. return selected;
  2013. }
  2014. bool
  2015. Accessible::IsItemSelected(uint32_t aIndex)
  2016. {
  2017. uint32_t index = 0;
  2018. AccIterator iter(this, filters::GetSelectable);
  2019. Accessible* selected = nullptr;
  2020. while ((selected = iter.Next()) && index < aIndex)
  2021. index++;
  2022. return selected &&
  2023. selected->State() & states::SELECTED;
  2024. }
  2025. bool
  2026. Accessible::AddItemToSelection(uint32_t aIndex)
  2027. {
  2028. uint32_t index = 0;
  2029. AccIterator iter(this, filters::GetSelectable);
  2030. Accessible* selected = nullptr;
  2031. while ((selected = iter.Next()) && index < aIndex)
  2032. index++;
  2033. if (selected)
  2034. selected->SetSelected(true);
  2035. return static_cast<bool>(selected);
  2036. }
  2037. bool
  2038. Accessible::RemoveItemFromSelection(uint32_t aIndex)
  2039. {
  2040. uint32_t index = 0;
  2041. AccIterator iter(this, filters::GetSelectable);
  2042. Accessible* selected = nullptr;
  2043. while ((selected = iter.Next()) && index < aIndex)
  2044. index++;
  2045. if (selected)
  2046. selected->SetSelected(false);
  2047. return static_cast<bool>(selected);
  2048. }
  2049. bool
  2050. Accessible::SelectAll()
  2051. {
  2052. bool success = false;
  2053. Accessible* selectable = nullptr;
  2054. AccIterator iter(this, filters::GetSelectable);
  2055. while((selectable = iter.Next())) {
  2056. success = true;
  2057. selectable->SetSelected(true);
  2058. }
  2059. return success;
  2060. }
  2061. bool
  2062. Accessible::UnselectAll()
  2063. {
  2064. bool success = false;
  2065. Accessible* selected = nullptr;
  2066. AccIterator iter(this, filters::GetSelected);
  2067. while ((selected = iter.Next())) {
  2068. success = true;
  2069. selected->SetSelected(false);
  2070. }
  2071. return success;
  2072. }
  2073. ////////////////////////////////////////////////////////////////////////////////
  2074. // Widgets
  2075. bool
  2076. Accessible::IsWidget() const
  2077. {
  2078. return false;
  2079. }
  2080. bool
  2081. Accessible::IsActiveWidget() const
  2082. {
  2083. if (FocusMgr()->HasDOMFocus(mContent))
  2084. return true;
  2085. // If text entry of combobox widget has a focus then the combobox widget is
  2086. // active.
  2087. const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
  2088. if (roleMapEntry && roleMapEntry->Is(nsGkAtoms::combobox)) {
  2089. uint32_t childCount = ChildCount();
  2090. for (uint32_t idx = 0; idx < childCount; idx++) {
  2091. Accessible* child = mChildren.ElementAt(idx);
  2092. if (child->Role() == roles::ENTRY)
  2093. return FocusMgr()->HasDOMFocus(child->GetContent());
  2094. }
  2095. }
  2096. return false;
  2097. }
  2098. bool
  2099. Accessible::AreItemsOperable() const
  2100. {
  2101. return HasOwnContent() &&
  2102. mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::aria_activedescendant);
  2103. }
  2104. Accessible*
  2105. Accessible::CurrentItem()
  2106. {
  2107. // Check for aria-activedescendant, which changes which element has focus.
  2108. // For activedescendant, the ARIA spec does not require that the user agent
  2109. // checks whether pointed node is actually a DOM descendant of the element
  2110. // with the aria-activedescendant attribute.
  2111. nsAutoString id;
  2112. if (HasOwnContent() &&
  2113. mContent->GetAttr(kNameSpaceID_None,
  2114. nsGkAtoms::aria_activedescendant, id)) {
  2115. nsIDocument* DOMDoc = mContent->OwnerDoc();
  2116. dom::Element* activeDescendantElm = DOMDoc->GetElementById(id);
  2117. if (activeDescendantElm) {
  2118. DocAccessible* document = Document();
  2119. if (document)
  2120. return document->GetAccessible(activeDescendantElm);
  2121. }
  2122. }
  2123. return nullptr;
  2124. }
  2125. void
  2126. Accessible::SetCurrentItem(Accessible* aItem)
  2127. {
  2128. nsIAtom* id = aItem->GetContent()->GetID();
  2129. if (id) {
  2130. nsAutoString idStr;
  2131. id->ToString(idStr);
  2132. mContent->SetAttr(kNameSpaceID_None,
  2133. nsGkAtoms::aria_activedescendant, idStr, true);
  2134. }
  2135. }
  2136. Accessible*
  2137. Accessible::ContainerWidget() const
  2138. {
  2139. if (HasARIARole() && mContent->HasID()) {
  2140. for (Accessible* parent = Parent(); parent; parent = parent->Parent()) {
  2141. nsIContent* parentContent = parent->GetContent();
  2142. if (parentContent &&
  2143. parentContent->HasAttr(kNameSpaceID_None,
  2144. nsGkAtoms::aria_activedescendant)) {
  2145. return parent;
  2146. }
  2147. // Don't cross DOM document boundaries.
  2148. if (parent->IsDoc())
  2149. break;
  2150. }
  2151. }
  2152. return nullptr;
  2153. }
  2154. void
  2155. Accessible::SetARIAHidden(bool aIsDefined)
  2156. {
  2157. if (aIsDefined)
  2158. mContextFlags |= eARIAHidden;
  2159. else
  2160. mContextFlags &= ~eARIAHidden;
  2161. uint32_t length = mChildren.Length();
  2162. for (uint32_t i = 0; i < length; i++) {
  2163. mChildren[i]->SetARIAHidden(aIsDefined);
  2164. }
  2165. }
  2166. ////////////////////////////////////////////////////////////////////////////////
  2167. // Accessible protected methods
  2168. void
  2169. Accessible::LastRelease()
  2170. {
  2171. // First cleanup if needed...
  2172. if (mDoc) {
  2173. Shutdown();
  2174. NS_ASSERTION(!mDoc,
  2175. "A Shutdown() impl forgot to call its parent's Shutdown?");
  2176. }
  2177. // ... then die.
  2178. delete this;
  2179. }
  2180. Accessible*
  2181. Accessible::GetSiblingAtOffset(int32_t aOffset, nsresult* aError) const
  2182. {
  2183. if (!mParent || mIndexInParent == -1) {
  2184. if (aError)
  2185. *aError = NS_ERROR_UNEXPECTED;
  2186. return nullptr;
  2187. }
  2188. if (aError &&
  2189. mIndexInParent + aOffset >= static_cast<int32_t>(mParent->ChildCount())) {
  2190. *aError = NS_OK; // fail peacefully
  2191. return nullptr;
  2192. }
  2193. Accessible* child = mParent->GetChildAt(mIndexInParent + aOffset);
  2194. if (aError && !child)
  2195. *aError = NS_ERROR_UNEXPECTED;
  2196. return child;
  2197. }
  2198. double
  2199. Accessible::AttrNumericValue(nsIAtom* aAttr) const
  2200. {
  2201. const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
  2202. if (!roleMapEntry || roleMapEntry->valueRule == eNoValue)
  2203. return UnspecifiedNaN<double>();
  2204. nsAutoString attrValue;
  2205. if (!mContent->GetAttr(kNameSpaceID_None, aAttr, attrValue))
  2206. return UnspecifiedNaN<double>();
  2207. nsresult error = NS_OK;
  2208. double value = attrValue.ToDouble(&error);
  2209. return NS_FAILED(error) ? UnspecifiedNaN<double>() : value;
  2210. }
  2211. uint32_t
  2212. Accessible::GetActionRule() const
  2213. {
  2214. if (!HasOwnContent() || (InteractiveState() & states::UNAVAILABLE))
  2215. return eNoAction;
  2216. // Return "click" action on elements that have an attached popup menu.
  2217. if (mContent->IsXULElement())
  2218. if (mContent->HasAttr(kNameSpaceID_None, nsGkAtoms::popup))
  2219. return eClickAction;
  2220. // Has registered 'click' event handler.
  2221. bool isOnclick = nsCoreUtils::HasClickListener(mContent);
  2222. if (isOnclick)
  2223. return eClickAction;
  2224. // Get an action based on ARIA role.
  2225. const nsRoleMapEntry* roleMapEntry = ARIARoleMap();
  2226. if (roleMapEntry &&
  2227. roleMapEntry->actionRule != eNoAction)
  2228. return roleMapEntry->actionRule;
  2229. // Get an action based on ARIA attribute.
  2230. if (nsAccUtils::HasDefinedARIAToken(mContent,
  2231. nsGkAtoms::aria_expanded))
  2232. return eExpandAction;
  2233. return eNoAction;
  2234. }
  2235. AccGroupInfo*
  2236. Accessible::GetGroupInfo()
  2237. {
  2238. if (IsProxy())
  2239. MOZ_CRASH("This should never be called on proxy wrappers");
  2240. if (mBits.groupInfo){
  2241. if (HasDirtyGroupInfo()) {
  2242. mBits.groupInfo->Update();
  2243. mStateFlags &= ~eGroupInfoDirty;
  2244. }
  2245. return mBits.groupInfo;
  2246. }
  2247. mBits.groupInfo = AccGroupInfo::CreateGroupInfo(this);
  2248. return mBits.groupInfo;
  2249. }
  2250. void
  2251. Accessible::GetPositionAndSizeInternal(int32_t *aPosInSet, int32_t *aSetSize)
  2252. {
  2253. AccGroupInfo* groupInfo = GetGroupInfo();
  2254. if (groupInfo) {
  2255. *aPosInSet = groupInfo->PosInSet();
  2256. *aSetSize = groupInfo->SetSize();
  2257. }
  2258. }
  2259. int32_t
  2260. Accessible::GetLevelInternal()
  2261. {
  2262. int32_t level = nsAccUtils::GetDefaultLevel(this);
  2263. if (!IsBoundToParent())
  2264. return level;
  2265. roles::Role role = Role();
  2266. if (role == roles::OUTLINEITEM) {
  2267. // Always expose 'level' attribute for 'outlineitem' accessible. The number
  2268. // of nested 'grouping' accessibles containing 'outlineitem' accessible is
  2269. // its level.
  2270. level = 1;
  2271. Accessible* parent = this;
  2272. while ((parent = parent->Parent())) {
  2273. roles::Role parentRole = parent->Role();
  2274. if (parentRole == roles::OUTLINE)
  2275. break;
  2276. if (parentRole == roles::GROUPING)
  2277. ++ level;
  2278. }
  2279. } else if (role == roles::LISTITEM) {
  2280. // Expose 'level' attribute on nested lists. We support two hierarchies:
  2281. // a) list -> listitem -> list -> listitem (nested list is a last child
  2282. // of listitem of the parent list);
  2283. // b) list -> listitem -> group -> listitem (nested listitems are contained
  2284. // by group that is a last child of the parent listitem).
  2285. // Calculate 'level' attribute based on number of parent listitems.
  2286. level = 0;
  2287. Accessible* parent = this;
  2288. while ((parent = parent->Parent())) {
  2289. roles::Role parentRole = parent->Role();
  2290. if (parentRole == roles::LISTITEM)
  2291. ++ level;
  2292. else if (parentRole != roles::LIST && parentRole != roles::GROUPING)
  2293. break;
  2294. }
  2295. if (level == 0) {
  2296. // If this listitem is on top of nested lists then expose 'level'
  2297. // attribute.
  2298. parent = Parent();
  2299. uint32_t siblingCount = parent->ChildCount();
  2300. for (uint32_t siblingIdx = 0; siblingIdx < siblingCount; siblingIdx++) {
  2301. Accessible* sibling = parent->GetChildAt(siblingIdx);
  2302. Accessible* siblingChild = sibling->LastChild();
  2303. if (siblingChild) {
  2304. roles::Role lastChildRole = siblingChild->Role();
  2305. if (lastChildRole == roles::LIST || lastChildRole == roles::GROUPING)
  2306. return 1;
  2307. }
  2308. }
  2309. } else {
  2310. ++ level; // level is 1-index based
  2311. }
  2312. }
  2313. return level;
  2314. }
  2315. void
  2316. Accessible::StaticAsserts() const
  2317. {
  2318. static_assert(eLastStateFlag <= (1 << kStateFlagsBits) - 1,
  2319. "Accessible::mStateFlags was oversized by eLastStateFlag!");
  2320. static_assert(eLastAccType <= (1 << kTypeBits) - 1,
  2321. "Accessible::mType was oversized by eLastAccType!");
  2322. static_assert(eLastContextFlag <= (1 << kContextFlagsBits) - 1,
  2323. "Accessible::mContextFlags was oversized by eLastContextFlag!");
  2324. static_assert(eLastAccGenericType <= (1 << kGenericTypesBits) - 1,
  2325. "Accessible::mGenericType was oversized by eLastAccGenericType!");
  2326. }
  2327. ////////////////////////////////////////////////////////////////////////////////
  2328. // KeyBinding class
  2329. // static
  2330. uint32_t
  2331. KeyBinding::AccelModifier()
  2332. {
  2333. switch (WidgetInputEvent::AccelModifier()) {
  2334. case MODIFIER_ALT:
  2335. return kAlt;
  2336. case MODIFIER_CONTROL:
  2337. return kControl;
  2338. case MODIFIER_META:
  2339. return kMeta;
  2340. case MODIFIER_OS:
  2341. return kOS;
  2342. default:
  2343. MOZ_CRASH("Handle the new result of WidgetInputEvent::AccelModifier()");
  2344. return 0;
  2345. }
  2346. }
  2347. void
  2348. KeyBinding::ToPlatformFormat(nsAString& aValue) const
  2349. {
  2350. nsCOMPtr<nsIStringBundle> keyStringBundle;
  2351. nsCOMPtr<nsIStringBundleService> stringBundleService =
  2352. mozilla::services::GetStringBundleService();
  2353. if (stringBundleService)
  2354. stringBundleService->CreateBundle(
  2355. "chrome://global-platform/locale/platformKeys.properties",
  2356. getter_AddRefs(keyStringBundle));
  2357. if (!keyStringBundle)
  2358. return;
  2359. nsAutoString separator;
  2360. keyStringBundle->GetStringFromName(u"MODIFIER_SEPARATOR",
  2361. getter_Copies(separator));
  2362. nsAutoString modifierName;
  2363. if (mModifierMask & kControl) {
  2364. keyStringBundle->GetStringFromName(u"VK_CONTROL",
  2365. getter_Copies(modifierName));
  2366. aValue.Append(modifierName);
  2367. aValue.Append(separator);
  2368. }
  2369. if (mModifierMask & kAlt) {
  2370. keyStringBundle->GetStringFromName(u"VK_ALT",
  2371. getter_Copies(modifierName));
  2372. aValue.Append(modifierName);
  2373. aValue.Append(separator);
  2374. }
  2375. if (mModifierMask & kShift) {
  2376. keyStringBundle->GetStringFromName(u"VK_SHIFT",
  2377. getter_Copies(modifierName));
  2378. aValue.Append(modifierName);
  2379. aValue.Append(separator);
  2380. }
  2381. if (mModifierMask & kMeta) {
  2382. keyStringBundle->GetStringFromName(u"VK_META",
  2383. getter_Copies(modifierName));
  2384. aValue.Append(modifierName);
  2385. aValue.Append(separator);
  2386. }
  2387. aValue.Append(mKey);
  2388. }
  2389. void
  2390. KeyBinding::ToAtkFormat(nsAString& aValue) const
  2391. {
  2392. nsAutoString modifierName;
  2393. if (mModifierMask & kControl)
  2394. aValue.AppendLiteral("<Control>");
  2395. if (mModifierMask & kAlt)
  2396. aValue.AppendLiteral("<Alt>");
  2397. if (mModifierMask & kShift)
  2398. aValue.AppendLiteral("<Shift>");
  2399. if (mModifierMask & kMeta)
  2400. aValue.AppendLiteral("<Meta>");
  2401. aValue.Append(mKey);
  2402. }