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.

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