The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1032 lines
44KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. #define JUCE_NATIVE_ACCESSIBILITY_INCLUDED 1
  21. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  22. METHOD (setSource, "setSource", "(Landroid/view/View;I)V") \
  23. METHOD (addChild, "addChild", "(Landroid/view/View;I)V") \
  24. METHOD (setParent, "setParent", "(Landroid/view/View;)V") \
  25. METHOD (setVirtualParent, "setParent", "(Landroid/view/View;I)V") \
  26. METHOD (setBoundsInScreen, "setBoundsInScreen", "(Landroid/graphics/Rect;)V") \
  27. METHOD (setBoundsInParent, "setBoundsInParent", "(Landroid/graphics/Rect;)V") \
  28. METHOD (setPackageName, "setPackageName", "(Ljava/lang/CharSequence;)V") \
  29. METHOD (setClassName, "setClassName", "(Ljava/lang/CharSequence;)V") \
  30. METHOD (setContentDescription, "setContentDescription", "(Ljava/lang/CharSequence;)V") \
  31. METHOD (setCheckable, "setCheckable", "(Z)V") \
  32. METHOD (setChecked, "setChecked", "(Z)V") \
  33. METHOD (setClickable, "setClickable", "(Z)V") \
  34. METHOD (setEnabled, "setEnabled", "(Z)V") \
  35. METHOD (setFocusable, "setFocusable", "(Z)V") \
  36. METHOD (setFocused, "setFocused", "(Z)V") \
  37. METHOD (setPassword, "setPassword", "(Z)V") \
  38. METHOD (setSelected, "setSelected", "(Z)V") \
  39. METHOD (setVisibleToUser, "setVisibleToUser", "(Z)V") \
  40. METHOD (setAccessibilityFocused, "setAccessibilityFocused", "(Z)V") \
  41. METHOD (setText, "setText", "(Ljava/lang/CharSequence;)V") \
  42. METHOD (setMovementGranularities, "setMovementGranularities", "(I)V") \
  43. METHOD (addAction, "addAction", "(I)V") \
  44. DECLARE_JNI_CLASS (AndroidAccessibilityNodeInfo, "android/view/accessibility/AccessibilityNodeInfo")
  45. #undef JNI_CLASS_MEMBERS
  46. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  47. METHOD (setCollectionInfo, "setCollectionInfo", "(Landroid/view/accessibility/AccessibilityNodeInfo$CollectionInfo;)V") \
  48. METHOD (setCollectionItemInfo, "setCollectionItemInfo", "(Landroid/view/accessibility/AccessibilityNodeInfo$CollectionItemInfo;)V")
  49. DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidAccessibilityNodeInfo19, "android/view/accessibility/AccessibilityNodeInfo", 19)
  50. #undef JNI_CLASS_MEMBERS
  51. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  52. STATICMETHOD (obtain, "obtain", "(IIZ)Landroid/view/accessibility/AccessibilityNodeInfo$CollectionInfo;")
  53. DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidAccessibilityNodeInfoCollectionInfo, "android/view/accessibility/AccessibilityNodeInfo$CollectionInfo", 19)
  54. #undef JNI_CLASS_MEMBERS
  55. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  56. STATICMETHOD (obtain, "obtain", "(IIIIZ)Landroid/view/accessibility/AccessibilityNodeInfo$CollectionItemInfo;")
  57. DECLARE_JNI_CLASS_WITH_MIN_SDK (AndroidAccessibilityNodeInfoCollectionItemInfo, "android/view/accessibility/AccessibilityNodeInfo$CollectionItemInfo", 19)
  58. #undef JNI_CLASS_MEMBERS
  59. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  60. STATICMETHOD (obtain, "obtain", "(I)Landroid/view/accessibility/AccessibilityEvent;") \
  61. METHOD (setPackageName, "setPackageName", "(Ljava/lang/CharSequence;)V") \
  62. METHOD (setSource, "setSource","(Landroid/view/View;I)V") \
  63. METHOD (setAction, "setAction", "(I)V") \
  64. METHOD (setFromIndex, "setFromIndex", "(I)V") \
  65. METHOD (setToIndex, "setToIndex", "(I)V") \
  66. DECLARE_JNI_CLASS (AndroidAccessibilityEvent, "android/view/accessibility/AccessibilityEvent")
  67. #undef JNI_CLASS_MEMBERS
  68. #define JNI_CLASS_MEMBERS(METHOD, STATICMETHOD, FIELD, STATICFIELD, CALLBACK) \
  69. METHOD (isEnabled, "isEnabled", "()Z") \
  70. DECLARE_JNI_CLASS (AndroidAccessibilityManager, "android/view/accessibility/AccessibilityManager")
  71. #undef JNI_CLASS_MEMBERS
  72. namespace
  73. {
  74. constexpr int HOST_VIEW_ID = -1;
  75. constexpr int TYPE_VIEW_CLICKED = 0x00000001,
  76. TYPE_VIEW_SELECTED = 0x00000004,
  77. TYPE_VIEW_ACCESSIBILITY_FOCUSED = 0x00008000,
  78. TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED = 0x00010000,
  79. TYPE_WINDOW_CONTENT_CHANGED = 0x00000800,
  80. TYPE_VIEW_TEXT_SELECTION_CHANGED = 0x00002000,
  81. TYPE_VIEW_TEXT_CHANGED = 0x00000010,
  82. TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY = 0x00020000;
  83. constexpr int CONTENT_CHANGE_TYPE_SUBTREE = 0x00000001,
  84. CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION = 0x00000004;
  85. constexpr int ACTION_ACCESSIBILITY_FOCUS = 0x00000040,
  86. ACTION_CLEAR_ACCESSIBILITY_FOCUS = 0x00000080,
  87. ACTION_CLEAR_FOCUS = 0x00000002,
  88. ACTION_CLEAR_SELECTION = 0x00000008,
  89. ACTION_CLICK = 0x00000010,
  90. ACTION_COLLAPSE = 0x00080000,
  91. ACTION_EXPAND = 0x00040000,
  92. ACTION_FOCUS = 0x00000001,
  93. ACTION_NEXT_AT_MOVEMENT_GRANULARITY = 0x00000100,
  94. ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY = 0x00000200,
  95. ACTION_SCROLL_BACKWARD = 0x00002000,
  96. ACTION_SCROLL_FORWARD = 0x00001000,
  97. ACTION_SELECT = 0x00000004,
  98. ACTION_SET_SELECTION = 0x00020000,
  99. ACTION_SET_TEXT = 0x00200000;
  100. constexpr int MOVEMENT_GRANULARITY_CHARACTER = 0x00000001,
  101. MOVEMENT_GRANULARITY_LINE = 0x00000004,
  102. MOVEMENT_GRANULARITY_PAGE = 0x00000010,
  103. MOVEMENT_GRANULARITY_PARAGRAPH = 0x00000008,
  104. MOVEMENT_GRANULARITY_WORD = 0x00000002,
  105. ALL_GRANULARITIES = MOVEMENT_GRANULARITY_CHARACTER
  106. | MOVEMENT_GRANULARITY_LINE
  107. | MOVEMENT_GRANULARITY_PAGE
  108. | MOVEMENT_GRANULARITY_PARAGRAPH
  109. | MOVEMENT_GRANULARITY_WORD;
  110. constexpr int ACCESSIBILITY_LIVE_REGION_POLITE = 0x00000001;
  111. }
  112. static jmethodID nodeInfoSetEditable = nullptr;
  113. static jmethodID nodeInfoSetTextSelection = nullptr;
  114. static jmethodID nodeInfoSetLiveRegion = nullptr;
  115. static jmethodID accessibilityEventSetContentChangeTypes = nullptr;
  116. static void loadSDKDependentMethods()
  117. {
  118. static bool hasChecked = false;
  119. if (! hasChecked)
  120. {
  121. hasChecked = true;
  122. auto* env = getEnv();
  123. const auto sdkVersion = getAndroidSDKVersion();
  124. if (sdkVersion >= 18)
  125. {
  126. nodeInfoSetEditable = env->GetMethodID (AndroidAccessibilityNodeInfo, "setEditable", "(Z)V");
  127. nodeInfoSetTextSelection = env->GetMethodID (AndroidAccessibilityNodeInfo, "setTextSelection", "(II)V");
  128. }
  129. if (sdkVersion >= 19)
  130. {
  131. nodeInfoSetLiveRegion = env->GetMethodID (AndroidAccessibilityNodeInfo, "setLiveRegion", "(I)V");
  132. accessibilityEventSetContentChangeTypes = env->GetMethodID (AndroidAccessibilityEvent, "setContentChangeTypes", "(I)V");
  133. }
  134. }
  135. }
  136. static constexpr auto getClassName (AccessibilityRole role)
  137. {
  138. switch (role)
  139. {
  140. case AccessibilityRole::editableText: return "android.widget.EditText";
  141. case AccessibilityRole::toggleButton: return "android.widget.CheckBox";
  142. case AccessibilityRole::radioButton: return "android.widget.RadioButton";
  143. case AccessibilityRole::image: return "android.widget.ImageView";
  144. case AccessibilityRole::popupMenu: return "android.widget.PopupMenu";
  145. case AccessibilityRole::comboBox: return "android.widget.Spinner";
  146. case AccessibilityRole::tree: return "android.widget.ExpandableListView";
  147. case AccessibilityRole::progressBar: return "android.widget.ProgressBar";
  148. case AccessibilityRole::scrollBar:
  149. case AccessibilityRole::slider: return "android.widget.SeekBar";
  150. case AccessibilityRole::hyperlink:
  151. case AccessibilityRole::button: return "android.widget.Button";
  152. case AccessibilityRole::label:
  153. case AccessibilityRole::staticText: return "android.widget.TextView";
  154. case AccessibilityRole::tooltip:
  155. case AccessibilityRole::splashScreen:
  156. case AccessibilityRole::dialogWindow: return "android.widget.PopupWindow";
  157. // If we don't supply a custom class type, then TalkBack will use the node's CollectionInfo
  158. // to make a sensible decision about how to describe the container
  159. case AccessibilityRole::list:
  160. case AccessibilityRole::table:
  161. case AccessibilityRole::column:
  162. case AccessibilityRole::row:
  163. case AccessibilityRole::cell:
  164. case AccessibilityRole::menuItem:
  165. case AccessibilityRole::menuBar:
  166. case AccessibilityRole::listItem:
  167. case AccessibilityRole::treeItem:
  168. case AccessibilityRole::window:
  169. case AccessibilityRole::tableHeader:
  170. case AccessibilityRole::unspecified:
  171. case AccessibilityRole::group:
  172. case AccessibilityRole::ignored: break;
  173. }
  174. return "android.view.View";
  175. }
  176. static jobject getSourceView (const AccessibilityHandler& handler)
  177. {
  178. if (auto* peer = handler.getComponent().getPeer())
  179. return (jobject) peer->getNativeHandle();
  180. return nullptr;
  181. }
  182. static jobject makeAndroidRect (Rectangle<int> r)
  183. {
  184. return getEnv()->NewObject (AndroidRect,
  185. AndroidRect.constructor,
  186. r.getX(),
  187. r.getY(),
  188. r.getRight(),
  189. r.getBottom());
  190. }
  191. static jobject makeAndroidPoint (Point<int> p)
  192. {
  193. return getEnv()->NewObject (AndroidPoint,
  194. AndroidPoint.create,
  195. p.getX(),
  196. p.getY());
  197. }
  198. //==============================================================================
  199. class AccessibilityNativeHandle
  200. {
  201. public:
  202. static AccessibilityHandler* getAccessibilityHandlerForVirtualViewId (int virtualViewId)
  203. {
  204. auto iter = virtualViewIdMap.find (virtualViewId);
  205. if (iter != virtualViewIdMap.end())
  206. return iter->second;
  207. return nullptr;
  208. }
  209. explicit AccessibilityNativeHandle (AccessibilityHandler& h)
  210. : accessibilityHandler (h),
  211. virtualViewId (getVirtualViewIdForHandler (accessibilityHandler))
  212. {
  213. loadSDKDependentMethods();
  214. if (virtualViewId != HOST_VIEW_ID)
  215. virtualViewIdMap[virtualViewId] = &accessibilityHandler;
  216. }
  217. ~AccessibilityNativeHandle()
  218. {
  219. if (virtualViewId != HOST_VIEW_ID)
  220. virtualViewIdMap.erase (virtualViewId);
  221. }
  222. int getVirtualViewId() const noexcept { return virtualViewId; }
  223. void populateNodeInfo (jobject info)
  224. {
  225. const ScopedValueSetter<bool> svs (inPopulateNodeInfo, true);
  226. const auto sourceView = getSourceView (accessibilityHandler);
  227. if (sourceView == nullptr)
  228. return;
  229. auto* env = getEnv();
  230. auto appContext = getAppContext();
  231. if (appContext.get() == nullptr)
  232. return;
  233. {
  234. for (auto* child : accessibilityHandler.getChildren())
  235. env->CallVoidMethod (info, AndroidAccessibilityNodeInfo.addChild,
  236. sourceView, child->getNativeImplementation()->getVirtualViewId());
  237. if (auto* parent = accessibilityHandler.getParent())
  238. env->CallVoidMethod (info, AndroidAccessibilityNodeInfo.setVirtualParent,
  239. sourceView, parent->getNativeImplementation()->getVirtualViewId());
  240. }
  241. {
  242. const auto scale = Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
  243. LocalRef<jobject> screenBounds (makeAndroidRect (accessibilityHandler.getComponent().getScreenBounds() * scale));
  244. env->CallVoidMethod (info, AndroidAccessibilityNodeInfo.setBoundsInScreen, screenBounds.get());
  245. LocalRef<jobject> boundsInParent (makeAndroidRect (accessibilityHandler.getComponent().getBoundsInParent() * scale));
  246. env->CallVoidMethod (info, AndroidAccessibilityNodeInfo.setBoundsInParent, boundsInParent.get());
  247. }
  248. const auto state = accessibilityHandler.getCurrentState();
  249. env->CallVoidMethod (info,
  250. AndroidAccessibilityNodeInfo.setEnabled,
  251. ! state.isIgnored());
  252. env->CallVoidMethod (info,
  253. AndroidAccessibilityNodeInfo.setVisibleToUser,
  254. true);
  255. env->CallVoidMethod (info,
  256. AndroidAccessibilityNodeInfo.setPackageName,
  257. env->CallObjectMethod (appContext.get(),
  258. AndroidContext.getPackageName));
  259. env->CallVoidMethod (info,
  260. AndroidAccessibilityNodeInfo.setSource,
  261. sourceView,
  262. virtualViewId);
  263. env->CallVoidMethod (info,
  264. AndroidAccessibilityNodeInfo.setClassName,
  265. javaString (getClassName (accessibilityHandler.getRole())).get());
  266. env->CallVoidMethod (info,
  267. AndroidAccessibilityNodeInfo.setContentDescription,
  268. getDescriptionString().get());
  269. if (state.isFocusable())
  270. {
  271. env->CallVoidMethod (info, AndroidAccessibilityNodeInfo.setFocusable, true);
  272. const auto& component = accessibilityHandler.getComponent();
  273. if (component.getWantsKeyboardFocus())
  274. {
  275. const auto hasKeyboardFocus = component.hasKeyboardFocus (false);
  276. env->CallVoidMethod (info,
  277. AndroidAccessibilityNodeInfo.setFocused,
  278. hasKeyboardFocus);
  279. env->CallVoidMethod (info,
  280. AndroidAccessibilityNodeInfo.addAction,
  281. hasKeyboardFocus ? ACTION_CLEAR_FOCUS : ACTION_FOCUS);
  282. }
  283. const auto isAccessibleFocused = accessibilityHandler.hasFocus (false);
  284. env->CallVoidMethod (info,
  285. AndroidAccessibilityNodeInfo.setAccessibilityFocused,
  286. isAccessibleFocused);
  287. env->CallVoidMethod (info,
  288. AndroidAccessibilityNodeInfo.addAction,
  289. isAccessibleFocused ? ACTION_CLEAR_ACCESSIBILITY_FOCUS
  290. : ACTION_ACCESSIBILITY_FOCUS);
  291. }
  292. if (state.isCheckable())
  293. {
  294. env->CallVoidMethod (info,
  295. AndroidAccessibilityNodeInfo.setCheckable,
  296. true);
  297. env->CallVoidMethod (info,
  298. AndroidAccessibilityNodeInfo.setChecked,
  299. state.isChecked());
  300. }
  301. if (state.isSelectable() || state.isMultiSelectable())
  302. {
  303. const auto isSelected = state.isSelected();
  304. env->CallVoidMethod (info,
  305. AndroidAccessibilityNodeInfo.setSelected,
  306. isSelected);
  307. env->CallVoidMethod (info,
  308. AndroidAccessibilityNodeInfo.addAction,
  309. isSelected ? ACTION_CLEAR_SELECTION : ACTION_SELECT);
  310. }
  311. if ((accessibilityHandler.getCurrentState().isCheckable() && accessibilityHandler.getActions().contains (AccessibilityActionType::toggle))
  312. || accessibilityHandler.getActions().contains (AccessibilityActionType::press))
  313. {
  314. env->CallVoidMethod (info,
  315. AndroidAccessibilityNodeInfo.setClickable,
  316. true);
  317. env->CallVoidMethod (info,
  318. AndroidAccessibilityNodeInfo.addAction,
  319. ACTION_CLICK);
  320. }
  321. if (accessibilityHandler.getActions().contains (AccessibilityActionType::showMenu)
  322. && state.isExpandable())
  323. {
  324. env->CallVoidMethod (info,
  325. AndroidAccessibilityNodeInfo.addAction,
  326. state.isExpanded() ? ACTION_COLLAPSE : ACTION_EXPAND);
  327. }
  328. if (auto* textInterface = accessibilityHandler.getTextInterface())
  329. {
  330. env->CallVoidMethod (info,
  331. AndroidAccessibilityNodeInfo.setText,
  332. javaString (textInterface->getAllText()).get());
  333. const auto isReadOnly = textInterface->isReadOnly();
  334. env->CallVoidMethod (info,
  335. AndroidAccessibilityNodeInfo.setPassword,
  336. textInterface->isDisplayingProtectedText());
  337. if (nodeInfoSetEditable != nullptr)
  338. env->CallVoidMethod (info, nodeInfoSetEditable, ! isReadOnly);
  339. const auto selection = textInterface->getSelection();
  340. if (nodeInfoSetTextSelection != nullptr && ! selection.isEmpty())
  341. env->CallVoidMethod (info,
  342. nodeInfoSetTextSelection,
  343. selection.getStart(), selection.getEnd());
  344. if (nodeInfoSetLiveRegion != nullptr && accessibilityHandler.hasFocus (false))
  345. env->CallVoidMethod (info,
  346. nodeInfoSetLiveRegion,
  347. ACCESSIBILITY_LIVE_REGION_POLITE);
  348. env->CallVoidMethod (info,
  349. AndroidAccessibilityNodeInfo.setMovementGranularities,
  350. ALL_GRANULARITIES);
  351. env->CallVoidMethod (info,
  352. AndroidAccessibilityNodeInfo.addAction,
  353. ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
  354. env->CallVoidMethod (info,
  355. AndroidAccessibilityNodeInfo.addAction,
  356. ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
  357. env->CallVoidMethod (info,
  358. AndroidAccessibilityNodeInfo.addAction,
  359. ACTION_SET_SELECTION);
  360. if (! isReadOnly)
  361. env->CallVoidMethod (info, AndroidAccessibilityNodeInfo.addAction, ACTION_SET_TEXT);
  362. }
  363. if (auto* valueInterface = accessibilityHandler.getValueInterface())
  364. {
  365. if (! valueInterface->isReadOnly())
  366. {
  367. const auto range = valueInterface->getRange();
  368. if (range.isValid())
  369. {
  370. env->CallVoidMethod (info,
  371. AndroidAccessibilityNodeInfo.addAction,
  372. ACTION_SCROLL_FORWARD);
  373. env->CallVoidMethod (info,
  374. AndroidAccessibilityNodeInfo.addAction,
  375. ACTION_SCROLL_BACKWARD);
  376. }
  377. }
  378. }
  379. if (getAndroidSDKVersion() >= 19)
  380. {
  381. if (auto* tableInterface = accessibilityHandler.getTableInterface())
  382. {
  383. const auto rows = tableInterface->getNumRows();
  384. const auto columns = tableInterface->getNumColumns();
  385. const LocalRef<jobject> collectionInfo { env->CallStaticObjectMethod (AndroidAccessibilityNodeInfoCollectionInfo,
  386. AndroidAccessibilityNodeInfoCollectionInfo.obtain,
  387. (jint) rows,
  388. (jint) columns,
  389. (jboolean) false) };
  390. env->CallVoidMethod (info, AndroidAccessibilityNodeInfo19.setCollectionInfo, collectionInfo.get());
  391. }
  392. if (auto* enclosingTableHandler = detail::AccessibilityHelpers::getEnclosingHandlerWithInterface (&accessibilityHandler, &AccessibilityHandler::getTableInterface))
  393. {
  394. auto* interface = enclosingTableHandler->getTableInterface();
  395. jassert (interface != nullptr);
  396. const auto rowSpan = interface->getRowSpan (accessibilityHandler);
  397. const auto columnSpan = interface->getColumnSpan (accessibilityHandler);
  398. enum class IsHeader { no, yes };
  399. const auto addCellInfo = [env, &info] (AccessibilityTableInterface::Span rows, AccessibilityTableInterface::Span columns, IsHeader header)
  400. {
  401. const LocalRef<jobject> collectionItemInfo { env->CallStaticObjectMethod (AndroidAccessibilityNodeInfoCollectionItemInfo,
  402. AndroidAccessibilityNodeInfoCollectionItemInfo.obtain,
  403. (jint) rows.begin,
  404. (jint) rows.num,
  405. (jint) columns.begin,
  406. (jint) columns.num,
  407. (jboolean) (header == IsHeader::yes)) };
  408. env->CallVoidMethod (info, AndroidAccessibilityNodeInfo19.setCollectionItemInfo, collectionItemInfo.get());
  409. };
  410. if (rowSpan.hasValue() && columnSpan.hasValue())
  411. {
  412. addCellInfo (*rowSpan, *columnSpan, IsHeader::no);
  413. }
  414. else
  415. {
  416. if (auto* tableHeader = interface->getHeaderHandler())
  417. {
  418. if (accessibilityHandler.getParent() == tableHeader)
  419. {
  420. const auto children = tableHeader->getChildren();
  421. const auto column = std::distance (children.cbegin(), std::find (children.cbegin(), children.cend(), &accessibilityHandler));
  422. // Talkback will only treat a row as a column header if its row index is zero
  423. // https://github.com/google/talkback/blob/acd0bc7631a3dfbcf183789c7557596a45319e1f/utils/src/main/java/CollectionState.java#L853
  424. addCellInfo ({ 0, 1 }, { (int) column, 1 }, IsHeader::yes);
  425. }
  426. }
  427. }
  428. }
  429. }
  430. }
  431. bool performAction (int action, jobject arguments)
  432. {
  433. switch (action)
  434. {
  435. case ACTION_ACCESSIBILITY_FOCUS:
  436. {
  437. const WeakReference<Component> safeComponent (&accessibilityHandler.getComponent());
  438. accessibilityHandler.getActions().invoke (AccessibilityActionType::focus);
  439. if (safeComponent != nullptr)
  440. accessibilityHandler.grabFocus();
  441. return true;
  442. }
  443. case ACTION_CLEAR_ACCESSIBILITY_FOCUS:
  444. {
  445. accessibilityHandler.giveAwayFocus();
  446. return true;
  447. }
  448. case ACTION_FOCUS:
  449. case ACTION_CLEAR_FOCUS:
  450. {
  451. auto& component = accessibilityHandler.getComponent();
  452. if (component.getWantsKeyboardFocus())
  453. {
  454. const auto hasFocus = component.hasKeyboardFocus (false);
  455. if (hasFocus && action == ACTION_CLEAR_FOCUS)
  456. component.giveAwayKeyboardFocus();
  457. else if (! hasFocus && action == ACTION_FOCUS)
  458. component.grabKeyboardFocus();
  459. return true;
  460. }
  461. break;
  462. }
  463. case ACTION_CLICK:
  464. {
  465. // Invoking the action may delete this handler
  466. const WeakReference<AccessibilityNativeHandle> savedHandle { this };
  467. if ((accessibilityHandler.getCurrentState().isCheckable() && accessibilityHandler.getActions().invoke (AccessibilityActionType::toggle))
  468. || accessibilityHandler.getActions().invoke (AccessibilityActionType::press))
  469. {
  470. if (savedHandle != nullptr)
  471. sendAccessibilityEventImpl (accessibilityHandler, TYPE_VIEW_CLICKED, 0);
  472. return true;
  473. }
  474. break;
  475. }
  476. case ACTION_SELECT:
  477. case ACTION_CLEAR_SELECTION:
  478. {
  479. const auto state = accessibilityHandler.getCurrentState();
  480. if (state.isSelectable() || state.isMultiSelectable())
  481. {
  482. const auto isSelected = state.isSelected();
  483. if ((isSelected && action == ACTION_CLEAR_SELECTION)
  484. || (! isSelected && action == ACTION_SELECT))
  485. {
  486. return accessibilityHandler.getActions().invoke (AccessibilityActionType::toggle);
  487. }
  488. }
  489. break;
  490. }
  491. case ACTION_EXPAND:
  492. case ACTION_COLLAPSE:
  493. {
  494. const auto state = accessibilityHandler.getCurrentState();
  495. if (state.isExpandable())
  496. {
  497. const auto isExpanded = state.isExpanded();
  498. if ((isExpanded && action == ACTION_COLLAPSE)
  499. || (! isExpanded && action == ACTION_EXPAND))
  500. {
  501. return accessibilityHandler.getActions().invoke (AccessibilityActionType::showMenu);
  502. }
  503. }
  504. break;
  505. }
  506. case ACTION_NEXT_AT_MOVEMENT_GRANULARITY: return moveCursor (arguments, true);
  507. case ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: return moveCursor (arguments, false);
  508. case ACTION_SET_SELECTION:
  509. {
  510. if (auto* textInterface = accessibilityHandler.getTextInterface())
  511. {
  512. auto* env = getEnv();
  513. const auto selection = [&]() -> Range<int>
  514. {
  515. const auto selectionStartKey = javaString ("ACTION_ARGUMENT_SELECTION_START_INT");
  516. const auto selectionEndKey = javaString ("ACTION_ARGUMENT_SELECTION_END_INT");
  517. const auto hasKey = [&env, &arguments] (const auto& key)
  518. {
  519. return env->CallBooleanMethod (arguments, AndroidBundle.containsKey, key.get());
  520. };
  521. if (hasKey (selectionStartKey) && hasKey (selectionEndKey))
  522. {
  523. const auto getKey = [&env, &arguments] (const auto& key)
  524. {
  525. return env->CallIntMethod (arguments, AndroidBundle.getInt, key.get());
  526. };
  527. const auto start = getKey (selectionStartKey);
  528. const auto end = getKey (selectionEndKey);
  529. return Range<int>::between (start, end);
  530. }
  531. return {};
  532. }();
  533. textInterface->setSelection (selection);
  534. return true;
  535. }
  536. break;
  537. }
  538. case ACTION_SET_TEXT:
  539. {
  540. if (auto* textInterface = accessibilityHandler.getTextInterface())
  541. {
  542. if (! textInterface->isReadOnly())
  543. {
  544. const auto charSequenceKey = javaString ("ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE");
  545. auto* env = getEnv();
  546. const auto text = [&]() -> String
  547. {
  548. if (env->CallBooleanMethod (arguments, AndroidBundle.containsKey, charSequenceKey.get()))
  549. {
  550. LocalRef<jobject> charSequence (env->CallObjectMethod (arguments,
  551. AndroidBundle.getCharSequence,
  552. charSequenceKey.get()));
  553. LocalRef<jstring> textStringRef ((jstring) env->CallObjectMethod (charSequence,
  554. JavaCharSequence.toString));
  555. return juceString (textStringRef.get());
  556. }
  557. return {};
  558. }();
  559. textInterface->setText (text);
  560. }
  561. }
  562. break;
  563. }
  564. case ACTION_SCROLL_BACKWARD:
  565. case ACTION_SCROLL_FORWARD:
  566. {
  567. if (auto* valueInterface = accessibilityHandler.getValueInterface())
  568. {
  569. if (! valueInterface->isReadOnly())
  570. {
  571. const auto range = valueInterface->getRange();
  572. if (range.isValid())
  573. {
  574. const auto interval = action == ACTION_SCROLL_BACKWARD ? -range.getInterval()
  575. : range.getInterval();
  576. valueInterface->setValue (jlimit (range.getMinimumValue(),
  577. range.getMaximumValue(),
  578. valueInterface->getCurrentValue() + interval));
  579. // required for Android to announce the new value
  580. sendAccessibilityEventImpl (accessibilityHandler, TYPE_VIEW_SELECTED, 0);
  581. return true;
  582. }
  583. }
  584. }
  585. break;
  586. }
  587. }
  588. return false;
  589. }
  590. bool isInPopulateNodeInfo() const noexcept { return inPopulateNodeInfo; }
  591. static bool areAnyAccessibilityClientsActive()
  592. {
  593. auto* env = getEnv();
  594. auto appContext = getAppContext();
  595. if (appContext.get() != nullptr)
  596. {
  597. LocalRef<jobject> accessibilityManager (env->CallObjectMethod (appContext.get(), AndroidContext.getSystemService,
  598. javaString ("accessibility").get()));
  599. if (accessibilityManager != nullptr)
  600. return env->CallBooleanMethod (accessibilityManager.get(), AndroidAccessibilityManager.isEnabled);
  601. }
  602. return false;
  603. }
  604. template <typename ModificationCallback>
  605. static void sendAccessibilityEventExtendedImpl (const AccessibilityHandler& handler,
  606. int eventType,
  607. ModificationCallback&& modificationCallback)
  608. {
  609. if (! areAnyAccessibilityClientsActive())
  610. return;
  611. if (const auto sourceView = getSourceView (handler))
  612. {
  613. const auto* nativeImpl = handler.getNativeImplementation();
  614. if (nativeImpl == nullptr || nativeImpl->isInPopulateNodeInfo())
  615. return;
  616. auto* env = getEnv();
  617. auto appContext = getAppContext();
  618. if (appContext.get() == nullptr)
  619. return;
  620. LocalRef<jobject> event (env->CallStaticObjectMethod (AndroidAccessibilityEvent,
  621. AndroidAccessibilityEvent.obtain,
  622. eventType));
  623. env->CallVoidMethod (event,
  624. AndroidAccessibilityEvent.setPackageName,
  625. env->CallObjectMethod (appContext.get(),
  626. AndroidContext.getPackageName));
  627. env->CallVoidMethod (event,
  628. AndroidAccessibilityEvent.setSource,
  629. sourceView,
  630. nativeImpl->getVirtualViewId());
  631. modificationCallback (event);
  632. env->CallBooleanMethod (sourceView,
  633. AndroidViewGroup.requestSendAccessibilityEvent,
  634. sourceView,
  635. event.get());
  636. }
  637. }
  638. static void sendAccessibilityEventImpl (const AccessibilityHandler& handler, int eventType, int contentChangeTypes)
  639. {
  640. sendAccessibilityEventExtendedImpl (handler, eventType, [contentChangeTypes] (auto event)
  641. {
  642. if (contentChangeTypes != 0 && accessibilityEventSetContentChangeTypes != nullptr)
  643. getEnv()->CallVoidMethod (event,
  644. accessibilityEventSetContentChangeTypes,
  645. contentChangeTypes);
  646. });
  647. }
  648. private:
  649. static std::unordered_map<int, AccessibilityHandler*> virtualViewIdMap;
  650. static int getVirtualViewIdForHandler (const AccessibilityHandler& handler)
  651. {
  652. static int counter = 0;
  653. if (handler.getComponent().isOnDesktop())
  654. return HOST_VIEW_ID;
  655. return counter++;
  656. }
  657. LocalRef<jstring> getDescriptionString() const
  658. {
  659. const auto valueString = [this]() -> String
  660. {
  661. if (auto* textInterface = accessibilityHandler.getTextInterface())
  662. return textInterface->getAllText();
  663. if (auto* valueInterface = accessibilityHandler.getValueInterface())
  664. return valueInterface->getCurrentValueAsString();
  665. return {};
  666. }();
  667. StringArray strings (accessibilityHandler.getTitle(),
  668. valueString,
  669. accessibilityHandler.getDescription(),
  670. accessibilityHandler.getHelp());
  671. strings.removeEmptyStrings();
  672. return javaString (strings.joinIntoString (","));
  673. }
  674. bool moveCursor (jobject arguments, bool forwards)
  675. {
  676. using ATH = AccessibilityTextHelpers;
  677. auto* textInterface = accessibilityHandler.getTextInterface();
  678. if (textInterface == nullptr)
  679. return false;
  680. const auto granularityKey = javaString ("ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT");
  681. const auto extendSelectionKey = javaString ("ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN");
  682. auto* env = getEnv();
  683. const auto boundaryType = [&]
  684. {
  685. const auto granularity = env->CallIntMethod (arguments, AndroidBundle.getInt, granularityKey.get());
  686. using BoundaryType = ATH::BoundaryType;
  687. switch (granularity)
  688. {
  689. case MOVEMENT_GRANULARITY_CHARACTER: return BoundaryType::character;
  690. case MOVEMENT_GRANULARITY_WORD: return BoundaryType::word;
  691. case MOVEMENT_GRANULARITY_LINE: return BoundaryType::line;
  692. case MOVEMENT_GRANULARITY_PARAGRAPH:
  693. case MOVEMENT_GRANULARITY_PAGE: return BoundaryType::document;
  694. }
  695. jassertfalse;
  696. return BoundaryType::character;
  697. }();
  698. const auto direction = forwards
  699. ? ATH::Direction::forwards
  700. : ATH::Direction::backwards;
  701. const auto extend = env->CallBooleanMethod (arguments, AndroidBundle.getBoolean, extendSelectionKey.get())
  702. ? ATH::ExtendSelection::yes
  703. : ATH::ExtendSelection::no;
  704. const auto oldSelection = textInterface->getSelection();
  705. const auto newSelection = ATH::findNewSelectionRangeAndroid (*textInterface, boundaryType, extend, direction);
  706. textInterface->setSelection (newSelection);
  707. // Required for Android to read back the text that the cursor moved over
  708. sendAccessibilityEventExtendedImpl (accessibilityHandler, TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY, [&] (auto event)
  709. {
  710. env->CallVoidMethod (event,
  711. AndroidAccessibilityEvent.setAction,
  712. forwards ? ACTION_NEXT_AT_MOVEMENT_GRANULARITY : ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
  713. env->CallVoidMethod (event,
  714. AndroidAccessibilityEvent.setFromIndex,
  715. oldSelection.getStart() != newSelection.getStart() ? oldSelection.getStart()
  716. : oldSelection.getEnd());
  717. env->CallVoidMethod (event,
  718. AndroidAccessibilityEvent.setToIndex,
  719. oldSelection.getStart() != newSelection.getStart() ? newSelection.getStart()
  720. : newSelection.getEnd());
  721. });
  722. return true;
  723. }
  724. AccessibilityHandler& accessibilityHandler;
  725. const int virtualViewId;
  726. bool inPopulateNodeInfo = false;
  727. //==============================================================================
  728. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AccessibilityNativeHandle)
  729. JUCE_DECLARE_WEAK_REFERENCEABLE (AccessibilityNativeHandle)
  730. };
  731. std::unordered_map<int, AccessibilityHandler*> AccessibilityNativeHandle::virtualViewIdMap;
  732. class AccessibilityHandler::AccessibilityNativeImpl : public AccessibilityNativeHandle
  733. {
  734. public:
  735. using AccessibilityNativeHandle::AccessibilityNativeHandle;
  736. };
  737. //==============================================================================
  738. AccessibilityNativeHandle* AccessibilityHandler::getNativeImplementation() const
  739. {
  740. return nativeImpl.get();
  741. }
  742. void detail::AccessibilityHelpers::notifyAccessibilityEvent (const AccessibilityHandler& handler,
  743. Event eventType)
  744. {
  745. if (eventType == Event::elementCreated
  746. || eventType == Event::elementDestroyed
  747. || eventType == Event::elementMovedOrResized)
  748. {
  749. if (auto* parent = handler.getParent())
  750. AccessibilityNativeHandle::sendAccessibilityEventImpl (*parent, TYPE_WINDOW_CONTENT_CHANGED, CONTENT_CHANGE_TYPE_SUBTREE);
  751. return;
  752. }
  753. auto notification = [&handler, eventType]
  754. {
  755. switch (eventType)
  756. {
  757. case Event::focusChanged:
  758. return handler.hasFocus (false) ? TYPE_VIEW_ACCESSIBILITY_FOCUSED
  759. : TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED;
  760. case Event::elementCreated:
  761. case Event::elementDestroyed:
  762. case Event::elementMovedOrResized:
  763. case Event::windowOpened:
  764. case Event::windowClosed:
  765. break;
  766. }
  767. return 0;
  768. }();
  769. if (notification != 0)
  770. AccessibilityNativeHandle::sendAccessibilityEventImpl (handler, notification, 0);
  771. }
  772. void AccessibilityHandler::notifyAccessibilityEvent (AccessibilityEvent eventType) const
  773. {
  774. auto notification = [eventType]
  775. {
  776. switch (eventType)
  777. {
  778. case AccessibilityEvent::textSelectionChanged: return TYPE_VIEW_TEXT_SELECTION_CHANGED;
  779. case AccessibilityEvent::textChanged: return TYPE_VIEW_TEXT_CHANGED;
  780. case AccessibilityEvent::titleChanged:
  781. case AccessibilityEvent::structureChanged: return TYPE_WINDOW_CONTENT_CHANGED;
  782. case AccessibilityEvent::rowSelectionChanged:
  783. case AccessibilityEvent::valueChanged: break;
  784. }
  785. return 0;
  786. }();
  787. if (notification == 0)
  788. return;
  789. const auto contentChangeTypes = [eventType]
  790. {
  791. if (eventType == AccessibilityEvent::titleChanged) return CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION;
  792. if (eventType == AccessibilityEvent::structureChanged) return CONTENT_CHANGE_TYPE_SUBTREE;
  793. return 0;
  794. }();
  795. AccessibilityNativeHandle::sendAccessibilityEventImpl (*this, notification, contentChangeTypes);
  796. }
  797. void AccessibilityHandler::postAnnouncement (const String& announcementString,
  798. AnnouncementPriority)
  799. {
  800. if (! AccessibilityNativeHandle::areAnyAccessibilityClientsActive())
  801. return;
  802. const auto rootView = []
  803. {
  804. LocalRef<jobject> activity (getMainActivity());
  805. if (activity != nullptr)
  806. {
  807. auto* env = getEnv();
  808. LocalRef<jobject> mainWindow (env->CallObjectMethod (activity.get(), AndroidActivity.getWindow));
  809. LocalRef<jobject> decorView (env->CallObjectMethod (mainWindow.get(), AndroidWindow.getDecorView));
  810. return LocalRef<jobject> (env->CallObjectMethod (decorView.get(), AndroidView.getRootView));
  811. }
  812. return LocalRef<jobject>();
  813. }();
  814. if (rootView != nullptr)
  815. getEnv()->CallVoidMethod (rootView.get(),
  816. AndroidView.announceForAccessibility,
  817. javaString (announcementString).get());
  818. }
  819. } // namespace juce