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.

1034 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. else
  241. env->CallVoidMethod (info, AndroidAccessibilityNodeInfo.setParent, sourceView);
  242. }
  243. {
  244. const auto scale = Desktop::getInstance().getDisplays().getPrimaryDisplay()->scale;
  245. LocalRef<jobject> screenBounds (makeAndroidRect (accessibilityHandler.getComponent().getScreenBounds() * scale));
  246. env->CallVoidMethod (info, AndroidAccessibilityNodeInfo.setBoundsInScreen, screenBounds.get());
  247. LocalRef<jobject> boundsInParent (makeAndroidRect (accessibilityHandler.getComponent().getBoundsInParent() * scale));
  248. env->CallVoidMethod (info, AndroidAccessibilityNodeInfo.setBoundsInParent, boundsInParent.get());
  249. }
  250. const auto state = accessibilityHandler.getCurrentState();
  251. env->CallVoidMethod (info,
  252. AndroidAccessibilityNodeInfo.setEnabled,
  253. ! state.isIgnored());
  254. env->CallVoidMethod (info,
  255. AndroidAccessibilityNodeInfo.setVisibleToUser,
  256. true);
  257. env->CallVoidMethod (info,
  258. AndroidAccessibilityNodeInfo.setPackageName,
  259. env->CallObjectMethod (appContext.get(),
  260. AndroidContext.getPackageName));
  261. env->CallVoidMethod (info,
  262. AndroidAccessibilityNodeInfo.setSource,
  263. sourceView,
  264. virtualViewId);
  265. env->CallVoidMethod (info,
  266. AndroidAccessibilityNodeInfo.setClassName,
  267. javaString (getClassName (accessibilityHandler.getRole())).get());
  268. env->CallVoidMethod (info,
  269. AndroidAccessibilityNodeInfo.setContentDescription,
  270. getDescriptionString().get());
  271. if (state.isFocusable())
  272. {
  273. env->CallVoidMethod (info, AndroidAccessibilityNodeInfo.setFocusable, true);
  274. const auto& component = accessibilityHandler.getComponent();
  275. if (component.getWantsKeyboardFocus())
  276. {
  277. const auto hasKeyboardFocus = component.hasKeyboardFocus (false);
  278. env->CallVoidMethod (info,
  279. AndroidAccessibilityNodeInfo.setFocused,
  280. hasKeyboardFocus);
  281. env->CallVoidMethod (info,
  282. AndroidAccessibilityNodeInfo.addAction,
  283. hasKeyboardFocus ? ACTION_CLEAR_FOCUS : ACTION_FOCUS);
  284. }
  285. const auto isAccessibleFocused = accessibilityHandler.hasFocus (false);
  286. env->CallVoidMethod (info,
  287. AndroidAccessibilityNodeInfo.setAccessibilityFocused,
  288. isAccessibleFocused);
  289. env->CallVoidMethod (info,
  290. AndroidAccessibilityNodeInfo.addAction,
  291. isAccessibleFocused ? ACTION_CLEAR_ACCESSIBILITY_FOCUS
  292. : ACTION_ACCESSIBILITY_FOCUS);
  293. }
  294. if (state.isCheckable())
  295. {
  296. env->CallVoidMethod (info,
  297. AndroidAccessibilityNodeInfo.setCheckable,
  298. true);
  299. env->CallVoidMethod (info,
  300. AndroidAccessibilityNodeInfo.setChecked,
  301. state.isChecked());
  302. }
  303. if (state.isSelectable() || state.isMultiSelectable())
  304. {
  305. const auto isSelected = state.isSelected();
  306. env->CallVoidMethod (info,
  307. AndroidAccessibilityNodeInfo.setSelected,
  308. isSelected);
  309. env->CallVoidMethod (info,
  310. AndroidAccessibilityNodeInfo.addAction,
  311. isSelected ? ACTION_CLEAR_SELECTION : ACTION_SELECT);
  312. }
  313. if ((accessibilityHandler.getCurrentState().isCheckable() && accessibilityHandler.getActions().contains (AccessibilityActionType::toggle))
  314. || accessibilityHandler.getActions().contains (AccessibilityActionType::press))
  315. {
  316. env->CallVoidMethod (info,
  317. AndroidAccessibilityNodeInfo.setClickable,
  318. true);
  319. env->CallVoidMethod (info,
  320. AndroidAccessibilityNodeInfo.addAction,
  321. ACTION_CLICK);
  322. }
  323. if (accessibilityHandler.getActions().contains (AccessibilityActionType::showMenu)
  324. && state.isExpandable())
  325. {
  326. env->CallVoidMethod (info,
  327. AndroidAccessibilityNodeInfo.addAction,
  328. state.isExpanded() ? ACTION_COLLAPSE : ACTION_EXPAND);
  329. }
  330. if (auto* textInterface = accessibilityHandler.getTextInterface())
  331. {
  332. env->CallVoidMethod (info,
  333. AndroidAccessibilityNodeInfo.setText,
  334. javaString (textInterface->getAllText()).get());
  335. const auto isReadOnly = textInterface->isReadOnly();
  336. env->CallVoidMethod (info,
  337. AndroidAccessibilityNodeInfo.setPassword,
  338. textInterface->isDisplayingProtectedText());
  339. if (nodeInfoSetEditable != nullptr)
  340. env->CallVoidMethod (info, nodeInfoSetEditable, ! isReadOnly);
  341. const auto selection = textInterface->getSelection();
  342. if (nodeInfoSetTextSelection != nullptr && ! selection.isEmpty())
  343. env->CallVoidMethod (info,
  344. nodeInfoSetTextSelection,
  345. selection.getStart(), selection.getEnd());
  346. if (nodeInfoSetLiveRegion != nullptr && accessibilityHandler.hasFocus (false))
  347. env->CallVoidMethod (info,
  348. nodeInfoSetLiveRegion,
  349. ACCESSIBILITY_LIVE_REGION_POLITE);
  350. env->CallVoidMethod (info,
  351. AndroidAccessibilityNodeInfo.setMovementGranularities,
  352. ALL_GRANULARITIES);
  353. env->CallVoidMethod (info,
  354. AndroidAccessibilityNodeInfo.addAction,
  355. ACTION_NEXT_AT_MOVEMENT_GRANULARITY);
  356. env->CallVoidMethod (info,
  357. AndroidAccessibilityNodeInfo.addAction,
  358. ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
  359. env->CallVoidMethod (info,
  360. AndroidAccessibilityNodeInfo.addAction,
  361. ACTION_SET_SELECTION);
  362. if (! isReadOnly)
  363. env->CallVoidMethod (info, AndroidAccessibilityNodeInfo.addAction, ACTION_SET_TEXT);
  364. }
  365. if (auto* valueInterface = accessibilityHandler.getValueInterface())
  366. {
  367. if (! valueInterface->isReadOnly())
  368. {
  369. const auto range = valueInterface->getRange();
  370. if (range.isValid())
  371. {
  372. env->CallVoidMethod (info,
  373. AndroidAccessibilityNodeInfo.addAction,
  374. ACTION_SCROLL_FORWARD);
  375. env->CallVoidMethod (info,
  376. AndroidAccessibilityNodeInfo.addAction,
  377. ACTION_SCROLL_BACKWARD);
  378. }
  379. }
  380. }
  381. if (getAndroidSDKVersion() >= 19)
  382. {
  383. if (auto* tableInterface = accessibilityHandler.getTableInterface())
  384. {
  385. const auto rows = tableInterface->getNumRows();
  386. const auto columns = tableInterface->getNumColumns();
  387. const LocalRef<jobject> collectionInfo { env->CallStaticObjectMethod (AndroidAccessibilityNodeInfoCollectionInfo,
  388. AndroidAccessibilityNodeInfoCollectionInfo.obtain,
  389. (jint) rows,
  390. (jint) columns,
  391. (jboolean) false) };
  392. env->CallVoidMethod (info, AndroidAccessibilityNodeInfo19.setCollectionInfo, collectionInfo.get());
  393. }
  394. if (auto* enclosingTableHandler = detail::AccessibilityHelpers::getEnclosingHandlerWithInterface (&accessibilityHandler, &AccessibilityHandler::getTableInterface))
  395. {
  396. auto* interface = enclosingTableHandler->getTableInterface();
  397. jassert (interface != nullptr);
  398. const auto rowSpan = interface->getRowSpan (accessibilityHandler);
  399. const auto columnSpan = interface->getColumnSpan (accessibilityHandler);
  400. enum class IsHeader { no, yes };
  401. const auto addCellInfo = [env, &info] (AccessibilityTableInterface::Span rows, AccessibilityTableInterface::Span columns, IsHeader header)
  402. {
  403. const LocalRef<jobject> collectionItemInfo { env->CallStaticObjectMethod (AndroidAccessibilityNodeInfoCollectionItemInfo,
  404. AndroidAccessibilityNodeInfoCollectionItemInfo.obtain,
  405. (jint) rows.begin,
  406. (jint) rows.num,
  407. (jint) columns.begin,
  408. (jint) columns.num,
  409. (jboolean) (header == IsHeader::yes)) };
  410. env->CallVoidMethod (info, AndroidAccessibilityNodeInfo19.setCollectionItemInfo, collectionItemInfo.get());
  411. };
  412. if (rowSpan.hasValue() && columnSpan.hasValue())
  413. {
  414. addCellInfo (*rowSpan, *columnSpan, IsHeader::no);
  415. }
  416. else
  417. {
  418. if (auto* tableHeader = interface->getHeaderHandler())
  419. {
  420. if (accessibilityHandler.getParent() == tableHeader)
  421. {
  422. const auto children = tableHeader->getChildren();
  423. const auto column = std::distance (children.cbegin(), std::find (children.cbegin(), children.cend(), &accessibilityHandler));
  424. // Talkback will only treat a row as a column header if its row index is zero
  425. // https://github.com/google/talkback/blob/acd0bc7631a3dfbcf183789c7557596a45319e1f/utils/src/main/java/CollectionState.java#L853
  426. addCellInfo ({ 0, 1 }, { (int) column, 1 }, IsHeader::yes);
  427. }
  428. }
  429. }
  430. }
  431. }
  432. }
  433. bool performAction (int action, jobject arguments)
  434. {
  435. switch (action)
  436. {
  437. case ACTION_ACCESSIBILITY_FOCUS:
  438. {
  439. const WeakReference<Component> safeComponent (&accessibilityHandler.getComponent());
  440. accessibilityHandler.getActions().invoke (AccessibilityActionType::focus);
  441. if (safeComponent != nullptr)
  442. accessibilityHandler.grabFocus();
  443. return true;
  444. }
  445. case ACTION_CLEAR_ACCESSIBILITY_FOCUS:
  446. {
  447. accessibilityHandler.giveAwayFocus();
  448. return true;
  449. }
  450. case ACTION_FOCUS:
  451. case ACTION_CLEAR_FOCUS:
  452. {
  453. auto& component = accessibilityHandler.getComponent();
  454. if (component.getWantsKeyboardFocus())
  455. {
  456. const auto hasFocus = component.hasKeyboardFocus (false);
  457. if (hasFocus && action == ACTION_CLEAR_FOCUS)
  458. component.giveAwayKeyboardFocus();
  459. else if (! hasFocus && action == ACTION_FOCUS)
  460. component.grabKeyboardFocus();
  461. return true;
  462. }
  463. break;
  464. }
  465. case ACTION_CLICK:
  466. {
  467. // Invoking the action may delete this handler
  468. const WeakReference<AccessibilityNativeHandle> savedHandle { this };
  469. if ((accessibilityHandler.getCurrentState().isCheckable() && accessibilityHandler.getActions().invoke (AccessibilityActionType::toggle))
  470. || accessibilityHandler.getActions().invoke (AccessibilityActionType::press))
  471. {
  472. if (savedHandle != nullptr)
  473. sendAccessibilityEventImpl (accessibilityHandler, TYPE_VIEW_CLICKED, 0);
  474. return true;
  475. }
  476. break;
  477. }
  478. case ACTION_SELECT:
  479. case ACTION_CLEAR_SELECTION:
  480. {
  481. const auto state = accessibilityHandler.getCurrentState();
  482. if (state.isSelectable() || state.isMultiSelectable())
  483. {
  484. const auto isSelected = state.isSelected();
  485. if ((isSelected && action == ACTION_CLEAR_SELECTION)
  486. || (! isSelected && action == ACTION_SELECT))
  487. {
  488. return accessibilityHandler.getActions().invoke (AccessibilityActionType::toggle);
  489. }
  490. }
  491. break;
  492. }
  493. case ACTION_EXPAND:
  494. case ACTION_COLLAPSE:
  495. {
  496. const auto state = accessibilityHandler.getCurrentState();
  497. if (state.isExpandable())
  498. {
  499. const auto isExpanded = state.isExpanded();
  500. if ((isExpanded && action == ACTION_COLLAPSE)
  501. || (! isExpanded && action == ACTION_EXPAND))
  502. {
  503. return accessibilityHandler.getActions().invoke (AccessibilityActionType::showMenu);
  504. }
  505. }
  506. break;
  507. }
  508. case ACTION_NEXT_AT_MOVEMENT_GRANULARITY: return moveCursor (arguments, true);
  509. case ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY: return moveCursor (arguments, false);
  510. case ACTION_SET_SELECTION:
  511. {
  512. if (auto* textInterface = accessibilityHandler.getTextInterface())
  513. {
  514. auto* env = getEnv();
  515. const auto selection = [&]() -> Range<int>
  516. {
  517. const auto selectionStartKey = javaString ("ACTION_ARGUMENT_SELECTION_START_INT");
  518. const auto selectionEndKey = javaString ("ACTION_ARGUMENT_SELECTION_END_INT");
  519. const auto hasKey = [&env, &arguments] (const auto& key)
  520. {
  521. return env->CallBooleanMethod (arguments, AndroidBundle.containsKey, key.get());
  522. };
  523. if (hasKey (selectionStartKey) && hasKey (selectionEndKey))
  524. {
  525. const auto getKey = [&env, &arguments] (const auto& key)
  526. {
  527. return env->CallIntMethod (arguments, AndroidBundle.getInt, key.get());
  528. };
  529. const auto start = getKey (selectionStartKey);
  530. const auto end = getKey (selectionEndKey);
  531. return Range<int>::between (start, end);
  532. }
  533. return {};
  534. }();
  535. textInterface->setSelection (selection);
  536. return true;
  537. }
  538. break;
  539. }
  540. case ACTION_SET_TEXT:
  541. {
  542. if (auto* textInterface = accessibilityHandler.getTextInterface())
  543. {
  544. if (! textInterface->isReadOnly())
  545. {
  546. const auto charSequenceKey = javaString ("ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE");
  547. auto* env = getEnv();
  548. const auto text = [&]() -> String
  549. {
  550. if (env->CallBooleanMethod (arguments, AndroidBundle.containsKey, charSequenceKey.get()))
  551. {
  552. LocalRef<jobject> charSequence (env->CallObjectMethod (arguments,
  553. AndroidBundle.getCharSequence,
  554. charSequenceKey.get()));
  555. LocalRef<jstring> textStringRef ((jstring) env->CallObjectMethod (charSequence,
  556. JavaCharSequence.toString));
  557. return juceString (textStringRef.get());
  558. }
  559. return {};
  560. }();
  561. textInterface->setText (text);
  562. }
  563. }
  564. break;
  565. }
  566. case ACTION_SCROLL_BACKWARD:
  567. case ACTION_SCROLL_FORWARD:
  568. {
  569. if (auto* valueInterface = accessibilityHandler.getValueInterface())
  570. {
  571. if (! valueInterface->isReadOnly())
  572. {
  573. const auto range = valueInterface->getRange();
  574. if (range.isValid())
  575. {
  576. const auto interval = action == ACTION_SCROLL_BACKWARD ? -range.getInterval()
  577. : range.getInterval();
  578. valueInterface->setValue (jlimit (range.getMinimumValue(),
  579. range.getMaximumValue(),
  580. valueInterface->getCurrentValue() + interval));
  581. // required for Android to announce the new value
  582. sendAccessibilityEventImpl (accessibilityHandler, TYPE_VIEW_SELECTED, 0);
  583. return true;
  584. }
  585. }
  586. }
  587. break;
  588. }
  589. }
  590. return false;
  591. }
  592. bool isInPopulateNodeInfo() const noexcept { return inPopulateNodeInfo; }
  593. static bool areAnyAccessibilityClientsActive()
  594. {
  595. auto* env = getEnv();
  596. auto appContext = getAppContext();
  597. if (appContext.get() != nullptr)
  598. {
  599. LocalRef<jobject> accessibilityManager (env->CallObjectMethod (appContext.get(), AndroidContext.getSystemService,
  600. javaString ("accessibility").get()));
  601. if (accessibilityManager != nullptr)
  602. return env->CallBooleanMethod (accessibilityManager.get(), AndroidAccessibilityManager.isEnabled);
  603. }
  604. return false;
  605. }
  606. template <typename ModificationCallback>
  607. static void sendAccessibilityEventExtendedImpl (const AccessibilityHandler& handler,
  608. int eventType,
  609. ModificationCallback&& modificationCallback)
  610. {
  611. if (! areAnyAccessibilityClientsActive())
  612. return;
  613. if (const auto sourceView = getSourceView (handler))
  614. {
  615. const auto* nativeImpl = handler.getNativeImplementation();
  616. if (nativeImpl == nullptr || nativeImpl->isInPopulateNodeInfo())
  617. return;
  618. auto* env = getEnv();
  619. auto appContext = getAppContext();
  620. if (appContext.get() == nullptr)
  621. return;
  622. LocalRef<jobject> event (env->CallStaticObjectMethod (AndroidAccessibilityEvent,
  623. AndroidAccessibilityEvent.obtain,
  624. eventType));
  625. env->CallVoidMethod (event,
  626. AndroidAccessibilityEvent.setPackageName,
  627. env->CallObjectMethod (appContext.get(),
  628. AndroidContext.getPackageName));
  629. env->CallVoidMethod (event,
  630. AndroidAccessibilityEvent.setSource,
  631. sourceView,
  632. nativeImpl->getVirtualViewId());
  633. modificationCallback (event);
  634. env->CallBooleanMethod (sourceView,
  635. AndroidViewGroup.requestSendAccessibilityEvent,
  636. sourceView,
  637. event.get());
  638. }
  639. }
  640. static void sendAccessibilityEventImpl (const AccessibilityHandler& handler, int eventType, int contentChangeTypes)
  641. {
  642. sendAccessibilityEventExtendedImpl (handler, eventType, [contentChangeTypes] (auto event)
  643. {
  644. if (contentChangeTypes != 0 && accessibilityEventSetContentChangeTypes != nullptr)
  645. getEnv()->CallVoidMethod (event,
  646. accessibilityEventSetContentChangeTypes,
  647. contentChangeTypes);
  648. });
  649. }
  650. private:
  651. static std::unordered_map<int, AccessibilityHandler*> virtualViewIdMap;
  652. static int getVirtualViewIdForHandler (const AccessibilityHandler& handler)
  653. {
  654. static int counter = 0;
  655. if (handler.getComponent().isOnDesktop())
  656. return HOST_VIEW_ID;
  657. return counter++;
  658. }
  659. LocalRef<jstring> getDescriptionString() const
  660. {
  661. const auto valueString = [this]() -> String
  662. {
  663. if (auto* textInterface = accessibilityHandler.getTextInterface())
  664. return textInterface->getAllText();
  665. if (auto* valueInterface = accessibilityHandler.getValueInterface())
  666. return valueInterface->getCurrentValueAsString();
  667. return {};
  668. }();
  669. StringArray strings (accessibilityHandler.getTitle(),
  670. valueString,
  671. accessibilityHandler.getDescription(),
  672. accessibilityHandler.getHelp());
  673. strings.removeEmptyStrings();
  674. return javaString (strings.joinIntoString (","));
  675. }
  676. bool moveCursor (jobject arguments, bool forwards)
  677. {
  678. using ATH = AccessibilityTextHelpers;
  679. auto* textInterface = accessibilityHandler.getTextInterface();
  680. if (textInterface == nullptr)
  681. return false;
  682. const auto granularityKey = javaString ("ACTION_ARGUMENT_MOVEMENT_GRANULARITY_INT");
  683. const auto extendSelectionKey = javaString ("ACTION_ARGUMENT_EXTEND_SELECTION_BOOLEAN");
  684. auto* env = getEnv();
  685. const auto boundaryType = [&]
  686. {
  687. const auto granularity = env->CallIntMethod (arguments, AndroidBundle.getInt, granularityKey.get());
  688. using BoundaryType = ATH::BoundaryType;
  689. switch (granularity)
  690. {
  691. case MOVEMENT_GRANULARITY_CHARACTER: return BoundaryType::character;
  692. case MOVEMENT_GRANULARITY_WORD: return BoundaryType::word;
  693. case MOVEMENT_GRANULARITY_LINE: return BoundaryType::line;
  694. case MOVEMENT_GRANULARITY_PARAGRAPH:
  695. case MOVEMENT_GRANULARITY_PAGE: return BoundaryType::document;
  696. }
  697. jassertfalse;
  698. return BoundaryType::character;
  699. }();
  700. const auto direction = forwards
  701. ? ATH::Direction::forwards
  702. : ATH::Direction::backwards;
  703. const auto extend = env->CallBooleanMethod (arguments, AndroidBundle.getBoolean, extendSelectionKey.get())
  704. ? ATH::ExtendSelection::yes
  705. : ATH::ExtendSelection::no;
  706. const auto oldSelection = textInterface->getSelection();
  707. const auto newSelection = ATH::findNewSelectionRangeAndroid (*textInterface, boundaryType, extend, direction);
  708. textInterface->setSelection (newSelection);
  709. // Required for Android to read back the text that the cursor moved over
  710. sendAccessibilityEventExtendedImpl (accessibilityHandler, TYPE_VIEW_TEXT_TRAVERSED_AT_MOVEMENT_GRANULARITY, [&] (auto event)
  711. {
  712. env->CallVoidMethod (event,
  713. AndroidAccessibilityEvent.setAction,
  714. forwards ? ACTION_NEXT_AT_MOVEMENT_GRANULARITY : ACTION_PREVIOUS_AT_MOVEMENT_GRANULARITY);
  715. env->CallVoidMethod (event,
  716. AndroidAccessibilityEvent.setFromIndex,
  717. oldSelection.getStart() != newSelection.getStart() ? oldSelection.getStart()
  718. : oldSelection.getEnd());
  719. env->CallVoidMethod (event,
  720. AndroidAccessibilityEvent.setToIndex,
  721. oldSelection.getStart() != newSelection.getStart() ? newSelection.getStart()
  722. : newSelection.getEnd());
  723. });
  724. return true;
  725. }
  726. AccessibilityHandler& accessibilityHandler;
  727. const int virtualViewId;
  728. bool inPopulateNodeInfo = false;
  729. //==============================================================================
  730. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AccessibilityNativeHandle)
  731. JUCE_DECLARE_WEAK_REFERENCEABLE (AccessibilityNativeHandle)
  732. };
  733. std::unordered_map<int, AccessibilityHandler*> AccessibilityNativeHandle::virtualViewIdMap;
  734. class AccessibilityHandler::AccessibilityNativeImpl : public AccessibilityNativeHandle
  735. {
  736. public:
  737. using AccessibilityNativeHandle::AccessibilityNativeHandle;
  738. };
  739. //==============================================================================
  740. AccessibilityNativeHandle* AccessibilityHandler::getNativeImplementation() const
  741. {
  742. return nativeImpl.get();
  743. }
  744. void detail::AccessibilityHelpers::notifyAccessibilityEvent (const AccessibilityHandler& handler,
  745. Event eventType)
  746. {
  747. if (eventType == Event::elementCreated
  748. || eventType == Event::elementDestroyed
  749. || eventType == Event::elementMovedOrResized)
  750. {
  751. if (auto* parent = handler.getParent())
  752. AccessibilityNativeHandle::sendAccessibilityEventImpl (*parent, TYPE_WINDOW_CONTENT_CHANGED, CONTENT_CHANGE_TYPE_SUBTREE);
  753. return;
  754. }
  755. auto notification = [&handler, eventType]
  756. {
  757. switch (eventType)
  758. {
  759. case Event::focusChanged:
  760. return handler.hasFocus (false) ? TYPE_VIEW_ACCESSIBILITY_FOCUSED
  761. : TYPE_VIEW_ACCESSIBILITY_FOCUS_CLEARED;
  762. case Event::elementCreated:
  763. case Event::elementDestroyed:
  764. case Event::elementMovedOrResized:
  765. case Event::windowOpened:
  766. case Event::windowClosed:
  767. break;
  768. }
  769. return 0;
  770. }();
  771. if (notification != 0)
  772. AccessibilityNativeHandle::sendAccessibilityEventImpl (handler, notification, 0);
  773. }
  774. void AccessibilityHandler::notifyAccessibilityEvent (AccessibilityEvent eventType) const
  775. {
  776. auto notification = [eventType]
  777. {
  778. switch (eventType)
  779. {
  780. case AccessibilityEvent::textSelectionChanged: return TYPE_VIEW_TEXT_SELECTION_CHANGED;
  781. case AccessibilityEvent::textChanged: return TYPE_VIEW_TEXT_CHANGED;
  782. case AccessibilityEvent::titleChanged:
  783. case AccessibilityEvent::structureChanged: return TYPE_WINDOW_CONTENT_CHANGED;
  784. case AccessibilityEvent::rowSelectionChanged:
  785. case AccessibilityEvent::valueChanged: break;
  786. }
  787. return 0;
  788. }();
  789. if (notification == 0)
  790. return;
  791. const auto contentChangeTypes = [eventType]
  792. {
  793. if (eventType == AccessibilityEvent::titleChanged) return CONTENT_CHANGE_TYPE_CONTENT_DESCRIPTION;
  794. if (eventType == AccessibilityEvent::structureChanged) return CONTENT_CHANGE_TYPE_SUBTREE;
  795. return 0;
  796. }();
  797. AccessibilityNativeHandle::sendAccessibilityEventImpl (*this, notification, contentChangeTypes);
  798. }
  799. void AccessibilityHandler::postAnnouncement (const String& announcementString,
  800. AnnouncementPriority)
  801. {
  802. if (! AccessibilityNativeHandle::areAnyAccessibilityClientsActive())
  803. return;
  804. const auto rootView = []
  805. {
  806. LocalRef<jobject> activity (getMainActivity());
  807. if (activity != nullptr)
  808. {
  809. auto* env = getEnv();
  810. LocalRef<jobject> mainWindow (env->CallObjectMethod (activity.get(), AndroidActivity.getWindow));
  811. LocalRef<jobject> decorView (env->CallObjectMethod (mainWindow.get(), AndroidWindow.getDecorView));
  812. return LocalRef<jobject> (env->CallObjectMethod (decorView.get(), AndroidView.getRootView));
  813. }
  814. return LocalRef<jobject>();
  815. }();
  816. if (rootView != nullptr)
  817. getEnv()->CallVoidMethod (rootView.get(),
  818. AndroidView.announceForAccessibility,
  819. javaString (announcementString).get());
  820. }
  821. } // namespace juce