1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085
|
// Copyright 2022 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifdef UNSAFE_BUFFERS_BUILD
// TODO(crbug.com/390223051): Remove C-library calls to fix the errors.
#pragma allow_unsafe_libc_calls
#endif
#include "chrome/renderer/accessibility/read_anything/read_anything_app_controller.h"
#include <climits>
#include <memory>
#include <optional>
#include <queue>
#include <string>
#include <utility>
#include <vector>
#include "base/check_deref.h"
#include "base/containers/fixed_flat_map.h"
#include "base/metrics/histogram_functions.h"
#include "base/metrics/metrics_hashes.h"
#include "base/notreached.h"
#include "base/strings/strcat.h"
#include "base/strings/string_util.h"
#include "base/strings/to_string.h"
#include "base/strings/utf_string_conversions.h"
#include "base/types/cxx23_to_underlying.h"
#include "build/build_config.h"
#include "chrome/common/read_anything/read_anything_util.h"
#include "chrome/renderer/accessibility/ax_tree_distiller.h"
#include "chrome/renderer/accessibility/phrase_segmentation/dependency_parser_model.h"
#include "chrome/renderer/accessibility/read_anything/read_aloud_traversal_utils.h"
#include "chrome/renderer/accessibility/read_anything/read_anything_app_model.h"
#include "chrome/renderer/accessibility/read_anything/read_anything_node_utils.h"
#include "components/language/core/common/locale_util.h"
#include "components/translate/core/common/translate_constants.h"
#include "content/public/renderer/chrome_object_extensions_utils.h"
#include "content/public/renderer/render_frame.h"
#include "content/public/renderer/render_thread.h"
#include "gin/converter.h"
#include "gin/dictionary.h"
#include "gin/handle.h"
#include "gin/object_template_builder.h"
#include "services/metrics/public/cpp/mojo_ukm_recorder.h"
#include "services/metrics/public/cpp/ukm_builders.h"
#include "third_party/blink/public/platform/browser_interface_broker_proxy.h"
#include "third_party/blink/public/platform/scheduler/web_agent_group_scheduler.h"
#include "third_party/blink/public/web/web_local_frame.h"
#include "third_party/blink/public/web/web_script_source.h"
#include "third_party/re2/src/re2/re2.h"
#include "third_party/skia/include/core/SkColorSpace.h"
#include "third_party/skia/include/core/SkColorType.h"
#include "third_party/skia/include/core/SkData.h"
#include "third_party/skia/include/core/SkImageInfo.h"
#include "ui/accessibility/accessibility_features.h"
#include "ui/accessibility/ax_enums.mojom-shared.h"
#include "ui/accessibility/ax_location_and_scroll_updates.h"
#include "ui/accessibility/ax_node.h"
#include "ui/accessibility/ax_node_id_forward.h"
#include "ui/accessibility/ax_role_properties.h"
#include "ui/accessibility/ax_selection.h"
#include "ui/accessibility/ax_serializable_tree.h"
#include "ui/accessibility/ax_text_utils.h"
#include "ui/accessibility/ax_tree.h"
#include "ui/accessibility/ax_tree_id.h"
#include "ui/accessibility/ax_tree_serializer.h"
#include "ui/accessibility/ax_tree_update.h"
#include "ui/accessibility/mojom/ax_event.mojom.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/gfx/geometry/size.h"
#include "url/url_util.h"
#include "v8/include/v8-context.h"
#include "v8/include/v8-microtask-queue.h"
#include "v8/include/v8-typed-array.h"
namespace {
constexpr char kUndeterminedLocale[] = "und";
// The number of seconds to wait before distilling after a user has stopped
// entering text into a richly editable text field.
const double kPostInputDistillSeconds = 1.5;
// The following methods convert v8::Value types to an AXTreeUpdate. This is not
// a complete conversion (thus way gin::Converter<ui::AXTreeUpdate> is not used
// or implemented) but just converting the bare minimum data types needed for
// the ReadAnythingAppTest.
void SetAXNodeDataChildIds(v8::Isolate* isolate,
gin::Dictionary* v8_dict,
ui::AXNodeData* ax_node_data) {
v8::Local<v8::Value> v8_child_ids;
v8_dict->Get("childIds", &v8_child_ids);
std::vector<int32_t> child_ids;
if (!gin::ConvertFromV8(isolate, v8_child_ids, &child_ids)) {
return;
}
ax_node_data->child_ids = std::move(child_ids);
}
void SetAXNodeDataId(v8::Isolate* isolate,
gin::Dictionary* v8_dict,
ui::AXNodeData* ax_node_data) {
v8::Local<v8::Value> v8_id;
v8_dict->Get("id", &v8_id);
ui::AXNodeID id;
if (!gin::ConvertFromV8(isolate, v8_id, &id)) {
return;
}
ax_node_data->id = id;
}
void SetAXNodeDataLanguage(v8::Isolate* isolate,
gin::Dictionary* v8_dict,
ui::AXNodeData* ax_node_data) {
v8::Local<v8::Value> v8_language;
v8_dict->Get("language", &v8_language);
std::string language;
if (!gin::ConvertFromV8(isolate, v8_language, &language)) {
return;
}
ax_node_data->AddStringAttribute(ax::mojom::StringAttribute::kLanguage,
language);
}
void SetAXNodeDataName(v8::Isolate* isolate,
gin::Dictionary* v8_dict,
ui::AXNodeData* ax_node_data) {
v8::Local<v8::Value> v8_name;
v8_dict->Get("name", &v8_name);
std::string name;
if (!gin::ConvertFromV8(isolate, v8_name, &name)) {
return;
}
ax_node_data->SetName(name);
ax_node_data->SetNameFrom(ax::mojom::NameFrom::kContents);
}
void SetAXNodeDataRole(v8::Isolate* isolate,
gin::Dictionary* v8_dict,
ui::AXNodeData* ax_node_data) {
v8::Local<v8::Value> v8_role;
v8_dict->Get("role", &v8_role);
std::string role_name;
if (!gin::ConvertFromV8(isolate, v8_role, &role_name)) {
return;
}
if (role_name == "rootWebArea") {
ax_node_data->role = ax::mojom::Role::kRootWebArea;
} else if (role_name == "heading") {
ax_node_data->role = ax::mojom::Role::kHeading;
} else if (role_name == "link") {
ax_node_data->role = ax::mojom::Role::kLink;
} else if (role_name == "paragraph") {
ax_node_data->role = ax::mojom::Role::kParagraph;
} else if (role_name == "staticText") {
ax_node_data->role = ax::mojom::Role::kStaticText;
} else if (role_name == "button") {
ax_node_data->role = ax::mojom::Role::kButton;
}
}
void SetAXNodeDataHtmlTag(v8::Isolate* isolate,
gin::Dictionary* v8_dict,
ui::AXNodeData* ax_node_data) {
v8::Local<v8::Value> v8_html_tag;
v8_dict->Get("htmlTag", &v8_html_tag);
std::string html_tag;
if (!gin::Converter<std::string>::FromV8(isolate, v8_html_tag, &html_tag)) {
return;
}
ax_node_data->AddStringAttribute(ax::mojom::StringAttribute::kHtmlTag,
html_tag);
}
void SetAXNodeDataDisplay(v8::Isolate* isolate,
gin::Dictionary* v8_dict,
ui::AXNodeData* ax_node_data) {
v8::Local<v8::Value> v8_display;
v8_dict->Get("display", &v8_display);
std::string display;
if (!gin::Converter<std::string>::FromV8(isolate, v8_display, &display)) {
return;
}
ax_node_data->AddStringAttribute(ax::mojom::StringAttribute::kDisplay,
display);
}
void SetAXNodeDataTextDirection(v8::Isolate* isolate,
gin::Dictionary* v8_dict,
ui::AXNodeData* ax_node_data) {
v8::Local<v8::Value> v8_direction;
v8_dict->Get("direction", &v8_direction);
int direction;
if (!gin::ConvertFromV8(isolate, v8_direction, &direction)) {
return;
}
ax_node_data->AddIntAttribute(ax::mojom::IntAttribute::kTextDirection,
direction);
}
void SetAXNodeDataTextStyle(v8::Isolate* isolate,
gin::Dictionary* v8_dict,
ui::AXNodeData* ax_node_data) {
v8::Local<v8::Value> v8_text_style;
v8_dict->Get("textStyle", &v8_text_style);
std::string text_style;
if (!gin::ConvertFromV8(isolate, v8_text_style, &text_style)) {
return;
}
if (text_style.find("underline") != std::string::npos) {
ax_node_data->AddTextStyle(ax::mojom::TextStyle::kUnderline);
}
if (text_style.find("overline") != std::string::npos) {
ax_node_data->AddTextStyle(ax::mojom::TextStyle::kOverline);
}
if (text_style.find("italic") != std::string::npos) {
ax_node_data->AddTextStyle(ax::mojom::TextStyle::kItalic);
}
if (text_style.find("bold") != std::string::npos) {
ax_node_data->AddTextStyle(ax::mojom::TextStyle::kBold);
}
}
void SetAXNodeDataUrl(v8::Isolate* isolate,
gin::Dictionary* v8_dict,
ui::AXNodeData* ax_node_data) {
v8::Local<v8::Value> v8_url;
v8_dict->Get("url", &v8_url);
std::string url;
if (!gin::ConvertFromV8(isolate, v8_url, &url)) {
return;
}
ax_node_data->AddStringAttribute(ax::mojom::StringAttribute::kUrl, url);
}
void SetSelectionAnchorObjectId(v8::Isolate* isolate,
gin::Dictionary* v8_dict,
ui::AXTreeData* ax_tree_data) {
v8::Local<v8::Value> v8_anchor_object_id;
v8_dict->Get("anchor_object_id", &v8_anchor_object_id);
ui::AXNodeID sel_anchor_object_id;
if (!gin::ConvertFromV8(isolate, v8_anchor_object_id,
&sel_anchor_object_id)) {
return;
}
ax_tree_data->sel_anchor_object_id = sel_anchor_object_id;
}
void SetSelectionFocusObjectId(v8::Isolate* isolate,
gin::Dictionary* v8_dict,
ui::AXTreeData* ax_tree_data) {
v8::Local<v8::Value> v8_focus_object_id;
v8_dict->Get("focus_object_id", &v8_focus_object_id);
ui::AXNodeID sel_focus_object_id;
if (!gin::ConvertFromV8(isolate, v8_focus_object_id, &sel_focus_object_id)) {
return;
}
ax_tree_data->sel_focus_object_id = sel_focus_object_id;
}
void SetSelectionAnchorOffset(v8::Isolate* isolate,
gin::Dictionary* v8_dict,
ui::AXTreeData* ax_tree_data) {
v8::Local<v8::Value> v8_anchor_offset;
v8_dict->Get("anchor_offset", &v8_anchor_offset);
int32_t sel_anchor_offset;
if (!gin::ConvertFromV8(isolate, v8_anchor_offset, &sel_anchor_offset)) {
return;
}
ax_tree_data->sel_anchor_offset = sel_anchor_offset;
}
void SetSelectionFocusOffset(v8::Isolate* isolate,
gin::Dictionary* v8_dict,
ui::AXTreeData* ax_tree_data) {
v8::Local<v8::Value> v8_focus_offset;
v8_dict->Get("focus_offset", &v8_focus_offset);
int32_t sel_focus_offset;
if (!gin::ConvertFromV8(isolate, v8_focus_offset, &sel_focus_offset)) {
return;
}
ax_tree_data->sel_focus_offset = sel_focus_offset;
}
void SetSelectionIsBackward(v8::Isolate* isolate,
gin::Dictionary* v8_dict,
ui::AXTreeData* ax_tree_data) {
v8::Local<v8::Value> v8_sel_is_backward;
v8_dict->Get("is_backward", &v8_sel_is_backward);
bool sel_is_backward;
if (!gin::ConvertFromV8(isolate, v8_sel_is_backward, &sel_is_backward)) {
return;
}
ax_tree_data->sel_is_backward = sel_is_backward;
}
void SetAXTreeUpdateRootId(v8::Isolate* isolate,
gin::Dictionary* v8_dict,
ui::AXTreeUpdate* snapshot) {
v8::Local<v8::Value> v8_root_id;
v8_dict->Get("rootId", &v8_root_id);
ui::AXNodeID root_id;
if (!gin::ConvertFromV8(isolate, v8_root_id, &root_id)) {
return;
}
snapshot->root_id = root_id;
}
ui::AXTreeUpdate GetSnapshotFromV8SnapshotLite(
v8::Isolate* isolate,
v8::Local<v8::Value> v8_snapshot_lite) {
ui::AXTreeUpdate snapshot;
ui::AXTreeData ax_tree_data;
ax_tree_data.tree_id = ui::AXTreeID::CreateNewAXTreeID();
snapshot.has_tree_data = true;
snapshot.tree_data = ax_tree_data;
gin::Dictionary v8_snapshot_dict(isolate);
if (!gin::ConvertFromV8(isolate, v8_snapshot_lite, &v8_snapshot_dict)) {
return snapshot;
}
SetAXTreeUpdateRootId(isolate, &v8_snapshot_dict, &snapshot);
v8::Local<v8::Value> v8_nodes;
v8_snapshot_dict.Get("nodes", &v8_nodes);
v8::LocalVector<v8::Value> v8_nodes_vector(isolate);
if (!gin::ConvertFromV8(isolate, v8_nodes, &v8_nodes_vector)) {
return snapshot;
}
for (v8::Local<v8::Value> v8_node : v8_nodes_vector) {
gin::Dictionary v8_node_dict(isolate);
if (!gin::ConvertFromV8(isolate, v8_node, &v8_node_dict)) {
continue;
}
ui::AXNodeData ax_node_data;
SetAXNodeDataId(isolate, &v8_node_dict, &ax_node_data);
SetAXNodeDataRole(isolate, &v8_node_dict, &ax_node_data);
SetAXNodeDataName(isolate, &v8_node_dict, &ax_node_data);
SetAXNodeDataChildIds(isolate, &v8_node_dict, &ax_node_data);
SetAXNodeDataHtmlTag(isolate, &v8_node_dict, &ax_node_data);
SetAXNodeDataLanguage(isolate, &v8_node_dict, &ax_node_data);
SetAXNodeDataTextDirection(isolate, &v8_node_dict, &ax_node_data);
SetAXNodeDataTextStyle(isolate, &v8_node_dict, &ax_node_data);
SetAXNodeDataUrl(isolate, &v8_node_dict, &ax_node_data);
SetAXNodeDataDisplay(isolate, &v8_node_dict, &ax_node_data);
snapshot.nodes.push_back(ax_node_data);
}
v8::Local<v8::Value> v8_selection;
v8_snapshot_dict.Get("selection", &v8_selection);
gin::Dictionary v8_selection_dict(isolate);
if (!gin::ConvertFromV8(isolate, v8_selection, &v8_selection_dict)) {
return snapshot;
}
SetSelectionAnchorObjectId(isolate, &v8_selection_dict, &snapshot.tree_data);
SetSelectionFocusObjectId(isolate, &v8_selection_dict, &snapshot.tree_data);
SetSelectionAnchorOffset(isolate, &v8_selection_dict, &snapshot.tree_data);
SetSelectionFocusOffset(isolate, &v8_selection_dict, &snapshot.tree_data);
SetSelectionIsBackward(isolate, &v8_selection_dict, &snapshot.tree_data);
return snapshot;
}
SkBitmap CorrectColorOfBitMap(SkBitmap& originalBitmap) {
SkBitmap converted;
converted.allocPixels(SkImageInfo::Make(
originalBitmap.width(), originalBitmap.height(),
SkColorType::kRGBA_8888_SkColorType, originalBitmap.alphaType()));
originalBitmap.readPixels(converted.info(), converted.getPixels(),
converted.rowBytes(), 0, 0);
return converted;
}
template <typename T>
requires(std::is_enum_v<T> &&
requires {
T::kMinValue;
T::kMaxValue;
})
std::optional<T> ToEnum(int value) {
if (value >= base::to_underlying(T::kMinValue) &&
value <= base::to_underlying(T::kMaxValue)) {
return static_cast<T>(value);
}
return std::nullopt;
}
} // namespace
// static
gin::WrapperInfo ReadAnythingAppController::kWrapperInfo = {
gin::kEmbedderNativeGin};
// static
ReadAnythingAppController* ReadAnythingAppController::Install(
content::RenderFrame* render_frame) {
v8::Isolate* isolate =
render_frame->GetWebFrame()->GetAgentGroupScheduler()->Isolate();
v8::HandleScope handle_scope(isolate);
v8::Local<v8::Context> context =
render_frame->GetWebFrame()->MainWorldScriptContext();
if (context.IsEmpty()) {
return nullptr;
}
v8::MicrotasksScope microtask_scope(isolate, context->GetMicrotaskQueue(),
v8::MicrotasksScope::kDoNotRunMicrotasks);
v8::Context::Scope context_scope(context);
ReadAnythingAppController* controller =
new ReadAnythingAppController(render_frame);
gin::Handle<ReadAnythingAppController> handle =
gin::CreateHandle(isolate, controller);
if (handle.IsEmpty()) {
return nullptr;
}
v8::Local<v8::Object> chrome =
content::GetOrCreateChromeObject(isolate, context);
chrome->Set(context, gin::StringToV8(isolate, "readingMode"), handle.ToV8())
.Check();
return controller;
}
ReadAnythingAppController::ReadAnythingAppController(
content::RenderFrame* render_frame)
: content::RenderFrameObserver(render_frame) {
post_user_entry_draw_timer_ = std::make_unique<base::RetainingOneShotTimer>(
FROM_HERE, base::Seconds(kPostInputDistillSeconds),
base::BindRepeating(&ReadAnythingAppController::Draw,
weak_ptr_factory_.GetWeakPtr(),
/* recompute_display_nodes= */ true));
renderer_load_triggered_time_ms_ = base::TimeTicks::Now();
distiller_ = std::make_unique<AXTreeDistiller>(
render_frame,
base::BindRepeating(&ReadAnythingAppController::OnAXTreeDistilled,
weak_ptr_factory_.GetWeakPtr()));
// TODO(crbug.com/40915547): Use a global ukm recorder instance instead.
mojo::Remote<ukm::mojom::UkmRecorderFactory> factory;
content::RenderThread::Get()->BindHostReceiver(
factory.BindNewPipeAndPassReceiver());
ukm_recorder_ = ukm::MojoUkmRecorder::Create(*factory);
if (features::IsDataCollectionModeForScreen2xEnabled()) {
model_.SetDataCollectionForScreen2xCallback(
base::BindOnce(&ReadAnythingAppController::DistillAndScreenshot,
weak_ptr_factory_.GetWeakPtr()));
}
model_observer_.Observe(&model_);
}
ReadAnythingAppController::~ReadAnythingAppController() {
RecordNumSelections();
post_user_entry_draw_timer_->Stop();
}
void ReadAnythingAppController::OnDestruct() {
delete this;
}
void ReadAnythingAppController::OnNodeDataChanged(
ui::AXTree* tree,
const ui::AXNodeData& old_node_data,
const ui::AXNodeData& new_node_data) {
if (!IsReadAloudEnabled() && tree->GetAXTreeID() == model_.active_tree_id()) {
if (old_node_data.HasState(ax::mojom::State::kExpanded) !=
new_node_data.HasState(ax::mojom::State::kExpanded) ||
old_node_data.HasState(ax::mojom::State::kCollapsed) !=
new_node_data.HasState(ax::mojom::State::kCollapsed)) {
model_.set_last_expanded_node_id(new_node_data.id);
}
}
}
void ReadAnythingAppController::OnNodeWillBeDeleted(ui::AXTree* tree,
ui::AXNode* node) {
ui::AXNodeID node_id = CHECK_DEREF(node).id();
if (model_.display_node_ids().contains(node_id)) {
displayed_nodes_pending_deletion_.insert(node_id);
if (IsReadAloudEnabled() && !read_aloud_model_.speech_playing()) {
ExecuteJavaScript("chrome.readingMode.onNodeWillBeDeleted(" +
base::ToString(node_id) + ")");
}
}
}
void ReadAnythingAppController::OnNodeDeleted(ui::AXTree* tree,
ui::AXNodeID node_id) {
if (displayed_nodes_pending_deletion_.contains(node_id)) {
displayed_nodes_pending_deletion_.erase(node_id);
// Instead of redrawing everything, we inform the webui that the node is
// being deleted and it will adjust on that side. See OnNodeWillBeDeleted.
if (IsReadAloudEnabled()) {
return;
}
// For Google Docs, we extract text from the "annotated canvas" element
// nodes, which hold the currently visible text on screen. As the user
// scrolls, these canvas elements are dynamically updated, resulting in
// frequent calls to OnNodeDeleted. We found that redrawing content in the
// Reading Model panel after node deletion during scrolling can lead to
// unexpected behavior (e.g., an empty side panel). Therefore, Google Docs
// require special handling to ensure correct text extraction and avoid
// these issues.
if (displayed_nodes_pending_deletion_.empty() && !IsGoogleDocs()) {
Draw(false);
if (model_.has_selection()) {
DrawSelection();
}
}
}
}
void ReadAnythingAppController::AccessibilityEventReceived(
const ui::AXTreeID& tree_id,
const std::vector<ui::AXTreeUpdate>& updates,
const std::vector<ui::AXEvent>& events) {
// Remove the const-ness of the data here so that subsequent methods can move
// the data.
model_.AccessibilityEventReceived(
tree_id, const_cast<std::vector<ui::AXTreeUpdate>&>(updates),
const_cast<std::vector<ui::AXEvent>&>(events),
read_aloud_model_.speech_playing());
// From this point onward, `updates` and `events` should not be accessed.
if (tree_id != model_.active_tree_id() ||
read_aloud_model_.speech_playing()) {
return;
}
SendEventUpdates();
}
void ReadAnythingAppController::SendEventUpdates() {
if (model_.requires_distillation()) {
Distill();
}
if (model_.redraw_required()) {
model_.reset_redraw_required();
Draw(/* recompute_display_nodes= */ true);
}
// TODO(accessibility): it isn't clear this handles the pending updates path
// correctly within the model.
if (model_.requires_post_process_selection()) {
PostProcessSelection();
}
// If the user typed something, this value will be true and it will reset the
// timer to distill.
if (model_.reset_draw_timer()) {
post_user_entry_draw_timer_->Reset();
model_.set_reset_draw_timer(false);
}
}
void ReadAnythingAppController::AccessibilityLocationChangesReceived(
const ui::AXTreeID& tree_id,
const ui::AXLocationAndScrollUpdates& details) {
NOTREACHED() << "Non-const ref version of this method should be used as a "
"performance optimization.";
}
void ReadAnythingAppController::AccessibilityLocationChangesReceived(
const ui::AXTreeID& tree_id,
ui::AXLocationAndScrollUpdates& details) {
// AccessibilityLocationChangesReceived causes some unexpected crashes and
// AXNode behavior. Therefore, flag-guard this behind the
// IsReadAnythingDocsIntegration flag, since these changes were initially
// added to support Google Docs. See crbug.com/411776559.
if (!features::IsReadAnythingDocsIntegrationEnabled()) {
return;
}
// If the AccessibilityLocationChangesReceived callback happens after
// the current active tree has been destroyed, do nothing.
DUMP_WILL_BE_CHECK(model_.active_tree_id() != ui::AXTreeIDUnknown());
DUMP_WILL_BE_CHECK(model_.ContainsTree(tree_id));
// TODO: crbug.com/411776559- Determine if a DUMP_WILL_BE_CHECK is needed
// here or if it's okay to just ignore AccessibilityLocationChangesReceived
// events if they're sent not on the active tree.
DUMP_WILL_BE_CHECK(model_.active_tree_id() == tree_id);
if (model_.active_tree_id() == ui::AXTreeIDUnknown() ||
!model_.ContainsTree(tree_id) || model_.active_tree_id() != tree_id) {
return;
}
// Listen to location change notifications to update locations of the nodes
// accordingly.
for (auto& change : details.location_changes) {
ui::AXNode* ax_node = model_.GetAXNode(change.id);
if (!ax_node) {
continue;
}
ax_node->SetLocation(change.new_location.offset_container_id,
change.new_location.bounds,
change.new_location.transform.get());
}
}
void ReadAnythingAppController::ExecuteJavaScript(const std::string& script) {
// TODO(crbug.com/40802192): Use v8::Function rather than javascript. If
// possible, replace this function call with firing an event.
render_frame()->ExecuteJavaScript(base::ASCIIToUTF16(script));
}
void ReadAnythingAppController::OnActiveAXTreeIDChanged(
const ui::AXTreeID& tree_id,
ukm::SourceId ukm_source_id,
bool is_pdf) {
if (tree_id == model_.active_tree_id() && !is_pdf) {
return;
}
RecordNumSelections();
// Cancel any running draw timers.
post_user_entry_draw_timer_->Stop();
model_.SetRootTreeId(tree_id);
model_.SetUkmSourceIdForTree(tree_id, ukm_source_id);
model_.set_is_pdf(is_pdf);
if (IsReadAloudEnabled() && read_aloud_model_.speech_playing()) {
model_.SetUrlInformationCallback(
base::BindOnce(&ReadAnythingAppController::OnUrlInformationSet,
weak_ptr_factory_.GetWeakPtr()));
}
// Delete all pending updates on the formerly active AXTree.
// TODO(crbug.com/40802192): If distillation is in progress, cancel the
// distillation request.
model_.ClearPendingUpdates();
model_.set_requires_distillation(false);
model_.set_page_finished_loading(false);
ExecuteJavaScript("chrome.readingMode.showLoading();");
// When the UI first constructs, this function may be called before tree_id
// has been added to the tree list in AccessibilityEventReceived. In that
// case, do not distill.
if (model_.active_tree_id() != ui::AXTreeIDUnknown() &&
model_.ContainsActiveTree()) {
Distill();
}
}
void ReadAnythingAppController::RecordNumSelections() {
ukm::builders::Accessibility_ReadAnything_EmptyState(model_.GetUkmSourceId())
.SetTotalNumSelections(model_.GetNumSelections())
.Record(ukm_recorder_.get());
model_.SetNumSelections(0);
}
void ReadAnythingAppController::OnAXTreeDestroyed(const ui::AXTreeID& tree_id) {
// Cancel any running draw timers.
post_user_entry_draw_timer_->Stop();
model_.OnAXTreeDestroyed(tree_id);
}
void ReadAnythingAppController::DistillAndScreenshot() {
// For screen2x data generation mode, chrome is opened from the CLI to a
// specific URL. The caller monitors for a dump of the distilled proto written
// to a local file. Distill should only be called once the page finished
// loading and is stable, so the proto represents the entire webpage.
CHECK(features::IsDataCollectionModeForScreen2xEnabled());
CHECK(model_.PageFinishedLoadingForDataCollection());
CHECK(model_.ScreenAIServiceReadyForDataCollection());
Distill(/*for_training_data=*/true);
page_handler_->OnScreenshotRequested();
}
void ReadAnythingAppController::Distill(bool for_training_data) {
if (!for_training_data &&
features::IsDataCollectionModeForScreen2xEnabled()) {
return;
}
if (model_.distillation_in_progress() || read_aloud_model_.speech_playing()) {
// When distillation is in progress, the model may have queued up tree
// updates. In those cases, assume we eventually get to `OnAXTreeDistilled`,
// where we re-request `Distill`. When speech is playing, assume it will
// eventually stop and call `OnIsSpeechActiveChanged` where we
// re-request `Distill`.
model_.set_requires_distillation(true);
return;
}
model_.set_requires_distillation(false);
ui::AXSerializableTree* tree = model_.GetActiveTree();
std::unique_ptr<
ui::AXTreeSource<const ui::AXNode*, ui::AXTreeData*, ui::AXNodeData>>
tree_source(tree->CreateTreeSource());
ui::AXTreeSerializer<const ui::AXNode*, std::vector<const ui::AXNode*>,
ui::AXTreeUpdate*, ui::AXTreeData*, ui::AXNodeData>
serializer(tree_source.get());
ui::AXTreeUpdate snapshot;
if (!tree->root()) {
return;
}
if (model_.requires_tree_lang()) {
model_.set_requires_tree_lang(false);
std::string tree_lang = tree->root()->GetLanguage();
SetLanguageCode(tree_lang.empty()
? read_aloud_model_.default_language_code()
: tree_lang);
}
CHECK(serializer.SerializeChanges(tree->root(), &snapshot));
model_.set_distillation_in_progress(true);
distiller_->Distill(*tree, snapshot, model_.GetUkmSourceId());
}
void ReadAnythingAppController::OnAXTreeDistilled(
const ui::AXTreeID& tree_id,
const std::vector<ui::AXNodeID>& content_node_ids) {
// The distiller will call OnAXTreeDistilled when the main content extractor
// disconnects. If this happens during middle of a distillation, there was an
// error, and we should reset the model. However, this disconnect can also
// happen after a long time of inactivity. In this case, we shouldn't reset
// the model since the last state is still the correct state and clearing the
// model causes issues for read aloud.
if (IsReadAloudEnabled() && !model_.distillation_in_progress() &&
tree_id == ui::AXTreeIDUnknown() && content_node_ids.empty()) {
return;
}
// If speech is playing, we don't want to redraw and disrupt speech. We will
// re-distill once speech pauses.
if (read_aloud_model_.speech_playing()) {
model_.set_requires_distillation(true);
model_.set_distillation_in_progress(false);
return;
}
// Reset state, including the current side panel selection so we can update
// it based on the new main panel selection in PostProcessSelection below.ona
model_.Reset(content_node_ids);
read_aloud_model_.ResetReadAloudState();
// Return early if any of the following scenarios occurred while waiting for
// distillation to complete:
// 1. tree_id != model_.active_tree_id(): The active tree was changed.
// 2. model_.active_tree_id()== ui::AXTreeIDUnknown(): The active tree was
// change to
// an unknown tree id.
// 3. !model_.ContainsTree(tree_id): The distilled tree was destroyed.
// 4. tree_id == ui::AXTreeIDUnknown(): The distiller sent back an unknown
// tree id which occurs when there was an error.
if (tree_id != model_.active_tree_id() ||
model_.active_tree_id() == ui::AXTreeIDUnknown() ||
!model_.ContainsTree(tree_id) || tree_id == ui::AXTreeIDUnknown()) {
return;
}
if (!model_.content_node_ids().empty()) {
// If there are content_node_ids, this means the AXTree was successfully
// distilled. We must call this before PostProcessSelection() below because
// that call checks if the current selection is inside the currently
// displayed nodes. Thus, we have to calculate the display nodes first.
model_.ComputeDisplayNodeIdsForDistilledTree();
}
// If there's no distillable content on the active tree, allow child tree
// content to be distilled. This is needed to distill content on pages with
// a single root node containing an iframe that contains a tree with all
// the page's content.
model_.AllowChildTreeForActiveTree(model_.content_node_ids().empty());
// Draw the selection in the side panel (if one exists in the main panel).
if (!PostProcessSelection()) {
// If a draw did not occur, make sure to draw. This will happen if there is
// no main content selection when the tree is distilled. Sometimes in Gmail,
// The above call to ComputeDisplayNodeIdsForDistilledTree still produces
// an empty display node list. If that happens and there are content nodes,
// we should recompute the display nodes again.
bool should_recompute_display_nodes =
!model_.content_node_ids().empty() && model_.display_node_ids().empty();
Draw(should_recompute_display_nodes);
}
if (model_.is_empty()) {
// For Google Docs, the initial AXTree may be empty while the document is
// loading. Therefore, to avoid displaying an empty side panel, wait for
// Google Docs to finish loading.
if (!IsGoogleDocs() || model_.page_finished_loading()) {
DrawEmptyState();
}
}
// AXNode's language code is BCP 47. Only the base language is needed to
// record the metric.
std::string language = model_.GetActiveTree()->root()->GetLanguage();
if (!language.empty()) {
base::UmaHistogramSparse(
"Accessibility.ReadAnything.Language",
base::HashMetricName(language::ExtractBaseLanguage(language)));
}
// Once drawing is complete, unserialize all of the pending updates on the
// active tree which may require more distillations (as tracked by the model's
// `requires_distillation()` state below).
model_.UnserializePendingUpdates(tree_id);
if (model_.requires_distillation()) {
Distill();
}
}
bool ReadAnythingAppController::PostProcessSelection() {
// It's possible for the active tree to be destroyed in-between when
// OnAXTreeDistilled returns early if the model doesn't contain the active
// tree and when PostProcessSelection is called after
// ComputeDisplayNodeIdsForDistilledTree is called. This seems to happen
// when it takes a long time to compute the display nodes. If this happens,
// return false rather than trying to continue to process information on a
// destroyed tree.
DUMP_WILL_BE_CHECK(model_.ContainsActiveTree());
if (!model_.ContainsActiveTree()) {
return false;
}
bool did_draw = false;
// Note post `model_.PostProcessSelection` returns true if a draw is required.
if (model_.PostProcessSelection()) {
did_draw = true;
if (model_.is_empty()) {
DrawEmptyState();
} else {
// TODO(b/40927698): When Read Aloud is playing and content is selected
// in the main panel, don't re-draw with the updated selection until
// Read Aloud is paused.
bool should_recompute_display_nodes = !model_.content_node_ids().empty();
Draw(should_recompute_display_nodes);
}
}
// Skip drawing the selection in the side panel if the selection originally
// came from there.
if (model_.unprocessed_selections_from_reading_mode() == 0) {
DrawSelection();
} else {
model_.decrement_selections_from_reading_mode();
}
return did_draw;
}
void ReadAnythingAppController::Draw(bool recompute_display_nodes) {
// For Google Docs, do not show any text before the doc finishing loading.
if (IsGoogleDocs() && !model_.page_finished_loading()) {
return;
}
if (recompute_display_nodes && !model_.content_node_ids().empty()) {
model_.ComputeDisplayNodeIdsForDistilledTree();
// If we need to recompute which nodes are displayed, reset read aloud as
// we previously preprocessed the previous nodes and should re-process the
// new ones.
if (IsReadAloudEnabled()) {
read_aloud_model_.ResetReadAloudState();
}
}
// This call should check that the active tree isn't in an undistilled state
// -- that is, it is awaiting distillation or never requested distillation.
ExecuteJavaScript("chrome.readingMode.updateContent();");
}
void ReadAnythingAppController::DrawSelection() {
// This call should check that the active tree isn't in an undistilled state
// -- that is, it is awaiting distillation or never requested distillation.
ExecuteJavaScript("chrome.readingMode.updateSelection();");
}
void ReadAnythingAppController::DrawEmptyState() {
ExecuteJavaScript("chrome.readingMode.showEmpty();");
base::UmaHistogramEnumeration(ReadAnythingAppModel::kEmptyStateHistogramName,
ReadAnythingAppModel::EmptyState::kShown);
}
void ReadAnythingAppController::OnSettingsRestoredFromPrefs(
read_anything::mojom::LineSpacing line_spacing,
read_anything::mojom::LetterSpacing letter_spacing,
const std::string& font,
double font_size,
bool links_enabled,
bool images_enabled,
read_anything::mojom::Colors color,
double speech_rate,
base::Value::Dict voices,
base::Value::List languages_enabled_in_pref,
read_anything::mojom::HighlightGranularity granularity) {
read_aloud_model_.OnSettingsRestoredFromPrefs(
speech_rate, &languages_enabled_in_pref, &voices, granularity);
bool needs_redraw_for_links = model_.links_enabled() != links_enabled;
model_.OnSettingsRestoredFromPrefs(line_spacing, letter_spacing, font,
font_size, links_enabled, images_enabled,
color);
ExecuteJavaScript("chrome.readingMode.restoreSettingsFromPrefs();");
// Only redraw if there is an active tree.
if (needs_redraw_for_links &&
model_.active_tree_id() != ui::AXTreeIDUnknown()) {
ExecuteJavaScript("chrome.readingMode.updateLinks();");
}
}
void ReadAnythingAppController::ScreenAIServiceReady() {
if (features::IsDataCollectionModeForScreen2xEnabled()) {
model_.SetScreenAIServiceReadyForDataCollection();
}
distiller_->ScreenAIServiceReady();
}
gin::ObjectTemplateBuilder ReadAnythingAppController::GetObjectTemplateBuilder(
v8::Isolate* isolate) {
return gin::Wrappable<ReadAnythingAppController>::GetObjectTemplateBuilder(
isolate)
.SetProperty("rootId", &ReadAnythingAppController::RootId)
.SetProperty("startNodeId", &ReadAnythingAppController::StartNodeId)
.SetProperty("startOffset", &ReadAnythingAppController::StartOffset)
.SetProperty("endNodeId", &ReadAnythingAppController::EndNodeId)
.SetProperty("endOffset", &ReadAnythingAppController::EndOffset)
.SetProperty("fontName", &ReadAnythingAppController::FontName)
.SetProperty("fontSize", &ReadAnythingAppController::FontSize)
.SetProperty("linksEnabled", &ReadAnythingAppController::LinksEnabled)
.SetProperty("imagesEnabled", &ReadAnythingAppController::ImagesEnabled)
.SetProperty("imagesFeatureEnabled",
&ReadAnythingAppController::ImagesFeatureEnabled)
.SetProperty("letterSpacing", &ReadAnythingAppController::LetterSpacing)
.SetProperty("lineSpacing", &ReadAnythingAppController::LineSpacing)
.SetProperty("standardLineSpacing",
&ReadAnythingAppController::StandardLineSpacing)
.SetProperty("looseLineSpacing",
&ReadAnythingAppController::LooseLineSpacing)
.SetProperty("veryLooseLineSpacing",
&ReadAnythingAppController::VeryLooseLineSpacing)
.SetProperty("standardLetterSpacing",
&ReadAnythingAppController::StandardLetterSpacing)
.SetProperty("wideLetterSpacing",
&ReadAnythingAppController::WideLetterSpacing)
.SetProperty("veryWideLetterSpacing",
&ReadAnythingAppController::VeryWideLetterSpacing)
.SetProperty("colorTheme", &ReadAnythingAppController::ColorTheme)
.SetProperty("highlightGranularity",
&ReadAnythingAppController::HighlightGranularity)
.SetProperty("defaultTheme", &ReadAnythingAppController::DefaultTheme)
.SetProperty("lightTheme", &ReadAnythingAppController::LightTheme)
.SetProperty("darkTheme", &ReadAnythingAppController::DarkTheme)
.SetProperty("yellowTheme", &ReadAnythingAppController::YellowTheme)
.SetProperty("blueTheme", &ReadAnythingAppController::BlueTheme)
.SetProperty("autoHighlighting",
&ReadAnythingAppController::AutoHighlighting)
.SetProperty("wordHighlighting",
&ReadAnythingAppController::WordHighlighting)
.SetProperty("phraseHighlighting",
&ReadAnythingAppController::PhraseHighlighting)
.SetProperty("sentenceHighlighting",
&ReadAnythingAppController::SentenceHighlighting)
.SetProperty("noHighlighting", &ReadAnythingAppController::NoHighlighting)
.SetProperty("pauseButtonStopSource",
&ReadAnythingAppController::PauseButtonStopSource)
.SetProperty("keyboardShortcutStopSource",
&ReadAnythingAppController::KeyboardShortcutStopSource)
.SetProperty("engineInterruptStopSource",
&ReadAnythingAppController::EngineInterruptStopSource)
.SetProperty("engineErrorStopSource",
&ReadAnythingAppController::EngineErrorStopSource)
.SetProperty("contentFinishedStopSource",
&ReadAnythingAppController::ContentFinishedStopSource)
.SetProperty("isSpeechTreeInitialized",
&ReadAnythingAppController::IsSpeechTreeInitialized)
.SetProperty(
"unexpectedUpdateContentStopSource",
&ReadAnythingAppController::UnexpectedUpdateContentStopSource)
.SetProperty("speechRate", &ReadAnythingAppController::SpeechRate)
.SetProperty("isGoogleDocs", &ReadAnythingAppController::IsGoogleDocs)
.SetProperty("isReadAloudEnabled",
&ReadAnythingAppController::IsReadAloudEnabled)
.SetProperty("isChromeOsAsh", &ReadAnythingAppController::IsChromeOsAsh)
.SetProperty("baseLanguageForSpeech",
&ReadAnythingAppController::GetLanguageCodeForSpeech)
.SetProperty("requiresDistillation",
&ReadAnythingAppController::RequiresDistillation)
.SetProperty("defaultLanguageForSpeech",
&ReadAnythingAppController::GetDefaultLanguageCodeForSpeech)
.SetProperty("isPhraseHighlightingEnabled",
&ReadAnythingAppController::IsPhraseHighlightingEnabled)
.SetMethod("isHighlightOn", &ReadAnythingAppController::IsHighlightOn)
.SetMethod("getChildren", &ReadAnythingAppController::GetChildren)
.SetMethod("getTextDirection",
&ReadAnythingAppController::GetTextDirection)
.SetMethod("getHtmlTag", &ReadAnythingAppController::GetHtmlTag)
.SetMethod("getLanguage", &ReadAnythingAppController::GetLanguage)
.SetMethod("getTextContent", &ReadAnythingAppController::GetTextContent)
.SetMethod("getUrl", &ReadAnythingAppController::GetUrl)
.SetMethod("getAltText", &ReadAnythingAppController::GetAltText)
.SetMethod("shouldBold", &ReadAnythingAppController::ShouldBold)
.SetMethod("isOverline", &ReadAnythingAppController::IsOverline)
.SetMethod("isLeafNode", &ReadAnythingAppController::IsLeafNode)
.SetMethod("onConnected", &ReadAnythingAppController::OnConnected)
.SetMethod("onCopy", &ReadAnythingAppController::OnCopy)
.SetMethod("onNoTextContent", &ReadAnythingAppController::OnNoTextContent)
.SetMethod("onFontSizeChanged",
&ReadAnythingAppController::OnFontSizeChanged)
.SetMethod("onFontSizeReset", &ReadAnythingAppController::OnFontSizeReset)
.SetMethod("onLinksEnabledToggled",
&ReadAnythingAppController::OnLinksEnabledToggled)
.SetMethod("onImagesEnabledToggled",
&ReadAnythingAppController::OnImagesEnabledToggled)
.SetMethod("onScroll", &ReadAnythingAppController::OnScroll)
.SetMethod("onLinkClicked", &ReadAnythingAppController::OnLinkClicked)
.SetMethod("onLetterSpacingChange",
&ReadAnythingAppController::OnLetterSpacingChange)
.SetMethod("onLineSpacingChange",
&ReadAnythingAppController::OnLineSpacingChange)
.SetMethod("onThemeChange", &ReadAnythingAppController::OnThemeChange)
.SetMethod("onFontChange", &ReadAnythingAppController::OnFontChange)
.SetMethod("onSpeechRateChange",
&ReadAnythingAppController::OnSpeechRateChange)
.SetMethod("getStoredVoice", &ReadAnythingAppController::GetStoredVoice)
.SetMethod("onVoiceChange", &ReadAnythingAppController::OnVoiceChange)
.SetMethod("onLanguagePrefChange",
&ReadAnythingAppController::OnLanguagePrefChange)
.SetMethod("getLanguagesEnabledInPref",
&ReadAnythingAppController::GetLanguagesEnabledInPref)
.SetMethod("onHighlightGranularityChanged",
&ReadAnythingAppController::OnHighlightGranularityChanged)
.SetMethod("getLineSpacingValue",
&ReadAnythingAppController::GetLineSpacingValue)
.SetMethod("getLetterSpacingValue",
&ReadAnythingAppController::GetLetterSpacingValue)
.SetMethod("onSelectionChange",
&ReadAnythingAppController::OnSelectionChange)
.SetMethod("onCollapseSelection",
&ReadAnythingAppController::OnCollapseSelection)
.SetProperty("supportedFonts",
&ReadAnythingAppController::GetSupportedFonts)
.SetProperty("allFonts", &ReadAnythingAppController::GetAllFonts)
.SetMethod("setContentForTesting",
&ReadAnythingAppController::SetContentForTesting)
.SetMethod("setLanguageForTesting",
&ReadAnythingAppController::SetLanguageForTesting)
.SetMethod("initAxPositionWithNode",
&ReadAnythingAppController::InitAXPositionWithNode)
.SetMethod("resetGranularityIndex",
&ReadAnythingAppController::ResetGranularityIndex)
.SetMethod("getCurrentTextStartIndex",
&ReadAnythingAppController::GetCurrentTextStartIndex)
.SetMethod("getCurrentTextEndIndex",
&ReadAnythingAppController::GetCurrentTextEndIndex)
.SetMethod("getCurrentText", &ReadAnythingAppController::GetCurrentText)
.SetMethod("shouldShowUi", &ReadAnythingAppController::ShouldShowUI)
.SetMethod("onIsSpeechActiveChanged",
&ReadAnythingAppController::OnIsSpeechActiveChanged)
.SetMethod("onIsAudioCurrentlyPlayingChanged",
&ReadAnythingAppController::OnIsAudioCurrentlyPlayingChanged)
.SetMethod("getAccessibleBoundary",
&ReadAnythingAppController::GetAccessibleBoundary)
.SetMethod("movePositionToNextGranularity",
&ReadAnythingAppController::MovePositionToNextGranularity)
.SetMethod("movePositionToPreviousGranularity",
&ReadAnythingAppController::MovePositionToPreviousGranularity)
.SetMethod("requestImageData",
&ReadAnythingAppController::RequestImageDataUrl)
.SetMethod("getImageBitmap", &ReadAnythingAppController::GetImageBitmap)
.SetMethod("getDisplayNameForLocale",
&ReadAnythingAppController::GetDisplayNameForLocale)
.SetMethod("incrementMetricCount",
&ReadAnythingAppController::IncrementMetricCount)
.SetMethod("logSpeechStop", &ReadAnythingAppController::LogSpeechStop)
.SetMethod("sendGetVoicePackInfoRequest",
&ReadAnythingAppController::SendGetVoicePackInfoRequest)
.SetMethod("sendInstallVoicePackRequest",
&ReadAnythingAppController::SendInstallVoicePackRequest)
.SetMethod("sendUninstallVoiceRequest",
&ReadAnythingAppController::SendUninstallVoiceRequest)
.SetMethod("getHighlightForCurrentSegmentIndex",
&ReadAnythingAppController::GetHighlightForCurrentSegmentIndex)
.SetMethod("getValidatedFontName",
&ReadAnythingAppController::GetValidatedFontName)
.SetMethod("onScrolledToBottom",
&ReadAnythingAppController::OnScrolledToBottom)
.SetProperty("isDocsLoadMoreButtonVisible",
&ReadAnythingAppController::IsDocsLoadMoreButtonVisible);
}
ui::AXNodeID ReadAnythingAppController::RootId() const {
ui::AXSerializableTree* tree = model_.GetActiveTree();
// Fail gracefully if RootId() is ever called with an invalid active tree.
DUMP_WILL_BE_CHECK(tree);
DUMP_WILL_BE_CHECK(tree->root());
if (!tree || !tree->root()) {
return ui::kInvalidAXNodeID;
}
return tree->root()->id();
}
ui::AXNodeID ReadAnythingAppController::StartNodeId() const {
return model_.start_node_id();
}
int ReadAnythingAppController::StartOffset() const {
return model_.start_offset();
}
ui::AXNodeID ReadAnythingAppController::EndNodeId() const {
return model_.end_node_id();
}
int ReadAnythingAppController::EndOffset() const {
return model_.end_offset();
}
std::string ReadAnythingAppController::FontName() const {
return model_.font_name();
}
float ReadAnythingAppController::FontSize() const {
return model_.font_size();
}
bool ReadAnythingAppController::LinksEnabled() const {
return model_.links_enabled();
}
bool ReadAnythingAppController::ImagesEnabled() const {
return model_.images_enabled();
}
bool ReadAnythingAppController::ImagesFeatureEnabled() const {
return features::IsReadAnythingImagesViaAlgorithmEnabled();
}
bool ReadAnythingAppController::IsPhraseHighlightingEnabled() const {
return features::IsReadAnythingReadAloudPhraseHighlightingEnabled();
}
int ReadAnythingAppController::LetterSpacing() const {
return base::to_underlying(model_.letter_spacing());
}
int ReadAnythingAppController::LineSpacing() const {
return base::to_underlying(model_.line_spacing());
}
int ReadAnythingAppController::ColorTheme() const {
return base::to_underlying(model_.color_theme());
}
double ReadAnythingAppController::SpeechRate() const {
return read_aloud_model_.speech_rate();
}
std::string ReadAnythingAppController::GetStoredVoice() const {
const std::string* const voice =
read_aloud_model_.voices().FindString(model_.base_language_code());
return voice ? *voice : std::string();
}
std::vector<std::string> ReadAnythingAppController::GetLanguagesEnabledInPref()
const {
std::vector<std::string> languages_enabled_in_pref;
for (const base::Value& value :
read_aloud_model_.languages_enabled_in_pref()) {
languages_enabled_in_pref.push_back(value.GetString());
}
return languages_enabled_in_pref;
}
int ReadAnythingAppController::HighlightGranularity() const {
return read_aloud_model_.highlight_granularity();
}
int ReadAnythingAppController::StandardLineSpacing() const {
return base::to_underlying(read_anything::mojom::LineSpacing::kStandard);
}
int ReadAnythingAppController::LooseLineSpacing() const {
return base::to_underlying(read_anything::mojom::LineSpacing::kLoose);
}
int ReadAnythingAppController::VeryLooseLineSpacing() const {
return base::to_underlying(read_anything::mojom::LineSpacing::kVeryLoose);
}
int ReadAnythingAppController::StandardLetterSpacing() const {
return base::to_underlying(read_anything::mojom::LetterSpacing::kStandard);
}
int ReadAnythingAppController::WideLetterSpacing() const {
return base::to_underlying(read_anything::mojom::LetterSpacing::kWide);
}
int ReadAnythingAppController::VeryWideLetterSpacing() const {
return base::to_underlying(read_anything::mojom::LetterSpacing::kVeryWide);
}
int ReadAnythingAppController::DefaultTheme() const {
return base::to_underlying(read_anything::mojom::Colors::kDefault);
}
int ReadAnythingAppController::LightTheme() const {
return base::to_underlying(read_anything::mojom::Colors::kLight);
}
int ReadAnythingAppController::DarkTheme() const {
return base::to_underlying(read_anything::mojom::Colors::kDark);
}
int ReadAnythingAppController::YellowTheme() const {
return base::to_underlying(read_anything::mojom::Colors::kYellow);
}
int ReadAnythingAppController::BlueTheme() const {
return base::to_underlying(read_anything::mojom::Colors::kBlue);
}
bool ReadAnythingAppController::IsHighlightOn() {
return read_aloud_model_.IsHighlightOn();
}
int ReadAnythingAppController::AutoHighlighting() const {
return static_cast<int>(read_anything::mojom::HighlightGranularity::kOn);
}
int ReadAnythingAppController::WordHighlighting() const {
return static_cast<int>(read_anything::mojom::HighlightGranularity::kWord);
}
int ReadAnythingAppController::PhraseHighlighting() const {
return static_cast<int>(read_anything::mojom::HighlightGranularity::kPhrase);
}
int ReadAnythingAppController::SentenceHighlighting() const {
return static_cast<int>(
read_anything::mojom::HighlightGranularity::kSentence);
}
int ReadAnythingAppController::NoHighlighting() const {
return static_cast<int>(read_anything::mojom::HighlightGranularity::kOff);
}
int ReadAnythingAppController::PauseButtonStopSource() const {
return base::to_underlying(ReadAloudAppModel::ReadAloudStopSource::kButton);
}
int ReadAnythingAppController::KeyboardShortcutStopSource() const {
return base::to_underlying(
ReadAloudAppModel::ReadAloudStopSource::kKeyboardShortcut);
}
int ReadAnythingAppController::EngineInterruptStopSource() const {
return base::to_underlying(
ReadAloudAppModel::ReadAloudStopSource::kEngineInterrupt);
}
int ReadAnythingAppController::EngineErrorStopSource() const {
return base::to_underlying(
ReadAloudAppModel::ReadAloudStopSource::kEngineError);
}
int ReadAnythingAppController::ContentFinishedStopSource() const {
return base::to_underlying(
ReadAloudAppModel::ReadAloudStopSource::kFinishContent);
}
int ReadAnythingAppController::UnexpectedUpdateContentStopSource() const {
return base::to_underlying(
ReadAloudAppModel::ReadAloudStopSource::kUnexpectedUpdateContent);
}
std::vector<ui::AXNodeID> ReadAnythingAppController::GetChildren(
ui::AXNodeID ax_node_id) const {
std::vector<ui::AXNodeID> child_ids;
ui::AXNode* ax_node = model_.GetAXNode(ax_node_id);
DCHECK(ax_node);
const std::set<ui::AXNodeID>* node_ids = model_.GetCurrentlyVisibleNodes();
for (auto it = ax_node->UnignoredChildrenBegin();
it != ax_node->UnignoredChildrenEnd(); ++it) {
if (base::Contains(*node_ids, it->id())) {
child_ids.push_back(it->id());
}
}
return child_ids;
}
std::string ReadAnythingAppController::GetHtmlTag(
ui::AXNodeID ax_node_id) const {
ui::AXNode* ax_node = model_.GetAXNode(ax_node_id);
DCHECK(ax_node);
return a11y::GetHtmlTag(ax_node, model_.is_pdf(), model_.IsDocs());
}
std::string ReadAnythingAppController::GetLanguage(
ui::AXNodeID ax_node_id) const {
ui::AXNode* ax_node = model_.GetAXNode(ax_node_id);
DCHECK(ax_node);
if (model_.NodeIsContentNode(ax_node_id)) {
return ax_node->GetLanguage();
}
return ax_node->GetStringAttribute(ax::mojom::StringAttribute::kLanguage);
}
std::u16string ReadAnythingAppController::GetTextContent(
ui::AXNodeID ax_node_id) const {
ui::AXNode* ax_node = model_.GetAXNode(ax_node_id);
CHECK(ax_node);
return a11y::GetTextContent(ax_node, IsGoogleDocs(), model_.is_pdf());
}
std::string ReadAnythingAppController::GetTextDirection(
ui::AXNodeID ax_node_id) const {
ui::AXNode* ax_node = model_.GetAXNode(ax_node_id);
if (!ax_node) {
return std::string();
}
auto text_direction = static_cast<ax::mojom::WritingDirection>(
ax_node->GetIntAttribute(ax::mojom::IntAttribute::kTextDirection));
// Vertical writing is displayed horizontally with "auto".
switch (text_direction) {
case ax::mojom::WritingDirection::kLtr:
return "ltr";
case ax::mojom::WritingDirection::kRtl:
return "rtl";
case ax::mojom::WritingDirection::kTtb:
return "auto";
case ax::mojom::WritingDirection::kBtt:
return "auto";
default:
return std::string();
}
}
std::string ReadAnythingAppController::GetUrl(ui::AXNodeID ax_node_id) const {
ui::AXNode* ax_node = model_.GetAXNode(ax_node_id);
DCHECK(ax_node);
const char* url =
ax_node->GetStringAttribute(ax::mojom::StringAttribute::kUrl).c_str();
// Prevent XSS from href attribute, which could be set to a script instead
// of a valid website.
if (url::FindAndCompareScheme(url, static_cast<int>(strlen(url)), "http",
nullptr) ||
url::FindAndCompareScheme(url, static_cast<int>(strlen(url)), "https",
nullptr)) {
return url;
}
return "";
}
void ReadAnythingAppController::SendGetVoicePackInfoRequest(
const std::string& language) const {
page_handler_->GetVoicePackInfo(language);
}
void ReadAnythingAppController::OnGetVoicePackInfo(
read_anything::mojom::VoicePackInfoPtr voice_pack_info) {
std::string status =
voice_pack_info->pack_state->is_installation_state()
? base::ToString(
voice_pack_info->pack_state->get_installation_state())
: base::ToString(voice_pack_info->pack_state->get_error_code());
ExecuteJavaScript("chrome.readingMode.updateVoicePackStatus(\'" +
voice_pack_info->language + "\', \'" + status + "\');");
}
void ReadAnythingAppController::SendInstallVoicePackRequest(
const std::string& language) const {
page_handler_->InstallVoicePack(language);
}
void ReadAnythingAppController::SendUninstallVoiceRequest(
const std::string& language) const {
page_handler_->UninstallVoice(language);
}
std::string ReadAnythingAppController::GetAltText(
ui::AXNodeID ax_node_id) const {
ui::AXNode* node = model_.GetAXNode(ax_node_id);
CHECK(node);
return a11y::GetAltText(node);
}
bool ReadAnythingAppController::ShouldBold(ui::AXNodeID ax_node_id) const {
ui::AXNode* ax_node = model_.GetAXNode(ax_node_id);
DCHECK(ax_node);
if (!ax_node) {
return false;
}
bool is_bold = ax_node->HasTextStyle(ax::mojom::TextStyle::kBold);
bool is_italic = ax_node->HasTextStyle(ax::mojom::TextStyle::kItalic);
bool is_underline = ax_node->HasTextStyle(ax::mojom::TextStyle::kUnderline);
return is_bold || is_italic || is_underline;
}
bool ReadAnythingAppController::IsOverline(ui::AXNodeID ax_node_id) const {
ui::AXNode* ax_node = model_.GetAXNode(ax_node_id);
DCHECK(ax_node);
if (!ax_node) {
return false;
}
return ax_node->HasTextStyle(ax::mojom::TextStyle::kOverline);
}
bool ReadAnythingAppController::IsLeafNode(ui::AXNodeID ax_node_id) const {
ui::AXNode* ax_node = model_.GetAXNode(ax_node_id);
DCHECK(ax_node);
if (!ax_node) {
return false;
}
return ax_node->IsLeaf();
}
bool ReadAnythingAppController::IsReadAloudEnabled() const {
return features::IsReadAnythingReadAloudEnabled();
}
bool ReadAnythingAppController::IsChromeOsAsh() const {
#if BUILDFLAG(IS_CHROMEOS)
return true;
#else
return false;
#endif
}
bool ReadAnythingAppController::IsGoogleDocs() const {
return model_.IsDocs();
}
std::vector<std::string> ReadAnythingAppController::GetSupportedFonts() {
return model_.supported_fonts();
}
std::string ReadAnythingAppController::GetValidatedFontName(
const std::string& font) const {
if (!base::Contains(GetAllFonts(), font)) {
return GetAllFonts().front();
}
if (font == "Serif" || font == "Sans-serif") {
return base::ToLowerASCII(font);
}
return base::Contains(font, ' ') ? base::StrCat({"\"", font, "\""}) : font;
}
std::vector<std::string> ReadAnythingAppController::GetAllFonts() const {
return ::GetSupportedFonts({});
}
void ReadAnythingAppController::RequestImageDataUrl(
ui::AXNodeID node_id) const {
if (features::IsReadAnythingImagesViaAlgorithmEnabled()) {
auto target_tree_id = model_.active_tree_id();
CHECK_NE(target_tree_id, ui::AXTreeIDUnknown());
page_handler_->OnImageDataRequested(target_tree_id, node_id);
}
}
void ReadAnythingAppController::OnImageDataDownloaded(
const ui::AXTreeID& tree_id,
ui::AXNodeID node_id,
const SkBitmap& image) {
// If the tree has changed since the request, do nothing with the downloaded
// image.
if (tree_id != model_.active_tree_id()) {
return;
}
// Temporarily store the image so that javascript can fetch it.
downloaded_images_[node_id] = image;
// Notify javascript to fetch the image.
ExecuteJavaScript("chrome.readingMode.onImageDownloaded(" +
base::ToString(node_id) + ")");
}
v8::Local<v8::Value> ReadAnythingAppController::GetImageBitmap(
ui::AXNodeID node_id) {
// Get the isolate for reading mode.
v8::Isolate* isolate =
render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate();
if (auto itr = downloaded_images_.find(node_id);
itr != downloaded_images_.end()) {
// Don't reference itr again.
SkBitmap bitmap = std::move(itr->second);
// Remove the downloaded image from the map.
downloaded_images_.erase(node_id);
// Ensure that the bitmap is in the correct color format.
if (bitmap.colorType() != SkColorType::kRGBA_8888_SkColorType) {
bitmap = CorrectColorOfBitMap(bitmap);
}
// Get the pixmap to compute the bytes.
auto pixmap = std::move(bitmap.pixmap());
auto size = pixmap.computeByteSize();
// Create an array buffer with the image bytes.
v8::Local<v8::ArrayBuffer> buffer = v8::ArrayBuffer::New(isolate, size);
// Copy the memory in.
memcpy(buffer->GetBackingStore()->Data(), pixmap.addr(), size);
// Create a clamped array so we can create an ImageData object on the
// javascript side.
v8::Local<v8::Uint8ClampedArray> array =
v8::Uint8ClampedArray::New(buffer, 0, size);
// Create an object with the image data and height, as well as a scale
// factor.
ui::AXNode* node = model_.GetAXNode(node_id);
CHECK(node);
int width = bitmap.width();
int height = bitmap.height();
float scale = (node->data().relative_bounds.bounds.width()) / width;
v8::Local<v8::Object> obj = v8::Object::New(isolate);
auto created = obj->DefineOwnProperty(
isolate->GetCurrentContext(),
v8::String::NewFromUtf8(isolate, "data").ToLocalChecked(), array);
created = obj->DefineOwnProperty(
isolate->GetCurrentContext(),
v8::String::NewFromUtf8(isolate, "width").ToLocalChecked(),
v8::Number::New(isolate, width));
created = obj->DefineOwnProperty(
isolate->GetCurrentContext(),
v8::String::NewFromUtf8(isolate, "height").ToLocalChecked(),
v8::Number::New(isolate, height));
created = obj->DefineOwnProperty(
isolate->GetCurrentContext(),
v8::String::NewFromUtf8(isolate, "scale").ToLocalChecked(),
v8::Number::New(isolate, scale));
return obj;
}
// If there wasn't an image, return undefined.
return v8::Undefined(isolate);
}
std::string ReadAnythingAppController::GetImageDataUrl(
ui::AXNodeID node_id) const {
ui::AXNode* node = model_.GetAXNode(node_id);
CHECK(node);
return a11y::GetImageDataUrl(node);
}
const std::string ReadAnythingAppController::GetDisplayNameForLocale(
const std::string& locale,
const std::string& display_locale) const {
bool found_valid_result = false;
std::string locale_result;
if (l10n_util::IsValidLocaleSyntax(locale) &&
l10n_util::IsValidLocaleSyntax(display_locale)) {
locale_result = base::UTF16ToUTF8(l10n_util::GetDisplayNameForLocale(
locale, display_locale, /*is_for_ui=*/true));
// Check for valid locales before getting the display name.
// The ICU Locale class returns "und" for undetermined locales, and
// returns the locale string directly if it has no translation.
// Treat these cases as invalid results.
found_valid_result =
locale_result != kUndeterminedLocale && locale_result != locale;
}
// Return an empty string to communicate there's no display name.
if (!found_valid_result) {
locale_result = std::string();
} else {
locale_result[0] = std::toupper(locale_result[0]);
}
return locale_result;
}
const std::string& ReadAnythingAppController::GetLanguageCodeForSpeech() const {
return model_.base_language_code();
}
bool ReadAnythingAppController::RequiresDistillation() {
return model_.requires_distillation();
}
const std::string& ReadAnythingAppController::GetDefaultLanguageCodeForSpeech()
const {
return read_aloud_model_.default_language_code();
}
void ReadAnythingAppController::OnConnected() {
// This needs to be logged here in the controller so we can base it off of the
// controller's constructor time.
base::UmaHistogramLongTimes(
"Accessibility.ReadAnything.TimeFromEntryTriggeredToWebUIConnected",
base::TimeTicks::Now() - renderer_load_triggered_time_ms_);
mojo::PendingReceiver<read_anything::mojom::UntrustedPageHandlerFactory>
page_handler_factory_receiver =
page_handler_factory_.BindNewPipeAndPassReceiver();
page_handler_factory_->CreateUntrustedPageHandler(
receiver_.BindNewPipeAndPassRemote(),
page_handler_.BindNewPipeAndPassReceiver());
render_frame()->GetBrowserInterfaceBroker().GetInterface(
std::move(page_handler_factory_receiver));
// Get the dependency parser model used by phrase-based highlighting.
if (read_aloud_model_.GetDependencyParserModel().IsAvailable()) {
return;
}
page_handler_->GetDependencyParserModel(
base::BindOnce(&ReadAnythingAppController::UpdateDependencyParserModel,
weak_ptr_factory_.GetWeakPtr()));
}
void ReadAnythingAppController::OnCopy() const {
page_handler_->OnCopy();
}
void ReadAnythingAppController::OnNoTextContent(bool previouslyHadContent) {
if (previouslyHadContent) {
Distill();
} else {
// If updateContent was called on a page with no valid content and
// reading mode previously didn't have content, ensure the empty state
// is now showing. Otherwise, the loading screen may never terminate.
DrawEmptyState();
}
}
void ReadAnythingAppController::OnFontSizeChanged(bool increase) {
model_.AdjustTextSize(increase ? 1 : -1);
page_handler_->OnFontSizeChange(model_.font_size());
}
void ReadAnythingAppController::OnFontSizeReset() {
model_.ResetTextSize();
page_handler_->OnFontSizeChange(model_.font_size());
}
void ReadAnythingAppController::OnLinksEnabledToggled() {
model_.set_links_enabled(!model_.links_enabled());
page_handler_->OnLinksEnabledChanged(model_.links_enabled());
}
void ReadAnythingAppController::OnImagesEnabledToggled() {
model_.set_images_enabled(!model_.images_enabled());
page_handler_->OnImagesEnabledChanged(model_.images_enabled());
}
void ReadAnythingAppController::OnScroll(bool on_selection) const {
model_.OnScroll(on_selection, /* from_reading_mode= */ true);
}
void ReadAnythingAppController::OnLinkClicked(ui::AXNodeID ax_node_id) const {
DCHECK_NE(model_.active_tree_id(), ui::AXTreeIDUnknown());
// Prevent link clicks while distillation is in progress, as it means that
// the tree may have changed in an unexpected way.
// TODO(crbug.com/40802192): Consider how to show this in a more
// user-friendly way.
if (model_.distillation_in_progress()) {
return;
}
page_handler_->OnLinkClicked(model_.active_tree_id(), ax_node_id);
}
void ReadAnythingAppController::OnLetterSpacingChange(int value) {
if (const auto maybe_enum =
ToEnum<read_anything::mojom::LetterSpacing>(value)) {
page_handler_->OnLetterSpaceChange(maybe_enum.value());
model_.set_letter_spacing(maybe_enum.value());
}
}
void ReadAnythingAppController::OnLineSpacingChange(int value) {
if (const auto maybe_enum =
ToEnum<read_anything::mojom::LineSpacing>(value)) {
page_handler_->OnLineSpaceChange(maybe_enum.value());
model_.set_line_spacing(maybe_enum.value());
}
}
void ReadAnythingAppController::OnThemeChange(int value) {
if (const auto maybe_enum = ToEnum<read_anything::mojom::Colors>(value)) {
page_handler_->OnColorChange(maybe_enum.value());
model_.set_color_theme(maybe_enum.value());
}
}
void ReadAnythingAppController::OnFontChange(const std::string& font) {
page_handler_->OnFontChange(font);
model_.set_font_name(font);
}
void ReadAnythingAppController::OnSpeechRateChange(double rate) {
page_handler_->OnSpeechRateChange(rate);
read_aloud_model_.set_speech_rate(rate);
}
void ReadAnythingAppController::OnVoiceChange(const std::string& voice,
const std::string& lang) {
// Store the given voice with the base language. If the user prefers a voice
// for a specific language, we should always use that voice, regardless of the
// more specific locale. e.g. if the user prefers the en-UK voice for English
// pages, use that voice even if the page is marked en-US.
std::string base_lang = std::string(language::ExtractBaseLanguage(lang));
page_handler_->OnVoiceChange(voice, base_lang);
read_aloud_model_.SetVoice(voice, base_lang);
}
void ReadAnythingAppController::OnLanguagePrefChange(const std::string& lang,
bool enabled) {
page_handler_->OnLanguagePrefChange(lang, enabled);
read_aloud_model_.SetLanguageEnabled(lang, enabled);
}
void ReadAnythingAppController::OnHighlightGranularityChanged(
const int granularity) {
page_handler_->OnHighlightGranularityChanged(
static_cast<read_anything::mojom::HighlightGranularity>(granularity));
read_aloud_model_.set_highlight_granularity(granularity);
}
double ReadAnythingAppController::GetLineSpacingValue(int line_spacing) const {
using read_anything::mojom::LineSpacing;
static constexpr auto kEnumToValue =
base::MakeFixedFlatMap<LineSpacing, double>({
{LineSpacing::kTightDeprecated, 1.0},
// This value needs to be at least 1.35 to avoid cutting off
// descenders with the highlight with larger fonts such as Poppins.
{LineSpacing::kStandard, 1.35},
{LineSpacing::kLoose, 1.5},
{LineSpacing::kVeryLoose, 2.0},
});
return kEnumToValue.at(
ToEnum<LineSpacing>(line_spacing).value_or(LineSpacing::kDefaultValue));
}
double ReadAnythingAppController::GetLetterSpacingValue(
int letter_spacing) const {
using read_anything::mojom::LetterSpacing;
static constexpr auto kEnumToValue =
base::MakeFixedFlatMap<LetterSpacing, double>({
{LetterSpacing::kTightDeprecated, -0.05},
{LetterSpacing::kStandard, 0},
{LetterSpacing::kWide, 0.05},
{LetterSpacing::kVeryWide, 0.1},
});
return kEnumToValue.at(ToEnum<LetterSpacing>(letter_spacing)
.value_or(LetterSpacing::kDefaultValue));
}
void ReadAnythingAppController::OnSelectionChange(ui::AXNodeID anchor_node_id,
int anchor_offset,
ui::AXNodeID focus_node_id,
int focus_offset) {
DCHECK_NE(model_.active_tree_id(), ui::AXTreeIDUnknown());
// Prevent link clicks while distillation is in progress, as it means that
// the tree may have changed in an unexpected way.
// TODO(crbug.com/40802192): Consider how to show this in a more
// user-friendly way.
if (model_.distillation_in_progress()) {
return;
}
// Ignore the new selection if it's collapsed, which is created by a simple
// click, unless there was a previous selection, in which case the click
// clears the selection, so we should tell the main page to clear too.
if ((anchor_offset == focus_offset) && (anchor_node_id == focus_node_id)) {
if (model_.has_selection()) {
model_.increment_selections_from_reading_mode();
OnCollapseSelection();
}
return;
}
ui::AXNode* focus_node = model_.GetAXNode(focus_node_id);
ui::AXNode* anchor_node = model_.GetAXNode(anchor_node_id);
if (!focus_node || !anchor_node) {
// Sometimes when the side panel size is adjusted, a focus or anchor node
// may be null. Return early if this happens.
return;
}
// Some text fields, like Gmail, allow a <div> to be returned as a focus
// node for selection, most frequently when a triple click causes an entire
// range of text to be selected, including non-text nodes. This can cause
// inconsistencies in how the selection is handled. e.g. the focus node can
// be before the anchor node and set to a non-text node, which can cause
// page_handler_->OnSelectionChange to be incorrectly triggered, resulting
// in a failing DCHECK. Therefore, return early if this happens. This check
// does not apply to pdfs.
if (!model_.is_pdf() && (!focus_node->IsText() || !anchor_node->IsText())) {
return;
}
// If the selection change matches the tree's selection, this means it was
// set by the controller. Javascript selections set by the controller are
// always forward selections. This means the anchor node always comes before
// the focus node.
if (anchor_node_id == model_.start_node_id() &&
anchor_offset == model_.start_offset() &&
focus_node_id == model_.end_node_id() &&
focus_offset == model_.end_offset()) {
return;
}
model_.increment_selections_from_reading_mode();
page_handler_->OnSelectionChange(model_.active_tree_id(), anchor_node_id,
anchor_offset, focus_node_id, focus_offset);
}
void ReadAnythingAppController::OnCollapseSelection() const {
if (model_.is_pdf()) {
// CollapseSelection does nothing in pdfs, so just set an empty selection
// instead.
page_handler_->OnSelectionChange(
model_.active_tree_id(), model_.start_node_id(), model_.start_offset(),
model_.start_node_id(), model_.start_offset());
} else {
page_handler_->OnCollapseSelection();
}
}
void ReadAnythingAppController::ResetGranularityIndex() {
read_aloud_model_.ResetGranularityIndex();
}
void ReadAnythingAppController::InitAXPositionWithNode(
const ui::AXNodeID& starting_node_id) {
ui::AXNode* ax_node = model_.GetAXNode(starting_node_id);
read_aloud_model_.InitAXPositionWithNode(ax_node, model_.active_tree_id());
// TODO: crbug.com/411198154: This should only be called if the ax position
// is not already initialized.
PreprocessTextForSpeech();
}
bool ReadAnythingAppController::IsSpeechTreeInitialized() {
return read_aloud_model_.speech_tree_initialized();
}
std::vector<ui::AXNodeID> ReadAnythingAppController::GetCurrentText() {
return read_aloud_model_.GetCurrentText(model_.is_pdf(), model_.IsDocs(),
model_.GetCurrentlyVisibleNodes());
}
void ReadAnythingAppController::PreprocessTextForSpeech() {
read_aloud_model_.PreprocessTextForSpeech(model_.is_pdf(), model_.IsDocs(),
model_.GetCurrentlyVisibleNodes());
}
void ReadAnythingAppController::MovePositionToNextGranularity() {
read_aloud_model_.MovePositionToNextGranularity();
}
void ReadAnythingAppController::MovePositionToPreviousGranularity() {
read_aloud_model_.MovePositionToPreviousGranularity();
}
int ReadAnythingAppController::GetCurrentTextStartIndex(ui::AXNodeID node_id) {
return read_aloud_model_.GetCurrentTextStartIndex(node_id);
}
int ReadAnythingAppController::GetCurrentTextEndIndex(ui::AXNodeID node_id) {
return read_aloud_model_.GetCurrentTextEndIndex(node_id);
}
void ReadAnythingAppController::SetLanguageForTesting(
const std::string& language_code) {
SetLanguageCode(language_code);
}
void ReadAnythingAppController::SetLanguageCode(const std::string& code) {
if (code.empty()) {
model_.set_requires_tree_lang(true);
return;
}
std::string base_lang = std::string(language::ExtractBaseLanguage(code));
model_.SetBaseLanguageCode(base_lang);
ExecuteJavaScript("chrome.readingMode.languageChanged();");
}
#if BUILDFLAG(IS_CHROMEOS)
void ReadAnythingAppController::OnDeviceLocked() {
read_aloud_model_.LogSpeechStop(
ReadAloudAppModel::ReadAloudStopSource::kLockChromeosDevice);
// Signal to the WebUI that the device has been locked. We'll only receive
// this callback on ChromeOS.
ExecuteJavaScript("chrome.readingMode.onLockScreen();");
}
#else
void ReadAnythingAppController::OnTtsEngineInstalled() {
ExecuteJavaScript("chrome.readingMode.onTtsEngineInstalled()");
}
#endif
void ReadAnythingAppController::OnReadingModeHidden() {
model_.set_will_hide(true);
read_aloud_model_.LogSpeechStop(
ReadAloudAppModel::ReadAloudStopSource::kCloseReadingMode);
}
void ReadAnythingAppController::OnTabWillDetach() {
model_.set_will_hide(true);
read_aloud_model_.LogSpeechStop(
ReadAloudAppModel::ReadAloudStopSource::kCloseTabOrWindow);
}
void ReadAnythingAppController::OnTabMuteStateChange(bool muted) {
ExecuteJavaScript("chrome.readingMode.onTabMuteStateChange(" +
base::ToString(muted) + ")");
}
void ReadAnythingAppController::SetDefaultLanguageCode(
const std::string& code) {
std::string default_lang = std::string(language::ExtractBaseLanguage(code));
// If the default language code is empty, continue to use the default
// language code, as defined by ReadAnythingAppModel, currently 'en'
if (default_lang.length() > 0) {
read_aloud_model_.set_default_language_code(default_lang);
}
}
void ReadAnythingAppController::SetContentForTesting(
v8::Local<v8::Value> v8_snapshot_lite,
std::vector<ui::AXNodeID> content_node_ids) {
v8::Isolate* isolate =
render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate();
ui::AXTreeUpdate snapshot =
GetSnapshotFromV8SnapshotLite(isolate, v8_snapshot_lite);
ui::AXEvent selection_event;
selection_event.event_type = ax::mojom::Event::kDocumentSelectionChanged;
selection_event.event_from = ax::mojom::EventFrom::kUser;
AccessibilityEventReceived(snapshot.tree_data.tree_id, {snapshot}, {});
OnActiveAXTreeIDChanged(snapshot.tree_data.tree_id, ukm::kInvalidSourceId,
false);
OnAXTreeDistilled(snapshot.tree_data.tree_id, content_node_ids);
// Trigger a selection event (for testing selections).
AccessibilityEventReceived(snapshot.tree_data.tree_id, {snapshot},
{selection_event});
}
void ReadAnythingAppController::ShouldShowUI() {
page_handler_factory_->ShouldShowUI();
}
void ReadAnythingAppController::OnIsSpeechActiveChanged(bool is_speech_active) {
// Don't send event updates if the speech playing state hasn't actually
// changed. This can get triggered incorrectly when changing pages.
if (read_aloud_model_.speech_playing() == is_speech_active) {
return;
}
read_aloud_model_.SetSpeechPlaying(is_speech_active);
if (!is_speech_active) {
SendEventUpdates();
}
}
void ReadAnythingAppController::OnIsAudioCurrentlyPlayingChanged(
bool is_audio_currently_playing) {
if (read_aloud_model_.audio_currently_playing() ==
is_audio_currently_playing) {
return;
}
read_aloud_model_.SetAudioCurrentlyPlaying(is_audio_currently_playing);
page_handler_->OnReadAloudAudioStateChange(is_audio_currently_playing);
}
int ReadAnythingAppController::GetAccessibleBoundary(const std::u16string& text,
int max_text_length) {
std::vector<int> offsets;
const std::u16string shorter_string = text.substr(0, max_text_length);
size_t sentence_ends_short = ui::FindAccessibleTextBoundary(
shorter_string, offsets, ax::mojom::TextBoundary::kSentenceStart, 0,
ax::mojom::MoveDirection::kForward,
ax::mojom::TextAffinity::kDefaultValue);
size_t sentence_ends_long = ui::FindAccessibleTextBoundary(
text, offsets, ax::mojom::TextBoundary::kSentenceStart, 0,
ax::mojom::MoveDirection::kForward,
ax::mojom::TextAffinity::kDefaultValue);
// Compare the index result for the sentence of maximum text length and of
// the longer text string. If the two values are the same, the index is
// correct. If they are different, the maximum text length may have
// incorrectly spliced a word (e.g. returned "this is a sen" instead of
// "this is a" or "this is a sentence"), so if this is the case, we'll want
// to use the last word boundary instead.
if (sentence_ends_short == sentence_ends_long) {
return sentence_ends_short;
}
size_t word_ends = ui::FindAccessibleTextBoundary(
shorter_string, offsets, ax::mojom::TextBoundary::kWordStart,
shorter_string.length() - 1, ax::mojom::MoveDirection::kBackward,
ax::mojom::TextAffinity::kDefaultValue);
return word_ends;
}
v8::Local<v8::Value>
ReadAnythingAppController::GetHighlightForCurrentSegmentIndex(int index,
bool phrases) {
v8::Isolate* isolate =
render_frame()->GetWebFrame()->GetAgentGroupScheduler()->Isolate();
auto context = isolate->GetCurrentContext();
std::vector<ReadAloudTextSegment> nodes =
read_aloud_model_.GetHighlightForCurrentSegmentIndex(index, phrases);
v8::Local<v8::Array> highlight_array = v8::Array::New(isolate, nodes.size());
for (int i = 0; i < (int)nodes.size(); i++) {
v8::Local<v8::Object> obj = v8::Object::New(isolate);
auto checked = obj->DefineOwnProperty(
context, v8::String::NewFromUtf8(isolate, "nodeId").ToLocalChecked(),
v8::Number::New(isolate, nodes[i].id));
checked = obj->DefineOwnProperty(
context, v8::String::NewFromUtf8(isolate, "start").ToLocalChecked(),
v8::Number::New(isolate, nodes[i].text_start));
checked = obj->DefineOwnProperty(
context, v8::String::NewFromUtf8(isolate, "length").ToLocalChecked(),
v8::Number::New(isolate, (nodes[i].text_end - nodes[i].text_start)));
checked = highlight_array->Set(isolate->GetCurrentContext(), i, obj);
}
return highlight_array;
}
void ReadAnythingAppController::IncrementMetricCount(
const std::string& metric) {
read_aloud_model_.IncrementMetric(metric);
}
void ReadAnythingAppController::LogSpeechStop(int source) {
if (!IsReadAloudEnabled()) {
return;
}
// Don't log speech stopping if the reading mode panel is going to hide. That
// case is logged separately.
if (model_.will_hide()) {
return;
}
if (const auto maybe_enum =
ToEnum<ReadAloudAppModel::ReadAloudStopSource>(source)) {
read_aloud_model_.LogSpeechStop(maybe_enum.value());
}
}
void ReadAnythingAppController::OnUrlInformationSet() {
read_aloud_model_.LogSpeechStop(
model_.IsReload() ? ReadAloudAppModel::ReadAloudStopSource::kReloadPage
: ReadAloudAppModel::ReadAloudStopSource::kChangePage);
}
void ReadAnythingAppController::OnScrolledToBottom() {
if (IsGoogleDocs()) {
// Scroll to the last display node shown on the Reading Mode side panel
// TODO (b/356935604): Investigate optimal scroll position
page_handler_->ScrollToTargetNode(model_.active_tree_id(),
*model_.display_node_ids().rbegin());
}
}
bool ReadAnythingAppController::IsDocsLoadMoreButtonVisible() const {
return (features::IsReadAnythingDocsLoadMoreButtonEnabled() &&
IsGoogleDocs());
}
void ReadAnythingAppController::UpdateDependencyParserModel(
base::File model_file) {
read_aloud_model_.GetDependencyParserModel().UpdateWithFile(
std::move(model_file));
}
DependencyParserModel&
ReadAnythingAppController::GetDependencyParserModelForTesting() {
return read_aloud_model_.GetDependencyParserModel();
}
void ReadAnythingAppController::OnTreeAdded(ui::AXTree* tree) {
auto observation =
std::make_unique<base::ScopedObservation<ui::AXTree, ui::AXTreeObserver>>(
this);
observation->Observe(tree);
tree_observers_.push_back(std::move(observation));
}
void ReadAnythingAppController::OnTreeRemoved(ui::AXTree* tree) {
auto it = std::ranges::find_if(tree_observers_,
[tree](const auto& observation) -> bool {
return observation->GetSource() == tree;
});
if (it != tree_observers_.end()) {
tree_observers_.erase(it);
}
}
|