From 9ce67ae3932754208122ef924b987b5ac7944776 Mon Sep 17 00:00:00 2001 From: Matti Mokko Date: Thu, 8 Feb 2024 12:41:31 +0200 Subject: [PATCH 01/11] Add java inspector backend --- robocorp-code/poetry.lock | 65 +++++++++++++------ robocorp-code/pyproject.toml | 5 +- .../robocorp_code/inspector/java/__init__.py | 0 .../inspector/java/java_inspector.py | 33 ++++++++++ .../inspector/java/robocorp_java/__init__.py | 0 .../java/robocorp_java/_event_pump.py | 63 ++++++++++++++++++ .../java/robocorp_java/_inspector.py | 24 +++++++ 7 files changed, 168 insertions(+), 22 deletions(-) create mode 100644 robocorp-code/src/robocorp_code/inspector/java/__init__.py create mode 100644 robocorp-code/src/robocorp_code/inspector/java/java_inspector.py create mode 100644 robocorp-code/src/robocorp_code/inspector/java/robocorp_java/__init__.py create mode 100644 robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py create mode 100644 robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py diff --git a/robocorp-code/poetry.lock b/robocorp-code/poetry.lock index 9cefb4ca63..fbb3729426 100644 --- a/robocorp-code/poetry.lock +++ b/robocorp-code/poetry.lock @@ -426,6 +426,20 @@ files = [ [package.extras] colors = ["colorama (>=0.4.6)"] +[[package]] +name = "java-access-bridge-wrapper" +version = "1.1.0" +description = "Python wrapper for the Windows Java Access Bridge" +optional = false +python-versions = ">=3.8.1,<4.0.0" +files = [ + {file = "java_access_bridge_wrapper-1.1.0-py3-none-any.whl", hash = "sha256:8d52556ec57b418dfbce319d7ed70160e7d21c5db9cff9606f73cf04cacb722f"}, + {file = "java_access_bridge_wrapper-1.1.0.tar.gz", hash = "sha256:bec4bff34d4c33e54f98efb8cafc2d2dc805bd756a8c08e5e5150f0520b074b2"}, +] + +[package.dependencies] +pywin32 = {version = ">=300,<307", markers = "python_full_version != \"3.8.1\" and sys_platform == \"win32\""} + [[package]] name = "mock" version = "5.1.0" @@ -1200,6 +1214,7 @@ files = [ {file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:69b023b2b4daa7548bcfbd4aa3da05b3a74b772db9e23b982788168117739938"}, {file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:81e0b275a9ecc9c0c0c07b4b90ba548307583c125f54d5b6946cfee6360c733d"}, {file = "PyYAML-6.0.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:ba336e390cd8e4d1739f42dfe9bb83a3cc2e80f567d8805e11b46f4a943f5515"}, + {file = "PyYAML-6.0.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:326c013efe8048858a6d312ddd31d56e468118ad4cdeda36c719bf5bb6192290"}, {file = "PyYAML-6.0.1-cp310-cp310-win32.whl", hash = "sha256:bd4af7373a854424dabd882decdc5579653d7868b8fb26dc7d0e99f823aa5924"}, {file = "PyYAML-6.0.1-cp310-cp310-win_amd64.whl", hash = "sha256:fd1592b3fdf65fff2ad0004b5e363300ef59ced41c2e6b3a99d4089fa8c5435d"}, {file = "PyYAML-6.0.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:6965a7bc3cf88e5a1c3bd2e0b5c22f8d677dc88a455344035f03399034eb3007"}, @@ -1207,8 +1222,16 @@ files = [ {file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:42f8152b8dbc4fe7d96729ec2b99c7097d656dc1213a3229ca5383f973a5ed6d"}, {file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:062582fca9fabdd2c8b54a3ef1c978d786e0f6b3a1510e0ac93ef59e0ddae2bc"}, {file = "PyYAML-6.0.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d2b04aac4d386b172d5b9692e2d2da8de7bfb6c387fa4f801fbf6fb2e6ba4673"}, + {file = "PyYAML-6.0.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:e7d73685e87afe9f3b36c799222440d6cf362062f78be1013661b00c5c6f678b"}, {file = "PyYAML-6.0.1-cp311-cp311-win32.whl", hash = "sha256:1635fd110e8d85d55237ab316b5b011de701ea0f29d07611174a1b42f1444741"}, {file = "PyYAML-6.0.1-cp311-cp311-win_amd64.whl", hash = "sha256:bf07ee2fef7014951eeb99f56f39c9bb4af143d8aa3c21b1677805985307da34"}, + {file = "PyYAML-6.0.1-cp312-cp312-macosx_10_9_x86_64.whl", hash = "sha256:855fb52b0dc35af121542a76b9a84f8d1cd886ea97c84703eaa6d88e37a2ad28"}, + {file = "PyYAML-6.0.1-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:40df9b996c2b73138957fe23a16a4f0ba614f4c0efce1e9406a184b6d07fa3a9"}, + {file = "PyYAML-6.0.1-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a08c6f0fe150303c1c6b71ebcd7213c2858041a7e01975da3a99aed1e7a378ef"}, + {file = "PyYAML-6.0.1-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:6c22bec3fbe2524cde73d7ada88f6566758a8f7227bfbf93a408a9d86bcc12a0"}, + {file = "PyYAML-6.0.1-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:8d4e9c88387b0f5c7d5f281e55304de64cf7f9c0021a3525bd3b1c542da3b0e4"}, + {file = "PyYAML-6.0.1-cp312-cp312-win32.whl", hash = "sha256:d483d2cdf104e7c9fa60c544d92981f12ad66a457afae824d146093b8c294c54"}, + {file = "PyYAML-6.0.1-cp312-cp312-win_amd64.whl", hash = "sha256:0d3304d8c0adc42be59c5f8a4d9e3d7379e6955ad754aa9d6ab7a398b59dd1df"}, {file = "PyYAML-6.0.1-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:50550eb667afee136e9a77d6dc71ae76a44df8b3e51e41b77f6de2932bfe0f47"}, {file = "PyYAML-6.0.1-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1fe35611261b29bd1de0070f0b2f47cb6ff71fa6595c077e42bd0c419fa27b98"}, {file = "PyYAML-6.0.1-cp36-cp36m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:704219a11b772aea0d8ecd7058d0082713c3562b4e271b849ad7dc4a5c90c13c"}, @@ -1225,6 +1248,7 @@ files = [ {file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:a0cd17c15d3bb3fa06978b4e8958dcdc6e0174ccea823003a106c7d4d7899ac5"}, {file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:28c119d996beec18c05208a8bd78cbe4007878c6dd15091efb73a30e90539696"}, {file = "PyYAML-6.0.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:7e07cbde391ba96ab58e532ff4803f79c4129397514e1413a7dc761ccd755735"}, + {file = "PyYAML-6.0.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:49a183be227561de579b4a36efbb21b3eab9651dd81b1858589f796549873dd6"}, {file = "PyYAML-6.0.1-cp38-cp38-win32.whl", hash = "sha256:184c5108a2aca3c5b3d3bf9395d50893a7ab82a38004c8f61c258d4428e80206"}, {file = "PyYAML-6.0.1-cp38-cp38-win_amd64.whl", hash = "sha256:1e2722cc9fbb45d9b87631ac70924c11d3a401b2d7f410cc0e3bbf249f2dca62"}, {file = "PyYAML-6.0.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:9eb6caa9a297fc2c2fb8862bc5370d0303ddba53ba97e71f08023b6cd73d16a8"}, @@ -1232,6 +1256,7 @@ files = [ {file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5773183b6446b2c99bb77e77595dd486303b4faab2b086e7b17bc6bef28865f6"}, {file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:b786eecbdf8499b9ca1d697215862083bd6d2a99965554781d0d8d1ad31e13a0"}, {file = "PyYAML-6.0.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:bc1bf2925a1ecd43da378f4db9e4f799775d6367bdb94671027b73b393a7c42c"}, + {file = "PyYAML-6.0.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:04ac92ad1925b2cff1db0cfebffb6ffc43457495c9b3c39d3fcae417d7125dc5"}, {file = "PyYAML-6.0.1-cp39-cp39-win32.whl", hash = "sha256:faca3bdcf85b2fc05d06ff3fbc1f83e1391b3e724afa3feba7d13eeab355484c"}, {file = "PyYAML-6.0.1-cp39-cp39-win_amd64.whl", hash = "sha256:510c9deebc5c0225e8c96813043e62b680ba2f9c50a08d3724c7f28a747d1486"}, {file = "PyYAML-6.0.1.tar.gz", hash = "sha256:bfdf460b1736c775f2ba9f6a92bca30bc2095067b8a9d77876d1fad6cc3b4a43"}, @@ -1480,28 +1505,28 @@ rpaframework-core = ">=11.0.0,<12.0.0" [[package]] name = "ruff" -version = "0.0.255" -description = "An extremely fast Python linter, written in Rust." +version = "0.2.1" +description = "An extremely fast Python linter and code formatter, written in Rust." optional = false python-versions = ">=3.7" files = [ - {file = "ruff-0.0.255-py3-none-macosx_10_7_x86_64.whl", hash = "sha256:b2d71fb6a7e50501a2473864acffc85dee6b750c25db198f7e71fe1dbbff1aad"}, - {file = "ruff-0.0.255-py3-none-macosx_10_9_x86_64.macosx_11_0_arm64.macosx_10_9_universal2.whl", hash = "sha256:6c97d746861a6010f941179e84bba9feb8a871815667471d9ed6beb98d45c252"}, - {file = "ruff-0.0.255-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9a7fa60085079b91a298b963361be9b1b1c724582af6c84be954cbabdbd9309a"}, - {file = "ruff-0.0.255-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:c089f7141496334ab5a127b54ce55e41f0d6714e68a4453a1e09d2204cdea8c3"}, - {file = "ruff-0.0.255-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:0423908caa7d437a416b853214565b9c33bbd1106c4f88147982216dddcbbd96"}, - {file = "ruff-0.0.255-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:981493e92547cacbb8e0874904ec049fe744507ee890dc8736caf89a8864f9a7"}, - {file = "ruff-0.0.255-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:59d5193d2aedb35db180824462b374dbcfc306b2e76076245088afa6e5837df2"}, - {file = "ruff-0.0.255-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:dd5e00733c9d160c8a34a22e62b390da9d1e9f326676402421cb8c1236beefc3"}, - {file = "ruff-0.0.255-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:694418cf41838bd19c6229e4e1b2d04505b1e6b86fe3ab81165484fc96d36f01"}, - {file = "ruff-0.0.255-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:5d0408985c9777369daebb5d3340a99e9f7294bdd7120642239261508185cf89"}, - {file = "ruff-0.0.255-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:abd6376ef9d12f370d95a8c7c98682fbb9bfedfba59f40e84a816fef8ddcb8de"}, - {file = "ruff-0.0.255-py3-none-musllinux_1_2_i686.whl", hash = "sha256:f9b1a5df0bc09193cbef58a6f78e4a9a0b058a4f9733c0442866d078006d1bb9"}, - {file = "ruff-0.0.255-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:6a25c5f4ff087445b2e1bbcb9963f2ae7c868d65e4a8d5f84c36c12f71571179"}, - {file = "ruff-0.0.255-py3-none-win32.whl", hash = "sha256:1ff87a8310354f9f1a099625e54a27fdd6756d9cd2a40b45922f2e943daf982d"}, - {file = "ruff-0.0.255-py3-none-win_amd64.whl", hash = "sha256:f3d8416be618f023f93ec4fd6ee3048585ef85dba9563b2a7e38fc7e5131d5b1"}, - {file = "ruff-0.0.255-py3-none-win_arm64.whl", hash = "sha256:8ba124819624145d7b6b53add40c367c44318893215ffc1bfe3d72e0225a1c9c"}, - {file = "ruff-0.0.255.tar.gz", hash = "sha256:f9eb1d3b2eecbeedae419fa494c4e2a5e4484baf93a1ce0f81eddb005e1919c5"}, + {file = "ruff-0.2.1-py3-none-macosx_10_12_x86_64.macosx_11_0_arm64.macosx_10_12_universal2.whl", hash = "sha256:dd81b911d28925e7e8b323e8d06951554655021df8dd4ac3045d7212ac4ba080"}, + {file = "ruff-0.2.1-py3-none-macosx_10_12_x86_64.whl", hash = "sha256:dc586724a95b7d980aa17f671e173df00f0a2eef23f8babbeee663229a938fec"}, + {file = "ruff-0.2.1-py3-none-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c92db7101ef5bfc18e96777ed7bc7c822d545fa5977e90a585accac43d22f18a"}, + {file = "ruff-0.2.1-py3-none-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:13471684694d41ae0f1e8e3a7497e14cd57ccb7dd72ae08d56a159d6c9c3e30e"}, + {file = "ruff-0.2.1-py3-none-manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:a11567e20ea39d1f51aebd778685582d4c56ccb082c1161ffc10f79bebe6df35"}, + {file = "ruff-0.2.1-py3-none-manylinux_2_17_ppc64.manylinux2014_ppc64.whl", hash = "sha256:00a818e2db63659570403e44383ab03c529c2b9678ba4ba6c105af7854008105"}, + {file = "ruff-0.2.1-py3-none-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:be60592f9d218b52f03384d1325efa9d3b41e4c4d55ea022cd548547cc42cd2b"}, + {file = "ruff-0.2.1-py3-none-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:fbd2288890b88e8aab4499e55148805b58ec711053588cc2f0196a44f6e3d855"}, + {file = "ruff-0.2.1-py3-none-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f3ef052283da7dec1987bba8d8733051c2325654641dfe5877a4022108098683"}, + {file = "ruff-0.2.1-py3-none-musllinux_1_2_aarch64.whl", hash = "sha256:7022d66366d6fded4ba3889f73cd791c2d5621b2ccf34befc752cb0df70f5fad"}, + {file = "ruff-0.2.1-py3-none-musllinux_1_2_armv7l.whl", hash = "sha256:0a725823cb2a3f08ee743a534cb6935727d9e47409e4ad72c10a3faf042ad5ba"}, + {file = "ruff-0.2.1-py3-none-musllinux_1_2_i686.whl", hash = "sha256:0034d5b6323e6e8fe91b2a1e55b02d92d0b582d2953a2b37a67a2d7dedbb7acc"}, + {file = "ruff-0.2.1-py3-none-musllinux_1_2_x86_64.whl", hash = "sha256:e5cb5526d69bb9143c2e4d2a115d08ffca3d8e0fddc84925a7b54931c96f5c02"}, + {file = "ruff-0.2.1-py3-none-win32.whl", hash = "sha256:6b95ac9ce49b4fb390634d46d6ece32ace3acdd52814671ccaf20b7f60adb232"}, + {file = "ruff-0.2.1-py3-none-win_amd64.whl", hash = "sha256:e3affdcbc2afb6f5bd0eb3130139ceedc5e3f28d206fe49f63073cb9e65988e0"}, + {file = "ruff-0.2.1-py3-none-win_arm64.whl", hash = "sha256:efababa8e12330aa94a53e90a81eb6e2d55f348bc2e71adbf17d9cad23c03ee6"}, + {file = "ruff-0.2.1.tar.gz", hash = "sha256:3b42b5d8677cd0c72b99fcaf068ffc62abb5a19e71b4a3b9cfa50658a0af02f1"}, ] [[package]] @@ -1865,4 +1890,4 @@ testing = ["big-O", "jaraco.functools", "jaraco.itertools", "more-itertools", "p [metadata] lock-version = "2.0" python-versions = ">=3.10,<3.11" -content-hash = "7c3c3b7ab1d98a2eeac92c7a688d673b793b90534d98ce157e0c4924a6bed198" +content-hash = "5bb9ac87f62b8cf8a00667dd489d3a42c614e9f1aceea3dacd59ed5698e6330a" diff --git a/robocorp-code/pyproject.toml b/robocorp-code/pyproject.toml index e6ddea026d..971cce26fc 100644 --- a/robocorp-code/pyproject.toml +++ b/robocorp-code/pyproject.toml @@ -39,6 +39,8 @@ pillow = "^9.0" pywin32 = { version = ">=300,<304", platform = "win32", python = "!=3.8.1" } psutil = "^5.9.0" comtypes = "^1.1" +java-access-bridge-wrapper = "^1.1.0" +ruff = "^0.2.1" [tool.poetry.group.dev.dependencies] robocorp-python-ls-core = {path = "../robocorp-python-ls-core/", develop = true} @@ -52,7 +54,6 @@ robocorp-actions = "^0.0.7" # Just needed for testing. numpy = "<2" black = "^23.1.0" -ruff = "^0.0.255" mypy = "^1.1.1" isort = { version = "^5.12.0", python = "^3.8" } invoke = "^2.0" @@ -89,7 +90,7 @@ exclude = "vendored" [tool.ruff] ignore = [ "E501", # Line-len. - "F541", # f-string without placeholders. + "F541", # f-string without placeholders. "E731", # Use 'def' instead of lambda. ] diff --git a/robocorp-code/src/robocorp_code/inspector/java/__init__.py b/robocorp-code/src/robocorp_code/inspector/java/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py b/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py new file mode 100644 index 0000000000..8d012df2bb --- /dev/null +++ b/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py @@ -0,0 +1,33 @@ +from typing import List, TypedDict, cast + +from JABWrapper.jab_wrapper import JavaWindow + +JavaWindowInfoTypedDict = TypedDict( + "JavaWindowInfoTypedDict", + { + # Same as JavaWindow + "pid": int, + "hwnd": int, + "title": str, + }, +) + + +def to_window_info(java_window: JavaWindow) -> JavaWindowInfoTypedDict: + ret = {} + for dct_name in JavaWindowInfoTypedDict.__annotations__: + ret[dct_name] = getattr(java_window, dct_name) + return cast(JavaWindowInfoTypedDict, ret) + + +class JavaInspector: + def __init__(self): + from robocorp_code.inspector.java.robocorp_java._inspector import ( + ElementInspector, + ) + + self._inspector = ElementInspector() + + def list_windows(self) -> List[JavaWindowInfoTypedDict]: + windows = self._inspector.list_windows() + return [to_window_info(window) for window in windows] diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/__init__.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py new file mode 100644 index 0000000000..c3758c992e --- /dev/null +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py @@ -0,0 +1,63 @@ +import ctypes +import queue +import threading +import time + +from JABWrapper.jab_wrapper import JavaAccessBridgeWrapper +from robocorp_ls_core.robotframework_log import get_logger + +PeekMessage = ctypes.windll.user32.PeekMessageW +GetMessage = ctypes.windll.user32.GetMessageW +TranslateMessage = ctypes.windll.user32.TranslateMessage +DispatchMessage = ctypes.windll.user32.DispatchMessageW + +log = get_logger(__name__) + + +REMOVE_FROM_QUEUE = 0x0001 + + +class _EventPumpThread(threading.Thread): + def __init__( + self, + ) -> None: + super().__init__() + # Jab wrapper needs to be part of the thread that pumps the window events + self._jab_wrapper: JavaAccessBridgeWrapper = None + self._queue = queue.Queue() + self._quit_queue_loop = threading.Event() + + def _pump_background(self) -> bool: + try: + message = ctypes.byref(ctypes.wintypes.MSG()) + # Nonblocking API to get windows window events from the queue. + # https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-peekmessagea + # Use non blocing API here so that the thread can quit. + if PeekMessage(message, 0, 0, 0, REMOVE_FROM_QUEUE): + TranslateMessage(message) + log.debug("Dispatching msg={}".format(repr(message))) + DispatchMessage(message) + return True + except Exception as err: + log.error(f"Pump error: {err}") + finally: + log.info("Stopped processing events") + return False + + def run(self) -> None: + self._jab_wrapper = JavaAccessBridgeWrapper(ignore_callbacks=True) + self._queue.put(self._jab_wrapper) + while not self._quit_queue_loop.is_set(): + # The pump is non blocking. If the is no message in the queue + # wait for 10 milliseconds until check again to prevent too + # fast loop. + # TODO: add backoff timer + if not self._pump_background(): + time.sleep(0.01) + + def stop(self): + self._quit_queue_loop.set() + self._jab_wrapper = None + + def get_wrapper(self) -> JavaAccessBridgeWrapper: + return self._queue.get() diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py new file mode 100644 index 0000000000..b4159deee8 --- /dev/null +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py @@ -0,0 +1,24 @@ +from typing import List + +from JABWrapper.jab_wrapper import JavaAccessBridgeWrapper, JavaWindow + + +class ElementInspector: + def __init__(self): + from ._event_pump import _EventPumpThread + + self._pump_thread = _EventPumpThread() + + def _start_pump(func, *args, **kwargs): + def wrapper(self: "ElementInspector", *args, **kwargs): + self._pump_thread.start() + jab_wrapper = self._pump_thread.get_wrapper() + ret = func(self, jab_wrapper, *args, **kwargs) + self._pump_thread.stop() + return ret + + return wrapper + + @_start_pump + def list_windows(self, jab_wrapper: JavaAccessBridgeWrapper) -> List[JavaWindow]: + return jab_wrapper.get_windows() From 328615e580e5d346ada2e69cc67cf9ecc464bd25 Mon Sep 17 00:00:00 2001 From: Matti Mokko Date: Thu, 8 Feb 2024 13:28:59 +0200 Subject: [PATCH 02/11] Get context tree --- .../inspector/java/java_inspector.py | 42 +++++++++++- .../java/robocorp_java/_inspector.py | 36 ++++++---- .../inspector/java/robocorp_java/_locators.py | 66 +++++++++++++++++++ 3 files changed, 132 insertions(+), 12 deletions(-) create mode 100644 robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py diff --git a/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py b/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py index 8d012df2bb..e0b0c863f2 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py +++ b/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py @@ -1,6 +1,10 @@ -from typing import List, TypedDict, cast +from typing import List, Optional, TypedDict, cast +from JABWrapper.context_tree import ContextNode from JABWrapper.jab_wrapper import JavaWindow +from robocorp_ls_core.robotframework_log import get_logger + +log = get_logger(__name__) JavaWindowInfoTypedDict = TypedDict( "JavaWindowInfoTypedDict", @@ -12,6 +16,27 @@ }, ) +LocatorNodeInfoTypedDict = TypedDict( + "LocatorNoneInfoTypedDict", + { + "name": str, + "role": str, + "description": str, + "states": str, + "indexInParent": int, + "childrenCount": int, + "x": int, + "y": int, + "width": int, + "height": int, + }, +) + +LocatorTreeInfoTypedDict = TypedDict( + "LocatorTreeInfoTypedDict", + {"nodes": List[LocatorNodeInfoTypedDict]}, +) + def to_window_info(java_window: JavaWindow) -> JavaWindowInfoTypedDict: ret = {} @@ -20,6 +45,13 @@ def to_window_info(java_window: JavaWindow) -> JavaWindowInfoTypedDict: return cast(JavaWindowInfoTypedDict, ret) +def to_locator_info(context_node: ContextNode) -> LocatorNodeInfoTypedDict: + ret = {} + for dct_name in LocatorNodeInfoTypedDict.__annotations__: + ret[dct_name] = getattr(context_node.context_info, dct_name) + return cast(LocatorNodeInfoTypedDict, ret) + + class JavaInspector: def __init__(self): from robocorp_code.inspector.java.robocorp_java._inspector import ( @@ -31,3 +63,11 @@ def __init__(self): def list_windows(self) -> List[JavaWindowInfoTypedDict]: windows = self._inspector.list_windows() return [to_window_info(window) for window in windows] + + def collect_tree( + self, window: str, locator: Optional[str] = None + ) -> LocatorTreeInfoTypedDict: + log.info(f"Collect tree from locator: {locator}") + + tree = self._inspector.collect_tree(window, locator) + return [to_locator_info(node) for node in tree] diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py index b4159deee8..0ee48f6f58 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py @@ -1,24 +1,38 @@ -from typing import List +from typing import List, Optional, Union +from JABWrapper.context_tree import ContextNode, ContextTree from JABWrapper.jab_wrapper import JavaAccessBridgeWrapper, JavaWindow class ElementInspector: - def __init__(self): - from ._event_pump import _EventPumpThread - - self._pump_thread = _EventPumpThread() - - def _start_pump(func, *args, **kwargs): + def _start_event_pump(func, *args, **kwargs): def wrapper(self: "ElementInspector", *args, **kwargs): - self._pump_thread.start() - jab_wrapper = self._pump_thread.get_wrapper() + from ._event_pump import _EventPumpThread + + event_pump_thread = _EventPumpThread() + event_pump_thread.start() + jab_wrapper = event_pump_thread.get_wrapper() ret = func(self, jab_wrapper, *args, **kwargs) - self._pump_thread.stop() + event_pump_thread.stop() return ret return wrapper - @_start_pump + @_start_event_pump def list_windows(self, jab_wrapper: JavaAccessBridgeWrapper) -> List[JavaWindow]: return jab_wrapper.get_windows() + + @_start_event_pump + def collect_tree( + self, + jab_wrapper: JavaAccessBridgeWrapper, + window: str, + locator: Optional[str] = None, + ) -> Union[ContextNode, List[ContextNode]]: + jab_wrapper.switch_window_by_title(window) + context_tree = ContextTree(jab_wrapper) + if locator: + from ._locators import find_elements_from_tree + + return find_elements_from_tree(context_tree, locator) + return context_tree.root diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py new file mode 100644 index 0000000000..73e12b7785 --- /dev/null +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py @@ -0,0 +1,66 @@ +from typing import List, Optional, Union + +from JABWrapper.context_tree import ContextNode, ContextTree, SearchElement + +IntegerLocatorTypes = [ + "x", + "y", + "width", + "height", + "indexInParent", + "ancestry", + "childrentCount", +] + + +def _parse_locator(locator: str, strict_default=False): + # TODO: from rpaframework, refactor if needed + levels = locator.split(">") + levels = [lvl.strip() for lvl in levels] + searches = [] + for lvl in levels: + conditions = lvl.split(" and ") + lvl_search = [] + strict_mode = strict_default + for cond in conditions: + parts = cond.split(":", 1) + if len(parts) == 1: + parts = ["name", parts[0]] + elif parts[0].lower() == "strict": + strict_mode = bool(parts[1]) + continue + elif parts[0] in IntegerLocatorTypes: + try: + parts[1] = int(parts[1]) + except ValueError as err: + raise Exception( + "Locator '%s' needs to be of 'integer' type" % parts[0] + ) from err + lvl_search.append(SearchElement(parts[0], parts[1], strict=strict_mode)) + searches.append(lvl_search) + return searches + + +def find_elements_from_tree( + context_tree: ContextTree, + locator: str, + index: Optional[int] = None, +) -> Union[ContextNode, List[ContextNode]]: + # TODO: from rpaframework, refactor if needed + searches = _parse_locator(locator) + elements = [] + for lvl, search_elements in enumerate(searches): + if lvl == 0: + elements = context_tree.get_by_attrs(search_elements) + else: + sub_matches = [] + for elem in elements: + matches = elem.get_by_attrs(search_elements) + sub_matches.extend(matches) + elements = sub_matches + if index and len(elements) > (index + 1): + raise AttributeError( + "Locator '%s' returned only %s elements (can't index element at %s)" + % (locator, len(elements), index) + ) + return elements[index] if index else elements From 927e31709396979d7b57c7d09b1e127b48315f28 Mon Sep 17 00:00:00 2001 From: Matti Mokko Date: Thu, 8 Feb 2024 13:41:11 +0200 Subject: [PATCH 03/11] Use thread to get the context tree --- .../java/robocorp_java/_context_tree.py | 23 +++++++++++++++++++ .../java/robocorp_java/_event_pump.py | 2 +- .../java/robocorp_java/_inspector.py | 13 ++++++++--- 3 files changed, 34 insertions(+), 4 deletions(-) create mode 100644 robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_context_tree.py diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_context_tree.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_context_tree.py new file mode 100644 index 0000000000..18142d9f79 --- /dev/null +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_context_tree.py @@ -0,0 +1,23 @@ +import queue +import threading + +from JABWrapper.context_tree import ContextTree +from JABWrapper.jab_wrapper import JavaAccessBridgeWrapper + + +class ContextTreeThread(threading.Thread): + """ + Building the ContextTree in a big java application may take several minutes. + """ + + def __init__(self, jab_wrapper: JavaAccessBridgeWrapper): + super().__init__() + self._queue = queue.Queue() + self._jab_wrapper = jab_wrapper + + def run(self) -> None: + context_tree = ContextTree(self._jab_wrapper) + self._queue.put(context_tree) + + def get_context_tree(self) -> ContextTree: + return self._queue.get() diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py index c3758c992e..5a68ff0035 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py @@ -17,7 +17,7 @@ REMOVE_FROM_QUEUE = 0x0001 -class _EventPumpThread(threading.Thread): +class EventPumpThread(threading.Thread): def __init__( self, ) -> None: diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py index 0ee48f6f58..9a485c36b0 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py @@ -7,9 +7,9 @@ class ElementInspector: def _start_event_pump(func, *args, **kwargs): def wrapper(self: "ElementInspector", *args, **kwargs): - from ._event_pump import _EventPumpThread + from ._event_pump import EventPumpThread - event_pump_thread = _EventPumpThread() + event_pump_thread = EventPumpThread() event_pump_thread.start() jab_wrapper = event_pump_thread.get_wrapper() ret = func(self, jab_wrapper, *args, **kwargs) @@ -30,7 +30,14 @@ def collect_tree( locator: Optional[str] = None, ) -> Union[ContextNode, List[ContextNode]]: jab_wrapper.switch_window_by_title(window) - context_tree = ContextTree(jab_wrapper) + + from ._context_tree import ContextTreeThread + + context_tree_thread = ContextTreeThread(jab_wrapper) + context_tree_thread.start() + context_tree = context_tree_thread.get_context_tree() + context_tree_thread.join() + if locator: from ._locators import find_elements_from_tree From 7cdccbbb9334986698406ec8696c6c9f0c951eea Mon Sep 17 00:00:00 2001 From: Matti Mokko Date: Fri, 9 Feb 2024 13:15:59 +0200 Subject: [PATCH 04/11] Add search depth for context tree instead of running in thread --- .../inspector/java/java_inspector.py | 4 ++-- .../java/robocorp_java/_context_tree.py | 23 ------------------- .../java/robocorp_java/_inspector.py | 18 ++++++--------- 3 files changed, 9 insertions(+), 36 deletions(-) delete mode 100644 robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_context_tree.py diff --git a/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py b/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py index e0b0c863f2..42191fa15e 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py +++ b/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py @@ -65,9 +65,9 @@ def list_windows(self) -> List[JavaWindowInfoTypedDict]: return [to_window_info(window) for window in windows] def collect_tree( - self, window: str, locator: Optional[str] = None + self, window: str, search_depth: int = 8, locator: Optional[str] = None ) -> LocatorTreeInfoTypedDict: log.info(f"Collect tree from locator: {locator}") - tree = self._inspector.collect_tree(window, locator) + tree = self._inspector.collect_tree(window, search_depth, locator) return [to_locator_info(node) for node in tree] diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_context_tree.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_context_tree.py deleted file mode 100644 index 18142d9f79..0000000000 --- a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_context_tree.py +++ /dev/null @@ -1,23 +0,0 @@ -import queue -import threading - -from JABWrapper.context_tree import ContextTree -from JABWrapper.jab_wrapper import JavaAccessBridgeWrapper - - -class ContextTreeThread(threading.Thread): - """ - Building the ContextTree in a big java application may take several minutes. - """ - - def __init__(self, jab_wrapper: JavaAccessBridgeWrapper): - super().__init__() - self._queue = queue.Queue() - self._jab_wrapper = jab_wrapper - - def run(self) -> None: - context_tree = ContextTree(self._jab_wrapper) - self._queue.put(context_tree) - - def get_context_tree(self) -> ContextTree: - return self._queue.get() diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py index 9a485c36b0..a81bce048d 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py @@ -11,9 +11,11 @@ def wrapper(self: "ElementInspector", *args, **kwargs): event_pump_thread = EventPumpThread() event_pump_thread.start() - jab_wrapper = event_pump_thread.get_wrapper() - ret = func(self, jab_wrapper, *args, **kwargs) - event_pump_thread.stop() + try: + jab_wrapper = event_pump_thread.get_wrapper() + ret = func(self, jab_wrapper, *args, **kwargs) + finally: + event_pump_thread.stop() return ret return wrapper @@ -27,17 +29,11 @@ def collect_tree( self, jab_wrapper: JavaAccessBridgeWrapper, window: str, + search_depth: int, locator: Optional[str] = None, ) -> Union[ContextNode, List[ContextNode]]: jab_wrapper.switch_window_by_title(window) - - from ._context_tree import ContextTreeThread - - context_tree_thread = ContextTreeThread(jab_wrapper) - context_tree_thread.start() - context_tree = context_tree_thread.get_context_tree() - context_tree_thread.join() - + context_tree = ContextTree(jab_wrapper, search_depth) if locator: from ._locators import find_elements_from_tree From 47c504a6d21773df3da0ac20434e24feac274206 Mon Sep 17 00:00:00 2001 From: Matti Mokko Date: Fri, 9 Feb 2024 15:11:39 +0200 Subject: [PATCH 05/11] Get tree with matches and hierarchy --- .../inspector/java/java_inspector.py | 35 ++++++++++++++----- .../java/robocorp_java/_inspector.py | 17 ++++++--- 2 files changed, 40 insertions(+), 12 deletions(-) diff --git a/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py b/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py index 42191fa15e..74d351eae7 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py +++ b/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py @@ -4,12 +4,13 @@ from JABWrapper.jab_wrapper import JavaWindow from robocorp_ls_core.robotframework_log import get_logger +from robocorp_code.inspector.java.robocorp_java._inspector import ColletedTreeTypedDict + log = get_logger(__name__) JavaWindowInfoTypedDict = TypedDict( "JavaWindowInfoTypedDict", { - # Same as JavaWindow "pid": int, "hwnd": int, "title": str, @@ -32,10 +33,14 @@ }, ) -LocatorTreeInfoTypedDict = TypedDict( - "LocatorTreeInfoTypedDict", - {"nodes": List[LocatorNodeInfoTypedDict]}, -) + +class MatchesAndHierarchyTypedDict(TypedDict): + # A list with the nodes matched (these are the ones that the + # locator matched) + matched_paths: List[str] + # This includes all the entries found along with the full hierarchy + # to reach the matched entries. + hierarchy: List[LocatorNodeInfoTypedDict] def to_window_info(java_window: JavaWindow) -> JavaWindowInfoTypedDict: @@ -52,6 +57,18 @@ def to_locator_info(context_node: ContextNode) -> LocatorNodeInfoTypedDict: return cast(LocatorNodeInfoTypedDict, ret) +def to_matches_and_hierarchy( + matches_and_hierarchy: ColletedTreeTypedDict, +) -> MatchesAndHierarchyTypedDict: + matches = ( + [str(matches_and_hierarchy["matches"])] + if type(matches_and_hierarchy["matches"]) == ContextNode + else [str(match) for match in matches_and_hierarchy["matches"]] + ) + hierarchy = [to_locator_info(node) for node in matches_and_hierarchy["tree"]] + return {"matches": matches, "hierarchy": hierarchy} + + class JavaInspector: def __init__(self): from robocorp_code.inspector.java.robocorp_java._inspector import ( @@ -66,8 +83,10 @@ def list_windows(self) -> List[JavaWindowInfoTypedDict]: def collect_tree( self, window: str, search_depth: int = 8, locator: Optional[str] = None - ) -> LocatorTreeInfoTypedDict: + ) -> MatchesAndHierarchyTypedDict: log.info(f"Collect tree from locator: {locator}") - tree = self._inspector.collect_tree(window, search_depth, locator) - return [to_locator_info(node) for node in tree] + matches_and_hierarchy = self._inspector.collect_tree( + window, search_depth, locator + ) + return to_matches_and_hierarchy(matches_and_hierarchy) diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py index a81bce048d..c290cad15b 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py @@ -1,8 +1,16 @@ -from typing import List, Optional, Union +from typing import List, Optional, TypedDict, Union from JABWrapper.context_tree import ContextNode, ContextTree from JABWrapper.jab_wrapper import JavaAccessBridgeWrapper, JavaWindow +ColletedTreeTypedDict = TypedDict( + "ColletedTreeTypedDict", + { + "matches": Union[ContextNode, List[ContextNode]], + "tree": ContextNode, + }, +) + class ElementInspector: def _start_event_pump(func, *args, **kwargs): @@ -31,11 +39,12 @@ def collect_tree( window: str, search_depth: int, locator: Optional[str] = None, - ) -> Union[ContextNode, List[ContextNode]]: + ) -> ColletedTreeTypedDict: jab_wrapper.switch_window_by_title(window) context_tree = ContextTree(jab_wrapper, search_depth) + matches: Union[ContextNode, List[ContextNode]] = [] if locator: from ._locators import find_elements_from_tree - return find_elements_from_tree(context_tree, locator) - return context_tree.root + matches = find_elements_from_tree(context_tree, locator) + return {"matches": matches, "tree": context_tree.root} From 18d68e22e3b1f0f2fad06750fa8165e7ac937cfe Mon Sep 17 00:00:00 2001 From: Matti Mokko Date: Tue, 13 Feb 2024 11:18:21 +0200 Subject: [PATCH 06/11] Collect tree to save the context --- .../inspector/java/java_inspector.py | 8 ++- .../inspector/java/robocorp_java/_errors.py | 2 + .../java/robocorp_java/_inspector.py | 54 ++++++++++++++++--- .../inspector/java/robocorp_java/_locators.py | 4 +- 4 files changed, 58 insertions(+), 10 deletions(-) create mode 100644 robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_errors.py diff --git a/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py b/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py index 74d351eae7..0a564fc8f5 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py +++ b/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py @@ -30,6 +30,7 @@ "y": int, "width": int, "height": int, + "ancestry": int, }, ) @@ -53,7 +54,10 @@ def to_window_info(java_window: JavaWindow) -> JavaWindowInfoTypedDict: def to_locator_info(context_node: ContextNode) -> LocatorNodeInfoTypedDict: ret = {} for dct_name in LocatorNodeInfoTypedDict.__annotations__: - ret[dct_name] = getattr(context_node.context_info, dct_name) + if (dct_name) == "ancestry": + ret["ancestry"] = getattr(context_node, dct_name) + else: + ret[dct_name] = getattr(context_node.context_info, dct_name) return cast(LocatorNodeInfoTypedDict, ret) @@ -82,7 +86,7 @@ def list_windows(self) -> List[JavaWindowInfoTypedDict]: return [to_window_info(window) for window in windows] def collect_tree( - self, window: str, search_depth: int = 8, locator: Optional[str] = None + self, window: str, search_depth=1, locator: Optional[str] = None ) -> MatchesAndHierarchyTypedDict: log.info(f"Collect tree from locator: {locator}") diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_errors.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_errors.py new file mode 100644 index 0000000000..1b446d7d90 --- /dev/null +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_errors.py @@ -0,0 +1,2 @@ +class NoMatchingLocatorException(Exception): + """Match for locator not found.""" diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py index c290cad15b..753fcc0bb3 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py @@ -13,6 +13,9 @@ class ElementInspector: + def __init__(self) -> None: + self._context: Optional[ContextNode] = None + def _start_event_pump(func, *args, **kwargs): def wrapper(self: "ElementInspector", *args, **kwargs): from ._event_pump import EventPumpThread @@ -32,6 +35,47 @@ def wrapper(self: "ElementInspector", *args, **kwargs): def list_windows(self, jab_wrapper: JavaAccessBridgeWrapper) -> List[JavaWindow]: return jab_wrapper.get_windows() + def _collect_from_root( + self, + jab_wrapper: JavaAccessBridgeWrapper, + locator: Optional[str], + search_depth=1, + ) -> ColletedTreeTypedDict: + self._context = ContextTree(jab_wrapper, search_depth).root + matches: Union[ContextNode, List[ContextNode]] = [] + if locator: + from ._locators import find_elements_from_tree + + matches = find_elements_from_tree(self._context, locator) + return {"matches": matches, "tree": self._context} + + def _collect_from_context( + self, jab_wrapper: JavaAccessBridgeWrapper, locator: str, search_depth=1 + ) -> ColletedTreeTypedDict: + from threading import RLock + + from ._errors import NoMatchingLocatorException + from ._locators import find_elements_from_tree + + # The JavaAccessBridgeWrapper object needs to be inserted into the context as the + # object has to be recreated every time we do a new query + # TODO: update the ContextTree to introduce the API for this + self._context._jab_wrapper = jab_wrapper + match = find_elements_from_tree(self._context, locator) + node = match[0] if isinstance(match, List) and len(match) > 0 else match + if not isinstance(node, ContextNode): + raise NoMatchingLocatorException(f"No matching locator for {locator}") + self._context = ContextNode( + jab_wrapper, + node.context, + RLock(), + node.ancestry, + True, + search_depth + node.ancestry, + ) + matches = find_elements_from_tree(self._context, locator) + return {"matches": matches, "tree": self._context} + @_start_event_pump def collect_tree( self, @@ -41,10 +85,8 @@ def collect_tree( locator: Optional[str] = None, ) -> ColletedTreeTypedDict: jab_wrapper.switch_window_by_title(window) - context_tree = ContextTree(jab_wrapper, search_depth) - matches: Union[ContextNode, List[ContextNode]] = [] - if locator: - from ._locators import find_elements_from_tree - matches = find_elements_from_tree(context_tree, locator) - return {"matches": matches, "tree": context_tree.root} + if not self._context: + return self._collect_from_root(jab_wrapper, locator, search_depth) + else: + return self._collect_from_context(jab_wrapper, locator, search_depth) diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py index 73e12b7785..fc2653e3f5 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py @@ -22,8 +22,8 @@ def _parse_locator(locator: str, strict_default=False): conditions = lvl.split(" and ") lvl_search = [] strict_mode = strict_default - for cond in conditions: - parts = cond.split(":", 1) + for condition in conditions: + parts = condition.split(":", 1) if len(parts) == 1: parts = ["name", parts[0]] elif parts[0].lower() == "strict": From 315bfc85ead26c97c8ef363bc3ffb0df0738a00e Mon Sep 17 00:00:00 2001 From: Matti Mokko Date: Tue, 13 Feb 2024 12:14:45 +0200 Subject: [PATCH 07/11] lint fixes --- .../inspector/java/java_inspector.py | 8 ++++---- .../inspector/java/robocorp_java/_errors.py | 4 ++++ .../inspector/java/robocorp_java/_event_pump.py | 17 ++++++++++------- .../inspector/java/robocorp_java/_inspector.py | 8 ++++++-- .../inspector/java/robocorp_java/_locators.py | 8 ++++++-- 5 files changed, 30 insertions(+), 15 deletions(-) diff --git a/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py b/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py index 0a564fc8f5..cdb2946694 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py +++ b/robocorp-code/src/robocorp_code/inspector/java/java_inspector.py @@ -1,7 +1,7 @@ from typing import List, Optional, TypedDict, cast -from JABWrapper.context_tree import ContextNode -from JABWrapper.jab_wrapper import JavaWindow +from JABWrapper.context_tree import ContextNode # type: ignore +from JABWrapper.jab_wrapper import JavaWindow # type: ignore from robocorp_ls_core.robotframework_log import get_logger from robocorp_code.inspector.java.robocorp_java._inspector import ColletedTreeTypedDict @@ -18,7 +18,7 @@ ) LocatorNodeInfoTypedDict = TypedDict( - "LocatorNoneInfoTypedDict", + "LocatorNodeInfoTypedDict", { "name": str, "role": str, @@ -70,7 +70,7 @@ def to_matches_and_hierarchy( else [str(match) for match in matches_and_hierarchy["matches"]] ) hierarchy = [to_locator_info(node) for node in matches_and_hierarchy["tree"]] - return {"matches": matches, "hierarchy": hierarchy} + return {"matched_paths": matches, "hierarchy": hierarchy} class JavaInspector: diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_errors.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_errors.py index 1b446d7d90..539691909c 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_errors.py +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_errors.py @@ -1,2 +1,6 @@ class NoMatchingLocatorException(Exception): """Match for locator not found.""" + + +class ContextNotAvailable(Exception): + """The Java context has not been created yet.""" diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py index 5a68ff0035..42ac16df28 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py @@ -1,16 +1,12 @@ import ctypes +import platform import queue import threading import time -from JABWrapper.jab_wrapper import JavaAccessBridgeWrapper +from JABWrapper.jab_wrapper import JavaAccessBridgeWrapper # type: ignore from robocorp_ls_core.robotframework_log import get_logger -PeekMessage = ctypes.windll.user32.PeekMessageW -GetMessage = ctypes.windll.user32.GetMessageW -TranslateMessage = ctypes.windll.user32.TranslateMessage -DispatchMessage = ctypes.windll.user32.DispatchMessageW - log = get_logger(__name__) @@ -24,11 +20,15 @@ def __init__( super().__init__() # Jab wrapper needs to be part of the thread that pumps the window events self._jab_wrapper: JavaAccessBridgeWrapper = None - self._queue = queue.Queue() + self._queue: queue.Queue = queue.Queue() self._quit_queue_loop = threading.Event() def _pump_background(self) -> bool: try: + PeekMessage = ctypes.windll.user32.PeekMessageW # type: ignore + TranslateMessage = ctypes.windll.user32.TranslateMessage # type: ignore + DispatchMessage = ctypes.windll.user32.DispatchMessageW # type: ignore + message = ctypes.byref(ctypes.wintypes.MSG()) # Nonblocking API to get windows window events from the queue. # https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-peekmessagea @@ -45,6 +45,9 @@ def _pump_background(self) -> bool: return False def run(self) -> None: + if platform.system() != "Windows": + return + self._jab_wrapper = JavaAccessBridgeWrapper(ignore_callbacks=True) self._queue.put(self._jab_wrapper) while not self._quit_queue_loop.is_set(): diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py index 753fcc0bb3..15bbe6b6b3 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py @@ -17,7 +17,7 @@ def __init__(self) -> None: self._context: Optional[ContextNode] = None def _start_event_pump(func, *args, **kwargs): - def wrapper(self: "ElementInspector", *args, **kwargs): + def wrapper(self, *args, **kwargs): from ._event_pump import EventPumpThread event_pump_thread = EventPumpThread() @@ -54,12 +54,16 @@ def _collect_from_context( ) -> ColletedTreeTypedDict: from threading import RLock - from ._errors import NoMatchingLocatorException + from ._errors import ContextNotAvailable, NoMatchingLocatorException from ._locators import find_elements_from_tree # The JavaAccessBridgeWrapper object needs to be inserted into the context as the # object has to be recreated every time we do a new query # TODO: update the ContextTree to introduce the API for this + if not self._context: + raise ContextNotAvailable( + "Cannot search from context as it hasn't been created yet" + ) self._context._jab_wrapper = jab_wrapper match = find_elements_from_tree(self._context, locator) node = match[0] if isinstance(match, List) and len(match) > 0 else match diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py index fc2653e3f5..7a882d38cb 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py @@ -1,6 +1,10 @@ from typing import List, Optional, Union -from JABWrapper.context_tree import ContextNode, ContextTree, SearchElement +from JABWrapper.context_tree import ( # type: ignore + ContextNode, + ContextTree, + SearchElement, +) IntegerLocatorTypes = [ "x", @@ -29,7 +33,7 @@ def _parse_locator(locator: str, strict_default=False): elif parts[0].lower() == "strict": strict_mode = bool(parts[1]) continue - elif parts[0] in IntegerLocatorTypes: + elif len(parts) > 1 and parts[0] in IntegerLocatorTypes: try: parts[1] = int(parts[1]) except ValueError as err: From 94c50e27598e87ad415cf325855d0ed6fda127a7 Mon Sep 17 00:00:00 2001 From: Matti Mokko Date: Tue, 13 Feb 2024 12:20:52 +0200 Subject: [PATCH 08/11] Get wrapper as future --- .../inspector/java/robocorp_java/_event_pump.py | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py index 42ac16df28..4cc7b496f2 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py @@ -1,8 +1,8 @@ import ctypes import platform -import queue import threading import time +from concurrent import futures from JABWrapper.jab_wrapper import JavaAccessBridgeWrapper # type: ignore from robocorp_ls_core.robotframework_log import get_logger @@ -20,7 +20,7 @@ def __init__( super().__init__() # Jab wrapper needs to be part of the thread that pumps the window events self._jab_wrapper: JavaAccessBridgeWrapper = None - self._queue: queue.Queue = queue.Queue() + self._future: futures.Future = futures.Future() self._quit_queue_loop = threading.Event() def _pump_background(self) -> bool: @@ -49,7 +49,7 @@ def run(self) -> None: return self._jab_wrapper = JavaAccessBridgeWrapper(ignore_callbacks=True) - self._queue.put(self._jab_wrapper) + self._future.set_result(self._jab_wrapper) while not self._quit_queue_loop.is_set(): # The pump is non blocking. If the is no message in the queue # wait for 10 milliseconds until check again to prevent too @@ -61,6 +61,8 @@ def run(self) -> None: def stop(self): self._quit_queue_loop.set() self._jab_wrapper = None + if not self._future.done(): + self._future.cancel() def get_wrapper(self) -> JavaAccessBridgeWrapper: - return self._queue.get() + return self._future.result() From 47cc45a5f57700c398a0fbf0eb1c91ea89814004 Mon Sep 17 00:00:00 2001 From: Matti Mokko Date: Tue, 13 Feb 2024 12:58:30 +0200 Subject: [PATCH 09/11] fix linting --- .../inspector/java/robocorp_java/_errors.py | 4 ++++ .../java/robocorp_java/_inspector.py | 23 ++++++++++++++----- .../inspector/java/robocorp_java/_locators.py | 6 ++--- 3 files changed, 24 insertions(+), 9 deletions(-) diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_errors.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_errors.py index 539691909c..3fa146ccf1 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_errors.py +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_errors.py @@ -4,3 +4,7 @@ class NoMatchingLocatorException(Exception): class ContextNotAvailable(Exception): """The Java context has not been created yet.""" + + +class LocatorNotProvidedException(Exception): + """Locator not provided.""" diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py index 15bbe6b6b3..a1fba971ab 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_inspector.py @@ -1,7 +1,8 @@ -from typing import List, Optional, TypedDict, Union +from functools import wraps +from typing import Any, Callable, List, Optional, TypedDict, TypeVar, Union, cast -from JABWrapper.context_tree import ContextNode, ContextTree -from JABWrapper.jab_wrapper import JavaAccessBridgeWrapper, JavaWindow +from JABWrapper.context_tree import ContextNode, ContextTree # type: ignore +from JABWrapper.jab_wrapper import JavaAccessBridgeWrapper, JavaWindow # type: ignore ColletedTreeTypedDict = TypedDict( "ColletedTreeTypedDict", @@ -11,13 +12,17 @@ }, ) +TFun = TypeVar("TFun", bound=Callable[..., Any]) + class ElementInspector: def __init__(self) -> None: self._context: Optional[ContextNode] = None - def _start_event_pump(func, *args, **kwargs): - def wrapper(self, *args, **kwargs): + @staticmethod + def _start_event_pump(func: TFun) -> TFun: + @wraps(func) + def wrapper(self: "ElementInspector", *args, **kwargs): from ._event_pump import EventPumpThread event_pump_thread = EventPumpThread() @@ -29,7 +34,7 @@ def wrapper(self, *args, **kwargs): event_pump_thread.stop() return ret - return wrapper + return cast(TFun, wrapper) @_start_event_pump def list_windows(self, jab_wrapper: JavaAccessBridgeWrapper) -> List[JavaWindow]: @@ -88,9 +93,15 @@ def collect_tree( search_depth: int, locator: Optional[str] = None, ) -> ColletedTreeTypedDict: + from ._errors import LocatorNotProvidedException + jab_wrapper.switch_window_by_title(window) if not self._context: return self._collect_from_root(jab_wrapper, locator, search_depth) else: + if not locator: + raise LocatorNotProvidedException( + "Locator needs to be provided to search the context" + ) return self._collect_from_context(jab_wrapper, locator, search_depth) diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py index 7a882d38cb..bb32c54e2f 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py @@ -1,4 +1,4 @@ -from typing import List, Optional, Union +from typing import List, Optional, Sequence, Union from JABWrapper.context_tree import ( # type: ignore ContextNode, @@ -27,13 +27,13 @@ def _parse_locator(locator: str, strict_default=False): lvl_search = [] strict_mode = strict_default for condition in conditions: - parts = condition.split(":", 1) + parts: Sequence[str | int] = condition.split(":", 1) if len(parts) == 1: parts = ["name", parts[0]] elif parts[0].lower() == "strict": strict_mode = bool(parts[1]) continue - elif len(parts) > 1 and parts[0] in IntegerLocatorTypes: + elif parts[0] in IntegerLocatorTypes: try: parts[1] = int(parts[1]) except ValueError as err: From 0a33c1c194cb850a0bb6584a86fca1e26263cb32 Mon Sep 17 00:00:00 2001 From: Matti Mokko Date: Wed, 14 Feb 2024 12:21:13 +0200 Subject: [PATCH 10/11] Add java-access-bridge to conda.yaml --- .../bin/create_env/conda_vscode_windows_amd64.yaml | 1 + .../inspector/java/robocorp_java/_event_pump.py | 7 ++++--- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/robocorp-code/bin/create_env/conda_vscode_windows_amd64.yaml b/robocorp-code/bin/create_env/conda_vscode_windows_amd64.yaml index f607f09062..1d8fa32c43 100644 --- a/robocorp-code/bin/create_env/conda_vscode_windows_amd64.yaml +++ b/robocorp-code/bin/create_env/conda_vscode_windows_amd64.yaml @@ -15,3 +15,4 @@ dependencies: - robocorp-inspector==0.10.2 # https://github.com/robocorp/inspector/blob/master/CHANGELOG.md - robotframework==5.0.1 # https://github.com/robotframework/robotframework/blob/master/doc/releasenotes/rf-5.0.1.rst - playwright==1.37.0 + - java-access-bridge-wrapper=="1.1.0" diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py index 4cc7b496f2..81b9457716 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_event_pump.py @@ -21,7 +21,7 @@ def __init__( # Jab wrapper needs to be part of the thread that pumps the window events self._jab_wrapper: JavaAccessBridgeWrapper = None self._future: futures.Future = futures.Future() - self._quit_queue_loop = threading.Event() + self._quit_event_loop = threading.Event() def _pump_background(self) -> bool: try: @@ -48,9 +48,10 @@ def run(self) -> None: if platform.system() != "Windows": return + # Raise the error to the main thread from here self._jab_wrapper = JavaAccessBridgeWrapper(ignore_callbacks=True) self._future.set_result(self._jab_wrapper) - while not self._quit_queue_loop.is_set(): + while not self._quit_event_loop.is_set(): # The pump is non blocking. If the is no message in the queue # wait for 10 milliseconds until check again to prevent too # fast loop. @@ -59,7 +60,7 @@ def run(self) -> None: time.sleep(0.01) def stop(self): - self._quit_queue_loop.set() + self._quit_event_loop.set() self._jab_wrapper = None if not self._future.done(): self._future.cancel() From c762b18d23226d88de5420a74a99a8c16920474d Mon Sep 17 00:00:00 2001 From: Matti Mokko Date: Wed, 14 Feb 2024 12:39:47 +0200 Subject: [PATCH 11/11] fix linting --- .../inspector/java/robocorp_java/_locators.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py index bb32c54e2f..e355c7548c 100644 --- a/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py +++ b/robocorp-code/src/robocorp_code/inspector/java/robocorp_java/_locators.py @@ -27,7 +27,9 @@ def _parse_locator(locator: str, strict_default=False): lvl_search = [] strict_mode = strict_default for condition in conditions: - parts: Sequence[str | int] = condition.split(":", 1) + parts: Sequence[str] = condition.split(":", 1) + name: str = parts[0] if len(parts) > 0 else "" + value: Union[str, int] = parts[1] if len(parts) > 1 else "" if len(parts) == 1: parts = ["name", parts[0]] elif parts[0].lower() == "strict": @@ -35,12 +37,12 @@ def _parse_locator(locator: str, strict_default=False): continue elif parts[0] in IntegerLocatorTypes: try: - parts[1] = int(parts[1]) + value = int(parts[1]) except ValueError as err: raise Exception( "Locator '%s' needs to be of 'integer' type" % parts[0] ) from err - lvl_search.append(SearchElement(parts[0], parts[1], strict=strict_mode)) + lvl_search.append(SearchElement(name, value, strict=strict_mode)) searches.append(lvl_search) return searches